opendevbrowser 0.0.21 → 0.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +13 -3
  2. package/dist/{chunk-4KVXCXV3.js → chunk-2MG7BRPF.js} +521 -84
  3. package/dist/{chunk-4KVXCXV3.js.map → chunk-2MG7BRPF.js.map} +1 -1
  4. package/dist/chunk-3ILXPKSJ.js +86 -0
  5. package/dist/chunk-3ILXPKSJ.js.map +1 -0
  6. package/dist/{chunk-ZE2E7ZGH.js → chunk-K2TEHJCV.js} +240 -33
  7. package/dist/chunk-K2TEHJCV.js.map +1 -0
  8. package/dist/chunk-QVWOPIZJ.js +612 -0
  9. package/dist/chunk-QVWOPIZJ.js.map +1 -0
  10. package/dist/{chunk-3VA6XR25.js → chunk-STGGGVYT.js} +23 -100
  11. package/dist/chunk-STGGGVYT.js.map +1 -0
  12. package/dist/cli/commands/macro-resolve.d.ts.map +1 -1
  13. package/dist/cli/commands/uninstall.d.ts +1 -0
  14. package/dist/cli/commands/uninstall.d.ts.map +1 -1
  15. package/dist/cli/daemon-commands.d.ts.map +1 -1
  16. package/dist/cli/help.d.ts.map +1 -1
  17. package/dist/cli/index.js +298 -618
  18. package/dist/cli/index.js.map +1 -1
  19. package/dist/cli/installers/postinstall-skill-sync.d.ts +15 -0
  20. package/dist/cli/installers/postinstall-skill-sync.d.ts.map +1 -0
  21. package/dist/cli/installers/postinstall-skill-sync.js +48 -0
  22. package/dist/cli/installers/postinstall-skill-sync.js.map +1 -0
  23. package/dist/cli/installers/skills.d.ts +9 -14
  24. package/dist/cli/installers/skills.d.ts.map +1 -1
  25. package/dist/cli/skill-lifecycle.d.ts +26 -0
  26. package/dist/cli/skill-lifecycle.d.ts.map +1 -0
  27. package/dist/cli/update-skill-modes.d.ts +3 -0
  28. package/dist/cli/update-skill-modes.d.ts.map +1 -0
  29. package/dist/cli/utils/workflow-message.d.ts +1 -0
  30. package/dist/cli/utils/workflow-message.d.ts.map +1 -1
  31. package/dist/index.js +25 -9
  32. package/dist/index.js.map +1 -1
  33. package/dist/opendevbrowser.js +25 -9
  34. package/dist/opendevbrowser.js.map +1 -1
  35. package/dist/providers/social/platform.d.ts.map +1 -1
  36. package/dist/providers/social/search-quality.d.ts.map +1 -1
  37. package/dist/providers/social/youtube.d.ts.map +1 -1
  38. package/dist/providers/workflow-handoff.d.ts +27 -3
  39. package/dist/providers/workflow-handoff.d.ts.map +1 -1
  40. package/dist/providers/workflows.d.ts +1 -0
  41. package/dist/providers/workflows.d.ts.map +1 -1
  42. package/dist/{providers-ZIVHHH4F.js → providers-6YVHKTOJ.js} +2 -2
  43. package/dist/public-surface/generated-manifest.d.ts +162 -4
  44. package/dist/public-surface/generated-manifest.d.ts.map +1 -1
  45. package/dist/public-surface/source.d.ts +12 -6
  46. package/dist/public-surface/source.d.ts.map +1 -1
  47. package/dist/skills/skill-loader.js +2 -1
  48. package/dist/tools/macro_resolve.d.ts.map +1 -1
  49. package/extension/manifest.json +1 -1
  50. package/package.json +6 -4
  51. package/scripts/postinstall-sync-skills.mjs +33 -0
  52. package/dist/chunk-3VA6XR25.js.map +0 -1
  53. package/dist/chunk-ZE2E7ZGH.js.map +0 -1
  54. /package/dist/{providers-ZIVHHH4F.js.map → providers-6YVHKTOJ.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/logging.ts","../src/providers/safety/prompt-guard.ts","../src/providers/blocker.ts","../src/providers/constraint.ts","../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/workflow-contracts.ts","../src/providers/workflows.ts","../src/providers/artifacts.ts","../src/providers/timebox.ts","../src/providers/enrichment.ts","../src/inspiredesign/handoff.ts","../src/providers/renderer.ts","../src/providers/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","../src/providers/workflow-handoff.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/providers/index.ts"],"sourcesContent":["import { randomUUID } from \"crypto\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"audit\";\n\nexport type LogEnvelope = {\n ts: string;\n level: LogLevel;\n module: string;\n event: string;\n requestId: string;\n sessionId?: string;\n traceId?: string;\n data?: unknown;\n};\n\ntype LogFields = {\n requestId?: string;\n sessionId?: string;\n traceId?: string;\n data?: unknown;\n};\n\nexport type LogSink = (entry: LogEnvelope) => void;\n\nconst SECRET_KEY_PATTERN = /(token|secret|password|authorization|cookie|api[-_]?key|session)/i;\nconst SECRET_VALUE_PATTERN = /(bearer\\s+[a-z0-9._-]+|sk_[a-z0-9_-]+|pk_[a-z0-9_-]+|eyJ[a-z0-9_-]+\\.[a-z0-9_-]+\\.[a-z0-9_-]+)/gi;\n\nfunction redactString(value: string): string {\n return value.replace(SECRET_VALUE_PATTERN, \"[REDACTED]\");\n}\n\nexport function redactSensitive(value: unknown, seen = new WeakSet<object>()): unknown {\n if (typeof value === \"string\") {\n return redactString(value);\n }\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n if (seen.has(value)) {\n return \"[Circular]\";\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n return value.map((item) => redactSensitive(item, seen));\n }\n\n const output: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n if (SECRET_KEY_PATTERN.test(key)) {\n output[key] = \"[REDACTED]\";\n continue;\n }\n output[key] = redactSensitive(entry, seen);\n }\n return output;\n}\n\nexport function createRequestId(): string {\n return randomUUID();\n}\n\nconst defaultSink: LogSink = (entry) => {\n const payload = JSON.stringify(entry);\n if (entry.level === \"error\") {\n console.error(payload);\n return;\n }\n if (entry.level === \"warn\") {\n console.warn(payload);\n return;\n }\n console.log(payload);\n};\n\nexport const stderrSink: LogSink = (entry) => {\n process.stderr.write(`${JSON.stringify(entry)}\\n`);\n};\n\nlet configuredDefaultSink: LogSink = defaultSink;\n\nexport function setDefaultLogSink(sink?: LogSink | null): void {\n configuredDefaultSink = sink ?? defaultSink;\n}\n\nexport function createLogger(moduleName: string, sink?: LogSink): {\n debug: (event: string, fields?: LogFields) => LogEnvelope;\n info: (event: string, fields?: LogFields) => LogEnvelope;\n warn: (event: string, fields?: LogFields) => LogEnvelope;\n error: (event: string, fields?: LogFields) => LogEnvelope;\n audit: (event: string, fields?: LogFields) => LogEnvelope;\n} {\n const emit = (level: LogLevel, event: string, fields: LogFields = {}): LogEnvelope => {\n const entry: LogEnvelope = {\n ts: new Date().toISOString(),\n level,\n module: moduleName,\n event,\n requestId: fields.requestId ?? createRequestId(),\n ...(fields.sessionId ? { sessionId: fields.sessionId } : {}),\n ...(fields.traceId ? { traceId: fields.traceId } : {}),\n ...(typeof fields.data === \"undefined\" ? {} : { data: redactSensitive(fields.data) })\n };\n (sink ?? configuredDefaultSink)(entry);\n return entry;\n };\n\n return {\n debug: (event, fields) => emit(\"debug\", event, fields),\n info: (event, fields) => emit(\"info\", event, fields),\n warn: (event, fields) => emit(\"warn\", event, fields),\n error: (event, fields) => emit(\"error\", event, fields),\n audit: (event, fields) => emit(\"audit\", event, fields)\n };\n}\n\nexport const __test__ = {\n redactString,\n defaultSink\n};\n","import type { JsonValue, NormalizedRecord } from \"../types\";\n\ntype PromptGuardSeverity = \"low\" | \"medium\" | \"high\";\ntype PromptGuardAction = \"strip\" | \"quarantine\";\ntype PromptGuardField = \"title\" | \"content\";\n\ntype PromptGuardRule = {\n id: string;\n regex: RegExp;\n severity: PromptGuardSeverity;\n action: PromptGuardAction;\n};\n\nexport interface PromptGuardEntry {\n pattern: string;\n action: PromptGuardAction;\n severity: PromptGuardSeverity;\n excerpt: string;\n}\n\nexport interface PromptGuardRecordEntry extends PromptGuardEntry {\n recordId: string;\n field: PromptGuardField;\n}\n\nexport interface PromptGuardTextResult {\n text: string;\n diagnostics: {\n entries: number;\n quarantinedSegments: number;\n };\n entries: PromptGuardEntry[];\n}\n\nexport interface PromptGuardResult {\n records: NormalizedRecord[];\n audit: {\n enabled: boolean;\n quarantinedSegments: number;\n entries: PromptGuardRecordEntry[];\n };\n}\n\nconst MAX_EXCERPT_LENGTH = 120;\n\nconst RULES: PromptGuardRule[] = [\n {\n id: \"reveal_system_prompt\",\n regex: /\\b(reveal|show|print|dump|expose|leak)\\b[^.!?\\n]{0,80}\\b(system prompt|hidden prompt|internal prompt)\\b/gi,\n severity: \"high\",\n action: \"quarantine\"\n },\n {\n id: \"tool_abuse_directive\",\n regex: /\\buse (?:the )?tool(?:ing)?\\b[^.!?\\n]{0,120}\\b(delete|remove|drop|wipe|exfiltrat|override|bypass)\\w*/gi,\n severity: \"high\",\n action: \"quarantine\"\n },\n {\n id: \"ignore_previous_instructions\",\n regex: /\\bignore (?:all )?previous instructions?\\b/gi,\n severity: \"medium\",\n action: \"strip\"\n },\n {\n id: \"reveal_hidden_data\",\n regex: /\\breveal (?:hidden|secret|confidential) (?:data|information)\\b/gi,\n severity: \"high\",\n action: \"quarantine\"\n }\n];\n\nconst sanitizeExcerpt = (value: string): string => {\n const compact = value.replace(/\\s+/g, \" \").trim();\n if (compact.length <= MAX_EXCERPT_LENGTH) return compact;\n return `${compact.slice(0, MAX_EXCERPT_LENGTH - 3)}...`;\n};\n\nconst isJsonObject = (value: JsonValue | undefined): value is Record<string, JsonValue> => {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n};\n\nconst withSecurityAttributes = (\n record: NormalizedRecord,\n enabled: boolean,\n guardEntries: number,\n quarantinedSegments: number\n): Record<string, JsonValue> => {\n const existingSecurity = isJsonObject(record.attributes.security)\n ? record.attributes.security\n : {};\n\n return {\n ...record.attributes,\n security: {\n ...existingSecurity,\n untrustedContent: true,\n dataOnlyContext: true,\n promptGuardEnabled: enabled,\n guardEntries,\n quarantinedSegments\n }\n };\n};\n\nexport function sanitizePromptGuardText(text: string, enabled: boolean): PromptGuardTextResult {\n if (!enabled || !text) {\n return {\n text,\n diagnostics: { entries: 0, quarantinedSegments: 0 },\n entries: []\n };\n }\n\n let output = text;\n const entries: PromptGuardEntry[] = [];\n\n for (const rule of RULES) {\n rule.regex.lastIndex = 0;\n output = output.replace(rule.regex, (match) => {\n entries.push({\n pattern: rule.id,\n action: rule.action,\n severity: rule.severity,\n excerpt: sanitizeExcerpt(match)\n });\n return rule.action === \"quarantine\" ? \"[QUARANTINED]\" : \" \";\n });\n }\n\n const normalized = output.replace(/\\s{2,}/g, \" \").trim();\n const quarantinedSegments = entries.reduce((count, entry) => {\n return entry.action === \"quarantine\" ? count + 1 : count;\n }, 0);\n\n return {\n text: normalized,\n diagnostics: {\n entries: entries.length,\n quarantinedSegments\n },\n entries\n };\n}\n\nexport function applyPromptGuard(records: NormalizedRecord[], enabled: boolean): PromptGuardResult {\n const auditEntries: PromptGuardRecordEntry[] = [];\n let totalQuarantinedSegments = 0;\n\n const guardedRecords = records.map((record) => {\n if (!enabled) {\n return {\n ...record,\n attributes: withSecurityAttributes(record, false, 0, 0)\n };\n }\n\n let title = record.title;\n let content = record.content;\n let recordEntries = 0;\n let recordQuarantinedSegments = 0;\n\n if (typeof record.title === \"string\") {\n const sanitizedTitle = sanitizePromptGuardText(record.title, true);\n title = sanitizedTitle.text;\n recordEntries += sanitizedTitle.diagnostics.entries;\n recordQuarantinedSegments += sanitizedTitle.diagnostics.quarantinedSegments;\n for (const entry of sanitizedTitle.entries) {\n auditEntries.push({\n ...entry,\n recordId: record.id,\n field: \"title\"\n });\n }\n }\n\n if (typeof record.content === \"string\") {\n const sanitizedContent = sanitizePromptGuardText(record.content, true);\n content = sanitizedContent.text;\n recordEntries += sanitizedContent.diagnostics.entries;\n recordQuarantinedSegments += sanitizedContent.diagnostics.quarantinedSegments;\n for (const entry of sanitizedContent.entries) {\n auditEntries.push({\n ...entry,\n recordId: record.id,\n field: \"content\"\n });\n }\n }\n\n totalQuarantinedSegments += recordQuarantinedSegments;\n\n return {\n ...record,\n ...(typeof title === \"string\" ? { title } : {}),\n ...(typeof content === \"string\" ? { content } : {}),\n attributes: withSecurityAttributes(record, true, recordEntries, recordQuarantinedSegments)\n };\n });\n\n return {\n records: guardedRecords,\n audit: {\n enabled,\n quarantinedSegments: enabled ? totalQuarantinedSegments : 0,\n entries: enabled ? auditEntries : []\n }\n };\n}\n","import { redactSensitive } from \"../core/logging\";\nimport { sanitizePromptGuardText } from \"./safety/prompt-guard\";\nimport type {\n BlockerActionHint,\n BlockerArtifactCaps,\n BlockerArtifactsV1,\n BlockerSignalV1,\n BlockerType,\n JsonValue,\n ProviderReasonCode\n} from \"./types\";\n\nconst AUTH_URL_PATTERNS: Array<{ id: string; regex: RegExp; confidence: number }> = [\n { id: \"redirect_login_flow\", regex: /\\/i\\/flow\\/login/i, confidence: 0.97 },\n { id: \"auth_login_path\", regex: /\\/(login|signin|sign-in|auth)(?:[./?]|$)/i, confidence: 0.9 }\n];\n\nconst AUTH_TITLE_PATTERNS: Array<{ id: string; regex: RegExp; confidence: number }> = [\n { id: \"title_login\", regex: /\\b(log ?in|sign ?in|login|signin)\\b/i, confidence: 0.92 },\n { id: \"title_auth_required\", regex: /authentication required/i, confidence: 0.9 }\n];\n\nconst CHALLENGE_PATTERNS: Array<{ id: string; regex: RegExp; confidence: number }> = [\n { id: \"challenge_keyword\", regex: /\\b(challenge|captcha|verify|interstitial|cf_chl|bot)\\b/i, confidence: 0.88 },\n { id: \"prove_humanity\", regex: /prove your humanity/i, confidence: 0.96 },\n { id: \"robot_or_human\", regex: /robot or human/i, confidence: 0.98 },\n { id: \"confirm_human\", regex: /confirm that you(?:'|’)re human/i, confidence: 0.96 },\n { id: \"click_and_hold\", regex: /\\b(?:click|press|tap|activate)\\s+(?:and\\s+)?hold\\b/i, confidence: 0.95 },\n { id: \"press_and_hold\", regex: /activate and hold the button/i, confidence: 0.95 },\n { id: \"drag_slider\", regex: /\\b(?:drag|slide|move)(?:\\s+the)?\\s+(?:slider|puzzle(?:\\s+piece)?|piece|button)\\b/i, confidence: 0.95 },\n { id: \"pardon_interruption\", regex: /pardon our interruption/i, confidence: 0.97 },\n { id: \"checking_browser_gate\", regex: /checking your browser before you access/i, confidence: 0.97 }\n];\n\nconst RECAPTCHA_HOST_PATTERNS = [/recaptcha/i, /hcaptcha/i, /challenges\\.cloudflare\\.com/i];\nconst STATIC_BLOCK_HOST_PATTERNS = [/redditstatic\\.com$/i, /abs\\.twimg\\.com$/i, /twimg\\.com$/i];\n\nconst ENV_LIMITED_PATTERNS = [\n /extension not connected/i,\n /connect the extension/i,\n /manual interaction/i,\n /timed out/i,\n /not available in this environment/i\n];\n\nconst RESTRICTED_TARGET_PATTERNS = [/^chrome:\\/\\//i, /^chrome-extension:\\/\\//i, /^about:blank$/i, /^devtools:\\/\\//i];\n\nexport const DEFAULT_BLOCKER_ARTIFACT_CAPS: BlockerArtifactCaps = {\n maxNetworkEvents: 20,\n maxConsoleEvents: 20,\n maxExceptionEvents: 10,\n maxHosts: 10,\n maxTextLength: 512\n};\n\nexport interface BlockerClassificationInput {\n source: BlockerSignalV1[\"source\"];\n url?: string;\n finalUrl?: string;\n title?: string;\n status?: number;\n providerErrorCode?: string;\n message?: string;\n matchedPatterns?: string[];\n networkHosts?: string[];\n traceRequestId?: string;\n retryable?: boolean;\n envLimited?: boolean;\n restrictedTarget?: boolean;\n promptGuardEnabled?: boolean;\n threshold?: number;\n detectedAt?: string;\n}\n\nexport interface BlockerArtifactInput {\n networkEvents?: unknown[];\n consoleEvents?: unknown[];\n exceptionEvents?: unknown[];\n promptGuardEnabled?: boolean;\n caps?: Partial<BlockerArtifactCaps>;\n}\n\nconst toLower = (value: string): string => value.trim().toLowerCase();\n\nconst clampNumber = (value: number, min: number, max: number): number => {\n if (!Number.isFinite(value)) return min;\n if (value < min) return min;\n if (value > max) return max;\n return value;\n};\n\nexport const clampBlockerConfidence = (value: number): number => {\n return clampNumber(value, 0, 1);\n};\n\nconst clampThreshold = (value: number | undefined): number => {\n if (typeof value !== \"number\") return 0.7;\n return clampNumber(value, 0, 1);\n};\n\nexport const clampText = (value: string | undefined, maxLength: number): string | undefined => {\n if (typeof value !== \"string\") return undefined;\n if (maxLength <= 0) return \"\";\n return value.length <= maxLength ? value : `${value.slice(0, Math.max(0, maxLength - 3))}...`;\n};\n\nexport const boundedUniqueList = (\n values: readonly string[] | undefined,\n maxLength: number\n): string[] => {\n if (!values || values.length === 0 || maxLength <= 0) return [];\n const seen = new Set<string>();\n const list: string[] = [];\n for (const value of values) {\n if (typeof value !== \"string\") continue;\n const normalized = value.trim();\n if (!normalized) continue;\n const key = normalized.toLowerCase();\n if (seen.has(key)) continue;\n seen.add(key);\n list.push(normalized);\n if (list.length >= maxLength) break;\n }\n return list;\n};\n\nconst extractHost = (value: string | undefined): string | null => {\n if (!value) return null;\n try {\n return toLower(new URL(value).hostname);\n } catch {\n return null;\n }\n};\n\nconst scorePatternMatches = (\n text: string,\n patterns: Array<{ id: string; regex: RegExp; confidence: number }>\n): { matched: string[]; confidence: number } => {\n const matched: string[] = [];\n let confidence = 0;\n for (const pattern of patterns) {\n if (!pattern.regex.test(text)) continue;\n matched.push(pattern.id);\n confidence = Math.max(confidence, pattern.confidence);\n }\n return { matched, confidence };\n};\n\nconst hasAnyPattern = (value: string, patterns: RegExp[]): boolean => {\n return patterns.some((pattern) => pattern.test(value));\n};\n\nconst isLoopbackHost = (value: string): boolean => {\n const normalized = toLower(value).replace(/^\\[|\\]$/g, \"\");\n if (!normalized) return false;\n if (normalized === \"localhost\" || normalized === \"::1\") return true;\n if (normalized === \"127.0.0.1\" || normalized.startsWith(\"127.\")) return true;\n return /^::ffff:127\\.\\d+\\.\\d+\\.\\d+$/.test(normalized);\n};\n\nconst buildHints = (type: BlockerType): BlockerActionHint[] => {\n switch (type) {\n case \"auth_required\":\n return [\n { id: \"manual_login\", reason: \"Authentication flow requires interactive login.\", priority: 1 },\n { id: \"switch_managed_headed\", reason: \"Headed mode can complete login and persist session state.\", priority: 2 },\n { id: \"switch_extension_mode\", reason: \"Extension mode can reuse an already logged-in browser profile.\", priority: 3 }\n ];\n case \"anti_bot_challenge\":\n return [\n { id: \"manual_challenge\", reason: \"Challenge page requires manual completion.\", priority: 1 },\n { id: \"switch_managed_headed\", reason: \"Headed mode improves challenge completion reliability.\", priority: 2 },\n { id: \"collect_debug_trace\", reason: \"Collect trace artifacts to compare challenge indicators before and after manual action.\", priority: 3 }\n ];\n case \"rate_limited\":\n return [\n { id: \"retry_after_backoff\", reason: \"Rate-limited responses should be retried after a bounded delay.\", priority: 1 },\n { id: \"collect_debug_trace\", reason: \"Trace data can confirm cooldown and request pacing behavior.\", priority: 2 }\n ];\n case \"upstream_block\":\n return [\n { id: \"retry_after_backoff\", reason: \"Upstream blocks may clear after network or host recovery.\", priority: 1 },\n { id: \"switch_managed_headed\", reason: \"Browser-assisted retrieval may bypass runtime fetch limitations.\", priority: 2 },\n { id: \"collect_debug_trace\", reason: \"Trace host evidence helps confirm blocked upstream dependencies.\", priority: 3 }\n ];\n case \"restricted_target\":\n return [\n { id: \"switch_managed_headed\", reason: \"Restricted internal targets require navigation to a normal http(s) tab.\", priority: 1 },\n { id: \"collect_debug_trace\", reason: \"Trace confirms blocked scheme or tab restriction source.\", priority: 2 }\n ];\n case \"env_limited\":\n return [\n { id: \"switch_extension_mode\", reason: \"Extension relay availability is required for this operation.\", priority: 1 },\n { id: \"switch_managed_headed\", reason: \"Managed headed mode is a deterministic fallback when extension is unavailable.\", priority: 2 },\n { id: \"collect_debug_trace\", reason: \"Diagnostics can confirm environment capability gaps.\", priority: 3 }\n ];\n case \"unknown\":\n return [{ id: \"collect_debug_trace\", reason: \"Additional trace evidence is required for reliable classification.\", priority: 1 }];\n }\n};\n\nconst classifyFromInputs = (\n input: BlockerClassificationInput,\n normalizedHosts: string[],\n matchedPatterns: string[]\n): { type: BlockerType; reasonCode?: ProviderReasonCode; confidence: number; retryable: boolean; matches: string[] } | null => {\n const status = input.status;\n const code = toLower(input.providerErrorCode ?? \"\");\n const url = input.url ?? \"\";\n const finalUrl = input.finalUrl ?? \"\";\n const title = input.title ?? \"\";\n const message = input.message ?? \"\";\n const challengeText = `${title} ${message}`;\n const urlSignals = `${url} ${finalUrl}`;\n const isUpstreamCode = code === \"upstream\" || code === \"network\" || code === \"unavailable\";\n const hasStaticBlockHost = normalizedHosts.some((host) => hasAnyPattern(host, STATIC_BLOCK_HOST_PATTERNS));\n const isLoopbackContext = [\n extractHost(url),\n extractHost(finalUrl),\n ...normalizedHosts\n ].some((host): host is string => typeof host === \"string\" && isLoopbackHost(host));\n\n const authMatches: string[] = [];\n let authConfidence = 0;\n if (status === 401 || status === 403) {\n authMatches.push(`status:${status}`);\n authConfidence = Math.max(authConfidence, status === 401 ? 0.94 : 0.9);\n }\n if (code === \"auth\") {\n authMatches.push(\"provider_code:auth\");\n authConfidence = Math.max(authConfidence, 0.9);\n }\n const authPathMatches = scorePatternMatches(`${url} ${finalUrl}`, AUTH_URL_PATTERNS);\n authMatches.push(...authPathMatches.matched);\n authConfidence = Math.max(authConfidence, authPathMatches.confidence);\n const authTitleMatches = scorePatternMatches(title, AUTH_TITLE_PATTERNS);\n authMatches.push(...authTitleMatches.matched);\n authConfidence = Math.max(authConfidence, authTitleMatches.confidence);\n if (authConfidence > 0) {\n return {\n type: \"auth_required\",\n reasonCode: \"token_required\",\n confidence: authConfidence,\n retryable: false,\n matches: boundedUniqueList([...matchedPatterns, ...authMatches], 16)\n };\n }\n\n if (!isLoopbackContext) {\n const challengeMatches: string[] = [];\n let challengeConfidence = 0;\n const challengePatternMatches = scorePatternMatches(challengeText, CHALLENGE_PATTERNS);\n challengeMatches.push(...challengePatternMatches.matched);\n challengeConfidence = Math.max(challengeConfidence, challengePatternMatches.confidence);\n if (/(captcha|cf_chl|hcaptcha|recaptcha|interstitial)/i.test(urlSignals)) {\n challengeMatches.push(\"url:challenge_token\");\n challengeConfidence = Math.max(challengeConfidence, 0.9);\n }\n if (hasAnyPattern(title, CHALLENGE_PATTERNS.map((entry) => entry.regex)) && status === 200) {\n challengeMatches.push(\"status:200_challenge_title\");\n challengeConfidence = Math.max(challengeConfidence, 0.92);\n }\n if (normalizedHosts.some((host) => hasAnyPattern(host, RECAPTCHA_HOST_PATTERNS))) {\n challengeMatches.push(\"network:challenge_host\");\n challengeConfidence = Math.max(challengeConfidence, 0.96);\n }\n if (challengeConfidence > 0) {\n return {\n type: \"anti_bot_challenge\",\n reasonCode: \"challenge_detected\",\n confidence: challengeConfidence,\n retryable: false,\n matches: boundedUniqueList([...matchedPatterns, ...challengeMatches], 16)\n };\n }\n }\n\n if (status === 429 || code === \"rate_limited\") {\n return {\n type: \"rate_limited\",\n reasonCode: \"rate_limited\",\n confidence: 0.95,\n retryable: true,\n matches: boundedUniqueList([...matchedPatterns, status === 429 ? \"status:429\" : \"provider_code:rate_limited\"], 16)\n };\n }\n\n if (isUpstreamCode && (hasStaticBlockHost || /retrieval failed/i.test(message) || (typeof status === \"number\" && status >= 500))) {\n return {\n type: \"upstream_block\",\n reasonCode: \"ip_blocked\",\n confidence: hasStaticBlockHost ? 0.9 : 0.8,\n retryable: input.retryable ?? true,\n matches: boundedUniqueList(\n [\n ...matchedPatterns,\n `provider_code:${code}`,\n ...(hasStaticBlockHost ? [\"network:blocked_static_host\"] : [])\n ],\n 16\n )\n };\n }\n\n if (\n input.restrictedTarget\n || RESTRICTED_TARGET_PATTERNS.some((pattern) => pattern.test(url))\n || RESTRICTED_TARGET_PATTERNS.some((pattern) => pattern.test(finalUrl))\n ) {\n return {\n type: \"restricted_target\",\n confidence: 0.92,\n retryable: false,\n matches: boundedUniqueList([...matchedPatterns, \"restricted_target\"], 16)\n };\n }\n\n if (input.envLimited || (code === \"unavailable\" && ENV_LIMITED_PATTERNS.some((pattern) => pattern.test(message)))) {\n return {\n type: \"env_limited\",\n reasonCode: \"env_limited\",\n confidence: input.envLimited ? 0.9 : 0.78,\n retryable: true,\n matches: boundedUniqueList([...matchedPatterns, \"env_limited\"], 16)\n };\n }\n\n if (status || code || title || message || normalizedHosts.length > 0) {\n return {\n type: \"unknown\",\n confidence: 0.5,\n retryable: input.retryable ?? false,\n matches: boundedUniqueList(matchedPatterns, 16)\n };\n }\n\n return null;\n};\n\nconst coerceJsonValue = (\n value: unknown,\n maxTextLength: number,\n promptGuardEnabled: boolean,\n diagnostics: { entries: number; quarantinedSegments: number },\n seen: WeakSet<object>\n): JsonValue => {\n if (value === null || typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n if (typeof value === \"string\") {\n const sanitized = sanitizePromptGuardText(value, promptGuardEnabled);\n diagnostics.entries += sanitized.diagnostics.entries;\n diagnostics.quarantinedSegments += sanitized.diagnostics.quarantinedSegments;\n const redacted = redactSensitive(sanitized.text);\n const asString = typeof redacted === \"string\" ? redacted : String(redacted);\n return clampText(asString, maxTextLength) ?? \"\";\n }\n\n if (Array.isArray(value)) {\n return value.slice(0, 20).map((entry) => coerceJsonValue(entry, maxTextLength, promptGuardEnabled, diagnostics, seen));\n }\n\n if (typeof value !== \"object\") {\n return String(value);\n }\n\n if (seen.has(value)) {\n return \"[Circular]\";\n }\n seen.add(value);\n\n const objectValue = value as Record<string, unknown>;\n const entries = Object.entries(objectValue).slice(0, 30);\n const output: Record<string, JsonValue> = {};\n for (const [key, entryValue] of entries) {\n output[key] = coerceJsonValue(entryValue, maxTextLength, promptGuardEnabled, diagnostics, seen);\n }\n return output;\n};\n\nconst coerceEventList = (\n values: unknown[] | undefined,\n maxItems: number,\n maxTextLength: number,\n promptGuardEnabled: boolean,\n diagnostics: { entries: number; quarantinedSegments: number }\n): Array<Record<string, JsonValue>> => {\n if (!Array.isArray(values) || maxItems <= 0) return [];\n return values.slice(-maxItems).map((entry) => {\n const sanitized = coerceJsonValue(\n redactSensitive(entry),\n maxTextLength,\n promptGuardEnabled,\n diagnostics,\n new WeakSet<object>()\n );\n if (!sanitized || typeof sanitized !== \"object\" || Array.isArray(sanitized)) {\n return { value: sanitized };\n }\n return sanitized as Record<string, JsonValue>;\n });\n};\n\nexport const resolveBlockerArtifactCaps = (\n partial: Partial<BlockerArtifactCaps> | undefined\n): BlockerArtifactCaps => {\n return {\n maxNetworkEvents: clampNumber(partial?.maxNetworkEvents ?? DEFAULT_BLOCKER_ARTIFACT_CAPS.maxNetworkEvents, 1, 500),\n maxConsoleEvents: clampNumber(partial?.maxConsoleEvents ?? DEFAULT_BLOCKER_ARTIFACT_CAPS.maxConsoleEvents, 1, 500),\n maxExceptionEvents: clampNumber(partial?.maxExceptionEvents ?? DEFAULT_BLOCKER_ARTIFACT_CAPS.maxExceptionEvents, 1, 200),\n maxHosts: clampNumber(partial?.maxHosts ?? DEFAULT_BLOCKER_ARTIFACT_CAPS.maxHosts, 1, 200),\n maxTextLength: clampNumber(partial?.maxTextLength ?? DEFAULT_BLOCKER_ARTIFACT_CAPS.maxTextLength, 32, 4096)\n };\n};\n\nexport const classifyBlockerSignal = (\n input: BlockerClassificationInput\n): BlockerSignalV1 | null => {\n const promptGuardEnabled = input.promptGuardEnabled ?? true;\n const titleSanitized = sanitizePromptGuardText(input.title ?? \"\", promptGuardEnabled);\n const messageSanitized = sanitizePromptGuardText(input.message ?? \"\", promptGuardEnabled);\n const matchedPatterns = boundedUniqueList(input.matchedPatterns, 16);\n const normalizedHosts = boundedUniqueList(input.networkHosts?.map(toLower), 20);\n\n const classification = classifyFromInputs({\n ...input,\n title: titleSanitized.text,\n message: messageSanitized.text\n }, normalizedHosts, matchedPatterns);\n if (!classification) {\n return null;\n }\n\n const threshold = clampThreshold(input.threshold);\n const confidence = clampBlockerConfidence(classification.confidence);\n if (confidence < threshold) {\n return null;\n }\n\n const evidence = {\n ...(input.url ? { url: clampText(input.url, 512) } : {}),\n ...(input.finalUrl ? { finalUrl: clampText(input.finalUrl, 512) } : {}),\n ...(titleSanitized.text ? { title: clampText(titleSanitized.text, 512) } : {}),\n ...(typeof input.status === \"number\" ? { status: input.status } : {}),\n ...(input.providerErrorCode ? { providerErrorCode: input.providerErrorCode } : {}),\n matchedPatterns: boundedUniqueList(classification.matches, 16),\n networkHosts: boundedUniqueList(normalizedHosts, 10),\n ...(input.traceRequestId ? { traceRequestId: input.traceRequestId } : {})\n };\n\n const sanitationEntries = titleSanitized.diagnostics.entries + messageSanitized.diagnostics.entries;\n const sanitationQuarantined = titleSanitized.diagnostics.quarantinedSegments + messageSanitized.diagnostics.quarantinedSegments;\n\n return {\n schemaVersion: \"1.0\",\n type: classification.type,\n source: input.source,\n ...(classification.reasonCode ? { reasonCode: classification.reasonCode } : {}),\n confidence,\n retryable: classification.retryable,\n detectedAt: input.detectedAt ?? new Date().toISOString(),\n evidence,\n actionHints: buildHints(classification.type),\n ...(sanitationEntries > 0 || sanitationQuarantined > 0\n ? {\n sanitation: {\n entries: sanitationEntries,\n quarantinedSegments: sanitationQuarantined\n }\n }\n : {})\n };\n};\n\nexport const buildBlockerArtifacts = (input: BlockerArtifactInput): BlockerArtifactsV1 => {\n const caps = resolveBlockerArtifactCaps(input.caps);\n const promptGuardEnabled = input.promptGuardEnabled ?? true;\n const diagnostics = {\n entries: 0,\n quarantinedSegments: 0\n };\n\n const network = coerceEventList(\n input.networkEvents,\n caps.maxNetworkEvents,\n caps.maxTextLength,\n promptGuardEnabled,\n diagnostics\n );\n const console = coerceEventList(\n input.consoleEvents,\n caps.maxConsoleEvents,\n caps.maxTextLength,\n promptGuardEnabled,\n diagnostics\n );\n const exception = coerceEventList(\n input.exceptionEvents,\n caps.maxExceptionEvents,\n caps.maxTextLength,\n promptGuardEnabled,\n diagnostics\n );\n\n const hosts = boundedUniqueList(\n network\n .map((event) => (typeof event.url === \"string\" ? extractHost(event.url) : null))\n .filter((host): host is string => typeof host === \"string\"),\n caps.maxHosts\n );\n\n return {\n schemaVersion: \"1.0\",\n network,\n console,\n exception,\n hosts,\n sanitation: diagnostics\n };\n};\n\nexport const __test__ = {\n classifyFromInputs,\n extractHost,\n hasAnyPattern,\n clampThreshold,\n isLoopbackHost\n};\n","import { classifyBlockerSignal } from \"./blocker\";\nimport { isProviderReasonCode } from \"./errors\";\nimport type {\n BlockerSignalV1,\n BlockerType,\n JsonValue,\n NormalizedRecord,\n ProviderConstraint,\n ProviderConstraintKind,\n ProviderReasonCode\n} from \"./types\";\n\nexport interface ProviderIssueHint {\n reasonCode: ProviderReasonCode;\n blockerType?: BlockerType;\n constraint?: ProviderConstraint;\n}\n\nexport interface ProviderNextStepGuidance {\n [key: string]: JsonValue;\n reason: string;\n recommendedNextCommands: string[];\n}\n\nexport interface ProviderIssueSummary extends ProviderIssueHint {\n provider?: string;\n summary: string;\n guidance?: ProviderNextStepGuidance;\n}\n\nconst BLOCKER_TYPES = new Set<BlockerType>([\n \"auth_required\",\n \"anti_bot_challenge\",\n \"rate_limited\",\n \"upstream_block\",\n \"restricted_target\",\n \"env_limited\",\n \"unknown\"\n]);\n\nconst CONSTRAINT_KINDS = new Set<ProviderConstraintKind>([\n \"session_required\",\n \"render_required\"\n]);\n\nconst RENDER_REQUIRED_SHELLS = new Set<string>([\n \"bestbuy_international_gate\",\n \"duckduckgo_non_js_redirect\",\n \"macys_access_denied_shell\",\n \"social_first_party_help_shell\",\n \"social_js_required_shell\",\n \"social_render_shell\",\n \"target_shell_page\",\n \"temu_empty_shell\"\n]);\n\nconst CHALLENGE_SHELLS = new Set<string>([\"social_verification_wall\", \"temu_challenge_shell\"]);\n\nconst toNonEmptyString = (value: unknown): string | undefined => {\n return typeof value === \"string\" && value.trim().length > 0\n ? value.trim()\n : undefined;\n};\n\nconst normalizeBlockerType = (value: unknown): BlockerType | undefined => {\n return typeof value === \"string\" && BLOCKER_TYPES.has(value as BlockerType)\n ? value as BlockerType\n : undefined;\n};\n\nconst buildConstraint = (\n kind: ProviderConstraintKind,\n evidenceCode: string,\n providerShell?: string,\n message?: string\n): ProviderConstraint => ({\n kind,\n evidenceCode,\n ...(providerShell ? { providerShell } : {}),\n ...(message ? { message } : {})\n});\n\nexport const isProviderConstraint = (value: unknown): value is ProviderConstraint => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n const candidate = value as Record<string, unknown>;\n return CONSTRAINT_KINDS.has(candidate.kind as ProviderConstraintKind)\n && typeof candidate.evidenceCode === \"string\"\n && candidate.evidenceCode.trim().length > 0\n && (candidate.providerShell === undefined || typeof candidate.providerShell === \"string\")\n && (candidate.message === undefined || typeof candidate.message === \"string\");\n};\n\nexport const classifyProviderIssue = (input: {\n url?: string;\n title?: string;\n message?: string;\n providerShell?: string;\n browserRequired?: boolean;\n status?: number;\n providerErrorCode?: string;\n source?: BlockerSignalV1[\"source\"];\n retryable?: boolean;\n}): ProviderIssueHint | null => {\n const providerShell = toNonEmptyString(input.providerShell);\n const message = toNonEmptyString(input.message);\n\n if (providerShell && CHALLENGE_SHELLS.has(providerShell)) {\n return {\n reasonCode: \"challenge_detected\",\n blockerType: \"anti_bot_challenge\"\n };\n }\n\n if (providerShell && RENDER_REQUIRED_SHELLS.has(providerShell)) {\n return {\n reasonCode: \"env_limited\",\n blockerType: \"env_limited\",\n constraint: buildConstraint(\"render_required\", providerShell, providerShell, message)\n };\n }\n\n const blocker = classifyBlockerSignal({\n source: input.source ?? \"runtime_fetch\",\n ...(input.url ? { url: input.url, finalUrl: input.url } : {}),\n ...(input.title ? { title: input.title } : {}),\n ...(message ? { message } : {}),\n ...(typeof input.status === \"number\" ? { status: input.status } : {}),\n ...(input.providerErrorCode ? { providerErrorCode: input.providerErrorCode } : {}),\n ...(typeof input.retryable === \"boolean\" ? { retryable: input.retryable } : {}),\n envLimited: input.browserRequired === true\n });\n\n if (blocker?.type === \"auth_required\") {\n return {\n /* c8 ignore next -- classifyBlockerSignal always supplies token_required for auth_required blockers */\n reasonCode: blocker.reasonCode ?? \"token_required\",\n blockerType: blocker.type,\n constraint: buildConstraint(\"session_required\", providerShell ?? \"auth_required\", providerShell, message)\n };\n }\n\n if (blocker?.type === \"anti_bot_challenge\") {\n return {\n /* c8 ignore next -- classifyBlockerSignal always supplies challenge_detected for anti-bot blockers */\n reasonCode: blocker.reasonCode ?? \"challenge_detected\",\n blockerType: blocker.type\n };\n }\n\n if (input.browserRequired === true) {\n return {\n /* c8 ignore next -- browserRequired inputs always classify to a blocker payload in the shared classifier */\n reasonCode: blocker?.reasonCode ?? \"env_limited\",\n /* c8 ignore next -- browserRequired fallbacks only normalize unknown blocker types */\n blockerType: blocker?.type === \"unknown\" ? \"env_limited\" : blocker?.type,\n /* c8 ignore next -- providerShell or blocker type always survives before the defensive browser_required fallback */\n constraint: buildConstraint(\"render_required\", providerShell ?? blocker?.type ?? \"browser_required\", providerShell, message)\n };\n }\n\n if (blocker?.type === \"env_limited\") {\n return {\n /* c8 ignore next -- classifyBlockerSignal always supplies env_limited for env_limited blockers */\n reasonCode: blocker.reasonCode ?? \"env_limited\",\n blockerType: blocker.type\n };\n }\n\n return null;\n};\n\nexport const readProviderIssueHint = (args: {\n reasonCode?: unknown;\n blockerType?: unknown;\n code?: unknown;\n message?: unknown;\n details?: Record<string, unknown> | undefined;\n}): ProviderIssueHint | null => {\n const details = args.details;\n const reasonCode = isProviderReasonCode(args.reasonCode)\n ? args.reasonCode\n : (isProviderReasonCode(details?.reasonCode) ? details.reasonCode : undefined);\n const blockerType = normalizeBlockerType(args.blockerType ?? details?.blockerType);\n const constraint = isProviderConstraint(details?.constraint)\n ? details.constraint\n : undefined;\n\n if (reasonCode || blockerType || constraint) {\n return {\n reasonCode: reasonCode\n ?? (constraint?.kind === \"session_required\" ? \"token_required\" : \"env_limited\"),\n ...(blockerType ? { blockerType } : {}),\n ...(constraint ? { constraint } : {})\n };\n }\n\n return classifyProviderIssue({\n url: toNonEmptyString(details?.url),\n title: toNonEmptyString(details?.title),\n message: toNonEmptyString(details?.message ?? args.message),\n providerShell: toNonEmptyString(details?.providerShell),\n browserRequired: details?.browserRequired === true,\n providerErrorCode: toNonEmptyString(args.code),\n source: \"runtime_fetch\"\n });\n};\n\nexport const readProviderIssueHintFromRecord = (\n record: Pick<NormalizedRecord, \"url\" | \"title\" | \"content\" | \"attributes\">\n): ProviderIssueHint | null => {\n const details = record.attributes as Record<string, unknown>;\n return readProviderIssueHint({\n reasonCode: details.reasonCode,\n blockerType: details.blockerType,\n message: record.content,\n details: {\n url: record.url,\n title: record.title,\n message: record.content,\n providerShell: details.providerShell,\n browserRequired: details.browserRequired,\n constraint: details.constraint\n }\n });\n};\n\nexport const applyProviderIssueHint = (\n details: Record<string, JsonValue> | undefined,\n hint: ProviderIssueHint | null\n): Record<string, JsonValue> | undefined => {\n if (!hint) return details;\n const next: Record<string, JsonValue> = {\n ...(details ?? {}),\n reasonCode: hint.reasonCode\n };\n if (hint.blockerType && typeof next.blockerType !== \"string\") {\n next.blockerType = hint.blockerType;\n }\n if (hint.constraint && !isProviderConstraint(next.constraint)) {\n next.constraint = hint.constraint;\n }\n if (typeof next.guidance === \"undefined\") {\n const guidance = buildProviderIssueGuidance({ hint, details: next });\n if (guidance) {\n next.guidance = guidance;\n }\n }\n return next;\n};\n\nconst providerLabel = (provider: string | undefined): string => {\n const normalized = toNonEmptyString(provider);\n if (!normalized) return \"Provider\";\n const separator = normalized.lastIndexOf(\"/\");\n const tail = separator >= 0 ? normalized.slice(separator + 1) : normalized;\n return tail.charAt(0).toUpperCase() + tail.slice(1);\n};\n\nconst hasPreservedBrowserState = (details: Record<string, JsonValue> | undefined): boolean => {\n return typeof details?.preservedSessionId === \"string\" || typeof details?.preservedTargetId === \"string\";\n};\n\nconst buildGuidance = (\n reason: string,\n recommendedNextCommands: string[]\n): ProviderNextStepGuidance => ({\n reason,\n recommendedNextCommands\n});\n\nconst buildAuthGuidance = (\n subject: string,\n preservedBrowserState: boolean\n): ProviderNextStepGuidance => {\n return preservedBrowserState\n ? buildGuidance(\n `${subject} preserved browser state that can finish authentication.`,\n [\n \"Complete the login or account checkpoint in the preserved browser session.\",\n \"Rerun the same provider or workflow after the session is fully authenticated.\"\n ]\n )\n : buildGuidance(\n `${subject} needs an authenticated session before retrying.`,\n [\n \"Reuse an authenticated browser session, import logged-in cookies, or use the provider sign-in flow.\",\n \"Rerun the same provider or workflow once the session is active.\"\n ]\n );\n};\n\nconst buildChallengeGuidance = (\n subject: string,\n preservedBrowserState: boolean\n): ProviderNextStepGuidance => {\n return preservedBrowserState\n ? buildGuidance(\n `${subject} preserved browser state that can complete the current challenge.`,\n [\n \"Finish the login or anti-bot challenge in the preserved browser session.\",\n \"Rerun the same provider or workflow after the page unlocks.\"\n ]\n )\n : buildGuidance(\n `${subject} hit a challenge that still needs browser-assisted follow-up.`,\n [\n \"Retry with browser assistance so the challenge can be completed interactively.\",\n \"Only ask for manual credentials if browser-assisted recovery still cannot unlock the page.\"\n ]\n );\n};\n\nconst buildRenderGuidance = (\n subject: string,\n preservedBrowserState: boolean\n): ProviderNextStepGuidance => {\n return preservedBrowserState\n ? buildGuidance(\n `${subject} still needs a live browser-rendered page, but browser state is already preserved.`,\n [\n \"Inspect the preserved browser session until usable content is visible.\",\n \"Rerun the same provider or workflow after the rendered page is ready.\"\n ]\n )\n : buildGuidance(\n `${subject} needs a live browser-rendered page before retrying.`,\n [\n \"Retry with browser assistance or a headed browser session.\",\n \"Rerun the same provider or workflow after the rendered page is ready.\"\n ]\n );\n};\n\nexport const buildProviderIssueGuidance = (args: {\n provider?: string;\n hint: ProviderIssueHint;\n details?: Record<string, JsonValue>;\n}): ProviderNextStepGuidance | undefined => {\n const subject = providerLabel(args.provider);\n const preservedBrowserState = hasPreservedBrowserState(args.details);\n const disposition = toNonEmptyString(args.details?.disposition);\n if (disposition === \"completed\") return undefined;\n if (disposition === \"challenge_preserved\") {\n return buildChallengeGuidance(subject, true);\n }\n if (args.hint.reasonCode === \"token_required\" || args.hint.reasonCode === \"auth_required\") {\n return buildAuthGuidance(subject, preservedBrowserState);\n }\n if (args.hint.reasonCode === \"challenge_detected\") {\n return buildChallengeGuidance(subject, preservedBrowserState);\n }\n if (args.hint.constraint?.kind === \"render_required\" || args.hint.reasonCode === \"env_limited\") {\n return buildRenderGuidance(subject, preservedBrowserState);\n }\n return undefined;\n};\n\nconst summaryPriority = (hint: ProviderIssueHint): number => {\n /* c8 ignore next -- providerLabel always passes a concrete tail string into this helper */\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\nexport const summarizeProviderIssue = (args: {\n provider?: string;\n hint: ProviderIssueHint;\n}): string => {\n const subject = providerLabel(args.provider);\n if (args.hint.reasonCode === \"token_required\" || args.hint.reasonCode === \"auth_required\") {\n return `${subject} requires login or an existing session.`;\n }\n if (args.hint.reasonCode === \"challenge_detected\") {\n return `${subject} hit an anti-bot challenge that requires manual completion.`;\n }\n if (args.hint.constraint?.kind === \"render_required\") {\n return `${subject} requires a live browser-rendered page.`;\n }\n return `${subject} requires manual browser follow-up; this run did not determine whether login or page rendering is required.`;\n};\n\nexport const summarizePrimaryProviderIssue = (\n failures: Array<{ provider?: string; error?: { reasonCode?: unknown; code?: unknown; message?: unknown; details?: Record<string, unknown> } }> | undefined\n): ProviderIssueSummary | null => {\n if (!Array.isArray(failures) || failures.length === 0) return null;\n let best: ProviderIssueSummary | null = null;\n\n for (const failure of failures) {\n const hint = readProviderIssueHint({\n reasonCode: failure.error?.reasonCode,\n code: failure.error?.code,\n message: failure.error?.message,\n details: failure.error?.details\n });\n if (!hint) continue;\n const summary = summarizeProviderIssue({ provider: failure.provider, hint });\n const guidance = buildProviderIssueGuidance({\n provider: failure.provider,\n hint,\n details: failure.error?.details as Record<string, JsonValue> | undefined\n });\n const candidate: ProviderIssueSummary = {\n provider: failure.provider,\n summary,\n ...hint,\n ...(guidance ? { guidance } : {})\n };\n if (!best || summaryPriority(candidate) > summaryPriority(best)) {\n best = candidate;\n }\n }\n\n return best;\n};\n","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|google)\\b/i;\nconst GITHUB_AUTH_RE = /\\b(?:continue with github|sign in with github|log in with github|github)\\b/i;\nconst APPLE_AUTH_RE = /\\b(?:continue with apple|sign in with apple|log in with apple|apple)\\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.length > 0 ? value : 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\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: Record<string, JsonValue> = {\n url: args.url,\n disposition: fallback.disposition,\n ...(fallback.mode ? { browserFallbackMode: fallback.mode } : {}),\n ...(fallback.challenge ? { challenge: toJsonRecord(fallback.challenge) } : {}),\n ...(fallback.preservedSessionId ? { preservedSessionId: fallback.preservedSessionId } : {}),\n ...(fallback.preservedTargetId ? { preservedTargetId: fallback.preservedTargetId } : {}),\n ...toJsonRecord(fallback.details ?? {})\n };\n const hint = readProviderIssueHint({\n reasonCode,\n details: details as Record<string, unknown>\n });\n const guidance = hint\n ? buildProviderIssueGuidance({ provider: args.provider, hint, details })\n : undefined;\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: guidance\n ? { ...details, guidance }\n : details\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 /(^|\\.)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;\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","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 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: toPositiveInt(\n asNumber(filters.hopLimit) ?? options.defaultTraversal?.hopLimit,\n DEFAULT_TRAVERSAL.hopLimit\n ),\n expansionPerRecord: toPositiveInt(\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 const pageRows = await options.search({\n ...input,\n filters: {\n ...(input.filters ?? {}),\n page\n }\n }, context);\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\nconst TARGETED_PLATFORMS = new Set<SocialPlatform>([\"x\", \"bluesky\", \"reddit\", \"facebook\"]);\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 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): boolean => TARGETED_PLATFORMS.has(platform);\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 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 (pathname === \"/\" || pathname === \"/login\" || (options.includeSearchRoute && pathname === \"/search\")) {\n return true;\n }\n const pathSegment = firstPathSegment(pathname);\n return pathSegment !== null && REDDIT_BLOCKED_FIRST_SEGMENTS.has(pathSegment);\n};\n\nconst isRootShellUrl = (platform: SocialPlatform, 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 default:\n return false;\n }\n};\n\nconst isBlockedExpansionPath = (platform: SocialPlatform, 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 default:\n return false;\n }\n};\n\nconst isFirstPartySearchRoute = (platform: SocialPlatform, 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\";\n case \"facebook\":\n return isPrimaryFacebookHost(host) && isFacebookSearchLikePath(pathname);\n default:\n return false;\n }\n};\n\nconst collectSocialSearchLinkEvidence = (\n platform: SocialPlatform,\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: SocialPlatform, url: string): boolean => {\n const parsed = parseUrl(url);\n if (!parsed) {\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 if (isFirstPartyHelpHost(platform, host)) {\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 isRetainableFacebookSearchSupportUrl = (url: string): boolean => {\n const parsed = parseUrl(url);\n if (parsed === null || !isPrimaryFacebookHost(parsed.hostname)) {\n return false;\n }\n if (isBlockedFacebookNonContentUrl(parsed, { includeSearchRoute: true })) {\n return false;\n }\n if (isFirstPartySearchRoute(\"facebook\", parsed)) {\n return false;\n }\n return !isUsableFacebookSearchEvidenceUrl(url);\n};\n\nconst hasFacebookSearchResultSignals = (\n input: { url: string; title?: string; content?: string; links?: readonly string[] }\n): boolean => {\n const parsed = parseUrl(input.url);\n if (parsed === null || !isFirstPartySearchRoute(\"facebook\", parsed)) {\n return false;\n }\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 supportLinkCount = evidence.usableLinks.filter(isRetainableFacebookSearchSupportUrl).length;\n if (markerCount >= 2) {\n return true;\n }\n if (!hasSearchHeading) {\n return false;\n }\n if (markerCount >= 1) {\n return true;\n }\n return supportLinkCount >= 2;\n};\n\nconst isUsableSocialSearchContentUrl = (\n platform: SocialPlatform,\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 default:\n return false;\n }\n};\n\nconst hasUsableFirstPartySearchEvidence = (\n platform: SocialPlatform,\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 && 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 (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 ) {\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(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: SocialPlatform,\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 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: toPositiveInt(\n asNumber(filters.hopLimit) ?? options.defaultTraversal?.hopLimit,\n DEFAULT_TRAVERSAL.hopLimit\n ),\n expansionPerRecord: toPositiveInt(\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(/&amp;/g, \"&\")\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&#39;/g, \"'\")\n .replace(/&quot;/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, providerErrorCodeFromReasonCode } from \"../errors\";\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 JsonValue,\n ProviderContext,\n ProviderFetchInput,\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(/&amp;/g, \"&\")\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&#39;/g, \"'\")\n .replace(/&quot;/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;\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\nconst fetchPage = async (url: string, context: ProviderContext): Promise<{ status: number; url: string; html: string }> => {\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 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[\"search\"]) => {\n if (options) return options;\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);\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 }\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);\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: 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 ...(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.search),\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 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 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);\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 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 return {\n record: {\n status: 200,\n url: resolvedUrl,\n html: readFallbackString(fallback.output, \"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 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\\/|[?&]id=\\d+/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(/&amp;/gi, \"&\")\n .replace(/&#x2f;/gi, \"/\")\n .replace(/&#47;/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 }\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): ProviderIssueHint | null => {\n const providerShell = requiresBrowserAssistance(profile, fetched.url, fetched.html);\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 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\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 = candidates.length === 0\n ? classifySearchPageIssue(profile, fetched, extracted, content)\n : null;\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 const reasonCode = pageIssue.reasonCode;\n const providerShell = requiresBrowserAssistance(profile, fetched.url, fetched.html);\n throw new ProviderRuntimeError(\n providerErrorCodeFromReasonCode(reasonCode),\n reasonCode === \"token_required\"\n ? `Authentication required for ${fetched.url}`\n : `Detected anti-bot challenge while retrieving ${fetched.url}`,\n {\n provider: providerId,\n source: SHOPPING_SOURCE,\n retryable: reasonCode === \"env_limited\",\n reasonCode,\n details: {\n ...applyProviderIssueHint({\n status: fetched.status,\n url: fetched.url,\n ...(typeof extracted.metadata.title === \"string\" ? { title: extracted.metadata.title } : {}),\n ...(content ? { message: content } : {}),\n ...(providerShell?.reason ? { providerShell: providerShell.reason } : {})\n }, pageIssue),\n ...browserFallbackObservationDetails(fetched.browserFallback)\n }\n }\n );\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 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","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 { createArtifactBundle, type ArtifactFile } from \"./artifacts\";\nimport {\n summarizePrimaryProviderIssue,\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 type InspiredesignCaptureEvidence,\n type InspiredesignFollowthrough,\n type InspiredesignReferenceEvidence\n} from \"./inspiredesign-contract\";\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 { 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 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 ProviderExecutor {\n search: (\n input: ProviderCallResultByOperation[\"search\"],\n options?: ProviderRunOptions\n ) => Promise<ProviderAggregateResult>;\n fetch: (\n input: ProviderCallResultByOperation[\"fetch\"],\n options?: ProviderRunOptions\n ) => Promise<ProviderAggregateResult>;\n getAntiBotSnapshots?: (providerIds?: string[]) => ProviderAntiBotSnapshot[];\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 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 urls?: string[];\n captureMode?: InspiredesignCaptureMode;\n includePrototypeGuidance?: boolean;\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 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 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: ProviderExecutor,\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: ProviderExecutor,\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: ProviderExecutor,\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: ProviderExecutor,\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 return guidance && typeof guidance === \"object\" && !Array.isArray(guidance)\n ? guidance as ProviderNextStepGuidance\n : undefined;\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 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};\n\nconst PRODUCT_ASSET_FETCH_TIMEOUT_MS = 15_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 \"social:search:index\"\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_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_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 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 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 return () => Math.max(1, timeoutMs - Math.max(0, Date.now() - startedAtMs));\n};\n\ntype InspiredesignResolvedInput = Omit<InspiredesignRunInput, \"brief\" | \"urls\" | \"captureMode\"> & {\n brief: string;\n urls: string[];\n captureMode: InspiredesignCaptureMode;\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\"]);\n\ntype InspiredesignCaptureOutcome = {\n captureStatus: InspiredesignReferenceEvidence[\"captureStatus\"];\n capture?: InspiredesignCaptureEvidence | null;\n captureFailure?: string;\n};\n\nconst serializeInspiredesignRunInput = (input: InspiredesignResolvedInput): Record<string, JsonValue> => ({\n brief: input.brief,\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 ...(typeof input.useCookies === \"boolean\" ? { useCookies: input.useCookies } : {}),\n ...(input.challengeAutomationMode ? { challengeAutomationMode: input.challengeAutomationMode } : {}),\n ...(input.cookiePolicyOverride ? { cookiePolicyOverride: input.cookiePolicyOverride } : {})\n});\n\nconst parseInspiredesignEnvelopeInput = (input: WorkflowResumeEnvelope[\"input\"]): InspiredesignRunInput => ({\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 ...(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\" && input.outputDir.length > 0 ? { outputDir: input.outputDir } : {}),\n ...(typeof input.ttlHours === \"number\" ? { ttlHours: input.ttlHours } : {}),\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\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 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 return {\n ...input,\n brief,\n urls: normalizeInspiredesignUrls(input.urls),\n captureMode: input.captureMode ?? \"off\",\n mode: input.mode ?? \"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 buildInspiredesignFetchOptions = (\n workflowInput: InspiredesignResolvedInput,\n envelope: WorkflowResumeEnvelope,\n timeoutMs?: number\n): ProviderRunOptions => withWorkflowResumeEnvelopeIntent(\n withChallengeAutomationOverride(\n withCookieOverrides({\n ...(typeof timeoutMs === \"number\" ? { timeoutMs } : {})\n }, workflowInput),\n workflowInput\n ),\n \"workflow.inspiredesign\",\n envelope\n);\n\nconst hasInspiredesignCaptureEvidence = (\n capture: InspiredesignCaptureEvidence | null | undefined\n): capture is InspiredesignCaptureEvidence => {\n if (!capture) return false;\n return Boolean(capture.title || capture.snapshot || capture.dom || capture.clone);\n};\n\nconst captureInspiredesignReference = async (\n url: string,\n captureMode: InspiredesignCaptureMode,\n workflowInput: InspiredesignResolvedInput,\n captureReference: InspiredesignWorkflowOptions[\"captureReference\"],\n timeoutMs?: number\n): Promise<InspiredesignCaptureOutcome> => {\n if (captureMode === \"off\") {\n return { captureStatus: \"off\" };\n }\n if (!captureReference) {\n return {\n captureStatus: \"failed\",\n captureFailure: \"Deep capture requested, but no browser capture callback was available.\"\n };\n }\n try {\n const capture = await captureReference(url, {\n timeoutMs,\n useCookies: workflowInput.useCookies,\n challengeAutomationMode: workflowInput.challengeAutomationMode,\n cookiePolicyOverride: workflowInput.cookiePolicyOverride\n });\n if (!hasInspiredesignCaptureEvidence(capture)) {\n return {\n captureStatus: \"failed\",\n captureFailure: \"Deep capture did not return usable snapshot, DOM, or clone evidence.\"\n };\n }\n return {\n captureStatus: \"captured\",\n capture\n };\n } catch (error) {\n return {\n captureStatus: \"failed\",\n captureFailure: error instanceof Error ? error.message : \"Deep capture failed.\"\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 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 buildInspiredesignReference = (\n url: string,\n result: ProviderAggregateResult,\n capture: InspiredesignCaptureOutcome\n): InspiredesignReferenceEvidence => {\n const primary = getInspiredesignPrimaryRecord(result, url);\n const title = primary?.title ?? capture.capture?.title;\n const excerpt = excerptFromInspiredesignRecord(primary);\n const fetchStatus: InspiredesignReferenceEvidence[\"fetchStatus\"] = result.records.length > 0 ? \"captured\" : \"failed\";\n return {\n id: createHash(\"sha256\").update(url).digest(\"hex\").slice(0, 12),\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 ...(capture.capture ? { capture: capture.capture } : {})\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 summary = `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: [\n \"Rerun inspiredesign after configuring providers.cookieSource for the protected references you need to capture.\",\n ...retryUrls\n ]\n }\n };\n};\n\nconst buildInspiredesignMeta = (\n runtime: ProviderExecutor,\n workflowInput: InspiredesignResolvedInput,\n references: InspiredesignReferenceEvidence[],\n failures: ProviderFailureEntry[],\n followthrough: InspiredesignFollowthrough\n): Record<string, unknown> => {\n const failedCaptures = references.filter((reference) => reference.captureStatus === \"failed\");\n let reasonCodeDistribution = summarizeReasonCodeDistribution(failures);\n let meta = withCamelCasePrimaryConstraintMeta(withReasonCodeDistributionMeta({\n selection: {\n urls: workflowInput.urls,\n capture_mode: workflowInput.captureMode,\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) => reference.fetchStatus === \"failed\").length,\n failed_captures: failedCaptures.length\n },\n alerts: buildWorkflowAlerts(runtime, failures)\n }, reasonCodeDistribution), failures);\n if (!meta.primaryConstraint) {\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 recommendedSkills: followthrough.recommendedSkills,\n deepCaptureRecommendation: followthrough.deepCaptureRecommendation,\n contractScope: followthrough.contractScope\n };\n};\n\nconst inferBrandFromContent = (content: string | undefined): string | undefined => {\n const normalized = normalizePlainText(content);\n if (!normalized) return undefined;\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 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 inferTitleFromContent = (content: string | undefined): 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 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 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 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),\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 extractBrandFromTitle(record.title),\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),\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\ntype ResearchSanitizeReason =\n | \"js_required_shell\"\n | \"login_shell\"\n | \"not_found_shell\"\n | \"search_index_shell\"\n | \"search_results_shell\";\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 (RESEARCH_LOGIN_SHELL_RE.test(combined) || url.includes(\"/login\")) {\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 (!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} => {\n const reasonDistribution: Record<string, number> = {};\n const sanitizedRecords = records.filter((record) => {\n const reason = classifyResearchShellRecord(record);\n if (!reason) return true;\n reasonDistribution[reason] = (reasonDistribution[reason] ?? 0) + 1;\n return false;\n });\n\n return {\n records: sanitizedRecords,\n sanitizedCount: records.length - sanitizedRecords.length,\n reasonDistribution\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 classifyInvalidProductTarget = (\n record: NormalizedRecord\n): { reason: \"http_status\" | \"not_found_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 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 workflowInput = envelope.input as unknown as ResearchRunInput;\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 stepOptions = withChallengeAutomationOverride(withCookieOverrides({\n source: step.input.source,\n ...(typeof workflowInput.timeoutMs === \"number\" ? { timeoutMs: workflowInput.timeoutMs } : {})\n }, workflowInput), workflowInput);\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 mergedRecords = removeExcludedProviders(\n [\n ...execution.searchRuns.flatMap((run) => run.result.records),\n ...execution.followUpRuns.flatMap((run) => run.result.records)\n ],\n excludedProviderSet\n );\n const sanitizedRecords = sanitizeResearchRecords(mergedRecords);\n const mergedFailures = removeExcludedProviders(\n [\n ...execution.searchRuns.flatMap((run) => run.result.failures),\n ...execution.followUpRuns.flatMap((run) => run.result.failures)\n ],\n excludedProviderSet\n );\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 noUsableResearchRecords = mergedRecords.length > 0\n && mergedFailures.length === 0\n && ranked.length === 0;\n const cookieDiagnostics = summarizeCookieDiagnostics(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 (noUsableResearchRecords && 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 (noUsableResearchRecords && 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 (noUsableResearchRecords) {\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 }, plan.compiled.autoExcludedProviders),\n metrics: {\n total_records: mergedRecords.length,\n sanitized_records: sanitizedRecords.sanitizedCount,\n sanitized_reason_distribution: sanitizedRecords.reasonDistribution,\n sanitizedReasonDistribution: sanitizedRecords.reasonDistribution,\n 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 anti_bot_pressure: antiBotPressure,\n antiBotPressure\n },\n failures: mergedFailures,\n alerts: buildWorkflowAlerts(runtime, mergedFailures)\n } as Record<string, unknown>, primaryConstraintFailures);\n const handoff = buildResearchSuccessHandoff(plan.compiled.topic);\n const responseMeta = withFollowthroughMeta(meta, handoff);\n\n const rendered = renderResearch({\n mode: workflowInput.mode,\n topic: plan.compiled.topic,\n records: ranked,\n meta: responseMeta\n });\n\n const bundle = await createArtifactBundle({\n namespace: \"research\",\n outputDir: workflowInput.outputDir,\n ttlHours: workflowInput.ttlHours,\n files: rendered.files\n });\n\n if (workflowInput.mode === \"path\") {\n return {\n ...rendered.response,\n ...handoff,\n 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 workflowInput = envelope.input as unknown as ShoppingRunInput;\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: workflowInput.outputDir,\n ttlHours: workflowInput.ttlHours,\n files: rendered.files\n });\n\n if (workflowInput.mode === \"path\") {\n return {\n ...rendered.response,\n ...handoff,\n 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: ProviderExecutor,\n input: InspiredesignRunInput | WorkflowResumeEnvelope,\n options: InspiredesignWorkflowOptions = {}\n): Promise<Record<string, unknown>> => {\n const { envelope, workflowInput } = buildInspiredesignEnvelope(input);\n const remainingTimeoutMs = createRemainingTimeoutResolver(workflowInput.timeoutMs);\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[] = [];\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 result = await runtime.fetch(\n { url },\n buildInspiredesignFetchOptions(\n workflowInput,\n buildInspiredesignStepEnvelope(workflowInput, stepTrace, index, url),\n fetchTimeoutMs\n )\n );\n observeWorkflowSignals(runtime, result);\n failures.push(...result.failures);\n const captureTimeoutMs = remainingTimeoutMs();\n const capture = await captureInspiredesignReference(\n url,\n workflowInput.captureMode,\n workflowInput,\n options.captureReference,\n captureTimeoutMs\n );\n references.push(buildInspiredesignReference(url, result, capture));\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\n const packet = buildInspiredesignPacket({\n brief: workflowInput.brief,\n urls: workflowInput.urls,\n references,\n includePrototypeGuidance: workflowInput.includePrototypeGuidance\n });\n const meta = buildInspiredesignMeta(runtime, workflowInput, references, failures, packet.followthrough);\n const rendered = renderInspiredesign({\n mode: workflowInput.mode,\n brief: workflowInput.brief,\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 meta\n });\n const bundle = await createArtifactBundle({\n namespace: \"inspiredesign\",\n outputDir: workflowInput.outputDir,\n ttlHours: workflowInput.ttlHours,\n files: rendered.files\n });\n\n if (workflowInput.mode === \"path\") {\n return {\n ...rendered.response,\n path: bundle.basePath,\n meta: {\n ...meta,\n artifact_manifest: bundle.manifest\n }\n };\n }\n\n return {\n ...rendered.response,\n artifact_path: bundle.basePath,\n meta: {\n ...meta,\n artifact_manifest: bundle.manifest\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 workflowInput = plan.input;\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 const step = plan.plan.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\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 ...timeoutOptions,\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 withChallengeAutomationOverride(\n withCookieOverrides({\n source,\n providerIds: shoppingProviderId ? [shoppingProviderId] : undefined,\n ...timeoutOptions\n }, workflowInput),\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-assets\",\n outputDir: workflowInput.output_dir,\n ttlHours: workflowInput.ttl_hours,\n files,\n manifestFileName: \"bundle-manifest.json\"\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 includeScreenshots: workflowInput.include_screenshots,\n includeAllImages: workflowInput.include_all_images,\n includeCopy: workflowInput.include_copy\n });\n const meta = withFollowthroughMeta({\n alerts: buildWorkflowAlerts(runtime, details.failures),\n failures: details.failures,\n ...(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 path: bundle.basePath,\n manifest: manifestPayload,\n product: productPayload,\n pricing,\n screenshots: screenshotPaths,\n images: imagePaths,\n meta\n };\n};\n","import { mkdir, readdir, readFile, rm, stat, writeFile } from \"fs/promises\";\nimport { dirname, join, resolve } from \"path\";\nimport { randomUUID } from \"crypto\";\nimport { tmpdir } from \"os\";\n\nexport const DEFAULT_ARTIFACT_TTL_HOURS = 72;\nexport const MAX_ARTIFACT_TTL_HOURS = 168;\n\ntype ArtifactContent = string | Buffer | Record<string, unknown>;\n\nexport interface ArtifactFile {\n path: string;\n content: ArtifactContent;\n}\n\nexport interface ArtifactManifest {\n run_id: string;\n created_at: string;\n ttl_hours: number;\n expires_at: string;\n files: string[];\n}\n\nexport interface ArtifactBundle {\n runId: string;\n basePath: string;\n manifest: ArtifactManifest;\n manifestFileName: string;\n}\n\nconst clampTtlHours = (value: number | undefined): number => {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) {\n return DEFAULT_ARTIFACT_TTL_HOURS;\n }\n return Math.min(MAX_ARTIFACT_TTL_HOURS, Math.floor(value));\n};\n\nconst serializeContent = (content: ArtifactContent): string | Buffer => {\n if (typeof content === \"string\" || Buffer.isBuffer(content)) {\n return content;\n }\n return `${JSON.stringify(content, null, 2)}\\n`;\n};\n\nexport const createArtifactBundle = async (args: {\n namespace: string;\n files: ArtifactFile[];\n outputDir?: string;\n ttlHours?: number;\n manifestFileName?: string;\n now?: Date;\n}): Promise<ArtifactBundle> => {\n const runId = randomUUID();\n const now = args.now ?? new Date();\n const ttlHours = clampTtlHours(args.ttlHours);\n const manifestFileName = args.manifestFileName ?? \"bundle-manifest.json\";\n const expiresAt = new Date(now.getTime() + ttlHours * 60 * 60 * 1000);\n const root = args.outputDir ? resolve(args.outputDir) : join(tmpdir(), \"opendevbrowser\");\n const basePath = join(root, args.namespace, runId);\n\n await mkdir(basePath, { recursive: true, mode: 0o700 });\n\n const writtenFiles: string[] = [];\n for (const file of args.files) {\n const filePath = join(basePath, file.path);\n const directory = dirname(filePath);\n if (directory && directory !== basePath) {\n await mkdir(directory, { recursive: true, mode: 0o700 });\n }\n await writeFile(filePath, serializeContent(file.content), { mode: 0o600 });\n writtenFiles.push(file.path);\n }\n\n const manifest: ArtifactManifest = {\n run_id: runId,\n created_at: now.toISOString(),\n ttl_hours: ttlHours,\n expires_at: expiresAt.toISOString(),\n files: [...writtenFiles, manifestFileName]\n };\n\n await writeFile(join(basePath, manifestFileName), `${JSON.stringify(manifest, null, 2)}\\n`, { mode: 0o600 });\n\n return {\n runId,\n basePath,\n manifest,\n manifestFileName\n };\n};\n\nconst isExpired = (manifest: ArtifactManifest, now: Date): boolean => {\n const expiry = new Date(manifest.expires_at);\n if (Number.isNaN(expiry.getTime())) return false;\n return expiry.getTime() <= now.getTime();\n};\n\nexport const cleanupExpiredArtifacts = async (\n rootDir: string,\n now: Date = new Date()\n): Promise<{ removed: string[]; skipped: string[] }> => {\n const removed: string[] = [];\n const skipped: string[] = [];\n\n let namespaces: string[] = [];\n try {\n namespaces = await readdir(rootDir);\n } catch {\n return { removed, skipped };\n }\n\n for (const namespace of namespaces) {\n const namespacePath = join(rootDir, namespace);\n let runs: string[] = [];\n try {\n runs = await readdir(namespacePath);\n } catch {\n continue;\n }\n\n for (const run of runs) {\n const runPath = join(namespacePath, run);\n const manifestCandidates = [join(runPath, \"bundle-manifest.json\"), join(runPath, \"manifest.json\")];\n try {\n let manifestPath: string | null = null;\n for (const candidate of manifestCandidates) {\n try {\n const candidateMetadata = await stat(candidate);\n if (candidateMetadata.isFile()) {\n manifestPath = candidate;\n break;\n }\n } catch {\n // try next manifest path\n }\n }\n if (!manifestPath) {\n skipped.push(runPath);\n continue;\n }\n\n const metadata = await stat(manifestPath);\n if (!metadata.isFile()) {\n skipped.push(runPath);\n continue;\n }\n const manifestRaw = await readFile(manifestPath, \"utf8\");\n const manifest = JSON.parse(manifestRaw) as ArtifactManifest;\n if (isExpired(manifest, now)) {\n await rm(runPath, { recursive: true, force: true });\n removed.push(runPath);\n } else {\n skipped.push(runPath);\n }\n } catch {\n skipped.push(runPath);\n }\n }\n }\n\n return { removed, skipped };\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","export const INSPIREDESIGN_HANDOFF_FILES = {\n designMarkdown: \"design.md\",\n designContract: \"design-contract.json\",\n canvasPlanRequest: \"canvas-plan.request.json\",\n designAgentHandoff: \"design-agent-handoff.json\",\n generationPlan: \"generation-plan.json\",\n implementationPlanMarkdown: \"implementation-plan.md\",\n implementationPlan: \"implementation-plan.json\",\n evidence: \"evidence.json\",\n prototypeGuidance: \"prototype-guidance.md\"\n} as const;\n\nexport const INSPIREDESIGN_HANDOFF_SKILLS = {\n bestPractices: {\n name: \"opendevbrowser-best-practices\",\n topic: \"quick start\"\n },\n designAgent: {\n name: \"opendevbrowser-design-agent\",\n topic: \"canvas-contract\"\n }\n} as const;\n\ntype InspiredesignHandoffSkill =\n (typeof INSPIREDESIGN_HANDOFF_SKILLS)[keyof typeof INSPIREDESIGN_HANDOFF_SKILLS];\n\nconst formatSkillReference = (skill: InspiredesignHandoffSkill): string => (\n `${skill.name} \"${skill.topic}\"`\n);\n\nconst formatSkillLoadCommand = (skill: InspiredesignHandoffSkill): string => (\n `opendevbrowser_skill_load ${skill.name} \"${skill.topic}\"`\n);\n\nexport const INSPIREDESIGN_HANDOFF_COMMANDS = {\n loadBestPractices: formatSkillLoadCommand(INSPIREDESIGN_HANDOFF_SKILLS.bestPractices),\n loadDesignAgent: formatSkillLoadCommand(INSPIREDESIGN_HANDOFF_SKILLS.designAgent),\n continueInCanvas: `opendevbrowser canvas --command canvas.plan.set --params-file ./${INSPIREDESIGN_HANDOFF_FILES.canvasPlanRequest}`\n} as const;\n\nexport const INSPIREDESIGN_HANDOFF_RECOMMENDED_SKILLS = [\n formatSkillReference(INSPIREDESIGN_HANDOFF_SKILLS.bestPractices),\n formatSkillReference(INSPIREDESIGN_HANDOFF_SKILLS.designAgent)\n] as const;\n\nexport const INSPIREDESIGN_HANDOFF_GUIDANCE = {\n prepareCanvasPlanRequest: `Fill canvasSessionId, leaseId, and documentId in ${INSPIREDESIGN_HANDOFF_FILES.canvasPlanRequest} before running ${INSPIREDESIGN_HANDOFF_COMMANDS.continueInCanvas}.`,\n deepCaptureRecommendation: \"Rerun inspiredesign with captureMode=deep only when you need richer evidence for visual hierarchy, protected references, or capture-specific debugging.\"\n} as const;\n\nexport const buildInspiredesignFollowthroughSummary = (): string => (\n `Continue in OpenDevBrowser Canvas with ${INSPIREDESIGN_HANDOFF_FILES.canvasPlanRequest} and ${INSPIREDESIGN_HANDOFF_FILES.designAgentHandoff}, load ${INSPIREDESIGN_HANDOFF_RECOMMENDED_SKILLS[0]} plus ${INSPIREDESIGN_HANDOFF_RECOMMENDED_SKILLS[1]} before implementation, and rerun with captureMode=deep only when you need richer evidence.`\n);\n\nexport const buildInspiredesignNextStep = (): string => (\n `${INSPIREDESIGN_HANDOFF_GUIDANCE.prepareCanvasPlanRequest} Then run ${INSPIREDESIGN_HANDOFF_COMMANDS.continueInCanvas}, confirm planStatus=accepted, then patch only the governance blocks listed in ${INSPIREDESIGN_HANDOFF_FILES.designAgentHandoff}.`\n);\n","import { canonicalizeUrl } from \"./web/crawler\";\nimport type { ResearchRecord } from \"./enrichment\";\nimport type { InspiredesignFollowthrough, InspiredesignImplementationPlan } from \"./inspiredesign-contract\";\nimport type { CanvasDesignGovernance, CanvasGenerationPlan } from \"../canvas/types\";\nimport {\n INSPIREDESIGN_HANDOFF_FILES,\n INSPIREDESIGN_HANDOFF_GUIDANCE\n} from \"../inspiredesign/handoff\";\n\nexport type RenderMode = \"compact\" | \"json\" | \"md\" | \"context\" | \"path\";\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 compactResearchLines = (records: ResearchRecord[], meta: Record<string, unknown>): string[] => {\n if (records.length === 0) {\n const summary = primaryConstraintSummaryFromMeta(meta);\n return summary\n ? [\n \"No records matched the requested timebox.\",\n `Primary constraint: ${summary}`\n ]\n : [\"No records matched the requested timebox.\"];\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\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 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 = {\n topic: args.topic,\n highlights: lines,\n records: args.records,\n meta: args.meta\n };\n\n const files = [\n { path: \"summary.md\", content: markdown },\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 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 meta: Record<string, unknown>;\n}): {\n response: Record<string, unknown>;\n files: Array<{ path: string; content: string | Record<string, unknown> }>;\n} => {\n const summary = [\n `Brief: ${args.brief}`,\n `References: ${args.urls.length}`,\n `Profile: ${args.generationPlan.visualDirection.profile}`\n ].join(\"\\n\");\n const contextPayload = {\n brief: args.brief,\n urls: args.urls,\n designContract: args.designContract,\n canvasPlanRequest: args.canvasPlanRequest,\n designAgentHandoff: args.designAgentHandoff,\n generationPlan: args.generationPlan,\n implementationPlan: args.implementationPlan,\n designMarkdown: args.designMarkdown,\n implementationPlanMarkdown: args.implementationPlanMarkdown,\n prototypeGuidanceMarkdown: args.prototypeGuidanceMarkdown,\n evidence: args.evidence,\n meta: args.meta\n };\n const suggestedSteps = [\n {\n reason: \"Load the baseline workflow runbook before implementation.\",\n command: args.designAgentHandoff.commandExamples.loadBestPractices\n },\n {\n reason: \"Load the Canvas contract lane before patching.\",\n command: args.designAgentHandoff.commandExamples.loadDesignAgent\n },\n {\n reason: INSPIREDESIGN_HANDOFF_GUIDANCE.prepareCanvasPlanRequest,\n command: args.designAgentHandoff.commandExamples.continueInCanvas\n },\n {\n reason: args.designAgentHandoff.deepCaptureRecommendation\n }\n ];\n const files: Array<{ path: string; content: string | Record<string, unknown> }> = [\n { path: INSPIREDESIGN_HANDOFF_FILES.designMarkdown, content: args.designMarkdown },\n { path: INSPIREDESIGN_HANDOFF_FILES.designContract, content: args.designContract },\n { path: INSPIREDESIGN_HANDOFF_FILES.canvasPlanRequest, content: args.canvasPlanRequest },\n { path: INSPIREDESIGN_HANDOFF_FILES.designAgentHandoff, content: args.designAgentHandoff },\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 ];\n if (args.prototypeGuidanceMarkdown) {\n files.push({ path: INSPIREDESIGN_HANDOFF_FILES.prototypeGuidance, content: args.prototypeGuidanceMarkdown });\n }\n\n if (args.mode === \"compact\") {\n return {\n response: {\n mode: args.mode,\n summary,\n followthroughSummary: args.designAgentHandoff.summary,\n suggestedNextAction: args.designAgentHandoff.nextStep,\n suggestedSteps,\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 urls: args.urls,\n canvasPlanRequest: args.canvasPlanRequest,\n designAgentHandoff: args.designAgentHandoff,\n designContract: args.designContract,\n generationPlan: args.generationPlan,\n implementationPlan: args.implementationPlan,\n prototypeGuidanceMarkdown: args.prototypeGuidanceMarkdown,\n evidence: args.evidence,\n followthroughSummary: args.designAgentHandoff.summary,\n suggestedNextAction: args.designAgentHandoff.nextStep,\n suggestedSteps,\n meta: args.meta\n },\n files\n };\n }\n if (args.mode === \"md\") {\n return {\n response: {\n mode: args.mode,\n markdown: args.designMarkdown,\n implementationPlanMarkdown: args.implementationPlanMarkdown,\n prototypeGuidanceMarkdown: args.prototypeGuidanceMarkdown,\n followthroughSummary: args.designAgentHandoff.summary,\n suggestedNextAction: args.designAgentHandoff.nextStep,\n suggestedSteps,\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 followthroughSummary: args.designAgentHandoff.summary,\n suggestedNextAction: args.designAgentHandoff.nextStep,\n suggestedSteps,\n meta: args.meta\n },\n files\n };\n }\n\n return {\n response: {\n mode: \"path\",\n followthroughSummary: args.designAgentHandoff.summary,\n suggestedNextAction: args.designAgentHandoff.nextStep,\n suggestedSteps,\n meta: args.meta\n },\n files\n };\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 CanvasDesignGovernance,\n CanvasGenerationPlan,\n CanvasNavigationModel,\n CanvasVisualDirectionProfile\n} from \"../canvas/types\";\nimport {\n INSPIREDESIGN_HANDOFF_COMMANDS,\n INSPIREDESIGN_HANDOFF_GUIDANCE,\n INSPIREDESIGN_HANDOFF_RECOMMENDED_SKILLS,\n INSPIREDESIGN_HANDOFF_FILES,\n buildInspiredesignFollowthroughSummary,\n buildInspiredesignNextStep\n} from \"../inspiredesign/handoff\";\nimport type { JsonValue } from \"./types\";\n\ntype JsonRecord = Record<string, JsonValue>;\ntype FetchStatus = \"captured\" | \"failed\" | \"skipped\";\ntype CaptureStatus = \"off\" | \"captured\" | \"failed\";\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};\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};\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 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\nexport type InspiredesignPacket = {\n designContract: CanvasDesignGovernance;\n generationPlan: CanvasGenerationPlan;\n canvasPlanRequest: CanvasPlanRequestTemplate;\n followthrough: InspiredesignFollowthrough;\n designMarkdown: string;\n implementationPlan: InspiredesignImplementationPlan;\n implementationPlanMarkdown: string;\n prototypeGuidanceMarkdown: string | null;\n evidence: JsonRecord;\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};\n\nexport type InspiredesignFollowthrough = {\n summary: string;\n nextStep: string;\n recommendedSkills: string[];\n commandExamples: {\n loadBestPractices: string;\n loadDesignAgent: string;\n continueInCanvas: string;\n };\n deepCaptureRecommendation: string;\n contractScope: InspiredesignContractScope;\n implementationContext: InspiredesignImplementationContext;\n};\n\nexport type BuildInspiredesignPacketInput = {\n brief: string;\n urls: string[];\n references: InspiredesignReferenceEvidence[];\n includePrototypeGuidance?: boolean;\n};\n\nconst BASE_CONTRACT_TEMPLATE: DesignContractTemplate = designContractTemplateJson;\nconst BASE_PLAN_REQUEST_TEMPLATE = generationPlanTemplateJson as CanvasPlanRequestTemplate;\nconst BASE_GENERATION_PLAN: CanvasGenerationPlan = BASE_PLAN_REQUEST_TEMPLATE.generationPlan;\n\nconst PROFILE_MATCHERS: ReadonlyArray<{\n profile: CanvasVisualDirectionProfile;\n keywords: readonly string[];\n}> = [\n { profile: \"auth-focused\", keywords: [\"auth\", \"login\", \"signin\", \"sign-in\", \"signup\", \"sign-up\", \"onboarding\"] },\n { profile: \"settings-system\", keywords: [\"settings\", \"preferences\", \"account\", \"profile\", \"billing\"] },\n { profile: \"ops-control\", keywords: [\"dashboard\", \"admin\", \"control\", \"analytics\", \"monitor\", \"reporting\"] },\n { profile: \"documentation\", keywords: [\"docs\", \"documentation\", \"knowledge base\", \"reference\", \"guide\"] },\n { profile: \"commerce-system\", keywords: [\"shop\", \"commerce\", \"pricing\", \"checkout\", \"product page\", \"catalog\"] }\n] as const;\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: \"reference-first documentation\",\n visualPersonality: \"legible, calm, highly structured\",\n brandTone: \"expert and accessible\",\n hierarchyPrinciples: [\"Make scanning effortless.\", \"Keep code, steps, and warnings visually distinct.\"],\n interactionPhilosophy: \"Light motion, sticky wayfinding, strong anchor visibility.\",\n navigationModel: \"sidebar\",\n layoutApproach: \"docs-shell\",\n pagePatterns: [\"Docs shell\", \"Procedure section\", \"Reference table block\"],\n componentSequence: [\"Sidebar\", \"Search\", \"Anchored headings\", \"Code blocks\", \"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\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 hasKeyword = (value: string, keywords: readonly string[]): boolean => {\n const haystack = value.toLowerCase();\n return keywords.some((keyword) => haystack.includes(keyword));\n};\n\nconst classifyProfile = (brief: string, references: InspiredesignReferenceEvidence[]): CanvasVisualDirectionProfile => {\n const combined = [brief, ...references.map((reference) => `${reference.title ?? \"\"} ${reference.excerpt ?? \"\"}`)]\n .join(\" \")\n .toLowerCase();\n return PROFILE_MATCHERS.find((matcher) => hasKeyword(combined, matcher.keywords))?.profile ?? \"product-story\";\n};\n\nconst resolveThemeStrategy = (brief: string, references: InspiredesignReferenceEvidence[]): CanvasGenerationPlan[\"visualDirection\"][\"themeStrategy\"] => {\n const combined = `${brief} ${references.map((reference) => reference.excerpt ?? \"\").join(\" \")}`.toLowerCase();\n return combined.includes(\"dark\")\n ? \"light-dark-parity\"\n : \"single-theme\";\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 buildGenerationPlan = (\n brief: string,\n profile: CanvasVisualDirectionProfile,\n references: InspiredesignReferenceEvidence[]\n): CanvasGenerationPlan => {\n const plan = cloneTemplate(BASE_GENERATION_PLAN);\n plan.targetOutcome.summary = summarizeBrief(brief);\n plan.visualDirection.profile = profile;\n plan.visualDirection.themeStrategy = resolveThemeStrategy(brief, references);\n plan.layoutStrategy.approach = PROFILE_CONFIG[profile].layoutApproach;\n plan.layoutStrategy.navigationModel = PROFILE_CONFIG[profile].navigationModel;\n plan.componentStrategy.interactionStates = [\"default\", \"hover\", \"focus\", \"disabled\", \"loading\"];\n plan.validationTargets.requiredThemes = plan.visualDirection.themeStrategy === \"light-dark-parity\"\n ? [\"light\", \"dark\"]\n : [\"light\"];\n return plan;\n};\n\nconst buildIntentBlock = (brief: string, urls: string[], references: InspiredesignReferenceEvidence[]): JsonRecord => {\n const intent = cloneTemplate(BASE_CONTRACT_TEMPLATE.intent);\n return {\n ...intent,\n task: summarizeBrief(brief),\n brief,\n briefHash: referenceFingerprint(brief),\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 = (profile: CanvasVisualDirectionProfile): 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 };\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 = (profile: CanvasVisualDirectionProfile): JsonRecord => {\n const block = cloneTemplate(BASE_CONTRACT_TEMPLATE.layoutSystem);\n return {\n ...block,\n pagePatterns: PROFILE_CONFIG[profile].pagePatterns\n };\n};\n\nconst buildTypographySystemBlock = (): JsonRecord => {\n const block = cloneTemplate(BASE_CONTRACT_TEMPLATE.typographySystem);\n return {\n ...block,\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 = (profile: CanvasVisualDirectionProfile): JsonRecord => {\n const colors = PROFILE_CONFIG[profile].colors;\n return {\n paletteName: `${profile}-default`,\n tokens: colors,\n contrastRequirements: {\n bodyText: \"4.5:1\",\n largeText: \"3:1\",\n focusRing: \"3:1\"\n }\n };\n};\n\nconst buildSurfaceSystemBlock = (): JsonRecord => ({\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 = (): JsonRecord => {\n const block = cloneTemplate(BASE_CONTRACT_TEMPLATE.motionSystem);\n return {\n ...block,\n durations: {\n quick: \"120ms\",\n standard: \"180ms\",\n emphasis: \"240ms\"\n }\n };\n};\n\nconst buildResponsiveSystemBlock = (): JsonRecord => {\n const block = cloneTemplate(BASE_CONTRACT_TEMPLATE.responsiveSystem);\n return {\n ...block,\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: [\"css\"],\n threeD: []\n});\n\nconst buildRuntimeBudgetsBlock = (plan: CanvasGenerationPlan): JsonRecord => ({\n maxHeroActions: 2,\n maxPrimarySections: 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 = (profile: CanvasVisualDirectionProfile): JsonRecord => {\n const block = cloneTemplate(BASE_CONTRACT_TEMPLATE.navigationModel);\n return {\n ...block,\n primaryRouteModel: `Use a ${PROFILE_CONFIG[profile].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: CanvasGenerationPlan\n): CanvasPlanRequestTemplate => ({\n ...cloneTemplate(BASE_PLAN_REQUEST_TEMPLATE),\n requestId: `req_plan_${referenceFingerprint(brief).slice(0, 12)}`,\n generationPlan\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 buildFollowthrough = (generationPlan: CanvasGenerationPlan): InspiredesignFollowthrough => ({\n summary: buildInspiredesignFollowthroughSummary(),\n nextStep: buildInspiredesignNextStep(),\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.visualDirection.profile),\n asyncModel: buildAsyncModelBlock(),\n performanceModel: buildPerformanceModelBlock()\n }\n});\n\nconst buildDesignContract = (\n brief: string,\n urls: string[],\n references: InspiredesignReferenceEvidence[],\n plan: CanvasGenerationPlan\n): CanvasDesignGovernance => ({\n intent: buildIntentBlock(brief, urls, references),\n generationPlan: plan,\n designLanguage: buildDesignLanguageBlock(plan.visualDirection.profile),\n contentModel: buildContentModelBlock(brief, references),\n layoutSystem: buildLayoutSystemBlock(plan.visualDirection.profile),\n typographySystem: buildTypographySystemBlock(),\n colorSystem: buildColorSystemBlock(plan.visualDirection.profile),\n surfaceSystem: buildSurfaceSystemBlock(),\n iconSystem: buildIconSystemBlock(),\n motionSystem: buildMotionSystemBlock(),\n responsiveSystem: buildResponsiveSystemBlock(),\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\nconst buildImplementationPlan = (\n brief: string,\n profile: CanvasVisualDirectionProfile,\n references: InspiredesignReferenceEvidence[]\n): InspiredesignImplementationPlan => ({\n architectureRecommendation: \"Implement the surface as token-first components using shared semantic CSS variables, then compose page sections from those primitives before adding any page-specific polish.\",\n tokenStrategy: buildTokenStrategy(profile),\n componentBuildPlan: buildComponentBuildPlan(profile),\n pageAssemblyPlan: [\n \"Start with the shell and primary navigation pattern.\",\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 \"Keep hover, focus, loading, success, and error states visually distinct.\",\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 \"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 references.length === 0\n ? \"No live references were supplied, so visual cues are derived entirely from the written brief.\"\n : \"Live references were reduced into reusable patterns; unique brand assets should still be recreated, not copied.\",\n \"Any missing interaction states must be validated during visual QA.\"\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 \"Run accessibility, responsive, and browser QA before final polish.\"\n ]\n});\n\nconst formatBulletList = (items: string[]): string => items.map((item) => `- ${item}`).join(\"\\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 if (reference.fetchStatus === \"captured\") return \"Content and structural cues inferred from fetched page data.\";\n return \"Only operator brief context was available for this reference.\";\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 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: ${reference.capture?.snapshot ? clipText(reference.capture.snapshot.content, 180) : 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 resolveProfileConfigFromGenerationPlan = (\n generationPlan: CanvasDesignGovernance[\"generationPlan\"]\n): ProfileConfig => {\n if (!generationPlan || typeof generationPlan !== \"object\" || !(\"visualDirection\" in generationPlan)) {\n throw new Error(\"Inspiredesign design contract requires a generation plan.\");\n }\n const visualDirection = generationPlan.visualDirection;\n if (!visualDirection || typeof visualDirection !== \"object\" || !(\"profile\" in visualDirection)) {\n throw new Error(\"Inspiredesign design contract requires a visual direction profile.\");\n }\n const profile = visualDirection.profile;\n if (typeof profile !== \"string\" || !(profile in PROFILE_CONFIG)) {\n throw new Error(\"Inspiredesign design contract profile is invalid.\");\n }\n return PROFILE_CONFIG[profile as CanvasVisualDirectionProfile];\n};\n\nconst renderGovernanceMarkdown = (\n designContract: CanvasDesignGovernance,\n implementationPlan: InspiredesignImplementationPlan\n): string => {\n const profileConfig = resolveProfileConfigFromGenerationPlan(designContract.generationPlan);\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 \"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 formatRecordList(implementationPlan.tokenStrategy.typography),\n \"\",\n \"## 4.6 Spacing and Layout System\",\n formatRecordList(implementationPlan.tokenStrategy.spacing),\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 formatRecordList(implementationPlan.tokenStrategy.motion),\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 ]),\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 Component Build Plan\",\n implementationPlan.componentBuildPlan.map((component, index) => (\n `${index + 1}. ${component.name}: ${component.purpose}`\n )).join(\"\\n\"),\n \"\",\n \"## 5.4 Page Assembly Plan\",\n formatBulletList(implementationPlan.pageAssemblyPlan),\n \"\",\n \"## 5.5 State and Interaction Plan\",\n formatBulletList(implementationPlan.stateAndInteractionPlan),\n \"\",\n \"## 5.6 Accessibility Implementation Checklist\",\n formatBulletList(implementationPlan.accessibilityChecklist),\n \"\",\n \"## 5.7 Responsive Implementation Checklist\",\n formatBulletList(implementationPlan.responsiveChecklist),\n \"\",\n \"## 5.8 Risks and Ambiguities\",\n formatBulletList(implementationPlan.risksAndAmbiguities),\n \"\",\n \"## 5.9 Recommended Build Sequence\",\n implementationPlan.buildSequence.map((step, index) => `${index + 1}. ${step}`).join(\"\\n\")\n ].join(\"\\n\");\n};\n\nconst renderPrototypeGuidance = (profile: CanvasVisualDirectionProfile): string => {\n return [\n \"# 6. Optional Prototype Plan\",\n \"\",\n \"- page structure: establish the shell, hero or primary action zone, proof sections, and footer in that order.\",\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: provide visible focus, compact hover feedback, and reduced-motion-safe entry transitions.\",\n \"- HTML skeleton guidance: start with one main landmark, one primary CTA group, and semantic sections for proof or detail bands.\",\n \"- styling approach: define CSS variables first, then map components to semantic tokens rather than raw values.\",\n \"- first prototype should include vs omit: include shell, hero, CTA, one proof section, and one form or action cluster; omit analytics, heavy animation, and tertiary content until hierarchy is proven.\"\n ].join(\"\\n\");\n};\n\nconst renderDeliverablesSummary = (includePrototypeGuidance: 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 \"Ready-to-fill `canvasPlanRequest` JSON for `canvas.plan.set`\",\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\nconst buildEvidencePayload = (\n brief: string,\n urls: string[],\n references: InspiredesignReferenceEvidence[]\n): JsonRecord => ({\n brief,\n briefHash: referenceFingerprint(brief),\n urls,\n referenceCount: references.length,\n references: references.map((reference) => toReferenceEvidenceJson(reference))\n});\n\nconst toCaptureEvidenceJson = (capture: InspiredesignCaptureEvidence | null | undefined): JsonValue => {\n if (!capture) return null;\n return {\n ...(capture.title ? { title: capture.title } : {}),\n ...(capture.snapshot ? { snapshot: capture.snapshot } : {}),\n ...(capture.dom ? { dom: capture.dom } : {}),\n ...(capture.clone ? { clone: capture.clone } : {})\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.capture)\n});\n\nexport const buildInspiredesignPacket = (input: BuildInspiredesignPacketInput): InspiredesignPacket => {\n const brief = trimText(input.brief);\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 profile = classifyProfile(brief, references);\n const generationPlan = buildGenerationPlan(brief, profile, references);\n const canvasPlanRequest = buildCanvasPlanRequest(brief, generationPlan);\n const designContract = buildDesignContract(brief, urls, references, generationPlan);\n const followthrough = buildFollowthrough(generationPlan);\n const implementationPlan = buildImplementationPlan(brief, profile, references);\n const governanceMarkdown = renderGovernanceMarkdown(designContract, implementationPlan);\n const implementationPlanMarkdown = renderImplementationMarkdown(implementationPlan);\n const prototypeGuidanceMarkdown = input.includePrototypeGuidance\n ? renderPrototypeGuidance(profile)\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: ${PROFILE_CONFIG[profile].direction}.`,\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 references.length > 0\n ? references.map(renderReferenceMarkdown).join(\"\\n\\n\")\n : \"- No live inspiration source was provided. The system is derived entirely from the brief.\",\n \"\",\n \"# 3. Unified Design Direction\",\n \"\",\n formatBulletList([\n `visual personality: ${PROFILE_CONFIG[profile].visualPersonality}`,\n `tone: ${PROFILE_CONFIG[profile].brandTone}`,\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 renderGovernanceMarkdown(designContract, implementationPlan),\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(Boolean(input.includePrototypeGuidance))\n ].join(\"\\n\");\n\n return {\n designContract,\n generationPlan,\n canvasPlanRequest,\n followthrough,\n designMarkdown,\n implementationPlan,\n implementationPlanMarkdown,\n prototypeGuidanceMarkdown,\n evidence: buildEvidencePayload(brief, urls, references)\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 },\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 }\n}\n","export type WorkflowSuccessStep = {\n reason: string;\n command?: string;\n};\n\nexport type WorkflowSuccessHandoff = {\n followthroughSummary: string;\n suggestedNextAction: string;\n suggestedSteps: WorkflowSuccessStep[];\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\nconst 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 => (\n `npx opendevbrowser ${command}${args ? ` ${args}` : \"\"}`\n);\n\nconst quoteCliValue = (value: string): string => JSON.stringify(value);\n\nconst buildResearchRerunCommand = (topic: string): string => (\n cliExample(\n \"research run\",\n `--topic ${quoteCliValue(topic)} --days 14 --source-selection auto --sources web,community --mode json --output-format json`\n )\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} --mode json --output-format json`\n );\n};\n\ntype ProductVideoHandoffInput = {\n productUrl?: string;\n productName?: string;\n providerHint?: 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 return cliExample(\n \"product-video run\",\n `${target}${providerHint}${screenshots}${allImages}${includeCopy} --output-format json`\n );\n};\n\ntype MacroResolveHandoffInput = {\n expression: string;\n defaultProvider?: string;\n execute: boolean;\n blocked: boolean;\n};\n\nconst buildMacroResolveArgs = (\n input: MacroResolveHandoffInput,\n options?: {\n execute?: boolean;\n challengeAutomationMode?: \"browser\" | \"browser_with_helper\";\n includeOutputFormat?: boolean;\n }\n): string => {\n const defaultProvider = input.defaultProvider ? ` --default-provider ${input.defaultProvider}` : \"\";\n const execute = options?.execute ? \" --execute\" : \"\";\n const challenge = options?.challengeAutomationMode\n ? ` --challenge-automation-mode ${options.challengeAutomationMode}`\n : \"\";\n const outputFormat = options?.includeOutputFormat === false ? \"\" : \" --output-format json\";\n return `--expression ${quoteCliValue(input.expression)}${defaultProvider}${execute}${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): string => (\n cliExample(\"macro-resolve\", buildMacroResolveArgs(input, {\n execute: true,\n challengeAutomationMode\n }))\n);\n\nexport const buildResearchSuccessHandoff = (topic: string): WorkflowSuccessHandoff => {\n const rerunCommand = buildResearchRerunCommand(topic);\n return createSuccessHandoff(\n \"Review the ranked records and artifact bundle before turning the result into a publishable claim.\",\n `Open the returned artifact path, inspect the supporting records, and rerun ${rerunCommand} if you need a tighter evidence set.`,\n [\n { reason: \"Check which records 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 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 ${PRODUCT_VIDEO_BRIEF_HELPER_COMMAND} 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\");\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","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 = 3;\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\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: {\n include_engagement: args.input.includeEngagement ?? false,\n timebox_from: timebox.from,\n timebox_to: timebox.to\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 {\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 \"web:search:index\",\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\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 const rawUrl = typeof record.url === \"string\" ? canonicalizeUrl(record.url) : \"\";\n if (!rawUrl) {\n continue;\n }\n\n let resolvedUrl = rawUrl;\n try {\n const parsed = new URL(rawUrl);\n if (/duckduckgo\\.com$/i.test(parsed.hostname) && 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 (!resolvedUrl || !isValidHttpUrl(resolvedUrl) || /duckduckgo\\.com/i.test(resolvedUrl) || seen.has(resolvedUrl)) {\n continue;\n }\n seen.add(resolvedUrl);\n candidates.push(resolvedUrl);\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 {\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 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 { isLikelyDocumentUrl } from \"./shared/traversal-url\";\nimport { createWebProvider, type WebProviderOptions } from \"./web\";\nimport { classifyBlockerSignal } from \"./blocker\";\nimport { canonicalizeUrl } from \"./web/crawler\";\nimport { extractStructuredContent, 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 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\"]);\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\"]);\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): boolean => {\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\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 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}): 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 (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\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 const resolvedUrl = canonicalizeUrl(readFallbackString(fallback.output, \"url\") ?? currentDocument.url);\n const html = readFallbackString(fallback.output, \"html\") ?? \"\";\n const extracted = extractStructuredContent(html, resolvedUrl);\n currentDocument = {\n url: resolvedUrl,\n status: 200,\n html,\n text: extracted.text,\n links: extracted.links,\n browserFallback: toBrowserFallbackObservation(fallback)\n };\n described = describeDefaultFetchedIssue(currentDocument);\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): 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) => isAllowedSocialSearchExpansionUrl(\"reddit\", url))\n .slice(0, limit);\n};\n\nconst shouldRejectBlockedCommunityFallback = (\n document: RuntimeFetchedDocument,\n links: readonly string[]\n): boolean => (\n document.browserFallback !== undefined\n && isFirstPartySocialSearchRoute(\"reddit\", document.url)\n && links.length === 0\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 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}): Promise<RuntimeFetchedDocument> => {\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 const fallbackPort = args.context?.browserFallbackPort ?? args.browserFallbackPort;\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 const resolvedUrl = canonicalizeUrl(readFallbackString(fallback.output, \"url\") ?? args.url);\n const html = readFallbackString(fallback.output, \"html\") ?? \"\";\n const extracted = extractStructuredContent(html, resolvedUrl);\n return {\n url: resolvedUrl,\n status: 200,\n html,\n text: extracted.text,\n links: extracted.links,\n browserFallback: toBrowserFallbackObservation(fallback)\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 Promise.all(\n providers.map((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 Promise.all(\n fallbackProviders.map((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 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 links = dedupeLinks(document.links, document.url, limit * 2)\n .filter((url) => !isDuckDuckGoSearchShellUrl(url))\n .slice(0, limit);\n const searchPath = isHttpUrl(query) ? \"web:search:url\" : \"web:search:index\";\n if (links.length === 0) {\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 }) => {\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 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 });\n const { document: resolvedDocument, pageMessage } = await resolveDefaultFallbackDocumentIfNeeded({\n providerId,\n source: \"community\",\n operation: \"search\",\n document,\n context,\n browserFallbackPort\n });\n const links = resolveCommunitySearchLinks(resolvedDocument, limit);\n if (shouldRejectBlockedCommunityFallback(resolvedDocument, links)) {\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 });\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 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)) {\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 resolvedUrl = canonicalizeUrl(readFallbackString(fallback.output, \"url\") ?? currentDocument.url);\n const html = readFallbackString(fallback.output, \"html\") ?? \"\";\n const extracted = extractStructuredContent(html, resolvedUrl);\n const effectiveUrl = resolveRecoveredSocialSearchDocumentUrl({\n platform,\n operation,\n requestedUrl,\n recoveredUrl: resolvedUrl,\n recoveredLinks: extracted.links\n });\n currentDocument = {\n url: effectiveUrl,\n status: 200,\n html,\n text: extracted.text,\n links: extracted.links,\n browserFallback: toBrowserFallbackObservation(fallback)\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 });\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 });\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 \"./tier-router\";\nexport * from \"./adaptive-concurrency\";\nexport * from \"./blocker\";\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,kBAAkB;AAwB3B,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;AAE7B,SAAS,aAAa,OAAuB;AAC3C,SAAO,MAAM,QAAQ,sBAAsB,YAAY;AACzD;AAEO,SAAS,gBAAgB,OAAgB,OAAO,oBAAI,QAAgB,GAAY;AACrF,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO,aAAa,KAAK;AAAA,EAC3B;AACA,MAAI,OAAO,UAAU,YAAY,UAAU,MAAM;AAC/C,WAAO;AAAA,EACT;AACA,MAAI,KAAK,IAAI,KAAK,GAAG;AACnB,WAAO;AAAA,EACT;AACA,OAAK,IAAI,KAAK;AAEd,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,IAAI,CAAC,SAAS,gBAAgB,MAAM,IAAI,CAAC;AAAA,EACxD;AAEA,QAAM,SAAkC,CAAC;AACzC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,GAAG;AAChD,QAAI,mBAAmB,KAAK,GAAG,GAAG;AAChC,aAAO,GAAG,IAAI;AACd;AAAA,IACF;AACA,WAAO,GAAG,IAAI,gBAAgB,OAAO,IAAI;AAAA,EAC3C;AACA,SAAO;AACT;AAEO,SAAS,kBAA0B;AACxC,SAAO,WAAW;AACpB;AAEA,IAAM,cAAuB,CAAC,UAAU;AACtC,QAAM,UAAU,KAAK,UAAU,KAAK;AACpC,MAAI,MAAM,UAAU,SAAS;AAC3B,YAAQ,MAAM,OAAO;AACrB;AAAA,EACF;AACA,MAAI,MAAM,UAAU,QAAQ;AAC1B,YAAQ,KAAK,OAAO;AACpB;AAAA,EACF;AACA,UAAQ,IAAI,OAAO;AACrB;AAEO,IAAM,aAAsB,CAAC,UAAU;AAC5C,UAAQ,OAAO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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":["console","randomUUID","randomUUID","path","DEFAULT_HOLD_MS","resolve","outcome","createHash","createHash","resolve","percentile","queue","percentile","isHttpUrl","extractLinks","fetch","normalizeText","DEFAULT_TRAVERSAL","LINK_RE","asNumber","toPositiveInt","isHttpUrl","coerceStringArray","extractLinks","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","readdir","rm","join","randomUUID","tmpdir","toDate","fromDate","asNumber","createHash","createHash","createHash","createHash","asNumber","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","asNumber","details","checkpointState","stepIndex","WORKFLOW_KIND_BY_SUSPENDED_INTENT_KIND","isJsonRecord","resolve","dedupeLinks","isHttpUrl","toPositiveInt","fallbackReasonCodeForError","hash","extractHost"]}