opendevbrowser 0.0.33 → 0.0.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{accessibility-snapshot-JSPFVWZ6.js → accessibility-snapshot-VCBXK47S.js} +7 -7
- package/dist/{active-window-2OB2MSCR.js → active-window-7EUN36LZ.js} +7 -7
- package/dist/{annotate-VDZBZBKZ.js → annotate-VLBK7YB6.js} +6 -6
- package/dist/{attr-7XIO4MCH.js → attr-JNANQKM6.js} +6 -6
- package/dist/browser/browser-manager.d.ts.map +1 -1
- package/dist/browser/manager-types.d.ts +3 -0
- package/dist/browser/manager-types.d.ts.map +1 -1
- package/dist/browser/ops-browser-manager.d.ts.map +1 -1
- package/dist/browser/screencast-recorder.d.ts +1 -0
- package/dist/browser/screencast-recorder.d.ts.map +1 -1
- package/dist/{canvas-N4PAA274.js → canvas-V5LO4JVL.js} +6 -6
- package/dist/{capture-desktop-T5YO3EBI.js → capture-desktop-FKVDWTVG.js} +7 -7
- package/dist/{capture-window-UKEUBWKH.js → capture-window-QVPM2DN2.js} +7 -7
- package/dist/{check-PQB6KKMN.js → check-V3CWZ56S.js} +6 -6
- package/dist/{checked-RNZIMCU6.js → checked-Q27Q6YZN.js} +6 -6
- package/dist/{chunk-FBKPDILE.js → chunk-5FDXH4CS.js} +315 -37
- package/dist/chunk-5FDXH4CS.js.map +1 -0
- package/dist/{chunk-J3KYGJRQ.js → chunk-G6NQ7WYD.js} +2 -2
- package/dist/{chunk-27W46IKI.js → chunk-GC2FWISX.js} +22 -11
- package/dist/chunk-GC2FWISX.js.map +1 -0
- package/dist/{chunk-MJF67OTH.js → chunk-NX2XYJP5.js} +2 -2
- package/dist/{chunk-FDBUB7BM.js → chunk-OJAUKABV.js} +2 -2
- package/dist/{chunk-HMRANSDX.js → chunk-QXJDJDSZ.js} +34 -13
- package/dist/chunk-QXJDJDSZ.js.map +1 -0
- package/dist/{chunk-SKFB5ICF.js → chunk-TI5I6UWY.js} +8 -3
- package/dist/chunk-TI5I6UWY.js.map +1 -0
- package/dist/{chunk-W6YPVNDX.js → chunk-VTGG5ZU2.js} +2 -2
- package/dist/{chunk-YRRRUGSQ.js → chunk-VX47SJZM.js} +2 -2
- package/dist/{chunk-JROW6ZNN.js → chunk-VY47VKXU.js} +3 -3
- package/dist/{chunk-NURQB55J.js → chunk-WY72GYAH.js} +2 -2
- package/dist/{chunk-EOX6U6Q4.js → chunk-XRDCSHKZ.js} +158 -110
- package/dist/chunk-XRDCSHKZ.js.map +1 -0
- package/dist/{chunk-52ZIOWVU.js → chunk-Z3HIX2SE.js} +3 -3
- package/dist/cli/commands/inspiredesign.d.ts.map +1 -1
- package/dist/cli/daemon-commands.d.ts.map +1 -1
- package/dist/cli/index.js +75 -75
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/utils/parse.d.ts +1 -0
- package/dist/cli/utils/parse.d.ts.map +1 -1
- package/dist/{click-U7ZFKSB4.js → click-EQDRSLR3.js} +6 -6
- package/dist/{clone-component-SWYAORTU.js → clone-component-SISUXTJS.js} +5 -5
- package/dist/{clone-page-WJ6UJOJG.js → clone-page-MLDPCBOY.js} +5 -5
- package/dist/{close-VKIGIKVT.js → close-2LQMJVOA.js} +5 -5
- package/dist/{close-NAVIHZ2T.js → close-7J7EV237.js} +5 -5
- package/dist/{connect-XVG2MOZL.js → connect-JFRSIW5M.js} +6 -6
- package/dist/{console-poll-XI5BZPL7.js → console-poll-NSVVUNEC.js} +6 -6
- package/dist/{cookie-import-QELKE7TK.js → cookie-import-B7IQTGTN.js} +5 -5
- package/dist/{cookie-list-QDA6KWIY.js → cookie-list-YHG7JCZZ.js} +5 -5
- package/dist/{daemon-CA4UIIZQ.js → daemon-ENU4FOV4.js} +4 -4
- package/dist/daemon-fingerprint.json +1 -1
- package/dist/{debug-trace-snapshot-AT4GAO57.js → debug-trace-snapshot-KLGU2AWY.js} +6 -6
- package/dist/{dialog-O3V2IBFH.js → dialog-MUVQIERS.js} +6 -6
- package/dist/{disconnect-NAX5TPTG.js → disconnect-KELQJ45J.js} +5 -5
- package/dist/{enabled-VT4FJXDX.js → enabled-SF6UU5HG.js} +6 -6
- package/dist/{goto-GBJG5NC4.js → goto-AZQWXYPG.js} +6 -6
- package/dist/guidance/context.d.ts.map +1 -1
- package/dist/guidance/recipes/generic.d.ts.map +1 -1
- package/dist/guidance/recipes/pinterest.d.ts.map +1 -1
- package/dist/guidance/recipes/site-recipe-validation.d.ts +27 -0
- package/dist/guidance/recipes/site-recipe-validation.d.ts.map +1 -0
- package/dist/guidance/types.d.ts +1 -0
- package/dist/guidance/types.d.ts.map +1 -1
- package/dist/{help-SUI4H77K.js → help-B44IBHXL.js} +3 -3
- package/dist/{hover-476ZNQZE.js → hover-MQRAKKVU.js} +6 -6
- package/dist/{html-5C4TXOV3.js → html-PLRTU2WS.js} +6 -6
- package/dist/index.js +49 -14
- package/dist/index.js.map +1 -1
- package/dist/{inspector-73ARPCIV.js → inspector-IY4GBIT6.js} +7 -7
- package/dist/{inspector-audit-QT6QY7KS.js → inspector-audit-7MQCRJHD.js} +9 -9
- package/dist/{inspector-plan-JRNSGN2Z.js → inspector-plan-ZAUDHBET.js} +7 -7
- package/dist/inspiredesign/contract.d.ts +1 -0
- package/dist/inspiredesign/contract.d.ts.map +1 -1
- package/dist/inspiredesign/reference-pattern-board.d.ts +5 -0
- package/dist/inspiredesign/reference-pattern-board.d.ts.map +1 -1
- package/dist/{inspiredesign-IPVZDLSQ.js → inspiredesign-VHPEO3UK.js} +80 -27
- package/dist/inspiredesign-VHPEO3UK.js.map +1 -0
- package/dist/{launch-B35YDRQC.js → launch-OCTWPTV5.js} +6 -6
- package/dist/{list-YETWKTKY.js → list-HUSYADUS.js} +5 -5
- package/dist/{list-JV55JVGB.js → list-JWKAMAUA.js} +5 -5
- package/dist/{macro-resolve-DQK4B3W3.js → macro-resolve-WOXMPZDQ.js} +6 -6
- package/dist/{network-poll-4GWHCJXI.js → network-poll-WHB62OEF.js} +6 -6
- package/dist/{new-XDCQPIEG.js → new-IKZBYBNK.js} +5 -5
- package/dist/{open-GIM3ZCSV.js → open-UA2VI6ZP.js} +5 -5
- package/dist/opendevbrowser.js +49 -14
- package/dist/opendevbrowser.js.map +1 -1
- package/dist/{perf-26VBXDPI.js → perf-DICS3VKH.js} +6 -6
- package/dist/{pointer-down-O3VSNAXW.js → pointer-down-2XPRZFJC.js} +7 -7
- package/dist/{pointer-drag-WQ5QGE6J.js → pointer-drag-7NY4BOLH.js} +7 -7
- package/dist/{pointer-move-4N4D7JY2.js → pointer-move-FWEXMH37.js} +7 -7
- package/dist/{pointer-up-CQC4NPDX.js → pointer-up-VU2OHK5D.js} +7 -7
- package/dist/{press-XGJD45CU.js → press-W7IZ3FCX.js} +6 -6
- package/dist/{product-video-HD4ZOUI7.js → product-video-XCZ6CHR5.js} +7 -7
- package/dist/providers/browser-output-artifacts.d.ts +13 -0
- package/dist/providers/browser-output-artifacts.d.ts.map +1 -0
- package/dist/providers/renderer.d.ts.map +1 -1
- package/dist/providers/workflows.d.ts.map +1 -1
- package/dist/{providers-KKNPJSQK.js → providers-XCNSU3T6.js} +2 -2
- package/dist/public-surface/generated-manifest.d.ts +3 -3
- package/dist/public-surface/generated-manifest.d.ts.map +1 -1
- package/dist/public-surface/source.d.ts.map +1 -1
- package/dist/{research-VUWWEQ4R.js → research-AYCKHOWK.js} +7 -7
- package/dist/{review-LZ3TA7U7.js → review-PP2UNSMJ.js} +7 -7
- package/dist/{review-desktop-LAO7U7T3.js → review-desktop-3JOJFUEJ.js} +7 -7
- package/dist/{rpc-HKNIVFGC.js → rpc-7EPTJQQ6.js} +6 -6
- package/dist/{run-SHCF53FO.js → run-P6UJS3D4.js} +4 -4
- package/dist/{screencast-start-JHMQZVWJ.js → screencast-start-ZZYNH2HT.js} +6 -6
- package/dist/{screencast-stop-RWQTWWQS.js → screencast-stop-Y6ADFOFA.js} +6 -6
- package/dist/{screenshot-QHFYO6PB.js → screenshot-CJB7PMAF.js} +6 -6
- package/dist/{scroll-L3FTMAV4.js → scroll-BP5MA4ZT.js} +6 -6
- package/dist/{scroll-into-view-JVDHX4WU.js → scroll-into-view-O3RDWLM2.js} +6 -6
- package/dist/{select-X4BO7GTB.js → select-QLCNRI36.js} +6 -6
- package/dist/{serve-JIMIBCNO.js → serve-OO2MQWGL.js} +5 -5
- package/dist/{shopping-EGSDP2GL.js → shopping-UYHCYPAH.js} +7 -7
- package/dist/{snapshot-QGJ7RDNV.js → snapshot-SXYZ3CMC.js} +6 -6
- package/dist/{status-CKGPNYIH.js → status-AL2AHVA5.js} +5 -5
- package/dist/{status-LEBY2X7N.js → status-QQW7REK4.js} +7 -7
- package/dist/{status-capabilities-6QTWNGKM.js → status-capabilities-AVHJYQQQ.js} +7 -7
- package/dist/{text-VUZU7D3L.js → text-B6Z47EOA.js} +6 -6
- package/dist/tools/inspiredesign_run.d.ts.map +1 -1
- package/dist/tools/product_video_run.d.ts.map +1 -1
- package/dist/{type-N5SURP74.js → type-LR3F3SQY.js} +6 -6
- package/dist/{uncheck-JFMK3SSY.js → uncheck-5PJEHR7J.js} +6 -6
- package/dist/{upload-KFUYLL7M.js → upload-HQ3QN2OW.js} +6 -6
- package/dist/{use-CNMPP2ED.js → use-KFZLMRUH.js} +5 -5
- package/dist/{value-J335MPZE.js → value-TKUFUK5I.js} +6 -6
- package/dist/{visible-YQZWWPBZ.js → visible-P5Z2N2QR.js} +6 -6
- package/dist/{wait-IC7YJJPJ.js → wait-BYSHJPSC.js} +6 -6
- package/dist/{windows-AGVQ3KX3.js → windows-6GTD25EU.js} +7 -7
- package/extension/manifest.json +1 -1
- package/package.json +1 -1
- package/dist/chunk-27W46IKI.js.map +0 -1
- package/dist/chunk-EOX6U6Q4.js.map +0 -1
- package/dist/chunk-FBKPDILE.js.map +0 -1
- package/dist/chunk-HMRANSDX.js.map +0 -1
- package/dist/chunk-SKFB5ICF.js.map +0 -1
- package/dist/inspiredesign-IPVZDLSQ.js.map +0 -1
- /package/dist/{accessibility-snapshot-JSPFVWZ6.js.map → accessibility-snapshot-VCBXK47S.js.map} +0 -0
- /package/dist/{active-window-2OB2MSCR.js.map → active-window-7EUN36LZ.js.map} +0 -0
- /package/dist/{annotate-VDZBZBKZ.js.map → annotate-VLBK7YB6.js.map} +0 -0
- /package/dist/{attr-7XIO4MCH.js.map → attr-JNANQKM6.js.map} +0 -0
- /package/dist/{canvas-N4PAA274.js.map → canvas-V5LO4JVL.js.map} +0 -0
- /package/dist/{capture-desktop-T5YO3EBI.js.map → capture-desktop-FKVDWTVG.js.map} +0 -0
- /package/dist/{capture-window-UKEUBWKH.js.map → capture-window-QVPM2DN2.js.map} +0 -0
- /package/dist/{check-PQB6KKMN.js.map → check-V3CWZ56S.js.map} +0 -0
- /package/dist/{checked-RNZIMCU6.js.map → checked-Q27Q6YZN.js.map} +0 -0
- /package/dist/{chunk-J3KYGJRQ.js.map → chunk-G6NQ7WYD.js.map} +0 -0
- /package/dist/{chunk-MJF67OTH.js.map → chunk-NX2XYJP5.js.map} +0 -0
- /package/dist/{chunk-FDBUB7BM.js.map → chunk-OJAUKABV.js.map} +0 -0
- /package/dist/{chunk-W6YPVNDX.js.map → chunk-VTGG5ZU2.js.map} +0 -0
- /package/dist/{chunk-YRRRUGSQ.js.map → chunk-VX47SJZM.js.map} +0 -0
- /package/dist/{chunk-JROW6ZNN.js.map → chunk-VY47VKXU.js.map} +0 -0
- /package/dist/{chunk-NURQB55J.js.map → chunk-WY72GYAH.js.map} +0 -0
- /package/dist/{chunk-52ZIOWVU.js.map → chunk-Z3HIX2SE.js.map} +0 -0
- /package/dist/{click-U7ZFKSB4.js.map → click-EQDRSLR3.js.map} +0 -0
- /package/dist/{clone-component-SWYAORTU.js.map → clone-component-SISUXTJS.js.map} +0 -0
- /package/dist/{clone-page-WJ6UJOJG.js.map → clone-page-MLDPCBOY.js.map} +0 -0
- /package/dist/{close-VKIGIKVT.js.map → close-2LQMJVOA.js.map} +0 -0
- /package/dist/{close-NAVIHZ2T.js.map → close-7J7EV237.js.map} +0 -0
- /package/dist/{connect-XVG2MOZL.js.map → connect-JFRSIW5M.js.map} +0 -0
- /package/dist/{console-poll-XI5BZPL7.js.map → console-poll-NSVVUNEC.js.map} +0 -0
- /package/dist/{cookie-import-QELKE7TK.js.map → cookie-import-B7IQTGTN.js.map} +0 -0
- /package/dist/{cookie-list-QDA6KWIY.js.map → cookie-list-YHG7JCZZ.js.map} +0 -0
- /package/dist/{daemon-CA4UIIZQ.js.map → daemon-ENU4FOV4.js.map} +0 -0
- /package/dist/{debug-trace-snapshot-AT4GAO57.js.map → debug-trace-snapshot-KLGU2AWY.js.map} +0 -0
- /package/dist/{dialog-O3V2IBFH.js.map → dialog-MUVQIERS.js.map} +0 -0
- /package/dist/{disconnect-NAX5TPTG.js.map → disconnect-KELQJ45J.js.map} +0 -0
- /package/dist/{enabled-VT4FJXDX.js.map → enabled-SF6UU5HG.js.map} +0 -0
- /package/dist/{goto-GBJG5NC4.js.map → goto-AZQWXYPG.js.map} +0 -0
- /package/dist/{help-SUI4H77K.js.map → help-B44IBHXL.js.map} +0 -0
- /package/dist/{hover-476ZNQZE.js.map → hover-MQRAKKVU.js.map} +0 -0
- /package/dist/{html-5C4TXOV3.js.map → html-PLRTU2WS.js.map} +0 -0
- /package/dist/{inspector-73ARPCIV.js.map → inspector-IY4GBIT6.js.map} +0 -0
- /package/dist/{inspector-audit-QT6QY7KS.js.map → inspector-audit-7MQCRJHD.js.map} +0 -0
- /package/dist/{inspector-plan-JRNSGN2Z.js.map → inspector-plan-ZAUDHBET.js.map} +0 -0
- /package/dist/{launch-B35YDRQC.js.map → launch-OCTWPTV5.js.map} +0 -0
- /package/dist/{list-YETWKTKY.js.map → list-HUSYADUS.js.map} +0 -0
- /package/dist/{list-JV55JVGB.js.map → list-JWKAMAUA.js.map} +0 -0
- /package/dist/{macro-resolve-DQK4B3W3.js.map → macro-resolve-WOXMPZDQ.js.map} +0 -0
- /package/dist/{network-poll-4GWHCJXI.js.map → network-poll-WHB62OEF.js.map} +0 -0
- /package/dist/{new-XDCQPIEG.js.map → new-IKZBYBNK.js.map} +0 -0
- /package/dist/{open-GIM3ZCSV.js.map → open-UA2VI6ZP.js.map} +0 -0
- /package/dist/{perf-26VBXDPI.js.map → perf-DICS3VKH.js.map} +0 -0
- /package/dist/{pointer-down-O3VSNAXW.js.map → pointer-down-2XPRZFJC.js.map} +0 -0
- /package/dist/{pointer-drag-WQ5QGE6J.js.map → pointer-drag-7NY4BOLH.js.map} +0 -0
- /package/dist/{pointer-move-4N4D7JY2.js.map → pointer-move-FWEXMH37.js.map} +0 -0
- /package/dist/{pointer-up-CQC4NPDX.js.map → pointer-up-VU2OHK5D.js.map} +0 -0
- /package/dist/{press-XGJD45CU.js.map → press-W7IZ3FCX.js.map} +0 -0
- /package/dist/{product-video-HD4ZOUI7.js.map → product-video-XCZ6CHR5.js.map} +0 -0
- /package/dist/{providers-KKNPJSQK.js.map → providers-XCNSU3T6.js.map} +0 -0
- /package/dist/{research-VUWWEQ4R.js.map → research-AYCKHOWK.js.map} +0 -0
- /package/dist/{review-LZ3TA7U7.js.map → review-PP2UNSMJ.js.map} +0 -0
- /package/dist/{review-desktop-LAO7U7T3.js.map → review-desktop-3JOJFUEJ.js.map} +0 -0
- /package/dist/{rpc-HKNIVFGC.js.map → rpc-7EPTJQQ6.js.map} +0 -0
- /package/dist/{run-SHCF53FO.js.map → run-P6UJS3D4.js.map} +0 -0
- /package/dist/{screencast-start-JHMQZVWJ.js.map → screencast-start-ZZYNH2HT.js.map} +0 -0
- /package/dist/{screencast-stop-RWQTWWQS.js.map → screencast-stop-Y6ADFOFA.js.map} +0 -0
- /package/dist/{screenshot-QHFYO6PB.js.map → screenshot-CJB7PMAF.js.map} +0 -0
- /package/dist/{scroll-L3FTMAV4.js.map → scroll-BP5MA4ZT.js.map} +0 -0
- /package/dist/{scroll-into-view-JVDHX4WU.js.map → scroll-into-view-O3RDWLM2.js.map} +0 -0
- /package/dist/{select-X4BO7GTB.js.map → select-QLCNRI36.js.map} +0 -0
- /package/dist/{serve-JIMIBCNO.js.map → serve-OO2MQWGL.js.map} +0 -0
- /package/dist/{shopping-EGSDP2GL.js.map → shopping-UYHCYPAH.js.map} +0 -0
- /package/dist/{snapshot-QGJ7RDNV.js.map → snapshot-SXYZ3CMC.js.map} +0 -0
- /package/dist/{status-CKGPNYIH.js.map → status-AL2AHVA5.js.map} +0 -0
- /package/dist/{status-LEBY2X7N.js.map → status-QQW7REK4.js.map} +0 -0
- /package/dist/{status-capabilities-6QTWNGKM.js.map → status-capabilities-AVHJYQQQ.js.map} +0 -0
- /package/dist/{text-VUZU7D3L.js.map → text-B6Z47EOA.js.map} +0 -0
- /package/dist/{type-N5SURP74.js.map → type-LR3F3SQY.js.map} +0 -0
- /package/dist/{uncheck-JFMK3SSY.js.map → uncheck-5PJEHR7J.js.map} +0 -0
- /package/dist/{upload-KFUYLL7M.js.map → upload-HQ3QN2OW.js.map} +0 -0
- /package/dist/{use-CNMPP2ED.js.map → use-KFZLMRUH.js.map} +0 -0
- /package/dist/{value-J335MPZE.js.map → value-TKUFUK5I.js.map} +0 -0
- /package/dist/{visible-YQZWWPBZ.js.map → visible-P5Z2N2QR.js.map} +0 -0
- /package/dist/{wait-IC7YJJPJ.js.map → wait-BYSHJPSC.js.map} +0 -0
- /package/dist/{windows-AGVQ3KX3.js.map → windows-6GTD25EU.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/providers/normalize.ts","../src/providers/policy.ts","../src/providers/registry.ts","../src/providers/adaptive-concurrency.ts","../src/providers/tier-router.ts","../src/challenges/types.ts","../src/challenges/evidence-bundle.ts","../src/challenges/interpreter.ts","../src/challenges/verification-gate.ts","../src/challenges/capability-matrix.ts","../src/challenges/capture.ts","../src/challenges/human-yield-gate.ts","../src/challenges/optional-computer-use-bridge.ts","../src/challenges/policy-gate.ts","../src/challenges/strategy-selector.ts","../src/challenges/inspect-plan.ts","../src/challenges/action-loop.ts","../src/challenges/owned-environment-lane.ts","../src/challenges/sanctioned-identity-lane.ts","../src/challenges/service-adapter-lane.ts","../src/challenges/governed-adapter-gateway.ts","../src/challenges/outcome-recorder.ts","../src/challenges/orchestrator.ts","../src/providers/runtime-policy.ts","../src/providers/browser-fallback.ts","../src/providers/shared/anti-bot-policy.ts","../src/providers/shared/post-policy.ts","../src/providers/shared/traversal-url.ts","../src/providers/web/policy.ts","../src/providers/web/crawl-worker.ts","../src/providers/web/extract.ts","../src/providers/web/crawler.ts","../src/providers/community/index.ts","../src/providers/social/search-quality.ts","../src/providers/social/platform.ts","../src/providers/social/bluesky.ts","../src/providers/social/facebook.ts","../src/providers/social/instagram.ts","../src/providers/social/linkedin.ts","../src/providers/social/reddit.ts","../src/providers/social/threads.ts","../src/providers/social/tiktok.ts","../src/providers/social/x.ts","../src/providers/shared/request-headers.ts","../src/providers/social/youtube-resolver.ts","../src/providers/social/youtube.ts","../src/providers/social/index.ts","../src/providers/shopping/index.ts","../src/providers/web/index.ts","../src/providers/bounded-map.ts","../src/providers/workflow-contracts.ts","../src/providers/workflows.ts","../src/providers/workflow-output-root.ts","../src/providers/timebox.ts","../src/providers/enrichment.ts","../src/inspiredesign/contract.ts","../skills/opendevbrowser-design-agent/assets/templates/canvas-generation-plan.design.v1.json","../skills/opendevbrowser-design-agent/assets/templates/design-contract.v1.json","../skills/opendevbrowser-design-agent/assets/templates/inspiredesign-advanced-brief.v1.json","../src/inspiredesign/brief-expansion.ts","../src/guidance/recipes/pinterest.ts","../src/inspiredesign/reference-pattern-board.ts","../src/inspiredesign/meta-prompt.ts","../src/inspiredesign/visual-evidence.ts","../src/guidance/renderers.ts","../src/guidance/readiness.ts","../src/canvas/repair-examples.ts","../src/guidance/recipes/generic.ts","../src/guidance/router.ts","../src/providers/workflow-handoff.ts","../src/providers/renderer.ts","../src/guidance/recipes/site-registry.ts","../src/guidance/context.ts","../src/guidance/recipes/site-recipe-validation.ts","../src/inspiredesign/reference-discovery.ts","../src/inspiredesign/visual-policy.ts","../src/canvas/types.ts","../src/providers/shopping-postprocess.ts","../src/providers/shopping-workflow.ts","../src/providers/shopping-compiler.ts","../src/providers/shopping-executor.ts","../src/providers/product-video-compiler.ts","../src/providers/research-compiler.ts","../src/providers/research-executor.ts","../src/inspiredesign/capture-mode.ts","../src/providers/browser-native-discovery.ts","../src/providers/index.ts"],"sourcesContent":["import { createHash, randomUUID } from \"crypto\";\nimport { createProviderError, toProviderError } from \"./errors\";\nimport type {\n JsonValue,\n NormalizedRecord,\n ProviderExecutionMetadata,\n ProviderError,\n ProviderOperationFailure,\n ProviderOperationSuccess,\n ProviderSource,\n ProviderTierMetadata,\n TraceContext\n} from \"./types\";\n\nexport interface NormalizeRecordInput {\n id?: string;\n url?: string;\n title?: string;\n content?: string;\n timestamp?: string;\n confidence?: number;\n attributes?: Record<string, JsonValue>;\n}\n\nexport const createTraceContext = (\n seed: Partial<TraceContext> = {},\n provider?: string\n): TraceContext => {\n return {\n requestId: seed.requestId ?? randomUUID(),\n ...(seed.sessionId ? { sessionId: seed.sessionId } : {}),\n ...(seed.targetId ? { targetId: seed.targetId } : {}),\n ...(provider ?? seed.provider ? { provider: provider ?? seed.provider } : {}),\n ts: seed.ts ?? new Date().toISOString()\n };\n};\n\nexport const clampConfidence = (value: number | undefined): number => {\n if (typeof value !== \"number\" || Number.isNaN(value)) return 0.5;\n if (value < 0) return 0;\n if (value > 1) return 1;\n return value;\n};\n\nexport const createStableRecordId = (\n provider: string,\n source: ProviderSource,\n value: NormalizeRecordInput\n): string => {\n const payload = stableStringify({\n provider,\n source,\n url: value.url ?? \"\",\n title: value.title ?? \"\",\n content: value.content ?? \"\",\n attributes: value.attributes ?? {}\n });\n\n return createHash(\"sha1\").update(payload).digest(\"hex\").slice(0, 16);\n};\n\nexport const normalizeRecord = (\n provider: string,\n source: ProviderSource,\n value: NormalizeRecordInput\n): NormalizedRecord => {\n const id = value.id ?? createStableRecordId(provider, source, value);\n const timestamp = value.timestamp ?? new Date().toISOString();\n\n return {\n id,\n source,\n provider,\n ...(value.url ? { url: value.url } : {}),\n ...(value.title ? { title: value.title } : {}),\n ...(value.content ? { content: value.content } : {}),\n timestamp,\n confidence: clampConfidence(value.confidence),\n attributes: value.attributes ?? {}\n };\n};\n\nexport const normalizeRecords = (\n provider: string,\n source: ProviderSource,\n records: NormalizeRecordInput[]\n): NormalizedRecord[] => {\n return records.map((record) => normalizeRecord(provider, source, record));\n};\n\nexport const normalizeSuccess = (\n provider: string,\n source: ProviderSource,\n records: NormalizeRecordInput[],\n options: {\n trace?: Partial<TraceContext>;\n startedAtMs?: number;\n attempts?: number;\n retries?: number;\n meta?: ProviderExecutionMetadata;\n provenance?: Record<string, JsonValue>;\n } = {}\n): ProviderOperationSuccess => {\n const trace = createTraceContext(options.trace, provider);\n const startedAtMs = options.startedAtMs ?? Date.now();\n\n return {\n ok: true,\n provider,\n source,\n trace,\n records: normalizeRecords(provider, source, records),\n latencyMs: Math.max(0, Date.now() - startedAtMs),\n attempts: options.attempts ?? 1,\n retries: options.retries ?? Math.max(0, (options.attempts ?? 1) - 1),\n ...(options.meta ? { meta: options.meta } : {}),\n ...(options.provenance ? { provenance: options.provenance } : {})\n };\n};\n\nexport const normalizeFailure = (\n provider: string,\n source: ProviderSource,\n error: unknown,\n options: {\n trace?: Partial<TraceContext>;\n startedAtMs?: number;\n attempts?: number;\n retries?: number;\n meta?: ProviderExecutionMetadata;\n defaultMessage?: string;\n defaultErrorCode?: ProviderError[\"code\"];\n } = {}\n): ProviderOperationFailure => {\n const trace = createTraceContext(options.trace, provider);\n const startedAtMs = options.startedAtMs ?? Date.now();\n const mapped = isProviderError(error)\n ? error\n : toProviderError(error, {\n provider,\n source,\n defaultCode: options.defaultErrorCode\n });\n const resolvedError = mapped.message\n ? mapped\n : createProviderError(mapped.code, options.defaultMessage ?? \"Provider request failed\", {\n retryable: mapped.retryable,\n provider,\n source\n });\n\n return {\n ok: false,\n provider,\n source,\n trace,\n error: resolvedError,\n latencyMs: Math.max(0, Date.now() - startedAtMs),\n attempts: options.attempts ?? 1,\n retries: options.retries ?? Math.max(0, (options.attempts ?? 1) - 1),\n ...(options.meta ? { meta: options.meta } : {})\n };\n};\n\nexport const createExecutionMetadata = (params: {\n tier: ProviderTierMetadata;\n provider: string;\n retrievalPath: string;\n retrievedAt?: string;\n}): ProviderExecutionMetadata => {\n return {\n tier: params.tier,\n provenance: {\n provider: params.provider,\n retrievalPath: params.retrievalPath,\n retrievedAt: params.retrievedAt ?? new Date().toISOString()\n }\n };\n};\n\nconst isProviderError = (value: unknown): value is ProviderError => {\n if (!value || typeof value !== \"object\") return false;\n const candidate = value as Record<string, unknown>;\n return typeof candidate.code === \"string\"\n && typeof candidate.message === \"string\"\n && typeof candidate.retryable === \"boolean\";\n};\n\nconst stableStringify = (value: JsonValue | Record<string, unknown>): string => {\n if (value === null) return \"null\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\n\n const entries = Object.entries(value)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entryValue]) => `${JSON.stringify(key)}:${stableStringify(entryValue as JsonValue | Record<string, unknown>)}`);\n return `{${entries.join(\",\")}}`;\n};\n","import type { ProviderAdapter, ProviderOperation, ProviderSelection } from \"./types\";\nimport type { ProviderRegistry } from \"./registry\";\n\nconst SOURCE_ORDER = [\"web\", \"community\", \"social\", \"shopping\"] as const;\n\ntype HealthStatus = ReturnType<ProviderRegistry[\"getHealth\"]>[\"status\"];\n\nconst hasOperation = (provider: ProviderAdapter, operation: ProviderOperation): boolean => {\n switch (operation) {\n case \"search\":\n return typeof provider.search === \"function\";\n case \"fetch\":\n return typeof provider.fetch === \"function\";\n case \"crawl\":\n return typeof provider.crawl === \"function\";\n case \"post\":\n return typeof provider.post === \"function\";\n }\n};\n\nconst rankHealth = (status: HealthStatus): number => {\n if (status === \"healthy\") return 0;\n if (status === \"degraded\") return 1;\n return 2;\n};\n\nconst rankPressure = (registry: ProviderRegistry, providerId: string): number => {\n return registry.getAntiBotPressure(providerId);\n};\n\nexport const selectProviders = (\n registry: ProviderRegistry,\n operation: ProviderOperation,\n selection: ProviderSelection = \"auto\"\n): ProviderAdapter[] => {\n const providers = registry.list().filter((provider) => hasOperation(provider, operation));\n\n const bySelection = providers.filter((provider) => {\n if (selection === \"all\") return true;\n if (selection === \"auto\") return provider.source !== \"shopping\";\n return provider.source === selection;\n });\n\n return bySelection.sort((left, right) => {\n const pressureDelta = rankPressure(registry, left.id) - rankPressure(registry, right.id);\n if (pressureDelta !== 0) return pressureDelta;\n\n const healthDelta = rankHealth(registry.getHealth(left.id).status) - rankHealth(registry.getHealth(right.id).status);\n if (healthDelta !== 0) return healthDelta;\n\n const leftSourceRank = SOURCE_ORDER.indexOf(left.source);\n const rightSourceRank = SOURCE_ORDER.indexOf(right.source);\n const sourceDelta = leftSourceRank - rightSourceRank;\n if (sourceDelta !== 0) return sourceDelta;\n\n return left.id.localeCompare(right.id);\n });\n};\n\nexport const shouldFallbackToNextProvider = (selection: ProviderSelection): boolean => {\n return selection === \"all\" || selection === \"auto\";\n};\n","import { createProviderError } from \"./errors\";\nimport type {\n BrowserFallbackDisposition,\n ProviderAdapter,\n ProviderCapabilities,\n ProviderError,\n ProviderHealth,\n ProviderOperation,\n ProviderReasonCode,\n ProviderSource\n} from \"./types\";\n\ntype ProviderCooldownState = {\n reasonCode: ProviderReasonCode;\n cooldownUntilMs: number;\n updatedAt: string;\n};\n\ntype ProviderAntiBotEventKind = \"challenge\" | \"rate_limited\" | \"success\" | \"other\";\n\ntype ProviderPreservedOutcome = {\n disposition: BrowserFallbackDisposition;\n reasonCode?: ProviderReasonCode;\n at: string;\n};\n\ntype ProviderAntiBotState = {\n activeChallenges: number;\n lastChallengeAt?: string;\n lastResolvedAt?: string;\n cooldownByOperation: Partial<Record<ProviderOperation, ProviderCooldownState>>;\n recentEvents: ProviderAntiBotEventKind[];\n lastPreservedOutcome?: ProviderPreservedOutcome;\n};\n\nexport interface ProviderAntiBotSnapshot {\n providerId: string;\n activeChallenges: number;\n lastChallengeAt?: string;\n lastResolvedAt?: string;\n recentChallengeRatio: number;\n recentRateLimitRatio: number;\n cooldownUntilMs: number;\n lastPreservedOutcome?: ProviderPreservedOutcome;\n}\n\ninterface ProviderState {\n health: ProviderHealth;\n failures: number;\n circuitOpenUntil: number;\n lastError?: ProviderError;\n antiBot: ProviderAntiBotState;\n}\n\nconst ANTI_BOT_WINDOW = 20;\n\nconst CHALLENGE_REASONS = new Set<ProviderReasonCode>([\n \"challenge_detected\",\n \"auth_required\",\n \"token_required\",\n \"ip_blocked\"\n]);\n\nconst RATE_LIMIT_REASONS = new Set<ProviderReasonCode>([\n \"rate_limited\"\n]);\n\nconst defaultAntiBotState = (): ProviderAntiBotState => ({\n activeChallenges: 0,\n cooldownByOperation: {},\n recentEvents: []\n});\n\nconst defaultHealth = (): ProviderHealth => ({\n status: \"healthy\",\n updatedAt: new Date().toISOString()\n});\n\nexport class ProviderRegistry {\n private readonly providers = new Map<string, ProviderAdapter>();\n private readonly state = new Map<string, ProviderState>();\n\n register(provider: ProviderAdapter): void {\n if (this.providers.has(provider.id)) {\n throw new Error(`Provider already registered: ${provider.id}`);\n }\n\n this.providers.set(provider.id, provider);\n this.state.set(provider.id, {\n health: defaultHealth(),\n failures: 0,\n circuitOpenUntil: 0,\n antiBot: defaultAntiBotState()\n });\n }\n\n get(providerId: string): ProviderAdapter {\n const provider = this.providers.get(providerId);\n if (!provider) {\n throw new Error(`Unknown provider: ${providerId}`);\n }\n return provider;\n }\n\n list(): ProviderAdapter[] {\n return [...this.providers.values()];\n }\n\n listBySource(source: ProviderSource): ProviderAdapter[] {\n return this.list().filter((provider) => provider.source === source);\n }\n\n capabilities(): ProviderCapabilities[] {\n return this.list().map((provider) => provider.capabilities());\n }\n\n setHealth(providerId: string, health: ProviderHealth): void {\n const existing = this.getState(providerId);\n existing.health = {\n ...health,\n updatedAt: health.updatedAt || new Date().toISOString()\n };\n }\n\n getHealth(providerId: string): ProviderHealth {\n return this.getState(providerId).health;\n }\n\n markSuccess(providerId: string, latencyMs: number): void {\n const existing = this.getState(providerId);\n existing.failures = 0;\n existing.circuitOpenUntil = 0;\n existing.lastError = undefined;\n existing.health = {\n status: \"healthy\",\n updatedAt: new Date().toISOString(),\n latencyMs\n };\n }\n\n markFailure(\n providerId: string,\n error: ProviderError,\n circuit: { failureThreshold: number; cooldownMs: number }\n ): void {\n const existing = this.getState(providerId);\n existing.failures += 1;\n existing.lastError = error;\n\n const now = Date.now();\n const threshold = Math.max(1, circuit.failureThreshold);\n if (existing.failures >= threshold) {\n existing.circuitOpenUntil = now + Math.max(0, circuit.cooldownMs);\n existing.health = {\n status: \"unhealthy\",\n updatedAt: new Date(now).toISOString(),\n reason: error.message\n };\n return;\n }\n\n existing.health = {\n status: \"degraded\",\n updatedAt: new Date(now).toISOString(),\n reason: error.message\n };\n }\n\n isCircuitOpen(providerId: string, nowMs = Date.now()): boolean {\n const existing = this.getState(providerId);\n if (existing.circuitOpenUntil <= 0) return false;\n if (existing.circuitOpenUntil > nowMs) return true;\n\n existing.circuitOpenUntil = 0;\n if (existing.health.status === \"unhealthy\") {\n existing.health = {\n status: \"degraded\",\n updatedAt: new Date(nowMs).toISOString(),\n reason: \"Circuit cooldown elapsed\"\n };\n }\n return false;\n }\n\n getCircuitError(providerId: string): ProviderError {\n const existing = this.getState(providerId);\n return createProviderError(\"circuit_open\", \"Provider circuit is open\", {\n provider: providerId,\n retryable: true,\n details: {\n openUntil: existing.circuitOpenUntil,\n failures: existing.failures,\n lastErrorCode: existing.lastError?.code ?? null\n }\n });\n }\n\n reset(providerId: string): void {\n const existing = this.getState(providerId);\n existing.failures = 0;\n existing.circuitOpenUntil = 0;\n existing.lastError = undefined;\n existing.health = defaultHealth();\n existing.antiBot = defaultAntiBotState();\n }\n\n setAntiBotCooldown(\n providerId: string,\n operation: ProviderOperation,\n reasonCode: ProviderReasonCode,\n cooldownUntilMs: number,\n nowMs = Date.now()\n ): void {\n const antiBot = this.getState(providerId).antiBot;\n antiBot.cooldownByOperation[operation] = {\n reasonCode,\n cooldownUntilMs,\n updatedAt: new Date(nowMs).toISOString()\n };\n }\n\n clearAntiBotCooldown(\n providerId: string,\n operation: ProviderOperation\n ): void {\n delete this.getState(providerId).antiBot.cooldownByOperation[operation];\n }\n\n getAntiBotCooldown(\n providerId: string,\n operation: ProviderOperation,\n nowMs = Date.now()\n ): ProviderCooldownState | undefined {\n const antiBot = this.getState(providerId).antiBot;\n const cooldown = antiBot.cooldownByOperation[operation];\n if (!cooldown) {\n return undefined;\n }\n if (cooldown.cooldownUntilMs <= nowMs) {\n delete antiBot.cooldownByOperation[operation];\n return undefined;\n }\n return cooldown;\n }\n\n recordAntiBotOutcome(args: {\n providerId: string;\n success?: boolean;\n reasonCode?: ProviderReasonCode;\n disposition?: BrowserFallbackDisposition;\n nowMs?: number;\n }): void {\n const antiBot = this.getState(args.providerId).antiBot;\n const nowMs = args.nowMs ?? Date.now();\n const nowIso = new Date(nowMs).toISOString();\n\n if (args.success) {\n this.pushAntiBotEvent(antiBot, \"success\");\n if (antiBot.activeChallenges > 0) {\n antiBot.activeChallenges = 0;\n antiBot.lastResolvedAt = nowIso;\n }\n return;\n }\n\n const eventKind = this.classifyAntiBotEventKind(args.reasonCode);\n this.pushAntiBotEvent(antiBot, eventKind);\n\n if (args.disposition) {\n antiBot.lastPreservedOutcome = {\n disposition: args.disposition,\n ...(args.reasonCode ? { reasonCode: args.reasonCode } : {}),\n at: nowIso\n };\n }\n\n if (args.disposition === \"challenge_preserved\") {\n antiBot.activeChallenges = Math.max(1, antiBot.activeChallenges);\n antiBot.lastChallengeAt = nowIso;\n return;\n }\n\n if (eventKind === \"challenge\") {\n antiBot.lastChallengeAt = nowIso;\n }\n }\n\n getAntiBotSnapshot(\n providerId: string,\n nowMs = Date.now()\n ): ProviderAntiBotSnapshot {\n const antiBot = this.getState(providerId).antiBot;\n const activeCooldowns = Object.values(antiBot.cooldownByOperation)\n .filter((cooldown): cooldown is ProviderCooldownState => Boolean(cooldown))\n .filter((cooldown) => cooldown.cooldownUntilMs > nowMs);\n const eventCount = antiBot.recentEvents.length;\n const challengeCount = antiBot.recentEvents.filter((entry) => entry === \"challenge\").length;\n const rateLimitCount = antiBot.recentEvents.filter((entry) => entry === \"rate_limited\").length;\n\n return {\n providerId,\n activeChallenges: antiBot.activeChallenges,\n ...(antiBot.lastChallengeAt ? { lastChallengeAt: antiBot.lastChallengeAt } : {}),\n ...(antiBot.lastResolvedAt ? { lastResolvedAt: antiBot.lastResolvedAt } : {}),\n recentChallengeRatio: eventCount > 0 ? challengeCount / eventCount : 0,\n recentRateLimitRatio: eventCount > 0 ? rateLimitCount / eventCount : 0,\n cooldownUntilMs: activeCooldowns.reduce((max, cooldown) => Math.max(max, cooldown.cooldownUntilMs), 0),\n ...(antiBot.lastPreservedOutcome ? { lastPreservedOutcome: antiBot.lastPreservedOutcome } : {})\n };\n }\n\n listAntiBotSnapshots(nowMs = Date.now()): ProviderAntiBotSnapshot[] {\n return this.list().map((provider) => this.getAntiBotSnapshot(provider.id, nowMs));\n }\n\n getAntiBotPressure(providerId: string, nowMs = Date.now()): number {\n const snapshot = this.getAntiBotSnapshot(providerId, nowMs);\n return Math.max(\n snapshot.recentChallengeRatio,\n snapshot.recentRateLimitRatio,\n snapshot.activeChallenges > 0 ? 1 : 0,\n snapshot.cooldownUntilMs > nowMs ? 0.75 : 0\n );\n }\n\n private getState(providerId: string): ProviderState {\n const state = this.state.get(providerId);\n if (!state) {\n throw new Error(`Unknown provider state: ${providerId}`);\n }\n return state;\n }\n\n private classifyAntiBotEventKind(reasonCode?: ProviderReasonCode): ProviderAntiBotEventKind {\n if (!reasonCode) {\n return \"other\";\n }\n if (CHALLENGE_REASONS.has(reasonCode)) {\n return \"challenge\";\n }\n if (RATE_LIMIT_REASONS.has(reasonCode)) {\n return \"rate_limited\";\n }\n return \"other\";\n }\n\n private pushAntiBotEvent(state: ProviderAntiBotState, event: ProviderAntiBotEventKind): void {\n state.recentEvents.push(event);\n if (state.recentEvents.length > ANTI_BOT_WINDOW) {\n state.recentEvents.splice(0, state.recentEvents.length - ANTI_BOT_WINDOW);\n }\n }\n}\n","import type { AdaptiveConcurrencyDiagnostics } from \"./types\";\n\nexport interface AdaptiveConcurrencyConfig {\n enabled: boolean;\n baselineGlobal: number;\n baselineScoped: number;\n minGlobal?: number;\n maxGlobal: number;\n minScoped?: number;\n maxScoped: number;\n windowSize?: number;\n cooldownMs?: number;\n increaseStep?: number;\n decreaseFactor?: number;\n healthyLatencyMs?: number;\n}\n\nexport interface AdaptiveSignal {\n latencyMs: number;\n timeout?: boolean;\n challenge?: boolean;\n http4xx?: boolean;\n http5xx?: boolean;\n queuePressure?: number;\n}\n\ntype TrackState = {\n limit: number;\n lastAdjustedAt: number;\n samples: AdaptiveSignal[];\n};\n\nconst clamp = (value: number, min: number, max: number): number => {\n return Math.max(min, Math.min(max, value));\n};\n\nconst percentile = (values: number[], ratio: number): number => {\n if (values.length === 0) return 0;\n const sorted = [...values].sort((left, right) => left - right);\n const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * ratio) - 1));\n return sorted[index] ?? 0;\n};\n\nconst rate = (values: AdaptiveSignal[], key: keyof AdaptiveSignal): number => {\n if (values.length === 0) return 0;\n const total = values.reduce((count, sample) => count + (sample[key] ? 1 : 0), 0);\n return total / values.length;\n};\n\nconst queuePressure = (values: AdaptiveSignal[]): number => {\n if (values.length === 0) return 0;\n const total = values.reduce((sum, sample) => sum + (sample.queuePressure ?? 0), 0);\n return total / values.length;\n};\n\nexport class AdaptiveConcurrencyController {\n private readonly global: TrackState;\n private readonly scoped = new Map<string, TrackState>();\n private readonly minGlobal: number;\n private readonly minScoped: number;\n private readonly windowSize: number;\n private readonly cooldownMs: number;\n private readonly increaseStep: number;\n private readonly decreaseFactor: number;\n private readonly healthyLatencyMs: number;\n\n constructor(private readonly config: AdaptiveConcurrencyConfig) {\n this.minGlobal = Math.max(1, config.minGlobal ?? 1);\n this.minScoped = Math.max(1, config.minScoped ?? 1);\n this.windowSize = clamp(Math.floor(config.windowSize ?? 20), 5, 100);\n this.cooldownMs = clamp(Math.floor(config.cooldownMs ?? 3000), 250, 60000);\n this.increaseStep = clamp(Math.floor(config.increaseStep ?? 1), 1, 8);\n this.decreaseFactor = clamp(config.decreaseFactor ?? 0.7, 0.1, 0.95);\n this.healthyLatencyMs = clamp(Math.floor(config.healthyLatencyMs ?? 1200), 50, 60000);\n this.global = {\n limit: clamp(config.baselineGlobal, this.minGlobal, Math.max(this.minGlobal, config.maxGlobal)),\n lastAdjustedAt: 0,\n samples: []\n };\n }\n\n snapshot(scope: string): AdaptiveConcurrencyDiagnostics {\n if (!this.config.enabled) {\n return {\n enabled: false,\n scope,\n global: {\n limit: this.global.limit,\n min: this.minGlobal,\n max: this.config.maxGlobal\n },\n scoped: {\n limit: clamp(this.config.baselineScoped, this.minScoped, this.config.maxScoped),\n min: this.minScoped,\n max: this.config.maxScoped\n }\n };\n }\n\n const scoped = this.getScoped(scope);\n return {\n enabled: true,\n scope,\n global: {\n limit: this.global.limit,\n min: this.minGlobal,\n max: this.config.maxGlobal\n },\n scoped: {\n limit: scoped.limit,\n min: this.minScoped,\n max: this.config.maxScoped\n }\n };\n }\n\n observe(scope: string, signal: AdaptiveSignal, nowMs = Date.now()): void {\n if (!this.config.enabled) return;\n\n this.record(this.global, signal);\n const scoped = this.getScoped(scope);\n this.record(scoped, signal);\n\n this.adjust(this.global, this.minGlobal, this.config.maxGlobal, nowMs);\n this.adjust(scoped, this.minScoped, this.config.maxScoped, nowMs);\n }\n\n private getScoped(scope: string): TrackState {\n const existing = this.scoped.get(scope);\n if (existing) return existing;\n const next: TrackState = {\n limit: clamp(this.config.baselineScoped, this.minScoped, this.config.maxScoped),\n lastAdjustedAt: 0,\n samples: []\n };\n this.scoped.set(scope, next);\n return next;\n }\n\n private record(track: TrackState, signal: AdaptiveSignal): void {\n track.samples.push(signal);\n if (track.samples.length > this.windowSize) {\n track.samples.splice(0, track.samples.length - this.windowSize);\n }\n }\n\n private adjust(track: TrackState, min: number, max: number, nowMs: number): void {\n if (nowMs - track.lastAdjustedAt < this.cooldownMs) {\n return;\n }\n\n const samples = track.samples;\n const p95Latency = percentile(samples.map((sample) => sample.latencyMs), 0.95);\n const timeoutRate = rate(samples, \"timeout\");\n const challengeRate = rate(samples, \"challenge\");\n const http5xxRate = rate(samples, \"http5xx\");\n const http4xxRate = rate(samples, \"http4xx\");\n const avgQueuePressure = queuePressure(samples);\n\n const unhealthy = timeoutRate > 0\n || challengeRate > 0\n || http5xxRate > 0.15\n || http4xxRate > 0.3\n || p95Latency > this.healthyLatencyMs * 1.35\n || avgQueuePressure > 0.85;\n\n if (unhealthy) {\n const reduced = Math.floor(track.limit * this.decreaseFactor);\n track.limit = clamp(reduced, min, max);\n track.lastAdjustedAt = nowMs;\n return;\n }\n\n const healthy = timeoutRate === 0\n && challengeRate === 0\n && http5xxRate === 0\n && p95Latency <= this.healthyLatencyMs\n && avgQueuePressure < 0.6;\n\n if (healthy) {\n track.limit = clamp(track.limit + this.increaseStep, min, max);\n track.lastAdjustedAt = nowMs;\n }\n }\n}\n","import type { ProviderTier, ProviderTierMetadata } from \"./types\";\n\nexport interface TierRouterConfig {\n defaultTier: ProviderTier;\n enableHybrid: boolean;\n enableRestrictedSafe: boolean;\n hybridRiskThreshold?: number;\n restrictedSafeRecoveryIntervalMs?: number;\n}\n\nexport interface TierRouterSignals {\n hybridEligible: boolean;\n preferredTier?: ProviderTier;\n forceRestrictedSafe?: boolean;\n challengePressure?: number;\n highFrictionTarget?: boolean;\n riskScore?: number;\n hybridHealthy?: boolean;\n policyRestrictedSafe?: boolean;\n latencyBudgetExceeded?: boolean;\n errorBudgetExceeded?: boolean;\n recoveryStableForMs?: number;\n policyAllowsRecovery?: boolean;\n}\n\nexport interface TierRouteDecision {\n tier: ProviderTierMetadata;\n fallbackTier: \"A\";\n}\n\nconst canSelectTier = (tier: ProviderTier, config: TierRouterConfig): boolean => {\n if (tier === \"A\") return true;\n if (tier === \"B\") return config.enableHybrid;\n return config.enableRestrictedSafe;\n};\n\nexport const selectTierRoute = (\n config: TierRouterConfig,\n signals: TierRouterSignals\n): TierRouteDecision => {\n const challengePressure = signals.challengePressure ?? 0;\n const hybridRiskThreshold = Math.max(0, Math.min(1, config.hybridRiskThreshold ?? 0.6));\n const riskScore = Math.max(0, Math.min(1, signals.riskScore ?? challengePressure));\n const hybridHealthy = signals.hybridHealthy ?? true;\n const policyRestrictedSafe = signals.policyRestrictedSafe ?? false;\n const latencyBudgetExceeded = signals.latencyBudgetExceeded ?? false;\n const errorBudgetExceeded = signals.errorBudgetExceeded ?? false;\n const policyAllowsRecovery = signals.policyAllowsRecovery ?? true;\n const recoveryStableForMs = Math.max(0, signals.recoveryStableForMs ?? 0);\n\n if (signals.preferredTier && canSelectTier(signals.preferredTier, config)) {\n return {\n tier: {\n selected: signals.preferredTier,\n reasonCode: \"operator_override\"\n },\n fallbackTier: \"A\"\n };\n }\n\n if (config.enableRestrictedSafe && policyRestrictedSafe) {\n return {\n tier: {\n selected: \"C\",\n reasonCode: \"policy_restricted_safe\"\n },\n fallbackTier: \"A\"\n };\n }\n\n if (config.enableRestrictedSafe && signals.forceRestrictedSafe) {\n return {\n tier: {\n selected: \"C\",\n reasonCode: \"restricted_safe_forced\"\n },\n fallbackTier: \"A\"\n };\n }\n\n if (config.enableRestrictedSafe && signals.highFrictionTarget) {\n return {\n tier: {\n selected: \"C\",\n reasonCode: \"high_friction_target\"\n },\n fallbackTier: \"A\"\n };\n }\n\n if (config.enableRestrictedSafe && challengePressure >= 0.5) {\n return {\n tier: {\n selected: \"C\",\n reasonCode: \"challenge_pressure\"\n },\n fallbackTier: \"A\"\n };\n }\n\n const resolveHybridTier = (\n reasonCode: \"default_tier\" | \"hybrid_eligible\"\n ): TierRouteDecision => {\n if (!hybridHealthy) {\n return {\n tier: {\n selected: \"A\",\n reasonCode: \"hybrid_unhealthy\"\n },\n fallbackTier: \"A\"\n };\n }\n if (riskScore > hybridRiskThreshold) {\n return {\n tier: {\n selected: \"A\",\n reasonCode: \"hybrid_risk_threshold\"\n },\n fallbackTier: \"A\"\n };\n }\n if (latencyBudgetExceeded) {\n return {\n tier: {\n selected: \"A\",\n reasonCode: \"hybrid_latency_budget\"\n },\n fallbackTier: \"A\"\n };\n }\n if (errorBudgetExceeded) {\n return {\n tier: {\n selected: \"A\",\n reasonCode: \"hybrid_error_budget\"\n },\n fallbackTier: \"A\"\n };\n }\n return {\n tier: {\n selected: \"B\",\n reasonCode\n },\n fallbackTier: \"A\"\n };\n };\n\n if (config.defaultTier === \"C\") {\n if (config.enableRestrictedSafe) {\n const recovered = policyAllowsRecovery\n && recoveryStableForMs >= Math.max(0, config.restrictedSafeRecoveryIntervalMs ?? 60000);\n if (recovered) {\n if (config.enableHybrid && signals.hybridEligible) {\n const route = resolveHybridTier(\"hybrid_eligible\");\n if (route.tier.selected === \"B\") {\n return {\n tier: {\n selected: \"B\",\n reasonCode: \"restricted_safe_recovered\"\n },\n fallbackTier: \"A\"\n };\n }\n }\n return {\n tier: {\n selected: \"A\",\n reasonCode: \"restricted_safe_recovered\"\n },\n fallbackTier: \"A\"\n };\n }\n return {\n tier: {\n selected: \"C\",\n reasonCode: \"default_tier\"\n },\n fallbackTier: \"A\"\n };\n }\n return {\n tier: {\n selected: \"A\",\n reasonCode: \"restricted_safe_disabled\"\n },\n fallbackTier: \"A\"\n };\n }\n\n if (config.defaultTier === \"B\") {\n if (!config.enableHybrid) {\n return {\n tier: {\n selected: \"A\",\n reasonCode: \"hybrid_disabled\"\n },\n fallbackTier: \"A\"\n };\n }\n if (signals.hybridEligible) {\n return resolveHybridTier(\"default_tier\");\n }\n }\n\n if (config.enableHybrid && signals.hybridEligible) {\n return resolveHybridTier(\"hybrid_eligible\");\n }\n\n return {\n tier: {\n selected: \"A\",\n reasonCode: \"default_tier\"\n },\n fallbackTier: \"A\"\n };\n};\n\nexport const shouldFallbackToTierA = (tier: ProviderTier): boolean => {\n return tier !== \"A\";\n};\n\nexport const fallbackTierMetadata = (): ProviderTierMetadata => {\n return {\n selected: \"A\",\n reasonCode: \"fallback_to_tier_a\"\n };\n};\n","import type { ProviderAntiBotSnapshot } from \"../providers/registry\";\nimport type {\n BlockerSignalV1,\n BrowserFallbackDisposition,\n JsonValue,\n ProviderCookieImportRecord,\n ProviderReasonCode,\n SessionChallengeSummary\n} from \"../providers/types\";\n\nexport type ChallengeClassification =\n | \"auth_required\"\n | \"existing_session_reuse\"\n | \"human_verification_required\"\n | \"owned_environment_test_challenge\"\n | \"unsupported_third_party_challenge\"\n | \"checkpoint_or_friction\";\n\nexport type ChallengeHumanBoundary =\n | \"none\"\n | \"secret_entry\"\n | \"mfa\"\n | \"explicit_consent\"\n | \"policy_blocked\"\n | \"unsupported_third_party\"\n | \"exhausted_no_progress\";\n\nexport const CHALLENGE_AUTOMATION_MODES = [\"off\", \"browser\", \"browser_with_helper\"] as const;\nexport type ChallengeAutomationMode = (typeof CHALLENGE_AUTOMATION_MODES)[number];\nconst CHALLENGE_AUTOMATION_MODE_SET = new Set<string>(CHALLENGE_AUTOMATION_MODES);\n\nexport function isChallengeAutomationMode(value: unknown): value is ChallengeAutomationMode {\n return typeof value === \"string\" && CHALLENGE_AUTOMATION_MODE_SET.has(value);\n}\n\nexport type ChallengeAutomationModeSource = \"run\" | \"session\" | \"config\";\n\nexport type ChallengeAutomationStandDownReason =\n | \"challenge_automation_off\"\n | \"helper_disabled_for_browser_mode\"\n | \"helper_disabled_by_policy\"\n | \"helper_blocked_by_human_boundary\"\n | \"helper_no_safe_actions\"\n | \"suppressed_by_manager\";\n\nexport type ChallengeAutomationHelperEligibility = {\n allowed: boolean;\n reason: string;\n standDownReason?: ChallengeAutomationStandDownReason;\n};\n\nexport type ResolvedChallengeAutomationPolicy = {\n mode: ChallengeAutomationMode;\n source: ChallengeAutomationModeSource;\n standDownReason?: ChallengeAutomationStandDownReason;\n};\n\nexport type ChallengeVerificationLevel = \"light\" | \"full\";\n\nexport type ChallengeGovernedLaneKind =\n | \"owned_environment_fixture\"\n | \"sanctioned_identity\"\n | \"service_adapter\";\n\nexport type ChallengeStrategyLane =\n | \"generic_browser_autonomy\"\n | \"human_yield\"\n | \"owned_environment_fixture\"\n | \"sanctioned_identity\"\n | \"service_adapter\"\n | \"optional_computer_use_bridge\"\n | \"defer\";\n\nexport type ChallengeActionFamily =\n | \"wait\"\n | \"auth_navigation\"\n | \"session_reuse\"\n | \"cookie_reuse\"\n | \"element_discovery\"\n | \"click_path\"\n | \"click_and_hold\"\n | \"non_secret_form_fill\"\n | \"dropdown\"\n | \"scroll\"\n | \"hover\"\n | \"press\"\n | \"pointer\"\n | \"drag\"\n | \"verification\"\n | \"debug_trace\";\n\nexport type ChallengeStepKind =\n | \"wait\"\n | \"goto\"\n | \"click\"\n | \"click_and_hold\"\n | \"hover\"\n | \"press\"\n | \"type\"\n | \"select\"\n | \"scroll\"\n | \"pointer\"\n | \"drag\"\n | \"cookie_list\"\n | \"cookie_import\"\n | \"snapshot\"\n | \"debug_trace\";\n\nexport type ChallengeActionStatus =\n | \"resolved\"\n | \"still_blocked\"\n | \"yield_required\"\n | \"deferred\"\n | \"no_progress\"\n | \"policy_blocked\";\n\nexport type ChallengeRuntimeBlockerState = \"clear\" | \"active\" | \"resolving\";\n\nexport type ChallengeResolutionMeta = {\n status: \"resolved\" | \"unresolved\" | \"deferred\";\n reason: \"verifier_passed\" | \"verification_timeout\" | \"verifier_failed\" | \"env_limited\" | \"manual_clear\";\n updatedAt: string;\n};\n\nexport type ChallengeActionable = {\n ref: string;\n role: string;\n name?: string;\n value?: string;\n disabled: boolean;\n checked: boolean;\n};\n\nexport type ChallengeInteractionSurface = \"page\" | \"popup\" | \"interstitial\" | \"unknown\";\nexport type ChallengeInteractionPreference = \"click\" | \"click_and_hold\" | \"drag\" | \"unknown\";\n\nexport type ChallengeInteractionSignals = {\n surface: ChallengeInteractionSurface;\n preferredAction: ChallengeInteractionPreference;\n clickRefs: string[];\n holdRefs: string[];\n dragRefs: string[];\n evidencePhrases: string[];\n holdMs?: number;\n};\n\nexport type ChallengeDiagnosticsSummary = {\n traceRequestId?: string;\n consoleCount: number;\n exceptionCount: number;\n networkCount: number;\n networkHosts: string[];\n warnings: string[];\n screenshotCaptured: boolean;\n};\n\nexport type ChallengeContinuitySignals = {\n hasPreservedSession: boolean;\n hasPreservedTarget: boolean;\n hasSuspendedIntent: boolean;\n attachedSession: boolean;\n cookieCount: number;\n canReuseExistingCookies: boolean;\n canImportCookies: boolean;\n hasNonSecretTaskData: boolean;\n likelyLoginPage: boolean;\n likelySessionPicker: boolean;\n likelyHumanVerification: boolean;\n loginRefs: string[];\n sessionReuseRefs: string[];\n humanVerificationRefs: string[];\n nonSecretFieldRefs: string[];\n checkpointRefs: string[];\n};\n\nexport type ChallengeEvidenceBundle = {\n challengeId?: string;\n blocker?: BlockerSignalV1;\n blockerState: ChallengeRuntimeBlockerState;\n blockerResolution?: ChallengeResolutionMeta;\n challenge?: SessionChallengeSummary;\n url?: string;\n title?: string;\n activeTargetId?: string | null;\n snapshotId?: string;\n mode?: string;\n fallbackDisposition?: BrowserFallbackDisposition;\n ownerSurface?: SessionChallengeSummary[\"ownerSurface\"];\n preservedSessionId?: string;\n preservedTargetId?: string;\n suspendedIntent?: SessionChallengeSummary[\"suspendedIntent\"];\n registryPressure?: ProviderAntiBotSnapshot;\n taskData?: Record<string, JsonValue>;\n actionables: ChallengeActionable[];\n snapshotText?: string;\n diagnostics: ChallengeDiagnosticsSummary;\n continuity: ChallengeContinuitySignals;\n interaction?: ChallengeInteractionSignals;\n};\n\nexport type ChallengeInterpreterResult = {\n classification: ChallengeClassification;\n authState:\n | \"unknown\"\n | \"authenticated\"\n | \"login_page\"\n | \"session_reusable\"\n | \"credentials_required\"\n | \"human_verification\";\n humanBoundary: ChallengeHumanBoundary;\n requiredVerification: ChallengeVerificationLevel;\n continuityOpportunities: Array<\"existing_session\" | \"cookie_reuse\" | \"non_secret_form_fill\">;\n allowedActionFamilies: ChallengeActionFamily[];\n laneHints: ChallengeStrategyLane[];\n stopRisk: \"low\" | \"medium\" | \"high\";\n summary: string;\n likelyCheckpoint?: string;\n};\n\nexport type ChallengePolicyGate = {\n resolvedPolicy: ResolvedChallengeAutomationPolicy;\n allowedActions: ChallengeActionFamily[];\n forbiddenActions: ChallengeActionFamily[];\n handoffTriggers: ChallengeHumanBoundary[];\n governedLanes: ChallengeGovernedLaneKind[];\n optionalComputerUseBridge: boolean;\n helperEligibility: ChallengeAutomationHelperEligibility;\n};\n\nexport type ChallengeCapabilityMatrix = {\n canNavigateToAuth: boolean;\n canReuseExistingSession: boolean;\n canReuseCookies: boolean;\n canFillNonSecretFields: boolean;\n canExploreClicks: boolean;\n canUseOwnedEnvironmentFixture: boolean;\n canUseSanctionedIdentity: boolean;\n canUseServiceAdapter: boolean;\n canUseComputerUseBridge: boolean;\n helperEligibility: ChallengeAutomationHelperEligibility;\n mustYield: boolean;\n mustDefer: boolean;\n};\n\nexport type ChallengeStrategyDecision = {\n lane: ChallengeStrategyLane;\n governedLane?: ChallengeGovernedLaneKind;\n rationale: string;\n attemptBudget: number;\n noProgressLimit: number;\n verificationLevel: ChallengeVerificationLevel;\n stopConditions: string[];\n allowedActionFamilies: ChallengeActionFamily[];\n};\n\nexport type ChallengeActionStep = {\n kind: ChallengeStepKind;\n reason: string;\n ref?: string;\n url?: string;\n text?: string;\n values?: string[];\n cookies?: ProviderCookieImportRecord[];\n snapshotChars?: number;\n traceMax?: number;\n dy?: number;\n holdMs?: number;\n coordinates?: {\n x: number;\n y: number;\n };\n};\n\nexport type VerificationResult = {\n status: \"clear\" | \"still_blocked\" | \"progress\" | \"yield_required\" | \"deferred\";\n blockerState: ChallengeRuntimeBlockerState;\n blocker?: BlockerSignalV1;\n challenge?: SessionChallengeSummary;\n bundle?: ChallengeEvidenceBundle;\n changed: boolean;\n reason: string;\n url?: string;\n title?: string;\n};\n\nexport type HumanYieldPacket = {\n challengeId: string;\n classification: ChallengeClassification;\n reason: ChallengeHumanBoundary;\n sessionId: string;\n targetId?: string | null;\n ownerSurface?: SessionChallengeSummary[\"ownerSurface\"];\n url?: string;\n title?: string;\n requiredHumanStep: string;\n targetHints: string[];\n expectedPostAuthCheckpoint?: string;\n preserveUntil?: string;\n verifyUntil?: string;\n traceRequestId?: string;\n lastVerificationStatus?: VerificationResult[\"status\"];\n lastVerificationReason?: string;\n evidenceSummary: string;\n reclaimHint: string;\n resumeRule: string;\n};\n\nexport type OutcomeRecord = {\n at: string;\n challengeId?: string;\n lane: ChallengeStrategyLane;\n status: ChallengeActionStatus;\n reason: string;\n attempts: number;\n reusedExistingSession: boolean;\n reusedCookies: boolean;\n verification?: VerificationResult;\n evidence: ChallengeOrchestrationSnapshot[\"evidence\"];\n resumeOutcome: \"continued\" | \"awaiting_human_reclaim\" | \"deferred\" | \"still_blocked\";\n executedSteps: ChallengeActionStep[];\n yielded?: HumanYieldPacket;\n};\n\nexport type ChallengeOrchestrationSnapshot = {\n challengeId?: string;\n classification: ChallengeClassification;\n mode: ChallengeAutomationMode;\n source: ChallengeAutomationModeSource;\n lane: ChallengeStrategyLane;\n status: ChallengeActionStatus;\n reason: string;\n attempts: number;\n reusedExistingSession: boolean;\n reusedCookies: boolean;\n standDownReason?: ChallengeAutomationStandDownReason;\n helperEligibility: ChallengeAutomationHelperEligibility;\n verification: VerificationResult;\n evidence: {\n url?: string;\n title?: string;\n blockerType?: BlockerSignalV1[\"type\"];\n fallbackDisposition?: BrowserFallbackDisposition;\n loginRefs: string[];\n humanVerificationRefs: string[];\n checkpointRefs: string[];\n interactionSurface?: ChallengeInteractionSurface;\n preferredAction?: ChallengeInteractionPreference;\n holdMs?: number;\n registryPressure?: ProviderAntiBotSnapshot;\n };\n yielded?: HumanYieldPacket;\n};\n\nexport type ChallengeActionResult = {\n status: ChallengeActionStatus;\n attempts: number;\n noProgressCount: number;\n executedSteps: ChallengeActionStep[];\n verification: VerificationResult;\n reusedExistingSession: boolean;\n reusedCookies: boolean;\n};\n\nexport type GovernedLaneRequest = {\n lane: ChallengeGovernedLaneKind;\n bundle: ChallengeEvidenceBundle;\n interpretation: ChallengeInterpreterResult;\n decision: ChallengeStrategyDecision;\n auditContext?: Record<string, JsonValue>;\n};\n\nexport type GovernedLaneResult = {\n status: \"executed\" | \"blocked\" | \"skipped\";\n lane: ChallengeGovernedLaneKind;\n reason: string;\n auditMetadata: Record<string, JsonValue>;\n suggestedSteps?: ChallengeActionStep[];\n};\n\nexport type ComputerUseBridgeResult = {\n status: \"disabled\" | \"suggested\" | \"unsupported\";\n reason: string;\n suggestedSteps: ChallengeActionStep[];\n standDownReason?: ChallengeAutomationStandDownReason;\n auditMetadata?: Record<string, JsonValue>;\n};\n\nexport type ChallengeInspectPlan = {\n challengeId?: string;\n sessionMode?: string;\n classification: ChallengeClassification;\n authState: ChallengeInterpreterResult[\"authState\"];\n summary: string;\n mode: ChallengeAutomationMode;\n source: ChallengeAutomationModeSource;\n helperEligibility: ChallengeAutomationHelperEligibility;\n standDownReason?: ChallengeAutomationStandDownReason;\n yield: {\n required: boolean;\n reason: ChallengeHumanBoundary;\n };\n decision: ChallengeStrategyDecision;\n allowedActionFamilies: ChallengeActionFamily[];\n forbiddenActionFamilies: ChallengeActionFamily[];\n governedLanes: ChallengeGovernedLaneKind[];\n capabilityMatrix: ChallengeCapabilityMatrix;\n helper: ComputerUseBridgeResult;\n suggestedSteps: ChallengeActionStep[];\n evidence: {\n blockerState: ChallengeRuntimeBlockerState;\n blockerType?: BlockerSignalV1[\"type\"];\n url?: string;\n title?: string;\n activeTargetId?: string | null;\n snapshotId?: string;\n loginRefs: string[];\n sessionReuseRefs: string[];\n humanVerificationRefs: string[];\n checkpointRefs: string[];\n };\n};\n\nexport type ChallengeOrchestrationResult = {\n bundle: ChallengeEvidenceBundle;\n interpretation: ChallengeInterpreterResult;\n decision: ChallengeStrategyDecision;\n action: ChallengeActionResult;\n outcome: ChallengeOrchestrationSnapshot;\n};\n","import type { ProviderAntiBotSnapshot } from \"../providers/registry\";\nimport type { BrowserFallbackDisposition, JsonValue } from \"../providers/types\";\nimport type {\n ChallengeActionable,\n ChallengeContinuitySignals,\n ChallengeDiagnosticsSummary,\n ChallengeEvidenceBundle,\n ChallengeInteractionSignals,\n ChallengeInteractionSurface\n} from \"./types\";\n\ntype ChallengeStatusInput = {\n mode: string;\n activeTargetId: string | null;\n url?: string;\n title?: string;\n meta?: {\n blocker?: ChallengeEvidenceBundle[\"blocker\"];\n blockerState: ChallengeEvidenceBundle[\"blockerState\"];\n blockerResolution?: ChallengeEvidenceBundle[\"blockerResolution\"];\n challenge?: ChallengeEvidenceBundle[\"challenge\"];\n };\n};\n\ntype ChallengeDebugTraceInput = {\n requestId?: string;\n channels?: {\n console?: { events?: unknown[] };\n network?: { events?: Array<{ url?: string }> };\n exception?: { events?: unknown[] };\n };\n};\n\nexport type ChallengeEvidenceInput = {\n status: ChallengeStatusInput;\n snapshot?: {\n snapshotId?: string;\n content?: string;\n warnings?: string[];\n };\n debugTrace?: ChallengeDebugTraceInput;\n cookieCount?: number;\n canImportCookies?: boolean;\n fallbackDisposition?: BrowserFallbackDisposition;\n registryPressure?: ProviderAntiBotSnapshot;\n taskData?: Record<string, JsonValue>;\n};\n\nconst ACTIONABLE_RE =\n /^\\[(r\\d+)\\]\\s+([^\\s]+)(?:\\s+(disabled))?(?:\\s+(checked))?(?:\\s+\"([^\"]+)\")?(?:\\s+value=\"([^\"]*)\")?/i;\n\nconst LOGIN_RE = /\\b(log ?in|sign ?in|sign in|continue with)\\b/i;\nconst SESSION_REUSE_RE = /\\b(use existing|existing session|choose account|switch account|stay signed in|remember me)\\b/i;\nconst ACCOUNT_CHOOSER_RE = /\\b(?:choose an account|choose account|pick an account|select an account|continue as)\\b/i;\nconst ALT_ACCOUNT_RE = /\\b(?:use another account|use a different account|add account|add another account|sign in with another account)\\b/i;\nconst HUMAN_VERIFICATION_RE = /\\b(captcha|verify (?:that )?you(?:'re| are) human|security check|prove you are human|turnstile|recaptcha|hcaptcha)\\b/i;\nconst NON_SECRET_FIELD_RE = /\\b(email|e-mail|username|first name|last name|full name|company|phone|city|state|country|linkedin|portfolio|resume|cv)\\b/i;\nconst CHECKPOINT_RE = /\\b(next|continue|resume|verify|submit|approve|allow)\\b/i;\nconst LOGIN_PAGE_RE = /\\/(login|signin|sign-in|auth|session)(?:[/?#]|$)/i;\nconst GOOGLE_AUTH_RE = /\\b(?:continue with google|sign in with google|log in with google|google sign(?: |-)?in)\\b/i;\nconst GITHUB_AUTH_RE = /\\b(?:continue with github|sign in with github|log in with github|github sign(?: |-)?in)\\b/i;\nconst APPLE_AUTH_RE = /\\b(?:continue with apple|sign in with apple|log in with apple|apple sign(?: |-)?in)\\b/i;\nconst ACCOUNT_CHOOSER_NOISE_RE = /\\b(?:help|privacy|terms|learn more|english|afrikaans|espa[ñn]ol)\\b/i;\nconst CLICK_ACTION_RE = /\\b(click|tap|select|choose|continue|allow|dismiss|close|not now|got it|delivery|pickup|ship(?:ping)? here)\\b/i;\nconst HOLD_ACTION_RE = /\\b(?:click|press|tap|activate)\\s+(?:and\\s+)?hold\\b|\\bhold (?:the )?(?:button|slider)\\b/i;\nconst DRAG_ACTION_RE = /\\b(?:drag|slide|move)(?:\\s+the)?\\s+(?:slider|puzzle(?:\\s+piece)?|piece|button)\\b/i;\nconst POPUP_SURFACE_RE = /\\b(?:popup|pop up|modal|dialog|choose where (?:you(?:'|’)d|you would|to) like to shop|how do you want your items|set your location|confirm your location|choose a store)\\b/i;\nconst INTERSTITIAL_SURFACE_RE = /\\b(?:interstitial|security check|verify (?:that )?you(?:'re| are) human|checking your browser|captcha|challenge|press and hold|click and hold|drag the slider|slide to verify)\\b/i;\nconst CLICKABLE_ROLE_RE = /^(?:button|link|menuitem|option|tab|radio|checkbox)$/i;\nconst DIALOG_ROLE_RE = /^(?:dialog|alertdialog)$/i;\nconst HOLD_DURATION_RE = /\\b(\\d+)\\s*(second|sec|seconds|minute|min|minutes)\\b/i;\nconst DEFAULT_HOLD_MS = 1500;\nconst MAX_HOLD_MS = 60_000;\n\nconst sanitize = (value: string | undefined): string | undefined => {\n if (!value) return undefined;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n};\n\nconst dedupe = (values: string[]): string[] => {\n return [...new Set(values.filter((value) => value.trim().length > 0))];\n};\n\nconst parseActionables = (content: string | undefined): ChallengeActionable[] => {\n if (!content) return [];\n const actionables: ChallengeActionable[] = [];\n for (const line of content.split(\"\\n\")) {\n const match = line.match(ACTIONABLE_RE);\n if (!match) continue;\n actionables.push({\n ref: match[1]!,\n role: match[2]!,\n name: sanitize(match[5]),\n value: sanitize(match[6]),\n disabled: Boolean(match[3]),\n checked: Boolean(match[4])\n });\n }\n return actionables;\n};\n\nconst collectRefs = (actionables: ChallengeActionable[], matcher: RegExp): string[] => {\n return actionables\n .filter((entry) => {\n const haystack = `${entry.role} ${entry.name ?? \"\"} ${entry.value ?? \"\"}`.trim();\n return matcher.test(haystack);\n })\n .map((entry) => entry.ref);\n};\n\nconst collectInteractiveRefs = (actionables: ChallengeActionable[], matcher: RegExp): string[] => {\n return actionables\n .filter((entry) => {\n if (entry.disabled || !CLICKABLE_ROLE_RE.test(entry.role)) {\n return false;\n }\n const haystack = `${entry.role} ${entry.name ?? \"\"} ${entry.value ?? \"\"}`.trim();\n return matcher.test(haystack);\n })\n .map((entry) => entry.ref);\n};\n\nconst resolveActionableLabel = (entry: ChallengeActionable): string =>\n `${entry.name ?? \"\"} ${entry.value ?? \"\"}`.trim();\n\nconst collectPreferredAuthRefs = (actionables: ChallengeActionable[]): string[] => {\n const collect = (matcher: RegExp): string[] => actionables\n .filter((entry) => {\n if (entry.disabled || !CLICKABLE_ROLE_RE.test(entry.role)) {\n return false;\n }\n return matcher.test(resolveActionableLabel(entry));\n })\n .map((entry) => entry.ref);\n\n return dedupe([\n ...collect(GOOGLE_AUTH_RE),\n ...collect(GITHUB_AUTH_RE),\n ...collect(APPLE_AUTH_RE),\n ...collectRefs(actionables, LOGIN_RE)\n ]);\n};\n\nconst collectChooserRefs = (actionables: ChallengeActionable[], chooserSurface: boolean): {\n recentAccountRefs: string[];\n alternateAccountRefs: string[];\n} => {\n if (!chooserSurface) {\n return {\n recentAccountRefs: [],\n alternateAccountRefs: []\n };\n }\n\n const interactiveActionables = actionables.filter((entry) => !entry.disabled && CLICKABLE_ROLE_RE.test(entry.role));\n const alternateAccountRefs = interactiveActionables\n .filter((entry) => ALT_ACCOUNT_RE.test(resolveActionableLabel(entry)))\n .map((entry) => entry.ref);\n const firstAlternateIndex = alternateAccountRefs.length > 0\n ? interactiveActionables.findIndex((entry) => entry.ref === alternateAccountRefs[0])\n : interactiveActionables.length;\n const recentAccountRefs = interactiveActionables\n .filter((entry, index) => {\n if (index >= firstAlternateIndex) {\n return false;\n }\n const label = resolveActionableLabel(entry);\n return label.length > 0\n && !ACCOUNT_CHOOSER_NOISE_RE.test(label)\n && !LOGIN_RE.test(label)\n && !CHECKPOINT_RE.test(label)\n && !HUMAN_VERIFICATION_RE.test(label);\n })\n .map((entry) => entry.ref);\n\n return {\n recentAccountRefs,\n alternateAccountRefs\n };\n};\n\nconst parseHoldDurationMs = (value: string): number | undefined => {\n const match = value.match(HOLD_DURATION_RE);\n if (!match?.[1] || !match[2]) {\n return undefined;\n }\n const amount = Number(match[1]);\n if (!Number.isFinite(amount) || amount <= 0) {\n return undefined;\n }\n const unit = match[2].toLowerCase();\n const multiplier = unit.startsWith(\"min\") ? 60_000 : 1000;\n return Math.min(MAX_HOLD_MS, Math.max(1000, Math.floor(amount * multiplier)));\n};\n\nconst buildContinuitySignals = (\n input: ChallengeEvidenceInput,\n actionables: ChallengeActionable[]\n): ChallengeContinuitySignals => {\n const challenge = input.status.meta?.challenge;\n const url = input.status.url ?? \"\";\n const chooserSurface = ACCOUNT_CHOOSER_RE.test([\n input.status.title,\n input.snapshot?.content,\n url\n ]\n .filter((value): value is string => typeof value === \"string\" && value.trim().length > 0)\n .join(\" \"));\n const { recentAccountRefs, alternateAccountRefs } = collectChooserRefs(actionables, chooserSurface);\n const loginRefs = dedupe([\n ...collectPreferredAuthRefs(actionables),\n ...alternateAccountRefs\n ]);\n const sessionReuseRefs = dedupe([\n ...recentAccountRefs,\n ...collectRefs(actionables, SESSION_REUSE_RE).filter((ref) => !alternateAccountRefs.includes(ref))\n ]);\n const humanVerificationRefs = collectRefs(actionables, HUMAN_VERIFICATION_RE);\n const nonSecretFieldRefs = collectRefs(actionables, NON_SECRET_FIELD_RE);\n const checkpointRefs = collectRefs(actionables, CHECKPOINT_RE);\n const hasTaskData = Boolean(input.taskData && Object.keys(input.taskData).length > 0);\n const cookieCount = input.cookieCount ?? 0;\n\n return {\n hasPreservedSession: typeof challenge?.preservedSessionId === \"string\" && challenge.preservedSessionId.length > 0,\n hasPreservedTarget: typeof challenge?.preservedTargetId === \"string\" && challenge.preservedTargetId.length > 0,\n hasSuspendedIntent: Boolean(challenge?.suspendedIntent),\n attachedSession: typeof challenge?.ownerSurface === \"string\",\n cookieCount,\n canReuseExistingCookies: cookieCount > 0,\n canImportCookies: Boolean(input.canImportCookies),\n hasNonSecretTaskData: hasTaskData,\n likelyLoginPage: LOGIN_PAGE_RE.test(url) || loginRefs.length > 0,\n likelySessionPicker: chooserSurface || sessionReuseRefs.length > 0,\n likelyHumanVerification: humanVerificationRefs.length > 0,\n loginRefs,\n sessionReuseRefs,\n humanVerificationRefs,\n nonSecretFieldRefs,\n checkpointRefs\n };\n};\n\nconst resolveInteractionSurface = (args: {\n actionables: ChallengeActionable[];\n combinedText: string;\n warnings: string[];\n}): ChallengeInteractionSurface => {\n if (args.actionables.some((entry) => DIALOG_ROLE_RE.test(entry.role)) || POPUP_SURFACE_RE.test(args.combinedText)) {\n return \"popup\";\n }\n if (INTERSTITIAL_SURFACE_RE.test(args.combinedText) || args.warnings.some((warning) => INTERSTITIAL_SURFACE_RE.test(warning))) {\n return \"interstitial\";\n }\n if (args.combinedText.trim().length > 0 || args.actionables.length > 0) {\n return \"page\";\n }\n return \"unknown\";\n};\n\nconst buildInteractionSignals = (\n input: ChallengeEvidenceInput,\n actionables: ChallengeActionable[],\n continuity: ChallengeContinuitySignals\n): ChallengeInteractionSignals => {\n const warnings = input.snapshot?.warnings ?? [];\n const combinedText = [\n input.status.title,\n input.snapshot?.content,\n ...warnings\n ]\n .filter((value): value is string => typeof value === \"string\" && value.trim().length > 0)\n .join(\" \");\n const surface = resolveInteractionSurface({ actionables, combinedText, warnings });\n const holdRefs = dedupe(collectInteractiveRefs(actionables, HOLD_ACTION_RE));\n const dragRefs = dedupe(collectInteractiveRefs(actionables, DRAG_ACTION_RE));\n const clickRefs = dedupe([\n ...collectInteractiveRefs(actionables, CLICK_ACTION_RE),\n ...continuity.checkpointRefs,\n ...(surface === \"popup\"\n ? actionables\n .filter((entry) => !entry.disabled && CLICKABLE_ROLE_RE.test(entry.role))\n .slice(0, 4)\n .map((entry) => entry.ref)\n : [])\n ]);\n\n const evidencePhrases = dedupe([\n ...(surface === \"popup\" ? [\"popup_surface\"] : []),\n ...(surface === \"interstitial\" ? [\"interstitial_surface\"] : []),\n ...(HOLD_ACTION_RE.test(combinedText) ? [\"click_and_hold_prompt\"] : []),\n ...(DRAG_ACTION_RE.test(combinedText) ? [\"drag_prompt\"] : [])\n ]);\n const holdMs = HOLD_ACTION_RE.test(combinedText)\n ? parseHoldDurationMs(combinedText) ?? DEFAULT_HOLD_MS\n : undefined;\n\n const preferredAction = holdRefs.length > 0 || HOLD_ACTION_RE.test(combinedText)\n ? \"click_and_hold\"\n : dragRefs.length > 0 || DRAG_ACTION_RE.test(combinedText)\n ? \"drag\"\n : clickRefs.length > 0 || surface === \"popup\"\n ? \"click\"\n : \"unknown\";\n\n return {\n surface,\n preferredAction,\n clickRefs,\n holdRefs,\n dragRefs,\n evidencePhrases,\n ...(typeof holdMs === \"number\" ? { holdMs } : {})\n };\n};\n\nconst buildDiagnostics = (input: ChallengeEvidenceInput): ChallengeDiagnosticsSummary => {\n const networkEvents = input.debugTrace?.channels?.network?.events ?? [];\n const warnings = input.snapshot?.warnings ?? [];\n const networkHosts = [...new Set(networkEvents\n .map((event) => {\n try {\n return event.url ? new URL(event.url).hostname.toLowerCase() : null;\n } catch {\n return null;\n }\n })\n .filter((value): value is string => Boolean(value)))];\n\n return {\n traceRequestId: sanitize(input.debugTrace?.requestId),\n consoleCount: input.debugTrace?.channels?.console?.events?.length ?? 0,\n exceptionCount: input.debugTrace?.channels?.exception?.events?.length ?? 0,\n networkCount: networkEvents.length,\n networkHosts,\n warnings,\n screenshotCaptured: false\n };\n};\n\nexport const buildChallengeEvidenceBundle = (input: ChallengeEvidenceInput): ChallengeEvidenceBundle => {\n const actionables = parseActionables(input.snapshot?.content);\n const diagnostics = buildDiagnostics(input);\n const continuity = buildContinuitySignals(input, actionables);\n const interaction = buildInteractionSignals(input, actionables, continuity);\n const blockerState = input.status.meta?.blockerState ?? \"clear\";\n const challenge = input.status.meta?.challenge;\n\n return {\n challengeId: challenge?.challengeId,\n blocker: input.status.meta?.blocker,\n blockerState,\n blockerResolution: input.status.meta?.blockerResolution,\n challenge,\n url: sanitize(input.status.url),\n title: sanitize(input.status.title),\n activeTargetId: input.status.activeTargetId,\n snapshotId: input.snapshot?.snapshotId,\n mode: sanitize(input.status.mode),\n fallbackDisposition: input.fallbackDisposition,\n ownerSurface: challenge?.ownerSurface,\n preservedSessionId: challenge?.preservedSessionId,\n preservedTargetId: challenge?.preservedTargetId,\n suspendedIntent: challenge?.suspendedIntent,\n registryPressure: input.registryPressure,\n taskData: input.taskData,\n actionables,\n snapshotText: input.snapshot?.content,\n diagnostics,\n continuity,\n interaction\n };\n};\n","import type { ChallengeClassification, ChallengeEvidenceBundle, ChallengeInterpreterResult } from \"./types\";\n\nconst PASSWORD_RE = /\\b(password|passcode|secret)\\b/i;\nconst MFA_RE = /\\b(mfa|otp|one.?time|two.?factor|verification code|passkey|security key|authenticator)\\b/i;\nconst HUMAN_RE = /\\b(captcha|verify (?:that )?you(?:'re| are) human|turnstile|recaptcha|hcaptcha|security check)\\b/i;\nconst FIXTURE_RE = /\\b(turnstile-checkbox|recaptcha-v2-checkbox|vendor test key|test site key)\\b/i;\n\nconst summarize = (parts: Array<string | false | null | undefined>): string => {\n return parts.filter((value): value is string => Boolean(value)).join(\"; \");\n};\n\nconst detectOwnedFixture = (bundle: ChallengeEvidenceBundle): boolean => {\n const haystack = [bundle.url, bundle.title, bundle.snapshotText]\n .filter((value): value is string => typeof value === \"string\" && value.length > 0)\n .join(\" \");\n return haystack.startsWith(\"file:\")\n ? FIXTURE_RE.test(haystack)\n : FIXTURE_RE.test(haystack);\n};\n\nconst detectHumanBoundary = (bundle: ChallengeEvidenceBundle): ChallengeInterpreterResult[\"humanBoundary\"] => {\n const text = [bundle.snapshotText, bundle.title]\n .filter((value): value is string => typeof value === \"string\" && value.length > 0)\n .join(\" \");\n if (MFA_RE.test(text)) return \"mfa\";\n if (PASSWORD_RE.test(text)) return \"secret_entry\";\n return \"none\";\n};\n\nconst detectClassification = (\n bundle: ChallengeEvidenceBundle,\n humanBoundary: ChallengeInterpreterResult[\"humanBoundary\"]\n): ChallengeClassification => {\n const blockerType = bundle.blocker?.type;\n const reasonCode = bundle.blocker?.reasonCode ?? bundle.challenge?.reasonCode;\n const isLogin = bundle.continuity.likelyLoginPage;\n const hasReuse = bundle.continuity.hasPreservedSession\n || bundle.continuity.canReuseExistingCookies\n || bundle.continuity.sessionReuseRefs.length > 0;\n const humanVerification = bundle.continuity.likelyHumanVerification\n || HUMAN_RE.test(bundle.snapshotText ?? \"\")\n || reasonCode === \"challenge_detected\";\n\n if (detectOwnedFixture(bundle)) return \"owned_environment_test_challenge\";\n if (humanBoundary === \"mfa\") return \"human_verification_required\";\n if (humanBoundary === \"secret_entry\") return \"auth_required\";\n if (isLogin && hasReuse) return \"existing_session_reuse\";\n if (blockerType === \"auth_required\" || reasonCode === \"auth_required\" || reasonCode === \"token_required\" || isLogin) {\n return hasReuse ? \"existing_session_reuse\" : \"auth_required\";\n }\n if (humanVerification) {\n return bundle.continuity.sessionReuseRefs.length > 0\n ? \"checkpoint_or_friction\"\n : \"unsupported_third_party_challenge\";\n }\n return \"checkpoint_or_friction\";\n};\n\nexport const interpretChallengeEvidence = (\n bundle: ChallengeEvidenceBundle\n): ChallengeInterpreterResult => {\n const humanBoundary = detectHumanBoundary(bundle);\n const classification = detectClassification(bundle, humanBoundary);\n const preferredAction = bundle.interaction?.preferredAction;\n const authState: ChallengeInterpreterResult[\"authState\"] = classification === \"existing_session_reuse\"\n ? \"session_reusable\"\n : classification === \"auth_required\"\n ? bundle.continuity.likelyLoginPage\n ? \"login_page\"\n : \"credentials_required\"\n : classification === \"human_verification_required\" || classification === \"unsupported_third_party_challenge\"\n ? \"human_verification\"\n : bundle.continuity.canReuseExistingCookies\n ? \"authenticated\"\n : \"unknown\";\n\n const allowedActionFamilies = new Set<ChallengeInterpreterResult[\"allowedActionFamilies\"][number]>([\n \"wait\",\n \"verification\",\n \"debug_trace\",\n ...(classification === \"auth_required\" || classification === \"existing_session_reuse\"\n ? [\"auth_navigation\", \"session_reuse\", \"cookie_reuse\", \"element_discovery\", \"click_path\", \"scroll\", \"hover\", \"press\"] as const\n : [\"element_discovery\", \"click_path\", \"scroll\", \"hover\", \"press\", \"pointer\", \"drag\"] as const),\n ...(bundle.continuity.hasNonSecretTaskData && bundle.continuity.nonSecretFieldRefs.length > 0\n ? [\"non_secret_form_fill\", \"dropdown\"] as const\n : [] as const)\n ]);\n if (preferredAction === \"click_and_hold\") {\n allowedActionFamilies.add(\"click_and_hold\");\n allowedActionFamilies.add(\"pointer\");\n }\n if (preferredAction === \"drag\") {\n allowedActionFamilies.add(\"drag\");\n allowedActionFamilies.add(\"pointer\");\n }\n\n const continuityOpportunities: ChallengeInterpreterResult[\"continuityOpportunities\"] = [];\n if (\n bundle.continuity.hasPreservedSession\n || bundle.continuity.attachedSession\n || bundle.continuity.sessionReuseRefs.length > 0\n ) {\n continuityOpportunities.push(\"existing_session\");\n }\n if (bundle.continuity.canReuseExistingCookies || bundle.continuity.canImportCookies) {\n continuityOpportunities.push(\"cookie_reuse\");\n }\n if (bundle.continuity.hasNonSecretTaskData && bundle.continuity.nonSecretFieldRefs.length > 0) {\n continuityOpportunities.push(\"non_secret_form_fill\");\n }\n\n const laneHints: ChallengeInterpreterResult[\"laneHints\"] = classification === \"owned_environment_test_challenge\"\n ? [\"owned_environment_fixture\", \"generic_browser_autonomy\"]\n : humanBoundary !== \"none\"\n ? [\"human_yield\"]\n : classification === \"unsupported_third_party_challenge\"\n ? [\"optional_computer_use_bridge\", \"human_yield\"]\n : [\"generic_browser_autonomy\"];\n\n const stopRisk = humanBoundary === \"mfa\" || classification === \"unsupported_third_party_challenge\"\n ? \"high\"\n : bundle.blockerState === \"active\"\n ? \"medium\"\n : \"low\";\n\n return {\n classification,\n authState,\n humanBoundary: classification === \"unsupported_third_party_challenge\" && humanBoundary === \"none\"\n ? \"unsupported_third_party\"\n : humanBoundary,\n requiredVerification: stopRisk === \"low\" ? \"light\" : \"full\",\n continuityOpportunities,\n allowedActionFamilies: [...allowedActionFamilies],\n laneHints,\n stopRisk,\n summary: summarize([\n `classification=${classification}`,\n `authState=${authState}`,\n bundle.interaction?.surface && bundle.interaction.surface !== \"unknown\" ? `surface=${bundle.interaction.surface}` : null,\n preferredAction && preferredAction !== \"unknown\" ? `preferredAction=${preferredAction}` : null,\n continuityOpportunities.length > 0 ? `continuity=${continuityOpportunities.join(\",\")}` : null,\n bundle.continuity.likelyLoginPage ? \"login-page-visible\" : null,\n bundle.continuity.likelyHumanVerification ? \"human-verification-visible\" : null\n ]),\n likelyCheckpoint: bundle.continuity.checkpointRefs.length > 0\n ? bundle.continuity.checkpointRefs[0]\n : undefined\n };\n};\n","import type { ChallengeRuntimeHandle } from \"../browser/manager-types\";\nimport { buildChallengeEvidenceBundle } from \"./evidence-bundle\";\nimport { interpretChallengeEvidence } from \"./interpreter\";\nimport type { ChallengeEvidenceBundle, VerificationResult } from \"./types\";\n\nconst hasProgress = (previous: ChallengeEvidenceBundle, next: ChallengeEvidenceBundle): boolean => {\n return previous.blockerState !== next.blockerState\n || previous.blocker?.type !== next.blocker?.type\n || previous.activeTargetId !== next.activeTargetId\n || previous.url !== next.url\n || previous.title !== next.title\n || previous.continuity.canReuseExistingCookies !== next.continuity.canReuseExistingCookies\n || previous.continuity.loginRefs.join(\",\") !== next.continuity.loginRefs.join(\",\")\n || previous.continuity.sessionReuseRefs.join(\",\") !== next.continuity.sessionReuseRefs.join(\",\")\n || previous.continuity.humanVerificationRefs.join(\",\") !== next.continuity.humanVerificationRefs.join(\",\")\n || previous.interaction?.surface !== next.interaction?.surface\n || previous.interaction?.preferredAction !== next.interaction?.preferredAction\n || (previous.interaction?.clickRefs.join(\",\") ?? \"\") !== (next.interaction?.clickRefs.join(\",\") ?? \"\")\n || (previous.interaction?.holdRefs.join(\",\") ?? \"\") !== (next.interaction?.holdRefs.join(\",\") ?? \"\")\n || (previous.interaction?.dragRefs.join(\",\") ?? \"\") !== (next.interaction?.dragRefs.join(\",\") ?? \"\");\n};\n\nexport const verifyChallengeProgress = async (args: {\n handle: ChallengeRuntimeHandle;\n sessionId: string;\n targetId?: string | null;\n previous: ChallengeEvidenceBundle;\n canImportCookies: boolean;\n fallbackDisposition?: ChallengeEvidenceBundle[\"fallbackDisposition\"];\n registryPressure?: ChallengeEvidenceBundle[\"registryPressure\"];\n taskData?: ChallengeEvidenceBundle[\"taskData\"];\n snapshotChars?: number;\n traceMax?: number;\n}): Promise<VerificationResult> => {\n const status = await args.handle.status(args.sessionId);\n const effectiveTargetId = status.activeTargetId ?? args.targetId ?? null;\n const snapshot = await args.handle.snapshot(\n args.sessionId,\n \"actionables\",\n args.snapshotChars ?? 2400,\n undefined,\n effectiveTargetId\n );\n const debugTrace = await args.handle.debugTraceSnapshot(args.sessionId, {\n max: args.traceMax ?? 50\n });\n const cookieList = status.url\n ? await args.handle.cookieList(args.sessionId, [status.url])\n : { count: 0 };\n const bundle = buildChallengeEvidenceBundle({\n status,\n snapshot: {\n snapshotId: snapshot.snapshotId,\n content: snapshot.content,\n warnings: snapshot.warnings\n },\n debugTrace,\n cookieCount: cookieList.count,\n canImportCookies: args.canImportCookies,\n fallbackDisposition: args.fallbackDisposition,\n registryPressure: args.registryPressure,\n taskData: args.taskData\n });\n const interpretation = interpretChallengeEvidence(bundle);\n const changed = hasProgress(args.previous, bundle);\n\n if (bundle.blockerState === \"clear\" || bundle.blockerResolution?.status === \"resolved\") {\n return {\n status: \"clear\",\n blockerState: bundle.blockerState,\n blocker: bundle.blocker,\n challenge: bundle.challenge,\n bundle,\n changed: true,\n reason: \"Manager verification cleared the blocker.\",\n url: bundle.url,\n title: bundle.title\n };\n }\n\n if (bundle.blockerResolution?.status === \"deferred\") {\n return {\n status: \"deferred\",\n blockerState: bundle.blockerState,\n blocker: bundle.blocker,\n challenge: bundle.challenge,\n bundle,\n changed,\n reason: \"Manager verification deferred blocker resolution.\",\n url: bundle.url,\n title: bundle.title\n };\n }\n\n if (interpretation.humanBoundary !== \"none\" && interpretation.humanBoundary !== \"policy_blocked\") {\n return {\n status: \"yield_required\",\n blockerState: bundle.blockerState,\n blocker: bundle.blocker,\n challenge: bundle.challenge,\n bundle,\n changed,\n reason: `Human authority boundary detected: ${interpretation.humanBoundary}.`,\n url: bundle.url,\n title: bundle.title\n };\n }\n\n return {\n status: changed ? \"progress\" : \"still_blocked\",\n blockerState: bundle.blockerState,\n blocker: bundle.blocker,\n challenge: bundle.challenge,\n bundle,\n changed,\n reason: changed\n ? \"Verification observed a meaningful state change, but the blocker is still active.\"\n : \"Verification observed no meaningful progress.\",\n url: bundle.url,\n title: bundle.title\n };\n};\n","import type { ChallengeCapabilityMatrix, ChallengeEvidenceBundle, ChallengeInterpreterResult, ChallengePolicyGate } from \"./types\";\n\nexport const buildCapabilityMatrix = (\n bundle: ChallengeEvidenceBundle,\n interpretation: ChallengeInterpreterResult,\n gate: ChallengePolicyGate\n): ChallengeCapabilityMatrix => {\n const hasActionables = bundle.actionables.length > 0;\n const helperActionRefs = [\n ...bundle.continuity.loginRefs,\n ...bundle.continuity.sessionReuseRefs,\n ...bundle.continuity.humanVerificationRefs,\n ...bundle.continuity.checkpointRefs,\n ...(bundle.interaction?.clickRefs ?? []),\n ...(bundle.interaction?.holdRefs ?? []),\n ...(bundle.interaction?.dragRefs ?? [])\n ];\n const authLaneRelevant = interpretation.classification === \"auth_required\"\n || interpretation.classification === \"existing_session_reuse\"\n || bundle.continuity.likelyLoginPage\n || bundle.continuity.likelySessionPicker;\n const canNavigateToAuth = gate.allowedActions.includes(\"auth_navigation\")\n && authLaneRelevant\n && (bundle.continuity.loginRefs.length > 0 || typeof bundle.url === \"string\");\n const canReuseExistingSession = gate.allowedActions.includes(\"session_reuse\")\n && (\n bundle.continuity.hasPreservedSession\n || bundle.continuity.attachedSession\n || bundle.continuity.sessionReuseRefs.length > 0\n );\n const canReuseCookies = gate.allowedActions.includes(\"cookie_reuse\")\n && authLaneRelevant\n && (bundle.continuity.canReuseExistingCookies || bundle.continuity.canImportCookies);\n const canFillNonSecretFields = gate.allowedActions.includes(\"non_secret_form_fill\")\n && bundle.continuity.hasNonSecretTaskData\n && bundle.continuity.nonSecretFieldRefs.length > 0;\n const canExploreClicks = gate.allowedActions.includes(\"click_path\")\n && (\n hasActionables\n || bundle.continuity.loginRefs.length > 0\n || bundle.continuity.sessionReuseRefs.length > 0\n || bundle.continuity.checkpointRefs.length > 0\n );\n const mustYield = interpretation.humanBoundary === \"secret_entry\"\n || interpretation.humanBoundary === \"mfa\"\n || interpretation.humanBoundary === \"explicit_consent\"\n || interpretation.humanBoundary === \"exhausted_no_progress\";\n const mustDefer = interpretation.humanBoundary === \"policy_blocked\"\n || (!bundle.blocker && bundle.blockerState === \"clear\");\n let helperEligibility = gate.helperEligibility ?? (\n gate.optionalComputerUseBridge\n ? {\n allowed: true,\n reason: \"Optional helper bridge remains eligible after policy resolution.\"\n }\n : {\n allowed: false,\n reason: \"Optional computer-use bridge is disabled by policy.\",\n standDownReason: \"helper_disabled_by_policy\"\n }\n );\n if (helperEligibility.allowed && interpretation.humanBoundary !== \"none\") {\n helperEligibility = {\n allowed: false,\n reason: `Helper bridge is blocked by human boundary: ${interpretation.humanBoundary}.`,\n standDownReason: \"helper_blocked_by_human_boundary\"\n };\n } else if (helperEligibility.allowed && helperActionRefs.length === 0) {\n helperEligibility = {\n allowed: false,\n reason: \"Canonical evidence did not expose any safe browser-scoped helper actions.\",\n standDownReason: \"helper_no_safe_actions\"\n };\n }\n\n return {\n canNavigateToAuth,\n canReuseExistingSession,\n canReuseCookies,\n canFillNonSecretFields,\n canExploreClicks,\n canUseOwnedEnvironmentFixture: interpretation.classification === \"owned_environment_test_challenge\"\n && gate.governedLanes.includes(\"owned_environment_fixture\"),\n canUseSanctionedIdentity: gate.governedLanes.includes(\"sanctioned_identity\"),\n canUseServiceAdapter: gate.governedLanes.includes(\"service_adapter\"),\n canUseComputerUseBridge: helperEligibility.allowed,\n helperEligibility,\n mustYield,\n mustDefer\n };\n};\n","import type { ChallengeRuntimeHandle } from \"../browser/manager-types\";\nimport { buildChallengeEvidenceBundle } from \"./evidence-bundle\";\nimport type { ChallengeEvidenceBundle } from \"./types\";\n\ntype CaptureChallengeEvidenceArgs = {\n handle: ChallengeRuntimeHandle;\n sessionId: string;\n targetId?: string | null;\n canImportCookies: boolean;\n fallbackDisposition?: ChallengeEvidenceBundle[\"fallbackDisposition\"];\n registryPressure?: ChallengeEvidenceBundle[\"registryPressure\"];\n taskData?: ChallengeEvidenceBundle[\"taskData\"];\n};\n\nexport async function captureChallengeEvidence(\n args: CaptureChallengeEvidenceArgs\n): Promise<ChallengeEvidenceBundle> {\n const status = await args.handle.status(args.sessionId);\n const effectiveTargetId = args.targetId ?? status.activeTargetId ?? null;\n const snapshot = await args.handle.snapshot(\n args.sessionId,\n \"actionables\",\n 2400,\n undefined,\n effectiveTargetId\n );\n const debugTrace = await args.handle.debugTraceSnapshot(args.sessionId, { max: 50 });\n const cookies = status.url\n ? await args.handle.cookieList(args.sessionId, [status.url])\n : { count: 0 };\n\n return buildChallengeEvidenceBundle({\n status,\n snapshot: {\n snapshotId: snapshot.snapshotId,\n content: snapshot.content,\n warnings: snapshot.warnings\n },\n debugTrace,\n cookieCount: cookies.count,\n canImportCookies: args.canImportCookies,\n fallbackDisposition: args.fallbackDisposition,\n registryPressure: args.registryPressure,\n taskData: args.taskData\n });\n}\n","import type { ChallengeEvidenceBundle, ChallengeHumanBoundary, ChallengeInterpreterResult, HumanYieldPacket } from \"./types\";\n\nexport const shouldYieldToHuman = (args: {\n interpretation: ChallengeInterpreterResult;\n noProgressExhausted: boolean;\n}): { yield: boolean; reason: ChallengeHumanBoundary } => {\n if (args.noProgressExhausted) {\n return {\n yield: true,\n reason: \"exhausted_no_progress\"\n };\n }\n return {\n yield: args.interpretation.humanBoundary !== \"none\",\n reason: args.interpretation.humanBoundary\n };\n};\n\nexport const buildHumanYieldPacket = (args: {\n bundle: ChallengeEvidenceBundle;\n interpretation: ChallengeInterpreterResult;\n sessionId: string;\n targetId?: string | null;\n reason: ChallengeHumanBoundary;\n verification?: {\n status: \"clear\" | \"still_blocked\" | \"progress\" | \"yield_required\" | \"deferred\";\n reason: string;\n };\n}): HumanYieldPacket => {\n const challengeId = args.bundle.challengeId ?? `challenge-${Date.now()}`;\n const targetHints = [\n ...args.bundle.continuity.loginRefs,\n ...args.bundle.continuity.sessionReuseRefs,\n ...args.bundle.continuity.humanVerificationRefs,\n ...args.bundle.continuity.checkpointRefs\n ];\n return {\n challengeId,\n classification: args.interpretation.classification,\n reason: args.reason,\n sessionId: args.sessionId,\n targetId: args.targetId ?? args.bundle.activeTargetId,\n ownerSurface: args.bundle.challenge?.ownerSurface ?? args.bundle.ownerSurface,\n url: args.bundle.url,\n title: args.bundle.title,\n requiredHumanStep: args.reason === \"mfa\"\n ? \"Complete MFA or passkey verification, then continue.\"\n : args.reason === \"secret_entry\"\n ? \"Enter the required secret-bearing credentials, then continue.\"\n : args.reason === \"unsupported_third_party\"\n ? \"Complete the unsupported third-party challenge manually, then continue.\"\n : \"Review the page state and continue when ready.\",\n targetHints,\n expectedPostAuthCheckpoint: args.interpretation.likelyCheckpoint,\n preserveUntil: args.bundle.challenge?.preserveUntil,\n verifyUntil: args.bundle.challenge?.verifyUntil,\n traceRequestId: args.bundle.diagnostics.traceRequestId,\n ...(args.verification ? {\n lastVerificationStatus: args.verification.status,\n lastVerificationReason: args.verification.reason\n } : {}),\n evidenceSummary: args.interpretation.summary,\n reclaimHint: \"Resume the preserved session and re-run verification after the human step completes.\",\n resumeRule: \"Re-run manager-owned verification after the human step completes before resuming automation.\"\n };\n};\n","import type {\n ChallengeActionStep,\n ChallengeAutomationHelperEligibility,\n ChallengeEvidenceBundle,\n ComputerUseBridgeResult\n} from \"./types\";\n\nexport const OPTIONAL_BRIDGE_SUGGESTION_REASON = \"Optional bridge suggested a browser-scoped click follow-up from canonical evidence.\";\n\nexport const buildComputerUseSuggestions = (\n bundle: ChallengeEvidenceBundle,\n maxSuggestions: number\n): ChallengeActionStep[] => {\n const refs = [\n ...bundle.continuity.loginRefs,\n ...bundle.continuity.sessionReuseRefs,\n ...bundle.continuity.humanVerificationRefs,\n ...bundle.continuity.checkpointRefs\n ];\n return refs\n .slice(0, maxSuggestions)\n .map((ref) => ({\n kind: \"click\",\n ref,\n reason: OPTIONAL_BRIDGE_SUGGESTION_REASON\n }));\n};\n\nexport const suggestComputerUseActions = (args: {\n helperEligibility: ChallengeAutomationHelperEligibility;\n bundle: ChallengeEvidenceBundle;\n maxSuggestions: number;\n}): ComputerUseBridgeResult => {\n if (!args.helperEligibility.allowed) {\n return {\n status: \"disabled\",\n reason: args.helperEligibility.reason,\n suggestedSteps: [],\n standDownReason: args.helperEligibility.standDownReason\n };\n }\n\n const suggestedSteps = buildComputerUseSuggestions(args.bundle, args.maxSuggestions);\n if (suggestedSteps.length === 0) {\n return {\n status: \"unsupported\",\n reason: \"Canonical evidence did not expose any safe browser-scoped bridge actions.\",\n suggestedSteps: [],\n standDownReason: \"helper_no_safe_actions\"\n };\n }\n\n return {\n status: \"suggested\",\n reason: \"Bridge returned bounded browser-scoped suggestions from canonical evidence.\",\n suggestedSteps,\n auditMetadata: {\n suggestions: suggestedSteps.length,\n source: \"canonical_evidence\"\n }\n };\n};\n","import type { ProvidersChallengeOrchestrationConfig } from \"../config\";\nimport type {\n ChallengeAutomationHelperEligibility,\n ChallengeAutomationMode,\n ChallengeActionFamily,\n ChallengeHumanBoundary,\n ChallengeInterpreterResult,\n ChallengePolicyGate,\n ResolvedChallengeAutomationPolicy\n} from \"./types\";\n\nconst ALL_ACTIONS: ChallengeActionFamily[] = [\n \"wait\",\n \"auth_navigation\",\n \"session_reuse\",\n \"cookie_reuse\",\n \"element_discovery\",\n \"click_path\",\n \"click_and_hold\",\n \"non_secret_form_fill\",\n \"dropdown\",\n \"scroll\",\n \"hover\",\n \"press\",\n \"pointer\",\n \"drag\",\n \"verification\",\n \"debug_trace\"\n];\n\nconst DEFAULT_HANDOFF_TRIGGERS: ChallengeHumanBoundary[] = [\n \"secret_entry\",\n \"mfa\",\n \"explicit_consent\",\n \"policy_blocked\",\n \"unsupported_third_party\",\n \"exhausted_no_progress\"\n];\n\nconst buildResolvedPolicy = (\n mode: ChallengeAutomationMode,\n source: ResolvedChallengeAutomationPolicy[\"source\"]\n): ResolvedChallengeAutomationPolicy => {\n if (mode === \"off\") {\n return {\n mode,\n source,\n standDownReason: \"challenge_automation_off\"\n };\n }\n if (mode === \"browser\") {\n return {\n mode,\n source,\n standDownReason: \"helper_disabled_for_browser_mode\"\n };\n }\n return { mode, source };\n};\n\nexport const resolveChallengeAutomationPolicy = (args: {\n runMode?: ChallengeAutomationMode;\n sessionMode?: ChallengeAutomationMode;\n configMode: ChallengeAutomationMode;\n}): ResolvedChallengeAutomationPolicy => {\n if (args.runMode) {\n return buildResolvedPolicy(args.runMode, \"run\");\n }\n if (args.sessionMode) {\n return buildResolvedPolicy(args.sessionMode, \"session\");\n }\n return buildResolvedPolicy(args.configMode, \"config\");\n};\n\nconst resolveHelperEligibility = (\n config: ProvidersChallengeOrchestrationConfig,\n policy: ResolvedChallengeAutomationPolicy\n): ChallengeAutomationHelperEligibility => {\n if (policy.mode === \"off\") {\n return {\n allowed: false,\n reason: \"Challenge automation mode is off; detection and reporting remain active.\",\n standDownReason: \"challenge_automation_off\"\n };\n }\n if (policy.mode === \"browser\") {\n return {\n allowed: false,\n reason: \"Browser mode keeps the optional helper bridge disabled.\",\n standDownReason: \"helper_disabled_for_browser_mode\"\n };\n }\n if (!config.optionalComputerUseBridge.enabled) {\n return {\n allowed: false,\n reason: \"Optional computer-use bridge is disabled by policy.\",\n standDownReason: \"helper_disabled_by_policy\"\n };\n }\n return {\n allowed: true,\n reason: \"Optional helper bridge remains eligible after mode resolution.\"\n };\n};\n\nexport const buildChallengePolicyGate = (\n config: ProvidersChallengeOrchestrationConfig,\n interpretation: ChallengeInterpreterResult,\n resolvedPolicy = resolveChallengeAutomationPolicy({\n configMode: config.mode\n })\n): ChallengePolicyGate => {\n const helperEligibility = resolveHelperEligibility(config, resolvedPolicy);\n if (resolvedPolicy.mode === \"off\") {\n return {\n resolvedPolicy,\n allowedActions: [],\n forbiddenActions: [...ALL_ACTIONS],\n handoffTriggers: [...DEFAULT_HANDOFF_TRIGGERS],\n governedLanes: [],\n optionalComputerUseBridge: false,\n helperEligibility\n };\n }\n\n const allowed = new Set<ChallengeActionFamily>([\"wait\", \"verification\", \"debug_trace\"]);\n if (config.allowAuthNavigation) {\n allowed.add(\"auth_navigation\");\n }\n if (config.allowSessionReuse) {\n allowed.add(\"session_reuse\");\n }\n if (config.allowCookieReuse) {\n allowed.add(\"cookie_reuse\");\n }\n if (config.allowNonSecretFormFill) {\n allowed.add(\"non_secret_form_fill\");\n allowed.add(\"dropdown\");\n }\n if (config.allowInteractionExploration) {\n allowed.add(\"element_discovery\");\n allowed.add(\"click_path\");\n allowed.add(\"click_and_hold\");\n allowed.add(\"scroll\");\n allowed.add(\"hover\");\n allowed.add(\"press\");\n allowed.add(\"pointer\");\n allowed.add(\"drag\");\n }\n\n if (interpretation.humanBoundary === \"secret_entry\" || interpretation.humanBoundary === \"mfa\") {\n allowed.delete(\"non_secret_form_fill\");\n }\n\n const governedLanes: ChallengePolicyGate[\"governedLanes\"] = [];\n if (config.governed.allowOwnedEnvironmentFixtures) {\n governedLanes.push(\"owned_environment_fixture\");\n }\n if (config.governed.allowSanctionedIdentity) {\n governedLanes.push(\"sanctioned_identity\");\n }\n if (config.governed.allowServiceAdapters) {\n governedLanes.push(\"service_adapter\");\n }\n\n return {\n resolvedPolicy,\n allowedActions: ALL_ACTIONS.filter((action) => allowed.has(action)),\n forbiddenActions: ALL_ACTIONS.filter((action) => !allowed.has(action)),\n handoffTriggers: [...DEFAULT_HANDOFF_TRIGGERS],\n governedLanes,\n optionalComputerUseBridge: helperEligibility.allowed,\n helperEligibility\n };\n};\n","import type { ProvidersChallengeOrchestrationConfig } from \"../config\";\nimport type {\n ChallengeCapabilityMatrix,\n ChallengeEvidenceBundle,\n ChallengeInterpreterResult,\n ChallengePolicyGate,\n ChallengeStrategyDecision,\n ChallengeStrategyLane\n} from \"./types\";\n\nconst buildDecision = (\n config: ProvidersChallengeOrchestrationConfig,\n lane: ChallengeStrategyLane,\n rationale: string,\n allowedActionFamilies: ChallengePolicyGate[\"allowedActions\"],\n verificationLevel: ChallengeInterpreterResult[\"requiredVerification\"],\n stopConditions: string[],\n governedLane?: ChallengeStrategyDecision[\"governedLane\"]\n): ChallengeStrategyDecision => ({\n lane,\n ...(governedLane ? { governedLane } : {}),\n rationale,\n attemptBudget: config.attemptBudget,\n noProgressLimit: config.noProgressLimit,\n verificationLevel,\n stopConditions,\n allowedActionFamilies: [...allowedActionFamilies]\n});\n\nexport const selectChallengeStrategy = (args: {\n config: ProvidersChallengeOrchestrationConfig;\n bundle: ChallengeEvidenceBundle;\n interpretation: ChallengeInterpreterResult;\n capabilityMatrix: ChallengeCapabilityMatrix;\n gate: ChallengePolicyGate;\n}): ChallengeStrategyDecision => {\n const { config, bundle, capabilityMatrix, gate, interpretation } = args;\n const registryCooldownActive = (bundle.registryPressure?.cooldownUntilMs ?? 0) > Date.now();\n const registryPressureElevated = (bundle.registryPressure?.activeChallenges ?? 0) > 0\n || (bundle.registryPressure?.recentChallengeRatio ?? 0) >= 0.5\n || (bundle.registryPressure?.recentRateLimitRatio ?? 0) >= 0.5;\n const stopConditions = [\n \"manager_verification_clears_blocker\",\n \"policy_gate_denies_next_action\",\n \"human_boundary_detected\",\n \"no_progress_budget_exhausted\"\n ];\n const { mode, standDownReason } = gate.resolvedPolicy;\n\n if (mode === \"off\") {\n return buildDecision(\n config,\n \"defer\",\n \"Challenge automation mode is off; challenge handling is detect-and-report only.\",\n [],\n \"light\",\n [standDownReason ?? \"challenge_automation_off\"]\n );\n }\n\n if (capabilityMatrix.mustDefer) {\n return buildDecision(\n config,\n \"defer\",\n \"Current policy or blocker state requires deferral before further automation.\",\n gate.allowedActions,\n interpretation.requiredVerification,\n [\"policy_blocked_or_clear_state\"]\n );\n }\n\n if (\n registryCooldownActive\n && !capabilityMatrix.canReuseExistingSession\n && !capabilityMatrix.canReuseCookies\n && !capabilityMatrix.canNavigateToAuth\n ) {\n return buildDecision(\n config,\n \"defer\",\n \"Registry cooldown is still active and no legitimate continuity or auth-navigation lane is currently available.\",\n gate.allowedActions,\n interpretation.requiredVerification,\n [\"registry_cooldown_active\"]\n );\n }\n\n if (capabilityMatrix.canUseOwnedEnvironmentFixture) {\n return buildDecision(\n config,\n \"owned_environment_fixture\",\n \"Owned-environment fixture detected and explicitly allowlisted.\",\n gate.allowedActions,\n interpretation.requiredVerification,\n stopConditions,\n \"owned_environment_fixture\"\n );\n }\n\n if (capabilityMatrix.mustYield) {\n return buildDecision(\n config,\n \"human_yield\",\n `Human authority boundary reached: ${interpretation.humanBoundary}.`,\n gate.allowedActions,\n interpretation.requiredVerification,\n [...stopConditions, \"human_authority_required\"]\n );\n }\n\n if (\n capabilityMatrix.canNavigateToAuth\n || capabilityMatrix.canReuseExistingSession\n || capabilityMatrix.canReuseCookies\n || capabilityMatrix.canFillNonSecretFields\n || capabilityMatrix.canExploreClicks\n ) {\n return buildDecision(\n config,\n \"generic_browser_autonomy\",\n registryPressureElevated\n ? \"Registry pressure is elevated, but legitimate browser continuity remains available for one bounded generic autonomy pass.\"\n : \"Existing browser controls can attempt bounded auth navigation, session reuse, non-secret fill, or interaction exploration.\",\n gate.allowedActions,\n interpretation.requiredVerification,\n registryPressureElevated\n ? [...stopConditions, \"registry_pressure_elevated\"]\n : stopConditions\n );\n }\n\n if (capabilityMatrix.canUseComputerUseBridge) {\n return buildDecision(\n config,\n \"optional_computer_use_bridge\",\n \"DOM-native autonomy is exhausted, but the optional browser-scoped bridge is enabled.\",\n gate.allowedActions,\n interpretation.requiredVerification,\n stopConditions\n );\n }\n\n if (capabilityMatrix.canUseSanctionedIdentity) {\n return buildDecision(\n config,\n \"sanctioned_identity\",\n \"Sanctioned identity lane is enabled and generic browser autonomy is insufficient.\",\n gate.allowedActions,\n interpretation.requiredVerification,\n stopConditions,\n \"sanctioned_identity\"\n );\n }\n\n if (capabilityMatrix.canUseServiceAdapter) {\n return buildDecision(\n config,\n \"service_adapter\",\n \"Governed service-adapter lane is enabled as the last non-human option.\",\n gate.allowedActions,\n interpretation.requiredVerification,\n stopConditions,\n \"service_adapter\"\n );\n }\n\n return buildDecision(\n config,\n \"human_yield\",\n `No legitimate autonomous lane remains after applying policy and continuity checks. ${capabilityMatrix.helperEligibility.reason}`,\n gate.allowedActions,\n interpretation.requiredVerification,\n [...stopConditions, \"no_legitimate_lane_remaining\"]\n );\n};\n","import type { ChallengeRuntimeHandle } from \"../browser/manager-types\";\nimport type { ProvidersChallengeOrchestrationConfig } from \"../config\";\nimport { buildCapabilityMatrix } from \"./capability-matrix\";\nimport { captureChallengeEvidence } from \"./capture\";\nimport { shouldYieldToHuman } from \"./human-yield-gate\";\nimport { interpretChallengeEvidence } from \"./interpreter\";\nimport { suggestComputerUseActions } from \"./optional-computer-use-bridge\";\nimport { buildChallengePolicyGate, resolveChallengeAutomationPolicy } from \"./policy-gate\";\nimport { selectChallengeStrategy } from \"./strategy-selector\";\nimport type {\n ChallengeActionStep,\n ChallengeActionable,\n ChallengeAutomationHelperEligibility,\n ChallengeAutomationMode,\n ChallengeEvidenceBundle,\n ChallengeInspectPlan,\n ChallengeStrategyDecision,\n ComputerUseBridgeResult\n} from \"./types\";\n\nconst SENSITIVE_FIELD_RE = /\\b(password|passcode|secret|otp|mfa|token|verification code|passkey)\\b/i;\n\nconst hasExecuted = (\n steps: ChallengeActionStep[],\n kind: ChallengeActionStep[\"kind\"],\n ref?: string,\n url?: string\n): boolean => {\n return steps.some((step) => step.kind === kind && step.ref === ref && step.url === url);\n};\n\nconst getActionable = (\n bundle: ChallengeEvidenceBundle,\n ref: string\n): ChallengeActionable | undefined => {\n return bundle.actionables.find((entry) => entry.ref === ref);\n};\n\nconst deriveAuthUrls = (url: string | undefined): string[] => {\n if (!url) {\n return [];\n }\n try {\n const current = new URL(url);\n const candidates = [\n \"/login\",\n \"/signin\",\n \"/sign-in\",\n \"/account/login\",\n \"/session\",\n \"/auth/login\"\n ];\n return candidates.map((path) => new URL(path, current.origin).toString());\n } catch {\n return [];\n }\n};\n\nconst resolveTaskValue = (\n bundle: ChallengeEvidenceBundle,\n ref: string\n): string | undefined => {\n const actionable = getActionable(bundle, ref);\n const name = actionable?.name?.toLowerCase();\n if (!name || !bundle.taskData) {\n return undefined;\n }\n for (const [key, value] of Object.entries(bundle.taskData)) {\n if (SENSITIVE_FIELD_RE.test(key) || SENSITIVE_FIELD_RE.test(name)) {\n continue;\n }\n if (!name.includes(key.toLowerCase())) {\n continue;\n }\n if (\n typeof value === \"string\"\n || typeof value === \"number\"\n || typeof value === \"boolean\"\n ) {\n return String(value);\n }\n }\n return undefined;\n};\n\nconst nextUnusedRef = (\n refs: string[],\n steps: ChallengeActionStep[],\n kind: \"click\" | \"click_and_hold\" | \"hover\" | \"type\"\n): string | undefined => {\n return refs.find((ref) => !hasExecuted(steps, kind, ref));\n};\n\nconst planInteractionStep = (\n bundle: ChallengeEvidenceBundle,\n decision: ChallengeStrategyDecision,\n executedSteps: ChallengeActionStep[]\n): ChallengeActionStep | undefined => {\n const interaction = bundle.interaction;\n if (!interaction || interaction.preferredAction === \"unknown\") {\n return undefined;\n }\n if (interaction.preferredAction === \"click\" && decision.allowedActionFamilies.includes(\"click_path\")) {\n const clickRef = nextUnusedRef(interaction.clickRefs, executedSteps, \"click\");\n if (clickRef) {\n return {\n kind: \"click\",\n ref: clickRef,\n reason: \"Visible popup or interstitial exposes a bounded click path.\"\n };\n }\n }\n if (\n interaction.preferredAction === \"click_and_hold\"\n && decision.allowedActionFamilies.includes(\"click_and_hold\")\n ) {\n const holdRef = nextUnusedRef(interaction.holdRefs, executedSteps, \"click_and_hold\");\n if (holdRef || !hasExecuted(executedSteps, \"click_and_hold\")) {\n return {\n kind: \"click_and_hold\",\n ...(holdRef ? { ref: holdRef } : {}),\n ...(typeof interaction.holdMs === \"number\" ? { holdMs: interaction.holdMs } : {}),\n reason: \"Visible challenge requests a bounded click-and-hold gesture.\"\n };\n }\n }\n if (\n interaction.preferredAction === \"drag\"\n && decision.allowedActionFamilies.includes(\"drag\")\n && !hasExecuted(executedSteps, \"drag\")\n ) {\n return {\n kind: \"drag\",\n ...(interaction.dragRefs[0] ? { ref: interaction.dragRefs[0] } : {}),\n coordinates: { x: 640, y: 360 },\n reason: \"Visible challenge requests a bounded drag gesture.\"\n };\n }\n return undefined;\n};\n\nconst planGenericStep = (\n bundle: ChallengeEvidenceBundle,\n decision: ChallengeStrategyDecision,\n executedSteps: ChallengeActionStep[]\n): ChallengeActionStep | undefined => {\n const sessionRef = nextUnusedRef(\n bundle.continuity.sessionReuseRefs,\n executedSteps,\n \"click\"\n );\n if (sessionRef) {\n return {\n kind: \"click\",\n ref: sessionRef,\n reason: \"Try the existing-session or account-selection path first.\"\n };\n }\n\n const loginRef = nextUnusedRef(bundle.continuity.loginRefs, executedSteps, \"click\");\n if (decision.allowedActionFamilies.includes(\"auth_navigation\") && loginRef) {\n return {\n kind: \"click\",\n ref: loginRef,\n reason: \"Try the visible auth-navigation entrypoint.\"\n };\n }\n\n if (decision.allowedActionFamilies.includes(\"auth_navigation\")) {\n const loginUrl = deriveAuthUrls(bundle.url).find((candidate) => {\n return !hasExecuted(executedSteps, \"goto\", undefined, candidate);\n });\n if (loginUrl) {\n return {\n kind: \"goto\",\n url: loginUrl,\n reason: \"Try a conventional auth-navigation URL on the current origin.\"\n };\n }\n }\n\n const fieldRef = nextUnusedRef(\n bundle.continuity.nonSecretFieldRefs,\n executedSteps,\n \"type\"\n );\n const fieldValue = fieldRef ? resolveTaskValue(bundle, fieldRef) : undefined;\n if (\n decision.allowedActionFamilies.includes(\"non_secret_form_fill\")\n && fieldRef\n && fieldValue\n ) {\n return {\n kind: \"type\",\n ref: fieldRef,\n text: fieldValue,\n reason: \"Fill a non-secret field from caller-provided task data.\"\n };\n }\n\n const checkpointRef = nextUnusedRef(\n bundle.continuity.checkpointRefs,\n executedSteps,\n \"click\"\n );\n if (decision.allowedActionFamilies.includes(\"click_path\") && checkpointRef) {\n return {\n kind: \"click\",\n ref: checkpointRef,\n reason: \"Try the next visible checkpoint or continue action.\"\n };\n }\n\n const hoverRef = nextUnusedRef(\n [...bundle.continuity.loginRefs, ...bundle.continuity.checkpointRefs],\n executedSteps,\n \"hover\"\n );\n if (decision.allowedActionFamilies.includes(\"hover\") && hoverRef) {\n return {\n kind: \"hover\",\n ref: hoverRef,\n reason: \"Hover a likely action target to reveal hidden menus or session pickers.\"\n };\n }\n\n if (decision.allowedActionFamilies.includes(\"scroll\") && !hasExecuted(executedSteps, \"scroll\")) {\n return {\n kind: \"scroll\",\n dy: 900,\n reason: \"Scroll down to uncover the next actionable region.\"\n };\n }\n\n if (\n decision.allowedActionFamilies.includes(\"scroll\")\n && executedSteps.filter((step) => step.kind === \"scroll\").length === 1\n ) {\n return {\n kind: \"scroll\",\n dy: -450,\n reason: \"Scroll back up to re-evaluate the visible challenge state.\"\n };\n }\n\n if (decision.allowedActionFamilies.includes(\"press\") && !hasExecuted(executedSteps, \"press\")) {\n return {\n kind: \"press\",\n text: \"Tab\",\n reason: \"Advance focus through the challenge surface.\"\n };\n }\n\n if (decision.allowedActionFamilies.includes(\"pointer\") && !hasExecuted(executedSteps, \"pointer\")) {\n return {\n kind: \"pointer\",\n coordinates: { x: 640, y: 360 },\n reason: \"Move the pointer through the center of the current browser surface.\"\n };\n }\n\n if (decision.allowedActionFamilies.includes(\"drag\") && !hasExecuted(executedSteps, \"drag\")) {\n return {\n kind: \"drag\",\n coordinates: { x: 640, y: 360 },\n reason: \"Attempt one bounded vertical drag across the visible surface.\"\n };\n }\n\n if (!hasExecuted(executedSteps, \"wait\")) {\n return {\n kind: \"wait\",\n reason: \"Give the page a short bounded settle window before yielding.\"\n };\n }\n\n return undefined;\n};\n\nconst pendingSteps = (\n steps: ChallengeActionStep[] | undefined,\n executedSteps: ChallengeActionStep[]\n): ChallengeActionStep[] => {\n return (steps ?? []).filter((step) => {\n return !hasExecuted(executedSteps, step.kind, step.ref, step.url);\n });\n};\n\nconst dedupeSteps = (steps: ChallengeActionStep[]): ChallengeActionStep[] => {\n const seen = new Set<string>();\n return steps.filter((step) => {\n const key = JSON.stringify([\n step.kind,\n step.ref ?? null,\n step.url ?? null,\n step.text ?? null,\n step.reason\n ]);\n if (seen.has(key)) {\n return false;\n }\n seen.add(key);\n return true;\n });\n};\n\nexport const buildChallengeActionSuggestions = (args: {\n bundle: ChallengeEvidenceBundle;\n decision: ChallengeStrategyDecision;\n helperEligibility: ChallengeAutomationHelperEligibility;\n config: ProvidersChallengeOrchestrationConfig;\n preferredSteps?: ChallengeActionStep[];\n executedSteps?: ChallengeActionStep[];\n}): {\n helper: ComputerUseBridgeResult;\n suggestedSteps: ChallengeActionStep[];\n} => {\n const executedSteps = args.executedSteps ?? [];\n const helper = suggestComputerUseActions({\n helperEligibility: args.helperEligibility,\n bundle: args.bundle,\n maxSuggestions: args.config.optionalComputerUseBridge.maxSuggestions\n });\n const preferredSteps = pendingSteps(args.preferredSteps, executedSteps);\n const interactionStep = planInteractionStep(args.bundle, args.decision, executedSteps);\n const genericStep = planGenericStep(args.bundle, args.decision, executedSteps);\n const helperSteps = pendingSteps(helper.suggestedSteps, executedSteps);\n\n const suggestedSteps = args.decision.lane === \"optional_computer_use_bridge\"\n ? dedupeSteps([...preferredSteps, ...helperSteps])\n : dedupeSteps([\n ...preferredSteps,\n ...(interactionStep ? [interactionStep] : []),\n ...(genericStep ? [genericStep] : []),\n ...helperSteps\n ]);\n\n return {\n helper,\n suggestedSteps\n };\n};\n\nexport const selectChallengeActionStep = (args: {\n bundle: ChallengeEvidenceBundle;\n decision: ChallengeStrategyDecision;\n helperEligibility: ChallengeAutomationHelperEligibility;\n config: ProvidersChallengeOrchestrationConfig;\n preferredSteps?: ChallengeActionStep[];\n executedSteps?: ChallengeActionStep[];\n}): ChallengeActionStep | undefined => {\n return buildChallengeActionSuggestions(args).suggestedSteps[0];\n};\n\nexport function buildChallengeInspectPlan(args: {\n bundle: ChallengeEvidenceBundle;\n config: ProvidersChallengeOrchestrationConfig;\n runMode?: ChallengeAutomationMode;\n sessionMode?: ChallengeAutomationMode;\n preferredSteps?: ChallengeActionStep[];\n executedSteps?: ChallengeActionStep[];\n}): ChallengeInspectPlan {\n const interpretation = interpretChallengeEvidence(args.bundle);\n const policy = resolveChallengeAutomationPolicy({\n runMode: args.runMode,\n sessionMode: args.sessionMode,\n configMode: args.config.mode\n });\n const gate = buildChallengePolicyGate(args.config, interpretation, policy);\n const capabilityMatrix = buildCapabilityMatrix(args.bundle, interpretation, gate);\n const decision = selectChallengeStrategy({\n config: args.config,\n bundle: args.bundle,\n interpretation,\n capabilityMatrix,\n gate\n });\n const actionSuggestions = buildChallengeActionSuggestions({\n bundle: args.bundle,\n decision,\n helperEligibility: capabilityMatrix.helperEligibility,\n config: args.config,\n preferredSteps: args.preferredSteps,\n executedSteps: args.executedSteps\n });\n const yieldDecision = shouldYieldToHuman({\n interpretation,\n noProgressExhausted: false\n });\n const standDownReason = capabilityMatrix.helperEligibility.standDownReason\n ?? gate.resolvedPolicy.standDownReason\n ?? actionSuggestions.helper.standDownReason;\n\n return {\n challengeId: args.bundle.challengeId,\n ...(args.bundle.mode ? { sessionMode: args.bundle.mode } : {}),\n classification: interpretation.classification,\n authState: interpretation.authState,\n summary: interpretation.summary,\n mode: gate.resolvedPolicy.mode,\n source: gate.resolvedPolicy.source,\n helperEligibility: capabilityMatrix.helperEligibility,\n ...(standDownReason ? { standDownReason } : {}),\n yield: {\n required: yieldDecision.yield,\n reason: yieldDecision.reason\n },\n decision,\n allowedActionFamilies: gate.allowedActions,\n forbiddenActionFamilies: gate.forbiddenActions,\n governedLanes: gate.governedLanes,\n capabilityMatrix,\n helper: actionSuggestions.helper,\n suggestedSteps: actionSuggestions.suggestedSteps,\n evidence: {\n blockerState: args.bundle.blockerState,\n ...(args.bundle.blocker?.type ? { blockerType: args.bundle.blocker.type } : {}),\n ...(args.bundle.url ? { url: args.bundle.url } : {}),\n ...(args.bundle.title ? { title: args.bundle.title } : {}),\n ...(typeof args.bundle.activeTargetId !== \"undefined\"\n ? { activeTargetId: args.bundle.activeTargetId }\n : {}),\n ...(args.bundle.snapshotId ? { snapshotId: args.bundle.snapshotId } : {}),\n loginRefs: args.bundle.continuity.loginRefs,\n sessionReuseRefs: args.bundle.continuity.sessionReuseRefs,\n humanVerificationRefs: args.bundle.continuity.humanVerificationRefs,\n checkpointRefs: args.bundle.continuity.checkpointRefs\n }\n };\n}\n\nexport async function inspectChallengePlanFromRuntime(args: {\n handle: ChallengeRuntimeHandle;\n sessionId: string;\n targetId?: string | null;\n config: ProvidersChallengeOrchestrationConfig;\n runMode?: ChallengeAutomationMode;\n sessionMode?: ChallengeAutomationMode;\n canImportCookies?: boolean;\n}): Promise<ChallengeInspectPlan> {\n const bundle = await captureChallengeEvidence({\n handle: args.handle,\n sessionId: args.sessionId,\n targetId: args.targetId,\n canImportCookies: args.canImportCookies ?? true\n });\n return buildChallengeInspectPlan({\n bundle,\n config: args.config,\n runMode: args.runMode,\n sessionMode: args.sessionMode\n });\n}\n","import type { ChallengeRuntimeHandle } from \"../browser/manager-types\";\nimport { verifyChallengeProgress } from \"./verification-gate\";\nimport type { ProvidersChallengeOrchestrationConfig } from \"../config\";\nimport { selectChallengeActionStep } from \"./inspect-plan\";\nimport type {\n ChallengeActionResult,\n ChallengeActionStep,\n ChallengeAutomationHelperEligibility,\n ChallengeEvidenceBundle,\n ChallengeStrategyDecision\n} from \"./types\";\n\nconst DEFAULT_HOLD_MS = 1500;\n\nconst resolveStepPoint = async (args: {\n handle: ChallengeRuntimeHandle;\n sessionId: string;\n step: ChallengeActionStep;\n targetId?: string | null;\n fallback: { x: number; y: number };\n}): Promise<{ x: number; y: number }> => {\n if (!args.step.ref) {\n return args.step.coordinates ?? args.fallback;\n }\n return await args.handle.resolveRefPoint(args.sessionId, args.step.ref, args.targetId);\n};\n\nconst executeStep = async (args: {\n handle: ChallengeRuntimeHandle;\n sessionId: string;\n targetId?: string | null;\n step: ChallengeActionStep;\n config: ProvidersChallengeOrchestrationConfig;\n}): Promise<void> => {\n const timeoutMs = args.config.stepTimeoutMs;\n switch (args.step.kind) {\n case \"goto\":\n if (args.step.url) {\n await args.handle.goto(args.sessionId, args.step.url, \"domcontentloaded\", timeoutMs, undefined, args.targetId);\n }\n return;\n case \"click\":\n if (args.step.ref) {\n await args.handle.click(args.sessionId, args.step.ref, args.targetId);\n }\n return;\n case \"click_and_hold\": {\n const point = await resolveStepPoint({\n handle: args.handle,\n sessionId: args.sessionId,\n step: args.step,\n targetId: args.targetId,\n fallback: { x: 640, y: 360 }\n });\n await args.handle.pointerMove(args.sessionId, point.x, point.y, args.targetId, 12);\n await args.handle.pointerDown(args.sessionId, point.x, point.y, args.targetId, \"left\", 1);\n await new Promise((resolve) => setTimeout(resolve, Math.max(250, args.step.holdMs ?? DEFAULT_HOLD_MS)));\n await args.handle.pointerUp(args.sessionId, point.x, point.y, args.targetId, \"left\", 1);\n return;\n }\n case \"hover\":\n if (args.step.ref) {\n await args.handle.hover(args.sessionId, args.step.ref, args.targetId);\n }\n return;\n case \"press\":\n await args.handle.press(args.sessionId, args.step.text ?? \"Tab\", undefined, args.targetId);\n return;\n case \"type\":\n if (args.step.ref && typeof args.step.text === \"string\") {\n await args.handle.type(args.sessionId, args.step.ref, args.step.text, true, false, args.targetId);\n }\n return;\n case \"select\":\n if (args.step.ref && args.step.values?.length) {\n await args.handle.select(args.sessionId, args.step.ref, args.step.values, args.targetId);\n }\n return;\n case \"scroll\":\n await args.handle.scroll(args.sessionId, args.step.dy ?? 600, undefined, args.targetId);\n return;\n case \"pointer\":\n await args.handle.pointerMove(\n args.sessionId,\n args.step.coordinates?.x ?? 640,\n args.step.coordinates?.y ?? 360,\n args.targetId,\n 12\n );\n return;\n case \"drag\":\n {\n const point = await resolveStepPoint({\n handle: args.handle,\n sessionId: args.sessionId,\n step: args.step,\n targetId: args.targetId,\n fallback: args.step.coordinates ?? { x: 640, y: 360 }\n });\n await args.handle.drag(\n args.sessionId,\n point,\n {\n x: point.x,\n y: point.y + 260\n },\n args.targetId,\n 16\n );\n }\n return;\n case \"cookie_list\":\n await args.handle.cookieList(args.sessionId, args.step.url ? [args.step.url] : undefined);\n return;\n case \"cookie_import\":\n await args.handle.cookieImport(args.sessionId, args.step.cookies ?? [], true);\n return;\n case \"snapshot\":\n await args.handle.snapshot(\n args.sessionId,\n \"actionables\",\n args.step.snapshotChars ?? 2400,\n undefined,\n args.targetId\n );\n return;\n case \"debug_trace\":\n await args.handle.debugTraceSnapshot(args.sessionId, { max: args.step.traceMax ?? 50 });\n return;\n case \"wait\":\n await args.handle.waitForLoad(args.sessionId, \"networkidle\", Math.min(timeoutMs, 3000), args.targetId);\n return;\n default:\n return;\n }\n};\n\nexport const runChallengeActionLoop = async (args: {\n handle: ChallengeRuntimeHandle;\n sessionId: string;\n targetId?: string | null;\n initialBundle: ChallengeEvidenceBundle;\n decision: ChallengeStrategyDecision;\n helperEligibility: ChallengeAutomationHelperEligibility;\n config: ProvidersChallengeOrchestrationConfig;\n suggestedSteps?: ChallengeActionStep[];\n}): Promise<ChallengeActionResult> => {\n let currentBundle = args.initialBundle;\n let currentTargetId = args.targetId ?? args.initialBundle.activeTargetId ?? null;\n const executedSteps: ChallengeActionStep[] = [];\n let noProgressCount = 0;\n let reusedExistingSession = false;\n let reusedCookies = false;\n\n for (let attempt = 1; attempt <= args.decision.attemptBudget; attempt += 1) {\n const step = selectChallengeActionStep({\n bundle: currentBundle,\n decision: args.decision,\n helperEligibility: args.helperEligibility,\n config: args.config,\n preferredSteps: args.suggestedSteps,\n executedSteps\n });\n\n if (!step) {\n return {\n status: \"no_progress\",\n attempts: attempt - 1,\n noProgressCount,\n executedSteps,\n verification: {\n status: \"still_blocked\",\n blockerState: currentBundle.blockerState,\n blocker: currentBundle.blocker,\n challenge: currentBundle.challenge,\n bundle: currentBundle,\n changed: false,\n reason: \"No additional safe browser action remained.\",\n url: currentBundle.url,\n title: currentBundle.title\n },\n reusedExistingSession,\n reusedCookies\n };\n }\n\n try {\n await executeStep({\n handle: args.handle,\n sessionId: args.sessionId,\n targetId: currentTargetId,\n step,\n config: args.config\n });\n } catch {\n // Verification below decides whether the failed step changed anything meaningful.\n }\n\n executedSteps.push(step);\n if (step.ref && currentBundle.continuity.sessionReuseRefs.includes(step.ref)) {\n reusedExistingSession = true;\n }\n if (step.kind === \"goto\" && currentBundle.continuity.canReuseExistingCookies) {\n reusedCookies = true;\n }\n\n const verification = await verifyChallengeProgress({\n handle: args.handle,\n sessionId: args.sessionId,\n targetId: currentTargetId,\n previous: currentBundle,\n canImportCookies: currentBundle.continuity.canImportCookies,\n fallbackDisposition: currentBundle.fallbackDisposition,\n registryPressure: currentBundle.registryPressure,\n taskData: currentBundle.taskData\n });\n currentBundle = verification.bundle ?? currentBundle;\n currentTargetId = verification.bundle?.activeTargetId ?? currentTargetId;\n\n if (verification.status === \"clear\") {\n return {\n status: \"resolved\",\n attempts: attempt,\n noProgressCount,\n executedSteps,\n verification,\n reusedExistingSession,\n reusedCookies\n };\n }\n\n if (verification.status === \"yield_required\") {\n return {\n status: \"yield_required\",\n attempts: attempt,\n noProgressCount,\n executedSteps,\n verification,\n reusedExistingSession,\n reusedCookies\n };\n }\n\n if (verification.status === \"deferred\") {\n return {\n status: \"deferred\",\n attempts: attempt,\n noProgressCount,\n executedSteps,\n verification,\n reusedExistingSession,\n reusedCookies\n };\n }\n\n if (verification.changed) {\n noProgressCount = 0;\n continue;\n }\n\n noProgressCount += 1;\n if (noProgressCount >= args.decision.noProgressLimit) {\n return {\n status: \"no_progress\",\n attempts: attempt,\n noProgressCount,\n executedSteps,\n verification,\n reusedExistingSession,\n reusedCookies\n };\n }\n }\n\n return {\n status: \"still_blocked\",\n attempts: args.decision.attemptBudget,\n noProgressCount,\n executedSteps,\n verification: {\n status: \"still_blocked\",\n blockerState: currentBundle.blockerState,\n blocker: currentBundle.blocker,\n challenge: currentBundle.challenge,\n bundle: currentBundle,\n changed: false,\n reason: \"Attempt budget exhausted without clearing the blocker.\",\n url: currentBundle.url,\n title: currentBundle.title\n },\n reusedExistingSession,\n reusedCookies\n };\n};\n","import type { GovernedLaneRequest, GovernedLaneResult } from \"./types\";\n\nconst APPROVED_FIXTURE_RE = /\\b(turnstile-checkbox|recaptcha-v2-checkbox|1x00000000000000000000AA|6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI)\\b/i;\n\nexport const runOwnedEnvironmentLane = (request: GovernedLaneRequest): GovernedLaneResult => {\n const haystack = [request.bundle.url, request.bundle.title, request.bundle.snapshotText]\n .filter((value): value is string => typeof value === \"string\" && value.length > 0)\n .join(\" \");\n const approved = APPROVED_FIXTURE_RE.test(haystack);\n return {\n status: approved ? \"executed\" : \"blocked\",\n lane: \"owned_environment_fixture\",\n reason: approved\n ? \"Approved owned-environment fixture detected.\"\n : \"Owned-environment lane requires an approved vendor test fixture.\",\n auditMetadata: {\n approvedFixture: approved\n }\n };\n};\n","import type { GovernedLaneRequest, GovernedLaneResult } from \"./types\";\n\nexport const runSanctionedIdentityLane = (request: GovernedLaneRequest): GovernedLaneResult => {\n const entitlement = request.auditContext?.identityEntitlement;\n const approved = typeof entitlement === \"string\" && entitlement.trim().length > 0;\n return {\n status: approved ? \"executed\" : \"blocked\",\n lane: \"sanctioned_identity\",\n reason: approved\n ? \"Sanctioned identity lane approved by explicit entitlement.\"\n : \"Sanctioned identity lane requires explicit entitlement metadata.\",\n auditMetadata: {\n approved,\n ...(approved ? { entitlement } : {})\n }\n };\n};\n","import type { GovernedLaneRequest, GovernedLaneResult } from \"./types\";\n\nexport const runServiceAdapterLane = (request: GovernedLaneRequest): GovernedLaneResult => {\n const adapter = request.auditContext?.adapterId;\n const approved = typeof adapter === \"string\" && adapter.trim().length > 0;\n return {\n status: approved ? \"executed\" : \"blocked\",\n lane: \"service_adapter\",\n reason: approved\n ? \"Governed service adapter approved by explicit adapter metadata.\"\n : \"Service-adapter lane requires an explicit adapter identifier and entitlement.\",\n auditMetadata: {\n approved,\n ...(approved ? { adapterId: adapter } : {})\n }\n };\n};\n","import type { ProvidersChallengeOrchestrationConfig } from \"../config\";\nimport { runOwnedEnvironmentLane } from \"./owned-environment-lane\";\nimport { runSanctionedIdentityLane } from \"./sanctioned-identity-lane\";\nimport { runServiceAdapterLane } from \"./service-adapter-lane\";\nimport type { GovernedLaneRequest, GovernedLaneResult } from \"./types\";\n\nexport const evaluateGovernedLane = (\n config: ProvidersChallengeOrchestrationConfig,\n request: GovernedLaneRequest\n): GovernedLaneResult => {\n if (config.mode === \"off\") {\n return {\n status: \"blocked\",\n lane: request.lane,\n reason: \"Challenge automation mode is off.\",\n auditMetadata: {}\n };\n }\n\n switch (request.lane) {\n case \"owned_environment_fixture\":\n if (!config.governed.allowOwnedEnvironmentFixtures) {\n return {\n status: \"blocked\",\n lane: request.lane,\n reason: \"Owned-environment fixtures are disabled by policy.\",\n auditMetadata: {}\n };\n }\n return runOwnedEnvironmentLane(request);\n case \"sanctioned_identity\":\n if (!config.governed.allowSanctionedIdentity) {\n return {\n status: \"blocked\",\n lane: request.lane,\n reason: \"Sanctioned identity is disabled by policy.\",\n auditMetadata: {}\n };\n }\n return runSanctionedIdentityLane(request);\n case \"service_adapter\":\n if (!config.governed.allowServiceAdapters) {\n return {\n status: \"blocked\",\n lane: request.lane,\n reason: \"Service adapters are disabled by policy.\",\n auditMetadata: {}\n };\n }\n return runServiceAdapterLane(request);\n }\n};\n","import type { OutcomeRecord } from \"./types\";\n\nconst MAX_RECORDS_PER_CHALLENGE = 25;\n\nexport class OutcomeRecorder {\n private readonly records = new Map<string, OutcomeRecord[]>();\n\n record(record: OutcomeRecord): void {\n const key = record.challengeId ?? \"__untracked__\";\n const existing = this.records.get(key) ?? [];\n const next = [...existing, record].slice(-MAX_RECORDS_PER_CHALLENGE);\n this.records.set(key, next);\n }\n\n latest(challengeId: string | undefined): OutcomeRecord | undefined {\n if (!challengeId) return undefined;\n const entries = this.records.get(challengeId);\n return entries?.[entries.length - 1];\n }\n\n read(challengeId: string | undefined): OutcomeRecord[] {\n if (!challengeId) return [];\n return [...(this.records.get(challengeId) ?? [])];\n }\n}\n","import type { ChallengeRuntimeHandle } from \"../browser/manager-types\";\nimport type { ProvidersChallengeOrchestrationConfig } from \"../config\";\nimport { buildCapabilityMatrix } from \"./capability-matrix\";\nimport { captureChallengeEvidence } from \"./capture\";\nimport { evaluateGovernedLane } from \"./governed-adapter-gateway\";\nimport { buildHumanYieldPacket, shouldYieldToHuman } from \"./human-yield-gate\";\nimport { interpretChallengeEvidence } from \"./interpreter\";\nimport { OutcomeRecorder } from \"./outcome-recorder\";\nimport { suggestComputerUseActions } from \"./optional-computer-use-bridge\";\nimport { buildChallengePolicyGate, resolveChallengeAutomationPolicy } from \"./policy-gate\";\nimport { selectChallengeStrategy } from \"./strategy-selector\";\nimport { runChallengeActionLoop } from \"./action-loop\";\nimport type {\n ChallengeCapabilityMatrix,\n ChallengeEvidenceBundle,\n ChallengeOrchestrationResult,\n ChallengeOrchestrationSnapshot,\n ChallengeStrategyDecision,\n OutcomeRecord,\n ResolvedChallengeAutomationPolicy,\n VerificationResult\n} from \"./types\";\nimport type { JsonValue } from \"../providers/types\";\n\nconst toStillBlockedVerification = (bundle: ChallengeEvidenceBundle, reason: string): VerificationResult => ({\n status: \"still_blocked\",\n blockerState: bundle.blockerState,\n blocker: bundle.blocker,\n challenge: bundle.challenge,\n bundle,\n changed: false,\n reason,\n url: bundle.url,\n title: bundle.title\n});\n\nconst buildOutcome = (args: {\n bundle: ChallengeEvidenceBundle;\n decision: ChallengeStrategyDecision;\n interpretation: ReturnType<typeof interpretChallengeEvidence>;\n policy: ResolvedChallengeAutomationPolicy;\n capabilityMatrix: ChallengeCapabilityMatrix;\n verification: VerificationResult;\n status: ChallengeOrchestrationSnapshot[\"status\"];\n reason: string;\n attempts: number;\n reusedExistingSession: boolean;\n reusedCookies: boolean;\n yielded?: ChallengeOrchestrationSnapshot[\"yielded\"];\n}): ChallengeOrchestrationSnapshot => ({\n challengeId: args.bundle.challengeId,\n classification: args.interpretation.classification,\n mode: args.policy.mode,\n source: args.policy.source,\n lane: args.decision.lane,\n status: args.status,\n reason: args.reason,\n attempts: args.attempts,\n reusedExistingSession: args.reusedExistingSession,\n reusedCookies: args.reusedCookies,\n helperEligibility: args.capabilityMatrix.helperEligibility,\n ...(\n !args.capabilityMatrix.helperEligibility.allowed || args.policy.standDownReason\n ? {\n standDownReason: args.capabilityMatrix.helperEligibility.standDownReason ?? args.policy.standDownReason\n }\n : {}\n ),\n verification: args.verification,\n evidence: {\n url: args.bundle.url,\n title: args.bundle.title,\n blockerType: args.bundle.blocker?.type,\n fallbackDisposition: args.bundle.fallbackDisposition,\n loginRefs: args.bundle.continuity.loginRefs,\n humanVerificationRefs: args.bundle.continuity.humanVerificationRefs,\n checkpointRefs: args.bundle.continuity.checkpointRefs,\n ...(args.bundle.interaction?.surface && args.bundle.interaction.surface !== \"unknown\"\n ? { interactionSurface: args.bundle.interaction.surface }\n : {}),\n ...(args.bundle.interaction?.preferredAction && args.bundle.interaction.preferredAction !== \"unknown\"\n ? { preferredAction: args.bundle.interaction.preferredAction }\n : {}),\n ...(typeof args.bundle.interaction?.holdMs === \"number\"\n ? { holdMs: args.bundle.interaction.holdMs }\n : {}),\n registryPressure: args.bundle.registryPressure\n },\n ...(args.yielded ? { yielded: args.yielded } : {})\n});\n\nconst buildRecord = (outcome: ChallengeOrchestrationSnapshot, executedSteps: OutcomeRecord[\"executedSteps\"]): OutcomeRecord => ({\n at: new Date().toISOString(),\n challengeId: outcome.challengeId,\n lane: outcome.lane,\n status: outcome.status,\n reason: outcome.reason,\n attempts: outcome.attempts,\n reusedExistingSession: outcome.reusedExistingSession,\n reusedCookies: outcome.reusedCookies,\n verification: outcome.verification,\n evidence: outcome.evidence,\n resumeOutcome: outcome.status === \"resolved\"\n ? \"continued\"\n : outcome.status === \"yield_required\"\n ? \"awaiting_human_reclaim\"\n : outcome.status === \"deferred\" || outcome.status === \"policy_blocked\"\n ? \"deferred\"\n : \"still_blocked\",\n executedSteps,\n ...(outcome.yielded ? { yielded: outcome.yielded } : {})\n});\n\nexport class ChallengeOrchestrator {\n private readonly recorder: OutcomeRecorder;\n private readonly config: ProvidersChallengeOrchestrationConfig;\n\n constructor(config: ProvidersChallengeOrchestrationConfig, recorder = new OutcomeRecorder()) {\n this.config = config;\n this.recorder = recorder;\n }\n\n getRecorder(): OutcomeRecorder {\n return this.recorder;\n }\n\n async captureEvidence(args: {\n handle: ChallengeRuntimeHandle;\n sessionId: string;\n targetId?: string | null;\n canImportCookies: boolean;\n fallbackDisposition?: ChallengeEvidenceBundle[\"fallbackDisposition\"];\n registryPressure?: ChallengeEvidenceBundle[\"registryPressure\"];\n taskData?: ChallengeEvidenceBundle[\"taskData\"];\n }): Promise<ChallengeEvidenceBundle> {\n return captureChallengeEvidence(args);\n }\n\n async orchestrate(args: {\n handle: ChallengeRuntimeHandle;\n sessionId: string;\n targetId?: string | null;\n policy?: ResolvedChallengeAutomationPolicy;\n canImportCookies?: boolean;\n fallbackDisposition?: ChallengeEvidenceBundle[\"fallbackDisposition\"];\n registryPressure?: ChallengeEvidenceBundle[\"registryPressure\"];\n taskData?: ChallengeEvidenceBundle[\"taskData\"];\n auditContext?: Record<string, JsonValue>;\n }): Promise<ChallengeOrchestrationResult> {\n const bundle = await this.captureEvidence({\n handle: args.handle,\n sessionId: args.sessionId,\n targetId: args.targetId,\n canImportCookies: args.canImportCookies ?? false,\n fallbackDisposition: args.fallbackDisposition,\n registryPressure: args.registryPressure,\n taskData: args.taskData\n });\n const interpretation = interpretChallengeEvidence(bundle);\n const policy = args.policy ?? resolveChallengeAutomationPolicy({\n configMode: this.config.mode\n });\n const gate = buildChallengePolicyGate(this.config, interpretation, policy);\n const capabilityMatrix = buildCapabilityMatrix(bundle, interpretation, gate);\n const decision = selectChallengeStrategy({\n config: this.config,\n bundle,\n interpretation,\n capabilityMatrix,\n gate\n });\n\n const latest = this.recorder.latest(bundle.challengeId);\n if (\n latest\n && Date.now() - Date.parse(latest.at) < this.config.minAttemptGapMs\n && latest.status !== \"resolved\"\n ) {\n const verification = toStillBlockedVerification(bundle, \"Recent bounded challenge attempt already ran; throttling repeated execution.\");\n const outcome = buildOutcome({\n bundle,\n decision,\n interpretation,\n policy: gate.resolvedPolicy,\n capabilityMatrix,\n verification,\n status: \"deferred\",\n reason: \"Recent attempt throttle\",\n attempts: 0,\n reusedExistingSession: false,\n reusedCookies: false\n });\n return {\n bundle,\n interpretation,\n decision,\n action: {\n status: \"deferred\",\n attempts: 0,\n noProgressCount: 0,\n executedSteps: [],\n verification,\n reusedExistingSession: false,\n reusedCookies: false\n },\n outcome\n };\n }\n\n if (decision.lane === \"defer\") {\n const verification = toStillBlockedVerification(bundle, decision.rationale);\n const outcome = buildOutcome({\n bundle,\n decision,\n interpretation,\n policy: gate.resolvedPolicy,\n capabilityMatrix,\n verification,\n status: \"deferred\",\n reason: decision.rationale,\n attempts: 0,\n reusedExistingSession: false,\n reusedCookies: false\n });\n this.recorder.record(buildRecord(outcome, []));\n return {\n bundle,\n interpretation,\n decision,\n action: {\n status: \"deferred\",\n attempts: 0,\n noProgressCount: 0,\n executedSteps: [],\n verification,\n reusedExistingSession: false,\n reusedCookies: false\n },\n outcome\n };\n }\n\n if (decision.lane === \"human_yield\") {\n const yieldDecision = shouldYieldToHuman({ interpretation, noProgressExhausted: false });\n const verification = toStillBlockedVerification(bundle, `Yield required: ${yieldDecision.reason}`);\n const packet = buildHumanYieldPacket({\n bundle,\n interpretation,\n sessionId: args.sessionId,\n targetId: bundle.activeTargetId ?? args.targetId ?? null,\n reason: yieldDecision.reason,\n verification\n });\n const outcome = buildOutcome({\n bundle,\n decision,\n interpretation,\n policy: gate.resolvedPolicy,\n capabilityMatrix,\n verification,\n status: \"yield_required\",\n reason: `Yield required: ${yieldDecision.reason}`,\n attempts: 0,\n reusedExistingSession: false,\n reusedCookies: false,\n yielded: packet\n });\n this.recorder.record(buildRecord(outcome, []));\n return {\n bundle,\n interpretation,\n decision,\n action: {\n status: \"yield_required\",\n attempts: 0,\n noProgressCount: 0,\n executedSteps: [],\n verification,\n reusedExistingSession: false,\n reusedCookies: false\n },\n outcome\n };\n }\n\n let suggestedSteps = undefined;\n if (decision.lane === \"optional_computer_use_bridge\") {\n suggestedSteps = suggestComputerUseActions({\n helperEligibility: capabilityMatrix.helperEligibility,\n bundle,\n maxSuggestions: this.config.optionalComputerUseBridge.maxSuggestions\n }).suggestedSteps;\n }\n if (decision.governedLane) {\n const governed = evaluateGovernedLane(this.config, {\n lane: decision.governedLane,\n bundle,\n interpretation,\n decision,\n auditContext: args.auditContext\n });\n if (governed.status === \"blocked\") {\n const verification = toStillBlockedVerification(bundle, governed.reason);\n const outcome = buildOutcome({\n bundle,\n decision,\n interpretation,\n policy: gate.resolvedPolicy,\n capabilityMatrix,\n verification,\n status: \"policy_blocked\",\n reason: governed.reason,\n attempts: 0,\n reusedExistingSession: false,\n reusedCookies: false\n });\n this.recorder.record(buildRecord(outcome, []));\n return {\n bundle,\n interpretation,\n decision,\n action: {\n status: \"policy_blocked\",\n attempts: 0,\n noProgressCount: 0,\n executedSteps: [],\n verification,\n reusedExistingSession: false,\n reusedCookies: false\n },\n outcome\n };\n }\n suggestedSteps = governed.suggestedSteps;\n }\n\n const action = await runChallengeActionLoop({\n handle: args.handle,\n sessionId: args.sessionId,\n targetId: args.targetId,\n initialBundle: bundle,\n decision,\n helperEligibility: capabilityMatrix.helperEligibility,\n config: this.config,\n suggestedSteps\n });\n const verifiedBundle = action.verification.bundle ?? bundle;\n\n const maybeYield = shouldYieldToHuman({\n interpretation,\n noProgressExhausted: action.status === \"no_progress\"\n });\n const yielded = action.status === \"yield_required\" || maybeYield.yield\n ? buildHumanYieldPacket({\n bundle: verifiedBundle,\n interpretation,\n sessionId: args.sessionId,\n targetId: verifiedBundle.activeTargetId ?? bundle.activeTargetId ?? args.targetId ?? null,\n reason: action.status === \"yield_required\" ? maybeYield.reason : maybeYield.reason,\n verification: action.verification\n })\n : undefined;\n\n const outcome = buildOutcome({\n bundle: verifiedBundle,\n decision,\n interpretation,\n policy: gate.resolvedPolicy,\n capabilityMatrix,\n verification: action.verification,\n status: action.status === \"yield_required\" || maybeYield.yield\n ? \"yield_required\"\n : action.status,\n reason: action.verification.reason,\n attempts: action.attempts,\n reusedExistingSession: action.reusedExistingSession,\n reusedCookies: action.reusedCookies,\n ...(yielded ? { yielded } : {})\n });\n\n this.recorder.record(buildRecord(outcome, action.executedSteps));\n return {\n bundle,\n interpretation,\n decision,\n action,\n outcome\n };\n }\n}\n","import { resolveChallengeAutomationPolicy, type ChallengeAutomationMode } from \"../challenges\";\nimport type {\n BrowserFallbackMode,\n ProviderCookiePolicy,\n ProviderRecoveryHints,\n ProviderRuntimePolicyInput,\n ProviderSource,\n ResolvedProviderRuntimePolicy,\n WorkflowBrowserMode\n} from \"./types\";\n\nexport const DEFAULT_PROVIDER_FALLBACK_MODES: Record<ProviderSource, BrowserFallbackMode[]> = {\n web: [\"managed_headed\"],\n community: [\"managed_headed\"],\n social: [\"managed_headed\"],\n shopping: [\"extension\", \"managed_headed\"]\n};\n\nexport const resolveWorkflowBrowserModeFallbackModes = (\n browserMode?: WorkflowBrowserMode\n): BrowserFallbackMode[] | undefined => {\n if (browserMode === \"extension\") {\n return [\"extension\"];\n }\n if (browserMode === \"managed\") {\n return [\"managed_headed\"];\n }\n return undefined;\n};\n\nexport const shouldForceWorkflowBrowserTransport = (\n browserMode?: WorkflowBrowserMode\n): boolean => browserMode === \"extension\" || browserMode === \"managed\";\n\nexport const resolveProviderFallbackModes = (args: {\n source: ProviderSource;\n recoveryHints?: ProviderRecoveryHints;\n preferredModes?: BrowserFallbackMode[];\n}): BrowserFallbackMode[] => {\n const candidates = args.preferredModes?.length\n ? args.preferredModes\n : args.recoveryHints?.preferredFallbackModes?.length\n ? args.recoveryHints.preferredFallbackModes\n : DEFAULT_PROVIDER_FALLBACK_MODES[args.source];\n return [...new Set(candidates)];\n};\n\nconst resolveCookiePolicy = (args: {\n configPolicy?: ProviderCookiePolicy;\n requestedUseCookies?: boolean;\n requestedOverride?: ProviderCookiePolicy;\n}): ProviderCookiePolicy => {\n if (args.requestedOverride) {\n return args.requestedOverride;\n }\n if (args.requestedUseCookies === false) {\n return \"off\";\n }\n const configPolicy = args.configPolicy ?? \"auto\";\n if (args.requestedUseCookies === true && configPolicy === \"off\") {\n return \"auto\";\n }\n return configPolicy;\n};\n\nexport const resolveProviderRuntimePolicy = (args: {\n source: ProviderSource;\n runtimePolicy?: ProviderRuntimePolicyInput;\n preferredFallbackModes?: BrowserFallbackMode[];\n forceBrowserTransport?: boolean;\n useCookies?: boolean;\n cookiePolicyOverride?: ProviderCookiePolicy;\n challengeAutomationMode?: ChallengeAutomationMode;\n sessionChallengeAutomationMode?: ChallengeAutomationMode;\n configChallengeAutomationMode?: ChallengeAutomationMode;\n configCookiePolicy?: ProviderCookiePolicy;\n recoveryHints?: ProviderRecoveryHints;\n}): ResolvedProviderRuntimePolicy => {\n const runtimeInput = args.runtimePolicy;\n const browserMode = runtimeInput?.browserMode;\n const requestedUseCookies = typeof runtimeInput?.useCookies === \"boolean\"\n ? runtimeInput.useCookies\n : args.useCookies;\n const requestedCookiePolicyOverride = runtimeInput?.cookiePolicyOverride ?? args.cookiePolicyOverride;\n const requestedChallengeAutomationMode = runtimeInput?.challengeAutomationMode ?? args.challengeAutomationMode;\n const preferredModes = args.preferredFallbackModes?.length\n ? args.preferredFallbackModes\n : resolveWorkflowBrowserModeFallbackModes(browserMode);\n\n return {\n browser: {\n preferredModes: resolveProviderFallbackModes({\n source: args.source,\n recoveryHints: args.recoveryHints,\n preferredModes\n }),\n forceTransport: args.forceBrowserTransport === true || shouldForceWorkflowBrowserTransport(browserMode)\n },\n cookies: {\n ...(typeof requestedUseCookies === \"boolean\" ? { requested: requestedUseCookies } : {}),\n policy: resolveCookiePolicy({\n configPolicy: args.configCookiePolicy,\n requestedUseCookies,\n requestedOverride: requestedCookiePolicyOverride\n })\n },\n challenge: resolveChallengeAutomationPolicy({\n runMode: requestedChallengeAutomationMode,\n sessionMode: args.sessionChallengeAutomationMode,\n configMode: args.configChallengeAutomationMode ?? \"browser_with_helper\"\n })\n };\n};\n","import { buildProviderIssueGuidance, readProviderIssueHint } from \"./constraint\";\nimport { ProviderRuntimeError, providerErrorCodeFromReasonCode } from \"./errors\";\nimport {\n resolveProviderFallbackModes,\n resolveProviderRuntimePolicy\n} from \"./runtime-policy\";\nimport type {\n BrowserFallbackObservation,\n BrowserFallbackMode,\n BrowserFallbackPort,\n BrowserFallbackResponse,\n JsonValue,\n ProviderContext,\n ProviderOperation,\n ProviderRecoveryHints,\n ProviderReasonCode,\n ProviderSource,\n SuspendedIntentKind,\n SuspendedIntentSummary\n} from \"./types\";\n\nexport { resolveProviderFallbackModes } from \"./runtime-policy\";\n\nconst DEFAULT_SUSPENDED_INTENT_KIND: Record<ProviderOperation, SuspendedIntentKind> = {\n search: \"provider.search\",\n fetch: \"provider.fetch\",\n crawl: \"provider.crawl\",\n post: \"provider.post\"\n};\n\nconst toJsonValue = (value: unknown): JsonValue | undefined => {\n if (\n value === null\n || typeof value === \"string\"\n || typeof value === \"number\"\n || typeof value === \"boolean\"\n ) {\n return value;\n }\n if (Array.isArray(value)) {\n const entries = value\n .map((entry) => toJsonValue(entry))\n .filter((entry): entry is JsonValue => typeof entry !== \"undefined\");\n return entries;\n }\n if (!value || typeof value !== \"object\") {\n return undefined;\n }\n\n const record: Record<string, JsonValue> = {};\n for (const [key, entry] of Object.entries(value)) {\n const normalized = toJsonValue(entry);\n if (typeof normalized !== \"undefined\") {\n record[key] = normalized;\n }\n }\n return record;\n};\n\nconst toJsonRecord = (value: unknown): Record<string, JsonValue> => {\n const normalized = toJsonValue(value);\n return normalized && typeof normalized === \"object\" && !Array.isArray(normalized)\n ? normalized\n : {};\n};\n\nconst readFallbackRecord = (\n details: Record<string, JsonValue> | undefined,\n key: string\n): Record<string, JsonValue> | undefined => {\n const candidate = details?.[key];\n return candidate && typeof candidate === \"object\" && !Array.isArray(candidate)\n ? candidate\n : undefined;\n};\n\nexport const readFallbackString = (\n output: Record<string, JsonValue> | undefined,\n key: \"html\" | \"url\"\n): string | undefined => {\n const value = output?.[key];\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n};\n\nexport const fallbackDispositionMessage = (\n fallback: BrowserFallbackResponse,\n url: string\n): string => {\n if (typeof fallback.details?.message === \"string\" && fallback.details.message.trim().length > 0) {\n return fallback.details.message;\n }\n switch (fallback.disposition) {\n case \"challenge_preserved\":\n return `Browser fallback preserved a challenge session for ${url}`;\n case \"deferred\":\n return `Browser fallback deferred recovery for ${url}`;\n default:\n return `Browser fallback failed for ${url}`;\n }\n};\n\nconst fallbackErrorDetails = (args: {\n url: string;\n fallback: BrowserFallbackResponse;\n extra?: Record<string, JsonValue>;\n}): Record<string, JsonValue> => ({\n url: args.url,\n disposition: args.fallback.disposition,\n ...(args.fallback.mode ? { browserFallbackMode: args.fallback.mode } : {}),\n ...(args.fallback.challenge ? { challenge: toJsonRecord(args.fallback.challenge) } : {}),\n ...(args.fallback.preservedSessionId ? { preservedSessionId: args.fallback.preservedSessionId } : {}),\n ...(args.fallback.preservedTargetId ? { preservedTargetId: args.fallback.preservedTargetId } : {}),\n ...toJsonRecord(args.fallback.details ?? {}),\n ...(args.extra ?? {})\n});\n\nconst addProviderIssueGuidance = (args: {\n provider: string;\n reasonCode: ProviderReasonCode;\n details: Record<string, JsonValue>;\n includeCompleted?: boolean;\n}): Record<string, JsonValue> => {\n const hint = readProviderIssueHint({\n reasonCode: args.reasonCode,\n details: args.details as Record<string, unknown>\n });\n const guidanceDetails = args.includeCompleted\n ? { ...args.details, disposition: \"failed\" }\n : args.details;\n const guidance = hint\n ? buildProviderIssueGuidance({ provider: args.provider, hint, details: guidanceDetails })\n : undefined;\n return guidance ? { ...args.details, guidance } : args.details;\n};\n\nexport const toProviderFallbackError = (args: {\n provider: string;\n source: ProviderSource;\n url: string;\n fallback: BrowserFallbackResponse;\n}): ProviderRuntimeError => {\n const { fallback } = args;\n const reasonCode = fallback.reasonCode;\n const details = fallbackErrorDetails({ url: args.url, fallback });\n return new ProviderRuntimeError(\n providerErrorCodeFromReasonCode(reasonCode),\n fallbackDispositionMessage(fallback, args.url),\n {\n provider: args.provider,\n source: args.source,\n retryable: reasonCode === \"rate_limited\",\n reasonCode,\n details: addProviderIssueGuidance({\n provider: args.provider,\n reasonCode,\n details\n })\n }\n );\n};\n\nexport const toCompletedFallbackOutputError = (args: {\n provider: string;\n source: ProviderSource;\n url: string;\n fallback: BrowserFallbackResponse;\n outputReason: string;\n}): ProviderRuntimeError => {\n const { fallback } = args;\n const reasonCode = fallback.reasonCode;\n const details = fallbackErrorDetails({\n url: args.url,\n fallback,\n extra: { fallbackOutputReason: args.outputReason }\n });\n return new ProviderRuntimeError(\n providerErrorCodeFromReasonCode(reasonCode),\n `Browser fallback completed for ${args.url} without usable HTML content.`,\n {\n provider: args.provider,\n source: args.source,\n retryable: reasonCode === \"rate_limited\",\n reasonCode,\n details: addProviderIssueGuidance({\n provider: args.provider,\n reasonCode,\n details,\n includeCompleted: true\n })\n }\n );\n};\n\nexport const toBrowserFallbackObservation = (\n fallback: Pick<BrowserFallbackResponse, \"reasonCode\" | \"mode\" | \"details\">\n): BrowserFallbackObservation => ({\n reasonCode: fallback.reasonCode,\n ...(fallback.mode ? { mode: fallback.mode } : {}),\n ...(readFallbackRecord(fallback.details, \"cookieDiagnostics\")\n ? { cookieDiagnostics: readFallbackRecord(fallback.details, \"cookieDiagnostics\") }\n : {}),\n ...(readFallbackRecord(fallback.details, \"challengeOrchestration\")\n ? { challengeOrchestration: readFallbackRecord(fallback.details, \"challengeOrchestration\") }\n : {})\n});\n\nexport const browserFallbackObservationDetails = (\n observation: BrowserFallbackObservation | undefined\n): Record<string, JsonValue> => (\n observation\n ? {\n browserFallbackReasonCode: observation.reasonCode,\n ...(observation.mode ? { browserFallbackMode: observation.mode } : {}),\n ...(observation.cookieDiagnostics ? { cookieDiagnostics: observation.cookieDiagnostics } : {}),\n ...(observation.challengeOrchestration ? { challengeOrchestration: observation.challengeOrchestration } : {})\n }\n : {}\n);\n\nexport const browserFallbackObservationAttributes = (\n observation: BrowserFallbackObservation | undefined\n): Record<string, JsonValue> => (\n observation\n ? {\n browser_fallback_reason_code: observation.reasonCode,\n ...(observation.mode ? { browser_fallback_mode: observation.mode } : {}),\n ...(observation.cookieDiagnostics\n ? { browser_fallback_cookie_diagnostics: observation.cookieDiagnostics }\n : {}),\n ...(observation.challengeOrchestration\n ? { browser_fallback_challenge_orchestration: observation.challengeOrchestration }\n : {})\n }\n : {}\n);\n\nconst buildSuspendedIntentSummary = (args: {\n provider: string;\n source: ProviderSource;\n operation: ProviderOperation;\n suspendedIntent?: SuspendedIntentSummary;\n input?: JsonValue;\n}): SuspendedIntentSummary => {\n if (args.suspendedIntent) {\n return typeof args.suspendedIntent.input === \"undefined\" && typeof args.input !== \"undefined\"\n ? {\n ...args.suspendedIntent,\n input: args.input\n }\n : args.suspendedIntent;\n }\n return {\n kind: DEFAULT_SUSPENDED_INTENT_KIND[args.operation],\n provider: args.provider,\n source: args.source,\n operation: args.operation,\n ...(typeof args.input !== \"undefined\" ? { input: args.input } : {})\n };\n};\n\nexport const resolveProviderBrowserFallback = async (args: {\n browserFallbackPort?: BrowserFallbackPort;\n allowEscalation?: boolean;\n provider: string;\n source: ProviderSource;\n operation: ProviderOperation;\n reasonCode: ProviderReasonCode;\n url?: string;\n context?: ProviderContext;\n details?: Record<string, JsonValue>;\n recoveryHints?: ProviderRecoveryHints;\n preferredModes?: BrowserFallbackMode[];\n suspendedIntent?: SuspendedIntentSummary;\n intentInput?: JsonValue;\n}): Promise<BrowserFallbackResponse | null> => {\n if (!args.browserFallbackPort || args.allowEscalation === false) {\n return null;\n }\n\n const runtimePolicy = args.context?.runtimePolicy ?? resolveProviderRuntimePolicy({\n source: args.source,\n recoveryHints: args.recoveryHints\n });\n\n const fallback = await args.browserFallbackPort.resolve({\n provider: args.provider,\n source: args.source,\n operation: args.operation,\n reasonCode: args.reasonCode,\n trace: args.context?.trace ?? {\n requestId: `provider-fallback-${Date.now()}`,\n provider: args.provider,\n ts: new Date().toISOString()\n },\n ...(args.url ? { url: args.url } : {}),\n ...(typeof args.context?.timeoutMs === \"number\" ? { timeoutMs: args.context.timeoutMs } : {}),\n ...(args.context?.signal ? { signal: args.context.signal } : {}),\n ...(args.details ? { details: args.details } : {}),\n runtimePolicy,\n ...(args.preferredModes?.length\n ? {\n preferredModes: resolveProviderFallbackModes({\n source: args.source,\n recoveryHints: args.recoveryHints,\n preferredModes: args.preferredModes\n })\n }\n : {}),\n ownerSurface: \"provider_fallback\",\n resumeMode: \"auto\",\n suspendedIntent: buildSuspendedIntentSummary({\n provider: args.provider,\n source: args.source,\n operation: args.operation,\n suspendedIntent: args.suspendedIntent ?? args.context?.suspendedIntent,\n input: args.intentInput ?? args.context?.suspendedIntent?.input\n }),\n ...(typeof args.recoveryHints?.settleTimeoutMs === \"number\"\n ? { settleTimeoutMs: args.recoveryHints.settleTimeoutMs }\n : {}),\n ...(typeof args.recoveryHints?.captureDelayMs === \"number\"\n ? { captureDelayMs: args.recoveryHints.captureDelayMs }\n : {})\n });\n\n return {\n ...fallback,\n disposition: fallback.disposition ?? (\n fallback.ok\n ? \"completed\"\n : fallback.reasonCode === \"env_limited\"\n ? \"deferred\"\n : \"failed\"\n )\n };\n};\n","import type { ProviderRegistry } from \"../registry\";\nimport type { ProviderOperation, ProviderReasonCode } from \"../types\";\n\nexport interface AntiBotPolicyConfig {\n enabled: boolean;\n cooldownMs: number;\n maxChallengeRetries: number;\n proxyHint?: string;\n sessionHint?: string;\n allowBrowserEscalation: boolean;\n}\n\nexport interface AntiBotPreflightContext {\n providerId: string;\n operation: ProviderOperation;\n nowMs?: number;\n}\n\nexport interface AntiBotPreflightResult {\n allow: boolean;\n reasonCode?: ProviderReasonCode;\n retryAfterMs?: number;\n retryGuidance?: string;\n proxyHint?: string;\n sessionHint?: string;\n escalationIntent: boolean;\n}\n\nexport interface AntiBotPostflightContext {\n providerId: string;\n operation: ProviderOperation;\n success: boolean;\n reasonCode?: ProviderReasonCode;\n retryable: boolean;\n attempt: number;\n maxAttempts: number;\n nowMs?: number;\n}\n\nexport interface AntiBotPostflightResult {\n allowRetry: boolean;\n reasonCode?: ProviderReasonCode;\n retryAfterMs?: number;\n escalationIntent: boolean;\n proxyHint?: string;\n sessionHint?: string;\n}\n\nconst clampInt = (value: number | undefined, fallback: number, min: number, max: number): number => {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return fallback;\n const rounded = Math.floor(value);\n if (rounded < min) return min;\n if (rounded > max) return max;\n return rounded;\n};\n\nexport const DEFAULT_ANTI_BOT_POLICY_CONFIG: AntiBotPolicyConfig = {\n enabled: true,\n cooldownMs: 30000,\n maxChallengeRetries: 1,\n allowBrowserEscalation: false\n};\n\nconst COOLDOWN_REASONS = new Set<ProviderReasonCode>([\n \"ip_blocked\",\n \"token_required\",\n \"auth_required\",\n \"challenge_detected\",\n \"rate_limited\"\n]);\n\nconst ESCALATION_REASONS = new Set<ProviderReasonCode>([\n \"ip_blocked\",\n \"token_required\",\n \"auth_required\",\n \"challenge_detected\"\n]);\n\nexport const resolveAntiBotPolicyConfig = (\n config: Partial<AntiBotPolicyConfig> | undefined\n): AntiBotPolicyConfig => ({\n enabled: config?.enabled ?? DEFAULT_ANTI_BOT_POLICY_CONFIG.enabled,\n cooldownMs: clampInt(config?.cooldownMs, DEFAULT_ANTI_BOT_POLICY_CONFIG.cooldownMs, 0, 300000),\n maxChallengeRetries: clampInt(\n config?.maxChallengeRetries,\n DEFAULT_ANTI_BOT_POLICY_CONFIG.maxChallengeRetries,\n 0,\n 10\n ),\n ...(config?.proxyHint ? { proxyHint: config.proxyHint.trim() } : {}),\n ...(config?.sessionHint ? { sessionHint: config.sessionHint.trim() } : {}),\n allowBrowserEscalation: config?.allowBrowserEscalation ?? DEFAULT_ANTI_BOT_POLICY_CONFIG.allowBrowserEscalation\n});\n\nexport class AntiBotPolicyEngine {\n private readonly registry: ProviderRegistry;\n private readonly config: AntiBotPolicyConfig;\n\n constructor(registry: ProviderRegistry, config: Partial<AntiBotPolicyConfig> | undefined = {}) {\n this.registry = registry;\n this.config = resolveAntiBotPolicyConfig(config);\n }\n\n preflight(context: AntiBotPreflightContext): AntiBotPreflightResult {\n if (!this.config.enabled) {\n return {\n allow: true,\n escalationIntent: false\n };\n }\n\n const nowMs = context.nowMs ?? Date.now();\n const cooldown = this.registry.getAntiBotCooldown(context.providerId, context.operation, nowMs);\n if (cooldown) {\n const retryAfterMs = cooldown.cooldownUntilMs - nowMs;\n return {\n allow: false,\n reasonCode: cooldown.reasonCode,\n retryAfterMs,\n retryGuidance: \"cooldown_active\",\n ...(this.config.proxyHint ? { proxyHint: this.config.proxyHint } : {}),\n ...(this.config.sessionHint ? { sessionHint: this.config.sessionHint } : {}),\n escalationIntent: this.config.allowBrowserEscalation && ESCALATION_REASONS.has(cooldown.reasonCode)\n };\n }\n\n return {\n allow: true,\n escalationIntent: false\n };\n }\n\n postflight(context: AntiBotPostflightContext): AntiBotPostflightResult {\n if (!this.config.enabled) {\n return {\n allowRetry: context.retryable && context.attempt < context.maxAttempts,\n escalationIntent: false\n };\n }\n\n if (context.success) {\n this.registry.clearAntiBotCooldown(context.providerId, context.operation);\n return {\n allowRetry: false,\n escalationIntent: false\n };\n }\n\n const reasonCode = context.reasonCode;\n const nowMs = context.nowMs ?? Date.now();\n if (reasonCode && COOLDOWN_REASONS.has(reasonCode) && this.config.cooldownMs > 0) {\n this.registry.setAntiBotCooldown(\n context.providerId,\n context.operation,\n reasonCode,\n nowMs + this.config.cooldownMs,\n nowMs\n );\n }\n\n const canRetryByAttempt = context.attempt < context.maxAttempts;\n const challengeRetryBudgetExceeded = reasonCode === \"challenge_detected\"\n && context.attempt > this.config.maxChallengeRetries + 1;\n const allowRetry = context.retryable && canRetryByAttempt && !challengeRetryBudgetExceeded;\n\n return {\n allowRetry,\n ...(reasonCode ? { reasonCode } : {}),\n ...(reasonCode && COOLDOWN_REASONS.has(reasonCode) && this.config.cooldownMs > 0\n ? { retryAfterMs: this.config.cooldownMs }\n : {}),\n ...(this.config.proxyHint ? { proxyHint: this.config.proxyHint } : {}),\n ...(this.config.sessionHint ? { sessionHint: this.config.sessionHint } : {}),\n escalationIntent: Boolean(\n reasonCode\n && this.config.allowBrowserEscalation\n && ESCALATION_REASONS.has(reasonCode)\n )\n };\n }\n}\n","import { createHash } from \"crypto\";\nimport { ProviderRuntimeError } from \"../errors\";\nimport type { JsonValue, ProviderPostInput, TraceContext } from \"../types\";\n\nexport interface PostPolicyContext {\n providerId: string;\n source: \"community\" | \"social\";\n payload: ProviderPostInput;\n trace: TraceContext;\n}\n\nexport interface PostPolicyDecision {\n allow: boolean;\n reason?: string;\n metadata?: Record<string, JsonValue>;\n}\n\nexport interface PostPolicyAuditEntry {\n providerId: string;\n source: \"community\" | \"social\";\n decision: \"allow\" | \"deny\";\n reason?: string;\n payloadHash: string;\n ts: string;\n requestId: string;\n}\n\nexport type PostPolicyHook = (context: PostPolicyContext) => Promise<PostPolicyDecision> | PostPolicyDecision;\n\nconst defaultPolicy: PostPolicyHook = (context) => {\n if (!context.payload.riskAccepted) {\n return {\n allow: false,\n reason: \"Posting requires risk acknowledgement\"\n };\n }\n\n if (!context.payload.confirm) {\n return {\n allow: false,\n reason: \"Posting requires explicit confirmation\"\n };\n }\n\n return { allow: true };\n};\n\nexport const hashPostPayload = (payload: ProviderPostInput): string => {\n const normalized = JSON.stringify({\n target: payload.target,\n content: payload.content,\n mediaUrls: payload.mediaUrls ?? [],\n metadata: payload.metadata ?? {}\n });\n return createHash(\"sha256\").update(normalized).digest(\"hex\");\n};\n\nexport const evaluatePostPolicy = async (\n context: PostPolicyContext,\n hooks: PostPolicyHook[] = []\n): Promise<{ allowed: boolean; reason?: string; audit: PostPolicyAuditEntry; metadata?: Record<string, JsonValue> }> => {\n const chain = [defaultPolicy, ...hooks];\n const payloadHash = hashPostPayload(context.payload);\n\n for (const hook of chain) {\n const decision = await hook(context);\n if (!decision.allow) {\n return {\n allowed: false,\n reason: decision.reason,\n ...(decision.metadata ? { metadata: decision.metadata } : {}),\n audit: {\n providerId: context.providerId,\n source: context.source,\n decision: \"deny\",\n reason: decision.reason,\n payloadHash,\n ts: new Date().toISOString(),\n requestId: context.trace.requestId\n }\n };\n }\n }\n\n return {\n allowed: true,\n audit: {\n providerId: context.providerId,\n source: context.source,\n decision: \"allow\",\n payloadHash,\n ts: new Date().toISOString(),\n requestId: context.trace.requestId\n }\n };\n};\n\nexport const assertPostPolicy = async (\n context: PostPolicyContext,\n hooks: PostPolicyHook[] = []\n): Promise<PostPolicyAuditEntry> => {\n const result = await evaluatePostPolicy(context, hooks);\n if (!result.allowed) {\n throw new ProviderRuntimeError(\"policy_blocked\", result.reason ?? \"Post policy blocked the request\", {\n provider: context.providerId,\n source: context.source,\n retryable: false,\n details: {\n payloadHash: result.audit.payloadHash,\n reason: result.reason ?? null,\n ...(result.metadata ? { metadata: result.metadata } : {})\n }\n });\n }\n\n return result.audit;\n};\n","const STATIC_HOST_PATTERNS = [\n /(^|\\.)analytics\\.google\\.com$/i,\n /(^|\\.)fonts\\.googleapis\\.com$/i,\n /(^|\\.)google-analytics\\.com$/i,\n /(^|\\.)googleadservices\\.com$/i,\n /(^|\\.)googletagmanager\\.com$/i,\n /(^|\\.)googlesyndication\\.com$/i,\n /(^|\\.)gstatic\\.com$/i,\n /(^|\\.)doubleclick\\.net$/i,\n /(^|\\.)redditstatic\\.com$/i,\n /(^|\\.)twimg\\.com$/i,\n /(^|\\.)static\\.licdn\\.com$/i,\n /(^|\\.)ytimg\\.com$/i,\n /(^|\\.)fbcdn\\.net$/i,\n /(^|\\.)cdninstagram\\.com$/i\n];\n\nconst STATIC_PATH_EXT_RE = /\\.(?:avif|bmp|css|csv|gif|ico|jpe?g|js|json|map|mjs|mp3|mp4|ogg|pdf|png|svg|txt|wav|webm|webp|woff2?|xml|zip)$/i;\nexport type ResearchDestinationRejectionReason =\n | \"login_shell\"\n | \"privacy_preference_shell\"\n | \"research_dead_end_shell\"\n | \"search_results_shell\";\n\nconst RESEARCH_DEAD_END_LOGIN_SEGMENTS = new Set([\n \"account\",\n \"accounts\",\n \"login\",\n \"sign-in\",\n \"signin\",\n \"submit\"\n]);\nconst RESEARCH_DEAD_END_PRIVACY_ROOT_SEGMENTS = new Set([\n \"choice\",\n \"choices\",\n \"consent\",\n \"cookie\",\n \"cookie-policy\",\n \"cookie-preferences\",\n \"cookies\",\n \"legal\",\n \"policies\",\n \"policy\",\n \"privacy\",\n \"privacy-policy\",\n \"prefs\",\n \"preferences\",\n \"terms\",\n \"terms-of-service\"\n]);\nconst RESEARCH_DEAD_END_SEARCH_ROOT_SEGMENTS = new Set([\"find\", \"results\", \"search\"]);\nconst RESEARCH_DEAD_END_OTHER_ROOT_SEGMENTS = new Set([\"settings\", \"verification\"]);\nconst RESEARCH_DEAD_END_PATHS = new Set([\n \"/legal/privacy\",\n \"/policies\",\n \"/privacy\",\n \"/privacy-policy\",\n \"/privacy/choices\",\n \"/privacychoices\",\n \"/privacychoices/\"\n]);\n\nconst isPrivacyDeadEndPath = (segments: string[]): boolean => {\n const [first, second] = segments;\n if (!first || !RESEARCH_DEAD_END_PRIVACY_ROOT_SEGMENTS.has(first)) return false;\n if (segments.length === 1) return true;\n return (\n (first === \"consent\" && second === \"manage\")\n || (first === \"privacy\" && second === \"choices\")\n || (first === \"prefs\" && second === \"privacy\")\n || (first === \"preferences\" && second === \"privacy\")\n || (first === \"legal\" && (second === \"privacy\" || second === \"terms\"))\n || (first === \"policies\" && second === \"privacy-policy\")\n );\n};\n\nexport const isLikelyDocumentUrl = (value: string): boolean => {\n try {\n const parsed = new URL(value);\n const protocol = parsed.protocol.toLowerCase();\n if (protocol !== \"http:\" && protocol !== \"https:\") return false;\n\n if (STATIC_HOST_PATTERNS.some((pattern) => pattern.test(parsed.hostname))) {\n return false;\n }\n\n return !STATIC_PATH_EXT_RE.test(parsed.pathname);\n } catch {\n return false;\n }\n};\n\nexport const isLikelyResearchDestinationUrl = (value: string): boolean => {\n return classifyResearchDestinationRejection(value) === null;\n};\n\nexport const classifyResearchDestinationRejection = (value: string): ResearchDestinationRejectionReason | null => {\n if (!isLikelyDocumentUrl(value)) return \"research_dead_end_shell\";\n const parsed = new URL(value);\n const pathname = parsed.pathname.toLowerCase().replace(/\\/+$/, \"\") || \"/\";\n if (RESEARCH_DEAD_END_PATHS.has(pathname)) return \"privacy_preference_shell\";\n const segments = pathname.split(\"/\").filter(Boolean);\n const firstSegment = segments[0] ?? \"\";\n if (segments.some((segment) => RESEARCH_DEAD_END_LOGIN_SEGMENTS.has(segment))) return \"login_shell\";\n if (RESEARCH_DEAD_END_SEARCH_ROOT_SEGMENTS.has(firstSegment)) return \"search_results_shell\";\n if (RESEARCH_DEAD_END_OTHER_ROOT_SEGMENTS.has(firstSegment)) return \"research_dead_end_shell\";\n if (isPrivacyDeadEndPath(segments)) return \"privacy_preference_shell\";\n return null;\n};\n","export type RobotsMode = \"strict\" | \"warn\" | \"off\";\n\nexport interface WebCrawlPolicy {\n robotsMode?: RobotsMode;\n allowDomains?: string[];\n denyDomains?: string[];\n robotsBlockedDomains?: string[];\n}\n\nexport interface CrawlPolicyDecision {\n allowed: boolean;\n warnings: string[];\n reason?: string;\n}\n\nconst normalizeDomain = (value: string): string => value.trim().toLowerCase();\n\nconst includesDomain = (list: string[] | undefined, value: string): boolean => {\n if (!list || list.length === 0) return false;\n const normalized = normalizeDomain(value);\n return list.some((entry) => normalized === normalizeDomain(entry));\n};\n\nexport const evaluateWebCrawlPolicy = (\n rawUrl: string,\n policy: WebCrawlPolicy = {}\n): CrawlPolicyDecision => {\n let hostname = \"\";\n try {\n hostname = new URL(rawUrl).hostname;\n } catch {\n return {\n allowed: false,\n warnings: [],\n reason: \"Invalid URL\"\n };\n }\n\n if (includesDomain(policy.denyDomains, hostname)) {\n return {\n allowed: false,\n warnings: [],\n reason: \"Domain denied by policy\"\n };\n }\n\n if ((policy.allowDomains?.length ?? 0) > 0 && !includesDomain(policy.allowDomains, hostname)) {\n return {\n allowed: false,\n warnings: [],\n reason: \"Domain not in allow list\"\n };\n }\n\n const mode = policy.robotsMode ?? \"warn\";\n if (!includesDomain(policy.robotsBlockedDomains, hostname)) {\n return { allowed: true, warnings: [] };\n }\n\n if (mode === \"off\") {\n return { allowed: true, warnings: [] };\n }\n\n if (mode === \"warn\") {\n return {\n allowed: true,\n warnings: [\"Blocked by robots policy but allowed due to warn mode\"]\n };\n }\n\n return {\n allowed: false,\n warnings: [],\n reason: \"Blocked by robots policy\"\n };\n};\n","import { Worker, isMainThread } from \"node:worker_threads\";\nimport { extractStructuredContent, type ExtractedContent } from \"./extract\";\n\nexport interface CrawlExtractInput {\n url: string;\n html: string;\n selectors: string[];\n}\n\nexport interface CrawlWorkerPoolOptions {\n workerThreads?: number;\n queueMax?: number;\n forceInline?: boolean;\n}\n\ninterface WorkerExtractRequest {\n id: number;\n url: string;\n html: string;\n selectors: string[];\n}\n\ninterface WorkerExtractSuccess {\n id: number;\n ok: true;\n extracted: ExtractedContent;\n}\n\ninterface WorkerExtractFailure {\n id: number;\n ok: false;\n error: string;\n}\n\ntype WorkerExtractResponse = WorkerExtractSuccess | WorkerExtractFailure;\n\ninterface CrawlTask {\n id: number;\n input: CrawlExtractInput;\n resolve: (value: ExtractedContent) => void;\n reject: (error: Error) => void;\n}\n\ninterface WorkerHandle {\n worker: Worker;\n busy: boolean;\n taskId?: number;\n}\n\nconst DEFAULT_WORKER_THREADS = 0;\nconst DEFAULT_QUEUE_MAX = 16;\n\nconst WORKER_SCRIPT = `\nconst { parentPort } = require(\"node:worker_threads\");\n\nconst SCRIPT_STYLE_RE = /<(script|style)[^>]*>[\\\\s\\\\S]*?<\\\\/\\\\1>/gi;\nconst TAG_RE = /<[^>]+>/g;\nconst SPACE_RE = /\\\\s+/g;\nconst HREF_RE = /href\\\\s*=\\\\s*([\"'])(.*?)\\\\1/gi;\n\nconst extractText = (html) => {\n return String(html)\n .replace(SCRIPT_STYLE_RE, \" \")\n .replace(TAG_RE, \" \")\n .replace(SPACE_RE, \" \")\n .trim();\n};\n\nconst normalizeLink = (href, baseUrl) => {\n if (!href || href.startsWith(\"javascript:\") || href.startsWith(\"mailto:\") || href.startsWith(\"tel:\")) {\n return null;\n }\n try {\n return new URL(href, baseUrl).toString();\n } catch {\n return null;\n }\n};\n\nconst extractLinks = (html, baseUrl) => {\n const links = new Set();\n for (const match of String(html).matchAll(HREF_RE)) {\n const raw = match[2]?.trim();\n if (!raw) continue;\n const normalized = normalizeLink(raw, baseUrl);\n if (!normalized) continue;\n links.add(normalized);\n }\n return [...links];\n};\n\nconst selectorRegex = (selector) => {\n const safe = selector.replace(/[-/\\\\\\\\^$*+?.()|[\\\\]{}]/g, \"\\\\\\\\$&\");\n if (selector.startsWith(\"#\")) {\n const id = selector.slice(1).replace(/[-/\\\\\\\\^$*+?.()|[\\\\]{}]/g, \"\\\\\\\\$&\");\n return new RegExp(\\`<([a-z0-9-]+)[^>]*id=[\"']\\${id}[\"'][^>]*>([\\\\\\\\s\\\\\\\\S]*?)<\\\\\\\\/\\\\\\\\1>\\`, \"gi\");\n }\n if (selector.startsWith(\".\")) {\n const className = selector.slice(1).replace(/[-/\\\\\\\\^$*+?.()|[\\\\]{}]/g, \"\\\\\\\\$&\");\n return new RegExp(\\`<([a-z0-9-]+)[^>]*class=[\"'][^\"']*\\\\\\\\b\\${className}\\\\\\\\b[^\"']*[\"'][^>]*>([\\\\\\\\s\\\\\\\\S]*?)<\\\\\\\\/\\\\\\\\1>\\`, \"gi\");\n }\n return new RegExp(\\`<\\${safe}[^>]*>([\\\\\\\\s\\\\\\\\S]*?)<\\\\\\\\/\\${safe}>\\`, \"gi\");\n};\n\nconst extractSelectors = (html, selectors = []) => {\n const out = {};\n for (const selector of selectors) {\n const values = [];\n for (const match of String(html).matchAll(selectorRegex(selector))) {\n const text = extractText(match[2] ?? match[1] ?? \"\");\n if (text) values.push(text);\n }\n out[selector] = values;\n }\n return out;\n};\n\nconst extractStructuredContent = (html, baseUrl, selectors = []) => {\n return {\n text: extractText(html),\n links: extractLinks(html, baseUrl),\n selectors: extractSelectors(html, selectors)\n };\n};\n\nparentPort?.on(\"message\", (message) => {\n const id = typeof message?.id === \"number\" ? message.id : null;\n if (id === null) return;\n\n try {\n const extracted = extractStructuredContent(\n String(message.html ?? \"\"),\n String(message.url ?? \"\"),\n Array.isArray(message.selectors) ? message.selectors.map((value) => String(value)) : []\n );\n parentPort?.postMessage({\n id,\n ok: true,\n extracted\n });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n parentPort?.postMessage({\n id,\n ok: false,\n error: reason\n });\n }\n});\n`;\n\nconst supportsWorkerThreads = (): boolean => {\n return isMainThread && typeof Worker === \"function\";\n};\n\nconst toError = (error: unknown, fallback: string): Error => {\n if (error instanceof Error) return error;\n return new Error(error === undefined ? fallback : String(error));\n};\n\nconst emptyMetadata = (): ExtractedContent[\"metadata\"] => ({\n imageUrls: [],\n features: []\n});\n\nexport class CrawlWorkerPool {\n private readonly queueMax: number;\n private readonly queue: CrawlTask[] = [];\n private readonly inFlight = new Map<number, CrawlTask>();\n private readonly workers: WorkerHandle[] = [];\n private nextTaskId = 1;\n private inlineOnly: boolean;\n private closed = false;\n\n constructor(options: CrawlWorkerPoolOptions = {}) {\n const requestedWorkers = Math.max(0, Math.floor(options.workerThreads ?? DEFAULT_WORKER_THREADS));\n this.queueMax = Math.max(1, Math.floor(options.queueMax ?? DEFAULT_QUEUE_MAX));\n this.inlineOnly = options.forceInline === true || requestedWorkers === 0 || !supportsWorkerThreads();\n\n if (!this.inlineOnly) {\n for (let index = 0; index < requestedWorkers; index += 1) {\n this.spawnWorker();\n }\n if (this.workers.length === 0) {\n this.inlineOnly = true;\n }\n }\n }\n\n async extract(input: CrawlExtractInput): Promise<ExtractedContent> {\n if (this.closed) {\n throw new Error(\"crawl_worker_pool_closed\");\n }\n\n if (this.inlineOnly) {\n return extractStructuredContent(input.html, input.url, input.selectors);\n }\n\n if (this.queue.length + this.inFlight.size >= this.queueMax) {\n throw new Error(`crawl_worker_queue_overflow:${this.queueMax}`);\n }\n\n const taskId = this.nextTaskId;\n this.nextTaskId += 1;\n\n return new Promise<ExtractedContent>((resolve, reject) => {\n this.queue.push({ id: taskId, input, resolve, reject });\n this.dispatch();\n });\n }\n\n async close(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n\n const closingError = new Error(\"crawl_worker_pool_closed\");\n for (const task of this.queue.splice(0)) {\n task.reject(closingError);\n }\n for (const task of this.inFlight.values()) {\n task.reject(closingError);\n }\n this.inFlight.clear();\n\n const handles = this.workers.splice(0);\n await Promise.all(handles.map((handle) => {\n return handle.worker.terminate()\n .then(() => undefined)\n .catch(() => undefined);\n }));\n }\n\n private spawnWorker(): void {\n try {\n const worker = new Worker(WORKER_SCRIPT, {\n eval: true\n });\n const handle: WorkerHandle = {\n worker,\n busy: false\n };\n\n worker.on(\"message\", (message: unknown) => {\n this.handleWorkerMessage(handle, message);\n });\n\n worker.on(\"error\", (error) => {\n this.handleWorkerFailure(handle, error);\n });\n\n worker.on(\"exit\", (code) => {\n if (code !== 0) {\n this.handleWorkerFailure(handle, new Error(`crawl_worker_exit:${code}`));\n }\n });\n\n this.workers.push(handle);\n } catch {\n this.inlineOnly = true;\n }\n }\n\n private dispatch(): void {\n if (this.inlineOnly || this.closed) return;\n for (const handle of this.workers) {\n if (handle.busy) continue;\n const task = this.queue.shift();\n if (!task) return;\n\n handle.busy = true;\n handle.taskId = task.id;\n this.inFlight.set(task.id, task);\n\n const request: WorkerExtractRequest = {\n id: task.id,\n url: task.input.url,\n html: task.input.html,\n selectors: task.input.selectors\n };\n\n try {\n handle.worker.postMessage(request);\n } catch (error) {\n this.inFlight.delete(task.id);\n handle.busy = false;\n handle.taskId = undefined;\n this.resolveTaskInline(task, error);\n }\n }\n }\n\n private handleWorkerMessage(handle: WorkerHandle, message: unknown): void {\n const response = this.parseWorkerResponse(message);\n const taskId = response?.id ?? handle.taskId;\n if (taskId === undefined) {\n handle.busy = false;\n handle.taskId = undefined;\n this.dispatch();\n return;\n }\n\n const task = this.inFlight.get(taskId);\n this.inFlight.delete(taskId);\n handle.busy = false;\n handle.taskId = undefined;\n\n if (!task) {\n this.dispatch();\n return;\n }\n\n if (response?.ok === true) {\n task.resolve(response.extracted);\n this.dispatch();\n return;\n }\n\n this.resolveTaskInline(task, response?.error);\n this.dispatch();\n }\n\n private handleWorkerFailure(handle: WorkerHandle, error: unknown): void {\n const taskId = handle.taskId;\n handle.busy = false;\n handle.taskId = undefined;\n\n if (taskId !== undefined) {\n const task = this.inFlight.get(taskId);\n if (task) {\n this.inFlight.delete(taskId);\n this.resolveTaskInline(task, error);\n }\n }\n\n const index = this.workers.indexOf(handle);\n if (index >= 0) {\n this.workers.splice(index, 1);\n }\n\n if (this.workers.length === 0) {\n this.inlineOnly = true;\n while (this.queue.length > 0) {\n const queuedTask = this.queue.shift();\n if (!queuedTask) continue;\n this.resolveTaskInline(queuedTask, error);\n }\n return;\n }\n\n this.dispatch();\n }\n\n private parseWorkerResponse(message: unknown): WorkerExtractResponse | null {\n if (!message || typeof message !== \"object\") return null;\n const candidate = message as Record<string, unknown>;\n if (typeof candidate.id !== \"number\") return null;\n if (candidate.ok === true) {\n const extracted = candidate.extracted;\n if (!extracted || typeof extracted !== \"object\") return null;\n const typedExtracted = extracted as Record<string, unknown>;\n if (typeof typedExtracted.text !== \"string\") return null;\n if (!Array.isArray(typedExtracted.links)) return null;\n if (!typedExtracted.selectors || typeof typedExtracted.selectors !== \"object\") return null;\n const selectors: Record<string, string[]> = {};\n for (const [key, value] of Object.entries(typedExtracted.selectors as Record<string, unknown>)) {\n selectors[key] = Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === \"string\")\n : [];\n }\n return {\n id: candidate.id,\n ok: true,\n extracted: {\n text: typedExtracted.text,\n links: typedExtracted.links\n .filter((value): value is string => typeof value === \"string\"),\n selectors,\n metadata: emptyMetadata()\n }\n };\n }\n\n return {\n id: candidate.id,\n ok: false,\n error: typeof candidate.error === \"string\" ? candidate.error : \"worker_parse_failed\"\n };\n }\n\n private resolveTaskInline(task: CrawlTask, cause: unknown): void {\n try {\n task.resolve(extractStructuredContent(task.input.html, task.input.url, task.input.selectors));\n } catch (error) {\n task.reject(toError(error, toError(cause, \"crawl_worker_inline_failed\").message));\n }\n }\n}\n\nexport const extractCrawlContentInline = (input: CrawlExtractInput): ExtractedContent => {\n return extractStructuredContent(input.html, input.url, input.selectors);\n};\n\nexport const createCrawlWorkerPool = (\n options: CrawlWorkerPoolOptions = {}\n): CrawlWorkerPool => {\n return new CrawlWorkerPool(options);\n};\n\nexport const __test__ = {\n supportsWorkerThreads,\n toError\n};\n","export interface ExtractedPrice {\n amount: number;\n currency: string;\n source: string;\n}\n\nexport interface ExtractedMetadata {\n title?: string;\n description?: string;\n brand?: string;\n siteName?: string;\n imageUrls: string[];\n features: string[];\n price?: ExtractedPrice;\n}\n\nexport interface ExtractedContent {\n text: string;\n links: string[];\n selectors: Record<string, string[]>;\n metadata: ExtractedMetadata;\n}\n\nconst SCRIPT_STYLE_RE = /<(script|style)[^>]*>[\\s\\S]*?<\\/\\1>/gi;\nconst TAG_RE = /<[^>]+>/g;\nconst SPACE_RE = /\\s+/g;\nconst HREF_RE = /href\\s*=\\s*([\"'])(.*?)\\1/gi;\nconst TITLE_RE = /<title[^>]*>([\\s\\S]*?)<\\/title>/i;\nconst META_TAG_RE = /<meta\\b[^>]*>/gi;\nconst JSON_LD_RE = /<script\\b[^>]*type=[\"']application\\/ld\\+json[\"'][^>]*>([\\s\\S]*?)<\\/script>/gi;\nconst LIST_ITEM_RE = /<li\\b[^>]*>([\\s\\S]*?)<\\/li>/gi;\nconst FEATURE_BLOCK_RE = /<(?:div|p|span)[^>]*class=([\"'])[^\"'<>]*(?:feature|highlight|benefit|bullet|spec)[^\"'<>]*\\1[^>]*>([\\s\\S]*?)<\\/(?:div|p|span)>/gi;\nconst IMAGE_TAG_RE = /<(?:img|source)\\b[^>]*>/gi;\nconst DEFAULT_CURRENCY = \"USD\";\nconst REJECT_IMAGE_URL_RE = /(?:^|[/?#_.-])(logo|icon|sprite|badge|avatar|placeholder|pixel|tracking|favicon)(?:[/?#_.-]|$)|\\.(?:svg|ico)(?:$|[?#])/i;\n\nconst HTML_ENTITY_MAP: Record<string, string> = {\n amp: \"&\",\n apos: \"'\",\n gt: \">\",\n lt: \"<\",\n nbsp: \" \",\n quot: \"\\\"\"\n};\n\nconst FEATURE_REJECT_RE = /^(quick view|compare|add to cart|previous page|next page|home)$/i;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n};\n\nconst decodeHtmlEntities = (value: string): string => {\n return value.replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (match, entity: string) => {\n const lower = entity.toLowerCase();\n if (lower in HTML_ENTITY_MAP) {\n return HTML_ENTITY_MAP[lower] ?? match;\n }\n if (lower.startsWith(\"#x\")) {\n const codePoint = Number.parseInt(lower.slice(2), 16);\n return Number.isFinite(codePoint) ? String.fromCodePoint(codePoint) : match;\n }\n if (lower.startsWith(\"#\")) {\n const codePoint = Number.parseInt(lower.slice(1), 10);\n return Number.isFinite(codePoint) ? String.fromCodePoint(codePoint) : match;\n }\n return match;\n });\n};\n\nconst normalizeWhitespace = (value: string): string => {\n return value.replace(SPACE_RE, \" \").trim();\n};\n\nconst normalizeText = (value: string): string => {\n return normalizeWhitespace(decodeHtmlEntities(value));\n};\n\nexport const extractText = (html: string): string => {\n return normalizeText(\n html\n .replace(SCRIPT_STYLE_RE, \" \")\n .replace(TAG_RE, \" \")\n );\n};\n\nconst normalizeLink = (href: string, baseUrl: string): string | null => {\n if (!href || href.startsWith(\"javascript:\") || href.startsWith(\"mailto:\") || href.startsWith(\"tel:\")) {\n return null;\n }\n\n try {\n return new URL(href, baseUrl).toString();\n } catch {\n return null;\n }\n};\n\nexport const extractLinks = (html: string, baseUrl: string): string[] => {\n const links = new Set<string>();\n for (const match of html.matchAll(HREF_RE)) {\n const raw = match[2]?.trim();\n if (!raw) continue;\n const normalized = normalizeLink(raw, baseUrl);\n if (!normalized) continue;\n links.add(normalized);\n }\n return [...links];\n};\n\nconst readAttribute = (tag: string, name: string): string | undefined => {\n const quoted = new RegExp(`${name}\\\\s*=\\\\s*([\"'])(.*?)\\\\1`, \"i\").exec(tag);\n if (quoted?.[2]) return normalizeText(quoted[2]);\n const unquoted = new RegExp(`${name}\\\\s*=\\\\s*([^\\\\s>]+)`, \"i\").exec(tag);\n if (unquoted?.[1]) return normalizeText(unquoted[1]);\n return undefined;\n};\n\nconst readMetaContent = (html: string, keys: string[]): string | undefined => {\n const keySet = new Set(keys.map((key) => key.toLowerCase()));\n for (const match of html.matchAll(META_TAG_RE)) {\n const tag = match[0];\n const name = readAttribute(tag, \"name\")?.toLowerCase();\n const property = readAttribute(tag, \"property\")?.toLowerCase();\n const content = readAttribute(tag, \"content\");\n if (!content) continue;\n if ((name && keySet.has(name)) || (property && keySet.has(property))) {\n return content;\n }\n }\n return undefined;\n};\n\nconst readSrcsetUrls = (value: string): string[] => {\n return value\n .split(\",\")\n .map((entry) => entry.trim().split(/\\s+/, 1)[0] ?? \"\")\n .filter((entry) => entry.length > 0);\n};\n\nconst readImageTagUrls = (html: string, baseUrl: string): string[] => {\n const urls = new Set<string>();\n for (const match of html.matchAll(IMAGE_TAG_RE)) {\n const tag = match[0];\n const directValues = [\n readAttribute(tag, \"src\"),\n readAttribute(tag, \"data-src\"),\n readAttribute(tag, \"data-lazy-src\"),\n readAttribute(tag, \"data-image\")\n ];\n for (const directValue of directValues) {\n const normalized = directValue ? normalizeLink(directValue, baseUrl) : null;\n if (!normalized || REJECT_IMAGE_URL_RE.test(normalized)) continue;\n urls.add(normalized);\n }\n\n const srcsetValues = [\n readAttribute(tag, \"srcset\"),\n readAttribute(tag, \"data-srcset\")\n ];\n for (const srcsetValue of srcsetValues) {\n if (!srcsetValue) continue;\n for (const entry of readSrcsetUrls(srcsetValue)) {\n const normalized = normalizeLink(entry, baseUrl);\n if (!normalized || REJECT_IMAGE_URL_RE.test(normalized)) continue;\n urls.add(normalized);\n }\n }\n }\n return [...urls];\n};\n\nconst flattenJsonLdNodes = (value: unknown): Array<Record<string, unknown>> => {\n if (Array.isArray(value)) {\n return value.flatMap((entry) => flattenJsonLdNodes(entry));\n }\n if (!isRecord(value)) {\n return [];\n }\n const graph = value[\"@graph\"];\n if (Array.isArray(graph)) {\n return [value, ...graph.flatMap((entry) => flattenJsonLdNodes(entry))];\n }\n return [value];\n};\n\nconst readSchemaTypes = (node: Record<string, unknown>): string[] => {\n const typeValue = node[\"@type\"];\n if (typeof typeValue === \"string\") return [typeValue];\n if (Array.isArray(typeValue)) {\n return typeValue.filter((entry): entry is string => typeof entry === \"string\");\n }\n return [];\n};\n\nconst readString = (value: unknown): string | undefined => {\n if (typeof value !== \"string\") return undefined;\n const normalized = normalizeText(value);\n return normalized.length > 0 ? normalized : undefined;\n};\n\nconst readNestedString = (value: unknown, key: string): string | undefined => {\n if (!isRecord(value)) return undefined;\n return readString(value[key]);\n};\n\nconst toStringArray = (value: unknown): string[] => {\n if (typeof value === \"string\") {\n return [value];\n }\n if (Array.isArray(value)) {\n return value.filter((entry): entry is string => typeof entry === \"string\");\n }\n if (isRecord(value)) {\n const nested = readString(value.url);\n return nested ? [nested] : [];\n }\n return [];\n};\n\nconst readNumber = (value: unknown): number | undefined => {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim()) {\n const parsed = Number(value.replace(/,/g, \"\"));\n if (Number.isFinite(parsed)) return parsed;\n }\n return undefined;\n};\n\nconst readPriceFromOfferNode = (value: unknown): ExtractedPrice | undefined => {\n if (Array.isArray(value)) {\n for (const entry of value) {\n const price = readPriceFromOfferNode(entry);\n if (price) return price;\n }\n return undefined;\n }\n if (!isRecord(value)) return undefined;\n const currency = readString(value.priceCurrency) ?? DEFAULT_CURRENCY;\n const exactPrice = readNumber(value.price);\n if (exactPrice !== undefined && exactPrice > 0) {\n return {\n amount: exactPrice,\n currency,\n source: \"jsonld:price\"\n };\n }\n const lowPrice = readNumber(value.lowPrice);\n if (lowPrice !== undefined && lowPrice > 0) {\n return {\n amount: lowPrice,\n currency,\n source: \"jsonld:lowPrice\"\n };\n }\n return readPriceFromOfferNode(value.priceSpecification);\n};\n\nconst readJsonLdMetadata = (html: string, baseUrl: string): Partial<ExtractedMetadata> => {\n const metadata: Partial<ExtractedMetadata> = {};\n const imageUrls = new Set<string>();\n\n for (const match of html.matchAll(JSON_LD_RE)) {\n const raw = match[1]?.trim();\n if (!raw) continue;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n continue;\n }\n\n const nodes = flattenJsonLdNodes(parsed);\n for (const node of nodes) {\n const types = readSchemaTypes(node).map((entry) => entry.toLowerCase());\n const isProduct = types.includes(\"product\");\n const isOffer = types.includes(\"offer\") || types.includes(\"aggregateoffer\");\n\n if (!metadata.title && isProduct) {\n metadata.title = readString(node.name);\n }\n if (!metadata.description && isProduct) {\n metadata.description = readString(node.description);\n }\n if (!metadata.brand && isProduct) {\n metadata.brand = readString(node.brand) ?? readNestedString(node.brand, \"name\");\n }\n if (metadata.price === undefined && (isProduct || isOffer)) {\n metadata.price = readPriceFromOfferNode(node.offers) ?? readPriceFromOfferNode(node);\n }\n if (isProduct) {\n for (const imageValue of toStringArray(node.image)) {\n const normalized = normalizeLink(imageValue, baseUrl);\n if (normalized) imageUrls.add(normalized);\n }\n }\n }\n }\n\n if (imageUrls.size > 0) {\n metadata.imageUrls = [...imageUrls];\n }\n return metadata;\n};\n\nconst isLikelyFeature = (value: string): boolean => {\n if (value.length < 8 || value.length > 180) return false;\n if (!/[a-z]/i.test(value)) return false;\n if (FEATURE_REJECT_RE.test(value)) return false;\n if (value.endsWith(\"?\")) return false;\n if (/\\$(?:\\d|[€£])/.test(value)) return false;\n if (/learn more|free shipping|returns? & orders|select address/i.test(value)) return false;\n return true;\n};\n\nconst pushFeature = (target: string[], value: string): void => {\n const normalized = normalizeText(value);\n if (!isLikelyFeature(normalized)) return;\n if (!target.includes(normalized)) {\n target.push(normalized);\n }\n};\n\nconst extractFeatureCandidates = (html: string): string[] => {\n const features: string[] = [];\n\n for (const match of html.matchAll(FEATURE_BLOCK_RE)) {\n pushFeature(features, extractText(match[2] ?? \"\"));\n if (features.length >= 12) return features;\n }\n\n for (const match of html.matchAll(LIST_ITEM_RE)) {\n pushFeature(features, extractText(match[1] ?? \"\"));\n if (features.length >= 12) return features;\n }\n\n return features;\n};\n\nexport const extractMetadata = (html: string, baseUrl: string): ExtractedMetadata => {\n const jsonLd = readJsonLdMetadata(html, baseUrl);\n const title = readMetaContent(html, [\"og:title\", \"twitter:title\"])\n ?? jsonLd.title\n ?? (() => {\n const match = TITLE_RE.exec(html);\n return match?.[1] ? normalizeText(match[1]) : undefined;\n })();\n const description = readMetaContent(html, [\"description\", \"og:description\", \"twitter:description\"])\n ?? jsonLd.description;\n const siteName = readMetaContent(html, [\"og:site_name\", \"application-name\"]);\n const brand = jsonLd.brand\n ?? readMetaContent(html, [\"product:brand\", \"brand\"])\n ?? siteName;\n\n const imageUrls = new Set<string>(jsonLd.imageUrls ?? []);\n const metaImages = [\n readMetaContent(html, [\"og:image\"]),\n readMetaContent(html, [\"twitter:image\"])\n ].filter((entry): entry is string => Boolean(entry));\n for (const imageUrl of metaImages) {\n const normalized = normalizeLink(imageUrl, baseUrl);\n if (normalized) imageUrls.add(normalized);\n }\n for (const imageUrl of readImageTagUrls(html, baseUrl)) {\n imageUrls.add(imageUrl);\n }\n\n return {\n ...(title ? { title } : {}),\n ...(description ? { description } : {}),\n ...(brand ? { brand } : {}),\n ...(siteName ? { siteName } : {}),\n imageUrls: [...imageUrls],\n features: extractFeatureCandidates(html),\n ...(jsonLd.price ? { price: jsonLd.price } : {})\n };\n};\n\nconst selectorRegex = (selector: string): RegExp => {\n const safe = selector.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\");\n if (selector.startsWith(\"#\")) {\n const id = selector.slice(1).replace(/[-/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\");\n return new RegExp(`<([a-z0-9-]+)[^>]*id=[\"']${id}[\"'][^>]*>([\\\\s\\\\S]*?)<\\\\/\\\\1>`, \"gi\");\n }\n if (selector.startsWith(\".\")) {\n const className = selector.slice(1).replace(/[-/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\");\n return new RegExp(`<([a-z0-9-]+)[^>]*class=[\"'][^\"']*\\\\b${className}\\\\b[^\"']*[\"'][^>]*>([\\\\s\\\\S]*?)<\\\\/\\\\1>`, \"gi\");\n }\n return new RegExp(`<${safe}[^>]*>([\\\\s\\\\S]*?)<\\\\/${safe}>`, \"gi\");\n};\n\nexport const extractSelectors = (html: string, selectors: string[] = []): Record<string, string[]> => {\n const out: Record<string, string[]> = {};\n for (const selector of selectors) {\n const values: string[] = [];\n for (const match of html.matchAll(selectorRegex(selector))) {\n const text = extractText(match[2] ?? match[1] ?? \"\");\n if (text) {\n values.push(text);\n }\n }\n out[selector] = values;\n }\n return out;\n};\n\nexport const extractStructuredContent = (\n html: string,\n baseUrl: string,\n selectors: string[] = []\n): ExtractedContent => {\n return {\n text: extractText(html),\n links: extractLinks(html, baseUrl),\n selectors: extractSelectors(html, selectors),\n metadata: extractMetadata(html, baseUrl)\n };\n};\n\nexport const toSnippet = (text: string, maxChars = 280): string => {\n if (text.length <= maxChars) return text;\n return `${text.slice(0, Math.max(0, maxChars - 1))}…`;\n};\n","import { evaluateWebCrawlPolicy, type WebCrawlPolicy } from \"./policy\";\nimport { createCrawlWorkerPool, extractCrawlContentInline, type CrawlWorkerPool } from \"./crawl-worker\";\nimport type { CrawlStrategy } from \"../types\";\n\nexport interface CrawlBudget {\n maxDepth: number;\n maxPages: number;\n maxPerDomain: number;\n}\n\nexport interface CrawlPipelineBudget {\n workerThreads: number;\n queueMax: number;\n fetchConcurrency: number;\n frontierMax: number;\n}\n\nexport interface CrawlPage {\n url: string;\n canonicalUrl: string;\n depth: number;\n status: number;\n text: string;\n links: string[];\n selectors: Record<string, string[]>;\n warnings: string[];\n}\n\nexport interface CrawlMetrics {\n visited: number;\n fetched: number;\n deduped: number;\n elapsedMs: number;\n pagesPerMinute: number;\n p50LatencyMs: number;\n p95LatencyMs: number;\n}\n\nexport interface CrawlResult {\n pages: CrawlPage[];\n graph: Array<{ from: string; to: string }>;\n warnings: string[];\n metrics: CrawlMetrics;\n}\n\nexport interface CrawlFetcherResponse {\n url?: string;\n html: string;\n status?: number;\n}\n\nexport type CrawlFetcher = (url: string) => Promise<CrawlFetcherResponse>;\n\nexport interface CrawlOptions {\n seeds: string[];\n strategy?: CrawlStrategy;\n budget?: Partial<CrawlBudget>;\n policy?: WebCrawlPolicy;\n selectors?: string[];\n pipeline?: Partial<CrawlPipelineBudget>;\n workerThreads?: number;\n queueMax?: number;\n forceInlineParse?: boolean;\n fetcher: CrawlFetcher;\n}\n\ninterface FrontierNode {\n url: string;\n depth: number;\n sequence: number;\n firstSeenOrder: number;\n firstSeenAtMs: number;\n sourcePriority: number;\n stableRecordId: string;\n}\n\ninterface CrawlTaskResult {\n sequence: number;\n firstSeenAtMs: number;\n sourcePriority: number;\n stableRecordId: string;\n page: CrawlPage | null;\n links: string[];\n warnings: string[];\n latencyMs: number;\n}\n\ninterface CrawlPageEntry {\n page: CrawlPage;\n firstSeenAtMs: number;\n sourcePriority: number;\n stableRecordId: string;\n sequence: number;\n}\n\nconst DEFAULT_BUDGET: CrawlBudget = {\n maxDepth: 2,\n maxPages: 20,\n maxPerDomain: 10\n};\n\nconst DEFAULT_PIPELINE: CrawlPipelineBudget = {\n workerThreads: 2,\n queueMax: 64,\n fetchConcurrency: 4,\n frontierMax: 256\n};\n\nconst TRACKING_QUERY_KEYS = new Set([\n \"utm_source\",\n \"utm_medium\",\n \"utm_campaign\",\n \"utm_term\",\n \"utm_content\",\n \"gclid\",\n \"fbclid\"\n]);\n\nexport const canonicalizeUrl = (rawUrl: string): string => {\n let parsed: URL;\n try {\n parsed = new URL(rawUrl);\n } catch {\n return rawUrl.trim();\n }\n\n parsed.hash = \"\";\n parsed.protocol = parsed.protocol.toLowerCase();\n parsed.hostname = parsed.hostname.toLowerCase();\n\n if ((parsed.protocol === \"http:\" && parsed.port === \"80\") || (parsed.protocol === \"https:\" && parsed.port === \"443\")) {\n parsed.port = \"\";\n }\n\n const next = new URL(parsed.toString());\n const params = [...next.searchParams.entries()]\n .filter(([key]) => !TRACKING_QUERY_KEYS.has(key.toLowerCase()))\n .sort(([a], [b]) => a.localeCompare(b));\n next.search = \"\";\n for (const [key, value] of params) {\n next.searchParams.append(key, value);\n }\n\n if (next.pathname.length > 1 && next.pathname.endsWith(\"/\")) {\n next.pathname = next.pathname.slice(0, -1);\n }\n\n if (next.pathname === \"/\") {\n return `${next.protocol}//${next.host}${next.search}`;\n }\n\n return next.toString();\n};\n\nconst percentile = (values: number[], ratio: number): number => {\n if (values.length === 0) return 0;\n const sorted = [...values].sort((a, b) => a - b);\n const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * ratio) - 1));\n return sorted[index] ?? 0;\n};\n\nconst isHttpUrl = (value: string): boolean => {\n try {\n const protocol = new URL(value).protocol;\n return protocol === \"http:\" || protocol === \"https:\";\n } catch {\n return false;\n }\n};\n\nconst compareFrontierNodes = (\n left: FrontierNode,\n right: FrontierNode,\n strategy: CrawlStrategy\n): number => {\n if (left.depth !== right.depth) {\n return strategy === \"dfs\"\n ? right.depth - left.depth\n : left.depth - right.depth;\n }\n if (left.firstSeenOrder !== right.firstSeenOrder) {\n return strategy === \"dfs\"\n ? right.firstSeenOrder - left.firstSeenOrder\n : left.firstSeenOrder - right.firstSeenOrder;\n }\n if (left.sourcePriority !== right.sourcePriority) {\n return left.sourcePriority - right.sourcePriority;\n }\n if (left.sequence !== right.sequence) {\n return strategy === \"dfs\"\n ? right.sequence - left.sequence\n : left.sequence - right.sequence;\n }\n return left.url.localeCompare(right.url);\n};\n\nconst dequeueNode = (\n frontier: FrontierNode[],\n strategy: CrawlStrategy\n): FrontierNode | undefined => {\n if (frontier.length === 0) return undefined;\n frontier.sort((left, right) => compareFrontierNodes(left, right, strategy));\n return frontier.shift();\n};\n\nconst resolveFrontierDomain = (url: string): string => {\n try {\n return new URL(url).hostname.toLowerCase();\n } catch {\n return \"__invalid__\";\n }\n};\n\nconst enqueueFrontierNode = (\n frontierByDomain: Map<string, FrontierNode[]>,\n node: FrontierNode\n): void => {\n const domain = resolveFrontierDomain(node.url);\n const queue = frontierByDomain.get(domain) ?? [];\n queue.push(node);\n frontierByDomain.set(domain, queue);\n};\n\nconst frontierSize = (frontierByDomain: Map<string, FrontierNode[]>): number => {\n let size = 0;\n for (const queue of frontierByDomain.values()) {\n size += queue.length;\n }\n return size;\n};\n\nconst dequeueFrontierByDomain = (\n frontierByDomain: Map<string, FrontierNode[]>,\n strategy: CrawlStrategy\n): FrontierNode | undefined => {\n let selectedDomain: string | undefined;\n let selected: FrontierNode | undefined;\n\n for (const [domain, queue] of frontierByDomain.entries()) {\n if (queue.length === 0) continue;\n queue.sort((left, right) => compareFrontierNodes(left, right, strategy));\n const candidate = queue[0];\n if (!candidate) continue;\n if (!selected || compareFrontierNodes(candidate, selected, strategy) < 0) {\n selected = candidate;\n selectedDomain = domain;\n }\n }\n\n if (!selectedDomain || !selected) {\n return undefined;\n }\n\n const queue = frontierByDomain.get(selectedDomain);\n if (!queue || queue.length === 0) {\n return undefined;\n }\n const next = queue.shift();\n if (queue.length === 0) {\n frontierByDomain.delete(selectedDomain);\n }\n return next;\n};\n\nconst waitForNextTask = async (\n tasks: Map<number, Promise<CrawlTaskResult>>\n): Promise<CrawlTaskResult> => {\n return Promise.race([...tasks.values()]);\n};\n\nconst sortPageEntries = (entries: CrawlPageEntry[]): CrawlPage[] => {\n return [...entries]\n .sort((left, right) => {\n if (left.firstSeenAtMs !== right.firstSeenAtMs) {\n return left.firstSeenAtMs - right.firstSeenAtMs;\n }\n if (left.sourcePriority !== right.sourcePriority) {\n return left.sourcePriority - right.sourcePriority;\n }\n if (left.stableRecordId !== right.stableRecordId) {\n return left.stableRecordId.localeCompare(right.stableRecordId);\n }\n return left.sequence - right.sequence;\n })\n .map((entry) => entry.page);\n};\n\nconst executeTask = async (args: {\n node: FrontierNode;\n fetcher: CrawlFetcher;\n selectors: string[];\n policyWarnings: string[];\n workerPool: CrawlWorkerPool;\n}): Promise<CrawlTaskResult> => {\n const startedAt = Date.now();\n const taskWarnings: string[] = [];\n let status = 0;\n let html = \"\";\n\n try {\n const response = await args.fetcher(args.node.url);\n status = response.status ?? 200;\n html = response.html;\n } catch {\n taskWarnings.push(`${args.node.url}: fetch failed`);\n return {\n sequence: args.node.sequence,\n firstSeenAtMs: args.node.firstSeenAtMs,\n sourcePriority: args.node.sourcePriority,\n stableRecordId: args.node.stableRecordId,\n page: null,\n links: [],\n warnings: taskWarnings,\n latencyMs: Math.max(0, Date.now() - startedAt)\n };\n }\n\n let extracted = extractCrawlContentInline({\n url: args.node.url,\n html,\n selectors: args.selectors\n });\n try {\n extracted = await args.workerPool.extract({\n url: args.node.url,\n html,\n selectors: args.selectors\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (message.startsWith(\"crawl_worker_queue_overflow:\")) {\n taskWarnings.push(`${args.node.url}: worker queue saturated`);\n } else {\n taskWarnings.push(`${args.node.url}: worker extraction fallback`);\n }\n }\n\n const links = extracted.links\n .map((link) => canonicalizeUrl(link))\n .filter((link) => isHttpUrl(link));\n\n return {\n sequence: args.node.sequence,\n firstSeenAtMs: args.node.firstSeenAtMs,\n sourcePriority: args.node.sourcePriority,\n stableRecordId: args.node.stableRecordId,\n page: {\n url: args.node.url,\n canonicalUrl: args.node.url,\n depth: args.node.depth,\n status,\n text: extracted.text,\n links,\n selectors: extracted.selectors,\n warnings: args.policyWarnings\n },\n links,\n warnings: taskWarnings,\n latencyMs: Math.max(0, Date.now() - startedAt)\n };\n};\n\nexport const crawlWeb = async (options: CrawlOptions): Promise<CrawlResult> => {\n const startedAt = Date.now();\n const budget: CrawlBudget = {\n ...DEFAULT_BUDGET,\n ...(options.budget ?? {})\n };\n const pipeline: CrawlPipelineBudget = {\n ...DEFAULT_PIPELINE,\n ...(options.pipeline ?? {}),\n ...(typeof options.workerThreads === \"number\" ? { workerThreads: options.workerThreads } : {}),\n ...(typeof options.queueMax === \"number\" ? { queueMax: options.queueMax } : {})\n };\n\n const strategy: CrawlStrategy = options.strategy ?? \"bfs\";\n const fetchConcurrency = Math.max(1, Math.floor(pipeline.fetchConcurrency));\n const workerPool = createCrawlWorkerPool({\n workerThreads: pipeline.workerThreads,\n queueMax: pipeline.queueMax,\n forceInline: options.forceInlineParse\n });\n\n let nextSequence = 0;\n let nextFirstSeenOrder = 0;\n const frontierByDomain = new Map<string, FrontierNode[]>();\n const visited = new Set<string>();\n const queued = new Set<string>();\n for (const seed of options.seeds) {\n const canonicalSeed = canonicalizeUrl(seed);\n const node: FrontierNode = {\n url: canonicalSeed,\n depth: 0,\n sequence: nextSequence++,\n firstSeenOrder: nextFirstSeenOrder,\n firstSeenAtMs: startedAt + nextFirstSeenOrder,\n sourcePriority: 0,\n stableRecordId: canonicalSeed\n };\n nextFirstSeenOrder += 1;\n enqueueFrontierNode(frontierByDomain, node);\n queued.add(canonicalSeed);\n }\n const domainCounts = new Map<string, number>();\n const pageEntries: CrawlPageEntry[] = [];\n const graph: Array<{ from: string; to: string }> = [];\n const warnings: string[] = [];\n const latencies: number[] = [];\n let deduped = 0;\n\n const inFlight = new Map<number, Promise<CrawlTaskResult>>();\n const completed = new Map<number, CrawlTaskResult>();\n const scheduledOrder: number[] = [];\n let appliedOrderIndex = 0;\n\n try {\n while (frontierSize(frontierByDomain) > 0 || inFlight.size > 0) {\n while (\n frontierSize(frontierByDomain) > 0\n && inFlight.size < fetchConcurrency\n && pageEntries.length + inFlight.size < budget.maxPages\n ) {\n const node = dequeueFrontierByDomain(frontierByDomain, strategy);\n if (!node) break;\n\n queued.delete(node.url);\n if (visited.has(node.url)) {\n deduped += 1;\n continue;\n }\n\n const decision = evaluateWebCrawlPolicy(node.url, options.policy);\n if (!decision.allowed) {\n warnings.push(`${node.url}: ${decision.reason ?? \"blocked\"}`);\n continue;\n }\n if (decision.warnings.length > 0) {\n warnings.push(...decision.warnings.map((warning) => `${node.url}: ${warning}`));\n }\n\n let hostname: string;\n try {\n hostname = new URL(node.url).hostname.toLowerCase();\n } catch {\n warnings.push(`${node.url}: invalid hostname`);\n continue;\n }\n\n const currentDomainCount = domainCounts.get(hostname) ?? 0;\n if (currentDomainCount >= budget.maxPerDomain) {\n warnings.push(`${node.url}: per-domain budget exceeded`);\n continue;\n }\n\n visited.add(node.url);\n domainCounts.set(hostname, currentDomainCount + 1);\n\n const task = executeTask({\n node,\n fetcher: options.fetcher,\n selectors: options.selectors ?? [],\n policyWarnings: decision.warnings,\n workerPool\n });\n inFlight.set(node.sequence, task);\n scheduledOrder.push(node.sequence);\n }\n\n if (inFlight.size === 0) {\n break;\n }\n\n const completedTask = await waitForNextTask(inFlight);\n inFlight.delete(completedTask.sequence);\n completed.set(completedTask.sequence, completedTask);\n\n while (appliedOrderIndex < scheduledOrder.length) {\n const sequence = scheduledOrder[appliedOrderIndex];\n if (typeof sequence !== \"number\") break;\n const ready = completed.get(sequence);\n if (!ready) break;\n\n appliedOrderIndex += 1;\n completed.delete(sequence);\n latencies.push(ready.latencyMs);\n if (ready.warnings.length > 0) {\n warnings.push(...ready.warnings);\n }\n if (!ready.page) {\n continue;\n }\n\n pageEntries.push({\n page: ready.page,\n firstSeenAtMs: ready.firstSeenAtMs,\n sourcePriority: ready.sourcePriority,\n stableRecordId: ready.stableRecordId,\n sequence: ready.sequence\n });\n if (pageEntries.length >= budget.maxPages) {\n continue;\n }\n\n for (const link of ready.links) {\n graph.push({ from: ready.page.url, to: link });\n if (ready.page.depth >= budget.maxDepth) continue;\n\n const linkDecision = evaluateWebCrawlPolicy(link, options.policy);\n if (!linkDecision.allowed) {\n warnings.push(`${link}: ${linkDecision.reason ?? \"blocked\"}`);\n continue;\n }\n if (linkDecision.warnings.length > 0) {\n warnings.push(...linkDecision.warnings.map((warning) => `${link}: ${warning}`));\n }\n\n if (visited.has(link) || queued.has(link)) {\n deduped += 1;\n continue;\n }\n if (frontierSize(frontierByDomain) >= pipeline.frontierMax) {\n warnings.push(`${link}: crawl frontier saturated`);\n continue;\n }\n\n const node: FrontierNode = {\n url: link,\n depth: ready.page.depth + 1,\n sequence: nextSequence++,\n firstSeenOrder: nextFirstSeenOrder,\n firstSeenAtMs: startedAt + nextFirstSeenOrder,\n sourcePriority: 1,\n stableRecordId: canonicalizeUrl(link)\n };\n nextFirstSeenOrder += 1;\n enqueueFrontierNode(frontierByDomain, node);\n queued.add(link);\n }\n }\n }\n } finally {\n await workerPool.close();\n }\n\n const pages = sortPageEntries(pageEntries);\n const elapsedMs = Math.max(1, Date.now() - startedAt);\n const pagesPerMinute = pages.length / (elapsedMs / 60000);\n\n return {\n pages,\n graph,\n warnings,\n metrics: {\n visited: visited.size,\n fetched: pages.length,\n deduped,\n elapsedMs,\n pagesPerMinute,\n p50LatencyMs: percentile(latencies, 0.5),\n p95LatencyMs: percentile(latencies, 0.95)\n }\n };\n};\n\nexport const __test__ = {\n percentile,\n isHttpUrl,\n compareFrontierNodes,\n dequeueNode,\n resolveFrontierDomain,\n enqueueFrontierNode,\n frontierSize,\n dequeueFrontierByDomain,\n sortPageEntries,\n waitForNextTask\n};\n","import { ProviderRuntimeError } from \"../errors\";\nimport { normalizeRecord, normalizeRecords } from \"../normalize\";\nimport { assertPostPolicy, type PostPolicyHook } from \"../shared/post-policy\";\nimport { isLikelyDocumentUrl } from \"../shared/traversal-url\";\nimport { canonicalizeUrl } from \"../web/crawler\";\nimport type {\n JsonValue,\n NormalizedRecord,\n ProviderAdapter,\n ProviderCapabilities,\n ProviderContext,\n ProviderCrawlInput,\n ProviderFetchInput,\n ProviderPostInput,\n ProviderSearchInput\n} from \"../types\";\n\nconst COMMUNITY_SOURCE = \"community\" as const;\n\ntype CommunityRow = {\n url: string;\n title?: string;\n content?: string;\n confidence?: number;\n attributes?: Record<string, JsonValue>;\n};\n\ntype CommunityFetchRow = {\n url?: string;\n title?: string;\n content?: string;\n attributes?: Record<string, JsonValue>;\n};\n\ninterface TraversalNode {\n url: string;\n hop: number;\n page: number;\n parent: string;\n}\n\nexport interface CommunityTraversalBudget {\n pageLimit: number;\n hopLimit: number;\n expansionPerRecord: number;\n maxRecords: number;\n}\n\nexport interface CommunityProviderOptions {\n id?: string;\n platform?: string;\n search?: (input: ProviderSearchInput, context: ProviderContext) => Promise<CommunityRow[]>;\n fetch?: (input: ProviderFetchInput, context: ProviderContext) => Promise<CommunityFetchRow>;\n crawl?: (input: ProviderCrawlInput, context: ProviderContext) => Promise<Array<{ url: string; title?: string; content?: string; attributes?: Record<string, JsonValue> }>>;\n post?: (input: ProviderPostInput, context: ProviderContext) => Promise<{ url?: string; title?: string; content?: string; attributes?: Record<string, JsonValue> }>;\n postPolicyHooks?: PostPolicyHook[];\n defaultTraversal?: Partial<CommunityTraversalBudget>;\n}\n\nconst DEFAULT_TRAVERSAL: CommunityTraversalBudget = {\n pageLimit: 2,\n hopLimit: 1,\n expansionPerRecord: 5,\n maxRecords: 25\n};\n\nconst LINK_RE = /https?:\\/\\/[^\\s\"'<>]+/g;\n\nconst createCapabilities = (id: string, platform: string): ProviderCapabilities => ({\n providerId: id,\n source: COMMUNITY_SOURCE,\n operations: {\n search: { op: \"search\", supported: true, description: \"Search community threads\" },\n fetch: { op: \"fetch\", supported: true, description: \"Fetch a community thread or post\" },\n crawl: { op: \"crawl\", supported: true, description: \"Crawl linked community discussions\" },\n post: { op: \"post\", supported: true, description: \"Create a community post with policy gates\" }\n },\n policy: {\n posting: \"gated\",\n riskNoticeRequired: true,\n confirmationRequired: true\n },\n metadata: {\n platform,\n source: COMMUNITY_SOURCE\n }\n});\n\nconst asNumber = (value: JsonValue | undefined): number | undefined => {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim()) {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) return parsed;\n }\n return undefined;\n};\n\nconst toPositiveInt = (value: number | undefined, fallback: number): number => {\n if (typeof value !== \"number\" || Number.isNaN(value)) return fallback;\n return Math.max(1, Math.floor(value));\n};\n\nconst toNonNegativeInt = (value: number | undefined, fallback: number): number => {\n if (typeof value !== \"number\" || Number.isNaN(value)) return fallback;\n return Math.max(0, Math.floor(value));\n};\n\nconst isHttpUrl = (value: string): boolean => {\n try {\n const protocol = new URL(value).protocol;\n return protocol === \"http:\" || protocol === \"https:\";\n } catch {\n return false;\n }\n};\n\nconst coerceStringArray = (value: JsonValue | undefined): string[] => {\n if (!Array.isArray(value)) return [];\n return value.filter((entry): entry is string => typeof entry === \"string\");\n};\n\nconst extractLinks = (\n row: { attributes?: Record<string, JsonValue>; content?: string },\n fallbackUrl: string\n): string[] => {\n const attributeLinks = [\n ...coerceStringArray(row.attributes?.links),\n ...coerceStringArray(row.attributes?.threadLinks),\n ...coerceStringArray(row.attributes?.replyLinks),\n ...coerceStringArray(row.attributes?.relatedUrls)\n ];\n const contentLinks = [...(row.content?.match(LINK_RE) ?? [])];\n const deduped = new Set<string>();\n for (const candidate of [...attributeLinks, ...contentLinks]) {\n const canonical = canonicalizeUrl(candidate);\n if (!isHttpUrl(canonical) || canonical === fallbackUrl || !isLikelyDocumentUrl(canonical)) continue;\n deduped.add(canonical);\n }\n return [...deduped].sort((left, right) => left.localeCompare(right));\n};\n\nconst qualityFlags = (args: {\n url: string;\n title?: string;\n content?: string;\n page: number;\n hop: number;\n expandedLinks: number;\n}): Record<string, JsonValue> => ({\n hasUrl: args.url.length > 0,\n hasTitle: typeof args.title === \"string\" && args.title.length > 0,\n hasContent: typeof args.content === \"string\" && args.content.length > 0,\n contentChars: args.content?.length ?? 0,\n page: args.page,\n hop: args.hop,\n expanded: args.hop > 0,\n expandedLinks: args.expandedLinks\n});\n\nconst mergedTraversal = (\n options: CommunityProviderOptions,\n input: { limit?: number; filters?: Record<string, JsonValue> }\n): CommunityTraversalBudget => {\n const filters = input.filters ?? {};\n return {\n pageLimit: toPositiveInt(\n asNumber(filters.pageLimit) ?? options.defaultTraversal?.pageLimit,\n DEFAULT_TRAVERSAL.pageLimit\n ),\n hopLimit: toNonNegativeInt(\n asNumber(filters.hopLimit) ?? options.defaultTraversal?.hopLimit,\n DEFAULT_TRAVERSAL.hopLimit\n ),\n expansionPerRecord: toNonNegativeInt(\n asNumber(filters.expansionPerRecord) ?? options.defaultTraversal?.expansionPerRecord,\n DEFAULT_TRAVERSAL.expansionPerRecord\n ),\n maxRecords: toPositiveInt(\n input.limit ?? asNumber(filters.maxRecords) ?? options.defaultTraversal?.maxRecords,\n DEFAULT_TRAVERSAL.maxRecords\n )\n };\n};\n\nconst unavailable = (id: string, message: string): ProviderRuntimeError => {\n return new ProviderRuntimeError(\"unavailable\", message, {\n provider: id,\n source: COMMUNITY_SOURCE\n });\n};\n\nconst shouldSkipExpansionError = (error: unknown): boolean => {\n if (!(error instanceof ProviderRuntimeError)) return false;\n return error.code === \"auth\"\n || error.code === \"network\"\n || error.code === \"rate_limited\"\n || error.code === \"timeout\"\n || error.code === \"unavailable\"\n || error.code === \"upstream\";\n};\n\nconst sortRows = <T extends { url: string; title?: string }>(rows: T[]): T[] => {\n return [...rows].sort((left, right) => {\n const leftUrl = canonicalizeUrl(left.url);\n const rightUrl = canonicalizeUrl(right.url);\n const byUrl = leftUrl.localeCompare(rightUrl);\n if (byUrl !== 0) return byUrl;\n return (left.title ?? \"\").localeCompare(right.title ?? \"\");\n });\n};\n\nexport const createCommunityProvider = (options: CommunityProviderOptions = {}): ProviderAdapter => {\n const id = options.id ?? \"community/default\";\n const platform = options.platform ?? \"community\";\n\n const search = async (input: ProviderSearchInput, context: ProviderContext): Promise<NormalizedRecord[]> => {\n if (!input.query.trim()) {\n throw new ProviderRuntimeError(\"invalid_input\", \"Community search query is required\", {\n provider: id,\n source: COMMUNITY_SOURCE,\n retryable: false\n });\n }\n if (!options.search) {\n throw unavailable(id, \"Community search retrieval is not configured\");\n }\n\n const traversal = mergedTraversal(options, input);\n const seen = new Set<string>();\n const pending: TraversalNode[] = [];\n const rows: CommunityRow[] = [];\n\n for (let page = 1; page <= traversal.pageLimit && rows.length < traversal.maxRecords; page += 1) {\n let pageRows: CommunityRow[];\n try {\n pageRows = await options.search({\n ...input,\n filters: {\n ...(input.filters ?? {}),\n page\n }\n }, context);\n } catch (error) {\n if (rows.length > 0 && shouldSkipExpansionError(error)) {\n break;\n }\n throw error;\n }\n for (const row of sortRows(pageRows)) {\n const canonical = canonicalizeUrl(row.url);\n if (!isHttpUrl(canonical) || seen.has(canonical)) continue;\n seen.add(canonical);\n rows.push({\n ...row,\n url: canonical,\n attributes: {\n ...(row.attributes ?? {}),\n traversal: {\n page,\n hop: 0\n },\n extractionQuality: qualityFlags({\n url: canonical,\n title: row.title,\n content: row.content,\n page,\n hop: 0,\n expandedLinks: 0\n })\n }\n });\n if (rows.length >= traversal.maxRecords) break;\n\n const links = extractLinks(row, canonical).slice(0, traversal.expansionPerRecord);\n for (const link of links) {\n pending.push({\n url: link,\n hop: 1,\n page,\n parent: canonical\n });\n }\n }\n }\n\n while (options.fetch && pending.length > 0 && rows.length < traversal.maxRecords) {\n const next = pending.shift();\n if (!next || next.hop > traversal.hopLimit) continue;\n const canonical = canonicalizeUrl(next.url);\n if (seen.has(canonical)) continue;\n\n let fetched: CommunityFetchRow;\n try {\n fetched = await options.fetch({\n url: canonical,\n filters: {\n ...(input.filters ?? {}),\n hop: next.hop,\n parent: next.parent\n }\n }, context);\n } catch (error) {\n if (shouldSkipExpansionError(error)) continue;\n throw error;\n }\n const resolvedUrl = canonicalizeUrl(fetched.url ?? canonical);\n if (!isHttpUrl(resolvedUrl) || seen.has(resolvedUrl)) continue;\n seen.add(resolvedUrl);\n\n const links = extractLinks(fetched, resolvedUrl).slice(0, traversal.expansionPerRecord);\n rows.push({\n url: resolvedUrl,\n title: fetched.title,\n content: fetched.content,\n confidence: 0.6,\n attributes: {\n ...(fetched.attributes ?? {}),\n traversal: {\n page: next.page,\n hop: next.hop,\n parent: next.parent\n },\n extractionQuality: qualityFlags({\n url: resolvedUrl,\n title: fetched.title,\n content: fetched.content,\n page: next.page,\n hop: next.hop,\n expandedLinks: links.length\n })\n }\n });\n\n if (next.hop < traversal.hopLimit) {\n for (const link of links) {\n if (seen.has(link)) continue;\n pending.push({\n url: link,\n hop: next.hop + 1,\n page: next.page,\n parent: resolvedUrl\n });\n }\n }\n }\n\n return normalizeRecords(id, COMMUNITY_SOURCE, rows.slice(0, traversal.maxRecords).map((row) => ({\n url: row.url,\n title: row.title,\n content: row.content,\n confidence: row.confidence ?? 0.65,\n attributes: row.attributes\n })));\n };\n\n const fetch = async (input: ProviderFetchInput, context: ProviderContext): Promise<NormalizedRecord[]> => {\n if (!options.fetch) {\n throw unavailable(id, \"Community fetch retrieval is not configured\");\n }\n const row = await options.fetch(input, context);\n const resolvedUrl = canonicalizeUrl(row.url ?? input.url);\n const links = extractLinks(row, resolvedUrl);\n return [normalizeRecord(id, COMMUNITY_SOURCE, {\n url: resolvedUrl,\n title: row.title,\n content: row.content,\n confidence: 0.7,\n attributes: {\n ...(row.attributes ?? {}),\n extractionQuality: qualityFlags({\n url: resolvedUrl,\n title: row.title,\n content: row.content,\n page: 0,\n hop: 0,\n expandedLinks: links.length\n })\n }\n })];\n };\n\n const crawl = async (input: ProviderCrawlInput, context: ProviderContext): Promise<NormalizedRecord[]> => {\n if (options.crawl) {\n const rows = await options.crawl(input, context);\n return normalizeRecords(id, COMMUNITY_SOURCE, sortRows(rows).map((row) => ({\n url: canonicalizeUrl(row.url),\n title: row.title,\n content: row.content,\n confidence: 0.6,\n attributes: {\n ...(row.attributes ?? {}),\n extractionQuality: qualityFlags({\n url: canonicalizeUrl(row.url),\n title: row.title,\n content: row.content,\n page: 0,\n hop: 0,\n expandedLinks: 0\n })\n }\n })));\n }\n if (!options.fetch) {\n throw unavailable(id, \"Community crawl retrieval is not configured\");\n }\n\n const maxPages = Math.max(1, input.maxPages ?? DEFAULT_TRAVERSAL.maxRecords);\n const maxDepth = Math.max(0, input.maxDepth ?? DEFAULT_TRAVERSAL.hopLimit);\n const expansionPerRecord = mergedTraversal(options, {\n filters: input.filters\n }).expansionPerRecord;\n\n const records: Array<{\n url: string;\n title?: string;\n content?: string;\n attributes?: Record<string, JsonValue>;\n }> = [];\n const seen = new Set<string>();\n const queue: Array<{ url: string; depth: number; parent?: string }> = input.seedUrls.map((url) => ({\n url: canonicalizeUrl(url),\n depth: 0\n }));\n\n while (queue.length > 0 && records.length < maxPages) {\n const node = queue.shift();\n if (!node || node.depth > maxDepth) continue;\n const canonical = canonicalizeUrl(node.url);\n if (!isHttpUrl(canonical) || seen.has(canonical)) continue;\n seen.add(canonical);\n\n const row = await options.fetch({\n url: canonical,\n filters: {\n ...(input.filters ?? {}),\n depth: node.depth,\n parent: node.parent ?? \"\"\n }\n }, context);\n const resolvedUrl = canonicalizeUrl(row.url ?? canonical);\n const links = extractLinks(row, resolvedUrl).slice(0, expansionPerRecord);\n\n records.push({\n url: resolvedUrl,\n title: row.title,\n content: row.content,\n attributes: {\n ...(row.attributes ?? {}),\n traversal: {\n depth: node.depth,\n parent: node.parent ?? resolvedUrl\n },\n extractionQuality: qualityFlags({\n url: resolvedUrl,\n title: row.title,\n content: row.content,\n page: 0,\n hop: node.depth,\n expandedLinks: links.length\n })\n }\n });\n\n if (node.depth >= maxDepth) continue;\n for (const link of links) {\n if (seen.has(link)) continue;\n queue.push({\n url: link,\n depth: node.depth + 1,\n parent: resolvedUrl\n });\n }\n }\n\n return normalizeRecords(id, COMMUNITY_SOURCE, records.map((row) => ({\n url: row.url,\n title: row.title,\n content: row.content,\n confidence: 0.6,\n attributes: row.attributes\n })));\n };\n\n const post = async (input: ProviderPostInput, context: ProviderContext): Promise<NormalizedRecord[]> => {\n const audit = await assertPostPolicy({\n providerId: id,\n source: COMMUNITY_SOURCE,\n payload: input,\n trace: context.trace\n }, options.postPolicyHooks);\n\n if (!options.post) {\n throw unavailable(id, \"Community posting transport is not configured\");\n }\n\n const row = await options.post(input, context);\n return [normalizeRecord(id, COMMUNITY_SOURCE, {\n url: row.url ?? \"\",\n title: row.title ?? `Post to ${input.target}`,\n content: row.content ?? input.content,\n confidence: 1,\n attributes: {\n ...(row.attributes ?? {}),\n auditHash: audit.payloadHash,\n decision: audit.decision\n }\n })];\n };\n\n return {\n id,\n source: COMMUNITY_SOURCE,\n search,\n fetch,\n crawl,\n post,\n health: async () => ({\n status: options.search || options.fetch ? \"healthy\" : \"degraded\",\n updatedAt: new Date().toISOString(),\n ...(options.search || options.fetch ? {} : { reason: \"Retrieval not configured\" })\n }),\n capabilities: () => createCapabilities(id, platform)\n };\n};\n","import type { SocialPlatform } from \"./index\";\n\nexport type SocialSearchShellCode =\n | \"social_render_shell\"\n | \"social_js_required_shell\"\n | \"social_first_party_help_shell\"\n | \"social_verification_wall\";\n\ntype TargetedSocialSearchPlatform = Extract<SocialPlatform, \"x\" | \"bluesky\" | \"reddit\" | \"facebook\" | \"threads\">;\ntype FirstPartySearchResultPlatform = Extract<TargetedSocialSearchPlatform, \"x\" | \"bluesky\">;\n\nconst TARGETED_PLATFORMS = new Set<TargetedSocialSearchPlatform>([\"x\", \"bluesky\", \"reddit\", \"facebook\", \"threads\"]);\nconst SOCIAL_JS_REQUIRED_RE = /\\b(?:javascript (?:is not available|required|is disabled(?: in this browser)?)|you need to enable javascript|please enable javascript)\\b/i;\nconst SOCIAL_JS_REQUIRED_SHELL_CONTEXT_RE = /\\b(?:supported browsers?|help center|something went wrong|try again|privacy policy|cookie policy|ads info)\\b/i;\nconst BLUESKY_LOGGED_OUT_SEARCH_RE = /\\bsearch is currently unavailable when logged out\\b/i;\nconst BLUESKY_EMPTY_SEARCH_SHELL_RE = /\\b(?:follow 10 people to get started|find people to follow)\\b/i;\nconst REDDIT_VERIFICATION_WALL_RE = /\\b(?:please wait for verification|verify (?:you(?:'re| are) human|that you(?:'re| are) human)|security check)\\b/i;\nconst FACEBOOK_SEARCH_RESULTS_HEADING_RE = /\\bsearch results\\b/i;\nconst FACEBOOK_SEARCH_RESULT_MARKERS = [\n /\\bshared with public\\b/i,\n /\\bopen reel in reels viewer\\b/i,\n /\\bcomment as\\b/i\n] as const;\nconst REDDIT_BLOCKED_EXPANSION_HOSTS = [\"accounts.google.com\", \"ads.reddit.com\"] as const;\nconst REDDIT_BLOCKED_FIRST_SEGMENTS = new Set([\"account\", \"ads\", \"notifications\", \"submit\", \"verification\"]);\n\ntype SocialSearchLinkEvidence = {\n usableLinks: string[];\n usableFirstPartyLinks: string[];\n usableContentLinks: string[];\n blockedLinks: string[];\n};\n\nconst FIRST_PARTY_HELP_HOSTS: Partial<Record<SocialPlatform, string[]>> = {\n x: [\n \"help.x.com\",\n \"developer.x.com\",\n \"business.x.com\",\n \"business.twitter.com\",\n \"legal.x.com\",\n \"legal.twitter.com\",\n \"support.x.com\",\n \"support.twitter.com\",\n \"t.co\"\n ],\n bluesky: [\"atproto.com\", \"docs.bsky.app\", \"bsky.social\", \"blueskyweb.zendesk.com\", \"go.bsky.app\"],\n reddit: [\"support.reddithelp.com\", \"reddithelp.com\", \"redditinc.com\"]\n};\n\nconst normalizeText = (value: string | undefined): string => (\n typeof value === \"string\"\n ? value.replace(/\\s+/g, \" \").trim()\n : \"\"\n);\n\nconst resolveCandidateUrl = (value: string, baseUrl: string): string | null => {\n try {\n return new URL(value, baseUrl).toString();\n } catch {\n return null;\n }\n};\n\nconst parseUrl = (value: string) => {\n try {\n return new URL(value);\n } catch {\n return null;\n }\n};\n\nconst matchesHost = (host: string, candidates: readonly string[]): boolean => {\n const normalized = host.toLowerCase();\n return candidates.some((candidate) => normalized === candidate || normalized.endsWith(`.${candidate}`));\n};\n\nconst firstPathSegment = (pathname: string): string | null => {\n const [firstSegment] = pathname\n .toLowerCase()\n .split(\"/\")\n .filter(Boolean);\n return typeof firstSegment === \"string\" && firstSegment.length > 0 ? firstSegment : null;\n};\n\nconst isStaticMetadataPath = (pathname: string): boolean => {\n const normalized = pathname.toLowerCase();\n return normalized.endsWith(\".json\")\n || normalized.endsWith(\".xml\")\n || normalized.endsWith(\".txt\")\n || normalized.endsWith(\".webmanifest\")\n || normalized.endsWith(\".ico\");\n};\n\nconst isTargetedPlatform = (platform: SocialPlatform): platform is TargetedSocialSearchPlatform => (\n TARGETED_PLATFORMS.has(platform as TargetedSocialSearchPlatform)\n);\n\nconst isFirstPartyHelpHost = (platform: SocialPlatform, host: string): boolean => {\n const candidates = FIRST_PARTY_HELP_HOSTS[platform];\n return Array.isArray(candidates) && matchesHost(host, candidates);\n};\n\nconst isPrimaryRedditHost = (host: string): boolean => {\n const normalized = host.toLowerCase();\n return normalized === \"www.reddit.com\"\n || normalized === \"reddit.com\"\n || normalized === \"old.reddit.com\";\n};\n\nconst isPrimaryFacebookHost = (host: string): boolean => {\n const normalized = host.toLowerCase();\n return normalized === \"www.facebook.com\"\n || normalized === \"facebook.com\"\n || normalized === \"m.facebook.com\";\n};\n\nconst isPrimaryThreadsHost = (host: string): boolean => {\n const normalized = host.toLowerCase();\n return normalized === \"www.threads.net\" || normalized === \"threads.net\";\n};\n\nconst isFacebookSearchLikePath = (pathname: string): boolean => (\n pathname === \"/watch/search\"\n || pathname === \"/watch/search/\"\n || pathname.startsWith(\"/watch/explore/\")\n || pathname.startsWith(\"/search/\")\n || pathname.startsWith(\"/public/\")\n || pathname.startsWith(\"/hashtag/\")\n);\n\nconst isBlockedFacebookNonContentUrl = (\n parsed: URL,\n options: { includeSearchRoute: boolean }\n): boolean => {\n if (!isPrimaryFacebookHost(parsed.hostname)) {\n return false;\n }\n const pathname = parsed.pathname.toLowerCase();\n if (\n pathname === \"/\"\n || pathname === \"/login\"\n || pathname === \"/login/\"\n || pathname === \"/reg\"\n || pathname === \"/reg/\"\n || pathname.startsWith(\"/recover/\")\n ) {\n return true;\n }\n if ((pathname === \"/watch\" || pathname === \"/watch/\") && !parsed.searchParams.get(\"v\")) {\n return true;\n }\n if (isStaticMetadataPath(pathname)) {\n return true;\n }\n return options.includeSearchRoute && isFacebookSearchLikePath(pathname);\n};\n\nconst isBlockedRedditNonContentUrl = (\n parsed: URL,\n options: { includeSearchRoute: boolean }\n): boolean => {\n const host = parsed.hostname.toLowerCase();\n if (matchesHost(host, REDDIT_BLOCKED_EXPANSION_HOSTS)) {\n return true;\n }\n if (!isPrimaryRedditHost(host)) {\n return false;\n }\n const pathname = parsed.pathname.toLowerCase();\n if (\n pathname === \"/\"\n || pathname === \"/login\"\n || pathname === \"/login/\"\n || (options.includeSearchRoute && (pathname === \"/search\" || pathname === \"/search/\"))\n ) {\n return true;\n }\n const pathSegment = firstPathSegment(pathname);\n return pathSegment !== null && REDDIT_BLOCKED_FIRST_SEGMENTS.has(pathSegment);\n};\n\nconst isRootShellUrl = (platform: TargetedSocialSearchPlatform, parsed: URL): boolean => {\n const host = parsed.hostname.toLowerCase();\n const pathname = parsed.pathname.toLowerCase();\n switch (platform) {\n case \"x\":\n return host === \"x.com\"\n && (pathname === \"/\" || pathname === \"/home\" || pathname === \"/login\" || pathname.startsWith(\"/i/flow/login\"));\n case \"bluesky\":\n return host === \"bsky.app\"\n && (pathname === \"/\" || pathname === \"/login\");\n case \"reddit\":\n return isBlockedRedditNonContentUrl(parsed, { includeSearchRoute: false });\n case \"facebook\":\n return isBlockedFacebookNonContentUrl(parsed, { includeSearchRoute: false });\n case \"threads\":\n return isPrimaryThreadsHost(host)\n && (pathname === \"/\" || pathname === \"/login\" || pathname === \"/login/\");\n }\n};\n\nconst isBlockedExpansionPath = (platform: TargetedSocialSearchPlatform, parsed: URL): boolean => {\n const host = parsed.hostname.toLowerCase();\n const pathname = parsed.pathname.toLowerCase();\n switch (platform) {\n case \"x\":\n return host === \"x.com\"\n && (\n pathname === \"/\"\n || pathname === \"/home\"\n || pathname === \"/login\"\n || pathname === \"/privacy\"\n || pathname === \"/search\"\n || pathname === \"/tos\"\n || isStaticMetadataPath(pathname)\n || pathname.startsWith(\"/i/flow/login\")\n );\n case \"bluesky\":\n return host === \"bsky.app\"\n && (\n pathname === \"/\"\n || pathname === \"/login\"\n || pathname === \"/search\"\n || isStaticMetadataPath(pathname)\n || (/^\\/profile\\/[^/]+\\/feed\\/[^/]+$/.test(pathname))\n );\n case \"reddit\":\n return isBlockedRedditNonContentUrl(parsed, { includeSearchRoute: true });\n case \"facebook\":\n return isBlockedFacebookNonContentUrl(parsed, { includeSearchRoute: true });\n case \"threads\":\n return isPrimaryThreadsHost(host)\n && (\n pathname === \"/\"\n || pathname === \"/login\"\n || pathname === \"/search\"\n || pathname === \"/search/\"\n || isStaticMetadataPath(pathname)\n );\n }\n};\n\nconst isFirstPartySearchRoute = (platform: TargetedSocialSearchPlatform, parsed: URL): boolean => {\n const host = parsed.hostname.toLowerCase();\n const pathname = parsed.pathname.toLowerCase();\n switch (platform) {\n case \"x\":\n return host === \"x.com\" && pathname === \"/search\";\n case \"bluesky\":\n return host === \"bsky.app\" && pathname === \"/search\";\n case \"reddit\":\n return isPrimaryRedditHost(host) && (pathname === \"/search\" || pathname === \"/search/\");\n case \"facebook\":\n return isPrimaryFacebookHost(host) && isFacebookSearchLikePath(pathname);\n case \"threads\":\n return isPrimaryThreadsHost(host) && (pathname === \"/search\" || pathname === \"/search/\");\n }\n};\n\nconst collectSocialSearchLinkEvidence = (\n platform: TargetedSocialSearchPlatform,\n baseUrl: string,\n links: readonly string[]\n): SocialSearchLinkEvidence => {\n const evidence: SocialSearchLinkEvidence = {\n usableLinks: [],\n usableFirstPartyLinks: [],\n usableContentLinks: [],\n blockedLinks: []\n };\n\n for (const candidate of links) {\n const resolved = resolveCandidateUrl(candidate, baseUrl);\n if (!resolved) {\n continue;\n }\n if (platform === \"x\" || platform === \"bluesky\") {\n if (isUsableFirstPartySearchResultUrl(platform, resolved)) {\n evidence.usableLinks.push(resolved);\n evidence.usableFirstPartyLinks.push(resolved);\n if (isUsableSocialSearchContentUrl(platform, resolved)) {\n evidence.usableContentLinks.push(resolved);\n }\n } else {\n evidence.blockedLinks.push(resolved);\n }\n continue;\n }\n if (isAllowedSocialSearchExpansionUrl(platform, resolved)) {\n evidence.usableLinks.push(resolved);\n if (isUsableSocialSearchContentUrl(platform, resolved)) {\n evidence.usableContentLinks.push(resolved);\n }\n } else {\n evidence.blockedLinks.push(resolved);\n }\n }\n\n return evidence;\n};\n\nconst isUsableFirstPartySearchResultUrl = (platform: FirstPartySearchResultPlatform, url: string): boolean => {\n const parsed = parseUrl(url);\n if (parsed === null) {\n return false;\n }\n const host = parsed.hostname.toLowerCase();\n if (\n (platform === \"x\" && host !== \"x.com\")\n || (platform === \"bluesky\" && host !== \"bsky.app\")\n ) {\n return false;\n }\n return !isBlockedExpansionPath(platform, parsed);\n};\n\nconst isUsableBlueskySearchEvidenceUrl = (url: string): boolean => {\n const parsed = parseUrl(url);\n return parsed !== null\n && parsed.hostname.toLowerCase() === \"bsky.app\"\n && /^\\/profile\\/[^/]+\\/post\\/[^/]+$/.test(parsed.pathname.toLowerCase());\n};\n\nconst isUsableXSearchEvidenceUrl = (url: string): boolean => {\n const parsed = parseUrl(url);\n return parsed !== null\n && parsed.hostname.toLowerCase() === \"x.com\"\n && (\n /^\\/[^/]+\\/status\\/\\d+\\/?$/.test(parsed.pathname.toLowerCase())\n || /^\\/i\\/web\\/status\\/\\d+\\/?$/.test(parsed.pathname.toLowerCase())\n );\n};\n\nconst isUsableRedditSearchEvidenceUrl = (url: string): boolean => {\n const parsed = parseUrl(url);\n return parsed !== null\n && isPrimaryRedditHost(parsed.hostname)\n && /^\\/r\\/[^/]+\\/comments\\/[^/]+(?:\\/|$)/.test(parsed.pathname.toLowerCase());\n};\n\nconst isUsableFacebookSearchEvidenceUrl = (url: string): boolean => {\n const parsed = parseUrl(url);\n if (parsed === null || !isPrimaryFacebookHost(parsed.hostname)) {\n return false;\n }\n const pathname = parsed.pathname.toLowerCase();\n if ((pathname === \"/watch\" || pathname === \"/watch/\") && parsed.searchParams.get(\"v\")) {\n return true;\n }\n return /^\\/reel\\/[^/]+\\/?$/.test(pathname)\n || /^\\/groups\\/[^/]+\\/posts\\/[^/]+\\/?$/.test(pathname)\n || /^\\/[^/]+\\/videos\\/[^/]+\\/?$/.test(pathname)\n || /^\\/share\\/v\\/[^/]+\\/?$/.test(pathname)\n || ((pathname === \"/permalink.php\" || pathname === \"/story.php\") && parsed.searchParams.has(\"story_fbid\"))\n || (pathname === \"/photo/\" && parsed.searchParams.has(\"fbid\"));\n};\n\nconst isUsableThreadsSearchEvidenceUrl = (url: string): boolean => {\n const parsed = parseUrl(url);\n return parsed !== null\n && isPrimaryThreadsHost(parsed.hostname)\n && /^\\/@[^/]+\\/post\\/[^/]+\\/?$/.test(parsed.pathname.toLowerCase());\n};\n\nconst isRetainableFacebookSearchSupportUrl = (url: string): boolean => {\n const parsed = parseUrl(url);\n if (parsed === null || !isPrimaryFacebookHost(parsed.hostname)) {\n return false;\n }\n return !isUsableFacebookSearchEvidenceUrl(url);\n};\n\nconst hasFacebookSearchResultSignals = (\n parsed: URL,\n input: { url: string; title?: string; content?: string; links?: readonly string[] }\n): boolean => {\n const combined = `${normalizeText(input.title)} ${normalizeText(input.content)}`.trim();\n const hasSearchHeading = FACEBOOK_SEARCH_RESULTS_HEADING_RE.test(combined);\n const markerCount = FACEBOOK_SEARCH_RESULT_MARKERS.filter((pattern) => pattern.test(combined)).length;\n const evidence = collectSocialSearchLinkEvidence(\"facebook\", parsed.toString(), Array.isArray(input.links) ? input.links : []);\n const hasContentEvidence = evidence.usableContentLinks.length > 0;\n const supportLinkCount = evidence.usableLinks.filter(isRetainableFacebookSearchSupportUrl).length;\n if (markerCount >= 2 && hasContentEvidence) {\n return true;\n }\n if (!hasSearchHeading) {\n return false;\n }\n if (markerCount >= 1 && hasContentEvidence) {\n return true;\n }\n return supportLinkCount >= 2 && hasContentEvidence;\n};\n\nconst isUsableSocialSearchContentUrl = (\n platform: TargetedSocialSearchPlatform,\n url: string\n): boolean => {\n switch (platform) {\n case \"x\":\n return isUsableXSearchEvidenceUrl(url);\n case \"bluesky\":\n return isUsableBlueskySearchEvidenceUrl(url);\n case \"reddit\":\n return isUsableRedditSearchEvidenceUrl(url);\n case \"facebook\":\n return isUsableFacebookSearchEvidenceUrl(url);\n case \"threads\":\n return isUsableThreadsSearchEvidenceUrl(url);\n }\n};\n\nconst hasUsableFirstPartySearchEvidence = (\n platform: TargetedSocialSearchPlatform,\n parsed: URL | null,\n links: readonly string[]\n): boolean => (\n parsed !== null\n && isFirstPartySearchRoute(platform, parsed)\n && collectSocialSearchLinkEvidence(platform, parsed.toString(), links).usableContentLinks.length > 0\n);\n\nexport const isFirstPartySocialSearchRoute = (\n platform: SocialPlatform,\n url: string\n): boolean => {\n const parsed = parseUrl(url);\n return parsed !== null && isTargetedPlatform(platform) && isFirstPartySearchRoute(platform, parsed);\n};\n\nexport const detectSocialSearchShell = (\n platform: SocialPlatform,\n input: { url: string; title?: string; content?: string; links?: readonly string[] }\n): { providerShell: SocialSearchShellCode; browserRequired: true } | null => {\n if (!isTargetedPlatform(platform)) {\n return null;\n }\n\n const parsed = parseUrl(input.url);\n const combined = `${normalizeText(input.title)} ${normalizeText(input.content)}`.trim();\n const links = Array.isArray(input.links) ? input.links : [];\n if (parsed && isFirstPartyHelpHost(platform, parsed.hostname)) {\n return {\n providerShell: \"social_first_party_help_shell\",\n browserRequired: true\n };\n }\n\n if (\n (platform === \"x\" || platform === \"bluesky\")\n && parsed\n && SOCIAL_JS_REQUIRED_RE.test(combined)\n && SOCIAL_JS_REQUIRED_SHELL_CONTEXT_RE.test(combined)\n && !hasUsableFirstPartySearchEvidence(platform, parsed, links)\n ) {\n return {\n providerShell: \"social_js_required_shell\",\n browserRequired: true\n };\n }\n\n if (platform === \"reddit\" && REDDIT_VERIFICATION_WALL_RE.test(combined)) {\n return {\n providerShell: \"social_verification_wall\",\n browserRequired: true\n };\n }\n\n if (\n platform === \"bluesky\"\n && parsed\n && isFirstPartySearchRoute(platform, parsed)\n && BLUESKY_LOGGED_OUT_SEARCH_RE.test(combined)\n && !hasUsableFirstPartySearchEvidence(platform, parsed, links)\n ) {\n return {\n providerShell: \"social_js_required_shell\",\n browserRequired: true\n };\n }\n\n if (\n platform === \"bluesky\"\n && parsed\n && isFirstPartySearchRoute(platform, parsed)\n && BLUESKY_EMPTY_SEARCH_SHELL_RE.test(combined)\n ) {\n return {\n providerShell: \"social_render_shell\",\n browserRequired: true\n };\n }\n\n if (\n (platform === \"x\" || platform === \"bluesky\")\n && parsed\n && isFirstPartySearchRoute(platform, parsed)\n && SOCIAL_JS_REQUIRED_RE.test(combined)\n && !hasUsableFirstPartySearchEvidence(platform, parsed, links)\n ) {\n return {\n providerShell: \"social_js_required_shell\",\n browserRequired: true\n };\n }\n\n if (parsed && isRootShellUrl(platform, parsed)) {\n return {\n providerShell: \"social_render_shell\",\n browserRequired: true\n };\n }\n\n if (\n parsed\n && isFirstPartySearchRoute(platform, parsed)\n && platform === \"facebook\"\n && hasFacebookSearchResultSignals(parsed, input)\n ) {\n return null;\n }\n\n if (\n parsed\n && isFirstPartySearchRoute(platform, parsed)\n && !hasUsableFirstPartySearchEvidence(platform, parsed, links)\n ) {\n return {\n providerShell: \"social_render_shell\",\n browserRequired: true\n };\n }\n\n return null;\n};\n\nexport const isAllowedSocialSearchExpansionUrl = (\n platform: SocialPlatform,\n url: string\n): boolean => {\n if (!isTargetedPlatform(platform)) {\n return true;\n }\n\n const parsed = parseUrl(url);\n if (!parsed) {\n return false;\n }\n\n if (isFirstPartyHelpHost(platform, parsed.hostname)) {\n return false;\n }\n\n return !isBlockedExpansionPath(platform, parsed);\n};\n\nconst socialSearchLinkPriority = (\n platform: TargetedSocialSearchPlatform,\n candidate: string,\n baseUrl: string\n): number => {\n const resolved = resolveCandidateUrl(candidate, baseUrl);\n if (!resolved) {\n return 3;\n }\n if (isUsableSocialSearchContentUrl(platform, resolved)) {\n return 0;\n }\n return isAllowedSocialSearchExpansionUrl(platform, resolved) ? 1 : 2;\n};\n\nexport const prioritizeSocialSearchLinks = (\n platform: SocialPlatform,\n baseUrl: string,\n links: readonly string[]\n): string[] => {\n if (!isTargetedPlatform(platform) || links.length < 2) {\n return [...links];\n }\n return links\n .map((url, index) => ({\n url,\n index,\n priority: socialSearchLinkPriority(platform, url, baseUrl)\n }))\n .sort((left, right) => left.priority - right.priority || left.index - right.index)\n .map((entry) => entry.url);\n};\n\nexport const selectUsableSocialSearchLinks = (\n platform: SocialPlatform,\n baseUrl: string,\n links: readonly string[]\n): string[] => {\n if (!isTargetedPlatform(platform)) {\n return [...links];\n }\n const evidence = collectSocialSearchLinkEvidence(platform, baseUrl, links);\n return prioritizeSocialSearchLinks(platform, baseUrl, evidence.usableContentLinks);\n};\n","import { ProviderRuntimeError } from \"../errors\";\nimport { normalizeRecords } from \"../normalize\";\nimport { assertPostPolicy, type PostPolicyHook } from \"../shared/post-policy\";\nimport { isLikelyDocumentUrl } from \"../shared/traversal-url\";\nimport { canonicalizeUrl } from \"../web/crawler\";\nimport {\n isAllowedSocialSearchExpansionUrl,\n isFirstPartySocialSearchRoute,\n prioritizeSocialSearchLinks,\n selectUsableSocialSearchLinks\n} from \"./search-quality\";\nimport type {\n JsonValue,\n NormalizedRecord,\n ProviderAdapter,\n ProviderCapabilities,\n ProviderContext,\n ProviderFetchInput,\n ProviderPostInput,\n ProviderRecoveryHints,\n ProviderSearchInput\n} from \"../types\";\n\nconst SOCIAL_SOURCE = \"social\" as const;\n\nexport interface SocialSearchRecord {\n url: string;\n title?: string;\n content?: string;\n confidence?: number;\n attributes?: Record<string, JsonValue>;\n}\n\ntype SocialFetchRecord = {\n url?: string;\n title?: string;\n content?: string;\n attributes?: Record<string, JsonValue>;\n};\n\ninterface SocialTraversalNode {\n url: string;\n page: number;\n hop: number;\n parent: string;\n carryForwardAttributes?: Record<string, JsonValue>;\n}\n\nexport interface SocialTraversalBudget {\n pageLimit: number;\n hopLimit: number;\n expansionPerRecord: number;\n maxRecords: number;\n}\n\nexport interface SocialProviderOptions {\n id?: string;\n search?: (input: ProviderSearchInput, context: ProviderContext) => Promise<SocialSearchRecord[]>;\n fetch?: (input: ProviderFetchInput, context: ProviderContext) => Promise<SocialFetchRecord>;\n post?: (input: ProviderPostInput, context: ProviderContext) => Promise<SocialFetchRecord>;\n postPolicyHooks?: PostPolicyHook[];\n defaultTraversal?: Partial<SocialTraversalBudget>;\n recoveryHints?: () => ProviderRecoveryHints;\n}\n\nexport interface SocialPlatformProfile {\n platform: \"x\" | \"reddit\" | \"bluesky\" | \"facebook\" | \"linkedin\" | \"instagram\" | \"tiktok\" | \"threads\" | \"youtube\";\n displayName: string;\n baseUrl: string;\n maxPostLength: number;\n supportsMedia: boolean;\n supportsThreads: boolean;\n}\n\nconst DEFAULT_TRAVERSAL: SocialTraversalBudget = {\n pageLimit: 2,\n hopLimit: 1,\n expansionPerRecord: 4,\n maxRecords: 20\n};\n\nconst LINK_RE = /https?:\\/\\/[^\\s\"'<>]+/g;\n\nconst capabilitiesForProfile = (providerId: string, profile: SocialPlatformProfile): ProviderCapabilities => ({\n providerId,\n source: SOCIAL_SOURCE,\n operations: {\n search: {\n op: \"search\",\n supported: true,\n description: `Search ${profile.displayName}`,\n metadata: {\n platform: profile.platform,\n supportsMedia: profile.supportsMedia\n }\n },\n fetch: {\n op: \"fetch\",\n supported: true,\n description: `Fetch ${profile.displayName} item`\n },\n crawl: {\n op: \"crawl\",\n supported: false,\n description: \"Social crawl is intentionally disabled\"\n },\n post: {\n op: \"post\",\n supported: true,\n description: `Post to ${profile.displayName} with policy confirmation`,\n metadata: {\n maxPostLength: profile.maxPostLength,\n supportsMedia: profile.supportsMedia,\n supportsThreads: profile.supportsThreads\n }\n }\n },\n policy: {\n posting: \"gated\",\n riskNoticeRequired: true,\n confirmationRequired: true\n },\n metadata: {\n platform: profile.platform,\n displayName: profile.displayName,\n source: SOCIAL_SOURCE,\n maxPostLength: profile.maxPostLength,\n supportsMedia: profile.supportsMedia,\n supportsThreads: profile.supportsThreads\n }\n});\n\nconst asNumber = (value: JsonValue | undefined): number | undefined => {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim()) {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) return parsed;\n }\n return undefined;\n};\n\nconst toPositiveInt = (value: number | undefined, fallback: number): number => {\n if (typeof value !== \"number\" || Number.isNaN(value)) return fallback;\n return Math.max(1, Math.floor(value));\n};\n\nconst toNonNegativeInt = (value: number | undefined, fallback: number): number => {\n if (typeof value !== \"number\" || Number.isNaN(value)) return fallback;\n return Math.max(0, Math.floor(value));\n};\n\nconst isHttpUrl = (value: string): boolean => {\n try {\n const protocol = new URL(value).protocol;\n return protocol === \"http:\" || protocol === \"https:\";\n } catch {\n return false;\n }\n};\n\nconst coerceStringArray = (value: JsonValue | undefined): string[] => {\n if (!Array.isArray(value)) return [];\n return value.filter((entry): entry is string => typeof entry === \"string\");\n};\n\nconst CARRY_FORWARD_SOCIAL_SEARCH_ATTRIBUTE_KEYS = new Set([\n \"links\",\n \"page\",\n \"query\",\n \"retrievalPath\",\n \"status\"\n]);\n\nconst pickCarryForwardSocialSearchAttributes = (\n attributes?: Record<string, JsonValue>\n): Record<string, JsonValue> | undefined => {\n if (!attributes) return undefined;\n const carried = Object.entries(attributes).reduce<Record<string, JsonValue>>((result, [key, value]) => {\n if (CARRY_FORWARD_SOCIAL_SEARCH_ATTRIBUTE_KEYS.has(key) || key.startsWith(\"browser_fallback_\")) {\n result[key] = value;\n }\n return result;\n }, {});\n return Object.keys(carried).length > 0 ? carried : undefined;\n};\n\nconst hasBrowserFallbackMode = (attributes?: Record<string, JsonValue>): boolean => (\n typeof attributes?.browser_fallback_mode === \"string\" && attributes.browser_fallback_mode.length > 0\n);\n\nconst hasVisibleSearchContent = (\n row: { title?: string; content?: string }\n): boolean => (\n (typeof row.title === \"string\" && row.title.trim().length > 0)\n || (typeof row.content === \"string\" && row.content.trim().length > 0)\n);\n\nconst shouldKeepRecoveredFacebookSearchRow = (\n platform: SocialPlatformProfile[\"platform\"],\n row: { title?: string; content?: string; attributes?: Record<string, JsonValue> }\n): boolean => (\n platform === \"facebook\"\n && hasBrowserFallbackMode(row.attributes)\n && hasVisibleSearchContent(row)\n);\n\nconst extractLinks = (\n platform: SocialPlatformProfile[\"platform\"],\n row: { attributes?: Record<string, JsonValue>; content?: string },\n fallbackUrl: string\n): string[] => {\n const attributeLinks = [\n ...coerceStringArray(row.attributes?.links),\n ...coerceStringArray(row.attributes?.threadLinks),\n ...coerceStringArray(row.attributes?.replyLinks),\n ...coerceStringArray(row.attributes?.relatedUrls)\n ];\n const contentLinks = [...(row.content?.match(LINK_RE) ?? [])];\n const deduped = new Set<string>();\n for (const candidate of [...attributeLinks, ...contentLinks]) {\n const canonical = canonicalizeUrl(candidate);\n if (\n !isHttpUrl(canonical)\n || canonical === fallbackUrl\n || !isLikelyDocumentUrl(canonical)\n || !isAllowedSocialSearchExpansionUrl(platform, canonical)\n ) {\n continue;\n }\n deduped.add(canonical);\n }\n if (isFirstPartySocialSearchRoute(platform, fallbackUrl)) {\n return selectUsableSocialSearchLinks(platform, fallbackUrl, [...deduped]);\n }\n return prioritizeSocialSearchLinks(platform, fallbackUrl, [...deduped]);\n};\n\nconst qualityFlags = (args: {\n url: string;\n title?: string;\n content?: string;\n page: number;\n hop: number;\n expandedLinks: number;\n}): Record<string, JsonValue> => ({\n hasUrl: args.url.length > 0,\n hasTitle: typeof args.title === \"string\" && args.title.length > 0,\n hasContent: typeof args.content === \"string\" && args.content.length > 0,\n contentChars: args.content?.length ?? 0,\n page: args.page,\n hop: args.hop,\n expanded: args.hop > 0,\n expandedLinks: args.expandedLinks\n});\n\nconst unavailable = (providerId: string, message: string): ProviderRuntimeError => {\n return new ProviderRuntimeError(\"unavailable\", message, {\n provider: providerId,\n source: SOCIAL_SOURCE\n });\n};\n\nconst shouldSkipExpansionError = (error: unknown): boolean => {\n if (!(error instanceof ProviderRuntimeError)) return false;\n return error.code === \"auth\"\n || error.code === \"network\"\n || error.code === \"rate_limited\"\n || error.code === \"timeout\"\n || error.code === \"unavailable\"\n || error.code === \"upstream\";\n};\n\nconst sortRows = <T extends { url: string; title?: string }>(rows: T[]): T[] => {\n return [...rows].sort((left, right) => {\n const leftUrl = canonicalizeUrl(left.url);\n const rightUrl = canonicalizeUrl(right.url);\n const byUrl = leftUrl.localeCompare(rightUrl);\n if (byUrl !== 0) return byUrl;\n /* v8 ignore next -- duplicate canonical rows are already exercised above; the fallback keeps titleless rows sortable */\n return (left.title ?? \"\").localeCompare(right.title ?? \"\");\n });\n};\n\nconst mergedTraversal = (\n input: ProviderSearchInput,\n options: SocialProviderOptions\n): SocialTraversalBudget => {\n const filters = input.filters ?? {};\n return {\n pageLimit: toPositiveInt(\n asNumber(filters.pageLimit) ?? options.defaultTraversal?.pageLimit,\n DEFAULT_TRAVERSAL.pageLimit\n ),\n hopLimit: toNonNegativeInt(\n asNumber(filters.hopLimit) ?? options.defaultTraversal?.hopLimit,\n DEFAULT_TRAVERSAL.hopLimit\n ),\n expansionPerRecord: toNonNegativeInt(\n asNumber(filters.expansionPerRecord) ?? options.defaultTraversal?.expansionPerRecord,\n DEFAULT_TRAVERSAL.expansionPerRecord\n ),\n maxRecords: toPositiveInt(\n input.limit ?? asNumber(filters.maxRecords) ?? options.defaultTraversal?.maxRecords,\n DEFAULT_TRAVERSAL.maxRecords\n )\n };\n};\n\nconst normalizeSocialRows = (\n providerId: string,\n profile: SocialPlatformProfile,\n rows: Array<{\n url: string;\n title?: string;\n content?: string;\n confidence?: number;\n attributes?: Record<string, JsonValue>;\n }>\n): NormalizedRecord[] => {\n return normalizeRecords(providerId, SOCIAL_SOURCE, rows.map((row) => ({\n url: row.url,\n title: row.title,\n content: row.content,\n confidence: row.confidence,\n attributes: Object.assign({ platform: profile.platform }, row.attributes)\n })));\n};\n\nexport const createSocialPlatformProvider = (\n profile: SocialPlatformProfile,\n options: SocialProviderOptions = {}\n): ProviderAdapter => {\n const providerId = options.id ?? `social/${profile.platform}`;\n\n const search = async (input: ProviderSearchInput, context: ProviderContext): Promise<NormalizedRecord[]> => {\n if (!input.query.trim()) {\n throw new ProviderRuntimeError(\"invalid_input\", `${profile.displayName} search query is required`, {\n provider: providerId,\n source: SOCIAL_SOURCE,\n retryable: false\n });\n }\n if (!options.search) {\n throw unavailable(providerId, `${profile.displayName} search retrieval is not configured`);\n }\n\n const traversal = mergedTraversal(input, options);\n const seen = new Set<string>();\n const queue: SocialTraversalNode[] = [];\n const rows: Array<{\n url: string;\n title?: string;\n content?: string;\n confidence?: number;\n attributes?: Record<string, JsonValue>;\n }> = [];\n\n for (let page = 1; page <= traversal.pageLimit && rows.length < traversal.maxRecords; page += 1) {\n let pageRows: SocialSearchRecord[];\n try {\n pageRows = await options.search({\n ...input,\n filters: {\n ...(input.filters ?? {}),\n page\n }\n }, context);\n } catch (error) {\n if (page > 1 && rows.length > 0 && shouldSkipExpansionError(error)) {\n break;\n }\n throw error;\n }\n\n for (const row of sortRows(pageRows)) {\n const canonical = canonicalizeUrl(row.url);\n if (!isHttpUrl(canonical) || seen.has(canonical)) continue;\n seen.add(canonical);\n\n const links = extractLinks(profile.platform, row, canonical).slice(0, traversal.expansionPerRecord);\n const keepFirstPartySearchRow = shouldKeepRecoveredFacebookSearchRow(profile.platform, row)\n || (profile.platform === \"facebook\" && links.length === 0);\n const keepRow = !isFirstPartySocialSearchRoute(profile.platform, canonical) || keepFirstPartySearchRow;\n const carryForwardAttributes = keepRow\n ? undefined\n : pickCarryForwardSocialSearchAttributes(row.attributes);\n\n if (keepRow) {\n rows.push({\n ...row,\n url: canonical,\n attributes: {\n ...(row.attributes ?? {}),\n traversal: {\n page,\n hop: 0\n },\n extractionQuality: qualityFlags({\n url: canonical,\n title: row.title,\n content: row.content,\n page,\n hop: 0,\n expandedLinks: links.length\n })\n }\n });\n if (rows.length >= traversal.maxRecords) break;\n }\n\n for (const link of links) {\n queue.push({\n url: link,\n page,\n hop: 1,\n parent: canonical,\n ...(carryForwardAttributes ? { carryForwardAttributes } : {})\n });\n }\n }\n }\n\n while (options.fetch && queue.length > 0 && rows.length < traversal.maxRecords) {\n const next = queue.shift()!;\n const canonical = canonicalizeUrl(next.url);\n if (seen.has(canonical)) continue;\n\n let fetched: SocialFetchRecord;\n try {\n fetched = await options.fetch({\n url: canonical,\n filters: {\n ...(input.filters ?? {}),\n hop: next.hop,\n parent: next.parent\n }\n }, context);\n } catch (error) {\n if (shouldSkipExpansionError(error)) continue;\n throw error;\n }\n const resolvedUrl = canonicalizeUrl(fetched.url ?? canonical);\n if (!isHttpUrl(resolvedUrl) || seen.has(resolvedUrl)) continue;\n seen.add(resolvedUrl);\n\n const links = extractLinks(profile.platform, fetched, resolvedUrl).slice(0, traversal.expansionPerRecord);\n rows.push({\n url: resolvedUrl,\n title: fetched.title,\n content: fetched.content,\n confidence: 0.6,\n attributes: {\n ...(fetched.attributes ?? {}),\n ...(next.carryForwardAttributes ?? {}),\n traversal: {\n page: next.page,\n hop: next.hop,\n parent: next.parent\n },\n extractionQuality: qualityFlags({\n url: resolvedUrl,\n title: fetched.title,\n content: fetched.content,\n page: next.page,\n hop: next.hop,\n expandedLinks: links.length\n })\n }\n });\n\n if (next.hop < traversal.hopLimit) {\n for (const link of links) {\n if (seen.has(link)) continue;\n queue.push({\n url: link,\n page: next.page,\n hop: next.hop + 1,\n parent: resolvedUrl\n });\n }\n }\n }\n\n return normalizeSocialRows(providerId, profile, rows.slice(0, traversal.maxRecords));\n };\n\n const fetch = async (input: ProviderFetchInput, context: ProviderContext): Promise<NormalizedRecord[]> => {\n if (!options.fetch) {\n throw unavailable(providerId, `${profile.displayName} fetch retrieval is not configured`);\n }\n const row = await options.fetch(input, context);\n const resolvedUrl = canonicalizeUrl(row.url ?? input.url);\n const links = extractLinks(profile.platform, row, resolvedUrl);\n return normalizeSocialRows(providerId, profile, [{\n url: resolvedUrl,\n title: row.title,\n content: row.content,\n confidence: 0.7,\n attributes: {\n ...(row.attributes ?? {}),\n extractionQuality: qualityFlags({\n url: resolvedUrl,\n title: row.title,\n content: row.content,\n page: 0,\n hop: 0,\n expandedLinks: links.length\n })\n }\n }]);\n };\n\n const post = async (input: ProviderPostInput, context: ProviderContext): Promise<NormalizedRecord[]> => {\n if (input.content.length > profile.maxPostLength) {\n throw new ProviderRuntimeError(\"invalid_input\", `${profile.displayName} post exceeds max length`, {\n provider: providerId,\n source: SOCIAL_SOURCE,\n retryable: false,\n details: {\n maxPostLength: profile.maxPostLength,\n contentLength: input.content.length\n }\n });\n }\n\n const audit = await assertPostPolicy({\n providerId,\n source: SOCIAL_SOURCE,\n payload: input,\n trace: context.trace\n }, options.postPolicyHooks);\n\n if (!options.post) {\n throw new ProviderRuntimeError(\"unavailable\", `${profile.displayName} posting transport is not configured`, {\n provider: providerId,\n source: SOCIAL_SOURCE,\n retryable: false,\n reasonCode: \"policy_blocked\",\n details: {\n reasonCode: \"policy_blocked\",\n postingTransportConfigured: false\n }\n });\n }\n\n const row = await options.post(input, context);\n return normalizeSocialRows(providerId, profile, [{\n url: canonicalizeUrl(row.url ?? `${profile.baseUrl}/${encodeURIComponent(input.target)}`),\n title: row.title ?? `${profile.displayName} post`,\n content: row.content ?? input.content,\n confidence: 1,\n attributes: {\n ...(row.attributes ?? {}),\n auditHash: audit.payloadHash,\n decision: audit.decision\n }\n }]);\n };\n\n return {\n id: providerId,\n source: SOCIAL_SOURCE,\n search,\n fetch,\n post,\n ...(typeof options.recoveryHints === \"function\" ? { recoveryHints: options.recoveryHints } : {}),\n health: async () => ({\n status: options.search || options.fetch || options.post ? \"healthy\" : \"degraded\",\n updatedAt: new Date().toISOString(),\n ...(options.search || options.fetch || options.post ? {} : { reason: \"Retrieval not configured\" })\n }),\n capabilities: () => capabilitiesForProfile(providerId, profile)\n };\n};\n","import { createSocialPlatformProvider, type SocialProviderOptions } from \"./platform\";\n\nexport const createBlueskyProvider = (options: SocialProviderOptions = {}) => {\n return createSocialPlatformProvider({\n platform: \"bluesky\",\n displayName: \"Bluesky\",\n baseUrl: \"https://bsky.app\",\n maxPostLength: 300,\n supportsMedia: true,\n supportsThreads: true\n }, options);\n};\n","import { createSocialPlatformProvider, type SocialProviderOptions } from \"./platform\";\n\nexport const createFacebookProvider = (options: SocialProviderOptions = {}) => {\n return createSocialPlatformProvider({\n platform: \"facebook\",\n displayName: \"Facebook\",\n baseUrl: \"https://www.facebook.com\",\n maxPostLength: 63206,\n supportsMedia: true,\n supportsThreads: false\n }, options);\n};\n","import { createSocialPlatformProvider, type SocialProviderOptions } from \"./platform\";\n\nexport const createInstagramProvider = (options: SocialProviderOptions = {}) => {\n return createSocialPlatformProvider({\n platform: \"instagram\",\n displayName: \"Instagram\",\n baseUrl: \"https://www.instagram.com\",\n maxPostLength: 2200,\n supportsMedia: true,\n supportsThreads: false\n }, options);\n};\n","import { createSocialPlatformProvider, type SocialProviderOptions } from \"./platform\";\n\nexport const createLinkedInProvider = (options: SocialProviderOptions = {}) => {\n return createSocialPlatformProvider({\n platform: \"linkedin\",\n displayName: \"LinkedIn\",\n baseUrl: \"https://www.linkedin.com\",\n maxPostLength: 3000,\n supportsMedia: true,\n supportsThreads: false\n }, options);\n};\n","import { createSocialPlatformProvider, type SocialProviderOptions } from \"./platform\";\n\nexport const createRedditProvider = (options: SocialProviderOptions = {}) => {\n return createSocialPlatformProvider({\n platform: \"reddit\",\n displayName: \"Reddit\",\n baseUrl: \"https://www.reddit.com\",\n maxPostLength: 40000,\n supportsMedia: true,\n supportsThreads: true\n }, options);\n};\n","import { createSocialPlatformProvider, type SocialProviderOptions } from \"./platform\";\n\nexport const createThreadsProvider = (options: SocialProviderOptions = {}) => {\n return createSocialPlatformProvider({\n platform: \"threads\",\n displayName: \"Threads\",\n baseUrl: \"https://www.threads.net\",\n maxPostLength: 500,\n supportsMedia: true,\n supportsThreads: true\n }, options);\n};\n","import { createSocialPlatformProvider, type SocialProviderOptions } from \"./platform\";\n\nexport const createTikTokProvider = (options: SocialProviderOptions = {}) => {\n return createSocialPlatformProvider({\n platform: \"tiktok\",\n displayName: \"TikTok\",\n baseUrl: \"https://www.tiktok.com\",\n maxPostLength: 2200,\n supportsMedia: true,\n supportsThreads: false\n }, options);\n};\n","import { createSocialPlatformProvider, type SocialProviderOptions } from \"./platform\";\n\nexport const createXProvider = (options: SocialProviderOptions = {}) => {\n return createSocialPlatformProvider({\n platform: \"x\",\n displayName: \"X\",\n baseUrl: \"https://x.com\",\n maxPostLength: 280,\n supportsMedia: true,\n supportsThreads: true\n }, options);\n};\n","const DEFAULT_PROVIDER_USER_AGENT = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 13_6_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36\";\nconst DEFAULT_PROVIDER_ACCEPT_LANGUAGE = \"en-US,en;q=0.9\";\n\nconst normalizeHeaderValue = (value: string | undefined, fallback: string): string => {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : fallback;\n};\n\nexport const providerRequestHeaders = {\n \"user-agent\": normalizeHeaderValue(process.env.OPDEVBROWSER_PROVIDER_USER_AGENT, DEFAULT_PROVIDER_USER_AGENT),\n \"accept-language\": normalizeHeaderValue(process.env.OPDEVBROWSER_PROVIDER_ACCEPT_LANGUAGE, DEFAULT_PROVIDER_ACCEPT_LANGUAGE)\n} as const;\n\n","import { execFile } from \"child_process\";\nimport { mkdtemp, readdir, rm } from \"fs/promises\";\nimport { tmpdir } from \"os\";\nimport * as path from \"path\";\nimport { promisify } from \"util\";\nimport { readFallbackString, resolveProviderBrowserFallback } from \"../browser-fallback\";\nimport { providerErrorCodeFromReasonCode } from \"../errors\";\nimport type {\n BrowserFallbackPort,\n JsonValue,\n ProviderContext,\n ProviderRecoveryHints,\n ProviderReasonCode\n} from \"../types\";\n\nconst execFileAsync = promisify(execFile);\n\nconst TRANSCRIPT_FETCH_HEADERS = {\n accept: \"application/xml,text/xml,text/vtt,*/*\"\n} as const;\n\nconst YOUTUBEI_HEADERS = {\n accept: \"application/json\",\n \"content-type\": \"application/json\"\n} as const;\n\nconst YOUTUBEI_PLAYER_CONTEXT = {\n client: {\n clientName: \"ANDROID\",\n clientVersion: \"20.10.38\"\n }\n} as const;\n\nconst APIFY_HEADERS = {\n accept: \"application/json\",\n \"content-type\": \"application/json\"\n} as const;\n\ntype TranscriptPlannerStrategy = \"youtubei\" | \"native_caption_parse\" | \"ytdlp_audio_asr\" | \"apify\";\n\ntype LegacyTranscriptStrategy = \"ytdlp_subtitle\" | \"optional_asr\";\n\nexport type YouTubeTranscriptMode = \"auto\" | \"web\" | \"no-auto\" | \"yt-dlp\" | \"apify\";\n\nexport type YouTubeTranscriptModeInput = YouTubeTranscriptMode | \"ytdlp\";\n\nexport type YouTubeTranscriptStrategyDetail =\n | \"youtubei\"\n | \"native_caption_parse\"\n | \"ytdlp_audio_asr\"\n | \"apify\"\n | \"browser_assisted\";\n\nexport type YouTubeTranscriptStrategy = \"native_caption_parse\" | \"optional_asr\" | \"browser_assisted\";\n\nexport interface YouTubeTranscriptLegalChecklist {\n approvalExpiryDate: string;\n signedOff: boolean;\n approvedTranscriptStrategies: Array<\n | YouTubeTranscriptStrategyDetail\n | YouTubeTranscriptStrategy\n | LegacyTranscriptStrategy\n >;\n}\n\nexport interface YouTubeTranscriptResolverConfig {\n modeDefault: YouTubeTranscriptMode;\n strategyOrder: Array<TranscriptPlannerStrategy | LegacyTranscriptStrategy>;\n enableYtdlp: boolean;\n enableAsr: boolean;\n enableYtdlpAudioAsr: boolean;\n enableApify: boolean;\n apifyActorId: string;\n enableBrowserFallback: boolean;\n ytdlpTimeoutMs: number;\n}\n\nexport interface YouTubeTranscriptAttempt {\n strategy: YouTubeTranscriptStrategyDetail;\n ok: boolean;\n reasonCode?: ProviderReasonCode;\n message?: string;\n details?: Record<string, JsonValue>;\n}\n\nexport interface YouTubeTranscriptSuccess {\n ok: true;\n mode: YouTubeTranscriptMode;\n text: string;\n language: string;\n transcriptStrategy: YouTubeTranscriptStrategy;\n transcriptStrategyDetail: YouTubeTranscriptStrategyDetail;\n attemptChain: YouTubeTranscriptAttempt[];\n}\n\nexport interface YouTubeTranscriptFailure {\n ok: false;\n mode: YouTubeTranscriptMode;\n reasonCode: ProviderReasonCode;\n attemptChain: YouTubeTranscriptAttempt[];\n}\n\nexport type YouTubeTranscriptResolution = YouTubeTranscriptSuccess | YouTubeTranscriptFailure;\n\nexport interface YouTubeTranscriptResolverDependencies {\n context: ProviderContext;\n watchUrl: string;\n pageHtml: string;\n legalChecklist: YouTubeTranscriptLegalChecklist;\n config?: Partial<YouTubeTranscriptResolverConfig>;\n mode?: YouTubeTranscriptModeInput | null;\n browserFallbackPort?: BrowserFallbackPort;\n recoveryHints?: ProviderRecoveryHints;\n allowBrowserFallbackEscalation?: boolean;\n asrTranscribe?: (args: {\n watchUrl: string;\n context: ProviderContext;\n audioFilePath?: string;\n }) => Promise<{ text: string; language?: string } | null>;\n}\n\ntype TranscriptFailureResult = {\n ok: false;\n reasonCode: ProviderReasonCode;\n message: string;\n};\n\ntype TranscriptSuccessResult = {\n ok: true;\n text: string;\n language: string;\n};\n\ntype TranscriptFetchResponse = {\n ok: boolean;\n status: number;\n payload: string;\n};\n\ntype CaptionTrack = {\n baseUrl: string;\n languageCode: string;\n name: string;\n kind?: string;\n vssId?: string;\n};\n\ntype ApifyRunResponse = {\n data?: {\n defaultDatasetId?: string;\n };\n};\n\nconst DEFAULT_TRANSCRIPT_RESOLVER_CONFIG: YouTubeTranscriptResolverConfig = {\n modeDefault: \"auto\",\n strategyOrder: [\"youtubei\", \"native_caption_parse\", \"ytdlp_audio_asr\", \"apify\"],\n enableYtdlp: false,\n enableAsr: false,\n enableYtdlpAudioAsr: true,\n enableApify: true,\n apifyActorId: \"streamers/youtube-scraper\",\n enableBrowserFallback: false,\n ytdlpTimeoutMs: 10000\n};\n\nconst dedupeStrategyOrder = (\n order: Array<TranscriptPlannerStrategy | LegacyTranscriptStrategy>\n): Array<TranscriptPlannerStrategy | LegacyTranscriptStrategy> => {\n const seen = new Set<string>();\n const output: Array<TranscriptPlannerStrategy | LegacyTranscriptStrategy> = [];\n for (const strategy of order) {\n if (seen.has(strategy)) continue;\n seen.add(strategy);\n output.push(strategy);\n }\n return output;\n};\n\nconst mapLegacyModeAlias = (value: string): YouTubeTranscriptMode | null => {\n if (value === \"ytdlp\") return \"yt-dlp\";\n if (value === \"auto\" || value === \"web\" || value === \"no-auto\" || value === \"yt-dlp\" || value === \"apify\") {\n return value;\n }\n return null;\n};\n\nexport const normalizeYouTubeTranscriptMode = (\n value: unknown\n): YouTubeTranscriptMode | null => {\n if (typeof value !== \"string\") return null;\n return mapLegacyModeAlias(value.trim().toLowerCase());\n};\n\nconst resolveMode = (\n inputMode: YouTubeTranscriptModeInput | null | undefined,\n fallbackMode: YouTubeTranscriptMode\n): YouTubeTranscriptMode => {\n const normalizedInput = normalizeYouTubeTranscriptMode(inputMode);\n if (normalizedInput) return normalizedInput;\n return normalizeYouTubeTranscriptMode(fallbackMode) ?? \"auto\";\n};\n\nexport const resolveYouTubeTranscriptConfig = (\n config: Partial<YouTubeTranscriptResolverConfig> | undefined\n): YouTubeTranscriptResolverConfig => {\n const merged: YouTubeTranscriptResolverConfig = {\n ...DEFAULT_TRANSCRIPT_RESOLVER_CONFIG,\n ...(config ?? {})\n };\n const dedupedOrder = dedupeStrategyOrder(merged.strategyOrder);\n const normalizedModeDefault = normalizeYouTubeTranscriptMode(merged.modeDefault) ?? \"auto\";\n const enableYtdlpAudioAsr = merged.enableYtdlpAudioAsr || merged.enableYtdlp || merged.enableAsr;\n\n return {\n ...merged,\n modeDefault: normalizedModeDefault,\n strategyOrder: dedupedOrder.includes(\"native_caption_parse\")\n ? dedupedOrder\n : [\"native_caption_parse\", ...dedupedOrder],\n enableYtdlpAudioAsr,\n ytdlpTimeoutMs: Math.min(120000, Math.max(1000, Math.floor(merged.ytdlpTimeoutMs))),\n apifyActorId: merged.apifyActorId.trim() || DEFAULT_TRANSCRIPT_RESOLVER_CONFIG.apifyActorId\n };\n};\n\nconst decodeHtml = (value: string): string => {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/'/g, \"'\")\n .replace(/"/g, '\"')\n .replace(/\\s+/g, \" \")\n .trim();\n};\n\nconst normalizeEscapedValue = (value: string): string => {\n return value\n .replace(/\\\\u0026/g, \"&\")\n .replace(/\\\\\\//g, \"/\")\n .replace(/\\\\u003d/g, \"=\")\n .replace(/\\\\u002F/g, \"/\");\n};\n\nconst findBalancedSlice = (\n value: string,\n startIndex: number,\n openChar: string,\n closeChar: string\n): string | null => {\n let depth = 0;\n let inString = false;\n let escaping = false;\n for (let index = startIndex; index < value.length; index += 1) {\n const char = value[index];\n if (escaping) {\n escaping = false;\n continue;\n }\n if (char === \"\\\\\") {\n if (inString) escaping = true;\n continue;\n }\n if (char === '\"') {\n inString = !inString;\n continue;\n }\n if (inString) continue;\n\n if (char === openChar) {\n depth += 1;\n continue;\n }\n if (char === closeChar) {\n depth -= 1;\n if (depth === 0) {\n return value.slice(startIndex, index + 1);\n }\n }\n }\n return null;\n};\n\nconst findJsonSegmentAfter = (\n value: string,\n marker: string,\n openChar: \"{\" | \"[\",\n closeChar: \"}\" | \"]\"\n): string | null => {\n const markerIndex = value.indexOf(marker);\n if (markerIndex < 0) return null;\n const openIndex = value.indexOf(openChar, markerIndex + marker.length);\n if (openIndex < 0) return null;\n return findBalancedSlice(value, openIndex, openChar, closeChar);\n};\n\nconst parseJson = <T>(value: string | null): T | null => {\n if (!value) return null;\n try {\n return JSON.parse(value) as T;\n } catch {\n try {\n return JSON.parse(normalizeEscapedValue(value)) as T;\n } catch {\n return null;\n }\n }\n};\n\nconst trackNameFromValue = (value: unknown): string => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return \"\";\n const record = value as Record<string, unknown>;\n if (typeof record.simpleText === \"string\") return decodeHtml(record.simpleText);\n if (Array.isArray(record.runs)) {\n return record.runs\n .filter((run): run is { text: string } => Boolean(run && typeof run === \"object\" && !Array.isArray(run) && typeof (run as { text?: unknown }).text === \"string\"))\n .map((run) => decodeHtml(run.text))\n .join(\"\")\n .trim();\n }\n return \"\";\n};\n\nconst normalizeCaptionTracks = (parsed: unknown[]): CaptionTrack[] => {\n const tracks: CaptionTrack[] = [];\n for (const candidate of parsed) {\n if (!candidate || typeof candidate !== \"object\" || Array.isArray(candidate)) continue;\n const record = candidate as Record<string, unknown>;\n const rawBaseUrl = record.baseUrl;\n const rawLanguage = record.languageCode;\n if (typeof rawBaseUrl !== \"string\" || typeof rawLanguage !== \"string\") continue;\n tracks.push({\n baseUrl: normalizeEscapedValue(rawBaseUrl),\n languageCode: rawLanguage,\n name: trackNameFromValue(record.name),\n kind: typeof record.kind === \"string\" ? record.kind : undefined,\n vssId: typeof record.vssId === \"string\" ? record.vssId : undefined\n });\n }\n return tracks;\n};\n\nconst extractCaptionTracks = (html: string): CaptionTrack[] => {\n const block = findJsonSegmentAfter(html, '\"captionTracks\":', \"[\", \"]\");\n const parsed = parseJson<unknown[]>(block);\n if (!Array.isArray(parsed)) return [];\n return normalizeCaptionTracks(parsed);\n};\n\nconst extractCaptionTracksFromTracklistRenderer = (value: unknown): CaptionTrack[] => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return [];\n const captionTracks = (value as Record<string, unknown>).captionTracks;\n return Array.isArray(captionTracks) ? normalizeCaptionTracks(captionTracks) : [];\n};\n\nconst isAutomaticCaptionTrack = (track: CaptionTrack): boolean => {\n if (track.kind?.toLowerCase() === \"asr\") return true;\n if (track.vssId?.startsWith(\"a.\")) return true;\n if (/auto[- ]generated/i.test(track.name)) return true;\n return false;\n};\n\nconst isEnglishLike = (languageCode: string): boolean => {\n return languageCode.toLowerCase().startsWith(\"en\");\n};\n\nconst pickCaptionTrack = (tracks: CaptionTrack[], manualOnly: boolean): CaptionTrack | null => {\n const eligible = manualOnly\n ? tracks.filter((track) => !isAutomaticCaptionTrack(track))\n : tracks;\n if (eligible.length === 0) return null;\n\n const sorted = [...eligible].sort((left, right) => {\n const leftManual = isAutomaticCaptionTrack(left) ? 0 : 1;\n const rightManual = isAutomaticCaptionTrack(right) ? 0 : 1;\n if (leftManual !== rightManual) return rightManual - leftManual;\n\n const leftEnglish = isEnglishLike(left.languageCode) ? 1 : 0;\n const rightEnglish = isEnglishLike(right.languageCode) ? 1 : 0;\n if (leftEnglish !== rightEnglish) return rightEnglish - leftEnglish;\n\n return left.languageCode.localeCompare(right.languageCode);\n });\n\n return sorted[0] ?? null;\n};\n\nexport const findCaptionBaseUrl = (html: string): string | null => {\n const track = pickCaptionTrack(extractCaptionTracks(html), false);\n return track?.baseUrl ?? null;\n};\n\nexport const findTranscriptLanguage = (html: string): string => {\n const track = pickCaptionTrack(extractCaptionTracks(html), false);\n return track?.languageCode ?? \"unknown\";\n};\n\nconst parseTranscriptXml = (xml: string): string => {\n const chunks = [...xml.matchAll(/<text[^>]*>([\\s\\S]*?)<\\/text>/g)]\n .map((match) => decodeHtml(match[1] ?? \"\"))\n .filter(Boolean);\n return chunks.join(\"\\n\").trim();\n};\n\nconst parseTranscriptVtt = (vtt: string): string => {\n return vtt\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .filter((line) => !/^WEBVTT/i.test(line))\n .filter((line) => !/^\\d{1,2}:\\d{2}(?::\\d{2})?\\.\\d{3}\\s+-->\\s+\\d{1,2}:\\d{2}(?::\\d{2})?\\.\\d{3}/.test(line))\n .filter((line) => !/^\\d+$/.test(line))\n .join(\"\\n\")\n .trim();\n};\n\nconst parseTranscriptPayload = (payload: string): string => {\n if (payload.includes(\"<text\")) return parseTranscriptXml(payload);\n return parseTranscriptVtt(payload);\n};\n\nconst parseTranscriptJson3 = (payload: string): string => {\n const parsed = parseJson<Record<string, unknown>>(payload);\n if (!parsed) return \"\";\n const events = parsed.events;\n if (!Array.isArray(events)) return \"\";\n\n const lines = events\n .map((event) => {\n if (!event || typeof event !== \"object\" || Array.isArray(event)) return \"\";\n const segs = (event as Record<string, unknown>).segs;\n if (!Array.isArray(segs)) return \"\";\n const text = segs\n .map((segment) => {\n if (!segment || typeof segment !== \"object\" || Array.isArray(segment)) return \"\";\n const utf8 = (segment as Record<string, unknown>).utf8;\n return typeof utf8 === \"string\" ? decodeHtml(utf8) : \"\";\n })\n .join(\"\")\n .trim();\n return text;\n })\n .filter(Boolean);\n\n return lines.join(\"\\n\").trim();\n};\n\nconst toTranscriptFetchReasonCode = (status: number): ProviderReasonCode => {\n if (status === 401 || status === 403) return \"token_required\";\n if (status === 429) return \"rate_limited\";\n return \"transcript_unavailable\";\n};\n\nconst fetchTranscriptPayload = async (\n transcriptUrl: string,\n context: ProviderContext,\n acceptHeader: string\n): Promise<TranscriptFetchResponse> => {\n try {\n const response = await fetch(transcriptUrl, {\n headers: {\n ...TRANSCRIPT_FETCH_HEADERS,\n accept: acceptHeader\n },\n signal: context.signal,\n redirect: \"follow\"\n });\n return {\n ok: response.ok,\n status: response.status,\n payload: await response.text()\n };\n } catch {\n return {\n ok: false,\n status: 0,\n payload: \"\"\n };\n }\n};\n\nconst withQueryParam = (baseUrl: string, key: string, value: string): string => {\n try {\n const url = new URL(baseUrl);\n url.searchParams.set(key, value);\n return url.toString();\n } catch {\n return baseUrl;\n }\n};\n\nconst withoutQueryParam = (baseUrl: string, key: string): string => {\n try {\n const url = new URL(baseUrl);\n url.searchParams.delete(key);\n return url.toString();\n } catch {\n return baseUrl;\n }\n};\n\nconst hasQueryParamValue = (value: string, key: string, expected: string): boolean => {\n try {\n const url = new URL(value);\n return url.searchParams.get(key) === expected;\n } catch {\n return false;\n }\n};\n\nconst parseAnyTranscriptPayload = (payload: string): string => {\n const trimmed = payload.trim();\n if (!trimmed) return \"\";\n if (trimmed.startsWith(\"{\")) return parseTranscriptJson3(trimmed);\n return parseTranscriptPayload(trimmed);\n};\n\nconst resolveNativeCaptionTranscriptFromTracks = async (args: {\n tracks: CaptionTrack[];\n context: ProviderContext;\n manualOnly: boolean;\n}): Promise<TranscriptSuccessResult | TranscriptFailureResult> => {\n const selectedTrack = pickCaptionTrack(args.tracks, args.manualOnly);\n if (!selectedTrack) {\n return {\n ok: false,\n reasonCode: \"caption_missing\",\n message: args.manualOnly\n ? \"No creator-provided caption track was found.\"\n : \"No caption track URL found in page payload.\"\n };\n }\n\n const candidateUrls = [\n withQueryParam(selectedTrack.baseUrl, \"fmt\", \"json3\"),\n withQueryParam(selectedTrack.baseUrl, \"fmt\", \"vtt\"),\n withoutQueryParam(selectedTrack.baseUrl, \"fmt\"),\n selectedTrack.baseUrl\n ].filter((url, index, values) => values.indexOf(url) === index);\n\n let sawEmptyPayload = false;\n let lastHttpFailure: TranscriptFailureResult | null = null;\n\n for (const candidateUrl of candidateUrls) {\n const response = await fetchTranscriptPayload(\n candidateUrl,\n args.context,\n \"application/json,text/plain,text/xml,text/vtt,*/*\"\n );\n\n if (response.ok) {\n const text = hasQueryParamValue(candidateUrl, \"fmt\", \"json3\")\n ? parseTranscriptJson3(response.payload.trim())\n : parseAnyTranscriptPayload(response.payload);\n if (text) {\n return {\n ok: true,\n text,\n language: selectedTrack.languageCode || \"unknown\"\n };\n }\n sawEmptyPayload = true;\n continue;\n }\n\n if (response.status === 401 || response.status === 403 || response.status === 429) {\n return {\n ok: false,\n reasonCode: toTranscriptFetchReasonCode(response.status),\n message: `Caption endpoint returned HTTP ${response.status}.`\n };\n }\n\n if (response.status > 0) {\n lastHttpFailure = {\n ok: false,\n reasonCode: toTranscriptFetchReasonCode(response.status),\n message: `Caption endpoint returned HTTP ${response.status}.`\n };\n }\n }\n\n if (sawEmptyPayload) {\n return {\n ok: false,\n reasonCode: \"transcript_unavailable\",\n message: \"Caption endpoint returned no transcript payload.\"\n };\n }\n\n if (lastHttpFailure) {\n return lastHttpFailure;\n }\n\n return {\n ok: false,\n reasonCode: \"transcript_unavailable\",\n message: \"Caption endpoint request failed.\"\n };\n};\n\nconst resolveNativeCaptionTranscript = async (args: {\n pageHtml: string;\n context: ProviderContext;\n manualOnly: boolean;\n}): Promise<TranscriptSuccessResult | TranscriptFailureResult> => {\n return resolveNativeCaptionTranscriptFromTracks({\n tracks: extractCaptionTracks(args.pageHtml),\n context: args.context,\n manualOnly: args.manualOnly\n });\n};\n\nconst firstNonEmptyMatch = (value: string, patterns: RegExp[]): string | null => {\n for (const pattern of patterns) {\n const match = value.match(pattern)?.[1];\n if (match && match.trim().length > 0) {\n return decodeHtml(normalizeEscapedValue(match));\n }\n }\n return null;\n};\n\nconst findLanguageInPayload = (payload: unknown): string | null => {\n const stack: unknown[] = [payload];\n while (stack.length > 0) {\n const current = stack.pop();\n if (!current) continue;\n if (Array.isArray(current)) {\n for (const entry of current) stack.push(entry);\n continue;\n }\n if (typeof current !== \"object\") continue;\n\n const record = current as Record<string, unknown>;\n const languageCode = record.languageCode;\n if (typeof languageCode === \"string\" && languageCode.trim().length > 0) {\n return languageCode;\n }\n\n for (const value of Object.values(record)) {\n stack.push(value);\n }\n }\n\n return null;\n};\n\nconst parseVideoIdFromWatchUrl = (watchUrl: string): string | null => {\n try {\n const parsed = new URL(watchUrl);\n if (parsed.hostname === \"youtu.be\") {\n const id = parsed.pathname.replace(/^\\//, \"\").trim();\n return id || null;\n }\n const queryId = parsed.searchParams.get(\"v\");\n if (queryId) return queryId;\n const shortsMatch = parsed.pathname.match(/\\/shorts\\/([^/?#]+)/);\n return shortsMatch?.[1] ?? null;\n } catch {\n return null;\n }\n};\n\nconst extractVideoIdFromHtml = (html: string): string | null => {\n return firstNonEmptyMatch(html, [\n /\"videoId\"\\s*:\\s*\"([^\"]+)\"/,\n /\"video_id\"\\s*:\\s*\"([^\"]+)\"/\n ]);\n};\n\nconst resolveYoutubeiTranscript = async (args: {\n watchUrl: string;\n pageHtml: string;\n context: ProviderContext;\n}): Promise<TranscriptSuccessResult | TranscriptFailureResult> => {\n const apiKey = firstNonEmptyMatch(args.pageHtml, [\n /\"INNERTUBE_API_KEY\"\\s*:\\s*\"([^\"]+)\"/,\n /\"innertubeApiKey\"\\s*:\\s*\"([^\"]+)\"/\n ]);\n const videoId = parseVideoIdFromWatchUrl(args.watchUrl) ?? extractVideoIdFromHtml(args.pageHtml);\n\n if (!apiKey || !videoId) {\n return {\n ok: false,\n reasonCode: \"caption_missing\",\n message: \"youtubei transcript bootstrap payload is missing API key or video id.\"\n };\n }\n\n let response: Response;\n try {\n response = await fetch(`https://www.youtube.com/youtubei/v1/player?key=${encodeURIComponent(apiKey)}`, {\n method: \"POST\",\n headers: YOUTUBEI_HEADERS,\n body: JSON.stringify({\n context: YOUTUBEI_PLAYER_CONTEXT,\n videoId\n }),\n signal: args.context.signal\n });\n } catch {\n return {\n ok: false,\n reasonCode: \"transcript_unavailable\",\n message: \"youtubei player endpoint request failed.\"\n };\n }\n\n if (!response.ok) {\n return {\n ok: false,\n reasonCode: toTranscriptFetchReasonCode(response.status),\n message: `youtubei player endpoint returned HTTP ${response.status}.`\n };\n }\n\n const payloadText = await response.text();\n const payload = parseJson<unknown>(payloadText);\n if (!payload) {\n return {\n ok: false,\n reasonCode: \"transcript_unavailable\",\n message: \"youtubei player endpoint returned malformed JSON.\"\n };\n }\n\n const captionsTracklistRenderer = ((payload as Record<string, unknown>).captions as Record<string, unknown> | undefined)\n ?.playerCaptionsTracklistRenderer;\n const tracks = extractCaptionTracksFromTracklistRenderer(captionsTracklistRenderer);\n if (tracks.length === 0) {\n return {\n ok: false,\n reasonCode: \"caption_missing\",\n message: \"youtubei player payload did not include caption tracks.\"\n };\n }\n\n const resolved = await resolveNativeCaptionTranscriptFromTracks({\n tracks,\n context: args.context,\n manualOnly: false\n });\n if (!resolved.ok) {\n return resolved;\n }\n\n return {\n ok: true,\n text: resolved.text,\n language: resolved.language || findLanguageInPayload(payload) || findTranscriptLanguage(args.pageHtml)\n };\n};\n\nconst normalizeErrorMessage = (error: unknown): string => {\n if (error instanceof Error) return error.message;\n return String(error);\n};\n\nconst toExecFailureReasonCode = (\n message: string,\n fallback: ProviderReasonCode\n): ProviderReasonCode => {\n if (/ENOENT|not found|spawn\\s+yt-dlp/i.test(message)) return \"env_limited\";\n if (/timeout|timed out|ETIMEDOUT/i.test(message)) return \"transcript_unavailable\";\n if (/429|rate\\s*limit/i.test(message)) return \"rate_limited\";\n if (/401|403|forbidden|unauthorized/i.test(message)) return \"token_required\";\n return fallback;\n};\n\nconst resolveYtdlpAudioAsrTranscript = async (args: {\n watchUrl: string;\n context: ProviderContext;\n timeoutMs: number;\n asrTranscribe: NonNullable<YouTubeTranscriptResolverDependencies[\"asrTranscribe\"]>;\n}): Promise<TranscriptSuccessResult | TranscriptFailureResult> => {\n const tempDir = await mkdtemp(path.join(tmpdir(), \"opendevbrowser-ytdlp-\"));\n try {\n const outputTemplate = path.join(tempDir, \"audio.%(ext)s\");\n await execFileAsync(\n \"yt-dlp\",\n [\n \"-x\",\n \"--audio-format\",\n \"mp3\",\n \"--no-playlist\",\n \"--no-warnings\",\n \"-o\",\n outputTemplate,\n args.watchUrl\n ],\n {\n timeout: args.timeoutMs,\n maxBuffer: 8 * 1024 * 1024\n }\n );\n\n const files = await readdir(tempDir);\n const audioFile = files\n .filter((file) => /\\.(mp3|m4a|wav|opus|ogg)$/i.test(file))\n .sort()[0];\n if (!audioFile) {\n return {\n ok: false,\n reasonCode: \"transcript_unavailable\",\n message: \"yt-dlp audio download did not produce an audio file.\"\n };\n }\n\n const transcript = await args.asrTranscribe({\n watchUrl: args.watchUrl,\n context: args.context,\n audioFilePath: path.join(tempDir, audioFile)\n });\n\n if (!transcript?.text.trim()) {\n return {\n ok: false,\n reasonCode: \"transcript_unavailable\",\n message: \"ASR returned an empty transcript.\"\n };\n }\n\n return {\n ok: true,\n text: transcript.text,\n language: transcript.language ?? \"unknown\"\n };\n } catch (error) {\n const message = normalizeErrorMessage(error);\n return {\n ok: false,\n reasonCode: toExecFailureReasonCode(message, \"transcript_unavailable\"),\n message\n };\n } finally {\n await rm(tempDir, { recursive: true, force: true }).catch(() => {\n // Best-effort temp cleanup.\n });\n }\n};\n\nconst readApifyTextCandidate = (value: unknown): string => {\n if (typeof value === \"string\") return value.trim();\n if (Array.isArray(value)) {\n const joined = value\n .map((entry) => {\n if (typeof entry === \"string\") return entry;\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) return \"\";\n const text = (entry as Record<string, unknown>).text;\n return typeof text === \"string\" ? text : \"\";\n })\n .filter(Boolean)\n .join(\"\\n\")\n .trim();\n return joined;\n }\n return \"\";\n};\n\nconst resolveApifyTranscriptFromItems = (items: unknown): { text: string; language: string } | null => {\n if (!Array.isArray(items)) return null;\n const transcriptKeys = [\"transcript\", \"captions\", \"subtitles\", \"text\"];\n\n for (const item of items) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n const record = item as Record<string, unknown>;\n\n for (const key of transcriptKeys) {\n const value = readApifyTextCandidate(record[key]);\n if (!value) continue;\n const language = typeof record.languageCode === \"string\"\n ? record.languageCode\n : typeof record.language === \"string\"\n ? record.language\n : \"unknown\";\n return {\n text: value,\n language\n };\n }\n }\n\n return null;\n};\n\nconst resolveApifyTranscript = async (args: {\n watchUrl: string;\n context: ProviderContext;\n actorId: string;\n token: string;\n}): Promise<TranscriptSuccessResult | TranscriptFailureResult> => {\n const encodedActorId = encodeURIComponent(args.actorId);\n const runUrl = `https://api.apify.com/v2/acts/${encodedActorId}/runs?token=${encodeURIComponent(args.token)}&waitForFinish=120`;\n\n let runResponse: Response;\n try {\n runResponse = await fetch(runUrl, {\n method: \"POST\",\n headers: APIFY_HEADERS,\n signal: args.context.signal,\n body: JSON.stringify({\n startUrls: [{ url: args.watchUrl }]\n })\n });\n } catch {\n return {\n ok: false,\n reasonCode: \"transcript_unavailable\",\n message: \"Apify actor request failed.\"\n };\n }\n\n if (!runResponse.ok) {\n return {\n ok: false,\n reasonCode: toTranscriptFetchReasonCode(runResponse.status),\n message: `Apify actor request returned HTTP ${runResponse.status}.`\n };\n }\n\n const runPayload = parseJson<ApifyRunResponse>(await runResponse.text());\n const datasetId = runPayload?.data?.defaultDatasetId;\n if (!datasetId) {\n return {\n ok: false,\n reasonCode: \"transcript_unavailable\",\n message: \"Apify actor response did not include a dataset id.\"\n };\n }\n\n const datasetUrl = `https://api.apify.com/v2/datasets/${encodeURIComponent(datasetId)}/items?token=${encodeURIComponent(args.token)}&clean=true&format=json`;\n\n let datasetResponse: Response;\n try {\n datasetResponse = await fetch(datasetUrl, {\n headers: {\n accept: \"application/json\"\n },\n signal: args.context.signal\n });\n } catch {\n return {\n ok: false,\n reasonCode: \"transcript_unavailable\",\n message: \"Apify dataset request failed.\"\n };\n }\n\n if (!datasetResponse.ok) {\n return {\n ok: false,\n reasonCode: toTranscriptFetchReasonCode(datasetResponse.status),\n message: `Apify dataset request returned HTTP ${datasetResponse.status}.`\n };\n }\n\n const transcript = resolveApifyTranscriptFromItems(parseJson<unknown>(await datasetResponse.text()));\n if (!transcript) {\n return {\n ok: false,\n reasonCode: \"transcript_unavailable\",\n message: \"Apify dataset did not include transcript text.\"\n };\n }\n\n return {\n ok: true,\n text: transcript.text,\n language: transcript.language\n };\n};\n\nconst isStrategyApproved = (\n checklist: YouTubeTranscriptLegalChecklist,\n strategy: YouTubeTranscriptStrategyDetail\n): boolean => {\n const expiry = Date.parse(checklist.approvalExpiryDate);\n if (!checklist.signedOff || Number.isNaN(expiry) || expiry <= Date.now()) {\n return false;\n }\n\n if (strategy === \"ytdlp_audio_asr\") {\n return checklist.approvedTranscriptStrategies.includes(\"ytdlp_audio_asr\")\n || checklist.approvedTranscriptStrategies.includes(\"optional_asr\")\n || checklist.approvedTranscriptStrategies.includes(\"ytdlp_subtitle\");\n }\n\n return checklist.approvedTranscriptStrategies.includes(strategy);\n};\n\nconst modeBaseStrategies = (mode: YouTubeTranscriptMode): TranscriptPlannerStrategy[] => {\n switch (mode) {\n case \"auto\":\n return [\"youtubei\", \"native_caption_parse\", \"ytdlp_audio_asr\", \"apify\"];\n case \"web\":\n return [\"youtubei\", \"native_caption_parse\"];\n case \"no-auto\":\n return [\"native_caption_parse\", \"ytdlp_audio_asr\"];\n case \"yt-dlp\":\n return [\"ytdlp_audio_asr\"];\n case \"apify\":\n return [\"apify\"];\n }\n};\n\nconst mapStrategyOrderEntry = (\n strategy: TranscriptPlannerStrategy | LegacyTranscriptStrategy\n): TranscriptPlannerStrategy[] => {\n if (strategy === \"youtubei\" || strategy === \"native_caption_parse\" || strategy === \"ytdlp_audio_asr\" || strategy === \"apify\") {\n return [strategy];\n }\n if (strategy === \"ytdlp_subtitle\") {\n return [\"ytdlp_audio_asr\"];\n }\n return [\"ytdlp_audio_asr\", \"apify\"];\n};\n\nconst planStrategies = (\n mode: YouTubeTranscriptMode,\n strategyOrder: Array<TranscriptPlannerStrategy | LegacyTranscriptStrategy>\n): TranscriptPlannerStrategy[] => {\n const base = modeBaseStrategies(mode);\n const allowed = new Set(base);\n const ordered: TranscriptPlannerStrategy[] = [];\n\n for (const entry of strategyOrder) {\n for (const mapped of mapStrategyOrderEntry(entry)) {\n if (!allowed.has(mapped) || ordered.includes(mapped)) continue;\n ordered.push(mapped);\n }\n }\n\n for (const fallback of base) {\n if (ordered.includes(fallback)) continue;\n ordered.push(fallback);\n }\n\n return ordered;\n};\n\nconst mapDetailToBucket = (detail: YouTubeTranscriptStrategyDetail): YouTubeTranscriptStrategy => {\n switch (detail) {\n case \"youtubei\":\n case \"native_caption_parse\":\n return \"native_caption_parse\";\n case \"ytdlp_audio_asr\":\n case \"apify\":\n return \"optional_asr\";\n case \"browser_assisted\":\n return \"browser_assisted\";\n }\n};\n\nconst createFailure = (\n mode: YouTubeTranscriptMode,\n reasonCode: ProviderReasonCode,\n attemptChain: YouTubeTranscriptAttempt[]\n): YouTubeTranscriptFailure => ({\n ok: false,\n mode,\n reasonCode,\n attemptChain\n});\n\nconst createAttempt = (\n strategy: YouTubeTranscriptStrategyDetail,\n reasonCode: ProviderReasonCode,\n message: string,\n details?: Record<string, JsonValue>\n): YouTubeTranscriptAttempt => ({\n strategy,\n ok: false,\n reasonCode,\n message,\n ...(details ? { details } : {})\n});\n\nconst isForcedMode = (mode: YouTubeTranscriptMode): boolean => {\n return mode === \"yt-dlp\" || mode === \"apify\";\n};\n\nconst isYtdlpSubtitleAliasConfigured = (\n config: YouTubeTranscriptResolverConfig\n): boolean => config.strategyOrder.includes(\"ytdlp_subtitle\");\n\nconst resolveApifyToken = (): string | null => {\n const token = process.env.APIFY_TOKEN ?? process.env.APIFY_API_TOKEN;\n if (!token || !token.trim()) return null;\n return token.trim();\n};\n\nconst precheckStrategyAvailability = (args: {\n strategy: TranscriptPlannerStrategy;\n config: YouTubeTranscriptResolverConfig;\n hasAsrTranscriber: boolean;\n apifyToken: string | null;\n}): TranscriptFailureResult | null => {\n if (args.strategy === \"youtubei\") {\n return null;\n }\n\n if (args.strategy === \"ytdlp_audio_asr\") {\n if (!args.config.enableYtdlpAudioAsr) {\n return {\n ok: false,\n reasonCode: \"env_limited\",\n message: \"yt-dlp audio ASR strategy is disabled by configuration.\"\n };\n }\n if (!args.hasAsrTranscriber) {\n return {\n ok: false,\n reasonCode: \"env_limited\",\n message: \"ASR engine is not configured.\"\n };\n }\n return null;\n }\n\n if (args.strategy === \"apify\") {\n if (!args.config.enableApify) {\n return {\n ok: false,\n reasonCode: \"env_limited\",\n message: \"Apify strategy is disabled by configuration.\"\n };\n }\n if (!args.apifyToken) {\n return {\n ok: false,\n reasonCode: \"token_required\",\n message: \"APIFY_TOKEN is required to use the Apify transcript strategy.\"\n };\n }\n return null;\n }\n\n return null;\n};\n\nconst withLegacyYtdlpAliasNote = (\n message: string,\n config: YouTubeTranscriptResolverConfig\n): string => {\n if (!isYtdlpSubtitleAliasConfigured(config)) return message;\n return `${message} (legacy ytdlp_subtitle alias mapped to ytdlp_audio_asr)`;\n};\n\nconst isDeferredFallbackReason = (reasonCode: ProviderReasonCode): boolean => {\n return reasonCode === \"env_limited\" || reasonCode === \"token_required\";\n};\n\nconst canAttemptTranscriptBrowserFallback = (args: {\n forcedMode: boolean;\n config: YouTubeTranscriptResolverConfig;\n browserFallbackPort?: BrowserFallbackPort;\n allowBrowserFallbackEscalation?: boolean;\n}): boolean => {\n return !args.forcedMode\n && args.config.enableBrowserFallback\n && Boolean(args.browserFallbackPort)\n && args.allowBrowserFallbackEscalation !== false;\n};\n\nconst resolveStrategyFailureReason = (\n fallback: ProviderReasonCode,\n attempts: YouTubeTranscriptAttempt[]\n): ProviderReasonCode => {\n for (let index = attempts.length - 1; index >= 0; index -= 1) {\n const reasonCode = attempts[index]?.reasonCode;\n if (!reasonCode) continue;\n if (!isDeferredFallbackReason(reasonCode)) {\n return reasonCode;\n }\n }\n for (let index = attempts.length - 1; index >= 0; index -= 1) {\n const reasonCode = attempts[index]?.reasonCode;\n if (!reasonCode || reasonCode === \"env_limited\") continue;\n return reasonCode;\n }\n return attempts.at(-1)?.reasonCode ?? fallback;\n};\n\nexport const resolveYouTubeTranscript = async (\n deps: YouTubeTranscriptResolverDependencies\n): Promise<YouTubeTranscriptResolution> => {\n const config = resolveYouTubeTranscriptConfig(deps.config);\n const mode = resolveMode(deps.mode, config.modeDefault);\n const forcedMode = isForcedMode(mode);\n const attemptChain: YouTubeTranscriptAttempt[] = [];\n const planned = planStrategies(mode, config.strategyOrder);\n const apifyToken = resolveApifyToken();\n\n for (const strategy of planned) {\n const availability = precheckStrategyAvailability({\n strategy,\n config,\n hasAsrTranscriber: Boolean(deps.asrTranscribe),\n apifyToken\n });\n\n if (availability) {\n const message = strategy === \"ytdlp_audio_asr\"\n ? withLegacyYtdlpAliasNote(availability.message, config)\n : availability.message;\n attemptChain.push(createAttempt(strategy, availability.reasonCode, message));\n if (forcedMode) {\n return createFailure(mode, availability.reasonCode, attemptChain);\n }\n continue;\n }\n\n if (!isStrategyApproved(deps.legalChecklist, strategy)) {\n const message = `Legal gate blocked transcript strategy: ${strategy}`;\n attemptChain.push(createAttempt(strategy, \"strategy_unapproved\", message));\n if (forcedMode) {\n return createFailure(mode, \"strategy_unapproved\", attemptChain);\n }\n continue;\n }\n\n if (strategy === \"youtubei\") {\n const resolved = await resolveYoutubeiTranscript({\n watchUrl: deps.watchUrl,\n pageHtml: deps.pageHtml,\n context: deps.context\n });\n\n if (!resolved.ok) {\n attemptChain.push(createAttempt(strategy, resolved.reasonCode, resolved.message));\n continue;\n }\n\n attemptChain.push({ strategy, ok: true });\n return {\n ok: true,\n mode,\n text: resolved.text,\n language: resolved.language,\n transcriptStrategy: mapDetailToBucket(strategy),\n transcriptStrategyDetail: strategy,\n attemptChain\n };\n }\n\n if (strategy === \"native_caption_parse\") {\n const resolved = await resolveNativeCaptionTranscript({\n pageHtml: deps.pageHtml,\n context: deps.context,\n manualOnly: mode === \"no-auto\"\n });\n\n if (!resolved.ok) {\n attemptChain.push(createAttempt(strategy, resolved.reasonCode, resolved.message));\n continue;\n }\n\n attemptChain.push({ strategy, ok: true });\n return {\n ok: true,\n mode,\n text: resolved.text,\n language: resolved.language,\n transcriptStrategy: mapDetailToBucket(strategy),\n transcriptStrategyDetail: strategy,\n attemptChain\n };\n }\n\n if (strategy === \"ytdlp_audio_asr\") {\n const asrTranscribe = deps.asrTranscribe as NonNullable<YouTubeTranscriptResolverDependencies[\"asrTranscribe\"]>;\n\n const resolved = await resolveYtdlpAudioAsrTranscript({\n watchUrl: deps.watchUrl,\n context: deps.context,\n timeoutMs: config.ytdlpTimeoutMs,\n asrTranscribe\n });\n\n if (!resolved.ok) {\n const message = withLegacyYtdlpAliasNote(resolved.message, config);\n attemptChain.push(createAttempt(strategy, resolved.reasonCode, message));\n continue;\n }\n\n const successMessage = isYtdlpSubtitleAliasConfigured(config)\n ? \"legacy ytdlp_subtitle alias mapped to ytdlp_audio_asr\"\n : undefined;\n attemptChain.push({\n strategy,\n ok: true,\n ...(successMessage ? { message: successMessage } : {})\n });\n return {\n ok: true,\n mode,\n text: resolved.text,\n language: resolved.language,\n transcriptStrategy: mapDetailToBucket(strategy),\n transcriptStrategyDetail: strategy,\n attemptChain\n };\n }\n\n if (strategy === \"apify\") {\n const ensuredApifyToken = apifyToken as string;\n\n const resolved = await resolveApifyTranscript({\n watchUrl: deps.watchUrl,\n context: deps.context,\n actorId: config.apifyActorId,\n token: ensuredApifyToken\n });\n\n if (!resolved.ok) {\n attemptChain.push(createAttempt(strategy, resolved.reasonCode, resolved.message));\n continue;\n }\n\n attemptChain.push({ strategy, ok: true });\n return {\n ok: true,\n mode,\n text: resolved.text,\n language: resolved.language,\n transcriptStrategy: mapDetailToBucket(strategy),\n transcriptStrategyDetail: strategy,\n attemptChain\n };\n }\n }\n\n if (canAttemptTranscriptBrowserFallback({\n forcedMode,\n config,\n browserFallbackPort: deps.browserFallbackPort,\n allowBrowserFallbackEscalation: deps.allowBrowserFallbackEscalation\n })) {\n const fallback = await resolveProviderBrowserFallback({\n browserFallbackPort: deps.browserFallbackPort as BrowserFallbackPort,\n allowEscalation: deps.allowBrowserFallbackEscalation,\n provider: \"social/youtube\",\n source: \"social\",\n operation: \"fetch\",\n reasonCode: \"transcript_unavailable\",\n url: deps.watchUrl,\n context: deps.context,\n details: {\n request: \"youtube_transcript\"\n },\n recoveryHints: deps.recoveryHints,\n suspendedIntent: {\n kind: \"youtube.transcript\",\n provider: \"social/youtube\",\n source: \"social\",\n operation: \"fetch\"\n }\n });\n\n if (fallback) {\n if (fallback.disposition !== \"completed\") {\n const fallbackDiagnostics = (\n fallback.details?.cookieDiagnostics\n && typeof fallback.details.cookieDiagnostics === \"object\"\n && !Array.isArray(fallback.details.cookieDiagnostics)\n )\n ? { cookieDiagnostics: fallback.details.cookieDiagnostics as Record<string, JsonValue> }\n : undefined;\n attemptChain.push({\n strategy: \"browser_assisted\",\n ok: false,\n reasonCode: fallback.reasonCode,\n message: typeof fallback.details?.message === \"string\" ? fallback.details.message : \"Browser fallback failed.\",\n ...(fallbackDiagnostics ? { details: fallbackDiagnostics } : {})\n });\n return createFailure(mode, fallback.reasonCode, attemptChain);\n }\n\n const html = readFallbackString(fallback.output, \"html\");\n if (!html) {\n attemptChain.push(createAttempt(\"browser_assisted\", \"env_limited\", \"Browser fallback did not return page HTML.\"));\n return createFailure(mode, \"env_limited\", attemptChain);\n }\n\n const nativeResolved = await resolveNativeCaptionTranscript({\n pageHtml: html,\n context: deps.context,\n manualOnly: mode === \"no-auto\"\n });\n\n if (!nativeResolved.ok) {\n attemptChain.push(createAttempt(\"browser_assisted\", nativeResolved.reasonCode, nativeResolved.message));\n return createFailure(mode, nativeResolved.reasonCode, attemptChain);\n }\n\n attemptChain.push({ strategy: \"browser_assisted\", ok: true });\n return {\n ok: true,\n mode,\n text: nativeResolved.text,\n language: nativeResolved.language,\n transcriptStrategy: \"browser_assisted\",\n transcriptStrategyDetail: \"browser_assisted\",\n attemptChain\n };\n }\n }\n\n return createFailure(\n mode,\n resolveStrategyFailureReason(\"transcript_unavailable\", attemptChain),\n attemptChain\n );\n};\n\nexport const asTranscriptProviderError = (\n message: string,\n reasonCode: ProviderReasonCode\n): {\n code: ReturnType<typeof providerErrorCodeFromReasonCode>;\n message: string;\n reasonCode: ProviderReasonCode;\n details: Record<string, JsonValue>;\n} => ({\n code: providerErrorCodeFromReasonCode(reasonCode),\n message,\n reasonCode,\n details: {\n reasonCode\n }\n});\n","import { ProviderRuntimeError, isProviderRuntimeError, providerErrorCodeFromReasonCode } from \"../errors\";\nimport { classifyBlockerSignal } from \"../blocker\";\nimport {\n browserFallbackObservationAttributes,\n readFallbackString,\n resolveProviderBrowserFallback,\n toBrowserFallbackObservation,\n toCompletedFallbackOutputError,\n toProviderFallbackError\n} from \"../browser-fallback\";\nimport type { AntiBotPolicyConfig } from \"../shared/anti-bot-policy\";\nimport { providerRequestHeaders } from \"../shared/request-headers\";\nimport { createSocialPlatformProvider, type SocialProviderOptions } from \"./platform\";\nimport {\n normalizeYouTubeTranscriptMode,\n resolveYouTubeTranscript,\n resolveYouTubeTranscriptConfig,\n type YouTubeTranscriptLegalChecklist,\n type YouTubeTranscriptMode,\n type YouTubeTranscriptResolverConfig,\n type YouTubeTranscriptStrategy\n} from \"./youtube-resolver\";\nimport { extractStructuredContent, toSnippet } from \"../web/extract\";\nimport type {\n BrowserFallbackPort,\n BrowserFallbackResponse,\n BrowserFallbackObservation,\n JsonValue,\n ProviderContext,\n ProviderFetchInput,\n ProviderReasonCode,\n ProviderSearchInput\n} from \"../types\";\n\nconst YOUTUBE_HEADERS = {\n accept: \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n ...providerRequestHeaders\n} as const;\n\nexport interface YouTubeLegalReviewChecklist extends YouTubeTranscriptLegalChecklist {\n providerId: \"social/youtube\";\n termsReviewDate: string;\n allowedExtractionSurfaces: string[];\n prohibitedFlows: string[];\n reviewer: string;\n}\n\nexport type YouTubeLegalReviewReasonCode =\n | \"missing_terms_review_date\"\n | \"invalid_terms_review_date\"\n | \"missing_allowed_surfaces\"\n | \"missing_prohibited_flows\"\n | \"missing_reviewer\"\n | \"missing_approval_expiry\"\n | \"invalid_approval_expiry\"\n | \"approval_expired\"\n | \"not_signed_off\"\n | \"missing_approved_transcript_strategies\";\n\nexport interface YouTubeProviderOptions extends SocialProviderOptions {\n transcriptResolver?: Partial<YouTubeTranscriptResolverConfig>;\n browserFallbackPort?: BrowserFallbackPort;\n antiBotPolicy?: Partial<AntiBotPolicyConfig>;\n asrTranscribe?: (args: {\n watchUrl: string;\n context: ProviderContext;\n audioFilePath?: string;\n }) => Promise<{ text: string; language?: string } | null>;\n}\n\nexport const YOUTUBE_LEGAL_REVIEW_CHECKLIST: YouTubeLegalReviewChecklist = {\n providerId: \"social/youtube\",\n termsReviewDate: \"2026-02-16\",\n allowedExtractionSurfaces: [\n \"public search pages\",\n \"public watch pages\",\n \"public transcript/subtitle endpoints\"\n ],\n prohibitedFlows: [\n \"account pages\",\n \"authenticated user inbox/subscriptions APIs\",\n \"paid membership purchase flows\"\n ],\n reviewer: \"opendevbrowser-compliance\",\n approvalExpiryDate: \"2030-12-31T00:00:00.000Z\",\n signedOff: true,\n approvedTranscriptStrategies: [\n \"youtubei\",\n \"native_caption_parse\",\n \"ytdlp_audio_asr\",\n \"apify\",\n \"browser_assisted\"\n ]\n};\n\nconst hasValues = (values: string[]): boolean => values.some((value) => value.trim().length > 0);\n\nconst parseIsoDate = (value: string): number => {\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? NaN : parsed;\n};\n\nexport const validateYouTubeLegalReviewChecklist = (\n now: Date = new Date()\n): { valid: boolean; reasonCode?: YouTubeLegalReviewReasonCode } => {\n const checklist = YOUTUBE_LEGAL_REVIEW_CHECKLIST;\n if (!checklist.termsReviewDate.trim()) return { valid: false, reasonCode: \"missing_terms_review_date\" };\n if (Number.isNaN(parseIsoDate(checklist.termsReviewDate))) return { valid: false, reasonCode: \"invalid_terms_review_date\" };\n if (!hasValues(checklist.allowedExtractionSurfaces)) return { valid: false, reasonCode: \"missing_allowed_surfaces\" };\n if (!hasValues(checklist.prohibitedFlows)) return { valid: false, reasonCode: \"missing_prohibited_flows\" };\n if (!checklist.reviewer.trim()) return { valid: false, reasonCode: \"missing_reviewer\" };\n if (!checklist.approvalExpiryDate.trim()) return { valid: false, reasonCode: \"missing_approval_expiry\" };\n if (!hasValues(checklist.approvedTranscriptStrategies)) return { valid: false, reasonCode: \"missing_approved_transcript_strategies\" };\n\n const expiry = parseIsoDate(checklist.approvalExpiryDate);\n if (Number.isNaN(expiry)) return { valid: false, reasonCode: \"invalid_approval_expiry\" };\n if (expiry <= now.getTime()) return { valid: false, reasonCode: \"approval_expired\" };\n if (!checklist.signedOff) return { valid: false, reasonCode: \"not_signed_off\" };\n return { valid: true };\n};\n\nconst assertYouTubeLegalReviewChecklist = (): void => {\n const validation = validateYouTubeLegalReviewChecklist();\n if (validation.valid) return;\n\n throw new ProviderRuntimeError(\"policy_blocked\", \"social/youtube legal review checklist is invalid or expired\", {\n provider: \"social/youtube\",\n source: \"social\",\n retryable: false,\n reasonCode: \"policy_blocked\",\n details: {\n reasonCode: validation.reasonCode as YouTubeLegalReviewReasonCode,\n policyReasonCode: \"policy_blocked\",\n approvalExpiryDate: YOUTUBE_LEGAL_REVIEW_CHECKLIST.approvalExpiryDate\n }\n });\n};\n\nconst isHttpUrl = (value: string): boolean => {\n try {\n const protocol = new URL(value).protocol;\n return protocol === \"http:\" || protocol === \"https:\";\n } catch {\n return false;\n }\n};\n\nconst decodeHtml = (value: string): string => {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/'/g, \"'\")\n .replace(/"/g, '\"')\n .replace(/\\s+/g, \" \")\n .trim();\n};\n\nconst normalizeEscapedValue = (value: string): string => {\n return value\n .replace(/\\\\u0026/g, \"&\")\n .replace(/\\\\\\//g, \"/\")\n .replace(/\\\\u003d/g, \"=\")\n .replace(/\\\\u002F/g, \"/\");\n};\n\nconst decodeJsonText = (value: string): string => decodeHtml(normalizeEscapedValue(value));\n\nconst escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\nconst parseVideoId = (url: string): string | null => {\n try {\n const parsed = new URL(url);\n if (parsed.hostname === \"youtu.be\") {\n const id = parsed.pathname.replace(/^\\//, \"\").trim();\n return id || null;\n }\n const queryId = parsed.searchParams.get(\"v\");\n if (queryId) return queryId;\n const shortsMatch = parsed.pathname.match(/\\/shorts\\/([^/?#]+)/);\n return shortsMatch?.[1] ?? null;\n } catch {\n return null;\n }\n};\n\nconst normalizeYouTubeVideoLink = (url: string): string | null => {\n try {\n const parsed = new URL(url);\n const hostname = parsed.hostname.toLowerCase();\n if (\n hostname !== \"youtu.be\"\n && hostname !== \"youtube.com\"\n && hostname !== \"www.youtube.com\"\n && !hostname.endsWith(\".youtube.com\")\n ) {\n return null;\n }\n const videoId = parseVideoId(url);\n return videoId ? `https://www.youtube.com/watch?v=${videoId}` : null;\n } catch {\n return null;\n }\n};\n\nconst YOUTUBE_SEARCH_SHELL_RE = /\\b(?:about press copyright contact us creators advertise developers terms privacy policy|google for developers skip to main content youtube)\\b/i;\nconst YOUTUBE_FALLBACK_MIN_TEXT_CHARS = 40;\nconst YOUTUBE_CONTENT_MARKER_RE = /\"videoId\"\\s*:|\"captionTracks\"\\s*:|itemprop=\"author\"|itemprop=\"datePublished\"|\"viewCount\"\\s*:/i;\n\nconst hasYouTubeFallbackEvidence = (html: string, url: string): boolean => {\n if (YOUTUBE_CONTENT_MARKER_RE.test(html)) return true;\n return extractStructuredContent(html, url)\n .links\n .some((link) => normalizeYouTubeVideoLink(link) !== null);\n};\n\nconst reviewedFallback = (\n fallback: BrowserFallbackResponse,\n reasonCode: ProviderReasonCode | undefined\n): BrowserFallbackResponse => ({\n ...fallback,\n reasonCode: reasonCode ?? fallback.reasonCode\n});\n\nconst assertUsableYouTubeFallbackPage = (\n url: string,\n fallback: BrowserFallbackResponse,\n html: string\n): void => {\n const extracted = extractStructuredContent(html, url);\n const text = extracted.text.trim();\n const blocker = classifyBlockerSignal({\n source: \"runtime_fetch\",\n url,\n message: text,\n status: 200,\n providerErrorCode: \"unavailable\",\n retryable: true\n });\n if (blocker && blocker.type !== \"unknown\") {\n throw toCompletedFallbackOutputError({\n provider: \"social/youtube\",\n source: \"social\",\n url,\n fallback: reviewedFallback(fallback, blocker.reasonCode),\n outputReason: blocker.type\n });\n }\n if (hasYouTubeFallbackEvidence(html, url)) return;\n if (text.length < YOUTUBE_FALLBACK_MIN_TEXT_CHARS || YOUTUBE_SEARCH_SHELL_RE.test(text)) {\n throw toCompletedFallbackOutputError({\n provider: \"social/youtube\",\n source: \"social\",\n url,\n fallback,\n outputReason: \"youtube_shell_or_metadata\"\n });\n }\n};\n\nconst extractSearchResultSegment = (html: string, videoId: string): string | null => {\n const marker = new RegExp(`\"videoId\"\\\\s*:\\\\s*\"${escapeRegExp(videoId)}\"`);\n const match = marker.exec(html);\n if (!match || typeof match.index !== \"number\") return null;\n const start = match.index;\n if (start < 0) return null;\n\n const nextPattern = /\"videoRenderer\"\\s*:\\s*\\{\\s*\"videoId\"\\s*:\\s*\"/g;\n nextPattern.lastIndex = start + match[0].length;\n const nextMatch = nextPattern.exec(html);\n const nextStart = typeof nextMatch?.index === \"number\" ? nextMatch.index : -1;\n return html.slice(start, nextStart >= 0 ? nextStart : undefined);\n};\n\nconst extractTextRuns = (value: string): string[] => {\n return Array.from(value.matchAll(/\"text\":\"([^\"]+)\"/g))\n .map((match) => decodeJsonText(match[1] ?? \"\"))\n .filter((entry) => entry.length > 0);\n};\n\nconst extractPrimarySearchResult = (\n html: string,\n videoId: string\n): {\n title?: string;\n content?: string;\n channel?: string;\n} | null => {\n const segment = extractSearchResultSegment(html, videoId);\n if (!segment) return null;\n\n const title = firstNonEmptyMatch(segment, [\n /\"title\"\\s*:\\s*\\{\\s*\"runs\"\\s*:\\s*\\[\\s*\\{\\s*\"text\"\\s*:\\s*\"([^\"]+)\"/\n ]);\n const channel = firstNonEmptyMatch(segment, [\n /\"longBylineText\"\\s*:\\s*\\{\\s*\"runs\"\\s*:\\s*\\[\\s*\\{\\s*\"text\"\\s*:\\s*\"([^\"]+)\"/,\n /\"ownerText\"\\s*:\\s*\\{\\s*\"runs\"\\s*:\\s*\\[\\s*\\{\\s*\"text\"\\s*:\\s*\"([^\"]+)\"/,\n /\"shortBylineText\"\\s*:\\s*\\{\\s*\"runs\"\\s*:\\s*\\[\\s*\\{\\s*\"text\"\\s*:\\s*\"([^\"]+)\"/\n ]);\n const published = firstNonEmptyMatch(segment, [\n /\"publishedTimeText\"\\s*:\\s*\\{\\s*\"simpleText\"\\s*:\\s*\"([^\"]+)\"/\n ]);\n const views = firstNonEmptyMatch(segment, [\n /\"viewCountText\"\\s*:\\s*\\{\\s*\"simpleText\"\\s*:\\s*\"([^\"]+)\"/,\n /\"shortViewCountText\"\\s*:\\s*\\{\\s*\"simpleText\"\\s*:\\s*\"([^\"]+)\"/\n ]);\n const snippetBlock = segment.match(/\"detailedMetadataSnippets\"\\s*:\\s*\\[\\s*\\{\\s*\"snippetText\"\\s*:\\s*\\{\\s*\"runs\"\\s*:\\s*\\[(.*?)\\]\\}/s)?.[1] ?? null;\n const snippet = snippetBlock ? extractTextRuns(snippetBlock).join(\" \").trim() : \"\";\n\n const contentParts = [\n snippet,\n channel ? `Channel: ${channel}.` : \"\",\n published ? `Published: ${published}.` : \"\",\n views ? `Views: ${views}.` : \"\"\n ].filter((part) => part.length > 0);\n\n const content = contentParts.join(\" \").trim();\n if (!title && !content) return null;\n\n return {\n ...(title ? { title } : {}),\n ...(content ? { content } : {}),\n ...(channel ? { channel } : {})\n };\n};\n\nconst firstNonEmptyMatch = (html: string, patterns: RegExp[]): string | null => {\n for (const pattern of patterns) {\n const match = html.match(pattern)?.[1];\n if (match && match.trim()) {\n return decodeHtml(normalizeEscapedValue(match));\n }\n }\n return null;\n};\n\nconst toIsoIfValid = (value: string | null): string | null => {\n if (!value) return null;\n const timestamp = Date.parse(value);\n if (Number.isNaN(timestamp)) return null;\n return new Date(timestamp).toISOString();\n};\n\nconst parseInteger = (value: string | null): number | null => {\n if (!value) return null;\n const normalized = value.replace(/[^\\d]/g, \"\");\n if (!normalized) return null;\n const parsed = Number(normalized);\n return Number.isFinite(parsed) ? parsed : null;\n};\n\nconst findChannel = (html: string): string | null => {\n return firstNonEmptyMatch(html, [\n /\"ownerChannelName\":\"([^\"]+)\"/,\n /\"channelName\":\"([^\"]+)\"/,\n /\"shortBylineText\":\\{\"runs\":\\[\\{\"text\":\"([^\"]+)\"/,\n /itemprop=\"author\"\\s+content=\"([^\"]+)\"/\n ]);\n};\n\nconst findPublishedAt = (html: string): string | null => {\n const rawDate = firstNonEmptyMatch(html, [\n /\"publishDate\":\"([^\"]+)\"/,\n /\"uploadDate\":\"([^\"]+)\"/,\n /itemprop=\"datePublished\"\\s+content=\"([^\"]+)\"/\n ]);\n return toIsoIfValid(rawDate);\n};\n\nconst findViews = (html: string, extractedText: string): number | null => {\n const viewCount = firstNonEmptyMatch(html, [\n /\"viewCount\":\"([^\"]+)\"/,\n /\"viewCountText\":\\{\"simpleText\":\"([^\"]+)\"/\n ]);\n const parsedFromHtml = parseInteger(viewCount);\n if (parsedFromHtml !== null) return parsedFromHtml;\n\n const parsedFromText = parseInteger(extractedText.match(/([0-9][0-9,]*)\\s+views/i)?.[1] ?? null);\n return parsedFromText;\n};\n\nconst summarizeTranscript = (transcript: string): string => {\n if (!transcript) return \"\";\n const lines = transcript\n .split(/\\n+/)\n .map((line) => line.trim())\n .filter(Boolean);\n return lines.slice(0, 8).join(\" \").slice(0, 800);\n};\n\ntype YouTubeFetchedPage = {\n status: number;\n url: string;\n html: string;\n browserFallback?: BrowserFallbackObservation;\n};\n\nconst fetchPageDirect = async (url: string, context: ProviderContext): Promise<YouTubeFetchedPage> => {\n let response: Response;\n try {\n response = await fetch(url, {\n headers: YOUTUBE_HEADERS,\n signal: context.signal,\n redirect: \"follow\"\n });\n } catch (error) {\n throw new ProviderRuntimeError(\"network\", `Failed to retrieve ${url}`, {\n provider: \"social/youtube\",\n source: \"social\",\n retryable: true,\n cause: error\n });\n }\n\n if (response.status === 401 || response.status === 403) {\n throw new ProviderRuntimeError(\"auth\", `Authentication required for ${url}`, {\n provider: \"social/youtube\",\n source: \"social\",\n retryable: false,\n reasonCode: \"token_required\",\n details: { status: response.status, url, reasonCode: \"token_required\" }\n });\n }\n if (response.status === 429) {\n throw new ProviderRuntimeError(\"rate_limited\", `Rate limited while retrieving ${url}`, {\n provider: \"social/youtube\",\n source: \"social\",\n retryable: true,\n reasonCode: \"rate_limited\",\n details: { status: response.status, url, reasonCode: \"rate_limited\" }\n });\n }\n if (response.status >= 400) {\n throw new ProviderRuntimeError(\"unavailable\", `Retrieval failed for ${url}`, {\n provider: \"social/youtube\",\n source: \"social\",\n retryable: response.status >= 500,\n reasonCode: response.status >= 500 ? \"ip_blocked\" : \"transcript_unavailable\",\n details: {\n status: response.status,\n url,\n reasonCode: response.status >= 500 ? \"ip_blocked\" : \"transcript_unavailable\"\n }\n });\n }\n\n return {\n status: response.status,\n url: response.url || url,\n html: await response.text()\n };\n};\n\nconst forcedFallbackReasonCode = (context: ProviderContext): ProviderReasonCode => {\n const policy = context.runtimePolicy;\n if (policy?.cookies.policy === \"required\") return \"auth_required\";\n return \"env_limited\";\n};\n\nconst fallbackReasonCodeForPageError = (\n error: unknown,\n context: ProviderContext\n): ProviderReasonCode | null => {\n if (!isProviderRuntimeError(error)) return \"env_limited\";\n if (error.code === \"auth\") {\n return context.runtimePolicy?.cookies.policy === \"required\" ? \"auth_required\" : \"token_required\";\n }\n if (error.code === \"rate_limited\") return \"rate_limited\";\n if (error.code === \"network\" || error.code === \"timeout\") return \"env_limited\";\n if (error.code === \"upstream\") return \"ip_blocked\";\n if (error.reasonCode === \"ip_blocked\" || error.reasonCode === \"challenge_detected\") return error.reasonCode;\n return null;\n};\n\nconst fallbackDetailsForError = (error: unknown): Record<string, JsonValue> => {\n if (!isProviderRuntimeError(error)) return {};\n return {\n errorCode: error.code,\n message: error.message,\n ...(error.details ?? {})\n };\n};\n\nconst pageFromFallback = (\n url: string,\n fallback: BrowserFallbackResponse\n): YouTubeFetchedPage => {\n const html = readFallbackString(fallback.output, \"html\");\n if (!html) {\n throw toCompletedFallbackOutputError({\n provider: \"social/youtube\",\n source: \"social\",\n url,\n fallback,\n outputReason: \"missing_or_empty_html\"\n });\n }\n assertUsableYouTubeFallbackPage(url, fallback, html);\n return {\n status: 200,\n url: readFallbackString(fallback.output, \"url\") ?? url,\n html,\n browserFallback: toBrowserFallbackObservation(fallback)\n };\n};\n\nconst resolveFallbackPage = async (args: {\n url: string;\n context: ProviderContext;\n options: YouTubeProviderOptions;\n operation: \"search\" | \"fetch\";\n reasonCode: ProviderReasonCode;\n details?: Record<string, JsonValue>;\n}): Promise<YouTubeFetchedPage | null> => {\n const fallback = await resolveProviderBrowserFallback({\n browserFallbackPort: args.context.browserFallbackPort ?? args.options.browserFallbackPort,\n provider: \"social/youtube\",\n source: \"social\",\n operation: args.operation,\n reasonCode: args.reasonCode,\n url: args.url,\n context: args.context,\n details: args.details,\n recoveryHints: args.options.recoveryHints?.()\n });\n if (!fallback) return null;\n if (fallback.disposition !== \"completed\") {\n throw toProviderFallbackError({\n provider: \"social/youtube\",\n source: \"social\",\n url: args.url,\n fallback\n });\n }\n return pageFromFallback(args.url, fallback);\n};\n\nconst fetchPage = async (\n url: string,\n context: ProviderContext,\n options: YouTubeProviderOptions,\n operation: \"search\" | \"fetch\"\n): Promise<YouTubeFetchedPage> => {\n if (context.runtimePolicy?.browser.forceTransport) {\n const page = await resolveFallbackPage({\n url,\n context,\n options,\n operation,\n reasonCode: forcedFallbackReasonCode(context),\n details: { message: \"Direct browser transport was selected for this YouTube provider run.\" }\n });\n if (page) return page;\n throw new ProviderRuntimeError(providerErrorCodeFromReasonCode(forcedFallbackReasonCode(context)), \"Direct browser transport is required for this YouTube provider run, but no browser transport is available.\", {\n provider: \"social/youtube\",\n source: \"social\",\n retryable: false,\n reasonCode: forcedFallbackReasonCode(context),\n details: { browserTransportRequired: true }\n });\n }\n\n try {\n return await fetchPageDirect(url, context);\n } catch (error) {\n const reasonCode = fallbackReasonCodeForPageError(error, context);\n if (!reasonCode) throw error;\n const page = await resolveFallbackPage({\n url,\n context,\n options,\n operation,\n reasonCode,\n details: fallbackDetailsForError(error)\n });\n if (page) return page;\n throw error;\n }\n};\n\nconst parseBooleanFilter = (value: unknown, fallback = false): boolean => {\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"string\") {\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n }\n return fallback;\n};\n\nconst parseYouTubeModeFilter = (value: unknown): YouTubeTranscriptMode | null => {\n return normalizeYouTubeTranscriptMode(value);\n};\n\nconst toJsonRecord = (value: Record<string, unknown>): Record<string, JsonValue> => {\n return JSON.parse(JSON.stringify(value)) as Record<string, JsonValue>;\n};\n\nconst toAttemptChainJson = (attempts: Array<{\n strategy: string;\n ok: boolean;\n reasonCode?: string;\n message?: string;\n details?: Record<string, unknown>;\n}>): Array<Record<string, JsonValue>> => {\n return attempts.map((attempt) => ({\n strategy: attempt.strategy,\n ok: attempt.ok,\n ...(attempt.reasonCode ? { reasonCode: attempt.reasonCode } : {}),\n ...(attempt.message ? { message: attempt.message } : {}),\n ...(attempt.details ? toJsonRecord(attempt.details) : {})\n }));\n};\n\nconst resolveTranscriptStrategyDetail = (\n transcript: Awaited<ReturnType<typeof resolveYouTubeTranscript>>\n): string | undefined => {\n if (transcript.ok) {\n return transcript.transcriptStrategyDetail;\n }\n for (let index = transcript.attemptChain.length - 1; index >= 0; index -= 1) {\n const attempt = transcript.attemptChain[index];\n if (!attempt?.reasonCode) continue;\n if (attempt.reasonCode !== \"env_limited\" && attempt.reasonCode !== \"token_required\") {\n return attempt.strategy;\n }\n }\n for (let index = transcript.attemptChain.length - 1; index >= 0; index -= 1) {\n const attempt = transcript.attemptChain[index];\n if (!attempt?.reasonCode || attempt.reasonCode === \"env_limited\") continue;\n return attempt.strategy;\n }\n return transcript.attemptChain.at(-1)?.strategy;\n};\n\nconst buildSearch = (options: YouTubeProviderOptions) => {\n if (options.search) return options.search;\n return async (input: ProviderSearchInput, context: ProviderContext) => {\n assertYouTubeLegalReviewChecklist();\n const query = input.query.trim();\n if (!query) {\n throw new ProviderRuntimeError(\"invalid_input\", \"YouTube search query is required\", {\n provider: \"social/youtube\",\n source: \"social\",\n retryable: false\n });\n }\n\n const lookupUrl = isHttpUrl(query)\n ? query\n : `https://www.youtube.com/results?search_query=${encodeURIComponent(query)}`;\n const directUrlQuery = isHttpUrl(query);\n const page = await fetchPage(lookupUrl, context, options, \"search\");\n const extracted = extractStructuredContent(page.html, page.url);\n const extractedVideoLinks = [...new Set(\n extracted.links\n .map((link) => normalizeYouTubeVideoLink(link))\n .filter((link): link is string => typeof link === \"string\" && link.length > 0)\n )];\n const firstVideoId = page.html.match(/\"videoId\"\\s*:\\s*\"([a-zA-Z0-9_-]{11})\"/)?.[1] ?? null;\n const extractedVideoId = extractedVideoLinks[0] ? parseVideoId(extractedVideoLinks[0]) : null;\n const resolvedVideoId = firstVideoId ?? (!directUrlQuery ? extractedVideoId : null) ?? parseVideoId(page.url);\n const watchUrl = !directUrlQuery && resolvedVideoId ? `https://www.youtube.com/watch?v=${resolvedVideoId}` : page.url;\n const primaryResult = resolvedVideoId ? extractPrimarySearchResult(page.html, resolvedVideoId) : null;\n const genericSearchShell = YOUTUBE_SEARCH_SHELL_RE.test(extracted.text);\n const fallbackTitle = toSnippet(extracted.text, 120);\n const fallbackContent = toSnippet(extracted.text, 1800);\n if (genericSearchShell && !resolvedVideoId) {\n throw new ProviderRuntimeError(\n \"unavailable\",\n `YouTube search returned generic site chrome for ${lookupUrl}`,\n {\n provider: \"social/youtube\",\n source: \"social\",\n retryable: true,\n reasonCode: \"env_limited\",\n details: {\n url: page.url,\n status: page.status,\n browserRequired: true,\n providerShell: \"youtube_search_shell\",\n message: toSnippet(extracted.text, 400)\n }\n }\n );\n }\n const safeFallbackTitle = genericSearchShell ? \"\" : fallbackTitle;\n const safeFallbackContent = genericSearchShell ? \"\" : fallbackContent;\n\n return [{\n url: watchUrl,\n title: (primaryResult?.title ?? safeFallbackTitle) || `YouTube search: ${query}`,\n content: primaryResult?.content ?? safeFallbackContent,\n confidence: 0.62,\n attributes: {\n platform: \"youtube\",\n query,\n status: page.status,\n retrievalPath: isHttpUrl(query) ? \"social:youtube:search:url\" : \"social:youtube:search:index\",\n video_id: resolvedVideoId,\n ...(primaryResult?.channel ? { channel: primaryResult.channel } : {}),\n links: extractedVideoLinks.slice(0, 20),\n ...browserFallbackObservationAttributes(page.browserFallback)\n }\n }];\n };\n};\n\nconst buildFetch = (options: YouTubeProviderOptions) => {\n if (options.fetch) return options.fetch;\n return async (input: ProviderFetchInput, context: ProviderContext) => {\n assertYouTubeLegalReviewChecklist();\n const page = await fetchPage(input.url, context, options, \"fetch\");\n const extracted = extractStructuredContent(page.html, page.url);\n\n const includeFullTranscript = parseBooleanFilter(input.filters?.include_full_transcript, false);\n const requireTranscript = parseBooleanFilter(input.filters?.requireTranscript, false);\n const translateToEnglish = parseBooleanFilter(input.filters?.translateToEnglish, true);\n const requestedMode = parseYouTubeModeFilter(input.filters?.youtube_mode);\n\n const transcriptConfig = resolveYouTubeTranscriptConfig(options.transcriptResolver);\n const recoveryHints = options.recoveryHints?.();\n const transcript = await resolveYouTubeTranscript({\n context,\n watchUrl: page.url,\n pageHtml: page.html,\n legalChecklist: YOUTUBE_LEGAL_REVIEW_CHECKLIST,\n config: transcriptConfig,\n mode: requestedMode,\n browserFallbackPort: context.browserFallbackPort ?? options.browserFallbackPort,\n recoveryHints,\n allowBrowserFallbackEscalation: options.antiBotPolicy?.allowBrowserEscalation ?? true,\n asrTranscribe: options.asrTranscribe\n });\n\n if (!transcript.ok && requireTranscript) {\n const requiredReasonCode = transcript.reasonCode === \"caption_missing\"\n ? \"transcript_unavailable\"\n : transcript.reasonCode;\n throw new ProviderRuntimeError(\n providerErrorCodeFromReasonCode(requiredReasonCode),\n `YouTube transcript unavailable (${requiredReasonCode})`,\n {\n provider: \"social/youtube\",\n source: \"social\",\n retryable: requiredReasonCode === \"rate_limited\",\n reasonCode: requiredReasonCode,\n details: {\n reasonCode: requiredReasonCode,\n transcriptReasonCode: transcript.reasonCode,\n url: page.url,\n attemptChain: toAttemptChainJson(transcript.attemptChain)\n }\n }\n );\n }\n\n const transcriptRaw = transcript.ok ? transcript.text : \"\";\n const transcriptLanguage = transcript.ok ? transcript.language : \"unknown\";\n const translationApplied = Boolean(transcriptRaw && translateToEnglish && !transcriptLanguage.startsWith(\"en\"));\n const transcriptContent = translationApplied\n ? `[translated:${transcriptLanguage}] ${transcriptRaw}`\n : transcriptRaw;\n const transcriptSummary = summarizeTranscript(transcriptContent || extracted.text);\n const transcriptOutput = includeFullTranscript || transcriptContent.length < 1200\n ? transcriptContent\n : transcriptSummary;\n const transcriptStrategyDetail = resolveTranscriptStrategyDetail(transcript);\n\n const videoId = parseVideoId(page.url);\n const channel = findChannel(page.html);\n const publishedAt = findPublishedAt(page.html);\n const views = findViews(page.html, extracted.text);\n const dateConfidence = publishedAt\n ? { score: 1, source: \"explicit\" as const }\n : { score: 0.8, source: \"inferred\" as const };\n\n return {\n url: page.url,\n title: toSnippet(extracted.text, 120) || page.url,\n content: transcriptOutput || toSnippet(extracted.text, 1800),\n attributes: {\n platform: \"youtube\",\n status: page.status,\n links: extracted.links.slice(0, 30),\n retrievalPath: \"social:youtube:fetch:url\",\n video_id: videoId,\n ...(channel ? { channel } : {}),\n ...(publishedAt ? { published_at: publishedAt } : {}),\n ...(typeof views === \"number\" ? { views } : {}),\n transcript_language: transcriptLanguage,\n transcript_retrieved_at: new Date().toISOString(),\n transcript_available: transcript.ok,\n transcript_mode: transcript.mode,\n translation_applied: translationApplied,\n transcript_summary: transcriptSummary,\n ...browserFallbackObservationAttributes(page.browserFallback),\n ...(includeFullTranscript ? { transcript_full: transcriptContent } : {}),\n ...(transcriptStrategyDetail ? { transcript_strategy_detail: transcriptStrategyDetail } : {}),\n ...(transcript.ok\n ? {\n transcript_strategy: transcript.transcriptStrategy,\n attempt_chain: toAttemptChainJson(transcript.attemptChain)\n }\n : {\n reasonCode: transcript.reasonCode,\n attempt_chain: toAttemptChainJson(transcript.attemptChain)\n }),\n date_confidence: dateConfidence\n }\n };\n };\n};\n\nexport const createYouTubeProvider = (options: YouTubeProviderOptions = {}) => {\n return createSocialPlatformProvider({\n platform: \"youtube\",\n displayName: \"YouTube\",\n baseUrl: \"https://www.youtube.com\",\n maxPostLength: 10000,\n supportsMedia: true,\n supportsThreads: false\n }, options);\n};\n\nexport const withDefaultYouTubeOptions = (options: YouTubeProviderOptions = {}): YouTubeProviderOptions => {\n const resolvedOptions: YouTubeProviderOptions = {\n ...options,\n recoveryHints: options.recoveryHints ?? (() => ({\n preferredFallbackModes: [\"extension\", \"managed_headed\"],\n challengeProne: true,\n settleTimeoutMs: 5000,\n captureDelayMs: 500\n })),\n defaultTraversal: {\n pageLimit: options.defaultTraversal?.pageLimit ?? 1,\n hopLimit: options.defaultTraversal?.hopLimit ?? 0,\n expansionPerRecord: options.defaultTraversal?.expansionPerRecord ?? 1,\n maxRecords: options.defaultTraversal?.maxRecords ?? 8\n }\n };\n\n return {\n ...resolvedOptions,\n search: buildSearch(resolvedOptions),\n fetch: buildFetch(resolvedOptions)\n };\n};\n\nexport type { YouTubeTranscriptStrategy };\n","import { createBlueskyProvider } from \"./bluesky\";\nimport { createFacebookProvider } from \"./facebook\";\nimport { createInstagramProvider } from \"./instagram\";\nimport { createLinkedInProvider } from \"./linkedin\";\nimport { createRedditProvider } from \"./reddit\";\nimport { createThreadsProvider } from \"./threads\";\nimport { createTikTokProvider } from \"./tiktok\";\nimport { createXProvider } from \"./x\";\nimport { createYouTubeProvider, type YouTubeProviderOptions } from \"./youtube\";\nimport type { ProviderAdapter } from \"../types\";\nimport type { SocialProviderOptions } from \"./platform\";\n\nexport { createXProvider } from \"./x\";\nexport { createRedditProvider } from \"./reddit\";\nexport { createBlueskyProvider } from \"./bluesky\";\nexport { createFacebookProvider } from \"./facebook\";\nexport { createLinkedInProvider } from \"./linkedin\";\nexport { createInstagramProvider } from \"./instagram\";\nexport { createTikTokProvider } from \"./tiktok\";\nexport { createThreadsProvider } from \"./threads\";\nexport { createYouTubeProvider } from \"./youtube\";\nexport { withDefaultYouTubeOptions } from \"./youtube\";\nexport { validateYouTubeLegalReviewChecklist, YOUTUBE_LEGAL_REVIEW_CHECKLIST } from \"./youtube\";\nexport type { YouTubeProviderOptions } from \"./youtube\";\nexport type { SocialProviderOptions, SocialPlatformProfile } from \"./platform\";\n\nexport type SocialPlatform =\n | \"x\"\n | \"reddit\"\n | \"bluesky\"\n | \"facebook\"\n | \"linkedin\"\n | \"instagram\"\n | \"tiktok\"\n | \"threads\"\n | \"youtube\";\n\nexport interface SocialProvidersOptions {\n x?: SocialProviderOptions;\n reddit?: SocialProviderOptions;\n bluesky?: SocialProviderOptions;\n facebook?: SocialProviderOptions;\n linkedin?: SocialProviderOptions;\n instagram?: SocialProviderOptions;\n tiktok?: SocialProviderOptions;\n threads?: SocialProviderOptions;\n youtube?: YouTubeProviderOptions;\n}\n\nexport const createSocialProviders = (options: SocialProvidersOptions = {}): ProviderAdapter[] => {\n return [\n createXProvider(options.x),\n createRedditProvider(options.reddit),\n createBlueskyProvider(options.bluesky),\n createFacebookProvider(options.facebook),\n createLinkedInProvider(options.linkedin),\n createInstagramProvider(options.instagram),\n createTikTokProvider(options.tiktok),\n createThreadsProvider(options.threads),\n createYouTubeProvider(options.youtube)\n ];\n};\n\nexport const createSocialProvider = (\n platform: SocialPlatform,\n options: SocialProviderOptions = {}\n): ProviderAdapter => {\n switch (platform) {\n case \"x\":\n return createXProvider(options);\n case \"reddit\":\n return createRedditProvider(options);\n case \"bluesky\":\n return createBlueskyProvider(options);\n case \"facebook\":\n return createFacebookProvider(options);\n case \"linkedin\":\n return createLinkedInProvider(options);\n case \"instagram\":\n return createInstagramProvider(options);\n case \"tiktok\":\n return createTikTokProvider(options);\n case \"threads\":\n return createThreadsProvider(options);\n case \"youtube\":\n return createYouTubeProvider(options);\n }\n};\n","import { classifyBlockerSignal } from \"../blocker\";\nimport {\n browserFallbackObservationDetails,\n browserFallbackObservationAttributes,\n readFallbackString,\n resolveProviderBrowserFallback,\n toBrowserFallbackObservation,\n toCompletedFallbackOutputError,\n toProviderFallbackError\n} from \"../browser-fallback\";\nimport { applyProviderIssueHint, classifyProviderIssue, readProviderIssueHint } from \"../constraint\";\nimport { providerErrorCodeFromReasonCode, ProviderRuntimeError, toProviderError } from \"../errors\";\nimport { normalizeRecord, normalizeRecords } from \"../normalize\";\nimport { providerRequestHeaders } from \"../shared/request-headers\";\nimport { canonicalizeUrl } from \"../web/crawler\";\nimport { extractStructuredContent, extractText, toSnippet } from \"../web/extract\";\nimport type { ProviderIssueHint } from \"../constraint\";\nimport type { ExtractedContent } from \"../web/extract\";\nimport type {\n BrowserFallbackMode,\n BrowserFallbackObservation,\n BrowserFallbackResponse,\n JsonValue,\n NormalizedRecord,\n ProviderAdapter,\n ProviderCapabilities,\n ProviderContext,\n ProviderErrorCode,\n ProviderFetchInput,\n ProviderHealth,\n ProviderRecoveryHints,\n ProviderReasonCode,\n ProviderSearchInput\n} from \"../types\";\n\nconst SHOPPING_SOURCE = \"shopping\" as const;\nconst DEFAULT_CURRENCY = \"USD\";\nconst DEFAULT_RECOVERABLE_SHOPPING_FETCH_TIMEOUT_MS = 15_000;\nconst DEFAULT_SHOPPING_FALLBACK_MODES: BrowserFallbackMode[] = [\"extension\", \"managed_headed\"];\n\nexport type ShoppingProviderName =\n | \"amazon\"\n | \"walmart\"\n | \"bestbuy\"\n | \"ebay\"\n | \"target\"\n | \"costco\"\n | \"macys\"\n | \"aliexpress\"\n | \"temu\"\n | \"newegg\"\n | \"others\";\n\nexport type ShoppingProviderId = `shopping/${ShoppingProviderName}`;\n\nexport interface ShoppingProviderProfile {\n name: ShoppingProviderName;\n id: ShoppingProviderId;\n displayName: string;\n domains: string[];\n tier: \"tier1\" | \"tier2\";\n extractionFocus: string;\n legalReview: ProviderLegalReviewChecklist;\n searchPath: (query: string) => string;\n}\n\nexport interface ShoppingRegionSupportDiagnostic {\n provider: string;\n requestedRegion: string;\n enforced: boolean;\n strategy: \"default_storefront\";\n storefrontDomain: string | null;\n reason: \"provider_search_path_ignores_region\";\n}\n\nexport interface ProviderLegalReviewChecklist {\n providerId: string;\n termsReviewDate: string;\n allowedExtractionSurfaces: string[];\n prohibitedFlows: string[];\n reviewer: string;\n approvalExpiryDate: string;\n signedOff: boolean;\n}\n\nexport type LegalReviewReasonCode =\n | \"missing_checklist\"\n | \"provider_mismatch\"\n | \"missing_terms_review_date\"\n | \"invalid_terms_review_date\"\n | \"missing_allowed_surfaces\"\n | \"missing_prohibited_flows\"\n | \"missing_reviewer\"\n | \"missing_approval_expiry\"\n | \"invalid_approval_expiry\"\n | \"approval_expired\"\n | \"not_signed_off\";\n\nexport interface LegalReviewValidationResult {\n valid: boolean;\n reasonCode?: LegalReviewReasonCode;\n}\n\nexport interface ShoppingSearchRecord {\n url: string;\n title?: string;\n content?: string;\n confidence?: number;\n attributes?: Record<string, JsonValue>;\n}\n\ninterface ShoppingFetchRecord {\n status: number;\n url: string;\n html: string;\n browserFallback?: BrowserFallbackObservation;\n}\n\ninterface ShoppingSearchCandidate {\n url: string;\n title: string;\n text: string;\n brand?: string;\n imageUrl?: string;\n price?: ResolvedShoppingPrice;\n rating?: number;\n reviews?: number;\n availability?: \"in_stock\" | \"limited\" | \"out_of_stock\" | \"unknown\";\n}\n\ntype ShoppingPriceSource =\n | \"structured_metadata\"\n | \"search_card_context\"\n | \"search_title_inline\"\n | \"unresolved\";\n\ninterface ResolvedShoppingPrice {\n amount: number;\n currency: string;\n source: ShoppingPriceSource;\n trustworthy: boolean;\n}\n\nexport type ShoppingFetcher = (args: {\n url: string;\n signal?: AbortSignal;\n provider: string;\n operation: \"search\" | \"fetch\";\n context?: ProviderContext;\n}) => Promise<ShoppingFetchRecord>;\n\nexport interface ShoppingProviderOptions {\n id?: string;\n search?: (input: ProviderSearchInput, context: ProviderContext) => Promise<ShoppingSearchRecord[]>;\n fetch?: (input: ProviderFetchInput, context: ProviderContext) => Promise<ShoppingSearchRecord>;\n fetcher?: ShoppingFetcher;\n}\n\nexport type ShoppingProvidersOptions = Partial<Record<ShoppingProviderName, ShoppingProviderOptions>>;\n\nconst DEFAULT_ALLOWED_SURFACES = [\n \"public search result pages\",\n \"public product detail pages\",\n \"public metadata tags\"\n];\n\nconst DEFAULT_PROHIBITED_FLOWS = [\n \"checkout workflows\",\n \"account/profile pages\",\n \"authenticated purchase APIs\"\n];\n\nconst DEFAULT_REVIEWER = \"opendevbrowser-compliance\";\nconst DEFAULT_TERMS_REVIEW_DATE = \"2026-02-16\";\nconst DEFAULT_APPROVAL_EXPIRY = \"2030-12-31T00:00:00.000Z\";\n\nconst createLegalReviewChecklist = (\n providerId: ShoppingProviderId,\n termsReviewDate = DEFAULT_TERMS_REVIEW_DATE,\n approvalExpiryDate = DEFAULT_APPROVAL_EXPIRY\n): ProviderLegalReviewChecklist => ({\n providerId,\n termsReviewDate,\n allowedExtractionSurfaces: [...DEFAULT_ALLOWED_SURFACES],\n prohibitedFlows: [...DEFAULT_PROHIBITED_FLOWS],\n reviewer: DEFAULT_REVIEWER,\n approvalExpiryDate,\n signedOff: true\n});\n\nexport const SHOPPING_PROVIDER_PROFILES: ShoppingProviderProfile[] = [\n {\n name: \"amazon\",\n id: \"shopping/amazon\",\n displayName: \"Amazon\",\n domains: [\"amazon.com\"],\n tier: \"tier1\",\n extractionFocus: \"PDP title/price/availability, offer blocks, image gallery\",\n legalReview: createLegalReviewChecklist(\"shopping/amazon\"),\n searchPath: (query) => `https://www.amazon.com/s?k=${encodeURIComponent(query)}`\n },\n {\n name: \"walmart\",\n id: \"shopping/walmart\",\n displayName: \"Walmart\",\n domains: [\"walmart.com\"],\n tier: \"tier1\",\n extractionFocus: \"Search cards, PDP price modules, delivery/pickup availability\",\n legalReview: createLegalReviewChecklist(\"shopping/walmart\"),\n searchPath: (query) => `https://www.walmart.com/search?q=${encodeURIComponent(query)}`\n },\n {\n name: \"bestbuy\",\n id: \"shopping/bestbuy\",\n displayName: \"Best Buy\",\n domains: [\"bestbuy.com\"],\n tier: \"tier1\",\n extractionFocus: \"Search results, PDP pricing/condition, fulfillment options\",\n legalReview: createLegalReviewChecklist(\"shopping/bestbuy\"),\n searchPath: (query) => `https://www.bestbuy.com/site/searchpage.jsp?st=${encodeURIComponent(query)}&intl=nosplash`\n },\n {\n name: \"ebay\",\n id: \"shopping/ebay\",\n displayName: \"eBay\",\n domains: [\"ebay.com\"],\n tier: \"tier1\",\n extractionFocus: \"Listing cards, seller/condition, buy-it-now vs auction fields\",\n legalReview: createLegalReviewChecklist(\"shopping/ebay\"),\n searchPath: (query) => `https://www.ebay.com/sch/i.html?_nkw=${encodeURIComponent(query)}`\n },\n {\n name: \"target\",\n id: \"shopping/target\",\n displayName: \"Target\",\n domains: [\"target.com\"],\n tier: \"tier2\",\n extractionFocus: \"PDP variants, store/ship availability, promotion blocks\",\n legalReview: createLegalReviewChecklist(\"shopping/target\"),\n searchPath: (query) => `https://www.target.com/s?searchTerm=${encodeURIComponent(query)}`\n },\n {\n name: \"costco\",\n id: \"shopping/costco\",\n displayName: \"Costco\",\n domains: [\"costco.com\"],\n tier: \"tier2\",\n extractionFocus: \"Membership-aware price blocks, stock notes, package quantity\",\n legalReview: createLegalReviewChecklist(\"shopping/costco\"),\n searchPath: (query) => `https://www.costco.com/CatalogSearch?dept=All&keyword=${encodeURIComponent(query)}`\n },\n {\n name: \"macys\",\n id: \"shopping/macys\",\n displayName: \"Macy's\",\n domains: [\"macys.com\"],\n tier: \"tier2\",\n extractionFocus: \"Category cards, PDP discounts, variant pricing\",\n legalReview: createLegalReviewChecklist(\"shopping/macys\"),\n searchPath: (query) => `https://www.macys.com/shop/featured/${encodeURIComponent(query)}`\n },\n {\n name: \"aliexpress\",\n id: \"shopping/aliexpress\",\n displayName: \"AliExpress\",\n domains: [\"aliexpress.com\"],\n tier: \"tier2\",\n extractionFocus: \"Listing pricing ranges, shipping estimates, seller signals\",\n legalReview: createLegalReviewChecklist(\"shopping/aliexpress\"),\n searchPath: (query) => `https://www.aliexpress.com/wholesale?SearchText=${encodeURIComponent(query)}`\n },\n {\n name: \"temu\",\n id: \"shopping/temu\",\n displayName: \"Temu\",\n domains: [\"temu.com\"],\n tier: \"tier2\",\n extractionFocus: \"Offer cards, coupon/discount overlays, shipping badges\",\n legalReview: createLegalReviewChecklist(\"shopping/temu\"),\n searchPath: (query) => `https://www.temu.com/search_result.html?search_key=${encodeURIComponent(query)}`\n },\n {\n name: \"newegg\",\n id: \"shopping/newegg\",\n displayName: \"Newegg\",\n domains: [\"newegg.com\"],\n tier: \"tier2\",\n extractionFocus: \"Tech catalog cards, seller conditions, shipping price/time\",\n legalReview: createLegalReviewChecklist(\"shopping/newegg\"),\n searchPath: (query) => `https://www.newegg.com/p/pl?d=${encodeURIComponent(query)}`\n },\n {\n name: \"others\",\n id: \"shopping/others\",\n displayName: \"Others\",\n domains: [],\n tier: \"tier2\",\n extractionFocus: \"JSON-LD Product/Offer, OpenGraph, common PDP selectors\",\n legalReview: createLegalReviewChecklist(\"shopping/others\"),\n searchPath: (query) => `https://html.duckduckgo.com/html/?q=${encodeURIComponent(`${query} buy`)}`\n }\n];\n\nexport const SHOPPING_PROVIDER_IDS = SHOPPING_PROVIDER_PROFILES.map((profile) => profile.id);\n\nexport const getShoppingRegionSupportDiagnostics = (\n providerIds: string[],\n region: string\n): ShoppingRegionSupportDiagnostic[] => {\n const requestedRegion = region.trim().toLowerCase();\n if (!requestedRegion) {\n return [];\n }\n return providerIds.map((providerId) => {\n const profile = SHOPPING_PROVIDER_PROFILES.find((entry) => entry.id === providerId);\n return {\n provider: providerId,\n requestedRegion,\n enforced: false,\n strategy: \"default_storefront\",\n storefrontDomain: profile?.domains[0] ?? null,\n reason: \"provider_search_path_ignores_region\"\n };\n });\n};\n\nconst hasValues = (values: string[]): boolean => values.some((value) => value.trim().length > 0);\nconst FALLBACK_HEAD_RE = /<head\\b[^>]*>[\\s\\S]*?<\\/head>/i;\nconst FALLBACK_BODY_RE = /<body\\b[^>]*>([\\s\\S]*?)<\\/body>/i;\nconst SHOPPING_FALLBACK_EVIDENCE_LIMIT = 1;\n\nconst extractShoppingFallbackBodyText = (html: string): string => {\n const body = FALLBACK_BODY_RE.exec(html)?.[1];\n return extractText(body ?? html.replace(FALLBACK_HEAD_RE, \" \"));\n};\n\nconst hasShoppingMetadataEvidence = (extracted: ExtractedContent): boolean => {\n return extracted.metadata.price !== undefined;\n};\n\nconst hasShoppingOfferTextEvidence = (text: string): boolean => {\n const price = parsePrice(text);\n if (price.amount <= 0) return false;\n return parseRating(text) > 0\n || parseReviews(text) > 0\n || parseAvailability(text) !== \"unknown\"\n || /\\b(?:add to cart|buy now|shipping|pickup|deal|save)\\b/i.test(text);\n};\n\nconst hasShoppingBlockingPageEvidence = (\n url: string,\n extracted: ExtractedContent\n): boolean => {\n const blocker = classifyBlockerSignal({\n source: \"runtime_fetch\",\n url,\n finalUrl: url,\n title: typeof extracted.metadata.title === \"string\" ? extracted.metadata.title : undefined,\n message: extracted.text,\n status: 200,\n providerErrorCode: \"unavailable\",\n retryable: true\n });\n return blocker?.type === \"auth_required\" || blocker?.type === \"anti_bot_challenge\";\n};\n\nconst hasShoppingFallbackEvidence = (args: {\n html: string,\n url: string,\n extracted: ExtractedContent,\n profile: ShoppingProviderProfile\n}): boolean => {\n return args.extracted.links.some((link) => isLikelyProductUrl(canonicalizeUrl(link), args.profile))\n || extractSearchCandidates(args.html, args.url, args.profile, SHOPPING_FALLBACK_EVIDENCE_LIMIT).length > 0\n || hasShoppingMetadataEvidence(args.extracted)\n || hasShoppingOfferTextEvidence(extractShoppingFallbackBodyText(args.html))\n || hasShoppingBlockingPageEvidence(args.url, args.extracted);\n};\n\nconst toFallbackShellIssueError = (args: {\n provider: string;\n url: string;\n html: string;\n fallback: BrowserFallbackResponse;\n profile: ShoppingProviderProfile;\n requirement: { reason: string; title?: string; message?: string };\n}): ProviderRuntimeError => {\n const issue = classifyProviderIssue({\n url: args.url,\n title: args.requirement.title,\n message: args.requirement.message,\n providerShell: args.requirement.reason,\n browserRequired: true,\n status: 200\n });\n const reasonCode = issue?.reasonCode ?? \"env_limited\";\n const extracted = extractStructuredContent(args.html, args.url);\n return new ProviderRuntimeError(\n providerErrorCodeFromReasonCode(reasonCode),\n reasonCode === \"challenge_detected\"\n ? `Detected anti-bot challenge while retrieving ${args.url}`\n : `Browser assistance required for ${args.url}`,\n {\n provider: args.provider,\n source: SHOPPING_SOURCE,\n retryable: reasonCode === \"env_limited\",\n reasonCode,\n details: {\n ...applyProviderIssueHint({\n status: 200,\n url: args.url,\n ...(args.requirement.title ? { title: args.requirement.title } : {}),\n ...(args.requirement.message ? { message: args.requirement.message } : {}),\n providerShell: args.requirement.reason,\n browserRequired: true,\n extractionFocus: args.profile.extractionFocus,\n extractedTextLength: extracted.text.length,\n extractedLinkCount: extracted.links.length\n }, issue),\n ...browserFallbackObservationDetails(toBrowserFallbackObservation(args.fallback))\n }\n }\n );\n};\n\nconst parseIsoDate = (value: string): number => {\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? NaN : parsed;\n};\n\nconst fallbackReasonCodeForError = (error: {\n reasonCode?: ProviderReasonCode;\n}): ProviderReasonCode => {\n if (error.reasonCode) return error.reasonCode;\n // resolveBrowserFallback is only reached from the default fetcher's recoverable paths.\n // auth/rate_limited carry explicit reason codes above; the remaining cases are env-limited.\n return \"env_limited\";\n};\n\nconst resolveRecoverableFetchTimeoutMs = (context?: ProviderContext): number | undefined => {\n if (!context?.browserFallbackPort) return undefined;\n if (typeof context.timeoutMs !== \"number\" || !Number.isFinite(context.timeoutMs) || context.timeoutMs <= 0) {\n return DEFAULT_RECOVERABLE_SHOPPING_FETCH_TIMEOUT_MS;\n }\n return Math.max(1, Math.min(context.timeoutMs, DEFAULT_RECOVERABLE_SHOPPING_FETCH_TIMEOUT_MS));\n};\n\nconst bindRecoverableFetchSignal = (\n signal: AbortSignal | undefined,\n timeoutMs?: number\n): { signal?: AbortSignal; didTimeout: () => boolean; dispose: () => void } => {\n if (typeof timeoutMs !== \"number\" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n return {\n signal,\n didTimeout: () => false,\n dispose: () => undefined\n };\n }\n\n let timedOut = false;\n const controller = new AbortController();\n const abortFromParent = () => {\n controller.abort(signal?.reason);\n };\n if (signal?.aborted) {\n abortFromParent();\n } else {\n signal?.addEventListener(\"abort\", abortFromParent, { once: true });\n }\n const timeoutId = setTimeout(() => {\n timedOut = true;\n controller.abort(\"timeout\");\n }, timeoutMs);\n\n return {\n signal: controller.signal,\n didTimeout: () => timedOut,\n dispose: () => {\n clearTimeout(timeoutId);\n signal?.removeEventListener(\"abort\", abortFromParent);\n }\n };\n};\n\nconst buildShoppingRecoveryHints = (profile: ShoppingProviderProfile): ProviderRecoveryHints => ({\n preferredFallbackModes: DEFAULT_SHOPPING_FALLBACK_MODES,\n highFrictionTarget: profile.name === \"temu\" || profile.name === \"target\",\n challengeProne: profile.name === \"temu\" || profile.name === \"target\" || profile.name === \"bestbuy\",\n settleTimeoutMs: 15000,\n captureDelayMs: 2000\n});\n\nconst resolveBrowserFallback = async (args: {\n error: ProviderRuntimeError;\n url: string;\n provider: string;\n profile: ShoppingProviderProfile;\n operation: \"search\" | \"fetch\";\n recoveryHints: ProviderRecoveryHints;\n context?: ProviderContext;\n}): Promise<{\n record: ShoppingFetchRecord | null;\n failure?: ProviderRuntimeError;\n}> => {\n const normalized = toProviderError(args.error, {\n provider: args.provider,\n source: SHOPPING_SOURCE\n });\n const reasonCode = fallbackReasonCodeForError(normalized);\n const fallbackIssue = readProviderIssueHint({\n reasonCode: normalized.reasonCode,\n code: normalized.code,\n message: normalized.message,\n details: normalized.details\n });\n const createTimedOutFallbackIssue = (timeoutError: ProviderRuntimeError): ProviderRuntimeError | null => {\n if (!fallbackIssue) return null;\n if (\n fallbackIssue.reasonCode !== \"token_required\"\n && fallbackIssue.reasonCode !== \"challenge_detected\"\n && !fallbackIssue.constraint\n ) {\n return null;\n }\n const message = fallbackIssue.reasonCode === \"token_required\"\n ? `Authentication required for ${args.url}`\n : fallbackIssue.reasonCode === \"challenge_detected\"\n ? `Detected anti-bot challenge while retrieving ${args.url}`\n : `Browser assistance required for ${args.url}`;\n return new ProviderRuntimeError(\n providerErrorCodeFromReasonCode(fallbackIssue.reasonCode),\n message,\n {\n provider: args.provider,\n source: SHOPPING_SOURCE,\n retryable: fallbackIssue.reasonCode === \"env_limited\",\n reasonCode: fallbackIssue.reasonCode,\n details: applyProviderIssueHint({\n url: args.url,\n fallbackTimeout: true,\n fallbackTimeoutMessage: timeoutError.message,\n ...(normalized.details ?? {}),\n ...(timeoutError.details ?? {})\n }, fallbackIssue)\n }\n );\n };\n\n let fallback;\n try {\n fallback = await resolveProviderBrowserFallback({\n browserFallbackPort: args.context?.browserFallbackPort,\n provider: args.provider,\n source: SHOPPING_SOURCE,\n operation: args.operation,\n reasonCode,\n url: args.url,\n context: args.context,\n details: {\n errorCode: normalized.code,\n message: normalized.message,\n ...(normalized.details ?? {})\n },\n recoveryHints: args.recoveryHints\n });\n } catch (error) {\n if (error instanceof ProviderRuntimeError && error.code === \"timeout\") {\n throw createTimedOutFallbackIssue(error) ?? error;\n }\n throw error;\n }\n if (!fallback) {\n return { record: null };\n }\n if (fallback.disposition !== \"completed\") {\n const failure = toProviderFallbackError({\n provider: args.provider,\n source: SHOPPING_SOURCE,\n url: args.url,\n fallback\n });\n if (fallback.reasonCode !== \"env_limited\") {\n throw failure;\n }\n return {\n record: null,\n failure\n };\n }\n\n const resolvedUrl = canonicalizeUrl(readFallbackString(fallback.output, \"url\") ?? args.url);\n const html = readFallbackString(fallback.output, \"html\");\n if (!html) {\n throw toCompletedFallbackOutputError({\n provider: args.provider,\n source: SHOPPING_SOURCE,\n url: resolvedUrl,\n fallback,\n outputReason: \"missing_or_empty_html\"\n });\n }\n const extracted = extractStructuredContent(html, resolvedUrl);\n const browserRequirement = requiresBrowserAssistance(args.profile, resolvedUrl, html);\n if (browserRequirement) {\n throw toFallbackShellIssueError({\n provider: args.provider,\n url: resolvedUrl,\n html,\n fallback,\n profile: args.profile,\n requirement: browserRequirement\n });\n }\n if (!hasShoppingFallbackEvidence({\n html,\n url: resolvedUrl,\n extracted,\n profile: args.profile\n })) {\n throw toCompletedFallbackOutputError({\n provider: args.provider,\n source: SHOPPING_SOURCE,\n url: resolvedUrl,\n fallback,\n outputReason: \"empty_extracted_content\"\n });\n }\n return {\n record: {\n status: 200,\n url: resolvedUrl,\n html,\n browserFallback: toBrowserFallbackObservation(fallback)\n }\n };\n};\n\nexport const validateLegalReviewChecklist = (\n checklist: ProviderLegalReviewChecklist | undefined,\n expectedProviderId: string,\n now: Date = new Date()\n): LegalReviewValidationResult => {\n if (!checklist) return { valid: false, reasonCode: \"missing_checklist\" };\n if (checklist.providerId !== expectedProviderId) return { valid: false, reasonCode: \"provider_mismatch\" };\n if (!checklist.termsReviewDate.trim()) return { valid: false, reasonCode: \"missing_terms_review_date\" };\n if (Number.isNaN(parseIsoDate(checklist.termsReviewDate))) return { valid: false, reasonCode: \"invalid_terms_review_date\" };\n if (!hasValues(checklist.allowedExtractionSurfaces)) return { valid: false, reasonCode: \"missing_allowed_surfaces\" };\n if (!hasValues(checklist.prohibitedFlows)) return { valid: false, reasonCode: \"missing_prohibited_flows\" };\n if (!checklist.reviewer.trim()) return { valid: false, reasonCode: \"missing_reviewer\" };\n if (!checklist.approvalExpiryDate.trim()) return { valid: false, reasonCode: \"missing_approval_expiry\" };\n\n const expiry = parseIsoDate(checklist.approvalExpiryDate);\n if (Number.isNaN(expiry)) return { valid: false, reasonCode: \"invalid_approval_expiry\" };\n if (expiry <= now.getTime()) return { valid: false, reasonCode: \"approval_expired\" };\n if (!checklist.signedOff) return { valid: false, reasonCode: \"not_signed_off\" };\n return { valid: true };\n};\n\nexport const getShoppingProviderProfile = (providerId: string): ShoppingProviderProfile | null => {\n return SHOPPING_PROVIDER_PROFILES.find((profile) => profile.id === providerId) ?? null;\n};\n\nexport const validateShoppingLegalReviewChecklist = (\n providerId: string,\n now: Date = new Date()\n): LegalReviewValidationResult => {\n const profile = getShoppingProviderProfile(providerId);\n if (!profile) return { valid: false, reasonCode: \"missing_checklist\" };\n return validateLegalReviewChecklist(profile.legalReview, profile.id, now);\n};\n\nconst defaultFetcher: ShoppingFetcher = async ({ url, signal, provider, operation, context }) => {\n const providerId = provider;\n const profile = getShoppingProviderProfile(providerId) ?? SHOPPING_PROVIDER_PROFILES.at(-1)!;\n const recoveryHints = buildShoppingRecoveryHints(profile);\n const buildSurfaceIssueError = (\n responseUrl: string,\n issue: ReturnType<typeof classifyProviderIssue>,\n details: Record<string, JsonValue>,\n browserFallback?: BrowserFallbackObservation\n ): ProviderRuntimeError => {\n /* c8 ignore next -- browser-assistance classification always returns a reasonCode when issue is present */\n const reasonCode = issue?.reasonCode ?? \"env_limited\";\n const message = reasonCode === \"token_required\"\n ? `Authentication required for ${responseUrl}`\n : reasonCode === \"challenge_detected\"\n ? `Detected anti-bot challenge while retrieving ${responseUrl}`\n : `Browser assistance required for ${responseUrl}`;\n return new ProviderRuntimeError(\n providerErrorCodeFromReasonCode(reasonCode),\n message,\n {\n provider: providerId,\n source: SHOPPING_SOURCE,\n retryable: reasonCode === \"env_limited\",\n reasonCode,\n details: {\n ...applyProviderIssueHint(details, issue),\n ...browserFallbackObservationDetails(browserFallback)\n }\n }\n );\n };\n const detectFetchedPageError = (\n responseUrl: string,\n status: number,\n html: string,\n browserFallback?: BrowserFallbackObservation\n ): ProviderRuntimeError | null => {\n const extracted = extractStructuredContent(html, responseUrl);\n const message = toSnippet(\n [\n extracted.metadata.title,\n extracted.metadata.description,\n extracted.text\n ].filter((value): value is string => typeof value === \"string\" && value.trim().length > 0).join(\" \"),\n 800\n );\n const blocker = classifyBlockerSignal({\n source: \"runtime_fetch\",\n url: responseUrl,\n finalUrl: responseUrl,\n title: typeof extracted.metadata.title === \"string\" ? extracted.metadata.title : undefined,\n message,\n status,\n providerErrorCode: \"unavailable\",\n retryable: true\n });\n if (blocker && blocker.type !== \"unknown\" && blocker.type !== \"env_limited\") {\n return new ProviderRuntimeError(\"unavailable\", `Detected ${blocker.type} while retrieving ${responseUrl}`, {\n provider: providerId,\n source: SHOPPING_SOURCE,\n retryable: blocker.retryable,\n reasonCode: blocker.reasonCode ?? \"env_limited\",\n details: {\n status,\n url: responseUrl,\n blockerType: blocker.type,\n blockerConfidence: blocker.confidence,\n ...(typeof extracted.metadata.title === \"string\" ? { title: extracted.metadata.title } : {}),\n reasonCode: blocker.reasonCode ?? \"env_limited\",\n ...browserFallbackObservationDetails(browserFallback)\n }\n });\n }\n\n const requirement = requiresBrowserAssistance(profile, responseUrl, html);\n if (!requirement) return null;\n\n const issue = classifyProviderIssue({\n url: responseUrl,\n title: requirement.title,\n message: requirement.message,\n providerShell: requirement.reason,\n browserRequired: true,\n status,\n providerErrorCode: \"unavailable\",\n retryable: true\n });\n return buildSurfaceIssueError(responseUrl, issue, {\n status,\n url: responseUrl,\n browserRequired: true,\n providerShell: requirement.reason,\n ...(requirement.title ? { title: requirement.title } : {}),\n ...(requirement.message ? { message: requirement.message } : {})\n }, browserFallback);\n };\n const resolveFallbackOrThrow = async (\n error: ProviderRuntimeError,\n options?: { preserveFallbackFailure?: boolean }\n ): Promise<ShoppingFetchRecord> => {\n const fallback = await resolveBrowserFallback({\n error,\n url,\n provider: providerId,\n profile,\n operation,\n recoveryHints,\n context\n });\n if (fallback.record) {\n const fallbackError = detectFetchedPageError(\n fallback.record.url,\n fallback.record.status,\n fallback.record.html,\n fallback.record.browserFallback\n );\n if (fallbackError) {\n throw fallbackError;\n }\n return fallback.record;\n }\n if (options?.preserveFallbackFailure && fallback.failure) {\n throw fallback.failure;\n }\n throw error;\n };\n\n if (context?.runtimePolicy?.browser.forceTransport) {\n return resolveFallbackOrThrow(\n new ProviderRuntimeError(\n \"unavailable\",\n `Explicit browser transport requested for ${url}`,\n {\n provider: providerId,\n source: SHOPPING_SOURCE,\n retryable: true,\n reasonCode: \"env_limited\",\n details: {\n url,\n stage: `${operation}:forced_browser_transport`\n }\n }\n ),\n { preserveFallbackFailure: true }\n );\n }\n\n let response: Response;\n const rawFetchSignal = bindRecoverableFetchSignal(signal, resolveRecoverableFetchTimeoutMs(context));\n try {\n response = await fetch(url, {\n signal: rawFetchSignal.signal,\n headers: {\n accept: \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n ...providerRequestHeaders\n },\n redirect: \"follow\"\n });\n } catch (error) {\n const runtimeError = new ProviderRuntimeError(\n rawFetchSignal.didTimeout() ? \"timeout\" : \"network\",\n rawFetchSignal.didTimeout() ? `Timed out retrieving ${url}` : `Failed to retrieve ${url}`,\n {\n provider: providerId,\n source: SHOPPING_SOURCE,\n retryable: true,\n cause: error,\n ...(rawFetchSignal.didTimeout()\n ? {\n details: {\n url,\n stage: `${operation}:raw_fetch_timeout`\n }\n }\n : {})\n }\n );\n return resolveFallbackOrThrow(runtimeError);\n } finally {\n rawFetchSignal.dispose();\n }\n\n if (response.status === 401 || response.status === 403) {\n const runtimeError = new ProviderRuntimeError(\"auth\", `Authentication required for ${url}`, {\n provider: providerId,\n source: SHOPPING_SOURCE,\n retryable: false,\n reasonCode: \"token_required\",\n details: { status: response.status, url, reasonCode: \"token_required\" }\n });\n return resolveFallbackOrThrow(runtimeError);\n }\n if (response.status === 429) {\n const runtimeError = new ProviderRuntimeError(\"rate_limited\", `Rate limited while retrieving ${url}`, {\n provider: providerId,\n source: SHOPPING_SOURCE,\n retryable: true,\n details: { status: response.status, url }\n });\n return resolveFallbackOrThrow(runtimeError);\n }\n if (response.status >= 400) {\n const runtimeError = new ProviderRuntimeError(\"unavailable\", `Retrieval failed for ${url}`, {\n provider: providerId,\n source: SHOPPING_SOURCE,\n retryable: response.status >= 500,\n details: { status: response.status, url }\n });\n return resolveFallbackOrThrow(runtimeError);\n }\n\n const html = await response.text();\n const responseUrl = response.url || url;\n const fetchedPageError = detectFetchedPageError(responseUrl, response.status, html);\n if (fetchedPageError) {\n return await resolveFallbackOrThrow(fetchedPageError);\n }\n\n return {\n status: response.status,\n url: responseUrl,\n html\n };\n};\n\nconst PRICE_SYMBOL_RE = /([$€£])\\s*([0-9]{1,3}(?:[.,][0-9]{3})*(?:[.,][0-9]{1,2})?)/;\nconst PRICE_CODE_RE = /\\b(USD|CAD|EUR|GBP)\\s*([0-9]{1,3}(?:[.,][0-9]{3})*(?:[.,][0-9]{1,2})?)/i;\nconst RATING_RE = /([0-5](?:\\.[0-9])?)\\s*(?:out of 5|\\/5)/i;\nconst REVIEWS_RE = /([0-9][0-9,]*)\\s*(?:ratings|reviews)/i;\nconst FETCH_TEXT_PRICE_TOKEN_RE = /(?:\\b(?:USD|CAD|EUR|GBP)\\s*[0-9]{1,4}(?:[.,][0-9]{3})*(?:[.,][0-9]{1,2})?|[$€£]\\s*[0-9]{1,4}(?:[.,][0-9]{3})*(?:[.,][0-9]{1,2})?)/gi;\nconst FETCH_TEXT_PRICE_NEGATIVE_PREFIX_RE = /\\b(?:customer review|reviews?|ratings?|stars?)\\b/i;\nconst FETCH_TEXT_PRICE_MAX_PREFIX_CHARS = 180;\nconst ANCHOR_RE = /<a\\b([^>]*?)href\\s*=\\s*(?:([\"'])(.*?)\\2|([^\\s>]+))([^>]*)>([\\s\\S]*?)<\\/a>/gi;\nconst AMAZON_CARD_RE = /<div\\b(?=[^>]*\\bdata-component-type=([\"'])s-search-result\\1)(?=[^>]*\\bclass=([\"'])[^\"']*\\bs-result-item\\b[^\"']*\\2)[^>]*>[\\s\\S]*?(?=<div\\b(?=[^>]*\\bdata-component-type=([\"'])s-search-result\\3)(?=[^>]*\\bclass=([\"'])[^\"']*\\bs-result-item\\b[^\"']*\\4)|$)/gi;\nconst COSTCO_CARD_RE = /<div\\b(?=[^>]*\\bdata-testid=([\"'])ProductTile_[^\"']+\\1)[^>]*>[\\s\\S]*?(?=<div\\b(?=[^>]*\\bdata-testid=([\"'])ProductTile_[^\"']+\\2)|$)/gi;\nconst NEWEGG_CARD_RE = /<div class=\"item-cell\"[\\s\\S]*?(?=<div class=\"item-cell\"|$)/gi;\nconst EBAY_CARD_RE = /<li\\b[^>]*class=([\"'])[^\"']*\\bs-card\\b[^\"']*\\1[^>]*>[\\s\\S]*?<\\/li>/gi;\nconst GENERIC_NOISE_TITLE_RE = /^(quick view|previous page|next page|home|compare|\\([0-9][0-9,]*\\))$/i;\nconst GENERIC_NOISE_URL_RE = /(?:\\/(?:p\\/pl|s(?:earch)?|signin|login|orders|cart|promotions|clearance|brandstore)\\b|#IsFeedbackTab\\b|\\/Product\\/RSS\\b|[?&](?:page|k|d|n)=)/i;\nconst DEFAULT_PRODUCT_URL_HINT_RE = /(?:\\/dp\\/|\\/gp\\/product\\/|\\/p\\/[a-z0-9-]+|\\/product(?:s)?\\/|\\/item(?:[/?-]|$)|\\/sku\\/)/i;\nconst PROVIDER_PRODUCT_URL_HINT_RE: Partial<Record<ShoppingProviderName, RegExp>> = {\n walmart: /\\/ip(?:\\/|$)/i,\n bestbuy: /\\/site\\/[^?#]*\\/\\d+\\.p(?:[?#]|$)/i,\n ebay: /\\/itm(?:\\/|$)/i,\n costco: /(?:\\/|\\.)(?:product|warehouse)\\.[^?#]+\\.html(?:[?#]|$)|[?&](?:prodid|itemnumber)=/i,\n macys: /\\/shop\\/product\\/[^?#]+(?:[?#]|$)/i,\n aliexpress: /\\/(?:item|i)\\/[^?#]+/i,\n temu: /\\/(?:goods\\.html|g-[^/?#]+\\.html)(?:[?#]|$)/i,\n others: /(?:\\/ip(?:\\/|$)|\\/itm(?:\\/|$)|\\/product(?:s)?\\/|\\/sku\\/|\\/site\\/[^?#]*\\/\\d+\\.p(?:[?#]|$)|(?:\\/|\\.)(?:product|warehouse)\\.[^?#]+\\.html(?:[?#]|$))/i\n};\nconst isHttpUrl = (value: string): boolean => {\n try {\n const protocol = new URL(value).protocol;\n return protocol === \"http:\" || protocol === \"https:\";\n } catch {\n return false;\n }\n};\n\nconst readAttribute = (tag: string, name: string): string | undefined => {\n const quoted = new RegExp(`${name}\\\\s*=\\\\s*([\"'])(.*?)\\\\1`, \"i\").exec(tag);\n if (quoted?.[2]) return extractText(quoted[2]);\n const unquoted = new RegExp(`${name}\\\\s*=\\\\s*([^\\\\s>]+)`, \"i\").exec(tag);\n if (unquoted?.[1]) return extractText(unquoted[1]);\n return undefined;\n};\n\nconst readAnchorHref = (match: RegExpMatchArray): string | undefined => {\n const quotedHref = match[3];\n if (quotedHref) return quotedHref;\n return match[4];\n};\n\nconst readAnchorTag = (match: RegExpMatchArray): string => {\n return `<a${match[1] ? ` ${match[1]}` : \"\"}${match[5] ? ` ${match[5]}` : \"\"}>`;\n};\n\nconst readAnchorInnerHtml = (match: RegExpMatchArray): string => {\n return match[6] as string;\n};\n\nconst hasClassToken = (value: string | undefined, token: string): boolean => {\n if (!value) return false;\n return new RegExp(`(?:^|\\\\s)${token}(?:\\\\s|$)`, \"i\").test(value);\n};\n\nconst findAnchorByClass = (\n html: string,\n token: string\n): { href: string; innerHtml: string; tag: string } | null => {\n for (const match of html.matchAll(ANCHOR_RE)) {\n const href = readAnchorHref(match);\n if (!href) continue;\n const tag = readAnchorTag(match);\n if (!hasClassToken(readAttribute(tag, \"class\"), token)) continue;\n return {\n href,\n innerHtml: readAnchorInnerHtml(match),\n tag\n };\n }\n return null;\n};\n\nconst resolveCardProductAnchor = (\n html: string,\n baseUrl: string,\n profile: ShoppingProviderProfile\n): { url: string; title: string; innerHtml: string } | null => {\n for (const match of html.matchAll(ANCHOR_RE)) {\n const href = readAnchorHref(match);\n if (!href) continue;\n const url = normalizeCandidateUrl(href, baseUrl, profile);\n if (!url || !isLikelyProductUrl(url, profile)) continue;\n const tag = readAnchorTag(match);\n const title = extractText(readAnchorInnerHtml(match))\n || readAttribute(tag, \"aria-label\")\n || readAttribute(tag, \"title\");\n if (!title || title.length < 20 || GENERIC_NOISE_TITLE_RE.test(title) || isPriceOnlyTitle(title)) continue;\n return {\n url,\n title,\n innerHtml: readAnchorInnerHtml(match)\n };\n }\n return null;\n};\n\nconst normalizePriceText = (text: string): string => {\n return text\n .replace(/([$€£])\\s+/g, \"$1\")\n .replace(/\\b(USD|CAD|EUR|GBP)\\s+/gi, (_match, code: string) => `${code.toUpperCase()} `)\n .replace(/(\\d)\\s*([.,])\\s*(\\d{2})/g, \"$1$2$3\");\n};\n\nconst parsePrice = (text: string): { amount: number; currency: string } => {\n const normalized = normalizePriceText(text);\n const codeMatch = normalized.match(PRICE_CODE_RE);\n if (codeMatch) {\n const amount = Number(codeMatch[2]!.replace(/,/g, \"\"));\n return {\n amount: Number.isFinite(amount) ? amount : 0,\n currency: codeMatch[1]!.toUpperCase()\n };\n }\n\n const symbolMatch = normalized.match(PRICE_SYMBOL_RE);\n if (!symbolMatch) {\n return { amount: 0, currency: DEFAULT_CURRENCY };\n }\n\n const currencySymbol = symbolMatch[1];\n const amount = Number(symbolMatch[2]!.replace(/,/g, \"\"));\n const currency = currencySymbol === \"€\"\n ? \"EUR\"\n : currencySymbol === \"£\"\n ? \"GBP\"\n : DEFAULT_CURRENCY;\n\n return {\n amount: Number.isFinite(amount) ? amount : 0,\n currency\n };\n};\n\nconst resolveFetchTextPrice = (text: string): ResolvedShoppingPrice | undefined => {\n const normalized = normalizePriceText(text);\n for (const match of normalized.matchAll(FETCH_TEXT_PRICE_TOKEN_RE)) {\n const token = match[0]?.trim();\n const index = match.index ?? -1;\n if (!token || index < 0 || index > FETCH_TEXT_PRICE_MAX_PREFIX_CHARS) {\n continue;\n }\n if (FETCH_TEXT_PRICE_NEGATIVE_PREFIX_RE.test(normalized.slice(0, index))) {\n continue;\n }\n const price = parsePrice(token);\n if (price.amount <= 0) {\n continue;\n }\n return {\n ...price,\n source: \"search_card_context\",\n trustworthy: false\n };\n }\n return undefined;\n};\n\nconst resolvePrice = (\n primaryText: string,\n ...fallbackTexts: string[]\n): ResolvedShoppingPrice => {\n const primary = parsePrice(primaryText);\n if (primary.amount > 0) {\n return {\n ...primary,\n source: \"search_card_context\",\n trustworthy: true\n };\n }\n for (const fallbackText of fallbackTexts) {\n const fallback = parsePrice(fallbackText);\n if (fallback.amount > 0) {\n return {\n ...fallback,\n source: \"search_title_inline\",\n trustworthy: true\n };\n }\n }\n return {\n ...primary,\n source: \"unresolved\",\n trustworthy: false\n };\n};\n\nconst parseRating = (text: string): number => {\n const match = text.match(RATING_RE);\n if (!match) return 0;\n return Math.max(0, Math.min(5, Number(match[1])));\n};\n\nconst parseReviews = (text: string): number => {\n const match = text.match(REVIEWS_RE);\n if (!match) return 0;\n const value = Number(match[1]!.replace(/,/g, \"\"));\n return Number.isFinite(value) ? Math.max(0, value) : 0;\n};\n\nconst parseAvailability = (text: string): \"in_stock\" | \"limited\" | \"out_of_stock\" | \"unknown\" => {\n const lower = text.toLowerCase();\n if (/out of stock|sold out|unavailable/.test(lower)) return \"out_of_stock\";\n if (/limited|few left|only \\d+ left/.test(lower)) return \"limited\";\n if (/in stock|available now|ships|add to cart|free shipping/.test(lower)) return \"in_stock\";\n return \"unknown\";\n};\n\nconst dedupeLinks = (links: string[], limit: number): string[] => {\n const seen = new Set<string>();\n const normalized: string[] = [];\n for (const link of links) {\n const url = canonicalizeUrl(link);\n if (!isHttpUrl(url) || seen.has(url)) continue;\n seen.add(url);\n normalized.push(url);\n if (normalized.length >= limit) break;\n }\n return normalized.sort((left, right) => left.localeCompare(right));\n};\n\nconst stripPriceScaffold = (title: string): string => {\n return normalizePriceText(title)\n .replace(/(?:USD|CAD|EUR|GBP)\\s*(?=[0-9])/gi, \" \")\n .replace(/\\b(?:USD|CAD|EUR|GBP|list|price|now|sale|deal|from)\\b/gi, \" \")\n .replace(/[$€£]/g, \" \")\n .replace(/[0-9]+(?:[.,][0-9]+)*/g, \" \")\n .replace(/[():/.,-]+/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n};\n\nconst RATING_ONLY_TITLE_RE = /^(?:rating\\s*)?[0-5](?:\\.[0-9])?\\s*out of 5 stars?(?:\\s*with\\s*[0-9][0-9,]*\\s*reviews?)?(?:\\s*\\([0-9][0-9,]*\\))?$/i;\n\nconst isPriceOnlyTitle = (title: string): boolean => {\n const stripped = stripPriceScaffold(title);\n return stripped.length < 8 || !/[a-z]{4,}/i.test(stripped);\n};\n\nconst isRatingOnlyTitle = (title: string): boolean => {\n return RATING_ONLY_TITLE_RE.test(title.trim());\n};\n\nconst TRACKING_DESTINATION_PARAM_KEYS = [\n \"uddg\",\n \"rd\",\n \"url\",\n \"u\",\n \"dest\",\n \"destination\",\n \"redirect\",\n \"redirect_url\",\n \"target\",\n \"to\"\n] as const;\n\nconst decodeTrackingDestination = (value: string): string | null => {\n let current = value.trim();\n if (!current) return null;\n for (let attempt = 0; attempt < 3; attempt += 1) {\n try {\n const decoded = decodeURIComponent(current);\n if (decoded === current) break;\n current = decoded;\n } catch {\n break;\n }\n }\n return current;\n};\n\nconst decodeHrefValue = (value: string): string => {\n return value\n .replace(/&/gi, \"&\")\n .replace(///gi, \"/\")\n .replace(///gi, \"/\");\n};\n\nconst requiresBrowserAssistance = (\n profile: ShoppingProviderProfile,\n responseUrl: string,\n html: string\n): { reason: string; title?: string; message?: string } | null => {\n const extracted = extractStructuredContent(html, responseUrl);\n const title = typeof extracted.metadata.title === \"string\" ? extracted.metadata.title.trim() : \"\";\n const text = extracted.text.trim();\n const titleLower = title.toLowerCase();\n const textLower = text.toLowerCase();\n\n if (profile.name === \"bestbuy\") {\n const hasInternationalGate = titleLower.includes(\"best buy international\")\n || textLower.includes(\"best buy international\")\n || textLower.includes(\"select your country\")\n || textLower.includes(\"choose a country\");\n if (hasInternationalGate) {\n return {\n reason: \"bestbuy_international_gate\",\n ...(title ? { title } : {}),\n ...(text ? { message: toSnippet(text, 400) } : {})\n };\n }\n const hasPdpErrorShell = textLower.includes(\"something went wrong\")\n && (\n textLower.includes(\"use our search bar\")\n || textLower.includes(\"pick a category below\")\n || textLower.includes(\"typed in a url\")\n );\n if (hasPdpErrorShell) {\n return {\n reason: \"bestbuy_pdp_error_shell\",\n ...(title ? { title } : {}),\n ...(text ? { message: toSnippet(text, 400) } : {})\n };\n }\n }\n\n if (profile.name === \"target\") {\n const isShellPage = /:\\s*target$/i.test(title)\n && textLower.includes(\"skip to main content\")\n && textLower.includes(\"skip to footer\");\n const isNextProductGridShell = /:\\s*target$/i.test(title)\n && (html.includes(\"WEB-search-product-grid-default\") || html.includes(\"__TGT_DATA__\"))\n && !/href=([\"'])[^\"']*\\/p\\/[^\"']+\\1/i.test(html);\n if (isShellPage || isNextProductGridShell) {\n return {\n reason: \"target_shell_page\",\n ...(title ? { title } : {}),\n message: toSnippet(text, 400)\n };\n }\n }\n\n if (profile.name === \"macys\") {\n const hasAccessDeniedHeading = titleLower.includes(\"access denied\") || textLower.includes(\"access denied\");\n const isAccessDeniedShell = hasAccessDeniedHeading\n && textLower.includes(\"you don't have permission to access\")\n && (textLower.includes(\"on this server\") || textLower.includes(\"reference #\"));\n if (isAccessDeniedShell) {\n return {\n reason: \"macys_access_denied_shell\",\n ...(title ? { title } : {}),\n message: toSnippet(text, 400)\n };\n }\n }\n\n if (profile.name === \"temu\") {\n const htmlLower = html.toLowerCase();\n const hasChallengeShell = /static(?:-\\d+)?\\.kwcdn\\.com/i.test(html)\n && (html.includes(\"/upload-static/assets/chl/js/\") || textLower.includes(\"challenge\"));\n const hasObfuscatedChallengeShell = htmlLower.includes(\"challenge\")\n && html.length < 12000\n && /function _0x[a-f0-9]+\\(/i.test(html);\n if (hasChallengeShell || hasObfuscatedChallengeShell) {\n return {\n reason: \"temu_challenge_shell\",\n ...(title ? { title } : {}),\n message: \"Temu returned a challenge shell that requires a live browser session.\"\n };\n }\n if (text.length === 0) {\n return {\n reason: \"temu_empty_shell\",\n ...(title ? { title } : {}),\n message: \"Temu returned an empty shell page.\"\n };\n }\n }\n\n if (profile.name === \"others\" && textLower.includes(\"redirected to the non-javascript site\")) {\n return {\n reason: \"duckduckgo_non_js_redirect\",\n ...(title ? { title } : {}),\n message: toSnippet(text, 400)\n };\n }\n\n return null;\n};\n\nconst classifySearchPageIssue = (\n profile: ShoppingProviderProfile,\n fetched: ShoppingFetchRecord,\n extracted: ExtractedContent,\n content: string,\n providerShell: ReturnType<typeof requiresBrowserAssistance> = requiresBrowserAssistance(profile, fetched.url, fetched.html)\n): ProviderIssueHint | null => {\n return classifyProviderIssue({\n url: fetched.url,\n title: providerShell?.title ?? (typeof extracted.metadata.title === \"string\" ? extracted.metadata.title : undefined),\n message: providerShell?.message ?? content,\n providerShell: providerShell?.reason,\n browserRequired: providerShell ? true : undefined,\n status: fetched.status,\n providerErrorCode: \"unavailable\",\n retryable: true\n });\n};\n\nconst toExplicitProviderShellIssue = (\n providerShell: NonNullable<ReturnType<typeof requiresBrowserAssistance>>,\n content: string\n): ProviderIssueHint => ({\n reasonCode: \"env_limited\",\n blockerType: \"env_limited\",\n constraint: {\n kind: \"render_required\",\n evidenceCode: providerShell.reason,\n providerShell: providerShell.reason,\n ...(content ? { message: content } : {})\n }\n});\n\nconst ensureProviderShellIssue = (\n issue: ProviderIssueHint | null,\n providerShell: NonNullable<ReturnType<typeof requiresBrowserAssistance>>,\n content: string\n): ProviderIssueHint => {\n if (!issue || (issue.reasonCode === \"env_limited\" && !issue.constraint)) {\n return toExplicitProviderShellIssue(providerShell, content);\n }\n return issue;\n};\n\nconst toShoppingPageIssueMessage = (reasonCode: ProviderReasonCode, url: string): string => {\n if (reasonCode === \"token_required\") return `Authentication required for ${url}`;\n if (reasonCode === \"env_limited\") return `Browser assistance required for ${url}`;\n return `Detected anti-bot challenge while retrieving ${url}`;\n};\n\nconst throwShoppingPageIssue = (args: {\n providerId: string;\n fetched: ShoppingFetchRecord;\n extracted: ExtractedContent;\n content: string;\n pageIssue: ProviderIssueHint;\n providerShell: ReturnType<typeof requiresBrowserAssistance>;\n}): never => {\n const reasonCode = args.pageIssue.reasonCode;\n throw new ProviderRuntimeError(\n providerErrorCodeFromReasonCode(reasonCode),\n toShoppingPageIssueMessage(reasonCode, args.fetched.url),\n {\n provider: args.providerId,\n source: SHOPPING_SOURCE,\n retryable: reasonCode === \"env_limited\",\n reasonCode,\n details: {\n ...applyProviderIssueHint({\n status: args.fetched.status,\n url: args.fetched.url,\n ...(typeof args.extracted.metadata.title === \"string\" ? { title: args.extracted.metadata.title } : {}),\n ...(args.content ? { message: args.content } : {}),\n ...(args.providerShell?.reason ? { providerShell: args.providerShell.reason } : {})\n }, args.pageIssue),\n ...(args.providerShell?.reason ? { browserRequired: true } : {}),\n ...browserFallbackObservationDetails(args.fetched.browserFallback)\n }\n }\n );\n};\n\nconst unwrapTrackingUrl = (url: string, profile: ShoppingProviderProfile): string => {\n const normalizedUrl = decodeHrefValue(url);\n try {\n const parsed = new URL(normalizedUrl);\n for (const key of TRACKING_DESTINATION_PARAM_KEYS) {\n const rawValue = parsed.searchParams.get(key);\n if (!rawValue) continue;\n const decoded = decodeTrackingDestination(rawValue);\n if (!decoded) continue;\n const candidate = canonicalizeUrl(decoded);\n if (isKnownProviderDomain(candidate, profile) && !GENERIC_NOISE_URL_RE.test(candidate) && hasProductUrlHint(candidate, profile)) {\n return candidate;\n }\n }\n } catch {\n // ignore malformed tracking wrappers and continue with string-based recovery\n }\n\n const schemeIndex = normalizedUrl.indexOf(\"://\");\n const searchFrom = schemeIndex >= 0 ? schemeIndex + 3 : 0;\n const nestedSchemes = [\n normalizedUrl.indexOf(\"https://\", searchFrom),\n normalizedUrl.indexOf(\"http://\", searchFrom)\n ].filter((index) => index >= 0).sort((left, right) => left - right);\n const nestedIndex = nestedSchemes[0];\n if (typeof nestedIndex === \"number\" && nestedIndex >= 0) {\n const candidate = canonicalizeUrl(normalizedUrl.slice(nestedIndex));\n if (isKnownProviderDomain(candidate, profile) && !GENERIC_NOISE_URL_RE.test(candidate) && hasProductUrlHint(candidate, profile)) {\n return candidate;\n }\n }\n\n return normalizedUrl;\n};\n\nconst normalizeCandidateUrl = (href: string, baseUrl: string, profile: ShoppingProviderProfile): string | null => {\n try {\n const resolved = canonicalizeUrl(new URL(decodeHrefValue(href), baseUrl).toString());\n return unwrapTrackingUrl(resolved, profile);\n } catch {\n return null;\n }\n};\n\nconst isKnownProviderDomain = (url: string, profile: ShoppingProviderProfile): boolean => {\n try {\n const host = new URL(url).hostname.toLowerCase();\n return profile.domains.length === 0 || profile.domains.some((domain) => host === domain || host.endsWith(`.${domain}`));\n } catch {\n return false;\n }\n};\n\nconst hasProductUrlHint = (url: string, profile: ShoppingProviderProfile): boolean => {\n const providerHint = PROVIDER_PRODUCT_URL_HINT_RE[profile.name];\n return providerHint?.test(url) === true || DEFAULT_PRODUCT_URL_HINT_RE.test(url);\n};\n\nconst isLikelyProductUrl = (url: string, profile: ShoppingProviderProfile): boolean => {\n if (!isHttpUrl(url)) return false;\n if (!isKnownProviderDomain(url, profile)) return false;\n if (/\\.(?:png|jpe?g|gif|webp|svg|ico|css|js)(?:$|\\?)/i.test(url)) return false;\n if (GENERIC_NOISE_URL_RE.test(url)) return false;\n return hasProductUrlHint(url, profile);\n};\n\nconst candidateUrlKey = (url: string): string => {\n const parsed = new URL(url);\n parsed.hash = \"\";\n parsed.search = \"\";\n parsed.pathname = parsed.pathname.replace(/\\/ref=[^/]+$/i, \"\");\n const amazonDpMatch = parsed.pathname.match(/^(\\/[^/]+\\/(?:dp|gp\\/product)\\/[A-Z0-9]+)/i);\n if (amazonDpMatch?.[1]) {\n parsed.pathname = amazonDpMatch[1];\n }\n return canonicalizeUrl(parsed.toString());\n};\n\nconst scoreCandidate = (candidate: ShoppingSearchCandidate): number => {\n let score = Math.min(candidate.title.length, 180) / 180;\n if (candidate.brand) score += 1;\n if (candidate.price && candidate.price.amount > 0) score += 2;\n if (candidate.rating && candidate.rating > 0) score += 1;\n if (candidate.reviews && candidate.reviews > 0) score += 1;\n if (candidate.availability === \"in_stock\" || candidate.availability === \"limited\") score += 0.5;\n if (isPriceOnlyTitle(candidate.title)) score -= 5;\n return score;\n};\n\nconst dedupeCandidates = (candidates: ShoppingSearchCandidate[], limit: number): ShoppingSearchCandidate[] => {\n const deduped = new Map<string, ShoppingSearchCandidate>();\n for (const candidate of candidates) {\n const key = candidateUrlKey(candidate.url);\n const existing = deduped.get(key);\n if (!existing || scoreCandidate(candidate) > scoreCandidate(existing)) {\n deduped.set(key, candidate);\n }\n if (deduped.size >= limit) break;\n }\n return [...deduped.values()];\n};\n\nconst toSearchCandidatePrice = (\n price: { amount: number; currency: string },\n source: ShoppingPriceSource = \"search_card_context\"\n): ResolvedShoppingPrice => ({\n ...price,\n source,\n trustworthy: price.amount > 0\n});\n\nconst extractNeweggSearchCandidates = (\n html: string,\n baseUrl: string,\n profile: ShoppingProviderProfile,\n limit: number\n): ShoppingSearchCandidate[] => {\n const candidates: ShoppingSearchCandidate[] = [];\n for (const match of html.matchAll(NEWEGG_CARD_RE)) {\n const cardHtml = match[0];\n const titleAnchor = findAnchorByClass(cardHtml, \"item-title\");\n if (!titleAnchor?.href) continue;\n const url = normalizeCandidateUrl(titleAnchor.href, baseUrl, profile);\n if (!url || !isLikelyProductUrl(url, profile)) continue;\n\n const title = extractText(titleAnchor.innerHtml)\n || readAttribute(titleAnchor.tag, \"aria-label\")\n || readAttribute(titleAnchor.tag, \"title\");\n if (!title || GENERIC_NOISE_TITLE_RE.test(title)) continue;\n\n const priceFragment = /<li\\b[^>]*class=[\"'][^\"']*price-current[^\"']*[\"'][^>]*>([\\s\\S]*?)<\\/li>/i.exec(cardHtml)?.[1] ?? \"\";\n const ratingFragment = /aria-label=[\"']rated ([0-9.]+) out of 5[\"']/i.exec(cardHtml)?.[1]\n ?? /title=[\"']Rating \\+ ([0-9.]+)[\"']/i.exec(cardHtml)?.[1];\n const reviewsFragment = /<span\\b[^>]*class=[\"'][^\"']*item-rating-num[^\"']*[\"'][^>]*>\\(([0-9][0-9,]*)/i.exec(cardHtml)?.[1];\n const brandAnchor = findAnchorByClass(cardHtml, \"item-brand\");\n const imageAnchor = findAnchorByClass(cardHtml, \"item-img\");\n const brand = /<li>\\s*<strong>\\s*Brand:\\s*<\\/strong>\\s*([^<]+)/i.exec(cardHtml)?.[1]\n ?? readAttribute(cardHtml, \"data-brand\")\n ?? (brandAnchor ? /<img\\b[^>]*(?:alt|title)=([\"'])(.*?)\\1/i.exec(brandAnchor.innerHtml)?.[2] : undefined);\n const imageUrl = imageAnchor ? /<img\\b[^>]*src=([\"'])(.*?)\\1/i.exec(imageAnchor.innerHtml)?.[2] : undefined;\n const text = toSnippet(extractText(cardHtml), 2000);\n const price = parsePrice(priceFragment || text);\n const rating = ratingFragment ? Number(ratingFragment) : parseRating(text);\n const reviews = reviewsFragment ? Number(reviewsFragment.replace(/,/g, \"\")) : parseReviews(text);\n const availability = parseAvailability(text);\n\n candidates.push({\n url,\n title,\n text,\n ...(brand ? { brand: extractText(brand) } : {}),\n ...(imageUrl ? { imageUrl: normalizeCandidateUrl(imageUrl, baseUrl, profile) ?? imageUrl } : {}),\n ...(price.amount > 0 ? { price: toSearchCandidatePrice(price) } : {}),\n ...(Number.isFinite(rating) && rating > 0 ? { rating } : {}),\n ...(Number.isFinite(reviews) && reviews > 0 ? { reviews } : {}),\n availability\n });\n if (candidates.length >= limit) break;\n }\n return dedupeCandidates(candidates, limit);\n};\n\nconst extractEbaySearchCandidates = (\n html: string,\n baseUrl: string,\n profile: ShoppingProviderProfile,\n limit: number\n): ShoppingSearchCandidate[] => {\n const candidates: ShoppingSearchCandidate[] = [];\n for (const match of html.matchAll(EBAY_CARD_RE)) {\n const cardHtml = match[0];\n const linkAnchor = findAnchorByClass(cardHtml, \"s-card__link\");\n if (!linkAnchor?.href) continue;\n\n const url = normalizeCandidateUrl(linkAnchor.href, baseUrl, profile);\n if (!url || !isLikelyProductUrl(url, profile)) continue;\n\n const titleHtml = /<(?:div|span)\\b[^>]*class=([\"'])[^\"']*\\bs-card__title\\b[^\"']*\\1[^>]*>([\\s\\S]*?)<\\/(?:div|span)>/i.exec(cardHtml)?.[2]\n ?? linkAnchor.innerHtml;\n const title = extractText(titleHtml).replace(/\\bOpens in a new window or tab\\b/gi, \"\").trim()\n || readAttribute(linkAnchor.tag, \"aria-label\")\n || readAttribute(linkAnchor.tag, \"title\");\n if (!title || title.length < 20 || GENERIC_NOISE_TITLE_RE.test(title) || isPriceOnlyTitle(title)) continue;\n\n const text = toSnippet(extractText(cardHtml), 2000);\n const priceFragment = /<(?:div|span)\\b[^>]*class=([\"'])[^\"']*\\bs-card__price\\b[^\"']*\\1[^>]*>([\\s\\S]*?)<\\/(?:div|span)>/i.exec(cardHtml)?.[2]\n ?? text;\n const price = parsePrice(priceFragment);\n const rating = parseRating(text);\n const reviews = parseReviews(text);\n const imageUrl = /<img\\b[^>]*class=([\"'])[^\"']*\\bs-card__image\\b[^\"']*\\1[^>]*src=([\"'])(.*?)\\2/i.exec(cardHtml)?.[3]\n ?? /<img\\b[^>]*src=([\"'])(.*?)\\1/i.exec(cardHtml)?.[2];\n const availability = parseAvailability(text);\n\n candidates.push({\n url,\n title,\n text,\n ...(imageUrl ? { imageUrl: normalizeCandidateUrl(imageUrl, baseUrl, profile) ?? imageUrl } : {}),\n ...(price.amount > 0 ? { price: toSearchCandidatePrice(price) } : {}),\n ...(rating > 0 ? { rating } : {}),\n ...(reviews > 0 ? { reviews } : {}),\n availability\n });\n if (candidates.length >= limit) break;\n }\n return dedupeCandidates(candidates, limit);\n};\n\nconst extractAmazonSearchCandidates = (\n html: string,\n baseUrl: string,\n profile: ShoppingProviderProfile,\n limit: number\n): ShoppingSearchCandidate[] => {\n const candidates: ShoppingSearchCandidate[] = [];\n for (const match of html.matchAll(AMAZON_CARD_RE)) {\n const cardHtml = match[0];\n const anchor = resolveCardProductAnchor(cardHtml, baseUrl, profile);\n if (!anchor) continue;\n\n const cardText = extractText(cardHtml);\n const text = toSnippet(cardText, 2000);\n const price = resolvePrice(cardText, anchor.title);\n const rating = parseRating(cardText);\n const reviews = parseReviews(cardText);\n const imageUrl = /<img\\b[^>]*(?:data-old-hires|data-src|src)=([\\\"'])(.*?)\\1/i.exec(cardHtml)?.[2]\n ?? /<img\\b[^>]*(?:data-old-hires|data-src|src)=([^\\s>]+)/i.exec(cardHtml)?.[1];\n const availability = parseAvailability(cardText);\n\n candidates.push({\n url: anchor.url,\n title: anchor.title,\n text,\n ...(imageUrl ? { imageUrl: normalizeCandidateUrl(imageUrl, baseUrl, profile) ?? imageUrl } : {}),\n ...(price.amount > 0 ? { price } : {}),\n ...(rating > 0 ? { rating } : {}),\n ...(reviews > 0 ? { reviews } : {}),\n availability\n });\n if (candidates.length >= limit) break;\n }\n return dedupeCandidates(candidates, limit);\n};\n\nconst extractCostcoSearchCandidates = (\n html: string,\n baseUrl: string,\n profile: ShoppingProviderProfile,\n limit: number\n): ShoppingSearchCandidate[] => {\n const candidates: ShoppingSearchCandidate[] = [];\n for (const match of html.matchAll(COSTCO_CARD_RE)) {\n const cardHtml = match[0];\n const anchor = resolveCardProductAnchor(cardHtml, baseUrl, profile);\n if (!anchor) continue;\n\n const cardText = extractText(cardHtml);\n const ratingLabel = [...cardHtml.matchAll(/aria-label=([\"'])(.*?)\\1/gi)]\n .map((match) => match[2]?.trim() ?? \"\")\n .find((value) => value.includes(\"out of 5\"))\n ?? \"\";\n const ratingText = `${cardText} ${ratingLabel}`.trim();\n const text = toSnippet(cardText, 2000);\n const price = resolvePrice(cardText, anchor.title);\n const rating = parseRating(ratingText);\n const reviews = parseReviews(ratingText);\n const imageUrl = /<img\\b[^>]*src=([\"'])(.*?)\\1/i.exec(cardHtml)?.[2];\n const availability = parseAvailability(cardText);\n\n candidates.push({\n url: anchor.url,\n title: anchor.title,\n text,\n ...(imageUrl ? { imageUrl: normalizeCandidateUrl(imageUrl, baseUrl, profile) ?? imageUrl } : {}),\n ...(price.amount > 0 ? { price } : {}),\n ...(rating > 0 ? { rating } : {}),\n ...(reviews > 0 ? { reviews } : {}),\n availability\n });\n if (candidates.length >= limit) break;\n }\n return dedupeCandidates(candidates, limit);\n};\n\nconst extractGenericSearchCandidates = (\n html: string,\n baseUrl: string,\n profile: ShoppingProviderProfile,\n limit: number\n): ShoppingSearchCandidate[] => {\n const candidates: ShoppingSearchCandidate[] = [];\n for (const match of html.matchAll(ANCHOR_RE)) {\n const href = readAnchorHref(match);\n if (!href) continue;\n const url = normalizeCandidateUrl(href, baseUrl, profile);\n if (!url || !isLikelyProductUrl(url, profile)) continue;\n\n const anchorTag = readAnchorTag(match);\n const inner = readAnchorInnerHtml(match);\n const title = extractText(inner)\n || readAttribute(anchorTag, \"aria-label\")\n || readAttribute(anchorTag, \"title\");\n if (!title || title.length < 20 || GENERIC_NOISE_TITLE_RE.test(title) || isPriceOnlyTitle(title) || isRatingOnlyTitle(title)) continue;\n\n const matchIndex = match.index as number;\n const start = Math.max(0, matchIndex - 400);\n const end = Math.min(html.length, matchIndex + inner.length + 1800);\n const context = toSnippet(extractText(html.slice(start, end)), 1800);\n const price = resolvePrice(context, title);\n const rating = parseRating(context);\n const reviews = parseReviews(context);\n const imageUrl = /<img\\b[^>]*src=([\"'])(.*?)\\1/i.exec(inner)?.[2];\n const availability = parseAvailability(context);\n\n candidates.push({\n url,\n title,\n text: context,\n ...(imageUrl ? { imageUrl: normalizeCandidateUrl(imageUrl, baseUrl, profile) ?? imageUrl } : {}),\n ...(price.amount > 0 ? { price } : {}),\n ...(rating > 0 ? { rating } : {}),\n ...(reviews > 0 ? { reviews } : {}),\n availability\n });\n if (candidates.length >= limit) break;\n }\n return dedupeCandidates(candidates, limit);\n};\n\nconst extractSearchCandidates = (\n html: string,\n baseUrl: string,\n profile: ShoppingProviderProfile,\n limit: number\n): ShoppingSearchCandidate[] => {\n if (profile.name === \"amazon\") {\n const amazon = extractAmazonSearchCandidates(html, baseUrl, profile, limit);\n if (amazon.length > 0) return amazon;\n }\n if (profile.name === \"costco\") {\n const costco = extractCostcoSearchCandidates(html, baseUrl, profile, limit);\n if (costco.length > 0) return costco;\n }\n if (profile.name === \"ebay\") {\n const ebay = extractEbaySearchCandidates(html, baseUrl, profile, limit);\n if (ebay.length > 0) return ebay;\n }\n if (profile.name === \"newegg\") {\n const newegg = extractNeweggSearchCandidates(html, baseUrl, profile, limit);\n if (newegg.length > 0) return newegg;\n }\n return extractGenericSearchCandidates(html, baseUrl, profile, limit);\n};\n\nconst compactImageUrls = (values: Array<string | undefined>): string[] => {\n const seen = new Set<string>();\n const compacted: string[] = [];\n for (const value of values) {\n const candidate = typeof value === \"string\" ? value.trim() : \"\";\n if (!candidate || seen.has(candidate)) continue;\n seen.add(candidate);\n compacted.push(candidate);\n }\n return compacted;\n};\n\nconst deriveOfferAttributes = (args: {\n profile: ShoppingProviderProfile;\n url: string;\n title: string;\n text: string;\n rank: number;\n brand?: string;\n imageUrl?: string;\n imageUrls?: string[];\n price?: {\n amount: number;\n currency: string;\n };\n priceSource?: ShoppingPriceSource;\n priceIsTrustworthy?: boolean;\n rating?: number;\n reviews?: number;\n availability?: \"in_stock\" | \"limited\" | \"out_of_stock\" | \"unknown\";\n allowTextPriceFallback?: boolean;\n}): Record<string, JsonValue> => {\n const nowIso = new Date().toISOString();\n const fallbackPrice = args.allowTextPriceFallback === false ? { amount: 0, currency: DEFAULT_CURRENCY } : parsePrice(args.text);\n const price = args.price ?? fallbackPrice;\n const priceSource = price.amount > 0\n ? (args.priceSource ?? (args.price ? \"structured_metadata\" : \"search_card_context\"))\n : \"unresolved\";\n const priceIsTrustworthy = args.priceIsTrustworthy ?? Boolean(args.price);\n const rating = args.rating ?? parseRating(args.text);\n const reviews = args.reviews ?? parseReviews(args.text);\n const availability = args.availability ?? parseAvailability(args.text);\n const imageUrls = compactImageUrls([\n ...(Array.isArray(args.imageUrls) ? args.imageUrls : []),\n args.imageUrl\n ]);\n\n return {\n shopping_offer: {\n provider: args.profile.id,\n product_id: `${args.profile.id}:${args.rank}:${Buffer.from(args.url).toString(\"base64\").slice(0, 8)}`,\n title: args.title,\n url: args.url,\n price: {\n amount: price.amount,\n currency: price.currency,\n retrieved_at: nowIso\n },\n price_source: priceSource,\n price_is_trustworthy: priceIsTrustworthy,\n shipping: {\n amount: 0,\n currency: price.currency,\n notes: \"unknown\"\n },\n availability,\n rating,\n reviews_count: reviews,\n capture_timestamp: nowIso\n },\n ...(args.brand ? { brand: args.brand } : {}),\n ...(imageUrls.length > 0 ? { image_urls: imageUrls } : {}),\n extractionQuality: {\n hasUrl: args.url.length > 0,\n hasTitle: args.title.length > 0,\n hasContent: args.text.length > 0,\n contentChars: args.text.length,\n linkCount: 0\n },\n providerTier: args.profile.tier,\n extractionFocus: args.profile.extractionFocus,\n canonicalUrl: canonicalizeUrl(args.url)\n };\n};\n\nconst buildCapabilities = (profile: ShoppingProviderProfile, providerId: string): ProviderCapabilities => ({\n providerId,\n source: SHOPPING_SOURCE,\n operations: {\n search: {\n op: \"search\",\n supported: true,\n description: `Search ${profile.displayName}`\n },\n fetch: {\n op: \"fetch\",\n supported: true,\n description: `Fetch ${profile.displayName} product details`\n },\n crawl: {\n op: \"crawl\",\n supported: false,\n description: \"Shopping crawl is disabled by default\"\n },\n post: {\n op: \"post\",\n supported: false,\n description: \"Shopping posting is not supported\"\n }\n },\n policy: {\n posting: \"unsupported\",\n riskNoticeRequired: false,\n confirmationRequired: false\n },\n metadata: {\n provider: profile.displayName,\n domains: profile.domains,\n tier: profile.tier,\n extractionFocus: profile.extractionFocus,\n legalReview: {\n termsReviewDate: profile.legalReview.termsReviewDate,\n approvalExpiryDate: profile.legalReview.approvalExpiryDate,\n reviewer: profile.legalReview.reviewer,\n signedOff: profile.legalReview.signedOff\n }\n }\n});\n\nconst normalizeRows = (\n providerId: string,\n rows: ShoppingSearchRecord[]\n): NormalizedRecord[] => normalizeRecords(providerId, SHOPPING_SOURCE, rows);\n\nconst createDefaultSearch = (\n profile: ShoppingProviderProfile,\n providerId: string,\n fetcher: ShoppingFetcher\n) => async (input: ProviderSearchInput, context: ProviderContext): Promise<ShoppingSearchRecord[]> => {\n const query = input.query.trim();\n if (!query) {\n throw new ProviderRuntimeError(\"invalid_input\", `${profile.displayName} query is required`, {\n provider: providerId,\n source: SHOPPING_SOURCE,\n retryable: false\n });\n }\n\n const lookupUrl = isHttpUrl(query)\n ? query\n : profile.searchPath(query);\n const fetched = await fetcher({\n url: lookupUrl,\n signal: context.signal,\n provider: providerId,\n operation: \"search\",\n context\n });\n const extracted = extractStructuredContent(fetched.html, fetched.url);\n const providerShell = requiresBrowserAssistance(profile, fetched.url, fetched.html);\n\n const limit = Math.max(1, Math.min(input.limit ?? 10, 20));\n const links = dedupeLinks(\n extracted.links.filter((link) => isLikelyProductUrl(canonicalizeUrl(link), profile)),\n limit\n );\n const content = toSnippet(extracted.text, 2000);\n const candidates = extractSearchCandidates(fetched.html, fetched.url, profile, limit);\n const pageIssue = providerShell\n ? classifySearchPageIssue(profile, fetched, extracted, content, providerShell)\n : candidates.length === 0\n ? classifySearchPageIssue(profile, fetched, extracted, content, providerShell)\n : null;\n\n if (providerShell) {\n throwShoppingPageIssue({\n providerId,\n fetched,\n extracted,\n content,\n pageIssue: ensureProviderShellIssue(pageIssue, providerShell, content),\n providerShell\n });\n }\n\n if (candidates.length > 0) {\n return candidates.map((candidate, index) => ({\n url: candidate.url,\n title: candidate.title,\n content: candidate.text,\n confidence: Math.max(0.55, 0.88 - index * 0.04),\n attributes: {\n ...deriveOfferAttributes({\n profile,\n url: candidate.url,\n title: candidate.title,\n text: candidate.text,\n rank: index + 1,\n ...(candidate.brand ? { brand: candidate.brand } : {}),\n ...(candidate.imageUrl ? { imageUrl: candidate.imageUrl } : {}),\n ...(candidate.price ? {\n price: {\n amount: candidate.price.amount,\n currency: candidate.price.currency\n },\n priceSource: candidate.price.source,\n priceIsTrustworthy: candidate.price.trustworthy\n } : {}),\n ...(candidate.rating ? { rating: candidate.rating } : {}),\n ...(candidate.reviews ? { reviews: candidate.reviews } : {}),\n availability: candidate.availability ?? \"unknown\"\n }),\n rank: index + 1,\n retrievalPath: \"shopping:search:result-card\",\n ...browserFallbackObservationAttributes(fetched.browserFallback)\n }\n }));\n }\n\n if (pageIssue && (pageIssue.reasonCode !== \"env_limited\" || pageIssue.constraint)) {\n throwShoppingPageIssue({ providerId, fetched, extracted, content, pageIssue, providerShell });\n }\n\n const rows: ShoppingSearchRecord[] = [\n {\n url: fetched.url,\n title: `${profile.displayName} search: ${query}`,\n content,\n confidence: 0.68,\n attributes: {\n ...deriveOfferAttributes({\n profile,\n url: fetched.url,\n title: `${profile.displayName} search: ${query}`,\n text: extracted.text,\n rank: 0\n }),\n status: fetched.status,\n links,\n retrievalPath: isHttpUrl(query) ? \"shopping:search:url\" : \"shopping:search:index\",\n ...(pageIssue ? { reasonCode: pageIssue.reasonCode } : {}),\n ...(pageIssue?.blockerType ? { blockerType: pageIssue.blockerType } : {}),\n ...browserFallbackObservationAttributes(fetched.browserFallback)\n }\n }\n ];\n\n return rows.slice(0, 1);\n};\n\nconst createDefaultFetch = (\n profile: ShoppingProviderProfile,\n providerId: string,\n fetcher: ShoppingFetcher\n) => async (input: ProviderFetchInput, context: ProviderContext): Promise<ShoppingSearchRecord> => {\n const fetched = await fetcher({\n url: input.url,\n signal: context.signal,\n provider: providerId,\n operation: \"fetch\",\n context\n });\n const extracted = extractStructuredContent(fetched.html, fetched.url);\n const content = toSnippet(extracted.text, 2000);\n const providerShell = requiresBrowserAssistance(profile, fetched.url, fetched.html);\n if (providerShell) {\n const pageIssue = classifySearchPageIssue(profile, fetched, extracted, content, providerShell);\n throwShoppingPageIssue({\n providerId,\n fetched,\n extracted,\n content,\n pageIssue: ensureProviderShellIssue(pageIssue, providerShell, content),\n providerShell\n });\n }\n const title = toSnippet(extracted.text, 120) || fetched.url;\n const extractedPrice = extracted.metadata.price\n ? {\n amount: extracted.metadata.price.amount,\n currency: extracted.metadata.price.currency,\n source: \"structured_metadata\" as const,\n trustworthy: true\n }\n : resolveFetchTextPrice(extracted.text);\n\n return {\n url: fetched.url,\n title,\n content: extracted.text,\n attributes: {\n ...deriveOfferAttributes({\n profile,\n url: fetched.url,\n title,\n text: extracted.text,\n rank: 1,\n ...(extracted.metadata.brand ? { brand: extracted.metadata.brand } : {}),\n ...(extracted.metadata.imageUrls.length > 0 ? { imageUrls: extracted.metadata.imageUrls } : {}),\n ...(extractedPrice ? {\n price: {\n amount: extractedPrice.amount,\n currency: extractedPrice.currency\n },\n priceSource: extractedPrice.source,\n priceIsTrustworthy: extractedPrice.trustworthy\n } : {\n priceSource: \"unresolved\" as const,\n priceIsTrustworthy: false\n }),\n allowTextPriceFallback: false\n }),\n status: fetched.status,\n links: dedupeLinks(extracted.links, 30),\n selectors: extracted.selectors,\n retrievalPath: \"shopping:fetch:url\",\n ...browserFallbackObservationAttributes(fetched.browserFallback)\n }\n };\n};\n\nconst resolveHealth = (): ProviderHealth => ({\n status: \"healthy\",\n updatedAt: new Date().toISOString()\n});\n\nexport const createShoppingProvider = (\n profile: ShoppingProviderProfile,\n options: ShoppingProviderOptions = {}\n): ProviderAdapter => {\n const providerId = options.id ?? profile.id;\n const fetcher = options.fetcher ?? defaultFetcher;\n const search = options.search ?? createDefaultSearch(profile, providerId, fetcher);\n const fetch = options.fetch ?? createDefaultFetch(profile, providerId, fetcher);\n\n return {\n id: providerId,\n source: SHOPPING_SOURCE,\n search: async (input, context) => normalizeRows(providerId, await search(input, context)),\n fetch: async (input, context) => {\n const row = await fetch(input, context);\n return [normalizeRecord(providerId, SHOPPING_SOURCE, row)];\n },\n recoveryHints: () => buildShoppingRecoveryHints(profile),\n health: async () => resolveHealth(),\n capabilities: () => buildCapabilities(profile, providerId)\n };\n};\n\nexport const createShoppingProviders = (options: ShoppingProvidersOptions = {}): ProviderAdapter[] => {\n return SHOPPING_PROVIDER_PROFILES.map((profile) => createShoppingProvider(profile, options[profile.name]));\n};\n\nexport const createShoppingProviderById = (\n providerId: string,\n options: ShoppingProviderOptions = {}\n): ProviderAdapter => {\n const profile = SHOPPING_PROVIDER_PROFILES.find((entry) => entry.id === providerId || entry.name === providerId.replace(/^shopping\\//, \"\"));\n if (!profile) {\n throw new ProviderRuntimeError(\"invalid_input\", `Unknown shopping provider: ${providerId}`, {\n source: SHOPPING_SOURCE,\n retryable: false,\n details: {\n providerId,\n available: SHOPPING_PROVIDER_IDS\n }\n });\n }\n return createShoppingProvider(profile, options);\n};\n","import { ProviderRuntimeError } from \"../errors\";\nimport { normalizeRecord, normalizeRecords } from \"../normalize\";\nimport {\n crawlWeb,\n type CrawlBudget,\n type CrawlFetcher,\n type CrawlFetcherResponse,\n type CrawlPipelineBudget\n} from \"./crawler\";\nimport { extractStructuredContent, toSnippet } from \"./extract\";\nimport type {\n JsonValue,\n NormalizedRecord,\n ProviderAdapter,\n ProviderCapabilities,\n ProviderContext,\n ProviderCrawlInput,\n ProviderFetchInput,\n ProviderSearchInput\n} from \"../types\";\nimport type { WebCrawlPolicy } from \"./policy\";\n\nexport interface WebSearchRecord {\n url: string;\n title?: string;\n content?: string;\n confidence?: number;\n attributes?: Record<string, JsonValue>;\n}\n\nexport interface WebProviderOptions {\n id?: string;\n fetcher?: CrawlFetcher;\n searchIndex?: (input: ProviderSearchInput, context: ProviderContext) => Promise<WebSearchRecord[]>;\n defaultBudget?: Partial<CrawlBudget>;\n defaultPipeline?: Partial<CrawlPipelineBudget>;\n selectors?: string[];\n workerThreads?: number;\n queueMax?: number;\n forceInlineParse?: boolean;\n policy?: WebCrawlPolicy;\n}\n\nconst WEB_SOURCE = \"web\" as const;\n\nconst capabilities = (id: string, policy: WebCrawlPolicy | undefined): ProviderCapabilities => ({\n providerId: id,\n source: WEB_SOURCE,\n operations: {\n search: { op: \"search\", supported: true, description: \"Query web content\" },\n fetch: { op: \"fetch\", supported: true, description: \"Fetch one web document\" },\n crawl: { op: \"crawl\", supported: true, description: \"Budgeted web crawl\" },\n post: { op: \"post\", supported: false, description: \"Posting is not supported for web provider\" }\n },\n policy: {\n posting: \"unsupported\",\n riskNoticeRequired: false,\n confirmationRequired: false\n },\n metadata: {\n crawler: true,\n robotsMode: policy?.robotsMode ?? \"warn\"\n }\n});\n\nconst fetchOne = async (\n fetcher: CrawlFetcher,\n url: string,\n context?: ProviderContext\n): Promise<{ status: number; html: string }> => {\n const fetcherWithContext = fetcher as unknown as (url: string, context?: ProviderContext) => Promise<CrawlFetcherResponse>;\n const result = await fetcherWithContext(url, context);\n return {\n status: result.status ?? 200,\n html: result.html\n };\n};\n\nconst isHttpUrl = (value: string): boolean => {\n try {\n const protocol = new URL(value).protocol;\n return protocol === \"http:\" || protocol === \"https:\";\n } catch {\n return false;\n }\n};\n\nconst toQualityFlags = (value: {\n url?: string;\n title?: string;\n content?: string;\n linkCount?: number;\n}): Record<string, JsonValue> => ({\n hasUrl: typeof value.url === \"string\" && value.url.length > 0,\n hasTitle: typeof value.title === \"string\" && value.title.length > 0,\n hasContent: typeof value.content === \"string\" && value.content.length > 0,\n contentChars: value.content?.length ?? 0,\n linkCount: value.linkCount ?? 0\n});\n\nconst asPositiveInt = (value: JsonValue | undefined): number | undefined => {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return undefined;\n const normalized = Math.floor(value);\n return normalized > 0 ? normalized : undefined;\n};\n\nexport const createWebProvider = (options: WebProviderOptions = {}): ProviderAdapter => {\n const id = options.id ?? \"web/default\";\n\n const search = async (input: ProviderSearchInput, context: ProviderContext): Promise<NormalizedRecord[]> => {\n if (!input.query.trim()) {\n throw new ProviderRuntimeError(\"invalid_input\", \"Search query is required\", {\n provider: id,\n source: WEB_SOURCE,\n retryable: false\n });\n }\n\n if (options.searchIndex) {\n const rows = await options.searchIndex(input, context);\n return normalizeRecords(id, WEB_SOURCE, rows.map((row) => ({\n url: row.url,\n title: row.title,\n content: row.content,\n confidence: row.confidence,\n attributes: {\n ...(row.attributes ?? {}),\n extractionQuality: toQualityFlags({\n url: row.url,\n title: row.title,\n content: row.content\n })\n }\n })));\n }\n\n if (!options.fetcher) {\n throw new ProviderRuntimeError(\"unavailable\", \"Web search retrieval is not configured\", {\n provider: id,\n source: WEB_SOURCE\n });\n }\n\n const queryUrl = input.query.trim();\n if (!isHttpUrl(queryUrl)) {\n throw new ProviderRuntimeError(\"invalid_input\", \"Web search query must be an HTTP URL when search index is not configured\", {\n provider: id,\n source: WEB_SOURCE,\n retryable: false\n });\n }\n\n const response = await fetchOne(options.fetcher, queryUrl, context);\n const extracted = extractStructuredContent(response.html, queryUrl);\n const title = extracted.metadata.title ?? queryUrl;\n const content = extracted.metadata.description ?? toSnippet(extracted.text);\n return [normalizeRecord(id, WEB_SOURCE, {\n url: queryUrl,\n title,\n content,\n confidence: 0.4,\n attributes: {\n status: response.status,\n links: extracted.links.length,\n ...(extracted.metadata.description ? { description: extracted.metadata.description } : {}),\n ...(extracted.metadata.brand ? { brand: extracted.metadata.brand } : {}),\n ...(extracted.metadata.imageUrls.length > 0 ? { image_urls: extracted.metadata.imageUrls } : {}),\n ...(extracted.metadata.features.length > 0 ? { features: extracted.metadata.features } : {}),\n ...(extracted.metadata.price ? {\n shopping_offer: {\n provider: id,\n product_id: \"\",\n title,\n url: queryUrl,\n price: {\n amount: extracted.metadata.price.amount,\n currency: extracted.metadata.price.currency,\n retrieved_at: new Date().toISOString()\n },\n shipping: {\n amount: 0,\n currency: extracted.metadata.price.currency,\n notes: \"unknown\"\n },\n availability: \"unknown\",\n rating: 0,\n reviews_count: 0,\n capture_timestamp: new Date().toISOString(),\n metadata_source: extracted.metadata.price.source\n }\n } : {}),\n extractionQuality: toQualityFlags({\n url: queryUrl,\n title,\n content,\n linkCount: extracted.links.length\n })\n }\n })];\n };\n\n const fetch = async (input: ProviderFetchInput, context: ProviderContext): Promise<NormalizedRecord[]> => {\n if (!options.fetcher) {\n throw new ProviderRuntimeError(\"unavailable\", \"Web fetcher is not configured\", {\n provider: id,\n source: WEB_SOURCE\n });\n }\n\n const response = await fetchOne(options.fetcher, input.url, context);\n const extracted = extractStructuredContent(response.html, input.url);\n const title = extracted.metadata.title ?? input.url;\n const content = extracted.metadata.description ?? extracted.text;\n const retrievedAt = new Date().toISOString();\n\n return [normalizeRecord(id, WEB_SOURCE, {\n url: input.url,\n title,\n content,\n confidence: 0.6,\n attributes: {\n status: response.status,\n links: extracted.links,\n selectors: extracted.selectors,\n ...(extracted.metadata.description ? { description: extracted.metadata.description } : {}),\n ...(extracted.metadata.brand ? { brand: extracted.metadata.brand } : {}),\n ...(extracted.metadata.siteName ? { site_name: extracted.metadata.siteName } : {}),\n ...(extracted.metadata.imageUrls.length > 0 ? { image_urls: extracted.metadata.imageUrls } : {}),\n ...(extracted.metadata.features.length > 0 ? { features: extracted.metadata.features } : {}),\n ...(extracted.metadata.price ? {\n shopping_offer: {\n provider: id,\n product_id: \"\",\n title,\n url: input.url,\n price: {\n amount: extracted.metadata.price.amount,\n currency: extracted.metadata.price.currency,\n retrieved_at: retrievedAt\n },\n shipping: {\n amount: 0,\n currency: extracted.metadata.price.currency,\n notes: \"unknown\"\n },\n availability: \"unknown\",\n rating: 0,\n reviews_count: 0,\n capture_timestamp: retrievedAt,\n metadata_source: extracted.metadata.price.source\n }\n } : {}),\n extractionQuality: toQualityFlags({\n url: input.url,\n title,\n content,\n linkCount: extracted.links.length\n })\n }\n })];\n };\n\n const crawl = async (input: ProviderCrawlInput): Promise<NormalizedRecord[]> => {\n if (!options.fetcher) {\n throw new ProviderRuntimeError(\"unavailable\", \"Web crawler fetcher is not configured\", {\n provider: id,\n source: WEB_SOURCE\n });\n }\n\n if (input.seedUrls.length === 0) {\n throw new ProviderRuntimeError(\"invalid_input\", \"At least one crawl seed URL is required\", {\n provider: id,\n source: WEB_SOURCE,\n retryable: false\n });\n }\n\n const adaptiveFetchConcurrency = asPositiveInt(input.filters?.fetchConcurrency);\n const adaptiveFrontierMax = asPositiveInt(input.filters?.frontierMax);\n\n const crawlResult = await crawlWeb({\n fetcher: options.fetcher,\n strategy: input.strategy,\n policy: options.policy,\n selectors: options.selectors,\n seeds: input.seedUrls,\n budget: {\n ...options.defaultBudget,\n maxDepth: input.maxDepth ?? options.defaultBudget?.maxDepth,\n maxPages: input.maxPages ?? options.defaultBudget?.maxPages,\n maxPerDomain: input.maxPerDomain ?? options.defaultBudget?.maxPerDomain\n },\n pipeline: {\n ...(options.defaultPipeline ?? {}),\n ...(adaptiveFetchConcurrency !== undefined ? { fetchConcurrency: adaptiveFetchConcurrency } : {}),\n ...(adaptiveFrontierMax !== undefined ? { frontierMax: adaptiveFrontierMax } : {}),\n ...(typeof options.workerThreads === \"number\" ? { workerThreads: options.workerThreads } : {}),\n ...(typeof options.queueMax === \"number\" ? { queueMax: options.queueMax } : {})\n },\n workerThreads: options.workerThreads,\n queueMax: options.queueMax,\n forceInlineParse: options.forceInlineParse\n });\n\n return crawlResult.pages.map((page) => normalizeRecord(id, WEB_SOURCE, {\n url: page.url,\n title: page.url,\n content: page.text,\n confidence: 0.7,\n attributes: {\n depth: page.depth,\n status: page.status,\n links: page.links,\n warnings: page.warnings,\n crawlWarnings: crawlResult.warnings,\n crawlMetrics: {\n visited: crawlResult.metrics.visited,\n fetched: crawlResult.metrics.fetched,\n deduped: crawlResult.metrics.deduped,\n elapsedMs: crawlResult.metrics.elapsedMs,\n pagesPerMinute: crawlResult.metrics.pagesPerMinute,\n p50LatencyMs: crawlResult.metrics.p50LatencyMs,\n p95LatencyMs: crawlResult.metrics.p95LatencyMs\n },\n extractionQuality: toQualityFlags({\n url: page.url,\n title: page.url,\n content: page.text,\n linkCount: page.links.length\n })\n }\n }));\n };\n\n return {\n id,\n source: WEB_SOURCE,\n search,\n fetch,\n crawl,\n health: async () => ({\n status: options.fetcher ? \"healthy\" : \"degraded\",\n updatedAt: new Date().toISOString(),\n ...(options.fetcher ? {} : { reason: \"Fetcher not configured\" })\n }),\n capabilities: () => capabilities(id, options.policy)\n };\n};\n","const resolveWorkerCount = (itemCount: number, limit: number): number => {\n if (itemCount <= 0) return 0;\n const finiteLimit = Number.isFinite(limit) ? Math.floor(limit) : 1;\n return Math.min(Math.max(1, finiteLimit), itemCount);\n};\n\nexport const mapBounded = async <Input, Output>(\n items: readonly Input[],\n limit: number,\n task: (item: Input, index: number) => Promise<Output>\n): Promise<Output[]> => {\n const results: Output[] = new Array<Output>(items.length);\n let cursor = 0;\n let firstError: Error | null = null;\n const workers = Array.from({ length: resolveWorkerCount(items.length, limit) }, async () => {\n for (;;) {\n if (firstError) return;\n const index = cursor;\n cursor += 1;\n if (index >= items.length) return;\n try {\n results[index] = await task(items[index] as Input, index);\n } catch (error) {\n if (!firstError) {\n firstError = error instanceof Error ? error : new Error(String(error));\n }\n return;\n }\n }\n });\n await Promise.all(workers);\n if (firstError) throw firstError;\n return results;\n};\n","import type { JsonValue } from \"./types\";\n\nexport type WorkflowKind = \"research\" | \"shopping\" | \"product_video\" | \"inspiredesign\";\nexport type WorkflowStage = \"compile\" | \"execute\" | \"postprocess\" | \"resume\";\n\nexport type WorkflowStepBudget = {\n maxAttempts?: number;\n maxResults?: number;\n timeoutMs?: number;\n};\n\nexport type WorkflowStepPolicy = {\n sources?: string[];\n providers?: string[];\n};\n\nexport type WorkflowPlanStep = {\n id: string;\n kind: string;\n budget?: WorkflowStepBudget;\n policy?: WorkflowStepPolicy;\n input?: Record<string, JsonValue>;\n};\n\nexport type WorkflowPlan = {\n kind: WorkflowKind;\n steps: WorkflowPlanStep[];\n meta?: Record<string, JsonValue>;\n};\n\nexport type WorkflowCheckpoint = {\n stage: WorkflowStage;\n stepId?: string;\n stepIndex?: number;\n state?: Record<string, JsonValue>;\n updatedAt?: string;\n};\n\nexport type WorkflowTraceEntry = {\n at: string;\n stage: WorkflowStage;\n event: string;\n details?: Record<string, JsonValue>;\n};\n\nexport type WorkflowResumeEnvelope = {\n kind: WorkflowKind;\n input: Record<string, JsonValue>;\n checkpoint?: WorkflowCheckpoint | null;\n trace?: WorkflowTraceEntry[];\n};\n\nconst isJsonRecord = (value: JsonValue | undefined): value is Record<string, JsonValue> => (\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n);\n\nconst isWorkflowStage = (value: JsonValue | undefined): value is WorkflowStage => (\n value === \"compile\" || value === \"execute\" || value === \"postprocess\" || value === \"resume\"\n);\n\nconst isWorkflowCheckpoint = (value: JsonValue | undefined): value is WorkflowCheckpoint => (\n isJsonRecord(value)\n && isWorkflowStage(value.stage)\n && (value.stepId === undefined || typeof value.stepId === \"string\")\n && (value.stepIndex === undefined || typeof value.stepIndex === \"number\")\n && (value.state === undefined || isJsonRecord(value.state))\n && (value.updatedAt === undefined || typeof value.updatedAt === \"string\")\n);\n\nconst isWorkflowTraceEntry = (value: JsonValue | undefined): value is WorkflowTraceEntry => (\n isJsonRecord(value)\n && typeof value.at === \"string\"\n && isWorkflowStage(value.stage)\n && typeof value.event === \"string\"\n && (value.details === undefined || isJsonRecord(value.details))\n);\n\nexport const isWorkflowKind = (value: JsonValue | undefined): value is WorkflowKind => (\n value === \"research\" || value === \"shopping\" || value === \"product_video\" || value === \"inspiredesign\"\n);\n\nexport const buildWorkflowResumeEnvelope = (\n kind: WorkflowKind,\n input: JsonValue,\n options: {\n checkpoint?: WorkflowCheckpoint | null;\n trace?: WorkflowTraceEntry[];\n } = {}\n): WorkflowResumeEnvelope => ({\n kind,\n input: input as Record<string, JsonValue>,\n ...(options.checkpoint !== undefined ? { checkpoint: options.checkpoint } : {}),\n ...(options.trace !== undefined ? { trace: options.trace } : {})\n});\n\nexport const isWorkflowResumeEnvelope = (value: JsonValue | undefined): value is WorkflowResumeEnvelope => (\n isJsonRecord(value)\n && isWorkflowKind(value.kind)\n && isJsonRecord(value.input)\n && (value.checkpoint === undefined || value.checkpoint === null || isWorkflowCheckpoint(value.checkpoint))\n && (\n value.trace === undefined\n || (\n Array.isArray(value.trace)\n && value.trace.every((entry) => isWorkflowTraceEntry(entry as JsonValue))\n )\n )\n);\n\nexport const isWorkflowResumePayload = (\n value: JsonValue | undefined\n): value is { workflow: WorkflowResumeEnvelope } => (\n isJsonRecord(value) && isWorkflowResumeEnvelope(value.workflow)\n);\n","import { createHash } from \"crypto\";\nimport { mkdtemp, readFile, rm } from \"fs/promises\";\nimport { tmpdir } from \"os\";\nimport { join, resolve } from \"path\";\nimport { createArtifactBundle, type ArtifactFile } from \"./artifacts\";\nimport { resolveWorkflowArtifactRoot } from \"./workflow-output-root\";\nimport {\n readProviderIssueHintFromRecord,\n summarizePrimaryProviderIssue,\n type ProviderIssueHint,\n type ProviderNextStepGuidance\n} from \"./constraint\";\nimport { enrichResearchRecords, type ResearchRecord } from \"./enrichment\";\nimport {\n renderInspiredesign,\n renderResearch,\n renderShopping,\n type RenderMode,\n type ShoppingOffer\n} from \"./renderer\";\nimport {\n buildInspiredesignPacket,\n formatInspiredesignCaptureAttemptSummary,\n hasInspiredesignCaptureArtifacts,\n INSPIREDESIGN_CAPTURE_ATTEMPT_KEYS,\n type InspiredesignCaptureAttemptKey,\n type InspiredesignCaptureAttemptStatus,\n type InspiredesignCaptureEvidence,\n type InspiredesignFollowthrough,\n normalizeInspiredesignCaptureEvidence,\n type InspiredesignReferenceEvidence\n} from \"../inspiredesign/contract\";\nimport {\n buildInspiredesignRankedArtifactPatternBoard,\n hasInspiredesignUsableReferenceEvidence,\n summarizeInspiredesignReferenceQuality,\n type InspiredesignReferencePatternBoard\n} from \"../inspiredesign/reference-pattern-board\";\nimport {\n createInspiredesignGuidanceContext,\n renderWorkflowCompatibility,\n routeNextStepGuidance,\n type InspiredesignGuidanceSource,\n type NextStepGuidance,\n type SiteRecipe\n} from \"../guidance\";\nimport {\n isNonCanonicalPinterestLikeUrl,\n requiresProviderUrlSiteRecipeCompatibility,\n validateProviderScopedUrlCanonicality,\n validateProviderUrlSiteRecipeCompatibility\n} from \"../guidance/recipes/site-recipe-validation\";\nimport { resolveSiteRecipeForProvider, resolveSiteRecipeForUrl } from \"../guidance/recipes/site-registry\";\nimport {\n mergeInspiredesignReferenceUrls,\n normalizeInspiredesignDiscoveryRecords,\n normalizeInspiredesignProviders,\n type InspiredesignDiscoveryResult\n} from \"../inspiredesign/reference-discovery\";\nimport {\n buildVisualEvidenceArtifactPath,\n hashVisualEvidenceBuffer,\n isInspiredesignVisualEvidenceKind,\n isInspiredesignVisualEvidenceMode,\n persistInspiredesignVisualEvidence,\n type InspiredesignPersistedVisualEvidence,\n type InspiredesignVisualEvidenceRuntimeMetadata,\n type InspiredesignVisualEvidenceMode\n} from \"../inspiredesign/visual-evidence\";\nimport {\n decideInspiredesignVisualCapturePolicy,\n type InspiredesignVisualPolicyDecision\n} from \"../inspiredesign/visual-policy\";\nimport {\n normalizeInspiredesignBriefText,\n expandInspiredesignBrief,\n INSPIREDESIGN_BRIEF_TEMPLATE_VERSION,\n type InspiredesignBriefExpansion,\n type InspiredesignBriefFormat\n} from \"../inspiredesign/brief-expansion\";\nimport {\n CANVAS_NAVIGATION_MODELS,\n CANVAS_THEME_STRATEGIES,\n CANVAS_VISUAL_DIRECTION_PROFILES\n} from \"../canvas/types\";\nimport {\n buildProductVideoSuccessHandoff,\n buildResearchSuccessHandoff,\n buildShoppingSuccessHandoff,\n type WorkflowSuccessHandoff\n} from \"./workflow-handoff\";\nimport type { InspiredesignCaptureOptions } from \"../inspiredesign/capture\";\nimport {\n LOOKS_LIKE_URL_RE,\n asNumber,\n extractBrandFromTitle,\n extractShoppingOffer,\n inferBrandFromUrl,\n isLikelyOfferRecord,\n normalizePlainText,\n parsePriceFromContent,\n sanitizeFeatureList,\n stripBrandSuffix,\n trimProductCopy,\n postprocessShoppingWorkflow,\n type ShoppingOfferFilterDiagnostic\n} from \"./shopping-postprocess\";\nimport { enforceShoppingLegalReviewGate } from \"./shopping-workflow\";\nimport { compileShoppingExecutionPlan, type ShoppingWorkflowExecutionStep } from \"./shopping-compiler\";\nimport { executeShoppingWorkflowPlan } from \"./shopping-executor\";\nimport {\n PRODUCT_VIDEO_STEP_IDS,\n compileProductVideoExecutionPlan,\n serializeProductVideoCheckpointState,\n type ProductVideoWorkflowCheckpointState,\n type ProductVideoWorkflowExecutionStep\n} from \"./product-video-compiler\";\nimport { filterByTimebox } from \"./timebox\";\nimport {\n SHOPPING_PROVIDER_IDS,\n SHOPPING_PROVIDER_PROFILES\n} from \"./shopping\";\nimport { createLogger, redactSensitive } from \"../core/logging\";\nimport { normalizeProviderReasonCode } from \"./errors\";\nimport {\n isChallengeAutomationMode,\n type ChallengeAutomationMode\n} from \"../challenges/types\";\nimport { providerRequestHeaders } from \"./shared/request-headers\";\nimport {\n classifyResearchDestinationRejection,\n isLikelyResearchDestinationUrl\n} from \"./shared/traversal-url\";\nimport { canonicalizeUrl } from \"./web/crawler\";\nimport { extractStructuredContent, toSnippet } from \"./web/extract\";\nimport type { ProviderAntiBotSnapshot } from \"./registry\";\nimport { compileResearchExecutionPlan, type ResearchWorkflowExecutionStep } from \"./research-compiler\";\nimport { executeResearchWorkflowPlan } from \"./research-executor\";\nimport {\n buildWorkflowResumeEnvelope,\n isWorkflowResumeEnvelope,\n type WorkflowCheckpoint,\n type WorkflowKind,\n type WorkflowResumeEnvelope,\n type WorkflowTraceEntry\n} from \"./workflow-contracts\";\nimport { resolveInspiredesignCaptureMode } from \"../inspiredesign/capture-mode\";\nimport { runBrowserNativeDiscovery, type BrowserNativeDiscoveryResult } from \"./browser-native-discovery\";\nimport type {\n BrowserFallbackMode,\n JsonValue,\n NormalizedRecord,\n ProviderAggregateResult,\n ProviderCallResultByOperation,\n ProviderCookiePolicy,\n ProviderError,\n ProviderFailureEntry,\n ProviderReasonCode,\n ProviderRunOptions,\n ProviderRuntimePolicyInput,\n ProviderSelection,\n ProviderSource,\n WorkflowSuspendedIntentKind,\n WorkflowBrowserMode,\n InspiredesignCaptureMode\n} from \"./types\";\n\nexport interface ReferenceRetrievalPort {\n fetch: (\n input: ProviderCallResultByOperation[\"fetch\"],\n options?: ProviderRunOptions\n ) => Promise<ProviderAggregateResult>;\n search?: (\n input: ProviderCallResultByOperation[\"search\"],\n options?: ProviderRunOptions\n ) => Promise<ProviderAggregateResult>;\n getAntiBotSnapshots?: (providerIds?: string[]) => ProviderAntiBotSnapshot[];\n}\n\nexport interface ProviderExecutor extends ReferenceRetrievalPort {\n search: (\n input: ProviderCallResultByOperation[\"search\"],\n options?: ProviderRunOptions\n ) => Promise<ProviderAggregateResult>;\n}\n\nexport interface ResearchRunInput {\n topic: string;\n days?: number;\n from?: string;\n to?: string;\n sourceSelection?: ProviderSelection;\n sources?: ProviderSource[];\n mode?: RenderMode;\n includeEngagement?: boolean;\n limitPerSource?: number;\n timeoutMs?: number;\n outputDir?: string;\n ttlHours?: number;\n browserMode?: WorkflowBrowserMode;\n useCookies?: boolean;\n challengeAutomationMode?: ChallengeAutomationMode;\n cookiePolicyOverride?: ProviderCookiePolicy;\n}\n\nexport interface ShoppingRunInput {\n query: string;\n providers?: string[];\n budget?: number;\n region?: string;\n browserMode?: WorkflowBrowserMode;\n sort?: \"best_deal\" | \"lowest_price\" | \"highest_rating\" | \"fastest_shipping\";\n mode: RenderMode;\n timeoutMs?: number;\n outputDir?: string;\n ttlHours?: number;\n useCookies?: boolean;\n challengeAutomationMode?: ChallengeAutomationMode;\n cookiePolicyOverride?: ProviderCookiePolicy;\n}\n\nexport interface InspiredesignRunInput {\n brief: string;\n briefExpansion?: InspiredesignBriefExpansion;\n harvest?: boolean;\n query?: string;\n providers?: string[];\n maxReferences?: number;\n visualEvidence?: InspiredesignVisualEvidenceMode;\n urls?: string[];\n captureMode?: InspiredesignCaptureMode;\n includePrototypeGuidance?: boolean;\n mode?: RenderMode;\n timeoutMs?: number;\n outputDir?: string;\n ttlHours?: number;\n browserMode?: WorkflowBrowserMode;\n useCookies?: boolean;\n challengeAutomationMode?: ChallengeAutomationMode;\n cookiePolicyOverride?: ProviderCookiePolicy;\n}\n\nexport interface ProductVideoRunInput {\n product_url?: string;\n product_name?: string;\n provider_hint?: string;\n include_screenshots?: boolean;\n include_all_images?: boolean;\n include_copy?: boolean;\n output_dir?: string;\n ttl_hours?: number;\n timeoutMs?: number;\n browserMode?: WorkflowBrowserMode;\n useCookies?: boolean;\n challengeAutomationMode?: ChallengeAutomationMode;\n cookiePolicyOverride?: ProviderCookiePolicy;\n}\n\nexport interface ProductVideoWorkflowOptions {\n captureScreenshot?: (url: string, timeoutMs?: number) => Promise<Buffer | null>;\n}\n\nexport interface InspiredesignWorkflowOptions {\n captureReference?: (\n url: string,\n options?: InspiredesignCaptureOptions\n ) => Promise<InspiredesignCaptureEvidence | null>;\n}\n\ntype ProviderSignal = \"ok\" | \"anti_bot_challenge\" | \"rate_limited\" | \"transcript_unavailable\";\ntype TrackedSignal = Exclude<ProviderSignal, \"ok\">;\ntype AlertState = \"none\" | \"warning\" | \"degraded\";\n\ntype ProviderSignalState = {\n entries: ProviderSignal[];\n previousWindowRates: Record<TrackedSignal, number>;\n signalState: Record<TrackedSignal, AlertState>;\n healthyWindows: Record<TrackedSignal, number>;\n};\n\nconst SIGNAL_WINDOW = 50;\nconst RECOVERY_WINDOWS_REQUIRED = 2;\nconst providerSignalMap = new Map<string, ProviderSignalState>();\nconst workflowLogger = createLogger(\"provider-workflows\");\n\nconst withFollowthroughMeta = (\n meta: Record<string, unknown>,\n handoff: WorkflowSuccessHandoff\n): Record<string, unknown> => ({\n ...meta,\n followthroughSummary: handoff.followthroughSummary\n});\n\nconst detectSignal = (error: ProviderError): ProviderSignal | null => {\n const reasonCode = error.reasonCode\n ?? normalizeProviderReasonCode({\n code: error.code,\n message: error.message,\n details: error.details\n });\n if (reasonCode === \"rate_limited\") return \"rate_limited\";\n if (reasonCode === \"challenge_detected\" || /captcha|challenge|anti.?bot|cf_chl/i.test(error.message)) {\n return \"anti_bot_challenge\";\n }\n if (reasonCode === \"transcript_unavailable\" || reasonCode === \"caption_missing\") {\n return \"transcript_unavailable\";\n }\n return null;\n};\n\nconst trackProviderSignals = (result: ProviderAggregateResult): void => {\n const failureByProvider = new Map<string, ProviderFailureEntry>();\n for (const failure of result.failures) {\n failureByProvider.set(failure.provider, failure);\n }\n\n for (const providerId of result.providerOrder) {\n const failure = failureByProvider.get(providerId);\n const signal = failure ? detectSignal(failure.error) ?? \"ok\" : \"ok\";\n const state = providerSignalMap.get(providerId) ?? {\n entries: [],\n previousWindowRates: {\n anti_bot_challenge: 0,\n rate_limited: 0,\n transcript_unavailable: 0\n },\n signalState: {\n anti_bot_challenge: \"none\",\n rate_limited: \"none\",\n transcript_unavailable: \"none\"\n },\n healthyWindows: {\n anti_bot_challenge: 0,\n rate_limited: 0,\n transcript_unavailable: 0\n }\n };\n state.entries.push(signal);\n if (state.entries.length > SIGNAL_WINDOW) {\n state.entries.splice(0, state.entries.length - SIGNAL_WINDOW);\n }\n providerSignalMap.set(providerId, state);\n }\n};\n\nconst isStagedAutoExclusionCandidate = (providerId: string): boolean => {\n return providerId === \"social/youtube\" || providerId.startsWith(\"shopping/\");\n};\n\nconst nextSignalState = (\n previous: AlertState,\n warning: boolean,\n degraded: boolean,\n healthyWindows: number\n): { state: AlertState; healthyWindows: number } => {\n if (degraded) {\n return { state: \"degraded\", healthyWindows: 0 };\n }\n if (warning) {\n return { state: \"warning\", healthyWindows: 0 };\n }\n\n const nextHealthyWindows = healthyWindows + 1;\n if (previous === \"degraded\" && nextHealthyWindows < RECOVERY_WINDOWS_REQUIRED) {\n return { state: \"degraded\", healthyWindows: nextHealthyWindows };\n }\n return { state: \"none\", healthyWindows: nextHealthyWindows };\n};\n\nconst buildAlerts = (): Array<Record<string, JsonValue>> => {\n const alerts: Array<Record<string, JsonValue>> = [];\n\n for (const [provider, state] of providerSignalMap.entries()) {\n const total = state.entries.length;\n if (total === 0) continue;\n\n for (const signal of [\"anti_bot_challenge\", \"rate_limited\", \"transcript_unavailable\"] as const) {\n const signalCount = state.entries.filter((entry) => entry === signal).length;\n const ratio = signalCount / total;\n\n let consecutive = 0;\n for (let index = state.entries.length - 1; index >= 0; index -= 1) {\n if (state.entries[index] !== signal) break;\n consecutive += 1;\n }\n\n const warning = ratio >= 0.15 || consecutive >= 3;\n const degraded = ratio >= 0.25 && state.previousWindowRates[signal] >= 0.25;\n state.previousWindowRates[signal] = ratio;\n\n const previousState = state.signalState[signal];\n const nextState = nextSignalState(previousState, warning, degraded, state.healthyWindows[signal]);\n state.signalState[signal] = nextState.state;\n state.healthyWindows[signal] = nextState.healthyWindows;\n\n if (\n (nextState.state === \"warning\" || nextState.state === \"degraded\")\n && nextState.state !== previousState\n ) {\n const transitionReason = degraded\n ? \"signal ratio >= 25% for two consecutive windows\"\n : consecutive >= 3\n ? \"3 consecutive events detected\"\n : \"signal ratio >= 15%\";\n workflowLogger.warn(\"provider.signal.transition\", {\n data: {\n provider,\n signal,\n previous_state: previousState,\n next_state: nextState.state,\n window_total: total,\n signal_count: signalCount,\n ratio: Number(ratio.toFixed(4)),\n consecutive,\n reason: transitionReason\n }\n });\n }\n\n if (nextState.state === \"none\") continue;\n\n alerts.push({\n provider,\n signal,\n reasonCode: signal === \"anti_bot_challenge\"\n ? \"challenge_detected\"\n : signal === \"rate_limited\"\n ? \"rate_limited\"\n : \"transcript_unavailable\",\n state: nextState.state,\n window_total: total,\n signal_count: signalCount,\n ratio: Number(ratio.toFixed(4)),\n consecutive,\n reason: nextState.state === \"degraded\" && !degraded\n ? `waiting for ${RECOVERY_WINDOWS_REQUIRED} healthy windows before recovery`\n : degraded\n ? \"signal ratio >= 25% for two consecutive windows\"\n : consecutive >= 3\n ? \"3 consecutive events detected\"\n : \"signal ratio >= 15%\"\n });\n }\n }\n\n return alerts;\n};\n\nconst getRuntimeAntiBotSnapshots = (\n runtime: ReferenceRetrievalPort,\n providerIds?: string[]\n): ProviderAntiBotSnapshot[] => {\n if (typeof runtime.getAntiBotSnapshots !== \"function\") {\n return [];\n }\n return runtime.getAntiBotSnapshots(providerIds);\n};\n\nconst buildRuntimePressureAlerts = (\n snapshots: ProviderAntiBotSnapshot[]\n): Array<Record<string, JsonValue>> => {\n const nowMs = Date.now();\n const alerts: Array<Record<string, JsonValue>> = [];\n\n for (const snapshot of snapshots) {\n if (snapshot.activeChallenges > 0 || snapshot.recentChallengeRatio >= 0.15) {\n const degraded = snapshot.activeChallenges > 0 || snapshot.recentChallengeRatio >= 0.25;\n alerts.push({\n provider: snapshot.providerId,\n signal: \"anti_bot_challenge\",\n reasonCode: \"challenge_detected\",\n state: degraded ? \"degraded\" : \"warning\",\n ratio: Number(snapshot.recentChallengeRatio.toFixed(4)),\n reason: snapshot.activeChallenges > 0\n ? \"preserved challenge session is still active\"\n : degraded\n ? \"signal ratio >= 25%\"\n : \"signal ratio >= 15%\"\n });\n }\n\n if (snapshot.cooldownUntilMs > nowMs || snapshot.recentRateLimitRatio >= 0.15) {\n const degraded = snapshot.cooldownUntilMs > nowMs || snapshot.recentRateLimitRatio >= 0.25;\n alerts.push({\n provider: snapshot.providerId,\n signal: \"rate_limited\",\n reasonCode: \"rate_limited\",\n state: degraded ? \"degraded\" : \"warning\",\n ratio: Number(snapshot.recentRateLimitRatio.toFixed(4)),\n reason: snapshot.cooldownUntilMs > nowMs\n ? \"cooldown active\"\n : degraded\n ? \"signal ratio >= 25%\"\n : \"signal ratio >= 15%\"\n });\n }\n }\n\n return alerts;\n};\n\nconst buildTranscriptAlertsFromFailures = (\n failures: ProviderFailureEntry[]\n): Array<Record<string, JsonValue>> => {\n const seen = new Set<string>();\n const alerts: Array<Record<string, JsonValue>> = [];\n\n for (const failure of failures) {\n const signal = detectSignal(failure.error);\n if (signal !== \"transcript_unavailable\") {\n continue;\n }\n const key = `${failure.provider}:${signal}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n alerts.push({\n provider: failure.provider,\n signal,\n reasonCode: \"transcript_unavailable\",\n state: \"warning\",\n reason: \"transcript retrieval remains unavailable in the current run\"\n });\n }\n\n return alerts;\n};\n\nconst buildWorkflowAlerts = (\n runtime: ReferenceRetrievalPort,\n failures: ProviderFailureEntry[],\n providerIds?: string[]\n): Array<Record<string, JsonValue>> => {\n const snapshots = getRuntimeAntiBotSnapshots(runtime, providerIds);\n if (snapshots.length === 0) {\n return buildAlerts();\n }\n return [\n ...buildRuntimePressureAlerts(snapshots),\n ...buildTranscriptAlertsFromFailures(failures)\n ];\n};\n\nconst getDegradedProviders = (): Set<string> => {\n const degradedProviders = new Set<string>();\n for (const [provider, state] of providerSignalMap.entries()) {\n if (!isStagedAutoExclusionCandidate(provider)) continue;\n if (state.signalState.anti_bot_challenge === \"degraded\" || state.signalState.rate_limited === \"degraded\") {\n degradedProviders.add(provider);\n }\n }\n return degradedProviders;\n};\n\nconst getRuntimeDegradedProviders = (\n runtime: ReferenceRetrievalPort,\n providerIds?: string[]\n): Set<string> => {\n const snapshots = getRuntimeAntiBotSnapshots(runtime, providerIds);\n if (snapshots.length === 0) {\n return getDegradedProviders();\n }\n const degradedProviders = new Set<string>();\n for (const alert of buildRuntimePressureAlerts(snapshots)) {\n if (alert.state !== \"degraded\") continue;\n if (typeof alert.provider === \"string\" && isStagedAutoExclusionCandidate(alert.provider)) {\n degradedProviders.add(alert.provider);\n }\n }\n return degradedProviders;\n};\n\nconst toProviderSource = (providerId: string): ProviderSource | null => {\n if (providerId.startsWith(\"web/\")) return \"web\";\n if (providerId.startsWith(\"community/\")) return \"community\";\n if (providerId.startsWith(\"social/\")) return \"social\";\n if (providerId.startsWith(\"shopping/\")) return \"shopping\";\n return null;\n};\n\nconst observeWorkflowSignals = (\n runtime: ReferenceRetrievalPort,\n result: ProviderAggregateResult\n): void => {\n if (typeof runtime.getAntiBotSnapshots === \"function\") {\n return;\n }\n trackProviderSignals(result);\n};\n\nconst removeExcludedProviders = <T extends { provider: string }>(\n items: T[],\n excludedProviders: Set<string>\n): T[] => {\n if (excludedProviders.size === 0) return items;\n return items.filter((item) => !excludedProviders.has(item.provider));\n};\n\nconst redactRawCapture = (record: Record<string, unknown>): Record<string, unknown> => {\n const redacted = redactSensitive(record);\n if (!redacted || typeof redacted !== \"object\" || Array.isArray(redacted)) {\n return {};\n }\n return redacted as Record<string, unknown>;\n};\n\nconst withExcludedProviders = (\n selection: { source_selection: ProviderSelection; resolved_sources: ProviderSource[] },\n excludedProviders: string[]\n): { source_selection: ProviderSelection; resolved_sources: ProviderSource[]; excluded_providers?: string[] } => {\n if (excludedProviders.length === 0) return selection;\n return {\n ...selection,\n excluded_providers: excludedProviders\n };\n};\n\nconst withPrimaryConstraintMeta = (\n meta: Record<string, unknown>,\n failures: ProviderFailureEntry[]\n): Record<string, unknown> => {\n const primaryIssue = summarizePrimaryProviderIssue(failures);\n return primaryIssue\n ? {\n ...meta,\n primaryConstraint: primaryIssue,\n primaryConstraintSummary: primaryIssue.summary\n }\n : meta;\n};\n\nconst withCamelCasePrimaryConstraintMeta = withPrimaryConstraintMeta;\n\nconst readPrimaryConstraintGuidance = (\n constraint: Record<string, unknown>\n): ProviderNextStepGuidance | undefined => {\n const guidance = constraint.guidance;\n if (!guidance || typeof guidance !== \"object\" || Array.isArray(guidance)) return undefined;\n const record = guidance as Record<string, unknown>;\n if (typeof record.reason !== \"string\") return undefined;\n if (!Array.isArray(record.recommendedNextCommands)) return undefined;\n if (!record.recommendedNextCommands.every((command) => typeof command === \"string\")) return undefined;\n return {\n reason: record.reason,\n recommendedNextCommands: record.recommendedNextCommands\n };\n};\n\nconst withPrimaryConstraintSummaryOverride = (\n meta: Record<string, unknown>,\n summary: string,\n guidance?: ProviderNextStepGuidance\n): Record<string, unknown> => {\n const currentPrimaryConstraint = meta.primaryConstraint;\n const baseConstraint = (\n currentPrimaryConstraint\n && typeof currentPrimaryConstraint === \"object\"\n && !Array.isArray(currentPrimaryConstraint)\n )\n ? currentPrimaryConstraint as Record<string, unknown>\n : { reasonCode: \"env_limited\" };\n const existingGuidance = readPrimaryConstraintGuidance(baseConstraint);\n const { guidance: _existingGuidance, ...nextPrimaryConstraintBase } = baseConstraint;\n const nextGuidance = guidance ?? existingGuidance;\n const nextPrimaryConstraint = (\n nextGuidance\n ? {\n ...nextPrimaryConstraintBase,\n summary,\n guidance: nextGuidance\n }\n : {\n ...nextPrimaryConstraintBase,\n summary\n }\n );\n\n return {\n ...meta,\n primaryConstraint: nextPrimaryConstraint,\n primaryConstraintSummary: summary\n };\n};\n\nconst withReasonCodeDistributionMeta = (\n meta: Record<string, unknown>,\n reasonCodeDistribution: Record<string, number>\n): Record<string, unknown> => {\n const metrics = meta.metrics;\n const nextMetrics = metrics && typeof metrics === \"object\" && !Array.isArray(metrics)\n ? {\n ...metrics,\n reasonCodeDistribution\n }\n : { reasonCodeDistribution };\n return {\n ...meta,\n metrics: nextMetrics,\n reasonCodeDistribution\n };\n};\n\nconst incrementReasonCodeDistribution = (\n reasonCodeDistribution: Record<string, number>,\n reasonCode: ProviderReasonCode,\n count: number\n): Record<string, number> => {\n if (count <= 0) return reasonCodeDistribution;\n return Object.fromEntries(Object.entries({\n ...reasonCodeDistribution,\n [reasonCode]: (reasonCodeDistribution[reasonCode] ?? 0) + count\n }).sort(([left], [right]) => left.localeCompare(right)));\n};\n\nconst summarizeShoppingOfferFilterConstraint = (args: {\n diagnostics: ShoppingOfferFilterDiagnostic[];\n budget?: number;\n region?: string;\n regionEnforced: boolean;\n failures: ProviderFailureEntry[];\n}): string | null => {\n const primaryIssue = summarizePrimaryProviderIssue(args.failures);\n if (\n primaryIssue\n && (primaryIssue.reasonCode !== \"env_limited\" || primaryIssue.constraint || primaryIssue.blockerType === \"anti_bot_challenge\")\n ) {\n return null;\n }\n\n const candidateOffers = args.diagnostics.reduce((sum, entry) => sum + entry.candidateOffers, 0);\n const pricedOffers = args.diagnostics.reduce((sum, entry) => sum + entry.pricedOffers, 0);\n const regionMatchedOffers = args.diagnostics.reduce((sum, entry) => sum + entry.regionMatchedOffers, 0);\n const finalOffers = args.diagnostics.reduce((sum, entry) => sum + entry.finalOffers, 0);\n const zeroPriceExcluded = args.diagnostics.reduce((sum, entry) => sum + entry.zeroPriceExcluded, 0);\n const regionCurrencyExcluded = args.diagnostics.reduce((sum, entry) => sum + entry.regionCurrencyExcluded, 0);\n const budgetExcluded = args.diagnostics.reduce((sum, entry) => sum + entry.budgetExcluded, 0);\n const requestedRegion = args.diagnostics.find((entry) => typeof entry.requestedRegion === \"string\")?.requestedRegion ?? args.region;\n const expectedCurrency = args.diagnostics.find((entry) => typeof entry.expectedCurrency === \"string\")?.expectedCurrency;\n\n if (candidateOffers === 0 || finalOffers > 0) {\n return null;\n }\n\n if (pricedOffers > 0 && regionMatchedOffers === 0 && regionCurrencyExcluded > 0 && requestedRegion && !args.regionEnforced) {\n return `Requested region ${requestedRegion} was not enforced by the selected providers, and all candidate offers were filtered by the ${expectedCurrency ?? \"requested\"} currency heuristic.`;\n }\n\n if (typeof args.budget === \"number\" && regionMatchedOffers > 0 && budgetExcluded > 0 && finalOffers === 0) {\n const budgetLabel = expectedCurrency ? `${expectedCurrency} ${args.budget.toFixed(2)}` : args.budget.toFixed(2);\n return `All candidate offers exceeded the requested budget of ${budgetLabel}.`;\n }\n\n if (candidateOffers > 0 && zeroPriceExcluded === candidateOffers) {\n return \"Selected providers returned only zero-price or missing-price offers, so this run could not determine a trustworthy deal price.\";\n }\n\n return null;\n};\n\nconst selectResearchPrimaryConstraintFailures = (\n failures: ProviderFailureEntry[]\n): ProviderFailureEntry[] => failures.filter((failure) => failure.error.code !== \"timeout\");\n\nconst mergeRuntimePolicyInput = (\n options: ProviderRunOptions,\n input: Partial<ProviderRuntimePolicyInput>\n): ProviderRunOptions => {\n const runtimePolicy: ProviderRuntimePolicyInput = {\n ...(options.runtimePolicy ?? {}),\n ...input\n };\n return {\n ...options,\n runtimePolicy\n };\n};\n\nconst withCookieOverrides = (\n options: ProviderRunOptions,\n input: { useCookies?: boolean; cookiePolicyOverride?: ProviderCookiePolicy }\n): ProviderRunOptions => {\n return mergeRuntimePolicyInput(options, {\n ...(typeof input.useCookies === \"boolean\" ? { useCookies: input.useCookies } : {}),\n ...(input.cookiePolicyOverride ? { cookiePolicyOverride: input.cookiePolicyOverride } : {})\n });\n};\n\nconst withChallengeAutomationOverride = (\n options: ProviderRunOptions,\n input: { challengeAutomationMode?: ChallengeAutomationMode }\n): ProviderRunOptions => {\n return mergeRuntimePolicyInput(options, {\n ...(input.challengeAutomationMode ? { challengeAutomationMode: input.challengeAutomationMode } : {})\n });\n};\n\nconst withBrowserModeOverride = (\n options: ProviderRunOptions,\n input: { browserMode?: WorkflowBrowserMode }\n): ProviderRunOptions => {\n return mergeRuntimePolicyInput(options, {\n ...(input.browserMode ? { browserMode: input.browserMode } : {})\n });\n};\n\nconst WORKFLOW_KIND_BY_SUSPENDED_INTENT_KIND: Record<WorkflowSuspendedIntentKind, WorkflowKind> = {\n \"workflow.research\": \"research\",\n \"workflow.shopping\": \"shopping\",\n \"workflow.inspiredesign\": \"inspiredesign\",\n \"workflow.product_video\": \"product_video\"\n};\n\nconst buildWorkflowResumePayload = (\n kind: WorkflowSuspendedIntentKind,\n input: JsonValue | WorkflowResumeEnvelope\n): { workflow: ReturnType<typeof buildWorkflowResumeEnvelope> } => ({\n workflow: isWorkflowResumeEnvelope(input as JsonValue)\n ? input as WorkflowResumeEnvelope\n : buildWorkflowResumeEnvelope(WORKFLOW_KIND_BY_SUSPENDED_INTENT_KIND[kind], input)\n});\n\nconst withWorkflowResumeEnvelopeIntent = (\n options: ProviderRunOptions,\n kind: WorkflowSuspendedIntentKind,\n envelope: WorkflowResumeEnvelope\n): ProviderRunOptions => ({\n ...options,\n suspendedIntent: {\n kind,\n input: buildWorkflowResumePayload(kind, envelope)\n }\n});\n\nconst detectFailureReasonCode = (failure: ProviderFailureEntry): ProviderReasonCode | undefined => {\n return failure.error.reasonCode\n ?? normalizeProviderReasonCode({\n code: failure.error.code,\n message: failure.error.message,\n details: failure.error.details\n });\n};\n\nconst summarizeReasonCodeDistribution = (failures: ProviderFailureEntry[]): Record<string, number> => {\n const counts = new Map<string, number>();\n for (const failure of failures) {\n const reasonCode = detectFailureReasonCode(failure);\n if (!reasonCode) continue;\n counts.set(reasonCode, (counts.get(reasonCode) ?? 0) + 1);\n }\n return Object.fromEntries([...counts.entries()].sort(([left], [right]) => left.localeCompare(right)));\n};\n\nconst summarizeTranscriptStrategyFailures = (failures: ProviderFailureEntry[]): Record<string, number> => {\n const counts = new Map<string, number>();\n for (const failure of failures) {\n const attemptChain = failure.error.details?.attemptChain;\n if (!Array.isArray(attemptChain)) continue;\n for (const item of attemptChain) {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) continue;\n const strategy = (item as Record<string, unknown>).strategy;\n const reasonCode = (item as Record<string, unknown>).reasonCode;\n if (typeof strategy !== \"string\" || typeof reasonCode !== \"string\") continue;\n const key = `${strategy}:${reasonCode}`;\n counts.set(key, (counts.get(key) ?? 0) + 1);\n }\n }\n return Object.fromEntries([...counts.entries()].sort(([left], [right]) => left.localeCompare(right)));\n};\n\nconst summarizeTranscriptStrategyDetailDistribution = (records: NormalizedRecord[]): Record<string, number> => {\n const counts = new Map<string, number>();\n for (const record of records) {\n const strategyDetail = record.attributes.transcript_strategy_detail;\n const transcriptStrategy = record.attributes.transcript_strategy;\n const resolved = typeof strategyDetail === \"string\" && strategyDetail.trim().length > 0\n ? strategyDetail\n : typeof transcriptStrategy === \"string\" && transcriptStrategy.trim().length > 0\n ? transcriptStrategy\n : null;\n if (!resolved) continue;\n counts.set(resolved, (counts.get(resolved) ?? 0) + 1);\n }\n return Object.fromEntries([...counts.entries()].sort(([left], [right]) => left.localeCompare(right)));\n};\n\nconst TRANSCRIPT_REASON_CODES = new Set<ProviderReasonCode>([\n \"caption_missing\",\n \"transcript_unavailable\",\n \"strategy_unapproved\"\n]);\n\nconst ANTI_BOT_REASON_CODES = new Set<ProviderReasonCode>([\n \"ip_blocked\",\n \"token_required\",\n \"auth_required\",\n \"challenge_detected\",\n \"rate_limited\",\n \"cooldown_active\"\n]);\n\nconst summarizeCookieDiagnostics = (\n failures: ProviderFailureEntry[],\n records: NormalizedRecord[]\n): Array<Record<string, JsonValue>> => {\n const diagnostics: Array<Record<string, JsonValue>> = [];\n for (const failure of failures) {\n const candidate = failure.error.details?.cookieDiagnostics;\n if (!candidate || typeof candidate !== \"object\" || Array.isArray(candidate)) continue;\n diagnostics.push({\n provider: failure.provider,\n source: failure.source,\n ...(detectFailureReasonCode(failure) ? { reasonCode: detectFailureReasonCode(failure) as JsonValue } : {}),\n ...(candidate as Record<string, JsonValue>)\n });\n }\n\n for (const record of records) {\n const candidate = record.attributes.browser_fallback_cookie_diagnostics;\n if (!candidate || typeof candidate !== \"object\" || Array.isArray(candidate)) continue;\n diagnostics.push({\n provider: record.provider,\n source: record.source,\n ...(candidate as Record<string, JsonValue>)\n });\n }\n\n for (const record of records) {\n const attemptChain = record.attributes.attempt_chain;\n if (!Array.isArray(attemptChain)) continue;\n for (const attempt of attemptChain) {\n if (!attempt || typeof attempt !== \"object\" || Array.isArray(attempt)) continue;\n const cookieDiagnostics = (attempt as Record<string, unknown>).cookieDiagnostics;\n if (!cookieDiagnostics || typeof cookieDiagnostics !== \"object\" || Array.isArray(cookieDiagnostics)) continue;\n diagnostics.push({\n provider: record.provider,\n source: record.source,\n ...(cookieDiagnostics as Record<string, JsonValue>)\n });\n }\n }\n return diagnostics;\n};\n\nconst summarizeChallengeOrchestration = (\n failures: ProviderFailureEntry[],\n records: NormalizedRecord[]\n): Array<Record<string, JsonValue>> => {\n const diagnostics: Array<Record<string, JsonValue>> = [];\n\n for (const failure of failures) {\n const candidate = failure.error.details?.challengeOrchestration;\n if (!candidate || typeof candidate !== \"object\" || Array.isArray(candidate)) continue;\n diagnostics.push({\n provider: failure.provider,\n source: failure.source,\n ...(detectFailureReasonCode(failure) ? { reasonCode: detectFailureReasonCode(failure) as JsonValue } : {}),\n ...(typeof failure.error.details?.browserFallbackReasonCode === \"string\"\n ? { browserFallbackReasonCode: failure.error.details.browserFallbackReasonCode }\n : {}),\n ...(typeof failure.error.details?.browserFallbackMode === \"string\"\n ? { browserFallbackMode: failure.error.details.browserFallbackMode }\n : {}),\n ...(candidate as Record<string, JsonValue>)\n });\n }\n\n for (const record of records) {\n const candidate = record.attributes.browser_fallback_challenge_orchestration;\n if (!candidate || typeof candidate !== \"object\" || Array.isArray(candidate)) continue;\n diagnostics.push({\n provider: record.provider,\n source: record.source,\n ...(typeof record.attributes.browser_fallback_reason_code === \"string\"\n ? { browserFallbackReasonCode: record.attributes.browser_fallback_reason_code }\n : {}),\n ...(typeof record.attributes.browser_fallback_mode === \"string\"\n ? { browserFallbackMode: record.attributes.browser_fallback_mode }\n : {}),\n ...(candidate as Record<string, JsonValue>)\n });\n }\n\n return diagnostics;\n};\n\nconst summarizeBrowserFallbackModes = (\n failures: ProviderFailureEntry[],\n records: NormalizedRecord[]\n): BrowserFallbackMode[] => {\n const observed = new Set<BrowserFallbackMode>();\n\n for (const failure of failures) {\n const mode = failure.error.details?.browserFallbackMode;\n if (mode === \"extension\" || mode === \"managed_headed\") {\n observed.add(mode);\n }\n }\n\n for (const record of records) {\n const mode = record.attributes.browser_fallback_mode;\n if (mode === \"extension\" || mode === \"managed_headed\") {\n observed.add(mode);\n }\n }\n\n return [...observed];\n};\n\nconst hasTranscriptSuccess = (record: NormalizedRecord): boolean => {\n const transcriptAvailable = record.attributes.transcript_available;\n if (transcriptAvailable === true) return true;\n const transcriptStrategy = record.attributes.transcript_strategy;\n return typeof transcriptStrategy === \"string\" && transcriptStrategy.trim().length > 0;\n};\n\nconst summarizeTranscriptDurability = (\n records: NormalizedRecord[],\n failures: ProviderFailureEntry[]\n): {\n attempted: number;\n successful: number;\n failed: number;\n success_rate: number;\n} => {\n const successful = records.filter((record) => hasTranscriptSuccess(record)).length;\n const failed = failures.filter((failure) => {\n const reasonCode = detectFailureReasonCode(failure);\n if (reasonCode && TRANSCRIPT_REASON_CODES.has(reasonCode)) return true;\n return Array.isArray(failure.error.details?.attemptChain);\n }).length;\n const attempted = successful + failed;\n return {\n attempted,\n successful,\n failed,\n success_rate: attempted > 0 ? Number((successful / attempted).toFixed(4)) : 0\n };\n};\n\nconst summarizeAntiBotPressure = (failures: ProviderFailureEntry[]): {\n total_failures: number;\n anti_bot_failures: number;\n anti_bot_failure_ratio: number;\n} => {\n const totalFailures = failures.length;\n const antiBotFailures = failures.filter((failure) => {\n const reasonCode = detectFailureReasonCode(failure);\n return Boolean(reasonCode && ANTI_BOT_REASON_CODES.has(reasonCode));\n }).length;\n return {\n total_failures: totalFailures,\n anti_bot_failures: antiBotFailures,\n anti_bot_failure_ratio: totalFailures > 0 ? Number((antiBotFailures / totalFailures).toFixed(4)) : 0\n };\n};\n\nexport const workflowTestUtils = {\n resetProviderSignalState: (): void => {\n providerSignalMap.clear();\n },\n getDegradedProviders: (): string[] => [...getDegradedProviders()],\n nextSignalState: (\n previous: \"none\" | \"warning\" | \"degraded\",\n warning: boolean,\n degraded: boolean,\n healthyWindows: number\n ): { state: \"none\" | \"warning\" | \"degraded\"; healthyWindows: number } =>\n nextSignalState(previous, warning, degraded, healthyWindows),\n redactRawCapture: (record: unknown): Record<string, unknown> =>\n redactRawCapture(record as Record<string, unknown>),\n toProviderSource: (providerId: string): ProviderSource | null => toProviderSource(providerId),\n resolveShoppingProviderIdForUrl: (url: string): string | null => resolveShoppingProviderIdForUrl(url),\n resolveShoppingSourceForUrl: (url: string): ProviderSource => resolveShoppingSourceForUrl(url),\n resolveProductCopy: (\n record: NormalizedRecord,\n productUrl: string,\n refreshedDescription: string | undefined,\n featureList: string[]\n ): string => resolveProductCopy(record, productUrl, refreshedDescription, featureList),\n getRequiredProductVideoExecutionStep: <\n TStepId extends ProductVideoWorkflowExecutionStep[\"id\"]\n >(\n steps: ProductVideoWorkflowExecutionStep[],\n stepId: TStepId\n ): Extract<ProductVideoWorkflowExecutionStep, { id: TStepId }> =>\n getRequiredProductVideoExecutionStep(steps, stepId),\n normalizeProductVideoProviderHint: (\n productUrl: string,\n providerHint?: string,\n fallbackProvider?: string\n ): string | undefined => normalizeProductVideoProviderHint(productUrl, providerHint, fallbackProvider),\n hasTranscriptSuccess: (record: NormalizedRecord): boolean => hasTranscriptSuccess(record),\n sanitizeFeatureList: (values: string[]): string[] => sanitizeFeatureList(values),\n parsePriceFromContent: (content: string | undefined): { amount: number; currency: string } =>\n parsePriceFromContent(content),\n inferBrandFromUrl: (url: string | undefined): string | undefined => inferBrandFromUrl(url),\n inferBrandFromContent: (content: string | undefined): string | undefined => inferBrandFromContent(content),\n isLikelyOfferRecord: (record: NormalizedRecord): boolean => isLikelyOfferRecord(record),\n needsProductMetadataRefresh: (record: NormalizedRecord, productUrl: string): boolean =>\n needsProductMetadataRefresh(record, productUrl),\n fetchBinary: (url: string, timeoutMs?: number): Promise<Buffer | null> => fetchBinary(url, timeoutMs),\n rankResearchRecords: (records: ResearchRecord[]): ResearchRecord[] => rankResearchRecords(records),\n isValidHttpUrl: (url: string): boolean => isValidHttpUrl(url),\n buildWorkflowResumePayload: (\n kind: WorkflowSuspendedIntentKind,\n input: JsonValue | WorkflowResumeEnvelope\n ): { workflow: ReturnType<typeof buildWorkflowResumeEnvelope> } => buildWorkflowResumePayload(kind, input),\n withPrimaryConstraintSummaryOverride: (\n meta: Record<string, unknown>,\n summary: string,\n guidance?: ProviderNextStepGuidance\n ): Record<string, unknown> => withPrimaryConstraintSummaryOverride(meta, summary, guidance),\n withReasonCodeDistributionMeta: (\n meta: Record<string, unknown>,\n reasonCodeDistribution: Record<string, number>\n ): Record<string, unknown> => withReasonCodeDistributionMeta(meta, reasonCodeDistribution),\n incrementReasonCodeDistribution: (\n reasonCodeDistribution: Record<string, number>,\n reasonCode: ProviderReasonCode,\n count: number\n ): Record<string, number> => incrementReasonCodeDistribution(reasonCodeDistribution, reasonCode, count),\n summarizeShoppingOfferFilterConstraint: (args: {\n diagnostics: ShoppingOfferFilterDiagnostic[];\n budget?: number;\n region?: string;\n regionEnforced: boolean;\n failures: ProviderFailureEntry[];\n }): string | null => summarizeShoppingOfferFilterConstraint(args),\n parseInspiredesignEnvelopeInput: (input: WorkflowResumeEnvelope[\"input\"]): InspiredesignRunInput =>\n parseInspiredesignEnvelopeInput(input),\n failureFromInspiredesignDiscoveryError: (\n workflowInput: InspiredesignResolvedInput,\n error: ProviderError | undefined\n ): ProviderFailureEntry[] => failureFromInspiredesignDiscoveryError(workflowInput, error),\n failureFromInspiredesignFetchError: (\n result: ProviderAggregateResult\n ): ProviderFailureEntry[] => failureFromInspiredesignFetchError(result),\n extractProductBrandFromTitle: (title: string | undefined, productUrl: string): string | undefined =>\n extractProductBrandFromTitle(title, productUrl)\n};\n\nconst PRODUCT_ASSET_FETCH_TIMEOUT_MS = 15_000;\nconst RESEARCH_PROVIDER_STEP_TIMEOUT_MS = 30_000;\n\nconst resolveAuxiliaryFetchTimeoutMs = (timeoutMs?: number): number => {\n if (typeof timeoutMs !== \"number\" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n return PRODUCT_ASSET_FETCH_TIMEOUT_MS;\n }\n return Math.max(1, Math.min(timeoutMs, PRODUCT_ASSET_FETCH_TIMEOUT_MS));\n};\n\nconst buildAuxiliaryFetchSignal = (timeoutMs?: number): AbortSignal | undefined => {\n return AbortSignal.timeout(resolveAuxiliaryFetchTimeoutMs(timeoutMs));\n};\n\nconst toDedupeKey = (record: { url?: string; title?: string }): string => {\n const url = record.url ? canonicalizeUrl(record.url) : \"\";\n const title = (record.title ?? \"\").trim().toLowerCase();\n return `${url}::${title}`;\n};\n\nconst dedupeResearchRecords = (records: ResearchRecord[]): ResearchRecord[] => {\n const deduped = new Map<string, ResearchRecord>();\n for (const record of records) {\n const key = toDedupeKey(record);\n if (!deduped.has(key)) {\n deduped.set(key, record);\n continue;\n }\n\n const existing = deduped.get(key)!;\n const existingScore = (existing.date_confidence.score * 2) + existing.confidence - existing.recency.age_hours * 0.001;\n const nextScore = (record.date_confidence.score * 2) + record.confidence - record.recency.age_hours * 0.001;\n if (nextScore > existingScore) {\n deduped.set(key, record);\n }\n }\n return [...deduped.values()];\n};\n\nconst rankResearchRecords = (records: ResearchRecord[]): ResearchRecord[] => {\n return [...records].sort((left, right) => {\n if (left.recency.within_timebox !== right.recency.within_timebox) {\n return left.recency.within_timebox ? -1 : 1;\n }\n if (left.date_confidence.score !== right.date_confidence.score) {\n return right.date_confidence.score - left.date_confidence.score;\n }\n if (left.recency.age_hours !== right.recency.age_hours) {\n return left.recency.age_hours - right.recency.age_hours;\n }\n if (left.confidence !== right.confidence) {\n return right.confidence - left.confidence;\n }\n return left.id.localeCompare(right.id);\n });\n};\n\nconst hash = (value: string): string => createHash(\"sha1\").update(value).digest(\"hex\").slice(0, 16);\n\nconst RESEARCH_ALWAYS_SANITIZED_PATHS = new Set<string>([\n \"community:search:index\",\n \"community:search:url\",\n \"social:search:index\",\n \"social:search:url\",\n \"social:youtube:search:url\",\n \"web:search:url\",\n]);\nconst RESEARCH_CONDITIONAL_SANITIZED_PATHS = new Set<string>([\n \"community:fetch:url\",\n \"social:fetch:url\",\n \"web:search:index\"\n]);\nconst RESEARCH_LOGIN_SHELL_RE = /\\b(?:log in|login|sign in|sign-in|please log in|continue with google|continue with apple)\\b/i;\nconst RESEARCH_LOGIN_SHELL_MAX_CONTENT_CHARS = 600;\nconst RESEARCH_LOGIN_REQUIRED_RE = /\\b(?:log in to continue|sign in to continue|authentication required|please log in|continue with google|continue with apple)\\b/i;\nconst RESEARCH_JS_REQUIRED_RE = /\\b(?:enable javascript|javascript required|javascript is not available|javascript is disabled|you need to enable javascript)\\b/i;\nconst RESEARCH_GENERIC_SHELL_RE = /\\b(?:skip to main content|the heart of the internet|open navigation|get the app|view in app|please wait for verification|verify you are human|security check)\\b/i;\nconst RESEARCH_NOT_FOUND_SHELL_RE = /\\b(?:error 404|page not found|not found|can['’]t seem to find the page)\\b/i;\nconst RESEARCH_PRIVACY_PREFERENCE_SHELL_RE = /\\b(?:select your cookie preferences|customize cookie preferences|unable to save cookie preferences|your privacy choices|manage consent preferences|privacy opt[- ]out|do not sell or share my personal information)\\b/i;\nconst RESEARCH_PRIVACY_RECOVERED_CONTENT_RE = /\\b(?:blogs? home|permalink|comments|article)\\b/i;\nconst RESEARCH_SEARCH_SHELL_RE = /\\b(?:duckduckgo|search results|all posts|communities|comments|try another search|no relevant content found|unable to load answer|search page)\\b/i;\nconst isDuckDuckGoResearchShellUrl = (url: string): boolean => {\n try {\n const parsed = new URL(url);\n const host = parsed.hostname.toLowerCase();\n const pathname = parsed.pathname.toLowerCase();\n return (host === \"duckduckgo.com\" && (pathname === \"/l\" || pathname === \"/l/\"))\n || (host === \"html.duckduckgo.com\" && pathname.startsWith(\"/html\"));\n } catch {\n return false;\n }\n};\nconst PRODUCT_TARGET_NOT_FOUND_RE = /\\b(?:error 404|page not found|not found|we can['’]t seem to find the page|can['’]t seem to find the page|return to homepage)\\b/i;\nconst BESTBUY_PDP_ERROR_SHELL_RE = /\\b(?:something went wrong|use our search bar|pick a category below|typed in a url|check it for errors)\\b/i;\nconst resolveShoppingProviderIdForUrl = (url: string): string | null => {\n try {\n const host = new URL(url).hostname.toLowerCase();\n for (const profile of SHOPPING_PROVIDER_PROFILES) {\n if (profile.domains.some((domain) => host === domain || host.endsWith(`.${domain}`))) {\n return profile.id;\n }\n }\n return \"shopping/others\";\n } catch {\n return null;\n }\n};\n\nconst normalizeProductVideoProviderHint = (\n productUrl: string,\n providerHint?: string,\n fallbackProvider?: string\n): string | undefined => {\n if (fallbackProvider?.includes(\"/\")) return fallbackProvider;\n if (providerHint?.includes(\"/\")) return providerHint;\n const shoppingProviderId = resolveShoppingProviderIdForUrl(productUrl);\n if (shoppingProviderId) {\n return providerHint ? `shopping/${providerHint}` : fallbackProvider ?? shoppingProviderId;\n }\n return fallbackProvider ?? providerHint;\n};\n\nconst IMAGE_ASSET_RE = /\\.(?:png|jpg|jpeg|webp|gif)(?:[?#].*)?$/i;\n\nconst isHttpAssetUrl = (value: string): boolean => {\n try {\n const parsed = new URL(value.trim());\n return parsed.protocol === \"http:\" || parsed.protocol === \"https:\";\n } catch {\n return false;\n }\n};\n\nconst extractImageUrls = (record: NormalizedRecord): string[] => {\n const structured = Array.isArray(record.attributes.image_urls)\n ? record.attributes.image_urls.filter((entry): entry is string => typeof entry === \"string\" && isHttpAssetUrl(entry))\n : [];\n const links = Array.isArray(record.attributes.links)\n ? record.attributes.links.filter((entry): entry is string => typeof entry === \"string\")\n : [];\n\n const imageLinks = [\n ...structured.map((entry) => entry.trim()),\n ...links.filter((link) => IMAGE_ASSET_RE.test(link))\n ];\n return [...new Set(imageLinks.map((link) => canonicalizeUrl(link)))].slice(0, 50);\n};\n\nconst mergeImageUrls = (record: NormalizedRecord, extra: string[] = []): string[] => {\n return [...new Set([\n ...extractImageUrls(record),\n ...extra.map((link) => canonicalizeUrl(link))\n ])].slice(0, 50);\n};\n\nconst MARKETPLACE_COPY_RE = /\\b(?:amazon\\.com|walmart\\.com|free delivery possible on eligible purchases|continue to site|see current price, availability, shipping cost|buy .* - amazon\\.com|shipper\\s*\\/\\s*seller|main content|about this item|buying options|compare with similar items)\\b/i;\nconst MARKETPLACE_OVERLAY_RE = /\\b(?:shipper \\/ seller|returns \\/ exchanges handled by|continue to site|see current price, availability, shipping cost|deliver to canada)\\b/i;\nconst WALMART_TITLE_PREFIX_RE = /^(?:free shipping!?\\s*)+/i;\nconst WALMART_TITLE_TAIL_RE = /\\s*[-|:]\\s*Walmart\\.com\\b.*$/i;\nconst WALMART_TITLE_CHROME_RE = /\\b(?:Walmart\\.com|Skip to Main Content|Pickup or delivery\\?|How do you want your item\\?|Departments Services)\\b/i;\nconst WALMART_BRAND_COLOR_RE = /\\bColor\\s+[A-Z0-9][A-Za-z0-9 /-]*(?=\\s+(?:View full specifications|Current price is|Skip to Main Content|Pickup or delivery\\?|How do you want your item\\?|Sold and shipped by|Seller Rating|Free shipping|Arrives\\b|Shipping\\b|Delivery\\b|Pickup\\b|Departments Services|More details|Add to cart)|$)/i;\nconst WALMART_BRAND_CHROME_TAIL_RE = /\\b(?:View full specifications|Current price is|Skip to Main Content|Pickup or delivery\\?|How do you want your item\\?|Sold and shipped by|Seller Rating|Free shipping|Arrives\\b|Shipping\\b|Delivery\\b|Pickup\\b|Departments Services|More details|Add to cart)\\b.*$/i;\nconst WALMART_BRAND_CHROME_RE = /\\b(?:Walmart\\.com|Skip to Main Content|Pickup or delivery\\?|How do you want your item\\?|Sold and shipped by|Seller Rating|View full specifications|Current price is|Free shipping|Departments Services)\\b/i;\nconst EBAY_TITLE_BRAND_PREFIX_RE = /^(?:new|used|pre-owned|preowned|open box|refurbished|renewed|genuine|authentic)\\s+/i;\nconst EBAY_KNOWN_MULTI_TOKEN_BRANDS = [\n \"3M\",\n \"Bang & Olufsen\",\n \"Bowers & Wilkins\",\n \"Hewlett-Packard\",\n \"iRobot\",\n \"New Balance\"\n] as const;\nconst EBAY_KNOWN_SINGLE_TOKEN_BRANDS = new Map([\n [\"apple\", \"Apple\"],\n [\"bose\", \"Bose\"],\n [\"canon\", \"Canon\"],\n [\"dell\", \"Dell\"],\n [\"dyson\", \"Dyson\"],\n [\"google\", \"Google\"],\n [\"jbl\", \"JBL\"],\n [\"lenovo\", \"Lenovo\"],\n [\"lg\", \"LG\"],\n [\"microsoft\", \"Microsoft\"],\n [\"nikon\", \"Nikon\"],\n [\"nintendo\", \"Nintendo\"],\n [\"panasonic\", \"Panasonic\"],\n [\"philips\", \"Philips\"],\n [\"samsung\", \"Samsung\"],\n [\"sony\", \"Sony\"]\n]);\nconst EBAY_TITLE_BRAND_STOP_WORDS = new Set([\n \"bluetooth\",\n \"case\",\n \"ergonomic\",\n \"gaming\",\n \"headphones\",\n \"keyboard\",\n \"leather\",\n \"noise\",\n \"portable\",\n \"rechargeable\",\n \"speaker\",\n \"vertical\",\n \"wireless\"\n]);\nconst PRODUCT_FEATURE_SECTION_MARKERS = [\n \"about this item\",\n \"key item features\",\n \"about this product\"\n] as const;\nconst PRODUCT_FEATURE_SECTION_STOP_RE = /\\b(?:report an issue|check compatibility|technical details|technical specifications|product information|customer reviews|compare [a-z0-9 ]+|top brand:|from the brand|from the manufacturer|questions|reviews|your recently viewed|back to top|view all item details|view full specifications|generated by ai|reviews summary|was this summary helpful|current price is|price when purchased online|all listings for this product|ratings and reviews|best selling in)\\b/i;\nconst PRODUCT_FEATURE_CAPS_TOKEN = \"[A-Z0-9][A-Z0-9'()+/&.,]*(?:-[A-Z0-9][A-Z0-9'()+/&.,]*)*\";\nconst PRODUCT_FEATURE_TITLE_TOKEN = \"[A-Z][A-Za-z0-9'()+/&.,]*(?:-[A-Z0-9][A-Za-z0-9'()+/&.,]*)*\";\nconst PRODUCT_FEATURE_PATTERNS = [\n new RegExp(\n `(${PRODUCT_FEATURE_CAPS_TOKEN}(?:\\\\s+${PRODUCT_FEATURE_CAPS_TOKEN}){0,11})\\\\s+[\\\\u2013\\\\u2014-]\\\\s+(.+?)(?=(?:${PRODUCT_FEATURE_CAPS_TOKEN}(?:\\\\s+${PRODUCT_FEATURE_CAPS_TOKEN}){0,11})\\\\s+[\\\\u2013\\\\u2014-]\\\\s+|$)`,\n \"g\"\n ),\n new RegExp(\n `(${PRODUCT_FEATURE_TITLE_TOKEN}(?:\\\\s+${PRODUCT_FEATURE_TITLE_TOKEN}){0,11})\\\\s*:\\\\s+(.+?)(?=(?:${PRODUCT_FEATURE_TITLE_TOKEN}(?:\\\\s+${PRODUCT_FEATURE_TITLE_TOKEN}){0,11})\\\\s*:\\\\s+|$)`,\n \"g\"\n )\n] as const;\nconst HOST_DEFAULT_CURRENCY: Array<[RegExp, string]> = [\n [/amazon\\.ca$/i, \"CAD\"],\n [/amazon\\.(?:co\\.uk|uk)$/i, \"GBP\"],\n [/amazon\\.(?:de|fr|es|it)$/i, \"EUR\"],\n [/(?:amazon\\.com|walmart\\.com|bestbuy\\.com|target\\.com|ebay\\.com)$/i, \"USD\"]\n];\n\nconst fetchBinary = async (url: string, timeoutMs?: number): Promise<Buffer | null> => {\n try {\n const response = await fetch(url, {\n headers: {\n accept: \"image/*,*/*;q=0.8\",\n ...providerRequestHeaders\n },\n redirect: \"follow\",\n signal: buildAuxiliaryFetchSignal(timeoutMs)\n });\n if (!response.ok) return null;\n const bytes = await response.arrayBuffer();\n return Buffer.from(bytes);\n } catch {\n return null;\n }\n};\n\nconst createRemainingTimeoutResolver = (timeoutMs?: number): (() => number | undefined) => {\n if (typeof timeoutMs !== \"number\" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n return () => undefined;\n }\n const startedAtMs = Date.now();\n let firstRead = true;\n return () => {\n if (firstRead) {\n firstRead = false;\n return timeoutMs;\n }\n return Math.max(1, timeoutMs - Math.max(0, Date.now() - startedAtMs));\n };\n};\n\nconst resolveResearchProviderStepTimeoutMs = (timeoutMs?: number): number | undefined => {\n if (typeof timeoutMs !== \"number\" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n return undefined;\n }\n return Math.max(1, Math.min(timeoutMs, RESEARCH_PROVIDER_STEP_TIMEOUT_MS));\n};\n\ntype InspiredesignResolvedInput = Omit<InspiredesignRunInput, \"brief\" | \"urls\" | \"captureMode\" | \"query\" | \"providers\" | \"maxReferences\" | \"visualEvidence\"> & {\n brief: string;\n briefExpansion: InspiredesignBriefExpansion;\n query?: string;\n providers: string[];\n maxReferences: number;\n referenceLimit?: number;\n visualEvidence: InspiredesignVisualEvidenceMode;\n urls: string[];\n captureMode: InspiredesignCaptureMode;\n mode: RenderMode;\n};\n\nconst INSPIREDESIGN_RENDER_MODES = new Set<RenderMode>([\"compact\", \"json\", \"md\", \"context\", \"path\"]);\nconst INSPIREDESIGN_CAPTURE_MODES = new Set<InspiredesignCaptureMode>([\"off\", \"deep\"]);\nconst INSPIREDESIGN_COOKIE_POLICIES = new Set<ProviderCookiePolicy>([\"off\", \"auto\", \"required\"]);\nconst WORKFLOW_BROWSER_MODES = new Set<WorkflowBrowserMode>([\"auto\", \"extension\", \"managed\"]);\nconst INSPIREDESIGN_DEFAULT_MAX_REFERENCES = 5;\nconst INSPIREDESIGN_MAX_REFERENCES_LIMIT = 10;\n\nconst isJsonRecord = (value: JsonValue | undefined): value is Record<string, JsonValue> => (\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n);\n\ntype InspiredesignCaptureOutcome = {\n captureStatus: InspiredesignReferenceEvidence[\"captureStatus\"];\n capture?: InspiredesignCaptureEvidence | null;\n captureFailure?: string;\n};\n\ntype InspiredesignVisualCapturePlan = {\n policy: InspiredesignVisualPolicyDecision;\n referenceId: string;\n tempPath?: string;\n};\n\ntype InspiredesignVisualArtifactCollation = {\n references: InspiredesignReferenceEvidence[];\n files: ArtifactFile[];\n};\n\nconst INSPIREDESIGN_CAPTURE_UNAVAILABLE_FAILURE =\n \"Deep capture requested, but browser capture is unavailable in this execution lane.\";\nconst REQUIRED_VISUAL_EVIDENCE_MISSING_FAILURE = \"Required visual evidence was not captured.\";\nconst INSPIREDESIGN_VISUAL_POLICY_BLOCKER_REASONS = new Set<InspiredesignVisualPolicyDecision[\"reason\"]>([\n \"policy_blocked\",\n \"auth_required\",\n \"challenge_detected\",\n \"rate_limited\"\n]);\ntype InspiredesignCaptureAttemptCounts = Record<\n InspiredesignCaptureAttemptKey,\n Record<InspiredesignCaptureAttemptStatus, number>\n>;\n\nconst isCanvasVisualDirectionProfile = (\n value: string\n): value is InspiredesignBriefFormat[\"route\"][\"profile\"] => {\n return (CANVAS_VISUAL_DIRECTION_PROFILES as readonly string[]).includes(value);\n};\n\nconst isCanvasThemeStrategy = (\n value: string\n): value is InspiredesignBriefFormat[\"route\"][\"themeStrategy\"] => {\n return (CANVAS_THEME_STRATEGIES as readonly string[]).includes(value);\n};\n\nconst isCanvasNavigationModel = (\n value: string\n): value is InspiredesignBriefFormat[\"route\"][\"navigationModel\"] => {\n return (CANVAS_NAVIGATION_MODELS as readonly string[]).includes(value);\n};\n\nconst serializeInspiredesignBriefExpansion = (\n expansion: InspiredesignBriefExpansion\n): Record<string, JsonValue> => structuredClone(expansion) as Record<string, JsonValue>;\n\nconst serializeInspiredesignRunInput = (input: InspiredesignResolvedInput): Record<string, JsonValue> => ({\n brief: input.brief,\n briefExpansion: serializeInspiredesignBriefExpansion(input.briefExpansion),\n ...(input.harvest === true ? { harvest: true } : {}),\n ...(input.query ? { query: input.query } : {}),\n ...(input.providers.length > 0 ? { providers: input.providers } : {}),\n ...(input.referenceLimit !== undefined ? { maxReferences: input.maxReferences } : {}),\n visualEvidence: input.visualEvidence,\n urls: input.urls,\n captureMode: input.captureMode,\n mode: input.mode,\n ...(input.includePrototypeGuidance !== undefined ? { includePrototypeGuidance: input.includePrototypeGuidance } : {}),\n ...(typeof input.timeoutMs === \"number\" ? { timeoutMs: input.timeoutMs } : {}),\n ...(input.outputDir ? { outputDir: input.outputDir } : {}),\n ...(typeof input.ttlHours === \"number\" ? { ttlHours: input.ttlHours } : {}),\n ...(input.browserMode ? { browserMode: input.browserMode } : {}),\n ...(typeof input.useCookies === \"boolean\" ? { useCookies: input.useCookies } : {}),\n ...(input.challengeAutomationMode ? { challengeAutomationMode: input.challengeAutomationMode } : {}),\n ...(input.cookiePolicyOverride ? { cookiePolicyOverride: input.cookiePolicyOverride } : {})\n});\n\nconst isStringArray = (value: JsonValue | undefined): value is string[] => (\n Array.isArray(value) && value.every((entry) => typeof entry === \"string\")\n);\n\nconst parseInspiredesignBriefFormatRoute = (\n value: JsonValue | undefined\n): InspiredesignBriefFormat[\"route\"] | undefined => {\n if (!isJsonRecord(value)) return undefined;\n const profile = typeof value.profile === \"string\" && isCanvasVisualDirectionProfile(value.profile)\n ? value.profile\n : undefined;\n const themeStrategy = typeof value.themeStrategy === \"string\" && isCanvasThemeStrategy(value.themeStrategy)\n ? value.themeStrategy\n : undefined;\n const navigationModel = typeof value.navigationModel === \"string\" && isCanvasNavigationModel(value.navigationModel)\n ? value.navigationModel\n : undefined;\n if (!profile || !themeStrategy || !navigationModel || typeof value.layoutApproach !== \"string\") {\n return undefined;\n }\n return {\n profile,\n themeStrategy,\n navigationModel,\n layoutApproach: value.layoutApproach\n };\n};\n\nconst parseInspiredesignBriefFormat = (\n value: JsonValue | undefined\n): InspiredesignBriefFormat | undefined => {\n if (!isJsonRecord(value)) return undefined;\n const route = parseInspiredesignBriefFormatRoute(value.route);\n if (\n typeof value.id !== \"string\"\n || typeof value.label !== \"string\"\n || !isStringArray(value.bestFor)\n || !isStringArray(value.businessFocus)\n || !isStringArray(value.keywords)\n || typeof value.archetype !== \"string\"\n || typeof value.layoutArchetype !== \"string\"\n || typeof value.typographySystem !== \"string\"\n || typeof value.surfaceTreatment !== \"string\"\n || typeof value.shapeLanguage !== \"string\"\n || typeof value.componentGrammar !== \"string\"\n || typeof value.motionGrammar !== \"string\"\n || typeof value.paletteIntent !== \"string\"\n || typeof value.visualDensity !== \"string\"\n || typeof value.designVariance !== \"string\"\n || !isStringArray(value.responsiveCollapseRules)\n || !isStringArray(value.guardrails)\n || !isStringArray(value.antiPatterns)\n || !isStringArray(value.deliverables)\n || !route\n ) {\n return undefined;\n }\n return {\n id: value.id,\n label: value.label,\n bestFor: [...value.bestFor],\n businessFocus: [...value.businessFocus],\n keywords: [...value.keywords],\n archetype: value.archetype,\n layoutArchetype: value.layoutArchetype,\n typographySystem: value.typographySystem,\n surfaceTreatment: value.surfaceTreatment,\n shapeLanguage: value.shapeLanguage,\n componentGrammar: value.componentGrammar,\n motionGrammar: value.motionGrammar,\n paletteIntent: value.paletteIntent,\n visualDensity: value.visualDensity,\n designVariance: value.designVariance,\n responsiveCollapseRules: [...value.responsiveCollapseRules],\n guardrails: [...value.guardrails],\n antiPatterns: [...value.antiPatterns],\n deliverables: [...value.deliverables],\n route\n };\n};\n\nconst parseInspiredesignBriefExpansion = (\n value: JsonValue | undefined\n): InspiredesignBriefExpansion | undefined => {\n if (!isJsonRecord(value)) return undefined;\n const format = parseInspiredesignBriefFormat(value.format);\n if (\n typeof value.sourceBrief !== \"string\"\n || typeof value.advancedBrief !== \"string\"\n || typeof value.templateVersion !== \"string\"\n || !format\n ) {\n return undefined;\n }\n return {\n sourceBrief: value.sourceBrief,\n advancedBrief: value.advancedBrief,\n templateVersion: value.templateVersion,\n format\n };\n};\n\nconst parseInspiredesignEnvelopeInput = (input: WorkflowResumeEnvelope[\"input\"]): InspiredesignRunInput => {\n const briefExpansion = parseInspiredesignBriefExpansion(input.briefExpansion);\n return {\n brief: typeof input.brief === \"string\" ? input.brief : \"\",\n mode: typeof input.mode === \"string\" && INSPIREDESIGN_RENDER_MODES.has(input.mode as RenderMode)\n ? (input.mode as RenderMode)\n : \"compact\",\n ...(typeof input.harvest === \"boolean\" ? { harvest: input.harvest } : {}),\n ...(typeof input.query === \"string\" && input.query.trim().length > 0 ? { query: input.query.trim() } : {}),\n ...(Array.isArray(input.providers) ? { providers: input.providers.filter((provider): provider is string => typeof provider === \"string\") } : {}),\n ...(typeof input.maxReferences === \"number\" ? { maxReferences: input.maxReferences } : {}),\n ...(isInspiredesignVisualEvidenceMode(input.visualEvidence) ? { visualEvidence: input.visualEvidence } : {}),\n ...(briefExpansion ? { briefExpansion } : {}),\n ...(Array.isArray(input.urls) ? { urls: input.urls.filter((url): url is string => typeof url === \"string\") } : {}),\n ...(typeof input.captureMode === \"string\" && INSPIREDESIGN_CAPTURE_MODES.has(input.captureMode as InspiredesignCaptureMode)\n ? { captureMode: input.captureMode as InspiredesignCaptureMode }\n : {}),\n ...(typeof input.includePrototypeGuidance === \"boolean\" ? { includePrototypeGuidance: input.includePrototypeGuidance } : {}),\n ...(typeof input.timeoutMs === \"number\" ? { timeoutMs: input.timeoutMs } : {}),\n ...(typeof input.outputDir === \"string\" ? { outputDir: input.outputDir } : {}),\n ...(typeof input.ttlHours === \"number\" ? { ttlHours: input.ttlHours } : {}),\n ...(typeof input.browserMode === \"string\" && WORKFLOW_BROWSER_MODES.has(input.browserMode as WorkflowBrowserMode)\n ? { browserMode: input.browserMode as WorkflowBrowserMode }\n : {}),\n ...(typeof input.useCookies === \"boolean\" ? { useCookies: input.useCookies } : {}),\n ...(isChallengeAutomationMode(input.challengeAutomationMode)\n ? { challengeAutomationMode: input.challengeAutomationMode }\n : {}),\n ...(typeof input.cookiePolicyOverride === \"string\" && INSPIREDESIGN_COOKIE_POLICIES.has(input.cookiePolicyOverride as ProviderCookiePolicy)\n ? { cookiePolicyOverride: input.cookiePolicyOverride as ProviderCookiePolicy }\n : {})\n };\n};\n\nconst normalizeInspiredesignUrls = (urls: string[] | undefined): string[] => {\n if (!urls || urls.length === 0) return [];\n const normalized = urls\n .map((url) => url.trim())\n .filter(Boolean);\n const invalid = normalized.find((url) => !LOOKS_LIKE_URL_RE.test(url));\n if (invalid) {\n throw new Error(`Inspiredesign workflow received an invalid URL: ${invalid}`);\n }\n return [...new Set(normalized.map((url) => canonicalizeUrl(url)))];\n};\n\nconst normalizeInspiredesignMaxReferences = (\n value: number | undefined,\n fallbackCount: number\n): number => {\n if (typeof value === \"undefined\") {\n return Math.max(1, Math.min(Math.max(fallbackCount, 1), INSPIREDESIGN_MAX_REFERENCES_LIMIT));\n }\n if (!Number.isInteger(value) || value < 1 || value > INSPIREDESIGN_MAX_REFERENCES_LIMIT) {\n throw new Error(\"Inspiredesign workflow maxReferences must be an integer from 1 to 10.\");\n }\n return value;\n};\n\nconst normalizeInspiredesignVisualEvidenceMode = (\n value: unknown,\n harvest: boolean | undefined\n): InspiredesignVisualEvidenceMode => {\n if (typeof value === \"undefined\") {\n return harvest === true ? \"required\" : \"off\";\n }\n if (!isInspiredesignVisualEvidenceMode(value)) {\n throw new Error(\"Inspiredesign workflow visualEvidence must be one of off, auto, or required.\");\n }\n return value;\n};\n\nconst hasValidInspiredesignBriefRoute = (route: InspiredesignBriefFormat[\"route\"]): boolean => {\n return isCanvasVisualDirectionProfile(route.profile)\n && isCanvasThemeStrategy(route.themeStrategy)\n && isCanvasNavigationModel(route.navigationModel);\n};\n\nconst shouldReuseInspiredesignBriefExpansion = (\n briefExpansion: InspiredesignBriefExpansion | undefined,\n normalizedBrief: string\n): briefExpansion is InspiredesignBriefExpansion => {\n if (!briefExpansion) {\n return false;\n }\n if (normalizeInspiredesignBriefText(briefExpansion.sourceBrief) !== normalizedBrief) {\n return false;\n }\n if (briefExpansion.templateVersion !== INSPIREDESIGN_BRIEF_TEMPLATE_VERSION) {\n return false;\n }\n return hasValidInspiredesignBriefRoute(briefExpansion.format.route);\n};\n\nconst normalizeInspiredesignInput = (input: InspiredesignRunInput): InspiredesignResolvedInput => {\n const brief = input.brief.trim();\n if (!brief) {\n throw new Error(\"Inspiredesign workflow requires a non-empty brief.\");\n }\n const urls = normalizeInspiredesignUrls(input.urls);\n const query = typeof input.query === \"string\" && input.query.trim().length > 0 ? input.query.trim() : undefined;\n const providers = normalizeInspiredesignProviders(input.providers);\n const hasExplicitMaxReferences = typeof input.maxReferences !== \"undefined\";\n if (query && input.harvest !== true) {\n throw new Error(\"Inspiredesign workflow query is only supported when harvest is true.\");\n }\n const canonicality = validateProviderScopedUrlCanonicality({ providers, urls });\n if (!canonicality.ok) {\n throw new Error(`Inspiredesign workflow ${canonicality.message}`);\n }\n if (requiresProviderUrlSiteRecipeCompatibility({ providers, urls, query })) {\n if (input.harvest !== true) {\n throw new Error(\"Inspiredesign workflow providers require query unless harvest uses compatible URL recovery.\");\n }\n const compatibility = validateProviderUrlSiteRecipeCompatibility({ providers, urls });\n if (!compatibility.ok) {\n throw new Error(`Inspiredesign workflow ${compatibility.message}`);\n }\n }\n if (input.harvest === true && !query && urls.length === 0) {\n throw new Error(\"Inspiredesign harvest requires query or URL references.\");\n }\n const visualEvidence = normalizeInspiredesignVisualEvidenceMode(\n (input as { visualEvidence?: unknown }).visualEvidence,\n input.harvest\n );\n const maxReferencesFallback = query || input.harvest === true\n ? INSPIREDESIGN_DEFAULT_MAX_REFERENCES\n : urls.length;\n const normalizedBrief = normalizeInspiredesignBriefText(brief);\n const preferredFormatId = shouldReuseInspiredesignBriefExpansion(input.briefExpansion, normalizedBrief)\n ? input.briefExpansion.format.id\n : undefined;\n const briefExpansion = expandInspiredesignBrief(brief, preferredFormatId);\n return {\n ...input,\n brief,\n briefExpansion,\n ...(query ? { query } : {}),\n providers,\n maxReferences: normalizeInspiredesignMaxReferences(input.maxReferences, maxReferencesFallback),\n ...(query || input.harvest === true || hasExplicitMaxReferences\n ? { referenceLimit: normalizeInspiredesignMaxReferences(input.maxReferences, maxReferencesFallback) }\n : {}),\n visualEvidence,\n urls,\n captureMode: resolveInspiredesignCaptureMode(input.captureMode, urls),\n mode: input.mode ?? (input.harvest === true ? \"path\" : \"compact\")\n };\n};\n\nconst isInspiredesignWorkflowEnvelopeInput = (\n input: InspiredesignRunInput | WorkflowResumeEnvelope\n): input is WorkflowResumeEnvelope => {\n return \"kind\" in input && \"input\" in input;\n};\n\nconst buildInspiredesignEnvelope = (\n input: InspiredesignRunInput | WorkflowResumeEnvelope\n): { envelope: WorkflowResumeEnvelope; workflowInput: InspiredesignResolvedInput } => {\n if (isInspiredesignWorkflowEnvelopeInput(input)) {\n if (!isWorkflowResumeEnvelope(input as JsonValue)) {\n throw new Error(\"Inspiredesign workflow envelope is invalid.\");\n }\n if (input.kind !== \"inspiredesign\") {\n throw new Error(`Inspiredesign workflow envelope kind mismatch. Expected inspiredesign but received ${input.kind}.`);\n }\n return {\n envelope: input,\n workflowInput: normalizeInspiredesignInput(parseInspiredesignEnvelopeInput(input.input))\n };\n }\n const workflowInput = normalizeInspiredesignInput(input);\n return {\n envelope: buildWorkflowResumeEnvelope(\"inspiredesign\", serializeInspiredesignRunInput(workflowInput)),\n workflowInput\n };\n};\n\nconst appendWorkflowTrace = (\n trace: WorkflowTraceEntry[],\n stage: WorkflowTraceEntry[\"stage\"],\n event: string,\n details: Record<string, JsonValue>\n): WorkflowTraceEntry[] => [\n ...trace,\n {\n at: new Date().toISOString(),\n stage,\n event,\n details\n }\n];\n\nconst buildInspiredesignStepEnvelope = (\n workflowInput: InspiredesignResolvedInput,\n trace: WorkflowTraceEntry[],\n stepIndex: number,\n url: string\n): WorkflowResumeEnvelope => buildWorkflowResumeEnvelope(\n \"inspiredesign\",\n serializeInspiredesignRunInput(workflowInput),\n {\n checkpoint: {\n stage: \"execute\",\n stepId: \"fetch_reference\",\n stepIndex,\n state: { url },\n updatedAt: new Date().toISOString()\n },\n trace\n }\n);\n\nconst buildInspiredesignFetchOptionsWithScope = (\n workflowInput: InspiredesignResolvedInput,\n envelope: WorkflowResumeEnvelope,\n providerScope: Pick<ProviderRunOptions, \"source\" | \"providerIds\">,\n timeoutMs?: number\n): ProviderRunOptions => (\n withWorkflowResumeEnvelopeIntent(\n withBrowserModeOverride(\n withChallengeAutomationOverride(\n withCookieOverrides({\n ...providerScope,\n ...(typeof timeoutMs === \"number\" ? { timeoutMs } : {})\n }, workflowInput),\n workflowInput\n ),\n workflowInput\n ),\n \"workflow.inspiredesign\",\n envelope\n )\n);\n\nconst buildInspiredesignFetchOptions = (\n workflowInput: InspiredesignResolvedInput,\n envelope: WorkflowResumeEnvelope,\n timeoutMs?: number\n): ProviderRunOptions => {\n const siteRecipeProviderIds = new Set(\n workflowInput.providers.filter((providerId) => resolveSiteRecipeForProvider(providerId) !== undefined)\n );\n const standardProviderIds = workflowInput.providers.filter((providerId) => !siteRecipeProviderIds.has(providerId));\n let providerScope: Pick<ProviderRunOptions, \"source\" | \"providerIds\"> = {};\n if (workflowInput.providers.length > 0 && standardProviderIds.length === 0) {\n providerScope = { source: \"web\" };\n } else if (standardProviderIds.length > 0) {\n providerScope = { providerIds: standardProviderIds };\n }\n return buildInspiredesignFetchOptionsWithScope(workflowInput, envelope, providerScope, timeoutMs);\n};\n\nconst buildInspiredesignSiteRecipeFetchOptions = (\n workflowInput: InspiredesignResolvedInput,\n envelope: WorkflowResumeEnvelope,\n timeoutMs?: number\n): ProviderRunOptions => buildInspiredesignFetchOptionsWithScope(\n workflowInput,\n envelope,\n { source: \"web\" },\n timeoutMs\n);\n\nconst buildInspiredesignReferenceFetchOptions = (\n workflowInput: InspiredesignResolvedInput,\n envelope: WorkflowResumeEnvelope,\n url: string,\n timeoutMs?: number\n): ProviderRunOptions => (\n resolveSiteRecipeForUrl(url)\n ? buildInspiredesignSiteRecipeFetchOptions(workflowInput, envelope, timeoutMs)\n : buildInspiredesignFetchOptions(workflowInput, envelope, timeoutMs)\n);\n\ntype InspiredesignDiscoveryDiagnostics = {\n requested: boolean;\n searchAvailable: boolean;\n query?: string;\n providers: string[];\n acceptedUrls: string[];\n rejected: InspiredesignDiscoveryResult[\"rejected\"];\n failures: ProviderFailureEntry[];\n failure?: string;\n siteRecipeId?: string;\n browserNativeDiagnostics?: Record<string, JsonValue>;\n};\n\nconst emptyInspiredesignDiscoveryDiagnostics = (\n workflowInput: InspiredesignResolvedInput,\n searchAvailable: boolean,\n failure?: string\n): InspiredesignDiscoveryDiagnostics => ({\n requested: Boolean(workflowInput.query),\n searchAvailable,\n ...(workflowInput.query ? { query: workflowInput.query } : {}),\n providers: workflowInput.providers,\n acceptedUrls: [],\n rejected: [],\n failures: [],\n ...(failure ? { failure } : {})\n});\n\nconst providerFromInspiredesignDiscoveryFailure = (\n workflowInput: InspiredesignResolvedInput,\n error: ProviderError\n): { provider: string; source: ProviderSource } | undefined => {\n const provider = error.provider ?? workflowInput.providers[0];\n const source = error.source ?? (provider ? toProviderSource(provider) : null);\n return provider && source ? { provider, source } : undefined;\n};\n\nconst failureFromInspiredesignDiscoveryError = (\n workflowInput: InspiredesignResolvedInput,\n error: ProviderError | undefined\n): ProviderFailureEntry[] => {\n if (!error) return [];\n const provider = providerFromInspiredesignDiscoveryFailure(workflowInput, error);\n if (!provider) return [];\n return [{\n provider: provider.provider,\n source: provider.source,\n error\n }];\n};\n\nconst providerFromInspiredesignFetchFailure = (\n result: ProviderAggregateResult\n): { provider: string; source: ProviderSource } | undefined => {\n const provider = result.error?.provider ?? result.providerOrder[0];\n const source = result.error?.source ?? (provider ? toProviderSource(provider) : null);\n return provider && source ? { provider, source } : undefined;\n};\n\nconst failureFromInspiredesignFetchError = (\n result: ProviderAggregateResult\n): ProviderFailureEntry[] => {\n if (!result.error || result.failures.length > 0) return [];\n const provider = providerFromInspiredesignFetchFailure(result);\n if (!provider) return [];\n return [{\n provider: provider.provider,\n source: provider.source,\n error: result.error\n }];\n};\n\nconst normalizeSiteRecipeFetchFailures = (\n siteRecipe: SiteRecipe,\n failures: ProviderFailureEntry[]\n): ProviderFailureEntry[] => {\n const source = toProviderSource(siteRecipe.id) ?? \"web\";\n return failures.map((failure) => ({\n provider: siteRecipe.id,\n source,\n error: {\n ...failure.error,\n provider: siteRecipe.id,\n source,\n details: {\n ...(failure.error.details ?? {}),\n upstreamProvider: failure.provider,\n upstreamSource: failure.source\n }\n }\n }));\n};\n\ntype InspiredesignAcceptedDiscovery = InspiredesignDiscoveryResult[\"accepted\"][number];\n\nconst appendNextUniqueDiscoveryCandidate = (\n queue: InspiredesignAcceptedDiscovery[],\n cursor: number,\n seen: Set<string>,\n accepted: InspiredesignAcceptedDiscovery[]\n): number => {\n let nextCursor = cursor;\n while (nextCursor < queue.length) {\n const candidate = queue[nextCursor];\n nextCursor += 1;\n if (!candidate || seen.has(candidate.url)) continue;\n seen.add(candidate.url);\n accepted.push(candidate);\n return nextCursor;\n }\n return nextCursor;\n};\n\nconst capMixedInspiredesignDiscovery = (\n siteDiscovery: InspiredesignDiscoveryResult,\n standardDiscovery: InspiredesignDiscoveryResult,\n maxReferences: number\n): InspiredesignDiscoveryResult => {\n const accepted: InspiredesignDiscoveryResult[\"accepted\"] = [];\n const seen = new Set<string>();\n let siteCursor = 0;\n let standardCursor = 0;\n while (\n accepted.length < maxReferences\n && (siteCursor < siteDiscovery.accepted.length || standardCursor < standardDiscovery.accepted.length)\n ) {\n siteCursor = appendNextUniqueDiscoveryCandidate(siteDiscovery.accepted, siteCursor, seen, accepted);\n if (accepted.length >= maxReferences) break;\n standardCursor = appendNextUniqueDiscoveryCandidate(standardDiscovery.accepted, standardCursor, seen, accepted);\n }\n return {\n accepted,\n rejected: [...siteDiscovery.rejected, ...standardDiscovery.rejected]\n };\n};\n\nconst filterStandardDiscoveryForSiteRecipe = (\n siteRecipe: SiteRecipe,\n discovery: InspiredesignDiscoveryResult\n): InspiredesignDiscoveryResult => {\n if (siteRecipe.id !== \"social/pinterest\") return discovery;\n\n const accepted: InspiredesignDiscoveryResult[\"accepted\"] = [];\n const rejected: InspiredesignDiscoveryResult[\"rejected\"] = [...discovery.rejected];\n discovery.accepted.forEach((candidate) => {\n if (!isNonCanonicalPinterestLikeUrl(candidate.url)) {\n accepted.push(candidate);\n return;\n }\n rejected.push({\n status: \"rejected\",\n reason: \"invalid_url\",\n rawUrl: candidate.url,\n ...(candidate.title ? { title: candidate.title } : {}),\n source: candidate.source,\n provider: candidate.provider,\n rank: candidate.rank\n });\n });\n return { accepted, rejected };\n};\n\nconst discoverInspiredesignReferences = async (\n runtime: ReferenceRetrievalPort,\n workflowInput: InspiredesignResolvedInput,\n envelope: WorkflowResumeEnvelope,\n timeoutMs?: number\n): Promise<InspiredesignDiscoveryDiagnostics> => {\n if (!workflowInput.query) {\n return emptyInspiredesignDiscoveryDiagnostics(workflowInput, typeof runtime.search === \"function\");\n }\n const query = workflowInput.query;\n const siteRecipe = workflowInput.providers\n .map((providerId) => resolveSiteRecipeForProvider(providerId))\n .find((recipe) => recipe !== undefined);\n const siteRecipeProviderIds = new Set(\n workflowInput.providers.filter((providerId) => resolveSiteRecipeForProvider(providerId) !== undefined)\n );\n const standardProviderIds = workflowInput.providers.filter((providerId) => !siteRecipeProviderIds.has(providerId));\n if (siteRecipe) {\n const runSiteRecipeDiscovery = async (): Promise<BrowserNativeDiscoveryResult> => runBrowserNativeDiscovery({\n recipe: siteRecipe,\n query,\n maxReferences: workflowInput.referenceLimit ?? workflowInput.maxReferences,\n ...(workflowInput.browserMode ? { browserMode: workflowInput.browserMode } : {}),\n ...(typeof workflowInput.useCookies === \"boolean\" ? { useCookies: workflowInput.useCookies } : {}),\n ...(workflowInput.cookiePolicyOverride ? { cookiePolicy: workflowInput.cookiePolicyOverride } : {}),\n fetchSearchPage: async (url) => {\n const result = normalizeInspiredesignFetchResult(await runtime.fetch(\n { url },\n buildInspiredesignSiteRecipeFetchOptions(workflowInput, envelope, timeoutMs)\n ));\n const failures = result.failures.length > 0 ? result.failures : failureFromInspiredesignFetchError(result);\n return {\n records: result.records,\n failures: normalizeSiteRecipeFetchFailures(siteRecipe, failures),\n ...(result.error?.message ? { errorMessage: result.error.message } : {})\n };\n }\n });\n if (standardProviderIds.length > 0 && typeof runtime.search === \"function\") {\n try {\n const searchResult = await runtime.search(\n {\n query,\n limit: workflowInput.maxReferences\n },\n {\n ...buildInspiredesignFetchOptions(workflowInput, envelope, timeoutMs),\n providerIds: standardProviderIds\n }\n );\n const searchFailures = searchResult.failures.length > 0\n ? searchResult.failures\n : failureFromInspiredesignDiscoveryError({ ...workflowInput, providers: standardProviderIds }, searchResult.error);\n const discovery = filterStandardDiscoveryForSiteRecipe(\n siteRecipe,\n normalizeInspiredesignDiscoveryRecords(searchResult.records)\n );\n const siteResult = await runSiteRecipeDiscovery();\n const siteDiscovery = normalizeInspiredesignDiscoveryRecords(siteResult.records);\n const combinedDiscovery = capMixedInspiredesignDiscovery(\n siteDiscovery,\n discovery,\n workflowInput.referenceLimit ?? workflowInput.maxReferences\n );\n const failures = [...searchFailures, ...siteResult.failures];\n return {\n requested: true,\n searchAvailable: true,\n query,\n providers: workflowInput.providers,\n acceptedUrls: combinedDiscovery.accepted.map((candidate) => candidate.url),\n rejected: combinedDiscovery.rejected,\n failures,\n ...(failures[0]?.error.message ? { failure: failures[0].error.message } : {}),\n siteRecipeId: siteRecipe.id,\n browserNativeDiagnostics: {\n ...siteResult.diagnostics,\n standardAcceptedCount: discovery.accepted.length,\n standardRejectedCount: discovery.rejected.length,\n siteAcceptedCount: siteDiscovery.accepted.length,\n cappedAcceptedCount: combinedDiscovery.accepted.length\n }\n };\n } catch (error) {\n const siteResult = await runSiteRecipeDiscovery();\n const discovery = normalizeInspiredesignDiscoveryRecords(siteResult.records);\n return {\n requested: true,\n searchAvailable: true,\n query,\n providers: workflowInput.providers,\n acceptedUrls: discovery.accepted.map((candidate) => candidate.url),\n rejected: discovery.rejected,\n failures: siteResult.failures,\n failure: error instanceof Error ? error.message : \"Reference discovery failed.\",\n siteRecipeId: siteRecipe.id,\n browserNativeDiagnostics: siteResult.diagnostics\n };\n }\n }\n const siteResult = await runSiteRecipeDiscovery();\n const discovery = normalizeInspiredesignDiscoveryRecords(siteResult.records);\n return {\n requested: true,\n searchAvailable: true,\n query,\n providers: workflowInput.providers,\n acceptedUrls: discovery.accepted.map((candidate) => candidate.url),\n rejected: discovery.rejected,\n failures: siteResult.failures,\n ...(siteResult.failures[0]?.error.message ? { failure: siteResult.failures[0].error.message } : {}),\n siteRecipeId: siteRecipe.id,\n browserNativeDiagnostics: siteResult.diagnostics\n };\n }\n if (typeof runtime.search !== \"function\") {\n return emptyInspiredesignDiscoveryDiagnostics(\n workflowInput,\n false,\n \"Reference discovery requested, but provider search is unavailable in this execution lane.\"\n );\n }\n let searchResult: ProviderAggregateResult;\n try {\n searchResult = await runtime.search(\n {\n query: workflowInput.query,\n limit: workflowInput.maxReferences\n },\n {\n ...buildInspiredesignFetchOptions(workflowInput, envelope, timeoutMs),\n ...(workflowInput.providers.length > 0 ? { providerIds: workflowInput.providers } : {})\n }\n );\n } catch (error) {\n return emptyInspiredesignDiscoveryDiagnostics(\n workflowInput,\n true,\n error instanceof Error ? error.message : \"Reference discovery failed.\"\n );\n }\n const discovery = normalizeInspiredesignDiscoveryRecords(searchResult.records);\n const discoveryFailures = searchResult.failures.length > 0\n ? searchResult.failures\n : failureFromInspiredesignDiscoveryError(workflowInput, searchResult.error);\n return {\n requested: true,\n searchAvailable: true,\n query: workflowInput.query,\n providers: workflowInput.providers,\n acceptedUrls: discovery.accepted.map((candidate) => candidate.url),\n rejected: discovery.rejected,\n failures: discoveryFailures,\n ...(searchResult.error?.message ? { failure: searchResult.error.message } : {})\n };\n};\n\nconst buildEmptyInspiredesignCaptureAttemptCounts = (): InspiredesignCaptureAttemptCounts => ({\n snapshot: { captured: 0, failed: 0, skipped: 0 },\n clone: { captured: 0, failed: 0, skipped: 0 },\n dom: { captured: 0, failed: 0, skipped: 0 }\n});\n\nconst buildUnavailableInspiredesignCaptureEvidence = (): InspiredesignCaptureEvidence => ({\n attempts: {\n snapshot: { status: \"skipped\", detail: INSPIREDESIGN_CAPTURE_UNAVAILABLE_FAILURE },\n clone: { status: \"skipped\", detail: INSPIREDESIGN_CAPTURE_UNAVAILABLE_FAILURE },\n dom: { status: \"skipped\", detail: INSPIREDESIGN_CAPTURE_UNAVAILABLE_FAILURE }\n }\n});\n\nconst getInspiredesignReferenceId = (url: string): string => (\n createHash(\"sha256\").update(url).digest(\"hex\").slice(0, 12)\n);\n\nconst buildVisualPolicyMetadata = (\n decision: InspiredesignVisualPolicyDecision\n): InspiredesignVisualEvidenceRuntimeMetadata | undefined => {\n if (decision.status === \"allowed\") return undefined;\n return {\n status: decision.status,\n kind: \"viewport\",\n fullPage: false,\n capturedAt: new Date().toISOString(),\n warnings: [`policy:${decision.reason}`],\n failure: decision.message\n };\n};\n\nconst mergeCaptureVisualEvidence = (\n capture: InspiredesignCaptureEvidence | null | undefined,\n visual: InspiredesignVisualEvidenceRuntimeMetadata | InspiredesignPersistedVisualEvidence | undefined\n): InspiredesignCaptureEvidence | null | undefined => {\n if (!visual) return capture;\n return {\n ...(capture ?? {}),\n visual\n };\n};\n\nconst isVisualPolicyBlockerDecision = (decision: InspiredesignVisualPolicyDecision): boolean => (\n INSPIREDESIGN_VISUAL_POLICY_BLOCKER_REASONS.has(decision.reason)\n);\n\nconst buildMissingRequiredVisualEvidence = (\n failure: string,\n _visualPlan: InspiredesignVisualCapturePlan\n): InspiredesignVisualEvidenceRuntimeMetadata => ({\n status: \"failed\",\n kind: \"viewport\",\n fullPage: false,\n capturedAt: new Date().toISOString(),\n warnings: [\"required_visual_evidence_missing\"],\n failure\n});\n\nconst getRequiredVisualEvidenceFailure = (\n workflowInput: InspiredesignResolvedInput,\n visualPlan: InspiredesignVisualCapturePlan,\n capture: InspiredesignCaptureEvidence | null | undefined\n): string | undefined => {\n if (workflowInput.visualEvidence !== \"required\" || visualPlan.policy.status !== \"allowed\") return undefined;\n const visual = normalizeInspiredesignCaptureEvidence(capture)?.visual;\n if (!visual) return REQUIRED_VISUAL_EVIDENCE_MISSING_FAILURE;\n if (visual.status === \"captured\") return undefined;\n return visual.failure ?? REQUIRED_VISUAL_EVIDENCE_MISSING_FAILURE;\n};\n\nconst addRequiredVisualEvidenceFailure = (\n capture: InspiredesignCaptureEvidence | null | undefined,\n visualPlan: InspiredesignVisualCapturePlan,\n failure: string\n): InspiredesignCaptureEvidence | null | undefined => {\n const visual = normalizeInspiredesignCaptureEvidence(capture)?.visual;\n if (visual) return capture;\n return mergeCaptureVisualEvidence(capture, buildMissingRequiredVisualEvidence(failure, visualPlan));\n};\n\nconst VISUAL_TEMP_PATH_MISMATCH_FAILURE =\n \"Visual evidence temp path did not match the workflow capture plan.\";\nconst VISUAL_KIND_MISMATCH_FAILURE =\n \"Visual evidence kind did not match the workflow capture contract.\";\n\nconst hasTrustedVisualTempPath = (\n visual: InspiredesignVisualEvidenceRuntimeMetadata,\n visualPlan: InspiredesignVisualCapturePlan\n): boolean => {\n if (visual.status === \"captured\" && !visual.tempPath) return false;\n if (!visual.tempPath) return true;\n if (!visualPlan.tempPath) return false;\n return resolve(visual.tempPath) === resolve(visualPlan.tempPath);\n};\n\nconst hasTrustedVisualKind = (\n visual: InspiredesignVisualEvidenceRuntimeMetadata\n): boolean => isInspiredesignVisualEvidenceKind((visual as { kind?: unknown }).kind);\n\nconst readRuntimeVisualWarnings = (\n visual: InspiredesignVisualEvidenceRuntimeMetadata\n): string[] => {\n const warnings = (visual as { warnings?: unknown }).warnings;\n return Array.isArray(warnings) ? warnings.filter((warning): warning is string => typeof warning === \"string\") : [];\n};\n\nconst failMismatchedVisualTempPath = (\n visual: InspiredesignVisualEvidenceRuntimeMetadata,\n failure = VISUAL_TEMP_PATH_MISMATCH_FAILURE,\n warning = \"visual_temp_path_mismatch\"\n): InspiredesignVisualEvidenceRuntimeMetadata => ({\n status: \"failed\",\n kind: hasTrustedVisualKind(visual) ? visual.kind : \"viewport\",\n fullPage: visual.fullPage,\n capturedAt: visual.capturedAt,\n warnings: [...readRuntimeVisualWarnings(visual), warning],\n failure\n});\n\nconst trustRuntimeVisualEvidence = (\n visual: InspiredesignVisualEvidenceRuntimeMetadata | undefined,\n visualPlan: InspiredesignVisualCapturePlan\n): InspiredesignVisualEvidenceRuntimeMetadata | undefined => {\n if (!visual) return undefined;\n if (!hasTrustedVisualKind(visual)) {\n return failMismatchedVisualTempPath(\n visual,\n VISUAL_KIND_MISMATCH_FAILURE,\n \"visual_kind_mismatch\"\n );\n }\n return hasTrustedVisualTempPath(visual, visualPlan)\n ? visual\n : failMismatchedVisualTempPath(visual);\n};\n\nconst PRE_ARTIFACT_CAPTURE_SKIP_MESSAGE =\n \"Skipped after deep capture failed before artifact capture started.\";\n\nconst buildFailedInspiredesignCaptureEvidence = (\n detail: string\n): InspiredesignCaptureEvidence => ({\n attempts: {\n snapshot: { status: \"failed\", detail },\n clone: { status: \"skipped\", detail: PRE_ARTIFACT_CAPTURE_SKIP_MESSAGE },\n dom: { status: \"skipped\", detail: PRE_ARTIFACT_CAPTURE_SKIP_MESSAGE }\n }\n});\n\nconst describeInspiredesignCaptureAttempts = (\n key: InspiredesignCaptureAttemptKey,\n counts: Record<InspiredesignCaptureAttemptStatus, number>,\n statuses: InspiredesignCaptureAttemptStatus[]\n): string | null => {\n const parts = statuses\n .filter((status) => counts[status] > 0)\n .map((status) => `${status} ${counts[status]}`);\n if (parts.length === 0) return null;\n return `${key} (${parts.join(\", \")})`;\n};\n\nconst summarizeInspiredesignCaptureAttempts = (\n references: InspiredesignReferenceEvidence[]\n): {\n counts: InspiredesignCaptureAttemptCounts;\n worked: string[];\n didNotWork: string[];\n summary: string;\n} | undefined => {\n const counts = buildEmptyInspiredesignCaptureAttemptCounts();\n let hasAttempts = false;\n for (const reference of references) {\n const attempts = normalizeInspiredesignCaptureEvidence(reference.capture)?.attempts;\n if (!attempts) continue;\n hasAttempts = true;\n for (const key of INSPIREDESIGN_CAPTURE_ATTEMPT_KEYS) {\n counts[key][attempts[key].status] += 1;\n }\n }\n if (!hasAttempts) return undefined;\n const worked = INSPIREDESIGN_CAPTURE_ATTEMPT_KEYS\n .map((key) => describeInspiredesignCaptureAttempts(key, counts[key], [\"captured\"]))\n .filter((value): value is string => value !== null);\n const didNotWork = INSPIREDESIGN_CAPTURE_ATTEMPT_KEYS\n .map((key) => describeInspiredesignCaptureAttempts(key, counts[key], [\"failed\", \"skipped\"]))\n .filter((value): value is string => value !== null);\n return {\n counts,\n worked,\n didNotWork,\n summary: formatInspiredesignCaptureAttemptSummary({ worked, didNotWork })\n };\n};\n\nconst captureInspiredesignReference = async (\n url: string,\n captureMode: InspiredesignCaptureMode,\n workflowInput: InspiredesignResolvedInput,\n captureReference: InspiredesignWorkflowOptions[\"captureReference\"],\n visualPlan: InspiredesignVisualCapturePlan,\n timeoutMs?: number\n): Promise<InspiredesignCaptureOutcome> => {\n const visualPolicyMetadata = buildVisualPolicyMetadata(visualPlan.policy);\n if (captureMode === \"off\") {\n return visualPolicyMetadata\n ? { captureStatus: \"off\", capture: { visual: visualPolicyMetadata } }\n : { captureStatus: \"off\" };\n }\n if (visualPolicyMetadata && isVisualPolicyBlockerDecision(visualPlan.policy)) {\n const captureStatus = visualPlan.policy.status === \"failed\" ? \"failed\" : \"off\";\n return {\n captureStatus,\n ...(captureStatus === \"failed\" ? { captureFailure: visualPlan.policy.message } : {}),\n capture: { visual: visualPolicyMetadata }\n };\n }\n if (!captureReference) {\n const visualFailureMetadata = visualPolicyMetadata\n ?? (workflowInput.visualEvidence === \"required\" && visualPlan.policy.status === \"allowed\"\n ? buildMissingRequiredVisualEvidence(INSPIREDESIGN_CAPTURE_UNAVAILABLE_FAILURE, visualPlan)\n : undefined);\n return {\n captureStatus: \"failed\",\n captureFailure: INSPIREDESIGN_CAPTURE_UNAVAILABLE_FAILURE,\n capture: mergeCaptureVisualEvidence(\n buildUnavailableInspiredesignCaptureEvidence(),\n visualFailureMetadata\n )\n };\n }\n try {\n const rawCapture = await captureReference(url, {\n timeoutMs,\n useCookies: workflowInput.useCookies,\n challengeAutomationMode: workflowInput.challengeAutomationMode,\n cookiePolicyOverride: workflowInput.cookiePolicyOverride,\n visualEvidence: visualPlan.policy.status === \"allowed\" ? workflowInput.visualEvidence : \"off\",\n visualEvidencePath: visualPlan.policy.status === \"allowed\" ? visualPlan.tempPath : undefined\n });\n const capture = normalizeInspiredesignCaptureEvidence(rawCapture);\n const runtimeVisual = rawCapture?.visual as InspiredesignVisualEvidenceRuntimeMetadata | undefined;\n const trustedRuntimeVisual = trustRuntimeVisualEvidence(runtimeVisual, visualPlan);\n const captureWithRuntimeVisual = trustedRuntimeVisual\n ? mergeCaptureVisualEvidence(capture, trustedRuntimeVisual)\n : capture;\n const captureWithVisualPolicy = trustedRuntimeVisual\n ? captureWithRuntimeVisual\n : mergeCaptureVisualEvidence(captureWithRuntimeVisual, visualPolicyMetadata);\n const requiredVisualFailure = getRequiredVisualEvidenceFailure(workflowInput, visualPlan, captureWithVisualPolicy);\n const captureWithRequiredVisual = requiredVisualFailure\n ? addRequiredVisualEvidenceFailure(captureWithVisualPolicy, visualPlan, requiredVisualFailure)\n : captureWithVisualPolicy;\n if (!hasInspiredesignCaptureArtifacts(capture)) {\n return {\n captureStatus: \"failed\",\n captureFailure: \"Deep capture did not return usable snapshot, DOM, or clone evidence.\",\n ...(captureWithRequiredVisual ? { capture: captureWithRequiredVisual } : {})\n };\n }\n if (requiredVisualFailure) {\n return {\n captureStatus: \"failed\",\n captureFailure: requiredVisualFailure,\n ...(captureWithRequiredVisual ? { capture: captureWithRequiredVisual } : {})\n };\n }\n return {\n captureStatus: \"captured\",\n ...(captureWithRequiredVisual ? { capture: captureWithRequiredVisual } : {})\n };\n } catch (error) {\n const captureFailure = error instanceof Error && error.message.trim()\n ? error.message\n : \"Deep capture failed.\";\n const visualFailureMetadata = visualPolicyMetadata\n ?? (workflowInput.visualEvidence === \"required\" && visualPlan.policy.status === \"allowed\"\n ? buildMissingRequiredVisualEvidence(captureFailure, visualPlan)\n : undefined);\n return {\n captureStatus: \"failed\",\n captureFailure,\n capture: mergeCaptureVisualEvidence(\n buildFailedInspiredesignCaptureEvidence(captureFailure),\n visualFailureMetadata\n )\n };\n }\n};\n\nconst getInspiredesignPrimaryRecord = (\n result: ProviderAggregateResult,\n url: string\n): NormalizedRecord | undefined => {\n const canonicalUrl = canonicalizeUrl(url);\n return result.records.find((record) => record.url && canonicalizeUrl(record.url) === canonicalUrl) ?? result.records[0];\n};\n\nconst summarizeInspiredesignIssueSnippet = (record: NormalizedRecord): string | undefined => {\n const content = normalizePlainText(record.content);\n if (!content) return undefined;\n return toSnippet(content, 240);\n};\n\nconst scoreInspiredesignIssueHint = (hint: ProviderIssueHint): number => {\n if (hint.reasonCode === \"token_required\" || hint.reasonCode === \"auth_required\") return 3;\n if (hint.reasonCode === \"challenge_detected\") return 2;\n if (hint.constraint?.kind === \"render_required\") return 1;\n return 0;\n};\n\nconst toInspiredesignIssueFailure = (\n record: NormalizedRecord,\n hint: ProviderIssueHint\n): ProviderFailureEntry => {\n const issueSnippet = summarizeInspiredesignIssueSnippet(record);\n const details: Record<string, JsonValue> = {\n reasonCode: hint.reasonCode,\n ...(record.url ? { url: record.url } : {}),\n ...(record.title ? { title: record.title } : {}),\n ...(issueSnippet ? { message: issueSnippet } : {}),\n ...(typeof record.attributes.providerShell === \"string\"\n ? { providerShell: record.attributes.providerShell }\n : {}),\n ...(record.attributes.browserRequired === true ? { browserRequired: true } : {}),\n ...(hint.blockerType ? { blockerType: hint.blockerType } : {}),\n ...(hint.constraint ? { constraint: hint.constraint } : {})\n };\n\n return {\n provider: record.provider,\n source: record.source,\n error: {\n code: hint.reasonCode === \"token_required\" || hint.reasonCode === \"auth_required\"\n ? \"auth\"\n : \"unavailable\",\n message: issueSnippet ?? record.title ?? \"Fetched reference content was not usable inspiration evidence.\",\n retryable: false,\n reasonCode: hint.reasonCode,\n details\n }\n };\n};\n\nconst normalizeInspiredesignFetchResult = (\n result: ProviderAggregateResult\n): ProviderAggregateResult => {\n if (result.records.length === 0) {\n const synthesizedFailures = failureFromInspiredesignFetchError(result);\n return synthesizedFailures.length > 0\n ? {\n ...result,\n failures: synthesizedFailures\n }\n : result;\n }\n\n const usableRecords: NormalizedRecord[] = [];\n const unusableRecords: Array<{ record: NormalizedRecord; hint: ProviderIssueHint }> = [];\n\n for (const record of result.records) {\n const hint = readProviderIssueHintFromRecord(record);\n if (hint) {\n unusableRecords.push({ record, hint });\n continue;\n }\n usableRecords.push(record);\n }\n\n if (unusableRecords.length === 0) {\n return result;\n }\n\n if (usableRecords.length > 0) {\n return {\n ...result,\n records: usableRecords\n };\n }\n\n const topUnusableRecord = unusableRecords\n .slice()\n .sort((left, right) => scoreInspiredesignIssueHint(right.hint) - scoreInspiredesignIssueHint(left.hint))[0];\n const hasPrimaryIssue = Boolean(summarizePrimaryProviderIssue(result.failures));\n const synthesizedFailure = !hasPrimaryIssue && topUnusableRecord\n ? toInspiredesignIssueFailure(topUnusableRecord.record, topUnusableRecord.hint)\n : undefined;\n\n return {\n ...result,\n ok: false,\n records: [],\n failures: synthesizedFailure ? [...result.failures, synthesizedFailure] : result.failures,\n ...(result.error ? {} : synthesizedFailure ? { error: synthesizedFailure.error } : {})\n };\n};\n\nconst summarizeInspiredesignFetchFailure = (result: ProviderAggregateResult): string | undefined => {\n return summarizePrimaryProviderIssue(result.failures)?.summary\n ?? result.error?.message;\n};\n\nconst excerptFromInspiredesignRecord = (record: NormalizedRecord | undefined): string | undefined => {\n const content = normalizePlainText(record?.content);\n if (!content) return undefined;\n return toSnippet(content, 240);\n};\n\nconst captureSnippet = (\n value: string | undefined,\n maxLength: number\n): string | undefined => {\n const content = normalizePlainText(value);\n if (!content) return undefined;\n return toSnippet(content, maxLength);\n};\n\nconst titleFromInspiredesignCapture = (\n capture: InspiredesignCaptureEvidence | null | undefined\n): string | undefined => {\n return captureSnippet(capture?.title, 120)\n ?? captureSnippet(capture?.snapshot?.content, 120)\n ?? captureSnippet(capture?.dom?.outerHTML, 120)\n ?? captureSnippet(capture?.clone?.componentPreview, 120)\n ?? captureSnippet(capture?.clone?.cssPreview, 120);\n};\n\nconst excerptFromInspiredesignCapture = (\n capture: InspiredesignCaptureEvidence | null | undefined\n): string | undefined => {\n return captureSnippet(capture?.snapshot?.content, 240)\n ?? captureSnippet(capture?.dom?.outerHTML, 240)\n ?? captureSnippet(capture?.clone?.componentPreview, 240)\n ?? captureSnippet(capture?.clone?.cssPreview, 240);\n};\n\nconst isInspiredesignFetchRecovered = (\n reference: InspiredesignReferenceEvidence\n): boolean => {\n return reference.fetchStatus === \"failed\"\n && reference.captureStatus === \"captured\"\n && hasInspiredesignUsableReferenceEvidence(reference);\n};\n\ntype InspiredesignRecoveredFetchTelemetry = {\n url: string;\n fetchFailure?: string;\n};\n\nconst summarizeInspiredesignRecoveredFetches = (\n references: InspiredesignReferenceEvidence[]\n): InspiredesignRecoveredFetchTelemetry[] => references\n .filter(isInspiredesignFetchRecovered)\n .map((reference) => ({\n url: reference.url,\n ...(reference.fetchFailure ? { fetchFailure: reference.fetchFailure } : {})\n }));\n\nconst buildInspiredesignReference = (\n url: string,\n result: ProviderAggregateResult,\n capture: InspiredesignCaptureOutcome\n): InspiredesignReferenceEvidence => {\n const primary = getInspiredesignPrimaryRecord(result, url);\n const baseCapture = normalizeInspiredesignCaptureEvidence(capture.capture);\n const runtimeVisual = capture.capture?.visual as InspiredesignVisualEvidenceRuntimeMetadata | undefined;\n const normalizedCapture = runtimeVisual?.tempPath\n ? mergeCaptureVisualEvidence(baseCapture, runtimeVisual)\n : baseCapture;\n const title = normalizePlainText(primary?.title) || titleFromInspiredesignCapture(normalizedCapture);\n const excerpt = excerptFromInspiredesignRecord(primary)\n ?? excerptFromInspiredesignCapture(normalizedCapture);\n const fetchStatus: InspiredesignReferenceEvidence[\"fetchStatus\"] = result.records.length > 0 ? \"captured\" : \"failed\";\n return {\n id: getInspiredesignReferenceId(url),\n url,\n ...(title ? { title } : {}),\n ...(excerpt ? { excerpt } : {}),\n fetchStatus,\n captureStatus: capture.captureStatus,\n ...(fetchStatus === \"failed\" && summarizeInspiredesignFetchFailure(result)\n ? { fetchFailure: summarizeInspiredesignFetchFailure(result) }\n : {}),\n ...(capture.captureFailure ? { captureFailure: capture.captureFailure } : {}),\n ...(normalizedCapture ? { capture: normalizedCapture } : {})\n };\n};\n\nconst failReferenceForRequiredVisualEvidence = (\n reference: InspiredesignReferenceEvidence,\n failure: string,\n visualEvidence: InspiredesignVisualEvidenceMode,\n shouldFail = true\n): InspiredesignReferenceEvidence => {\n if (visualEvidence !== \"required\" || !shouldFail) return reference;\n return {\n ...reference,\n captureStatus: \"failed\",\n captureFailure: reference.captureFailure ?? failure\n };\n};\n\nconst isPolicySkippedVisualEvidence = (\n visual: InspiredesignVisualEvidenceRuntimeMetadata | InspiredesignPersistedVisualEvidence\n): boolean => visual.status === \"skipped\" && visual.warnings.some((warning) => warning.startsWith(\"policy:\"));\n\nconst finalizeInspiredesignReferenceVisual = async (\n reference: InspiredesignReferenceEvidence,\n visualEvidence: InspiredesignVisualEvidenceMode\n): Promise<{ reference: InspiredesignReferenceEvidence; file?: ArtifactFile }> => {\n const visual = reference.capture?.visual;\n if (!visual) {\n return { reference };\n }\n const runtimeVisual = visual as InspiredesignVisualEvidenceRuntimeMetadata;\n if (visual.status !== \"captured\" || !runtimeVisual.tempPath) {\n const persisted = persistInspiredesignVisualEvidence(visual);\n const referenceWithPersistedVisual = {\n ...reference,\n capture: mergeCaptureVisualEvidence(reference.capture, persisted)\n };\n return {\n reference: failReferenceForRequiredVisualEvidence(\n referenceWithPersistedVisual,\n persisted.failure ?? REQUIRED_VISUAL_EVIDENCE_MISSING_FAILURE,\n visualEvidence,\n !isPolicySkippedVisualEvidence(persisted)\n )\n };\n }\n const artifactPath = buildVisualEvidenceArtifactPath(reference.id, visual.kind);\n try {\n const buffer = await readFile(runtimeVisual.tempPath);\n if (buffer.byteLength === 0) {\n throw new Error(\"Visual evidence screenshot file was empty.\");\n }\n const persisted = persistInspiredesignVisualEvidence(visual, {\n artifactPath,\n sha256: hashVisualEvidenceBuffer(buffer),\n bytes: buffer.byteLength\n });\n return {\n reference: {\n ...reference,\n capture: mergeCaptureVisualEvidence(reference.capture, persisted)\n },\n file: {\n path: artifactPath,\n content: buffer\n }\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message.trim() : \"\";\n const failure = errorMessage === \"Visual evidence screenshot file was empty.\"\n ? errorMessage\n : \"Visual evidence screenshot file was unavailable.\";\n const persisted = persistInspiredesignVisualEvidence({\n ...visual,\n status: \"failed\",\n warnings: [...readRuntimeVisualWarnings(runtimeVisual), \"finalize_failed\"],\n failure\n });\n const referenceWithPersistedVisual = {\n ...reference,\n capture: mergeCaptureVisualEvidence(reference.capture, persisted)\n };\n return {\n reference: failReferenceForRequiredVisualEvidence(referenceWithPersistedVisual, failure, visualEvidence)\n };\n }\n};\n\nconst finalizeInspiredesignVisualArtifacts = async (\n references: InspiredesignReferenceEvidence[],\n visualEvidence: InspiredesignVisualEvidenceMode\n): Promise<InspiredesignVisualArtifactCollation> => {\n const finalized = await Promise.all(\n references.map((reference) => finalizeInspiredesignReferenceVisual(reference, visualEvidence))\n );\n return {\n references: finalized.map((entry) => entry.reference),\n files: finalized.map((entry) => entry.file).filter((file): file is ArtifactFile => Boolean(file))\n };\n};\n\nconst buildInspiredesignVisualCapturePlan = (\n url: string,\n workflowInput: InspiredesignResolvedInput,\n result: ProviderAggregateResult,\n visualEvidenceTempDir: string | undefined\n): InspiredesignVisualCapturePlan => {\n const referenceId = getInspiredesignReferenceId(url);\n const policy = decideInspiredesignVisualCapturePolicy({\n visualEvidence: workflowInput.visualEvidence,\n failures: result.failures,\n topLevelError: result.error,\n cookiePolicy: workflowInput.cookiePolicyOverride,\n hasUsableRecords: result.records.length > 0\n });\n if (policy.status !== \"allowed\" || !visualEvidenceTempDir) {\n return { policy, referenceId };\n }\n return {\n policy,\n referenceId,\n tempPath: join(visualEvidenceTempDir, `${referenceId}-viewport.png`)\n };\n};\n\nconst summarizeInspiredesignCaptureConstraint = (\n references: InspiredesignReferenceEvidence[]\n): { summary: string; guidance: ProviderNextStepGuidance } | undefined => {\n const failedReferences = references.filter((reference) => reference.captureStatus === \"failed\");\n if (failedReferences.length === 0) {\n return undefined;\n }\n const unavailableOnly = failedReferences.every((reference) => reference.captureFailure === INSPIREDESIGN_CAPTURE_UNAVAILABLE_FAILURE);\n const summary = unavailableOnly\n ? `Deep capture was unavailable for ${failedReferences.length} ${failedReferences.length === 1 ? \"reference\" : \"references\"} in this execution lane.`\n : `Deep capture failed for ${failedReferences.length} ${failedReferences.length === 1 ? \"reference\" : \"references\"}.`;\n const retryUrls = failedReferences\n .slice(0, 2)\n .map((reference) => `Retry deep capture for ${reference.url} after restoring the required browser session state.`);\n return {\n summary,\n guidance: {\n reason: summary,\n recommendedNextCommands: unavailableOnly\n ? [\n \"Restore browser capture access for this execution lane, then rerun inspiredesign.\",\n ...retryUrls\n ]\n : [\n \"Rerun inspiredesign after configuring providers.cookieSource for the protected references you need to capture.\",\n ...retryUrls\n ]\n }\n };\n};\n\nconst summarizeInspiredesignFetchConstraint = (\n references: InspiredesignReferenceEvidence[]\n): string | undefined => {\n return references.find((reference) => (\n reference.fetchStatus === \"failed\"\n && !isInspiredesignFetchRecovered(reference)\n && typeof reference.fetchFailure === \"string\"\n && reference.fetchFailure.trim().length > 0\n ))?.fetchFailure;\n};\n\nconst hasSurvivingInspiredesignReference = (references: InspiredesignReferenceEvidence[]): boolean => (\n references.some((reference) => reference.fetchStatus === \"captured\" || reference.captureStatus === \"captured\")\n);\n\nconst INSPIREDESIGN_HARD_DISCOVERY_REASON_CODES = new Set<ProviderReasonCode>([\n \"auth_required\",\n \"challenge_detected\",\n \"policy_blocked\",\n \"rate_limited\",\n \"token_required\"\n]);\n\nconst readInspiredesignFailureReasonCode = (failure: ProviderFailureEntry): ProviderReasonCode | undefined => {\n const reasonCode = failure.error.reasonCode ?? failure.error.details?.reasonCode;\n return typeof reasonCode === \"string\" && INSPIREDESIGN_HARD_DISCOVERY_REASON_CODES.has(reasonCode as ProviderReasonCode)\n ? reasonCode as ProviderReasonCode\n : undefined;\n};\n\nconst hardInspiredesignDiscoveryReasonCodes = (discovery: InspiredesignDiscoveryDiagnostics): ProviderReasonCode[] => {\n const reasonCodes = discovery.failures\n .map(readInspiredesignFailureReasonCode)\n .filter((reasonCode): reasonCode is ProviderReasonCode => reasonCode !== undefined);\n return [...new Set(reasonCodes)];\n};\n\nconst hardInspiredesignMetaReasonCodes = (meta: Record<string, unknown>): ProviderReasonCode[] => {\n const distribution = meta.reasonCodeDistribution;\n if (!distribution || typeof distribution !== \"object\" || Array.isArray(distribution)) return [];\n return Object.keys(distribution)\n .filter((reasonCode): reasonCode is ProviderReasonCode => (\n INSPIREDESIGN_HARD_DISCOVERY_REASON_CODES.has(reasonCode as ProviderReasonCode)\n ));\n};\n\nconst hardInspiredesignGuidanceReasonCodes = (\n discovery: InspiredesignDiscoveryDiagnostics,\n meta: Record<string, unknown>\n): ProviderReasonCode[] => [\n ...new Set([\n ...hardInspiredesignDiscoveryReasonCodes(discovery),\n ...hardInspiredesignMetaReasonCodes(meta)\n ])\n];\n\nconst selectInspiredesignPrimaryConstraintFailures = (\n failures: ProviderFailureEntry[],\n references: InspiredesignReferenceEvidence[],\n discovery: InspiredesignDiscoveryDiagnostics\n): ProviderFailureEntry[] => {\n if (!hasSurvivingInspiredesignReference(references)) return failures;\n if (discovery.failures.length === 0) return failures;\n return failures.slice(discovery.failures.length);\n};\n\nconst readMetaPrimaryConstraint = (\n meta: Record<string, unknown>\n): InspiredesignGuidanceSource[\"primaryConstraint\"] => {\n const value = meta.primaryConstraint;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n const record = value as Record<string, unknown>;\n const primaryConstraint = {\n ...(typeof record.reasonCode === \"string\" ? { reasonCode: record.reasonCode } : {}),\n ...(typeof record.summary === \"string\" ? { summary: record.summary } : {})\n };\n return Object.keys(primaryConstraint).length > 0 ? primaryConstraint : undefined;\n};\n\nconst isInspiredesignReferenceEvidenceRequired = (workflowInput: InspiredesignResolvedInput): boolean => (\n workflowInput.harvest === true\n || workflowInput.urls.length > 0\n || workflowInput.providers.length > 0\n || typeof workflowInput.query === \"string\"\n || workflowInput.visualEvidence === \"required\"\n);\n\nconst buildInspiredesignGuidanceSource = (\n workflowInput: InspiredesignResolvedInput,\n discovery: InspiredesignDiscoveryDiagnostics,\n meta: Record<string, unknown>,\n referencePatternBoard: InspiredesignReferencePatternBoard\n): InspiredesignGuidanceSource => {\n const quality = summarizeInspiredesignReferenceQuality(referencePatternBoard);\n const primaryConstraint = readMetaPrimaryConstraint(meta);\n return {\n brief: workflowInput.brief,\n ...(workflowInput.query ? { query: workflowInput.query } : {}),\n urls: workflowInput.urls,\n requestedProviders: workflowInput.providers,\n ...(workflowInput.browserMode ? { browserMode: workflowInput.browserMode } : {}),\n ...(workflowInput.cookiePolicyOverride ? { cookiePolicy: workflowInput.cookiePolicyOverride } : {}),\n ...(typeof workflowInput.useCookies === \"boolean\" ? { useCookies: workflowInput.useCookies } : {}),\n discovery: {\n requested: discovery.requested,\n acceptedUrls: discovery.acceptedUrls,\n failures: discovery.failures.length,\n ...(discovery.failure ? { failure: discovery.failure } : {}),\n hardFailureReasonCodes: hardInspiredesignGuidanceReasonCodes(discovery, meta)\n },\n metrics: {\n referenceCount: quality.rankedReferenceCount + quality.rejectedReferenceCount,\n referenceEvidenceRequired: isInspiredesignReferenceEvidenceRequired(workflowInput),\n failedCaptureCount: quality.failedCaptureCount,\n visualEvidenceRequired: workflowInput.visualEvidence === \"required\"\n },\n quality: {\n rankedReferenceCount: quality.rankedReferenceCount,\n rankedReferenceUrls: referencePatternBoard.references.map((reference) => reference.url),\n rejectedReferenceCount: quality.rejectedReferenceCount,\n missingScreenshotCount: quality.missingScreenshotCount,\n diagnosticOnlyReasons: quality.diagnosticOnlyReasons,\n ...(typeof quality.topReferenceScore === \"number\" ? { topReferenceScore: quality.topReferenceScore } : {}),\n ...(typeof quality.topReferenceConfidence === \"number\" ? { topReferenceConfidence: quality.topReferenceConfidence } : {}),\n ...(typeof quality.topReferenceIntentMatched === \"boolean\"\n ? { topReferenceIntentMatched: quality.topReferenceIntentMatched }\n : {})\n },\n ...(primaryConstraint ? { primaryConstraint } : {})\n };\n};\n\nconst buildInspiredesignMeta = (\n runtime: ReferenceRetrievalPort,\n workflowInput: InspiredesignResolvedInput,\n references: InspiredesignReferenceEvidence[],\n failures: ProviderFailureEntry[],\n followthrough: InspiredesignFollowthrough,\n discovery: InspiredesignDiscoveryDiagnostics\n): Record<string, unknown> => {\n const failedCaptures = references.filter((reference) => reference.captureStatus === \"failed\");\n const captureAttemptReport = summarizeInspiredesignCaptureAttempts(references);\n const recoveredFetches = summarizeInspiredesignRecoveredFetches(references);\n const hasSurvivingReference = hasSurvivingInspiredesignReference(references);\n const primaryConstraintFailures = selectInspiredesignPrimaryConstraintFailures(failures, references, discovery);\n let reasonCodeDistribution = summarizeReasonCodeDistribution(failures);\n let meta = withCamelCasePrimaryConstraintMeta(withReasonCodeDistributionMeta({\n selection: {\n urls: workflowInput.urls,\n ...(workflowInput.query ? { query: workflowInput.query } : {}),\n ...(workflowInput.providers.length > 0 ? { providers: workflowInput.providers } : {}),\n ...(workflowInput.referenceLimit !== undefined\n ? { max_references: workflowInput.referenceLimit }\n : {}),\n ...(workflowInput.visualEvidence !== \"off\" ? { visual_evidence: workflowInput.visualEvidence } : {}),\n capture_mode: workflowInput.captureMode,\n ...(workflowInput.browserMode ? { requested_browser_mode: workflowInput.browserMode } : {}),\n include_prototype_guidance: Boolean(workflowInput.includePrototypeGuidance)\n },\n metrics: {\n reference_count: references.length,\n fetched_references: references.filter((reference) => reference.fetchStatus === \"captured\").length,\n captured_references: references.filter((reference) => reference.captureStatus === \"captured\").length,\n failed_fetches: references.filter((reference) => (\n reference.fetchStatus === \"failed\" && !isInspiredesignFetchRecovered(reference)\n )).length,\n failed_captures: failedCaptures.length,\n ...(recoveredFetches.length > 0\n ? {\n recovered_fetches: recoveredFetches.length,\n recovered_fetch_details: recoveredFetches\n }\n : {}),\n ...(captureAttemptReport ? { capture_attempts: captureAttemptReport.counts } : {})\n },\n alerts: buildWorkflowAlerts(runtime, failures)\n }, reasonCodeDistribution), primaryConstraintFailures);\n if (!meta.primaryConstraint) {\n const fetchConstraint = summarizeInspiredesignFetchConstraint(references);\n if (fetchConstraint) {\n meta = {\n ...meta,\n primaryConstraintSummary: fetchConstraint\n };\n }\n }\n if (!hasSurvivingReference && !meta.primaryConstraint && !meta.primaryConstraintSummary) {\n const discoveryConstraint = summarizeInspiredesignDiscoveryConstraint(discovery);\n if (discoveryConstraint) {\n meta = withPrimaryConstraintSummaryOverride(\n meta,\n discoveryConstraint.summary,\n discoveryConstraint.guidance\n );\n }\n }\n if (!meta.primaryConstraint && !meta.primaryConstraintSummary) {\n const captureConstraint = summarizeInspiredesignCaptureConstraint(references);\n if (captureConstraint) {\n reasonCodeDistribution = incrementReasonCodeDistribution(\n reasonCodeDistribution,\n \"env_limited\",\n failedCaptures.length\n );\n meta = withReasonCodeDistributionMeta(meta, reasonCodeDistribution);\n meta = withPrimaryConstraintSummaryOverride(meta, captureConstraint.summary, captureConstraint.guidance);\n }\n }\n return {\n ...meta,\n followthroughSummary: followthrough.summary,\n ...(captureAttemptReport\n ? {\n captureAttemptSummary: captureAttemptReport.summary,\n captureAttemptReport: {\n worked: captureAttemptReport.worked,\n didNotWork: captureAttemptReport.didNotWork\n }\n }\n : {}),\n recommendedSkills: followthrough.recommendedSkills,\n deepCaptureRecommendation: followthrough.deepCaptureRecommendation,\n discovery,\n contractScope: followthrough.contractScope\n };\n};\n\nconst buildInspiredesignDiscoveryGuidance = (\n discovery: InspiredesignDiscoveryDiagnostics\n): ProviderNextStepGuidance => ({\n reason: discovery.failure ?? \"Reference discovery did not produce usable design references.\",\n recommendedNextCommands: [\n \"Rerun inspiredesign harvest with explicit --url references from usable inspiration pages.\",\n \"Retry provider discovery in a lane with provider search support and any required authenticated browser session.\"\n ]\n});\n\nconst summarizeInspiredesignDiscoveryConstraint = (\n discovery: InspiredesignDiscoveryDiagnostics\n): { summary: string; guidance: ProviderNextStepGuidance } | undefined => {\n if (!discovery.requested || discovery.acceptedUrls.length > 0) return undefined;\n const queryDetail = discovery.query ? ` for query \"${discovery.query}\"` : \"\";\n const summary = discovery.failure\n ?? `Reference discovery returned no usable references${queryDetail}.`;\n return {\n summary,\n guidance: buildInspiredesignDiscoveryGuidance(discovery)\n };\n};\n\nconst buildInspiredesignGuidanceFollowthroughSummary = (\n _followthrough: InspiredesignFollowthrough,\n meta: Record<string, unknown>,\n nextStepGuidance: NextStepGuidance\n): string => {\n const primaryConstraintSummary = typeof meta.primaryConstraintSummary === \"string\"\n ? meta.primaryConstraintSummary.trim()\n : \"\";\n const fallbackSummary = primaryConstraintSummary\n ? `Primary constraint: ${primaryConstraintSummary} ${nextStepGuidance.primaryAction.summary}`\n : undefined;\n return renderWorkflowCompatibility(nextStepGuidance, fallbackSummary).followthroughSummary;\n};\n\nconst inferBrandFromContent = (content: string | undefined, productUrl?: string): string | undefined => {\n const normalized = normalizePlainText(content);\n if (!normalized) return undefined;\n const isEbayProduct = productUrl ? resolveShoppingProviderIdForUrl(productUrl) === \"shopping/ebay\" : false;\n const bestBuyTitle = inferBestBuyTitleFromContent(normalized);\n const bestBuyBrand = inferBestBuyBrandFromTitle(bestBuyTitle) ?? extractBrandFromTitle(bestBuyTitle);\n if (bestBuyBrand) {\n return bestBuyBrand;\n }\n const storeMatch = /\\bVisit the ([A-Z][A-Za-z0-9&+' -]{1,60}) Store\\b/i.exec(normalized);\n if (storeMatch?.[1]) {\n return storeMatch[1].trim();\n }\n const topBrandMatch = /\\bTop Brand:\\s*([A-Z][A-Za-z0-9&+' -]{1,60})\\b/i.exec(normalized);\n if (topBrandMatch?.[1]) {\n return topBrandMatch[1].trim();\n }\n const productIdentifiersBrandMatch = /\\bProduct Identifiers\\s+Brand\\s+([A-Z][A-Za-z0-9&+' -]{1,60}?)(?=\\s+(?:MPN|UPC|Model)\\b|$)/i.exec(normalized);\n if (productIdentifiersBrandMatch?.[1]) {\n return productIdentifiersBrandMatch[1].trim();\n }\n const ebayTitle = inferEbayTitleFromContent(normalized);\n const ebayBrand = inferEbayBrandFromTitle(ebayTitle);\n if (ebayBrand) {\n return ebayBrand;\n }\n if (isEbayProduct) {\n return undefined;\n }\n const brandMatch = /\\bBrand ([A-Z][A-Za-z0-9&+' -]{1,60})\\b/i.exec(normalized);\n if (brandMatch?.[1]) {\n return brandMatch[1].trim();\n }\n return undefined;\n};\n\nconst inferBestBuyBrandFromTitle = (title: string | undefined): string | undefined => {\n const cleaned = normalizePlainText(title);\n const match = /^([A-Z][A-Za-z0-9&+' ]{1,40})\\s+-\\s+/.exec(cleaned);\n return match?.[1]?.trim() || undefined;\n};\n\nconst inferBestBuyTitleFromContent = (normalized: string): string | undefined => {\n const match = /\\bMain Content\\s+(.+?)(?=\\s+Rating [0-9](?:\\.[0-9])? out of 5 stars|\\s+Model:|\\s+SKU:|\\s+Back to top\\b)/i.exec(normalized);\n const candidate = normalizePlainText(match?.[1]);\n if (!candidate || candidate.length < 20 || LOOKS_LIKE_URL_RE.test(candidate)) {\n return undefined;\n }\n return candidate;\n};\n\nconst inferEbayTitleFromContent = (normalized: string): string | undefined => {\n const patterns = [\n /\\bExpand Cart Loading\\.\\.\\.\\s+(.+?)(?:\\s+for sale online\\s*\\|\\s*eBay)?\\s+Condition:/i,\n /\\bBuy It Now\\s+(.+?)\\s+Sign in to check out\\b/i\n ];\n for (const pattern of patterns) {\n const candidate = stripMarketplaceTitleFraming(normalizePlainText(pattern.exec(normalized)?.[1]), \"https://www.ebay.com\");\n if (\n candidate\n && candidate.length >= 20\n && candidate.length <= 180\n && !candidate.endsWith(\"...\")\n && !LOOKS_LIKE_URL_RE.test(candidate)\n ) {\n return candidate;\n }\n }\n return undefined;\n};\n\nconst inferKnownEbayBrandFromTitle = (title: string): string | undefined => {\n const normalized = title.toLowerCase();\n return EBAY_KNOWN_MULTI_TOKEN_BRANDS.find((brand) => {\n const candidate = brand.toLowerCase();\n return normalized === candidate || normalized.startsWith(`${candidate} `);\n });\n};\n\nconst inferKnownSingleEbayBrandFromTitle = (title: string): string | undefined => {\n const firstToken = /^([A-Za-z][A-Za-z0-9&+']{1,30})(?:\\s|$)/.exec(title)?.[1];\n return firstToken ? EBAY_KNOWN_SINGLE_TOKEN_BRANDS.get(firstToken.toLowerCase()) : undefined;\n};\n\nconst inferEbayBrandFromTitle = (title: string | undefined): string | undefined => {\n const framed = normalizePlainText(title).replace(/\\s+[-|]\\s+[^-|]+$/i, \"\").trim();\n const knownBrand = inferKnownEbayBrandFromTitle(framed);\n if (knownBrand) return knownBrand;\n const cleaned = framed.replace(EBAY_TITLE_BRAND_PREFIX_RE, \"\");\n const prefixedBrand = inferKnownEbayBrandFromTitle(cleaned);\n if (prefixedBrand) return prefixedBrand;\n const singleTokenBrand = inferKnownSingleEbayBrandFromTitle(cleaned);\n if (singleTokenBrand) return singleTokenBrand;\n const exactBrand = /^([A-Z][A-Za-z0-9&+']{1,30})$/.exec(cleaned)?.[1];\n if (exactBrand && EBAY_KNOWN_SINGLE_TOKEN_BRANDS.has(exactBrand.toLowerCase())) {\n return exactBrand;\n }\n const match = /^([A-Z][A-Za-z0-9&+']{1,30})\\s+([A-Z0-9][A-Za-z0-9&+'().-]+|AirPods)\\b/.exec(cleaned);\n const brand = match?.[1]?.trim();\n if (!brand || EBAY_TITLE_BRAND_STOP_WORDS.has(brand.toLowerCase())) {\n return undefined;\n }\n if (EBAY_KNOWN_SINGLE_TOKEN_BRANDS.has(brand.toLowerCase())) {\n return EBAY_KNOWN_SINGLE_TOKEN_BRANDS.get(brand.toLowerCase());\n }\n if (!/[\\d-]/.test(match?.[2] ?? \"\")) {\n return undefined;\n }\n return brand;\n};\n\nconst inferTitleFromContent = (content: string | undefined, productUrl?: string): string | undefined => {\n const normalized = normalizePlainText(content);\n if (!normalized) return undefined;\n const bestBuyTitle = inferBestBuyTitleFromContent(normalized);\n if (bestBuyTitle) {\n return bestBuyTitle;\n }\n if (productUrl && resolveShoppingProviderIdForUrl(productUrl) === \"shopping/ebay\") {\n const ebayTitle = inferEbayTitleFromContent(normalized);\n if (ebayTitle) {\n return ebayTitle;\n }\n }\n const storeMatch = /\\bVisit the [A-Z][A-Za-z0-9&+' -]{1,60} Store\\s+(.+?)(?=\\s+(?:Brand [A-Z]|About this item|Key item features|Current price is|Actual Color|[0-9]+(?:\\.[0-9]+)? stars out of|Best seller\\b))/i.exec(normalized);\n const candidate = normalizePlainText(storeMatch?.[1]);\n if (!candidate || candidate.length < 20 || LOOKS_LIKE_URL_RE.test(candidate)) {\n return undefined;\n }\n return candidate;\n};\n\nconst sanitizeProductBrandCandidate = (candidate: string | undefined, productUrl: string): string | undefined => {\n const normalized = normalizePlainText(candidate);\n if (!normalized) return undefined;\n try {\n const host = new URL(productUrl).hostname.toLowerCase();\n const hostBrand = normalizePlainText(inferBrandFromUrl(productUrl)).replace(/\\.com\\b/gi, \"\").toLowerCase();\n const candidateBrand = normalized.replace(/\\.com\\b/gi, \"\").toLowerCase();\n if (host.includes(\"ebay.\") && hostBrand && candidateBrand === hostBrand) {\n return undefined;\n }\n if (!host.includes(\"walmart.\")) {\n return normalized;\n }\n const cleaned = normalized\n .replace(/^Brand\\s+/i, \"\")\n .replace(/\\bVisit the ([A-Z][A-Za-z0-9&+' -]{1,60}) Store\\b/i, \"$1\")\n .replace(WALMART_BRAND_COLOR_RE, \"\")\n .replace(WALMART_BRAND_CHROME_TAIL_RE, \"\")\n .replace(/\\bWalmart\\.com\\b.*$/i, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n if (\n !cleaned\n || WALMART_BRAND_CHROME_RE.test(cleaned)\n || LOOKS_LIKE_URL_RE.test(cleaned)\n || /[.!?]/.test(cleaned)\n || cleaned.split(/\\s+/).length > 5\n ) {\n return undefined;\n }\n return cleaned;\n } catch {\n return normalized;\n }\n};\n\nconst stripMarketplaceTitleFraming = (title: string, productUrl: string): string => {\n let cleaned = normalizePlainText(title);\n if (!cleaned) return \"\";\n try {\n const host = new URL(productUrl).hostname.toLowerCase();\n if (host.includes(\"amazon.\")) {\n cleaned = cleaned\n .replace(/^Amazon\\.com:\\s*/i, \"\")\n .replace(/\\s*:\\s*Electronics\\s*$/i, \"\")\n .trim();\n }\n if (host.includes(\"ebay.\")) {\n cleaned = cleaned\n .replace(/\\s+for sale online\\s*\\|\\s*eBay.*$/i, \"\")\n .replace(/\\s*\\|\\s*eBay.*$/i, \"\")\n .trim();\n }\n if (host.includes(\"walmart.\")) {\n cleaned = cleaned\n .replace(WALMART_TITLE_PREFIX_RE, \"\")\n .replace(WALMART_TITLE_TAIL_RE, \"\")\n .replace(/\\bWalmart\\.com\\b.*$/i, \"\")\n .replace(/\\b(?:Skip to Main Content|Pickup or delivery\\?|How do you want your item\\?|Departments Services)\\b.*$/i, \"\")\n .trim();\n }\n const hostBrand = normalizePlainText(inferBrandFromUrl(productUrl)).replace(/\\.com\\b/gi, \"\").trim();\n if (hostBrand) {\n const escapedHostBrand = hostBrand.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\");\n cleaned = cleaned.replace(new RegExp(`\\\\s*[-|:]\\\\s*${escapedHostBrand}(?:\\\\.com)?\\\\s*$`, \"i\"), \"\").trim();\n }\n } catch {\n return cleaned;\n }\n return cleaned;\n};\n\nconst isMarketplaceTitleChrome = (title: string, productUrl: string): boolean => {\n const cleaned = normalizePlainText(title);\n if (!cleaned) return true;\n try {\n const canonicalHostBrand = normalizePlainText(inferBrandFromUrl(productUrl))\n .replace(/\\.com\\b/gi, \"\")\n .trim()\n .toLowerCase();\n const canonicalTitle = cleaned\n .replace(/\\.com\\b/gi, \"\")\n .trim()\n .toLowerCase();\n if (canonicalHostBrand && canonicalTitle === canonicalHostBrand) {\n return true;\n }\n const host = new URL(productUrl).hostname.toLowerCase();\n if (host.includes(\"walmart.\")) {\n return WALMART_TITLE_CHROME_RE.test(cleaned);\n }\n if (host.includes(\"bestbuy.\")) {\n return /\\$\\(csi\\.user\\.businessName\\)|\\bSkip to content\\b|\\bGo to Product Search\\b/i.test(cleaned);\n }\n return false;\n } catch {\n return false;\n }\n};\n\nconst collectMarkerIndexes = (value: string, marker: string): number[] => {\n const indexes: number[] = [];\n const lowerValue = value.toLowerCase();\n const lowerMarker = marker.toLowerCase();\n let cursor = lowerValue.indexOf(lowerMarker);\n while (cursor >= 0) {\n indexes.push(cursor);\n cursor = lowerValue.indexOf(lowerMarker, cursor + lowerMarker.length);\n }\n return indexes;\n};\n\nconst extractProductFeatureSection = (content: string | undefined): string => {\n const normalized = normalizePlainText(content);\n if (!normalized) return \"\";\n let bestSection = \"\";\n let bestScore = -1;\n for (const marker of PRODUCT_FEATURE_SECTION_MARKERS) {\n const markerIndexes = collectMarkerIndexes(normalized, marker);\n for (const markerIndex of markerIndexes) {\n let section = normalized.slice(markerIndex + marker.length).trim();\n const stopIndex = section.search(PRODUCT_FEATURE_SECTION_STOP_RE);\n if (stopIndex >= 0) {\n section = section.slice(0, stopIndex).trim();\n }\n section = section\n .replace(/\\bAbout this item\\b/gi, \" \")\n .replace(/\\bKey item features\\b/gi, \" \")\n .replace(/\\bSee more product details\\b/gi, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n if (!section) {\n continue;\n }\n const labeledFeatureCount = extractLabeledProductFeatures(section).length;\n const sentenceFeatureCount = sanitizeFeatureList(section.split(/(?<=[.!?])\\s+/)).length;\n const score = (labeledFeatureCount * 10) + (sentenceFeatureCount * 5) + Math.min(section.length, 500) / 100;\n if (score > bestScore) {\n bestSection = section;\n bestScore = score;\n }\n }\n }\n\n return bestSection;\n};\n\nconst extractLabeledProductFeatures = (section: string): string[] => {\n let best: string[] = [];\n for (const pattern of PRODUCT_FEATURE_PATTERNS) {\n pattern.lastIndex = 0;\n const matches = [...section.matchAll(pattern)]\n .map((match) => normalizePlainText(match[2]))\n .filter(Boolean);\n const cleaned = sanitizeFeatureList(matches);\n if (cleaned.length > best.length) {\n best = cleaned;\n }\n }\n return best;\n};\n\nconst extractAboutItemFeatures = (content: string | undefined): string[] => {\n const section = extractProductFeatureSection(content);\n if (!section) return [];\n const cleanedLabeledFeatures = extractLabeledProductFeatures(section);\n if (cleanedLabeledFeatures.length > 0) {\n return cleanedLabeledFeatures;\n }\n return sanitizeFeatureList(section.split(/(?<=[.!?])\\s+/));\n};\n\nconst extractMarketplaceSummaryCopy = (content: string | undefined, productUrl: string): string => {\n const normalized = normalizePlainText(content);\n if (!normalized) return \"\";\n try {\n const host = new URL(productUrl).hostname.toLowerCase();\n if (host.includes(\"ebay.\")) {\n return normalizePlainText(/\\bCondition:\\s+[A-Za-z-]+\\s+[A-Za-z-]+\\s+(.+?)\\s+Buy It Now\\b/i.exec(normalized)?.[1]);\n }\n } catch {\n return \"\";\n }\n return \"\";\n};\n\nconst extractMarketplaceSummaryFeatures = (content: string | undefined, productUrl: string): string[] => {\n const summary = extractMarketplaceSummaryCopy(content, productUrl);\n if (!summary) return [];\n return sanitizeFeatureList(summary.split(/(?<=[.!?])\\s+/));\n};\n\nconst inferHostDefaultCurrency = (productUrl: string): string | undefined => {\n try {\n const host = new URL(productUrl).hostname.toLowerCase();\n const match = HOST_DEFAULT_CURRENCY.find(([pattern]) => pattern.test(host));\n return match?.[1];\n } catch {\n return undefined;\n }\n};\n\nconst extractProductBrandFromTitle = (title: string | undefined, productUrl: string): string | undefined => {\n try {\n const host = new URL(productUrl).hostname.toLowerCase();\n if (host.includes(\"ebay.\")) {\n return inferEbayBrandFromTitle(title);\n }\n } catch {\n return extractBrandFromTitle(title);\n }\n return extractBrandFromTitle(title);\n};\n\nconst shouldSuppressMarketplacePrice = (\n record: NormalizedRecord,\n productUrl: string,\n price: { amount: number; currency: string }\n): boolean => {\n if (price.amount <= 0) return false;\n const expectedCurrency = inferHostDefaultCurrency(productUrl);\n if (!expectedCurrency) return false;\n if (!MARKETPLACE_OVERLAY_RE.test(normalizePlainText(record.content))) return false;\n return price.currency.trim().toUpperCase() !== expectedCurrency;\n};\n\nconst resolvePreferredProductPrice = (\n record: NormalizedRecord,\n productUrl: string,\n refreshedPrice: { amount: number; currency: string } | undefined,\n primaryOffer: ShoppingOffer\n): { amount: number; currency: string; retrieved_at: string } => {\n if (refreshedPrice && refreshedPrice.amount > 0) {\n return {\n amount: refreshedPrice.amount,\n currency: refreshedPrice.currency,\n retrieved_at: primaryOffer.price.retrieved_at\n };\n }\n if (primaryOffer.price.amount > 0) {\n return {\n amount: primaryOffer.price.amount,\n currency: primaryOffer.price.currency,\n retrieved_at: primaryOffer.price.retrieved_at\n };\n }\n if (!requiresManualMarketplacePriceFollowUp(productUrl)) {\n const fallbackPrice = parsePriceFromContent(record.content);\n if (fallbackPrice.amount > 0) {\n return {\n amount: fallbackPrice.amount,\n currency: fallbackPrice.currency,\n retrieved_at: primaryOffer.price.retrieved_at\n };\n }\n }\n return {\n amount: primaryOffer.price.amount,\n currency: primaryOffer.price.currency,\n retrieved_at: primaryOffer.price.retrieved_at\n };\n};\n\nconst resolveProductPrice = (\n record: NormalizedRecord,\n productUrl: string,\n refreshedPrice: { amount: number; currency: string } | undefined,\n primaryOffer: ShoppingOffer\n): { amount: number; currency: string; retrieved_at: string } => {\n const preferred = resolvePreferredProductPrice(record, productUrl, refreshedPrice, primaryOffer);\n if (shouldSuppressMarketplacePrice(record, productUrl, preferred)) {\n return {\n amount: 0,\n currency: inferHostDefaultCurrency(productUrl) ?? preferred.currency,\n retrieved_at: preferred.retrieved_at\n };\n }\n return preferred;\n};\n\nconst MANUAL_MARKETPLACE_PRICE_FOLLOW_UP_PROVIDER_IDS = new Set<string>([\n \"shopping/amazon\"\n]);\n\nconst requiresManualMarketplacePriceFollowUp = (productUrl: string): boolean => {\n const providerId = resolveShoppingProviderIdForUrl(productUrl);\n return providerId !== null && MANUAL_MARKETPLACE_PRICE_FOLLOW_UP_PROVIDER_IDS.has(providerId);\n};\n\nconst buildManualProductPriceFollowUpMessage = (productUrl: string): string => {\n const provider = normalizePlainText(inferBrandFromUrl(productUrl)) || \"Product page\";\n return `${provider} requires manual browser follow-up; this run did not determine a reliable PDP price.`;\n};\n\nconst deriveFeatureList = (record: NormalizedRecord, productUrl: string, fallbackFeatures: string[] = []): string[] => {\n const structured = Array.isArray(record.attributes.features)\n ? record.attributes.features.filter((entry): entry is string => typeof entry === \"string\" && entry.trim().length > 0)\n : [];\n const structuredFeatures = sanitizeFeatureList(structured);\n if (structuredFeatures.length > 0) {\n return structuredFeatures;\n }\n\n const marketplaceSummaryFeatures = extractMarketplaceSummaryFeatures(record.content, productUrl);\n if (marketplaceSummaryFeatures.length > 0) {\n return marketplaceSummaryFeatures;\n }\n\n const aboutItemFeatures = extractAboutItemFeatures(record.content);\n if (aboutItemFeatures.length > 0) {\n return aboutItemFeatures;\n }\n\n const fallbackFeatureList = sanitizeFeatureList(fallbackFeatures);\n if (fallbackFeatureList.length > 0) {\n return fallbackFeatureList;\n }\n\n if (!record.content) return [];\n const candidates = trimProductCopy(record.content)\n .split(/(?<=[.!?])\\s+|\\n+/)\n .map((line) => line.trim());\n return sanitizeFeatureList(candidates);\n};\n\nconst hasStructuredShoppingPrice = (record: NormalizedRecord): boolean => {\n const nested = record.attributes.shopping_offer;\n if (!nested || typeof nested !== \"object\" || Array.isArray(nested)) return false;\n const price = (nested as Record<string, unknown>).price;\n if (!price || typeof price !== \"object\" || Array.isArray(price)) return false;\n return asNumber((price as Record<string, unknown>).amount) > 0;\n};\n\nconst needsProductMetadataRefresh = (record: NormalizedRecord, productUrl: string): boolean => {\n if (!/^https?:/i.test(productUrl)) return false;\n const title = normalizePlainText(record.title);\n const brand = typeof record.attributes.brand === \"string\" ? normalizePlainText(record.attributes.brand) : \"\";\n return !title || title === canonicalizeUrl(productUrl) || LOOKS_LIKE_URL_RE.test(title) || !brand || brand === \"unknown\" || !hasStructuredShoppingPrice(record);\n};\n\nconst refreshProductMetadata = async (\n productUrl: string,\n timeoutMs?: number\n): Promise<ReturnType<typeof extractStructuredContent>[\"metadata\"] | null> => {\n try {\n const response = await fetch(productUrl, {\n headers: {\n accept: \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n ...providerRequestHeaders\n },\n redirect: \"follow\",\n signal: buildAuxiliaryFetchSignal(timeoutMs)\n });\n if (!response.ok) return null;\n const html = await response.text();\n return extractStructuredContent(html, response.url || productUrl).metadata;\n } catch {\n return null;\n }\n};\n\nconst resolveProductBrand = (\n record: NormalizedRecord,\n productUrl: string,\n refreshedBrand: string | undefined\n): string => {\n const canonicalHostBrand = normalizePlainText(inferBrandFromUrl(productUrl))\n .replace(/\\.com\\b/gi, \"\")\n .toLowerCase();\n const rejectRetailerBrand = (candidate: string | undefined): string | undefined => {\n const normalized = normalizePlainText(candidate);\n if (!normalized) return undefined;\n const canonicalCandidate = normalized.replace(/\\.com\\b/gi, \"\").toLowerCase();\n return canonicalHostBrand && canonicalCandidate === canonicalHostBrand ? undefined : normalized;\n };\n const nested = record.attributes.shopping_offer;\n const nestedProvider = nested && typeof nested === \"object\" && !Array.isArray(nested)\n ? (nested as Record<string, unknown>).provider\n : undefined;\n const providerBrand = typeof nestedProvider === \"string\"\n ? SHOPPING_PROVIDER_PROFILES.find((entry) => entry.id === nestedProvider)?.displayName\n : undefined;\n const candidates = [\n inferBrandFromContent(record.content, productUrl),\n rejectRetailerBrand(refreshedBrand),\n rejectRetailerBrand(typeof record.attributes.brand === \"string\" ? record.attributes.brand : undefined),\n rejectRetailerBrand(typeof record.attributes.site_name === \"string\" ? record.attributes.site_name : undefined),\n rejectRetailerBrand(providerBrand && providerBrand !== \"Others\" ? providerBrand : undefined),\n extractProductBrandFromTitle(record.title, productUrl),\n inferBrandFromUrl(productUrl)\n ]\n .map((entry) => sanitizeProductBrandCandidate(entry, productUrl))\n .filter(Boolean);\n return candidates[0] || \"unknown\";\n};\n\nconst resolveProductTitle = (\n record: NormalizedRecord,\n productUrl: string,\n brand: string,\n refreshedTitle: string | undefined\n): string => {\n const nested = record.attributes.shopping_offer;\n const nestedTitle = nested && typeof nested === \"object\" && !Array.isArray(nested)\n ? (nested as Record<string, unknown>).title\n : undefined;\n const candidates = [\n refreshedTitle,\n inferTitleFromContent(record.content, productUrl),\n record.title,\n typeof nestedTitle === \"string\" ? nestedTitle : undefined,\n typeof record.attributes.description === \"string\" ? record.attributes.description.split(/(?<=[.!?])\\s+/)[0] : undefined,\n trimProductCopy(record.content ?? \"\").split(/(?<=[.!?])\\s+/)[0]\n ]\n .map((entry) => stripBrandSuffix(stripMarketplaceTitleFraming(normalizePlainText(entry), productUrl), brand))\n .filter((entry) =>\n entry.length > 0\n && !LOOKS_LIKE_URL_RE.test(entry)\n && entry !== canonicalizeUrl(productUrl)\n && !isMarketplaceTitleChrome(entry, productUrl)\n );\n return candidates[0] || productUrl;\n};\n\nconst resolveProductCopy = (\n record: NormalizedRecord,\n productUrl: string,\n refreshedDescription: string | undefined,\n featureList: string[]\n): string => {\n const preferred = normalizePlainText(refreshedDescription)\n || normalizePlainText(typeof record.attributes.description === \"string\" ? record.attributes.description : undefined);\n const marketplacePromoCopy = (() => {\n if (!preferred) return false;\n try {\n const host = new URL(productUrl).hostname.toLowerCase();\n return host.includes(\"walmart.\") && /\\bfree shipping!?/i.test(preferred);\n } catch {\n return false;\n }\n })();\n if (preferred && !MARKETPLACE_COPY_RE.test(preferred) && !marketplacePromoCopy) {\n return toSnippet(preferred, 8000);\n }\n const marketplaceSummaryCopy = extractMarketplaceSummaryCopy(record.content, productUrl);\n if (marketplaceSummaryCopy) {\n return toSnippet(marketplaceSummaryCopy, 8000);\n }\n if (featureList.length > 0) {\n return toSnippet(featureList.slice(0, 2).join(\" \"), 8000);\n }\n const featureSectionCopy = normalizePlainText(extractProductFeatureSection(record.content));\n if (featureSectionCopy) {\n return toSnippet(featureSectionCopy, 8000);\n }\n if (preferred) {\n return toSnippet(preferred, 8000);\n }\n return toSnippet(trimProductCopy(record.content ?? \"\"), 8000);\n};\n\nconst resolveShoppingSourceForUrl = (url: string): ProviderSource => {\n try {\n const host = new URL(url).hostname.toLowerCase();\n const match = SHOPPING_PROVIDER_PROFILES.some((profile) => profile.domains.some((domain) => host === domain || host.endsWith(`.${domain}`)));\n return match ? \"shopping\" : \"web\";\n } catch {\n return \"web\";\n }\n};\n\nconst getRequiredProductVideoExecutionStep = <\n TStepId extends ProductVideoWorkflowExecutionStep[\"id\"]\n>(\n steps: ProductVideoWorkflowExecutionStep[],\n stepId: TStepId\n): Extract<ProductVideoWorkflowExecutionStep, { id: TStepId }> => {\n const step = steps.find(\n (candidate): candidate is Extract<ProductVideoWorkflowExecutionStep, { id: TStepId }> => candidate.id === stepId\n );\n if (!step) {\n throw new Error(`Product-video workflow plan is missing required step ${stepId}.`);\n }\n return step;\n};\n\ntype ResearchSanitizeReason =\n | \"js_required_shell\"\n | \"login_shell\"\n | \"not_found_shell\"\n | \"privacy_preference_shell\"\n | \"research_dead_end_shell\"\n | \"search_index_shell\"\n | \"search_results_shell\";\n\nconst RESEARCH_REJECTED_CANDIDATE_LIMIT = 25;\n\ntype ResearchRejectedCandidate = {\n provider: string;\n source: ProviderSource;\n reason: ResearchSanitizeReason;\n replacement_status: \"rejected_before_synthesis\";\n retrievalPath?: string;\n title?: string;\n url?: string;\n};\n\nconst isResearchPrivacyPreferenceShell = (content: string): boolean => {\n const matchIndex = content.slice(0, 400).search(RESEARCH_PRIVACY_PREFERENCE_SHELL_RE);\n return matchIndex >= 0\n && matchIndex <= 80\n && !RESEARCH_PRIVACY_RECOVERED_CONTENT_RE.test(content);\n};\n\nconst classifyResearchDeadEndUrl = (value: string): ResearchSanitizeReason | null => {\n if (!value) return null;\n return classifyResearchDestinationRejection(value);\n};\n\nconst isResearchLoginShellRecord = (args: {\n url: string;\n combined: string;\n content: string;\n}): boolean => {\n if (args.url.includes(\"/login\")) {\n return true;\n }\n if (!RESEARCH_LOGIN_SHELL_RE.test(args.combined)) {\n return false;\n }\n return args.content.length <= RESEARCH_LOGIN_SHELL_MAX_CONTENT_CHARS\n || RESEARCH_LOGIN_REQUIRED_RE.test(args.combined);\n};\n\nconst classifyResearchShellRecord = (record: NormalizedRecord): ResearchSanitizeReason | null => {\n const retrievalPath = typeof record.attributes.retrievalPath === \"string\"\n ? record.attributes.retrievalPath\n : \"\";\n\n const url = typeof record.url === \"string\" ? record.url.trim().toLowerCase() : \"\";\n const title = normalizePlainText(record.title).toLowerCase();\n const content = normalizePlainText(record.content).toLowerCase();\n const combined = `${title} ${content}`.trim();\n\n if (isResearchLoginShellRecord({ url, combined, content })) {\n return \"login_shell\";\n }\n if (RESEARCH_JS_REQUIRED_RE.test(combined)) {\n return \"js_required_shell\";\n }\n if (RESEARCH_NOT_FOUND_SHELL_RE.test(combined)) {\n return \"not_found_shell\";\n }\n if (isResearchPrivacyPreferenceShell(content)) {\n return \"privacy_preference_shell\";\n }\n const deadEndUrlReason = classifyResearchDeadEndUrl(url);\n if (deadEndUrlReason) {\n return deadEndUrlReason;\n }\n if (!retrievalPath) {\n return null;\n }\n if (RESEARCH_ALWAYS_SANITIZED_PATHS.has(retrievalPath)) {\n return \"search_index_shell\";\n }\n if (!RESEARCH_CONDITIONAL_SANITIZED_PATHS.has(retrievalPath)) {\n return null;\n }\n if (retrievalPath === \"web:search:index\" && (/duckduckgo\\.com/.test(url) || LOOKS_LIKE_URL_RE.test(title))) {\n return \"search_index_shell\";\n }\n if (LOOKS_LIKE_URL_RE.test(title) && RESEARCH_GENERIC_SHELL_RE.test(combined)) {\n return \"search_results_shell\";\n }\n if (\n RESEARCH_SEARCH_SHELL_RE.test(combined)\n || url.includes(\"/search\")\n || isDuckDuckGoResearchShellUrl(url)\n ) {\n return \"search_results_shell\";\n }\n return null;\n};\n\nconst sanitizeResearchRecords = (\n records: NormalizedRecord[]\n): {\n records: NormalizedRecord[];\n sanitizedCount: number;\n reasonDistribution: Record<string, number>;\n rejectedCandidates: ResearchRejectedCandidate[];\n} => {\n const reasonDistribution: Record<string, number> = {};\n const rejectedCandidates: ResearchRejectedCandidate[] = [];\n const sanitizedRecords = records.filter((record) => {\n const reason = classifyResearchShellRecord(record);\n if (!reason) return true;\n reasonDistribution[reason] = (reasonDistribution[reason] ?? 0) + 1;\n if (rejectedCandidates.length < RESEARCH_REJECTED_CANDIDATE_LIMIT) {\n const retrievalPath = typeof record.attributes.retrievalPath === \"string\"\n ? record.attributes.retrievalPath\n : undefined;\n rejectedCandidates.push({\n provider: record.provider,\n source: record.source,\n reason,\n replacement_status: \"rejected_before_synthesis\",\n ...(retrievalPath ? { retrievalPath } : {}),\n ...(record.title ? { title: record.title } : {}),\n ...(record.url ? { url: record.url } : {})\n });\n }\n return false;\n });\n\n return {\n records: sanitizedRecords,\n sanitizedCount: records.length - sanitizedRecords.length,\n reasonDistribution,\n rejectedCandidates\n };\n};\n\nconst rejectedCandidateFromFailure = (failure: ProviderFailureEntry): ResearchRejectedCandidate | null => {\n const details = failure.error.details ?? {};\n if (details.fallbackOutputReason !== \"research_dead_end_shell\") return null;\n const retrievalPath = typeof details.retrievalPath === \"string\" ? details.retrievalPath : undefined;\n const url = typeof details.url === \"string\" ? details.url : undefined;\n return {\n provider: failure.provider,\n source: failure.source,\n reason: \"research_dead_end_shell\",\n replacement_status: \"rejected_before_synthesis\",\n ...(retrievalPath ? { retrievalPath } : {}),\n ...(url ? { url } : {})\n };\n};\n\nconst rejectedCandidatesFromFailures = (failures: ProviderFailureEntry[]): ResearchRejectedCandidate[] => (\n failures.map(rejectedCandidateFromFailure).filter((candidate): candidate is ResearchRejectedCandidate => candidate !== null)\n);\n\nconst isValidHttpUrl = (url: string): boolean => {\n try {\n const parsed = new URL(url.trim());\n return parsed.protocol === \"http:\" || parsed.protocol === \"https:\";\n } catch {\n return false;\n }\n};\n\nconst classifyInvalidProductTarget = (\n record: NormalizedRecord\n): { reason: \"http_status\" | \"not_found_shell\" | \"provider_error_shell\"; message: string } | null => {\n const status = asNumber(record.attributes.status);\n if (status === 404 || status === 410) {\n return {\n reason: \"http_status\",\n message: \"Product target appears to be a not-found page\"\n };\n }\n\n const title = normalizePlainText(record.title);\n const content = normalizePlainText(record.content);\n const combined = `${title} ${content}`.trim();\n if ((/\\b404\\b/i.test(title) || /\\bnot found\\b/i.test(title) || /\\b404\\b/i.test(content)) && PRODUCT_TARGET_NOT_FOUND_RE.test(combined)) {\n return {\n reason: \"not_found_shell\",\n message: \"Product target appears to be a not-found page\"\n };\n }\n const providerId = resolveShoppingProviderIdForUrl(record.url ?? \"\");\n if (\n providerId === \"shopping/bestbuy\"\n && combined.toLowerCase().includes(\"something went wrong\")\n && BESTBUY_PDP_ERROR_SHELL_RE.test(combined)\n ) {\n return {\n reason: \"provider_error_shell\",\n message: \"Best Buy product target returned a generic error shell\"\n };\n }\n return null;\n};\n\nexport const runResearchWorkflow = async (\n runtime: ProviderExecutor,\n input: ResearchRunInput | WorkflowResumeEnvelope\n): Promise<Record<string, unknown>> => {\n const envelope = isWorkflowResumeEnvelope(input as unknown as JsonValue)\n ? input as WorkflowResumeEnvelope\n : buildWorkflowResumeEnvelope(\"research\", input as unknown as JsonValue);\n if (envelope.kind !== \"research\") {\n throw new Error(`Research workflow envelope kind mismatch. Expected research but received ${envelope.kind}.`);\n }\n\n const rawWorkflowInput = envelope.input as unknown as ResearchRunInput;\n const artifactRoot = resolveWorkflowArtifactRoot(rawWorkflowInput.outputDir);\n const workflowInput: ResearchRunInput = { ...rawWorkflowInput, outputDir: artifactRoot };\n let trace: WorkflowTraceEntry[] = [\n ...(envelope.trace ?? []),\n {\n at: new Date().toISOString(),\n stage: \"compile\",\n event: \"compile_started\",\n details: {\n kind: \"research\"\n }\n }\n ];\n const plan = compileResearchExecutionPlan({\n input: workflowInput,\n envelope,\n now: new Date(),\n getDegradedProviders: () => getRuntimeDegradedProviders(runtime)\n });\n trace = [\n ...trace,\n {\n at: new Date().toISOString(),\n stage: \"compile\",\n event: \"compile_completed\",\n details: {\n searchSteps: plan.plan.steps.length,\n completedSteps: plan.checkpointState.completed_step_ids.length\n }\n }\n ];\n\n const buildResearchStepOptions = (\n step: ResearchWorkflowExecutionStep,\n stepEnvelope: WorkflowResumeEnvelope\n ): ProviderRunOptions => {\n const timeoutMs = resolveResearchProviderStepTimeoutMs(workflowInput.timeoutMs);\n const stepOptions = withBrowserModeOverride(\n withChallengeAutomationOverride(\n withCookieOverrides({\n source: step.input.source,\n ...(typeof timeoutMs === \"number\" ? { timeoutMs } : {})\n }, workflowInput),\n workflowInput\n ),\n workflowInput\n );\n\n return withWorkflowResumeEnvelopeIntent(\n stepOptions,\n \"workflow.research\",\n stepEnvelope\n );\n };\n\n const execution = await executeResearchWorkflowPlan(runtime, plan, {\n trace,\n buildStepOptions: buildResearchStepOptions,\n observeResult: (result) => {\n observeWorkflowSignals(runtime, result);\n }\n });\n\n const excludedProviderSet = new Set(plan.compiled.autoExcludedProviders);\n const rawRecords = [\n ...execution.searchRuns.flatMap((run) => run.result.records),\n ...execution.followUpRuns.flatMap((run) => run.result.records)\n ];\n const rawFailures = [\n ...execution.searchRuns.flatMap((run) => run.result.failures),\n ...execution.followUpRuns.flatMap((run) => run.result.failures)\n ];\n const mergedRecords = removeExcludedProviders(rawRecords, excludedProviderSet);\n const sanitizedRecords = sanitizeResearchRecords(mergedRecords);\n const mergedFailures = removeExcludedProviders(rawFailures, excludedProviderSet);\n const rejectedFailureCandidates = rejectedCandidatesFromFailures(mergedFailures);\n const rejectedCandidates = [\n ...sanitizedRecords.rejectedCandidates,\n ...rejectedFailureCandidates\n ].slice(0, RESEARCH_REJECTED_CANDIDATE_LIMIT);\n const rejectedCandidateCount = sanitizedRecords.sanitizedCount + rejectedFailureCandidates.length;\n const reasonCodeDistribution = summarizeReasonCodeDistribution(mergedFailures);\n const transcriptStrategyFailures = summarizeTranscriptStrategyFailures(mergedFailures);\n const evaluationNow = new Date();\n const withinTimebox = filterByTimebox(sanitizedRecords.records, plan.compiled.timebox, evaluationNow);\n const enriched = enrichResearchRecords(withinTimebox, plan.compiled.timebox, evaluationNow);\n const deduped = dedupeResearchRecords(enriched);\n const ranked = rankResearchRecords(deduped);\n const cookieDiagnostics = summarizeCookieDiagnostics(mergedFailures, mergedRecords);\n const challengeOrchestration = summarizeChallengeOrchestration(mergedFailures, mergedRecords);\n const transcriptStrategyDetailDistribution = summarizeTranscriptStrategyDetailDistribution(ranked);\n const transcriptDurability = summarizeTranscriptDurability(ranked, mergedFailures);\n const antiBotPressure = summarizeAntiBotPressure(mergedFailures);\n const resolvedTimebox = plan.compiled.timebox.mode === \"days\"\n ? {\n ...plan.compiled.timebox,\n to: new Date(Math.max(new Date(plan.compiled.timebox.to).getTime(), evaluationNow.getTime())).toISOString()\n }\n : plan.compiled.timebox;\n\n if (mergedRecords.length > 0 && sanitizedRecords.records.length === 0) {\n const sanitizedReasons = Object.entries(sanitizedRecords.reasonDistribution)\n .map(([reason, count]) => `${reason}:${count}`)\n .join(\",\");\n throw new Error(\n `Research workflow produced only shell records and no usable results (${sanitizedReasons || \"sanitized\"}).`\n );\n }\n\n if (sanitizedRecords.records.length > 0 && withinTimebox.length === 0) {\n throw new Error(\"Research workflow produced no usable in-timebox results after sanitization.\");\n }\n\n if (ranked.length === 0) {\n throw new Error(\"Research workflow produced no usable results after post-processing.\");\n }\n\n const primaryConstraintFailures = selectResearchPrimaryConstraintFailures(mergedFailures);\n const meta = withPrimaryConstraintMeta({\n timebox: resolvedTimebox,\n selection: withExcludedProviders({\n source_selection: plan.compiled.sourceSelection,\n resolved_sources: plan.compiled.resolvedSources,\n ...(workflowInput.browserMode ? { requested_browser_mode: workflowInput.browserMode } : {})\n\t }, plan.compiled.autoExcludedProviders),\n\t metrics: {\n\t total_records: mergedRecords.length,\n\t sanitized_records: sanitizedRecords.sanitizedCount,\n\t rejected_candidate_count: rejectedCandidateCount,\n\t sanitized_reason_distribution: sanitizedRecords.reasonDistribution,\n\t sanitizedReasonDistribution: sanitizedRecords.reasonDistribution,\n\t rejected_candidate_sample_size: rejectedCandidates.length,\n\t within_timebox: withinTimebox.length,\n final_records: ranked.length,\n failed_sources: execution.searchRuns.filter((run) => !run.result.ok).map((run) => run.source),\n reasonCodeDistribution,\n transcript_strategy_failures: transcriptStrategyFailures,\n transcriptStrategyFailures,\n transcript_strategy_detail_failures: transcriptStrategyFailures,\n transcriptStrategyDetailFailures: transcriptStrategyFailures,\n transcript_strategy_detail_distribution: transcriptStrategyDetailDistribution,\n transcriptStrategyDetailDistribution,\n transcript_durability: transcriptDurability,\n transcriptDurability,\n cookie_diagnostics: cookieDiagnostics,\n cookieDiagnostics,\n challenge_orchestration: challengeOrchestration,\n challengeOrchestration,\n anti_bot_pressure: antiBotPressure,\n antiBotPressure\n },\n\t failures: mergedFailures,\n\t rejected_candidates: rejectedCandidates,\n\t rejectedCandidates,\n\t alerts: buildWorkflowAlerts(runtime, mergedFailures)\n } as Record<string, unknown>, primaryConstraintFailures);\n const handoff = buildResearchSuccessHandoff({\n topic: plan.compiled.topic,\n browserMode: workflowInput.browserMode,\n failures: mergedFailures,\n cookieDiagnostics,\n challengeOrchestration\n });\n const responseMeta = withFollowthroughMeta(meta, handoff);\n\n const renderMode = workflowInput.mode ?? \"compact\";\n const rendered = renderResearch({\n mode: renderMode,\n topic: plan.compiled.topic,\n records: ranked,\n meta: responseMeta\n });\n\n const bundle = await createArtifactBundle({\n namespace: \"research\",\n outputDir: artifactRoot,\n ttlHours: workflowInput.ttlHours,\n files: rendered.files\n });\n\n if (renderMode === \"path\") {\n return {\n ...rendered.response,\n ...handoff,\n artifact_path: bundle.basePath,\n records: ranked,\n meta: {\n ...responseMeta,\n artifact_manifest: bundle.manifest\n }\n };\n }\n\n return {\n ...rendered.response,\n ...handoff,\n artifact_path: bundle.basePath,\n records: ranked,\n meta: {\n ...responseMeta,\n artifact_manifest: bundle.manifest\n }\n };\n};\n\nexport const runShoppingWorkflow = async (\n runtime: ProviderExecutor,\n input: ShoppingRunInput | WorkflowResumeEnvelope\n): Promise<Record<string, unknown>> => {\n const envelope = isWorkflowResumeEnvelope(input as unknown as JsonValue)\n ? input as WorkflowResumeEnvelope\n : buildWorkflowResumeEnvelope(\"shopping\", input as unknown as JsonValue);\n if (envelope.kind !== \"shopping\") {\n throw new Error(`Shopping workflow envelope kind mismatch. Expected shopping but received ${envelope.kind}.`);\n }\n\n const rawWorkflowInput = envelope.input as unknown as ShoppingRunInput;\n const artifactRoot = resolveWorkflowArtifactRoot(rawWorkflowInput.outputDir);\n const workflowInput: ShoppingRunInput = { ...rawWorkflowInput, outputDir: artifactRoot };\n const remainingTimeoutMs = createRemainingTimeoutResolver(workflowInput.timeoutMs);\n let trace: WorkflowTraceEntry[] = [\n ...(envelope.trace ?? []),\n {\n at: new Date().toISOString(),\n stage: \"compile\",\n event: \"compile_started\",\n details: {\n kind: \"shopping\"\n }\n }\n ];\n const plan = compileShoppingExecutionPlan({\n input: workflowInput,\n envelope,\n now: new Date(),\n getDegradedProviders: (providerIds) => getRuntimeDegradedProviders(runtime, providerIds)\n });\n trace = [\n ...trace,\n {\n at: new Date().toISOString(),\n stage: \"compile\",\n event: \"compile_completed\",\n details: {\n searchSteps: plan.plan.steps.length,\n completedSteps: plan.checkpointState.completed_step_ids.length\n }\n }\n ];\n\n const buildShoppingStepOptions = (\n step: ShoppingWorkflowExecutionStep,\n stepEnvelope: WorkflowResumeEnvelope\n ): ProviderRunOptions => {\n const timeoutMs = remainingTimeoutMs();\n const stepOptions = withBrowserModeOverride(\n withChallengeAutomationOverride(\n withCookieOverrides({\n source: \"shopping\",\n providerIds: [step.input.providerId],\n ...(typeof timeoutMs === \"number\" ? { timeoutMs } : {})\n }, workflowInput),\n workflowInput\n ),\n workflowInput\n );\n\n return withWorkflowResumeEnvelopeIntent(\n stepOptions,\n \"workflow.shopping\",\n stepEnvelope\n );\n };\n\n const execution = await executeShoppingWorkflowPlan(runtime, plan, {\n trace,\n buildStepOptions: buildShoppingStepOptions,\n observeResult: (result) => {\n observeWorkflowSignals(runtime, result);\n }\n });\n\n const {\n offers,\n failures,\n records,\n zeroPriceExcluded,\n budgetExcluded,\n regionCurrencyExcluded,\n offerFilterDiagnostics\n } = postprocessShoppingWorkflow(plan.compiled, execution.runs);\n const reasonCodeDistribution = summarizeReasonCodeDistribution(failures);\n const transcriptStrategyFailures = summarizeTranscriptStrategyFailures(failures);\n const transcriptStrategyDetailDistribution = summarizeTranscriptStrategyDetailDistribution(records);\n const transcriptDurability = summarizeTranscriptDurability(records, failures);\n const cookieDiagnostics = summarizeCookieDiagnostics(failures, records);\n const challengeOrchestration = summarizeChallengeOrchestration(failures, records);\n const browserFallbackModesObserved = summarizeBrowserFallbackModes(failures, records);\n const antiBotPressure = summarizeAntiBotPressure(failures);\n const alerts = buildWorkflowAlerts(runtime, failures, plan.compiled.effectiveProviderIds);\n const regionEnforced = plan.compiled.regionDiagnostics.length > 0\n ? plan.compiled.regionDiagnostics.every((entry) => entry.enforced)\n : false;\n if (plan.compiled.regionDiagnostics.length > 0) {\n alerts.push({\n signal: \"region_unenforced\",\n reasonCode: \"region_unenforced\",\n state: \"warning\",\n reason: \"Default shopping adapters currently use provider default storefronts, so requested region filters are advisory only and not authoritative.\",\n providers: plan.compiled.regionDiagnostics.map((entry) => entry.provider),\n requested_region: workflowInput.region ?? plan.compiled.regionDiagnostics[0]?.requestedRegion ?? \"\"\n });\n }\n let meta = withPrimaryConstraintMeta({\n selection: {\n providers: plan.compiled.effectiveProviderIds,\n ...(plan.compiled.autoExcludedProviders.length > 0 ? { excluded_providers: plan.compiled.autoExcludedProviders } : {}),\n ...(workflowInput.browserMode ? { requested_browser_mode: workflowInput.browserMode } : {}),\n ...(workflowInput.region\n ? {\n requested_region: workflowInput.region,\n region_enforced: regionEnforced,\n region_authoritative: regionEnforced,\n region_support: plan.compiled.regionDiagnostics\n }\n : {})\n },\n metrics: {\n total_offers: offers.length,\n candidate_offers: offerFilterDiagnostics.reduce((sum, entry) => sum + entry.candidateOffers, 0),\n failed_providers: failures.map((entry) => entry.provider),\n reasonCodeDistribution,\n transcript_strategy_failures: transcriptStrategyFailures,\n transcriptStrategyFailures,\n transcript_strategy_detail_failures: transcriptStrategyFailures,\n transcriptStrategyDetailFailures: transcriptStrategyFailures,\n transcript_strategy_detail_distribution: transcriptStrategyDetailDistribution,\n transcriptStrategyDetailDistribution,\n transcript_durability: transcriptDurability,\n transcriptDurability,\n cookie_diagnostics: cookieDiagnostics,\n cookieDiagnostics,\n challenge_orchestration: challengeOrchestration,\n challengeOrchestration,\n browser_fallback_modes_observed: browserFallbackModesObserved,\n browserFallbackModesObserved,\n anti_bot_pressure: antiBotPressure,\n antiBotPressure,\n zero_price_excluded: zeroPriceExcluded,\n budget_excluded: budgetExcluded,\n region_currency_excluded: regionCurrencyExcluded\n },\n offerFilterDiagnostics,\n failures,\n alerts\n } as Record<string, unknown>, failures);\n\n const filterConstraintSummary = summarizeShoppingOfferFilterConstraint({\n diagnostics: offerFilterDiagnostics,\n budget: plan.compiled.budget,\n region: workflowInput.region,\n regionEnforced,\n failures\n });\n if (typeof filterConstraintSummary === \"string\") {\n meta = withPrimaryConstraintSummaryOverride(meta, filterConstraintSummary);\n }\n const handoff = buildShoppingSuccessHandoff({\n query: plan.compiled.query,\n providers: plan.compiled.providerIds,\n budget: plan.compiled.budget,\n region: workflowInput.region,\n browserMode: workflowInput.browserMode,\n sort: workflowInput.sort\n });\n const responseMeta = withFollowthroughMeta(meta, handoff);\n\n const rendered = renderShopping({\n mode: workflowInput.mode,\n query: plan.compiled.query,\n offers,\n meta: responseMeta\n });\n\n const bundle = await createArtifactBundle({\n namespace: \"shopping\",\n outputDir: artifactRoot,\n ttlHours: workflowInput.ttlHours,\n files: rendered.files\n });\n\n if (workflowInput.mode === \"path\") {\n return {\n ...rendered.response,\n ...handoff,\n artifact_path: bundle.basePath,\n offers,\n meta: {\n ...responseMeta,\n artifact_manifest: bundle.manifest\n }\n };\n }\n\n return {\n ...rendered.response,\n ...handoff,\n offers,\n artifact_path: bundle.basePath,\n meta: {\n ...responseMeta,\n artifact_manifest: bundle.manifest\n }\n };\n};\n\nexport const runInspiredesignWorkflow = async (\n runtime: ReferenceRetrievalPort,\n input: InspiredesignRunInput | WorkflowResumeEnvelope,\n options: InspiredesignWorkflowOptions = {}\n): Promise<Record<string, unknown>> => {\n const { envelope, workflowInput: rawWorkflowInput } = buildInspiredesignEnvelope(input);\n const artifactRoot = resolveWorkflowArtifactRoot(rawWorkflowInput.outputDir);\n let workflowInput: InspiredesignResolvedInput = { ...rawWorkflowInput, outputDir: artifactRoot };\n const remainingTimeoutMs = createRemainingTimeoutResolver(workflowInput.timeoutMs);\n const visualEvidenceTempDir = workflowInput.visualEvidence !== \"off\"\n ? await mkdtemp(join(tmpdir(), \"inspiredesign-visual-\"))\n : undefined;\n try {\n const discovery = await discoverInspiredesignReferences(\n runtime,\n workflowInput,\n envelope,\n workflowInput.query ? remainingTimeoutMs() : undefined\n );\n workflowInput = {\n ...workflowInput,\n urls: mergeInspiredesignReferenceUrls(\n workflowInput.urls,\n discovery.acceptedUrls,\n workflowInput.referenceLimit ?? workflowInput.urls.length + discovery.acceptedUrls.length\n ),\n captureMode: resolveInspiredesignCaptureMode(workflowInput.captureMode, [\n ...workflowInput.urls,\n ...discovery.acceptedUrls\n ])\n };\n let trace = appendWorkflowTrace(envelope.trace ?? [], \"compile\", \"compile_started\", {\n kind: \"inspiredesign\"\n });\n trace = appendWorkflowTrace(trace, \"compile\", \"compile_completed\", {\n kind: \"inspiredesign\",\n urlCount: workflowInput.urls.length,\n captureMode: workflowInput.captureMode\n });\n\n const references: InspiredesignReferenceEvidence[] = [];\n const failures: ProviderFailureEntry[] = [...discovery.failures];\n for (const [index, url] of workflowInput.urls.entries()) {\n const stepTrace = appendWorkflowTrace(trace, \"execute\", \"reference_started\", {\n stepIndex: index,\n url\n });\n const fetchTimeoutMs = remainingTimeoutMs();\n const fetchResult = await runtime.fetch(\n { url },\n buildInspiredesignReferenceFetchOptions(\n workflowInput,\n buildInspiredesignStepEnvelope(workflowInput, stepTrace, index, url),\n url,\n fetchTimeoutMs\n )\n );\n const result = normalizeInspiredesignFetchResult(fetchResult);\n observeWorkflowSignals(runtime, result);\n const captureTimeoutMs = remainingTimeoutMs();\n const visualPlan = buildInspiredesignVisualCapturePlan(\n url,\n workflowInput,\n result,\n visualEvidenceTempDir\n );\n const capture = await captureInspiredesignReference(\n url,\n workflowInput.captureMode,\n workflowInput,\n options.captureReference,\n visualPlan,\n captureTimeoutMs\n );\n const reference = buildInspiredesignReference(url, result, capture);\n references.push(reference);\n if (reference.fetchStatus === \"failed\" && !isInspiredesignFetchRecovered(reference)) {\n const fetchFailures = result.failures.length > 0 ? result.failures : failureFromInspiredesignFetchError(result);\n const siteRecipe = resolveSiteRecipeForUrl(url);\n failures.push(...(siteRecipe ? normalizeSiteRecipeFetchFailures(siteRecipe, fetchFailures) : fetchFailures));\n }\n trace = appendWorkflowTrace(stepTrace, \"execute\", \"reference_completed\", {\n stepIndex: index,\n url,\n fetchStatus: result.records.length > 0 ? \"captured\" : \"failed\",\n captureStatus: capture.captureStatus\n });\n }\n\tconst visualCollation = await finalizeInspiredesignVisualArtifacts(references, workflowInput.visualEvidence);\n\n const packet = buildInspiredesignPacket({\n brief: workflowInput.brief,\n briefExpansion: workflowInput.briefExpansion,\n urls: workflowInput.urls,\n references: visualCollation.references,\n includePrototypeGuidance: workflowInput.includePrototypeGuidance,\n referenceEvidenceRequired: isInspiredesignReferenceEvidenceRequired(workflowInput)\n });\n const meta = buildInspiredesignMeta(\n runtime,\n workflowInput,\n visualCollation.references,\n failures,\n packet.followthrough,\n discovery\n );\n const nextStepGuidance = routeNextStepGuidance(createInspiredesignGuidanceContext(\n buildInspiredesignGuidanceSource(\n workflowInput,\n discovery,\n meta,\n packet.generationPlan.referencePatternBoard\n )\n ));\n const metaWithGuidance = {\n ...meta,\n followthroughSummary: nextStepGuidance.readiness === \"ready\"\n ? meta.followthroughSummary\n : buildInspiredesignGuidanceFollowthroughSummary(\n packet.followthrough,\n meta,\n nextStepGuidance\n ),\n nextStepGuidance\n };\n const rendered = renderInspiredesign({\n mode: workflowInput.mode,\n brief: workflowInput.brief,\n advancedBriefMarkdown: packet.advancedBriefMarkdown,\n urls: workflowInput.urls,\n designContract: packet.designContract,\n canvasPlanRequest: packet.canvasPlanRequest,\n designAgentHandoff: packet.followthrough,\n generationPlan: packet.generationPlan,\n implementationPlan: packet.implementationPlan,\n designMarkdown: packet.designMarkdown,\n implementationPlanMarkdown: packet.implementationPlanMarkdown,\n prototypeGuidanceMarkdown: packet.prototypeGuidanceMarkdown,\n evidence: packet.evidence,\n visualEvidence: packet.visualEvidence,\n screenshotIndex: packet.screenshotIndex,\n rankedReferences: packet.rankedReferences,\n referencePatternBoard: buildInspiredesignRankedArtifactPatternBoard(\n packet.generationPlan.referencePatternBoard,\n packet.referencePatternBoard\n ),\n metaPromptMarkdown: packet.metaPromptMarkdown,\n nextStepGuidance,\n meta: metaWithGuidance\n });\n const bundle = await createArtifactBundle({\n namespace: \"inspiredesign\",\n outputDir: artifactRoot,\n ttlHours: workflowInput.ttlHours,\n files: [...rendered.files, ...visualCollation.files]\n });\n\n if (workflowInput.mode === \"path\") {\n return {\n ...rendered.response,\n artifact_path: bundle.basePath,\n meta: {\n ...metaWithGuidance,\n artifact_manifest: bundle.manifest\n }\n };\n }\n\n return {\n ...rendered.response,\n artifact_path: bundle.basePath,\n meta: {\n ...metaWithGuidance,\n artifact_manifest: bundle.manifest\n }\n };\n } finally {\n if (visualEvidenceTempDir) {\n await rm(visualEvidenceTempDir, { recursive: true, force: true }).catch(() => undefined);\n }\n }\n};\n\nexport const runProductVideoWorkflow = async (\n runtime: ProviderExecutor,\n input: ProductVideoRunInput | WorkflowResumeEnvelope,\n options: ProductVideoWorkflowOptions = {}\n): Promise<Record<string, unknown>> => {\n const envelope = isWorkflowResumeEnvelope(input as unknown as JsonValue)\n ? input as WorkflowResumeEnvelope\n : buildWorkflowResumeEnvelope(\"product_video\", input as unknown as JsonValue);\n if (envelope.kind !== \"product_video\") {\n throw new Error(`Product-video workflow envelope kind mismatch. Expected product_video but received ${envelope.kind}.`);\n }\n\n let trace: WorkflowTraceEntry[] = [\n ...(envelope.trace ?? []),\n {\n at: new Date().toISOString(),\n stage: \"compile\",\n event: \"compile_started\",\n details: {\n kind: \"product_video\"\n }\n }\n ];\n const plan = compileProductVideoExecutionPlan({\n input: envelope.input as unknown as ProductVideoRunInput,\n envelope\n });\n trace = [\n ...trace,\n {\n at: new Date().toISOString(),\n stage: \"compile\",\n event: \"compile_completed\",\n details: {\n steps: plan.plan.steps.length,\n completedSteps: plan.checkpointState.completed_step_ids.length,\n resolutionRequired: plan.compiled.resolutionRequired\n }\n }\n ];\n\n const rawWorkflowInput = plan.input;\n const productVideoArtifactRoot = resolveWorkflowArtifactRoot(rawWorkflowInput.output_dir);\n const workflowInput = { ...rawWorkflowInput, output_dir: productVideoArtifactRoot };\n const includeScreenshots = plan.compiled.includeScreenshots;\n const includeAllImages = plan.compiled.includeAllImages;\n const includeCopy = plan.compiled.includeCopy;\n const timeoutOptions = typeof workflowInput.timeoutMs === \"number\"\n ? { timeoutMs: workflowInput.timeoutMs }\n : {};\n const remainingTimeoutMs = createRemainingTimeoutResolver(workflowInput.timeoutMs);\n const appendProductVideoTrace = (\n currentTrace: WorkflowTraceEntry[],\n stage: WorkflowTraceEntry[\"stage\"],\n event: string,\n details: Record<string, JsonValue>\n ): WorkflowTraceEntry[] => [\n ...currentTrace,\n {\n at: new Date().toISOString(),\n stage,\n event,\n details\n }\n ];\n const buildProductVideoCheckpoint = (\n checkpointState: ProductVideoWorkflowCheckpointState,\n step: ProductVideoWorkflowExecutionStep,\n stepIndex: number\n ): WorkflowCheckpoint => ({\n stage: \"execute\",\n stepId: step.id,\n stepIndex,\n state: serializeProductVideoCheckpointState(checkpointState),\n updatedAt: new Date().toISOString()\n });\n const markProductVideoStepCompleted = (\n checkpointState: ProductVideoWorkflowCheckpointState,\n stepId: string,\n updates: Partial<Omit<ProductVideoWorkflowCheckpointState, \"completed_step_ids\">> = {}\n ): ProductVideoWorkflowCheckpointState => ({\n ...checkpointState,\n ...updates,\n completed_step_ids: checkpointState.completed_step_ids.includes(stepId)\n ? checkpointState.completed_step_ids\n : [...checkpointState.completed_step_ids, stepId]\n });\n const getRequiredProductVideoStep = <\n TStepId extends ProductVideoWorkflowExecutionStep[\"id\"]\n >(stepId: TStepId): Extract<ProductVideoWorkflowExecutionStep, { id: TStepId }> =>\n getRequiredProductVideoExecutionStep(plan.plan.steps, stepId);\n\n let checkpointState: ProductVideoWorkflowCheckpointState = {\n ...plan.checkpointState,\n completed_step_ids: [...plan.checkpointState.completed_step_ids]\n };\n let productUrl = checkpointState.resolved_product_url ?? plan.compiled.productUrl;\n let providerHint = checkpointState.resolved_provider_hint ?? plan.compiled.providerHint;\n let stepIndex = 0;\n\n const normalizeStep = getRequiredProductVideoStep(PRODUCT_VIDEO_STEP_IDS.normalizeInput);\n stepIndex += 1;\n trace = appendProductVideoTrace(trace, \"execute\", \"step_started\", {\n stepId: normalizeStep.id,\n stepKind: normalizeStep.kind\n });\n checkpointState = markProductVideoStepCompleted(checkpointState, normalizeStep.id);\n trace = appendProductVideoTrace(trace, \"execute\", \"step_completed\", {\n stepId: normalizeStep.id,\n stepKind: normalizeStep.kind,\n resolutionRequired: plan.compiled.resolutionRequired\n });\n\n const resolveStep = plan.plan.steps.find(\n (step): step is Extract<ProductVideoWorkflowExecutionStep, { id: typeof PRODUCT_VIDEO_STEP_IDS.resolveProductUrl }> => (\n step.id === PRODUCT_VIDEO_STEP_IDS.resolveProductUrl\n )\n );\n if (resolveStep) {\n const currentStepIndex = stepIndex;\n stepIndex += 1;\n if (checkpointState.completed_step_ids.includes(resolveStep.id)) {\n if (!checkpointState.resolved_product_url) {\n throw new Error(\"Product-video workflow checkpoint is missing resolved_product_url for a completed resolution step.\");\n }\n productUrl = checkpointState.resolved_product_url;\n providerHint = checkpointState.resolved_provider_hint ?? providerHint;\n trace = appendProductVideoTrace(trace, \"resume\", \"step_reused\", {\n stepId: resolveStep.id,\n stepKind: resolveStep.kind\n });\n } else {\n trace = appendProductVideoTrace(trace, \"execute\", \"step_started\", {\n stepId: resolveStep.id,\n stepKind: resolveStep.kind\n });\n const shoppingResult = await runShoppingWorkflow(runtime, {\n query: resolveStep.input.product_name,\n providers: providerHint ? [providerHint] : undefined,\n mode: \"json\",\n outputDir: productVideoArtifactRoot,\n ttlHours: workflowInput.ttl_hours,\n ...timeoutOptions,\n browserMode: workflowInput.browserMode,\n useCookies: workflowInput.useCookies,\n challengeAutomationMode: workflowInput.challengeAutomationMode,\n cookiePolicyOverride: workflowInput.cookiePolicyOverride\n });\n\n const offers = shoppingResult.offers as ShoppingOffer[];\n const resolutionSummary = (shoppingResult.meta as Record<string, unknown>).primaryConstraintSummary;\n if (offers.length === 0) {\n throw new Error(\n typeof resolutionSummary === \"string\"\n ? resolutionSummary\n : (\n /* c8 ignore next -- no-offer shopping responses always carry a canonical summary */\n \"Unable to resolve product URL from product_name\"\n )\n );\n }\n const resolvedOffer = offers.find((offer) => /^https?:\\/\\//i.test(offer.url)) ?? offers[0];\n productUrl = resolvedOffer?.url;\n providerHint = resolvedOffer?.provider;\n checkpointState = markProductVideoStepCompleted(checkpointState, resolveStep.id, {\n resolved_product_url: productUrl,\n resolved_provider_hint: providerHint\n });\n trace = appendProductVideoTrace(trace, \"execute\", \"step_completed\", {\n stepId: resolveStep.id,\n stepKind: resolveStep.kind,\n offers: offers.length,\n ...(productUrl ? { resolvedProductUrl: productUrl } : {})\n });\n }\n }\n\n if (!productUrl) {\n throw new Error(\"Unable to resolve product URL\");\n }\n\n const fetchStep = getRequiredProductVideoStep(PRODUCT_VIDEO_STEP_IDS.fetchProductDetail);\n let details: ProviderAggregateResult;\n if (checkpointState.completed_step_ids.includes(fetchStep.id)) {\n if (!checkpointState.detail_result) {\n throw new Error(\"Product-video workflow checkpoint is missing detail_result for a completed fetch step.\");\n }\n details = checkpointState.detail_result;\n trace = appendProductVideoTrace(trace, \"resume\", \"step_reused\", {\n stepId: fetchStep.id,\n stepKind: fetchStep.kind,\n productUrl\n });\n stepIndex += 1;\n } else {\n const source = resolveShoppingSourceForUrl(productUrl);\n const shoppingProviderId = source === \"shopping\"\n ? (\n providerHint\n ? (providerHint.startsWith(\"shopping/\") ? providerHint : `shopping/${providerHint}`)\n : resolveShoppingProviderIdForUrl(productUrl)\n )\n : null;\n if (shoppingProviderId) {\n enforceShoppingLegalReviewGate([shoppingProviderId], new Date());\n }\n\n const currentStepIndex = stepIndex;\n stepIndex += 1;\n trace = appendProductVideoTrace(trace, \"execute\", \"step_started\", {\n stepId: fetchStep.id,\n stepKind: fetchStep.kind,\n productUrl,\n ...(shoppingProviderId ? { providerId: shoppingProviderId } : {})\n });\n const checkpoint = buildProductVideoCheckpoint(checkpointState, fetchStep, currentStepIndex);\n const preSuspendTrace = appendProductVideoTrace(trace, \"execute\", \"pre_suspend_checkpoint\", {\n stepId: fetchStep.id,\n stepKind: fetchStep.kind,\n completedSteps: checkpointState.completed_step_ids.length,\n productUrl,\n ...(providerHint ? { providerHint } : {})\n });\n const stepEnvelope = buildWorkflowResumeEnvelope(\n \"product_video\",\n workflowInput as unknown as JsonValue,\n {\n checkpoint,\n trace: preSuspendTrace\n }\n );\n details = await runtime.fetch(\n { url: productUrl },\n withWorkflowResumeEnvelopeIntent(\n withBrowserModeOverride(\n withChallengeAutomationOverride(\n withCookieOverrides({\n source,\n providerIds: shoppingProviderId ? [shoppingProviderId] : undefined,\n ...timeoutOptions\n }, workflowInput),\n workflowInput\n ),\n workflowInput\n ),\n \"workflow.product_video\",\n stepEnvelope\n )\n );\n observeWorkflowSignals(runtime, details);\n checkpointState = markProductVideoStepCompleted(checkpointState, PRODUCT_VIDEO_STEP_IDS.fetchProductDetail, {\n resolved_product_url: productUrl,\n resolved_provider_hint: providerHint,\n detail_result: details\n });\n trace = appendProductVideoTrace(preSuspendTrace, \"execute\", \"step_completed\", {\n stepId: fetchStep.id,\n stepKind: fetchStep.kind,\n records: details.records.length,\n failures: details.failures.length\n });\n }\n\n if (details.records.length === 0) {\n const reason = summarizePrimaryProviderIssue(details.failures)?.summary\n ?? details.error?.message\n ?? \"Product details unavailable\";\n throw new Error(reason);\n }\n\n const extractStep = getRequiredProductVideoStep(PRODUCT_VIDEO_STEP_IDS.extractProductData);\n trace = appendProductVideoTrace(trace, \"execute\", \"step_started\", {\n stepId: extractStep.id,\n stepKind: extractStep.kind\n });\n stepIndex += 1;\n const primary = details.records[0] as NormalizedRecord;\n const invalidTarget = classifyInvalidProductTarget(primary);\n if (invalidTarget) {\n throw new Error(invalidTarget.message);\n }\n const refreshedMetadata = needsProductMetadataRefresh(primary, productUrl)\n ? await refreshProductMetadata(productUrl, remainingTimeoutMs())\n : null;\n const primaryOffer = extractShoppingOffer(primary, new Date());\n const preferredPrice = resolvePreferredProductPrice(primary, productUrl, refreshedMetadata?.price, primaryOffer);\n providerHint = normalizeProductVideoProviderHint(productUrl, providerHint, primary.provider);\n\n const resolvedBrand = resolveProductBrand(primary, productUrl, refreshedMetadata?.brand);\n const resolvedTitle = resolveProductTitle(primary, productUrl, resolvedBrand, refreshedMetadata?.title);\n const resolvedPrice = resolveProductPrice(primary, productUrl, refreshedMetadata?.price, primaryOffer);\n if (\n resolvedPrice.amount <= 0\n && (\n shouldSuppressMarketplacePrice(primary, productUrl, preferredPrice)\n || requiresManualMarketplacePriceFollowUp(productUrl)\n )\n ) {\n throw new Error(buildManualProductPriceFollowUpMessage(productUrl));\n }\n const featureList = deriveFeatureList(primary, productUrl, refreshedMetadata?.features ?? []);\n const imageUrls = mergeImageUrls(primary, refreshedMetadata?.imageUrls ?? []);\n const selectedImageUrls = includeAllImages ? imageUrls : imageUrls.slice(0, 1);\n trace = appendProductVideoTrace(trace, \"execute\", \"step_completed\", {\n stepId: extractStep.id,\n stepKind: extractStep.kind,\n imageCandidates: imageUrls.length,\n featureCount: featureList.length,\n refreshedMetadata: Boolean(refreshedMetadata)\n });\n\n const assembleStep = getRequiredProductVideoStep(PRODUCT_VIDEO_STEP_IDS.assembleArtifacts);\n trace = appendProductVideoTrace(trace, \"execute\", \"step_started\", {\n stepId: assembleStep.id,\n stepKind: assembleStep.kind\n });\n stepIndex += 1;\n const files: ArtifactFile[] = [];\n const imagePaths: string[] = [];\n const imageContents: Buffer[] = [];\n for (const [index, imageUrl] of selectedImageUrls.entries()) {\n const imageContent = await fetchBinary(imageUrl, remainingTimeoutMs());\n if (!imageContent) continue;\n const extension = imageUrl.match(/\\.(png|jpg|jpeg|webp|gif)(?:[?#].*)?$/i)?.[1]?.toLowerCase() ?? \"jpg\";\n const relativePath = `images/image-${String(index + 1).padStart(2, \"0\")}.${extension}`;\n files.push({ path: relativePath, content: imageContent });\n imagePaths.push(relativePath);\n imageContents.push(imageContent);\n }\n\n const screenshotPaths: string[] = [];\n if (includeScreenshots) {\n const screenshotBuffer = options.captureScreenshot\n ? await options.captureScreenshot(productUrl, remainingTimeoutMs())\n : null;\n if (screenshotBuffer) {\n const screenshotPath = \"screenshots/screenshot-01.png\";\n files.push({ path: screenshotPath, content: screenshotBuffer });\n screenshotPaths.push(screenshotPath);\n } else if (imagePaths[0]) {\n const fallbackPath = \"screenshots/screenshot-01.png\";\n files.push({ path: fallbackPath, content: imageContents[0]! });\n screenshotPaths.push(fallbackPath);\n }\n }\n\n const copyText = includeCopy ? resolveProductCopy(primary, productUrl, refreshedMetadata?.description, featureList) : \"\";\n const pricing = resolvedPrice;\n\n const productPayload = {\n title: resolvedTitle,\n brand: resolvedBrand,\n provider: providerHint ?? primary.provider,\n url: productUrl,\n features: featureList,\n copy: copyText\n };\n\n const manifestPayload = {\n run_id: hash(`${productUrl}:${Date.now()}`),\n created_at: new Date().toISOString(),\n source_url: productUrl,\n provider: providerHint ?? primary.provider,\n product: {\n title: productPayload.title,\n brand: productPayload.brand,\n price: pricing,\n features: featureList,\n copy: copyText\n },\n assets: {\n images: imagePaths,\n screenshots: screenshotPaths,\n raw: [\"raw/source-record.json\"]\n }\n };\n\n files.push(\n { path: \"manifest.json\", content: manifestPayload },\n { path: \"product.json\", content: productPayload },\n { path: \"pricing.json\", content: pricing },\n { path: \"copy.md\", content: copyText || \"\" },\n { path: \"features.md\", content: featureList.map((feature) => `- ${feature}`).join(\"\\n\") },\n {\n path: \"raw/source-record.json\",\n content: redactRawCapture(JSON.parse(JSON.stringify(primary)) as Record<string, unknown>)\n }\n );\n trace = appendProductVideoTrace(trace, \"postprocess\", \"step_completed\", {\n stepId: assembleStep.id,\n stepKind: assembleStep.kind,\n images: imagePaths.length,\n screenshots: screenshotPaths.length,\n files: files.length\n });\n\n const bundle = await createArtifactBundle({\n namespace: \"product-video\",\n outputDir: productVideoArtifactRoot,\n ttlHours: workflowInput.ttl_hours,\n files\n });\n\n const reasonCodeDistribution = summarizeReasonCodeDistribution(details.failures);\n const transcriptStrategyFailures = summarizeTranscriptStrategyFailures(details.failures);\n const transcriptStrategyDetailDistribution = summarizeTranscriptStrategyDetailDistribution(details.records);\n const transcriptDurability = summarizeTranscriptDurability(details.records, details.failures);\n const cookieDiagnostics = summarizeCookieDiagnostics(details.failures, details.records);\n const antiBotPressure = summarizeAntiBotPressure(details.failures);\n const primaryIssue = summarizePrimaryProviderIssue(details.failures);\n const handoff = buildProductVideoSuccessHandoff({\n productUrl,\n productName: workflowInput.product_name,\n providerHint,\n browserMode: workflowInput.browserMode,\n includeScreenshots: workflowInput.include_screenshots,\n includeAllImages: workflowInput.include_all_images,\n includeCopy: workflowInput.include_copy\n });\n const meta = withFollowthroughMeta({\n ...(workflowInput.browserMode\n ? { selection: { requested_browser_mode: workflowInput.browserMode } }\n : {}),\n alerts: buildWorkflowAlerts(runtime, details.failures),\n failures: details.failures,\n ...(primaryIssue ? { primaryConstraint: primaryIssue, primaryConstraintSummary: primaryIssue.summary } : {}),\n reasonCodeDistribution,\n transcript_strategy_failures: transcriptStrategyFailures,\n transcriptStrategyFailures,\n transcript_strategy_detail_failures: transcriptStrategyFailures,\n transcriptStrategyDetailFailures: transcriptStrategyFailures,\n transcript_strategy_detail_distribution: transcriptStrategyDetailDistribution,\n transcriptStrategyDetailDistribution,\n transcript_durability: transcriptDurability,\n transcriptDurability,\n cookie_diagnostics: cookieDiagnostics,\n cookieDiagnostics,\n anti_bot_pressure: antiBotPressure,\n antiBotPressure,\n artifact_manifest: bundle.manifest\n }, handoff);\n\n return {\n ...handoff,\n artifact_path: bundle.basePath,\n manifest: manifestPayload,\n product: productPayload,\n pricing,\n screenshots: screenshotPaths,\n images: imagePaths,\n meta\n };\n};\n","import { join } from \"path\";\n\nexport const WORKFLOW_ARTIFACT_DIRECTORY = \".opendevbrowser\";\n\nexport type WorkflowArtifactRootOptions = {\n workspaceRoot?: string;\n};\n\nexport const resolveWorkflowArtifactRoot = (\n outputDir?: string,\n options: WorkflowArtifactRootOptions = {}\n): string => {\n if (outputDir === undefined) {\n return join(options.workspaceRoot ?? process.cwd(), WORKFLOW_ARTIFACT_DIRECTORY);\n }\n if (outputDir.trim() === \"\") {\n throw new Error(\"outputDir cannot be empty\");\n }\n return outputDir;\n};\n","export interface TimeboxInput {\n days?: number;\n from?: string;\n to?: string;\n now?: Date;\n allowDaysWithRange?: boolean;\n}\n\nexport interface ResolvedTimebox {\n mode: \"days\" | \"range\";\n days?: number;\n from: string;\n to: string;\n applied: true;\n}\n\nconst MAX_DAYS = 365;\n\nconst ensureIsoDate = (value: string, label: string): Date => {\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) {\n throw new Error(`Invalid ${label} date: ${value}`);\n }\n return date;\n};\n\nconst clampDays = (days: number): number => {\n if (!Number.isFinite(days) || days <= 0) {\n throw new Error(\"days must be a positive number\");\n }\n return Math.min(MAX_DAYS, Math.floor(days));\n};\n\nexport const resolveTimebox = (input: TimeboxInput): ResolvedTimebox => {\n const now = input.now ?? new Date();\n const hasDays = typeof input.days === \"number\";\n const hasFrom = typeof input.from === \"string\" && input.from.trim().length > 0;\n const hasTo = typeof input.to === \"string\" && input.to.trim().length > 0;\n\n if (hasDays && (hasFrom || hasTo) && !input.allowDaysWithRange) {\n throw new Error(\"days cannot be combined with from/to\");\n }\n\n if (hasTo && !hasFrom && !hasDays) {\n throw new Error(\"to cannot be provided without from or days\");\n }\n\n if (hasDays) {\n const days = clampDays(input.days as number);\n const toDate = now;\n const fromDate = new Date(toDate.getTime() - days * 24 * 60 * 60 * 1000);\n return {\n mode: \"days\",\n days,\n from: fromDate.toISOString(),\n to: toDate.toISOString(),\n applied: true\n };\n }\n\n if (hasFrom) {\n const fromDate = ensureIsoDate(input.from as string, \"from\");\n const toDate = hasTo ? ensureIsoDate(input.to as string, \"to\") : now;\n if (fromDate.getTime() > toDate.getTime()) {\n throw new Error(\"from cannot be later than to\");\n }\n const diffMs = toDate.getTime() - fromDate.getTime();\n const days = Math.max(1, Math.ceil(diffMs / (24 * 60 * 60 * 1000)));\n return {\n mode: \"range\",\n days,\n from: fromDate.toISOString(),\n to: toDate.toISOString(),\n applied: true\n };\n }\n\n const defaultDays = 30;\n const toDate = now;\n const fromDate = new Date(toDate.getTime() - defaultDays * 24 * 60 * 60 * 1000);\n return {\n mode: \"days\",\n days: defaultDays,\n from: fromDate.toISOString(),\n to: toDate.toISOString(),\n applied: true\n };\n};\n\nexport const isWithinTimebox = (\n timestamp: string | undefined,\n timebox: ResolvedTimebox,\n now?: Date\n): boolean => {\n if (!timestamp) return false;\n const value = new Date(timestamp);\n if (Number.isNaN(value.getTime())) return false;\n const from = new Date(timebox.from).getTime();\n const to = new Date(timebox.to).getTime();\n const upperBound =\n timebox.mode === \"days\" ? Math.max(to, now?.getTime() ?? to) : to;\n const current = value.getTime();\n return current >= from && current <= upperBound;\n};\n\nexport const filterByTimebox = <T extends { timestamp?: string }>(\n records: T[],\n timebox: ResolvedTimebox,\n now?: Date\n): T[] => {\n return records.filter((record) =>\n isWithinTimebox(record.timestamp, timebox, now)\n );\n};\n","import type { JsonValue, NormalizedRecord, ProviderSource } from \"./types\";\nimport type { ResolvedTimebox } from \"./timebox\";\nimport { isWithinTimebox } from \"./timebox\";\n\nexport interface EngagementMetrics {\n likes: number;\n comments: number;\n views: number;\n upvotes: number;\n}\n\nexport interface RecencyMetadata {\n within_timebox: boolean;\n age_hours: number;\n}\n\nexport interface DateConfidenceMetadata {\n score: number;\n source: \"explicit\" | \"inferred\" | \"missing\";\n}\n\nexport interface ResearchRecord {\n id: string;\n source: ProviderSource;\n provider: string;\n url?: string;\n title?: string;\n content?: string;\n timestamp: string;\n confidence: number;\n engagement: EngagementMetrics;\n recency: RecencyMetadata;\n date_confidence: DateConfidenceMetadata;\n attributes: Record<string, JsonValue>;\n}\n\nconst asNumber = (value: JsonValue | undefined): number => {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return Math.max(0, value);\n }\n if (typeof value === \"string\" && value.trim()) {\n const normalized = value.replace(/,/g, \"\").trim();\n const parsed = Number(normalized);\n if (Number.isFinite(parsed)) {\n return Math.max(0, parsed);\n }\n }\n return 0;\n};\n\nconst readEngagement = (attributes: Record<string, JsonValue>): EngagementMetrics => {\n const nested = (attributes.engagement ?? {}) as Record<string, JsonValue>;\n return {\n likes: asNumber(nested.likes ?? attributes.likes),\n comments: asNumber(nested.comments ?? attributes.comments),\n views: asNumber(nested.views ?? attributes.views),\n upvotes: asNumber(nested.upvotes ?? attributes.upvotes)\n };\n};\n\nconst computeDateConfidence = (record: NormalizedRecord): DateConfidenceMetadata => {\n const timestamp = new Date(record.timestamp);\n if (!Number.isNaN(timestamp.getTime())) {\n return {\n score: 1,\n source: \"explicit\"\n };\n }\n\n const inferred = record.attributes.published_at;\n if (typeof inferred === \"string\" && !Number.isNaN(new Date(inferred).getTime())) {\n return {\n score: 0.6,\n source: \"inferred\"\n };\n }\n\n return {\n score: 0,\n source: \"missing\"\n };\n};\n\nconst computeRecency = (\n record: NormalizedRecord,\n timebox: ResolvedTimebox,\n now: Date\n): RecencyMetadata => {\n const parsed = new Date(record.timestamp);\n if (Number.isNaN(parsed.getTime())) {\n return {\n within_timebox: false,\n age_hours: Number.POSITIVE_INFINITY\n };\n }\n\n const ageHours = Math.max(0, (now.getTime() - parsed.getTime()) / (60 * 60 * 1000));\n return {\n within_timebox: isWithinTimebox(record.timestamp, timebox, now),\n age_hours: Number(ageHours.toFixed(2))\n };\n};\n\nexport const toResearchRecord = (\n record: NormalizedRecord,\n timebox: ResolvedTimebox,\n now: Date = new Date()\n): ResearchRecord => {\n const engagement = readEngagement(record.attributes);\n const recency = computeRecency(record, timebox, now);\n const dateConfidence = computeDateConfidence(record);\n\n const engagementJson = {\n likes: engagement.likes,\n comments: engagement.comments,\n views: engagement.views,\n upvotes: engagement.upvotes\n };\n const recencyJson = {\n within_timebox: recency.within_timebox,\n age_hours: recency.age_hours\n };\n const dateConfidenceJson = {\n score: dateConfidence.score,\n source: dateConfidence.source\n };\n\n return {\n id: record.id,\n source: record.source,\n provider: record.provider,\n ...(record.url ? { url: record.url } : {}),\n ...(record.title ? { title: record.title } : {}),\n ...(record.content ? { content: record.content } : {}),\n timestamp: record.timestamp,\n confidence: record.confidence,\n engagement,\n recency,\n date_confidence: dateConfidence,\n attributes: {\n ...record.attributes,\n engagement: engagementJson,\n recency: recencyJson,\n date_confidence: dateConfidenceJson\n }\n };\n};\n\nexport const enrichResearchRecords = (\n records: NormalizedRecord[],\n timebox: ResolvedTimebox,\n now: Date = new Date()\n): ResearchRecord[] => {\n return records.map((record) => toResearchRecord(record, timebox, now));\n};\n","import { createHash } from \"crypto\";\nimport generationPlanTemplateJson from \"../../skills/opendevbrowser-design-agent/assets/templates/canvas-generation-plan.design.v1.json\";\nimport designContractTemplateJson from \"../../skills/opendevbrowser-design-agent/assets/templates/design-contract.v1.json\";\nimport type {\n CanvasAsset,\n CanvasComponentInventoryItem,\n CanvasDesignGovernance,\n CanvasGenerationPlan,\n CanvasNavigationModel,\n CanvasVisualDirectionProfile\n} from \"../canvas/types\";\nimport {\n INSPIREDESIGN_ARTIFACT_GUIDE,\n INSPIREDESIGN_CONTRACT_SECTION_GUIDE,\n INSPIREDESIGN_HANDOFF_COMMANDS,\n INSPIREDESIGN_HANDOFF_GUIDANCE,\n INSPIREDESIGN_HANDOFF_RECOMMENDED_SKILLS,\n INSPIREDESIGN_HANDOFF_FILES,\n buildInspiredesignFollowthroughSummary,\n buildInspiredesignNextStep,\n type InspiredesignArtifactGuide,\n type InspiredesignContractSectionGuide\n} from \"./handoff\";\nimport {\n INSPIREDESIGN_BRIEF_COMMON_RULES,\n INSPIREDESIGN_BRIEF_OUTPUT_REQUIREMENTS,\n cloneInspiredesignBriefFormat,\n type InspiredesignBriefExpansion,\n type InspiredesignBriefFormat\n} from \"./brief-expansion\";\nimport {\n buildInspiredesignDesignVectors,\n buildInspiredesignDesignReferencePatternBoard,\n buildInspiredesignReferencePatternBoard,\n getInspiredesignReferenceSignals,\n isInspiredesignDesignReference,\n hasInspiredesignUsableReferenceEvidence,\n type InspiredesignDesignVectors,\n type InspiredesignReferencePatternBoard\n} from \"./reference-pattern-board\";\nimport { buildInspiredesignMetaPrompt } from \"./meta-prompt\";\nimport {\n persistInspiredesignVisualEvidence,\n type InspiredesignPersistedVisualEvidence,\n type InspiredesignVisualEvidenceRuntimeMetadata\n} from \"./visual-evidence\";\nimport type { JsonValue } from \"../providers/types\";\n\ntype JsonRecord = Record<string, JsonValue>;\ntype FetchStatus = \"captured\" | \"failed\" | \"skipped\";\ntype CaptureStatus = \"off\" | \"captured\" | \"failed\";\n\nexport type InspiredesignCaptureAttemptStatus = \"captured\" | \"failed\" | \"skipped\";\n\nexport type InspiredesignCaptureAttemptEvidence = {\n status: InspiredesignCaptureAttemptStatus;\n detail?: string;\n};\n\nexport const INSPIREDESIGN_CAPTURE_ATTEMPT_KEYS = [\"snapshot\", \"clone\", \"dom\"] as const;\n\nexport type InspiredesignCaptureAttemptKey = typeof INSPIREDESIGN_CAPTURE_ATTEMPT_KEYS[number];\n\nexport type InspiredesignCaptureAttempts = {\n snapshot: InspiredesignCaptureAttemptEvidence;\n clone: InspiredesignCaptureAttemptEvidence;\n dom: InspiredesignCaptureAttemptEvidence;\n};\n\ntype DesignContractTemplate = {\n intent: JsonRecord;\n designLanguage: JsonRecord;\n contentModel: JsonRecord;\n navigationModel: JsonRecord;\n asyncModel: JsonRecord;\n layoutSystem: JsonRecord;\n typographySystem: JsonRecord;\n motionSystem: JsonRecord;\n performanceModel: JsonRecord;\n responsiveSystem: JsonRecord;\n accessibilityPolicy: JsonRecord;\n};\n\ntype CanvasPlanRequestTemplate = {\n requestId: string;\n canvasSessionId: string;\n leaseId: string;\n documentId: string;\n generationPlan: CanvasGenerationPlan & {\n designVectors?: JsonRecord;\n };\n};\n\ntype ProfileConfig = {\n direction: string;\n visualPersonality: string;\n brandTone: string;\n hierarchyPrinciples: string[];\n interactionPhilosophy: string;\n navigationModel: CanvasNavigationModel;\n layoutApproach: string;\n pagePatterns: string[];\n componentSequence: string[];\n colors: Record<string, string>;\n};\n\nexport type InspiredesignCaptureEvidence = {\n title?: string;\n snapshot?: {\n content: string;\n refCount: number;\n warnings: string[];\n };\n dom?: {\n outerHTML: string;\n truncated: boolean;\n };\n clone?: {\n componentPreview: string;\n cssPreview: string;\n warnings: string[];\n };\n visual?: InspiredesignVisualEvidenceRuntimeMetadata | InspiredesignPersistedVisualEvidence;\n attempts?: InspiredesignCaptureAttempts;\n};\n\ntype CaptureAttemptSummaryReport = {\n worked: string[];\n didNotWork: string[];\n};\n\nconst MALFORMED_CAPTURE_ATTEMPT_DETAIL = \"Capture attempt metadata missing or malformed.\";\nconst NORMALIZED_CAPTURE_ATTEMPT_DETAIL = \"Captured artifact was empty after normalization.\";\n\nconst isJsonRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n};\n\nconst isInspiredesignCaptureAttemptStatus = (\n value: unknown\n): value is InspiredesignCaptureAttemptStatus => {\n return value === \"captured\" || value === \"failed\" || value === \"skipped\";\n};\n\nconst hasUsableCaptureText = (value: string | undefined): boolean => {\n return typeof value === \"string\" && value.trim().length > 0;\n};\n\nconst hasUsableInspiredesignSnapshot = (\n capture: InspiredesignCaptureEvidence | null | undefined\n): boolean => {\n return hasUsableCaptureText(capture?.snapshot?.content);\n};\n\nconst hasUsableInspiredesignDom = (\n capture: InspiredesignCaptureEvidence | null | undefined\n): boolean => {\n return hasUsableCaptureText(capture?.dom?.outerHTML);\n};\n\nconst hasUsableInspiredesignClone = (\n capture: InspiredesignCaptureEvidence | null | undefined\n): boolean => {\n return hasUsableCaptureText(capture?.clone?.componentPreview)\n || hasUsableCaptureText(capture?.clone?.cssPreview);\n};\n\nconst hasUsableInspiredesignCaptureArtifact = (\n capture: InspiredesignCaptureEvidence,\n key: InspiredesignCaptureAttemptKey\n): boolean => {\n switch (key) {\n case \"snapshot\":\n return hasUsableInspiredesignSnapshot(capture);\n case \"clone\":\n return hasUsableInspiredesignClone(capture);\n case \"dom\":\n return hasUsableInspiredesignDom(capture);\n }\n};\n\nconst reconcileInspiredesignCaptureAttemptEvidence = (\n attempt: InspiredesignCaptureAttemptEvidence,\n artifactPresent: boolean\n): InspiredesignCaptureAttemptEvidence => {\n if (attempt.status !== \"captured\" || artifactPresent) {\n return attempt;\n }\n return {\n status: \"failed\",\n detail: NORMALIZED_CAPTURE_ATTEMPT_DETAIL\n };\n};\n\nconst reconcileInspiredesignCaptureAttempts = (\n capture: InspiredesignCaptureEvidence,\n attempts: InspiredesignCaptureAttempts | undefined\n): InspiredesignCaptureAttempts | undefined => {\n if (!attempts) {\n return undefined;\n }\n return {\n snapshot: reconcileInspiredesignCaptureAttemptEvidence(\n attempts.snapshot,\n hasUsableInspiredesignCaptureArtifact(capture, \"snapshot\")\n ),\n clone: reconcileInspiredesignCaptureAttemptEvidence(\n attempts.clone,\n hasUsableInspiredesignCaptureArtifact(capture, \"clone\")\n ),\n dom: reconcileInspiredesignCaptureAttemptEvidence(\n attempts.dom,\n hasUsableInspiredesignCaptureArtifact(capture, \"dom\")\n )\n };\n};\n\nexport const hasInspiredesignCaptureArtifacts = (\n capture: InspiredesignCaptureEvidence | null | undefined\n): capture is InspiredesignCaptureEvidence => {\n return hasUsableInspiredesignSnapshot(capture)\n || hasUsableInspiredesignDom(capture)\n || hasUsableInspiredesignClone(capture);\n};\n\nexport const normalizeInspiredesignCaptureAttemptEvidence = (\n value: unknown,\n fallbackDetail = MALFORMED_CAPTURE_ATTEMPT_DETAIL\n): InspiredesignCaptureAttemptEvidence => {\n if (!isJsonRecord(value) || !isInspiredesignCaptureAttemptStatus(value.status)) {\n return {\n status: \"skipped\",\n detail: fallbackDetail\n };\n }\n return {\n status: value.status,\n ...(typeof value.detail === \"string\" && value.detail.trim().length > 0\n ? { detail: value.detail.trim() }\n : {})\n };\n};\n\nexport const normalizeInspiredesignCaptureAttempts = (\n value: unknown\n): InspiredesignCaptureAttempts | undefined => {\n if (!isJsonRecord(value)) {\n return undefined;\n }\n return {\n snapshot: normalizeInspiredesignCaptureAttemptEvidence(value.snapshot),\n clone: normalizeInspiredesignCaptureAttemptEvidence(value.clone),\n dom: normalizeInspiredesignCaptureAttemptEvidence(value.dom)\n };\n};\n\nexport const normalizeInspiredesignCaptureEvidence = (\n capture: InspiredesignCaptureEvidence | null | undefined\n): InspiredesignCaptureEvidence | null | undefined => {\n if (!capture) {\n return capture;\n }\n const normalizedBase: InspiredesignCaptureEvidence = {\n ...(capture.title ? { title: capture.title } : {}),\n ...(hasUsableInspiredesignSnapshot(capture) && capture.snapshot ? { snapshot: capture.snapshot } : {}),\n ...(hasUsableInspiredesignDom(capture) && capture.dom ? { dom: capture.dom } : {}),\n ...(hasUsableInspiredesignClone(capture) && capture.clone ? { clone: capture.clone } : {}),\n ...(capture.visual ? { visual: persistInspiredesignVisualEvidence(capture.visual) } : {})\n };\n const attempts = reconcileInspiredesignCaptureAttempts(\n normalizedBase,\n normalizeInspiredesignCaptureAttempts(capture.attempts)\n );\n return {\n ...normalizedBase,\n ...(attempts ? { attempts } : {})\n };\n};\n\nexport const formatInspiredesignCaptureAttemptSummary = (\n report: CaptureAttemptSummaryReport\n): string => {\n const worked = report.worked.length > 0 ? report.worked.join(\", \") : \"none\";\n const didNotWork = report.didNotWork.length > 0 ? report.didNotWork.join(\", \") : \"none\";\n return `worked=${worked}; did_not_work=${didNotWork}`;\n};\n\nexport type InspiredesignReferenceEvidence = {\n id: string;\n url: string;\n title?: string;\n excerpt?: string;\n fetchStatus: FetchStatus;\n captureStatus: CaptureStatus;\n fetchFailure?: string;\n captureFailure?: string;\n capture?: InspiredesignCaptureEvidence | null;\n};\n\nexport type InspiredesignTokenStrategy = {\n colors: Record<string, string>;\n typography: Record<string, string>;\n spacing: Record<string, string>;\n radius: Record<string, string>;\n shadow: Record<string, string>;\n motion: Record<string, string>;\n zIndex: Record<string, number>;\n breakpoints: Record<string, string>;\n};\n\nexport type InspiredesignImplementationPlan = {\n architectureRecommendation: string;\n tokenStrategy: InspiredesignTokenStrategy;\n referenceImplementationNotes: string[];\n componentBuildPlan: Array<{\n name: string;\n purpose: string;\n states: string[];\n implementationNote: string;\n }>;\n pageAssemblyPlan: string[];\n stateAndInteractionPlan: string[];\n accessibilityChecklist: string[];\n responsiveChecklist: string[];\n risksAndAmbiguities: string[];\n buildSequence: string[];\n};\n\ntype InspiredesignGenerationPlan = CanvasGenerationPlan & {\n referencePatternBoard: InspiredesignReferencePatternBoard;\n designVectors: InspiredesignDesignVectors;\n targetAnalysis: InspiredesignTargetAnalysis;\n interactionMoments: string[];\n materialEffects: string[];\n};\n\nexport type InspiredesignVisualEvidenceJson = {\n referenceId: string;\n url: string;\n visual: InspiredesignPersistedVisualEvidence;\n};\n\nexport type InspiredesignScreenshotIndexEntry = {\n referenceId: string;\n url: string;\n path: string;\n sha256: string;\n bytes: number;\n kind: InspiredesignPersistedVisualEvidence[\"kind\"];\n fullPage: boolean;\n capturedAt: string;\n};\n\nexport type InspiredesignPacket = {\n advancedBriefMarkdown: string;\n designContract: CanvasDesignGovernance;\n generationPlan: InspiredesignGenerationPlan;\n canvasPlanRequest: CanvasPlanRequestTemplate;\n followthrough: InspiredesignFollowthrough;\n designMarkdown: string;\n implementationPlan: InspiredesignImplementationPlan;\n implementationPlanMarkdown: string;\n prototypeGuidanceMarkdown: string | null;\n evidence: JsonRecord;\n visualEvidence: InspiredesignVisualEvidenceJson[];\n screenshotIndex: InspiredesignScreenshotIndexEntry[];\n rankedReferences: InspiredesignReferencePatternBoard[\"references\"];\n referencePatternBoard: InspiredesignReferencePatternBoard;\n metaPromptMarkdown: string;\n};\n\nexport type InspiredesignContractScope = {\n emittedContract: \"CanvasDesignGovernance\";\n emittedGovernanceBlocks: string[];\n omittedTemplateBlocks: Array<\"navigationModel\" | \"asyncModel\" | \"performanceModel\">;\n note: string;\n};\n\nexport type InspiredesignImplementationContext = {\n navigationModel: JsonRecord;\n asyncModel: JsonRecord;\n performanceModel: JsonRecord;\n referenceSynthesis: JsonRecord;\n referencePatternBoard: InspiredesignReferencePatternBoard;\n designVectors: InspiredesignDesignVectors;\n targetAnalysis: InspiredesignTargetAnalysis;\n};\n\ntype InspiredesignTargetKind = \"page\" | \"component\" | \"asset\";\n\ntype InspiredesignEvidenceBuckets = {\n anatomy: string[];\n propsSlots: string[];\n stateMatrix: string[];\n tokens: string[];\n assets: string[];\n accessibility: string[];\n motion: string[];\n previewFixtures: string[];\n};\n\ntype InspiredesignComponentInventoryEvidence = Pick<\n CanvasComponentInventoryItem,\n \"id\" | \"name\" | \"componentName\" | \"description\" | \"sourceFamily\" | \"origin\"\n> & {\n variants: CanvasComponentInventoryItem[\"variants\"];\n props: CanvasComponentInventoryItem[\"props\"];\n slots: CanvasComponentInventoryItem[\"slots\"];\n events: CanvasComponentInventoryItem[\"events\"];\n content: CanvasComponentInventoryItem[\"content\"];\n metadata: JsonRecord;\n};\n\ntype InspiredesignAssetEvidence = Pick<\n CanvasAsset,\n \"id\" | \"sourceType\" | \"kind\" | \"url\" | \"status\"\n> & {\n provenanceNotes: string[];\n usageNotes: string[];\n metadata: JsonRecord;\n};\n\ntype InspiredesignTargetAnalysis = {\n primaryKind: InspiredesignTargetKind;\n kinds: InspiredesignTargetKind[];\n confidence: number;\n triggeringSignals: string[];\n evidenceBuckets: InspiredesignEvidenceBuckets;\n page?: {\n canvasType: \"CanvasPage\";\n assemblyFocus: string[];\n implementationNotes: string[];\n };\n component?: {\n canvasType: \"CanvasComponentInventoryItem\";\n inventoryItems: InspiredesignComponentInventoryEvidence[];\n prototypeGuidance: string[];\n };\n asset?: {\n canvasType: \"CanvasAsset\";\n assets: InspiredesignAssetEvidence[];\n prototypeGuidance: string[];\n };\n};\n\nexport type InspiredesignFollowthrough = {\n summary: string;\n nextStep: string;\n nextStepGuidance?: Record<string, JsonValue>;\n artifactGuide: InspiredesignArtifactGuide;\n contractSectionGuide: InspiredesignContractSectionGuide;\n briefExpansion: {\n templateVersion: string;\n file: string;\n format: InspiredesignBriefFormat;\n };\n recommendedSkills: string[];\n commandExamples: {\n loadBestPractices: string;\n loadDesignAgent: string;\n loadMotionDesign: string;\n continueInCanvas: string;\n };\n deepCaptureRecommendation: string;\n contractScope: InspiredesignContractScope;\n implementationContext: InspiredesignImplementationContext;\n};\n\nexport type BuildInspiredesignPacketInput = {\n brief: string;\n briefExpansion: InspiredesignBriefExpansion;\n urls: string[];\n references: InspiredesignReferenceEvidence[];\n includePrototypeGuidance?: boolean;\n referenceEvidenceRequired?: boolean;\n};\n\nconst BASE_CONTRACT_TEMPLATE: DesignContractTemplate = designContractTemplateJson;\nconst BASE_PLAN_REQUEST_TEMPLATE = generationPlanTemplateJson as Omit<CanvasPlanRequestTemplate, \"generationPlan\"> & {\n generationPlan: CanvasGenerationPlan;\n};\nconst BASE_GENERATION_PLAN: CanvasGenerationPlan = BASE_PLAN_REQUEST_TEMPLATE.generationPlan;\n\nconst PROFILE_CONFIG: Record<CanvasVisualDirectionProfile, ProfileConfig> = {\n \"clean-room\": {\n direction: \"clean-room execution\",\n visualPersonality: \"disciplined, quiet, system-first\",\n brandTone: \"neutral and exacting\",\n hierarchyPrinciples: [\"Keep one message per section.\", \"Use spacing, not ornament, to separate priority.\"],\n interactionPhilosophy: \"Minimal motion, zero ambiguity, strong focus affordances.\",\n navigationModel: \"contextual\",\n layoutApproach: \"modular-grid\",\n pagePatterns: [\"Single-message hero\", \"Dense decision panel\", \"Clean spec sheet\"],\n componentSequence: [\"Buttons\", \"Inputs\", \"Decision cards\", \"Structured tables\"],\n colors: {\n primary: \"#0F172A\",\n accent: \"#0F766E\",\n accentSurface: \"#E6FFFB\",\n background: \"#F8FAFC\",\n surface: \"#FFFFFF\",\n border: \"#CBD5E1\",\n text: \"#0F172A\",\n mutedText: \"#475569\",\n success: \"#15803D\",\n warning: \"#B45309\",\n danger: \"#B91C1C\"\n }\n },\n \"cinematic-minimal\": {\n direction: \"cinematic restraint\",\n visualPersonality: \"dramatic, sparse, image-led\",\n brandTone: \"premium and deliberate\",\n hierarchyPrinciples: [\"Let the visual plane carry atmosphere.\", \"Keep copy short and decisive.\"],\n interactionPhilosophy: \"Use motion for presence, not explanation.\",\n navigationModel: \"immersive\",\n layoutApproach: \"full-bleed-hero\",\n pagePatterns: [\"Full-bleed hero\", \"Editorial feature strip\", \"High-contrast CTA block\"],\n componentSequence: [\"Hero shell\", \"CTA buttons\", \"Image-led sections\", \"Minimal footer\"],\n colors: {\n primary: \"#111827\",\n accent: \"#C2410C\",\n accentSurface: \"#FFF7ED\",\n background: \"#F8F5F0\",\n surface: \"#FFFFFF\",\n border: \"#D6D3D1\",\n text: \"#111827\",\n mutedText: \"#57534E\",\n success: \"#15803D\",\n warning: \"#B45309\",\n danger: \"#B91C1C\"\n }\n },\n \"product-story\": {\n direction: \"product-led clarity\",\n visualPersonality: \"confident, editorial, product-first\",\n brandTone: \"clear and ambitious\",\n hierarchyPrinciples: [\"Lead with value before proof.\", \"Keep action close to the message it completes.\"],\n interactionPhilosophy: \"Short, decisive motion with obvious focus states.\",\n navigationModel: \"global-header\",\n layoutApproach: \"hero-led-grid\",\n pagePatterns: [\"Hero with anchored CTA\", \"Feature narrative strip\", \"Proof and conversion band\"],\n componentSequence: [\"Hero\", \"Buttons\", \"Cards\", \"Feature sections\", \"Footer\"],\n colors: {\n primary: \"#0B6BFF\",\n accent: \"#F97316\",\n accentSurface: \"#FFF7ED\",\n background: \"#F5F7FB\",\n surface: \"#FFFFFF\",\n border: \"#D7E3F4\",\n text: \"#111827\",\n mutedText: \"#475569\",\n success: \"#15803D\",\n warning: \"#B45309\",\n danger: \"#B91C1C\"\n }\n },\n \"commerce-system\": {\n direction: \"trust-driven commerce\",\n visualPersonality: \"decisive, reassuring, conversion-aware\",\n brandTone: \"credible and practical\",\n hierarchyPrinciples: [\"Keep purchasing signals scannable.\", \"Surface trust proof before commitment moments.\"],\n interactionPhilosophy: \"Fast feedback, strong affordances, no ambiguous states.\",\n navigationModel: \"global-header\",\n layoutApproach: \"commerce-grid\",\n pagePatterns: [\"Merchandising hero\", \"Offer comparison band\", \"Decision-support detail section\"],\n componentSequence: [\"Hero\", \"Offer cards\", \"Buttons\", \"Trust badges\", \"Comparison table\"],\n colors: {\n primary: \"#0F766E\",\n accent: \"#D97706\",\n accentSurface: \"#FFFBEB\",\n background: \"#F8FAFC\",\n surface: \"#FFFFFF\",\n border: \"#D1D5DB\",\n text: \"#111827\",\n mutedText: \"#4B5563\",\n success: \"#15803D\",\n warning: \"#B45309\",\n danger: \"#B91C1C\"\n }\n },\n \"control-room\": {\n direction: \"high-signal control room\",\n visualPersonality: \"dense, sharp, operational\",\n brandTone: \"authoritative and fast\",\n hierarchyPrinciples: [\"Use structure to reduce scanning cost.\", \"Separate primary metrics from diagnostics.\"],\n interactionPhilosophy: \"Fast updates, explicit states, motion only when it clarifies change.\",\n navigationModel: \"sidebar\",\n layoutApproach: \"panel-grid\",\n pagePatterns: [\"Metric summary rail\", \"Split-pane workspace\", \"Diagnostic detail panel\"],\n componentSequence: [\"Sidebar\", \"Stat blocks\", \"Tables\", \"Filters\", \"Panels\"],\n colors: {\n primary: \"#155EEF\",\n accent: \"#0F766E\",\n accentSurface: \"#ECFDF3\",\n background: \"#F8FAFC\",\n surface: \"#FFFFFF\",\n border: \"#CBD5E1\",\n text: \"#0F172A\",\n mutedText: \"#475569\",\n success: \"#15803D\",\n warning: \"#B45309\",\n danger: \"#B91C1C\"\n }\n },\n \"ops-control\": {\n direction: \"operational precision\",\n visualPersonality: \"structured, dense, high-confidence\",\n brandTone: \"decisive and exact\",\n hierarchyPrinciples: [\"Pin the primary metric and action path.\", \"Separate overview from detail panes.\"],\n interactionPhilosophy: \"Low-latency controls, strong state contrast, keyboard-friendly flows.\",\n navigationModel: \"sidebar\",\n layoutApproach: \"workspace-shell\",\n pagePatterns: [\"KPI overview bar\", \"Filterable data shell\", \"Detail drawer or inspector\"],\n componentSequence: [\"Sidebar\", \"Toolbar\", \"Data table\", \"Filters\", \"Detail panel\"],\n colors: {\n primary: \"#155EEF\",\n accent: \"#0891B2\",\n accentSurface: \"#ECFEFF\",\n background: \"#F8FAFC\",\n surface: \"#FFFFFF\",\n border: \"#CBD5E1\",\n text: \"#0F172A\",\n mutedText: \"#475569\",\n success: \"#15803D\",\n warning: \"#B45309\",\n danger: \"#B91C1C\"\n }\n },\n \"auth-focused\": {\n direction: \"trust-forward entry flow\",\n visualPersonality: \"calm, direct, reassuring\",\n brandTone: \"safe and premium\",\n hierarchyPrinciples: [\"One job per screen.\", \"Trust and recovery paths must be visible without clutter.\"],\n interactionPhilosophy: \"Low-friction focus flow with immediate validation feedback.\",\n navigationModel: \"contextual\",\n layoutApproach: \"two-panel-auth\",\n pagePatterns: [\"Auth split layout\", \"Trust panel\", \"Recovery and help strip\"],\n componentSequence: [\"Auth form\", \"Inputs\", \"Buttons\", \"Alerts\", \"Trust panel\"],\n colors: {\n primary: \"#1D4ED8\",\n accent: \"#0F766E\",\n accentSurface: \"#ECFDF5\",\n background: \"#F8FAFC\",\n surface: \"#FFFFFF\",\n border: \"#D1D5DB\",\n text: \"#111827\",\n mutedText: \"#4B5563\",\n success: \"#15803D\",\n warning: \"#B45309\",\n danger: \"#B91C1C\"\n }\n },\n \"settings-system\": {\n direction: \"calm settings system\",\n visualPersonality: \"ordered, practical, quietly premium\",\n brandTone: \"confident and low-friction\",\n hierarchyPrinciples: [\"Group related decisions tightly.\", \"Keep destructive actions isolated and explicit.\"],\n interactionPhilosophy: \"Prefer clear toggles and inline explanations over hidden complexity.\",\n navigationModel: \"tabbed\",\n layoutApproach: \"settings-grid\",\n pagePatterns: [\"Sectioned settings page\", \"Inline form groups\", \"Preference summary rail\"],\n componentSequence: [\"Tabs\", \"Forms\", \"Inputs\", \"Alerts\", \"Confirmation modal\"],\n colors: {\n primary: \"#1D4ED8\",\n accent: \"#0F766E\",\n accentSurface: \"#ECFDF5\",\n background: \"#F8FAFC\",\n surface: \"#FFFFFF\",\n border: \"#D1D5DB\",\n text: \"#111827\",\n mutedText: \"#475569\",\n success: \"#15803D\",\n warning: \"#B45309\",\n danger: \"#B91C1C\"\n }\n },\n \"documentation\": {\n direction: \"text-light knowledge story\",\n visualPersonality: \"legible, calm, visually led\",\n brandTone: \"expert, concise, and accessible\",\n hierarchyPrinciples: [\"Make scanning effortless.\", \"Use visual proof before long explanatory text.\"],\n interactionPhilosophy: \"Light motion, clear wayfinding, strong anchor visibility.\",\n navigationModel: \"sidebar\",\n layoutApproach: \"knowledge-story-shell\",\n pagePatterns: [\"Insight overview\", \"Visual proof band\", \"Action path\"],\n componentSequence: [\"Navigation\", \"Search\", \"Anchored headings\", \"Proof bands\", \"Callouts\"],\n colors: {\n primary: \"#1D4ED8\",\n accent: \"#0F766E\",\n accentSurface: \"#ECFDF5\",\n background: \"#F8FAFC\",\n surface: \"#FFFFFF\",\n border: \"#CBD5E1\",\n text: \"#0F172A\",\n mutedText: \"#475569\",\n success: \"#15803D\",\n warning: \"#B45309\",\n danger: \"#B91C1C\"\n }\n }\n};\n\nconst trimText = (value: string): string => {\n return value.trim().replace(/\\s+/g, \" \");\n};\n\nconst clipText = (value: string, maxLength: number): string => {\n if (value.length <= maxLength) return value;\n return `${value.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;\n};\n\ntype InspiredesignReferenceSynthesis = {\n lines: string[];\n summary: string;\n};\n\nconst REFERENCE_SUMMARY_CLIP_LENGTH = 220;\nconst GENERATION_PLAN_REFERENCE_CLIP_LENGTH = 600;\n\nconst buildReferenceSynthesis = (\n references: InspiredesignReferenceEvidence[]\n): InspiredesignReferenceSynthesis => {\n const lines = references\n .filter(hasInspiredesignUsableReferenceEvidence)\n .map((reference, index) => {\n const signals = getInspiredesignReferenceSignals(reference);\n if (signals.length === 0) return \"\";\n return `Source ${index + 1} ${reference.title ?? reference.url}: ${signals.join(\" | \")}`;\n })\n .filter((line) => line.length > 0);\n return {\n lines,\n summary: lines.length > 0\n ? lines.map((line) => clipText(line, REFERENCE_SUMMARY_CLIP_LENGTH)).join(\" \")\n : \"No live reference cues were captured.\"\n };\n};\n\nconst renderReferenceFirstAdvancedBrief = (\n briefExpansion: InspiredesignBriefExpansion,\n board: InspiredesignReferencePatternBoard,\n vectors: InspiredesignDesignVectors,\n references: InspiredesignReferenceEvidence[]\n): string => {\n if (board.references.length === 0 || vectors.sourcePriority !== \"reference-evidence-first\") {\n if (references.length > 0) {\n return [\n \"Reference evidence unavailable:\",\n \"URL references were attempted, but no ready-quality creative evidence was captured. Treat this as a capture or intent gap, not a design direction.\",\n \"\",\n formatBulletList([\n `${references.length} attempted reference(s) are retained in diagnostic artifacts only.`,\n \"Do not use rejected or not-ready reference URLs, names, screenshots, or metadata as creative direction.\"\n ]),\n \"\",\n briefExpansion.advancedBrief\n ].join(\"\\n\");\n }\n return briefExpansion.advancedBrief;\n }\n return [\n \"Reference pattern board:\",\n \"URL reference evidence is the creative source of truth when references are supplied.\",\n \"\",\n \"Reference evidence analysis:\",\n formatBulletList(board.references.map((reference) => (\n `${reference.name}: ${reference.layoutRecipe}`\n ))),\n \"\",\n \"Design vectors:\",\n formatBulletList([\n `directionLabel: ${vectors.directionLabel}`,\n `surfaceIntent: ${vectors.surfaceIntent}`,\n `premiumPosture: ${vectors.premiumPosture.join(\" \")}`,\n `motionPosture: ${vectors.motionPosture.join(\" \")}`,\n `sectionArchitecture: ${vectors.sectionArchitecture.join(\" \")}`,\n `interactionMoments: ${vectors.interactionMoments.join(\" \")}`,\n `materialEffects: ${vectors.materialEffects.join(\" \")}`,\n `advancedMotionAdvisory: ${vectors.advancedMotionAdvisory.join(\" \")}`\n ]),\n \"\",\n \"Fixed format guardrails:\",\n \"Selected prompt format supplies route defaults and guardrails, not the creative source of truth.\",\n \"\",\n briefExpansion.advancedBrief\n ].join(\"\\n\");\n};\n\nconst renderEvidenceDerivedAdvancedBrief = (\n briefExpansion: InspiredesignBriefExpansion,\n format: InspiredesignBriefFormat\n): string => [\n `Selected prompt format: ${format.label}`,\n \"\",\n \"Source brief:\",\n briefExpansion.sourceBrief,\n \"\",\n \"Prompt objective:\",\n `Use the reference evidence and source brief to define a ${format.archetype}.`,\n \"\",\n \"Business focus:\",\n formatBulletList(format.businessFocus),\n \"\",\n \"Keywords:\",\n formatBulletList(format.keywords),\n \"\",\n \"Route defaults:\",\n formatBulletList([\n `profile: ${format.route.profile}`,\n `theme strategy: ${format.route.themeStrategy}`,\n `navigation model: ${format.route.navigationModel}`,\n `layout approach: ${format.route.layoutApproach}`\n ]),\n \"\",\n \"Design direction:\",\n formatBulletList([\n `archetype: ${format.archetype}`,\n `layout archetype: ${format.layoutArchetype}`,\n `typography system: ${format.typographySystem}`,\n `surface treatment: ${format.surfaceTreatment}`,\n `shape language: ${format.shapeLanguage}`,\n `component grammar: ${format.componentGrammar}`,\n `motion grammar: ${format.motionGrammar}`,\n `palette intent: ${format.paletteIntent}`,\n `visual density: ${format.visualDensity}`,\n `design variance: ${format.designVariance}`\n ]),\n \"\",\n \"Responsive collapse rules:\",\n formatBulletList(format.responsiveCollapseRules),\n \"\",\n \"Focus areas:\",\n formatBulletList(format.focusAreas ?? []),\n \"\",\n \"Execution rules:\",\n formatBulletList([...INSPIREDESIGN_BRIEF_COMMON_RULES, ...format.guardrails]),\n \"\",\n \"Anti-patterns:\",\n formatBulletList(format.antiPatterns),\n \"\",\n \"Return:\",\n formatBulletList([...INSPIREDESIGN_BRIEF_OUTPUT_REQUIREMENTS, ...format.deliverables]),\n \"\",\n \"Best fit use cases:\",\n formatBulletList(format.bestFor)\n].join(\"\\n\");\n\nconst cloneTemplate = <T>(value: T): T => structuredClone(value);\n\nconst referenceFingerprint = (value: string): string => {\n return createHash(\"sha256\").update(value).digest(\"hex\").slice(0, 12);\n};\n\nconst summarizeBrief = (brief: string): string => {\n const normalized = trimText(brief);\n const sentence = normalized.split(/[.!?]/).map((part) => part.trim()).find(Boolean);\n return clipText(sentence ?? normalized, 140);\n};\n\nconst buildSupportingMessages = (references: InspiredesignReferenceEvidence[]): string[] => {\n const messages = references\n .map((reference) => reference.title ?? reference.excerpt ?? \"\")\n .map((value) => clipText(trimText(value), 72))\n .filter((value) => value.length > 0);\n return messages.slice(0, 3);\n};\n\nconst summarizeDesignVectors = (designVectors: InspiredesignDesignVectors): string => [\n `direction: ${designVectors.directionLabel}`,\n `sections: ${designVectors.sectionArchitecture.join(\" \")}`,\n `motion: ${designVectors.motionPosture.slice(0, 1).join(\" \")}`,\n `interactions: ${designVectors.interactionMoments.slice(0, 1).join(\" \")}`,\n `materials: ${designVectors.materialEffects.slice(0, 1).join(\" \")}`,\n `advancedMotion: ${designVectors.advancedMotionAdvisory.slice(0, 1).join(\" \")}`\n].join(\" \");\n\nconst isReferenceFirstPublicLanding = (designVectors: InspiredesignDesignVectors): boolean => {\n return designVectors.sourcePriority === \"reference-evidence-first\"\n && designVectors.surfaceIntent.toLowerCase().includes(\"public landing page\");\n};\n\nconst buildEvidenceDerivedFormat = (\n format: InspiredesignBriefFormat,\n designVectors: InspiredesignDesignVectors\n): InspiredesignBriefFormat => {\n const clone = cloneInspiredesignBriefFormat(format);\n if (!isReferenceFirstPublicLanding(designVectors)) return clone;\n return {\n ...clone,\n label: \"Reference-led public landing page\",\n archetype: \"reference-led public landing page\",\n layoutArchetype: \"full-bleed hero with narrative section cadence\",\n componentGrammar: \"hero composition, proof bands, narrative pathways, service or story sections, conversion CTA, and footer\",\n route: {\n ...clone.route,\n profile: \"product-story\",\n navigationModel: \"global-header\",\n layoutApproach: \"reference-led-landing-page\"\n }\n };\n};\n\nconst TARGET_KIND_ORDER: InspiredesignTargetKind[] = [\"page\", \"component\", \"asset\"];\n\ntype TargetSignalBucket = {\n intent: string[];\n supporting: string[];\n incidental: string[];\n};\n\ntype TargetEligibility = {\n kind: InspiredesignTargetKind;\n eligible: boolean;\n confidence: number;\n triggeringSignals: string[];\n};\n\ntype TargetDecisionReason =\n | \"no_non_page_gate\"\n | \"non_page_did_not_beat_page\"\n | \"page_first_brief_target\"\n | \"page_tie_break\"\n | \"non_page_selected\";\n\ntype TargetDecision = {\n primaryKind: InspiredesignTargetKind;\n reason: TargetDecisionReason;\n};\n\nconst TARGET_CONFIDENCE = {\n defaultPage: 0.55,\n pageIntentStep: 0.05,\n nonPageBase: 0.55,\n intentStep: 0.08,\n supportingStep: 0.05,\n maxPage: 0.7,\n maxNonPage: 0.95\n} as const;\n\nconst TARGET_SIGNAL_PROFILES: Record<InspiredesignTargetKind, TargetSignalBucket> = {\n page: {\n intent: [\"page\", \"landing page\", \"website\", \"homepage\", \"dashboard\", \"workspace\", \"screen\", \"flow\", \"surface\", \"microsite\"],\n supporting: [\"section\", \"sections\", \"navigation\", \"footer\", \"hero section\", \"conversion flow\"],\n incidental: [\"card\", \"cards\", \"button\", \"buttons\", \"image\", \"images\", \"media\", \"hero\", \"cta\", \"background\"]\n },\n component: {\n intent: [\"component\", \"component family\", \"reusable component\", \"component prototype\", \"hero component\", \"card component\", \"storybook\"],\n supporting: [\"prop\", \"props\", \"slot\", \"slots\", \"variant\", \"variants\", \"state matrix\", \"hover\", \"focus\", \"disabled\", \"loading\", \"error\", \"fixture\", \"fixtures\", \"arg\", \"args\"],\n incidental: [\"card\", \"cards\", \"button\", \"buttons\", \"form\", \"modal\", \"drawer\", \"navbar\", \"hero\", \"input\", \"tabs\", \"cta\"]\n },\n asset: {\n intent: [\"asset\", \"asset pack\", \"visual asset\", \"icon pack\", \"logo pack\", \"illustration set\", \"artwork set\"],\n supporting: [\"responsive variant\", \"responsive variants\", \"responsive artwork\", \"provenance\", \"usage rules\", \"alt text\", \"replacement rules\", \"tokenized usage\", \"source asset\", \"source assets\"],\n incidental: [\"icon\", \"icons\", \"illustration\", \"illustrations\", \"logo\", \"logos\", \"media\", \"image\", \"images\", \"background\", \"texture\", \"sprite\", \"artwork\"]\n }\n};\n\nconst buildTargetCorpus = (\n brief: string,\n references: InspiredesignReferenceEvidence[],\n synthesis: InspiredesignReferenceSynthesis\n): string => [\n brief,\n synthesis.lines.join(\" \"),\n ...references\n .filter(hasInspiredesignUsableReferenceEvidence)\n .flatMap((reference) => getInspiredesignReferenceSignals(reference))\n].join(\" \").toLowerCase();\n\nconst escapeRegex = (value: string): string => value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\nconst matchesTargetSignal = (corpus: string, signal: string): boolean => {\n const pattern = escapeRegex(signal.toLowerCase()).replace(/\\s+/g, \"\\\\s+\");\n return new RegExp(`(^|[^a-z0-9])${pattern}([^a-z0-9]|$)`).test(corpus);\n};\n\nconst findTargetSignalIndex = (corpus: string, signal: string): number | null => {\n const pattern = escapeRegex(signal.toLowerCase()).replace(/\\s+/g, \"\\\\s+\");\n return new RegExp(`(^|[^a-z0-9])${pattern}([^a-z0-9]|$)`).exec(corpus)?.index ?? null;\n};\n\nconst findFirstBriefTargetKind = (brief: string): InspiredesignTargetKind | null => {\n const corpus = brief.toLowerCase();\n const hits = TARGET_KIND_ORDER.flatMap((kind) => (\n TARGET_SIGNAL_PROFILES[kind].intent\n .map((signal) => findTargetSignalIndex(corpus, signal))\n .filter((index): index is number => index !== null)\n .map((index) => ({ kind, index }))\n ));\n return hits.sort((left, right) => left.index - right.index)[0]?.kind ?? null;\n};\n\nconst collectTargetSignals = (corpus: string): Record<InspiredesignTargetKind, TargetSignalBucket> => {\n const collect = (kind: InspiredesignTargetKind): TargetSignalBucket => {\n const profile = TARGET_SIGNAL_PROFILES[kind];\n return {\n intent: profile.intent.filter((signal) => matchesTargetSignal(corpus, signal)),\n supporting: profile.supporting.filter((signal) => matchesTargetSignal(corpus, signal)),\n incidental: profile.incidental.filter((signal) => matchesTargetSignal(corpus, signal))\n };\n };\n return {\n page: collect(\"page\"),\n component: collect(\"component\"),\n asset: collect(\"asset\")\n };\n};\n\nconst clampTargetConfidence = (value: number, max: number): number => Math.min(max, Number(value.toFixed(2)));\n\nconst buildPageConfidence = (signals: TargetSignalBucket): number => {\n return clampTargetConfidence(\n TARGET_CONFIDENCE.defaultPage + (signals.intent.length * TARGET_CONFIDENCE.pageIntentStep),\n TARGET_CONFIDENCE.maxPage\n );\n};\n\nconst buildTargetEligibility = (\n kind: InspiredesignTargetKind,\n briefSignals: TargetSignalBucket,\n supportSignals: TargetSignalBucket\n): TargetEligibility => {\n const eligible = briefSignals.intent.length > 0 && supportSignals.supporting.length > 0;\n const confidence = eligible\n ? clampTargetConfidence(\n TARGET_CONFIDENCE.nonPageBase\n + (briefSignals.intent.length * TARGET_CONFIDENCE.intentStep)\n + (supportSignals.supporting.length * TARGET_CONFIDENCE.supportingStep),\n TARGET_CONFIDENCE.maxNonPage\n )\n : 0;\n return {\n kind,\n eligible,\n confidence,\n triggeringSignals: [\n ...briefSignals.intent.map((signal) => `${kind} intent: ${signal}`),\n ...supportSignals.supporting.map((signal) => `${kind} support: ${signal}`)\n ]\n };\n};\n\nconst choosePrimaryTargetKind = (\n pageConfidence: number,\n pageSignals: TargetSignalBucket,\n firstBriefTargetKind: InspiredesignTargetKind | null,\n component: TargetEligibility,\n asset: TargetEligibility\n): TargetDecision => {\n const eligibleTargets = [component, asset].filter((target) => target.eligible);\n if (eligibleTargets.length === 0) return { primaryKind: \"page\", reason: \"no_non_page_gate\" };\n if (firstBriefTargetKind === \"page\" && pageSignals.intent.length > 0) {\n return { primaryKind: \"page\", reason: \"page_first_brief_target\" };\n }\n const [first, second] = eligibleTargets.sort((left, right) => right.confidence - left.confidence);\n if (!first || first.confidence <= pageConfidence) {\n return { primaryKind: \"page\", reason: \"non_page_did_not_beat_page\" };\n }\n if (second && first.confidence === second.confidence && pageSignals.intent.length > 0) {\n return { primaryKind: \"page\", reason: \"page_tie_break\" };\n }\n return { primaryKind: first.kind, reason: \"non_page_selected\" };\n};\n\nconst chooseTargetKinds = (\n primaryKind: InspiredesignTargetKind,\n component: TargetEligibility,\n asset: TargetEligibility\n): InspiredesignTargetKind[] => {\n if (primaryKind === \"page\") return [\"page\"];\n const eligible = new Set([component, asset].filter((target) => target.eligible).map((target) => target.kind));\n const secondaryKinds = TARGET_KIND_ORDER.filter((kind) => kind !== primaryKind && eligible.has(kind));\n return [primaryKind, ...secondaryKinds];\n};\n\nconst buildTriggeringSignals = (\n decision: TargetDecision,\n signals: Record<InspiredesignTargetKind, TargetSignalBucket>,\n component: TargetEligibility,\n asset: TargetEligibility\n): string[] => {\n const pageSignals = signals.page.intent.map((signal) => `page intent: ${signal}`);\n const eligibleTargets = [component, asset].filter((target) => target.eligible);\n const targetIntents = eligibleTargets\n .flatMap((target) => target.triggeringSignals.filter((signal) => signal.includes(\" intent: \")));\n const targetSupport = eligibleTargets\n .flatMap((target) => target.triggeringSignals.filter((signal) => signal.includes(\" support: \")));\n const defaultSignal = decision.primaryKind === \"page\" ? [buildPageDecisionSignal(decision.reason)] : [];\n return [...pageSignals, ...targetIntents, ...targetSupport, ...defaultSignal].slice(0, 12);\n};\n\nconst buildPageDecisionSignal = (reason: TargetDecisionReason): string => {\n if (reason === \"no_non_page_gate\") return \"page default: non-page targets did not clear brief intent plus support gates\";\n if (reason === \"non_page_did_not_beat_page\") return \"page default: non-page targets did not beat page confidence\";\n if (reason === \"page_first_brief_target\") return \"page default: page was the first explicit target in the brief\";\n if (reason === \"page_tie_break\") return \"page default: page intent won a tied non-page confidence score\";\n return \"page default: page selected\";\n};\n\nconst getTargetConfidence = (\n primaryKind: InspiredesignTargetKind,\n pageConfidence: number,\n component: TargetEligibility,\n asset: TargetEligibility\n): number => {\n if (primaryKind === \"component\") return component.confidence;\n if (primaryKind === \"asset\") return asset.confidence;\n return pageConfidence;\n};\n\nconst buildTargetEvidenceBuckets = (\n primaryKind: InspiredesignTargetKind,\n format: InspiredesignBriefFormat,\n designVectors: InspiredesignDesignVectors\n): InspiredesignEvidenceBuckets => ({\n anatomy: [`Map ${primaryKind} anatomy before styling: root, content hierarchy, interaction zones, and supporting regions.`],\n propsSlots: [`Define props/slots from ${format.componentGrammar}; separate data props, content slots, and visual variant controls.`],\n stateMatrix: [\"Cover default, hover, focus, active, disabled, loading, empty, error, success, and selected where relevant.\"],\n tokens: [`Resolve typography, color, spacing, radius, shadow, motion, and z-index through semantic tokens for ${format.paletteIntent}.`],\n assets: [`Inventory source assets, derived assets, usage rights, responsive variants, and replacement notes for ${primaryKind} prototypes.`],\n accessibility: [\"Validate keyboard order, visible focus, accessible names, ARIA pattern fit, contrast, and WCAG 2.2 states.\"],\n motion: [`Use ${format.motionGrammar}; include reduced-motion alternatives for ${designVectors.motionPosture.join(\" \") || \"all transitions\"}.`],\n previewFixtures: [`Build isolated preview fixtures for ${primaryKind} default, responsive, reduced-motion, and failure states.`]\n});\n\nconst buildComponentTargetAnalysis = (\n briefHash: string,\n format: InspiredesignBriefFormat\n): InspiredesignTargetAnalysis[\"component\"] => ({\n canvasType: \"CanvasComponentInventoryItem\",\n inventoryItems: [{\n id: `component_${briefHash}`,\n name: `${format.label} Component`,\n componentName: `${format.route.profile.replace(/-/g, \"\")}PrototypeComponent`,\n description: `Reusable component prototype derived from ${format.componentGrammar}.`,\n sourceFamily: \"framework_component\",\n origin: \"code_sync\",\n variants: [{\n id: \"default\",\n name: \"Default\",\n selector: { interaction: \"default\" },\n description: \"Default preview fixture.\",\n metadata: {}\n }],\n props: [\n { name: \"variant\", type: \"string\", required: false, description: \"Visual variant key.\", metadata: {} },\n { name: \"state\", type: \"string\", required: false, description: \"Interaction state fixture.\", metadata: {} }\n ],\n slots: [\n { name: \"media\", description: \"Optional visual or icon slot.\", allowedKinds: [\"asset\", \"image\", \"icon\"], metadata: {} },\n { name: \"content\", description: \"Primary text or rich content slot.\", allowedKinds: [\"text\", \"rich-text\"], metadata: {} }\n ],\n events: [{ name: \"onPrimaryAction\", description: \"Primary interaction callback.\", payloadShape: {}, metadata: {} }],\n content: { acceptsText: true, acceptsRichText: true, slotNames: [\"media\", \"content\"], metadata: {} },\n metadata: { targetKind: \"component\" }\n }],\n prototypeGuidance: [\n \"Component prototype target: document anatomy, props/slots, variant rules, and interaction state fixtures before page composition.\",\n \"Use Storybook-style args and interaction checks when converting this guidance into executable component previews.\"\n ]\n});\n\nconst buildAssetTargetAnalysis = (briefHash: string): InspiredesignTargetAnalysis[\"asset\"] => ({\n canvasType: \"CanvasAsset\",\n assets: [{\n id: `asset_${briefHash}`,\n sourceType: \"page-derived\",\n kind: \"visual-asset\",\n url: null,\n status: \"needs-production-source\",\n provenanceNotes: [\"Derived from brief/reference evidence; recreate rather than copy proprietary source assets.\"],\n usageNotes: [\"Define responsive variants, token usage, alt text, and replacement rules before implementation.\"],\n metadata: { targetKind: \"asset\" }\n }],\n prototypeGuidance: [\n \"Asset prototype target: catalog provenance, variants, token usage, responsive behavior, and replacement rules.\",\n \"Pair each visual asset with preview fixtures for default, high contrast, and reduced-motion contexts when relevant.\"\n ]\n});\n\nconst buildPageTargetAnalysis = (\n format: InspiredesignBriefFormat,\n designVectors: InspiredesignDesignVectors\n): InspiredesignTargetAnalysis[\"page\"] => ({\n canvasType: \"CanvasPage\",\n assemblyFocus: [\n format.layoutArchetype,\n ...designVectors.sectionArchitecture\n ],\n implementationNotes: [\n \"Page prototype target: validate section order, navigation model, CTA visibility, responsive collapse, and reduced-motion behavior.\",\n \"Use component primitives before page-specific wrappers.\"\n ]\n});\n\nconst buildTargetAnalysis = (\n brief: string,\n format: InspiredesignBriefFormat,\n references: InspiredesignReferenceEvidence[],\n synthesis: InspiredesignReferenceSynthesis,\n designVectors: InspiredesignDesignVectors\n): InspiredesignTargetAnalysis => {\n const briefSignals = collectTargetSignals(brief.toLowerCase());\n const supportSignals = collectTargetSignals(buildTargetCorpus(brief, references, synthesis));\n const pageConfidence = buildPageConfidence(briefSignals.page);\n const component = buildTargetEligibility(\"component\", briefSignals.component, supportSignals.component);\n const asset = buildTargetEligibility(\"asset\", briefSignals.asset, supportSignals.asset);\n const decision = choosePrimaryTargetKind(\n pageConfidence,\n briefSignals.page,\n findFirstBriefTargetKind(brief),\n component,\n asset\n );\n const primaryKind = decision.primaryKind;\n const kinds = chooseTargetKinds(primaryKind, component, asset);\n const briefHash = referenceFingerprint(brief);\n return {\n primaryKind,\n kinds,\n confidence: getTargetConfidence(primaryKind, pageConfidence, component, asset),\n triggeringSignals: buildTriggeringSignals(decision, briefSignals, component, asset),\n evidenceBuckets: buildTargetEvidenceBuckets(primaryKind, format, designVectors),\n ...(kinds.includes(\"page\") ? { page: buildPageTargetAnalysis(format, designVectors) } : {}),\n ...(kinds.includes(\"component\") ? { component: buildComponentTargetAnalysis(briefHash, format) } : {}),\n ...(kinds.includes(\"asset\") ? { asset: buildAssetTargetAnalysis(briefHash) } : {})\n };\n};\n\ntype BuildGenerationPlanInput = {\n brief: string;\n format: InspiredesignBriefFormat;\n synthesis: InspiredesignReferenceSynthesis;\n referencePatternBoard: InspiredesignReferencePatternBoard;\n designVectors: InspiredesignDesignVectors;\n targetAnalysis: InspiredesignTargetAnalysis;\n};\n\nconst buildGenerationPlan = ({\n brief,\n format,\n synthesis,\n referencePatternBoard,\n designVectors,\n targetAnalysis\n}: BuildGenerationPlanInput): InspiredesignGenerationPlan => {\n const plan = cloneTemplate(BASE_GENERATION_PLAN);\n const profile = format.route.profile;\n const vectorSummary = summarizeDesignVectors(designVectors);\n plan.targetOutcome.summary = clipText(\n `${summarizeBrief(brief)} Reference cues: ${synthesis.summary} ${vectorSummary}`,\n GENERATION_PLAN_REFERENCE_CLIP_LENGTH\n );\n plan.visualDirection.profile = profile;\n plan.visualDirection.themeStrategy = format.route.themeStrategy;\n plan.layoutStrategy.approach = format.route.layoutApproach;\n plan.layoutStrategy.navigationModel = format.route.navigationModel;\n plan.contentStrategy.source = clipText(\n `${INSPIREDESIGN_HANDOFF_FILES.evidence}, ${INSPIREDESIGN_HANDOFF_FILES.advancedBrief}, ${INSPIREDESIGN_HANDOFF_FILES.designMarkdown}. Use reference pattern board and design vectors from evidence/handoff artifacts. ${synthesis.summary} ${vectorSummary}`,\n GENERATION_PLAN_REFERENCE_CLIP_LENGTH\n );\n plan.componentStrategy.mode = clipText(\n `reuse-first, adapted from captured references: ${synthesis.summary}. Include hero entrance reveal, section scroll reveal, CTA/focus feedback, microinteractions, hover effects, evidence-gated cursor effects, material depth, parallax constraints, glass/translucency policy, and prefers-reduced-motion behavior. Capture desktop and mobile browser proof for responsive layout, reduced-motion behavior, focus states, and primary CTA visibility.`,\n GENERATION_PLAN_REFERENCE_CLIP_LENGTH\n );\n plan.componentStrategy.interactionStates = [\"default\", \"hover\", \"focus\", \"disabled\", \"loading\"];\n plan.validationTargets.requiredThemes = plan.visualDirection.themeStrategy === \"single-theme\"\n ? [\"light\"]\n : [\"light\", \"dark\"];\n return {\n ...plan,\n referencePatternBoard,\n designVectors,\n targetAnalysis,\n interactionMoments: [...designVectors.interactionMoments],\n materialEffects: [...designVectors.materialEffects]\n };\n};\n\nconst buildIntentBlock = (\n brief: string,\n urls: string[],\n references: InspiredesignReferenceEvidence[],\n format: InspiredesignBriefFormat\n): JsonRecord => {\n const intent = cloneTemplate(BASE_CONTRACT_TEMPLATE.intent);\n return {\n ...intent,\n task: summarizeBrief(brief),\n brief,\n briefHash: referenceFingerprint(brief),\n selectedFormat: format.label,\n businessFocus: [...format.businessFocus],\n keywords: [...format.keywords],\n referenceCount: references.length,\n referenceUrls: urls,\n evidenceStatus: {\n fetched: references.filter((reference) => reference.fetchStatus === \"captured\").length,\n captured: references.filter((reference) => reference.captureStatus === \"captured\").length\n }\n };\n};\n\nconst buildDesignLanguageBlock = (\n profile: CanvasVisualDirectionProfile,\n format: InspiredesignBriefFormat\n): JsonRecord => {\n const block = cloneTemplate(BASE_CONTRACT_TEMPLATE.designLanguage);\n const config = PROFILE_CONFIG[profile];\n return {\n ...block,\n direction: config.direction,\n visualPersonality: config.visualPersonality,\n brandTone: config.brandTone,\n archetype: format.archetype,\n surfaceTreatment: format.surfaceTreatment,\n shapeLanguage: format.shapeLanguage,\n paletteIntent: format.paletteIntent,\n visualDensity: format.visualDensity,\n designVariance: format.designVariance\n };\n};\n\nconst buildContentModelBlock = (\n brief: string,\n references: InspiredesignReferenceEvidence[]\n): JsonRecord => {\n const block = cloneTemplate(BASE_CONTRACT_TEMPLATE.contentModel);\n return {\n ...block,\n primaryMessage: summarizeBrief(brief),\n supportingMessages: buildSupportingMessages(references)\n };\n};\n\nconst buildLayoutSystemBlock = (\n plan: CanvasGenerationPlan,\n format: InspiredesignBriefFormat\n): JsonRecord => {\n const block = cloneTemplate(BASE_CONTRACT_TEMPLATE.layoutSystem);\n return {\n ...block,\n layoutArchetype: format.layoutArchetype,\n layoutApproach: plan.layoutStrategy.approach,\n navigationModel: plan.layoutStrategy.navigationModel,\n pagePatterns: [format.layoutArchetype, ...PROFILE_CONFIG[plan.visualDirection.profile].pagePatterns]\n };\n};\n\nconst buildTypographySystemBlock = (format: InspiredesignBriefFormat): JsonRecord => {\n const block = cloneTemplate(BASE_CONTRACT_TEMPLATE.typographySystem);\n return {\n ...block,\n system: format.typographySystem,\n tokens: {\n display: \"56/1.0\",\n h1: \"40/1.05\",\n h2: \"28/1.1\",\n h3: \"20/1.2\",\n body: \"16/1.6\",\n label: \"14/1.4\",\n caption: \"12/1.4\"\n }\n };\n};\n\nconst buildColorSystemBlock = (\n profile: CanvasVisualDirectionProfile,\n format: InspiredesignBriefFormat\n): JsonRecord => {\n const colors = PROFILE_CONFIG[profile].colors;\n return {\n paletteName: `${format.id}-default`,\n paletteIntent: format.paletteIntent,\n tokens: colors,\n contrastRequirements: {\n bodyText: \"4.5:1\",\n largeText: \"3:1\",\n focusRing: \"3:1\"\n }\n };\n};\n\nconst buildSurfaceSystemBlock = (format: InspiredesignBriefFormat): JsonRecord => ({\n surfaceTreatment: format.surfaceTreatment,\n shapeLanguage: format.shapeLanguage,\n radiusScale: {\n xs: \"6px\",\n sm: \"10px\",\n md: \"16px\",\n lg: \"24px\"\n },\n borderPolicy: \"Use 1px neutral strokes before adding elevation.\",\n shadowPolicy: {\n sm: \"0 1px 2px rgba(15, 23, 42, 0.06)\",\n md: \"0 10px 30px rgba(15, 23, 42, 0.10)\",\n lg: \"0 24px 60px rgba(15, 23, 42, 0.14)\"\n }\n});\n\nconst buildIconSystemBlock = (): JsonRecord => ({\n family: \"tabler\",\n strokeWidth: 1.5,\n style: \"rounded-linear\",\n usageRules: [\n \"Use icons to reinforce labels, not replace them.\",\n \"Decorative icons should remain visually lighter than primary copy.\"\n ]\n});\n\nconst buildMotionSystemBlock = (\n format: InspiredesignBriefFormat,\n designVectors: InspiredesignDesignVectors\n): JsonRecord => {\n const block = cloneTemplate(BASE_CONTRACT_TEMPLATE.motionSystem);\n return {\n ...block,\n grammar: format.motionGrammar,\n posture: [...designVectors.motionPosture],\n interactionMoments: [...designVectors.interactionMoments],\n materialEffects: [...designVectors.materialEffects],\n advancedMotionAdvisory: [...designVectors.advancedMotionAdvisory],\n advancedMotionRuntimePolicy: \"Advanced motion fields are advisory contract metadata only and do not authorize shader, WebGL, Spline, R3F, Pixi, Babylon, or GLSL runtime support.\",\n parallaxPolicy: \"Use parallax only as a restrained hierarchy cue and remove transform-based depth for reduced-motion users.\",\n hoverPolicy: \"Hover effects must clarify clickability without becoming the only visible affordance.\",\n cursorPolicy: \"Cursor effects are allowed only on premium hero or CTA moments and must not interfere with reading or form controls.\",\n durations: {\n quick: \"120ms\",\n standard: \"180ms\",\n emphasis: \"240ms\"\n }\n };\n};\n\nconst buildResponsiveSystemBlock = (format: InspiredesignBriefFormat): JsonRecord => {\n const block = cloneTemplate(BASE_CONTRACT_TEMPLATE.responsiveSystem);\n return {\n ...block,\n collapseRules: [...format.responsiveCollapseRules],\n breakpoints: {\n mobile: \"0-639px\",\n tablet: \"640-1023px\",\n desktop: \"1024px+\"\n }\n };\n};\n\nconst buildAccessibilityBlock = (): JsonRecord => {\n const block = cloneTemplate(BASE_CONTRACT_TEMPLATE.accessibilityPolicy);\n return {\n ...block,\n reducedMotion: \"Respect user preference and preserve information without animation.\"\n };\n};\n\nconst buildLibraryPolicyBlock = (): JsonRecord => ({\n components: [\"shadcn\"],\n icons: [\"tabler\"],\n styling: [\"tailwindcss\"],\n motion: [],\n threeD: []\n});\n\nconst buildRuntimeBudgetsBlock = (plan: CanvasGenerationPlan): JsonRecord => ({\n maxHeroActions: 2,\n maxPrimarySections: plan.layoutStrategy.navigationModel === \"global-header\" ? 12 : 8,\n maxInteractionLatencyMs: plan.validationTargets.maxInteractionLatencyMs,\n previewBudgetMs: 1500,\n notes: [\n \"Keep above-the-fold content inside one visual composition.\",\n \"Avoid heavyweight decorative animation before interaction clarity is established.\"\n ]\n});\n\nconst EMITTED_GOVERNANCE_BLOCKS: InspiredesignContractScope[\"emittedGovernanceBlocks\"] = [\n \"intent\",\n \"generationPlan\",\n \"designLanguage\",\n \"contentModel\",\n \"layoutSystem\",\n \"typographySystem\",\n \"colorSystem\",\n \"surfaceSystem\",\n \"iconSystem\",\n \"motionSystem\",\n \"responsiveSystem\",\n \"accessibilityPolicy\",\n \"libraryPolicy\",\n \"runtimeBudgets\"\n];\n\nconst buildNavigationModelBlock = (navigationModel: CanvasNavigationModel): JsonRecord => {\n const block = cloneTemplate(BASE_CONTRACT_TEMPLATE.navigationModel);\n return {\n ...block,\n primaryRouteModel: `Use a ${navigationModel} route shell so the primary action remains stable through state changes.`\n };\n};\n\nconst buildAsyncModelBlock = (): JsonRecord => {\n return cloneTemplate(BASE_CONTRACT_TEMPLATE.asyncModel);\n};\n\nconst buildPerformanceModelBlock = (): JsonRecord => {\n return cloneTemplate(BASE_CONTRACT_TEMPLATE.performanceModel);\n};\n\nconst buildCanvasPlanRequest = (\n brief: string,\n generationPlan: InspiredesignGenerationPlan\n): CanvasPlanRequestTemplate => ({\n ...cloneTemplate(BASE_PLAN_REQUEST_TEMPLATE),\n requestId: `req_plan_${referenceFingerprint(brief).slice(0, 12)}`,\n generationPlan: toCanvasGenerationPlan(generationPlan)\n});\n\nconst toCanvasGenerationPlan = (plan: InspiredesignGenerationPlan): CanvasPlanRequestTemplate[\"generationPlan\"] => cloneTemplate({\n targetOutcome: plan.targetOutcome,\n visualDirection: plan.visualDirection,\n layoutStrategy: plan.layoutStrategy,\n contentStrategy: plan.contentStrategy,\n componentStrategy: plan.componentStrategy,\n motionPosture: plan.motionPosture,\n responsivePosture: plan.responsivePosture,\n accessibilityPosture: plan.accessibilityPosture,\n validationTargets: plan.validationTargets,\n interactionMoments: [...plan.interactionMoments],\n materialEffects: [...plan.materialEffects],\n designVectors: plan.designVectors as JsonRecord\n});\n\nconst buildContractScope = (): InspiredesignContractScope => ({\n emittedContract: \"CanvasDesignGovernance\",\n emittedGovernanceBlocks: [...EMITTED_GOVERNANCE_BLOCKS],\n omittedTemplateBlocks: [\"navigationModel\", \"asyncModel\", \"performanceModel\"],\n note: `${INSPIREDESIGN_HANDOFF_FILES.designContract} is the narrowed canvas governance contract. Use ${INSPIREDESIGN_HANDOFF_FILES.designAgentHandoff} for navigation, async, and performance context that informs implementation but does not belong in canvas governance patches.`\n});\n\nconst buildBriefExpansionMetadata = (\n briefExpansion: InspiredesignBriefExpansion\n): InspiredesignFollowthrough[\"briefExpansion\"] => ({\n templateVersion: briefExpansion.templateVersion,\n file: INSPIREDESIGN_HANDOFF_FILES.advancedBrief,\n format: cloneInspiredesignBriefFormat(briefExpansion.format)\n});\n\nconst buildRequiredReferenceArtifacts = (includePrototypeGuidance: boolean): string[] => {\n const files = [\n INSPIREDESIGN_HANDOFF_FILES.evidence,\n INSPIREDESIGN_HANDOFF_FILES.visualEvidence,\n INSPIREDESIGN_HANDOFF_FILES.screenshotIndex,\n INSPIREDESIGN_HANDOFF_FILES.rankedReferences,\n INSPIREDESIGN_HANDOFF_FILES.metaPrompt,\n INSPIREDESIGN_HANDOFF_FILES.advancedBrief,\n INSPIREDESIGN_HANDOFF_FILES.designMarkdown,\n INSPIREDESIGN_HANDOFF_FILES.generationPlan,\n INSPIREDESIGN_HANDOFF_FILES.canvasPlanRequest,\n INSPIREDESIGN_HANDOFF_FILES.designContract,\n INSPIREDESIGN_HANDOFF_FILES.implementationPlanMarkdown\n ];\n return includePrototypeGuidance\n ? [...files, INSPIREDESIGN_HANDOFF_FILES.prototypeGuidance]\n : files;\n};\n\ntype BuildFollowthroughInput = {\n generationPlan: InspiredesignGenerationPlan;\n briefExpansion: InspiredesignBriefExpansion;\n synthesis: InspiredesignReferenceSynthesis;\n includePrototypeGuidance: boolean;\n referencePatternBoard: InspiredesignReferencePatternBoard;\n designVectors: InspiredesignDesignVectors;\n targetAnalysis: InspiredesignTargetAnalysis;\n};\n\nconst buildFollowthrough = ({\n generationPlan,\n briefExpansion,\n synthesis,\n includePrototypeGuidance,\n referencePatternBoard,\n designVectors,\n targetAnalysis\n}: BuildFollowthroughInput): InspiredesignFollowthrough => ({\n summary: buildInspiredesignFollowthroughSummary(),\n nextStep: buildInspiredesignNextStep(),\n artifactGuide: INSPIREDESIGN_ARTIFACT_GUIDE,\n contractSectionGuide: INSPIREDESIGN_CONTRACT_SECTION_GUIDE,\n briefExpansion: buildBriefExpansionMetadata(briefExpansion),\n recommendedSkills: [...INSPIREDESIGN_HANDOFF_RECOMMENDED_SKILLS],\n commandExamples: { ...INSPIREDESIGN_HANDOFF_COMMANDS },\n deepCaptureRecommendation: INSPIREDESIGN_HANDOFF_GUIDANCE.deepCaptureRecommendation,\n contractScope: buildContractScope(),\n implementationContext: {\n navigationModel: buildNavigationModelBlock(generationPlan.layoutStrategy.navigationModel),\n asyncModel: buildAsyncModelBlock(),\n performanceModel: buildPerformanceModelBlock(),\n referenceSynthesis: {\n requiredArtifacts: buildRequiredReferenceArtifacts(includePrototypeGuidance),\n cues: synthesis.lines\n },\n referencePatternBoard,\n designVectors,\n targetAnalysis\n }\n});\n\ntype BuildDesignContractInput = {\n brief: string;\n designReferences: InspiredesignReferenceEvidence[];\n plan: InspiredesignGenerationPlan;\n format: InspiredesignBriefFormat;\n};\n\nconst buildDesignContract = ({\n brief,\n designReferences,\n plan,\n format\n}: BuildDesignContractInput): CanvasDesignGovernance => ({\n intent: buildIntentBlock(brief, designReferences.map((reference) => reference.url), designReferences, format),\n generationPlan: toCanvasGenerationPlan(plan),\n designLanguage: buildDesignLanguageBlock(plan.visualDirection.profile, format),\n contentModel: buildContentModelBlock(brief, designReferences),\n layoutSystem: buildLayoutSystemBlock(plan, format),\n typographySystem: buildTypographySystemBlock(format),\n colorSystem: buildColorSystemBlock(plan.visualDirection.profile, format),\n surfaceSystem: buildSurfaceSystemBlock(format),\n iconSystem: buildIconSystemBlock(),\n motionSystem: buildMotionSystemBlock(format, plan.designVectors),\n responsiveSystem: buildResponsiveSystemBlock(format),\n accessibilityPolicy: buildAccessibilityBlock(),\n libraryPolicy: buildLibraryPolicyBlock(),\n runtimeBudgets: buildRuntimeBudgetsBlock(plan)\n});\n\nconst buildTokenStrategy = (profile: CanvasVisualDirectionProfile): InspiredesignTokenStrategy => ({\n colors: PROFILE_CONFIG[profile].colors,\n typography: {\n display: \"font-display text-[56px] leading-[1.0]\",\n h1: \"font-display text-[40px] leading-[1.05]\",\n h2: \"font-display text-[28px] leading-[1.1]\",\n h3: \"font-display text-[20px] leading-[1.2]\",\n body: \"font-body text-[16px] leading-[1.6]\",\n label: \"font-body text-[14px] leading-[1.4]\",\n caption: \"font-body text-[12px] leading-[1.4]\"\n },\n spacing: {\n xs: \"4px\",\n sm: \"8px\",\n md: \"16px\",\n lg: \"24px\",\n xl: \"40px\",\n section: \"96px\"\n },\n radius: {\n xs: \"6px\",\n sm: \"10px\",\n md: \"16px\",\n lg: \"24px\"\n },\n shadow: {\n sm: \"0 1px 2px rgba(15, 23, 42, 0.06)\",\n md: \"0 10px 30px rgba(15, 23, 42, 0.10)\",\n lg: \"0 24px 60px rgba(15, 23, 42, 0.14)\"\n },\n motion: {\n quick: \"120ms ease-out\",\n standard: \"180ms ease-out\",\n emphasis: \"240ms cubic-bezier(0.22, 1, 0.36, 1)\"\n },\n zIndex: {\n base: 0,\n sticky: 20,\n overlay: 40,\n modal: 60,\n toast: 70\n },\n breakpoints: {\n mobile: \"640px\",\n tablet: \"1024px\",\n desktop: \"1280px\"\n }\n});\n\nconst buildComponentBuildPlan = (profile: CanvasVisualDirectionProfile) => {\n return PROFILE_CONFIG[profile].componentSequence.map((name) => ({\n name,\n purpose: `Establish the ${name.toLowerCase()} pattern as a reusable system primitive.`,\n states: [\"default\", \"hover\", \"focus\", \"disabled\"],\n implementationNote: \"Use semantic tokens first and keep copy/state logic outside the visual component.\"\n }));\n};\n\ntype BuildImplementationPlanInput = {\n profile: CanvasVisualDirectionProfile;\n format: InspiredesignBriefFormat;\n references: InspiredesignReferenceEvidence[];\n attemptedReferenceCount: number;\n synthesis: InspiredesignReferenceSynthesis;\n designVectors: InspiredesignDesignVectors;\n};\n\nconst buildImplementationPlan = ({\n profile,\n format,\n references,\n attemptedReferenceCount,\n synthesis,\n designVectors\n}: BuildImplementationPlanInput): InspiredesignImplementationPlan => ({\n architectureRecommendation: `Implement the surface as a ${format.archetype} using token-first components and shared semantic CSS variables, then compose page sections from those primitives before adding any page-specific polish.`,\n tokenStrategy: buildTokenStrategy(profile),\n referenceImplementationNotes: synthesis.lines.length > 0\n ? synthesis.lines\n : [\"No live reference cues were captured; keep implementation anchored to the source brief and selected prompt format.\"],\n componentBuildPlan: buildComponentBuildPlan(profile),\n pageAssemblyPlan: [\n `Start with the ${format.layoutArchetype} and the primary navigation pattern.`,\n ...designVectors.sectionArchitecture,\n \"Make each major section content-rich with a concrete headline, supporting copy, proof detail, and a clear role in the journey.\",\n \"Compose the hero or primary decision section before supporting sections.\",\n \"Add proof, utility, and footer sections only after the top-level hierarchy is stable.\"\n ],\n stateAndInteractionPlan: [\n `Use ${format.motionGrammar} while keeping hover, focus, loading, success, and error states visually distinct.`,\n ...designVectors.motionPosture,\n ...designVectors.interactionMoments,\n ...designVectors.materialEffects,\n ...designVectors.advancedMotionAdvisory,\n \"Implement hero entrance reveal, section scroll reveal, and CTA/focus feedback as the minimum motion system for landing pages.\",\n \"Use @media (prefers-reduced-motion: reduce) to preserve hierarchy without motion.\",\n \"Preserve layout during loading and keep transient confirmations out of the main flow.\",\n \"Use reduced-motion-safe transitions for reveals and CTA feedback.\"\n ],\n accessibilityChecklist: [\n \"Maintain 4.5:1 body text contrast across all surfaces.\",\n \"Preserve visible focus rings on every interactive element.\",\n \"Keep landmarks and heading levels explicit and sequential.\"\n ],\n responsiveChecklist: [\n ...format.responsiveCollapseRules,\n \"Collapse multicolumn layouts before text measure becomes cramped.\",\n \"Keep the primary CTA visible without overlap on narrow screens.\",\n \"Avoid horizontal scrolling for primary content.\"\n ],\n risksAndAmbiguities: [\n attemptedReferenceCount === 0\n ? \"No live references were supplied, so visual cues are derived entirely from the written brief.\"\n : synthesis.lines.length > 0\n ? \"Live references were reduced into reusable patterns; unique brand assets should still be recreated, not copied.\"\n : \"Reference URLs were attempted, but no usable creative evidence was captured; keep implementation anchored to the source brief and selected prompt format.\",\n \"Any missing interaction states must be validated during visual QA.\",\n \"Capture desktop and mobile browser proof before handoff, including reduced-motion behavior and primary CTA visibility.\"\n ],\n buildSequence: [\n \"Define semantic tokens and typography.\",\n \"Build the shell, navigation, and primary CTA components.\",\n \"Implement section-level patterns and proof blocks.\",\n \"Add loading, empty, and error states.\",\n \"Capture desktop and mobile browser proof for responsive layout, reduced-motion behavior, focus states, and primary CTA visibility before final polish.\"\n ]\n});\n\nconst formatBulletList = (items: string[]): string => items.map((item) => `- ${item}`).join(\"\\n\");\n\nconst renderAntiPatternRule = (rule: string): string => {\n const cleanRule = rule.replace(/\\.$/, \"\").trim();\n const withoutNo = cleanRule.replace(/^no\\s+/i, \"\");\n if (withoutNo !== cleanRule) return `Don't use ${withoutNo.charAt(0).toLowerCase()}${withoutNo.slice(1)}.`;\n const withoutDoNot = cleanRule.replace(/^do not\\s+/i, \"\");\n if (withoutDoNot !== cleanRule) return `Don't ${withoutDoNot.charAt(0).toLowerCase()}${withoutDoNot.slice(1)}.`;\n return `Don't ${cleanRule.charAt(0).toLowerCase()}${cleanRule.slice(1)}.`;\n};\n\nconst formatRecordList = (record: Record<string, string | number>): string => {\n return Object.entries(record).map(([key, value]) => `- \\`${key}\\`: ${value}`).join(\"\\n\");\n};\n\nconst referenceContribution = (reference: InspiredesignReferenceEvidence): string => {\n if (reference.captureStatus === \"captured\") return \"Live hierarchy and component evidence captured from the page.\";\n return \"Content and structural cues inferred from fetched page data.\";\n};\n\nconst referenceMotionNote = (reference: InspiredesignReferenceEvidence): string => {\n if (reference.capture?.snapshot?.warnings?.length) {\n return `Capture warnings: ${reference.capture.snapshot.warnings.join(\", \")}`;\n }\n if (reference.captureStatus === \"captured\") return \"Motion should remain subtle until validated against the live capture.\";\n return \"Motion is inferred from the brief rather than directly observed.\";\n};\n\nconst referenceLayoutObservation = (\n reference: InspiredesignReferenceEvidence,\n excerpt: string\n): string => {\n if (!reference.capture?.snapshot && !reference.capture?.clone && !reference.capture?.dom) return excerpt;\n const signals = getInspiredesignReferenceSignals(reference);\n return signals.find((signal) => signal !== reference.title) ?? signals[0] ?? excerpt;\n};\n\nconst renderReferenceMarkdown = (reference: InspiredesignReferenceEvidence, index: number): string => {\n const excerpt = reference.excerpt ? clipText(reference.excerpt, 220) : \"No fetched excerpt captured.\";\n const title = reference.title ?? reference.url;\n return [\n `### Source ${index + 1}: ${title}`,\n `- what it contributes: ${referenceContribution(reference)}`,\n `- notable UI patterns: ${reference.capture?.snapshot ? \"Primary hierarchy and actionables were captured from the live page.\" : \"Patterns inferred from brief and fetched content.\"}`,\n `- typography observations: ${reference.title ? \"Headline density and copy hierarchy were inferred from the fetched title and excerpt.\" : \"Typography is inferred.\"}`,\n `- color and theme observations: ${reference.captureStatus === \"captured\" ? \"Color posture should be validated against the captured page before cloning brand treatment.\" : \"Color posture remains a synthesis decision.\"}`,\n `- layout and hierarchy observations: ${referenceLayoutObservation(reference, excerpt)}`,\n `- component patterns: ${reference.capture?.clone ? \"Buttons, cards, or layout wrappers can be inferred from the captured clone preview.\" : \"Component families were inferred from available reference text.\"}`,\n `- motion/interaction observations: ${referenceMotionNote(reference)}`,\n `- accessibility/responsiveness notes: ${reference.captureStatus === \"captured\" ? \"Validate focus order, CTA prominence, and stacked layouts during build QA.\" : \"Accessibility and responsiveness are inferred from system defaults.\"}`,\n `- what should be adopted, adapted, or avoided: adopt layout hierarchy, adapt it to the new brand tokens, avoid copying proprietary copy or visual assets directly.`\n ].join(\"\\n\");\n};\n\nconst renderInspirationAnalysis = (\n references: InspiredesignReferenceEvidence[],\n usableReferences: InspiredesignReferenceEvidence[]\n): string => {\n if (usableReferences.length > 0) return usableReferences.map(renderReferenceMarkdown).join(\"\\n\\n\");\n if (references.length > 0) {\n return \"- Reference URLs were attempted, but no usable creative evidence was captured. See evidence.json for fetch/capture status.\";\n }\n return \"- No live inspiration source was provided. The system is derived entirely from the brief.\";\n};\n\nconst renderGovernanceMarkdown = (\n designContract: CanvasDesignGovernance,\n implementationPlan: InspiredesignImplementationPlan,\n format: InspiredesignBriefFormat\n): string => {\n const generationPlan = designContract.generationPlan as CanvasGenerationPlan;\n const profileConfig = PROFILE_CONFIG[generationPlan.visualDirection.profile];\n return [\n \"## 4.1 Design Intent\",\n formatBulletList([\n `Purpose: ${(designContract.intent.task as string) || \"\"}`,\n \"Capture the reusable visual logic from the references without cloning proprietary brand assets.\",\n \"Keep the resulting system executable for downstream build agents.\"\n ]),\n \"\",\n \"## 4.2 Core UX Principles\",\n formatBulletList(profileConfig.hierarchyPrinciples),\n \"\",\n \"## 4.3 Visual Identity\",\n formatBulletList([\n `Aesthetic style: ${profileConfig.visualPersonality}`,\n `Brand tone: ${profileConfig.brandTone}`,\n `Quality posture: ${profileConfig.direction}`,\n `Format archetype: ${format.archetype}`,\n `Surface treatment: ${format.surfaceTreatment}`,\n `Shape language: ${format.shapeLanguage}`,\n `Palette intent: ${format.paletteIntent}`,\n \"Direction: modern, system-led, and implementation-aware.\"\n ]),\n \"\",\n \"## 4.4 Color System\",\n formatRecordList(implementationPlan.tokenStrategy.colors),\n \"\",\n \"## 4.5 Typography System\",\n [\n formatBulletList([`system: ${format.typographySystem}`]),\n formatRecordList(implementationPlan.tokenStrategy.typography)\n ].join(\"\\n\"),\n \"\",\n \"## 4.6 Spacing and Layout System\",\n [\n formatBulletList([\n `layout archetype: ${format.layoutArchetype}`,\n `layout approach: ${generationPlan.layoutStrategy.approach}`,\n `navigation model: ${generationPlan.layoutStrategy.navigationModel}`\n ]),\n formatRecordList(implementationPlan.tokenStrategy.spacing)\n ].join(\"\\n\"),\n \"\",\n \"## 4.7 Shape, Border, and Elevation Rules\",\n [\n formatRecordList(implementationPlan.tokenStrategy.radius),\n formatRecordList(implementationPlan.tokenStrategy.shadow)\n ].join(\"\\n\"),\n \"\",\n \"## 4.8 Motion and Interaction Rules\",\n [\n formatBulletList([`motion grammar: ${format.motionGrammar}`]),\n formatRecordList(implementationPlan.tokenStrategy.motion)\n ].join(\"\\n\"),\n \"\",\n \"## 4.9 Component System\",\n implementationPlan.componentBuildPlan.map((component) => [\n `### ${component.name}`,\n formatBulletList([\n `purpose: ${component.purpose}`,\n `structure: build from semantic tokens and keep state visuals explicit`,\n `visual style: ${profileConfig.direction}`,\n `states: ${component.states.join(\", \")}`,\n \"spacing: keep internal padding on the 8px rhythm\",\n \"accessibility notes: preserve focus visibility and keyboard parity\",\n \"responsive behavior: stack content before line length becomes cramped\",\n `implementation notes: ${component.implementationNote}`\n ])\n ].join(\"\\n\")).join(\"\\n\\n\"),\n \"\",\n \"## 4.10 Page or Section Patterns\",\n formatBulletList(profileConfig.pagePatterns),\n \"\",\n \"## 4.11 Accessibility Requirements\",\n formatBulletList(implementationPlan.accessibilityChecklist),\n \"\",\n \"## 4.12 Responsiveness Requirements\",\n formatBulletList(implementationPlan.responsiveChecklist),\n \"\",\n \"## 4.13 Content and Microcopy Guidance\",\n formatBulletList([\n \"Use direct, confident labels and short CTA copy.\",\n \"Keep error and success messages specific to the affected region.\",\n \"Prefer descriptive button copy over generic verbs.\"\n ]),\n \"\",\n \"## 4.14 Do / Don't Rules\",\n formatBulletList([\n \"Do preserve one dominant message per section.\",\n \"Do encode repeated visual rules into semantic tokens.\",\n \"Don't copy proprietary logos, screenshots, or brand-only illustrations.\",\n \"Don't hide important actions inside ambiguous hover-only affordances.\",\n ...format.antiPatterns.map(renderAntiPatternRule)\n ]),\n \"\",\n \"## 4.15 Acceptance Criteria\",\n formatBulletList([\n \"Primary action is obvious within one viewport.\",\n \"Color, typography, spacing, and elevation all resolve through named tokens.\",\n \"Keyboard, focus, and reduced-motion behavior remain intact across breakpoints.\"\n ])\n ].join(\"\\n\");\n};\n\nconst renderImplementationMarkdown = (implementationPlan: InspiredesignImplementationPlan): string => {\n return [\n \"# 5. Implementation Plan\",\n \"\",\n \"## 5.1 Architecture Recommendation\",\n implementationPlan.architectureRecommendation,\n \"\",\n \"## 5.2 Design Token Strategy\",\n formatRecordList(implementationPlan.tokenStrategy.colors),\n \"\",\n formatRecordList(implementationPlan.tokenStrategy.typography),\n \"\",\n \"## 5.3 Reference Implementation Notes\",\n formatBulletList(implementationPlan.referenceImplementationNotes),\n \"\",\n \"## 5.4 Component Build Plan\",\n implementationPlan.componentBuildPlan.map((component, index) => (\n `${index + 1}. ${component.name}: ${component.purpose}`\n )).join(\"\\n\"),\n \"\",\n \"## 5.5 Page Assembly Plan\",\n formatBulletList(implementationPlan.pageAssemblyPlan),\n \"\",\n \"## 5.6 State and Interaction Plan\",\n formatBulletList(implementationPlan.stateAndInteractionPlan),\n \"\",\n \"## 5.7 Accessibility Implementation Checklist\",\n formatBulletList(implementationPlan.accessibilityChecklist),\n \"\",\n \"## 5.8 Responsive Implementation Checklist\",\n formatBulletList(implementationPlan.responsiveChecklist),\n \"\",\n \"## 5.9 Risks and Ambiguities\",\n formatBulletList(implementationPlan.risksAndAmbiguities),\n \"\",\n \"## 5.10 Recommended Build Sequence\",\n implementationPlan.buildSequence.map((step, index) => `${index + 1}. ${step}`).join(\"\\n\")\n ].join(\"\\n\");\n};\n\nconst renderTargetAnalysisGuidance = (targetAnalysis: InspiredesignTargetAnalysis): string => {\n const targetGuidance = [\n ...(targetAnalysis.page?.implementationNotes ?? []),\n ...(targetAnalysis.component?.prototypeGuidance ?? []),\n ...(targetAnalysis.asset?.prototypeGuidance ?? [])\n ];\n return [\n \"## 6.3 Target Analysis\",\n formatBulletList([\n `primary target: ${targetAnalysis.primaryKind}`,\n `target kinds: ${targetAnalysis.kinds.join(\", \")}`,\n `confidence: ${targetAnalysis.confidence.toFixed(2)}`,\n `triggering signals: ${targetAnalysis.triggeringSignals.join(\"; \")}`,\n ...targetGuidance,\n `anatomy: ${targetAnalysis.evidenceBuckets.anatomy.join(\" \")}`,\n `props/slots: ${targetAnalysis.evidenceBuckets.propsSlots.join(\" \")}`,\n `state matrix: ${targetAnalysis.evidenceBuckets.stateMatrix.join(\" \")}`,\n `tokens: ${targetAnalysis.evidenceBuckets.tokens.join(\" \")}`,\n `assets: ${targetAnalysis.evidenceBuckets.assets.join(\" \")}`,\n `accessibility: ${targetAnalysis.evidenceBuckets.accessibility.join(\" \")}`,\n `motion: ${targetAnalysis.evidenceBuckets.motion.join(\" \")}`,\n `preview fixtures: ${targetAnalysis.evidenceBuckets.previewFixtures.join(\" \")}`\n ])\n ].join(\"\\n\");\n};\n\nconst renderPrototypeGuidance = (\n profile: CanvasVisualDirectionProfile,\n synthesis: InspiredesignReferenceSynthesis,\n designVectors: InspiredesignDesignVectors,\n targetAnalysis: InspiredesignTargetAnalysis\n): string => {\n return [\n \"# 6. Optional Prototype Plan\",\n \"\",\n \"## 6.1 Reference Anchors\",\n formatBulletList(synthesis.lines.length > 0 ? synthesis.lines : [\"No live reference cues were captured.\"]),\n \"\",\n \"## 6.2 Prototype Structure\",\n \"- page structure: for public landing pages, build 8 to 12 content-rich sections unless the brief explicitly asks for a microsite.\",\n `- section architecture: ${designVectors.sectionArchitecture.join(\" \")}`,\n `- section order: ${PROFILE_CONFIG[profile].pagePatterns.join(\" -> \")}`,\n \"- component composition: reuse button, card, input, and navigation primitives before page-specific wrappers.\",\n `- interaction expectations: ${designVectors.interactionMoments.join(\" \")}`,\n `- motion expectations: ${designVectors.motionPosture.join(\" \")}`,\n `- material and depth expectations: ${designVectors.materialEffects.join(\" \")}`,\n `- advisory advanced motion: ${designVectors.advancedMotionAdvisory.join(\" \")}`,\n \"\",\n renderTargetAnalysisGuidance(targetAnalysis),\n \"\",\n \"- browser proof: capture desktop and mobile browser screenshots, verify reduced-motion behavior, inspect focus states, and confirm the primary CTA remains visible without overlap.\",\n \"- HTML skeleton guidance: start with one main landmark, one primary CTA group, and semantic sections that follow the design vector section architecture instead of fixed industry-specific defaults.\",\n \"- styling approach: define CSS variables for timing, easing, elevation, translucency, backdrop blur, cursor effects, hover effects, and parallax distance before mapping components to semantic tokens.\",\n \"- first prototype should include vs omit: include shell, primary hero or decision section, CTA group, proof or detail sections, section patterns named in the design vectors, final CTA, and footer; omit analytics, app-shell widgets, empty card grids, and any section not supported by the brief or reference evidence.\"\n ].join(\"\\n\");\n};\n\nconst renderDeliverablesSummary = (includePrototypeGuidance: boolean, canvasContinuationReady: boolean): string => {\n const deliverables = [\n \"Structured `designContract` JSON aligned to canvas governance\",\n \"Valid `generationPlan` JSON aligned to the canvas generation plan contract\",\n canvasContinuationReady\n ? \"Ready-to-fill `canvasPlanRequest` JSON for `canvas.plan.set`\"\n : \"Diagnostic `canvasPlanRequest` preview; do not submit to Canvas until next-step guidance is ready\",\n \"Design-agent handoff JSON with contract scope, skill nudges, and richer implementation context\",\n \"Human-readable `design.md` design specification\",\n \"Engineering implementation plan in JSON and Markdown\"\n ];\n if (includePrototypeGuidance) {\n deliverables.push(\"Prototype guidance Markdown for the first HTML pass\");\n }\n deliverables.push(\"Evidence digest describing brief, references, fetch outcomes, and capture outcomes\");\n return formatBulletList(deliverables);\n};\n\ntype BuildEvidencePayloadInput = {\n brief: string;\n briefExpansion: InspiredesignBriefExpansion;\n advancedBriefMarkdown: string;\n urls: string[];\n references: InspiredesignReferenceEvidence[];\n referencePatternBoard: InspiredesignReferencePatternBoard;\n designVectors: InspiredesignDesignVectors;\n targetAnalysis: InspiredesignTargetAnalysis;\n};\n\nconst buildEvidencePayload = ({\n brief,\n briefExpansion,\n advancedBriefMarkdown,\n urls,\n references,\n referencePatternBoard,\n designVectors,\n targetAnalysis\n}: BuildEvidencePayloadInput): JsonRecord => ({\n brief,\n briefHash: referenceFingerprint(brief),\n advancedBrief: advancedBriefMarkdown,\n advancedBriefHash: referenceFingerprint(advancedBriefMarkdown),\n briefExpansion: {\n templateVersion: briefExpansion.templateVersion,\n format: cloneInspiredesignBriefFormat(briefExpansion.format)\n },\n urls,\n referenceCount: references.length,\n references: references.map((reference) => toReferenceEvidenceJson(reference)),\n referencePatternBoard: referencePatternBoard as JsonRecord,\n rankedReferences: referencePatternBoard.references as unknown as JsonValue,\n designVectors: designVectors as JsonRecord,\n targetAnalysis: targetAnalysis as JsonRecord,\n visualEvidence: buildVisualEvidencePayload(references) as unknown as JsonValue,\n screenshotIndex: buildScreenshotIndex(references) as unknown as JsonValue\n});\n\nconst buildVisualEvidencePayload = (\n references: InspiredesignReferenceEvidence[]\n): InspiredesignVisualEvidenceJson[] => references.flatMap((reference) => {\n const visual = normalizeInspiredesignCaptureEvidence(reference.capture)?.visual;\n return visual ? [{\n referenceId: reference.id,\n url: reference.url,\n visual: persistInspiredesignVisualEvidence(visual)\n }] : [];\n});\n\nconst buildScreenshotIndex = (\n references: InspiredesignReferenceEvidence[]\n): InspiredesignScreenshotIndexEntry[] => buildVisualEvidencePayload(references)\n .filter((entry): entry is InspiredesignVisualEvidenceJson & {\n visual: InspiredesignPersistedVisualEvidence & { path: string; sha256: string; bytes: number };\n } => (\n entry.visual.status === \"captured\"\n && typeof entry.visual.path === \"string\"\n && typeof entry.visual.sha256 === \"string\"\n && typeof entry.visual.bytes === \"number\"\n ))\n .map((entry) => ({\n referenceId: entry.referenceId,\n url: entry.url,\n path: entry.visual.path,\n sha256: entry.visual.sha256,\n bytes: entry.visual.bytes,\n kind: entry.visual.kind,\n fullPage: entry.visual.fullPage,\n capturedAt: entry.visual.capturedAt\n }));\n\nconst toCaptureEvidenceJson = (reference: InspiredesignReferenceEvidence): JsonValue => {\n const normalized = normalizeInspiredesignCaptureEvidence(reference.capture);\n if (!normalized) return null;\n const signals = getInspiredesignReferenceSignals(reference);\n return {\n ...(normalized.title ? { title: normalized.title } : {}),\n ...(signals.length > 0 ? { signals } : {}),\n ...(normalized.visual ? { visual: normalized.visual as JsonRecord } : {}),\n ...(normalized.attempts ? { attempts: normalized.attempts } : {})\n };\n};\n\nconst toReferenceEvidenceJson = (reference: InspiredesignReferenceEvidence): JsonValue => ({\n id: reference.id,\n url: reference.url,\n ...(reference.title ? { title: reference.title } : {}),\n ...(reference.excerpt ? { excerpt: reference.excerpt } : {}),\n fetchStatus: reference.fetchStatus,\n captureStatus: reference.captureStatus,\n ...(reference.fetchFailure ? { fetchFailure: reference.fetchFailure } : {}),\n ...(reference.captureFailure ? { captureFailure: reference.captureFailure } : {}),\n capture: toCaptureEvidenceJson(reference)\n});\n\nexport const buildInspiredesignPacket = (input: BuildInspiredesignPacketInput): InspiredesignPacket => {\n const brief = trimText(input.brief);\n const selectedFormat = cloneInspiredesignBriefFormat(input.briefExpansion.format);\n const includePrototypeGuidance = input.includePrototypeGuidance ?? false;\n const urls = [...new Set(input.urls.map((url) => trimText(url)).filter(Boolean))];\n const references = input.references.map((reference) => ({\n ...reference,\n title: reference.title ? trimText(reference.title) : undefined,\n excerpt: reference.excerpt ? trimText(reference.excerpt) : undefined\n }));\n const referenceEvidenceRequired = input.referenceEvidenceRequired ?? (urls.length > 0 || references.length > 0);\n const referencePatternBoard = buildInspiredesignReferencePatternBoard(\n referenceFingerprint(brief),\n selectedFormat,\n references,\n brief\n );\n const readyReferenceIds = new Set(\n referencePatternBoard.references.filter(isInspiredesignDesignReference).map((reference) => reference.id)\n );\n const usableReferences = references\n .filter(hasInspiredesignUsableReferenceEvidence)\n .filter((reference) => readyReferenceIds.has(reference.id));\n const synthesis = buildReferenceSynthesis(usableReferences);\n const designVectors = buildInspiredesignDesignVectors(selectedFormat, referencePatternBoard);\n const designReferencePatternBoard = buildInspiredesignDesignReferencePatternBoard(referencePatternBoard, designVectors);\n const effectiveFormat = buildEvidenceDerivedFormat(selectedFormat, designVectors);\n const targetAnalysis = buildTargetAnalysis(\n brief,\n effectiveFormat,\n usableReferences,\n synthesis,\n designVectors\n );\n const effectiveBriefExpansion: InspiredesignBriefExpansion = {\n ...input.briefExpansion,\n advancedBrief: isReferenceFirstPublicLanding(designVectors)\n ? renderEvidenceDerivedAdvancedBrief(input.briefExpansion, effectiveFormat)\n : input.briefExpansion.advancedBrief,\n format: effectiveFormat\n };\n const metaPromptMarkdown = buildInspiredesignMetaPrompt({\n brief,\n briefExpansion: effectiveBriefExpansion,\n referencePatternBoard,\n designVectors\n });\n const advancedBriefMarkdown = renderReferenceFirstAdvancedBrief(\n effectiveBriefExpansion,\n designReferencePatternBoard,\n designVectors,\n references\n );\n const generationPlan = buildGenerationPlan({\n brief,\n format: effectiveFormat,\n synthesis,\n referencePatternBoard: designReferencePatternBoard,\n designVectors,\n targetAnalysis\n });\n const profile = generationPlan.visualDirection.profile;\n const canvasPlanRequest = buildCanvasPlanRequest(brief, generationPlan);\n const designContract = buildDesignContract({\n brief,\n designReferences: usableReferences,\n plan: generationPlan,\n format: effectiveFormat\n });\n const followthrough = buildFollowthrough({\n generationPlan,\n briefExpansion: effectiveBriefExpansion,\n synthesis,\n includePrototypeGuidance,\n referencePatternBoard: designReferencePatternBoard,\n designVectors,\n targetAnalysis\n });\n const implementationPlan = buildImplementationPlan({\n profile,\n format: effectiveFormat,\n references: usableReferences,\n attemptedReferenceCount: references.length,\n synthesis,\n designVectors\n });\n const governanceMarkdown = renderGovernanceMarkdown(designContract, implementationPlan, effectiveFormat);\n const implementationPlanMarkdown = renderImplementationMarkdown(implementationPlan);\n const prototypeGuidanceMarkdown = includePrototypeGuidance\n ? renderPrototypeGuidance(profile, synthesis, designVectors, targetAnalysis)\n : null;\n const designMarkdown = [\n \"# 1. Executive Summary\",\n \"\",\n formatBulletList([\n `Analyzed brief plus ${references.length || 0} inspiration reference(s).`,\n `Chosen design direction: ${designVectors.surfaceIntent}.`,\n `Route profile: ${PROFILE_CONFIG[profile].direction}.`,\n `Prompt format: ${selectedFormat.label} (${input.briefExpansion.templateVersion}).`,\n \"Final outcome: a reusable design contract, engineering plan, and optional prototype guidance.\",\n `Scope mode: ${references.length > 1 ? \"full-site synthesis\" : \"single-surface synthesis\"}.`\n ]),\n \"\",\n \"# 2. Inspiration Analysis\",\n \"\",\n renderInspirationAnalysis(references, usableReferences),\n \"\",\n \"# 3. Unified Design Direction\",\n \"\",\n \"## 3.1 Reference-Specific Build Rules\",\n \"\",\n formatBulletList(synthesis.lines.length > 0 ? synthesis.lines : [\"No live reference cues were captured.\"]),\n \"\",\n \"## 3.2 Reference Pattern Board\",\n \"\",\n formatBulletList(designVectors.patternsToBorrow.length > 0\n ? designVectors.patternsToBorrow\n : [\"No live reference cues were captured.\"]),\n \"\",\n \"## 3.3 Design Vectors\",\n \"\",\n formatBulletList([\n `source priority: ${designVectors.sourcePriority}`,\n `direction: ${designVectors.directionLabel}`,\n `premium posture: ${designVectors.premiumPosture.join(\" \")}`,\n `motion posture: ${designVectors.motionPosture.join(\" \")}`,\n `section architecture: ${designVectors.sectionArchitecture.join(\" \")}`,\n `interaction moments: ${designVectors.interactionMoments.join(\" \")}`,\n `material effects: ${designVectors.materialEffects.join(\" \")}`,\n `advanced motion advisory: ${designVectors.advancedMotionAdvisory.join(\" \")}`\n ]),\n \"\",\n \"## 3.4 System Direction\",\n \"\",\n formatBulletList([\n `visual personality: ${PROFILE_CONFIG[profile].visualPersonality}`,\n `tone: ${PROFILE_CONFIG[profile].brandTone}`,\n `layout archetype: ${effectiveFormat.layoutArchetype}`,\n `typography system: ${effectiveFormat.typographySystem}`,\n `motion grammar: ${effectiveFormat.motionGrammar}`,\n `UX principles: ${PROFILE_CONFIG[profile].hierarchyPrinciples.join(\" \")}`,\n `interaction philosophy: ${PROFILE_CONFIG[profile].interactionPhilosophy}`,\n \"branding posture: preserve the intent of the references without cloning brand-only assets.\",\n \"system coherence rules: encode tokens first, keep one dominant idea per section, and keep states explicit.\"\n ]),\n \"\",\n \"# 4. Design Governance (`design.md`)\",\n \"\",\n governanceMarkdown,\n \"\",\n renderImplementationMarkdown(implementationPlan),\n \"\",\n prototypeGuidanceMarkdown ?? \"# 6. Optional Prototype Plan\\n\\n- Prototype guidance omitted for this run.\",\n \"\",\n \"# 7. Deliverables Summary\",\n \"\",\n renderDeliverablesSummary(\n Boolean(input.includePrototypeGuidance),\n !referenceEvidenceRequired || designReferencePatternBoard.references.length > 0\n )\n ].join(\"\\n\");\n\n const visualEvidence = buildVisualEvidencePayload(references);\n const screenshotIndex = buildScreenshotIndex(references);\n return {\n advancedBriefMarkdown,\n designContract,\n generationPlan,\n canvasPlanRequest,\n followthrough,\n designMarkdown,\n implementationPlan,\n implementationPlanMarkdown,\n prototypeGuidanceMarkdown,\n visualEvidence,\n screenshotIndex,\n rankedReferences: designReferencePatternBoard.references,\n referencePatternBoard,\n metaPromptMarkdown,\n evidence: buildEvidencePayload({\n brief,\n briefExpansion: effectiveBriefExpansion,\n advancedBriefMarkdown,\n urls,\n references,\n referencePatternBoard: designReferencePatternBoard,\n designVectors,\n targetAnalysis\n })\n };\n};\n","{\n \"requestId\": \"req_plan_design_01\",\n \"canvasSessionId\": \"<canvas-session-id>\",\n \"leaseId\": \"<lease-id>\",\n \"documentId\": \"<document-id>\",\n \"generationPlan\": {\n \"targetOutcome\": {\n \"mode\": \"high-fi-live-edit\",\n \"summary\": \"Clarify hierarchy, trust, and action flow\"\n },\n \"visualDirection\": {\n \"profile\": \"product-story\",\n \"themeStrategy\": \"single-theme\"\n },\n \"layoutStrategy\": {\n \"approach\": \"hero-led-grid\",\n \"navigationModel\": \"global-header\"\n },\n \"contentStrategy\": {\n \"source\": \"real-content-first\"\n },\n \"componentStrategy\": {\n \"mode\": \"reuse-first\",\n \"interactionStates\": [\n \"default\",\n \"hover\",\n \"focus\",\n \"disabled\"\n ]\n },\n \"motionPosture\": {\n \"level\": \"subtle\",\n \"reducedMotion\": \"respect-user-preference\"\n },\n \"responsivePosture\": {\n \"primaryViewport\": \"desktop\",\n \"requiredViewports\": [\n \"desktop\",\n \"tablet\",\n \"mobile\"\n ]\n },\n \"accessibilityPosture\": {\n \"target\": \"WCAG_2_2_AA\",\n \"keyboardNavigation\": \"full\"\n },\n \"validationTargets\": {\n \"blockOn\": [\n \"contrast-failure\",\n \"responsive-mismatch\"\n ],\n \"requiredThemes\": [\n \"light\"\n ],\n \"browserValidation\": \"required\",\n \"maxInteractionLatencyMs\": 160\n }\n }\n}\n","{\n \"intent\": {\n \"audience\": \"Operators evaluating a new OpenDevBrowser design flow\",\n \"task\": \"Understand the primary page value and complete the intended action quickly\",\n \"successCriteria\": [\n \"Primary action is obvious within 5 seconds\",\n \"Layout remains coherent on desktop, tablet, and mobile\"\n ],\n \"trustPosture\": \"clear and confident\"\n },\n \"designLanguage\": {\n \"direction\": \"product-led clarity\",\n \"styleAxes\": {\n \"contrast\": \"high\",\n \"density\": \"airy\",\n \"shapeLanguage\": \"rounded-structured\",\n \"depth\": \"subtle\",\n \"texture\": \"minimal\",\n \"motion\": \"purposeful\"\n },\n \"approvedLibraries\": {\n \"components\": [\n \"shadcn\"\n ],\n \"icons\": [\n \"tabler\"\n ],\n \"styling\": [\n \"tailwindcss\"\n ]\n },\n \"semanticTokenSource\": {\n \"owner\": \"app-shell theme provider\",\n \"tokens\": [\n \"color\",\n \"typography\",\n \"spacing\",\n \"radius\",\n \"shadow\",\n \"motion\"\n ],\n \"rule\": \"Use semantic tokens in repeated UI; reserve raw values for rare one-off illustration\"\n }\n },\n \"contentModel\": {\n \"primaryMessage\": \"Show the core value immediately with real copy\",\n \"supportingMessages\": [\n \"Reinforce trust\",\n \"Clarify the primary action\",\n \"Reduce ambiguity\"\n ],\n \"realContentRequired\": true,\n \"states\": [\n \"default\",\n \"hover\",\n \"focus\",\n \"empty\",\n \"loading\",\n \"success\",\n \"error\"\n ],\n \"loadingStrategy\": \"Preserve the final layout with 3-6 placeholders or one section-level loader when structure cannot be previewed\",\n \"emptyStateStrategy\": \"Explain why nothing is shown and provide the next useful action\",\n \"errorStateStrategy\": \"Keep retry or recovery actions close to the failed region\",\n \"transientFeedbackStrategy\": \"Use short, non-blocking overlays for confirmations instead of reflowing the main layout\",\n \"avoidPlaceholderCopy\": true\n },\n \"navigationModel\": {\n \"owner\": \"feature shell route controller\",\n \"primaryRouteModel\": \"One canonical route map translates tabs, selected records, and editor modes into URL-backed state\",\n \"deepLinkPolicy\": \"Shareable tabs, filters, sort, and selected entities stay in the URL with a safe fallback when params are stale or incomplete\",\n \"invalidRouteFallback\": \"Recover to the closest safe baseline view instead of leaving the screen in a partially initialized state\",\n \"overlayEntryPoints\": [\n \"route-owned detail drawer\",\n \"feature-owned confirmation modal\"\n ]\n },\n \"asyncModel\": {\n \"owner\": \"feature-local controller with URL-owned query state when sharing or refresh matters\",\n \"loadTrigger\": \"load-on-enter for the first view; debounced restart on query, scope, or sort change\",\n \"restartTriggers\": [\n \"query\",\n \"scope\",\n \"sort\"\n ],\n \"debounceMs\": 250,\n \"emptyQueryBehavior\": \"Reset to the baseline or empty state without a remote fetch unless the product explicitly needs default results\",\n \"cancellationPolicy\": \"Treat stale requests as normal and do not surface cancellation as a user-facing error\",\n \"moveToServiceWhen\": [\n \"work must survive dismissal\",\n \"caching or retry policy becomes shared\",\n \"multiple screens depend on the same in-flight state\"\n ],\n \"urlOwnership\": \"Put query, filter, and sort in the URL when the state should survive refresh, sharing, or handoff\"\n },\n \"layoutSystem\": {\n \"grid\": \"12-column responsive grid\",\n \"containers\": \"max-width sections with asymmetric emphasis\",\n \"spacingRhythm\": \"8px base with larger section jumps\",\n \"alignmentRules\": [\n \"Primary content aligns to a consistent reading column\",\n \"Actions stay near the message they complete\"\n ]\n },\n \"typographySystem\": {\n \"families\": [\n \"Space Grotesk\",\n \"Source Sans 3\"\n ],\n \"scale\": [\n \"12\",\n \"14\",\n \"16\",\n \"20\",\n \"28\",\n \"40\",\n \"56\"\n ],\n \"measure\": \"60-72 characters for dense reading blocks\",\n \"fallbackPolicy\": \"Use repo-native or licensed alternatives when these families are unavailable\",\n \"loadingStrategy\": \"Avoid layout shift and keep fallback metrics close\"\n },\n \"motionSystem\": {\n \"timing\": \"short and decisive\",\n \"reducedMotionPolicy\": \"Preserve meaning with reduced movement\",\n \"interactionMoments\": [\n \"page entry\",\n \"section reveal\",\n \"primary CTA feedback\"\n ],\n \"parallaxPolicy\": \"off unless explicitly justified\",\n \"advancedMotionAdvisory\": [\n \"Advisory shader-like gradient depth: describe intent only; implement with approved runtime primitives unless a separate runtime change authorizes more.\",\n \"Advisory WebGL-style spatial reveal: document depth and hierarchy without implying WebGL runtime support.\",\n \"Advisory Spline-style product orbit: document scene posture and static fallback without approving custom 3D runtime dependencies.\",\n \"Runtime boundary: libraryPolicy.motion and libraryPolicy.threeD stay empty unless separately approved.\"\n ]\n },\n \"performanceModel\": {\n \"renderHotspots\": [\n \"scan-heavy collection region\",\n \"secondary inspector or preview pane\"\n ],\n \"stableIdentityPolicy\": \"Rows, cards, tabs, and overlays use stable domain ids instead of array indexes\",\n \"listStrategy\": \"Use the smallest structure that stays fast with realistic data; choose progressive reveal, lazy containers, or virtualization deliberately\",\n \"secondaryPanelPolicy\": \"Heavy inspectors, previews, and editors load on demand when they are not required for first paint\",\n \"measurementPlan\": \"Validate realistic data volume with browser traces and the framework profiler before claiming the surface is performant\"\n },\n \"responsiveSystem\": {\n \"breakpoints\": [\n \"mobile\",\n \"tablet\",\n \"desktop\"\n ],\n \"adaptationRules\": [\n \"Collapse multicolumn sections before copy becomes cramped\",\n \"Preserve primary CTA prominence on the smallest viewport\"\n ],\n \"touchPolicy\": \"Comfortable targets and low-friction scroll paths\",\n \"overflowPolicy\": \"No horizontal scroll for primary content\"\n },\n \"accessibilityPolicy\": {\n \"target\": \"WCAG 2.2 AA\",\n \"keyboardRequirements\": [\n \"Visible focus\",\n \"Logical tab order\"\n ],\n \"focusPolicy\": \"Focus rings must remain visible against every background\",\n \"semanticRequirements\": [\n \"Landmarks are explicit\",\n \"Headings remain hierarchical\"\n ]\n },\n \"generationPlan\": {\n \"targetOutcome\": {\n \"mode\": \"high-fi-live-edit\",\n \"summary\": \"Improve hierarchy, clarity, and conversion confidence\"\n },\n \"visualDirection\": {\n \"profile\": \"product-led-clarity\",\n \"styleAxes\": {\n \"contrast\": \"high\",\n \"density\": \"airy\"\n }\n },\n \"layoutStrategy\": {\n \"approach\": \"hero-led-grid\"\n },\n \"contentStrategy\": {\n \"source\": \"real-content-first\"\n },\n \"componentStrategy\": {\n \"mode\": \"reuse-first\",\n \"approvedLibraries\": [\n \"shadcn\"\n ]\n },\n \"motionPosture\": {\n \"level\": \"subtle\",\n \"allow3D\": false,\n \"allowParallax\": false,\n \"allowCustomSmoothScroll\": false\n },\n \"responsivePosture\": {\n \"primaryViewport\": \"desktop\",\n \"requiredViewports\": [\n \"desktop\",\n \"tablet\",\n \"mobile\"\n ]\n },\n \"accessibilityPosture\": {\n \"target\": \"WCAG_2_2_AA\",\n \"reducedMotion\": \"required\",\n \"keyboardParity\": true\n },\n \"validationTargets\": {\n \"blockOn\": [\n \"contrast-failure\",\n \"keyboard-regression\",\n \"stale-search-results\",\n \"invalid-route-recovery-failure\"\n ],\n \"warnOn\": [\n \"responsive-mismatch\",\n \"layout-shift\",\n \"spinner-stacking\",\n \"scan-surface-jank\"\n ]\n },\n \"designVectors\": {\n \"advancedMotionAdvisory\": [\n \"Advisory shader-like gradient depth\",\n \"Advisory WebGL-style spatial reveal\",\n \"Advisory Spline-style product orbit\",\n \"Runtime support: none. Library policy authorization: none.\"\n ]\n }\n }\n}\n","{\n \"version\": \"inspiredesign-advanced-brief.v1\",\n \"defaultFormatId\": \"premium-editorial-landing-page\",\n \"commonRules\": [\n \"Preserve only the product, brand, audience, platform, and tone cues that are explicitly present in the source brief.\",\n \"Treat missing details as open constraints instead of inventing brand facts or user needs.\",\n \"Use inspiration references to extract transferable design logic rather than copying a single layout, visual treatment, or narrative beat literally.\",\n \"Treat shader, WebGL, Spline-style, and 3D motion ideas as advisory design cues only, not as runtime support or dependency approval.\",\n \"Carry accepted advanced motion cues in designVectors and motionSystem as intent, and keep libraryPolicy authorization separate.\"\n ],\n \"outputRequirements\": [\n \"Return a reusable design contract that can drive design.md, implementation-plan artifacts, and a Canvas-ready prototype path.\",\n \"Keep the direction premium, specific, and implementable instead of generic or template-driven.\",\n \"Keep libraryPolicy.motion and libraryPolicy.threeD empty in generated samples unless a separate runtime change explicitly approves those libraries.\"\n ],\n \"formats\": [\n {\n \"id\": \"premium-editorial-landing-page\",\n \"label\": \"Premium editorial landing page\",\n \"bestFor\": [\n \"product homepages\",\n \"docs homepages\",\n \"consulting service homepages\",\n \"launch pages\",\n \"rebrands\"\n ],\n \"businessFocus\": [\n \"premium SaaS marketing\",\n \"product launches\",\n \"AI consulting services\",\n \"enterprise advisory landing pages\",\n \"docs-first brands\",\n \"brand refresh surfaces\"\n ],\n \"keywords\": [\n \"landing\",\n \"homepage\",\n \"launch\",\n \"brand\",\n \"editorial\",\n \"hero\",\n \"marketing\",\n \"consulting\",\n \"advisory\",\n \"enterprise AI\",\n \"services\",\n \"case studies\",\n \"docs\"\n ],\n \"matchSignals\": {\n \"positive\": [\n \"landing\",\n \"homepage\",\n \"home page\",\n \"launch\",\n \"brand\",\n \"rebrand\",\n \"editorial\",\n \"hero\",\n \"marketing\",\n \"consulting\",\n \"advisory\",\n \"ai consulting\",\n \"enterprise ai\",\n \"business services\",\n \"client services\",\n \"case studies\",\n \"transformation\",\n \"services\",\n \"cta\",\n \"docs\"\n ],\n \"excluded\": [\n \"dashboard\",\n \"admin\",\n \"onboarding\"\n ],\n \"tieBreaker\": 2\n },\n \"lead\": \"Study the inspiration references and synthesize a premium editorial landing page system that translates the source brief into a reusable, brand-specific direction.\",\n \"archetype\": \"editorial brand campaign\",\n \"layoutArchetype\": \"full-bleed hero with narrative section cadence\",\n \"typographySystem\": \"display serif or refined grotesk headlines paired with restrained sans body copy\",\n \"surfaceTreatment\": \"bright print-like planes, disciplined image crops, and hairline dividers\",\n \"shapeLanguage\": \"sharp framing with selective soft corners only where interaction requires it\",\n \"componentGrammar\": \"hero composition, proof bands, narrative media strips, restrained CTA groups\",\n \"motionGrammar\": \"measured fades, staggered reveals, and restrained parallax\",\n \"paletteIntent\": \"bright neutral field with one confident accent and controlled contrast\",\n \"visualDensity\": \"airy\",\n \"designVariance\": \"balanced asymmetry\",\n \"focusAreas\": [\n \"hero composition\",\n \"brand presence\",\n \"typography rhythm\",\n \"spacing cadence\",\n \"image treatment\",\n \"CTA hierarchy\",\n \"section sequencing\",\n \"trust-building moments\",\n \"motion tone\"\n ],\n \"responsiveCollapseRules\": [\n \"Collapse split editorial compositions into a single text-first stack before line length becomes cramped.\",\n \"Keep one dominant visual plane on mobile rather than shrinking multiple competing media blocks.\"\n ],\n \"guardrails\": [\n \"Prioritize one dominant hero idea and a clear narrative progression instead of dashboard-style clutter.\",\n \"Favor a full-bleed visual approach with restrained supporting copy and deliberate section sequencing.\"\n ],\n \"antiPatterns\": [\n \"No feature-card hero.\",\n \"No metric strip in the first viewport.\",\n \"No generic startup copy tone.\",\n \"No dashboard chrome on a marketing surface.\"\n ],\n \"deliverables\": [\n \"Translate the references into a reusable design contract that fits the product story, audience, and brand voice in the source brief.\",\n \"Define the hero doctrine, visual hierarchy, and section cadence clearly enough for a first implementation pass.\"\n ],\n \"route\": {\n \"profile\": \"product-story\",\n \"themeStrategy\": \"single-theme\",\n \"navigationModel\": \"global-header\",\n \"layoutApproach\": \"editorial-hero-sequence\"\n }\n },\n {\n \"id\": \"b2b-dashboard-app-shell\",\n \"label\": \"B2B dashboard or app shell\",\n \"bestFor\": [\n \"admin products\",\n \"internal tools\",\n \"data-heavy SaaS\"\n ],\n \"businessFocus\": [\n \"operations software\",\n \"internal tooling\",\n \"multi-tenant analytics products\",\n \"enterprise control surfaces\"\n ],\n \"keywords\": [\n \"dashboard\",\n \"admin\",\n \"app shell\",\n \"internal tool\",\n \"operator\",\n \"table\",\n \"analytics\",\n \"SaaS\"\n ],\n \"matchSignals\": {\n \"positive\": [\n \"dashboard\",\n \"admin\",\n \"app shell\",\n \"app-shell\",\n \"internal tool\",\n \"operator\",\n \"table\",\n \"analytics\",\n \"saas\",\n \"control room\"\n ],\n \"excluded\": [\n \"onboarding\",\n \"villa\",\n \"festival\"\n ],\n \"tieBreaker\": 2\n },\n \"lead\": \"Use the inspiration references and source brief to extract a reusable dashboard and app-shell contract that stays fast, calm, and operator-friendly.\",\n \"archetype\": \"operational workspace shell\",\n \"layoutArchetype\": \"predictable desktop shell with fixed navigation zones and state-aware work panels\",\n \"typographySystem\": \"sharp grotesk UI type with monospaced numeric support for tables and diagnostics\",\n \"surfaceTreatment\": \"bright control-room surfaces with disciplined dividers and low-elevation panels\",\n \"shapeLanguage\": \"rectilinear structure with restrained radii and explicit separators\",\n \"componentGrammar\": \"sidebar, command toolbar, filter rail, data tables, detail drawers, empty states\",\n \"motionGrammar\": \"state-transition clarity, panel continuity, and zero decorative animation noise\",\n \"paletteIntent\": \"crisp neutral shell with one utility accent and clear semantic state colors\",\n \"visualDensity\": \"dense but breathable\",\n \"designVariance\": \"low-variance structure\",\n \"focusAreas\": [\n \"information hierarchy\",\n \"sidebar behavior\",\n \"top-bar responsibilities\",\n \"search and filter placement\",\n \"table-versus-card decisions\",\n \"density management\",\n \"panel rhythm\",\n \"empty states\",\n \"loading states\",\n \"primary action priority\"\n ],\n \"responsiveCollapseRules\": [\n \"Collapse secondary panes before compressing the primary work surface.\",\n \"Preserve search, filters, and the primary action path as fixed zones on narrow breakpoints.\"\n ],\n \"guardrails\": [\n \"Favor predictable layout zones, strong state communication, and clean action paths over decorative UI noise.\",\n \"Keep the interaction model credible and scalable across desktop breakpoints.\"\n ],\n \"antiPatterns\": [\n \"No hero marketing treatment inside the shell.\",\n \"No floating-window chaos.\",\n \"No equal-emphasis KPI tiles everywhere.\",\n \"No ornamental glass or neon styling.\"\n ],\n \"deliverables\": [\n \"Return a dashboard contract that can guide a first implementation plan and a Canvas-first prototype handoff.\",\n \"Specify the shell grammar for navigation, filters, data views, and state feedback.\"\n ],\n \"route\": {\n \"profile\": \"ops-control\",\n \"themeStrategy\": \"single-theme\",\n \"navigationModel\": \"sidebar\",\n \"layoutApproach\": \"workspace-shell\"\n }\n },\n {\n \"id\": \"cinematic-product-story\",\n \"label\": \"Cinematic product-story or photostudio direction\",\n \"bestFor\": [\n \"hardware\",\n \"consumer products\",\n \"showcase pages\",\n \"keynote-style launches\"\n ],\n \"businessFocus\": [\n \"hardware launches\",\n \"premium consumer products\",\n \"device showcases\",\n \"showcase-led commerce alternatives\"\n ],\n \"keywords\": [\n \"product story\",\n \"hardware\",\n \"device\",\n \"physical product\",\n \"showcase\",\n \"photography\",\n \"keynote\"\n ],\n \"matchSignals\": {\n \"positive\": [\n \"product story\",\n \"product-story\",\n \"hardware\",\n \"device\",\n \"physical product\",\n \"showcase\",\n \"photography\",\n \"launch page\",\n \"keynote\",\n \"consumer product\"\n ],\n \"excluded\": [\n \"dashboard\",\n \"settings\",\n \"festival\"\n ],\n \"tieBreaker\": 2\n },\n \"lead\": \"Study the inspiration references and synthesize a cinematic product-story direction that turns the source brief into a premium, product-led narrative.\",\n \"archetype\": \"photostudio launch narrative\",\n \"layoutArchetype\": \"scene-based scroll story with full-bleed product reveals\",\n \"typographySystem\": \"restrained sans or condensed display with large scale contrast and minimal body copy\",\n \"surfaceTreatment\": \"dark or bright studio backdrops, high-contrast product planes, and controlled material highlights\",\n \"shapeLanguage\": \"large uninterrupted planes with almost no ornamental framing\",\n \"componentGrammar\": \"scene hero, proof interludes, spec reveals, testimonial or quote punctuations\",\n \"motionGrammar\": \"slow dissolves, glide transitions, and product-led reveal timing\",\n \"paletteIntent\": \"controlled studio palette that serves material realism instead of interface variety\",\n \"visualDensity\": \"sparse\",\n \"designVariance\": \"high cinematic contrast\",\n \"focusAreas\": [\n \"lighting\",\n \"framing\",\n \"crop strategy\",\n \"material and surface cues\",\n \"typography restraint\",\n \"scroll pacing\",\n \"transition from emotion to proof\",\n \"product-detail storytelling\"\n ],\n \"responsiveCollapseRules\": [\n \"Keep one scene per scroll beat on mobile instead of compressing multiple proof layers together.\",\n \"Stack product proof and supporting copy under the main image plane once panoramic width is lost.\"\n ],\n \"guardrails\": [\n \"Do not fall back to generic ecommerce grids, trust-badge clutter, or spec-dump layouts.\",\n \"Prioritize product-story clarity over commerce-system conventions and keep the scene count disciplined.\"\n ],\n \"antiPatterns\": [\n \"No marketplace product grid.\",\n \"No coupon or deal framing.\",\n \"No dense comparison tables in the hero.\",\n \"No dashboard-like metric blocks.\"\n ],\n \"deliverables\": [\n \"Return a premium product-led story with 3 to 5 clear scene beats and a strong visual hierarchy.\",\n \"Define the scene structure, motion posture, and proof handoff clearly enough for a launch-page build.\"\n ],\n \"route\": {\n \"profile\": \"cinematic-minimal\",\n \"themeStrategy\": \"single-theme\",\n \"navigationModel\": \"immersive\",\n \"layoutApproach\": \"product-scene-scroll\"\n }\n },\n {\n \"id\": \"mobile-first-onboarding-activation\",\n \"label\": \"Mobile-first onboarding and activation flow\",\n \"bestFor\": [\n \"consumer apps\",\n \"onboarding redesigns\",\n \"activation funnel work\"\n ],\n \"businessFocus\": [\n \"consumer mobile apps\",\n \"activation funnel redesigns\",\n \"first-session experiences\",\n \"trust-forward account creation\"\n ],\n \"keywords\": [\n \"mobile\",\n \"onboarding\",\n \"activation\",\n \"signup\",\n \"first session\",\n \"consumer app\",\n \"funnel\"\n ],\n \"matchSignals\": {\n \"positive\": [\n \"mobile\",\n \"onboarding\",\n \"activation\",\n \"signup\",\n \"sign-up\",\n \"first session\",\n \"consumer app\",\n \"funnel\",\n \"activation flow\",\n \"native app\"\n ],\n \"required\": [\n \"mobile\"\n ],\n \"excluded\": [\n \"dashboard\",\n \"festival\"\n ],\n \"tieBreaker\": 2\n },\n \"lead\": \"Work from the inspiration references and source brief to define a mobile-first onboarding and activation experience that moves a user from curiosity to a confident first action.\",\n \"archetype\": \"trust-forward activation flow\",\n \"layoutArchetype\": \"screen-sequenced onboarding stack with clear first-action transition\",\n \"typographySystem\": \"high-legibility mobile sans with deliberate contrast between titles, helper copy, and CTA labels\",\n \"surfaceTreatment\": \"native-feeling surfaces, clean overlays, and quiet previews of the core product\",\n \"shapeLanguage\": \"soft, tap-friendly forms and decisive CTA containers\",\n \"componentGrammar\": \"value slides, progress moments, CTA stacks, trust cues, first-session empty states\",\n \"motionGrammar\": \"confident screen pacing, low-friction transitions, and gentle confirmation motion\",\n \"paletteIntent\": \"safe, modern mobile palette with one brand accent and generous clean space\",\n \"visualDensity\": \"balanced\",\n \"designVariance\": \"low-noise clarity\",\n \"focusAreas\": [\n \"first impression\",\n \"explanation of value\",\n \"screen pacing\",\n \"UI-preview usage\",\n \"illustration or motion strategy\",\n \"trust cues\",\n \"CTA structure\",\n \"key transition moments\",\n \"first-session empty state behavior\",\n \"visual rules that should carry into the core product\"\n ],\n \"responsiveCollapseRules\": [\n \"Treat mobile as the source layout and only expand supporting previews for larger breakpoints.\",\n \"Keep primary CTAs anchored within thumb reach when the flow collapses to narrow screens.\"\n ],\n \"guardrails\": [\n \"Keep the system simple, emotionally clear, and conversion-focused instead of overloaded with feature marketing.\",\n \"Make the outcome feel native, modern, and brand-specific rather than template-driven.\"\n ],\n \"antiPatterns\": [\n \"No marketing landing page hero inside onboarding.\",\n \"No overloaded feature tour before first action.\",\n \"No desktop-first shell adapted down to mobile.\",\n \"No modal maze.\"\n ],\n \"deliverables\": [\n \"Return a reusable onboarding direction that can become both a contract and an implementation-ready prototype plan.\",\n \"Define the launch tone, CTA posture, first-session empty-state behavior, and transition moments.\"\n ],\n \"route\": {\n \"profile\": \"auth-focused\",\n \"themeStrategy\": \"light-dark-parity\",\n \"navigationModel\": \"contextual\",\n \"layoutApproach\": \"stacked-mobile-flow\"\n }\n },\n {\n \"id\": \"existing-product-redesign\",\n \"label\": \"Existing product redesign from inspiration\",\n \"bestFor\": [\n \"redesigns that must keep identity\",\n \"quality upgrades without a full rebrand\",\n \"surface modernization\"\n ],\n \"businessFocus\": [\n \"existing digital products\",\n \"incremental modernization programs\",\n \"identity-preserving redesigns\",\n \"mature brands needing a quality lift\"\n ],\n \"keywords\": [\n \"redesign\",\n \"refresh\",\n \"modernize\",\n \"upgrade\",\n \"existing product\",\n \"keep identity\"\n ],\n \"matchSignals\": {\n \"positive\": [\n \"redesign\",\n \"refresh\",\n \"modernize\",\n \"upgrade\",\n \"existing product\",\n \"current product\",\n \"keep identity\",\n \"retain identity\",\n \"simplify\",\n \"amplify\"\n ],\n \"excluded\": [\n \"festival\",\n \"villa\"\n ],\n \"tieBreaker\": 1\n },\n \"lead\": \"Compare the source brief against the inspiration references and synthesize a redesign contract that upgrades the product without discarding its core identity.\",\n \"archetype\": \"incremental premium redesign\",\n \"layoutArchetype\": \"familiar shell with sharpened hierarchy and reduced ornament\",\n \"typographySystem\": \"brand-safe type refresh that raises contrast without forcing a new visual language\",\n \"surfaceTreatment\": \"existing brand DNA cleaned into brighter, calmer, more disciplined surfaces\",\n \"shapeLanguage\": \"minimal shape shifts that improve confidence without looking like a rebrand\",\n \"componentGrammar\": \"keep-versus-rebuild map across nav, hero, sections, cards, and forms\",\n \"motionGrammar\": \"subtle polish motion that signals quality rather than novelty\",\n \"paletteIntent\": \"stay inside brand memory while improving clarity, contrast, and discipline\",\n \"visualDensity\": \"balanced\",\n \"designVariance\": \"low-disruption improvement\",\n \"focusAreas\": [\n \"hierarchy\",\n \"tone\",\n \"composition\",\n \"visual confidence\",\n \"motion\",\n \"photography\",\n \"layout discipline\",\n \"what to keep\",\n \"what to remove\",\n \"what to simplify\",\n \"what to amplify\"\n ],\n \"responsiveCollapseRules\": [\n \"Preserve the core product shell while removing only the weakest supporting decoration on smaller breakpoints.\",\n \"Collapse any new premium framing before harming the known action path or navigation model.\"\n ],\n \"guardrails\": [\n \"Avoid superficial mimicry and avoid proposing a totally unrelated brand system.\",\n \"Favor the smallest coherent visual shift that creates a real quality jump.\"\n ],\n \"antiPatterns\": [\n \"No hard rebrand unless the brief explicitly asks for it.\",\n \"No novelty components that disrupt known user flows.\",\n \"No random style mixing from multiple references.\",\n \"No gratuitous animation layer.\"\n ],\n \"deliverables\": [\n \"Return a transformation plan that is specific enough to drive implementation-plan artifacts and clear enough to hand directly into Canvas.\",\n \"Explain what to keep, remove, simplify, amplify, and restyle across the core surface.\"\n ],\n \"route\": {\n \"profile\": \"clean-room\",\n \"themeStrategy\": \"single-theme\",\n \"navigationModel\": \"contextual\",\n \"layoutApproach\": \"incremental-redesign-system\"\n }\n },\n {\n \"id\": \"maison-campaign-world\",\n \"label\": \"Maison campaign world\",\n \"bestFor\": [\n \"luxury fashion\",\n \"fashion design studios\",\n \"fragrance launches\",\n \"jewelry campaigns\",\n \"premium hospitality brands\"\n ],\n \"businessFocus\": [\n \"fashion maisons\",\n \"fashion design studios\",\n \"luxury accessories\",\n \"fragrance campaigns\",\n \"high-end hospitality identity\"\n ],\n \"keywords\": [\n \"fashion\",\n \"fashion design\",\n \"fashion studio\",\n \"maison\",\n \"atelier\",\n \"collection\",\n \"season\",\n \"campaign\",\n \"couture\",\n \"fragrance\",\n \"heritage\"\n ],\n \"matchSignals\": {\n \"positive\": [\n \"fashion\",\n \"fashion design\",\n \"fashion studio\",\n \"maison\",\n \"atelier\",\n \"collection\",\n \"season\",\n \"campaign\",\n \"craft\",\n \"couture\",\n \"fragrance\",\n \"editorial\",\n \"heritage\"\n ],\n \"excluded\": [\n \"dashboard\",\n \"onboarding\",\n \"table\"\n ],\n \"tieBreaker\": 3\n },\n \"lead\": \"Study the inspiration references and synthesize a maison campaign system that feels expensive, editorial, and brand-sovereign rather than digitally generic.\",\n \"archetype\": \"luxury campaign world\",\n \"layoutArchetype\": \"poster-scale editorial spread with chaptered campaign beats\",\n \"typographySystem\": \"high-contrast serif display paired with a narrow polished grotesk support system\",\n \"surfaceTreatment\": \"bright gallery whites, deep photographic contrast, and couture-grade negative space\",\n \"shapeLanguage\": \"frame-led compositions, hairline dividers, and almost no utilitarian chrome\",\n \"componentGrammar\": \"campaign hero, chapter markers, collection highlights, quote interludes, couture CTA moments\",\n \"motionGrammar\": \"slow dissolves, image drifts, and precise text reveal pacing\",\n \"paletteIntent\": \"light editorial base with ink-black contrast and one jewel-toned accent\",\n \"visualDensity\": \"very airy\",\n \"designVariance\": \"high-fashion asymmetry\",\n \"focusAreas\": [\n \"brand mythmaking\",\n \"editorial pacing\",\n \"hero image posture\",\n \"headline scale\",\n \"collection sequencing\",\n \"proof without dashboard logic\",\n \"campaign chapter structure\"\n ],\n \"responsiveCollapseRules\": [\n \"Keep one campaign image dominant on mobile rather than shrinking a spread into multiple tiles.\",\n \"Move supporting chapter markers beneath the hero stack once the poster layout collapses.\"\n ],\n \"guardrails\": [\n \"Keep the system poised, bright, and expensive rather than dark, loud, or overtly technical.\",\n \"Treat interaction chrome as secondary to image-led composition and typographic authority.\"\n ],\n \"antiPatterns\": [\n \"No SaaS cards.\",\n \"No metric strips.\",\n \"No feature-grid hero.\",\n \"No startup copy tone.\"\n ],\n \"deliverables\": [\n \"Define the hero doctrine, chapter sequence, typography scale, photography treatment, motion cues, and CTA posture.\",\n \"Return a reusable campaign-world contract that can scale across launch, collection, and brand story surfaces.\"\n ],\n \"route\": {\n \"profile\": \"cinematic-minimal\",\n \"themeStrategy\": \"single-theme\",\n \"navigationModel\": \"immersive\",\n \"layoutApproach\": \"maison-editorial-campaign\"\n }\n },\n {\n \"id\": \"sunlit-resort-narrative\",\n \"label\": \"Sunlit resort narrative\",\n \"bestFor\": [\n \"destination resorts\",\n \"travel products\",\n \"premium real estate hospitality\",\n \"villa or stay showcases\"\n ],\n \"businessFocus\": [\n \"resort brands\",\n \"villa booking experiences\",\n \"destination marketing\",\n \"luxury stay products\"\n ],\n \"keywords\": [\n \"retreat\",\n \"stay\",\n \"villa\",\n \"destination\",\n \"itinerary\",\n \"suite\",\n \"property\",\n \"oceanview\"\n ],\n \"matchSignals\": {\n \"positive\": [\n \"retreat\",\n \"stay\",\n \"villa\",\n \"destination\",\n \"itinerary\",\n \"suite\",\n \"property\",\n \"escape\",\n \"reservation\",\n \"oceanview\"\n ],\n \"excluded\": [\n \"dashboard\",\n \"admin\",\n \"table\"\n ],\n \"tieBreaker\": 3\n },\n \"lead\": \"Work from the references to create a resort narrative system that feels sunlit, breathable, and destination-led rather than like a booking engine template.\",\n \"archetype\": \"panoramic hospitality story\",\n \"layoutArchetype\": \"panoramic media planes with story-to-booking progression\",\n \"typographySystem\": \"refined sans with lightly romantic display moments and generous line length\",\n \"surfaceTreatment\": \"warm mineral surfaces, luminous image planes, and quiet itinerary bands\",\n \"shapeLanguage\": \"soft-edged frames, map ribbons, and understated sectional dividers\",\n \"componentGrammar\": \"panorama hero, itinerary strips, amenity chapters, map moments, booking CTA band\",\n \"motionGrammar\": \"soft parallax, crossfades, and calm scroll pacing\",\n \"paletteIntent\": \"sunlit mineral neutrals with ocean or stone accents\",\n \"visualDensity\": \"airy\",\n \"designVariance\": \"serene asymmetry\",\n \"focusAreas\": [\n \"story-to-booking flow\",\n \"gallery rhythm\",\n \"map placement\",\n \"reservation CTA timing\",\n \"ambient proof moments\",\n \"quiet destination framing\"\n ],\n \"responsiveCollapseRules\": [\n \"Collapse panoramas into one priority image followed by itinerary and booking content.\",\n \"Move any map or amenity ribbons below the first booking CTA on narrow screens.\"\n ],\n \"guardrails\": [\n \"Keep the composition spacious, bright, and calm rather than dense or transactional in the first viewport.\",\n \"Use reservation moments as a payoff to the story, not as the dominant hero payload.\"\n ],\n \"antiPatterns\": [\n \"No booking-engine clutter above the fold.\",\n \"No discount language.\",\n \"No crowded comparison blocks.\",\n \"No generic travel-card mosaic.\"\n ],\n \"deliverables\": [\n \"Define the story-to-booking sequence, gallery rules, map module grammar, booking CTA cadence, and responsive image behavior.\",\n \"Return a reusable hospitality narrative contract that can support both destination storytelling and conversion.\"\n ],\n \"route\": {\n \"profile\": \"product-story\",\n \"themeStrategy\": \"single-theme\",\n \"navigationModel\": \"immersive\",\n \"layoutApproach\": \"panoramic-resort-story\"\n }\n },\n {\n \"id\": \"architecture-monograph-system\",\n \"label\": \"Architecture monograph system\",\n \"bestFor\": [\n \"architecture studios\",\n \"interior practices\",\n \"luxury real estate showcases\",\n \"industrial design portfolios\"\n ],\n \"businessFocus\": [\n \"architecture practices\",\n \"interior design studios\",\n \"monograph-style project archives\",\n \"project-led real estate showcases\"\n ],\n \"keywords\": [\n \"studio\",\n \"practice\",\n \"residence\",\n \"project archive\",\n \"monograph\",\n \"materiality\",\n \"plan\",\n \"case study\"\n ],\n \"matchSignals\": {\n \"positive\": [\n \"studio\",\n \"practice\",\n \"residence\",\n \"project archive\",\n \"monograph\",\n \"materiality\",\n \"plan\",\n \"section\",\n \"site\",\n \"case study\"\n ],\n \"excluded\": [\n \"dashboard\",\n \"activation\",\n \"festival\"\n ],\n \"tieBreaker\": 3\n },\n \"lead\": \"Study the references and define an architecture monograph system that feels rigorous, silent, and materially precise rather than market-driven.\",\n \"archetype\": \"architectural monograph\",\n \"layoutArchetype\": \"baseline-driven case-study grid with full-bleed drawing and photography pairings\",\n \"typographySystem\": \"elegant serif narrative text with mono or narrow sans captioning for plans, sections, and annotations\",\n \"surfaceTreatment\": \"paper-bright backgrounds, disciplined black rules, and full-bleed documentation plates\",\n \"shapeLanguage\": \"hard-edged framing, asymmetrical margins, and gallery-like restraint\",\n \"componentGrammar\": \"project index, drawing plate, material notes, caption rails, silent CTA treatments\",\n \"motionGrammar\": \"almost-silent motion, precise image crossfades, and subtle chapter shifts\",\n \"paletteIntent\": \"architectural neutrals with stone, graphite, and one material accent\",\n \"visualDensity\": \"measured\",\n \"designVariance\": \"controlled asymmetry\",\n \"focusAreas\": [\n \"archive index design\",\n \"case-study cadence\",\n \"plan and section treatment\",\n \"caption systems\",\n \"material cues\",\n \"image rhythm\",\n \"spacing discipline\"\n ],\n \"responsiveCollapseRules\": [\n \"Stack drawings and photography vertically before shrinking annotation legibility.\",\n \"Keep captions attached to their artifacts on mobile instead of floating them into side rails.\"\n ],\n \"guardrails\": [\n \"Keep the system rigorous, restrained, and material-first rather than promotional.\",\n \"Let drawings, plans, and photography carry authority instead of decorative interface chrome.\"\n ],\n \"antiPatterns\": [\n \"No rounded-card ecosystem.\",\n \"No playful animation.\",\n \"No marketing filler.\",\n \"No sales-led CTA dominance.\"\n ],\n \"deliverables\": [\n \"Define the archive index, case-study template, caption rules, image rhythm, and spacing discipline.\",\n \"Return a monograph-grade contract that can guide both portfolio and project-depth surfaces.\"\n ],\n \"route\": {\n \"profile\": \"clean-room\",\n \"themeStrategy\": \"single-theme\",\n \"navigationModel\": \"contextual\",\n \"layoutApproach\": \"monograph-case-study-grid\"\n }\n },\n {\n \"id\": \"luminous-research-atlas\",\n \"label\": \"Luminous insight landing page\",\n \"bestFor\": [\n \"AI labs\",\n \"think tanks\",\n \"climate or health research\",\n \"data-storytelling products\"\n ],\n \"businessFocus\": [\n \"research organizations\",\n \"evidence-led storytelling\",\n \"insight-led public landing pages\",\n \"visual research narratives\"\n ],\n \"keywords\": [\n \"atlas\",\n \"observatory\",\n \"insight\",\n \"evidence\",\n \"research\",\n \"index\",\n \"publication\"\n ],\n \"matchSignals\": {\n \"positive\": [\n \"atlas\",\n \"observatory\",\n \"insight\",\n \"evidence\",\n \"research\",\n \"map\",\n \"model\",\n \"index\",\n \"publication\"\n ],\n \"excluded\": [\n \"checkout\",\n \"festival\",\n \"villa\",\n \"consulting\",\n \"advisory\",\n \"bcg\",\n \"services\",\n \"landing page\",\n \"homepage\"\n ],\n \"tieBreaker\": 1\n },\n \"lead\": \"Study the inspiration references and synthesize a luminous insight landing page that turns research-backed ideas into a premium, text-light public story.\",\n \"archetype\": \"luminous insight landing page\",\n \"layoutArchetype\": \"full-bleed insight story with visual proof bands\",\n \"typographySystem\": \"precise sans for data and narrative paired with restrained serif emphasis\",\n \"surfaceTreatment\": \"ivory research planes, layered evidence visuals, and generous image-led whitespace\",\n \"shapeLanguage\": \"clean modules, visual proof frames, and quiet emphasis bands\",\n \"componentGrammar\": \"hero composition, insight proof bands, visual story panels, outcome moments, restrained CTA groups\",\n \"motionGrammar\": \"calm reveal transitions, proof-panel emphasis, and restrained visual depth\",\n \"paletteIntent\": \"bright ivory base with measured accent coding for evidence groups\",\n \"visualDensity\": \"balanced\",\n \"designVariance\": \"structured expressiveness\",\n \"focusAreas\": [\n \"evidence hierarchy\",\n \"insight framing\",\n \"visual proof bands\",\n \"chart restraint\",\n \"public story cadence\",\n \"scroll-story beats\",\n \"proof sequencing\"\n ],\n \"responsiveCollapseRules\": [\n \"Collapse visual proof bands into a single readable story stack before reducing chart legibility.\",\n \"Keep evidence labels visually close to the relevant section without turning mobile into an appendix.\"\n ],\n \"guardrails\": [\n \"Keep the surface bright, exact, and evidence-led without becoming a documentation hub.\",\n \"Use motion to clarify priority, proof, and action rather than to explain long-form methodology.\"\n ],\n \"antiPatterns\": [\n \"No cyber glow.\",\n \"No dashboard clutter.\",\n \"No decorative charts.\",\n \"No unexplained iconography.\"\n ],\n \"deliverables\": [\n \"Define the evidence hierarchy, visual proof rhythm, insight story cadence, and conversion path.\",\n \"Return a premium insight landing contract detailed enough for a visually led Canvas-ready implementation.\"\n ],\n \"route\": {\n \"profile\": \"product-story\",\n \"themeStrategy\": \"single-theme\",\n \"navigationModel\": \"global-header\",\n \"layoutApproach\": \"insight-led-landing-page\"\n }\n },\n {\n \"id\": \"private-wealth-salon\",\n \"label\": \"Private wealth salon\",\n \"bestFor\": [\n \"private banking\",\n \"wealth platforms\",\n \"family office software\",\n \"premium fintech\"\n ],\n \"businessFocus\": [\n \"private client finance\",\n \"wealth intelligence products\",\n \"family office tools\",\n \"advisor-facing premium fintech\"\n ],\n \"keywords\": [\n \"wealth\",\n \"capital\",\n \"portfolio\",\n \"treasury\",\n \"allocation\",\n \"advisor\",\n \"estate\",\n \"reporting\"\n ],\n \"matchSignals\": {\n \"positive\": [\n \"wealth\",\n \"capital\",\n \"portfolio\",\n \"treasury\",\n \"allocation\",\n \"advisor\",\n \"private client\",\n \"estate\",\n \"intelligence\",\n \"reporting\"\n ],\n \"excluded\": [\n \"crypto\",\n \"token\",\n \"festival\"\n ],\n \"tieBreaker\": 3\n },\n \"lead\": \"Work from the references to synthesize a private wealth system that feels like a discreet salon rather than a retail fintech dashboard.\",\n \"archetype\": \"salon-grade trust interface\",\n \"layoutArchetype\": \"split-panel trust sequence with couture data previews and service-led sections\",\n \"typographySystem\": \"tall high-contrast headlines with polished sans detail and refined numeric styling\",\n \"surfaceTreatment\": \"warm neutral surfaces, quiet paper textures, and disciplined premium separators\",\n \"shapeLanguage\": \"framed content rooms, quiet tab rails, and couture table spacing\",\n \"componentGrammar\": \"trust hero, portfolio preview, advisor modules, secure access moments, service panels\",\n \"motionGrammar\": \"restrained hover microphysics and dignified panel continuity\",\n \"paletteIntent\": \"warm neutrals, muted metallic accents, and calm signal colors\",\n \"visualDensity\": \"measured\",\n \"designVariance\": \"low-noise luxury\",\n \"focusAreas\": [\n \"trust architecture\",\n \"advisor touchpoints\",\n \"portfolio preview hierarchy\",\n \"secure entry tone\",\n \"service-led proof\",\n \"numeric typography discipline\"\n ],\n \"responsiveCollapseRules\": [\n \"Collapse split salons into a single guided trust sequence before compressing numeric previews.\",\n \"Keep the secure action path and advisor contact moment visible without crowding the first viewport.\"\n ],\n \"guardrails\": [\n \"Keep the system discreet, bright, and high-confidence instead of aggressive or hype-driven.\",\n \"Treat data previews as crafted typography and spacing problems, not as loud KPI tiles.\"\n ],\n \"antiPatterns\": [\n \"No crypto aesthetic.\",\n \"No KPI tile wall.\",\n \"No loud B2B dashboard chrome.\",\n \"No neon or dark-trading UI posture.\"\n ],\n \"deliverables\": [\n \"Define the trust architecture, data-preview modules, advisor touchpoints, secure entry tone, and motion restraint rules.\",\n \"Return a reusable private-wealth contract that can guide both marketing and authenticated advisory surfaces.\"\n ],\n \"route\": {\n \"profile\": \"clean-room\",\n \"themeStrategy\": \"single-theme\",\n \"navigationModel\": \"contextual\",\n \"layoutApproach\": \"salon-trust-panels\"\n }\n },\n {\n \"id\": \"cultural-festival-atlas\",\n \"label\": \"Cultural festival atlas\",\n \"bestFor\": [\n \"biennales\",\n \"art fairs\",\n \"music festivals\",\n \"design weeks\",\n \"premium conferences\"\n ],\n \"businessFocus\": [\n \"festival identity systems\",\n \"program-driven event surfaces\",\n \"cultural institutions\",\n \"multi-venue schedule products\"\n ],\n \"keywords\": [\n \"edition\",\n \"lineup\",\n \"program\",\n \"venue\",\n \"exhibition\",\n \"passes\",\n \"festival\",\n \"screening\"\n ],\n \"matchSignals\": {\n \"positive\": [\n \"edition\",\n \"lineup\",\n \"program\",\n \"venue\",\n \"exhibition\",\n \"passes\",\n \"festival\",\n \"talks\",\n \"screening\",\n \"schedule\"\n ],\n \"excluded\": [\n \"dashboard\",\n \"billing\",\n \"checkout\"\n ],\n \"tieBreaker\": 3\n },\n \"lead\": \"Study the references and define a cultural festival atlas that feels poster-led, kinetic, and editorial rather than like a corporate event microsite.\",\n \"archetype\": \"poster-grid program atlas\",\n \"layoutArchetype\": \"chaptered program sequence with wayfinding color blocks and event-driven typographic beats\",\n \"typographySystem\": \"expressive variable type paired with a sober schedule support face\",\n \"surfaceTreatment\": \"bright poster fields, color-block navigation, and layered program markers\",\n \"shapeLanguage\": \"poster frames, directional bars, stacked ribbons, and event tags\",\n \"componentGrammar\": \"edition hero, lineup atlas, schedule chapters, venue maps, ticket pathways\",\n \"motionGrammar\": \"kinetic type bands, chapter transitions, and route-aware section motion\",\n \"paletteIntent\": \"bright thematic palette system with venue or category coding\",\n \"visualDensity\": \"high but legible\",\n \"designVariance\": \"high-expression systems\",\n \"focusAreas\": [\n \"identity system\",\n \"schedule grammar\",\n \"venue map modules\",\n \"ticket CTA logic\",\n \"wayfinding hierarchy\",\n \"program chaptering\"\n ],\n \"responsiveCollapseRules\": [\n \"Reduce poster-grid complexity to a clean event list plus prominent schedule filters on mobile.\",\n \"Keep venue maps and ticket actions in the same narrative lane once space becomes limited.\"\n ],\n \"guardrails\": [\n \"Keep the direction cultural, expressive, and controlled rather than generic corporate-conference UI.\",\n \"Let typography and wayfinding structure create the energy before adding decorative media.\"\n ],\n \"antiPatterns\": [\n \"No corporate conference template.\",\n \"No equal-width card grids.\",\n \"No dead spreadsheet agenda hero.\",\n \"No low-energy generic icon rows.\"\n ],\n \"deliverables\": [\n \"Define the identity system, schedule grammar, venue map modules, ticket CTA logic, and motion choreography.\",\n \"Return a reusable festival contract that can cover edition landing, lineup, program, and pass-conversion surfaces.\"\n ],\n \"route\": {\n \"profile\": \"cinematic-minimal\",\n \"themeStrategy\": \"multi-theme-system\",\n \"navigationModel\": \"immersive\",\n \"layoutApproach\": \"poster-program-sequence\"\n }\n },\n {\n \"id\": \"wellness-ritual-system\",\n \"label\": \"Wellness ritual system\",\n \"bestFor\": [\n \"beauty\",\n \"skincare\",\n \"clinics\",\n \"premium wellness apps\",\n \"recovery products\"\n ],\n \"businessFocus\": [\n \"wellness programs\",\n \"skincare systems\",\n \"beauty rituals\",\n \"recovery and clinic products\"\n ],\n \"keywords\": [\n \"ritual\",\n \"treatment\",\n \"glow\",\n \"routine\",\n \"recovery\",\n \"clinic\",\n \"ingredient\",\n \"reset\"\n ],\n \"matchSignals\": {\n \"positive\": [\n \"ritual\",\n \"treatment\",\n \"glow\",\n \"routine\",\n \"recovery\",\n \"clinic\",\n \"session\",\n \"ingredient\",\n \"skin\",\n \"reset\"\n ],\n \"excluded\": [\n \"dashboard\",\n \"table\",\n \"festival\"\n ],\n \"tieBreaker\": 3\n },\n \"lead\": \"Study the references and synthesize a wellness ritual system that feels luminous, calm, and premium without collapsing into stock spa cliches.\",\n \"archetype\": \"ritual-led wellness story\",\n \"layoutArchetype\": \"porcelain chapter flow with ritual steps, proof surfaces, and booking or activation moments\",\n \"typographySystem\": \"soft modern serif accents over highly legible sans narrative copy\",\n \"surfaceTreatment\": \"porcelain surfaces, mineral gradients, translucent layers, and macro texture photography\",\n \"shapeLanguage\": \"gentle curves, rounded panels, and flowing sectional transitions\",\n \"componentGrammar\": \"ritual hero, routine modules, ingredient proof surfaces, booking moments, calm testimonials\",\n \"motionGrammar\": \"breathing rhythm, gentle float motion, and calm confirmation transitions\",\n \"paletteIntent\": \"bright mineral palette with skin-safe neutrals and one clean accent\",\n \"visualDensity\": \"airy\",\n \"designVariance\": \"soft continuity\",\n \"focusAreas\": [\n \"ritual flow modules\",\n \"ingredient and proof surfaces\",\n \"booking posture\",\n \"first-session tone\",\n \"wellness trust cues\",\n \"motion breathing rules\"\n ],\n \"responsiveCollapseRules\": [\n \"Stack ritual steps vertically before shrinking proof imagery or ingredient legibility.\",\n \"Keep booking or activation moments separated from storytelling content on narrow screens.\"\n ],\n \"guardrails\": [\n \"Keep the system bright, thematic, and premium rather than washed-out, decorative, or medicalized.\",\n \"Use motion to reinforce calm confidence, not to create soft-focus vagueness.\"\n ],\n \"antiPatterns\": [\n \"No stock-spa cliches.\",\n \"No pseudo-medical dashboard.\",\n \"No oversaturated gradient fog.\",\n \"No generic beauty ecommerce grid.\"\n ],\n \"deliverables\": [\n \"Define the ritual flow modules, ingredient and proof surfaces, booking moments, first-session tone, and motion breathing rules.\",\n \"Return a reusable wellness contract for product, clinic, and app activation surfaces.\"\n ],\n \"route\": {\n \"profile\": \"product-story\",\n \"themeStrategy\": \"single-theme\",\n \"navigationModel\": \"global-header\",\n \"layoutApproach\": \"ritual-story-flow\"\n }\n },\n {\n \"id\": \"creative-tool-laboratory\",\n \"label\": \"Creative tool laboratory\",\n \"bestFor\": [\n \"design tools\",\n \"AI builders\",\n \"devtools with premium brand positioning\",\n \"creative software\"\n ],\n \"businessFocus\": [\n \"creative software\",\n \"builder platforms\",\n \"design tooling\",\n \"AI-assisted creation products\"\n ],\n \"keywords\": [\n \"canvas\",\n \"lab\",\n \"studio\",\n \"editor\",\n \"compose\",\n \"prototype\",\n \"generate\",\n \"workspace\",\n \"toolkit\",\n \"layer\"\n ],\n \"matchSignals\": {\n \"positive\": [\n \"canvas\",\n \"lab\",\n \"studio\",\n \"editor\",\n \"compose\",\n \"prototype\",\n \"generate\",\n \"workspace\",\n \"toolkit\",\n \"layer\"\n ],\n \"excluded\": [\n \"villa\",\n \"festival\",\n \"fragrance\",\n \"fashion\",\n \"fashion design\",\n \"maison\",\n \"couture\",\n \"collection\",\n \"campaign\"\n ],\n \"tieBreaker\": 3\n },\n \"lead\": \"Use the references to create a creative tool laboratory direction that feels precise, bright, and premium without falling back to generic admin shells.\",\n \"archetype\": \"specimen-grade creative workspace\",\n \"layoutArchetype\": \"bright laboratory shell with stage, inspector, and specimen panels\",\n \"typographySystem\": \"sharp grotesk UI type with monospaced support for tokens, coordinates, and diagnostics\",\n \"surfaceTreatment\": \"lab-white shell, modular trays, and layered canvas previews\",\n \"shapeLanguage\": \"modular docks, specimen cards, inspector rails, and crisp separators\",\n \"componentGrammar\": \"stage shell, inspector, prompt panels, specimen modules, stateful controls\",\n \"motionGrammar\": \"state continuity, transform-led panel transitions, and specimen emphasis motion\",\n \"paletteIntent\": \"bright lab whites with one vivid tool accent and disciplined neutral scaffolding\",\n \"visualDensity\": \"balanced to dense\",\n \"designVariance\": \"structured experimentation\",\n \"focusAreas\": [\n \"shell grammar\",\n \"sidebar and inspector rules\",\n \"stage hierarchy\",\n \"specimen component set\",\n \"transition map\",\n \"tool-state communication\"\n ],\n \"responsiveCollapseRules\": [\n \"Collapse the inspector after the stage and primary controls are stable on smaller breakpoints.\",\n \"Keep prompt input and primary creation actions in a fixed vertical lane on narrow screens.\"\n ],\n \"guardrails\": [\n \"Keep the workspace premium and bright, not dark-gamer or gadget-heavy.\",\n \"Make motion serve state continuity and tool confidence, not generic micro-animation noise.\"\n ],\n \"antiPatterns\": [\n \"No gamer neon.\",\n \"No floating-window chaos.\",\n \"No generic admin shell.\",\n \"No decorative empty-state illustration that hides the tool's real structure.\"\n ],\n \"deliverables\": [\n \"Define the shell grammar, sidebar and inspector rules, stage hierarchy, specimen component set, and transition map.\",\n \"Return a reusable creative-tool contract that can drive both the marketing frame and the actual product shell.\"\n ],\n \"route\": {\n \"profile\": \"control-room\",\n \"themeStrategy\": \"single-theme\",\n \"navigationModel\": \"contextual\",\n \"layoutApproach\": \"specimen-workspace\"\n }\n },\n {\n \"id\": \"precision-mobility-flagship\",\n \"label\": \"Precision mobility flagship\",\n \"bestFor\": [\n \"automotive\",\n \"aviation\",\n \"robotics\",\n \"micromobility\",\n \"transport hardware\"\n ],\n \"businessFocus\": [\n \"vehicle launches\",\n \"mobility hardware\",\n \"robotic systems\",\n \"engineering-led transport brands\"\n ],\n \"keywords\": [\n \"cockpit\",\n \"range\",\n \"chassis\",\n \"drive\",\n \"vehicle\",\n \"engineering\",\n \"autonomous\",\n \"aero\"\n ],\n \"matchSignals\": {\n \"positive\": [\n \"cockpit\",\n \"range\",\n \"chassis\",\n \"drive\",\n \"vehicle\",\n \"engineering\",\n \"autonomous\",\n \"performance\",\n \"aero\",\n \"machine\"\n ],\n \"excluded\": [\n \"dashboard\",\n \"festival\",\n \"onboarding\"\n ],\n \"tieBreaker\": 3\n },\n \"lead\": \"Study the references and define a precision mobility flagship that feels engineered, aerodynamic, and premium without becoming a spec dump or dealer template.\",\n \"archetype\": \"engineering-led flagship story\",\n \"layoutArchetype\": \"panoramic launch composition with sectional proof reveals and cockpit framing\",\n \"typographySystem\": \"condensed display typography with technical mono or narrow sans support\",\n \"surfaceTreatment\": \"bright or graphite technical planes, cutaway diagrams, and controlled highlight lines\",\n \"shapeLanguage\": \"aerodynamic bands, sectional overlays, and instrument-inspired detail modules\",\n \"componentGrammar\": \"flagship hero, technical proof rail, sectional cutaways, performance figures, CTA close\",\n \"motionGrammar\": \"glide motion, instrument-style reveals, and controlled engineering emphasis\",\n \"paletteIntent\": \"precision neutrals with one performance accent and disciplined contrast\",\n \"visualDensity\": \"measured technical density\",\n \"designVariance\": \"high-control precision\",\n \"focusAreas\": [\n \"launch storyboard\",\n \"technical proof modules\",\n \"performance-data styling\",\n \"cutaway treatment\",\n \"CTA sequence\",\n \"motion timing\"\n ],\n \"responsiveCollapseRules\": [\n \"Turn sectional cutaways into stacked proof chapters before sacrificing diagram clarity.\",\n \"Keep the primary performance and CTA story lane intact on mobile rather than distributing it across tabs or accordions.\"\n ],\n \"guardrails\": [\n \"Keep the system premium, exact, and flagship-oriented rather than automotive commerce or gadget marketing.\",\n \"Let engineering proof emerge in sequence instead of dumping all specifications at once.\"\n ],\n \"antiPatterns\": [\n \"No ecommerce spec dump.\",\n \"No dealer-site layout.\",\n \"No cluttered comparison tables above the fold.\",\n \"No generic performance stat tiles.\"\n ],\n \"deliverables\": [\n \"Define the launch storyboard, technical proof modules, performance-data styling, CTA sequence, and motion timing.\",\n \"Return a reusable flagship contract for mobility, robotics, and engineering-led hardware launches.\"\n ],\n \"route\": {\n \"profile\": \"cinematic-minimal\",\n \"themeStrategy\": \"single-theme\",\n \"navigationModel\": \"immersive\",\n \"layoutApproach\": \"engineering-glide-story\"\n }\n },\n {\n \"id\": \"members-club-concierge\",\n \"label\": \"Members club concierge\",\n \"bestFor\": [\n \"invite-only communities\",\n \"premium memberships\",\n \"concierge products\",\n \"executive networks\"\n ],\n \"businessFocus\": [\n \"membership programs\",\n \"concierge services\",\n \"executive communities\",\n \"invite-only access products\"\n ],\n \"keywords\": [\n \"members\",\n \"access\",\n \"club\",\n \"concierge\",\n \"curation\",\n \"invite\",\n \"tier\",\n \"privileges\"\n ],\n \"matchSignals\": {\n \"positive\": [\n \"members\",\n \"access\",\n \"club\",\n \"concierge\",\n \"curation\",\n \"invite\",\n \"tier\",\n \"private\",\n \"privileges\",\n \"network\"\n ],\n \"excluded\": [\n \"dashboard\",\n \"checkout\",\n \"festival\"\n ],\n \"tieBreaker\": 3\n },\n \"lead\": \"Use the references to synthesize a members-club concierge system that feels stately, selective, and service-led rather than like a benefits comparison page.\",\n \"archetype\": \"private members salon\",\n \"layoutArchetype\": \"invitation-led room sequence with framed service modules and access moments\",\n \"typographySystem\": \"stately serif headlines with polished sans navigation and membership detail copy\",\n \"surfaceTreatment\": \"bright club rooms, invitation cards, schedule ribbons, and warm premium materials\",\n \"shapeLanguage\": \"framed rooms, invitation panels, ribbon markers, and curated content compartments\",\n \"componentGrammar\": \"invitation hero, tier narrative, concierge request modules, schedule ribbons, social proof rooms\",\n \"motionGrammar\": \"subtle reveal, magnetic hover restraint, and service-led transition pacing\",\n \"paletteIntent\": \"bright cream or stone base with restrained metallic and club-accent notes\",\n \"visualDensity\": \"balanced\",\n \"designVariance\": \"curated composure\",\n \"focusAreas\": [\n \"access narrative\",\n \"membership architecture\",\n \"concierge request surfaces\",\n \"proof and testimonial format\",\n \"schedule ribbons\",\n \"spacing and motion contract\"\n ],\n \"responsiveCollapseRules\": [\n \"Collapse framed rooms into a guided membership sequence before compressing the access narrative.\",\n \"Keep the invitation and concierge request moment within the same mobile lane.\"\n ],\n \"guardrails\": [\n \"Keep the direction stately, bright, and selective rather than flashy or social-feed oriented.\",\n \"Use privilege and service cues with discipline so the surface still feels curated and elegant.\"\n ],\n \"antiPatterns\": [\n \"No coupon language.\",\n \"No social-feed feeling.\",\n \"No generic benefit-card grid.\",\n \"No noisy badge wall.\"\n ],\n \"deliverables\": [\n \"Define the access narrative, membership architecture, concierge request surfaces, proof format, and spacing plus motion contract.\",\n \"Return a reusable members-club contract for private access, service, and executive-network surfaces.\"\n ],\n \"route\": {\n \"profile\": \"product-story\",\n \"themeStrategy\": \"single-theme\",\n \"navigationModel\": \"global-header\",\n \"layoutApproach\": \"concierge-room-sequence\"\n }\n }\n ]\n}\n","import type {\n CanvasNavigationModel,\n CanvasThemeStrategy,\n CanvasVisualDirectionProfile\n} from \"../canvas/types\";\nimport templateJson from \"../../skills/opendevbrowser-design-agent/assets/templates/inspiredesign-advanced-brief.v1.json\";\n\ntype InspiredesignBriefMatchSignals = {\n positive: string[];\n required?: string[];\n excluded?: string[];\n tieBreaker?: number;\n};\n\ntype InspiredesignBriefFormatRoute = {\n profile: CanvasVisualDirectionProfile;\n themeStrategy: CanvasThemeStrategy;\n navigationModel: CanvasNavigationModel;\n layoutApproach: string;\n};\n\ntype InspiredesignBriefFormatTemplate = {\n id: string;\n label: string;\n bestFor: string[];\n businessFocus: string[];\n keywords: string[];\n matchSignals: InspiredesignBriefMatchSignals;\n lead: string;\n archetype: string;\n layoutArchetype: string;\n typographySystem: string;\n surfaceTreatment: string;\n shapeLanguage: string;\n componentGrammar: string;\n motionGrammar: string;\n paletteIntent: string;\n visualDensity: string;\n designVariance: string;\n focusAreas: string[];\n responsiveCollapseRules: string[];\n guardrails: string[];\n antiPatterns: string[];\n deliverables: string[];\n route: InspiredesignBriefFormatRoute;\n};\n\ntype InspiredesignBriefTemplate = {\n version: string;\n defaultFormatId: string;\n commonRules: string[];\n outputRequirements: string[];\n formats: InspiredesignBriefFormatTemplate[];\n};\n\nexport type InspiredesignBriefFormat = {\n id: string;\n label: string;\n bestFor: string[];\n businessFocus: string[];\n keywords: string[];\n archetype: string;\n layoutArchetype: string;\n typographySystem: string;\n surfaceTreatment: string;\n shapeLanguage: string;\n componentGrammar: string;\n motionGrammar: string;\n paletteIntent: string;\n visualDensity: string;\n designVariance: string;\n focusAreas?: string[];\n responsiveCollapseRules: string[];\n guardrails: string[];\n antiPatterns: string[];\n deliverables: string[];\n route: InspiredesignBriefFormatRoute;\n};\n\nexport type InspiredesignBriefExpansion = {\n sourceBrief: string;\n advancedBrief: string;\n templateVersion: string;\n format: InspiredesignBriefFormat;\n};\n\nconst BRIEF_TEMPLATE = templateJson as InspiredesignBriefTemplate;\nexport const INSPIREDESIGN_BRIEF_TEMPLATE_VERSION = BRIEF_TEMPLATE.version;\nexport const INSPIREDESIGN_BRIEF_COMMON_RULES = [...BRIEF_TEMPLATE.commonRules];\nexport const INSPIREDESIGN_BRIEF_OUTPUT_REQUIREMENTS = [...BRIEF_TEMPLATE.outputRequirements];\n\nexport const normalizeInspiredesignBriefText = (value: string): string => value.trim().replace(/\\s+/g, \" \");\n\nconst formatBulletList = (items: readonly string[]): string => items.map((item) => `- ${item}`).join(\"\\n\");\n\nconst countMatches = (brief: string, keywords: readonly string[]): number => {\n const haystack = brief.toLowerCase();\n return keywords.reduce(\n (total, keyword) => total + (haystack.includes(keyword.toLowerCase()) ? 1 : 0),\n 0\n );\n};\n\nconst escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\nconst removeNegativeSignal = (brief: string, keyword: string): string => {\n const escaped = escapeRegExp(keyword.toLowerCase());\n const modifiers = \"(?:[a-z0-9-]+\\\\s+){0,3}\";\n return brief\n .replace(new RegExp(`\\\\b(?:not|no|without|avoid|exclude|excluding)\\\\s+(?:an?\\\\s+|the\\\\s+)?${modifiers}${escaped}\\\\b(?:\\\\s+[a-z0-9-]+){0,2}`, \"g\"), \" \")\n .replace(new RegExp(`\\\\b${escaped}\\\\s+(?:is\\\\s+)?(?:not|excluded|forbidden)\\\\b`, \"g\"), \" \");\n};\n\nconst positiveSignalText = (brief: string, formats: readonly InspiredesignBriefFormatTemplate[]): string => {\n const keywords = formats.flatMap((format) => [\n ...format.matchSignals.positive,\n ...(format.matchSignals.required ?? []),\n ...(format.matchSignals.excluded ?? [])\n ]);\n return [...new Set(keywords)].reduce(removeNegativeSignal, brief.toLowerCase());\n};\n\nconst cloneStringList = (items: readonly string[]): string[] => [...items];\n\nconst cloneRoute = (route: InspiredesignBriefFormatRoute): InspiredesignBriefFormatRoute => ({\n profile: route.profile,\n themeStrategy: route.themeStrategy,\n navigationModel: route.navigationModel,\n layoutApproach: route.layoutApproach\n});\n\nexport const cloneInspiredesignBriefFormat = (\n format: InspiredesignBriefFormat\n): InspiredesignBriefFormat => ({\n id: format.id,\n label: format.label,\n bestFor: cloneStringList(format.bestFor),\n businessFocus: cloneStringList(format.businessFocus),\n keywords: cloneStringList(format.keywords),\n archetype: format.archetype,\n layoutArchetype: format.layoutArchetype,\n typographySystem: format.typographySystem,\n surfaceTreatment: format.surfaceTreatment,\n shapeLanguage: format.shapeLanguage,\n componentGrammar: format.componentGrammar,\n motionGrammar: format.motionGrammar,\n paletteIntent: format.paletteIntent,\n visualDensity: format.visualDensity,\n designVariance: format.designVariance,\n focusAreas: cloneStringList(format.focusAreas ?? []),\n responsiveCollapseRules: cloneStringList(format.responsiveCollapseRules),\n guardrails: cloneStringList(format.guardrails),\n antiPatterns: cloneStringList(format.antiPatterns),\n deliverables: cloneStringList(format.deliverables),\n route: cloneRoute(format.route)\n});\n\nconst summarizeFormat = (format: InspiredesignBriefFormatTemplate): InspiredesignBriefFormat => ({\n id: format.id,\n label: format.label,\n bestFor: cloneStringList(format.bestFor),\n businessFocus: cloneStringList(format.businessFocus),\n keywords: cloneStringList(format.keywords),\n archetype: format.archetype,\n layoutArchetype: format.layoutArchetype,\n typographySystem: format.typographySystem,\n surfaceTreatment: format.surfaceTreatment,\n shapeLanguage: format.shapeLanguage,\n componentGrammar: format.componentGrammar,\n motionGrammar: format.motionGrammar,\n paletteIntent: format.paletteIntent,\n visualDensity: format.visualDensity,\n designVariance: format.designVariance,\n focusAreas: cloneStringList(format.focusAreas),\n responsiveCollapseRules: cloneStringList(format.responsiveCollapseRules),\n guardrails: cloneStringList(format.guardrails),\n antiPatterns: cloneStringList(format.antiPatterns),\n deliverables: cloneStringList(format.deliverables),\n route: cloneRoute(format.route)\n});\n\nconst getDefaultFormat = (): InspiredesignBriefFormatTemplate => {\n const defaultFormat = BRIEF_TEMPLATE.formats.find((format) => format.id === BRIEF_TEMPLATE.defaultFormatId)\n ?? BRIEF_TEMPLATE.formats[0];\n if (!defaultFormat) {\n throw new Error(\"Inspiredesign brief template must define at least one format.\");\n }\n return defaultFormat;\n};\n\nconst findFormatById = (\n formatId: string | undefined\n): InspiredesignBriefFormatTemplate | undefined => {\n if (!formatId) {\n return undefined;\n }\n return BRIEF_TEMPLATE.formats.find((format) => format.id === formatId);\n};\n\nconst scoreFormat = (sourceBrief: string, format: InspiredesignBriefFormatTemplate): number => {\n const brief = positiveSignalText(sourceBrief, BRIEF_TEMPLATE.formats);\n const requiredMatches = countMatches(brief, format.matchSignals.required ?? []);\n if ((format.matchSignals.required?.length ?? 0) > 0 && requiredMatches === 0) {\n return Number.NEGATIVE_INFINITY;\n }\n const excludedMatches = countMatches(brief, format.matchSignals.excluded ?? []);\n const positiveMatches = countMatches(brief, format.matchSignals.positive);\n return (positiveMatches * 4)\n + (requiredMatches * 6)\n - (excludedMatches * 8)\n + (format.matchSignals.tieBreaker ?? 0);\n};\n\nconst chooseFormat = (sourceBrief: string): InspiredesignBriefFormatTemplate => {\n const defaultFormat = getDefaultFormat();\n const seeded = {\n score: scoreFormat(sourceBrief, defaultFormat) + 0.5,\n format: defaultFormat\n };\n return BRIEF_TEMPLATE.formats.reduce((best, format) => {\n const score = scoreFormat(sourceBrief, format);\n return score > best.score ? { score, format } : best;\n }, seeded).format;\n};\n\nconst resolveFormat = (\n sourceBrief: string,\n preferredFormatId: string | undefined\n): InspiredesignBriefFormatTemplate => {\n const preferredFormat = findFormatById(preferredFormatId);\n if (preferredFormat) {\n return preferredFormat;\n }\n return chooseFormat(sourceBrief);\n};\n\nconst buildReturnRequirements = (format: InspiredesignBriefFormatTemplate): string[] => (\n [...new Set([...format.deliverables, ...BRIEF_TEMPLATE.outputRequirements])]\n);\n\nconst buildRouteDefaults = (format: InspiredesignBriefFormatTemplate): string[] => ([\n `profile: ${format.route.profile}`,\n `theme strategy: ${format.route.themeStrategy}`,\n `navigation model: ${format.route.navigationModel}`,\n `layout approach: ${format.route.layoutApproach}`\n]);\n\nconst buildDesignDirection = (format: InspiredesignBriefFormatTemplate): string[] => ([\n `archetype: ${format.archetype}`,\n `layout archetype: ${format.layoutArchetype}`,\n `typography system: ${format.typographySystem}`,\n `surface treatment: ${format.surfaceTreatment}`,\n `shape language: ${format.shapeLanguage}`,\n `component grammar: ${format.componentGrammar}`,\n `motion grammar: ${format.motionGrammar}`,\n `palette intent: ${format.paletteIntent}`,\n `visual density: ${format.visualDensity}`,\n `design variance: ${format.designVariance}`\n]);\n\nconst renderAdvancedBrief = (\n sourceBrief: string,\n format: InspiredesignBriefFormatTemplate\n): string => [\n `Selected prompt format: ${format.label}`,\n \"\",\n \"Source brief:\",\n sourceBrief,\n \"\",\n \"Prompt objective:\",\n format.lead,\n \"\",\n \"Business focus:\",\n formatBulletList(format.businessFocus),\n \"\",\n \"Keywords:\",\n formatBulletList(format.keywords),\n \"\",\n \"Route defaults:\",\n formatBulletList(buildRouteDefaults(format)),\n \"\",\n \"Design direction:\",\n formatBulletList(buildDesignDirection(format)),\n \"\",\n \"Focus areas:\",\n formatBulletList(format.focusAreas),\n \"\",\n \"Responsive collapse rules:\",\n formatBulletList(format.responsiveCollapseRules),\n \"\",\n \"Execution rules:\",\n formatBulletList([...BRIEF_TEMPLATE.commonRules, ...format.guardrails]),\n \"\",\n \"Anti-patterns:\",\n formatBulletList(format.antiPatterns),\n \"\",\n \"Return:\",\n formatBulletList(buildReturnRequirements(format)),\n \"\",\n \"Best fit use cases:\",\n formatBulletList(format.bestFor)\n].join(\"\\n\");\n\nexport const expandInspiredesignBrief = (\n brief: string,\n preferredFormatId?: string\n): InspiredesignBriefExpansion => {\n const sourceBrief = normalizeInspiredesignBriefText(brief);\n const format = resolveFormat(sourceBrief, preferredFormatId);\n return {\n sourceBrief,\n advancedBrief: renderAdvancedBrief(sourceBrief, format),\n templateVersion: INSPIREDESIGN_BRIEF_TEMPLATE_VERSION,\n format: summarizeFormat(format)\n };\n};\n","import type { NextStepGuidance, SiteRecipe, SiteRecipeReferenceCandidate } from \"../types\";\n\nconst pinterestGuidance: NextStepGuidance = {\n id: \"inspiredesign.harvest.browser_native_site_search.pinterest\",\n recipeType: \"site_navigation\",\n workflow: \"inspiredesign\",\n severity: \"warning\",\n readiness: \"needs_recovery\",\n reasonCode: \"pinterest_browser_native_recovery\",\n primaryAction: {\n id: \"pinterest_browser_native_discovery\",\n label: \"Use Pinterest browser-native discovery\",\n summary: \"Use a user-authorized signed-in Pinterest browser session when required, search Pinterest naturally, collect visual pins or boards, and reject full login walls, challenges, empty grids, and search-shell pages.\"\n },\n commands: [{\n id: \"pinterest-authenticated-harvest\",\n label: \"Run an authenticated Pinterest harvest\",\n command: \"npx opendevbrowser inspiredesign harvest --brief \\\"Digital photography studio landing page\\\" --query \\\"cinematic photography studio landing page inspiration\\\" --provider social/pinterest --max-references 5 --visual-evidence required --browser-mode extension --use-cookies --cookie-policy required --challenge-automation-mode browser_with_helper --mode json --output-format json\"\n }],\n paramsExamples: [{\n id: \"pinterest-harvest-input\",\n label: \"Pinterest discovery input\",\n params: {\n provider: \"social/pinterest\",\n browserMode: \"extension\",\n useCookies: true,\n cookiePolicy: \"required\",\n visualEvidence: \"required\"\n }\n }],\n fieldExamples: [],\n artifactInputs: [\n { path: \"ranked-references.json\", purpose: \"Confirm accepted URLs are pins, boards, or idea pages with actual visual grids.\", required: true },\n { path: \"visual-evidence.json\", purpose: \"Reject login, challenge, empty-grid, and search-shell screenshots.\", required: true }\n ],\n validationChecks: [\n { id: \"pinterest-hosts\", description: \"Accepted URLs stay on Pinterest hosts.\", assertion: \"acceptedUrls.every(url => { const host = new URL(url).hostname; return host === \\\"pinterest.com\\\" || host.endsWith(\\\".pinterest.com\\\"); })\" },\n { id: \"pinterest-visual-grid\", description: \"Screenshots show usable visual grids, pins, boards, or idea pages, not blocked UI.\" }\n ],\n fallbackPolicy: {\n allowed: false,\n requiresUserConfirmation: true,\n reason: \"Do not switch a Pinterest-scoped request to unrelated web providers without user confirmation.\"\n },\n doNotProceedIf: [\n \"Pinterest is logged out when cookies are required or protected by a challenge\",\n \"The signed-in Pinterest session was not explicitly authorized by the user\",\n \"Captured page is only a search shell, login wall, or empty grid\",\n \"No ranked Pinterest references remain after scoring\"\n ]\n};\n\nconst PINTEREST_PIN_ID_PATTERN = /^\\d+$/;\nconst RESERVED_PINTEREST_BOARD_PATHS = new Set([\n \"about\",\n \"ads\",\n \"board\",\n \"business\",\n \"careers\",\n \"contact\",\n \"create\",\n \"developers\",\n \"explore\",\n \"help\",\n \"ideas\",\n \"login\",\n \"messages\",\n \"notifications\",\n \"pin\",\n \"search\",\n \"settings\",\n \"shopping\",\n \"terms\",\n \"today\"\n]);\nconst RESERVED_PINTEREST_IDEA_PATHS = new Set([\"create\", \"edit\", \"search\"]);\nconst RESERVED_PINTEREST_PROFILE_TABS = new Set([\n \"activity\",\n \"boards\",\n \"comments\",\n \"created\",\n \"followers\",\n \"following\",\n \"likes\",\n \"pins\",\n \"saved\",\n \"tried\"\n]);\n\nexport const isAllowedPinterestReferenceHost = (hostname: string): boolean => (\n hostname === \"pinterest.com\"\n || hostname === \"www.pinterest.com\"\n || /^[a-z]{2}\\.pinterest\\.com$/.test(hostname)\n);\n\nexport const normalizePinterestReferenceUrl = (value: string): string | null => {\n const trimmed = value.trim();\n const absolute = trimmed.startsWith(\"/\")\n ? `https://www.pinterest.com${trimmed}`\n : trimmed;\n try {\n const url = new URL(absolute);\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") return null;\n url.protocol = \"https:\";\n const hostname = url.hostname.toLowerCase();\n if (!isAllowedPinterestReferenceHost(hostname)) return null;\n const pathSegments = url.pathname.split(\"/\").filter(Boolean);\n const isPin = (\n pathSegments[0] === \"pin\"\n && pathSegments.length === 2\n && PINTEREST_PIN_ID_PATTERN.test(pathSegments[1] ?? \"\")\n );\n const isIdea = (\n pathSegments[0] === \"ideas\"\n && pathSegments.length >= 3\n && !RESERVED_PINTEREST_IDEA_PATHS.has(pathSegments[1] ?? \"\")\n && PINTEREST_PIN_ID_PATTERN.test(pathSegments[pathSegments.length - 1] ?? \"\")\n );\n const isBoard = pathSegments.length === 2\n && !RESERVED_PINTEREST_BOARD_PATHS.has(pathSegments[0] ?? \"\")\n && !RESERVED_PINTEREST_PROFILE_TABS.has(pathSegments[1] ?? \"\")\n && pathSegments.every((segment) => !segment.startsWith(\"_\"));\n if (!isPin && !isIdea && !isBoard) return null;\n url.hash = \"\";\n url.search = \"\";\n return url.toString();\n } catch {\n return null;\n }\n};\n\nconst extractPinterestUrlsFromText = (value: string): string[] => {\n const candidates = value.match(/(?:https?:\\/\\/(?:(?:www|[a-z]{2})\\.)?pinterest\\.com\\/(?:pin\\/[a-zA-Z0-9_-]+|ideas\\/[a-zA-Z0-9/_-]+|[a-zA-Z0-9_-]+\\/[a-zA-Z0-9_-]+)|(?<![A-Za-z0-9.])\\/(?:pin\\/[a-zA-Z0-9_-]+|ideas\\/[a-zA-Z0-9/_-]+|[a-zA-Z0-9_-]+\\/[a-zA-Z0-9_-]+))\\/?/g) ?? [];\n return candidates\n .map(normalizePinterestReferenceUrl)\n .filter((url): url is string => url !== null);\n};\n\nconst buildPinterestSearchUrl = (query: string): string => {\n const params = new URLSearchParams({ q: query });\n return `https://www.pinterest.com/search/pins/?${params.toString()}`;\n};\n\nconst extractPinterestReferenceUrls = (candidate: SiteRecipeReferenceCandidate): string[] => {\n return [\n normalizePinterestReferenceUrl(candidate.url ?? \"\"),\n ...(candidate.links ?? []).map(normalizePinterestReferenceUrl),\n ...extractPinterestUrlsFromText(candidate.content ?? \"\"),\n ...extractPinterestUrlsFromText(candidate.html ?? \"\")\n ].filter((url): url is string => url !== null);\n};\n\nexport const pinterestSiteRecipe: SiteRecipe = {\n id: \"social/pinterest\",\n providerIds: [\"social/pinterest\", \"pinterest\"],\n hostnames: [\"pinterest.com\", \"www.pinterest.com\", \"uk.pinterest.com\"],\n authMode: \"authenticated_preferred\",\n navigationSteps: [\n { id: \"open\", instruction: \"Open Pinterest in the requested browser mode.\" },\n { id: \"verify-session\", instruction: \"Verify the page is logged in before searching when cookies are required.\" },\n { id: \"search\", instruction: \"Use the Pinterest search box with the brief-specific visual query.\" },\n { id: \"scroll\", instruction: \"Scroll enough to collect varied pins, boards, and idea pages.\" },\n { id: \"collect\", instruction: \"Collect candidate URLs only from visual result pages.\" }\n ],\n badStates: [\n { id: \"login\", markers: [\"log in\", \"sign up\", \"continue with\"], reasonCode: \"auth_required\", recoveryAction: \"Use extension mode with a user-authorized logged-in Pinterest session.\" },\n { id: \"challenge\", markers: [\"captcha\", \"verification\", \"challenge\"], reasonCode: \"challenge_detected\", recoveryAction: \"Resolve the browser challenge before rerunning harvest.\" },\n { id: \"search-shell\", markers: [\"pin card\", \"your profile\", \"when autocomplete results are available\"], reasonCode: \"env_limited\", recoveryAction: \"Open a concrete pin, board, or idea page before capture.\" }\n ],\n evidenceRequirements: [\n { id: \"visual-grid\", description: \"Candidate shows visual design material, not only Pinterest chrome.\", validation: \"Screenshot contains pins, boards, or idea page content.\" },\n { id: \"on-brief\", description: \"Candidate matches the design brief surface and style intent.\", validation: \"Reference signals overlap the brief target and are not generic marketplace chrome.\" }\n ],\n recoverySteps: [\n { id: \"authenticate\", instruction: \"Use extension mode and cookies only from a user-authorized signed-in Pinterest tab.\" },\n { id: \"explicit-url\", instruction: \"If search is blocked, provide explicit Pinterest pin, board, or idea page URLs.\" }\n ],\n browserNativeDiscovery: {\n buildSearchUrl: buildPinterestSearchUrl,\n extractReferenceUrls: extractPinterestReferenceUrls\n },\n guidance: pinterestGuidance\n};\n","import { isAllowedPinterestReferenceHost, normalizePinterestReferenceUrl } from \"../guidance/recipes/pinterest\";\nimport type { InspiredesignBriefFormat } from \"./brief-expansion\";\n\ntype ReferenceStatus = \"captured\" | \"failed\" | \"skipped\";\n\ntype ReferenceInput = {\n id: string;\n url: string;\n title?: string;\n excerpt?: string;\n fetchStatus: ReferenceStatus;\n captureStatus: \"off\" | \"captured\" | \"failed\";\n capture?: {\n title?: string;\n snapshot?: {\n content: string;\n };\n dom?: {\n outerHTML: string;\n };\n clone?: {\n componentPreview: string;\n cssPreview: string;\n };\n visual?: {\n status: \"captured\" | \"skipped\" | \"failed\";\n path?: string;\n sha256?: string;\n bytes?: number;\n failure?: string;\n warnings: string[];\n };\n } | null;\n};\n\nexport type InspiredesignReferenceQualitySummary = {\n rankedReferenceCount: number;\n rejectedReferenceCount: number;\n topReferenceScore?: number;\n topReferenceConfidence?: number;\n topReferenceIntentMatched?: boolean;\n failedCaptureCount: number;\n missingScreenshotCount: number;\n diagnosticOnlyReasons: string[];\n};\n\nexport type InspiredesignReferencePatternBoard = {\n briefId: string;\n targetSurface: string;\n qualitySummary: InspiredesignReferenceQualitySummary;\n references: Array<{\n id: string;\n rank: number;\n score: number;\n confidence: number;\n name: string;\n url: string;\n surfaceType: string;\n capturedVia: string[];\n intentMatched: boolean;\n selectionReason: string;\n visualStrengths: string[];\n visualRisks: string[];\n layoutRecipe: string;\n contentHierarchy: string[];\n componentFamilies: string[];\n motionPosture: string[];\n tokenNotes: string[];\n patternsToBorrow: string[];\n patternsToReject: string[];\n whyItWorks: string;\n }>;\n rejectedReferences: Array<{\n id: string;\n url: string;\n reason: string;\n fetchStatus: ReferenceStatus;\n captureStatus: \"off\" | \"captured\" | \"failed\";\n captured?: true;\n diagnosticReasons?: string[];\n capturedButRejectedReason?: string;\n evidenceGap?: string;\n }>;\n synthesis: {\n dominantDirection: string;\n sharedStrengths: string[];\n sharedFailuresToAvoid: string[];\n contractDeltas: string[];\n };\n};\n\nexport type InspiredesignDesignVectors = {\n sourcePriority: \"reference-evidence-first\" | \"brief-only\";\n directionLabel: string;\n surfaceIntent: string;\n compositionModel: string[];\n premiumPosture: string[];\n motionPosture: string[];\n sectionArchitecture: string[];\n typographyPosture: string[];\n imageryPosture: string[];\n interactionDensity: string;\n interactionMoments: string[];\n materialEffects: string[];\n advancedMotionAdvisory: string[];\n referenceInfluence: string[];\n patternsToBorrow: string[];\n patternsToReject: string[];\n guardrails: string[];\n antiPatterns: string[];\n};\n\nconst SIGNAL_LIMIT = 5;\nconst SIGNAL_CLIP = 180;\nconst PATTERN_LIMIT = 6;\nconst SCORE_FETCH_CAPTURED = 20;\nconst SCORE_CAPTURE_CAPTURED = 20;\nconst SCORE_VISUAL_CAPTURED = 30;\nconst SCORE_SNAPSHOT = 10;\nconst SCORE_CLONE = 8;\nconst SCORE_DOM = 8;\nconst SCORE_PUBLIC_LANDING = 6;\nconst SCORE_SIGNAL_CAP = 12;\nconst SCORE_INTENT_MISMATCH_PENALTY = 55;\nconst SCORE_PINTEREST_CHROME_METADATA_PENALTY = 35;\nconst MAX_REFERENCE_SCORE = 100;\nconst MIN_READY_REFERENCE_SCORE = 50;\nconst MIN_READY_REFERENCE_CONFIDENCE = 0.5;\nconst ADVANCED_MOTION_FIELDS = [\n \"Advisory shader-style gradients: specify effect type, uniforms, static fallback, and reduced-motion replacement as design language only.\",\n \"Advisory WebGL-style depth cues: describe layered depth, camera-like parallax, and spatial hierarchy without requiring WebGL runtime.\",\n \"Advisory Spline-style staging: describe object-like hero composition, scene count, camera posture, depth model, asset source, and spatial sequencing as implementation guidance only.\",\n \"Advanced motion performance policy: define frame budget, lazy loading, offscreen pause behavior, and vestibular risk before implementation.\",\n \"Runtime boundary: implement with approved CSS and Canvas-safe primitives unless explicit source-owned runtime support is added later.\"\n] as const;\n\nconst trimText = (value: string): string => value.trim().replace(/\\s+/g, \" \");\n\nconst clipText = (value: string, maxLength: number): string => {\n if (value.length <= maxLength) return value;\n return `${value.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;\n};\n\nconst textFromHtml = (html: string | undefined): string | undefined => {\n return html ? trimText(html.replace(/<[^>]+>/g, \" \")) : undefined;\n};\n\nconst stripActionRefs = (value: string): string => (\n value\n .replace(/\\[r\\d+\\]\\s+(?:link|button|combobox|textbox|option)\\s+/gi, \"\")\n .replace(/\\[r\\d+\\]\\s+/gi, \"\")\n .replace(/\\bvalue=/gi, \"\")\n);\n\nconst isCodeOrCssPreview = (value: string): boolean => {\n const lower = value.toLowerCase();\n return lower.includes(\"dangerouslysetinnerhtml\")\n || lower.includes(\"opendevbrowser-root\")\n || lower.includes(\"--gestalt-\")\n || lower.includes(\"align-content:\")\n || lower.startsWith(\":root\")\n || lower.startsWith(\"import \")\n || /^[.#][a-z0-9_-]+\\s*\\{/.test(lower)\n || (lower.includes(\"{\") && /[a-z-]+:\\s*[^;]+;/.test(lower));\n};\n\nconst cleanEvidenceText = (value: string): string => {\n return trimText(stripActionRefs(value).replace(/[{};]/g, \" \"));\n};\n\nconst DIAGNOSTIC_TEXT_MARKERS = [\n \"authentication required\",\n \"sign in\",\n \"login required\",\n \"challenge page\",\n \"access denied\",\n \"browser capture unavailable\",\n \"404\",\n \"page not found\",\n \"not found\",\n \"unavailable page\",\n \"accept all cookies\",\n \"cookie consent\",\n \"cookie preferences\",\n \"privacy settings\",\n \"consent modal\",\n \"javascript required\",\n \"javascript is required\",\n \"captcha\",\n \"verification challenge\",\n \"enable cookies\",\n \"checking if the site connection is secure\",\n \"complete the verification\",\n \"blocked reference\"\n] as const;\n\nconst SEARCH_OR_LISTING_SHELL_MARKERS = [\n \"search results for\",\n \"related searches\",\n \"sort by\",\n \"filter by\"\n] as const;\n\nconst MARKETPLACE_CHROME_MARKERS = [\n \"add to cart\",\n \"marketplace\",\n \"envato\",\n \"etsy\",\n \"template kits\"\n] as const;\n\nconst HARD_DIAGNOSTIC_PAGE_MARKERS = [\n \"404\",\n \"page not found\",\n \"this page is unavailable\",\n \"accept all cookies\",\n \"manage cookies\",\n \"cookie consent\",\n \"sign in to continue\",\n \"log in to continue\",\n \"captcha\",\n \"verification challenge\"\n] as const;\n\nconst INTERFACE_CHROME_TEXT_MARKERS = [\n \"your profile\",\n \"your boards\",\n \"remove search input\",\n \"settings & support\",\n \"pin card\",\n \"voice search\",\n \"lens\",\n \"back to home page\",\n \"toggle mobile menu\",\n \"facebook\",\n \"instagram\",\n \"updates\",\n \"messages\",\n \"when autocomplete results are available\",\n \"touch device users\"\n] as const;\n\nconst PUBLIC_LANDING_TEXT_MARKERS = [\n \"church\",\n \"landing page\",\n \"homepage\",\n \"home page\",\n \"consulting\",\n \"advisory\",\n \"bcg\",\n \"ai consulting\",\n \"enterprise ai\",\n \"transformation\",\n \"client services\",\n \"business services\",\n \"case studies\",\n \"clients\",\n \"industries\",\n \"worship\",\n \"locations\",\n \"gallery\",\n \"atelier\",\n \"fashion\"\n] as const;\n\nconst PUBLIC_LANDING_SUPPORT_MARKERS = [\n \"online\",\n \"events\",\n \"studio\",\n \"website\",\n \"full-bleed\",\n \"hero\",\n \"story\",\n \"stories\",\n \"services\",\n \"service\",\n \"cta\",\n] as const;\n\nconst isDiagnosticText = (value: string): boolean => {\n const lower = value.toLowerCase();\n return DIAGNOSTIC_TEXT_MARKERS.some((marker) => lower.includes(marker));\n};\n\nconst diagnosticPageReasons = (value: string): string[] => {\n const lower = value.toLowerCase();\n const reasons: string[] = [];\n if ([\"404\", \"page not found\", \"this page is unavailable\"].some((marker) => lower.includes(marker))) {\n reasons.push(\"unavailable_page\");\n }\n if ([\"accept all cookies\", \"manage cookies\", \"cookie consent\", \"privacy settings\", \"enable cookies\"].some((marker) => lower.includes(marker))) {\n reasons.push(\"cookie_or_consent_modal\");\n }\n if ([\n \"sign in to continue\",\n \"log in to continue\",\n \"authentication required\",\n \"access denied\",\n \"captcha\",\n \"verification challenge\",\n \"complete the verification\"\n ].some((marker) => lower.includes(marker))) {\n reasons.push(\"login_or_challenge_state\");\n }\n const searchShellCount = SEARCH_OR_LISTING_SHELL_MARKERS.filter((marker) => lower.includes(marker)).length;\n if (searchShellCount >= 2 || lower.includes(\"search results for\") || lower.includes(\"related searches\")) {\n reasons.push(\"search_or_listing_shell\");\n }\n const marketplaceChromeCount = MARKETPLACE_CHROME_MARKERS.filter((marker) => lower.includes(marker)).length;\n if (\n marketplaceChromeCount >= 2\n || ((lower.includes(\"envato\") || lower.includes(\"etsy\")) && (lower.includes(\"template kits\") || searchShellCount > 0))\n ) {\n reasons.push(\"marketplace_or_template_chrome\");\n }\n if (isInterfaceChromeText(value)) {\n reasons.push(\"interface_chrome_shell\");\n }\n return [...new Set(reasons)];\n};\n\nconst isDiagnosticPageText = (value: string): boolean => {\n const lower = value.toLowerCase();\n return HARD_DIAGNOSTIC_PAGE_MARKERS.some((marker) => lower.includes(marker))\n || diagnosticPageReasons(value).length > 0;\n};\n\nconst isInterfaceChromeText = (value: string): boolean => {\n const lower = value.toLowerCase();\n const actionRefCount = countActionRefs(value);\n const markerCount = INTERFACE_CHROME_TEXT_MARKERS.filter((marker) => lower.includes(marker)).length;\n if (\n lower === \"your profile\"\n || lower === \"adobe, inc.\"\n || lower === \"dribbble: the community for graphic design\"\n || /^https?:\\/\\/\\S+$/.test(lower)\n || (lower.includes(\"when autocomplete results are available\") && lower.includes(\"touch device users\"))\n || (actionRefCount >= 3 && markerCount >= 2)\n || (lower.includes(\"get 20%\") && lower.includes(\"dribbble: the community for graphic design\"))\n || (lower.includes(\"our free wordpress themes are downloaded\") && lower.includes(\"get them now\"))\n ) {\n return true;\n }\n return markerCount >= 3 || (lower.includes(\"pin card\") && lower.includes(\"your profile\"));\n};\n\nconst countActionRefs = (value: string): number => (\n (value.match(/\\[r\\d+\\]\\s+(?:link|button|combobox|textbox|option)\\s+/gi) ?? []).length\n);\n\nconst hasPublicLandingSignal = (value: string): boolean => {\n const lower = value.toLowerCase();\n const strongCount = PUBLIC_LANDING_TEXT_MARKERS.filter((marker) => lower.includes(marker)).length;\n const supportCount = PUBLIC_LANDING_SUPPORT_MARKERS.filter((marker) => lower.includes(marker)).length;\n const visualLandingCombo = lower.includes(\"hero\")\n && (lower.includes(\"full-bleed\") || lower.includes(\"cta\") || lower.includes(\"website\"));\n return visualLandingCombo || strongCount >= 2 || (strongCount >= 1 && strongCount + supportCount >= 2);\n};\n\nconst pushSignal = (signals: string[], value: string | undefined): void => {\n if (!value || isCodeOrCssPreview(value)) return;\n const text = cleanEvidenceText(value);\n if (isCodeOrCssPreview(text) || isDiagnosticText(text) || isInterfaceChromeText(text)) return;\n if (text.length > 0 && !signals.includes(text)) {\n signals.push(text);\n }\n};\n\nexport const getInspiredesignReferenceSignals = (reference: ReferenceInput): string[] => {\n const signals: string[] = [];\n pushSignal(signals, reference.title);\n pushSignal(signals, reference.excerpt);\n pushSignal(signals, reference.capture?.title);\n pushSignal(signals, reference.capture?.snapshot?.content);\n pushSignal(signals, textFromHtml(reference.capture?.clone?.componentPreview));\n pushSignal(signals, reference.capture?.clone?.cssPreview);\n pushSignal(signals, textFromHtml(reference.capture?.dom?.outerHTML));\n return signals.map((signal) => clipText(signal, SIGNAL_CLIP)).slice(0, SIGNAL_LIMIT);\n};\n\nconst hasCleanSignal = (value: string | undefined): boolean => {\n if (!value || isCodeOrCssPreview(value)) return false;\n const text = cleanEvidenceText(value);\n return text.length > 0\n && !isCodeOrCssPreview(text)\n && !isDiagnosticText(text)\n && !isDiagnosticPageText(text)\n && !isInterfaceChromeText(text);\n};\n\nconst hasUsableCloneCreativeEvidence = (reference: ReferenceInput): boolean => (\n hasCleanSignal(reference.capture?.clone?.componentPreview)\n);\n\nconst hasUsableRecoveredCreativeEvidence = (reference: ReferenceInput): boolean => (\n hasUsableCloneCreativeEvidence(reference)\n || hasCleanSignal(textFromHtml(reference.capture?.dom?.outerHTML))\n);\n\nconst isPinterestVisualReferenceUrl = (value: string): boolean => normalizePinterestReferenceUrl(value) !== null;\n\nconst pinterestHostnameFromUrl = (value: string): string | null => {\n try {\n return new URL(value).hostname.toLowerCase();\n } catch {\n return null;\n }\n};\n\nconst isPinterestOwnedReferenceUrl = (value: string): boolean => {\n const hostname = pinterestHostnameFromUrl(value);\n return hostname !== null && (hostname === \"pinterest.com\" || hostname.endsWith(\".pinterest.com\"));\n};\n\nconst isUnapprovedPinterestReferenceUrl = (value: string): boolean => {\n const hostname = pinterestHostnameFromUrl(value);\n return hostname !== null && isPinterestOwnedReferenceUrl(value) && !isAllowedPinterestReferenceHost(hostname);\n};\n\nconst hasCleanMetadataValue = (value: string | undefined): boolean => (\n typeof value === \"string\" && countActionRefs(value) < 3 && hasCleanSignal(value)\n);\n\nconst hasCleanMetadataSignal = (reference: ReferenceInput): boolean => (\n hasCleanMetadataValue(reference.title)\n || hasCleanMetadataValue(reference.excerpt)\n || hasCleanMetadataValue(reference.capture?.title)\n);\n\nconst hasOnlySoftPinterestChromeDiagnostics = (reasons: string[]): boolean => (\n reasons.every((reason) => reason === \"interface_chrome_shell\")\n);\n\nconst hasPinterestVisualMetadataEvidence = (reference: ReferenceInput, diagnosticReasons: string[]): boolean => (\n isPinterestVisualReferenceUrl(reference.url)\n && reference.captureStatus === \"captured\"\n && reference.capture?.visual?.status === \"captured\"\n && hasCleanMetadataSignal(reference)\n && hasOnlySoftPinterestChromeDiagnostics(diagnosticReasons)\n);\n\nconst hasUsableCaptureEvidence = (reference: ReferenceInput): boolean => (\n hasCleanSignal(reference.capture?.snapshot?.content)\n || hasUsableCloneCreativeEvidence(reference)\n || hasCleanSignal(textFromHtml(reference.capture?.dom?.outerHTML))\n);\n\nconst referenceDiagnosticReasons = (reference: ReferenceInput): string[] => {\n const text = [\n reference.title,\n reference.excerpt,\n reference.capture?.title,\n reference.capture?.snapshot?.content,\n textFromHtml(reference.capture?.clone?.componentPreview),\n reference.capture?.clone?.cssPreview,\n textFromHtml(reference.capture?.dom?.outerHTML),\n reference.capture?.visual?.failure,\n ...(reference.capture?.visual?.warnings ?? [])\n ].filter((value): value is string => typeof value === \"string\" && value.trim().length > 0).join(\" \");\n return diagnosticPageReasons(text);\n};\n\nconst hasBlockingDiagnosticReason = (reasons: string[]): boolean => (\n reasons.some((reason) => reason !== \"login_or_challenge_state\")\n);\n\nexport const hasInspiredesignUsableReferenceEvidence = (reference: ReferenceInput): boolean => {\n if (isUnapprovedPinterestReferenceUrl(reference.url)) return false;\n const diagnosticReasons = referenceDiagnosticReasons(reference);\n if (hasPinterestVisualMetadataEvidence(reference, diagnosticReasons)) return true;\n if (hasBlockingDiagnosticReason(diagnosticReasons)) return false;\n if (diagnosticReasons.includes(\"login_or_challenge_state\") && !hasUsableRecoveredCreativeEvidence(reference)) {\n return false;\n }\n if (reference.captureStatus === \"captured\" && hasUsableCaptureEvidence(reference)) return true;\n return reference.fetchStatus === \"captured\"\n && diagnosticReasons.length === 0\n && (hasCleanSignal(reference.title) || hasCleanSignal(reference.excerpt));\n};\n\nconst firstSignal = (reference: ReferenceInput): string => {\n const preferred = [\n reference.capture?.title,\n reference.capture?.snapshot?.content,\n textFromHtml(reference.capture?.clone?.componentPreview),\n textFromHtml(reference.capture?.dom?.outerHTML),\n reference.excerpt,\n reference.title\n ].map((value) => value ? cleanEvidenceText(value) : \"\").find((value) => (\n value.length > 0 && !isCodeOrCssPreview(value) && !isDiagnosticText(value) && !isInterfaceChromeText(value)\n ));\n return preferred ? clipText(preferred, SIGNAL_CLIP) : reference.url;\n};\n\nconst displayNameForReference = (reference: ReferenceInput, primarySignal: string): string => {\n const title = reference.title ? cleanEvidenceText(reference.title) : \"\";\n if (title && !isDiagnosticText(title) && !isInterfaceChromeText(title)) {\n return clipText(title, SIGNAL_CLIP);\n }\n return primarySignal !== reference.url ? primarySignal : reference.url;\n};\n\ntype ReferencePatternRule = {\n summary: string;\n matches: readonly string[];\n};\n\nconst REFERENCE_PATTERN_RULES: readonly ReferencePatternRule[] = [\n {\n summary: \"location-first church discovery with regional pathways\",\n matches: [\"find a church\", \"church locations\", \"location\", \"city or postcode\", \"current location\"]\n },\n {\n summary: \"worship and music content as atmosphere and ministry proof\",\n matches: [\"music\", \"worship\", \"united\", \"young & free\", \"chapel\", \"instrumentals\"]\n },\n {\n summary: \"global region navigation with online participation path\",\n matches: [\"asia pacific\", \"europe\", \"north america\", \"latin america\", \"africa\", \"middle east\", \"online\"]\n },\n {\n summary: \"story-led editorial pathway after the primary church action\",\n matches: [\"stories\", \"blog\", \"start reading\", \"newsroom\"]\n },\n {\n summary: \"ministry ecosystem pathways for college, conferences, and events\",\n matches: [\"college\", \"conference\", \"tours\", \"events\"]\n },\n {\n summary: \"multilingual/global audience affordance\",\n matches: [\"language\", \"\\\"en\\\"\", \"\\\"fr\\\"\", \"\\\"es\\\"\", \"\\\"pt\\\"\", \"\\\"de\\\"\"]\n },\n {\n summary: \"full-bleed hero with restrained CTA rail\",\n matches: [\"full-bleed\", \"hero\", \"cta rail\", \"primary cta\"]\n },\n {\n summary: \"premium consulting public landing page with service narrative, client proof, and conversion CTAs\",\n matches: [\"consulting\", \"advisory\", \"bcg\", \"enterprise ai\", \"transformation\", \"client services\", \"case studies\", \"industries\"]\n }\n];\n\nconst ruleMatches = (text: string, rule: ReferencePatternRule): boolean => {\n const lower = text.toLowerCase();\n return rule.matches.some((match) => lower.includes(match));\n};\n\nconst derivePatternSummaries = (signals: string[], fallback: string): string[] => {\n const text = signals.join(\" \");\n const matches = REFERENCE_PATTERN_RULES\n .filter((rule) => ruleMatches(text, rule))\n .map((rule) => rule.summary);\n return matches.length > 0 ? matches.slice(0, PATTERN_LIMIT) : [fallback];\n};\n\nconst appendSourceDetail = (patterns: string[], primarySignal: string): string[] => {\n if (patterns.some((pattern) => primarySignal.toLowerCase().includes(pattern.toLowerCase()))) {\n return patterns;\n }\n return [...patterns, `source detail: ${primarySignal}`].slice(0, PATTERN_LIMIT);\n};\n\nconst deriveCapturedVia = (reference: ReferenceInput): string[] => {\n const methods: string[] = [];\n const diagnosticReasons = referenceDiagnosticReasons(reference);\n const hasPinterestVisualMetadata = hasPinterestVisualMetadataEvidence(reference, diagnosticReasons);\n if (reference.fetchStatus === \"captured\") methods.push(\"fetch\");\n if (hasCleanSignal(reference.capture?.snapshot?.content)) methods.push(\"snapshot\");\n if (hasUsableCloneCreativeEvidence(reference)) {\n methods.push(\"clone\");\n }\n if (hasCleanSignal(textFromHtml(reference.capture?.dom?.outerHTML))) methods.push(\"dom\");\n if (\n reference.capture?.visual?.status === \"captured\"\n && (hasUsableCaptureEvidence(reference) || hasPinterestVisualMetadata)\n ) methods.push(\"visual\");\n return methods;\n};\n\nconst scoreReference = (\n reference: ReferenceInput,\n signals: string[],\n isPublicLanding: boolean\n): number => {\n let score = 0;\n const diagnosticReasons = referenceDiagnosticReasons(reference);\n const hasPinterestVisualMetadata = hasPinterestVisualMetadataEvidence(reference, diagnosticReasons);\n if (reference.fetchStatus === \"captured\") score += SCORE_FETCH_CAPTURED;\n if (reference.captureStatus === \"captured\" && (hasUsableCaptureEvidence(reference) || hasPinterestVisualMetadata)) {\n score += SCORE_CAPTURE_CAPTURED;\n }\n if (\n reference.capture?.visual?.status === \"captured\"\n && (hasUsableCaptureEvidence(reference) || hasPinterestVisualMetadata)\n ) score += SCORE_VISUAL_CAPTURED;\n if (hasCleanSignal(reference.capture?.snapshot?.content)) score += SCORE_SNAPSHOT;\n if (hasUsableCloneCreativeEvidence(reference)) score += SCORE_CLONE;\n if (hasCleanSignal(textFromHtml(reference.capture?.dom?.outerHTML))) score += SCORE_DOM;\n if (isPublicLanding) score += SCORE_PUBLIC_LANDING;\n score += Math.min(SCORE_SIGNAL_CAP, signals.length * 2);\n if (hasPinterestVisualMetadata && diagnosticReasons.includes(\"interface_chrome_shell\")) {\n score -= SCORE_PINTEREST_CHROME_METADATA_PENALTY;\n }\n return Math.min(MAX_REFERENCE_SCORE, score);\n};\n\nconst confidenceFromScore = (score: number): number => (\n Number((score / MAX_REFERENCE_SCORE).toFixed(2))\n);\n\nconst deriveVisualStrengths = (\n reference: ReferenceInput,\n patterns: string[]\n): string[] => {\n const strengths = [\n ...(reference.capture?.visual?.status === \"captured\"\n ? [\"Screenshot artifact is available for direct visual inspection.\"]\n : []),\n ...(reference.capture?.snapshot?.content.trim()\n ? [\"Snapshot text confirms visible hierarchy and interaction targets.\"]\n : []),\n ...(hasUsableCloneCreativeEvidence(reference)\n ? [\"Clone preview exposes reusable component and styling cues.\"]\n : []),\n ...patterns.slice(0, 2).map((pattern) => `Reusable visual cue: ${pattern}.`)\n ];\n return strengths.slice(0, PATTERN_LIMIT);\n};\n\nconst deriveVisualRisks = (reference: ReferenceInput): string[] => {\n const risks = [\n ...(reference.capture?.visual?.status !== \"captured\"\n ? [\"No finalized screenshot artifact, so visual claims must stay conservative.\"]\n : []),\n ...(reference.capture?.visual?.status === \"failed\" && reference.capture.visual.failure\n ? [`Screenshot failure: ${reference.capture.visual.failure}.`]\n : []),\n ...(reference.capture?.visual?.warnings ?? []).map((warning) => `Screenshot warning: ${warning}.`),\n ...(reference.fetchStatus !== \"captured\"\n ? [\"Fetch evidence failed or was skipped, so use browser capture cautiously.\"]\n : [])\n ];\n return risks.length > 0\n ? risks.slice(0, PATTERN_LIMIT)\n : [\"No major visual evidence risk detected in the captured reference.\"];\n};\n\nconst selectionReasonForScore = (score: number, capturedVia: string[]): string => {\n if (capturedVia.includes(\"visual\")) {\n return `Ranked for screenshot-backed visual evidence plus ${capturedVia.join(\", \")} capture.`;\n }\n if (score >= 50) {\n return `Ranked for strong text and structural evidence from ${capturedVia.join(\", \") || \"reference metadata\"}.`;\n }\n return \"Ranked for limited but usable reference cues.\";\n};\n\nconst deriveComponentFamilies = (\n format: InspiredesignBriefFormat,\n patterns: string[],\n isPublicLanding: boolean\n): string[] => {\n const base = isPublicLanding\n ? \"hero composition, proof bands, narrative pathways, service or story sections, conversion CTA, and footer\"\n : format.componentGrammar;\n return [base, ...patterns.slice(0, 3)];\n};\n\nconst hasReferencePublicLandingEvidence = (\n reference: InspiredesignReferencePatternBoard[\"references\"][number]\n): boolean => {\n const text = [\n reference.surfaceType,\n reference.layoutRecipe,\n ...reference.contentHierarchy,\n ...reference.patternsToBorrow\n ].join(\" \");\n return hasPublicLandingSignal(text);\n};\n\nconst hasBoardPublicLandingEvidence = (board: InspiredesignReferencePatternBoard): boolean => (\n board.references.some(hasReferencePublicLandingEvidence)\n);\n\nconst boardEvidenceText = (board: InspiredesignReferencePatternBoard): string => (\n board.references.map((reference) => [\n reference.layoutRecipe,\n ...reference.contentHierarchy,\n ...reference.componentFamilies,\n ...reference.motionPosture,\n ...reference.patternsToBorrow\n ].join(\" \")).join(\" \").toLowerCase()\n);\n\nconst hasEvidenceCue = (text: string, matches: readonly string[]): boolean => (\n matches.some((match) => text.includes(match))\n);\n\nconst INTENT_STOP_WORDS = new Set([\n \"and\",\n \"cinematic\",\n \"dark\",\n \"digital\",\n \"for\",\n \"from\",\n \"landing\",\n \"light\",\n \"microinteractions\",\n \"motion\",\n \"page\",\n \"parallax\",\n \"premium\",\n \"reveal\",\n \"site\",\n \"scroll\",\n \"theme\",\n \"with\",\n \"design\",\n \"website\"\n]);\n\nconst tokenizeIntent = (value: string): string[] => (\n value.toLowerCase().match(/[a-z0-9][a-z0-9-]{2,}/g) ?? []\n).filter((token) => !INTENT_STOP_WORDS.has(token));\n\nconst formatIntentTokens = (format: InspiredesignBriefFormat): string[] => [\n ...format.keywords,\n ...format.businessFocus,\n ...format.bestFor,\n ...(format.focusAreas ?? []),\n format.archetype,\n format.layoutArchetype,\n format.surfaceTreatment,\n format.motionGrammar,\n format.paletteIntent\n].flatMap(tokenizeIntent);\n\nconst intentTokenVariants = (token: string): string[] => {\n if (token === \"photo\" || token === \"photos\" || token === \"photography\" || token === \"photographer\" || token === \"photographic\") {\n return [\"photo\", \"photos\", \"photography\", \"photographer\", \"photographic\"];\n }\n return [token];\n};\n\nconst countMatchedIntentTokens = (signals: string[], intentTokens: string[]): number => {\n const evidenceTokens = new Set(signals.flatMap(tokenizeIntent));\n return intentTokens.filter((token) => intentTokenVariants(token).some((variant) => evidenceTokens.has(variant))).length;\n};\n\nconst hasBriefIntentMatch = (\n signals: string[],\n format: InspiredesignBriefFormat,\n briefText: string\n): boolean => {\n const briefTokens = tokenizeIntent(briefText);\n const hasBriefIntentTokens = briefTokens.length > 0;\n const intentTokens = [...new Set(hasBriefIntentTokens ? briefTokens : formatIntentTokens(format))];\n if (intentTokens.length === 0) return true;\n const matchCount = countMatchedIntentTokens(signals, intentTokens);\n if (!hasBriefIntentTokens) return matchCount > 0;\n return matchCount >= Math.min(2, intentTokens.length);\n};\n\nconst deriveReferenceEntry = (\n reference: ReferenceInput,\n format: InspiredesignBriefFormat,\n briefText: string\n): Omit<InspiredesignReferencePatternBoard[\"references\"][number], \"rank\"> => {\n const signals = getInspiredesignReferenceSignals(reference);\n const primarySignal = firstSignal(reference);\n const patterns = appendSourceDetail(derivePatternSummaries(signals, primarySignal), primarySignal);\n const isPublicLanding = signals.some(hasPublicLandingSignal);\n const capturedVia = deriveCapturedVia(reference);\n const intentMatched = hasBriefIntentMatch(signals, format, briefText);\n const rawScore = scoreReference(reference, signals, isPublicLanding);\n const score = intentMatched ? rawScore : Math.max(0, rawScore - SCORE_INTENT_MISMATCH_PENALTY);\n return {\n id: reference.id,\n score,\n confidence: confidenceFromScore(score),\n name: displayNameForReference(reference, primarySignal),\n url: reference.url,\n surfaceType: isPublicLanding ? \"public landing page\" : format.archetype,\n capturedVia,\n intentMatched,\n selectionReason: intentMatched\n ? selectionReasonForScore(score, capturedVia)\n : `${selectionReasonForScore(score, capturedVia)} Intent overlap with the brief is weak, so the score was downgraded.`,\n visualStrengths: deriveVisualStrengths(reference, patterns),\n visualRisks: deriveVisualRisks(reference),\n layoutRecipe: patterns.join(\"; \"),\n contentHierarchy: patterns.slice(0, 4),\n componentFamilies: deriveComponentFamilies(format, patterns, isPublicLanding),\n motionPosture: [format.motionGrammar, \"Plan hero reveal, scroll reveal, CTA feedback, and reduced-motion behavior.\"],\n tokenNotes: [format.paletteIntent, format.typographySystem, format.surfaceTreatment],\n patternsToBorrow: [...patterns, ...signals.slice(0, 2)].slice(0, PATTERN_LIMIT),\n patternsToReject: [...format.antiPatterns],\n whyItWorks: reference.captureStatus === \"captured\"\n ? \"Captured reference evidence provides reusable hierarchy, rhythm, and component cues.\"\n : \"Available reference text provides directional content and hierarchy cues.\"\n };\n};\n\nconst sortReferenceEntries = (\n entries: Array<Omit<InspiredesignReferencePatternBoard[\"references\"][number], \"rank\">>\n): Array<InspiredesignReferencePatternBoard[\"references\"][number]> => entries\n .slice()\n .sort((left, right) => (\n right.score - left.score\n || left.id.localeCompare(right.id)\n || left.url.localeCompare(right.url)\n ))\n .map((entry, index) => ({\n rank: index + 1,\n ...entry\n }));\n\nconst rejectionReasonForReference = (reference: ReferenceInput): string => {\n if (isUnapprovedPinterestReferenceUrl(reference.url)) {\n return \"Pinterest reference host is not approved for creative synthesis.\";\n }\n const diagnosticReasons = referenceDiagnosticReasons(reference);\n if (diagnosticReasons.length > 0) {\n return `Reference evidence is diagnostic-only: ${diagnosticReasons.join(\", \")}.`;\n }\n if (reference.fetchStatus === \"failed\" && reference.captureStatus === \"failed\") {\n return \"Fetch and capture did not produce usable creative evidence.\";\n }\n if (reference.captureStatus === \"failed\") {\n return \"Capture did not produce usable creative evidence.\";\n }\n if (reference.fetchStatus === \"failed\") {\n return \"Fetch did not produce usable creative evidence.\";\n }\n return \"Reference evidence was diagnostic, empty, or too weak for creative synthesis.\";\n};\n\nconst hasCapturedEvidence = (reference: ReferenceInput): boolean => (\n reference.captureStatus === \"captured\" || reference.capture?.visual?.status === \"captured\"\n);\n\nconst capturedButRejectedReason = (diagnosticReasons: string[]): string => (\n diagnosticReasons.length > 0\n ? `Captured browser evidence was rejected because it only exposed diagnostic signals: ${diagnosticReasons.join(\", \")}.`\n : \"Captured browser evidence was rejected because it did not contain usable creative reference evidence.\"\n);\n\nconst buildRejectedReferences = (\n references: ReferenceInput[]\n): InspiredesignReferencePatternBoard[\"rejectedReferences\"] => references\n .filter((reference) => !hasInspiredesignUsableReferenceEvidence(reference))\n .map((reference) => {\n const diagnosticReasons = referenceDiagnosticReasons(reference);\n const captured = hasCapturedEvidence(reference);\n return {\n id: reference.id,\n url: reference.url,\n reason: rejectionReasonForReference(reference),\n fetchStatus: reference.fetchStatus,\n captureStatus: reference.captureStatus,\n ...(captured ? { captured: true as const } : {}),\n ...(diagnosticReasons.length > 0 ? { diagnosticReasons } : {}),\n ...(captured ? {\n capturedButRejectedReason: capturedButRejectedReason(diagnosticReasons),\n evidenceGap: \"Design-facing artifacts require creative layout evidence; diagnostic browser chrome is kept only as rejection metadata.\"\n } : {})\n };\n });\n\nconst buildQualitySummary = (\n references: ReferenceInput[],\n rankedEntries: InspiredesignReferencePatternBoard[\"references\"],\n rejectedReferences: InspiredesignReferencePatternBoard[\"rejectedReferences\"]\n): InspiredesignReferenceQualitySummary => {\n const diagnosticOnlyReasons = [...new Set(references.flatMap(referenceDiagnosticReasons))];\n const rankedIds = new Set(rankedEntries.map((entry) => entry.id));\n const rankedReferences = references.filter((reference) => rankedIds.has(reference.id));\n const failedCaptureCount = rankedReferences.filter((reference) => reference.captureStatus === \"failed\").length;\n const missingScreenshotCount = rankedReferences.filter((reference) => reference.capture?.visual?.status !== \"captured\").length;\n const topReference = rankedEntries[0];\n return {\n rankedReferenceCount: rankedEntries.length,\n rejectedReferenceCount: rejectedReferences.length,\n failedCaptureCount,\n missingScreenshotCount,\n diagnosticOnlyReasons,\n ...(topReference\n ? {\n topReferenceScore: topReference.score,\n topReferenceConfidence: topReference.confidence,\n topReferenceIntentMatched: topReference.intentMatched\n }\n : {})\n };\n};\n\nexport const summarizeInspiredesignReferenceQuality = (\n board: InspiredesignReferencePatternBoard\n): InspiredesignReferenceQualitySummary => ({ ...board.qualitySummary });\n\nexport const isInspiredesignReadyReference = (\n reference: InspiredesignReferencePatternBoard[\"references\"][number]\n): boolean => (\n reference.intentMatched\n && reference.score >= MIN_READY_REFERENCE_SCORE\n && reference.confidence >= MIN_READY_REFERENCE_CONFIDENCE\n);\n\nexport const isInspiredesignDesignReference = (\n reference: InspiredesignReferencePatternBoard[\"references\"][number]\n): boolean => (\n !isPinterestOwnedReferenceUrl(reference.url) || (\n isPinterestVisualReferenceUrl(reference.url) && isInspiredesignReadyReference(reference)\n )\n);\n\nconst buildNotReadyRejectedReference = (\n reference: InspiredesignReferencePatternBoard[\"references\"][number]\n): InspiredesignReferencePatternBoard[\"rejectedReferences\"][number] => {\n const captured = reference.capturedVia.length > 0;\n return {\n id: reference.id,\n url: reference.url,\n reason: reference.intentMatched\n ? \"Reference evidence did not meet the design-ready ranking threshold.\"\n : \"Reference evidence did not match the requested design intent.\",\n fetchStatus: reference.capturedVia.includes(\"fetch\") ? \"captured\" : \"skipped\",\n captureStatus: reference.capturedVia.some((method) => method !== \"fetch\") ? \"captured\" : \"off\",\n ...(captured ? {\n captured: true as const,\n capturedButRejectedReason: \"Captured reference evidence did not satisfy design-ready ranking gates.\",\n evidenceGap: \"Design-facing artifacts require design-ready creative evidence; non-ready captures are kept only as rejection metadata.\"\n } : {})\n };\n};\n\nconst mergeRejectedReferences = (\n rejectedReferences: InspiredesignReferencePatternBoard[\"rejectedReferences\"]\n): InspiredesignReferencePatternBoard[\"rejectedReferences\"] => {\n const seen = new Set<string>();\n return rejectedReferences.filter((reference) => {\n if (seen.has(reference.id)) return false;\n seen.add(reference.id);\n return true;\n });\n};\n\nexport const buildInspiredesignRankedArtifactPatternBoard = (\n designBoard: InspiredesignReferencePatternBoard,\n sourceBoard: InspiredesignReferencePatternBoard\n): InspiredesignReferencePatternBoard => {\n const designReferenceIds = new Set(designBoard.references.map((reference) => reference.id));\n const notReadyReferences = sourceBoard.references\n .filter((reference) => !designReferenceIds.has(reference.id))\n .map(buildNotReadyRejectedReference);\n return {\n ...designBoard,\n rejectedReferences: mergeRejectedReferences([\n ...sourceBoard.rejectedReferences,\n ...notReadyReferences\n ])\n };\n};\n\nexport const buildInspiredesignDesignReferencePatternBoard = (\n board: InspiredesignReferencePatternBoard,\n designVectors: InspiredesignDesignVectors\n): InspiredesignReferencePatternBoard => {\n const references = board.references.filter(isInspiredesignDesignReference);\n const notReadyCount = board.references.length - references.length;\n const topReference = references[0];\n const missingScreenshotCount = references.filter((reference) => !reference.capturedVia.includes(\"visual\")).length;\n const qualitySummary: InspiredesignReferenceQualitySummary = {\n rankedReferenceCount: references.length,\n rejectedReferenceCount: board.rejectedReferences.length + notReadyCount,\n failedCaptureCount: 0,\n missingScreenshotCount,\n diagnosticOnlyReasons: [...board.qualitySummary.diagnosticOnlyReasons],\n ...(topReference\n ? {\n topReferenceScore: topReference.score,\n topReferenceConfidence: topReference.confidence,\n topReferenceIntentMatched: topReference.intentMatched\n }\n : {})\n };\n return {\n ...board,\n targetSurface: designVectors.surfaceIntent,\n qualitySummary,\n references,\n rejectedReferences: [],\n synthesis: {\n dominantDirection: designVectors.directionLabel,\n sharedStrengths: [...designVectors.patternsToBorrow],\n sharedFailuresToAvoid: [...designVectors.patternsToReject],\n contractDeltas: references.length > 0\n ? [...board.synthesis.contractDeltas]\n : [\"No ready reference evidence is available; keep implementation anchored to the source brief.\"]\n }\n };\n};\n\nexport const buildInspiredesignReferencePatternBoard = (\n briefId: string,\n format: InspiredesignBriefFormat,\n references: ReferenceInput[],\n briefText = \"\"\n): InspiredesignReferencePatternBoard => {\n const entries = references\n .filter(hasInspiredesignUsableReferenceEvidence)\n .map((reference) => deriveReferenceEntry(reference, format, briefText));\n const rankedEntries = sortReferenceEntries(entries);\n const rejectedReferences = buildRejectedReferences(references);\n const sharedStrengths = rankedEntries.flatMap((entry) => entry.patternsToBorrow).slice(0, 6);\n const targetSurface = rankedEntries.some((entry) => entry.surfaceType === \"public landing page\")\n ? \"reference-led public landing page\"\n : format.layoutArchetype;\n return {\n briefId,\n targetSurface,\n qualitySummary: buildQualitySummary(references, rankedEntries, rejectedReferences),\n references: rankedEntries,\n rejectedReferences,\n synthesis: {\n dominantDirection: rankedEntries[0]?.layoutRecipe ?? format.archetype,\n sharedStrengths,\n sharedFailuresToAvoid: [...format.antiPatterns],\n contractDeltas: [\n \"Selected prompt format supplies route defaults and guardrails, not the creative source of truth.\",\n \"Use captured reference hierarchy before generic profile defaults when URL evidence exists.\"\n ]\n }\n };\n};\n\nconst buildInteractionDensity = (\n format: InspiredesignBriefFormat,\n board: InspiredesignReferencePatternBoard\n): string => {\n if (hasBoardPublicLandingEvidence(board)) {\n return \"low-to-medium; prioritize confident public-page CTAs over app-shell controls.\";\n }\n if (format.route.navigationModel === \"sidebar\") {\n return \"medium-to-high; prioritize command surfaces, state clarity, and durable workspace controls.\";\n }\n if (format.route.profile === \"documentation\") {\n return \"low-to-medium; prioritize visual overview, proof scanning, and a small number of clear action paths.\";\n }\n if (format.route.profile === \"auth-focused\") {\n return \"low; prioritize one confident first action with clear feedback and trust cues.\";\n }\n return \"low-to-medium; prioritize confident public-page CTAs over app-shell controls.\";\n};\n\nconst buildImageryPosture = (\n format: InspiredesignBriefFormat,\n board: InspiredesignReferencePatternBoard\n): string[] => {\n if (hasBoardPublicLandingEvidence(board)) {\n return [format.surfaceTreatment, \"Use dominant atmospheric imagery as the visual anchor.\"];\n }\n if (format.route.navigationModel === \"sidebar\") {\n return [format.surfaceTreatment, \"Use product state, data hierarchy, and workspace continuity as the visual anchor.\"];\n }\n return [format.surfaceTreatment, \"Use dominant atmospheric imagery as the visual anchor.\"];\n};\n\nconst buildInteractionMoments = (\n format: InspiredesignBriefFormat,\n board: InspiredesignReferencePatternBoard\n): string[] => {\n const evidenceText = boardEvidenceText(board);\n const publicLanding = hasBoardPublicLandingEvidence(board);\n const referenceBacked = board.references.length > 0;\n const cursorScope = publicLanding\n ? \"hero CTA, media reveals, and primary navigation moments\"\n : \"high-value actions and selected command surfaces\";\n const moments = [\n \"Microinteractions: define hover effects, visible focus rings, pressed states, loading states, and confirmation feedback for every primary action.\",\n `Animation choreography: sequence ${format.motionGrammar}, hover feedback, active feedback, and page transitions through one timing system.`\n ];\n const cursorBacked = hasEvidenceCue(evidenceText, [\"cursor\", \"magnetic\", \"follow-cursor\", \"pointer\"]);\n const cursorPolicy = cursorBacked\n ? `Cursor effects: reference evidence supports premium pointer affordances for ${cursorScope}; keep default cursor behavior for reading surfaces.`\n : `Cursor effects policy: consider magnetic or follow-cursor affordances only when reference evidence supports ${cursorScope}.`;\n return referenceBacked ? [...moments, cursorPolicy] : moments;\n};\n\nconst buildMaterialEffects = (board: InspiredesignReferencePatternBoard): string[] => {\n if (board.references.length === 0) {\n return [\n \"Material effects: define elevation, shadows, surface contrast, and reduced-motion-safe depth from the brief.\",\n \"Reduced-motion material fallback: preserve hierarchy and CTA clarity without transform-based depth.\"\n ];\n }\n const evidenceText = boardEvidenceText(board);\n const publicLanding = hasBoardPublicLandingEvidence(board);\n const glassScope = publicLanding\n ? \"navigation overlays, hero scrims, and atmospheric CTA surfaces\"\n : \"focused overlays, inspectors, or state containers\";\n const parallaxBacked = hasEvidenceCue(evidenceText, [\"parallax\", \"depth\", \"layered\", \"immersive\", \"full-bleed\"]);\n const glassBacked = hasEvidenceCue(evidenceText, [\"glass\", \"frosted\", \"blur\", \"translucent\", \"scrim\", \"overlay\"]);\n const parallax = parallaxBacked\n ? \"Depth language: reference evidence supports restrained parallax, layered shadows, and atmospheric depth where it reinforces hierarchy.\"\n : \"Depth language policy: use parallax only when reference evidence supports layered depth; otherwise use spacing, scale, and shadow hierarchy.\";\n const glass = glassBacked\n ? `Glassmorphism/translucency: reference evidence supports frosted or translucent surfaces for ${glassScope}; never use glass as generic decoration.`\n : `Glassmorphism/translucency policy: use frosted or translucent surfaces only when reference evidence supports ${glassScope}.`;\n return [\n parallax,\n glass,\n \"Reduced-motion material fallback: remove parallax and cursor-follow transforms while preserving hierarchy, depth, and CTA clarity.\"\n ];\n};\n\nconst buildSectionArchitecture = (\n format: InspiredesignBriefFormat,\n board: InspiredesignReferencePatternBoard\n): string[] => {\n if (hasBoardPublicLandingEvidence(board)) {\n return [\n \"Use 8 to 12 primary landing-page sections unless the user explicitly asks for a microsite.\",\n \"Build a clear sequence from hero, proof, story, service pathways, impact, conversion CTA, and footer.\"\n ];\n }\n if (format.route.profile === \"documentation\") {\n return [\n \"Use a text-light overview sequence for purpose, proof, examples, action paths, and footer.\",\n \"Keep long-form reference depth, citation modules, annotation rails, and methodology blocks out of the primary visual route.\"\n ];\n }\n if (format.route.profile === \"auth-focused\") {\n return [\n \"Use a screen sequence for value, trust, input, confirmation, and first-action transition.\",\n \"Keep the flow compact instead of expanding into marketing section sprawl.\"\n ];\n }\n if (format.route.navigationModel === \"immersive\") {\n return [\n \"Use cinematic scene beats for hero, product reveal, proof, detail, and decisive CTA.\",\n \"Keep each scroll beat focused on one visual idea.\"\n ];\n }\n if (format.route.navigationModel === \"sidebar\") {\n return [\n \"Use workspace shell zones for navigation, command surfaces, primary work area, detail panels, and state feedback.\",\n \"Prioritize task continuity over marketing-section cadence.\"\n ];\n }\n return [\n \"Use 8 to 12 primary landing-page sections unless the user explicitly asks for a microsite.\",\n \"Build a clear sequence from hero, proof, story, service pathways, impact, conversion CTA, and footer.\"\n ];\n};\n\nexport const buildInspiredesignDesignVectors = (\n format: InspiredesignBriefFormat,\n board: InspiredesignReferencePatternBoard\n): InspiredesignDesignVectors => {\n const designReferences = board.references.filter(isInspiredesignDesignReference);\n const designStrengths = designReferences.flatMap((entry) => entry.patternsToBorrow).slice(0, 6);\n const influence = designStrengths.length > 0\n ? designStrengths\n : [format.archetype];\n const designBoard = { ...board, references: designReferences };\n const publicLandingEvidence = hasBoardPublicLandingEvidence(designBoard);\n const surfaceIntent = publicLandingEvidence\n ? \"reference-led public landing page\"\n : format.archetype;\n const compositionModel = publicLandingEvidence\n ? [\"full-bleed hero with narrative section cadence\", ...designReferences.map((entry) => entry.layoutRecipe)]\n : [format.layoutArchetype, ...designReferences.map((entry) => entry.layoutRecipe)];\n return {\n sourcePriority: designReferences.length > 0 ? \"reference-evidence-first\" : \"brief-only\",\n directionLabel: designReferences[0]?.layoutRecipe ?? format.archetype,\n surfaceIntent,\n compositionModel: compositionModel.slice(0, 5),\n premiumPosture: [\n \"premium visual hierarchy, refined spacing, and editorial image treatment.\",\n \"Premium typography, spacing, visual hierarchy, palette, and image treatment must lead the page.\",\n format.surfaceTreatment,\n format.paletteIntent\n ],\n motionPosture: [\n \"Use a hero entrance reveal, section scroll reveal, and CTA/focus feedback.\",\n \"Respect reduced-motion preference with static hierarchy preserved.\",\n format.motionGrammar\n ],\n sectionArchitecture: buildSectionArchitecture(format, designBoard),\n typographyPosture: [format.typographySystem],\n imageryPosture: buildImageryPosture(format, designBoard),\n interactionDensity: buildInteractionDensity(format, designBoard),\n interactionMoments: buildInteractionMoments(format, designBoard),\n materialEffects: buildMaterialEffects(designBoard),\n advancedMotionAdvisory: [...ADVANCED_MOTION_FIELDS],\n referenceInfluence: influence,\n patternsToBorrow: designReferences.flatMap((entry) => entry.patternsToBorrow).slice(0, 8),\n patternsToReject: designReferences.flatMap((entry) => entry.patternsToReject).slice(0, 8),\n guardrails: [...format.guardrails],\n antiPatterns: [...format.antiPatterns]\n };\n};\n","import type { InspiredesignBriefExpansion } from \"./brief-expansion\";\nimport {\n isInspiredesignDesignReference,\n type InspiredesignDesignVectors,\n type InspiredesignReferencePatternBoard\n} from \"./reference-pattern-board\";\n\ntype RankedReference = InspiredesignReferencePatternBoard[\"references\"][number];\n\nconst formatList = (items: readonly string[]): string => (\n items.length > 0\n ? items.map((item) => `- ${item}`).join(\"\\n\")\n : \"- No evidence-backed item available.\"\n);\n\nconst formatRankedReferences = (\n references: readonly RankedReference[]\n): string => {\n if (references.length === 0) {\n return \"- No ready references were ranked. Work from the brief and note missing evidence.\";\n }\n return references.map((reference) => [\n `### Rank ${reference.rank}: ${reference.name}`,\n `- URL: ${reference.url}`,\n `- Score: ${reference.score}`,\n `- Confidence: ${reference.confidence.toFixed(2)}`,\n `- Selection reason: ${reference.selectionReason}`,\n `- Borrow: ${reference.patternsToBorrow.join(\"; \")}`,\n `- Reject: ${reference.patternsToReject.join(\"; \")}`,\n `- Visual strengths: ${reference.visualStrengths.join(\"; \")}`,\n `- Visual risks: ${reference.visualRisks.join(\"; \")}`\n ].join(\"\\n\")).join(\"\\n\\n\");\n};\n\nconst formatRejectedReferences = (\n board: InspiredesignReferencePatternBoard,\n notReadyReferences: readonly RankedReference[]\n): string => {\n const lines = [\n ...(board.rejectedReferences.length > 0\n ? [`- ${board.rejectedReferences.length} reference(s) were rejected as diagnostic-only or unavailable.`]\n : []),\n ...(notReadyReferences.length > 0\n ? [`- ${notReadyReferences.length} ranked reference(s) were not ready for creative synthesis due to score, confidence, or brief-intent mismatch.`]\n : [])\n ];\n return lines.length > 0 ? lines.join(\"\\n\") : \"- No references were rejected from the creative synthesis.\";\n};\n\nexport const buildInspiredesignMetaPrompt = (input: {\n brief: string;\n briefExpansion: InspiredesignBriefExpansion;\n referencePatternBoard: InspiredesignReferencePatternBoard;\n designVectors: InspiredesignDesignVectors;\n}): string => {\n const designReferences = input.referencePatternBoard.references.filter(isInspiredesignDesignReference);\n const notReadyReferences = input.referencePatternBoard.references.filter(\n (reference) => !isInspiredesignDesignReference(reference)\n );\n return [\n \"# InspireDesign Meta Prompt\",\n \"\",\n \"Use this prompt to generate a fresh design direction from evidence without copying any reference brand, asset, layout, or proprietary expression.\",\n \"\",\n \"## Source Brief\",\n input.brief,\n \"\",\n \"## Prompt Format\",\n `- Format: ${input.briefExpansion.format.label}`,\n `- Target surface: ${input.designVectors.surfaceIntent}`,\n `- Dominant direction: ${input.designVectors.directionLabel}`,\n \"\",\n \"## Ranked References\",\n formatRankedReferences(designReferences),\n \"\",\n \"## Rejected References\",\n formatRejectedReferences(input.referencePatternBoard, notReadyReferences),\n \"\",\n \"## Borrow Guidance\",\n formatList(input.designVectors.patternsToBorrow),\n \"\",\n \"## Reject Guidance\",\n formatList([\n ...input.designVectors.patternsToReject,\n \"Do not copy logos, screenshots, protected brand assets, page structure, copy, or trade dress from references.\"\n ]),\n \"\",\n \"## Motion Posture\",\n formatList([\n ...input.designVectors.motionPosture,\n ...input.designVectors.interactionMoments,\n ...input.designVectors.advancedMotionAdvisory\n ]),\n \"\",\n \"## Accessibility Constraints\",\n formatList([\n \"Keyboard navigation must reach every interactive element.\",\n \"Focus states must be visible in every theme and viewport.\",\n \"Respect prefers-reduced-motion with a static hierarchy-preserving alternative.\",\n \"Validate contrast for text, controls, overlays, and disabled states.\"\n ]),\n \"\",\n \"## Validation Gates\",\n formatList([\n \"Read visual-evidence.json, screenshot-index.json, ranked-references.json, and evidence.json before implementation.\",\n \"Confirm screenshot paths exist before making visual claims.\",\n \"Verify desktop and mobile layouts with real browser screenshots.\",\n \"Run reduced-motion, keyboard, focus, and contrast checks before shipping.\",\n \"Keep production code generation outside the harvest output.\"\n ])\n ].join(\"\\n\");\n};\n","import { createHash } from \"crypto\";\n\nexport const INSPIREDESIGN_VISUAL_EVIDENCE_MODES = [\"off\", \"auto\", \"required\"] as const;\nexport const INSPIREDESIGN_VISUAL_EVIDENCE_KINDS = [\"viewport\", \"full_page\"] as const;\n\nexport type InspiredesignVisualEvidenceMode = typeof INSPIREDESIGN_VISUAL_EVIDENCE_MODES[number];\nexport type InspiredesignVisualEvidenceKind = typeof INSPIREDESIGN_VISUAL_EVIDENCE_KINDS[number];\nexport type InspiredesignVisualEvidenceStatus = \"captured\" | \"skipped\" | \"failed\";\n\nexport type InspiredesignVisualEvidenceViewport = {\n width?: number;\n height?: number;\n deviceScaleFactor?: number;\n};\n\nexport type InspiredesignVisualEvidenceRuntimeMetadata = {\n status: InspiredesignVisualEvidenceStatus;\n kind: InspiredesignVisualEvidenceKind;\n fullPage: boolean;\n capturedAt: string;\n artifactPath?: string;\n tempPath?: string;\n viewport?: InspiredesignVisualEvidenceViewport;\n warnings: string[];\n failure?: string;\n};\n\nexport type InspiredesignPersistedVisualEvidence = {\n status: InspiredesignVisualEvidenceStatus;\n kind: InspiredesignVisualEvidenceKind;\n fullPage: boolean;\n capturedAt: string;\n path?: string;\n sha256?: string;\n bytes?: number;\n viewport?: InspiredesignVisualEvidenceViewport;\n warnings: string[];\n failure?: string;\n};\n\ntype PersistVisualEvidenceOptions = {\n artifactPath?: string;\n sha256?: string;\n bytes?: number;\n};\n\nconst SAFE_REFERENCE_ID_PATTERN = /[^a-z0-9._-]+/gi;\nconst MAX_VISUAL_REFERENCE_ID_LENGTH = 96;\nconst MAX_VISUAL_WARNING_LENGTH = 160;\nconst MAX_VISUAL_FAILURE_LENGTH = 240;\nconst UNSAFE_VISUAL_TEXT_PATTERN =\n /(?:\\/(?:Users|private|tmp|var|Volumes)\\/|[A-Za-z]:\\\\|\\\\|data:image|;base64|base64,|[A-Za-z0-9+/]{80,}={0,2})/i;\nconst DOT_ONLY_PATH_SEGMENT_PATTERN = /^\\.+$/;\nconst SHA256_HEX_PATTERN = /^[a-f0-9]{64}$/i;\nconst VISUAL_ARTIFACT_PATH_PATTERN =\n /^visual-evidence\\/([A-Za-z0-9._-]+)\\/(?:viewport|full_page)\\.png$/;\nconst FALLBACK_VISUAL_CAPTURED_AT = \"1970-01-01T00:00:00.000Z\";\n\nexport const isInspiredesignVisualEvidenceMode = (\n value: unknown\n): value is InspiredesignVisualEvidenceMode => (\n typeof value === \"string\"\n && (INSPIREDESIGN_VISUAL_EVIDENCE_MODES as readonly string[]).includes(value)\n);\n\nexport const isInspiredesignVisualEvidenceKind = (\n value: unknown\n): value is InspiredesignVisualEvidenceKind => (\n typeof value === \"string\"\n && (INSPIREDESIGN_VISUAL_EVIDENCE_KINDS as readonly string[]).includes(value)\n);\n\nexport const sanitizeInspiredesignVisualReferenceId = (referenceId: string): string => {\n const sanitized = referenceId.trim().replace(SAFE_REFERENCE_ID_PATTERN, \"-\").replace(/^-+|-+$/g, \"\");\n if (!sanitized || DOT_ONLY_PATH_SEGMENT_PATTERN.test(sanitized)) return \"reference\";\n const truncated = sanitized.slice(0, MAX_VISUAL_REFERENCE_ID_LENGTH);\n return DOT_ONLY_PATH_SEGMENT_PATTERN.test(truncated) ? \"reference\" : truncated;\n};\n\nexport const buildVisualEvidenceArtifactPath = (\n referenceId: string,\n kind: InspiredesignVisualEvidenceKind\n): string => `visual-evidence/${sanitizeInspiredesignVisualReferenceId(referenceId)}/${kind}.png`;\n\nexport const hashVisualEvidenceBuffer = (buffer: Buffer): string => (\n createHash(\"sha256\").update(buffer).digest(\"hex\")\n);\n\nconst sanitizeVisualEvidenceText = (\n value: unknown,\n maxLength: number\n): string | undefined => {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (!trimmed || UNSAFE_VISUAL_TEXT_PATTERN.test(trimmed)) return undefined;\n return trimmed.slice(0, maxLength);\n};\n\nconst sanitizeVisualEvidencePath = (value: unknown): string | undefined => {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n const match = VISUAL_ARTIFACT_PATH_PATTERN.exec(trimmed);\n const referenceSegment = match?.[1];\n if (!referenceSegment || DOT_ONLY_PATH_SEGMENT_PATTERN.test(referenceSegment)) return undefined;\n return trimmed;\n};\n\nconst sanitizeVisualEvidenceSha256 = (value: unknown): string | undefined => {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return SHA256_HEX_PATTERN.test(trimmed) ? trimmed.toLowerCase() : undefined;\n};\n\nconst sanitizeVisualEvidenceBytes = (value: unknown): number | undefined => (\n typeof value === \"number\" && Number.isFinite(value) && Number.isInteger(value) && value >= 0\n ? value\n : undefined\n);\n\nconst sanitizeVisualEvidenceCapturedAt = (value: unknown): string => {\n if (typeof value !== \"string\") return FALLBACK_VISUAL_CAPTURED_AT;\n const trimmed = value.trim();\n if (!trimmed || UNSAFE_VISUAL_TEXT_PATTERN.test(trimmed)) return FALLBACK_VISUAL_CAPTURED_AT;\n const timestamp = Date.parse(trimmed);\n if (!Number.isFinite(timestamp)) return FALLBACK_VISUAL_CAPTURED_AT;\n return new Date(timestamp).toISOString();\n};\n\nconst normalizeVisualEvidenceViewport = (\n value: unknown\n): InspiredesignVisualEvidenceViewport | undefined => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n const record = value as Record<string, unknown>;\n const viewport: InspiredesignVisualEvidenceViewport = {};\n if (typeof record.width === \"number\" && Number.isFinite(record.width)) {\n viewport.width = record.width;\n }\n if (typeof record.height === \"number\" && Number.isFinite(record.height)) {\n viewport.height = record.height;\n }\n if (typeof record.deviceScaleFactor === \"number\" && Number.isFinite(record.deviceScaleFactor)) {\n viewport.deviceScaleFactor = record.deviceScaleFactor;\n }\n return Object.keys(viewport).length > 0 ? viewport : undefined;\n};\n\nconst normalizeVisualEvidenceWarnings = (value: unknown): string[] => {\n if (!Array.isArray(value)) return [];\n return value\n .map((warning) => sanitizeVisualEvidenceText(warning, MAX_VISUAL_WARNING_LENGTH))\n .filter((warning): warning is string => Boolean(warning));\n};\n\nexport const persistInspiredesignVisualEvidence = (\n metadata: InspiredesignVisualEvidenceRuntimeMetadata | InspiredesignPersistedVisualEvidence,\n options: PersistVisualEvidenceOptions = {}\n): InspiredesignPersistedVisualEvidence => {\n const runtimeMetadata = metadata as InspiredesignVisualEvidenceRuntimeMetadata;\n const persistedMetadata = metadata as InspiredesignPersistedVisualEvidence;\n const path = metadata.status === \"captured\"\n ? sanitizeVisualEvidencePath(options.artifactPath)\n ?? sanitizeVisualEvidencePath(persistedMetadata.path)\n ?? sanitizeVisualEvidencePath(runtimeMetadata.artifactPath)\n : undefined;\n const sha256 = sanitizeVisualEvidenceSha256(options.sha256) ?? sanitizeVisualEvidenceSha256(persistedMetadata.sha256);\n const bytes = sanitizeVisualEvidenceBytes(options.bytes) ?? sanitizeVisualEvidenceBytes(persistedMetadata.bytes);\n const capturedAt = sanitizeVisualEvidenceCapturedAt(metadata.capturedAt);\n const viewport = normalizeVisualEvidenceViewport(metadata.viewport);\n const failure = sanitizeVisualEvidenceText(metadata.failure, MAX_VISUAL_FAILURE_LENGTH);\n return {\n status: metadata.status,\n kind: isInspiredesignVisualEvidenceKind(metadata.kind) ? metadata.kind : \"viewport\",\n fullPage: metadata.fullPage === true,\n capturedAt,\n ...(path ? { path } : {}),\n ...(sha256 ? { sha256 } : {}),\n ...(bytes !== undefined ? { bytes } : {}),\n ...(viewport ? { viewport } : {}),\n warnings: normalizeVisualEvidenceWarnings(metadata.warnings),\n ...(failure ? { failure } : {})\n };\n};\n","import type { JsonValue } from \"../providers/types\";\nimport type { NextStepGuidance } from \"./types\";\n\nexport type GuidanceCompatibilityStep = {\n reason: string;\n command?: string;\n};\n\nexport type GuidanceWorkflowCompatibility = {\n followthroughSummary: string;\n suggestedNextAction: string;\n suggestedSteps: GuidanceCompatibilityStep[];\n};\n\nexport type GuidanceProviderCompatibility = {\n reason: string;\n recommendedNextCommands: string[];\n nextStepGuidance: Record<string, JsonValue>;\n};\n\nconst toJsonValue = (value: NextStepGuidance): Record<string, JsonValue> => {\n return structuredClone(value) as Record<string, JsonValue>;\n};\n\nexport const renderWorkflowGuidance = (guidance: NextStepGuidance): Record<string, JsonValue> => {\n return toJsonValue(guidance);\n};\n\nexport const renderCliGuidance = (guidance: NextStepGuidance): string => {\n const commands = guidance.commands.map((entry) => `Run: ${entry.command}`);\n const checks = guidance.validationChecks.map((entry) => `Check: ${entry.assertion ?? entry.description}`);\n return [guidance.primaryAction.summary, ...commands, ...checks].join(\"\\n\");\n};\n\nexport const renderWorkflowCompatibility = (\n guidance: NextStepGuidance,\n fallbackSummary?: string\n): GuidanceWorkflowCompatibility => {\n const commandSteps = guidance.commands.map((entry) => ({\n reason: entry.label,\n command: entry.command\n }));\n const artifactSteps = guidance.artifactInputs.map((entry) => ({\n reason: `${entry.required ? \"Required\" : \"Optional\"}: ${entry.path}. ${entry.purpose}`\n }));\n const validationSteps = guidance.validationChecks.map((entry) => ({\n reason: entry.assertion ? `${entry.description} Assertion: ${entry.assertion}` : entry.description,\n ...(entry.command ? { command: entry.command } : {})\n }));\n return {\n followthroughSummary: fallbackSummary ?? guidance.primaryAction.summary,\n suggestedNextAction: guidance.primaryAction.summary,\n suggestedSteps: [...commandSteps, ...artifactSteps, ...validationSteps]\n };\n};\n\nexport const renderProviderConstraintCompatibility = (\n guidance: NextStepGuidance\n): GuidanceProviderCompatibility => ({\n reason: guidance.primaryAction.summary,\n recommendedNextCommands: guidance.commands.map((entry) => entry.command),\n nextStepGuidance: renderWorkflowGuidance(guidance)\n});\n\nexport const renderDaemonReadinessText = (guidance: NextStepGuidance): string => {\n const firstCheck = guidance.validationChecks[0]?.assertion ?? guidance.validationChecks[0]?.description;\n if (firstCheck) {\n return `${guidance.primaryAction.summary} Validate with ${firstCheck}.`;\n }\n return guidance.primaryAction.summary;\n};\n","import type { GuidanceContext, GuidanceReadiness } from \"./types\";\n\nconst MIN_READY_REFERENCE_SCORE = 50;\nconst MIN_READY_REFERENCE_CONFIDENCE = 0.5;\n\nconst hasProviderBlocker = (context: GuidanceContext): boolean => {\n if (context.providerUnavailable === true) return true;\n return context.reasonCode === \"provider_unavailable\" || context.reasonCode === \"auth_required\";\n};\n\nconst hasDiagnosticOnlyEvidence = (context: GuidanceContext): boolean => {\n const reasons = context.evidence?.diagnosticOnlyReasons ?? [];\n if (reasons.length === 0) return false;\n return (context.evidence?.rankedReferenceCount ?? 0) === 0;\n};\n\nconst hasNoReferences = (context: GuidanceContext): boolean => {\n return context.evidence?.referenceEvidenceRequired !== false && (context.evidence?.referenceCount ?? 0) === 0;\n};\n\nconst hasNoRankedReferences = (context: GuidanceContext): boolean => {\n const referenceCount = context.evidence?.referenceCount ?? 0;\n if (referenceCount === 0) return false;\n return (context.evidence?.rankedReferenceCount ?? 0) === 0;\n};\n\nconst hasRequiredCaptureFailure = (context: GuidanceContext): boolean => {\n if (context.evidence?.visualEvidenceRequired !== true) return false;\n return (context.evidence.failedCaptureCount ?? 0) > 0 || (context.evidence.missingScreenshotCount ?? 0) > 0;\n};\n\nconst hasWeakTopReference = (context: GuidanceContext): boolean => {\n const rankedCount = context.evidence?.rankedReferenceCount ?? 0;\n if (rankedCount === 0) return false;\n const score = context.evidence?.topReferenceScore ?? 0;\n const confidence = context.evidence?.topReferenceConfidence ?? 0;\n return score < MIN_READY_REFERENCE_SCORE || confidence < MIN_READY_REFERENCE_CONFIDENCE;\n};\n\nconst hasOffBriefTopReference = (context: GuidanceContext): boolean => {\n const rankedCount = context.evidence?.rankedReferenceCount ?? 0;\n return rankedCount > 0 && context.evidence?.topReferenceIntentMatched === false;\n};\n\nexport const classifyGuidanceReadiness = (context: GuidanceContext): GuidanceReadiness => {\n if (context.reasonCode === \"missing_input\" || context.reasonCode === \"missing_params\") return \"needs_input\";\n if (context.reasonCode === \"daemon_fingerprint_mismatch\") return \"blocked\";\n if (hasProviderBlocker(context)) return \"blocked\";\n if (hasDiagnosticOnlyEvidence(context)) return \"diagnostic_only\";\n if (hasNoReferences(context)) return \"needs_recovery\";\n if (hasNoRankedReferences(context)) return \"needs_recovery\";\n if (hasRequiredCaptureFailure(context)) return \"needs_recovery\";\n if (hasOffBriefTopReference(context)) return \"needs_recovery\";\n if (hasWeakTopReference(context)) return \"needs_recovery\";\n return \"ready\";\n};\n\nexport const guidanceReadinessThresholds = {\n minReadyReferenceScore: MIN_READY_REFERENCE_SCORE,\n minReadyReferenceConfidence: MIN_READY_REFERENCE_CONFIDENCE\n} as const;\n","import type { JsonValue } from \"../providers/types\";\nimport type {\n GuidanceFieldExample,\n GuidanceParamsExample,\n GuidanceValidationCheck,\n NextStepGuidance\n} from \"../guidance/types\";\nimport { renderWorkflowGuidance } from \"../guidance/renderers\";\nimport type {\n CanvasGenerationPlan,\n CanvasGenerationPlanIssue\n} from \"./types\";\n\nconst EXAMPLE_MAX_INTERACTION_LATENCY_MS = 150;\nconst MAX_ISSUE_FIELD_EXAMPLES = 8;\n\nexport type CanvasRepairReasonCode =\n | \"plan_required\"\n | \"generation_plan_invalid\"\n | \"governance_missing\"\n | \"missing_canvas_session_id\"\n | \"missing_lease_id\"\n | \"missing_document_id\";\n\nexport type CanvasMissingIdentifier = \"canvasSessionId\" | \"leaseId\" | \"documentId\";\n\nexport type CanvasRepairGuidancePayload = {\n recommendedNextCommands: string[];\n reason: string;\n nextStepGuidance: Record<string, JsonValue>;\n paramsExamples: GuidanceParamsExample[];\n fieldExamples: GuidanceFieldExample[];\n validationChecks: GuidanceValidationCheck[];\n doNotProceedIf: string[];\n};\n\nexport type CanvasRepairEnvelope = {\n code: CanvasRepairReasonCode;\n message: string;\n recommendedNextCommands: string[];\n guidance: CanvasRepairGuidancePayload;\n nextStepGuidance: Record<string, JsonValue>;\n paramsExamples: GuidanceParamsExample[];\n fieldExamples: GuidanceFieldExample[];\n validationChecks: GuidanceValidationCheck[];\n doNotProceedIf: string[];\n};\n\nexport const EXAMPLE_CANVAS_GENERATION_PLAN: CanvasGenerationPlan = {\n targetOutcome: {\n mode: \"high-fi-live-edit\",\n summary: \"Produce an evidence-backed, responsive landing page iteration.\"\n },\n visualDirection: {\n profile: \"cinematic-minimal\",\n themeStrategy: \"single-theme\"\n },\n layoutStrategy: {\n approach: \"hero-led composition with clear content sections\",\n navigationModel: \"global-header\"\n },\n contentStrategy: {\n source: \"design brief, harvested references, and current project content\"\n },\n componentStrategy: {\n mode: \"reuse existing components before creating new primitives\",\n interactionStates: [\"default\", \"hover\", \"focus\", \"disabled\"]\n },\n motionPosture: {\n level: \"subtle\",\n reducedMotion: \"respect-user-preference\"\n },\n responsivePosture: {\n primaryViewport: \"desktop\",\n requiredViewports: [\"desktop\", \"tablet\", \"mobile\"]\n },\n accessibilityPosture: {\n target: \"WCAG_2_2_AA\",\n keyboardNavigation: \"full\"\n },\n validationTargets: {\n blockOn: [\"contrast-failure\", \"missing-intent\", \"missing-design-language\"],\n requiredThemes: [\"light\"],\n browserValidation: \"required\",\n maxInteractionLatencyMs: EXAMPLE_MAX_INTERACTION_LATENCY_MS\n },\n interactionMoments: [\"primary CTA hover\", \"keyboard focus ring\", \"mobile navigation open\"],\n materialEffects: [\"soft depth on primary surfaces\"],\n designVectors: {\n density: \"editorial\",\n imagery: \"dominant first-viewport visual plane\"\n }\n};\n\nconst exampleIds = {\n canvasSessionId: \"canvas-session-from-session-open\",\n leaseId: \"lease-from-session-open\",\n documentId: \"document-from-session-open\"\n} as const;\n\nconst stringifyReceived = (value: unknown): string | undefined => {\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n};\n\nconst toExpectedString = (value: string | string[] | undefined): string | undefined => {\n if (Array.isArray(value)) return value.join(\" | \");\n return value;\n};\n\nconst commandForReason = (reasonCode: CanvasRepairReasonCode, blockedCommand?: string): string[] => {\n const retryCommand = blockedCommand && blockedCommand !== \"canvas.session.attach\" ? blockedCommand : \"canvas.plan.set\";\n if (reasonCode === \"missing_canvas_session_id\") return [\"canvas.session.open\", retryCommand];\n if (reasonCode === \"missing_lease_id\") return [\"canvas.session.attach\", retryCommand];\n if (reasonCode === \"missing_document_id\") return [\"canvas.document.load\"];\n if (reasonCode === \"governance_missing\") return [\"canvas.document.patch\", \"canvas.preview.render\", \"canvas.document.save\"];\n return [\"canvas.plan.set\", \"canvas.plan.get\"];\n};\n\nconst titleForReason = (reasonCode: CanvasRepairReasonCode): string => {\n if (reasonCode === \"missing_canvas_session_id\") return \"Open a Canvas session before running this command.\";\n if (reasonCode === \"missing_lease_id\") return \"Attach to the Canvas session and include the active leaseId.\";\n if (reasonCode === \"missing_document_id\") return \"Load a Canvas document by documentId or repoPath before continuing.\";\n if (reasonCode === \"governance_missing\") return \"Patch missing governance blocks before mutation, preview, or save.\";\n if (reasonCode === \"plan_required\") return \"Submit a valid generationPlan before mutating the Canvas document.\";\n return \"Repair generationPlan and resubmit canvas.plan.set.\";\n};\n\nconst labelForCommand = (command: string): string => {\n switch (command) {\n case \"canvas.session.open\":\n return \"Open a Canvas session\";\n case \"canvas.session.attach\":\n return \"Attach or reclaim a Canvas lease\";\n case \"canvas.document.load\":\n return \"Load the target Canvas document\";\n case \"canvas.document.patch\":\n return \"Patch missing governance\";\n case \"canvas.plan.get\":\n return \"Inspect the current plan status\";\n case \"canvas.plan.set\":\n return \"Submit a valid generationPlan\";\n default:\n return command.startsWith(\"canvas.\") ? `Retry ${command}` : \"Submit a valid generationPlan\";\n }\n};\n\nconst shellSingleQuote = (value: string): string => `'${value.replaceAll(\"'\", \"'\\\"'\\\"'\")}'`;\n\nconst inlineParamsFlag = (params: Record<string, JsonValue>): string => (\n ` --params ${shellSingleQuote(JSON.stringify(params))}`\n);\n\nconst buildCanvasSessionParamsExample = (): Record<string, JsonValue> => ({\n canvasSessionId: exampleIds.canvasSessionId,\n leaseId: exampleIds.leaseId\n});\n\nconst cliForCommand = (command: string): string => {\n switch (command) {\n case \"canvas.session.open\":\n return \"npx opendevbrowser canvas --command canvas.session.open --output-format json\";\n case \"canvas.session.attach\":\n return `npx opendevbrowser canvas --command canvas.session.attach${inlineParamsFlag(buildAttachParamsExample())} --output-format json`;\n case \"canvas.document.load\":\n return `npx opendevbrowser canvas --command canvas.document.load${inlineParamsFlag(buildDocumentLoadParamsExample())} --output-format json`;\n case \"canvas.document.patch\":\n return `npx opendevbrowser canvas --command canvas.document.patch${inlineParamsFlag(buildCanvasGovernancePatchParamsExample())} --output-format json`;\n case \"canvas.plan.get\":\n return `npx opendevbrowser canvas --command canvas.plan.get${inlineParamsFlag(buildCanvasSessionParamsExample())} --output-format json`;\n case \"canvas.plan.set\":\n return `npx opendevbrowser canvas --command canvas.plan.set${inlineParamsFlag(buildCanvasPlanSetParamsExample())} --output-format json`;\n default:\n if (command.startsWith(\"canvas.\")) {\n return `npx opendevbrowser canvas --command ${command}${inlineParamsFlag(buildCanvasSessionParamsExample())} --output-format json`;\n }\n return `npx opendevbrowser canvas --command canvas.plan.set${inlineParamsFlag(buildCanvasPlanSetParamsExample())} --output-format json`;\n }\n};\n\nconst commandExamples = (reasonCode: CanvasRepairReasonCode, blockedCommand?: string) => {\n const commands = commandForReason(reasonCode, blockedCommand);\n return commands.map((command) => ({\n id: command.replaceAll(\".\", \"-\"),\n label: labelForCommand(command),\n command: cliForCommand(command)\n }));\n};\n\nexport const buildCanvasPlanSetParamsExample = (): Record<string, JsonValue> => ({\n canvasSessionId: exampleIds.canvasSessionId,\n leaseId: exampleIds.leaseId,\n generationPlan: EXAMPLE_CANVAS_GENERATION_PLAN as unknown as JsonValue\n});\n\nexport const buildCanvasGovernancePatchParamsExample = (): Record<string, JsonValue> => ({\n canvasSessionId: exampleIds.canvasSessionId,\n leaseId: exampleIds.leaseId,\n baseRevision: 1,\n patches: [{\n op: \"governance.update\",\n block: \"intent\",\n changes: {\n summary: \"Create an evidence-backed landing page iteration for the current brief.\",\n audience: \"Primary product or service buyers\",\n task: \"Understand the offer and take the primary conversion action\",\n successCriteria: [\n \"Hero communicates the brand and offer without relying on navigation text\",\n \"Primary CTA is visible and keyboard reachable\",\n \"Desktop, tablet, and mobile layouts preserve content hierarchy\"\n ]\n }\n }]\n});\n\nconst buildDocumentLoadParamsExample = (): Record<string, JsonValue> => ({\n canvasSessionId: exampleIds.canvasSessionId,\n leaseId: exampleIds.leaseId,\n documentId: exampleIds.documentId\n});\n\nconst buildAttachParamsExample = (): Record<string, JsonValue> => ({\n canvasSessionId: exampleIds.canvasSessionId,\n attachMode: \"lease_reclaim\"\n});\n\nconst issuePriority = (issue: CanvasGenerationPlanIssue): number => {\n if (issue.code === \"invalid_value\") return 0;\n if (issue.code === \"invalid_type\") return 1;\n return 2;\n};\n\nconst issueFieldExamples = (issues: CanvasGenerationPlanIssue[]): GuidanceFieldExample[] => {\n const prioritizedIssues = [...issues].sort((left, right) => issuePriority(left) - issuePriority(right));\n return prioritizedIssues.slice(0, MAX_ISSUE_FIELD_EXAMPLES).map((issue) => ({\n path: `generationPlan.${issue.path}`,\n description: issue.message,\n example: readExampleForIssuePath(issue.path),\n ...(issue.expected ? { expected: toExpectedString(issue.expected) } : {}),\n ...(typeof issue.received !== \"undefined\" ? { received: stringifyReceived(issue.received) } : {})\n }));\n};\n\nconst readExampleForIssuePath = (path: string): JsonValue => {\n const segments = path.split(\".\");\n let current: JsonValue = EXAMPLE_CANVAS_GENERATION_PLAN as unknown as JsonValue;\n for (const segment of segments) {\n if (!current || typeof current !== \"object\" || Array.isArray(current)) return \"<valid value>\";\n current = current[segment] ?? \"<valid value>\";\n }\n return current;\n};\n\nconst normalizeGenerationPlanPath = (path: string): string => {\n const trimmed = path.trim();\n return trimmed.startsWith(\"generationPlan.\") ? trimmed.slice(\"generationPlan.\".length) : trimmed;\n};\n\nconst missingFieldExamples = (missingFields: string[]): GuidanceFieldExample[] => missingFields\n .map(normalizeGenerationPlanPath)\n .filter((path) => path.length > 0)\n .slice(0, MAX_ISSUE_FIELD_EXAMPLES)\n .map((path) => ({\n path: `generationPlan.${path}`,\n description: `Provide generationPlan.${path} before retrying canvas.plan.set.`,\n example: readExampleForIssuePath(path),\n expected: \"valid Canvas generation plan field\"\n }));\n\nconst baseFieldExamples = (reasonCode: CanvasRepairReasonCode): GuidanceFieldExample[] => {\n if (reasonCode === \"missing_canvas_session_id\") {\n return [{\n path: \"canvasSessionId\",\n description: \"Use the canvasSessionId returned by canvas.session.open.\",\n example: exampleIds.canvasSessionId,\n expected: \"non-empty string\"\n }];\n }\n if (reasonCode === \"missing_lease_id\") {\n return [{\n path: \"leaseId\",\n description: \"Use the active leaseId returned by canvas.session.open or canvas.session.attach.\",\n example: exampleIds.leaseId,\n expected: \"non-empty string\"\n }];\n }\n if (reasonCode === \"missing_document_id\") {\n return [{\n path: \"documentId\",\n description: \"Use documentId when loading a persisted Canvas document. Use repoPath instead when loading by file path.\",\n example: exampleIds.documentId,\n expected: \"non-empty string\"\n }];\n }\n return [{\n path: \"designGovernance.intent\",\n description: \"Patch intent before save or downstream handoff when governance warnings report missing intent.\",\n example: {\n summary: \"Create an evidence-backed landing page iteration for the current brief.\",\n audience: \"Primary product or service buyers\",\n task: \"Understand the offer and take the primary conversion action\"\n }\n }];\n};\n\nconst chooseFieldExamples = (\n reasonCode: CanvasRepairReasonCode,\n issues: CanvasGenerationPlanIssue[],\n missingFields: string[]\n): GuidanceFieldExample[] => {\n const issueExamples = issueFieldExamples(issues);\n if (issueExamples.length > 0) return issueExamples;\n const missingExamples = missingFieldExamples(missingFields);\n if (missingExamples.length > 0) return missingExamples;\n return baseFieldExamples(reasonCode);\n};\n\nconst paramsForCommand = (command: string): Record<string, JsonValue> | null => {\n switch (command) {\n case \"canvas.session.attach\":\n return buildAttachParamsExample();\n case \"canvas.document.load\":\n return buildDocumentLoadParamsExample();\n case \"canvas.document.patch\":\n return buildCanvasGovernancePatchParamsExample();\n case \"canvas.plan.get\":\n return buildCanvasSessionParamsExample();\n case \"canvas.plan.set\":\n return buildCanvasPlanSetParamsExample();\n default:\n return command.startsWith(\"canvas.\") ? buildCanvasSessionParamsExample() : null;\n }\n};\n\nconst paramsExamples = (reasonCode: CanvasRepairReasonCode, blockedCommand?: string): GuidanceParamsExample[] => {\n const examples: GuidanceParamsExample[] = [];\n if (reasonCode === \"missing_lease_id\") {\n examples.push({\n id: \"canvas-attach-request\",\n label: \"Attach or reclaim a session lease\",\n command: \"canvas.session.attach\",\n params: buildAttachParamsExample()\n });\n const blockedParams = blockedCommand ? paramsForCommand(blockedCommand) : null;\n if (blockedCommand && blockedCommand !== \"canvas.session.attach\" && blockedParams) {\n examples.push({\n id: `${blockedCommand.replaceAll(\".\", \"-\")}-request`,\n label: `Valid ${blockedCommand} params after lease recovery`,\n command: blockedCommand,\n params: blockedParams\n });\n return examples;\n }\n }\n if (reasonCode === \"missing_document_id\") {\n examples.push({\n id: \"canvas-document-load-request\",\n label: \"Load a document by id\",\n command: \"canvas.document.load\",\n params: buildDocumentLoadParamsExample()\n });\n return examples;\n }\n examples.push({\n id: \"canvas-plan-set-request\",\n label: \"Valid canvas.plan.set params\",\n command: \"canvas.plan.set\",\n params: buildCanvasPlanSetParamsExample()\n });\n if (reasonCode === \"governance_missing\") {\n examples.push({\n id: \"canvas-governance-intent-patch\",\n label: \"Patch missing intent governance\",\n command: \"canvas.document.patch\",\n params: buildCanvasGovernancePatchParamsExample()\n });\n }\n return examples;\n};\n\nconst validationChecks = (reasonCode: CanvasRepairReasonCode): GuidanceValidationCheck[] => {\n const checks: GuidanceValidationCheck[] = [{\n id: \"session-opened\",\n description: \"canvas.session.open or canvas.session.attach returns active ids before command retry.\",\n assertion: \"typeof canvasSessionId === \\\"string\\\" && typeof leaseId === \\\"string\\\"\"\n }];\n if (reasonCode !== \"missing_document_id\") {\n checks.push({\n id: \"plan-valid\",\n description: \"generationPlan passes Canvas validation.\",\n assertion: \"validateGenerationPlan(generationPlan).ok === true\"\n });\n } else {\n checks.push({\n id: \"document-target-selected\",\n description: \"documentId or repoPath is present before loading a Canvas document.\",\n assertion: \"typeof documentId === \\\"string\\\" || typeof repoPath === \\\"string\\\"\"\n });\n }\n if (reasonCode === \"governance_missing\") {\n checks.push({\n id: \"intent-present\",\n description: \"intent governance block is present after canvas.document.patch.\",\n assertion: \"designGovernance.intent is present\"\n });\n }\n return checks;\n};\n\nconst doNotProceedIf = (reasonCode: CanvasRepairReasonCode): string[] => {\n const blockers = [\n \"canvasSessionId is missing or stale\",\n \"leaseId is missing or no longer active\"\n ];\n if (reasonCode !== \"missing_document_id\") {\n blockers.push(\"generationPlan validation still reports missing or invalid fields\");\n } else {\n blockers.push(\"documentId and repoPath are both missing\");\n }\n if (reasonCode === \"governance_missing\") {\n blockers.push(\"intent or other required governance blocks are still missing\");\n }\n return blockers;\n};\n\nexport const buildCanvasRepairGuidance = (input: {\n reasonCode: CanvasRepairReasonCode;\n missingFields?: string[];\n issues?: CanvasGenerationPlanIssue[];\n message?: string;\n blockedCommand?: string;\n}): NextStepGuidance => {\n const fields = chooseFieldExamples(input.reasonCode, input.issues ?? [], input.missingFields ?? []);\n const readiness = input.reasonCode === \"governance_missing\" ? \"needs_recovery\" : \"needs_input\";\n const severity = input.reasonCode === \"governance_missing\" ? \"warning\" : \"blocked\";\n return {\n id: `canvas.${input.reasonCode}`,\n recipeType: \"schema_repair\",\n workflow: \"canvas\",\n severity,\n readiness,\n reasonCode: input.reasonCode,\n primaryAction: {\n id: \"repair_canvas_request\",\n label: \"Repair Canvas command params\",\n summary: input.message ?? titleForReason(input.reasonCode)\n },\n commands: commandExamples(input.reasonCode, input.blockedCommand),\n paramsExamples: paramsExamples(input.reasonCode, input.blockedCommand),\n fieldExamples: fields,\n artifactInputs: [],\n validationChecks: validationChecks(input.reasonCode),\n fallbackPolicy: {\n allowed: false,\n requiresUserConfirmation: true,\n reason: \"Do not skip Canvas validation or governance gates. Repair the typed command payload first.\"\n },\n doNotProceedIf: doNotProceedIf(input.reasonCode)\n };\n};\n\nexport const buildCanvasRepairEnvelope = (input: {\n reasonCode: CanvasRepairReasonCode;\n message?: string;\n missingFields?: string[];\n issues?: CanvasGenerationPlanIssue[];\n blockedCommand?: string;\n}): CanvasRepairEnvelope => {\n const guidance = buildCanvasRepairGuidance(input);\n const recommendedNextCommands = commandForReason(input.reasonCode, input.blockedCommand);\n const message = input.message ?? guidance.primaryAction.summary;\n const guidancePayload = {\n recommendedNextCommands,\n reason: message,\n nextStepGuidance: renderWorkflowGuidance(guidance),\n paramsExamples: guidance.paramsExamples,\n fieldExamples: guidance.fieldExamples,\n validationChecks: guidance.validationChecks,\n doNotProceedIf: guidance.doNotProceedIf\n };\n // Root-level fields preserve the legacy CLI/tool surface; details.guidance is the canonical typed payload.\n return {\n code: input.reasonCode,\n message,\n recommendedNextCommands,\n guidance: guidancePayload,\n nextStepGuidance: guidancePayload.nextStepGuidance,\n paramsExamples: guidancePayload.paramsExamples,\n fieldExamples: guidancePayload.fieldExamples,\n validationChecks: guidancePayload.validationChecks,\n doNotProceedIf: guidancePayload.doNotProceedIf\n };\n};\n\nconst missingIdentifierReasonCode = (field: CanvasMissingIdentifier): CanvasRepairReasonCode => {\n if (field === \"canvasSessionId\") return \"missing_canvas_session_id\";\n if (field === \"leaseId\") return \"missing_lease_id\";\n return \"missing_document_id\";\n};\n\nconst SESSION_REQUIRED_COMMANDS = new Set([\n \"canvas.session.attach\",\n \"canvas.session.status\",\n \"canvas.session.close\",\n \"canvas.capabilities.get\",\n \"canvas.plan.set\",\n \"canvas.plan.get\",\n \"canvas.document.load\",\n \"canvas.document.import\",\n \"canvas.document.patch\",\n \"canvas.history.undo\",\n \"canvas.history.redo\",\n \"canvas.document.save\",\n \"canvas.document.export\",\n \"canvas.inventory.list\",\n \"canvas.inventory.insert\",\n \"canvas.starter.apply\",\n \"canvas.tab.open\",\n \"canvas.tab.close\",\n \"canvas.overlay.mount\",\n \"canvas.overlay.unmount\",\n \"canvas.overlay.select\",\n \"canvas.preview.render\",\n \"canvas.preview.refresh\",\n \"canvas.feedback.poll\",\n \"canvas.feedback.subscribe\",\n \"canvas.feedback.next\",\n \"canvas.feedback.unsubscribe\",\n \"canvas.code.bind\",\n \"canvas.code.unbind\",\n \"canvas.code.pull\",\n \"canvas.code.push\",\n \"canvas.code.status\",\n \"canvas.code.resolve\"\n]);\n\nconst requiresCanvasSessionId = (command: string): boolean => SESSION_REQUIRED_COMMANDS.has(command);\n\nconst LEASE_REQUIRED_COMMANDS = new Set([\n \"canvas.session.close\",\n \"canvas.plan.set\",\n \"canvas.plan.get\",\n \"canvas.document.load\",\n \"canvas.document.import\",\n \"canvas.document.patch\",\n \"canvas.history.undo\",\n \"canvas.history.redo\",\n \"canvas.document.save\",\n \"canvas.document.export\",\n \"canvas.inventory.insert\",\n \"canvas.starter.apply\",\n \"canvas.tab.open\",\n \"canvas.tab.close\",\n \"canvas.overlay.mount\",\n \"canvas.overlay.unmount\",\n \"canvas.overlay.select\",\n \"canvas.preview.render\",\n \"canvas.preview.refresh\",\n \"canvas.code.bind\",\n \"canvas.code.unbind\",\n \"canvas.code.pull\",\n \"canvas.code.push\",\n \"canvas.code.resolve\"\n]);\n\nconst requiresLeaseId = (command: string): boolean => LEASE_REQUIRED_COMMANDS.has(command);\n\nconst missingString = (params: Record<string, unknown>, field: CanvasMissingIdentifier): boolean => {\n const value = params[field];\n return typeof value !== \"string\" || value.trim().length === 0;\n};\n\nexport const buildCanvasCommandValidationEnvelope = (\n command: string,\n params: Record<string, unknown>\n): CanvasRepairEnvelope | null => {\n if (requiresCanvasSessionId(command) && missingString(params, \"canvasSessionId\")) {\n return buildCanvasMissingIdentifierEnvelope(\"canvasSessionId\", command);\n }\n if (requiresLeaseId(command) && missingString(params, \"leaseId\")) {\n return buildCanvasMissingIdentifierEnvelope(\"leaseId\", command);\n }\n const repoPath = params.repoPath;\n const hasRepoPath = typeof repoPath === \"string\" && repoPath.trim().length > 0;\n if (command === \"canvas.document.load\" && missingString(params, \"documentId\") && !hasRepoPath) {\n return buildCanvasMissingIdentifierEnvelope(\"documentId\", command);\n }\n return null;\n};\n\nexport const buildCanvasMissingIdentifierEnvelope = (\n field: CanvasMissingIdentifier,\n blockedCommand?: string\n): CanvasRepairEnvelope => {\n const reasonCode = missingIdentifierReasonCode(field);\n return buildCanvasRepairEnvelope({\n reasonCode,\n ...(blockedCommand ? { blockedCommand } : {}),\n message: `Missing ${field}. ${titleForReason(reasonCode)}`\n });\n};\n","import { buildCanvasPlanSetParamsExample, buildCanvasRepairGuidance } from \"../../canvas/repair-examples\";\nimport { normalizePinterestReferenceUrl } from \"./pinterest\";\nimport type { CanvasGenerationPlanIssue } from \"../../canvas/types\";\nimport type {\n GuidanceCommandExample,\n GuidanceContext,\n GuidanceFallbackPolicy,\n GuidanceRecipe,\n GuidanceReadiness,\n NextStepGuidance\n} from \"../types\";\n\nconst quote = (value: string): string => JSON.stringify(value);\n\nconst DAEMON_STATUS_PREFLIGHT_COMMAND = \"opendevbrowser status --daemon --output-format json\";\nconst DAEMON_FINGERPRINT_CURRENT_ASSERTION = \"data.fingerprintCurrent === true\";\nconst DEFAULT_INSPIREDESIGN_BRIEF = \"Digital photography studio landing page\";\nconst DEFAULT_INSPIREDESIGN_QUERY = \"cinematic photography studio landing page inspiration\";\nconst DEFAULT_RESEARCH_TOPIC = \"browser automation provider recovery\";\nconst DEFAULT_PROVIDER = \"provider diagnostics\";\nconst DEFAULT_PINTEREST_REFERENCE_URL = \"https://www.pinterest.com/pin/27654985208435505/\";\n\nconst isCanvasGenerationPlanIssue = (value: unknown): value is CanvasGenerationPlanIssue => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const record = value as Record<string, unknown>;\n return typeof record.path === \"string\"\n && typeof record.message === \"string\"\n && typeof record.code === \"string\";\n};\n\nconst canvasGenerationPlanIssues = (value: unknown): CanvasGenerationPlanIssue[] => (\n Array.isArray(value) ? value.filter(isCanvasGenerationPlanIssue) : []\n);\n\nconst isPinterestProvider = (provider: string): boolean => provider === \"social/pinterest\" || provider === \"pinterest\";\n\nconst isPinterestOnlyContext = (context: GuidanceContext): boolean => {\n const providers = context.requestedProviders ?? [];\n return providers.length === 0 || providers.every(isPinterestProvider);\n};\n\nconst selectedInspiredesignProvider = (context: GuidanceContext): string => {\n const providers = context.requestedProviders ?? [];\n const nonPinterestProvider = providers.find((provider) => !isPinterestProvider(provider));\n if (!isPinterestOnlyContext(context) && nonPinterestProvider) return nonPinterestProvider;\n return providers[0] ?? context.siteRecipeId ?? \"web/default\";\n};\n\nconst selectedProviderIsPinterest = (context: GuidanceContext): boolean => (\n isPinterestProvider(selectedInspiredesignProvider(context))\n);\n\nconst isPinterestScopedRecovery = (context: GuidanceContext): boolean => (\n context.siteRecipeId === \"social/pinterest\"\n && isPinterestOnlyContext(context)\n);\n\nconst inspiredesignBrowserMode = (context: GuidanceContext): string =>\n selectedProviderIsPinterest(context) ? \"extension\" : context.browserMode ?? \"managed\";\n\nconst inspiredesignCookieFlags = (context: GuidanceContext): string => {\n if (selectedProviderIsPinterest(context)) return \" --use-cookies --cookie-policy required\";\n return context.useCookies === true ? \" --use-cookies\" : \"\";\n};\n\nconst pinterestRecoveryUrls = (context: GuidanceContext): string[] => {\n if (!isPinterestScopedRecovery(context)) return [];\n const urls = context.referenceUrls ?? [];\n const canonicalUrls = urls\n .map(normalizePinterestReferenceUrl)\n .filter((url): url is string => url !== null);\n return [...new Set(canonicalUrls)];\n};\n\nconst inspiredesignRecoveryExampleUrls = (context: GuidanceContext): string[] => (\n selectedProviderIsPinterest(context)\n ? [DEFAULT_PINTEREST_REFERENCE_URL]\n : [\"https://example.com/usable-reference\"]\n);\n\nconst inspiredesignHarvestCommand = (context: GuidanceContext): GuidanceCommandExample => {\n const brief = typeof context.details?.brief === \"string\" ? context.details.brief : DEFAULT_INSPIREDESIGN_BRIEF;\n const query = context.query ?? DEFAULT_INSPIREDESIGN_QUERY;\n const provider = selectedInspiredesignProvider(context);\n const browserMode = inspiredesignBrowserMode(context);\n const cookieFlags = inspiredesignCookieFlags(context);\n const urls = pinterestRecoveryUrls(context);\n if (urls.length > 0) {\n const urlFlags = urls.map((url) => `--url ${quote(url)}`).join(\" \");\n return {\n id: \"inspiredesign-harvest-url-recovery\",\n label: \"Recover Inspired Design harvest with explicit Pinterest URLs\",\n command: `npx opendevbrowser inspiredesign harvest --brief ${quote(brief)} --provider social/pinterest ${urlFlags} --max-references 5 --visual-evidence required --browser-mode extension --use-cookies --cookie-policy required --challenge-automation-mode browser_with_helper --mode json --output-format json`\n };\n }\n return {\n id: \"inspiredesign-harvest-rerun\",\n label: \"Rerun Inspired Design harvest with explicit evidence settings\",\n command: `npx opendevbrowser inspiredesign harvest --brief ${quote(brief)} --query ${quote(query)} --provider ${provider} --max-references 5 --visual-evidence required --browser-mode ${browserMode}${cookieFlags} --challenge-automation-mode browser_with_helper --mode json --output-format json`\n };\n};\n\nconst canvasSessionOpenCommand: GuidanceCommandExample = {\n id: \"canvas-session-open\",\n label: \"Open a Canvas session before submitting the plan\",\n command: \"npx opendevbrowser canvas --command canvas.session.open --output-format json\"\n};\n\nconst canvasPlanSetCommand: GuidanceCommandExample = {\n id: \"canvas-plan-set\",\n label: \"Submit the generated Canvas plan request after filling ids\",\n command: \"npx opendevbrowser canvas --command canvas.plan.set --params-file ./canvas-plan.request.json --output-format json\"\n};\n\nconst defaultFallbackPolicy: GuidanceFallbackPolicy = {\n allowed: false,\n requiresUserConfirmation: true,\n reason: \"Do not widen provider or source scope without user confirmation.\"\n};\n\nconst inspiredesignArtifacts = [\n { path: \"advanced-brief.md\", purpose: \"Review the reference-first brief before design or implementation.\", required: true },\n { path: \"ranked-references.json\", purpose: \"Verify ranked evidence quality and rejected diagnostics.\", required: true },\n { path: \"visual-evidence.json\", purpose: \"Confirm screenshot metadata and warnings.\", required: true },\n { path: \"screenshot-index.json\", purpose: \"Confirm screenshot artifact paths exist before visual claims.\", required: true }\n] as const;\n\nconst requiresInspiredesignReferenceEvidence = (context: GuidanceContext): boolean => (\n context.evidence?.referenceEvidenceRequired !== false\n);\n\nconst notReadyInspiredesignReasonCode = (context: GuidanceContext): string => (\n context.evidence?.topReferenceIntentMatched === false ? \"off_brief_reference\" : \"weak_reference\"\n);\n\nconst notReadyInspiredesignSummary = (reasonCode: string): string => (\n reasonCode === \"off_brief_reference\"\n ? \"The workflow requested a design-ready handoff, but the top ranked reference is off brief for Canvas continuation.\"\n : \"The workflow requested a design-ready handoff, but the evidence does not meet the ready threshold for Canvas continuation.\"\n);\n\nconst buildReadyInspiredesignGuidance = (context: GuidanceContext, readiness: GuidanceReadiness): NextStepGuidance => {\n if (readiness !== \"ready\") {\n const reasonCode = notReadyInspiredesignReasonCode(context);\n return buildEvidenceRecoveryGuidance(\n context,\n readiness,\n reasonCode,\n reasonCode === \"off_brief_reference\" ? \"Replace off-brief reference evidence\" : \"Strengthen reference evidence before Canvas\",\n notReadyInspiredesignSummary(reasonCode)\n );\n }\n const referenceEvidenceRequired = requiresInspiredesignReferenceEvidence(context);\n const artifactInputs = referenceEvidenceRequired\n ? [...inspiredesignArtifacts, { path: \"canvas-plan.request.json\", purpose: \"Runtime request body for canvas.plan.set.\", required: true }]\n : [\n { path: \"advanced-brief.md\", purpose: \"Review the brief-expanded design direction before Canvas.\", required: true },\n { path: \"design-contract.json\", purpose: \"Use the brief-derived Canvas governance contract.\", required: true },\n { path: \"canvas-plan.request.json\", purpose: \"Runtime request body for canvas.plan.set.\", required: true }\n ];\n const validationChecks = referenceEvidenceRequired\n ? [{\n id: \"plan-accepted\",\n description: \"canvas.plan.set returns planStatus=accepted before document mutation.\",\n assertion: \"planStatus === \\\"accepted\\\"\"\n }]\n : [{\n id: \"brief-contract-accepted\",\n description: \"canvas.plan.set accepts the generated brief-only generationPlan before document mutation.\",\n assertion: \"planStatus === \\\"accepted\\\"\"\n }];\n const doNotProceedIf = referenceEvidenceRequired\n ? [\n \"rankedReferences is empty\",\n \"screenshot paths are missing when visual evidence was required\",\n \"planStatus is not accepted\"\n ]\n : [\n \"advanced-brief.md or design-contract.json is missing\",\n \"planStatus is not accepted\"\n ];\n return {\n id: \"inspiredesign.canvas_ready_handoff\",\n recipeType: \"artifact_handoff\",\n workflow: \"inspiredesign\",\n severity: \"info\",\n readiness,\n reasonCode: \"design_ready\",\n primaryAction: {\n id: \"continue_in_canvas\",\n label: \"Continue in Canvas\",\n summary: \"Read the generated artifacts, open a Canvas session, fill canvas-plan.request.json ids, then submit canvas.plan.set.\"\n },\n commands: [canvasSessionOpenCommand, canvasPlanSetCommand],\n paramsExamples: [{\n id: \"canvas-plan-request-ids\",\n label: \"Canvas plan request id placeholders to fill\",\n command: \"canvas.plan.set\",\n params: {\n canvasSessionId: \"<canvasSessionId from canvas.session.open>\",\n leaseId: \"<leaseId from canvas.session.open>\",\n generationPlan: \"<keep generated generationPlan object unchanged>\"\n }\n }],\n fieldExamples: [{\n path: \"intent\",\n description: \"Patch emitted governance blocks from design-contract.json after plan acceptance.\",\n example: { audience: \"Primary user\", task: \"Complete the design goal\", successCriteria: [\"Evidence-backed design direction is implemented\"] }\n }],\n artifactInputs,\n validationChecks,\n fallbackPolicy: {\n allowed: true,\n requiresUserConfirmation: false,\n reason: referenceEvidenceRequired\n ? \"Canvas continuation is allowed because ranked reference evidence is ready.\"\n : \"Canvas continuation is allowed because this brief-only run did not require reference evidence.\"\n },\n doNotProceedIf\n };\n};\n\nconst buildDaemonFingerprintMismatchGuidance = (readiness: GuidanceReadiness): NextStepGuidance => ({\n id: \"daemon.fingerprint_mismatch\",\n recipeType: \"workflow_entry\",\n workflow: \"daemon\",\n severity: \"blocked\",\n readiness,\n reasonCode: \"daemon_fingerprint_mismatch\",\n primaryAction: {\n id: \"verify_daemon_fingerprint\",\n label: \"Verify daemon fingerprint\",\n summary: \"Run the daemon status preflight and continue only when the running daemon matches the current opendevbrowser build.\"\n },\n commands: [{\n id: \"daemon-status-preflight\",\n label: \"Check daemon fingerprint freshness\",\n command: DAEMON_STATUS_PREFLIGHT_COMMAND\n }],\n paramsExamples: [],\n fieldExamples: [{\n path: \"data.fingerprintCurrent\",\n description: \"The daemon status response must report the current build fingerprint.\",\n example: true,\n expected: \"true\"\n }],\n artifactInputs: [],\n validationChecks: [{\n id: \"fingerprint-current\",\n description: \"Daemon status confirms the binary and daemon fingerprint match.\",\n assertion: DAEMON_FINGERPRINT_CURRENT_ASSERTION,\n command: DAEMON_STATUS_PREFLIGHT_COMMAND\n }],\n fallbackPolicy: {\n allowed: true,\n requiresUserConfirmation: false,\n reason: \"Use the matching binary, restart the daemon from the current install, or isolate config, cache, daemon port, and relay port.\"\n },\n doNotProceedIf: [\n \"data.fingerprintCurrent is false or missing\",\n \"the daemon is still running a different opendevbrowser build\"\n ]\n});\n\nconst buildResearchGatedProviderGuidance = (\n context: GuidanceContext,\n readiness: GuidanceReadiness\n): NextStepGuidance => {\n const topic = typeof context.details?.topic === \"string\" ? context.details.topic : DEFAULT_RESEARCH_TOPIC;\n const browserMode = context.browserMode ?? \"extension\";\n const cookieFlag = context.useCookies === true ? \" --use-cookies\" : \"\";\n const providers = context.requestedProviders?.length ? context.requestedProviders.join(\", \") : \"gated providers\";\n return {\n id: \"research.gated_provider_recovery\",\n recipeType: \"evidence_recovery\",\n workflow: \"research\",\n severity: \"warning\",\n readiness,\n reasonCode: \"gated_provider\",\n primaryAction: {\n id: \"recover_gated_provider_evidence\",\n label: \"Recover gated provider evidence\",\n summary: `Inspect gated-provider diagnostics for ${providers}, then rerun research with a user-authorized signed-in browser session before publishing claims.`\n },\n commands: [{\n id: \"research-gated-provider-rerun\",\n label: \"Rerun research with browser-scoped provider recovery\",\n command: `npx opendevbrowser research run --topic ${quote(topic)} --days 14 --sources web,community --browser-mode ${browserMode}${cookieFlag} --challenge-automation-mode browser_with_helper --mode json --output-format json`\n }],\n paramsExamples: [{\n id: \"research-gated-provider-input\",\n label: \"Research gated-provider retry input\",\n params: {\n topic,\n browserMode,\n useCookies: context.useCookies === true,\n challengeAutomationMode: \"browser_with_helper\",\n providers\n }\n }],\n fieldExamples: [{\n path: \"meta.failures[].error.reasonCode\",\n description: \"Gated provider failures should identify auth or challenge reason codes before retry.\",\n example: \"auth_required\"\n }],\n artifactInputs: [\n { path: \"records.json\", purpose: \"Confirm destination records support claims.\", required: true },\n { path: \"context.json\", purpose: \"Inspect source and timebox context.\", required: true },\n { path: \"meta.json\", purpose: \"Review failures, cookie diagnostics, and challenge orchestration metadata.\", required: true },\n { path: \"report.md\", purpose: \"Publish only claims supported by accepted records.\", required: true }\n ],\n validationChecks: [\n { id: \"signed-in-session\", description: \"Provider auth or challenge state has been resolved in the browser session.\" },\n { id: \"records-supported\", description: \"Final claims are supported by destination records, not SERP snippets.\" }\n ],\n fallbackPolicy: {\n allowed: false,\n requiresUserConfirmation: true,\n reason: \"Do not switch sources or publish unsupported claims without user approval.\"\n },\n doNotProceedIf: [\n \"gated provider failures remain unresolved\",\n \"records.json lacks destination evidence for the claim\",\n \"cookie or challenge recovery has not been user-authorized\"\n ]\n };\n};\n\nconst buildProviderWorkflowGuidance = (\n context: GuidanceContext,\n readiness: GuidanceReadiness\n): NextStepGuidance => {\n const providers = context.requestedProviders?.join(\", \") || DEFAULT_PROVIDER;\n const reasonCode = context.reasonCode ?? \"provider_recovery\";\n return {\n id: `provider.${reasonCode}`,\n recipeType: \"evidence_recovery\",\n workflow: \"provider\",\n severity: readiness === \"blocked\" ? \"blocked\" : \"warning\",\n readiness,\n reasonCode,\n primaryAction: {\n id: \"inspect_provider_diagnostics\",\n label: \"Inspect provider diagnostics\",\n summary: \"Use the typed failure details to resolve auth, challenge, availability, or evidence-quality blockers before widening provider scope.\"\n },\n commands: [{\n id: \"provider-diagnostic-rerun\",\n label: \"Show executable workflow help before rerunning\",\n command: \"npx opendevbrowser help\"\n }],\n paramsExamples: [{\n id: \"provider-recovery-input\",\n label: \"Provider recovery input\",\n params: {\n providers,\n reasonCode,\n browserMode: context.browserMode ?? \"extension\",\n useCookies: context.useCookies === true\n }\n }],\n fieldExamples: [{\n path: \"meta.failures[].error.reasonCode\",\n description: \"Use the provider reason code to choose auth, challenge, availability, or evidence recovery.\",\n example: reasonCode\n }],\n artifactInputs: [\n { path: \"meta.json\", purpose: \"Inspect provider diagnostics and reason codes.\", required: true },\n { path: \"records.json\", purpose: \"Confirm accepted destination records before using results.\", required: true }\n ],\n validationChecks: [{\n id: \"provider-evidence-ready\",\n description: \"At least one accepted record supports the workflow output before proceeding.\"\n }],\n fallbackPolicy: defaultFallbackPolicy,\n doNotProceedIf: [\n \"provider failure reason codes remain unresolved\",\n \"accepted records are empty\",\n \"the requested provider scope would be widened without user confirmation\"\n ]\n };\n};\n\nconst buildCliValidationGuidance = (\n context: GuidanceContext,\n readiness: GuidanceReadiness\n): NextStepGuidance => {\n const reasonCode = context.reasonCode ?? \"validation_error\";\n return {\n id: `cli.${reasonCode}`,\n recipeType: \"schema_repair\",\n workflow: \"cli\",\n severity: \"blocked\",\n readiness,\n reasonCode,\n primaryAction: {\n id: \"repair_cli_arguments\",\n label: \"Repair CLI arguments\",\n summary: \"Use the command help and typed error details to rerun with valid flags, params, and output mode.\"\n },\n commands: [{\n id: \"cli-help\",\n label: \"Show command help\",\n command: \"npx opendevbrowser help\"\n }],\n paramsExamples: [{\n id: \"cli-validation-input\",\n label: \"CLI validation retry\",\n params: {\n reasonCode,\n outputFormat: \"json\"\n }\n }],\n fieldExamples: [{\n path: \"error.reasonCode\",\n description: \"The reason code identifies which CLI argument or params field must be repaired.\",\n example: reasonCode\n }],\n artifactInputs: [],\n validationChecks: [{\n id: \"json-output\",\n description: \"Rerun the command with --output-format json and verify the response has no validation errors.\"\n }],\n fallbackPolicy: {\n allowed: true,\n requiresUserConfirmation: false,\n reason: \"Help output and typed examples are the supported recovery path for invalid CLI input.\"\n },\n doNotProceedIf: [\n \"the command still returns validation errors\",\n \"required params are missing or empty\"\n ]\n };\n};\n\nconst buildEvidenceRecoveryGuidance = (\n context: GuidanceContext,\n readiness: GuidanceReadiness,\n reasonCode: string,\n actionLabel: string,\n actionSummary: string\n): NextStepGuidance => ({\n id: `inspiredesign.harvest.${reasonCode}`,\n recipeType: \"evidence_recovery\",\n workflow: \"inspiredesign\",\n severity: readiness === \"blocked\" ? \"blocked\" : \"warning\",\n readiness,\n reasonCode,\n primaryAction: {\n id: \"recover_reference_evidence\",\n label: actionLabel,\n summary: actionSummary\n },\n commands: [inspiredesignHarvestCommand(context)],\n paramsExamples: [{\n id: \"explicit-reference-url-recovery\",\n label: \"Use explicit high-quality visual references when provider discovery is blocked\",\n params: {\n brief: typeof context.details?.brief === \"string\" ? context.details.brief : DEFAULT_INSPIREDESIGN_BRIEF,\n urls: inspiredesignRecoveryExampleUrls(context),\n visualEvidence: \"required\",\n browserMode: inspiredesignBrowserMode(context),\n ...(selectedProviderIsPinterest(context) ? { useCookies: true, cookiePolicy: \"required\" } : {})\n }\n }],\n fieldExamples: [],\n artifactInputs: inspiredesignArtifacts.map((artifact) => ({ ...artifact, required: false })),\n validationChecks: [\n { id: \"ranked-reference-count\", description: \"At least one ranked reference is present.\", assertion: \"rankedReferences.length > 0\" },\n { id: \"reference-score\", description: \"The top reference score meets the ready threshold.\", assertion: \"topReferenceScore >= 50\" },\n { id: \"reference-intent\", description: \"The top ranked reference overlaps the requested brief intent.\", assertion: \"topReferenceIntentMatched === true\" },\n { id: \"visual-artifact\", description: \"Required visual evidence has finalized screenshot paths.\", assertion: \"missingScreenshotCount === 0\" }\n ],\n fallbackPolicy: defaultFallbackPolicy,\n doNotProceedIf: [\n \"reference_count is 0\",\n \"rankedReferences is empty\",\n \"top ranked reference is diagnostic-only or off brief\",\n \"required visual evidence is missing or failed\"\n ]\n});\n\nexport const genericGuidanceRecipes: GuidanceRecipe[] = [\n {\n id: \"provider.generic_recovery\",\n recipeType: \"evidence_recovery\",\n workflow: \"provider\",\n priority: 130,\n reasonCode: \"provider_recovery\",\n matches: (context) => context.workflow === \"provider\",\n build: buildProviderWorkflowGuidance\n },\n {\n id: \"cli.validation_recovery\",\n recipeType: \"schema_repair\",\n workflow: \"cli\",\n priority: 125,\n reasonCode: \"validation_error\",\n matches: (context) => context.workflow === \"cli\",\n build: buildCliValidationGuidance\n },\n {\n id: \"daemon.fingerprint_mismatch\",\n recipeType: \"workflow_entry\",\n workflow: \"daemon\",\n priority: 120,\n reasonCode: \"daemon_fingerprint_mismatch\",\n matches: (context) => context.workflow === \"daemon\" && context.reasonCode === \"daemon_fingerprint_mismatch\",\n build: (_context, readiness) => buildDaemonFingerprintMismatchGuidance(readiness)\n },\n {\n id: \"research.gated_provider\",\n recipeType: \"evidence_recovery\",\n workflow: \"research\",\n priority: 110,\n reasonCode: \"gated_provider\",\n matches: (context) => context.workflow === \"research\" && context.reasonCode === \"gated_provider\",\n build: buildResearchGatedProviderGuidance\n },\n {\n id: \"canvas.generation_plan_invalid\",\n recipeType: \"schema_repair\",\n workflow: \"canvas\",\n priority: 100,\n reasonCode: \"generation_plan_invalid\",\n matches: (context) => context.workflow === \"canvas\" && context.reasonCode === \"generation_plan_invalid\",\n build: (context) => buildCanvasRepairGuidance({\n reasonCode: \"generation_plan_invalid\",\n missingFields: Array.isArray(context.details?.missingFields)\n ? context.details.missingFields.filter((field): field is string => typeof field === \"string\")\n : [],\n issues: canvasGenerationPlanIssues(context.details?.issues)\n })\n },\n {\n id: \"canvas.plan_required\",\n recipeType: \"schema_repair\",\n workflow: \"canvas\",\n priority: 90,\n reasonCode: \"plan_required\",\n matches: (context) => context.workflow === \"canvas\" && context.reasonCode === \"plan_required\",\n build: () => buildCanvasRepairGuidance({ reasonCode: \"plan_required\" })\n },\n {\n id: \"canvas.governance_missing\",\n recipeType: \"schema_repair\",\n workflow: \"canvas\",\n priority: 80,\n reasonCode: \"governance_missing\",\n matches: (context) => context.workflow === \"canvas\" && context.reasonCode === \"governance_missing\",\n build: () => buildCanvasRepairGuidance({ reasonCode: \"governance_missing\" })\n },\n {\n id: \"canvas.missing_canvas_session_id\",\n recipeType: \"schema_repair\",\n workflow: \"canvas\",\n priority: 70,\n reasonCode: \"missing_canvas_session_id\",\n matches: (context) => context.workflow === \"canvas\" && context.reasonCode === \"missing_canvas_session_id\",\n build: () => buildCanvasRepairGuidance({ reasonCode: \"missing_canvas_session_id\" })\n },\n {\n id: \"canvas.missing_lease_id\",\n recipeType: \"schema_repair\",\n workflow: \"canvas\",\n priority: 60,\n reasonCode: \"missing_lease_id\",\n matches: (context) => context.workflow === \"canvas\" && context.reasonCode === \"missing_lease_id\",\n build: () => buildCanvasRepairGuidance({ reasonCode: \"missing_lease_id\" })\n },\n {\n id: \"canvas.missing_document_id\",\n recipeType: \"schema_repair\",\n workflow: \"canvas\",\n priority: 50,\n reasonCode: \"missing_document_id\",\n matches: (context) => context.workflow === \"canvas\" && context.reasonCode === \"missing_document_id\",\n build: () => buildCanvasRepairGuidance({ reasonCode: \"missing_document_id\" })\n },\n {\n id: \"inspiredesign.pinterest.browser_native_recovery\",\n recipeType: \"site_navigation\",\n workflow: \"inspiredesign\",\n priority: 100,\n reasonCode: \"pinterest_browser_native_recovery\",\n matches: (context) => context.workflow === \"inspiredesign\"\n && isPinterestScopedRecovery(context)\n && context.reasonCode !== \"design_ready\",\n build: (context, readiness) => buildEvidenceRecoveryGuidance(\n context,\n readiness,\n \"pinterest_browser_native_recovery\",\n \"Recover Pinterest evidence in an authenticated browser session\",\n \"Use the Pinterest browser-native recipe to verify login, search the brief on Pinterest, collect usable pins or boards, and reject login, challenge, empty-grid, and search-shell pages before Canvas.\"\n )\n },\n {\n id: \"inspiredesign.provider_unavailable\",\n recipeType: \"evidence_recovery\",\n workflow: \"inspiredesign\",\n priority: 90,\n reasonCode: \"provider_unavailable\",\n matches: (context) => context.workflow === \"inspiredesign\" && context.reasonCode === \"provider_unavailable\",\n build: (context, readiness) => buildEvidenceRecoveryGuidance(\n context,\n readiness,\n \"provider_unavailable\",\n \"Recover provider evidence\",\n \"Resolve the requested provider lane or supply explicit usable reference URLs before continuing to Canvas.\"\n )\n },\n {\n id: \"inspiredesign.diagnostic_only\",\n recipeType: \"quality_gate\",\n workflow: \"inspiredesign\",\n priority: 80,\n reasonCode: \"diagnostic_only\",\n matches: (context) => context.workflow === \"inspiredesign\" && context.reasonCode === \"diagnostic_only\",\n build: (context, readiness) => buildEvidenceRecoveryGuidance(\n context,\n readiness,\n \"diagnostic_only\",\n \"Replace diagnostic references\",\n \"The harvest captured diagnostic or blocked pages. Replace them with usable creative references before Canvas.\"\n )\n },\n {\n id: \"inspiredesign.zero_references\",\n recipeType: \"evidence_recovery\",\n workflow: \"inspiredesign\",\n priority: 70,\n reasonCode: \"zero_references\",\n matches: (context) => context.workflow === \"inspiredesign\" && context.reasonCode === \"zero_references\",\n build: (context, readiness) => buildEvidenceRecoveryGuidance(\n context,\n readiness,\n \"zero_references\",\n \"Collect reference evidence\",\n \"The harvest produced no references. Run source-specific discovery or provide explicit URLs before Canvas.\"\n )\n },\n {\n id: \"inspiredesign.failed_capture\",\n recipeType: \"evidence_recovery\",\n workflow: \"inspiredesign\",\n priority: 60,\n reasonCode: \"failed_capture\",\n matches: (context) => context.workflow === \"inspiredesign\" && context.reasonCode === \"failed_capture\",\n build: (context, readiness) => buildEvidenceRecoveryGuidance(\n context,\n readiness,\n \"failed_capture\",\n \"Retry capture with a usable browser session\",\n \"Deep capture or required visual evidence failed. Restore session state or use explicit references with capturable pages.\"\n )\n },\n {\n id: \"inspiredesign.zero_ranked_references\",\n recipeType: \"evidence_recovery\",\n workflow: \"inspiredesign\",\n priority: 55,\n reasonCode: \"zero_ranked_references\",\n matches: (context) => context.workflow === \"inspiredesign\" && context.reasonCode === \"zero_ranked_references\",\n build: (context, readiness) => buildEvidenceRecoveryGuidance(\n context,\n readiness,\n \"zero_ranked_references\",\n \"Replace rejected reference evidence\",\n \"The harvest captured references, but none survived scoring. Replace rejected, off-brief, blocked, or diagnostic pages before Canvas.\"\n )\n },\n {\n id: \"inspiredesign.off_brief_reference\",\n recipeType: \"quality_gate\",\n workflow: \"inspiredesign\",\n priority: 52,\n reasonCode: \"off_brief_reference\",\n matches: (context) => context.workflow === \"inspiredesign\" && context.reasonCode === \"off_brief_reference\",\n build: (context, readiness) => buildEvidenceRecoveryGuidance(\n context,\n readiness,\n \"off_brief_reference\",\n \"Replace off-brief reference evidence\",\n \"The top ranked reference is captured, but its signals do not overlap the requested brief. Replace it with on-brief references before Canvas.\"\n )\n },\n {\n id: \"inspiredesign.weak_reference\",\n recipeType: \"quality_gate\",\n workflow: \"inspiredesign\",\n priority: 50,\n reasonCode: \"weak_reference\",\n matches: (context) => context.workflow === \"inspiredesign\" && context.reasonCode === \"weak_reference\",\n build: (context, readiness) => buildEvidenceRecoveryGuidance(\n context,\n readiness,\n \"weak_reference\",\n \"Strengthen weak reference evidence\",\n \"The harvest has ranked references, but their score or confidence is too weak for Canvas-first design handoff.\"\n )\n },\n {\n id: \"inspiredesign.ready\",\n recipeType: \"artifact_handoff\",\n workflow: \"inspiredesign\",\n priority: 1,\n reasonCode: \"design_ready\",\n matches: (context) => context.workflow === \"inspiredesign\" && context.reasonCode === \"design_ready\",\n build: buildReadyInspiredesignGuidance\n }\n];\n","import { classifyGuidanceReadiness } from \"./readiness\";\nimport { genericGuidanceRecipes } from \"./recipes/generic\";\nimport type { GuidanceContext, GuidanceRecipe, NextStepGuidance } from \"./types\";\n\nconst byPriority = (left: GuidanceRecipe, right: GuidanceRecipe): number => {\n return right.priority - left.priority || left.id.localeCompare(right.id);\n};\n\nexport class GuidanceRouter {\n private readonly recipes: GuidanceRecipe[];\n\n constructor(recipes: GuidanceRecipe[] = genericGuidanceRecipes) {\n this.recipes = recipes.slice().sort(byPriority);\n }\n\n route(context: GuidanceContext): NextStepGuidance {\n const readiness = classifyGuidanceReadiness(context);\n const recipe = this.recipes.find((candidate) => candidate.matches(context));\n if (!recipe) {\n throw new Error(`No guidance recipe matched workflow ${context.workflow}.`);\n }\n return recipe.build(context, readiness);\n }\n}\n\nexport const routeNextStepGuidance = (context: GuidanceContext): NextStepGuidance => {\n return new GuidanceRouter().route(context);\n};\n","import { INSPIREDESIGN_HANDOFF_GUIDANCE } from \"../inspiredesign/handoff\";\nimport { renderWorkflowCompatibility, renderWorkflowGuidance } from \"../guidance/renderers\";\nimport { routeNextStepGuidance } from \"../guidance/router\";\nimport type { NextStepGuidance } from \"../guidance/types\";\nimport { isProviderReasonCode, normalizeProviderReasonCode } from \"./errors\";\nimport type { JsonValue, ProviderFailureEntry, ProviderReasonCode } from \"./types\";\n\nexport type WorkflowSuccessStep = {\n reason: string;\n command?: string;\n};\n\nexport type WorkflowSuccessHandoff = {\n followthroughSummary: string;\n suggestedNextAction: string;\n suggestedSteps: WorkflowSuccessStep[];\n nextStepGuidance?: Record<string, JsonValue>;\n};\n\nexport const PRODUCT_VIDEO_BRIEF_HELPER_PATH = \"./skills/opendevbrowser-product-presentation-asset/scripts/render-video-brief.sh\";\n\nconst PRODUCT_VIDEO_BRIEF_HELPER_COMMAND = `${PRODUCT_VIDEO_BRIEF_HELPER_PATH} <pack>/manifest.json`;\n\nexport const createSuccessHandoff = (\n followthroughSummary: string,\n suggestedNextAction: string,\n suggestedSteps: WorkflowSuccessStep[]\n): WorkflowSuccessHandoff => ({\n followthroughSummary,\n suggestedNextAction,\n suggestedSteps\n});\n\nconst cliExample = (command: string, args: string): string => (\n `npx opendevbrowser ${command} ${args}`\n);\n\nconst quoteCliValue = (value: string): string => JSON.stringify(value);\n\ntype ResearchHandoffInput = {\n topic: string;\n browserMode?: string;\n failures?: ProviderFailureEntry[];\n cookieDiagnostics?: Array<Record<string, JsonValue>>;\n challengeOrchestration?: Array<Record<string, JsonValue>>;\n};\n\ntype ResearchRerunOptions = {\n browserMode?: string;\n useCookies?: boolean;\n challengeAutomationMode?: \"browser_with_helper\";\n};\n\ntype ResearchGatedProviderSignal = {\n providers: string[];\n reasonCodes: string[];\n useCookies: boolean;\n};\n\nconst GATED_PROVIDER_REASON_CODES = new Set<ProviderReasonCode>([\n \"auth_required\",\n \"token_required\",\n \"challenge_detected\"\n]);\n\nconst buildResearchRerunCommand = (\n input: ResearchHandoffInput,\n options: ResearchRerunOptions = {}\n): string => {\n const browserMode = options.browserMode ?? input.browserMode ?? \"managed\";\n const useCookies = options.useCookies ? \" --use-cookies\" : \"\";\n const challengeMode = options.challengeAutomationMode\n ? ` --challenge-automation-mode ${options.challengeAutomationMode}`\n : \"\";\n return cliExample(\n \"research run\",\n `--topic ${quoteCliValue(input.topic)} --days 14 --sources web,community --browser-mode ${browserMode}${useCookies}${challengeMode} --mode json --output-format json`\n );\n};\n\nconst isJsonRecord = (value: JsonValue | undefined): value is Record<string, JsonValue> => (\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value)\n);\n\nconst readFailureReasonCode = (failure: ProviderFailureEntry): ProviderReasonCode | null => {\n return failure.error.reasonCode\n ?? normalizeProviderReasonCode({\n code: failure.error.code,\n message: failure.error.message,\n details: failure.error.details\n })\n ?? null;\n};\n\nconst readDiagnosticReasonCode = (diagnostic: Record<string, JsonValue>): ProviderReasonCode | null => {\n const reasonCode = diagnostic.reasonCode ?? diagnostic.browserFallbackReasonCode;\n return isProviderReasonCode(reasonCode) && GATED_PROVIDER_REASON_CODES.has(reasonCode) ? reasonCode : null;\n};\n\nconst cookieDiagnosticShowsAvailableCookies = (diagnostic: Record<string, JsonValue>): boolean => {\n return diagnostic.available === true\n || (typeof diagnostic.loaded === \"number\" && diagnostic.loaded > 0)\n || (typeof diagnostic.injected === \"number\" && diagnostic.injected > 0)\n || (typeof diagnostic.verifiedCount === \"number\" && diagnostic.verifiedCount > 0);\n};\n\nconst addProviderSignal = (\n signal: ResearchGatedProviderSignal,\n provider: string | undefined,\n reasonCode: ProviderReasonCode | null\n): void => {\n if (provider) signal.providers.push(provider);\n if (reasonCode) signal.reasonCodes.push(reasonCode);\n};\n\nconst readFailureCookieDiagnostics = (failure: ProviderFailureEntry): Record<string, JsonValue> | null => {\n const candidate = failure.error.details?.cookieDiagnostics;\n return isJsonRecord(candidate) ? candidate : null;\n};\n\nconst emptyResearchGatedProviderSignal = (): ResearchGatedProviderSignal => ({\n providers: [],\n reasonCodes: [],\n useCookies: false\n});\n\nconst normalizeResearchGatedProviderSignal = (\n signal: ResearchGatedProviderSignal\n): ResearchGatedProviderSignal | null => {\n return signal.providers.length > 0 || signal.reasonCodes.length > 0 ? {\n providers: [...new Set(signal.providers)].sort(),\n reasonCodes: [...new Set(signal.reasonCodes)].sort(),\n useCookies: signal.useCookies\n } : null;\n};\n\nconst mergeResearchGatedProviderSignals = (\n signals: ResearchGatedProviderSignal[]\n): ResearchGatedProviderSignal => {\n const merged = emptyResearchGatedProviderSignal();\n for (const signal of signals) {\n merged.providers.push(...signal.providers);\n merged.reasonCodes.push(...signal.reasonCodes);\n merged.useCookies = merged.useCookies || signal.useCookies;\n }\n return merged;\n};\n\nconst detectResearchFailureSignals = (failures: ProviderFailureEntry[]): ResearchGatedProviderSignal => {\n const signal = emptyResearchGatedProviderSignal();\n for (const failure of failures) {\n const reasonCode = readFailureReasonCode(failure);\n const isGatedFailure = Boolean(reasonCode && GATED_PROVIDER_REASON_CODES.has(reasonCode));\n if (isGatedFailure) {\n addProviderSignal(signal, failure.provider, reasonCode);\n const diagnostic = readFailureCookieDiagnostics(failure);\n signal.useCookies = signal.useCookies || Boolean(diagnostic && cookieDiagnosticShowsAvailableCookies(diagnostic));\n }\n }\n return signal;\n};\n\nconst detectResearchCookieSignals = (\n diagnostics: Array<Record<string, JsonValue>>\n): ResearchGatedProviderSignal => {\n const signal = emptyResearchGatedProviderSignal();\n for (const diagnostic of diagnostics) {\n const reasonCode = readDiagnosticReasonCode(diagnostic);\n const isGatedDiagnostic = Boolean(reasonCode || diagnostic.policy === \"required\");\n if (isGatedDiagnostic) {\n addProviderSignal(signal, typeof diagnostic.provider === \"string\" ? diagnostic.provider : undefined, reasonCode);\n signal.useCookies = signal.useCookies || cookieDiagnosticShowsAvailableCookies(diagnostic);\n }\n }\n return signal;\n};\n\nconst detectResearchChallengeSignals = (\n diagnostics: Array<Record<string, JsonValue>>\n): ResearchGatedProviderSignal => {\n const signal = emptyResearchGatedProviderSignal();\n for (const diagnostic of diagnostics) {\n const reasonCode = readDiagnosticReasonCode(diagnostic);\n if (reasonCode || diagnostic.blockerType === \"auth_required\" || diagnostic.blockerType === \"anti_bot_challenge\") {\n addProviderSignal(signal, typeof diagnostic.provider === \"string\" ? diagnostic.provider : undefined, reasonCode);\n }\n }\n return signal;\n};\n\nconst detectResearchGatedProviderSignal = (input: ResearchHandoffInput): ResearchGatedProviderSignal | null => {\n return normalizeResearchGatedProviderSignal(mergeResearchGatedProviderSignals([\n detectResearchFailureSignals(input.failures ?? []),\n detectResearchCookieSignals(input.cookieDiagnostics ?? []),\n detectResearchChallengeSignals(input.challengeOrchestration ?? [])\n ]));\n};\n\nconst buildResearchRecoveryRerunCommand = (\n input: ResearchHandoffInput,\n signal: ResearchGatedProviderSignal\n): string => buildResearchRerunCommand(input, {\n browserMode: \"extension\",\n useCookies: signal.useCookies,\n challengeAutomationMode: \"browser_with_helper\"\n});\n\ntype ShoppingHandoffInput = {\n query: string;\n providers?: string[];\n budget?: number;\n region?: string;\n browserMode?: string;\n sort?: string;\n};\n\nconst buildShoppingRerunCommand = (input: ShoppingHandoffInput): string => {\n const providers = input.providers?.length\n ? ` --providers ${input.providers.join(\",\")}`\n : \" --providers shopping/bestbuy,shopping/ebay\";\n const budget = typeof input.budget === \"number\" ? ` --budget ${input.budget}` : \"\";\n const region = input.region ? ` --region ${quoteCliValue(input.region)}` : \"\";\n const browserMode = ` --browser-mode ${input.browserMode ?? \"managed\"}`;\n const sort = input.sort ? ` --sort ${input.sort}` : \"\";\n return cliExample(\n \"shopping run\",\n `--query ${quoteCliValue(input.query)}${providers}${budget}${region}${browserMode}${sort} --use-cookies --challenge-automation-mode browser_with_helper --mode json --output-format json`\n );\n};\n\ntype ProductVideoHandoffInput = {\n productUrl?: string;\n productName?: string;\n providerHint?: string;\n browserMode?: string;\n includeScreenshots?: boolean;\n includeAllImages?: boolean;\n includeCopy?: boolean;\n};\n\nconst buildProductVideoRerunCommand = (input: ProductVideoHandoffInput = {}): string => {\n const target = input.productUrl\n ? `--product-url ${quoteCliValue(input.productUrl)}`\n : `--product-name ${quoteCliValue(input.productName ?? \"<product-name>\")}`;\n const providerHint = input.providerHint ? ` --provider-hint ${input.providerHint}` : \"\";\n const screenshots = input.includeScreenshots ? \" --include-screenshots\" : \"\";\n const allImages = input.includeAllImages ? \" --include-all-images\" : \"\";\n const includeCopy = input.includeCopy ? \" --include-copy\" : \"\";\n const browserMode = ` --browser-mode ${input.browserMode ?? \"managed\"}`;\n return cliExample(\n \"product-video run\",\n `${target}${providerHint}${screenshots}${allImages}${includeCopy}${browserMode} --use-cookies --challenge-automation-mode browser_with_helper --output-format json`\n );\n};\n\ntype MacroResolveHandoffInput = {\n expression: string;\n defaultProvider?: string;\n execute: boolean;\n blocked: boolean;\n};\n\ntype InspiredesignSuccessHandoffInput = {\n summary: string;\n nextStep: string;\n commandExamples: {\n loadBestPractices: string;\n loadDesignAgent: string;\n loadMotionDesign: string;\n continueInCanvas: string;\n };\n deepCaptureRecommendation: string;\n nextStepGuidance?: NextStepGuidance;\n};\n\nconst extractPrimaryConstraintSentence = (summary: string): string | null => {\n const match = /^Primary constraint:\\s+(.+?\\.)\\s/.exec(summary);\n return match?.[1] ?? null;\n};\n\nconst buildMacroResolveArgs = (\n input: MacroResolveHandoffInput,\n options?: {\n execute?: boolean;\n browserMode?: \"extension\" | \"managed\";\n useCookies?: boolean;\n challengeAutomationMode?: \"browser\" | \"browser_with_helper\";\n cookiePolicyOverride?: \"off\" | \"auto\" | \"required\";\n }\n): string => {\n const defaultProvider = input.defaultProvider ? ` --default-provider ${input.defaultProvider}` : \"\";\n const execute = options?.execute ? \" --execute\" : \"\";\n const browserMode = options?.browserMode ? ` --browser-mode ${options.browserMode}` : \"\";\n const useCookies = options?.useCookies ? \" --use-cookies\" : \"\";\n const challenge = options?.challengeAutomationMode\n ? ` --challenge-automation-mode ${options.challengeAutomationMode}`\n : \"\";\n const cookiePolicy = options?.cookiePolicyOverride\n ? ` --cookie-policy ${options.cookiePolicyOverride}`\n : \"\";\n const outputFormat = \" --output-format json\";\n return `--expression ${quoteCliValue(input.expression)}${defaultProvider}${execute}${browserMode}${useCookies}${cookiePolicy}${challenge}${outputFormat}`;\n};\n\nconst buildMacroPreviewCommand = (input: MacroResolveHandoffInput): string => (\n cliExample(\"macro-resolve\", buildMacroResolveArgs(input))\n);\n\nconst buildMacroExecuteCommand = (\n input: MacroResolveHandoffInput,\n challengeAutomationMode?: \"browser\" | \"browser_with_helper\",\n browserMode?: \"extension\" | \"managed\"\n): string => (\n cliExample(\"macro-resolve\", buildMacroResolveArgs(input, {\n execute: true,\n browserMode,\n ...(browserMode === \"extension\" ? { useCookies: true, cookiePolicyOverride: \"required\" } : {}),\n challengeAutomationMode\n }))\n);\n\nconst buildResearchGatedSuccessHandoff = (\n input: ResearchHandoffInput,\n signal: ResearchGatedProviderSignal\n): WorkflowSuccessHandoff => {\n const recoveryCommand = buildResearchRecoveryRerunCommand(input, signal);\n const providers = signal.providers.length > 0 ? signal.providers.join(\", \") : \"gated providers\";\n const cookieNote = signal.useCookies\n ? \" The command includes --use-cookies because cookie diagnostics show available cookies.\"\n : \" Add --use-cookies only when legitimate provider cookies are available.\";\n const handoff = createSuccessHandoff(\n `Review ranked records, artifact metadata, and gated-provider diagnostics for ${providers} before publishing claims.`,\n `Open the returned artifact path, inspect records.json, context.json, meta.json, and report.md, then rerun ${recoveryCommand} only with a user-authorized signed-in relay session.${cookieNote}`,\n [\n { reason: \"Check records.json, context.json, meta.json, failures, and cookie diagnostics before using the result as evidence.\" },\n {\n reason: \"Rerun with an existing signed-in extension session and browser-scoped challenge assistance when gated providers blocked useful evidence.\",\n command: recoveryCommand\n },\n { reason: \"Keep SERPs discovery-only and publish only claims supported by destination records that passed review.\" }\n ]\n );\n const guidance = routeNextStepGuidance({\n workflow: \"research\",\n reasonCode: \"gated_provider\",\n requestedProviders: signal.providers,\n browserMode: \"extension\",\n useCookies: signal.useCookies,\n details: {\n topic: input.topic,\n reasonCodes: signal.reasonCodes\n }\n });\n return {\n ...handoff,\n nextStepGuidance: renderWorkflowGuidance(guidance)\n };\n};\n\nconst buildResearchDefaultSuccessHandoff = (input: ResearchHandoffInput): WorkflowSuccessHandoff => {\n const rerunCommand = buildResearchRerunCommand(input);\n return createSuccessHandoff(\n \"Review ranked records, artifact metadata, and source support before turning the result into a publishable claim.\",\n `Open the returned artifact path, inspect records.json, context.json, meta.json, and report.md, then rerun ${rerunCommand} if you need a tighter evidence set.`,\n [\n { reason: \"Check which ranked records and artifact metadata actually support the final claim.\" },\n {\n reason: \"Rerun with explicit sources and a narrower timebox if the evidence set is still too broad.\",\n command: rerunCommand\n }\n ]\n );\n};\n\nexport const buildResearchSuccessHandoff = (input: ResearchHandoffInput): WorkflowSuccessHandoff => {\n const signal = detectResearchGatedProviderSignal(input);\n return signal\n ? buildResearchGatedSuccessHandoff(input, signal)\n : buildResearchDefaultSuccessHandoff(input);\n};\n\nexport const buildShoppingSuccessHandoff = (input: ShoppingHandoffInput): WorkflowSuccessHandoff => {\n const rerunCommand = buildShoppingRerunCommand(input);\n return createSuccessHandoff(\n \"Review the offer set and diagnostics before calling any result a strong deal.\",\n `Inspect the offers and meta.offerFilterDiagnostics, then rerun ${rerunCommand} if you need a tighter comparison.`,\n [\n { reason: \"Check which offers survived the workflow filters and why.\" },\n {\n reason: \"Rerun with explicit providers or updated budget and region inputs if the comparison is still noisy.\",\n command: rerunCommand\n }\n ]\n );\n};\n\nexport const buildProductVideoSuccessHandoff = (input: ProductVideoHandoffInput = {}): WorkflowSuccessHandoff => {\n const rerunCommand = buildProductVideoRerunCommand(input);\n return createSuccessHandoff(\n \"Review the generated asset pack to confirm whether it is visual-ready or metadata-first before briefing production.\",\n \"Open the returned pack path, inspect manifest.json plus copy and features, then run the product-video brief helper with that manifest path to generate production briefs and sourcing notes.\",\n [\n { reason: \"Confirm whether the pack already includes enough images or screenshots for production.\" },\n {\n reason: \"Run the product-presentation-asset brief helper on manifest.json to generate the production brief files.\",\n command: PRODUCT_VIDEO_BRIEF_HELPER_COMMAND\n },\n {\n reason: \"Rerun the asset workflow with adjusted provider or media flags when the current pack is too thin.\",\n command: rerunCommand\n },\n { reason: \"Source or capture visuals before final handoff if the pack is metadata-first.\" }\n ]\n );\n};\n\nexport const buildMacroResolveSuccessHandoff = (input: MacroResolveHandoffInput): WorkflowSuccessHandoff => {\n const previewCommand = buildMacroPreviewCommand(input);\n const executeCommand = buildMacroExecuteCommand(input);\n const browserRetryCommand = buildMacroExecuteCommand(input, \"browser_with_helper\", \"extension\");\n if (!input.execute) {\n return createSuccessHandoff(\n \"Review the resolved provider action and provenance before executing the macro.\",\n `Run ${executeCommand} when the resolved action looks correct.`,\n [\n { reason: \"Inspect resolution.action and resolution.provenance to confirm provider and query shaping.\" },\n { reason: \"Execute the resolved macro once the plan looks correct.\", command: executeCommand },\n { reason: \"Add --default-provider only when you need to force a different provider lane.\", command: previewCommand }\n ]\n );\n }\n if (input.blocked) {\n return createSuccessHandoff(\n \"Review execution.meta.blocker and failures before retrying the macro.\",\n `Run ${browserRetryCommand} after checking execution.meta.blocker and the current recovery path.`,\n [\n { reason: \"Inspect execution.meta.blocker and execution.failures before retrying.\" },\n { reason: \"Retry with browser-scoped challenge automation when the blocker requires live follow-up.\", command: browserRetryCommand },\n { reason: \"Preview the resolved action again if you need to switch providers before another execute attempt.\", command: previewCommand }\n ]\n );\n }\n return createSuccessHandoff(\n \"Review execution.records and trace metadata before widening the macro or changing providers.\",\n `Inspect execution.records and execution.meta, then rerun ${previewCommand} if you need a narrower plan.`,\n [\n { reason: \"Inspect execution.records and execution.meta to confirm the resolved action hit the expected lane.\" },\n { reason: \"Preview the macro again before changing providers or expression scope.\", command: previewCommand },\n { reason: \"Re-execute with browser-scoped challenge automation when the target requires live browser recovery.\", command: browserRetryCommand }\n ]\n );\n};\n\nexport const buildInspiredesignSuccessHandoff = (\n input: InspiredesignSuccessHandoffInput\n): WorkflowSuccessHandoff => {\n if (input.nextStepGuidance && input.nextStepGuidance.readiness !== \"ready\") {\n const primaryConstraint = extractPrimaryConstraintSentence(input.summary);\n const summary = primaryConstraint\n ? `Primary constraint: ${primaryConstraint} ${input.nextStepGuidance.primaryAction.summary}`\n : undefined;\n const compatibility = renderWorkflowCompatibility(input.nextStepGuidance, summary);\n return {\n ...compatibility,\n nextStepGuidance: renderWorkflowGuidance(input.nextStepGuidance)\n };\n }\n const handoff = createSuccessHandoff(\n input.summary,\n input.nextStep,\n [\n { reason: INSPIREDESIGN_HANDOFF_GUIDANCE.reviewAdvancedBrief },\n {\n reason: \"Load the baseline workflow runbook before implementation.\",\n command: input.commandExamples.loadBestPractices\n },\n {\n reason: \"Load the Canvas contract lane before patching.\",\n command: input.commandExamples.loadDesignAgent\n },\n {\n reason: \"Load the motion-design lane before translating visual evidence into animation, timing, or reduced-motion behavior.\",\n command: input.commandExamples.loadMotionDesign\n },\n { reason: INSPIREDESIGN_HANDOFF_GUIDANCE.visualArtifactRecommendation },\n {\n reason: INSPIREDESIGN_HANDOFF_GUIDANCE.prepareCanvasPlanRequest,\n command: input.commandExamples.continueInCanvas\n },\n { reason: input.deepCaptureRecommendation }\n ]\n );\n return input.nextStepGuidance\n ? { ...handoff, nextStepGuidance: renderWorkflowGuidance(input.nextStepGuidance) }\n : handoff;\n};\n","import { canonicalizeUrl } from \"./web/crawler\";\nimport type { ResearchRecord } from \"./enrichment\";\nimport {\n formatInspiredesignCaptureAttemptSummary,\n type InspiredesignFollowthrough,\n type InspiredesignImplementationPlan,\n type InspiredesignScreenshotIndexEntry,\n type InspiredesignVisualEvidenceJson\n} from \"../inspiredesign/contract\";\nimport type { InspiredesignReferencePatternBoard } from \"../inspiredesign/reference-pattern-board\";\nimport type { CanvasDesignGovernance, CanvasGenerationPlan } from \"../canvas/types\";\nimport {\n INSPIREDESIGN_HANDOFF_FILES,\n type InspiredesignArtifactGuide,\n type InspiredesignContractSectionGuide\n} from \"../inspiredesign/handoff\";\nimport { buildInspiredesignSuccessHandoff } from \"./workflow-handoff\";\nimport type { NextStepGuidance } from \"../guidance/types\";\n\nexport type RenderMode = \"compact\" | \"json\" | \"md\" | \"context\" | \"path\";\n\ntype RenderedInspiredesignArtifactGuide = Partial<InspiredesignArtifactGuide>;\ntype RenderedInspiredesignFollowthrough = Omit<InspiredesignFollowthrough, \"artifactGuide\"> & {\n artifactGuide: RenderedInspiredesignArtifactGuide;\n};\ntype InspiredesignGuideEntry = InspiredesignContractSectionGuide[string];\n\nexport interface ShoppingOffer {\n offer_id: string;\n product_id: string;\n provider: string;\n url: string;\n title: string;\n price: {\n amount: number;\n currency: string;\n retrieved_at: string;\n };\n shipping: {\n amount: number;\n currency: string;\n notes: string;\n };\n availability: \"in_stock\" | \"limited\" | \"out_of_stock\" | \"unknown\";\n rating: number;\n reviews_count: number;\n deal_score: number;\n attributes: Record<string, unknown>;\n}\n\nconst toCurrency = (value: number): string => `$${value.toFixed(2)}`;\n\nconst primaryConstraintSummaryFromMeta = (meta: Record<string, unknown>): string | null => {\n const summary = meta.primaryConstraintSummary;\n return typeof summary === \"string\" && summary.trim().length > 0\n ? summary.trim()\n : null;\n};\n\nconst isStringArray = (value: unknown): value is string[] => (\n Array.isArray(value) && value.every((item) => typeof item === \"string\")\n);\n\nconst inspiredesignCaptureAttemptReportFromMeta = (\n meta: Record<string, unknown>\n): { worked: string[]; didNotWork: string[] } | null => {\n const report = meta.captureAttemptReport;\n if (typeof report !== \"object\" || report === null || Array.isArray(report)) {\n return null;\n }\n const candidate = report as Record<string, unknown>;\n if (!isStringArray(candidate.worked) || !isStringArray(candidate.didNotWork)) {\n return null;\n }\n return {\n worked: candidate.worked,\n didNotWork: candidate.didNotWork\n };\n};\n\nconst inspiredesignCaptureAttemptSummaryFromMeta = (meta: Record<string, unknown>): string | null => {\n const summary = meta.captureAttemptSummary;\n if (typeof summary === \"string\" && summary.trim().length > 0) {\n return summary.trim();\n }\n const report = inspiredesignCaptureAttemptReportFromMeta(meta);\n return report ? formatInspiredesignCaptureAttemptSummary(report) : null;\n};\n\nconst prependPrimaryConstraint = (text: string, meta: Record<string, unknown>): string => {\n const summary = primaryConstraintSummaryFromMeta(meta);\n return summary ? `Primary constraint: ${summary} ${text}` : text;\n};\n\nconst buildInspiredesignSummary = (args: {\n brief: string;\n referenceCount: number;\n profile: string;\n meta: Record<string, unknown>;\n}): string => {\n const lines = [\n `Brief: ${args.brief}`,\n `References: ${args.referenceCount}`,\n `Profile: ${args.profile}`\n ];\n const summary = primaryConstraintSummaryFromMeta(args.meta);\n if (summary) {\n lines.push(`Primary constraint: ${summary}`);\n }\n const captureSummary = inspiredesignCaptureAttemptSummaryFromMeta(args.meta);\n if (captureSummary) {\n lines.push(`Capture: ${captureSummary}`);\n }\n return lines.join(\"\\n\");\n};\n\nconst compactResearchLines = (records: ResearchRecord[], meta: Record<string, unknown>): string[] => {\n if (records.length === 0) {\n const summary = primaryConstraintSummaryFromMeta(meta);\n return summary\n ? [\n \"No usable research findings were available.\",\n `Primary constraint: ${summary}`\n ]\n : [\"No usable research findings were available.\"];\n }\n return records.slice(0, 10).map((record, index) => {\n const title = record.title ?? record.url ?? record.provider;\n const engagement = record.engagement.likes + record.engagement.comments + record.engagement.upvotes;\n return `${index + 1}. ${title} (${record.source}; ${record.provider}) score=${record.confidence.toFixed(2)} engagement=${engagement}`;\n });\n};\n\nconst RESEARCH_REPORT_LIMITS = {\n findings: 10,\n sources: 20,\n failures: 10,\n excerptCharacters: 240,\n failureMessageCharacters: 240\n} as const;\nconst RESEARCH_REPORT_FILE_NAMES = [\n \"summary.md\",\n \"report.md\",\n \"records.json\",\n \"context.json\",\n \"meta.json\",\n \"bundle-manifest.json\"\n] as const;\n\nconst plainObject = (value: unknown): Record<string, unknown> => (\n typeof value === \"object\" && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : {}\n);\n\nconst researchTitle = (record: ResearchRecord): string => record.title ?? record.url ?? record.provider;\n\nconst normalizedInlineText = (content: string | undefined): string => content?.replace(/\\s+/g, \" \").trim() ?? \"\";\n\nconst boundedInlineText = (args: {\n content: string | undefined;\n fallback: string;\n limit: number;\n target: string;\n}): string => {\n const normalized = normalizedInlineText(args.content);\n if (!normalized) {\n return args.fallback;\n }\n if (normalized.length <= args.limit) {\n return normalized;\n }\n return `${normalized.slice(0, args.limit)} [truncated; see ${args.target}]`;\n};\n\nconst researchExcerpt = (content: string | undefined): string => (\n boundedInlineText({\n content,\n fallback: \"No content excerpt was available.\",\n limit: RESEARCH_REPORT_LIMITS.excerptCharacters,\n target: \"records.json for full content\"\n })\n);\n\nconst researchFailureMessage = (content: string | undefined): string => (\n boundedInlineText({\n content,\n fallback: \"provider failure\",\n limit: RESEARCH_REPORT_LIMITS.failureMessageCharacters,\n target: \"meta.json\"\n })\n);\n\nconst CANVAS_CONTINUATION_BLOCKED_COMMAND = \"Unavailable until nextStepGuidance.readiness is ready.\";\nconst CANVAS_PLAN_OMITTED_GUIDANCE = \"Canvas plan request omitted until nextStepGuidance.readiness is ready.\";\n\nconst canContinueInspiredesignInCanvas = (guidance: NextStepGuidance | undefined): boolean => (\n guidance?.readiness === \"ready\"\n);\n\nconst scrubCanvasPlanReference = (value: string): string => (\n value.includes(INSPIREDESIGN_HANDOFF_FILES.canvasPlanRequest)\n ? CANVAS_PLAN_OMITTED_GUIDANCE\n : value\n);\n\nconst scrubGuideEntryCanvasReferences = (entry: InspiredesignGuideEntry): InspiredesignGuideEntry => ({\n ...entry,\n expectedContents: entry.expectedContents.map(scrubCanvasPlanReference),\n howToUse: entry.howToUse.map(scrubCanvasPlanReference),\n mustNot: entry.mustNot.map(scrubCanvasPlanReference)\n});\n\nconst scrubArtifactGuideCanvasReferences = (\n guide: RenderedInspiredesignArtifactGuide\n): RenderedInspiredesignArtifactGuide => {\n const scrubbed: RenderedInspiredesignArtifactGuide = {};\n for (const [key, entry] of Object.entries(guide)) {\n if (entry) {\n scrubbed[key as keyof InspiredesignArtifactGuide] = scrubGuideEntryCanvasReferences(entry);\n }\n }\n return scrubbed;\n};\n\nconst scrubContractSectionGuideCanvasReferences = (\n guide: InspiredesignContractSectionGuide\n): InspiredesignContractSectionGuide => {\n const scrubbed: InspiredesignContractSectionGuide = {};\n for (const [key, entry] of Object.entries(guide)) {\n scrubbed[key] = scrubGuideEntryCanvasReferences(entry);\n }\n return scrubbed;\n};\n\nconst blockInspiredesignCanvasArtifactGuide = (\n handoff: InspiredesignFollowthrough\n): RenderedInspiredesignArtifactGuide => {\n const artifactGuide: RenderedInspiredesignArtifactGuide = { ...handoff.artifactGuide };\n delete artifactGuide[INSPIREDESIGN_HANDOFF_FILES.canvasPlanRequest];\n return artifactGuide;\n};\n\nconst blockInspiredesignNotReadyArtifacts = (\n handoff: RenderedInspiredesignFollowthrough\n): RenderedInspiredesignFollowthrough => {\n const referenceSynthesis = plainObject(handoff.implementationContext.referenceSynthesis);\n const blockedArtifacts: ReadonlySet<string> = new Set([\n INSPIREDESIGN_HANDOFF_FILES.canvasPlanRequest,\n INSPIREDESIGN_HANDOFF_FILES.prototypeGuidance\n ]);\n const requiredArtifacts = isStringArray(referenceSynthesis.requiredArtifacts)\n ? referenceSynthesis.requiredArtifacts.filter((artifact) => !blockedArtifacts.has(artifact))\n : [];\n const artifactGuide: RenderedInspiredesignArtifactGuide = { ...handoff.artifactGuide };\n delete artifactGuide[INSPIREDESIGN_HANDOFF_FILES.canvasPlanRequest];\n delete artifactGuide[INSPIREDESIGN_HANDOFF_FILES.prototypeGuidance];\n return {\n ...handoff,\n artifactGuide: scrubArtifactGuideCanvasReferences(artifactGuide),\n contractSectionGuide: scrubContractSectionGuideCanvasReferences(handoff.contractSectionGuide),\n implementationContext: {\n ...handoff.implementationContext,\n referenceSynthesis: {\n ...referenceSynthesis,\n requiredArtifacts\n }\n }\n };\n};\n\nconst blockPrototypeGuidanceInDesignMarkdown = (\n markdown: string,\n prototypeGuidanceMarkdown: string | null\n): string => {\n const withoutCanvasDeliverable = markdown.replace(\n /\\n- Diagnostic `canvasPlanRequest` preview; do not submit to Canvas until next-step guidance is ready/g,\n `\\n- ${CANVAS_PLAN_OMITTED_GUIDANCE}`\n );\n const withoutPrototypeDeliverable = withoutCanvasDeliverable.replace(\n /\\n- Prototype guidance Markdown for the first HTML pass/g,\n \"\"\n );\n if (!prototypeGuidanceMarkdown) return withoutPrototypeDeliverable;\n return withoutPrototypeDeliverable.replace(\n prototypeGuidanceMarkdown,\n \"# 6. Optional Prototype Plan\\n\\n- Prototype guidance omitted because next-step guidance is not ready.\"\n );\n};\n\nconst buildMissingInspiredesignGuidanceHandoff = (): {\n followthroughSummary: string;\n suggestedNextAction: string;\n suggestedSteps: Array<{ reason: string; command?: string }>;\n} => {\n const summary = \"Canvas continuation unavailable until nextStepGuidance.readiness is ready.\";\n return {\n followthroughSummary: summary,\n suggestedNextAction: summary,\n suggestedSteps: [{\n reason: \"Inspect the workflow output for nextStepGuidance before using Canvas artifacts.\"\n }]\n };\n};\n\nconst limitedCount = (total: number, limit: number): number => Math.min(total, limit);\n\nconst omissionLine = (args: {\n total: number;\n limit: number;\n singular: string;\n plural: string;\n target: string;\n}): string[] => {\n const omitted = args.total - limitedCount(args.total, args.limit);\n if (omitted <= 0) {\n return [];\n }\n const noun = omitted === 1 ? args.singular : args.plural;\n return [`- ${omitted} more ${noun} omitted from this report; see ${args.target} for the complete dataset.`];\n};\n\nconst researchFindingsLines = (records: ResearchRecord[]): string[] => (\n records.length === 0\n ? [\"- No usable findings were available.\"]\n : [\n ...records.slice(0, RESEARCH_REPORT_LIMITS.findings).flatMap((record, index) => [\n `### ${index + 1}. ${researchTitle(record)}`,\n `- Source: ${record.source}`,\n `- Provider: ${record.provider}`,\n `- URL: ${record.url ?? \"not provided\"}`,\n `- Published: ${record.timestamp}`,\n `- Confidence: ${record.confidence.toFixed(2)}`,\n `- Evidence: ${researchExcerpt(record.content)}`\n ]),\n ...omissionLine({\n total: records.length,\n limit: RESEARCH_REPORT_LIMITS.findings,\n singular: \"finding\",\n plural: \"findings\",\n target: \"records.json\"\n })\n ]\n);\n\nconst researchSourcesLines = (records: ResearchRecord[]): string[] => (\n records.length === 0\n ? [\"- No sources available.\"]\n : [\n ...records\n .slice(0, RESEARCH_REPORT_LIMITS.sources)\n .map((record) => `- ${researchTitle(record)}: ${record.url ?? \"URL not provided\"}`),\n ...omissionLine({\n total: records.length,\n limit: RESEARCH_REPORT_LIMITS.sources,\n singular: \"source\",\n plural: \"sources\",\n target: \"records.json\"\n })\n ]\n);\n\nconst researchReasonLine = (metrics: Record<string, unknown>): string[] => {\n const reasons = Object.entries(plainObject(metrics.sanitized_reason_distribution))\n .map(([reason, count]) => `${reason}: ${String(count)}`);\n return reasons.length === 0 ? [] : [`- Sanitized record reasons: ${reasons.join(\", \")}`];\n};\n\nconst deadEndSearchFailures = (failures: unknown): Record<string, unknown>[] => {\n if (!Array.isArray(failures)) return [];\n return failures.filter((failure): failure is Record<string, unknown> => {\n const record = plainObject(failure);\n const error = plainObject(record.error);\n const details = plainObject(error.details);\n return details.fallbackOutputReason === \"research_dead_end_shell\";\n });\n};\n\nconst deadEndSearchFailureCount = (meta: Record<string, unknown>): number => (\n deadEndSearchFailures(meta.failures).length\n);\n\nconst rejectedCandidatesFromMeta = (meta: Record<string, unknown>): Record<string, unknown>[] => (\n Array.isArray(meta.rejected_candidates)\n ? meta.rejected_candidates.map(plainObject).filter((candidate) => Object.keys(candidate).length > 0)\n : []\n);\n\nconst rejectedCandidateCount = (meta: Record<string, unknown>): number => {\n const metrics = plainObject(meta.metrics);\n if (typeof metrics.rejected_candidate_count === \"number\") {\n return metrics.rejected_candidate_count;\n }\n const sanitized = typeof metrics.sanitized_records === \"number\" ? metrics.sanitized_records : 0;\n return sanitized + deadEndSearchFailureCount(meta);\n};\n\nconst deadEndSearchFailureLines = (meta: Record<string, unknown>): string[] => {\n const failures = deadEndSearchFailures(meta.failures);\n if (failures.length === 0) return [];\n return [`- Dead-end search failures: ${failures.length}`];\n};\n\nconst researchRejectedCandidateSummary = (candidate: Record<string, unknown>): string => {\n const reason = typeof candidate.reason === \"string\" ? candidate.reason : \"unknown_reason\";\n const provider = typeof candidate.provider === \"string\" ? candidate.provider : \"unknown_provider\";\n const source = typeof candidate.source === \"string\" ? candidate.source : \"unknown_source\";\n const status = typeof candidate.replacement_status === \"string\" ? candidate.replacement_status : \"not_recorded\";\n const retrievalPath = typeof candidate.retrievalPath === \"string\" ? `; path=${candidate.retrievalPath}` : \"\";\n const url = typeof candidate.url === \"string\" ? candidate.url : \"URL not recorded\";\n return `${reason} from ${provider} (${source}; ${status}${retrievalPath}): ${url}`;\n};\n\nconst researchFailureSummary = (failure: unknown): string => {\n const record = plainObject(failure);\n const error = plainObject(record.error);\n const provider = typeof record.provider === \"string\" ? record.provider : \"unknown\";\n const source = typeof record.source === \"string\" ? record.source : \"unknown\";\n const reason = typeof error.reasonCode === \"string\" ? `${error.reasonCode}: ` : \"\";\n const message = researchFailureMessage(typeof error.message === \"string\" ? error.message : undefined);\n return `${provider} (${source}): ${reason}${message}`;\n};\n\nconst researchFailureLines = (failures: unknown): string[] => {\n if (!Array.isArray(failures) || failures.length === 0) {\n return [];\n }\n const summaries = failures.slice(0, RESEARCH_REPORT_LIMITS.failures).map(researchFailureSummary);\n const omitted = failures.length - summaries.length;\n const noun = omitted === 1 ? \"failure\" : \"failures\";\n const suffix = omitted > 0\n ? `; ${omitted} more provider ${noun} omitted from this report; see meta.json`\n : \"\";\n return [`- Provider failures: ${summaries.join(\"; \")}${suffix}`];\n};\n\nconst researchGapLines = (meta: Record<string, unknown>): string[] => {\n const metrics = plainObject(meta.metrics);\n const details = [\n typeof metrics.final_records === \"number\" ? `- Final records reported by workflow: ${metrics.final_records}` : \"\",\n typeof metrics.sanitized_records === \"number\" ? `- Sanitized records excluded: ${metrics.sanitized_records}` : \"\",\n ...researchReasonLine(metrics),\n ...researchFailureLines(meta.failures)\n ].filter(Boolean);\n const constraint = primaryConstraintSummaryFromMeta(meta);\n const fallback = \"- No provider limitations or sanitization gaps were reported.\";\n const gapDetails = details.length > 0 || constraint ? details : [fallback];\n return [\n \"## Confidence and Gaps\",\n ...(constraint ? [`- Primary constraint: ${constraint}`] : []),\n ...gapDetails\n ];\n};\n\nconst researchSearchDirectionLines = (meta: Record<string, unknown>): string[] => {\n const selection = plainObject(meta.selection);\n const sources = Array.isArray(selection.resolved_sources)\n ? selection.resolved_sources.map(String).join(\", \")\n : \"not recorded\";\n return [\n \"## Search Direction\",\n `- Source families searched: ${sources}`,\n \"- Direction: Follow accepted destination pages from provider/search output before synthesis.\"\n ];\n};\n\nconst researchSourceFamilies = (meta: Record<string, unknown>): string[] => {\n const sources = plainObject(meta.selection).resolved_sources;\n return Array.isArray(sources) ? sources.map(String) : [];\n};\n\nconst researchCandidateTriageSchema = (): Record<string, unknown> => ({\n url: \"\",\n rank: 0,\n engine: \"\",\n query: \"\",\n source_family: \"\",\n title: \"\",\n status: \"pending|accepted|rejected\",\n blocker_notes: \"\",\n rejection_reason: \"\",\n replacement_url: \"\",\n retrieval_notes: \"\",\n extraction_status: \"pending|fetched|blocked|shell|stale|irrelevant\"\n});\n\nconst researchCandidateTriageLines = (records: ResearchRecord[], meta: Record<string, unknown>): string[] => {\n const rejected = rejectedCandidateCount(meta);\n return [\n \"## Candidate Triage\",\n `- Accepted destination records: ${records.length}`,\n `- Rejected shell or dead-end candidates: ${rejected}`,\n \"- Rejection policy: search pages, login/account pages, privacy/cookie pages, JavaScript shells, not-found pages, and unsupported shells are not final evidence.\"\n ];\n};\n\nconst researchRejectedCandidateLines = (meta: Record<string, unknown>): string[] => {\n const rejectedCandidates = rejectedCandidatesFromMeta(meta);\n const rejectionLines = [\n ...researchReasonLine(plainObject(meta.metrics)),\n ...rejectedCandidates.slice(0, RESEARCH_REPORT_LIMITS.failures)\n .map((candidate) => `- Rejected candidate: ${researchRejectedCandidateSummary(candidate)}`),\n ...deadEndSearchFailureLines(meta)\n ];\n return [\n \"## Rejected Candidates\",\n ...rejectionLines,\n ...(rejectionLines.length === 0\n ? [\"- No rejected candidate distribution was reported.\"]\n : [])\n ];\n};\n\nconst researchDeepDiveLines = (records: ResearchRecord[]): string[] => [\n \"## Deep Dives\",\n ...(records.length === 0\n ? [\"- No destination pages passed the evidence gate.\"]\n : records.slice(0, RESEARCH_REPORT_LIMITS.sources).map((record) => {\n const retrievalPath = typeof record.attributes.retrievalPath === \"string\"\n ? record.attributes.retrievalPath\n : \"\";\n const prefix = retrievalPath.includes(\":fetch:\") ? \"Opened destination evidence\" : \"Accepted evidence record\";\n return `- ${prefix}: ${record.url ?? researchTitle(record)}`;\n }))\n];\n\nconst researchSynthesisFeedbackText = (records: ResearchRecord[], meta: Record<string, unknown>): string => {\n const rejected = rejectedCandidateCount(meta);\n return records.length === 0 || rejected > records.length\n ? \"Continue with remaining public destination candidates or narrow the query; use auth/cookies only when a selected evidence page itself requires authorized access.\"\n : \"Synthesize only the accepted destination evidence and cite records.json for full source text.\";\n};\n\nconst researchSynthesisFeedbackLines = (records: ResearchRecord[], meta: Record<string, unknown>): string[] => {\n return [\"## Synthesis Feedback\", `- Next step: ${researchSynthesisFeedbackText(records, meta)}`];\n};\n\nconst researchContextPayload = (args: {\n topic: string;\n lines: string[];\n records: ResearchRecord[];\n meta: Record<string, unknown>;\n}): Record<string, unknown> => ({\n topic: args.topic,\n timebox: plainObject(args.meta.timebox),\n source_families: researchSourceFamilies(args.meta),\n evidence_gate: {\n status: \"pending_review\",\n reviewed_artifacts: []\n },\n artifact_files: RESEARCH_REPORT_FILE_NAMES,\n source_ledger: args.records.map((record) => ({\n title: researchTitle(record),\n url: record.url,\n source_family: record.source,\n provider: record.provider\n })),\n search_direction_notes: researchSearchDirectionLines(args.meta),\n candidate_triage_schema: researchCandidateTriageSchema(),\n highlights: args.lines,\n records: args.records,\n candidate_triage: {\n accepted_destination_records: args.records.length,\n rejected_shell_or_dead_end_candidates: rejectedCandidateCount(args.meta)\n },\n rejected_candidates: rejectedCandidatesFromMeta(args.meta),\n deep_dive_pages: args.records.map((record) => ({\n title: researchTitle(record),\n url: record.url,\n provider: record.provider,\n source: record.source,\n retrievalPath: record.attributes.retrievalPath\n })),\n iteration_log: researchSearchDirectionLines(args.meta),\n synthesis_feedback: researchSynthesisFeedbackText(args.records, args.meta),\n meta: args.meta\n});\n\nconst researchArtifactFileLines = (): string[] => [\n \"## Report Files\",\n ...RESEARCH_REPORT_FILE_NAMES.map((fileName) => `- ${fileName}`)\n];\n\nconst buildResearchReport = (args: {\n topic: string;\n records: ResearchRecord[];\n meta: Record<string, unknown>;\n}): string => [\n \"# Research Report\",\n \"\",\n \"## Executive Summary\",\n `- Topic: ${args.topic}`,\n `- Usable findings: ${args.records.length}`,\n `- Findings shown in report: ${limitedCount(args.records.length, RESEARCH_REPORT_LIMITS.findings)}`,\n `- Sources shown in report: ${limitedCount(args.records.length, RESEARCH_REPORT_LIMITS.sources)}`,\n \"- Final output: Usable records are persisted in records.json.\",\n \"- Diagnostics: Run metadata, failures, and constraints are persisted in meta.json; this report summarizes the bounded inline subset.\",\n \"\",\n ...researchArtifactFileLines(),\n \"\",\n ...researchSearchDirectionLines(args.meta),\n \"\",\n ...researchCandidateTriageLines(args.records, args.meta),\n \"\",\n ...researchRejectedCandidateLines(args.meta),\n \"\",\n ...researchDeepDiveLines(args.records),\n \"\",\n ...researchSynthesisFeedbackLines(args.records, args.meta),\n \"\",\n \"## Findings\",\n ...researchFindingsLines(args.records),\n \"\",\n ...researchGapLines(args.meta),\n \"\",\n \"## Sources\",\n ...researchSourcesLines(args.records)\n].join(\"\\n\");\n\nexport const renderResearch = (args: {\n mode: RenderMode;\n topic: string;\n records: ResearchRecord[];\n meta: Record<string, unknown>;\n}): {\n response: Record<string, unknown>;\n files: Array<{ path: string; content: string | Record<string, unknown> }>;\n} => {\n const lines = compactResearchLines(args.records, args.meta);\n const summary = lines.join(\"\\n\");\n const report = buildResearchReport(args);\n const markdown = [\n `# Research: ${args.topic}`,\n \"\",\n ...lines,\n \"\",\n \"## Metadata\",\n \"```json\",\n JSON.stringify(args.meta, null, 2),\n \"```\"\n ].join(\"\\n\");\n const contextPayload = researchContextPayload({\n topic: args.topic,\n lines,\n records: args.records,\n meta: args.meta\n });\n\n const files = [\n { path: \"summary.md\", content: markdown },\n { path: \"report.md\", content: report },\n { path: \"records.json\", content: { records: args.records } },\n { path: \"context.json\", content: contextPayload },\n { path: \"meta.json\", content: args.meta }\n ];\n\n if (args.mode === \"compact\") {\n return {\n response: {\n mode: args.mode,\n summary,\n meta: args.meta\n },\n files\n };\n }\n if (args.mode === \"json\") {\n return {\n response: {\n mode: args.mode,\n records: args.records,\n meta: args.meta\n },\n files\n };\n }\n if (args.mode === \"md\") {\n return {\n response: {\n mode: args.mode,\n markdown,\n meta: args.meta\n },\n files\n };\n }\n\n if (args.mode === \"context\") {\n return {\n response: {\n mode: args.mode,\n context: contextPayload,\n meta: args.meta\n },\n files\n };\n }\n\n return {\n response: {\n mode: \"path\",\n meta: args.meta\n },\n files\n };\n};\n\nconst toComparisonCsv = (offers: ShoppingOffer[]): string => {\n const header = [\"provider\", \"title\", \"price\", \"shipping\", \"deal_score\", \"availability\", \"url\"].join(\",\");\n const rows = offers.map((offer) => {\n return [\n offer.provider,\n JSON.stringify(offer.title),\n offer.price.amount.toFixed(2),\n offer.shipping.amount.toFixed(2),\n offer.deal_score.toFixed(4),\n offer.availability,\n canonicalizeUrl(offer.url)\n ].join(\",\");\n });\n return [header, ...rows].join(\"\\n\");\n};\n\nconst compactShoppingLines = (offers: ShoppingOffer[], meta: Record<string, unknown>): string[] => {\n if (offers.length === 0) {\n const summary = primaryConstraintSummaryFromMeta(meta);\n return summary\n ? [\n \"No offers available from the selected providers.\",\n `Primary constraint: ${summary}`\n ]\n : [\"No offers available from the selected providers.\"];\n }\n return offers.slice(0, 10).map((offer, index) => {\n const total = offer.price.amount + offer.shipping.amount;\n return `${index + 1}. ${offer.title} - ${toCurrency(total)} (${offer.provider}, deal=${offer.deal_score.toFixed(2)})`;\n });\n};\n\nexport const renderShopping = (args: {\n mode: RenderMode;\n query: string;\n offers: ShoppingOffer[];\n meta: Record<string, unknown>;\n}): {\n response: Record<string, unknown>;\n files: Array<{ path: string; content: string | Record<string, unknown> }>;\n} => {\n const lines = compactShoppingLines(args.offers, args.meta);\n const markdown = [\n `# Shopping: ${args.query}`,\n \"\",\n ...lines,\n \"\",\n \"## Metadata\",\n \"```json\",\n JSON.stringify(args.meta, null, 2),\n \"```\"\n ].join(\"\\n\");\n\n const comparisonCsv = toComparisonCsv(args.offers);\n const contextPayload = {\n query: args.query,\n highlights: lines,\n offers: args.offers,\n meta: args.meta\n };\n\n const files = [\n { path: \"deals.md\", content: markdown },\n { path: \"offers.json\", content: { offers: args.offers } },\n { path: \"comparison.csv\", content: comparisonCsv },\n { path: \"meta.json\", content: args.meta },\n { path: \"deals-context.json\", content: contextPayload }\n ];\n\n if (args.mode === \"compact\") {\n return {\n response: {\n mode: args.mode,\n summary: lines.join(\"\\n\"),\n meta: args.meta\n },\n files\n };\n }\n if (args.mode === \"json\") {\n return {\n response: {\n mode: args.mode,\n offers: args.offers,\n meta: args.meta\n },\n files\n };\n }\n if (args.mode === \"md\") {\n return {\n response: {\n mode: args.mode,\n markdown,\n meta: args.meta\n },\n files\n };\n }\n if (args.mode === \"context\") {\n return {\n response: {\n mode: args.mode,\n context: contextPayload,\n meta: args.meta\n },\n files\n };\n }\n\n return {\n response: {\n mode: \"path\",\n meta: args.meta\n },\n files\n };\n};\n\nexport const renderInspiredesign = (args: {\n mode: RenderMode;\n brief: string;\n advancedBriefMarkdown: string;\n urls: string[];\n designContract: CanvasDesignGovernance;\n canvasPlanRequest: Record<string, unknown>;\n designAgentHandoff: InspiredesignFollowthrough;\n generationPlan: CanvasGenerationPlan;\n implementationPlan: InspiredesignImplementationPlan;\n designMarkdown: string;\n implementationPlanMarkdown: string;\n prototypeGuidanceMarkdown: string | null;\n evidence: Record<string, unknown>;\n visualEvidence?: InspiredesignVisualEvidenceJson[];\n screenshotIndex?: InspiredesignScreenshotIndexEntry[];\n rankedReferences?: InspiredesignReferencePatternBoard[\"references\"];\n referencePatternBoard?: InspiredesignReferencePatternBoard;\n metaPromptMarkdown?: string;\n nextStepGuidance?: NextStepGuidance;\n meta: Record<string, unknown>;\n}): {\n response: Record<string, unknown>;\n files: Array<{ path: string; content: string | Record<string, unknown> }>;\n} => {\n const captureAttemptReport = inspiredesignCaptureAttemptReportFromMeta(args.meta);\n const captureAttemptSummary = inspiredesignCaptureAttemptSummaryFromMeta(args.meta);\n const visualEvidence = args.visualEvidence ?? [];\n const screenshotIndex = args.screenshotIndex ?? [];\n const rankedReferences = args.rankedReferences ?? [];\n const rankedReferencesArtifact = args.referencePatternBoard\n ? {\n qualitySummary: args.referencePatternBoard.qualitySummary,\n references: args.referencePatternBoard.references,\n rejectedReferences: args.referencePatternBoard.rejectedReferences,\n synthesis: args.referencePatternBoard.synthesis\n }\n : {\n references: rankedReferences,\n rejectedReferences: []\n };\n const metaPromptMarkdown = args.metaPromptMarkdown ?? \"\";\n const summary = buildInspiredesignSummary({\n brief: args.brief,\n referenceCount: args.urls.length,\n profile: args.generationPlan.visualDirection.profile,\n meta: args.meta\n });\n const followthroughSummary = prependPrimaryConstraint(args.designAgentHandoff.summary, args.meta);\n const canContinueInCanvas = canContinueInspiredesignInCanvas(args.nextStepGuidance);\n const prototypeGuidanceMarkdown = canContinueInCanvas ? args.prototypeGuidanceMarkdown : null;\n const designMarkdown = canContinueInCanvas\n ? args.designMarkdown\n : blockPrototypeGuidanceInDesignMarkdown(args.designMarkdown, args.prototypeGuidanceMarkdown);\n const commandExamples = {\n ...args.designAgentHandoff.commandExamples,\n continueInCanvas: canContinueInCanvas\n ? args.designAgentHandoff.commandExamples.continueInCanvas\n : CANVAS_CONTINUATION_BLOCKED_COMMAND\n };\n const renderedWorkflowHandoff = buildInspiredesignSuccessHandoff({\n summary: followthroughSummary,\n nextStep: args.designAgentHandoff.nextStep,\n commandExamples,\n deepCaptureRecommendation: args.designAgentHandoff.deepCaptureRecommendation,\n ...(args.nextStepGuidance ? { nextStepGuidance: args.nextStepGuidance } : {})\n });\n const handoff = args.nextStepGuidance ? renderedWorkflowHandoff : buildMissingInspiredesignGuidanceHandoff();\n const blockedCanvasArtifactGuide: RenderedInspiredesignArtifactGuide = canContinueInCanvas\n ? args.designAgentHandoff.artifactGuide\n : blockInspiredesignCanvasArtifactGuide(args.designAgentHandoff);\n const renderedDesignAgentHandoffBase: RenderedInspiredesignFollowthrough = {\n ...args.designAgentHandoff,\n ...handoff,\n summary: handoff.followthroughSummary,\n nextStep: handoff.suggestedNextAction,\n artifactGuide: blockedCanvasArtifactGuide,\n commandExamples\n };\n const renderedDesignAgentHandoff = canContinueInCanvas\n ? renderedDesignAgentHandoffBase\n : blockInspiredesignNotReadyArtifacts(renderedDesignAgentHandoffBase);\n const contextPayload = {\n brief: args.brief,\n advancedBriefMarkdown: args.advancedBriefMarkdown,\n urls: args.urls,\n designContract: args.designContract,\n ...(canContinueInCanvas ? { canvasPlanRequest: args.canvasPlanRequest } : {}),\n designAgentHandoff: renderedDesignAgentHandoff,\n ...(args.nextStepGuidance ? { nextStepGuidance: args.nextStepGuidance } : {}),\n generationPlan: args.generationPlan,\n implementationPlan: args.implementationPlan,\n designMarkdown,\n implementationPlanMarkdown: args.implementationPlanMarkdown,\n prototypeGuidanceMarkdown,\n evidence: args.evidence,\n visualEvidence,\n screenshotIndex,\n rankedReferences,\n metaPromptMarkdown,\n meta: args.meta\n };\n const files: Array<{ path: string; content: string | Record<string, unknown> }> = [\n { path: INSPIREDESIGN_HANDOFF_FILES.designMarkdown, content: designMarkdown },\n { path: INSPIREDESIGN_HANDOFF_FILES.advancedBrief, content: args.advancedBriefMarkdown },\n { path: INSPIREDESIGN_HANDOFF_FILES.designContract, content: args.designContract },\n {\n path: INSPIREDESIGN_HANDOFF_FILES.designAgentHandoff,\n content: renderedDesignAgentHandoff\n },\n { path: INSPIREDESIGN_HANDOFF_FILES.generationPlan, content: args.generationPlan },\n { path: INSPIREDESIGN_HANDOFF_FILES.implementationPlanMarkdown, content: args.implementationPlanMarkdown },\n { path: INSPIREDESIGN_HANDOFF_FILES.implementationPlan, content: args.implementationPlan },\n { path: INSPIREDESIGN_HANDOFF_FILES.evidence, content: args.evidence },\n { path: INSPIREDESIGN_HANDOFF_FILES.visualEvidence, content: { visualEvidence } },\n { path: INSPIREDESIGN_HANDOFF_FILES.screenshotIndex, content: { screenshots: screenshotIndex } },\n { path: INSPIREDESIGN_HANDOFF_FILES.rankedReferences, content: rankedReferencesArtifact },\n { path: INSPIREDESIGN_HANDOFF_FILES.metaPrompt, content: metaPromptMarkdown }\n ];\n if (prototypeGuidanceMarkdown) {\n files.push({ path: INSPIREDESIGN_HANDOFF_FILES.prototypeGuidance, content: prototypeGuidanceMarkdown });\n }\n if (canContinueInCanvas) {\n files.push({ path: INSPIREDESIGN_HANDOFF_FILES.canvasPlanRequest, content: args.canvasPlanRequest });\n }\n const captureAttemptFields = {\n ...(captureAttemptSummary ? { captureAttemptSummary } : {}),\n ...(captureAttemptReport ? { captureAttemptReport } : {})\n };\n\n if (args.mode === \"compact\") {\n return {\n response: {\n mode: args.mode,\n summary,\n ...handoff,\n ...captureAttemptFields,\n meta: args.meta\n },\n files\n };\n }\n if (args.mode === \"json\") {\n return {\n response: {\n mode: args.mode,\n brief: args.brief,\n advancedBriefMarkdown: args.advancedBriefMarkdown,\n urls: args.urls,\n ...(canContinueInCanvas ? { canvasPlanRequest: args.canvasPlanRequest } : {}),\n designAgentHandoff: renderedDesignAgentHandoff,\n ...(args.nextStepGuidance ? { nextStepGuidance: args.nextStepGuidance } : {}),\n designContract: args.designContract,\n generationPlan: args.generationPlan,\n implementationPlan: args.implementationPlan,\n prototypeGuidanceMarkdown,\n evidence: args.evidence,\n visualEvidence,\n screenshotIndex,\n rankedReferences,\n metaPromptMarkdown,\n ...handoff,\n ...captureAttemptFields,\n meta: args.meta\n },\n files\n };\n }\n if (args.mode === \"md\") {\n return {\n response: {\n mode: args.mode,\n markdown: designMarkdown,\n implementationPlanMarkdown: args.implementationPlanMarkdown,\n prototypeGuidanceMarkdown,\n ...handoff,\n ...captureAttemptFields,\n meta: args.meta\n },\n files\n };\n }\n if (args.mode === \"context\") {\n return {\n response: {\n mode: args.mode,\n context: contextPayload,\n ...handoff,\n ...captureAttemptFields,\n meta: args.meta\n },\n files\n };\n }\n\n return {\n response: {\n mode: \"path\",\n ...handoff,\n ...captureAttemptFields,\n meta: args.meta\n },\n files\n };\n};\n","import { isAllowedPinterestReferenceHost, pinterestSiteRecipe } from \"./pinterest\";\nimport type { SiteRecipe } from \"../types\";\n\nconst freezeRecipeValue = <T>(value: T): T => {\n if (value === null || typeof value !== \"object\" || Object.isFrozen(value)) return value;\n for (const child of Object.values(value)) {\n freezeRecipeValue(child);\n }\n return Object.freeze(value);\n};\n\nconst SITE_RECIPES: SiteRecipe[] = [freezeRecipeValue(pinterestSiteRecipe)];\n\nconst normalizeHostname = (hostname: string): string => hostname.toLowerCase().replace(/^www\\./, \"\");\n\nexport const listSiteRecipes = (): SiteRecipe[] => [...SITE_RECIPES];\n\nexport const resolveSiteRecipeForProvider = (providerId: string): SiteRecipe | undefined => {\n return SITE_RECIPES.find((recipe) => recipe.providerIds.includes(providerId));\n};\n\nexport const resolveSiteRecipeForUrl = (url: string): SiteRecipe | undefined => {\n let hostname: string;\n try {\n hostname = new URL(url).hostname.toLowerCase();\n } catch {\n return undefined;\n }\n return SITE_RECIPES.find((recipe) => {\n if (recipe.id === \"social/pinterest\") {\n return isAllowedPinterestReferenceHost(hostname);\n }\n const normalizedHost = normalizeHostname(hostname);\n return recipe.hostnames.some((candidate) => {\n const normalized = normalizeHostname(candidate);\n return normalizedHost === normalized || normalizedHost.endsWith(`.${normalized}`);\n });\n });\n};\n","import { resolveSiteRecipeForProvider, resolveSiteRecipeForUrl } from \"./recipes/site-registry\";\nimport type { GuidanceContext } from \"./types\";\n\nexport type InspiredesignGuidanceQualitySource = {\n rankedReferenceCount: number;\n rankedReferenceUrls?: string[];\n rejectedReferenceCount: number;\n topReferenceScore?: number;\n topReferenceConfidence?: number;\n topReferenceIntentMatched?: boolean;\n diagnosticOnlyReasons: string[];\n missingScreenshotCount: number;\n};\n\nexport type InspiredesignGuidanceSource = {\n brief: string;\n query?: string;\n urls?: string[];\n requestedProviders: string[];\n browserMode?: string;\n cookiePolicy?: string;\n useCookies?: boolean;\n discovery: {\n requested: boolean;\n acceptedUrls: string[];\n failure?: string;\n failures: number;\n hardFailureReasonCodes?: string[];\n };\n metrics: {\n referenceCount: number;\n referenceEvidenceRequired?: boolean;\n failedCaptureCount: number;\n visualEvidenceRequired: boolean;\n };\n quality: InspiredesignGuidanceQualitySource;\n primaryConstraint?: {\n reasonCode?: string;\n summary?: string;\n };\n};\n\nconst HARD_PROVIDER_FAILURE_REASON_CODES = new Set([\n \"auth_required\",\n \"challenge_detected\",\n \"policy_blocked\",\n \"rate_limited\",\n \"token_required\"\n]);\n\nconst normalizeComparableUrl = (value: string): string | null => {\n try {\n const url = new URL(value);\n url.protocol = \"https:\";\n url.hostname = url.hostname.toLowerCase().replace(/^www\\./, \"\");\n url.hash = \"\";\n url.search = \"\";\n return url.toString();\n } catch {\n return null;\n }\n};\n\nconst hasAcceptedUserSuppliedSiteRecipeReferenceUrl = (source: InspiredesignGuidanceSource): boolean => {\n if (source.metrics.referenceCount === 0 || source.quality.rankedReferenceCount === 0) return false;\n const rankedReferenceUrls = new Set((source.quality.rankedReferenceUrls ?? [])\n .map(normalizeComparableUrl)\n .filter((url): url is string => typeof url === \"string\"));\n if (rankedReferenceUrls.size === 0) return false;\n const requestedSiteRecipeIds = new Set(source.requestedProviders\n .map((providerId) => resolveSiteRecipeForProvider(providerId)?.id)\n .filter((recipeId): recipeId is string => typeof recipeId === \"string\"));\n return (source.urls ?? []).some((url) => {\n const recipeId = resolveSiteRecipeForUrl(url)?.id;\n if (!recipeId) return false;\n if (requestedSiteRecipeIds.size > 0 && !requestedSiteRecipeIds.has(recipeId)) return false;\n const normalizedUrl = normalizeComparableUrl(url);\n return normalizedUrl !== null && rankedReferenceUrls.has(normalizedUrl);\n });\n};\n\nconst hasHardProviderFailureSignal = (source: InspiredesignGuidanceSource): boolean => (\n (\n !hasAcceptedUserSuppliedSiteRecipeReferenceUrl(source)\n && (source.discovery.hardFailureReasonCodes ?? []).some((reasonCode) => HARD_PROVIDER_FAILURE_REASON_CODES.has(reasonCode))\n )\n || (source.primaryConstraint?.reasonCode ? HARD_PROVIDER_FAILURE_REASON_CODES.has(source.primaryConstraint.reasonCode) : false)\n);\n\nconst hasProviderUnavailableSignal = (source: InspiredesignGuidanceSource): boolean => {\n if (hasHardProviderFailureSignal(source)) return true;\n if (source.metrics.referenceCount > 0 && source.quality.rankedReferenceCount > 0) return false;\n if (source.discovery.requested && source.discovery.acceptedUrls.length === 0 && source.discovery.failures > 0) return true;\n if (source.discovery.failure && source.discovery.acceptedUrls.length === 0) return true;\n return source.primaryConstraint?.reasonCode === \"auth_required\";\n};\n\nconst hasWeakTopReference = (source: InspiredesignGuidanceSource): boolean => {\n if (source.quality.rankedReferenceCount === 0) return false;\n const score = source.quality.topReferenceScore ?? 0;\n const confidence = source.quality.topReferenceConfidence ?? 0;\n return score < 50 || confidence < 0.5;\n};\n\nconst reasonCodeForInspiredesign = (source: InspiredesignGuidanceSource): string => {\n if (hasProviderUnavailableSignal(source)) return \"provider_unavailable\";\n if (source.quality.diagnosticOnlyReasons.length > 0 && source.quality.rankedReferenceCount === 0) return \"diagnostic_only\";\n if (source.metrics.referenceCount === 0 && source.metrics.referenceEvidenceRequired !== false) return \"zero_references\";\n if (source.metrics.referenceCount > 0 && source.quality.rankedReferenceCount === 0) return \"zero_ranked_references\";\n if (\n source.metrics.visualEvidenceRequired\n && (source.metrics.failedCaptureCount > 0 || source.quality.missingScreenshotCount > 0)\n ) {\n return \"failed_capture\";\n }\n if (source.quality.topReferenceIntentMatched === false) return \"off_brief_reference\";\n if (hasWeakTopReference(source)) return \"weak_reference\";\n return \"design_ready\";\n};\n\nconst dedupeInspiredesignReferenceUrls = (source: InspiredesignGuidanceSource): string[] => {\n const urls = [...(source.urls ?? []), ...source.discovery.acceptedUrls]\n .map((url) => url.trim())\n .filter((url) => url.length > 0);\n return [...new Set(urls)];\n};\n\nconst resolveInspiredesignSiteRecipe = (source: InspiredesignGuidanceSource): string | undefined => {\n const providerRecipe = source.requestedProviders\n .map((providerId) => resolveSiteRecipeForProvider(providerId))\n .find((recipe) => recipe !== undefined);\n if (providerRecipe) return providerRecipe.id;\n const urlRecipe = (source.urls ?? [])\n .map((url) => resolveSiteRecipeForUrl(url))\n .find((recipe) => recipe !== undefined);\n return urlRecipe?.id;\n};\n\nexport const createInspiredesignGuidanceContext = (\n source: InspiredesignGuidanceSource\n): GuidanceContext => {\n const siteRecipeId = resolveInspiredesignSiteRecipe(source);\n const referenceUrls = dedupeInspiredesignReferenceUrls(source);\n return {\n workflow: \"inspiredesign\",\n reasonCode: reasonCodeForInspiredesign(source),\n requestedProviders: source.requestedProviders,\n ...(siteRecipeId ? { siteRecipeId } : {}),\n ...(source.query ? { query: source.query } : {}),\n ...(referenceUrls.length > 0 ? { referenceUrls } : {}),\n ...(source.browserMode ? { browserMode: source.browserMode } : {}),\n ...(source.cookiePolicy ? { cookiePolicy: source.cookiePolicy } : {}),\n ...(typeof source.useCookies === \"boolean\" ? { useCookies: source.useCookies } : {}),\n providerUnavailable: hasProviderUnavailableSignal(source),\n evidence: {\n referenceCount: source.metrics.referenceCount,\n referenceEvidenceRequired: source.metrics.referenceEvidenceRequired,\n failedCaptureCount: source.metrics.failedCaptureCount,\n visualEvidenceRequired: source.metrics.visualEvidenceRequired,\n rankedReferenceCount: source.quality.rankedReferenceCount,\n rejectedReferenceCount: source.quality.rejectedReferenceCount,\n missingScreenshotCount: source.quality.missingScreenshotCount,\n diagnosticOnlyReasons: source.quality.diagnosticOnlyReasons,\n ...(typeof source.quality.topReferenceScore === \"number\" ? { topReferenceScore: source.quality.topReferenceScore } : {}),\n ...(typeof source.quality.topReferenceConfidence === \"number\" ? { topReferenceConfidence: source.quality.topReferenceConfidence } : {}),\n ...(typeof source.quality.topReferenceIntentMatched === \"boolean\"\n ? { topReferenceIntentMatched: source.quality.topReferenceIntentMatched }\n : {})\n },\n details: {\n brief: source.brief,\n discoveryFailure: source.discovery.failure ?? \"\",\n hardFailureReasonCodes: source.discovery.hardFailureReasonCodes ?? [],\n primaryConstraintSummary: source.primaryConstraint?.summary ?? \"\"\n }\n };\n};\n\nexport const createProviderWorkflowGuidanceContext = (reasonCode: string): GuidanceContext => ({\n workflow: \"provider\",\n reasonCode\n});\n\nexport const createCanvasGuidanceContext = (reasonCode: string): GuidanceContext => ({\n workflow: \"canvas\",\n reasonCode\n});\n\nexport const createDaemonGuidanceContext = (reasonCode: string): GuidanceContext => ({\n workflow: \"daemon\",\n reasonCode\n});\n\nexport const createCliValidationGuidanceContext = (reasonCode: string): GuidanceContext => ({\n workflow: \"cli\",\n reasonCode\n});\n","import { resolveSiteRecipeForProvider, resolveSiteRecipeForUrl } from \"./site-registry\";\nimport { normalizePinterestReferenceUrl } from \"./pinterest\";\nimport type { SiteRecipe } from \"../types\";\n\nexport type ProviderUrlSiteRecipeCompatibilityResult =\n | { ok: true; recipeId: string }\n | { ok: false; message: string };\n\nexport type ProviderScopedUrlCanonicalityResult =\n | { ok: true }\n | { ok: false; message: string };\n\ntype ProviderUrlSiteRecipeCompatibilityInput = {\n providers: string[];\n urls: string[];\n};\n\ntype ProviderUrlSiteRecipeCompatibilityGateInput = ProviderUrlSiteRecipeCompatibilityInput & {\n query?: string;\n};\n\nconst normalizeNonBlank = (values: string[]): string[] => values\n .map((value) => value.trim())\n .filter((value) => value.length > 0);\n\nconst incompatible = (message: string): ProviderUrlSiteRecipeCompatibilityResult => ({ ok: false, message });\n\nconst supportsBrowserNativeRecovery = (recipe: SiteRecipe | undefined): recipe is SiteRecipe => (\n typeof recipe?.browserNativeDiscovery?.buildSearchUrl === \"function\"\n);\n\nconst isCanonicalRecipeReferenceUrl = (recipe: SiteRecipe, url: string): boolean => {\n if (recipe.id === \"social/pinterest\") {\n return normalizePinterestReferenceUrl(url) !== null;\n }\n return true;\n};\n\nconst isPinterestLikeHostname = (value: string): boolean => {\n const hostname = value.toLowerCase();\n return [\n hostname === \"pinterest.com\",\n hostname.endsWith(\".pinterest.com\"),\n hostname.startsWith(\"pinterest.\"),\n hostname.includes(\".pinterest.\")\n ].some(Boolean);\n};\n\nexport const isPinterestLikeUrl = (value: string): boolean => {\n try {\n return isPinterestLikeHostname(new URL(value).hostname);\n } catch {\n return false;\n }\n};\n\nexport const isNonCanonicalPinterestLikeUrl = (url: string): boolean => (\n (resolveSiteRecipeForUrl(url)?.id === \"social/pinterest\" || isPinterestLikeUrl(url))\n && normalizePinterestReferenceUrl(url) === null\n);\n\nexport const requiresProviderUrlSiteRecipeCompatibility = ({\n providers,\n urls,\n query\n}: ProviderUrlSiteRecipeCompatibilityGateInput): boolean => {\n const providerIds = normalizeNonBlank(providers);\n if (providerIds.length === 0) return false;\n if (!query?.trim()) return true;\n return false;\n};\n\nexport const validateProviderScopedUrlCanonicality = ({\n providers,\n urls\n}: ProviderUrlSiteRecipeCompatibilityInput): ProviderScopedUrlCanonicalityResult => {\n const providerHasPinterest = normalizeNonBlank(providers)\n .some((providerId) => resolveSiteRecipeForProvider(providerId)?.id === \"social/pinterest\");\n if (!providerHasPinterest) return { ok: true };\n\n const nonCanonicalPinterestUrl = normalizeNonBlank(urls)\n .find((url) => normalizePinterestReferenceUrl(url) === null);\n if (!nonCanonicalPinterestUrl) return { ok: true };\n return incompatible(\n `URL ${nonCanonicalPinterestUrl} is not a canonical social/pinterest reference URL for provider-scoped recovery.`\n );\n};\n\nexport const validateProviderUrlSiteRecipeCompatibility = ({\n providers,\n urls\n}: ProviderUrlSiteRecipeCompatibilityInput): ProviderUrlSiteRecipeCompatibilityResult => {\n const providerIds = normalizeNonBlank(providers);\n const referenceUrls = normalizeNonBlank(urls);\n\n if (providerIds.length === 0) {\n return incompatible(\"Provider-scoped URL recovery requires at least one provider.\");\n }\n if (referenceUrls.length === 0) {\n return incompatible(\"Provider-scoped URL recovery requires at least one URL.\");\n }\n\n const providerRecipes = providerIds.map((providerId) => ({\n providerId,\n recipe: resolveSiteRecipeForProvider(providerId)\n }));\n const missingProviderRecipe = providerRecipes.find((entry) => entry.recipe === undefined);\n if (missingProviderRecipe) {\n return incompatible(`Provider ${missingProviderRecipe.providerId} does not support URL-only site recipe recovery.`);\n }\n const nonNativeProviderRecipe = providerRecipes.find((entry) => !supportsBrowserNativeRecovery(entry.recipe));\n if (nonNativeProviderRecipe) {\n return incompatible(`Provider ${nonNativeProviderRecipe.providerId} does not support browser-native URL-only site recipe recovery.`);\n }\n\n const urlRecipes = referenceUrls.map((url) => ({\n url,\n recipe: resolveSiteRecipeForUrl(url)\n }));\n const missingUrlRecipe = urlRecipes.find((entry) => entry.recipe === undefined);\n if (missingUrlRecipe) {\n return incompatible(`URL ${missingUrlRecipe.url} does not match a browser-native site recipe for provider-scoped recovery.`);\n }\n const nonNativeUrlRecipe = urlRecipes.find((entry) => !supportsBrowserNativeRecovery(entry.recipe));\n if (nonNativeUrlRecipe) {\n return incompatible(`URL ${nonNativeUrlRecipe.url} does not match a browser-native site recipe for provider-scoped recovery.`);\n }\n\n const recipeIds = new Set([\n ...providerRecipes.map((entry) => entry.recipe?.id),\n ...urlRecipes.map((entry) => entry.recipe?.id)\n ]);\n if (recipeIds.size !== 1) {\n return incompatible(\"Provider-scoped URL recovery requires every provider and URL to resolve to the same site recipe.\");\n }\n\n const recipeId = providerRecipes[0]?.recipe?.id;\n if (!recipeId) {\n return incompatible(\"Provider-scoped URL recovery could not resolve a site recipe.\");\n }\n const recipe = providerRecipes[0]?.recipe;\n const nonReferenceUrl = recipe\n ? urlRecipes.find((entry) => !isCanonicalRecipeReferenceUrl(recipe, entry.url))\n : undefined;\n if (nonReferenceUrl) {\n return incompatible(`URL ${nonReferenceUrl.url} is not a canonical ${recipeId} reference URL for provider-scoped recovery.`);\n }\n return { ok: true, recipeId };\n};\n","import type { NormalizedRecord } from \"../providers/types\";\n\nexport type InspiredesignDiscoveryRejectionReason =\n | \"missing_url\"\n | \"invalid_url\"\n | \"duplicate_url\";\n\nexport type InspiredesignAcceptedDiscoveryCandidate = {\n status: \"accepted\";\n url: string;\n title?: string;\n source: NormalizedRecord[\"source\"];\n provider: string;\n rank: number;\n};\n\nexport type InspiredesignRejectedDiscoveryCandidate = {\n status: \"rejected\";\n title?: string;\n source: NormalizedRecord[\"source\"];\n provider: string;\n rank: number;\n reason: InspiredesignDiscoveryRejectionReason;\n rawUrl?: string;\n};\n\nexport type InspiredesignDiscoveryCandidate =\n | InspiredesignAcceptedDiscoveryCandidate\n | InspiredesignRejectedDiscoveryCandidate;\n\nexport type InspiredesignDiscoveryResult = {\n accepted: InspiredesignAcceptedDiscoveryCandidate[];\n rejected: InspiredesignRejectedDiscoveryCandidate[];\n};\n\nconst normalizeHttpUrl = (value: string): string | null => {\n try {\n const url = new URL(value);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return null;\n url.hash = \"\";\n if (url.pathname === \"/\" && !/^https?:\\/\\/[^/]+\\/[^?#]/i.test(value)) {\n return `${url.origin}${url.search}`;\n }\n return url.toString();\n } catch (error) {\n void error;\n return null;\n }\n};\n\nexport const extractInspiredesignDiscoveryUrl = (record: Pick<NormalizedRecord, \"url\">): string | null => {\n if (typeof record.url !== \"string\") return null;\n const trimmed = record.url.trim();\n if (!trimmed) return null;\n return normalizeHttpUrl(trimmed);\n};\n\nexport const normalizeInspiredesignDiscoveryRecords = (\n records: NormalizedRecord[]\n): InspiredesignDiscoveryResult => {\n const seen = new Set<string>();\n const accepted: InspiredesignAcceptedDiscoveryCandidate[] = [];\n const rejected: InspiredesignRejectedDiscoveryCandidate[] = [];\n\n records.forEach((record, index) => {\n const rawUrl = typeof record.url === \"string\" ? record.url.trim() : undefined;\n const url = extractInspiredesignDiscoveryUrl(record);\n const base = {\n ...(record.title ? { title: record.title } : {}),\n source: record.source,\n provider: record.provider,\n rank: index + 1\n };\n if (!rawUrl) {\n rejected.push({ ...base, status: \"rejected\", reason: \"missing_url\" });\n return;\n }\n if (!url) {\n rejected.push({ ...base, status: \"rejected\", reason: \"invalid_url\", rawUrl });\n return;\n }\n if (seen.has(url)) {\n rejected.push({ ...base, status: \"rejected\", reason: \"duplicate_url\", rawUrl });\n return;\n }\n seen.add(url);\n accepted.push({ ...base, status: \"accepted\", url });\n });\n\n return { accepted, rejected };\n};\n\nexport const mergeInspiredesignReferenceUrls = (\n explicitUrls: string[],\n discoveredUrls: string[],\n maxReferences: number\n): string[] => {\n const merged: string[] = [];\n const seen = new Set<string>();\n for (const url of [...explicitUrls, ...discoveredUrls]) {\n const normalized = normalizeHttpUrl(url.trim());\n if (!normalized || seen.has(normalized)) continue;\n seen.add(normalized);\n merged.push(normalized);\n if (merged.length >= maxReferences) return merged;\n }\n return merged;\n};\n\nexport const normalizeInspiredesignProviders = (providers: string[] | undefined): string[] => {\n const normalized = (providers ?? [])\n .map((provider) => provider.trim())\n .filter((provider) => provider.length > 0);\n return [...new Set(normalized)];\n};\n","import type { ProviderCookiePolicy, ProviderError, ProviderFailureEntry, ProviderReasonCode } from \"../providers/types\";\nimport type { InspiredesignVisualEvidenceMode } from \"./visual-evidence\";\n\nexport type InspiredesignVisualPolicyReason =\n | \"visual_evidence_off\"\n | \"visual_capture_allowed\"\n | \"policy_blocked\"\n | \"auth_required\"\n | \"challenge_detected\"\n | \"rate_limited\";\n\nexport type InspiredesignVisualPolicyDecision = {\n status: \"allowed\" | \"skipped\" | \"failed\";\n reason: InspiredesignVisualPolicyReason;\n message: string;\n};\n\nexport type InspiredesignVisualPolicyInput = {\n visualEvidence: InspiredesignVisualEvidenceMode;\n failures?: ProviderFailureEntry[];\n topLevelError?: ProviderError;\n cookiePolicy?: ProviderCookiePolicy;\n hasUsableRecords?: boolean;\n};\n\nconst VISUAL_BLOCKER_REASONS = new Set<ProviderReasonCode>([\n \"policy_blocked\",\n \"auth_required\",\n \"challenge_detected\",\n \"rate_limited\"\n]);\n\nconst toVisualPolicyReason = (reasonCode: ProviderReasonCode): InspiredesignVisualPolicyReason | null => {\n if (!VISUAL_BLOCKER_REASONS.has(reasonCode)) return null;\n if (\n reasonCode === \"policy_blocked\"\n || reasonCode === \"auth_required\"\n || reasonCode === \"challenge_detected\"\n || reasonCode === \"rate_limited\"\n ) {\n return reasonCode;\n }\n return null;\n};\n\nconst blockerFromFailures = (\n failures: ProviderFailureEntry[] | undefined\n): InspiredesignVisualPolicyReason | null => {\n for (const failure of failures ?? []) {\n const reasonCode = failure.error.reasonCode;\n if (!reasonCode) continue;\n const blocker = toVisualPolicyReason(reasonCode);\n if (blocker) return blocker;\n }\n return null;\n};\n\nconst blockerFromTopLevelError = (\n error: ProviderError | undefined\n): InspiredesignVisualPolicyReason | null => {\n if (!error?.reasonCode) return null;\n return toVisualPolicyReason(error.reasonCode);\n};\n\nconst messageForBlocker = (reason: InspiredesignVisualPolicyReason): string => {\n switch (reason) {\n case \"policy_blocked\":\n return \"Visual capture skipped because provider policy blocked the reference.\";\n case \"auth_required\":\n return \"Visual capture skipped because authenticated access is unresolved.\";\n case \"challenge_detected\":\n return \"Visual capture skipped because a challenge was detected.\";\n case \"rate_limited\":\n return \"Visual capture skipped because the provider is rate limited.\";\n case \"visual_evidence_off\":\n return \"Visual evidence is disabled for this run.\";\n case \"visual_capture_allowed\":\n return \"Visual capture is allowed for this reference.\";\n }\n};\n\nexport const decideInspiredesignVisualCapturePolicy = (\n input: InspiredesignVisualPolicyInput\n): InspiredesignVisualPolicyDecision => {\n if (input.visualEvidence === \"off\") {\n return {\n status: \"skipped\",\n reason: \"visual_evidence_off\",\n message: messageForBlocker(\"visual_evidence_off\")\n };\n }\n const blocker = input.hasUsableRecords === true\n ? null\n : blockerFromFailures(input.failures) ?? blockerFromTopLevelError(input.topLevelError);\n if (blocker) {\n return {\n status: \"skipped\",\n reason: blocker,\n message: messageForBlocker(blocker)\n };\n }\n return {\n status: \"allowed\",\n reason: \"visual_capture_allowed\",\n message: messageForBlocker(\"visual_capture_allowed\")\n };\n};\n","import type {\n CanvasCodeSyncBindingMetadata,\n CanvasParityArtifact,\n CodeSyncAttachMode,\n CodeSyncBindingStatus,\n CodeSyncLeaseRole,\n CodeSyncProjectionMode,\n CodeSyncSessionStatus,\n CodeSyncState\n} from \"./code-sync/types\";\nexport type { CanvasParityArtifact } from \"./code-sync/types\";\n\nexport const CANVAS_SCHEMA_VERSION = \"1.0.0\";\n\nexport type CanvasPreflightState =\n | \"opened\"\n | \"handshake_read\"\n | \"plan_submitted\"\n | \"plan_invalid\"\n | \"plan_accepted\"\n | \"patching_enabled\";\n\nexport type CanvasPlanStatus = \"missing\" | \"submitted\" | \"invalid\" | \"accepted\";\n\nexport const CANVAS_SESSION_MODES = [\"low-fi-wireframe\", \"high-fi-live-edit\", \"dual-track\", \"document-only\"] as const;\n\nexport type CanvasSessionMode = (typeof CANVAS_SESSION_MODES)[number];\n\nexport const CANVAS_GOVERNANCE_BLOCK_KEYS = [\n \"intent\",\n \"generationPlan\",\n \"designLanguage\",\n \"contentModel\",\n \"layoutSystem\",\n \"typographySystem\",\n \"colorSystem\",\n \"surfaceSystem\",\n \"iconSystem\",\n \"motionSystem\",\n \"responsiveSystem\",\n \"accessibilityPolicy\",\n \"libraryPolicy\",\n \"runtimeBudgets\"\n] as const;\n\nexport type CanvasGovernanceBlockKey = (typeof CANVAS_GOVERNANCE_BLOCK_KEYS)[number];\n\nexport const CANVAS_REQUIRED_MUTATION_GOVERNANCE_KEYS = [\n \"intent\",\n \"generationPlan\",\n \"designLanguage\",\n \"contentModel\",\n \"layoutSystem\",\n \"typographySystem\",\n \"motionSystem\",\n \"responsiveSystem\",\n \"accessibilityPolicy\"\n] as const satisfies readonly CanvasGovernanceBlockKey[];\n\nexport const CANVAS_REQUIRED_SAVE_GOVERNANCE_KEYS = [\n \"intent\",\n \"generationPlan\",\n \"designLanguage\",\n \"contentModel\",\n \"layoutSystem\",\n \"typographySystem\",\n \"colorSystem\",\n \"surfaceSystem\",\n \"iconSystem\",\n \"motionSystem\",\n \"responsiveSystem\",\n \"accessibilityPolicy\",\n \"libraryPolicy\",\n \"runtimeBudgets\"\n] as const satisfies readonly CanvasGovernanceBlockKey[];\n\nexport const CANVAS_OPTIONAL_INHERITED_GOVERNANCE_KEYS = [\n \"colorSystem\",\n \"surfaceSystem\",\n \"iconSystem\",\n \"libraryPolicy\",\n \"runtimeBudgets\"\n] as const satisfies readonly CanvasGovernanceBlockKey[];\n\nexport const CANVAS_GENERATION_PLAN_REQUIRED_FIELDS = [\n \"targetOutcome\",\n \"visualDirection\",\n \"layoutStrategy\",\n \"contentStrategy\",\n \"componentStrategy\",\n \"motionPosture\",\n \"responsivePosture\",\n \"accessibilityPosture\",\n \"validationTargets\"\n] as const;\n\nexport type CanvasGenerationPlanField = (typeof CANVAS_GENERATION_PLAN_REQUIRED_FIELDS)[number];\n\nexport const CANVAS_VISUAL_DIRECTION_PROFILES = [\n \"clean-room\",\n \"cinematic-minimal\",\n \"product-story\",\n \"commerce-system\",\n \"control-room\",\n \"ops-control\",\n \"auth-focused\",\n \"settings-system\",\n \"documentation\"\n] as const;\n\nexport type CanvasVisualDirectionProfile = (typeof CANVAS_VISUAL_DIRECTION_PROFILES)[number];\n\nexport const CANVAS_THEME_STRATEGIES = [\"single-theme\", \"light-dark-parity\", \"multi-theme-system\"] as const;\n\nexport type CanvasThemeStrategy = (typeof CANVAS_THEME_STRATEGIES)[number];\n\nexport const CANVAS_NAVIGATION_MODELS = [\"global-header\", \"sidebar\", \"tabbed\", \"contextual\", \"immersive\"] as const;\n\nexport type CanvasNavigationModel = (typeof CANVAS_NAVIGATION_MODELS)[number];\n\nexport const CANVAS_INTERACTION_STATES = [\n \"default\",\n \"hover\",\n \"focus\",\n \"active\",\n \"disabled\",\n \"loading\",\n \"empty\",\n \"error\",\n \"success\",\n \"selected\"\n] as const;\n\nexport type CanvasInteractionState = (typeof CANVAS_INTERACTION_STATES)[number];\n\nexport const CANVAS_PLAN_VIEWPORTS = [\"desktop\", \"tablet\", \"mobile\"] as const;\n\nexport type CanvasPlanViewport = (typeof CANVAS_PLAN_VIEWPORTS)[number];\n\nexport const CANVAS_PLAN_THEMES = [\"light\", \"dark\"] as const;\n\nexport type CanvasPlanTheme = (typeof CANVAS_PLAN_THEMES)[number];\n\nexport const CANVAS_MOTION_LEVELS = [\"none\", \"minimal\", \"subtle\", \"expressive\"] as const;\n\nexport type CanvasMotionLevel = (typeof CANVAS_MOTION_LEVELS)[number];\n\nexport const CANVAS_REDUCED_MOTION_POLICIES = [\"respect-user-preference\", \"static-alternative\"] as const;\n\nexport type CanvasReducedMotionPolicy = (typeof CANVAS_REDUCED_MOTION_POLICIES)[number];\n\nexport const CANVAS_KEYBOARD_NAVIGATION_MODES = [\"full\", \"core-flows\"] as const;\n\nexport type CanvasKeyboardNavigationMode = (typeof CANVAS_KEYBOARD_NAVIGATION_MODES)[number];\n\nexport const CANVAS_BROWSER_VALIDATION_MODES = [\"required\", \"optional\"] as const;\n\nexport type CanvasBrowserValidationMode = (typeof CANVAS_BROWSER_VALIDATION_MODES)[number];\n\nexport type CanvasVariantSelector = Partial<Record<\"viewport\" | \"theme\" | \"interaction\" | \"content\", string>>;\n\nexport type CanvasLibraryPolicy = {\n icons: string[];\n components: string[];\n styling: string[];\n motion: string[];\n threeD: string[];\n};\n\nexport type CanvasIconRoles = {\n primary: string | null;\n secondary: string | null;\n secondaryAlt: string | null;\n decorative: string | null;\n};\n\nexport type CanvasNodeKind =\n | \"frame\"\n | \"group\"\n | \"text\"\n | \"shape\"\n | \"note\"\n | \"connector\"\n | \"wire-block\"\n | \"component-instance\"\n | \"dom-binding\";\n\nexport type CanvasFeedbackCategory =\n | \"render\"\n | \"console\"\n | \"network\"\n | \"validation\"\n | \"performance\"\n | \"asset\"\n | \"export\"\n | \"import\"\n | \"plugin\"\n | \"code-sync\"\n | \"parity\";\n\nexport type CanvasFeedbackSeverity = \"info\" | \"warning\" | \"error\";\n\nexport type CanvasValidationWarningCode =\n | \"missing-generation-plan\"\n | \"invalid-generation-plan\"\n | \"missing-governance-block\"\n | \"missing-intent\"\n | \"missing-design-language\"\n | \"missing-content-model\"\n | \"missing-typography-system\"\n | \"missing-color-role\"\n | \"missing-surface-policy\"\n | \"missing-state-coverage\"\n | \"missing-reduced-motion-policy\"\n | \"missing-responsive-policy\"\n | \"overflow\"\n | \"token-missing\"\n | \"broken-asset-reference\"\n | \"contrast-failure\"\n | \"hierarchy-weak\"\n | \"asset-provenance-missing\"\n | \"font-policy-missing\"\n | \"font-load-failure\"\n | \"reduced-motion-violation\"\n | \"unresolved-component-binding\"\n | \"icon-policy-violation\"\n | \"library-policy-violation\"\n | \"responsive-mismatch\"\n | \"runtime-budget-exceeded\"\n | \"unsupported-target\"\n | \"export-warning\";\n\nexport const CANVAS_VALIDATION_TARGET_BLOCK_ON_CODES = [\n \"missing-generation-plan\",\n \"invalid-generation-plan\",\n \"missing-governance-block\",\n \"missing-intent\",\n \"missing-design-language\",\n \"missing-content-model\",\n \"missing-typography-system\",\n \"missing-color-role\",\n \"missing-surface-policy\",\n \"missing-state-coverage\",\n \"missing-reduced-motion-policy\",\n \"missing-responsive-policy\",\n \"overflow\",\n \"token-missing\",\n \"broken-asset-reference\",\n \"contrast-failure\",\n \"hierarchy-weak\",\n \"asset-provenance-missing\",\n \"font-policy-missing\",\n \"font-load-failure\",\n \"reduced-motion-violation\",\n \"unresolved-component-binding\",\n \"icon-policy-violation\",\n \"library-policy-violation\",\n \"responsive-mismatch\",\n \"runtime-budget-exceeded\",\n \"unsupported-target\",\n \"export-warning\"\n] as const satisfies readonly CanvasValidationWarningCode[];\n\nexport const CANVAS_PUBLIC_WARNING_CLASSES = CANVAS_VALIDATION_TARGET_BLOCK_ON_CODES;\n\nexport type CanvasPreviewState = \"focused\" | \"pinned\" | \"background\" | \"degraded\";\n\nexport type CanvasDegradeReason = \"overflow\" | \"memory_pressure\" | \"queue_pressure\" | \"frozen\" | \"discarded\";\n\nexport type CanvasProjectionFallbackReason =\n | \"runtime_bridge_unavailable\"\n | \"runtime_projection_unsupported\"\n | \"runtime_projection_failed\"\n | \"runtime_instrumentation_missing\"\n | \"fallback_canvas_html\";\n\nexport type CanvasBlockerCode =\n | \"plan_required\"\n | \"generation_plan_invalid\"\n | \"revision_conflict\"\n | \"unsupported_target\"\n | \"lease_reclaim_required\"\n | \"policy_violation\"\n | \"code_sync_required\"\n | \"code_sync_conflict\"\n | \"code_sync_unsupported\"\n | \"code_sync_out_of_date\";\n\nexport type CanvasBindingKind = string;\n\nexport type CanvasBlockState = \"present\" | \"missing\" | \"invalid\" | \"inherited\" | \"locked\";\n\nexport type CanvasGenerationPlanIssueCode = \"missing_field\" | \"invalid_type\" | \"invalid_value\";\n\nexport type CanvasGenerationPlanIssue = {\n path: string;\n code: CanvasGenerationPlanIssueCode;\n message: string;\n expected?: string | string[];\n received?: unknown;\n};\n\nexport type CanvasGenerationPlanTargetOutcome = {\n mode: CanvasSessionMode;\n summary: string;\n};\n\nexport type CanvasGenerationPlanVisualDirection = {\n profile: CanvasVisualDirectionProfile;\n themeStrategy: CanvasThemeStrategy;\n};\n\nexport type CanvasGenerationPlanLayoutStrategy = {\n approach: string;\n navigationModel: CanvasNavigationModel;\n};\n\nexport type CanvasGenerationPlanContentStrategy = {\n source: string;\n};\n\nexport type CanvasGenerationPlanComponentStrategy = {\n mode: string;\n interactionStates: CanvasInteractionState[];\n};\n\nexport type CanvasGenerationPlanMotionPosture = {\n level: CanvasMotionLevel;\n reducedMotion: CanvasReducedMotionPolicy;\n};\n\nexport type CanvasGenerationPlanResponsivePosture = {\n primaryViewport: CanvasPlanViewport;\n requiredViewports: CanvasPlanViewport[];\n};\n\nexport type CanvasGenerationPlanAccessibilityPosture = {\n target: string;\n keyboardNavigation: CanvasKeyboardNavigationMode;\n};\n\nexport type CanvasGenerationPlanValidationTargets = {\n blockOn: CanvasValidationWarningCode[];\n requiredThemes: CanvasPlanTheme[];\n browserValidation: CanvasBrowserValidationMode;\n maxInteractionLatencyMs: number;\n};\n\nexport type CanvasGenerationPlan = {\n targetOutcome: CanvasGenerationPlanTargetOutcome;\n visualDirection: CanvasGenerationPlanVisualDirection;\n layoutStrategy: CanvasGenerationPlanLayoutStrategy;\n contentStrategy: CanvasGenerationPlanContentStrategy;\n componentStrategy: CanvasGenerationPlanComponentStrategy;\n motionPosture: CanvasGenerationPlanMotionPosture;\n responsivePosture: CanvasGenerationPlanResponsivePosture;\n accessibilityPosture: CanvasGenerationPlanAccessibilityPosture;\n validationTargets: CanvasGenerationPlanValidationTargets;\n interactionMoments?: string[];\n materialEffects?: string[];\n designVectors?: Record<string, unknown>;\n};\n\nexport type CanvasGenerationPlanValidationResult =\n | {\n ok: true;\n missing: [];\n issues: [];\n plan: CanvasGenerationPlan;\n }\n | {\n ok: false;\n missing: CanvasGenerationPlanField[];\n issues: CanvasGenerationPlanIssue[];\n };\n\nexport type CanvasGovernanceBlockState = {\n status: CanvasBlockState;\n source: \"document\" | \"project-default\";\n editable: boolean;\n};\n\nexport type CanvasRect = {\n x: number;\n y: number;\n width: number;\n height: number;\n};\n\nexport type CanvasVariantPatch = {\n selector: CanvasVariantSelector;\n changes: Record<string, unknown>;\n};\n\nexport type CanvasBinding = {\n id: string;\n nodeId: string;\n kind: CanvasBindingKind;\n selector?: string;\n componentName?: string;\n metadata?: Record<string, unknown>;\n codeSync?: CanvasCodeSyncBindingMetadata;\n};\n\nexport type CanvasAsset = {\n id: string;\n sourceType?: \"repo\" | \"remote\" | \"page-derived\" | \"generated\" | \"transient\";\n kind?: string;\n repoPath?: string | null;\n url?: string | null;\n mime?: string;\n width?: number;\n height?: number;\n hash?: string;\n status?: string;\n variants?: Array<Record<string, unknown>>;\n metadata?: Record<string, unknown>;\n};\n\nexport type CanvasSourceFamily =\n | \"canvas_document\"\n | \"framework_component\"\n | \"design_import\"\n | \"starter_template\"\n | \"adapter_plugin\"\n | \"unknown\";\n\nexport type CanvasInventoryOrigin =\n | \"document\"\n | \"code_sync\"\n | \"import\"\n | \"starter\"\n | \"plugin\"\n | \"unknown\";\n\nexport type CanvasAdapterCapability =\n | \"import\"\n | \"export\"\n | \"preview\"\n | \"code_sync\"\n | \"inventory\"\n | \"tokens\"\n | \"starter_templates\";\n\nexport type CanvasAdapterRef = {\n id: string;\n label?: string | null;\n version?: string | null;\n packageName?: string | null;\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasFrameworkRef = {\n id: string;\n label?: string | null;\n packageName?: string | null;\n adapter?: CanvasAdapterRef | null;\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasAdapterPluginRef = {\n id: string;\n label?: string | null;\n version?: string | null;\n packageName?: string | null;\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasComponentVariant = {\n id: string;\n name: string;\n selector: CanvasVariantSelector;\n description?: string | null;\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasComponentPropDescriptor = {\n name: string;\n type?: string | null;\n required?: boolean;\n defaultValue?: unknown;\n description?: string | null;\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasComponentSlotDescriptor = {\n name: string;\n description?: string | null;\n allowedKinds: string[];\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasComponentEventDescriptor = {\n name: string;\n description?: string | null;\n payloadShape?: Record<string, unknown>;\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasComponentContentContract = {\n acceptsText: boolean;\n acceptsRichText: boolean;\n slotNames: string[];\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasComponentInventoryItem = {\n id: string;\n name: string;\n componentName?: string | null;\n description?: string | null;\n sourceKind?: string | null;\n sourceFamily: CanvasSourceFamily;\n origin: CanvasInventoryOrigin;\n framework?: CanvasFrameworkRef | null;\n adapter?: CanvasAdapterRef | null;\n plugin?: CanvasAdapterPluginRef | null;\n variants: CanvasComponentVariant[];\n props: CanvasComponentPropDescriptor[];\n slots: CanvasComponentSlotDescriptor[];\n events: CanvasComponentEventDescriptor[];\n content: CanvasComponentContentContract;\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasTokenAlias = {\n path: string;\n targetPath: string;\n modeId?: string | null;\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasTokenBinding = {\n path: string;\n nodeId?: string | null;\n bindingId?: string | null;\n property?: string | null;\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasTokenMode = {\n id: string;\n name: string;\n value: unknown;\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasTokenItem = {\n id: string;\n path: string;\n value: unknown;\n type?: string | null;\n description?: string | null;\n modes: CanvasTokenMode[];\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasTokenCollection = {\n id: string;\n name: string;\n items: CanvasTokenItem[];\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasTokenStore = {\n values: Record<string, unknown>;\n collections: CanvasTokenCollection[];\n aliases: CanvasTokenAlias[];\n bindings: CanvasTokenBinding[];\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasDocumentImportMode =\n | \"replace_current_page\"\n | \"append_pages\"\n | \"components_only\";\n\nexport type CanvasImportFailureCode =\n | \"missing_token\"\n | \"scope_denied\"\n | \"variables_unavailable\"\n | \"plan_limited\"\n | \"account_limited\"\n | \"rate_limited\"\n | \"node_not_found\"\n | \"asset_fetch_failed\"\n | \"framework_materializer_missing\"\n | \"unsupported_figma_node\";\n\nexport type CanvasDocumentImportRequest = {\n sourceUrl?: string | null;\n fileKey?: string | null;\n nodeIds?: string[];\n mode?: CanvasDocumentImportMode;\n frameworkId?: string | null;\n frameworkAdapterId?: string | null;\n includeVariables?: boolean;\n depth?: number | null;\n geometryPaths?: boolean;\n};\n\nexport type CanvasImportAssetReceipt = {\n assetId: string;\n sourceType?: string | null;\n repoPath?: string | null;\n url?: string | null;\n status?: string | null;\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasImportSource = {\n id: string;\n kind: string;\n label?: string | null;\n uri?: string | null;\n sourceDialect?: string | null;\n frameworkId?: string | null;\n pluginId?: string | null;\n adapterIds: string[];\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasImportProvenance = {\n id: string;\n source: CanvasImportSource;\n importedAt?: string | null;\n assetReceipts: CanvasImportAssetReceipt[];\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasDocumentImportResult = {\n ok: true;\n mode: CanvasDocumentImportMode;\n documentRevision: number;\n importedPageIds: string[];\n importedNodeIds: string[];\n importedInventoryItemIds: string[];\n importedAssetIds: string[];\n importedTokenCollectionIds: string[];\n degradedFailureCodes: CanvasImportFailureCode[];\n provenance: CanvasImportProvenance;\n summary: CanvasSessionSummary;\n};\n\nexport type CanvasStarterTemplate = {\n id: string;\n name: string;\n description?: string | null;\n tags: string[];\n defaultFrameworkId: string;\n compatibleFrameworkIds: string[];\n kitIds: string[];\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasStarterApplication = {\n template: CanvasStarterTemplate | null;\n frameworkId?: string | null;\n appliedAt?: string | null;\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasKitStarterHook = {\n starterId: string;\n priority?: number;\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasKitCatalogEntry = {\n id: string;\n label: string;\n description?: string | null;\n defaultFrameworkId: string;\n compatibleFrameworkIds: string[];\n defaultLibraryAdapterIds: string[];\n pluginHints: string[];\n starterHooks: CanvasKitStarterHook[];\n tokenCollections: CanvasTokenCollection[];\n items: CanvasComponentInventoryItem[];\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasFrameworkCompatibility = {\n frameworkId: string;\n versions: string[];\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasLibraryCompatibility = {\n libraryId: string;\n categories: string[];\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasCapabilityGrant = {\n capability: CanvasAdapterCapability;\n granted: boolean;\n reason?: string | null;\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasAdapterPluginDeclaration = {\n id: string;\n label?: string | null;\n frameworks: CanvasFrameworkCompatibility[];\n libraries: CanvasLibraryCompatibility[];\n declaredCapabilities: CanvasAdapterCapability[];\n grantedCapabilities: CanvasCapabilityGrant[];\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasAdapterErrorEnvelope = {\n pluginId?: string | null;\n code: string;\n message: string;\n details: Record<string, unknown>;\n};\n\nexport type CanvasDocumentMeta = {\n imports: CanvasImportProvenance[];\n starter: CanvasStarterApplication | null;\n adapterPlugins: CanvasAdapterPluginDeclaration[];\n pluginErrors: CanvasAdapterErrorEnvelope[];\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasNode = {\n id: string;\n kind: CanvasNodeKind;\n name: string;\n pageId: string;\n parentId: string | null;\n childIds: string[];\n rect: CanvasRect;\n props: Record<string, unknown>;\n style: Record<string, unknown>;\n tokenRefs: Record<string, unknown>;\n bindingRefs: Record<string, unknown>;\n variantPatches: CanvasVariantPatch[];\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasPage = {\n id: string;\n name: string;\n description?: string;\n path: string;\n rootNodeId: string | null;\n prototypeIds: string[];\n nodes: CanvasNode[];\n metadata: Record<string, unknown>;\n};\n\nexport type CanvasPrototype = {\n id: string;\n pageId: string;\n route: string;\n name?: string;\n defaultVariants?: CanvasVariantSelector;\n targetPreferences?: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n};\n\nexport type CanvasGovernanceRecord = Record<string, unknown>;\n\nexport type CanvasDesignGovernance = {\n intent: CanvasGovernanceRecord;\n generationPlan: CanvasGenerationPlan | CanvasGovernanceRecord;\n designLanguage: CanvasGovernanceRecord;\n contentModel: CanvasGovernanceRecord;\n layoutSystem: CanvasGovernanceRecord;\n typographySystem: CanvasGovernanceRecord;\n colorSystem: CanvasGovernanceRecord;\n surfaceSystem: CanvasGovernanceRecord;\n iconSystem: CanvasGovernanceRecord;\n motionSystem: CanvasGovernanceRecord;\n responsiveSystem: CanvasGovernanceRecord;\n accessibilityPolicy: CanvasGovernanceRecord;\n libraryPolicy: CanvasGovernanceRecord;\n runtimeBudgets: CanvasGovernanceRecord;\n};\n\nexport type CanvasDocument = {\n schemaVersion: string;\n documentId: string;\n title: string;\n createdAt: string;\n updatedAt: string;\n designGovernance: CanvasDesignGovernance;\n pages: CanvasPage[];\n components: Array<Record<string, unknown>>;\n componentInventory: CanvasComponentInventoryItem[];\n tokens: CanvasTokenStore;\n assets: CanvasAsset[];\n viewports: Array<Record<string, unknown>>;\n themes: Array<Record<string, unknown>>;\n bindings: CanvasBinding[];\n prototypes: CanvasPrototype[];\n meta: CanvasDocumentMeta;\n};\n\nexport type CanvasHistoryDirection = \"undo\" | \"redo\";\n\nexport type CanvasHistoryState = {\n canUndo: boolean;\n canRedo: boolean;\n undoDepth: number;\n redoDepth: number;\n stale: boolean;\n depthLimit: number;\n};\n\nexport type CanvasPatch =\n | {\n op: \"page.create\";\n page: Partial<CanvasPage> & Pick<CanvasPage, \"id\" | \"rootNodeId\">;\n }\n | {\n op: \"page.update\";\n pageId: string;\n changes: Record<string, unknown>;\n }\n | {\n op: \"node.insert\";\n pageId: string;\n parentId: string | null;\n node: Partial<CanvasNode> & Pick<CanvasNode, \"id\" | \"kind\">;\n }\n | {\n op: \"node.update\";\n nodeId: string;\n changes: Record<string, unknown>;\n }\n | {\n op: \"node.remove\";\n nodeId: string;\n }\n | {\n op: \"node.reparent\";\n nodeId: string;\n parentId: string | null;\n index?: number;\n }\n | {\n op: \"node.reorder\";\n nodeId: string;\n index: number;\n }\n | {\n op: \"node.duplicate\";\n nodeId: string;\n parentId?: string | null;\n index?: number;\n idMap?: Record<string, string>;\n }\n | {\n op: \"node.visibility.set\";\n nodeId: string;\n hidden: boolean;\n }\n | {\n op: \"variant.patch\";\n nodeId: string;\n selector: CanvasVariantSelector;\n changes: Record<string, unknown>;\n }\n | {\n op: \"token.set\";\n path: string;\n value: unknown;\n }\n | {\n op: \"tokens.merge\";\n tokens: Partial<CanvasTokenStore>;\n }\n | {\n op: \"tokens.replace\";\n tokens: CanvasTokenStore;\n }\n | {\n op: \"governance.update\";\n block: CanvasGovernanceBlockKey;\n changes: Record<string, unknown>;\n }\n | {\n op: \"asset.attach\";\n nodeId: string;\n assetId: string;\n }\n | {\n op: \"binding.set\";\n nodeId: string;\n binding: Omit<CanvasBinding, \"nodeId\"> & Partial<Pick<CanvasBinding, \"nodeId\">>;\n }\n | {\n op: \"binding.remove\";\n bindingId: string;\n }\n | {\n op: \"prototype.upsert\";\n prototype: CanvasPrototype;\n }\n | {\n op: \"inventory.promote\";\n nodeId: string;\n itemId?: string;\n name?: string;\n description?: string | null;\n origin?: CanvasInventoryOrigin;\n metadata?: Record<string, unknown>;\n }\n | {\n op: \"inventory.update\";\n itemId: string;\n changes: Record<string, unknown>;\n }\n | {\n op: \"inventory.upsert\";\n item: CanvasComponentInventoryItem;\n }\n | {\n op: \"inventory.remove\";\n itemId: string;\n }\n | {\n op: \"starter.apply\";\n starter: CanvasStarterApplication | null;\n };\n\nexport type CanvasFeedbackItem = {\n id: string;\n cursor: string;\n severity: CanvasFeedbackSeverity;\n category: CanvasFeedbackCategory;\n class: string;\n documentId: string;\n pageId: string | null;\n prototypeId: string | null;\n targetId: string | null;\n documentRevision: number;\n message: string;\n evidenceRefs: string[];\n details: Record<string, unknown>;\n};\n\nexport type CanvasFeedbackCompleteReason =\n | \"session_closed\"\n | \"lease_revoked\"\n | \"subscription_replaced\"\n | \"document_unloaded\";\n\nexport type CanvasFeedbackEvent =\n | {\n eventType: \"feedback.item\";\n item: CanvasFeedbackItem;\n }\n | {\n eventType: \"feedback.heartbeat\";\n cursor: string | null;\n ts: string;\n activeTargetIds: string[];\n }\n | {\n eventType: \"feedback.complete\";\n cursor: string | null;\n ts: string;\n reason: CanvasFeedbackCompleteReason;\n };\n\nexport type CanvasFeedbackSubscribeResult = {\n subscriptionId: string;\n cursor: string | null;\n heartbeatMs: number;\n expiresAt: string | null;\n initialItems: CanvasFeedbackItem[];\n activeTargetIds: string[];\n};\n\nexport type CanvasFeedbackUnsubscribeResult = {\n ok: true;\n subscriptionId: string;\n};\n\nexport type CanvasValidationWarning = {\n code: CanvasValidationWarningCode;\n severity: CanvasFeedbackSeverity;\n message: string;\n details?: Record<string, unknown>;\n auditId?: string;\n};\n\nexport type CanvasBlocker = {\n code: CanvasBlockerCode;\n blockingCommand: string;\n requiredNextCommands: string[];\n latestRevision?: number;\n message: string;\n details?: Record<string, unknown>;\n};\n\nexport type CanvasTargetState = {\n targetId: string;\n prototypeId: string | null;\n previewMode: CanvasPreviewState;\n previewState: CanvasPreviewState;\n renderStatus: \"idle\" | \"rendered\" | \"degraded\";\n degradeReason?: CanvasDegradeReason;\n lastRenderedAt?: string;\n sourceUrl?: string | null;\n projection?: CodeSyncProjectionMode;\n fallbackReason?: CanvasProjectionFallbackReason | null;\n parityArtifact?: CanvasParityArtifact | null;\n};\n\nexport type CanvasAttachedClient = {\n clientId: string;\n role: CodeSyncLeaseRole;\n attachedAt: string;\n lastSeenAt: string;\n};\n\nexport type CanvasSessionSummary = {\n canvasSessionId: string;\n browserSessionId: string | null;\n documentId: string;\n leaseId: string;\n attachModes?: CodeSyncAttachMode[];\n preflightState: CanvasPreflightState;\n planStatus: CanvasPlanStatus;\n mode: CanvasSessionMode;\n documentRevision: number;\n libraryPolicy: CanvasLibraryPolicy;\n componentInventoryCount: number;\n availableInventoryCount?: number;\n catalogKitIds?: string[];\n availableStarterCount?: number;\n componentSourceKinds: string[];\n frameworkIds?: string[];\n pluginIds?: string[];\n inventoryOrigins?: CanvasInventoryOrigin[];\n declaredCapabilities?: CanvasAdapterCapability[];\n grantedCapabilities?: CanvasAdapterCapability[];\n capabilityDenials?: CanvasCapabilityGrant[];\n pluginErrors?: CanvasAdapterErrorEnvelope[];\n importSources?: string[];\n iconRoles: CanvasIconRoles;\n targets: CanvasTargetState[];\n overlayMounts: Array<{ mountId: string; targetId: string; mountedAt: string }>;\n designTabTargetId?: string | null;\n attachedClients?: CanvasAttachedClient[];\n leaseHolderClientId?: string | null;\n watchState?: CodeSyncSessionStatus[\"watchState\"];\n codeSyncState?: CodeSyncState;\n boundFiles?: string[];\n conflictCount?: number;\n driftState?: CodeSyncSessionStatus[\"driftState\"];\n lastImportAt?: string;\n lastPushAt?: string;\n starterId?: string | null;\n starterName?: string | null;\n starterFrameworkId?: string | null;\n starterAppliedAt?: string | null;\n bindings?: CodeSyncBindingStatus[];\n history?: CanvasHistoryState;\n};\n\nexport type CanvasCommandContext = {\n command: string;\n canvasSessionId?: string;\n leaseId?: string;\n};\n","import { createHash } from \"crypto\";\nimport { classifyBlockerSignal } from \"./blocker\";\nimport { applyProviderIssueHint, readProviderIssueHintFromRecord } from \"./constraint\";\nimport { normalizeProviderReasonCode } from \"./errors\";\nimport { renderShopping, type ShoppingOffer } from \"./renderer\";\nimport { SHOPPING_PROVIDER_PROFILES } from \"./shopping\";\nimport type {\n JsonValue,\n NormalizedRecord,\n ProviderFailureEntry,\n ProviderReasonCode\n} from \"./types\";\nimport { canonicalizeUrl } from \"./web/crawler\";\nimport { extractText, toSnippet } from \"./web/extract\";\nimport type { CompiledShoppingWorkflow, ShoppingWorkflowRun } from \"./shopping-workflow\";\n\nexport const LOOKS_LIKE_URL_RE = /^https?:\\/\\/\\S+$/i;\nconst PRICE_TOKEN_RE = /((?:US\\$|CA\\$|C\\$|USD|CAD|EUR|GBP|[$€£]))\\s*([0-9]{1,4}(?:[.,][0-9]{3})*(?:[.,][0-9]{1,2})?)/gi;\nconst CONTEXTUAL_PRICE_TOKEN_RE = /(?:connect to any carrier later|starting at|starts at|starting from|from|buy now for|buy for)\\s*((?:US\\$|CA\\$|C\\$|USD|CAD|EUR|GBP|[$€£]))\\s*([0-9]{1,4}(?:[.,][0-9]{3})*(?:[.,][0-9]{1,2})?)/gi;\nconst PRODUCT_COPY_CUTOFF_PATTERNS = [\n /frequently asked questions/i,\n /footer footnotes/i,\n /which [a-z0-9 ]+ is right for you/i,\n /compare all [a-z0-9 ]+ models/i,\n /more ways to shop/i,\n /privacy policy/i,\n /terms of use/i\n] as const;\nconst PRODUCT_FEATURE_NOISE_RE = /\\b(?:frequently asked questions|footnote|carrier deals|connect to any carrier later|at&t|t-mobile|verizon|boost mobile|applecare|privacy policy|terms of use|returns?|refunds?|bill credits?|trade[- ]?in|required|monthly|\\/mo\\b|deductible|service fee|more ways to shop|shipper\\s*\\/\\s*seller|main content|about this item|buying options|compare with similar items|search opt|cart shift|home shift|orders shift|add to cart shift|show\\/hide shortcuts|image unavailable|brief content visible|full content visible|see more product details)\\b/i;\nconst PRODUCT_PRICE_NEGATIVE_CONTEXT_RE = /\\b(?:save(?: up to)?|trade[- ]?in|bill credits?|credit|credits|off\\b|monthly|per month|payments?|\\/mo\\b|deductible|service fee|activation fee|finance options?|learn more|view your offers)\\b/i;\nconst PRODUCT_PRICE_POSITIVE_CONTEXT_RE = /\\b(?:starting at|starts at|starting from|from|connect to any carrier later|buy now|buy for|unlocked)\\b/i;\nconst SHOPPING_INTENT_STOP_WORDS = new Set([\n \"a\",\n \"an\",\n \"and\",\n \"best\",\n \"buy\",\n \"deal\",\n \"deals\",\n \"for\",\n \"from\",\n \"new\",\n \"on\",\n \"sale\",\n \"shop\",\n \"shopping\",\n \"the\",\n \"to\",\n \"with\"\n]);\nconst SHOPPING_ACCESSORY_KEYWORDS = new Set([\n \"accessory\",\n \"adapter\",\n \"adapters\",\n \"bag\",\n \"bags\",\n \"cable\",\n \"cables\",\n \"case\",\n \"cases\",\n \"charger\",\n \"chargers\",\n \"cover\",\n \"covers\",\n \"dock\",\n \"docks\",\n \"hub\",\n \"hubs\",\n \"keyboard\",\n \"protector\",\n \"protectors\",\n \"screenprotector\",\n \"skin\",\n \"skins\",\n \"sleeve\",\n \"sleeves\",\n \"stand\",\n \"stands\"\n]);\nconst USED_INVENTORY_QUERY_RE = /\\b(?:used|pre owned|preowned|refurbished|renewed|open box|openbox)\\b/i;\nconst USED_INVENTORY_URL_RE = /\\b(?:conditiongroupcode=3|used|pre-?owned|refurbished|renewed|open-?box)\\b/i;\nconst KNOWN_BRAND_BY_HOST_SUFFIX: Record<string, string> = {\n \"aliexpress.com\": \"AliExpress\",\n \"amazon.com\": \"Amazon\",\n \"apple.com\": \"Apple\",\n \"bestbuy.com\": \"Best Buy\",\n \"costco.com\": \"Costco\",\n \"ebay.com\": \"eBay\",\n \"macys.com\": \"Macy's\",\n \"newegg.com\": \"Newegg\",\n \"target.com\": \"Target\",\n \"temu.com\": \"Temu\",\n \"walmart.com\": \"Walmart\"\n};\nconst REGION_CURRENCY_BY_REGION: Record<string, string> = {\n us: \"USD\",\n ca: \"CAD\",\n gb: \"GBP\",\n uk: \"GBP\",\n eu: \"EUR\"\n};\n\nconst hash = (value: string): string => createHash(\"sha1\").update(value).digest(\"hex\").slice(0, 16);\n\nexport const normalizePlainText = (value: string | undefined): string => {\n if (!value) return \"\";\n return extractText(value)\n .replace(/[\\u0000-\\u001F\\u007F-\\u009F]+/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n};\n\nconst normalizeShoppingIntentText = (value: string | undefined): string => {\n return normalizePlainText(value)\n .toLowerCase()\n .replace(/(\\d+)\\s+(gb|tb|inch|in)\\b/g, \"$1$2\")\n .replace(/[^a-z0-9]+/g, \" \")\n .trim();\n};\n\nconst tokenizeShoppingIntent = (value: string | undefined): string[] => {\n const normalized = normalizeShoppingIntentText(value);\n if (!normalized) return [];\n return normalized\n .split(/\\s+/)\n .filter((token) => token.length >= 2 && !SHOPPING_INTENT_STOP_WORDS.has(token));\n};\n\nconst hasAccessoryMarker = (value: string | undefined): boolean => {\n return tokenizeShoppingIntent(value).some((token) => SHOPPING_ACCESSORY_KEYWORDS.has(token));\n};\n\nconst isAccessoryQuery = (query: string): boolean => hasAccessoryMarker(query);\n\nconst queryRequestsUsedInventory = (query: string): boolean => USED_INVENTORY_QUERY_RE.test(normalizeShoppingIntentText(query));\n\nconst offerLooksUsedInventory = (offer: ShoppingOffer): boolean => {\n const normalizedOffer = normalizeShoppingIntentText(`${offer.title} ${offer.url}`);\n return USED_INVENTORY_QUERY_RE.test(normalizedOffer) || USED_INVENTORY_URL_RE.test(offer.url);\n};\n\nconst normalizeFeatureEntry = (value: string): string | null => {\n const normalized = normalizePlainText(value);\n if (normalized.length < 8 || normalized.length > 160) return null;\n if (!/[a-z]/i.test(normalized)) return null;\n if (PRODUCT_FEATURE_NOISE_RE.test(normalized)) return null;\n if (/\\$[0-9]/.test(normalized)) return null;\n if (/\\b(?:can i|will my|when i|what resources|learn more)\\b/i.test(normalized)) return null;\n return normalized;\n};\n\nexport const sanitizeFeatureList = (values: string[]): string[] => {\n const seen = new Set<string>();\n const normalized: string[] = [];\n for (const value of values) {\n const cleaned = normalizeFeatureEntry(value);\n if (!cleaned) continue;\n const key = cleaned.toLowerCase();\n if (seen.has(key)) continue;\n seen.add(key);\n normalized.push(cleaned);\n if (normalized.length >= 12) break;\n }\n return normalized;\n};\n\nexport const trimProductCopy = (value: string): string => {\n let trimmed = normalizePlainText(value);\n if (!trimmed) return \"\";\n let cutoff = trimmed.length;\n for (const pattern of PRODUCT_COPY_CUTOFF_PATTERNS) {\n const matchIndex = trimmed.search(pattern);\n if (matchIndex >= 0) {\n cutoff = Math.min(cutoff, matchIndex);\n }\n }\n trimmed = trimmed.slice(0, cutoff).trim();\n return trimmed.replace(/\\bFootnote\\b\\s*[0-9†‡§∆◊※±]*/gi, \" \").replace(/\\s+/g, \" \").trim();\n};\n\nexport const stripBrandSuffix = (title: string, brand: string | undefined): string => {\n if (!brand) return title;\n return title.replace(new RegExp(`\\\\s*[-|:]\\\\s*${brand.replace(/[-/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")}\\\\s*$`, \"i\"), \"\").trim();\n};\n\nexport const inferBrandFromUrl = (url: string | undefined): string | undefined => {\n if (!url) return undefined;\n try {\n const host = new URL(url).hostname.toLowerCase();\n for (const [suffix, brand] of Object.entries(KNOWN_BRAND_BY_HOST_SUFFIX)) {\n if (host === suffix || host.endsWith(`.${suffix}`)) {\n return brand;\n }\n }\n const profile = SHOPPING_PROVIDER_PROFILES.find((entry) => entry.domains.some((domain) => host === domain || host.endsWith(`.${domain}`)));\n if (profile) return profile.displayName;\n return undefined;\n } catch {\n return undefined;\n }\n};\n\nexport const extractBrandFromTitle = (title: string | undefined): string | undefined => {\n if (!title) return undefined;\n const cleaned = normalizePlainText(title);\n const match = /(?:[-|:]\\s*)([A-Z][A-Za-z0-9&+' -]{1,40})$/.exec(cleaned);\n return match?.[1]?.trim() || undefined;\n};\n\nconst parseMatchedPrice = (currencySymbol: string, rawAmount: string): {\n amount: number;\n currency: string;\n} | null => {\n const amount = Number(rawAmount.replace(/,/g, \"\"));\n if (!Number.isFinite(amount) || amount <= 0) return null;\n const normalizedCurrency = currencySymbol.trim().toUpperCase();\n const currency = normalizedCurrency === \"€\"\n ? \"EUR\"\n : normalizedCurrency === \"£\"\n ? \"GBP\"\n : normalizedCurrency === \"CAD\" || normalizedCurrency === \"CA$\" || normalizedCurrency === \"C$\"\n ? \"CAD\"\n : \"USD\";\n return {\n amount,\n currency\n };\n};\n\nexport const asNumber = (value: unknown): number => {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim()) {\n const parsed = Number(value.replace(/,/g, \"\"));\n if (Number.isFinite(parsed)) return parsed;\n }\n return 0;\n};\n\nexport const parsePriceFromContent = (content: string | undefined): { amount: number; currency: string } => {\n const normalized = normalizePlainText(content)\n .replace(/([$€£])\\s+/g, \"$1\")\n .replace(/\\b(?:US\\$|CA\\$|C\\$|USD|CAD|EUR|GBP)\\s+/gi, (match) => `${match.trim().toUpperCase()} `)\n .replace(/(\\d)\\s*([.,])\\s*(\\d{2})/g, \"$1$2$3\");\n if (!normalized) return { amount: 0, currency: \"USD\" };\n\n const contextualMatches = [...normalized.matchAll(CONTEXTUAL_PRICE_TOKEN_RE)]\n .map((match) => {\n const parsed = parseMatchedPrice(match[1]!, match[2]!);\n if (!parsed) return null;\n const index = match.index as number;\n const context = normalized.slice(Math.max(0, index - 48), Math.min(normalized.length, index + match[0].length + 48));\n return PRODUCT_PRICE_NEGATIVE_CONTEXT_RE.test(context) ? null : parsed;\n })\n .filter((entry): entry is { amount: number; currency: string } => entry !== null)\n .sort((left, right) => left.amount - right.amount);\n if (contextualMatches.length > 0) {\n return contextualMatches[0]!;\n }\n\n const candidates = [...normalized.matchAll(PRICE_TOKEN_RE)]\n .map((match) => {\n const parsed = parseMatchedPrice(match[1]!, match[2]!);\n if (!parsed) return null;\n const index = match.index as number;\n const context = normalized.slice(Math.max(0, index - 48), Math.min(normalized.length, index + match[0].length + 48));\n let score = 0;\n if (PRODUCT_PRICE_NEGATIVE_CONTEXT_RE.test(context)) score -= 4;\n if (PRODUCT_PRICE_POSITIVE_CONTEXT_RE.test(context)) score += 3;\n if (parsed.amount < 10) score -= 3;\n return {\n ...parsed,\n score,\n index\n };\n })\n .filter((entry): entry is { amount: number; currency: string; score: number; index: number } => entry !== null)\n .sort((left, right) => right.score - left.score || left.amount - right.amount || left.index - right.index);\n if (candidates.length === 0 || candidates[0]!.score < -1) {\n return { amount: 0, currency: \"USD\" };\n }\n return {\n amount: candidates[0]!.amount,\n currency: candidates[0]!.currency\n };\n};\n\nconst scoreShoppingOfferIntent = (\n query: string,\n offer: ShoppingOffer\n): { intentScore: number; accessoryPenalty: number; usedInventoryPenalty: number; directMatch: boolean } => {\n const queryTokens = tokenizeShoppingIntent(query);\n if (queryTokens.length === 0) {\n return {\n intentScore: 0,\n accessoryPenalty: 0,\n usedInventoryPenalty: 0,\n directMatch: false\n };\n }\n\n let offerUrlIntentText = \"\";\n try {\n const parsed = new URL(offer.url);\n offerUrlIntentText = `${parsed.hostname} ${parsed.pathname}`;\n } catch {\n offerUrlIntentText = \"\";\n }\n const offerText = `${offer.title} ${offerUrlIntentText}`.trim();\n const offerTokens = new Set(tokenizeShoppingIntent(offerText));\n const normalizedQuery = normalizeShoppingIntentText(query);\n const normalizedOffer = normalizeShoppingIntentText(offerText);\n const matchedTokens = queryTokens.filter((token) => offerTokens.has(token));\n const importantMatches = matchedTokens.filter((token) => token.length > 2 || /\\d/.test(token));\n const exactPhrase = normalizedQuery.length > 0 && normalizedOffer.includes(normalizedQuery);\n const directMatch = exactPhrase || importantMatches.length >= Math.min(queryTokens.length, 3);\n const accessoryPenalty = !isAccessoryQuery(query) && hasAccessoryMarker(offerText) ? 6 : 0;\n const usedInventoryPenalty = !queryRequestsUsedInventory(query) && offerLooksUsedInventory(offer) ? 10 : 0;\n const intentScore = (importantMatches.length * 3)\n + ((matchedTokens.length - importantMatches.length) * 1.5)\n + (exactPhrase ? 4 : 0)\n + (directMatch ? 2 : 0)\n - accessoryPenalty\n - usedInventoryPenalty;\n\n return {\n intentScore,\n accessoryPenalty,\n usedInventoryPenalty,\n directMatch\n };\n};\n\nconst availabilityRank = (availability: ShoppingOffer[\"availability\"]): number => {\n switch (availability) {\n case \"in_stock\":\n return 1;\n case \"limited\":\n return 0.75;\n case \"unknown\":\n return 0.45;\n case \"out_of_stock\":\n return 0.1;\n }\n};\n\nconst computeDealScore = (offer: ShoppingOffer, now: Date): number => {\n const total = Math.max(0, offer.price.amount + offer.shipping.amount);\n const priceScore = total > 0 ? 1 / (1 + total / 100) : 0;\n const availabilityScore = availabilityRank(offer.availability);\n const ratingScore = Math.max(0, Math.min(1, offer.rating / 5));\n const recencyHours = Math.max(0, (now.getTime() - new Date(offer.price.retrieved_at).getTime()) / (60 * 60 * 1000));\n const recencyScore = 1 / (1 + recencyHours / 24);\n const score = (priceScore * 0.55) + (availabilityScore * 0.2) + (ratingScore * 0.15) + (recencyScore * 0.1);\n return Number(score.toFixed(6));\n};\n\nexport const extractShoppingOffer = (record: NormalizedRecord, now: Date): ShoppingOffer => {\n const nested = (record.attributes.shopping_offer ?? {}) as Record<string, unknown>;\n const nestedPrice = (nested.price ?? {}) as Record<string, unknown>;\n const nestedShipping = (nested.shipping ?? {}) as Record<string, unknown>;\n const retrievalPath = typeof record.attributes.retrievalPath === \"string\"\n ? record.attributes.retrievalPath\n : \"\";\n const hasNestedPrice = asNumber(nestedPrice.amount) > 0;\n const priceSource = typeof nested.price_source === \"string\" ? nested.price_source : \"unresolved\";\n const priceIsTrustworthy = nested.price_is_trustworthy === true;\n const allowContentFallback = retrievalPath === \"shopping:search:result-card\"\n || retrievalPath === \"shopping:search:url\"\n || priceIsTrustworthy\n || priceSource === \"search_card_context\"\n || priceSource === \"search_title_inline\";\n const fallbackPrice = allowContentFallback ? parsePriceFromContent(record.content) : { amount: 0, currency: \"USD\" };\n const priceAmount = hasNestedPrice ? asNumber(nestedPrice.amount) : fallbackPrice.amount;\n const priceCurrency = hasNestedPrice && typeof nestedPrice.currency === \"string\" && nestedPrice.currency.trim()\n ? nestedPrice.currency\n : fallbackPrice.currency;\n const retrievedAt = typeof nestedPrice.retrieved_at === \"string\" && nestedPrice.retrieved_at.trim()\n ? nestedPrice.retrieved_at\n : now.toISOString();\n\n const title = (typeof nested.title === \"string\" && nested.title.trim())\n ? nested.title\n : record.title ?? record.url ?? record.provider;\n const url = (typeof nested.url === \"string\" && nested.url.trim())\n ? nested.url\n : record.url ?? \"\";\n\n const shippingAmount = asNumber(nestedShipping.amount);\n const shippingCurrency = typeof nestedShipping.currency === \"string\" && nestedShipping.currency.trim()\n ? nestedShipping.currency\n : priceCurrency;\n\n const availabilityRaw = typeof nested.availability === \"string\" ? nested.availability : \"unknown\";\n const availability: ShoppingOffer[\"availability\"] = availabilityRaw === \"in_stock\" || availabilityRaw === \"limited\" || availabilityRaw === \"out_of_stock\"\n ? availabilityRaw\n : \"unknown\";\n\n const offer: ShoppingOffer = {\n offer_id: `${record.provider}:${record.id}`,\n product_id: typeof nested.product_id === \"string\" && nested.product_id.trim()\n ? nested.product_id\n : hash(`${canonicalizeUrl(url)}::${title.toLowerCase()}`),\n provider: record.provider,\n url,\n title,\n price: {\n amount: priceAmount,\n currency: priceCurrency,\n retrieved_at: retrievedAt\n },\n shipping: {\n amount: shippingAmount,\n currency: shippingCurrency,\n notes: typeof nestedShipping.notes === \"string\" ? nestedShipping.notes : \"unknown\"\n },\n availability,\n rating: asNumber(nested.rating),\n reviews_count: asNumber(nested.reviews_count),\n deal_score: 0,\n attributes: {\n ...record.attributes,\n source_record_id: record.id\n }\n };\n\n offer.deal_score = computeDealScore(offer, now);\n return offer;\n};\n\nconst resolveExpectedCurrencyForRegion = (region: string | undefined): string | null => {\n if (!region) return null;\n return REGION_CURRENCY_BY_REGION[region.trim().toLowerCase()] ?? null;\n};\n\nconst offerMatchesRegionCurrency = (\n offer: ShoppingOffer,\n expectedCurrency: string | null\n): boolean => {\n if (!expectedCurrency) {\n return true;\n }\n return offer.price.currency.trim().toUpperCase() === expectedCurrency;\n};\n\nexport interface ShoppingOfferFilterDiagnostic {\n providerId: string;\n candidateOffers: number;\n pricedOffers: number;\n regionMatchedOffers: number;\n zeroPriceExcluded: number;\n regionCurrencyExcluded: number;\n budgetExcluded: number;\n finalOffers: number;\n requestedRegion?: string;\n expectedCurrency?: string;\n allCandidateOffersDroppedByZeroPrice: boolean;\n allCandidateOffersDroppedByRegionCurrency: boolean;\n allCandidateOffersDroppedByBudget: boolean;\n}\n\nconst buildOfferFilterDiagnostic = (\n providerId: string,\n offers: ShoppingOffer[],\n compiled: CompiledShoppingWorkflow,\n expectedCurrency: string | null\n): ShoppingOfferFilterDiagnostic => {\n const pricedOffers = offers.filter((offer) => offer.price.amount > 0);\n const regionMatchedOffers = pricedOffers.filter((offer) => offerMatchesRegionCurrency(offer, expectedCurrency));\n const budget = typeof compiled.budget === \"number\" ? compiled.budget : null;\n const finalOffers = typeof budget === \"number\"\n ? regionMatchedOffers.filter((offer) => offer.price.amount <= budget)\n : regionMatchedOffers;\n\n return {\n providerId,\n candidateOffers: offers.length,\n pricedOffers: pricedOffers.length,\n regionMatchedOffers: regionMatchedOffers.length,\n zeroPriceExcluded: offers.length - pricedOffers.length,\n regionCurrencyExcluded: pricedOffers.length - regionMatchedOffers.length,\n budgetExcluded: regionMatchedOffers.length - finalOffers.length,\n finalOffers: finalOffers.length,\n ...(compiled.region ? { requestedRegion: compiled.region } : {}),\n ...(expectedCurrency ? { expectedCurrency } : {}),\n allCandidateOffersDroppedByZeroPrice: offers.length > 0 && pricedOffers.length === 0,\n allCandidateOffersDroppedByRegionCurrency: pricedOffers.length > 0 && regionMatchedOffers.length === 0,\n allCandidateOffersDroppedByBudget: regionMatchedOffers.length > 0 && finalOffers.length === 0\n };\n};\n\nconst filterShoppingOffers = (\n offers: ShoppingOffer[],\n compiled: CompiledShoppingWorkflow,\n expectedCurrency: string | null\n): ShoppingOffer[] => {\n return offers.filter((offer) => {\n if (offer.price.amount <= 0) return false;\n if (!offerMatchesRegionCurrency(offer, expectedCurrency)) return false;\n if (typeof compiled.budget !== \"number\") return true;\n return offer.price.amount <= compiled.budget;\n });\n};\n\nexport const dedupeOffers = (offers: ShoppingOffer[]): ShoppingOffer[] => {\n const deduped = new Map<string, ShoppingOffer>();\n for (const offer of offers) {\n const key = `${canonicalizeUrl(offer.url)}::${offer.title.toLowerCase()}`;\n const existing = deduped.get(key);\n if (!existing || offer.deal_score > existing.deal_score) {\n deduped.set(key, offer);\n }\n }\n return [...deduped.values()];\n};\n\nexport const rankOffers = (\n offers: ShoppingOffer[],\n sort: CompiledShoppingWorkflow[\"sort\"],\n query: string\n): ShoppingOffer[] => {\n const ordered = [...offers];\n switch (sort) {\n case \"lowest_price\":\n return ordered.sort((left, right) => {\n const leftTotal = left.price.amount + left.shipping.amount;\n const rightTotal = right.price.amount + right.shipping.amount;\n return leftTotal - rightTotal;\n });\n case \"highest_rating\":\n return ordered.sort((left, right) => right.rating - left.rating || right.reviews_count - left.reviews_count);\n case \"fastest_shipping\":\n return ordered.sort((left, right) => left.shipping.amount - right.shipping.amount || right.deal_score - left.deal_score);\n case \"best_deal\":\n default:\n return ordered.sort((left, right) => {\n const leftIntent = scoreShoppingOfferIntent(query, left);\n const rightIntent = scoreShoppingOfferIntent(query, right);\n if (leftIntent.directMatch !== rightIntent.directMatch) {\n return rightIntent.directMatch ? 1 : -1;\n }\n if (leftIntent.intentScore !== rightIntent.intentScore) {\n return rightIntent.intentScore - leftIntent.intentScore;\n }\n return right.deal_score - left.deal_score\n || (left.price.amount + left.shipping.amount) - (right.price.amount + right.shipping.amount);\n });\n }\n};\n\nexport const isLikelyOfferRecord = (record: NormalizedRecord): boolean => {\n const retrievalPath = typeof record.attributes.retrievalPath === \"string\"\n ? record.attributes.retrievalPath\n : \"\";\n if (retrievalPath === \"shopping:search:index\" || retrievalPath === \"shopping:search:link\") return false;\n if (retrievalPath.startsWith(\"shopping:search:\") && retrievalPath !== \"shopping:search:result-card\" && retrievalPath !== \"shopping:search:url\") {\n return false;\n }\n\n if (!record.url) return true;\n\n const canonicalUrl = canonicalizeUrl(record.url);\n if (!/^https?:/i.test(canonicalUrl)) return false;\n if (/\\.(?:png|jpe?g|gif|webp|svg|ico|css|js)(?:$|\\?)/i.test(canonicalUrl)) return false;\n const title = normalizePlainText(record.title);\n if (!title || LOOKS_LIKE_URL_RE.test(title) || title === canonicalUrl) return false;\n\n const profile = SHOPPING_PROVIDER_PROFILES.find((entry) => entry.id === record.provider);\n if (profile && profile.domains.length > 0 && retrievalPath.startsWith(\"shopping:search:\")) {\n try {\n const host = new URL(canonicalUrl).hostname.toLowerCase();\n const matchesProviderDomain = profile.domains.some((domain) => host === domain || host.endsWith(`.${domain}`));\n if (!matchesProviderDomain) return false;\n } catch {\n return false;\n }\n }\n return true;\n};\n\nexport const hasShoppingIssueHint = (records: NormalizedRecord[]): boolean => {\n return records.some((record) => readProviderIssueHintFromRecord(record) !== null);\n};\n\nconst withOfferFilterDiagnosticDetails = (\n details: Record<string, JsonValue>,\n offerFilterDiagnostic?: ShoppingOfferFilterDiagnostic\n): Record<string, JsonValue> => {\n if (!offerFilterDiagnostic) {\n return details;\n }\n\n return {\n ...details,\n candidateOffers: offerFilterDiagnostic.candidateOffers,\n pricedOffers: offerFilterDiagnostic.pricedOffers,\n regionMatchedOffers: offerFilterDiagnostic.regionMatchedOffers,\n zeroPriceExcluded: offerFilterDiagnostic.zeroPriceExcluded,\n regionCurrencyExcluded: offerFilterDiagnostic.regionCurrencyExcluded,\n budgetExcluded: offerFilterDiagnostic.budgetExcluded,\n finalOffers: offerFilterDiagnostic.finalOffers,\n ...(offerFilterDiagnostic.requestedRegion ? { requestedRegion: offerFilterDiagnostic.requestedRegion } : {}),\n ...(offerFilterDiagnostic.expectedCurrency ? { expectedCurrency: offerFilterDiagnostic.expectedCurrency } : {})\n };\n};\n\nconst inferShoppingNoOfferFailure = (\n providerId: string,\n query: string,\n records: NormalizedRecord[],\n offerFilterDiagnostic?: ShoppingOfferFilterDiagnostic\n): ProviderFailureEntry => {\n const issuePriority = (issue: NonNullable<ReturnType<typeof readProviderIssueHintFromRecord>>): number => (\n ({\n token_required: 3,\n auth_required: 3,\n challenge_detected: 2\n } as Partial<Record<typeof issue.reasonCode, number>>)[issue.reasonCode] ?? Number(issue.constraint?.kind === \"render_required\")\n );\n const primaryRecordIssue = records\n .flatMap((record) => {\n const hint = readProviderIssueHintFromRecord(record);\n if (!hint) return [];\n const title = normalizePlainText(record.title);\n return [{\n hint,\n ...(typeof record.url === \"string\" ? { url: canonicalizeUrl(record.url) } : {}),\n ...(title ? { title } : {}),\n ...(typeof record.attributes.providerShell === \"string\" && record.attributes.providerShell.trim().length > 0\n ? { providerShell: record.attributes.providerShell.trim() }\n : {})\n }];\n })\n .sort((left, right) => issuePriority(right.hint) - issuePriority(left.hint))[0] ?? null;\n\n if (primaryRecordIssue) {\n const reasonCode = primaryRecordIssue.hint.reasonCode;\n return {\n provider: providerId,\n source: \"shopping\",\n error: {\n code: reasonCode === \"token_required\" || reasonCode === \"auth_required\" ? \"auth\" : \"unavailable\",\n message: reasonCode === \"token_required\" || reasonCode === \"auth_required\"\n ? `Authentication required for provider results for query \"${query}\".`\n : reasonCode === \"challenge_detected\"\n ? `Detected anti-bot challenge while retrieving provider results for query \"${query}\".`\n : `Provider requires browser-rendered results for query \"${query}\".`,\n retryable: reasonCode === \"env_limited\",\n reasonCode,\n provider: providerId,\n source: \"shopping\",\n details: applyProviderIssueHint(withOfferFilterDiagnosticDetails({\n query,\n recordsCount: records.length,\n noOfferRecords: true,\n ...(primaryRecordIssue.url ? { url: primaryRecordIssue.url } : {}),\n ...(primaryRecordIssue.title ? { title: primaryRecordIssue.title } : {}),\n ...(primaryRecordIssue.providerShell ? { providerShell: primaryRecordIssue.providerShell } : {})\n }, offerFilterDiagnostic), primaryRecordIssue.hint)\n }\n };\n }\n\n if (offerFilterDiagnostic?.candidateOffers) {\n const filterDetails = withOfferFilterDiagnosticDetails({\n query,\n recordsCount: records.length,\n noOfferRecords: true,\n reasonCode: \"env_limited\"\n }, offerFilterDiagnostic);\n\n if (offerFilterDiagnostic.allCandidateOffersDroppedByRegionCurrency) {\n return {\n provider: providerId,\n source: \"shopping\",\n error: {\n code: \"unavailable\",\n message: `Provider returned priced offers for query \"${query}\", but all candidate offers were filtered by the ${offerFilterDiagnostic.expectedCurrency ?? \"requested\"} currency heuristic.`,\n retryable: false,\n reasonCode: \"env_limited\",\n provider: providerId,\n source: \"shopping\",\n details: {\n ...filterDetails,\n filterReason: \"region_currency\"\n }\n }\n };\n }\n\n if (offerFilterDiagnostic.allCandidateOffersDroppedByBudget) {\n return {\n provider: providerId,\n source: \"shopping\",\n error: {\n code: \"unavailable\",\n message: typeof offerFilterDiagnostic.expectedCurrency === \"string\" && typeof offerFilterDiagnostic.requestedRegion === \"string\"\n ? `Provider returned priced offers for query \"${query}\", but all candidate offers exceeded the requested budget after applying the ${offerFilterDiagnostic.expectedCurrency} currency heuristic for region ${offerFilterDiagnostic.requestedRegion}.`\n : `Provider returned priced offers for query \"${query}\", but all candidate offers exceeded the requested budget.`,\n retryable: false,\n reasonCode: \"env_limited\",\n provider: providerId,\n source: \"shopping\",\n details: {\n ...filterDetails,\n filterReason: \"budget\"\n }\n }\n };\n }\n\n if (offerFilterDiagnostic.allCandidateOffersDroppedByZeroPrice) {\n return {\n provider: providerId,\n source: \"shopping\",\n error: {\n code: \"unavailable\",\n message: `Provider returned candidate offers for query \"${query}\", but none had a trustworthy non-zero price.`,\n retryable: false,\n reasonCode: \"env_limited\",\n provider: providerId,\n source: \"shopping\",\n details: {\n ...filterDetails,\n filterReason: \"zero_price\"\n }\n }\n };\n }\n }\n\n const fallbackFailure: ProviderFailureEntry = {\n provider: providerId,\n source: \"shopping\",\n error: {\n code: \"unavailable\",\n message: `Provider returned no usable shopping offers for query \"${query}\".`,\n retryable: true,\n reasonCode: \"env_limited\",\n provider: providerId,\n source: \"shopping\",\n details: withOfferFilterDiagnosticDetails({\n query,\n recordsCount: records.length,\n noOfferRecords: true,\n reasonCode: \"env_limited\"\n }, offerFilterDiagnostic)\n }\n };\n\n for (const record of records) {\n const url = typeof record.url === \"string\" ? canonicalizeUrl(record.url) : undefined;\n const title = normalizePlainText(record.title) || undefined;\n const message = toSnippet(normalizePlainText(record.content), 800) || undefined;\n const blocker = classifyBlockerSignal({\n source: \"runtime_fetch\",\n ...(url ? { url, finalUrl: url } : {}),\n ...(title ? { title } : {}),\n ...(message ? { message } : {}),\n providerErrorCode: \"unavailable\",\n retryable: true\n });\n if (!blocker || blocker.type === \"unknown\") continue;\n\n const reasonCode = blocker.reasonCode ?? \"env_limited\";\n return {\n provider: providerId,\n source: \"shopping\",\n error: {\n code: \"unavailable\",\n message: `Provider returned no usable shopping offers for query \"${query}\".`,\n retryable: blocker.retryable,\n reasonCode,\n provider: providerId,\n source: \"shopping\",\n details: withOfferFilterDiagnosticDetails({\n query,\n recordsCount: records.length,\n noOfferRecords: true,\n reasonCode,\n blockerType: blocker.type,\n blockerConfidence: blocker.confidence,\n ...(url ? { url } : {}),\n ...(title ? { title } : {})\n }, offerFilterDiagnostic)\n }\n };\n }\n\n return fallbackFailure;\n};\n\nconst createEmptyShoppingResultFailure = (\n providerId: string,\n query: string,\n records: NormalizedRecord[],\n offerFilterDiagnostic?: ShoppingOfferFilterDiagnostic\n): ProviderFailureEntry => inferShoppingNoOfferFailure(providerId, query, records, offerFilterDiagnostic);\n\nexport interface ShoppingWorkflowPostprocessResult {\n records: NormalizedRecord[];\n failures: ProviderFailureEntry[];\n offers: ShoppingOffer[];\n zeroPriceExcluded: number;\n budgetExcluded: number;\n regionCurrencyExcluded: number;\n offerFilterDiagnostics: ShoppingOfferFilterDiagnostic[];\n}\n\nexport const postprocessShoppingWorkflow = (\n compiled: CompiledShoppingWorkflow,\n runs: ShoppingWorkflowRun[]\n): ShoppingWorkflowPostprocessResult => {\n const runsWithOfferRecords = runs.map((run) => ({\n ...run,\n offerRecords: run.result.records.filter((record) => isLikelyOfferRecord(record))\n }));\n const expectedCurrency = resolveExpectedCurrencyForRegion(compiled.region);\n const runsWithExtractedOffers = runsWithOfferRecords.map((run) => ({\n ...run,\n extractedOffers: run.offerRecords.map((record) => extractShoppingOffer(record, compiled.now))\n }));\n const runsWithOfferDiagnostics = runsWithExtractedOffers.map((run) => {\n const offerFilterDiagnostic = buildOfferFilterDiagnostic(\n run.providerId,\n run.extractedOffers,\n compiled,\n expectedCurrency\n );\n return {\n ...run,\n offerFilterDiagnostic,\n filteredOffers: filterShoppingOffers(run.extractedOffers, compiled, expectedCurrency)\n };\n });\n const zeroPriceExcluded = runsWithOfferDiagnostics.reduce((sum, run) => sum + run.offerFilterDiagnostic.zeroPriceExcluded, 0);\n const budgetExcluded = runsWithOfferDiagnostics.reduce((sum, run) => sum + run.offerFilterDiagnostic.budgetExcluded, 0);\n const regionCurrencyExcluded = runsWithOfferDiagnostics.reduce((sum, run) => sum + run.offerFilterDiagnostic.regionCurrencyExcluded, 0);\n\n const offers = rankOffers(\n dedupeOffers(runsWithOfferDiagnostics.flatMap((run) => run.filteredOffers)),\n compiled.sort,\n compiled.query\n );\n\n const failures = runsWithOfferDiagnostics.flatMap((run) => {\n if (run.result.failures.length > 0) {\n return run.result.failures;\n }\n if (run.offerFilterDiagnostic.finalOffers > 0) {\n return [];\n }\n return [createEmptyShoppingResultFailure(\n run.providerId,\n compiled.query,\n run.result.records,\n run.offerFilterDiagnostic\n )];\n });\n\n return {\n records: runsWithOfferDiagnostics.flatMap((run) => run.result.records),\n failures,\n offers,\n zeroPriceExcluded,\n budgetExcluded,\n regionCurrencyExcluded,\n offerFilterDiagnostics: runsWithOfferDiagnostics.map((run) => run.offerFilterDiagnostic)\n };\n};\n","import {\n SHOPPING_PROVIDER_IDS,\n SHOPPING_PROVIDER_PROFILES,\n getShoppingRegionSupportDiagnostics,\n validateShoppingLegalReviewChecklist,\n type ShoppingRegionSupportDiagnostic\n} from \"./shopping\";\nimport type { ProviderAggregateResult, ProviderRunOptions } from \"./types\";\nimport type { ProviderExecutor, ShoppingRunInput } from \"./workflows\";\n\nconst DEFAULT_SHOPPING_PROVIDER_IDS = SHOPPING_PROVIDER_PROFILES\n .filter((profile) => profile.tier === \"tier1\")\n .map((profile) => profile.id);\n\nexport interface CompiledShoppingWorkflow {\n query: string;\n now: Date;\n providerIds: string[];\n hasExplicitProviderSelection: boolean;\n autoExcludedProviders: string[];\n effectiveProviderIds: string[];\n regionDiagnostics: ShoppingRegionSupportDiagnostic[];\n budget?: number;\n region?: string;\n sort: NonNullable<ShoppingRunInput[\"sort\"]>;\n}\n\nexport interface ShoppingWorkflowRun {\n providerId: string;\n result: ProviderAggregateResult;\n}\n\nexport interface CompileShoppingWorkflowOptions {\n now?: Date;\n getDegradedProviders?: (providerIds: string[]) => ReadonlySet<string>;\n}\n\nexport interface ExecuteShoppingSearchesOptions {\n buildSearchOptions: (providerId: string) => ProviderRunOptions;\n observeResult?: (result: ProviderAggregateResult) => void;\n limit?: number;\n}\n\nexport const resolveShoppingProviders = (providers?: string[]): string[] => {\n if (!providers || providers.length === 0) {\n return DEFAULT_SHOPPING_PROVIDER_IDS.length > 0\n ? [...DEFAULT_SHOPPING_PROVIDER_IDS]\n : [...SHOPPING_PROVIDER_IDS];\n }\n\n const normalized = providers\n .map((provider) => provider.trim().toLowerCase())\n .filter(Boolean)\n .map((provider) => provider.startsWith(\"shopping/\") ? provider : `shopping/${provider}`);\n\n const deduped = [...new Set(normalized)].filter((provider) => SHOPPING_PROVIDER_IDS.includes(provider as (typeof SHOPPING_PROVIDER_IDS)[number]));\n if (deduped.length === 0) {\n throw new Error(\"No valid shopping providers were requested\");\n }\n return deduped;\n};\n\nexport const enforceShoppingLegalReviewGate = (providerIds: string[], now: Date): void => {\n const blocked = providerIds\n .map((providerId) => ({ providerId, validation: validateShoppingLegalReviewChecklist(providerId, now) }))\n .filter((entry) => !entry.validation.valid);\n\n if (blocked.length === 0) return;\n const summary = blocked\n .map((entry) => `${entry.providerId}:${entry.validation.reasonCode ?? \"missing_checklist\"}`)\n .join(\", \");\n throw new Error(`Provider legal review checklist invalid or expired: ${summary}`);\n};\n\nexport const compileShoppingWorkflow = (\n input: ShoppingRunInput,\n options: CompileShoppingWorkflowOptions = {}\n): CompiledShoppingWorkflow => {\n const query = input.query?.trim();\n if (!query) {\n throw new Error(\"query is required\");\n }\n\n const providerIds = resolveShoppingProviders(input.providers);\n const hasExplicitProviderSelection = Boolean(input.providers && input.providers.length > 0);\n const degradedProviders = options.getDegradedProviders?.(providerIds) ?? new Set<string>();\n const autoExcludedProviders = hasExplicitProviderSelection\n ? []\n : providerIds.filter((providerId) => degradedProviders.has(providerId));\n const effectiveProviderIds = hasExplicitProviderSelection\n ? providerIds\n : providerIds.filter((providerId) => !degradedProviders.has(providerId));\n const now = options.now ?? new Date();\n if (effectiveProviderIds.length === 0) {\n throw new Error(\"All default shopping providers are temporarily excluded due to degraded anti-bot/rate-limit state\");\n }\n\n enforceShoppingLegalReviewGate(effectiveProviderIds, now);\n\n return {\n query,\n now,\n providerIds,\n hasExplicitProviderSelection,\n autoExcludedProviders,\n effectiveProviderIds,\n regionDiagnostics: input.region\n ? getShoppingRegionSupportDiagnostics(effectiveProviderIds, input.region)\n : [],\n ...(typeof input.budget === \"number\" ? { budget: input.budget } : {}),\n ...(input.region ? { region: input.region } : {}),\n sort: input.sort ?? \"best_deal\"\n };\n};\n\nexport const executeShoppingSearches = async (\n runtime: ProviderExecutor,\n compiled: CompiledShoppingWorkflow,\n options: ExecuteShoppingSearchesOptions\n): Promise<ShoppingWorkflowRun[]> => {\n return Promise.all(compiled.effectiveProviderIds.map(async (providerId) => {\n const result = await runtime.search({\n query: compiled.query,\n limit: options.limit ?? 8,\n filters: {\n ...(typeof compiled.budget === \"number\" ? { budget: compiled.budget } : {}),\n ...(compiled.region ? { region: compiled.region } : {})\n }\n }, options.buildSearchOptions(providerId));\n options.observeResult?.(result);\n return {\n providerId,\n result\n };\n }));\n};\n","import { createHash } from \"crypto\";\nimport { canonicalizeUrl } from \"./web/crawler\";\nimport { hasShoppingIssueHint, isLikelyOfferRecord } from \"./shopping-postprocess\";\nimport { compileShoppingWorkflow, type CompiledShoppingWorkflow } from \"./shopping-workflow\";\nimport { getShoppingProviderProfile } from \"./shopping\";\nimport type { ProviderAggregateResult, JsonValue, NormalizedRecord, ProviderFailureEntry, ProviderSource } from \"./types\";\nimport type { ShoppingRunInput } from \"./workflows\";\nimport type { WorkflowCheckpoint, WorkflowPlan, WorkflowPlanStep, WorkflowResumeEnvelope } from \"./workflow-contracts\";\n\nconst DEFAULT_SHOPPING_SEARCH_LIMIT = 8;\nconst SHOPPING_FETCH_RECOVERY_LIMIT = 2;\nconst SEARCH_INDEX_RETRIEVAL_PATHS = new Set([\"shopping:search:index\", \"shopping:search:link\"]);\n\nexport type ShoppingWorkflowStepKind = \"search\" | \"fetch\";\n\nexport type ShoppingSearchStepInput = {\n providerId: string;\n query: string;\n limit: number;\n filters?: Record<string, JsonValue>;\n};\n\nexport type ShoppingFetchStepInput = {\n providerId: string;\n url: string;\n};\n\nexport type ShoppingSearchWorkflowStep = WorkflowPlanStep & {\n kind: \"search\";\n input: ShoppingSearchStepInput;\n};\n\nexport type ShoppingFetchWorkflowStep = WorkflowPlanStep & {\n kind: \"fetch\";\n input: ShoppingFetchStepInput;\n};\n\nexport type ShoppingWorkflowExecutionStep = (\n | ShoppingSearchWorkflowStep\n | ShoppingFetchWorkflowStep\n) & {\n kind: ShoppingWorkflowStepKind;\n};\n\nexport type ShoppingCheckpointStepResult = ProviderAggregateResult;\n\nexport type ShoppingWorkflowCheckpointState = {\n completed_step_ids: string[];\n step_results_by_id: Record<string, ShoppingCheckpointStepResult>;\n};\n\nexport type CompiledShoppingExecutionPlan = {\n input: ShoppingRunInput;\n compiled: CompiledShoppingWorkflow;\n plan: WorkflowPlan & {\n steps: ShoppingWorkflowExecutionStep[];\n };\n checkpointState: ShoppingWorkflowCheckpointState;\n};\n\nconst isJsonRecord = (value: unknown): value is Record<string, JsonValue> => (\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n);\n\nconst isFiniteNumber = (value: unknown): value is number => (\n typeof value === \"number\" && Number.isFinite(value)\n);\n\nconst isProviderSource = (value: unknown): value is ProviderSource => (\n value === \"web\" || value === \"community\" || value === \"social\" || value === \"shopping\"\n);\n\nconst isTraceContext = (value: unknown): value is ProviderAggregateResult[\"trace\"] => (\n isJsonRecord(value)\n && typeof value.requestId === \"string\"\n && typeof value.ts === \"string\"\n && (value.sessionId === undefined || typeof value.sessionId === \"string\")\n && (value.targetId === undefined || typeof value.targetId === \"string\")\n && (value.provider === undefined || typeof value.provider === \"string\")\n);\n\nconst isProviderError = (value: unknown): boolean => (\n isJsonRecord(value)\n && typeof value.code === \"string\"\n && typeof value.message === \"string\"\n && typeof value.retryable === \"boolean\"\n && (value.reasonCode === undefined || typeof value.reasonCode === \"string\")\n && (value.provider === undefined || typeof value.provider === \"string\")\n && (value.source === undefined || isProviderSource(value.source))\n && (value.details === undefined || isJsonRecord(value.details))\n);\n\nconst isNormalizedRecord = (value: unknown): value is NormalizedRecord => (\n isJsonRecord(value)\n && typeof value.id === \"string\"\n && isProviderSource(value.source)\n && typeof value.provider === \"string\"\n && (value.url === undefined || typeof value.url === \"string\")\n && (value.title === undefined || typeof value.title === \"string\")\n && (value.content === undefined || typeof value.content === \"string\")\n && typeof value.timestamp === \"string\"\n && isFiniteNumber(value.confidence)\n && isJsonRecord(value.attributes)\n);\n\nconst isProviderFailureEntry = (value: unknown): value is ProviderFailureEntry => (\n isJsonRecord(value)\n && typeof value.provider === \"string\"\n && isProviderSource(value.source)\n && isProviderError(value.error)\n);\n\nconst isProviderAggregateResult = (value: unknown): value is ProviderAggregateResult => (\n isJsonRecord(value)\n && typeof value.ok === \"boolean\"\n && Array.isArray(value.records)\n && value.records.every((entry) => isNormalizedRecord(entry))\n && isTraceContext(value.trace)\n && typeof value.partial === \"boolean\"\n && Array.isArray(value.failures)\n && value.failures.every((entry) => isProviderFailureEntry(entry))\n && isJsonRecord(value.metrics)\n && isFiniteNumber(value.metrics.attempted)\n && isFiniteNumber(value.metrics.succeeded)\n && isFiniteNumber(value.metrics.failed)\n && isFiniteNumber(value.metrics.retries)\n && isFiniteNumber(value.metrics.latencyMs)\n && typeof value.sourceSelection === \"string\"\n && Array.isArray(value.providerOrder)\n && value.providerOrder.every((entry) => typeof entry === \"string\")\n && (value.meta === undefined || isJsonRecord(value.meta))\n && (value.diagnostics === undefined || isJsonRecord(value.diagnostics))\n && (value.error === undefined || isProviderError(value.error))\n);\n\nconst emptyCheckpointState = (): ShoppingWorkflowCheckpointState => ({\n completed_step_ids: [],\n step_results_by_id: {}\n});\n\nexport const createShoppingSearchStepId = (providerId: string): string => `search:${providerId}`;\n\nexport const createShoppingFetchStepId = (providerId: string, url: string): string => (\n `fetch:${providerId}:${createHash(\"sha1\").update(canonicalizeUrl(url)).digest(\"hex\").slice(0, 16)}`\n);\n\nexport const serializeShoppingCheckpointState = (\n state: ShoppingWorkflowCheckpointState\n): Record<string, JsonValue> => ({\n completed_step_ids: [...state.completed_step_ids],\n step_results_by_id: state.step_results_by_id as unknown as Record<string, JsonValue>\n});\n\nexport const readShoppingCheckpointState = (\n checkpoint?: WorkflowCheckpoint | null\n): ShoppingWorkflowCheckpointState => {\n const state = checkpoint?.state;\n if (state === undefined || state === null) {\n return emptyCheckpointState();\n }\n if (!isJsonRecord(state)) {\n throw new Error(\"Shopping workflow checkpoint state must be a record.\");\n }\n\n const completedStepIds = state.completed_step_ids;\n if (!Array.isArray(completedStepIds) || !completedStepIds.every((entry) => typeof entry === \"string\")) {\n throw new Error(\"Shopping workflow checkpoint state is missing valid completed_step_ids.\");\n }\n\n const rawResults = state.step_results_by_id;\n if (!isJsonRecord(rawResults)) {\n throw new Error(\"Shopping workflow checkpoint state is missing valid step_results_by_id.\");\n }\n\n const stepResultsById: Record<string, ShoppingCheckpointStepResult> = {};\n for (const [stepId, result] of Object.entries(rawResults)) {\n if (!isProviderAggregateResult(result)) {\n throw new Error(`Shopping workflow checkpoint state contains an invalid result for ${stepId}.`);\n }\n stepResultsById[stepId] = result;\n }\n\n return {\n completed_step_ids: [...completedStepIds],\n step_results_by_id: stepResultsById\n };\n};\n\nconst buildSearchFilters = (compiled: CompiledShoppingWorkflow): Record<string, JsonValue> | undefined => {\n const filters: Record<string, JsonValue> = {};\n if (typeof compiled.budget === \"number\") {\n filters.budget = compiled.budget;\n }\n if (compiled.region) {\n filters.region = compiled.region;\n }\n return Object.keys(filters).length > 0 ? filters : undefined;\n};\n\nconst hasProviderOwnedDomain = (providerId: string, url: string): boolean => {\n const profile = getShoppingProviderProfile(providerId);\n if (!profile || profile.domains.length === 0) {\n return false;\n }\n try {\n const hostname = new URL(url).hostname.toLowerCase();\n return profile.domains.some((domain) => hostname === domain || hostname.endsWith(`.${domain}`));\n } catch {\n return false;\n }\n};\n\nconst collectRecordLinkCandidates = (record: NormalizedRecord): string[] => {\n const links = Array.isArray(record.attributes.links)\n ? record.attributes.links.filter((entry): entry is string => typeof entry === \"string\")\n : [];\n return links.map((entry) => canonicalizeUrl(entry));\n};\n\nconst collectProviderCandidateUrls = (\n providerId: string,\n records: NormalizedRecord[]\n): string[] => {\n const seen = new Set<string>();\n const candidates: string[] = [];\n\n for (const record of records) {\n const retrievalPath = typeof record.attributes.retrievalPath === \"string\"\n ? record.attributes.retrievalPath\n : \"\";\n const maybeRecordUrl = typeof record.url === \"string\" && !SEARCH_INDEX_RETRIEVAL_PATHS.has(retrievalPath)\n ? [canonicalizeUrl(record.url)]\n : [];\n const maybeLinkedUrls = collectRecordLinkCandidates(record);\n\n for (const candidate of [...maybeRecordUrl, ...maybeLinkedUrls]) {\n if (!/^https?:\\/\\//i.test(candidate)) {\n continue;\n }\n if (!hasProviderOwnedDomain(providerId, candidate)) {\n continue;\n }\n if (seen.has(candidate)) {\n continue;\n }\n seen.add(candidate);\n candidates.push(candidate);\n }\n }\n\n return candidates;\n};\n\nexport const deriveShoppingFetchSteps = (\n compiled: CompiledShoppingWorkflow,\n checkpointState: ShoppingWorkflowCheckpointState\n): ShoppingWorkflowExecutionStep[] => {\n return compiled.effectiveProviderIds.flatMap((providerId) => {\n if (!getShoppingProviderProfile(providerId)?.domains.length) {\n return [];\n }\n\n const searchStepId = createShoppingSearchStepId(providerId);\n if (!checkpointState.completed_step_ids.includes(searchStepId)) {\n return [];\n }\n\n const searchResult = checkpointState.step_results_by_id[searchStepId];\n if (!searchResult || searchResult.failures.length > 0) {\n return [];\n }\n if (searchResult.records.some((record) => isLikelyOfferRecord(record))) {\n return [];\n }\n if (hasShoppingIssueHint(searchResult.records)) {\n return [];\n }\n\n const candidateUrls = collectProviderCandidateUrls(providerId, searchResult.records)\n .slice(0, SHOPPING_FETCH_RECOVERY_LIMIT);\n if (candidateUrls.length === 0) {\n return [];\n }\n\n return candidateUrls.map((candidateUrl) => ({\n id: createShoppingFetchStepId(providerId, candidateUrl),\n kind: \"fetch\",\n policy: {\n sources: [\"shopping\"],\n providers: [providerId]\n },\n input: {\n providerId,\n url: candidateUrl\n }\n }));\n });\n};\n\nexport const compileShoppingExecutionPlan = (args: {\n input: ShoppingRunInput;\n envelope?: WorkflowResumeEnvelope | null;\n now?: Date;\n getDegradedProviders?: (providerIds: string[]) => ReadonlySet<string>;\n}): CompiledShoppingExecutionPlan => {\n const compiled = compileShoppingWorkflow(args.input, {\n now: args.now,\n getDegradedProviders: args.getDegradedProviders\n });\n const checkpointState = readShoppingCheckpointState(args.envelope?.checkpoint ?? null);\n const filters = buildSearchFilters(compiled);\n const searchSteps: ShoppingWorkflowExecutionStep[] = compiled.effectiveProviderIds.map((providerId) => ({\n id: createShoppingSearchStepId(providerId),\n kind: \"search\",\n budget: {\n maxResults: DEFAULT_SHOPPING_SEARCH_LIMIT\n },\n policy: {\n sources: [\"shopping\"],\n providers: [providerId]\n },\n input: {\n providerId,\n query: compiled.query,\n limit: DEFAULT_SHOPPING_SEARCH_LIMIT,\n ...(filters ? { filters } : {})\n }\n }));\n\n return {\n input: args.input,\n compiled,\n checkpointState,\n plan: {\n kind: \"shopping\",\n steps: searchSteps\n }\n };\n};\n","import {\n buildWorkflowResumeEnvelope,\n type WorkflowCheckpoint,\n type WorkflowResumeEnvelope,\n type WorkflowTraceEntry\n} from \"./workflow-contracts\";\nimport {\n createShoppingSearchStepId,\n deriveShoppingFetchSteps,\n serializeShoppingCheckpointState,\n type CompiledShoppingExecutionPlan,\n type ShoppingFetchWorkflowStep,\n type ShoppingWorkflowCheckpointState,\n type ShoppingWorkflowExecutionStep,\n type ShoppingSearchWorkflowStep\n} from \"./shopping-compiler\";\nimport type { JsonValue, ProviderAggregateResult, ProviderRunOptions } from \"./types\";\nimport type { ShoppingWorkflowRun } from \"./shopping-workflow\";\nimport type { ProviderExecutor } from \"./workflows\";\n\nexport type ShoppingWorkflowExecutionResult = {\n runs: ShoppingWorkflowRun[];\n checkpoint: WorkflowCheckpoint;\n trace: WorkflowTraceEntry[];\n};\n\nexport type ShoppingWorkflowProviderAccumulator = Record<string, ProviderAggregateResult>;\n\nexport type ExecuteShoppingWorkflowPlanOptions = {\n trace?: WorkflowTraceEntry[];\n observeResult?: (result: ProviderAggregateResult) => void;\n buildStepOptions: (\n step: ShoppingWorkflowExecutionStep,\n envelope: WorkflowResumeEnvelope\n ) => ProviderRunOptions;\n};\n\nconst appendTrace = (\n trace: WorkflowTraceEntry[],\n stage: WorkflowTraceEntry[\"stage\"],\n event: string,\n details: Record<string, JsonValue>\n): WorkflowTraceEntry[] => [\n ...trace,\n {\n at: new Date().toISOString(),\n stage,\n event,\n details\n }\n];\n\nconst getCheckpointedResult = (\n checkpointState: ShoppingWorkflowCheckpointState,\n stepId: string\n): ProviderAggregateResult => {\n const result = checkpointState.step_results_by_id[stepId];\n if (!result) {\n throw new Error(`Shopping workflow checkpoint is missing result for completed step ${stepId}.`);\n }\n return result;\n};\n\nconst buildCheckpoint = (\n checkpointState: ShoppingWorkflowCheckpointState,\n step: ShoppingWorkflowExecutionStep,\n stepIndex: number\n): WorkflowCheckpoint => ({\n stage: \"execute\",\n stepId: step.id,\n stepIndex,\n state: serializeShoppingCheckpointState(checkpointState),\n updatedAt: new Date().toISOString()\n});\n\nconst markStepCompleted = (\n checkpointState: ShoppingWorkflowCheckpointState,\n stepId: string,\n result: ProviderAggregateResult\n): ShoppingWorkflowCheckpointState => ({\n completed_step_ids: [...new Set([...checkpointState.completed_step_ids, stepId])],\n step_results_by_id: {\n ...checkpointState.step_results_by_id,\n [stepId]: result\n }\n});\n\nconst mergeProviderResult = (\n base: ProviderAggregateResult,\n fetchResult: ProviderAggregateResult\n): ProviderAggregateResult => {\n return {\n ...base,\n ok: base.ok && fetchResult.ok,\n partial: base.partial || fetchResult.partial,\n records: [...base.records, ...fetchResult.records],\n failures: [...base.failures, ...fetchResult.failures],\n providerOrder: [...new Set([...base.providerOrder, ...fetchResult.providerOrder])],\n metrics: {\n attempted: base.metrics.attempted + fetchResult.metrics.attempted,\n succeeded: base.metrics.succeeded + fetchResult.metrics.succeeded,\n failed: base.metrics.failed + fetchResult.metrics.failed,\n retries: base.metrics.retries + fetchResult.metrics.retries,\n latencyMs: base.metrics.latencyMs + fetchResult.metrics.latencyMs\n },\n ...(fetchResult.error ? { error: fetchResult.error } : {})\n };\n};\n\nconst buildProviderRuns = (\n plan: CompiledShoppingExecutionPlan,\n checkpointState: ShoppingWorkflowCheckpointState,\n fetchSteps: ShoppingWorkflowExecutionStep[]\n): ShoppingWorkflowRun[] => {\n const fetchStepsByProviderId = new Map<string, ShoppingWorkflowExecutionStep[]>();\n for (const step of fetchSteps) {\n const existing = fetchStepsByProviderId.get(step.input.providerId) ?? [];\n existing.push(step);\n fetchStepsByProviderId.set(step.input.providerId, existing);\n }\n\n return plan.compiled.effectiveProviderIds.flatMap((providerId) => {\n const searchStepId = createShoppingSearchStepId(providerId);\n const searchResult = checkpointState.step_results_by_id[searchStepId];\n if (!searchResult) {\n return [];\n }\n\n const fetchResults = (fetchStepsByProviderId.get(providerId) ?? [])\n .map((step) => checkpointState.step_results_by_id[step.id])\n .filter((result): result is ProviderAggregateResult => result !== undefined);\n const result = fetchResults.reduce(mergeProviderResult, searchResult);\n\n return [{\n providerId,\n result\n }];\n });\n};\n\nconst executeSearchStep = async (\n runtime: ProviderExecutor,\n step: ShoppingSearchWorkflowStep,\n options: ExecuteShoppingWorkflowPlanOptions,\n envelope: WorkflowResumeEnvelope\n): Promise<ProviderAggregateResult> => {\n const input = step.input;\n return runtime.search({\n query: input.query,\n limit: input.limit,\n ...(input.filters ? { filters: input.filters } : {})\n }, options.buildStepOptions(step, envelope));\n};\n\nconst executeFetchStep = async (\n runtime: ProviderExecutor,\n step: ShoppingFetchWorkflowStep,\n options: ExecuteShoppingWorkflowPlanOptions,\n envelope: WorkflowResumeEnvelope\n): Promise<ProviderAggregateResult> => {\n return runtime.fetch({\n url: step.input.url\n }, options.buildStepOptions(step, envelope));\n};\n\nexport const executeShoppingWorkflowPlan = async (\n runtime: ProviderExecutor,\n plan: CompiledShoppingExecutionPlan,\n options: ExecuteShoppingWorkflowPlanOptions\n): Promise<ShoppingWorkflowExecutionResult> => {\n let checkpointState: ShoppingWorkflowCheckpointState = {\n completed_step_ids: [...plan.checkpointState.completed_step_ids],\n step_results_by_id: { ...plan.checkpointState.step_results_by_id }\n };\n let trace = [...(options.trace ?? [])];\n let stepIndex = 0;\n let lastCheckpoint = buildCheckpoint(\n checkpointState,\n plan.plan.steps[0] ?? {\n id: \"shopping:execute\",\n kind: \"search\",\n input: {\n providerId: plan.compiled.effectiveProviderIds[0] ?? \"shopping/unknown\",\n query: plan.compiled.query,\n limit: 0\n }\n },\n 0\n );\n\n const runSteps = async (steps: ShoppingWorkflowExecutionStep[]): Promise<void> => {\n for (const step of steps) {\n const currentStepIndex = stepIndex;\n stepIndex += 1;\n\n if (checkpointState.completed_step_ids.includes(step.id)) {\n getCheckpointedResult(checkpointState, step.id);\n lastCheckpoint = buildCheckpoint(checkpointState, step, currentStepIndex);\n trace = appendTrace(trace, \"resume\", \"step_reused\", {\n stepId: step.id,\n stepKind: step.kind,\n providerId: step.input.providerId\n });\n continue;\n }\n\n trace = appendTrace(trace, \"execute\", \"step_started\", {\n stepId: step.id,\n stepKind: step.kind,\n providerId: step.input.providerId\n });\n const checkpoint = buildCheckpoint(checkpointState, step, currentStepIndex);\n const preSuspendTrace = appendTrace(trace, \"execute\", \"pre_suspend_checkpoint\", {\n stepId: step.id,\n stepKind: step.kind,\n providerId: step.input.providerId,\n completedSteps: checkpointState.completed_step_ids.length\n });\n const envelope = buildWorkflowResumeEnvelope(\n \"shopping\",\n plan.input as unknown as JsonValue,\n {\n checkpoint,\n trace: preSuspendTrace\n }\n );\n const result = step.kind === \"search\"\n ? await executeSearchStep(runtime, step, options, envelope)\n : await executeFetchStep(runtime, step, options, envelope);\n checkpointState = markStepCompleted(checkpointState, step.id, result);\n options.observeResult?.(result);\n trace = appendTrace(preSuspendTrace, \"execute\", \"step_completed\", {\n stepId: step.id,\n stepKind: step.kind,\n providerId: step.input.providerId,\n records: result.records.length,\n failures: result.failures.length\n });\n lastCheckpoint = buildCheckpoint(checkpointState, step, currentStepIndex);\n }\n };\n\n await runSteps(plan.plan.steps);\n\n const fetchSteps = deriveShoppingFetchSteps(plan.compiled, checkpointState);\n if (fetchSteps.length > 0) {\n trace = appendTrace(trace, \"execute\", \"tactical_decision\", {\n reason: \"selective_fetch_recovery\",\n fetchSteps: fetchSteps.length,\n providers: fetchSteps.map((step) => step.input.providerId)\n });\n }\n await runSteps(fetchSteps);\n\n return {\n runs: buildProviderRuns(plan, checkpointState, fetchSteps),\n checkpoint: lastCheckpoint,\n trace\n };\n};\n","import type {\n JsonValue,\n NormalizedRecord,\n ProviderAggregateResult,\n ProviderFailureEntry,\n ProviderSource\n} from \"./types\";\nimport type { ProductVideoRunInput } from \"./workflows\";\nimport type { WorkflowCheckpoint, WorkflowPlan, WorkflowPlanStep, WorkflowResumeEnvelope } from \"./workflow-contracts\";\n\nexport const PRODUCT_VIDEO_STEP_IDS = {\n normalizeInput: \"product_video:normalize_input\",\n resolveProductUrl: \"product_video:resolve_product_url\",\n fetchProductDetail: \"product_video:fetch_product_detail\",\n extractProductData: \"product_video:extract_product_data\",\n assembleArtifacts: \"product_video:assemble_artifacts\"\n} as const;\n\nexport type ProductVideoWorkflowStepKind =\n | \"normalize_input\"\n | \"resolve_product_url\"\n | \"fetch_product_detail\"\n | \"extract_product_data\"\n | \"assemble_artifacts\";\n\nexport type ProductVideoNormalizeStep = WorkflowPlanStep & {\n id: typeof PRODUCT_VIDEO_STEP_IDS.normalizeInput;\n kind: \"normalize_input\";\n input: {\n has_product_url: boolean;\n has_product_name: boolean;\n has_provider_hint: boolean;\n };\n};\n\nexport type ProductVideoResolveUrlStep = WorkflowPlanStep & {\n id: typeof PRODUCT_VIDEO_STEP_IDS.resolveProductUrl;\n kind: \"resolve_product_url\";\n input: {\n product_name: string;\n provider_hint?: string;\n };\n};\n\nexport type ProductVideoFetchDetailStep = WorkflowPlanStep & {\n id: typeof PRODUCT_VIDEO_STEP_IDS.fetchProductDetail;\n kind: \"fetch_product_detail\";\n input: {\n product_url?: string;\n provider_hint?: string;\n timeout_ms?: number;\n };\n};\n\nexport type ProductVideoExtractStep = WorkflowPlanStep & {\n id: typeof PRODUCT_VIDEO_STEP_IDS.extractProductData;\n kind: \"extract_product_data\";\n input: Record<string, JsonValue>;\n};\n\nexport type ProductVideoAssembleArtifactsStep = WorkflowPlanStep & {\n id: typeof PRODUCT_VIDEO_STEP_IDS.assembleArtifacts;\n kind: \"assemble_artifacts\";\n input: {\n include_screenshots: boolean;\n include_all_images: boolean;\n include_copy: boolean;\n };\n};\n\nexport type ProductVideoWorkflowExecutionStep = (\n | ProductVideoNormalizeStep\n | ProductVideoResolveUrlStep\n | ProductVideoFetchDetailStep\n | ProductVideoExtractStep\n | ProductVideoAssembleArtifactsStep\n) & {\n kind: ProductVideoWorkflowStepKind;\n};\n\nexport type ProductVideoWorkflowCheckpointState = {\n completed_step_ids: string[];\n resolved_product_url?: string;\n resolved_provider_hint?: string;\n detail_result?: ProviderAggregateResult;\n};\n\ntype NormalizedProductVideoRunInput = ProductVideoRunInput & {\n include_screenshots: boolean;\n include_all_images: boolean;\n include_copy: boolean;\n};\n\nexport type CompiledProductVideoExecutionPlan = {\n input: NormalizedProductVideoRunInput;\n compiled: {\n productUrl?: string;\n productName?: string;\n providerHint?: string;\n includeScreenshots: boolean;\n includeAllImages: boolean;\n includeCopy: boolean;\n outputDir?: string;\n ttlHours?: number;\n timeoutMs?: number;\n resolutionRequired: boolean;\n };\n plan: WorkflowPlan & {\n steps: ProductVideoWorkflowExecutionStep[];\n };\n checkpointState: ProductVideoWorkflowCheckpointState;\n};\n\nconst isJsonRecord = (value: unknown): value is Record<string, JsonValue> => (\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n);\n\nconst isFiniteNumber = (value: unknown): value is number => (\n typeof value === \"number\" && Number.isFinite(value)\n);\n\nconst isProviderSource = (value: unknown): value is ProviderSource => (\n value === \"web\" || value === \"community\" || value === \"social\" || value === \"shopping\"\n);\n\nconst isTraceContext = (value: unknown): value is ProviderAggregateResult[\"trace\"] => (\n isJsonRecord(value)\n && typeof value.requestId === \"string\"\n && typeof value.ts === \"string\"\n && (value.sessionId === undefined || typeof value.sessionId === \"string\")\n && (value.targetId === undefined || typeof value.targetId === \"string\")\n && (value.provider === undefined || typeof value.provider === \"string\")\n);\n\nconst isProviderError = (value: unknown): boolean => (\n isJsonRecord(value)\n && typeof value.code === \"string\"\n && typeof value.message === \"string\"\n && typeof value.retryable === \"boolean\"\n && (value.reasonCode === undefined || typeof value.reasonCode === \"string\")\n && (value.provider === undefined || typeof value.provider === \"string\")\n && (value.source === undefined || isProviderSource(value.source))\n && (value.details === undefined || isJsonRecord(value.details))\n);\n\nconst isNormalizedRecord = (value: unknown): value is NormalizedRecord => (\n isJsonRecord(value)\n && typeof value.id === \"string\"\n && isProviderSource(value.source)\n && typeof value.provider === \"string\"\n && (value.url === undefined || typeof value.url === \"string\")\n && (value.title === undefined || typeof value.title === \"string\")\n && (value.content === undefined || typeof value.content === \"string\")\n && typeof value.timestamp === \"string\"\n && isFiniteNumber(value.confidence)\n && isJsonRecord(value.attributes)\n);\n\nconst isProviderFailureEntry = (value: unknown): value is ProviderFailureEntry => (\n isJsonRecord(value)\n && typeof value.provider === \"string\"\n && isProviderSource(value.source)\n && isProviderError(value.error)\n);\n\nconst isProviderAggregateResult = (value: unknown): value is ProviderAggregateResult => (\n isJsonRecord(value)\n && typeof value.ok === \"boolean\"\n && Array.isArray(value.records)\n && value.records.every((entry) => isNormalizedRecord(entry))\n && isTraceContext(value.trace)\n && typeof value.partial === \"boolean\"\n && Array.isArray(value.failures)\n && value.failures.every((entry) => isProviderFailureEntry(entry))\n && isJsonRecord(value.metrics)\n && isFiniteNumber(value.metrics.attempted)\n && isFiniteNumber(value.metrics.succeeded)\n && isFiniteNumber(value.metrics.failed)\n && isFiniteNumber(value.metrics.retries)\n && isFiniteNumber(value.metrics.latencyMs)\n && typeof value.sourceSelection === \"string\"\n && Array.isArray(value.providerOrder)\n && value.providerOrder.every((entry) => typeof entry === \"string\")\n && (value.meta === undefined || isJsonRecord(value.meta))\n && (value.diagnostics === undefined || isJsonRecord(value.diagnostics))\n && (value.error === undefined || isProviderError(value.error))\n);\n\nconst emptyCheckpointState = (): ProductVideoWorkflowCheckpointState => ({\n completed_step_ids: []\n});\n\nconst isValidHttpUrl = (url: string): boolean => {\n try {\n const parsed = new URL(url.trim());\n return parsed.protocol === \"http:\" || parsed.protocol === \"https:\";\n } catch {\n return false;\n }\n};\n\nconst normalizeProductVideoInput = (input: ProductVideoRunInput): NormalizedProductVideoRunInput => {\n const productUrl = input.product_url?.trim();\n const productName = input.product_name?.trim();\n const providerHint = input.provider_hint?.trim();\n\n if (!productUrl && !productName) {\n throw new Error(\"product_url or product_name is required\");\n }\n if (productUrl && !isValidHttpUrl(productUrl)) {\n throw new Error(\"product_url must be an http(s) URL\");\n }\n\n return {\n ...input,\n ...(productUrl ? { product_url: productUrl } : {}),\n ...(productName ? { product_name: productName } : {}),\n ...(providerHint ? { provider_hint: providerHint } : {}),\n include_screenshots: input.include_screenshots ?? true,\n include_all_images: input.include_all_images ?? true,\n include_copy: input.include_copy ?? true\n };\n};\n\nexport const serializeProductVideoCheckpointState = (\n state: ProductVideoWorkflowCheckpointState\n): Record<string, JsonValue> => ({\n completed_step_ids: [...state.completed_step_ids],\n ...(state.resolved_product_url ? { resolved_product_url: state.resolved_product_url } : {}),\n ...(state.resolved_provider_hint ? { resolved_provider_hint: state.resolved_provider_hint } : {}),\n ...(state.detail_result ? { detail_result: state.detail_result as unknown as Record<string, JsonValue> } : {})\n});\n\nexport const readProductVideoCheckpointState = (\n checkpoint?: WorkflowCheckpoint | null\n): ProductVideoWorkflowCheckpointState => {\n const state = checkpoint?.state;\n if (state === undefined || state === null) {\n return emptyCheckpointState();\n }\n if (!isJsonRecord(state)) {\n throw new Error(\"Product-video workflow checkpoint state must be a record.\");\n }\n\n const completedStepIds = state.completed_step_ids;\n if (!Array.isArray(completedStepIds) || !completedStepIds.every((entry) => typeof entry === \"string\")) {\n throw new Error(\"Product-video workflow checkpoint state is missing valid completed_step_ids.\");\n }\n\n const resolvedProductUrl = state.resolved_product_url;\n if (resolvedProductUrl !== undefined && typeof resolvedProductUrl !== \"string\") {\n throw new Error(\"Product-video workflow checkpoint state has an invalid resolved_product_url.\");\n }\n\n const resolvedProviderHint = state.resolved_provider_hint;\n if (resolvedProviderHint !== undefined && typeof resolvedProviderHint !== \"string\") {\n throw new Error(\"Product-video workflow checkpoint state has an invalid resolved_provider_hint.\");\n }\n\n const detailResult = state.detail_result;\n if (detailResult !== undefined && !isProviderAggregateResult(detailResult)) {\n throw new Error(\"Product-video workflow checkpoint state has an invalid detail_result.\");\n }\n\n return {\n completed_step_ids: [...completedStepIds],\n ...(resolvedProductUrl ? { resolved_product_url: resolvedProductUrl } : {}),\n ...(resolvedProviderHint ? { resolved_provider_hint: resolvedProviderHint } : {}),\n ...(detailResult ? { detail_result: detailResult } : {})\n };\n};\n\nconst buildProductVideoPlanSteps = (\n input: NormalizedProductVideoRunInput\n): ProductVideoWorkflowExecutionStep[] => {\n const steps: ProductVideoWorkflowExecutionStep[] = [\n {\n id: PRODUCT_VIDEO_STEP_IDS.normalizeInput,\n kind: \"normalize_input\",\n input: {\n has_product_url: typeof input.product_url === \"string\",\n has_product_name: typeof input.product_name === \"string\",\n has_provider_hint: typeof input.provider_hint === \"string\"\n }\n }\n ];\n\n if (!input.product_url && input.product_name) {\n steps.push({\n id: PRODUCT_VIDEO_STEP_IDS.resolveProductUrl,\n kind: \"resolve_product_url\",\n input: {\n product_name: input.product_name,\n ...(input.provider_hint ? { provider_hint: input.provider_hint } : {})\n }\n });\n }\n\n steps.push(\n {\n id: PRODUCT_VIDEO_STEP_IDS.fetchProductDetail,\n kind: \"fetch_product_detail\",\n input: {\n ...(input.product_url ? { product_url: input.product_url } : {}),\n ...(input.provider_hint ? { provider_hint: input.provider_hint } : {}),\n ...(typeof input.timeoutMs === \"number\" ? { timeout_ms: input.timeoutMs } : {})\n }\n },\n {\n id: PRODUCT_VIDEO_STEP_IDS.extractProductData,\n kind: \"extract_product_data\",\n input: {}\n },\n {\n id: PRODUCT_VIDEO_STEP_IDS.assembleArtifacts,\n kind: \"assemble_artifacts\",\n input: {\n include_screenshots: input.include_screenshots,\n include_all_images: input.include_all_images,\n include_copy: input.include_copy\n }\n }\n );\n\n return steps;\n};\n\nexport const compileProductVideoExecutionPlan = (args: {\n input: ProductVideoRunInput;\n envelope?: WorkflowResumeEnvelope | null;\n}): CompiledProductVideoExecutionPlan => {\n const input = normalizeProductVideoInput(args.input);\n const checkpointState = readProductVideoCheckpointState(args.envelope?.checkpoint);\n return {\n input,\n compiled: {\n productUrl: input.product_url,\n productName: input.product_name,\n providerHint: input.provider_hint,\n includeScreenshots: input.include_screenshots,\n includeAllImages: input.include_all_images,\n includeCopy: input.include_copy,\n outputDir: input.output_dir,\n ttlHours: input.ttl_hours,\n timeoutMs: input.timeoutMs,\n resolutionRequired: !input.product_url\n },\n plan: {\n kind: \"product_video\",\n steps: buildProductVideoPlanSteps(input),\n meta: {\n resolution_required: !input.product_url,\n include_screenshots: input.include_screenshots,\n include_all_images: input.include_all_images,\n include_copy: input.include_copy\n }\n },\n checkpointState\n };\n};\n","import { createHash } from \"crypto\";\nimport { canonicalizeUrl } from \"./web/crawler\";\nimport { SHOPPING_PROVIDER_IDS } from \"./shopping\";\nimport { enforceShoppingLegalReviewGate } from \"./shopping-workflow\";\nimport { resolveTimebox, type ResolvedTimebox } from \"./timebox\";\nimport type {\n JsonValue,\n NormalizedRecord,\n ProviderAggregateResult,\n ProviderFailureEntry,\n ProviderSelection,\n ProviderSource\n} from \"./types\";\nimport type { ResearchRunInput } from \"./workflows\";\nimport type { WorkflowCheckpoint, WorkflowPlan, WorkflowPlanStep, WorkflowResumeEnvelope } from \"./workflow-contracts\";\n\nconst RESEARCH_AUTO_SOURCES: ProviderSource[] = [\"web\", \"community\", \"social\"];\nconst RESEARCH_ALL_SOURCES: ProviderSource[] = [...RESEARCH_AUTO_SOURCES];\nconst DEFAULT_RESEARCH_SEARCH_LIMIT = 10;\nexport const RESEARCH_WEB_SEARCH_FETCH_LIMIT = 5;\nconst RESEARCH_COMMUNITY_EXPANSION_PER_RECORD = 2;\n\nexport type ResearchWorkflowStepKind = \"search\" | \"fetch\";\n\nexport type ResearchSearchStepInput = {\n source: ProviderSource;\n query: string;\n limit: number;\n filters: Record<string, JsonValue>;\n};\n\nexport type ResearchFetchStepInput = {\n source: \"web\";\n url: string;\n};\n\nexport type ResearchSearchWorkflowStep = WorkflowPlanStep & {\n kind: \"search\";\n input: ResearchSearchStepInput;\n};\n\nexport type ResearchFetchWorkflowStep = WorkflowPlanStep & {\n kind: \"fetch\";\n input: ResearchFetchStepInput;\n};\n\nexport type ResearchWorkflowExecutionStep = (\n | ResearchSearchWorkflowStep\n | ResearchFetchWorkflowStep\n) & {\n kind: ResearchWorkflowStepKind;\n};\n\nexport type ResearchCheckpointStepResult = ProviderAggregateResult;\n\nexport type ResearchWorkflowCheckpointState = {\n completed_step_ids: string[];\n step_results_by_id: Record<string, ResearchCheckpointStepResult>;\n};\n\nexport type CompiledResearchExecutionPlan = {\n input: ResearchRunInput;\n compiled: {\n topic: string;\n sourceSelection: ProviderSelection;\n resolvedSources: ProviderSource[];\n timebox: ResolvedTimebox;\n searchLimit: number;\n followUpFetchLimit: number;\n allowFollowUpWebFetch: boolean;\n autoExcludedProviders: string[];\n };\n plan: WorkflowPlan & {\n steps: ResearchSearchWorkflowStep[];\n };\n checkpointState: ResearchWorkflowCheckpointState;\n};\n\nconst isJsonRecord = (value: unknown): value is Record<string, JsonValue> => (\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n);\n\nconst isFiniteNumber = (value: unknown): value is number => (\n typeof value === \"number\" && Number.isFinite(value)\n);\n\nconst isProviderSource = (value: unknown): value is ProviderSource => (\n value === \"web\" || value === \"community\" || value === \"social\" || value === \"shopping\"\n);\n\nconst isTraceContext = (value: unknown): value is ProviderAggregateResult[\"trace\"] => (\n isJsonRecord(value)\n && typeof value.requestId === \"string\"\n && typeof value.ts === \"string\"\n && (value.sessionId === undefined || typeof value.sessionId === \"string\")\n && (value.targetId === undefined || typeof value.targetId === \"string\")\n && (value.provider === undefined || typeof value.provider === \"string\")\n);\n\nconst isProviderError = (value: unknown): boolean => (\n isJsonRecord(value)\n && typeof value.code === \"string\"\n && typeof value.message === \"string\"\n && typeof value.retryable === \"boolean\"\n && (value.reasonCode === undefined || typeof value.reasonCode === \"string\")\n && (value.provider === undefined || typeof value.provider === \"string\")\n && (value.source === undefined || isProviderSource(value.source))\n && (value.details === undefined || isJsonRecord(value.details))\n);\n\nconst isNormalizedRecord = (value: unknown): value is NormalizedRecord => (\n isJsonRecord(value)\n && typeof value.id === \"string\"\n && isProviderSource(value.source)\n && typeof value.provider === \"string\"\n && (value.url === undefined || typeof value.url === \"string\")\n && (value.title === undefined || typeof value.title === \"string\")\n && (value.content === undefined || typeof value.content === \"string\")\n && typeof value.timestamp === \"string\"\n && isFiniteNumber(value.confidence)\n && isJsonRecord(value.attributes)\n);\n\nconst isProviderFailureEntry = (value: unknown): value is ProviderFailureEntry => (\n isJsonRecord(value)\n && typeof value.provider === \"string\"\n && isProviderSource(value.source)\n && isProviderError(value.error)\n);\n\nconst isProviderAggregateResult = (value: unknown): value is ProviderAggregateResult => (\n isJsonRecord(value)\n && typeof value.ok === \"boolean\"\n && Array.isArray(value.records)\n && value.records.every((entry) => isNormalizedRecord(entry))\n && isTraceContext(value.trace)\n && typeof value.partial === \"boolean\"\n && Array.isArray(value.failures)\n && value.failures.every((entry) => isProviderFailureEntry(entry))\n && isJsonRecord(value.metrics)\n && isFiniteNumber(value.metrics.attempted)\n && isFiniteNumber(value.metrics.succeeded)\n && isFiniteNumber(value.metrics.failed)\n && isFiniteNumber(value.metrics.retries)\n && isFiniteNumber(value.metrics.latencyMs)\n && typeof value.sourceSelection === \"string\"\n && Array.isArray(value.providerOrder)\n && value.providerOrder.every((entry) => typeof entry === \"string\")\n && (value.meta === undefined || isJsonRecord(value.meta))\n && (value.diagnostics === undefined || isJsonRecord(value.diagnostics))\n && (value.error === undefined || isProviderError(value.error))\n);\n\nconst emptyCheckpointState = (): ResearchWorkflowCheckpointState => ({\n completed_step_ids: [],\n step_results_by_id: {}\n});\n\nconst toProviderSource = (providerId: string): ProviderSource | null => {\n if (providerId.startsWith(\"web/\")) return \"web\";\n if (providerId.startsWith(\"community/\")) return \"community\";\n if (providerId.startsWith(\"social/\")) return \"social\";\n if (providerId.startsWith(\"shopping/\")) return \"shopping\";\n return null;\n};\n\nexport const createResearchSearchStepId = (source: ProviderSource): string => `search:${source}`;\n\nexport const createResearchFetchStepId = (url: string): string => (\n `fetch:web:${createHash(\"sha1\").update(canonicalizeUrl(url)).digest(\"hex\").slice(0, 16)}`\n);\n\nexport const serializeResearchCheckpointState = (\n state: ResearchWorkflowCheckpointState\n): Record<string, JsonValue> => ({\n completed_step_ids: [...state.completed_step_ids],\n step_results_by_id: state.step_results_by_id as unknown as Record<string, JsonValue>\n});\n\nexport const readResearchCheckpointState = (\n checkpoint?: WorkflowCheckpoint | null\n): ResearchWorkflowCheckpointState => {\n const state = checkpoint?.state;\n if (state === undefined || state === null) {\n return emptyCheckpointState();\n }\n if (!isJsonRecord(state)) {\n throw new Error(\"Research workflow checkpoint state must be a record.\");\n }\n\n const completedStepIds = state.completed_step_ids;\n if (!Array.isArray(completedStepIds) || !completedStepIds.every((entry) => typeof entry === \"string\")) {\n throw new Error(\"Research workflow checkpoint state is missing valid completed_step_ids.\");\n }\n\n const rawResults = state.step_results_by_id;\n if (!isJsonRecord(rawResults)) {\n throw new Error(\"Research workflow checkpoint state is missing valid step_results_by_id.\");\n }\n\n const stepResultsById: Record<string, ResearchCheckpointStepResult> = {};\n for (const [stepId, result] of Object.entries(rawResults)) {\n if (!isProviderAggregateResult(result)) {\n throw new Error(`Research workflow checkpoint state contains an invalid result for ${stepId}.`);\n }\n stepResultsById[stepId] = result;\n }\n\n return {\n completed_step_ids: [...completedStepIds],\n step_results_by_id: stepResultsById\n };\n};\n\nexport const resolveResearchSources = (input: ResearchRunInput): {\n sourceSelection: ProviderSelection;\n resolved: ProviderSource[];\n} => {\n if (input.sources && input.sources.length > 0) {\n return {\n sourceSelection: input.sourceSelection ?? \"auto\",\n resolved: [...new Set(input.sources)]\n };\n }\n\n const selection = input.sourceSelection ?? \"auto\";\n if (selection === \"all\") {\n return { sourceSelection: selection, resolved: RESEARCH_ALL_SOURCES };\n }\n if (selection === \"auto\") {\n return { sourceSelection: selection, resolved: RESEARCH_AUTO_SOURCES };\n }\n return {\n sourceSelection: selection,\n resolved: [selection]\n };\n};\n\nconst resolveResearchAutoExcludedProviders = (\n sourceSelection: ProviderSelection,\n resolvedSources: ProviderSource[],\n degradedProviders: ReadonlySet<string>\n): string[] => {\n if (sourceSelection !== \"auto\") {\n return [];\n }\n const sourceSet = new Set(resolvedSources);\n return [...degradedProviders]\n .filter((provider) => {\n const source = toProviderSource(provider);\n return source !== null && sourceSet.has(source);\n })\n .sort((left, right) => left.localeCompare(right));\n};\n\nconst buildResearchSearchFilters = (\n source: ProviderSource,\n args: {\n includeEngagement?: boolean;\n timebox: ResolvedTimebox;\n }\n): Record<string, JsonValue> => ({\n include_engagement: args.includeEngagement ?? false,\n timebox_from: args.timebox.from,\n timebox_to: args.timebox.to,\n ...(source === \"community\" || source === \"social\" ? {\n pageLimit: 1,\n hopLimit: source === \"community\" ? 1 : 0,\n expansionPerRecord: source === \"community\" ? RESEARCH_COMMUNITY_EXPANSION_PER_RECORD : 0\n } : {})\n});\n\nexport const compileResearchExecutionPlan = (args: {\n input: ResearchRunInput;\n envelope?: WorkflowResumeEnvelope | null;\n now?: Date;\n getDegradedProviders?: () => ReadonlySet<string>;\n}): CompiledResearchExecutionPlan => {\n const topic = args.input.topic?.trim();\n if (!topic) {\n throw new Error(\"topic is required\");\n }\n\n const { sourceSelection, resolved } = resolveResearchSources(args.input);\n const now = args.now ?? new Date();\n const timebox = resolveTimebox({\n days: args.input.days,\n from: args.input.from,\n to: args.input.to,\n now\n });\n if (resolved.includes(\"shopping\")) {\n enforceShoppingLegalReviewGate(SHOPPING_PROVIDER_IDS, now);\n }\n\n const searchLimit = args.input.limitPerSource ?? DEFAULT_RESEARCH_SEARCH_LIMIT;\n const autoExcludedProviders = resolveResearchAutoExcludedProviders(\n sourceSelection,\n resolved,\n args.getDegradedProviders?.() ?? new Set<string>()\n );\n const checkpointState = readResearchCheckpointState(args.envelope?.checkpoint ?? null);\n const searchSteps: ResearchSearchWorkflowStep[] = resolved.map((source) => ({\n id: createResearchSearchStepId(source),\n kind: \"search\",\n budget: {\n maxResults: searchLimit\n },\n policy: {\n sources: [source]\n },\n input: {\n source,\n query: topic,\n limit: searchLimit,\n filters: buildResearchSearchFilters(source, {\n includeEngagement: args.input.includeEngagement,\n timebox\n })\n }\n }));\n\n return {\n input: args.input,\n compiled: {\n topic,\n sourceSelection,\n resolvedSources: resolved,\n timebox,\n searchLimit,\n followUpFetchLimit: Math.max(1, Math.min(searchLimit, RESEARCH_WEB_SEARCH_FETCH_LIMIT)),\n allowFollowUpWebFetch: resolved.includes(\"web\"),\n autoExcludedProviders\n },\n checkpointState,\n plan: {\n kind: \"research\",\n steps: searchSteps\n }\n };\n};\n","import { canonicalizeUrl } from \"./web/crawler\";\nimport { isLikelyResearchDestinationUrl } from \"./shared/traversal-url\";\nimport {\n buildWorkflowResumeEnvelope,\n type WorkflowCheckpoint,\n type WorkflowResumeEnvelope,\n type WorkflowTraceEntry\n} from \"./workflow-contracts\";\nimport {\n createResearchFetchStepId,\n serializeResearchCheckpointState,\n type CompiledResearchExecutionPlan,\n type ResearchFetchWorkflowStep,\n type ResearchSearchWorkflowStep,\n type ResearchWorkflowCheckpointState,\n type ResearchWorkflowExecutionStep\n} from \"./research-compiler\";\nimport type {\n JsonValue,\n NormalizedRecord,\n ProviderAggregateResult,\n ProviderRunOptions,\n ProviderSource\n} from \"./types\";\nimport type { ProviderExecutor } from \"./workflows\";\n\nconst RESEARCH_WEB_SEARCH_FETCH_PATHS = new Set<string>([\n \"community:search:index\",\n \"community:search:url\",\n \"web:search:index\",\n \"web:search:url\",\n \"social:youtube:search:url\",\n \"social:search:url\",\n \"social:search:index\"\n]);\n\nexport type ResearchWorkflowSearchRun = {\n source: ProviderSource;\n result: ProviderAggregateResult;\n};\n\nexport type ResearchWorkflowFollowUpRun = {\n source: \"web\";\n url: string;\n result: ProviderAggregateResult;\n};\n\nexport type ResearchWorkflowExecutionResult = {\n searchRuns: ResearchWorkflowSearchRun[];\n followUpRuns: ResearchWorkflowFollowUpRun[];\n checkpoint: WorkflowCheckpoint;\n trace: WorkflowTraceEntry[];\n};\n\nexport type ExecuteResearchWorkflowPlanOptions = {\n trace?: WorkflowTraceEntry[];\n observeResult?: (result: ProviderAggregateResult) => void;\n buildStepOptions: (\n step: ResearchWorkflowExecutionStep,\n envelope: WorkflowResumeEnvelope\n ) => ProviderRunOptions;\n};\n\nconst appendTrace = (\n trace: WorkflowTraceEntry[],\n stage: WorkflowTraceEntry[\"stage\"],\n event: string,\n details: Record<string, JsonValue>\n): WorkflowTraceEntry[] => [\n ...trace,\n {\n at: new Date().toISOString(),\n stage,\n event,\n details\n }\n];\n\nconst getCheckpointedResult = (\n checkpointState: ResearchWorkflowCheckpointState,\n stepId: string\n): ProviderAggregateResult => {\n const result = checkpointState.step_results_by_id[stepId];\n if (!result) {\n throw new Error(`Research workflow checkpoint is missing result for completed step ${stepId}.`);\n }\n return result;\n};\n\nconst buildCheckpoint = (\n checkpointState: ResearchWorkflowCheckpointState,\n step: ResearchWorkflowExecutionStep,\n stepIndex: number\n): WorkflowCheckpoint => ({\n stage: \"execute\",\n stepId: step.id,\n stepIndex,\n state: serializeResearchCheckpointState(checkpointState),\n updatedAt: new Date().toISOString()\n});\n\nconst markStepCompleted = (\n checkpointState: ResearchWorkflowCheckpointState,\n stepId: string,\n result: ProviderAggregateResult\n): ResearchWorkflowCheckpointState => ({\n completed_step_ids: [...new Set([...checkpointState.completed_step_ids, stepId])],\n step_results_by_id: {\n ...checkpointState.step_results_by_id,\n [stepId]: result\n }\n});\n\nconst isValidHttpUrl = (url: string): boolean => {\n try {\n const parsed = new URL(url.trim());\n return parsed.protocol === \"http:\" || parsed.protocol === \"https:\";\n } catch {\n return false;\n }\n};\n\nconst attributeLinks = (record: NormalizedRecord): string[] => {\n const links = record.attributes.links;\n if (!Array.isArray(links)) return [];\n return links.filter((link): link is string => typeof link === \"string\");\n};\n\nconst researchCandidateUrls = (record: NormalizedRecord): string[] => [\n ...(typeof record.url === \"string\" ? [record.url] : []),\n ...attributeLinks(record)\n];\n\nexport const resolveResearchWebFetchCandidates = (\n records: NormalizedRecord[],\n limit: number\n): string[] => {\n const candidates: string[] = [];\n const seen = new Set<string>();\n\n for (const record of records) {\n const retrievalPath = typeof record.attributes.retrievalPath === \"string\"\n ? record.attributes.retrievalPath\n : \"\";\n if (!RESEARCH_WEB_SEARCH_FETCH_PATHS.has(retrievalPath)) {\n continue;\n }\n for (const candidateUrl of researchCandidateUrls(record)) {\n const rawUrl = canonicalizeUrl(candidateUrl);\n if (!rawUrl) continue;\n\n let resolvedUrl = rawUrl;\n try {\n const parsed = new URL(rawUrl);\n if (/duckduckgo\\.com$/i.test(parsed.hostname) && (parsed.pathname === \"/l\" || parsed.pathname === \"/l/\")) {\n const redirect = parsed.searchParams.get(\"uddg\");\n if (typeof redirect === \"string\" && redirect.length > 0) {\n resolvedUrl = canonicalizeUrl(redirect);\n }\n }\n } catch {\n continue;\n }\n\n if (\n !resolvedUrl\n || !isValidHttpUrl(resolvedUrl)\n || !isLikelyResearchDestinationUrl(resolvedUrl)\n || /duckduckgo\\.com/i.test(resolvedUrl)\n || seen.has(resolvedUrl)\n ) {\n continue;\n }\n seen.add(resolvedUrl);\n candidates.push(resolvedUrl);\n if (candidates.length >= limit) {\n break;\n }\n }\n if (candidates.length >= limit) {\n break;\n }\n }\n\n return candidates;\n};\n\nconst buildSearchRuns = (\n steps: readonly ResearchSearchWorkflowStep[],\n checkpointState: ResearchWorkflowCheckpointState\n): ResearchWorkflowSearchRun[] => steps.map((step) => ({\n source: step.input.source,\n result: getCheckpointedResult(checkpointState, step.id)\n}));\n\nconst deriveResearchFetchSteps = (\n plan: CompiledResearchExecutionPlan,\n searchRuns: ResearchWorkflowSearchRun[]\n): ResearchFetchWorkflowStep[] => {\n if (!plan.compiled.allowFollowUpWebFetch) {\n return [];\n }\n\n return resolveResearchWebFetchCandidates(\n searchRuns.flatMap((run) => run.result.records),\n plan.compiled.followUpFetchLimit\n ).map((url) => ({\n id: createResearchFetchStepId(url),\n kind: \"fetch\",\n policy: {\n sources: [\"web\"]\n },\n input: {\n source: \"web\",\n url\n }\n }));\n};\n\nconst buildFollowUpRuns = (\n steps: ResearchFetchWorkflowStep[],\n checkpointState: ResearchWorkflowCheckpointState\n): ResearchWorkflowFollowUpRun[] => steps.map((step) => ({\n source: \"web\",\n url: step.input.url,\n result: getCheckpointedResult(checkpointState, step.id)\n}));\n\nconst executeSearchStep = async (\n runtime: ProviderExecutor,\n step: ResearchSearchWorkflowStep,\n options: ExecuteResearchWorkflowPlanOptions,\n envelope: WorkflowResumeEnvelope\n): Promise<ProviderAggregateResult> => {\n return runtime.search({\n query: step.input.query,\n limit: step.input.limit,\n filters: step.input.filters\n }, options.buildStepOptions(step, envelope));\n};\n\nconst executeFetchStep = async (\n runtime: ProviderExecutor,\n step: ResearchFetchWorkflowStep,\n options: ExecuteResearchWorkflowPlanOptions,\n envelope: WorkflowResumeEnvelope\n): Promise<ProviderAggregateResult> => {\n return runtime.fetch({\n url: step.input.url\n }, options.buildStepOptions(step, envelope));\n};\n\nexport const executeResearchWorkflowPlan = async (\n runtime: ProviderExecutor,\n plan: CompiledResearchExecutionPlan,\n options: ExecuteResearchWorkflowPlanOptions\n): Promise<ResearchWorkflowExecutionResult> => {\n let checkpointState: ResearchWorkflowCheckpointState = {\n completed_step_ids: [...plan.checkpointState.completed_step_ids],\n step_results_by_id: { ...plan.checkpointState.step_results_by_id }\n };\n let trace = [...(options.trace ?? [])];\n let stepIndex = 0;\n let lastCheckpoint = buildCheckpoint(\n checkpointState,\n plan.plan.steps[0] ?? {\n id: \"research:execute\",\n kind: \"search\",\n input: {\n source: plan.compiled.resolvedSources[0] ?? \"web\",\n query: plan.compiled.topic,\n limit: 0,\n filters: {\n include_engagement: false,\n timebox_from: plan.compiled.timebox.from,\n timebox_to: plan.compiled.timebox.to\n }\n }\n },\n 0\n );\n\n const runSteps = async (steps: ResearchWorkflowExecutionStep[]): Promise<void> => {\n for (const step of steps) {\n const currentStepIndex = stepIndex;\n stepIndex += 1;\n\n if (checkpointState.completed_step_ids.includes(step.id)) {\n getCheckpointedResult(checkpointState, step.id);\n lastCheckpoint = buildCheckpoint(checkpointState, step, currentStepIndex);\n trace = appendTrace(trace, \"resume\", \"step_reused\", {\n stepId: step.id,\n stepKind: step.kind,\n source: step.input.source,\n ...(step.kind === \"fetch\" ? { url: step.input.url } : {})\n });\n continue;\n }\n\n trace = appendTrace(trace, \"execute\", \"step_started\", {\n stepId: step.id,\n stepKind: step.kind,\n source: step.input.source,\n ...(step.kind === \"fetch\" ? { url: step.input.url } : {})\n });\n const checkpoint = buildCheckpoint(checkpointState, step, currentStepIndex);\n const preSuspendTrace = appendTrace(trace, \"execute\", \"pre_suspend_checkpoint\", {\n stepId: step.id,\n stepKind: step.kind,\n source: step.input.source,\n ...(step.kind === \"fetch\" ? { url: step.input.url } : {}),\n completedSteps: checkpointState.completed_step_ids.length\n });\n const envelope = buildWorkflowResumeEnvelope(\n \"research\",\n plan.input as unknown as JsonValue,\n {\n checkpoint,\n trace: preSuspendTrace\n }\n );\n const result = step.kind === \"search\"\n ? await executeSearchStep(runtime, step, options, envelope)\n : await executeFetchStep(runtime, step, options, envelope);\n checkpointState = markStepCompleted(checkpointState, step.id, result);\n options.observeResult?.(result);\n trace = appendTrace(preSuspendTrace, \"execute\", \"step_completed\", {\n stepId: step.id,\n stepKind: step.kind,\n source: step.input.source,\n ...(step.kind === \"fetch\" ? { url: step.input.url } : {}),\n records: result.records.length,\n failures: result.failures.length\n });\n lastCheckpoint = buildCheckpoint(checkpointState, step, currentStepIndex);\n }\n };\n\n await runSteps(plan.plan.steps);\n\n const searchRuns = buildSearchRuns(plan.plan.steps, checkpointState);\n const followUpSteps = deriveResearchFetchSteps(plan, searchRuns);\n if (followUpSteps.length > 0) {\n trace = appendTrace(trace, \"execute\", \"tactical_decision\", {\n reason: \"selective_web_follow_up\",\n fetchSteps: followUpSteps.length,\n urls: followUpSteps.map((step) => step.input.url)\n });\n }\n await runSteps(followUpSteps);\n\n return {\n searchRuns: buildSearchRuns(plan.plan.steps, checkpointState),\n followUpRuns: buildFollowUpRuns(followUpSteps, checkpointState),\n checkpoint: lastCheckpoint,\n trace\n };\n};\n","import type { InspiredesignCaptureMode } from \"../providers/types\";\n\nconst hasInspiredesignUrls = (urls?: readonly string[]): boolean => {\n return Array.isArray(urls) && urls.some((url) => url.trim().length > 0);\n};\n\nexport function resolveInspiredesignCaptureMode(\n requested: InspiredesignCaptureMode | undefined,\n urls?: readonly string[]\n): InspiredesignCaptureMode {\n return hasInspiredesignUrls(urls) ? \"deep\" : requested ?? \"off\";\n}\n","import { createProviderError, isProviderReasonCode, providerErrorCodeFromReasonCode } from \"./errors\";\nimport type { JsonValue, NormalizedRecord, ProviderFailureEntry, ProviderReasonCode, ProviderSource } from \"./types\";\nimport type { SiteRecipe, SiteRecipeBadState } from \"../guidance/types\";\n\nexport type BrowserNativeDiscoveryResult = {\n records: NormalizedRecord[];\n failures: ProviderFailureEntry[];\n diagnostics: Record<string, JsonValue>;\n};\n\nexport type BrowserNativeDiscoveryInput = {\n recipe: SiteRecipe;\n query: string;\n maxReferences: number;\n browserMode?: string;\n useCookies?: boolean;\n cookiePolicy?: string;\n fetchSearchPage?: (url: string) => Promise<BrowserNativeDiscoveryFetchResult>;\n};\n\nexport type BrowserNativeDiscoveryFetchResult = {\n records: NormalizedRecord[];\n failures: ProviderFailureEntry[];\n errorMessage?: string;\n};\n\ntype MatchedBadState = {\n state: SiteRecipeBadState;\n reasonCode: ProviderReasonCode;\n};\n\ntype BadStateMatchMode = \"hard_blocker\" | \"pre_extraction\" | \"all\";\n\nconst HARD_FAILURE_REASON_CODES = new Set<ProviderReasonCode>([\n \"auth_required\",\n \"challenge_detected\",\n \"policy_blocked\",\n \"rate_limited\",\n \"token_required\"\n]);\n\nconst sourceForRecipe = (recipe: SiteRecipe): ProviderSource => {\n return recipe.id.startsWith(\"social/\") ? \"social\" : \"web\";\n};\n\nconst needsAuthenticatedBrowser = (input: BrowserNativeDiscoveryInput): boolean => {\n if (input.recipe.authMode === \"public\") return false;\n if (input.cookiePolicy === \"required\") return true;\n return input.recipe.authMode === \"authenticated\";\n};\n\nconst hasAuthenticatedBrowser = (input: BrowserNativeDiscoveryInput): boolean => {\n return input.browserMode === \"extension\" && input.useCookies === true;\n};\n\nconst htmlFromRecord = (record: NormalizedRecord): string => {\n const html = record.attributes.html;\n return typeof html === \"string\" ? html : \"\";\n};\n\nconst linksFromRecord = (record: NormalizedRecord): string[] => {\n const links = record.attributes.links;\n return Array.isArray(links) ? links.filter((link): link is string => typeof link === \"string\") : [];\n};\n\nconst badStateTextForRecord = (record: NormalizedRecord): string => {\n return [\n record.url ?? \"\",\n record.title ?? \"\",\n record.content ?? \"\",\n htmlFromRecord(record)\n ].join(\" \").toLowerCase();\n};\n\nconst normalizeBadStateReasonCode = (state: SiteRecipeBadState): ProviderReasonCode => {\n return isProviderReasonCode(state.reasonCode) ? state.reasonCode : \"env_limited\";\n};\n\nconst shouldMatchBadState = (state: SiteRecipeBadState, mode: BadStateMatchMode): boolean => {\n if (mode === \"hard_blocker\") return state.id === \"challenge\";\n return mode === \"all\" || state.id !== \"search-shell\";\n};\n\nconst findBadState = (\n recipe: SiteRecipe,\n records: NormalizedRecord[],\n mode: BadStateMatchMode\n): MatchedBadState | undefined => {\n for (const record of records) {\n const text = badStateTextForRecord(record);\n const state = recipe.badStates.find((candidate) => (\n shouldMatchBadState(candidate, mode)\n && candidate.markers.some((marker) => text.includes(marker.toLowerCase()))\n ));\n if (state) {\n return {\n state,\n reasonCode: normalizeBadStateReasonCode(state)\n };\n }\n }\n return undefined;\n};\n\nconst findHardFailure = (failures: ProviderFailureEntry[]): ProviderFailureEntry | undefined => (\n failures.find((failure) => {\n const reasonCode = failure.error.reasonCode ?? failure.error.details?.reasonCode;\n return typeof reasonCode === \"string\"\n && isProviderReasonCode(reasonCode)\n && HARD_FAILURE_REASON_CODES.has(reasonCode);\n })\n);\n\nconst reasonCodeForFailure = (failure: ProviderFailureEntry): ProviderReasonCode | undefined => {\n const reasonCode = failure.error.reasonCode ?? failure.error.details?.reasonCode;\n return typeof reasonCode === \"string\" && isProviderReasonCode(reasonCode) ? reasonCode : undefined;\n};\n\nconst buildBadStateResult = (\n input: BrowserNativeDiscoveryInput,\n source: ProviderSource,\n searchUrl: string,\n fetchedRecordCount: number,\n badState: MatchedBadState\n): BrowserNativeDiscoveryResult => ({\n records: [],\n failures: [{\n provider: input.recipe.id,\n source,\n error: createProviderError(\n providerErrorCodeFromReasonCode(badState.reasonCode),\n badState.state.recoveryAction,\n {\n retryable: true,\n reasonCode: badState.reasonCode,\n provider: input.recipe.id,\n source,\n details: {\n siteRecipeId: input.recipe.id,\n query: input.query,\n searchUrl,\n badStateId: badState.state.id\n }\n }\n )\n }],\n diagnostics: {\n siteRecipeId: input.recipe.id,\n attempted: true,\n reason: badState.reasonCode,\n searchUrl,\n fetchedRecordCount,\n badStateId: badState.state.id,\n recoveryAction: badState.state.recoveryAction\n }\n});\n\nconst buildHardFailureResult = (\n input: BrowserNativeDiscoveryInput,\n source: ProviderSource,\n searchUrl: string,\n fetchedRecordCount: number,\n failure: ProviderFailureEntry\n): BrowserNativeDiscoveryResult => ({\n records: [],\n failures: [failure],\n diagnostics: {\n siteRecipeId: input.recipe.id,\n attempted: true,\n reason: reasonCodeForFailure(failure) ?? \"challenge_detected\",\n searchUrl,\n fetchedRecordCount,\n recoveryAction: failure.error.message\n }\n});\n\nconst extractRecipeReferenceUrls = (\n input: BrowserNativeDiscoveryInput,\n records: NormalizedRecord[],\n maxReferences: number\n): string[] => {\n const extractor = input.recipe.browserNativeDiscovery?.extractReferenceUrls;\n if (!extractor) return [];\n const urls: string[] = [];\n const seen = new Set<string>();\n const pushUrl = (url: string): void => {\n if (!url || seen.has(url)) return;\n seen.add(url);\n urls.push(url);\n };\n for (const record of records) {\n extractor({\n url: record.url ?? undefined,\n content: record.content ?? undefined,\n html: typeof record.attributes.html === \"string\" ? record.attributes.html : undefined,\n links: linksFromRecord(record)\n }).forEach(pushUrl);\n if (urls.length >= maxReferences) break;\n }\n return urls.slice(0, maxReferences);\n};\n\nconst buildRecipeReferenceRecord = (\n input: BrowserNativeDiscoveryInput,\n url: string,\n index: number\n): NormalizedRecord => {\n const timestamp = new Date().toISOString();\n return {\n id: `${input.recipe.id}:reference:${index + 1}:${timestamp}`,\n source: sourceForRecipe(input.recipe),\n provider: input.recipe.id,\n url,\n title: `Site visual reference ${index + 1} for ${input.query}`,\n content: input.recipe.navigationSteps.map((step) => step.instruction).join(\" \"),\n timestamp,\n confidence: 0.72,\n attributes: {\n siteRecipeId: input.recipe.id,\n discoveryMode: \"browser_native_extracted_reference\",\n authMode: input.recipe.authMode,\n maxReferences: input.maxReferences,\n validationChecks: input.recipe.evidenceRequirements.map((entry) => entry.validation)\n }\n };\n};\n\nexport const runBrowserNativeDiscovery = async (\n input: BrowserNativeDiscoveryInput\n): Promise<BrowserNativeDiscoveryResult> => {\n const source = sourceForRecipe(input.recipe);\n const searchUrl = input.recipe.browserNativeDiscovery?.buildSearchUrl(input.query);\n if (!searchUrl) {\n return {\n records: [],\n failures: [{\n provider: input.recipe.id,\n source,\n error: createProviderError(\n \"unavailable\",\n `Site recipe ${input.recipe.id} does not define browser-native discovery.`,\n {\n retryable: false,\n reasonCode: \"env_limited\",\n provider: input.recipe.id,\n source,\n details: {\n siteRecipeId: input.recipe.id,\n query: input.query\n }\n }\n )\n }],\n diagnostics: {\n siteRecipeId: input.recipe.id,\n attempted: false,\n reason: \"unsupported_site_recipe\"\n }\n };\n }\n if (needsAuthenticatedBrowser(input) && !hasAuthenticatedBrowser(input)) {\n return {\n records: [],\n failures: [{\n provider: input.recipe.id,\n source,\n error: createProviderError(\n \"auth\",\n `${input.recipe.id} requires an authenticated browser session before search results are visible.`,\n {\n retryable: true,\n reasonCode: \"auth_required\",\n provider: input.recipe.id,\n source,\n details: {\n siteRecipeId: input.recipe.id,\n query: input.query,\n requiredBrowserMode: \"extension\",\n requiredCookies: true\n }\n }\n )\n }],\n diagnostics: {\n siteRecipeId: input.recipe.id,\n attempted: false,\n reason: \"auth_required\",\n recoverySteps: input.recipe.recoverySteps.map((step) => step.instruction)\n }\n };\n }\n\n if (!input.fetchSearchPage) {\n return {\n records: [],\n failures: [{\n provider: input.recipe.id,\n source,\n error: createProviderError(\n \"unavailable\",\n `${input.recipe.id} browser-native discovery requires a browser-backed fetch executor for the search page.`,\n {\n retryable: true,\n reasonCode: \"env_limited\",\n provider: input.recipe.id,\n source,\n details: {\n siteRecipeId: input.recipe.id,\n query: input.query,\n searchUrl\n }\n }\n )\n }],\n diagnostics: {\n siteRecipeId: input.recipe.id,\n attempted: false,\n reason: \"fetch_executor_missing\",\n searchUrl\n }\n };\n }\n\n const fetched = await input.fetchSearchPage(searchUrl);\n const hardFailure = findHardFailure(fetched.failures);\n if (hardFailure) {\n return buildHardFailureResult(input, source, searchUrl, fetched.records.length, hardFailure);\n }\n const preExtractionMode = needsAuthenticatedBrowser(input) ? \"pre_extraction\" : \"hard_blocker\";\n const hardBlocker = findBadState(input.recipe, fetched.records, preExtractionMode);\n if (hardBlocker) {\n return buildBadStateResult(input, source, searchUrl, fetched.records.length, hardBlocker);\n }\n const extractedUrls = extractRecipeReferenceUrls(input, fetched.records, input.maxReferences);\n if (extractedUrls.length === 0) {\n const shellState = fetched.failures.length === 0 ? findBadState(input.recipe, fetched.records, \"all\") : undefined;\n if (shellState) {\n return buildBadStateResult(input, source, searchUrl, fetched.records.length, shellState);\n }\n return {\n records: [],\n failures: fetched.failures.length > 0\n ? fetched.failures\n : [{\n provider: input.recipe.id,\n source,\n error: createProviderError(\n \"unavailable\",\n fetched.errorMessage ?? `${input.recipe.id} search did not expose recipe-approved URLs that can be used as references.`,\n {\n retryable: true,\n reasonCode: \"env_limited\",\n provider: input.recipe.id,\n source,\n details: {\n siteRecipeId: input.recipe.id,\n query: input.query,\n searchUrl\n }\n }\n )\n }],\n diagnostics: {\n siteRecipeId: input.recipe.id,\n attempted: true,\n reason: \"no_reference_urls_extracted\",\n searchUrl,\n fetchedRecordCount: fetched.records.length\n }\n };\n }\n\n return {\n records: extractedUrls.map((url, index) => buildRecipeReferenceRecord(input, url, index)),\n failures: [],\n diagnostics: {\n siteRecipeId: input.recipe.id,\n attempted: true,\n reason: \"reference_urls_extracted\",\n searchUrl,\n navigationSteps: input.recipe.navigationSteps.map((step) => step.instruction),\n badStates: input.recipe.badStates.map((state) => state.id),\n extractedUrlCount: extractedUrls.length\n }\n };\n};\n","import {\n isProviderRuntimeError,\n ProviderRuntimeError,\n normalizeProviderReasonCode,\n providerErrorCodeFromReasonCode,\n toProviderError\n} from \"./errors\";\nimport { applyProviderIssueHint, classifyProviderIssue, type ProviderIssueHint } from \"./constraint\";\nimport { createExecutionMetadata, normalizeFailure, normalizeSuccess, createTraceContext } from \"./normalize\";\nimport { selectProviders } from \"./policy\";\nimport { ProviderRegistry, type ProviderAntiBotSnapshot } from \"./registry\";\nimport { AdaptiveConcurrencyController } from \"./adaptive-concurrency\";\nimport { applyPromptGuard } from \"./safety/prompt-guard\";\nimport { fallbackTierMetadata, selectTierRoute, shouldFallbackToTierA } from \"./tier-router\";\nimport {\n browserFallbackObservationDetails,\n browserFallbackObservationAttributes,\n readFallbackString,\n resolveProviderBrowserFallback,\n toCompletedFallbackOutputError,\n toBrowserFallbackObservation,\n toProviderFallbackError\n} from \"./browser-fallback\";\nimport { resolveProviderRuntimePolicy } from \"./runtime-policy\";\nimport { createLogger } from \"../core/logging\";\nimport type { ChallengeAutomationMode } from \"../challenges\";\nimport {\n AntiBotPolicyEngine,\n type AntiBotPolicyConfig\n} from \"./shared/anti-bot-policy\";\nimport { createCommunityProvider, type CommunityProviderOptions } from \"./community\";\nimport {\n createSocialProviders,\n withDefaultYouTubeOptions,\n type SocialPlatform,\n type SocialProviderOptions,\n type SocialProvidersOptions\n} from \"./social\";\nimport {\n detectSocialSearchShell,\n isAllowedSocialSearchExpansionUrl,\n isFirstPartySocialSearchRoute,\n prioritizeSocialSearchLinks,\n selectUsableSocialSearchLinks\n} from \"./social/search-quality\";\nimport { createShoppingProviders, type ShoppingProvidersOptions } from \"./shopping\";\nimport { providerRequestHeaders } from \"./shared/request-headers\";\nimport {\n isLikelyDocumentUrl,\n isLikelyResearchDestinationUrl\n} from \"./shared/traversal-url\";\nimport { createWebProvider, type WebProviderOptions } from \"./web\";\nimport { mapBounded } from \"./bounded-map\";\nimport { classifyBlockerSignal } from \"./blocker\";\nimport { canonicalizeUrl } from \"./web/crawler\";\nimport { extractStructuredContent, extractText, toSnippet } from \"./web/extract\";\nimport { isWorkflowResumePayload, type WorkflowKind, type WorkflowResumeEnvelope } from \"./workflow-contracts\";\nimport {\n runInspiredesignWorkflow,\n runProductVideoWorkflow,\n runResearchWorkflow,\n runShoppingWorkflow\n} from \"./workflows\";\nimport type {\n AdaptiveConcurrencyDiagnostics,\n BrowserFallbackObservation,\n BrowserFallbackResponse,\n BrowserFallbackPort,\n BrowserFallbackMode,\n BlockerSignalV1,\n ChallengeOwnerSurface,\n JsonValue,\n NormalizedRecord,\n ProviderAdapter,\n ProviderAggregateResult,\n ProviderCallResultByOperation,\n ProviderCookiePolicy,\n ProviderCookieSourceConfig,\n ProviderContext,\n ProviderExecutionMetadata,\n ProviderErrorCode,\n ProviderOperation,\n ProviderOperationResult,\n ProviderRecoveryHints,\n ProviderReasonCode,\n ProviderRunOptions,\n ProviderRuntimeBudgets,\n ProviderRuntimeDiagnostics,\n ProviderSelection,\n ProviderSource,\n ProviderTierMetadata,\n ResumeMode,\n SessionChallengeSummary,\n SuspendedIntentKind,\n SuspendedIntentSummary,\n WorkflowSuspendedIntentKind,\n TraceContext\n} from \"./types\";\n\nconst DEFAULT_PROVIDER_SUSPENDED_INTENT_KIND: Record<ProviderOperation, SuspendedIntentKind> = {\n search: \"provider.search\",\n fetch: \"provider.fetch\",\n crawl: \"provider.crawl\",\n post: \"provider.post\"\n};\nconst WORKFLOW_KIND_BY_SUSPENDED_INTENT_KIND: Record<WorkflowSuspendedIntentKind, WorkflowKind> = {\n \"workflow.research\": \"research\",\n \"workflow.shopping\": \"shopping\",\n \"workflow.inspiredesign\": \"inspiredesign\",\n \"workflow.product_video\": \"product_video\"\n};\n\ntype SuspendedIntentResumeResult = ProviderAggregateResult | Record<string, unknown>;\n\nconst EXTENSION_FIRST_SOCIAL_FALLBACK_PLATFORMS = new Set<SocialPlatform>([\"x\", \"reddit\", \"bluesky\", \"facebook\", \"linkedin\", \"threads\"]);\nconst EXTENSION_MINIMAL_TRAVERSAL_SOCIAL_PLATFORMS = new Set<SocialPlatform>([\"linkedin\"]);\nconst EXTENSION_FIRST_FALLBACK_MODES: BrowserFallbackMode[] = [\"extension\", \"managed_headed\"];\nconst SOCIAL_BROWSER_RECOVERY_REASON_CODES = new Set<ProviderReasonCode>([\"challenge_detected\"]);\nconst SEARCH_RENDER_RECOVERY_SOCIAL_PLATFORMS = new Set<SocialPlatform>([\"x\", \"bluesky\", \"reddit\", \"facebook\", \"threads\"]);\n\nconst withPrioritizedFallbackModes = (\n prioritized: readonly BrowserFallbackMode[],\n existing?: readonly BrowserFallbackMode[]\n): BrowserFallbackMode[] => [...new Set([...prioritized, ...(existing ?? [])])];\n\nconst buildSocialRecoveryHints = (\n platform: SocialPlatform,\n options: SocialProviderOptions | undefined\n): ProviderRecoveryHints | undefined => {\n const existing = options?.recoveryHints?.();\n if (!EXTENSION_FIRST_SOCIAL_FALLBACK_PLATFORMS.has(platform)) {\n return existing;\n }\n return {\n ...(existing ?? {}),\n preferredFallbackModes: withPrioritizedFallbackModes(\n EXTENSION_FIRST_FALLBACK_MODES,\n existing?.preferredFallbackModes\n )\n };\n};\n\nconst buildSocialDefaultTraversal = (\n platform: SocialPlatform,\n options: SocialProviderOptions | undefined\n): SocialProviderOptions[\"defaultTraversal\"] => {\n const existing = options?.defaultTraversal;\n if (!EXTENSION_MINIMAL_TRAVERSAL_SOCIAL_PLATFORMS.has(platform)) {\n return existing;\n }\n return {\n pageLimit: 1,\n hopLimit: 0,\n expansionPerRecord: 0,\n ...(existing ?? {})\n };\n};\n\nconst shouldRecoverSocialDocumentIssue = (\n platform: SocialPlatform,\n operation: \"search\" | \"fetch\",\n issue: ProviderIssueHint,\n context: ProviderContext\n): boolean => {\n if (isResearchSearchDiscoveryRun(operation, context)) {\n return false;\n }\n if (SOCIAL_BROWSER_RECOVERY_REASON_CODES.has(issue.reasonCode)) {\n return true;\n }\n if (issue.reasonCode === \"token_required\" && EXTENSION_FIRST_SOCIAL_FALLBACK_PLATFORMS.has(platform)) {\n return true;\n }\n return operation === \"search\"\n && SEARCH_RENDER_RECOVERY_SOCIAL_PLATFORMS.has(platform)\n && issue.reasonCode === \"env_limited\"\n && issue.constraint?.kind === \"render_required\";\n};\n\nconst isJsonRecord = (value: JsonValue | undefined): value is Record<string, JsonValue> => (\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n);\n\nconst unwrapWorkflowResumeEnvelope = (\n kind: WorkflowKind,\n input: JsonValue\n): WorkflowResumeEnvelope => {\n if (!isWorkflowResumePayload(input)) {\n throw new ProviderRuntimeError(\n \"invalid_input\",\n \"Workflow resume payload is missing or malformed.\",\n {\n retryable: false\n }\n );\n }\n if (input.workflow.kind !== kind) {\n throw new ProviderRuntimeError(\n \"invalid_input\",\n `Workflow resume payload kind mismatch. Expected ${kind} but received ${input.workflow.kind}.`,\n {\n retryable: false\n }\n );\n }\n return input.workflow;\n};\n\nclass Semaphore {\n private active = 0;\n private readonly queue: Array<() => void> = [];\n\n constructor(private limit: number) {}\n\n setLimit(limit: number): void {\n this.limit = Math.max(1, Math.floor(limit));\n this.drain();\n }\n\n snapshot(): { limit: number; active: number; queued: number } {\n return {\n limit: this.limit,\n active: this.active,\n queued: this.queue.length\n };\n }\n\n async use<T>(task: () => Promise<T>): Promise<T> {\n await this.acquire();\n try {\n return await task();\n } finally {\n this.release();\n }\n }\n\n private async acquire(): Promise<void> {\n if (this.limit <= 0) return;\n if (this.active < this.limit) {\n this.active += 1;\n return;\n }\n\n await new Promise<void>((resolve) => {\n this.queue.push(() => {\n this.active += 1;\n resolve();\n });\n });\n }\n\n private release(): void {\n if (this.limit <= 0) return;\n this.active = Math.max(0, this.active - 1);\n this.drain();\n }\n\n private drain(): void {\n if (this.limit <= 0) return;\n while (this.active < this.limit) {\n const next = this.queue.shift();\n if (!next) return;\n next();\n }\n }\n}\n\nexport const DEFAULT_PROVIDER_BUDGETS: ProviderRuntimeBudgets = {\n timeoutMs: {\n search: 12000,\n fetch: 12000,\n crawl: 20000,\n post: 15000\n },\n retries: {\n read: 1,\n write: 0\n },\n concurrency: {\n global: 4,\n perProvider: 2,\n perDomain: 2\n },\n circuitBreaker: {\n failureThreshold: 3,\n cooldownMs: 30000\n }\n};\n\nconst isReadOperation = (operation: ProviderOperation): boolean => operation !== \"post\";\n\ntype RuntimeTierConfig = {\n defaultTier: \"A\" | \"B\" | \"C\";\n enableHybrid: boolean;\n enableRestrictedSafe: boolean;\n hybridRiskThreshold: number;\n restrictedSafeRecoveryIntervalMs: number;\n};\n\nconst DEFAULT_TIER_CONFIG = {\n defaultTier: \"A\",\n enableHybrid: false,\n enableRestrictedSafe: false,\n hybridRiskThreshold: 0.6,\n restrictedSafeRecoveryIntervalMs: 60000\n} satisfies RuntimeTierConfig;\n\nconst PLACEHOLDER_PATTERNS: Array<{ code: string; regex: RegExp }> = [\n { code: \"placeholder_local_url\", regex: /https?:\\/\\/(?:placeholder|synthetic|example)\\.local(?:\\/|$)/i },\n { code: \"placeholder_token\", regex: /\\b(?:todo|placeholder|lorem ipsum)\\b/i },\n { code: \"echo_input\", regex: /\\b(?:seed url|query):\\s*[\"'`].{1,120}[\"'`]/i }\n];\n\nconst RUNTIME_FETCH_HEADERS = {\n accept: \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n ...providerRequestHeaders\n} as const;\n\nconst SOCIAL_SEARCH_ENDPOINTS: Record<SocialPlatform, (query: string, page: number) => string> = {\n x: (query, page) => `https://x.com/search?q=${encodeURIComponent(query)}&f=live&page=${page}`,\n reddit: (query, page) => `https://www.reddit.com/search/?q=${encodeURIComponent(query)}&sort=relevance&t=all&page=${page}`,\n bluesky: (query, page) => `https://bsky.app/search?q=${encodeURIComponent(query)}&page=${page}`,\n facebook: (query, page) => `https://www.facebook.com/watch/search/?q=${encodeURIComponent(query)}&page=${page}`,\n linkedin: (query, page) => `https://www.linkedin.com/search/results/content/?keywords=${encodeURIComponent(query)}&page=${page}`,\n instagram: (query, page) => `https://www.instagram.com/explore/search/keyword/?q=${encodeURIComponent(query)}&page=${page}`,\n tiktok: (query, page) => `https://www.tiktok.com/search?q=${encodeURIComponent(query)}&page=${page}`,\n threads: (query, page) => `https://www.threads.net/search?q=${encodeURIComponent(query)}&page=${page}`,\n youtube: (query, page) => `https://www.youtube.com/results?search_query=${encodeURIComponent(query)}&page=${page}`\n};\n\ntype RuntimeFetchSource = ProviderSource;\n\ntype RuntimeFetchedDocument = {\n url: string;\n status: number;\n html: string;\n text: string;\n links: string[];\n browserFallback?: BrowserFallbackObservation;\n};\n\ntype CompletedFallbackOwnerReviewInput = {\n providerId: string;\n source: ProviderSource;\n operation: \"search\" | \"fetch\";\n url: string;\n html: string;\n extracted: ReturnType<typeof extractStructuredContent>;\n};\n\ntype CompletedFallbackOwnerReviewPredicate = (input: CompletedFallbackOwnerReviewInput) => boolean;\n\nconst FALLBACK_SHELL_LINK_SEGMENTS = new Set([\n \"account\",\n \"auth\",\n \"about\",\n \"cart\",\n \"categories\",\n \"category\",\n \"collections\",\n \"contact\",\n \"explore\",\n \"help\",\n \"home\",\n \"legal\",\n \"login\",\n \"policies\",\n \"product\",\n \"products\",\n \"privacy\",\n \"search\",\n \"settings\",\n \"shop\",\n \"signin\",\n \"sign-in\",\n \"sitemap\",\n \"store\",\n \"submit\",\n \"support\",\n \"terms\"\n]);\nconst FALLBACK_SHELL_TEXT_TOKENS = new Set([\n \"account\",\n \"ad\",\n \"ads\",\n \"about\",\n \"cart\",\n \"contact\",\n \"explore\",\n \"help\",\n \"home\",\n \"in\",\n \"legal\",\n \"log\",\n \"login\",\n \"policies\",\n \"product\",\n \"products\",\n \"privacy\",\n \"search\",\n \"settings\",\n \"sign\",\n \"signin\",\n \"submit\",\n \"support\",\n \"terms\"\n]);\n\nconst FALLBACK_HEAD_RE = /<head\\b[^>]*>[\\s\\S]*?<\\/head>/i;\nconst FALLBACK_BODY_RE = /<body\\b[^>]*>([\\s\\S]*?)<\\/body>/i;\nconst FALLBACK_MIN_MEANINGFUL_TEXT_CHARS = 20;\nconst FALLBACK_MIN_MEANINGFUL_TOKENS = 3;\nconst FALLBACK_SHELL_PHRASES_RE = /\\b(?:search results?|please enable javascript|enable javascript|continue|welcome|accept cookies?|privacy policy|terms of service)\\b/i;\n\nconst extractFallbackBodyHtml = (html: string): string => {\n const body = FALLBACK_BODY_RE.exec(html)?.[1];\n return body ?? html.replace(FALLBACK_HEAD_RE, \" \");\n};\n\nconst extractFallbackBodyText = (html: string): string => {\n return extractText(extractFallbackBodyHtml(html));\n};\n\nconst hasUsableFallbackText = (html: string): boolean => {\n const text = extractFallbackBodyText(html);\n const blocker = classifyBlockerSignal({\n source: \"runtime_fetch\",\n message: text,\n status: 200,\n providerErrorCode: \"unavailable\",\n retryable: true\n });\n if (blocker && blocker.type !== \"unknown\") return false;\n if (text.length < FALLBACK_MIN_MEANINGFUL_TEXT_CHARS || FALLBACK_SHELL_PHRASES_RE.test(text)) {\n return false;\n }\n const tokens = text.toLowerCase().match(/[a-z0-9]+/g) ?? [];\n const meaningfulTokens = tokens.filter((token) => !FALLBACK_SHELL_TEXT_TOKENS.has(token));\n return meaningfulTokens.length >= FALLBACK_MIN_MEANINGFUL_TOKENS;\n};\n\nconst isUsableFallbackLink = (link: string, documentUrl: string): boolean => {\n try {\n const parsed = new URL(link);\n const source = new URL(documentUrl);\n const segments = parsed.pathname\n .toLowerCase()\n .split(\"/\")\n .filter(Boolean);\n const firstSegment = segments[0];\n if (parsed.origin === source.origin && parsed.pathname === source.pathname) {\n return false;\n }\n if (segments.length === 0 && parsed.search.length === 0) {\n return false;\n }\n return firstSegment === undefined || !FALLBACK_SHELL_LINK_SEGMENTS.has(firstSegment);\n } catch {\n return false;\n }\n};\n\nconst hasUsableFallbackBodyLink = (documentUrl: string, html: string): boolean => (\n extractStructuredContent(extractFallbackBodyHtml(html), documentUrl)\n .links\n .some((link) => isUsableFallbackLink(link, documentUrl))\n);\n\nconst hasUsableFallbackContent = (documentUrl: string, html: string): boolean => (\n hasUsableFallbackText(html)\n || hasUsableFallbackBodyLink(documentUrl, html)\n);\n\nconst isBlockedRedditFallbackLink = (link: string): boolean => {\n try {\n const hostname = new URL(link).hostname.toLowerCase();\n const isReddit = hostname === \"reddit.com\" || hostname.endsWith(\".reddit.com\");\n return isReddit && !isAllowedSocialSearchExpansionUrl(\"reddit\", link);\n } catch {\n return false;\n }\n};\n\nconst shouldOwnerReviewCommunityRedditSearchFallback: CompletedFallbackOwnerReviewPredicate = (input) => (\n input.providerId === \"community/default\"\n && input.source === \"community\"\n && input.operation === \"search\"\n && isFirstPartySocialSearchRoute(\"reddit\", input.url)\n && (\n hasUsableCommunityFallbackSearchContent(input.extracted.text)\n || (\n input.extracted.links.length > 0\n && input.extracted.links.every(isBlockedRedditFallbackLink)\n )\n )\n);\n\nconst shouldReturnCompletedFallbackForOwnerReview = (args: {\n providerId: string;\n source: ProviderSource;\n operation: \"search\" | \"fetch\";\n document: RuntimeFetchedDocument;\n ownerReview?: CompletedFallbackOwnerReviewPredicate;\n}): boolean => (\n args.document.browserFallback !== undefined\n && args.ownerReview?.({\n providerId: args.providerId,\n source: args.source,\n operation: args.operation,\n url: args.document.url,\n html: args.document.html,\n extracted: extractStructuredContent(args.document.html, args.document.url)\n }) === true\n);\n\nconst toCompletedFallbackDocument = (args: {\n providerId: string;\n source: ProviderSource;\n operation: \"search\" | \"fetch\";\n url: string;\n fallback: BrowserFallbackResponse;\n ownerReview?: CompletedFallbackOwnerReviewPredicate;\n}): RuntimeFetchedDocument => {\n const resolvedUrl = canonicalizeUrl(readFallbackString(args.fallback.output, \"url\") ?? args.url);\n const html = readFallbackString(args.fallback.output, \"html\");\n if (!html) {\n throw toCompletedFallbackOutputError({ ...args, provider: args.providerId, url: resolvedUrl, outputReason: \"missing_or_empty_html\" });\n }\n const extracted = extractStructuredContent(html, resolvedUrl);\n const reviewInput = {\n providerId: args.providerId,\n source: args.source,\n operation: args.operation,\n url: resolvedUrl,\n html,\n extracted\n };\n if (!hasUsableFallbackContent(resolvedUrl, html) && !args.ownerReview?.(reviewInput)) {\n throw toCompletedFallbackOutputError({ ...args, provider: args.providerId, url: resolvedUrl, outputReason: \"empty_extracted_content\" });\n }\n return {\n url: resolvedUrl,\n status: 200,\n html,\n text: extracted.text,\n links: extracted.links,\n browserFallback: toBrowserFallbackObservation(args.fallback)\n };\n};\n\nconst describeDefaultFetchedIssue = (document: RuntimeFetchedDocument) => {\n const extracted = extractStructuredContent(document.html, document.url);\n const title = typeof extracted.metadata.title === \"string\" ? extracted.metadata.title : undefined;\n const pageMessage = toSnippet(stripUrls(extracted.text), 1600);\n const detectedCommunityShell = document.url.includes(\"reddit.com\")\n ? detectSocialSearchShell(\"reddit\", {\n url: document.url,\n title,\n content: pageMessage,\n links: extracted.links\n })\n : null;\n const communityShell = detectedCommunityShell?.providerShell === \"social_verification_wall\"\n ? detectedCommunityShell\n : null;\n const issue = classifyProviderIssue({\n url: document.url,\n title,\n message: pageMessage,\n status: document.status,\n providerErrorCode: \"unavailable\",\n retryable: true,\n ...(communityShell ?? {})\n });\n return {\n extracted,\n pageMessage,\n issue,\n details: applyProviderIssueHint({\n status: document.status,\n url: document.url,\n ...(title ? { title } : {}),\n ...(pageMessage ? { message: pageMessage } : {}),\n ...(communityShell ? {\n providerShell: communityShell.providerShell,\n browserRequired: true\n } : {})\n }, issue)\n };\n};\n\nconst shouldRecoverDefaultFetchedIssue = (issue: ProviderIssueHint): boolean => (\n issue.reasonCode === \"challenge_detected\"\n || issue.reasonCode === \"token_required\"\n || (issue.reasonCode === \"env_limited\" && !!issue.constraint)\n);\n\nconst isUsableCommunityRedditSearchFallback = (args: {\n source: ProviderSource;\n operation: \"search\" | \"fetch\";\n document: RuntimeFetchedDocument;\n pageMessage: string;\n}): boolean => (\n args.source === \"community\"\n && args.operation === \"search\"\n && args.document.browserFallback !== undefined\n && isFirstPartySocialSearchRoute(\"reddit\", args.document.url)\n && hasUsableCommunityFallbackSearchContent(args.pageMessage)\n);\n\nconst isResearchSearchDiscoveryRun = (\n operation: \"search\" | \"fetch\",\n context: ProviderContext\n): boolean => (\n operation === \"search\" && context.suspendedIntent?.kind === \"workflow.research\"\n);\n\nconst toDefaultFetchedIssueError = (args: {\n providerId: string;\n source: ProviderSource;\n document: RuntimeFetchedDocument;\n issueDetails: ReturnType<typeof describeDefaultFetchedIssue>;\n}): ProviderRuntimeError => {\n const reasonCode = args.issueDetails.issue?.reasonCode ?? \"env_limited\";\n return new ProviderRuntimeError(\n providerErrorCodeFromReasonCode(reasonCode),\n reasonCode === \"token_required\"\n ? `Authentication required for ${args.document.url}`\n : reasonCode === \"challenge_detected\"\n ? `Detected anti-bot challenge while retrieving ${args.document.url}`\n : `Browser assistance required for ${args.document.url}`,\n {\n provider: args.providerId,\n source: args.source,\n retryable: reasonCode === \"env_limited\",\n reasonCode,\n details: {\n ...args.issueDetails.details,\n ...browserFallbackObservationDetails(args.document.browserFallback)\n }\n }\n );\n};\n\nconst resolveDefaultFallbackDocumentIfNeeded = async (args: {\n providerId: string;\n source: ProviderSource;\n operation: \"search\" | \"fetch\";\n document: RuntimeFetchedDocument;\n context: ProviderContext;\n browserFallbackPort?: BrowserFallbackPort;\n ownerReview?: CompletedFallbackOwnerReviewPredicate;\n}): Promise<{ document: RuntimeFetchedDocument } & ReturnType<typeof describeDefaultFetchedIssue>> => {\n let currentDocument = args.document;\n let described = describeDefaultFetchedIssue(currentDocument);\n const initialIssue = described.issue;\n if (!initialIssue) {\n return { document: currentDocument, ...described };\n }\n if (isUsableCommunityRedditSearchFallback({\n source: args.source,\n operation: args.operation,\n document: currentDocument,\n pageMessage: described.pageMessage\n })) {\n return { document: currentDocument, ...described, issue: null };\n }\n if (shouldReturnCompletedFallbackForOwnerReview({ ...args, document: currentDocument })) {\n return { document: currentDocument, ...described };\n }\n if (initialIssue.reasonCode === \"env_limited\" && !initialIssue.constraint) {\n return { document: currentDocument, ...described };\n }\n if (!shouldRecoverDefaultFetchedIssue(initialIssue)) {\n throw toDefaultFetchedIssueError({\n providerId: args.providerId,\n source: args.source,\n document: currentDocument,\n issueDetails: described\n });\n }\n const fallback = await resolveProviderBrowserFallback({\n browserFallbackPort: args.context.browserFallbackPort ?? args.browserFallbackPort,\n provider: args.providerId,\n source: args.source,\n operation: args.operation,\n reasonCode: initialIssue.reasonCode,\n url: currentDocument.url,\n context: args.context,\n details: described.details\n });\n if (fallback) {\n if (fallback.disposition !== \"completed\") {\n throw toProviderFallbackError({\n provider: args.providerId,\n source: args.source,\n url: currentDocument.url,\n fallback\n });\n }\n\n currentDocument = toCompletedFallbackDocument({\n providerId: args.providerId,\n source: args.source,\n operation: args.operation,\n url: currentDocument.url,\n fallback,\n ownerReview: args.ownerReview\n });\n described = describeDefaultFetchedIssue(currentDocument);\n if (isUsableCommunityRedditSearchFallback({\n source: args.source,\n operation: args.operation,\n document: currentDocument,\n pageMessage: described.pageMessage\n })) {\n return { document: currentDocument, ...described, issue: null };\n }\n if (shouldReturnCompletedFallbackForOwnerReview({ ...args, document: currentDocument })) {\n return { document: currentDocument, ...described };\n }\n if (!described.issue || (described.issue.reasonCode === \"env_limited\" && !described.issue.constraint)) {\n return { document: currentDocument, ...described };\n }\n }\n\n throw toDefaultFetchedIssueError({\n providerId: args.providerId,\n source: args.source,\n document: currentDocument,\n issueDetails: described\n });\n};\n\nconst COMMUNITY_SEARCH_LINK_SCAN_MULTIPLIER = 4;\nconst MIN_COMMUNITY_SEARCH_LINK_SCAN = 12;\n\nconst resolveCommunitySearchLinks = (\n document: RuntimeFetchedDocument,\n limit: number,\n researchContext: boolean\n): string[] => {\n const scanLimit = Math.max(limit * COMMUNITY_SEARCH_LINK_SCAN_MULTIPLIER, MIN_COMMUNITY_SEARCH_LINK_SCAN);\n const links = prioritizeSocialSearchLinks(\n \"reddit\",\n document.url,\n dedupeLinks(document.links, document.url, scanLimit)\n );\n return links\n .filter((url) => researchContext ? isLikelyResearchDestinationUrl(url) : isLikelyDocumentUrl(url))\n .filter((url) => isAllowedSocialSearchExpansionUrl(\"reddit\", url))\n .slice(0, limit);\n};\n\nconst shouldRejectBlockedCommunityFallback = (\n document: RuntimeFetchedDocument,\n links: readonly string[],\n pageMessage: string\n): boolean => (\n document.browserFallback !== undefined\n && isFirstPartySocialSearchRoute(\"reddit\", document.url)\n && links.length === 0\n && !hasUsableCommunityFallbackSearchContent(pageMessage)\n);\n\nconst COMMUNITY_FALLBACK_SEARCH_MIN_CHARS = 120;\nconst COMMUNITY_FALLBACK_SEARCH_EVIDENCE_RE = [\n /\\bshowing results for\\b/i,\n /\\bsearch for\\b/i,\n /\\banswers?\\b/i,\n /\\bsources?:\\s+/i,\n /\\br\\/[a-z0-9_]+\\b/i\n];\n\nconst hasUsableCommunityFallbackSearchContent = (pageMessage: string): boolean => {\n const trimmed = pageMessage.trim();\n if (trimmed.length < COMMUNITY_FALLBACK_SEARCH_MIN_CHARS) {\n return false;\n }\n const evidenceCount = COMMUNITY_FALLBACK_SEARCH_EVIDENCE_RE\n .filter((pattern) => pattern.test(trimmed))\n .length;\n return evidenceCount >= 2;\n};\n\nconst toCommunityFallbackSearchError = (args: {\n providerId: string;\n document: RuntimeFetchedDocument;\n pageMessage: string;\n}): ProviderRuntimeError => {\n const reasonCode = args.document.browserFallback?.reasonCode ?? \"env_limited\";\n return new ProviderRuntimeError(\n providerErrorCodeFromReasonCode(reasonCode),\n reasonCode === \"challenge_detected\"\n ? `Detected anti-bot challenge while retrieving ${args.document.url}`\n : reasonCode === \"token_required\"\n ? `Authentication required for ${args.document.url}`\n : `Browser assistance required for ${args.document.url}`,\n {\n provider: args.providerId,\n source: \"community\",\n retryable: reasonCode === \"env_limited\",\n reasonCode,\n details: {\n status: args.document.status,\n url: args.document.url,\n message: args.pageMessage,\n blockedLinks: dedupeLinks(args.document.links, args.document.url, 12),\n browserRequired: true,\n ...browserFallbackObservationDetails(args.document.browserFallback)\n }\n }\n );\n};\n\nconst shouldPreserveRecoveredSocialSearchUrl = (args: {\n platform: SocialPlatform;\n operation: \"search\" | \"fetch\";\n requestedUrl: string;\n recoveredUrl: string;\n recoveredLinks: readonly string[];\n}): boolean => {\n if (args.operation !== \"search\") {\n return false;\n }\n if (!isFirstPartySocialSearchRoute(args.platform, args.requestedUrl)) {\n return false;\n }\n if (isFirstPartySocialSearchRoute(args.platform, args.recoveredUrl)) {\n return false;\n }\n return selectUsableSocialSearchLinks(args.platform, args.requestedUrl, args.recoveredLinks).length > 0;\n};\n\nconst resolveRecoveredSocialSearchDocumentUrl = (args: {\n platform: SocialPlatform;\n operation: \"search\" | \"fetch\";\n requestedUrl: string;\n recoveredUrl: string;\n recoveredLinks: readonly string[];\n}): string => (\n shouldPreserveRecoveredSocialSearchUrl(args)\n ? args.requestedUrl\n : args.recoveredUrl\n);\n\nconst isHttpUrl = (value: string): boolean => {\n try {\n const protocol = new URL(value).protocol;\n return protocol === \"http:\" || protocol === \"https:\";\n } catch {\n return false;\n }\n};\n\nconst toPositiveInt = (value: unknown, fallback: number): number => {\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return Math.max(1, Math.floor(value));\n }\n if (typeof value === \"string\" && value.trim()) {\n const parsed = Number(value);\n if (Number.isFinite(parsed)) {\n return Math.max(1, Math.floor(parsed));\n }\n }\n return fallback;\n};\n\nconst clampBlockerThreshold = (value: number | undefined): number => {\n if (typeof value !== \"number\" || Number.isNaN(value)) return 0.7;\n if (value < 0) return 0;\n if (value > 1) return 1;\n return value;\n};\n\nconst stripUrls = (value: string): string => {\n return value.replace(/https?:\\/\\/[^\\s]+/gi, \" \").replace(/\\s+/g, \" \").trim();\n};\n\nconst unwrapDuckDuckGoRedirect = (value: string): string => {\n try {\n const parsed = new URL(value);\n if (\n /(^|\\.)duckduckgo\\.com$/i.test(parsed.hostname)\n && (parsed.pathname === \"/l\" || parsed.pathname === \"/l/\")\n ) {\n const redirect = parsed.searchParams.get(\"uddg\");\n if (redirect && isHttpUrl(redirect)) {\n return canonicalizeUrl(redirect);\n }\n }\n } catch {\n return value;\n }\n return value;\n};\n\nconst isDuckDuckGoSearchShellUrl = (value: string): boolean => {\n try {\n const parsed = new URL(value);\n const host = parsed.hostname.toLowerCase();\n const pathname = parsed.pathname.toLowerCase();\n if (!/(^|\\.)duckduckgo\\.com$/i.test(host)) {\n return false;\n }\n if (pathname === \"/l\" || pathname === \"/l/\") {\n return false;\n }\n return pathname === \"/\" || pathname === \"/html\" || pathname === \"/html/\" || pathname === \"/lite\" || pathname === \"/lite/\";\n } catch {\n return false;\n }\n};\n\nconst normalizeHttpLink = (candidate: string, baseUrl: string): string | null => {\n try {\n const resolved = new URL(candidate, baseUrl).toString();\n if (!isHttpUrl(resolved)) return null;\n return unwrapDuckDuckGoRedirect(canonicalizeUrl(resolved));\n } catch {\n return null;\n }\n};\n\nconst dedupeLinks = (links: string[], baseUrl: string, limit: number): string[] => {\n const seen = new Set<string>();\n const deduped: string[] = [];\n for (const candidate of links) {\n const normalized = normalizeHttpLink(candidate, baseUrl);\n if (!normalized || !isLikelyDocumentUrl(normalized) || seen.has(normalized)) continue;\n seen.add(normalized);\n deduped.push(normalized);\n if (deduped.length >= limit) break;\n }\n return deduped;\n};\n\nconst isUsableWebSearchResultUrl = (url: string, researchContext: boolean): boolean => (\n !isDuckDuckGoSearchShellUrl(url)\n && (researchContext ? isLikelyResearchDestinationUrl(url) : isLikelyDocumentUrl(url))\n);\n\nconst isResearchWorkflowContext = (context: ProviderContext): boolean => (\n context.suspendedIntent?.kind === \"workflow.research\"\n);\n\nconst resolveWebSearchResultLinks = (\n document: RuntimeFetchedDocument,\n limit: number,\n researchContext: boolean,\n includeDocumentUrl: boolean\n): string[] => {\n const links = dedupeLinks(document.links, document.url, limit * 2);\n const candidates = includeDocumentUrl ? [document.url, ...links] : links;\n const seen = new Set<string>();\n return candidates\n .filter((url) => {\n const keep = isUsableWebSearchResultUrl(url, researchContext) && !seen.has(url);\n if (keep) seen.add(url);\n return keep;\n })\n .slice(0, limit);\n};\n\nconst toResearchDeadEndSearchError = (args: {\n providerId: string;\n source: ProviderSource;\n document: RuntimeFetchedDocument;\n retrievalPath: string;\n}): ProviderRuntimeError => new ProviderRuntimeError(\n \"unavailable\",\n `Research search resolved only dead-end pages for ${args.document.url}`,\n {\n provider: args.providerId,\n source: args.source,\n retryable: false,\n reasonCode: \"policy_blocked\",\n details: {\n status: args.document.status,\n url: args.document.url,\n ...(args.document.browserFallback?.reasonCode ? { browserFallbackReasonCode: args.document.browserFallback.reasonCode } : {}),\n retrievalPath: args.retrievalPath,\n fallbackOutputReason: \"research_dead_end_shell\",\n ...browserFallbackObservationDetails(args.document.browserFallback)\n }\n }\n);\n\nconst RUNTIME_FALLBACK_ERROR_CODES = new Set<ProviderErrorCode>([\n \"auth\",\n \"rate_limited\",\n \"timeout\",\n \"network\",\n \"upstream\",\n \"unavailable\"\n]);\n\nconst fallbackReasonCodeForError = (error: {\n code: ProviderErrorCode;\n message: string;\n details?: Record<string, JsonValue>;\n reasonCode?: ProviderReasonCode;\n}): ProviderReasonCode | undefined => {\n if (error.reasonCode) return error.reasonCode;\n switch (error.code) {\n case \"upstream\":\n return \"ip_blocked\";\n case \"timeout\":\n case \"network\":\n case \"unavailable\":\n return \"env_limited\";\n default:\n return undefined;\n }\n};\n\nconst fetchRuntimeDocument = async (args: {\n url: string;\n provider: string;\n source: RuntimeFetchSource;\n signal?: AbortSignal;\n}): Promise<RuntimeFetchedDocument> => {\n if (!isHttpUrl(args.url)) {\n throw new ProviderRuntimeError(\"invalid_input\", \"Retrieval URL must be an HTTP(S) URL\", {\n provider: args.provider,\n source: args.source,\n retryable: false,\n details: { url: args.url }\n });\n }\n\n let response: Response;\n try {\n response = await fetch(args.url, {\n headers: RUNTIME_FETCH_HEADERS,\n redirect: \"follow\",\n signal: args.signal\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (message.toLowerCase().includes(\"abort\")) {\n throw new ProviderRuntimeError(\"timeout\", `Timed out retrieving ${args.url}`, {\n provider: args.provider,\n source: args.source,\n retryable: true,\n cause: error\n });\n }\n throw new ProviderRuntimeError(\"network\", `Failed to retrieve ${args.url}`, {\n provider: args.provider,\n source: args.source,\n retryable: true,\n cause: error\n });\n }\n\n if (response.status === 401 || response.status === 403) {\n throw new ProviderRuntimeError(\"auth\", `Authentication required for ${args.url}`, {\n provider: args.provider,\n source: args.source,\n retryable: false\n });\n }\n if (response.status === 429) {\n throw new ProviderRuntimeError(\"rate_limited\", `Rate limited while retrieving ${args.url}`, {\n provider: args.provider,\n source: args.source,\n retryable: true\n });\n }\n if (response.status >= 500) {\n throw new ProviderRuntimeError(\"upstream\", `Upstream failed while retrieving ${args.url}`, {\n provider: args.provider,\n source: args.source,\n retryable: true\n });\n }\n if (response.status >= 400) {\n throw new ProviderRuntimeError(\"unavailable\", `Retrieval failed for ${args.url}`, {\n provider: args.provider,\n source: args.source,\n retryable: false\n });\n }\n\n const resolvedUrl = canonicalizeUrl(response.url || args.url);\n const html = await readResponseTextWithAbort(response, {\n signal: args.signal,\n provider: args.provider,\n source: args.source,\n url: args.url\n });\n const extracted = extractStructuredContent(html, resolvedUrl);\n return {\n url: resolvedUrl,\n status: response.status,\n html,\n text: extracted.text,\n links: extracted.links\n };\n};\n\nconst readResponseTextWithAbort = async (\n response: Response,\n args: {\n signal?: AbortSignal;\n provider: string;\n source: RuntimeFetchSource;\n url: string;\n }\n): Promise<string> => {\n if (!args.signal) {\n return response.text();\n }\n\n const timeoutError = (cause?: unknown) => new ProviderRuntimeError(\"timeout\", `Timed out retrieving ${args.url}`, {\n provider: args.provider,\n source: args.source,\n retryable: true,\n ...(cause !== undefined ? { cause } : {})\n });\n\n if (args.signal.aborted) {\n try {\n void response.body?.cancel?.();\n } catch {\n // Best effort only.\n }\n throw timeoutError(args.signal.reason);\n }\n\n let removeAbortListener: (() => void) | undefined;\n const abortPromise = new Promise<string>((_, reject) => {\n const onAbort = () => {\n try {\n void response.body?.cancel?.();\n } catch {\n // Best effort only.\n }\n reject(timeoutError(args.signal?.reason));\n };\n args.signal?.addEventListener(\"abort\", onAbort, { once: true });\n removeAbortListener = () => args.signal?.removeEventListener(\"abort\", onAbort);\n });\n\n try {\n return await Promise.race([response.text(), abortPromise]);\n } catch (error) {\n if (args.signal.aborted) {\n throw timeoutError(error);\n }\n throw error;\n } finally {\n removeAbortListener?.();\n }\n};\n\nconst fetchRuntimeDocumentWithFallback = async (args: {\n url: string;\n provider: string;\n source: RuntimeFetchSource;\n operation: \"search\" | \"fetch\";\n signal?: AbortSignal;\n context?: ProviderContext;\n browserFallbackPort?: BrowserFallbackPort;\n recoveryHints?: ProviderRecoveryHints;\n recoverRuntimeErrors?: boolean;\n ownerReview?: CompletedFallbackOwnerReviewPredicate;\n}): Promise<RuntimeFetchedDocument> => {\n const researchSearchDiscovery = args.context !== undefined\n && isResearchSearchDiscoveryRun(args.operation, args.context);\n const fallbackPort = args.context?.browserFallbackPort ?? args.browserFallbackPort;\n const runtimePolicy = args.context?.runtimePolicy;\n const forcedBrowserTransport = runtimePolicy?.browser.forceTransport === true;\n const forcedReasonCode: ProviderReasonCode = runtimePolicy?.cookies.policy === \"required\"\n ? \"auth_required\"\n : \"env_limited\";\n if (forcedBrowserTransport) {\n const fallback = await resolveProviderBrowserFallback({\n browserFallbackPort: fallbackPort,\n provider: args.provider,\n source: args.source,\n operation: args.operation,\n reasonCode: forcedReasonCode,\n url: args.url,\n context: args.context,\n details: {\n message: \"Direct browser transport was selected for this provider run.\"\n },\n recoveryHints: args.recoveryHints\n });\n if (!fallback) {\n throw new ProviderRuntimeError(\n providerErrorCodeFromReasonCode(forcedReasonCode),\n \"Direct browser transport is required for this provider run, but no browser transport is available.\",\n {\n provider: args.provider,\n source: args.source,\n retryable: false,\n reasonCode: forcedReasonCode,\n details: {\n reasonCode: forcedReasonCode,\n browserTransportRequired: true\n }\n }\n );\n }\n if (fallback.disposition !== \"completed\") {\n throw toProviderFallbackError({\n provider: args.provider,\n source: args.source,\n url: args.url,\n fallback\n });\n }\n return toCompletedFallbackDocument({\n providerId: args.provider,\n source: args.source,\n operation: args.operation,\n url: args.url,\n fallback,\n ownerReview: args.ownerReview\n });\n }\n try {\n return await fetchRuntimeDocument({\n url: args.url,\n provider: args.provider,\n source: args.source,\n signal: args.signal\n });\n } catch (error) {\n const normalized = toProviderError(error, {\n provider: args.provider,\n source: args.source\n });\n if (args.recoverRuntimeErrors === false) {\n throw error;\n }\n if (researchSearchDiscovery) {\n throw error;\n }\n if (!fallbackPort) {\n throw error;\n }\n if (!RUNTIME_FALLBACK_ERROR_CODES.has(normalized.code)) {\n throw error;\n }\n const reasonCode = fallbackReasonCodeForError(normalized) ?? \"env_limited\";\n\n const fallback = await resolveProviderBrowserFallback({\n browserFallbackPort: fallbackPort,\n provider: args.provider,\n source: args.source,\n operation: args.operation,\n reasonCode,\n url: args.url,\n context: args.context,\n details: {\n errorCode: normalized.code,\n message: normalized.message,\n ...(normalized.details ?? {})\n },\n recoveryHints: args.recoveryHints\n });\n if (!fallback) {\n throw error;\n }\n if (fallback.disposition !== \"completed\") {\n throw toProviderFallbackError({\n provider: args.provider,\n source: args.source,\n url: args.url,\n fallback\n });\n }\n\n return toCompletedFallbackDocument({\n providerId: args.provider,\n source: args.source,\n operation: args.operation,\n url: args.url,\n fallback,\n ownerReview: args.ownerReview\n });\n }\n};\n\nexport interface RuntimeInit {\n budgets?: Partial<ProviderRuntimeBudgets>;\n providers?: ProviderAdapter[];\n tiers?: Partial<RuntimeTierConfig>;\n adaptiveConcurrency?: {\n enabled?: boolean;\n maxGlobal?: number;\n maxPerDomain?: number;\n };\n blockerDetectionThreshold?: number;\n promptInjectionGuard?: {\n enabled?: boolean;\n };\n antiBotPolicy?: Partial<AntiBotPolicyConfig>;\n transcript?: {\n modeDefault?: \"auto\" | \"web\" | \"no-auto\" | \"yt-dlp\" | \"apify\";\n strategyOrder?: Array<\n \"youtubei\"\n | \"native_caption_parse\"\n | \"ytdlp_audio_asr\"\n | \"apify\"\n | \"ytdlp_subtitle\"\n | \"optional_asr\"\n >;\n enableYtdlp?: boolean;\n enableAsr?: boolean;\n enableYtdlpAudioAsr?: boolean;\n enableApify?: boolean;\n apifyActorId?: string;\n enableBrowserFallback?: boolean;\n ytdlpTimeoutMs?: number;\n };\n cookies?: {\n policy?: ProviderCookiePolicy;\n source?: ProviderCookieSourceConfig;\n };\n challengeAutomationModeDefault?: ChallengeAutomationMode;\n browserFallbackPort?: BrowserFallbackPort;\n}\n\nexport interface RuntimeDefaults {\n web?: WebProviderOptions;\n community?: CommunityProviderOptions;\n social?: SocialProvidersOptions;\n shopping?: ShoppingProvidersOptions;\n}\n\nexport class ProviderRuntime {\n readonly registry: ProviderRegistry;\n private readonly logger = createLogger(\"provider-runtime\");\n private budgets: ProviderRuntimeBudgets;\n private globalSemaphore: Semaphore;\n private readonly scopedSemaphores = new Map<string, Semaphore>();\n private readonly tierConfig: RuntimeTierConfig;\n private readonly promptGuardEnabled: boolean;\n private readonly blockerDetectionThreshold: number;\n private readonly antiBotPolicy: AntiBotPolicyEngine;\n private readonly adaptiveConfig: Required<NonNullable<RuntimeInit[\"adaptiveConcurrency\"]>>;\n private adaptiveConcurrency: AdaptiveConcurrencyController;\n private readonly browserFallbackPort?: BrowserFallbackPort;\n private readonly runtimePolicyDefaults: {\n challengeAutomationMode: ChallengeAutomationMode;\n cookiePolicy: ProviderCookiePolicy;\n };\n\n constructor(init: RuntimeInit = {}) {\n this.registry = new ProviderRegistry();\n this.budgets = mergeBudgets(DEFAULT_PROVIDER_BUDGETS, init.budgets);\n this.globalSemaphore = new Semaphore(this.budgets.concurrency.global);\n this.tierConfig = {\n ...DEFAULT_TIER_CONFIG,\n ...(init.tiers ?? {})\n };\n this.promptGuardEnabled = init.promptInjectionGuard?.enabled ?? true;\n this.blockerDetectionThreshold = clampBlockerThreshold(init.blockerDetectionThreshold);\n this.antiBotPolicy = new AntiBotPolicyEngine(this.registry, init.antiBotPolicy);\n this.browserFallbackPort = init.browserFallbackPort;\n this.runtimePolicyDefaults = {\n challengeAutomationMode: init.challengeAutomationModeDefault ?? \"browser_with_helper\",\n cookiePolicy: init.cookies?.policy ?? \"auto\"\n };\n this.adaptiveConfig = {\n enabled: init.adaptiveConcurrency?.enabled ?? false,\n maxGlobal: Math.max(this.budgets.concurrency.global, init.adaptiveConcurrency?.maxGlobal ?? this.budgets.concurrency.global),\n maxPerDomain: Math.max(\n this.budgets.concurrency.perDomain ?? this.budgets.concurrency.perProvider,\n init.adaptiveConcurrency?.maxPerDomain ?? (this.budgets.concurrency.perDomain ?? this.budgets.concurrency.perProvider)\n )\n };\n this.adaptiveConcurrency = this.createAdaptiveConcurrencyController();\n\n for (const provider of init.providers ?? []) {\n this.register(provider);\n }\n }\n\n register(provider: ProviderAdapter): void {\n this.registry.register(provider);\n this.scopedSemaphores.set(provider.id, new Semaphore(this.budgets.concurrency.perProvider));\n }\n\n listProviders(): ProviderAdapter[] {\n return this.registry.list();\n }\n\n listCapabilities() {\n return this.registry.capabilities();\n }\n\n getHealth(providerId: string) {\n return this.registry.getHealth(providerId);\n }\n\n getAntiBotSnapshots(providerIds?: string[]): ProviderAntiBotSnapshot[] {\n const allowed = providerIds?.length ? new Set(providerIds) : null;\n return this.registry\n .listAntiBotSnapshots()\n .filter((snapshot) => !allowed || allowed.has(snapshot.providerId));\n }\n\n updateBudgets(partial: Partial<ProviderRuntimeBudgets>): ProviderRuntimeBudgets {\n this.budgets = mergeBudgets(this.budgets, partial);\n this.globalSemaphore = new Semaphore(this.budgets.concurrency.global);\n this.scopedSemaphores.clear();\n for (const provider of this.registry.list()) {\n this.scopedSemaphores.set(provider.id, new Semaphore(this.budgets.concurrency.perProvider));\n }\n this.adaptiveConcurrency = this.createAdaptiveConcurrencyController();\n return this.budgets;\n }\n\n getBudgets(): ProviderRuntimeBudgets {\n return this.budgets;\n }\n\n async search(input: ProviderCallResultByOperation[\"search\"], options: ProviderRunOptions = {}): Promise<ProviderAggregateResult> {\n return this.execute(\"search\", input, options);\n }\n\n async fetch(input: ProviderCallResultByOperation[\"fetch\"], options: ProviderRunOptions = {}): Promise<ProviderAggregateResult> {\n return this.execute(\"fetch\", input, options);\n }\n\n async crawl(input: ProviderCallResultByOperation[\"crawl\"], options: ProviderRunOptions = {}): Promise<ProviderAggregateResult> {\n return this.execute(\"crawl\", input, options);\n }\n\n async post(input: ProviderCallResultByOperation[\"post\"], options: ProviderRunOptions = {}): Promise<ProviderAggregateResult> {\n return this.execute(\"post\", input, options);\n }\n\n async resumeChallengeIntent(\n challenge: SessionChallengeSummary,\n options: ProviderRunOptions = {}\n ): Promise<SuspendedIntentResumeResult> {\n if (challenge.resumeMode !== \"auto\") {\n throw new ProviderRuntimeError(\"policy_blocked\", \"Challenge resume is manual for this owner.\", {\n retryable: false,\n reasonCode: challenge.reasonCode\n });\n }\n if (challenge.status !== \"resolved\") {\n throw new ProviderRuntimeError(\"policy_blocked\", \"Challenge must be resolved before resume.\", {\n retryable: false,\n reasonCode: challenge.reasonCode\n });\n }\n if (!challenge.suspendedIntent) {\n throw new ProviderRuntimeError(\"invalid_input\", \"Challenge is missing suspended intent metadata.\", {\n retryable: false,\n reasonCode: challenge.reasonCode\n });\n }\n return this.resumeSuspendedIntent(challenge.suspendedIntent, options);\n }\n\n async execute<Operation extends ProviderOperation>(\n operation: Operation,\n input: ProviderCallResultByOperation[Operation],\n options: ProviderRunOptions = {}\n ): Promise<ProviderAggregateResult> {\n const startedAt = Date.now();\n const selection = options.source ?? \"auto\";\n const trace = createTraceContext(options.trace);\n\n const selectedProviders = selectProviders(this.registry, operation, selection)\n .filter((provider) => (options.providerIds?.length ?? 0) === 0 || options.providerIds?.includes(provider.id));\n const challengePressure = options.tier?.challengePressure ?? this.calculateChallengePressure(selectedProviders);\n const tierRoute = selectTierRoute(this.tierConfig, {\n hybridEligible: this.isHybridEligible(selectedProviders),\n preferredTier: options.tier?.preferred,\n forceRestrictedSafe: options.tier?.forceRestrictedSafe,\n challengePressure,\n highFrictionTarget: options.tier?.highFrictionTarget,\n riskScore: options.tier?.riskScore ?? this.calculateRiskScore(selectedProviders, challengePressure),\n hybridHealthy: options.tier?.hybridHealthy ?? this.isHybridHealthy(selectedProviders),\n policyRestrictedSafe: options.tier?.policyRestrictedSafe ?? false,\n latencyBudgetExceeded: options.tier?.latencyBudgetExceeded ?? this.isLatencyBudgetExceeded(selectedProviders, operation),\n errorBudgetExceeded: options.tier?.errorBudgetExceeded ?? this.isErrorBudgetExceeded(selectedProviders),\n recoveryStableForMs: options.tier?.recoveryStableForMs,\n policyAllowsRecovery: options.tier?.policyAllowsRecovery\n });\n const tierMetadata = tierRoute.tier;\n\n this.logger.info(\"provider.tier.selected\", {\n requestId: trace.requestId,\n sessionId: trace.sessionId,\n data: {\n selected: tierMetadata.selected,\n reasonCode: tierMetadata.reasonCode,\n operation,\n selection\n }\n });\n\n if (selectedProviders.length === 0) {\n const meta = createExecutionMetadata({\n tier: tierMetadata,\n provider: \"runtime\",\n retrievalPath: `${operation}:${selection}:unavailable`\n });\n const failure = normalizeFailure(\"runtime\", \"web\", new ProviderRuntimeError(\"unavailable\", \"No providers available\", {\n retryable: false,\n details: {\n operation,\n selection\n }\n }), {\n trace,\n startedAtMs: startedAt,\n meta\n });\n\n return {\n ok: false,\n records: [],\n trace: failure.trace,\n partial: false,\n failures: [{ provider: failure.provider, source: failure.source, error: failure.error }],\n metrics: {\n attempted: 0,\n succeeded: 0,\n failed: 1,\n retries: 0,\n latencyMs: failure.latencyMs\n },\n sourceSelection: selection,\n providerOrder: [],\n meta,\n diagnostics: this.buildDiagnostics({\n enabled: false,\n scope: \"runtime\",\n global: { limit: this.budgets.concurrency.global, min: 1, max: this.budgets.concurrency.global },\n scoped: { limit: this.budgets.concurrency.perProvider, min: 1, max: this.budgets.concurrency.perProvider }\n }, { enabled: this.promptGuardEnabled, quarantinedSegments: 0, entries: 0 }, []),\n error: failure.error\n };\n }\n\n const timeout = options.timeoutMs ?? this.budgets.timeoutMs[operation];\n if (selection === \"all\") {\n return this.executeAll(\n selectedProviders,\n operation,\n input,\n trace,\n timeout,\n selection,\n startedAt,\n tierMetadata,\n options.providerIds,\n options\n );\n }\n\n return this.executeSequential(\n selectedProviders,\n operation,\n input,\n trace,\n timeout,\n selection,\n startedAt,\n tierMetadata,\n options.providerIds,\n options\n );\n }\n\n private async executeSequential<Operation extends ProviderOperation>(\n providers: ProviderAdapter[],\n operation: Operation,\n input: ProviderCallResultByOperation[Operation],\n trace: TraceContext,\n timeoutMs: number,\n selection: ProviderSelection,\n startedAt: number,\n tierMetadata: ProviderTierMetadata,\n providerIds?: string[],\n runOptions: ProviderRunOptions = {}\n ): Promise<ProviderAggregateResult> {\n const failures: ProviderAggregateResult[\"failures\"] = [];\n let retries = 0;\n const attemptedOrder: string[] = [];\n let diagnostics: ProviderRuntimeDiagnostics | undefined;\n let blocker: BlockerSignalV1 | undefined;\n\n for (const provider of providers) {\n attemptedOrder.push(provider.id);\n const result = await this.invokeProvider(provider, operation, input, trace, timeoutMs, tierMetadata, runOptions);\n retries += result.retries;\n diagnostics = result.diagnostics ?? diagnostics;\n blocker = result.meta?.blocker ?? blocker;\n if (result.ok) {\n return {\n ok: true,\n records: result.records,\n trace: result.trace,\n partial: failures.length > 0,\n failures,\n metrics: {\n attempted: failures.length + 1,\n succeeded: 1,\n failed: failures.length,\n retries,\n latencyMs: Math.max(0, Date.now() - startedAt)\n },\n sourceSelection: selection,\n providerOrder: providers.map((candidate) => candidate.id),\n ...(result.meta ? { meta: result.meta } : {}),\n ...(result.diagnostics ? { diagnostics: result.diagnostics } : {})\n };\n }\n failures.push({\n provider: result.provider,\n source: result.source,\n error: result.error\n });\n }\n\n if (shouldFallbackToTierA(tierMetadata.selected)) {\n const fallbackProviders = this.selectTierAProviders(operation, providerIds, attemptedOrder);\n if (fallbackProviders.length > 0) {\n this.logger.warn(\"provider.tier.transition\", {\n requestId: trace.requestId,\n sessionId: trace.sessionId,\n data: {\n previousTier: tierMetadata.selected,\n nextTier: \"A\",\n reasonCode: \"fallback_to_tier_a\"\n }\n });\n }\n\n const fallbackTier = fallbackTierMetadata();\n for (const provider of fallbackProviders) {\n attemptedOrder.push(provider.id);\n const fallback = await this.invokeProvider(provider, operation, input, trace, timeoutMs, fallbackTier, runOptions);\n retries += fallback.retries;\n diagnostics = fallback.diagnostics ?? diagnostics;\n blocker = fallback.meta?.blocker ?? blocker;\n if (fallback.ok) {\n return {\n ok: true,\n records: fallback.records,\n trace: fallback.trace,\n partial: failures.length > 0,\n failures,\n metrics: {\n attempted: failures.length + 1,\n succeeded: 1,\n failed: failures.length,\n retries,\n latencyMs: Math.max(0, Date.now() - startedAt)\n },\n sourceSelection: selection,\n providerOrder: [...providers, ...fallbackProviders].map((candidate) => candidate.id),\n ...(fallback.meta ? { meta: fallback.meta } : {}),\n ...(fallback.diagnostics ? { diagnostics: fallback.diagnostics } : {})\n };\n }\n failures.push({\n provider: fallback.provider,\n source: fallback.source,\n error: fallback.error\n });\n }\n }\n\n const error = failures.at(-1)?.error;\n const meta = failures.length > 0\n ? createExecutionMetadata({\n tier: tierMetadata,\n provider: failures.at(-1)?.provider ?? \"runtime\",\n retrievalPath: `${operation}:${selection}:failure`\n })\n : undefined;\n if (meta && blocker) {\n meta.blocker = blocker;\n }\n return {\n ok: false,\n records: [],\n trace,\n partial: false,\n failures,\n metrics: {\n attempted: failures.length,\n succeeded: 0,\n failed: failures.length,\n retries,\n latencyMs: Math.max(0, Date.now() - startedAt)\n },\n sourceSelection: selection,\n providerOrder: attemptedOrder.length > 0 ? attemptedOrder : providers.map((provider) => provider.id),\n ...(meta ? { meta } : {}),\n ...(diagnostics ? { diagnostics } : {}),\n ...(error ? { error } : {})\n };\n }\n\n private async executeAll<Operation extends ProviderOperation>(\n providers: ProviderAdapter[],\n operation: Operation,\n input: ProviderCallResultByOperation[Operation],\n trace: TraceContext,\n timeoutMs: number,\n selection: ProviderSelection,\n startedAt: number,\n tierMetadata: ProviderTierMetadata,\n providerIds?: string[],\n runOptions: ProviderRunOptions = {}\n ): Promise<ProviderAggregateResult> {\n const results = await this.mapProvidersBounded(\n providers,\n (provider) => this.invokeProvider(provider, operation, input, trace, timeoutMs, tierMetadata, runOptions)\n );\n\n const records: NormalizedRecord[] = [];\n const failures: ProviderAggregateResult[\"failures\"] = [];\n let retries = 0;\n let attempted = results.length;\n let meta: ProviderExecutionMetadata | undefined;\n let diagnostics: ProviderRuntimeDiagnostics | undefined;\n let fallbackProviderIds: string[] = [];\n let blocker: BlockerSignalV1 | undefined;\n\n for (const result of results) {\n retries += result.retries;\n if (result.ok) {\n records.push(...result.records);\n meta = result.meta ?? meta;\n blocker = result.meta?.blocker ?? blocker;\n diagnostics = result.diagnostics ?? diagnostics;\n continue;\n }\n failures.push({\n provider: result.provider,\n source: result.source,\n error: result.error\n });\n diagnostics = result.diagnostics ?? diagnostics;\n meta = result.meta ?? meta;\n blocker = result.meta?.blocker ?? blocker;\n }\n\n if (records.length === 0 && shouldFallbackToTierA(tierMetadata.selected)) {\n const fallbackTier = fallbackTierMetadata();\n const fallbackProviders = this.selectTierAProviders(operation, providerIds, providers.map((provider) => provider.id));\n fallbackProviderIds = fallbackProviders.map((provider) => provider.id);\n if (fallbackProviders.length > 0) {\n this.logger.warn(\"provider.tier.transition\", {\n requestId: trace.requestId,\n sessionId: trace.sessionId,\n data: {\n previousTier: tierMetadata.selected,\n nextTier: \"A\",\n reasonCode: \"fallback_to_tier_a\"\n }\n });\n }\n\n const fallbackResults = await this.mapProvidersBounded(\n fallbackProviders,\n (provider) => this.invokeProvider(provider, operation, input, trace, timeoutMs, fallbackTier, runOptions)\n );\n\n for (const result of fallbackResults) {\n attempted += 1;\n retries += result.retries;\n diagnostics = result.diagnostics ?? diagnostics;\n meta = result.meta ?? meta;\n blocker = result.meta?.blocker ?? blocker;\n if (result.ok) {\n records.push(...result.records);\n continue;\n }\n failures.push({\n provider: result.provider,\n source: result.source,\n error: result.error\n });\n }\n }\n\n const ok = records.length > 0;\n const attemptedProviders = [\n ...providers.map((provider) => provider.id),\n ...fallbackProviderIds\n ];\n if (meta && blocker) {\n meta.blocker = blocker;\n }\n return {\n ok,\n records,\n trace,\n partial: ok && failures.length > 0,\n failures,\n metrics: {\n attempted,\n succeeded: attempted - failures.length,\n failed: failures.length,\n retries,\n latencyMs: Math.max(0, Date.now() - startedAt)\n },\n sourceSelection: selection,\n providerOrder: attemptedProviders,\n ...(meta ? { meta } : {}),\n ...(diagnostics ? { diagnostics } : {}),\n ...(!ok && failures[0] ? { error: failures[0].error } : {})\n };\n }\n\n private async mapProvidersBounded<T>(\n providers: ProviderAdapter[],\n task: (provider: ProviderAdapter) => Promise<T>\n ): Promise<T[]> {\n return mapBounded(providers, this.budgets.concurrency.global, task);\n }\n\n private async invokeProvider<Operation extends ProviderOperation>(\n provider: ProviderAdapter,\n operation: Operation,\n input: ProviderCallResultByOperation[Operation],\n trace: TraceContext,\n timeoutMs: number,\n tierMetadata: ProviderTierMetadata,\n runOptions: ProviderRunOptions\n ): Promise<ProviderOperationResult> {\n const startedAt = Date.now();\n const scopeKey = this.resolveScopeKey(provider.id, operation, input);\n const initialAdaptive = this.adaptiveConcurrency.snapshot(scopeKey);\n\n if (this.registry.isCircuitOpen(provider.id)) {\n const failure = normalizeFailure(provider.id, provider.source, this.registry.getCircuitError(provider.id), {\n trace,\n startedAtMs: startedAt,\n attempts: 1,\n retries: 0,\n meta: createExecutionMetadata({\n tier: tierMetadata,\n provider: provider.id,\n retrievalPath: `${operation}:${scopeKey}:circuit_open`\n })\n });\n failure.diagnostics = this.buildDiagnostics(initialAdaptive, {\n enabled: this.promptGuardEnabled,\n quarantinedSegments: 0,\n entries: 0\n }, []);\n return failure;\n }\n\n const retries = isReadOperation(operation)\n ? this.budgets.retries.read\n : this.budgets.retries.write;\n const maxAttempts = Math.max(1, retries + 1);\n const preparedInput = this.applyAdaptiveOperationInput(provider, operation, input, initialAdaptive);\n\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n try {\n const preflight = this.antiBotPolicy.preflight({\n providerId: provider.id,\n operation\n });\n if (!preflight.allow) {\n const reasonCode = preflight.reasonCode ?? \"cooldown_active\";\n throw new ProviderRuntimeError(\n providerErrorCodeFromReasonCode(reasonCode),\n `Provider execution paused by anti-bot policy for ${provider.id}`,\n {\n provider: provider.id,\n source: provider.source,\n retryable: false,\n reasonCode,\n details: {\n reasonCode,\n ...(typeof preflight.retryAfterMs === \"number\" ? { retryAfterMs: preflight.retryAfterMs } : {}),\n ...(preflight.retryGuidance ? { retryGuidance: preflight.retryGuidance } : {}),\n ...(preflight.proxyHint ? { proxyHint: preflight.proxyHint } : {}),\n ...(preflight.sessionHint ? { sessionHint: preflight.sessionHint } : {})\n }\n }\n );\n }\n\n const records = await this.withProviderConcurrency(provider.id, scopeKey, async () => {\n return this.withTimeout(timeoutMs, async (signal) => {\n const recoveryHints = provider.recoveryHints?.();\n const runtimePolicy = resolveProviderRuntimePolicy({\n source: provider.source,\n runtimePolicy: runOptions.runtimePolicy,\n preferredFallbackModes: runOptions.preferredFallbackModes,\n forceBrowserTransport: runOptions.forceBrowserTransport,\n useCookies: runOptions.useCookies,\n cookiePolicyOverride: runOptions.cookiePolicyOverride,\n challengeAutomationMode: runOptions.challengeAutomationMode,\n configChallengeAutomationMode: this.runtimePolicyDefaults.challengeAutomationMode,\n configCookiePolicy: this.runtimePolicyDefaults.cookiePolicy,\n recoveryHints\n });\n const context: ProviderContext = {\n trace: createTraceContext(trace, provider.id),\n timeoutMs,\n attempt,\n signal,\n runtimePolicy,\n suspendedIntent: this.buildSuspendedIntent(provider.id, provider.source, operation, input, runOptions),\n ...(this.browserFallbackPort\n ? { browserFallbackPort: this.browserFallbackPort }\n : {})\n };\n return this.callOperation(provider, operation, preparedInput, context);\n });\n });\n const guarded = applyPromptGuard(records, this.promptGuardEnabled);\n if (guarded.audit.entries.length > 0) {\n this.logger.audit(\"provider.prompt_guard\", {\n requestId: trace.requestId,\n sessionId: trace.sessionId,\n data: {\n provider: provider.id,\n operation,\n entries: guarded.audit.entries.length,\n quarantinedSegments: guarded.audit.quarantinedSegments\n }\n });\n }\n const realismPatterns = this.detectRealismViolations(guarded.records);\n if (realismPatterns.length > 0) {\n this.logger.warn(\"provider.realism.violation\", {\n requestId: trace.requestId,\n sessionId: trace.sessionId,\n data: {\n provider: provider.id,\n operation,\n patterns: realismPatterns\n }\n });\n }\n\n const meta = createExecutionMetadata({\n tier: tierMetadata,\n provider: provider.id,\n retrievalPath: `${operation}:${scopeKey}`\n });\n\n const success = normalizeSuccess(provider.id, provider.source, guarded.records, {\n trace,\n startedAtMs: startedAt,\n attempts: attempt,\n retries: attempt - 1,\n meta,\n provenance: {\n provider: provider.id,\n source: provider.source,\n operation,\n retrievalPath: meta.provenance.retrievalPath,\n retrievedAt: meta.provenance.retrievedAt\n }\n });\n this.adaptiveConcurrency.observe(scopeKey, {\n latencyMs: success.latencyMs,\n queuePressure: this.queuePressure(scopeKey)\n });\n const adaptive = this.adaptiveConcurrency.snapshot(scopeKey);\n success.diagnostics = this.buildDiagnostics(adaptive, {\n enabled: guarded.audit.enabled,\n quarantinedSegments: guarded.audit.quarantinedSegments,\n entries: guarded.audit.entries.length\n }, realismPatterns);\n if (operation === \"post\") {\n this.logger.audit(\"provider.post\", {\n requestId: trace.requestId,\n sessionId: trace.sessionId,\n data: {\n provider: provider.id,\n source: provider.source,\n operation,\n decision: \"allow\",\n recordCount: success.records.length,\n payloadHashes: success.records\n .map((record) => record.attributes?.auditHash)\n .filter((hash): hash is string => typeof hash === \"string\")\n }\n });\n }\n this.registry.markSuccess(provider.id, success.latencyMs);\n this.antiBotPolicy.postflight({\n providerId: provider.id,\n operation,\n success: true,\n retryable: false,\n attempt,\n maxAttempts\n });\n this.recordAntiBotOutcome({\n providerId: provider.id,\n success: true\n });\n return success;\n } catch (error) {\n let normalizedError = toProviderError(error, {\n provider: provider.id,\n source: provider.source\n });\n const reasonCode = normalizedError.reasonCode;\n this.adaptiveConcurrency.observe(scopeKey, {\n latencyMs: Math.max(0, Date.now() - startedAt),\n timeout: normalizedError.code === \"timeout\",\n challenge: this.isChallengeError(normalizedError.message),\n http4xx: this.isClientError(normalizedError.code, normalizedError.message),\n http5xx: this.isServerError(normalizedError.code, normalizedError.message),\n queuePressure: this.queuePressure(scopeKey)\n });\n this.registry.markFailure(provider.id, normalizedError, this.budgets.circuitBreaker);\n\n const postflight = this.antiBotPolicy.postflight({\n providerId: provider.id,\n operation,\n success: false,\n reasonCode,\n retryable: normalizedError.retryable,\n attempt,\n maxAttempts\n });\n this.recordAntiBotOutcome({\n providerId: provider.id,\n error: normalizedError\n });\n if (attempt < maxAttempts && postflight.allowRetry) {\n continue;\n }\n\n const meta = createExecutionMetadata({\n tier: tierMetadata,\n provider: provider.id,\n retrievalPath: `${operation}:${scopeKey}:failure`\n });\n const blocker = this.detectRuntimeBlocker({\n operation,\n code: normalizedError.code,\n message: normalizedError.message,\n details: normalizedError.details,\n retryable: normalizedError.retryable,\n trace\n });\n if (blocker) {\n meta.blocker = blocker;\n }\n const failure = normalizeFailure(provider.id, provider.source, normalizedError, {\n trace,\n startedAtMs: startedAt,\n attempts: attempt,\n retries: attempt - 1,\n meta\n });\n failure.diagnostics = this.buildDiagnostics(this.adaptiveConcurrency.snapshot(scopeKey), {\n enabled: this.promptGuardEnabled,\n quarantinedSegments: 0,\n entries: 0\n }, []);\n if (operation === \"post\") {\n this.logger.audit(\"provider.post\", {\n requestId: trace.requestId,\n sessionId: trace.sessionId,\n data: {\n provider: provider.id,\n source: provider.source,\n operation,\n decision: \"deny\",\n error: failure.error.code\n }\n });\n }\n return failure;\n }\n }\n\n const exhausted = normalizeFailure(provider.id, provider.source, new ProviderRuntimeError(\"internal\", \"Provider invocation exhausted attempts\", {\n provider: provider.id,\n source: provider.source\n }), {\n trace,\n startedAtMs: startedAt,\n attempts: maxAttempts,\n retries: Math.max(0, maxAttempts - 1),\n meta: createExecutionMetadata({\n tier: tierMetadata,\n provider: provider.id,\n retrievalPath: `${operation}:${scopeKey}:exhausted`\n })\n });\n exhausted.diagnostics = this.buildDiagnostics(this.adaptiveConcurrency.snapshot(scopeKey), {\n enabled: this.promptGuardEnabled,\n quarantinedSegments: 0,\n entries: 0\n }, []);\n return exhausted;\n }\n\n private async callOperation<Operation extends ProviderOperation>(\n provider: ProviderAdapter,\n operation: Operation,\n input: ProviderCallResultByOperation[Operation],\n context: ProviderContext\n ): Promise<NormalizedRecord[]> {\n switch (operation) {\n case \"search\":\n if (!provider.search) {\n throw new ProviderRuntimeError(\"not_supported\", \"Search operation is not supported\", {\n provider: provider.id,\n source: provider.source,\n retryable: false\n });\n }\n return provider.search(input as ProviderCallResultByOperation[\"search\"], context);\n case \"fetch\":\n if (!provider.fetch) {\n throw new ProviderRuntimeError(\"not_supported\", \"Fetch operation is not supported\", {\n provider: provider.id,\n source: provider.source,\n retryable: false\n });\n }\n return provider.fetch(input as ProviderCallResultByOperation[\"fetch\"], context);\n case \"crawl\":\n if (!provider.crawl) {\n throw new ProviderRuntimeError(\"not_supported\", \"Crawl operation is not supported\", {\n provider: provider.id,\n source: provider.source,\n retryable: false\n });\n }\n return provider.crawl(input as ProviderCallResultByOperation[\"crawl\"], context);\n case \"post\":\n if (!provider.post) {\n throw new ProviderRuntimeError(\"not_supported\", \"Post operation is not supported\", {\n provider: provider.id,\n source: provider.source,\n retryable: false\n });\n }\n return provider.post(input as ProviderCallResultByOperation[\"post\"], context);\n }\n }\n\n private async withProviderConcurrency<T>(providerId: string, scopeKey: string, task: () => Promise<T>): Promise<T> {\n const adaptive = this.adaptiveConcurrency.snapshot(scopeKey);\n this.globalSemaphore.setLimit(adaptive.global.limit);\n const scopedSemaphore = this.scopedSemaphores.get(scopeKey)\n ?? this.scopedSemaphores.get(providerId)\n ?? new Semaphore(adaptive.scoped.limit);\n scopedSemaphore.setLimit(adaptive.scoped.limit);\n this.scopedSemaphores.set(scopeKey, scopedSemaphore);\n\n return this.globalSemaphore.use(async () => scopedSemaphore.use(task));\n }\n\n private createAdaptiveConcurrencyController(): AdaptiveConcurrencyController {\n return new AdaptiveConcurrencyController({\n enabled: this.adaptiveConfig.enabled,\n baselineGlobal: this.budgets.concurrency.global,\n baselineScoped: this.budgets.concurrency.perDomain ?? this.budgets.concurrency.perProvider,\n maxGlobal: this.adaptiveConfig.maxGlobal,\n maxScoped: this.adaptiveConfig.maxPerDomain\n });\n }\n\n private selectTierAProviders(\n operation: ProviderOperation,\n providerIds: string[] | undefined,\n excludeProviderIds: string[] = []\n ): ProviderAdapter[] {\n return selectProviders(this.registry, operation, \"web\")\n .filter((provider) => !excludeProviderIds.includes(provider.id))\n .filter((provider) => (providerIds?.length ?? 0) === 0 || providerIds?.includes(provider.id));\n }\n\n private calculateChallengePressure(providers: ProviderAdapter[]): number {\n if (providers.length === 0) return 0;\n let total = 0;\n for (const provider of providers) {\n total += this.registry.getAntiBotPressure(provider.id);\n }\n return total / providers.length;\n }\n\n private calculateRiskScore(providers: ProviderAdapter[], challengePressure: number): number {\n if (providers.length === 0) return Math.max(0, Math.min(1, challengePressure));\n let unhealthy = 0;\n let degraded = 0;\n for (const provider of providers) {\n const health = this.registry.getHealth(provider.id);\n if (health.status === \"unhealthy\") unhealthy += 1;\n else if (health.status === \"degraded\") degraded += 1;\n }\n const healthPressure = (unhealthy + degraded * 0.5) / providers.length;\n return Math.max(0, Math.min(1, Math.max(challengePressure, healthPressure)));\n }\n\n private isHybridHealthy(providers: ProviderAdapter[]): boolean {\n const hybridProviders = providers.filter((provider) => provider.source !== \"web\");\n if (hybridProviders.length === 0) return false;\n return hybridProviders.some((provider) => {\n const health = this.registry.getHealth(provider.id);\n return health.status !== \"unhealthy\" && !this.registry.isCircuitOpen(provider.id);\n });\n }\n\n private isLatencyBudgetExceeded(\n providers: ProviderAdapter[],\n operation: ProviderOperation\n ): boolean {\n const timeoutBudget = this.budgets.timeoutMs[operation];\n return providers.some((provider) => {\n if (provider.source === \"web\") return false;\n const latency = this.registry.getHealth(provider.id).latencyMs;\n return typeof latency === \"number\" && latency > timeoutBudget;\n });\n }\n\n private isErrorBudgetExceeded(providers: ProviderAdapter[]): boolean {\n if (providers.length === 0) return false;\n let violations = 0;\n for (const provider of providers) {\n const status = this.registry.getHealth(provider.id).status;\n if (status === \"unhealthy\") {\n violations += 1;\n }\n }\n return violations / providers.length >= 0.5;\n }\n\n private buildSuspendedIntent<Operation extends ProviderOperation>(\n providerId: string,\n source: ProviderSource,\n operation: Operation,\n input: ProviderCallResultByOperation[Operation],\n options: ProviderRunOptions\n ): SuspendedIntentSummary {\n const baseInput = input as unknown as SuspendedIntentSummary[\"input\"];\n const existing = options.suspendedIntent;\n if (existing) {\n return typeof existing.input === \"undefined\" && typeof baseInput !== \"undefined\"\n ? {\n ...existing,\n input: baseInput\n }\n : existing;\n }\n return {\n kind: DEFAULT_PROVIDER_SUSPENDED_INTENT_KIND[operation],\n provider: providerId,\n source,\n operation,\n input: baseInput\n };\n }\n\n private async resumeSuspendedIntent(\n intent: SuspendedIntentSummary,\n options: ProviderRunOptions\n ): Promise<SuspendedIntentResumeResult> {\n const input = intent.input;\n if (!isJsonRecord(input)) {\n throw new ProviderRuntimeError(\"invalid_input\", \"Suspended intent input is missing or malformed.\", {\n retryable: false\n });\n }\n switch (intent.kind) {\n case \"provider.search\":\n return this.search(input as unknown as ProviderCallResultByOperation[\"search\"], {\n ...options,\n source: intent.source ?? options.source ?? \"auto\",\n providerIds: intent.provider ? [intent.provider] : options.providerIds\n });\n case \"provider.fetch\":\n return this.fetch(input as unknown as ProviderCallResultByOperation[\"fetch\"], {\n ...options,\n source: intent.source ?? options.source ?? \"auto\",\n providerIds: intent.provider ? [intent.provider] : options.providerIds\n });\n case \"provider.crawl\":\n return this.crawl(input as unknown as ProviderCallResultByOperation[\"crawl\"], {\n ...options,\n source: intent.source ?? options.source ?? \"auto\",\n providerIds: intent.provider ? [intent.provider] : options.providerIds\n });\n case \"provider.post\":\n return this.post(input as unknown as ProviderCallResultByOperation[\"post\"], {\n ...options,\n source: intent.source ?? options.source ?? \"auto\",\n providerIds: intent.provider ? [intent.provider] : options.providerIds\n });\n case \"workflow.research\":\n return runResearchWorkflow(\n this,\n unwrapWorkflowResumeEnvelope(\n WORKFLOW_KIND_BY_SUSPENDED_INTENT_KIND[intent.kind],\n input\n )\n );\n case \"workflow.shopping\":\n return runShoppingWorkflow(\n this,\n unwrapWorkflowResumeEnvelope(\n WORKFLOW_KIND_BY_SUSPENDED_INTENT_KIND[intent.kind],\n input\n )\n );\n case \"workflow.inspiredesign\":\n return runInspiredesignWorkflow(\n this,\n unwrapWorkflowResumeEnvelope(\n WORKFLOW_KIND_BY_SUSPENDED_INTENT_KIND[intent.kind],\n input\n )\n );\n case \"workflow.product_video\":\n return runProductVideoWorkflow(\n this,\n unwrapWorkflowResumeEnvelope(\n WORKFLOW_KIND_BY_SUSPENDED_INTENT_KIND[intent.kind],\n input\n )\n );\n case \"youtube.transcript\":\n return this.fetch(input as unknown as ProviderCallResultByOperation[\"fetch\"], {\n ...options,\n source: intent.source ?? options.source ?? \"social\",\n providerIds: intent.provider ? [intent.provider] : options.providerIds\n });\n default:\n throw new ProviderRuntimeError(\"not_supported\", `Unsupported suspended intent: ${intent.kind}`, {\n retryable: false\n });\n }\n }\n\n private recordAntiBotOutcome(args: {\n providerId: string;\n success?: boolean;\n error?: {\n reasonCode?: ProviderReasonCode;\n details?: Record<string, JsonValue>;\n };\n }): void {\n const dispositionValue = args.error?.details?.disposition;\n const disposition = (\n dispositionValue === \"completed\"\n || dispositionValue === \"challenge_preserved\"\n || dispositionValue === \"deferred\"\n || dispositionValue === \"failed\"\n )\n ? dispositionValue\n : undefined;\n\n this.registry.recordAntiBotOutcome({\n providerId: args.providerId,\n ...(args.success ? { success: true } : {}),\n ...(args.error?.reasonCode ? { reasonCode: args.error.reasonCode } : {}),\n ...(disposition ? { disposition } : {})\n });\n }\n\n private isHybridEligible(providers: ProviderAdapter[]): boolean {\n return providers.some((provider) => provider.source !== \"web\");\n }\n\n private resolveScopeKey<Operation extends ProviderOperation>(\n providerId: string,\n operation: Operation,\n input: ProviderCallResultByOperation[Operation]\n ): string {\n const extractHost = (value: string | undefined): string | null => {\n if (!value) return null;\n try {\n return new URL(value).hostname.toLowerCase();\n } catch {\n return null;\n }\n };\n\n if (operation === \"fetch\") {\n return extractHost((input as ProviderCallResultByOperation[\"fetch\"]).url) ?? providerId;\n }\n if (operation === \"crawl\") {\n const first = (input as ProviderCallResultByOperation[\"crawl\"]).seedUrls[0];\n return extractHost(first) ?? providerId;\n }\n if (operation === \"search\") {\n return extractHost((input as ProviderCallResultByOperation[\"search\"]).query) ?? providerId;\n }\n return providerId;\n }\n\n private queuePressure(scopeKey: string): number {\n const global = this.globalSemaphore.snapshot();\n const scoped = this.scopedSemaphores.get(scopeKey)?.snapshot();\n const globalPressure = global.limit <= 0 ? 0 : Math.min(1, (global.active + global.queued) / global.limit);\n const scopedPressure = !scoped || scoped.limit <= 0\n ? 0\n : Math.min(1, (scoped.active + scoped.queued) / scoped.limit);\n return Math.max(globalPressure, scopedPressure);\n }\n\n private detectRealismViolations(records: NormalizedRecord[]): string[] {\n const matched = new Set<string>();\n for (const record of records) {\n const haystacks = [record.url ?? \"\", record.title ?? \"\", record.content ?? \"\"];\n for (const pattern of PLACEHOLDER_PATTERNS) {\n if (haystacks.some((value) => pattern.regex.test(value))) {\n matched.add(pattern.code);\n }\n }\n }\n return [...matched];\n }\n\n private applyAdaptiveOperationInput<Operation extends ProviderOperation>(\n provider: ProviderAdapter,\n operation: Operation,\n input: ProviderCallResultByOperation[Operation],\n adaptive: AdaptiveConcurrencyDiagnostics\n ): ProviderCallResultByOperation[Operation] {\n if (!adaptive.enabled || operation !== \"crawl\" || provider.source !== \"web\") {\n return input;\n }\n\n const crawlInput = input as ProviderCallResultByOperation[\"crawl\"];\n const scopedLimit = Math.max(1, Math.floor(adaptive.scoped.limit));\n const currentMaxPerDomain = typeof crawlInput.maxPerDomain === \"number\"\n ? Math.max(1, Math.floor(crawlInput.maxPerDomain))\n : undefined;\n const currentFetchConcurrency = toPositiveInt(crawlInput.filters?.fetchConcurrency, scopedLimit);\n const nextMaxPerDomain = currentMaxPerDomain !== undefined\n ? Math.min(currentMaxPerDomain, scopedLimit)\n : scopedLimit;\n const nextFetchConcurrency = Math.min(currentFetchConcurrency, scopedLimit);\n\n if (currentMaxPerDomain === nextMaxPerDomain && currentFetchConcurrency === nextFetchConcurrency) {\n return input;\n }\n\n return {\n ...crawlInput,\n maxPerDomain: nextMaxPerDomain,\n filters: {\n ...(crawlInput.filters ?? {}),\n fetchConcurrency: nextFetchConcurrency as JsonValue\n }\n } as unknown as ProviderCallResultByOperation[Operation];\n }\n\n private isChallengeError(message: string): boolean {\n return /captcha|challenge|cf_chl|interstitial|bot/i.test(message);\n }\n\n private isClientError(code: string, message: string): boolean {\n return code === \"auth\"\n || code === \"invalid_input\"\n || code === \"policy_blocked\"\n || /\\b4\\d{2}\\b/.test(message);\n }\n\n private isServerError(code: string, message: string): boolean {\n return code === \"upstream\"\n || code === \"unavailable\"\n || /\\b5\\d{2}\\b/.test(message);\n }\n\n private buildDiagnostics(\n adaptive: AdaptiveConcurrencyDiagnostics,\n promptGuard: { enabled: boolean; quarantinedSegments: number; entries: number },\n realismPatterns: string[]\n ): ProviderRuntimeDiagnostics {\n return {\n adaptiveConcurrency: adaptive,\n promptGuard,\n realism: {\n violations: realismPatterns.length,\n patterns: realismPatterns\n }\n };\n }\n\n private detectRuntimeBlocker(params: {\n operation: ProviderOperation;\n code: string;\n message: string;\n details?: Record<string, JsonValue>;\n retryable: boolean;\n trace: TraceContext;\n }): BlockerSignalV1 | undefined {\n const details = params.details;\n const url = typeof details?.url === \"string\"\n ? details.url\n : undefined;\n const hostFromUrl = (() => {\n if (!url) return null;\n try {\n return new URL(url).hostname.toLowerCase();\n } catch {\n return null;\n }\n })();\n const status = typeof details?.status === \"number\" ? details.status : undefined;\n const normalizedReasonCode = normalizeProviderReasonCode({\n code: params.code as ProviderErrorCode,\n message: params.message,\n status,\n details\n });\n const envLimited = normalizedReasonCode === \"env_limited\"\n || (\n params.code === \"unavailable\"\n && /extension not connected|not available in this environment|manual interaction/i.test(params.message)\n );\n const blocker = classifyBlockerSignal({\n source: params.operation === \"post\" ? \"macro_execution\" : \"runtime_fetch\",\n ...(url ? { url } : {}),\n ...(status !== undefined ? { status } : {}),\n providerErrorCode: params.code,\n message: params.message,\n networkHosts: hostFromUrl ? [hostFromUrl] : undefined,\n traceRequestId: params.trace.requestId,\n retryable: params.retryable,\n envLimited,\n promptGuardEnabled: this.promptGuardEnabled,\n threshold: this.blockerDetectionThreshold\n });\n if (!blocker) return undefined;\n if (blocker.reasonCode || !normalizedReasonCode) {\n return blocker;\n }\n return {\n ...blocker,\n reasonCode: normalizedReasonCode\n };\n }\n\n private async withTimeout<T>(\n timeoutMs: number,\n task: (signal: AbortSignal) => Promise<T>\n ): Promise<T> {\n const controller = new AbortController();\n const createTimeoutError = (cause?: unknown): ProviderRuntimeError => {\n return new ProviderRuntimeError(\"timeout\", `Provider request timed out after ${timeoutMs}ms`, {\n retryable: true,\n ...(cause !== undefined ? { cause } : {})\n });\n };\n const taskPromise = Promise.resolve().then(() => task(controller.signal));\n const timeoutPromise = new Promise<never>((_, reject) => {\n const timeoutId = setTimeout(() => {\n controller.abort(\"timeout\");\n reject(createTimeoutError());\n }, timeoutMs);\n controller.signal.addEventListener(\"abort\", () => clearTimeout(timeoutId), { once: true });\n });\n\n try {\n return await Promise.race([\n taskPromise.catch((error) => {\n if (controller.signal.aborted) {\n throw createTimeoutError(error);\n }\n throw error;\n }),\n timeoutPromise\n ]);\n } catch (error) {\n if (isProviderRuntimeError(error) && error.code === \"timeout\") {\n throw error;\n }\n if (controller.signal.aborted) {\n throw createTimeoutError(error);\n }\n throw error;\n }\n }\n}\n\nexport const createProviderRuntime = (init: RuntimeInit = {}): ProviderRuntime => {\n return new ProviderRuntime(init);\n};\n\nconst withDefaultWebOptions = (\n options: WebProviderOptions | undefined,\n browserFallbackPort?: BrowserFallbackPort\n): WebProviderOptions => {\n const providerId = options?.id ?? \"web/default\";\n return {\n ...options,\n fetcher: options?.fetcher ?? (async (url: string, context?: ProviderContext) => {\n const document = await fetchRuntimeDocumentWithFallback({\n url,\n provider: providerId,\n source: \"web\",\n operation: \"fetch\",\n signal: context?.signal,\n context,\n browserFallbackPort\n });\n return {\n url: document.url,\n status: document.status,\n html: document.html\n };\n }),\n searchIndex: options?.searchIndex ?? (async (input, context) => {\n const query = input.query.trim();\n const lookupUrl = isHttpUrl(query)\n ? query\n : `https://duckduckgo.com/html/?q=${encodeURIComponent(query)}&ia=web`;\n const document = await fetchRuntimeDocumentWithFallback({\n url: lookupUrl,\n provider: providerId,\n source: \"web\",\n operation: \"search\",\n signal: context.signal,\n context,\n browserFallbackPort\n });\n\n const limit = Math.max(1, Math.min(input.limit ?? 5, 10));\n const researchContext = isResearchWorkflowContext(context);\n const links = resolveWebSearchResultLinks(document, limit, researchContext, researchContext || isHttpUrl(query));\n const searchPath = isHttpUrl(query) ? \"web:search:url\" : \"web:search:index\";\n if (links.length === 0) {\n if (researchContext && !isUsableWebSearchResultUrl(document.url, true)) {\n throw toResearchDeadEndSearchError({\n providerId,\n source: \"web\",\n document,\n retrievalPath: searchPath\n });\n }\n return [{\n url: document.url,\n title: document.url,\n content: toSnippet(stripUrls(document.text), 1500),\n confidence: isHttpUrl(query) ? 0.75 : 0.55,\n attributes: {\n query,\n status: document.status,\n retrievalPath: searchPath,\n ...browserFallbackObservationAttributes(document.browserFallback)\n }\n }];\n }\n\n return links.map((url, index) => ({\n url,\n title: url,\n ...(index === 0 ? { content: toSnippet(stripUrls(document.text), 700) } : {}),\n confidence: Math.max(0.35, 0.75 - index * 0.05),\n attributes: {\n query,\n rank: index + 1,\n status: document.status,\n retrievalPath: searchPath,\n ...browserFallbackObservationAttributes(document.browserFallback)\n }\n }));\n })\n };\n};\n\nconst withDefaultCommunityOptions = (\n options: CommunityProviderOptions | undefined,\n browserFallbackPort?: BrowserFallbackPort\n): CommunityProviderOptions => {\n const providerId = options?.id ?? \"community/default\";\n const buildSearchRows = (args: {\n query: string;\n page: number;\n document: RuntimeFetchedDocument;\n pageMessage: string;\n links: string[];\n context: ProviderContext;\n }) => {\n const searchPath = isHttpUrl(args.query) ? \"community:search:url\" : \"community:search:index\";\n const attributes = {\n query: args.query,\n page: args.page,\n status: args.document.status,\n links: args.links,\n retrievalPath: searchPath,\n ...browserFallbackObservationAttributes(args.document.browserFallback)\n };\n if (args.links.length === 0) {\n if (isResearchWorkflowContext(args.context) && !isLikelyResearchDestinationUrl(args.document.url)) {\n throw toResearchDeadEndSearchError({\n providerId,\n source: \"community\",\n document: args.document,\n retrievalPath: searchPath\n });\n }\n return [{\n url: args.document.url,\n title: isHttpUrl(args.query) ? args.document.url : `Community search: ${args.query}`,\n content: args.pageMessage,\n confidence: isHttpUrl(args.query) ? 0.75 : 0.6,\n attributes\n }];\n }\n return args.links.map((url, index) => ({\n url,\n title: url,\n confidence: Math.max(0.35, 0.75 - index * 0.05),\n attributes: { ...attributes, rank: index + 1 }\n }));\n };\n return {\n ...options,\n search: options?.search ?? (async (input, context) => {\n const query = input.query.trim();\n const page = toPositiveInt(input.filters?.page, 1);\n const limit = Math.max(1, Math.min(input.limit ?? 5, 10));\n const lookupUrl = isHttpUrl(query)\n ? query\n : `https://www.reddit.com/search/?q=${encodeURIComponent(query)}&sort=relevance&t=all&page=${page}`;\n const document = await fetchRuntimeDocumentWithFallback({\n url: lookupUrl,\n provider: providerId,\n source: \"community\",\n operation: \"search\",\n signal: context.signal,\n context,\n browserFallbackPort,\n ownerReview: shouldOwnerReviewCommunityRedditSearchFallback\n });\n const { document: resolvedDocument, pageMessage } = await resolveDefaultFallbackDocumentIfNeeded({\n providerId,\n source: \"community\",\n operation: \"search\",\n document,\n context,\n browserFallbackPort,\n ownerReview: shouldOwnerReviewCommunityRedditSearchFallback\n });\n const links = resolveCommunitySearchLinks(resolvedDocument, limit, isResearchWorkflowContext(context));\n if (shouldRejectBlockedCommunityFallback(resolvedDocument, links, pageMessage)) {\n throw toCommunityFallbackSearchError({\n providerId,\n document: resolvedDocument,\n pageMessage\n });\n }\n return buildSearchRows({\n query,\n page,\n document: resolvedDocument,\n pageMessage,\n links,\n context\n });\n }),\n fetch: options?.fetch ?? (async (input, context) => {\n const document = await fetchRuntimeDocumentWithFallback({\n url: input.url,\n provider: providerId,\n source: \"community\",\n operation: \"fetch\",\n signal: context.signal,\n context,\n browserFallbackPort\n });\n const { document: resolvedDocument } = await resolveDefaultFallbackDocumentIfNeeded({\n providerId,\n source: \"community\",\n operation: \"fetch\",\n document,\n context,\n browserFallbackPort\n });\n const links = dedupeLinks(resolvedDocument.links, resolvedDocument.url, 20);\n return {\n url: resolvedDocument.url,\n title: resolvedDocument.url,\n content: resolvedDocument.text,\n attributes: {\n status: resolvedDocument.status,\n links,\n retrievalPath: \"community:fetch:url\",\n ...browserFallbackObservationAttributes(resolvedDocument.browserFallback)\n }\n };\n })\n };\n};\n\nconst withDefaultSocialPlatformOptions = (\n platform: SocialPlatform,\n options: SocialProviderOptions | undefined,\n browserFallbackPort?: BrowserFallbackPort\n): SocialProviderOptions => {\n const providerId = options?.id ?? `social/${platform}`;\n const extensionFirstRecoveryHints = buildSocialRecoveryHints(platform, options);\n const defaultTraversal = buildSocialDefaultTraversal(platform, options);\n const describeDocumentIssue = (operation: \"search\" | \"fetch\", document: RuntimeFetchedDocument) => {\n const extracted = extractStructuredContent(document.html, document.url);\n const title = typeof extracted.metadata.title === \"string\" ? extracted.metadata.title : undefined;\n const pageMessage = toSnippet(stripUrls(extracted.text), 1600);\n const shell = operation === \"search\"\n ? detectSocialSearchShell(platform, {\n url: document.url,\n title,\n content: pageMessage,\n links: extracted.links\n })\n : null;\n const usableSearchLinks = operation === \"search\"\n ? selectUsableSocialSearchLinks(platform, document.url, extracted.links)\n : [];\n const hasUsableSearchEvidence = operation === \"search\"\n && isFirstPartySocialSearchRoute(platform, document.url)\n && usableSearchLinks.length > 0;\n const issue = hasUsableSearchEvidence && !shell\n ? null\n : classifyProviderIssue({\n url: document.url,\n title,\n message: pageMessage,\n status: document.status,\n providerErrorCode: \"unavailable\",\n retryable: true,\n ...(shell ?? {})\n });\n return {\n extracted,\n title,\n pageMessage,\n usableSearchLinks,\n issue,\n details: applyProviderIssueHint({\n status: document.status,\n url: document.url,\n ...(title ? { title } : {}),\n ...(pageMessage ? { message: pageMessage } : {}),\n ...(shell ? {\n providerShell: shell.providerShell,\n browserRequired: true,\n platform\n } : {})\n }, issue)\n };\n };\n const toIssueError = (document: RuntimeFetchedDocument, issueDetails: ReturnType<typeof describeDocumentIssue>) => {\n const reasonCode = issueDetails.issue?.reasonCode ?? \"env_limited\";\n return new ProviderRuntimeError(\n providerErrorCodeFromReasonCode(reasonCode),\n reasonCode === \"token_required\"\n ? `Authentication required for ${document.url}`\n : reasonCode === \"challenge_detected\"\n ? `Detected anti-bot challenge while retrieving ${document.url}`\n : `Browser assistance required for ${document.url}`,\n {\n provider: providerId,\n source: \"social\",\n retryable: reasonCode === \"env_limited\",\n reasonCode,\n details: {\n ...issueDetails.details,\n ...browserFallbackObservationDetails(document.browserFallback)\n }\n }\n );\n };\n const shouldOwnerReviewSocialFallback: CompletedFallbackOwnerReviewPredicate = (input) => (\n input.source === \"social\"\n && input.operation === \"search\"\n && detectSocialSearchShell(platform, {\n url: input.url,\n title: typeof input.extracted.metadata.title === \"string\" ? input.extracted.metadata.title : undefined,\n content: toSnippet(stripUrls(input.extracted.text), 1600),\n links: input.extracted.links\n })?.browserRequired === true\n );\n const resolveFallbackDocumentIfNeeded = async (\n operation: \"search\" | \"fetch\",\n document: RuntimeFetchedDocument,\n context: ProviderContext\n ): Promise<{ document: RuntimeFetchedDocument } & ReturnType<typeof describeDocumentIssue>> => {\n let currentDocument = document;\n let described = describeDocumentIssue(operation, currentDocument);\n const initialIssue = described.issue;\n if (!initialIssue) {\n return { document: currentDocument, ...described };\n }\n if (initialIssue.reasonCode === \"env_limited\" && !initialIssue.constraint) {\n return { document: currentDocument, ...described };\n }\n if (!shouldRecoverSocialDocumentIssue(platform, operation, initialIssue, context)) {\n throw toIssueError(currentDocument, described);\n }\n\n const fallback = await resolveProviderBrowserFallback({\n browserFallbackPort: context.browserFallbackPort ?? browserFallbackPort,\n provider: providerId,\n source: \"social\",\n operation,\n reasonCode: initialIssue.reasonCode,\n url: currentDocument.url,\n context,\n details: described.details,\n recoveryHints: extensionFirstRecoveryHints\n });\n if (fallback) {\n if (fallback.disposition !== \"completed\") {\n throw toProviderFallbackError({\n provider: providerId,\n source: \"social\",\n url: currentDocument.url,\n fallback\n });\n }\n\n const requestedUrl = currentDocument.url;\n const fallbackDocument = toCompletedFallbackDocument({\n providerId,\n source: \"social\",\n operation,\n url: currentDocument.url,\n fallback,\n ownerReview: shouldOwnerReviewSocialFallback\n });\n const effectiveUrl = resolveRecoveredSocialSearchDocumentUrl({\n platform,\n operation,\n requestedUrl,\n recoveredUrl: fallbackDocument.url,\n recoveredLinks: fallbackDocument.links\n });\n currentDocument = {\n ...fallbackDocument,\n url: effectiveUrl,\n };\n described = describeDocumentIssue(operation, currentDocument);\n if (!described.issue || (described.issue.reasonCode === \"env_limited\" && !described.issue.constraint)) {\n return { document: currentDocument, ...described };\n }\n }\n\n throw toIssueError(currentDocument, described);\n };\n return {\n ...options,\n ...(defaultTraversal ? { defaultTraversal } : {}),\n search: options?.search ?? (async (input, context) => {\n const query = input.query.trim();\n const page = toPositiveInt(input.filters?.page, 1);\n const lookupUrl = isHttpUrl(query)\n ? query\n : SOCIAL_SEARCH_ENDPOINTS[platform](query, page);\n const document = await fetchRuntimeDocumentWithFallback({\n url: lookupUrl,\n provider: providerId,\n source: \"social\",\n operation: \"search\",\n signal: context.signal,\n context,\n browserFallbackPort,\n recoveryHints: extensionFirstRecoveryHints,\n recoverRuntimeErrors: EXTENSION_FIRST_SOCIAL_FALLBACK_PLATFORMS.has(platform),\n ownerReview: shouldOwnerReviewSocialFallback\n });\n const { document: resolvedDocument, extracted, pageMessage } = await resolveFallbackDocumentIfNeeded(\"search\", document, context);\n const links = dedupeLinks(\n selectUsableSocialSearchLinks(platform, resolvedDocument.url, resolvedDocument.links),\n resolvedDocument.url,\n 20\n );\n\n return [{\n url: resolvedDocument.url,\n title: isHttpUrl(query) ? resolvedDocument.url : `${platform} search: ${query}`,\n content: pageMessage,\n confidence: isHttpUrl(query) ? 0.72 : 0.58,\n attributes: {\n platform,\n query,\n page,\n status: resolvedDocument.status,\n links,\n retrievalPath: isHttpUrl(query) ? \"social:search:url\" : \"social:search:index\",\n ...browserFallbackObservationAttributes(resolvedDocument.browserFallback)\n }\n }];\n }),\n fetch: options?.fetch ?? (async (input, context) => {\n const document = await fetchRuntimeDocumentWithFallback({\n url: input.url,\n provider: providerId,\n source: \"social\",\n operation: \"fetch\",\n signal: context.signal,\n context,\n browserFallbackPort,\n recoveryHints: extensionFirstRecoveryHints,\n recoverRuntimeErrors: EXTENSION_FIRST_SOCIAL_FALLBACK_PLATFORMS.has(platform),\n ownerReview: shouldOwnerReviewSocialFallback\n });\n const { document: resolvedDocument, extracted } = await resolveFallbackDocumentIfNeeded(\"fetch\", document, context);\n const links = dedupeLinks(resolvedDocument.links, resolvedDocument.url, 20);\n return {\n url: resolvedDocument.url,\n title: resolvedDocument.url,\n content: resolvedDocument.text,\n attributes: {\n platform,\n status: resolvedDocument.status,\n links,\n retrievalPath: \"social:fetch:url\",\n ...browserFallbackObservationAttributes(resolvedDocument.browserFallback)\n }\n };\n }),\n ...(extensionFirstRecoveryHints ? { recoveryHints: () => extensionFirstRecoveryHints } : {})\n };\n};\n\nconst withDefaultSocialOptions = (\n options: SocialProvidersOptions | undefined,\n runtimeInit: Pick<RuntimeInit, \"transcript\" | \"browserFallbackPort\" | \"antiBotPolicy\">\n): SocialProvidersOptions => ({\n x: withDefaultSocialPlatformOptions(\"x\", options?.x, runtimeInit.browserFallbackPort),\n reddit: withDefaultSocialPlatformOptions(\"reddit\", options?.reddit, runtimeInit.browserFallbackPort),\n bluesky: withDefaultSocialPlatformOptions(\"bluesky\", options?.bluesky, runtimeInit.browserFallbackPort),\n facebook: withDefaultSocialPlatformOptions(\"facebook\", options?.facebook, runtimeInit.browserFallbackPort),\n linkedin: withDefaultSocialPlatformOptions(\"linkedin\", options?.linkedin, runtimeInit.browserFallbackPort),\n instagram: withDefaultSocialPlatformOptions(\"instagram\", options?.instagram, runtimeInit.browserFallbackPort),\n tiktok: withDefaultSocialPlatformOptions(\"tiktok\", options?.tiktok, runtimeInit.browserFallbackPort),\n threads: withDefaultSocialPlatformOptions(\"threads\", options?.threads, runtimeInit.browserFallbackPort),\n youtube: withDefaultYouTubeOptions({\n ...(options?.youtube ?? {}),\n ...(runtimeInit.transcript\n ? {\n transcriptResolver: {\n modeDefault: runtimeInit.transcript.modeDefault,\n strategyOrder: runtimeInit.transcript.strategyOrder,\n enableYtdlp: runtimeInit.transcript.enableYtdlp,\n enableAsr: runtimeInit.transcript.enableAsr,\n enableYtdlpAudioAsr: runtimeInit.transcript.enableYtdlpAudioAsr,\n enableApify: runtimeInit.transcript.enableApify,\n apifyActorId: runtimeInit.transcript.apifyActorId,\n enableBrowserFallback: runtimeInit.transcript.enableBrowserFallback,\n ytdlpTimeoutMs: runtimeInit.transcript.ytdlpTimeoutMs\n }\n }\n : {}),\n ...(runtimeInit.browserFallbackPort\n ? { browserFallbackPort: runtimeInit.browserFallbackPort }\n : {}),\n ...(runtimeInit.antiBotPolicy\n ? { antiBotPolicy: runtimeInit.antiBotPolicy }\n : {})\n })\n});\n\nexport const createDefaultRuntime = (\n defaults: RuntimeDefaults = {},\n init: Omit<RuntimeInit, \"providers\"> = {}\n): ProviderRuntime => {\n const runtime = new ProviderRuntime(init);\n runtime.register(createWebProvider(withDefaultWebOptions(defaults.web, init.browserFallbackPort)));\n runtime.register(createCommunityProvider(withDefaultCommunityOptions(defaults.community, init.browserFallbackPort)));\n for (const provider of createSocialProviders(withDefaultSocialOptions(defaults.social, {\n transcript: init.transcript,\n browserFallbackPort: init.browserFallbackPort,\n antiBotPolicy: init.antiBotPolicy\n }))) {\n runtime.register(provider);\n }\n for (const provider of createShoppingProviders(defaults.shopping)) {\n runtime.register(provider);\n }\n return runtime;\n};\n\nconst mergeBudgets = (\n base: ProviderRuntimeBudgets,\n partial: Partial<ProviderRuntimeBudgets> | undefined\n): ProviderRuntimeBudgets => {\n if (!partial) return base;\n\n return {\n timeoutMs: {\n ...base.timeoutMs,\n ...(partial.timeoutMs ?? {})\n },\n retries: {\n ...base.retries,\n ...(partial.retries ?? {})\n },\n concurrency: {\n ...base.concurrency,\n ...(partial.concurrency ?? {})\n },\n circuitBreaker: {\n ...base.circuitBreaker,\n ...(partial.circuitBreaker ?? {})\n }\n };\n};\n\nexport { ProviderRegistry } from \"./registry\";\nexport { selectProviders } from \"./policy\";\nexport { createWebProvider } from \"./web\";\nexport { createCommunityProvider } from \"./community\";\nexport { createSocialProvider, createSocialProviders } from \"./social\";\nexport { createShoppingProvider, createShoppingProviders, createShoppingProviderById, SHOPPING_PROVIDER_IDS } from \"./shopping\";\nexport * from \"./timebox\";\nexport * from \"./enrichment\";\nexport * from \"./renderer\";\nexport * from \"./artifacts\";\nexport * from \"./workflows\";\nexport * from \"./types\";\nexport * from \"./errors\";\nexport * from \"./normalize\";\nexport * from \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AAwB,SAAS,QAAQ,GAAG;AACjE,YAAQ,SAAS,QAAQ;AAAA,EAC3B;AACA,SAAO;AACT;AAEA,IAAM,eAAe,CACnB,MACA,YAC2B;AAC3B,MAAI,CAAC,QAAS,QAAO;AAErB,SAAO;AAAA,IACL,WAAW;AAAA,MACT,GAAG,KAAK;AAAA,MACR,GAAI,QAAQ,aAAa,CAAC;AAAA,IAC5B;AAAA,IACA,SAAS;AAAA,MACP,GAAG,KAAK;AAAA,MACR,GAAI,QAAQ,WAAW,CAAC;AAAA,IAC1B;AAAA,IACA,aAAa;AAAA,MACX,GAAG,KAAK;AAAA,MACR,GAAI,QAAQ,eAAe,CAAC;AAAA,IAC9B;AAAA,IACA,gBAAgB;AAAA,MACd,GAAG,KAAK;AAAA,MACR,GAAI,QAAQ,kBAAkB,CAAC;AAAA,IACjC;AAAA,EACF;AACF;","names":["path","DEFAULT_HOLD_MS","resolve","outcome","createHash","createHash","resolve","percentile","queue","percentile","isHttpUrl","extractLinks","attributeLinks","fetch","normalizeText","DEFAULT_TRAVERSAL","LINK_RE","asNumber","toPositiveInt","toNonNegativeInt","isHttpUrl","coerceStringArray","extractLinks","attributeLinks","qualityFlags","unavailable","shouldSkipExpansionError","sortRows","mergedTraversal","fetch","isHttpUrl","decodeHtml","normalizeEscapedValue","firstNonEmptyMatch","toJsonRecord","DEFAULT_CURRENCY","hasValues","parseIsoDate","responseUrl","html","isHttpUrl","readAttribute","amount","match","fetch","isHttpUrl","fetch","createHash","mkdtemp","rm","tmpdir","join","join","toDate","fromDate","asNumber","createHash","escapeRegExp","createHash","path","isJsonRecord","trimText","clipText","formatBulletList","createHash","toJsonValue","MIN_READY_REFERENCE_SCORE","MIN_READY_REFERENCE_CONFIDENCE","path","validationChecks","doNotProceedIf","isJsonRecord","commandExamples","hasWeakTopReference","createHash","createHash","asNumber","issuePriority","createHash","isJsonRecord","isProviderError","createHash","result","isJsonRecord","isFiniteNumber","isProviderSource","isTraceContext","isProviderError","isNormalizedRecord","isProviderFailureEntry","isProviderAggregateResult","emptyCheckpointState","createHash","isJsonRecord","isFiniteNumber","isProviderSource","isTraceContext","isProviderError","isNormalizedRecord","isProviderFailureEntry","isProviderAggregateResult","emptyCheckpointState","createHash","appendTrace","getCheckpointedResult","buildCheckpoint","markStepCompleted","isValidHttpUrl","executeSearchStep","executeFetchStep","toProviderSource","isValidHttpUrl","hash","createHash","isJsonRecord","isStringArray","searchResult","discovery","siteResult","join","asNumber","rejectedCandidateCount","mkdtemp","tmpdir","rm","details","checkpointState","stepIndex","WORKFLOW_KIND_BY_SUSPENDED_INTENT_KIND","isJsonRecord","resolve","FALLBACK_HEAD_RE","FALLBACK_BODY_RE","dedupeLinks","isHttpUrl","toPositiveInt","fallbackReasonCodeForError","hash"]}
|