import { createHash } from 'node:crypto'; import { open } from 'node:fs/promises'; import { createNativeHttpAdapter } from './adapters/native-http.mjs'; import { validateExtractSchema } from './adapters/python-helper.mjs'; import { ATTEMPT_CODE, ATTEMPT_KIND, RUN_STATUS, createResultEnvelope, exitCodeForStatus, } from './contracts.mjs'; import { deriveRepresentation, detectRepresentation } from './formats.mjs'; import { parsePublicUrl } from './policy.mjs'; import { acceptRepresentation, buildRoutePlan, createCapabilitySnapshot, decideTransition, healthReport, renderedFallbackSkip, runModelRoute, } from './router.mjs'; import { runBoundedCrawl } from './frontier.mjs'; import { createRobotsGate } from './robots.mjs'; import { createSearchRegistry, runSearchJob } from './search.mjs'; import { createRequestFingerprint } from './storage.mjs'; // One AbortController per run owns every stop signal: SIGINT, SIGTERM and the // wall deadline all funnel into a single first-wins finalize. The winner aborts // in-flight egress/children, records one sanitized termination event, commits // exactly one interrupted manifest (never a cache record), and exits with the // contract code. Redundant signals — or a signal racing the deadline — are // dropped by a synchronous claim, so there is always exactly one commit and one // exit. Listeners and the timer are always detached, so no handler leaks. const CLEANUP_BUDGET_MS = 500; export function createInterruptionGuard({ storage, run, buildInterruptedManifest, emitter = process, exit = (code) => process.exit(code), scheduler = { setTimeout, clearTimeout }, wallMs = null, gateway = null, supervisor = null, } = {}) { if (!storage || typeof storage.commitManifest !== 'function') { throw new TypeError('interruption guard requires storage.commitManifest'); } if (!run || typeof run !== 'object') throw new TypeError('interruption guard requires a run'); if (typeof buildInterruptedManifest !== 'function') { throw new TypeError('interruption guard requires buildInterruptedManifest'); } if (!emitter || typeof emitter.on !== 'function' || typeof emitter.removeListener !== 'function') { throw new TypeError('interruption guard requires an event emitter'); } const controller = new AbortController(); let settled = false; // synchronous first-wins claim — guarantees one commit/exit let installed = false; let detached = false; let commitCount = 0; let deadlineTimer = null; let resolveDone; const done = new Promise((resolve) => { resolveDone = resolve; }); const diag = (error) => { try { process.stderr.write(`interruption_guard: ${error?.stack ?? error}\n`); } catch { // A broken diagnostic stream cannot safely be recovered mid-teardown. } }; function detach() { if (detached) return; detached = true; emitter.removeListener('SIGINT', onSigint); emitter.removeListener('SIGTERM', onSigterm); if (deadlineTimer !== null) { scheduler.clearTimeout(deadlineTimer); deadlineTimer = null; } } // Bounded so a wedged child or gateway can never delay the interrupted exit. async function boundedCleanup() { const tasks = []; if (gateway && typeof gateway.abort === 'function') tasks.push(gateway.abort()); if (supervisor && typeof supervisor.terminateAll === 'function') tasks.push(supervisor.terminateAll()); if (tasks.length === 0) return; await Promise.race([ Promise.allSettled(tasks.map((task) => Promise.resolve(task))), new Promise((resolve) => { const timer = globalThis.setTimeout(resolve, CLEANUP_BUDGET_MS); timer?.unref?.(); }), ]); } async function appendTermination(termination) { if (typeof storage.appendAttempt !== 'function') return; try { await storage.appendAttempt(run, { type: 'termination', outcome: 'interrupted', ...termination }); } catch (error) { diag(error); // telemetry is best-effort; the manifest is the durable record } } async function finalize(termination) { if (settled) return; // claim is synchronous: the first signal/deadline wins settled = true; const code = exitCodeForStatus(RUN_STATUS.INTERRUPTED, termination); try { controller.abort(new Error(`run interrupted: ${termination.reason ?? termination.signal}`)); await boundedCleanup(); await appendTermination(termination); await storage.commitManifest(run, buildInterruptedManifest(termination)); commitCount += 1; } catch (error) { diag(error); // still detach + exit; never hang on a failed teardown } finally { detach(); exit(code); resolveDone(); } } function onSigint() { void finalize({ signal: 'SIGINT' }); } function onSigterm() { void finalize({ signal: 'SIGTERM' }); } function install() { if (installed) return guardApi; installed = true; emitter.on('SIGINT', onSigint); emitter.on('SIGTERM', onSigterm); if (Number.isFinite(wallMs) && wallMs > 0) { deadlineTimer = scheduler.setTimeout(() => { void finalize({ reason: 'timeout' }); }, wallMs); deadlineTimer?.unref?.(); } return guardApi; } function dispose() { if (settled) return; // an interrupted run already detached inside finalize detach(); } const guardApi = { install, dispose, done, get commitCount() { return commitCount; }, signal: controller.signal, }; return guardApi; } function milliseconds(clock) { const value = clock(); const result = value instanceof Date ? value.getTime() : Number(value); if (!Number.isFinite(result)) throw new TypeError('clock returned invalid time'); return result; } function iso(millisecondsValue) { return new Date(millisecondsValue).toISOString(); } function hardLimit() { return { kind: ATTEMPT_KIND.TERMINAL, code: ATTEMPT_CODE.HARD_LIMIT }; } function limitsFor(job) { const source = job?.limits ?? {}; const limits = { wallMs: source.wallMs, perAttemptMs: source.perAttemptMs, retriesPerAdapter: source.retriesPerAdapter, maxRetryAfterMs: source.maxRetryAfterMs, maxRedirects: source.maxRedirects, maxWireBytes: source.maxWireBytes ?? source.maxBytesPerPage, maxDecodedBytes: source.maxDecodedBytes ?? source.maxBytesPerPage, }; for (const [name, value] of Object.entries(limits)) { const allowsZero = name === 'retriesPerAdapter' || name === 'maxRedirects'; if (!Number.isSafeInteger(value) || value < (allowsZero ? 0 : 1)) { throw new TypeError(`invalid native limit: ${name}`); } } return limits; } function retryDecision(outcome, retriesUsed, rateLimitRetries, limits) { if (outcome.kind !== ATTEMPT_KIND.RETRYABLE) return null; if (outcome.code === ATTEMPT_CODE.RATE_LIMITED) { if (rateLimitRetries >= 1 || retriesUsed >= limits.retriesPerAdapter) return null; const requested = Number.isFinite(outcome.retryAfterMs) && outcome.retryAfterMs > 0 ? outcome.retryAfterMs : 0; return { delayMs: Math.min(requested, limits.maxRetryAfterMs), capped: requested > limits.maxRetryAfterMs, rateLimited: true, }; } if (![ATTEMPT_CODE.NETWORK, ATTEMPT_CODE.TIMEOUT, ATTEMPT_CODE.HTTP_5XX].includes(outcome.code) || retriesUsed >= limits.retriesPerAdapter) return null; return { delayMs: 0, capped: false, rateLimited: false }; } export async function runNativeAttempts(job, { adapter, clock = Date.now, sleep = async () => {}, onAttemptStart = async () => {}, onAttemptFinish = async () => undefined, } = {}) { if (!adapter || typeof adapter.run !== 'function') throw new TypeError('native adapter is required'); if (typeof clock !== 'function' || typeof sleep !== 'function') throw new TypeError('clock and sleep are required'); const limits = limitsFor(job); const startedMs = milliseconds(clock); const deadlineMs = startedMs + limits.wallMs; const timeline = []; let retriesUsed = 0; let rateLimitRetries = 0; let completion; while (true) { const attemptStartedMs = milliseconds(clock); if (attemptStartedMs >= deadlineMs) return { outcome: hardLimit(), timeline }; await onAttemptStart({ attempt: timeline.length + 1, started_at: iso(attemptStartedMs), }); const controller = new AbortController(); const attemptBudgetMs = Math.min(limits.perAttemptMs, deadlineMs - attemptStartedMs); const timer = setTimeout(() => controller.abort(new Error('attempt timeout')), attemptBudgetMs); timer.unref?.(); let outcome; try { outcome = await adapter.run({ runId: job.runId ?? 'native-run', url: job.target.url, method: 'GET', conditionalHeaders: job.conditionalHeaders ?? {}, remaining: { wallMs: deadlineMs - attemptStartedMs, bytes: limits.maxWireBytes, redirects: limits.maxRedirects, }, limits: { maxWireBytes: limits.maxWireBytes, maxDecodedBytes: limits.maxDecodedBytes, }, signal: controller.signal, }); } catch { outcome = { kind: ATTEMPT_KIND.BROKEN, code: ATTEMPT_CODE.ADAPTER_CRASH }; } finally { clearTimeout(timer); } if (!outcome || typeof outcome.kind !== 'string' || typeof outcome.code !== 'string') { outcome = { kind: ATTEMPT_KIND.BROKEN, code: ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR }; } const finishedMs = milliseconds(clock); const entry = { attempt: timeline.length + 1, started_at: iso(attemptStartedMs), finished_at: iso(finishedMs), duration_ms: Math.max(0, finishedMs - attemptStartedMs), outcome: outcome.kind, code: outcome.code, delay_ms: 0, retry_after_capped: false, }; const http = responseEvidence(outcome); if (http) entry.http = http; timeline.push(entry); completion = await onAttemptFinish({ entry: { ...entry }, outcome }); const retry = retryDecision(outcome, retriesUsed, rateLimitRetries, limits); if (!retry) { if (outcome.kind === ATTEMPT_KIND.RETRYABLE && outcome.code === ATTEMPT_CODE.RATE_LIMITED) { return { outcome: { ...outcome, kind: ATTEMPT_KIND.TERMINAL }, timeline, }; } return { outcome, timeline, completion }; } if (finishedMs + retry.delayMs >= deadlineMs) return { outcome: hardLimit(), timeline }; entry.delay_ms = retry.delayMs; entry.retry_after_capped = retry.capped; retriesUsed += 1; if (retry.rateLimited) rateLimitRetries += 1; await sleep(retry.delayMs); } } const SAFE_RESPONSE_HEADERS = new Set([ 'cache-control', 'content-encoding', 'content-length', 'content-type', 'date', 'etag', 'last-modified', ]); function hashBytes(bytes) { return `sha256:${createHash('sha256').update(bytes).digest('hex')}`; } function safeHeaders(headers) { const result = {}; for (const [rawName, rawValue] of Object.entries(headers ?? {})) { const name = rawName.toLowerCase(); if (!SAFE_RESPONSE_HEADERS.has(name)) continue; const value = Array.isArray(rawValue) ? rawValue.join(', ') : String(rawValue); if (value.length <= 4096 && !/[\r\n\0]/u.test(value)) result[name] = value; } return result; } function responseEvidence(outcome) { const response = outcome?.response ?? outcome?.evidence; if (!response) return null; return { status_code: response.statusCode, final_url: response.finalUrl, redirect_chain: response.redirectChain ?? [], selected_address: response.permit?.selectedAddress ?? null, headers: safeHeaders(response.headers), wire_bytes: response.wireBytes ?? null, decoded_bytes: response.decodedBytes ?? null, }; } function outcomeStatus(outcome) { if (outcome?.kind === ATTEMPT_KIND.TERMINAL) { if ([ATTEMPT_CODE.NOT_FOUND, ATTEMPT_CODE.GONE].includes(outcome.code)) { return { status: RUN_STATUS.EXHAUSTED, code: outcome.code }; } return { status: RUN_STATUS.BLOCKED, code: outcome.code }; } if (outcome?.kind === ATTEMPT_KIND.BROKEN) { return { status: RUN_STATUS.INTERNAL_ERROR, code: outcome.code }; } return { status: RUN_STATUS.EXHAUSTED, code: 'exhausted' }; } function resultFor(job, context, status, code, fields = {}) { return createResultEnvelope({ command: job.kind, status, code, message: fields.message ?? (status === RUN_STATUS.OK ? 'Public source captured' : 'Native URL path stopped'), route: context.route ?? [], capabilities: context.capabilities ?? [], warnings: fields.warnings ?? [], ...(fields.manifestPath ? { manifest_path: fields.manifestPath } : {}), ...(fields.artifactPath ? { artifact_path: fields.artifactPath } : {}), ...(fields.sourceHash ? { source_hash: fields.sourceHash } : {}), ...(fields.cacheStatus ? { cache_status: fields.cacheStatus } : {}), }); } function manifestBase({ run, requestedUrl, effectiveUrl, requestedFormat, format, fetchedAt, servedAt, revalidatedAt = null, status, attempts, sourceRef = null, artifactRef = null, artifacts = [], warnings = [], evidence = [], cacheStatus, }) { return { schema_version: 1, run_id: run.id, status, requested_url: requestedUrl, effective_url: effectiveUrl, requested_format: requestedFormat, format, alternatives: [], fetched_at: fetchedAt, served_at: servedAt, revalidated_at: revalidatedAt, engine: { id: 'native', version: '1' }, policy: { version: '1', network: 'public-only', auth: 'none', money_budget: 0, }, attempts, source_hash: sourceRef?.hash ?? null, artifact_hash: artifactRef?.hash ?? null, artifact_path: artifactRef?.path ?? null, artifacts, evidence, warnings, cost_money: 0, credits_used: 0, verification: sourceRef ? 'source_captured' : 'no_source_captured', cache_status: cacheStatus, }; } function fingerprintFor(job, canonicalUrl) { return createRequestFingerprint({ canonicalUrl, method: 'GET', headers: { accept: 'text/html,application/xhtml+xml,application/json,application/xml,text/xml,text/plain;q=0.9,*/*;q=0.1', 'accept-encoding': 'gzip, deflate, br', }, adapter: { id: 'native', version: '1' }, policyVersion: '1', format: job.output.format, goal: job.goal, decode: { encodings: ['gzip', 'deflate', 'br'], maxBytes: job.limits.maxBytesPerPage, }, }); } function sourceFromManifest(manifest, sourceHash) { return manifest?.artifacts?.find((artifact) => artifact.hash === sourceHash && artifact.role === 'raw') ?? manifest?.artifacts?.find((artifact) => artifact.hash === sourceHash) ?? null; } async function loadVerifiedCachedArtifact(storage, cached, maxBytes) { const { record, manifest } = cached; const sourceRef = sourceFromManifest(manifest, record.source_hash); const artifactRef = manifest?.artifacts?.find((artifact) => ( artifact.hash === record.artifact_hash && artifact.path === record.artifact_path )); if (!sourceRef || !artifactRef) throw new Error('cache artifact reference is missing'); const bytes = await storage.readObject(artifactRef, { maxBytes }); if (hashBytes(bytes) !== artifactRef.hash) throw new Error('cache artifact hash mismatch'); return { sourceRef, artifactRef, bytes }; } function derivedMediaType(format, sourceMediaType) { if (format === 'markdown') return 'text/markdown; charset=utf-8'; if (['metadata', 'links', 'json'].includes(format)) return 'application/json'; return sourceMediaType; } async function publishSelectedOutput(storage, requestedPath, artifactRef, bytes) { if (requestedPath === null) return artifactRef.path; return (await storage.publishOutput(requestedPath, bytes)).path; } function cacheRecord({ fingerprint, canonicalUrl, requestedFormat, run, manifest, sourceRef, artifactRef, fetchedAt, expiresAt, effectiveUrl, mediaType, headers, format, }) { return { schema_version: 1, request_fingerprint: fingerprint, canonical_url: canonicalUrl, requested_format: requestedFormat, format, run_id: run.id, manifest_path: manifest.path, manifest_hash: manifest.hash, source_hash: sourceRef.hash, source_path: sourceRef.path, artifact_hash: artifactRef.hash, artifact_path: artifactRef.path, fetched_at: fetchedAt, expires_at: expiresAt, effective_url: effectiveUrl, media_type: mediaType, etag: headers.etag ?? null, last_modified: headers['last-modified'] ?? null, }; } function addFinalEvidence(timeline, outcome) { const evidence = responseEvidence(outcome); return timeline.map((entry, index) => ( index === timeline.length - 1 && evidence ? { ...entry, http: evidence } : { ...entry } )); } async function finishCacheHit({ job, context, storage, fingerprint, cached, verified, canonicalUrl, servedAt, warnings, }) { const run = await storage.beginRun({ schema_version: 1, command: 'url', requested_url: canonicalUrl, method: 'GET', format: job.output.format, cache: job.cache.mode, }); const attempt = { type: 'cache_hit', at: servedAt, source_hash: verified.sourceRef.hash, manifest_hash: cached.record.manifest_hash, }; await storage.appendAttempt(run, attempt); const manifestValue = manifestBase({ run, requestedUrl: canonicalUrl, effectiveUrl: cached.record.effective_url ?? canonicalUrl, requestedFormat: job.output.format, format: cached.record.format, fetchedAt: cached.record.fetched_at, servedAt, status: RUN_STATUS.OK, attempts: [attempt], sourceRef: verified.sourceRef, artifactRef: verified.artifactRef, artifacts: cached.manifest.artifacts, warnings, evidence: cached.manifest.evidence ?? [], cacheStatus: 'hit', }); const manifest = await storage.commitManifest(run, manifestValue); await storage.commitCache(fingerprint, { ...cached.record, run_id: run.id, manifest_path: manifest.path, manifest_hash: manifest.hash, }); const artifactPath = await publishSelectedOutput( storage, job.output.path, verified.artifactRef, verified.bytes, ); return resultFor(job, context, RUN_STATUS.OK, 'ok', { manifestPath: manifest.path, artifactPath, sourceHash: verified.sourceRef.hash, cacheStatus: 'hit', warnings, }); } function htmlAttribute(tag, name) { const match = tag.match(new RegExp( `(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\u0060]+))`, 'iu', )); return (match?.[1] ?? match?.[2] ?? match?.[3] ?? '') .replace(/&/giu, '&') .replace(/"/giu, '"') .replace(/'|'/giu, "'"); } function safeCandidate(candidate, finalUrl) { if (typeof candidate !== 'string' || candidate.length === 0 || candidate.length > 8192) return null; try { return parsePublicUrl(new URL(candidate, finalUrl).href).canonicalUrl; } catch { return null; } } function basicHtmlRepresentation(bytes, finalUrl) { const source = bytes.toString('utf8'); const body = source.match(/
]*>([^]*?)<\/body\s*>/iu)?.[1] ?? source; const scriptCount = [...body.matchAll(/