pi-background-tasks 2.5.0 → 2.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/BACKGROUND-TASKS-INSTRUCTIONS.md +1 -1
- package/README.md +70 -25
- package/TESTING.md +42 -2
- package/TEST_PLAN.md +7 -4
- package/dist/extensions/anthropic-attribution-child.js +4 -0
- package/dist/extensions/anthropic-attribution-child.js.map +1 -0
- package/dist/extensions/anthropic-attribution.js +107 -0
- package/dist/extensions/anthropic-attribution.js.map +1 -0
- package/dist/extensions/background-tasks.js +2 -0
- package/dist/extensions/background-tasks.js.map +1 -0
- package/dist/extensions/delegate-child.js +2 -0
- package/dist/extensions/delegate-child.js.map +1 -0
- package/dist/extensions/fusion-child.js +2 -0
- package/dist/extensions/fusion-child.js.map +1 -0
- package/dist/package.json +5 -0
- package/dist/src/core/anthropic-attribution-path.js +24 -0
- package/dist/src/core/anthropic-attribution-path.js.map +1 -0
- package/dist/src/core/anthropic-attribution.js +2247 -0
- package/dist/src/core/anthropic-attribution.js.map +1 -0
- package/dist/src/core/attested-pi-contract.js +5 -0
- package/dist/src/core/attested-pi-contract.js.map +1 -0
- package/dist/src/core/attested-pi-run.js +749 -0
- package/dist/src/core/attested-pi-run.js.map +1 -0
- package/dist/src/core/canonical-json.js +19 -0
- package/dist/src/core/canonical-json.js.map +1 -0
- package/dist/src/core/common.js +787 -0
- package/dist/src/core/common.js.map +1 -0
- package/dist/src/core/config.js +78 -0
- package/dist/src/core/config.js.map +1 -0
- package/dist/src/core/context/parent-snapshot.js +75 -0
- package/dist/src/core/context/parent-snapshot.js.map +1 -0
- package/dist/src/core/context/token-budget.js +631 -0
- package/dist/src/core/context/token-budget.js.map +1 -0
- package/dist/src/core/context/visible-conversation-v2.js +390 -0
- package/dist/src/core/context/visible-conversation-v2.js.map +1 -0
- package/dist/src/core/delegate/artifacts.js +357 -0
- package/dist/src/core/delegate/artifacts.js.map +1 -0
- package/dist/src/core/delegate/budget.js +266 -0
- package/dist/src/core/delegate/budget.js.map +1 -0
- package/dist/src/core/delegate/facade-contract.js +7 -0
- package/dist/src/core/delegate/facade-contract.js.map +1 -0
- package/dist/src/core/delegate/hook-contract-evidence.json +18 -0
- package/dist/src/core/delegate/hook-contract.js +124 -0
- package/dist/src/core/delegate/hook-contract.js.map +1 -0
- package/dist/src/core/delegate/launch.js +366 -0
- package/dist/src/core/delegate/launch.js.map +1 -0
- package/dist/src/core/delegate/result-package.js +293 -0
- package/dist/src/core/delegate/result-package.js.map +1 -0
- package/dist/src/core/delegate/runner.js +398 -0
- package/dist/src/core/delegate/runner.js.map +1 -0
- package/dist/src/core/delegate/seed.js +334 -0
- package/dist/src/core/delegate/seed.js.map +1 -0
- package/dist/src/core/delegate/types.js +103 -0
- package/dist/src/core/delegate/types.js.map +1 -0
- package/dist/src/core/durable-fs.js +372 -0
- package/dist/src/core/durable-fs.js.map +1 -0
- package/dist/src/core/extension-api.js +382 -0
- package/dist/src/core/extension-api.js.map +1 -0
- package/dist/src/core/fusion/artifacts.js +654 -0
- package/dist/src/core/fusion/artifacts.js.map +1 -0
- package/dist/src/core/fusion/budget.js +949 -0
- package/dist/src/core/fusion/budget.js.map +1 -0
- package/dist/src/core/fusion/child-protocol.js +176 -0
- package/dist/src/core/fusion/child-protocol.js.map +1 -0
- package/dist/src/core/fusion/claude-cache.js +156 -0
- package/dist/src/core/fusion/claude-cache.js.map +1 -0
- package/dist/src/core/fusion/clean-context.js +64 -0
- package/dist/src/core/fusion/clean-context.js.map +1 -0
- package/dist/src/core/fusion/config.js +349 -0
- package/dist/src/core/fusion/config.js.map +1 -0
- package/dist/src/core/fusion/context.js +184 -0
- package/dist/src/core/fusion/context.js.map +1 -0
- package/dist/src/core/fusion/evaluation.js +696 -0
- package/dist/src/core/fusion/evaluation.js.map +1 -0
- package/dist/src/core/fusion/facade-contract.js +3 -0
- package/dist/src/core/fusion/facade-contract.js.map +1 -0
- package/dist/src/core/fusion/orchestrator.js +867 -0
- package/dist/src/core/fusion/orchestrator.js.map +1 -0
- package/dist/src/core/fusion/output-contract.js +27 -0
- package/dist/src/core/fusion/output-contract.js.map +1 -0
- package/dist/src/core/fusion/pi-child.js +1741 -0
- package/dist/src/core/fusion/pi-child.js.map +1 -0
- package/dist/src/core/fusion/prompts.js +260 -0
- package/dist/src/core/fusion/prompts.js.map +1 -0
- package/dist/src/core/fusion/result-package.js +857 -0
- package/dist/src/core/fusion/result-package.js.map +1 -0
- package/dist/src/core/fusion/source-policy.js +259 -0
- package/dist/src/core/fusion/source-policy.js.map +1 -0
- package/dist/src/core/fusion/types.js +207 -0
- package/dist/src/core/fusion/types.js.map +1 -0
- package/dist/src/core/fusion/web-fetch.js +777 -0
- package/dist/src/core/fusion/web-fetch.js.map +1 -0
- package/dist/src/core/fusion/workflows.js +126 -0
- package/dist/src/core/fusion/workflows.js.map +1 -0
- package/dist/src/core/lazy-module.js +181 -0
- package/dist/src/core/lazy-module.js.map +1 -0
- package/dist/src/core/pi-launch.js +431 -0
- package/dist/src/core/pi-launch.js.map +1 -0
- package/dist/src/core/registry.js +3331 -0
- package/dist/src/core/registry.js.map +1 -0
- package/dist/src/core/reload-shell-owner.js +1396 -0
- package/dist/src/core/reload-shell-owner.js.map +1 -0
- package/dist/src/core/shell-policy.js +80 -0
- package/dist/src/core/shell-policy.js.map +1 -0
- package/dist/src/core/task-durable.js +51 -0
- package/dist/src/core/task-durable.js.map +1 -0
- package/dist/src/core/update-check.js +92 -0
- package/dist/src/core/update-check.js.map +1 -0
- package/dist/src/core/windows-taskkill.js +185 -0
- package/dist/src/core/windows-taskkill.js.map +1 -0
- package/dist/src/delegate-child-extension.js +776 -0
- package/dist/src/delegate-child-extension.js.map +1 -0
- package/dist/src/delegate-extension.js +746 -0
- package/dist/src/delegate-extension.js.map +1 -0
- package/dist/src/extension.js +953 -0
- package/dist/src/extension.js.map +1 -0
- package/dist/src/fusion-child-extension.js +760 -0
- package/dist/src/fusion-child-extension.js.map +1 -0
- package/dist/src/fusion-extension.js +1030 -0
- package/dist/src/fusion-extension.js.map +1 -0
- package/dist/src/ui/background-tasks-manager.js +689 -0
- package/dist/src/ui/background-tasks-manager.js.map +1 -0
- package/dist/src/ui/fusion-model-selector.js +277 -0
- package/dist/src/ui/fusion-model-selector.js.map +1 -0
- package/docs/INDEX.md +35 -33
- package/docs/api/eventbus-v1.md +21 -5
- package/docs/choose-a-workflow.md +2 -0
- package/docs/commands/bg-clear.md +3 -3
- package/docs/commands/bg-update.md +3 -3
- package/docs/commands/bg.md +18 -6
- package/docs/commands/claude-cache.md +4 -4
- package/docs/commands/fusion-models.md +49 -4
- package/docs/commands/fusion.md +3 -3
- package/docs/commands/jobs.md +3 -3
- package/docs/commands/kill.md +3 -3
- package/docs/commands/logs.md +3 -3
- package/docs/commands/task-manager.md +5 -5
- package/docs/concepts/completion-delivery.md +6 -2
- package/docs/getting-started.md +7 -1
- package/docs/manifest.json +228 -42
- package/docs/operations/configuration.md +58 -5
- package/docs/operations/releasing.md +4 -2
- package/docs/operations/testing.md +22 -0
- package/docs/operations/troubleshooting.md +6 -2
- package/docs/read-before-edit.md +44 -31
- package/docs/reference/runtime-contracts.md +87 -51
- package/docs/reference/shortcuts-and-dock.md +28 -14
- package/docs/subsystems/anthropic-attribution.md +23 -11
- package/docs/subsystems/attested-pi-runs.md +12 -7
- package/docs/subsystems/background-task-runtime.md +53 -11
- package/docs/subsystems/child-launch-durability-and-safety.md +28 -9
- package/docs/subsystems/delegation.md +16 -3
- package/docs/subsystems/docs-freshness-gate.md +14 -7
- package/docs/subsystems/fusion.md +36 -11
- package/docs/subsystems/host-ui-and-telemetry.md +22 -9
- package/docs/tools/bg_delegate.md +3 -1
- package/docs/tools/bg_kill.md +3 -1
- package/docs/tools/bg_logs.md +3 -1
- package/docs/tools/bg_result.md +5 -3
- package/docs/tools/bg_run.md +31 -5
- package/docs/tools/bg_run_pi_attested.md +3 -1
- package/docs/tools/bg_status.md +3 -1
- package/docs/tools/fusion_investigate.md +3 -1
- package/docs/tools/fusion_reason.md +3 -1
- package/docs/tools/fusion_research.md +3 -1
- package/docs/tools/fusion_validate.md +3 -1
- package/extensions/anthropic-attribution-child.ts +3 -0
- package/extensions/anthropic-attribution.ts +166 -1
- package/package.json +12 -10
- package/src/core/anthropic-attribution-path.ts +5 -4
- package/src/core/anthropic-attribution.ts +293 -113
- package/src/core/attested-pi-contract.ts +4 -0
- package/src/core/attested-pi-run.ts +468 -81
- package/src/core/canonical-json.ts +21 -0
- package/src/core/common.ts +450 -40
- package/src/core/config.ts +121 -0
- package/src/core/context/visible-conversation-v2.ts +3 -6
- package/src/core/delegate/artifacts.ts +13 -9
- package/src/core/delegate/budget.ts +13 -6
- package/src/core/delegate/facade-contract.ts +6 -0
- package/src/core/delegate/result-package.ts +32 -14
- package/src/core/delegate/runner.ts +129 -58
- package/src/core/delegate/seed.ts +5 -7
- package/src/core/durable-fs.ts +178 -30
- package/src/core/extension-api.ts +36 -8
- package/src/core/fusion/artifacts.ts +17 -16
- package/src/core/fusion/clean-context.ts +8 -5
- package/src/core/fusion/config.ts +2 -1
- package/src/core/fusion/context.ts +2 -6
- package/src/core/fusion/facade-contract.ts +2 -0
- package/src/core/fusion/orchestrator.ts +3 -3
- package/src/core/fusion/prompts.ts +1 -1
- package/src/core/fusion/result-package.ts +259 -72
- package/src/core/fusion/source-policy.ts +43 -17
- package/src/core/lazy-module.ts +215 -0
- package/src/core/pi-launch.ts +390 -65
- package/src/core/registry.ts +2010 -381
- package/src/core/reload-shell-owner.ts +1662 -0
- package/src/core/shell-policy.ts +134 -0
- package/src/core/task-durable.ts +67 -0
- package/src/delegate-extension.ts +404 -144
- package/src/extension.ts +387 -114
- package/src/fusion-extension.ts +202 -96
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"web-fetch.js","sourceRoot":"","sources":["../../../../src/core/fusion/web-fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC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Ae;IAC1C,MAAM,MAAM,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;IACzC,IAAI,MAAM,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,mCAAmC,OAAO,EAAE,CAAC,CAAC;IACxF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,kBAAkB,CAAC,OAAe;IACzC,MAAM,YAAY,GAAG,mBAAmB,CAAC,YAAY,CAAC,CAAC;IACvD,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,CAAC;QAAE,OAAO,SAAS,CAAC;IAC9D,OAAO,MAAM,CAAC,OAAO,GAAG,WAAW,CAAC,CAAC;AACvC,CAAC;AAED,SAAS,WAAW,CAAC,OAAe,EAAE,IAAY,EAAE,MAAc;IAChE,MAAM,OAAO,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,MAAM,CAAC,CAAC;IACnC,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,OAAO,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC;AACtE,CAAC;AAED,SAAS,WAAW,CAAC,OAAe,EAAE,IAAY,EAAE,MAAc;IAChE,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,GAAG,MAAM,CAAC,CAAC;IACnC,OAAO,OAAO,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,CAAC;AAC5C,CAAC","sourcesContent":["import { createHash } from 'node:crypto';\nimport { lookup as nodeLookup } from 'node:dns/promises';\nimport * as http from 'node:http';\nimport * as https from 'node:https';\nimport { isIP } from 'node:net';\nimport { performance } from 'node:perf_hooks';\nimport { TextDecoder } from 'node:util';\n\nimport type TurndownService from 'turndown';\n\nexport const FUSION_WEB_FETCH_TIMEOUT_MS = 90_000;\nexport const FUSION_WEB_FETCH_MAX_RESPONSE_BYTES = 4 * 1024 * 1024;\nexport const FUSION_WEB_FETCH_MAX_OUTPUT_BYTES = 32 * 1024;\nexport const FUSION_WEB_FETCH_MAX_REDIRECTS = 5;\n\nexport interface FusionWebFetchRequest {\n url: string;\n extract?: 'text' | 'markdown';\n}\n\nexport interface FusionWebFetchResult {\n url: string;\n final_url: string;\n status: number;\n content_type: string;\n format: 'text' | 'markdown';\n truncated: boolean;\n content: string;\n response_bytes: number;\n content_sha256: string;\n duration_ms: number;\n}\n\nexport type FusionWebFetchErrorCode =\n | 'invalid_url'\n | 'unsupported_scheme'\n | 'blocked_address'\n | 'dns_failure'\n | 'redirect_limit'\n | 'redirect_blocked'\n | 'response_too_large'\n | 'unsupported_content_type'\n | 'request_timeout'\n | 'network_error'\n | 'extraction_failed'\n | 'http_error';\n\nexport interface FusionDnsAddress {\n address: string;\n family: 4 | 6;\n}\n\nexport type FusionDnsLookup = (hostname: string) => Promise<readonly FusionDnsAddress[]>;\n\nexport type FusionTransportRequest = (\n protocol: 'http:' | 'https:',\n options: http.RequestOptions | https.RequestOptions,\n) => http.ClientRequest;\n\nexport type FusionContentExtractor = (\n body: Buffer,\n contentType: string,\n requestedFormat: 'text' | 'markdown',\n) => Promise<{ content: string; format: 'text' | 'markdown' }>;\n\nexport interface FusionWebFetchOptions {\n lookup?: FusionDnsLookup;\n request?: FusionTransportRequest;\n agent?: http.Agent | https.Agent | false;\n createConnection?: http.RequestOptions['createConnection'];\n now?: () => number;\n timeoutMs?: number;\n maxResponseBytes?: number;\n maxOutputBytes?: number;\n maxRedirects?: number;\n allowBlockedAddressesForTests?: boolean;\n /** Test seam for proving extraction remains inside the full-operation deadline. */\n extractContent?: FusionContentExtractor;\n}\n\ninterface NormalizedRequestUrl {\n url: URL;\n hostname: string;\n}\n\ninterface VettedHost {\n selectedAddress: FusionDnsAddress;\n resolvedAddresses: readonly FusionDnsAddress[];\n}\n\ninterface FetchOneSuccess {\n kind: 'success';\n status: number;\n contentType: string;\n body: Buffer;\n}\n\ninterface FetchOneRedirect {\n kind: 'redirect';\n status: number;\n location: string;\n}\n\ntype FetchOneResult = FetchOneSuccess | FetchOneRedirect;\n\ninterface EffectiveOptions {\n lookup: FusionDnsLookup;\n request: FusionTransportRequest;\n agent: http.Agent | https.Agent | false;\n createConnection?: http.RequestOptions['createConnection'];\n now: () => number;\n timeoutMs: number;\n maxResponseBytes: number;\n maxOutputBytes: number;\n maxRedirects: number;\n allowBlockedAddressesForTests: boolean;\n extractContent: FusionContentExtractor;\n}\n\ninterface ExtractionResult {\n content: string;\n format: 'text' | 'markdown';\n}\n\ninterface TableReplacement {\n token: string;\n markdown: string;\n}\n\ntype TurndownServiceConstructor = typeof TurndownService;\n\nlet turndownServiceLoad: Promise<TurndownServiceConstructor> | undefined;\n\nconst USER_AGENT = 'pi-background-tasks fusion_web_fetch/1.0';\nconst ACCEPT_HEADER = 'text/markdown, text/html;q=0.9, application/xhtml+xml;q=0.8, text/plain;q=0.7';\nconst METADATA_HOSTNAMES = new Set([\n 'metadata',\n 'metadata.local',\n 'metadata.google.internal',\n 'metadata.goog',\n 'instance-data',\n 'instance-data.ec2.internal',\n]);\n\nconst IPV4_DENY_RANGES: readonly [number, number][] = [\n [ipv4ToNumberLiteral('0.0.0.0'), 8],\n [ipv4ToNumberLiteral('10.0.0.0'), 8],\n [ipv4ToNumberLiteral('100.64.0.0'), 10],\n [ipv4ToNumberLiteral('127.0.0.0'), 8],\n [ipv4ToNumberLiteral('169.254.0.0'), 16],\n [ipv4ToNumberLiteral('172.16.0.0'), 12],\n [ipv4ToNumberLiteral('192.0.0.0'), 24],\n [ipv4ToNumberLiteral('192.0.2.0'), 24],\n [ipv4ToNumberLiteral('192.168.0.0'), 16],\n [ipv4ToNumberLiteral('198.18.0.0'), 15],\n [ipv4ToNumberLiteral('198.51.100.0'), 24],\n [ipv4ToNumberLiteral('203.0.113.0'), 24],\n [ipv4ToNumberLiteral('224.0.0.0'), 4],\n [ipv4ToNumberLiteral('240.0.0.0'), 4],\n [ipv4ToNumberLiteral('255.255.255.255'), 32],\n [ipv4ToNumberLiteral('169.254.169.254'), 32],\n] as const;\n\nconst IPV6_DENY_RANGES: readonly [bigint, number][] = [\n [ipv6ToBigIntLiteral('::'), 128],\n [ipv6ToBigIntLiteral('::1'), 128],\n [ipv6ToBigIntLiteral('64:ff9b::'), 96],\n [ipv6ToBigIntLiteral('64:ff9b:1::'), 48],\n [ipv6ToBigIntLiteral('100::'), 64],\n [ipv6ToBigIntLiteral('2001:2::'), 48],\n [ipv6ToBigIntLiteral('2001:db8::'), 32],\n [ipv6ToBigIntLiteral('2002::'), 16],\n [ipv6ToBigIntLiteral('fc00::'), 7],\n [ipv6ToBigIntLiteral('fe80::'), 10],\n [ipv6ToBigIntLiteral('ff00::'), 8],\n [ipv6ToBigIntLiteral('fd00:ec2::254'), 128],\n [ipv6ToBigIntLiteral('::ffff:0:0'), 96],\n] as const;\n\nexport class FusionWebFetchError extends Error {\n public readonly code: FusionWebFetchErrorCode;\n public readonly url?: string;\n public readonly status?: number;\n\n public constructor(\n code: FusionWebFetchErrorCode,\n message: string,\n details: { url?: string; status?: number; cause?: Error } = {},\n ) {\n super(message, details.cause === undefined ? undefined : { cause: details.cause });\n this.name = 'FusionWebFetchError';\n this.code = code;\n if (details.url !== undefined) this.url = details.url;\n if (details.status !== undefined) this.status = details.status;\n }\n}\n\nexport async function fusionWebFetch(\n req: FusionWebFetchRequest,\n options: FusionWebFetchOptions = {},\n): Promise<FusionWebFetchResult> {\n const effective = mergeOptions(options);\n const requestedFormat = req.extract ?? 'markdown';\n const start = effective.now();\n const deadlineMs = start + effective.timeoutMs;\n const requestedUrl = normalizeRequestUrl(req.url).url;\n let currentUrl = requestedUrl;\n\n for (let redirectCount = 0; ; redirectCount += 1) {\n const remainingMs = deadlineMs - effective.now();\n if (remainingMs <= 0) {\n throw new FusionWebFetchError('request_timeout', 'fusion_web_fetch request timeout elapsed', {\n url: currentUrl.toString(),\n });\n }\n\n const result = await fetchOne(currentUrl, effective, deadlineMs, redirectCount > 0);\n if (result.kind === 'redirect') {\n if (redirectCount >= effective.maxRedirects) {\n throw new FusionWebFetchError(\n 'redirect_limit',\n `fusion_web_fetch redirect limit exceeded (${String(effective.maxRedirects)})`,\n { url: currentUrl.toString(), status: result.status },\n );\n }\n currentUrl = normalizeRedirectUrl(currentUrl, result.location);\n continue;\n }\n\n const extracted = await extractWithinDeadline(\n result.body,\n result.contentType,\n requestedFormat,\n effective,\n deadlineMs,\n currentUrl,\n );\n const capped = capUtf8Bytes(extracted.content, effective.maxOutputBytes);\n const contentSha256 = createHash('sha256').update(result.body).digest('hex');\n assertFetchDeadline(effective, deadlineMs, currentUrl, 'content extraction');\n const durationMs = Math.max(0, effective.now() - start);\n if (durationMs > effective.timeoutMs) {\n throw fetchTimeout(currentUrl, 'content extraction');\n }\n return {\n url: requestedUrl.toString(),\n final_url: currentUrl.toString(),\n status: result.status,\n content_type: result.contentType,\n format: extracted.format,\n truncated: capped.truncated,\n content: capped.content,\n response_bytes: result.body.byteLength,\n content_sha256: contentSha256,\n duration_ms: durationMs,\n };\n }\n}\n\nfunction mergeOptions(options: FusionWebFetchOptions): EffectiveOptions {\n return {\n lookup: options.lookup ?? defaultLookup,\n request: options.request ?? defaultTransportRequest,\n agent: options.agent ?? false,\n createConnection: options.createConnection,\n now: options.now ?? (() => performance.now()),\n timeoutMs: options.timeoutMs ?? FUSION_WEB_FETCH_TIMEOUT_MS,\n maxResponseBytes: options.maxResponseBytes ?? FUSION_WEB_FETCH_MAX_RESPONSE_BYTES,\n maxOutputBytes: options.maxOutputBytes ?? FUSION_WEB_FETCH_MAX_OUTPUT_BYTES,\n maxRedirects: options.maxRedirects ?? FUSION_WEB_FETCH_MAX_REDIRECTS,\n allowBlockedAddressesForTests: options.allowBlockedAddressesForTests ?? false,\n extractContent: options.extractContent ?? extractContent,\n };\n}\n\nfunction fetchTimeout(url: URL, phase: string): FusionWebFetchError {\n return new FusionWebFetchError(\n 'request_timeout',\n `fusion_web_fetch request timeout elapsed during ${phase}`,\n { url: url.toString() },\n );\n}\n\nfunction assertFetchDeadline(\n options: EffectiveOptions,\n deadlineMs: number,\n url: URL,\n phase: string,\n): number {\n const remainingMs = deadlineMs - options.now();\n if (remainingMs <= 0) throw fetchTimeout(url, phase);\n return remainingMs;\n}\n\nasync function extractWithinDeadline(\n body: Buffer,\n contentType: string,\n requestedFormat: 'text' | 'markdown',\n options: EffectiveOptions,\n deadlineMs: number,\n url: URL,\n): Promise<ExtractionResult> {\n const remainingMs = assertFetchDeadline(options, deadlineMs, url, 'content extraction');\n let timer: NodeJS.Timeout | undefined;\n try {\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(fetchTimeout(url, 'content extraction')), remainingMs);\n });\n const extraction = Promise.resolve().then(() =>\n options.extractContent(body, contentType, requestedFormat),\n );\n const result = await Promise.race([extraction, timeout]);\n assertFetchDeadline(options, deadlineMs, url, 'content extraction');\n return result;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\nfunction normalizeRequestUrl(rawUrl: string): NormalizedRequestUrl {\n let parsed: URL;\n try {\n parsed = new URL(rawUrl.trim());\n } catch (error) {\n throw new FusionWebFetchError(\n 'invalid_url',\n 'fusion_web_fetch requires a valid absolute URL',\n error instanceof Error ? { cause: error } : {},\n );\n }\n\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new FusionWebFetchError(\n 'unsupported_scheme',\n 'fusion_web_fetch supports only absolute http: and https: URLs',\n { url: rawUrl },\n );\n }\n if (parsed.username !== '' || parsed.password !== '') {\n throw new FusionWebFetchError('invalid_url', 'fusion_web_fetch URL credentials are blocked', {\n url: rawUrl,\n });\n }\n if (parsed.hostname.length === 0) {\n throw new FusionWebFetchError('invalid_url', 'fusion_web_fetch URL host is required', {\n url: rawUrl,\n });\n }\n\n parsed.hash = '';\n return { url: parsed, hostname: normalizeHostname(parsed.hostname) };\n}\n\nfunction normalizeRedirectUrl(baseUrl: URL, location: string): URL {\n let next: URL;\n try {\n next = new URL(location, baseUrl);\n } catch (error) {\n throw new FusionWebFetchError(\n 'redirect_blocked',\n 'fusion_web_fetch redirect target is not a valid URL',\n error instanceof Error ? { url: baseUrl.toString(), cause: error } : { url: baseUrl.toString() },\n );\n }\n\n try {\n return normalizeRequestUrl(next.toString()).url;\n } catch (error) {\n if (error instanceof FusionWebFetchError) {\n throw new FusionWebFetchError('redirect_blocked', `fusion_web_fetch redirect blocked: ${error.message}`, {\n url: next.toString(),\n cause: error,\n });\n }\n throw error;\n }\n}\n\nasync function fetchOne(\n url: URL,\n options: EffectiveOptions,\n deadlineMs: number,\n redirectHop: boolean,\n): Promise<FetchOneResult> {\n const normalized = normalizeRequestUrl(url.toString());\n const vetted = await vetHost(\n normalized.hostname,\n options,\n redirectHop,\n normalized.url.toString(),\n deadlineMs,\n );\n const remainingMs = deadlineMs - options.now();\n if (remainingMs <= 0) {\n throw new FusionWebFetchError('request_timeout', 'fusion_web_fetch request timeout elapsed', {\n url: normalized.url.toString(),\n });\n }\n return await executeRequest(normalized.url, vetted.selectedAddress, options, remainingMs);\n}\n\nasync function vetHost(\n hostname: string,\n options: EffectiveOptions,\n redirectHop: boolean,\n url: string,\n deadlineMs: number,\n): Promise<VettedHost> {\n if (METADATA_HOSTNAMES.has(hostname) || hostname === 'localhost' || hostname.endsWith('.localhost')) {\n throwAddressError(redirectHop, `fusion_web_fetch blocked host: ${hostname}`, url);\n }\n\n const literalFamily = isIP(hostname);\n const literalAddress: FusionDnsAddress = { address: hostname, family: literalFamily === 4 ? 4 : 6 };\n const resolvedAddresses =\n literalFamily === 0\n ? await resolveWithLookup(hostname, options.lookup, url, deadlineMs - options.now())\n : [literalAddress];\n\n if (resolvedAddresses.length === 0) {\n throw new FusionWebFetchError('dns_failure', `DNS lookup returned no addresses for ${hostname}`, { url });\n }\n\n for (const address of resolvedAddresses) {\n const classification = classifyAddress(address.address);\n if (!classification.public && !options.allowBlockedAddressesForTests) {\n throwAddressError(\n redirectHop,\n `fusion_web_fetch blocked non-public address for ${hostname}: ${address.address}`,\n url,\n );\n }\n }\n\n const selectedAddress = resolvedAddresses[0];\n if (selectedAddress === undefined) {\n throw new FusionWebFetchError('dns_failure', `DNS lookup returned no addresses for ${hostname}`, { url });\n }\n return { selectedAddress, resolvedAddresses };\n}\n\nfunction throwAddressError(redirectHop: boolean, message: string, url: string): never {\n throw new FusionWebFetchError(redirectHop ? 'redirect_blocked' : 'blocked_address', message, { url });\n}\n\nasync function resolveWithLookup(\n hostname: string,\n lookup: FusionDnsLookup,\n url: string,\n remainingMs: number,\n): Promise<readonly FusionDnsAddress[]> {\n if (remainingMs <= 0) {\n throw new FusionWebFetchError('request_timeout', 'fusion_web_fetch request timeout elapsed', { url });\n }\n let timer: NodeJS.Timeout | undefined;\n try {\n return await Promise.race([\n lookup(hostname),\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new FusionWebFetchError(\n 'request_timeout',\n 'fusion_web_fetch request timeout elapsed during DNS lookup',\n { url },\n ),\n ),\n Math.max(1, remainingMs),\n );\n }),\n ]);\n } catch (error) {\n if (error instanceof FusionWebFetchError) throw error;\n throw new FusionWebFetchError(\n 'dns_failure',\n `DNS lookup failed for ${hostname}: ${error instanceof Error ? error.message : 'unknown error'}`,\n error instanceof Error ? { url, cause: error } : { url },\n );\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\nfunction executeRequest(\n url: URL,\n selectedAddress: FusionDnsAddress,\n options: EffectiveOptions,\n remainingMs: number,\n): Promise<FetchOneResult> {\n return new Promise<FetchOneResult>((resolve, reject) => {\n let settled = false;\n let requestSocket: { destroy: () => void } | undefined;\n let timer: NodeJS.Timeout | undefined;\n\n const settleResolve = (result: FetchOneResult): void => {\n if (settled) return;\n settled = true;\n if (timer !== undefined) clearTimeout(timer);\n resolve(result);\n };\n const settleReject = (error: FusionWebFetchError): void => {\n if (settled) return;\n settled = true;\n if (timer !== undefined) clearTimeout(timer);\n reject(error);\n };\n\n const request = options.request(url.protocol as 'http:' | 'https:', buildRequestOptions(url, selectedAddress, options));\n timer = setTimeout(() => {\n settleReject(new FusionWebFetchError('request_timeout', 'fusion_web_fetch request timeout elapsed', {\n url: url.toString(),\n }));\n request.destroy();\n requestSocket?.destroy();\n }, Math.max(1, remainingMs));\n request.once('socket', (socket) => {\n requestSocket = socket;\n });\n request.once('response', (response) => {\n const remoteAddress = response.socket.remoteAddress;\n if (!addressMatches(selectedAddress.address, remoteAddress)) {\n response.destroy();\n settleReject(\n new FusionWebFetchError(\n 'blocked_address',\n `fusion_web_fetch socket remote address mismatch: expected ${selectedAddress.address}, got ${remoteAddress ?? 'missing'}`,\n errorDetails(url.toString(), response.statusCode),\n ),\n );\n return;\n }\n const remoteClass = classifyAddress(remoteAddress ?? '');\n if (!remoteClass.public && !options.allowBlockedAddressesForTests) {\n response.destroy();\n settleReject(\n new FusionWebFetchError(\n 'blocked_address',\n 'fusion_web_fetch socket remote address is blocked',\n errorDetails(url.toString(), response.statusCode),\n ),\n );\n return;\n }\n\n const status = response.statusCode ?? 0;\n const location = firstHeader(response, 'location');\n if (isRedirectStatus(status)) {\n // Redirect payloads are never consumed. Destroy the response/socket before\n // advancing so an endless or oversized redirect body cannot outlive this hop.\n response.destroy();\n if (location === undefined || location.trim().length === 0) {\n settleReject(\n new FusionWebFetchError('http_error', `fusion_web_fetch redirect status ${String(status)} lacks Location`, {\n url: url.toString(),\n status,\n }),\n );\n return;\n }\n settleResolve({ kind: 'redirect', status, location });\n return;\n }\n\n if (status < 200 || status > 299) {\n response.destroy();\n settleReject(\n new FusionWebFetchError('http_error', `fusion_web_fetch HTTP status ${String(status)}`, {\n url: url.toString(),\n status,\n }),\n );\n return;\n }\n\n const contentType = firstHeader(response, 'content-type') ?? '';\n const contentTypeError = unsupportedContentTypeError(contentType, url.toString(), status);\n if (contentTypeError !== undefined) {\n response.destroy();\n settleReject(contentTypeError);\n return;\n }\n let contentLength: number | undefined;\n try {\n contentLength = readContentLength(firstHeader(response, 'content-length'), url.toString(), status);\n } catch (error) {\n response.destroy();\n settleReject(\n error instanceof FusionWebFetchError\n ? error\n : new FusionWebFetchError('network_error', 'fusion_web_fetch invalid Content-Length check failed'),\n );\n return;\n }\n if (contentLength !== undefined && contentLength > options.maxResponseBytes) {\n response.destroy();\n settleReject(\n new FusionWebFetchError('response_too_large', 'fusion_web_fetch Content-Length exceeds response cap', {\n url: url.toString(),\n status,\n }),\n );\n return;\n }\n\n let bytesRead = 0;\n const chunks: Buffer[] = [];\n response.on('data', (chunk: Buffer) => {\n const nextBytesRead = bytesRead + chunk.byteLength;\n if (nextBytesRead > options.maxResponseBytes) {\n response.destroy();\n settleReject(\n new FusionWebFetchError('response_too_large', 'fusion_web_fetch streamed body exceeds response cap', {\n url: url.toString(),\n status,\n }),\n );\n return;\n }\n bytesRead = nextBytesRead;\n chunks.push(chunk);\n });\n response.once('end', () => {\n settleResolve({ kind: 'success', status, contentType, body: Buffer.concat(chunks, bytesRead) });\n });\n response.once('error', (error) => {\n settleReject(mapNetworkError(error, url.toString(), status));\n });\n });\n request.once('error', (error) => {\n settleReject(mapNetworkError(error, url.toString()));\n });\n request.end();\n });\n}\n\nfunction buildRequestOptions(\n url: URL,\n selectedAddress: FusionDnsAddress,\n options: EffectiveOptions,\n): http.RequestOptions | https.RequestOptions {\n const requestOptions: https.RequestOptions = {\n protocol: url.protocol,\n hostname: url.hostname,\n port: url.port,\n family: selectedAddress.family,\n method: 'GET',\n path: `${url.pathname}${url.search}`,\n agent: options.agent,\n headers: {\n Accept: ACCEPT_HEADER,\n 'Accept-Encoding': 'identity',\n Host: url.host,\n 'User-Agent': USER_AGENT,\n },\n lookup: forceSelectedLookup(selectedAddress),\n };\n if (url.protocol === 'https:') requestOptions.servername = normalizeHostname(url.hostname);\n if (options.createConnection !== undefined) requestOptions.createConnection = options.createConnection;\n return requestOptions;\n}\n\nfunction forceSelectedLookup(selectedAddress: FusionDnsAddress): NonNullable<http.RequestOptions['lookup']> {\n // Every DNS answer is vetted before this point. The request then receives a lookup hook\n // that can return only the vetted address, and the response socket is checked against it.\n // That pins the connection to the reviewed IP and closes the DNS rebinding gap from\n // validate-then-call-global-fetch implementations.\n return (_hostname, lookupOptions, callback) => {\n if (typeof lookupOptions === 'object' && lookupOptions.all === true) {\n const allCallback = callback as (error: NodeJS.ErrnoException | null, addresses: FusionDnsAddress[]) => void;\n allCallback(null, [selectedAddress]);\n return;\n }\n callback(null, selectedAddress.address, selectedAddress.family);\n };\n}\n\nfunction defaultTransportRequest(\n protocol: 'http:' | 'https:',\n options: http.RequestOptions | https.RequestOptions,\n): http.ClientRequest {\n return protocol === 'https:' ? https.request(options) : http.request(options);\n}\n\nasync function defaultLookup(hostname: string): Promise<readonly FusionDnsAddress[]> {\n const records = await nodeLookup(hostname, { all: true, verbatim: true });\n return records.map((record) => ({ address: record.address, family: normalizeFamily(record.family) }));\n}\n\nfunction normalizeFamily(family: number): 4 | 6 {\n if (family === 4 || family === 6) return family;\n throw new Error(`Unsupported DNS address family: ${String(family)}`);\n}\n\nfunction firstHeader(response: http.IncomingMessage, name: string): string | undefined {\n const value = response.headers[name];\n if (Array.isArray(value)) return value.join(', ');\n return value;\n}\n\nfunction isRedirectStatus(status: number): boolean {\n return status === 300 || status === 301 || status === 302 || status === 303 || status === 307 || status === 308;\n}\n\nfunction mapNetworkError(error: Error, url: string, status?: number): FusionWebFetchError {\n if (error instanceof FusionWebFetchError) return error;\n return new FusionWebFetchError(\n 'network_error',\n `fusion_web_fetch network error: ${error.message}`,\n errorDetails(url, status, error),\n );\n}\n\nfunction errorDetails(\n url: string,\n status?: number,\n cause?: Error,\n): { url: string; status?: number; cause?: Error } {\n const details: { url: string; status?: number; cause?: Error } = { url };\n if (status !== undefined) details.status = status;\n if (cause !== undefined) details.cause = cause;\n return details;\n}\n\nfunction unsupportedContentTypeError(\n contentType: string,\n url: string,\n status: number,\n): FusionWebFetchError | undefined {\n const mediaType = mediaTypeFromContentType(contentType);\n if (\n mediaType === 'text/html' ||\n mediaType === 'application/xhtml+xml' ||\n mediaType === 'text/plain' ||\n mediaType === 'text/markdown'\n ) {\n return undefined;\n }\n return new FusionWebFetchError(\n 'unsupported_content_type',\n `fusion_web_fetch unsupported content type: ${contentType.length === 0 ? 'missing' : contentType}`,\n { url, status },\n );\n}\n\nfunction readContentLength(value: string | undefined, url: string, status: number): number | undefined {\n if (value === undefined) return undefined;\n const trimmed = value.trim();\n if (!/^\\d+$/u.test(trimmed)) {\n throw new FusionWebFetchError('network_error', 'fusion_web_fetch invalid Content-Length header', { url, status });\n }\n return Number(trimmed);\n}\n\nasync function extractContent(\n body: Buffer,\n contentType: string,\n requestedFormat: 'text' | 'markdown',\n): Promise<ExtractionResult> {\n try {\n const mediaType = mediaTypeFromContentType(contentType);\n const decoded = decodeBody(body, contentType);\n if (mediaType === 'text/plain') return { content: decoded, format: 'text' };\n if (mediaType === 'text/markdown') return { content: decoded, format: 'markdown' };\n if (requestedFormat === 'text') return { content: htmlToText(decoded), format: 'text' };\n return { content: await htmlToMarkdown(decoded), format: 'markdown' };\n } catch (error) {\n if (error instanceof FusionWebFetchError) throw error;\n throw new FusionWebFetchError(\n 'extraction_failed',\n `fusion_web_fetch extraction failed: ${error instanceof Error ? error.message : 'unknown error'}`,\n error instanceof Error ? { cause: error } : {},\n );\n }\n}\n\nfunction decodeBody(body: Buffer, contentType: string): string {\n const charset = charsetFromContentType(contentType) ?? 'utf-8';\n try {\n return new TextDecoder(charset, { fatal: true, ignoreBOM: false }).decode(body);\n } catch (error) {\n throw new FusionWebFetchError(\n 'extraction_failed',\n `fusion_web_fetch response body could not be decoded as ${charset}`,\n error instanceof Error ? { cause: error } : {},\n );\n }\n}\n\nfunction mediaTypeFromContentType(contentType: string): string {\n return contentType.split(';')[0]?.trim().toLowerCase() ?? '';\n}\n\nfunction charsetFromContentType(contentType: string): string | undefined {\n for (const parameter of contentType.split(';').slice(1)) {\n const separator = parameter.indexOf('=');\n if (separator < 0) continue;\n const key = parameter.slice(0, separator).trim().toLowerCase();\n if (key !== 'charset') continue;\n const value = stripAsciiQuotes(parameter.slice(separator + 1).trim());\n if (value.length === 0) throw new FusionWebFetchError('extraction_failed', 'fusion_web_fetch charset is empty');\n return value;\n }\n return undefined;\n}\n\nfunction stripAsciiQuotes(value: string): string {\n if (value.length >= 2 && value.startsWith('\"') && value.endsWith('\"')) return value.slice(1, -1);\n return value;\n}\n\nasync function htmlToMarkdown(html: string): Promise<string> {\n const TurndownServiceClass = await loadTurndownService();\n const stripped = stripUnsafeHtmlBlocks(html);\n const tables = replaceTablesWithTokens(stripped);\n const turndown = new TurndownServiceClass({ bulletListMarker: '-', codeBlockStyle: 'fenced', headingStyle: 'atx' });\n let markdown = turndown.turndown(tables.html).trim();\n for (const table of tables.replacements) {\n markdown = markdown.replace(table.token, table.markdown);\n }\n return markdown.trim();\n}\n\nasync function loadTurndownService(): Promise<TurndownServiceConstructor> {\n if (turndownServiceLoad === undefined) {\n turndownServiceLoad = import('turndown').then((module) => module.default);\n }\n try {\n return await turndownServiceLoad;\n } catch (error) {\n turndownServiceLoad = undefined;\n throw normalizeTurndownLoadError(error);\n }\n}\n\nfunction normalizeTurndownLoadError(error: unknown): Error {\n if (isMissingTurndownDependency(error)) {\n const details = error instanceof Error ? { cause: error } : {};\n return new FusionWebFetchError(\n 'extraction_failed',\n 'fusion_web_fetch markdown extraction dependency \"turndown\" is missing from pi-background-tasks; repair the package install with `pi update --extensions` or `npm install --omit=dev --prefix <pi-background-tasks>`.',\n details,\n );\n }\n if (error instanceof Error) return error;\n return new Error(`fusion_web_fetch markdown extraction dependency failed to load: ${String(error)}`);\n}\n\nfunction isMissingTurndownDependency(error: unknown): boolean {\n const code = errorCode(error);\n if (code !== 'MODULE_NOT_FOUND' && code !== 'ERR_MODULE_NOT_FOUND') return false;\n return errorMessage(error).includes('turndown');\n}\n\nfunction errorCode(error: unknown): string | undefined {\n if (typeof error !== 'object' || error === null) return undefined;\n const code = Reflect.get(error, 'code');\n return typeof code === 'string' ? code : undefined;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction htmlToText(html: string): string {\n const withoutBlocks = stripUnsafeHtmlBlocks(html);\n const withBreaks = withoutBlocks\n .replace(/<br\\s*\\/?\\s*>/giu, '\\n')\n .replace(/<\\/(p|div|section|article|header|footer|li|tr|h[1-6]|pre)>/giu, '\\n')\n .replace(/<[^>]+>/gu, ' ');\n return decodeHtmlEntities(withBreaks)\n .split(/\\r?\\n/u)\n .map((line) => line.replace(/[\\t\\f\\v ]+/gu, ' ').trim())\n .filter((line) => line.length > 0)\n .join('\\n');\n}\n\nfunction stripUnsafeHtmlBlocks(html: string): string {\n return html.replace(/<(script|style|noscript)\\b[^>]*>[\\s\\S]*?<\\/\\1>/giu, '');\n}\n\nfunction replaceTablesWithTokens(html: string): { html: string; replacements: readonly TableReplacement[] } {\n const replacements: TableReplacement[] = [];\n const replaced = html.replace(/<table\\b[^>]*>[\\s\\S]*?<\\/table>/giu, (tableHtml) => {\n const markdown = tableToMarkdown(tableHtml);\n if (markdown.length === 0) return '';\n const token = `FUSIONWEBFETCHTABLE${String(replacements.length)}TOKEN`;\n replacements.push({ token, markdown });\n return `<p>${token}</p>`;\n });\n return { html: replaced, replacements };\n}\n\nfunction tableToMarkdown(tableHtml: string): string {\n const rows: string[][] = [];\n for (const rowMatch of tableHtml.matchAll(/<tr\\b[^>]*>([\\s\\S]*?)<\\/tr>/giu)) {\n const rowHtml = rowMatch[1] ?? '';\n const cells = [...rowHtml.matchAll(/<(?:th|td)\\b[^>]*>([\\s\\S]*?)<\\/(?:th|td)>/giu)].map((cellMatch) =>\n inlineHtmlToText(cellMatch[1] ?? ''),\n );\n if (cells.length > 0) rows.push(cells);\n }\n if (rows.length === 0) return '';\n const columnCount = Math.max(...rows.map((row) => row.length));\n const normalizedRows = rows.map((row) => [...row, ...Array.from({ length: columnCount - row.length }, () => '')]);\n const header = normalizedRows[0] ?? [];\n const separator = Array.from({ length: columnCount }, () => '---');\n const bodyRows = normalizedRows.slice(1);\n return [header, separator, ...bodyRows].map(markdownTableRow).join('\\n');\n}\n\nfunction markdownTableRow(cells: readonly string[]): string {\n return `| ${cells.map((cell) => cell.replace(/\\|/gu, '\\\\|')).join(' | ')} |`;\n}\n\nfunction inlineHtmlToText(html: string): string {\n return decodeHtmlEntities(html.replace(/<[^>]+>/gu, ' ')).replace(/[\\t\\n\\f\\r ]+/gu, ' ').trim();\n}\n\nfunction decodeHtmlEntities(value: string): string {\n return value.replace(/&(#x[0-9a-f]+|#\\d+|amp|lt|gt|quot|apos|nbsp);/giu, (_match, entity: string) => {\n const lower = entity.toLowerCase();\n if (lower === 'amp') return '&';\n if (lower === 'lt') return '<';\n if (lower === 'gt') return '>';\n if (lower === 'quot') return '\"';\n if (lower === 'apos') return \"'\";\n if (lower === 'nbsp') return ' ';\n if (lower.startsWith('#x')) return codePointToString(Number.parseInt(lower.slice(2), 16));\n if (lower.startsWith('#')) return codePointToString(Number.parseInt(lower.slice(1), 10));\n return `&${entity};`;\n });\n}\n\nfunction codePointToString(value: number): string {\n if (!Number.isFinite(value) || value < 0 || value > 0x10ffff) return '';\n return String.fromCodePoint(value);\n}\n\nfunction capUtf8Bytes(content: string, maxBytes: number): { content: string; truncated: boolean } {\n let usedBytes = 0;\n let output = '';\n for (const character of content) {\n const nextBytes = Buffer.byteLength(character, 'utf8');\n if (usedBytes + nextBytes > maxBytes) return { content: output, truncated: true };\n usedBytes += nextBytes;\n output += character;\n }\n return { content, truncated: false };\n}\n\nfunction normalizeHostname(hostname: string): string {\n const withoutBrackets = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n const lower = withoutBrackets.toLowerCase();\n return lower.endsWith('.') ? lower.slice(0, -1) : lower;\n}\n\nfunction classifyAddress(address: string): { public: boolean } {\n const ipv4 = parseIpv4Address(address);\n if (ipv4 !== undefined) return { public: !IPV4_DENY_RANGES.some(([base, prefix]) => ipv4InRange(ipv4, base, prefix)) };\n const ipv6 = parseIpv6Address(address);\n if (ipv6 !== undefined) return { public: !IPV6_DENY_RANGES.some(([base, prefix]) => ipv6InRange(ipv6, base, prefix)) };\n return { public: false };\n}\n\nfunction addressMatches(expected: string, actual: string | undefined): boolean {\n if (actual === undefined || actual.length === 0) return false;\n const expectedComparable = comparableAddress(expected);\n const actualComparable = comparableAddress(actual);\n return (\n expectedComparable !== undefined &&\n actualComparable !== undefined &&\n expectedComparable.family === actualComparable.family &&\n expectedComparable.value === actualComparable.value\n );\n}\n\nfunction comparableAddress(address: string): { family: 4 | 6; value: bigint } | undefined {\n const ipv4 = parseIpv4Address(address);\n if (ipv4 !== undefined) return { family: 4, value: BigInt(ipv4) };\n const ipv6 = parseIpv6Address(address);\n if (ipv6 === undefined) return undefined;\n const mapped = ipv4FromMappedIpv6(ipv6);\n if (mapped !== undefined) return { family: 4, value: BigInt(mapped) };\n return { family: 6, value: ipv6 };\n}\n\nfunction parseIpv4Address(address: string): number | undefined {\n const pieces = address.split('.');\n if (pieces.length !== 4) return undefined;\n let value = 0;\n for (const piece of pieces) {\n if (!/^\\d{1,3}$/u.test(piece)) return undefined;\n const octet = Number(piece);\n if (!Number.isInteger(octet) || octet < 0 || octet > 255) return undefined;\n value = value * 256 + octet;\n }\n return value;\n}\n\nfunction ipv4ToNumberLiteral(address: string): number {\n const parsed = parseIpv4Address(address);\n if (parsed === undefined) throw new Error(`Invalid IPv4 literal in source: ${address}`);\n return parsed;\n}\n\nfunction parseIpv6Address(address: string): bigint | undefined {\n if (address.includes('%')) return undefined;\n const rawSides = address.toLowerCase().split('::');\n if (rawSides.length > 2) return undefined;\n const left = parseIpv6Side(rawSides[0] ?? '');\n const right = parseIpv6Side(rawSides[1] ?? '');\n if (left === undefined || right === undefined) return undefined;\n const compressed = rawSides.length === 2;\n const missing = 8 - left.length - right.length;\n if ((!compressed && missing !== 0) || (compressed && missing < 1)) return undefined;\n const hextets = compressed ? [...left, ...Array.from({ length: missing }, () => 0), ...right] : left;\n if (hextets.length !== 8) return undefined;\n return hextets.reduce((value, hextet) => (value << 16n) + BigInt(hextet), 0n);\n}\n\nfunction parseIpv6Side(side: string): number[] | undefined {\n if (side.length === 0) return [];\n const parts = side.split(':');\n const hextets: number[] = [];\n for (const [index, part] of parts.entries()) {\n if (part.includes('.')) {\n if (index !== parts.length - 1) return undefined;\n const ipv4 = parseIpv4Address(part);\n if (ipv4 === undefined) return undefined;\n hextets.push(Math.floor(ipv4 / 0x10000), ipv4 % 0x10000);\n continue;\n }\n if (!/^[0-9a-f]{1,4}$/u.test(part)) return undefined;\n hextets.push(Number.parseInt(part, 16));\n }\n return hextets;\n}\n\nfunction ipv6ToBigIntLiteral(address: string): bigint {\n const parsed = parseIpv6Address(address);\n if (parsed === undefined) throw new Error(`Invalid IPv6 literal in source: ${address}`);\n return parsed;\n}\n\nfunction ipv4FromMappedIpv6(address: bigint): number | undefined {\n const mappedPrefix = ipv6ToBigIntLiteral('::ffff:0:0');\n if (!ipv6InRange(address, mappedPrefix, 96)) return undefined;\n return Number(address & 0xffffffffn);\n}\n\nfunction ipv4InRange(address: number, base: number, prefix: number): boolean {\n const divisor = 2 ** (32 - prefix);\n return Math.floor(address / divisor) === Math.floor(base / divisor);\n}\n\nfunction ipv6InRange(address: bigint, base: bigint, prefix: number): boolean {\n const shift = BigInt(128 - prefix);\n return address >> shift === base >> shift;\n}\n"]}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { FUSION_EVALUATION_REPAIR_SYSTEM_PROMPT, FUSION_EVALUATOR_SYSTEM_PROMPT, FUSION_MERGER_SYSTEM_PROMPT, FUSION_VALIDATE_EVALUATION_REPAIR_SYSTEM_PROMPT, FUSION_VALIDATE_EVALUATOR_SYSTEM_PROMPT, FUSION_VALIDATE_MERGER_SYSTEM_PROMPT, fusionCandidateSystemPrompt, fusionValidateCandidateSystemPrompt, } from './prompts.js';
|
|
2
|
+
import { FUSION_INSPECT_TOOLS, FUSION_NO_TOOLS_CAPABILITY, FUSION_RESEARCH_TOOLS, FUSION_VALIDATE_CAPABILITY, FusionError, } from './types.js';
|
|
3
|
+
export const FUSION_REASON_TOOL_NAME = 'fusion_reason';
|
|
4
|
+
export const FUSION_INVESTIGATE_TOOL_NAME = 'fusion_investigate';
|
|
5
|
+
export const FUSION_RESEARCH_TOOL_NAME = 'fusion_research';
|
|
6
|
+
export const FUSION_VALIDATE_TOOL_NAME = 'fusion_validate';
|
|
7
|
+
/** @deprecated v4 recursion-denylist compatibility only; do not register new public APIs with this name. */
|
|
8
|
+
export const FUSION_BRAINSTORM_TOOL_NAME = 'fusion_brainstorm';
|
|
9
|
+
function freezeProfile(profile) {
|
|
10
|
+
const empty = Object.freeze([]);
|
|
11
|
+
return Object.freeze({
|
|
12
|
+
...profile,
|
|
13
|
+
candidateTools: Object.freeze([...profile.candidateTools]),
|
|
14
|
+
evaluatorTools: empty,
|
|
15
|
+
mergeTools: empty,
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
export const FUSION_REASON_WORKFLOW = freezeProfile({
|
|
19
|
+
id: 'reason',
|
|
20
|
+
publicName: FUSION_REASON_TOOL_NAME,
|
|
21
|
+
toolName: FUSION_REASON_TOOL_NAME,
|
|
22
|
+
runIdPrefix: 'reason-',
|
|
23
|
+
contextKind: 'session_projection',
|
|
24
|
+
candidateCapability: FUSION_NO_TOOLS_CAPABILITY,
|
|
25
|
+
candidateTools: [],
|
|
26
|
+
evaluatorCapability: FUSION_NO_TOOLS_CAPABILITY,
|
|
27
|
+
evaluatorTools: [],
|
|
28
|
+
mergeCapability: FUSION_NO_TOOLS_CAPABILITY,
|
|
29
|
+
mergeTools: [],
|
|
30
|
+
candidateSystemPrompt: fusionCandidateSystemPrompt,
|
|
31
|
+
evaluatorSystemPrompt: FUSION_EVALUATOR_SYSTEM_PROMPT,
|
|
32
|
+
evaluationRepairSystemPrompt: FUSION_EVALUATION_REPAIR_SYSTEM_PROMPT,
|
|
33
|
+
mergerSystemPrompt: FUSION_MERGER_SYSTEM_PROMPT,
|
|
34
|
+
label: 'fusion reason',
|
|
35
|
+
});
|
|
36
|
+
export const FUSION_INVESTIGATE_WORKFLOW = freezeProfile({
|
|
37
|
+
id: 'investigate',
|
|
38
|
+
publicName: FUSION_INVESTIGATE_TOOL_NAME,
|
|
39
|
+
toolName: FUSION_INVESTIGATE_TOOL_NAME,
|
|
40
|
+
runIdPrefix: 'investigate-',
|
|
41
|
+
contextKind: 'clean_task',
|
|
42
|
+
candidateCapability: 'inspect',
|
|
43
|
+
candidateTools: FUSION_INSPECT_TOOLS,
|
|
44
|
+
evaluatorCapability: FUSION_NO_TOOLS_CAPABILITY,
|
|
45
|
+
evaluatorTools: [],
|
|
46
|
+
mergeCapability: FUSION_NO_TOOLS_CAPABILITY,
|
|
47
|
+
mergeTools: [],
|
|
48
|
+
candidateSystemPrompt: fusionCandidateSystemPrompt,
|
|
49
|
+
evaluatorSystemPrompt: FUSION_EVALUATOR_SYSTEM_PROMPT,
|
|
50
|
+
evaluationRepairSystemPrompt: FUSION_EVALUATION_REPAIR_SYSTEM_PROMPT,
|
|
51
|
+
mergerSystemPrompt: FUSION_MERGER_SYSTEM_PROMPT,
|
|
52
|
+
label: 'fusion investigate',
|
|
53
|
+
});
|
|
54
|
+
export const FUSION_RESEARCH_WORKFLOW = freezeProfile({
|
|
55
|
+
id: 'research',
|
|
56
|
+
publicName: FUSION_RESEARCH_TOOL_NAME,
|
|
57
|
+
toolName: FUSION_RESEARCH_TOOL_NAME,
|
|
58
|
+
runIdPrefix: 'research-',
|
|
59
|
+
contextKind: 'clean_task',
|
|
60
|
+
candidateCapability: 'research',
|
|
61
|
+
candidateTools: FUSION_RESEARCH_TOOLS,
|
|
62
|
+
evaluatorCapability: FUSION_NO_TOOLS_CAPABILITY,
|
|
63
|
+
evaluatorTools: [],
|
|
64
|
+
mergeCapability: FUSION_NO_TOOLS_CAPABILITY,
|
|
65
|
+
mergeTools: [],
|
|
66
|
+
candidateSystemPrompt: fusionCandidateSystemPrompt,
|
|
67
|
+
evaluatorSystemPrompt: FUSION_EVALUATOR_SYSTEM_PROMPT,
|
|
68
|
+
evaluationRepairSystemPrompt: FUSION_EVALUATION_REPAIR_SYSTEM_PROMPT,
|
|
69
|
+
mergerSystemPrompt: FUSION_MERGER_SYSTEM_PROMPT,
|
|
70
|
+
label: 'fusion research',
|
|
71
|
+
});
|
|
72
|
+
export const FUSION_VALIDATE_WORKFLOW = freezeProfile({
|
|
73
|
+
id: 'validate',
|
|
74
|
+
publicName: FUSION_VALIDATE_TOOL_NAME,
|
|
75
|
+
toolName: FUSION_VALIDATE_TOOL_NAME,
|
|
76
|
+
runIdPrefix: 'validate-',
|
|
77
|
+
contextKind: 'clean_task',
|
|
78
|
+
candidateCapability: FUSION_VALIDATE_CAPABILITY,
|
|
79
|
+
candidateTools: FUSION_INSPECT_TOOLS,
|
|
80
|
+
evaluatorCapability: FUSION_NO_TOOLS_CAPABILITY,
|
|
81
|
+
evaluatorTools: [],
|
|
82
|
+
mergeCapability: FUSION_NO_TOOLS_CAPABILITY,
|
|
83
|
+
mergeTools: [],
|
|
84
|
+
candidateSystemPrompt: fusionValidateCandidateSystemPrompt,
|
|
85
|
+
evaluatorSystemPrompt: FUSION_VALIDATE_EVALUATOR_SYSTEM_PROMPT,
|
|
86
|
+
evaluationRepairSystemPrompt: FUSION_VALIDATE_EVALUATION_REPAIR_SYSTEM_PROMPT,
|
|
87
|
+
mergerSystemPrompt: FUSION_VALIDATE_MERGER_SYSTEM_PROMPT,
|
|
88
|
+
label: 'fusion validate',
|
|
89
|
+
});
|
|
90
|
+
const PROFILES_BY_ID = Object.freeze({
|
|
91
|
+
reason: FUSION_REASON_WORKFLOW,
|
|
92
|
+
investigate: FUSION_INVESTIGATE_WORKFLOW,
|
|
93
|
+
research: FUSION_RESEARCH_WORKFLOW,
|
|
94
|
+
validate: FUSION_VALIDATE_WORKFLOW,
|
|
95
|
+
});
|
|
96
|
+
export const FUSION_WORKFLOW_PROFILES = Object.freeze([
|
|
97
|
+
FUSION_REASON_WORKFLOW,
|
|
98
|
+
FUSION_INVESTIGATE_WORKFLOW,
|
|
99
|
+
FUSION_RESEARCH_WORKFLOW,
|
|
100
|
+
FUSION_VALIDATE_WORKFLOW,
|
|
101
|
+
]);
|
|
102
|
+
export function fusionWorkflowProfile(id) {
|
|
103
|
+
const profile = PROFILES_BY_ID[id];
|
|
104
|
+
if (profile === undefined) {
|
|
105
|
+
throw new FusionError(`unknown fusion workflow ${String(id)}`, {
|
|
106
|
+
code: 'orchestration_failed',
|
|
107
|
+
childCreated: false,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
return profile;
|
|
111
|
+
}
|
|
112
|
+
export function assertWorkflowCapability(profile, requested) {
|
|
113
|
+
if (requested !== undefined && requested !== profile.candidateCapability) {
|
|
114
|
+
throw new FusionError(`fusion workflow ${profile.id} always runs candidates with the ${profile.candidateCapability} capability; received ${String(requested)}`, { code: 'orchestration_failed', childCreated: false });
|
|
115
|
+
}
|
|
116
|
+
return profile.candidateCapability;
|
|
117
|
+
}
|
|
118
|
+
/** @deprecated v4 artifact/testing alias. The retired public tool is never registered. */
|
|
119
|
+
export const FUSION_BRAINSTORM_WORKFLOW = FUSION_REASON_WORKFLOW;
|
|
120
|
+
export const FUSION_REASON = FUSION_REASON_WORKFLOW;
|
|
121
|
+
export const FUSION_INVESTIGATE = FUSION_INVESTIGATE_WORKFLOW;
|
|
122
|
+
export const FUSION_RESEARCH = FUSION_RESEARCH_WORKFLOW;
|
|
123
|
+
export const FUSION_VALIDATE = FUSION_VALIDATE_WORKFLOW;
|
|
124
|
+
/** @deprecated v5 workflows do not default; retained for old imports. */
|
|
125
|
+
export const resolveWorkflowCapability = assertWorkflowCapability;
|
|
126
|
+
//# sourceMappingURL=workflows.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"workflows.js","sourceRoot":"","sources":["../../../../src/core/fusion/workflows.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sCAAsC,EACtC,8BAA8B,EAC9B,2BAA2B,EAC3B,+CAA+C,EAC/C,uCAAuC,EACvC,oCAA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,EAAE,YAAY,EAAE,KAAK,EAAE,CACtD,CAAC;IACJ,CAAC;IACD,OAAO,OAAO,CAAC,mBAAmB,CAAC;AACrC,CAAC;AAED,0FAA0F;AAC1F,MAAM,CAAC,MAAM,0BAA0B,GAAG,sBAAsB,CAAC;AAEjE,MAAM,CAAC,MAAM,aAAa,GAAG,sBAAsB,CAAC;AACpD,MAAM,CAAC,MAAM,kBAAkB,GAAG,2BAA2B,CAAC;AAC9D,MAAM,CAAC,MAAM,eAAe,GAAG,wBAAwB,CAAC;AACxD,MAAM,CAAC,MAAM,eAAe,GAAG,wBAAwB,CAAC;AAExD,yEAAyE;AACzE,MAAM,CAAC,MAAM,yBAAyB,GAAG,wBAAwB,CAAC","sourcesContent":["import {\n FUSION_EVALUATION_REPAIR_SYSTEM_PROMPT,\n FUSION_EVALUATOR_SYSTEM_PROMPT,\n FUSION_MERGER_SYSTEM_PROMPT,\n FUSION_VALIDATE_EVALUATION_REPAIR_SYSTEM_PROMPT,\n FUSION_VALIDATE_EVALUATOR_SYSTEM_PROMPT,\n FUSION_VALIDATE_MERGER_SYSTEM_PROMPT,\n fusionCandidateSystemPrompt,\n fusionValidateCandidateSystemPrompt,\n} from './prompts.js';\nimport {\n FUSION_INSPECT_TOOLS,\n FUSION_NO_TOOLS_CAPABILITY,\n FUSION_RESEARCH_TOOLS,\n FUSION_VALIDATE_CAPABILITY,\n FusionError,\n type FusionCapability,\n type FusionContextKind,\n type FusionPublicWorkflowName,\n type FusionWorkflowId,\n} from './types.js';\n\nexport const FUSION_REASON_TOOL_NAME = 'fusion_reason' as const;\nexport const FUSION_INVESTIGATE_TOOL_NAME = 'fusion_investigate' as const;\nexport const FUSION_RESEARCH_TOOL_NAME = 'fusion_research' as const;\nexport const FUSION_VALIDATE_TOOL_NAME = 'fusion_validate' as const;\n\n/** @deprecated v4 recursion-denylist compatibility only; do not register new public APIs with this name. */\nexport const FUSION_BRAINSTORM_TOOL_NAME = 'fusion_brainstorm' as const;\n\nexport interface FusionWorkflowProfile {\n readonly id: FusionWorkflowId;\n readonly publicName: FusionPublicWorkflowName;\n readonly toolName: FusionPublicWorkflowName;\n /** Human-readable run-id prefix, e.g. `reason-<hex>`. */\n readonly runIdPrefix: `${FusionWorkflowId}-`;\n readonly contextKind: FusionContextKind;\n readonly candidateCapability: FusionCapability;\n readonly candidateTools: readonly string[];\n readonly evaluatorCapability: typeof FUSION_NO_TOOLS_CAPABILITY;\n readonly evaluatorTools: readonly [];\n readonly mergeCapability: typeof FUSION_NO_TOOLS_CAPABILITY;\n readonly mergeTools: readonly [];\n readonly candidateSystemPrompt: (capability: FusionCapability) => string;\n readonly evaluatorSystemPrompt: string;\n readonly evaluationRepairSystemPrompt: string;\n readonly mergerSystemPrompt: string;\n readonly label: string;\n}\n\nfunction freezeProfile(profile: FusionWorkflowProfile): FusionWorkflowProfile {\n const empty = Object.freeze([]) as readonly [];\n return Object.freeze({\n ...profile,\n candidateTools: Object.freeze([...profile.candidateTools]),\n evaluatorTools: empty,\n mergeTools: empty,\n });\n}\n\nexport const FUSION_REASON_WORKFLOW = freezeProfile({\n id: 'reason',\n publicName: FUSION_REASON_TOOL_NAME,\n toolName: FUSION_REASON_TOOL_NAME,\n runIdPrefix: 'reason-',\n contextKind: 'session_projection',\n candidateCapability: FUSION_NO_TOOLS_CAPABILITY,\n candidateTools: [],\n evaluatorCapability: FUSION_NO_TOOLS_CAPABILITY,\n evaluatorTools: [],\n mergeCapability: FUSION_NO_TOOLS_CAPABILITY,\n mergeTools: [],\n candidateSystemPrompt: fusionCandidateSystemPrompt,\n evaluatorSystemPrompt: FUSION_EVALUATOR_SYSTEM_PROMPT,\n evaluationRepairSystemPrompt: FUSION_EVALUATION_REPAIR_SYSTEM_PROMPT,\n mergerSystemPrompt: FUSION_MERGER_SYSTEM_PROMPT,\n label: 'fusion reason',\n});\n\nexport const FUSION_INVESTIGATE_WORKFLOW = freezeProfile({\n id: 'investigate',\n publicName: FUSION_INVESTIGATE_TOOL_NAME,\n toolName: FUSION_INVESTIGATE_TOOL_NAME,\n runIdPrefix: 'investigate-',\n contextKind: 'clean_task',\n candidateCapability: 'inspect',\n candidateTools: FUSION_INSPECT_TOOLS,\n evaluatorCapability: FUSION_NO_TOOLS_CAPABILITY,\n evaluatorTools: [],\n mergeCapability: FUSION_NO_TOOLS_CAPABILITY,\n mergeTools: [],\n candidateSystemPrompt: fusionCandidateSystemPrompt,\n evaluatorSystemPrompt: FUSION_EVALUATOR_SYSTEM_PROMPT,\n evaluationRepairSystemPrompt: FUSION_EVALUATION_REPAIR_SYSTEM_PROMPT,\n mergerSystemPrompt: FUSION_MERGER_SYSTEM_PROMPT,\n label: 'fusion investigate',\n});\n\nexport const FUSION_RESEARCH_WORKFLOW = freezeProfile({\n id: 'research',\n publicName: FUSION_RESEARCH_TOOL_NAME,\n toolName: FUSION_RESEARCH_TOOL_NAME,\n runIdPrefix: 'research-',\n contextKind: 'clean_task',\n candidateCapability: 'research',\n candidateTools: FUSION_RESEARCH_TOOLS,\n evaluatorCapability: FUSION_NO_TOOLS_CAPABILITY,\n evaluatorTools: [],\n mergeCapability: FUSION_NO_TOOLS_CAPABILITY,\n mergeTools: [],\n candidateSystemPrompt: fusionCandidateSystemPrompt,\n evaluatorSystemPrompt: FUSION_EVALUATOR_SYSTEM_PROMPT,\n evaluationRepairSystemPrompt: FUSION_EVALUATION_REPAIR_SYSTEM_PROMPT,\n mergerSystemPrompt: FUSION_MERGER_SYSTEM_PROMPT,\n label: 'fusion research',\n});\n\nexport const FUSION_VALIDATE_WORKFLOW = freezeProfile({\n id: 'validate',\n publicName: FUSION_VALIDATE_TOOL_NAME,\n toolName: FUSION_VALIDATE_TOOL_NAME,\n runIdPrefix: 'validate-',\n contextKind: 'clean_task',\n candidateCapability: FUSION_VALIDATE_CAPABILITY,\n candidateTools: FUSION_INSPECT_TOOLS,\n evaluatorCapability: FUSION_NO_TOOLS_CAPABILITY,\n evaluatorTools: [],\n mergeCapability: FUSION_NO_TOOLS_CAPABILITY,\n mergeTools: [],\n candidateSystemPrompt: fusionValidateCandidateSystemPrompt,\n evaluatorSystemPrompt: FUSION_VALIDATE_EVALUATOR_SYSTEM_PROMPT,\n evaluationRepairSystemPrompt: FUSION_VALIDATE_EVALUATION_REPAIR_SYSTEM_PROMPT,\n mergerSystemPrompt: FUSION_VALIDATE_MERGER_SYSTEM_PROMPT,\n label: 'fusion validate',\n});\n\nconst PROFILES_BY_ID: Readonly<Record<FusionWorkflowId, FusionWorkflowProfile>> = Object.freeze({\n reason: FUSION_REASON_WORKFLOW,\n investigate: FUSION_INVESTIGATE_WORKFLOW,\n research: FUSION_RESEARCH_WORKFLOW,\n validate: FUSION_VALIDATE_WORKFLOW,\n});\n\nexport const FUSION_WORKFLOW_PROFILES = Object.freeze([\n FUSION_REASON_WORKFLOW,\n FUSION_INVESTIGATE_WORKFLOW,\n FUSION_RESEARCH_WORKFLOW,\n FUSION_VALIDATE_WORKFLOW,\n] as const);\n\nexport function fusionWorkflowProfile(id: FusionWorkflowId): FusionWorkflowProfile {\n const profile = PROFILES_BY_ID[id];\n if (profile === undefined) {\n throw new FusionError(`unknown fusion workflow ${String(id)}`, {\n code: 'orchestration_failed',\n childCreated: false,\n });\n }\n return profile;\n}\n\nexport function assertWorkflowCapability(\n profile: FusionWorkflowProfile,\n requested: FusionCapability | undefined,\n): FusionCapability {\n if (requested !== undefined && requested !== profile.candidateCapability) {\n throw new FusionError(\n `fusion workflow ${profile.id} always runs candidates with the ${profile.candidateCapability} capability; received ${String(requested)}`,\n { code: 'orchestration_failed', childCreated: false },\n );\n }\n return profile.candidateCapability;\n}\n\n/** @deprecated v4 artifact/testing alias. The retired public tool is never registered. */\nexport const FUSION_BRAINSTORM_WORKFLOW = FUSION_REASON_WORKFLOW;\n\nexport const FUSION_REASON = FUSION_REASON_WORKFLOW;\nexport const FUSION_INVESTIGATE = FUSION_INVESTIGATE_WORKFLOW;\nexport const FUSION_RESEARCH = FUSION_RESEARCH_WORKFLOW;\nexport const FUSION_VALIDATE = FUSION_VALIDATE_WORKFLOW;\n\n/** @deprecated v5 workflows do not default; retained for old imports. */\nexport const resolveWorkflowCapability = assertWorkflowCapability;\n"]}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/** Activation-local synchronous close callbacks installed by the entrypoint. */
|
|
2
|
+
export class SynchronousActivationCloseFence {
|
|
3
|
+
closed = false;
|
|
4
|
+
callbacks = new Set();
|
|
5
|
+
add(callback) {
|
|
6
|
+
this.callbacks.add(callback);
|
|
7
|
+
if (this.closed)
|
|
8
|
+
callback();
|
|
9
|
+
}
|
|
10
|
+
close() {
|
|
11
|
+
this.closed = true;
|
|
12
|
+
// Re-run idempotent teardown callbacks on repeated lifecycle dispatch. The
|
|
13
|
+
// core callback deliberately clears handles assigned by racing continuations.
|
|
14
|
+
const failures = [];
|
|
15
|
+
for (const callback of this.callbacks) {
|
|
16
|
+
try {
|
|
17
|
+
callback();
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
failures.push(error);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
if (failures.length > 0) {
|
|
24
|
+
throw new AggregateError(failures, `synchronous activation close barrier failed in ${String(failures.length)} callback(s)`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
const MODULE_ID_MAX_CHARS = 120;
|
|
29
|
+
const CAUSE_MAX_CHARS = 480;
|
|
30
|
+
const CLOSE_REASON_MAX_CHARS = 160;
|
|
31
|
+
function boundedSingleLine(value, maximum) {
|
|
32
|
+
const singleLine = value.replace(/\s+/gu, ' ').trim();
|
|
33
|
+
if (singleLine.length <= maximum)
|
|
34
|
+
return singleLine;
|
|
35
|
+
return `${singleLine.slice(0, maximum)}…`;
|
|
36
|
+
}
|
|
37
|
+
function boundedModuleId(moduleId) {
|
|
38
|
+
const bounded = boundedSingleLine(moduleId, MODULE_ID_MAX_CHARS);
|
|
39
|
+
return bounded.length > 0 ? bounded : 'unnamed-module';
|
|
40
|
+
}
|
|
41
|
+
function causeText(error) {
|
|
42
|
+
if (error instanceof Error) {
|
|
43
|
+
const message = error.message.trim();
|
|
44
|
+
return boundedSingleLine(message.length > 0 ? `${error.name}: ${message}` : error.name, CAUSE_MAX_CHARS);
|
|
45
|
+
}
|
|
46
|
+
return boundedSingleLine(String(error), CAUSE_MAX_CHARS);
|
|
47
|
+
}
|
|
48
|
+
class LazyModuleLoadError extends Error {
|
|
49
|
+
code = 'lazy_module_load_failed';
|
|
50
|
+
moduleId;
|
|
51
|
+
constructor(moduleId, error) {
|
|
52
|
+
const cause = causeText(error);
|
|
53
|
+
super(`lazy_module_load_failed: deferred module ${moduleId} could not load: ${cause}`);
|
|
54
|
+
this.name = 'LazyModuleLoadError';
|
|
55
|
+
this.moduleId = moduleId;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
class LazyModuleClosedError extends Error {
|
|
59
|
+
code = 'lazy_module_closed';
|
|
60
|
+
moduleId;
|
|
61
|
+
constructor(moduleId, reason) {
|
|
62
|
+
super(`lazy_module_closed: deferred module ${moduleId} belongs to a closed activation (${boundedSingleLine(reason, CLOSE_REASON_MAX_CHARS) || 'closed'})`);
|
|
63
|
+
this.name = 'LazyModuleClosedError';
|
|
64
|
+
this.moduleId = moduleId;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Activation-local, single-flight deferred module loader.
|
|
69
|
+
*
|
|
70
|
+
* The loader is deliberately terminal after `close()`: a Pi reload creates a
|
|
71
|
+
* fresh facade and therefore a fresh loader rather than reviving stale state.
|
|
72
|
+
*/
|
|
73
|
+
export class LazyModule {
|
|
74
|
+
moduleId;
|
|
75
|
+
importer;
|
|
76
|
+
currentState = 'unloaded';
|
|
77
|
+
activationGeneration = 0;
|
|
78
|
+
loadingPromise;
|
|
79
|
+
loadedValue;
|
|
80
|
+
loadFailure;
|
|
81
|
+
closedFailure;
|
|
82
|
+
constructor(moduleId, importer) {
|
|
83
|
+
this.moduleId = boundedModuleId(moduleId);
|
|
84
|
+
this.importer = importer;
|
|
85
|
+
}
|
|
86
|
+
get state() {
|
|
87
|
+
return this.currentState;
|
|
88
|
+
}
|
|
89
|
+
/** Synchronously and permanently close this activation. */
|
|
90
|
+
close(reason = 'activation closed') {
|
|
91
|
+
if (this.currentState === 'closed')
|
|
92
|
+
return;
|
|
93
|
+
this.activationGeneration += 1;
|
|
94
|
+
this.currentState = 'closed';
|
|
95
|
+
this.loadedValue = undefined;
|
|
96
|
+
this.loadingPromise = undefined;
|
|
97
|
+
this.loadFailure = undefined;
|
|
98
|
+
this.closedFailure = new LazyModuleClosedError(this.moduleId, reason);
|
|
99
|
+
}
|
|
100
|
+
/** Assert immediately before an activation-owned side effect. */
|
|
101
|
+
assertOpen(expectedGeneration = this.activationGeneration) {
|
|
102
|
+
if (this.currentState === 'closed' ||
|
|
103
|
+
expectedGeneration !== this.activationGeneration) {
|
|
104
|
+
throw this.closedError();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
load() {
|
|
108
|
+
const generation = this.activationGeneration;
|
|
109
|
+
try {
|
|
110
|
+
this.assertOpen(generation);
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
return Promise.reject(error);
|
|
114
|
+
}
|
|
115
|
+
if (this.currentState === 'loaded') {
|
|
116
|
+
const loaded = this.loadedValue;
|
|
117
|
+
if (loaded === undefined) {
|
|
118
|
+
return Promise.reject(new Error(`lazy_module_invariant: ${this.moduleId} is loaded without a value`));
|
|
119
|
+
}
|
|
120
|
+
return Promise.resolve(loaded.value);
|
|
121
|
+
}
|
|
122
|
+
if (this.currentState === 'failed') {
|
|
123
|
+
const failure = this.loadFailure;
|
|
124
|
+
if (failure === undefined) {
|
|
125
|
+
return Promise.reject(new Error(`lazy_module_invariant: ${this.moduleId} failed without an error`));
|
|
126
|
+
}
|
|
127
|
+
return Promise.reject(failure);
|
|
128
|
+
}
|
|
129
|
+
if (this.currentState === 'loading') {
|
|
130
|
+
const pending = this.loadingPromise;
|
|
131
|
+
if (pending === undefined) {
|
|
132
|
+
return Promise.reject(new Error(`lazy_module_invariant: ${this.moduleId} is loading without a promise`));
|
|
133
|
+
}
|
|
134
|
+
return pending;
|
|
135
|
+
}
|
|
136
|
+
this.currentState = 'loading';
|
|
137
|
+
// The importer itself runs in a later microtask. `loadingPromise` is stored
|
|
138
|
+
// before that callback can run, including under re-entrant test importers.
|
|
139
|
+
const pending = Promise.resolve()
|
|
140
|
+
.then(() => {
|
|
141
|
+
this.assertOpen(generation);
|
|
142
|
+
return this.importer();
|
|
143
|
+
})
|
|
144
|
+
.then((value) => {
|
|
145
|
+
this.assertOpen(generation);
|
|
146
|
+
this.loadedValue = { value };
|
|
147
|
+
this.loadingPromise = undefined;
|
|
148
|
+
this.currentState = 'loaded';
|
|
149
|
+
return value;
|
|
150
|
+
}, (error) => {
|
|
151
|
+
this.assertOpen(generation);
|
|
152
|
+
const failure = new LazyModuleLoadError(this.moduleId, error);
|
|
153
|
+
this.loadFailure = failure;
|
|
154
|
+
this.loadingPromise = undefined;
|
|
155
|
+
this.currentState = 'failed';
|
|
156
|
+
throw failure;
|
|
157
|
+
});
|
|
158
|
+
this.loadingPromise = pending;
|
|
159
|
+
return pending;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Load once, then invoke this caller's operation independently after the
|
|
163
|
+
* final generation check. Only module loading is shared between callers.
|
|
164
|
+
*/
|
|
165
|
+
async run(operation) {
|
|
166
|
+
const generation = this.activationGeneration;
|
|
167
|
+
this.assertOpen(generation);
|
|
168
|
+
const module = await this.load();
|
|
169
|
+
this.assertOpen(generation);
|
|
170
|
+
return operation(module);
|
|
171
|
+
}
|
|
172
|
+
closedError() {
|
|
173
|
+
const failure = this.closedFailure;
|
|
174
|
+
if (failure !== undefined)
|
|
175
|
+
return failure;
|
|
176
|
+
const created = new LazyModuleClosedError(this.moduleId, 'activation closed');
|
|
177
|
+
this.closedFailure = created;
|
|
178
|
+
return created;
|
|
179
|
+
}
|
|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ACjC,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;QAC5B,OAAO,SAAS,CAAC,MAAM,CAAC,CAAC;IAC3B,CAAC;IAEO,WAAW;QACjB,MAAM,OAAO,GAAG,IAAI,CAAC,aAAa,CAAC;QACnC,IAAI,OAAO,KAAK,SAAS;YAAE,OAAO,OAAO,CAAC;QAC1C,MAAM,OAAO,GAAG,IAAI,qBAAqB,CAAC,IAAI,CAAC,QAAQ,EAAE,mBAAmB,CAAC,CAAC;QAC9E,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC;QAC7B,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["export type LazyModuleState = 'unloaded' | 'loading' | 'loaded' | 'failed' | 'closed';\n\n/** Activation-local synchronous close callbacks installed by the entrypoint. */\nexport class SynchronousActivationCloseFence {\n private closed = false;\n private readonly callbacks = new Set<() => void>();\n\n add(callback: () => void): void {\n this.callbacks.add(callback);\n if (this.closed) callback();\n }\n\n close(): void {\n this.closed = true;\n // Re-run idempotent teardown callbacks on repeated lifecycle dispatch. The\n // core callback deliberately clears handles assigned by racing continuations.\n const failures: unknown[] = [];\n for (const callback of this.callbacks) {\n try {\n callback();\n } catch (error) {\n failures.push(error);\n }\n }\n if (failures.length > 0) {\n throw new AggregateError(\n failures,\n `synchronous activation close barrier failed in ${String(failures.length)} callback(s)`,\n );\n }\n }\n}\n\nconst MODULE_ID_MAX_CHARS = 120;\nconst CAUSE_MAX_CHARS = 480;\nconst CLOSE_REASON_MAX_CHARS = 160;\n\nfunction boundedSingleLine(value: string, maximum: number): string {\n const singleLine = value.replace(/\\s+/gu, ' ').trim();\n if (singleLine.length <= maximum) return singleLine;\n return `${singleLine.slice(0, maximum)}…`;\n}\n\nfunction boundedModuleId(moduleId: string): string {\n const bounded = boundedSingleLine(moduleId, MODULE_ID_MAX_CHARS);\n return bounded.length > 0 ? bounded : 'unnamed-module';\n}\n\nfunction causeText(error: unknown): string {\n if (error instanceof Error) {\n const message = error.message.trim();\n return boundedSingleLine(\n message.length > 0 ? `${error.name}: ${message}` : error.name,\n CAUSE_MAX_CHARS,\n );\n }\n return boundedSingleLine(String(error), CAUSE_MAX_CHARS);\n}\n\nclass LazyModuleLoadError extends Error {\n readonly code = 'lazy_module_load_failed';\n readonly moduleId: string;\n\n constructor(moduleId: string, error: unknown) {\n const cause = causeText(error);\n super(`lazy_module_load_failed: deferred module ${moduleId} could not load: ${cause}`);\n this.name = 'LazyModuleLoadError';\n this.moduleId = moduleId;\n }\n}\n\nclass LazyModuleClosedError extends Error {\n readonly code = 'lazy_module_closed';\n readonly moduleId: string;\n\n constructor(moduleId: string, reason: string) {\n super(\n `lazy_module_closed: deferred module ${moduleId} belongs to a closed activation (${boundedSingleLine(reason, CLOSE_REASON_MAX_CHARS) || 'closed'})`,\n );\n this.name = 'LazyModuleClosedError';\n this.moduleId = moduleId;\n }\n}\n\n/**\n * Activation-local, single-flight deferred module loader.\n *\n * The loader is deliberately terminal after `close()`: a Pi reload creates a\n * fresh facade and therefore a fresh loader rather than reviving stale state.\n */\nexport class LazyModule<T> {\n readonly moduleId: string;\n private readonly importer: () => Promise<T>;\n private currentState: LazyModuleState = 'unloaded';\n private activationGeneration = 0;\n private loadingPromise: Promise<T> | undefined;\n private loadedValue: { value: T } | undefined;\n private loadFailure: Error | undefined;\n private closedFailure: Error | undefined;\n\n constructor(moduleId: string, importer: () => Promise<T>) {\n this.moduleId = boundedModuleId(moduleId);\n this.importer = importer;\n }\n\n get state(): LazyModuleState {\n return this.currentState;\n }\n\n /** Synchronously and permanently close this activation. */\n close(reason = 'activation closed'): void {\n if (this.currentState === 'closed') return;\n this.activationGeneration += 1;\n this.currentState = 'closed';\n this.loadedValue = undefined;\n this.loadingPromise = undefined;\n this.loadFailure = undefined;\n this.closedFailure = new LazyModuleClosedError(this.moduleId, reason);\n }\n\n /** Assert immediately before an activation-owned side effect. */\n assertOpen(expectedGeneration = this.activationGeneration): void {\n if (\n this.currentState === 'closed' ||\n expectedGeneration !== this.activationGeneration\n ) {\n throw this.closedError();\n }\n }\n\n load(): Promise<T> {\n const generation = this.activationGeneration;\n try {\n this.assertOpen(generation);\n } catch (error) {\n return Promise.reject(error);\n }\n\n if (this.currentState === 'loaded') {\n const loaded = this.loadedValue;\n if (loaded === undefined) {\n return Promise.reject(\n new Error(`lazy_module_invariant: ${this.moduleId} is loaded without a value`),\n );\n }\n return Promise.resolve(loaded.value);\n }\n if (this.currentState === 'failed') {\n const failure = this.loadFailure;\n if (failure === undefined) {\n return Promise.reject(\n new Error(`lazy_module_invariant: ${this.moduleId} failed without an error`),\n );\n }\n return Promise.reject(failure);\n }\n if (this.currentState === 'loading') {\n const pending = this.loadingPromise;\n if (pending === undefined) {\n return Promise.reject(\n new Error(`lazy_module_invariant: ${this.moduleId} is loading without a promise`),\n );\n }\n return pending;\n }\n\n this.currentState = 'loading';\n // The importer itself runs in a later microtask. `loadingPromise` is stored\n // before that callback can run, including under re-entrant test importers.\n const pending = Promise.resolve()\n .then(() => {\n this.assertOpen(generation);\n return this.importer();\n })\n .then(\n (value) => {\n this.assertOpen(generation);\n this.loadedValue = { value };\n this.loadingPromise = undefined;\n this.currentState = 'loaded';\n return value;\n },\n (error: unknown) => {\n this.assertOpen(generation);\n const failure = new LazyModuleLoadError(this.moduleId, error);\n this.loadFailure = failure;\n this.loadingPromise = undefined;\n this.currentState = 'failed';\n throw failure;\n },\n );\n this.loadingPromise = pending;\n return pending;\n }\n\n /**\n * Load once, then invoke this caller's operation independently after the\n * final generation check. Only module loading is shared between callers.\n */\n async run<R>(operation: (module: T) => R | Promise<R>): Promise<R> {\n const generation = this.activationGeneration;\n this.assertOpen(generation);\n const module = await this.load();\n this.assertOpen(generation);\n return operation(module);\n }\n\n private closedError(): Error {\n const failure = this.closedFailure;\n if (failure !== undefined) return failure;\n const created = new LazyModuleClosedError(this.moduleId, 'activation closed');\n this.closedFailure = created;\n return created;\n }\n}\n"]}
|