@ponythewhite/base-context 1.0.0 → 1.0.2
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/CHANGELOG.md +37 -0
- package/NOTICE +0 -5
- package/README.md +44 -27
- package/dist/NOTICE +0 -5
- package/dist/base-context-runtime/pyproject.toml +1 -1
- package/dist/base-context-runtime/src/rlm/__init__.py +7 -5
- package/dist/base-context-runtime/test/test_subagent_registry.py +28 -1
- package/dist/base-context-runtime/uv.lock +1 -1
- package/dist/build-info.json +1 -1
- package/dist/bundle/amazon-bedrock.js +21 -0
- package/dist/bundle/{anthropic-YY4S534V.js → anthropic-UV5GZDGU.js} +5 -5
- package/dist/bundle/{azure-openai-responses-JRP6MIM3.js → azure-openai-responses-WSNPXLYC.js} +6 -6
- package/dist/bundle/{bundled-modules-P5HARVZA.js → bundled-modules-PWOGKUQQ.js} +71 -16
- package/dist/bundle/chunk-27QCJ2AZ.js +2578 -0
- package/dist/bundle/{chunk-BYVP7LWV.js → chunk-44PEHPOG.js} +1916 -4689
- package/dist/bundle/{chunk-MZHTNNVA.js → chunk-4GXPNXOJ.js} +8 -0
- package/dist/bundle/{chunk-SC5KG5R4.js → chunk-DGNX7HQ3.js} +1 -7
- package/dist/bundle/{chunk-A53O363M.js → chunk-GRJFXLBM.js} +0 -1
- package/dist/bundle/chunk-HKINIBP4.js +29 -0
- package/dist/bundle/{chunk-73DCPU3D.js → chunk-IADCPVEI.js} +1019 -3427
- package/dist/bundle/{chunk-UDSW6FNG.js → chunk-KTNETTHI.js} +1 -1
- package/dist/bundle/{chunk-U7AUVG3B.js → chunk-VSIYFWYI.js} +24 -6
- package/dist/bundle/{chunk-IW77OXFS.js → chunk-W46VZFI6.js} +0 -2099
- package/dist/bundle/{cli-main-O4X7GFGY.js → cli-main-4DS7Y3PI.js} +8 -6
- package/dist/bundle/cli.js +2 -2
- package/dist/bundle/{google-AUTVGDGZ.js → google-T32FMD4G.js} +6 -6
- package/dist/bundle/{google-vertex-Q75D7RKS.js → google-vertex-56KP6I3B.js} +3 -3
- package/dist/bundle/{main-XKOW2BV6.js → main-SV7JLVEB.js} +7 -5
- package/dist/bundle/{mistral-7ESB7QUD.js → mistral-WGBMYIVU.js} +5 -5
- package/dist/bundle/{openai-codex-responses-LV3QRPN4.js → openai-codex-responses-PIV2RQ3G.js} +6 -6
- package/dist/bundle/{openai-completions-OJECLPXJ.js → openai-completions-64C3JPR4.js} +11 -22
- package/dist/bundle/{openai-responses-FN6HZMBC.js → openai-responses-UI7RSTDV.js} +6 -6
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +108 -59
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/daemon-ps.d.ts +4 -3
- package/dist/cli/daemon-ps.d.ts.map +1 -1
- package/dist/cli/daemon-ps.js +6 -1
- package/dist/cli/daemon-ps.js.map +1 -1
- package/dist/cli/product-doctor.d.ts +0 -1
- package/dist/cli/product-doctor.d.ts.map +1 -1
- package/dist/cli/product-doctor.js +6 -3
- package/dist/cli/product-doctor.js.map +1 -1
- package/dist/config.d.ts +0 -3
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +0 -8
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-config.d.ts +1 -2
- package/dist/core/agent-session-config.d.ts.map +1 -1
- package/dist/core/agent-session-config.js +0 -3
- package/dist/core/agent-session-config.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +5 -4
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +5 -3
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +2 -27
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +10 -6
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +107 -107
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts +8 -35
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +33 -243
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/cron-jobs.d.ts.map +1 -1
- package/dist/core/cron-jobs.js +7 -1
- package/dist/core/cron-jobs.js.map +1 -1
- package/dist/core/inference-coordinator.d.ts +6 -1
- package/dist/core/inference-coordinator.d.ts.map +1 -1
- package/dist/core/inference-coordinator.js +18 -2
- package/dist/core/inference-coordinator.js.map +1 -1
- package/dist/core/kernel/bootstrap.d.ts.map +1 -1
- package/dist/core/kernel/bootstrap.js +2 -2
- package/dist/core/kernel/bootstrap.js.map +1 -1
- package/dist/core/kernel/repl-manager.d.ts +2 -0
- package/dist/core/kernel/repl-manager.d.ts.map +1 -1
- package/dist/core/kernel/repl-manager.js +44 -1
- package/dist/core/kernel/repl-manager.js.map +1 -1
- package/dist/core/logging.d.ts +4 -3
- package/dist/core/logging.d.ts.map +1 -1
- package/dist/core/logging.js +6 -6
- package/dist/core/logging.js.map +1 -1
- package/dist/core/mcp/mcp-manager.d.ts.map +1 -1
- package/dist/core/mcp/mcp-manager.js +3 -3
- package/dist/core/mcp/mcp-manager.js.map +1 -1
- package/dist/core/model-registry.d.ts +1 -16
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +88 -196
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts +2 -19
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +36 -266
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/provider-contracts.d.ts +5 -6
- package/dist/core/provider-contracts.d.ts.map +1 -1
- package/dist/core/provider-contracts.js +25 -36
- package/dist/core/provider-contracts.js.map +1 -1
- package/dist/core/provider-display-names.d.ts.map +1 -1
- package/dist/core/provider-display-names.js +0 -2
- package/dist/core/provider-display-names.js.map +1 -1
- package/dist/core/rlm-max-subagents.d.ts +32 -0
- package/dist/core/rlm-max-subagents.d.ts.map +1 -0
- package/dist/core/rlm-max-subagents.js +50 -0
- package/dist/core/rlm-max-subagents.js.map +1 -0
- package/dist/core/rlm-runtime.d.ts +3 -3
- package/dist/core/rlm-runtime.d.ts.map +1 -1
- package/dist/core/rlm-runtime.js.map +1 -1
- package/dist/core/sdk.d.ts +4 -3
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +27 -14
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager.d.ts +3 -16
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +12 -44
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +6 -6
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/installer.mjs +2 -3
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +39 -34
- package/dist/main.js.map +1 -1
- package/dist/modes/acp/acp-mode.d.ts.map +1 -1
- package/dist/modes/acp/acp-mode.js +1 -1
- package/dist/modes/acp/acp-mode.js.map +1 -1
- package/dist/modes/agent-connection/daemon-agent-connection.d.ts +6 -2
- package/dist/modes/agent-connection/daemon-agent-connection.d.ts.map +1 -1
- package/dist/modes/agent-connection/daemon-agent-connection.js +13 -2
- package/dist/modes/agent-connection/daemon-agent-connection.js.map +1 -1
- package/dist/modes/agent-connection/in-process-agent-connection.d.ts +2 -0
- package/dist/modes/agent-connection/in-process-agent-connection.d.ts.map +1 -1
- package/dist/modes/agent-connection/in-process-agent-connection.js +6 -0
- package/dist/modes/agent-connection/in-process-agent-connection.js.map +1 -1
- package/dist/modes/agent-connection/types.d.ts +3 -0
- package/dist/modes/agent-connection/types.d.ts.map +1 -1
- package/dist/modes/agent-connection/types.js.map +1 -1
- package/dist/modes/agents-view/agents-view-mode.d.ts.map +1 -1
- package/dist/modes/agents-view/agents-view-mode.js +2 -19
- package/dist/modes/agents-view/agents-view-mode.js.map +1 -1
- package/dist/modes/daemon/daemon-mode.d.ts +5 -0
- package/dist/modes/daemon/daemon-mode.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-mode.js +107 -12
- package/dist/modes/daemon/daemon-mode.js.map +1 -1
- package/dist/modes/daemon/daemon-protocol.d.ts +194 -165
- package/dist/modes/daemon/daemon-protocol.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-protocol.js +16 -11
- package/dist/modes/daemon/daemon-protocol.js.map +1 -1
- package/dist/modes/daemon/daemon-rlm-capacity-coordinator.d.ts +19 -0
- package/dist/modes/daemon/daemon-rlm-capacity-coordinator.d.ts.map +1 -0
- package/dist/modes/daemon/daemon-rlm-capacity-coordinator.js +74 -0
- package/dist/modes/daemon/daemon-rlm-capacity-coordinator.js.map +1 -0
- package/dist/modes/daemon/daemon-rlm-capacity.d.ts +19 -0
- package/dist/modes/daemon/daemon-rlm-capacity.d.ts.map +1 -0
- package/dist/modes/daemon/daemon-rlm-capacity.js +85 -0
- package/dist/modes/daemon/daemon-rlm-capacity.js.map +1 -0
- package/dist/modes/daemon/daemon-session-summarizer.d.ts +2 -3
- package/dist/modes/daemon/daemon-session-summarizer.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-session-summarizer.js +32 -23
- package/dist/modes/daemon/daemon-session-summarizer.js.map +1 -1
- package/dist/modes/daemon/daemon-state-root.d.ts +15 -0
- package/dist/modes/daemon/daemon-state-root.d.ts.map +1 -0
- package/dist/modes/daemon/daemon-state-root.js +40 -0
- package/dist/modes/daemon/daemon-state-root.js.map +1 -0
- package/dist/modes/daemon/daemon-supervisor-ownership.d.ts +2 -0
- package/dist/modes/daemon/daemon-supervisor-ownership.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-supervisor-ownership.js +27 -0
- package/dist/modes/daemon/daemon-supervisor-ownership.js.map +1 -1
- package/dist/modes/daemon/daemon-supervisor.d.ts +10 -1
- package/dist/modes/daemon/daemon-supervisor.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-supervisor.js +213 -20
- package/dist/modes/daemon/daemon-supervisor.js.map +1 -1
- package/dist/modes/daemon/daemon-worker-protocol.d.ts +28 -1
- package/dist/modes/daemon/daemon-worker-protocol.d.ts.map +1 -1
- package/dist/modes/daemon/daemon-worker-protocol.js +16 -2
- package/dist/modes/daemon/daemon-worker-protocol.js.map +1 -1
- package/dist/modes/daemon/saved-session-catalog.d.ts.map +1 -1
- package/dist/modes/daemon/saved-session-catalog.js +2 -0
- package/dist/modes/daemon/saved-session-catalog.js.map +1 -1
- package/dist/modes/interactive/auth-flows.d.ts +0 -6
- package/dist/modes/interactive/auth-flows.d.ts.map +1 -1
- package/dist/modes/interactive/auth-flows.js +6 -126
- package/dist/modes/interactive/auth-flows.js.map +1 -1
- package/dist/modes/interactive/components/configuration-menu.d.ts +3 -0
- package/dist/modes/interactive/components/configuration-menu.d.ts.map +1 -1
- package/dist/modes/interactive/components/configuration-menu.js +13 -2
- package/dist/modes/interactive/components/configuration-menu.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +2 -2
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/index.d.ts +0 -1
- package/dist/modes/interactive/components/index.d.ts.map +1 -1
- package/dist/modes/interactive/components/index.js +0 -1
- package/dist/modes/interactive/components/index.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +0 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +3 -40
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +2 -0
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +13 -2
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +2 -11
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/feature-hints.d.ts.map +1 -1
- package/dist/modes/interactive/feature-hints.js +0 -4
- package/dist/modes/interactive/feature-hints.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +3 -12
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +81 -507
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/onboarding.d.ts +0 -3
- package/dist/modes/interactive/onboarding.d.ts.map +1 -1
- package/dist/modes/interactive/onboarding.js +0 -17
- package/dist/modes/interactive/onboarding.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +4 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +82 -42
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/node/amazon-bedrock.d.ts +2 -0
- package/dist/node/amazon-bedrock.d.ts.map +1 -0
- package/dist/node/amazon-bedrock.js +6 -0
- package/dist/node/amazon-bedrock.js.map +1 -0
- package/dist/product-identity.d.ts +0 -1
- package/dist/product-identity.d.ts.map +1 -1
- package/dist/product-identity.js +0 -1
- package/dist/product-identity.js.map +1 -1
- package/docs/development.md +1 -1
- package/docs/fork-philosophy.md +4 -8
- package/docs/installation.md +83 -62
- package/docs/providers.md +23 -25
- package/docs/quickstart.md +19 -10
- package/docs/rlm-runtime.md +13 -5
- package/docs/rpc.md +4 -4
- package/docs/sdk.md +20 -11
- package/docs/sessions.md +0 -1
- package/docs/settings.md +9 -42
- package/docs/skills.md +0 -1
- package/docs/upstream-0.9.5.md +171 -0
- package/docs/usage.md +14 -10
- package/package.json +4 -4
- package/dist/core/agent-traces.d.ts +0 -149
- package/dist/core/agent-traces.d.ts.map +0 -1
- package/dist/core/agent-traces.js +0 -904
- package/dist/core/agent-traces.js.map +0 -1
- package/dist/core/prime-inference-auth.d.ts +0 -70
- package/dist/core/prime-inference-auth.d.ts.map +0 -1
- package/dist/core/prime-inference-auth.js +0 -352
- package/dist/core/prime-inference-auth.js.map +0 -1
- package/dist/core/prime-inference-model-selection.d.ts +0 -16
- package/dist/core/prime-inference-model-selection.d.ts.map +0 -1
- package/dist/core/prime-inference-model-selection.js +0 -16
- package/dist/core/prime-inference-model-selection.js.map +0 -1
- package/dist/core/prime-inference-models.d.ts +0 -6
- package/dist/core/prime-inference-models.d.ts.map +0 -1
- package/dist/core/prime-inference-models.js +0 -62
- package/dist/core/prime-inference-models.js.map +0 -1
- package/dist/core/telemetry.d.ts +0 -95
- package/dist/core/telemetry.d.ts.map +0 -1
- package/dist/core/telemetry.js +0 -637
- package/dist/core/telemetry.js.map +0 -1
- package/dist/modes/interactive/components/prime-onboarding-splash.d.ts +0 -39
- package/dist/modes/interactive/components/prime-onboarding-splash.d.ts.map +0 -1
- package/dist/modes/interactive/components/prime-onboarding-splash.js +0 -286
- package/dist/modes/interactive/components/prime-onboarding-splash.js.map +0 -1
- package/dist/modes/interactive/components/prime-team-selector.d.ts +0 -30
- package/dist/modes/interactive/components/prime-team-selector.d.ts.map +0 -1
- package/dist/modes/interactive/components/prime-team-selector.js +0 -166
- package/dist/modes/interactive/components/prime-team-selector.js.map +0 -1
- package/dist/skills/prime-intellect/SKILL.md +0 -87
- package/dist/skills/prime-intellect/references/compute.md +0 -45
- package/dist/skills/prime-intellect/references/environments.md +0 -73
- package/dist/skills/prime-intellect/references/inference.md +0 -47
- package/dist/skills/prime-intellect/references/sandboxes.md +0 -75
- package/skills/prime-intellect/SKILL.md +0 -87
- package/skills/prime-intellect/references/compute.md +0 -45
- package/skills/prime-intellect/references/environments.md +0 -73
- package/skills/prime-intellect/references/inference.md +0 -47
- package/skills/prime-intellect/references/sandboxes.md +0 -75
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inference-coordinator.js","sourceRoot":"","sources":["../../src/core/inference-coordinator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,M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as delay } from \"node:timers/promises\";\nimport type { AgentMessage, AgentOwnedStreamFn, StreamFn } from \"@ponythewhite/base-context-agent\";\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\tassertBuiltInAttemptSupport,\n\ttype Context,\n\tcompleteSimple,\n\tinvokeRequestMeasurement,\n\tisLocalFauxStream,\n\tisTransientProviderFailure,\n\ttype Model,\n\ttype ProviderAttemptObserver,\n\tRequestTokenBudget,\n\ttype RequestTokenBudgetOptions,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n} from \"@ponythewhite/base-context-ai\";\nimport type {\n\tBoundRequestSink,\n\tContextEpochEntryRef,\n\tNativeBranchRequestOutputWriter,\n\tNativeCompactionRequestOutputAssociation,\n\tNativePlannerRequestOutputWriter,\n\tNativeRequestMetadata,\n\tNativeRequestOutputWriter,\n\tRequestOwnerRef,\n\tRequestPurpose,\n\tResolvedModelContract,\n\tSourceSnapshotRef,\n} from \"./request-events.js\";\nimport {\n\ttype CapturedRequestViewBoundary,\n\tcaptureRequestViewBoundary,\n\tmatchesRequestView,\n\tprepareFixedRequestView,\n\ttype RequestViewCommit,\n\ttype RequestViewFixedPrepare,\n\ttype RequestViewValidate,\n\tselectRequestView,\n} from \"./request-view-selection.js\";\nimport { hashTurnBody, MODEL_REQUEST_ID_HEADER, unwrapSemanticEdgeStreamFn } from \"./semantic-edges.js\";\nimport type { SessionHistoryReadView } from \"./session-history-index.js\";\nimport {\n\tcaptureNativeBranchOutputSource,\n\tcaptureNativeCompactionOutputSource,\n\tcaptureNativePlannerOutputSource,\n\tcaptureNativeRequestOutputSource,\n} from \"./session-manager.js\";\n\nexport interface InferenceRequestOptions {\n\treadonly purpose: RequestPurpose;\n\treadonly purposeDetail?: string;\n\treadonly operationId?: string;\n\treadonly parentOperationId?: string;\n\treadonly semanticEdgeId?: string;\n}\n\nexport interface InferenceSettlement {\n\treadonly message: AssistantMessage;\n\treadonly operationId: string;\n\treadonly attemptIds: readonly string[];\n\t/** Reporting is not a guarantee about an opaque adapter's hidden retries. */\n\treadonly physicalCoverage: \"reported\" | \"unestablished\" | \"local-simulation\";\n}\n\n/** Private completion identity carries this actual source, never descriptive sink labels. */\nexport interface NativeCompactionOutputBinding {\n\treadonly sink: BoundRequestSink;\n\treadonly output: NativeCompactionRequestOutputAssociation;\n}\n\ninterface NativeBranchOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativeBranchRequestOutputWriter;\n}\n\ninterface NativePlannerOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativePlannerRequestOutputWriter;\n}\n\nexport interface InferenceRun {\n\treadonly events: Awaited<ReturnType<StreamFn>>;\n\treadonly settled: Promise<InferenceSettlement>;\n}\n\nexport interface SessionRuntimeServices {\n\treadonly requests: InferenceCoordinator;\n}\n\ninterface ProviderRecoveryPolicy {\n\tenabled: boolean;\n\tbaseDelayMs: number;\n\tmaxRetryDelayMs: number;\n}\n\ninterface SinkUse {\n\treadonly sink: BoundRequestSink;\n\tactiveUsers: number;\n\tcaptures: number;\n\trelease?: Promise<void>;\n}\n\ninterface BoundOperation {\n\treadonly binding: SinkUse;\n\treadonly owner: Omit<RequestOwnerRef, \"sessionId\">;\n\treadonly metadata: Omit<NativeRequestMetadata, \"source\" | \"owner\" | \"contextEpoch\">;\n}\n\nconst REQUEST_STREAM_BINDING = Symbol(\"base-context.request-stream-binding\");\n/** Internal AgentSession built-in compaction entry, not a public inference option. */\nexport const captureNativeCompactionRequests = Symbol(\"base-context.native-compaction-requests\");\n/** Internal AgentSession built-in branch-summary invocation, never inherited by generic capture. */\nexport const captureNativeBranchRequests = Symbol(\"base-context.native-branch-requests\");\n/** Internal native AgentSession planner capture, never inherited by generic capture. */\nexport const captureNativePlannerRequests = Symbol(\"base-context.native-planner-requests\");\n/** Internal native AgentSession reviewer invocation. */\nexport const captureNativeReviewerRequests = Symbol(\"base-context.native-reviewer-requests\");\ninterface StreamBinding {\n\treadonly coordinator: InferenceCoordinator;\n\treadonly inner: StreamFn;\n}\ntype BoundStreamFn = AgentOwnedStreamFn & { [REQUEST_STREAM_BINDING]?: StreamBinding };\n\nfunction modelContract(model: Model<Api>): ResolvedModelContract {\n\treturn {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tprofile: { id: \"native-default\", status: \"unvalidated\" },\n\t\tpricing: {\n\t\t\tstatus: \"unvalidated\",\n\t\t\tcurrency: \"USD\",\n\t\t\tunit: \"million-tokens\",\n\t\t\tcatalogRates: {\n\t\t\t\tinput: model.cost.input,\n\t\t\t\toutput: model.cost.output,\n\t\t\t\tcacheRead: model.cost.cacheRead,\n\t\t\t\tcacheWrite: model.cost.cacheWrite,\n\t\t\t},\n\t\t},\n\t};\n}\n\nconst nativeStreamFunctions = new WeakSet<StreamFn>();\n\n/** Internal SDK auth/options resolver; transport stays the known instrumented AI dispatcher. */\nexport function createNativeInferenceStream(\n\tresolveOptions: (\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t) => Promise<SimpleStreamOptions>,\n): StreamFn {\n\tconst dispatch: StreamFn = async (model, context, options) => {\n\t\tconst resolved = await resolveOptions(model, context, options);\n\t\treturn streamSimple(model, context, {\n\t\t\t...resolved,\n\t\t\tsignal: options?.signal,\n\t\t\tattempts: options?.attempts,\n\t\t\trequireProviderAttempts: true,\n\t\t});\n\t};\n\tnativeStreamFunctions.add(dispatch);\n\treturn dispatch;\n}\n\n/** Routes physical observations to the source writer. It owns no receipt store. */\nexport class InferenceCoordinator {\n\t#nativeCompactionOutput = false;\n\t#nativeBranchOutput = false;\n\t#nativePlannerOutput = false;\n\t#auxiliaryAttempts?: { remaining: number };\n\tprivate retryTurn = false;\n\tprivate requestViewBoundary?: CapturedRequestViewBoundary;\n\tprivate active = new Set<Promise<void>>();\n\tprivate capturedSink?: SinkUse;\n\tprivate captureReserved = false;\n\tprivate finishCapturePending?: () => void;\n\tprivate disposed = false;\n\tprivate disposal?: Promise<void>;\n\tprivate work = {\n\t\tpending: new Set<Promise<void>>(),\n\t\tsinks: new WeakMap<BoundRequestSink, SinkUse>(),\n\t\tmainOutputs: new WeakMap<AssistantMessage, NativeRequestOutputWriter>(),\n\t\tcompactionSettlements: new WeakMap<InferenceSettlement, NativeCompactionOutputBinding>(),\n\t\tcompactionCompletions: new WeakMap<Promise<AssistantMessage>, NativeCompactionOutputBinding>(),\n\t\tbranchSettlements: new WeakMap<InferenceSettlement, NativeBranchOutputBinding>(),\n\t\tbranchCompletions: new WeakMap<Promise<AssistantMessage>, NativeBranchOutputBinding>(),\n\t\tplannerSettlements: new WeakMap<InferenceSettlement, NativePlannerOutputBinding>(),\n\t\tplannerCompletions: new WeakMap<Promise<AssistantMessage>, NativePlannerOutputBinding>(),\n\t\tlisteners: new Set<() => void>(),\n\t\tadmissionOpen: true,\n\t\tcancellation: new AbortController(),\n\t\tbudget: undefined as RequestTokenBudget | undefined,\n\t\tbudgetMode: undefined as RequestTokenBudgetOptions[\"mode\"] | undefined,\n\t\tproviderRecoveryPolicy: undefined as (() => ProviderRecoveryPolicy) | undefined,\n\t};\n\n\tsetProviderRecoveryPolicy(policy: () => ProviderRecoveryPolicy): void {\n\t\tthis.work.providerRecoveryPolicy = policy;\n\t}\n\n\tget hasPending(): boolean {\n\t\treturn this.work.pending.size > 0;\n\t}\n\tget pendingCount(): number {\n\t\treturn this.work.pending.size;\n\t}\n\n\tonActivityChange(listener: () => void): () => void {\n\t\tthis.work.listeners.add(listener);\n\t\treturn () => this.work.listeners.delete(listener);\n\t}\n\n\tprivate notifyActivity(): void {\n\t\t// Observers can wake an existing owner, but cannot own request settlement.\n\t\tfor (const listener of this.work.listeners) {\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Notification is not execution. */\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Consume only this owner's real returned object. Labels and replacement messages remain unassociated. */\n\tappendMainOutput(message: AssistantMessage, owner: object): Promise<string | undefined> | undefined {\n\t\tconst write = this.work.mainOutputs.get(message);\n\t\tthis.work.mainOutputs.delete(message);\n\t\treturn write?.(owner, message);\n\t}\n\n\t/** Opt this native invocation into output association; ordinary captures do not inherit that authority. */\n\t[captureNativeCompactionRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#nativeCompactionOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 4 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeBranchRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativeBranchOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakeBranchOutput(completion: Promise<AssistantMessage>): NativeBranchRequestOutputWriter | undefined {\n\t\tconst binding = this.work.branchCompletions.get(completion);\n\t\tthis.work.branchCompletions.delete(completion);\n\t\tif (!binding || !this.#nativeBranchOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t[captureNativePlannerRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativePlannerOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeReviewerRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakePlannerOutput(completion: Promise<AssistantMessage>): NativePlannerRequestOutputWriter | undefined {\n\t\tconst binding = this.work.plannerCompletions.get(completion);\n\t\tthis.work.plannerCompletions.delete(completion);\n\t\tif (!binding || !this.#nativePlannerOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t/** Only the original completion promise and captured source can supply a projected-output link. */\n\ttakeCompactionOutput(completion: Promise<AssistantMessage>): NativeCompactionOutputBinding | undefined {\n\t\tconst binding = this.work.compactionCompletions.get(completion);\n\t\tthis.work.compactionCompletions.delete(completion);\n\t\treturn binding?.sink === this.capturedSink?.sink ? binding : undefined;\n\t}\n\n\t/** Owner teardown stops new sends, but never suppresses an admitted request's settlement. */\n\tstopAdmission(): void {\n\t\tthis.work.admissionOpen = false;\n\t\tthis.work.cancellation.abort();\n\t\tthis.notifyActivity();\n\t}\n\n\tasync waitForIdle(): Promise<void> {\n\t\twhile (this.work.pending.size > 0) await Promise.all([...this.work.pending]);\n\t}\n\n\tprepareTurnRetry(): void {\n\t\tthis.retryTurn = true;\n\t}\n\tclearTurnRetry(): void {\n\t\tthis.retryTurn = false;\n\t}\n\n\tconstructor(\n\t\tprivate readonly bindSink: () => BoundRequestSink,\n\t\tprivate readonly owner: () => Omit<RequestOwnerRef, \"sessionId\"> = () => ({}),\n\t\trequestTokenBudget?: RequestTokenBudgetOptions,\n\t) {\n\t\tif (requestTokenBudget) {\n\t\t\tthis.work.budget = new RequestTokenBudget(requestTokenBudget);\n\t\t\tthis.work.budgetMode = requestTokenBudget.mode;\n\t\t}\n\t}\n\n\t/** Copy the configured policy, not this owner's learned request observations. */\n\tgetRequestTokenBudgetOptions(): RequestTokenBudgetOptions | undefined {\n\t\treturn this.work.budget?.getOptions();\n\t}\n\n\tprivate assertAdmission(): void {\n\t\tif (this.disposed || !this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t}\n\n\tprivate sinkUse(sink: BoundRequestSink): SinkUse {\n\t\tlet binding = this.work.sinks.get(sink);\n\t\tif (!binding) {\n\t\t\tbinding = { sink, activeUsers: 0, captures: 0 };\n\t\t\tthis.work.sinks.set(sink, binding);\n\t\t}\n\t\treturn binding;\n\t}\n\n\tprivate releaseCapture(): void {\n\t\tif (this.captureReserved && this.capturedSink) {\n\t\t\tthis.captureReserved = false;\n\t\t\tthis.capturedSink.captures--;\n\t\t}\n\t}\n\n\t/** Capture an auxiliary operation's subject before asynchronous auth or UI work. */\n\tcapture(sink?: BoundRequestSink): InferenceCoordinator {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst binding = this.sinkUse(sink ?? this.bindSink());\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tconst captured = new InferenceCoordinator(\n\t\t\t() => binding.sink,\n\t\t\t() => owner,\n\t\t);\n\t\tcaptured.work = this.work;\n\t\t// Nested captures share the invocation's allowance, not its native output authority.\n\t\tcaptured.#auxiliaryAttempts = this.#auxiliaryAttempts;\n\t\tcaptured.capturedSink = binding;\n\t\tcaptured.captureReserved = true;\n\t\tlet release!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tcaptured.finishCapturePending = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tcaptured.finishCapturePending = undefined;\n\t\t\trelease();\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tthis.notifyActivity();\n\t\treturn captured;\n\t}\n\n\t/** Explicit Root-owned epoch boundary, on this same captured MAIN source only. */\n\tbindRequestViewBoundary(\n\t\tmessages: readonly AgentMessage[],\n\t\tcommit: RequestViewCommit,\n\t\tvalidate?: RequestViewValidate,\n\t\tfixedPrepare?: RequestViewFixedPrepare,\n\t): void {\n\t\tthis.assertAdmission();\n\t\tif (!this.capturedSink) throw new Error(\"Request view boundary requires a captured inference owner\");\n\t\tif (this.requestViewBoundary) throw new Error(\"Request view boundary is already bound\");\n\t\tthis.requestViewBoundary = captureRequestViewBoundary(messages, commit, validate, fixedPrepare);\n\t}\n\n\t/** Read through an explicit capture, never by recapturing the mutable current session. */\n\tasync readHistory<T>(read: (view: SessionHistoryReadView) => Promise<T>): Promise<T> {\n\t\tthis.assertAdmission();\n\t\tconst sink = this.capturedSink?.sink;\n\t\tif (!sink?.readHistory) throw new Error(\"Captured canonical history is unavailable\");\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\ttry {\n\t\t\treturn await sink.readHistory(read);\n\t\t} finally {\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tfinish();\n\t\t\tthis.notifyActivity();\n\t\t}\n\t}\n\n\t/** Release an unused capture, or join this capture's admitted requests. */\n\tdispose(): Promise<void> {\n\t\tthis.disposed = true;\n\t\tthis.disposal ??= (async () => {\n\t\t\tthis.releaseCapture();\n\t\t\ttry {\n\t\t\t\tawait Promise.all([...this.active]);\n\t\t\t\tif (this.capturedSink) await this.finishSink(this.capturedSink, [], false, []);\n\t\t\t} finally {\n\t\t\t\tthis.finishCapturePending?.();\n\t\t\t}\n\t\t})();\n\t\treturn this.disposal;\n\t}\n\n\tprivate bindOperation(model: Model<Api>, request: InferenceRequestOptions, operationId: string): BoundOperation {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst metadata = Object.freeze({\n\t\t\toperationId,\n\t\t\tparentOperationId: request.parentOperationId,\n\t\t\tsemanticEdgeId: request.semanticEdgeId,\n\t\t\tpurpose: request.purpose,\n\t\t\tpurposeDetail: request.purposeDetail,\n\t\t\tmodelContract: modelContract(model),\n\t\t});\n\t\treturn { binding: this.sinkUse(this.bindSink()), owner, metadata };\n\t}\n\n\tprivate async finishSink(\n\t\tbinding: SinkUse,\n\t\twrites: readonly Promise<void>[],\n\t\tactiveUser: boolean,\n\t\tfailures: unknown[],\n\t): Promise<void> {\n\t\tconst results = await Promise.allSettled([binding.sink.source, ...writes]);\n\t\tfor (const result of results) {\n\t\t\tif (result.status === \"rejected\") failures.push(result.reason);\n\t\t}\n\t\tif (activeUser) binding.activeUsers--;\n\t\ttry {\n\t\t\tif (binding.activeUsers === 0 && binding.captures === 0) {\n\t\t\t\tbinding.release ??= binding.sink.release();\n\t\t\t\tawait binding.release;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailures.push(error);\n\t\t}\n\t\tconst distinct = [...new Set(failures)];\n\t\tif (distinct.length === 1) throw distinct[0];\n\t\tif (distinct.length > 1) throw new AggregateError(distinct, \"Inference request or source cleanup failed\");\n\t}\n\n\t/** Hold one logical operation through settled sends and recovery delays. */\n\tprivate retainWork(binding: SinkUse): (failures?: unknown[]) => Promise<void> {\n\t\tthis.assertAdmission();\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tlet release: Promise<void> | undefined;\n\t\treturn (failures = []) => {\n\t\t\trelease ??= (async () => {\n\t\t\t\tbinding.captures--;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.finishSink(binding, [], false, failures);\n\t\t\t\t} finally {\n\t\t\t\t\tthis.active.delete(pending);\n\t\t\t\t\tthis.work.pending.delete(pending);\n\t\t\t\t\tfinish();\n\t\t\t\t\tthis.notifyActivity();\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn release;\n\t\t};\n\t}\n\n\tprivate providerRecoveryWait(): (message: AssistantMessage, signal?: AbortSignal) => Promise<boolean> {\n\t\tlet nextDelayMs: number | undefined;\n\t\treturn async (message, callerSignal) => {\n\t\t\tconst policy = this.work.providerRecoveryPolicy?.();\n\t\t\tif (!policy?.enabled || !isTransientProviderFailure(message)) return false;\n\t\t\tthis.assertAdmission();\n\t\t\tconst signal = callerSignal\n\t\t\t\t? AbortSignal.any([callerSignal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst delayMs = Math.min(nextDelayMs ?? policy.baseDelayMs, policy.maxRetryDelayMs);\n\t\t\tawait delay(delayMs, undefined, { signal });\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.assertAdmission();\n\t\t\tnextDelayMs = Math.min(delayMs * 2, policy.maxRetryDelayMs);\n\t\t\treturn this.work.providerRecoveryPolicy?.().enabled === true;\n\t\t};\n\t}\n\n\tprivate async execute(\n\t\toperation: BoundOperation,\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\tsend: StreamFn,\n\t\tbindMainOutput = false,\n\t): Promise<InferenceRun> {\n\t\tconst outputSource = bindMainOutput ? captureNativeRequestOutputSource(operation.binding.sink) : undefined;\n\t\tconst part =\n\t\t\toperation.metadata.purpose === \"summary\"\n\t\t\t\t? operation.metadata.purposeDetail === \"compaction\"\n\t\t\t\t\t? \"history\"\n\t\t\t\t\t: operation.metadata.purposeDetail === \"compaction-turn-prefix\"\n\t\t\t\t\t\t? \"turn-prefix\"\n\t\t\t\t\t\t: undefined\n\t\t\t\t: undefined;\n\t\tconst compactionSource =\n\t\t\tthis.#nativeCompactionOutput && part && this.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeCompactionOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst branchSource =\n\t\t\tthis.#nativeBranchOutput &&\n\t\t\toperation.metadata.purpose === \"summary\" &&\n\t\t\toperation.metadata.purposeDetail === \"branch\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeBranchOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst plannerSource =\n\t\t\tthis.#nativePlannerOutput &&\n\t\t\toperation.metadata.purpose === \"refine\" &&\n\t\t\toperation.metadata.purposeDetail === \"plan\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativePlannerOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tlet outputSourceRef: SourceSnapshotRef | undefined;\n\t\tlet release!: (completion?: PromiseLike<void>) => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tconst finish = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tconst admittedAttempts: Array<{ attemptId: string; contextEpoch?: ContextEpochEntryRef }> = [];\n\t\tconst receiptWrites: Promise<void>[] = [];\n\t\tlet activeUser = false;\n\t\tlet localSimulation = false;\n\t\tlet budgetFailure: unknown;\n\t\tconst settle = async (result: Promise<AssistantMessage>): Promise<InferenceSettlement> => {\n\t\t\tconst failures: unknown[] = [];\n\t\t\tlet message: AssistantMessage | undefined;\n\t\t\ttry {\n\t\t\t\tmessage = await result;\n\t\t\t} catch (error) {\n\t\t\t\tfailures.push(error);\n\t\t\t}\n\t\t\tif (budgetFailure !== undefined && !failures.includes(budgetFailure)) failures.push(budgetFailure);\n\t\t\tawait this.finishSink(operation.binding, receiptWrites, activeUser, failures);\n\t\t\tif (message && outputSource && outputSourceRef) {\n\t\t\t\tconst write = outputSource({\n\t\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.mainOutputs.set(message, write);\n\t\t\t}\n\t\t\tconst settlement: InferenceSettlement = {\n\t\t\t\tmessage: message!,\n\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\tphysicalCoverage: admittedAttempts.length\n\t\t\t\t\t? \"reported\"\n\t\t\t\t\t: localSimulation\n\t\t\t\t\t\t? \"local-simulation\"\n\t\t\t\t\t\t: \"unestablished\",\n\t\t\t};\n\t\t\tif (part && compactionSource && outputSourceRef) {\n\t\t\t\tconst output = compactionSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (output)\n\t\t\t\t\tthis.work.compactionSettlements.set(settlement, {\n\t\t\t\t\t\tsink: operation.binding.sink,\n\t\t\t\t\t\toutput: { ...output, part },\n\t\t\t\t\t});\n\t\t\t}\n\t\t\tif (branchSource && outputSourceRef) {\n\t\t\t\tconst write = branchSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.branchSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\tif (plannerSource && outputSourceRef) {\n\t\t\t\tconst write = plannerSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.plannerSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\treturn settlement;\n\t\t};\n\t\ttry {\n\t\t\tthis.assertAdmission();\n\t\t\toperation.binding.sink.retain();\n\t\t\toperation.binding.release = undefined;\n\t\t\toperation.binding.activeUsers++;\n\t\t\tactiveUser = true;\n\t\t\tthis.releaseCapture();\n\t\t\tthis.finishCapturePending?.();\n\t\t\t// Capture the opted-in budgeted invocation before source/auth waits. Callbacks and signals stay live handles.\n\t\t\tif (this.work.budget || (this.requestViewBoundary && operation.metadata.purpose === \"main\")) {\n\t\t\t\tmodel = structuredClone(model);\n\t\t\t\t// Agent tool objects also carry live executors. Snapshot only the native Tool definition.\n\t\t\t\tcontext = structuredClone({\n\t\t\t\t\t...context,\n\t\t\t\t\t...(context.tools\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\ttools: context.tools.map(({ name, description, parameters }) => ({\n\t\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\t\tdescription,\n\t\t\t\t\t\t\t\t\tparameters,\n\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t});\n\t\t\t\toptions = options\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...options,\n\t\t\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\t}\n\t\t\tconst source = Object.freeze({ ...(await operation.binding.sink.source) });\n\t\t\toutputSourceRef = source;\n\t\t\tconst metadata: NativeRequestMetadata = {\n\t\t\t\t...operation.metadata,\n\t\t\t\tsource,\n\t\t\t\towner: Object.freeze({ ...operation.owner, sessionId: source.sessionId }),\n\t\t\t};\n\t\t\tif (send !== streamSimple && !nativeStreamFunctions.has(send)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Native inference cannot admit a custom or proxy StreamFn with unestablished physical-attempt coverage. Use the SDK's instrumented built-in API route instead.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tassertBuiltInAttemptSupport(model.api);\n\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\tconst parentBudget = this.work.budget;\n\t\t\tconst boundary = operation.metadata.purpose === \"main\" ? this.requestViewBoundary : undefined;\n\t\t\tconst budget = boundary ? parentBudget?.capture() : parentBudget;\n\t\t\tlet measuredForAdmission = false;\n\t\t\tconst measureRequest: ProviderAttemptObserver[\"measureRequest\"] =\n\t\t\t\tbudget || boundary?.validate\n\t\t\t\t\t? (representation) => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst assessment = budget?.measure(representation);\n\t\t\t\t\t\t\t\tboundary?.validate?.(representation, assessment);\n\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\tmeasuredForAdmission = true;\n\t\t\t\t\t\t\t\treturn assessment;\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\tconst canSelect =\n\t\t\t\t(budget || boundary?.fixedPrepare) && boundary && matchesRequestView(boundary, source, context);\n\t\t\tconst requiredPublic = Boolean(boundary?.pendingPublicMessageGroups?.length);\n\t\t\tif (requiredPublic && (!canSelect || boundary?.fixedPrepare))\n\t\t\t\tthrow new Error(\"Tool continuation requires a selectable native public request boundary\");\n\t\t\tlet publicAccepted = false;\n\t\t\tlet selectedContextEpoch: ContextEpochEntryRef | undefined;\n\t\t\tconst attempts: ProviderAttemptObserver = {\n\t\t\t\t...(requiredPublic\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpendingPublicMessageGroups: boundary!.providerPendingPublicMessageGroups!.map((group) => [\n\t\t\t\t\t\t\t\t...group,\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(measureRequest ? { measureRequest } : {}),\n\t\t\t\t...(canSelect\n\t\t\t\t\t? ({\n\t\t\t\t\t\t\tprepareRequest: async (representation, projection) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tselectedContextEpoch = undefined;\n\t\t\t\t\t\t\t\t\tpublicAccepted = false;\n\t\t\t\t\t\t\t\t\tif (JSON.parse(representation.body!).model !== model.id) return;\n\t\t\t\t\t\t\t\t\tif (boundary!.fixedPrepare) {\n\t\t\t\t\t\t\t\t\t\tconst assessment = budget?.measure(representation);\n\t\t\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\t\t\tconst accepted = await prepareFixedRequestView(\n\t\t\t\t\t\t\t\t\t\t\tboundary!,\n\t\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\t\tassessment,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\tif (accepted) selectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn await selectRequestView(\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t...boundary!,\n\t\t\t\t\t\t\t\t\t\t\tcommit: async (candidate) => {\n\t\t\t\t\t\t\t\t\t\t\t\tconst accepted = await boundary!.commit(candidate);\n\t\t\t\t\t\t\t\t\t\t\t\tif (accepted) selectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\t\t\tpublicAccepted = Boolean(\n\t\t\t\t\t\t\t\t\t\t\t\t\taccepted &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.publicMessages &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.projection.publicWindow &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t!candidate.projection.pendingPublicMessageGroups?.length,\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t\treturn accepted || undefined;\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\tbudget!,\n\t\t\t\t\t\t\t\t\t\tthis.work.budgetMode === \"enforce\",\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies Pick<ProviderAttemptObserver, \"prepareRequest\">)\n\t\t\t\t\t: {}),\n\t\t\t\tadmit: async (descriptor) => {\n\t\t\t\t\tif (requiredPublic && !publicAccepted)\n\t\t\t\t\t\tthrow new Error(\"Unaccepted tool continuation cannot enter native transport\");\n\t\t\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\t\t\t// An adapter without a serializer meter must not bypass an enforced budget.\n\t\t\t\t\tif (measureRequest && !descriptor.requestBudget && (budget || !measuredForAdmission)) {\n\t\t\t\t\t\tconst assessment = invokeRequestMeasurement(attempts, {\n\t\t\t\t\t\t\tapi: descriptor.api,\n\t\t\t\t\t\t\tprovider: descriptor.provider,\n\t\t\t\t\t\t\turl: \"\",\n\t\t\t\t\t\t\tbody: undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (assessment) descriptor = { ...descriptor, requestBudget: assessment };\n\t\t\t\t\t}\n\t\t\t\t\tmeasuredForAdmission = false;\n\t\t\t\t\tif (this.#auxiliaryAttempts) {\n\t\t\t\t\t\tif (this.#auxiliaryAttempts.remaining === 0) {\n\t\t\t\t\t\t\tbudgetFailure ??= new Error(\"Native auxiliary operation attempt limit exhausted\");\n\t\t\t\t\t\t\tthrow budgetFailure;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Reserve synchronously before persistence; failures and cancellation do not refund it.\n\t\t\t\t\t\tthis.#auxiliaryAttempts.remaining--;\n\t\t\t\t\t}\n\t\t\t\t\tconst attemptId = randomUUID();\n\t\t\t\t\tconst contextEpoch = selectedContextEpoch ? Object.freeze({ ...selectedContextEpoch }) : undefined;\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...metadata,\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_admitted\",\n\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\tdescriptor,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tadmittedAttempts.push({ attemptId, contextEpoch });\n\t\t\t\t\treturn attemptId;\n\t\t\t\t},\n\t\t\t\tsettle: async (receipt) => {\n\t\t\t\t\tconst contextEpoch = admittedAttempts.find(\n\t\t\t\t\t\t(attempt) => attempt.attemptId === receipt.attemptId,\n\t\t\t\t\t)?.contextEpoch;\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...metadata,\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_settled\",\n\t\t\t\t\t\tattemptId: receipt.attemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\treceipt,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tparentBudget?.observe(receipt);\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst signal = options?.signal\n\t\t\t\t? AbortSignal.any([options.signal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tconst events = await send(model, context, { ...options, signal, attempts, requireProviderAttempts: true });\n\t\t\tlocalSimulation = isLocalFauxStream(events);\n\t\t\tconst settled = settle(events.result());\n\t\t\tevents.result = async () => (await settled).message;\n\t\t\t// Idle tracking observes rejection; callers still receive it through settled/result().\n\t\t\trelease(settled.then(finish, finish));\n\t\t\treturn { events, settled };\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait settle(Promise.reject(error));\n\t\t\t} finally {\n\t\t\t\tfinish();\n\t\t\t\trelease();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync start(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceRun> {\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\treturn this.execute(\n\t\t\tthis.bindOperation(model, { ...request, semanticEdgeId }, operationId),\n\t\t\tmodel,\n\t\t\tcontext,\n\t\t\toptions,\n\t\t\tstreamSimple,\n\t\t);\n\t}\n\n\tprivate async completeWithProviderRecovery(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceSettlement> {\n\t\t// Retry the same request, not a caller's later mutable inputs. Keep callbacks/signals live.\n\t\tmodel = structuredClone(model);\n\t\tcontext = structuredClone({\n\t\t\t...context,\n\t\t\t...(context.tools\n\t\t\t\t? { tools: context.tools.map(({ name, description, parameters }) => ({ name, description, parameters })) }\n\t\t\t\t: {}),\n\t\t});\n\t\toptions = options\n\t\t\t? {\n\t\t\t\t\t...options,\n\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\tconst operation = this.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\tconst release = this.retainWork(operation.binding);\n\t\tconst recover = this.providerRecoveryWait();\n\t\tlet failure: unknown;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst settlement = await (await this.execute(operation, model, context, options, streamSimple)).settled;\n\t\t\t\t// Rejected execution/settlement, including local allowance exhaustion, never reaches recovery.\n\t\t\t\tif (!(await recover(settlement.message, options?.signal))) return settlement;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailure = error;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait release(failure === undefined ? [] : [failure]);\n\t\t}\n\t}\n\n\tcomplete(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<AssistantMessage> {\n\t\tlet completion!: Promise<AssistantMessage>;\n\t\tcompletion = (async () => {\n\t\t\tconst settlement = this.work.providerRecoveryPolicy?.().enabled\n\t\t\t\t? await this.completeWithProviderRecovery(model, context, options, request)\n\t\t\t\t: await (await this.start(model, context, options, request)).settled;\n\t\t\tconst binding = this.work.compactionSettlements.get(settlement);\n\t\t\tthis.work.compactionSettlements.delete(settlement);\n\t\t\tif (binding) this.work.compactionCompletions.set(completion, binding);\n\t\t\tconst branchBinding = this.work.branchSettlements.get(settlement);\n\t\t\tthis.work.branchSettlements.delete(settlement);\n\t\t\tif (branchBinding) this.work.branchCompletions.set(completion, branchBinding);\n\t\t\tconst plannerBinding = this.work.plannerSettlements.get(settlement);\n\t\t\tthis.work.plannerSettlements.delete(settlement);\n\t\t\tif (plannerBinding) this.work.plannerCompletions.set(completion, plannerBinding);\n\t\t\treturn settlement.message;\n\t\t})();\n\t\treturn completion;\n\t}\n\n\tbindAuxiliaryStream(streamFn: StreamFn, request: InferenceRequestOptions): DisposableInferenceStream {\n\t\tconst captured = this.capture();\n\t\tconst release = captured.retainWork(captured.capturedSink!);\n\t\tconst recover = captured.providerRecoveryWait();\n\t\tconst stream = captured.bindStream(streamFn, request);\n\t\tlet disposal: Promise<void> | undefined;\n\t\treturn Object.assign(stream, {\n\t\t\trecoverProviderFailure: async (message: AssistantMessage, signal?: AbortSignal) => {\n\t\t\t\tif (!(await recover(message, signal))) return false;\n\t\t\t\tcaptured.prepareTurnRetry();\n\t\t\t\treturn true;\n\t\t\t},\n\t\t\tdispose: () => {\n\t\t\t\tdisposal ??= (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait release();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tawait captured.dispose();\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\treturn disposal;\n\t\t\t},\n\t\t});\n\t}\n\n\tbindStream(streamFn: StreamFn, request: InferenceRequestOptions): AgentOwnedStreamFn {\n\t\tconst unwrapped = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\t\tconst inner = unwrapped[REQUEST_STREAM_BINDING]?.inner ?? unwrapped;\n\t\t// One Agent stream is serial. Keep only its latest binding for semantic retries.\n\t\t// A side question or child gets its own closure, not the parent's source binding.\n\t\tlet previous: BoundOperation | undefined;\n\t\tlet previousBody: string | undefined;\n\t\tconst wrapped: BoundStreamFn = async (model, context, options, streamContext) => {\n\t\t\tlet captured: InferenceCoordinator | undefined;\n\t\t\tif (streamContext !== undefined) {\n\t\t\t\tif (\n\t\t\t\t\t!(streamContext instanceof InferenceCoordinator) ||\n\t\t\t\t\tstreamContext.work !== this.work ||\n\t\t\t\t\t!streamContext.capturedSink\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Native stream context is not a capture of this inference owner\");\n\t\t\t\tcaptured = streamContext;\n\t\t\t}\n\t\t\tconst executor = captured ?? this;\n\t\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\t\t// Reuse the existing semantic body identity if its best-effort recorder is unavailable.\n\t\t\tconst body = semanticEdgeId ? undefined : hashTurnBody(model, context, options);\n\t\t\tconst retryId =\n\t\t\t\tthis.retryTurn && body !== undefined && body === previousBody ? previous?.metadata.operationId : undefined;\n\t\t\tthis.retryTurn = false;\n\t\t\tconst operationId = request.operationId ?? semanticEdgeId ?? retryId ?? randomUUID();\n\t\t\tpreviousBody = body;\n\t\t\tif (captured || previous?.metadata.operationId !== operationId) {\n\t\t\t\t// A semantic retry can reuse its operation ID, but compilation owns this exact source frontier.\n\t\t\t\tprevious = executor.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\t\t}\n\t\t\treturn (\n\t\t\t\tawait executor.execute(\n\t\t\t\t\tprevious,\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions,\n\t\t\t\t\tinner,\n\t\t\t\t\tcaptured !== undefined && request.purpose === \"main\",\n\t\t\t\t)\n\t\t\t).events;\n\t\t};\n\t\twrapped[REQUEST_STREAM_BINDING] = { coordinator: this, inner };\n\t\treturn wrapped;\n\t}\n}\n\n/** Standalone helper embedding stays optional; native session callers always supply requests. */\nexport function completeInference(\n\trequests: InferenceCoordinator | undefined,\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions | undefined,\n\trequest: InferenceRequestOptions,\n): Promise<AssistantMessage> {\n\treturn requests ? requests.complete(model, context, options, request) : completeSimple(model, context, options);\n}\n\nexport type DisposableInferenceStream = StreamFn & {\n\tdispose(): Promise<void>;\n\trecoverProviderFailure?(message: AssistantMessage, signal?: AbortSignal): Promise<boolean>;\n};\n\n/** Side questions keep the subject's writer, but get their own operation and purpose. */\nexport function bindAuxiliaryInferenceStream(\n\tstreamFn: StreamFn,\n\trequest: InferenceRequestOptions,\n): DisposableInferenceStream {\n\tconst inner = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\tconst binding = inner[REQUEST_STREAM_BINDING];\n\tif (binding) return binding.coordinator.bindAuxiliaryStream(binding.inner, request);\n\tconst stream: StreamFn = (model, context, options) => inner(model, context, options);\n\treturn Object.assign(stream, { dispose: async () => {} });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"inference-coordinator.js","sourceRoot":"","sources":["../../src/core/inference-coordinator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,EAGN,2BAA2B,EAE3B,cAAc,EACd,wBAAwB,EACxB,iBAAiB,EACjB,0BAA0B,EAG1B,kBAAkB,EAGlB,YAAY,GACZ,MAAM,+BAA+B,CAAC;AAevC,OAA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M,OAAO,GAAG,KAAK,CAAC,sBAAsB,CAAC,CAAC;IAC9C,IAAI,OAAO;QAAE,OAAO,OAAO,CAAC,WAAW,CAAC,mBAAmB,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACpF,MAAM,MAAM,GAAa,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IACrF,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,KAAK,IAAI,EAAE,CAAC,EAAC,CAAC,EAAE,CAAC,CAAC;AAAA,CAC1D","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { AgentMessage, AgentOwnedStreamFn, StreamFn } from \"@ponythewhite/base-context-agent\";\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\tassertBuiltInAttemptSupport,\n\ttype Context,\n\tcompleteSimple,\n\tinvokeRequestMeasurement,\n\tisLocalFauxStream,\n\tisTransientProviderFailure,\n\ttype Model,\n\ttype ProviderAttemptObserver,\n\tRequestTokenBudget,\n\ttype RequestTokenBudgetOptions,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n} from \"@ponythewhite/base-context-ai\";\nimport type { AuthSourceToken } from \"./auth-storage.js\";\nimport type {\n\tBoundRequestSink,\n\tContextEpochEntryRef,\n\tNativeBranchRequestOutputWriter,\n\tNativeCompactionRequestOutputAssociation,\n\tNativePlannerRequestOutputWriter,\n\tNativeRequestMetadata,\n\tNativeRequestOutputWriter,\n\tRequestOwnerRef,\n\tRequestPurpose,\n\tResolvedModelContract,\n\tSourceSnapshotRef,\n} from \"./request-events.js\";\nimport {\n\ttype CapturedRequestViewBoundary,\n\tcaptureRequestViewBoundary,\n\tmatchesRequestView,\n\tprepareFixedRequestView,\n\ttype RequestViewCommit,\n\ttype RequestViewFixedPrepare,\n\ttype RequestViewValidate,\n\tselectRequestView,\n} from \"./request-view-selection.js\";\nimport { hashTurnBody, MODEL_REQUEST_ID_HEADER, unwrapSemanticEdgeStreamFn } from \"./semantic-edges.js\";\nimport type { SessionHistoryReadView } from \"./session-history-index.js\";\nimport {\n\tcaptureNativeBranchOutputSource,\n\tcaptureNativeCompactionOutputSource,\n\tcaptureNativePlannerOutputSource,\n\tcaptureNativeRequestOutputSource,\n} from \"./session-manager.js\";\n\nexport interface InferenceRequestOptions {\n\treadonly purpose: RequestPurpose;\n\treadonly purposeDetail?: string;\n\treadonly operationId?: string;\n\treadonly parentOperationId?: string;\n\treadonly semanticEdgeId?: string;\n}\n\nexport interface InferenceSettlement {\n\treadonly message: AssistantMessage;\n\treadonly operationId: string;\n\treadonly attemptIds: readonly string[];\n\t/** Reporting is not a guarantee about an opaque adapter's hidden retries. */\n\treadonly physicalCoverage: \"reported\" | \"unestablished\" | \"local-simulation\";\n}\n\n/** Private completion identity carries this actual source, never descriptive sink labels. */\nexport interface NativeCompactionOutputBinding {\n\treadonly sink: BoundRequestSink;\n\treadonly output: NativeCompactionRequestOutputAssociation;\n}\n\ninterface NativeBranchOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativeBranchRequestOutputWriter;\n}\n\ninterface NativePlannerOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativePlannerRequestOutputWriter;\n}\n\nexport interface InferenceRun {\n\treadonly events: Awaited<ReturnType<StreamFn>>;\n\treadonly settled: Promise<InferenceSettlement>;\n}\n\nexport interface SessionRuntimeServices {\n\treadonly requests: InferenceCoordinator;\n}\n\ninterface ProviderRecoveryPolicy {\n\tenabled: boolean;\n\tbaseDelayMs: number;\n\tmaxRetryDelayMs: number;\n}\n\ninterface SinkUse {\n\treadonly sink: BoundRequestSink;\n\tactiveUsers: number;\n\tcaptures: number;\n\trelease?: Promise<void>;\n}\n\ninterface BoundOperation {\n\treadonly binding: SinkUse;\n\treadonly owner: Omit<RequestOwnerRef, \"sessionId\">;\n\treadonly metadata: Omit<NativeRequestMetadata, \"source\" | \"owner\" | \"contextEpoch\">;\n}\n\nconst REQUEST_STREAM_BINDING = Symbol(\"base-context.request-stream-binding\");\n/** Internal AgentSession built-in compaction entry, not a public inference option. */\nexport const captureNativeCompactionRequests = Symbol(\"base-context.native-compaction-requests\");\n/** Internal AgentSession built-in branch-summary invocation, never inherited by generic capture. */\nexport const captureNativeBranchRequests = Symbol(\"base-context.native-branch-requests\");\n/** Internal native AgentSession planner capture, never inherited by generic capture. */\nexport const captureNativePlannerRequests = Symbol(\"base-context.native-planner-requests\");\n/** Internal native AgentSession reviewer invocation. */\nexport const captureNativeReviewerRequests = Symbol(\"base-context.native-reviewer-requests\");\ninterface StreamBinding {\n\treadonly coordinator: InferenceCoordinator;\n\treadonly inner: StreamFn;\n}\ntype BoundStreamFn = AgentOwnedStreamFn & { [REQUEST_STREAM_BINDING]?: StreamBinding };\n\nfunction modelContract(model: Model<Api>): ResolvedModelContract {\n\treturn {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tprofile: { id: \"native-default\", status: \"unvalidated\" },\n\t\tpricing: {\n\t\t\tstatus: \"unvalidated\",\n\t\t\tcurrency: \"USD\",\n\t\t\tunit: \"million-tokens\",\n\t\t\tcatalogRates: {\n\t\t\t\tinput: model.cost.input,\n\t\t\t\toutput: model.cost.output,\n\t\t\t\tcacheRead: model.cost.cacheRead,\n\t\t\t\tcacheWrite: model.cost.cacheWrite,\n\t\t\t},\n\t\t},\n\t};\n}\n\nconst nativeStreamFunctions = new WeakSet<StreamFn>();\nconst nativeAuthSources = new WeakMap<AssistantMessage, AuthSourceToken>();\n\n/** Consume the credential source resolved for this exact native request. Never persisted or sent to providers. */\nexport function takeNativeInferenceAuthSource(message: AssistantMessage): AuthSourceToken | undefined {\n\tconst source = nativeAuthSources.get(message);\n\tnativeAuthSources.delete(message);\n\treturn source;\n}\n\n/** Internal SDK auth/options resolver; transport stays the known instrumented AI dispatcher. */\nexport function createNativeInferenceStream(\n\tresolveOptions: (\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t) => Promise<SimpleStreamOptions & { authSourceToken?: AuthSourceToken }>,\n): StreamFn {\n\tconst dispatch: StreamFn = async (model, context, options) => {\n\t\tconst { authSourceToken, ...resolved } = await resolveOptions(model, context, options);\n\t\tconst events = streamSimple(model, context, {\n\t\t\t...resolved,\n\t\t\tsignal: options?.signal,\n\t\t\tattempts: options?.attempts,\n\t\t\trequireProviderAttempts: true,\n\t\t});\n\t\tif (authSourceToken) {\n\t\t\tconst source = { ...authSourceToken };\n\t\t\tconst result = events.result().then((message) => {\n\t\t\t\tnativeAuthSources.set(message, source);\n\t\t\t\treturn message;\n\t\t\t});\n\t\t\tevents.result = () => result;\n\t\t}\n\t\treturn events;\n\t};\n\tnativeStreamFunctions.add(dispatch);\n\treturn dispatch;\n}\n\n/** Routes physical observations to the source writer. It owns no receipt store. */\nexport class InferenceCoordinator {\n\t#nativeCompactionOutput = false;\n\t#nativeBranchOutput = false;\n\t#nativePlannerOutput = false;\n\t#auxiliaryAttempts?: { remaining: number };\n\tprivate retryTurn = false;\n\tprivate requestViewBoundary?: CapturedRequestViewBoundary;\n\tprivate active = new Set<Promise<void>>();\n\tprivate capturedSink?: SinkUse;\n\tprivate captureReserved = false;\n\tprivate finishCapturePending?: () => void;\n\tprivate disposed = false;\n\tprivate disposal?: Promise<void>;\n\tprivate work = {\n\t\tpending: new Set<Promise<void>>(),\n\t\tsinks: new WeakMap<BoundRequestSink, SinkUse>(),\n\t\tmainOutputs: new WeakMap<AssistantMessage, NativeRequestOutputWriter>(),\n\t\tcompactionSettlements: new WeakMap<InferenceSettlement, NativeCompactionOutputBinding>(),\n\t\tcompactionCompletions: new WeakMap<Promise<AssistantMessage>, NativeCompactionOutputBinding>(),\n\t\tbranchSettlements: new WeakMap<InferenceSettlement, NativeBranchOutputBinding>(),\n\t\tbranchCompletions: new WeakMap<Promise<AssistantMessage>, NativeBranchOutputBinding>(),\n\t\tplannerSettlements: new WeakMap<InferenceSettlement, NativePlannerOutputBinding>(),\n\t\tplannerCompletions: new WeakMap<Promise<AssistantMessage>, NativePlannerOutputBinding>(),\n\t\tlisteners: new Set<() => void>(),\n\t\tadmissionOpen: true,\n\t\tcancellation: new AbortController(),\n\t\tbudget: undefined as RequestTokenBudget | undefined,\n\t\tbudgetMode: undefined as RequestTokenBudgetOptions[\"mode\"] | undefined,\n\t\tproviderRecoveryPolicy: undefined as (() => ProviderRecoveryPolicy) | undefined,\n\t};\n\n\tsetProviderRecoveryPolicy(policy: () => ProviderRecoveryPolicy): void {\n\t\tthis.work.providerRecoveryPolicy = policy;\n\t}\n\n\tget hasPending(): boolean {\n\t\treturn this.work.pending.size > 0;\n\t}\n\tget pendingCount(): number {\n\t\treturn this.work.pending.size;\n\t}\n\n\tonActivityChange(listener: () => void): () => void {\n\t\tthis.work.listeners.add(listener);\n\t\treturn () => this.work.listeners.delete(listener);\n\t}\n\n\tprivate notifyActivity(): void {\n\t\t// Observers can wake an existing owner, but cannot own request settlement.\n\t\tfor (const listener of this.work.listeners) {\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Notification is not execution. */\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Consume only this owner's real returned object. Labels and replacement messages remain unassociated. */\n\tappendMainOutput(message: AssistantMessage, owner: object): Promise<string | undefined> | undefined {\n\t\tconst write = this.work.mainOutputs.get(message);\n\t\tthis.work.mainOutputs.delete(message);\n\t\treturn write?.(owner, message);\n\t}\n\n\t/** Opt this native invocation into output association; ordinary captures do not inherit that authority. */\n\t[captureNativeCompactionRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#nativeCompactionOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 4 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeBranchRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativeBranchOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakeBranchOutput(completion: Promise<AssistantMessage>): NativeBranchRequestOutputWriter | undefined {\n\t\tconst binding = this.work.branchCompletions.get(completion);\n\t\tthis.work.branchCompletions.delete(completion);\n\t\tif (!binding || !this.#nativeBranchOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t[captureNativePlannerRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativePlannerOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeReviewerRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakePlannerOutput(completion: Promise<AssistantMessage>): NativePlannerRequestOutputWriter | undefined {\n\t\tconst binding = this.work.plannerCompletions.get(completion);\n\t\tthis.work.plannerCompletions.delete(completion);\n\t\tif (!binding || !this.#nativePlannerOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t/** Only the original completion promise and captured source can supply a projected-output link. */\n\ttakeCompactionOutput(completion: Promise<AssistantMessage>): NativeCompactionOutputBinding | undefined {\n\t\tconst binding = this.work.compactionCompletions.get(completion);\n\t\tthis.work.compactionCompletions.delete(completion);\n\t\treturn binding?.sink === this.capturedSink?.sink ? binding : undefined;\n\t}\n\n\t/** Owner teardown stops new sends, but never suppresses an admitted request's settlement. */\n\tstopAdmission(): void {\n\t\tthis.work.admissionOpen = false;\n\t\tthis.work.cancellation.abort();\n\t\tthis.notifyActivity();\n\t}\n\n\tasync waitForIdle(): Promise<void> {\n\t\twhile (this.work.pending.size > 0) await Promise.all([...this.work.pending]);\n\t}\n\n\tprepareTurnRetry(): void {\n\t\tthis.retryTurn = true;\n\t}\n\tclearTurnRetry(): void {\n\t\tthis.retryTurn = false;\n\t}\n\n\tconstructor(\n\t\tprivate readonly bindSink: () => BoundRequestSink,\n\t\tprivate readonly owner: () => Omit<RequestOwnerRef, \"sessionId\"> = () => ({}),\n\t\trequestTokenBudget?: RequestTokenBudgetOptions,\n\t) {\n\t\tif (requestTokenBudget) {\n\t\t\tthis.work.budget = new RequestTokenBudget(requestTokenBudget);\n\t\t\tthis.work.budgetMode = requestTokenBudget.mode;\n\t\t}\n\t}\n\n\t/** Copy the configured policy, not this owner's learned request observations. */\n\tgetRequestTokenBudgetOptions(): RequestTokenBudgetOptions | undefined {\n\t\treturn this.work.budget?.getOptions();\n\t}\n\n\tprivate assertAdmission(): void {\n\t\tif (this.disposed || !this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t}\n\n\tprivate sinkUse(sink: BoundRequestSink): SinkUse {\n\t\tlet binding = this.work.sinks.get(sink);\n\t\tif (!binding) {\n\t\t\tbinding = { sink, activeUsers: 0, captures: 0 };\n\t\t\tthis.work.sinks.set(sink, binding);\n\t\t}\n\t\treturn binding;\n\t}\n\n\tprivate releaseCapture(): void {\n\t\tif (this.captureReserved && this.capturedSink) {\n\t\t\tthis.captureReserved = false;\n\t\t\tthis.capturedSink.captures--;\n\t\t}\n\t}\n\n\t/** Capture an auxiliary operation's subject before asynchronous auth or UI work. */\n\tcapture(sink?: BoundRequestSink): InferenceCoordinator {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst binding = this.sinkUse(sink ?? this.bindSink());\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tconst captured = new InferenceCoordinator(\n\t\t\t() => binding.sink,\n\t\t\t() => owner,\n\t\t);\n\t\tcaptured.work = this.work;\n\t\t// Nested captures share the invocation's allowance, not its native output authority.\n\t\tcaptured.#auxiliaryAttempts = this.#auxiliaryAttempts;\n\t\tcaptured.capturedSink = binding;\n\t\tcaptured.captureReserved = true;\n\t\tlet release!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tcaptured.finishCapturePending = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tcaptured.finishCapturePending = undefined;\n\t\t\trelease();\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tthis.notifyActivity();\n\t\treturn captured;\n\t}\n\n\t/** Explicit Root-owned epoch boundary, on this same captured MAIN source only. */\n\tbindRequestViewBoundary(\n\t\tmessages: readonly AgentMessage[],\n\t\tcommit: RequestViewCommit,\n\t\tvalidate?: RequestViewValidate,\n\t\tfixedPrepare?: RequestViewFixedPrepare,\n\t): void {\n\t\tthis.assertAdmission();\n\t\tif (!this.capturedSink) throw new Error(\"Request view boundary requires a captured inference owner\");\n\t\tif (this.requestViewBoundary) throw new Error(\"Request view boundary is already bound\");\n\t\tthis.requestViewBoundary = captureRequestViewBoundary(messages, commit, validate, fixedPrepare);\n\t}\n\n\t/** Read through an explicit capture, never by recapturing the mutable current session. */\n\tasync readHistory<T>(read: (view: SessionHistoryReadView) => Promise<T>): Promise<T> {\n\t\tthis.assertAdmission();\n\t\tconst sink = this.capturedSink?.sink;\n\t\tif (!sink?.readHistory) throw new Error(\"Captured canonical history is unavailable\");\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\ttry {\n\t\t\treturn await sink.readHistory(read);\n\t\t} finally {\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tfinish();\n\t\t\tthis.notifyActivity();\n\t\t}\n\t}\n\n\t/** Release an unused capture, or join this capture's admitted requests. */\n\tdispose(): Promise<void> {\n\t\tthis.disposed = true;\n\t\tthis.disposal ??= (async () => {\n\t\t\tthis.releaseCapture();\n\t\t\ttry {\n\t\t\t\tawait Promise.all([...this.active]);\n\t\t\t\tif (this.capturedSink) await this.finishSink(this.capturedSink, [], false, []);\n\t\t\t} finally {\n\t\t\t\tthis.finishCapturePending?.();\n\t\t\t}\n\t\t})();\n\t\treturn this.disposal;\n\t}\n\n\tprivate bindOperation(model: Model<Api>, request: InferenceRequestOptions, operationId: string): BoundOperation {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst metadata = Object.freeze({\n\t\t\toperationId,\n\t\t\tparentOperationId: request.parentOperationId,\n\t\t\tsemanticEdgeId: request.semanticEdgeId,\n\t\t\tpurpose: request.purpose,\n\t\t\tpurposeDetail: request.purposeDetail,\n\t\t\tmodelContract: modelContract(model),\n\t\t});\n\t\treturn { binding: this.sinkUse(this.bindSink()), owner, metadata };\n\t}\n\n\tprivate async finishSink(\n\t\tbinding: SinkUse,\n\t\twrites: readonly Promise<void>[],\n\t\tactiveUser: boolean,\n\t\tfailures: unknown[],\n\t): Promise<void> {\n\t\tconst results = await Promise.allSettled([binding.sink.source, ...writes]);\n\t\tfor (const result of results) {\n\t\t\tif (result.status === \"rejected\") failures.push(result.reason);\n\t\t}\n\t\tif (activeUser) binding.activeUsers--;\n\t\ttry {\n\t\t\tif (binding.activeUsers === 0 && binding.captures === 0) {\n\t\t\t\tbinding.release ??= binding.sink.release();\n\t\t\t\tawait binding.release;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailures.push(error);\n\t\t}\n\t\tconst distinct = [...new Set(failures)];\n\t\tif (distinct.length === 1) throw distinct[0];\n\t\tif (distinct.length > 1) throw new AggregateError(distinct, \"Inference request or source cleanup failed\");\n\t}\n\n\t/** Hold one logical operation through settled sends and recovery delays. */\n\tprivate retainWork(binding: SinkUse): (failures?: unknown[]) => Promise<void> {\n\t\tthis.assertAdmission();\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tlet release: Promise<void> | undefined;\n\t\treturn (failures = []) => {\n\t\t\trelease ??= (async () => {\n\t\t\t\tbinding.captures--;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.finishSink(binding, [], false, failures);\n\t\t\t\t} finally {\n\t\t\t\t\tthis.active.delete(pending);\n\t\t\t\t\tthis.work.pending.delete(pending);\n\t\t\t\t\tfinish();\n\t\t\t\t\tthis.notifyActivity();\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn release;\n\t\t};\n\t}\n\n\tprivate providerRecoveryWait(): (message: AssistantMessage, signal?: AbortSignal) => Promise<boolean> {\n\t\tlet nextDelayMs: number | undefined;\n\t\treturn async (message, callerSignal) => {\n\t\t\tconst policy = this.work.providerRecoveryPolicy?.();\n\t\t\tif (!policy?.enabled || !isTransientProviderFailure(message)) return false;\n\t\t\tthis.assertAdmission();\n\t\t\tconst signal = callerSignal\n\t\t\t\t? AbortSignal.any([callerSignal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst delayMs = Math.min(nextDelayMs ?? policy.baseDelayMs, policy.maxRetryDelayMs);\n\t\t\tawait delay(delayMs, undefined, { signal });\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.assertAdmission();\n\t\t\tnextDelayMs = Math.min(delayMs * 2, policy.maxRetryDelayMs);\n\t\t\treturn this.work.providerRecoveryPolicy?.().enabled === true;\n\t\t};\n\t}\n\n\tprivate async execute(\n\t\toperation: BoundOperation,\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\tsend: StreamFn,\n\t\tbindMainOutput = false,\n\t): Promise<InferenceRun> {\n\t\tconst outputSource = bindMainOutput ? captureNativeRequestOutputSource(operation.binding.sink) : undefined;\n\t\tconst part =\n\t\t\toperation.metadata.purpose === \"summary\"\n\t\t\t\t? operation.metadata.purposeDetail === \"compaction\"\n\t\t\t\t\t? \"history\"\n\t\t\t\t\t: operation.metadata.purposeDetail === \"compaction-turn-prefix\"\n\t\t\t\t\t\t? \"turn-prefix\"\n\t\t\t\t\t\t: undefined\n\t\t\t\t: undefined;\n\t\tconst compactionSource =\n\t\t\tthis.#nativeCompactionOutput && part && this.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeCompactionOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst branchSource =\n\t\t\tthis.#nativeBranchOutput &&\n\t\t\toperation.metadata.purpose === \"summary\" &&\n\t\t\toperation.metadata.purposeDetail === \"branch\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeBranchOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst plannerSource =\n\t\t\tthis.#nativePlannerOutput &&\n\t\t\toperation.metadata.purpose === \"refine\" &&\n\t\t\toperation.metadata.purposeDetail === \"plan\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativePlannerOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tlet outputSourceRef: SourceSnapshotRef | undefined;\n\t\tlet release!: (completion?: PromiseLike<void>) => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tconst finish = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tconst admittedAttempts: Array<{ attemptId: string; contextEpoch?: ContextEpochEntryRef }> = [];\n\t\tconst receiptWrites: Promise<void>[] = [];\n\t\tlet activeUser = false;\n\t\tlet localSimulation = false;\n\t\tlet budgetFailure: unknown;\n\t\tconst settle = async (result: Promise<AssistantMessage>): Promise<InferenceSettlement> => {\n\t\t\tconst failures: unknown[] = [];\n\t\t\tlet message: AssistantMessage | undefined;\n\t\t\ttry {\n\t\t\t\tmessage = await result;\n\t\t\t} catch (error) {\n\t\t\t\tfailures.push(error);\n\t\t\t}\n\t\t\tif (budgetFailure !== undefined && !failures.includes(budgetFailure)) failures.push(budgetFailure);\n\t\t\tawait this.finishSink(operation.binding, receiptWrites, activeUser, failures);\n\t\t\tif (message && outputSource && outputSourceRef) {\n\t\t\t\tconst write = outputSource({\n\t\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.mainOutputs.set(message, write);\n\t\t\t}\n\t\t\tconst settlement: InferenceSettlement = {\n\t\t\t\tmessage: message!,\n\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\tphysicalCoverage: admittedAttempts.length\n\t\t\t\t\t? \"reported\"\n\t\t\t\t\t: localSimulation\n\t\t\t\t\t\t? \"local-simulation\"\n\t\t\t\t\t\t: \"unestablished\",\n\t\t\t};\n\t\t\tif (part && compactionSource && outputSourceRef) {\n\t\t\t\tconst output = compactionSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (output)\n\t\t\t\t\tthis.work.compactionSettlements.set(settlement, {\n\t\t\t\t\t\tsink: operation.binding.sink,\n\t\t\t\t\t\toutput: { ...output, part },\n\t\t\t\t\t});\n\t\t\t}\n\t\t\tif (branchSource && outputSourceRef) {\n\t\t\t\tconst write = branchSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.branchSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\tif (plannerSource && outputSourceRef) {\n\t\t\t\tconst write = plannerSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.plannerSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\treturn settlement;\n\t\t};\n\t\ttry {\n\t\t\tthis.assertAdmission();\n\t\t\toperation.binding.sink.retain();\n\t\t\toperation.binding.release = undefined;\n\t\t\toperation.binding.activeUsers++;\n\t\t\tactiveUser = true;\n\t\t\tthis.releaseCapture();\n\t\t\tthis.finishCapturePending?.();\n\t\t\t// Capture the opted-in budgeted invocation before source/auth waits. Callbacks and signals stay live handles.\n\t\t\tif (this.work.budget || (this.requestViewBoundary && operation.metadata.purpose === \"main\")) {\n\t\t\t\tmodel = structuredClone(model);\n\t\t\t\t// Agent tool objects also carry live executors. Snapshot only the native Tool definition.\n\t\t\t\tcontext = structuredClone({\n\t\t\t\t\t...context,\n\t\t\t\t\t...(context.tools\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\ttools: context.tools.map(({ name, description, parameters }) => ({\n\t\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\t\tdescription,\n\t\t\t\t\t\t\t\t\tparameters,\n\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t});\n\t\t\t\toptions = options\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...options,\n\t\t\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\t}\n\t\t\tconst source = Object.freeze({ ...(await operation.binding.sink.source) });\n\t\t\toutputSourceRef = source;\n\t\t\tconst metadata: NativeRequestMetadata = {\n\t\t\t\t...operation.metadata,\n\t\t\t\tsource,\n\t\t\t\towner: Object.freeze({ ...operation.owner, sessionId: source.sessionId }),\n\t\t\t};\n\t\t\tif (send !== streamSimple && !nativeStreamFunctions.has(send)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Native inference cannot admit a custom or proxy StreamFn with unestablished physical-attempt coverage. Use the SDK's instrumented built-in API route instead.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tassertBuiltInAttemptSupport(model.api);\n\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\tconst parentBudget = this.work.budget;\n\t\t\tconst boundary = operation.metadata.purpose === \"main\" ? this.requestViewBoundary : undefined;\n\t\t\tconst budget = boundary ? parentBudget?.capture() : parentBudget;\n\t\t\tlet measuredForAdmission = false;\n\t\t\tconst measureRequest: ProviderAttemptObserver[\"measureRequest\"] =\n\t\t\t\tbudget || boundary?.validate\n\t\t\t\t\t? (representation) => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst assessment = budget?.measure(representation);\n\t\t\t\t\t\t\t\tboundary?.validate?.(representation, assessment);\n\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\tmeasuredForAdmission = true;\n\t\t\t\t\t\t\t\treturn assessment;\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\tconst canSelect =\n\t\t\t\t(budget || boundary?.fixedPrepare) && boundary && matchesRequestView(boundary, source, context);\n\t\t\tconst requiredPublic = Boolean(boundary?.pendingPublicMessageGroups?.length);\n\t\t\tif (requiredPublic && (!canSelect || boundary?.fixedPrepare))\n\t\t\t\tthrow new Error(\"Tool continuation requires a selectable native public request boundary\");\n\t\t\tlet publicAccepted = false;\n\t\t\tlet selectedContextEpoch: ContextEpochEntryRef | undefined;\n\t\t\tconst attempts: ProviderAttemptObserver = {\n\t\t\t\t...(requiredPublic\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpendingPublicMessageGroups: boundary!.providerPendingPublicMessageGroups!.map((group) => [\n\t\t\t\t\t\t\t\t...group,\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(measureRequest ? { measureRequest } : {}),\n\t\t\t\t...(canSelect\n\t\t\t\t\t? ({\n\t\t\t\t\t\t\tprepareRequest: async (representation, projection) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tselectedContextEpoch = undefined;\n\t\t\t\t\t\t\t\t\tpublicAccepted = false;\n\t\t\t\t\t\t\t\t\tif (JSON.parse(representation.body!).model !== model.id) return;\n\t\t\t\t\t\t\t\t\tif (boundary!.fixedPrepare) {\n\t\t\t\t\t\t\t\t\t\tconst assessment = budget?.measure(representation);\n\t\t\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\t\t\tconst accepted = await prepareFixedRequestView(\n\t\t\t\t\t\t\t\t\t\t\tboundary!,\n\t\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\t\tassessment,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\tif (accepted) selectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn await selectRequestView(\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t...boundary!,\n\t\t\t\t\t\t\t\t\t\t\tcommit: async (candidate) => {\n\t\t\t\t\t\t\t\t\t\t\t\tconst accepted = await boundary!.commit(candidate);\n\t\t\t\t\t\t\t\t\t\t\t\tif (accepted) selectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\t\t\tpublicAccepted = Boolean(\n\t\t\t\t\t\t\t\t\t\t\t\t\taccepted &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.publicMessages &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.projection.publicWindow &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t!candidate.projection.pendingPublicMessageGroups?.length,\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t\treturn accepted || undefined;\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\tbudget!,\n\t\t\t\t\t\t\t\t\t\tthis.work.budgetMode === \"enforce\",\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies Pick<ProviderAttemptObserver, \"prepareRequest\">)\n\t\t\t\t\t: {}),\n\t\t\t\tadmit: async (descriptor) => {\n\t\t\t\t\tif (requiredPublic && !publicAccepted)\n\t\t\t\t\t\tthrow new Error(\"Unaccepted tool continuation cannot enter native transport\");\n\t\t\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\t\t\t// An adapter without a serializer meter must not bypass an enforced budget.\n\t\t\t\t\tif (measureRequest && !descriptor.requestBudget && (budget || !measuredForAdmission)) {\n\t\t\t\t\t\tconst assessment = invokeRequestMeasurement(attempts, {\n\t\t\t\t\t\t\tapi: descriptor.api,\n\t\t\t\t\t\t\tprovider: descriptor.provider,\n\t\t\t\t\t\t\turl: \"\",\n\t\t\t\t\t\t\tbody: undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (assessment) descriptor = { ...descriptor, requestBudget: assessment };\n\t\t\t\t\t}\n\t\t\t\t\tmeasuredForAdmission = false;\n\t\t\t\t\tif (this.#auxiliaryAttempts) {\n\t\t\t\t\t\tif (this.#auxiliaryAttempts.remaining === 0) {\n\t\t\t\t\t\t\tbudgetFailure ??= new Error(\"Native auxiliary operation attempt limit exhausted\");\n\t\t\t\t\t\t\tthrow budgetFailure;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Reserve synchronously before persistence; failures and cancellation do not refund it.\n\t\t\t\t\t\tthis.#auxiliaryAttempts.remaining--;\n\t\t\t\t\t}\n\t\t\t\t\tconst attemptId = randomUUID();\n\t\t\t\t\tconst contextEpoch = selectedContextEpoch ? Object.freeze({ ...selectedContextEpoch }) : undefined;\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...metadata,\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_admitted\",\n\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\tdescriptor,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tadmittedAttempts.push({ attemptId, contextEpoch });\n\t\t\t\t\treturn attemptId;\n\t\t\t\t},\n\t\t\t\tsettle: async (receipt) => {\n\t\t\t\t\tconst contextEpoch = admittedAttempts.find(\n\t\t\t\t\t\t(attempt) => attempt.attemptId === receipt.attemptId,\n\t\t\t\t\t)?.contextEpoch;\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...metadata,\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_settled\",\n\t\t\t\t\t\tattemptId: receipt.attemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\treceipt,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tparentBudget?.observe(receipt);\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst signal = options?.signal\n\t\t\t\t? AbortSignal.any([options.signal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tconst events = await send(model, context, { ...options, signal, attempts, requireProviderAttempts: true });\n\t\t\tlocalSimulation = isLocalFauxStream(events);\n\t\t\tconst settled = settle(events.result());\n\t\t\tevents.result = async () => (await settled).message;\n\t\t\t// Idle tracking observes rejection; callers still receive it through settled/result().\n\t\t\trelease(settled.then(finish, finish));\n\t\t\treturn { events, settled };\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait settle(Promise.reject(error));\n\t\t\t} finally {\n\t\t\t\tfinish();\n\t\t\t\trelease();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync start(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceRun> {\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\treturn this.execute(\n\t\t\tthis.bindOperation(model, { ...request, semanticEdgeId }, operationId),\n\t\t\tmodel,\n\t\t\tcontext,\n\t\t\toptions,\n\t\t\tstreamSimple,\n\t\t);\n\t}\n\n\tprivate async completeWithProviderRecovery(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceSettlement> {\n\t\t// Retry the same request, not a caller's later mutable inputs. Keep callbacks/signals live.\n\t\tmodel = structuredClone(model);\n\t\tcontext = structuredClone({\n\t\t\t...context,\n\t\t\t...(context.tools\n\t\t\t\t? { tools: context.tools.map(({ name, description, parameters }) => ({ name, description, parameters })) }\n\t\t\t\t: {}),\n\t\t});\n\t\toptions = options\n\t\t\t? {\n\t\t\t\t\t...options,\n\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\tconst operation = this.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\tconst release = this.retainWork(operation.binding);\n\t\tconst recover = this.providerRecoveryWait();\n\t\tlet failure: unknown;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst settlement = await (await this.execute(operation, model, context, options, streamSimple)).settled;\n\t\t\t\t// Rejected execution/settlement, including local allowance exhaustion, never reaches recovery.\n\t\t\t\tif (!(await recover(settlement.message, options?.signal))) return settlement;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailure = error;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait release(failure === undefined ? [] : [failure]);\n\t\t}\n\t}\n\n\tcomplete(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<AssistantMessage> {\n\t\tlet completion!: Promise<AssistantMessage>;\n\t\tcompletion = (async () => {\n\t\t\tconst settlement = this.work.providerRecoveryPolicy?.().enabled\n\t\t\t\t? await this.completeWithProviderRecovery(model, context, options, request)\n\t\t\t\t: await (await this.start(model, context, options, request)).settled;\n\t\t\tconst binding = this.work.compactionSettlements.get(settlement);\n\t\t\tthis.work.compactionSettlements.delete(settlement);\n\t\t\tif (binding) this.work.compactionCompletions.set(completion, binding);\n\t\t\tconst branchBinding = this.work.branchSettlements.get(settlement);\n\t\t\tthis.work.branchSettlements.delete(settlement);\n\t\t\tif (branchBinding) this.work.branchCompletions.set(completion, branchBinding);\n\t\t\tconst plannerBinding = this.work.plannerSettlements.get(settlement);\n\t\t\tthis.work.plannerSettlements.delete(settlement);\n\t\t\tif (plannerBinding) this.work.plannerCompletions.set(completion, plannerBinding);\n\t\t\treturn settlement.message;\n\t\t})();\n\t\treturn completion;\n\t}\n\n\tbindAuxiliaryStream(streamFn: StreamFn, request: InferenceRequestOptions): DisposableInferenceStream {\n\t\tconst captured = this.capture();\n\t\tconst release = captured.retainWork(captured.capturedSink!);\n\t\tconst recover = captured.providerRecoveryWait();\n\t\tconst stream = captured.bindStream(streamFn, request);\n\t\tlet disposal: Promise<void> | undefined;\n\t\treturn Object.assign(stream, {\n\t\t\trecoverProviderFailure: async (message: AssistantMessage, signal?: AbortSignal) => {\n\t\t\t\tif (!(await recover(message, signal))) return false;\n\t\t\t\tcaptured.prepareTurnRetry();\n\t\t\t\treturn true;\n\t\t\t},\n\t\t\tdispose: () => {\n\t\t\t\tdisposal ??= (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait release();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tawait captured.dispose();\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\treturn disposal;\n\t\t\t},\n\t\t});\n\t}\n\n\tbindStream(streamFn: StreamFn, request: InferenceRequestOptions): AgentOwnedStreamFn {\n\t\tconst unwrapped = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\t\tconst inner = unwrapped[REQUEST_STREAM_BINDING]?.inner ?? unwrapped;\n\t\t// One Agent stream is serial. Keep only its latest binding for semantic retries.\n\t\t// A side question or child gets its own closure, not the parent's source binding.\n\t\tlet previous: BoundOperation | undefined;\n\t\tlet previousBody: string | undefined;\n\t\tconst wrapped: BoundStreamFn = async (model, context, options, streamContext) => {\n\t\t\tlet captured: InferenceCoordinator | undefined;\n\t\t\tif (streamContext !== undefined) {\n\t\t\t\tif (\n\t\t\t\t\t!(streamContext instanceof InferenceCoordinator) ||\n\t\t\t\t\tstreamContext.work !== this.work ||\n\t\t\t\t\t!streamContext.capturedSink\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Native stream context is not a capture of this inference owner\");\n\t\t\t\tcaptured = streamContext;\n\t\t\t}\n\t\t\tconst executor = captured ?? this;\n\t\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\t\t// Reuse the existing semantic body identity if its best-effort recorder is unavailable.\n\t\t\tconst body = semanticEdgeId ? undefined : hashTurnBody(model, context, options);\n\t\t\tconst retryId =\n\t\t\t\tthis.retryTurn && body !== undefined && body === previousBody ? previous?.metadata.operationId : undefined;\n\t\t\tthis.retryTurn = false;\n\t\t\tconst operationId = request.operationId ?? semanticEdgeId ?? retryId ?? randomUUID();\n\t\t\tpreviousBody = body;\n\t\t\tif (captured || previous?.metadata.operationId !== operationId) {\n\t\t\t\t// A semantic retry can reuse its operation ID, but compilation owns this exact source frontier.\n\t\t\t\tprevious = executor.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\t\t}\n\t\t\treturn (\n\t\t\t\tawait executor.execute(\n\t\t\t\t\tprevious,\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions,\n\t\t\t\t\tinner,\n\t\t\t\t\tcaptured !== undefined && request.purpose === \"main\",\n\t\t\t\t)\n\t\t\t).events;\n\t\t};\n\t\twrapped[REQUEST_STREAM_BINDING] = { coordinator: this, inner };\n\t\treturn wrapped;\n\t}\n}\n\n/** Standalone helper embedding stays optional; native session callers always supply requests. */\nexport function completeInference(\n\trequests: InferenceCoordinator | undefined,\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions | undefined,\n\trequest: InferenceRequestOptions,\n): Promise<AssistantMessage> {\n\treturn requests ? requests.complete(model, context, options, request) : completeSimple(model, context, options);\n}\n\nexport type DisposableInferenceStream = StreamFn & {\n\tdispose(): Promise<void>;\n\trecoverProviderFailure?(message: AssistantMessage, signal?: AbortSignal): Promise<boolean>;\n};\n\n/** Side questions keep the subject's writer, but get their own operation and purpose. */\nexport function bindAuxiliaryInferenceStream(\n\tstreamFn: StreamFn,\n\trequest: InferenceRequestOptions,\n): DisposableInferenceStream {\n\tconst inner = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\tconst binding = inner[REQUEST_STREAM_BINDING];\n\tif (binding) return binding.coordinator.bindAuxiliaryStream(binding.inner, request);\n\tconst stream: StreamFn = (model, context, options) => inner(model, context, options);\n\treturn Object.assign(stream, { dispose: async () => {} });\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bootstrap.d.ts","sourceRoot":"","sources":["../../../src/core/kernel/bootstrap.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAuB3D,eAAO,MAAM,yBAAyB,UAAqD,CAAC;AAC5F,eAAO,MAAM,8BAA8B,UAA0D,CAAC;AACtG,eAAO,MAAM,+BAA+B,UAA2D,CAAC;AAyBxG,MAAM,MAAM,iBAAiB,GAAG,sBAAsB,CAAC;AACvD,MAAM,MAAM,8BAA8B,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;AAEvE,MAAM,WAAW,yBAAyB;IACzC,YAAY,CAAC,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC5C,UAAU,CAAC,EAAE,8BAA8B,CAAC;CAC5C;AAwQD,wBAAgB,gBAAgB,IAAI,MAAM,CAGzC;AAgSD,wBAAgB,oBAAoB,IAAI,MAAM,EAAE,CAO/C;AAWD,wBAAsB,sBAAsB,IAAI,OAAO,CAAC,MAAM,CAAC,CAE9D;AAqOD,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,MAAM,CAAC,CAU3F;AAED,wFAAwF;AACxF,wBAAsB,wBAAwB,IAAI,OAAO,CAAC,MAAM,CAAC,CAmBhE","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { constants, existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { access, mkdir, readdir, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { stderr, stdin } from \"node:process\";\nimport { createInterface } from \"node:readline/promises\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { getPackageDir, getPhysicalPackageDir } from \"../../config.js\";\nimport { getOwnedInstallation, readInstallSelection } from \"../../owned-install-layout.js\";\nimport { PRODUCT, PRODUCT_ENV } from \"../../product-identity.js\";\nimport { assertProductStatePath, readAbsolutePathEnv, resolveRuntimePaths } from \"../../runtime-paths.js\";\nimport type { PythonSkillRuntimeInfo } from \"../skills.js\";\n\nconst ownedRuntime = getOwnedInstallation(getPhysicalPackageDir());\nconst BOOTSTRAP_SCHEMA = 11;\nconst PYTHON_VERSION = \"3.11\";\nconst RUNTIME_REQUIREMENT = PRODUCT.runtimeDistribution;\n// Serializes the kernel's user namespace so it can be revived across session\n// resume. Internal-only; intentionally not surfaced to the model as an import.\nconst STATE_SNAPSHOT_REQUIREMENT = \"dill\";\nconst DEFAULT_RLM_EXTRA_PACKAGES = [\n\t{ uvArg: \"requests\", importName: \"requests\", promptLabel: \"requests\" },\n\t{ uvArg: \"httpx\", importName: \"httpx\", promptLabel: \"httpx\" },\n\t{ uvArg: \"pyyaml\", importName: \"yaml\", promptLabel: \"yaml (PyYAML)\" },\n\t{ uvArg: \"tomli\", importName: \"tomli\", promptLabel: \"tomli\" },\n\t{ uvArg: \"python-dotenv\", importName: \"dotenv\", promptLabel: \"dotenv (python-dotenv)\" },\n\t{ uvArg: \"pandas\", importName: \"pandas\", promptLabel: \"pandas\" },\n\t{ uvArg: \"numpy\", importName: \"numpy\", promptLabel: \"numpy\" },\n\t{ uvArg: \"scipy\", importName: \"scipy\", promptLabel: \"scipy\" },\n\t{ uvArg: \"beautifulsoup4\", importName: \"bs4\", promptLabel: \"bs4 (Beautiful Soup)\" },\n\t{ uvArg: \"lxml\", importName: \"lxml\", promptLabel: \"lxml\" },\n\t{ uvArg: \"pydantic\", importName: \"pydantic\", promptLabel: \"pydantic\" },\n\t{ uvArg: \"tyro\", importName: \"tyro\", promptLabel: \"tyro\" },\n];\nexport const DEFAULT_RLM_EXTRA_UV_ARGS = DEFAULT_RLM_EXTRA_PACKAGES.map((pkg) => pkg.uvArg);\nexport const DEFAULT_RLM_EXTRA_IMPORT_NAMES = DEFAULT_RLM_EXTRA_PACKAGES.map((pkg) => pkg.importName);\nexport const DEFAULT_RLM_EXTRA_IMPORT_LABELS = DEFAULT_RLM_EXTRA_PACKAGES.map((pkg) => pkg.promptLabel);\nconst UV_INSTALL_COMMAND = \"curl -LsSf https://astral.sh/uv/install.sh | sh\";\nconst REQUIRED_HARNESS_METHODS = [\n\t\"create_memory\",\n\t\"update_memory\",\n\t\"delete_memory\",\n\t\"create_skill\",\n\t\"update_skill\",\n\t\"delete_skill\",\n\t\"create_subagent\",\n\t\"update_subagent\",\n\t\"delete_subagent\",\n\t\"create_prompt_note\",\n\t\"update_prompt_note\",\n\t\"delete_prompt_note\",\n\t\"record_refinement\",\n];\nconst RUNTIME_READY_CHECK = `import inspect; from importlib import metadata; import rlm; assert metadata.version(\"${RUNTIME_REQUIREMENT}\"); assert \"prime-agent-runtime\" not in {d.metadata[\"Name\"].lower().replace(\"_\", \"-\") for d in metadata.distributions()}; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ${JSON.stringify(REQUIRED_HARNESS_METHODS)}; assert callable(mcp.list_tools); assert callable(mcp.call_tool); assert hasattr(rlm, 'run'); assert callable(rlm); assert hasattr(rlm, 'rlm'); assert callable(rlm.rlm); assert callable(rlm.host_request); assert callable(rlm.find_models); assert callable(rlm.rlm.find_models); assert hasattr(rlm, 'harness'); assert hasattr(rlm, 'get_harness_state'); assert hasattr(rlm.rlm, 'harness'); assert hasattr(rlm.rlm, 'get_harness_state'); assert all(callable(getattr(_harness, _method, None)) for _harness in (rlm.harness, rlm.rlm.harness) for _method in _harness_methods); assert 'reference' in HarnessEntry.__dataclass_fields__; assert 'scope' in HarnessEntry.__dataclass_fields__; assert 'reference' in inspect.signature(rlm.harness.create_skill).parameters; assert 'reference' in inspect.signature(rlm.harness.update_skill).parameters; assert 'global_' in inspect.signature(rlm.harness.create_memory).parameters; assert 'global_' in inspect.signature(rlm.get_harness_state).parameters; assert not hasattr(rlm, 'background'); assert not hasattr(rlm.rlm, 'background'); from rlm.bash import BashHandle, BashResult; assert callable(rlm.bash); assert all(callable(getattr(BashHandle, _m, None)) for _m in ('tail', 'output', 'poll', 'kill')); assert {'exit_code', 'output', 'duration'} <= set(BashResult.__dataclass_fields__); import rlm.repl as _repl; assert callable(_repl.main); assert callable(_repl.emit); assert callable(_repl.host_request); assert callable(_repl.is_active); assert _repl.PROTOCOL_VERSION == 4; assert callable(rlm.emit); assert not hasattr(rlm, 'HOST_COMM_TARGET'); assert not hasattr(mcp, 'install_shutdown_hook')`;\nconst BOOTSTRAP_VERSION_FILE = \".bootstrap-version\";\nconst BOOTSTRAP_LOCK_NAME = \".bootstrap.lock\";\nconst BOOTSTRAP_LOCK_RETRY_MS = 100;\nconst BOOTSTRAP_LOCK_STALE_WITHOUT_PID_MS = 30_000;\n\nlet inFlightEnsureKernelPython: { key: string; promise: Promise<string> } | null = null;\n\nexport type KernelPythonSkill = PythonSkillRuntimeInfo;\nexport type KernelBootstrapProgressHandler = (message: string) => void;\n\nexport interface EnsureKernelPythonOptions {\n\tpythonSkills?: readonly KernelPythonSkill[];\n\tonProgress?: KernelBootstrapProgressHandler;\n}\n\ninterface BootstrapPythonSkill {\n\timportName: string;\n\tpackagePath: string;\n\tpyprojectPath: string;\n\tpyprojectHash: string;\n}\n\ninterface BootstrapVersion {\n\tschema: number;\n\truntime?: string;\n\tsnapshot?: string;\n\textraUvArgs?: string[];\n\tpythonSkills?: BootstrapPythonSkill[];\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction isNodeError(error: unknown, code: string): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === code;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nasync function exists(filePath: string): Promise<boolean> {\n\ttry {\n\t\tawait access(filePath);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nasync function isExecutable(filePath: string): Promise<boolean> {\n\ttry {\n\t\tawait access(filePath, constants.X_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction fileContentHash(filePath: string): string {\n\ttry {\n\t\treturn `sha256:${createHash(\"sha256\").update(readFileSync(filePath)).digest(\"hex\")}`;\n\t} catch {\n\t\treturn \"unreadable\";\n\t}\n}\n\nfunction normalizePythonSkills(pythonSkills: readonly KernelPythonSkill[] | undefined): BootstrapPythonSkill[] {\n\tconst byKey = new Map<string, BootstrapPythonSkill>();\n\tconst addSkill = (skill: Pick<KernelPythonSkill, \"importName\" | \"packagePath\" | \"pyprojectPath\">): void => {\n\t\tconst packagePath = path.resolve(skill.packagePath);\n\t\tconst pyprojectPath = path.resolve(skill.pyprojectPath);\n\t\tconst key = `${skill.importName}\\0${packagePath}`;\n\t\tif (byKey.has(key)) {\n\t\t\treturn;\n\t\t}\n\t\tconst bootstrapSkill: BootstrapPythonSkill = {\n\t\t\timportName: skill.importName,\n\t\t\tpackagePath,\n\t\t\tpyprojectPath,\n\t\t\tpyprojectHash: fileContentHash(pyprojectPath),\n\t\t};\n\t\tbyKey.set(key, bootstrapSkill);\n\t\tfor (const dependencyName of readPythonSkillDependencyNames(bootstrapSkill)) {\n\t\t\tconst siblingDependency = resolveSiblingPythonSkillDependency(bootstrapSkill, dependencyName);\n\t\t\tif (siblingDependency) {\n\t\t\t\taddSkill(siblingDependency);\n\t\t\t}\n\t\t}\n\t};\n\tfor (const skill of pythonSkills ?? []) {\n\t\taddSkill(skill);\n\t}\n\treturn [...byKey.values()].sort((a, b) => {\n\t\tconst packageCompare = a.packagePath.localeCompare(b.packagePath);\n\t\tif (packageCompare !== 0) return packageCompare;\n\t\treturn a.importName.localeCompare(b.importName);\n\t});\n}\n\nfunction readTomlProjectSection(pyprojectPath: string): string | undefined {\n\ttry {\n\t\tconst text = readFileSync(pyprojectPath, \"utf-8\");\n\t\tconst match = text.match(/^\\s*\\[project\\]\\s*$/m);\n\t\tif (!match || match.index === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst sectionStart = match.index + match[0].length;\n\t\tconst rest = text.slice(sectionStart);\n\t\tconst nextSection = rest.search(/^\\s*\\[/m);\n\t\treturn nextSection >= 0 ? rest.slice(0, nextSection) : rest;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction readPythonSkillProjectName(skill: BootstrapPythonSkill): string {\n\tconst projectSection = readTomlProjectSection(skill.pyprojectPath);\n\tconst name = projectSection?.match(/^\\s*name\\s*=\\s*[\"']([^\"']+)[\"']/m)?.[1];\n\treturn name?.trim() || skill.importName.replaceAll(\"_\", \"-\");\n}\n\nfunction parseDependencyPackageName(dependency: string): string | undefined {\n\tconst withoutMarker = dependency.split(\";\")[0]?.trim() ?? \"\";\n\tif (!withoutMarker) {\n\t\treturn undefined;\n\t}\n\tconst match = withoutMarker.match(/^([A-Za-z0-9_.-]+)/);\n\treturn match?.[1]?.replaceAll(\"_\", \"-\").toLowerCase();\n}\n\nfunction findTomlArrayEnd(text: string, startIndex: number): number {\n\tlet inQuote: '\"' | \"'\" | undefined;\n\tlet escaped = false;\n\tfor (let index = startIndex; index < text.length; index++) {\n\t\tconst char = text[index];\n\t\tif (inQuote) {\n\t\t\tif (escaped) {\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === \"\\\\\") {\n\t\t\t\tescaped = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === inQuote) {\n\t\t\t\tinQuote = undefined;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"' || char === \"'\") {\n\t\t\tinQuote = char;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"]\") {\n\t\t\treturn index;\n\t\t}\n\t}\n\treturn -1;\n}\n\nfunction readPythonSkillDependencyNames(skill: BootstrapPythonSkill): Set<string> {\n\tconst projectSection = readTomlProjectSection(skill.pyprojectPath);\n\tif (!projectSection) {\n\t\treturn new Set();\n\t}\n\tconst dependenciesStart = projectSection.search(/^\\s*dependencies\\s*=\\s*\\[/m);\n\tif (dependenciesStart < 0) {\n\t\treturn new Set();\n\t}\n\tconst arrayStart = projectSection.indexOf(\"[\", dependenciesStart);\n\tif (arrayStart < 0) {\n\t\treturn new Set();\n\t}\n\tconst arrayEnd = findTomlArrayEnd(projectSection, arrayStart + 1);\n\tif (arrayEnd < 0) {\n\t\treturn new Set();\n\t}\n\tconst dependenciesArray = projectSection.slice(arrayStart, arrayEnd + 1);\n\tconst dependencies = new Set<string>();\n\tconst dependencyPattern = /\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"|'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'/g;\n\tfor (const match of dependenciesArray.matchAll(dependencyPattern)) {\n\t\tconst dependency = (match[1] ?? match[2] ?? \"\").replaceAll('\\\\\"', '\"').replaceAll(\"\\\\'\", \"'\");\n\t\tconst name = parseDependencyPackageName(dependency);\n\t\tif (name) {\n\t\t\tdependencies.add(name);\n\t\t}\n\t}\n\treturn dependencies;\n}\n\nfunction resolveSiblingPythonSkillDependency(\n\tskill: BootstrapPythonSkill,\n\tdependencyName: string,\n): BootstrapPythonSkill | undefined {\n\tconst siblingsDir = path.dirname(skill.packagePath);\n\tfor (const entry of readdirSync(siblingsDir, { withFileTypes: true })) {\n\t\tif (!entry.isDirectory()) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst packagePath = path.join(siblingsDir, entry.name);\n\t\tconst pyprojectPath = path.join(packagePath, \"pyproject.toml\");\n\t\tif (!existsSync(pyprojectPath)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst dependency: BootstrapPythonSkill = {\n\t\t\timportName: entry.name.replaceAll(\"-\", \"_\"),\n\t\t\tpackagePath,\n\t\t\tpyprojectPath,\n\t\t\tpyprojectHash: fileContentHash(pyprojectPath),\n\t\t};\n\t\tif (readPythonSkillProjectName(dependency).replaceAll(\"_\", \"-\").toLowerCase() === dependencyName) {\n\t\t\treturn dependency;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction sortPythonSkillsForInstall(pythonSkills: readonly BootstrapPythonSkill[]): BootstrapPythonSkill[] {\n\tconst byProjectName = new Map<string, BootstrapPythonSkill>();\n\tconst originalIndex = new Map<BootstrapPythonSkill, number>();\n\tfor (const [index, skill] of pythonSkills.entries()) {\n\t\toriginalIndex.set(skill, index);\n\t\tbyProjectName.set(readPythonSkillProjectName(skill).replaceAll(\"_\", \"-\").toLowerCase(), skill);\n\t}\n\n\tconst dependenciesBySkill = new Map<BootstrapPythonSkill, BootstrapPythonSkill[]>();\n\tfor (const skill of pythonSkills) {\n\t\tdependenciesBySkill.set(\n\t\t\tskill,\n\t\t\t[...readPythonSkillDependencyNames(skill)]\n\t\t\t\t.map(\n\t\t\t\t\t(dependencyName) =>\n\t\t\t\t\t\tbyProjectName.get(dependencyName) ?? resolveSiblingPythonSkillDependency(skill, dependencyName),\n\t\t\t\t)\n\t\t\t\t.filter((dependency): dependency is BootstrapPythonSkill => Boolean(dependency)),\n\t\t);\n\t}\n\n\tconst pending = new Set(pythonSkills);\n\tconst sorted: BootstrapPythonSkill[] = [];\n\twhile (pending.size > 0) {\n\t\tlet progressed = false;\n\t\tfor (const skill of [...pending].sort((a, b) => (originalIndex.get(a) ?? 0) - (originalIndex.get(b) ?? 0))) {\n\t\t\tconst dependencies = dependenciesBySkill.get(skill) ?? [];\n\t\t\tif (dependencies.some((dependency) => pending.has(dependency))) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsorted.push(skill);\n\t\t\tpending.delete(skill);\n\t\t\tprogressed = true;\n\t\t}\n\t\tif (!progressed) {\n\t\t\t// Cyclic local skill dependencies cannot be topologically ordered; keep a\n\t\t\t// deterministic order and let uv surface the packaging error if needed.\n\t\t\tsorted.push(...[...pending].sort((a, b) => a.packagePath.localeCompare(b.packagePath)));\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn sorted;\n}\n\nfunction formatPythonSkillInstallArgs(skill: BootstrapPythonSkill): string[] {\n\treturn [\"--editable\", skill.packagePath];\n}\n\nfunction ensureKernelPythonKey(pythonSkills: readonly BootstrapPythonSkill[]): string {\n\treturn [\n\t\tprocess.env[PRODUCT_ENV.kernelPython] ?? \"\",\n\t\tprocess.env[PRODUCT_ENV.kernelVenv] ?? \"\",\n\t\tprocess.env.HOME ?? \"\",\n\t\tprocess.env[PRODUCT_ENV.home] ?? \"\",\n\t\tJSON.stringify(pythonSkills),\n\t].join(\"\\0\");\n}\n\nexport function getKernelVenvDir(): string {\n\tconst override = readAbsolutePathEnv(PRODUCT_ENV.kernelVenv);\n\treturn assertProductStatePath(override ?? ownedRuntime?.runtimeDir ?? resolveRuntimePaths().runtime);\n}\n\nasync function resolveWritableKernelVenvDir(): Promise<string> {\n\tconst venv = getKernelVenvDir();\n\tawait mkdir(path.dirname(venv), { recursive: true });\n\treturn venv;\n}\n\nfunction run(command: string, args: string[], options: { stdio?: \"ignore\" | \"inherit\" } = {}): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tenv: process.env,\n\t\t\tstdio: options.stdio ?? \"ignore\",\n\t\t});\n\t\tchild.on(\"error\", reject);\n\t\tchild.on(\"exit\", (code, signal) => {\n\t\t\tif (code === 0) {\n\t\t\t\tresolve();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst reason = signal ? `signal ${signal}` : `exit code ${code}`;\n\t\t\treject(new Error(`${command} ${args.join(\" \")} failed with ${reason}`));\n\t\t});\n\t});\n}\n\nasync function pythonImports(python: string, moduleName: string): Promise<boolean> {\n\ttry {\n\t\tawait run(python, [\"-c\", `import ${moduleName}`], { stdio: \"ignore\" });\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nasync function hasBaseContextRuntime(python: string): Promise<boolean> {\n\ttry {\n\t\tawait run(python, [\"-c\", RUNTIME_READY_CHECK], { stdio: \"ignore\" });\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nasync function missingRlmExtraImportLabels(python: string): Promise<string[]> {\n\tconst missing: string[] = [];\n\tfor (const pkg of DEFAULT_RLM_EXTRA_PACKAGES) {\n\t\tif (!(await pythonImports(python, pkg.importName))) {\n\t\t\tmissing.push(pkg.promptLabel);\n\t\t}\n\t}\n\treturn missing;\n}\n\nasync function missingPythonSkillImportLabels(\n\tpython: string,\n\tpythonSkills: readonly KernelPythonSkill[],\n): Promise<string[]> {\n\tconst missing: string[] = [];\n\tfor (const skill of pythonSkills) {\n\t\tif (!(await pythonImports(python, skill.importName))) {\n\t\t\tmissing.push(`${skill.name} (${skill.importName})`);\n\t\t}\n\t}\n\treturn missing;\n}\n\nfunction reportProgress(options: EnsureKernelPythonOptions, message: string): void {\n\tif (options.onProgress) {\n\t\toptions.onProgress(message);\n\t\treturn;\n\t}\n\tprocess.stderr.write(`${message}\\n`);\n}\n\nfunction bootstrapLockDir(venv: string): string {\n\treturn path.join(path.dirname(venv), `${path.basename(venv)}${BOOTSTRAP_LOCK_NAME}`);\n}\n\nfunction processIsRunning(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn isNodeError(error, \"EPERM\");\n\t}\n}\n\nasync function readLockPid(lockDir: string): Promise<number | null> {\n\ttry {\n\t\tconst raw = await readFile(path.join(lockDir, \"pid\"), \"utf8\");\n\t\tconst pid = Number.parseInt(raw.trim(), 10);\n\t\treturn Number.isInteger(pid) && pid > 0 ? pid : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function lockMissingPidIsStale(lockDir: string): Promise<boolean> {\n\ttry {\n\t\tconst lockStat = await stat(lockDir);\n\t\treturn Date.now() - lockStat.mtimeMs > BOOTSTRAP_LOCK_STALE_WITHOUT_PID_MS;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nasync function acquireBootstrapLock(venv: string): Promise<() => Promise<void>> {\n\tconst lockDir = bootstrapLockDir(venv);\n\tawait mkdir(path.dirname(lockDir), { recursive: true });\n\n\tfor (;;) {\n\t\ttry {\n\t\t\tawait mkdir(lockDir);\n\t\t\tawait writeFile(path.join(lockDir, \"pid\"), `${process.pid}\\n`, \"utf8\");\n\t\t\treturn () => rm(lockDir, { recursive: true, force: true });\n\t\t} catch (error) {\n\t\t\tif (!isNodeError(error, \"EEXIST\")) throw error;\n\n\t\t\tconst pid = await readLockPid(lockDir);\n\t\t\tif (pid === null ? await lockMissingPidIsStale(lockDir) : !processIsRunning(pid)) {\n\t\t\t\tawait rm(lockDir, { recursive: true, force: true });\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tawait sleep(BOOTSTRAP_LOCK_RETRY_MS);\n\t\t}\n\t}\n}\n\nasync function findExecutable(name: string): Promise<string | null> {\n\tconst pathValue = process.env.PATH;\n\tif (!pathValue) return null;\n\tconst candidates = process.platform === \"win32\" ? [name, `${name}.exe`] : [name];\n\tfor (const dir of pathValue.split(path.delimiter)) {\n\t\tif (!dir) continue;\n\t\tfor (const candidate of candidates) {\n\t\t\tconst fullPath = path.join(dir, candidate);\n\t\t\tif (await isExecutable(fullPath)) return fullPath;\n\t\t}\n\t}\n\treturn null;\n}\n\nasync function ensureUv(options: EnsureKernelPythonOptions): Promise<string> {\n\tconst fromPath = await findExecutable(\"uv\");\n\tif (fromPath) return fromPath;\n\n\tconst localUv = path.join(os.homedir(), \".local\", \"bin\", process.platform === \"win32\" ? \"uv.exe\" : \"uv\");\n\tif (await isExecutable(localUv)) return localUv;\n\n\tconst shouldInstallUv =\n\t\tprocess.env[PRODUCT_ENV.installUv] === \"1\" || (!options.onProgress && (await confirmUvInstall()));\n\tif (!shouldInstallUv) {\n\t\tthrow new Error(\n\t\t\t`uv is required to set up the Python kernel. Install uv yourself: ${UV_INSTALL_COMMAND}, ` +\n\t\t\t\t\"or set BASE_CONTEXT_INSTALL_UV=1 to let base-context run that installer.\",\n\t\t);\n\t}\n\n\treportProgress(options, \"› installing uv (one-time)…\");\n\ttry {\n\t\tawait run(\"sh\", [\"-c\", UV_INSTALL_COMMAND], { stdio: options.onProgress ? \"ignore\" : \"inherit\" });\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`couldn't install uv from astral.sh; install it yourself: ${UV_INSTALL_COMMAND}, then re-run base-context. ${errorMessage(error)}`,\n\t\t);\n\t}\n\n\tif (await isExecutable(localUv)) return localUv;\n\tconst installedFromPath = await findExecutable(\"uv\");\n\tif (installedFromPath) return installedFromPath;\n\tthrow new Error(\"uv install completed but binary not found at ~/.local/bin/uv\");\n}\n\nasync function confirmUvInstall(): Promise<boolean> {\n\tif (process.env[PRODUCT_ENV.installUv] === \"0\") return false;\n\tif (!stdin.isTTY || !stderr.isTTY) return false;\n\n\tconst rl = createInterface({ input: stdin, output: stderr });\n\ttry {\n\t\tconst answer = (\n\t\t\tawait rl.question(\"Base Context needs uv to set up Python. Install uv from astral.sh now? [Y/n] \")\n\t\t)\n\t\t\t.trim()\n\t\t\t.toLowerCase();\n\t\treturn answer !== \"n\" && answer !== \"no\";\n\t} finally {\n\t\trl.close();\n\t}\n}\n\nasync function readBootstrapVersion(venv: string): Promise<BootstrapVersion | null> {\n\ttry {\n\t\tconst raw = await readFile(path.join(venv, BOOTSTRAP_VERSION_FILE), \"utf8\");\n\t\tconst parsed: unknown = JSON.parse(raw);\n\t\tif (!isRecord(parsed) || typeof parsed.schema !== \"number\") return null;\n\t\tconst extraUvArgs =\n\t\t\tArray.isArray(parsed.extraUvArgs) &&\n\t\t\tparsed.extraUvArgs.every((v: unknown): v is string => typeof v === \"string\")\n\t\t\t\t? (parsed.extraUvArgs as string[])\n\t\t\t\t: undefined;\n\t\tlet pythonSkills: BootstrapPythonSkill[] | undefined;\n\t\tif (Array.isArray(parsed.pythonSkills)) {\n\t\t\tif (\n\t\t\t\t!parsed.pythonSkills.every((v: unknown): v is BootstrapPythonSkill => {\n\t\t\t\t\tif (!isRecord(v)) return false;\n\t\t\t\t\treturn (\n\t\t\t\t\t\ttypeof v.importName === \"string\" &&\n\t\t\t\t\t\ttypeof v.packagePath === \"string\" &&\n\t\t\t\t\t\ttypeof v.pyprojectPath === \"string\" &&\n\t\t\t\t\t\ttypeof v.pyprojectHash === \"string\"\n\t\t\t\t\t);\n\t\t\t\t})\n\t\t\t) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tpythonSkills = parsed.pythonSkills as BootstrapPythonSkill[];\n\t\t}\n\t\treturn {\n\t\t\tschema: parsed.schema,\n\t\t\truntime: typeof parsed.runtime === \"string\" ? parsed.runtime : undefined,\n\t\t\tsnapshot: typeof parsed.snapshot === \"string\" ? parsed.snapshot : undefined,\n\t\t\textraUvArgs,\n\t\t\tpythonSkills,\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction extraUvArgsMatch(a: string[] | undefined, b: string[] | undefined): boolean {\n\tif (a === b) return true;\n\tif (!a || !b) return false;\n\tif (a.length !== b.length) return false;\n\treturn a.every((v, i) => v === b[i]);\n}\n\nfunction pythonSkillsMatch(a: BootstrapPythonSkill[] | undefined, b: readonly BootstrapPythonSkill[]): boolean {\n\tconst left = a ?? [];\n\tif (left.length !== b.length) return false;\n\treturn left.every((skill, index) => {\n\t\tconst expected = b[index];\n\t\treturn (\n\t\t\tskill.importName === expected.importName &&\n\t\t\tskill.packagePath === expected.packagePath &&\n\t\t\tskill.pyprojectPath === expected.pyprojectPath &&\n\t\t\tskill.pyprojectHash === expected.pyprojectHash\n\t\t);\n\t});\n}\n\nfunction bootstrapVersionCurrent(\n\tversion: BootstrapVersion | null,\n\truntimeIdentity: string,\n\tpythonSkills: readonly BootstrapPythonSkill[],\n): boolean {\n\treturn (\n\t\tversion !== null &&\n\t\tbootstrapBaseVersionCurrent(version, runtimeIdentity) &&\n\t\tpythonSkillsMatch(version.pythonSkills, pythonSkills)\n\t);\n}\n\nfunction bootstrapBaseVersionCurrent(version: BootstrapVersion | null, runtimeIdentity: string): boolean {\n\treturn (\n\t\tversion?.schema === BOOTSTRAP_SCHEMA &&\n\t\tversion.runtime === runtimeIdentity &&\n\t\tversion.snapshot === STATE_SNAPSHOT_REQUIREMENT &&\n\t\textraUvArgsMatch(version.extraUvArgs, DEFAULT_RLM_EXTRA_UV_ARGS)\n\t);\n}\n\nasync function writeBootstrapVersion(\n\tvenv: string,\n\truntimeIdentity: string,\n\tpythonSkills: readonly BootstrapPythonSkill[],\n): Promise<void> {\n\tconst version: BootstrapVersion = {\n\t\tschema: BOOTSTRAP_SCHEMA,\n\t\truntime: runtimeIdentity,\n\t\tsnapshot: STATE_SNAPSHOT_REQUIREMENT,\n\t\textraUvArgs: DEFAULT_RLM_EXTRA_UV_ARGS,\n\t\tpythonSkills: [...pythonSkills],\n\t};\n\tawait writeFile(path.join(venv, BOOTSTRAP_VERSION_FILE), `${JSON.stringify(version)}\\n`, \"utf8\");\n}\n\nexport function runtimeCandidateDirs(): string[] {\n\tif (ownedRuntime) return [path.join(ownedRuntime.packageDir, \"dist\", RUNTIME_REQUIREMENT)];\n\tconst packageDir = getPackageDir();\n\tif (existsSync(path.join(packageDir, \"src\"))) {\n\t\treturn [path.resolve(packageDir, \"..\", \"..\", \"prime-agent-runtime\")];\n\t}\n\treturn [path.join(packageDir, \"dist\", RUNTIME_REQUIREMENT), path.join(packageDir, RUNTIME_REQUIREMENT)];\n}\n\nasync function resolveRuntimeSourceDir(): Promise<string> {\n\tfor (const candidate of runtimeCandidateDirs()) {\n\t\tif (await exists(path.join(candidate, \"pyproject.toml\"))) return candidate;\n\t}\n\tthrow new Error(\n\t\t\"Base Context runtime payload is missing. Reinstall this Base Context release; registry runtime fallback is disabled.\",\n\t);\n}\n\nexport async function resolveRuntimeIdentity(): Promise<string> {\n\treturn hashRuntimeSource(await resolveRuntimeSourceDir());\n}\n\n// A source read failure must not be replaced by a registry runtime.\nasync function hashRuntimeSource(sourceDir: string): Promise<string> {\n\tconst rlmDir = path.join(sourceDir, \"src\", \"rlm\");\n\tconst files: string[] = [path.join(sourceDir, \"pyproject.toml\")];\n\tasync function collect(dir: string): Promise<void> {\n\t\tconst entries = await readdir(dir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst full = path.join(dir, entry.name);\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tawait collect(full);\n\t\t\t} else if (entry.isFile() && entry.name.endsWith(\".py\")) {\n\t\t\t\tfiles.push(full);\n\t\t\t}\n\t\t}\n\t}\n\tawait collect(rlmDir);\n\tfiles.sort();\n\tconst hash = createHash(\"sha256\");\n\tfor (const file of files) {\n\t\thash.update(path.relative(sourceDir, file));\n\t\thash.update(\"\\0\");\n\t\thash.update(await readFile(file));\n\t\thash.update(\"\\0\");\n\t}\n\treturn `sha256:${hash.digest(\"hex\")}`;\n}\n\nasync function bootstrapVenv(\n\tvenv: string,\n\tpythonSkills: readonly BootstrapPythonSkill[],\n\toptions: EnsureKernelPythonOptions,\n): Promise<void> {\n\tawait mkdir(path.dirname(venv), { recursive: true });\n\tconst uv = await ensureUv(options);\n\tconst python = path.join(venv, \"bin\", \"python\");\n\tconst sourceDir = await resolveRuntimeSourceDir();\n\tconst runtimeRequirement = sourceDir;\n\tconst runtimeIdentity = await resolveRuntimeIdentity();\n\n\tawait run(uv, [\"python\", \"install\", PYTHON_VERSION]);\n\tawait run(uv, [\"venv\", venv, \"--python\", PYTHON_VERSION, \"--seed\"]);\n\tawait run(uv, [\n\t\t\"pip\",\n\t\t\"install\",\n\t\t\"--python\",\n\t\tpython,\n\t\truntimeRequirement,\n\t\tSTATE_SNAPSHOT_REQUIREMENT,\n\t\t...DEFAULT_RLM_EXTRA_UV_ARGS,\n\t]);\n\tawait syncPythonSkills(uv, venv, python, runtimeIdentity, pythonSkills, options);\n}\n\nasync function syncPythonSkills(\n\tuv: string,\n\tvenv: string,\n\tpython: string,\n\truntimeIdentity: string,\n\tpythonSkills: readonly BootstrapPythonSkill[],\n\toptions: EnsureKernelPythonOptions,\n): Promise<void> {\n\tconst version = await readBootstrapVersion(venv);\n\tconst installedPythonSkills: BootstrapPythonSkill[] = [];\n\tconst currentPythonSkills = new Map(\n\t\t(version?.pythonSkills ?? []).map((skill) => [`${skill.importName}\\0${skill.packagePath}`, skill]),\n\t);\n\tconst pythonSkillsByProjectName = new Map(\n\t\tpythonSkills.map((skill) => [readPythonSkillProjectName(skill).replaceAll(\"_\", \"-\").toLowerCase(), skill]),\n\t);\n\tconst dependenciesBySkill = new Map(\n\t\tpythonSkills.map((skill) => [\n\t\t\tskill,\n\t\t\t[...readPythonSkillDependencyNames(skill)]\n\t\t\t\t.map(\n\t\t\t\t\t(dependencyName) =>\n\t\t\t\t\t\tpythonSkillsByProjectName.get(dependencyName) ??\n\t\t\t\t\t\tresolveSiblingPythonSkillDependency(skill, dependencyName),\n\t\t\t\t)\n\t\t\t\t.filter((dependency): dependency is BootstrapPythonSkill => Boolean(dependency)),\n\t\t]),\n\t);\n\n\tfor (const skill of sortPythonSkillsForInstall(pythonSkills)) {\n\t\tconst existingSkill = currentPythonSkills.get(`${skill.importName}\\0${skill.packagePath}`);\n\t\tif (existingSkill?.pyprojectPath === skill.pyprojectPath && existingSkill.pyprojectHash === skill.pyprojectHash) {\n\t\t\tinstalledPythonSkills.push(skill);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst localDependencies = dependenciesBySkill.get(skill) ?? [];\n\t\tconst localDependencyArgs = localDependencies\n\t\t\t.filter((dependency) => {\n\t\t\t\tconst installedDependency = currentPythonSkills.get(`${dependency.importName}\\0${dependency.packagePath}`);\n\t\t\t\tconst installedThisSync = installedPythonSkills.some(\n\t\t\t\t\t(installed) =>\n\t\t\t\t\t\tinstalled.importName === dependency.importName &&\n\t\t\t\t\t\tinstalled.packagePath === dependency.packagePath &&\n\t\t\t\t\t\tinstalled.pyprojectPath === dependency.pyprojectPath &&\n\t\t\t\t\t\tinstalled.pyprojectHash === dependency.pyprojectHash,\n\t\t\t\t);\n\t\t\t\treturn !(\n\t\t\t\t\tinstalledThisSync ||\n\t\t\t\t\t(installedDependency?.pyprojectPath === dependency.pyprojectPath &&\n\t\t\t\t\t\tinstalledDependency.pyprojectHash === dependency.pyprojectHash)\n\t\t\t\t);\n\t\t\t})\n\t\t\t.flatMap(formatPythonSkillInstallArgs);\n\n\t\ttry {\n\t\t\tawait run(uv, [\n\t\t\t\t\"pip\",\n\t\t\t\t\"install\",\n\t\t\t\t\"--python\",\n\t\t\t\tpython,\n\t\t\t\t...formatPythonSkillInstallArgs(skill),\n\t\t\t\t...localDependencyArgs,\n\t\t\t]);\n\t\t\tinstalledPythonSkills.push(\n\t\t\t\tskill,\n\t\t\t\t...localDependencies.filter((dependency) => !installedPythonSkills.includes(dependency)),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\treportProgress(\n\t\t\t\toptions,\n\t\t\t\t`Warning: Python skill ${skill.importName} failed to install and will be unavailable: ${errorMessage(error)}`,\n\t\t\t);\n\t\t}\n\t}\n\tawait writeBootstrapVersion(venv, runtimeIdentity, installedPythonSkills);\n}\n\nasync function kernelBaseReady(python: string, venv: string, runtimeIdentity: string): Promise<boolean> {\n\treturn (\n\t\t(await hasBaseContextRuntime(python)) &&\n\t\tbootstrapBaseVersionCurrent(await readBootstrapVersion(venv), runtimeIdentity)\n\t);\n}\n\nasync function kernelReady(\n\tpython: string,\n\tvenv: string,\n\truntimeIdentity: string,\n\tpythonSkills: readonly BootstrapPythonSkill[],\n): Promise<boolean> {\n\treturn (\n\t\t(await hasBaseContextRuntime(python)) &&\n\t\tbootstrapVersionCurrent(await readBootstrapVersion(venv), runtimeIdentity, pythonSkills)\n\t);\n}\n\nfunction formatBootstrapFailure(error: unknown): Error {\n\treturn new Error(\n\t\t`Failed to set up the Python kernel runtime. ${errorMessage(error)}\\n` +\n\t\t\t\"First-time setup needs internet to install uv, Python, the bundled base-context-runtime, and default Python packages; once set up, base-context runs offline. \" +\n\t\t\t\"Set BASE_CONTEXT_KERNEL_PYTHON to a Python with a current base-context-runtime and default Python packages installed to skip auto-bootstrap.\",\n\t);\n}\n\nasync function ensureKernelPythonUncached(\n\toptions: EnsureKernelPythonOptions,\n\tpythonSkills: readonly BootstrapPythonSkill[],\n): Promise<string> {\n\tconst override = readAbsolutePathEnv(PRODUCT_ENV.kernelPython);\n\tif (override) {\n\t\tconst python = override;\n\t\tconst missing: string[] = [];\n\t\tif (!(await hasBaseContextRuntime(python))) {\n\t\t\tmissing.push(\n\t\t\t\t\"a current base-context-runtime with callable rlm.run, rlm.host_request, and explicit harness CRUD methods\",\n\t\t\t);\n\t\t}\n\t\tif (missing.length === 0) {\n\t\t\tconst missingExtraImports = await missingRlmExtraImportLabels(python);\n\t\t\tif (missingExtraImports.length > 0) {\n\t\t\t\tmissing.push(`default Python packages (${missingExtraImports.join(\", \")})`);\n\t\t\t}\n\t\t}\n\t\tif (missing.length === 0 && pythonSkills.length > 0) {\n\t\t\tconst missingPythonSkills = await missingPythonSkillImportLabels(python, options.pythonSkills ?? []);\n\t\t\tif (missingPythonSkills.length > 0) {\n\t\t\t\treportProgress(\n\t\t\t\t\toptions,\n\t\t\t\t\t`Warning: Python skills unavailable in BASE_CONTEXT_KERNEL_PYTHON and will be disabled: ${missingPythonSkills.join(\", \")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (missing.length === 0) return python;\n\t\tthrow new Error(`BASE_CONTEXT_KERNEL_PYTHON points to a Python missing ${missing.join(\" and \")}: ${python}`);\n\t}\n\n\tconst venv = await resolveWritableKernelVenvDir();\n\tconst python = path.join(venv, \"bin\", \"python\");\n\tconst runtimeIdentity = await resolveRuntimeIdentity();\n\tif (await kernelReady(python, venv, runtimeIdentity, pythonSkills)) return python;\n\n\tconst releaseLock = await acquireBootstrapLock(venv);\n\ttry {\n\t\tif (await kernelReady(python, venv, runtimeIdentity, pythonSkills)) return python;\n\t\tif (await kernelBaseReady(python, venv, runtimeIdentity)) {\n\t\t\tawait syncPythonSkills(await ensureUv(options), venv, python, runtimeIdentity, pythonSkills, options);\n\t\t\treturn python;\n\t\t}\n\n\t\tif (ownedRuntime && !readAbsolutePathEnv(PRODUCT_ENV.kernelVenv)) {\n\t\t\tthrow new Error(\n\t\t\t\t\"The selected Base-Context default runtime is unavailable or stale. Install a prepared candidate or explicitly roll back; the retained runtime was not rebuilt.\",\n\t\t\t);\n\t\t}\n\n\t\tconst hadVenv = existsSync(venv);\n\t\treportProgress(options, \"› setting up python kernel (one-time, ~30s)…\");\n\t\tif (hadVenv) {\n\t\t\treportProgress(options, \"rebuilding kernel venv\");\n\t\t\tawait rm(venv, { recursive: true, force: true });\n\t\t}\n\n\t\tawait bootstrapVenv(venv, pythonSkills, options);\n\t} catch (error) {\n\t\tthrow formatBootstrapFailure(error);\n\t} finally {\n\t\tawait releaseLock().catch(() => undefined);\n\t}\n\n\treportProgress(options, \"✓ ready\");\n\treturn python;\n}\n\nexport function ensureKernelPython(options: EnsureKernelPythonOptions = {}): Promise<string> {\n\tconst pythonSkills = normalizePythonSkills(options.pythonSkills);\n\tconst key = ensureKernelPythonKey(pythonSkills);\n\tif (inFlightEnsureKernelPython?.key === key) return inFlightEnsureKernelPython.promise;\n\n\tconst promise = ensureKernelPythonUncached(options, pythonSkills).finally(() => {\n\t\tif (inFlightEnsureKernelPython?.promise === promise) inFlightEnsureKernelPython = null;\n\t});\n\tinFlightEnsureKernelPython = { key, promise };\n\treturn promise;\n}\n\n/** Prepare only a new physical owned release, before its selection can be published. */\nexport async function prepareOwnedKernelPython(): Promise<string> {\n\tif (!ownedRuntime || existsSync(ownedRuntime.runtimeDir)) {\n\t\tthrow new Error(\"Base-Context runtime preparation requires a new, empty owned release runtime directory.\");\n\t}\n\tconst selected = readInstallSelection(ownedRuntime.root);\n\tif (selected?.active === ownedRuntime.version || selected?.previous === ownedRuntime.version) {\n\t\tthrow new Error(\"Base-Context will not prepare a published release in place. Install a new candidate instead.\");\n\t}\n\tconst python = path.join(ownedRuntime.runtimeDir, \"bin\", \"python\");\n\tconst options: EnsureKernelPythonOptions = { onProgress: (message) => console.error(message) };\n\tawait bootstrapVenv(ownedRuntime.runtimeDir, [], options);\n\tconst runtimeIdentity = await resolveRuntimeIdentity();\n\tif (\n\t\t!(await kernelReady(python, ownedRuntime.runtimeDir, runtimeIdentity, [])) ||\n\t\t(await missingRlmExtraImportLabels(python)).length > 0\n\t) {\n\t\tthrow new Error(\"Base-Context candidate Python runtime did not become ready. This candidate was not activated.\");\n\t}\n\treturn python;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bootstrap.d.ts","sourceRoot":"","sources":["../../../src/core/kernel/bootstrap.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAuB3D,eAAO,MAAM,yBAAyB,UAAqD,CAAC;AAC5F,eAAO,MAAM,8BAA8B,UAA0D,CAAC;AACtG,eAAO,MAAM,+BAA+B,UAA2D,CAAC;AAyBxG,MAAM,MAAM,iBAAiB,GAAG,sBAAsB,CAAC;AACvD,MAAM,MAAM,8BAA8B,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;AAEvE,MAAM,WAAW,yBAAyB;IACzC,YAAY,CAAC,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC5C,UAAU,CAAC,EAAE,8BAA8B,CAAC;CAC5C;AAwQD,wBAAgB,gBAAgB,IAAI,MAAM,CAGzC;AAgSD,wBAAgB,oBAAoB,IAAI,MAAM,EAAE,CAO/C;AAWD,wBAAsB,sBAAsB,IAAI,OAAO,CAAC,MAAM,CAAC,CAE9D;AAqOD,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,MAAM,CAAC,CAU3F;AAED,wFAAwF;AACxF,wBAAsB,wBAAwB,IAAI,OAAO,CAAC,MAAM,CAAC,CAmBhE","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { constants, existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { access, mkdir, readdir, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { stderr, stdin } from \"node:process\";\nimport { createInterface } from \"node:readline/promises\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\nimport { getPackageDir, getPhysicalPackageDir } from \"../../config.js\";\nimport { getOwnedInstallation, readInstallSelection } from \"../../owned-install-layout.js\";\nimport { PRODUCT, PRODUCT_ENV } from \"../../product-identity.js\";\nimport { assertProductStatePath, readAbsolutePathEnv, resolveRuntimePaths } from \"../../runtime-paths.js\";\nimport type { PythonSkillRuntimeInfo } from \"../skills.js\";\n\nconst ownedRuntime = getOwnedInstallation(getPhysicalPackageDir());\nconst BOOTSTRAP_SCHEMA = 11;\nconst PYTHON_VERSION = \"3.13\";\nconst RUNTIME_REQUIREMENT = PRODUCT.runtimeDistribution;\n// Serializes the kernel's user namespace so it can be revived across session\n// resume. Internal-only; intentionally not surfaced to the model as an import.\nconst STATE_SNAPSHOT_REQUIREMENT = \"dill\";\nconst DEFAULT_RLM_EXTRA_PACKAGES = [\n\t{ uvArg: \"requests\", importName: \"requests\", promptLabel: \"requests\" },\n\t{ uvArg: \"httpx\", importName: \"httpx\", promptLabel: \"httpx\" },\n\t{ uvArg: \"pyyaml\", importName: \"yaml\", promptLabel: \"yaml (PyYAML)\" },\n\t{ uvArg: \"tomli\", importName: \"tomli\", promptLabel: \"tomli\" },\n\t{ uvArg: \"python-dotenv\", importName: \"dotenv\", promptLabel: \"dotenv (python-dotenv)\" },\n\t{ uvArg: \"pandas\", importName: \"pandas\", promptLabel: \"pandas\" },\n\t{ uvArg: \"numpy\", importName: \"numpy\", promptLabel: \"numpy\" },\n\t{ uvArg: \"scipy\", importName: \"scipy\", promptLabel: \"scipy\" },\n\t{ uvArg: \"beautifulsoup4\", importName: \"bs4\", promptLabel: \"bs4 (Beautiful Soup)\" },\n\t{ uvArg: \"lxml\", importName: \"lxml\", promptLabel: \"lxml\" },\n\t{ uvArg: \"pydantic\", importName: \"pydantic\", promptLabel: \"pydantic\" },\n\t{ uvArg: \"tyro\", importName: \"tyro\", promptLabel: \"tyro\" },\n];\nexport const DEFAULT_RLM_EXTRA_UV_ARGS = DEFAULT_RLM_EXTRA_PACKAGES.map((pkg) => pkg.uvArg);\nexport const DEFAULT_RLM_EXTRA_IMPORT_NAMES = DEFAULT_RLM_EXTRA_PACKAGES.map((pkg) => pkg.importName);\nexport const DEFAULT_RLM_EXTRA_IMPORT_LABELS = DEFAULT_RLM_EXTRA_PACKAGES.map((pkg) => pkg.promptLabel);\nconst UV_INSTALL_COMMAND = \"curl -LsSf https://astral.sh/uv/install.sh | UV_NO_MODIFY_PATH=1 sh\";\nconst REQUIRED_HARNESS_METHODS = [\n\t\"create_memory\",\n\t\"update_memory\",\n\t\"delete_memory\",\n\t\"create_skill\",\n\t\"update_skill\",\n\t\"delete_skill\",\n\t\"create_subagent\",\n\t\"update_subagent\",\n\t\"delete_subagent\",\n\t\"create_prompt_note\",\n\t\"update_prompt_note\",\n\t\"delete_prompt_note\",\n\t\"record_refinement\",\n];\nconst RUNTIME_READY_CHECK = `import inspect; from importlib import metadata; import rlm; assert metadata.version(\"${RUNTIME_REQUIREMENT}\"); assert \"prime-agent-runtime\" not in {d.metadata[\"Name\"].lower().replace(\"_\", \"-\") for d in metadata.distributions()}; from rlm import McpIntegration; import rlm.mcp as mcp; from rlm.harness import HarnessEntry; _harness_methods = ${JSON.stringify(REQUIRED_HARNESS_METHODS)}; assert callable(mcp.list_tools); assert callable(mcp.call_tool); assert hasattr(rlm, 'run'); assert callable(rlm); assert hasattr(rlm, 'rlm'); assert callable(rlm.rlm); assert callable(rlm.host_request); assert callable(rlm.find_models); assert callable(rlm.rlm.find_models); assert hasattr(rlm, 'harness'); assert hasattr(rlm, 'get_harness_state'); assert hasattr(rlm.rlm, 'harness'); assert hasattr(rlm.rlm, 'get_harness_state'); assert all(callable(getattr(_harness, _method, None)) for _harness in (rlm.harness, rlm.rlm.harness) for _method in _harness_methods); assert 'reference' in HarnessEntry.__dataclass_fields__; assert 'scope' in HarnessEntry.__dataclass_fields__; assert 'reference' in inspect.signature(rlm.harness.create_skill).parameters; assert 'reference' in inspect.signature(rlm.harness.update_skill).parameters; assert 'global_' in inspect.signature(rlm.harness.create_memory).parameters; assert 'global_' in inspect.signature(rlm.get_harness_state).parameters; assert not hasattr(rlm, 'background'); assert not hasattr(rlm.rlm, 'background'); from rlm.bash import BashHandle, BashResult; assert callable(rlm.bash); assert all(callable(getattr(BashHandle, _m, None)) for _m in ('tail', 'output', 'poll', 'kill')); assert {'exit_code', 'output', 'duration'} <= set(BashResult.__dataclass_fields__); import rlm.repl as _repl; assert callable(_repl.main); assert callable(_repl.emit); assert callable(_repl.host_request); assert callable(_repl.is_active); assert _repl.PROTOCOL_VERSION == 4; assert callable(rlm.emit); assert not hasattr(rlm, 'HOST_COMM_TARGET'); assert not hasattr(mcp, 'install_shutdown_hook')`;\nconst BOOTSTRAP_VERSION_FILE = \".bootstrap-version\";\nconst BOOTSTRAP_LOCK_NAME = \".bootstrap.lock\";\nconst BOOTSTRAP_LOCK_RETRY_MS = 100;\nconst BOOTSTRAP_LOCK_STALE_WITHOUT_PID_MS = 30_000;\n\nlet inFlightEnsureKernelPython: { key: string; promise: Promise<string> } | null = null;\n\nexport type KernelPythonSkill = PythonSkillRuntimeInfo;\nexport type KernelBootstrapProgressHandler = (message: string) => void;\n\nexport interface EnsureKernelPythonOptions {\n\tpythonSkills?: readonly KernelPythonSkill[];\n\tonProgress?: KernelBootstrapProgressHandler;\n}\n\ninterface BootstrapPythonSkill {\n\timportName: string;\n\tpackagePath: string;\n\tpyprojectPath: string;\n\tpyprojectHash: string;\n}\n\ninterface BootstrapVersion {\n\tschema: number;\n\truntime?: string;\n\tsnapshot?: string;\n\textraUvArgs?: string[];\n\tpythonSkills?: BootstrapPythonSkill[];\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\nfunction isNodeError(error: unknown, code: string): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === code;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nasync function exists(filePath: string): Promise<boolean> {\n\ttry {\n\t\tawait access(filePath);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nasync function isExecutable(filePath: string): Promise<boolean> {\n\ttry {\n\t\tawait access(filePath, constants.X_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction fileContentHash(filePath: string): string {\n\ttry {\n\t\treturn `sha256:${createHash(\"sha256\").update(readFileSync(filePath)).digest(\"hex\")}`;\n\t} catch {\n\t\treturn \"unreadable\";\n\t}\n}\n\nfunction normalizePythonSkills(pythonSkills: readonly KernelPythonSkill[] | undefined): BootstrapPythonSkill[] {\n\tconst byKey = new Map<string, BootstrapPythonSkill>();\n\tconst addSkill = (skill: Pick<KernelPythonSkill, \"importName\" | \"packagePath\" | \"pyprojectPath\">): void => {\n\t\tconst packagePath = path.resolve(skill.packagePath);\n\t\tconst pyprojectPath = path.resolve(skill.pyprojectPath);\n\t\tconst key = `${skill.importName}\\0${packagePath}`;\n\t\tif (byKey.has(key)) {\n\t\t\treturn;\n\t\t}\n\t\tconst bootstrapSkill: BootstrapPythonSkill = {\n\t\t\timportName: skill.importName,\n\t\t\tpackagePath,\n\t\t\tpyprojectPath,\n\t\t\tpyprojectHash: fileContentHash(pyprojectPath),\n\t\t};\n\t\tbyKey.set(key, bootstrapSkill);\n\t\tfor (const dependencyName of readPythonSkillDependencyNames(bootstrapSkill)) {\n\t\t\tconst siblingDependency = resolveSiblingPythonSkillDependency(bootstrapSkill, dependencyName);\n\t\t\tif (siblingDependency) {\n\t\t\t\taddSkill(siblingDependency);\n\t\t\t}\n\t\t}\n\t};\n\tfor (const skill of pythonSkills ?? []) {\n\t\taddSkill(skill);\n\t}\n\treturn [...byKey.values()].sort((a, b) => {\n\t\tconst packageCompare = a.packagePath.localeCompare(b.packagePath);\n\t\tif (packageCompare !== 0) return packageCompare;\n\t\treturn a.importName.localeCompare(b.importName);\n\t});\n}\n\nfunction readTomlProjectSection(pyprojectPath: string): string | undefined {\n\ttry {\n\t\tconst text = readFileSync(pyprojectPath, \"utf-8\");\n\t\tconst match = text.match(/^\\s*\\[project\\]\\s*$/m);\n\t\tif (!match || match.index === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst sectionStart = match.index + match[0].length;\n\t\tconst rest = text.slice(sectionStart);\n\t\tconst nextSection = rest.search(/^\\s*\\[/m);\n\t\treturn nextSection >= 0 ? rest.slice(0, nextSection) : rest;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction readPythonSkillProjectName(skill: BootstrapPythonSkill): string {\n\tconst projectSection = readTomlProjectSection(skill.pyprojectPath);\n\tconst name = projectSection?.match(/^\\s*name\\s*=\\s*[\"']([^\"']+)[\"']/m)?.[1];\n\treturn name?.trim() || skill.importName.replaceAll(\"_\", \"-\");\n}\n\nfunction parseDependencyPackageName(dependency: string): string | undefined {\n\tconst withoutMarker = dependency.split(\";\")[0]?.trim() ?? \"\";\n\tif (!withoutMarker) {\n\t\treturn undefined;\n\t}\n\tconst match = withoutMarker.match(/^([A-Za-z0-9_.-]+)/);\n\treturn match?.[1]?.replaceAll(\"_\", \"-\").toLowerCase();\n}\n\nfunction findTomlArrayEnd(text: string, startIndex: number): number {\n\tlet inQuote: '\"' | \"'\" | undefined;\n\tlet escaped = false;\n\tfor (let index = startIndex; index < text.length; index++) {\n\t\tconst char = text[index];\n\t\tif (inQuote) {\n\t\t\tif (escaped) {\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === \"\\\\\") {\n\t\t\t\tescaped = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (char === inQuote) {\n\t\t\t\tinQuote = undefined;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === '\"' || char === \"'\") {\n\t\t\tinQuote = char;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"]\") {\n\t\t\treturn index;\n\t\t}\n\t}\n\treturn -1;\n}\n\nfunction readPythonSkillDependencyNames(skill: BootstrapPythonSkill): Set<string> {\n\tconst projectSection = readTomlProjectSection(skill.pyprojectPath);\n\tif (!projectSection) {\n\t\treturn new Set();\n\t}\n\tconst dependenciesStart = projectSection.search(/^\\s*dependencies\\s*=\\s*\\[/m);\n\tif (dependenciesStart < 0) {\n\t\treturn new Set();\n\t}\n\tconst arrayStart = projectSection.indexOf(\"[\", dependenciesStart);\n\tif (arrayStart < 0) {\n\t\treturn new Set();\n\t}\n\tconst arrayEnd = findTomlArrayEnd(projectSection, arrayStart + 1);\n\tif (arrayEnd < 0) {\n\t\treturn new Set();\n\t}\n\tconst dependenciesArray = projectSection.slice(arrayStart, arrayEnd + 1);\n\tconst dependencies = new Set<string>();\n\tconst dependencyPattern = /\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"|'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)'/g;\n\tfor (const match of dependenciesArray.matchAll(dependencyPattern)) {\n\t\tconst dependency = (match[1] ?? match[2] ?? \"\").replaceAll('\\\\\"', '\"').replaceAll(\"\\\\'\", \"'\");\n\t\tconst name = parseDependencyPackageName(dependency);\n\t\tif (name) {\n\t\t\tdependencies.add(name);\n\t\t}\n\t}\n\treturn dependencies;\n}\n\nfunction resolveSiblingPythonSkillDependency(\n\tskill: BootstrapPythonSkill,\n\tdependencyName: string,\n): BootstrapPythonSkill | undefined {\n\tconst siblingsDir = path.dirname(skill.packagePath);\n\tfor (const entry of readdirSync(siblingsDir, { withFileTypes: true })) {\n\t\tif (!entry.isDirectory()) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst packagePath = path.join(siblingsDir, entry.name);\n\t\tconst pyprojectPath = path.join(packagePath, \"pyproject.toml\");\n\t\tif (!existsSync(pyprojectPath)) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst dependency: BootstrapPythonSkill = {\n\t\t\timportName: entry.name.replaceAll(\"-\", \"_\"),\n\t\t\tpackagePath,\n\t\t\tpyprojectPath,\n\t\t\tpyprojectHash: fileContentHash(pyprojectPath),\n\t\t};\n\t\tif (readPythonSkillProjectName(dependency).replaceAll(\"_\", \"-\").toLowerCase() === dependencyName) {\n\t\t\treturn dependency;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction sortPythonSkillsForInstall(pythonSkills: readonly BootstrapPythonSkill[]): BootstrapPythonSkill[] {\n\tconst byProjectName = new Map<string, BootstrapPythonSkill>();\n\tconst originalIndex = new Map<BootstrapPythonSkill, number>();\n\tfor (const [index, skill] of pythonSkills.entries()) {\n\t\toriginalIndex.set(skill, index);\n\t\tbyProjectName.set(readPythonSkillProjectName(skill).replaceAll(\"_\", \"-\").toLowerCase(), skill);\n\t}\n\n\tconst dependenciesBySkill = new Map<BootstrapPythonSkill, BootstrapPythonSkill[]>();\n\tfor (const skill of pythonSkills) {\n\t\tdependenciesBySkill.set(\n\t\t\tskill,\n\t\t\t[...readPythonSkillDependencyNames(skill)]\n\t\t\t\t.map(\n\t\t\t\t\t(dependencyName) =>\n\t\t\t\t\t\tbyProjectName.get(dependencyName) ?? resolveSiblingPythonSkillDependency(skill, dependencyName),\n\t\t\t\t)\n\t\t\t\t.filter((dependency): dependency is BootstrapPythonSkill => Boolean(dependency)),\n\t\t);\n\t}\n\n\tconst pending = new Set(pythonSkills);\n\tconst sorted: BootstrapPythonSkill[] = [];\n\twhile (pending.size > 0) {\n\t\tlet progressed = false;\n\t\tfor (const skill of [...pending].sort((a, b) => (originalIndex.get(a) ?? 0) - (originalIndex.get(b) ?? 0))) {\n\t\t\tconst dependencies = dependenciesBySkill.get(skill) ?? [];\n\t\t\tif (dependencies.some((dependency) => pending.has(dependency))) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsorted.push(skill);\n\t\t\tpending.delete(skill);\n\t\t\tprogressed = true;\n\t\t}\n\t\tif (!progressed) {\n\t\t\t// Cyclic local skill dependencies cannot be topologically ordered; keep a\n\t\t\t// deterministic order and let uv surface the packaging error if needed.\n\t\t\tsorted.push(...[...pending].sort((a, b) => a.packagePath.localeCompare(b.packagePath)));\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn sorted;\n}\n\nfunction formatPythonSkillInstallArgs(skill: BootstrapPythonSkill): string[] {\n\treturn [\"--editable\", skill.packagePath];\n}\n\nfunction ensureKernelPythonKey(pythonSkills: readonly BootstrapPythonSkill[]): string {\n\treturn [\n\t\tprocess.env[PRODUCT_ENV.kernelPython] ?? \"\",\n\t\tprocess.env[PRODUCT_ENV.kernelVenv] ?? \"\",\n\t\tprocess.env.HOME ?? \"\",\n\t\tprocess.env[PRODUCT_ENV.home] ?? \"\",\n\t\tJSON.stringify(pythonSkills),\n\t].join(\"\\0\");\n}\n\nexport function getKernelVenvDir(): string {\n\tconst override = readAbsolutePathEnv(PRODUCT_ENV.kernelVenv);\n\treturn assertProductStatePath(override ?? ownedRuntime?.runtimeDir ?? resolveRuntimePaths().runtime);\n}\n\nasync function resolveWritableKernelVenvDir(): Promise<string> {\n\tconst venv = getKernelVenvDir();\n\tawait mkdir(path.dirname(venv), { recursive: true });\n\treturn venv;\n}\n\nfunction run(command: string, args: string[], options: { stdio?: \"ignore\" | \"inherit\" } = {}): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tenv: process.env,\n\t\t\tstdio: options.stdio ?? \"ignore\",\n\t\t});\n\t\tchild.on(\"error\", reject);\n\t\tchild.on(\"exit\", (code, signal) => {\n\t\t\tif (code === 0) {\n\t\t\t\tresolve();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst reason = signal ? `signal ${signal}` : `exit code ${code}`;\n\t\t\treject(new Error(`${command} ${args.join(\" \")} failed with ${reason}`));\n\t\t});\n\t});\n}\n\nasync function pythonImports(python: string, moduleName: string): Promise<boolean> {\n\ttry {\n\t\tawait run(python, [\"-c\", `import ${moduleName}`], { stdio: \"ignore\" });\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nasync function hasBaseContextRuntime(python: string): Promise<boolean> {\n\ttry {\n\t\tawait run(python, [\"-c\", RUNTIME_READY_CHECK], { stdio: \"ignore\" });\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nasync function missingRlmExtraImportLabels(python: string): Promise<string[]> {\n\tconst missing: string[] = [];\n\tfor (const pkg of DEFAULT_RLM_EXTRA_PACKAGES) {\n\t\tif (!(await pythonImports(python, pkg.importName))) {\n\t\t\tmissing.push(pkg.promptLabel);\n\t\t}\n\t}\n\treturn missing;\n}\n\nasync function missingPythonSkillImportLabels(\n\tpython: string,\n\tpythonSkills: readonly KernelPythonSkill[],\n): Promise<string[]> {\n\tconst missing: string[] = [];\n\tfor (const skill of pythonSkills) {\n\t\tif (!(await pythonImports(python, skill.importName))) {\n\t\t\tmissing.push(`${skill.name} (${skill.importName})`);\n\t\t}\n\t}\n\treturn missing;\n}\n\nfunction reportProgress(options: EnsureKernelPythonOptions, message: string): void {\n\tif (options.onProgress) {\n\t\toptions.onProgress(message);\n\t\treturn;\n\t}\n\tprocess.stderr.write(`${message}\\n`);\n}\n\nfunction bootstrapLockDir(venv: string): string {\n\treturn path.join(path.dirname(venv), `${path.basename(venv)}${BOOTSTRAP_LOCK_NAME}`);\n}\n\nfunction processIsRunning(pid: number): boolean {\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn isNodeError(error, \"EPERM\");\n\t}\n}\n\nasync function readLockPid(lockDir: string): Promise<number | null> {\n\ttry {\n\t\tconst raw = await readFile(path.join(lockDir, \"pid\"), \"utf8\");\n\t\tconst pid = Number.parseInt(raw.trim(), 10);\n\t\treturn Number.isInteger(pid) && pid > 0 ? pid : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function lockMissingPidIsStale(lockDir: string): Promise<boolean> {\n\ttry {\n\t\tconst lockStat = await stat(lockDir);\n\t\treturn Date.now() - lockStat.mtimeMs > BOOTSTRAP_LOCK_STALE_WITHOUT_PID_MS;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nasync function acquireBootstrapLock(venv: string): Promise<() => Promise<void>> {\n\tconst lockDir = bootstrapLockDir(venv);\n\tawait mkdir(path.dirname(lockDir), { recursive: true });\n\n\tfor (;;) {\n\t\ttry {\n\t\t\tawait mkdir(lockDir);\n\t\t\tawait writeFile(path.join(lockDir, \"pid\"), `${process.pid}\\n`, \"utf8\");\n\t\t\treturn () => rm(lockDir, { recursive: true, force: true });\n\t\t} catch (error) {\n\t\t\tif (!isNodeError(error, \"EEXIST\")) throw error;\n\n\t\t\tconst pid = await readLockPid(lockDir);\n\t\t\tif (pid === null ? await lockMissingPidIsStale(lockDir) : !processIsRunning(pid)) {\n\t\t\t\tawait rm(lockDir, { recursive: true, force: true });\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tawait sleep(BOOTSTRAP_LOCK_RETRY_MS);\n\t\t}\n\t}\n}\n\nasync function findExecutable(name: string): Promise<string | null> {\n\tconst pathValue = process.env.PATH;\n\tif (!pathValue) return null;\n\tconst candidates = process.platform === \"win32\" ? [name, `${name}.exe`] : [name];\n\tfor (const dir of pathValue.split(path.delimiter)) {\n\t\tif (!dir) continue;\n\t\tfor (const candidate of candidates) {\n\t\t\tconst fullPath = path.join(dir, candidate);\n\t\t\tif (await isExecutable(fullPath)) return fullPath;\n\t\t}\n\t}\n\treturn null;\n}\n\nasync function ensureUv(options: EnsureKernelPythonOptions): Promise<string> {\n\tconst fromPath = await findExecutable(\"uv\");\n\tif (fromPath) return fromPath;\n\n\tconst localUv = path.join(os.homedir(), \".local\", \"bin\", process.platform === \"win32\" ? \"uv.exe\" : \"uv\");\n\tif (await isExecutable(localUv)) return localUv;\n\n\tconst shouldInstallUv =\n\t\tprocess.env[PRODUCT_ENV.installUv] === \"1\" || (!options.onProgress && (await confirmUvInstall()));\n\tif (!shouldInstallUv) {\n\t\tthrow new Error(\n\t\t\t`uv is required to set up the Python kernel. Install uv yourself: ${UV_INSTALL_COMMAND}, ` +\n\t\t\t\t\"or set BASE_CONTEXT_INSTALL_UV=1 to let base-context run that installer.\",\n\t\t);\n\t}\n\n\treportProgress(options, \"› installing uv (one-time)…\");\n\ttry {\n\t\tawait run(\"sh\", [\"-c\", UV_INSTALL_COMMAND], { stdio: options.onProgress ? \"ignore\" : \"inherit\" });\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`couldn't install uv from astral.sh; install it yourself: ${UV_INSTALL_COMMAND}, then re-run base-context. ${errorMessage(error)}`,\n\t\t);\n\t}\n\n\tif (await isExecutable(localUv)) return localUv;\n\tconst installedFromPath = await findExecutable(\"uv\");\n\tif (installedFromPath) return installedFromPath;\n\tthrow new Error(\"uv install completed but binary not found at ~/.local/bin/uv\");\n}\n\nasync function confirmUvInstall(): Promise<boolean> {\n\tif (process.env[PRODUCT_ENV.installUv] === \"0\") return false;\n\tif (!stdin.isTTY || !stderr.isTTY) return false;\n\n\tconst rl = createInterface({ input: stdin, output: stderr });\n\ttry {\n\t\tconst answer = (\n\t\t\tawait rl.question(\"Base Context needs uv to set up Python. Install uv from astral.sh now? [Y/n] \")\n\t\t)\n\t\t\t.trim()\n\t\t\t.toLowerCase();\n\t\treturn answer !== \"n\" && answer !== \"no\";\n\t} finally {\n\t\trl.close();\n\t}\n}\n\nasync function readBootstrapVersion(venv: string): Promise<BootstrapVersion | null> {\n\ttry {\n\t\tconst raw = await readFile(path.join(venv, BOOTSTRAP_VERSION_FILE), \"utf8\");\n\t\tconst parsed: unknown = JSON.parse(raw);\n\t\tif (!isRecord(parsed) || typeof parsed.schema !== \"number\") return null;\n\t\tconst extraUvArgs =\n\t\t\tArray.isArray(parsed.extraUvArgs) &&\n\t\t\tparsed.extraUvArgs.every((v: unknown): v is string => typeof v === \"string\")\n\t\t\t\t? (parsed.extraUvArgs as string[])\n\t\t\t\t: undefined;\n\t\tlet pythonSkills: BootstrapPythonSkill[] | undefined;\n\t\tif (Array.isArray(parsed.pythonSkills)) {\n\t\t\tif (\n\t\t\t\t!parsed.pythonSkills.every((v: unknown): v is BootstrapPythonSkill => {\n\t\t\t\t\tif (!isRecord(v)) return false;\n\t\t\t\t\treturn (\n\t\t\t\t\t\ttypeof v.importName === \"string\" &&\n\t\t\t\t\t\ttypeof v.packagePath === \"string\" &&\n\t\t\t\t\t\ttypeof v.pyprojectPath === \"string\" &&\n\t\t\t\t\t\ttypeof v.pyprojectHash === \"string\"\n\t\t\t\t\t);\n\t\t\t\t})\n\t\t\t) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tpythonSkills = parsed.pythonSkills as BootstrapPythonSkill[];\n\t\t}\n\t\treturn {\n\t\t\tschema: parsed.schema,\n\t\t\truntime: typeof parsed.runtime === \"string\" ? parsed.runtime : undefined,\n\t\t\tsnapshot: typeof parsed.snapshot === \"string\" ? parsed.snapshot : undefined,\n\t\t\textraUvArgs,\n\t\t\tpythonSkills,\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction extraUvArgsMatch(a: string[] | undefined, b: string[] | undefined): boolean {\n\tif (a === b) return true;\n\tif (!a || !b) return false;\n\tif (a.length !== b.length) return false;\n\treturn a.every((v, i) => v === b[i]);\n}\n\nfunction pythonSkillsMatch(a: BootstrapPythonSkill[] | undefined, b: readonly BootstrapPythonSkill[]): boolean {\n\tconst left = a ?? [];\n\tif (left.length !== b.length) return false;\n\treturn left.every((skill, index) => {\n\t\tconst expected = b[index];\n\t\treturn (\n\t\t\tskill.importName === expected.importName &&\n\t\t\tskill.packagePath === expected.packagePath &&\n\t\t\tskill.pyprojectPath === expected.pyprojectPath &&\n\t\t\tskill.pyprojectHash === expected.pyprojectHash\n\t\t);\n\t});\n}\n\nfunction bootstrapVersionCurrent(\n\tversion: BootstrapVersion | null,\n\truntimeIdentity: string,\n\tpythonSkills: readonly BootstrapPythonSkill[],\n): boolean {\n\treturn (\n\t\tversion !== null &&\n\t\tbootstrapBaseVersionCurrent(version, runtimeIdentity) &&\n\t\tpythonSkillsMatch(version.pythonSkills, pythonSkills)\n\t);\n}\n\nfunction bootstrapBaseVersionCurrent(version: BootstrapVersion | null, runtimeIdentity: string): boolean {\n\treturn (\n\t\tversion?.schema === BOOTSTRAP_SCHEMA &&\n\t\tversion.runtime === runtimeIdentity &&\n\t\tversion.snapshot === STATE_SNAPSHOT_REQUIREMENT &&\n\t\textraUvArgsMatch(version.extraUvArgs, DEFAULT_RLM_EXTRA_UV_ARGS)\n\t);\n}\n\nasync function writeBootstrapVersion(\n\tvenv: string,\n\truntimeIdentity: string,\n\tpythonSkills: readonly BootstrapPythonSkill[],\n): Promise<void> {\n\tconst version: BootstrapVersion = {\n\t\tschema: BOOTSTRAP_SCHEMA,\n\t\truntime: runtimeIdentity,\n\t\tsnapshot: STATE_SNAPSHOT_REQUIREMENT,\n\t\textraUvArgs: DEFAULT_RLM_EXTRA_UV_ARGS,\n\t\tpythonSkills: [...pythonSkills],\n\t};\n\tawait writeFile(path.join(venv, BOOTSTRAP_VERSION_FILE), `${JSON.stringify(version)}\\n`, \"utf8\");\n}\n\nexport function runtimeCandidateDirs(): string[] {\n\tif (ownedRuntime) return [path.join(ownedRuntime.packageDir, \"dist\", RUNTIME_REQUIREMENT)];\n\tconst packageDir = getPackageDir();\n\tif (existsSync(path.join(packageDir, \"src\"))) {\n\t\treturn [path.resolve(packageDir, \"..\", \"..\", \"prime-agent-runtime\")];\n\t}\n\treturn [path.join(packageDir, \"dist\", RUNTIME_REQUIREMENT), path.join(packageDir, RUNTIME_REQUIREMENT)];\n}\n\nasync function resolveRuntimeSourceDir(): Promise<string> {\n\tfor (const candidate of runtimeCandidateDirs()) {\n\t\tif (await exists(path.join(candidate, \"pyproject.toml\"))) return candidate;\n\t}\n\tthrow new Error(\n\t\t\"Base Context runtime payload is missing. Reinstall this Base Context release; registry runtime fallback is disabled.\",\n\t);\n}\n\nexport async function resolveRuntimeIdentity(): Promise<string> {\n\treturn hashRuntimeSource(await resolveRuntimeSourceDir());\n}\n\n// A source read failure must not be replaced by a registry runtime.\nasync function hashRuntimeSource(sourceDir: string): Promise<string> {\n\tconst rlmDir = path.join(sourceDir, \"src\", \"rlm\");\n\tconst files: string[] = [path.join(sourceDir, \"pyproject.toml\")];\n\tasync function collect(dir: string): Promise<void> {\n\t\tconst entries = await readdir(dir, { withFileTypes: true });\n\t\tfor (const entry of entries) {\n\t\t\tconst full = path.join(dir, entry.name);\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tawait collect(full);\n\t\t\t} else if (entry.isFile() && entry.name.endsWith(\".py\")) {\n\t\t\t\tfiles.push(full);\n\t\t\t}\n\t\t}\n\t}\n\tawait collect(rlmDir);\n\tfiles.sort();\n\tconst hash = createHash(\"sha256\");\n\tfor (const file of files) {\n\t\thash.update(path.relative(sourceDir, file));\n\t\thash.update(\"\\0\");\n\t\thash.update(await readFile(file));\n\t\thash.update(\"\\0\");\n\t}\n\treturn `sha256:${hash.digest(\"hex\")}`;\n}\n\nasync function bootstrapVenv(\n\tvenv: string,\n\tpythonSkills: readonly BootstrapPythonSkill[],\n\toptions: EnsureKernelPythonOptions,\n): Promise<void> {\n\tawait mkdir(path.dirname(venv), { recursive: true });\n\tconst uv = await ensureUv(options);\n\tconst python = path.join(venv, \"bin\", \"python\");\n\tconst sourceDir = await resolveRuntimeSourceDir();\n\tconst runtimeRequirement = sourceDir;\n\tconst runtimeIdentity = await resolveRuntimeIdentity();\n\n\tawait run(uv, [\"python\", \"install\", PYTHON_VERSION]);\n\tawait run(uv, [\"venv\", venv, \"--python\", PYTHON_VERSION, \"--seed\"]);\n\tawait run(uv, [\n\t\t\"pip\",\n\t\t\"install\",\n\t\t\"--python\",\n\t\tpython,\n\t\truntimeRequirement,\n\t\tSTATE_SNAPSHOT_REQUIREMENT,\n\t\t...DEFAULT_RLM_EXTRA_UV_ARGS,\n\t]);\n\tawait syncPythonSkills(uv, venv, python, runtimeIdentity, pythonSkills, options);\n}\n\nasync function syncPythonSkills(\n\tuv: string,\n\tvenv: string,\n\tpython: string,\n\truntimeIdentity: string,\n\tpythonSkills: readonly BootstrapPythonSkill[],\n\toptions: EnsureKernelPythonOptions,\n): Promise<void> {\n\tconst version = await readBootstrapVersion(venv);\n\tconst installedPythonSkills: BootstrapPythonSkill[] = [];\n\tconst currentPythonSkills = new Map(\n\t\t(version?.pythonSkills ?? []).map((skill) => [`${skill.importName}\\0${skill.packagePath}`, skill]),\n\t);\n\tconst pythonSkillsByProjectName = new Map(\n\t\tpythonSkills.map((skill) => [readPythonSkillProjectName(skill).replaceAll(\"_\", \"-\").toLowerCase(), skill]),\n\t);\n\tconst dependenciesBySkill = new Map(\n\t\tpythonSkills.map((skill) => [\n\t\t\tskill,\n\t\t\t[...readPythonSkillDependencyNames(skill)]\n\t\t\t\t.map(\n\t\t\t\t\t(dependencyName) =>\n\t\t\t\t\t\tpythonSkillsByProjectName.get(dependencyName) ??\n\t\t\t\t\t\tresolveSiblingPythonSkillDependency(skill, dependencyName),\n\t\t\t\t)\n\t\t\t\t.filter((dependency): dependency is BootstrapPythonSkill => Boolean(dependency)),\n\t\t]),\n\t);\n\n\tfor (const skill of sortPythonSkillsForInstall(pythonSkills)) {\n\t\tconst existingSkill = currentPythonSkills.get(`${skill.importName}\\0${skill.packagePath}`);\n\t\tif (existingSkill?.pyprojectPath === skill.pyprojectPath && existingSkill.pyprojectHash === skill.pyprojectHash) {\n\t\t\tinstalledPythonSkills.push(skill);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst localDependencies = dependenciesBySkill.get(skill) ?? [];\n\t\tconst localDependencyArgs = localDependencies\n\t\t\t.filter((dependency) => {\n\t\t\t\tconst installedDependency = currentPythonSkills.get(`${dependency.importName}\\0${dependency.packagePath}`);\n\t\t\t\tconst installedThisSync = installedPythonSkills.some(\n\t\t\t\t\t(installed) =>\n\t\t\t\t\t\tinstalled.importName === dependency.importName &&\n\t\t\t\t\t\tinstalled.packagePath === dependency.packagePath &&\n\t\t\t\t\t\tinstalled.pyprojectPath === dependency.pyprojectPath &&\n\t\t\t\t\t\tinstalled.pyprojectHash === dependency.pyprojectHash,\n\t\t\t\t);\n\t\t\t\treturn !(\n\t\t\t\t\tinstalledThisSync ||\n\t\t\t\t\t(installedDependency?.pyprojectPath === dependency.pyprojectPath &&\n\t\t\t\t\t\tinstalledDependency.pyprojectHash === dependency.pyprojectHash)\n\t\t\t\t);\n\t\t\t})\n\t\t\t.flatMap(formatPythonSkillInstallArgs);\n\n\t\ttry {\n\t\t\tawait run(uv, [\n\t\t\t\t\"pip\",\n\t\t\t\t\"install\",\n\t\t\t\t\"--python\",\n\t\t\t\tpython,\n\t\t\t\t...formatPythonSkillInstallArgs(skill),\n\t\t\t\t...localDependencyArgs,\n\t\t\t]);\n\t\t\tinstalledPythonSkills.push(\n\t\t\t\tskill,\n\t\t\t\t...localDependencies.filter((dependency) => !installedPythonSkills.includes(dependency)),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\treportProgress(\n\t\t\t\toptions,\n\t\t\t\t`Warning: Python skill ${skill.importName} failed to install and will be unavailable: ${errorMessage(error)}`,\n\t\t\t);\n\t\t}\n\t}\n\tawait writeBootstrapVersion(venv, runtimeIdentity, installedPythonSkills);\n}\n\nasync function kernelBaseReady(python: string, venv: string, runtimeIdentity: string): Promise<boolean> {\n\treturn (\n\t\t(await hasBaseContextRuntime(python)) &&\n\t\tbootstrapBaseVersionCurrent(await readBootstrapVersion(venv), runtimeIdentity)\n\t);\n}\n\nasync function kernelReady(\n\tpython: string,\n\tvenv: string,\n\truntimeIdentity: string,\n\tpythonSkills: readonly BootstrapPythonSkill[],\n): Promise<boolean> {\n\treturn (\n\t\t(await hasBaseContextRuntime(python)) &&\n\t\tbootstrapVersionCurrent(await readBootstrapVersion(venv), runtimeIdentity, pythonSkills)\n\t);\n}\n\nfunction formatBootstrapFailure(error: unknown): Error {\n\treturn new Error(\n\t\t`Failed to set up the Python kernel runtime. ${errorMessage(error)}\\n` +\n\t\t\t\"First-time setup needs internet to install uv, Python, the bundled base-context-runtime, and default Python packages; once set up, base-context runs offline. \" +\n\t\t\t\"Set BASE_CONTEXT_KERNEL_PYTHON to a Python with a current base-context-runtime and default Python packages installed to skip auto-bootstrap.\",\n\t);\n}\n\nasync function ensureKernelPythonUncached(\n\toptions: EnsureKernelPythonOptions,\n\tpythonSkills: readonly BootstrapPythonSkill[],\n): Promise<string> {\n\tconst override = readAbsolutePathEnv(PRODUCT_ENV.kernelPython);\n\tif (override) {\n\t\tconst python = override;\n\t\tconst missing: string[] = [];\n\t\tif (!(await hasBaseContextRuntime(python))) {\n\t\t\tmissing.push(\n\t\t\t\t\"a current base-context-runtime with callable rlm.run, rlm.host_request, and explicit harness CRUD methods\",\n\t\t\t);\n\t\t}\n\t\tif (missing.length === 0) {\n\t\t\tconst missingExtraImports = await missingRlmExtraImportLabels(python);\n\t\t\tif (missingExtraImports.length > 0) {\n\t\t\t\tmissing.push(`default Python packages (${missingExtraImports.join(\", \")})`);\n\t\t\t}\n\t\t}\n\t\tif (missing.length === 0 && pythonSkills.length > 0) {\n\t\t\tconst missingPythonSkills = await missingPythonSkillImportLabels(python, options.pythonSkills ?? []);\n\t\t\tif (missingPythonSkills.length > 0) {\n\t\t\t\treportProgress(\n\t\t\t\t\toptions,\n\t\t\t\t\t`Warning: Python skills unavailable in BASE_CONTEXT_KERNEL_PYTHON and will be disabled: ${missingPythonSkills.join(\", \")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (missing.length === 0) return python;\n\t\tthrow new Error(`BASE_CONTEXT_KERNEL_PYTHON points to a Python missing ${missing.join(\" and \")}: ${python}`);\n\t}\n\n\tconst venv = await resolveWritableKernelVenvDir();\n\tconst python = path.join(venv, \"bin\", \"python\");\n\tconst runtimeIdentity = await resolveRuntimeIdentity();\n\tif (await kernelReady(python, venv, runtimeIdentity, pythonSkills)) return python;\n\n\tconst releaseLock = await acquireBootstrapLock(venv);\n\ttry {\n\t\tif (await kernelReady(python, venv, runtimeIdentity, pythonSkills)) return python;\n\t\tif (await kernelBaseReady(python, venv, runtimeIdentity)) {\n\t\t\tawait syncPythonSkills(await ensureUv(options), venv, python, runtimeIdentity, pythonSkills, options);\n\t\t\treturn python;\n\t\t}\n\n\t\tif (ownedRuntime && !readAbsolutePathEnv(PRODUCT_ENV.kernelVenv)) {\n\t\t\tthrow new Error(\n\t\t\t\t\"The selected Base-Context default runtime is unavailable or stale. Install a prepared candidate or explicitly roll back; the retained runtime was not rebuilt.\",\n\t\t\t);\n\t\t}\n\n\t\tconst hadVenv = existsSync(venv);\n\t\treportProgress(options, \"› setting up python kernel (one-time, ~30s)…\");\n\t\tif (hadVenv) {\n\t\t\treportProgress(options, \"rebuilding kernel venv\");\n\t\t\tawait rm(venv, { recursive: true, force: true });\n\t\t}\n\n\t\tawait bootstrapVenv(venv, pythonSkills, options);\n\t} catch (error) {\n\t\tthrow formatBootstrapFailure(error);\n\t} finally {\n\t\tawait releaseLock().catch(() => undefined);\n\t}\n\n\treportProgress(options, \"✓ ready\");\n\treturn python;\n}\n\nexport function ensureKernelPython(options: EnsureKernelPythonOptions = {}): Promise<string> {\n\tconst pythonSkills = normalizePythonSkills(options.pythonSkills);\n\tconst key = ensureKernelPythonKey(pythonSkills);\n\tif (inFlightEnsureKernelPython?.key === key) return inFlightEnsureKernelPython.promise;\n\n\tconst promise = ensureKernelPythonUncached(options, pythonSkills).finally(() => {\n\t\tif (inFlightEnsureKernelPython?.promise === promise) inFlightEnsureKernelPython = null;\n\t});\n\tinFlightEnsureKernelPython = { key, promise };\n\treturn promise;\n}\n\n/** Prepare only a new physical owned release, before its selection can be published. */\nexport async function prepareOwnedKernelPython(): Promise<string> {\n\tif (!ownedRuntime || existsSync(ownedRuntime.runtimeDir)) {\n\t\tthrow new Error(\"Base-Context runtime preparation requires a new, empty owned release runtime directory.\");\n\t}\n\tconst selected = readInstallSelection(ownedRuntime.root);\n\tif (selected?.active === ownedRuntime.version || selected?.previous === ownedRuntime.version) {\n\t\tthrow new Error(\"Base-Context will not prepare a published release in place. Install a new candidate instead.\");\n\t}\n\tconst python = path.join(ownedRuntime.runtimeDir, \"bin\", \"python\");\n\tconst options: EnsureKernelPythonOptions = { onProgress: (message) => console.error(message) };\n\tawait bootstrapVenv(ownedRuntime.runtimeDir, [], options);\n\tconst runtimeIdentity = await resolveRuntimeIdentity();\n\tif (\n\t\t!(await kernelReady(python, ownedRuntime.runtimeDir, runtimeIdentity, [])) ||\n\t\t(await missingRlmExtraImportLabels(python)).length > 0\n\t) {\n\t\tthrow new Error(\"Base-Context candidate Python runtime did not become ready. This candidate was not activated.\");\n\t}\n\treturn python;\n}\n"]}
|
|
@@ -13,7 +13,7 @@ import { PRODUCT, PRODUCT_ENV } from "../../product-identity.js";
|
|
|
13
13
|
import { assertProductStatePath, readAbsolutePathEnv, resolveRuntimePaths } from "../../runtime-paths.js";
|
|
14
14
|
const ownedRuntime = getOwnedInstallation(getPhysicalPackageDir());
|
|
15
15
|
const BOOTSTRAP_SCHEMA = 11;
|
|
16
|
-
const PYTHON_VERSION = "3.
|
|
16
|
+
const PYTHON_VERSION = "3.13";
|
|
17
17
|
const RUNTIME_REQUIREMENT = PRODUCT.runtimeDistribution;
|
|
18
18
|
// Serializes the kernel's user namespace so it can be revived across session
|
|
19
19
|
// resume. Internal-only; intentionally not surfaced to the model as an import.
|
|
@@ -35,7 +35,7 @@ const DEFAULT_RLM_EXTRA_PACKAGES = [
|
|
|
35
35
|
export const DEFAULT_RLM_EXTRA_UV_ARGS = DEFAULT_RLM_EXTRA_PACKAGES.map((pkg) => pkg.uvArg);
|
|
36
36
|
export const DEFAULT_RLM_EXTRA_IMPORT_NAMES = DEFAULT_RLM_EXTRA_PACKAGES.map((pkg) => pkg.importName);
|
|
37
37
|
export const DEFAULT_RLM_EXTRA_IMPORT_LABELS = DEFAULT_RLM_EXTRA_PACKAGES.map((pkg) => pkg.promptLabel);
|
|
38
|
-
const UV_INSTALL_COMMAND = "curl -LsSf https://astral.sh/uv/install.sh | sh";
|
|
38
|
+
const UV_INSTALL_COMMAND = "curl -LsSf https://astral.sh/uv/install.sh | UV_NO_MODIFY_PATH=1 sh";
|
|
39
39
|
const REQUIRED_HARNESS_METHODS = [
|
|
40
40
|
"create_memory",
|
|
41
41
|
"update_memory",
|