@opengeni/runtime 3.2.2 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/agent-LJT5NPWT.js +9 -0
  2. package/dist/assets/codemode-client.json +1 -1
  3. package/dist/browser-current-tab.d.ts +46 -0
  4. package/dist/browser-model-text.d.ts +126 -0
  5. package/dist/{chunk-2AUDDDO2.js → chunk-3DFH3ZHU.js} +784 -121
  6. package/dist/chunk-3DFH3ZHU.js.map +1 -0
  7. package/dist/{chunk-HJSIPTFA.js → chunk-4XDJ4TJA.js} +2 -2
  8. package/dist/{chunk-XQ23VCZ4.js → chunk-6FQ6KEII.js} +3 -3
  9. package/dist/{chunk-7LJ7KDPI.js → chunk-ERD4ICVB.js} +4 -3
  10. package/dist/{chunk-462CH77G.js → chunk-ETTCGPBT.js} +400 -9
  11. package/dist/chunk-ETTCGPBT.js.map +1 -0
  12. package/dist/{chunk-7OUG7WBV.js → chunk-GWRBALGQ.js} +181 -13
  13. package/dist/chunk-GWRBALGQ.js.map +1 -0
  14. package/dist/{chunk-YG26XE7B.js → chunk-JYDG2A7H.js} +2 -2
  15. package/dist/{chunk-RSHQSLEJ.js → chunk-KIL4FGX5.js} +3 -3
  16. package/dist/{chunk-NWS4HPB7.js → chunk-MIAL5I4O.js} +2 -2
  17. package/dist/{chunk-Z5U6WE22.js → chunk-PRZPGRIK.js} +2 -2
  18. package/dist/{chunk-KCPW4K7L.js → chunk-PZQUUBEB.js} +2 -2
  19. package/dist/{chunk-5WJOPANS.js → chunk-Y5THZH5N.js} +7 -7
  20. package/dist/codex-tool-search.d.ts +9 -0
  21. package/dist/gmail-rest-mcp.js +8 -8
  22. package/dist/index.d.ts +3 -0
  23. package/dist/index.js +14 -12
  24. package/dist/interaction-tool-json-schema.d.ts +27 -0
  25. package/dist/{lazy-manifest-AJ6XPJ4F.js → lazy-manifest-BLZ3UZLX.js} +4 -4
  26. package/dist/lazy-tool-transport.d.ts +10 -0
  27. package/dist/{localSources-SSIEH5F5.js → localSources-I6SIQ6CX.js} +6 -6
  28. package/dist/model-call.js +3 -3
  29. package/dist/sandbox/browser-control-client.d.ts +87 -0
  30. package/dist/sandbox/browser-control-http.d.ts +33 -0
  31. package/dist/sandbox/index.d.ts +1 -1
  32. package/dist/sandbox/index.js +7 -7
  33. package/dist/sandbox/routing/backend-resolver.d.ts +1 -0
  34. package/dist/sandbox/selfhosted/session.d.ts +22 -0
  35. package/dist/slack-rest-mcp.js +8 -8
  36. package/dist/workspace-tool-gateway.js +12 -12
  37. package/package.json +14 -14
  38. package/src/browser-current-tab.ts +139 -0
  39. package/src/browser-model-text.ts +378 -0
  40. package/src/bundled_site_skills/opengeni-sites/SKILL.md +46 -12
  41. package/src/codex-tool-search.ts +53 -0
  42. package/src/index.ts +39 -1
  43. package/src/interaction-tool-json-schema.ts +281 -0
  44. package/src/interaction-tools.ts +425 -235
  45. package/src/lazy-tool-transport.ts +229 -10
  46. package/src/model-input.ts +12 -1
  47. package/src/sandbox/browser-control-client.ts +425 -0
  48. package/src/sandbox/browser-control-http.ts +32 -0
  49. package/src/sandbox/index.ts +4 -0
  50. package/src/sandbox/routing/backend-resolver.ts +2 -0
  51. package/src/sandbox/selfhosted/session.ts +154 -0
  52. package/dist/agent-CTPLA3HP.js +0 -9
  53. package/dist/browser-action-json-schema.d.ts +0 -4
  54. package/dist/chunk-2AUDDDO2.js.map +0 -1
  55. package/dist/chunk-462CH77G.js.map +0 -1
  56. package/dist/chunk-7OUG7WBV.js.map +0 -1
  57. package/src/browser-action-json-schema.ts +0 -10
  58. /package/dist/{agent-CTPLA3HP.js.map → agent-LJT5NPWT.js.map} +0 -0
  59. /package/dist/{chunk-HJSIPTFA.js.map → chunk-4XDJ4TJA.js.map} +0 -0
  60. /package/dist/{chunk-XQ23VCZ4.js.map → chunk-6FQ6KEII.js.map} +0 -0
  61. /package/dist/{chunk-7LJ7KDPI.js.map → chunk-ERD4ICVB.js.map} +0 -0
  62. /package/dist/{chunk-YG26XE7B.js.map → chunk-JYDG2A7H.js.map} +0 -0
  63. /package/dist/{chunk-RSHQSLEJ.js.map → chunk-KIL4FGX5.js.map} +0 -0
  64. /package/dist/{chunk-NWS4HPB7.js.map → chunk-MIAL5I4O.js.map} +0 -0
  65. /package/dist/{chunk-Z5U6WE22.js.map → chunk-PRZPGRIK.js.map} +0 -0
  66. /package/dist/{chunk-KCPW4K7L.js.map → chunk-PZQUUBEB.js.map} +0 -0
  67. /package/dist/{chunk-5WJOPANS.js.map → chunk-Y5THZH5N.js.map} +0 -0
  68. /package/dist/{lazy-manifest-AJ6XPJ4F.js.map → lazy-manifest-BLZ3UZLX.js.map} +0 -0
  69. /package/dist/{localSources-SSIEH5F5.js.map → localSources-I6SIQ6CX.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sandbox/index.ts","../src/sandbox/host-archive-temporary.ts","../src/sandbox/providers/modal-command-raw-page.ts","../src/sandbox/providers/modal-legacy-command-control.ts","../src/sandbox/providers/modal-command-argv.ts","../src/sandbox/host-archive-spool.ts","../src/sandbox/workspace-archive.ts","../src/sandbox/providers/index.ts","../src/sandbox/capabilities.ts","../src/sandbox/providers/types.ts","../src/sandbox/providers/blaxel.ts","../src/sandbox/providers/cloudflare.ts","../src/sandbox/providers/daytona.ts","../src/sandbox/providers/docker.ts","../src/sandbox/providers/docker-workspace-drain.ts","../src/sandbox/providers/e2b.ts","../src/sandbox/providers/local.ts","../../../node_modules/.bun/@openai+agents-extensions@0.14.3+2947a48661dbc659/node_modules/@openai/agents-extensions/src/sandbox/modal/sandbox.ts","../../../node_modules/.bun/@openai+agents-extensions@0.14.3+2947a48661dbc659/node_modules/@openai/agents-extensions/src/sandbox/modal/mounts.ts","../src/sandbox/providers/modal.ts","../src/sandbox/providers/modal-command-session.ts","../src/sandbox/provider-errors.ts","../src/sandbox/providers/modal-materialization-verification.ts","../src/sandbox/providers/modal-command-control.ts","../src/sandbox/providers/modal-command-observation-errors.ts","../src/sandbox/providers/modal-create-session.ts","../src/sandbox/providers/modal-create-boundary.ts","../src/sandbox/providers/none.ts","../src/sandbox/providers/opensandbox-adapter.ts","../src/sandbox/stream-port.ts","../src/sandbox/stream-token.ts","../src/sandbox/providers/opensandbox-command-stream.ts","../src/sandbox/providers/opensandbox.ts","../src/sandbox/providers/runloop.ts","../src/sandbox/selfhosted/session.ts","../src/sandbox/selfhosted/file-transfer.ts","../src/sandbox/browser-control-http.ts","../src/sandbox/selfhosted/retry-policy.ts","../src/sandbox/selfhosted/op-stream.ts","../src/sandbox/selfhosted/op-transport.ts","../src/sandbox/providers/selfhosted.ts","../src/sandbox/providers/vercel.ts","../src/sandbox/select.ts","../src/sandbox/command-result.ts","../src/sandbox/run-state-compat.ts","../src/sandbox/tool-call-command-not-started.ts","../src/sandbox/providers/modal-native-create-preparation.ts","../src/sandbox/display-stack.ts","../src/sandbox/terminal-server.ts","../src/sandbox/browser-control-server.ts","../src/sandbox/browser-control-client.ts","../src/sandbox/browser-control-stream.ts","../src/sandbox/run-credentials.ts","../src/sandbox/codemode-token.ts","../src/sandbox/codemode-client.ts","../src/sandbox/codemode-authority.ts","../src/sandbox/recording.ts","../src/sandbox/selfhosted/capabilities.ts","../src/sandbox/selfhosted/testing.ts","../src/sandbox/selfhosted/op-testing.ts","../src/sandbox/routing/backend-resolver.ts"],"sourcesContent":["export type {\n ProviderCommandPersistence,\n ProviderCommandSession,\n} from \"./provider-command-session\";\nexport {\n ProviderCommandStartOutcomeUnknownError,\n ProviderCommandInputOutcomeUnknownError,\n ProviderCommandObservationUnavailableError,\n isProviderCommandObservationUnavailableError,\n} from \"./provider-command-session\";\n// @opengeni/runtime/sandbox — the agent-loop-free sandbox leaf.\n//\n// This module is the load-bearing pre-req for the API-direct control plane\n// (docs/connected-machines.md). It exposes the sandbox client factory plus\n// the resume / recovery-envelope helpers that the API needs to touch a box by\n// id (resume-by-id, file/exec/port ops) WITHOUT importing the @openai/agents\n// agent-loop graph.\n//\n// IMPORT DISCIPLINE (enforced by packages/runtime/test/sandbox-leaf-no-agent-loop.test.ts):\n// - ALLOWED: the per-provider sandbox SDK build imports\n// `@openai/agents/sandbox`, `@openai/agents/sandbox/local`,\n// `@openai/agents-extensions/sandbox/modal`\n// and the workspace `@opengeni/config` / `@opengeni/contracts` packages.\n// - FORBIDDEN: the agent-loop entrypoints — the bare `@openai/agents`,\n// `@openai/agents-extensions`, or `@openai/agents-core` roots, and the\n// loop symbols (`Agent`, `run`, `Runner`, `RunState`).\n// The barrel `packages/runtime/src/index.ts` re-exports everything here via\n// `export * from \"./sandbox\"`, so existing consumers (apps/worker) are\n// unchanged.\n\nimport type { Settings } from \"@opengeni/config\";\nimport { collectSandboxEnvironment, parseExposedPorts } from \"@opengeni/config\";\nexport type { WorkspaceArchiveSpool, VerifiedHostWorkspaceArchive } from \"./archive-spool\";\nexport {\n sweepOrphanedHostArchiveTemporaryDirectoriesOnce,\n workspaceArchiveDownloadTemporaryDirectory,\n} from \"./host-archive-temporary\";\nexport type { DockerHostWorkspaceRelease } from \"./providers/docker-workspace-drain\";\nexport { reduceModalRawOutputPage } from \"./providers/modal-command-raw-page\";\nexport type {\n ModalRawOutputPage,\n ModalRawOutputStreams,\n ModalRawOutputExit,\n} from \"./providers/modal-command-raw-page\";\nimport type { WorkspaceArchiveSpool } from \"./archive-spool\";\nimport {\n convertHostWorkspaceArchiveToTar,\n restoreHostWorkspaceArchive,\n type PortableWorkspaceTar,\n} from \"./host-archive-spool\";\nexport {\n captureWorkspaceArchiveForStorage,\n disposeWorkspaceArchive,\n type VerifiedWorkspaceArchivePayload,\n} from \"./workspace-archive\";\n\nimport {\n BROWSER_CONTROL_PORT,\n DESKTOP_STREAM_PORT,\n OPENGENI_SANDBOX_PROVIDER_INSTANCE_ID_FIELD,\n TERMINAL_STREAM_PORT,\n omitInlineWorkspaceArchiveWhenObjectRefPresent,\n parseWorkspaceArchiveObjectRef,\n parseWorkspaceArchiveDescriptor,\n type WorkspaceArchiveObjectRef,\n type TarWorkspaceArchiveDescriptor,\n type SandboxBackend,\n type SandboxProviderContinuityRecovery,\n} from \"@opengeni/contracts\";\nimport type {\n Manifest,\n SandboxClient,\n SandboxSessionLike,\n SandboxSessionState,\n} from \"@openai/agents/sandbox\";\nimport { serializeManifestRecord } from \"@openai/agents-core/sandbox/internal\";\nimport { isProviderApiThrottleError, PROVIDER_REGISTRY } from \"./providers\";\nimport { ensureModalRegistryImage } from \"./providers/modal\";\nimport type { ModalCreateIntent } from \"./providers/modal-create-boundary\";\nimport type { ProviderRegistration } from \"./providers/types\";\nimport { sandboxBackendForSdkBackendId } from \"./select\";\nimport {\n SandboxConfigError,\n SandboxExactResumeReplacedError,\n SandboxProviderContinuityUnavailableError,\n SandboxResumeIdentityMismatchError,\n SandboxResumeIdentityUnavailableError,\n SandboxResumeStateUnavailableError,\n} from \"./errors\";\nimport { isProviderSandboxNotFoundError } from \"./provider-errors\";\nimport {\n decodeNativeSnapshotRef,\n readVerifiedWorkspaceArchive,\n verifyRestoredWorkspace,\n verifyRestoredWorkspaceContents,\n workspaceArchiveExcludedPaths,\n WorkspaceArchiveIntegrityError,\n type VerifiedWorkspaceArchive,\n type WorkspaceArchiveDescriptor,\n} from \"./workspace-archive\";\nimport type { RuntimeMetricsHooks } from \"../metrics\";\nimport { normalizeProtocolJsonValue } from \"../protocol-json\";\nimport { sandboxCommandExitCode, sandboxCommandStillRunning } from \"./command-result\";\nimport { parseExecBannerSessionId } from \"./exec-banner\";\nimport { runStateCompatibilityProvider, runStateExposedPortsRecord } from \"./run-state-compat\";\nimport type { ExposedPortEndpoint } from \"./stream-port\";\n\n// Re-export the config-owned environment/port helpers from the leaf so the\n// API-direct control plane can pull its full sandbox-construction surface from\n// a single agent-loop-free entrypoint. They physically live in @opengeni/config\n// (moving them into runtime would create a config→runtime cycle — ledger CR8).\nexport { collectSandboxEnvironment, parseExposedPorts } from \"@opengeni/config\";\nexport {\n SandboxMaterializationVerificationError,\n materializationVerificationDiagnostic,\n type MaterializationFailureReason,\n type MaterializationVerificationDiagnostic,\n} from \"./materialization-verification-error\";\nexport { sendCommandInput, type CommandInputSession } from \"./command-input\";\nexport { OpStreamExecClient, type OpStreamOutputFrame } from \"./selfhosted/op-stream\";\n\nexport {\n repairSerializedRunStateExposedPorts,\n runStateCompatibilityProvider,\n runStateExposedPortsRecord,\n type RunStateExposedPortsCompatibilityRepair,\n type RunStateExposedPortsCompatibilityResult,\n} from \"./run-state-compat\";\n\n// The provider registry surface — the descriptor table self-test, the per-\n// provider registrations, selection + capability negotiation, and the typed\n// construction errors. All agent-loop-free, so the API-direct control plane\n// imports them from this one leaf.\nexport {\n CAPABILITY_DESCRIPTORS,\n DESKTOP_STREAM_PORT,\n assertDescriptorRegistryInvariants,\n type CapabilityDescriptor,\n} from \"./capabilities\";\nexport {\n SandboxConfigError,\n SandboxExactResumeInstanceUnavailableError,\n SandboxExactResumeReplacedError,\n SandboxProviderContinuityUnavailableError,\n SandboxProviderUnavailableError,\n SandboxResumeIdentityMismatchError,\n SandboxResumeIdentityUnavailableError,\n SandboxResumeStateUnavailableError,\n} from \"./errors\";\nexport {\n PROVIDER_REGISTRY,\n assertProviderRegistryInvariants,\n buildImmutableProviderImage,\n isProviderApiThrottleError,\n prepareProviderForTeardownAfterCapture,\n providerSupportsImmutableImageBuild,\n renewSandboxProviderExpiration,\n providerWorkspaceCapturePolicy,\n providerWorkspaceCaptureIsPointInTime,\n type ProviderRegistration,\n type ProviderConstructionContext,\n type ProviderExactResumeMode,\n type ProviderImmutableImageBuildInput,\n type ProviderImmutableImageBuildResult,\n type ProviderExpirationRenewalInput,\n type ProviderWorkspaceCapturePolicy,\n type ProviderWorkspaceCaptureTakeover,\n} from \"./providers\";\nexport {\n classifyProviderSandboxFailure,\n isProviderSandboxGoneDuringRoutedOperation,\n isProviderSandboxNotFoundError,\n isProviderSandboxTransientError,\n type ProviderSandboxFailure,\n type ProviderSandboxFailureKind,\n} from \"./provider-errors\";\nexport {\n WORKSPACE_ARCHIVE_DESCRIPTOR_VERSION,\n WorkspaceArchiveIntegrityError,\n captureVerifiedWorkspaceArchive,\n decodeNativeSnapshotRef,\n encodeNativeSnapshotRef,\n describeLegacyNativeSnapshotArchive,\n describeNativeSnapshotArchive,\n fingerprintSandboxWorkspace,\n inlineWorkspaceArchiveForRestore,\n parseWorkspaceArchiveDescriptor,\n readVerifiedWorkspaceArchive,\n verifyRestoredWorkspace,\n type NativeSnapshotDescriptor,\n type NativeSnapshotProvider,\n type NativeSnapshotRef,\n type TarWorkspaceArchiveDescriptor,\n type VerifiedWorkspaceArchive,\n type WorkspaceArchiveDescriptor,\n type WorkspaceArchiveIntegrityCode,\n type WorkspaceTreeFingerprint,\n} from \"./workspace-archive\";\nexport {\n ToolCallCommandNotStartedError,\n toolCallCommandNotStartedCallIds,\n withCommandNotStartedCallProof,\n} from \"./tool-call-command-not-started\";\nexport {\n ensureModalRegistryImage,\n deleteModalCheckpointSnapshot,\n inspectModalSandboxLifecycle,\n isModalTaskExecStartPreDispatchUnavailableError,\n isModalCommandStartOutcomeUnknownError,\n modalSessionMatchesCheckpointProviderBinding,\n modalSandboxAttributionEnvironment,\n modalSandboxAttributionTags,\n resolveModalCheckpointProviderBinding,\n findModalProviderCreateReceipt,\n resolveModalCheckpointProviderBindingForLiveSandbox,\n resolveModalCheckpointProviderBindingForSession,\n modalAppHasRunningSandboxes,\n sweepModalOrphanSandboxes,\n tagModalSandbox,\n terminateModalSandboxById,\n type LiveModalSandboxLeaseAttribution,\n type ModalModuleLoader,\n type ModalCheckpointProviderBinding,\n type ModalOrphanSweepResult,\n type ModalOrphanSweepTermination,\n type ModalSandboxAttribution,\n type RevalidateModalOrphanTermination,\n} from \"./providers/modal\";\nexport {\n getModalCommandStartInvocation,\n withModalCommandStartSignal,\n type ModalCommandStartInvocation,\n} from \"./providers/modal-command-start-errors\";\n// Pure correlation only: these passive exports grant no dispatch authority.\nexport {\n compileNativeFreshCreate,\n describeNativeFreshCreate,\n type NativeFreshCreateSpec,\n type NativeFreshCreatePreparation,\n type NativeFreshCreateCompilation,\n} from \"./providers/modal-native-create-preparation\";\nexport {\n OpenSandboxClient,\n OpenSandboxSession,\n setOpenSandboxApplyDiff,\n type OpenSandboxApplyDiff,\n type OpenSandboxClientOptions,\n type OpenSandboxEditor,\n type OpenSandboxSessionState,\n} from \"./providers/opensandbox-adapter\";\nexport {\n selectBackend,\n sdkBackendIdForSandboxBackend,\n sandboxBackendForSdkBackendId,\n backendSupportsOs,\n desktopCapableBackend,\n negotiateCapabilities,\n type NegotiationContext,\n} from \"./select\";\n\n// Scoped data-plane stream-token mint/verify (P3.1). Agent-loop-free; the API\n// pulls these from this leaf to authorize the desktop pixel plane.\nexport {\n STREAM_TOKEN_DEFAULT_TTL_SECONDS,\n mintStreamToken,\n verifyStreamToken,\n StreamTokenPayload,\n type MintStreamTokenInput,\n type StreamTokenPayloadType,\n} from \"./stream-token\";\n\n// The Channel-B desktop display-stack launcher (P4.1). Exec-launched,\n// flock-idempotent; the worker (per-turn) and the API (per viewer op) both drive\n// it from this leaf to bring up Xvfb -> XFCE -> x11vnc -viewonly -> websockify:6080.\nexport {\n STREAM_PORT,\n DISPLAY_STACK_TIMEOUT_MS,\n DEFAULT_DESKTOP_GEOMETRY,\n DisplayStackError,\n DisplayStackUnsupportedError,\n buildDisplayStackScript,\n ensureDisplayStack,\n tearDownDisplayStack,\n type DesktopGeometry,\n type DisplayStackCallerKind,\n type DisplayStackClassification,\n type DisplayStackTelemetryContext,\n type DisplayStackTelemetryEvent,\n type DisplayStackTelemetryStatus,\n type EnsureDisplayStackOptions,\n type EnsureDisplayStackResult,\n} from \"./display-stack\";\n\nexport {\n sandboxCommandExitCode,\n sandboxCommandOutput,\n sandboxCommandStdout,\n sandboxCommandStillRunning,\n} from \"./command-result\";\n\nexport {\n createTurnToolCancellationController,\n TurnSandboxCommandCancelledError,\n} from \"./turn-tool-cancellation\";\nexport type {\n TurnSandboxCommandArgs,\n TurnSandboxCommandSession,\n TurnToolCancellationController,\n TurnToolCancellationFence,\n} from \"./turn-tool-cancellation\";\n\n// The Channel-B REAL PTY terminal-server launcher (P5.t). Exec-launched,\n// flock-idempotent twin of ensureDisplayStack; brings up ttyd PTY-over-websocket\n// (bash -l per ws client) on 7681 over the SAME tunnel the desktop noVNC uses.\nexport {\n TERMINAL_STREAM_PORT,\n TERMINAL_SERVER_TIMEOUT_MS,\n TerminalServerError,\n TerminalServerUnsupportedError,\n buildTerminalServerScript,\n ensureTerminalServer,\n tearDownTerminalServer,\n type EnsureTerminalServerOptions,\n type EnsureTerminalServerResult,\n} from \"./terminal-server\";\n\nexport {\n BROWSER_CONTROL_PORT,\n BROWSER_CONTROL_SERVER_TIMEOUT_MS,\n BrowserControlServerError,\n BrowserControlServerUnsupportedError,\n buildBrowserControlServerScript,\n ensureBrowserControlServer,\n tearDownBrowserControlServer,\n type EnsureBrowserControlServerOptions,\n type EnsureBrowserControlServerResult,\n} from \"./browser-control-server\";\n\nexport {\n BROWSER_CONTROL_ADMIN_TOKEN_FILE,\n BrowserControlClient,\n BrowserControlProtocolError,\n BrowserControlRequestError,\n BrowserControlSessionClient,\n BrowserControlTransportError,\n BrowserControlUnsupportedError,\n ComputerFrameEvidenceMismatchError,\n decodeComputerControlFrameMetadataHeader,\n provisionBrowserControlClient,\n validateComputerControlFrameEvidence,\n type BrowserControlPlacementSession,\n type BrowserControlScreenshotOptions,\n type BrowserControlFrame,\n type BrowserStateDownloadGrant,\n type BrowserStateUploadGrant,\n type BrowserViewGrant,\n type CapturePlacementBrowserStateInput,\n type CreatePlacementBrowserSessionInput,\n type PlacementBrowserSession,\n type PlacementBrowserSessionReference,\n type PlacementBrowserNetworkRoute,\n type PlacementBrowserTransport,\n type PlacementBrowserStateCaptureReceipt,\n type PlacementBrowserWorkingCopyAdoption,\n type PlacementBrowserWorkingCopyAuthority,\n type PlacementBrowserWorkingCopyInspection,\n type PlacementBrowserWorkingCopyRefusal,\n type ComputerControlFrame,\n type ComputerControlFrameMetadata,\n type ComputerFrameEvidenceMismatchReason,\n type ExpectedComputerFrameEvidence,\n type ProvisionBrowserControlClientInput,\n type ProvisionBrowserControlClientResult,\n type RestorePlacementBrowserStateInput,\n} from \"./browser-control-client\";\n\n// Host-owned rotating run credentials. Material lives outside the persisted\n// workspace/manifest and is activated atomically per session generation.\nexport {\n RunCredentialValidationError,\n normalizeRunCredentialsResolution,\n runCredentialRoot,\n runCredentialPointerFile,\n materializeRunCredentials,\n clearRunCredentials,\n clearRunCredentialsForAttempt,\n withRunCredentialEnvironment,\n withRunCredentialsSession,\n withRunCredentialsClient,\n type RunCredentialExpectedScope,\n type NormalizedRunCredentialMaterial,\n type RunCredentialCommandSession,\n type RunCredentialCommandRunner,\n type RunCredentialSessionReady,\n type MaterializeRunCredentialsOptions,\n} from \"./run-credentials\";\n\n// Secret references delivered at the physical exec boundary (W1). Values ride\n// an in-memory carry to the provider call; recorders keep references.\nexport {\n SECRET_ENV_TOTAL_MAX_BYTES,\n SECRET_ENV_VALUE_MAX_BYTES,\n SECRET_FILE_ROOT,\n clearSecretFilesCommand,\n prepareSecretExec,\n prepareSecretStdin,\n resolveSecretImagePath,\n resolveSecretLiteralText,\n resolveSecretPatchText,\n runWithSecretCarry,\n secretExecCarryFor,\n secretFilePath,\n secretScopeFor,\n type SecretCarry,\n type SecretExecCarry,\n type SecretStdinCarry,\n} from \"./secret-delivery\";\n\n// Session-specific Codemode token routing. The manifest retains one stable\n// legacy pointer for warm-box env parity; every session command selects its own\n// hashed token file off-manifest.\nexport {\n CodemodeTokenPathError,\n codemodeTokenFileForSession,\n codemodeTokenFileFromEnvironment,\n withCodemodeTokenEnvironment,\n withCodemodeTokenSession,\n withCodemodeTokenClient,\n} from \"./codemode-token\";\n\n// Exact-attempt Codemode authority. Shared by ordinary turn execution and\n// one-off Connected Machine execution so neither surface can drift into a\n// second token shape or lifetime.\nexport {\n CODEMODE_TOKEN_TTL_SECONDS,\n mintSandboxCodemodeToken,\n type CodemodeAuthorityScope,\n type SandboxCodemodeAuthority,\n type MintedSandboxCodemodeToken,\n} from \"./codemode-authority\";\n\n// The Channel-B pixel DATA PLANE (P4.2). Resolves the provider's scoped tunnel\n// for port 6080 (client → provider-tunnel direct), assembles the WS URL, and\n// mints the scoped stream token. Called API-direct on the resumed handle.\nexport {\n exposeStreamPort,\n buildStreamUrl,\n exposedPortAllowsHostFetch,\n exposedPortEndpointFromUrl,\n isOpenSandboxLifecycleProxyPath,\n joinExposedPortPath,\n parseOpenSandboxSignedUriPath,\n redactOpenSandboxSignedUriPath,\n signedEndpointExpiresAtMs,\n signedEndpointNeedsRefresh,\n StreamPortUnavailableError,\n type ExposedPortEndpoint,\n type ExposeStreamPortInput,\n type ExposeStreamPortResult,\n type OpenSandboxSignedUriPath,\n} from \"./stream-port\";\n\n// P4.3 recording loop — plain functions over a live session handle (no agent\n// loop); finalize uploads box -> object storage without buffering in the worker.\nexport {\n startRecording,\n stopRecording,\n inspectRecordingArtifact,\n uploadRecordingArtifact,\n deleteRecordingArtifacts,\n recordingStorageKey,\n contentTypeForCodec,\n extForCodec,\n RecordingUnavailableError,\n RecordingError,\n type RecordingCodec,\n type RecordingContentType,\n type StartRecordingInput,\n type RecordingProcess,\n type RecordingArtifactMetadata,\n} from \"./recording\";\n\n// P4.4 Channel-A structured services — the provider-agnostic SandboxChannelAService\n// (FileSystem + Git + Terminal) over a live, resumed-by-id session handle. The\n// API constructs one per request around the box it just resumed; no ownership.\n// Agent-loop-free, so the API-direct control plane imports it from this leaf.\nexport { SynchronousCommandOutcomeUnknownError } from \"./synchronous-command\";\nexport {\n SandboxChannelAService,\n ChannelAPartialMutationError,\n ChannelAValidationError,\n ChannelAUnavailableError,\n ChannelAConflictError,\n ChannelAFileSystemRouteChangedError,\n ChannelANotFoundError,\n ChannelAUnsupportedError,\n stripExecBanner,\n parseExecBannerSessionId,\n parseExecBannerExitCode,\n isExecSessionLostBanner,\n assertSafeRelPath,\n parsePorcelainV2,\n parseNumstatZ,\n parseUnifiedPatch,\n REPOSITORY_DISCOVERY_LIMIT,\n CODE_SEARCH_RG_MAX_BYTES,\n validateCodeSearchRipgrepArgs,\n type CodeSearchRipgrepOutcome,\n type ChannelASession,\n type ChannelAExecArgs,\n type ChannelAExecResult,\n type ChannelAEmitter,\n type SandboxChannelAServiceOptions,\n type FsWriteFilesRequest,\n type FsWriteFilesResponse,\n type RepositoryDiscoveryDegradedReason,\n type RepositoryDiscoveryResult,\n type NumstatEntry,\n} from \"./channel-a\";\n\n// The selfhosted (bring-your-own-compute) control surface (M3). The NATS-backed\n// `SelfhostedSession` presents the SAME structural exec/fs/git surface as Modal\n// over a `ControlRpc` seam (request/reply on the exact claimed process subject, encoded via\n// `@opengeni/agent-proto`). agent-offline is NEVER a NotFound — the lease never\n// cold-creates a rival for a user's real machine. The real NATS transport +\n// Accounts land in M4 behind the SAME `ControlRpc`.\nexport {\n type ControlRpc,\n NatsControlRpc,\n SelfhostedControlError,\n agentErrorToControlError,\n subjectFor,\n offlineControlResponse,\n timeoutControlResponse,\n offlineAgentError,\n timeoutAgentError,\n drainingExhaustedError,\n payloadTooLargeMessage,\n drainingMessage,\n execDeadlineHint,\n NEVER_SENT_DETAIL_KEY,\n type NatsRequestConnection,\n type SelfhostedUnavailableReason,\n} from \"./selfhosted/control-rpc\";\n// The transport-agnostic per-op observation seam (out-of-band telemetry — metrics\n// + machine.* events; the op-engine's op-stream client emits through this too).\nexport type { SelfhostedOpObserver, SelfhostedOpObservation } from \"./selfhosted/op-observer\";\n// The four-field in-band fault renderer (the failure-visibility doctrine).\nexport {\n selfhostedFaultClass,\n SELFHOSTED_INFRASTRUCTURE_FAULT_CLASSES,\n renderSelfhostedFault,\n FAULT_FIELD_WHAT_HAPPENED,\n FAULT_FIELD_WHICH_LAYER,\n FAULT_FIELD_WHAT_PRESERVED,\n FAULT_FIELD_WHAT_TO_TRY,\n} from \"./selfhosted/fault-rendering\";\n// The selfhosted control-op retry policy (the pure decision + the injected clock).\nexport {\n decideSelfhostedRetry,\n selfhostedRetryBackoffMs,\n defaultSelfhostedRetryClock,\n SELFHOSTED_IDEMPOTENT_READONLY_OPS,\n SELFHOSTED_DRAINING_MAX_RETRIES,\n SELFHOSTED_EXEC_DRAINING_MAX_RETRIES,\n SELFHOSTED_TIMEOUT_MAX_RETRIES,\n SELFHOSTED_NEVER_SENT_MAX_RETRIES,\n SELFHOSTED_RETRY_BACKOFF_BASE_MS,\n SELFHOSTED_RETRY_BACKOFF_FACTOR,\n SELFHOSTED_RETRY_BACKOFF_CAP_MS,\n type SelfhostedRetryClock,\n type SelfhostedRetryDecision,\n} from \"./selfhosted/retry-policy\";\nexport {\n SelfhostedSession,\n SelfhostedWorkspaceRootChangedError,\n SelfhostedSandboxClient,\n buildSelfhostedBackendSession,\n isSelfhostedProviderNotFoundError,\n setSelfhostedApplyDiff,\n SELFHOSTED_DEFAULT_TIMEOUT_MS,\n SELFHOSTED_RELAY_STREAM_PATH,\n type SelfhostedSessionState,\n type SelfhostedSessionDeps,\n type SelfhostedSessionBuild,\n type SelfhostedOperationResourcePolicy,\n type SelfhostedOperationAdmission,\n type SelfhostedRelayConfig,\n type SelfhostedExecArgs,\n type SelfhostedExecResult,\n type SelfhostedApplyDiff,\n type SelfhostedEditor,\n type SelfhostedImageOutput,\n type SelfhostedOpStreamDeps,\n} from \"./selfhosted/session\";\nexport {\n connectedMachinePathWithinRoot,\n connectedMachineWorkspaceRootsEqual,\n isConnectedMachineAbsolutePath,\n isWindowsConnectedMachinePath,\n normalizeConnectedMachineWorkspaceRoot,\n relativeConnectedMachinePath,\n resolveConnectedMachinePath,\n resolveConnectedMachineWorkspaceRoot,\n type ConnectedMachineOs,\n} from \"./selfhosted/workspace-path\";\nexport type { SelfhostedConnectionBinding } from \"./routing/backend-resolver\";\n// The op-stream exec transport (op-stream protocol v1.1 — streaming exec to a\n// Connected Machine runner). The worker injects `NatsOpStreamTransport` (over\n// the same bus connection as the control rpc) plus an `OpStreamJournal`\n// adapted onto Temporal. Connected Machine exec requires this injection and\n// fails closed when it is absent or unsupported.\nexport {\n NatsOpStreamTransport,\n OpStreamUnavailableError,\n opAckSubject,\n opFrameSubject,\n type NatsOpStreamConnection,\n type OpStreamSubscription,\n type OpStreamTransport,\n} from \"./selfhosted/op-transport\";\nexport {\n cancelSelfhostedOp,\n OP_STREAM_ACK_INTERVAL_MS,\n OP_STREAM_DEFAULT_WINDOW_BYTES,\n OP_STREAM_RECONNECT_HOLD_MS,\n OP_STREAM_SILENCE_TIMEOUT_MS,\n querySelfhostedOp,\n type ExactSelfhostedOpControlInput,\n type OpStreamExecOutcome,\n type OpStreamJournal,\n} from \"./selfhosted/op-stream\";\n// The durable op-id correlation seam (B1): the runtime barrel BINDS it around\n// the SDK shell tool; the sandbox leaf READS it when minting op ids.\nexport { nextDurableOpId, runWithToolCallCorrelation, sanitizeOpIdToken } from \"./op-correlation\";\nexport {\n negotiateSelfhostedCapabilities,\n selfhostedLiveness,\n selfhostedHeartbeatLiveness,\n SELFHOSTED_RECONNECT_WINDOW_MS,\n type SelfhostedNegotiationInput,\n type SelfhostedLivenessState,\n type SelfhostedEnrollment,\n} from \"./selfhosted/capabilities\";\nexport {\n MockAgentResponder,\n type MockAgentResponderOptions,\n type MockExecHandler,\n} from \"./selfhosted/testing\";\nexport {\n createMockSelfhostedOpStream,\n FakeOpRunner,\n type FakeOpScript,\n InMemoryOpStreamTransport,\n} from \"./selfhosted/op-testing\";\n\n// The hot-swap routing proxy (M7): ONE stable session-shaped object the SDK binds\n// to, which re-reads the per-session active pointer per op and dispatches to the\n// currently-active backend (Modal or selfhosted) — flippable mid-turn, single\n// active at a time, fence-retrying on a swap race.\nexport {\n isRoutingMutationOutcomeUnknownError,\n isRoutingMutationOutputRejectedError,\n RoutingMutationOutputRejectedError,\n withRoutingMutationOutputRejectionFence,\n RoutingBackendRecoveryRequiredError,\n RoutingMutationOutcomeUnknownError,\n renderRoutingMutationOutcomeUnknownToolResult,\n RoutingRetainedProcessNotFoundError,\n RoutingSandboxSession,\n RoutingWorkspaceRootChangedError,\n RoutingActiveRouteChangedError,\n RoutingUnsupportedError,\n type ActivePointer,\n type DefaultBackendLossResult,\n type RoutableBackendSession,\n type ResolvedActiveBackend,\n type RoutingMutationSettlementResult,\n type RoutingSandboxFirstOperationObservation,\n type RoutingSandboxFirstOperationObserver,\n type RoutingSandboxFirstOperationPhase,\n type RoutingSandboxFirstOperationPhaseObservation,\n type RoutingSandboxOperationObservation,\n type RoutingSandboxOperationObserver,\n type RoutingSandboxCaptureWaitObserver,\n type RoutingSandboxPhaseOutcome,\n type RoutingSandboxWaitObservation,\n type RoutingRetainedProcess,\n type RoutingRetainedProcessAdoption,\n type RoutingRetainedProcessTerminalProof,\n type RoutingSandboxSessionDeps,\n type RoutingTransitionEvent,\n} from \"./routing/routing-session\";\nexport {\n makeActiveBackendResolver,\n ActiveBackendUnresolvableError,\n swapTargetEstablishability,\n type ActiveBackendResolverDeps,\n type RoutableSandbox,\n type BackendUnresolvableCode,\n type SwapTargetEstablishability,\n} from \"./routing/backend-resolver\";\n\n/**\n * Construct the raw provider SandboxClient for the configured backend. Registry-\n * driven (the old flat if/else is gone): the backend's ProviderRegistration owns\n * validateCredentials + build, with per-provider units/field-names. Returns\n * undefined for \"none\".\n *\n * The desktop stream port (6080) is merged into exposedPorts for every desktop-\n * capable (backend, os) when desktop is enabled AND the provider cannot expose\n * ports on demand (modal/runloop/e2b pre-declare; blaxel resolves on demand).\n * Existing modal/docker/local construction is behavior-preserved.\n */\nexport function createSandboxClient(\n settings: Settings,\n environment = collectSandboxEnvironment(settings),\n): unknown {\n return createSandboxClientForBackend(\n settings.sandboxBackend as SandboxBackend,\n settings,\n environment,\n );\n}\n\n/**\n * Construct the raw provider SandboxClient for an EXPLICIT backend, independent\n * of settings.sandboxBackend. This is the resume-by-id builder the per-turn\n * resume path (and the API-direct control plane) call: a lease's box was created\n * on a specific backend (the envelope's backendId / the lease's\n * resume_backend_id), and the client that reattaches to it must be built for\n * THAT backend, not the process's currently-configured default. When the backend\n * equals settings.sandboxBackend this is identical to createSandboxClient\n * (behavior-preserved). Returns undefined for \"none\".\n */\nexport function createSandboxClientForBackend(\n backend: SandboxBackend,\n settings: Settings,\n environment = collectSandboxEnvironment(settings),\n metrics?: RuntimeMetricsHooks,\n): unknown {\n const registration = PROVIDER_REGISTRY[backend];\n if (!registration) {\n throw new SandboxConfigError(backend, `Unknown sandbox backend \"${backend}\"`);\n }\n if (registration.backend === \"none\") {\n return undefined;\n }\n registration.validateCredentials(settings); // fail-fast, typed\n\n const exposedPorts = parseExposedPorts(settings.dockerExposedPorts);\n // 6080 port-merge: a desktop-capable backend that pre-declares ports (not\n // on-demand) must carry the desktop port at construction so resolveExposedPort\n // (6080) succeeds later. runloop is included (it is desktop-capable but NOT\n // on-demand → must pre-declare). blaxel is on-demand → skipped here.\n const desktop = registration.descriptor.capabilities.DesktopStream;\n if (\n desktop.available &&\n settings.sandboxDesktopEnabled &&\n !registration.descriptor.portExposure.supportsOnDemandPorts &&\n !exposedPorts.includes(DESKTOP_STREAM_PORT)\n ) {\n exposedPorts.push(DESKTOP_STREAM_PORT);\n }\n // 7681 port-merge: the REAL PTY terminal (ttyd) rides the SAME tunnel as the\n // desktop, so a desktop-capable pre-declared-port backend must ALSO carry 7681\n // at construction for resolveExposedPort(7681) to succeed later on a fresh box.\n // Same condition as the 6080 merge (a desktop-capable image bakes ttyd too).\n if (\n desktop.available &&\n settings.sandboxTerminalEnabled &&\n !registration.descriptor.portExposure.supportsOnDemandPorts &&\n !exposedPorts.includes(TERMINAL_STREAM_PORT)\n ) {\n exposedPorts.push(TERMINAL_STREAM_PORT);\n }\n // The browser controller is a placement service baked into both canonical\n // images. Providers that require port declaration must receive its fixed\n // port when the box is created; on-demand providers resolve it lazily.\n if (\n !registration.descriptor.portExposure.supportsOnDemandPorts &&\n !exposedPorts.includes(BROWSER_CONTROL_PORT)\n ) {\n exposedPorts.push(BROWSER_CONTROL_PORT);\n }\n\n const raw = withProviderExactResumeContract(\n registration,\n registration.build({\n settings,\n environment,\n exposedPorts,\n ...(metrics ? { metrics } : {}),\n }),\n );\n // Docker network decoration stays backend-specific (only docker).\n return registration.backend === \"docker\"\n ? withDockerNetwork(raw as SandboxClient, settings.dockerNetwork)\n : raw;\n}\n\nfunction withProviderExactResumeContract(\n registration: ProviderRegistration,\n raw: unknown,\n): unknown {\n if (!raw || typeof raw !== \"object\") {\n throw new SandboxConfigError(\n registration.backend,\n `Sandbox backend \"${registration.backend}\" returned no client`,\n );\n }\n const client = raw as {\n resume?: (state: unknown, options?: unknown) => Promise<unknown>;\n resumeExact?: (state: unknown) => Promise<unknown>;\n };\n if (typeof client.resume !== \"function\") {\n throw new SandboxConfigError(\n registration.backend,\n `Sandbox backend \"${registration.backend}\" does not support resume()`,\n );\n }\n if (registration.exactResumeMode === \"custom\") {\n if (typeof client.resumeExact !== \"function\") {\n throw new SandboxConfigError(\n registration.backend,\n `Sandbox backend \"${registration.backend}\" has no non-replacing resumeExact()`,\n );\n }\n return client;\n }\n if (registration.exactResumeMode !== \"ordinary\") {\n throw new SandboxConfigError(\n registration.backend,\n `Sandbox backend \"${registration.backend}\" has an invalid exact-resume contract`,\n );\n }\n const resume = client.resume;\n Object.defineProperty(client, \"resumeExact\", {\n configurable: false,\n enumerable: false,\n writable: false,\n value: async (state: unknown) => await resume.call(client, state),\n });\n return client;\n}\n\nfunction withDockerNetwork(client: SandboxClient, network: string | undefined): SandboxClient {\n const trimmed = network?.trim();\n if (!trimmed) {\n return client;\n }\n const exactResume = (\n client as SandboxClient & {\n resumeExact?: (state: SandboxSessionState) => Promise<SandboxSessionLike>;\n }\n ).resumeExact;\n const wrapSession = async <T extends SandboxSessionLike>(session: T): Promise<T> => {\n const containerId = (session as { state?: { containerId?: unknown } }).state?.containerId;\n if (typeof containerId === \"string\" && containerId.length > 0) {\n await connectDockerNetwork(trimmed, containerId);\n const portResolver = (\n session as T & {\n resolveExposedPort?: (port: number) => Promise<ExposedPortEndpoint>;\n }\n ).resolveExposedPort;\n if (typeof portResolver === \"function\") {\n Object.defineProperty(session, \"resolveExposedPort\", {\n configurable: true,\n enumerable: true,\n writable: true,\n value: async (port: number) =>\n dockerNetworkExposedPortEndpoint(\n containerId,\n port,\n await portResolver.call(session, port),\n ),\n });\n }\n }\n return session;\n };\n return {\n backendId: client.backendId,\n ...(client.supportsDefaultOptions !== undefined\n ? { supportsDefaultOptions: client.supportsDefaultOptions }\n : {}),\n ...(client.create\n ? {\n create: async (...args: any[]) =>\n await wrapSession(await (client.create as any)(...args)),\n }\n : {}),\n ...(client.resume\n ? {\n resume: async (state: SandboxSessionState) =>\n await wrapSession(await client.resume!(state)),\n }\n : {}),\n ...(exactResume\n ? {\n // Docker's ordinary SDK resume creates a replacement when the exact\n // container is absent. Preserve Opengeni's non-replacing attach path\n // through the network decorator; dropping it would turn an exact\n // recovery probe into a provider mutation.\n resumeExact: async (state: SandboxSessionState) =>\n await wrapSession(await exactResume.call(client, state)),\n }\n : {}),\n ...(\"attachWorkspaceForDrain\" in client && typeof client.attachWorkspaceForDrain === \"function\"\n ? {\n // A drain handle has no networking or normal execution capability.\n attachWorkspaceForDrain: client.attachWorkspaceForDrain.bind(client),\n }\n : {}),\n ...(client.delete\n ? {\n delete: async (state: SandboxSessionState) => await client.delete!(state),\n }\n : {}),\n ...(client.serializeSessionState\n ? {\n serializeSessionState: async (state: SandboxSessionState, options) =>\n await client.serializeSessionState!(state, options),\n }\n : {}),\n ...(client.canPersistOwnedSessionState\n ? {\n canPersistOwnedSessionState: async (state: SandboxSessionState) =>\n await client.canPersistOwnedSessionState!(state),\n }\n : {}),\n ...(client.canReusePreservedOwnedSession\n ? {\n canReusePreservedOwnedSession: async (state: SandboxSessionState) =>\n await client.canReusePreservedOwnedSession!(state),\n }\n : {}),\n ...(client.deserializeSessionState\n ? {\n deserializeSessionState: async (state: Record<string, unknown>) =>\n await client.deserializeSessionState!(state),\n }\n : {}),\n };\n}\n\n/**\n * Once a Docker sandbox joins the API's network, server-side traffic must use\n * the container's network identity and original port. The SDK's published\n * 127.0.0.1 host port is meaningful only to the Docker host, not to an API\n * process running in another container. Calling the provider resolver first\n * preserves its exposed-port validation.\n */\nexport function dockerNetworkExposedPortEndpoint(\n containerId: string,\n containerPort: number,\n endpoint: ExposedPortEndpoint,\n): ExposedPortEndpoint {\n const host = /^[a-f0-9]{64}$/i.test(containerId) ? containerId.slice(0, 12) : containerId;\n return {\n ...endpoint,\n host,\n port: containerPort,\n };\n}\n\nasync function connectDockerNetwork(network: string, containerId: string): Promise<void> {\n const { spawnSync } = await import(\"node:child_process\");\n const result = spawnSync(\"docker\", [\"network\", \"connect\", network, containerId], {\n encoding: \"utf8\",\n });\n if (result.status === 0) {\n return;\n }\n const stderr = result.stderr ?? result.error?.message ?? \"\";\n if (stderr.includes(\"already exists\")) {\n return;\n }\n throw new Error(\n `Failed to connect Docker sandbox container to network ${network}: ${stderr.trim()}`,\n );\n}\n\n/**\n * Extract the sandbox recovery entry from a run state as a plain JSON record,\n * for storage decoupled from the RunState blob (issue #35). Encapsulates the\n * underscore-internal `_sandbox` read in exactly one place.\n */\nexport function sandboxStateEntryFromRunState(\n state: unknown,\n options: {\n /** W1 defensive strip: when set, persisted manifest/state env keeps only\n * names this predicate accepts (deployment constants), so a legacy box\n * whose live state still carries user values never re-persists them. */\n keepEnvironmentName?: (name: string) => boolean;\n } = {},\n): Record<string, unknown> | null {\n const sandboxState = (state as any)?._sandbox;\n if (!sandboxState) {\n return null;\n }\n const entry =\n sandboxState.sessionsByAgent?.[sandboxState.currentAgentKey] ??\n (sandboxState.currentAgentKey && sandboxState.sessionState\n ? {\n backendId: sandboxState.backendId,\n currentAgentKey: sandboxState.currentAgentKey,\n currentAgentName: sandboxState.currentAgentName,\n sessionState: sandboxState.sessionState,\n }\n : null);\n if (!entry || !entry.sessionState) {\n return null;\n }\n const persisted = sandboxEntryForPersistence(entry as Record<string, unknown>);\n return normalizeProtocolJsonValue(\n options.keepEnvironmentName\n ? sandboxEntryWithConstantEnvironment(persisted, options.keepEnvironmentName)\n : persisted,\n '$[\"sandboxSessionEnvelope\"]',\n ) as Record<string, unknown>;\n}\n\nfunction filterEnvironmentRecord(value: unknown, keep: (name: string) => boolean): unknown {\n if (!isObjectRecord(value)) return value;\n return Object.fromEntries(Object.entries(value).filter(([name]) => keep(name)));\n}\n\n/** Copy of a persisted entry whose `sessionState.manifest.environment`,\n * `sessionState.environment` and `sessionState.providerState.environment` keep\n * only accepted names. Values are never inspected. */\nexport function sandboxEntryWithConstantEnvironment(\n entry: Record<string, unknown>,\n keep: (name: string) => boolean,\n): Record<string, unknown> {\n const sessionState = entry.sessionState;\n if (!isObjectRecord(sessionState)) return entry;\n const next: Record<string, unknown> = { ...sessionState };\n const manifest = sessionState.manifest;\n if (isObjectRecord(manifest) && Object.hasOwn(manifest, \"environment\")) {\n const plain =\n Object.getPrototypeOf(manifest) === Object.prototype ||\n Object.getPrototypeOf(manifest) === null\n ? manifest\n : (serializeSdkManifestForEnvelope(manifest) as Record<string, unknown>);\n next.manifest = { ...plain, environment: filterEnvironmentRecord(plain.environment, keep) };\n }\n if (Object.hasOwn(sessionState, \"environment\")) {\n next.environment = filterEnvironmentRecord(sessionState.environment, keep);\n }\n const providerState = sessionState.providerState;\n if (isObjectRecord(providerState) && Object.hasOwn(providerState, \"environment\")) {\n next.providerState = {\n ...providerState,\n environment: filterEnvironmentRecord(providerState.environment, keep),\n };\n }\n return { ...entry, sessionState: next };\n}\n\n/**\n * The Agents SDK session envelope carries its canonical serialized manifest at\n * `sessionState.manifest`. Some provider serializers also repeat a hydrated\n * `Manifest` instance at `sessionState.providerState.manifest`; the SDK restore\n * path always overlays the canonical outer value, so the duplicate is neither\n * read nor JSON-protocol-safe. Remove only that known redundant field before the\n * envelope crosses Opengeni's durable canonical-JSON boundary.\n */\nfunction sandboxEntryForPersistence(entry: Record<string, unknown>): Record<string, unknown> {\n const sessionState = entry.sessionState;\n if (!isObjectRecord(sessionState) || !Object.hasOwn(sessionState, \"manifest\")) {\n return entry;\n }\n const providerState = sessionState.providerState;\n if (!isObjectRecord(providerState) || !Object.hasOwn(providerState, \"manifest\")) {\n return entry;\n }\n const { manifest: _redundantManifest, ...canonicalProviderState } = providerState;\n return {\n ...entry,\n sessionState: {\n ...sessionState,\n providerState: canonicalProviderState,\n },\n };\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction providerStateWithoutDuplicateManifest(value: object): Record<string, unknown> {\n const { manifest: _manifest, ...providerState } = value as Record<string, unknown>;\n return providerState;\n}\n\nfunction serializeSdkManifestForEnvelope(value: unknown): unknown {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return value;\n const prototype = Object.getPrototypeOf(value);\n if (prototype === Object.prototype || prototype === null) return value;\n return serializeManifestRecord(value as Manifest);\n}\n\n/**\n * Items-mode counterpart of restoredSandboxSessionState: rebuild the live\n * sandbox session state from a stored entry (as produced by\n * sandboxStateEntryFromRunState) instead of from a RunState blob.\n */\nexport async function restoredSandboxSessionStateFromEntry(\n entry: Record<string, unknown>,\n client: unknown,\n): Promise<SandboxSessionState | undefined> {\n if (!client || !entry || typeof entry !== \"object\" || !(\"sessionState\" in entry)) {\n return undefined;\n }\n if (entry.backendId && (client as SandboxClient).backendId !== entry.backendId) {\n throw new Error(\"Stored sandbox envelope backend does not match the configured sandbox client\");\n }\n return await deserializeSandboxSessionStateEnvelope(client as SandboxClient, entry.sessionState);\n}\n\n/**\n * Read the persisted /workspace snapshot archive off a lease envelope's\n * `sessionState` (sandbox-file-persistence). The reaper (persistDrainSnapshot)\n * folds the base64 archive — a Modal native snapshot-ref or a tar archive, the\n * exact bytes `session.persistWorkspace()` returned — at\n * `sessionState.workspaceArchive`. Cold-restore decodes it and replays it via\n * `session.hydrateWorkspace(archive)` on the freshly-created box so /workspace is\n * restored. Returns undefined when the envelope carries no archive (a box that\n * was never drain-persisted, or a non-persistence config that stored none).\n *\n * It is deliberately read SEPARATELY from deserializeSandboxSessionStateEnvelope:\n * the archive does NOT ride serializeSessionState (it originates at reaper time),\n * and the SDK's deserializeSessionState must NOT receive it (it is an opaque\n * runtime-level field, not provider state).\n */\nexport function readWorkspaceArchiveFromEnvelopeSessionState(\n sessionState: unknown,\n): Uint8Array | undefined {\n if (!sessionState || typeof sessionState !== \"object\") {\n return undefined;\n }\n const b64 = (sessionState as { workspaceArchive?: unknown }).workspaceArchive;\n if (typeof b64 !== \"string\" || b64.length === 0) {\n return undefined;\n }\n try {\n return Uint8Array.from(Buffer.from(b64, \"base64\"));\n } catch {\n return undefined;\n }\n}\n\n/** Decode the Modal snapshot id out of a persisted base64 archive ref, or\n * undefined when the archive is a tar payload or is unparseable. */\nexport function decodeModalSnapshotId(archive: Uint8Array): string | undefined {\n const ref = decodeNativeSnapshotRef(archive);\n return ref?.provider === \"modal_snapshot_filesystem\" ||\n ref?.provider === \"modal_snapshot_directory\"\n ? ref.snapshotId\n : undefined;\n}\n\nexport async function deserializeSandboxSessionStateEnvelope(\n client: SandboxClient,\n envelope: unknown,\n expectedInstanceId?: string,\n): Promise<SandboxSessionState | undefined> {\n if (!envelope || typeof envelope !== \"object\") {\n return undefined;\n }\n if (!client.deserializeSessionState) {\n throw new Error(\n \"Sandbox client must implement deserializeSessionState() to resume RunState sandbox state\",\n );\n }\n const state = envelope as {\n providerState?: Record<string, unknown>;\n manifest?: unknown;\n snapshot?: unknown;\n snapshotFingerprint?: unknown;\n snapshotFingerprintVersion?: unknown;\n workspaceReady?: unknown;\n exposedPorts?: unknown;\n };\n const providerState = { ...(state.providerState ?? {}) };\n if (expectedInstanceId) {\n const backend = sandboxBackendForSdkBackendId(client.backendId) ?? client.backendId;\n const observedInstanceId = liveProviderInstanceIdFromState(backend, providerState);\n if (observedInstanceId && observedInstanceId !== expectedInstanceId) {\n throw new SandboxResumeIdentityMismatchError(backend, expectedInstanceId, observedInstanceId);\n }\n if (!observedInstanceId) {\n const instanceIdField = PROVIDER_REGISTRY[backend as SandboxBackend]?.instanceIdFields[0];\n if (instanceIdField) {\n // New envelopes persist one provider-neutral Opengeni identity. SDK\n // deserializers still require their legacy provider-specific address,\n // so materialize it into a cloned payload at this adapter boundary.\n // The live resumed handle is independently identity-checked before use.\n providerState[instanceIdField] = expectedInstanceId;\n }\n }\n }\n const exposedPorts = runStateExposedPortsRecord(state.exposedPorts);\n if (state.exposedPorts !== undefined && exposedPorts === undefined) {\n console.warn(\"[sandbox] ignored incompatible RunState exposedPorts\", {\n provider: runStateCompatibilityProvider(client.backendId),\n sessionClass: \"root\",\n path: \"sessionState.exposedPorts\",\n });\n }\n return await client.deserializeSessionState({\n ...providerState,\n manifest: state.manifest,\n ...(state.snapshot !== undefined ? { snapshot: state.snapshot } : {}),\n ...(state.snapshotFingerprint !== undefined\n ? { snapshotFingerprint: state.snapshotFingerprint }\n : {}),\n ...(state.snapshotFingerprintVersion !== undefined\n ? { snapshotFingerprintVersion: state.snapshotFingerprintVersion }\n : {}),\n workspaceReady: state.workspaceReady,\n ...(exposedPorts !== undefined ? { exposedPorts } : {}),\n });\n}\n\n// ============================================================================\n// The ONE resume / recovery primitive (P1.2).\n//\n// establishSandboxSessionFromEnvelope is the single re-establish-from-envelope\n// path the stateless model leans on. Creation authority is explicit:\n//\n// - `create-or-restore` is reserved for the caller that won the durable\n// cold->warming lease transition. It may create a cold box, or replace a\n// resumable box that the provider proves is gone.\n// - `resume-only` is for attached turns and API-direct operations. It may\n// resume the leased box by id, but a provider NotFound propagates to the\n// caller so the lease can be atomically marked cold. It NEVER creates.\n//\n// This ownership boundary is the double-spawn guard. A provider NotFound alone\n// is not creation authority: many attached callers can observe the same dead id\n// concurrently, while only one caller may own cold->warming.\n// ============================================================================\n\n/** A live, externally-owned sandbox session re-established from the group lease\n * envelope. The caller injects `{client, session, sessionState}` NON-OWNED into\n * the run (or drives session.exec/readFile/resolveExposedPort directly) and\n * drops the handle when done — the lease, not this handle, owns the box. */\nexport type EstablishedSandboxSession = {\n client: unknown;\n session: unknown;\n sessionState: unknown;\n instanceId: string;\n backendId: string;\n /** How this establish reached a live box: warm reattach by id (\"resumed\"),\n * fresh create (\"created\"), or fresh create + archive hydration\n * (\"restored\"). Callers use it to emit the durable sandbox.box.* lifecycle\n * events — box transitions were previously unrecorded, which made both\n * 2026-07-06 incidents near-unattributable. Optional so external/legacy\n * constructors of this shape stay valid. */\n origin?: \"resumed\" | \"created\" | \"restored\";\n /** Set when a create-authorized reattach found the envelope's box GONE\n * (provider NotFound) and fell through to cold-restore. */\n lostInstanceId?: string;\n /** Durable authorization used when an elected recovery owner adopted a new\n * execution wrapper over the same provider-owned workspace. Unpublished\n * failure cleanup must preserve that workspace for the next recovery owner. */\n providerContinuity?: SandboxProviderContinuityRecovery;\n /** Exact durable archive revision verified byte-for-byte after hydration. */\n restoredArchive?: WorkspaceArchiveDescriptor;\n};\n\n/**\n * Terminate an SDK-managed provider session through the declared sandbox\n * lifecycle surface. The reaper must never guess non-standard `kill` or\n * `terminate` method names: every supported SDK provider exposes one of these\n * standard operations, while provider-specific by-id rescue stays in its\n * adapter.\n */\nexport async function terminateManagedSandboxSession(\n client: unknown,\n sessionState: unknown,\n session: unknown,\n): Promise<void> {\n const lifecycleClient = client as {\n backendId?: unknown;\n delete?: (state: never) => Promise<void>;\n };\n const lifecycleSession = session as Partial<SandboxSessionLike>;\n const options = { reason: \"cleanup\" };\n let firstError: unknown;\n const attempt = async (operation: (() => Promise<void>) | undefined): Promise<void> => {\n if (!operation) return;\n try {\n await operation();\n } catch (error) {\n firstError ??= error;\n }\n };\n const runPreStopHooks =\n typeof lifecycleSession.runPreStopHooks === \"function\"\n ? lifecycleSession.runPreStopHooks.bind(lifecycleSession)\n : undefined;\n const preStop =\n typeof lifecycleSession.preStop === \"function\"\n ? lifecycleSession.preStop.bind(lifecycleSession)\n : undefined;\n const stop =\n typeof lifecycleSession.stop === \"function\"\n ? lifecycleSession.stop.bind(lifecycleSession)\n : undefined;\n const shutdown =\n typeof lifecycleSession.shutdown === \"function\"\n ? lifecycleSession.shutdown.bind(lifecycleSession)\n : undefined;\n const deleteSession =\n typeof lifecycleSession.delete === \"function\"\n ? lifecycleSession.delete.bind(lifecycleSession)\n : undefined;\n const close =\n typeof lifecycleSession.close === \"function\"\n ? lifecycleSession.close.bind(lifecycleSession)\n : undefined;\n\n // Mirror the Agents SDK's provider-neutral cleanupSandboxSession contract.\n // Agents SDK 0.14.3 does not publicly export that helper, so this agent-loop-free leaf\n // keeps the same small sequence locally. Prefer the live session lifecycle:\n // it owns registered pre-stop hooks and provider cleanup semantics. The\n // state-only client.delete contract is a fallback when no session teardown\n // operation exists.\n await attempt(runPreStopHooks);\n await attempt(preStop ? async () => await preStop(options) : undefined);\n await attempt(stop ? async () => await stop(options) : undefined);\n await attempt(shutdown ? async () => await shutdown(options) : undefined);\n await attempt(deleteSession ? async () => await deleteSession(options) : undefined);\n const hasProviderTeardown = Boolean(stop || shutdown || deleteSession);\n if (!hasProviderTeardown && close) {\n await attempt(close);\n } else if (\n !hasProviderTeardown &&\n !close &&\n typeof lifecycleClient.delete === \"function\" &&\n sessionState !== undefined &&\n sessionState !== null\n ) {\n await attempt(async () => await lifecycleClient.delete!(sessionState as never));\n }\n if (firstError) throw firstError;\n if (\n hasProviderTeardown ||\n close ||\n (typeof lifecycleClient.delete === \"function\" &&\n sessionState !== undefined &&\n sessionState !== null)\n ) {\n return;\n }\n\n const backendId =\n typeof lifecycleClient.backendId === \"string\" ? lifecycleClient.backendId : \"unknown\";\n throw new Error(`Sandbox backend ${backendId} exposes no teardown lifecycle operation`);\n}\n\nexport class SandboxExecReadinessError extends Error {\n readonly name = \"SandboxExecReadinessError\";\n\n constructor(\n public readonly backend: string,\n public readonly code: \"exec_probe_unavailable\" | \"exec_probe_timeout\" | \"exec_probe_failed\",\n public readonly timeoutMs: number,\n public readonly exitCode: number | null = null,\n public readonly instanceId: string | null = null,\n ) {\n const target = instanceId ? `${backend} sandbox ${instanceId}` : `${backend} sandbox`;\n super(\n code === \"exec_probe_timeout\"\n ? `${target} timed out waiting for command readiness after ${timeoutMs}ms`\n : code === \"exec_probe_unavailable\"\n ? `${target} session does not expose an exec readiness probe`\n : exitCode === null\n ? `${target} exec readiness probe did not return a command exit code`\n : `${target} exec readiness probe failed with exit code ${exitCode}`,\n );\n }\n}\n\n/** A remote provider may return a sandbox handle before its command router\n * accepts exec. Allow cold restores to absorb provider tail latency without\n * publishing the lease warm before command execution is possible. */\nexport const MODAL_EXEC_READINESS_TIMEOUT_MS = 60_000;\n\nfunction sandboxExecProbeSessionId(result: unknown): number | null {\n if (typeof result === \"string\") return parseExecBannerSessionId(result);\n if (!result || typeof result !== \"object\") return null;\n const candidate = result as { sessionId?: unknown; session_id?: unknown };\n for (const value of [candidate.sessionId, candidate.session_id]) {\n if (typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0) return value;\n }\n return null;\n}\n\n/** A provider handle is not workspace readiness. Providers with asynchronous\n * startup must pass this bounded command probe before a caller publishes the\n * lease warm/ready. */\nexport async function verifySandboxExecReadiness(\n established: EstablishedSandboxSession,\n timeoutMs = MODAL_EXEC_READINESS_TIMEOUT_MS,\n signal?: AbortSignal,\n): Promise<void> {\n signal?.throwIfAborted();\n if (established.backendId !== \"modal\" && established.backendId !== \"opensandbox\") return;\n const session = established.session as {\n verifyExecReadiness?: (signal: AbortSignal) => Promise<number>;\n exec?: (args: {\n cmd: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<unknown>;\n execCommand?: (args: {\n cmd: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<unknown>;\n writeStdin?: (args: {\n sessionId: number;\n chars?: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<unknown>;\n };\n const run = session.exec ?? session.execCommand;\n const nativeModalProbe =\n established.backendId === \"modal\" ? session.verifyExecReadiness : undefined;\n if (!run && !nativeModalProbe) {\n throw new SandboxExecReadinessError(\n established.backendId,\n \"exec_probe_unavailable\",\n timeoutMs,\n null,\n established.instanceId,\n );\n }\n const timeoutError = () =>\n new SandboxExecReadinessError(\n established.backendId,\n \"exec_probe_timeout\",\n timeoutMs,\n null,\n established.instanceId,\n );\n const deadline = Date.now() + timeoutMs;\n const withinDeadline = async <T>(operation: () => Promise<T>): Promise<T> => {\n signal?.throwIfAborted();\n const remainingMs = deadline - Date.now();\n if (remainingMs <= 0) throw timeoutError();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let abort: (() => void) | undefined;\n try {\n const interrupted = new Promise<never>((_, reject) => {\n abort = () => reject(signal?.reason);\n signal?.addEventListener(\"abort\", abort, { once: true });\n if (signal?.aborted) abort();\n timer = setTimeout(() => reject(timeoutError()), remainingMs);\n if (timer && \"unref\" in timer && typeof timer.unref === \"function\") timer.unref();\n });\n const result = await Promise.race([operation(), interrupted]);\n signal?.throwIfAborted();\n return result;\n } finally {\n if (timer) clearTimeout(timer);\n if (abort) signal?.removeEventListener(\"abort\", abort);\n }\n };\n if (nativeModalProbe) {\n const cancellation = new AbortController();\n const abort = () => cancellation.abort(signal?.reason);\n signal?.addEventListener(\"abort\", abort, { once: true });\n if (signal?.aborted) abort();\n try {\n const exitCode = await withinDeadline(() =>\n nativeModalProbe.call(session, cancellation.signal),\n );\n if (exitCode !== 0)\n throw new SandboxExecReadinessError(\n established.backendId,\n \"exec_probe_failed\",\n timeoutMs,\n exitCode,\n established.instanceId,\n );\n return;\n } finally {\n signal?.removeEventListener(\"abort\", abort);\n cancellation.abort(new Error(\"Sandbox readiness observation finished\"));\n }\n }\n const execProbe = () =>\n withinDeadline(() =>\n run!.call(session, {\n cmd: \"true\",\n yieldTimeMs: Math.min(1_000, Math.max(1, deadline - Date.now())),\n maxOutputTokens: 1_000,\n }),\n );\n\n let result = await execProbe();\n while (true) {\n const exitCode = sandboxCommandExitCode(result);\n if (exitCode !== null) {\n if (exitCode === 0) return;\n throw new SandboxExecReadinessError(\n established.backendId,\n \"exec_probe_failed\",\n timeoutMs,\n exitCode,\n established.instanceId,\n );\n }\n\n const sessionId = sandboxCommandStillRunning(result) ? sandboxExecProbeSessionId(result) : null;\n const writeStdin = session.writeStdin;\n if (sessionId !== null && writeStdin) {\n result = await withinDeadline(() =>\n writeStdin.call(session, {\n sessionId,\n chars: \"\",\n yieldTimeMs: Math.min(1_000, Math.max(1, deadline - Date.now())),\n maxOutputTokens: 1_000,\n }),\n );\n continue;\n }\n\n const remainingMs = deadline - Date.now();\n if (remainingMs <= 0) throw timeoutError();\n await new Promise((resolve) => setTimeout(resolve, Math.min(100, remainingMs)));\n result = await execProbe();\n }\n}\n\nexport type SandboxCreatedCallback = (established: EstablishedSandboxSession) => Promise<void>;\n\n// The structural slice we need from a provider SandboxClient to resume by id and\n// cold-restore. Narrowed (not the full agent-loop SandboxClient) so the leaf\n// stays agent-loop-free.\ntype ResumeCapableClient = {\n backendId: string;\n deserializeSessionState?: (state: Record<string, unknown>) => Promise<unknown>;\n resume?: (state: unknown, options?: unknown) => Promise<unknown>;\n /** Opengeni extension implemented by providers whose ordinary SDK resume may\n * create a replacement. This method must either return the addressed wrapper\n * or prove it unavailable without creating anything. */\n resumeExact?: (state: unknown) => Promise<unknown>;\n create?: (manifest?: unknown, options?: unknown) => Promise<unknown>;\n createWithLifecycle?: (\n args: { manifest: unknown },\n lifecycle: {\n beforeDispatch: (intent: ModalCreateIntent, providerContext: unknown) => Promise<void>;\n onCreated: (session: unknown, intent: ModalCreateIntent) => Promise<void>;\n },\n ) => Promise<unknown>;\n};\n\n/**\n * Per-provider NotFound discriminator. The @openai/agents-extensions\n * `isProviderSandboxNotFoundError` / `assertResumeRecreateAllowed` helpers live\n * under `@openai/agents-extensions/sandbox/shared`, which is NOT an exported\n * subpath (the package `exports` map only exposes `./sandbox/<provider>`), so we\n * re-implement the discrimination here by inspecting the thrown error shape.\n *\n * \"Box no longer running\" (the box was reaped / idled out / 24h-ceiling) is the\n * ONLY error that licenses a cold-restore via create(). Every other resume\n * failure (transient provider error, auth, network) must propagate so the caller\n * backs off — never spawns a rival box. We err on the side of NOT recreating:\n * an unrecognized error is treated as \"not NotFound\" (propagate), because a\n * false-positive recreate is the dangerous direction (double-spawn).\n */\nfunction liveProviderInstanceIdFromState(\n backend: SandboxBackend | string,\n state: unknown,\n): string | null {\n if (!state || typeof state !== \"object\" || Array.isArray(state)) return null;\n const registration = PROVIDER_REGISTRY[backend as SandboxBackend];\n if (!registration || registration.backend !== backend) return null;\n const record = state as Record<string, unknown>;\n for (const field of registration.instanceIdFields) {\n const value = record[field];\n if (typeof value === \"string\" && value.length > 0) return value;\n }\n return null;\n}\n\nfunction legacySandboxProviderInstanceIdFromEnvelope(\n envelope: Record<string, unknown> | null | undefined,\n backend?: SandboxBackend | string,\n): string | null {\n const sessionState =\n envelope?.sessionState && typeof envelope.sessionState === \"object\"\n ? (envelope.sessionState as Record<string, unknown>)\n : null;\n const providerState =\n sessionState?.providerState && typeof sessionState.providerState === \"object\"\n ? sessionState.providerState\n : envelope?.providerState;\n const envelopeBackendId =\n typeof envelope?.backendId === \"string\" && envelope.backendId.length > 0\n ? envelope.backendId\n : null;\n const resolvedBackend =\n backend ??\n (envelopeBackendId\n ? (sandboxBackendForSdkBackendId(envelopeBackendId) ?? envelopeBackendId)\n : null);\n return resolvedBackend ? liveProviderInstanceIdFromState(resolvedBackend, providerState) : null;\n}\n\n/** Resolve the stable Opengeni identity first, then legacy SDK provider keys.\n * The fallback is compatibility-only: new envelopes always persist the stable\n * top-level identity, so downstream lease/reaper code remains provider-neutral. */\nexport function sandboxProviderInstanceIdFromEnvelope(\n envelope: Record<string, unknown> | null | undefined,\n backend?: SandboxBackend | string,\n): string | null {\n const declared = envelope?.[OPENGENI_SANDBOX_PROVIDER_INSTANCE_ID_FIELD];\n if (typeof declared === \"string\" && declared.length > 0) return declared;\n return legacySandboxProviderInstanceIdFromEnvelope(envelope, backend);\n}\n\n/** Validate rolling-format envelopes before addressing a provider. The stable\n * Opengeni identity is authoritative, but a disagreeing legacy SDK address is\n * corruption/staleness—not evidence that the provider disappeared. */\nexport function assertConsistentSandboxProviderIdentity(\n backend: SandboxBackend | string,\n envelope: Record<string, unknown> | null | undefined,\n): string | null {\n const declared = envelope?.[OPENGENI_SANDBOX_PROVIDER_INSTANCE_ID_FIELD];\n const stable = typeof declared === \"string\" && declared.length > 0 ? declared : null;\n const legacy = legacySandboxProviderInstanceIdFromEnvelope(envelope, backend);\n if (stable && legacy && stable !== legacy) {\n throw new SandboxResumeIdentityMismatchError(backend, stable, legacy);\n }\n return stable ?? legacy;\n}\n\nfunction exactResumeStateForBackend(backend: string, state: unknown): unknown {\n if (backend !== \"vercel\" || !state || typeof state !== \"object\" || Array.isArray(state)) {\n return state;\n }\n // Vercel's ordinary resume intentionally creates a replacement whenever the\n // serialized state carries a fresh snapshot. Exact attach/reaper recovery\n // must address sandboxId instead; clearing only this freshness marker makes\n // the SDK use Sandbox.get while retaining the snapshot as recovery data.\n const exactState = { ...(state as Record<string, unknown>) };\n delete exactState.snapshotSandboxId;\n return exactState;\n}\n\nfunction providerContinuityRegistration(backend: SandboxBackend | string) {\n const registration = PROVIDER_REGISTRY[backend as SandboxBackend];\n return registration?.backend === backend ? registration.continuity : undefined;\n}\n\nexport function sandboxProviderContinuityForState(\n backend: SandboxBackend | string,\n state: unknown,\n sourceInstanceId: string,\n): SandboxProviderContinuityRecovery | null {\n const continuity = providerContinuityRegistration(backend);\n const continuityKey = continuity?.keyFromState(state) ?? null;\n if (!continuity || !continuityKey || sourceInstanceId.length === 0) return null;\n return {\n version: 1,\n backend: backend as SandboxBackend,\n kind: continuity.kind,\n sourceInstanceId,\n continuityKey,\n };\n}\n\nfunction parsedEnvelopeContinuity(\n backend: SandboxBackend | string,\n envelope: Record<string, unknown> | null,\n state: unknown,\n expectedInstanceId: string,\n): SandboxProviderContinuityRecovery | null {\n const recovery =\n envelope?.opengeniRecovery && typeof envelope.opengeniRecovery === \"object\"\n ? (envelope.opengeniRecovery as { continuity?: unknown })\n : null;\n const value = recovery?.continuity;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const candidate = value as Partial<SandboxProviderContinuityRecovery>;\n const derived = sandboxProviderContinuityForState(backend, state, expectedInstanceId);\n return derived &&\n candidate.version === derived.version &&\n candidate.backend === derived.backend &&\n candidate.kind === derived.kind &&\n candidate.sourceInstanceId === derived.sourceInstanceId &&\n candidate.continuityKey === derived.continuityKey\n ? derived\n : null;\n}\n\nfunction continuityMatchesState(\n receipt: SandboxProviderContinuityRecovery,\n state: unknown,\n): boolean {\n const continuity = providerContinuityRegistration(receipt.backend);\n return (\n continuity?.kind === receipt.kind && continuity.keyFromState(state) === receipt.continuityKey\n );\n}\n\nfunction preserveContinuityWorkspaceForDiscard(\n backend: SandboxBackend | string,\n requestedState: unknown,\n session: unknown,\n sessionState: unknown,\n): boolean {\n const continuity = providerContinuityRegistration(backend);\n if (!continuity) return false;\n const requestedKey = continuity.keyFromState(requestedState);\n const replacementKey = continuity.keyFromState(sessionState);\n if (!requestedKey || requestedKey !== replacementKey) return false;\n continuity.preserveWorkspaceForDiscard(session, sessionState);\n return true;\n}\n\nexport async function resumeExactSandboxSession(\n clientInput: unknown,\n backend: SandboxBackend | string,\n state: unknown,\n expectedInstanceId: string,\n options?: { continuity?: SandboxProviderContinuityRecovery },\n): Promise<{\n session: unknown;\n sessionState: unknown;\n instanceId: string;\n providerContinuity?: SandboxProviderContinuityRecovery;\n}> {\n const client = clientInput as ResumeCapableClient;\n if (!client.resume) {\n throw new SandboxConfigError(backend, `Sandbox backend \"${backend}\" does not support resume()`);\n }\n const exactState = exactResumeStateForBackend(client.backendId, state);\n const continuity = options?.continuity;\n if (\n continuity &&\n (continuity.backend !== backend ||\n continuity.sourceInstanceId !== expectedInstanceId ||\n !continuityMatchesState(continuity, exactState))\n ) {\n throw new SandboxResumeIdentityMismatchError(\n backend,\n expectedInstanceId,\n continuity.sourceInstanceId,\n );\n }\n if (!continuity && !client.resumeExact) {\n throw new SandboxConfigError(\n backend,\n `Sandbox backend \"${backend}\" has no non-replacing resumeExact()`,\n );\n }\n // A durable continuity receipt is creation authority owned by either the\n // unique cold->warming winner or a durable teardown claim. Ordinary attached\n // callers use resumeExact so an SDK cannot silently create a rival wrapper.\n const session = continuity\n ? await client.resume(exactState)\n : await client.resumeExact!(exactState);\n const actualInstanceId = readInstanceId(backend, session);\n if (!actualInstanceId) {\n // Do not tear down an unidentifiable handle: it may be the requested live\n // provider. The adapter must expose a stable identity before Opengeni can\n // safely command, publish, snapshot, or delete it.\n throw new SandboxResumeIdentityUnavailableError(backend, expectedInstanceId);\n }\n if (actualInstanceId !== expectedInstanceId) {\n const replacementState = (session as { state?: unknown }).state ?? exactState;\n if (continuity && continuityMatchesState(continuity, replacementState)) {\n return {\n session,\n sessionState: replacementState,\n instanceId: actualInstanceId,\n providerContinuity: continuity,\n };\n }\n // A provider may race from running to absent between an exact preflight and\n // its SDK resume. If that produced a same-workspace wrapper, discard only\n // the wrapper; deleting the shared workspace would destroy recovery truth.\n preserveContinuityWorkspaceForDiscard(backend, exactState, session, replacementState);\n try {\n await terminateManagedSandboxSession(client, replacementState, session);\n } catch (cleanupError) {\n throw new SandboxResumeIdentityMismatchError(backend, expectedInstanceId, actualInstanceId, {\n cause: cleanupError,\n });\n }\n throw new SandboxExactResumeReplacedError(backend, expectedInstanceId, actualInstanceId);\n }\n return {\n session,\n sessionState: (session as { state?: unknown }).state ?? exactState,\n instanceId: actualInstanceId,\n ...(continuity ? { providerContinuity: continuity } : {}),\n };\n}\n\n/** Terminate a provider handle that never became durable warm ownership. A\n * continuity-adopted Docker wrapper is removed while its durable host\n * workspace remains available to the next elected recovery owner. */\nexport async function terminateUnpublishedSandboxSession(\n established: EstablishedSandboxSession,\n): Promise<void> {\n if (established.providerContinuity) {\n const continuity = providerContinuityRegistration(established.providerContinuity.backend);\n if (\n continuity?.kind === established.providerContinuity.kind &&\n continuity.keyFromState(established.sessionState) ===\n established.providerContinuity.continuityKey\n ) {\n continuity.preserveWorkspaceForDiscard(established.session, established.sessionState);\n }\n }\n await terminateManagedSandboxSession(\n established.client,\n established.sessionState,\n established.session,\n );\n}\n\n/** Remove every live-provider address while retaining backend-independent\n * archive/config state for a safe cold rematerialization. */\nexport function withoutSandboxProviderIdentity(\n envelope: Record<string, unknown> | null,\n): Record<string, unknown> | null {\n if (!envelope) return null;\n const providerIndependentEnvelope = { ...envelope };\n delete providerIndependentEnvelope[OPENGENI_SANDBOX_PROVIDER_INSTANCE_ID_FIELD];\n // Some rolling/legacy envelopes contain both a top-level providerState and\n // the newer nested sessionState. Strip both representations; retaining the\n // top-level fallback would make the compatibility reader rediscover a dead\n // provider after we deliberately converted the envelope to archive-only.\n delete providerIndependentEnvelope.providerState;\n const sessionState =\n envelope.sessionState && typeof envelope.sessionState === \"object\"\n ? (envelope.sessionState as Record<string, unknown>)\n : null;\n if (!sessionState) {\n return providerIndependentEnvelope;\n }\n const { providerState: _providerState, ...providerIndependentState } = sessionState;\n return {\n ...providerIndependentEnvelope,\n sessionState: providerIndependentState,\n };\n}\n\nfunction readInstanceId(backend: SandboxBackend | string, session: unknown): string {\n return liveProviderInstanceIdFromState(backend, (session as { state?: unknown }).state) ?? \"\";\n}\n\nasync function terminateCreatedSandbox(\n client: ResumeCapableClient,\n session: unknown,\n sessionState: unknown,\n): Promise<void> {\n try {\n await terminateManagedSandboxSession(client, sessionState, session);\n } catch {\n /* best-effort */\n }\n}\n\ntype ModalNativeWorkspacePersistence = \"snapshot_filesystem\" | \"snapshot_directory\";\ntype RestoreWorkspaceArchive =\n | VerifiedWorkspaceArchive\n | {\n kind: \"host_spool\";\n descriptor: TarWorkspaceArchiveDescriptor;\n ref: WorkspaceArchiveObjectRef;\n };\n\nfunction modalWorkspacePersistenceForRestore(\n archive: RestoreWorkspaceArchive | null,\n): ModalNativeWorkspacePersistence | null {\n if (archive?.kind !== \"provider_snapshot\") return null;\n const snapshot = archive.nativeSnapshot;\n if (!snapshot) {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n `selected native snapshot archive revision ${archive.descriptor.revision} has no decoded provider receipt`,\n );\n }\n const expected =\n snapshot.provider === \"modal_snapshot_filesystem\"\n ? \"snapshot_filesystem\"\n : snapshot.provider === \"modal_snapshot_directory\"\n ? \"snapshot_directory\"\n : null;\n if (!expected) return null;\n if (snapshot.workspacePersistence !== undefined && snapshot.workspacePersistence !== expected) {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n `selected Modal snapshot archive revision ${archive.descriptor.revision} has inconsistent persistence metadata`,\n );\n }\n return expected;\n}\n\nfunction settingsForWorkspaceArchiveRestore(\n backend: SandboxBackend,\n settings: Settings,\n archive: RestoreWorkspaceArchive | null,\n): Settings {\n if (backend !== \"modal\") return settings;\n const workspacePersistence = modalWorkspacePersistenceForRestore(archive);\n if (workspacePersistence === \"snapshot_filesystem\" && archive?.kind === \"provider_snapshot\") {\n // Boot the selected filesystem image directly. SDK hydrateWorkspace would\n // create a second box and expose its identity only after old-box teardown.\n // The ordinary create callback must own the only destination before verify.\n return {\n ...settings,\n modalWorkspacePersistence: workspacePersistence,\n modalImageId: archive.nativeSnapshot!.snapshotId,\n };\n }\n return workspacePersistence && settings.modalWorkspacePersistence !== workspacePersistence\n ? { ...settings, modalWorkspacePersistence: workspacePersistence }\n : settings;\n}\n\n/**\n * Establish from one recovery envelope under an explicit creation policy. The\n * envelope is the lease's box-identity descriptor (the same per-turn `_sandbox`\n * envelope upserted by the turn activity).\n *\n * - `opts.backendOverride ?? envelope.backendId ?? settings.sandboxBackend`\n * selects the backend; the client is built for THAT backend (resume-by-id is\n * fenced to the original provider).\n * - warm reattach: deserialize the envelope sessionState → client.resume(state)\n * (no lock; R4-safe). `resume-only` propagates provider NotFound.\n * - `create-or-restore`: the elected owner may replace a missing warm instance,\n * or create directly from a cold/null envelope.\n */\nexport async function establishSandboxSessionFromEnvelope(\n settings: Settings,\n envelope: Record<string, unknown> | null,\n opts: {\n sessionId: string;\n recovery: \"create-or-restore\" | \"resume-only\";\n loadHostWorkspaceArchive?: (ref: WorkspaceArchiveObjectRef) => Promise<WorkspaceArchiveSpool>;\n backendOverride?: SandboxBackend;\n environment?: Record<string, string>;\n onSandboxCreated?: SandboxCreatedCallback;\n /** Durable lease owners fence the attempt before invoking a provider create.\n * Called for each physical attempt, including logical-image fallback. A\n * rejected hook prevents dispatch; a lost create reply is never permission\n * to invoke the fallback under the same unresolved operation. */\n onBeforeSandboxCreate?: (\n settings: Settings,\n intent?: ModalCreateIntent,\n providerContext?: unknown,\n ) => Promise<void>;\n /** Called after archive hydration but immediately before the exact workspace\n * fingerprint probe. Lease-aware callers persist `verifying` here so a box\n * is never observable as ready while verification is in flight. */\n onWorkspaceRestoreVerifying?: (descriptor: WorkspaceArchiveDescriptor) => Promise<void>;\n metrics?: RuntimeMetricsHooks;\n /** Exact pre-optimization sandbox settings. When a provider-immutable rig\n * image is missing, retry from this logical image identity rather than\n * guessing from a possibly absent tag or falling through to provider\n * defaults. */\n logicalFallbackSettings?: Settings;\n /** Isolated conformance-test/embedding seam. Ordinary runtime callers use\n * the validated provider registry. */\n clientFactory?: (\n backend: SandboxBackend,\n settings: Settings,\n environment: Record<string, string>,\n ) => unknown;\n },\n): Promise<EstablishedSandboxSession> {\n const envelopeBackend =\n typeof envelope?.backendId === \"string\" ? (envelope.backendId as SandboxBackend) : undefined;\n const backend =\n opts.backendOverride ?? envelopeBackend ?? (settings.sandboxBackend as SandboxBackend);\n const createImageSource =\n backend === \"modal\" && settings.modalImageId ? \"provider_immutable\" : \"logical\";\n const environment = opts.environment ?? collectSandboxEnvironment(settings);\n const client = (\n opts.clientFactory\n ? opts.clientFactory(backend, settings, environment)\n : createSandboxClientForBackend(backend, settings, environment, opts.metrics)\n ) as ResumeCapableClient | undefined;\n if (!client) {\n throw new SandboxConfigError(\n backend,\n `Cannot establish a sandbox session for backend \"${backend}\" (no client; sandboxBackend=none?)`,\n );\n }\n if (opts.recovery === \"create-or-restore\" && !client.create) {\n throw new SandboxConfigError(backend, `Sandbox backend \"${backend}\" does not support create()`);\n }\n\n // The manifest the box is CREATED with. Its `environment` must equal the\n // environment the agent declares for this run (buildManifest's `environment`),\n // because the SDK injects this box NON-OWNED and then applies the agent's\n // manifest as a provided-session delta — `applyManifestToProvidedSession`\n // throws on ANY environment delta (validateNoEnvironmentDelta). The client's\n // constructor `env` materializes the RUNTIME env but does NOT populate\n // `manifest.environment` (a bare create() yields `new Manifest()` with an empty\n // environment), so the manifest env must be set here explicitly. `root` is left\n // to default to \"/workspace\" to match buildManifest's declared root (the\n // root-delta guard). The caller threads `opts.environment` = the SAME object\n // passed to runtime.buildAgent, so current==target and the delta is empty.\n const createManifest = { environment };\n\n // The serialized provider state the box was last persisted as. The envelope\n // shape is the per-turn `_sandbox` entry; its `sessionState` is the provider\n // payload deserializeSandboxSessionStateEnvelope re-hydrates.\n const envelopeSessionState =\n envelope && typeof envelope === \"object\"\n ? (envelope as { sessionState?: unknown }).sessionState\n : undefined;\n\n // The persisted /workspace snapshot the reaper folded onto the lease envelope\n // (sandbox-file-persistence). Present on a re-warm whose box was drain-persisted:\n // - WARM reattach NotFound path (box gone, full envelope still has sandboxId);\n // - COLD lease re-warm (confirmDrainCold preserved a MINIMAL archive-only\n // envelope `{ sessionState: { workspaceArchive } }` — NO sandboxId, so the\n // warm-reattach branch must NOT try resume()-by-id; it cold-creates+hydrates).\n const archiveState =\n envelopeSessionState && typeof envelopeSessionState === \"object\"\n ? (envelopeSessionState as {\n workspaceArchive?: unknown;\n workspaceArchiveRef?: unknown;\n workspaceArchiveMeta?: unknown;\n })\n : undefined;\n // Exactly one selected revision is restored. A present archive without its\n // revision/hash/tree descriptor is not recoverable truth and fails before any\n // provider create. `workspaceArchivePrev` is retained for explicit future\n // operator selection, never silently substituted in this attempt.\n const workspaceArchiveBase64 = archiveState?.workspaceArchive;\n const workspaceArchiveMetadata = archiveState?.workspaceArchiveMeta;\n\n // Create one destination directly from a Modal filesystem snapshot; other\n // archive protocols hydrate the fresh destination. No archive is valid only\n // for a genuinely new workspace; callers select and verify an exact archive before\n // entering this seam. This is the SOLE archive-replay path, shared by the\n // NotFound warm-reattach path and the cold-restore branch (b) below.\n const coldRestore = async (resumeFallbackState?: unknown): Promise<EstablishedSandboxSession> => {\n // Parse/verify lazily: a warm resume-by-id does not consume its retained\n // archive, so a legacy live box remains resumable. Creation/restoration is\n // the boundary that requires complete durable metadata.\n let workspaceArchive: RestoreWorkspaceArchive | null = readVerifiedWorkspaceArchive(\n workspaceArchiveBase64,\n workspaceArchiveMetadata,\n );\n const objectRef = parseWorkspaceArchiveObjectRef(archiveState?.workspaceArchiveRef);\n const objectDescriptor = parseWorkspaceArchiveDescriptor(workspaceArchiveMetadata);\n if (\n process.platform === \"linux\" &&\n objectRef &&\n objectDescriptor?.version === 1 &&\n objectDescriptor.workspace.projection === \"sdk_local_archive_v1\" &&\n opts.loadHostWorkspaceArchive\n ) {\n // Local/Docker restore a host-backed archive natively. Any other backend\n // hydrates a portable tar converted from it, so a deployment that changes\n // sandbox backend can still continue chats archived before the change.\n if (\n objectRef.sha256 !== objectDescriptor.archiveSha256 ||\n objectRef.bytes !== objectDescriptor.archiveBytes\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_metadata_invalid\",\n \"Host archive object reference does not match its descriptor\",\n );\n }\n workspaceArchive = { kind: \"host_spool\", descriptor: objectDescriptor, ref: objectRef };\n }\n const hostBackedBackend = backend === \"local\" || backend === \"docker\";\n if (objectRef && !workspaceArchive) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_hydration_failed\",\n \"Selected workspace archive object has no supported restore loader\",\n );\n }\n let hostSpool: WorkspaceArchiveSpool | undefined;\n try {\n // Preserve the pre-create integrity boundary used by inline archives.\n // A missing/corrupt object must not create a provider just to delete it.\n if (workspaceArchive?.kind === \"host_spool\") {\n hostSpool = await opts.loadHostWorkspaceArchive!(workspaceArchive.ref);\n if (\n hostSpool.sha256 !== workspaceArchive.descriptor.archiveSha256 ||\n hostSpool.byteSize !== workspaceArchive.descriptor.archiveBytes\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_hash_mismatch\",\n \"Downloaded workspace archive does not match its descriptor\",\n );\n }\n }\n // The selected native artifact is the durable authority for its restore\n // protocol. The process setting governs new sandboxes only: a mode rollout\n // must not make an older, verified Modal snapshot impossible to hydrate.\n const restoreSettings = settingsForWorkspaceArchiveRestore(\n backend,\n settings,\n workspaceArchive,\n );\n const createdFromFilesystemSnapshot =\n backend === \"modal\" &&\n workspaceArchive?.kind === \"provider_snapshot\" &&\n workspaceArchive.nativeSnapshot?.provider === \"modal_snapshot_filesystem\";\n const restoreImageSource = createdFromFilesystemSnapshot\n ? \"provider_immutable\"\n : createImageSource;\n // Resolve only the image this create will use. A retained filesystem\n // snapshot must not depend on the availability of today's registry image\n // or its secret. Rebuild the Modal client after registry resolution so\n // fresh/directory creates receive the resolved private-image selector.\n if (backend === \"modal\" && !opts.clientFactory) {\n await ensureModalRegistryImage(restoreSettings);\n }\n const restoreClient =\n restoreSettings === settings && (backend !== \"modal\" || opts.clientFactory)\n ? client\n : ((opts.clientFactory\n ? opts.clientFactory(backend, restoreSettings, environment)\n : createSandboxClientForBackend(\n backend,\n restoreSettings,\n environment,\n opts.metrics,\n )) as ResumeCapableClient | undefined);\n if (!restoreClient?.create) {\n throw new SandboxConfigError(\n backend,\n `Sandbox backend \"${backend}\" does not support fresh archive restoration`,\n );\n }\n let createdClient = restoreClient;\n let attributedDuringCreate = false;\n let providerDispatchAttempted = false;\n const createWithAttribution = async (\n candidate: ResumeCapableClient,\n createSettings: Settings,\n ) => {\n if (candidate.createWithLifecycle && opts.onBeforeSandboxCreate) {\n return await candidate.createWithLifecycle(\n { manifest: createManifest },\n {\n beforeDispatch: async (intent, providerContext) => {\n providerDispatchAttempted = true;\n await opts.onBeforeSandboxCreate!(createSettings, intent, providerContext);\n },\n onCreated: async (session) => {\n const instanceId = readInstanceId(backend, session);\n if (!instanceId) throw new Error(\"Modal provider receipt has no physical identity\");\n await opts.onSandboxCreated?.({\n client: candidate,\n session,\n sessionState: (session as { state?: unknown }).state ?? resumeFallbackState,\n instanceId,\n backendId: candidate.backendId,\n });\n attributedDuringCreate = true;\n },\n },\n );\n }\n // Non-Modal providers and isolated client-factory fixtures retain their\n // ordinary admission hook. Production Modal requires the wire intent.\n await opts.onBeforeSandboxCreate?.(createSettings);\n return await candidate.create!({ manifest: createManifest });\n };\n const createStarted = Date.now();\n let restored: Awaited<ReturnType<NonNullable<typeof restoreClient.create>>>;\n try {\n restored = await createWithAttribution(restoreClient, restoreSettings);\n recordSandboxCreateMetric(\n opts.metrics,\n restoreClient.backendId,\n restoreImageSource,\n \"completed\",\n createStarted,\n );\n } catch (error) {\n recordSandboxCreateMetric(\n opts.metrics,\n restoreClient.backendId,\n restoreImageSource,\n \"failed\",\n createStarted,\n );\n recordSandboxProviderApiThrottleMetric(\n opts.metrics,\n restoreClient.backendId,\n \"create\",\n error,\n );\n if (providerDispatchAttempted) {\n // Preserve the actual failure (including a known cleanup/setup\n // failure); the durable receipt decides whether outcome is unknown.\n throw error;\n }\n if (\n createdFromFilesystemSnapshot ||\n createImageSource !== \"provider_immutable\" ||\n backend !== \"modal\" ||\n !isProviderSandboxNotFoundError(restoreClient.backendId, error)\n ) {\n throw error;\n }\n const fallbackBaseSettings =\n opts.logicalFallbackSettings ??\n (settings.modalImageRef ? { ...settings, modalImageId: undefined } : null);\n if (!fallbackBaseSettings) {\n // An ID-only logical base is supported. Without the exact pre-selection\n // settings, clearing the optimized ID would silently boot Modal's\n // default image, so fail closed instead of changing the rig base.\n throw error;\n }\n const fallbackSettings = settingsForWorkspaceArchiveRestore(\n backend,\n fallbackBaseSettings,\n workspaceArchive,\n );\n await ensureModalRegistryImage(fallbackSettings);\n const fallbackClient = (\n opts.clientFactory\n ? opts.clientFactory(backend, fallbackSettings, environment)\n : createSandboxClientForBackend(backend, fallbackSettings, environment, opts.metrics)\n ) as ResumeCapableClient | undefined;\n if (!fallbackClient?.create) {\n throw new SandboxConfigError(\n backend,\n \"Modal logical-image fallback does not support fresh creation\",\n );\n }\n const fallbackStarted = Date.now();\n try {\n restored = await createWithAttribution(fallbackClient, fallbackSettings);\n recordSandboxCreateMetric(\n opts.metrics,\n fallbackClient.backendId,\n \"logical\",\n \"completed\",\n fallbackStarted,\n );\n createdClient = fallbackClient;\n } catch (fallbackError) {\n recordSandboxCreateMetric(\n opts.metrics,\n fallbackClient.backendId,\n \"logical\",\n \"failed\",\n fallbackStarted,\n );\n recordSandboxProviderApiThrottleMetric(\n opts.metrics,\n fallbackClient.backendId,\n \"create\",\n fallbackError,\n );\n throw fallbackError;\n }\n }\n let restoredState = (restored as { state?: unknown }).state;\n const restoredInstanceId = readInstanceId(backend, restored);\n if (!restoredInstanceId) {\n await terminateCreatedSandbox(createdClient, restored, restoredState);\n throw new SandboxConfigError(\n backend,\n `Sandbox backend \"${backend}\" created a handle without its declared provider identity`,\n );\n }\n let established: EstablishedSandboxSession = {\n client: createdClient,\n session: restored,\n sessionState: restoredState ?? resumeFallbackState,\n instanceId: restoredInstanceId,\n backendId: createdClient.backendId,\n };\n if (opts.onSandboxCreated && !attributedDuringCreate) {\n try {\n await opts.onSandboxCreated(established);\n } catch (createCallbackError) {\n await terminateCreatedSandbox(createdClient, restored, restoredState);\n throw createCallbackError;\n }\n }\n let hydrationApplied = false;\n // A host-backed archive hydrated into a remote sandbox: what the converted\n // tar materializes, verified after hydration instead of the archive's\n // host-only fingerprint projection.\n let portableContents: PortableWorkspaceTar[\"contents\"] | null = null;\n if (workspaceArchive) {\n const hydrate = (restored as { hydrateWorkspace?: (data: Uint8Array) => Promise<void> })\n .hydrateWorkspace;\n if (\n !createdFromFilesystemSnapshot &&\n (workspaceArchive.kind !== \"host_spool\" || !hostBackedBackend) &&\n typeof hydrate !== \"function\"\n ) {\n await terminateCreatedSandbox(createdClient, restored, restoredState);\n throw new WorkspaceArchiveIntegrityError(\n \"archive_hydration_failed\",\n `sandbox backend ${createdClient.backendId} cannot hydrate selected archive revision ${workspaceArchive.descriptor.revision}`,\n );\n }\n try {\n if (\n createdFromFilesystemSnapshot &&\n (restoredState as { imageId?: unknown } | undefined)?.imageId !==\n restoreSettings.modalImageId\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_hydration_failed\",\n \"Modal destination did not boot the selected filesystem snapshot\",\n );\n }\n // Directory/tar hydration operates on the attributed destination.\n if (workspaceArchive.kind === \"host_spool\" && hostBackedBackend) {\n // This is the exact newly-created, unpublished destination. The lease\n // restore fence must exclude admitted writers until verification ends;\n // descriptor-relative filesystem access alone is not writer isolation.\n const root = (restored as { state?: { workspaceRootPath?: unknown } }).state\n ?.workspaceRootPath;\n if (typeof root !== \"string\")\n throw new WorkspaceArchiveIntegrityError(\n \"archive_hydration_failed\",\n \"Host archive restore has no exact workspace root\",\n );\n await restoreHostWorkspaceArchive(root, hostSpool!, {\n archiveLimits: Reflect.get(restored as object, \"archiveLimits\"),\n });\n } else if (workspaceArchive.kind === \"host_spool\") {\n const portable = await convertHostWorkspaceArchiveToTar(hostSpool!, {\n excludedPaths: workspaceArchiveExcludedPaths(restored),\n mtimeSeconds: Date.parse(workspaceArchive.descriptor.capturedAt) / 1000,\n });\n // The descriptor was fingerprinted from the source tree when it was\n // captured; the archive must still be exactly that tree.\n const expected = workspaceArchive.descriptor.workspace;\n if (\n portable.fingerprint.sha256 !== expected.sha256 ||\n portable.fingerprint.entryCount !== expected.entryCount ||\n portable.fingerprint.fileCount !== expected.fileCount ||\n portable.fingerprint.totalFileBytes !== expected.totalFileBytes\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_hash_mismatch\",\n `workspace archive revision ${workspaceArchive.descriptor.revision} does not match its recorded fingerprint`,\n );\n }\n await hydrate!.call(restored, portable.bytes);\n portableContents = portable.contents;\n } else if (!createdFromFilesystemSnapshot) {\n await hydrate!.call(restored, workspaceArchive.bytes);\n }\n } catch (error) {\n await terminateCreatedSandbox(\n createdClient,\n restored,\n (restored as { state?: unknown }).state,\n );\n if (error instanceof WorkspaceArchiveIntegrityError) throw error;\n throw new WorkspaceArchiveIntegrityError(\n \"archive_hydration_failed\",\n `failed to hydrate selected workspace archive revision ${workspaceArchive.descriptor.revision}`,\n { retryable: true, cause: error },\n );\n }\n // Defend against a backend replacing its provider during hydration.\n // Attribute the newly-active identity immediately,\n // before restore-state marking, fingerprint verification, or any caller\n // can publish the box warm. The callback is the durable lease/tagging\n // boundary; if it cannot persist the replacement, the caller fails closed\n // and this exact replacement is terminated below.\n const hydratedState = (restored as { state?: unknown }).state;\n const hydratedInstanceId = readInstanceId(backend, restored);\n if (!hydratedInstanceId) {\n await terminateCreatedSandbox(createdClient, restored, hydratedState);\n throw new SandboxConfigError(\n backend,\n `Sandbox backend \"${backend}\" hydrated a handle without its declared provider identity`,\n );\n }\n if (hydratedInstanceId !== established.instanceId) {\n established = {\n client: createdClient,\n session: restored,\n sessionState: hydratedState ?? resumeFallbackState,\n instanceId: hydratedInstanceId,\n backendId: createdClient.backendId,\n };\n if (opts.onSandboxCreated) {\n try {\n await opts.onSandboxCreated(established);\n } catch (createCallbackError) {\n await terminateCreatedSandbox(createdClient, restored, hydratedState);\n throw createCallbackError;\n }\n }\n }\n if (opts.onWorkspaceRestoreVerifying) {\n try {\n await opts.onWorkspaceRestoreVerifying(workspaceArchive.descriptor);\n } catch (error) {\n await terminateCreatedSandbox(\n createdClient,\n restored,\n (restored as { state?: unknown }).state,\n );\n throw error;\n }\n }\n // Native provider snapshots are restored by their exact opaque receipt.\n // Opengeni verifies receipt identity/hash before hydration, but it must not\n // impose a tar/inode equivalence contract on the provider's filesystem\n // image. Tar archives remain content-verified after hydration.\n if (workspaceArchive.kind === \"tar\" || workspaceArchive.kind === \"host_spool\") {\n try {\n if (portableContents) {\n await verifyRestoredWorkspaceContents(\n restored,\n portableContents,\n workspaceArchive.descriptor.revision,\n );\n } else {\n await verifyRestoredWorkspace(restored, workspaceArchive.descriptor);\n }\n } catch (error) {\n await terminateCreatedSandbox(\n createdClient,\n restored,\n (restored as { state?: unknown }).state,\n );\n if (error instanceof WorkspaceArchiveIntegrityError) throw error;\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n `failed to verify selected workspace archive revision ${workspaceArchive.descriptor.revision}`,\n { retryable: true },\n );\n }\n }\n hydrationApplied = true;\n console.info(\n `[sandbox] cold-restore applied ${workspaceArchive.kind === \"provider_snapshot\" ? \"native snapshot receipt\" : \"verified tar archive\"} revision ${workspaceArchive.descriptor.revision}`,\n );\n }\n restoredState = (restored as { state?: unknown }).state;\n const finalInstanceId = readInstanceId(backend, restored);\n if (!finalInstanceId) {\n await terminateCreatedSandbox(createdClient, restored, restoredState);\n throw new SandboxConfigError(\n backend,\n `Sandbox backend \"${backend}\" returned a handle without its declared provider identity`,\n );\n }\n return {\n client: createdClient,\n session: restored,\n sessionState: restoredState ?? resumeFallbackState,\n instanceId: finalInstanceId,\n backendId: createdClient.backendId,\n origin: hydrationApplied ? (\"restored\" as const) : (\"created\" as const),\n ...(workspaceArchive ? { restoredArchive: workspaceArchive.descriptor } : {}),\n };\n } finally {\n await hostSpool?.dispose().catch(() => {\n // Cleanup must not discard a successfully established provider handle\n // or replace the authoritative restore failure with a filesystem error.\n console.warn(\"workspace archive download spool cleanup failed\");\n });\n }\n };\n\n // Does the envelope carry a RESUMABLE box id (warm reattach), or only a\n // restorable archive (cold lease)? Archive-only state is not resumable: the\n // provider's deserialize/resume path would reject it before Opengeni could\n // cold-restore. New envelopes use the stable Opengeni identity; legacy SDK\n // provider keys remain readable during rollout.\n const persistedInstanceId = assertConsistentSandboxProviderIdentity(backend, envelope);\n const hasResumableInstance = persistedInstanceId !== null;\n\n // (a) WARM REATTACH BY ID — only when the envelope carries a resumable box id.\n if (\n hasResumableInstance &&\n envelopeSessionState &&\n client.resume &&\n client.deserializeSessionState\n ) {\n let resumedState: unknown;\n try {\n resumedState = await deserializeSandboxSessionStateEnvelope(\n client as unknown as SandboxClient,\n envelopeSessionState,\n persistedInstanceId,\n );\n } catch (error) {\n throw new SandboxConfigError(\n backend,\n `Failed to deserialize sandbox resume envelope for backend \"${backend}\": ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (resumedState !== undefined) {\n const providerContinuity =\n opts.recovery === \"create-or-restore\"\n ? parsedEnvelopeContinuity(backend, envelope, resumedState, persistedInstanceId)\n : null;\n try {\n const resumed = await resumeExactSandboxSession(\n client,\n backend,\n resumedState,\n persistedInstanceId,\n providerContinuity ? { continuity: providerContinuity } : undefined,\n );\n const established: EstablishedSandboxSession = {\n client,\n session: resumed.session,\n sessionState: resumed.sessionState,\n instanceId: resumed.instanceId,\n backendId: client.backendId,\n origin: \"resumed\",\n ...(resumed.providerContinuity ? { providerContinuity: resumed.providerContinuity } : {}),\n ...(resumed.instanceId !== persistedInstanceId\n ? { lostInstanceId: persistedInstanceId }\n : {}),\n };\n // A continuity resume occurs only on a lease's unique warming owner.\n // Attribute the restarted/adopted wrapper before returning exactly as\n // for a fresh create; failure discards the wrapper but preserves the\n // durable workspace for the next owner.\n if (resumed.providerContinuity && opts.onSandboxCreated) {\n try {\n await opts.onSandboxCreated(established);\n } catch (error) {\n await terminateUnpublishedSandboxSession(established).catch(() => undefined);\n throw error;\n }\n }\n return established;\n } catch (error) {\n // Attached callers never own replacement. Propagate the provider\n // NotFound so their lease-aware caller can atomically mark this exact\n // warm epoch/instance cold and re-enter normal admission. Only the\n // cold->warming winner may replace the missing box.\n if (\n !isProviderSandboxNotFoundError(client.backendId, error) ||\n opts.recovery === \"resume-only\"\n ) {\n throw error;\n }\n // COLD-RESTORE: the box is genuinely gone. Modal does NOT restore via\n // create({ snapshot }) — passing `snapshot` to ModalSandboxClient.create()\n // THROWS (assertCoreSnapshotUnsupported). Modal's real persistence is an\n // OPAQUE ARCHIVE captured by session.persistWorkspace() at drain/turn-\n // snapshot time and folded onto the lease envelope\n // (sandbox-file-persistence). The shared coldRestore() seam creates a\n // fresh box and replays that archive. `lostInstanceId` carries the gone\n // box's id so the caller can emit the durable sandbox.box.lost event.\n if (\n providerContinuity &&\n (typeof workspaceArchiveBase64 !== \"string\" || workspaceArchiveBase64.length === 0)\n ) {\n throw new SandboxProviderContinuityUnavailableError(backend, persistedInstanceId, false, {\n cause: error,\n });\n }\n let restoredSession: EstablishedSandboxSession;\n try {\n restoredSession = await coldRestore(resumedState);\n } catch (restoreError) {\n if (!providerContinuity) throw restoreError;\n throw new SandboxProviderContinuityUnavailableError(\n backend,\n persistedInstanceId,\n restoreError instanceof WorkspaceArchiveIntegrityError ? restoreError.retryable : true,\n { cause: restoreError },\n );\n }\n return persistedInstanceId\n ? { ...restoredSession, lostInstanceId: persistedInstanceId }\n : restoredSession;\n }\n }\n }\n\n // (b) COLD SESSION / COLD LEASE — no resumable box id. create() a fresh box, and\n // if the envelope carries a persisted /workspace snapshot (the archive-only\n // envelope confirmDrainCold preserves across draining->cold), replay it so\n // /workspace survives the box churn (sandbox-file-persistence). No archive -> a\n // clean empty box (a never-warmed session).\n if (opts.recovery === \"resume-only\") {\n throw new SandboxResumeStateUnavailableError(backend);\n }\n return await coldRestore();\n}\n\nfunction recordSandboxCreateMetric(\n metrics: RuntimeMetricsHooks | undefined,\n backend: string,\n imageSource: \"logical\" | \"provider_immutable\",\n outcome: \"completed\" | \"failed\",\n startedMs: number,\n): void {\n try {\n metrics?.onSandboxCreate?.({\n backend,\n imageSource,\n outcome,\n durationSeconds: Math.max(0, (Date.now() - startedMs) / 1000),\n });\n } catch {\n // Metrics emission must not affect sandbox lifecycle.\n }\n}\n\nfunction recordSandboxProviderApiThrottleMetric(\n metrics: RuntimeMetricsHooks | undefined,\n backend: string,\n operation: \"create\" | \"renew\",\n error: unknown,\n): void {\n if (!isProviderApiThrottleError(error)) return;\n try {\n metrics?.onSandboxProviderApiThrottle?.({ backend, operation });\n } catch {\n // Metrics emission must not affect sandbox lifecycle.\n }\n}\n\n// A client that can SERIALIZE a live session state back to the persistable\n// envelope form (the inverse of deserializeSessionState). Narrowed so the leaf\n// stays agent-loop-free.\ntype SerializeCapableClient = {\n backendId: string;\n serializeSessionState?: (state: unknown, options?: unknown) => Promise<Record<string, unknown>>;\n};\n\n/**\n * Fold a freshly-established (or resumed) sandbox session into the persistable\n * `resume_state` envelope the lease stores — the SAME `{ backendId, sessionState }`\n * shape `establishSandboxSessionFromEnvelope` consumes to RESUME BY ID. The\n * API-direct control plane (viewer attach / Channel-A) MUST persist this onto the\n * lease at warm-commit time, or a later op (which reads the lease's resume_state)\n * has nothing to resume from and COLD-CREATES A RIVAL BOX — the box-churn the\n * prove-it surfaced (fs.write then fs.read 404'd on a different box; N Channel-A\n * ops leaked N boxes). Returns null when the client cannot serialize (the caller\n * stores null and the box rides the provider idle-timeout — no rival spawn, just\n * no warm-reattach).\n */\nexport async function serializeEstablishedSandboxEnvelope(\n established: EstablishedSandboxSession,\n): Promise<Record<string, unknown> | null> {\n const client = established.client as SerializeCapableClient | undefined;\n if (!client || typeof client.serializeSessionState !== \"function\") {\n return null;\n }\n if (established.sessionState === undefined || established.sessionState === null) {\n return null;\n }\n try {\n // serializeSessionState returns the PERSISTABLE FLAT provider state — for\n // Modal `{ sandboxId, appName, imageTag, manifest(serialized),\n // configuredExposedPorts, ... }` (sandboxId preserved via `...state`).\n const serialized = await client.serializeSessionState(established.sessionState);\n\n // deserializeSandboxSessionStateEnvelope expects the lease-envelope shape\n // `{ providerState, manifest, snapshot?, exposedPorts?, workspaceReady }` and\n // rehydrates `{ ...providerState, manifest, snapshot?, exposedPorts?,\n // workspaceReady }`. So the FLAT serialized state must be nested under\n // `providerState` (and manifest/ports lifted), or sandboxId is dropped on the\n // round-trip and resume() throws \"requires a persisted sandboxId\". SDK-owned\n // envelope fields are removed from providerState after lifting; providers can\n // return live Manifest instances there, and deserialization overlays the\n // authoritative manifest anyway. configuredExposedPorts is provider\n // configuration/state, not the SDK's port-keyed endpoint record, so it must\n // never be lifted.\n const flat = serialized as Record<string, unknown>;\n const backend = sandboxBackendForSdkBackendId(established.backendId) ?? established.backendId;\n const serializedInstanceId = liveProviderInstanceIdFromState(backend, flat);\n if (!serializedInstanceId || serializedInstanceId !== established.instanceId) {\n return null;\n }\n const manifest = serializeSdkManifestForEnvelope(flat.manifest);\n const exposedPorts = runStateExposedPortsRecord(flat.exposedPorts);\n const sessionState: Record<string, unknown> = {\n providerState: providerStateWithoutDuplicateManifest(flat),\n ...(manifest !== undefined ? { manifest } : {}),\n ...(exposedPorts !== undefined ? { exposedPorts } : {}),\n workspaceReady: true,\n };\n return {\n backendId: established.backendId,\n [OPENGENI_SANDBOX_PROVIDER_INSTANCE_ID_FIELD]: established.instanceId,\n sessionState,\n };\n } catch {\n // A serialize failure must NOT fail the attach/op; we just lose warm-reattach\n // for this box (it stays resumable-by-instance only via the next cold path).\n return null;\n }\n}\n\n/**\n * Whether a replacement envelope contains a provider-resumable identity. An\n * archive-only envelope is intentionally valid recovery metadata, but it is\n * never proof that the newly-created provider box can be resumed or attached.\n */\nexport function hasPersistableSandboxProviderIdentity(\n envelope: Record<string, unknown> | null | undefined,\n backend?: SandboxBackend | string,\n): envelope is Record<string, unknown> {\n try {\n const resolvedBackend =\n backend ??\n (typeof envelope?.backendId === \"string\"\n ? (sandboxBackendForSdkBackendId(envelope.backendId) ?? envelope.backendId)\n : undefined);\n return resolvedBackend\n ? assertConsistentSandboxProviderIdentity(resolvedBackend, envelope) !== null\n : sandboxProviderInstanceIdFromEnvelope(envelope) !== null;\n } catch {\n return false;\n }\n}\n\n/** A replacement provider may not be published warm without a resumable\n * identity. Archive-only state is retained only when the caller rolls back to\n * cold and needs the verified workspace bytes for the next attempt. */\nexport class SandboxReplacementProviderStateError extends Error {\n readonly code = \"replacement_provider_state_unpersistable\" as const;\n\n constructor(public readonly backend: string) {\n super(\n `sandbox backend \"${backend}\" replacement provider state could not be serialized; refusing to publish an attachable lease`,\n );\n this.name = \"SandboxReplacementProviderStateError\";\n }\n}\n\nexport function requirePersistableReplacementSandboxEnvelope(\n envelope: Record<string, unknown> | null,\n backend: string,\n): Record<string, unknown> {\n const providerInstanceId = assertConsistentSandboxProviderIdentity(backend, envelope);\n if (!envelope || !providerInstanceId) {\n throw new SandboxReplacementProviderStateError(backend);\n }\n return envelope;\n}\n\nconst DURABLE_WORKSPACE_ARCHIVE_FIELDS = [\n \"workspaceArchive\",\n \"workspaceArchiveMeta\",\n \"workspaceArchiveRef\",\n \"workspaceArchivePrev\",\n \"workspaceArchivePrevMeta\",\n \"workspaceArchivePrevRef\",\n \"workspaceArchiveAt\",\n] as const;\n\nfunction durableWorkspaceArchiveFields(\n envelope: Record<string, unknown> | null,\n): Record<string, unknown> | null {\n const sessionState =\n envelope?.sessionState && typeof envelope.sessionState === \"object\"\n ? (envelope.sessionState as Record<string, unknown>)\n : null;\n if (!sessionState) return null;\n const archiveRef = parseWorkspaceArchiveObjectRef(sessionState.workspaceArchiveRef);\n const previousRef = parseWorkspaceArchiveObjectRef(sessionState.workspaceArchivePrevRef);\n const hasInline =\n typeof sessionState.workspaceArchive === \"string\" && sessionState.workspaceArchive.length > 0;\n const hasPreviousInline =\n typeof sessionState.workspaceArchivePrev === \"string\" &&\n sessionState.workspaceArchivePrev.length > 0;\n if (!hasInline && !archiveRef && !hasPreviousInline && !previousRef) {\n return null;\n }\n const fields: Record<string, unknown> = {};\n for (const key of DURABLE_WORKSPACE_ARCHIVE_FIELDS) {\n if (sessionState[key] !== undefined && sessionState[key] !== null) {\n fields[key] = sessionState[key];\n }\n }\n return omitInlineWorkspaceArchiveWhenObjectRefPresent(fields);\n}\n\n/**\n * Build the only resume envelope that may be published for a newly-created\n * replacement sandbox. Historical state contributes durable archive pointers\n * only; it can never substitute for serialization of the replacement's provider\n * identity. If replacement serialization is unavailable or fails, publication\n * keeps an archive-only envelope (when one exists) or null. The new instance id\n * remains separately fenced on the lease, while later attach/resume fails closed\n * rather than targeting the dead provider that initiated rematerialization.\n */\nexport async function serializeReplacementSandboxEnvelope(\n established: EstablishedSandboxSession,\n archiveSource: Record<string, unknown> | null,\n): Promise<Record<string, unknown> | null> {\n const serialized = await serializeEstablishedSandboxEnvelope(established);\n const archiveFields = durableWorkspaceArchiveFields(archiveSource);\n if (!serialized && !archiveFields) {\n return null;\n }\n const serializedSessionState =\n serialized?.sessionState && typeof serialized.sessionState === \"object\"\n ? (serialized.sessionState as Record<string, unknown>)\n : {};\n const sessionState: Record<string, unknown> = {\n ...serializedSessionState,\n ...(archiveFields ?? {}),\n };\n // Spread cannot delete keys. Restore inlines that leaked into serialized\n // replacement state must not survive a durable object-storage ref.\n if (parseWorkspaceArchiveObjectRef(sessionState.workspaceArchiveRef)) {\n delete sessionState.workspaceArchive;\n }\n if (parseWorkspaceArchiveObjectRef(sessionState.workspaceArchivePrevRef)) {\n delete sessionState.workspaceArchivePrev;\n }\n return {\n ...(serialized ?? {}),\n // Never inherit a historical backend marker when the replacement could not\n // serialize. The separately-persisted resume_backend_id and this envelope\n // must both describe the replacement.\n backendId: established.backendId,\n sessionState,\n };\n}\n","import { rmSync } from \"node:fs\";\nimport { lstat, mkdtemp, readdir, readFile, readlink, realpath, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\n/**\n * Private host-archive spool directories are process-owned. In-process callers\n * dispose them on every success/failure path, but a worker that stops while a\n * capture, upload or restore is in flight (rolling deploy, SIGTERM drain, crash)\n * cannot run that cleanup, and each spool holds a whole workspace archive.\n *\n * The directory name therefore records its owner process identity: the PID\n * namespace, PID and kernel start time. A later process may remove a directory\n * only when that exact owner is provably gone: same PID namespace (PIDs from\n * another namespace are not comparable), and that PID either no longer exists or\n * now belongs to a different process start. Live owners, including concurrent\n * workers sharing one TMPDIR, are never touched. Unmarked legacy names are\n * never swept because their owner cannot be proven gone.\n *\n * The same ownership applies to the object-storage download spool\n * (`@opengeni/storage` `downloadWorkspaceArchiveSpool`), which cannot depend on\n * runtime and therefore receives `workspaceArchiveDownloadTemporaryDirectory`\n * from its callers.\n */\nexport const HOST_ARCHIVE_TEMPORARY_PREFIX = \"opengeni-host-archive-\";\nexport const WORKSPACE_ARCHIVE_DOWNLOAD_TEMPORARY_PREFIX = \"opengeni-workspace-archive-\";\nconst OWNER_MARKED_PREFIXES = [\n HOST_ARCHIVE_TEMPORARY_PREFIX,\n WORKSPACE_ARCHIVE_DOWNLOAD_TEMPORARY_PREFIX,\n] as const;\ntype OwnerMarkedPrefix = (typeof OWNER_MARKED_PREFIXES)[number];\n\nfunction ownedName(prefix: OwnerMarkedPrefix): RegExp {\n return new RegExp(\"^\" + prefix + \"o(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)-[A-Za-z0-9]{6}$\");\n}\nconst OWNED_NAMES = OWNER_MARKED_PREFIXES.map(ownedName);\n\ntype ProcessOwner = { namespace: string; pid: number; startTime: string };\n\nasync function processStartTime(pid: number | \"self\"): Promise<string | null> {\n try {\n const stat = await readFile(`/proc/${pid}/stat`, \"utf8\");\n // The command name is parenthesized and may contain spaces or ')'.\n const fields = stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \");\n // Field 22 (starttime) is the 20th field after \"pid (comm)\".\n const startTime = fields[19];\n return startTime && /^\\d+$/.test(startTime) ? startTime : null;\n } catch {\n return null;\n }\n}\n\nasync function pidNamespace(): Promise<string | null> {\n try {\n return /^pid:\\[(\\d+)\\]$/.exec(await readlink(\"/proc/self/ns/pid\"))?.[1] ?? null;\n } catch {\n return null;\n }\n}\n\nlet ownerIdentity: Promise<ProcessOwner | null> | undefined;\nfunction currentOwner(): Promise<ProcessOwner | null> {\n return (ownerIdentity ??= (async () => {\n const [namespace, startTime] = await Promise.all([pidNamespace(), processStartTime(\"self\")]);\n return namespace && startTime ? { namespace, pid: process.pid, startTime } : null;\n })());\n}\n\n/** Spool directories this process still owns; removed on normal process exit. */\nconst liveDirectories = new Set<string>();\nlet exitHookInstalled = false;\nfunction removeLiveDirectoriesOnExit() {\n for (const directory of liveDirectories) {\n try {\n rmSync(directory, { recursive: true, force: true });\n } catch {\n // Exit cleanup is best effort; the next process's sweep reclaims it.\n }\n }\n liveDirectories.clear();\n}\n\n/** Create a private owner-marked spool directory directly under `base`. */\nexport async function createHostArchiveTemporaryDirectory(\n base: string,\n kind: OwnerMarkedPrefix = HOST_ARCHIVE_TEMPORARY_PREFIX,\n): Promise<string> {\n const owner = await currentOwner();\n const prefix = owner ? `${kind}o${owner.namespace}.${owner.pid}.${owner.startTime}-` : kind;\n const directory = await mkdtemp(join(base, prefix));\n liveDirectories.add(directory);\n if (!exitHookInstalled) {\n exitHookInstalled = true;\n process.once(\"exit\", removeLiveDirectoriesOnExit);\n }\n return directory;\n}\n\n/** Remove a spool directory created by this process. Idempotent. */\nexport async function removeHostArchiveTemporaryDirectory(directory: string): Promise<void> {\n await rm(directory, { recursive: true, force: true });\n liveDirectories.delete(directory);\n}\n\nasync function ownerIsGone(\n current: ProcessOwner,\n owner: { namespace: string; pid: number; startTime: string },\n): Promise<boolean> {\n if (owner.namespace !== current.namespace) return false;\n if (owner.pid === current.pid) return owner.startTime !== current.startTime;\n if (!Number.isSafeInteger(owner.pid) || owner.pid < 1) return false;\n const liveStartTime = await processStartTime(owner.pid);\n return liveStartTime !== owner.startTime;\n}\n\n/**\n * Remove spool directories left behind by processes that no longer exist.\n * Returns the removed paths. Never throws: cleanup must not block startup or a\n * capture.\n */\nexport async function sweepOrphanedHostArchiveTemporaryDirectories(\n bases: readonly string[] = hostArchiveTemporaryBases(),\n): Promise<string[]> {\n const removed: string[] = [];\n const current = await currentOwner();\n const uid = typeof process.getuid === \"function\" ? process.getuid() : undefined;\n if (!current || uid === undefined) return removed;\n const seen = new Set<string>();\n for (const candidate of bases) {\n const base = await realpath(candidate).catch(() => null);\n if (!base || seen.has(base)) continue;\n seen.add(base);\n const names = await readdir(base).catch(() => [] as string[]);\n for (const name of names) {\n const match = OWNED_NAMES.map((pattern) => pattern.exec(name)).find(Boolean);\n if (!match) continue;\n const owner = { namespace: match[1]!, pid: Number(match[2]), startTime: match[3]! };\n try {\n if (!(await ownerIsGone(current, owner))) continue;\n const path = join(base, name);\n const stats = await lstat(path);\n if (!stats.isDirectory() || stats.uid !== uid) continue;\n await rm(path, { recursive: true, force: true });\n removed.push(path);\n } catch {\n // Another sweeper removed it, or it is not ours to inspect.\n }\n }\n }\n return removed;\n}\n\n/** The disk temporary locations `privateTemporaryDirectory` may choose. */\nexport function hostArchiveTemporaryBases(): string[] {\n return [tmpdir(), \"/var/tmp\", \"/tmp\"];\n}\n\nlet processSweep: Promise<string[]> | undefined;\n/** Sweep once per process: at worker start and before the first spool or\n * download. Covers every owner-marked prefix. */\nexport function sweepOrphanedHostArchiveTemporaryDirectoriesOnce(): Promise<string[]> {\n return (processSweep ??= sweepOrphanedHostArchiveTemporaryDirectories());\n}\n\n/** Owner-marked private directories for `downloadWorkspaceArchiveSpool`, so a\n * process killed mid-download leaves a directory a later process can prove\n * orphaned and reclaim. */\nexport const workspaceArchiveDownloadTemporaryDirectory = Object.freeze({\n async create(): Promise<string> {\n await sweepOrphanedHostArchiveTemporaryDirectoriesOnce();\n return await createHostArchiveTemporaryDirectory(\n tmpdir(),\n WORKSPACE_ARCHIVE_DOWNLOAD_TEMPORARY_PREFIX,\n );\n },\n remove: removeHostArchiveTemporaryDirectory,\n});\n","import { isDeepStrictEqual } from \"node:util\";\nimport { z } from \"zod\";\nimport { ModalRouterProviderCommand } from \"@opengeni/contracts\";\nimport type { ProviderCommandOutput } from \"../provider-command-session\";\nimport { decodePage } from \"./modal-legacy-command-control\";\nimport { MODAL_ROUTER_READ_PAGE_BYTES } from \"./modal-command-router-wire\";\n\nconst RawStream = z\n .object({\n bytes: z\n .instanceof(Uint8Array)\n .transform((bytes): Uint8Array<ArrayBufferLike> => bytes)\n .refine(\n (bytes) => bytes.byteLength <= MODAL_ROUTER_READ_PAGE_BYTES,\n \"Raw page exceeded its bound\",\n ),\n eof: z.boolean(),\n })\n .strict();\nconst RawExit = z.discriminatedUnion(\"source\", [\n z.object({ source: z.literal(\"router_poll\"), code: z.number().int().nullable() }).strict(),\n z.object({ source: z.literal(\"retained_terminal\"), code: z.number().int() }).strict(),\n]);\nconst RawPage = z\n .object({\n protocol: z.literal(\"modal-router-raw-page-v1\"),\n expected: ModalRouterProviderCommand,\n command: ModalRouterProviderCommand,\n streams: z.object({ stdout: RawStream, stderr: RawStream }).strict(),\n exit: RawExit,\n })\n .strict();\n\n/** Bounded native RPC bytes and their exact cursor projection. The source tag\n * distinguishes a fresh poll from previously captured terminal evidence; it\n * does not authenticate an object supplied by a caller. No Start, custody,\n * database settlement or parent completion authority is conveyed. */\nexport type ModalRawOutputPage = z.infer<typeof RawPage>;\nexport type ModalRawOutputStreams = ModalRawOutputPage[\"streams\"];\nexport type ModalRawOutputExit = ModalRawOutputPage[\"exit\"];\ntype NativeOutput = ProviderCommandOutput & {\n expected: ModalRouterProviderCommand;\n command: ModalRouterProviderCommand;\n};\n\nfunction project(\n expected: ModalRouterProviderCommand,\n streams: ModalRawOutputStreams,\n exit: ModalRawOutputExit,\n): NativeOutput {\n const command = structuredClone(expected);\n const chunks: ProviderCommandOutput[\"chunks\"] = [];\n for (const stream of [\"stdout\", \"stderr\"] as const) {\n const old = expected.streams[stream];\n const page = streams[stream];\n const decoded = decodePage(old.utf8Remainder, [page.bytes], page.eof);\n const byteOffset = old.byteOffset + page.bytes.byteLength;\n if (!Number.isSafeInteger(byteOffset)) throw new Error(\"Modal output offset exhausted\");\n command.streams[stream] = {\n byteOffset,\n utf8Remainder: decoded.remainder,\n eof: page.eof,\n exitCode: page.eof ? exit.code : null,\n };\n if (decoded.text)\n chunks.push({\n stream,\n chunkId: `modal-router:${expected.execId}:${stream}:${old.byteOffset}:${byteOffset}:${page.eof ? 1 : 0}`,\n text: decoded.text,\n });\n }\n return {\n command,\n expected: structuredClone(expected),\n chunks,\n exitCode: command.streams.stdout.eof && command.streams.stderr.eof ? exit.code : null,\n providerExited: exit.code !== null,\n streamFidelity: expected.pty ? \"merged\" : \"separate\",\n };\n}\n\n/** Provider-private construction from joined read/poll replies. Keep the SDK\n * projection unchanged; this pure helper itself is not provider proof. */\nexport function collectModalRawOutputPage(\n command: ModalRouterProviderCommand,\n streams: ModalRawOutputStreams,\n exit: ModalRawOutputExit,\n): { raw: ModalRawOutputPage; output: NativeOutput } {\n const expected = structuredClone(command);\n const captured = {\n stdout: { bytes: Buffer.from(streams.stdout.bytes), eof: streams.stdout.eof },\n stderr: { bytes: Buffer.from(streams.stderr.bytes), eof: streams.stderr.eof },\n };\n const output = project(expected, captured, exit);\n return {\n raw: {\n protocol: \"modal-router-raw-page-v1\",\n expected,\n command: structuredClone(output.command),\n streams: captured,\n exit: { ...exit },\n },\n output,\n };\n}\n\n/** Recompute decoded output from exact bytes, never caller-decoded text. The\n * current cursor must come from the caller's authoritative store. Equality\n * checks are not a database CAS; coherent bytes still need trusted acquisition\n * and atomic capture by the owner. */\nexport function reduceModalRawOutputPage(\n input: ModalRawOutputPage,\n current: ModalRouterProviderCommand,\n): NativeOutput {\n const page = RawPage.parse(input);\n const expected = ModalRouterProviderCommand.parse(current);\n if (!isDeepStrictEqual(page.expected, expected))\n throw new Error(\"Raw page does not match the current native cursor\");\n for (const stream of [\"stdout\", \"stderr\"] as const) {\n const old = expected.streams[stream];\n const raw = page.streams[stream];\n const remainder = Buffer.from(old.utf8Remainder, \"base64\");\n if (\n remainder.toString(\"base64\") !== old.utf8Remainder ||\n remainder.length > 3 ||\n remainder.length > old.byteOffset ||\n (old.eof && remainder.length !== 0)\n )\n throw new Error(\"Raw page has an invalid saved UTF-8 remainder\");\n if (old.eof && (!raw.eof || raw.bytes.byteLength !== 0))\n throw new Error(\"Raw page reopened or advanced a completed stream\");\n if (old.exitCode !== null && page.exit.code !== old.exitCode)\n throw new Error(\"Raw page rewrote captured terminal evidence\");\n }\n if (\n page.exit.source === \"retained_terminal\" &&\n (!expected.streams.stdout.eof ||\n !expected.streams.stderr.eof ||\n expected.streams.stdout.exitCode !== page.exit.code ||\n expected.streams.stderr.exitCode !== page.exit.code)\n )\n throw new Error(\"Raw page has no matching retained terminal evidence\");\n const output = project(expected, page.streams, page.exit);\n if (!isDeepStrictEqual(page.command, output.command))\n throw new Error(\"Raw page cursor delta or remainder does not match its bytes\");\n return output;\n}\n","import { posix } from \"node:path\";\nimport { ModalClient } from \"modal\";\nimport { ModalCommandStartOutcomeUnknownError } from \"./modal-command-start-errors\";\nimport { status } from \"@grpc/grpc-js\";\nimport { ModalCommandStartPreDispatchUnavailableError } from \"./modal-command-router-wire\";\nimport { ProviderCommandStartRejectedError } from \"../provider-command-session\";\nimport { ModalLegacyProviderCommand } from \"@opengeni/contracts\";\nimport type { ChannelAExecArgs } from \"../channel-a\";\nimport { modalCommandArgv } from \"./modal-command-argv\";\n\ntype ControlPlane = Pick<\n ModalClient[\"cpClient\"],\n | \"sandboxGetTaskId\"\n | \"containerExec\"\n | \"containerExecGetOutput\"\n | \"containerExecPutInput\"\n | \"taskGetCommandRouterAccess\"\n>;\n\ntype CommandClient = Pick<ModalClient, \"cpClient\" | \"version\"> &\n Partial<Pick<ModalClient, \"profile\" | \"logger\">>;\ntype GrpcMiddleware = NonNullable<\n NonNullable<ConstructorParameters<typeof ModalClient>[0]>[\"grpcMiddleware\"]\n>[number];\n/** This dedicated command client never retries a request behind the caller's\n * back and preserves the exact cancellation signal, including streaming RPCs. */\nexport const modalCommandAbortMiddleware: GrpcMiddleware = async function* (call, options) {\n options.signal?.throwIfAborted();\n return yield* call.next(call.request, options);\n};\n\n// Version-pinned compatibility boundary: 0.9.0's retryMiddleware drops signal\n// for streaming and retries=0. Its public custom middleware runs OUTSIDE that\n// branch, so cannot repair it. Override only this dedicated instance's factory\n// hook before construction; never mutate the SDK's global prototype or use\n// negative/fractional retry counts to manipulate its branch conditions.\ntype PublicModalClient = Pick<ModalClient, keyof ModalClient>;\nconst ModalClientBase: new (\n options?: ConstructorParameters<typeof ModalClient>[0],\n) => PublicModalClient = ModalClient;\nclass ModalCommandClient extends ModalClientBase {\n retryMiddleware(): GrpcMiddleware {\n return modalCommandAbortMiddleware;\n }\n}\nconst controlClients = new WeakMap<object, PublicModalClient>();\n\nexport function commandControlPlane(client: CommandClient): ControlPlane {\n // Minimal injected control planes are used by deterministic unit tests.\n // Production installation requires the authenticated SDK profile below.\n if (!client.profile) return client.cpClient;\n if (typeof Reflect.get(ModalClient.prototype, \"retryMiddleware\") !== \"function\")\n throw new Error(\"Verified Modal command cancellation contract is unavailable\");\n let controlled = controlClients.get(client);\n if (!controlled) {\n const profile = client.profile;\n if (!profile.tokenId || !profile.tokenSecret)\n throw new Error(\"Modal command control requires its original authenticated profile\");\n controlled = new ModalCommandClient({\n tokenId: profile.tokenId,\n tokenSecret: profile.tokenSecret,\n endpoint: profile.serverUrl,\n environment: profile.environment ?? \"\",\n ...(profile.maxThrottleWaitSecs !== undefined\n ? { maxThrottleWaitSecs: profile.maxThrottleWaitSecs }\n : {}),\n ...(client.logger ? { logger: client.logger } : {}),\n });\n controlClients.set(client, controlled);\n }\n return controlled.cpClient;\n}\nexport type ModalCommandStream = \"stdout\" | \"stderr\";\nexport type ModalProviderCommand = ModalLegacyProviderCommand;\nexport type ModalProviderOutputPage = {\n command: ModalProviderCommand;\n chunks: Array<{ stream: ModalCommandStream; chunkId: string; text: string }>;\n exitCode: number | null;\n streamFidelity: \"separate\" | \"merged\";\n};\n\n// A provider batch may end halfway through a UTF-8 character. Keep only that\n// unfinished suffix in protected cursor state; invalid complete bytes still\n// use the usual replacement-character decoding policy.\nexport function decodePage(prior: string, input: Uint8Array[], terminal: boolean) {\n const bytes = Buffer.concat([Buffer.from(prior, \"base64\"), ...input]);\n let boundary = bytes.length;\n if (!terminal) {\n for (let start = Math.max(0, bytes.length - 3); start < bytes.length; start++) {\n const first = bytes[start]!;\n const width =\n first >= 0xc2 && first <= 0xdf\n ? 2\n : first >= 0xe0 && first <= 0xef\n ? 3\n : first >= 0xf0 && first <= 0xf4\n ? 4\n : 0;\n if (!width || bytes.length - start >= width) continue;\n const suffix = bytes.subarray(start + 1);\n if (!suffix.every((byte) => byte >= 0x80 && byte <= 0xbf)) continue;\n const second = suffix[0];\n if (\n second !== undefined &&\n ((first === 0xe0 && second < 0xa0) ||\n (first === 0xed && second > 0x9f) ||\n (first === 0xf0 && second < 0x90) ||\n (first === 0xf4 && second > 0x8f))\n )\n continue;\n boundary = start;\n break;\n }\n }\n return {\n text: bytes.subarray(0, boundary).toString(\"utf8\"),\n remainder: bytes.subarray(boundary).toString(\"base64\"),\n };\n}\n\n/** Version-pinned Modal control-plane boundary. Execution identity, output\n * batches and exit status come from authenticated provider RPCs, never sandbox\n * files or an SDK object's in-memory process map. Callers must store the\n * returned locator/cursors outside the command's write authority. */\nexport class ModalCommandControl {\n private constructor(\n private readonly client: ControlPlane,\n private readonly sandboxIdentity: string | (() => string),\n private readonly root: string,\n private readonly environment: Record<string, string> | (() => Record<string, string>) = {},\n ) {}\n\n static forSandbox(\n client: CommandClient,\n sandboxId: string | (() => string),\n root: string,\n environment: Record<string, string> | (() => Record<string, string>) = {},\n ): ModalCommandControl {\n if (client.version() !== \"0.9.0\")\n throw new Error(\"Modal command control requires the verified 0.9.0 SDK contract\");\n return new ModalCommandControl(commandControlPlane(client), sandboxId, root, environment);\n }\n\n private get sandboxId(): string {\n return typeof this.sandboxIdentity === \"function\"\n ? this.sandboxIdentity()\n : this.sandboxIdentity;\n }\n\n async start(args: ChannelAExecArgs, signal?: AbortSignal): Promise<ModalProviderCommand> {\n signal?.throwIfAborted();\n const workdir = posix.resolve(this.root, args.workdir ?? this.root);\n if (workdir !== this.root && !workdir.startsWith(`${this.root.replace(/\\/$/u, \"\")}/`))\n throw new Error(\"Command workdir is outside the sandbox workspace\");\n // Hydration replaces the SDK sandbox. Freeze its current identity for this\n // start so an asynchronous replacement cannot relabel the returned locator.\n const sandboxId = this.sandboxId;\n const task = await ModalCommandStartPreDispatchUnavailableError.beforeDispatch(\n () => this.client.sandboxGetTaskId({ sandboxId }, signal ? { signal } : undefined),\n signal,\n );\n if (!task.taskId || task.taskResult) throw new Error(\"Modal command task is unavailable\");\n if (sandboxId !== this.sandboxId)\n throw new Error(\"Modal sandbox changed during command preparation\");\n let command = modalCommandArgv(args);\n const environment =\n typeof this.environment === \"function\" ? this.environment() : this.environment;\n if (Object.keys(environment).length) {\n command = [\n \"/usr/bin/env\",\n \"--\",\n ...Object.entries(environment).map(([key, value]) => `${key}=${value}`),\n ...command,\n ];\n }\n // Do not retry this mutating start on an ambiguous transport error: this\n // provider API assigns the execution id in its response, not in our request.\n const result = await this.client\n .containerExec(\n {\n taskId: task.taskId,\n command,\n terminateContainerOnExit: false,\n runtimeDebug: false,\n stdoutOutput: 2,\n stderrOutput: 2,\n timeoutSecs: 0,\n workdir,\n secretIds: [],\n ...(args.tty\n ? {\n ptyInfo: {\n enabled: true,\n winszRows: 24,\n winszCols: 80,\n envTerm: \"xterm\",\n envColorterm: \"\",\n envTermProgram: \"\",\n ptyType: 1,\n noTerminateOnIdleStdin: true,\n },\n }\n : {}),\n },\n { retries: 0, ...(signal ? { signal } : {}) },\n )\n .catch((error: unknown) => {\n const code = (error as { code?: unknown } | null)?.code;\n if (\n typeof code === \"number\" &&\n [\n status.INVALID_ARGUMENT,\n status.NOT_FOUND,\n status.PERMISSION_DENIED,\n status.UNAUTHENTICATED,\n status.UNIMPLEMENTED,\n ].includes(code)\n )\n throw new ProviderCommandStartRejectedError(error);\n // Legacy ContainerExec assigns its id in the lost response. There is no\n // safe invocation locator and no authority to issue another launch.\n throw new ModalCommandStartOutcomeUnknownError(task.taskId!, \"\", error);\n });\n if (!result.execId)\n throw new ModalCommandStartOutcomeUnknownError(\n task.taskId,\n \"\",\n new Error(\"Modal command start returned no execution identity\"),\n );\n return {\n kind: \"modal-control-v1\",\n sandboxId,\n taskId: task.taskId,\n execId: result.execId,\n ...(args.tty ? { pty: true } : {}),\n streams: {\n stdout: { batchIndex: 0, utf8Remainder: \"\", exitCode: null },\n stderr: { batchIndex: 0, utf8Remainder: \"\", exitCode: null },\n },\n };\n }\n\n async read(\n command: ModalProviderCommand,\n yieldTimeMs: number,\n signal?: AbortSignal,\n ): Promise<ModalProviderOutputPage> {\n return this.readOutput(command, yieldTimeMs, signal);\n }\n\n /** Fixed internal probes own their cancellation controller and must drain\n * both reads before relinquishing the surrounding provider-operation gate.\n * Retained-command readers keep their existing signal/receipt contract.\n */\n async readProbe(\n command: ModalProviderCommand,\n yieldTimeMs: number,\n cancellation: AbortController,\n ): Promise<ModalProviderOutputPage> {\n return this.readOutput(command, yieldTimeMs, cancellation.signal, (error) =>\n cancellation.abort(error),\n );\n }\n\n private async readOutput(\n command: ModalProviderCommand,\n yieldTimeMs: number,\n signal?: AbortSignal,\n cancelSiblings?: (error: unknown) => void,\n ): Promise<ModalProviderOutputPage> {\n signal?.throwIfAborted();\n this.assertIdentity(command);\n const next = structuredClone(command);\n let failure: { error: unknown } | undefined;\n const reads = ([\"stdout\", \"stderr\"] as const)\n .map(async (stream) => {\n const cursor = command.streams[stream];\n if (cursor.exitCode !== null) return null;\n const descriptor = stream === \"stdout\" ? 1 : 2;\n for await (const batch of this.client.containerExecGetOutput(\n {\n execId: command.execId,\n timeout: Math.max(0, yieldTimeMs) / 1000,\n lastBatchIndex: cursor.batchIndex,\n fileDescriptor: descriptor,\n getRawBytes: true,\n },\n signal ? { signal } : undefined,\n )) {\n if (batch.batchIndex <= cursor.batchIndex) continue;\n if (!Number.isSafeInteger(batch.batchIndex))\n throw new Error(\"Invalid Modal output cursor\");\n const terminal = batch.exitCode !== undefined;\n if (terminal && !Number.isSafeInteger(batch.exitCode))\n throw new Error(\"Invalid Modal exit status\");\n const decoded = decodePage(\n cursor.utf8Remainder,\n batch.items\n .filter((item) => item.fileDescriptor === descriptor)\n .map((item) => item.messageBytes),\n terminal,\n );\n next.streams[stream] = {\n batchIndex: batch.batchIndex,\n utf8Remainder: decoded.remainder,\n exitCode: terminal ? batch.exitCode! : null,\n };\n return {\n stream,\n chunkId: `modal:${command.execId}:${stream}:${cursor.batchIndex}:${batch.batchIndex}`,\n text: decoded.text,\n };\n }\n return null;\n })\n .map((read) =>\n !cancelSiblings\n ? read\n : read.catch((error: unknown) => {\n // A logical read owns both output streams. Promise.all alone releases\n // its caller on the first rejection while a sibling RPC may still be\n // running. Cancel that sibling, retain the original error, and drain\n // both reads before returning control to mutation/capture ownership.\n failure ??= { error };\n cancelSiblings(error);\n throw error;\n }),\n );\n const pages = cancelSiblings\n ? await Promise.allSettled(reads).then((results) => {\n if (failure) throw failure.error;\n return results.map((result) => {\n if (result.status === \"rejected\") throw result.reason;\n return result.value;\n });\n })\n : await Promise.all(reads);\n const stdoutExit = next.streams.stdout.exitCode;\n const stderrExit = next.streams.stderr.exitCode;\n if (stdoutExit !== null && stderrExit !== null && stdoutExit !== stderrExit)\n throw new Error(\"Modal output streams disagree about command exit status\");\n return {\n command: next,\n streamFidelity: command.pty ? \"merged\" : \"separate\",\n chunks: pages.filter((page): page is NonNullable<typeof page> => page !== null),\n exitCode: stdoutExit !== null && stderrExit !== null ? stdoutExit : null,\n };\n }\n\n async write(command: ModalProviderCommand, chars: string, messageIndex: number): Promise<void> {\n this.assertIdentity(command);\n if (!chars) return;\n if (!Number.isSafeInteger(messageIndex) || messageIndex < 1)\n throw new Error(\"Modal stdin requires a protected monotonic message index\");\n await this.client.containerExecPutInput(\n {\n execId: command.execId,\n input: { message: Buffer.from(chars), messageIndex, eof: false },\n },\n { retries: 0 },\n );\n }\n\n private assertIdentity(command: ModalProviderCommand): void {\n ModalLegacyProviderCommand.parse(command);\n if (\n command.kind !== \"modal-control-v1\" ||\n command.sandboxId !== this.sandboxId ||\n !command.taskId ||\n !command.execId\n )\n throw new Error(\"Modal command locator does not match the original sandbox\");\n }\n}\n","import type { ChannelAExecArgs } from \"../channel-a\";\n\n/** Keep the command payload once in argv. Embedding it in each run-as branch\n * multiplies large lifecycle scripts past the provider's aggregate limit. */\nexport function modalCommandArgv(args: ChannelAExecArgs): string[] {\n const command = [\n args.shell ?? \"/bin/sh\",\n args.shell && (args.login ?? true) ? \"-lc\" : \"-c\",\n args.cmd,\n ];\n if (!args.runAs) return command;\n return [\n \"/bin/sh\",\n \"-c\",\n 'user=$1; shift; if [ \"$(id -u)\" = \"$user\" ] || [ \"$(id -un 2>/dev/null)\" = \"$user\" ]; then exec \"$@\"; elif [ \"$(id -u)\" = 0 ]; then exec su -s /bin/sh -c \\'exec \"$@\"\\' -- \"$user\" sh \"$@\"; else exec sudo -n -u \"$user\" -- \"$@\"; fi',\n \"opengeni-run-as\",\n args.runAs,\n ...command,\n ];\n}\n","import { createHash, type Hash } from \"node:crypto\";\nimport { constants, type BigIntStats } from \"node:fs\";\nimport {\n lstat,\n mkdir,\n open,\n readdir,\n realpath,\n rmdir,\n unlink,\n type FileHandle,\n} from \"node:fs/promises\";\nimport { isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport type { WorkspaceTreeFingerprint } from \"@opengeni/contracts\";\nimport type { WorkspaceArchiveSpool } from \"./archive-spool\";\nimport {\n WorkspaceArchiveIntegrityError,\n workspaceContentManifest,\n type WorkspaceContentEntry,\n type WorkspaceContentManifest,\n} from \"./workspace-archive\";\nimport {\n createHostArchiveTemporaryDirectory,\n hostArchiveTemporaryBases,\n removeHostArchiveTemporaryDirectory,\n sweepOrphanedHostArchiveTemporaryDirectoriesOnce,\n} from \"./host-archive-temporary\";\n\nconst CHUNK_BYTES = 64 * 1024;\n// Filesystem representability, not an archive resource quota. Check component\n// UTF-8 bytes before clearing a destination, not after open/mkdir fails.\nconst HOST_FILENAME_BYTES = 255;\nconst PROJECTION = \"sdk_local_archive_v1\" as const;\nconst READ = constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK;\nconst READ_DIRECTORY = READ | constants.O_DIRECTORY;\nconst CREATE = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW;\n\n/** Matches SDK 0.14.3 resolveSandboxArchiveLimits: absent/null means unlimited;\n * an explicit object fills undefined fields with SDK defaults, null disables a field.\n * chunkBytes controls buffering, never the amount of input accepted. */\nexport type HostWorkspaceArchiveOptions = {\n chunkBytes?: number;\n archiveLimits?: {\n maxInputBytes?: number | null;\n maxExtractedBytes?: number | null;\n maxMembers?: number | null;\n } | null;\n};\n\nfunction invalid(message: string): never {\n throw new WorkspaceArchiveIntegrityError(\"archive_hydration_failed\", message);\n}\n\nfunction changed(cause?: unknown): never {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_changed_during_capture\",\n \"host workspace changed during archive observation\",\n { retryable: true, cause },\n );\n}\n\nfunction captureError(error: unknown): never {\n if (error instanceof WorkspaceArchiveIntegrityError) throw error;\n const code = (error as NodeJS.ErrnoException | null)?.code;\n if (code === \"ENOENT\" || code === \"ELOOP\" || code === \"ENOTDIR\") return changed(error);\n // Disk exhaustion, permission failures and other operational errors are not\n // evidence of a changing tree and must not become a retryable race diagnosis.\n throw error;\n}\n\nfunction chunkSize(options: HostWorkspaceArchiveOptions): number {\n const size = options.chunkBytes ?? CHUNK_BYTES;\n if (!Number.isSafeInteger(size) || size < 1 || size > CHUNK_BYTES) {\n throw new RangeError(`chunkBytes must be between 1 and ${CHUNK_BYTES}`);\n }\n return size;\n}\n\nfunction limitsFor(options: HostWorkspaceArchiveOptions) {\n if (options.archiveLimits == null) return null;\n const defaults = {\n maxInputBytes: 1024 ** 3,\n maxExtractedBytes: 4 * 1024 ** 3,\n maxMembers: 100_000,\n };\n const limits = { ...defaults, ...options.archiveLimits };\n for (const key of Object.keys(defaults) as Array<keyof typeof defaults>) {\n if (limits[key] === undefined) limits[key] = defaults[key];\n const value = limits[key];\n if (value != null && (!Number.isSafeInteger(value) || value < 1)) {\n throw new RangeError(`archiveLimits.${key} must be at least 1`);\n }\n }\n return limits;\n}\n\nfunction checkLimit(actual: number, limit: number | null | undefined, label: string) {\n if (!Number.isSafeInteger(actual)) invalid(`${label} exceeds the supported integer range`);\n if (limit != null && actual > limit)\n invalid(`workspace archive ${label} exceeds configured limit`);\n}\n\nfunction sameEntry(a: BigIntStats, b: BigIntStats) {\n return a.dev === b.dev && a.ino === b.ino && a.mode === b.mode;\n}\n\nfunction sameVersion(a: BigIntStats, b: BigIntStats) {\n return sameEntry(a, b) && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;\n}\n\nfunction fdPath(handle: FileHandle, name?: string) {\n return name === undefined ? `/proc/self/fd/${handle.fd}` : `/proc/self/fd/${handle.fd}/${name}`;\n}\n\n/** Node has no openat API. Linux's descriptor namespace supplies the same pinned\n * parent resolution; O_NOFOLLOW applies to the child, never an untrusted ancestor.\n * Do not replace this with lstat(path) followed by open(path): that races. */\nexport type HostWorkspaceRootIdentity = Readonly<{\n dev: string;\n ino: string;\n uid: string;\n gid: string;\n mode: string;\n}>;\n\nfunction rootIdentity(stats: BigIntStats): HostWorkspaceRootIdentity {\n return Object.freeze({\n dev: String(stats.dev),\n ino: String(stats.ino),\n uid: String(stats.uid),\n gid: String(stats.gid),\n mode: String(stats.mode),\n });\n}\n\nasync function openRoot(\n root: string,\n create = false,\n expected?: HostWorkspaceRootIdentity,\n): Promise<FileHandle> {\n if (process.platform !== \"linux\")\n invalid(\"host archive codec requires Linux descriptor-relative filesystem access\");\n if (!isAbsolute(root)) invalid(\"host workspace root must be absolute\");\n const absolute = resolve(root);\n if (create && absolute === sep) invalid(\"cannot restore into the filesystem root\");\n let current = await open(sep, READ_DIRECTORY);\n try {\n for (const segment of absolute.split(sep).filter(Boolean)) {\n if (create) {\n await mkdir(fdPath(current, segment), { mode: 0o777 }).catch(\n (error: NodeJS.ErrnoException) => {\n if (error.code !== \"EEXIST\") throw error;\n },\n );\n }\n const next = await open(fdPath(current, segment), READ_DIRECTORY);\n await current.close();\n current = next;\n }\n if (expected) {\n const actual = rootIdentity(await current.stat({ bigint: true }));\n if (\n Object.keys(actual).some(\n (key) =>\n actual[key as keyof HostWorkspaceRootIdentity] !==\n expected[key as keyof HostWorkspaceRootIdentity],\n )\n )\n invalid(\"owned workspace root identity changed\");\n }\n return current;\n } catch (error) {\n await current.close();\n throw error;\n }\n}\n\n/** Metadata only. Content readers repeat this identity comparison on their\n * opened directory descriptor before inventory or file reads. */\nexport async function readHostWorkspaceRootIdentity(\n root: string,\n expected?: HostWorkspaceRootIdentity,\n): Promise<HostWorkspaceRootIdentity> {\n if (process.platform !== \"linux\") {\n if (!isAbsolute(root) || resolve(root) !== root || (await realpath(root)) !== root)\n invalid(\"owned workspace root is not canonical\");\n const handle = await open(root, READ_DIRECTORY);\n try {\n const stats = await handle.stat({ bigint: true });\n if (!stats.isDirectory()) invalid(\"owned workspace root is not a directory\");\n const actual = rootIdentity(stats);\n if (\n expected &&\n Object.keys(actual).some(\n (key) =>\n actual[key as keyof HostWorkspaceRootIdentity] !==\n expected[key as keyof HostWorkspaceRootIdentity],\n )\n )\n invalid(\"owned workspace root identity changed\");\n return actual;\n } finally {\n await handle.close();\n }\n }\n const handle = await openRoot(root, false, expected);\n try {\n return rootIdentity(await handle.stat({ bigint: true }));\n } finally {\n await handle.close();\n }\n}\n\ntype TreeIndex = {\n directories: Map<string, BigIntStats>;\n files: Map<string, BigIntStats>;\n};\n\nconst compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);\n\nasync function inventory(\n root: FileHandle,\n excludedPaths: readonly string[],\n signal?: AbortSignal,\n): Promise<TreeIndex> {\n const tree: TreeIndex = { directories: new Map(), files: new Map() };\n const walk = async (handle: FileHandle, logical: string) => {\n const before = await handle.stat({ bigint: true });\n tree.directories.set(logical, before);\n const names = await readdir(fdPath(handle));\n for (const name of names) {\n signal?.throwIfAborted();\n const path = logical ? `${logical}/${name}` : name;\n if (\n excludedPaths.some(\n (excluded) => excluded === \"\" || path === excluded || path.startsWith(`${excluded}/`),\n )\n )\n continue;\n const stats = await lstat(fdPath(handle, name), { bigint: true });\n if (stats.isDirectory()) {\n const child = await open(fdPath(handle, name), READ_DIRECTORY);\n try {\n if (!sameVersion(stats, await child.stat({ bigint: true }))) changed();\n await walk(child, path);\n if (!sameVersion(stats, await lstat(fdPath(handle, name), { bigint: true }))) changed();\n } finally {\n await child.close();\n }\n } else if (stats.isFile()) {\n tree.files.set(path, stats);\n }\n // Exactly the SDK projection: symlinks, FIFOs, sockets and devices are skipped.\n }\n if (!sameVersion(before, await handle.stat({ bigint: true }))) changed();\n };\n await walk(root, \"\");\n return tree;\n}\n\nasync function openDirectory(root: FileHandle, logical: string, tree?: TreeIndex, create = false) {\n let current = await open(fdPath(root), READ_DIRECTORY & ~constants.O_NOFOLLOW);\n try {\n if (tree && !sameVersion(tree.directories.get(\"\")!, await current.stat({ bigint: true })))\n changed();\n let path = \"\";\n for (const segment of logical.split(\"/\").filter(Boolean)) {\n path = path ? `${path}/${segment}` : segment;\n if (create) {\n await mkdir(fdPath(current, segment), { mode: 0o777 }).catch(\n (error: NodeJS.ErrnoException) => {\n if (error.code !== \"EEXIST\") throw error;\n },\n );\n }\n const next = await open(fdPath(current, segment), READ_DIRECTORY);\n await current.close();\n current = next;\n if (tree) {\n const expected = tree.directories.get(path);\n if (!expected || !sameVersion(expected, await current.stat({ bigint: true }))) changed();\n }\n }\n return current;\n } catch (error) {\n await current.close();\n throw error;\n }\n}\n\nfunction parentAndName(path: string): [string, string] {\n const slash = path.lastIndexOf(\"/\");\n return slash < 0 ? [\"\", path] : [path.slice(0, slash), path.slice(slash + 1)];\n}\n\nasync function readTreeFile(\n root: FileHandle,\n tree: TreeIndex,\n path: string,\n consume: (bytes: Buffer) => void | Promise<void>,\n signal?: AbortSignal,\n) {\n const [parent, name] = parentAndName(path);\n const directory = await openDirectory(root, parent, tree);\n try {\n const expected = tree.files.get(path)!;\n const handle = await open(fdPath(directory, name), READ);\n try {\n if (!sameVersion(expected, await handle.stat({ bigint: true }))) changed();\n const size = Number(expected.size);\n checkLimit(size, null, \"file size\");\n const buffer = Buffer.allocUnsafe(CHUNK_BYTES);\n let offset = 0;\n while (offset < size) {\n signal?.throwIfAborted();\n const { bytesRead } = await handle.read(\n buffer,\n 0,\n Math.min(buffer.length, size - offset),\n offset,\n );\n if (bytesRead === 0) changed();\n await consume(buffer.subarray(0, bytesRead));\n offset += bytesRead;\n }\n if (\n !sameVersion(expected, await handle.stat({ bigint: true })) ||\n !sameVersion(expected, await lstat(fdPath(directory, name), { bigint: true }))\n )\n changed();\n } finally {\n await handle.close();\n }\n } finally {\n await directory.close();\n }\n}\n\nfunction frame(hash: Hash, label: string, value: string) {\n hash\n .update(label)\n .update(\"\\0\")\n .update(String(Buffer.byteLength(value)))\n .update(\"\\0\")\n .update(value)\n .update(\"\\0\");\n}\n\nfunction projection(directories: readonly string[]) {\n const hash = createHash(\"sha256\");\n frame(hash, \"projection\", PROJECTION);\n for (const path of [...directories].sort(compare)) frame(hash, \"dir\", path);\n return hash;\n}\n\nfunction fingerprint(\n hash: Hash,\n directories: number,\n files: number,\n totalFileBytes: number,\n): WorkspaceTreeFingerprint {\n checkLimit(totalFileBytes, null, \"extracted size\");\n return {\n algorithm: \"sha256\",\n sha256: hash.digest(\"hex\"),\n entryCount: directories + files,\n fileCount: files,\n totalFileBytes,\n projection: PROJECTION,\n };\n}\n\nasync function verifyInventory(\n rootPath: string,\n root: FileHandle,\n tree: TreeIndex,\n signal?: AbortSignal,\n) {\n const fresh = await openRoot(rootPath);\n try {\n if (!sameVersion(tree.directories.get(\"\")!, await fresh.stat({ bigint: true }))) changed();\n } finally {\n await fresh.close();\n }\n for (const path of tree.directories.keys()) {\n signal?.throwIfAborted();\n const handle = await openDirectory(root, path, tree);\n await handle.close();\n }\n for (const [path, expected] of tree.files) {\n signal?.throwIfAborted();\n const [parent, name] = parentAndName(path);\n const handle = await openDirectory(root, parent, tree);\n try {\n if (!sameVersion(expected, await lstat(fdPath(handle, name), { bigint: true }))) changed();\n } finally {\n await handle.close();\n }\n }\n}\n\nasync function hashTree(rootPath: string, root: FileHandle, tree: TreeIndex, signal?: AbortSignal) {\n const directories = [...tree.directories.keys()].filter(Boolean);\n const hash = projection(directories);\n let total = 0;\n for (const path of [...tree.files.keys()].sort(compare)) {\n const size = Number(tree.files.get(path)!.size);\n frame(hash, \"file\", path);\n frame(hash, \"bytes\", String(size));\n signal?.throwIfAborted();\n await readTreeFile(\n root,\n tree,\n path,\n (bytes) => {\n hash.update(bytes);\n },\n signal,\n );\n total += size;\n }\n await verifyInventory(rootPath, root, tree, signal);\n return fingerprint(hash, directories.length, tree.files.size, total);\n}\n\nexport async function fingerprintHostWorkspace(\n root: string,\n excludedPaths: readonly string[],\n expectedRoot?: HostWorkspaceRootIdentity,\n): Promise<WorkspaceTreeFingerprint> {\n const handle = await openRoot(root, false, expectedRoot);\n try {\n return await hashTree(root, handle, await inventory(handle, excludedPaths));\n } catch (error) {\n return captureError(error);\n } finally {\n await handle.close();\n }\n}\n\nfunction within(root: string, candidate: string) {\n const path = relative(root, candidate);\n return path === \"\" || (!isAbsolute(path) && path !== \"..\" && !path.startsWith(`..${sep}`));\n}\n\nasync function privateTemporaryDirectory(root: string | null) {\n // Resolve the actual location before creating anything: TMPDIR can itself be a\n // symlink or live inside the source workspace. Never add spool files to it.\n const actualRoot = root === null ? null : await realpath(root).catch(() => resolve(root));\n // Reclaim spools whose owner process stopped mid-capture/upload/restore\n // before adding another multi-gigabyte one. Never removes a live owner's.\n await sweepOrphanedHostArchiveTemporaryDirectoriesOnce();\n for (const candidate of hostArchiveTemporaryBases()) {\n const base = await realpath(candidate).catch(() => null);\n if (!base || (actualRoot !== null && within(actualRoot, base)) || within(\"/dev/shm\", base))\n continue;\n return await createHostArchiveTemporaryDirectory(base);\n }\n invalid(\"no private disk temporary directory exists outside the workspace\");\n}\n\nasync function writeAll(handle: FileHandle, bytes: Uint8Array) {\n let offset = 0;\n while (offset < bytes.byteLength) {\n const { bytesWritten } = await handle.write(bytes, offset, bytes.byteLength - offset);\n if (!bytesWritten) throw new Error(\"archive spool write made no progress\");\n offset += bytesWritten;\n }\n}\n\nclass ArchiveWriter {\n readonly hash = createHash(\"sha256\");\n byteSize = 0;\n constructor(readonly handle: FileHandle) {}\n async write(input: string | Uint8Array) {\n const bytes = typeof input === \"string\" ? Buffer.from(input) : input;\n for (let offset = 0; offset < bytes.length; offset += CHUNK_BYTES) {\n const chunk = bytes.subarray(offset, offset + CHUNK_BYTES);\n await writeAll(this.handle, chunk);\n this.hash.update(chunk);\n this.byteSize += chunk.length;\n checkLimit(this.byteSize, null, \"input size\");\n }\n }\n}\n\n/** Native base64 conversion remains bounded to a chunk; both binary backing\n * stores are reused. In particular, never Buffer.concat the carry with every\n * source chunk or Buffer.from every encoded string: external-memory GC can lag\n * far behind those allocations even though no individual buffer is large. */\nclass Base64Encoder {\n private readonly input = Buffer.allocUnsafe(CHUNK_BYTES + 2);\n private readonly output = Buffer.allocUnsafe(Math.ceil((CHUNK_BYTES + 2) / 3) * 4);\n private carry = 0;\n constructor(private readonly writer: ArchiveWriter) {}\n async write(bytes: Buffer) {\n bytes.copy(this.input, this.carry);\n const available = this.carry + bytes.length;\n const length = available - (available % 3);\n if (length) await this.encode(length);\n this.carry = available - length;\n this.input.copy(this.input, 0, length, available);\n }\n private async encode(length: number) {\n const written = this.output.write(this.input.subarray(0, length).toString(\"base64\"), \"ascii\");\n await this.writer.write(this.output.subarray(0, written));\n }\n async finish() {\n if (this.carry) await this.encode(this.carry);\n }\n}\n\nfunction ownedSpool(\n directory: string,\n path: string,\n byteSize: number,\n sha256: string,\n): WorkspaceArchiveSpool {\n let disposal: Promise<void> | undefined;\n return {\n path,\n byteSize,\n sha256,\n async *open() {\n if (disposal) throw new Error(\"archive spool has been disposed\");\n const handle = await open(path, READ);\n try {\n const before = await handle.stat({ bigint: true });\n if (!before.isFile() || Number(before.size) !== byteSize) invalid(\"archive spool changed\");\n let position = 0;\n while (position < byteSize) {\n const buffer = Buffer.allocUnsafe(Math.min(CHUNK_BYTES, byteSize - position));\n const { bytesRead } = await handle.read(buffer, 0, buffer.length, position);\n if (!bytesRead) invalid(\"archive spool was truncated\");\n position += bytesRead;\n yield buffer.subarray(0, bytesRead);\n }\n if (!sameVersion(before, await handle.stat({ bigint: true })))\n invalid(\"archive spool changed while reading\");\n } finally {\n await handle.close();\n }\n },\n dispose() {\n return (disposal ??= removeHostArchiveTemporaryDirectory(directory));\n },\n };\n}\n\n/**\n * An aborted `signal` stops the capture at the next file chunk, removes its\n * temporary spool and rejects with the signal's reason. Every read is local\n * and owned here, so the rejection is the physical end of the capture: callers\n * may treat it as settled.\n */\nexport async function captureHostWorkspaceArchive(\n root: string,\n excludedPaths: readonly string[],\n expectedRoot?: HostWorkspaceRootIdentity,\n signal?: AbortSignal,\n): Promise<{\n spool: WorkspaceArchiveSpool;\n workspace: WorkspaceTreeFingerprint;\n}> {\n signal?.throwIfAborted();\n const handle = await openRoot(root, false, expectedRoot);\n let temporary: string | undefined;\n let handleClosed = false;\n try {\n const tree = await inventory(handle, excludedPaths, signal);\n const before = await hashTree(root, handle, tree, signal);\n temporary = await privateTemporaryDirectory(root);\n const path = join(temporary, \"archive.json\");\n const file = await open(path, CREATE, 0o600);\n const writer = new ArchiveWriter(file);\n const directories = [...tree.directories.keys()].filter(Boolean).sort(compare);\n const hash = projection(directories);\n let total = 0;\n try {\n await writer.write('{\"version\":1,\"directories\":[');\n for (let index = 0; index < directories.length; index++) {\n await writer.write(`${index ? \",\" : \"\"}${JSON.stringify(directories[index])}`);\n }\n await writer.write('],\"files\":[');\n let first = true;\n for (const logical of [...tree.files.keys()].sort(compare)) {\n const size = Number(tree.files.get(logical)!.size);\n frame(hash, \"file\", logical);\n frame(hash, \"bytes\", String(size));\n await writer.write(`${first ? \"\" : \",\"}{\"path\":${JSON.stringify(logical)},\"data\":\"`);\n first = false;\n const encoder = new Base64Encoder(writer);\n await readTreeFile(\n handle,\n tree,\n logical,\n async (bytes) => {\n hash.update(bytes);\n await encoder.write(bytes);\n },\n signal,\n );\n await encoder.finish();\n await writer.write('\"}');\n total += size;\n }\n await writer.write(\"]}\");\n } finally {\n await file.close();\n }\n const archived = fingerprint(hash, directories.length, tree.files.size, total);\n // Prove equivalence of the serialized bytes themselves, not just of the\n // source chunks passed to the base64 encoder.\n const encoded = await open(path, READ);\n const payloadPath = join(temporary, \"capture-payload\");\n let decoded: WorkspaceTreeFingerprint;\n try {\n const payload = await open(\n payloadPath,\n constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,\n 0o600,\n );\n try {\n signal?.throwIfAborted();\n const index = await indexArchive(encoded, payload, {}, signal);\n signal?.throwIfAborted();\n decoded = await fingerprintArchiveIndex(index, payload, signal);\n } finally {\n await payload.close();\n }\n } finally {\n await encoded.close();\n }\n await unlink(payloadPath);\n signal?.throwIfAborted();\n await verifyInventory(root, handle, tree, signal);\n const after = await hashTree(\n root,\n handle,\n await inventory(handle, excludedPaths, signal),\n signal,\n );\n if (\n before.sha256 !== archived.sha256 ||\n after.sha256 !== archived.sha256 ||\n decoded.sha256 !== archived.sha256\n )\n changed();\n // Close before handing over ownership: a close failure after the transfer\n // would reject without giving the caller the spool it must dispose.\n handleClosed = true;\n await handle.close();\n const spool = ownedSpool(temporary, path, writer.byteSize, writer.hash.digest(\"hex\"));\n temporary = undefined;\n return { spool, workspace: archived };\n } catch (error) {\n return captureError(error);\n } finally {\n try {\n if (!handleClosed) await handle.close();\n } finally {\n if (temporary) await removeHostArchiveTemporaryDirectory(temporary);\n }\n }\n}\n\n/** Byte-oriented JSON lexer. Only metadata strings are accumulated. String\n * payloads are decoded in bounded runs, including JSON escapes and split UTF-8. */\nclass JsonReader {\n private readonly buffer: Buffer;\n private cursor = 0;\n private available = 0;\n private position = 0;\n constructor(\n private readonly handle: FileHandle,\n size: number,\n private readonly signal?: AbortSignal,\n ) {\n this.buffer = Buffer.allocUnsafe(size);\n }\n private async fill() {\n if (this.cursor < this.available) return true;\n // Re-reading a multi-gigabyte capture is not instantaneous: stop at the\n // next chunk like every other capture pass.\n this.signal?.throwIfAborted();\n const { bytesRead } = await this.handle.read(this.buffer, 0, this.buffer.length, this.position);\n this.position += bytesRead;\n this.cursor = 0;\n this.available = bytesRead;\n return bytesRead !== 0;\n }\n async peek(): Promise<number> {\n return (await this.fill()) ? this.buffer[this.cursor]! : -1;\n }\n async byte(): Promise<number> {\n const byte = await this.peek();\n if (byte === -1) invalid(\"truncated workspace archive JSON\");\n this.cursor++;\n return byte;\n }\n async whitespace() {\n while (true) {\n const byte = await this.peek();\n if (byte !== 32 && byte !== 9 && byte !== 10 && byte !== 13) return;\n this.cursor++;\n }\n }\n async expect(character: string) {\n await this.whitespace();\n if ((await this.byte()) !== character.charCodeAt(0))\n invalid(`expected ${character} in workspace archive JSON`);\n }\n async string(consume?: Base64Decoder): Promise<string> {\n await this.expect('\"');\n const parts: string[] = [];\n const decoder = consume\n ? undefined\n : new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true });\n const emit = async (text: string) => {\n if (!text) return;\n if (consume) await consume.write(text);\n else parts.push(text);\n };\n while (await this.fill()) {\n const start = this.cursor;\n while (this.cursor < this.available) {\n const byte = this.buffer[this.cursor]!;\n if (byte === 34 || byte === 92 || byte < 32) break;\n this.cursor++;\n }\n if (this.cursor > start) {\n const bytes = this.buffer.subarray(start, this.cursor);\n // Base64's alphabet is ASCII. Its decoder validates these bytes directly,\n // so payload runs never become UTF-8/base64 strings or fresh buffers.\n if (consume) await consume.write(bytes);\n else await emit(decoder!.decode(bytes, { stream: true }));\n }\n if (this.cursor === this.available) continue;\n if (decoder) await emit(decoder.decode());\n const special = await this.byte();\n if (special === 34) return parts.join(\"\");\n if (special !== 92) invalid(\"unescaped control character in workspace archive JSON\");\n const escape = String.fromCharCode(await this.byte());\n if (escape === \"u\") {\n let digits = \"\";\n for (let index = 0; index < 4; index++) digits += String.fromCharCode(await this.byte());\n if (!/^[0-9a-fA-F]{4}$/.test(digits)) invalid(\"invalid JSON Unicode escape\");\n await emit(String.fromCharCode(Number.parseInt(digits, 16)));\n } else {\n const escapes: Record<string, string> = {\n '\"': '\"',\n \"\\\\\": \"\\\\\",\n \"/\": \"/\",\n b: \"\\b\",\n f: \"\\f\",\n n: \"\\n\",\n r: \"\\r\",\n t: \"\\t\",\n };\n if (!Object.hasOwn(escapes, escape)) invalid(\"invalid JSON escape\");\n await emit(escapes[escape]!);\n }\n }\n invalid(\"unterminated workspace archive JSON string\");\n }\n async array(item: () => Promise<void>) {\n await this.expect(\"[\");\n await this.whitespace();\n if ((await this.peek()) === 93) {\n await this.byte();\n return;\n }\n while (true) {\n await item();\n await this.whitespace();\n const separator = await this.byte();\n if (separator === 93) return;\n if (separator !== 44) invalid(\"invalid workspace archive JSON array\");\n }\n }\n async object(field: (key: string) => Promise<void>) {\n await this.expect(\"{\");\n const keys = new Set<string>();\n await this.whitespace();\n if ((await this.peek()) === 125) {\n await this.byte();\n return keys;\n }\n while (true) {\n const key = await this.string();\n if (keys.has(key)) invalid(\"duplicate workspace archive JSON property\");\n keys.add(key);\n await this.expect(\":\");\n await field(key);\n await this.whitespace();\n const separator = await this.byte();\n if (separator === 125) return keys;\n if (separator !== 44) invalid(\"invalid workspace archive JSON object\");\n }\n }\n async version() {\n await this.whitespace();\n // Recognize the exact numeric value 1 without accumulating a potentially\n // archive-sized number token (1, 1.0, 0.1e1, 100e-2, etc.).\n let digits = 0;\n let integerDigits = 0;\n let significant = -1;\n let valid = true;\n const isDigit = (byte: number) => byte >= 48 && byte <= 57;\n const mantissaDigit = (byte: number) => {\n if (byte !== 48) {\n if (byte !== 49 || significant !== -1) valid = false;\n if (significant === -1) significant = digits;\n }\n digits++;\n };\n if ((await this.peek()) === 45) {\n valid = false;\n await this.byte();\n }\n const first = await this.byte();\n if (!isDigit(first)) invalid(\"invalid workspace archive version number\");\n mantissaDigit(first);\n integerDigits++;\n if (first !== 48) {\n while (isDigit(await this.peek())) {\n mantissaDigit(await this.byte());\n integerDigits++;\n }\n } else if (isDigit(await this.peek())) invalid(\"invalid leading zero in archive version\");\n if ((await this.peek()) === 46) {\n await this.byte();\n if (!isDigit(await this.peek())) invalid(\"invalid archive version fraction\");\n while (isDigit(await this.peek())) mantissaDigit(await this.byte());\n }\n let exponent = 0;\n let sign = 1;\n if ((await this.peek()) === 101 || (await this.peek()) === 69) {\n await this.byte();\n if ((await this.peek()) === 45 || (await this.peek()) === 43) {\n if ((await this.byte()) === 45) sign = -1;\n }\n if (!isDigit(await this.peek())) invalid(\"invalid archive version exponent\");\n while (isDigit(await this.peek())) {\n // Saturation is arithmetic only: every byte is still read/validated.\n exponent = Math.min(Number.MAX_SAFE_INTEGER, exponent * 10 + (await this.byte()) - 48);\n }\n }\n if (!valid || significant === -1 || integerDigits - significant - 1 + sign * exponent !== 0)\n invalid(\"unsupported workspace archive version\");\n }\n}\n\nclass Base64Decoder {\n private readonly output = Buffer.allocUnsafe(CHUNK_BYTES);\n private outputLength = 0;\n private bits = 0;\n private digits = 0;\n /** 1 requires the second '=', 2 forbids any further data. */\n private padding = 0;\n byteSize = 0;\n constructor(private readonly consume: (bytes: Buffer) => Promise<void>) {}\n private async flush() {\n if (!this.outputLength) return;\n await this.consume(this.output.subarray(0, this.outputLength));\n this.byteSize += this.outputLength;\n this.outputLength = 0;\n }\n async write(input: string | Uint8Array) {\n for (let index = 0; index < input.length; index++) {\n const code = typeof input === \"string\" ? input.charCodeAt(index) : input[index]!;\n if (this.padding === 2) invalid(\"data follows workspace archive base64 padding\");\n if (this.padding === 1) {\n if (code !== 61) invalid(\"missing workspace archive base64 padding\");\n this.padding = 2;\n continue;\n }\n // Any complete quartet emits at most three bytes. Await the sink before\n // reusing storage; there are no asynchronous operations per input byte.\n if (this.outputLength > this.output.length - 3) await this.flush();\n if (code === 61) {\n if (this.digits === 2) {\n if (this.bits & 15) invalid(\"noncanonical workspace archive base64 unused bits\");\n this.output[this.outputLength++] = this.bits >>> 4;\n this.padding = 1;\n } else if (this.digits === 3) {\n if (this.bits & 3) invalid(\"noncanonical workspace archive base64 unused bits\");\n this.output[this.outputLength++] = this.bits >>> 10;\n this.output[this.outputLength++] = (this.bits >>> 2) & 255;\n this.padding = 2;\n } else invalid(\"invalid workspace archive base64 padding\");\n this.digits = 0;\n continue;\n }\n const value =\n code >= 65 && code <= 90\n ? code - 65\n : code >= 97 && code <= 122\n ? code - 71\n : code >= 48 && code <= 57\n ? code + 4\n : code === 43\n ? 62\n : code === 47\n ? 63\n : -1;\n if (value < 0) invalid(\"invalid workspace archive base64 alphabet\");\n this.bits = (this.bits << 6) | value;\n if (++this.digits === 4) {\n this.output[this.outputLength++] = this.bits >>> 16;\n this.output[this.outputLength++] = (this.bits >>> 8) & 255;\n this.output[this.outputLength++] = this.bits & 255;\n this.bits = 0;\n this.digits = 0;\n }\n }\n }\n async finish() {\n if (this.digits || this.padding === 1) invalid(\"truncated workspace archive base64\");\n await this.flush();\n }\n}\n\ntype FileSpan = { path: string; offset: number; byteSize: number };\ntype ArchiveIndex = { directories: string[]; files: FileSpan[] };\n\nasync function fingerprintArchiveIndex(\n index: ArchiveIndex,\n payload: FileHandle,\n signal?: AbortSignal,\n) {\n const hash = projection(index.directories);\n let total = 0;\n const buffer = Buffer.allocUnsafe(CHUNK_BYTES);\n for (const file of [...index.files].sort((a, b) => compare(a.path, b.path))) {\n signal?.throwIfAborted();\n frame(hash, \"file\", file.path);\n frame(hash, \"bytes\", String(file.byteSize));\n let copied = 0;\n while (copied < file.byteSize) {\n const { bytesRead } = await payload.read(\n buffer,\n 0,\n Math.min(buffer.length, file.byteSize - copied),\n file.offset + copied,\n );\n if (!bytesRead) invalid(\"validated workspace payload was truncated\");\n hash.update(buffer.subarray(0, bytesRead));\n copied += bytesRead;\n }\n total += file.byteSize;\n }\n return fingerprint(hash, index.directories.length, index.files.length, total);\n}\n\nfunction validatePath(path: string) {\n if (\n !path ||\n path.includes(\"\\0\") ||\n Buffer.from(path).toString(\"utf8\") !== path ||\n path\n .split(\"/\")\n .some(\n (part) =>\n !part ||\n part === \".\" ||\n part === \"..\" ||\n Buffer.byteLength(part, \"utf8\") > HOST_FILENAME_BYTES,\n )\n )\n invalid(\"unsafe workspace archive path\");\n}\n\nasync function indexArchive(\n input: FileHandle,\n payload: FileHandle,\n options: HostWorkspaceArchiveOptions,\n signal?: AbortSignal,\n): Promise<ArchiveIndex> {\n const reader = new JsonReader(input, chunkSize(options), signal);\n const limits = limitsFor(options);\n const directories: string[] = [];\n const files: FileSpan[] = [];\n let extracted = 0;\n let members = 0;\n const member = () => {\n checkLimit(++members, limits?.maxMembers, \"member count\");\n };\n const keys = await reader.object(async (key) => {\n if (key === \"version\") return await reader.version();\n if (key === \"directories\") {\n return await reader.array(async () => {\n const path = await reader.string();\n validatePath(path);\n directories.push(path);\n member();\n });\n }\n if (key === \"files\") {\n return await reader.array(async () => {\n let path: string | undefined;\n const offset = extracted;\n const decoder = new Base64Decoder(async (bytes) => {\n extracted += bytes.length;\n checkLimit(extracted, limits?.maxExtractedBytes, \"extracted size\");\n await writeAll(payload, bytes);\n });\n const fields = await reader.object(async (field) => {\n if (field === \"path\") {\n path = await reader.string();\n validatePath(path);\n } else if (field === \"data\") {\n await reader.string(decoder);\n await decoder.finish();\n } else invalid(\"unknown workspace archive file property\");\n });\n if (path === undefined || !fields.has(\"data\"))\n invalid(\"workspace archive file is missing path or data\");\n files.push({ path, offset, byteSize: decoder.byteSize });\n member();\n });\n }\n invalid(\"unknown workspace archive property\");\n });\n if (!keys.has(\"version\") || !keys.has(\"directories\") || !keys.has(\"files\"))\n invalid(\"workspace archive is missing required properties\");\n await reader.whitespace();\n if ((await reader.peek()) !== -1) invalid(\"trailing data in workspace archive JSON\");\n const paths = new Map<string, \"file\" | \"directory\">();\n for (const [path, kind] of [\n ...directories.map((directory) => [directory, \"directory\"] as const),\n ...files.map((file) => [file.path, \"file\"] as const),\n ]) {\n if (paths.has(path)) invalid(\"duplicate workspace archive path\");\n paths.set(path, kind);\n }\n for (const path of paths.keys()) {\n let parent = parentAndName(path)[0];\n while (parent) {\n if (paths.get(parent) === \"file\") invalid(\"workspace archive file is also an ancestor\");\n parent = parentAndName(parent)[0];\n }\n }\n return { directories, files };\n}\n\n/** Removes directory entries through pinned parents. unlink never follows a\n * symlink; rmdir never follows a replacement symlink. No recursive rm uses an\n * attacker-controlled pathname. */\nasync function clearDirectory(handle: FileHandle) {\n for (const name of await readdir(fdPath(handle))) {\n const path = fdPath(handle, name);\n const stats = await lstat(path, { bigint: true });\n if (stats.isDirectory()) {\n const child = await open(path, READ_DIRECTORY);\n try {\n if (!sameEntry(stats, await child.stat({ bigint: true })))\n invalid(\"restore destination directory changed\");\n await clearDirectory(child);\n if (!sameEntry(stats, await lstat(path, { bigint: true })))\n invalid(\"restore destination directory changed\");\n await rmdir(path);\n } finally {\n await child.close();\n }\n } else {\n await unlink(path);\n }\n }\n}\n\nasync function copySpan(payload: FileHandle, output: FileHandle, span: FileSpan) {\n const buffer = Buffer.allocUnsafe(CHUNK_BYTES);\n let copied = 0;\n while (copied < span.byteSize) {\n const { bytesRead } = await payload.read(\n buffer,\n 0,\n Math.min(buffer.length, span.byteSize - copied),\n span.offset + copied,\n );\n if (!bytesRead) invalid(\"validated workspace payload was truncated\");\n await writeAll(output, buffer.subarray(0, bytesRead));\n copied += bytesRead;\n }\n}\n\n/** Copies the untrusted spool once into a private temporary directory outside\n * `avoidRoot`, verifies its exact size and SHA-256, indexes it, and hands the\n * validated index and decoded payload to `use`. */\nasync function withValidatedHostArchive<T>(\n avoidRoot: string | null,\n spool: WorkspaceArchiveSpool,\n options: HostWorkspaceArchiveOptions,\n use: (archive: ArchiveIndex, payload: FileHandle) => Promise<T>,\n): Promise<T> {\n // A provider callback can mutate the caller's spool/options objects. The\n // selected expectation must remain the one supplied before any asynchronous\n // work, not a replacement advertised while bytes are being produced.\n const { byteSize: expectedByteSize, sha256: expectedSha256 } = spool;\n const readChunks = spool.open.bind(spool);\n const processingChunkBytes = chunkSize(options);\n const limits = limitsFor(options);\n checkLimit(expectedByteSize, limits?.maxInputBytes, \"input size\");\n if (expectedByteSize < 0 || !/^[0-9a-f]{64}$/.test(expectedSha256))\n invalid(\"invalid workspace archive spool metadata\");\n const temporary = await privateTemporaryDirectory(avoidRoot);\n const handles: FileHandle[] = [];\n try {\n const input = await open(\n join(temporary, \"input.json\"),\n constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,\n 0o600,\n );\n handles.push(input);\n const writer = new ArchiveWriter(input);\n // Read the untrusted source exactly once. All later work uses this private\n // copy, so a changing/reopenable provider cannot switch bytes after validation.\n for await (const bytes of readChunks()) {\n if (!(bytes instanceof Uint8Array)) invalid(\"invalid workspace archive stream chunk\");\n checkLimit(writer.byteSize + bytes.length, limits?.maxInputBytes, \"input size\");\n if (writer.byteSize + bytes.length > expectedByteSize)\n invalid(\"workspace archive size mismatch\");\n await writer.write(bytes);\n }\n if (writer.byteSize !== expectedByteSize || writer.hash.digest(\"hex\") !== expectedSha256)\n invalid(\"workspace archive SHA-256/size mismatch\");\n const payload = await open(\n join(temporary, \"payload\"),\n constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,\n 0o600,\n );\n handles.push(payload);\n const archive = await indexArchive(input, payload, {\n chunkBytes: processingChunkBytes,\n archiveLimits: limits,\n });\n return await use(archive, payload);\n } finally {\n try {\n await Promise.all(handles.map((handle) => handle.close()));\n } finally {\n await removeHostArchiveTemporaryDirectory(temporary);\n }\n }\n}\n\nexport async function restoreHostWorkspaceArchive(\n root: string,\n spool: WorkspaceArchiveSpool,\n options: HostWorkspaceArchiveOptions = {},\n): Promise<void> {\n await withValidatedHostArchive(root, spool, options, async (archive, payload) => {\n const handles: FileHandle[] = [];\n try {\n await restoreValidatedArchive(root, archive, payload, handles);\n } finally {\n await Promise.all(handles.map((handle) => handle.close()));\n }\n });\n}\n\nasync function restoreValidatedArchive(\n root: string,\n archive: ArchiveIndex,\n payload: FileHandle,\n handles: FileHandle[],\n): Promise<void> {\n // Nothing before this creates, clears or truncates anything under root.\n const destination = await openRoot(root, true);\n handles.push(destination);\n const destinationIdentity = await destination.stat({ bigint: true });\n await clearDirectory(destination);\n for (const path of archive.directories) {\n const directory = await openDirectory(destination, path, undefined, true);\n await directory.close();\n }\n for (const span of archive.files) {\n const [parent, name] = parentAndName(span.path);\n const directory = await openDirectory(destination, parent, undefined, true);\n try {\n const output = await open(fdPath(directory, name), CREATE, 0o666);\n try {\n const identity = await output.stat({ bigint: true });\n await copySpan(payload, output, span);\n const freshParent = await openDirectory(destination, parent);\n try {\n if (\n !sameEntry(\n await directory.stat({ bigint: true }),\n await freshParent.stat({ bigint: true }),\n ) ||\n !sameEntry(identity, await lstat(fdPath(freshParent, name), { bigint: true }))\n )\n invalid(\"restore destination file changed\");\n } finally {\n await freshParent.close();\n }\n } finally {\n await output.close();\n }\n } finally {\n await directory.close();\n }\n }\n const fresh = await openRoot(root);\n try {\n if (!sameEntry(destinationIdentity, await fresh.stat({ bigint: true })))\n invalid(\"restore destination root changed\");\n } finally {\n await fresh.close();\n }\n}\n\nconst TAR_BLOCK = 512;\n// Largest size a ustar header's 11 octal digits can carry. Portable sandbox\n// tar validators refuse a PAX size override, so a larger member is unportable.\nconst TAR_MAX_MEMBER_BYTES = 0o77777777777;\nconst TAR_DIRECTORY_MODE = 0o755;\nconst TAR_FILE_MODE = 0o644;\n\nfunction tarOctal(header: Buffer, offset: number, width: number, value: number) {\n header.write(`${value.toString(8).padStart(width - 1, \"0\")}\\0`, offset, width, \"ascii\");\n}\n\nfunction tarHeader(name: string, type: \"0\" | \"5\" | \"x\", size: number, mode: number, mtime: number) {\n const header = Buffer.alloc(TAR_BLOCK);\n header.write(name, 0, 100, \"utf8\");\n tarOctal(header, 100, 8, mode);\n tarOctal(header, 108, 8, 0);\n tarOctal(header, 116, 8, 0);\n tarOctal(header, 124, 12, size);\n tarOctal(header, 136, 12, mtime);\n header.fill(0x20, 148, 156);\n header.write(type, 156, 1, \"ascii\");\n header.write(\"ustar\\0\", 257, 6, \"ascii\");\n header.write(\"00\", 263, 2, \"ascii\");\n let checksum = 0;\n for (const byte of header) checksum += byte;\n header.write(`${checksum.toString(8).padStart(6, \"0\")}\\0 `, 148, 8, \"ascii\");\n return header;\n}\n\nfunction paxRecord(key: string, value: string): Buffer {\n const body = ` ${key}=${value}\\n`;\n const bodyBytes = Buffer.byteLength(body);\n // The decimal length prefix counts its own digits.\n let length = bodyBytes + String(bodyBytes).length;\n while (bodyBytes + String(length).length !== length) length = bodyBytes + String(length).length;\n return Buffer.from(`${length}${body}`);\n}\n\nfunction padded(bytes: number) {\n return Math.ceil(bytes / TAR_BLOCK) * TAR_BLOCK;\n}\n\n/** Header blocks for one member; a name that does not fit ustar's 100 bytes\n * travels in a PAX `path` record, which sandbox tar validators accept. */\nfunction tarMemberHeader(name: string, type: \"0\" | \"5\", size: number, mtime: number): Buffer {\n const mode = type === \"5\" ? TAR_DIRECTORY_MODE : TAR_FILE_MODE;\n if (Buffer.byteLength(name) <= 100) return tarHeader(name, type, size, mode, mtime);\n const record = paxRecord(\"path\", name);\n const pax = Buffer.alloc(TAR_BLOCK + padded(record.length));\n tarHeader(\"././@PaxHeader\", \"x\", record.length, 0o644, mtime).copy(pax, 0);\n record.copy(pax, TAR_BLOCK);\n return Buffer.concat([pax, tarHeader(\"././@LongName\", type, size, mode, mtime)]);\n}\n\nfunction excludedBy(path: string, excluded: readonly string[]) {\n return excluded.some((prefix) => path === prefix || path.startsWith(`${prefix}/`));\n}\n\nexport type PortableWorkspaceTar = {\n /** A plain ustar/PAX archive of the workspace: directories and regular files. */\n bytes: Uint8Array;\n /** The archive's own `sdk_local_archive_v1` fingerprint over every member,\n * comparable with the descriptor captured alongside it. */\n fingerprint: WorkspaceTreeFingerprint;\n /** Exactly what extracting `bytes` materializes, for verifying the result. */\n contents: WorkspaceContentManifest;\n};\n\n/**\n * Converts a host-backed workspace archive (the portable JSON projection that\n * Local/Docker sandboxes capture) into a tar any remote sandbox can hydrate.\n * The spool is validated exactly like a host restore. `excludedPaths` are the\n * destination's ephemeral paths: they are not persisted there, so they are left\n * out of the tar and of `contents`.\n */\nexport async function convertHostWorkspaceArchiveToTar(\n spool: WorkspaceArchiveSpool,\n options: HostWorkspaceArchiveOptions & {\n excludedPaths?: readonly string[];\n mtimeSeconds?: number;\n } = {},\n): Promise<PortableWorkspaceTar> {\n const excluded = (options.excludedPaths ?? [])\n .map((path) => path.replace(/^(\\.\\/)+/, \"\").replace(/\\/+$/, \"\"))\n .filter((path) => path.length > 0);\n const mtime =\n options.mtimeSeconds !== undefined && Number.isFinite(options.mtimeSeconds)\n ? Math.max(0, Math.floor(options.mtimeSeconds))\n : 0;\n return await withValidatedHostArchive(null, spool, options, async (archive, payload) => {\n const archiveFingerprint = await fingerprintArchiveIndex(archive, payload);\n // Every ancestor is a directory of the restored tree, listed or not.\n const listed = new Set(archive.directories);\n const directories = new Set<string>();\n for (const path of [...archive.directories, ...archive.files.map((file) => file.path)]) {\n let parent = listed.has(path) ? path : parentAndName(path)[0];\n while (parent) {\n if (!excludedBy(parent, excluded)) directories.add(parent);\n parent = parentAndName(parent)[0];\n }\n }\n const files = archive.files.filter((file) => !excludedBy(file.path, excluded));\n const orderedDirectories = [...directories].sort((left, right) =>\n Buffer.compare(Buffer.from(left), Buffer.from(right)),\n );\n const headers = new Map<string, Buffer>();\n let total = 2 * TAR_BLOCK;\n for (const directory of orderedDirectories) {\n const header = tarMemberHeader(`${directory}/`, \"5\", 0, mtime);\n headers.set(`d:${directory}`, header);\n total += header.length;\n }\n for (const file of files) {\n if (file.byteSize > TAR_MAX_MEMBER_BYTES)\n invalid(\"workspace archive file is too large for a portable tar\");\n const header = tarMemberHeader(file.path, \"0\", file.byteSize, mtime);\n headers.set(`f:${file.path}`, header);\n total += header.length + padded(file.byteSize);\n }\n checkLimit(total, Number.MAX_SAFE_INTEGER, \"portable tar size\");\n const tar = Buffer.alloc(total);\n const entries: WorkspaceContentEntry[] = [];\n let offset = 0;\n for (const directory of orderedDirectories) {\n offset += headers.get(`d:${directory}`)!.copy(tar, offset);\n entries.push({ kind: \"directory\", path: directory });\n }\n for (const file of files) {\n offset += headers.get(`f:${file.path}`)!.copy(tar, offset);\n const hash = createHash(\"sha256\");\n let copied = 0;\n while (copied < file.byteSize) {\n const { bytesRead } = await payload.read(\n tar,\n offset + copied,\n Math.min(CHUNK_BYTES, file.byteSize - copied),\n file.offset + copied,\n );\n if (!bytesRead) invalid(\"validated workspace payload was truncated\");\n hash.update(tar.subarray(offset + copied, offset + copied + bytesRead));\n copied += bytesRead;\n }\n offset += padded(file.byteSize);\n entries.push({\n kind: \"file\",\n path: file.path,\n sha256: hash.digest(\"hex\"),\n byteSize: file.byteSize,\n });\n }\n return {\n bytes: new Uint8Array(tar.buffer, tar.byteOffset, tar.byteLength),\n fingerprint: archiveFingerprint,\n contents: workspaceContentManifest(entries),\n };\n });\n}\n","import { createHash } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport { lstat, open, readdir } from \"node:fs/promises\";\nimport { isAbsolute, join } from \"node:path\";\nimport {\n WORKSPACE_ARCHIVE_DESCRIPTOR_VERSION,\n decodeNativeSnapshotRef,\n parseWorkspaceArchiveDescriptor,\n parseWorkspaceArchiveObjectRef,\n type NativeSnapshotDescriptor,\n type NativeSnapshotRef,\n type TarWorkspaceArchiveDescriptor,\n type WorkspaceArchiveDescriptor,\n type WorkspaceTreeFingerprint,\n} from \"@opengeni/contracts\";\nimport { withSandboxProviderCapture } from \"./provider-operation-gate\";\nimport type { VerifiedHostWorkspaceArchive } from \"./archive-spool\";\nimport {\n captureHostWorkspaceArchive,\n fingerprintHostWorkspace,\n type HostWorkspaceRootIdentity,\n} from \"./host-archive-spool\";\n\nexport {\n WORKSPACE_ARCHIVE_DESCRIPTOR_VERSION,\n decodeNativeSnapshotRef,\n encodeNativeSnapshotRef,\n parseWorkspaceArchiveDescriptor,\n type NativeSnapshotDescriptor,\n type NativeSnapshotProvider,\n type NativeSnapshotRef,\n type TarWorkspaceArchiveDescriptor,\n type WorkspaceArchiveDescriptor,\n type WorkspaceTreeFingerprint,\n} from \"@opengeni/contracts\";\n\nexport type VerifiedWorkspaceArchive = {\n bytes: Uint8Array;\n base64: string;\n descriptor: WorkspaceArchiveDescriptor;\n kind: \"tar\" | \"provider_snapshot\";\n nativeSnapshot?: NativeSnapshotRef;\n};\n\nexport type VerifiedWorkspaceArchivePayload =\n | VerifiedWorkspaceArchive\n | VerifiedHostWorkspaceArchive;\n\n/** Host-backed portable archives can go directly to object storage without an\n * intermediate whole-document string or buffer. Existing inline/provider APIs\n * retain their compatibility path when disk-backed publication is unavailable. */\nexport async function captureWorkspaceArchiveForStorage(\n session: unknown,\n capturedAtMs: number,\n options: WorkspaceArchiveCaptureOptions,\n objectStorageAvailable: boolean,\n): Promise<VerifiedWorkspaceArchivePayload> {\n const target = session as WorkspaceSession;\n await target.assertWorkspaceCaptureAuthority?.();\n const root = hostBackedWorkspaceRoot(target);\n if (\n process.platform !== \"linux\" ||\n !root ||\n !objectStorageAvailable ||\n options.strategy === \"portable_tar\"\n ) {\n return await captureVerifiedWorkspaceArchive(session, capturedAtMs, options);\n }\n return await withSandboxProviderCapture(\n session,\n async () => {\n const { spool, workspace } = await captureHostWorkspaceArchive(\n root,\n workspaceFingerprintExcludes(target),\n target.workspaceCaptureRootIdentity,\n options.signal,\n );\n return {\n kind: \"host_spool\" as const,\n spool,\n descriptor: {\n version: 1 as const,\n revision: `wa1:${String(capturedAtMs).padStart(13, \"0\")}:${spool.sha256}`,\n archiveSha256: spool.sha256,\n archiveBytes: spool.byteSize,\n capturedAt: new Date(capturedAtMs).toISOString(),\n workspace,\n },\n };\n },\n options.signal,\n );\n}\n\nexport async function disposeWorkspaceArchive(\n archive: VerifiedWorkspaceArchivePayload | undefined,\n): Promise<void> {\n if (archive?.kind === \"host_spool\") await archive.spool.dispose();\n}\n\nexport type WorkspaceArchiveIntegrityCode =\n | \"archive_metadata_missing\"\n | \"archive_metadata_invalid\"\n | \"archive_base64_invalid\"\n | \"archive_hash_mismatch\"\n | \"archive_hydration_failed\"\n /** The referenced archive object does not exist (deleted, wrong bucket or\n * account). Never proof that the checkpoint content is corrupt. */\n | \"archive_object_missing\"\n /** This process has no archive object storage configured. */\n | \"archive_storage_unavailable\"\n | \"workspace_fingerprint_unavailable\"\n | \"workspace_changed_during_capture\"\n | \"workspace_fingerprint_mismatch\"\n | \"native_snapshot_reference_invalid\"\n | \"native_snapshot_fallback_unverified\";\n\nexport class WorkspaceArchiveIntegrityError extends Error {\n readonly name = \"WorkspaceArchiveIntegrityError\";\n readonly retryable: boolean;\n\n constructor(\n public readonly code: WorkspaceArchiveIntegrityCode,\n message: string,\n options: { retryable?: boolean; cause?: unknown } = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.retryable = options.retryable ?? false;\n }\n}\n\ntype WorkspaceSession = {\n /** Present only on the reaper's restricted Docker capture attachment. */\n assertWorkspaceCaptureAuthority?: () => Promise<void>;\n workspaceCaptureRootIdentity?: HostWorkspaceRootIdentity;\n exec?: (args: {\n cmd: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<unknown>;\n execCommand?: (args: {\n cmd: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<unknown>;\n persistWorkspace?: (options?: WorkspaceArchiveCaptureOptions) => Promise<Uint8Array | undefined>;\n /** Agents Extensions remote sessions expose this protected-at-type-level\n * primitive on the concrete JS instance. Opengeni uses it only through an\n * explicit provider policy to bypass replacing/unledgered native capture. */\n persistWorkspaceTar?: () => Promise<Uint8Array | undefined>;\n state?: {\n workspacePersistence?: unknown;\n workspaceRootPath?: unknown;\n manifest?: {\n root?: unknown;\n ephemeralPersistencePaths?: () => Set<unknown>;\n };\n };\n};\n\ntype SdkLocalArchiveFile = { path: string; content: Uint8Array };\n\n/**\n * Durable correlation identity for one logical provider capture. A provider\n * adapter may place it on its wire request, but callers must not infer replay\n * idempotency unless that provider contract explicitly guarantees it.\n */\nexport type WorkspaceArchiveCaptureOptions = {\n requestId: string;\n strategy?: \"configured\" | \"portable_tar\";\n /**\n * Abandons the capture while it still waits for the provider operation gate,\n * and stops a host-backed spool capture mid-read. A provider-native persist\n * call that already started is not interrupted: its own settlement remains\n * authoritative.\n */\n signal?: AbortSignal;\n};\n\nfunction sha256(bytes: Uint8Array): string {\n return createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n\nfunction decodeBase64Strict(value: string): Uint8Array | null {\n if (value.length === 0 || value.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) {\n return null;\n }\n const bytes = Uint8Array.from(Buffer.from(value, \"base64\"));\n return Buffer.from(bytes).toString(\"base64\") === value ? bytes : null;\n}\n\nexport function describeNativeSnapshotArchive(\n bytes: Uint8Array,\n capturedAtMs = Date.now(),\n): NativeSnapshotDescriptor | null {\n const native = decodeNativeSnapshotRef(bytes);\n if (!native) return null;\n const archiveSha256 = sha256(bytes);\n return {\n version: WORKSPACE_ARCHIVE_DESCRIPTOR_VERSION,\n kind: \"provider_snapshot\",\n revision: `wa2:${String(capturedAtMs).padStart(13, \"0\")}:${archiveSha256}`,\n archiveSha256,\n archiveBytes: bytes.length,\n capturedAt: new Date(capturedAtMs).toISOString(),\n provider: native.provider,\n snapshotId: native.snapshotId,\n ...(native.workspacePersistence ? { workspacePersistence: native.workspacePersistence } : {}),\n };\n}\n\nexport function describeLegacyNativeSnapshotArchive(\n base64: unknown,\n observedAtMs = Date.now(),\n): { archiveBase64: string; descriptor: NativeSnapshotDescriptor } | null {\n if (typeof base64 !== \"string\") return null;\n const bytes = decodeBase64Strict(base64);\n if (!bytes) return null;\n const descriptor = describeNativeSnapshotArchive(bytes, observedAtMs);\n return descriptor ? { archiveBase64: base64, descriptor } : null;\n}\n\nexport function readVerifiedWorkspaceArchive(\n base64: unknown,\n metadata: unknown,\n): VerifiedWorkspaceArchive | null {\n if (base64 === undefined || base64 === null || base64 === \"\") return null;\n if (typeof base64 !== \"string\") {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_base64_invalid\",\n \"selected workspace archive is not a base64 string\",\n );\n }\n if (metadata === undefined || metadata === null) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_metadata_missing\",\n \"selected workspace archive has no durable revision/fingerprint metadata\",\n );\n }\n const descriptor = parseWorkspaceArchiveDescriptor(metadata);\n if (!descriptor) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_metadata_invalid\",\n \"selected workspace archive metadata is invalid\",\n );\n }\n const bytes = decodeBase64Strict(base64);\n if (!bytes) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_base64_invalid\",\n `workspace archive revision ${descriptor.revision} has invalid base64 bytes`,\n );\n }\n const actualHash = sha256(bytes);\n if (bytes.length !== descriptor.archiveBytes || actualHash !== descriptor.archiveSha256) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_hash_mismatch\",\n `workspace archive revision ${descriptor.revision} failed SHA-256/size verification`,\n );\n }\n const nativeSnapshot = decodeNativeSnapshotRef(bytes);\n if (descriptor.version === WORKSPACE_ARCHIVE_DESCRIPTOR_VERSION) {\n if (\n !nativeSnapshot ||\n nativeSnapshot.provider !== descriptor.provider ||\n nativeSnapshot.snapshotId !== descriptor.snapshotId ||\n nativeSnapshot.workspacePersistence !== descriptor.workspacePersistence\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n `native snapshot receipt does not match descriptor revision ${descriptor.revision}`,\n );\n }\n } else if (nativeSnapshot) {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_reference_invalid\",\n `legacy native snapshot receipt ${descriptor.revision} was not durably upgraded to a v2 provider descriptor`,\n );\n }\n return {\n bytes,\n base64,\n descriptor,\n kind: descriptor.version === WORKSPACE_ARCHIVE_DESCRIPTOR_VERSION ? \"provider_snapshot\" : \"tar\",\n ...(descriptor.version === WORKSPACE_ARCHIVE_DESCRIPTOR_VERSION && nativeSnapshot\n ? { nativeSnapshot }\n : {}),\n };\n}\n\n/** Fetch object-storage tar bytes into the in-memory restore envelope. Legacy\n * inline base64 is left unchanged. Both payloads must agree when both exist. */\nexport async function inlineWorkspaceArchiveForRestore(\n sessionState: Record<string, unknown>,\n getObjectBytes: (key: string) => Promise<{ bytes: Uint8Array } | null>,\n): Promise<Record<string, unknown>> {\n const ref = parseWorkspaceArchiveObjectRef(sessionState.workspaceArchiveRef);\n if (!ref) return sessionState;\n const object = await getObjectBytes(ref.key);\n if (!object) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_object_missing\",\n `workspace archive object ${ref.key} is missing`,\n );\n }\n const actualHash = sha256(object.bytes);\n if (object.bytes.length !== ref.bytes || actualHash !== ref.sha256) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_hash_mismatch\",\n `workspace archive object ${ref.key} failed SHA-256/size verification`,\n );\n }\n const base64 = Buffer.from(object.bytes).toString(\"base64\");\n const inline = sessionState.workspaceArchive;\n if (typeof inline === \"string\" && inline.length > 0 && inline !== base64) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_hash_mismatch\",\n \"inline workspace archive and object-storage ref disagree\",\n );\n }\n readVerifiedWorkspaceArchive(base64, sessionState.workspaceArchiveMeta);\n return { ...sessionState, workspaceArchive: base64 };\n}\n\nfunction stdoutFromExecResult(value: unknown): string {\n if (typeof value === \"string\") {\n const delimiter = /\\r?\\nOutput:\\r?\\n/u.exec(value);\n return delimiter ? value.slice(delimiter.index + delimiter[0].length) : value;\n }\n if (!value || typeof value !== \"object\") return \"\";\n const output = value as { stdout?: unknown; output?: unknown };\n return typeof output.stdout === \"string\"\n ? output.stdout\n : typeof output.output === \"string\"\n ? output.output\n : \"\";\n}\n\nfunction execFailureDiagnostic(value: unknown): string {\n if (!value || typeof value !== \"object\") return \"result=unstructured\";\n const result = value as {\n exitCode?: unknown;\n status?: unknown;\n stderr?: unknown;\n };\n const status =\n typeof result.exitCode === \"number\"\n ? `exitCode=${result.exitCode}`\n : typeof result.status === \"number\"\n ? `status=${result.status}`\n : \"exitCode=unknown\";\n const stderr =\n typeof result.stderr === \"string\"\n ? result.stderr.replace(/\\s+/g, \" \").trim().slice(0, 240)\n : \"\";\n return stderr.length > 0 ? `${status}, stderr=${stderr}` : status;\n}\n\nfunction isTransientRootDirectoryFingerprintRace(value: unknown): boolean {\n if (!value || typeof value !== \"object\") return false;\n const result = value as {\n exitCode?: unknown;\n status?: unknown;\n stderr?: unknown;\n };\n const exitCode =\n typeof result.exitCode === \"number\"\n ? result.exitCode\n : typeof result.status === \"number\"\n ? result.status\n : null;\n if (exitCode !== 1 || typeof result.stderr !== \"string\") return false;\n return result.stderr\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .some((line) => line === \"tar: .: file changed as we read it\");\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n\nfunction workspaceFingerprintExcludes(session: WorkspaceSession): string[] {\n return [...(session.state?.manifest?.ephemeralPersistencePaths?.() ?? [])]\n .filter((path): path is string => typeof path === \"string\" && path.length > 0)\n .sort((left, right) => left.localeCompare(right));\n}\n\n/** Workspace-relative paths a session never persists (its manifest's\n * ephemeral paths). Archives and fingerprints leave them out. */\nexport function workspaceArchiveExcludedPaths(session: unknown): string[] {\n return workspaceFingerprintExcludes(session as WorkspaceSession);\n}\n\nfunction findPruneExpression(excludedPaths: readonly string[]): string {\n const findExcludes = excludedPaths.flatMap((path) => [\n `-path ${shellQuote(`./${path}`)}`,\n `-path ${shellQuote(`./${path}/*`)}`,\n ]);\n return findExcludes.length === 0 ? \"\" : `\\\\( ${findExcludes.join(\" -o \")} \\\\) -prune -o `;\n}\n\nfunction workspaceFingerprintCommand(excludedPaths: readonly string[]): string {\n const tarExcludes = excludedPaths.flatMap((path) => [\n shellQuote(`--exclude=${path}`),\n shellQuote(`--exclude=./${path}`),\n ]);\n const findPrefix = findPruneExpression(excludedPaths);\n const script = String.raw`set -eu\ncd /workspace\ndigest=$(LC_ALL=C tar ${tarExcludes.join(\" \")} --sort=name --mtime=\"@0\" --owner=0 --group=0 --numeric-owner --hard-dereference --format=gnu -cf - . | sha256sum | awk \"{print \\$1}\")\nentries=$(find . -xdev -mindepth 1 ${findPrefix}! \\( -type s -o -type p -o -type b -o -type c \\) -printf x | wc -c | tr -d \" \")\nfiles=$(find . -xdev ${findPrefix}-type f -printf x | wc -c | tr -d \" \")\nbytes=$(find . -xdev ${findPrefix}-type f -printf \"%s\\n\" | awk \"{s+=\\$1} END {printf \\\"%.0f\\\", s+0}\")\nprintf \"OPENGENI_WORKSPACE_FINGERPRINT_V1 %s %s %s %s\\n\" \"$digest\" \"$entries\" \"$files\" \"$bytes\"`;\n return `bash -o pipefail -c ${shellQuote(script)}`;\n}\n\nconst SDK_LOCAL_ARCHIVE_PROJECTION = \"sdk_local_archive_v1\" as const;\nconst HOST_FINGERPRINT_READ_FLAGS = constants.O_RDONLY | constants.O_NOFOLLOW;\n\nfunction hostBackedWorkspaceRoot(session: WorkspaceSession): string | null {\n const root = session.state?.workspaceRootPath;\n return typeof root === \"string\" && isAbsolute(root) ? root : null;\n}\n\nfunction appendFingerprintFrame(\n hash: ReturnType<typeof createHash>,\n label: string,\n value: string,\n): void {\n hash.update(label);\n hash.update(\"\\0\");\n hash.update(String(Buffer.byteLength(value)));\n hash.update(\"\\0\");\n hash.update(value);\n hash.update(\"\\0\");\n}\n\nfunction stableLogicalPathCompare(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction fingerprintSdkLocalProjection(\n directoryInput: readonly string[],\n fileInput: readonly SdkLocalArchiveFile[],\n): WorkspaceTreeFingerprint {\n const directories = [...directoryInput].sort(stableLogicalPathCompare);\n const files = [...fileInput].sort((left, right) =>\n stableLogicalPathCompare(left.path, right.path),\n );\n const paths = new Set<string>();\n const hash = createHash(\"sha256\");\n appendFingerprintFrame(hash, \"projection\", SDK_LOCAL_ARCHIVE_PROJECTION);\n for (const directory of directories) {\n if (paths.has(directory)) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n \"host-backed sandbox archive contains a duplicate logical path\",\n { retryable: true },\n );\n }\n paths.add(directory);\n appendFingerprintFrame(hash, \"dir\", directory);\n }\n let totalFileBytes = 0;\n for (const file of files) {\n if (paths.has(file.path)) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n \"host-backed sandbox archive contains a duplicate logical path\",\n { retryable: true },\n );\n }\n paths.add(file.path);\n totalFileBytes += file.content.byteLength;\n if (!Number.isSafeInteger(totalFileBytes)) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n \"host-backed sandbox workspace exceeds the supported fingerprint byte range\",\n );\n }\n appendFingerprintFrame(hash, \"file\", file.path);\n appendFingerprintFrame(hash, \"bytes\", String(file.content.byteLength));\n hash.update(file.content);\n }\n return {\n algorithm: \"sha256\",\n sha256: hash.digest(\"hex\"),\n entryCount: directories.length + files.length,\n fileCount: files.length,\n totalFileBytes,\n projection: SDK_LOCAL_ARCHIVE_PROJECTION,\n };\n}\n\nfunction sdkArchivePath(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length > 0 &&\n !value.startsWith(\"/\") &&\n !value.includes(\"\\0\") &&\n value.split(\"/\").every((segment) => segment.length > 0 && segment !== \".\" && segment !== \"..\")\n );\n}\n\nfunction decodeSdkArchiveFile(value: unknown): Uint8Array | null {\n if (value === \"\") return new Uint8Array();\n return typeof value === \"string\" ? decodeBase64Strict(value) : null;\n}\n\n/** Parse only the portable JSON shape emitted by Agents SDK Local/Docker\n * persistWorkspace(). This lets capture prove that the bytes themselves—not\n * merely two live-directory observations—contain the exact fenced projection. */\nfunction fingerprintSdkLocalArchive(bytes: Uint8Array): WorkspaceTreeFingerprint {\n let decoded: unknown;\n try {\n decoded = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes));\n } catch {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n \"host-backed sandbox persistence returned an invalid SDK archive\",\n { retryable: true },\n );\n }\n if (!decoded || typeof decoded !== \"object\" || Array.isArray(decoded)) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n \"host-backed sandbox persistence returned an invalid SDK archive\",\n { retryable: true },\n );\n }\n const archive = decoded as {\n version?: unknown;\n directories?: unknown;\n files?: unknown;\n };\n if (\n archive.version !== 1 ||\n !Array.isArray(archive.directories) ||\n !archive.directories.every(sdkArchivePath) ||\n !Array.isArray(archive.files)\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n \"host-backed sandbox persistence returned an invalid SDK archive\",\n { retryable: true },\n );\n }\n const files: SdkLocalArchiveFile[] = [];\n for (const candidate of archive.files) {\n if (!candidate || typeof candidate !== \"object\" || Array.isArray(candidate)) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n \"host-backed sandbox persistence returned an invalid SDK archive\",\n { retryable: true },\n );\n }\n const file = candidate as { path?: unknown; data?: unknown };\n const content = decodeSdkArchiveFile(file.data);\n if (!sdkArchivePath(file.path) || !content) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n \"host-backed sandbox persistence returned an invalid SDK archive\",\n { retryable: true },\n );\n }\n files.push({ path: file.path, content });\n }\n return fingerprintSdkLocalProjection(archive.directories, files);\n}\n\nfunction sameFilesystemEntry(\n left: Awaited<ReturnType<typeof lstat>>,\n right: Awaited<ReturnType<typeof lstat>>,\n): boolean {\n return left.dev === right.dev && left.ino === right.ino;\n}\n\nfunction hostPathChanged(): WorkspaceArchiveIntegrityError {\n return new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n \"host-backed sandbox workspace changed while fingerprinting\",\n { retryable: true },\n );\n}\n\nasync function readStableHostFile(\n path: string,\n expected: Awaited<ReturnType<typeof lstat>>,\n): Promise<Buffer> {\n const before = await lstat(path).catch(() => {\n throw hostPathChanged();\n });\n if (!before.isFile() || !sameFilesystemEntry(before, expected)) {\n throw hostPathChanged();\n }\n let handle: Awaited<ReturnType<typeof open>>;\n try {\n handle = await open(path, HOST_FINGERPRINT_READ_FLAGS);\n } catch {\n throw hostPathChanged();\n }\n try {\n const opened = await handle.stat();\n if (!opened.isFile() || !sameFilesystemEntry(opened, before)) {\n throw hostPathChanged();\n }\n const content = await handle.readFile();\n const after = await handle.stat();\n if (\n !after.isFile() ||\n !sameFilesystemEntry(after, opened) ||\n after.size !== opened.size ||\n after.mtimeMs !== opened.mtimeMs ||\n after.ctimeMs !== opened.ctimeMs\n ) {\n throw hostPathChanged();\n }\n return content;\n } finally {\n await handle.close();\n }\n}\n\nfunction shouldSkipHostArchivePath(path: string, excludedPaths: ReadonlySet<string>): boolean {\n for (const excluded of excludedPaths) {\n if (excluded === \"\" || path === excluded || path.startsWith(`${excluded}/`)) return true;\n }\n return false;\n}\n\n/** Mirrors Agents SDK 0.13.x createWorkspaceArchive(): its Local/Docker\n * persistence is a provider-agnostic JSON archive containing directories and\n * regular files, not an in-container tar stream. Fingerprinting the same host\n * projection removes all image-tool dependencies (including Alpine's lack of\n * bash) and makes the descriptor match what cold restore can actually rebuild. */\nasync function fingerprintHostBackedWorkspace(\n root: string,\n excludedPaths: readonly string[],\n): Promise<WorkspaceTreeFingerprint> {\n const excluded = new Set(excludedPaths);\n const directories: string[] = [];\n const files: SdkLocalArchiveFile[] = [];\n\n const walk = async (\n currentRoot: string,\n relativeRoot = \"\",\n expected?: Awaited<ReturnType<typeof lstat>>,\n ): Promise<void> => {\n const before = await lstat(currentRoot).catch(() => {\n throw hostPathChanged();\n });\n if (!before.isDirectory() || (expected && !sameFilesystemEntry(before, expected))) {\n throw hostPathChanged();\n }\n const entries = await readdir(currentRoot, { withFileTypes: true });\n const afterRead = await lstat(currentRoot).catch(() => {\n throw hostPathChanged();\n });\n if (!afterRead.isDirectory() || !sameFilesystemEntry(afterRead, before)) {\n throw hostPathChanged();\n }\n entries.sort((left, right) => left.name.localeCompare(right.name));\n for (const entry of entries) {\n const relativePath = relativeRoot ? `${relativeRoot}/${entry.name}` : entry.name;\n if (shouldSkipHostArchivePath(relativePath, excluded)) continue;\n const entryPath = join(currentRoot, entry.name);\n const stats = await lstat(entryPath).catch(() => {\n throw hostPathChanged();\n });\n if (stats.isDirectory()) {\n directories.push(relativePath);\n await walk(entryPath, relativePath, stats);\n continue;\n }\n // This is deliberately identical to the SDK archive projection: symlinks,\n // sockets, devices and FIFOs are not serialized and therefore must not\n // influence the restore fingerprint either.\n if (!stats.isFile()) continue;\n const content = await readStableHostFile(entryPath, stats);\n files.push({ path: relativePath, content });\n }\n const afterWalk = await lstat(currentRoot).catch(() => {\n throw hostPathChanged();\n });\n if (!afterWalk.isDirectory() || !sameFilesystemEntry(afterWalk, before)) {\n throw hostPathChanged();\n }\n };\n\n await walk(root);\n return fingerprintSdkLocalProjection(directories, files);\n}\n\nasync function fingerprintRemoteWorkspace(\n target: WorkspaceSession,\n): Promise<WorkspaceTreeFingerprint> {\n const run = target.exec ?? target.execCommand;\n if (!run) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n \"sandbox session cannot execute the workspace fingerprint probe\",\n );\n }\n const cmd = workspaceFingerprintCommand(workspaceFingerprintExcludes(target));\n let result: unknown;\n let match: RegExpMatchArray | null = null;\n for (let attempt = 1; attempt <= 3; attempt += 1) {\n result = await run.call(target, {\n cmd,\n yieldTimeMs: 120_000,\n maxOutputTokens: 1_000,\n });\n match = stdoutFromExecResult(result)\n .trim()\n .match(/^OPENGENI_WORKSPACE_FINGERPRINT_V1 ([a-f0-9]{64}) ([0-9]+) ([0-9]+) ([0-9]+)$/);\n if (match || !isTransientRootDirectoryFingerprintRace(result) || attempt === 3) break;\n await new Promise((resolve) => setTimeout(resolve, attempt * 25));\n }\n if (!match) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n `sandbox workspace fingerprint probe returned no valid digest (${execFailureDiagnostic(result)})`,\n { retryable: true },\n );\n }\n const entryCount = Number(match[2]);\n const fileCount = Number(match[3]);\n const totalFileBytes = Number(match[4]);\n if (![entryCount, fileCount, totalFileBytes].every(Number.isSafeInteger)) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n \"sandbox workspace fingerprint counters exceeded the supported range\",\n );\n }\n return {\n algorithm: \"sha256\",\n sha256: match[1]!,\n entryCount,\n fileCount,\n totalFileBytes,\n };\n}\n\n/**\n * A projection-independent description of a workspace tree: every directory by\n * path and every regular file by path and content SHA-256. It verifies an\n * archive restored by a provider whose native fingerprint is not the archive's\n * own (for example a host-backed archive hydrated into a remote sandbox).\n */\nexport type WorkspaceContentManifest = {\n sha256: string;\n directoryCount: number;\n fileCount: number;\n totalFileBytes: number;\n};\n\nexport type WorkspaceContentEntry =\n | { kind: \"directory\"; path: string }\n | { kind: \"file\"; path: string; sha256: string; byteSize: number };\n\n/** Records are `d <path>` or `<sha256> <path>` (the `sha256sum` line shape),\n * NUL-terminated and ordered by their bytes, so a remote shell computes the\n * identical digest with find, sha256sum -z and `LC_ALL=C sort -z`. */\nexport function workspaceContentManifest(\n entries: Iterable<WorkspaceContentEntry>,\n): WorkspaceContentManifest {\n const records: Buffer[] = [];\n let directoryCount = 0;\n let fileCount = 0;\n let totalFileBytes = 0;\n for (const entry of entries) {\n if (entry.kind === \"directory\") {\n directoryCount += 1;\n records.push(Buffer.from(`d ${entry.path}`));\n } else {\n fileCount += 1;\n totalFileBytes += entry.byteSize;\n records.push(Buffer.from(`${entry.sha256} ${entry.path}`));\n }\n }\n records.sort(Buffer.compare);\n const hash = createHash(\"sha256\");\n for (const record of records) hash.update(record).update(\"\\0\");\n return { sha256: hash.digest(\"hex\"), directoryCount, fileCount, totalFileBytes };\n}\n\nfunction workspaceRoot(target: WorkspaceSession): string {\n const root = target.state?.manifest?.root;\n return typeof root === \"string\" && isAbsolute(root) ? root : \"/workspace\";\n}\n\nfunction workspaceContentManifestCommand(root: string, excludedPaths: readonly string[]): string {\n const prune = findPruneExpression(excludedPaths);\n const script = String.raw`set -eu\ncd ${shellQuote(root)}\ndigest=$( { find . -xdev -mindepth 1 ${prune}-type d -printf \"d %P\\0\"; find . -xdev -mindepth 1 ${prune}-type f -printf \"%P\\0\" | xargs -0 -r sha256sum -z --; } | LC_ALL=C sort -z | sha256sum | awk \"{print \\$1}\")\ndirs=$(find . -xdev -mindepth 1 ${prune}-type d -printf x | wc -c | tr -d \" \")\nfiles=$(find . -xdev -mindepth 1 ${prune}-type f -printf x | wc -c | tr -d \" \")\nbytes=$(find . -xdev -mindepth 1 ${prune}-type f -printf \"%s\\n\" | awk \"{s+=\\$1} END {printf \\\"%.0f\\\", s+0}\")\nprintf \"OPENGENI_WORKSPACE_CONTENTS_V1 %s %s %s %s\\n\" \"$digest\" \"$dirs\" \"$files\" \"$bytes\"`;\n return `bash -o pipefail -c ${shellQuote(script)}`;\n}\n\n/** Reads the content manifest of a remote session's persistent workspace,\n * excluding its manifest-declared ephemeral paths. */\nexport async function readRemoteWorkspaceContentManifest(\n session: unknown,\n): Promise<WorkspaceContentManifest> {\n const target = session as WorkspaceSession;\n const run = target.exec ?? target.execCommand;\n if (!run) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n \"sandbox session cannot execute the workspace content probe\",\n );\n }\n const result = await run.call(target, {\n cmd: workspaceContentManifestCommand(\n workspaceRoot(target),\n workspaceFingerprintExcludes(target),\n ),\n yieldTimeMs: 300_000,\n maxOutputTokens: 1_000,\n });\n const match = stdoutFromExecResult(result)\n .trim()\n .match(/^OPENGENI_WORKSPACE_CONTENTS_V1 ([a-f0-9]{64}) ([0-9]+) ([0-9]+) ([0-9]+)$/);\n if (!match) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n `sandbox workspace content probe returned no valid digest (${execFailureDiagnostic(result)})`,\n { retryable: true },\n );\n }\n const directoryCount = Number(match[2]);\n const fileCount = Number(match[3]);\n const totalFileBytes = Number(match[4]);\n if (![directoryCount, fileCount, totalFileBytes].every(Number.isSafeInteger)) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n \"sandbox workspace content counters exceeded the supported range\",\n );\n }\n return { sha256: match[1]!, directoryCount, fileCount, totalFileBytes };\n}\n\n/** Verifies that a remote session's workspace holds exactly `expected`. */\nexport async function verifyRestoredWorkspaceContents(\n session: unknown,\n expected: WorkspaceContentManifest,\n revision: string,\n): Promise<void> {\n const actual = await readRemoteWorkspaceContentManifest(session);\n if (\n actual.sha256 !== expected.sha256 ||\n actual.directoryCount !== expected.directoryCount ||\n actual.fileCount !== expected.fileCount ||\n actual.totalFileBytes !== expected.totalFileBytes\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_mismatch\",\n `restored workspace does not match selected archive revision ${revision}`,\n );\n }\n}\n\n/** Fingerprints the provider's exact persistent projection. Local/Docker use\n * the SDK's host-backed portable archive projection; remote tar providers use a\n * deterministic GNU-tar stream. Manifest-declared ephemeral paths are excluded\n * in both cases. Only the aggregate enters logs or durable metadata. */\nexport async function fingerprintSandboxWorkspace(\n session: unknown,\n): Promise<WorkspaceTreeFingerprint> {\n const target = session as WorkspaceSession;\n await target.assertWorkspaceCaptureAuthority?.();\n const hostRoot = hostBackedWorkspaceRoot(target);\n return hostRoot\n ? target.workspaceCaptureRootIdentity && process.platform === \"linux\"\n ? await fingerprintHostWorkspace(\n hostRoot,\n workspaceFingerprintExcludes(target),\n target.workspaceCaptureRootIdentity,\n )\n : await fingerprintHostBackedWorkspace(hostRoot, workspaceFingerprintExcludes(target))\n : await fingerprintRemoteWorkspace(target);\n}\n\nfunction fingerprintsEqual(a: WorkspaceTreeFingerprint, b: WorkspaceTreeFingerprint): boolean {\n return (\n (a.projection ?? \"gnu_tar_v1\") === (b.projection ?? \"gnu_tar_v1\") &&\n a.sha256 === b.sha256 &&\n a.entryCount === b.entryCount &&\n a.fileCount === b.fileCount &&\n a.totalFileBytes === b.totalFileBytes\n );\n}\n\n/** Provider-native persistence returns an opaque receipt and is accepted under\n * the provider/artifact publication fence. A real tar capture is accepted only\n * when the complete persistent tree is byte-identical immediately before and\n * after serialization; a concurrent mutation makes that candidate unusable. */\nexport async function captureVerifiedWorkspaceArchive(\n session: unknown,\n capturedAtMs = Date.now(),\n options?: WorkspaceArchiveCaptureOptions,\n): Promise<VerifiedWorkspaceArchive> {\n return await withSandboxProviderCapture(\n session,\n async () => await captureVerifiedWorkspaceArchiveExclusive(session, capturedAtMs, options),\n options?.signal,\n );\n}\n\nasync function captureVerifiedWorkspaceArchiveExclusive(\n session: unknown,\n capturedAtMs: number,\n options?: WorkspaceArchiveCaptureOptions,\n): Promise<VerifiedWorkspaceArchive> {\n const target = session as WorkspaceSession;\n await target.assertWorkspaceCaptureAuthority?.();\n const portableTar = options?.strategy === \"portable_tar\";\n const persist = portableTar ? target.persistWorkspaceTar : target.persistWorkspace;\n if (typeof persist !== \"function\") {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n portableTar\n ? \"sandbox provider policy requires portable tar capture but the session exposes no tar primitive\"\n : \"sandbox session does not support workspace persistence\",\n );\n }\n const configuredPersistence = target.state?.workspacePersistence;\n const configuredTarFallback = workspaceFingerprintExcludes(target).length > 0;\n const expectsNativeSnapshot =\n !portableTar &&\n typeof configuredPersistence === \"string\" &&\n configuredPersistence !== \"tar\" &&\n !configuredTarFallback;\n const before = expectsNativeSnapshot ? null : await fingerprintSandboxWorkspace(target);\n const bytes = portableTar\n ? await target.persistWorkspaceTar!()\n : await target.persistWorkspace!(options);\n if (!bytes || bytes.length === 0) {\n throw new WorkspaceArchiveIntegrityError(\n \"archive_base64_invalid\",\n \"sandbox workspace persistence returned an empty archive\",\n { retryable: true },\n );\n }\n const nativeSnapshot = decodeNativeSnapshotRef(bytes);\n if (nativeSnapshot) {\n const descriptor = describeNativeSnapshotArchive(bytes, capturedAtMs)!;\n return {\n bytes,\n base64: Buffer.from(bytes).toString(\"base64\"),\n descriptor,\n kind: \"provider_snapshot\",\n nativeSnapshot,\n };\n }\n if (expectsNativeSnapshot) {\n throw new WorkspaceArchiveIntegrityError(\n \"native_snapshot_fallback_unverified\",\n `sandbox configured for ${String(configuredPersistence)} returned a tar archive instead of a native snapshot receipt`,\n );\n }\n const after = await fingerprintSandboxWorkspace(target);\n const capturedProjection =\n before?.projection === SDK_LOCAL_ARCHIVE_PROJECTION ? fingerprintSdkLocalArchive(bytes) : null;\n if (\n !before ||\n !fingerprintsEqual(before, after) ||\n (capturedProjection !== null && !fingerprintsEqual(before, capturedProjection))\n ) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_changed_during_capture\",\n \"workspace changed while its durable archive was being captured\",\n { retryable: true },\n );\n }\n const archiveSha256 = sha256(bytes);\n const descriptor: TarWorkspaceArchiveDescriptor = {\n version: 1,\n revision: `wa1:${String(capturedAtMs).padStart(13, \"0\")}:${archiveSha256}`,\n archiveSha256,\n archiveBytes: bytes.length,\n capturedAt: new Date(capturedAtMs).toISOString(),\n workspace: before,\n };\n return {\n bytes,\n base64: Buffer.from(bytes).toString(\"base64\"),\n descriptor,\n kind: \"tar\",\n };\n}\n\nexport async function verifyRestoredWorkspace(\n session: unknown,\n descriptor: WorkspaceArchiveDescriptor,\n): Promise<WorkspaceTreeFingerprint | null> {\n if (descriptor.version === WORKSPACE_ARCHIVE_DESCRIPTOR_VERSION) {\n return null;\n }\n const target = session as WorkspaceSession;\n // Descriptors written before the projection discriminator always used the\n // in-sandbox GNU-tar probe, even for Local/Docker. Preserve that exact legacy\n // behavior; new host-backed descriptors remain independent of image tools.\n const actual =\n descriptor.workspace.projection === SDK_LOCAL_ARCHIVE_PROJECTION\n ? await (() => {\n const root = hostBackedWorkspaceRoot(target);\n if (!root) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_unavailable\",\n \"selected host-backed workspace archive was restored by a non-host-backed provider\",\n );\n }\n return process.platform === \"linux\"\n ? fingerprintHostWorkspace(root, workspaceFingerprintExcludes(target))\n : fingerprintHostBackedWorkspace(root, workspaceFingerprintExcludes(target));\n })()\n : await fingerprintRemoteWorkspace(target);\n if (!fingerprintsEqual(actual, descriptor.workspace)) {\n throw new WorkspaceArchiveIntegrityError(\n \"workspace_fingerprint_mismatch\",\n `restored workspace does not match selected archive revision ${descriptor.revision}`,\n );\n }\n return actual;\n}\n","// The provider registry — PROVIDER_REGISTRY maps each SandboxBackend to its\n// ProviderRegistration. This is the data structure createSandboxClient drives\n// (replacing the old flat if/else chain). The module also owns the\n// descriptor.backendId === SDK client.backendId assertion (deferred from P0.1):\n// it must construct the real SDK clients, so it lives here rather than in the\n// contracts-only capabilities self-test.\n\nimport type { Settings } from \"@opengeni/config\";\nimport {\n LEGACY_SANDBOX_PROVIDER_INSTANCE_ID_FIELDS,\n SANDBOX_PROVIDER_INSTANCE_ID_FIELDS_BY_BACKEND,\n SandboxBackend,\n} from \"@opengeni/contracts\";\nimport type { RuntimeMetricsHooks } from \"../../metrics\";\nimport { assertDescriptorRegistryInvariants } from \"../capabilities\";\nimport { blaxelProvider } from \"./blaxel\";\nimport { cloudflareProvider } from \"./cloudflare\";\nimport { daytonaProvider } from \"./daytona\";\nimport { dockerProvider } from \"./docker\";\nimport { e2bProvider } from \"./e2b\";\nimport { localProvider } from \"./local\";\nimport { modalProvider } from \"./modal\";\nimport { noneProvider } from \"./none\";\nimport { opensandboxProvider } from \"./opensandbox\";\nimport { runloopProvider } from \"./runloop\";\nimport { selfhostedProvider } from \"./selfhosted\";\nimport {\n providerWorkspacePersistence,\n type ProviderImmutableImageBuildResult,\n type ProviderRegistration,\n type ProviderWorkspaceCapturePolicy,\n} from \"./types\";\nimport { vercelProvider } from \"./vercel\";\n\nexport const PROVIDER_REGISTRY: Record<SandboxBackend, ProviderRegistration> = {\n docker: dockerProvider,\n modal: modalProvider,\n local: localProvider,\n none: noneProvider,\n daytona: daytonaProvider,\n runloop: runloopProvider,\n e2b: e2bProvider,\n blaxel: blaxelProvider,\n cloudflare: cloudflareProvider,\n vercel: vercelProvider,\n selfhosted: selfhostedProvider,\n opensandbox: opensandboxProvider,\n};\n\n// Stub settings carrying every per-provider credential, used ONLY by the\n// boot-time backendId assertion to construct each client without tripping\n// validateCredentials. The SDK client constructors are pure option-stores (the\n// underlying provider SDK is required lazily at create()/resume() time, never at\n// construction — verified against the pinned @openai/agents-extensions 0.14.3), so this is\n// safe with no provider peer dep installed and no network.\nconst ASSERTION_STUB_SETTINGS = {\n dockerImage: \"opengeni-sandbox:local\",\n modalAppName: \"opengeni-sandbox\",\n modalTimeoutSeconds: 900,\n daytonaApiKey: \"stub\",\n runloopApiKey: \"stub\",\n runloopTunnel: true,\n e2bApiKey: \"stub\",\n blaxelApiKey: \"stub\",\n cloudflareWorkerUrl: \"https://stub.example.com\",\n vercelToken: \"stub\",\n vercelProjectId: \"stub\",\n openSandboxBaseUrl: \"https://opensandbox.example.test\",\n openSandboxApiKey: \"stub\",\n openSandboxImage:\n \"ghcr.io/cloudgeni-ai/opengeni-sandbox@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n} as unknown as Settings;\n\n/**\n * Assert the descriptor table AND that each registered provider's SDK client\n * reports the backendId its descriptor claims. The latter is the\n * deferred-from-P0.1 invariant — it can only run here because it constructs the\n * real clients. Called once at registry build (and from a unit test).\n */\nexport function assertProviderRegistryInvariants(): void {\n assertDescriptorRegistryInvariants();\n const knownIdentityFields = new Set<string>(LEGACY_SANDBOX_PROVIDER_INSTANCE_ID_FIELDS);\n for (const backend of SandboxBackend.options) {\n const registration = PROVIDER_REGISTRY[backend];\n if (registration.backend !== backend) {\n throw new Error(\n `PROVIDER_REGISTRY[\"${backend}\"].backend mismatch (got \"${registration.backend}\")`,\n );\n }\n if (registration.descriptor.backend !== backend) {\n throw new Error(\n `PROVIDER_REGISTRY[\"${backend}\"].descriptor.backend mismatch (got \"${registration.descriptor.backend}\")`,\n );\n }\n const identityFields = [...registration.instanceIdFields];\n const contractIdentityFields = [...SANDBOX_PROVIDER_INSTANCE_ID_FIELDS_BY_BACKEND[backend]];\n if (\n new Set(identityFields).size !== identityFields.length ||\n identityFields.some((field) => !knownIdentityFields.has(field)) ||\n identityFields.length !== contractIdentityFields.length ||\n identityFields.some((field, index) => field !== contractIdentityFields[index])\n ) {\n throw new Error(`Provider \"${backend}\" has an invalid live instance identity declaration`);\n }\n if (backend === \"none\") {\n // \"none\" has no SDK client (build returns undefined); the descriptor\n // backendId \"none\" is self-consistent.\n if (registration.descriptor.backendId !== \"none\") {\n throw new Error(\n `\"none\" descriptor.backendId must be \"none\" (got \"${registration.descriptor.backendId}\")`,\n );\n }\n if (registration.exactResumeMode !== \"none\") {\n throw new Error('Provider \"none\" must declare exactResumeMode=\"none\"');\n }\n continue;\n }\n if (registration.exactResumeMode === \"none\") {\n throw new Error(`Provider \"${backend}\" cannot declare exactResumeMode=\"none\"`);\n }\n const client = registration.build({\n settings: ASSERTION_STUB_SETTINGS,\n environment: {},\n exposedPorts: [],\n });\n const sdkBackendId = (client as { backendId?: unknown } | undefined)?.backendId;\n if (typeof sdkBackendId !== \"string\") {\n throw new Error(`Provider \"${backend}\" SDK client has no string backendId`);\n }\n if (sdkBackendId !== registration.descriptor.backendId) {\n throw new Error(\n `Provider \"${backend}\" backendId mismatch: descriptor.backendId=\"${registration.descriptor.backendId}\" but SDK client.backendId=\"${sdkBackendId}\"`,\n );\n }\n if (typeof (client as { resume?: unknown }).resume !== \"function\") {\n throw new Error(`Provider \"${backend}\" SDK client exposes no resume()`);\n }\n if (\n registration.exactResumeMode === \"custom\" &&\n typeof (client as { resumeExact?: unknown }).resumeExact !== \"function\"\n ) {\n throw new Error(`Provider \"${backend}\" requires but exposes no non-replacing resumeExact()`);\n }\n if (registration.continuity && registration.exactResumeMode !== \"custom\") {\n throw new Error(`Provider \"${backend}\" continuity requires custom exact resume`);\n }\n const capturePolicy = registration.workspaceCapturePolicy({});\n if ((backend === \"selfhosted\") !== (capturePolicy === null)) {\n throw new Error(\n `Provider \"${backend}\" must explicitly ${\n backend === \"selfhosted\" ? \"omit\" : \"declare\"\n } workspace capture`,\n );\n }\n if (capturePolicy?.strategy === \"portable_tar\" && capturePolicy.liveInstance !== \"preserved\") {\n throw new Error(`Provider \"${backend}\" portable tar capture must preserve its instance`);\n }\n }\n}\n\nexport function providerWorkspaceCapturePolicy(\n backend: string,\n state: unknown,\n): ProviderWorkspaceCapturePolicy | null {\n const registration = PROVIDER_REGISTRY[backend as SandboxBackend];\n return registration?.workspaceCapturePolicy(state) ?? null;\n}\n\n/** True when the provider's workspace capture images the paused box at one\n * instant (Modal native filesystem/directory snapshots), so a command still\n * running cannot tear the captured state across files the way a file-by-file\n * tar read of a running box can. */\nexport function providerWorkspaceCaptureIsPointInTime(backend: string, state: unknown): boolean {\n if (backend !== \"modal\") return false;\n const persistence = providerWorkspacePersistence(state);\n return persistence === \"snapshot_filesystem\" || persistence === \"snapshot_directory\";\n}\n\nexport function prepareProviderForTeardownAfterCapture(backend: string, session: unknown): void {\n PROVIDER_REGISTRY[backend as SandboxBackend]?.prepareForTeardownAfterCapture?.(session);\n}\n\nexport function providerSupportsImmutableImageBuild(backend: SandboxBackend): boolean {\n return typeof PROVIDER_REGISTRY[backend].buildImmutableImage === \"function\";\n}\n\nexport async function renewSandboxProviderExpiration(input: {\n backend: SandboxBackend;\n settings: Settings;\n instanceId: string;\n metrics?: RuntimeMetricsHooks;\n}): Promise<boolean> {\n const registration = PROVIDER_REGISTRY[input.backend];\n const renew = registration.renewExpiration;\n if (!renew) return false;\n registration.validateCredentials(input.settings);\n try {\n await renew({ settings: input.settings, instanceId: input.instanceId });\n recordProviderRenewalMetric(input.metrics, input.backend, \"completed\");\n return true;\n } catch (error) {\n recordProviderRenewalMetric(input.metrics, input.backend, \"failed\");\n if (isProviderApiThrottleError(error)) {\n try {\n input.metrics?.onSandboxProviderApiThrottle?.({\n backend: input.backend,\n operation: \"renew\",\n });\n } catch {\n // Metrics emission must not affect provider lifecycle.\n }\n }\n throw error;\n }\n}\n\nexport function isProviderApiThrottleError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const candidate = error as {\n status?: unknown;\n statusCode?: unknown;\n response?: { status?: unknown };\n };\n return (\n candidate.status === 429 || candidate.statusCode === 429 || candidate.response?.status === 429\n );\n}\n\nfunction recordProviderRenewalMetric(\n metrics: RuntimeMetricsHooks | undefined,\n backend: SandboxBackend,\n outcome: \"completed\" | \"failed\",\n): void {\n try {\n metrics?.onSandboxTtlRenewal?.({ backend, outcome });\n } catch {\n // Metrics emission must not affect provider lifecycle.\n }\n}\n\nexport async function buildImmutableProviderImage(input: {\n backend: SandboxBackend;\n settings: Settings;\n session: unknown;\n requestId: string;\n timeoutMs: number;\n}): Promise<ProviderImmutableImageBuildResult | null> {\n const build = PROVIDER_REGISTRY[input.backend].buildImmutableImage;\n if (!build) return null;\n return await build({\n settings: input.settings,\n session: input.session,\n requestId: input.requestId,\n timeoutMs: input.timeoutMs,\n });\n}\n\n// Boot-validate the registry once at module load: the descriptor-table self-\n// test PLUS the descriptor.backendId === SDK client.backendId assertion (the\n// deferred-from-P0.1 invariant). The SDK client constructors are pure option-\n// stores (no network, no peer-dep require at construction), so this is a cheap,\n// side-effect-free guard that fails fast on any drift between the static matrix\n// and the installed @openai/agents-extensions.\nassertProviderRegistryInvariants();\n\nexport type {\n ProviderRegistration,\n ProviderConstructionContext,\n ProviderExactResumeMode,\n ProviderImmutableImageBuildInput,\n ProviderImmutableImageBuildResult,\n ProviderExpirationRenewalInput,\n ProviderWorkspaceCapturePolicy,\n ProviderWorkspaceCaptureTakeover,\n} from \"./types\";\n","// Capability-descriptor access + boot-time registry invariants (module 03 §2.3).\n//\n// The CapabilityDescriptor type and the CAPABILITY_DESCRIPTORS table-as-data\n// live in @opengeni/contracts (NOT here) so config can read them without an\n// import cycle through runtime (ledger CR8). This module re-exports them for the\n// registry's convenience and owns the boot-time self-test that keeps the table\n// honest as providers are added.\n\nimport {\n CAPABILITY_DESCRIPTORS,\n DESKTOP_STREAM_PORT,\n SandboxBackend,\n type CapabilityDescriptor,\n} from \"@opengeni/contracts\";\n\nexport { CAPABILITY_DESCRIPTORS, DESKTOP_STREAM_PORT };\nexport type { CapabilityDescriptor };\n\n/**\n * Descriptor-table invariants, asserted once at registry build (and from a unit\n * test). This is the guardrail that keeps the static matrix internally coherent.\n * It validates the descriptor data only; the descriptor.backendId === SDK\n * client.backendId assertion (the deferred-from-P0.1 check) lives in\n * providers/index.ts because it must construct the real SDK clients.\n */\nexport function assertDescriptorRegistryInvariants(): void {\n for (const backend of SandboxBackend.options) {\n const descriptor = CAPABILITY_DESCRIPTORS[backend];\n if (!descriptor) {\n throw new Error(`No CapabilityDescriptor for backend \"${backend}\"`);\n }\n if (descriptor.backend !== backend) {\n throw new Error(`Descriptor.backend mismatch for \"${backend}\" (got \"${descriptor.backend}\")`);\n }\n\n // DesktopStream implies a non-\"none\" port-exposure mechanism (split-plane B\n // needs a way to surface 6080 to a viewer).\n if (\n descriptor.capabilities.DesktopStream.available &&\n descriptor.portExposure.kind === \"none\"\n ) {\n throw new Error(`\"${backend}\" claims DesktopStream but portExposure.kind=none`);\n }\n\n // DesktopStream implies a transport, and a desktop transport implies the\n // capability is available (no half-declared desktop rows).\n if (\n descriptor.capabilities.DesktopStream.available &&\n descriptor.capabilities.DesktopStream.transport === null\n ) {\n throw new Error(`\"${backend}\" claims DesktopStream but transport is null`);\n }\n\n // Recording feasibility is the same Xvfb display as DesktopStream: a desktop\n // backend MUST be able to x11grab; a non-desktop backend MUST NOT claim it\n // (Recording.available == DesktopStream.available && os==linux — Part D).\n if (\n descriptor.capabilities.DesktopStream.available !==\n descriptor.capabilities.Recording.available\n ) {\n throw new Error(\n `\"${backend}\" Recording.available (${descriptor.capabilities.Recording.available}) must equal DesktopStream.available (${descriptor.capabilities.DesktopStream.available})`,\n );\n }\n\n // Persistable backends are the only ones the lease can re-establish from an\n // envelope — they must carry a real snapshot mechanism.\n if (descriptor.persistable && descriptor.snapshot.kind === \"none\") {\n throw new Error(`\"${backend}\" persistable but snapshot.kind=none`);\n }\n\n // A nativeBucketMount backend must be desktop/headless-tier real (modal):\n // a dev/none tier cannot own a provider bucket mount.\n if (descriptor.nativeBucketMount && (descriptor.tier === \"dev\" || descriptor.tier === \"none\")) {\n throw new Error(`\"${backend}\" claims nativeBucketMount on tier=${descriptor.tier}`);\n }\n }\n}\n","// The uniform per-provider registration shape (module 03 §3.1).\n//\n// One file per provider implements ProviderRegistration; PROVIDER_REGISTRY maps\n// each SandboxBackend to its registration. This replaces the flat if/else chain\n// that createSandboxClient used to be.\n\nimport type { Settings } from \"@opengeni/config\";\nimport type { CapabilityDescriptor, SandboxBackend } from \"@opengeni/contracts\";\nimport type { RuntimeMetricsHooks } from \"../../metrics\";\n\nexport interface ProviderConstructionContext {\n settings: Settings;\n /** The env map for the box (collectSandboxEnvironment / per-run environment). */\n environment: Record<string, string>;\n /**\n * Parsed exposed ports (config string -> number[]); already includes the\n * desktop stream port (6080) when this is a desktop tier with desktop enabled\n * and the provider cannot expose ports on demand (the merge happens in\n * createSandboxClient before build()).\n */\n exposedPorts: number[];\n metrics?: RuntimeMetricsHooks;\n}\n\nexport type ProviderImmutableImageBuildResult = {\n provider: string;\n backend: SandboxBackend;\n imageId: string | null;\n imageDigest: string | null;\n /** Exact provider account/workspace binding. Persist only a hash publicly. */\n providerBindingKey: string | null;\n /** Non-secret canonical binding retained only for durable provider artifact ownership. */\n providerBinding: Record<string, unknown> | null;\n};\n\nexport type ProviderImmutableImageBuildInput = {\n settings: Settings;\n session: unknown;\n requestId: string;\n timeoutMs: number;\n};\n\nexport type ProviderExpirationRenewalInput = {\n settings: Settings;\n instanceId: string;\n};\n\n/**\n * Crash-recovery contract for one provider's /workspace capture path.\n *\n * - `same_request`: retrying with the durable request id resumes/returns the\n * same provider operation.\n * - `parallel_read`: the adapter deliberately uses an independently repeatable,\n * read-only capture (normally a uniquely-named tar); overlapping a predecessor\n * after worker loss cannot replace or mutate the live sandbox.\n * - `exclusive`: neither property is proven, so an ambiguous predecessor may\n * never be overlapped while the provider instance is still live.\n */\nexport type ProviderWorkspaceCaptureTakeover = \"same_request\" | \"parallel_read\" | \"exclusive\";\n\nexport type ProviderWorkspaceCapturePolicy = {\n takeover: ProviderWorkspaceCaptureTakeover;\n /** `portable_tar` bypasses a provider-native persistence mode whose capture\n * replaces the live instance or creates an unledgered native artifact. */\n strategy: \"configured\" | \"portable_tar\";\n /** Warm checkpoints are legal only when capture preserves the addressed\n * physical instance. A replacing capture must never run behind a lease whose\n * provider identity cannot be atomically republished with it. */\n liveInstance: \"preserved\" | \"replaced\";\n};\n\n/**\n * How Opengeni obtains a non-replacing attachment to the exact persisted\n * provider instance.\n *\n * - `ordinary`: SDK `resume()` is already a pure re-address operation; the\n * factory exposes it through the explicit `resumeExact()` contract.\n * - `custom`: ordinary resume may restore/recreate, so the adapter itself must\n * implement `resumeExact()` and fail when the addressed instance is absent.\n * - `none`: the backend has no provider session.\n */\nexport type ProviderExactResumeMode = \"ordinary\" | \"custom\" | \"none\";\n\nexport const REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE = Object.freeze({\n takeover: \"parallel_read\",\n strategy: \"configured\",\n liveInstance: \"preserved\",\n} satisfies ProviderWorkspaceCapturePolicy);\n\nexport const REPEATABLE_PORTABLE_TAR_WORKSPACE_CAPTURE = Object.freeze({\n takeover: \"parallel_read\",\n strategy: \"portable_tar\",\n liveInstance: \"preserved\",\n} satisfies ProviderWorkspaceCapturePolicy);\n\n/** Read SDK workspace persistence without coupling callers to the three shapes\n * used across live sessions, serialized provider state, and lease envelopes. */\nexport function providerWorkspacePersistence(state: unknown): unknown {\n if (!state || typeof state !== \"object\" || Array.isArray(state)) return undefined;\n const outer = state as Record<string, unknown>;\n const liveState =\n outer.state && typeof outer.state === \"object\" && !Array.isArray(outer.state)\n ? (outer.state as Record<string, unknown>)\n : outer;\n const sessionState =\n liveState.sessionState &&\n typeof liveState.sessionState === \"object\" &&\n !Array.isArray(liveState.sessionState)\n ? (liveState.sessionState as Record<string, unknown>)\n : liveState;\n const providerState =\n sessionState.providerState &&\n typeof sessionState.providerState === \"object\" &&\n !Array.isArray(sessionState.providerState)\n ? (sessionState.providerState as Record<string, unknown>)\n : null;\n return providerState?.workspacePersistence ?? sessionState.workspacePersistence;\n}\n\nexport interface ProviderRegistration {\n backend: SandboxBackend;\n exactResumeMode: ProviderExactResumeMode;\n /** Exact live-session state fields that address this provider. New providers\n * must declare this explicitly; generic `id` guessing is forbidden. */\n instanceIdFields: readonly string[];\n /** Optional identity below the disposable provider execution wrapper. A\n * matching key licenses a replacement only when the caller supplies a\n * durable continuity receipt; ordinary attached resumes remain exact. */\n continuity?: {\n kind: \"docker_workspace\";\n keyFromState(state: unknown): string | null;\n /** Make discarding an unpublished replacement preserve the shared durable\n * workspace named by the continuity key. */\n preserveWorkspaceForDiscard(session: unknown, sessionState: unknown): void;\n };\n /** Resolve capture semantics from either a live session, a serialized SDK\n * session state, or Opengeni's outer session envelope. Required for every\n * provider so new backends cannot silently inherit unsafe teardown behavior.\n * `null` means the backend has no provider workspace to capture. */\n workspaceCapturePolicy(state: unknown): ProviderWorkspaceCapturePolicy | null;\n /** Optional provider preparation after a verified archive is durable and\n * immediately before generic SDK teardown. This may only suppress redundant\n * provider persistence; it must not alter durable identity or workspace data. */\n prepareForTeardownAfterCapture?(session: unknown): void;\n /**\n * Build one provider-native immutable image from an already verified clean\n * sandbox. Omission is the truthful unsupported-provider signal; callers\n * must retain runtime setup as the fallback.\n */\n buildImmutableImage?(\n input: ProviderImmutableImageBuildInput,\n ): Promise<ProviderImmutableImageBuildResult>;\n /** Refresh a renewable provider expiration for one exact live instance.\n * Omission means the provider has no renewable TTL contract. */\n renewExpiration?(input: ProviderExpirationRenewalInput): Promise<void>;\n descriptor: CapabilityDescriptor;\n /**\n * Validate that the settings carry the credentials/config this provider\n * REQUIRES. Throw SandboxConfigError on any missing/contradictory field.\n * Pure — no network. Called by both the factory and a deploy-time preflight.\n * The factory calls this before build(), so build() may assume valid settings.\n */\n validateCredentials(settings: Settings): void;\n /**\n * Build the raw SDK SandboxClient. Returns undefined ONLY for \"none\".\n * The factory calls validateCredentials() first, so build() can assume valid.\n */\n build(ctx: ProviderConstructionContext): unknown;\n}\n","import { BlaxelSandboxClient } from \"@openai/agents-extensions/sandbox/blaxel\";\nimport { CAPABILITY_DESCRIPTORS } from \"../capabilities\";\nimport { SandboxConfigError } from \"../errors\";\nimport { REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE, type ProviderRegistration } from \"./types\";\n\nexport const blaxelProvider: ProviderRegistration = {\n backend: \"blaxel\",\n exactResumeMode: \"custom\",\n instanceIdFields: [\"sandboxIdentity\"],\n workspaceCapturePolicy: () => REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE,\n descriptor: CAPABILITY_DESCRIPTORS.blaxel,\n validateCredentials(settings) {\n if (!settings.blaxelApiKey) {\n throw new SandboxConfigError(\"blaxel\", \"OPENGENI_BLAXEL_API_KEY is required\");\n }\n },\n build({ settings, environment }) {\n // Blaxel exposes ports ON DEMAND (the only such backend) — its options take\n // no `exposedPorts: number[]` list; 6080 is resolved at handshake time, so\n // we do NOT pre-declare it here (this is why the factory's 6080-merge is\n // gated on !supportsOnDemandPorts).\n const options: NonNullable<ConstructorParameters<typeof BlaxelSandboxClient>[0]> = {\n apiKey: settings.blaxelApiKey!,\n env: environment,\n // persistWorkspace() creates a remote tarball. Bound that provider-native\n // operation by the same immutable deadline as the durable capture claim;\n // Opengeni's outer timeout still protects every provider uniformly.\n timeouts: { workspaceTarTimeoutMs: settings.sandboxSnapshotTimeoutMs },\n };\n if (settings.blaxelImage) options.image = settings.blaxelImage;\n if (settings.blaxelRegion) options.region = settings.blaxelRegion;\n if (settings.blaxelExposedPortPublic !== undefined) {\n options.exposedPortPublic = settings.blaxelExposedPortPublic;\n }\n if (settings.blaxelExposedPortUrlTtlSeconds) {\n options.exposedPortUrlTtlS = settings.blaxelExposedPortUrlTtlSeconds;\n }\n if (settings.blaxelMemoryMb) options.memory = settings.blaxelMemoryMb;\n if (settings.blaxelTtl) options.ttl = settings.blaxelTtl;\n return new BlaxelSandboxClient(options);\n },\n};\n","import { CloudflareSandboxClient } from \"@openai/agents-extensions/sandbox/cloudflare\";\nimport { CAPABILITY_DESCRIPTORS } from \"../capabilities\";\nimport { SandboxConfigError } from \"../errors\";\nimport { REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE, type ProviderRegistration } from \"./types\";\n\nexport const cloudflareProvider: ProviderRegistration = {\n backend: \"cloudflare\",\n exactResumeMode: \"ordinary\",\n instanceIdFields: [\"sandboxId\"],\n workspaceCapturePolicy: () => REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE,\n descriptor: CAPABILITY_DESCRIPTORS.cloudflare,\n validateCredentials(settings) {\n // workerUrl is the addressing root for the Cloudflare Sandbox Worker — there\n // is no construction without it (it is the one non-optional client option).\n if (!settings.cloudflareWorkerUrl) {\n throw new SandboxConfigError(\"cloudflare\", \"OPENGENI_CLOUDFLARE_WORKER_URL is required\");\n }\n },\n build({ settings, exposedPorts }) {\n const options: NonNullable<ConstructorParameters<typeof CloudflareSandboxClient>[0]> = {\n workerUrl: settings.cloudflareWorkerUrl!,\n exposedPorts,\n // `/persist` is an HTTP request rather than the shared remote-tar helper.\n // Abort its provider transport at the same immutable budget as the\n // durable capture claim; the outer lifecycle fence still owns settlement.\n timeouts: { requestTimeoutMs: settings.sandboxSnapshotTimeoutMs },\n };\n if (settings.cloudflareApiKey) options.apiKey = settings.cloudflareApiKey;\n return new CloudflareSandboxClient(options);\n },\n};\n","import { DaytonaSandboxClient } from \"@openai/agents-extensions/sandbox/daytona\";\nimport { CAPABILITY_DESCRIPTORS } from \"../capabilities\";\nimport { SandboxConfigError } from \"../errors\";\nimport { REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE, type ProviderRegistration } from \"./types\";\nimport { withDaytonaCommandBinding } from \"./daytona-command-binding\";\n\nexport const daytonaProvider: ProviderRegistration = {\n backend: \"daytona\",\n exactResumeMode: \"custom\",\n instanceIdFields: [\"sandboxId\"],\n workspaceCapturePolicy: () => REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE,\n descriptor: CAPABILITY_DESCRIPTORS.daytona,\n validateCredentials(settings) {\n if (!settings.daytonaApiKey) {\n throw new SandboxConfigError(\"daytona\", \"OPENGENI_DAYTONA_API_KEY is required\");\n }\n },\n build({ settings, environment, exposedPorts }) {\n const options: NonNullable<ConstructorParameters<typeof DaytonaSandboxClient>[0]> = {\n apiKey: settings.daytonaApiKey!,\n env: environment,\n exposedPorts,\n };\n if (settings.daytonaApiUrl) options.apiUrl = settings.daytonaApiUrl;\n if (settings.daytonaTarget) options.target = settings.daytonaTarget;\n if (settings.daytonaImage) options.image = settings.daytonaImage;\n if (settings.daytonaSnapshotName) options.sandboxSnapshotName = settings.daytonaSnapshotName;\n // autoStopInterval=0 disables the idle-kill, so forward 0 explicitly.\n if (settings.daytonaAutoStopInterval !== undefined) {\n options.autoStopInterval = settings.daytonaAutoStopInterval;\n }\n if (settings.daytonaTimeoutSeconds) options.timeoutSec = settings.daytonaTimeoutSeconds;\n if (settings.daytonaExposedPortUrlTtlSeconds) {\n options.exposedPortUrlTtlS = settings.daytonaExposedPortUrlTtlSeconds;\n }\n return withDaytonaCommandBinding(new DaytonaSandboxClient(options), options);\n },\n};\n","import {\n DockerSandboxClient,\n DockerSandboxSession,\n type DockerSandboxClientOptions,\n} from \"@openai/agents/sandbox/local\";\nimport { NoopSnapshotSpec } from \"@openai/agents/sandbox\";\nimport { execFile } from \"node:child_process\";\nimport { isAbsolute } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { CAPABILITY_DESCRIPTORS } from \"../capabilities\";\nimport { SandboxConfigError, SandboxExactResumeInstanceUnavailableError } from \"../errors\";\nimport { REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE, type ProviderRegistration } from \"./types\";\n\nimport {\n attachDockerWorkspaceForDrain,\n rememberOwnedDockerSdkState,\n rememberSerializedDockerOwnership,\n serializeDockerOwnership,\n} from \"./docker-workspace-drain\";\n\nconst execFileAsync = promisify(execFile);\nconst DOCKER_EXACT_INSPECT_TIMEOUT_MS = 10_000;\nconst DOCKER_INSTANCE_ID = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;\n\ntype DockerResumeState = {\n containerId?: unknown;\n image?: unknown;\n workspaceRootPath?: unknown;\n workspaceRootOwned?: unknown;\n snapshot?: unknown;\n};\n\n/** A cold continuity owner is the only caller allowed to replace a missing\n * Docker execution wrapper while preserving its host workspace. The durable\n * provider state carries the image of the missing container; prefer the\n * currently configured image for the replacement so a deployment upgrade\n * cannot publish a new lease image while silently restarting the old one. */\nexport function dockerContinuityResumeStateForImage<T>(\n state: T,\n configuredImage: string | undefined,\n): T {\n const image = configuredImage?.trim();\n if (!image || !state || typeof state !== \"object\" || Array.isArray(state)) return state;\n return { ...state, image };\n}\n\nfunction dockerContinuityKey(state: unknown): string | null {\n if (!state || typeof state !== \"object\" || Array.isArray(state)) return null;\n const value = state as DockerResumeState;\n // Opengeni explicitly disables the SDK's local snapshot facility. Requiring\n // that invariant prevents the SDK from restoring an older local snapshot\n // over a newer host workspace before restarting the container.\n return typeof value.workspaceRootPath === \"string\" &&\n isAbsolute(value.workspaceRootPath) &&\n value.workspaceRootOwned === true &&\n (value.snapshot === null || value.snapshot === undefined)\n ? value.workspaceRootPath\n : null;\n}\n\nfunction preserveDockerWorkspaceForDiscard(session: unknown, sessionState: unknown): void {\n for (const candidate of [(session as { state?: unknown } | null)?.state, sessionState]) {\n if (!candidate || typeof candidate !== \"object\" || Array.isArray(candidate)) continue;\n (candidate as { workspaceRootOwned?: boolean }).workspaceRootOwned = false;\n }\n}\n\nfunction dockerInspectMessage(error: unknown): string {\n if (!error || typeof error !== \"object\") return \"\";\n const stderr = Reflect.get(error, \"stderr\");\n return typeof stderr === \"string\" ? stderr.trim() : \"\";\n}\n\nexport function dockerInspectProvesMissing(error: unknown, containerId: string): boolean {\n const escaped = containerId.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(\n `^(?:Error|Error response from daemon): No such (?:object|container): ${escaped}$`,\n ).test(dockerInspectMessage(error));\n}\n\nclass OpenGeniDockerSandboxClient extends DockerSandboxClient {\n readonly #openGeniOptions: DockerSandboxClientOptions;\n\n constructor(options: DockerSandboxClientOptions = {}) {\n super(options);\n this.#openGeniOptions = options;\n }\n\n override async create(...args: Parameters<DockerSandboxClient[\"create\"]>) {\n const session = await super.create(...args);\n rememberOwnedDockerSdkState(session.state);\n return session;\n }\n\n override async deserializeSessionState(\n state: Parameters<DockerSandboxClient[\"deserializeSessionState\"]>[0],\n ) {\n const restored = await super.deserializeSessionState(state);\n rememberSerializedDockerOwnership(restored, state);\n return restored;\n }\n\n override async serializeSessionState(\n state: Parameters<DockerSandboxClient[\"serializeSessionState\"]>[0],\n options?: Parameters<DockerSandboxClient[\"serializeSessionState\"]>[1],\n ) {\n const ownership = await serializeDockerOwnership(this, state);\n return { ...(await super.serializeSessionState(state, options)), ...ownership };\n }\n\n /** Only the server reaper uses this capture-only surface. The network\n * decorator forwards it without setup, connect or ordinary resume. */\n async attachWorkspaceForDrain(\n state: Parameters<DockerSandboxClient[\"resume\"]>[0],\n assertCurrentCapture: () => Promise<{ archivePublished: boolean }>,\n options?: Parameters<DockerSandboxClient[\"resume\"]>[1],\n ) {\n const archiveLimits =\n options?.archiveLimits === undefined\n ? this.#openGeniOptions.archiveLimits\n : options.archiveLimits;\n return await attachDockerWorkspaceForDrain(\n this,\n state,\n assertCurrentCapture,\n undefined,\n archiveLimits,\n );\n }\n\n /** Ordinary resume is reserved by Opengeni for the elected cold continuity\n * owner. Exact live attachment uses resumeExact() below and never reimages. */\n override async resume(\n state: Parameters<DockerSandboxClient[\"resume\"]>[0],\n options?: Parameters<DockerSandboxClient[\"resume\"]>[1],\n ) {\n const session = await super.resume(\n dockerContinuityResumeStateForImage(state, this.#openGeniOptions.image),\n options,\n );\n rememberOwnedDockerSdkState(session.state);\n return session;\n }\n\n /** Exact attach must not call the SDK's ordinary resume when the persisted\n * container is absent: ordinary resume intentionally starts a new container.\n * The elected recovery owner calls ordinary resume through the shared\n * continuity protocol instead. */\n async resumeExact(\n state: Parameters<DockerSandboxClient[\"resume\"]>[0],\n options?: Parameters<DockerSandboxClient[\"resume\"]>[1],\n ) {\n const containerId = (state as DockerResumeState).containerId;\n if (typeof containerId !== \"string\" || !DOCKER_INSTANCE_ID.test(containerId)) {\n throw new SandboxConfigError(\"docker\", \"persisted Docker container identity is invalid\");\n }\n try {\n const result = await execFileAsync(\n \"docker\",\n [\"inspect\", \"--type\", \"container\", \"--format\", \"{{.State.Running}}\", containerId],\n { timeout: DOCKER_EXACT_INSPECT_TIMEOUT_MS, maxBuffer: 64 * 1024 },\n );\n if (result.stdout.trim() !== \"true\") {\n throw new SandboxExactResumeInstanceUnavailableError(\"docker\", containerId);\n }\n } catch (error) {\n if (\n error instanceof SandboxExactResumeInstanceUnavailableError ||\n dockerInspectProvesMissing(error, containerId)\n ) {\n throw new SandboxExactResumeInstanceUnavailableError(\"docker\", containerId);\n }\n throw error;\n }\n // Do not call super.resume() after the preflight. The container can vanish\n // between those operations and the SDK then restores/restarts a replacement.\n // A direct session wrapper is non-mutating; a later command may fail if the\n // container stopped after inspect, which is the correct fenced outcome.\n const archiveLimits =\n options?.archiveLimits === undefined\n ? this.#openGeniOptions.archiveLimits\n : options.archiveLimits;\n const session = new DockerSandboxSession({\n state,\n ...(archiveLimits !== undefined ? { archiveLimits } : {}),\n });\n rememberOwnedDockerSdkState(session.state);\n return session;\n }\n}\n\nexport const dockerProvider: ProviderRegistration = {\n backend: \"docker\",\n exactResumeMode: \"custom\",\n instanceIdFields: [\"containerId\"],\n workspaceCapturePolicy: () => REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE,\n continuity: {\n kind: \"docker_workspace\",\n keyFromState: dockerContinuityKey,\n preserveWorkspaceForDiscard: preserveDockerWorkspaceForDiscard,\n },\n descriptor: CAPABILITY_DESCRIPTORS.docker,\n // Local dev container — no credentials. (The dockerNetwork decoration is\n // applied by the factory, not here: it wraps the constructed client.)\n validateCredentials(settings) {\n const workspaceBaseDir = settings.dockerWorkspaceBaseDir?.trim();\n if (workspaceBaseDir && !isAbsolute(workspaceBaseDir)) {\n throw new SandboxConfigError(\n \"docker\",\n \"OPENGENI_DOCKER_WORKSPACE_BASE_DIR must be an absolute path\",\n );\n }\n },\n build({ settings, exposedPorts }) {\n const workspaceBaseDir = settings.dockerWorkspaceBaseDir?.trim();\n return new OpenGeniDockerSandboxClient({\n image: settings.dockerImage,\n exposedPorts,\n // The Opengeni archive ledger is the recovery authority. SDK-local\n // snapshots are process-host artifacts and, more importantly, ordinary\n // Docker resume may overwrite a newer live host workspace from them.\n snapshot: new NoopSnapshotSpec(),\n ...(workspaceBaseDir ? { workspaceBaseDir } : {}),\n });\n },\n};\n","import { execFile } from \"node:child_process\";\nimport { isAbsolute, join, resolve } from \"node:path\";\nimport { constants } from \"node:fs\";\nimport { chmod, lstat, open, readdir, realpath, rm } from \"node:fs/promises\";\nimport { promisify } from \"node:util\";\nimport { DockerSandboxSession, type DockerSandboxClient } from \"@openai/agents/sandbox/local\";\nimport type { SandboxArchiveLimits } from \"@openai/agents/sandbox\";\nimport {\n captureHostWorkspaceArchive,\n readHostWorkspaceRootIdentity,\n type HostWorkspaceRootIdentity,\n} from \"../host-archive-spool\";\nimport { SandboxConfigError } from \"../errors\";\n\nconst execFileAsync = promisify(execFile);\ntype NativeProbe = (\n args: readonly string[],\n timeout: number,\n) => Promise<{ stdout: string; stderr: string }>;\nconst nativeProbe: NativeProbe = async (args, timeout) =>\n await execFileAsync(\"docker\", [...args], { timeout, maxBuffer: 1024 * 1024 });\nconst FIELD = \"opengeniDockerWorkspaceOwnership\";\nconst ID = /^[a-f0-9]{64}$/;\nconst UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;\nconst SHA = /^[a-f0-9]{64}$/;\ntype State = Parameters<DockerSandboxClient[\"resume\"]>[0];\ntype Ownership = {\n version: 1;\n containerId: string;\n sessionIdentity: string;\n daemonId: string;\n mountFingerprint: string;\n root: string;\n sourceRoot: string;\n identity: HostWorkspaceRootIdentity;\n};\nconst receipts = new WeakMap<object, Ownership>();\nconst ownedSdkStates = new WeakSet<object>();\n\n/** Internal SDK producer identity, not caller metadata or a filesystem grant. */\nexport function rememberOwnedDockerSdkState(state: State): void {\n ownedSdkStates.add(state);\n}\n\nfunction invalid(message: string): never {\n throw new SandboxConfigError(\"docker\", \"Docker drain workspace authority: \" + message);\n}\n\nfunction shape(state: State) {\n if (\n !ID.test(state.containerId) ||\n !UUID.test(state.sessionIdentity ?? \"\") ||\n state.workspaceRootOwned !== true ||\n !isAbsolute(state.workspaceRootPath) ||\n resolve(state.workspaceRootPath) !== state.workspaceRootPath ||\n state.workspaceRootPath === \"/\" ||\n (state.snapshot !== null && state.snapshot !== undefined)\n )\n invalid(\"owned SDK state is unavailable\");\n return {\n containerId: state.containerId,\n sessionIdentity: state.sessionIdentity!,\n root: state.workspaceRootPath,\n };\n}\n\nfunction parsedReceipt(value: unknown, state: State): Ownership | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const v = value as Ownership;\n const s = shape(state);\n if (\n v.version !== 1 ||\n v.containerId !== s.containerId ||\n v.sessionIdentity !== s.sessionIdentity ||\n v.sourceRoot !== s.root ||\n typeof v.root !== \"string\" ||\n !isAbsolute(v.root) ||\n resolve(v.root) !== v.root ||\n v.root === \"/\" ||\n typeof v.daemonId !== \"string\" ||\n !/^[A-Za-z0-9:_.-]{1,200}$/.test(v.daemonId) ||\n !SHA.test(v.mountFingerprint) ||\n !v.identity ||\n typeof v.identity !== \"object\" ||\n ![\"dev\", \"ino\", \"uid\", \"gid\", \"mode\"].every(\n (key) =>\n typeof v.identity[key as keyof HostWorkspaceRootIdentity] === \"string\" &&\n /^(?:0|[1-9][0-9]*)$/.test(v.identity[key as keyof HostWorkspaceRootIdentity]),\n )\n )\n invalid(\"protected ownership receipt differs\");\n return Object.freeze({ ...v, identity: Object.freeze({ ...v.identity }) });\n}\n\n/** Called only for the protected provider-state envelope deserialized by the\n * server lifecycle. This receipt is evidence, not authorization: drain must\n * independently pass the current scoped lease/epoch/capture fence. */\nexport function rememberSerializedDockerOwnership(state: State, serialized: unknown): void {\n const value =\n serialized && typeof serialized === \"object\" ? Reflect.get(serialized, FIELD) : undefined;\n if (value !== undefined) {\n if (\n !serialized ||\n typeof serialized !== \"object\" ||\n Reflect.get(serialized, \"workspaceRootOwned\") !== true ||\n Reflect.get(serialized, \"containerId\") !== state.containerId ||\n Reflect.get(serialized, \"sessionIdentity\") !== state.sessionIdentity ||\n Reflect.get(serialized, \"workspaceRootPath\") !== state.workspaceRootPath\n )\n invalid(\"protected SDK producer state differs\");\n const receipt = parsedReceipt(value, state);\n if (!receipt) invalid(\"protected ownership receipt is invalid\");\n receipts.set(state, receipt);\n }\n}\n\ntype Observation = {\n id: string;\n running: boolean;\n labels: Record<string, string>;\n mounts: Array<{ Source: string; Destination: string; Type: string; RW: boolean }>;\n};\n\nasync function daemon(probe: NativeProbe): Promise<string> {\n const result = await probe([\"info\", \"--format\", \"{{.ID}}\"], 10_000);\n const id = result.stdout.trim();\n if (!/^[A-Za-z0-9:_.-]{1,200}$/.test(id) || result.stderr.trim())\n invalid(\"native daemon observation failed\");\n return id;\n}\n\nasync function observe(containerId: string, probe: NativeProbe): Promise<Observation | null> {\n try {\n const result = await probe(\n [\n \"inspect\",\n \"--type\",\n \"container\",\n \"--format\",\n '{\"id\":{{json .Id}},\"running\":{{json .State.Running}},\"labels\":{{json .Config.Labels}},\"mounts\":{{json .Mounts}}}',\n containerId,\n ],\n 10_000,\n );\n if (result.stderr.trim()) invalid(\"native container observation failed\");\n const value = JSON.parse(result.stdout) as Observation;\n if (\n value.id !== containerId ||\n typeof value.running !== \"boolean\" ||\n !value.labels ||\n !Array.isArray(value.mounts)\n )\n invalid(\"native container identity differs\");\n return value;\n } catch (error) {\n const stderr = error && typeof error === \"object\" ? Reflect.get(error, \"stderr\") : null;\n if (\n typeof stderr === \"string\" &&\n Reflect.get(error as object, \"code\") === 1 &&\n !Reflect.get(error as object, \"signal\") &&\n !Reflect.get(error as object, \"killed\") &&\n new RegExp(\n \"^(?:Error|Error response from daemon): No such (?:object|container): \" + containerId + \"$\",\n ).test(stderr.trim())\n )\n return null;\n throw error;\n }\n}\n\nasync function ownedMount(\n observation: Observation,\n state: State,\n receipt?: Ownership,\n): Promise<{ fingerprint: string; root: string }> {\n const s = shape(state);\n const fingerprint = observation.labels[\"openai-agents-sandbox.mount-authority-fingerprint\"];\n if (\n observation.labels[\"openai-agents-sandbox\"] !== \"true\" ||\n observation.labels[\"openai-agents-sandbox.session-identity\"] !== s.sessionIdentity ||\n !SHA.test(fingerprint ?? \"\") ||\n (receipt && fingerprint !== receipt.mountFingerprint)\n )\n invalid(\"native SDK mount ownership differs\");\n // The SDK records an actual canonical bind source. Preserve that authority,\n // including platform-owned aliases such as macOS /var -> /private/var;\n // content access always uses the recorded canonical source, never the alias.\n const root = await realpath(s.root);\n if (\n (receipt && root !== receipt.root) ||\n !observation.mounts.some(\n (m) =>\n m.Type === \"bind\" &&\n m.Source === root &&\n m.Destination === state.manifest.root &&\n m.RW === true,\n )\n )\n invalid(\"native SDK mount ownership differs\");\n return { fingerprint: fingerprint!, root };\n}\n\n/** Mint only for a returned SDK producer state or an authenticated exact-live\n * attachment. SDK native reuse validation checks the complete mount authority\n * fingerprint, including inode identity; names and caller shapes do not mint. */\nexport async function serializeDockerOwnership(\n client: DockerSandboxClient,\n state: State,\n probe: NativeProbe = nativeProbe,\n): Promise<Record<string, unknown>> {\n if (!ownedSdkStates.has(state)) return {};\n const s = shape(state);\n const daemonId = await daemon(probe);\n const native = await observe(s.containerId, probe);\n if (!native?.running) invalid(\"live SDK ownership could not be verified\");\n const mount = await ownedMount(native, state);\n const identity = await readHostWorkspaceRootIdentity(mount.root);\n if (!(await client.canReusePreservedOwnedSession(state)))\n invalid(\"live SDK ownership could not be verified\");\n await readHostWorkspaceRootIdentity(mount.root, identity);\n if ((await daemon(probe)) !== daemonId) invalid(\"native daemon identity changed\");\n const receipt = Object.freeze({\n version: 1 as const,\n containerId: s.containerId,\n sessionIdentity: s.sessionIdentity,\n sourceRoot: s.root,\n root: mount.root,\n daemonId,\n mountFingerprint: mount.fingerprint,\n identity,\n });\n receipts.set(state, receipt);\n return { [FIELD]: receipt };\n}\n\n/** What happened to the drained host workspace directory after exact\n * container teardown. `retained` is never an error for the drain: the archive\n * is already durably published, so the lease still goes cold. */\nexport type DockerHostWorkspaceRelease =\n | { status: \"released\" }\n | { status: \"already_released\" }\n | { status: \"retained\"; reason: string };\n\nexport type DockerWorkspaceDrainCapture = {\n state: { workspaceRootPath: string; manifest: State[\"manifest\"] };\n workspaceCaptureRootIdentity: HostWorkspaceRootIdentity;\n assertWorkspaceCaptureAuthority: () => Promise<void>;\n persistWorkspace: () => Promise<Uint8Array>;\n delete: () => Promise<void>;\n /** Set by `delete()`; null until teardown ran. */\n readonly hostWorkspaceRelease: DockerHostWorkspaceRelease | null;\n};\n\nfunction errorCode(error: unknown): unknown {\n return error && typeof error === \"object\" ? Reflect.get(error, \"code\") : undefined;\n}\n\nfunction reasonOf(error: unknown): string {\n return (error instanceof Error ? error.message : String(error)).slice(0, 300);\n}\n\n/** True only when both the recorded SDK path and its canonical receipt root\n * are definitively absent. Any other failure keeps the ordinary fence. */\nasync function rootIsAbsent(sourceRoot: string, canonicalRoot: string): Promise<boolean> {\n for (const path of [sourceRoot, canonicalRoot]) {\n try {\n await lstat(path);\n return false;\n } catch (error) {\n if (errorCode(error) !== \"ENOENT\") return false;\n }\n }\n return true;\n}\n\n/** Grants the owner u+rwx on every real descendant directory so read-only\n * trees (the Go module cache is written 0555) can be unlinked. Symlinks are\n * never followed or chmodded, and the root itself is left untouched so its\n * receipt identity (which includes the mode) still authenticates a retry. */\nasync function makeDescendantsRemovable(root: string): Promise<void> {\n const pending = [root];\n while (pending.length > 0) {\n const directory = pending.pop()!;\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const path = join(directory, entry.name);\n const stats = await lstat(path);\n if (!stats.isDirectory()) continue;\n if ((stats.mode & 0o700) !== 0o700) await grantOwnerAccess(path, stats);\n pending.push(path);\n }\n }\n}\n\n/** chmod through a no-follow directory handle pinned to the inode just\n * lstat'ed, so a path swapped for a symlink or another directory in between\n * is left alone. A directory without read permission cannot be opened; it\n * falls back to a path chmod of the same lstat'ed directory. */\nasync function grantOwnerAccess(\n path: string,\n stats: { dev: number; ino: number; mode: number },\n): Promise<void> {\n const mode = (stats.mode & 0o7777) | 0o700;\n let handle;\n try {\n handle = await open(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);\n } catch (error) {\n if (errorCode(error) !== \"EACCES\") throw error;\n await chmod(path, mode);\n return;\n }\n try {\n const pinned = await handle.stat();\n if (pinned.dev !== stats.dev || pinned.ino !== stats.ino) {\n throw new Error(`workspace directory changed during release: ${path}`);\n }\n await handle.chmod(mode);\n } finally {\n await handle.close();\n }\n}\n\nasync function removeOwnedTree(root: string): Promise<void> {\n try {\n await rm(root, { recursive: true, force: true });\n } catch (error) {\n const code = errorCode(error);\n if (code !== \"EACCES\" && code !== \"EPERM\") throw error;\n await makeDescendantsRemovable(root);\n await rm(root, { recursive: true, force: true });\n }\n}\n\n/** Capture-only attachment: no SDK resume/create, exec, viewer, hydration or\n * close capability. Its root comes from the protected SDK receipt and the\n * current scoped capture fence, never from a path/ownership flag alone. */\nexport async function attachDockerWorkspaceForDrain(\n client: DockerSandboxClient,\n state: State,\n assertCurrentCapture: () => Promise<{ archivePublished: boolean }>,\n probe: NativeProbe = nativeProbe,\n archiveLimits?: SandboxArchiveLimits | null,\n): Promise<DockerWorkspaceDrainCapture> {\n await assertCurrentCapture();\n const s = shape(state);\n let receipt = receipts.get(state);\n if (!receipt) {\n const native = await observe(s.containerId, probe);\n // Legacy stopped/missing state has no independent inode/owner receipt.\n // Preserve its data and lease; neither NotFound nor siblings grant custody.\n if (!native?.running) invalid(\"legacy stopped/missing workspace has no owned-root receipt\");\n await ownedMount(native, state);\n if (!(await client.canReusePreservedOwnedSession(state)))\n invalid(\"live SDK ownership could not be verified\");\n rememberOwnedDockerSdkState(state);\n await serializeDockerOwnership(client, state, probe);\n receipt = receipts.get(state)!;\n }\n const granted = receipt;\n if (await rootIsAbsent(s.root, granted.root)) {\n // A previous attempt of this same published drain already tore the\n // container down and released the host workspace, then died before the\n // cold commit. Only that exact state may skip the root fence: the archive\n // is durably published (so no re-arm or continuity can claim this root),\n // the daemon is unchanged and the exact container is gone.\n const assertReleased = async () => {\n if (!(await assertCurrentCapture()).archivePublished)\n invalid(\"recorded SDK root is missing before durable publication\");\n if ((await daemon(probe)) !== granted.daemonId) invalid(\"native daemon identity changed\");\n if (await observe(s.containerId, probe))\n invalid(\"recorded SDK root is missing while its exact container exists\");\n };\n await assertReleased();\n let release: DockerHostWorkspaceRelease | null = null;\n const released = () => invalid(\"host workspace was already released after publication\");\n return {\n state: { workspaceRootPath: granted.root, manifest: state.manifest },\n workspaceCaptureRootIdentity: granted.identity,\n assertWorkspaceCaptureAuthority: async () => released(),\n persistWorkspace: async () => released(),\n async delete() {\n await assertReleased();\n release = { status: \"already_released\" };\n },\n get hostWorkspaceRelease() {\n return release;\n },\n };\n }\n const assertAuthority = async () => {\n await assertCurrentCapture();\n if ((await daemon(probe)) !== granted.daemonId) invalid(\"native daemon identity changed\");\n const native = await observe(s.containerId, probe);\n if ((await realpath(s.root)) !== granted.root) invalid(\"recorded SDK root changed\");\n if (native) await ownedMount(native, state, granted);\n await readHostWorkspaceRootIdentity(granted.root, granted.identity);\n };\n /** Best effort and never throws: the archive is already durable, and a\n * throw here would keep the lease draining with a released container. */\n const releaseHostWorkspace = async (): Promise<DockerHostWorkspaceRelease> => {\n try {\n // Re-prove every fence immediately before removal: the same published\n // capture, the same daemon, the exact container gone (nothing can write\n // or re-attach through it), and the recorded canonical root still the\n // receipt's inode/owner/mode. The cold commit that follows is\n // archive-only and never keeps docker continuity for this root.\n if (!(await assertCurrentCapture()).archivePublished)\n return {\n status: \"retained\",\n reason: \"capture is no longer durably published\",\n };\n if ((await daemon(probe)) !== granted.daemonId)\n return {\n status: \"retained\",\n reason: \"native daemon identity changed\",\n };\n if (await observe(s.containerId, probe))\n return { status: \"retained\", reason: \"exact container still exists\" };\n if ((await realpath(s.root)) !== granted.root)\n return { status: \"retained\", reason: \"recorded SDK root changed\" };\n await readHostWorkspaceRootIdentity(granted.root, granted.identity);\n await removeOwnedTree(granted.root);\n return { status: \"released\" };\n } catch (error) {\n return { status: \"retained\", reason: reasonOf(error) };\n }\n };\n let release: DockerHostWorkspaceRelease | null = null;\n await assertAuthority();\n return {\n state: { workspaceRootPath: granted.root, manifest: state.manifest },\n workspaceCaptureRootIdentity: granted.identity,\n assertWorkspaceCaptureAuthority: assertAuthority,\n async persistWorkspace() {\n await assertAuthority();\n if (process.platform !== \"linux\") {\n // Preserve the SDK's existing non-Linux archive format/limits. The\n // borrowed object remains private and exposes no execution or close.\n const borrowed = new DockerSandboxSession({\n state: { ...state, workspaceRootPath: granted.root },\n ...(archiveLimits !== undefined ? { archiveLimits } : {}),\n });\n const bytes = await borrowed.persistWorkspace();\n await assertAuthority();\n return bytes;\n }\n const archive = await captureHostWorkspaceArchive(\n granted.root,\n [...state.manifest.ephemeralPersistencePaths()],\n granted.identity,\n );\n try {\n const chunks: Uint8Array[] = [];\n for await (const chunk of archive.spool.open()) chunks.push(chunk);\n return Buffer.concat(chunks);\n } finally {\n await archive.spool.dispose();\n }\n },\n async delete() {\n if (!(await assertCurrentCapture()).archivePublished)\n invalid(\"exact capture is not durably published\");\n await assertAuthority();\n if (await observe(s.containerId, probe)) {\n // Exact-container teardown, without SDK close (which would also remove\n // unrelated volumes and skips every fence below).\n const result = await probe([\"rm\", \"-f\", s.containerId], 30_000);\n if (result.stderr.trim() || result.stdout.trim() !== s.containerId)\n invalid(\"exact-container teardown outcome is unknown\");\n }\n // Once the published capture's container is gone, nothing references\n // this host workspace: the lease can only commit cold from an archive.\n release = await releaseHostWorkspace();\n },\n get hostWorkspaceRelease() {\n return release;\n },\n };\n}\n","import { E2BSandboxClient } from \"@openai/agents-extensions/sandbox/e2b\";\nimport { CAPABILITY_DESCRIPTORS } from \"../capabilities\";\nimport { SandboxConfigError } from \"../errors\";\nimport {\n REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE,\n REPEATABLE_PORTABLE_TAR_WORKSPACE_CAPTURE,\n providerWorkspacePersistence,\n type ProviderRegistration,\n} from \"./types\";\n\nexport const e2bProvider: ProviderRegistration = {\n backend: \"e2b\",\n exactResumeMode: \"custom\",\n instanceIdFields: [\"sandboxId\"],\n workspaceCapturePolicy: (state) =>\n providerWorkspacePersistence(state) === \"snapshot\"\n ? REPEATABLE_PORTABLE_TAR_WORKSPACE_CAPTURE\n : REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE,\n descriptor: CAPABILITY_DESCRIPTORS.e2b,\n validateCredentials(settings) {\n // The underlying e2b SDK reads E2B_API_KEY from process.env; we mirror it to\n // settings so a misconfigured deployment fails fast here instead of deep in\n // the SDK at create() time.\n if (!settings.e2bApiKey) {\n throw new SandboxConfigError(\"e2b\", \"OPENGENI_E2B_API_KEY is required\");\n }\n },\n build({ settings, environment, exposedPorts }) {\n const options: NonNullable<ConstructorParameters<typeof E2BSandboxClient>[0]> = {\n env: environment,\n exposedPorts,\n };\n if (settings.e2bTemplate) options.template = settings.e2bTemplate;\n // e2b's `timeout` is in SECONDS (the SDK multiplies by 1000 internally) —\n // a different unit from Modal's `timeoutMs`.\n if (settings.e2bTimeoutSeconds) options.timeout = settings.e2bTimeoutSeconds;\n if (settings.e2bTimeoutAction) options.timeoutAction = settings.e2bTimeoutAction;\n if (settings.e2bAllowInternetAccess !== undefined) {\n options.allowInternetAccess = settings.e2bAllowInternetAccess;\n }\n if (settings.e2bAutoResume !== undefined) options.autoResume = settings.e2bAutoResume;\n if (settings.e2bWorkspacePersistence) {\n options.workspacePersistence = settings.e2bWorkspacePersistence;\n }\n return new E2BSandboxClient(options);\n },\n};\n","import {\n UnixLocalSandboxClient,\n UnixLocalSandboxSession,\n type UnixLocalSandboxClientOptions,\n type UnixLocalSandboxSessionState,\n} from \"@openai/agents/sandbox/local\";\nimport { NoopSnapshotSpec } from \"@openai/agents/sandbox\";\nimport { lstat } from \"node:fs/promises\";\nimport { isAbsolute } from \"node:path\";\nimport { CAPABILITY_DESCRIPTORS } from \"../capabilities\";\nimport { SandboxConfigError, SandboxExactResumeInstanceUnavailableError } from \"../errors\";\nimport { REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE, type ProviderRegistration } from \"./types\";\n\nfunction isMissingLocalWorkspaceError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const code = Reflect.get(error, \"code\");\n return code === \"ENOENT\" || code === \"ENOTDIR\";\n}\n\nclass OpenGeniUnixLocalSandboxClient extends UnixLocalSandboxClient {\n readonly #openGeniOptions: UnixLocalSandboxClientOptions;\n\n constructor(options: UnixLocalSandboxClientOptions = {}) {\n super(options);\n this.#openGeniOptions = options;\n }\n\n /** The SDK's ordinary resume may restore an older snapshot, including into a\n * newly-created temporary directory. Exact attachment only re-opens the live\n * workspace path and therefore never writes or creates provider state. */\n async resumeExact(\n state: UnixLocalSandboxSessionState,\n options: Parameters<UnixLocalSandboxClient[\"resume\"]>[1] = {},\n ): Promise<UnixLocalSandboxSession> {\n if (!isAbsolute(state.workspaceRootPath)) {\n throw new SandboxConfigError(\"local\", \"persisted local workspace path is invalid\");\n }\n let entry: Awaited<ReturnType<typeof lstat>>;\n try {\n entry = await lstat(state.workspaceRootPath);\n } catch (error) {\n if (isMissingLocalWorkspaceError(error)) {\n throw new SandboxExactResumeInstanceUnavailableError(\"local\", state.workspaceRootPath);\n }\n throw error;\n }\n // A workspace created by this client is a real directory. Following a\n // replacement symlink would silently rebind the persisted identity.\n if (!entry.isDirectory()) {\n throw new SandboxExactResumeInstanceUnavailableError(\"local\", state.workspaceRootPath);\n }\n const archiveLimits =\n options?.archiveLimits === undefined\n ? this.#openGeniOptions.archiveLimits\n : options.archiveLimits;\n return new UnixLocalSandboxSession({\n state,\n ...(this.#openGeniOptions.defaultShell !== undefined\n ? { defaultShell: this.#openGeniOptions.defaultShell }\n : {}),\n ...(archiveLimits !== undefined ? { archiveLimits } : {}),\n });\n }\n}\n\nexport const localProvider: ProviderRegistration = {\n backend: \"local\",\n exactResumeMode: \"custom\",\n instanceIdFields: [\"workspaceRootPath\"],\n workspaceCapturePolicy: () => REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE,\n descriptor: CAPABILITY_DESCRIPTORS.local,\n // UnixLocalSandboxClient runs in-process — no credentials, no options.\n validateCredentials() {},\n build() {\n // The durable Opengeni archive ledger owns restoration. A process-local SDK\n // snapshot is neither portable nor independently governed and can be older\n // than the still-live workspace path.\n return new OpenGeniUnixLocalSandboxClient({ snapshot: new NoopSnapshotSpec() });\n },\n};\n",null,null,"import {\n ModalImageSelector,\n ModalSandboxClient,\n type ModalSandboxSession,\n type ModalSandboxSessionState,\n} from \"@openai/agents-extensions/sandbox/modal\";\nimport { effectiveModalIdleTimeoutSeconds } from \"@opengeni/config\";\nimport type { Settings } from \"@opengeni/config\";\nimport {\n canonicalModalCheckpointProviderBinding,\n type ModalCheckpointProviderBinding,\n} from \"@opengeni/contracts\";\nimport { CAPABILITY_DESCRIPTORS } from \"../capabilities\";\nimport { SandboxChannelAService, type ChannelASession } from \"../channel-a\";\nimport { installModalCommandSession } from \"./modal-command-session\";\nimport {\n installModalSynchronousCommandCollection,\n withNativeSynchronousCommandCollection,\n} from \"../native-synchronous-collection\";\nimport { ModalCommandControl } from \"./modal-command-control\";\nimport {\n ModalCommandStartPreDispatchUnavailableError,\n ModalCommandStartNotDispatchedError,\n} from \"./modal-command-router-wire\";\nimport { createModalSessionWithLifecycle, type ModalCreateLifecycle } from \"./modal-create-session\";\nimport { isRoutingMutationOutcomeUnknownError } from \"../routing/routing-session\";\nimport type { ModalClient } from \"modal\";\nimport {\n hasModalCommandStartBoundary,\n hasModalCommandStartOutcomeUnknownBoundary,\n installModalCommandStartContext,\n installModalCommandStartRetention,\n modalCommandStartHasOwnAccessor,\n modalCommandStartOwnData,\n} from \"./modal-command-start-errors\";\nimport { ModalProcessObservationUnavailableError, SandboxConfigError } from \"../errors\";\nexport { ModalProcessObservationUnavailableError } from \"../errors\";\nimport { markTypedExecHandleLoss } from \"../exec-banner\";\nimport {\n REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE,\n providerWorkspacePersistence,\n type ProviderRegistration,\n} from \"./types\";\n\nexport type { ModalCheckpointProviderBinding } from \"@opengeni/contracts\";\n\nconst MODAL_ORPHAN_SWEEP_LIMIT = 50;\nconst OPENGENI_MODAL_SDK_VERSION = \"0.9.0\";\nconst MODAL_LIST_DIR_MAX_ENTRIES = 20_000;\n// A provider box is invisible to the lease until Modal create + manifest\n// materialization returns and the creation callback records its instance id.\n// Production baseline (2026-07-15, all 8 turn workers): 155/155 completed creates\n// finished under 10s (154 under 2.5s). Two minutes is a 12x observed-max buffer,\n// while avoiding the former 30-minute retention of boxes abandoned by a rolling\n// worker restart. The live-instance guard below remains authoritative: once a box\n// is recorded by any lease, age and missing/stale tags can never terminate it.\nconst MODAL_UNATTRIBUTED_ORPHAN_GRACE_MS = 2 * 60_000;\n\nexport type ModalSandboxAttribution = {\n leaseId: string;\n workspaceId: string;\n sandboxGroupId: string;\n};\n\nexport type LiveModalSandboxLeaseAttribution = ModalSandboxAttribution & {\n instanceId: string | null;\n liveness?: string;\n};\n\nexport type ModalOrphanSweepTermination = {\n sandboxId: string;\n reason: \"stale_attribution\" | \"unattributed\";\n tags: Record<string, string>;\n};\n\nexport type ModalOrphanSweepResult = {\n examined: number;\n terminated: ModalOrphanSweepTermination[];\n skipped: number;\n /**\n * Provider/lease reconciliation observed by this pass, judged against the\n * live-lease snapshot passed in (read before the listing). `unterminated`\n * holds orphan candidates still running after the pass (termination skipped,\n * postponed, or failed); `missingLiveLeaseInstanceIds` names live-lease\n * instances absent from the listing. Both can include a lease transition that\n * raced the listing, so a caller re-reads durable ownership before reporting\n * them. Only meaningful when `complete` (the whole app listing was read; the\n * termination budget can cut a pass short).\n */\n inventory: {\n complete: boolean;\n running: number;\n unterminated: ModalOrphanSweepTermination[];\n missingLiveLeaseInstanceIds: string[];\n };\n};\n\nexport type RevalidateModalOrphanTermination = (\n candidate: ModalOrphanSweepTermination,\n) => Promise<boolean>;\n\nexport function modalSandboxAttributionEnvironment(\n input: ModalSandboxAttribution,\n): Record<string, string> {\n return {\n OPENGENI_SANDBOX_LEASE_ID: input.leaseId,\n OPENGENI_SANDBOX_GROUP_ID: input.sandboxGroupId,\n OPENGENI_WORKSPACE_ID: input.workspaceId,\n };\n}\n\nexport function modalSandboxAttributionTags(\n input: ModalSandboxAttribution,\n): Record<string, string> {\n return {\n opengeni: \"true\",\n opengeni_lease_id: input.leaseId,\n opengeni_workspace_id: input.workspaceId,\n opengeni_sandbox_group_id: input.sandboxGroupId,\n };\n}\n\ntype MutableModalSnapshotSandbox = {\n exec?: ConstructorParameters<typeof ModalSandboxSession>[0][\"sandbox\"][\"exec\"];\n terminate?: (options?: { wait?: boolean }) => Promise<unknown>;\n detach?: () => void;\n snapshotFilesystem?: (...args: unknown[]) => Promise<unknown>;\n snapshotDirectory?: (...args: unknown[]) => Promise<unknown>;\n};\n\ntype ModalWorkspaceCaptureOptions = {\n requestId: string;\n};\n\ntype MutableModalSandboxSession = {\n close?: () => Promise<void>;\n // Pinned Agents Extensions 0.14.3 uses this synchronous adapter-local map.\n activeProcesses?: unknown;\n modal?: {\n cpClient?: ModalClient[\"cpClient\"];\n profile?: ModalClient[\"profile\"];\n logger?: ModalClient[\"logger\"];\n version?: () => string;\n sandboxes?: {\n fromId?: (sandboxId: string) => Promise<MutableModalSnapshotSandbox>;\n };\n };\n sandbox?: MutableModalSnapshotSandbox;\n state?: {\n sandboxId?: string;\n environment?: Record<string, string>;\n manifest?: { root?: string };\n workspacePersistence?: string;\n snapshotFilesystemTimeoutMs?: number;\n };\n execCommand?: ChannelASession[\"execCommand\"];\n getSynchronousCommandOutput?: ChannelASession[\"getSynchronousCommandOutput\"];\n cancelPendingExecCommand?: () => Promise<void>;\n readFile?: ChannelASession[\"readFile\"];\n listDir?: ChannelASession[\"listDir\"];\n persistWorkspace?: (options?: ModalWorkspaceCaptureOptions) => Promise<Uint8Array>;\n writeStdin?: (args: {\n sessionId: number;\n chars?: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<string>;\n};\n\nconst modalRetentionWrappedSessions = new WeakSet<object>();\nconst modalTerminationWrappedSandboxes = new WeakSet<object>();\nconst modalFilesystemRetentionWrappedSandboxes = new WeakSet<object>();\nconst modalDirectoryRetentionWrappedSandboxes = new WeakSet<object>();\nconst modalSnapshotRequestIds = new WeakMap<object, string>();\nconst modalDirectorySnapshotTimeouts = new WeakMap<object, number | undefined>();\nconst MODAL_TURN_SHELL_MARKER = \"/tmp/opengeni-turn-shell/\";\n\ntype ModalPendingExecStart = {\n sandbox: MutableModalSnapshotSandbox | null;\n cancellationRequested: boolean;\n};\n\ntype ModalExecCancellationState = {\n pending: Set<ModalPendingExecStart>;\n cancellation: Promise<void> | null;\n};\n\nfunction modalWorkspaceRelativePath(path: string, workspaceRoot: string): string {\n if (!path.startsWith(\"/\")) return path;\n const root = workspaceRoot.replace(/\\/+$/, \"\") || \"/\";\n const normalized = path.replace(/\\/+$/, \"\") || \"/\";\n if (normalized === root) return \"\";\n if (root === \"/\") return normalized.slice(1);\n if (normalized.startsWith(`${root}/`)) return normalized.slice(root.length + 1);\n throw new Error(`Modal listDir path is outside the workspace root: ${path}`);\n}\n\nfunction modalWorkspaceAbsolutePath(path: string, workspaceRoot: string): string {\n const root = workspaceRoot.replace(/\\/+$/, \"\") || \"/\";\n if (!path) return root;\n return root === \"/\" ? `/${path}` : `${root}/${path}`;\n}\n\nfunction installModalListDirCompatibility(session: MutableModalSandboxSession): void {\n if (typeof session.listDir === \"function\") return;\n const execCommand = session.execCommand;\n const writeStdin = session.writeStdin?.bind(session);\n const getOutput = session.getSynchronousCommandOutput?.bind(session);\n if (typeof execCommand !== \"function\" || typeof session.readFile !== \"function\") return;\n const workspaceRoot = session.state?.manifest?.root;\n if (!workspaceRoot) {\n throw new Error(\"Modal listDir compatibility requires a manifest workspace root\");\n }\n session.listDir = async (args, commandRunner) => {\n const absoluteResultPaths = args.path.startsWith(\"/\");\n const relativePath = modalWorkspaceRelativePath(args.path, workspaceRoot);\n // This function is the provider's listDir compatibility surface. Do not\n // pass it back into Channel A as a native accelerator or fsList() recurses\n // into this shim instead of using Modal's command data plane.\n const service = new SandboxChannelAService({\n session: {\n execCommand: execCommand.bind(session),\n ...(writeStdin ? { writeStdin } : {}),\n ...(getOutput ? { getSynchronousCommandOutput: getOutput } : {}),\n ...(session.cancelPendingExecCommand\n ? { cancelPendingExecCommand: session.cancelPendingExecCommand.bind(session) }\n : {}),\n },\n ...(commandRunner ? { commandRunner } : {}),\n workspaceRoot,\n ...(args.runAs ? { runAs: args.runAs } : {}),\n });\n const listed = await withNativeSynchronousCommandCollection(session as ChannelASession, () =>\n service.fsList({\n path: relativePath,\n depth: 1,\n maxEntries: MODAL_LIST_DIR_MAX_ENTRIES,\n includeHidden: true,\n }),\n );\n if (listed.truncated || listed.root.truncated) {\n throw new Error(\n `Modal listDir exceeded the ${MODAL_LIST_DIR_MAX_ENTRIES}-entry safety bound`,\n );\n }\n return (listed.root.children ?? []).map((entry) => ({\n name: entry.name,\n path: absoluteResultPaths\n ? modalWorkspaceAbsolutePath(entry.path, workspaceRoot)\n : entry.path,\n type: entry.type === \"file\" || entry.type === \"dir\" ? entry.type : \"other\",\n }));\n };\n}\n\nconst MODAL_EXEC_STDIN_WRITE_PATH =\n \"/modal.task_command_router.TaskCommandRouter/TaskExecStdinWrite\";\nconst MODAL_EXEC_ALREADY_COMPLETED_DETAILS =\n /^Exec has already completed; stdin is no longer accepting writes(?: \\(Error code: [A-Z0-9]+\\))?$/;\nconst MODAL_TASK_EXEC_START_ERROR_MAX_DEPTH = 8;\nconst MODAL_TASK_EXEC_START_ERROR_MAX_NODES = 64;\nconst MODAL_TASK_EXEC_START_ERROR_MAX_AGGREGATE_ERRORS = 32;\n\nfunction modalHttpStatus(value: unknown): number | null {\n if (typeof value !== \"number\" && typeof value !== \"string\") return null;\n const status = Number(value);\n return Number.isInteger(status) && status >= 100 && status <= 599 ? status : null;\n}\n\nfunction hasContradictoryModalHttpStatus(record: Record<string, unknown>): boolean {\n const keys = [\"status\", \"statusCode\", \"httpStatus\", \"httpStatusCode\"];\n const values = keys.map((key) => modalCommandStartOwnData(record, key));\n const response = modalCommandStartOwnData(record, \"response\");\n if (response && typeof response === \"object\") {\n values.push(...keys.map((key) => modalCommandStartOwnData(response, key)));\n }\n return values.some((value) => modalHttpStatus(value) !== null);\n}\n\n/**\n * Only the native client's pre-dispatch readiness gate proves Start was not\n * sent. Server-controlled gRPC/SDK status and DNS-looking details prove nothing.\n * Any retained or outcome-unknown routing boundary vetoes recovery even when\n * it contains a genuine pre-dispatch error among its causes.\n */\nexport function isModalTaskExecStartPreDispatchUnavailableError(error: unknown): boolean {\n const pending: Array<{ depth: number; value: unknown }> = [{ depth: 0, value: error }];\n const seen = new WeakSet<object>();\n let inspected = 0;\n let matchingLeaves = 0;\n\n while (pending.length > 0) {\n if (inspected >= MODAL_TASK_EXEC_START_ERROR_MAX_NODES) return false;\n const current = pending.shift()!;\n inspected += 1;\n if (!current.value || typeof current.value !== \"object\" || seen.has(current.value)) {\n return false;\n }\n if (current.depth > MODAL_TASK_EXEC_START_ERROR_MAX_DEPTH) return false;\n seen.add(current.value);\n\n let nested: unknown[];\n try {\n const record = current.value as Record<string, unknown>;\n if (\n [\n \"cause\",\n \"error\",\n \"errors\",\n \"response\",\n \"status\",\n \"statusCode\",\n \"httpStatus\",\n \"httpStatusCode\",\n ].some((key) => modalCommandStartHasOwnAccessor(record, key))\n )\n return false;\n if (isRoutingMutationOutcomeUnknownError(current.value)) return false;\n if (hasModalCommandStartBoundary(current.value, \"outcome-unknown\")) return false;\n if (current.value instanceof ModalCommandStartNotDispatchedError) return false;\n if (hasContradictoryModalHttpStatus(record)) return false;\n\n // This instance is created only by the client's readiness gate before\n // Start dispatch; an RPC's own status or details never enters this path.\n if (\n current.value instanceof ModalCommandStartPreDispatchUnavailableError ||\n hasModalCommandStartBoundary(current.value, \"pre-dispatch-unavailable\")\n ) {\n matchingLeaves += 1;\n continue;\n }\n\n nested = [];\n for (const key of [\"cause\", \"error\"] as const) {\n const value = modalCommandStartOwnData(record, key);\n if (value !== undefined) nested.push(value);\n }\n\n const errors = modalCommandStartOwnData(record, \"errors\");\n if (errors !== undefined) {\n if (\n !Array.isArray(errors) ||\n errors.length === 0 ||\n errors.length > MODAL_TASK_EXEC_START_ERROR_MAX_AGGREGATE_ERRORS\n ) {\n return false;\n }\n for (let index = 0; index < errors.length; index++)\n nested.push(modalCommandStartOwnData(errors, String(index)));\n }\n\n if (nested.length === 0) return false;\n } catch {\n return false;\n }\n\n if (current.depth >= MODAL_TASK_EXEC_START_ERROR_MAX_DEPTH) return false;\n for (const value of nested) {\n pending.push({ depth: current.depth + 1, value });\n }\n }\n\n return matchingLeaves > 0;\n}\n\n/** Any typed ambiguous Start in a bounded wrapper graph vetoes generic provider\n * retries. Its original IDs are observation authority, never replay authority. */\nexport function isModalCommandStartOutcomeUnknownError(error: unknown): boolean {\n return hasModalCommandStartOutcomeUnknownBoundary(error);\n}\n\n/**\n * Modal proves that the exact exec has already terminated with a typed\n * FAILED_PRECONDITION from its stdin-write RPC. Keep this deliberately\n * structural and exact: other FAILED_PRECONDITION errors are not process\n * lifetime authority.\n */\nexport function isModalExecAlreadyCompletedError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const record = error as {\n name?: unknown;\n path?: unknown;\n code?: unknown;\n details?: unknown;\n };\n return (\n record.name === \"ClientError\" &&\n record.path === MODAL_EXEC_STDIN_WRITE_PATH &&\n record.code === 9 &&\n typeof record.details === \"string\" &&\n MODAL_EXEC_ALREADY_COMPLETED_DETAILS.test(record.details)\n );\n}\n\nfunction assertPinnedModalSdk(session: MutableModalSandboxSession): void {\n const actualVersion = session.modal?.version?.();\n if (actualVersion !== OPENGENI_MODAL_SDK_VERSION) {\n throw new Error(\n `Opengeni Modal snapshot compatibility requires modal@${OPENGENI_MODAL_SDK_VERSION}; ` +\n `the active session reported ${actualVersion ?? \"no version\"}`,\n );\n }\n}\n\nasync function confirmModalTermination(\n terminate: (options: { wait: true }) => Promise<unknown>,\n): Promise<number> {\n // Modal 0.9 resolves terminate() once the stop request is accepted. Only\n // wait:true observes the provider's terminal result before releasing a lease.\n const exitCode = await terminate({ wait: true });\n if (typeof exitCode !== \"number\" || !Number.isInteger(exitCode)) {\n throw new Error(\"Modal termination did not confirm a terminal exit\");\n }\n return exitCode;\n}\n\nfunction installModalTerminationConfirmation(session: MutableModalSandboxSession): void {\n if (typeof session.close !== \"function\") return;\n const close = session.close.bind(session);\n session.close = async () => {\n // Hydration/cancellation may replace this handle. Install at close time,\n // retaining the SDK's ownsSandbox check and process/hook cleanup ordering.\n const sandbox = session.sandbox;\n if (!sandbox || typeof sandbox.terminate !== \"function\") {\n throw new Error(\"Modal session does not expose provider termination\");\n }\n if (!modalTerminationWrappedSandboxes.has(sandbox)) {\n const terminate = sandbox.terminate.bind(sandbox);\n sandbox.terminate = async () => confirmModalTermination(terminate);\n modalTerminationWrappedSandboxes.add(sandbox);\n }\n await close();\n };\n}\n\nfunction installModalNativeSnapshotRetention(session: MutableModalSandboxSession): void {\n const persistence = session.state?.workspacePersistence;\n if (persistence !== \"snapshot_filesystem\" && persistence !== \"snapshot_directory\") {\n return;\n }\n const sandbox = session.sandbox;\n if (!sandbox || typeof sandbox !== \"object\") {\n throw new Error(`Modal ${persistence} persistence has no active provider sandbox`);\n }\n\n if (persistence === \"snapshot_filesystem\") {\n if (modalFilesystemRetentionWrappedSandboxes.has(sandbox)) return;\n const snapshotFilesystem = sandbox.snapshotFilesystem;\n if (typeof snapshotFilesystem !== \"function\") {\n throw new Error(\"Modal snapshot_filesystem persistence is unavailable\");\n }\n // Agents Extensions 0.13.x still invokes the Modal 0.7 positional timeout\n // signature. Modal 0.9 moved timeout into an options object and changed the\n // default Image retention from indefinite to 30 days. Translate at the\n // provider boundary and retain the Image until Opengeni's artifact ledger\n // proves it unreferenced and garbage-collects its exact provider id.\n sandbox.snapshotFilesystem = async (legacyParams?: unknown) => {\n if (legacyParams !== undefined && typeof legacyParams !== \"number\") {\n throw new Error(\"Unexpected Modal snapshot_filesystem adapter call shape\");\n }\n const requestId = modalSnapshotRequestIds.get(session);\n if (!requestId) {\n throw new Error(\"Modal native workspace capture requires a durable request id\");\n }\n return await snapshotFilesystem.call(sandbox, {\n ...(legacyParams === undefined ? {} : { timeoutMs: legacyParams }),\n ttlMs: null,\n snapshotId: requestId,\n });\n };\n modalFilesystemRetentionWrappedSandboxes.add(sandbox);\n return;\n }\n\n if (modalDirectoryRetentionWrappedSandboxes.has(sandbox)) return;\n const snapshotDirectory = sandbox.snapshotDirectory;\n if (typeof snapshotDirectory !== \"function\") {\n throw new Error(\"Modal snapshot_directory persistence is unavailable\");\n }\n sandbox.snapshotDirectory = async (path?: unknown, legacyParams?: unknown) => {\n if (typeof path !== \"string\" || legacyParams !== undefined) {\n throw new Error(\"Unexpected Modal snapshot_directory adapter call shape\");\n }\n const requestId = modalSnapshotRequestIds.get(session);\n if (!requestId) {\n throw new Error(\"Modal native workspace capture requires a durable request id\");\n }\n // Own both timeout and caller id at the provider boundary. The wrapper\n // around persistWorkspace temporarily disables Agents SDK 0.14.3's second,\n // outer timeout; otherwise an old timed-out caller can later delete the same\n // idempotent Image after a recovered caller has already published it.\n const timeoutMs = modalDirectorySnapshotTimeouts.get(session);\n return await snapshotDirectory.call(sandbox, path, {\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n ttlMs: null,\n snapshotId: requestId,\n });\n };\n modalDirectoryRetentionWrappedSandboxes.add(sandbox);\n}\n\nfunction installModalExecCompletionRecovery(session: MutableModalSandboxSession): void {\n const writeStdin = session.writeStdin;\n if (typeof writeStdin !== \"function\") return;\n const observe = async (args: Parameters<typeof writeStdin>[0]) => {\n // The pinned SDK looks up this map before its first await. Check the same\n // handle synchronously, with no await before calling it: a missing entry\n // is observer-state loss, while a real command may print the exact missing\n // handle banner at ANY exit code. Never classify its output as authority.\n // An SDK shape change must fail closed rather than reintroduce that guess.\n if (!(session.activeProcesses instanceof Map)) {\n throw new ModalProcessObservationUnavailableError(args.sessionId, {\n reason: \"unsupported_handle_map\",\n });\n }\n if (!session.activeProcesses.has(args.sessionId)) {\n throw new ModalProcessObservationUnavailableError(args.sessionId, {\n reason: \"missing_handle\",\n });\n }\n return await writeStdin.call(session, args);\n };\n markTypedExecHandleLoss(session);\n session.writeStdin = async (args) => {\n try {\n return await observe(args);\n } catch (error) {\n if (\n !isModalExecAlreadyCompletedError(error) ||\n !Number.isSafeInteger(args.sessionId) ||\n args.sessionId <= 0\n ) {\n throw error;\n }\n // The process can finish between the SDK lookup and the provider stdin\n // write. An empty poll may recover its exact terminal result; never replay\n // stdin, and never turn failure to observe that result into loss proof.\n try {\n return await observe({ ...args, chars: \"\" });\n } catch (cause) {\n throw new ModalProcessObservationUnavailableError(args.sessionId, { cause });\n }\n }\n };\n}\n\nfunction installModalPendingExecCancellation(session: MutableModalSandboxSession): void {\n if (session.cancelPendingExecCommand) return;\n if (\n typeof session.execCommand !== \"function\" ||\n typeof session.sandbox?.detach !== \"function\" ||\n typeof session.modal?.sandboxes?.fromId !== \"function\" ||\n !session.state?.sandboxId\n ) {\n return;\n }\n const state: ModalExecCancellationState = {\n pending: new Set(),\n cancellation: null,\n };\n const execCommand = session.execCommand.bind(session);\n session.execCommand = async (args) => {\n const command =\n args && typeof args === \"object\" && typeof (args as { cmd?: unknown }).cmd === \"string\"\n ? (args as { cmd: string }).cmd\n : null;\n if (!command?.includes(MODAL_TURN_SHELL_MARKER)) {\n return await execCommand(args);\n }\n\n // A yielded ContainerProcess owns its command-router connection. Give each\n // turn-owned start a separate handle so aborting a stuck TaskExecStart can\n // never break stdin/control for an older, already-yielded command.\n const pending: ModalPendingExecStart = {\n sandbox: null,\n cancellationRequested: false,\n };\n state.pending.add(pending);\n try {\n const sandbox = await session.modal!.sandboxes!.fromId!(session.state!.sandboxId!);\n pending.sandbox = sandbox;\n if (pending.cancellationRequested) {\n sandbox.detach?.();\n throw new Error(\"Modal exec start was cancelled before provider yield\");\n }\n session.sandbox = sandbox;\n return await execCommand(args);\n } finally {\n state.pending.delete(pending);\n }\n };\n\n session.cancelPendingExecCommand = async () => {\n if (!state.cancellation) {\n state.cancellation = (async () => {\n const pendingStarts = [...state.pending];\n const detached = new Set<MutableModalSnapshotSandbox>();\n for (const start of pendingStarts) {\n start.cancellationRequested = true;\n if (start.sandbox) {\n start.sandbox.detach?.();\n detached.add(start.sandbox);\n }\n }\n // Keep the session usable for the token/PGID proof helper. Handles for\n // already-yielded commands were removed from `pending` and stay open.\n if (session.sandbox && detached.has(session.sandbox)) {\n const replacement = await session.modal!.sandboxes!.fromId!(session.state!.sandboxId!);\n if (session.sandbox && detached.has(session.sandbox)) {\n session.sandbox = replacement;\n installModalNativeSnapshotRetention(session);\n } else {\n replacement.detach?.();\n }\n }\n })().finally(() => {\n state.cancellation = null;\n });\n }\n await state.cancellation;\n };\n}\n\n/**\n * Bridge the pinned Agents Extensions Modal adapter to Modal 0.9's provider\n * contracts. The wrapper re-checks the private provider sandbox on every\n * capture because snapshot_filesystem hydration replaces that object.\n */\nexport function installOpenGeniModalSnapshotPolicy<T extends object>(session: T): T {\n const mutable = session as MutableModalSandboxSession;\n if (modalRetentionWrappedSessions.has(session)) return session;\n if (typeof mutable.persistWorkspace !== \"function\") {\n throw new Error(\"Modal session does not expose workspace persistence\");\n }\n assertPinnedModalSdk(mutable);\n if (mutable.modal) installModalCommandStartContext(mutable.modal);\n installModalTerminationConfirmation(mutable);\n installModalNativeSnapshotRetention(mutable);\n installModalExecCompletionRecovery(mutable);\n installModalPendingExecCancellation(mutable);\n installModalSynchronousCommandCollection(mutable, () => mutable.sandbox);\n installModalListDirCompatibility(mutable);\n if (\n mutable.modal?.cpClient &&\n mutable.modal.version &&\n mutable.state?.sandboxId &&\n mutable.state.manifest?.root\n ) {\n if (!mutable.modal.profile)\n throw new Error(\"Modal command control requires its original authenticated SDK profile\");\n installModalCommandSession(\n mutable,\n ModalCommandControl.forSandbox(\n {\n cpClient: mutable.modal.cpClient,\n version: mutable.modal.version.bind(mutable.modal),\n profile: mutable.modal.profile,\n ...(mutable.modal.logger ? { logger: mutable.modal.logger } : {}),\n },\n () => {\n const sandboxId = mutable.state?.sandboxId;\n if (!sandboxId) throw new Error(\"Modal session sandbox identity is unavailable\");\n return sandboxId;\n },\n mutable.state.manifest.root,\n () => mutable.state?.environment ?? {},\n ),\n );\n }\n const persistWorkspace = mutable.persistWorkspace.bind(session);\n mutable.persistWorkspace = async (options?: ModalWorkspaceCaptureOptions) => {\n assertPinnedModalSdk(mutable);\n installModalNativeSnapshotRetention(mutable);\n if (\n (mutable.state?.workspacePersistence === \"snapshot_filesystem\" ||\n mutable.state?.workspacePersistence === \"snapshot_directory\") &&\n (!options ||\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(\n options.requestId,\n ))\n ) {\n throw new Error(\"Modal native workspace capture requires a valid UUID request id\");\n }\n const nativePersistence =\n mutable.state?.workspacePersistence === \"snapshot_filesystem\" ||\n mutable.state?.workspacePersistence === \"snapshot_directory\";\n if (options && nativePersistence) {\n modalSnapshotRequestIds.set(session, options.requestId);\n }\n const directoryTimeout =\n mutable.state?.workspacePersistence === \"snapshot_directory\"\n ? mutable.state.snapshotFilesystemTimeoutMs\n : undefined;\n const directoryTimeoutWasPresent =\n mutable.state?.workspacePersistence === \"snapshot_directory\" &&\n Object.hasOwn(mutable.state, \"snapshotFilesystemTimeoutMs\");\n if (mutable.state?.workspacePersistence === \"snapshot_directory\") {\n modalDirectorySnapshotTimeouts.set(session, directoryTimeout);\n // The wrapped provider call above owns this exact timeout. Disable the\n // SDK's lossy late-result deletion race for the duration of this exclusive\n // capture, then restore the serialized session field byte-for-byte.\n delete mutable.state.snapshotFilesystemTimeoutMs;\n }\n try {\n return await persistWorkspace();\n } finally {\n modalSnapshotRequestIds.delete(session);\n if (mutable.state?.workspacePersistence === \"snapshot_directory\") {\n if (directoryTimeoutWasPresent) {\n Reflect.set(mutable.state, \"snapshotFilesystemTimeoutMs\", directoryTimeout);\n } else {\n delete mutable.state.snapshotFilesystemTimeoutMs;\n }\n modalDirectorySnapshotTimeouts.delete(session);\n }\n }\n };\n modalRetentionWrappedSessions.add(session);\n installModalCommandStartRetention(session);\n return session;\n}\n\nexport class OpenGeniModalSandboxClient extends ModalSandboxClient {\n readonly #snapshotFilesystemTimeoutMs: number | undefined;\n readonly #createOptions: NonNullable<ConstructorParameters<typeof ModalSandboxClient>[0]>;\n\n constructor(...args: ConstructorParameters<typeof ModalSandboxClient>) {\n super(...args);\n this.#snapshotFilesystemTimeoutMs = args[0]?.snapshotFilesystemTimeoutMs;\n this.#createOptions = { ...args[0] };\n }\n\n override async create(\n args?: Parameters<ModalSandboxClient[\"create\"]>[0],\n manifestOptions?: Parameters<ModalSandboxClient[\"create\"]>[1],\n ): Promise<ModalSandboxSession> {\n const session = await super.create(args, manifestOptions);\n return installOpenGeniModalSnapshotPolicy(session);\n }\n\n async createWithLifecycle(\n args: Parameters<ModalSandboxClient[\"create\"]>[0],\n lifecycle: ModalCreateLifecycle,\n ): Promise<ModalSandboxSession> {\n return await createModalSessionWithLifecycle(\n this.#createOptions,\n args,\n lifecycle,\n installOpenGeniModalSnapshotPolicy,\n );\n }\n\n override async resume(state: ModalSandboxSessionState): Promise<ModalSandboxSession> {\n // Snapshot timeout is an operator-controlled execution budget, not durable\n // provider identity. Older resume envelopes legitimately retain the value\n // that was current when the box was created; letting that stale value win\n // makes a later production increase ineffective exactly when a large\n // workspace needs it. Rebind only this operational field while preserving\n // every provider-identity and filesystem field byte-for-byte.\n const effectiveState =\n this.#snapshotFilesystemTimeoutMs === undefined ||\n state.snapshotFilesystemTimeoutMs === this.#snapshotFilesystemTimeoutMs\n ? state\n : {\n ...state,\n snapshotFilesystemTimeoutMs: this.#snapshotFilesystemTimeoutMs,\n };\n const session = await super.resume(effectiveState);\n return installOpenGeniModalSnapshotPolicy(session);\n }\n}\n\nexport const modalProvider: ProviderRegistration = {\n backend: \"modal\",\n exactResumeMode: \"ordinary\",\n instanceIdFields: [\"sandboxId\"],\n workspaceCapturePolicy(state) {\n const persistence = providerWorkspacePersistence(state);\n if (persistence === \"snapshot_filesystem\" || persistence === \"snapshot_directory\") {\n return {\n takeover: \"same_request\",\n strategy: \"configured\",\n liveInstance: \"preserved\",\n };\n }\n return REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE;\n },\n async buildImmutableImage({ settings, session, requestId, timeoutMs }) {\n const mutable = session as MutableModalSandboxSession;\n const sandboxId = mutable.state?.sandboxId;\n const sandboxes = mutable.modal?.sandboxes;\n if (!sandboxId || typeof sandboxes?.fromId !== \"function\") {\n throw new Error(\"Modal provider image build requires an exact live sandbox identity\");\n }\n const snapshotHandle = await sandboxes.fromId(sandboxId);\n try {\n if (typeof snapshotHandle.snapshotFilesystem !== \"function\") {\n throw new Error(\"Modal provider image build requires snapshotFilesystem support\");\n }\n const image = (await snapshotHandle.snapshotFilesystem({\n snapshotId: requestId,\n timeoutMs,\n ttlMs: null,\n })) as { imageId?: unknown; objectId?: unknown };\n const imageId =\n typeof image.imageId === \"string\"\n ? image.imageId\n : typeof image.objectId === \"string\"\n ? image.objectId\n : null;\n if (!imageId) {\n throw new Error(\"Modal provider image snapshot returned no immutable image id\");\n }\n const binding = await resolveModalCheckpointProviderBindingForSession(settings, session);\n return {\n provider: \"modal\",\n backend: \"modal\",\n imageId,\n imageDigest: null,\n providerBindingKey: binding.key,\n providerBinding: binding.binding,\n };\n } finally {\n snapshotHandle.detach?.();\n }\n },\n descriptor: CAPABILITY_DESCRIPTORS.modal,\n validateCredentials(settings) {\n // both-or-neither (preserves existing validation at config validateSettings).\n if (Boolean(settings.modalTokenId) !== Boolean(settings.modalTokenSecret)) {\n throw new SandboxConfigError(\n \"modal\",\n \"OPENGENI_MODAL_TOKEN_ID and OPENGENI_MODAL_TOKEN_SECRET must both be set or both omitted\",\n );\n }\n if (!settings.modalAppName) {\n throw new SandboxConfigError(\"modal\", \"OPENGENI_MODAL_APP_NAME is required\");\n }\n },\n build({ settings, environment, exposedPorts }) {\n const options: NonNullable<ConstructorParameters<typeof ModalSandboxClient>[0]> = {\n appName: settings.modalAppName,\n timeoutMs: settings.modalTimeoutSeconds * 1000,\n sandboxCreateTimeoutS: Math.ceil(settings.sandboxWarmingTimeoutMs / 1000),\n // The Agents Extensions session persists this value in its provider\n // state and passes it to persistWorkspace(). Keep it aligned with the\n // same current setting that bounds Opengeni's outer capture operation.\n snapshotFilesystemTimeoutMs: settings.sandboxSnapshotTimeoutMs,\n exposedPorts,\n env: environment,\n // A registry image's own CMD is not a sandbox keepalive contract (for\n // example, python:3.12-slim can exit immediately). Keep the provider's\n // control process alive so exec/resume remains available; Modal's hard\n // timeout and explicit Opengeni teardown still own the box lifetime.\n useSleepCmd: true,\n };\n // gap-fill (module 03 §4.1): these SDK options were previously unmapped.\n // ALWAYS pin idleTimeoutMs (sandbox-file-persistence): an UNSET idle timeout\n // lets the SDK send idleTimeoutSecs=undefined, so Modal applies its short\n // server-default idle-reap and kills an idle (between-turns) box LONG before\n // Opengeni's reaper can resume+snapshot it. effectiveModalIdleTimeoutSeconds\n // defaults this to the hard lifetime so the box survives its full warm window\n // and the reaper — not Modal's idle-reap — governs teardown (and snapshots\n // /workspace first).\n options.idleTimeoutMs = effectiveModalIdleTimeoutSeconds(settings) * 1000;\n if (settings.modalSandboxCpu !== undefined) {\n options.cpu = settings.modalSandboxCpu;\n }\n if (settings.modalSandboxMemoryMiB !== undefined) {\n options.memoryMiB = settings.modalSandboxMemoryMiB;\n }\n if (settings.modalWorkspacePersistence) {\n options.workspacePersistence = settings.modalWorkspacePersistence;\n }\n const imageSelector = resolveModalImageSelector(settings);\n if (imageSelector) {\n options.image = imageSelector;\n }\n if (settings.modalTokenId) {\n options.tokenId = settings.modalTokenId;\n }\n if (settings.modalTokenSecret) {\n options.tokenSecret = settings.modalTokenSecret;\n }\n if (settings.modalEnvironment) {\n options.environment = settings.modalEnvironment;\n }\n return new OpenGeniModalSandboxClient(options);\n },\n};\n\ntype ModalModule = typeof import(\"modal\");\ntype ModalClientLike = InstanceType<ModalModule[\"ModalClient\"]>;\n\n// --- Modal provider-native / private-registry image resolution --------------------\n//\n// OPENGENI_MODAL_IMAGE_ID is the preferred immutable provider-native path. The\n// Agents extension resolves it with ModalImageSelector.fromId and serializes the\n// actual imageId into the session state, while modalImageRef remains the logical\n// digest persisted on the Opengeni lease.\n//\n// The Agents-extension Modal backend resolves `modalImageRef` via\n// `Image.fromRegistry(tag)` with NO secret, so it can only pull PUBLIC images. To run\n// a PRIVATE image we resolve the named Modal Secret and pre-build the authenticated\n// `fromRegistry(tag, secret)` image ONCE per process, then hand the provider `build`\n// a `ModalImageSelector.fromImage(...)`. `build` is synchronous and modal is imported\n// lazily (never loaded for non-modal backends), so resolution can't happen inside\n// `build`; the worker awaits `ensureModalRegistryImage` at boot for global refs and\n\n// images are lazy, workspace-scoped definitions, so an image built by this module's\n// client is usable by the ModalSandboxClient's own client.\n\n/** Loader seam so unit tests can inject a fake modal module. */\nexport type ModalModuleLoader = () => Promise<Pick<ModalModule, \"ModalClient\">>;\n\nconst defaultModalLoader: ModalModuleLoader = () => import(\"modal\");\n\n/** Settled, synchronously-readable resolved images, keyed per config. */\nconst resolvedRegistryImages = new Map<string, unknown>();\n/** In-flight resolutions, for cross-call de-duplication. */\nconst inFlightRegistryImages = new Map<string, Promise<void>>();\nconst MODAL_AUTHENTICATED_REGISTRY_LABEL = \"LABEL io.opengeni.registry-import=authenticated\";\n\nfunction registryImageCacheKey(settings: Settings): string {\n return [\n settings.modalImageRef ?? \"\",\n settings.modalImageRegistrySecret ?? \"\",\n settings.modalEnvironment ?? \"\",\n ].join(\"|\");\n}\n\nexport async function ensureModalRegistryImage(\n settings: Settings,\n loadModal: ModalModuleLoader = defaultModalLoader,\n): Promise<void> {\n // A provider-native immutable image ID bypasses registry import entirely.\n // ModalImageSelector.fromId resolves it during sandbox creation and the\n // provider session state records that exact ID.\n if (settings.modalImageId) {\n return;\n }\n if (!settings.modalImageRegistrySecret || !settings.modalImageRef) {\n return;\n }\n const key = registryImageCacheKey(settings);\n if (resolvedRegistryImages.has(key)) {\n return;\n }\n let pending = inFlightRegistryImages.get(key);\n if (!pending) {\n pending = (async () => {\n const modal = await loadModal();\n const client = new modal.ModalClient(modalClientOptions(settings));\n // Resolve the Secret via the AUTHENTICATED client (client.secrets.fromName),\n // NOT the static `modal.Secret.fromName`, which resolves against\n // `getDefaultClient()` — i.e. the standard MODAL_TOKEN_ID/MODAL_TOKEN_SECRET env\n // or ~/.modal.toml — and so would throw \"Profile is missing token_id\" in any host\n // that supplies the token only through Opengeni settings (OPENGENI_MODAL_TOKEN_ID).\n const secret = await client.secrets.fromName(\n settings.modalImageRegistrySecret!,\n settings.modalEnvironment ? { environment: settings.modalEnvironment } : undefined,\n );\n // fromRegistry is synchronous and returns a lazy image definition. Build it\n // here with the same authenticated client that resolved the registry Secret.\n // Passing the lazy definition into ModalSandboxClient crosses a ModalClient\n // boundary and makes every sandbox creation hydrate/import it again; registry\n // auth can then be lost and failed imports become sticky image builds. A built\n // provider-native Image is immutable, reusable, and contains no registry\n // credential boundary for the sandbox client to reconstruct.\n const app = await client.apps.fromName(settings.modalAppName, {\n ...(settings.modalEnvironment ? { environment: settings.modalEnvironment } : {}),\n createIfMissing: true,\n });\n const registryImage = (forceBuild: boolean) =>\n client.images\n .fromRegistry(settings.modalImageRef!, secret)\n .dockerfileCommands([MODAL_AUTHENTICATED_REGISTRY_LABEL], {\n ...(forceBuild ? { forceBuild: true } : {}),\n });\n let builtImage;\n try {\n builtImage = await registryImage(false).build(app);\n } catch {\n // Modal memoizes registry-import failures by image definition. A\n // corrected/rotated Secret would otherwise receive the same stale\n // failed Image forever. Retry exactly once with the same deterministic\n // definition and Modal's explicit force-build bit; successful imports\n // remain cached normally on later worker starts.\n builtImage = await registryImage(true).build(app);\n }\n resolvedRegistryImages.set(key, builtImage);\n })().finally(() => {\n inFlightRegistryImages.delete(key);\n });\n inFlightRegistryImages.set(key, pending);\n }\n await pending;\n}\n\n/** The resolved private-registry image for these settings, or undefined if none. */\nfunction cachedModalRegistryImage(settings: Settings): unknown | undefined {\n if (!settings.modalImageRegistrySecret || !settings.modalImageRef) {\n return undefined;\n }\n return resolvedRegistryImages.get(registryImageCacheKey(settings));\n}\n\n/**\n * Choose the image selector for a Modal sandbox client from settings. Returns:\n * - `fromId(modalImageId)` when a provider-native immutable ID is configured;\n * - `fromImage(resolved)` when a private-registry secret is configured AND the\n * image has been resolved (ensureModalRegistryImage ran before create);\n * - `fromTag(modalImageRef)` for the public path (no secret, or cold cache — the\n * resume/attach paths never pull an image so the tag branch is harmless there);\n * - `undefined` when no image ref is set (Modal uses its default image).\n * Exported for unit tests.\n */\nexport function resolveModalImageSelector(settings: Settings): ModalImageSelector | undefined {\n if (settings.modalImageId) {\n return ModalImageSelector.fromId(settings.modalImageId);\n }\n if (!settings.modalImageRef) {\n return undefined;\n }\n const registryImage = cachedModalRegistryImage(settings);\n return registryImage\n ? ModalImageSelector.fromImage(\n registryImage as Parameters<typeof ModalImageSelector.fromImage>[0],\n )\n : ModalImageSelector.fromTag(settings.modalImageRef);\n}\n\n/** Test-only: clear the resolved/in-flight image caches. */\nexport function __resetModalRegistryImageCacheForTest(): void {\n resolvedRegistryImages.clear();\n inFlightRegistryImages.clear();\n}\n\nfunction modalClientOptions(\n settings: Settings,\n): ConstructorParameters<ModalModule[\"ModalClient\"]>[0] {\n return {\n ...(settings.modalTokenId ? { tokenId: settings.modalTokenId } : {}),\n ...(settings.modalTokenSecret ? { tokenSecret: settings.modalTokenSecret } : {}),\n ...(settings.modalEnvironment ? { environment: settings.modalEnvironment } : {}),\n };\n}\n\nasync function createModalClient(settings: Settings): Promise<ModalClientLike> {\n const modal = await import(\"modal\");\n return new modal.ModalClient(modalClientOptions(settings));\n}\n\nfunction isModalNotFoundError(error: unknown): boolean {\n const candidate = error as {\n name?: unknown;\n code?: unknown;\n };\n // The pinned Modal SDK normalizes image/sandbox NOT_FOUND and its documented\n // FAILED_PRECONDITION alias to NotFoundError. Numeric gRPC code 5 is retained\n // for narrow adapter/fake compatibility. Never classify message text: an auth,\n // workspace, DNS, or proxy error containing \"not found\" is not deletion proof.\n return candidate?.name === \"NotFoundError\" || candidate?.code === 5;\n}\n\nasync function modalCheckpointProviderBindingForClient(\n settings: Settings,\n modal: ModalClientLike,\n): Promise<ModalCheckpointProviderBinding> {\n const identity = await modal.cpClient.workspaceNameLookup({});\n const workspaceName = identity.workspaceName || identity.username;\n if (!workspaceName) {\n throw new Error(\"Modal credential resolved no workspace identity\");\n }\n const resolved = canonicalModalCheckpointProviderBinding({\n version: 1,\n serverUrl: modal.profile.serverUrl,\n workspaceName,\n // Resolve through the authenticated client, not the optional Opengeni\n // override alone. When the override is absent Modal may select a profile\n // environment; persisting \"\" would fail to fence a later profile change.\n environment: modal.environmentName(settings.modalEnvironment),\n });\n if (!resolved) {\n throw new Error(\"Modal credential resolved an invalid checkpoint provider identity\");\n }\n return resolved.binding;\n}\n\nconst modalSessionCheckpointBindings = new WeakMap<\n object,\n Promise<{ key: string; binding: ModalCheckpointProviderBinding }>\n>();\n\n/**\n * Resolve checkpoint ownership through the exact authenticated Modal client\n * embedded in the session that creates the snapshot. The field is private in\n * the pinned Agents extension, so this adapter is intentionally fail-closed:\n * an upstream shape change disables native publication instead of guessing\n * ownership from a newly-resolved ambient profile.\n */\nexport async function resolveModalCheckpointProviderBindingForSession(\n settings: Settings,\n session: unknown,\n): Promise<{ key: string; binding: ModalCheckpointProviderBinding }> {\n if (!session || typeof session !== \"object\") {\n throw new Error(\"Modal checkpoint session identity is unavailable\");\n }\n const cached = modalSessionCheckpointBindings.get(session);\n if (cached) return await cached;\n const modal = (session as { modal?: unknown }).modal as ModalClientLike | undefined;\n if (\n !modal ||\n typeof modal.cpClient?.workspaceNameLookup !== \"function\" ||\n typeof modal.profile?.serverUrl !== \"string\" ||\n typeof modal.environmentName !== \"function\"\n ) {\n throw new Error(\"Pinned Modal session no longer exposes its authenticated checkpoint identity\");\n }\n const pending = modalCheckpointProviderBindingForClient(settings, modal).then(\n (binding) => canonicalModalCheckpointProviderBinding(binding)!,\n );\n modalSessionCheckpointBindings.set(session, pending);\n try {\n return await pending;\n } catch (error) {\n modalSessionCheckpointBindings.delete(session);\n throw error;\n }\n}\n\n/** Compare a restore receipt against the exact authenticated Modal client\n * embedded in the created session. This deliberately does not resolve a second\n * ambient client: the session that will consume the snapshot is the authority. */\nexport async function modalSessionMatchesCheckpointProviderBinding(\n settings: Settings,\n session: unknown,\n expectedBindingKey: string,\n): Promise<boolean> {\n const identity = await resolveModalCheckpointProviderBindingForSession(settings, session);\n return identity.key === expectedBindingKey;\n}\n\n/** Resolve the authoritative Modal workspace behind the configured credential.\n * Snapshot ids are workspace-scoped; persisting this non-secret binding lets GC\n * reject a credential rotation that points at a different workspace instead of\n * issuing a destructive call under ambient credentials. */\nexport async function resolveModalCheckpointProviderBinding(\n settings: Settings,\n createClient: (settings: Settings) => Promise<ModalClientLike> = createModalClient,\n): Promise<{ key: string; binding: ModalCheckpointProviderBinding }> {\n const modal = await createClient(settings);\n try {\n const binding = await modalCheckpointProviderBindingForClient(settings, modal);\n return canonicalModalCheckpointProviderBinding(binding)!;\n } finally {\n modal.close();\n }\n}\n\n/** Positive discovery only. A missing/expired provider listing never proves\n * that a dispatched create did not happen, and never authorizes a retry. */\nexport async function findModalProviderCreateReceipt(\n settings: Settings,\n attempt: {\n operationId: string;\n providerBindingKey: string;\n appId: string;\n providerName: string;\n imageId: string | null;\n },\n createClient: (settings: Settings) => Promise<ModalClientLike> = createModalClient,\n): Promise<string | null> {\n if (\n !attempt.imageId ||\n !attempt.appId ||\n attempt.providerName !== `opengeni-create-${attempt.operationId}`\n )\n throw new Error(\"Modal create recovery requires exact persisted provider identity\");\n const modal = await createClient(settings);\n try {\n const binding = canonicalModalCheckpointProviderBinding(\n await modalCheckpointProviderBindingForClient(settings, modal),\n );\n if (binding?.key !== attempt.providerBindingKey)\n throw new Error(\"Modal create recovery refused a different authenticated namespace\");\n let beforeTimestamp: number | undefined;\n const found = new Set<string>();\n // An operation normally has one result. Bound malformed/ambiguous provider\n // inventory without treating partial pagination as a unique receipt.\n for (let page = 0; page < 16; page++) {\n const response = await modal.cpClient.sandboxList({\n appId: attempt.appId,\n environmentName: modal.environmentName(settings.modalEnvironment),\n includeFinished: true,\n tags: [{ tagName: \"opengeni_provider_create_operation_id\", tagValue: attempt.operationId }],\n ...(beforeTimestamp === undefined ? {} : { beforeTimestamp }),\n });\n if (!response.sandboxes.length) return found.size === 1 ? [...found][0]! : null;\n for (const info of response.sandboxes) {\n if (\n !info.id.startsWith(\"sb-\") ||\n info.appId !== attempt.appId ||\n info.name !== attempt.providerName ||\n info.imageId !== attempt.imageId ||\n info.tags.filter((tag) => tag.tagName === \"opengeni_provider_create_operation_id\")\n .length !== 1 ||\n !info.tags.some(\n (tag) =>\n tag.tagName === \"opengeni_provider_create_operation_id\" &&\n tag.tagValue === attempt.operationId,\n )\n )\n throw new Error(\"Modal create discovery returned inconsistent operation identity\");\n found.add(info.id);\n if (found.size > 1) throw new Error(\"Modal create discovery is ambiguous; preserve fence\");\n }\n const oldest = Math.min(...response.sandboxes.map((info) => info.createdAt));\n if (\n !Number.isFinite(oldest) ||\n oldest <= 0 ||\n (beforeTimestamp !== undefined && oldest >= beforeTimestamp)\n )\n throw new Error(\"Modal create discovery pagination did not advance\");\n beforeTimestamp = oldest;\n }\n throw new Error(\"Modal create discovery exceeded its bounded inventory\");\n } finally {\n modal.close();\n }\n}\n\n/** Prove a legacy lease's live sandbox is visible in the same Modal namespace\n * whose identity will own the adopted checkpoint row. */\nexport async function resolveModalCheckpointProviderBindingForLiveSandbox(\n settings: Settings,\n sandboxId: string,\n createClient: (settings: Settings) => Promise<ModalClientLike> = createModalClient,\n): Promise<{ key: string; binding: ModalCheckpointProviderBinding }> {\n if (!sandboxId) throw new Error(\"Modal live-sandbox identity requires a sandbox id\");\n const modal = await createClient(settings);\n try {\n const binding = await modalCheckpointProviderBindingForClient(settings, modal);\n const sandbox = await modal.sandboxes.fromId(sandboxId);\n const exitCode = await sandbox.poll();\n if (exitCode !== null) {\n throw new Error(`Modal sandbox ${sandboxId} is no longer running`);\n }\n return canonicalModalCheckpointProviderBinding(binding)!;\n } finally {\n modal.close();\n }\n}\n\n/**\n * Observe one exact historical Modal sandbox without consulting the current\n * lease or its (possibly successor-owned) resume envelope. This is deliberately\n * lifecycle-only: a running sandbox does not prove whether an individual\n * retained process is still running, while a terminal/missing sandbox proves\n * that none of its processes can still execute.\n */\nexport async function inspectModalSandboxLifecycle(\n settings: Settings,\n sandboxId: string,\n expectedBindingKey?: string | null,\n createClient: (settings: Settings) => Promise<ModalClientLike> = createModalClient,\n): Promise<\n | {\n status: \"running\";\n providerBindingKey: string;\n providerBinding: ModalCheckpointProviderBinding;\n }\n | {\n status: \"terminated\";\n exitCode: number;\n providerBindingKey: string;\n providerBinding: ModalCheckpointProviderBinding;\n }\n | {\n status: \"not_found\";\n providerBindingKey: string;\n providerBinding: ModalCheckpointProviderBinding;\n }\n> {\n if (!sandboxId) throw new Error(\"Modal lifecycle inspection requires a sandbox id\");\n const modal = await createClient(settings);\n try {\n const binding = canonicalModalCheckpointProviderBinding(\n await modalCheckpointProviderBindingForClient(settings, modal),\n )!;\n if (expectedBindingKey && binding.key !== expectedBindingKey) {\n throw new Error(\n \"Modal lifecycle inspection refused because the configured credential workspace changed\",\n );\n }\n try {\n const sandbox = await modal.sandboxes.fromId(sandboxId);\n const exitCode = await sandbox.poll();\n return exitCode === null\n ? {\n status: \"running\",\n providerBindingKey: binding.key,\n providerBinding: binding.binding,\n }\n : {\n status: \"terminated\",\n exitCode,\n providerBindingKey: binding.key,\n providerBinding: binding.binding,\n };\n } catch (error) {\n if (isModalNotFoundError(error)) {\n return {\n status: \"not_found\",\n providerBindingKey: binding.key,\n providerBinding: binding.binding,\n };\n }\n throw error;\n }\n } finally {\n modal.close();\n }\n}\n\nexport async function deleteModalCheckpointSnapshot(\n settings: Settings,\n expectedBindingKey: string,\n snapshotId: string,\n createClient: (settings: Settings) => Promise<ModalClientLike> = createModalClient,\n): Promise<\"deleted\" | \"not_found\"> {\n if (!snapshotId) throw new Error(\"Modal checkpoint deletion requires a snapshot id\");\n // Resolve identity and delete through the same authenticated client. A cached\n // or separately-created identity probe could approve workspace A and then\n // issue the destructive call through a rotated ambient profile for workspace B.\n const modal = await createClient(settings);\n try {\n const binding = await modalCheckpointProviderBindingForClient(settings, modal);\n const identity = canonicalModalCheckpointProviderBinding(binding)!;\n if (expectedBindingKey !== identity.key) {\n throw new Error(\n \"Modal checkpoint deletion refused because the configured credential workspace changed\",\n );\n }\n try {\n await modal.images.delete(snapshotId);\n return \"deleted\";\n } catch (error) {\n if (isModalNotFoundError(error)) return \"not_found\";\n throw error;\n }\n } finally {\n modal.close();\n }\n}\n\nexport async function tagModalSandbox(\n settings: Settings,\n sandboxId: string,\n attribution: ModalSandboxAttribution,\n): Promise<boolean> {\n if (!sandboxId) {\n return false;\n }\n const modal = await createModalClient(settings);\n try {\n const sandbox = await modal.sandboxes.fromId(sandboxId);\n await sandbox.setTags(modalSandboxAttributionTags(attribution));\n return true;\n } finally {\n modal.close();\n }\n}\n\nexport async function terminateModalSandboxById(\n settings: Settings,\n sandboxId: string,\n createClient: (settings: Settings) => Promise<ModalClientLike> = createModalClient,\n expectedProviderBindingKey?: string,\n): Promise<boolean> {\n if (!sandboxId) {\n return true;\n }\n const modal = await createClient(settings);\n try {\n if (expectedProviderBindingKey) {\n const binding = canonicalModalCheckpointProviderBinding(\n await modalCheckpointProviderBindingForClient(settings, modal),\n );\n if (binding?.key !== expectedProviderBindingKey)\n throw new Error(\"Modal create cleanup refused a different authenticated namespace\");\n }\n const sandbox = await modal.sandboxes.fromId(sandboxId);\n await confirmModalTermination(sandbox.terminate.bind(sandbox));\n return true;\n } finally {\n modal.close();\n }\n}\n\ntype ModalSandboxInfo = {\n id: string;\n createdAt?: number;\n tags?: Array<{ tagName?: string; tagValue?: string }>;\n};\n\ntype ModalCpListClient = ModalClientLike & {\n cpClient: {\n sandboxList(input: {\n appId?: string;\n beforeTimestamp?: number;\n environmentName?: string;\n includeFinished?: boolean;\n tags?: Array<{ tagName: string; tagValue: string }>;\n }): Promise<{ sandboxes?: ModalSandboxInfo[] }>;\n };\n};\n\nfunction tagsFromInfo(info: ModalSandboxInfo): Record<string, string> {\n const tags: Record<string, string> = {};\n for (const tag of info.tags ?? []) {\n if (typeof tag.tagName === \"string\" && typeof tag.tagValue === \"string\") {\n tags[tag.tagName] = tag.tagValue;\n }\n }\n return tags;\n}\n\nfunction sandboxCreatedAtMs(info: ModalSandboxInfo): number | null {\n if (\n typeof info.createdAt !== \"number\" ||\n !Number.isFinite(info.createdAt) ||\n info.createdAt <= 0\n ) {\n return null;\n }\n // Modal protobuf timestamps in this SDK are seconds as doubles.\n return info.createdAt < 10_000_000_000\n ? Math.floor(info.createdAt * 1000)\n : Math.floor(info.createdAt);\n}\n\nfunction attributionKey(\n input: Pick<ModalSandboxAttribution, \"leaseId\" | \"workspaceId\" | \"sandboxGroupId\">,\n): string {\n return `${input.workspaceId}:${input.sandboxGroupId}:${input.leaseId}`;\n}\n\n/**\n * Whether the deployment's Modal app has any unfinished sandbox: the first\n * page of exactly the listing the orphan sweep walks. When it has none, the\n * sweep has nothing to terminate or attribute, and its inventory is empty. A\n * missing app is an empty inventory, as in the sweep.\n */\nexport async function modalAppHasRunningSandboxes(\n settings: Settings,\n options: { client?: ModalClientLike } = {},\n): Promise<boolean> {\n const ownedClient = options.client ? null : await createModalClient(settings);\n const modal = (options.client ?? ownedClient)! as ModalCpListClient;\n try {\n let appId: string | undefined;\n try {\n appId = (\n await modal.apps.fromName(settings.modalAppName, {\n createIfMissing: false,\n ...(settings.modalEnvironment ? { environment: settings.modalEnvironment } : {}),\n })\n ).appId;\n } catch (error) {\n if (isModalNotFoundError(error)) return false;\n throw error;\n }\n if (!appId) return false;\n const response = await modal.cpClient.sandboxList({\n appId,\n includeFinished: false,\n ...(settings.modalEnvironment ? { environmentName: settings.modalEnvironment } : {}),\n tags: [],\n });\n return (response.sandboxes ?? []).length > 0;\n } finally {\n ownedClient?.close();\n }\n}\n\nexport async function sweepModalOrphanSandboxes(\n settings: Settings,\n liveLeases: LiveModalSandboxLeaseAttribution[],\n options: {\n now?: Date;\n maxTerminations?: number;\n unattributedGraceMs?: number;\n client?: ModalClientLike;\n /** Re-read durable ownership immediately before provider termination. A\n * false result or callback failure skips the destructive action. */\n revalidateTermination?: RevalidateModalOrphanTermination;\n } = {},\n): Promise<ModalOrphanSweepResult> {\n const nowMs = options.now?.getTime() ?? Date.now();\n const maxTerminations = options.maxTerminations ?? MODAL_ORPHAN_SWEEP_LIMIT;\n const unattributedGraceMs = options.unattributedGraceMs ?? MODAL_UNATTRIBUTED_ORPHAN_GRACE_MS;\n const liveByAttribution = new Map(liveLeases.map((lease) => [attributionKey(lease), lease]));\n // LIVE-INSTANCE GUARD: a box that any live lease's envelope points at is NEVER\n // an orphan, whatever its tags say. Tags are best-effort attribution (setTags\n // is a separate call after create and can fail or lag); the lease envelope is\n // the source of truth the turn path actually resumes by. Judging by tags alone\n // terminated a LIVE box mid-turn at exactly creation+30min (staging session\n // e644e8a8, 2026-07-06) — the box's unpushed work was unrecoverable because\n // nothing outside the reaper drain persists /workspace.\n const liveByInstanceId = new Map(\n liveLeases\n .filter((lease) => lease.instanceId)\n .map((lease) => [lease.instanceId as string, lease]),\n );\n const ownedClient = options.client ? null : await createModalClient(settings);\n const modal = (options.client ?? ownedClient)! as ModalCpListClient;\n try {\n let app: Awaited<ReturnType<typeof modal.apps.fromName>>;\n try {\n app = await modal.apps.fromName(settings.modalAppName, {\n createIfMissing: false,\n ...(settings.modalEnvironment ? { environment: settings.modalEnvironment } : {}),\n });\n } catch (error) {\n // A new deployment has no Modal app until its first sandbox is created.\n // That is an empty provider inventory, not a failed orphan sweep.\n if (isModalNotFoundError(error)) {\n return emptyModalOrphanSweepResult(liveLeases);\n }\n throw error;\n }\n const appId = app.appId;\n if (!appId) {\n return emptyModalOrphanSweepResult(liveLeases);\n }\n\n let examined = 0;\n let skipped = 0;\n const unterminated: ModalOrphanSweepTermination[] = [];\n let complete = false;\n const seenInstanceIds = new Set<string>();\n const terminated: ModalOrphanSweepTermination[] = [];\n let beforeTimestamp: number | undefined;\n while (terminated.length < maxTerminations) {\n const response = await modal.cpClient.sandboxList({\n appId,\n ...(beforeTimestamp !== undefined ? { beforeTimestamp } : {}),\n includeFinished: false,\n ...(settings.modalEnvironment ? { environmentName: settings.modalEnvironment } : {}),\n tags: [],\n });\n const sandboxes = response.sandboxes ?? [];\n if (sandboxes.length === 0) {\n complete = true;\n break;\n }\n for (const info of sandboxes) {\n examined += 1;\n if (info.id) {\n seenInstanceIds.add(info.id);\n }\n const tags = tagsFromInfo(info);\n const leaseId = tags.opengeni_lease_id;\n const workspaceId = tags.opengeni_workspace_id;\n const sandboxGroupId = tags.opengeni_sandbox_group_id;\n const liveByInstance = info.id ? liveByInstanceId.get(info.id) : undefined;\n if (liveByInstance) {\n // Live-instance guard (see above): a live lease resumes this exact box\n // by id — hard-skip it, and HEAL its attribution tags when they are\n // missing/stale so it stops looking sweep-eligible. Best-effort: a\n // failed re-tag must never fail the sweep (the guard, not the tags,\n // is what protects the box now).\n if (\n leaseId !== liveByInstance.leaseId ||\n workspaceId !== liveByInstance.workspaceId ||\n sandboxGroupId !== liveByInstance.sandboxGroupId\n ) {\n try {\n const sandbox = await modal.sandboxes.fromId(info.id);\n await sandbox.setTags(\n modalSandboxAttributionTags({\n leaseId: liveByInstance.leaseId,\n workspaceId: liveByInstance.workspaceId,\n sandboxGroupId: liveByInstance.sandboxGroupId,\n }),\n );\n } catch {\n // Tag healing is opportunistic; the instance guard already\n // protects this box on every future sweep pass.\n }\n }\n skipped += 1;\n continue;\n }\n let reason: ModalOrphanSweepTermination[\"reason\"] | null = null;\n if (leaseId && workspaceId && sandboxGroupId) {\n const live = liveByAttribution.get(\n attributionKey({ leaseId, workspaceId, sandboxGroupId }),\n );\n if (!live || (live.instanceId && live.instanceId !== info.id)) {\n reason = \"stale_attribution\";\n }\n } else {\n const createdAtMs = sandboxCreatedAtMs(info);\n if (createdAtMs !== null && nowMs - createdAtMs >= unattributedGraceMs) {\n reason = \"unattributed\";\n }\n }\n\n if (!reason) {\n skipped += 1;\n continue;\n }\n const candidate = { sandboxId: info.id, reason, tags };\n let sandbox: Awaited<ReturnType<typeof modal.sandboxes.fromId>>;\n try {\n sandbox = await modal.sandboxes.fromId(info.id);\n } catch {\n skipped += 1;\n unterminated.push(candidate);\n continue;\n }\n if (options.revalidateTermination) {\n try {\n if (!(await options.revalidateTermination(candidate))) {\n skipped += 1;\n unterminated.push(candidate);\n continue;\n }\n } catch {\n // Destructive provider cleanup fails closed when the fresh durable\n // ownership read is unavailable or otherwise inconclusive.\n skipped += 1;\n unterminated.push(candidate);\n continue;\n }\n }\n try {\n await confirmModalTermination(sandbox.terminate.bind(sandbox));\n terminated.push(candidate);\n } catch {\n skipped += 1;\n unterminated.push(candidate);\n }\n if (terminated.length >= maxTerminations) {\n break;\n }\n }\n beforeTimestamp = sandboxes[sandboxes.length - 1]?.createdAt;\n if (beforeTimestamp === undefined) {\n complete = true;\n break;\n }\n }\n return {\n examined,\n terminated,\n skipped,\n inventory: {\n complete,\n running: examined,\n unterminated,\n // The live-lease snapshot was read before the listing began, so an\n // instance id it names already existed and a complete listing of\n // running boxes contains it unless that box has stopped.\n missingLiveLeaseInstanceIds: complete\n ? liveLeases.flatMap((lease) =>\n lease.instanceId && !seenInstanceIds.has(lease.instanceId) ? [lease.instanceId] : [],\n )\n : [],\n },\n };\n } finally {\n ownedClient?.close();\n }\n}\n\nfunction emptyModalOrphanSweepResult(\n liveLeases: LiveModalSandboxLeaseAttribution[],\n): ModalOrphanSweepResult {\n return {\n examined: 0,\n terminated: [],\n skipped: 0,\n inventory: {\n complete: true,\n running: 0,\n unterminated: [],\n missingLiveLeaseInstanceIds: liveLeases.flatMap((lease) =>\n lease.instanceId ? [lease.instanceId] : [],\n ),\n },\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { truncateOutput } from \"@openai/agents-core/sandbox/internal\";\nimport type { ChannelASession } from \"../channel-a\";\nimport {\n aliasNativeSynchronousCommandOutput,\n retainSynchronousTerminalProviderPage,\n synchronousTerminalProviderPage,\n} from \"../native-synchronous-collection\";\nimport { ModalProcessObservationUnavailableError } from \"../errors\";\nimport { classifyProviderSandboxFailure } from \"../provider-errors\";\nimport { markTypedExecHandleLoss, parseExecResponseBanner } from \"../exec-banner\";\nimport {\n MAX_PROVIDER_COMMAND_HANDLE,\n type ProviderCommandOutput,\n type ProviderCommandPersistence,\n type ProviderCommandSession,\n admittedProviderCommandHandle,\n ProviderCommandStartOutcomeUnknownError,\n ProviderCommandInputOutcomeUnknownError,\n} from \"../provider-command-session\";\nimport type { ModalCommandControl, ModalProviderCommand } from \"./modal-command-control\";\nimport { verifyModalMaterializedPath } from \"./modal-materialization-verification\";\n\ntype Entry = {\n command: ModalProviderCommand;\n persistence?: ProviderCommandPersistence;\n};\n\nfunction sameExecution(a: ModalProviderCommand, b: ModalProviderCommand): boolean {\n return (\n a.kind === b.kind &&\n a.sandboxId === b.sandboxId &&\n a.taskId === b.taskId &&\n a.execId === b.execId &&\n isDeepStrictEqual(\n \"supervision\" in a ? a.supervision : undefined,\n \"supervision\" in b ? b.supervision : undefined,\n ) &&\n Boolean(a.pty) === Boolean(b.pty)\n );\n}\n\n/** Bridges the SDK's numeric/banner surface to provider-owned execution\n * locators. The local maps are only caches: a fresh adapter can adopt the same\n * handle from protected persistence and replay any unacknowledged page. */\nexport function installModalCommandSession(\n session: ProviderCommandSession & {\n execCommand?: ChannelASession[\"execCommand\"];\n writeStdin?: ChannelASession[\"writeStdin\"];\n verifyMaterializedPath?: (path: string, workdir: string) => Promise<void>;\n verifyExecReadiness?: (signal: AbortSignal) => Promise<number>;\n },\n control: Pick<ModalCommandControl, \"start\" | \"read\" | \"readProbe\" | \"write\"> &\n Partial<\n Pick<\n ModalCommandControl,\n \"supervisionControl\" | \"verifySupervisionCapability\" | \"verifyExecReadiness\"\n >\n >,\n): void {\n markTypedExecHandleLoss(session);\n const originalExec = session.execCommand?.bind(session);\n const originalWrite = session.writeStdin?.bind(session);\n const cancelLegacyStart = session.cancelPendingExecCommand?.bind(session);\n const pendingStarts = new Set<AbortController>();\n if (control.verifyExecReadiness) {\n const verify = control.verifyExecReadiness.bind(control);\n session.verifyExecReadiness = async (signal: AbortSignal) => {\n const cancellation = new AbortController();\n const abort = () => cancellation.abort(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n if (signal.aborted) abort();\n pendingStarts.add(cancellation);\n try {\n const exit = await verify(cancellation.signal);\n cancellation.signal.throwIfAborted();\n return exit;\n } finally {\n signal.removeEventListener(\"abort\", abort);\n pendingStarts.delete(cancellation);\n }\n };\n }\n session.verifyCommandSupervisionCapability = async () => {\n if (!control.verifySupervisionCapability)\n throw new Error(\"Modal instance lacks supervised command capability verification\");\n return await control.verifySupervisionCapability();\n };\n session.verifyMaterializedPath = (path, workdir) =>\n verifyModalMaterializedPath(control, path, workdir, pendingStarts);\n const entries = new Map<number, Entry>();\n // Current SDK setup commands are not retained/admitted commands. Give their\n // live observer handles a disjoint, adapter-local range; never use a missing\n // retained alias as permission to poll an unrelated SDK process with that id.\n const setupHandles = new Map<number, number>();\n let nextSetupHandle = MAX_PROVIDER_COMMAND_HANDLE + 1;\n const receipts = new Map<string, { handle: number; page: ProviderCommandOutput }>();\n const atomicallyCaptured = new WeakSet<ProviderCommandOutput>();\n\n const supervise = async (entry: Entry, release = false): Promise<void> => {\n if (entry.command.kind !== \"modal-router-v1\" || !entry.command.supervision) return;\n const persistence = entry.persistence;\n if (\n !persistence?.recordSupervisionReceipt ||\n !persistence.loadSupervisionReceipt ||\n !persistence.cancellationRequested ||\n !control.supervisionControl\n )\n throw new Error(\"Supervised command requires durable control persistence\");\n let receipt = await persistence.loadSupervisionReceipt();\n if (!receipt) {\n const action = (await persistence.cancellationRequested())\n ? \"cancel\"\n : release\n ? \"release\"\n : \"status\";\n const observation = await control.supervisionControl(entry.command, action);\n receipt = observation.receipt ?? null;\n if (receipt) await persistence.recordSupervisionReceipt(receipt);\n }\n if (receipt) {\n // Lost ACK responses are safe to retry. A dead control socket is not\n // terminal proof: the subsequent authenticated provider read still must\n // prove exit and commit every output byte.\n await control\n .supervisionControl(entry.command, \"ack\", receipt.receiptId)\n .catch(() => undefined);\n }\n };\n\n const captureRouterPage = async (entry: Entry, page: ProviderCommandOutput): Promise<boolean> => {\n if (\n page.command.kind !== \"modal-router-v1\" ||\n !page.expected ||\n !entry.persistence?.captureRouterPage\n )\n throw new Error(\"Modal byte-offset output requires atomic retained capture\");\n const result = await entry.persistence.captureRouterPage({\n expected: page.expected,\n command: page.command,\n stdout: page.chunks\n .filter((chunk) => chunk.stream === \"stdout\")\n .map((chunk) => chunk.text)\n .join(\"\"),\n stderr: page.chunks\n .filter((chunk) => chunk.stream === \"stderr\")\n .map((chunk) => chunk.text)\n .join(\"\"),\n });\n if (!sameExecution(entry.command, result.command))\n throw new Error(\"Modal output capture changed execution identity\");\n entry.command = result.command;\n if (result.captured) atomicallyCaptured.add(page);\n return result.captured;\n };\n\n const setupPage = (raw: string, handle: number, sdkHandle: number): string => {\n const banner = parseExecResponseBanner(raw);\n if (banner.kind === \"exited\") {\n setupHandles.delete(handle);\n return raw;\n }\n if (banner.kind !== \"running\" || banner.sessionId !== sdkHandle)\n throw new ModalProcessObservationUnavailableError(handle);\n // The parser validated the unique status in the metadata header, before\n // command-controlled Output. Replace only that first trusted status line.\n const aliased = raw.replace(\n /^Process running with session ID \\d+(?=\\r?$)/mu,\n `Process running with session ID ${handle}`,\n );\n aliasNativeSynchronousCommandOutput(session, raw, aliased, handle);\n return aliased;\n };\n\n const formatPage = (\n handle: number,\n page: ProviderCommandOutput,\n maxOutputTokens?: number,\n ): string => {\n const result = [\n `Provider output receipt: ${randomUUID()}`,\n page.exitCode === null\n ? `Process running with session ID ${handle}`\n : `Process exited with code ${page.exitCode}`,\n \"Output:\",\n truncateOutput(page.chunks.map((chunk) => chunk.text).join(\"\"), maxOutputTokens).text,\n ].join(\"\\n\");\n if (page.exitCode === null || entries.get(handle)?.persistence) {\n receipts.set(result, { handle, page });\n } else {\n retainSynchronousTerminalProviderPage(session, result, page);\n entries.delete(handle);\n }\n return result;\n };\n const read = async (\n handle: number,\n entry: Entry,\n yieldTimeMs: number,\n maxOutputTokens?: number,\n signal?: AbortSignal,\n ): Promise<string> => {\n if (entry.persistence) {\n const retained = await entry.persistence.load();\n if (!retained || !sameExecution(entry.command, retained))\n throw new Error(\"Original Modal command identity is unavailable\");\n entry.command = retained;\n // Output observation stays available when control/proof persistence is\n // unavailable. Terminal exposure below remains fenced by durable proof.\n await supervise(entry).catch(() => undefined);\n }\n let page = await control.read(entry.command, yieldTimeMs, signal);\n if (entry.persistence && page.command.kind === \"modal-router-v1\") {\n // A stale concurrent observer must reread from the committed cursor before\n // exposing a terminal receipt; its uncommitted tail is not settlement proof.\n let captured = false;\n for (let attempt = 0; attempt < 3; attempt++) {\n if (await captureRouterPage(entry, page)) {\n captured = true;\n break;\n }\n if (attempt < 2) page = await control.read(entry.command, yieldTimeMs, signal);\n }\n if (!captured) throw new Error(\"Modal command output cursor changed during bounded capture\");\n }\n if (page.command.kind === \"modal-router-v1\" && page.command.supervision) {\n const receipt = await entry.persistence?.loadSupervisionReceipt?.();\n // The supervisor exits 0 after ACK; that is provider terminal evidence,\n // not the original shell result. Retain both without conflating them.\n page = { ...page, exitCode: receipt && page.exitCode === 0 ? receipt.leaderExitCode : null };\n }\n // The receipt is generated here, not parsed from command output. Its only\n // purpose is correlating this return value with a trusted in-memory page.\n return formatPage(handle, page, maxOutputTokens);\n };\n\n session.execCommand = async (args) => {\n const handle = admittedProviderCommandHandle();\n // Setup/readiness may yield too. Retain only its original local observer,\n // without publishing a durable locator or replaying its command.\n if (handle === undefined) {\n if (!originalExec) throw new Error(\"Modal command requires mutation admission\");\n if (!Number.isSafeInteger(nextSetupHandle)) throw new Error(\"Modal setup handles exhausted\");\n const setupHandle = nextSetupHandle++;\n const raw = await originalExec(args);\n const banner = parseExecResponseBanner(raw);\n if (banner.kind !== \"running\") return raw;\n setupHandles.set(setupHandle, banner.sessionId);\n return setupPage(raw, setupHandle, banner.sessionId);\n }\n if (entries.has(handle)) throw new Error(\"Modal command handle is already bound\");\n const cancellation = new AbortController();\n pendingStarts.add(cancellation);\n try {\n const command = await control.start(args, cancellation.signal);\n // Pre-dispatch reservation can already bind protected persistence.\n const entry = entries.get(handle) ?? { command };\n if (!sameExecution(entry.command, command))\n throw new Error(\"Reserved Modal command changed during dispatch\");\n entries.set(handle, entry);\n if (entry.command.kind === \"modal-router-v1\" && entry.command.supervision) {\n // The launch cannot run user code until the routing layer commits\n // initial retention and calls releaseSupervisedCommand.\n return formatPage(handle, { command: entry.command, chunks: [], exitCode: null });\n }\n try {\n return await read(\n handle,\n entry,\n args.yieldTimeMs ?? 10000,\n args.maxOutputTokens,\n cancellation.signal,\n );\n } catch {\n // Start succeeded. A failed/cancelled first observation must still\n // publish the known locator for durable retention and exact cleanup.\n return formatPage(handle, {\n command: entry.command,\n chunks: [],\n exitCode: null,\n });\n }\n } catch (error) {\n if (error instanceof ProviderCommandStartOutcomeUnknownError) {\n const entry = entries.get(handle);\n if (entry && !sameExecution(entry.command, error.command))\n throw new Error(\"Reserved Modal command changed during failed dispatch\", {\n cause: error,\n });\n entries.set(handle, entry ?? { command: error.command });\n }\n throw error;\n } finally {\n pendingStarts.delete(cancellation);\n }\n };\n\n session.cancelPendingExecCommand = async () => {\n for (const start of pendingStarts)\n start.abort(\n new Error(\"Modal command start observation cancelled; provider outcome is unknown\"),\n );\n // SDK-internal foreground commands retain their separate legacy transport\n // cancellation. Neither path closes an already-yielded command's locator.\n await cancelLegacyStart?.();\n };\n\n session.getProviderCommand = (handle) => {\n const entry = entries.get(handle);\n return entry ? structuredClone(entry.command) : null;\n };\n session.releaseSupervisedCommand = async (handle) => {\n const entry = entries.get(handle);\n if (!entry || entry.command.kind !== \"modal-router-v1\" || !entry.command.supervision) return;\n const retained = await entry.persistence?.load();\n if (!retained || !sameExecution(entry.command, retained))\n throw new Error(\"Supervisor release requires committed initial retention\");\n entry.command = retained;\n await supervise(entry, true);\n };\n session.cancelSupervisedCommand = async (handle, reason) => {\n const entry = entries.get(handle);\n if (!entry || entry.command.kind !== \"modal-router-v1\" || !entry.command.supervision)\n return false;\n if (!entry.persistence?.requestCancellation)\n throw new Error(\"Supervisor cancellation requires durable intent\");\n await entry.persistence.requestCancellation(reason);\n await supervise(entry);\n return true;\n };\n session.bindProviderCommand = (handle, command, persistence) => {\n if (!Number.isSafeInteger(handle) || handle <= 0 || handle > MAX_PROVIDER_COMMAND_HANDLE)\n throw new Error(\"Invalid retained Modal command handle\");\n const existing = entries.get(handle);\n if (existing && !sameExecution(existing.command, command))\n throw new Error(\"Modal command handle cannot be rebound to another execution\");\n entries.set(handle, { command: structuredClone(command), persistence });\n };\n session.getProviderCommandOutput = (result) =>\n typeof result === \"string\"\n ? (receipts.get(result)?.page ?? synchronousTerminalProviderPage(session, result))\n : null;\n session.captureCommandOutput = async (result) => {\n const receipt = receipts.get(result);\n if (!receipt || receipt.page.command.kind !== \"modal-router-v1\") return false;\n if (\n !receipt.page.expected &&\n receipt.page.exitCode === null &&\n receipt.page.chunks.length === 0\n ) {\n // Both a supervised idle launch and an unavailable first observation\n // carry identity only. Retention already owns this command; there are\n // no observed bytes or terminal evidence to ACK.\n receipts.delete(result);\n return true;\n }\n if (atomicallyCaptured.has(receipt.page)) {\n receipts.delete(result);\n return true;\n }\n const entry = entries.get(receipt.handle);\n if (!entry?.persistence?.captureRouterPage || !receipt.page.expected)\n throw new Error(\"Modal byte-offset output requires atomic retained capture\");\n if (!(await captureRouterPage(entry, receipt.page))) {\n const target = receipt.page.command;\n const covered = () =>\n entry.command.kind === \"modal-router-v1\" &&\n ([\"stdout\", \"stderr\"] as const).every((stream) => {\n const current = entry.command.streams[stream];\n // This narrowing stays inside the discriminator's synchronous scope.\n if (!(\"byteOffset\" in current)) return false;\n const wanted = target.streams[stream];\n return (\n current.byteOffset >= wanted.byteOffset &&\n (!wanted.eof || current.eof) &&\n (wanted.exitCode === null || current.exitCode === wanted.exitCode)\n );\n });\n for (let attempt = 0; !covered() && attempt < 3; attempt++) {\n // Initial promotion can race reconciliation before background adoption.\n // Re-read, never re-execute; only a committed cursor covering the original\n // page makes that page's terminal proof eligible for settlement.\n const refreshedReceipt = await read(receipt.handle, entry, 250);\n const refreshed = receipts.get(refreshedReceipt);\n if (refreshed && atomicallyCaptured.has(refreshed.page)) receipts.delete(refreshedReceipt);\n }\n if (!covered())\n throw new Error(\"Initial Modal output tail remains uncommitted after bounded capture\");\n }\n receipts.delete(result);\n return true;\n };\n session.acknowledgeCommandOutput = async (result) => {\n const receipt = receipts.get(result);\n if (!receipt) return;\n const entry = entries.get(receipt.handle);\n if (!entry?.persistence)\n throw new Error(\"Modal output cannot advance before durable command retention\");\n const saved = await entry.persistence.acknowledge(receipt.page.command);\n if (!sameExecution(entry.command, saved))\n throw new Error(\"Modal output acknowledgment changed execution identity\");\n entry.command = saved;\n receipts.delete(result);\n };\n session.writeStdin = async (args) => {\n const sdkHandle = setupHandles.get(args.sessionId);\n if (sdkHandle !== undefined && originalWrite) {\n const raw = await originalWrite({ ...args, sessionId: sdkHandle });\n return setupPage(raw, args.sessionId, sdkHandle);\n }\n const entry = entries.get(args.sessionId);\n if (!entry?.persistence)\n throw new ModalProcessObservationUnavailableError(args.sessionId, {\n reason: \"missing_handle\",\n });\n if (args.chars) {\n const retained = await entry.persistence.load();\n if (!retained || !sameExecution(entry.command, retained))\n throw new Error(\"Original Modal command identity is unavailable\");\n const index = await entry.persistence.reserveInput(Buffer.byteLength(args.chars));\n try {\n await control.write(retained, args.chars, index);\n } catch (error) {\n // Native gRPC transport failure does not establish whether this reserved\n // range reached stdin. Never resend it or recommend another input write.\n if (\n retained.kind === \"modal-router-v1\" &&\n // Contain supported transport graphs, including mixed failures. This\n // grants no read/write retry permission; the locator and byte range\n // come only from the retained command and its one input reservation.\n classifyProviderSandboxFailure(\"modal\", error).kind === \"transient_transport\"\n )\n throw new ProviderCommandInputOutcomeUnknownError(\n retained,\n index,\n Buffer.byteLength(args.chars),\n error,\n );\n throw error;\n }\n }\n return read(args.sessionId, entry, args.yieldTimeMs ?? 250, args.maxOutputTokens, args.signal);\n };\n}\n","/**\n * Provider sandbox failure classification.\n *\n * This is deliberately structural and fail-closed. DNS failures often contain\n * the word \"not found\" (`ENOTFOUND`) while gRPC status values are also used by\n * unrelated SDKs and command routers. A bare numeric status (including gRPC's\n * numeric 5) is therefore not enough to retire a provider instance. Only\n * authoritative, non-transient evidence may retire a provider instance and\n * license lease recovery.\n */\nexport type ProviderSandboxFailureKind = \"not_found\" | \"transient_transport\" | \"other\";\n\nexport type ProviderSandboxFailure = {\n kind: ProviderSandboxFailureKind;\n /** Bounded, non-secret diagnostic suitable for logs and lifecycle events. */\n diagnostic: string;\n};\n\nconst GRPC_TRANSIENT = new Set([1, 2, 4, 13, 14]);\nconst TRANSIENT_CODES = new Set([\n \"1\",\n \"2\",\n \"4\",\n \"13\",\n \"14\",\n \"CANCELLED\",\n \"UNKNOWN\",\n \"DEADLINE_EXCEEDED\",\n \"INTERNAL\",\n \"UNAVAILABLE\",\n \"ECONNRESET\",\n \"ECONNREFUSED\",\n \"ETIMEDOUT\",\n \"EAI_AGAIN\",\n \"ENOTFOUND\",\n]);\nconst NOT_FOUND_CODES = new Set([\"404\", \"NOT_FOUND\", \"RESOURCE_NOT_FOUND\", \"SANDBOX_NOT_FOUND\"]);\nconst SAFE_CODE = /^[A-Z0-9._:-]{1,64}$/;\n\ntype ErrorSignals = {\n numbers: number[];\n codes: string[];\n messages: string[];\n incomplete: boolean;\n};\n\nconst UNREADABLE_ERROR_SIGNAL = Symbol(\"unreadable-error-signal\");\n\nfunction safeRead(record: object, key: string): unknown {\n try {\n const descriptor = Object.getOwnPropertyDescriptor(record, key);\n return descriptor\n ? \"value\" in descriptor\n ? descriptor.value\n : UNREADABLE_ERROR_SIGNAL\n : undefined;\n } catch {\n return UNREADABLE_ERROR_SIGNAL;\n }\n}\n\nfunction collectSignals(value: unknown): ErrorSignals {\n const out: ErrorSignals = { numbers: [], codes: [], messages: [], incomplete: false };\n const seen = new Set<object>();\n const read = (record: object, key: string): unknown => {\n const signal = safeRead(record, key);\n if (signal !== UNREADABLE_ERROR_SIGNAL) return signal;\n out.incomplete = true;\n return undefined;\n };\n const visit = (current: unknown, depth: number): void => {\n if (current === null || current === undefined) return;\n if (depth > 6 || seen.size >= 64) {\n out.incomplete = true;\n return;\n }\n if (typeof current === \"string\") {\n if (current.length <= 512) out.messages.push(current);\n return;\n }\n if (typeof current !== \"object\" || seen.has(current)) return;\n seen.add(current);\n for (const key of [\n \"status\",\n \"statusCode\",\n \"httpStatus\",\n \"httpStatusCode\",\n \"responseStatus\",\n \"errorCode\",\n \"code\",\n ]) {\n const signal = read(current, key);\n if (typeof signal === \"number\" && Number.isFinite(signal)) out.numbers.push(signal);\n if (typeof signal === \"string\") {\n const code = signal.trim().toUpperCase();\n if (SAFE_CODE.test(code)) out.codes.push(code);\n }\n }\n for (const key of [\"name\", \"message\", \"details\", \"cause\"]) {\n const signal = read(current, key);\n if (typeof signal === \"string\" && signal.length <= 512) out.messages.push(signal);\n else visit(signal, depth + 1);\n }\n visit(read(current, \"response\"), depth + 1);\n visit(read(current, \"error\"), depth + 1);\n const errors = read(current, \"errors\");\n if (errors !== undefined) {\n if (!Array.isArray(errors) || !errors.length || errors.length > 16) out.incomplete = true;\n else\n for (let index = 0; index < errors.length; index++) {\n const nested = read(errors, String(index));\n if (!nested || typeof nested !== \"object\") out.incomplete = true;\n visit(nested, depth + 1);\n }\n }\n };\n visit(value, 0);\n return out;\n}\n\nfunction safeDiagnostic(signals: ErrorSignals): string {\n const code = signals.codes.find(Boolean);\n const numeric = signals.numbers.find((value) => Number.isFinite(value));\n return [code ? `code=${code}` : \"\", numeric !== undefined ? `status=${numeric}` : \"\"]\n .filter(Boolean)\n .join(\" \");\n}\n\nfunction hasTransientSignal(signals: ErrorSignals): boolean {\n return (\n signals.codes.some((code) => TRANSIENT_CODES.has(code)) ||\n signals.numbers.some((status) => GRPC_TRANSIENT.has(status))\n );\n}\n\nfunction hasModalTerminalSandboxMessage(signals: ErrorSignals): boolean {\n return signals.messages.some(\n (message) =>\n /^Modal sandbox [A-Za-z0-9_-]+ is no longer running\\.$/.test(message) ||\n /^Modal sandbox [A-Za-z0-9_-]+ not found \\(has been terminated\\)$/.test(message),\n );\n}\n\nfunction hasUnixLocalTerminalWorkspaceMessage(signals: ErrorSignals): boolean {\n return signals.messages.includes(\n \"UnixLocal sandbox workspace is unavailable and no local snapshot could be restored.\",\n );\n}\n\nfunction hasDockerTerminalWorkspaceMessage(signals: ErrorSignals): boolean {\n return signals.messages.includes(\n \"Docker sandbox resources are unavailable and no local snapshot could be restored.\",\n );\n}\n\nfunction hasCloudflareTerminalSandboxMessage(signals: ErrorSignals): boolean {\n return signals.messages.some((message) =>\n /^Cloudflare sandbox [A-Za-z0-9._:-]+ is no longer running\\.$/.test(message),\n );\n}\n\n/** Typed transport evidence always dominates nested/string NotFound text. */\nexport function classifyProviderSandboxFailure(\n backendId: string,\n error: unknown,\n): ProviderSandboxFailure {\n if (backendId === \"selfhosted\" || !error) {\n return { kind: \"other\", diagnostic: \"selfhosted-or-empty\" };\n }\n const signals = collectSignals(error);\n const diagnostic = safeDiagnostic(signals) || \"unclassified_provider_failure\";\n\n if (hasTransientSignal(signals)) {\n return { kind: \"transient_transport\", diagnostic };\n }\n if (signals.incomplete) return { kind: \"other\", diagnostic };\n if (\n signals.numbers.some((status) => status === 404) ||\n signals.codes.some((code) => NOT_FOUND_CODES.has(code))\n ) {\n return { kind: \"not_found\", diagnostic };\n }\n\n // Modal's SDK emits these exact terminal grammars after resolving one exact\n // sandbox id. Generic \"not found\" prose is intentionally not authoritative.\n if (backendId === \"modal\" && hasModalTerminalSandboxMessage(signals)) {\n return {\n kind: \"not_found\",\n diagnostic:\n diagnostic === \"unclassified_provider_failure\"\n ? \"modal_terminal_message\"\n : `${diagnostic} modal_terminal_message`,\n };\n }\n\n // Cloudflare's resume() performs its sandbox-scoped running probe itself and\n // emits this exact UserError only after that probe returns false. It carries\n // no HTTP/code field, so omitting the provider grammar would strand a dead\n // lease in warm/draining forever. Arbitrary Cloudflare path 404s do not match.\n if (backendId === \"cloudflare\" && hasCloudflareTerminalSandboxMessage(signals)) {\n return {\n kind: \"not_found\",\n diagnostic:\n diagnostic === \"unclassified_provider_failure\"\n ? \"cloudflare_terminal_message\"\n : `${diagnostic} cloudflare_terminal_message`,\n };\n }\n\n // The SDK emits this exact UserError only after resolving one serialized\n // unix_local session and proving that both its process-local workspace and\n // its persisted fallback are absent. That is authoritative provider loss:\n // on resume it licenses a fresh local workspace, and on drain it licenses\n // the lease's provider-missing cold transition. Generic \"unavailable\" prose\n // remains fail-closed.\n if (\n (backendId === \"local\" || backendId === \"unix_local\") &&\n hasUnixLocalTerminalWorkspaceMessage(signals)\n ) {\n return {\n kind: \"not_found\",\n diagnostic:\n diagnostic === \"unclassified_provider_failure\"\n ? \"unix_local_workspace_missing\"\n : `${diagnostic} unix_local_workspace_missing`,\n };\n }\n\n // Docker's ordinary resume is used only by a durable same-workspace recovery\n // owner. This exact SDK error is emitted after it has checked both the\n // serialized container and its host workspace (plus any configured local\n // snapshot) and proved that none can be resumed. Treating it as transient\n // would preserve an unusable continuity receipt forever. Routed operations\n // use the stricter discriminator below, so an arbitrary command error cannot\n // retire a live container through this message rule.\n if (backendId === \"docker\" && hasDockerTerminalWorkspaceMessage(signals)) {\n return {\n kind: \"not_found\",\n diagnostic:\n diagnostic === \"unclassified_provider_failure\"\n ? \"docker_resources_missing\"\n : `${diagnostic} docker_resources_missing`,\n };\n }\n\n return { kind: \"other\", diagnostic };\n}\n\nexport function isProviderSandboxNotFoundError(backendId: string, error: unknown): boolean {\n return classifyProviderSandboxFailure(backendId, error).kind === \"not_found\";\n}\n\n/**\n * Whether a failure from an operation routed through an already-established\n * sandbox proves that exact provider sandbox disappeared.\n *\n * Routed operations can legitimately return HTTP 404 / `NOT_FOUND` for paths,\n * files, ports, processes, and other subresources. Those generic signals are\n * sufficient for provider create/resume APIs, but they must never retire the\n * live sandbox identity after an arbitrary operation. Only an explicit\n * sandbox-scoped provider code or Modal's exact terminal sandbox grammar is\n * authoritative on this path. Transient transport evidence still dominates.\n */\nexport function isProviderSandboxGoneDuringRoutedOperation(\n backendId: string,\n error: unknown,\n): boolean {\n if (backendId === \"selfhosted\" || !error) return false;\n const signals = collectSignals(error);\n if (hasTransientSignal(signals) || signals.incomplete) return false;\n if (signals.codes.includes(\"SANDBOX_NOT_FOUND\")) return true;\n return backendId === \"modal\" && hasModalTerminalSandboxMessage(signals);\n}\n\nexport function isProviderSandboxTransientError(backendId: string, error: unknown): boolean {\n return classifyProviderSandboxFailure(backendId, error).kind === \"transient_transport\";\n}\n","import { isDeepStrictEqual } from \"node:util\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport {\n SandboxMaterializationVerificationError,\n retainMaterializationVerificationDiagnostic,\n type MaterializationVerificationDiagnostic,\n} from \"../materialization-verification-error\";\nimport type { ModalCommandControl, ModalProviderCommand } from \"./modal-command-control\";\nimport {\n ProviderCommandObservationUnavailableError,\n ProviderCommandStartOutcomeUnknownError,\n type ProviderCommandOutput,\n} from \"../provider-command-session\";\n\nconst MARKER = \"__OPENGENI_MATERIALIZED_PATH_VISIBLE__\";\nconst OUTPUT_LIMIT = 16 * 1024;\n\n/** A fixed read-only probe, not an admitted user command. Advance its private\n * provider cursor locally; never borrow the surrounding mutation's retained\n * handle or relax retained-command persistence requirements. The caller keeps\n * the original backend and provider-operation gate for the entire observation.\n */\nexport async function verifyModalMaterializedPath(\n control: Pick<ModalCommandControl, \"start\" | \"readProbe\">,\n path: string,\n workdir: string,\n pending: Set<AbortController>,\n observationTimeoutMs = 30_000,\n): Promise<void> {\n const quote = (value: string) => `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n const command = `test -e ${quote(path)} && printf %s ${quote(MARKER)}`;\n const cancellation = new AbortController();\n const deadlineReason = new Error(\"Materialization visibility observation deadline exceeded\");\n let providerCommand: ModalProviderCommand | undefined;\n let startUnknown: ProviderCommandStartOutcomeUnknownError | undefined;\n let stdout = \"\";\n let stderr = \"\";\n const diagnostic = (\n reason: MaterializationVerificationDiagnostic[\"reason\"],\n exitCode: number | null = null,\n ): MaterializationVerificationDiagnostic => ({\n reason,\n path,\n workdir,\n command,\n output: (stdout + stderr).slice(0, OUTPUT_LIMIT),\n exitCode,\n providerSessionId: null,\n ...(providerCommand\n ? {\n providerExecution: {\n sandboxId: providerCommand.sandboxId,\n taskId: providerCommand.taskId,\n execId: providerCommand.execId,\n },\n }\n : {}),\n });\n const timer = setTimeout(() => {\n cancellation.abort(deadlineReason);\n }, observationTimeoutMs);\n timer.unref();\n pending.add(cancellation);\n try {\n try {\n providerCommand = await control.start(\n { cmd: command, workdir, shell: \"sh\", login: false, tty: false },\n cancellation.signal,\n );\n } catch (error) {\n // A possibly dispatched fixed visibility probe has one original locator.\n // Observe that invocation; never replay it or the surrounding mutation.\n if (!(error instanceof ProviderCommandStartOutcomeUnknownError)) throw error;\n providerCommand = structuredClone(error.command);\n startUnknown = error;\n }\n for (;;) {\n cancellation.signal.throwIfAborted();\n let page: ProviderCommandOutput;\n try {\n page = await control.readProbe(providerCommand, 1_000, cancellation);\n } catch (error) {\n cancellation.signal.throwIfAborted();\n if (\n !(error instanceof ProviderCommandObservationUnavailableError) ||\n !error.readRetryAllowed\n ) {\n if (!startUnknown) throw error;\n // A missing/denied read cannot disprove the original Start. Preserve\n // its exact invocation without granting any further read retry.\n throw new ProviderCommandObservationUnavailableError(\n structuredClone(providerCommand),\n new AggregateError(\n [startUnknown, error],\n \"Original visibility Start and observation remain uncertain\",\n ),\n false,\n );\n }\n // Unavailable reads do not advance any cursor. A contradictory locator\n // is an invariant failure, never authority to inspect another process.\n if (!isDeepStrictEqual(error.command, providerCommand))\n throw new SandboxMaterializationVerificationError(diagnostic(\"invalid_response\"), {\n cause: error,\n });\n // Read retries remain inside this probe's original thirty-second\n // deadline, including outages longer than a single bounded read.\n try {\n await delay(100, undefined, { signal: cancellation.signal });\n } catch (interrupted) {\n cancellation.signal.throwIfAborted();\n throw interrupted;\n }\n continue;\n }\n // Cancellation ends observation, not the process. Never accept a late\n // success after the attempt requested cancellation.\n cancellation.signal.throwIfAborted();\n if (\n page.command.sandboxId !== providerCommand.sandboxId ||\n page.command.taskId !== providerCommand.taskId ||\n page.command.execId !== providerCommand.execId\n ) {\n throw new SandboxMaterializationVerificationError(diagnostic(\"invalid_response\"));\n }\n providerCommand = page.command;\n for (const chunk of page.chunks) {\n if (chunk.stream === \"stdout\") stdout += chunk.text;\n else stderr += chunk.text;\n }\n if (stdout.length + stderr.length > OUTPUT_LIMIT) {\n throw new SandboxMaterializationVerificationError(diagnostic(\"invalid_response\"));\n }\n if (page.exitCode === null) {\n // An empty provider page may return immediately. Yield to cancellation\n // and the deadline instead of starving timers with resolved promises.\n await new Promise<void>((resolve) => setImmediate(resolve));\n continue;\n }\n if (page.exitCode === 0 && stdout === MARKER) return;\n throw new SandboxMaterializationVerificationError(\n diagnostic(\n page.exitCode === 1\n ? \"path_not_visible\"\n : page.exitCode === 0\n ? \"invalid_response\"\n : \"command_failed\",\n page.exitCode,\n ),\n );\n }\n } catch (error) {\n if (cancellation.signal.reason === deadlineReason) {\n throw new SandboxMaterializationVerificationError(\n {\n ...diagnostic(\"command_pending\"),\n causeMessage: \"Observation deadline exceeded; provider process completion is unconfirmed\",\n },\n {\n cause: providerCommand\n ? new ProviderCommandObservationUnavailableError(\n providerCommand,\n startUnknown\n ? new AggregateError(\n [startUnknown, error],\n \"Original visibility Start and observation deadline remain uncertain\",\n )\n : error,\n )\n : error,\n },\n );\n }\n if (!(error instanceof SandboxMaterializationVerificationError)) {\n retainMaterializationVerificationDiagnostic(error, {\n ...diagnostic(\"command_error\"),\n causeMessage: error instanceof Error ? error.message : String(error),\n });\n }\n throw error;\n } finally {\n cancellation.abort(new Error(\"Materialization visibility observation finished\"));\n clearTimeout(timer);\n pending.delete(cancellation);\n }\n}\n","import { randomUUID, randomBytes } from \"node:crypto\";\nimport { posix } from \"node:path\";\nimport { status } from \"@grpc/grpc-js\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { modalCommandArgv } from \"./modal-command-argv\";\nimport {\n SandboxProviderCommand,\n CommandSupervisionReceipt,\n ModalRouterProviderCommand,\n} from \"@opengeni/contracts\";\nimport type { ChannelAExecArgs } from \"../channel-a\";\nimport type { ProviderCommandOutput } from \"../provider-command-session\";\nimport {\n admittedCommandSupervisionReady,\n markPendingCommandSupervised,\n reserveSupervisedLaunch,\n ProviderCommandStartOutcomeUnknownError,\n ProviderCommandObservationUnavailableError,\n} from \"../provider-command-session\";\nimport { isModalCommandObservationTransportError } from \"./modal-command-observation-errors\";\nimport { ModalCommandStartOutcomeUnknownError } from \"./modal-command-start-errors\";\nimport { classifyProviderSandboxFailure } from \"../provider-errors\";\nimport {\n ModalCommandControl as LegacyControl,\n commandControlPlane,\n} from \"./modal-legacy-command-control\";\nimport {\n ModalCommandRouterWire,\n ModalCommandStartPreDispatchUnavailableError,\n ModalCommandStartRejectedError,\n ModalCommandStartNotDispatchedError,\n} from \"./modal-command-router-wire\";\nimport { collectModalRawOutputPage, type ModalRawOutputPage } from \"./modal-command-raw-page\";\n\nexport { modalCommandAbortMiddleware } from \"./modal-legacy-command-control\";\nexport type ModalProviderCommand = SandboxProviderCommand;\nexport type ModalProviderOutputPage = ProviderCommandOutput;\n\ntype Client = Parameters<typeof commandControlPlane>[0];\ntype RouterEntry = {\n router: ModalCommandRouterWire;\n users: number;\n refreshAt: number;\n idle?: ReturnType<typeof setTimeout>;\n};\ntype RouterLookup = { controller: AbortController; waiters: number; settled: boolean };\n/** A post-EOF exit re-poll may finish this long after the read deadline. */\nconst REPOLL_GRACE_MS = 250;\ntype ControlObservation = { command: ModalRouterProviderCommand; output: string };\ntype SupervisionControlResult = {\n state: \"idle\" | \"running\" | \"quiescent\";\n receipt?: CommandSupervisionReceipt;\n};\ntype ControlHelper = ControlObservation & {\n startPending: boolean;\n startUnknown?: unknown;\n inFlight?: Promise<SupervisionControlResult>;\n};\n\n/** Cancels this waiter, not the shared provider operation. The rejection\n * handler remains attached even when an uncooperative provider settles late. */\nfunction awaitRouterAccess<T>(pending: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) return pending;\n signal.throwIfAborted();\n return new Promise<T>((resolve, reject) => {\n const abort = () => {\n signal.removeEventListener(\"abort\", abort);\n reject(signal.reason);\n };\n signal.addEventListener(\"abort\", abort, { once: true });\n void pending.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", abort));\n });\n}\n\n/** New commands use replayable task-router byte offsets. Legacy identifiers\n * never cross that protocol boundary and are never used for new starts. */\nexport class ModalCommandControl {\n private readonly routers = new Map<string, Promise<RouterEntry>>();\n private readonly routerLookups = new Map<Promise<RouterEntry>, RouterLookup>();\n private readonly controlHelpers = new Map<string, ControlHelper>();\n private readonly client: ReturnType<typeof commandControlPlane>;\n private readonly legacy: LegacyControl;\n private closed = false;\n\n private constructor(\n client: Client,\n private readonly sandboxIdentity: string | (() => string),\n private readonly root: string,\n private readonly environment: Record<string, string> | (() => Record<string, string>),\n ) {\n this.client = commandControlPlane(client);\n this.legacy = LegacyControl.forSandbox(client, sandboxIdentity, root, environment);\n }\n\n static forSandbox(\n client: Client,\n sandboxId: string | (() => string),\n root: string,\n environment: Record<string, string> | (() => Record<string, string>) = {},\n ): ModalCommandControl {\n if (client.version() !== \"0.9.0\")\n throw new Error(\"Modal command control requires the verified 0.9.0 SDK contract\");\n return new ModalCommandControl(client, sandboxId, root, environment);\n }\n\n private get sandboxId(): string {\n return typeof this.sandboxIdentity === \"function\"\n ? this.sandboxIdentity()\n : this.sandboxIdentity;\n }\n\n private async withRouter<T>(\n taskId: string,\n signal: AbortSignal | undefined,\n run: (router: ModalCommandRouterWire) => Promise<T>,\n ): Promise<T> {\n signal?.throwIfAborted();\n if (this.closed) throw new Error(\"Modal command control is closed\");\n let pending = this.routers.get(taskId);\n const reused = Boolean(pending);\n if (!pending) {\n const lookup: RouterLookup = {\n controller: new AbortController(),\n waiters: 0,\n settled: false,\n };\n pending = (async () => {\n const access = await awaitRouterAccess(\n this.client.taskGetCommandRouterAccess({ taskId }, { signal: lookup.controller.signal }),\n lookup.controller.signal,\n );\n let refreshAt = Date.now() + 60_000;\n try {\n // Expiry only shortens cache lifetime; it never authenticates access.\n const payload = JSON.parse(\n Buffer.from(access.jwt.split(\".\")[1] ?? \"\", \"base64url\").toString(),\n );\n if (typeof payload.exp === \"number\" && Number.isFinite(payload.exp))\n refreshAt = Math.min(refreshAt, payload.exp * 1000 - 15_000);\n } catch {\n /* Authentication remains the provider's responsibility. */\n }\n return { router: new ModalCommandRouterWire(access), users: 0, refreshAt };\n })();\n this.routers.set(taskId, pending);\n this.routerLookups.set(pending, lookup);\n const settled = () => {\n lookup.settled = true;\n this.routerLookups.delete(pending!);\n };\n void pending.then(settled, () => {\n settled();\n if (this.routers.get(taskId) === pending) this.routers.delete(taskId);\n });\n }\n const lookup = this.routerLookups.get(pending);\n if (lookup) lookup.waiters++;\n let entry: RouterEntry;\n try {\n entry = await awaitRouterAccess(pending, signal);\n } finally {\n if (lookup && --lookup.waiters === 0 && !lookup.settled) {\n // No interested callers remain. Never cancel a sibling's lookup, and\n // retire only this exact promise if a replacement has already won.\n if (this.routers.get(taskId) === pending) this.routers.delete(taskId);\n lookup.controller.abort(new Error(\"Modal router access has no remaining waiters\"));\n }\n }\n // Refresh credentials between operations, never close another active read.\n if (reused && !entry.users && Date.now() > entry.refreshAt) {\n // Another continuation may already have installed fresh access. Retire\n // only the captured cache entry, then join its replacement rather than\n // deleting or closing the newer transport.\n if (this.routers.get(taskId) === pending) {\n this.routers.delete(taskId);\n clearTimeout(entry.idle);\n entry.router.close();\n }\n return await this.withRouter(taskId, signal, run);\n }\n clearTimeout(entry.idle);\n entry.users++;\n try {\n signal?.throwIfAborted();\n return await run(entry.router);\n } finally {\n entry.users--;\n if (!entry.users) {\n entry.idle = setTimeout(() => {\n if (this.routers.get(taskId) === pending && !entry.users) {\n this.routers.delete(taskId);\n entry.router.close();\n }\n }, 30_000);\n entry.idle.unref?.();\n }\n }\n }\n\n async close(): Promise<void> {\n this.closed = true;\n for (const lookup of this.routerLookups.values())\n lookup.controller.abort(new Error(\"Modal command control is closed\"));\n const entries = await Promise.allSettled(this.routers.values());\n this.routers.clear();\n for (const entry of entries)\n if (entry.status === \"fulfilled\") {\n clearTimeout(entry.value.idle);\n entry.value.router.close();\n }\n }\n\n /** Access lookup may retry safely, but once the callback enters the Start\n * boundary only the wire's own dispatch proof can authorize recovery. */\n private async withStartRouter<T>(\n taskId: string,\n signal: AbortSignal | undefined,\n run: (router: ModalCommandRouterWire) => Promise<T>,\n ): Promise<T> {\n let entered = false;\n try {\n return await this.withRouter(taskId, signal, async (router) => {\n entered = true;\n return await run(router);\n });\n } catch (error) {\n if (entered) throw error;\n return await ModalCommandStartPreDispatchUnavailableError.beforeDispatch(async () => {\n throw error;\n }, signal);\n }\n }\n\n async start(args: ChannelAExecArgs, signal?: AbortSignal): Promise<ModalRouterProviderCommand> {\n signal?.throwIfAborted();\n const supervised = admittedCommandSupervisionReady() && !args.tty && !args.runAs;\n if (supervised) markPendingCommandSupervised();\n const sandboxId = this.sandboxId;\n const workdir = posix.resolve(this.root, args.workdir ?? this.root);\n if (workdir !== this.root && !workdir.startsWith(`${this.root.replace(/\\/$/u, \"\")}/`))\n throw new Error(\"Command workdir is outside the sandbox workspace\");\n const task = await ModalCommandStartPreDispatchUnavailableError.beforeDispatch(\n () => this.client.sandboxGetTaskId({ sandboxId }, signal ? { signal } : undefined),\n signal,\n );\n if (!task.taskId || task.taskResult) throw new Error(\"Modal command task is unavailable\");\n const taskId = task.taskId;\n if (this.sandboxId !== sandboxId)\n throw new Error(\"Modal sandbox changed during command preparation\");\n const execId = randomUUID();\n // PTY and runAs retain their existing explicit unsupported supervision\n // semantics. Never attach a fabricated descriptor to either path.\n const invocationId = randomUUID();\n const supervision = supervised\n ? {\n protocol: \"native-subreaper-v1\" as const,\n invocationId,\n nonce: randomBytes(32).toString(\"hex\"),\n controlPath: `/tmp/opengeni-supervision/${invocationId}.sock`,\n }\n : undefined;\n let commandArgs = modalCommandArgv(args);\n const env = typeof this.environment === \"function\" ? this.environment() : this.environment;\n if (supervision)\n commandArgs = [\n \"/usr/local/bin/opengeni-command-supervisor\",\n \"launch\",\n \"--invocation\",\n supervision.invocationId,\n \"--nonce\",\n supervision.nonce,\n \"--socket\",\n supervision.controlPath,\n \"--\",\n ...commandArgs,\n ];\n const command: ModalRouterProviderCommand = {\n kind: \"modal-router-v1\",\n sandboxId,\n taskId,\n execId,\n ...(args.tty ? { pty: true } : {}),\n ...(supervision ? { supervision } : {}),\n streams: {\n stdout: { byteOffset: 0, utf8Remainder: \"\", eof: false, exitCode: null },\n stderr: { byteOffset: 0, utf8Remainder: \"\", eof: false, exitCode: null },\n },\n };\n if (supervision) await reserveSupervisedLaunch(command);\n let startAttempted = false;\n try {\n await this.withStartRouter(taskId, signal, async (router) => {\n startAttempted = true;\n await router.start(\n {\n taskId,\n execId,\n commandArgs,\n workdir,\n env,\n ...(args.tty\n ? {\n ptyInfo: {\n enabled: true,\n winszRows: 24,\n winszCols: 80,\n envTerm: \"xterm\",\n ptyType: 1,\n noTerminateOnIdleStdin: true,\n },\n }\n : {}),\n },\n signal,\n );\n });\n } catch (error) {\n // A client-chosen router id remains the only possible invocation. Retain\n // it even for PTY/runAs/unsupervised starts: a rejected acknowledgement\n // does not prove that the provider rejected the launch.\n if (\n !startAttempted ||\n error instanceof ModalCommandStartNotDispatchedError ||\n error instanceof ModalCommandStartRejectedError ||\n error instanceof ModalCommandStartPreDispatchUnavailableError\n )\n throw error;\n throw new ProviderCommandStartOutcomeUnknownError(command, error);\n }\n return command;\n }\n\n /** Read-only, authenticated control execution on this exact instance. Never\n * inferred from a fleet image selector or user command stdout. No cache: warm\n * instances and route/task replacement must each pass before admission. */\n async verifySupervisionCapability(): Promise<{ sandboxId: string; taskId: string }> {\n const sandboxId = this.sandboxId;\n const signal = AbortSignal.timeout(5_000);\n const task = await ModalCommandStartPreDispatchUnavailableError.beforeDispatch(\n () => this.client.sandboxGetTaskId({ sandboxId }, { signal }),\n signal,\n );\n if (!task.taskId || task.taskResult) throw new Error(\"Modal command task is unavailable\");\n await this.withStartRouter(task.taskId, signal, async (router) => {\n const identity = { taskId: task.taskId!, execId: randomUUID() };\n const observation: ControlObservation = {\n command: {\n kind: \"modal-router-v1\",\n sandboxId,\n ...identity,\n streams: {\n stdout: { byteOffset: 0, utf8Remainder: \"\", eof: false, exitCode: null },\n stderr: { byteOffset: 0, utf8Remainder: \"\", eof: false, exitCode: null },\n },\n },\n output: \"\",\n };\n let startUnknown: ModalCommandStartOutcomeUnknownError | undefined;\n try {\n await router.start(\n {\n ...identity,\n commandArgs: [\"/usr/local/bin/opengeni-command-supervisor\", \"capabilities\"],\n workdir: \"/tmp\",\n env: {},\n },\n signal,\n );\n } catch (error) {\n // A lost acknowledgement does not authorize another Start. This fixed\n // read-only probe can still prove capability by observing its original\n // invocation inside the same five-second budget.\n if (!(error instanceof ModalCommandStartOutcomeUnknownError)) throw error;\n if (error.taskId !== identity.taskId || error.execId !== identity.execId) throw error;\n startUnknown = error;\n }\n let result: { output: string; exit: number };\n try {\n result = await this.readControlOutput(identity, 128, signal, observation);\n } catch (error) {\n if (!startUnknown) throw error;\n // Missing/denied observation cannot erase a genuine unknown Start or\n // turn it into sandbox-loss or replay authority.\n throw new ProviderCommandObservationUnavailableError(\n structuredClone(observation.command),\n new AggregateError(\n [startUnknown, error],\n \"Original capability Start and observation remain uncertain\",\n ),\n error instanceof ProviderCommandObservationUnavailableError && error.readRetryAllowed,\n );\n }\n signal.throwIfAborted();\n const { output, exit } = result;\n if (exit !== 0 || output !== \"native-subreaper-v1\")\n throw new Error(\n \"Exact Modal instance lacks compatible native supervision; command not admitted\",\n );\n });\n if (sandboxId !== this.sandboxId)\n throw new Error(\"Modal instance changed during supervision capability verification\");\n return { sandboxId, taskId: task.taskId };\n }\n\n /** Fixed provider readiness probe. No shell, user environment, admission or\n * SDK Start retries. Once Start may have been sent, only observe that exact\n * invocation; DNS-shaped server replies never authorize another Start. */\n async verifyExecReadiness(signal: AbortSignal): Promise<number> {\n signal.throwIfAborted();\n const sandboxId = this.sandboxId;\n const task = await ModalCommandStartPreDispatchUnavailableError.beforeDispatch(\n () => this.client.sandboxGetTaskId({ sandboxId }, { signal }),\n signal,\n );\n if (!task.taskId || task.taskResult) throw new Error(\"Modal command task is unavailable\");\n if (sandboxId !== this.sandboxId)\n throw new Error(\"Modal sandbox changed during readiness preparation\");\n const identity = { taskId: task.taskId, execId: randomUUID() };\n const transientObservation = (error: unknown) =>\n [status.UNAVAILABLE, status.DEADLINE_EXCEEDED].includes(\n (error as { code?: number } | null)?.code ?? -1,\n );\n const pause = () => delay(100, undefined, { signal });\n return await this.withStartRouter(task.taskId, signal, async (router) => {\n for (;;) {\n signal.throwIfAborted();\n try {\n await router.start(\n { ...identity, commandArgs: [\"/bin/true\"], workdir: \"/tmp\", env: {} },\n signal,\n );\n break;\n } catch (error) {\n signal.throwIfAborted();\n if (error instanceof ModalCommandStartPreDispatchUnavailableError) {\n await pause();\n continue;\n }\n // A lost Start acknowledgement is not replay permission. The probe\n // may already exist, so keep this identity even if observation later\n // exhausts the caller's readiness budget.\n if (\n error instanceof ModalCommandStartRejectedError ||\n error instanceof ModalCommandStartNotDispatchedError\n )\n throw error;\n break;\n }\n }\n const streams = {\n stdout: { offset: 0, eof: false },\n stderr: { offset: 0, eof: false },\n };\n for (;;) {\n signal.throwIfAborted();\n try {\n for (const stream of [\"stdout\", \"stderr\"] as const) {\n const cursor = streams[stream];\n if (cursor.eof) continue;\n const page = await router.read(identity, stream, cursor.offset, 1_000, signal);\n cursor.offset += page.bytes.length;\n cursor.eof = page.eof;\n }\n const exit = await router.poll(identity, signal);\n signal.throwIfAborted();\n if (exit !== null && streams.stdout.eof && streams.stderr.eof) return exit;\n } catch (error) {\n signal.throwIfAborted();\n if (!transientObservation(error)) throw error;\n }\n await pause();\n }\n });\n }\n\n /** Separate authenticated provider execution of the installed control helper.\n * User command streams are never inspected for control evidence. */\n async supervisionControl(\n command: ModalRouterProviderCommand,\n action: \"release\" | \"cancel\" | \"status\" | \"ack\",\n receiptId?: string,\n ): Promise<SupervisionControlResult> {\n SandboxProviderCommand.parse(command);\n const descriptor = command.supervision;\n if (!descriptor || command.sandboxId !== this.sandboxId)\n throw new Error(\"Supervised command identity is unavailable\");\n const key = JSON.stringify([\n command.sandboxId,\n command.taskId,\n command.execId,\n descriptor.invocationId,\n descriptor.nonce,\n descriptor.controlPath,\n action,\n receiptId ?? null,\n ]);\n let helper = this.controlHelpers.get(key);\n if (!helper) {\n helper = {\n startPending: true,\n output: \"\",\n command: {\n kind: \"modal-router-v1\",\n sandboxId: command.sandboxId,\n taskId: command.taskId,\n execId: randomUUID(),\n streams: {\n stdout: { byteOffset: 0, utf8Remainder: \"\", eof: false, exitCode: null },\n stderr: { byteOffset: 0, utf8Remainder: \"\", eof: false, exitCode: null },\n },\n },\n };\n this.controlHelpers.set(key, helper);\n }\n const observation = helper;\n const run = async (): Promise<SupervisionControlResult> => {\n const signal = AbortSignal.timeout(5_000);\n if (observation.startPending) {\n try {\n await this.withStartRouter(command.taskId, signal, async (router) => {\n // Once the wire may dispatch, neither a failed acknowledgement nor\n // a later drain may create another helper invocation.\n observation.startPending = false;\n await router.start(\n {\n taskId: observation.command.taskId,\n execId: observation.command.execId,\n commandArgs: [\n \"/usr/local/bin/opengeni-command-supervisor\",\n \"control\",\n \"--invocation\",\n descriptor.invocationId,\n \"--nonce\",\n descriptor.nonce,\n \"--socket\",\n descriptor.controlPath,\n \"--action\",\n action,\n ...(receiptId ? [\"--receipt\", receiptId] : []),\n ],\n workdir: \"/tmp\",\n env: {},\n },\n signal,\n );\n });\n } catch (error) {\n if (\n observation.startPending ||\n error instanceof ModalCommandStartNotDispatchedError ||\n error instanceof ModalCommandStartRejectedError ||\n error instanceof ModalCommandStartPreDispatchUnavailableError\n ) {\n this.controlHelpers.delete(key);\n throw error;\n }\n // Preserve the genuine original Start boundary. A later drain reads\n // this same helper; it never repeats a possibly dispatched Start.\n observation.startUnknown = error;\n throw error;\n }\n }\n let response: { output: string; exit: number };\n try {\n response = await this.readControlOutput(observation.command, 4096, signal, observation);\n } catch (error) {\n if (\n observation.startUnknown !== undefined &&\n error instanceof ProviderCommandObservationUnavailableError\n )\n throw new ProviderCommandObservationUnavailableError(\n error.command,\n new AggregateError(\n [observation.startUnknown, error],\n \"Original helper Start and observation remain uncertain\",\n ),\n error.readRetryAllowed,\n );\n throw error;\n }\n const { output, exit } = response;\n // Only a complete authenticated helper response retires its private\n // cursor/output cache. Uncertainty keeps the same action and UUID.\n this.controlHelpers.delete(key);\n if (exit !== 0) throw new Error(\"Supervisor control is unavailable\");\n const result = JSON.parse(output);\n if (!result || ![\"idle\", \"running\", \"quiescent\"].includes(result.state))\n throw new Error(\"Invalid supervisor control response\");\n if (result.receipt !== undefined) {\n result.receipt = CommandSupervisionReceipt.parse(result.receipt);\n if (result.receipt.invocationId !== descriptor.invocationId)\n throw new Error(\"Supervisor receipt invocation mismatch\");\n }\n if ((result.state === \"quiescent\") !== Boolean(result.receipt))\n throw new Error(\"Supervisor quiescence response lacks its receipt\");\n return result;\n };\n observation.inFlight ??= run().finally(() => {\n delete observation.inFlight;\n });\n return await observation.inFlight;\n }\n\n /** These fixed helpers already started once. Observe only their original\n * invocation within the caller's existing five-second budget. */\n private async readControlOutput(\n identity: { taskId: string; execId: string },\n limit: number,\n signal: AbortSignal,\n observation?: ControlObservation,\n ): Promise<{ output: string; exit: number }> {\n const state: ControlObservation = observation ?? {\n command: {\n kind: \"modal-router-v1\",\n sandboxId: this.sandboxId,\n ...identity,\n streams: {\n stdout: { byteOffset: 0, utf8Remainder: \"\", eof: false, exitCode: null },\n stderr: { byteOffset: 0, utf8Remainder: \"\", eof: false, exitCode: null },\n },\n },\n output: \"\",\n };\n for (;;) {\n try {\n signal.throwIfAborted();\n const page = await this.read(state.command, 250, signal);\n state.command = page.command as ModalRouterProviderCommand;\n if (\n state.command.streams.stdout.byteOffset + state.command.streams.stderr.byteOffset >\n limit\n )\n throw new Error(\"Supervisor control response exceeds its bound\");\n state.output += page.chunks\n .filter((chunk) => chunk.stream === \"stdout\")\n .map((chunk) => chunk.text)\n .join(\"\");\n if (page.exitCode !== null) return { output: state.output, exit: page.exitCode };\n } catch (error) {\n if (signal.aborted)\n throw new ProviderCommandObservationUnavailableError(\n structuredClone(state.command),\n error,\n );\n if (\n !(error instanceof ProviderCommandObservationUnavailableError) ||\n !error.readRetryAllowed\n )\n throw error;\n }\n try {\n await delay(100, undefined, { signal });\n } catch (error) {\n throw new ProviderCommandObservationUnavailableError(structuredClone(state.command), error);\n }\n }\n }\n\n async read(\n command: ModalProviderCommand,\n waitMs: number,\n signal?: AbortSignal,\n ): Promise<ModalProviderOutputPage> {\n SandboxProviderCommand.parse(command);\n if (command.sandboxId !== this.sandboxId)\n throw new Error(\"Modal command does not belong to this sandbox\");\n if (command.kind === \"modal-control-v1\") return await this.legacy.read(command, waitMs, signal);\n return (await this.readNative(command, waitMs, signal)).output;\n }\n\n /** Native capture plumbing only. Raw bytes are acquired by the same joined\n * read/poll path as read(); no legacy locator or new command is admitted. */\n async readRaw(\n command: ModalRouterProviderCommand,\n waitMs: number,\n signal?: AbortSignal,\n ): Promise<ModalRawOutputPage> {\n return (await this.readNative(command, waitMs, signal)).raw;\n }\n\n private async readNative(\n input: ModalRouterProviderCommand,\n waitMs: number,\n signal?: AbortSignal,\n ): Promise<ReturnType<typeof collectModalRawOutputPage>> {\n const command = structuredClone(ModalRouterProviderCommand.parse(input));\n if (command.sandboxId !== this.sandboxId)\n throw new Error(\"Modal command does not belong to this sandbox\");\n if (!Number.isFinite(waitMs) || waitMs < 0 || waitMs > 50_000)\n throw new Error(\"Invalid Modal output read bounds\");\n signal?.throwIfAborted();\n const stdout = command.streams.stdout;\n const stderr = command.streams.stderr;\n if (\n stdout.eof &&\n stderr.eof &&\n stdout.utf8Remainder === \"\" &&\n stderr.utf8Remainder === \"\" &&\n stdout.exitCode !== null &&\n stdout.exitCode === stderr.exitCode\n ) {\n // Both complete streams and their matching terminal observation were\n // already captured. An expired provider handle cannot revoke that exact\n // evidence; the session still atomically verifies the retained cursor.\n return collectModalRawOutputPage(\n command,\n {\n stdout: { bytes: Buffer.alloc(0), eof: true },\n stderr: { bytes: Buffer.alloc(0), eof: true },\n },\n { source: \"retained_terminal\", code: stdout.exitCode },\n );\n }\n const budget = new AbortController();\n const abort = () => budget.abort(signal?.reason);\n signal?.addEventListener(\"abort\", abort, { once: true });\n if (signal?.aborted) abort();\n // The router deliberately ends a quiet stream at its read deadline with\n // a partial page. Let that deadline settle before outer containment aborts\n // the whole page, including bytes already read from the other stream.\n // Caller cancellation still bounds this allowance independently.\n const deadline = performance.now() + Math.max(1, waitMs);\n const timeout = setTimeout(\n () => budget.abort(new Error(\"Modal command read budget exhausted\")),\n Math.max(1, waitMs) + 5_000,\n );\n let lastError: unknown;\n try {\n for (let attempt = 0; attempt < 5; attempt++) {\n signal?.throwIfAborted();\n if (attempt > 0 && performance.now() >= deadline) break;\n try {\n return await this.readRouterPage(\n command,\n Math.min(Math.max(1, waitMs), Math.max(1, deadline - performance.now())),\n budget.signal,\n deadline,\n );\n } catch (error) {\n signal?.throwIfAborted();\n if (!budget.signal.aborted && !isModalCommandObservationTransportError(error)) {\n // Containment is not retry permission. A structural provider fault\n // dominates nested missing-handle prose, but mixed/unreadable\n // graphs do not acquire the strict safe-read retry authority.\n if (classifyProviderSandboxFailure(\"modal\", error).kind === \"transient_transport\")\n throw new ProviderCommandObservationUnavailableError(\n structuredClone(command),\n error,\n false,\n );\n throw error;\n }\n lastError = error;\n if (budget.signal.aborted || performance.now() >= deadline || attempt === 4) break;\n try {\n await delay(Math.min(100, Math.max(1, deadline - performance.now())), undefined, {\n signal: budget.signal,\n });\n } catch {\n signal?.throwIfAborted();\n break;\n }\n }\n }\n throw new ProviderCommandObservationUnavailableError(structuredClone(command), lastError);\n } finally {\n clearTimeout(timeout);\n signal?.removeEventListener(\"abort\", abort);\n }\n }\n\n private async readRouterPage(\n command: ModalRouterProviderCommand,\n waitMs: number,\n signal: AbortSignal,\n deadline: number,\n ): Promise<ReturnType<typeof collectModalRawOutputPage>> {\n const cancellation = new AbortController();\n const lookupCancellation = new AbortController();\n const abort = () => {\n cancellation.abort(signal.reason);\n lookupCancellation.abort(signal.reason);\n };\n signal?.addEventListener(\"abort\", abort, { once: true });\n if (signal?.aborted) abort();\n const lookupTimeout = setTimeout(\n () =>\n lookupCancellation.abort(\n new ProviderCommandObservationUnavailableError(\n structuredClone(command),\n new Error(\"Modal command read access budget exhausted\"),\n ),\n ),\n Math.max(1, deadline - performance.now()),\n );\n try {\n return await this.withRouter(command.taskId, lookupCancellation.signal, async (router) => {\n clearTimeout(lookupTimeout);\n lookupCancellation.signal.throwIfAborted();\n signal.throwIfAborted();\n if (performance.now() >= deadline)\n throw new ProviderCommandObservationUnavailableError(\n structuredClone(command),\n new Error(\"Modal command read budget exhausted\"),\n );\n const remainingWait = Math.max(1, Math.min(waitMs, deadline - performance.now()));\n const operations = [\n ...([\"stdout\", \"stderr\"] as const).map(async (stream) =>\n command.streams[stream].eof\n ? { bytes: Buffer.alloc(0), eof: true }\n : await router.read(\n command,\n stream,\n command.streams[stream].byteOffset,\n remainingWait,\n cancellation.signal,\n ),\n ),\n router.poll(command, cancellation.signal),\n ] as const;\n const results = await Promise.allSettled(\n operations.map((operation) =>\n operation.catch((error) => {\n cancellation.abort(error);\n throw error;\n }),\n ),\n );\n const failed = results.find((result) => result.status === \"rejected\");\n // Abort-induced sibling rejections may sort before the failing poll.\n // Preserve the first actual provider fault rather than array order.\n if (failed?.status === \"rejected\") throw cancellation.signal.reason ?? failed.reason;\n const stdout = (results[0] as PromiseFulfilledResult<{ bytes: Buffer; eof: boolean }>)\n .value;\n const stderr = (results[1] as PromiseFulfilledResult<{ bytes: Buffer; eof: boolean }>)\n .value;\n let exit = (results[2] as PromiseFulfilledResult<number | null>).value;\n if (exit === null && stdout.eof && stderr.eof)\n exit = await this.pollAfterEof(router, command, cancellation.signal, deadline);\n return collectModalRawOutputPage(\n command,\n { stdout, stderr },\n { source: \"router_poll\", code: exit },\n );\n });\n } finally {\n clearTimeout(lookupTimeout);\n signal?.removeEventListener(\"abort\", abort);\n }\n }\n\n /** TaskExecPoll is a point-in-time status, issued concurrently with stream\n * reads that may wait for EOF. A poll answered before the command exited\n * reports \"running\" even when both streams then finish, and callers that\n * read once (internal Channel-A commands) would treat a finished command as\n * still running. After both streams reach EOF, poll again within this read's\n * existing budget. EOF is not exit proof: a re-poll fault or an exhausted\n * budget keeps the observed bytes and reports the exit as still unknown, and\n * only caller cancellation propagates. Re-poll faults are deliberately not\n * classified here; the next page's concurrent poll classifies the same\n * provider state. Each re-poll is bounded by the read deadline so a slow\n * poll cannot exhaust the outer budget and discard the page. */\n private async pollAfterEof(\n router: ModalCommandRouterWire,\n command: ModalRouterProviderCommand,\n signal: AbortSignal,\n deadline: number,\n ): Promise<number | null> {\n let pause = 10;\n for (;;) {\n signal.throwIfAborted();\n const budget = deadline - performance.now();\n if (budget <= 0) return null;\n let exit: number | null;\n try {\n exit = await router.poll(\n command,\n AbortSignal.any([signal, AbortSignal.timeout(Math.ceil(budget) + REPOLL_GRACE_MS)]),\n );\n } catch {\n signal.throwIfAborted();\n return null;\n }\n if (exit !== null) return exit;\n const remaining = deadline - performance.now();\n if (remaining <= 0) return null;\n try {\n await delay(Math.min(pause, remaining), undefined, { signal });\n } catch {\n signal.throwIfAborted();\n return null;\n }\n pause = Math.min(pause * 2, 250);\n }\n }\n\n async readProbe(\n command: ModalProviderCommand,\n waitMs: number,\n cancellation: AbortController,\n ): Promise<ModalProviderOutputPage> {\n return await this.read(command, waitMs, cancellation.signal);\n }\n\n async write(command: ModalProviderCommand, chars: string, index: number): Promise<void> {\n SandboxProviderCommand.parse(command);\n if (command.sandboxId !== this.sandboxId)\n throw new Error(\"Modal command does not belong to this sandbox\");\n if (command.kind === \"modal-control-v1\") return await this.legacy.write(command, chars, index);\n await this.withRouter(command.taskId, undefined, (router) =>\n router.write(command, index, Buffer.from(chars)),\n );\n }\n}\n","/** Only used inside a read-only provider RPC boundary. This is deliberately\n * not a Start classifier: remote DNS prose never proves non-dispatch. */\nexport function isModalCommandObservationTransportError(error: unknown): boolean {\n const seen = new Map<object, boolean>();\n let nodes = 0;\n const own = (value: object, key: string): unknown => {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor && !(\"value\" in descriptor)) throw new Error(\"Unreadable provider error graph\");\n return descriptor && \"value\" in descriptor ? descriptor.value : undefined;\n };\n const visit = (value: unknown, depth: number): boolean => {\n if (!value || typeof value !== \"object\" || depth > 6 || ++nodes > 32) return false;\n if (seen.has(value)) return seen.get(value)!;\n // A cycle sees false until this bounded branch has been fully evaluated.\n seen.set(value, false);\n try {\n const code = own(value, \"code\");\n const nested: unknown[] = [own(value, \"cause\"), own(value, \"error\")].filter(\n (item) => item !== undefined,\n );\n const errors = own(value, \"errors\");\n if (errors !== undefined) {\n if (!Array.isArray(errors) || !errors.length || errors.length > 16) return false;\n for (let index = 0; index < errors.length; index++) nested.push(own(errors, String(index)));\n }\n if (code !== undefined) {\n const normalized = typeof code === \"string\" ? code.trim().toUpperCase() : code;\n if (\n ![\n 1,\n 2,\n 4,\n 13,\n 14,\n \"1\",\n \"2\",\n \"4\",\n \"13\",\n \"14\",\n \"CANCELLED\",\n \"UNKNOWN\",\n \"DEADLINE_EXCEEDED\",\n \"INTERNAL\",\n \"UNAVAILABLE\",\n \"ECONNRESET\",\n \"ECONNREFUSED\",\n \"ETIMEDOUT\",\n \"EAI_AGAIN\",\n \"ENOTFOUND\",\n ].includes(normalized as never)\n )\n return false;\n const result = nested.length === 0 || nested.every((item) => visit(item, depth + 1));\n seen.set(value, result);\n return result;\n }\n const result = nested.length > 0 && nested.every((item) => visit(item, depth + 1));\n seen.set(value, result);\n return result;\n } catch {\n return false;\n }\n };\n return visit(error, 0);\n}\n","import {\n ModalImageSelector,\n ModalSandboxSession,\n buildModalCloudBucketMountConfig,\n isModalCloudBucketMountEntry,\n type ModalSandboxClient,\n type ModalSandboxClientOptions,\n type ModalSandboxSessionState,\n} from \"@openai/agents-extensions/sandbox/modal\";\nimport {\n Manifest,\n isMount,\n normalizeSandboxClientCreateArgs,\n SandboxUnsupportedFeatureError,\n type Entry,\n} from \"@openai/agents/sandbox\";\nimport { materializeEnvironment, readOptionalString } from \"@openai/agents-core/sandbox/internal\";\nimport { ModalClient, Sandbox, type Image, type CloudBucketMount } from \"modal\";\nimport { createModalProviderCreateBoundary, type ModalCreateIntent } from \"./modal-create-boundary\";\nimport { modalCommandStartCleanupIsSafe } from \"./modal-command-start-errors\";\n\nexport type ModalCreateLifecycle = {\n beforeDispatch: (intent: ModalCreateIntent, providerContext: unknown) => Promise<void>;\n onCreated: (session: ModalSandboxSession, intent: ModalCreateIntent) => Promise<void>;\n};\n\n/** Release local transport after a failed create, but never stop a box whose\n * original setup invocation may still be writing behind its durable fence. */\nexport async function releaseModalCreateFailure(\n session: Pick<ModalSandboxSession, \"close\"> | undefined,\n modal: Pick<ModalClient, \"close\">,\n error: unknown,\n): Promise<never> {\n try {\n if (session && modalCommandStartCleanupIsSafe(error)) {\n try {\n await session.close();\n } catch (cleanupError) {\n // eslint-disable-next-line preserve-caught-error -- Both failures remain exact AggregateError causes.\n throw new AggregateError(\n [error, cleanupError],\n \"Modal create failed and cleanup needs reconciliation\",\n { cause: cleanupError },\n );\n }\n }\n } finally {\n modal.close();\n }\n throw error;\n}\n\nfunction defined<T extends object>(\n value: T,\n): {\n [K in keyof T]?: Exclude<T[K], undefined>;\n} {\n return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as {\n [K in keyof T]?: Exclude<T[K], undefined>;\n };\n}\n\nfunction unsupported(feature: string): never {\n throw new SandboxUnsupportedFeatureError(`Modal create does not support ${feature}`, {\n provider: \"modal\",\n feature,\n });\n}\n\nfunction validateManifest(manifest: Manifest): void {\n if (manifest.users.length) unsupported(\"manifest.users\");\n if (manifest.groups.length) unsupported(\"manifest.groups\");\n if (manifest.extraPathGrants.length) unsupported(\"manifest.extraPathGrants\");\n for (const { entry } of manifest.iterEntries()) {\n if (entry.permissions !== undefined) unsupported(\"entry.permissions\");\n if (entry.group !== undefined) unsupported(\"entry.group\");\n if (isMount(entry) && !isModalCloudBucketMountEntry(entry)) unsupported(\"entry.mountStrategy\");\n }\n}\n\nfunction withoutMounts(manifest: Manifest): Manifest {\n const entries = (source: Record<string, Entry>): Record<string, Entry> =>\n Object.fromEntries(\n Object.entries(source)\n .filter(([, entry]) => !isMount(entry))\n .map(([path, entry]) => [\n path,\n entry.type === \"dir\" && entry.children\n ? { ...structuredClone(entry), children: entries(entry.children) }\n : structuredClone(entry),\n ]),\n );\n return new Manifest({\n version: manifest.version,\n root: manifest.root,\n entries: entries(manifest.entries),\n environment: Object.fromEntries(\n Object.entries(manifest.environment).map(([key, value]) => [key, value.init()]),\n ),\n users: structuredClone(manifest.users),\n groups: structuredClone(manifest.groups),\n extraPathGrants: structuredClone(manifest.extraPathGrants),\n remoteMountCommandAllowlist: [...manifest.remoteMountCommandAllowlist],\n });\n}\n\n/** Own physical creation while retaining the pinned SDK's public session API.\n * Its ordinary create() applies the manifest before exposing the instance ID,\n * which is too late for a durable worker lease. No global SDK monkey-patching.\n */\nexport async function createModalSessionWithLifecycle(\n defaults: Partial<ModalSandboxClientOptions>,\n args: Parameters<ModalSandboxClient[\"create\"]>[0],\n lifecycle: ModalCreateLifecycle,\n installPolicy: (session: ModalSandboxSession) => ModalSandboxSession,\n): Promise<ModalSandboxSession> {\n const create = normalizeSandboxClientCreateArgs(args);\n if (create.snapshot !== undefined) unsupported(\"snapshot\");\n const overrides = create.options as Partial<ModalSandboxClientOptions> | undefined;\n const options = { ...defaults };\n for (const [key, value] of Object.entries(overrides ?? {})) {\n if (value !== null && value !== undefined) Object.assign(options, { [key]: value });\n }\n options.env = { ...defaults.env, ...overrides?.env };\n if (options.sandbox) unsupported(\"existing sandbox selector in physical create\");\n if (!options.appName?.trim()) throw new Error(\"Modal create requires a non-empty appName\");\n if (\n options.nativeCloudBucketSecretName !== undefined &&\n !options.nativeCloudBucketSecretName.trim()\n ) {\n throw new Error(\"Modal nativeCloudBucketSecretName must be non-empty\");\n }\n const workspacePersistence = options.workspacePersistence ?? \"tar\";\n if (![\"tar\", \"snapshot_filesystem\", \"snapshot_directory\"].includes(workspacePersistence))\n unsupported(\"workspacePersistence\");\n for (const key of [\n \"sandboxCreateTimeoutS\",\n \"snapshotFilesystemTimeoutMs\",\n \"snapshotFilesystemRestoreTimeoutMs\",\n \"timeoutMs\",\n \"idleTimeoutMs\",\n \"cpu\",\n \"memoryMiB\",\n ] as const) {\n const value = options[key];\n if (value !== undefined && (!Number.isFinite(value) || value <= 0))\n throw new Error(`Modal ${key} must be positive`);\n }\n const manifest = create.manifest;\n validateManifest(manifest);\n // Validate mount configuration before any provider resource is requested.\n for (const { entry } of manifest.mountTargets()) {\n buildModalCloudBucketMountConfig(\n entry,\n defined({\n secretName:\n readOptionalString(entry.mountStrategy, \"secretName\") ??\n options.nativeCloudBucketSecretName,\n secretEnvironmentName: readOptionalString(entry.mountStrategy, \"secretEnvironmentName\"),\n }),\n );\n }\n let session: ModalSandboxSession | undefined;\n let timedOut = false;\n let cloudBucketMounts: Record<string, CloudBucketMount> | undefined;\n let state: Omit<ModalSandboxSessionState, \"sandboxId\">;\n let app: Awaited<ReturnType<ModalClient[\"apps\"][\"fromName\"]>>;\n const modal = new ModalClient(\n defined({\n tokenId: options.tokenId,\n tokenSecret: options.tokenSecret,\n environment: options.environment,\n endpoint: options.endpoint,\n grpcMiddleware: [\n createModalProviderCreateBoundary({\n operationId: crypto.randomUUID(),\n beforeDispatch: async (intent) => {\n if (timedOut) throw new Error(\"Modal create expired before provider dispatch\");\n await lifecycle.beforeDispatch(intent, { modal });\n },\n onReceipt: async (receipt) => {\n const constructorArgs = {\n modal,\n app,\n sandbox: new Sandbox(modal, receipt.instanceId),\n ownsSandbox: true,\n state: { ...state, sandboxId: receipt.instanceId, imageId: receipt.imageId },\n cloudBucketMounts,\n cloudBucketMountsProvider: async () =>\n await resolveMounts(session?.state.manifest ?? manifest),\n concurrencyLimits: create.concurrencyLimits,\n archiveLimits: create.archiveLimits,\n };\n // Agents Extensions 0.14.3's structural Modal types predate Modal 0.9's\n // snapshot options. Runtime policy adapts that pinned interface.\n session = installPolicy(\n new ModalSandboxSession(\n constructorArgs as unknown as ConstructorParameters<typeof ModalSandboxSession>[0],\n ),\n );\n // The pinned SDK closes processes/the box, but not its Modal\n // transport. This adapter owns a dedicated client per create.\n const closeSession = session.close.bind(session);\n session.close = async () => {\n await closeSession();\n modal.close();\n };\n await lifecycle.onCreated(session, receipt);\n },\n }),\n ],\n }),\n );\n const resolveMounts = async (source: Manifest) => {\n const result: Record<string, CloudBucketMount> = {};\n for (const { entry, mountPath } of source.mountTargets()) {\n if (!isModalCloudBucketMountEntry(entry)) unsupported(\"entry.mountStrategy\");\n const config = buildModalCloudBucketMountConfig(\n entry,\n defined({\n secretName:\n readOptionalString(entry.mountStrategy, \"secretName\") ??\n options.nativeCloudBucketSecretName,\n secretEnvironmentName: readOptionalString(entry.mountStrategy, \"secretEnvironmentName\"),\n }),\n );\n const secret = config.secretName\n ? await modal.secrets.fromName(\n config.secretName,\n defined({\n environment: config.secretEnvironmentName,\n }),\n )\n : config.credentials\n ? await modal.secrets.fromObject(config.credentials)\n : undefined;\n result[mountPath] = modal.cloudBucketMounts.create(\n config.bucketName,\n defined({\n bucketEndpointUrl: config.bucketEndpointUrl,\n keyPrefix: config.keyPrefix,\n readOnly: config.readOnly,\n secret,\n }),\n );\n }\n return Object.keys(result).length ? result : undefined;\n };\n try {\n app = await modal.apps.fromName(\n options.appName,\n defined({\n createIfMissing: true,\n environment: options.environment,\n }),\n );\n const environment = await materializeEnvironment(manifest, options.env);\n const selector =\n options.image ?? ModalImageSelector.fromTag(options.imageTag ?? \"debian:bookworm-slim\");\n let image: Image;\n if (selector.kind === \"image\") image = selector.value as Image;\n else if (typeof selector.value !== \"string\" || !selector.value.trim())\n throw new Error(\"Modal image identity must be non-empty\");\n else if (selector.kind === \"id\") image = await modal.images.fromId(selector.value);\n else if (selector.kind === \"tag\") image = modal.images.fromRegistry(selector.value);\n else throw new Error(\"Unsupported Modal image selector\");\n if (typeof image?.build !== \"function\")\n throw new Error(\"Modal image selector requires a native Image\");\n cloudBucketMounts = await resolveMounts(manifest);\n state = {\n manifest,\n ownsSandbox: true,\n appName: options.appName,\n imageTag:\n selector.kind === \"tag\"\n ? (selector.value as string)\n : (options.imageTag ?? \"debian:bookworm-slim\"),\n sandboxCreateTimeoutS: options.sandboxCreateTimeoutS,\n workspacePersistence,\n snapshotFilesystemTimeoutMs: options.snapshotFilesystemTimeoutMs,\n snapshotFilesystemRestoreTimeoutMs: options.snapshotFilesystemRestoreTimeoutMs,\n environment,\n timeoutMs: options.timeoutMs,\n idleTimeoutMs: options.idleTimeoutMs,\n cpu: options.cpu,\n memoryMiB: options.memoryMiB,\n gpu: options.gpu,\n configuredExposedPorts: options.exposedPorts,\n modalEnvironment: options.environment,\n endpoint: options.endpoint,\n imageBuilderVersion: options.imageBuilderVersion,\n nativeCloudBucketSecretName: options.nativeCloudBucketSecretName,\n useSleepCmd: options.useSleepCmd ?? true,\n };\n const physicalCreate = modal.sandboxes.create(\n app,\n image,\n defined({\n workdir: manifest.root,\n env: environment,\n command: state.useSleepCmd ? [\"sleep\", \"infinity\"] : undefined,\n timeoutMs: options.timeoutMs,\n idleTimeoutMs: options.idleTimeoutMs,\n cpu: options.cpu,\n memoryMiB: options.memoryMiB,\n gpu: options.gpu,\n encryptedPorts: options.exposedPorts,\n cloudBucketMounts,\n }),\n );\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await (options.sandboxCreateTimeoutS === undefined\n ? physicalCreate\n : Promise.race([\n physicalCreate,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n timedOut = true;\n reject(\n new Error(\"Modal sandbox creation timed out; provider receipt remains fenced\"),\n );\n }, options.sandboxCreateTimeoutS! * 1000);\n }),\n ]));\n } finally {\n if (timer) clearTimeout(timer);\n // A late callback still persists its ID. Cleanup cannot license another\n // create until the durable lease has that identity and terminal proof.\n if (timedOut)\n void physicalCreate\n .then(\n async () => {\n await session?.close();\n },\n async () => {\n await session?.close();\n },\n )\n .catch(() => {\n modal.logger.warn(\n \"Late Modal create cleanup failed; durable lease requires reconciliation\",\n );\n })\n .finally(() => modal.close());\n }\n if (!session) throw new Error(\"Modal create bypassed the required physical receipt boundary\");\n await session.applyManifest(withoutMounts(manifest));\n return session;\n } catch (error) {\n // Timed-out work still owns its transport until its late receipt settles.\n // Every synchronous failure releases the transport even if stopping the\n // provider fails; durable reconciliation uses a separate authenticated client.\n if (!timedOut) {\n return await releaseModalCreateFailure(session, modal, error);\n }\n throw error;\n }\n}\n","import { createHash } from \"node:crypto\";\nimport type { ModalClient } from \"modal\";\n\ntype ModalMiddleware = NonNullable<\n NonNullable<ConstructorParameters<typeof ModalClient>[0]>[\"grpcMiddleware\"]\n>[number];\n\nconst CREATE_PATH = \"/modal.client.ModalClient/SandboxCreate\";\nconst OPERATION_TAG = \"opengeni_provider_create_operation_id\";\n\nexport type ModalCreateIntent = {\n operationId: string;\n name: string;\n appId: string;\n imageId: string;\n requestSha256: string;\n};\n\nexport function modalCreateOperationName(operationId: string): string {\n if (!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u.test(operationId)) {\n throw new Error(\"Modal create requires a UUID operation identity\");\n }\n return `opengeni-create-${operationId}`;\n}\n\n/** One controller per attempted physical create, on a dedicated Modal client.\n *\n * Modal 0.9.0 runs this middleware outside its retry middleware. Disable retries\n * for this RPC: the SDK otherwise invents a new, unpersisted idempotency key.\n * Preparation (image builds, secret hydration) runs before this boundary. Once\n * beforeDispatch starts, even an interrupted database acknowledgement is an\n * uncertain attempt. Neither an exception nor named lookup absence licenses a\n * second dispatch. The durable lease, not this in-memory latch, owns recovery.\n *\n * Names/tags are atomic positive-discovery aids, never a quiescence guarantee.\n * No raw request, environment, or secret material leaves this adapter.\n */\nexport function createModalProviderCreateBoundary(input: {\n operationId: string;\n beforeDispatch: (intent: ModalCreateIntent) => Promise<void>;\n onReceipt: (receipt: ModalCreateIntent & { instanceId: string }) => Promise<void>;\n}): ModalMiddleware {\n const name = modalCreateOperationName(input.operationId);\n let attempted = false;\n return async function* modalProviderCreateBoundary(call, options) {\n if (call.method.path !== CREATE_PATH) return yield* call.next(call.request, options);\n if (call.requestStream || call.responseStream) {\n throw new Error(\"Modal SandboxCreate unexpectedly became a streaming RPC\");\n }\n if (attempted)\n throw new Error(\"Modal provider create was already attempted; reconcile its receipt\");\n const request = call.request as {\n appId?: unknown;\n definition?: { imageId?: unknown; name?: unknown; [key: string]: unknown };\n tags?: Array<{ tagName: string; tagValue: string }>;\n };\n if (\n typeof request.appId !== \"string\" ||\n !request.appId ||\n typeof request.definition?.imageId !== \"string\" ||\n !request.definition.imageId ||\n (request.definition.name && request.definition.name !== name) ||\n !Array.isArray(request.tags) ||\n request.tags.some(\n (tag) => tag.tagName === OPERATION_TAG && tag.tagValue !== input.operationId,\n )\n ) {\n throw new Error(\"Modal SandboxCreate wire identity does not match the owned operation\");\n }\n const wireRequest = {\n ...request,\n definition: { ...request.definition, name },\n tags: [\n ...request.tags.filter((tag) => tag.tagName !== OPERATION_TAG),\n { tagName: OPERATION_TAG, tagValue: input.operationId },\n ],\n };\n const intent: ModalCreateIntent = {\n operationId: input.operationId,\n name,\n appId: request.appId,\n imageId: request.definition.imageId,\n requestSha256: createHash(\"sha256\").update(JSON.stringify(wireRequest)).digest(\"hex\"),\n };\n attempted = true;\n await input.beforeDispatch(intent);\n // Middleware is generic over every Modal RPC. The exact method/path and\n // validated request above narrow this one operation's protobuf boundary.\n const dispatchOptions = { ...options, retries: 0 };\n const response = yield* call.next(wireRequest as typeof call.request, dispatchOptions);\n const instanceId = (response as { sandboxId?: unknown } | null)?.sandboxId;\n if (typeof instanceId !== \"string\" || !instanceId.startsWith(\"sb-\")) {\n throw new Error(\n \"Modal create returned no physical sandbox identity; operation remains uncertain\",\n );\n }\n // Persist even if the caller has since cancelled. Cancellation cannot erase\n // an already-created provider instance or turn it into a never-sent request.\n await input.onReceipt({ ...intent, instanceId });\n return response;\n };\n}\n","import { CAPABILITY_DESCRIPTORS } from \"../capabilities\";\nimport type { ProviderRegistration } from \"./types\";\n\nexport const noneProvider: ProviderRegistration = {\n backend: \"none\",\n exactResumeMode: \"none\",\n instanceIdFields: [],\n workspaceCapturePolicy: () => null,\n descriptor: CAPABILITY_DESCRIPTORS.none,\n // No sandbox: nothing to validate, and build() returns undefined. The factory\n // short-circuits on \"none\" before calling build, but we keep build honest.\n validateCredentials() {},\n build() {\n return undefined;\n },\n};\n","import {\n ConnectionConfig,\n Sandbox as ProviderSandbox,\n SandboxApiException,\n createDefaultAdapterFactory,\n type AdapterFactory,\n type ConnectionConfigOptions,\n type CreateSandboxRequest,\n type Endpoint,\n type Sandboxes,\n} from \"@alibaba-group/opensandbox\";\nimport { confinedFileReadCommand, parseConfinedFileRead } from \"../confined-file-read\";\nimport {\n Manifest,\n Permissions,\n SandboxArchiveError,\n SandboxConfigurationError,\n SandboxExposedPortUnavailableError,\n SandboxProviderError,\n SandboxUnsupportedFeatureError,\n SandboxWorkspaceReadNotFoundError,\n normalizeRelativePath,\n normalizeSandboxClientCreateArgs,\n recordExposedPortEndpoint,\n resolveSandboxArchiveLimits,\n validateSandboxArchiveLimits,\n type Entry,\n type ExecCommandArgs,\n type ExposedPortEndpoint,\n type MaterializeEntryArgs,\n type SandboxArchiveLimits,\n type SandboxClientCreateArgs,\n type SandboxClientResumeOptions,\n type SandboxDirectoryEntry,\n type SandboxExecResult,\n type SandboxSessionState,\n type ViewImageArgs,\n type WorkspaceArchiveData,\n type WorkspaceArchiveOptions,\n type WriteStdinArgs,\n} from \"@openai/agents/sandbox\";\nimport {\n deserializeManifest,\n elapsedSeconds,\n formatExecResponse,\n imageOutputFromBytes,\n mergeManifestDelta,\n mergeManifestEntryDelta,\n mergeMaterializedEnvironment,\n rehydratePersistedEnvironmentForRuntime,\n serializeManifestRecord,\n serializeRuntimeEnvironmentForPersistence,\n shellQuote,\n toUint8Array,\n truncateOutput,\n} from \"@openai/agents-core/sandbox/internal\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { lstat, readFile as readLocalFile, readdir } from \"node:fs/promises\";\nimport { posix } from \"node:path\";\nimport { SandboxConfigError, SandboxExactResumeInstanceUnavailableError } from \"../errors\";\nimport {\n nextDurableOpId,\n notifyRemoteOperationNotDispatched,\n notifyRemoteOperationTransportSelected,\n type RemoteOperationObservation,\n} from \"../op-correlation\";\nimport { parseOpenSandboxSignedUriPath, redactOpenSandboxSignedUriPath } from \"../stream-port\";\nimport type { RuntimeMetricsHooks } from \"../../metrics\";\nimport {\n SynchronousCommandOutcomeUnknownError,\n type SynchronousCommandPage,\n} from \"../synchronous-command\";\nimport {\n OpenSandboxCommandStreamError,\n OpenSandboxCommandDispatchError,\n withOpenSandboxCommandDispatchProof,\n withOpenSandboxCommandStreamProof,\n} from \"./opensandbox-command-stream\";\n\nconst WORKSPACE_ROOT = \"/workspace\";\nconst PRIVATE_ROOT = \"/tmp/opengeni-private\";\nconst BROWSERD_ROOT = \"/tmp/opengeni-browserd\";\nconst ALLOWED_PRIVATE_ROOTS = [PRIVATE_ROOT, BROWSERD_ROOT] as const;\nconst DEFAULT_EXEC_YIELD_TIME_MS = 10_000;\n/** Lifecycle `commands.run` often spends ~10s on the control plane even for\n * `echo`. Channel-A file/git reads use a 10–20s yield and must not be\n * classified as retained processes just because that round-trip is slow. */\nconst COMMAND_API_SETTLE_GRACE_MS = 30_000;\nconst DEFAULT_WRITE_STDIN_YIELD_TIME_MS = 250;\nconst OPENSANDBOX_STATE_VERSION = 1;\n\nexport type OpenSandboxApplyDiff = (\n input: string,\n diff: string,\n mode?: \"default\" | \"create\",\n) => string;\nlet injectedApplyDiff: OpenSandboxApplyDiff | undefined;\n\nexport function setOpenSandboxApplyDiff(fn: OpenSandboxApplyDiff): void {\n injectedApplyDiff = fn;\n}\n\nexport interface OpenSandboxEditor {\n createFile(\n operation: { path: string; diff: string },\n context?: unknown,\n ): Promise<{ output?: string } | void>;\n updateFile(\n operation: { path: string; diff: string; moveTo?: string },\n context?: unknown,\n ): Promise<{ output?: string } | void>;\n deleteFile(operation: { path: string }, context?: unknown): Promise<{ output?: string } | void>;\n}\n\nexport type OpenSandboxClientOptions = {\n baseUrl: string;\n apiKey: string;\n image: string;\n ttlSeconds: number;\n useServerProxy: boolean;\n /** OSEP-0011 signed URI-mode Channel B. Independent of `useServerProxy`. */\n signedEndpoints?: boolean;\n signedEndpointTtlSeconds?: number;\n /** Laptop/port-forward rewrite for Channel B only. Preserves the signed path. */\n channelBPublicBaseUrl?: string;\n poolRef?: string;\n readyTimeoutSeconds: number;\n resourceLimits: Record<string, string>;\n resourceRequests: Record<string, string>;\n environment?: Record<string, string>;\n exposedPorts?: number[];\n adapterFactory?: AdapterFactory;\n metrics?: RuntimeMetricsHooks;\n};\n\nexport interface OpenSandboxSessionState extends SandboxSessionState {\n stateVersion: typeof OPENSANDBOX_STATE_VERSION;\n sandboxId: string;\n manifest: Manifest;\n environment: Record<string, string>;\n image: string;\n poolRef: string | null;\n providerBindingHash: string;\n workspacePersistence: \"tar\";\n configuredExposedPorts: number[];\n workspaceReady: boolean;\n expiresAt: string | null;\n}\n\ntype ProcessEvent = { stream: \"stdout\" | \"stderr\"; text: string; commandOutput?: false };\ntype ProcessOutcome = {\n exitCode: number | null;\n error?: unknown;\n uncertain?: boolean;\n};\ntype RetainedProcess = {\n opId: string;\n sessionId: number | null;\n /** The launch client, never a later reconnect or active route. */\n provider: ProviderSandbox | null;\n /** Physical terminal proof survives native alias retirement. It neither\n * consumes output nor proves that the event stream was complete. */\n physicalOutcome: { exitCode: number; error?: unknown } | null;\n failureCause?: unknown;\n startedAt: number;\n events: ProcessEvent[];\n cursor: number;\n executionId: string | null;\n executionIdReady: Promise<string | null>;\n resolveExecutionId: (value: string | null) => void;\n completed: Promise<ProcessOutcome>;\n settled: boolean;\n transportUncertain: boolean;\n /** Status can prove physical exit, never reconstruct a lost event stream. */\n outputUnavailable: boolean;\n outputCursor: { stdout: number; stderr: number };\n};\n\nfunction canonicalBaseUrl(value: string): string {\n const url = new URL(value);\n url.hash = \"\";\n url.search = \"\";\n url.pathname = url.pathname.replace(/\\/+$/u, \"\");\n return url.toString().replace(/\\/$/u, \"\");\n}\n\nfunction providerBindingHash(baseUrl: string): string {\n return createHash(\"sha256\").update(canonicalBaseUrl(baseUrl)).digest(\"hex\");\n}\n\nfunction connectionOptions(input: OpenSandboxClientOptions): ConnectionConfigOptions {\n return {\n domain: canonicalBaseUrl(input.baseUrl),\n apiKey: input.apiKey,\n requestTimeoutSeconds: input.readyTimeoutSeconds,\n useServerProxy: input.useServerProxy,\n disableMetrics: true,\n };\n}\n\nasync function withLifecycle<T>(\n options: OpenSandboxClientOptions,\n fn: (sandboxes: Sandboxes) => Promise<T>,\n): Promise<T> {\n const connection = new ConnectionConfig(connectionOptions(options)).withTransportIfMissing();\n try {\n const factory = options.adapterFactory ?? createDefaultAdapterFactory();\n const stack = factory.createLifecycleStack({\n connectionConfig: connection,\n lifecycleBaseUrl: connection.getBaseUrl(),\n });\n return await fn(stack.sandboxes);\n } finally {\n await connection.closeTransport();\n }\n}\n\nfunction isNotFound(error: unknown): boolean {\n return error instanceof SandboxApiException && error.statusCode === 404;\n}\n\nfunction assertSupportedProviderState(\n info: { status?: { state?: unknown } },\n sandboxId: string,\n): void {\n const state = info.status?.state;\n if (state !== \"Running\" && state !== \"Creating\") {\n throw new SandboxExactResumeInstanceUnavailableError(\"opensandbox\", sandboxId);\n }\n}\n\nfunction normalizeConfiguredPorts(ports: readonly number[] | undefined): number[] {\n return [\n ...new Set(\n (ports ?? []).filter((port) => Number.isInteger(port) && port > 0 && port <= 65_535),\n ),\n ].sort((left, right) => left - right);\n}\n\nfunction assertNoSnapshot(args: ReturnType<typeof normalizeSandboxClientCreateArgs>): void {\n if (args.snapshot && (args.snapshot as { type?: unknown }).type !== \"noop\") {\n throw new SandboxUnsupportedFeatureError(\n \"OpenSandbox v1 uses Opengeni portable workspace archives and does not accept SDK snapshot specs.\",\n );\n }\n}\n\nfunction recordSignedEndpointMetric(\n metrics: RuntimeMetricsHooks | undefined,\n input: { outcome: \"minted\" | \"mint_failed\" | \"host_fetch_unauthorized\"; port: number },\n): void {\n try {\n metrics?.onOpenSandboxSignedEndpoint?.(input);\n } catch {\n /* metrics must not affect Channel B */\n }\n}\n\nfunction createRequest(\n options: OpenSandboxClientOptions,\n environment: Record<string, string>,\n): CreateSandboxRequest {\n const common: CreateSandboxRequest = {\n timeout: options.ttlSeconds,\n env: environment,\n metadata: { opengeni: \"true\", backend: \"opensandbox\" },\n resourceLimits: options.resourceLimits,\n resourceRequests: options.resourceRequests,\n ...(options.signedEndpoints ? { secureAccess: true } : {}),\n };\n if (options.poolRef) {\n return {\n ...common,\n extensions: { poolRef: options.poolRef },\n };\n }\n return {\n ...common,\n image: { uri: options.image },\n entrypoint: [\"tail\", \"-f\", \"/dev/null\"],\n };\n}\n\nfunction parseStateString(value: unknown, field: string): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new SandboxConfigError(\"opensandbox\", `persisted OpenSandbox ${field} is invalid`);\n }\n return value;\n}\n\nfunction parseOptionalString(value: unknown, field: string): string | null {\n if (value === null || value === undefined) return null;\n return parseStateString(value, field);\n}\n\nfunction assertStateMatchesOptions(\n state: OpenSandboxSessionState,\n options: OpenSandboxClientOptions,\n): void {\n if (state.providerBindingHash !== providerBindingHash(options.baseUrl)) {\n throw new SandboxConfigError(\n \"opensandbox\",\n \"persisted OpenSandbox provider binding does not match the configured base URL\",\n );\n }\n if (state.image !== options.image) {\n throw new SandboxConfigError(\n \"opensandbox\",\n \"persisted OpenSandbox image does not match OPENGENI_OPENSANDBOX_IMAGE\",\n );\n }\n if (state.poolRef !== (options.poolRef ?? null)) {\n throw new SandboxConfigError(\n \"opensandbox\",\n \"persisted OpenSandbox pool does not match OPENGENI_OPENSANDBOX_POOL_REF\",\n );\n }\n}\n\nfunction isAllowedPrivatePath(absolute: string): boolean {\n return ALLOWED_PRIVATE_ROOTS.some((root) => absolute === root || absolute.startsWith(`${root}/`));\n}\n\nfunction workspacePath(path: string, options: { allowPrivate?: boolean } = {}): string {\n const raw = path.trim();\n if (raw.includes(\"\\0\") || raw.includes(\"\\\\\")) {\n throw new SandboxConfigurationError(`Invalid OpenSandbox path: ${path}`);\n }\n const absolute = raw.startsWith(\"/\") ? posix.normalize(raw) : posix.join(WORKSPACE_ROOT, raw);\n const allowed =\n absolute === WORKSPACE_ROOT ||\n absolute.startsWith(`${WORKSPACE_ROOT}/`) ||\n (options.allowPrivate === true && isAllowedPrivatePath(absolute));\n if (!allowed) {\n throw new SandboxConfigurationError(\n `OpenSandbox path must stay within ${WORKSPACE_ROOT}${options.allowPrivate ? ` or ${ALLOWED_PRIVATE_ROOTS.join(\" or \")}` : \"\"}: ${path}`,\n );\n }\n return absolute;\n}\n\nfunction logicalWorkspacePath(path: string): string {\n const absolute = workspacePath(path);\n return absolute === WORKSPACE_ROOT ? \"\" : absolute.slice(WORKSPACE_ROOT.length + 1);\n}\n\nfunction assertRunAsUnsupported(runAs: string | undefined): void {\n if (runAs?.trim()) {\n throw new SandboxUnsupportedFeatureError(\n `OpenSandbox v1 cannot prove the uid/gid mapping for runAs=\"${runAs.trim()}\"; the operation was not run.`,\n );\n }\n}\n\nfunction commandForArgs(args: ExecCommandArgs): string {\n const requestedShell = args.shell?.trim();\n if (!requestedShell) return args.cmd;\n return `${shellQuote(requestedShell)}${args.login === false ? \"\" : \" -l\"} -c ${shellQuote(args.cmd)}`;\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));\n}\n\nfunction consumeProcessOutput(process: RetainedProcess): {\n output: string;\n stdout: string;\n stderr: string;\n commandStdout: string;\n commandStderr: string;\n outputCursor: {\n expected: { stdout: number; stderr: number };\n next: { stdout: number; stderr: number };\n };\n} {\n const events = process.events.slice(process.cursor);\n process.cursor = process.events.length;\n const commandStdout = events\n .filter((entry) => entry.stream === \"stdout\" && entry.commandOutput !== false)\n .map((entry) => entry.text)\n .join(\"\");\n const commandStderr = events\n .filter((entry) => entry.stream === \"stderr\" && entry.commandOutput !== false)\n .map((entry) => entry.text)\n .join(\"\");\n const expected = { ...process.outputCursor };\n process.outputCursor.stdout += Buffer.byteLength(commandStdout);\n process.outputCursor.stderr += Buffer.byteLength(commandStderr);\n return {\n output: events.map((entry) => entry.text).join(\"\"),\n stdout: events\n .filter((entry) => entry.stream === \"stdout\")\n .map((entry) => entry.text)\n .join(\"\"),\n stderr: events\n .filter((entry) => entry.stream === \"stderr\")\n .map((entry) => entry.text)\n .join(\"\"),\n commandStdout,\n commandStderr,\n outputCursor: { expected, next: { ...process.outputCursor } },\n };\n}\n\nfunction archiveLimitArg(value: number | null): string {\n return value === null ? \"-1\" : String(value);\n}\n\nexport function archiveRestoreScript(): string {\n return String.raw`\nimport os, shutil, sys, tarfile\narchive, root, staging, backup, max_members, max_bytes, excluded_raw = sys.argv[1:]\nmax_members = int(max_members)\nmax_bytes = int(max_bytes)\nexcluded = [p for p in excluded_raw.split(\"\\n\") if p]\nreserved_prefixes = (\".opengeni-restore-\", \".opengeni-old-\")\n\ndef logical(name):\n name = name.replace(\"\\\\\", \"/\")\n while name.startswith(\"./\"):\n name = name[2:]\n if name in (\"\", \".\"):\n return \"\"\n if name.startswith(\"/\"):\n raise ValueError(\"absolute archive member\")\n normalized = os.path.normpath(name).replace(\"\\\\\", \"/\")\n if normalized == \"..\" or normalized.startswith(\"../\"):\n raise ValueError(\"escaping archive member\")\n return normalized\n\ndef protected(name):\n return any(name == p or name.startswith(p + \"/\") for p in excluded)\n\ndef reserved(name):\n first = name.split(\"/\", 1)[0]\n return any(first.startswith(prefix) for prefix in reserved_prefixes)\n\ndef workspace_child(path, prefix):\n root_abs = os.path.abspath(root)\n path_abs = os.path.abspath(path)\n if os.path.dirname(path_abs) != root_abs:\n raise ValueError(\"restore workspace path escaped root\")\n if not os.path.basename(path_abs).startswith(prefix):\n raise ValueError(\"restore workspace path has an invalid prefix\")\n return path_abs\n\ndef exists(path):\n return os.path.lexists(path)\n\nwith tarfile.open(archive, \"r:*\") as tf:\n members = tf.getmembers()\n if max_members >= 0 and len(members) > max_members:\n raise ValueError(\"archive member limit exceeded\")\n total = 0\n checked = []\n for member in members:\n name = logical(member.name)\n if protected(name):\n raise ValueError(\"archive contains an ephemeral path\")\n if reserved(name):\n raise ValueError(\"archive contains a reserved restore path\")\n if not (member.isdir() or member.isreg()):\n raise ValueError(\"archive contains a non-file member\")\n if member.isreg():\n total += member.size\n if max_bytes >= 0 and total > max_bytes:\n raise ValueError(\"archive extracted-byte limit exceeded\")\n checked.append((member, name))\n shutil.rmtree(staging, ignore_errors=True)\n os.makedirs(staging, mode=0o700, exist_ok=False)\n for member, name in checked:\n target = os.path.join(staging, name)\n if member.isdir():\n os.makedirs(target, exist_ok=True)\n os.chmod(target, member.mode & 0o777)\n continue\n os.makedirs(os.path.dirname(target), exist_ok=True)\n source = tf.extractfile(member)\n if source is None:\n raise ValueError(\"archive file has no content\")\n with source, open(target, \"wb\") as dest:\n shutil.copyfileobj(source, dest)\n os.chmod(target, member.mode & 0o777)\n\nif not os.path.isdir(root):\n raise ValueError(\"workspace root does not exist\")\nstaging = workspace_child(staging, \".opengeni-restore-\")\nbackup = workspace_child(backup, \".opengeni-old-\")\nshutil.rmtree(backup, ignore_errors=True)\nos.makedirs(backup, mode=0o700, exist_ok=False)\nmoved_old = []\nmoved_new = []\ntry:\n for name in sorted(os.listdir(root)):\n if name in (os.path.basename(staging), os.path.basename(backup)):\n continue\n os.replace(os.path.join(root, name), os.path.join(backup, name))\n moved_old.append(name)\n for name in sorted(os.listdir(staging)):\n os.replace(os.path.join(staging, name), os.path.join(root, name))\n moved_new.append(name)\nexcept Exception as swap_error:\n rollback_errors = []\n for name in reversed(moved_new):\n current = os.path.join(root, name)\n restored = os.path.join(staging, name)\n try:\n if exists(current):\n os.replace(current, restored)\n except Exception as error:\n rollback_errors.append(str(error))\n for name in reversed(moved_old):\n saved = os.path.join(backup, name)\n current = os.path.join(root, name)\n try:\n if exists(saved):\n os.replace(saved, current)\n except Exception as error:\n rollback_errors.append(str(error))\n if rollback_errors:\n raise RuntimeError(\"workspace restore rollback failed: \" + \"; \".join(rollback_errors)) from swap_error\n raise\nshutil.rmtree(backup)\nshutil.rmtree(staging)\n`;\n}\n\nexport class OpenSandboxSession {\n readonly backendId = \"opensandbox\" as const;\n readonly state: OpenSandboxSessionState;\n private readonly options: OpenSandboxClientOptions;\n get requireHostFetchController(): boolean {\n return this.options.signedEndpoints === true;\n }\n get runtimeMetrics(): RuntimeMetricsHooks | undefined {\n return this.options.metrics;\n }\n private provider: ProviderSandbox | null = null;\n private startPromise: Promise<ProviderSandbox> | null = null;\n private archiveLimits: SandboxArchiveLimits | null | undefined;\n private nextSessionId = 1;\n private readonly processesBySession = new Map<number, RetainedProcess>();\n private readonly processesByOpId = new Map<string, RetainedProcess>();\n private readonly synchronousResults = new WeakMap<object, SynchronousCommandPage>();\n private readonly commandFailureCauses = new WeakMap<object, unknown>();\n private readonly synchronousBanners = new Map<string, SynchronousCommandPage>();\n\n constructor(args: {\n state: OpenSandboxSessionState;\n options: OpenSandboxClientOptions;\n archiveLimits?: SandboxArchiveLimits | null;\n }) {\n this.state = args.state;\n this.options = args.options;\n this.setArchiveLimits(args.archiveLimits);\n }\n\n setArchiveLimits(limits?: SandboxArchiveLimits | null): void {\n validateSandboxArchiveLimits(limits);\n this.archiveLimits = limits;\n }\n\n private async ensureStarted(): Promise<ProviderSandbox> {\n if (this.provider) return this.provider;\n if (!this.startPromise) {\n this.startPromise = ProviderSandbox.connect({\n connectionConfig: connectionOptions(this.options),\n sandboxId: this.state.sandboxId,\n readyTimeoutSeconds: this.options.readyTimeoutSeconds,\n adapterFactory: withOpenSandboxCommandStreamProof(\n this.options.adapterFactory ?? createDefaultAdapterFactory(),\n ),\n })\n .then(async (provider) => {\n const info = await provider.getInfo();\n assertSupportedProviderState(info, this.state.sandboxId);\n if (info.id !== this.state.sandboxId) {\n await provider.close().catch(() => undefined);\n throw new SandboxProviderError(\"OpenSandbox connected to an unexpected sandbox ID\", {\n expectedSandboxId: this.state.sandboxId,\n actualSandboxId: info.id,\n });\n }\n const image = info.image?.uri;\n // Pool-backed BatchSandbox GET responses use \"unknown\" because the CR records a\n // poolRef instead of an inline Pod template. Keep direct-image verification strict.\n const providerReportedImage =\n image && (this.state.poolRef === null || image !== \"unknown\") ? image : null;\n if (providerReportedImage && providerReportedImage !== this.state.image) {\n await provider.close().catch(() => undefined);\n throw new SandboxProviderError(\"OpenSandbox image changed for the persisted sandbox\", {\n sandboxId: this.state.sandboxId,\n });\n }\n const poolRef =\n info.extensions && typeof info.extensions.poolRef === \"string\"\n ? info.extensions.poolRef\n : null;\n if (poolRef !== null && poolRef !== this.state.poolRef) {\n await provider.close().catch(() => undefined);\n throw new SandboxProviderError(\"OpenSandbox pool changed for the persisted sandbox\", {\n sandboxId: this.state.sandboxId,\n });\n }\n this.provider = provider;\n this.state.expiresAt = info.expiresAt?.toISOString() ?? this.state.expiresAt;\n return provider;\n })\n .catch((error) => {\n this.startPromise = null;\n if (isNotFound(error)) {\n throw new SandboxExactResumeInstanceUnavailableError(\n \"opensandbox\",\n this.state.sandboxId,\n );\n }\n throw error;\n });\n }\n return await this.startPromise;\n }\n\n async start(): Promise<void> {\n await this.ensureInitialManifestMaterialized();\n }\n\n async running(): Promise<boolean> {\n try {\n return await withLifecycle(this.options, async (sandboxes) => {\n const info = await sandboxes.getSandbox(this.state.sandboxId);\n return this.state.workspaceReady && info.status.state === \"Running\";\n });\n } catch (error) {\n if (isNotFound(error)) return false;\n throw error;\n }\n }\n\n async renewExpiration(): Promise<string | null> {\n const expiresAt = new Date(Date.now() + this.options.ttlSeconds * 1000).toISOString();\n const response = await withLifecycle(\n this.options,\n async (sandboxes) =>\n await sandboxes.renewSandboxExpiration(this.state.sandboxId, {\n expiresAt,\n }),\n );\n this.state.expiresAt = response.expiresAt?.toISOString() ?? expiresAt;\n return this.state.expiresAt;\n }\n\n async delete(): Promise<void> {\n try {\n await withLifecycle(this.options, async (sandboxes) => {\n await sandboxes.deleteSandbox(this.state.sandboxId);\n });\n } catch (error) {\n if (!isNotFound(error)) throw error;\n } finally {\n await this.close();\n }\n }\n\n async close(): Promise<void> {\n const provider = this.provider;\n this.provider = null;\n this.startPromise = null;\n if (provider) await provider.close();\n }\n\n supportsPty(): boolean {\n return false;\n }\n\n async commandCancellationTransport(): Promise<\"remote_operation\"> {\n return \"remote_operation\";\n }\n\n /** Adapter-owned event pages, never projections of the presentation banner.\n * Reading a receipt does not acknowledge or release its output custody. */\n getSynchronousCommandOutput(result: unknown): SynchronousCommandPage | null {\n return typeof result === \"string\"\n ? (this.synchronousBanners.get(result) ?? null)\n : result && typeof result === \"object\"\n ? (this.synchronousResults.get(result) ?? null)\n : null;\n }\n\n async acknowledgeCommandOutput(result: string): Promise<void> {\n const page = this.synchronousBanners.get(result);\n if (page && !page.collectionUnavailable) this.synchronousBanners.delete(result);\n }\n\n private commandResult(\n process: RetainedProcess,\n consumed: ReturnType<typeof consumeProcessOutput>,\n result: SandboxExecResult,\n ): SandboxExecResult {\n if (\"failureCause\" in process) this.commandFailureCauses.set(result, process.failureCause);\n this.synchronousResults.set(result, {\n stdout: consumed.commandStdout,\n stderr: consumed.commandStderr,\n exitCode: Number.isSafeInteger(result.exitCode) ? result.exitCode! : null,\n ...(result.sessionId !== undefined ? { sessionId: result.sessionId } : {}),\n wallTimeSeconds: result.wallTimeSeconds,\n ...(process.outputUnavailable ? { collectionUnavailable: true } : {}),\n outputCursor: {\n identity: JSON.stringify([this.state.sandboxId, process.opId]),\n ...consumed.outputCursor,\n },\n });\n return result;\n }\n\n private commandBanner(result: SandboxExecResult): string {\n let banner = formatExecResponse(result);\n const page = this.synchronousResults.get(result);\n if (page) {\n // The SDK chooses the opaque Chunk ID. Do not rebind a still-owned\n // receipt on a collision; formatting again performs no provider action.\n while (this.synchronousBanners.has(banner)) banner = formatExecResponse(result);\n this.synchronousBanners.set(banner, page);\n }\n return banner;\n }\n\n private async ensureInitialManifestMaterialized(): Promise<void> {\n const provider = await this.ensureStarted();\n if (this.state.workspaceReady) return;\n await provider.files.createDirectories([{ path: WORKSPACE_ROOT }]);\n for (const [path, entry] of Object.entries(this.state.manifest.entries)) {\n await this.materialize(path, entry);\n }\n this.state.workspaceReady = true;\n }\n private beginCommand(args: ExecCommandArgs): RetainedProcess {\n const opId = nextDurableOpId() ?? `anon_${randomUUID()}`;\n let resolveExecutionId!: (value: string | null) => void;\n const executionIdReady = new Promise<string | null>((resolve) => {\n resolveExecutionId = resolve;\n });\n const process: RetainedProcess = {\n opId,\n sessionId: null,\n provider: null,\n physicalOutcome: null,\n startedAt: Date.now(),\n events: [],\n cursor: 0,\n executionId: null,\n executionIdReady,\n resolveExecutionId,\n completed: Promise.resolve({ exitCode: 1 }),\n settled: false,\n transportUncertain: false,\n outputUnavailable: false,\n outputCursor: { stdout: 0, stderr: 0 },\n };\n let commandInvoked = false;\n this.processesByOpId.set(opId, process);\n // Joined turn cleanup outlives provider/routing alias retirement. Capture\n // this exact process and its launch transport, not a mutable map lookup.\n notifyRemoteOperationTransportSelected({\n cancelExecCommand: async (requestedOpId) => {\n this.assertOperationIdentity(process, requestedOpId);\n return await this.cancelRetainedProcess(process);\n },\n observeExecCommand: async (requestedOpId) => {\n this.assertOperationIdentity(process, requestedOpId);\n return await this.observeRetainedProcess(process);\n },\n });\n process.completed = this.ensureInitialManifestMaterialized()\n .then(async () => {\n const provider = await this.ensureStarted();\n process.provider = provider;\n commandInvoked = true;\n const execution = await withOpenSandboxCommandDispatchProof(provider.commands, () =>\n provider.commands.run(\n commandForArgs(args),\n {\n workingDirectory: args.workdir ? workspacePath(args.workdir) : WORKSPACE_ROOT,\n envs: this.state.environment,\n },\n {\n onInit: (init) => {\n this.bindExecutionIdentity(process, init.id);\n },\n onEvent: (event) => {\n if (!event || typeof event !== \"object\") return;\n const fields = event as Record<string, unknown>;\n if (fields.type === \"init\") this.bindExecutionIdentity(process, fields.text);\n for (const field of [\"id\", \"execution_id\", \"executionId\"] as const) {\n if (fields[field] !== undefined && fields[field] !== process.executionId)\n throw new SandboxProviderError(\"OpenSandbox command event identity mismatch\");\n }\n },\n onStdout: (message) => {\n process.events.push({ stream: \"stdout\", text: message.text });\n },\n onStderr: (message) => {\n process.events.push({ stream: \"stderr\", text: message.text });\n },\n },\n ),\n );\n this.bindExecutionIdentity(process, execution.id);\n const exitCode = execution.exitCode;\n if (!execution.complete || !Number.isSafeInteger(exitCode)) {\n // A resolved transport without its completion envelope is not stream\n // EOF or exit proof. Keep the original execution for status/control.\n process.outputUnavailable = true;\n process.transportUncertain = true;\n return { exitCode: null, uncertain: true };\n }\n const outcome = {\n exitCode: exitCode!,\n ...(execution.error ? { error: execution.error } : {}),\n };\n process.physicalOutcome = outcome;\n return outcome;\n })\n .catch((error) => {\n const notDispatched =\n error instanceof OpenSandboxCommandDispatchError && error.notDispatched;\n const cause = error instanceof OpenSandboxCommandDispatchError ? error.cause : error;\n process.failureCause = cause;\n process.events.push({\n stream: \"stderr\",\n text: `${cause instanceof Error ? cause.message : String(cause)}\\n`,\n commandOutput: false,\n });\n if (\n process.executionId ||\n cause instanceof OpenSandboxCommandStreamError ||\n (commandInvoked && !notDispatched)\n ) {\n process.transportUncertain = true;\n process.outputUnavailable = true;\n process.resolveExecutionId(process.executionId);\n // Keep the genuine original transport/SDK cause with the retained\n // invocation. No first authenticated ID means control stays unknown.\n return { exitCode: null, error: cause, uncertain: true };\n }\n if (notDispatched) notifyRemoteOperationNotDispatched(opId);\n process.resolveExecutionId(null);\n return { exitCode: 1, error: cause };\n })\n .finally(() => {\n if (!process.transportUncertain) {\n process.settled = true;\n this.processesByOpId.delete(opId);\n }\n });\n return process;\n }\n\n private bindExecutionIdentity(process: RetainedProcess, id: unknown): void {\n if (typeof id !== \"string\" || !id.trim())\n throw new OpenSandboxCommandStreamError(\"command execution identity is missing\");\n if (process.executionId !== null && process.executionId !== id)\n throw new OpenSandboxCommandStreamError(\"command execution identity mismatch\");\n if (process.executionId === null) {\n process.executionId = id;\n process.resolveExecutionId(id);\n }\n }\n\n private assertStatusIdentity(statusId: unknown, executionId: string): void {\n if (statusId !== executionId)\n throw new SandboxProviderError(\"OpenSandbox command status identity mismatch\");\n }\n\n private assertOperationIdentity(process: RetainedProcess, opId: string): void {\n if (opId !== process.opId)\n throw new SandboxProviderError(\"OpenSandbox operation identity mismatch\");\n }\n\n private launchProvider(process: RetainedProcess): ProviderSandbox {\n if (!process.provider)\n throw new SandboxProviderError(\"OpenSandbox command launch transport is unavailable\");\n return process.provider;\n }\n\n private async cancelRetainedProcess(process: RetainedProcess): Promise<boolean> {\n if (process.physicalOutcome) return true;\n const executionId = process.executionId ?? (await process.executionIdReady);\n if (!executionId) return process.settled;\n await this.launchProvider(process).commands.interrupt(executionId);\n // Request delivery is advisory; only observeRetainedProcess proves exit.\n return true;\n }\n\n private async observeRetainedProcess(\n process: RetainedProcess,\n ): Promise<RemoteOperationObservation> {\n if (!process.physicalOutcome) {\n const executionId = process.executionId;\n if (!executionId) return { status: \"running\" };\n const status = await this.launchProvider(process).commands.getCommandStatus(executionId);\n this.assertStatusIdentity(status.id, executionId);\n if (status.running !== false || !Number.isSafeInteger(status.exitCode))\n return { status: \"running\" };\n process.physicalOutcome = { exitCode: status.exitCode! };\n }\n return {\n status: \"completed\",\n result: { exitCode: process.physicalOutcome.exitCode },\n // This control-only observer deliberately cannot recover command output.\n // Never substitute its proof for a lossless FS/model result, acknowledge\n // a receipt, advance cursors, or remove the native/routed output holder.\n failure: new SynchronousCommandOutcomeUnknownError(\n process.sessionId,\n { stdout: \"\", stderr: \"\" },\n new Error(\"Physical completion observed without consuming retained command output\"),\n ),\n };\n }\n\n async observeExecCommand(opId: string): Promise<RemoteOperationObservation> {\n const process = this.processesByOpId.get(opId);\n if (!process) throw new SandboxProviderError(\"OpenSandbox operation is not retained\");\n return await this.observeRetainedProcess(process);\n }\n\n private async settleTransportUncertainProcess(process: RetainedProcess): Promise<ProcessOutcome> {\n const executionId = process.executionId ?? (await process.executionIdReady);\n if (!executionId) {\n throw new SandboxProviderError(\n \"OpenSandbox internal command lost its provider execution identity\",\n );\n }\n const provider = this.launchProvider(process);\n while (true) {\n try {\n const status = await provider.commands.getCommandStatus(executionId);\n this.assertStatusIdentity(status.id, executionId);\n if (status.running === false && Number.isSafeInteger(status.exitCode)) {\n if (status.error) {\n process.events.push({\n stream: \"stderr\",\n text: `${status.error}\\n`,\n commandOutput: false,\n });\n }\n process.settled = true;\n process.transportUncertain = false;\n process.physicalOutcome = {\n exitCode: status.exitCode!,\n ...(status.error ? { error: status.error } : {}),\n };\n this.processesByOpId.delete(process.opId);\n return process.physicalOutcome;\n }\n } catch {\n // The provider accepted this exact execution before transport loss. Keep\n // polling its immutable execution ID instead of replaying or cleaning\n // paths that the still-running command may be mutating.\n }\n await delay(DEFAULT_WRITE_STDIN_YIELD_TIME_MS);\n }\n }\n\n private async execToCompletion(args: ExecCommandArgs): Promise<SandboxExecResult> {\n if (args.tty) {\n throw new SandboxUnsupportedFeatureError(\n \"OpenSandbox v1 does not expose a bidirectional PTY; run the command with tty=false.\",\n );\n }\n assertRunAsUnsupported(args.runAs);\n if (args.workdir) workspacePath(args.workdir);\n const process = this.beginCommand(args);\n let outcome = await process.completed;\n if (outcome.uncertain) {\n outcome = await this.settleTransportUncertainProcess(process);\n }\n const consumed = consumeProcessOutput(process);\n const output = truncateOutput(consumed.output, args.maxOutputTokens);\n if (outcome.error && !process.executionId) throw outcome.error;\n return this.commandResult(process, consumed, {\n output: output.text,\n stdout: consumed.stdout,\n stderr: consumed.stderr,\n wallTimeSeconds: elapsedSeconds(process.startedAt),\n exitCode: outcome.exitCode,\n ...(output.originalTokenCount !== undefined\n ? { originalTokenCount: output.originalTokenCount }\n : {}),\n });\n }\n\n async exec(args: ExecCommandArgs): Promise<SandboxExecResult> {\n if (args.tty) {\n throw new SandboxUnsupportedFeatureError(\n \"OpenSandbox v1 does not expose a bidirectional PTY; run the command with tty=false.\",\n );\n }\n assertRunAsUnsupported(args.runAs);\n if (args.workdir) workspacePath(args.workdir);\n const process = this.beginCommand(args);\n const requestedYieldMs = args.yieldTimeMs ?? DEFAULT_EXEC_YIELD_TIME_MS;\n const yieldTimeMs =\n requestedYieldMs >= DEFAULT_EXEC_YIELD_TIME_MS\n ? requestedYieldMs + COMMAND_API_SETTLE_GRACE_MS\n : requestedYieldMs;\n const outcome = await Promise.race([\n process.completed.then((value) => ({ done: true as const, value })),\n delay(yieldTimeMs).then(() => ({ done: false as const })),\n ]);\n const consumed = consumeProcessOutput(process);\n const output = truncateOutput(consumed.output, args.maxOutputTokens);\n if (outcome.done) {\n if (outcome.value.uncertain) {\n const sessionId = this.nextSessionId++;\n process.sessionId = sessionId;\n this.processesBySession.set(sessionId, process);\n return this.commandResult(process, consumed, {\n output: output.text,\n stdout: consumed.stdout,\n stderr: consumed.stderr,\n wallTimeSeconds: elapsedSeconds(process.startedAt),\n sessionId,\n ...(output.originalTokenCount !== undefined\n ? { originalTokenCount: output.originalTokenCount }\n : {}),\n });\n }\n if (outcome.value.error && !process.executionId) throw outcome.value.error;\n return this.commandResult(process, consumed, {\n output: output.text,\n stdout: consumed.stdout,\n stderr: consumed.stderr,\n wallTimeSeconds: elapsedSeconds(process.startedAt),\n exitCode: outcome.value.exitCode,\n ...(output.originalTokenCount !== undefined\n ? { originalTokenCount: output.originalTokenCount }\n : {}),\n });\n }\n const sessionId = this.nextSessionId++;\n process.sessionId = sessionId;\n this.processesBySession.set(sessionId, process);\n return this.commandResult(process, consumed, {\n output: output.text,\n stdout: consumed.stdout,\n stderr: consumed.stderr,\n wallTimeSeconds: elapsedSeconds(process.startedAt),\n sessionId,\n ...(output.originalTokenCount !== undefined\n ? { originalTokenCount: output.originalTokenCount }\n : {}),\n });\n }\n\n async execCommand(args: ExecCommandArgs): Promise<string> {\n return this.commandBanner(await this.exec(args));\n }\n\n hasRetainedProcess(providerSessionId: number): boolean {\n return this.processesBySession.has(providerSessionId);\n }\n\n async cancelExecCommand(opId: string): Promise<boolean> {\n const process = this.processesByOpId.get(opId);\n if (!process) return false;\n return await this.cancelRetainedProcess(process);\n }\n\n async writeStdin(args: WriteStdinArgs): Promise<string> {\n const process = this.processesBySession.get(args.sessionId);\n if (!process) {\n return formatExecResponse({\n output: `write_stdin failed: session not found: ${args.sessionId}`,\n wallTimeSeconds: 0,\n exitCode: 1,\n });\n }\n const chars = args.chars ?? \"\";\n const unsupportedChars = chars.replaceAll(\"\\u0003\", \"\");\n if (unsupportedChars.length > 0) {\n throw new SandboxUnsupportedFeatureError(\n \"OpenSandbox v1 retained commands support polling and Ctrl-C interrupt, not arbitrary stdin.\",\n );\n }\n const startedAt = Date.now();\n if (chars.includes(\"\\u0003\")) {\n const executionId = process.executionId ?? (await process.executionIdReady);\n if (executionId) {\n const provider = this.launchProvider(process);\n await provider.commands.interrupt(executionId);\n }\n }\n if (process.transportUncertain) {\n const executionId = process.executionId;\n if (!executionId) {\n throw new SandboxProviderError(\n \"OpenSandbox retained command lost its provider execution identity\",\n );\n }\n const provider = this.launchProvider(process);\n const status = await provider.commands.getCommandStatus(executionId);\n this.assertStatusIdentity(status.id, executionId);\n if (status.error) {\n process.events.push({ stream: \"stderr\", text: `${status.error}\\n`, commandOutput: false });\n }\n const consumed = consumeProcessOutput(process);\n const output = truncateOutput(consumed.output, args.maxOutputTokens);\n if (status.running !== false || !Number.isSafeInteger(status.exitCode)) {\n return this.commandBanner(\n this.commandResult(process, consumed, {\n output: output.text,\n stdout: consumed.stdout,\n stderr: consumed.stderr,\n wallTimeSeconds: elapsedSeconds(startedAt),\n sessionId: args.sessionId,\n ...(output.originalTokenCount !== undefined\n ? { originalTokenCount: output.originalTokenCount }\n : {}),\n }),\n );\n }\n process.settled = true;\n process.physicalOutcome = { exitCode: status.exitCode! };\n this.processesBySession.delete(args.sessionId);\n this.processesByOpId.delete(process.opId);\n return this.commandBanner(\n this.commandResult(process, consumed, {\n output: output.text,\n stdout: consumed.stdout,\n stderr: consumed.stderr,\n wallTimeSeconds: elapsedSeconds(startedAt),\n exitCode: status.exitCode!,\n ...(output.originalTokenCount !== undefined\n ? { originalTokenCount: output.originalTokenCount }\n : {}),\n }),\n );\n }\n const outcome = await Promise.race([\n process.completed.then((value) => ({ done: true as const, value })),\n delay(args.yieldTimeMs ?? DEFAULT_WRITE_STDIN_YIELD_TIME_MS).then(() => ({\n done: false as const,\n })),\n ]);\n const consumed = consumeProcessOutput(process);\n const output = truncateOutput(consumed.output, args.maxOutputTokens);\n if (outcome.done) {\n // Loss can arrive while this read awaits completion, not only before it.\n // The same alias remains available for exact status/control observation.\n if (!outcome.value.uncertain) this.processesBySession.delete(args.sessionId);\n return this.commandBanner(\n this.commandResult(process, consumed, {\n output: output.text,\n stdout: consumed.stdout,\n stderr: consumed.stderr,\n wallTimeSeconds: elapsedSeconds(startedAt),\n ...(outcome.value.uncertain\n ? { sessionId: args.sessionId }\n : { exitCode: outcome.value.exitCode }),\n ...(output.originalTokenCount !== undefined\n ? { originalTokenCount: output.originalTokenCount }\n : {}),\n }),\n );\n }\n return this.commandBanner(\n this.commandResult(process, consumed, {\n output: output.text,\n stdout: consumed.stdout,\n stderr: consumed.stderr,\n wallTimeSeconds: elapsedSeconds(startedAt),\n sessionId: args.sessionId,\n ...(output.originalTokenCount !== undefined\n ? { originalTokenCount: output.originalTokenCount }\n : {}),\n }),\n );\n }\n\n async writeStdinForProcessControl(args: WriteStdinArgs): Promise<string> {\n return await this.writeStdin(args);\n }\n\n async readFile(args: { path: string; runAs?: string; maxBytes?: number }): Promise<Uint8Array> {\n assertRunAsUnsupported(args.runAs);\n const absolute = workspacePath(args.path, { allowPrivate: true });\n const root = [WORKSPACE_ROOT, ...ALLOWED_PRIVATE_ROOTS].find(\n (candidate) => absolute === candidate || absolute.startsWith(`${candidate}/`),\n )!;\n const maxBytes = args.maxBytes ?? 512 * 1024 * 1024;\n if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 512 * 1024 * 1024) {\n throw new SandboxConfigurationError(\"Invalid OpenSandbox read byte limit\");\n }\n const result = await this.exec({\n cmd: confinedFileReadCommand(root, absolute.slice(root.length + 1), maxBytes),\n login: false,\n yieldTimeMs: 30_000,\n maxOutputTokens: Math.ceil((maxBytes * 4) / 3) + 1024,\n });\n if (result.exitCode === 66) {\n throw new SandboxWorkspaceReadNotFoundError(\"OpenSandbox workspace path not found\");\n }\n if (result.exitCode === 67) {\n throw new SandboxConfigurationError(\"path resolves outside workspace or contains a symlink\");\n }\n const bytes =\n result.sessionId === undefined && result.exitCode === 0\n ? parseConfinedFileRead(result.stdout, maxBytes)\n : null;\n if (!bytes) {\n // Preserve the native cause without treating it as terminal/no-dispatch\n // proof. The original uncertain command and output remain retained.\n if (this.commandFailureCauses.has(result)) throw this.commandFailureCauses.get(result);\n throw new SandboxProviderError(\"OpenSandbox confined file read unavailable\");\n }\n return bytes;\n }\n\n private async rethrowFilesystemReadError(\n provider: ProviderSandbox,\n error: unknown,\n ): Promise<never> {\n if (isNotFound(error)) {\n // A filesystem 404 is optional-path absence only while the exact provider\n // still exists. Provider loss and lifecycle failures must reach recovery.\n const info = await provider.getInfo();\n assertSupportedProviderState(info, this.state.sandboxId);\n if (info.id === this.state.sandboxId) {\n throw new SandboxWorkspaceReadNotFoundError(\"OpenSandbox workspace path not found\");\n }\n }\n throw error;\n }\n\n async writeFile(args: {\n path: string;\n content: string | Uint8Array;\n createParents?: boolean;\n append?: boolean;\n }): Promise<number> {\n if (args.append) {\n throw new SandboxUnsupportedFeatureError(\n \"OpenSandbox v1 raw file writes do not support append; use a shell command for append semantics.\",\n );\n }\n const provider = await this.ensureStarted();\n const target = workspacePath(args.path, { allowPrivate: true });\n if (args.createParents ?? true) {\n await provider.files.createDirectories([{ path: posix.dirname(target) }]);\n }\n await provider.files.writeFiles([{ path: target, data: args.content }]);\n return typeof args.content === \"string\"\n ? new TextEncoder().encode(args.content).byteLength\n : args.content.byteLength;\n }\n\n async pathExists(path: string, runAs?: string): Promise<boolean> {\n assertRunAsUnsupported(runAs);\n const provider = await this.ensureStarted();\n const target = workspacePath(path, { allowPrivate: true });\n try {\n const info = await provider.files.getFileInfo([target]);\n return Boolean(info[target]);\n } catch (error) {\n if (isNotFound(error)) return false;\n throw error;\n }\n }\n\n async listDir(args: { path: string; runAs?: string }): Promise<SandboxDirectoryEntry[]> {\n assertRunAsUnsupported(args.runAs);\n const provider = await this.ensureStarted();\n const absolute = workspacePath(args.path);\n const absoluteOutput = args.path.trim().startsWith(\"/\");\n const entries = await provider.files\n .listDirectory({\n path: absolute,\n depth: 1,\n })\n .catch((error) => this.rethrowFilesystemReadError(provider, error));\n return entries.map((entry) => {\n const entryPath = workspacePath(entry.path);\n return {\n name: posix.basename(entryPath),\n path: absoluteOutput\n ? entryPath\n : entryPath === WORKSPACE_ROOT\n ? \"\"\n : entryPath.slice(WORKSPACE_ROOT.length + 1),\n type: entry.type === \"directory\" ? \"dir\" : entry.type === \"file\" ? \"file\" : \"other\",\n };\n });\n }\n\n async viewImage(args: ViewImageArgs) {\n assertRunAsUnsupported(args.runAs);\n const bytes = await this.readFile({ path: args.path });\n return imageOutputFromBytes(args.path, bytes);\n }\n\n private async deletePath(path: string): Promise<void> {\n const provider = await this.ensureStarted();\n const target = workspacePath(path, { allowPrivate: true });\n const info = await provider.files.getFileInfo([target]);\n const entry = info[target];\n if (!entry) return;\n if (entry.type === \"directory\") await provider.files.deleteDirectories([target]);\n else await provider.files.deleteFiles([target]);\n }\n\n createEditor(runAs?: string): OpenSandboxEditor {\n assertRunAsUnsupported(runAs);\n const applyDiff = injectedApplyDiff;\n if (!applyDiff) {\n throw new Error(\n \"opensandbox createEditor: applyDiff not injected (the runtime barrel must call setOpenSandboxApplyDiff before an agent turn binds the filesystem capability)\",\n );\n }\n const readText = async (path: string): Promise<string> =>\n new TextDecoder().decode(await this.readFile({ path }));\n return {\n createFile: async (operation) => {\n if (await this.pathExists(operation.path)) {\n throw new Error(`opensandbox createFile: file already exists: ${operation.path}`);\n }\n await this.writeFile({\n path: operation.path,\n content: applyDiff(\"\", operation.diff, \"create\"),\n createParents: true,\n });\n return {};\n },\n updateFile: async (operation) => {\n const next = applyDiff(await readText(operation.path), operation.diff);\n const destination = operation.moveTo ?? operation.path;\n await this.writeFile({\n path: destination,\n content: next,\n createParents: true,\n });\n if (operation.moveTo && operation.moveTo !== operation.path) {\n await this.deletePath(operation.path);\n }\n return {};\n },\n deleteFile: async (operation) => {\n await this.deletePath(operation.path);\n return {};\n },\n };\n }\n\n private async applyPermissions(path: string, entry: Entry): Promise<void> {\n if (entry.group !== undefined) {\n throw new SandboxUnsupportedFeatureError(\n \"OpenSandbox v1 does not materialize named manifest groups.\",\n );\n }\n if (entry.permissions === undefined) return;\n const provider = await this.ensureStarted();\n await provider.files.setPermissions([\n { path, mode: new Permissions(entry.permissions).toMode() & 0o777 },\n ]);\n }\n\n private async copyLocalDirectory(source: string, destination: string): Promise<void> {\n const stats = await lstat(source);\n if (stats.isSymbolicLink()) {\n throw new SandboxUnsupportedFeatureError(\n `OpenSandbox local_dir source contains a symbolic link: ${source}`,\n );\n }\n if (!stats.isDirectory()) {\n throw new SandboxConfigurationError(\n `OpenSandbox local_dir source is not a directory: ${source}`,\n );\n }\n const provider = await this.ensureStarted();\n await provider.files.createDirectories([{ path: destination }]);\n const entries = await readdir(source, { withFileTypes: true });\n for (const entry of entries) {\n const sourcePath = `${source.replace(/\\/$/u, \"\")}/${entry.name}`;\n const destinationPath = posix.join(destination, entry.name);\n if (entry.isSymbolicLink()) {\n throw new SandboxUnsupportedFeatureError(\n `OpenSandbox local_dir source contains a symbolic link: ${sourcePath}`,\n );\n }\n if (entry.isDirectory()) {\n await this.copyLocalDirectory(sourcePath, destinationPath);\n } else if (entry.isFile()) {\n await provider.files.writeFiles([\n {\n path: destinationPath,\n data: new Uint8Array(await readLocalFile(sourcePath)),\n },\n ]);\n } else {\n throw new SandboxUnsupportedFeatureError(\n `OpenSandbox local_dir source contains an unsupported file type: ${sourcePath}`,\n );\n }\n }\n }\n\n private async materialize(path: string, entry: Entry): Promise<void> {\n const target = workspacePath(path);\n const provider = await this.ensureStarted();\n if (entry.type === \"dir\") {\n await provider.files.createDirectories([{ path: target }]);\n for (const [childPath, child] of Object.entries(entry.children ?? {})) {\n await this.materialize(posix.join(path, childPath), child);\n }\n await this.applyPermissions(target, entry);\n return;\n }\n if (entry.type === \"file\") {\n await provider.files.createDirectories([{ path: posix.dirname(target) }]);\n await provider.files.writeFiles([{ path: target, data: entry.content }]);\n await this.applyPermissions(target, entry);\n return;\n }\n if (entry.type === \"local_file\") {\n const stats = await lstat(entry.src);\n if (!stats.isFile() || stats.isSymbolicLink()) {\n throw new SandboxUnsupportedFeatureError(\n `OpenSandbox local_file source must be a regular non-symlink file: ${entry.src}`,\n );\n }\n await provider.files.createDirectories([{ path: posix.dirname(target) }]);\n await provider.files.writeFiles([\n { path: target, data: new Uint8Array(await readLocalFile(entry.src)) },\n ]);\n await this.applyPermissions(target, entry);\n return;\n }\n if (entry.type === \"local_dir\") {\n await this.copyLocalDirectory(entry.src, target);\n await this.applyPermissions(target, entry);\n return;\n }\n if (entry.type === \"git_repo\") {\n const temp = `/tmp/opengeni-git-${randomUUID()}`;\n const subpath = entry.subpath ? normalizeRelativePath(entry.subpath) : null;\n const script = [\n \"set -eu\",\n `rm -rf -- ${shellQuote(temp)} ${shellQuote(target)}`,\n `git clone --no-checkout --depth=1 ${shellQuote(entry.repo)} ${shellQuote(temp)}`,\n ...(entry.ref\n ? [\n `git -C ${shellQuote(temp)} fetch --depth=1 origin ${shellQuote(entry.ref)}`,\n `git -C ${shellQuote(temp)} checkout --detach FETCH_HEAD`,\n ]\n : [`git -C ${shellQuote(temp)} checkout --detach HEAD`]),\n subpath\n ? `mkdir -p -- ${shellQuote(target)} && cp -a -- ${shellQuote(`${temp}/${subpath}/.`)} ${shellQuote(target)}`\n : `mv -- ${shellQuote(temp)} ${shellQuote(target)}`,\n subpath ? `rm -rf -- ${shellQuote(temp)}` : \":\",\n ].join(\"\\n\");\n const result = await this.execToCompletion({\n cmd: script,\n maxOutputTokens: 2_000,\n });\n if (typeof result.exitCode !== \"number\" || result.exitCode !== 0) {\n throw new SandboxProviderError(\"OpenSandbox git repository materialization failed\", {\n path,\n exitCode: result.exitCode ?? null,\n });\n }\n await this.applyPermissions(target, entry);\n return;\n }\n throw new SandboxUnsupportedFeatureError(\n `OpenSandbox v1 does not support manifest mount entry type \"${entry.type}\".`,\n );\n }\n\n async materializeEntry(args: MaterializeEntryArgs): Promise<void> {\n assertRunAsUnsupported(args.runAs);\n const logicalPath = logicalWorkspacePath(args.path);\n await this.materialize(logicalPath, args.entry);\n this.state.manifest = mergeManifestEntryDelta(this.state.manifest, logicalPath, args.entry);\n }\n\n async applyManifest(manifest: Manifest, runAs?: string): Promise<void> {\n assertRunAsUnsupported(runAs);\n await this.ensureInitialManifestMaterialized();\n if (manifest.root !== this.state.manifest.root) {\n throw new SandboxConfigurationError(\n `OpenSandbox manifest root must remain ${this.state.manifest.root}.`,\n );\n }\n if (\n manifest.users.length > 0 ||\n manifest.groups.length > 0 ||\n manifest.extraPathGrants.length > 0\n ) {\n throw new SandboxUnsupportedFeatureError(\n \"OpenSandbox v1 does not support manifest users, groups, or host path grants.\",\n );\n }\n for (const [path, entry] of Object.entries(manifest.entries)) {\n await this.materialize(path, entry);\n }\n const nextManifest = mergeManifestDelta(this.state.manifest, manifest);\n this.state.environment = await mergeMaterializedEnvironment(\n this.state.manifest,\n nextManifest,\n this.state.environment,\n );\n this.state.manifest = nextManifest;\n }\n\n private resolvedArchiveLimits(options?: WorkspaceArchiveOptions) {\n return resolveSandboxArchiveLimits(\n options?.archiveLimits === undefined ? this.archiveLimits : options.archiveLimits,\n );\n }\n\n async persistWorkspaceTar(): Promise<Uint8Array> {\n const archivePath = `${PRIVATE_ROOT}/capture-${randomUUID()}.tar`;\n const excludes = [\n ...this.state.manifest.ephemeralPersistencePaths(),\n \".opengeni-old-*\",\n \".opengeni-restore-*\",\n ].sort();\n const excludeArgs = excludes.flatMap((path) => [\n shellQuote(`--exclude=${path}`),\n shellQuote(`--exclude=./${path}`),\n ]);\n const script = String.raw`set -eu\nmkdir -p ${shellQuote(PRIVATE_ROOT)}\ncd ${shellQuote(WORKSPACE_ROOT)}\n# Sockets (gpg-agent) and symlinks are normal in a live /workspace. GNU tar\n# ignores sockets (exit 0) and --hard-dereference stores symlink targets as\n# files. Fifos/devices are not portable archive members and can hang tar.\nif find . -xdev -mindepth 1 \\( -type p -o -type b -o -type c \\) -print -quit | grep -q .; then\n printf 'workspace contains a non-portable fifo or device\\n' >&2\n exit 65\nfi\ntar ${excludeArgs.join(\" \")} --sort=name --mtime='@0' --owner=0 --group=0 --numeric-owner --hard-dereference --format=gnu -cf ${shellQuote(archivePath)} .`;\n try {\n const result = await this.execToCompletion({\n cmd: script,\n maxOutputTokens: 1_000,\n });\n if (result.exitCode !== 0) {\n throw new SandboxArchiveError(\"OpenSandbox workspace archive capture failed\", {\n sandboxId: this.state.sandboxId,\n exitCode: result.exitCode ?? null,\n });\n }\n const bytes = await this.readFile({ path: archivePath });\n const limits = this.resolvedArchiveLimits();\n if (limits && limits.maxInputBytes !== null && bytes.byteLength > limits.maxInputBytes) {\n throw new SandboxArchiveError(\"OpenSandbox workspace archive exceeds maxInputBytes\", {\n archiveBytes: bytes.byteLength,\n maxInputBytes: limits.maxInputBytes,\n });\n }\n return bytes;\n } finally {\n await this.deletePath(archivePath).catch(() => undefined);\n }\n }\n\n async persistWorkspace(): Promise<Uint8Array> {\n return await this.persistWorkspaceTar();\n }\n\n async hydrateWorkspace(\n data: WorkspaceArchiveData,\n options: WorkspaceArchiveOptions = {},\n ): Promise<void> {\n const bytes = await toUint8Array(data);\n const limits = this.resolvedArchiveLimits(options);\n if (limits && limits.maxInputBytes !== null && bytes.byteLength > limits.maxInputBytes) {\n throw new SandboxArchiveError(\"OpenSandbox workspace archive exceeds maxInputBytes\", {\n archiveBytes: bytes.byteLength,\n maxInputBytes: limits.maxInputBytes,\n });\n }\n const archivePath = `${PRIVATE_ROOT}/restore-${randomUUID()}.tar`;\n const stagingPath = `${WORKSPACE_ROOT}/.opengeni-restore-${randomUUID()}`;\n const backupPath = `${WORKSPACE_ROOT}/.opengeni-old-${randomUUID()}`;\n await this.writeFile({\n path: archivePath,\n content: bytes,\n createParents: true,\n });\n const excluded = [...this.state.manifest.ephemeralPersistencePaths()].sort().join(\"\\n\");\n const command = [\n \"python3\",\n \"-c\",\n shellQuote(archiveRestoreScript()),\n shellQuote(archivePath),\n shellQuote(WORKSPACE_ROOT),\n shellQuote(stagingPath),\n shellQuote(backupPath),\n shellQuote(archiveLimitArg(limits?.maxMembers ?? null)),\n shellQuote(archiveLimitArg(limits?.maxExtractedBytes ?? null)),\n shellQuote(excluded),\n ].join(\" \");\n try {\n const result = await this.execToCompletion({\n cmd: command,\n maxOutputTokens: 2_000,\n });\n if (result.exitCode !== 0) {\n throw new SandboxArchiveError(\"OpenSandbox workspace archive restore failed\", {\n sandboxId: this.state.sandboxId,\n exitCode: result.exitCode ?? null,\n stderr: result.stderr.slice(-1_000),\n });\n }\n this.state.workspaceReady = true;\n } finally {\n await this.deletePath(archivePath).catch(() => undefined);\n await this.deletePath(stagingPath).catch(() => undefined);\n await this.deletePath(backupPath).catch(() => undefined);\n }\n }\n\n async resolveExposedPort(port: number): Promise<ExposedPortEndpoint> {\n if (!Number.isInteger(port) || port <= 0 || port > 65_535) {\n throw new SandboxExposedPortUnavailableError(`Invalid OpenSandbox port: ${port}`);\n }\n const signed = this.options.signedEndpoints === true;\n try {\n const endpoint = await withLifecycle(this.options, async (sandboxes) => {\n if (signed) {\n const expires =\n Math.floor(Date.now() / 1000) + (this.options.signedEndpointTtlSeconds ?? 600);\n return await sandboxes.getSignedEndpoint(this.state.sandboxId, port, expires);\n }\n return await sandboxes.getSandboxEndpoint(\n this.state.sandboxId,\n port,\n this.options.useServerProxy,\n );\n });\n const rewrite = channelBRewriteTarget(this.options);\n const resolved = recordExposedPortEndpoint(\n this.state,\n withOpenSandboxDesktopViewerPath(\n endpointToExposedPort(endpoint, rewrite.baseUrl, rewrite.rewriteToBaseUrl),\n port,\n signed,\n ),\n port,\n );\n const parsed = signed\n ? parseOpenSandboxSignedUriPath(typeof resolved.path === \"string\" ? resolved.path : \"\")\n : null;\n console.info(\"opensandbox channel-b resolve\", {\n mode: signed ? \"signed\" : \"server-proxy\",\n sandboxId: this.state.sandboxId,\n port,\n expiresAtSeconds: parsed?.expiresAtSeconds ?? null,\n path:\n typeof resolved.path === \"string\" ? redactOpenSandboxSignedUriPath(resolved.path) : null,\n });\n if (signed) {\n recordSignedEndpointMetric(this.options.metrics, { outcome: \"minted\", port });\n }\n return resolved;\n } catch (error) {\n if (signed) {\n recordSignedEndpointMetric(this.options.metrics, { outcome: \"mint_failed\", port });\n }\n throw error;\n }\n }\n}\n\n/** noVNC on the OpenSandbox lifecycle proxy serves HTML at the port root\n * (`…/proxy/6080`). The RFB socket is `…/websockify`. Mint `vnc.html` so the\n * existing SDK `desktopSocketUrl` rewrite dials that socket. Signed URI-mode\n * ingress is a reverse proxy to the box port and does not need that HTML\n * viewer path. Modal/Daytona edges at `/` stay untouched. */\nconst OPENSANDBOX_DESKTOP_STREAM_PORT = 6080;\n\nfunction channelBRewriteTarget(options: OpenSandboxClientOptions): {\n baseUrl: string;\n rewriteToBaseUrl: boolean;\n} {\n if (options.signedEndpoints) {\n if (options.channelBPublicBaseUrl) {\n return { baseUrl: options.channelBPublicBaseUrl, rewriteToBaseUrl: true };\n }\n return { baseUrl: options.baseUrl, rewriteToBaseUrl: false };\n }\n return { baseUrl: options.baseUrl, rewriteToBaseUrl: options.useServerProxy };\n}\n\nfunction withOpenSandboxDesktopViewerPath(\n endpoint: ExposedPortEndpoint,\n port: number,\n signedEndpoints: boolean,\n): ExposedPortEndpoint {\n if (signedEndpoints) return endpoint;\n if (port !== OPENSANDBOX_DESKTOP_STREAM_PORT) return endpoint;\n const rawPath =\n typeof endpoint.path === \"string\" && endpoint.path.length > 0 ? endpoint.path : \"/\";\n const prefix = (rawPath.startsWith(\"/\") ? rawPath : `/${rawPath}`).replace(/\\/+$/u, \"\");\n if (prefix.length === 0) return endpoint;\n if (/\\/vnc(_lite)?\\.html$/u.test(prefix) || prefix.endsWith(\"/websockify\")) {\n return endpoint;\n }\n const path = `${prefix}/vnc.html`;\n const url =\n typeof endpoint.url === \"string\" && endpoint.url.length > 0\n ? `${endpoint.url.replace(/\\/+$/u, \"\")}/vnc.html`\n : endpoint.url;\n return { ...endpoint, path, ...(url ? { url } : {}) };\n}\n\nfunction endpointToExposedPort(\n endpoint: Endpoint,\n baseUrl: string,\n rewriteToBaseUrl: boolean,\n): ExposedPortEndpoint {\n const base = new URL(baseUrl);\n const reported = new URL(`${base.protocol}//${endpoint.endpoint}`);\n // Channel B is browser → provider-tunnel direct. When we use the lifecycle\n // server proxy, rewrite the advertised host to the configured base URL so a\n // local port-forward (or in-cluster DNS) is what the viewer actually opens.\n const url = rewriteToBaseUrl ? new URL(`${reported.pathname}${reported.search}`, base) : reported;\n const tls = url.protocol === \"https:\" || url.protocol === \"wss:\";\n return {\n host: url.hostname,\n port: url.port ? Number(url.port) : tls ? 443 : 80,\n tls,\n ...(url.pathname && url.pathname !== \"/\" ? { path: url.pathname } : {}),\n ...(url.search.length > 1 ? { query: url.search.slice(1) } : {}),\n protocol: url.protocol.replace(/:$/u, \"\"),\n url: url.toString(),\n ...(endpoint.headers ? { headers: { ...endpoint.headers } } : {}),\n };\n}\n\nexport class OpenSandboxClient {\n readonly backendId = \"opensandbox\" as const;\n readonly supportsDefaultOptions = false;\n private readonly options: OpenSandboxClientOptions;\n\n constructor(options: OpenSandboxClientOptions) {\n this.options = {\n ...options,\n baseUrl: canonicalBaseUrl(options.baseUrl),\n environment: { ...(options.environment ?? {}) },\n exposedPorts: normalizeConfiguredPorts(options.exposedPorts),\n resourceLimits: { ...options.resourceLimits },\n resourceRequests: { ...options.resourceRequests },\n };\n }\n\n async create(\n args?: SandboxClientCreateArgs,\n manifestOptions?: Record<string, unknown>,\n ): Promise<OpenSandboxSession> {\n const normalized = normalizeSandboxClientCreateArgs(args as never, manifestOptions);\n assertNoSnapshot(normalized);\n const manifest = normalized.manifest;\n if (manifest.root !== WORKSPACE_ROOT) {\n throw new SandboxConfigurationError(`OpenSandbox manifest root must be ${WORKSPACE_ROOT}.`);\n }\n if (\n manifest.users.length > 0 ||\n manifest.groups.length > 0 ||\n manifest.extraPathGrants.length > 0\n ) {\n throw new SandboxUnsupportedFeatureError(\n \"OpenSandbox v1 does not support manifest users, groups, or host path grants.\",\n );\n }\n const environment = {\n ...(this.options.environment ?? {}),\n ...(await manifest.resolveEnvironment()),\n };\n const created = await withLifecycle(\n this.options,\n async (sandboxes) => await sandboxes.createSandbox(createRequest(this.options, environment)),\n );\n const state: OpenSandboxSessionState = {\n stateVersion: OPENSANDBOX_STATE_VERSION,\n sandboxId: created.id,\n manifest,\n environment,\n image: this.options.image,\n poolRef: this.options.poolRef ?? null,\n providerBindingHash: providerBindingHash(this.options.baseUrl),\n workspacePersistence: \"tar\",\n configuredExposedPorts: normalizeConfiguredPorts(this.options.exposedPorts),\n workspaceReady: false,\n expiresAt: created.expiresAt?.toISOString() ?? null,\n };\n return new OpenSandboxSession({\n state,\n options: this.options,\n ...(normalized.archiveLimits !== undefined\n ? { archiveLimits: normalized.archiveLimits }\n : {}),\n });\n }\n\n async resume(\n state: OpenSandboxSessionState,\n options: SandboxClientResumeOptions = {},\n ): Promise<OpenSandboxSession> {\n return await this.resumeExact(state, options);\n }\n\n async resumeExact(\n state: OpenSandboxSessionState,\n options: SandboxClientResumeOptions = {},\n ): Promise<OpenSandboxSession> {\n assertStateMatchesOptions(state, this.options);\n try {\n await withLifecycle(this.options, async (sandboxes) => {\n const info = await sandboxes.getSandbox(state.sandboxId);\n assertSupportedProviderState(info, state.sandboxId);\n });\n } catch (error) {\n if (error instanceof SandboxExactResumeInstanceUnavailableError || isNotFound(error)) {\n throw new SandboxExactResumeInstanceUnavailableError(\"opensandbox\", state.sandboxId);\n }\n throw error;\n }\n return new OpenSandboxSession({\n state,\n options: this.options,\n ...(options.archiveLimits !== undefined ? { archiveLimits: options.archiveLimits } : {}),\n });\n }\n\n async delete(state: OpenSandboxSessionState): Promise<void> {\n assertStateMatchesOptions(state, this.options);\n try {\n await withLifecycle(this.options, async (sandboxes) => {\n await sandboxes.deleteSandbox(state.sandboxId);\n });\n } catch (error) {\n if (!isNotFound(error)) throw error;\n }\n }\n\n async renewExpiration(sandboxId: string): Promise<string> {\n const expiresAt = new Date(Date.now() + this.options.ttlSeconds * 1000).toISOString();\n const response = await withLifecycle(\n this.options,\n async (sandboxes) => await sandboxes.renewSandboxExpiration(sandboxId, { expiresAt }),\n );\n return response.expiresAt?.toISOString() ?? expiresAt;\n }\n\n async canPersistOwnedSessionState(): Promise<boolean> {\n return true;\n }\n\n async canReusePreservedOwnedSession(): Promise<boolean> {\n return false;\n }\n\n async serializeSessionState(state: OpenSandboxSessionState): Promise<Record<string, unknown>> {\n assertStateMatchesOptions(state, this.options);\n return {\n stateVersion: OPENSANDBOX_STATE_VERSION,\n sandboxId: state.sandboxId,\n manifest: serializeManifestRecord(state.manifest),\n environment: serializeRuntimeEnvironmentForPersistence(state.manifest, state.environment),\n image: state.image,\n poolRef: state.poolRef,\n providerBindingHash: state.providerBindingHash,\n workspacePersistence: \"tar\",\n configuredExposedPorts: [...state.configuredExposedPorts],\n workspaceReady: state.workspaceReady,\n expiresAt: state.expiresAt,\n ...(this.options.signedEndpoints\n ? {}\n : state.exposedPorts\n ? { exposedPorts: structuredClone(state.exposedPorts) }\n : {}),\n };\n }\n\n async deserializeSessionState(value: Record<string, unknown>): Promise<OpenSandboxSessionState> {\n if (value.stateVersion !== OPENSANDBOX_STATE_VERSION) {\n throw new SandboxConfigError(\n \"opensandbox\",\n `unsupported persisted OpenSandbox state version: ${String(value.stateVersion)}`,\n );\n }\n const manifest = deserializeManifest(\n value.manifest && typeof value.manifest === \"object\" && !Array.isArray(value.manifest)\n ? (value.manifest as Record<string, unknown>)\n : undefined,\n );\n if (manifest.root !== WORKSPACE_ROOT) {\n throw new SandboxConfigError(\n \"opensandbox\",\n `persisted manifest root must be ${WORKSPACE_ROOT}`,\n );\n }\n const state: OpenSandboxSessionState = {\n stateVersion: OPENSANDBOX_STATE_VERSION,\n sandboxId: parseStateString(value.sandboxId, \"sandboxId\"),\n manifest,\n environment: await rehydratePersistedEnvironmentForRuntime(\n manifest,\n value.environment &&\n typeof value.environment === \"object\" &&\n !Array.isArray(value.environment)\n ? (value.environment as Record<string, string>)\n : undefined,\n this.options.environment,\n ),\n image: parseStateString(value.image, \"image\"),\n poolRef: parseOptionalString(value.poolRef, \"poolRef\"),\n providerBindingHash: parseStateString(value.providerBindingHash, \"providerBindingHash\"),\n workspacePersistence: \"tar\",\n configuredExposedPorts: Array.isArray(value.configuredExposedPorts)\n ? normalizeConfiguredPorts(\n value.configuredExposedPorts.filter(\n (entry): entry is number => typeof entry === \"number\",\n ),\n )\n : [],\n workspaceReady: value.workspaceReady === true,\n expiresAt: parseOptionalString(value.expiresAt, \"expiresAt\"),\n ...(value.exposedPorts &&\n typeof value.exposedPorts === \"object\" &&\n !Array.isArray(value.exposedPorts)\n ? {\n exposedPorts: structuredClone(\n value.exposedPorts as Record<string, ExposedPortEndpoint>,\n ),\n }\n : {}),\n };\n assertStateMatchesOptions(state, this.options);\n return state;\n }\n}\n","// @opengeni/runtime/sandbox — the pixel DATA PLANE: exposeStreamPort (P4.2).\n//\n// This is the heart of Channel B's data plane. exposeStreamPort resolves the\n// provider's scoped tunnel for the ONE exposed stream port (6080), assembles the\n// direct-to-provider WS URL (client → provider-tunnel direct; the pixel socket\n// never traverses Opengeni), and mints the scoped Opengeni stream token. It is a\n// plain function over a live, externally-owned `{session}` handle — NO Temporal,\n// NO worker RPC, NO actor. The API-direct handshake handler (apps/api) calls it\n// in-process on a freshly-resumed-by-id box and returns the result as the HTTP\n// response; the worker's per-turn resume path calls the same function when a turn\n// is the first to bring the box up. Both pull it from this single agent-loop-free\n// leaf (@opengeni/runtime/sandbox).\n//\n// THE TOKEN IS NOT A URL QUERY PARAM. The provider's own scoped tunnel URL\n// (Modal raw-TLS host:port, Daytona signed preview, Blaxel preview-token query)\n// carries the reach-the-port boundary; the Opengeni stream token is RECORDED\n// against the viewer holder and is the in-box websockify edge boundary (P3/P5).\n// Per the sandbox contract ruling, exposeStreamPort returns the token alongside the\n// URL so the caller records it; it does NOT append it to `url`.\n\nimport { DESKTOP_STREAM_PORT } from \"@opengeni/contracts\";\nimport { mintStreamToken, STREAM_TOKEN_DEFAULT_TTL_SECONDS } from \"./stream-token\";\n\n/** The provider-resolved endpoint for an exposed port. Mirrors the SDK's\n * `ExposedPortEndpoint` (host/port/tls/query/...) WITHOUT importing the\n * agent-loop barrel — the leaf stays agent-loop-free. */\nexport type ExposedPortEndpoint = {\n host: string;\n port: number;\n tls?: boolean;\n query?: string;\n protocol?: string;\n url?: string;\n /** The URL path the socket connects on. Modal/Daytona/Blaxel serve the edge at\n * the root (`/`, the default); the selfhosted relay serves it at `/stream`\n * (M8b). When set, buildStreamUrl uses it instead of the root. */\n path?: string;\n [key: string]: unknown;\n};\n\n/** The structural slice of a provider session we need to resolve a tunnel. */\ntype PortResolvableSession = {\n resolveExposedPort?: (port: number) => Promise<ExposedPortEndpoint>;\n};\n\n/** Thrown when the provider cannot expose the stream port (no resolveExposedPort,\n * or the provider tunnel lookup failed). The caller degrades the desktop cell to\n * `transport:null` (a value, never a crash) — a headless-only provider or a\n * transient tunnel failure must not fail the whole handshake. */\nexport class StreamPortUnavailableError extends Error {\n constructor(\n message: string,\n readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"StreamPortUnavailableError\";\n }\n}\n\nexport type ExposeStreamPortInput = {\n workspaceId: string;\n sessionId: string;\n /** The sandbox_lease_holders viewer row id the token is scoped to. */\n viewerId: string;\n /** The live lease epoch — the fence the token is pinned to. */\n leaseEpoch: number;\n /** The HMAC secret for the scoped stream token (resolveStreamTokenSecret). */\n streamTokenSecret: string;\n /** The exposed stream port; defaults to 6080. */\n port?: number;\n /** Token TTL in seconds; defaults to STREAM_TOKEN_DEFAULT_TTL_SECONDS. */\n ttlSeconds?: number;\n /** The framebuffer geometry to echo back to the client. */\n resolution?: [number, number];\n /** Override the issue clock (tests). Seconds since the epoch. */\n nowSeconds?: number;\n /** The authenticated viewer subject the token is minted for (0281). */\n subjectId?: string;\n /** The session authority epoch observed at mint (0281). */\n authorityEpoch?: number;\n};\n\nexport type ExposeStreamPortResult = {\n /** The direct-to-provider WS URL the viewer connects to (provider-scoped; the\n * Opengeni token is NOT appended). */\n url: string;\n /** The scoped Opengeni stream token — recorded against the holder, NEVER a URL\n * query param. */\n token: string;\n /** ISO absolute expiry of the token (the rotation hot-swap window backstop). */\n expiresAt: string;\n /** The pixel transport the client speaks. */\n transport: \"vnc-ws\";\n /** The reference noVNC client the SDK helper mounts. */\n client: \"novnc\";\n resolution: [number, number];\n leaseEpoch: number;\n};\n\nconst DEFAULT_RESOLUTION: [number, number] = [1280, 800];\n\n/**\n * Assemble the direct-to-provider WS URL from a resolved endpoint. The SDK's\n * `urlForExposedPort(endpoint,'ws')` is the canonical tls-aware, IPv6-bracketing,\n * provider-query-preserving assembler — we reimplement its exact logic here so\n * the leaf stays agent-loop-free (the helper lives behind the bare\n * `@openai/agents-core` root, which the import-discipline test forbids). The\n * provider's own `endpoint.query` (Blaxel `bl_preview_token`, Daytona signed\n * token) is preserved; the Opengeni token is NOT appended (it is recorded against\n * the holder + validated at the in-box websockify edge).\n */\nexport function buildStreamUrl(endpoint: ExposedPortEndpoint): string {\n if (\n typeof endpoint.host !== \"string\" ||\n endpoint.host.length === 0 ||\n typeof endpoint.port !== \"number\"\n ) {\n throw new StreamPortUnavailableError(\n `provider returned a malformed exposed-port endpoint (host=${String(endpoint.host)}, port=${String(endpoint.port)})`,\n );\n }\n const tls = endpoint.tls ?? false;\n const scheme = tls ? \"wss\" : \"ws\";\n const defaultPort = tls ? 443 : 80;\n // Bracket a bare IPv6 host (urlForExposedPort parity).\n const host =\n endpoint.host.includes(\":\") && !endpoint.host.startsWith(\"[\")\n ? `[${endpoint.host}]`\n : endpoint.host;\n // The path: default the root `/` (Modal/Daytona/Blaxel edge), or the\n // provider-supplied path (the selfhosted relay's `/stream` route, M8b). Always\n // leading-slash-normalized.\n const rawPath =\n typeof endpoint.path === \"string\" && endpoint.path.length > 0 ? endpoint.path : \"/\";\n const path = rawPath.startsWith(\"/\") ? rawPath : `/${rawPath}`;\n const origin =\n endpoint.port === defaultPort ? `${scheme}://${host}` : `${scheme}://${host}:${endpoint.port}`;\n const authority = `${origin}${path}`;\n const query = endpoint.query ?? \"\";\n return query ? `${authority}?${query}` : authority;\n}\n\n/**\n * Join a provider tunnel prefix with a controller/API path. Modal/Daytona/Blaxel\n * serve the edge at `/`; OpenSandbox's lifecycle proxy serves it at\n * `/v1/sandboxes/<id>/proxy/<port>`. The request path (`/v1/browser-sessions/...`)\n * must keep that prefix so Channel B hits browserd, not the lifecycle API root.\n */\nexport function joinExposedPortPath(endpointPath: string | undefined, requestPath: string): string {\n if (\n typeof requestPath !== \"string\" ||\n !requestPath.startsWith(\"/\") ||\n requestPath.includes(\"\\0\") ||\n requestPath.includes(\"#\") ||\n requestPath.includes(\"?\")\n ) {\n throw new StreamPortUnavailableError(\"exposed-port request path is invalid\");\n }\n const raw = typeof endpointPath === \"string\" && endpointPath.length > 0 ? endpointPath : \"/\";\n const prefix = (raw.startsWith(\"/\") ? raw : `/${raw}`).replace(/\\/+$/u, \"\") || \"\";\n return `${prefix}${requestPath}`;\n}\n\nconst OPENSANDBOX_LIFECYCLE_PROXY_PATH = /\\/v1\\/sandboxes\\/[^/]+\\/proxy\\/\\d+(?:\\/|$)/u;\n/** OSEP-0011 URI mode: `/{sandbox_id}/{port}/{expires_b36}/{signature}/…`. */\nconst OPENSANDBOX_SIGNED_URI_PATH =\n /^\\/([^/]{1,128})\\/(\\d{1,5})\\/([0-9a-z]{1,13})\\/([0-9a-z]{8,64})(?:\\/|$)/iu;\nconst SIGNED_ENDPOINT_REFRESH_SKEW_MS = 30_000;\n\nexport type OpenSandboxSignedUriPath = {\n sandboxId: string;\n port: number;\n expiresAtSeconds: number;\n signature: string;\n};\n\nexport function isOpenSandboxLifecycleProxyPath(path: string): boolean {\n return OPENSANDBOX_LIFECYCLE_PROXY_PATH.test(path);\n}\n\nexport function parseOpenSandboxSignedUriPath(path: string): OpenSandboxSignedUriPath | null {\n const normalized = path.startsWith(\"/\") ? path : `/${path}`;\n const match = OPENSANDBOX_SIGNED_URI_PATH.exec(normalized);\n if (!match) return null;\n const port = Number(match[2]);\n if (!Number.isInteger(port) || port < 1 || port > 65_535) return null;\n const expiresAtSeconds = Number.parseInt(match[3]!, 36);\n if (!Number.isSafeInteger(expiresAtSeconds) || expiresAtSeconds < 0) return null;\n return {\n sandboxId: match[1]!,\n port,\n expiresAtSeconds,\n signature: match[4]!,\n };\n}\n\nfunction pathnameFromExposedPort(endpoint: ExposedPortEndpoint | string): string | null {\n if (typeof endpoint === \"string\") {\n try {\n return new URL(endpoint).pathname;\n } catch {\n return null;\n }\n }\n return typeof endpoint.path === \"string\" && endpoint.path.length > 0 ? endpoint.path : \"/\";\n}\n\n/**\n * Host-side JSON/WebSocket may send the browserd Bearer only when the edge does\n * not rewrite `Authorization`. Lifecycle `/v1/sandboxes/<id>/proxy/<port>` does;\n * native `/` tunnels and OSEP-0011 signed URIs do not.\n */\nexport function exposedPortAllowsHostFetch(endpoint: ExposedPortEndpoint | string): boolean {\n const path = pathnameFromExposedPort(endpoint);\n if (path === null) return false;\n if (isOpenSandboxLifecycleProxyPath(path)) return false;\n if (path === \"/\" || path === \"\") return true;\n return parseOpenSandboxSignedUriPath(path) !== null;\n}\n\nexport function signedEndpointExpiresAtMs(path: string): number | null {\n const parsed = parseOpenSandboxSignedUriPath(path);\n return parsed ? parsed.expiresAtSeconds * 1000 : null;\n}\n\nexport function signedEndpointNeedsRefresh(\n path: string,\n nowMs = Date.now(),\n skewMs = SIGNED_ENDPOINT_REFRESH_SKEW_MS,\n): boolean {\n const expiresAt = signedEndpointExpiresAtMs(path);\n if (expiresAt === null) return false;\n return nowMs + skewMs >= expiresAt;\n}\n\n/** Logs and artifacts may keep the signed path shape, never the signature. */\nexport function redactOpenSandboxSignedUriPath(path: string): string {\n return path.replace(/^(\\/[^/]+\\/\\d+\\/[0-9a-z]+)\\/[0-9a-z]+/iu, \"$1/[redacted]\");\n}\n\n/** Rehydrate a persisted provider tunnel URL without contacting the provider.\n * Only the exact ws/wss shape emitted by buildStreamUrl is accepted. */\nexport function exposedPortEndpointFromUrl(value: string): ExposedPortEndpoint {\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n throw new StreamPortUnavailableError(\"cached provider endpoint is not a valid URL\");\n }\n if (\n (parsed.protocol !== \"ws:\" && parsed.protocol !== \"wss:\") ||\n parsed.username !== \"\" ||\n parsed.password !== \"\" ||\n parsed.hash !== \"\" ||\n parsed.hostname === \"\"\n ) {\n throw new StreamPortUnavailableError(\"cached provider endpoint has an invalid authority\");\n }\n const tls = parsed.protocol === \"wss:\";\n const port = parsed.port === \"\" ? (tls ? 443 : 80) : Number(parsed.port);\n if (!Number.isInteger(port) || port < 1 || port > 65_535) {\n throw new StreamPortUnavailableError(\"cached provider endpoint has an invalid port\");\n }\n return {\n host: parsed.hostname,\n port,\n tls,\n path: parsed.pathname || \"/\",\n query: parsed.search.startsWith(\"?\") ? parsed.search.slice(1) : parsed.search,\n };\n}\n\n/**\n * Resolve the provider's scoped tunnel for the stream port and mint the scoped\n * Opengeni stream token. Returns a coherent `{url, token, expiresAt, transport,\n * client, resolution}` cell the caller records on the lease (data_plane_url) and\n * returns in the DesktopStream handshake.\n *\n * Throws `StreamPortUnavailableError` when the provider session cannot resolve\n * the port (no `resolveExposedPort`, or the tunnel lookup failed) — the caller\n * maps this to a `transport:null` degradation (a value, never a crash).\n */\nexport async function exposeStreamPort(\n session: unknown,\n input: ExposeStreamPortInput,\n): Promise<ExposeStreamPortResult> {\n const s = session as PortResolvableSession;\n const port = input.port ?? DESKTOP_STREAM_PORT;\n if (typeof s?.resolveExposedPort !== \"function\") {\n throw new StreamPortUnavailableError(\n \"provider session cannot resolve exposed ports (no resolveExposedPort) — desktop stream unavailable\",\n );\n }\n\n let endpoint: ExposedPortEndpoint;\n try {\n // (I7/OD-7) per-provider URL re-resolution folds in here: a provider with a\n // preview/signed token (Daytona/Blaxel) re-resolves its own short-TTL token\n // on every call, so a rotation re-mints both planes' freshness in one place.\n endpoint = await s.resolveExposedPort(port);\n } catch (error) {\n throw new StreamPortUnavailableError(\n `provider failed to resolve the stream port ${port}: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n\n const url = buildStreamUrl(endpoint);\n const ttlSeconds = input.ttlSeconds ?? STREAM_TOKEN_DEFAULT_TTL_SECONDS;\n const nowSeconds = input.nowSeconds ?? Math.floor(Date.now() / 1000);\n const token = await mintStreamToken(input.streamTokenSecret, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n viewerId: input.viewerId,\n leaseEpoch: input.leaseEpoch,\n mode: \"view\",\n port,\n ttlSeconds,\n nowSeconds,\n ...(input.subjectId ? { subjectId: input.subjectId } : {}),\n ...(input.authorityEpoch ? { authorityEpoch: input.authorityEpoch } : {}),\n });\n\n return {\n url,\n token,\n expiresAt: new Date((nowSeconds + ttlSeconds) * 1000).toISOString(),\n transport: \"vnc-ws\",\n client: \"novnc\",\n resolution: input.resolution ?? DEFAULT_RESOLUTION,\n leaseEpoch: input.leaseEpoch,\n };\n}\n","// @opengeni/runtime/sandbox — scoped stream-token mint/verify (P3.1).\n//\n// The agent-loop-free home for the scoped data-plane stream token used by the\n// desktop pixel plane (Channel B, sandbox contract §C.3 / crosscut PART 1.3). It is\n// a THIN wrapper over the contracts HMAC envelope (signStreamToken /\n// verifyStreamToken) — NOT a second crypto: it REUSES the exact base64Url +\n// hmacSha256 construction that backs signDelegatedAccessToken, with the distinct\n// `ogs_` prefix and the hard-narrow StreamTokenPayload claim set.\n//\n// It lives under @opengeni/runtime/sandbox so the API-direct control plane\n// (apps/api) can mint + verify stream tokens from the same single agent-loop-free\n// leaf it already pulls createSandboxClient / resume-by-id from.\n\nimport {\n DESKTOP_STREAM_PORT,\n StreamTokenPayload,\n signStreamToken,\n verifyStreamToken as verifyStreamTokenEnvelope,\n type StreamTokenPayload as StreamTokenPayloadType,\n} from \"@opengeni/contracts\";\n\n// The default stream-token TTL (seconds). The token is short-lived by design:\n// URL rotation is event-driven under the epoch fence (re-resolve recorded on the\n// lease), not on a keepalive clock — so the token never needs a long life.\nexport const STREAM_TOKEN_DEFAULT_TTL_SECONDS = 120;\n\nexport type MintStreamTokenInput = {\n workspaceId: string;\n sessionId: string;\n /** The sandbox_lease_holders viewer row id. */\n viewerId: string;\n /** The epoch the token is fenced to. For a Modal box this is the live LEASE\n * epoch (re-minted on box rollover). For a SELFHOSTED relay stream (M8b) this is\n * the session's swap `active_epoch`: the relay tracks the highest epoch any\n * viewer presented per channel and REJECTS a token with a lower epoch, so a\n * viewer whose token predates a swap-away cannot reach the machine the session\n * swapped off of. One field, two fences — the relay/in-box edge reads it as the\n * stale-viewer floor either way. */\n leaseEpoch: number;\n /** v1 is always \"view\"; \"control\" is the never-granted raw-input plane. */\n mode?: \"view\" | \"control\";\n /** The exposed stream port (noVNC); defaults to 6080. */\n port?: number;\n /** TTL in seconds; defaults to STREAM_TOKEN_DEFAULT_TTL_SECONDS. */\n ttlSeconds?: number;\n /** Override the issue clock (tests). Seconds since the epoch. */\n nowSeconds?: number;\n /** The authenticated viewer subject the token is minted for (0281). */\n subjectId?: string;\n /** The session authority epoch observed at mint (0281). */\n authorityEpoch?: number;\n};\n\n/**\n * Mint a scoped stream token for one viewer holder. Builds the hard-narrow\n * StreamTokenPayload (the claim set the in-box edge / control plane validates)\n * and signs it with the resolved stream-token secret via the contracts HMAC\n * envelope (`ogs_` prefix). The token is RECORDED against the holder row by the\n * caller and is NEVER appended to the data-plane URL as a query param.\n */\nexport async function mintStreamToken(\n secret: string,\n input: MintStreamTokenInput,\n): Promise<string> {\n const nowSeconds = input.nowSeconds ?? Math.floor(Date.now() / 1000);\n const ttlSeconds = input.ttlSeconds ?? STREAM_TOKEN_DEFAULT_TTL_SECONDS;\n const payload: StreamTokenPayloadType = StreamTokenPayload.parse({\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n viewerId: input.viewerId,\n leaseEpoch: input.leaseEpoch,\n mode: input.mode ?? \"view\",\n port: input.port ?? DESKTOP_STREAM_PORT,\n exp: nowSeconds + ttlSeconds,\n ...(input.subjectId ? { subjectId: input.subjectId } : {}),\n ...(input.authorityEpoch ? { authorityEpoch: input.authorityEpoch } : {}),\n });\n return signStreamToken(secret, payload);\n}\n\n/**\n * Verify a scoped stream token. Returns the parsed claims on success, or null on\n * a bad prefix / malformed envelope / bad HMAC signature / schema-invalid claims\n * / expiry. Re-exports the contracts verify; the leaf is the agent-loop-free\n * import surface the API uses.\n *\n * The epoch fence (claim.leaseEpoch vs the LIVE lease epoch) and the\n * workspace+session scope are enforced at USE by the caller against the live\n * lease + route params — verify proves authenticity + freshness only.\n */\nexport async function verifyStreamToken(\n secret: string,\n token: string,\n nowSeconds = Math.floor(Date.now() / 1000),\n): Promise<StreamTokenPayloadType | null> {\n return verifyStreamTokenEnvelope(secret, token, nowSeconds);\n}\n\nexport {\n StreamTokenPayload,\n type StreamTokenPayload as StreamTokenPayloadType,\n} from \"@opengeni/contracts\";\n","import { DefaultAdapterFactory, type AdapterFactory } from \"@alibaba-group/opensandbox\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\ntype Commands = ReturnType<AdapterFactory[\"createExecdStack\"]>[\"commands\"];\nconst defaultCreateExecdStack = DefaultAdapterFactory.prototype.createExecdStack;\nconst boundDefaultCommands = new WeakMap<Commands, Pick<Commands, \"run\" | \"runStream\">>();\nconst commandDispatch = new AsyncLocalStorage<{ attempted: boolean }>();\n\n/** Local proof from the actual command invocation and its bound wire seam,\n * never inferred from provider status codes, error text or a missing init. */\nexport class OpenSandboxCommandDispatchError extends Error {\n constructor(\n readonly notDispatched: boolean,\n cause: unknown,\n ) {\n super(\n notDispatched\n ? \"OpenSandbox command was not dispatched\"\n : \"OpenSandbox command dispatch is uncertain\",\n { cause },\n );\n this.name = \"OpenSandboxCommandDispatchError\";\n }\n}\n\nexport async function withOpenSandboxCommandDispatchProof<T>(\n commands: Commands,\n invoke: () => Promise<T>,\n): Promise<T> {\n const bound = boundDefaultCommands.get(commands);\n const trusted =\n bound !== undefined && bound.run === commands.run && bound.runStream === commands.runStream;\n const state = { attempted: false };\n return await commandDispatch.run(state, async () => {\n try {\n return await invoke();\n } catch (cause) {\n // A custom adapter can bypass this fetch entirely. Its absence is never\n // no-dispatch proof; only an unchanged, genuinely bound default SDK path\n // that failed before invoking the command transport can grant that proof.\n throw new OpenSandboxCommandDispatchError(trusted && !state.attempted, cause);\n }\n });\n}\n\n/** A successful command HTTP response was accepted, but its event stream no\n * longer proves complete output or exit. It is not proof of an unstarted op. */\nexport class OpenSandboxCommandStreamError extends Error {\n constructor(message: string, cause?: unknown) {\n super(`OpenSandbox command stream is uncertain: ${message}`, { cause });\n this.name = \"OpenSandboxCommandStreamError\";\n }\n}\n\n/** Decode complete wire lines, not whole transport chunks: a corrupt later\n * line must not erase an earlier authenticated init in the same HTTP chunk. */\nasync function* wireLines(reader: ReadableStreamDefaultReader<Uint8Array>) {\n const decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true });\n let parts: Uint8Array[] = [];\n let skipLf = false;\n let first = true;\n const decode = () => {\n let line = decoder.decode(Buffer.concat(parts));\n parts = [];\n if (first) line = line.replace(/^\\uFEFF/u, \"\");\n first = false;\n return line;\n };\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n let start = 0;\n for (let index = 0; index < value.length; index++) {\n const byte = value[index];\n if (skipLf) {\n skipLf = false;\n if (byte === 10) {\n start = index + 1;\n continue;\n }\n }\n if (byte !== 10 && byte !== 13) continue;\n parts.push(value.subarray(start, index));\n yield { line: decode(), terminated: true };\n skipLf = byte === 13;\n start = index + 1;\n }\n if (start < value.length) parts.push(value.subarray(start));\n }\n if (parts.length) yield { line: decode(), terminated: false };\n}\n\n/** The SDK coerces these fields with String(), which can turn an array value\n * into a successful exit code. Validate the wire DTO before that conversion.\n * Fields are optional in the provider schema; supplied aliases must agree. */\nfunction assertCommandError(value: unknown): void {\n if (!value || typeof value !== \"object\" || Array.isArray(value))\n throw new Error(\"invalid command error envelope\");\n const error = value as Record<string, unknown>;\n let recognized = false;\n for (const [primary, alias] of [\n [\"ename\", \"name\"],\n [\"evalue\", \"value\"],\n ] as const) {\n for (const field of [primary, alias]) {\n if (error[field] === undefined) continue;\n recognized = true;\n if (typeof error[field] !== \"string\") throw new Error(\"invalid command error field\");\n }\n if (\n error[primary] !== undefined &&\n error[alias] !== undefined &&\n error[primary] !== error[alias]\n )\n throw new Error(\"contradictory command error aliases\");\n }\n if (error.traceback !== undefined) {\n recognized = true;\n if (!Array.isArray(error.traceback) || error.traceback.some((line) => typeof line !== \"string\"))\n throw new Error(\"invalid command error traceback\");\n }\n if (!recognized) throw new Error(\"empty command error DTO\");\n}\n\nasync function* commandFrames(response: Response): AsyncGenerator<Uint8Array> {\n if (!response.body) throw new OpenSandboxCommandStreamError(\"missing response body\");\n const reader = response.body.getReader();\n const encoder = new TextEncoder();\n let data: string[] = [];\n let executionId: string | null = null;\n let completed = false;\n let eof = false;\n // The SDK supports SSE and NDJSON independently of the response MIME type.\n let mode: \"sse\" | \"ndjson\" | null = null;\n const frame = (json: string) => {\n const value: unknown = JSON.parse(json);\n if (!value || typeof value !== \"object\" || Array.isArray(value))\n throw new Error(\"invalid command event envelope\");\n const event = value as Record<string, unknown>;\n if (typeof event.type !== \"string\") throw new Error(\"missing command event type\");\n if (event.type === \"init\") {\n if (typeof event.text !== \"string\" || !event.text.trim())\n throw new Error(\"missing execution identity\");\n if (executionId !== null && event.text !== executionId)\n throw new Error(\"contradictory execution identity\");\n executionId = event.text;\n }\n for (const field of [\"id\", \"execution_id\", \"executionId\"] as const) {\n if (event[field] !== undefined && event[field] !== executionId)\n throw new Error(\"contradictory event identity\");\n }\n if ((event.type === \"stdout\" || event.type === \"stderr\") && typeof event.text !== \"string\")\n throw new Error(\"invalid command output\");\n if (event.type === \"error\") assertCommandError(event.error);\n if (event.type === \"execution_complete\") {\n if (executionId === null) throw new Error(\"completion without execution identity\");\n completed = true;\n }\n // The pinned SDK accepts one JSON value per data line, but not legal SSE\n // multiline JSON. Canonicalizing only framing preserves every text value.\n return encoder.encode(`data: ${JSON.stringify(event)}\\n\\n`);\n };\n try {\n for await (const { line, terminated } of wireLines(reader)) {\n if (mode === null && line && !line.startsWith(\":\"))\n mode = line.trimStart().startsWith(\"{\") ? \"ndjson\" : \"sse\";\n if (mode === \"ndjson\") {\n if (line.trim()) yield frame(line);\n continue;\n }\n if (!terminated && line && !line.startsWith(\":\")) throw new Error(\"truncated SSE line\");\n if (line === \"\") {\n if (data.length) {\n const json = data.join(\"\\n\");\n data = [];\n yield frame(json);\n }\n continue;\n }\n if (line.startsWith(\":\")) continue;\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n const value = colon === -1 ? \"\" : line.slice(colon + 1).replace(/^ /u, \"\");\n if (field === \"data\") data.push(value);\n // Other legal SSE fields (event/id/retry/extensions) do not alter data.\n }\n eof = true;\n if (data.length) throw new Error(\"truncated SSE frame\");\n if (!completed) throw new Error(\"EOF without command completion\");\n } catch (error) {\n throw error instanceof OpenSandboxCommandStreamError\n ? error\n : new OpenSandboxCommandStreamError(\"invalid or incomplete events\", error);\n } finally {\n if (!eof) await reader.cancel().catch(() => undefined);\n reader.releaseLock();\n }\n}\n\nfunction strictCommandFetch(original: typeof fetch): typeof fetch {\n const wrapped = (async (input, init) => {\n const url = input instanceof Request ? input.url : String(input);\n const isCommand =\n (init?.method ?? (input instanceof Request ? input.method : \"GET\")).toUpperCase() ===\n \"POST\" && new URL(url).pathname.endsWith(\"/command\");\n // Mark BEFORE the original transport. Header loss and a non-2xx response\n // do not prove that the provider refused the original mutation.\n const dispatch = commandDispatch.getStore();\n if (isCommand && dispatch) dispatch.attempted = true;\n const response = await original(input, init);\n if (!response.ok || !isCommand) return response;\n if (!response.body) throw new OpenSandboxCommandStreamError(\"missing response body\");\n const frames = commandFrames(response);\n const body = new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n try {\n const next = await frames.next();\n if (next.done) controller.close();\n else controller.enqueue(next.value);\n } catch (error) {\n controller.error(error);\n }\n },\n async cancel() {\n await frames.return(undefined);\n },\n },\n // Do not observe later errors ahead of the SDK consuming a valid page.\n { highWaterMark: 0 },\n );\n const headers = new Headers(response.headers);\n headers.delete(\"content-length\");\n headers.delete(\"content-encoding\");\n headers.set(\"content-type\", \"text/event-stream\");\n return new Response(body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }) as typeof fetch;\n return wrapped;\n}\n\n/** Public factory/config seams only. The SDK still owns request construction,\n * headers, dispatch, HTTP errors and event callbacks. No start is repeated. */\nexport function withOpenSandboxCommandStreamProof(factory: AdapterFactory): AdapterFactory {\n return {\n createLifecycleStack: (options) => factory.createLifecycleStack(options),\n createEgressStack: (options) => factory.createEgressStack(options),\n createExecdStack(options) {\n const sseFetch = strictCommandFetch(options.connectionConfig.sseFetch);\n const createExecdStack = factory.createExecdStack;\n const stack = createExecdStack.call(factory, {\n ...options,\n connectionConfig: new Proxy(options.connectionConfig, {\n get(target, property) {\n return property === \"sseFetch\" ? sseFetch : Reflect.get(target, property, target);\n },\n }),\n });\n if (createExecdStack === defaultCreateExecdStack) {\n // The public default constructor binds THIS sseFetch to its commands.\n // Delegating/custom factory methods are not assumed to do the same.\n boundDefaultCommands.set(stack.commands, {\n run: stack.commands.run,\n runStream: stack.commands.runStream,\n });\n }\n return stack;\n },\n };\n}\n","import { CAPABILITY_DESCRIPTORS } from \"../capabilities\";\nimport { SandboxConfigError } from \"../errors\";\nimport { OpenSandboxClient } from \"./opensandbox-adapter\";\nimport { REPEATABLE_PORTABLE_TAR_WORKSPACE_CAPTURE, type ProviderRegistration } from \"./types\";\n\nconst IMMUTABLE_OCI_IMAGE = /@sha256:[0-9a-f]{64}$/iu;\n/** Desktop-class box: Chromium + XFCE + ttyd will OOM in 1Gi. Two such boxes still fit a D4s_v3. */\nexport const OPENSANDBOX_DIRECT_RESOURCE_LIMITS = Object.freeze({ cpu: \"2\", memory: \"4Gi\" });\nexport const OPENSANDBOX_DIRECT_RESOURCE_REQUESTS = Object.freeze({\n cpu: \"500m\",\n memory: \"2Gi\",\n});\n\nfunction clientOptions(\n settings: Parameters<ProviderRegistration[\"validateCredentials\"]>[0],\n environment: Record<string, string> = {},\n exposedPorts: number[] = [],\n metrics?: import(\"../../metrics\").RuntimeMetricsHooks,\n) {\n return {\n baseUrl: settings.openSandboxBaseUrl!,\n apiKey: settings.openSandboxApiKey!,\n image: settings.openSandboxImage!,\n ttlSeconds: settings.openSandboxTtlSeconds,\n useServerProxy: settings.openSandboxUseServerProxy,\n signedEndpoints: settings.openSandboxSignedEndpoints,\n signedEndpointTtlSeconds: settings.openSandboxSignedEndpointTtlSeconds,\n ...(settings.openSandboxChannelBPublicBaseUrl\n ? { channelBPublicBaseUrl: settings.openSandboxChannelBPublicBaseUrl }\n : {}),\n readyTimeoutSeconds: Math.ceil(settings.sandboxWarmingTimeoutMs / 1000),\n resourceLimits: OPENSANDBOX_DIRECT_RESOURCE_LIMITS,\n resourceRequests: OPENSANDBOX_DIRECT_RESOURCE_REQUESTS,\n environment,\n exposedPorts,\n ...(settings.openSandboxPoolRef ? { poolRef: settings.openSandboxPoolRef } : {}),\n ...(metrics ? { metrics } : {}),\n };\n}\n\nexport const opensandboxProvider: ProviderRegistration = {\n backend: \"opensandbox\",\n exactResumeMode: \"custom\",\n instanceIdFields: [\"sandboxId\"],\n workspaceCapturePolicy: () => REPEATABLE_PORTABLE_TAR_WORKSPACE_CAPTURE,\n descriptor: CAPABILITY_DESCRIPTORS.opensandbox,\n validateCredentials(settings) {\n if (!settings.openSandboxBaseUrl) {\n throw new SandboxConfigError(\"opensandbox\", \"OPENGENI_OPENSANDBOX_BASE_URL is required\");\n }\n if (!settings.openSandboxApiKey) {\n throw new SandboxConfigError(\"opensandbox\", \"OPENGENI_OPENSANDBOX_API_KEY is required\");\n }\n if (!settings.openSandboxImage || !IMMUTABLE_OCI_IMAGE.test(settings.openSandboxImage)) {\n throw new SandboxConfigError(\n \"opensandbox\",\n \"OPENGENI_OPENSANDBOX_IMAGE must be an immutable OCI digest\",\n );\n }\n },\n async renewExpiration({ settings, instanceId }) {\n await new OpenSandboxClient(clientOptions(settings)).renewExpiration(instanceId);\n },\n build({ settings, environment, exposedPorts, metrics }) {\n return new OpenSandboxClient(clientOptions(settings, environment, exposedPorts, metrics));\n },\n};\n","import { RunloopSandboxClient } from \"@openai/agents-extensions/sandbox/runloop\";\nimport { CAPABILITY_DESCRIPTORS } from \"../capabilities\";\nimport { SandboxConfigError } from \"../errors\";\nimport { REPEATABLE_PORTABLE_TAR_WORKSPACE_CAPTURE, type ProviderRegistration } from \"./types\";\n\nexport const runloopProvider: ProviderRegistration = {\n backend: \"runloop\",\n exactResumeMode: \"custom\",\n instanceIdFields: [\"devboxId\"],\n // The SDK otherwise creates a non-idempotent native disk snapshot whose\n // provider artifact has no Opengeni outcome ledger. Lifecycle capture uses\n // the inherited unique-path tar primitive instead.\n workspaceCapturePolicy: () => REPEATABLE_PORTABLE_TAR_WORKSPACE_CAPTURE,\n descriptor: CAPABILITY_DESCRIPTORS.runloop,\n validateCredentials(settings) {\n if (!settings.runloopApiKey) {\n throw new SandboxConfigError(\"runloop\", \"OPENGENI_RUNLOOP_API_KEY is required\");\n }\n },\n build({ settings, environment, exposedPorts }) {\n const options: NonNullable<ConstructorParameters<typeof RunloopSandboxClient>[0]> = {\n apiKey: settings.runloopApiKey!,\n env: environment,\n exposedPorts,\n // Tunnel v2: one tunnel for all ports. Defaults to true in our config.\n tunnel: settings.runloopTunnel,\n };\n if (settings.runloopBaseUrl) options.baseUrl = settings.runloopBaseUrl;\n if (settings.runloopBlueprintName) options.blueprintName = settings.runloopBlueprintName;\n if (settings.runloopBlueprintId) options.blueprintId = settings.runloopBlueprintId;\n // Keep the provider-native snapshot request inside the same immutable\n // budget as Opengeni's durable capture claim. The outer lifecycle timeout\n // remains the final fence; this prevents an abandoned SDK request from\n // needlessly running past it when Runloop supports an exact operation knob.\n // Runloop keep-alive also lives in this bag (ms), not at Modal's top level.\n options.timeouts = {\n snapshotTimeoutMs: settings.sandboxSnapshotTimeoutMs,\n ...(settings.runloopKeepAliveSeconds\n ? { keepAliveTimeoutMs: settings.runloopKeepAliveSeconds * 1000 }\n : {}),\n };\n return new RunloopSandboxClient(options);\n },\n};\n","// `SelfhostedSession` + `SelfhostedSandboxClient` — the NATS-backed structural\n// sandbox surface for the `selfhosted` backend (bring-your-own-compute).\n//\n// The insight: every existing seam (Channel-A exec/fs/git, the\n// viewer's `resolveExposedPort`) consumes a provider session\n// STRUCTURALLY — `session.exec ?? session.execCommand`, `session.readFile`,\n// `session.resolveExposedPort`, `session.serializeSessionState`. If the\n// selfhosted client's `create()`/`resume()` return a session presenting that\n// EXACT surface — but backed by `ControlRpc` (request/reply to the agent over\n// the exact claimed process subject, encoded via `@opengeni/agent-proto`) instead of a\n// provider SDK — then those seams work UNCHANGED. The agent IS the box.\n//\n// The session depends ONLY on `ControlRpc` + `{workspaceId, agentId}` (+ the\n// relay config for the stream-URL SHAPE). It knows nothing about NATS directly\n// (the M3/M4 seam). `serializeSessionState`/`deserializeSessionState` round-trip\n// `{agentId}` ONLY — resume = re-address the live subject, NO provider state.\n\nimport {\n ControlRequest,\n ControlResponse,\n ErrorCode,\n FsEntryKind,\n StreamKind,\n type BrowserControlEnsureRequest,\n type BrowserControlEnsureResponse,\n type BrowserFramesOpenRequest,\n type ComputerFramesOpenRequest,\n type ExecRequest,\n type ExecResponse,\n type OperationResourcePolicy,\n type StreamChannel,\n} from \"@opengeni/agent-proto\";\nimport { DESKTOP_STREAM_PORT } from \"@opengeni/contracts\";\nimport {\n SELFHOSTED_FILE_CHUNK_BYTES,\n fileContentDigest,\n transferEditorFile,\n} from \"./file-transfer\";\n// `Manifest` from the ALLOWED sandbox-leaf entrypoint (`@openai/agents/sandbox`\n// re-exports `@openai/agents-core/sandbox`, which exports the Manifest class) —\n// NOT the agent-loop `@openai/agents` root the sandbox leaf forbids. The live\n// `state.manifest` slice the @openai/agents SDK reads per turn must be a real\n// Manifest (see the `state` field below); selfhosted exec routes over NATS and\n// does not use the manifest, but the SDK requires it present + well-formed.\nimport { Manifest } from \"@openai/agents/sandbox\";\nimport { formatExecResponse } from \"@openai/agents-core/sandbox/internal\";\nimport type { ExposedPortEndpoint } from \"../stream-port\";\nimport {\n BROWSER_CONTROL_HTTP_REPLY_GRACE_MS,\n type BrowserControlHttpCall,\n type BrowserControlHttpOutcome,\n} from \"../browser-control-http\";\nimport {\n agentErrorToControlError,\n drainingExhaustedError,\n execDeadlineHint,\n SelfhostedControlError,\n subjectFor,\n type ControlRpc,\n} from \"./control-rpc\";\nimport {\n decideSelfhostedRetry,\n defaultSelfhostedRetryClock,\n type SelfhostedRetryClock,\n} from \"./retry-policy\";\nimport type { SelfhostedOpObservation, SelfhostedOpObserver } from \"./op-observer\";\nimport { selfhostedFaultClass } from \"./fault-rendering\";\nimport {\n nextDurableOpId,\n notifyRemoteOperationTransportSelected,\n notifyDurableOpOwnershipTransferStarted,\n notifyDurableOpOwnershipTransferFailed,\n notifyDurableOpOwnershipTransferred,\n notifyRemoteOperationNotDispatched,\n type RemoteOperationControl,\n type RemoteOperationObservation,\n} from \"../op-correlation\";\nimport {\n OpStreamExecClient,\n runnerFailureToControlError,\n type OpStreamJournal,\n type OpStreamOutputFrame,\n type OpStreamOutputReceipt,\n} from \"./op-stream\";\nimport { OpStreamUnavailableError, type OpStreamTransport } from \"./op-transport\";\nimport { connectedMachineWorkspaceRootsEqual, resolveConnectedMachinePath } from \"./workspace-path\";\nimport type { ShellDialect } from \"@opengeni/vaults\";\nimport {\n secretExecCarryFor,\n secretExecEnvironment,\n secretScopeDirectory,\n shellDialectFor,\n spliceCarry,\n} from \"../secret-delivery\";\n\nconst decoder = new TextDecoder();\nconst encoder = new TextEncoder();\n// Keep one RPC reply comfortably below the agent's negotiated 1 MiB payload\n// ceiling. `fsRead` is ranged, so larger logical reads are assembled here.\nconst SELFHOSTED_FS_READ_CHUNK_BYTES = 512 * 1024;\nconst SELFHOSTED_PLACEMENT_PRIVATE_PREFIX = \"/tmp/opengeni-private/\";\nconst SELFHOSTED_PLACEMENT_PRIVATE_MAX_BYTES = 128 * 1024;\n// Private files (secretfile values up to the vault's 256 KiB file limit) stay\n// well below the 1 MiB RPC payload ceiling.\nconst SELFHOSTED_PLACEMENT_PRIVATE_FILE_MAX_BYTES = 512 * 1024;\n\n/**\n * Builds the exact argv for an explicitly selected shell.\n *\n * The self-hosted wire already supports direct argv (`ExecRequest.shell=false`),\n * which is the compatibility-safe way to honor the SDK shell tool's `shell` and\n * `login` arguments: every enrolled agent version understands this shape. Sending\n * `{ command: [cmd], shell: true }` instead delegates shell selection to the\n * machine's ambient `$SHELL`/`ComSpec` and silently discards the caller's choice.\n *\n * `login` maps to profile/login semantics where the shell family exposes them.\n * Windows `cmd.exe` has no login-shell mode. PowerShell profile loading is the\n * closest equivalent, so non-login calls use `-NoProfile` while login calls do\n * not. Other shells use the common POSIX `-l -c` / `-c` contract.\n */\nfunction explicitShellArgv(shell: string, command: string, login: boolean): string[] {\n const leaf = shell.replaceAll(\"\\\\\", \"/\").split(\"/\").at(-1)?.toLowerCase() ?? \"\";\n if (leaf === \"cmd\" || leaf === \"cmd.exe\") {\n return [shell, \"/D\", \"/S\", \"/C\", command];\n }\n if (\n leaf === \"powershell\" ||\n leaf === \"powershell.exe\" ||\n leaf === \"pwsh\" ||\n leaf === \"pwsh.exe\"\n ) {\n return [\n shell,\n \"-NoLogo\",\n ...(!login ? [\"-NoProfile\"] : []),\n \"-NonInteractive\",\n \"-Command\",\n command,\n ];\n }\n return [shell, ...(login ? [\"-l\"] : []), \"-c\", command];\n}\n\n// ── The agent-turn provided-session contract (@openai/agents-core) ──────────\n// When the routing proxy resolves a selfhosted ACTIVE backend, the @openai/agents\n// agent loop binds its filesystem/shell/skills capabilities to THIS session and\n// calls a richer method set than the Channel-A structural surface: `createEditor`\n// + `viewImage` (filesystem), `execCommand` + `supportsPty` (shell), `pathExists`\n// + `listDir` + `materializeEntry` + `readFile` (skills). The session must present\n// all of them or the turn crashes (e.g. \"Filesystem sandbox sessions must provide\n// createEditor()\"). These run over the SAME NATS exec/fs primitives; the machine\n// owns its filesystem so source materialization is a no-op.\n\n/** The V4A-diff applier the SDK's apply_patch editor uses. The leaf cannot import\n * `@openai/agents`'s `applyDiff` (the agent-loop root the leaf forbids), so the\n * runtime barrel (`packages/runtime/src/index.ts`, which DOES import that root)\n * injects it via `setSelfhostedApplyDiff` at module load. Until injected,\n * `createEditor()` surfaces a clear error rather than a silent wrong-edit. */\nexport type SelfhostedApplyDiff = (\n input: string,\n diff: string,\n mode?: \"default\" | \"create\",\n) => string;\nlet injectedApplyDiff: SelfhostedApplyDiff | undefined;\n\n/** Register the SDK's `applyDiff` so `SelfhostedSession.createEditor()` can apply\n * V4A diffs over the NATS fs ops. Called once by the runtime barrel. */\nexport function setSelfhostedApplyDiff(fn: SelfhostedApplyDiff): void {\n injectedApplyDiff = fn;\n}\n\n/** The structural Editor surface the SDK's filesystem capability consumes (the\n * three apply_patch operations). Mirrors `@openai/agents-core`'s `Editor`. */\nexport interface SelfhostedEditor {\n createFile(\n operation: { path: string; diff: string },\n context?: unknown,\n ): Promise<{ output?: string } | void>;\n updateFile(\n operation: { path: string; diff: string; moveTo?: string },\n context?: unknown,\n ): Promise<{ output?: string } | void>;\n deleteFile(operation: { path: string }, context?: unknown): Promise<{ output?: string } | void>;\n}\n\n/** The image tool-output shape the SDK's view_image tool expects (mirror of\n * `ToolOutputImage` — not re-exported by `@openai/agents/sandbox`, so structural). */\nexport interface SelfhostedImageOutput {\n type: \"image\";\n image: { data: Uint8Array; mediaType: string };\n}\n\n/** Default control-op timeout. A transient miss surfaces as `agent_reconnecting`\n * (the turn pauses + retries); it is NOT a hard failure. */\nexport const SELFHOSTED_DEFAULT_TIMEOUT_MS = 30_000;\n/** Reply grace after an agent-side exec deadline. The child is terminated at\n * `ExecRequest.timeoutMs`; this outer window lets the typed `timedOut` response\n * cross NATS before request/reply gives up. */\nconst SELFHOSTED_EXEC_REPLY_GRACE_MS = 5_000;\n/** nats.js ultimately schedules a JS timer; stay inside the signed 32-bit timer\n * range while also fitting the reply grace. */\nconst SELFHOSTED_MAX_EXEC_TIMEOUT_MS = 2_147_483_647 - SELFHOSTED_EXEC_REPLY_GRACE_MS;\nconst SELFHOSTED_BACKGROUND_DEFAULT_YIELD_MS = 10_000;\nconst SELFHOSTED_BACKGROUND_MAX_YIELD_MS = 30_000;\n\nfunction normalizeOperationResourcePolicy(\n policy: SelfhostedOperationResourcePolicy | undefined,\n): OperationResourcePolicy | undefined {\n const memoryMaxBytes = policy?.memoryMaxBytes ?? null;\n const memoryHighBytes = policy?.memoryHighBytes ?? null;\n const cpuMaxMillicores = policy?.cpuMaxMillicores ?? null;\n for (const [name, value] of [\n [\"memoryMaxBytes\", memoryMaxBytes],\n [\"memoryHighBytes\", memoryHighBytes],\n ] as const) {\n if (value !== null && (!Number.isSafeInteger(value) || value <= 0)) {\n throw new Error(`${name} must be a positive safe-integer byte count or null`);\n }\n }\n if (memoryMaxBytes !== null && memoryHighBytes !== null && memoryHighBytes > memoryMaxBytes) {\n throw new Error(\"memoryHighBytes cannot exceed memoryMaxBytes\");\n }\n if (\n cpuMaxMillicores !== null &&\n (!Number.isInteger(cpuMaxMillicores) || cpuMaxMillicores <= 0 || cpuMaxMillicores > 0xffff_ffff)\n ) {\n throw new Error(\"cpuMaxMillicores must be a positive uint32 value or null\");\n }\n if (memoryMaxBytes === null && memoryHighBytes === null && cpuMaxMillicores === null) {\n return undefined;\n }\n return {\n ...(memoryMaxBytes !== null ? { memoryMaxBytes: String(memoryMaxBytes) } : {}),\n ...(memoryHighBytes !== null ? { memoryHighBytes: String(memoryHighBytes) } : {}),\n ...(cpuMaxMillicores !== null ? { cpuMaxMillicores } : {}),\n };\n}\n\n/** The relay-URL shape config the session needs to build a stream endpoint. M8b\n * wires the real relay deployment behind THIS seam so `buildStreamUrl` works\n * unchanged behind `resolveExposedPort`. */\nexport interface SelfhostedRelayConfig {\n /** The relay edge host (no scheme), e.g. \"relay.opengeni.ai\". */\n host: string;\n /** The relay port. Defaults to 443 (the relay terminates TLS). */\n port?: number;\n /** Whether the relay endpoint is TLS (wss/https). Defaults true. */\n tls?: boolean;\n /** The relay's stream-dial path (the `opengeni-relay` wss route). Defaults to\n * \"/stream\" — the route the relay listens on (M8b). */\n path?: string;\n}\n\n/** The relay's default wss dial path (the `opengeni-relay` server route). */\nexport const SELFHOSTED_RELAY_STREAM_PATH = \"/stream\";\n\n/**\n * The op-stream injection (op-stream protocol v1.1 — see op-stream.ts). PRESENT\n * = the streaming exec transport is enabled for this session (the worker\n * injects it only when the runner advertised `Capabilities.op_stream` AND the\n * server flag is on — the leaf carries no flag logic). ABSENT = the legacy\n * monolithic exec, byte-identical to before. The timing knobs exist for tests.\n */\nexport interface SelfhostedOpStreamDeps {\n transport: OpStreamTransport;\n /** The durable-resume journal (attach generation + settled-frontier persist).\n * Absent (tests, non-activity callers) ⇒ generation \"1\", no persistence. */\n journal?: OpStreamJournal;\n windowBytes?: number;\n ackIntervalMs?: number;\n silenceTimeoutMs?: number;\n reconnectHoldMs?: number;\n}\n\nexport interface SelfhostedOperationResourcePolicy {\n memoryMaxBytes?: number | null;\n memoryHighBytes?: number | null;\n cpuMaxMillicores?: number | null;\n}\n\nexport interface SelfhostedBackgroundCommandAdoption {\n controlWorkspaceId: string;\n enrollmentId: string;\n connectionInstanceId: string;\n opId: string;\n command: string;\n /** The exec already failed because the machine stopped answering. Record it\n * with a stop request instead of as a running background command. */\n abandoned?: boolean;\n}\n\n/** Exact command-admission snapshot. A worker resolves this immediately before\n * every exec/Git admission; retries and already-started operations retain it. */\nexport interface SelfhostedOperationAdmission {\n transactionalFsWriteSupported?: boolean;\n /** The live runner serves in-process browser/computer controller requests. */\n browserControlHttpSupported?: boolean;\n /** Workspace segment of the physical agent/relay route. Personal machines may\n * originate in a different same-organization workspace than the session. */\n workspaceId?: string;\n connectionInstanceId: string;\n /** Effective absolute workspace root for this exact live connection and\n * session configuration. A reconnect that changes it cannot continue inside\n * the current turn attempt. */\n workspaceRoot: string;\n opStream?: SelfhostedOpStreamDeps;\n operationResourcePolicy: {\n memoryMaxBytes: number | null;\n memoryHighBytes: number | null;\n cpuMaxMillicores: number | null;\n /** Optimistic-control revision identifies the coherent admission truth; it\n * is not itself an enforcement setting. */\n revision: number;\n };\n operationResourcePolicySupported: boolean;\n operationCpuQuotaSupported: boolean;\n}\n\nexport interface SelfhostedSessionDeps {\n /** Exact live daemon capability; absent preserves legacy small-file writes. */\n transactionalFsWriteSupported?: boolean;\n /** Exact live daemon capability; absent keeps controller requests on the\n * command transport. */\n browserControlHttpSupported?: boolean;\n /** Authorization/session workspace. */\n workspaceId: string;\n /** Physical control-plane workspace. Defaults to workspaceId for legacy and\n * workspace-owned routes. */\n controlWorkspaceId?: string;\n agentId: string;\n /** Exact live daemon process claimed for this enrollment. */\n connectionInstanceId: string;\n controlRpc: ControlRpc;\n relay: SelfhostedRelayConfig;\n /** Effective absolute host-native workspace root. This is the persisted Hello\n * root, optionally resolved with the session's configured relative cwd. */\n workspaceRoot: string;\n /** Stable identity for the session's interactive terminal. Repeated stream\n * capability mints carrying this value reattach the existing PTY/channel\n * instead of spawning a replacement shell. Omitted preserves explicit\n * create-new semantics for non-viewer callers. */\n terminalScopeId?: string;\n /** Op-stream exec transport (present = enabled; see SelfhostedOpStreamDeps). */\n opStream?: SelfhostedOpStreamDeps;\n /** The lease/active epoch this session is fenced under (echoed on every\n * ControlRequest so the agent can reject a stale op with ERROR_CODE_FENCED).\n * Defaults to 0 (no fence) for the negotiation-only / test path. */\n epoch?: number;\n /** The CONTROL-op timeout (ping/fs/desktop/pty and op-stream control RPCs). The\n * agent's own control liveness must stay responsive, so this is short (the 30s\n * default). Override for tests or per-deployment tuning. */\n timeoutMs?: number;\n /**\n * The EXEC process deadline — distinct from `timeoutMs`. A real command\n * (compile, test run, install) routinely outlives the short control timeout, so\n * a positive value asks the agent to kill the child at that wall; 0 means no\n * duration deadline over op-stream. Omitted preserves the `timeoutMs` value\n * fallback for older embedding callers; production settings always thread this\n * field explicitly.\n */\n execTimeoutMs?: number;\n /** Optional per-connection command memory policy. Missing/null values are\n * unrestricted. The runner's local and ancestor policy may only tighten it. */\n operationResourcePolicy?: SelfhostedOperationResourcePolicy;\n /** Exact live Hello capability paired with this connection snapshot. */\n operationResourcePolicySupported?: boolean;\n /** Exact live CPU enforcement capability paired with the same snapshot. */\n operationCpuQuotaSupported?: boolean;\n /** Re-read immediately before every provider operation. It must return\n * connection identity, effective workspace root, policy revision,\n * capabilities, op-stream state, and any caller-owned live authority from one\n * authoritative snapshot. */\n resolveOperationAdmission?: () => Promise<SelfhostedOperationAdmission | null>;\n /** Durable session ownership transfer for model-facing exec that outlives its\n * bounded wait. Omitted for one-off/Channel-A callers, which remain terminal. */\n adoptBackgroundCommand?: (\n input: SelfhostedBackgroundCommandAdoption,\n ) => Promise<{ commandId: string }>;\n captureBackgroundCommandOutput?: (\n commandId: string,\n frames: OpStreamOutputFrame[],\n ) => Promise<void>;\n /** Best-effort fast settlement for the race where an adopted op exits while\n * the adoption transaction is committing. The reconciler remains authority. */\n settleBackgroundCommand?: (input: {\n commandId: string;\n controlWorkspaceId: string;\n enrollmentId: string;\n connectionInstanceId: string;\n opId: string;\n outcome: \"exited\" | \"lost\";\n exitCode: number | null;\n reason: string;\n failure?: import(\"@opengeni/contracts\").SessionCommandFailure;\n outputReceipt?: OpStreamOutputReceipt;\n }) => void | Promise<void>;\n /** The clock the bounded control-op retry loop drives (sleep + jitter). Injected\n * so tests are deterministic; defaults to a real timer + `Math.random()`. */\n retryClock?: SelfhostedRetryClock;\n /** A fire-and-forget observer invoked once per completed control op (out-of-band\n * telemetry — metrics + `machine.*` events). The worker/api wire it to the sinks;\n * the leaf only invokes it (guarded so it can never break an op). Omitted ⇒ no-op. */\n onOp?: SelfhostedOpObserver;\n /**\n * The run's declared sandbox environment — the SAME `Record<string,string>` the\n * worker turn passes to `runtime.buildAgent`'s `sandboxEnvironment` (and that the\n * agent's TARGET manifest, `buildManifest`, carries). The SDK injects this\n * selfhosted session NON-OWNED and applies the agent's manifest as a provided-\n * session delta; `validateNoEnvironmentDelta` throws \"Live sandbox sessions cannot\n * change manifest environment variables\" on ANY env mismatch. So `state.manifest`'s\n * `environment` MUST EQUAL the turn's environment for the delta to be empty. The\n * selfhosted exec routes over NATS and does NOT consume this env (the machine\n * owns its own shell and credentials). The manifest carries the full env only\n * for provided-session parity. Omitted → `{}` (the negotiation-only\n * / test path, which never applies a turn manifest, so there is no delta).\n */\n environment?: Record<string, string>;\n /**\n * Attempt-local values projected onto each newly launched child process.\n * They are deliberately absent from `state`, the manifest, serialized session\n * envelopes, argv, and the machine filesystem. The callback is reread for\n * every exec so worker-side bearer renewal is visible without reconnecting.\n */\n transientExecEnvironment?: () => Readonly<Record<string, string>>;\n}\n\n/** A live reconnect changed the effective host root after this session was\n * bound. No filesystem operation is dispatched under stale path authority. */\nexport class SelfhostedWorkspaceRootChangedError extends Error {\n readonly name = \"SelfhostedWorkspaceRootChangedError\";\n readonly retryable = true;\n\n constructor(\n public readonly expectedWorkspaceRoot: string,\n public readonly actualWorkspaceRoot: string,\n ) {\n super(\n `Connected Machine workspace root changed from \"${expectedWorkspaceRoot}\" to \"${actualWorkspaceRoot}\"; continue in a fresh turn attempt`,\n );\n }\n}\n\n/** The Channel-A `exec` result shape (a structural superset of the SDK's). */\nexport interface SelfhostedExecResult {\n output: string;\n stdout: string;\n stderr: string;\n exitCode: number | null;\n /** True when the agent killed the child at the exec deadline. Additive to the\n * Channel-A superset (consumers that don't read it are unaffected); `exec()`\n * places the deadline hint on stderr so Channel-A stdout stays byte-exact. */\n timedOut?: boolean;\n /** Present only for a model-facing command durably transferred to its session. */\n backgroundCommandId?: string;\n backgroundOpId?: string;\n}\n\n/** The `exec` args the structural surface accepts (mirrors ChannelAExecArgs). */\nexport interface SelfhostedExecArgs {\n cmd: string;\n workdir?: string | undefined;\n shell?: string | undefined;\n login?: boolean | undefined;\n tty?: boolean | undefined;\n yieldTimeMs?: number | undefined;\n maxOutputTokens?: number | undefined;\n runAs?: string | undefined;\n}\n\n/**\n * The persistable session state. For selfhosted this is `{agentId}` ONLY — there\n * is NO provider box id, no snapshot, no manifest. Resume re-addresses the live\n * subject; the machine itself is the persistence (`persistable:false`).\n */\nexport interface SelfhostedSessionState {\n agentId: string;\n}\n\n/**\n * A live selfhosted session — the structural `SandboxSessionLike` surface over a\n * `ControlRpc`. Mirrors Modal's session shape so Channel-A and viewer surfaces\n * consume it unchanged.\n */\nexport class SelfhostedSession {\n readonly backendId = \"selfhosted\" as const;\n readonly workspaceId: string;\n readonly controlWorkspaceId: string;\n readonly agentId: string;\n private readonly controlRpc: ControlRpc;\n /** Attempt scopes this session wrote `{{secretfile:…}}` files under. */\n private readonly secretScopes = new Set<string>();\n private readonly relay: SelfhostedRelayConfig;\n private readonly terminalScopeId: string;\n private readonly epoch: number;\n private readonly timeoutMs: number;\n /** The exec process deadline (0 = none; omission is legacy embedding behavior). */\n private readonly execTimeoutMs: number | undefined;\n private readonly retryClock: SelfhostedRetryClock;\n private readonly onOp: SelfhostedOpObserver | undefined;\n private readonly subject: string;\n /** Command clients are admission-snapshot-bound. Keep them through the turn-end\n * durability hook; never retarget an already-admitted operation on reconnect. */\n private readonly opStreamClients = new Map<string, OpStreamExecClient>();\n private readonly inFlightOpStreamClients = new Map<string, OpStreamExecClient>();\n private readonly inFlightOpStreamOutput = new Map<\n string,\n { stdout: string[]; stderr: string[]; completed?: RemoteOperationObservation }\n >();\n private readonly ownedCommandReaders = new Map<string, () => Promise<void>>();\n private readonly commandRefreshes = new Map<string, Promise<void>>();\n\n /** Attach only to operations adopted by this exact live session. Output and\n * terminal settlement are durable control work, never model observation. */\n async refreshOwnedCommand(commandId: string): Promise<boolean> {\n const read = this.ownedCommandReaders.get(commandId);\n if (!read) return false;\n let pending = this.commandRefreshes.get(commandId);\n if (!pending) {\n pending = read();\n this.commandRefreshes.set(commandId, pending);\n }\n try {\n await pending;\n } finally {\n if (this.commandRefreshes.get(commandId) === pending) this.commandRefreshes.delete(commandId);\n }\n return true;\n }\n private readonly defaultOpStreamClient: OpStreamExecClient | undefined;\n /** Exact host-native root bound for this session/attempt. */\n readonly workspaceRoot: string;\n private readonly transientExecEnvironment: (() => Readonly<Record<string, string>>) | undefined;\n private readonly resourcePolicy: OperationResourcePolicy | undefined;\n private readonly resourcePolicySupported: boolean;\n private readonly operationCpuQuotaSupported: boolean;\n private readonly transactionalFsWriteSupported: boolean;\n private readonly browserControlHttpSupported: boolean;\n private readonly defaultOpStream: SelfhostedOpStreamDeps | undefined;\n private readonly connectionInstanceId: string;\n private readonly resolveOperationAdmission:\n | (() => Promise<SelfhostedOperationAdmission | null>)\n | undefined;\n private readonly adoptBackgroundCommand:\n | SelfhostedSessionDeps[\"adoptBackgroundCommand\"]\n | undefined;\n private readonly settleBackgroundCommand:\n | SelfhostedSessionDeps[\"settleBackgroundCommand\"]\n | undefined;\n private readonly captureBackgroundCommandOutput: SelfhostedSessionDeps[\"captureBackgroundCommandOutput\"];\n\n /**\n * The structural `state` slice consumers read. `agentId`/`instanceId` serve the\n * channel-a `readInstanceId` + docker-network decoration (the agentId IS the\n * identity). `manifest` is the slice the @openai/agents SDK reads AND writes per\n * turn (serializeManifestEnvironment / validateProvidedSessionManifestUpdate read\n * `manifest.root` + iterate `manifest.environment`; providedSessionManifest WRITES\n * `state.manifest = next`). It must be a real, MUTABLE Manifest field — when the\n * RoutingSandboxSession proxy resolves THIS as the active backend it returns\n * `session.state` BY REFERENCE, so the SDK's read and write must both land on a\n * well-formed Manifest here (defined `root`, object `environment`). Without it the\n * SDK crashes with `undefined is not an object (evaluating 'current.root')`.\n *\n * `manifest` is intentionally a plain mutable field (not `readonly`) so the SDK's\n * `state.manifest = next` write succeeds. It is NOT part of the persistable state\n * (`serializeSessionState` round-trips `{agentId}` only).\n *\n * `environment` is the SDK `SandboxSessionState.environment` (a `Record<string,\n * string>`). It MUST be present because the GROUP box's client serializes THIS\n * (the active backend's) state at end-of-turn — the non-owned injected session is\n * serialized via the CONFIGURED client (modal in prod), NOT the selfhosted client.\n * Modal's `serializeRemoteSandboxSessionState` does `Object.entries(state.environment)`;\n * an absent field crashes the post-turn RunState serialize with \"Object.entries\n * requires that input parameter not be null or undefined\". It carries the run's\n * threaded environment (or `{}`). The resulting modal-tagged envelope is inert for\n * selfhosted (resume re-addresses the machine by agentId via the lease pointer,\n * never from this SDK envelope), so its only job is to not crash the serialize.\n */\n readonly state: {\n agentId: string;\n instanceId: string;\n manifest: Manifest;\n environment: Record<string, string>;\n };\n\n constructor(deps: SelfhostedSessionDeps) {\n if (typeof deps.workspaceRoot !== \"string\" || deps.workspaceRoot.length === 0) {\n throw new TypeError(\"Connected Machine workspaceRoot is required\");\n }\n const workspaceRoot = resolveConnectedMachinePath(deps.workspaceRoot, undefined);\n if (workspaceRoot !== deps.workspaceRoot) {\n throw new TypeError(\"Connected Machine workspaceRoot must be a normalized absolute path\");\n }\n this.workspaceId = deps.workspaceId;\n this.controlWorkspaceId = deps.controlWorkspaceId ?? deps.workspaceId;\n this.agentId = deps.agentId;\n this.controlRpc = deps.controlRpc;\n this.relay = deps.relay;\n this.terminalScopeId = deps.terminalScopeId ?? \"\";\n this.epoch = deps.epoch ?? 0;\n this.timeoutMs = deps.timeoutMs ?? SELFHOSTED_DEFAULT_TIMEOUT_MS;\n this.execTimeoutMs = deps.execTimeoutMs;\n this.retryClock = deps.retryClock ?? defaultSelfhostedRetryClock;\n this.onOp = deps.onOp;\n this.subject = subjectFor(this.controlWorkspaceId, deps.agentId, deps.connectionInstanceId);\n this.workspaceRoot = workspaceRoot;\n this.transientExecEnvironment = deps.transientExecEnvironment;\n this.resourcePolicy = normalizeOperationResourcePolicy(deps.operationResourcePolicy);\n this.resourcePolicySupported = deps.operationResourcePolicySupported === true;\n this.operationCpuQuotaSupported = deps.operationCpuQuotaSupported === true;\n this.transactionalFsWriteSupported = deps.transactionalFsWriteSupported === true;\n this.browserControlHttpSupported = deps.browserControlHttpSupported === true;\n this.defaultOpStream = deps.opStream;\n this.connectionInstanceId = deps.connectionInstanceId;\n this.resolveOperationAdmission = deps.resolveOperationAdmission;\n this.adoptBackgroundCommand = deps.adoptBackgroundCommand;\n this.settleBackgroundCommand = deps.settleBackgroundCommand;\n this.captureBackgroundCommandOutput = deps.captureBackgroundCommandOutput;\n // A pre-admission tombstone is safe only for a static connection. Dynamic\n // sessions must never route an unknown op id through their constructor's\n // potentially stale connection after a reconnect.\n this.defaultOpStreamClient =\n deps.opStream && !deps.resolveOperationAdmission\n ? this.opStreamClientFor({\n controlWorkspaceId: this.controlWorkspaceId,\n connectionInstanceId: deps.connectionInstanceId,\n subject: this.subject,\n resourcePolicy: this.resourcePolicy,\n opStream: deps.opStream,\n transactionalFsWriteSupported: this.transactionalFsWriteSupported,\n browserControlHttpSupported: this.browserControlHttpSupported,\n })\n : undefined;\n // A valid Manifest whose root is the machine's actual effective root. There\n // is no virtual /workspace alias and no path translation layer. `environment`\n // is the run's declared\n // sandbox environment — the SAME object the worker turn threads into the agent's\n // TARGET manifest — so the SDK's per-turn provided-session delta\n // (validateNoEnvironmentDelta) finds NO mismatch. `entries: {}` because the\n // selfhosted machine already owns its filesystem (no SDK materialization; exec\n // routes over NATS). Omitted env (the negotiation-only / test path) defaults to\n // `{}` — no turn manifest is applied there, so there is no delta to validate.\n this.state = {\n agentId: deps.agentId,\n instanceId: deps.agentId,\n manifest: new Manifest({\n root: deps.workspaceRoot,\n entries: {},\n environment: deps.environment ?? {},\n }),\n // The SDK `SandboxSessionState.environment` — the run's threaded env (or `{}`).\n // The group client's end-of-turn serialize reads `state.environment` directly\n // (Object.entries), so it must be a defined object, not absent.\n environment: deps.environment ?? {},\n };\n }\n\n /** Invoke the injected per-op observer, guarded: a telemetry tap must NEVER break\n * an op (a throwing sink is swallowed). No-op when no observer is wired. */\n private emitOp(observation: SelfhostedOpObservation): void {\n if (!this.onOp) {\n return;\n }\n try {\n this.onOp(observation);\n } catch {\n // A telemetry sink must never surface into the op path.\n }\n }\n\n private assertResourcePolicySupported(\n policy: OperationResourcePolicy | undefined,\n memorySupported: boolean,\n cpuSupported: boolean,\n ): void {\n const memoryConfigured =\n policy?.memoryMaxBytes !== undefined || policy?.memoryHighBytes !== undefined;\n if (memoryConfigured && !memorySupported) {\n throw new SelfhostedControlError({\n message:\n \"This Connected Machine has an operation memory policy, but its current runner, OS, or service configuration cannot enforce it. Update or reconfigure the installation, or clear the memory policy before executing commands.\",\n code: ErrorCode.ERROR_CODE_UNSUPPORTED,\n reason: null,\n retryable: false,\n });\n }\n if (policy?.cpuMaxMillicores !== undefined && (!memorySupported || !cpuSupported)) {\n throw new SelfhostedControlError({\n message:\n \"This Connected Machine has an operation CPU policy, but its current runner, OS, or service configuration cannot enforce CPU quotas. Update or reconfigure the installation, or clear the CPU policy before executing commands.\",\n code: ErrorCode.ERROR_CODE_UNSUPPORTED,\n reason: null,\n retryable: false,\n });\n }\n }\n\n private async admitOperation(commandPolicy: boolean): Promise<{\n transactionalFsWriteSupported: boolean;\n browserControlHttpSupported: boolean;\n controlWorkspaceId: string;\n connectionInstanceId: string;\n subject: string;\n resourcePolicy: OperationResourcePolicy | undefined;\n opStream: SelfhostedOpStreamDeps | undefined;\n }> {\n if (!this.resolveOperationAdmission) {\n if (commandPolicy) {\n this.assertResourcePolicySupported(\n this.resourcePolicy,\n this.resourcePolicySupported,\n this.operationCpuQuotaSupported,\n );\n }\n return {\n controlWorkspaceId: this.controlWorkspaceId,\n connectionInstanceId: this.connectionInstanceId,\n subject: this.subject,\n resourcePolicy: commandPolicy ? this.resourcePolicy : undefined,\n opStream: this.defaultOpStream,\n transactionalFsWriteSupported: this.transactionalFsWriteSupported,\n browserControlHttpSupported: this.browserControlHttpSupported,\n };\n }\n\n const resolved = await this.resolveOperationAdmission();\n if (!resolved) {\n throw new SelfhostedControlError({\n message: \"The Connected Machine has no authoritative live runner connection.\",\n code: ErrorCode.ERROR_CODE_AGENT_OFFLINE,\n reason: \"agent_offline\",\n retryable: false,\n agentOffline: true,\n });\n }\n if (!connectedMachineWorkspaceRootsEqual(resolved.workspaceRoot, this.workspaceRoot)) {\n throw new SelfhostedWorkspaceRootChangedError(this.workspaceRoot, resolved.workspaceRoot);\n }\n const resourcePolicy = normalizeOperationResourcePolicy(resolved.operationResourcePolicy);\n if (commandPolicy) {\n this.assertResourcePolicySupported(\n resourcePolicy,\n resolved.operationResourcePolicySupported,\n resolved.operationCpuQuotaSupported,\n );\n }\n return {\n controlWorkspaceId: resolved.workspaceId ?? this.controlWorkspaceId,\n connectionInstanceId: resolved.connectionInstanceId,\n subject: subjectFor(\n resolved.workspaceId ?? this.controlWorkspaceId,\n this.agentId,\n resolved.connectionInstanceId,\n ),\n resourcePolicy: commandPolicy ? resourcePolicy : undefined,\n opStream: resolved.opStream,\n transactionalFsWriteSupported: resolved.transactionalFsWriteSupported === true,\n browserControlHttpSupported: resolved.browserControlHttpSupported === true,\n };\n }\n\n private async admitCommand(): Promise<Awaited<ReturnType<SelfhostedSession[\"admitOperation\"]>>> {\n return await this.admitOperation(true);\n }\n\n /** A proven-unstarted op-stream retry may reuse its stable op id, but it must\n * not reuse mutable authorization or silently retarget the command. Require a\n * fresh admission for the exact same physical route and effective policy;\n * callers can start a later operation against a newly resolved route. */\n private async revalidateCommandAdmission(\n expected: Awaited<ReturnType<SelfhostedSession[\"admitCommand\"]>>,\n ): Promise<void> {\n const current = await this.admitCommand();\n const samePolicy =\n current.resourcePolicy?.memoryMaxBytes === expected.resourcePolicy?.memoryMaxBytes &&\n current.resourcePolicy?.memoryHighBytes === expected.resourcePolicy?.memoryHighBytes &&\n current.resourcePolicy?.cpuMaxMillicores === expected.resourcePolicy?.cpuMaxMillicores;\n if (\n current.subject !== expected.subject ||\n current.connectionInstanceId !== expected.connectionInstanceId ||\n Boolean(current.opStream) !== Boolean(expected.opStream) ||\n !samePolicy\n ) {\n throw new SelfhostedControlError({\n message: \"The Connected Machine route or operation policy changed before dispatch.\",\n code: ErrorCode.ERROR_CODE_FENCED,\n reason: null,\n retryable: true,\n fenced: true,\n });\n }\n }\n\n private opStreamClientFor(\n admission: Awaited<ReturnType<SelfhostedSession[\"admitCommand\"]>>,\n ): OpStreamExecClient | undefined {\n const stream = admission.opStream;\n if (!stream) return undefined;\n const key = JSON.stringify([\n admission.controlWorkspaceId,\n admission.connectionInstanceId,\n admission.resourcePolicy?.memoryMaxBytes ?? null,\n admission.resourcePolicy?.memoryHighBytes ?? null,\n admission.resourcePolicy?.cpuMaxMillicores ?? null,\n ]);\n const existing = this.opStreamClients.get(key);\n if (existing) return existing;\n const client = new OpStreamExecClient({\n workspaceId: admission.controlWorkspaceId,\n agentId: this.agentId,\n connectionInstanceId: admission.connectionInstanceId,\n epoch: this.epoch,\n controlRpc: this.controlRpc,\n rpcSubject: admission.subject,\n transport: stream.transport,\n controlTimeoutMs: this.timeoutMs,\n retryClock: this.retryClock,\n ...(admission.resourcePolicy !== undefined\n ? { resourcePolicy: admission.resourcePolicy }\n : {}),\n ...(this.resolveOperationAdmission !== undefined\n ? {\n revalidateBeforeStartRetry: async () =>\n await this.revalidateCommandAdmission(admission),\n }\n : {}),\n ...(stream.journal !== undefined ? { journal: stream.journal } : {}),\n ...(stream.windowBytes !== undefined ? { windowBytes: stream.windowBytes } : {}),\n ...(stream.ackIntervalMs !== undefined ? { ackIntervalMs: stream.ackIntervalMs } : {}),\n ...(stream.silenceTimeoutMs !== undefined\n ? { silenceTimeoutMs: stream.silenceTimeoutMs }\n : {}),\n ...(stream.reconnectHoldMs !== undefined ? { reconnectHoldMs: stream.reconnectHoldMs } : {}),\n });\n this.opStreamClients.set(key, client);\n return client;\n }\n\n /**\n * Issue a control op, decoding the agent's reply or throwing the mapped\n * `SelfhostedControlError` on an AgentError (incl. a synthesized offline /\n * timeout error from the transport).\n *\n * Two failure modes are retried in-place (the decision is the pure\n * `decideSelfhostedRetry` policy):\n * - DRAINING — a pre-admission host-work backpressure rejection; the op never\n * started, so it is safe to re-issue for ANY op kind (bounded).\n * - a TIMEOUT / `agent_reconnecting` blip — re-issued ONCE, and ONLY for a\n * read-only idempotent-safe op. A timed-out MUTATION is NEVER re-issued: it\n * may already have executed on the machine (at-least-once), which would\n * duplicate the write/command. FENCED is intentionally NOT retried here — the\n * routing proxy retries it against a re-resolved backend under a fresh epoch.\n * Each attempt carries a FRESH `requestId` (a retry is a distinct request).\n */\n private async call(\n op: NonNullable<ControlRequest[\"op\"]>,\n timeoutMs = this.timeoutMs,\n admittedCommand?: Awaited<ReturnType<SelfhostedSession[\"admitCommand\"]>>,\n ): Promise<NonNullable<ControlResponse[\"result\"]>> {\n const opKind = op.$case;\n // This is the last shared boundary before every request/reply provider\n // operation. Even a cached routed or pinned session must re-resolve its live\n // authority here; an already-admitted Git operation threads its exact\n // snapshot. Exec uses the op-stream client and never enters this helper.\n const commandOperation = opKind === \"git\";\n let operationAdmission = admittedCommand ?? (await this.admitOperation(commandOperation));\n const startedAt = Date.now();\n let drainingRetries = 0;\n let timeoutRetries = 0;\n let neverSentRetries = 0;\n for (;;) {\n const commandAdmission = opKind === \"git\" ? operationAdmission : undefined;\n const resourcePolicy = commandAdmission?.resourcePolicy;\n const req: ControlRequest = {\n requestId: crypto.randomUUID(),\n epoch: this.epoch,\n resourcePolicy,\n op,\n };\n const res = await this.controlRpc.request(operationAdmission.subject, req, {\n timeoutMs,\n });\n if (!res.error && res.result) {\n const retries = drainingRetries + timeoutRetries + neverSentRetries;\n this.emitOp({\n op: opKind,\n outcome: \"ok\",\n healed: retries > 0,\n retries,\n durationMs: Date.now() - startedAt,\n machineId: this.agentId,\n // A healed op's class is whichever retry budget it recovered from.\n ...(retries > 0\n ? {\n faultClass:\n neverSentRetries > 0\n ? \"offline\"\n : drainingRetries > 0\n ? \"draining\"\n : \"reconnecting\",\n }\n : {}),\n });\n return res.result;\n }\n const error = res.error\n ? agentErrorToControlError(res.error, req.requestId)\n : agentErrorToControlError(\n {\n code: 7, // ERROR_CODE_PROTOCOL — an empty result is a protocol violation\n message: \"agent returned an empty control response\",\n retryable: false,\n detail: {},\n },\n req.requestId,\n );\n const decision = decideSelfhostedRetry({\n opKind,\n error,\n drainingRetries,\n timeoutRetries,\n neverSentRetries,\n jitter: this.retryClock.jitter(),\n });\n if (decision.action === \"fail\") {\n const retries = drainingRetries + timeoutRetries + neverSentRetries;\n const encoded = Number(error.detail.encoded_bytes);\n this.emitOp({\n op: opKind,\n outcome: \"failed\",\n healed: false,\n retries,\n durationMs: Date.now() - startedAt,\n code: error.code,\n reason: error.reason,\n neverSent: error.neverSent,\n machineId: this.agentId,\n faultClass: selfhostedFaultClass(error),\n // Known only on a PAYLOAD_TOO_LARGE fault (the agent's encoded_bytes detail).\n ...(Number.isFinite(encoded) && error.detail.direction !== \"request\"\n ? { replyBytes: encoded }\n : {}),\n });\n // Fold the retry count into the DRAINING copy when we actually retried, so\n // the surfaced message reads \"…retried N times first…\".\n if (error.draining && drainingRetries > 0) {\n throw drainingExhaustedError(error, drainingRetries);\n }\n throw error;\n }\n await this.retryClock.sleep(decision.delayMs);\n // Every physical retry is a new provider dispatch. The retry policy has\n // already proven it safe (never-sent/draining, or read-only timeout), so\n // revalidate live authority without ever replaying an ambiguous mutation.\n operationAdmission = await this.admitOperation(commandOperation);\n // Advance the counter for the class that was retried (separate budgets).\n if (error.neverSent) {\n neverSentRetries += 1;\n } else if (error.draining) {\n drainingRetries += 1;\n } else {\n timeoutRetries += 1;\n }\n }\n }\n\n /** The effective clamped exec process deadline (ms). 0 means no process\n * deadline; positive configured values are clamped to the wire-safe range.\n * Public so adapters that project a\n * structured command receipt can report the exact deadline the agent enforces\n * instead of repeating (and potentially drifting from) this normalization. */\n get effectiveExecDeadlineMs(): number {\n // Production always threads the setting explicitly (default 0). Preserve the\n // short control timeout only for structural/test callers that omit the newer\n // exec field entirely, so those callers remain safely bounded.\n const configured = Math.trunc(this.execTimeoutMs ?? this.timeoutMs);\n if (configured <= 0) return 0;\n return Math.min(configured, SELFHOSTED_MAX_EXEC_TIMEOUT_MS);\n }\n\n /** Host OS family, from the Hello workspace root (drive letter / UNC => Windows). */\n private hostOs(): \"linux\" | \"windows\" | \"unknown\" {\n const root = this.workspaceRoot;\n if (/^[A-Za-z]:[\\\\/]/.test(root) || root.startsWith(\"\\\\\\\\\")) return \"windows\";\n if (root.startsWith(\"/\")) return \"linux\";\n return \"unknown\";\n }\n\n /** The splice dialect a command run through `shell` (or the default) uses here. */\n describeShellDialect(shell?: string): ShellDialect {\n return shellDialectFor(shell?.trim() || null, this.hostOs());\n }\n\n /** Host family for the browser/computer controller transport. */\n controllerHostOs(): \"posix\" | \"windows\" {\n return this.hostOs() === \"windows\" ? \"windows\" : \"posix\";\n }\n\n private async prepareSecretExec(\n args: SelfhostedExecArgs,\n requestedShell: string | undefined,\n ): Promise<{ command: string; shell: string; env: Record<string, string> } | null> {\n const carry = secretExecCarryFor(args.cmd);\n if (!carry) return null;\n const dialect = carry.spliced ? \"posix\" : this.describeShellDialect(requestedShell);\n const spliced = spliceCarry(carry, dialect);\n const command = carry.spliced ? args.cmd : args.cmd.split(carry.command).join(spliced.text);\n const env = await secretExecEnvironment(carry, spliced, async (file) => {\n await this.writePlacementPrivate({ ...file, createParents: true });\n this.secretScopes.add(carry.scope);\n });\n const shell = requestedShell || (dialect === \"powershell\" ? \"powershell\" : \"/bin/sh\");\n return { command, shell, env };\n }\n\n /**\n * Remove this attempt's secret files from the machine (attempt end). Uses the\n * recursive filesystem control op, not a shell, so it works on any host OS\n * and runs even when the consuming command never started.\n */\n async clearSecretFilesForAttempt(scope?: string): Promise<void> {\n const scopes = scope === undefined ? [...this.secretScopes] : [scope];\n for (const entry of scopes) {\n const path = selfhostedPlacementPrivatePath(secretScopeDirectory(entry));\n try {\n const result = await this.call({\n $case: \"fsRemove\",\n fsRemove: { path, recursive: true },\n });\n if (result.$case !== \"fsRemove\") {\n throw new Error(`selfhosted clearSecretFiles: unexpected result ${result.$case}`);\n }\n } catch (error) {\n if (!(error instanceof SelfhostedControlError && error.osNotFound)) throw error;\n }\n this.secretScopes.delete(entry);\n }\n }\n\n /** Channel-A `exec`: run a command on the machine and return its output. */\n async exec(args: SelfhostedExecArgs): Promise<SelfhostedExecResult> {\n return await this.execInternal(args, false);\n }\n\n /** Internal controller transport: stream private request bytes over the\n * existing command channel, never through argv, environment or host files. */\n async execWithInput(\n args: SelfhostedExecArgs & { stdin: Uint8Array },\n ): Promise<SelfhostedExecResult> {\n if (args.stdin.byteLength > SELFHOSTED_PLACEMENT_PRIVATE_MAX_BYTES) {\n throw new RangeError(\"controller command input is too large\");\n }\n return await this.execInternal(args, false, args.stdin.slice());\n }\n\n private async execInternal(\n args: SelfhostedExecArgs,\n allowBackground: boolean,\n stdin: Uint8Array = new Uint8Array(0),\n ): Promise<SelfhostedExecResult> {\n // Mint once before local preflight so a proven refusal can settle exactly\n // this command's turn registration, including SDK-rendered error paths.\n const opId = nextDurableOpId() ?? `anon_${crypto.randomUUID()}`;\n let admission: Awaited<ReturnType<SelfhostedSession[\"admitCommand\"]>>;\n let execReq: ExecRequest;\n let opStreamClient: OpStreamExecClient | undefined;\n // 0 deliberately means no process deadline. That contract is safe only over\n // op-stream: its liveness probes, replay, and cancellation do not depend on a\n // request/reply timer or a monolithic response.\n const executionTimeoutMs = this.effectiveExecDeadlineMs;\n try {\n // Admission is the only mutable-policy read. Everything below retains\n // its exact connection/capability/policy snapshot through completion.\n admission = await this.admitCommand();\n const requestedShell = args.shell?.trim();\n // Secret references (design §10.3, connected machines): splice in the\n // machine's dialect and deliver the values natively in ExecRequest.env.\n // With no explicit shell the command is forced through a known one\n // (`/bin/sh -c` on POSIX, `powershell -NoProfile -NonInteractive\n // -Command` on Windows) so the splice matches the parser. `args.cmd`\n // (references) remains the command recorded for background adoption.\n const secret = await this.prepareSecretExec(args, requestedShell);\n const commandText = secret?.command ?? args.cmd;\n const shell = secret?.shell ?? requestedShell;\n execReq = {\n // An explicit shell is encoded as direct argv so every agent version honors\n // it. With no explicit shell, preserve the existing machine-owned default\n // shell behavior byte-for-byte.\n command: shell\n ? explicitShellArgv(shell, commandText, secret ? false : args.login === true)\n : [commandText],\n shell: !shell,\n // Relative paths resolve from the exact host root, while absolute paths\n // retain their literal machine meaning. In particular, \"/workspace\" is\n // sent as the real absolute path \"/workspace\".\n cwd: resolveConnectedMachinePath(this.workspaceRoot, args.workdir),\n // The machine owns its ambient shell environment and ordinary credentials.\n // Only attempt-local values explicitly supplied by the worker cross here;\n // snapshot now so a later renewal cannot mutate an in-flight request.\n env: { ...(this.transientExecEnvironment?.() ?? {}), ...(secret?.env ?? {}) },\n stdin,\n timeoutMs: executionTimeoutMs,\n };\n opStreamClient = this.opStreamClientFor(admission);\n if (!opStreamClient) throw execRequiresOpStream();\n } catch (error) {\n // This region has issued no command RPC and registered no live consumer.\n // This local fact, not the error's code/shape, proves non-dispatch.\n notifyRemoteOperationNotDispatched(opId);\n throw error;\n }\n try {\n return await this.execViaOpStream(\n opStreamClient,\n admission,\n execReq,\n executionTimeoutMs,\n allowBackground\n ? Math.min(\n SELFHOSTED_BACKGROUND_MAX_YIELD_MS,\n Math.max(1, Math.trunc(args.yieldTimeMs ?? SELFHOSTED_BACKGROUND_DEFAULT_YIELD_MS)),\n )\n : 0,\n args.cmd,\n opId,\n );\n } catch (error) {\n if (error instanceof OpStreamUnavailableError) {\n throw execRequiresOpStream(error);\n }\n throw error;\n }\n }\n\n /**\n * The op-stream exec path: the SAME `ExecRequest`, streamed (see\n * op-stream.ts). The durable op id comes from the tool-call correlation\n * context (`{callId}:{ordinal}` — B1) when this exec runs inside an SDK tool\n * invocation; a non-tool caller falls back to a random unique id (never\n * collides, merely not stable across a turn re-dispatch). Emits the standard\n * per-op observation, with `replyBytes` filled from the reassembled stream\n * (the field the framed transport was designed to own).\n */\n private async execViaOpStream(\n client: OpStreamExecClient,\n admission: Awaited<ReturnType<SelfhostedSession[\"admitCommand\"]>>,\n execReq: ExecRequest,\n executionTimeoutMs: number,\n backgroundYieldMs: number,\n command: string,\n opId: string,\n ): Promise<SelfhostedExecResult> {\n const startedAt = Date.now();\n let adoptedCommandId: string | null = null;\n let ownershipTransferPending = false;\n let terminalProof = false;\n const retainedOutput: {\n stdout: string[];\n stderr: string[];\n completed?: RemoteOperationObservation;\n } = {\n stdout: [],\n stderr: [],\n };\n this.inFlightOpStreamClients.set(opId, client);\n this.inFlightOpStreamOutput.set(opId, retainedOutput);\n const remoteControl: RemoteOperationControl = {\n cancelExecCommand: async (requestedOpId) => {\n if (requestedOpId !== opId) return false;\n await client.cancel(opId);\n return true;\n },\n observeExecCommand: async (requestedOpId) => {\n if (requestedOpId !== opId) {\n throw new Error(\"Remote operation observer received a different operation id\");\n }\n return await this.observeExecCommandWithClient(opId, client, retainedOutput);\n },\n };\n notifyRemoteOperationTransportSelected(remoteControl);\n try {\n const wallMs =\n executionTimeoutMs > 0 ? executionTimeoutMs + SELFHOSTED_EXEC_REPLY_GRACE_MS : 0;\n const result =\n backgroundYieldMs > 0 && this.adoptBackgroundCommand\n ? await client.execWithYield(opId, execReq, executionTimeoutMs, wallMs, {\n yieldMs: backgroundYieldMs,\n captureOutput: async (frames) => {\n if (adoptedCommandId)\n await this.captureBackgroundCommandOutput?.(adoptedCommandId, frames);\n },\n onYield: async () => {\n ownershipTransferPending = true;\n notifyDurableOpOwnershipTransferStarted(opId);\n const adopted = await this.adoptBackgroundCommand!({\n controlWorkspaceId: admission.controlWorkspaceId,\n enrollmentId: this.agentId,\n connectionInstanceId: admission.connectionInstanceId,\n opId,\n command,\n });\n adoptedCommandId = adopted.commandId;\n this.ownedCommandReaders.set(adopted.commandId, async () => {\n const replay = await client.readExisting(opId, 250, async (frames) => {\n await this.captureBackgroundCommandOutput?.(adopted.commandId, frames);\n });\n const terminal = replay.status === \"completed\" ? replay : replay.terminal;\n const outputReceipt =\n replay.outputReceipt ??\n (replay.status === \"running\" ? replay.terminal?.outputReceipt : undefined);\n if (terminal) {\n await this.settleBackgroundCommand?.({\n commandId: adopted.commandId,\n controlWorkspaceId: admission.controlWorkspaceId,\n enrollmentId: this.agentId,\n connectionInstanceId: admission.connectionInstanceId,\n opId,\n outcome: \"exited\",\n ...(this.captureBackgroundCommandOutput && outputReceipt\n ? { outputReceipt }\n : {}),\n exitCode: terminal.outcome.response.exitCode,\n reason: terminal.outcome.failure\n ? `op_failure_${terminal.outcome.failure.failureCode.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 128)}`\n : \"op_exit\",\n ...(terminal.outcome.failure\n ? {\n failure: {\n code: terminal.outcome.failure.failureCode\n .replace(/[^A-Za-z0-9_-]/g, \"_\")\n .slice(0, 128),\n detail: terminal.outcome.failure.failureDetail,\n retryable: false as const,\n },\n }\n : {}),\n });\n this.ownedCommandReaders.delete(adopted.commandId);\n if (terminal.outcome.failure)\n throw runnerFailureToControlError(terminal.outcome.failure);\n }\n });\n ownershipTransferPending = false;\n notifyDurableOpOwnershipTransferred(opId);\n },\n })\n : {\n status: \"completed\" as const,\n outcome: await client.exec(opId, execReq, executionTimeoutMs, wallMs),\n };\n if (result.status === \"running\") {\n terminalProof = result.terminal !== undefined;\n if (result.terminal && adoptedCommandId) {\n await Promise.resolve(\n this.settleBackgroundCommand?.({\n commandId: adoptedCommandId,\n controlWorkspaceId: admission.controlWorkspaceId,\n enrollmentId: this.agentId,\n connectionInstanceId: admission.connectionInstanceId,\n opId,\n outcome: \"exited\",\n ...(this.captureBackgroundCommandOutput && result.terminal.outputReceipt\n ? { outputReceipt: result.terminal.outputReceipt }\n : {}),\n exitCode: result.terminal.outcome.response.exitCode,\n reason: result.terminal.outcome.failure\n ? `op_failure_${result.terminal.outcome.failure.failureCode.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 128)}`\n : \"op_exit\",\n ...(result.terminal.outcome.failure\n ? {\n failure: {\n code: result.terminal.outcome.failure.failureCode\n .replace(/[^A-Za-z0-9_-]/g, \"_\")\n .slice(0, 128),\n detail: result.terminal.outcome.failure.failureDetail,\n retryable: false as const,\n },\n }\n : {}),\n }),\n ).catch(() => undefined);\n }\n const retries = result.heals + result.startRetries;\n this.emitOp({\n op: \"exec\",\n outcome: \"ok\",\n healed: retries > 0,\n retries,\n durationMs: Date.now() - startedAt,\n machineId: this.agentId,\n replyBytes: result.replyBytes,\n ...(retries > 0 ? { faultClass: result.heals > 0 ? \"reconnecting\" : \"draining\" } : {}),\n });\n const stdout = decoder.decode(result.stdout);\n const stderr = decoder.decode(result.stderr);\n return {\n output: stdout,\n stdout,\n stderr,\n exitCode: null,\n timedOut: false,\n backgroundCommandId: adoptedCommandId!,\n backgroundOpId: result.opId,\n };\n }\n terminalProof = true;\n const outcome = result.outcome;\n if (adoptedCommandId) {\n await Promise.resolve(\n this.settleBackgroundCommand?.({\n commandId: adoptedCommandId,\n controlWorkspaceId: admission.controlWorkspaceId,\n enrollmentId: this.agentId,\n connectionInstanceId: admission.connectionInstanceId,\n opId,\n outcome: \"exited\",\n exitCode: outcome.response.exitCode,\n reason: outcome.failure\n ? `op_failure_${outcome.failure.failureCode.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 128)}`\n : \"op_exit\",\n ...(outcome.failure\n ? {\n failure: {\n code: outcome.failure.failureCode.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 128),\n detail: outcome.failure.failureDetail,\n retryable: false as const,\n },\n }\n : {}),\n }),\n ).catch(() => undefined);\n }\n const retries = outcome.heals + outcome.startRetries;\n this.emitOp({\n op: \"exec\",\n outcome: \"ok\",\n healed: retries > 0,\n retries,\n durationMs: Date.now() - startedAt,\n machineId: this.agentId,\n replyBytes: outcome.replyBytes,\n // A healed op's class: attach heals are link blips (reconnecting);\n // start retries without heals were admission backpressure (draining).\n ...(retries > 0 ? { faultClass: outcome.heals > 0 ? \"reconnecting\" : \"draining\" } : {}),\n });\n const nativeResult = execResultToChannelA(outcome.response, executionTimeoutMs);\n retainedOutput.completed = { status: \"completed\", result: nativeResult };\n return nativeResult;\n } catch (error) {\n if (ownershipTransferPending && !adoptedCommandId) {\n // The live consumer's failed-adoption cleanup has also rejected. Its\n // exact client remains retained below, so turn cleanup must rejoin it.\n ownershipTransferPending = false;\n notifyDurableOpOwnershipTransferFailed(opId);\n }\n if (error instanceof OpStreamUnavailableError) throw error;\n const controlError =\n error instanceof SelfhostedControlError\n ? error\n : new SelfhostedControlError({\n message: error instanceof Error ? error.message : String(error),\n code: ErrorCode.ERROR_CODE_PROTOCOL,\n reason: null,\n retryable: false,\n });\n if (\n !terminalProof &&\n !adoptedCommandId &&\n !controlError.neverSent &&\n machineStoppedAnswering(controlError) &&\n this.adoptBackgroundCommand\n ) {\n // The machine went away mid-operation. The command may still run there,\n // but only the machine can stop or report it, so this turn must not wait\n // for it. Hand it to the session's command ledger with a stop request;\n // the reconciler stops or settles it once the machine returns or its\n // runner is retired. If recording fails, turn cleanup keeps ownership.\n try {\n notifyDurableOpOwnershipTransferStarted(opId);\n const abandoned = await this.adoptBackgroundCommand({\n controlWorkspaceId: admission.controlWorkspaceId,\n enrollmentId: this.agentId,\n connectionInstanceId: admission.connectionInstanceId,\n opId,\n command,\n abandoned: true,\n });\n adoptedCommandId = abandoned.commandId;\n notifyDurableOpOwnershipTransferred(opId);\n } catch {\n notifyDurableOpOwnershipTransferFailed(opId);\n }\n }\n this.emitOp({\n op: \"exec\",\n outcome: \"failed\",\n healed: false,\n retries: 0,\n durationMs: Date.now() - startedAt,\n code: controlError.code,\n reason: controlError.reason,\n neverSent: controlError.neverSent,\n machineId: this.agentId,\n faultClass: selfhostedFaultClass(controlError),\n });\n throw controlError;\n } finally {\n // An observer failure does not prove that the exact provider operation\n // stopped. Keep its launch client available for cancellation and\n // readExisting recovery; only terminal proof or durable adoption releases\n // this process-local custody entry.\n if (terminalProof || adoptedCommandId) {\n this.inFlightOpStreamClients.delete(opId);\n this.inFlightOpStreamOutput.delete(opId);\n }\n }\n }\n\n /**\n * The result/turn-end durability hook: persists each settled op's frontier\n * to the journal, then final-acks it on the wire (licensing the runner to GC\n * its retained frames). A tool-scoped call releases only that tool's output\n * after its result is durably recorded. Omit scope only once every settled\n * result has been accepted at the complete turn or one-off API boundary.\n * A no-op for sessions without the op-stream transport.\n */\n async finalizeOpStreamOps(toolCallIds?: readonly string[]): Promise<void> {\n for (const client of this.opStreamClients.values()) {\n await client.finalizeSettledOps(toolCallIds);\n }\n }\n\n // ── The agent-turn provided-session contract (over the SAME NATS primitives) ──\n // These are what the @openai/agents shell/filesystem/skills capabilities call on\n // the ACTIVE session once the routing proxy resolves selfhosted. They reuse the\n // exec/fs ops above; the machine owns its filesystem (materialization is a no-op).\n\n /** SDK shell capability `execCommand`: the `exec_command` tool. Selfhosted exec\n * is non-interactive (no PTY) — `tty` is ignored; `supportsPty()` is false so\n * the SDK never offers a stdin session.\n *\n * Docker/unix-local return `formatExecResponse` (exit code + combined\n * stdout/stderr). This path must match that contract: returning raw stdout\n * made `ls` ENOENT and `npx --help` look like success with empty output.\n * The structured `exec()` result stays split for Channel-A parsers; the\n * deadline hint already lands on stderr there and is included in this body. */\n async execCommand(args: SelfhostedExecArgs): Promise<string> {\n const startedAt = Date.now();\n const result = await this.execInternal(args, true);\n if (result.backgroundCommandId && result.backgroundOpId) {\n const output = joinExecCommandOutput(result.stdout, result.stderr);\n return [\n `Command running in background with command ID ${result.backgroundCommandId}.`,\n `Connected Machine operation ${result.backgroundOpId} remains pinned to its launch daemon.`,\n ...(output ? [\"\", \"Output:\", output] : []),\n ].join(\"\\n\");\n }\n const exitCode =\n typeof result.exitCode === \"number\" && Number.isSafeInteger(result.exitCode)\n ? result.exitCode\n : 1;\n return formatExecResponse({\n output: joinExecCommandOutput(result.stdout, result.stderr),\n wallTimeSeconds: Math.max(0, Date.now() - startedAt) / 1000,\n exitCode,\n });\n }\n\n /**\n * Physical turn-cancellation seam used by the runtime tool fence. Only the\n * op-stream transport has a process-tree cancellation protocol; a legacy\n * runner returns false and the caller remains fail-closed until its exec\n * deadline rather than claiming the machine is quiescent.\n */\n async cancelExecCommand(opId: string): Promise<boolean> {\n const client = this.inFlightOpStreamClients.get(opId) ?? this.defaultOpStreamClient;\n if (!client) return false;\n await client.cancel(opId);\n return true;\n }\n\n /** Reconcile the exact retained foreground exec without OpStart or final ACK.\n * Running/unobservable results keep the pinned client for another attempt. */\n async observeExecCommand(opId: string): Promise<RemoteOperationObservation> {\n const client = this.inFlightOpStreamClients.get(opId);\n if (!client) throw new Error(\"No retained observer is available for this operation\");\n const output = this.inFlightOpStreamOutput.get(opId);\n if (!output) throw new Error(\"No retained output custody is available for this operation\");\n return await this.observeExecCommandWithClient(opId, client, output);\n }\n\n private async observeExecCommandWithClient(\n opId: string,\n client: OpStreamExecClient,\n output: { stdout: string[]; stderr: string[]; completed?: RemoteOperationObservation },\n ): Promise<RemoteOperationObservation> {\n if (output.completed?.status === \"completed\") return output.completed;\n const observed = await client.readExisting(opId, 250, async (frames) => {\n for (const frame of frames) output[frame.stream].push(frame.chunk);\n });\n if (observed.status === \"running\") {\n return {\n status: \"running\",\n result: {\n stdout: output.stdout.join(\"\"),\n stderr: output.stderr.join(\"\"),\n exitCode: null,\n },\n };\n }\n const result = execResultToChannelA(observed.outcome.response, this.effectiveExecDeadlineMs);\n const completed: RemoteOperationObservation = {\n status: \"completed\",\n result: {\n ...result,\n stdout: output.stdout.join(\"\"),\n stderr: output.stderr.join(\"\"),\n output: output.stdout.join(\"\"),\n },\n ...(observed.outcome.failure\n ? { failure: runnerFailureToControlError(observed.outcome.failure) }\n : {}),\n };\n output.completed = completed;\n if (this.inFlightOpStreamClients.get(opId) === client) {\n this.inFlightOpStreamClients.delete(opId);\n this.inFlightOpStreamOutput.delete(opId);\n }\n return completed;\n }\n\n /** SDK shell capability never calls this (gated on `supportsPty()` which is\n * false), but the surface advertises it. Selfhosted exec has no interactive PTY\n * session over the structured RPC, so a stdin write is unsupported. */\n supportsPty(): boolean {\n return false;\n }\n\n /** SDK filesystem capability `view_image`: read the image bytes off the machine\n * and wrap them in the tool-output image shape (magic-byte sniff + path fallback,\n * mirroring the SDK's `imageOutputFromBytes`). */\n async viewImage(args: { path: string; runAs?: string }): Promise<SelfhostedImageOutput> {\n const bytes = await this.readFile({\n path: args.path,\n ...(args.runAs ? { runAs: args.runAs } : {}),\n });\n const mediaType = sniffImageMediaType(bytes, args.path);\n if (!mediaType) {\n throw new Error(`selfhosted view_image: unsupported image format for ${args.path}`);\n }\n return {\n type: \"image\",\n image: { data: Uint8Array.from(bytes), mediaType },\n };\n }\n\n /** SDK skills/filesystem `pathExists`: whether a path exists on the machine. */\n async pathExists(path: string, _runAs?: string): Promise<boolean> {\n const { exists } = await this.statFile({ path });\n return exists;\n }\n\n /** SDK skills `listDir`: list a directory as `{name, path, type}[]`. */\n async listDir(args: {\n path: string;\n runAs?: string;\n }): Promise<Array<{ name: string; path: string; type: \"file\" | \"dir\" | \"other\" }>> {\n const result = await this.listFiles({ path: args.path });\n return result.fsList.entries.map((entry) => ({\n name: entry.name,\n path: entry.path,\n type:\n entry.kind === FsEntryKind.FS_ENTRY_KIND_DIRECTORY\n ? (\"dir\" as const)\n : entry.kind === FsEntryKind.FS_ENTRY_KIND_FILE\n ? (\"file\" as const)\n : (\"other\" as const),\n }));\n }\n\n /** SDK manifest-delta `materializeEntry`: a NO-OP for selfhosted. Source\n * materialization (cloning repos / staging files into the box) is how cloud\n * providers prepare a fresh box; a bring-your-own machine already owns its\n * filesystem and is prepared by the agent itself, so there is nothing to stage.\n * Present (not absent) so the SDK's provided-session manifest apply path — which\n * requires `applyManifest()` OR `materializeEntry()` when the agent declares\n * entries — is satisfied without error. A session swapped from a managed\n * sandbox can still present managed-only manifest entries here; they remain\n * intentionally unstaged on the user-owned machine. */\n async materializeEntry(_args: { path: string; entry: unknown; runAs?: string }): Promise<void> {\n // There is deliberately no provider write for BYO compute, but the model's\n // materialization operation must still fail closed when a cached personal\n // route lost its exact-attempt authority.\n await this.admitOperation(false);\n return;\n }\n\n /** SDK filesystem capability `createEditor`: the apply_patch host. Applies V4A\n * diffs over the NATS fs ops (read → applyDiff → write). `applyDiff` is the SDK's\n * own parser, injected by the runtime barrel (the leaf cannot import it). */\n createEditor(runAs?: string): SelfhostedEditor {\n const applyDiff = injectedApplyDiff;\n if (!applyDiff) {\n throw new Error(\n \"selfhosted createEditor: applyDiff not injected (the runtime barrel must call setSelfhostedApplyDiff before an agent turn binds the filesystem capability)\",\n );\n }\n const pathExists = (path: string): Promise<boolean> => this.pathExists(path, runAs);\n const readText = async (path: string): Promise<string> =>\n decoder.decode(await this.readFile({ path, ...(runAs ? { runAs } : {}) }));\n const writeText = async (\n path: string,\n content: string,\n base?: string | (() => Promise<string | undefined>),\n ): Promise<((source: string, sourceBase: string) => Promise<void>) | undefined> => {\n const bytes = encoder.encode(content);\n // Atomic publication and exact base checks matter for small edits too:\n // a direct fsWrite can be interrupted after truncating the destination.\n // Preserve legacy small moves into write-only destinations: their lazy\n // base reader would introduce a new destination-read requirement.\n if (bytes.byteLength <= SELFHOSTED_FILE_CHUNK_BYTES && typeof base === \"function\") {\n await this.writeFile({ path, content, createParents: true });\n return;\n }\n const initial = await this.admitOperation(false);\n if (!initial.transactionalFsWriteSupported) {\n // Older agents may have a larger negotiated message budget. Preserve\n // their existing writes; a real size rejection remains a typed fault.\n await this.writeFile({ path, content, createParents: true });\n return;\n }\n if (runAs) {\n throw new SelfhostedControlError({\n code: ErrorCode.ERROR_CODE_UNSUPPORTED,\n message:\n \"Transactional file editing does not support runAs impersonation; no file was written.\",\n reason: null,\n retryable: false,\n });\n }\n const requestTransfer = this.fileTransferRequest(initial);\n const resolvedBase = typeof base === \"function\" ? await base() : base;\n const transferStartedAt = Date.now();\n try {\n const result = await transferEditorFile({\n path: resolveConnectedMachinePath(this.workspaceRoot, path),\n content: bytes,\n ...(resolvedBase === undefined ? {} : { baseContent: encoder.encode(resolvedBase) }),\n request: requestTransfer,\n });\n // Unlike physical request observations, this is a verified file outcome.\n this.emitOp({\n op: \"fsWrite\",\n outcome: \"ok\",\n healed: result.recovered,\n retries: 0,\n durationMs: Date.now() - transferStartedAt,\n machineId: this.agentId,\n });\n } catch (error) {\n this.emitOp({\n op: \"fsWrite\",\n outcome: \"failed\",\n healed: false,\n retries: 0,\n durationMs: Date.now() - transferStartedAt,\n machineId: this.agentId,\n });\n throw error;\n }\n return async (source, sourceBase) => {\n // A move is verified destination replacement followed by source cleanup,\n // not an atomic rename. Never retarget cleanup after a runner change.\n // The source check and deletion are not CAS against unrelated writers.\n try {\n const sourcePath = resolveConnectedMachinePath(this.workspaceRoot, source);\n const sourceBytes: Uint8Array[] = [];\n let offset = 0;\n let total = Infinity;\n while (offset < total) {\n const reply = await requestTransfer(crypto.randomUUID(), {\n $case: \"fsRead\",\n fsRead: {\n path: sourcePath,\n offset: String(offset),\n length: String(SELFHOSTED_FILE_CHUNK_BYTES),\n },\n });\n if (reply.error) throw agentErrorToControlError(reply.error);\n if (reply.result?.$case !== \"fsRead\")\n throw new Error(\"Source verification response missing\");\n const part = reply.result.fsRead;\n total = safeWireSize(part.totalSize, \"source file size\");\n if (!part.content.length && offset < total)\n throw new Error(\"Source verification was incomplete\");\n sourceBytes.push(part.content);\n offset += part.content.length;\n }\n const actual = new Uint8Array(offset);\n let cursor = 0;\n for (const chunk of sourceBytes) {\n actual.set(chunk, cursor);\n cursor += chunk.length;\n }\n if (fileContentDigest(actual) !== fileContentDigest(encoder.encode(sourceBase)))\n throw new Error(\"Source changed before move cleanup\");\n const reply = await requestTransfer(crypto.randomUUID(), {\n $case: \"fsRemove\",\n fsRemove: { path: sourcePath, recursive: false },\n });\n if (reply.error) throw agentErrorToControlError(reply.error);\n if (reply.result?.$case !== \"fsRemove\")\n throw new Error(\"Source cleanup response missing\");\n } catch (cause) {\n throw new Error(\n \"The destination edit was verified, but source cleanup was not verified. The move was not replayed; inspect both paths.\",\n { cause },\n );\n }\n };\n };\n const deletePath = async (path: string): Promise<void> => {\n const result = await this.call({\n $case: \"fsRemove\",\n fsRemove: {\n path: resolveConnectedMachinePath(this.workspaceRoot, path),\n recursive: true,\n },\n });\n if (result.$case !== \"fsRemove\") {\n throw new Error(`selfhosted deleteFile: unexpected result ${result.$case}`);\n }\n };\n return {\n async createFile(operation) {\n if (await pathExists(operation.path)) {\n throw new Error(`selfhosted createFile: file already exists: ${operation.path}`);\n }\n await writeText(operation.path, applyDiff(\"\", operation.diff, \"create\"));\n return {};\n },\n async updateFile(operation) {\n const current = await readText(operation.path);\n const next = applyDiff(current, operation.diff);\n const destination = operation.moveTo ?? operation.path;\n const destinationBase =\n destination === operation.path\n ? current\n : async () =>\n (await pathExists(destination)) ? await readText(destination) : undefined;\n const cleanup = await writeText(destination, next, destinationBase);\n if (operation.moveTo && destination !== operation.path) {\n if (cleanup) await cleanup(operation.path, current);\n else await deletePath(operation.path);\n }\n return {};\n },\n async deleteFile(operation) {\n await deletePath(operation.path);\n return {};\n },\n };\n }\n\n /** Channel-A `readFile`: read a file off the machine (binary-safe). */\n async readFile(args: { path: string; runAs?: string; maxBytes?: number }): Promise<Uint8Array> {\n const path = resolveConnectedMachinePath(this.workspaceRoot, args.path);\n const requestedBytes = args.maxBytes ?? Number.POSITIVE_INFINITY;\n const chunks: Uint8Array[] = [];\n let offset = 0;\n let totalSize = Number.POSITIVE_INFINITY;\n\n while (offset < requestedBytes && offset < totalSize) {\n const remaining = Math.min(requestedBytes - offset, SELFHOSTED_FS_READ_CHUNK_BYTES);\n const result = await this.call({\n $case: \"fsRead\",\n fsRead: {\n path,\n offset: String(offset),\n length: String(remaining),\n },\n });\n if (result.$case !== \"fsRead\") {\n throw new Error(`selfhosted readFile: unexpected result ${result.$case}`);\n }\n totalSize = safeWireSize(result.fsRead.totalSize, \"selfhosted file size\");\n if (result.fsRead.content.byteLength === 0) break;\n chunks.push(result.fsRead.content);\n offset += result.fsRead.content.byteLength;\n }\n\n const content = new Uint8Array(offset);\n let cursor = 0;\n for (const chunk of chunks) {\n content.set(chunk, cursor);\n cursor += chunk.byteLength;\n }\n return content;\n }\n\n private fileTransferRequest(initial: Awaited<ReturnType<SelfhostedSession[\"admitOperation\"]>>) {\n return async (\n requestId: string,\n op: NonNullable<ControlRequest[\"op\"]>,\n ): Promise<ControlResponse> => {\n const startedAt = Date.now();\n try {\n const current = await this.admitOperation(false);\n if (\n !current.transactionalFsWriteSupported ||\n current.subject !== initial.subject ||\n current.connectionInstanceId !== initial.connectionInstanceId\n ) {\n throw new Error(\n \"The authorized machine connection changed during the file transfer; the operation was not replayed.\",\n );\n }\n const response = await this.controlRpc.request(\n current.subject,\n {\n requestId,\n epoch: this.epoch,\n op,\n resourcePolicy: undefined,\n },\n { timeoutMs: this.timeoutMs },\n );\n if (response.requestId !== requestId)\n throw new Error(\"The machine returned a mismatched file-transfer response identity.\");\n const error = response.error\n ? agentErrorToControlError(response.error, requestId)\n : undefined;\n this.emitOp({\n op: op.$case,\n outcome: error || !response.result ? \"failed\" : \"ok\",\n healed: false,\n retries: 0,\n durationMs: Date.now() - startedAt,\n machineId: this.agentId,\n ...(error\n ? { code: error.code, reason: error.reason, faultClass: selfhostedFaultClass(error) }\n : {}),\n });\n return response;\n } catch (error) {\n this.emitOp({\n op: op.$case,\n outcome: \"failed\",\n healed: false,\n retries: 0,\n durationMs: Date.now() - startedAt,\n machineId: this.agentId,\n ...(error instanceof SelfhostedControlError\n ? { code: error.code, reason: error.reason, faultClass: selfhostedFaultClass(error) }\n : {}),\n });\n throw error;\n }\n };\n }\n\n /** Write a file onto the machine (the fs surface the descriptor advertises). */\n async writeFile(args: {\n path: string;\n content: string | Uint8Array;\n createParents?: boolean;\n append?: boolean;\n runAs?: string;\n }): Promise<number> {\n const content = typeof args.content === \"string\" ? encoder.encode(args.content) : args.content;\n if (args.runAs) {\n throw new SelfhostedControlError({\n code: ErrorCode.ERROR_CODE_UNSUPPORTED,\n message: \"Native file writes do not support runAs impersonation; no file was written.\",\n reason: null,\n retryable: false,\n });\n }\n if (content.byteLength > SELFHOSTED_FILE_CHUNK_BYTES && !args.append) {\n const initial = await this.admitOperation(false);\n if (initial.transactionalFsWriteSupported) {\n const baseContent = (await this.pathExists(args.path))\n ? await this.readFile({ path: args.path })\n : undefined;\n await transferEditorFile({\n path: resolveConnectedMachinePath(this.workspaceRoot, args.path),\n content,\n ...(baseContent === undefined ? {} : { baseContent }),\n createParents: args.createParents ?? true,\n request: this.fileTransferRequest(initial),\n });\n return content.byteLength;\n }\n }\n const result = await this.call({\n $case: \"fsWrite\",\n fsWrite: {\n path: resolveConnectedMachinePath(this.workspaceRoot, args.path),\n content,\n createParents: args.createParents ?? true,\n append: args.append ?? false,\n mode: 0,\n },\n });\n if (result.$case !== \"fsWrite\") {\n throw new Error(`selfhosted writeFile: unexpected result ${result.$case}`);\n }\n return Number(result.fsWrite.bytesWritten);\n }\n\n /** Stage one bounded controller-owned authority file outside the workspace.\n * The exact private path is deliberately narrower than the ordinary fs\n * surface, and the explicit wire mode keeps the file private even when the\n * Connected Machine agent was launched under a permissive umask. */\n async writePlacementPrivate(args: {\n path: string;\n content: string | Uint8Array;\n createParents?: boolean;\n runAs?: string;\n }): Promise<number> {\n const path = selfhostedPlacementPrivatePath(args.path);\n const content = typeof args.content === \"string\" ? encoder.encode(args.content) : args.content;\n if (content.byteLength > SELFHOSTED_PLACEMENT_PRIVATE_FILE_MAX_BYTES) {\n throw new TypeError(\"selfhosted placement-private content is invalid\");\n }\n const result = await this.call({\n $case: \"fsWrite\",\n fsWrite: {\n path,\n content,\n createParents: args.createParents ?? true,\n append: false,\n mode: 0o600,\n },\n });\n if (result.$case !== \"fsWrite\") {\n throw new Error(`selfhosted writePlacementPrivate: unexpected result ${result.$case}`);\n }\n return Number(result.fsWrite.bytesWritten);\n }\n\n /** Idempotently remove only an Opengeni placement-private authority file.\n * This uses the filesystem control op rather than exec, so cleanup still\n * runs when the consuming command fails before a child process starts. */\n async deletePlacementPrivate(path: string, _runAs?: string): Promise<void> {\n const privatePath = selfhostedPlacementPrivatePath(path);\n try {\n const result = await this.call({\n $case: \"fsRemove\",\n fsRemove: { path: privatePath, recursive: false },\n });\n if (result.$case !== \"fsRemove\") {\n throw new Error(`selfhosted deletePlacementPrivate: unexpected result ${result.$case}`);\n }\n } catch (error) {\n if (error instanceof SelfhostedControlError && error.osNotFound) return;\n throw error;\n }\n }\n\n /** List a directory on the machine. */\n async listFiles(args: {\n path: string;\n recursive?: boolean;\n }): Promise<NonNullable<ControlResponse[\"result\"]> & { $case: \"fsList\" }> {\n const result = await this.call({\n $case: \"fsList\",\n fsList: {\n path: resolveConnectedMachinePath(this.workspaceRoot, args.path),\n recursive: args.recursive ?? false,\n },\n });\n if (result.$case !== \"fsList\") {\n throw new Error(`selfhosted listFiles: unexpected result ${result.$case}`);\n }\n return result;\n }\n\n /** Stat a path on the machine. */\n async statFile(args: { path: string }): Promise<{ exists: boolean }> {\n const result = await this.call({\n $case: \"fsStat\",\n fsStat: { path: resolveConnectedMachinePath(this.workspaceRoot, args.path) },\n });\n if (result.$case !== \"fsStat\") {\n throw new Error(`selfhosted statFile: unexpected result ${result.$case}`);\n }\n return { exists: result.fsStat.exists };\n }\n\n /** Ensure the loopback browser controller sidecar owned by this connected\n * machine. The authority scope is supplied by the caller and remains local. */\n async ensureBrowserControl(\n request: BrowserControlEnsureRequest,\n ): Promise<BrowserControlEnsureResponse> {\n const result = await this.call({\n $case: \"browserControlEnsure\",\n browserControlEnsure: request,\n });\n if (result.$case !== \"browserControlEnsure\") {\n throw new Error(`selfhosted ensureBrowserControl: unexpected result ${result.$case}`);\n }\n return result.browserControlEnsure;\n }\n\n /** Send one request to the agent-owned controller of an exact authority\n * scope, served inside the runner over loopback without starting a process.\n * `unsupported` means this connection's runner does not serve it and nothing\n * was sent. `controller_absent` means no controller for that scope and\n * generation accepted the request, so it was not delivered and the caller may\n * ensure the controller and send again. A body too large for one reply is\n * drained from the runner's spool; the request is never repeated. */\n async browserControlHttp(request: BrowserControlHttpCall): Promise<BrowserControlHttpOutcome> {\n const admission = await this.admitOperation(false);\n if (!admission.browserControlHttpSupported) return { kind: \"unsupported\" };\n // The runner bounds the request by timeoutMs; allow the reply to arrive.\n const rpcTimeoutMs = request.timeoutMs + BROWSER_CONTROL_HTTP_REPLY_GRACE_MS;\n let result: NonNullable<ControlResponse[\"result\"]>;\n try {\n result = await this.call(\n {\n $case: \"browserControlHttp\",\n browserControlHttp: {\n scopeId: request.scopeId,\n scopeGeneration: request.scopeGeneration,\n method: request.method,\n path: request.path,\n bearerToken: request.bearerToken,\n body: request.body ?? new Uint8Array(),\n hasBody: request.body !== undefined,\n timeoutMs: request.timeoutMs,\n maxResponseBytes: String(request.maxResponseBytes),\n },\n },\n rpcTimeoutMs,\n admission,\n );\n } catch (error) {\n if (\n error instanceof SelfhostedControlError &&\n error.code === ErrorCode.ERROR_CODE_NOT_FOUND\n ) {\n return { kind: \"controller_absent\" };\n }\n throw error;\n }\n if (result.$case !== \"browserControlHttp\") {\n throw new Error(`selfhosted browserControlHttp: unexpected result ${result.$case}`);\n }\n const response = result.browserControlHttp;\n const totalBytes = Number(response.totalBytes);\n if (\n !Number.isSafeInteger(totalBytes) ||\n totalBytes < response.body.byteLength ||\n totalBytes > request.maxResponseBytes\n ) {\n throw new Error(\"selfhosted browserControlHttp: response length is invalid\");\n }\n let body = response.body;\n if (response.spoolId) {\n const complete = new Uint8Array(totalBytes);\n complete.set(response.body, 0);\n let offset = response.body.byteLength;\n for (;;) {\n const read = await this.call(\n {\n $case: \"browserControlHttpRead\",\n browserControlHttpRead: { spoolId: response.spoolId, offset: String(offset) },\n },\n this.timeoutMs,\n admission,\n );\n if (read.$case !== \"browserControlHttpRead\") {\n throw new Error(`selfhosted browserControlHttpRead: unexpected result ${read.$case}`);\n }\n const part = read.browserControlHttpRead;\n if (offset + part.data.byteLength > totalBytes) {\n throw new Error(\"selfhosted browserControlHttpRead: response exceeds its length\");\n }\n complete.set(part.data, offset);\n offset += part.data.byteLength;\n if (part.done) break;\n if (part.data.byteLength === 0) {\n throw new Error(\"selfhosted browserControlHttpRead: spool made no progress\");\n }\n }\n if (offset !== totalBytes) {\n throw new Error(\"selfhosted browserControlHttpRead: response is incomplete\");\n }\n body = complete;\n } else if (response.body.byteLength !== totalBytes) {\n throw new Error(\"selfhosted browserControlHttp: response is incomplete\");\n }\n const headers = new Map<string, string>();\n for (const header of response.headers) headers.set(header.name.toLowerCase(), header.value);\n return { kind: \"response\", status: response.status, headers, body };\n }\n\n /** Open one browser-native frame producer and return its canonical relay\n * endpoint. This does not route through `resolveExposedPort`: that legacy\n * method allocates PTY/desktop resources based on fixed ports, while this op\n * returns the exact fresh browser StreamChannel allocated by the agent. */\n async openBrowserFrames(\n request: BrowserFramesOpenRequest,\n ): Promise<{ channel: StreamChannel; endpoint: ExposedPortEndpoint }> {\n const result = await this.call({\n $case: \"browserFramesOpen\",\n browserFramesOpen: request,\n });\n if (result.$case !== \"browserFramesOpen\" || !result.browserFramesOpen.channel) {\n throw new Error(`selfhosted openBrowserFrames: unexpected result ${result.$case}`);\n }\n const channel = result.browserFramesOpen.channel;\n return { channel, endpoint: this.relayEndpoint(channel) };\n }\n\n /** Open one ComputerSession frame producer through the same relay fabric. */\n async openComputerFrames(\n request: ComputerFramesOpenRequest,\n ): Promise<{ channel: StreamChannel; endpoint: ExposedPortEndpoint }> {\n const result = await this.call({\n $case: \"computerFramesOpen\",\n computerFramesOpen: request,\n });\n if (result.$case !== \"computerFramesOpen\" || !result.computerFramesOpen.channel) {\n throw new Error(`selfhosted openComputerFrames: unexpected result ${result.$case}`);\n }\n const channel = result.computerFramesOpen.channel;\n return { channel, endpoint: this.relayEndpoint(channel) };\n }\n\n /** A cheap liveness probe — request a Ping on the subject; returns true iff a\n * responder answered (no AgentError). Used by `negotiateSelfhostedCapabilities`.\n * The wire `nonce` is a uint64 (a numeric string), so the default is a random\n * numeric value — NOT a UUID (which would fail proto uint64 encoding). */\n async ping(nonce = randomNonce()): Promise<boolean> {\n const admission = await this.admitOperation(false);\n const req: ControlRequest = {\n requestId: crypto.randomUUID(),\n epoch: this.epoch,\n resourcePolicy: undefined,\n op: { $case: \"ping\", ping: { nonce } },\n };\n const res = await this.controlRpc.request(admission.subject, req, {\n timeoutMs: this.timeoutMs,\n });\n return !res.error && res.result?.$case === \"ping\";\n }\n\n /**\n * Resolve an exposed port to a relay stream endpoint (the viewer/pty plane).\n * Returns the relay URL SHAPE — `{host:relay, port, tls, query:channel-key}` —\n * after asking the agent to ensure a stream channel for the port. M8b wires the\n * real relay tier (the byte pump) behind THIS seam.\n *\n * THE CHANNEL-KEY QUERY (the M8b relay-dial contract): the relay\n * routes by `{workspaceId, agentId, port, channelId}` — the EXACT `ChannelKey::query` the\n * agent's relay client (`opengeni-agent-stream`) appends when it registers the\n * producer side: `ws=<workspaceId>&agent=<agentId>&port=<port>&channel=<channelId>`.\n * Channel id is routing identity, not a correlation hint, so concurrent PTYs\n * on one connected machine never replace one another. The viewer\n * dials `wss://<relay>/stream?ws=&agent=&port=&channel=` and presents the minted\n * `ogs_` token in-band (NEVER as a URL param) — the relay pairs it with the\n * producer by the routing key.\n */\n async resolveExposedPort(port: number): Promise<ExposedPortEndpoint> {\n // Ask the agent to ensure a relay PRODUCER channel exists for the port, using the\n // PORT-APPROPRIATE op. The PTY plane (7681) is INDEPENDENT of the desktop display:\n // route it through `ptyOpen` (which spawns/attaches a PTY and NEVER touches X11),\n // and ONLY the desktop framebuffer plane (6080) through `desktopEnsure` (which\n // hard-requires a live virtual display). Earlier M8b used `desktopEnsure` for\n // EVERY port — that wrongly coupled the terminal to the desktop probe, so a\n // headless (or display-degraded) machine could never get a terminal even though\n // `ptyOpen` would have succeeded. The returned channelId is the relay\n // routing identity; both ops carry a `StreamChannel` on their response.\n let channel: StreamChannel | undefined;\n if (port === DESKTOP_STREAM_PORT) {\n const result = await this.call({\n $case: \"desktopEnsure\",\n desktopEnsure: { width: 0, height: 0 },\n });\n if (result.$case !== \"desktopEnsure\") {\n throw new Error(\n `selfhosted resolveExposedPort(${port}): unexpected result ${result.$case}`,\n );\n }\n channel = result.desktopEnsure.channel;\n } else {\n // The PTY plane (7681) + any non-desktop stream port. `command: []` => the\n // user's default login shell; the agent's pty_pump bridges the PTY master to\n // the relay channel. Display-INDEPENDENT — works on a headless machine.\n const result = await this.call({\n $case: \"ptyOpen\",\n // Open the terminal in the exact host-native root bound to this session.\n ptyOpen: {\n command: [],\n cwd: this.workspaceRoot,\n env: {},\n cols: 0,\n rows: 0,\n term: \"xterm-256color\",\n scopeId: this.terminalScopeId,\n },\n });\n if (result.$case !== \"ptyOpen\") {\n throw new Error(\n `selfhosted resolveExposedPort(${port}): unexpected result ${result.$case}`,\n );\n }\n channel = result.ptyOpen.channel;\n }\n if (channel) return this.relayEndpoint(channel);\n const channelId = channelKey(this.controlWorkspaceId, this.agentId, port);\n const tls = this.relay.tls ?? true;\n // The routing key the relay pairs producer↔consumer by — IDENTICAL to the\n // agent's `ChannelKey::query`, including the stream-instance channel id.\n const routingQuery =\n `ws=${encodeURIComponent(this.controlWorkspaceId)}` +\n `&agent=${encodeURIComponent(this.agentId)}` +\n `&port=${port}` +\n `&channel=${encodeURIComponent(channelId)}`;\n return {\n host: this.relay.host,\n port: this.relay.port ?? (tls ? 443 : 80),\n tls,\n // The relay's wss route (`/stream`); buildStreamUrl honors `path`.\n path: this.relay.path ?? SELFHOSTED_RELAY_STREAM_PATH,\n query: routingQuery,\n };\n }\n\n private relayEndpoint(channel: StreamChannel): ExposedPortEndpoint {\n const tls = this.relay.tls ?? true;\n const routingQuery =\n `ws=${encodeURIComponent(channel.workspaceId)}` +\n `&agent=${encodeURIComponent(channel.agentId)}` +\n `&port=${channel.port}` +\n `&channel=${encodeURIComponent(channel.channelId)}`;\n return {\n host: this.relay.host,\n port: this.relay.port ?? (tls ? 443 : 80),\n tls,\n path: this.relay.path ?? SELFHOSTED_RELAY_STREAM_PATH,\n query: routingQuery,\n protocol: kindToProtocol(channel.kind),\n };\n }\n\n /** Round-trip the persistable state — `{agentId}` ONLY (resume = re-address). */\n async serializeSessionState(): Promise<SelfhostedSessionState> {\n return { agentId: this.agentId };\n }\n}\n\n/**\n * The selfhosted SDK-client surface the registry builds. `backendId:\"selfhosted\"`\n * (the resume-fence field asserted against the descriptor). `create()`/`resume()`\n * return a `SelfhostedSession` bound to `{workspaceId, agentId, controlRpc}`.\n *\n * `create()` and `resume()` are IDENTICAL for selfhosted — there is no box to\n * provision (the machine already exists); both just bind a session to the live\n * subject. `serializeSessionState`/`deserializeSessionState` round-trip\n * `{agentId}` only.\n *\n * The `controlRpc` is constructed LAZILY via an injected factory (defaulting to\n * `NatsControlRpc`); a session built before NATS is configured surfaces\n * `agent_offline` on its first op rather than failing at construction.\n */\nexport class SelfhostedSandboxClient {\n readonly backendId = \"selfhosted\" as const;\n readonly supportsDefaultOptions = false;\n private readonly workspaceId: string;\n private readonly controlWorkspaceId: string | undefined;\n private readonly relay: SelfhostedRelayConfig;\n private readonly controlRpcFactory: () => ControlRpc;\n private readonly defaultAgentId: string | undefined;\n private readonly connectionInstanceId: string | undefined;\n private readonly terminalScopeId: string | undefined;\n private readonly epoch: number | undefined;\n private readonly timeoutMs: number | undefined;\n private readonly execTimeoutMs: number | undefined;\n private readonly environment: Record<string, string> | undefined;\n private readonly transientExecEnvironment: (() => Readonly<Record<string, string>>) | undefined;\n private readonly workspaceRoot: string;\n private readonly operationResourcePolicy: SelfhostedOperationResourcePolicy | undefined;\n private readonly operationResourcePolicySupported: boolean | undefined;\n private readonly operationCpuQuotaSupported: boolean | undefined;\n private readonly transactionalFsWriteSupported: boolean | undefined;\n private readonly browserControlHttpSupported: boolean | undefined;\n private readonly resolveOperationAdmission:\n | (() => Promise<SelfhostedOperationAdmission | null>)\n | undefined;\n private readonly adoptBackgroundCommand:\n | SelfhostedSessionDeps[\"adoptBackgroundCommand\"]\n | undefined;\n private readonly settleBackgroundCommand:\n | SelfhostedSessionDeps[\"settleBackgroundCommand\"]\n | undefined;\n private readonly captureBackgroundCommandOutput: SelfhostedSessionDeps[\"captureBackgroundCommandOutput\"];\n private readonly onOp: SelfhostedOpObserver | undefined;\n private readonly opStream: SelfhostedOpStreamDeps | undefined;\n private controlRpcMemo: ControlRpc | undefined;\n\n constructor(opts: {\n workspaceId: string;\n controlWorkspaceId?: string;\n relay: SelfhostedRelayConfig;\n /** Lazily build the ControlRpc (defaults to NatsControlRpc in the provider). */\n controlRpcFactory: () => ControlRpc;\n /** Exact effective host-native root threaded into every bound session. */\n workspaceRoot: string;\n /** The agentId a bare create()/resume() (no state) binds to. Optional: the\n * resume path supplies it via deserializeSessionState. */\n agentId?: string;\n /** Exact live daemon process. Optional only for the inert registry client;\n * any live create()/resume() fails closed until one is bound. */\n connectionInstanceId?: string;\n /** Stable terminal identity (normally the durable Opengeni session id). */\n terminalScopeId?: string;\n epoch?: number;\n /** The control-op timeout threaded into every bound session. */\n timeoutMs?: number;\n /** The exec process deadline threaded into every bound session (distinct from\n * `timeoutMs`; 0 means no duration deadline, while omission preserves the\n * historical control-timeout value fallback for embedding callers). */\n execTimeoutMs?: number;\n operationResourcePolicy?: SelfhostedOperationResourcePolicy;\n operationResourcePolicySupported?: boolean;\n operationCpuQuotaSupported?: boolean;\n transactionalFsWriteSupported?: boolean;\n browserControlHttpSupported?: boolean;\n resolveOperationAdmission?: () => Promise<SelfhostedOperationAdmission | null>;\n adoptBackgroundCommand?: SelfhostedSessionDeps[\"adoptBackgroundCommand\"];\n settleBackgroundCommand?: SelfhostedSessionDeps[\"settleBackgroundCommand\"];\n captureBackgroundCommandOutput?: SelfhostedSessionDeps[\"captureBackgroundCommandOutput\"];\n /** The run's declared sandbox environment, threaded into every bound session's\n * `state.manifest.environment` so the SDK's per-turn manifest-env delta is\n * empty (validateNoEnvironmentDelta). See SelfhostedSessionDeps.environment.\n * Omitted → `{}` (the negotiation-only path; no turn manifest is applied). */\n environment?: Record<string, string>;\n /** Attempt-local child-process environment; never persisted or manifested. */\n transientExecEnvironment?: () => Readonly<Record<string, string>>;\n /** The per-op observer threaded into every bound session (out-of-band telemetry). */\n onOp?: SelfhostedOpObserver;\n /** The op-stream exec transport threaded into every bound session (present\n * = enabled; see SelfhostedOpStreamDeps). */\n opStream?: SelfhostedOpStreamDeps;\n }) {\n this.workspaceId = opts.workspaceId;\n this.controlWorkspaceId = opts.controlWorkspaceId;\n this.relay = opts.relay;\n this.controlRpcFactory = opts.controlRpcFactory;\n this.workspaceRoot = opts.workspaceRoot;\n this.defaultAgentId = opts.agentId;\n this.connectionInstanceId = opts.connectionInstanceId;\n this.terminalScopeId = opts.terminalScopeId;\n this.epoch = opts.epoch;\n this.timeoutMs = opts.timeoutMs;\n this.execTimeoutMs = opts.execTimeoutMs;\n this.operationResourcePolicy = opts.operationResourcePolicy;\n this.operationResourcePolicySupported = opts.operationResourcePolicySupported;\n this.operationCpuQuotaSupported = opts.operationCpuQuotaSupported;\n this.transactionalFsWriteSupported = opts.transactionalFsWriteSupported;\n this.browserControlHttpSupported = opts.browserControlHttpSupported;\n this.resolveOperationAdmission = opts.resolveOperationAdmission;\n this.adoptBackgroundCommand = opts.adoptBackgroundCommand;\n this.settleBackgroundCommand = opts.settleBackgroundCommand;\n this.captureBackgroundCommandOutput = opts.captureBackgroundCommandOutput;\n this.environment = opts.environment;\n this.transientExecEnvironment = opts.transientExecEnvironment;\n this.onOp = opts.onOp;\n this.opStream = opts.opStream;\n }\n\n private controlRpc(): ControlRpc {\n if (!this.controlRpcMemo) {\n this.controlRpcMemo = this.controlRpcFactory();\n }\n return this.controlRpcMemo;\n }\n\n private bind(agentId: string): SelfhostedSession {\n return new SelfhostedSession({\n workspaceId: this.workspaceId,\n ...(this.controlWorkspaceId !== undefined\n ? { controlWorkspaceId: this.controlWorkspaceId }\n : {}),\n agentId,\n connectionInstanceId: this.requireConnectionInstanceId(),\n controlRpc: this.controlRpc(),\n relay: this.relay,\n workspaceRoot: this.workspaceRoot,\n ...(this.terminalScopeId !== undefined ? { terminalScopeId: this.terminalScopeId } : {}),\n ...(this.epoch !== undefined ? { epoch: this.epoch } : {}),\n ...(this.timeoutMs !== undefined ? { timeoutMs: this.timeoutMs } : {}),\n ...(this.execTimeoutMs !== undefined ? { execTimeoutMs: this.execTimeoutMs } : {}),\n ...(this.operationResourcePolicy !== undefined\n ? { operationResourcePolicy: this.operationResourcePolicy }\n : {}),\n ...(this.operationResourcePolicySupported !== undefined\n ? {\n operationResourcePolicySupported: this.operationResourcePolicySupported,\n }\n : {}),\n ...(this.operationCpuQuotaSupported !== undefined\n ? { operationCpuQuotaSupported: this.operationCpuQuotaSupported }\n : {}),\n transactionalFsWriteSupported: this.transactionalFsWriteSupported === true,\n browserControlHttpSupported: this.browserControlHttpSupported === true,\n ...(this.resolveOperationAdmission !== undefined\n ? { resolveOperationAdmission: this.resolveOperationAdmission }\n : {}),\n ...(this.adoptBackgroundCommand !== undefined\n ? { adoptBackgroundCommand: this.adoptBackgroundCommand }\n : {}),\n ...(this.settleBackgroundCommand !== undefined\n ? { settleBackgroundCommand: this.settleBackgroundCommand }\n : {}),\n ...(this.captureBackgroundCommandOutput\n ? { captureBackgroundCommandOutput: this.captureBackgroundCommandOutput }\n : {}),\n ...(this.environment !== undefined ? { environment: this.environment } : {}),\n ...(this.transientExecEnvironment !== undefined\n ? { transientExecEnvironment: this.transientExecEnvironment }\n : {}),\n ...(this.onOp !== undefined ? { onOp: this.onOp } : {}),\n ...(this.opStream !== undefined ? { opStream: this.opStream } : {}),\n });\n }\n\n /** Bind a session to the live agent subject. There is no box to provision. */\n async create(_manifest?: unknown, _options?: unknown): Promise<SelfhostedSession> {\n const agentId = this.requireAgentId();\n return this.bind(agentId);\n }\n\n /** Resume = re-address the subject. Identical to create — no provider state. */\n async resume(\n state: SelfhostedSessionState | Record<string, unknown>,\n _options?: unknown,\n ): Promise<SelfhostedSession> {\n const agentId = readAgentId(state) ?? this.requireAgentId();\n return this.bind(agentId);\n }\n\n /** Serialize a live session's state → `{agentId}` ONLY. */\n async serializeSessionState(\n state: SelfhostedSessionState | { agentId?: string } | unknown,\n ): Promise<SelfhostedSessionState> {\n const agentId = readAgentId(state) ?? this.requireAgentId();\n return { agentId };\n }\n\n /** Deserialize `{agentId}` from the persisted envelope. */\n async deserializeSessionState(state: Record<string, unknown>): Promise<SelfhostedSessionState> {\n const agentId = readAgentId(state) ?? this.requireAgentId();\n return { agentId };\n }\n\n /** selfhosted is NOT persistable — there is no owned session state to preserve\n * (the machine is the persistence). The lease never snapshots it. */\n async canPersistOwnedSessionState(): Promise<boolean> {\n return false;\n }\n\n private requireAgentId(): string {\n if (!this.defaultAgentId) {\n throw new Error(\n \"selfhosted sandbox client: no agentId bound (create()/resume() need a session state carrying agentId)\",\n );\n }\n return this.defaultAgentId;\n }\n\n private requireConnectionInstanceId(): string {\n if (!this.connectionInstanceId) {\n throw new Error(\n \"selfhosted sandbox client: no connectionInstanceId bound (live create()/resume() requires an exact claimed daemon instance)\",\n );\n }\n return this.connectionInstanceId;\n }\n}\n\n/**\n * The dependency shape `buildSelfhostedBackendSession` needs to bind a live\n * selfhosted session to a target machine. A structural superset of the fields the\n * routing resolver (backend-resolver.ts) reads off its deps + pointer, and the\n * fields the WORKER turn's machine-primary establish branch threads in — so a\n * SINGLE build shape is shared by both (never two divergent constructions of the\n * same SelfhostedSandboxClient/resume pair).\n */\nexport interface SelfhostedSessionBuild {\n /** Authorization/session workspace. */\n workspaceId: string;\n /** Physical machine-origin workspace used in agent and relay routes. */\n controlWorkspaceId?: string;\n /** The enrollment id == the agent id the exact process subject addresses. */\n agentId: string;\n /** Exact daemon instance holding the enrollment's live connection lease. */\n connectionInstanceId: string;\n /** The relay-URL shape for stream endpoints. */\n relay: SelfhostedRelayConfig;\n /** Stable terminal identity; normally the durable Opengeni session id. */\n terminalScopeId?: string;\n /** Lazily build the live ControlRpc (the request-scoped NATS connection). */\n controlRpcFactory: () => ControlRpc;\n /** Exact effective host-native root for this session. */\n workspaceRoot: string;\n /** The lease/active epoch the session is fenced under (echoed on every op). */\n epoch: number;\n /** The run's declared sandbox environment → the session manifest.environment\n * (env-parity; see SelfhostedSessionDeps.environment). */\n environment?: Record<string, string>;\n /** Attempt-local child-process values; see SelfhostedSessionDeps. */\n transientExecEnvironment?: () => Readonly<Record<string, string>>;\n /** The control-op timeout (ping/fs/desktop/pty). Absent ⇒ the 30s default. */\n timeoutMs?: number;\n /** The exec process deadline, distinct from `timeoutMs`. 0 = none; absence\n * preserves the historical control-timeout value fallback for embedding callers. */\n execTimeoutMs?: number;\n /** Per-enrollment optional command policy resolved from the same database\n * snapshot as the exact connection identity. */\n operationResourcePolicy?: SelfhostedOperationResourcePolicy;\n /** Exact live runner capability paired with that snapshot. */\n operationResourcePolicySupported?: boolean;\n /** Exact live CPU enforcement capability paired with the initial snapshot. */\n operationCpuQuotaSupported?: boolean;\n transactionalFsWriteSupported?: boolean;\n /** Exact live runner capability for in-process controller requests. */\n browserControlHttpSupported?: boolean;\n /** Live last-boundary operation admission resolver; see SelfhostedSessionDeps. */\n resolveOperationAdmission?: () => Promise<SelfhostedOperationAdmission | null>;\n adoptBackgroundCommand?: SelfhostedSessionDeps[\"adoptBackgroundCommand\"];\n settleBackgroundCommand?: SelfhostedSessionDeps[\"settleBackgroundCommand\"];\n captureBackgroundCommandOutput?: SelfhostedSessionDeps[\"captureBackgroundCommandOutput\"];\n /** The per-op observer (out-of-band telemetry). Absent ⇒ no-op. */\n onOp?: SelfhostedOpObserver;\n /** The op-stream exec transport (present when the runner advertises it and the\n * server flag is on). Required for every Connected Machine exec command. */\n opStream?: SelfhostedOpStreamDeps;\n}\n\n/**\n * Build a live selfhosted session bound to a target machine: construct a request-\n * scoped `SelfhostedSandboxClient` (fenced under `epoch`, carrying the run's env +\n * working dir) and `resume()` it (= re-address the live subject — no provider box\n * is created). Returns BOTH the client (the OWNED-sandbox client the turn injects,\n * whose `serializeSessionState` round-trips `{agentId}`) and the live session.\n *\n * Shared by:\n * - the routing resolver (backend-resolver.ts) — a swap target, where only the\n * session is needed; and\n * - the worker turn's machine-primary establish branch — where the client is the\n * owned-sandbox client AND the session is the pinned routing default.\n * Factoring it here keeps the two builds identical (no divergence in the fence\n * epoch, env threading, or working-dir base).\n */\nexport async function buildSelfhostedBackendSession(\n deps: SelfhostedSessionBuild,\n): Promise<{ client: SelfhostedSandboxClient; session: SelfhostedSession }> {\n const client = new SelfhostedSandboxClient({\n workspaceId: deps.workspaceId,\n ...(deps.controlWorkspaceId !== undefined\n ? { controlWorkspaceId: deps.controlWorkspaceId }\n : {}),\n relay: deps.relay,\n controlRpcFactory: deps.controlRpcFactory,\n workspaceRoot: deps.workspaceRoot,\n agentId: deps.agentId,\n connectionInstanceId: deps.connectionInstanceId,\n epoch: deps.epoch,\n ...(deps.terminalScopeId !== undefined ? { terminalScopeId: deps.terminalScopeId } : {}),\n ...(deps.timeoutMs !== undefined ? { timeoutMs: deps.timeoutMs } : {}),\n ...(deps.execTimeoutMs !== undefined ? { execTimeoutMs: deps.execTimeoutMs } : {}),\n ...(deps.operationResourcePolicy !== undefined\n ? { operationResourcePolicy: deps.operationResourcePolicy }\n : {}),\n ...(deps.operationResourcePolicySupported !== undefined\n ? {\n operationResourcePolicySupported: deps.operationResourcePolicySupported,\n }\n : {}),\n ...(deps.operationCpuQuotaSupported !== undefined\n ? { operationCpuQuotaSupported: deps.operationCpuQuotaSupported }\n : {}),\n transactionalFsWriteSupported: deps.transactionalFsWriteSupported === true,\n browserControlHttpSupported: deps.browserControlHttpSupported === true,\n ...(deps.resolveOperationAdmission !== undefined\n ? { resolveOperationAdmission: deps.resolveOperationAdmission }\n : {}),\n ...(deps.adoptBackgroundCommand !== undefined\n ? { adoptBackgroundCommand: deps.adoptBackgroundCommand }\n : {}),\n ...(deps.settleBackgroundCommand !== undefined\n ? { settleBackgroundCommand: deps.settleBackgroundCommand }\n : {}),\n ...(deps.captureBackgroundCommandOutput\n ? { captureBackgroundCommandOutput: deps.captureBackgroundCommandOutput }\n : {}),\n ...(deps.onOp !== undefined ? { onOp: deps.onOp } : {}),\n ...(deps.environment !== undefined ? { environment: deps.environment } : {}),\n ...(deps.transientExecEnvironment !== undefined\n ? { transientExecEnvironment: deps.transientExecEnvironment }\n : {}),\n ...(deps.opStream !== undefined ? { opStream: deps.opStream } : {}),\n });\n const session = await client.resume({ agentId: deps.agentId });\n return { client, session };\n}\n\nfunction readAgentId(state: unknown): string | undefined {\n if (state && typeof state === \"object\") {\n const candidate =\n (state as { agentId?: unknown }).agentId ??\n (state as { providerState?: { agentId?: unknown } }).providerState?.agentId;\n if (typeof candidate === \"string\" && candidate.length > 0) {\n return candidate;\n }\n }\n return undefined;\n}\n\nfunction safeWireSize(value: string, label: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new Error(`${label} is outside the supported range`);\n }\n return parsed;\n}\n\nfunction selfhostedPlacementPrivatePath(value: unknown): string {\n if (\n typeof value !== \"string\" ||\n value.length < `${SELFHOSTED_PLACEMENT_PRIVATE_PREFIX}x`.length ||\n value.length > 4_096 ||\n !value.startsWith(SELFHOSTED_PLACEMENT_PRIVATE_PREFIX) ||\n /[\\u0000-\\u001f\\u007f]/u.test(value) ||\n value.split(\"/\").some((segment) => segment === \".\" || segment === \"..\")\n ) {\n throw new TypeError(\"selfhosted placement-private path is invalid\");\n }\n return value;\n}\n\nfunction joinExecCommandOutput(stdout: string, stderr: string): string {\n return [stdout, stderr].filter((value) => value.trim().length > 0).join(\"\\n\");\n}\n\nfunction execResultToChannelA(res: ExecResponse, execDeadlineMs: number): SelfhostedExecResult {\n const stdout = decoder.decode(res.stdout);\n let stderr = decoder.decode(res.stderr);\n if (res.timedOut && execDeadlineMs > 0) {\n // The agent killed the child at the exec deadline. Surface an actionable hint\n // on STDERR ONLY — stdout is left byte-exact because the structural Channel-A\n // surface parses command stdout (find/stat/git listings); a hint injected there\n // would corrupt those parsers.\n const hint = execDeadlineHint(Math.round(execDeadlineMs / 1000));\n stderr = stderr ? `${stderr}\\n${hint}` : hint;\n }\n return {\n output: stdout,\n stdout,\n stderr,\n exitCode: res.exitCode,\n timedOut: res.timedOut,\n };\n}\n\nfunction execRequiresOpStream(cause?: OpStreamUnavailableError): SelfhostedControlError {\n const runnerUpgrade = cause?.unavailableKind === \"runner\" || cause === undefined;\n return new SelfhostedControlError({\n message: runnerUpgrade\n ? \"This Connected Machine does not advertise the streaming command protocol required for exec. Update and reconnect the Opengeni agent. The command was not started.\"\n : \"The Connected Machine streaming channel is temporarily unavailable. Opengeni did not downgrade to an ambiguous request/reply command; the command was not started. Retry after the machine reconnects.\",\n code: runnerUpgrade ? ErrorCode.ERROR_CODE_UNSUPPORTED : ErrorCode.ERROR_CODE_STREAM,\n reason: runnerUpgrade ? null : \"agent_reconnecting\",\n retryable: !runnerUpgrade,\n });\n}\n\nfunction channelKey(workspaceId: string, agentId: string, port: number): string {\n return `${workspaceId}:${agentId}:${port}`;\n}\n\n/** Detect an image media type from magic bytes (with a path-extension fallback),\n * mirroring @openai/agents-core's `sniffImageMediaType` so `viewImage` returns the\n * SAME media types the SDK would. Returns undefined for an unrecognized format. */\nfunction sniffImageMediaType(bytes: Uint8Array, path: string): string | undefined {\n if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47)\n return \"image/png\";\n if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return \"image/jpeg\";\n if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38)\n return \"image/gif\";\n if (\n bytes[0] === 0x52 &&\n bytes[1] === 0x49 &&\n bytes[2] === 0x46 &&\n bytes[3] === 0x46 &&\n bytes[8] === 0x57 &&\n bytes[9] === 0x45 &&\n bytes[10] === 0x42 &&\n bytes[11] === 0x50\n )\n return \"image/webp\";\n if (bytes[0] === 0x42 && bytes[1] === 0x4d) return \"image/bmp\";\n if (\n (bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 0x2a && bytes[3] === 0x00) ||\n (bytes[0] === 0x4d && bytes[1] === 0x4d && bytes[2] === 0x00 && bytes[3] === 0x2a)\n )\n return \"image/tiff\";\n if (looksLikeSvg(bytes)) return \"image/svg+xml\";\n return mediaTypeFromPath(path);\n}\n\nfunction looksLikeSvg(bytes: Uint8Array): boolean {\n const prefix = decoder\n .decode(bytes.subarray(0, Math.min(bytes.byteLength, 512)))\n .trimStart()\n .toLowerCase();\n return prefix.startsWith(\"<svg\") || /^<\\?xml[\\s\\S]*<svg/u.test(prefix);\n}\n\nfunction mediaTypeFromPath(path: string): string | undefined {\n const p = path?.trim().toLowerCase() ?? \"\";\n if (p.endsWith(\".png\")) return \"image/png\";\n if (p.endsWith(\".jpg\") || p.endsWith(\".jpeg\")) return \"image/jpeg\";\n if (p.endsWith(\".gif\")) return \"image/gif\";\n if (p.endsWith(\".webp\")) return \"image/webp\";\n if (p.endsWith(\".bmp\")) return \"image/bmp\";\n if (p.endsWith(\".tif\") || p.endsWith(\".tiff\")) return \"image/tiff\";\n if (p.endsWith(\".svg\") || p.endsWith(\".svgz\")) return \"image/svg+xml\";\n return undefined;\n}\n\n/** A random uint64-safe numeric nonce (the wire `PingRequest.nonce` is a uint64,\n * represented as a numeric string by ts-proto). */\n/** The machine itself stopped answering (offline, reconnecting past the hold\n * window, or draining), as opposed to an answer that the operation failed. */\nfunction machineStoppedAnswering(error: SelfhostedControlError): boolean {\n const faultClass = selfhostedFaultClass(error);\n return faultClass === \"offline\" || faultClass === \"reconnecting\" || faultClass === \"draining\";\n}\n\nfunction randomNonce(): string {\n // 2^53-safe random integer as a decimal string.\n return String(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER));\n}\n\nfunction kindToProtocol(kind: StreamKind | undefined): string {\n switch (kind) {\n case StreamKind.STREAM_KIND_PTY:\n return \"pty\";\n case StreamKind.STREAM_KIND_DESKTOP:\n return \"vnc\";\n default:\n return \"raw\";\n }\n}\n\n/**\n * The selfhosted NotFound discriminator — THE load-bearing safety property\n *: for selfhosted, `agent-offline` (no responder) is NEVER a\n * provider NotFound. A user's real machine is not recreatable; if the lease saw\n * agent-offline as NotFound it would cold-create a RIVAL box (a Modal box) for\n * the user's machine. So this ALWAYS returns FALSE for selfhosted — there is no\n * \"box gone, recreate it\" condition. An OS-level file NotFound is an op-level\n * error the fs layer 404s; it is likewise NOT a session-recreate condition.\n *\n * `establishSandboxSessionFromEnvelope` cold-restores ONLY when the per-backend\n * NotFound discriminator returns true; returning false here guarantees the\n * selfhosted path never cold-creates a rival — the op surfaces agent_offline and\n * the caller backs off / retries.\n */\nexport function isSelfhostedProviderNotFoundError(_error: unknown): false {\n return false;\n}\n","import { blake3 } from \"@noble/hashes/blake3\";\nimport { bytesToHex } from \"@noble/hashes/utils\";\nimport { ControlRequest, ControlResponse, OpState } from \"@opengeni/agent-proto\";\nimport { agentErrorToControlError } from \"./control-rpc\";\n\n// Below the protocol's 512 KiB chunk maximum, leaving control-envelope headroom.\nexport const SELFHOSTED_FILE_CHUNK_BYTES = 256 * 1024;\n\nexport function fileContentDigest(content: Uint8Array): string {\n return bytesToHex(blake3(content));\n}\n\nexport class FileTransferOutcomeError extends Error {\n readonly retryable = false;\n constructor(\n readonly operationId: string,\n readonly phase: \"begin\" | \"upload\" | \"verify\",\n cause: unknown,\n readonly observationError?: unknown,\n ) {\n const detail = cause instanceof Error ? cause.message : \"unknown failure\";\n const observation =\n observationError instanceof Error ? ` Outcome check: ${observationError.message}` : \"\";\n super(\n `File transfer ${operationId} ${phase} failed: ${detail}.${observation} No mutation was replayed; inspect the destination before another edit.`,\n { cause },\n );\n this.name = \"FileTransferOutcomeError\";\n }\n}\n\n/** The caller must reauthorize every request and keep the exact physical route.\n * No mutation is automatically replayed, including after an ambiguous reply. */\nexport async function transferEditorFile(input: {\n path: string;\n content: Uint8Array;\n baseContent?: Uint8Array;\n createParents?: boolean;\n request: (requestId: string, op: NonNullable<ControlRequest[\"op\"]>) => Promise<ControlResponse>;\n}): Promise<{ recovered: boolean }> {\n const opId = `fsw-${crypto.randomUUID()}`;\n const digest = fileContentDigest(input.content);\n const checked = (reply: ControlResponse) => {\n if (reply.error) throw agentErrorToControlError(reply.error, reply.requestId);\n if (!reply.result) throw new Error(\"The machine omitted the file-transfer result.\");\n return reply.result;\n };\n const send = async (requestId: string, op: NonNullable<ControlRequest[\"op\"]>) => {\n const reply = await input.request(requestId, op);\n if (reply.requestId !== requestId)\n throw new Error(\"The machine returned a mismatched file-transfer response identity.\");\n return checked(reply);\n };\n const isVerified = (observed: NonNullable<ControlResponse[\"result\"]>): boolean =>\n !(\n observed.$case !== \"opStatus\" ||\n observed.opStatus.opId !== opId ||\n observed.opStatus.state !== OpState.OP_STATE_COMPLETE ||\n observed.opStatus.exit?.exitCode !== 0 ||\n observed.opStatus.exit.cancelled ||\n observed.opStatus.exit.timedOut ||\n observed.opStatus.exit.failureCode ||\n observed.opStatus.exit.digests.content !== digest ||\n observed.opStatus.exit.totals.content !== String(input.content.byteLength)\n );\n const verifyOutcome = async (cancelRunning = false): Promise<void> => {\n const observed = await send(crypto.randomUUID(), { $case: \"opQuery\", opQuery: { opId } });\n if (isVerified(observed)) return;\n if (\n cancelRunning &&\n observed.$case === \"opStatus\" &&\n observed.opStatus.opId === opId &&\n observed.opStatus.state === OpState.OP_STATE_RUNNING\n ) {\n // This explicit transfer is being abandoned. Cancel only its known live\n // identity through the same reauthorized callback; never sweep or expire\n // other work. A commit racing cancellation must retain its real receipt.\n const cancelled = await send(crypto.randomUUID(), { $case: \"opCancel\", opCancel: { opId } });\n if (isVerified(cancelled)) return;\n if (\n cancelled.$case === \"opStatus\" &&\n cancelled.opStatus.opId === opId &&\n cancelled.opStatus.state === OpState.OP_STATE_COMPLETE &&\n cancelled.opStatus.exit?.cancelled\n ) {\n throw new Error(\"Cancellation of the abandoned transfer's private staging was verified.\");\n }\n }\n throw new Error(\n \"The file-transfer outcome is not verified; the operation was not replayed. Inspect the destination before another edit.\",\n );\n };\n let phase: \"begin\" | \"upload\" | \"verify\" = \"begin\";\n try {\n const begun = await send(opId, {\n $case: \"opStart\",\n opStart: {\n op: {\n $case: \"fsWrite\",\n fsWrite: {\n path: input.path,\n createParents: input.createParents ?? true,\n mode: 0,\n expectedBaseDigest:\n input.baseContent === undefined ? \"\" : fileContentDigest(input.baseContent),\n expectedAbsent: input.baseContent === undefined,\n contentDigest: digest,\n contentSize: String(input.content.byteLength),\n },\n },\n windowBytes: \"0\",\n deadlineMs: \"0\",\n originId: \"\",\n },\n });\n if (\n begun.$case !== \"opStart\" ||\n !begun.opStart.accepted ||\n begun.opStart.status?.opId !== opId\n ) {\n throw new Error(\"The machine did not accept the exact file-transfer operation.\");\n }\n\n phase = \"upload\";\n let offset = 0;\n let seq = 0;\n do {\n const end = Math.min(input.content.byteLength, offset + SELFHOSTED_FILE_CHUNK_BYTES);\n const reply = await send(crypto.randomUUID(), {\n $case: \"writeChunk\",\n writeChunk: {\n opId,\n seq: String(seq),\n offset: String(offset),\n bytes: input.content.subarray(offset, end),\n last: end === input.content.byteLength,\n },\n });\n if (reply.$case !== \"writeChunk\" || reply.writeChunk.seq !== String(seq)) {\n throw new Error(\n \"The machine returned a mismatched file-transfer acknowledgment; no chunk was replayed.\",\n );\n }\n offset = end;\n seq += 1;\n } while (offset < input.content.byteLength);\n phase = \"verify\";\n await verifyOutcome();\n } catch (error) {\n if (phase === \"verify\") throw new FileTransferOutcomeError(opId, phase, error);\n // An acknowledgment can be lost after commit. Observe this exact operation\n // once under current authority; never restart it or resend a chunk.\n try {\n await verifyOutcome(true);\n return { recovered: true };\n } catch (observationError) {\n throw new FileTransferOutcomeError(opId, phase, error, observationError);\n }\n }\n return { recovered: false };\n}\n","/** One request to an agent-owned browser/computer controller, addressed by its\n * exact authority scope rather than a local port. */\nexport type BrowserControlHttpCall = {\n scopeId: string;\n scopeGeneration: string;\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n /** Absolute controller path with optional query. */\n path: string;\n bearerToken: string;\n /** JSON request body bytes, when the request has a body. */\n body?: Uint8Array;\n timeoutMs: number;\n maxResponseBytes: number;\n};\n\n/** What a placement transport did with one controller request. */\nexport type BrowserControlHttpOutcome =\n /** The placement cannot serve it natively; nothing was sent. */\n | { kind: \"unsupported\" }\n /** No controller for that scope and generation accepted it; nothing was\n * delivered, so the caller may ensure the controller and send again. */\n | { kind: \"controller_absent\" }\n | {\n kind: \"response\";\n status: number;\n /** Lowercase header names. */\n headers: Map<string, string>;\n body: Uint8Array;\n };\n\n/** Extra time beyond the request's own deadline for the reply to arrive. */\nexport const BROWSER_CONTROL_HTTP_REPLY_GRACE_MS = 5_000;\n","// The selfhosted control-op RETRY POLICY — a small, PURE decision function the\n// `SelfhostedSession.call()` loop consults after each control-plane reply.\n//\n// Before this, a typed AgentError surfaced straight to the model as a failed tool\n// call: a `DRAINING` backpressure rejection (the machine was momentarily at its\n// concurrent-work capacity) and a transient `TIMEOUT` / `agent_reconnecting` blip\n// both looked like hard failures even though the op never ran (DRAINING) or was a\n// pure read that is safe to re-issue (a read that timed out). This policy retries\n// exactly those two, with a hard safety line around anything that MUTATES state.\n//\n// It is intentionally a pure function (op kind + error + prior-retry counts +\n// injected jitter → a decision) so the whole retry matrix is unit-testable with no\n// clock, no transport, and no session. The sleep + jitter side effects live behind\n// the injected `SelfhostedRetryClock` so tests are deterministic.\n\nimport type { SelfhostedControlError } from \"./control-rpc\";\n\n/**\n * The read-only, idempotent-safe control ops that MAY be retried after a TIMEOUT\n * / `agent_reconnecting` blip.\n *\n * A timed-out request is AT-LEAST-ONCE on the wire: the agent may have RECEIVED\n * and fully EXECUTED the op before its reply was lost, so re-issuing it is only\n * safe when a second execution is observably identical to one — i.e. a pure read.\n * Every MUTATING op (`exec`, `git`, `fsWrite`/`fsMove`/`fsMkdir`/`fsRemove`, and\n * the pty/desktop input ops) is DELIBERATELY EXCLUDED: re-running a mutation that\n * already ran on the machine is a real correctness hazard (a duplicated write, a\n * second `git push`, a re-applied command). Only DRAINING (a pre-admission\n * rejection — see `decideSelfhostedRetry`) is safe to retry for those.\n */\nexport const SELFHOSTED_IDEMPOTENT_READONLY_OPS: ReadonlySet<string> = new Set([\n \"ping\",\n \"metrics\",\n \"fsStat\",\n \"fsList\",\n \"fsRead\",\n]);\n\n/**\n * DRAINING is a pre-admission backpressure rejection (the op never started), so it\n * is safe to retry for ANY op kind. The budget is split by op class:\n *\n * - NON-EXEC control ops (fs/git/desktop/pty) keep a SHORT budget — 3 retries,\n * worst-case backoff 500+1000+2000 = 3.5s (≤5s). Their start latency matters\n * (fs/git ops gate the model's next step), so a saturated machine should surface\n * quickly rather than stall.\n * - EXEC gets a LONG, patient budget — 10 retries, worst-case ≈55.5s (<60s). exec\n * start is not latency-critical, and the agent-side admission pool is (until a\n * later agent release) a FLAT 8 permits with no per-class split: a burst of slow\n * execs can hold every permit and blanket-DRAIN all fs/git ops. A patient exec\n * retry converts those DRAINING storms into mild queueing instead of a wall of\n * failed tool calls, and pairs with the deliberately modest exec deadline (which,\n * for the same 8-permit reason, defaults to 2min, not 5).\n */\nexport const SELFHOSTED_DRAINING_MAX_RETRIES = 3;\nexport const SELFHOSTED_EXEC_DRAINING_MAX_RETRIES = 10;\n/** A read-only op that timed out is retried at most once (see the at-least-once\n * note above — even a read gets a single re-issue, not an unbounded loop). */\nexport const SELFHOSTED_TIMEOUT_MAX_RETRIES = 1;\n/** A fault the transport synthesized PRE-SEND (no connection / no responder) — the\n * op provably never reached the machine, so it is safe to re-issue for ANY op kind.\n * Short bounded budget (≈3.5s summed): enough to ride out a NATS reconnect blip\n * quietly, not so long it stalls the model on a machine that is genuinely down. */\nexport const SELFHOSTED_NEVER_SENT_MAX_RETRIES = 3;\n\n/** Full-jitter backoff base (ms). Delay N is sampled in `[0, base * factor^N)`. */\nexport const SELFHOSTED_RETRY_BACKOFF_BASE_MS = 500;\nexport const SELFHOSTED_RETRY_BACKOFF_FACTOR = 2;\n/** Per-delay ceiling: 500 → 1s → 2s → 4s → 8s, then flat at 8s. Bounds the summed\n * backoff — non-exec (3 retries) ≈3.5s ≤5s; exec (10 retries) ≈55.5s <60s. */\nexport const SELFHOSTED_RETRY_BACKOFF_CAP_MS = 8_000;\n\nexport type SelfhostedRetryDecision =\n | { readonly action: \"fail\" }\n | { readonly action: \"retry\"; readonly delayMs: number };\n\n/**\n * Full-jitter exponential backoff. Returns a delay in\n * `[0, min(cap, base * factor^attempt))`. `jitter` is an injected sample in\n * `[0, 1)` so the delay is fully deterministic under test.\n */\nexport function selfhostedRetryBackoffMs(attempt: number, jitter: number): number {\n const uncapped = SELFHOSTED_RETRY_BACKOFF_BASE_MS * SELFHOSTED_RETRY_BACKOFF_FACTOR ** attempt;\n const ceiling = Math.min(SELFHOSTED_RETRY_BACKOFF_CAP_MS, uncapped);\n const clampedJitter = Math.min(0.999_999, Math.max(0, jitter));\n return Math.floor(clampedJitter * ceiling);\n}\n\n/**\n * PURE retry policy for one selfhosted control-op reply.\n *\n * - `error.draining` (DRAINING — pre-admission host-work backpressure; the op was\n * rejected at the pool gate and NEVER started) → retry for ANY op kind, since\n * nothing executed. exec gets the long `SELFHOSTED_EXEC_DRAINING_MAX_RETRIES`\n * budget (≈60s of patient queueing under the flat 8-permit pool); every other op\n * keeps the short `SELFHOSTED_DRAINING_MAX_RETRIES` budget (≤5s).\n * - `error.neverSent` (a pre-send AGENT_OFFLINE synthesis — no connection / no\n * responder; the op provably never reached the machine) → retry for ANY op kind\n * up to `SELFHOSTED_NEVER_SENT_MAX_RETRIES`. At-least-once does NOT apply (nothing\n * executed), so even a mutation is safe to re-issue; this heals a NATS reconnect\n * blip quietly. A truly-offline machine surfaces honestly after the short budget.\n * - `error.reason === \"agent_reconnecting\"` (a TIMEOUT / transient blip AFTER send)\n * → retry at most `SELFHOSTED_TIMEOUT_MAX_RETRIES`, and ONLY for a read-only\n * idempotent-safe op (`SELFHOSTED_IDEMPOTENT_READONLY_OPS`). A timed-out\n * MUTATION is never retried here — it may already have run (at-least-once).\n * - Everything else → no retry at this layer:\n * · FENCED is retried by the routing proxy against a RE-RESOLVED backend\n * (retrying here under the same stale epoch would just re-fence);\n * · AGENT_OFFLINE / OS / PROTOCOL / PAYLOAD_TOO_LARGE / CONSENT_REQUIRED are\n * not transient and must surface to the caller.\n *\n * The draining and timeout budgets are SEPARATE counters so a read that first hit\n * backpressure still keeps its single timeout re-issue (and vice versa); both are\n * bounded, so the total number of attempts — and the summed backoff — is bounded.\n */\nexport function decideSelfhostedRetry(input: {\n opKind: string;\n error: SelfhostedControlError;\n drainingRetries: number;\n timeoutRetries: number;\n /** Prior never-sent retries. Optional (default 0) — only the pre-send AGENT_OFFLINE\n * branch reads it, so callers that cannot hit that class may omit it. */\n neverSentRetries?: number;\n jitter: number;\n}): SelfhostedRetryDecision {\n const { opKind, error, drainingRetries, timeoutRetries, neverSentRetries = 0, jitter } = input;\n\n if (error.neverSent) {\n // Provably not executed (the request never reached the machine) → safe to\n // re-issue for ANY op kind. Bounded so a genuinely-offline machine surfaces\n // honestly rather than hanging the turn.\n if (neverSentRetries >= SELFHOSTED_NEVER_SENT_MAX_RETRIES) {\n return { action: \"fail\" };\n }\n return { action: \"retry\", delayMs: selfhostedRetryBackoffMs(neverSentRetries, jitter) };\n }\n\n if (error.draining) {\n // exec is patient (the flat 8-permit pool needs longer than 5s to free a slot);\n // every other op keeps the short budget so fs/git latency stays snappy.\n const maxDrainingRetries =\n opKind === \"exec\" ? SELFHOSTED_EXEC_DRAINING_MAX_RETRIES : SELFHOSTED_DRAINING_MAX_RETRIES;\n if (drainingRetries >= maxDrainingRetries) {\n return { action: \"fail\" };\n }\n return { action: \"retry\", delayMs: selfhostedRetryBackoffMs(drainingRetries, jitter) };\n }\n\n if (error.reason === \"agent_reconnecting\") {\n if (!SELFHOSTED_IDEMPOTENT_READONLY_OPS.has(opKind)) {\n // A timed-out mutation may already have executed on the machine — never\n // re-issue it (at-least-once). Surface the reconnecting error instead.\n return { action: \"fail\" };\n }\n if (timeoutRetries >= SELFHOSTED_TIMEOUT_MAX_RETRIES) {\n return { action: \"fail\" };\n }\n return { action: \"retry\", delayMs: selfhostedRetryBackoffMs(timeoutRetries, jitter) };\n }\n\n return { action: \"fail\" };\n}\n\n/**\n * The injected clock the retry loop drives — real in production, a deterministic\n * fake in tests. `jitter()` returns a full-jitter sample in `[0, 1)`.\n */\nexport interface SelfhostedRetryClock {\n sleep(ms: number): Promise<void>;\n jitter(): number;\n}\n\n/** The production clock: a real timer + `Math.random()` jitter. */\nexport const defaultSelfhostedRetryClock: SelfhostedRetryClock = {\n sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n jitter: () => Math.random(),\n};\n","// The op-stream EXEC client (op-stream protocol v1.1, server half; PROTOCOL.md\n// + ENGINE-INTEGRATION.md step 6 in .agent/).\n//\n// Replaces monolithic exec request/reply with sequenced, acked,\n// credit-flowed frames when the runner advertises `Capabilities.op_stream` AND\n// the server flag is on. What it buys, in order of importance:\n//\n// * ATTACH-NOT-RERUN (B1/B2): the op id is durable (`{tool_call_id}:{ordinal}`)\n// and OpStart is idempotent by it — a re-dispatched turn that re-executes the\n// same function_call COLLECTS the already-running/completed op instead of\n// re-running the command. The at-least-once re-run hazard dies here.\n// * No reply-size wall: output streams in ≤128 KiB frames; the runner retains\n// ring→spool for replay, and a too-big stream fails TYPED (OP_OVERFLOW with\n// exact counters), never silently truncated.\n// * Blip tolerance: a connection loss detaches, never kills; frames resume via\n// OpAttach replay (gap-triggered attach is a ROUTINE heal, incl. seq-0 loss).\n//\n// ACK POLICY (design delta Δ2, DESIGN-OPSTREAM-CLIENT.md): mid-op acks are\n// CREDIT-ONLY — `OpAck{acked_seq: 0, credit_bytes: received_total + window}`.\n// The runner FREES retained frames at acked_seq, and a re-dispatched consumer\n// must reassemble from seq 0 (its predecessor's buffered bytes died with it),\n// so no mid-op acked_seq > 0 is ever durably backed. Credit is an ABSOLUTE\n// window replacement on the wire, so growing it keeps the child flowing while\n// the runner retains everything (bounded by its ring+spool quotas — the honest\n// output ceiling, typed when hit). The acked frontier advances exactly once,\n// at the FINAL ack, after the consumed result is durable (the hard gate's\n// ordering: result durable → journal persist → wire final ack — see\n// `finalizeSettledOps`).\n//\n// Everything above the transport is unchanged: the caller builds the same\n// `ExecRequest`, receives the same `ExecResponse` shape, and every failure is a\n// `SelfhostedControlError` in the existing taxonomy so the fault renderer and\n// the op observer behave identically across the transport swap.\n\nimport { blake3 } from \"@noble/hashes/blake3\";\nimport { bytesToHex } from \"@noble/hashes/utils\";\nimport { currentOpToolCallId } from \"../op-correlation\";\nimport {\n ControlRequest,\n ErrorCode,\n OpAck,\n OpChannel,\n OpFrame,\n OpLostReason,\n OpState,\n type ExecRequest,\n type ExecResponse,\n type OperationResourcePolicy,\n type OpExit,\n type OpStatus,\n} from \"@opengeni/agent-proto\";\nimport {\n agentErrorToControlError,\n SelfhostedControlError,\n timeoutAgentError,\n type ControlRpc,\n} from \"./control-rpc\";\nimport { selfhostedRetryBackoffMs, type SelfhostedRetryClock } from \"./retry-policy\";\nimport {\n opAckSubject,\n opFrameSubject,\n OpStreamUnavailableError,\n type OpStreamSubscription,\n type OpStreamTransport,\n} from \"./op-transport\";\n\n/** Initial send-credit window (bytes) when the caller does not size it. Matches\n * the wire default OpStart advertises (~4 MiB). */\nexport const OP_STREAM_DEFAULT_WINDOW_BYTES = 4 * 1024 * 1024;\n/** Cumulative-ack repetition cadence while an op is live (ruling M1: acks are\n * best-effort and healed by repetition). */\nexport const OP_STREAM_ACK_INTERVAL_MS = 5_000;\n/** Frame-silence threshold before the client starts probing with OpQuery. The\n * runner emits Progress every 5s while an op is alive and quiet, so 30s of\n * TOTAL silence means frames are not reaching us (or the op is gone). */\nexport const OP_STREAM_SILENCE_TIMEOUT_MS = 30_000;\n/** How long a silent op is held open across a machine reconnect window before\n * the client fails it typed (PROTOCOL liveness rule: hold ≤120s, then only a\n * definitive answer fails the op). */\nexport const OP_STREAM_RECONNECT_HOLD_MS = 120_000;\n/** A detached background consumer grants the runner the complete uint64 credit\n * range. Retention remains bounded by the runner's ring/spool quotas, so a noisy\n * command reaches the existing typed OP_OVERFLOW terminal instead of stalling\n * forever merely because the turn that launched it finished. */\nconst OP_STREAM_BACKGROUND_CREDIT_BYTES = \"18446744073709551615\";\n/** The out-of-order stash is a disposable replay optimization, never retained\n * command output. Bound it in bytes to two live-flow windows per op: a gap that\n * outgrows that cache drops the cache and heals from the runner's authoritative\n * retention log. This scales with the negotiated stream window and cannot turn\n * 100 concurrent quiet gaps into a multi-gigabyte frame-count allocation. */\nconst OP_STREAM_STASH_WINDOW_MULTIPLIER = 2;\n/** OpStart DRAINING retry budget (retry-policy.ts): op start is not\n * latency-critical and a saturated machine should queue, not fail. OpStart\n * is idempotent by op id, so pre-dispatch timeout blips are also safe to\n * re-issue with the same small bounded budget. */\nconst OP_START_DRAINING_MAX_RETRIES = 10;\nconst OP_START_BLIP_MAX_RETRIES = 3;\n\n/**\n * The durable-resume journal the worker adapts onto Temporal (design delta Δ1:\n * the attach generation is `Info.currentAttemptScheduledTimestampMs` — strictly\n * monotonic across worker-death redispatches, which `Info.attempt` is NOT under\n * `maximumAttempts: 1`). `persistSettled` folds the op's settled frontier into\n * the activity heartbeat details and MUST complete before the wire final ack\n * (the durable-before-wire-ack gate); the default no-journal client (tests,\n * non-activity callers) uses generation \"1\" and skips persistence.\n */\nexport interface OpStreamJournal {\n /** The consumer's attach generation (u64 decimal string). */\n attachGeneration(): string;\n /** Durably record `opId` as settled at `exitSeq` BEFORE its final ack. */\n persistSettled(opId: string, exitSeq: string): void | Promise<void>;\n}\n\nexport interface OpStreamExecClientDeps {\n workspaceId: string;\n agentId: string;\n /** Exact live daemon instance pinned at operation admission. */\n connectionInstanceId: string;\n /** The lease/active epoch every ControlRequest is fenced under. */\n epoch: number;\n /** The rpc request/reply seam (OpStart/OpQuery/OpAttach ride here). */\n controlRpc: ControlRpc;\n /** The exact claimed process RPC subject. */\n rpcSubject: string;\n /** The frame/ack seam (subscribe + publish). */\n transport: OpStreamTransport;\n journal?: OpStreamJournal;\n windowBytes?: number;\n /** Control-op round-trip timeout for OpStart/OpQuery/OpAttach (the SHORT\n * control budget, not the exec deadline). */\n controlTimeoutMs: number;\n /** The retry clock (sleep + jitter), injected for deterministic tests. */\n retryClock: SelfhostedRetryClock;\n ackIntervalMs?: number;\n silenceTimeoutMs?: number;\n reconnectHoldMs?: number;\n /** Per-connection policy snapshot attached only to OpStart. Lifecycle controls\n * identify an already-admitted operation and must not imply a policy change. */\n resourcePolicy?: OperationResourcePolicy;\n /** Revalidate the exact live route/authority immediately before every\n * physical OpStart dispatch. An already-accepted or outcome-ambiguous\n * operation never calls this hook again. */\n revalidateBeforeStartRetry?: () => void | Promise<void>;\n}\n\n/** A completed op-stream exec: the SDK-facing response plus the healing\n * telemetry the session folds into its op observation. */\nexport interface OpStreamExecOutcome {\n response: ExecResponse;\n /** Runner transport failure is independent of the process exit code. */\n failure?: Pick<OpExit, \"failureCode\" | \"failureDetail\">;\n /** Attach/query heals that occurred after streaming began (gap replays,\n * silence probes that re-attached). >0 marks the op `healed`. */\n heals: number;\n /** OpStart-level retries (draining/blip) before the op was accepted. */\n startRetries: number;\n /** Total reassembled Data payload bytes (the observer's replyBytes). */\n replyBytes: number;\n}\n\nexport type OpStreamExecResult =\n | { status: \"completed\"; outcome: OpStreamExecOutcome }\n | {\n status: \"running\";\n opId: string;\n stdout: Uint8Array;\n stderr: Uint8Array;\n heals: number;\n startRetries: number;\n replyBytes: number;\n /** Terminal proof may race durable adoption. The caller must settle the\n * adopted command but still return only its background receipt. */\n terminal?: {\n outcome: OpStreamExecOutcome;\n exitSeq: string;\n outputReceipt?: OpStreamOutputReceipt;\n };\n };\n\n/** Produced only after contiguous replay, byte verification and awaited capture.\n * The caller must persist this under its exact command before releasing output. */\nexport type OpStreamOutputReceipt = { exitSeq: string; attachGeneration: string };\n\nexport type OpStreamYieldOptions = {\n yieldMs: number;\n /** Durable ownership transfer. It runs while the exact consumer is still\n * attached; returning a running result is forbidden until this resolves. */\n onYield: () => void | Promise<void>;\n captureOutput?: (frames: OpStreamOutputFrame[]) => Promise<void>;\n};\n\nexport type OpStreamOutputFrame = { sequence: string; stream: \"stdout\" | \"stderr\"; chunk: string };\n\nexport type ExactSelfhostedOpControlInput = {\n controlRpc: ControlRpc;\n rpcSubject: string;\n opId: string;\n controlTimeoutMs: number;\n};\n\nasync function exactSelfhostedOpControl(\n input: ExactSelfhostedOpControlInput,\n operation: \"query\" | \"cancel\",\n): Promise<OpStatus> {\n const requestId = crypto.randomUUID();\n const response = await input.controlRpc.request(\n input.rpcSubject,\n {\n requestId,\n // Exact lifecycle control is pinned by subject + op id. It deliberately\n // bypasses the mutable session-route epoch so a later machine swap cannot\n // fence observation/cancellation of an already-adopted command.\n epoch: 0,\n resourcePolicy: undefined,\n op:\n operation === \"query\"\n ? { $case: \"opQuery\", opQuery: { opId: input.opId } }\n : { $case: \"opCancel\", opCancel: { opId: input.opId } },\n },\n { timeoutMs: input.controlTimeoutMs },\n );\n if (response.error || !response.result) {\n throw agentErrorToControlError(\n response.error ?? {\n code: ErrorCode.ERROR_CODE_PROTOCOL,\n message: `op-stream ${operation} returned an empty result`,\n retryable: false,\n detail: {},\n },\n requestId,\n );\n }\n if (response.result.$case !== \"opStatus\") {\n throw protocolError(`op-stream ${operation}: unexpected result ${response.result.$case}`);\n }\n if (response.result.opStatus.opId !== input.opId) {\n throw protocolError(`op-stream ${operation}: status identity mismatch for ${input.opId}`);\n }\n return response.result.opStatus;\n}\n\n/** Query one durably adopted operation at its immutable physical locator. */\nexport async function querySelfhostedOp(input: ExactSelfhostedOpControlInput): Promise<OpStatus> {\n return await exactSelfhostedOpControl(input, \"query\");\n}\n\n/** Cancel one durably adopted operation at its immutable physical locator. */\nexport async function cancelSelfhostedOp(input: ExactSelfhostedOpControlInput): Promise<OpStatus> {\n return await exactSelfhostedOpControl(input, \"cancel\");\n}\n\n/** One op settled but not yet final-acked (awaiting its result's durable point). */\ninterface SettledOp {\n opId: string;\n exitSeq: string;\n generation: string;\n toolCallId: string | null;\n}\n\nconst OP_CHANNEL_NAMES: Partial<Record<OpChannel, \"stdout\" | \"stderr\">> = {\n [OpChannel.OP_CHANNEL_STDOUT]: \"stdout\",\n [OpChannel.OP_CHANNEL_STDERR]: \"stderr\",\n};\n\n/**\n * The per-session op-stream exec client. One instance per `SelfhostedSession`;\n * `exec()` runs one op end-to-end; `finalizeSettledOps()` is the durability hook\n * that advances the acked frontier durably (journal) and then on the wire.\n */\nexport class OpStreamExecClient {\n private readonly deps: OpStreamExecClientDeps;\n private readonly settled: SettledOp[] = [];\n private readonly inFlight = new Set<string>();\n private readonly readCheckpoints = new Map<string, OpReadCheckpoint>();\n private finalization: Promise<void> = Promise.resolve();\n private lastReadGeneration = 0n;\n\n constructor(deps: OpStreamExecClientDeps) {\n this.deps = deps;\n }\n\n private generation(): string {\n return this.deps.journal?.attachGeneration() ?? \"1\";\n }\n\n /** Adopted-command reads are new consumers, not recovery of the launching\n * activity. Use the same epoch-millisecond generation domain as reconciliation\n * so a later owning-runtime read can follow a reaper attach. Execution and\n * its recovery continue to use the immutable journal generation. Equal\n * generations are accepted by the runner; never decrease within this client. */\n private readGeneration(): string {\n const journal = BigInt(this.generation());\n const now = BigInt(Date.now());\n this.lastReadGeneration = [this.lastReadGeneration, journal, now].reduce(\n (highest, generation) => (generation > highest ? generation : highest),\n 1n,\n );\n return this.lastReadGeneration.toString();\n }\n\n /**\n * Cancel an exec by its durable op id. OpCancel is idempotent and also acts\n * as a cancel-before-start tombstone, so calling this while OpStart is still\n * racing is safe: the runner either kills the accepted process tree or\n * refuses the later start without spawning it.\n */\n async cancel(opId: string): Promise<void> {\n const response = await this.deps.controlRpc.request(\n this.deps.rpcSubject,\n {\n requestId: crypto.randomUUID(),\n epoch: this.deps.epoch,\n resourcePolicy: undefined,\n op: { $case: \"opCancel\", opCancel: { opId } },\n },\n { timeoutMs: this.deps.controlTimeoutMs },\n );\n if (response.error || !response.result) {\n throw agentErrorToControlError(\n response.error ?? {\n code: ErrorCode.ERROR_CODE_PROTOCOL,\n message: \"op-stream cancel returned an empty result\",\n retryable: false,\n detail: {},\n },\n );\n }\n if (response.result.$case !== \"opStatus\") {\n throw protocolError(`op-stream cancel: unexpected result ${response.result.$case}`);\n }\n }\n\n /**\n * Run one exec over the op stream. `opId` is the durable id (B1) — a re-issue\n * with the same id attaches instead of re-running. `deadlineMs` is the exec\n * process budget (relative); the runner's enforcement is authoritative.\n * `wallMs` is the client-side give-up wall (deadline + reply grace); 0 means\n * no duration wall. Liveness probing and explicit cancellation still apply.\n */\n async exec(\n opId: string,\n exec: ExecRequest,\n deadlineMs: number,\n wallMs: number,\n ): Promise<OpStreamExecOutcome> {\n const result = await this.execWithYield(opId, exec, deadlineMs, wallMs, null);\n if (result.status !== \"completed\") {\n throw protocolError(\"op-stream terminal exec unexpectedly yielded\");\n }\n return result.outcome;\n }\n\n /** Run an exec that may transfer to durable session ownership after one\n * bounded model-facing wait. Adoption is inside the live consumer boundary:\n * a failure cancels the exact op and waits for terminal proof before throwing,\n * so an outcome-unknown command is never forgotten or replayed. */\n async execWithYield(\n opId: string,\n exec: ExecRequest,\n deadlineMs: number,\n wallMs: number,\n yieldOptions: OpStreamYieldOptions | null,\n ): Promise<OpStreamExecResult> {\n if (this.inFlight.has(opId)) {\n throw new SelfhostedControlError({\n message: `op-stream exec: duplicate concurrent op id ${opId}`,\n code: ErrorCode.ERROR_CODE_PROTOCOL,\n reason: null,\n retryable: false,\n });\n }\n this.inFlight.add(opId);\n const toolCallId = currentOpToolCallId();\n try {\n const consumer = new OpConsumer(this.deps, opId, this.generation());\n try {\n const result = await consumer.run(exec, deadlineMs, wallMs, yieldOptions);\n if (result.status === \"completed\") {\n this.settled.push({\n opId,\n exitSeq: result.exitSeq,\n generation: consumer.generation,\n toolCallId,\n });\n return { status: \"completed\", outcome: result.outcome };\n }\n return result;\n } finally {\n consumer.teardown();\n }\n } finally {\n this.inFlight.delete(opId);\n }\n }\n\n /** Observe an already-adopted operation. Never issues OpStart, cancellation,\n * final ACK, or terminal model-observation acknowledgment. Output is delivered\n * through captureOutput, not accumulated in response stdout/stderr. Successful\n * running reads reuse local integrity state; a new client replays from zero. */\n async readExisting(\n opId: string,\n yieldMs: number,\n captureOutput: (frames: OpStreamOutputFrame[]) => Promise<void>,\n ): Promise<\n OpStreamExecResult & { replaySequence: string; outputReceipt?: OpStreamOutputReceipt }\n > {\n if (this.inFlight.has(opId)) throw protocolError(\"op-stream read: duplicate concurrent op id\");\n const consumer = new OpConsumer(\n this.deps,\n opId,\n this.readGeneration(),\n this.readCheckpoints.get(opId),\n );\n this.inFlight.add(opId);\n this.readCheckpoints.delete(opId);\n try {\n const result = await consumer.run(\n null,\n 0,\n Math.max(yieldMs + this.deps.controlTimeoutMs, 1000),\n {\n yieldMs: Math.max(1, yieldMs),\n onYield: () => {},\n captureOutput,\n },\n );\n // Only a successful capture may advance this local replay optimization.\n // A fresh client or failed persistence always replays retained truth.\n consumer.teardown();\n if (result.status === \"running\" && !result.terminal) {\n this.readCheckpoints.set(opId, consumer.readCheckpoint());\n }\n // Progress/partial UTF-8 frames can advance verified replay without\n // producing a decoded output chunk. Expose the contiguous protocol\n // frontier only after capture succeeds, never the provider high watermark.\n const replaySequence = consumer.readCheckpoint().lastApplied.toString();\n return result.status === \"completed\"\n ? {\n status: \"completed\",\n outcome: result.outcome,\n replaySequence,\n outputReceipt: { exitSeq: result.exitSeq, attachGeneration: consumer.generation },\n }\n : { ...result, replaySequence };\n } finally {\n consumer.teardown();\n this.inFlight.delete(opId);\n }\n }\n\n /** Release only an independently persisted, fully captured background exit.\n * Re-attach under a fresh generation before ACK so an intervening reader cannot\n * strand a stale ACK. Never starts, cancels, replays output or observes a model\n * result. A publish is not native delivery proof: retry until an exact control\n * observation establishes that the operation is no longer retained. */\n async releaseCapturedOutput(\n opId: string,\n receipt: OpStreamOutputReceipt,\n ): Promise<\"published\" | \"not_retained\"> {\n const u64 = (value: string): bigint => {\n if (!/^[1-9][0-9]{0,19}$/.test(value) || BigInt(value) > 18446744073709551615n)\n throw protocolError(\"op-stream output release: invalid retained frontier\");\n return BigInt(value);\n };\n const exitSeq = u64(receipt.exitSeq);\n const previousGeneration = u64(receipt.attachGeneration);\n const currentGeneration = u64(this.readGeneration());\n const generation = (\n currentGeneration > previousGeneration ? currentGeneration : previousGeneration + 1n\n ).toString();\n u64(generation);\n const requestId = crypto.randomUUID();\n const response = await this.deps.controlRpc.request(\n this.deps.rpcSubject,\n {\n requestId,\n epoch: 0,\n resourcePolicy: undefined,\n op: {\n $case: \"opAttach\",\n opAttach: {\n opId,\n fromSeq: receipt.exitSeq,\n attachGeneration: generation,\n windowBytes: \"1\",\n },\n },\n },\n { timeoutMs: this.deps.controlTimeoutMs },\n );\n if (response.error || !response.result)\n throw agentErrorToControlError(\n response.error ?? {\n code: ErrorCode.ERROR_CODE_PROTOCOL,\n message: \"op-stream output release returned an empty result\",\n retryable: false,\n detail: {},\n },\n );\n if (response.result.$case !== \"opStatus\" || response.result.opStatus.opId !== opId)\n throw protocolError(\"op-stream output release: status identity mismatch\");\n const status = response.result.opStatus;\n if (status.state === OpState.OP_STATE_LOST) return \"not_retained\";\n if (\n status.state !== OpState.OP_STATE_COMPLETE ||\n !status.exit ||\n !/^[0-9]+$/.test(status.nextSeq) ||\n BigInt(status.nextSeq) !== exitSeq + 1n\n )\n throw protocolError(\"op-stream output release: durable exit frontier disagrees with runner\");\n await this.deps.transport.publish(\n opAckSubject(this.deps.workspaceId, this.deps.agentId, this.deps.connectionInstanceId),\n OpAck.encode({\n opId,\n ackedSeq: receipt.exitSeq,\n creditBytes: \"0\",\n final: true,\n attachGeneration: generation,\n }).finish(),\n );\n return \"published\";\n }\n\n /**\n * The result durability hook (the hard gate's ordering): for every op whose\n * result the caller has durably consumed — (1) already true when this runs —\n * (2) persist the settled frontier to the journal, then (3) publish the wire\n * final ack (`acked_seq = exit_seq, final = true`), which licenses the runner\n * to GC the op. A kill between (2) and (3) is safe: the re-dispatched turn\n * does not re-execute a durably-recorded call, and the runner's retention TTL\n * reaps the never-final-acked op — no loss, bounded residue. A supplied call\n * list selects only those exact result owners; omitted means the complete\n * turn/API boundary. Snapshot before I/O so later completions cannot become\n * eligible accidentally. Failed persistence/publish leaves the op retryable.\n */\n async finalizeSettledOps(toolCallIds?: readonly string[]): Promise<void> {\n const selected = toolCallIds === undefined ? null : new Set(toolCallIds);\n const eligible = this.settled.filter(\n (op) => selected === null || (op.toolCallId !== null && selected.has(op.toolCallId)),\n );\n const finalization = this.finalization.then(() => this.finalizeOps(eligible));\n // Serialize overlapping durability hooks without letting one failed\n // journal poison later attempts to finalize the same retained frontier.\n this.finalization = finalization.catch(() => undefined);\n await finalization;\n }\n\n private async finalizeOps(eligible: readonly SettledOp[]): Promise<void> {\n const ackSubject = opAckSubject(\n this.deps.workspaceId,\n this.deps.agentId,\n this.deps.connectionInstanceId,\n );\n for (const op of eligible) {\n // A preceding queued hook may already have acknowledged this object.\n if (!this.settled.includes(op)) continue;\n await this.deps.journal?.persistSettled(op.opId, op.exitSeq);\n const ack = OpAck.encode({\n opId: op.opId,\n ackedSeq: op.exitSeq,\n creditBytes: \"0\",\n final: true,\n attachGeneration: op.generation,\n }).finish();\n try {\n await this.deps.transport.publish(ackSubject, ack);\n } catch {\n // Retry at a later durability hook; the runner's TTL is the backstop.\n continue;\n }\n this.settled.splice(this.settled.indexOf(op), 1);\n }\n }\n}\n\n/** In-memory only: never licenses runner GC or substitutes for durable output. */\ntype OpReadCheckpoint = {\n lastApplied: bigint;\n hashes: { stdout: ReturnType<typeof blake3.create>; stderr: ReturnType<typeof blake3.create> };\n totals: { stdout: bigint; stderr: bigint };\n decoders: { stdout: TextDecoder; stderr: TextDecoder };\n};\n\n/** Internal per-op consumer: subscription, reassembly, flow, liveness. */\nclass OpConsumer {\n private readonly deps: OpStreamExecClientDeps;\n private readonly opId: string;\n readonly generation: string;\n private readonly windowBytes: number;\n\n /** Highest contiguously APPLIED seq (frames start at 1; 0 = none yet). */\n private lastApplied = 0n;\n private readonly stash = new Map<bigint, { frame: OpFrame; wireBytes: number }>();\n private stashedWireBytes = 0;\n private readonly chunks: { stdout: Uint8Array[]; stderr: Uint8Array[] } = {\n stdout: [],\n stderr: [],\n };\n private readonly outputFrames: OpStreamOutputFrame[] = [];\n private readonly outputDecoders = { stdout: new TextDecoder(), stderr: new TextDecoder() };\n private readonly hashes = { stdout: blake3.create(), stderr: blake3.create() };\n private readonly totals = { stdout: 0n, stderr: 0n };\n private captureOnly = false;\n private receivedPayloadBytes = 0n;\n private creditAtLastAck = 0n;\n private exit: OpExit | undefined;\n private exitSeq: bigint | undefined;\n private heals = 0;\n private lastFrameAt: number;\n private silenceSince: number | undefined;\n private attachInFlight = false;\n private subscription: OpStreamSubscription | undefined;\n private ackTimer: ReturnType<typeof setInterval> | undefined;\n private settleResolve: (() => void) | undefined;\n private settleReject: ((error: unknown) => void) | undefined;\n private torn = false;\n\n constructor(\n deps: OpStreamExecClientDeps,\n opId: string,\n generation: string,\n checkpoint?: OpReadCheckpoint,\n ) {\n this.deps = deps;\n this.opId = opId;\n this.generation = generation;\n this.windowBytes = deps.windowBytes ?? OP_STREAM_DEFAULT_WINDOW_BYTES;\n this.lastFrameAt = Date.now();\n if (checkpoint) {\n this.lastApplied = checkpoint.lastApplied;\n this.hashes = checkpoint.hashes;\n this.totals = checkpoint.totals;\n this.outputDecoders = checkpoint.decoders;\n }\n }\n\n readCheckpoint(): OpReadCheckpoint {\n return {\n lastApplied: this.lastApplied,\n hashes: this.hashes,\n totals: this.totals,\n decoders: this.outputDecoders,\n };\n }\n\n private get ackIntervalMs(): number {\n return this.deps.ackIntervalMs ?? OP_STREAM_ACK_INTERVAL_MS;\n }\n private get silenceTimeoutMs(): number {\n return this.deps.silenceTimeoutMs ?? OP_STREAM_SILENCE_TIMEOUT_MS;\n }\n private get reconnectHoldMs(): number {\n return this.deps.reconnectHoldMs ?? OP_STREAM_RECONNECT_HOLD_MS;\n }\n\n teardown(): void {\n this.torn = true;\n if (this.ackTimer) {\n clearInterval(this.ackTimer);\n this.ackTimer = undefined;\n }\n this.subscription?.unsubscribe();\n this.subscription = undefined;\n }\n\n async run(\n exec: ExecRequest | null,\n deadlineMs: number,\n wallMs: number,\n yieldOptions: OpStreamYieldOptions | null,\n ): Promise<\n | {\n status: \"completed\";\n outcome: OpStreamExecOutcome;\n exitSeq: string;\n }\n | Extract<OpStreamExecResult, { status: \"running\" }>\n > {\n this.captureOnly = exec === null;\n // Arm the settle promise FIRST: frames can start applying the moment the\n // attach below returns (replay is asynchronous), and a completion that\n // fires before the resolver exists would strand the op on its wall.\n const settled = new Promise<void>((resolve, reject) => {\n this.settleResolve = resolve;\n this.settleReject = reject;\n });\n\n // Subscription BEFORE OpStart (protocol invariant): no frame can be\n // published before the consumer exists on a healthy path.\n this.subscription = await this.deps.transport.subscribe(\n opFrameSubject(\n this.deps.workspaceId,\n this.deps.agentId,\n this.opId,\n this.deps.connectionInstanceId,\n ),\n (payload) => this.onFramePayload(payload),\n );\n\n const startRetries = exec === null ? 0 : await this.startOp(exec, deadlineMs);\n\n // The universal begin (B2): attach from our contiguous frontier under the\n // initial window — for a FRESH op that is seq 0 (replay nothing, start live\n // flow); for a KNOWN op (re-dispatch) it replays everything we do not hold.\n await this.attach(this.windowBytes);\n\n // Cumulative-ack repetition (M1) — the periodic leg.\n this.ackTimer = setInterval(() => {\n void this.sendAck();\n }, this.ackIntervalMs);\n const liveness = this.watchLiveness(wallMs);\n let yieldTimer: ReturnType<typeof setTimeout> | undefined;\n let adopted = false;\n try {\n if (yieldOptions && yieldOptions.yieldMs > 0) {\n const phase = await Promise.race([\n settled.then(() => \"settled\" as const),\n liveness.wall,\n new Promise<\"yield\">((resolve) => {\n yieldTimer = setTimeout(() => resolve(\"yield\"), yieldOptions.yieldMs);\n }),\n ]);\n if (phase === \"yield\" && this.exitSeq === undefined) {\n try {\n await yieldOptions.onYield();\n adopted = true;\n } catch (adoptionError) {\n // The command has started, so the failed durable transfer is an\n // outcome-unknown mutation. Cancel only this exact idempotent op and\n // retain the consumer until its terminal frame is physically proven;\n // never return a live locator and never replay the start.\n await this.cancelAfterFailedAdoption();\n await Promise.race([settled, liveness.wall]);\n throw adoptionError;\n }\n // Once adoption commits, this invocation owns only the background\n // receipt. A completion racing the transaction is handled below as\n // terminal proof for the adopted command, never returned inline too.\n if (this.exitSeq === undefined) {\n // Freeze a read's exact local frontier before persistence can block.\n // The runner retains later output; do not accumulate it while the\n // database is slow. Foreground/adoption receipt behavior is unchanged.\n if (this.captureOnly) this.teardown();\n await this.sendBackgroundCredit();\n const partial = this.snapshotOutput();\n await yieldOptions.captureOutput?.(this.outputFrames.splice(0));\n return {\n status: \"running\",\n opId: this.opId,\n stdout: partial.stdout,\n stderr: partial.stderr,\n heals: this.heals,\n startRetries,\n replyBytes: partial.stdout.byteLength + partial.stderr.byteLength,\n };\n }\n }\n } else {\n await Promise.race([settled, liveness.wall]);\n }\n } finally {\n if (yieldTimer) {\n clearTimeout(yieldTimer);\n }\n liveness.stop();\n }\n\n // Settled: the exit frame and every frame before it are applied.\n const exit = this.exit as OpExit;\n const exitSeq = this.exitSeq as bigint;\n if (exit.failureCode && exec !== null && !adopted) {\n throw runnerFailureToControlError(exit);\n }\n const { stdout, stderr } = this.assembleAndVerify(exit);\n if (adopted || exec === null) await yieldOptions?.captureOutput?.(this.outputFrames.splice(0));\n const outcome: OpStreamExecOutcome = {\n ...(exit.failureCode\n ? { failure: { failureCode: exit.failureCode, failureDetail: exit.failureDetail } }\n : {}),\n response: {\n exitCode: exit.exitCode,\n stdout,\n stderr,\n timedOut: exit.timedOut,\n durationMs: exit.durationMs,\n },\n heals: this.heals,\n startRetries,\n replyBytes: stdout.byteLength + stderr.byteLength,\n };\n if (adopted) {\n return {\n status: \"running\",\n opId: this.opId,\n stdout,\n stderr,\n heals: this.heals,\n startRetries,\n replyBytes: outcome.replyBytes,\n terminal: {\n outcome,\n exitSeq: exitSeq.toString(),\n ...(yieldOptions?.captureOutput\n ? {\n outputReceipt: { exitSeq: exitSeq.toString(), attachGeneration: this.generation },\n }\n : {}),\n },\n };\n }\n return {\n status: \"completed\",\n outcome,\n exitSeq: exitSeq.toString(),\n };\n }\n\n private async cancelAfterFailedAdoption(): Promise<void> {\n for (;;) {\n try {\n const result = await this.controlOp({\n $case: \"opCancel\",\n opCancel: { opId: this.opId },\n });\n if (result.$case !== \"opStatus\") {\n throw protocolError(`op-stream cancel: unexpected result ${result.$case}`);\n }\n if (result.opStatus.state === OpState.OP_STATE_LOST) {\n throw lostToControlError(result.opStatus);\n }\n await this.attach(0);\n return;\n } catch (error) {\n if (\n error instanceof SelfhostedControlError &&\n (error.retryable || error.agentOffline || error.reason === \"agent_reconnecting\")\n ) {\n await this.deps.retryClock.sleep(\n selfhostedRetryBackoffMs(0, this.deps.retryClock.jitter()),\n );\n continue;\n }\n throw error;\n }\n }\n }\n\n private async sendBackgroundCredit(): Promise<void> {\n const ack = OpAck.encode({\n opId: this.opId,\n ackedSeq: \"0\",\n creditBytes: OP_STREAM_BACKGROUND_CREDIT_BYTES,\n final: false,\n attachGeneration: this.generation,\n }).finish();\n try {\n await this.deps.transport.publish(\n opAckSubject(this.deps.workspaceId, this.deps.agentId, this.deps.connectionInstanceId),\n ack,\n );\n } catch {\n // Ownership is already durable. Credit is an optimization repeated by a\n // later attach/query path; a publish blip must not turn an adopted command\n // back into an outcome-unknown turn failure.\n }\n }\n\n private snapshotOutput(): { stdout: Uint8Array; stderr: Uint8Array } {\n return {\n stdout: concatChunks(this.chunks.stdout),\n stderr: concatChunks(this.chunks.stderr),\n };\n }\n\n /** OpStart with the patient DRAINING budget and a small blip budget. OpStart\n * is IDEMPOTENT BY OP ID (the request id), so a timed-out/never-sent start\n * is safe to re-issue even though exec mutates — the runner either never saw\n * it or answers the SAME op. The stable request id is what makes that true. */\n private async startOp(exec: ExecRequest, deadlineMs: number): Promise<number> {\n let drainingRetries = 0;\n let blipRetries = 0;\n for (;;) {\n // Subscription setup can yield after the caller's initial admission.\n // Close that window, and the equivalent proven-unstarted retry windows,\n // at the last boundary before bytes can reach the provider.\n await this.deps.revalidateBeforeStartRetry?.();\n try {\n const result = await this.controlOp(\n {\n $case: \"opStart\",\n opStart: {\n op: { $case: \"exec\", exec },\n windowBytes: String(this.windowBytes),\n // Absolute epoch deadline (the runner's clock decides the actual\n // budget; host clock skew shifts it — a known wire caveat).\n deadlineMs: deadlineMs > 0 ? String(Date.now() + deadlineMs) : \"0\",\n originId: this.deps.rpcSubject,\n },\n },\n this.opId,\n );\n if (result.$case !== \"opStart\") {\n throw protocolError(`op-stream start: unexpected result ${result.$case}`);\n }\n const status = result.opStart.status;\n if (!result.opStart.accepted) {\n throw this.refusedStart(status);\n }\n if (status?.state === OpState.OP_STATE_LOST) {\n throw lostToControlError(status);\n }\n return drainingRetries + blipRetries;\n } catch (error) {\n if (!(error instanceof SelfhostedControlError)) {\n throw error;\n }\n // A PROTOCOL/UNSUPPORTED refusal of the START ITSELF means the runner\n // does not speak the required op-stream protocol. The op provably\n // never started, so surface a typed availability error without trying\n // another wire form.\n if (\n error.code === ErrorCode.ERROR_CODE_PROTOCOL ||\n error.code === ErrorCode.ERROR_CODE_UNSUPPORTED\n ) {\n throw new OpStreamUnavailableError(\n `the runner refused OpStart (${error.message})`,\n \"runner\",\n );\n }\n const blip = error.reason === \"agent_reconnecting\" || error.neverSent;\n if (error.draining && drainingRetries < OP_START_DRAINING_MAX_RETRIES) {\n await this.deps.retryClock.sleep(\n selfhostedRetryBackoffMs(drainingRetries, this.deps.retryClock.jitter()),\n );\n drainingRetries += 1;\n continue;\n }\n if (blip && blipRetries < OP_START_BLIP_MAX_RETRIES) {\n await this.deps.retryClock.sleep(\n selfhostedRetryBackoffMs(blipRetries, this.deps.retryClock.jitter()),\n );\n blipRetries += 1;\n continue;\n }\n throw error;\n }\n }\n }\n\n private refusedStart(status: OpStatus | undefined): SelfhostedControlError {\n if (status?.exit?.cancelled) {\n return new SelfhostedControlError({\n message: \"The command was cancelled before the machine admitted it.\",\n code: ErrorCode.ERROR_CODE_TIMEOUT,\n reason: null,\n retryable: false,\n detail: { cancelled: \"true\" },\n });\n }\n if (status?.state === OpState.OP_STATE_LOST) {\n return lostToControlError(status);\n }\n return protocolError(\"op-stream start: the runner refused the op without a typed reason\");\n }\n\n /** One control op on the rpc subject; throws the mapped\n * `SelfhostedControlError` on any AgentError. `requestId` is overridable\n * because OpStart's REQUEST ID IS THE OP ID (its idempotency key) and must\n * be STABLE across retries — every other op uses a fresh UUID per attempt. */\n private async controlOp(\n op: NonNullable<ControlRequest[\"op\"]>,\n requestId: string = crypto.randomUUID(),\n ) {\n const resourcePolicy = op.$case === \"opStart\" ? this.deps.resourcePolicy : undefined;\n const res = await this.deps.controlRpc.request(\n this.deps.rpcSubject,\n {\n requestId,\n epoch: this.deps.epoch,\n resourcePolicy,\n op,\n },\n { timeoutMs: this.deps.controlTimeoutMs },\n );\n if (res.error || !res.result) {\n throw agentErrorToControlError(\n res.error ?? {\n code: ErrorCode.ERROR_CODE_PROTOCOL,\n message: \"agent returned an empty control response\",\n retryable: false,\n detail: {},\n },\n );\n }\n return res.result;\n }\n\n /** OpAttach from the contiguous frontier. `windowBytes` sizes the fresh\n * replay window; 0 = reuse the OpStart grant (the gap-heal path). */\n private async attach(windowBytes: number): Promise<OpStatus> {\n const result = await this.controlOp({\n $case: \"opAttach\",\n opAttach: {\n opId: this.opId,\n fromSeq: this.lastApplied.toString(),\n attachGeneration: this.generation,\n windowBytes: String(windowBytes),\n },\n });\n if (result.$case !== \"opStatus\") {\n throw protocolError(`op-stream attach: unexpected result ${result.$case}`);\n }\n if (result.opStatus.state === OpState.OP_STATE_LOST) {\n throw lostToControlError(result.opStatus);\n }\n return result.opStatus;\n }\n\n /** Gap/silence heal: one re-attach in flight at a time; each success counts\n * as a heal (the observer's `healed` breadcrumb). Failures are left to the\n * liveness watcher — a dead link fails typed there, not here. */\n private requestAttachHeal(): void {\n if (this.attachInFlight || this.torn) {\n return;\n }\n this.attachInFlight = true;\n void this.attach(0)\n .then(() => {\n this.heals += 1;\n })\n .catch((error) => {\n if (error instanceof SelfhostedControlError && !error.retryable && !error.agentOffline) {\n this.settleReject?.(error);\n }\n })\n .finally(() => {\n this.attachInFlight = false;\n });\n }\n\n private onFramePayload(payload: Uint8Array): void {\n if (this.torn) return;\n let frame: OpFrame;\n try {\n frame = OpFrame.decode(payload);\n } catch {\n // A torn frame never kills the subscription; the seq gap it leaves is\n // healed by attach-replay.\n return;\n }\n if (frame.opId !== this.opId) {\n return;\n }\n this.lastFrameAt = Date.now();\n this.silenceSince = undefined;\n const seq = BigInt(frame.seq);\n if (seq <= this.lastApplied) {\n return; // Duplicate (re-delivery / replay overlap) — reassembly is seq-idempotent.\n }\n if (seq !== this.lastApplied + 1n) {\n // Out of order: stash and ask for the gap. Replay heals from the frontier,\n // so an overgrown stash is dropped, not grown without bound.\n const wireBytes = payload.byteLength;\n const stashMaxBytes = this.windowBytes * OP_STREAM_STASH_WINDOW_MULTIPLIER;\n if (!this.stash.has(seq)) {\n if (this.stashedWireBytes + wireBytes <= stashMaxBytes) {\n this.stash.set(seq, { frame, wireBytes });\n this.stashedWireBytes += wireBytes;\n } else {\n this.stash.clear();\n this.stashedWireBytes = 0;\n }\n }\n this.requestAttachHeal();\n return;\n }\n this.applyFrame(frame);\n // Drain any stashed continuation.\n for (;;) {\n const stashed = this.stash.get(this.lastApplied + 1n);\n if (!stashed) {\n break;\n }\n this.stash.delete(this.lastApplied + 1n);\n this.stashedWireBytes -= stashed.wireBytes;\n this.applyFrame(stashed.frame);\n }\n this.maybeSettle();\n this.maybeGrantCredit();\n }\n\n private applyFrame(frame: OpFrame): void {\n this.lastApplied = BigInt(frame.seq);\n const body = frame.body;\n if (!body) {\n return;\n }\n switch (body.$case) {\n case \"data\": {\n const channel = OP_CHANNEL_NAMES[body.data.channel];\n if (channel) {\n if (this.captureOnly) {\n this.hashes[channel].update(body.data.bytes);\n this.totals[channel] += BigInt(body.data.bytes.byteLength);\n } else {\n this.chunks[channel].push(body.data.bytes);\n }\n const chunk = this.outputDecoders[channel].decode(body.data.bytes, { stream: true });\n if (chunk) this.outputFrames.push({ sequence: frame.seq, stream: channel, chunk });\n }\n this.receivedPayloadBytes += BigInt(body.data.bytes.byteLength);\n break;\n }\n case \"progress\":\n // A liveness tick; echo our cumulative ack (M1's on-progress leg).\n void this.sendAck();\n break;\n case \"exit\":\n for (const stream of [\"stdout\", \"stderr\"] as const) {\n const chunk = this.outputDecoders[stream].decode();\n if (chunk) this.outputFrames.push({ sequence: frame.seq, stream, chunk });\n }\n this.exit = body.exit;\n this.exitSeq = BigInt(frame.seq);\n break;\n }\n }\n\n private maybeSettle(): void {\n if (this.exitSeq !== undefined && this.lastApplied >= this.exitSeq) {\n this.settleResolve?.();\n }\n }\n\n /** Prompt credit replenishment: the periodic ack alone would stall a fast\n * child for up to the ack interval each window; grant as soon as half the\n * window has been consumed since the last grant. */\n private maybeGrantCredit(): void {\n if (this.receivedPayloadBytes - this.creditAtLastAck >= BigInt(this.windowBytes) / 2n) {\n void this.sendAck();\n }\n }\n\n /** The mid-op cumulative ack: CREDIT-ONLY (Δ2 — acked_seq stays 0 so the\n * runner retains every frame for a possible successor consumer; the credit\n * is an absolute replacement sized to keep ~one window of live headroom). */\n private async sendAck(): Promise<void> {\n if (this.torn) {\n return;\n }\n this.creditAtLastAck = this.receivedPayloadBytes;\n const ack = OpAck.encode({\n opId: this.opId,\n ackedSeq: \"0\",\n creditBytes: (this.receivedPayloadBytes + BigInt(this.windowBytes)).toString(),\n final: false,\n attachGeneration: this.generation,\n }).finish();\n try {\n await this.deps.transport.publish(\n opAckSubject(this.deps.workspaceId, this.deps.agentId, this.deps.connectionInstanceId),\n ack,\n );\n } catch {\n // Acks are best-effort and healed by repetition (M1).\n }\n }\n\n /**\n * The liveness watcher: probes a silent op with OpQuery, re-attaches when the\n * runner is ahead of us (frames lost in flight), holds a quiet-but-alive op\n * open through the reconnect window, and enforces an explicit client-side wall.\n * Resolves only by rejection (typed failure) or by `stop()` at settle.\n */\n private watchLiveness(wallMs: number): { wall: Promise<never>; stop: () => void } {\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const wall = new Promise<never>((_, reject) => {\n const startedAt = Date.now();\n const tick = async () => {\n if (stopped) {\n return;\n }\n try {\n if (wallMs > 0 && Date.now() - startedAt >= wallMs) {\n // The runner enforces the exec deadline and emits Exit{timed_out};\n // reaching OUR wall means even that terminal frame never arrived —\n // the same ambiguity as a legacy reply timeout, surfaced the same.\n reject(agentErrorToControlError(timeoutAgentError()));\n return;\n }\n if (Date.now() - this.lastFrameAt >= this.silenceTimeoutMs) {\n await this.probeSilence(reject);\n }\n } catch (error) {\n reject(error);\n return;\n }\n timer = setTimeout(tick, Math.min(this.silenceTimeoutMs / 3, 2_500));\n };\n timer = setTimeout(tick, Math.min(this.silenceTimeoutMs / 3, 2_500));\n });\n return {\n wall,\n stop: () => {\n stopped = true;\n if (timer) {\n clearTimeout(timer);\n }\n },\n };\n }\n\n /** One silence probe: OpQuery the op; a definitive answer acts, an offline /\n * blip answer holds through the reconnect window, then fails typed. */\n private async probeSilence(reject: (error: unknown) => void): Promise<void> {\n this.silenceSince ??= Date.now();\n try {\n const result = await this.controlOp({ $case: \"opQuery\", opQuery: { opId: this.opId } });\n if (result.$case !== \"opStatus\") {\n throw protocolError(`op-stream query: unexpected result ${result.$case}`);\n }\n const status = result.opStatus;\n if (status.state === OpState.OP_STATE_LOST) {\n reject(lostToControlError(status));\n return;\n }\n // Alive on the runner. If it is ahead of our frontier, frames were lost\n // in flight — re-attach to replay them (this also restores live flow\n // after a reconnect). A quiet-but-current op just keeps holding.\n if (BigInt(status.nextSeq) > this.lastApplied + 1n) {\n this.requestAttachHeal();\n }\n } catch (error) {\n if (!(error instanceof SelfhostedControlError)) {\n throw error;\n }\n const transient =\n error.agentOffline || error.reason === \"agent_reconnecting\" || error.draining;\n if (!transient) {\n throw error;\n }\n const heldFor = Date.now() - (this.silenceSince ?? Date.now());\n if (heldFor >= this.reconnectHoldMs) {\n // The hold window expired without the machine coming back — surface\n // the LAST probe's typed error (offline/reconnecting), same taxonomy\n // as the legacy path.\n reject(error);\n }\n // Otherwise: keep holding — op ⊥ connection (the runner keeps the child\n // running and retains its output through the blip).\n }\n }\n\n /** Assemble each channel once and prove byte exactness. Clearing the chunk\n * arrays after assembly avoids keeping both every source frame and the final\n * contiguous result live while a large response crosses the caller boundary. */\n private assembleAndVerify(exit: OpExit): { stdout: Uint8Array; stderr: Uint8Array } {\n const assembled = {\n stdout: concatChunks(this.chunks.stdout),\n stderr: concatChunks(this.chunks.stderr),\n };\n for (const channel of [\"stdout\", \"stderr\"] as const) {\n const bytes = assembled[channel];\n // A terminal result can license collection of retained native output.\n // Both channels, including empty ones, must carry verifiable metadata.\n const declaredTotal = exit.totals?.[channel];\n if (typeof declaredTotal !== \"string\" || !/^[0-9]+$/.test(declaredTotal)) {\n throw protocolError(`op-stream reassembly: ${channel} total missing or invalid`);\n }\n const total = this.captureOnly ? this.totals[channel] : BigInt(bytes.byteLength);\n if (BigInt(declaredTotal) !== total) {\n throw protocolError(\n `op-stream reassembly: ${channel} total mismatch (got ${total}, ` +\n `runner declared ${declaredTotal})`,\n );\n }\n const declaredDigest = exit.digests?.[channel];\n if (typeof declaredDigest !== \"string\" || declaredDigest.length === 0) {\n throw protocolError(`op-stream reassembly: ${channel} digest missing`);\n }\n const digest = bytesToHex(\n this.captureOnly ? this.hashes[channel].clone().digest() : blake3(bytes),\n );\n if (digest !== declaredDigest) {\n throw protocolError(\n `op-stream reassembly: ${channel} digest mismatch (got ${digest}, ` +\n `runner declared ${declaredDigest})`,\n );\n }\n this.chunks[channel].length = 0;\n }\n return assembled;\n }\n}\n\nfunction concatChunks(chunks: Uint8Array[]): Uint8Array {\n const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return out;\n}\n\nfunction protocolError(message: string): SelfhostedControlError {\n return new SelfhostedControlError({\n message,\n code: ErrorCode.ERROR_CODE_PROTOCOL,\n reason: null,\n retryable: false,\n });\n}\n\n/** A definitive `lost` status → a typed op-level failure. The result was\n * bounded-retention collateral (LRU eviction / a runner restart predating the\n * persistence milestone) — honest, never silent. */\nfunction lostToControlError(status: OpStatus): SelfhostedControlError {\n const reason =\n status.lostReason === OpLostReason.OP_LOST_REASON_EVICTED\n ? \"its retained result was evicted before collection\"\n : status.lostReason === OpLostReason.OP_LOST_REASON_AGENT_RESTARTED\n ? \"the machine agent restarted and the op did not survive\"\n : \"the runner reported it lost\";\n return new SelfhostedControlError({\n message:\n `The command's result is no longer available on the machine (${reason}). ` +\n \"Check whether its effects already took place before re-running it.\",\n code: ErrorCode.ERROR_CODE_STREAM,\n reason: null,\n retryable: false,\n detail: { lost_reason: String(status.lostReason) },\n });\n}\n\n/**\n * A runner-typed terminal failure (OpExit.failure_code — OP_OVERFLOW /\n * OP_SPOOL_IO / OP_PIPE_IO; never an exit-code sentinel). OP_OVERFLOW maps to\n * the PAYLOAD_TOO_LARGE taxonomy: the semantics differ (retention quota vs\n * reply size) but the model's correct next action is identical — bound the\n * output, redirect to a file, read it back in ranges — so it gets the same\n * actionable rendering, with the runner's exact counters in the detail.\n */\nexport function runnerFailureToControlError(\n exit: Pick<OpExit, \"failureCode\" | \"failureDetail\">,\n): SelfhostedControlError {\n if (exit.failureCode === \"OP_OVERFLOW\") {\n return new SelfhostedControlError({\n message:\n \"The command produced more output than the machine link can retain for delivery. \" +\n \"Redirect the command's output to a file (for example `<command> > /tmp/out.log 2>&1`) \" +\n \"and then read that file back in ranges or chunks instead of returning it all at once.\",\n code: ErrorCode.ERROR_CODE_PAYLOAD_TOO_LARGE,\n reason: null,\n retryable: false,\n payloadTooLarge: true,\n // failure_code lets the fault renderer distinguish the retention-ceiling\n // overflow (command TERMINATED at the ceiling) from the legacy reply-size\n // wall (command ran to completion) — the four fields must tell the truth.\n detail: { ...exit.failureDetail, failure_code: exit.failureCode },\n });\n }\n return new SelfhostedControlError({\n message:\n `The command failed on the machine's streaming transport (${exit.failureCode}). ` +\n \"The machine kept running it, but its output could not be captured intact.\",\n code: ErrorCode.ERROR_CODE_STREAM,\n reason: null,\n retryable: false,\n detail: { ...exit.failureDetail, failure_code: exit.failureCode },\n });\n}\n","// The op-stream TRANSPORT seam (op-stream protocol v1.1, server half).\n//\n// The op-stream client needs two primitives the request/reply `ControlRpc`\n// cannot express: a plain SUBSCRIPTION (runner→server op frames on\n// `agent.<ws>.<id>.connection.<instance>.op.<op_id>`, fire-and-forget publishes)\n// and a plain PUBLISH (server→runner acks on the exact instance's `.ack`).\n// exactly like control-rpc.ts defines `ControlRpc`: the session leaf speaks\n// ONLY `OpStreamTransport`; the worker/api inject a live NATS-backed\n// implementation (the same lazy-factory discipline — boot never requires a\n// live NATS), and tests inject an in-memory one.\n//\n// The control ops that START/steer an op (OpStart/OpCancel/OpQuery/OpAttach)\n// deliberately do NOT ride this seam — they are ordinary `ControlRequest`s on\n// the existing rpc subject through the existing `ControlRpc`, with its typed\n// offline/timeout synthesis and retry taxonomy.\n\n/** The per-op frame subject for one exact runner generation. */\nexport function opFrameSubject(\n workspaceId: string,\n agentId: string,\n opId: string,\n connectionInstanceId: string,\n): string {\n if (typeof connectionInstanceId !== \"string\" || connectionInstanceId.trim().length === 0) {\n throw new Error(\"Connected Machine op frames require an exact connection instance\");\n }\n return `agent.${workspaceId}.${agentId}.connection.${connectionInstanceId}.op.${opId}`;\n}\n\n/** The per-agent ack subject (server→runner, fire-and-forget). Mirrors the\n * runner's exact generation-fenced ack subject. */\nexport function opAckSubject(\n workspaceId: string,\n agentId: string,\n connectionInstanceId: string,\n): string {\n if (typeof connectionInstanceId !== \"string\" || connectionInstanceId.trim().length === 0) {\n throw new Error(\"Connected Machine op acknowledgements require an exact connection instance\");\n }\n return `agent.${workspaceId}.${agentId}.connection.${connectionInstanceId}.ack`;\n}\n\n/** A live subscription handle. `unsubscribe` is idempotent and never throws. */\nexport interface OpStreamSubscription {\n unsubscribe(): void;\n}\n\n/**\n * The op-stream transport seam. `subscribe` MUST be established before the\n * OpStart that makes frames flow (subscription-before-start is a protocol\n * invariant: no frame is published before the consumer exists on a healthy\n * path; a missed frame is healed via OpAttach replay regardless). `onMessage`\n * is invoked in arrival order; a decode failure inside the handler must be\n * contained by the caller (a torn frame must never kill the subscription).\n */\nexport interface OpStreamTransport {\n subscribe(\n subject: string,\n onMessage: (payload: Uint8Array) => void,\n ): Promise<OpStreamSubscription>;\n publish(subject: string, payload: Uint8Array): Promise<void>;\n}\n\n/** Thrown before OpStart when the stream transport is unavailable or the runner\n * does not support the required protocol. Exec fails before dispatch and never\n * retries through a request/reply wire form. */\nexport class OpStreamUnavailableError extends Error {\n readonly name = \"OpStreamUnavailableError\";\n\n constructor(\n message: string,\n readonly unavailableKind: \"transport\" | \"runner\" = \"transport\",\n ) {\n super(message);\n }\n}\n\n/**\n * The minimal NATS surface the transport needs — mirrors the `nats`\n * `NatsConnection` subscribe/publish WITHOUT importing `nats` into the\n * agent-loop-free runtime leaf (the worker injects the live `@opengeni/events`\n * bus connection, exactly like `NatsRequestConnection` in control-rpc.ts).\n * `subscribe` returns the nats.js Subscription shape: an async iterable of\n * messages plus `unsubscribe()`.\n */\nexport interface NatsOpStreamConnection {\n subscribe(subject: string): AsyncIterable<{ data: Uint8Array }> & { unsubscribe(): void };\n publish(subject: string, payload: Uint8Array): void;\n}\n\n/**\n * The NATS-backed transport. Lazy memoized factory (identical discipline to\n * `NatsControlRpc`): the connection resolves on first use; a null factory\n * result or a dial failure surfaces `OpStreamUnavailableError` — the caller\n * (the session) fails before dispatch; exec has no request/reply downgrade.\n */\nexport class NatsOpStreamTransport implements OpStreamTransport {\n private readonly connect: () => Promise<NatsOpStreamConnection | null>;\n private connection: NatsOpStreamConnection | undefined;\n private connecting: Promise<NatsOpStreamConnection | null> | undefined;\n\n constructor(connect: () => Promise<NatsOpStreamConnection | null>) {\n this.connect = connect;\n }\n\n private async resolveConnection(): Promise<NatsOpStreamConnection | null> {\n if (this.connection) {\n return this.connection;\n }\n // Share one in-flight dial; cache only a real connection (a transient\n // null/throw must be retried by the next call — see NatsControlRpc).\n this.connecting ??= this.connect()\n .then((connection) => {\n if (connection) {\n this.connection = connection;\n }\n return connection;\n })\n .catch(() => null)\n .finally(() => {\n this.connecting = undefined;\n });\n return this.connecting;\n }\n\n async subscribe(\n subject: string,\n onMessage: (payload: Uint8Array) => void,\n ): Promise<OpStreamSubscription> {\n const conn = await this.resolveConnection();\n if (!conn) {\n throw new OpStreamUnavailableError(\"op-stream transport has no live connection\");\n }\n const subscription = conn.subscribe(subject);\n // Pump the async iterator into the callback. The iterator ends when\n // `unsubscribe()` is called (nats.js closes the iterator); a pump error\n // (torn connection) simply ends delivery — the op-stream client's silence\n // handling (OpQuery + re-attach) owns recovery, not the transport.\n void (async () => {\n try {\n for await (const message of subscription) {\n onMessage(message.data);\n }\n } catch {\n // Delivery ended with the connection; recovery is the client's job.\n }\n })();\n let unsubscribed = false;\n return {\n unsubscribe: () => {\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n try {\n subscription.unsubscribe();\n } catch {\n // Idempotent teardown: a torn connection already unsubscribed us.\n }\n },\n };\n }\n\n async publish(subject: string, payload: Uint8Array): Promise<void> {\n const conn = await this.resolveConnection();\n if (!conn) {\n throw new OpStreamUnavailableError(\"op-stream transport has no live connection\");\n }\n conn.publish(subject, payload);\n }\n}\n","// Bring-your-own-compute: the user's own machine, enrolled via the Rust agent,\n// is reached over the NATS request/reply control plane. Postgres resolves the\n// exact claimed runner instance and NATS addresses\n// `agent.<workspace>.<agentId>.connection.<instanceId>.rpc`. There is NO provider\n// SDK and NO per-box credential — \"the agent is the box\".\n//\n// M3 ships the REAL `SelfhostedSandboxClient`: its `create()`/`resume()` return a\n// `SelfhostedSession` presenting the structural surface (`exec`/`readFile`/\n// `writeFile`/`resolveExposedPort`/`serializeSessionState`) that Channel-A and the\n// viewer consume unchanged — backed by a `ControlRpc` seam\n// (request/reply encoded via `@opengeni/agent-proto`) instead of a provider SDK.\n// `serializeSessionState`/`deserializeSessionState` round-trip `{agentId}` ONLY:\n// resume = re-address the live subject, never a cold re-create (the machine is\n// not recreatable). The live NATS request/reply transport + Accounts land in M4\n// behind the SAME `ControlRpc`.\n\nimport type { Settings } from \"@opengeni/config\";\nimport { CAPABILITY_DESCRIPTORS } from \"../capabilities\";\nimport {\n NatsControlRpc,\n type ControlRpc,\n type NatsRequestConnection,\n} from \"../selfhosted/control-rpc\";\nimport { SelfhostedSandboxClient, type SelfhostedRelayConfig } from \"../selfhosted/session\";\nimport type { ProviderRegistration } from \"./types\";\n\n/**\n * Resolve the relay-URL shape config from settings. M8b threads the real relay\n * deployment URL (`OPENGENI_SELFHOSTED_RELAY_URL`, ops-repo IaC) behind this seam:\n * `resolveExposedPort` returns `{host, port, tls, path, query}` so `buildStreamUrl`\n * assembles the relay dial URL. A path-less URL defaults to the relay's `/stream`\n * route; an unconfigured deployment falls back to a placeholder host (the URL shape\n * is still well-formed; the relay is simply unreachable until configured).\n */\nfunction resolveRelayConfig(settings: Settings): SelfhostedRelayConfig {\n const raw = settings.selfhostedRelayUrl?.trim();\n if (!raw) {\n return { host: \"relay.opengeni.local\", port: 443, tls: true, path: \"/stream\" };\n }\n try {\n const url = new URL(raw.includes(\"://\") ? raw : `wss://${raw}`);\n const tls = url.protocol === \"wss:\" || url.protocol === \"https:\";\n const port = url.port ? Number(url.port) : tls ? 443 : 80;\n const path = url.pathname && url.pathname !== \"/\" ? url.pathname : \"/stream\";\n return { host: url.hostname, port, tls, path };\n } catch {\n return { host: raw, port: 443, tls: true, path: \"/stream\" };\n }\n}\n\n/**\n * The default `ControlRpc` factory for a registry-built client: a\n * `NatsControlRpc` whose connection factory returns null — there is NO live NATS\n * connection wired into the agent-loop-free runtime leaf at build() time (the\n * API/worker inject the live `@opengeni/events` connection per request in M4).\n * A null connection surfaces `agent_offline` on every op rather than throwing at\n * construction, so boot never requires a live NATS — exactly the M3 ruling.\n */\nfunction defaultControlRpcFactory(): ControlRpc {\n return new NatsControlRpc(async (): Promise<NatsRequestConnection | null> => null);\n}\n\nexport const selfhostedProvider: ProviderRegistration = {\n backend: \"selfhosted\",\n exactResumeMode: \"ordinary\",\n instanceIdFields: [\"agentId\"],\n workspaceCapturePolicy: () => null,\n descriptor: CAPABILITY_DESCRIPTORS.selfhosted,\n /**\n * No per-box credentials: the machine is reached over the agent's own\n * enrollment. The enrollment-signing + relay-token secrets are deployment-level\n * config that lands with the connectivity/enrollment milestones (M4/M5) — and\n * the whole feature is gated by a `sandboxSelfhostedEnabled` flag (default off)\n * that does not yet exist in Settings. So validation is LENIENT (no-op) in M3:\n * boot must never break, and there is nothing per-box to validate. M4/M5 add\n * the (flag-gated) signing/relay presence checks here behind the same seam.\n */\n validateCredentials() {},\n /**\n * Build the registry client. `create()`/`resume()` bind a `SelfhostedSession`\n * to the agent subject; the per-request `{workspaceId, agentId, controlRpc}`\n * are supplied by the resume path (the lease's enrollment) — the registry\n * client carries the relay config + the default (offline-until-M4) ControlRpc\n * factory and a backendId-correct surface for `assertProviderRegistryInvariants`.\n */\n build({ settings }) {\n return new SelfhostedSandboxClient({\n // The workspaceId is bound per-request by the resume path (the API/worker\n // construct a request-scoped client with the lease's workspace + a live\n // ControlRpc). The registry-built client is the boot/assertion shape; an\n // empty workspaceId is fine until a session is bound with a real one.\n workspaceId: \"\",\n // Inert registry shape only; request-scoped production clients replace\n // this with the persisted machine Hello root before any operation.\n workspaceRoot: \"/workspace\",\n relay: resolveRelayConfig(settings),\n controlRpcFactory: defaultControlRpcFactory,\n });\n },\n};\n","import { VercelSandboxClient } from \"@openai/agents-extensions/sandbox/vercel\";\nimport { CAPABILITY_DESCRIPTORS } from \"../capabilities\";\nimport { SandboxConfigError } from \"../errors\";\nimport {\n REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE,\n REPEATABLE_PORTABLE_TAR_WORKSPACE_CAPTURE,\n providerWorkspacePersistence,\n type ProviderRegistration,\n} from \"./types\";\n\nexport const vercelProvider: ProviderRegistration = {\n backend: \"vercel\",\n exactResumeMode: \"ordinary\",\n instanceIdFields: [\"sandboxId\"],\n workspaceCapturePolicy: (state) =>\n providerWorkspacePersistence(state) === \"snapshot\"\n ? REPEATABLE_PORTABLE_TAR_WORKSPACE_CAPTURE\n : REPEATABLE_CONFIGURED_WORKSPACE_CAPTURE,\n prepareForTeardownAfterCapture(session) {\n const state = (session as { state?: { workspacePersistence?: unknown } } | null)?.state;\n if (state?.workspacePersistence === \"snapshot\") {\n // Vercel close() otherwise takes a second native snapshot before stop.\n // The portable tar is already durable, so suppress that unledgered,\n // identity-adjacent side effect on this disposable resumed handle only.\n state.workspacePersistence = \"tar\";\n }\n },\n descriptor: CAPABILITY_DESCRIPTORS.vercel,\n validateCredentials(settings) {\n // Vercel needs the access token + the project/team it scopes to.\n if (!settings.vercelToken) {\n throw new SandboxConfigError(\"vercel\", \"OPENGENI_VERCEL_TOKEN is required\");\n }\n if (!settings.vercelProjectId) {\n throw new SandboxConfigError(\"vercel\", \"OPENGENI_VERCEL_PROJECT_ID is required\");\n }\n },\n build({ settings, environment, exposedPorts }) {\n const options: NonNullable<ConstructorParameters<typeof VercelSandboxClient>[0]> = {\n token: settings.vercelToken!,\n projectId: settings.vercelProjectId!,\n env: environment,\n exposedPorts,\n };\n if (settings.vercelTeamId) options.teamId = settings.vercelTeamId;\n if (settings.vercelRuntime) options.runtime = settings.vercelRuntime;\n return new VercelSandboxClient(options);\n },\n};\n","// Backend selection + capability negotiation/degradation (module 03 §0, §5).\n//\n// negotiateCapabilities() turns a static CapabilityDescriptor + runtime context\n// (the selected OS, the lease liveness/epoch, and the deployment's desktop\n// policy) into a coherent SessionCapabilities document. The load-bearing rule\n// (sandbox contract Part D): a capability cell is ALWAYS present — when unavailable\n// it is `available:false` + a typed `reason`, NEVER absent. Degradation is a\n// value, not a silent drop.\n\nimport {\n CAPABILITY_DESCRIPTORS,\n type CapabilityDescriptor,\n type CapabilityUnavailableReason,\n type SandboxBackend,\n type SandboxOs,\n type SessionCapabilities,\n} from \"@opengeni/contracts\";\n\nexport interface NegotiationContext {\n sessionId: string;\n backend: SandboxBackend;\n os: SandboxOs;\n /** Current lease liveness; only warm proves a holder-backed live provider. */\n liveness: \"cold\" | \"warming\" | \"warm\" | \"draining\";\n /** The lease epoch echoed on viewer heartbeats (the split-brain fence). */\n leaseEpoch: number;\n /** Numeric/boolean archive completeness truth. Non-persistable targets use\n * null/null/false; archive locations and provider details are never exposed. */\n workspaceGeneration?: number | null;\n archiveGeneration?: number | null;\n archiveComplete?: boolean;\n /** The deployment desktop toggle (settings.sandboxDesktopEnabled). */\n desktopEnabled: boolean;\n /**\n * The HUMAN take-control toggle (settings.sandboxDesktopInteractive). When true\n * (default) and the desktop cell is available, the negotiated DesktopStream.mode\n * is \"interactive\" — the noVNC viewer can drive mouse+keyboard into :0 (the box's\n * x11vnc runs without -viewonly). When false the cell reports mode \"read-only\"\n * and the client disables the \"Take control\" affordance (a genuinely read-only\n * deployment). Agent interaction is authorized separately through managed\n * ComputerSession tools. Defaults to true so a caller that never threads it\n * (e.g. headless tests) still gets the interactive plane when the desktop is\n * available.\n */\n desktopInteractive?: boolean;\n /**\n * Whether a scoped-stream-token secret is resolvable (stream-token availability contract). When desktop\n * is enabled but this is false (no streamTokenSecret AND no delegationSecret),\n * the desktop plane GRACEFULLY DEGRADES to transport:null — the deployment\n * boots, but the pixel plane cannot mint scoped tokens. Defaults to true so a\n * caller that never threads it (e.g. headless tests) is unaffected.\n */\n streamTokenSecretAvailable?: boolean;\n /** Whether the calling principal has acknowledged the un-redacted desktop\n * pixels (and, for a shared box, the shared-exposure disclosure). When the\n * box is shared this must be the SHARED acknowledgment; a bare un-redacted ack\n * does not satisfy a shared box. */\n desktopAcknowledged?: boolean;\n /** True when the box's group has >1 session: watching this desktop also shows\n * the sibling sessions' agents on the one :0 framebuffer (addendum E.1). */\n shared?: boolean;\n /** The OTHER sessions whose agents may appear on the shared desktop — IDS\n * ONLY, never their conversation/metadata (stress g). Empty for a solo box. */\n sharedSessionIds?: string[];\n /**\n * The minted pixel-plane endpoint (P4.2): the direct-to-provider WS URL + the\n * scoped stream token + its expiry + the framebuffer geometry. Threaded only by\n * the explicit viewer grant AFTER it has resumed the box, ensured the display\n * stack, and resolved the provider tunnel. When ABSENT (the descriptor read, a\n * cold lease, or a degraded desktop) the DesktopStream cell reports url/token/\n * expiresAt as null — the capability is advertised, the live address is not yet\n * minted (the caller POSTs to /viewers to mint it). Presence does NOT override\n * the gates: a degraded/cold/unacked desktop still reports transport:null and\n * the minted endpoint is dropped.\n */\n desktopStream?: {\n url: string;\n token: string;\n expiresAt: string;\n resolution: [number, number];\n };\n /** The deployment terminal toggle (settings.sandboxTerminalEnabled). The REAL\n * PTY (ttyd pty-ws) is gated on this + a real-PTY backend; when off the\n * Terminal cell still advertises the read-only sse-events firehose. Defaults to\n * true so a caller that never threads it is unaffected. */\n terminalEnabled?: boolean;\n /**\n * The minted terminal-plane endpoint (P5.t): the direct-to-provider ttyd\n * PTY-over-websocket URL + the scoped stream token + its expiry. Threaded by the\n * explicit viewer grant AFTER it has resumed the box, ensured the terminal\n * server, and resolved the provider tunnel (mintTerminalStream) — SYMMETRIC with\n * `desktopStream`. When ABSENT (the negotiation-only read, a cold lease, or a\n * degraded terminal) the Terminal cell reports url/token/expiresAt as null and\n * falls back to transport \"sse-events\" (the read-only firehose) — the caller\n * POSTs to /viewers to mint the live pty-ws address.\n */\n terminalStream?: {\n url: string;\n token: string;\n expiresAt: string;\n transport?: \"pty-ws\" | \"relay-pty\";\n };\n /** Override the negotiation clock (tests). */\n now?: Date;\n}\n\n/**\n * Resolve the descriptor for a backend. Throws on an unknown backend rather than\n * returning a half-formed default (the registry is the single source of truth).\n */\nexport function selectBackend(backend: SandboxBackend): CapabilityDescriptor {\n const descriptor = CAPABILITY_DESCRIPTORS[backend];\n if (!descriptor) {\n throw new Error(`Unknown sandbox backend \"${backend}\"`);\n }\n return descriptor;\n}\n\n/**\n * Return the Agents SDK wire identifier for a product sandbox backend.\n *\n * Durable envelopes use the SDK identifier, which differs from the product\n * registry key for the local provider (`unix_local` versus `local`). Keep that\n * translation here so persistence, routing, and provider construction cannot\n * drift into near-identical private mappings.\n */\nexport function sdkBackendIdForSandboxBackend(backend: SandboxBackend): string {\n return selectBackend(backend).backendId;\n}\n\n/**\n * Resolve either a product registry key or an Agents SDK wire identifier to the\n * canonical product backend. Unknown identifiers stay unknown instead of being\n * coerced to the deployment default.\n */\nexport function sandboxBackendForSdkBackendId(backendId: string): SandboxBackend | null {\n if (Object.hasOwn(CAPABILITY_DESCRIPTORS, backendId)) {\n return backendId as SandboxBackend;\n }\n for (const backend of Object.keys(CAPABILITY_DESCRIPTORS) as SandboxBackend[]) {\n if (CAPABILITY_DESCRIPTORS[backend].backendId === backendId) {\n return backend;\n }\n }\n return null;\n}\n\n/** True iff the descriptor lists the requested OS as supported. */\nexport function backendSupportsOs(descriptor: CapabilityDescriptor, os: SandboxOs): boolean {\n return descriptor.os.supported.includes(os);\n}\n\n/**\n * True iff the backend can serve the Channel-B desktop pixel plane at all — i.e.\n * its static descriptor advertises DesktopStream as available. The gate the\n * worker / API use before launching the display stack (so a headless-only\n * backend like cloudflare/vercel/none never tries). This is the STATIC\n * feasibility only; the runtime `sandboxDesktopEnabled` policy toggle and the\n * stream-token-secret gate are layered on by the caller / negotiateCapabilities.\n *\n * Accepts EITHER the SandboxBackend enum value (e.g. \"local\") OR the SDK\n * client backendId (e.g. \"unix_local\") — they diverge for the local backend —\n * so a caller holding only `established.backendId` resolves correctly.\n */\nexport function desktopCapableBackend(backend: SandboxBackend | string): boolean {\n const direct = CAPABILITY_DESCRIPTORS[backend as SandboxBackend];\n if (direct) {\n return direct.capabilities.DesktopStream.available === true;\n }\n // Fall back to a backendId lookup (the SDK client id, which differs from the\n // enum key for `local`/`unix_local`).\n for (const descriptor of Object.values(CAPABILITY_DESCRIPTORS)) {\n if (descriptor.backendId === backend) {\n return descriptor.capabilities.DesktopStream.available === true;\n }\n }\n return false;\n}\n\n/**\n * Negotiate a coherent SessionCapabilities document for (backend, os). Every\n * capability is reported with availability + a reason-when-unavailable; nothing\n * is ever absent. The reason precedence is: os_unsupported (the OS axis can't be\n * served at all) > the per-capability static feasibility > policy/liveness gates.\n */\nexport function negotiateCapabilities(ctx: NegotiationContext): SessionCapabilities {\n const descriptor = selectBackend(ctx.backend);\n const osSupported = backendSupportsOs(descriptor, ctx.os);\n const negotiatedAt = (ctx.now ?? new Date()).toISOString();\n\n // The dominant degrade: an unsupported OS knocks out every capability with a\n // single coherent reason.\n const osReason: CapabilityUnavailableReason | null = osSupported ? null : \"os_unsupported\";\n\n const fileSystem = (() => {\n if (osReason) {\n return {\n available: false,\n readOnly: true,\n root: descriptor.workspaceRoot,\n pathSep: \"/\" as const,\n treeMode: \"lazy\" as const,\n reason: osReason,\n };\n }\n const cap = descriptor.capabilities.FileSystem;\n return {\n available: cap.available,\n readOnly: cap.readOnly,\n root: descriptor.workspaceRoot,\n pathSep: \"/\" as const,\n treeMode: \"lazy\" as const,\n reason: cap.available ? null : (\"backend_unsupported\" as const),\n };\n })();\n\n const terminal = (() => {\n const cap = descriptor.capabilities.Terminal;\n if (osReason) {\n return {\n transport: null,\n ptyCapable: false,\n shell: \"/bin/bash\",\n url: null,\n token: null,\n expiresAt: null,\n reason: osReason,\n };\n }\n if (!cap.available) {\n return {\n transport: null,\n ptyCapable: false,\n shell: \"/bin/bash\",\n url: null,\n token: null,\n expiresAt: null,\n reason: \"backend_unsupported\" as const,\n };\n }\n // The REAL PTY (ttyd pty-ws) rides the SAME tunnel as the desktop, so it is\n // gated identically: a real-PTY backend (cap.pty), the terminal policy toggle\n // ON, and a live box. Until those hold the cell advertises the read-only\n // sse-events firehose (Channel-A command.output still works) with a typed\n // reason — degradation is a value, never an absent capability.\n // - terminal off -> sse-events + disabled_by_policy.\n // - cold lease + NO mint -> sse-events + lease_cold (no live pty-ws address;\n // the caller mints it via mintTerminalStream at\n // viewer attach).\n // - not a real-PTY backend-> sse-events (no reason; the firehose IS the cap).\n // A PRESENT minted pty-ws url (ctx.terminalStream) is ITSELF proof of liveness:\n // the box (Modal-warm OR selfhosted-online) actually served the ttyd port, so a\n // cold MODAL-GROUP lease liveness must NOT degrade it. lease_cold only fires\n // when nothing was minted. A selfhosted-active session has no warm Modal lease\n // (liveness \"cold\") yet mints a valid RELAY pty-ws cell — honour it.\n const ptyCapable = cap.pty;\n let transport: \"pty-ws\" | \"relay-pty\" | \"sse-events\" = ptyCapable\n ? (ctx.terminalStream?.transport ?? (cap.transport === \"relay-pty\" ? \"relay-pty\" : \"pty-ws\"))\n : \"sse-events\";\n let reason: CapabilityUnavailableReason | null = null;\n if (ptyCapable && (ctx.terminalEnabled === false || ctx.streamTokenSecretAvailable === false)) {\n transport = \"sse-events\";\n reason = \"disabled_by_policy\";\n } else if (ptyCapable && ctx.liveness !== \"warm\" && !ctx.terminalStream) {\n transport = \"sse-events\";\n reason = \"lease_cold\";\n }\n // The minted pty-ws endpoint is folded in ONLY when the terminal is actually\n // serving pty-ws (the gates passed). When absent the cell advertises the\n // capability with a null live address — the caller mints it via POST /viewers.\n const minted =\n transport === \"pty-ws\" || transport === \"relay-pty\" ? ctx.terminalStream : undefined;\n return {\n transport,\n ptyCapable,\n shell: \"/bin/bash\",\n url: minted?.url ?? null,\n token: minted?.token ?? null,\n expiresAt: minted?.expiresAt ?? null,\n reason,\n };\n })();\n\n const git = (() => {\n const cap = descriptor.capabilities.Git;\n if (osReason) {\n return { available: false, repos: [], reason: osReason };\n }\n return {\n available: cap.available,\n repos: [],\n reason: cap.available ? null : (\"backend_unsupported\" as const),\n };\n })();\n\n const desktop = (() => {\n const cap = descriptor.capabilities.DesktopStream;\n // Reason precedence: OS > backend-tier feasibility > policy disable >\n // stream-token-secret > cold lease WITHOUT a mint.\n let reason: CapabilityUnavailableReason | null = null;\n let available = cap.available;\n if (osReason) {\n available = false;\n reason = osReason;\n } else if (!cap.available) {\n available = false;\n // Headless tiers expose the typed tier_headless reason; dev/none are\n // backend_unsupported for desktop.\n reason = descriptor.tier === \"headless\" ? \"tier_headless\" : \"backend_unsupported\";\n } else if (!ctx.desktopEnabled) {\n available = false;\n reason = \"disabled_by_policy\";\n } else if (ctx.streamTokenSecretAvailable === false) {\n // Graceful degrade (stream-token availability contract): desktop is enabled + backend-capable, but no\n // stream-token secret is resolvable, so no scoped token can be minted. The\n // deployment boots; the desktop cell reports transport:null + a typed\n // reason rather than crashing the API.\n available = false;\n reason = \"disabled_by_policy\";\n } else if (ctx.liveness !== \"warm\" && !ctx.desktopStream) {\n // A PRESENT minted pixel url (ctx.desktopStream) is ITSELF proof of liveness:\n // the box (Modal-warm OR selfhosted-online) actually served the noVNC port,\n // so a cold MODAL-GROUP lease liveness must NOT degrade it. lease_cold only\n // fires when nothing was minted. A selfhosted-active session has no warm\n // Modal lease (liveness \"cold\") yet mints a valid RELAY framebuffer cell —\n // honour it (the un-redacted-pixel ack gate below still applies).\n available = false;\n reason = \"lease_cold\";\n }\n const shared = available ? Boolean(ctx.shared) : false;\n // The minted pixel endpoint is handed out ONLY when the desktop is actually\n // available (the gates passed) AND acknowledged: an unacked/cold/degraded\n // desktop never leaks a live URL (the un-redacted-pixel consent gate). When\n // absent the cell advertises the capability with a null live address — the\n // caller mints it via POST /viewers.\n const acknowledged = available ? Boolean(ctx.desktopAcknowledged) : false;\n const minted = available && acknowledged ? ctx.desktopStream : undefined;\n // Human take-control: the cell is \"interactive\" when the desktop is actually\n // available AND the deployment's take-control policy is on (default true). The\n // box's x11vnc runs without -viewonly, so a viewer driving input reaches :0;\n // this mode bit is the CLIENT gate (the \"Take control\" affordance). A\n // deployment that wants a genuinely read-only desktop sets\n // sandboxDesktopInteractive=false → mode \"read-only\" and the client disables\n // take-control. An unavailable cell is always \"read-only\" (nothing to drive).\n // Selfhosted desktop is the RELAY framebuffer: PNG-per-frame protobuf datagrams\n // spliced over the relay, rendered by the \"frames\" canvas client — NOT noVNC/RFB\n // (that x11vnc path exists only for Modal boxes). It is VIEW-ONLY in v1 (the\n // frame client does not forward input yet), so its mode is always read-only\n // regardless of the take-control policy.\n const selfhostedFrames = ctx.backend === \"selfhosted\";\n const interactive = available && !selfhostedFrames && ctx.desktopInteractive !== false;\n const mode = interactive ? (\"interactive\" as const) : (\"read-only\" as const);\n return {\n transport: available ? (selfhostedFrames ? (\"relay-frames\" as const) : cap.transport) : null,\n client: available ? (selfhostedFrames ? (\"frames\" as const) : (\"novnc\" as const)) : null,\n mode,\n url: minted?.url ?? null,\n token: minted?.token ?? null,\n expiresAt: minted?.expiresAt ?? null,\n resolution: minted?.resolution ?? ([1024, 768] as [number, number]),\n // Desktop pixels are ALWAYS un-redacted when present (the literal\n // framebuffer); the acknowledgment gate rests on this.\n unredacted: true,\n requiresAcknowledgment: available,\n acknowledged: available ? Boolean(ctx.desktopAcknowledged) : false,\n // Shared-exposure disclosure (addendum E.1): `shared` when the group has\n // >1 session; `sharedSessionIds` is the OTHER sessions' ids ONLY (never\n // their conversation/metadata). Empty/false for a solo box or when the\n // desktop cell is unavailable.\n shared,\n sharedSessionIds: shared ? (ctx.sharedSessionIds ?? []) : [],\n reason,\n };\n })();\n\n const recording = (() => {\n const cap = descriptor.capabilities.Recording;\n if (osReason) {\n return {\n available: false,\n modes: [] as (\"manual\" | \"on-verify\")[],\n codecs: [] as (\"h264-mp4\" | \"vp9-webm\")[],\n reason: osReason,\n };\n }\n if (!cap.available) {\n return {\n available: false,\n modes: [] as (\"manual\" | \"on-verify\")[],\n codecs: [] as (\"h264-mp4\" | \"vp9-webm\")[],\n reason:\n descriptor.tier === \"headless\"\n ? (\"tier_headless\" as const)\n : (\"backend_unsupported\" as const),\n };\n }\n // Recording feasibility tracks desktop; policy-gate it the same way.\n if (!ctx.desktopEnabled) {\n return {\n available: false,\n modes: [] as (\"manual\" | \"on-verify\")[],\n codecs: [] as (\"h264-mp4\" | \"vp9-webm\")[],\n reason: \"disabled_by_policy\" as const,\n };\n }\n return {\n available: true,\n modes: [\"manual\", \"on-verify\"] as (\"manual\" | \"on-verify\")[],\n codecs: [\"h264-mp4\", \"vp9-webm\"] as (\"h264-mp4\" | \"vp9-webm\")[],\n reason: null,\n };\n })();\n\n // Compatibility cell only. New agent interaction is exposed through the\n // managed ComputerSession tool family, never this legacy capability flag.\n const computerUse = {\n available: false,\n readOnly: true,\n reason: \"disabled_by_policy\" as const,\n };\n\n return {\n sessionId: ctx.sessionId,\n backend: ctx.backend,\n os: ctx.os,\n liveness: ctx.liveness,\n leaseEpoch: ctx.leaseEpoch,\n workspaceGeneration: ctx.workspaceGeneration ?? null,\n archiveGeneration: ctx.archiveGeneration ?? null,\n archiveComplete: ctx.archiveComplete ?? false,\n viewerHeartbeatIntervalMs: 30_000,\n FileSystem: fileSystem,\n Terminal: terminal,\n Git: git,\n DesktopStream: desktop,\n Recording: recording,\n ComputerUse: computerUse,\n negotiatedAt,\n };\n}\n","/** Provider-neutral helpers for normalizing sandbox command results. */\nexport function sandboxCommandExitCode(result: unknown): number | null {\n if (typeof result === \"string\") {\n const match = result.match(/Process exited with code (-?\\d+)/);\n return match ? Number(match[1]) : null;\n }\n if (!result || typeof result !== \"object\") return null;\n const candidate = result as {\n exitCode?: unknown;\n exit_code?: unknown;\n code?: unknown;\n status?: unknown;\n };\n for (const value of [candidate.exitCode, candidate.exit_code, candidate.code, candidate.status]) {\n if (typeof value === \"number\") return value;\n }\n return null;\n}\n\nexport function sandboxCommandOutput(result: unknown): string {\n if (typeof result === \"string\") {\n const outputIndex = result.indexOf(\"Output:\");\n return outputIndex >= 0 ? result.slice(outputIndex + \"Output:\".length).trim() : result.trim();\n }\n if (!result || typeof result !== \"object\") return \"\";\n const candidate = result as { output?: unknown; stdout?: unknown; stderr?: unknown };\n return [candidate.output, candidate.stderr, candidate.stdout]\n .filter((value): value is string => typeof value === \"string\" && value.length > 0)\n .join(\"\\n\");\n}\n\n/** Return stdout exactly once for machine parsing. */\nexport function sandboxCommandStdout(result: unknown): string {\n if (typeof result === \"string\") return sandboxCommandOutput(result);\n if (!result || typeof result !== \"object\") return \"\";\n const candidate = result as { output?: unknown; stdout?: unknown };\n if (typeof candidate.stdout === \"string\" && candidate.stdout.length > 0) {\n return candidate.stdout;\n }\n return typeof candidate.output === \"string\" ? candidate.output : \"\";\n}\n\nexport function sandboxCommandStillRunning(result: unknown): boolean {\n if (typeof result === \"string\") return /Process running with session ID \\d+/u.test(result);\n if (!result || typeof result !== \"object\") return false;\n const candidate = result as { sessionId?: unknown; session_id?: unknown };\n return typeof candidate.sessionId === \"number\" || typeof candidate.session_id === \"number\";\n}\n","const RUN_STATE_SANDBOX_PROVIDERS = new Set([\n \"blaxel\",\n \"cloudflare\",\n \"daytona\",\n \"docker\",\n \"e2b\",\n \"local\",\n \"modal\",\n \"none\",\n \"runloop\",\n \"selfhosted\",\n \"vercel\",\n]);\n\nexport type RunStateExposedPortsCompatibilityRepair = {\n provider: string;\n sessionClass: \"root\" | \"agent\";\n path:\n | \"sandbox.sessionState.exposedPorts\"\n | \"sandbox.sessionsByAgent[*].sessionState.exposedPorts\";\n};\n\nexport type RunStateExposedPortsCompatibilityResult = {\n serializedRunState: string;\n repairs: RunStateExposedPortsCompatibilityRepair[];\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * RunState owns `exposedPorts` as a port-keyed endpoint record. Provider clients\n * separately own configured/predeclared port arrays in their provider state.\n */\nexport function runStateExposedPortsRecord(value: unknown): Record<string, unknown> | undefined {\n return isRecord(value) ? structuredClone(value) : undefined;\n}\n\nexport function runStateCompatibilityProvider(value: unknown): string {\n return typeof value === \"string\" && RUN_STATE_SANDBOX_PROVIDERS.has(value) ? value : \"unknown\";\n}\n\nfunction runStateCompatibilityProviderFromEntry(\n sessionState: unknown,\n enclosingBackendId: unknown,\n): string {\n const sessionProvider = runStateCompatibilityProvider(\n isRecord(sessionState) ? sessionState.backendId : undefined,\n );\n return sessionProvider === \"unknown\"\n ? runStateCompatibilityProvider(enclosingBackendId)\n : sessionProvider;\n}\n\nfunction removeInvalidExposedPorts(\n sessionState: unknown,\n repair: RunStateExposedPortsCompatibilityRepair,\n observations: Map<string, RunStateExposedPortsCompatibilityRepair>,\n): boolean {\n if (!isRecord(sessionState) || !(\"exposedPorts\" in sessionState)) {\n return false;\n }\n if (runStateExposedPortsRecord(sessionState.exposedPorts)) {\n return false;\n }\n delete sessionState.exposedPorts;\n observations.set(`${repair.provider}:${repair.sessionClass}:${repair.path}`, repair);\n return true;\n}\n\n/**\n * Repair only the two SDK-owned RunState sandbox envelope locations. This is a\n * deterministic, path-bounded compatibility transform for historical blobs;\n * providerState (including configuredExposedPorts arrays) and every unrelated\n * RunState field remain untouched.\n */\nexport function repairSerializedRunStateExposedPorts(\n serializedRunState: string,\n): RunStateExposedPortsCompatibilityResult {\n let parsed: unknown;\n try {\n parsed = JSON.parse(serializedRunState);\n } catch {\n return { serializedRunState, repairs: [] };\n }\n if (!isRecord(parsed) || !isRecord(parsed.sandbox)) {\n return { serializedRunState, repairs: [] };\n }\n\n const sandbox = parsed.sandbox;\n const observations = new Map<string, RunStateExposedPortsCompatibilityRepair>();\n let changed = removeInvalidExposedPorts(\n sandbox.sessionState,\n {\n provider: runStateCompatibilityProviderFromEntry(sandbox.sessionState, sandbox.backendId),\n sessionClass: \"root\",\n path: \"sandbox.sessionState.exposedPorts\",\n },\n observations,\n );\n\n if (isRecord(sandbox.sessionsByAgent)) {\n for (const entry of Object.values(sandbox.sessionsByAgent)) {\n if (!isRecord(entry)) continue;\n changed =\n removeInvalidExposedPorts(\n entry.sessionState,\n {\n provider: runStateCompatibilityProviderFromEntry(entry.sessionState, entry.backendId),\n sessionClass: \"agent\",\n path: \"sandbox.sessionsByAgent[*].sessionState.exposedPorts\",\n },\n observations,\n ) || changed;\n }\n }\n\n return changed\n ? { serializedRunState: JSON.stringify(parsed), repairs: [...observations.values()] }\n : { serializedRunState, repairs: [] };\n}\n","import { isModalTaskExecStartPreDispatchUnavailableError } from \"./providers/modal\";\n\n/** The function tool whose one invocation starts exactly one sandbox command. */\nexport const COMMAND_START_TOOL_NAME = \"exec_command\";\n\nconst MAX_DEPTH = 8;\nconst MAX_NODES = 64;\n\n/**\n * Call-scoped proof that one `exec_command` invocation never dispatched its\n * command. Only the runtime's own invocation wrapper creates it, and only around\n * the provider's typed pre-dispatch readiness proof, so the worker can settle\n * exactly this call as not started instead of unknown.\n */\nexport class ToolCallCommandNotStartedError extends Error {\n readonly callId: string;\n\n constructor(callId: string, cause: unknown) {\n super(\"The sandbox command was not started\", { cause });\n this.name = \"ToolCallCommandNotStartedError\";\n this.callId = callId;\n }\n}\n\ntype InvokableTool = {\n type: string;\n name: string;\n invoke?: (context: never, input: string, details?: never) => Promise<unknown>;\n};\n\n/**\n * Wrap `exec_command` so a proven pre-dispatch command-start failure carries\n * the exact call it belongs to. Every other outcome, including a rendered\n * error string or an ambiguous start, passes through unchanged.\n */\nexport function withCommandNotStartedCallProof<T extends InvokableTool>(tool: T): T {\n if (tool.type !== \"function\" || tool.name !== COMMAND_START_TOOL_NAME || !tool.invoke) {\n return tool;\n }\n const invoke = tool.invoke;\n return {\n ...tool,\n invoke: async (context: never, input: string, details?: never) => {\n try {\n return await invoke(context, input, details);\n } catch (error) {\n const callId = (details as { toolCall?: { callId?: unknown } } | undefined)?.toolCall\n ?.callId;\n if (\n typeof callId === \"string\" &&\n callId.length > 0 &&\n isModalTaskExecStartPreDispatchUnavailableError(error)\n ) {\n throw new ToolCallCommandNotStartedError(callId, error);\n }\n throw error;\n }\n },\n };\n}\n\n/**\n * The call ids an error proves were never started. The whole error must still\n * satisfy the pre-dispatch proof: any retained or outcome-unknown boundary in\n * the same chain vetoes every call, and lookalike names never qualify.\n */\nexport function toolCallCommandNotStartedCallIds(error: unknown): string[] {\n if (!isModalTaskExecStartPreDispatchUnavailableError(error)) return [];\n const callIds = new Set<string>();\n const pending: Array<{ depth: number; value: unknown }> = [{ depth: 0, value: error }];\n const seen = new WeakSet<object>();\n let inspected = 0;\n while (pending.length > 0 && inspected < MAX_NODES) {\n const current = pending.shift()!;\n inspected += 1;\n if (!current.value || typeof current.value !== \"object\" || seen.has(current.value)) continue;\n if (current.depth > MAX_DEPTH) continue;\n seen.add(current.value);\n if (current.value instanceof ToolCallCommandNotStartedError) {\n if (isModalTaskExecStartPreDispatchUnavailableError(current.value.cause)) {\n callIds.add(current.value.callId);\n }\n continue;\n }\n const record = current.value as Record<string, unknown>;\n for (const key of [\"cause\", \"error\"] as const) {\n const descriptor = Object.getOwnPropertyDescriptor(record, key);\n if (descriptor && \"value\" in descriptor) {\n pending.push({ depth: current.depth + 1, value: descriptor.value });\n }\n }\n const errors = Object.getOwnPropertyDescriptor(record, \"errors\");\n if (errors && \"value\" in errors && Array.isArray(errors.value)) {\n for (const nested of errors.value.slice(0, 32)) {\n pending.push({ depth: current.depth + 1, value: nested });\n }\n }\n }\n return [...callIds];\n}\n","import { createHash } from \"node:crypto\";\nimport { types } from \"node:util\";\nimport { z } from \"zod\";\nimport { canonicalModalCheckpointProviderBinding } from \"@opengeni/contracts\";\n\nconst uuid = z.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u);\nconst empty = z.object({}).strict();\nconst binding = z\n .object({\n version: z.literal(1),\n serverUrl: z.string().max(2048),\n workspaceName: z.string().min(1).max(200),\n environment: z.string().max(200),\n })\n .strict();\nconst blueprint = z\n .object({\n version: z.literal(1),\n adapterId: z.literal(\"modal-native-fresh-creator-reservation-v1\"),\n create: z\n .object({\n operationId: uuid,\n appId: z.string().regex(/^ap-[A-Za-z0-9_-]{1,200}$/u),\n imageId: z.string().regex(/^im-[A-Za-z0-9_-]{1,200}$/u),\n cpu: z\n .number()\n .positive()\n .max(128)\n .refine((value) => {\n const milli = Math.trunc(1000 * value);\n return Number.isSafeInteger(milli) && milli >= 1 && milli / 1000 === value;\n }),\n memoryMiB: z.number().int().safe().min(128).max(1_048_576),\n timeoutSeconds: z.number().int().safe().min(1).max(86_400),\n env: empty,\n mounts: z.tuple([]),\n })\n .strict(),\n restore: z.null(),\n readiness: z\n .object({\n operationId: uuid,\n execId: uuid,\n commandArgs: z.tuple([z.literal(\"/bin/true\")]),\n workdir: z.literal(\"/tmp\"),\n env: empty,\n })\n .strict(),\n publishOperationId: uuid,\n cleanup: z\n .object({ operationId: uuid, requires: z.literal(\"physical-terminal-proof\") })\n .strict(),\n })\n .strict();\n\n/** A new wrapper around the unchanged reservation vocabulary. These additional\n * fields MUST NOT be passed as extra keys to the reservation-v1 DB API. */\nconst specSchema = z\n .object({\n version: z.literal(1),\n recipeId: z.literal(\"modal-native-fresh-v1\"),\n recipeRevision: z.literal(1),\n createWorkdir: z.literal(\"/tmp\"),\n entrypoint: z.tuple([z.literal(\"sleep\"), z.literal(\"infinity\")]),\n origin: z\n .object({\n version: z.literal(1),\n planId: uuid,\n creatorId: uuid,\n accountId: uuid,\n workspaceId: uuid,\n sessionId: uuid,\n turnId: uuid,\n attemptId: uuid,\n executionGeneration: z.number().int().positive().safe(),\n triggerEventId: uuid,\n sandboxGroupId: uuid,\n routeKind: z.literal(\"home\"),\n routeTargetId: z.null(),\n routeEpoch: z.number().int().nonnegative().safe(),\n providerBindingKey: z.string().min(1).max(4096),\n providerBinding: binding,\n })\n .strict(),\n blueprint,\n })\n .strict();\nexport type NativeFreshCreateSpec = z.infer<typeof specSchema>;\n\ntype Immutable<T> = T extends readonly unknown[]\n ? { readonly [K in keyof T]: Immutable<T[K]> }\n : T extends object\n ? { readonly [K in keyof T]: Immutable<T[K]> }\n : T;\n\nconst normalization = {\n recipeId: \"modal-native-fresh-v1\",\n recipeRevision: 1,\n schema: \"modal.client.ModalClient/SandboxCreate\",\n encoding: \"modal-create-json-v1\",\n sdkVersion: \"0.9.0\",\n // Reviewed installed source; this is a pinned normalization fingerprint,\n // not a runtime file read or an attestation of transmitted protobuf bytes.\n sdkSourceSha256: \"bb830ded1925e1d927d1fc221b2329d961f9a57eafdd9a85bf13fb7cfc982599\",\n entrypoint: [\"sleep\", \"infinity\"],\n createWorkdir: \"/tmp\",\n env: {},\n mounts: [],\n restore: null,\n idleTimeout: \"unset\",\n gpu: \"unset\",\n gpuProto: { type: 0, count: 0, gpuType: \"\" },\n cpuLimit: \"unset\",\n memoryLimit: \"unset\",\n pty: \"unset\",\n regions: \"unset\",\n proxy: \"unset\",\n readinessProbe: \"unset\",\n environmentVariables: \"unset\",\n network: {\n access: \"OPEN\",\n outboundCidrs: [],\n outboundDomains: [],\n inboundCidrs: [],\n i6pn: false,\n },\n volumes: [],\n cloudBucketMounts: [],\n secrets: [],\n ports: [],\n cloud: \"\",\n verbose: false,\n includeOidcIdentityToken: false,\n experimentalOptions: {},\n experimentalOptionsV2: {},\n customDomain: \"\",\n} as const;\nconst sha256 = (value: string) => createHash(\"sha256\").update(value).digest(\"hex\");\nconst compilerFingerprint = sha256(JSON.stringify(normalization));\n\nfunction freeze<T>(value: T): Immutable<T> {\n if (value !== null && typeof value === \"object\") {\n for (const child of Object.values(value)) freeze(child);\n Object.freeze(value);\n }\n return value as Immutable<T>;\n}\nfreeze(normalization);\n\n/** Inspect descriptors before parsing/cloning: no getter, callback, class,\n * sparse array, hidden key or non-JSON input may provide a specification. */\nfunction ownData(value: unknown, depth = 0): void {\n if (depth > 12) throw new Error(\"Unsupported native fresh-create specification\");\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return;\n if (typeof value === \"number\") {\n if (Number.isFinite(value) && !Object.is(value, -0)) return;\n throw new Error(\"Unsupported native fresh-create specification\");\n }\n // Native detection must precede reflection, including for revoked Proxies.\n if (typeof value !== \"object\" || types.isProxy(value))\n throw new Error(\"Unsupported native fresh-create specification\");\n const array = Array.isArray(value);\n const prototype = Object.getPrototypeOf(value);\n if (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null)\n throw new Error(\"Unsupported native fresh-create specification\");\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const keys = Reflect.ownKeys(descriptors).filter((key) => !(array && key === \"length\"));\n if (array && keys.length !== (value as unknown[]).length)\n throw new Error(\"Unsupported native fresh-create specification\");\n for (const key of keys) {\n if (typeof key !== \"string\" || (array && !/^(0|[1-9][0-9]*)$/u.test(key)))\n throw new Error(\"Unsupported native fresh-create specification\");\n const descriptor = descriptors[key]!;\n if (!descriptor.enumerable || !(\"value\" in descriptor))\n throw new Error(\"Unsupported native fresh-create specification\");\n ownData(descriptor.value, depth + 1);\n }\n}\n\n/** Modal 0.9.0 buildSandboxCreateRequestProto + generated fromPartial defaults,\n * followed by the atomic name/tag injection of modal-create-boundary. Property\n * order and intentionally undefined fields are part of this JSON correlation\n * recipe. Pinned-SDK parity tests, not generic SDK reentry, guard this mirror. */\nfunction normalizedRequest(spec: NativeFreshCreateSpec) {\n const create = spec.blueprint.create;\n return {\n appId: create.appId,\n definition: {\n entrypointArgs: [...spec.entrypoint],\n mountIds: [],\n imageId: create.imageId,\n secretIds: [],\n resources: {\n memoryMb: create.memoryMiB,\n milliCpu: Math.trunc(1000 * create.cpu),\n gpuConfig: { type: 0, count: 0, gpuType: \"\" },\n memoryMbMax: 0,\n ephemeralDiskMb: 0,\n milliCpuMax: 0,\n rdma: false,\n },\n cloudProvider: 0,\n timeoutSecs: (create.timeoutSeconds * 1000) / 1000,\n workdir: spec.createWorkdir,\n nfsMounts: [],\n runtimeDebug: false,\n blockNetwork: false,\n s3Mounts: [],\n cloudBucketMounts: [],\n volumeMounts: [],\n ptyInfo: undefined,\n schedulerPlacement: undefined,\n workerId: \"\",\n openPorts: { ports: [] },\n i6pnEnabled: false,\n networkAccess: { networkAccessType: 1, allowedCidrs: [], allowedDomains: [] },\n proxyId: undefined,\n enableSnapshot: false,\n snapshotVersion: undefined,\n cloudProviderStr: \"\",\n runscRuntimeVersion: undefined,\n runtime: undefined,\n verbose: false,\n name: `opengeni-create-${create.operationId}`,\n experimentalOptions: {},\n experimentalOptionsV2: {},\n preloadPathPrefixes: [],\n idleTimeoutSecs: undefined,\n directSandboxCommandsEnabled: false,\n RestoreInstanceType: \"\",\n customDomain: \"\",\n includeOidcIdentityToken: false,\n readinessProbe: undefined,\n inboundCidrAllowlist: [],\n environmentVariables: undefined,\n },\n environmentName: \"\",\n tags: [{ tagName: \"opengeni_provider_create_operation_id\", tagValue: create.operationId }],\n };\n}\n\nexport type NativeFreshCreateCompilation = Immutable<{\n version: 1;\n recipeId: \"modal-native-fresh-v1\";\n recipeRevision: 1;\n compilerFingerprint: string;\n normalization: typeof normalization;\n spec: NativeFreshCreateSpec;\n normalizedRequest: ReturnType<typeof normalizedRequest>;\n requestJson: string;\n request: {\n encoding: \"modal-create-json-v1\";\n sha256: string;\n byteLength: number;\n encoderFingerprint: string;\n };\n}>;\n\n/** Opaque local compilation handle. It is correlation data, never an accepted\n * operation, authenticated principal, reservation or fresh dispatch grant. */\nexport type NativeFreshCreatePreparation = Readonly<object>;\nconst prepared = new WeakMap<object, NativeFreshCreateCompilation>();\n\n/** Synchronous, credentials-free and zero provider/DB/config I/O. Requires all\n * IDs and the complete known fresh recipe before election. Never creates IDs,\n * resolves apps/images, invokes SDK helpers or consumes dispatch authority. */\nexport function compileNativeFreshCreate(\n input: NativeFreshCreateSpec,\n): NativeFreshCreatePreparation {\n try {\n ownData(input);\n const copied: unknown = structuredClone(input);\n if (Buffer.byteLength(JSON.stringify(copied)) > 32_768)\n throw new Error(\"Unsupported native fresh-create specification\");\n const spec = specSchema.parse(copied);\n const { origin, blueprint: plan } = spec;\n const canonical = canonicalModalCheckpointProviderBinding(origin.providerBinding);\n const serverUrl = new URL(origin.providerBinding.serverUrl);\n if (\n !canonical ||\n canonical.key !== origin.providerBindingKey ||\n ([\"serverUrl\", \"workspaceName\", \"environment\"] as const).some(\n (field) => canonical.binding[field] !== origin.providerBinding[field],\n ) ||\n ![\"https:\", \"http:\"].includes(serverUrl.protocol) ||\n serverUrl.username ||\n serverUrl.password ||\n serverUrl.search ||\n serverUrl.hash ||\n origin.creatorId === origin.attemptId\n )\n throw new Error(\"Unsupported native fresh-create specification\");\n const ids = [\n origin.planId,\n origin.creatorId,\n plan.create.operationId,\n plan.readiness.operationId,\n plan.readiness.execId,\n plan.publishOperationId,\n plan.cleanup.operationId,\n ];\n if (new Set(ids).size !== 7) throw new Error(\"Unsupported native fresh-create specification\");\n const request = normalizedRequest(spec);\n const requestJson = JSON.stringify(request);\n const compilation: NativeFreshCreateCompilation = freeze({\n version: 1,\n recipeId: \"modal-native-fresh-v1\",\n recipeRevision: 1,\n compilerFingerprint,\n normalization,\n spec,\n normalizedRequest: request,\n requestJson,\n request: {\n encoding: \"modal-create-json-v1\",\n sha256: sha256(requestJson),\n byteLength: Buffer.byteLength(requestJson),\n encoderFingerprint: compilerFingerprint,\n },\n });\n const handle = Object.freeze({});\n prepared.set(handle, compilation);\n return handle;\n } catch {\n // Do not echo arbitrary input, provider tokens or schema diagnostics.\n throw new Error(\"Unsupported native fresh-create specification\");\n }\n}\n\n/** Authenticates ONLY local compiler issuance. The full frozen record contains\n * no credential/JWT, grant, DB receipt or transmitted-byte attestation. */\nexport function describeNativeFreshCreate(\n handle: NativeFreshCreatePreparation,\n): NativeFreshCreateCompilation {\n const compilation = prepared.get(handle);\n if (!compilation) throw new Error(\"Unknown native fresh-create preparation\");\n return compilation;\n}\n","// @opengeni/runtime/sandbox — the desktop display-stack launcher (P4.1).\n//\n// The agent-loop-free home for `ensureDisplayStack`: the exec-launched,\n// flock-idempotent procedure that brings up the Channel-B pixel stack\n// (Xvfb :0 -> XFCE -> x11vnc -> websockify:6080 -> noVNC) on a live,\n// externally-owned box. It is driven over the box's `exec`/`execCommand` channel\n// (NOT a container CMD) so it re-establishes after a snapshot rollover / box\n// re-election, and it is safe to call from the API on a viewer op OR from the\n// agent turn — a second concurrent call serializes on the in-box flock and\n// no-ops when the stack is already up.\n//\n// It lives under @opengeni/runtime/sandbox so the API-direct control plane\n// (apps/api) and the worker (apps/worker) both pull it from the same single\n// agent-loop-free leaf.\n//\n// Productionized from the PROVEN spike (spikes/desktop-stack PASSED locally:\n// noVNC 200, WS 101 + RFB banner, OCR'd a secret off the framebuffer) + the\n// gVisor harness (V2 PASSED live on Modal: XTEST input read-back under runsc).\n\nimport {\n DESKTOP_STREAM_PORT,\n LEGACY_SANDBOX_PROVIDER_INSTANCE_ID_FIELDS,\n OPENGENI_SANDBOX_PROVIDER_INSTANCE_ID_FIELD,\n} from \"@opengeni/contracts\";\nimport { parseExecResponseBanner } from \"./exec-banner\";\n\n// Re-export under the canonical name the module spec uses (STREAM_PORT) while\n// keeping DESKTOP_STREAM_PORT as the single source of truth (contracts).\nexport { DESKTOP_STREAM_PORT };\nexport const STREAM_PORT = DESKTOP_STREAM_PORT;\n\n// The whole-stack launch is bounded by the readiness gates inside the up-script\n// (four loops of 50 * 0.1s = ~5s each, ~20s worst case) PLUS the PAINTABLE-FRAME\n// gate we append (up to ~30s of scrot probing) PLUS first-boot XFCE/dbus + font-cache\n// warm-up on a cold gVisor box. 90s gives headroom over the spike's observed ~5-10s\n// warm path AND the cold-box paint warm-up without masking a genuine wedge.\nexport const DISPLAY_STACK_TIMEOUT_MS = 90_000;\n\n// Provider exec APIs use `yieldTimeMs` as an output-yield window, not a process\n// deadline. Poll often enough to surface stage telemetry while the command keeps\n// running, but let the in-box `timeout(1)` own termination (see\n// `boundedDisplayStackCommand`).\nconst DISPLAY_STACK_PROVIDER_YIELD_MS = 15_000;\nconst DISPLAY_STACK_PROVIDER_POLL_MS = 5_000;\nconst DISPLAY_STACK_TERMINATION_GRACE_MS = 5_000;\n// Provider cancellation is transport-level and may never settle. Keep the\n// JavaScript-side cleanup/drain bounded as well; a later caller either gets a\n// positive in-box quiescence proof or remains fail-closed, but it must never\n// wait forever on a provider promise.\nconst DISPLAY_STACK_CLEANUP_CALL_MS = 250;\nconst DISPLAY_STACK_DRAIN_GRACE_MS = 100;\n\n// PAINTABLE-FRAME gate: poll scrot up to this many times, this many seconds apart,\n// waiting for an actually-PAINTED frame before declaring the stack \"up\" (~30s worst case).\nconst PAINT_PROBE_ATTEMPTS = 150;\nconst PAINT_PROBE_INTERVAL_S = 0.2;\n\n// The paint FLOOR (bytes): a scrot at/above this size is a real painted desktop; below\n// it, the root is still unpainted and the frame would read as \"blank\" to the model.\n//\n// WHY A SIZE FLOOR, NOT NON-EMPTINESS (the bug this fixes): the old gate only checked\n// `[ -s frame.png ]` (non-empty). But an UNPAINTED root is never zero-byte — a fresh\n// Xvfb draws either the `-retro` weave stipple or (with `-retro` dropped) solid black,\n// and scrot happily encodes that as a small-but-non-empty PNG. So the old gate passed\n// the instant the VNC ports bound — MEASURED at ~1.4s (fast runc host) to several\n// seconds (cold gVisor) BEFORE xfdesktop finishes its first wallpaper paint — handing\n// the model the pre-paint frame. That pre-paint frame is exactly the \"blank/black\"\n// screenshot that 400s the model and blanks the human viewer.\n//\n// The sizes are unambiguous and were measured on the canonical desktop image (1280x800)\n// under runc — both the current staging image and a fresh local build:\n// painted XFCE desktop (blue-gradient wallpaper + panel + icons): ~210-222 KB\n// `-retro` stipple root (unpainted, current image): ~17 KB\n// solid-black root (unpainted, after we drop `-retro`): ~13.5 KB\n// 60 KB sits ~3.5x above every unpainted state and ~3.5x below a real paint — a wide,\n// unambiguous margin. It holds against BOTH the currently-deployed `-retro` image and\n// the `-retro`-dropped image this change ships, so the runtime gate is correct before\n// AND after the image rebuild lands. (Assumes the default ~1280x800 geometry; a larger\n// framebuffer only scales the painted frame further above the floor.)\nconst PAINT_MIN_BYTES = 60_000;\n\n// SETTLE gate (the gVisor staged-paint fix): crossing the 60 KB floor is necessary but\n// NOT sufficient. On a fast runc host the paint is atomic (black 13.5 KB -> full 209 KB\n// in one step, panel + icons included). On a STONE-COLD gVisor Modal box it is STAGED:\n// the wallpaper gradient paints and crosses 60 KB a beat BEFORE xfdesktop draws the\n// panel / launcher icons / logo. A screenshot in that window shows a bare teal wallpaper\n// with no panel — which the model correctly reports as \"graphical, but the desktop\n// hasn't fully loaded\" (VERIFIED live on staging: a cold-box turn's first agent\n// screenshot caught exactly this). So the gate additionally waits for the frame to\n// SETTLE: two consecutive probes both above the floor whose byte-sizes agree within\n// PAINT_SETTLE_DELTA_BYTES. A still-painting desktop grows between probes; a fully\n// rendered, static one is byte-stable (scrot -o omits the cursor, and the clock is\n// minute-precision, so consecutive captures of a settled desktop are near-identical).\n// This makes ensureDisplayStack block until the FULL desktop is up, so the turn's first\n// screenshot — which runs AFTER this gate — sees the panel, not a bare wallpaper.\nconst PAINT_SETTLE_DELTA_BYTES = 2_000;\n\n/** Desktop geometry for the framebuffer. v1 has no live RANDR: a resolution\n * change is a full down -> up restart (a separate op). */\nexport type DesktopGeometry = {\n width: number; // default 1280\n height: number; // default 800\n dpi: number; // default 96\n};\n\nexport const DEFAULT_DESKTOP_GEOMETRY: DesktopGeometry = { width: 1280, height: 800, dpi: 96 };\n\n/** Thrown when a stage of the launch script failed. exitCode 11/12/13 map to\n * Xvfb / x11vnc / websockify respectively (the stage that died); 14 is the\n * PAINTABLE-FRAME gate (ports listening but scrot still yields an empty frame —\n * the display is up but not actually painting). Degradation is surfaced as a\n * value to viewers by the caller; this error is for diagnostics. */\nexport class DisplayStackError extends Error {\n readonly exitCode: number;\n readonly stage: \"xvfb\" | \"x11vnc\" | \"websockify\" | \"paint\" | \"lock\" | \"timeout\" | \"unknown\";\n\n constructor(exitCode: number, output: string) {\n const stage =\n exitCode === 11\n ? \"xvfb\"\n : exitCode === 12\n ? \"x11vnc\"\n : exitCode === 13\n ? \"websockify\"\n : exitCode === 14\n ? \"paint\"\n : exitCode === 15\n ? \"lock\"\n : exitCode === 124 || /OPENGENI_DISPLAY_TIMEOUT/u.test(output)\n ? \"timeout\"\n : \"unknown\";\n super(\n `desktop display stack failed at stage \"${stage}\" (exit ${exitCode})${output ? `:\\n${output}` : \"\"}`,\n );\n this.name = \"DisplayStackError\";\n this.exitCode = exitCode;\n this.stage = stage;\n }\n}\n\n/** Thrown when the provider session cannot run commands (a headless-only\n * backend with neither `exec` nor `execCommand`). The desktop tier degrades to\n * Channel-A-only — the caller maps this to `DesktopStream.transport: null`. */\nexport class DisplayStackUnsupportedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DisplayStackUnsupportedError\";\n }\n}\n\n// The structural slice of a provider session we need: run a command (preferring\n// `exec` for the structured exit code, falling back to `execCommand`).\ntype ExecResultLike = {\n output?: string;\n stdout?: string;\n stderr?: string;\n exitCode?: number | null;\n sessionId?: number;\n session_id?: number;\n};\ntype ExecCapableSession = {\n state?: unknown;\n exec?: (args: {\n cmd: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n signal?: AbortSignal;\n }) => Promise<ExecResultLike>;\n execCommand?: (args: {\n cmd: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n signal?: AbortSignal;\n }) => Promise<string>;\n writeStdin?: (args: {\n sessionId: number;\n chars: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n signal?: AbortSignal;\n }) => Promise<ExecResultLike | string>;\n};\n\nexport type DisplayStackCallerKind = \"viewer\" | \"computer\" | \"unknown\";\nexport type DisplayStackClassification = \"cold\" | \"already_ready\" | \"contention\" | \"unknown\";\nexport type DisplayStackTelemetryStatus = \"started\" | \"waiting\" | \"completed\" | \"failed\";\n\n/** Secret-free, bounded-cardinality stage observation. Provider/sandbox IDs are\n * log correlation fields, never metric labels. */\nexport type DisplayStackTelemetryEvent = {\n type: \"display_stack.stage\";\n requestId: string;\n stage: string;\n status: DisplayStackTelemetryStatus;\n elapsedMs: number;\n source: \"host\" | \"sandbox\";\n classification: DisplayStackClassification;\n callerKind: DisplayStackCallerKind;\n sandboxId?: string;\n leaseEpoch?: number;\n providerSessionId?: number;\n};\n\nexport type DisplayStackTelemetryContext = {\n callerKind: DisplayStackCallerKind;\n sandboxId?: string;\n leaseEpoch?: number;\n};\n\nexport type EnsureDisplayStackOptions = {\n geometry?: DesktopGeometry;\n /** The exposed stream port; defaults to 6080. */\n port?: number;\n /** Whole-operation wall-clock timeout; defaults to DISPLAY_STACK_TIMEOUT_MS. */\n timeoutMs?: number;\n /** Caller correlation. Supplying it enables the default structured log sink. */\n telemetryContext?: DisplayStackTelemetryContext;\n /** Optional non-blocking telemetry sink (tests/embedders may replace logging). */\n onTelemetry?: (event: DisplayStackTelemetryEvent) => void | Promise<void>;\n};\n\nexport type EnsureDisplayStackResult = {\n /** The exposed port the stack listens on (websockify/noVNC). */\n port: number;\n geometry: DesktopGeometry;\n /** The raw `OPENGENI_DESKTOP_UP …` marker line, for diagnostics. Never\n * surfaced to viewers. */\n marker: string;\n};\n\n/**\n * Build the shell command that runs the idempotent up-script under an in-box\n * `flock`. The script is shipped in the image at /usr/local/bin/opengeni-desktop-up\n * (the canonical desktop image); we set the geometry/port env and wrap the call\n * in `flock` so two concurrent ensureDisplayStack callers (the API viewer op +\n * the agent turn, both racing after a rollover) serialize without a double\n * launch. The up-script's own per-stage PID guards make the second call a no-op.\n *\n * Exported (pure, side-effect-free) so the ensureDisplayStack unit test can\n * assert the exact command sequence without a live box.\n */\nexport function buildDisplayStackScript(options: EnsureDisplayStackOptions = {}): string {\n const geometry = options.geometry ?? DEFAULT_DESKTOP_GEOMETRY;\n const port = options.port ?? DESKTOP_STREAM_PORT;\n const env =\n `DESKTOP_W=${geometry.width} DESKTOP_H=${geometry.height} ` +\n `DESKTOP_DPI=${geometry.dpi} STREAM_PORT=${port}`;\n // FAST PRE-CHECK (lock-free) before the outer flock: if the exposed port and\n // x11vnc are ALREADY listening, the stack is up — print the marker and short-\n // circuit, so a no-op caller (the agent turn re-ensuring after a viewer attach\n // already brought the stack up) never serializes behind a lock holder and never\n // burns the 45s flock -w timeout. `nc -z` to the two loopback ports is the cheap\n // (sub-millisecond) \"already up?\" signal; on a miss we fall through to the\n // flock-wrapped up-script (which ALSO pre-checks under its own lock).\n //\n // flock -w bounds the wait so a wedged holder can't deadlock the caller; the\n // up-script itself ALSO takes the same lock (belt + braces) so this works even\n // against an older image that predates the wrapper.\n //\n // PAINTABLE-FRAME GATE (the completion criterion): the up-script's readiness gates\n // only assert that Xvfb answers xdpyinfo and that x11vnc:5900 + websockify:PORT are\n // LISTENING — NOT that the display actually PAINTS. On a stone-cold gVisor box (the\n // machine→sandbox swap-recovery turn always hits one), Xvfb answers and the VNC ports\n // bind ~1.4s (fast host) to several seconds BEFORE xfdesktop finishes its first\n // wallpaper paint. In that window a scrot yields a small UNPAINTED frame (the -retro\n // stipple or a solid-black root) — never zero-byte — which is exactly the \"blank/black\"\n // screenshot that 400s the model and blanks the human viewer. (VERIFIED locally: the\n // real xfdesktop backdrop window maps at full 1280x800 the whole time; the render is\n // never structurally broken — it is purely this pre-paint capture race.)\n //\n // We therefore chain a real scrot probe as the completion gate: after the up-script\n // reports success, poll scrot until it produces an actually-PAINTED frame — a PNG at or\n // above PAINT_MIN_BYTES, not merely NON-EMPTY (the old `[ -s ]` check passed on the\n // ~17 KB pre-paint stipple immediately; that WAS the bug) — bounded ~30s, and only THEN\n // let the command exit 0. If it never paints we exit 14 so the caller sees a typed\n // DisplayStackError(\"paint\") — an HONEST failure the worker can degrade + log, rather\n // than a false \"up\" that hands the model an unpainted image. `-ac` on Xvfb disables\n // access control so this root-side scrot reaches :0. Runs on a pre-check hit too (cheap\n // — an already-up display paints on the first probe). Lives in the runtime-built script\n // (not the baked image up-script) so it ships with the worker/api, no image rebuild —\n // and its size floor holds against the currently-deployed image too.\n const lockedLauncher =\n `ds_started=$1; fw=$2; ds_class=cold; ` +\n `ds_stage() { ds_now=$(date +%s%3N); echo \"OPENGENI_DISPLAY_STAGE stage=$1 elapsed_ms=$((ds_now-ds_started)) classification=$ds_class\"; }; ` +\n `fa=$(date +%s%3N); fd=$((fa-fw)); [ \"$fd\" -ge 50 ] && ds_class=contention; ` +\n `ds_stage outer_flock_acquired; ds_stage launcher_issued; ` +\n `env ${env} opengeni-desktop-up; urc=$?; ds_stage launcher_complete; exit \"$urc\"`;\n const bringUp =\n `if nc -z 127.0.0.1 ${port} >/dev/null 2>&1 && nc -z 127.0.0.1 5900 >/dev/null 2>&1; then ` +\n `ds_class=already_ready; ds_stage precheck_ready; ` +\n `echo \"OPENGENI_DESKTOP_UP port=${port} geometry=${geometry.width}x${geometry.height} dpi=${geometry.dpi} (precheck)\"; ` +\n `else ` +\n `ds_class=cold; ds_stage precheck_miss; ` +\n `mkdir -p /tmp/opengeni-desktop; ` +\n `ds_stage outer_flock_wait; fw=$(date +%s%3N); ` +\n // Command-mode flock is the supervisor: it retains the lock until the launcher\n // exits, while --close prevents Xvfb/XFCE/x11vnc/websockify from inheriting the\n // lock descriptor when the launcher intentionally detaches them.\n `flock --close --conflict-exit-code 75 --wait 45 /tmp/opengeni-desktop/up.outer.lock ` +\n `bash -c ${shellQuote(lockedLauncher)} _ \"$ds_started\" \"$fw\"; frc=$?; ` +\n `if [ \"$frc\" -eq 75 ]; then ds_stage outer_flock_timeout; echo \"OPENGENI_DESKTOP_LOCK_TIMEOUT\"; exit 15; fi; ` +\n `if [ \"$frc\" -ne 0 ]; then exit \"$frc\"; fi; ` +\n `fi`;\n // A fresh /workspace HOME has no xfce4-desktop xfconf. xfdesktop then keeps a\n // 10x10 manager window and never maps the 1280x800 Desktop child, so scrot\n // stays ~21 KB (panel on black) and this gate fails forever. Seed the\n // canonical xfce-blue.jpg backdrop (measured ~365 KB scrot) and start\n // xfdesktop when the session autostart did not. $mon/$candidate/$WALL are\n // shell — no ${} braces.\n const paintSeed =\n `ds_stage paint_backdrop_seed; ` +\n `WALL=\"\"; ` +\n `for candidate in /usr/share/backgrounds/xfce/xfce-blue.jpg /usr/share/backgrounds/xfce/*.jpg /usr/share/backgrounds/xfce/*.png; do ` +\n `[ -f \"$candidate\" ] && WALL=\"$candidate\" && break; ` +\n `done; ` +\n `if [ -n \"$WALL\" ] && command -v xfconf-query >/dev/null 2>&1; then ` +\n `for mon in monitor0 monitor1 monitorscreen monitorScreen monitorXvfb; do ` +\n `xfconf-query -c xfce4-desktop -p /backdrop/screen0/$mon/workspace0/last-image --create -t string -s \"$WALL\" >/dev/null 2>&1 || true; ` +\n `xfconf-query -c xfce4-desktop -p /backdrop/screen0/$mon/workspace0/image-style --create -t int -s 5 >/dev/null 2>&1 || true; ` +\n `done; ` +\n `fi; ` +\n `if command -v xfdesktop >/dev/null 2>&1 && ! pgrep -x xfdesktop >/dev/null 2>&1; then ` +\n `DISPLAY=:0 xfdesktop --disable-wm-check >/tmp/opengeni-desktop/xfdesktop.log 2>&1 & ` +\n `fi; `;\n const paintProbe =\n `${paintSeed}` +\n `ds_stage paint_probe_started; p=/tmp/opengeni-desktop/paint-probe.png; prev=0; ` +\n `for i in $(seq 1 ${PAINT_PROBE_ATTEMPTS}); do ` +\n // Capture, then measure the PNG byte-size. `wc -c < \"$p\"` yields a bare integer; a\n // failed scrot leaves sz=0. A frame at/above PAINT_MIN_BYTES is a real painted desktop.\n `if DISPLAY=:0 scrot -o \"$p\" >/dev/null 2>&1; then sz=$(wc -c < \"$p\" 2>/dev/null || echo 0); else sz=0; fi; ` +\n `rm -f \"$p\"; ` +\n // SETTLE: accept only when THIS probe AND the PREVIOUS one are both above the floor\n // and their sizes agree within PAINT_SETTLE_DELTA_BYTES — i.e., the paint has stopped\n // growing (the full desktop, panel + icons included, is up), not merely crossed the\n // floor mid-paint on a staged gVisor boot. ($sz/$prev/$d are bare shell — no ${}\n // braces — so JS leaves them for bash; ${PAINT_*} ARE JS constants and interpolate.)\n `if [ \"$sz\" -ge ${PAINT_MIN_BYTES} ] && [ \"$prev\" -ge ${PAINT_MIN_BYTES} ]; then d=$((sz-prev)); [ \"$d\" -lt 0 ] && d=$((0-d)); if [ \"$d\" -le ${PAINT_SETTLE_DELTA_BYTES} ]; then ds_stage paint_ready; break; fi; fi; ` +\n `prev=$sz; ` +\n // NOTE: NOT_PAINTING goes to STDOUT (not stderr): Modal is execCommand-only, so the\n // caller infers the outcome by string-matching the output — stdout is always captured.\n `if [ \"$i\" = \"${PAINT_PROBE_ATTEMPTS}\" ]; then ds_stage paint_failed; echo \"OPENGENI_DESKTOP_NOT_PAINTING scrot below ${PAINT_MIN_BYTES}B or unsettled after warmup (last=$sz)\"; exit 14; fi; ` +\n `sleep ${PAINT_PROBE_INTERVAL_S}; ` +\n `done`;\n const trace =\n `ds_started=$(date +%s%3N); ds_class=unknown; ` +\n `ds_stage() { ds_now=$(date +%s%3N); echo \"OPENGENI_DISPLAY_STAGE stage=$1 elapsed_ms=$((ds_now-ds_started)) classification=$ds_class\"; }; ` +\n `ds_stage script_entry`;\n return `${trace}; mkdir -p /tmp/opengeni-desktop; { ${bringUp} ; } && { ${paintProbe} ; }`;\n}\n\nfunction execResultOutput(result: ExecResultLike | string): string {\n if (typeof result === \"string\") {\n return result;\n }\n return [result.output, result.stderr, result.stdout]\n .filter((v): v is string => typeof v === \"string\" && v.length > 0)\n .join(\"\\n\");\n}\n\nfunction execResultExitCode(result: ExecResultLike | string): number | null {\n if (typeof result === \"string\") {\n const banner = parseExecResponseBanner(result);\n if (banner.kind === \"exited\") return banner.exitCode;\n // A malformed/truncated SDK response must not fall through to command-body\n // marker inference, because its real terminal status is unknowable.\n return banner.kind === \"invalid\" ? -1 : null;\n }\n return typeof result.exitCode === \"number\" ? result.exitCode : null;\n}\n\nfunction execResultSessionId(result: ExecResultLike | string): number | null {\n if (typeof result === \"string\") {\n const banner = parseExecResponseBanner(result);\n return banner.kind === \"running\" ? banner.sessionId : null;\n }\n const value = result.sessionId ?? result.session_id;\n return typeof value === \"number\" ? value : null;\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n\n/** The provider yield is not a deadline. Bound the actual lock-owning process in\n * the box, leaving time for TERM/KILL cleanup and the final exit result to reach\n * the caller before the outer JavaScript deadline. */\nfunction boundedDisplayStackCommand(\n command: string,\n timeoutMs: number,\n markerPath: string,\n markerToken: string,\n): string {\n const graceMs = Math.min(\n DISPLAY_STACK_TERMINATION_GRACE_MS,\n Math.max(20, Math.floor(timeoutMs / 4)),\n );\n const commandTimeoutMs = Math.max(1, timeoutMs - graceMs);\n const killAfterMs = Math.max(1, Math.floor(graceMs / 2));\n const commandTimeoutSeconds = (commandTimeoutMs / 1_000).toFixed(3);\n const killAfterSeconds = (killAfterMs / 1_000).toFixed(3);\n const managedCommand =\n `marker=${shellQuote(markerPath)}; token=${shellQuote(markerToken)}; ` +\n `cancel=\"$marker.cancelled\"; ` +\n `if [ -e \"$cancel\" ]; then echo \"OPENGENI_DISPLAY_CANCELLED\"; exit 124; fi; ` +\n `pid=$$; pgid=$(ps -o pgid= -p \"$pid\" 2>/dev/null | tr -d ' '); ` +\n `start=$(awk '{print $22}' \"/proc/$pid/stat\" 2>/dev/null || true); ` +\n `printf '%s %s %s %s\\\\n' \"$pid\" \"$pgid\" \"$start\" \"$token\" >\"$marker\"; ` +\n `if [ -e \"$cancel\" ]; then rm -f \"$marker\"; echo \"OPENGENI_DISPLAY_CANCELLED\"; exit 124; fi; ` +\n // Do not install an EXIT trap: GNU timeout may terminate this supervisor\n // while descendants survive. The marker must remain for the independent\n // cleanup command to find and kill that orphaned process group.\n `bash -c ${shellQuote(command)}; rc=$?; rm -f \"$marker\"; exit \"$rc\"`;\n return (\n // Do not use timeout --foreground here. The display command contains flock\n // supervisors and launcher children; default process-group mode is required\n // so a deadline cannot leave a waiter alive to acquire the lock and launch\n // after the caller has already failed.\n `timeout --signal=TERM --kill-after=${killAfterSeconds}s ${commandTimeoutSeconds}s ` +\n `bash -c ${shellQuote(managedCommand)}; rc=$?; ` +\n // Exit 137 is also a normal SIGKILL/OOM/provider-termination result. Only\n // attach timeout attribution to the exit code that this wrapper positively\n // knows GNU timeout emitted for its own deadline. A kill-after escalation\n // may still be reported as 137, but it is not safe to infer that here.\n `if [ \"$rc\" -eq 124 ]; then ` +\n `echo \"OPENGENI_DISPLAY_TIMEOUT elapsed_ms=${commandTimeoutMs}\"; fi; exit \"$rc\"`\n );\n}\n\nclass DisplayStackWallTimeoutError extends Error {}\nclass DisplayStackOperationFencedError extends Error {}\n\ntype PendingDisplayStackCleanup = {\n markerPath: string;\n markerToken: string;\n};\n\ntype DisplayStackOperationWaiter = {\n epoch: number;\n settled: boolean;\n resolve: () => void;\n reject: (error: unknown) => void;\n timer?: ReturnType<typeof setTimeout>;\n};\n\ntype DisplayStackOperationState = {\n /** Incremented before a timed-out operation is reported to its caller. */\n epoch: number;\n /** One provider operation at a time for each physical sandbox. */\n owner: DisplayStackOperationWaiter | null;\n /** Calls that started in the current epoch but are waiting for admission. */\n waiters: DisplayStackOperationWaiter[];\n /** Raw provider calls from fenced operations; only the in-box proof gates retries. */\n inFlight: Set<Promise<unknown>>;\n /** A bounded advisory drain for provider calls that may never settle. */\n drain: Promise<void> | null;\n /** Timed-out in-box processes that still need an independent kill/verify. */\n pendingCleanup: Map<string, PendingDisplayStackCleanup>;\n /** True only after every timed-out process has a positive quiescence proof. */\n physicallyQuiescent: boolean;\n};\n\nconst stableDisplayStackOperationStates = new Map<string, DisplayStackOperationState>();\nconst stableSessionStateOperationStates = new WeakMap<object, DisplayStackOperationState>();\nconst displayStackOperationStates = new WeakMap<object, DisplayStackOperationState>();\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === \"object\" ? (value as Record<string, unknown>) : null;\n}\n\nfunction nonEmptyString(value: unknown): string | null {\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nfunction readSessionState(session: unknown): unknown {\n try {\n return asRecord(session)?.state;\n } catch {\n return undefined;\n }\n}\n\nfunction stableSandboxIdentity(\n session: unknown,\n options: EnsureDisplayStackOptions,\n): string | null {\n const explicit = nonEmptyString(options.telemetryContext?.sandboxId);\n if (explicit) return `sandbox:${explicit}`;\n\n const sessionRecord = asRecord(session);\n const state = asRecord(readSessionState(session));\n const providerState = state ? asRecord(state.providerState) : null;\n const candidates = [sessionRecord, state, providerState];\n // Use the same provider-neutral identity vocabulary as durable envelopes and\n // the reaper. This keeps display-stack serialization stable for providers\n // whose SDK identity is not named `sandboxId` (for example Runloop devboxId\n // and Blaxel sandboxName) while retaining compatibility with existing SDKs.\n const fields = [\n OPENGENI_SANDBOX_PROVIDER_INSTANCE_ID_FIELD,\n ...LEGACY_SANDBOX_PROVIDER_INSTANCE_ID_FIELDS,\n ];\n for (const candidate of candidates) {\n if (!candidate) continue;\n for (const field of fields) {\n const value = nonEmptyString(candidate[field]);\n if (value) return `sandbox:${value}`;\n }\n }\n return null;\n}\n\nfunction newOperationState(): DisplayStackOperationState {\n return {\n epoch: 0,\n owner: null,\n waiters: [],\n inFlight: new Set(),\n drain: null,\n pendingCleanup: new Map(),\n physicallyQuiescent: true,\n };\n}\n\nfunction operationState(\n session: unknown,\n options: EnsureDisplayStackOptions,\n): DisplayStackOperationState | null {\n if ((typeof session !== \"object\" || session === null) && typeof session !== \"function\") {\n return null;\n }\n const stableKey = stableSandboxIdentity(session, options);\n if (stableKey) {\n let state = stableDisplayStackOperationStates.get(stableKey);\n if (!state) {\n state = newOperationState();\n stableDisplayStackOperationStates.set(stableKey, state);\n }\n return state;\n }\n\n // Modal resumed wrappers share their provider `state` object even when the\n // wrapper instance is reconstructed. This is a useful stable fallback when\n // an older/provider-specific state shape has no named identity field.\n const providerState = readSessionState(session);\n if (providerState && (typeof providerState === \"object\" || typeof providerState === \"function\")) {\n const stateKey = providerState as object;\n let state = stableSessionStateOperationStates.get(stateKey);\n if (!state) {\n state = newOperationState();\n stableSessionStateOperationStates.set(stateKey, state);\n }\n return state;\n }\n\n const key = session as object;\n let state = displayStackOperationStates.get(key);\n if (!state) {\n state = newOperationState();\n displayStackOperationStates.set(key, state);\n }\n return state;\n}\n\nfunction settleOperationWaiter(waiter: DisplayStackOperationWaiter, error?: unknown): void {\n if (waiter.settled) return;\n waiter.settled = true;\n if (waiter.timer) clearTimeout(waiter.timer);\n if (error === undefined) waiter.resolve();\n else waiter.reject(error);\n}\n\nfunction pumpOperationWaiters(state: DisplayStackOperationState): void {\n if (state.owner) return;\n while (state.waiters.length > 0) {\n const waiter = state.waiters.shift()!;\n if (waiter.settled) continue;\n if (waiter.epoch !== state.epoch) {\n settleOperationWaiter(waiter, new DisplayStackOperationFencedError());\n continue;\n }\n state.owner = waiter;\n settleOperationWaiter(waiter);\n return;\n }\n}\n\nfunction acquireOperation(\n state: DisplayStackOperationState,\n deadline: number,\n): Promise<() => void> {\n return new Promise<() => void>((resolve, reject) => {\n const waiter: DisplayStackOperationWaiter = {\n epoch: state.epoch,\n settled: false,\n resolve: () => {\n resolve(() => {\n if (state.owner !== waiter) return;\n state.owner = null;\n pumpOperationWaiters(state);\n });\n },\n reject,\n };\n state.waiters.push(waiter);\n const remainingMs = deadline - monotonicNow();\n if (remainingMs <= 0) {\n waiter.settled = true;\n state.waiters = state.waiters.filter((candidate) => candidate !== waiter);\n reject(new DisplayStackWallTimeoutError());\n return;\n }\n waiter.timer = setTimeout(() => {\n if (waiter.settled) return;\n waiter.settled = true;\n state.waiters = state.waiters.filter((candidate) => candidate !== waiter);\n reject(new DisplayStackWallTimeoutError());\n }, remainingMs);\n waiter.timer.unref?.();\n pumpOperationWaiters(state);\n });\n}\n\nfunction invalidateQueuedOperations(state: DisplayStackOperationState, epoch: number): void {\n const retained: DisplayStackOperationWaiter[] = [];\n for (const waiter of state.waiters) {\n if (waiter.epoch === epoch)\n settleOperationWaiter(waiter, new DisplayStackOperationFencedError());\n else retained.push(waiter);\n }\n state.waiters = retained;\n}\n\nfunction monotonicNow(): number {\n return performance.now();\n}\n\nasync function waitForFencedOperation(\n state: DisplayStackOperationState,\n deadline: number,\n): Promise<boolean> {\n const drain = state.drain;\n if (!drain) return true;\n try {\n await beforeDeadline(drain, deadline);\n } catch {\n return false;\n }\n if (state.drain === drain) state.drain = null;\n return true;\n}\n\nfunction trackProviderCall<T>(\n state: DisplayStackOperationState | null,\n promise: Promise<T>,\n): Promise<T> {\n if (!state) return promise;\n state.inFlight.add(promise);\n void promise.then(\n () => state.inFlight.delete(promise),\n () => state.inFlight.delete(promise),\n );\n return promise;\n}\n\nfunction boundedProviderDrain(pending: Promise<unknown>[]): Promise<void> {\n if (pending.length === 0) return Promise.resolve();\n return new Promise<void>((resolve) => {\n let remaining = pending.length;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const finish = () => {\n if (timer) clearTimeout(timer);\n resolve();\n };\n timer = setTimeout(finish, DISPLAY_STACK_DRAIN_GRACE_MS);\n timer.unref?.();\n for (const promise of pending) {\n void promise.then(\n () => {\n remaining -= 1;\n if (remaining === 0) finish();\n },\n () => {\n remaining -= 1;\n if (remaining === 0) finish();\n },\n );\n }\n });\n}\n\nfunction fenceOperation(\n state: DisplayStackOperationState | null,\n epoch: number,\n abortController: AbortController,\n cleanup: PendingDisplayStackCleanup,\n): void {\n abortController.abort(new DisplayStackWallTimeoutError());\n if (!state) return;\n\n if (state.epoch !== epoch) return;\n\n state.pendingCleanup.set(cleanup.markerToken, cleanup);\n state.physicallyQuiescent = false;\n invalidateQueuedOperations(state, epoch);\n\n // Advance the ownership epoch BEFORE the timeout error is surfaced. Any\n // completion from this operation is now stale. A retry is gated by the\n // independent in-box cleanup proof, not by an SDK promise that may hang.\n state.epoch += 1;\n const pending = [...state.inFlight];\n const drain = boundedProviderDrain(pending);\n state.drain = state.drain ? Promise.all([state.drain, drain]).then(() => undefined) : drain;\n // A provider transport can retain an unresolved promise forever. Once the\n // bounded advisory window ends, release those promises from the registry;\n // the tombstone and in-box process-group proof remain the authoritative fence.\n void drain.then(() => {\n for (const promise of pending) state.inFlight.delete(promise);\n });\n}\n\nfunction assertCurrentOperation(state: DisplayStackOperationState | null, epoch: number): void {\n if (state && state.epoch !== epoch) throw new DisplayStackOperationFencedError();\n}\n\nasync function beforeDeadline<T>(\n promise: Promise<T>,\n deadline: number,\n now: () => number = monotonicNow,\n): Promise<T> {\n const remainingMs = deadline - now();\n if (remainingMs <= 0) throw new DisplayStackWallTimeoutError();\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<T>((_resolve, reject) => {\n timer = setTimeout(() => reject(new DisplayStackWallTimeoutError()), remainingMs);\n timer.unref?.();\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nfunction displayStackCleanupCommand(markerPath: string, markerToken: string): string {\n const marker = shellQuote(markerPath);\n const token = shellQuote(markerToken);\n // The launcher writes pid, process-group id, /proc start time, and a random\n // token before it starts the lock-owning command. The start-time check keeps\n // a stale marker from killing an unrelated process after PID reuse. The\n // process group is the authority: a provider session can disappear while\n // descendants of the shell continue to hold the display lock.\n const script =\n `marker=${marker}; token=${token}; ` +\n `cancel=\"$marker.cancelled\"; ` +\n `: >\"$cancel\" || { echo \"OPENGENI_DISPLAY_CLEANUP status=invalid\"; exit 75; }; ` +\n `if [ ! -r \"$marker\" ]; then echo \"OPENGENI_DISPLAY_CLEANUP status=stopped\"; exit 0; fi; ` +\n `read -r pid pgid start actual <\"$marker\" || { echo \"OPENGENI_DISPLAY_CLEANUP status=invalid\"; exit 75; }; ` +\n `[ \"$actual\" = \"$token\" ] || { echo \"OPENGENI_DISPLAY_CLEANUP status=invalid\"; exit 75; }; ` +\n `case \"$pid\" in ''|*[!0-9]*) echo \"OPENGENI_DISPLAY_CLEANUP status=invalid\"; exit 75;; esac; ` +\n `case \"$pgid\" in ''|*[!0-9]*) echo \"OPENGENI_DISPLAY_CLEANUP status=invalid\"; exit 75;; esac; ` +\n `case \"$start\" in ''|*[!0-9]*) echo \"OPENGENI_DISPLAY_CLEANUP status=invalid\"; exit 75;; esac; ` +\n `current=$(awk '{print $22}' \"/proc/$pid/stat\" 2>/dev/null || true); ` +\n `if [ -z \"$current\" ] || [ \"$current\" != \"$start\" ]; then rm -f \"$marker\"; echo \"OPENGENI_DISPLAY_CLEANUP status=stopped\"; exit 0; fi; ` +\n `kill -TERM -- \"-$pgid\" 2>/dev/null || true; ` +\n `for i in $(seq 1 10); do ` +\n `if ! kill -0 -- \"-$pgid\" 2>/dev/null; then rm -f \"$marker\"; echo \"OPENGENI_DISPLAY_CLEANUP status=stopped\"; exit 0; fi; ` +\n `sleep 0.05; done; ` +\n `kill -KILL -- \"-$pgid\" 2>/dev/null || true; ` +\n `for i in $(seq 1 20); do ` +\n `if ! kill -0 -- \"-$pgid\" 2>/dev/null; then rm -f \"$marker\"; echo \"OPENGENI_DISPLAY_CLEANUP status=stopped\"; exit 0; fi; ` +\n `sleep 0.05; done; ` +\n `echo \"OPENGENI_DISPLAY_CLEANUP status=alive\"; exit 75`;\n return `timeout --signal=TERM --kill-after=0.2s 1.5s bash -c ${shellQuote(script)}`;\n}\n\nasync function runProviderCommandToDeadline(\n session: ExecCapableSession,\n command: string,\n deadline: number,\n): Promise<ExecResultLike | string> {\n const controller = new AbortController();\n let result: ExecResultLike | string = await beforeDeadline(\n Promise.resolve(\n typeof session.exec === \"function\"\n ? session.exec({\n cmd: command,\n yieldTimeMs: Math.min(500, DISPLAY_STACK_CLEANUP_CALL_MS),\n maxOutputTokens: 4_000,\n signal: controller.signal,\n })\n : session.execCommand!({\n cmd: command,\n yieldTimeMs: Math.min(500, DISPLAY_STACK_CLEANUP_CALL_MS),\n maxOutputTokens: 4_000,\n signal: controller.signal,\n }),\n ),\n deadline,\n );\n\n let providerSessionId = execResultSessionId(result);\n while (providerSessionId !== null) {\n if (typeof session.writeStdin !== \"function\") {\n throw new Error(\"display cleanup provider yielded without writeStdin\");\n }\n const remainingMs = deadline - monotonicNow();\n if (remainingMs <= 1) throw new DisplayStackWallTimeoutError();\n result = await beforeDeadline(\n session.writeStdin({\n sessionId: providerSessionId,\n chars: \"\",\n yieldTimeMs: Math.max(1, Math.min(250, remainingMs - 1)),\n maxOutputTokens: 4_000,\n signal: controller.signal,\n }),\n deadline,\n );\n providerSessionId = execResultSessionId(result);\n }\n return result;\n}\n\nasync function interruptProviderProcess(\n session: ExecCapableSession,\n providerSessionId: number | null,\n deadline: number,\n): Promise<void> {\n if (providerSessionId === null || typeof session.writeStdin !== \"function\") return;\n try {\n // This is an advisory provider-level interrupt. The marker/PGID cleanup\n // below remains authoritative because the Agents SDK 0.14.3 Modal adapter ignores AbortSignal.\n await beforeDeadline(\n session.writeStdin({\n sessionId: providerSessionId,\n chars: \"\\u0003\",\n yieldTimeMs: 100,\n maxOutputTokens: 256,\n }),\n deadline,\n );\n } catch {\n // A hung provider write is not evidence either way; in-box cleanup decides.\n }\n}\n\nasync function cleanupDisplayStackProcess(\n session: ExecCapableSession,\n pending: PendingDisplayStackCleanup,\n deadline: number,\n): Promise<boolean> {\n try {\n const result = await runProviderCommandToDeadline(\n session,\n displayStackCleanupCommand(pending.markerPath, pending.markerToken),\n deadline,\n );\n const output = execResultOutput(result);\n const status = /OPENGENI_DISPLAY_CLEANUP status=(stopped|absent|alive|invalid)/u.exec(\n output,\n )?.[1];\n return status === \"stopped\";\n } catch {\n return false;\n }\n}\n\nasync function reconcilePendingCleanup(\n session: ExecCapableSession,\n state: DisplayStackOperationState,\n deadline: number,\n): Promise<boolean> {\n const entries = [...state.pendingCleanup.values()];\n if (entries.length === 0) {\n state.physicallyQuiescent = true;\n return true;\n }\n const results = await Promise.all(\n entries.map(async (pending) => ({\n pending,\n stopped: await cleanupDisplayStackProcess(session, pending, deadline),\n })),\n );\n for (const { pending, stopped } of results) {\n if (stopped) state.pendingCleanup.delete(pending.markerToken);\n }\n state.physicallyQuiescent = state.pendingCleanup.size === 0;\n return state.physicallyQuiescent;\n}\n\nfunction requestId(): string {\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction telemetryReporter(\n options: EnsureDisplayStackOptions,\n started: number,\n now: () => number = monotonicNow,\n) {\n const id = requestId();\n const context = options.telemetryContext;\n const sink =\n options.onTelemetry ??\n (context\n ? (event: DisplayStackTelemetryEvent) =>\n console.info(`[display-stack] ${JSON.stringify(event)}`)\n : undefined);\n const emittedSandboxStages = new Set<string>();\n\n const emit = (\n stage: string,\n status: DisplayStackTelemetryStatus,\n fields: {\n source?: \"host\" | \"sandbox\";\n elapsedMs?: number;\n classification?: DisplayStackClassification;\n providerSessionId?: number;\n } = {},\n ) => {\n if (!sink) return;\n const event: DisplayStackTelemetryEvent = {\n type: \"display_stack.stage\",\n requestId: id,\n stage,\n status,\n elapsedMs: fields.elapsedMs ?? now() - started,\n source: fields.source ?? \"host\",\n classification: fields.classification ?? \"unknown\",\n callerKind: context?.callerKind ?? \"unknown\",\n ...(context?.sandboxId ? { sandboxId: context.sandboxId } : {}),\n ...(context?.leaseEpoch !== undefined ? { leaseEpoch: context.leaseEpoch } : {}),\n ...(fields.providerSessionId !== undefined\n ? { providerSessionId: fields.providerSessionId }\n : {}),\n };\n try {\n void Promise.resolve(sink(event)).catch(() => undefined);\n } catch {\n // Telemetry must never affect display readiness.\n }\n };\n\n const emitSandboxStages = (output: string) => {\n for (const match of output.matchAll(\n /OPENGENI_(?:DISPLAY|DESKTOP)_STAGE stage=([a-z0-9_]+) elapsed_ms=(\\d+)(?: classification=(cold|already_ready|contention|unknown))?/gu,\n )) {\n const [line, stage, elapsed, classification] = match;\n if (!stage || !elapsed || emittedSandboxStages.has(line)) continue;\n emittedSandboxStages.add(line);\n emit(stage, \"completed\", {\n source: \"sandbox\",\n elapsedMs: Number(elapsed),\n classification: (classification as DisplayStackClassification | undefined) ?? \"unknown\",\n });\n }\n };\n\n return { emit, emitSandboxStages };\n}\n\n// Parse the exit code the up-script signals via its trailing marker. When we ran\n// through `exec` we have the real exitCode; when we only had `execCommand` (a\n// bare string), we infer success from the OPENGENI_DESKTOP_UP marker and infer\n// the failing stage from the stage-failure message the script prints to stderr.\nfunction inferExitFromOutput(output: string): number {\n if (/OPENGENI_DISPLAY_TIMEOUT/.test(output)) {\n return 124;\n }\n if (/OPENGENI_DESKTOP_LOCK_TIMEOUT/.test(output)) {\n return 15;\n }\n // Check the PAINTABLE-FRAME failure FIRST: on that path the up-script already\n // printed OPENGENI_DESKTOP_UP (bring-up succeeded) and THEN the paint gate failed,\n // so both markers are present — the NOT_PAINTING one is the authoritative outcome.\n // (Modal is execCommand-only, so this string-inference path is the live one.)\n if (/OPENGENI_DESKTOP_NOT_PAINTING/.test(output)) {\n return 14;\n }\n if (/OPENGENI_DESKTOP_UP\\b/.test(output)) {\n return 0;\n }\n if (/Xvfb failed to come up/.test(output)) {\n return 11;\n }\n if (/x11vnc failed on/.test(output)) {\n return 12;\n }\n if (/websockify failed on/.test(output)) {\n return 13;\n }\n return -1;\n}\n\n/**\n * Idempotently bring up the desktop display stack on the live box. Safe to call\n * N times (the in-box flock + the up-script's PID guards make a second call a\n * no-op). Resolves with the exposed port + geometry on success; throws\n * `DisplayStackError` on a stage failure and `DisplayStackUnsupportedError` when\n * the session cannot run commands.\n *\n * `session` is the externally-owned provider session (the `established.session`\n * from establishSandboxSessionFromEnvelope, or any SandboxSessionLike). We\n * prefer `session.exec` (structured `{exitCode}`) and fall back to\n * `session.execCommand` (bare string), inferring success from the up-script's\n * marker line in the fallback case.\n */\nexport async function ensureDisplayStack(\n session: unknown,\n options: EnsureDisplayStackOptions = {},\n): Promise<EnsureDisplayStackResult> {\n const s = session as ExecCapableSession;\n if (typeof s?.exec !== \"function\" && typeof s?.execCommand !== \"function\") {\n throw new DisplayStackUnsupportedError(\n \"provider session cannot run commands (no exec/execCommand) — desktop tier unavailable\",\n );\n }\n\n const geometry = options.geometry ?? DEFAULT_DESKTOP_GEOMETRY;\n const port = options.port ?? DESKTOP_STREAM_PORT;\n const timeoutMs = options.timeoutMs ?? DISPLAY_STACK_TIMEOUT_MS;\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new RangeError(\"ensureDisplayStack timeoutMs must be a positive finite number\");\n }\n const started = monotonicNow();\n const deadline = started + timeoutMs;\n const telemetry = telemetryReporter(options, started, monotonicNow);\n const operationToken = requestId();\n const markerPath = `/tmp/opengeni-desktop/display-stack-${operationToken}.pid`;\n const cmd = boundedDisplayStackCommand(\n buildDisplayStackScript({ geometry, port }),\n timeoutMs,\n markerPath,\n operationToken,\n );\n const outputParts: string[] = [];\n const state = operationState(session, options);\n let release: (() => void) | undefined;\n if (state) {\n try {\n release = await acquireOperation(state, deadline);\n } catch (error) {\n if (\n error instanceof DisplayStackWallTimeoutError ||\n error instanceof DisplayStackOperationFencedError\n ) {\n throw new DisplayStackError(\n 124,\n \"OPENGENI_DISPLAY_TIMEOUT display operation admission was fenced\",\n );\n }\n throw error;\n }\n }\n\n try {\n if (state && !state.physicallyQuiescent) {\n const cleanupDeadline = monotonicNow() + DISPLAY_STACK_CLEANUP_CALL_MS;\n const quiesced = await reconcilePendingCleanup(s, state, cleanupDeadline);\n if (!quiesced) {\n // Fail closed. A new session wrapper may share this physical sandbox,\n // but without a positive marker/PGID proof it must not issue overlapping\n // display work merely because the old SDK promise remains unresolved.\n throw new DisplayStackError(\n 124,\n \"OPENGENI_DISPLAY_TIMEOUT physical cleanup is still pending; retry is fenced\",\n );\n }\n }\n const epoch = state?.epoch ?? 0;\n const abortController = new AbortController();\n let activeProviderSessionId: number | null = null;\n telemetry.emit(\"request_entry\", \"started\");\n telemetry.emit(\"exec_issued\", \"started\");\n\n try {\n const initialYieldMs = Math.max(1, Math.min(DISPLAY_STACK_PROVIDER_YIELD_MS, timeoutMs - 1));\n const initialExec: Promise<ExecResultLike | string> = trackProviderCall<\n ExecResultLike | string\n >(\n state,\n Promise.resolve(\n typeof s.exec === \"function\"\n ? s.exec({\n cmd,\n yieldTimeMs: initialYieldMs,\n maxOutputTokens: 20_000,\n signal: abortController.signal,\n })\n : s.execCommand!({\n cmd,\n yieldTimeMs: initialYieldMs,\n maxOutputTokens: 20_000,\n signal: abortController.signal,\n }),\n ),\n );\n let result: ExecResultLike | string = await beforeDeadline(\n initialExec,\n deadline,\n monotonicNow,\n );\n assertCurrentOperation(state, epoch);\n let chunk = execResultOutput(result);\n outputParts.push(chunk);\n telemetry.emitSandboxStages(chunk);\n telemetry.emit(\"provider_first_result\", \"completed\");\n\n let providerSessionId = execResultSessionId(result);\n activeProviderSessionId = providerSessionId;\n while (providerSessionId !== null) {\n telemetry.emit(\"provider_yield\", \"waiting\", { providerSessionId });\n if (typeof s.writeStdin !== \"function\") {\n throw new DisplayStackError(\n -1,\n `${outputParts.join(\"\\n\")}\\nprovider yielded process ${providerSessionId} but exposes no writeStdin poll surface`,\n );\n }\n assertCurrentOperation(state, epoch);\n const remainingMs = deadline - monotonicNow();\n if (remainingMs <= 1) throw new DisplayStackWallTimeoutError();\n const pollYieldMs = Math.max(1, Math.min(DISPLAY_STACK_PROVIDER_POLL_MS, remainingMs - 1));\n result = await beforeDeadline(\n trackProviderCall(\n state,\n s.writeStdin({\n sessionId: providerSessionId,\n chars: \"\",\n yieldTimeMs: pollYieldMs,\n maxOutputTokens: 20_000,\n signal: abortController.signal,\n }),\n ),\n deadline,\n monotonicNow,\n );\n assertCurrentOperation(state, epoch);\n chunk = execResultOutput(result);\n outputParts.push(chunk);\n telemetry.emitSandboxStages(chunk);\n providerSessionId = execResultSessionId(result);\n activeProviderSessionId = providerSessionId;\n }\n\n const output = outputParts.join(\"\\n\");\n const exitCode = execResultExitCode(result) ?? inferExitFromOutput(output);\n telemetry.emit(\"process_complete\", exitCode === 0 ? \"completed\" : \"failed\");\n if (exitCode !== 0) {\n throw new DisplayStackError(exitCode, output);\n }\n\n const marker = (output.match(/OPENGENI_DESKTOP_UP[^\\n]*/) ?? [\"\"])[0];\n telemetry.emit(\"readiness_complete\", \"completed\");\n return { port, geometry, marker };\n } catch (error) {\n if (\n error instanceof DisplayStackWallTimeoutError ||\n error instanceof DisplayStackOperationFencedError\n ) {\n const pendingCleanup: PendingDisplayStackCleanup = {\n markerPath,\n markerToken: operationToken,\n };\n fenceOperation(state, epoch, abortController, pendingCleanup);\n const cleanupDeadline = monotonicNow() + DISPLAY_STACK_CLEANUP_CALL_MS;\n telemetry.emit(\"process_cleanup\", \"started\");\n await interruptProviderProcess(\n s,\n activeProviderSessionId,\n Math.min(cleanupDeadline, monotonicNow() + 50),\n );\n let quiesced = false;\n if (state) {\n quiesced = await reconcilePendingCleanup(s, state, cleanupDeadline);\n if (!quiesced) {\n await waitForFencedOperation(\n state,\n Math.min(cleanupDeadline, monotonicNow() + DISPLAY_STACK_DRAIN_GRACE_MS),\n );\n }\n } else {\n quiesced = await cleanupDisplayStackProcess(s, pendingCleanup, cleanupDeadline);\n }\n telemetry.emit(\"process_cleanup\", quiesced ? \"completed\" : \"failed\");\n const output = `${outputParts.join(\"\\n\")}\\nOPENGENI_DISPLAY_TIMEOUT wall_ms=${timeoutMs}`;\n telemetry.emit(\"wall_deadline\", \"failed\");\n throw new DisplayStackError(124, output);\n }\n telemetry.emit(\"request_failed\", \"failed\");\n throw error;\n }\n } finally {\n release?.();\n }\n}\n\n/** Tear the stack down (down-script). Best-effort; never throws on a missing\n * process. Used by the geometry-change restart and cold/drain. */\nexport async function tearDownDisplayStack(session: unknown): Promise<void> {\n const s = session as ExecCapableSession;\n if (typeof s?.exec === \"function\") {\n await s.exec({ cmd: \"opengeni-desktop-down\", yieldTimeMs: 10_000, maxOutputTokens: 4_000 });\n return;\n }\n if (typeof s?.execCommand === \"function\") {\n await s.execCommand({\n cmd: \"opengeni-desktop-down\",\n yieldTimeMs: 10_000,\n maxOutputTokens: 4_000,\n });\n }\n}\n","// @opengeni/runtime/sandbox — the REAL PTY terminal-server launcher (P5.t).\n//\n// The agent-loop-free home for `ensureTerminalServer`: the exec-launched,\n// flock-idempotent procedure that brings up the ttyd PTY-over-websocket server\n// (a live PTY-backed `bash -l` per ws client, listening on 7681) on a live,\n// externally-owned box. It is the SYMMETRIC TWIN of ensureDisplayStack (the\n// Channel-B pixel stack) — same exec/execCommand channel (NOT a container CMD)\n// so it re-establishes after a snapshot rollover / box re-election, same flock\n// idempotency so a second concurrent caller (the API viewer op + the agent turn,\n// both racing after a rollover) serializes and no-ops when ttyd is already up.\n//\n// WHY A REAL PTY OVER THE TUNNEL (not the old ptyWrite-over-HTTP): the stateless\n// HTTP plane builds a fresh provider session per call, so the in-memory live-PTY\n// process handle (Modal's per-call activeProcesses Map) is gone by the next\n// write (\"session not found: 1\"). ttyd holds the live PTY in-box and streams it\n// over the SAME Modal raw-TLS tunnel the desktop noVNC already uses, gated by the\n// SAME scoped stream-token mechanism (the server records the token; the boundary\n// is the unguessable short-TTL tunnel URL + the recorded token — no in-box gate).\n//\n// It lives under @opengeni/runtime/sandbox so the API-direct control plane\n// (apps/api) and the worker (apps/worker) both pull it from the same single\n// agent-loop-free leaf.\n\nimport { TERMINAL_STREAM_PORT } from \"@opengeni/contracts\";\n\n// Re-export the canonical terminal port so callers (exposeStreamPort, the API\n// mint) pull the single source of truth (contracts) from this leaf.\nexport { TERMINAL_STREAM_PORT };\n\n// The ttyd launch is bounded by the readiness gate inside the up-script (50 *\n// 0.1s = ~5s) PLUS first-boot warm-up on a cold gVisor box. 60s gives headroom\n// over the observed warm path (~1-2s; ttyd is a single static binary) without\n// masking a genuine wedge. Symmetric with DISPLAY_STACK_TIMEOUT_MS.\nexport const TERMINAL_SERVER_TIMEOUT_MS = 60_000;\n\n/** Thrown when the ttyd launch failed inside the box. exitCode 14 maps to the\n * up-script's \"ttyd failed to come up\" stage; any other non-zero is unknown.\n * Degradation is surfaced as a value to clients by the caller (Terminal\n * transport falls back to sse-events / null); this error is for diagnostics. */\nexport class TerminalServerError extends Error {\n readonly exitCode: number;\n readonly stage: \"ttyd\" | \"unknown\";\n\n constructor(exitCode: number, output: string) {\n const stage = exitCode === 14 ? \"ttyd\" : \"unknown\";\n super(\n `terminal server failed at stage \"${stage}\" (exit ${exitCode})${output ? `:\\n${output}` : \"\"}`,\n );\n this.name = \"TerminalServerError\";\n this.exitCode = exitCode;\n this.stage = stage;\n }\n}\n\n/** Thrown when the provider session cannot run commands (a headless-only backend\n * with neither `exec` nor `execCommand`). The terminal tier degrades to the\n * Channel-A sse-events firehose — the caller maps this to a `transport:null`\n * pty-ws (the read-only firehose still works). */\nexport class TerminalServerUnsupportedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TerminalServerUnsupportedError\";\n }\n}\n\n// The structural slice of a provider session we need: run a command (preferring\n// `exec` for the structured exit code, falling back to `execCommand`).\ntype ExecResultLike = {\n output?: string;\n stdout?: string;\n stderr?: string;\n exitCode?: number | null;\n};\ntype ExecCapableSession = {\n exec?: (args: {\n cmd: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<ExecResultLike>;\n execCommand?: (args: {\n cmd: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<string>;\n};\n\nexport type EnsureTerminalServerOptions = {\n /** The exposed terminal port; defaults to 7681 (ttyd default). */\n port?: number;\n /** Per-exec timeout; defaults to TERMINAL_SERVER_TIMEOUT_MS. */\n timeoutMs?: number;\n};\n\nexport type EnsureTerminalServerResult = {\n /** The exposed port ttyd listens on (PTY-over-websocket). */\n port: number;\n /** The raw `OPENGENI_TERMINAL_UP …` marker line, for diagnostics. Never\n * surfaced to clients. */\n marker: string;\n};\n\n/**\n * Build the shell command that runs the idempotent up-script under an in-box\n * `flock`. The script is shipped in the image at /usr/local/bin/opengeni-terminal-up\n * (the canonical desktop image, alongside opengeni-desktop-up); we set the port\n * env and wrap the call in `flock` so two concurrent ensureTerminalServer callers\n * (the API viewer op + the agent turn, both racing after a rollover) serialize\n * without a double launch. The up-script's own curl readiness probe makes the\n * second call a no-op.\n *\n * Exported (pure, side-effect-free) so the ensureTerminalServer unit test can\n * assert the exact command sequence without a live box. Mirrors\n * buildDisplayStackScript. A ttyd process is sandbox-group-global, not\n * Opengeni-session-specific, so it must never inherit the box-global legacy\n * Codemode pointer. Session-scoped interactive exec/PTY uses Channel A; the\n * shared ttyd shell fails closed for Codemode until that stream plane itself is\n * session-isolated.\n */\nexport function buildTerminalServerScript(options: EnsureTerminalServerOptions = {}): string {\n const port = options.port ?? TERMINAL_STREAM_PORT;\n // flock -w bounds the wait so a wedged holder can't deadlock the caller; the\n // up-script's curl probe ALSO makes the launch idempotent (belt + braces) so\n // this works even against an older image that predates the wrapper.\n return (\n `mkdir -p /tmp/opengeni-terminal && ` +\n // --close prevents the detached ttyd child from inheriting the lock fd and\n // pinning this lock for its entire lifetime. The flock parent still holds\n // the lock until opengeni-terminal-up exits.\n `flock -w 30 --close /tmp/opengeni-terminal/up.outer.lock ` +\n `env TERMINAL_PORT=${port} OPENGENI_CODEMODE_TOKEN_FILE=/dev/null opengeni-terminal-up`\n );\n}\n\nfunction execResultOutput(result: ExecResultLike | string): string {\n if (typeof result === \"string\") {\n return result;\n }\n return [result.output, result.stderr, result.stdout]\n .filter((v): v is string => typeof v === \"string\" && v.length > 0)\n .join(\"\\n\");\n}\n\nfunction execResultExitCode(result: ExecResultLike | string): number | null {\n if (typeof result === \"string\") {\n return null; // execCommand returns a bare string — no exit code available.\n }\n return typeof result.exitCode === \"number\" ? result.exitCode : null;\n}\n\n// Parse the exit code the up-script signals via its trailing marker. When we ran\n// through `exec` we have the real exitCode; when we only had `execCommand` (a\n// bare string), we infer success from the OPENGENI_TERMINAL_UP marker and infer\n// the failing stage from the stage-failure message the script prints to stderr.\n// Mirrors inferExitFromOutput (display-stack).\nfunction inferExitFromOutput(output: string): number {\n if (/OPENGENI_TERMINAL_UP\\b/.test(output)) {\n return 0;\n }\n if (/ttyd failed to come up/.test(output)) {\n return 14;\n }\n return -1;\n}\n\n/**\n * Idempotently bring up the ttyd PTY-over-websocket server on the live box. Safe\n * to call N times (the in-box flock + the up-script's curl readiness probe make a\n * second call a no-op). Resolves with the exposed port on success; throws\n * `TerminalServerError` on a launch failure and `TerminalServerUnsupportedError`\n * when the session cannot run commands.\n *\n * `session` is the externally-owned provider session (the `established.session`\n * from establishSandboxSessionFromEnvelope, or any SandboxSessionLike). We prefer\n * `session.exec` (structured `{exitCode}`) and fall back to `session.execCommand`\n * (bare string), inferring success from the up-script's marker line in the\n * fallback case. Mirrors ensureDisplayStack exactly.\n */\nexport async function ensureTerminalServer(\n session: unknown,\n options: EnsureTerminalServerOptions = {},\n): Promise<EnsureTerminalServerResult> {\n const s = session as ExecCapableSession;\n if (typeof s?.exec !== \"function\" && typeof s?.execCommand !== \"function\") {\n throw new TerminalServerUnsupportedError(\n \"provider session cannot run commands (no exec/execCommand) — terminal pty-ws unavailable\",\n );\n }\n\n const port = options.port ?? TERMINAL_STREAM_PORT;\n const timeoutMs = options.timeoutMs ?? TERMINAL_SERVER_TIMEOUT_MS;\n const cmd = buildTerminalServerScript({ port });\n\n const result =\n typeof s.exec === \"function\"\n ? await s.exec({ cmd, yieldTimeMs: timeoutMs, maxOutputTokens: 20_000 })\n : await s.execCommand!({ cmd, yieldTimeMs: timeoutMs, maxOutputTokens: 20_000 });\n\n const output = execResultOutput(result);\n const exitCode = execResultExitCode(result) ?? inferExitFromOutput(output);\n\n if (exitCode !== 0) {\n throw new TerminalServerError(exitCode, output);\n }\n\n const marker = (output.match(/OPENGENI_TERMINAL_UP[^\\n]*/) ?? [\"\"])[0];\n return { port, marker };\n}\n\n/** Tear the terminal server down (down-script). Best-effort; never throws on a\n * missing process. Mirrors tearDownDisplayStack. */\nexport async function tearDownTerminalServer(session: unknown): Promise<void> {\n const s = session as ExecCapableSession;\n if (typeof s?.exec === \"function\") {\n await s.exec({ cmd: \"opengeni-terminal-down\", yieldTimeMs: 10_000, maxOutputTokens: 4_000 });\n return;\n }\n if (typeof s?.execCommand === \"function\") {\n await s.execCommand({\n cmd: \"opengeni-terminal-down\",\n yieldTimeMs: 10_000,\n maxOutputTokens: 4_000,\n });\n }\n}\n","import { posix as posixPath } from \"node:path\";\nimport { BROWSER_CONTROL_PORT } from \"@opengeni/contracts\";\n\nexport { BROWSER_CONTROL_PORT };\n\nexport const BROWSER_CONTROL_SERVER_TIMEOUT_MS = 60_000;\nexport const BROWSER_CONTROL_STATE_DIRECTORY = \"/tmp/opengeni-browserd/state\";\nexport const BROWSER_CONTROL_SERVER_BIN = \"/usr/local/bin/opengeni-browserd-up\";\nexport const BROWSER_CONTROL_SERVER_DOWN_BIN = \"/usr/local/bin/opengeni-browserd-down\";\n\nexport class BrowserControlServerError extends Error {\n readonly exitCode: number;\n readonly stage: \"startup\" | \"port_conflict\" | \"engine_unavailable\" | \"unknown\";\n\n constructor(exitCode: number, output: string) {\n const stage = classifyBrowserControlStage(exitCode, output);\n super(\n `browser control server failed at stage \"${stage}\" (exit ${exitCode})${output ? `:\\n${output}` : \"\"}`,\n );\n this.name = \"BrowserControlServerError\";\n this.exitCode = exitCode;\n this.stage = stage;\n }\n}\n\nexport class BrowserControlServerUnsupportedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"BrowserControlServerUnsupportedError\";\n }\n}\n\ntype ExecResultLike = {\n output?: string;\n stdout?: string;\n stderr?: string;\n exitCode?: number | null;\n};\n\ntype ExecCapableSession = {\n exec?: (args: {\n cmd: string;\n workdir?: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<ExecResultLike>;\n execCommand?: (args: {\n cmd: string;\n workdir?: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<string>;\n};\n\n// Image-backed controller commands use absolute private paths under /tmp, but\n// managed sandbox exec confines `workdir` to the canonical workspace root.\n// Keep the cwd stable without asking the provider to validate /tmp as a\n// workspace path.\nconst PLACEMENT_CONTROLLER_WORKDIR = \"/workspace\";\n\nexport type EnsureBrowserControlServerOptions = {\n port?: number;\n timeoutMs?: number;\n adminTokenFile: string;\n allowedOrigins?: readonly string[];\n};\n\nexport type EnsureBrowserControlServerResult = {\n port: number;\n marker: string;\n};\n\nexport function buildBrowserControlServerScript(\n options: Pick<EnsureBrowserControlServerOptions, \"adminTokenFile\"> &\n Partial<Pick<EnsureBrowserControlServerOptions, \"port\" | \"allowedOrigins\">>,\n): string {\n const port = boundedPort(options.port ?? BROWSER_CONTROL_PORT);\n const tokenFile = absolutePath(options.adminTokenFile, \"browser controller admin token file\");\n const allowedOrigins = normalizeOrigins(options.allowedOrigins ?? []);\n return [\n \"mkdir -p /tmp/opengeni-browserd &&\",\n `if ! test -x ${BROWSER_CONTROL_SERVER_BIN}; then echo 'opengeni-browserd-up is not installed on this sandbox image' >&2; exit 16; fi &&`,\n \"flock -w 30 --close /tmp/opengeni-browserd/up.outer.lock\",\n `env OPENGENI_BROWSERD_PORT=${port}`,\n `OPENGENI_BROWSERD_ROOT=${shellQuote(BROWSER_CONTROL_STATE_DIRECTORY)}`,\n `OPENGENI_BROWSERD_ADMIN_TOKEN_FILE=${shellQuote(tokenFile)}`,\n `OPENGENI_BROWSERD_ALLOWED_ORIGINS=${shellQuote(allowedOrigins.join(\",\"))}`,\n \"OPENGENI_CODEMODE_TOKEN_FILE=/dev/null\",\n BROWSER_CONTROL_SERVER_BIN,\n ].join(\" \");\n}\n\nexport async function ensureBrowserControlServer(\n session: unknown,\n options: EnsureBrowserControlServerOptions,\n): Promise<EnsureBrowserControlServerResult> {\n const target = session as ExecCapableSession;\n if (typeof target?.exec !== \"function\" && typeof target?.execCommand !== \"function\") {\n throw new BrowserControlServerUnsupportedError(\n \"provider session cannot run commands (no exec/execCommand) — browser control unavailable\",\n );\n }\n const port = boundedPort(options.port ?? BROWSER_CONTROL_PORT);\n const timeoutMs = boundedTimeout(options.timeoutMs ?? BROWSER_CONTROL_SERVER_TIMEOUT_MS);\n const cmd = buildBrowserControlServerScript({\n port,\n adminTokenFile: options.adminTokenFile,\n ...(options.allowedOrigins ? { allowedOrigins: options.allowedOrigins } : {}),\n });\n const result = target.exec\n ? await target.exec({\n cmd,\n workdir: PLACEMENT_CONTROLLER_WORKDIR,\n yieldTimeMs: timeoutMs,\n maxOutputTokens: 4_000,\n })\n : await target.execCommand!({\n cmd,\n workdir: PLACEMENT_CONTROLLER_WORKDIR,\n yieldTimeMs: timeoutMs,\n maxOutputTokens: 4_000,\n });\n const output = outputOf(result);\n const exitCode = exitCodeOf(result) ?? inferExitCode(output);\n if (exitCode !== 0) throw new BrowserControlServerError(exitCode, output);\n const marker = (output.match(/OPENGENI_BROWSERD_UP[^\\n]*/) ?? [\"\"])[0];\n if (!marker) {\n throw new BrowserControlServerError(\n 14,\n output || \"browser controller did not emit its readiness marker\",\n );\n }\n return { port, marker };\n}\n\nexport async function tearDownBrowserControlServer(session: unknown): Promise<void> {\n const target = session as ExecCapableSession;\n if (target?.exec) {\n await target.exec({\n cmd: BROWSER_CONTROL_SERVER_DOWN_BIN,\n workdir: PLACEMENT_CONTROLLER_WORKDIR,\n yieldTimeMs: 15_000,\n maxOutputTokens: 4_000,\n });\n } else if (target?.execCommand) {\n await target.execCommand({\n cmd: BROWSER_CONTROL_SERVER_DOWN_BIN,\n workdir: PLACEMENT_CONTROLLER_WORKDIR,\n yieldTimeMs: 15_000,\n maxOutputTokens: 4_000,\n });\n }\n}\n\nfunction outputOf(result: ExecResultLike | string): string {\n if (typeof result === \"string\") return result;\n return [result.output, result.stderr, result.stdout]\n .filter((value): value is string => typeof value === \"string\" && value.length > 0)\n .join(\"\\n\");\n}\n\nfunction exitCodeOf(result: ExecResultLike | string): number | null {\n return typeof result === \"string\" || typeof result.exitCode !== \"number\" ? null : result.exitCode;\n}\n\nfunction classifyBrowserControlStage(\n exitCode: number,\n output: string,\n): BrowserControlServerError[\"stage\"] {\n if (exitCode === 14) return \"startup\";\n if (exitCode === 15) return \"port_conflict\";\n if (exitCode === 16 || isMissingBrowserControlServer(exitCode, output)) {\n return \"engine_unavailable\";\n }\n return \"unknown\";\n}\n\nfunction isMissingBrowserControlServer(exitCode: number, output: string): boolean {\n if (exitCode === 127) return true;\n return /opengeni-browserd-up[^\\n]*No such file or directory|opengeni-browserd-up is not installed on this sandbox image/u.test(\n output,\n );\n}\n\nfunction inferExitCode(output: string): number {\n if (/OPENGENI_BROWSERD_UP\\b/u.test(output)) return 0;\n if (/occupied by an unmanaged process/u.test(output)) return 15;\n if (/no supported Chromium engine/u.test(output) || isMissingBrowserControlServer(-1, output)) {\n return 16;\n }\n if (/exited during startup|failed to become ready/u.test(output)) return 14;\n return -1;\n}\n\nfunction boundedPort(value: number): number {\n if (!Number.isSafeInteger(value) || value < 1 || value > 65_535) {\n throw new RangeError(\"browser controller port is invalid\");\n }\n return value;\n}\n\nfunction boundedTimeout(value: number): number {\n if (!Number.isSafeInteger(value) || value < 1 || value > 10 * 60_000) {\n throw new RangeError(\"browser controller timeout is invalid\");\n }\n return value;\n}\n\nfunction absolutePath(value: string, label: string): string {\n if (!value || value.includes(\"\\0\") || !posixPath.isAbsolute(value)) {\n throw new Error(`${label} must be absolute`);\n }\n return posixPath.normalize(value);\n}\n\nfunction normalizeOrigins(values: readonly string[]): string[] {\n if (values.length > 64) throw new Error(\"too many browser controller origins\");\n return values.map((value) => {\n const url = new URL(value);\n if (url.origin === \"null\" || url.pathname !== \"/\" || url.search || url.hash) {\n throw new Error(\"browser controller origin must be an absolute origin\");\n }\n return url.origin;\n });\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n","import {\n ComputerNativeCommand,\n ComputerNativeReceipt,\n ComputerOperationReceipt,\n} from \"@opengeni/contracts\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { posix as posixPath } from \"node:path\";\nimport { parseBrowserFrameMetadata, type BrowserFrameMetadata } from \"@opengeni/sdk\";\nimport {\n BROWSER_ACTION_RECEIPT_TARGETS_PARAMETER,\n BROWSER_CONTROL_MAX_JSON_BYTES,\n BROWSER_CONTROL_PORT,\n BROWSER_CONTROL_PROTOCOL_VERSION,\n BROWSER_PROFILE_ARTIFACT_FORMAT,\n BROWSER_STATE_ARTIFACT_CONTENT_TYPE,\n BrowserActionCommand,\n BrowserActionReceipt,\n BrowserClipboard,\n BrowserDiagnosticBatch,\n BrowserDownload,\n BrowserDownloadExportReceipt,\n BrowserDownloadExportRequest,\n BrowserDownloadListResponse,\n BrowserDomReadRequest,\n BrowserDomReadResponse,\n BrowserExternalAuthCommand,\n BrowserExternalAuthResult,\n BrowserObservation,\n BrowserRevisionMaterialization,\n BrowserTarget,\n BrowserTargetListResponse,\n BrowserTargetState,\n BrowserWorkspaceFileStageRequest,\n BrowserWorkspaceFileStageResponse,\n BrowserPasskeySyncRequest,\n BrowserPasskeySyncResponse,\n ComputerActionCommand,\n ComputerActionReceipt,\n ComputerClipboard,\n ComputerObservation,\n COMPUTER_SCREENSHOT_MAX_BYTES,\n ComputerSessionCapabilities,\n ComputerTarget,\n InteractionError,\n NetworkRouteConsistency,\n type BrowserActionCommand as BrowserActionCommandValue,\n type BrowserActionReceipt as BrowserActionReceiptValue,\n type BrowserClipboard as BrowserClipboardValue,\n type BrowserDiagnosticBatch as BrowserDiagnosticBatchValue,\n type BrowserDownload as BrowserDownloadValue,\n type BrowserDownloadExportReceipt as BrowserDownloadExportReceiptValue,\n type BrowserDownloadExportRequest as BrowserDownloadExportRequestValue,\n type BrowserDownloadListResponse as BrowserDownloadListResponseValue,\n type BrowserDomReadRequest as BrowserDomReadRequestValue,\n type BrowserDomReadResponse as BrowserDomReadResponseValue,\n type BrowserExternalAuthCommand as BrowserExternalAuthCommandValue,\n type BrowserExternalAuthResult as BrowserExternalAuthResultValue,\n type BrowserDiagnosticKind,\n type BrowserTargetListResponse as BrowserTargetListResponseValue,\n type BrowserObservation as BrowserObservationValue,\n type BrowserRevisionMaterialization as BrowserRevisionMaterializationValue,\n type BrowserTarget as BrowserTargetValue,\n type BrowserTargetState as BrowserTargetStateValue,\n type BrowserWorkspaceFileStageRequest as BrowserWorkspaceFileStageRequestValue,\n type BrowserWorkspaceFileStageResponse as BrowserWorkspaceFileStageResponseValue,\n type BrowserPasskeySyncRequest as BrowserPasskeySyncRequestValue,\n type BrowserPasskeySyncResponse as BrowserPasskeySyncResponseValue,\n type ComputerActionCommand as ComputerActionCommandValue,\n type ComputerActionReceipt as ComputerActionReceiptValue,\n type ComputerClipboard as ComputerClipboardValue,\n type ComputerObservation as ComputerObservationValue,\n type ComputerSessionCapabilities as ComputerSessionCapabilitiesValue,\n type ComputerTarget as ComputerTargetValue,\n type InteractionError as InteractionErrorValue,\n type NetworkRouteConsistency as NetworkRouteConsistencyValue,\n} from \"@opengeni/contracts\";\nimport type {\n BrowserControlEnsureRequest,\n BrowserControlEnsureResponse,\n BrowserFramesOpenRequest,\n ComputerFramesOpenRequest,\n StreamChannel,\n} from \"@opengeni/agent-proto\";\nimport {\n ensureBrowserControlServer,\n type EnsureBrowserControlServerResult,\n} from \"./browser-control-server\";\nimport { parseExecResponseBanner } from \"./exec-banner\";\nimport { controllerStreamRequest, parseControllerStreamResponse } from \"./browser-control-stream\";\nimport type { BrowserControlHttpCall, BrowserControlHttpOutcome } from \"./browser-control-http\";\nimport {\n buildStreamUrl,\n exposedPortAllowsHostFetch,\n joinExposedPortPath,\n parseOpenSandboxSignedUriPath,\n StreamPortUnavailableError,\n type ExposedPortEndpoint,\n} from \"./stream-port\";\n\nconst CLIENT_ROOT = \"/tmp/opengeni-private/browser-control-client\";\nconst MANAGED_PLACEMENT_CONTROLLER_WORKDIR = \"/workspace\";\nconst NATIVE_PLACEMENT_CONTROLLER_WORKDIR = \"/tmp\";\nexport const BROWSER_CONTROL_ADMIN_TOKEN_FILE = \"/tmp/opengeni-browserd/authority/admin-token\";\nconst COMMAND_OK = \"OPENGENI_BROWSER_CONTROL_CLIENT_OK\";\nconst TOKEN_PATTERN = /^[A-Za-z0-9._~-]{32,2048}$/u;\nconst MAX_REQUEST_TIMEOUT_MS = 20 * 60_000;\nconst BROWSER_STATE_TRANSFER_TIMEOUT_MS = 20 * 60_000;\nconst PRIVATE_READ_CHUNK_BYTES = 512 * 1024;\nconst SHA256_PATTERN = /^[0-9a-f]{64}$/u;\n\n// Connected-machine browserd binds an OS-assigned loopback port. The agent\n// owns that endpoint, so the API must never fall back to the image port merely\n// because a fresh request constructed a fresh client. Cache the negotiated\n// endpoint by its physical authority fence; a transport failure invalidates it\n// and performs one idempotent ensure/retry below.\nconst nativeControllerPorts = new Map<string, number>();\n\ntype ExecResultLike = {\n output?: string;\n stdout?: string;\n stderr?: string;\n exitCode?: number | null;\n sessionId?: number;\n};\n\nexport type BrowserControlPlacementSession = {\n /** Connected Machine command stdin is byte-exact and private. Optional so\n * older placement adapters retain their existing file-based transport. */\n execWithInput?: (args: {\n cmd: string;\n stdin: Uint8Array;\n shell: string;\n login: boolean;\n workdir: string;\n }) => Promise<ExecResultLike>;\n /** Host family of a Connected Machine. Windows hosts have no POSIX shell,\n * /tmp or base64, so the controller transport uses its Windows form there. */\n controllerHostOs?: () => \"posix\" | \"windows\";\n exec?: (args: {\n cmd: string;\n workdir?: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<ExecResultLike | string>;\n execCommand?: (args: {\n cmd: string;\n workdir?: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<string>;\n readFile?: (args: { path: string; maxBytes?: number }) => Promise<string | Uint8Array>;\n writeFile?: (args: {\n path: string;\n content: string | Uint8Array;\n createParents?: boolean;\n }) => Promise<unknown>;\n writePlacementPrivate?: (args: {\n path: string;\n content: string | Uint8Array;\n createParents?: boolean;\n }) => Promise<unknown>;\n deletePlacementPrivate?: (path: string) => Promise<void>;\n writeStdin?: (args: {\n sessionId: number;\n chars?: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<string>;\n resolveExposedPort?: (port: number) => Promise<ExposedPortEndpoint>;\n /** Signed OpenSandbox Channel B must host-fetch. Never fall through to in-box curl. */\n requireHostFetchController?: boolean;\n runtimeMetrics?: {\n onOpenSandboxSignedEndpoint?: (input: {\n outcome: \"minted\" | \"mint_failed\" | \"host_fetch_unauthorized\";\n port: number;\n }) => void;\n };\n ensureBrowserControl?: (\n request: BrowserControlEnsureRequest,\n ) => Promise<BrowserControlEnsureResponse>;\n /** Agent-native controller transport, addressed by authority scope. */\n browserControlHttp?: (request: BrowserControlHttpCall) => Promise<BrowserControlHttpOutcome>;\n openBrowserFrames?: (\n request: BrowserFramesOpenRequest,\n ) => Promise<{ channel: StreamChannel; endpoint: ExposedPortEndpoint }>;\n openComputerFrames?: (\n request: ComputerFramesOpenRequest,\n ) => Promise<{ channel: StreamChannel; endpoint: ExposedPortEndpoint }>;\n finalizeOpStreamOps?: () => Promise<void>;\n};\n\nexport type ComputerControlFrame = {\n data: Uint8Array;\n mediaType: \"image/jpeg\" | \"image/png\";\n metadataHeader: string;\n metadata: ComputerControlFrameMetadata;\n};\n\nexport type BrowserControlFrame = {\n data: Uint8Array;\n mediaType: \"image/jpeg\" | \"image/png\";\n metadataHeader: string;\n metadata: BrowserFrameMetadata;\n};\n\nexport type BrowserControlScreenshotOptions = {\n fullPage?: boolean;\n format?: \"jpeg\" | \"png\";\n quality?: number;\n};\n\ntype ExpectedBrowserFrameEvidence = {\n browserSessionId: string;\n controllerGeneration: string;\n targetId: string;\n};\n\ntype FrameRequest = {\n method: \"GET\";\n path: string;\n token: string;\n timeoutMs?: number;\n} & (\n | { surface: \"browser\"; expectedFrameEvidence: ExpectedBrowserFrameEvidence }\n | { surface: \"computer\"; expectedFrameEvidence: ExpectedComputerFrameEvidence }\n);\n\nexport type ComputerControlFrameMetadata = {\n frameId: string;\n computerSessionId: string;\n controllerGeneration: string;\n targetId: string;\n targetGeneration: string;\n sequence: number;\n mediaType: \"image/jpeg\" | \"image/png\";\n width: number;\n height: number;\n capturedAt: string;\n sha256: string;\n};\n\nexport type ComputerFrameEvidenceMismatchReason =\n | \"frame_session_mismatch\"\n | \"frame_target_mismatch\"\n | \"frame_controller_mismatch\"\n | \"frame_media_mismatch\"\n | \"frame_digest_mismatch\";\n\nexport type ExpectedComputerFrameEvidence = {\n computerSessionId: string;\n controllerGeneration: string;\n targetId: string;\n};\n\n/** Controller I/O uses absolute private paths under /tmp, so its cwd carries\n * no data authority. Connected Machines need a native /tmp cwd because their\n * session directory may disappear; managed sandboxes must use /workspace\n * because provider exec confines workdir to the workspace root. */\nfunction placementControllerWorkdir(session: BrowserControlPlacementSession): string {\n if (!session.ensureBrowserControl) return MANAGED_PLACEMENT_CONTROLLER_WORKDIR;\n // A Windows machine has no /tmp. The relative \".\" resolves to its reported\n // workspace root, which exists for the connection's lifetime.\n return session.controllerHostOs?.() === \"windows\" ? \".\" : NATIVE_PLACEMENT_CONTROLLER_WORKDIR;\n}\n\nexport type PlacementBrowserSessionReference = {\n browserSessionId: string;\n controllerGeneration: string;\n};\n\nexport type PlacementBrowserSession = PlacementBrowserSessionReference & {\n observation: BrowserObservationValue;\n /** The tab inventory at creation, when the controller reports it. */\n targets?: BrowserTargetValue[];\n};\n\nexport type PlacementComputerSessionReference = {\n computerSessionId: string;\n controllerGeneration: string;\n};\n\nexport type PlacementComputerSession = PlacementComputerSessionReference & {\n platform: \"linux\" | \"macos\" | \"windows\";\n adapter: string;\n seatId: string;\n displayId: string;\n capabilities: ComputerSessionCapabilitiesValue;\n targets: ComputerTargetValue[];\n};\n\nexport type CreatePlacementComputerSessionInput = PlacementComputerSessionReference & {\n tokenGeneration: number;\n controlToken: string;\n viewToken: string;\n};\n\nexport type CreatePlacementBrowserSessionInput = PlacementBrowserSessionReference & {\n tokenGeneration: number;\n controlToken: string;\n viewToken: string;\n headed: boolean;\n initialUrl?: string;\n /** Private same-runtime recovery intent; never restores a saved revision. */\n recoverExistingWorkingDirectory?: true;\n restore?: RestorePlacementBrowserStateInput;\n transport?: PlacementBrowserTransport;\n linkedComputer?: PlacementComputerSessionReference;\n networkRoute?: PlacementBrowserNetworkRoute;\n};\n\nexport type PlacementBrowserNetworkRoute = {\n routeId: string;\n routeVersion: number;\n authorityDigest: string;\n kind: \"direct\" | \"proxy\" | \"managed\" | \"tunnel\";\n consistency: NetworkRouteConsistencyValue;\n /** Present for an initial authenticated-proxy launch; omitted only when\n * replaying an already-live controller after the referenced credential was\n * rotated. Never persisted or returned by the controller. */\n proxyUrl?: string;\n /** Provider-native egress selector. Provider API authority remains on the\n * external transport and is never duplicated into this route material. */\n providerRoute?: {\n providerId: \"browserbase\" | \"kernel\";\n routeId: string;\n egressClass: \"datacenter\" | \"residential\" | \"isp\";\n region: string | null;\n };\n};\n\nexport type PlacementBrowserTransport =\n | { kind: \"managed\"; engine?: \"chromium\" | \"lightpanda\"; ephemeralPartition?: string }\n | {\n kind: \"external_provider\";\n providerId: \"browserbase\" | \"kernel\";\n placementId: string;\n /** Private launch authority. Browserd never returns or journals it. */\n authority: {\n apiKey: string;\n endpoint?: string;\n };\n timeoutSeconds?: number;\n stealth?: boolean;\n }\n | {\n kind: \"attached_chrome\";\n deviceId: string;\n connectionGeneration: string;\n browserName: string;\n browserVersion: string;\n };\n\nexport type BrowserViewGrant = {\n fencedInputBatches?: true;\n focusedInputObservations?: true;\n grantId: string;\n expiresAt: string;\n};\n\nexport type ComputerViewGrant = BrowserViewGrant & { scopedRfbInput: boolean };\n\nexport type BrowserStateUploadGrant = {\n url: string;\n requiredHeaders: Readonly<Record<string, string>>;\n expiresAt: string;\n};\n\nexport type BrowserStateDownloadGrant = {\n url: string;\n expiresAt: string;\n};\n\nexport type RestorePlacementBrowserStateInput = {\n objectKey: string;\n format: typeof BROWSER_PROFILE_ARTIFACT_FORMAT;\n artifactDigest: string;\n contentDigest: string;\n manifestDigest: string;\n sizeBytes: number;\n dataKey: Uint8Array;\n aad: Uint8Array;\n materialization: BrowserRevisionMaterializationValue;\n download: BrowserStateDownloadGrant;\n};\n\nexport type CapturePlacementBrowserStateInput = PlacementBrowserSessionReference & {\n operationId: string;\n objectKey: string;\n afterCapture: \"restart\" | \"stop\";\n dataKey: Uint8Array;\n aad: Uint8Array;\n upload: BrowserStateUploadGrant;\n};\n\nexport type PlacementBrowserStateCaptureReceipt = PlacementBrowserSessionReference & {\n operationId: string;\n objectKey: string;\n format: typeof BROWSER_PROFILE_ARTIFACT_FORMAT;\n artifactDigest: string;\n contentDigest: string;\n sizeBytes: number;\n fileCount: number;\n profileBytes: number;\n manifest: {\n schemaVersion: 1;\n browserSessionId: string;\n controllerGeneration: string;\n capturedAt: string;\n engine: \"chromium\" | \"chrome\";\n engineVersion: string | null;\n driverId: string;\n driverSchemaVersion: number;\n profileCrypto: \"chromium_basic\" | \"chromium_mock_keychain\" | \"platform_bound\";\n platform: \"linux\" | \"macos\" | \"windows\";\n architecture: \"x64\" | \"arm64\";\n tabs: Array<{ url: string; selected: boolean }>;\n };\n};\n\n/** The exact controller authority a preserved working copy was launched\n * under; the controller refuses any other. */\nexport type PlacementBrowserWorkingCopyAuthority = PlacementBrowserSessionReference & {\n tokenGeneration: number;\n controlToken: string;\n viewToken: string;\n};\n\nexport const BROWSER_WORKING_COPY_REFUSALS = [\n \"unsupported_platform\",\n \"browser_running\",\n \"working_copy_invalid\",\n \"receipt_not_adoptable\",\n \"authority_changed\",\n \"process_state_unknown\",\n \"adoption_not_needed\",\n \"adoption_unresolved\",\n] as const;\nexport type PlacementBrowserWorkingCopyRefusal = (typeof BROWSER_WORKING_COPY_REFUSALS)[number];\n\nexport const BROWSER_WORKING_COPY_ADOPTION_PHASES = [\n \"intent\",\n \"copied\",\n \"receipt\",\n \"source_preserved\",\n \"adopted\",\n \"interrupted\",\n \"failed\",\n \"collision\",\n \"reverting\",\n \"reverted\",\n] as const;\nexport type PlacementBrowserWorkingCopyAdoptionPhase =\n (typeof BROWSER_WORKING_COPY_ADOPTION_PHASES)[number];\n\nexport type PlacementBrowserWorkingCopyAdoption = PlacementBrowserSessionReference & {\n operationId: string;\n manifestDigest: string;\n phase: PlacementBrowserWorkingCopyAdoptionPhase;\n failureCode: string | null;\n /** Directories this adoption kept beside the browser's own, by name. */\n retainedDirectories: string[];\n createdAt: string;\n updatedAt: string;\n};\n\nexport type PlacementBrowserWorkingCopyInspection = PlacementBrowserSessionReference & {\n platformSupported: boolean;\n refusal: PlacementBrowserWorkingCopyRefusal | null;\n /** Exact digest of the bytes an adoption would take; null when refused. */\n manifest: { digest: string; entries: number; bytes: number; excluded: string[] } | null;\n profileIdentityMatches: boolean;\n /** false only when no process provably uses the profile. */\n profileInUse: boolean | null;\n receipt: {\n operationId: string;\n intent: \"launch\" | \"suspend\" | \"retire\" | \"adopt\";\n state: string;\n directoryLaunchAllowed: boolean;\n authorityMatches: boolean;\n /** True when this working copy was first launched from a saved checkpoint. */\n launchedFromCheckpoint: boolean;\n adoption: { operationId: string; manifestDigest: string } | null;\n } | null;\n activeAdoption: PlacementBrowserWorkingCopyAdoption | null;\n};\n\nexport type ProvisionBrowserControlClientInput = {\n adminToken: string;\n adminTokenFile?: string;\n allowedOrigins?: readonly string[];\n port?: number;\n timeoutMs?: number;\n /** Native connected-machine sidecar authority. Ignored by image-backed\n * placements, whose browserd is already supervised inside the sandbox image. */\n nativeAuthority?: {\n scopeId: string;\n scopeGeneration: string;\n };\n};\n\nexport type ProvisionBrowserControlClientResult = {\n client: BrowserControlClient;\n server: EnsureBrowserControlServerResult;\n};\n\nexport class BrowserControlTransportError extends Error {\n readonly name = \"BrowserControlTransportError\";\n readonly retryable = true;\n}\n\nexport class BrowserControlProtocolError extends Error {\n readonly name = \"BrowserControlProtocolError\";\n readonly retryable = false;\n}\n\nexport class ComputerFrameEvidenceMismatchError extends BrowserControlProtocolError {\n constructor(readonly reason: ComputerFrameEvidenceMismatchReason) {\n super(\"computer frame evidence does not match its request\");\n }\n}\n\nexport class BrowserControlRequestError extends Error {\n readonly name = \"BrowserControlRequestError\";\n readonly retryable: boolean;\n\n constructor(\n readonly status: number,\n readonly error: InteractionErrorValue,\n ) {\n super(error.message);\n this.retryable = error.retryable;\n }\n}\n\nexport class BrowserControlUnsupportedError extends Error {\n readonly name = \"BrowserControlUnsupportedError\";\n}\n\nfunction browserControllerCompatibilityError(feature: string): BrowserControlRequestError {\n return new BrowserControlRequestError(409, {\n code: \"unsupported\",\n message: `browser controller does not support ${feature}; update the placement's controller image to match this Opengeni release`,\n retryable: false,\n });\n}\n\n/** Install one placement-stable admin credential and start the pinned controller. */\nexport async function provisionBrowserControlClient(\n session: BrowserControlPlacementSession,\n input: ProvisionBrowserControlClientInput,\n): Promise<ProvisionBrowserControlClientResult> {\n requirePlacementProvisioningSurface(session);\n const adminToken = requireToken(input.adminToken, \"browser controller admin token\");\n if (session.ensureBrowserControl) {\n if (!input.nativeAuthority) {\n throw new BrowserControlProtocolError(\n \"connected browser placement is missing its controller authority scope\",\n );\n }\n const ensured = await session.ensureBrowserControl({\n scopeId: input.nativeAuthority.scopeId,\n scopeGeneration: input.nativeAuthority.scopeGeneration,\n adminToken,\n allowedOrigins: [...(input.allowedOrigins ?? [])],\n });\n const port = boundedPort(ensured.port);\n nativeControllerPorts.set(nativeControllerKey(input.nativeAuthority), port);\n return {\n client: new BrowserControlClient(session, {\n adminToken,\n port,\n nativeAuthority: input.nativeAuthority,\n ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),\n }),\n server: { port, marker: `agent:${ensured.sidecarGeneration}` },\n };\n }\n const adminTokenFile = absolutePrivatePath(\n input.adminTokenFile ?? BROWSER_CONTROL_ADMIN_TOKEN_FILE,\n \"browser controller admin token file\",\n );\n const temporaryTokenFile = `${adminTokenFile}.new.${randomUUID()}`;\n const parent = adminTokenFile.slice(0, adminTokenFile.lastIndexOf(\"/\")) || \"/\";\n try {\n await runChecked(\n session,\n `umask 077; install -d -m 0700 -- ${shellQuote(parent)}; printf '%s\\\\n' ${shellQuote(COMMAND_OK)}`,\n input.timeoutMs,\n );\n await writePrivateFile(\n session,\n {\n path: temporaryTokenFile,\n content: `${adminToken}\\n`,\n createParents: false,\n },\n input.timeoutMs,\n );\n await runChecked(\n session,\n `chmod 0600 -- ${shellQuote(temporaryTokenFile)}; mv -f -- ${shellQuote(temporaryTokenFile)} ${shellQuote(adminTokenFile)}; printf '%s\\\\n' ${shellQuote(COMMAND_OK)}`,\n input.timeoutMs,\n );\n const server = await ensureBrowserControlServer(session, {\n adminTokenFile,\n ...(input.allowedOrigins ? { allowedOrigins: input.allowedOrigins } : {}),\n ...(input.port === undefined ? {} : { port: input.port }),\n ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),\n });\n const client = new BrowserControlClient(session, {\n adminToken,\n port: server.port,\n ...(input.nativeAuthority ? { nativeAuthority: input.nativeAuthority } : {}),\n ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),\n });\n if (input.allowedOrigins && input.allowedOrigins.length > 0) {\n await client.addAllowedOrigins(input.allowedOrigins);\n }\n return { client, server };\n } finally {\n await runBestEffort(session, `rm -f -- ${shellQuote(temporaryTokenFile)}`);\n await session.finalizeOpStreamOps?.().catch(() => undefined);\n }\n}\n\nexport class BrowserControlClient {\n readonly port: number;\n private readonly session: BrowserControlPlacementSession;\n private readonly adminToken: string;\n private readonly timeoutMs: number;\n private readonly nativeAuthority: { scopeId: string; scopeGeneration: string } | undefined;\n\n constructor(\n session: BrowserControlPlacementSession,\n options: {\n adminToken: string;\n port?: number;\n timeoutMs?: number;\n nativeAuthority?: { scopeId: string; scopeGeneration: string };\n },\n ) {\n requirePlacementRequestSurface(session);\n this.session = session;\n this.adminToken = requireToken(options.adminToken, \"browser controller admin token\");\n this.port = boundedPort(options.port ?? BROWSER_CONTROL_PORT);\n this.timeoutMs = boundedTimeout(options.timeoutMs ?? 60_000);\n this.nativeAuthority = options.nativeAuthority;\n }\n\n async addAllowedOrigins(origins: readonly string[]): Promise<readonly string[]> {\n if (origins.length === 0 || origins.length > 64) {\n throw new RangeError(\"browser controller origin list size is invalid\");\n }\n const normalized = origins.map(normalizeOrigin);\n const data = await this.requestJson({\n method: \"PUT\",\n path: \"/v1/origins\",\n token: this.adminToken,\n body: { origins: normalized },\n });\n if (!isRecord(data) || !Array.isArray(data.origins)) {\n throw new BrowserControlProtocolError(\"browser controller returned malformed origins\");\n }\n return data.origins.map((origin) => normalizeOrigin(origin));\n }\n\n async createSession(input: CreatePlacementBrowserSessionInput): Promise<PlacementBrowserSession> {\n const reference = parseReference(input);\n if (\n input.recoverExistingWorkingDirectory !== undefined &&\n (input.recoverExistingWorkingDirectory !== true ||\n input.restore ||\n input.initialUrl !== undefined)\n ) {\n throw new BrowserControlProtocolError(\n \"working directory recovery cannot restore or navigate\",\n );\n }\n const restore = input.restore ? browserStateRestoreRequest(input.restore) : null;\n let data: unknown;\n try {\n data = await this.requestJson({\n method: \"POST\",\n path: \"/v1/browser-sessions\",\n token: this.adminToken,\n body: {\n ...reference,\n tokenGeneration: positiveSafeInteger(input.tokenGeneration, \"token generation\"),\n controlToken: requireToken(input.controlToken, \"browser control token\"),\n viewToken: requireToken(input.viewToken, \"browser view token\"),\n headed: input.headed,\n ...(input.recoverExistingWorkingDirectory\n ? { recoverExistingWorkingDirectory: true }\n : {}),\n ...(input.initialUrl === undefined ? {} : { initialUrl: boundedUrl(input.initialUrl) }),\n ...(input.transport ? { transport: placementBrowserTransport(input.transport) } : {}),\n ...(input.linkedComputer\n ? { linkedComputer: parseComputerReference(input.linkedComputer) }\n : {}),\n ...(input.networkRoute\n ? { networkRoute: placementBrowserNetworkRoute(input.networkRoute) }\n : {}),\n ...(restore ? { restore: restore.wire } : {}),\n },\n ...(restore ? { timeoutMs: BROWSER_STATE_TRANSFER_TIMEOUT_MS } : {}),\n });\n } finally {\n restore?.dataKey.fill(0);\n restore?.aad.fill(0);\n }\n if (!isRecord(data)) {\n throw new BrowserControlProtocolError(\"browser controller returned malformed session data\");\n }\n const returnedReference = parseReference(data);\n if (\n returnedReference.browserSessionId !== reference.browserSessionId ||\n returnedReference.controllerGeneration !== reference.controllerGeneration\n ) {\n throw new BrowserControlProtocolError(\"browser controller returned another session binding\");\n }\n return {\n ...returnedReference,\n observation: BrowserObservation.parse(data.observation),\n ...creationTargets(data.targets, returnedReference),\n };\n }\n\n async createComputerSession(\n input: CreatePlacementComputerSessionInput,\n ): Promise<PlacementComputerSession> {\n const reference = parseComputerReference(input);\n const data = await this.requestJson({\n method: \"POST\",\n path: \"/v1/computer-sessions\",\n token: this.adminToken,\n body: {\n ...reference,\n tokenGeneration: positiveSafeInteger(input.tokenGeneration, \"token generation\"),\n controlToken: requireToken(input.controlToken, \"computer control token\"),\n viewToken: requireToken(input.viewToken, \"computer view token\"),\n },\n });\n if (!isRecord(data) || !Array.isArray(data.targets)) {\n throw new BrowserControlProtocolError(\n \"interaction controller returned malformed computer session data\",\n );\n }\n const returned = parseComputerReference(data);\n if (\n returned.computerSessionId !== reference.computerSessionId ||\n returned.controllerGeneration !== reference.controllerGeneration\n ) {\n throw new BrowserControlProtocolError(\n \"interaction controller returned another computer session binding\",\n );\n }\n const platform = data.platform;\n if (platform !== \"linux\" && platform !== \"macos\" && platform !== \"windows\") {\n throw new BrowserControlProtocolError(\n \"interaction controller returned an invalid computer platform\",\n );\n }\n return {\n ...returned,\n platform,\n adapter: requireOpaqueId(data.adapter, \"computer adapter\"),\n seatId: requireOpaqueId(data.seatId, \"computer seat id\"),\n displayId: requireOpaqueId(data.displayId, \"computer display id\"),\n capabilities: ComputerSessionCapabilities.parse(data.capabilities),\n targets: data.targets.map((target) => ComputerTarget.parse(target)),\n };\n }\n\n async endSession(\n reference: PlacementBrowserSessionReference,\n options: {\n removeState: boolean;\n discardWorkingRuntime?: boolean;\n setAsideInterruptedLaunch?: boolean;\n },\n ): Promise<void> {\n const binding = parseReference(reference);\n const data = await this.requestJson({\n method: \"POST\",\n path: `/v1/browser-sessions/${binding.browserSessionId}/end`,\n token: this.adminToken,\n body: {\n controllerGeneration: binding.controllerGeneration,\n removeState: options.removeState,\n // Older controllers reject unknown keys, so send it only when set.\n ...(options.discardWorkingRuntime ? { discardWorkingRuntime: true } : {}),\n ...(options.setAsideInterruptedLaunch ? { setAsideInterruptedLaunch: true } : {}),\n },\n });\n if (!isRecord(data) || data.ended !== true) {\n throw new BrowserControlProtocolError(\"browser controller returned malformed end receipt\");\n }\n }\n\n async endComputerSession(\n reference: PlacementComputerSessionReference,\n options: { removeState: boolean },\n ): Promise<void> {\n const binding = parseComputerReference(reference);\n const data = await this.requestJson({\n method: \"POST\",\n path: `/v1/computer-sessions/${binding.computerSessionId}/end`,\n token: this.adminToken,\n body: {\n controllerGeneration: binding.controllerGeneration,\n removeState: options.removeState,\n },\n });\n if (!isRecord(data) || data.ended !== true) {\n throw new BrowserControlProtocolError(\n \"interaction controller returned malformed computer end receipt\",\n );\n }\n }\n\n async createViewGrant(\n reference: PlacementBrowserSessionReference,\n input: { grantId: string; token: string; expiresAt: string },\n ): Promise<BrowserViewGrant> {\n const binding = parseReference(reference);\n const grantId = requireUuid(input.grantId, \"view grant id\");\n const expiresAt = timestamp(input.expiresAt, \"view grant expiry\");\n const data = await this.requestJson({\n method: \"POST\",\n path: `/v1/browser-sessions/${binding.browserSessionId}/view-grants`,\n token: this.adminToken,\n body: {\n grantId,\n controllerGeneration: binding.controllerGeneration,\n token: requireToken(input.token, \"view grant token\"),\n expiresAt,\n },\n });\n if (!isRecord(data) || data.grantId !== grantId || data.expiresAt !== expiresAt) {\n throw new BrowserControlProtocolError(\"browser controller returned malformed view grant\");\n }\n if (data.fencedInputBatches !== undefined && data.fencedInputBatches !== true) {\n throw new BrowserControlProtocolError(\n \"browser controller returned invalid input batching capability\",\n );\n }\n if (data.focusedInputObservations !== undefined && data.focusedInputObservations !== true) {\n throw new BrowserControlProtocolError(\n \"browser controller returned invalid focused input capability\",\n );\n }\n return {\n grantId,\n expiresAt,\n ...(data.fencedInputBatches === true ? { fencedInputBatches: true } : {}),\n ...(data.focusedInputObservations === true ? { focusedInputObservations: true } : {}),\n };\n }\n\n async createComputerViewGrant(\n reference: PlacementComputerSessionReference,\n input: {\n grantId: string;\n token: string;\n expiresAt: string;\n rfbScope?: { targetId: string; targetGeneration: string; inputAllowed: boolean };\n },\n ): Promise<ComputerViewGrant> {\n const binding = parseComputerReference(reference);\n const grantId = requireUuid(input.grantId, \"computer view grant id\");\n const expiresAt = timestamp(input.expiresAt, \"computer view grant expiry\");\n const data = await this.requestJson({\n method: \"POST\",\n path: `/v1/computer-sessions/${binding.computerSessionId}/view-grants`,\n token: this.adminToken,\n body: {\n grantId,\n controllerGeneration: binding.controllerGeneration,\n token: requireToken(input.token, \"computer view grant token\"),\n expiresAt,\n ...(input.rfbScope\n ? {\n targetId: requireOpaqueId(input.rfbScope.targetId, \"RFB target id\"),\n targetGeneration: requireGeneration(input.rfbScope.targetGeneration),\n inputAllowed: input.rfbScope.inputAllowed,\n }\n : {}),\n },\n });\n if (!isRecord(data) || data.grantId !== grantId || data.expiresAt !== expiresAt) {\n throw new BrowserControlProtocolError(\n \"interaction controller returned malformed computer view grant\",\n );\n }\n if (data.scopedRfbInput !== undefined && typeof data.scopedRfbInput !== \"boolean\") {\n throw new BrowserControlProtocolError(\n \"interaction controller returned invalid RFB scope capability\",\n );\n }\n if (\n input.rfbScope &&\n (data.scopedRfbInput !== true ||\n data.targetId !== input.rfbScope.targetId ||\n data.targetGeneration !== input.rfbScope.targetGeneration ||\n data.inputAllowed !== input.rfbScope.inputAllowed)\n ) {\n throw new BrowserControlProtocolError(\n \"interaction controller did not bind the requested RFB scope\",\n );\n }\n return { grantId, expiresAt, scopedRfbInput: data.scopedRfbInput === true };\n }\n\n /** Quiesce one exact controller, upload its encrypted working profile, and\n * return only integrity/compatibility metadata. Secret authority is carried\n * in a private placement request file and never returned by browserd. */\n async captureState(\n input: CapturePlacementBrowserStateInput,\n ): Promise<PlacementBrowserStateCaptureReceipt> {\n const reference = parseReference(input);\n const operationId = requireUuid(input.operationId, \"browser state operation id\");\n const objectKey = browserStateObjectKey(input.objectKey);\n const dataKey = exactBytes(input.dataKey, 32, \"browser state data key\");\n const aad = boundedBytes(input.aad, 1, 16 * 1024, \"browser state associated data\");\n const upload = browserStateUploadGrant(input.upload);\n const data = await this.requestJson({\n method: \"POST\",\n path: `/v1/browser-sessions/${reference.browserSessionId}/state-captures`,\n token: this.adminToken,\n body: {\n operationId,\n controllerGeneration: reference.controllerGeneration,\n objectKey,\n afterCapture: input.afterCapture,\n dataKeyBase64: Buffer.from(dataKey).toString(\"base64\"),\n aadBase64: Buffer.from(aad).toString(\"base64\"),\n upload,\n },\n timeoutMs: BROWSER_STATE_TRANSFER_TIMEOUT_MS,\n });\n const receipt = parseStateCaptureReceipt(data);\n if (\n receipt.operationId !== operationId ||\n receipt.browserSessionId !== reference.browserSessionId ||\n receipt.controllerGeneration !== reference.controllerGeneration ||\n receipt.objectKey !== objectKey\n ) {\n throw new BrowserControlProtocolError(\n \"browser controller returned another state-capture binding\",\n );\n }\n return receipt;\n }\n\n /** Read-only evidence about a preserved working copy whose controller\n * memory was lost: the exact digest of its bytes and whether it can be\n * adopted. Hashing a large profile can take minutes. */\n async inspectWorkingCopy(\n input: PlacementBrowserWorkingCopyAuthority,\n ): Promise<PlacementBrowserWorkingCopyInspection> {\n const reference = parseReference(input);\n const data = await this.requestJson({\n method: \"POST\",\n path: `/v1/browser-sessions/${reference.browserSessionId}/working-copy/inspection`,\n token: this.adminToken,\n body: workingCopyAuthorityBody(reference, input),\n timeoutMs: BROWSER_STATE_TRANSFER_TIMEOUT_MS,\n });\n return parseWorkingCopyInspection(data, reference);\n }\n\n /** Adopt the exact inspected bytes of a preserved working copy. A lost reply\n * is checked with {@link workingCopyAdoption}. Sending the same operation id\n * again never repeats a side effect: it only settles what that operation\n * already did, under the authority that approved it. */\n async adoptWorkingCopy(\n input: PlacementBrowserWorkingCopyAuthority & { operationId: string; manifestDigest: string },\n ): Promise<PlacementBrowserWorkingCopyAdoption> {\n const reference = parseReference(input);\n const operationId = requireUuid(input.operationId, \"working copy adoption id\");\n const data = await this.requestJson({\n method: \"POST\",\n path: `/v1/browser-sessions/${reference.browserSessionId}/working-copy/adoptions`,\n token: this.adminToken,\n body: {\n ...workingCopyAuthorityBody(reference, input),\n operationId,\n manifestDigest: sha256(input.manifestDigest, \"working copy manifest digest\"),\n },\n timeoutMs: BROWSER_STATE_TRANSFER_TIMEOUT_MS,\n });\n const adoption = parseWorkingCopyAdoption(data, reference, \"current\");\n if (adoption.operationId !== operationId) {\n throw new BrowserControlProtocolError(\"browser controller returned another adoption\");\n }\n return adoption;\n }\n\n /** The recorded state of one adoption, read without changing it. */\n async workingCopyAdoption(\n reference: PlacementBrowserSessionReference,\n operationId: string,\n ): Promise<{ inFlight: boolean; adoption: PlacementBrowserWorkingCopyAdoption | null }> {\n const binding = parseReference(reference);\n const id = requireUuid(operationId, \"working copy adoption id\");\n const data = await this.requestJson({\n method: \"GET\",\n path: `/v1/browser-sessions/${binding.browserSessionId}/working-copy/adoptions/${id}`,\n token: this.adminToken,\n });\n if (!isRecord(data) || typeof data.inFlight !== \"boolean\") {\n throw new BrowserControlProtocolError(\n \"browser controller returned malformed adoption status\",\n );\n }\n const adoption =\n data.adoption === null ? null : parseWorkingCopyAdoption(data.adoption, binding, \"recorded\");\n if (adoption && adoption.operationId !== id) {\n throw new BrowserControlProtocolError(\"browser controller returned another adoption\");\n }\n return { inFlight: data.inFlight, adoption };\n }\n\n /** Revert one unfinished adoption under the browser's current authority:\n * its own directory goes back to the live path and the staged copy is\n * kept. Retrying the same revert finishes one that stopped part way. */\n async revertWorkingCopyAdoption(\n input: PlacementBrowserWorkingCopyAuthority & { operationId: string },\n ): Promise<{ inFlight: boolean; adoption: PlacementBrowserWorkingCopyAdoption | null }> {\n const reference = parseReference(input);\n const id = requireUuid(input.operationId, \"working copy adoption id\");\n const data = await this.requestJson({\n method: \"POST\",\n path: `/v1/browser-sessions/${reference.browserSessionId}/working-copy/adoptions/${id}/revert`,\n token: this.adminToken,\n body: workingCopyAuthorityBody(reference, input),\n timeoutMs: BROWSER_STATE_TRANSFER_TIMEOUT_MS,\n });\n if (!isRecord(data) || typeof data.inFlight !== \"boolean\") {\n throw new BrowserControlProtocolError(\"browser controller returned malformed revert status\");\n }\n const adoption =\n data.adoption === null\n ? null\n : parseWorkingCopyAdoption(data.adoption, reference, \"recorded\");\n if (adoption && adoption.operationId !== id) {\n throw new BrowserControlProtocolError(\"browser controller returned another adoption\");\n }\n return { inFlight: data.inFlight, adoption };\n }\n\n sessionClient(input: {\n reference: PlacementBrowserSessionReference;\n controlToken: string;\n viewToken: string;\n }): BrowserControlSessionClient {\n return new BrowserControlSessionClient(this, input);\n }\n\n computerSessionClient(input: {\n reference: PlacementComputerSessionReference;\n controlToken: string;\n viewToken: string;\n }): ComputerControlSessionClient {\n return new ComputerControlSessionClient(this, input);\n }\n\n async frameStreamUrl(\n reference: PlacementBrowserSessionReference,\n targetId: string,\n stream: {\n format?: \"jpeg\" | \"png\" | undefined;\n quality?: number | undefined;\n maxWidth?: number | undefined;\n maxHeight?: number | undefined;\n everyNthFrame?: number | undefined;\n } = {},\n ): Promise<string> {\n const binding = parseReference(reference);\n if (!this.session.resolveExposedPort) {\n throw new BrowserControlUnsupportedError(\n \"browser placement cannot expose its live-frame port\",\n );\n }\n const endpoint = await this.session.resolveExposedPort(this.port);\n const path = joinControllerPath(\n endpoint.path,\n `/v1/browser-sessions/${binding.browserSessionId}/targets/${encodeURIComponent(requireOpaqueId(targetId, \"target id\"))}/frames`,\n );\n return frameStreamUrlWithOptions(buildStreamUrl({ ...endpoint, path }), stream);\n }\n\n async computerFrameStreamUrl(\n reference: PlacementComputerSessionReference,\n targetId: string,\n stream: {\n format?: \"jpeg\" | \"png\" | undefined;\n quality?: number | undefined;\n maxWidth?: number | undefined;\n maxHeight?: number | undefined;\n everyNthFrame?: number | undefined;\n } = {},\n ): Promise<string> {\n const binding = parseComputerReference(reference);\n if (!this.session.resolveExposedPort) {\n throw new BrowserControlUnsupportedError(\n \"computer placement cannot expose its live-frame port\",\n );\n }\n const endpoint = await this.session.resolveExposedPort(this.port);\n const path = joinControllerPath(\n endpoint.path,\n `/v1/computer-sessions/${binding.computerSessionId}/targets/${encodeURIComponent(requireOpaqueId(targetId, \"computer target id\"))}/frames`,\n );\n return frameStreamUrlWithOptions(buildStreamUrl({ ...endpoint, path }), stream);\n }\n\n async computerRfbStreamUrl(\n reference: PlacementComputerSessionReference,\n targetId: string,\n ): Promise<string> {\n const binding = parseComputerReference(reference);\n if (!this.session.resolveExposedPort) {\n throw new BrowserControlUnsupportedError(\n \"computer placement cannot expose its live RFB port\",\n );\n }\n const endpoint = await this.session.resolveExposedPort(this.port);\n const path = joinControllerPath(\n endpoint.path,\n `/v1/computer-sessions/${binding.computerSessionId}/targets/${encodeURIComponent(requireOpaqueId(targetId, \"computer target id\"))}/rfb`,\n );\n return buildStreamUrl({ ...endpoint, path });\n }\n\n /** Open the browser frame source through the connected-machine relay adapter.\n * Returns null on image-backed placements, which expose browserd directly. */\n async openRelayedFrameStream(input: {\n reference: PlacementBrowserSessionReference;\n targetId: string;\n viewToken: string;\n expiresAt: string;\n stream?: {\n format?: \"jpeg\" | \"png\" | undefined;\n quality?: number | undefined;\n maxWidth?: number | undefined;\n maxHeight?: number | undefined;\n everyNthFrame?: number | undefined;\n };\n }): Promise<{\n channel: StreamChannel;\n endpoint: ExposedPortEndpoint;\n } | null> {\n if (!this.session.openBrowserFrames) return null;\n if (!this.nativeAuthority) {\n throw new BrowserControlProtocolError(\n \"connected browser placement is missing its controller authority scope\",\n );\n }\n const reference = parseReference(input.reference);\n const expiresAtMs = Date.parse(input.expiresAt);\n if (!Number.isSafeInteger(expiresAtMs)) {\n throw new BrowserControlProtocolError(\"browser view grant expiry is invalid\");\n }\n const stream = input.stream ?? {};\n return await this.session.openBrowserFrames({\n scopeId: this.nativeAuthority.scopeId,\n scopeGeneration: this.nativeAuthority.scopeGeneration,\n browserSessionId: reference.browserSessionId,\n controllerGeneration: reference.controllerGeneration,\n targetId: requireOpaqueId(input.targetId, \"target id\"),\n viewToken: requireToken(input.viewToken, \"browser view grant\"),\n expiresAtMs: String(expiresAtMs),\n format: stream.format ?? \"jpeg\",\n quality: boundedInteger(stream.quality ?? 70, 1, 100, \"browser frame quality\"),\n maxWidth: boundedInteger(stream.maxWidth ?? 1_440, 1, 4_096, \"browser frame width\"),\n maxHeight: boundedInteger(stream.maxHeight ?? 900, 1, 4_096, \"browser frame height\"),\n everyNthFrame: boundedInteger(\n stream.everyNthFrame ?? 1,\n 1,\n 60,\n \"browser frame sampling interval\",\n ),\n });\n }\n\n /** Open a ComputerSession frame source through the connected-machine relay.\n * Image-backed placements return null and expose browserd directly. */\n async openRelayedComputerFrameStream(input: {\n reference: PlacementComputerSessionReference;\n targetId: string;\n viewToken: string;\n expiresAt: string;\n stream?: {\n format?: \"jpeg\" | \"png\" | undefined;\n quality?: number | undefined;\n maxWidth?: number | undefined;\n maxHeight?: number | undefined;\n everyNthFrame?: number | undefined;\n };\n }): Promise<{\n channel: StreamChannel;\n endpoint: ExposedPortEndpoint;\n } | null> {\n if (!this.session.openComputerFrames) return null;\n if (!this.nativeAuthority) {\n throw new BrowserControlProtocolError(\n \"connected computer placement is missing its controller authority scope\",\n );\n }\n const reference = parseComputerReference(input.reference);\n const expiresAtMs = Date.parse(input.expiresAt);\n if (!Number.isSafeInteger(expiresAtMs)) {\n throw new BrowserControlProtocolError(\"computer view grant expiry is invalid\");\n }\n const stream = input.stream ?? {};\n return await this.session.openComputerFrames({\n scopeId: this.nativeAuthority.scopeId,\n scopeGeneration: this.nativeAuthority.scopeGeneration,\n computerSessionId: reference.computerSessionId,\n controllerGeneration: reference.controllerGeneration,\n targetId: requireOpaqueId(input.targetId, \"computer target id\"),\n viewToken: requireToken(input.viewToken, \"computer view grant\"),\n expiresAtMs: String(expiresAtMs),\n format: stream.format ?? \"jpeg\",\n quality: boundedInteger(stream.quality ?? 70, 1, 100, \"computer frame quality\"),\n maxWidth: boundedInteger(stream.maxWidth ?? 4_096, 1, 4_096, \"computer frame width\"),\n maxHeight: boundedInteger(stream.maxHeight ?? 4_096, 1, 4_096, \"computer frame height\"),\n everyNthFrame: boundedInteger(\n stream.everyNthFrame ?? 1,\n 1,\n 60,\n \"computer frame sampling interval\",\n ),\n });\n }\n\n async requestForSession(input: {\n method: \"GET\" | \"POST\" | \"DELETE\";\n path: string;\n token: string;\n body?: unknown;\n timeoutMs?: number;\n }): Promise<unknown> {\n return await this.requestJson(input);\n }\n\n async requestBytesForSession(input: {\n method: \"GET\";\n path: string;\n token: string;\n expectedFrameEvidence: ExpectedComputerFrameEvidence;\n timeoutMs?: number;\n }): Promise<ComputerControlFrame> {\n return (await this.requestBytes({ ...input, surface: \"computer\" })) as ComputerControlFrame;\n }\n\n async requestBrowserBytesForSession(input: {\n method: \"GET\";\n path: string;\n token: string;\n expectedFrameEvidence: ExpectedBrowserFrameEvidence;\n timeoutMs?: number;\n }): Promise<BrowserControlFrame> {\n return (await this.requestBytes({ ...input, surface: \"browser\" })) as BrowserControlFrame;\n }\n\n private async requestJson(\n input: {\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n path: string;\n token: string;\n body?: unknown;\n timeoutMs?: number;\n },\n retryNativeEndpoint = true,\n ): Promise<unknown> {\n // Image-backed placements expose browserd through the provider tunnel. Use\n // that actual data plane for control too: one authenticated HTTP request,\n // instead of materializing files and starting curl through the sandbox exec\n // API for every click or key. Connected machines keep their agent transport.\n const requireHostFetch = this.session.requireHostFetchController === true;\n if (this.session.resolveExposedPort && !this.session.ensureBrowserControl) {\n try {\n const endpoint = await this.session.resolveExposedPort(this.port);\n // Lifecycle proxies rewrite Authorization, so a host-side Bearer cannot\n // be both the proxy key and the browserd admin token. Native `/` tunnels\n // and OSEP-0011 signed URIs host-fetch. Unsigned OpenSandbox still uses\n // in-box loopback curl on the lifecycle prefix. Signed Channel B never\n // takes that path. A cached controller-only session has no exec, so\n // host-fetching a lifecycle prefix would 401; throw a retryable\n // transport error so the caller invalidates and provisions.\n const hostFetchAllowed = exposedPortAllowsHostFetch(endpoint);\n const canExec = Boolean(this.session.exec || this.session.execCommand);\n if (!hostFetchAllowed && (requireHostFetch || !canExec)) {\n throw new BrowserControlTransportError(\n requireHostFetch\n ? \"signed Channel B cannot use the lifecycle proxy\"\n : \"cached browser controller endpoint cannot host-fetch a prefixed proxy\",\n );\n }\n if (hostFetchAllowed) {\n try {\n return await requestExposedController(\n endpoint,\n input,\n this.timeoutMs,\n this.session.runtimeMetrics,\n );\n } catch (error) {\n if (\n retryNativeEndpoint &&\n !requireHostFetch &&\n input.method === \"GET\" &&\n error instanceof BrowserControlTransportError\n ) {\n return await this.requestJson(input, false);\n }\n throw error;\n }\n }\n } catch (error) {\n if (\n error instanceof BrowserControlRequestError ||\n error instanceof BrowserControlProtocolError ||\n error instanceof BrowserControlTransportError ||\n error instanceof RangeError\n ) {\n throw error;\n }\n if (requireHostFetch || (!this.session.exec && !this.session.execCommand)) {\n throw new BrowserControlTransportError(\n requireHostFetch\n ? \"signed Channel B host-fetch failed\"\n : \"cached browser controller endpoint is temporarily unavailable\",\n { cause: error },\n );\n }\n // Unsigned lifecycle placements may fall back to in-box curl when port\n // discovery fails. Signed Channel B must not; that would restore the\n // Authorization-rewriting proxy path the signed edge exists to avoid.\n }\n } else if (requireHostFetch) {\n throw new BrowserControlTransportError(\n \"signed Channel B requires a host-fetch controller endpoint\",\n );\n }\n\n const native = await this.requestNative(input, BROWSER_CONTROL_MAX_JSON_BYTES);\n if (native) {\n let text: string;\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(native.body);\n } catch (error) {\n throw new BrowserControlProtocolError(\"browser controller response is not UTF-8\", {\n cause: error,\n });\n }\n return parseEnvelope(text, native.status);\n }\n\n if (\n this.session.execWithInput &&\n (input.body === undefined || Buffer.byteLength(JSON.stringify(input.body)) <= 32 * 1024)\n ) {\n try {\n const response = await this.requestStream(input, BROWSER_CONTROL_MAX_JSON_BYTES);\n return parseEnvelope(\n new TextDecoder(\"utf-8\", { fatal: true }).decode(response.data),\n response.status,\n );\n } catch (error) {\n if (\n retryNativeEndpoint &&\n input.method === \"GET\" &&\n this.nativeAuthority &&\n this.session.ensureBrowserControl &&\n error instanceof BrowserControlTransportError\n ) {\n nativeControllerPorts.delete(nativeControllerKey(this.nativeAuthority));\n await this.controllerPort();\n return await this.requestJson(input, false);\n }\n throw error;\n } finally {\n await this.session.finalizeOpStreamOps?.().catch(() => undefined);\n }\n }\n\n const controllerPort = await this.controllerPort();\n const directory = `${CLIENT_ROOT}/${randomUUID()}`;\n const configPath = `${directory}/curl.conf`;\n const requestPath = `${directory}/request.json`;\n const responsePath = `${directory}/response.json`;\n const statusPath = `${directory}/status`;\n const exitPath = `${directory}/curl-exit`;\n const token = requireToken(input.token, \"browser controller token\");\n const timeoutMs = boundedTimeout(input.timeoutMs ?? this.timeoutMs);\n const url = localControllerUrl(controllerPort, input.path);\n const body = input.body === undefined ? undefined : JSON.stringify(input.body);\n try {\n await runChecked(\n this.session,\n `umask 077; install -d -m 0700 -- ${shellQuote(directory)}; printf '%s\\\\n' ${shellQuote(COMMAND_OK)}`,\n timeoutMs,\n );\n if (body !== undefined) {\n if (Buffer.byteLength(body) > BROWSER_CONTROL_MAX_JSON_BYTES) {\n throw new RangeError(\"browser controller request body is too large\");\n }\n await writePrivateFile(\n this.session,\n { path: requestPath, content: body, createParents: false },\n timeoutMs,\n );\n }\n await writePrivateFile(\n this.session,\n {\n path: configPath,\n content: curlConfig({\n method: input.method,\n url,\n token,\n responsePath,\n ...(body === undefined ? {} : { requestPath }),\n timeoutMs,\n }),\n createParents: false,\n },\n timeoutMs,\n );\n await runChecked(\n this.session,\n `chmod 0600 -- ${shellQuote(configPath)}${body === undefined ? \"\" : ` ${shellQuote(requestPath)}`}; : > ${shellQuote(statusPath)}; curl --disable --config ${shellQuote(configPath)} > ${shellQuote(statusPath)}; curl_exit=$?; printf '%s' \"$curl_exit\" > ${shellQuote(exitPath)}; printf '%s\\\\n' ${shellQuote(COMMAND_OK)}`,\n timeoutMs,\n );\n const curlExit = parseUnsignedInteger(\n await readText(this.session, exitPath, 32, timeoutMs),\n \"curl exit\",\n );\n if (curlExit !== 0) {\n throw new BrowserControlTransportError(\n `browser controller transport failed (curl exit ${curlExit})`,\n );\n }\n const status = parseHttpStatus(await readText(this.session, statusPath, 32, timeoutMs));\n const responseText = await readText(\n this.session,\n responsePath,\n BROWSER_CONTROL_MAX_JSON_BYTES + 1,\n timeoutMs,\n );\n if (Buffer.byteLength(responseText) > BROWSER_CONTROL_MAX_JSON_BYTES) {\n throw new BrowserControlProtocolError(\"browser controller response is too large\");\n }\n return parseEnvelope(responseText, status);\n } catch (error) {\n if (\n error instanceof BrowserControlRequestError ||\n error instanceof BrowserControlProtocolError ||\n error instanceof RangeError\n ) {\n throw error;\n }\n if (error instanceof BrowserControlTransportError) {\n if (\n retryNativeEndpoint &&\n input.method === \"GET\" &&\n this.nativeAuthority &&\n this.session.ensureBrowserControl\n ) {\n nativeControllerPorts.delete(nativeControllerKey(this.nativeAuthority));\n await this.controllerPort();\n return await this.requestJson(input, false);\n }\n throw error;\n }\n throw new BrowserControlTransportError(\"browser controller request transport failed\", {\n cause: error,\n });\n } finally {\n await runBestEffort(this.session, `rm -rf -- ${shellQuote(directory)}`);\n await this.session.finalizeOpStreamOps?.().catch(() => undefined);\n }\n }\n\n private async requestBytes(\n input: FrameRequest,\n retryNativeEndpoint = true,\n ): Promise<ComputerControlFrame | BrowserControlFrame> {\n const requireHostFetch = this.session.requireHostFetchController === true;\n if (this.session.resolveExposedPort && !this.session.ensureBrowserControl) {\n try {\n const endpoint = await this.session.resolveExposedPort(this.port);\n const hostFetchAllowed = exposedPortAllowsHostFetch(endpoint);\n const canExec = Boolean(this.session.exec || this.session.execCommand);\n if (!hostFetchAllowed && (requireHostFetch || !canExec)) {\n throw new BrowserControlTransportError(\n requireHostFetch\n ? \"signed Channel B cannot use the lifecycle proxy\"\n : \"cached browser controller endpoint cannot host-fetch a prefixed proxy\",\n );\n }\n if (hostFetchAllowed) {\n try {\n return await requestExposedControllerBytes(endpoint, input, this.timeoutMs);\n } catch (error) {\n if (\n retryNativeEndpoint &&\n !requireHostFetch &&\n error instanceof BrowserControlTransportError\n ) {\n return await this.requestBytes(input, false);\n }\n throw error;\n }\n }\n } catch (error) {\n if (\n error instanceof BrowserControlRequestError ||\n error instanceof BrowserControlProtocolError ||\n error instanceof BrowserControlTransportError ||\n error instanceof RangeError\n ) {\n throw error;\n }\n if (requireHostFetch || (!this.session.exec && !this.session.execCommand)) {\n throw new BrowserControlTransportError(\n requireHostFetch\n ? \"signed Channel B host-fetch failed\"\n : \"cached browser controller endpoint is temporarily unavailable\",\n { cause: error },\n );\n }\n }\n } else if (requireHostFetch) {\n throw new BrowserControlTransportError(\n \"signed Channel B requires a host-fetch controller endpoint\",\n );\n }\n\n const nativeFrame = await this.requestNative(\n input,\n input.surface === \"browser\" ? 24 * 1024 * 1024 : COMPUTER_SCREENSHOT_MAX_BYTES,\n );\n if (nativeFrame) {\n if (nativeFrame.status < 200 || nativeFrame.status >= 300) {\n parseEnvelope(new TextDecoder().decode(nativeFrame.body), nativeFrame.status);\n throw new BrowserControlProtocolError(\"browser controller image response is invalid\");\n }\n return controllerImageFrame(nativeFrame.body, nativeFrame.headers, input);\n }\n\n if (this.session.execWithInput) {\n try {\n const response = await this.requestStream(\n input,\n input.surface === \"browser\" ? 24 * 1024 * 1024 : COMPUTER_SCREENSHOT_MAX_BYTES,\n );\n if (response.status < 200 || response.status >= 300) {\n parseEnvelope(new TextDecoder().decode(response.data), response.status);\n throw new BrowserControlProtocolError(\"browser controller image response is invalid\");\n }\n return controllerImageFrame(response.data, response.headers, input);\n } catch (error) {\n if (\n retryNativeEndpoint &&\n this.nativeAuthority &&\n this.session.ensureBrowserControl &&\n error instanceof BrowserControlTransportError\n ) {\n nativeControllerPorts.delete(nativeControllerKey(this.nativeAuthority));\n await this.controllerPort();\n return await this.requestBytes(input, false);\n }\n throw error;\n } finally {\n await this.session.finalizeOpStreamOps?.().catch(() => undefined);\n }\n }\n\n const controllerPort = await this.controllerPort();\n const directory = `${CLIENT_ROOT}/${randomUUID()}`;\n const configPath = `${directory}/curl.conf`;\n const responsePath = `${directory}/response.bin`;\n const responseHeadersPath = `${directory}/response.headers`;\n const statusPath = `${directory}/status`;\n const exitPath = `${directory}/curl-exit`;\n const token = requireToken(input.token, \"browser controller token\");\n const timeoutMs = boundedTimeout(input.timeoutMs ?? this.timeoutMs);\n const url = localControllerUrl(controllerPort, input.path);\n try {\n await runChecked(\n this.session,\n `umask 077; install -d -m 0700 -- ${shellQuote(directory)}; printf '%s\\n' ${shellQuote(COMMAND_OK)}`,\n timeoutMs,\n );\n await writePrivateFile(\n this.session,\n {\n path: configPath,\n content: curlConfig({\n method: input.method,\n url,\n token,\n responsePath,\n responseHeadersPath,\n timeoutMs,\n }),\n createParents: false,\n },\n timeoutMs,\n );\n await runChecked(\n this.session,\n `chmod 0600 -- ${shellQuote(configPath)}; : > ${shellQuote(statusPath)}; curl --disable --config ${shellQuote(configPath)} > ${shellQuote(statusPath)}; curl_exit=$?; printf '%s' \"$curl_exit\" > ${shellQuote(exitPath)}; printf '%s\\n' ${shellQuote(COMMAND_OK)}`,\n timeoutMs,\n );\n const curlExit = parseUnsignedInteger(\n await readText(this.session, exitPath, 32, timeoutMs),\n \"curl exit\",\n );\n if (curlExit !== 0) {\n throw new BrowserControlTransportError(\n `browser controller transport failed (curl exit ${curlExit})`,\n );\n }\n const status = parseHttpStatus(await readText(this.session, statusPath, 32, timeoutMs));\n if (status < 200 || status >= 300) {\n const responseText = await readText(\n this.session,\n responsePath,\n BROWSER_CONTROL_MAX_JSON_BYTES + 1,\n timeoutMs,\n );\n parseEnvelope(responseText, status);\n throw new BrowserControlProtocolError(\"browser controller image response is invalid\");\n }\n const headers = parseCurlResponseHeaders(\n await readText(this.session, responseHeadersPath, 64 * 1024, timeoutMs),\n );\n const data = await readBytes(\n this.session,\n responsePath,\n input.surface === \"browser\" ? 24 * 1024 * 1024 : COMPUTER_SCREENSHOT_MAX_BYTES,\n timeoutMs,\n );\n return controllerImageFrame(data, headers, input);\n } catch (error) {\n if (\n error instanceof BrowserControlRequestError ||\n error instanceof BrowserControlProtocolError ||\n error instanceof RangeError\n ) {\n throw error;\n }\n if (error instanceof BrowserControlTransportError) {\n if (retryNativeEndpoint && this.nativeAuthority && this.session.ensureBrowserControl) {\n nativeControllerPorts.delete(nativeControllerKey(this.nativeAuthority));\n await this.controllerPort();\n return await this.requestBytes(input, false);\n }\n throw error;\n }\n throw new BrowserControlTransportError(\"browser controller image transport failed\", {\n cause: error,\n });\n } finally {\n await runBestEffort(this.session, `rm -rf -- ${shellQuote(directory)}`);\n await this.session.finalizeOpStreamOps?.().catch(() => undefined);\n }\n }\n\n private async requestStream(\n input: { method: string; path: string; token: string; body?: unknown; timeoutMs?: number },\n maxBytes: number,\n ): Promise<ReturnType<typeof parseControllerStreamResponse>> {\n const port = await this.controllerPort();\n const request = controllerStreamRequest({\n method: input.method,\n url: localControllerUrl(port, input.path),\n token: requireToken(input.token, \"browser controller token\"),\n ...(input.body === undefined ? {} : { body: JSON.stringify(input.body) }),\n timeoutMs: boundedTimeout(input.timeoutMs ?? this.timeoutMs),\n maxBytes,\n host: this.session.controllerHostOs?.() ?? \"posix\",\n });\n try {\n const result = await this.session.execWithInput!({\n cmd: request.cmd,\n stdin: request.stdin,\n shell: request.shell,\n login: false,\n workdir: placementControllerWorkdir(this.session),\n });\n if (result.exitCode !== 0 || result.stdout === undefined) {\n throw new BrowserControlTransportError(\"browser controller command failed\");\n }\n return parseControllerStreamResponse(result.stdout, request.marker, maxBytes);\n } catch (error) {\n if (error instanceof RangeError || error instanceof BrowserControlTransportError) throw error;\n throw new BrowserControlTransportError(\"browser controller request transport failed\", {\n cause: error,\n });\n }\n }\n\n private async controllerPort(): Promise<number> {\n if (!this.nativeAuthority || !this.session.ensureBrowserControl) return this.port;\n return await this.ensureControllerPort(false);\n }\n\n /** The agent-native transport: one in-process loopback request on the\n * Connected Machine, addressed by authority scope, with no process started.\n * Null when the placement does not serve it; the caller then keeps its\n * command transport. A controller that is not running receives nothing, so\n * it is ensured and the request sent once more whatever its method. */\n private async requestNative(\n input: { method: string; path: string; token: string; body?: unknown; timeoutMs?: number },\n maxResponseBytes: number,\n retry = true,\n ): Promise<{ status: number; headers: Map<string, string>; body: Uint8Array } | null> {\n const authority = this.nativeAuthority;\n if (!authority || !this.session.browserControlHttp || !this.session.ensureBrowserControl) {\n return null;\n }\n const method = input.method;\n if (method !== \"GET\" && method !== \"POST\" && method !== \"PUT\" && method !== \"DELETE\") {\n throw new BrowserControlProtocolError(\"browser controller request method is invalid\");\n }\n // Validates the path exactly as the command transport does.\n localControllerUrl(this.port, input.path);\n const body =\n input.body === undefined ? undefined : new TextEncoder().encode(JSON.stringify(input.body));\n if (body !== undefined && body.byteLength > BROWSER_CONTROL_MAX_JSON_BYTES) {\n throw new RangeError(\"browser controller request body is too large\");\n }\n let outcome: BrowserControlHttpOutcome;\n try {\n outcome = await this.session.browserControlHttp({\n scopeId: authority.scopeId,\n scopeGeneration: authority.scopeGeneration,\n method,\n path: input.path,\n bearerToken: requireToken(input.token, \"browser controller token\"),\n ...(body === undefined ? {} : { body }),\n timeoutMs: boundedTimeout(input.timeoutMs ?? this.timeoutMs),\n maxResponseBytes,\n });\n } catch (error) {\n if (retry && method === \"GET\") {\n await this.ensureControllerPort(true);\n return await this.requestNative(input, maxResponseBytes, false);\n }\n throw new BrowserControlTransportError(\"browser controller request transport failed\", {\n cause: error,\n });\n }\n if (outcome.kind === \"unsupported\") return null;\n if (outcome.kind === \"controller_absent\") {\n if (!retry) throw new BrowserControlTransportError(\"browser controller is not running\");\n await this.ensureControllerPort(true);\n return await this.requestNative(input, maxResponseBytes, false);\n }\n return outcome;\n }\n\n private async ensureControllerPort(replace: boolean): Promise<number> {\n if (!this.nativeAuthority || !this.session.ensureBrowserControl) return this.port;\n const key = nativeControllerKey(this.nativeAuthority);\n if (replace) nativeControllerPorts.delete(key);\n const cached = nativeControllerPorts.get(key);\n if (cached !== undefined) return cached;\n const ensured = await this.session.ensureBrowserControl({\n scopeId: this.nativeAuthority.scopeId,\n scopeGeneration: this.nativeAuthority.scopeGeneration,\n adminToken: this.adminToken,\n allowedOrigins: [],\n });\n const port = boundedPort(ensured.port);\n nativeControllerPorts.set(key, port);\n return port;\n }\n}\n\nfunction nativeControllerKey(authority: { scopeId: string; scopeGeneration: string }): string {\n return `${authority.scopeId}\\u0000${authority.scopeGeneration}`;\n}\n\nexport class BrowserControlSessionClient {\n readonly reference: PlacementBrowserSessionReference;\n private readonly parent: BrowserControlClient;\n private readonly controlToken: string;\n private readonly viewToken: string;\n\n constructor(\n parent: BrowserControlClient,\n input: {\n reference: PlacementBrowserSessionReference;\n controlToken: string;\n viewToken: string;\n },\n ) {\n this.parent = parent;\n this.reference = parseReference(input.reference);\n this.controlToken = requireToken(input.controlToken, \"browser control token\");\n this.viewToken = requireToken(input.viewToken, \"browser view token\");\n }\n\n async listTargets(): Promise<BrowserTargetValue[]> {\n const data = await this.parent.requestForSession({\n method: \"GET\",\n path: this.path(\"targets\"),\n token: this.viewToken,\n });\n if (!Array.isArray(data)) {\n throw new BrowserControlProtocolError(\"browser controller returned malformed targets\");\n }\n return data.map((target) => BrowserTarget.parse(target));\n }\n\n async listDownloads(): Promise<BrowserDownloadListResponseValue> {\n const data = await this.parent.requestForSession({\n method: \"GET\",\n path: this.path(\"downloads\"),\n token: this.viewToken,\n });\n const response = BrowserDownloadListResponse.parse(data);\n if (\n response.browserSessionId !== this.reference.browserSessionId ||\n response.controllerGeneration !== this.reference.controllerGeneration\n ) {\n throw new BrowserControlProtocolError(\n \"browser controller returned downloads for another session binding\",\n );\n }\n return response;\n }\n\n async download(downloadId: string): Promise<BrowserDownloadValue> {\n const id = requireUuid(downloadId, \"download id\");\n const data = await this.parent.requestForSession({\n method: \"GET\",\n path: this.path(`downloads/${id}`),\n token: this.viewToken,\n });\n const download = BrowserDownload.parse(data);\n if (\n download.id !== id ||\n download.browserSessionId !== this.reference.browserSessionId ||\n download.controllerGeneration !== this.reference.controllerGeneration\n ) {\n throw new BrowserControlProtocolError(\"browser controller returned another download binding\");\n }\n return download;\n }\n\n async exportDownload(\n downloadId: string,\n requestInput: BrowserDownloadExportRequestValue,\n ): Promise<BrowserDownloadExportReceiptValue> {\n const id = requireUuid(downloadId, \"download id\");\n const request = BrowserDownloadExportRequest.parse(requestInput);\n if (request.downloadId !== id) {\n throw new BrowserControlProtocolError(\"download export targets another resource\");\n }\n const receipt = BrowserDownloadExportReceipt.parse(\n await this.parent.requestForSession({\n method: \"POST\",\n path: this.path(`downloads/${id}/exports`),\n token: this.controlToken,\n body: request,\n }),\n );\n if (receipt.operationId !== request.operationId || receipt.downloadId !== id) {\n throw new BrowserControlProtocolError(\"browser controller returned another export receipt\");\n }\n return receipt;\n }\n\n async openTarget(url?: string): Promise<BrowserObservationValue> {\n return BrowserObservation.parse(\n await this.parent.requestForSession({\n method: \"POST\",\n path: this.path(\"targets\"),\n token: this.controlToken,\n body: url === undefined ? {} : { url: boundedUrl(url) },\n }),\n );\n }\n\n async openTargetWithInventory(url?: string): Promise<BrowserTargetListResponseValue> {\n let response: BrowserTargetListResponseValue;\n try {\n response = BrowserTargetListResponse.parse(\n await this.parent.requestForSession({\n method: \"POST\",\n path: this.path(\"targets/open-with-inventory\"),\n token: this.controlToken,\n body: url === undefined ? {} : { url: boundedUrl(url) },\n }),\n );\n } catch (error) {\n // An older controller can refuse the new route before dispatch. Never\n // fall back to another mutation after an uncertain open outcome.\n if (\n error instanceof BrowserControlRequestError &&\n error.status === 404 &&\n error.error.code === \"resource_not_found\" &&\n error.error.message === \"route not found\"\n ) {\n throw browserControllerCompatibilityError(\"metadata-only tab opening\");\n }\n throw error;\n }\n if (\n response.browserSessionId !== this.reference.browserSessionId ||\n response.controllerGeneration !== this.reference.controllerGeneration ||\n response.targets.some(\n (target) =>\n target.browserSessionId !== this.reference.browserSessionId ||\n target.controllerGeneration !== this.reference.controllerGeneration,\n )\n ) {\n throw new BrowserControlProtocolError(\n \"browser controller returned inventory for another session binding\",\n );\n }\n return response;\n }\n\n async selectTarget(targetId: string): Promise<BrowserObservationValue> {\n return BrowserObservation.parse(\n await this.parent.requestForSession({\n method: \"POST\",\n path: this.targetPath(targetId, \"select\"),\n token: this.controlToken,\n body: {},\n }),\n );\n }\n\n async closeTarget(targetId: string): Promise<BrowserTargetValue[]> {\n const data = await this.parent.requestForSession({\n method: \"DELETE\",\n path: this.targetPath(targetId),\n token: this.controlToken,\n });\n if (!Array.isArray(data)) {\n throw new BrowserControlProtocolError(\"browser controller returned malformed targets\");\n }\n return data.map((target) => BrowserTarget.parse(target));\n }\n\n async observe(targetId: string): Promise<BrowserObservationValue> {\n return BrowserObservation.parse(\n await this.parent.requestForSession({\n method: \"GET\",\n path: this.targetPath(targetId, \"observation\"),\n token: this.viewToken,\n }),\n );\n }\n\n async targetState(targetId: string): Promise<BrowserTargetStateValue> {\n let state: BrowserTargetStateValue;\n try {\n state = BrowserTargetState.parse(\n await this.parent.requestForSession({\n method: \"GET\",\n path: this.targetPath(targetId, \"state\"),\n token: this.viewToken,\n }),\n );\n } catch (error) {\n // Active Connected Machines can run an older browserd during an API rollout.\n // Only its exact unknown-route response permits the existing observation path.\n // A missing session or target must keep its original error.\n if (\n !(error instanceof BrowserControlRequestError) ||\n error.status !== 404 ||\n error.error.code !== \"resource_not_found\" ||\n error.error.message !== \"route not found\"\n ) {\n throw error;\n }\n const observation = await this.observe(targetId);\n state = BrowserTargetState.parse({\n browserSessionId: observation.browserSessionId,\n controllerGeneration: observation.target.controllerGeneration,\n targetId: observation.target.id,\n targetGeneration: observation.target.targetGeneration,\n documentGeneration: observation.target.documentGeneration,\n frameId: observation.frameId,\n });\n }\n if (\n state.browserSessionId !== this.reference.browserSessionId ||\n state.controllerGeneration !== this.reference.controllerGeneration ||\n state.targetId !== targetId\n ) {\n throw new BrowserControlProtocolError(\"browser target state belongs to another binding\");\n }\n return state;\n }\n\n async readDom(\n targetId: string,\n requestInput: BrowserDomReadRequestValue,\n ): Promise<BrowserDomReadResponseValue> {\n const request = BrowserDomReadRequest.parse(requestInput);\n let data: unknown;\n try {\n data = await this.parent.requestForSession({\n method: \"POST\",\n path: this.targetPath(targetId, \"dom-read\"),\n token: this.viewToken,\n body: request,\n });\n } catch (error) {\n // Protocol v1 predates focused DOM reads. Distinguish that exact legacy\n // route response from a missing target/session; neither is safe to retry.\n if (\n error instanceof BrowserControlRequestError &&\n error.status === 404 &&\n error.error.code === \"resource_not_found\" &&\n error.error.message === \"route not found\"\n ) {\n throw browserControllerCompatibilityError(\"focused DOM reads\");\n }\n throw error;\n }\n const result = BrowserDomReadResponse.parse(data);\n if (\n result.browserSessionId !== this.reference.browserSessionId ||\n result.controllerGeneration !== this.reference.controllerGeneration ||\n result.targetId !== targetId ||\n result.targetGeneration !== request.expectedTargetGeneration ||\n result.documentGeneration !== request.expectedDocumentGeneration ||\n result.frameId !== request.expectedFrameId ||\n result.kind !== request.kind\n ) {\n throw new BrowserControlProtocolError(\"browser DOM read belongs to another binding\");\n }\n return result;\n }\n\n async capture(\n targetId: string,\n options: BrowserControlScreenshotOptions = {},\n ): Promise<BrowserControlFrame> {\n const query = new URLSearchParams({\n format: options.format ?? \"jpeg\",\n quality: String(boundedInteger(options.quality ?? 55, 1, 100, \"browser screenshot quality\")),\n });\n if (options.format !== undefined && options.format !== \"jpeg\" && options.format !== \"png\") {\n throw new RangeError(\"browser screenshot format is invalid\");\n }\n if (options.fullPage !== undefined) {\n if (typeof options.fullPage !== \"boolean\") {\n throw new RangeError(\"browser screenshot fullPage is invalid\");\n }\n query.set(\"fullPage\", String(options.fullPage));\n }\n return await this.parent.requestBrowserBytesForSession({\n method: \"GET\",\n path: this.targetPath(targetId, `screenshot?${query}`),\n token: this.viewToken,\n expectedFrameEvidence: {\n browserSessionId: this.reference.browserSessionId,\n controllerGeneration: this.reference.controllerGeneration,\n targetId: requireOpaqueId(targetId, \"browser target id\"),\n },\n });\n }\n\n async readClipboard(): Promise<BrowserClipboardValue> {\n return BrowserClipboard.parse(\n await this.parent.requestForSession({\n method: \"GET\",\n path: this.path(\"clipboard\"),\n token: this.viewToken,\n }),\n );\n }\n\n async action(command: BrowserActionCommandValue): Promise<BrowserActionReceiptValue> {\n const parsed = BrowserActionCommand.parse(command);\n if (\n parsed.browserSessionId !== this.reference.browserSessionId ||\n parsed.controllerGeneration !== this.reference.controllerGeneration\n ) {\n throw new BrowserControlProtocolError(\"browser action targets another controller binding\");\n }\n let data: unknown;\n try {\n data = await this.parent.requestForSession({\n method: \"POST\",\n // Controllers that predate resolved targets ignore this parameter.\n path: `${this.path(\"actions\")}?${BROWSER_ACTION_RECEIPT_TARGETS_PARAMETER}=1`,\n token: this.controlToken,\n body: parsed,\n });\n } catch (error) {\n // This command already passed the release's schema. The controller's\n // exact parser rejection proves a schema mismatch, not invalid tool use.\n // Do not replay the action, restart the controller, or lose live tabs.\n if (\n error instanceof BrowserControlRequestError &&\n error.status === 400 &&\n error.error.code === \"invalid_action\" &&\n error.error.message === \"browser action is invalid\"\n ) {\n throw browserControllerCompatibilityError(\"this browser action\");\n }\n throw error;\n }\n return BrowserActionReceipt.parse(data);\n }\n\n /** API-broker-only file authority path. Signed read URLs are materialized by\n * browserd and never become part of the public action or durable receipt. */\n async stageWorkspaceFiles(\n request: BrowserWorkspaceFileStageRequestValue,\n ): Promise<BrowserWorkspaceFileStageResponseValue> {\n const parsed = BrowserWorkspaceFileStageRequest.parse(request);\n return BrowserWorkspaceFileStageResponse.parse(\n await this.parent.requestForSession({\n method: \"POST\",\n path: this.path(`operations/${parsed.operationId}/workspace-files`),\n token: this.controlToken,\n body: parsed,\n timeoutMs: BROWSER_STATE_TRANSFER_TIMEOUT_MS,\n }),\n );\n }\n\n async receipt(operationId: string): Promise<BrowserActionReceiptValue> {\n return BrowserActionReceipt.parse(\n await this.parent.requestForSession({\n method: \"GET\",\n path: this.path(`operations/${requireUuid(operationId, \"operation id\")}`),\n token: this.viewToken,\n }),\n );\n }\n\n /** Controller-private passkey exchange (design §10B.4): load the\n * principal's passkeys into every authenticator and pull registration and\n * assertion events. Controllers that predate it answer 404. */\n async passkeySync(\n request: BrowserPasskeySyncRequestValue,\n ): Promise<BrowserPasskeySyncResponseValue> {\n const parsed = BrowserPasskeySyncRequest.parse(request);\n if (\n parsed.browserSessionId !== this.reference.browserSessionId ||\n parsed.controllerGeneration !== this.reference.controllerGeneration\n ) {\n throw new BrowserControlProtocolError(\"passkey sync targets another controller binding\");\n }\n return BrowserPasskeySyncResponse.parse(\n await this.parent.requestForSession({\n method: \"POST\",\n path: this.path(\"passkeys/sync\"),\n token: this.controlToken,\n body: parsed,\n }),\n );\n }\n\n /** API-broker-only provider-auth path. The interactive URL response is\n * deliberately not exposed by any model-facing SDK or Codemode facade. */\n async externalAuth(\n commandInput: BrowserExternalAuthCommandValue,\n ): Promise<BrowserExternalAuthResultValue> {\n const command = BrowserExternalAuthCommand.parse(commandInput);\n if (\n command.browserSessionId !== this.reference.browserSessionId ||\n command.controllerGeneration !== this.reference.controllerGeneration\n ) {\n throw new BrowserControlProtocolError(\n \"external authentication targets another browser controller binding\",\n );\n }\n return BrowserExternalAuthResult.parse(\n await this.parent.requestForSession({\n method: \"POST\",\n path: this.path(\"external-auth\"),\n token: this.controlToken,\n body: command,\n }),\n );\n }\n\n async diagnostics(\n targetId: string,\n options: {\n kinds?: readonly BrowserDiagnosticKind[];\n afterSequence?: number;\n limit?: number;\n } = {},\n ): Promise<BrowserDiagnosticBatchValue> {\n const query = new URLSearchParams();\n if (options.kinds) query.set(\"kinds\", [...new Set(options.kinds)].join(\",\"));\n if (options.afterSequence !== undefined) {\n query.set(\n \"after\",\n nonnegativeSafeInteger(options.afterSequence, \"diagnostic cursor\").toString(),\n );\n }\n if (options.limit !== undefined) {\n const limit = positiveSafeInteger(options.limit, \"diagnostic limit\");\n if (limit > 1_000) throw new RangeError(\"diagnostic limit is too large\");\n query.set(\"limit\", limit.toString());\n }\n const suffix = query.size === 0 ? \"\" : `?${query.toString()}`;\n return BrowserDiagnosticBatch.parse(\n await this.parent.requestForSession({\n method: \"GET\",\n path: `${this.targetPath(targetId, \"diagnostics\")}${suffix}`,\n token: this.viewToken,\n }),\n );\n }\n\n private path(suffix: string): string {\n return `/v1/browser-sessions/${this.reference.browserSessionId}/${suffix}`;\n }\n\n private targetPath(targetId: string, suffix?: string): string {\n const base = this.path(`targets/${encodeURIComponent(requireOpaqueId(targetId, \"target id\"))}`);\n return suffix ? `${base}/${suffix}` : base;\n }\n}\n\nexport class ComputerControlSessionClient {\n readonly reference: PlacementComputerSessionReference;\n private readonly parent: BrowserControlClient;\n private readonly controlToken: string;\n private readonly viewToken: string;\n\n constructor(\n parent: BrowserControlClient,\n input: {\n reference: PlacementComputerSessionReference;\n controlToken: string;\n viewToken: string;\n },\n ) {\n this.parent = parent;\n this.reference = parseComputerReference(input.reference);\n this.controlToken = requireToken(input.controlToken, \"computer control token\");\n this.viewToken = requireToken(input.viewToken, \"computer view token\");\n }\n\n async listTargets(): Promise<ComputerTargetValue[]> {\n const data = await this.parent.requestForSession({\n method: \"GET\",\n path: this.path(\"targets\"),\n token: this.viewToken,\n });\n if (!Array.isArray(data)) {\n throw new BrowserControlProtocolError(\n \"interaction controller returned malformed computer targets\",\n );\n }\n return data.map((target) => ComputerTarget.parse(target));\n }\n\n async observe(targetId: string): Promise<ComputerObservationValue> {\n return ComputerObservation.parse(\n await this.parent.requestForSession({\n method: \"GET\",\n path: this.targetPath(targetId, \"observation\"),\n token: this.viewToken,\n }),\n );\n }\n\n async capture(\n targetId: string,\n options: {\n format?: \"jpeg\" | \"png\";\n quality?: number;\n maxWidth?: number;\n maxHeight?: number;\n } = {},\n ): Promise<ComputerControlFrame> {\n const query = new URLSearchParams();\n if (options.format !== undefined) query.set(\"format\", options.format);\n if (options.quality !== undefined) query.set(\"quality\", String(options.quality));\n if (options.maxWidth !== undefined) query.set(\"maxWidth\", String(options.maxWidth));\n if (options.maxHeight !== undefined) query.set(\"maxHeight\", String(options.maxHeight));\n const suffix = query.size > 0 ? `screenshot?${query}` : \"screenshot\";\n return await this.parent.requestBytesForSession({\n method: \"GET\",\n path: this.targetPath(targetId, suffix),\n token: this.viewToken,\n expectedFrameEvidence: {\n computerSessionId: this.reference.computerSessionId,\n controllerGeneration: this.reference.controllerGeneration,\n targetId: requireOpaqueId(targetId, \"computer target id\"),\n },\n });\n }\n\n async readClipboard(): Promise<ComputerClipboardValue> {\n return ComputerClipboard.parse(\n await this.parent.requestForSession({\n method: \"GET\",\n path: this.path(\"clipboard\"),\n token: this.viewToken,\n }),\n );\n }\n\n async nativeCall(command: ComputerNativeCommand): Promise<ComputerNativeReceipt> {\n const parsed = ComputerNativeCommand.parse(command);\n if (\n parsed.computerSessionId !== this.reference.computerSessionId ||\n parsed.controllerGeneration !== this.reference.controllerGeneration\n )\n throw new BrowserControlProtocolError(\"native call targets another controller binding\");\n return ComputerNativeReceipt.parse(\n await this.parent.requestForSession({\n method: \"POST\",\n path: this.path(\"native-calls\"),\n token: this.controlToken,\n body: parsed,\n }),\n );\n }\n\n async action(command: ComputerActionCommandValue): Promise<ComputerActionReceiptValue> {\n const parsed = ComputerActionCommand.parse(command);\n if (\n parsed.computerSessionId !== this.reference.computerSessionId ||\n parsed.controllerGeneration !== this.reference.controllerGeneration\n ) {\n throw new BrowserControlProtocolError(\"computer action targets another controller binding\");\n }\n return ComputerActionReceipt.parse(\n await this.parent.requestForSession({\n method: \"POST\",\n path: this.path(\"actions\"),\n token: this.controlToken,\n body: parsed,\n }),\n );\n }\n\n async receipt(operationId: string): Promise<ComputerOperationReceipt> {\n return ComputerOperationReceipt.parse(\n await this.parent.requestForSession({\n method: \"GET\",\n path: this.path(`operations/${requireUuid(operationId, \"operation id\")}`),\n token: this.viewToken,\n }),\n );\n }\n\n async heartbeat(): Promise<void> {\n const data = await this.parent.requestForSession({\n method: \"POST\",\n path: this.path(\"heartbeat\"),\n token: this.controlToken,\n body: {},\n });\n if (!isRecord(data) || data.alive !== true) {\n throw new BrowserControlProtocolError(\n \"interaction controller returned malformed computer heartbeat\",\n );\n }\n }\n\n private path(suffix: string): string {\n return `/v1/computer-sessions/${this.reference.computerSessionId}/${suffix}`;\n }\n\n private targetPath(targetId: string, suffix?: string): string {\n const base = this.path(\n `targets/${encodeURIComponent(requireOpaqueId(targetId, \"computer target id\"))}`,\n );\n return suffix ? `${base}/${suffix}` : base;\n }\n}\n\nfunction curlConfig(input: {\n method: string;\n url: string;\n token: string;\n responsePath: string;\n responseHeadersPath?: string;\n requestPath?: string;\n timeoutMs: number;\n}): string {\n const seconds = Math.max(1, Math.ceil(input.timeoutMs / 1_000));\n return [\n \"silent\",\n \"show-error\",\n `noproxy = ${curlConfigQuote(\"*\")}`,\n `connect-timeout = ${Math.min(seconds, 15)}`,\n `max-time = ${seconds}`,\n `request = ${curlConfigQuote(input.method)}`,\n `url = ${curlConfigQuote(input.url)}`,\n `header = ${curlConfigQuote(`Authorization: Bearer ${input.token}`)}`,\n ...(input.requestPath\n ? [\n `header = ${curlConfigQuote(\"Content-Type: application/json\")}`,\n `data-binary = ${curlConfigQuote(`@${input.requestPath}`)}`,\n ]\n : []),\n `output = ${curlConfigQuote(input.responsePath)}`,\n ...(input.responseHeadersPath\n ? [`dump-header = ${curlConfigQuote(input.responseHeadersPath)}`]\n : []),\n `write-out = ${curlConfigQuote(\"%{http_code}\")}`,\n \"\",\n ].join(\"\\n\");\n}\n\nfunction joinControllerPath(endpointPath: string | undefined, requestPath: string): string {\n try {\n return joinExposedPortPath(endpointPath, requestPath);\n } catch (error) {\n if (error instanceof StreamPortUnavailableError) {\n throw new BrowserControlProtocolError(error.message);\n }\n throw error;\n }\n}\n\nfunction exposedPortHeaders(endpoint: ExposedPortEndpoint): Record<string, string> {\n const raw = endpoint.headers;\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return {};\n const headers: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {\n if (typeof key !== \"string\" || typeof value !== \"string\") continue;\n if (key.toLowerCase() === \"authorization\") continue;\n headers[key] = value;\n }\n return headers;\n}\n\nasync function requestExposedController(\n endpoint: ExposedPortEndpoint,\n input: {\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n path: string;\n token: string;\n body?: unknown;\n timeoutMs?: number;\n },\n defaultTimeoutMs: number,\n metrics?: {\n onOpenSandboxSignedEndpoint?: (input: {\n outcome: \"minted\" | \"mint_failed\" | \"host_fetch_unauthorized\";\n port: number;\n }) => void;\n },\n): Promise<unknown> {\n const token = requireToken(input.token, \"browser controller token\");\n const timeoutMs = boundedTimeout(input.timeoutMs ?? defaultTimeoutMs);\n const streamUrl = exposedControllerUrl(endpoint, input.path);\n streamUrl.protocol = streamUrl.protocol === \"wss:\" ? \"https:\" : \"http:\";\n const body = input.body === undefined ? undefined : JSON.stringify(input.body);\n if (body !== undefined && Buffer.byteLength(body) > BROWSER_CONTROL_MAX_JSON_BYTES) {\n throw new RangeError(\"browser controller request body is too large\");\n }\n const response = await controllerTransport(\n async () =>\n await fetch(streamUrl, {\n method: input.method,\n headers: {\n ...exposedPortHeaders(endpoint),\n authorization: `Bearer ${token}`,\n ...(body === undefined ? {} : { \"content-type\": \"application/json\" }),\n },\n ...(body === undefined ? {} : { body }),\n redirect: \"manual\",\n signal: AbortSignal.timeout(timeoutMs),\n }),\n );\n const responseText = await controllerTransport(async () => await response.text());\n if (Buffer.byteLength(responseText) > BROWSER_CONTROL_MAX_JSON_BYTES) {\n throw new BrowserControlProtocolError(\"browser controller response is too large\");\n }\n rejectProviderGatewayResponse(responseText, response.status);\n if (\n (response.status === 401 || response.status === 403) &&\n !looksLikeBrowserControlEnvelope(responseText)\n ) {\n const signed = parseOpenSandboxSignedUriPath(endpoint.path ?? \"\");\n if (signed) {\n try {\n metrics?.onOpenSandboxSignedEndpoint?.({\n outcome: \"host_fetch_unauthorized\",\n port: signed.port,\n });\n } catch {\n /* metrics must not affect Channel B */\n }\n }\n throw new BrowserControlTransportError(`browser controller returned HTTP ${response.status}`);\n }\n return parseEnvelope(responseText, response.status);\n}\n\nasync function requestExposedControllerBytes(\n endpoint: ExposedPortEndpoint,\n input: FrameRequest,\n defaultTimeoutMs: number,\n): Promise<ComputerControlFrame | BrowserControlFrame> {\n const token = requireToken(input.token, \"browser controller token\");\n const timeoutMs = boundedTimeout(input.timeoutMs ?? defaultTimeoutMs);\n const streamUrl = exposedControllerUrl(endpoint, input.path);\n streamUrl.protocol = streamUrl.protocol === \"wss:\" ? \"https:\" : \"http:\";\n const response = await controllerTransport(\n async () =>\n await fetch(streamUrl, {\n method: input.method,\n headers: {\n ...exposedPortHeaders(endpoint),\n authorization: `Bearer ${token}`,\n accept: \"image/jpeg, image/png\",\n },\n redirect: \"manual\",\n signal: AbortSignal.timeout(timeoutMs),\n }),\n );\n if (!response.ok) {\n const responseText = await controllerTransport(async () => await response.text());\n if (Buffer.byteLength(responseText) > BROWSER_CONTROL_MAX_JSON_BYTES) {\n throw new BrowserControlProtocolError(\"browser controller response is too large\");\n }\n rejectProviderGatewayResponse(responseText, response.status);\n parseEnvelope(responseText, response.status);\n throw new BrowserControlProtocolError(\"browser controller image response is invalid\");\n }\n const declaredLength = Number(response.headers.get(\"content-length\"));\n const maxBytes = input.surface === \"browser\" ? 24 * 1024 * 1024 : COMPUTER_SCREENSHOT_MAX_BYTES;\n if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {\n await response.body?.cancel(\"frame exceeds its byte bound\").catch(() => undefined);\n throw new RangeError(\"frame exceeds its byte bound\");\n }\n const data = await controllerTransport(\n async () => await readBoundedFrameResponse(response, maxBytes),\n );\n return controllerImageFrame(data, response.headers, input);\n}\n\nasync function controllerTransport<T>(readOrDispatch: () => Promise<T>): Promise<T> {\n try {\n return await readOrDispatch();\n } catch (error) {\n if (\n error instanceof BrowserControlProtocolError ||\n error instanceof BrowserControlTransportError ||\n error instanceof RangeError\n ) {\n throw error;\n }\n // Fetch or response-body failure cannot prove the controller did not\n // execute a mutation. Keep it typed so endpoint discovery's in-box fallback\n // cannot replay an already-dispatched request.\n throw new BrowserControlTransportError(\"browser controller host-fetch failed\", {\n cause: error,\n });\n }\n}\n\nasync function readBoundedFrameResponse(response: Response, maxBytes: number): Promise<Uint8Array> {\n if (!response.body) throw new BrowserControlProtocolError(\"browser controller image is empty\");\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > maxBytes) {\n await reader.cancel(\"frame exceeds its byte bound\").catch(() => undefined);\n throw new RangeError(\"frame exceeds its byte bound\");\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n const data = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) {\n data.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return data;\n}\n\nfunction controllerImageFrame(\n data: Uint8Array,\n headers: { get(name: string): string | null | undefined },\n input: FrameRequest,\n): ComputerControlFrame | BrowserControlFrame {\n return input.surface === \"browser\"\n ? browserControlFrame(data, headers, input.expectedFrameEvidence)\n : computerControlFrame(data, headers, input.expectedFrameEvidence);\n}\n\nfunction browserControlFrame(\n data: Uint8Array,\n headers: { get(name: string): string | null | undefined },\n expected: ExpectedBrowserFrameEvidence,\n): BrowserControlFrame {\n if (data.byteLength < 1 || data.byteLength > 24 * 1024 * 1024) {\n throw new RangeError(\"browser frame exceeds its byte bound\");\n }\n const get = (name: string): string | null => headers.get(name.toLowerCase()) ?? null;\n const mediaType = get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n if (mediaType !== \"image/jpeg\" && mediaType !== \"image/png\") {\n throw new BrowserControlProtocolError(\"browser frame media type is invalid\");\n }\n const metadataHeader = get(\"x-opengeni-browser-frame\");\n if (\n !metadataHeader ||\n metadataHeader.length > 64 * 1024 ||\n !/^[A-Za-z0-9_-]+$/u.test(metadataHeader)\n ) {\n throw new BrowserControlProtocolError(\"browser frame metadata is invalid\");\n }\n let metadata: BrowserFrameMetadata;\n try {\n metadata = parseBrowserFrameMetadata(\n JSON.parse(Buffer.from(metadataHeader, \"base64url\").toString(\"utf8\")),\n );\n } catch {\n throw new BrowserControlProtocolError(\"browser frame metadata is invalid\");\n }\n if (\n metadata.browserSessionId !== expected.browserSessionId ||\n metadata.controllerGeneration !== expected.controllerGeneration ||\n metadata.targetId !== expected.targetId ||\n metadata.mediaType !== mediaType\n ) {\n throw new BrowserControlProtocolError(\"browser frame evidence does not match its request\");\n }\n return { data, mediaType, metadataHeader, metadata };\n}\n\nfunction computerControlFrame(\n data: Uint8Array,\n headers: { get(name: string): string | null | undefined },\n expected: ExpectedComputerFrameEvidence,\n): ComputerControlFrame {\n if (data.byteLength < 1 || data.byteLength > COMPUTER_SCREENSHOT_MAX_BYTES) {\n throw new RangeError(\"computer frame exceeds its byte bound\");\n }\n const get = (name: string): string | null => headers.get(name.toLowerCase()) ?? null;\n const mediaType = get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n if (mediaType !== \"image/jpeg\" && mediaType !== \"image/png\") {\n throw new BrowserControlProtocolError(\"computer frame media type is invalid\");\n }\n const metadataHeader = get(\"x-opengeni-computer-frame\");\n if (\n !metadataHeader ||\n metadataHeader.length > 32 * 1024 ||\n !/^[A-Za-z0-9_-]+$/u.test(metadataHeader)\n ) {\n throw new BrowserControlProtocolError(\"computer frame metadata is invalid\");\n }\n return validateComputerControlFrameEvidence({ data, mediaType, metadataHeader }, expected);\n}\n\nexport function validateComputerControlFrameEvidence(\n frame: Pick<ComputerControlFrame, \"data\" | \"mediaType\" | \"metadataHeader\">,\n expected: ExpectedComputerFrameEvidence,\n): ComputerControlFrame {\n const metadata = decodeComputerControlFrameMetadataHeader(frame.metadataHeader);\n if (metadata.computerSessionId !== expected.computerSessionId) {\n throw new ComputerFrameEvidenceMismatchError(\"frame_session_mismatch\");\n }\n if (metadata.targetId !== expected.targetId) {\n throw new ComputerFrameEvidenceMismatchError(\"frame_target_mismatch\");\n }\n if (metadata.controllerGeneration !== expected.controllerGeneration) {\n throw new ComputerFrameEvidenceMismatchError(\"frame_controller_mismatch\");\n }\n if (metadata.mediaType !== frame.mediaType) {\n throw new ComputerFrameEvidenceMismatchError(\"frame_media_mismatch\");\n }\n const digest = createHash(\"sha256\").update(frame.data).digest(\"hex\");\n if (metadata.sha256 !== digest) {\n throw new ComputerFrameEvidenceMismatchError(\"frame_digest_mismatch\");\n }\n return { ...frame, metadata };\n}\n\nexport function decodeComputerControlFrameMetadataHeader(\n value: string,\n): ComputerControlFrameMetadata {\n if (!value || value.length > 32 * 1024 || !/^[A-Za-z0-9_-]+$/u.test(value)) {\n throw new BrowserControlProtocolError(\"computer frame metadata is invalid\");\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(Buffer.from(value, \"base64url\").toString(\"utf8\"));\n } catch {\n throw new BrowserControlProtocolError(\"computer frame metadata is invalid\");\n }\n if (!isRecord(decoded)) {\n throw new BrowserControlProtocolError(\"computer frame metadata is invalid\");\n }\n const allowed = new Set([\n \"frameId\",\n \"computerSessionId\",\n \"controllerGeneration\",\n \"targetId\",\n \"targetGeneration\",\n \"sequence\",\n \"mediaType\",\n \"width\",\n \"height\",\n \"capturedAt\",\n \"sha256\",\n ]);\n if (Object.keys(decoded).some((key) => !allowed.has(key))) {\n throw new BrowserControlProtocolError(\"computer frame metadata is invalid\");\n }\n for (const key of [\n \"frameId\",\n \"computerSessionId\",\n \"controllerGeneration\",\n \"targetId\",\n \"targetGeneration\",\n \"mediaType\",\n \"capturedAt\",\n ] as const) {\n const item = decoded[key];\n const maxBytes = key === \"targetId\" ? 512 : key === \"capturedAt\" ? 128 : 256;\n if (typeof item !== \"string\" || item.length < 1 || Buffer.byteLength(item) > maxBytes) {\n throw new BrowserControlProtocolError(\"computer frame metadata is invalid\");\n }\n }\n if (typeof decoded.sha256 !== \"string\" || !SHA256_PATTERN.test(decoded.sha256)) {\n throw new ComputerFrameEvidenceMismatchError(\"frame_digest_mismatch\");\n }\n if (\n !Number.isSafeInteger(decoded.sequence) ||\n Number(decoded.sequence) < 0 ||\n !boundedComputerFrameDimension(decoded.width, decoded.height)\n ) {\n throw new BrowserControlProtocolError(\"computer frame metadata is invalid\");\n }\n if (decoded.mediaType !== \"image/jpeg\" && decoded.mediaType !== \"image/png\") {\n throw new BrowserControlProtocolError(\"computer frame metadata is invalid\");\n }\n if (!isUuidString(decoded.computerSessionId)) {\n throw new BrowserControlProtocolError(\"computer frame metadata is invalid\");\n }\n const controllerGeneration = decoded.controllerGeneration;\n if (\n typeof controllerGeneration !== \"string\" ||\n !/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u.test(controllerGeneration)\n ) {\n throw new BrowserControlProtocolError(\"computer frame metadata is invalid\");\n }\n const capturedAt = decoded.capturedAt;\n if (typeof capturedAt !== \"string\" || !Number.isFinite(new Date(capturedAt).valueOf())) {\n throw new BrowserControlProtocolError(\"computer frame metadata is invalid\");\n }\n return decoded as ComputerControlFrameMetadata;\n}\n\nfunction boundedComputerFrameDimension(width: unknown, height: unknown): boolean {\n return (\n Number.isSafeInteger(width) &&\n Number.isSafeInteger(height) &&\n Number(width) > 0 &&\n Number(height) > 0 &&\n Number(width) <= 32_768 &&\n Number(height) <= 32_768 &&\n Number(width) * Number(height) <= 100_000_000\n );\n}\n\nfunction isUuidString(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(value)\n );\n}\n\nfunction exposedControllerUrl(endpoint: ExposedPortEndpoint, requestPath: string): URL {\n const separator = requestPath.indexOf(\"?\");\n const path = separator === -1 ? requestPath : requestPath.slice(0, separator);\n const requestQuery = separator === -1 ? \"\" : requestPath.slice(separator + 1);\n const url = new URL(\n buildStreamUrl({ ...endpoint, path: joinControllerPath(endpoint.path, path) }),\n );\n for (const [name, value] of new URLSearchParams(requestQuery)) {\n url.searchParams.append(name, value);\n }\n return url;\n}\n\nfunction parseCurlResponseHeaders(value: string): Map<string, string> {\n const headers = new Map<string, string>();\n for (const line of value.split(/\\r?\\n/u)) {\n if (/^HTTP\\//u.test(line)) {\n headers.clear();\n continue;\n }\n const separator = line.indexOf(\":\");\n if (separator <= 0) continue;\n const name = line.slice(0, separator).trim().toLowerCase();\n const headerValue = line.slice(separator + 1).trim();\n if (name && headerValue) headers.set(name, headerValue);\n }\n return headers;\n}\n\nfunction looksLikeBrowserControlEnvelope(body: string): boolean {\n try {\n const value: unknown = JSON.parse(body);\n return isRecord(value) && value.protocolVersion === BROWSER_CONTROL_PROTOCOL_VERSION;\n } catch {\n return false;\n }\n}\n\nfunction rejectProviderGatewayResponse(body: string, status: number): void {\n // A tunnel's transient upstream failure is not a browserd protocol response.\n // Preserve browserd envelopes, including their semantic retry policy. This\n // transport classification cannot prove that a mutation was not dispatched.\n if ([502, 503, 504].includes(status) && !looksLikeBrowserControlEnvelope(body)) {\n throw new BrowserControlTransportError(`browser controller returned HTTP ${status}`);\n }\n}\n\nfunction parseEnvelope(body: string, status: number): unknown {\n let value: unknown;\n try {\n value = JSON.parse(body);\n } catch {\n throw new BrowserControlProtocolError(\"browser controller response is invalid JSON\");\n }\n if (!isRecord(value) || value.protocolVersion !== BROWSER_CONTROL_PROTOCOL_VERSION) {\n throw new BrowserControlProtocolError(\"browser controller protocol version is invalid\");\n }\n if (value.ok === true && status >= 200 && status < 300 && \"data\" in value) return value.data;\n if (value.ok === false && status >= 400 && status <= 599) {\n const parsed = InteractionError.safeParse(value.error);\n if (parsed.success) throw new BrowserControlRequestError(status, parsed.data);\n }\n throw new BrowserControlProtocolError(\"browser controller response envelope is invalid\");\n}\n\nfunction localControllerUrl(port: number, path: string): string {\n if (!path.startsWith(\"/\") || path.includes(\"\\0\") || path.includes(\"#\")) {\n throw new BrowserControlProtocolError(\"browser controller request path is invalid\");\n }\n return `http://127.0.0.1:${port}${path}`;\n}\n\nfunction parseReference(value: unknown): PlacementBrowserSessionReference {\n if (!isRecord(value)) throw new BrowserControlProtocolError(\"browser session binding is invalid\");\n return {\n browserSessionId: requireUuid(value.browserSessionId, \"browser session id\"),\n controllerGeneration: requireGeneration(value.controllerGeneration),\n };\n}\n\n/** A create's tab inventory is a convenience: an older controller omits it,\n * and an inventory that does not validate, or that belongs to another\n * binding, is dropped rather than failing a browser that did launch. */\nfunction creationTargets(\n value: unknown,\n reference: PlacementBrowserSessionReference,\n): { targets?: BrowserTargetValue[] } {\n if (!Array.isArray(value) || value.length > 10_000) return {};\n const targets: BrowserTargetValue[] = [];\n for (const entry of value) {\n const parsed = BrowserTarget.safeParse(entry);\n if (\n !parsed.success ||\n parsed.data.browserSessionId !== reference.browserSessionId ||\n parsed.data.controllerGeneration !== reference.controllerGeneration\n )\n return {};\n targets.push(parsed.data);\n }\n return { targets };\n}\n\nfunction parseComputerReference(value: unknown): PlacementComputerSessionReference {\n if (!isRecord(value)) {\n throw new BrowserControlProtocolError(\"computer session binding is invalid\");\n }\n return {\n computerSessionId: requireUuid(value.computerSessionId, \"computer session id\"),\n controllerGeneration: requireGeneration(value.controllerGeneration),\n };\n}\n\nfunction placementBrowserTransport(input: PlacementBrowserTransport): PlacementBrowserTransport {\n if (input.kind === \"managed\") {\n if (\n input.engine !== undefined &&\n input.engine !== \"chromium\" &&\n input.engine !== \"lightpanda\"\n ) {\n throw new BrowserControlProtocolError(\"managed browser engine is invalid\");\n }\n if (input.ephemeralPartition !== undefined && !SHA256_PATTERN.test(input.ephemeralPartition))\n throw new Error(\"ephemeral browser partition is invalid\");\n return {\n kind: \"managed\",\n engine: input.engine ?? \"chromium\",\n ...(input.ephemeralPartition ? { ephemeralPartition: input.ephemeralPartition } : {}),\n };\n }\n if (input.kind === \"external_provider\") {\n if (input.providerId !== \"browserbase\" && input.providerId !== \"kernel\") {\n throw new BrowserControlProtocolError(\"external browser provider is unsupported\");\n }\n const endpoint = input.authority.endpoint\n ? boundedHttpUrl(input.authority.endpoint, \"external browser provider endpoint\")\n : undefined;\n return {\n kind: \"external_provider\",\n providerId: input.providerId,\n placementId: requireOpaqueId(input.placementId, \"external browser placement id\"),\n authority: {\n apiKey: requireBoundedText(\n input.authority.apiKey,\n 1,\n 8_192,\n \"external browser provider credential\",\n ),\n ...(endpoint ? { endpoint } : {}),\n },\n ...(input.timeoutSeconds === undefined\n ? {}\n : {\n timeoutSeconds: boundedExternalBrowserTimeout(input.timeoutSeconds),\n }),\n ...(input.stealth === undefined ? {} : { stealth: input.stealth }),\n };\n }\n return {\n kind: \"attached_chrome\",\n deviceId: requireUuid(input.deviceId, \"attached browser id\"),\n connectionGeneration: requireBridgeGeneration(input.connectionGeneration),\n browserName: requireBoundedText(input.browserName, 1, 100, \"attached browser name\"),\n browserVersion: requireBoundedText(input.browserVersion, 1, 256, \"attached browser version\"),\n };\n}\n\nfunction boundedExternalBrowserTimeout(value: number): number {\n const timeout = positiveSafeInteger(value, \"external browser timeout\");\n if (timeout > 86_400) {\n throw new BrowserControlProtocolError(\"external browser timeout is invalid\");\n }\n return timeout;\n}\n\nfunction boundedHttpUrl(value: string, label: string): string {\n if (Buffer.byteLength(value) > 16_384) {\n throw new BrowserControlProtocolError(`${label} is invalid`);\n }\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n throw new BrowserControlProtocolError(`${label} is invalid`);\n }\n if (\n (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") ||\n parsed.username ||\n parsed.password ||\n parsed.hash\n ) {\n throw new BrowserControlProtocolError(`${label} is invalid`);\n }\n return parsed.toString().replace(/\\/$/u, \"\");\n}\n\nfunction placementBrowserNetworkRoute(\n input: PlacementBrowserNetworkRoute,\n): PlacementBrowserNetworkRoute {\n const kind = input.kind;\n if (kind !== \"direct\" && kind !== \"proxy\" && kind !== \"managed\" && kind !== \"tunnel\") {\n throw new BrowserControlProtocolError(\"browser network route kind is invalid\");\n }\n if (!/^[A-Za-z0-9._~-]{16,256}$/u.test(input.authorityDigest)) {\n throw new BrowserControlProtocolError(\"browser network route authority is invalid\");\n }\n const proxyUrl = input.proxyUrl === undefined ? undefined : boundedProxyUrl(input.proxyUrl);\n if (kind !== \"proxy\" && proxyUrl !== undefined) {\n throw new BrowserControlProtocolError(\"non-proxy browser route contains proxy authority\");\n }\n const providerRoute =\n input.providerRoute === undefined ? undefined : placementProviderRoute(input.providerRoute);\n if (kind !== \"managed\" && providerRoute !== undefined) {\n throw new BrowserControlProtocolError(\n \"non-managed browser route contains provider route material\",\n );\n }\n if (kind === \"managed\" && providerRoute === undefined) {\n throw new BrowserControlProtocolError(\"managed browser route omits provider route material\");\n }\n return {\n routeId: requireUuid(input.routeId, \"network route id\"),\n routeVersion: positiveSafeInteger(input.routeVersion, \"network route version\"),\n authorityDigest: input.authorityDigest,\n kind,\n consistency: NetworkRouteConsistency.parse(input.consistency),\n ...(proxyUrl === undefined ? {} : { proxyUrl }),\n ...(providerRoute === undefined ? {} : { providerRoute }),\n };\n}\n\nfunction placementProviderRoute(\n input: NonNullable<PlacementBrowserNetworkRoute[\"providerRoute\"]>,\n): NonNullable<PlacementBrowserNetworkRoute[\"providerRoute\"]> {\n if (input.providerId !== \"browserbase\" && input.providerId !== \"kernel\") {\n throw new BrowserControlProtocolError(\"managed browser route provider is unsupported\");\n }\n if (\n input.egressClass !== \"datacenter\" &&\n input.egressClass !== \"residential\" &&\n input.egressClass !== \"isp\"\n ) {\n throw new BrowserControlProtocolError(\"managed browser route egress class is invalid\");\n }\n return {\n providerId: input.providerId,\n routeId: requireOpaqueId(input.routeId, \"managed browser provider route id\"),\n egressClass: input.egressClass,\n region:\n input.region === null\n ? null\n : requireBoundedText(input.region, 1, 128, \"managed browser route region\"),\n };\n}\n\nfunction boundedProxyUrl(value: string): string {\n if (Buffer.byteLength(value) > 16_384) {\n throw new BrowserControlProtocolError(\"browser proxy authority is too large\");\n }\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new BrowserControlProtocolError(\"browser proxy authority is invalid\");\n }\n if (\n ![\"http:\", \"https:\", \"socks5:\"].includes(url.protocol) ||\n !url.hostname ||\n (!url.port && url.protocol !== \"http:\" && url.protocol !== \"https:\") ||\n (url.pathname !== \"\" && url.pathname !== \"/\") ||\n url.search ||\n url.hash\n ) {\n throw new BrowserControlProtocolError(\"browser proxy authority is invalid\");\n }\n return url.toString();\n}\n\nfunction workingCopyAuthorityBody(\n reference: PlacementBrowserSessionReference,\n input: PlacementBrowserWorkingCopyAuthority,\n) {\n return {\n controllerGeneration: reference.controllerGeneration,\n tokenGeneration: positiveSafeInteger(input.tokenGeneration, \"token generation\"),\n controlToken: requireToken(input.controlToken, \"control token\"),\n viewToken: requireToken(input.viewToken, \"view token\"),\n };\n}\n\n/**\n * An adoption record. `generation: \"current\"` (a new adoption) requires the\n * record to belong to the requesting controller generation. `\"recorded\"`\n * (status, revert, inspection) keeps the generation the adoption was recorded\n * under: recovering an unfinished adoption after a controller restart means\n * reading and reverting a record made by an earlier generation, under the\n * browser's legitimate current control. The browser and operation always\n * have to match exactly.\n */\nfunction parseWorkingCopyAdoption(\n value: unknown,\n reference: PlacementBrowserSessionReference,\n generation: \"current\" | \"recorded\",\n): PlacementBrowserWorkingCopyAdoption {\n if (\n !isRecord(value) ||\n value.browserSessionId !== reference.browserSessionId ||\n (generation === \"current\" && value.controllerGeneration !== reference.controllerGeneration) ||\n !BROWSER_WORKING_COPY_ADOPTION_PHASES.includes(\n value.phase as PlacementBrowserWorkingCopyAdoptionPhase,\n ) ||\n !(value.failureCode === null || typeof value.failureCode === \"string\") ||\n !Array.isArray(value.retainedDirectories) ||\n value.retainedDirectories.length > 64 ||\n !value.retainedDirectories.every(\n (name) => typeof name === \"string\" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/u.test(name),\n )\n ) {\n throw new BrowserControlProtocolError(\"browser controller returned a malformed adoption\");\n }\n return {\n browserSessionId: reference.browserSessionId,\n controllerGeneration:\n generation === \"current\"\n ? reference.controllerGeneration\n : requireGeneration(value.controllerGeneration),\n operationId: requireUuid(value.operationId, \"working copy adoption id\"),\n manifestDigest: sha256(value.manifestDigest, \"working copy manifest digest\"),\n phase: value.phase as PlacementBrowserWorkingCopyAdoptionPhase,\n failureCode:\n value.failureCode === null ? null : requireOpaqueId(value.failureCode, \"failure code\"),\n retainedDirectories: value.retainedDirectories as string[],\n createdAt: timestamp(value.createdAt, \"adoption created at\"),\n updatedAt: timestamp(value.updatedAt, \"adoption updated at\"),\n };\n}\n\nfunction parseWorkingCopyInspection(\n value: unknown,\n reference: PlacementBrowserSessionReference,\n): PlacementBrowserWorkingCopyInspection {\n if (\n !isRecord(value) ||\n value.browserSessionId !== reference.browserSessionId ||\n value.controllerGeneration !== reference.controllerGeneration ||\n typeof value.platformSupported !== \"boolean\" ||\n typeof value.profileIdentityMatches !== \"boolean\" ||\n !(value.profileInUse === null || typeof value.profileInUse === \"boolean\") ||\n !(\n value.refusal === null ||\n BROWSER_WORKING_COPY_REFUSALS.includes(value.refusal as PlacementBrowserWorkingCopyRefusal)\n )\n ) {\n throw new BrowserControlProtocolError(\"browser controller returned a malformed inspection\");\n }\n let manifest: PlacementBrowserWorkingCopyInspection[\"manifest\"] = null;\n if (value.manifest !== null) {\n if (!isRecord(value.manifest)) {\n throw new BrowserControlProtocolError(\"browser controller returned a malformed manifest\");\n }\n manifest = {\n digest: sha256(value.manifest.digest, \"working copy manifest digest\"),\n entries: nonnegativeSafeInteger(value.manifest.entries, \"working copy entries\"),\n bytes: nonnegativeSafeInteger(value.manifest.bytes, \"working copy bytes\"),\n excluded: excludedWorkingCopyEntries(value.manifest.excluded),\n };\n }\n let receipt: PlacementBrowserWorkingCopyInspection[\"receipt\"] = null;\n if (value.receipt !== null) {\n const raw = value.receipt;\n if (\n !isRecord(raw) ||\n ![\"launch\", \"suspend\", \"retire\", \"adopt\"].includes(raw.intent as string) ||\n typeof raw.state !== \"string\" ||\n typeof raw.directoryLaunchAllowed !== \"boolean\" ||\n typeof raw.authorityMatches !== \"boolean\" ||\n !(raw.restoreAuthorityDigest === null || typeof raw.restoreAuthorityDigest === \"string\") ||\n !(raw.adoption === null || isRecord(raw.adoption))\n ) {\n throw new BrowserControlProtocolError(\"browser controller returned a malformed receipt\");\n }\n receipt = {\n operationId: requireUuid(raw.operationId, \"working runtime receipt id\"),\n intent: raw.intent as \"launch\" | \"suspend\" | \"retire\" | \"adopt\",\n state: requireOpaqueId(raw.state, \"working runtime receipt state\"),\n directoryLaunchAllowed: raw.directoryLaunchAllowed,\n authorityMatches: raw.authorityMatches,\n launchedFromCheckpoint: raw.restoreAuthorityDigest !== null,\n adoption: isRecord(raw.adoption)\n ? {\n operationId: requireUuid(raw.adoption.operationId, \"working copy adoption id\"),\n manifestDigest: sha256(raw.adoption.manifestDigest, \"working copy manifest digest\"),\n }\n : null,\n };\n }\n return {\n browserSessionId: reference.browserSessionId,\n controllerGeneration: reference.controllerGeneration,\n platformSupported: value.platformSupported,\n refusal: value.refusal as PlacementBrowserWorkingCopyRefusal | null,\n manifest,\n profileIdentityMatches: value.profileIdentityMatches,\n profileInUse: value.profileInUse,\n receipt,\n activeAdoption:\n value.activeAdoption === null || value.activeAdoption === undefined\n ? null\n : parseWorkingCopyAdoption(value.activeAdoption, reference, \"recorded\"),\n };\n}\n\nfunction parseStateCaptureReceipt(value: unknown): PlacementBrowserStateCaptureReceipt {\n if (!isRecord(value) || !isRecord(value.manifest)) {\n throw new BrowserControlProtocolError(\n \"browser controller returned malformed state-capture data\",\n );\n }\n const manifest = value.manifest;\n if (!Array.isArray(manifest.tabs)) {\n throw new BrowserControlProtocolError(\n \"browser controller returned malformed state-capture manifest\",\n );\n }\n const browserSessionId = requireUuid(value.browserSessionId, \"browser session id\");\n const controllerGeneration = requireGeneration(value.controllerGeneration);\n const manifestSessionId = requireUuid(\n manifest.browserSessionId,\n \"browser state manifest session id\",\n );\n const manifestControllerGeneration = requireGeneration(manifest.controllerGeneration);\n if (\n manifestSessionId !== browserSessionId ||\n manifestControllerGeneration !== controllerGeneration\n ) {\n throw new BrowserControlProtocolError(\n \"browser controller returned inconsistent state-capture metadata\",\n );\n }\n if (\n value.format !== BROWSER_PROFILE_ARTIFACT_FORMAT ||\n manifest.schemaVersion !== 1 ||\n (manifest.engine !== \"chromium\" && manifest.engine !== \"chrome\") ||\n (manifest.platform !== \"linux\" &&\n manifest.platform !== \"macos\" &&\n manifest.platform !== \"windows\") ||\n (manifest.architecture !== \"x64\" && manifest.architecture !== \"arm64\")\n ) {\n throw new BrowserControlProtocolError(\n \"browser controller returned unsupported state-capture metadata\",\n );\n }\n if (\n manifest.profileCrypto !== \"chromium_basic\" &&\n manifest.profileCrypto !== \"chromium_mock_keychain\" &&\n manifest.profileCrypto !== \"platform_bound\"\n ) {\n throw new BrowserControlProtocolError(\n \"browser controller returned unsupported profile crypto policy\",\n );\n }\n const tabs = manifest.tabs.map((tab) => {\n if (!isRecord(tab) || typeof tab.selected !== \"boolean\") {\n throw new BrowserControlProtocolError(\n \"browser controller returned malformed state-capture tab\",\n );\n }\n return { url: boundedUrl(tab.url), selected: tab.selected };\n });\n if (tabs.length > 1_000 || tabs.filter((tab) => tab.selected).length > 1) {\n throw new BrowserControlProtocolError(\"browser controller returned invalid state-capture tabs\");\n }\n return {\n operationId: requireUuid(value.operationId, \"browser state operation id\"),\n browserSessionId,\n controllerGeneration,\n objectKey: browserStateObjectKey(value.objectKey),\n format: BROWSER_PROFILE_ARTIFACT_FORMAT,\n artifactDigest: sha256(value.artifactDigest, \"browser state artifact digest\"),\n contentDigest: sha256(value.contentDigest, \"browser state content digest\"),\n sizeBytes: positiveSafeInteger(value.sizeBytes, \"browser state artifact size\"),\n fileCount: nonnegativeSafeInteger(value.fileCount, \"browser state file count\"),\n profileBytes: nonnegativeSafeInteger(value.profileBytes, \"browser state profile size\"),\n manifest: {\n schemaVersion: 1,\n browserSessionId: manifestSessionId,\n controllerGeneration: manifestControllerGeneration,\n capturedAt: timestamp(manifest.capturedAt, \"browser state capture time\"),\n engine: manifest.engine,\n engineVersion:\n manifest.engineVersion === null\n ? null\n : requireOpaqueId(manifest.engineVersion, \"browser engine version\"),\n driverId: requireOpaqueId(manifest.driverId, \"browser driver id\"),\n driverSchemaVersion: positiveSafeInteger(\n manifest.driverSchemaVersion,\n \"browser driver schema version\",\n ),\n profileCrypto: manifest.profileCrypto,\n platform: manifest.platform,\n architecture: manifest.architecture,\n tabs,\n },\n };\n}\n\nfunction browserStateObjectKey(value: unknown): string {\n if (\n typeof value !== \"string\" ||\n Buffer.byteLength(value) > 2_048 ||\n !/^workspaces\\/[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\\/browser-state\\/[A-Za-z0-9._=-]+(?:\\/[A-Za-z0-9._=-]+)*$/iu.test(\n value,\n )\n ) {\n throw new RangeError(\"browser state object key is invalid\");\n }\n return value;\n}\n\nfunction browserStateUploadGrant(value: unknown): BrowserStateUploadGrant {\n if (!isRecord(value) || !isRecord(value.requiredHeaders)) {\n throw new RangeError(\"browser state upload grant is invalid\");\n }\n const url = boundedUrl(value.url);\n const parsed = new URL(url);\n if (\n (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") ||\n parsed.username ||\n parsed.password ||\n parsed.hash\n ) {\n throw new RangeError(\"browser state upload URL is invalid\");\n }\n const headers: Record<string, string> = {};\n for (const [name, headerValue] of Object.entries(value.requiredHeaders)) {\n if (\n (name !== \"content-type\" && name !== \"x-ms-blob-type\") ||\n typeof headerValue !== \"string\" ||\n /[\\r\\n]/u.test(headerValue)\n ) {\n throw new RangeError(\"browser state upload header is invalid\");\n }\n headers[name] = headerValue;\n }\n if (Object.keys(headers).length < 1 || Object.keys(headers).length > 2) {\n throw new RangeError(\"browser state upload header count is invalid\");\n }\n if (headers[\"content-type\"] !== BROWSER_STATE_ARTIFACT_CONTENT_TYPE) {\n throw new RangeError(\"browser state upload content type is invalid\");\n }\n return {\n url: parsed.toString(),\n requiredHeaders: headers,\n expiresAt: timestamp(value.expiresAt, \"browser state upload expiry\"),\n };\n}\n\nfunction browserStateDownloadGrant(value: unknown): BrowserStateDownloadGrant {\n if (!isRecord(value)) {\n throw new RangeError(\"browser state download grant is invalid\");\n }\n const url = boundedUrl(value.url);\n const parsed = new URL(url);\n if (\n (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") ||\n parsed.username ||\n parsed.password ||\n parsed.hash\n ) {\n throw new RangeError(\"browser state download URL is invalid\");\n }\n return {\n url: parsed.toString(),\n expiresAt: timestamp(value.expiresAt, \"browser state download expiry\"),\n };\n}\n\nfunction browserStateRestoreRequest(input: RestorePlacementBrowserStateInput): {\n wire: Record<string, unknown>;\n dataKey: Buffer;\n aad: Buffer;\n} {\n if (input.format !== BROWSER_PROFILE_ARTIFACT_FORMAT) {\n throw new RangeError(\"browser state restore format is unsupported\");\n }\n const dataKey = Buffer.from(exactBytes(input.dataKey, 32, \"browser state data key\"));\n const aad = Buffer.from(boundedBytes(input.aad, 1, 16 * 1024, \"browser state associated data\"));\n try {\n return {\n wire: {\n objectKey: browserStateObjectKey(input.objectKey),\n format: BROWSER_PROFILE_ARTIFACT_FORMAT,\n artifactDigest: sha256(input.artifactDigest, \"browser state artifact digest\"),\n contentDigest: sha256(input.contentDigest, \"browser state content digest\"),\n manifestDigest: sha256(input.manifestDigest, \"browser state manifest digest\"),\n sizeBytes: positiveSafeInteger(input.sizeBytes, \"browser state artifact size\"),\n dataKeyBase64: dataKey.toString(\"base64\"),\n aadBase64: aad.toString(\"base64\"),\n materialization: BrowserRevisionMaterialization.parse(input.materialization),\n download: browserStateDownloadGrant(input.download),\n },\n dataKey,\n aad,\n };\n } catch (error) {\n dataKey.fill(0);\n aad.fill(0);\n throw error;\n }\n}\n\nfunction exactBytes(value: Uint8Array, length: number, label: string): Uint8Array {\n return boundedBytes(value, length, length, label);\n}\n\nfunction boundedBytes(\n value: Uint8Array,\n minimum: number,\n maximum: number,\n label: string,\n): Uint8Array {\n if (!(value instanceof Uint8Array) || value.byteLength < minimum || value.byteLength > maximum) {\n throw new RangeError(`${label} is invalid`);\n }\n return value;\n}\n\nfunction sha256(value: unknown, label: string): string {\n if (typeof value !== \"string\" || !SHA256_PATTERN.test(value)) {\n throw new BrowserControlProtocolError(`${label} is invalid`);\n }\n return value;\n}\n\nfunction requirePlacementProvisioningSurface(session: BrowserControlPlacementSession): void {\n const hasPrivateWrite =\n typeof session.writePlacementPrivate === \"function\" ||\n typeof session.writeFile === \"function\" ||\n ((typeof session.exec === \"function\" || typeof session.execCommand === \"function\") &&\n typeof session.writeStdin === \"function\");\n if (\n (typeof session.exec !== \"function\" && typeof session.execCommand !== \"function\") ||\n !hasPrivateWrite\n ) {\n throw new BrowserControlUnsupportedError(\n \"browser placement requires exec and a private file transport\",\n );\n }\n}\n\nfunction requirePlacementRequestSurface(session: BrowserControlPlacementSession): void {\n const hasExec = typeof session.exec === \"function\" || typeof session.execCommand === \"function\";\n const hasPrivateWrite =\n typeof session.writePlacementPrivate === \"function\" ||\n typeof session.writeFile === \"function\" ||\n (hasExec && typeof session.writeStdin === \"function\");\n if (\n typeof session.execWithInput !== \"function\" &&\n typeof session.resolveExposedPort !== \"function\" &&\n (!hasExec || !hasPrivateWrite)\n ) {\n throw new BrowserControlUnsupportedError(\n \"browser placement requires a controller endpoint or exec and a private file transport\",\n );\n }\n}\n\nfunction isWorkspaceConfinedWrite(error: unknown): boolean {\n return (\n error instanceof Error &&\n /must stay within|confines|workspace mount|within \\/workspace|escapes? the workspace(?: root)?/iu.test(\n error.message,\n )\n );\n}\n\nasync function writePrivateFile(\n session: BrowserControlPlacementSession,\n input: {\n path: string;\n content: string | Uint8Array;\n createParents?: boolean;\n },\n timeoutMs = 60_000,\n): Promise<void> {\n if (session.writePlacementPrivate) {\n await session.writePlacementPrivate(input);\n return;\n }\n if (session.writeFile) {\n try {\n await session.writeFile(input);\n return;\n } catch (error) {\n if (\n !isWorkspaceConfinedWrite(error) ||\n (!session.exec && !session.execCommand) ||\n !session.writeStdin\n ) {\n throw error;\n }\n }\n }\n if ((!session.exec && !session.execCommand) || !session.writeStdin) {\n throw new BrowserControlUnsupportedError(\"browser placement has no private file transport\");\n }\n const path = absolutePrivatePath(input.path, \"browser private file path\");\n const bytes = typeof input.content === \"string\" ? Buffer.from(input.content) : input.content;\n if (bytes.byteLength > BROWSER_CONTROL_MAX_JSON_BYTES) {\n throw new RangeError(\"browser private file is too large\");\n }\n const parent = posixPath.dirname(path);\n if (input.createParents) {\n await runChecked(\n session,\n `umask 077; install -d -m 0700 -- ${shellQuote(parent)}; printf '%s\\n' ${shellQuote(COMMAND_OK)}`,\n timeoutMs,\n );\n }\n if (bytes.byteLength === 0) {\n await runChecked(\n session,\n `umask 077; : > ${shellQuote(path)}; chmod 0600 -- ${shellQuote(path)}; printf '%s\\n' ${shellQuote(COMMAND_OK)}`,\n timeoutMs,\n );\n return;\n }\n\n // SandboxSession deliberately has no generic writeFile capability. Stream a\n // bounded base64 payload over the provider's stdin channel into an exact-byte\n // decoder. Secret material never appears in a shell command, argv, env, URL,\n // workspace, or provider process listing.\n const payload = Buffer.from(bytes).toString(\"base64\");\n const command = [\n \"umask 077;\",\n \"if base64 --help 2>&1 | grep -q -- '--decode'; then decode_flag=--decode;\",\n \"elif printf '' | base64 -d >/dev/null 2>&1; then decode_flag=-d;\",\n \"elif printf '' | base64 -D >/dev/null 2>&1; then decode_flag=-D;\",\n \"else exit 69; fi;\",\n `dd bs=1 count=${payload.length} 2>/dev/null | base64 \"$decode_flag\" > ${shellQuote(path)};`,\n `chmod 0600 -- ${shellQuote(path)};`,\n `printf '%s\\n' ${shellQuote(COMMAND_OK)}`,\n ].join(\" \");\n const started = session.exec\n ? await session.exec({\n cmd: command,\n workdir: placementControllerWorkdir(session),\n yieldTimeMs: 250,\n maxOutputTokens: 2_000,\n })\n : await session.execCommand!({\n cmd: command,\n workdir: placementControllerWorkdir(session),\n yieldTimeMs: 250,\n maxOutputTokens: 2_000,\n });\n const startedSessionId =\n typeof started === \"string\"\n ? (() => {\n const banner = parseExecResponseBanner(started);\n return banner.kind === \"running\" ? banner.sessionId : null;\n })()\n : Number.isSafeInteger(started.sessionId) && (started.sessionId ?? -1) >= 0\n ? started.sessionId!\n : null;\n if (startedSessionId === null) {\n throw new BrowserControlTransportError(\n \"browser private file transport did not yield an input session\",\n );\n }\n const output = await session.writeStdin({\n sessionId: startedSessionId,\n chars: payload,\n yieldTimeMs: boundedTimeout(timeoutMs),\n maxOutputTokens: 2_000,\n });\n const terminal = parseExecResponseBanner(output);\n if (\n terminal.kind === \"invalid\" ||\n terminal.kind === \"running\" ||\n (terminal.kind === \"exited\" && terminal.exitCode !== 0) ||\n !output.includes(COMMAND_OK)\n ) {\n throw new BrowserControlTransportError(\"browser private file transport failed\");\n }\n}\n\nasync function runChecked(\n session: BrowserControlPlacementSession,\n command: string,\n timeoutMs = 60_000,\n): Promise<void> {\n const bounded = boundedTimeout(timeoutMs);\n const result = session.exec\n ? await session.exec({\n cmd: command,\n workdir: placementControllerWorkdir(session),\n yieldTimeMs: bounded,\n maxOutputTokens: 2_000,\n })\n : await session.execCommand!({\n cmd: command,\n workdir: placementControllerWorkdir(session),\n yieldTimeMs: bounded,\n maxOutputTokens: 2_000,\n });\n const output = commandOutput(result);\n const exitCode = typeof result === \"object\" && result ? result.exitCode : undefined;\n if ((typeof exitCode === \"number\" && exitCode !== 0) || !output.includes(COMMAND_OK)) {\n throw new BrowserControlTransportError(\"browser placement command failed\");\n }\n}\n\nasync function runBestEffort(\n session: BrowserControlPlacementSession,\n command: string,\n): Promise<void> {\n try {\n if (session.exec) {\n await session.exec({\n cmd: command,\n workdir: placementControllerWorkdir(session),\n yieldTimeMs: 15_000,\n maxOutputTokens: 100,\n });\n } else if (session.execCommand) {\n await session.execCommand({\n cmd: command,\n workdir: placementControllerWorkdir(session),\n yieldTimeMs: 15_000,\n maxOutputTokens: 100,\n });\n }\n } catch {\n // UUID-scoped request directories contain no durable state.\n }\n}\n\nasync function readText(\n session: BrowserControlPlacementSession,\n path: string,\n maxBytes: number,\n timeoutMs: number,\n): Promise<string> {\n const privatePath = absolutePrivatePath(path, \"browser private response path\");\n if (\n !Number.isSafeInteger(maxBytes) ||\n maxBytes < 1 ||\n maxBytes > BROWSER_CONTROL_MAX_JSON_BYTES + 1\n ) {\n throw new RangeError(\"browser private response limit is invalid\");\n }\n if (session.readFile) {\n try {\n const value = await session.readFile({ path: privatePath, maxBytes });\n return typeof value === \"string\"\n ? value\n : new TextDecoder(\"utf-8\", { fatal: true }).decode(value);\n } catch {\n // The standard Docker SandboxSession intentionally confines readFile to\n // its workspace mount. Keep controller traffic out of that capturable\n // mount and fall back to the same placement's bounded command channel.\n }\n }\n\n const sizeMarker = `OPENGENI_BROWSER_PRIVATE_SIZE_${randomUUID()}`;\n const sizeOutput = await runPrivateReadCommand(\n session,\n [\n \"LC_ALL=C;\",\n `size=$(wc -c < ${shellQuote(privatePath)}) || exit 66;`,\n `printf '%s%s%s' ${shellQuote(sizeMarker)} \"$size\" ${shellQuote(sizeMarker)}`,\n ].join(\" \"),\n 1_024,\n timeoutMs,\n );\n const sizeText = extractMarkedValue(sizeOutput, sizeMarker);\n const size = parseUnsignedInteger(sizeText, \"browser private response size\");\n const requestedBytes = Math.min(size, maxBytes);\n if (requestedBytes === 0) return \"\";\n\n const chunks: Buffer[] = [];\n for (let offset = 0; offset < requestedBytes; offset += PRIVATE_READ_CHUNK_BYTES) {\n const chunkIndex = Math.floor(offset / PRIVATE_READ_CHUNK_BYTES);\n const expectedBytes = Math.min(PRIVATE_READ_CHUNK_BYTES, requestedBytes - offset);\n const marker = `OPENGENI_BROWSER_PRIVATE_CHUNK_${randomUUID()}`;\n const output = await runPrivateReadCommand(\n session,\n [\n \"LC_ALL=C;\",\n `printf '%s' ${shellQuote(marker)};`,\n `dd if=${shellQuote(privatePath)} bs=${PRIVATE_READ_CHUNK_BYTES} skip=${chunkIndex} count=1 2>/dev/null | base64 | tr -d '\\\\r\\\\n';`,\n `printf '%s' ${shellQuote(marker)}`,\n ].join(\" \"),\n Math.ceil((expectedBytes * 4) / 3) + 4_096,\n timeoutMs,\n );\n const encoded = extractMarkedValue(output, marker);\n if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(encoded)) {\n throw new BrowserControlTransportError(\"browser private response encoding is invalid\");\n }\n const decoded = Buffer.from(encoded, \"base64\");\n if (decoded.byteLength < expectedBytes) {\n throw new BrowserControlTransportError(\"browser private response changed during read\");\n }\n chunks.push(decoded.subarray(0, expectedBytes));\n }\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(Buffer.concat(chunks));\n}\n\nasync function readBytes(\n session: BrowserControlPlacementSession,\n path: string,\n maxBytes: number,\n timeoutMs: number,\n): Promise<Uint8Array> {\n const privatePath = absolutePrivatePath(path, \"browser private binary response path\");\n if (\n !Number.isSafeInteger(maxBytes) ||\n maxBytes < 1 ||\n maxBytes > Math.max(24 * 1024 * 1024, COMPUTER_SCREENSHOT_MAX_BYTES)\n ) {\n throw new RangeError(\"browser private binary response limit is invalid\");\n }\n const sizeMarker = `OPENGENI_BROWSER_PRIVATE_SIZE_${randomUUID()}`;\n const sizeOutput = await runPrivateReadCommand(\n session,\n [\n \"LC_ALL=C;\",\n `size=$(wc -c < ${shellQuote(privatePath)}) || exit 66;`,\n `printf '%s%s%s' ${shellQuote(sizeMarker)} \"$size\" ${shellQuote(sizeMarker)}`,\n ].join(\" \"),\n 1_024,\n timeoutMs,\n );\n const size = parseUnsignedInteger(\n extractMarkedValue(sizeOutput, sizeMarker),\n \"browser private binary response size\",\n );\n if (size < 1 || size > maxBytes) {\n throw new RangeError(\"frame exceeds its byte bound\");\n }\n const chunks: Buffer[] = [];\n for (let offset = 0; offset < size; offset += PRIVATE_READ_CHUNK_BYTES) {\n const chunkIndex = Math.floor(offset / PRIVATE_READ_CHUNK_BYTES);\n const expectedBytes = Math.min(PRIVATE_READ_CHUNK_BYTES, size - offset);\n const marker = `OPENGENI_BROWSER_PRIVATE_CHUNK_${randomUUID()}`;\n const output = await runPrivateReadCommand(\n session,\n [\n \"LC_ALL=C;\",\n `printf '%s' ${shellQuote(marker)};`,\n `dd if=${shellQuote(privatePath)} bs=${PRIVATE_READ_CHUNK_BYTES} skip=${chunkIndex} count=1 2>/dev/null | base64 | tr -d '\\\\r\\\\n';`,\n `printf '%s' ${shellQuote(marker)}`,\n ].join(\" \"),\n Math.ceil((expectedBytes * 4) / 3) + 4_096,\n timeoutMs,\n );\n const encoded = extractMarkedValue(output, marker);\n if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(encoded)) {\n throw new BrowserControlTransportError(\"browser private binary response encoding is invalid\");\n }\n const decoded = Buffer.from(encoded, \"base64\");\n if (decoded.byteLength !== expectedBytes) {\n throw new BrowserControlTransportError(\"browser private binary response changed during read\");\n }\n chunks.push(decoded);\n }\n return Uint8Array.from(Buffer.concat(chunks));\n}\n\nasync function runPrivateReadCommand(\n session: BrowserControlPlacementSession,\n command: string,\n maxOutputTokens: number,\n timeoutMs: number,\n): Promise<string> {\n const bounded = boundedTimeout(timeoutMs);\n const result = session.exec\n ? await session.exec({\n cmd: command,\n workdir: placementControllerWorkdir(session),\n yieldTimeMs: bounded,\n maxOutputTokens,\n })\n : await session.execCommand!({\n cmd: command,\n workdir: placementControllerWorkdir(session),\n yieldTimeMs: bounded,\n maxOutputTokens,\n });\n const exitCode = typeof result === \"object\" && result ? result.exitCode : undefined;\n if (typeof result === \"object\" && result?.sessionId !== undefined) {\n throw new BrowserControlTransportError(\"browser private response read failed\");\n }\n if (typeof result === \"string\") {\n const terminal = parseExecResponseBanner(result);\n if (\n terminal.kind === \"invalid\" ||\n terminal.kind === \"running\" ||\n (terminal.kind === \"exited\" && terminal.exitCode !== 0)\n ) {\n throw new BrowserControlTransportError(\"browser private response read failed\");\n }\n return result;\n }\n if (typeof exitCode === \"number\" && exitCode !== 0) {\n throw new BrowserControlTransportError(\"browser private response read failed\");\n }\n return result.stdout ?? result.output ?? \"\";\n}\n\nfunction extractMarkedValue(output: string, marker: string): string {\n const start = output.indexOf(marker);\n if (start < 0) {\n throw new BrowserControlTransportError(\"browser private response marker is absent\");\n }\n const valueStart = start + marker.length;\n const end = output.indexOf(marker, valueStart);\n if (end < 0) {\n throw new BrowserControlTransportError(\"browser private response marker is incomplete\");\n }\n return output.slice(valueStart, end);\n}\n\nfunction commandOutput(result: ExecResultLike | string): string {\n if (typeof result === \"string\") return result;\n return [result.output, result.stdout, result.stderr]\n .filter((part): part is string => typeof part === \"string\")\n .join(\"\\n\");\n}\n\nfunction curlConfigQuote(value: string): string {\n if (/[\\r\\n\\0]/u.test(value)) throw new BrowserControlProtocolError(\"curl value is invalid\");\n return `\"${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"')}\"`;\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\nfunction requireToken(value: unknown, label: string): string {\n if (typeof value !== \"string\" || !TOKEN_PATTERN.test(value)) {\n throw new BrowserControlProtocolError(`${label} is invalid`);\n }\n return value;\n}\n\nfunction requireUuid(value: unknown, label: string): string {\n if (\n typeof value !== \"string\" ||\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(value)\n ) {\n throw new BrowserControlProtocolError(`${label} is invalid`);\n }\n return value;\n}\n\nfunction requireGeneration(value: unknown): string {\n if (\n typeof value !== \"string\" ||\n value.length > 256 ||\n !/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u.test(value)\n ) {\n throw new BrowserControlProtocolError(\"controller generation is invalid\");\n }\n return value;\n}\n\nfunction requireOpaqueId(value: unknown, label: string): string {\n if (\n typeof value !== \"string\" ||\n value.length === 0 ||\n Buffer.byteLength(value) > 512 ||\n /[\\u0000-\\u001f\\u007f]/u.test(value)\n ) {\n throw new BrowserControlProtocolError(`${label} is invalid`);\n }\n return value;\n}\n\nfunction requireBridgeGeneration(value: unknown): string {\n if (\n typeof value !== \"string\" ||\n value.length > 512 ||\n !/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u.test(value)\n ) {\n throw new BrowserControlProtocolError(\"attached browser connection generation is invalid\");\n }\n return value;\n}\n\nfunction requireBoundedText(\n value: unknown,\n minimum: number,\n maximum: number,\n label: string,\n): string {\n if (\n typeof value !== \"string\" ||\n Buffer.byteLength(value) < minimum ||\n Buffer.byteLength(value) > maximum ||\n /[\\u0000-\\u001f\\u007f]/u.test(value)\n ) {\n throw new BrowserControlProtocolError(`${label} is invalid`);\n }\n return value;\n}\n\nfunction boundedUrl(value: unknown): string {\n if (typeof value !== \"string\" || value.length === 0 || Buffer.byteLength(value) > 16_384) {\n throw new BrowserControlProtocolError(\"browser URL is invalid\");\n }\n return value;\n}\n\nfunction normalizeOrigin(value: unknown): string {\n if (typeof value !== \"string\") throw new BrowserControlProtocolError(\"browser origin is invalid\");\n try {\n const url = new URL(value);\n if (url.origin === \"null\" || url.pathname !== \"/\" || url.search || url.hash) throw new Error();\n return url.origin;\n } catch {\n throw new BrowserControlProtocolError(\"browser origin must be an absolute origin\");\n }\n}\n\nfunction timestamp(value: unknown, label: string): string {\n if (typeof value !== \"string\" || value.length > 128 || !Number.isFinite(Date.parse(value))) {\n throw new BrowserControlProtocolError(`${label} is invalid`);\n }\n return value;\n}\n\nfunction absolutePrivatePath(value: string, label: string): string {\n if (\n !value.startsWith(\"/\") ||\n value.includes(\"\\0\") ||\n value.endsWith(\"/\") ||\n posixPath.normalize(value) !== value\n ) {\n throw new BrowserControlProtocolError(`${label} is invalid`);\n }\n return value;\n}\n\nfunction boundedPort(value: number): number {\n if (!Number.isSafeInteger(value) || value < 1 || value > 65_535) {\n throw new RangeError(\"browser controller port is invalid\");\n }\n return value;\n}\n\nfunction boundedInteger(value: number, minimum: number, maximum: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {\n throw new RangeError(`${label} is invalid`);\n }\n return value;\n}\n\nfunction frameStreamUrlWithOptions(\n value: string,\n stream: {\n format?: \"jpeg\" | \"png\" | undefined;\n quality?: number | undefined;\n maxWidth?: number | undefined;\n maxHeight?: number | undefined;\n everyNthFrame?: number | undefined;\n },\n): string {\n const url = new URL(value);\n if (stream.format !== undefined) url.searchParams.set(\"format\", stream.format);\n if (stream.quality !== undefined) {\n url.searchParams.set(\n \"quality\",\n String(boundedInteger(stream.quality, 1, 100, \"browser frame quality\")),\n );\n }\n if (stream.maxWidth !== undefined) {\n url.searchParams.set(\n \"maxWidth\",\n String(boundedInteger(stream.maxWidth, 1, 4_096, \"browser frame width\")),\n );\n }\n if (stream.maxHeight !== undefined) {\n url.searchParams.set(\n \"maxHeight\",\n String(boundedInteger(stream.maxHeight, 1, 4_096, \"browser frame height\")),\n );\n }\n if (stream.everyNthFrame !== undefined) {\n url.searchParams.set(\n \"everyNthFrame\",\n String(boundedInteger(stream.everyNthFrame, 1, 60, \"browser frame sampling interval\")),\n );\n }\n return url.toString();\n}\n\nfunction boundedTimeout(value: number): number {\n if (!Number.isSafeInteger(value) || value < 1 || value > MAX_REQUEST_TIMEOUT_MS) {\n throw new RangeError(\"browser controller timeout is invalid\");\n }\n return value;\n}\n\nfunction positiveSafeInteger(value: unknown, label: string): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 1) {\n throw new RangeError(`${label} is invalid`);\n }\n return value;\n}\n\nfunction nonnegativeSafeInteger(value: unknown, label: string): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n throw new RangeError(`${label} is invalid`);\n }\n return value;\n}\n\nfunction excludedWorkingCopyEntries(value: unknown): string[] {\n if (\n !Array.isArray(value) ||\n value.length > 16 ||\n !value.every((entry) => typeof entry === \"string\" && entry.length > 0 && entry.length <= 256)\n ) {\n throw new BrowserControlProtocolError(\n \"browser controller returned malformed working copy exclusions\",\n );\n }\n return [...value];\n}\n\nfunction parseUnsignedInteger(value: string, label: string): number {\n const trimmed = value.trim();\n if (!/^(0|[1-9][0-9]*)$/u.test(trimmed)) {\n throw new BrowserControlProtocolError(`${label} is invalid`);\n }\n const parsed = Number(trimmed);\n if (!Number.isSafeInteger(parsed)) {\n throw new BrowserControlProtocolError(`${label} is invalid`);\n }\n return parsed;\n}\n\nfunction parseHttpStatus(value: string): number {\n const status = parseUnsignedInteger(value, \"HTTP status\");\n if (status < 100 || status > 599) {\n throw new BrowserControlProtocolError(\"HTTP status is invalid\");\n }\n return status;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","export const CONTROLLER_STREAM_MAX_INPUT = 128 * 1024;\nconst MAX_HEADER_BYTES = 64 * 1024;\n\n/** The machine family that runs the controller command. POSIX hosts use\n * `/bin/sh`, curl and base64. Windows has no POSIX shell or base64 utility, so\n * Windows PowerShell 5.1 (present on every supported Windows) relays the same\n * curl config to the system curl.exe and base64-encodes its exact bytes. */\nexport type ControllerStreamHost = \"posix\" | \"windows\";\n\nconst MARKER = \"OPENGENI_CONTROLLER_END_V1\";\n\n// Single quotes only: the script crosses a Windows command line as one argv\n// element, where embedded double quotes are not reliably preserved. The stdin\n// writer encoding is set without a BOM before the child pipe is created; a BOM\n// would make curl reject the first config line.\nconst WINDOWS_STREAM_SCRIPT = [\n \"$ErrorActionPreference='Stop'\",\n \"$i=New-Object IO.MemoryStream\",\n \"[Console]::OpenStandardInput().CopyTo($i)\",\n \"[Console]::InputEncoding=New-Object Text.UTF8Encoding($false)\",\n \"$s=New-Object Diagnostics.ProcessStartInfo\",\n \"$s.FileName=[IO.Path]::Combine([Environment]::SystemDirectory,'curl.exe')\",\n \"$s.Arguments='--disable --config -'\",\n \"$s.UseShellExecute=$false\",\n \"$s.CreateNoWindow=$true\",\n \"$s.RedirectStandardInput=$true\",\n \"$s.RedirectStandardOutput=$true\",\n \"$s.RedirectStandardError=$true\",\n \"$p=[Diagnostics.Process]::Start($s)\",\n \"$e=$p.StandardError.ReadToEndAsync()\",\n \"$i.WriteTo($p.StandardInput.BaseStream)\",\n \"$p.StandardInput.Close()\",\n \"$o=New-Object IO.MemoryStream\",\n \"$p.StandardOutput.BaseStream.CopyTo($o)\",\n \"$p.WaitForExit()\",\n `$t=[Text.Encoding]::ASCII.GetBytes([string][char]10+'${MARKER}'+$p.ExitCode)`,\n \"$o.Write($t,0,$t.Length)\",\n \"[Console]::Out.Write([Convert]::ToBase64String($o.ToArray()))\",\n].join(\";\");\n\n/** One command over the existing binary-input transport. The command is static\n * with a stable trailer so replayed command output remains readable; all\n * authority and page data stay on stdin.\n * Base64 preserves screenshot bytes across text-only command result adapters. */\nexport function controllerStreamRequest(input: {\n method: string;\n url: string;\n token: string;\n body?: string;\n timeoutMs: number;\n maxBytes: number;\n host?: ControllerStreamHost;\n}): { cmd: string; shell: string; stdin: Uint8Array; marker: string } {\n const quote = (value: string): string => {\n if (/[\\r\\n\\0]/u.test(value)) throw new Error(\"invalid controller request value\");\n return `\"${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"')}\"`;\n };\n const seconds = Math.max(1, Math.ceil(input.timeoutMs / 1_000));\n const marker = MARKER;\n const config = [\n \"silent\",\n \"show-error\",\n \"include\",\n `noproxy = \"*\"`,\n `connect-timeout = ${Math.min(seconds, 15)}`,\n `max-time = ${seconds}`,\n `max-filesize = ${input.maxBytes}`,\n `request = ${quote(input.method)}`,\n `url = ${quote(input.url)}`,\n `header = ${quote(`Authorization: Bearer ${input.token}`)}`,\n ...(input.body === undefined\n ? []\n : [`header = \"Content-Type: application/json\"`, `data-binary = ${quote(input.body)}`]),\n \"\",\n ].join(\"\\n\");\n const stdin = Buffer.from(config);\n if (stdin.byteLength > CONTROLLER_STREAM_MAX_INPUT) {\n throw new RangeError(\"controller command input is too large\");\n }\n if (input.host === \"windows\") {\n return { cmd: WINDOWS_STREAM_SCRIPT, shell: \"powershell\", stdin, marker };\n }\n return {\n cmd: `(curl --disable --config -; controller_exit=$?; printf '\\\\n${marker}%s' \"$controller_exit\") | base64`,\n shell: \"/bin/sh\",\n stdin,\n marker,\n };\n}\n\nexport function parseControllerStreamResponse(\n output: string,\n marker: string,\n maxBytes: number,\n): { status: number; headers: Map<string, string>; data: Uint8Array } {\n const maxWireBytes = maxBytes + MAX_HEADER_BYTES + marker.length + 32;\n // Allow the standard base64 utility's line wrapping, but no arbitrary log\n // noise or oversized allocation before validating and decoding the payload.\n if (output.length > Math.ceil(maxWireBytes / 3) * 4 * 1.05 + 4) {\n throw new RangeError(\"controller response exceeds its byte bound\");\n }\n const encoded = output.replace(/[\\r\\n]/gu, \"\");\n if (encoded.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/u.test(encoded)) {\n throw new Error(\"controller response encoding is invalid\");\n }\n const bytes = Buffer.from(encoded, \"base64\");\n const trailer = Buffer.from(`\\n${marker}`);\n const end = bytes.lastIndexOf(trailer);\n if (end < 0) throw new Error(\"controller response is incomplete\");\n const exit = bytes.subarray(end + trailer.length).toString(\"ascii\");\n if (!/^\\d{1,3}$/u.test(exit) || exit !== \"0\") {\n throw new Error(\"controller request did not complete successfully\");\n }\n let offset = 0;\n while (offset < end) {\n const headerEnd = bytes.indexOf(\"\\r\\n\\r\\n\", offset);\n if (headerEnd < offset || headerEnd + 4 > end || headerEnd + 4 > MAX_HEADER_BYTES) {\n throw new Error(\"controller response headers are invalid\");\n }\n const lines = bytes.subarray(offset, headerEnd).toString(\"latin1\").split(\"\\r\\n\");\n const match = /^HTTP\\/\\d(?:\\.\\d)? (\\d{3})(?: |$)/u.exec(lines.shift() ?? \"\");\n if (!match) throw new Error(\"controller response status is invalid\");\n const status = Number(match[1]);\n offset = headerEnd + 4;\n if (status >= 100 && status < 200 && status !== 101) continue;\n if (status < 200 || status > 599) throw new Error(\"controller response status is invalid\");\n const headers = new Map<string, string>();\n for (const line of lines) {\n const separator = line.indexOf(\":\");\n if (separator <= 0) throw new Error(\"controller response header is invalid\");\n headers.set(line.slice(0, separator).trim().toLowerCase(), line.slice(separator + 1).trim());\n }\n const data = bytes.subarray(offset, end);\n if (data.byteLength > maxBytes)\n throw new RangeError(\"controller response exceeds its byte bound\");\n return { status, headers, data };\n }\n throw new Error(\"controller response is incomplete\");\n}\n","import {\n CredentialProviderMcpMaterial,\n type CredentialProviderMcpMaterial as McpMaterial,\n type RunCredentialAuthNeeded,\n type RunCredentialFile,\n type RunCredentialsResolution,\n} from \"@opengeni/contracts\";\nimport type {\n ExecCommandArgs,\n SandboxClient,\n SandboxSessionLike,\n SandboxSessionState,\n} from \"@openai/agents/sandbox\";\n\nconst MAX_ENVIRONMENT_ENTRIES = 256;\nconst MAX_ENVIRONMENT_VALUE_BYTES = 64 * 1024;\nconst MAX_CREDENTIAL_FILES = 64;\nconst MAX_CREDENTIAL_FILE_BYTES = 1024 * 1024;\nconst MAX_TOTAL_MATERIAL_BYTES = 4 * 1024 * 1024;\nconst MAX_AUTH_NEEDED_NOTICES = 32;\n// Encoded chunks must leave room for both the cancellation shell and the SDK\n// run-as wrapper, each of which repeats and quotes the command. Keep chunks\n// base64-aligned and bounded without dropping any credential bytes.\nconst WRITE_CHUNK_BYTES = 1536;\nconst COMMAND_OK_MARKER = \"__OPENGENI_RUN_CREDENTIAL_COMMAND_OK__\";\nconst AUTH_NEEDED_REASONS = new Set([\n \"missing_connection\",\n \"expired\",\n \"insufficient_scope\",\n \"refresh_failed\",\n]);\nconst PORTABLE_LOCK_STALE_MINUTES = 2;\n\nexport type RunCredentialExpectedScope = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n};\n\nexport type NormalizedRunCredentialMaterial = {\n environment: Record<string, string>;\n files: RunCredentialFile[];\n fileEnvironment: Record<string, string>;\n expiresAt: Date | null;\n authNeeded: RunCredentialAuthNeeded[];\n mcp?: McpMaterial;\n};\n\nexport type RunCredentialCommandSession = Pick<SandboxSessionLike, \"exec\" | \"execCommand\">;\nexport type RunCredentialCommandRunner = (\n session: RunCredentialCommandSession,\n args: ExecCommandArgs,\n) => Promise<unknown>;\nexport type RunCredentialSessionReady = (\n session: RunCredentialCommandSession,\n) => Promise<void> | void;\n\nexport class RunCredentialValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RunCredentialValidationError\";\n }\n}\n\nfunction byteLength(value: string): number {\n return new TextEncoder().encode(value).byteLength;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction assertBoundedString(value: unknown, label: string, maxBytes: number): void {\n if (value === undefined) return;\n if (typeof value !== \"string\") {\n throw new RunCredentialValidationError(`${label} must be a string`);\n }\n if (byteLength(value) > maxBytes) {\n throw new RunCredentialValidationError(`${label} exceeds ${maxBytes} bytes`);\n }\n if (value?.includes(\"\\0\")) {\n throw new RunCredentialValidationError(`${label} contains a NUL byte`);\n }\n}\n\nfunction requiredBoundedString(value: unknown, label: string, maxBytes: number): string {\n if (typeof value !== \"string\") {\n throw new RunCredentialValidationError(`${label} must be a string`);\n }\n assertBoundedString(value, label, maxBytes);\n return value;\n}\n\nfunction assertOptionalNonEmptyString(value: unknown, label: string, maxBytes: number): void {\n assertBoundedString(value, label, maxBytes);\n if (typeof value === \"string\" && !value.trim()) {\n throw new RunCredentialValidationError(`${label} must not be empty`);\n }\n}\n\nfunction normalizeAuthNeeded(notices: unknown, required: boolean): RunCredentialAuthNeeded[] {\n if (notices !== undefined && !Array.isArray(notices)) {\n throw new RunCredentialValidationError(\"authNeeded must be an array\");\n }\n const rawNotices = notices ?? [];\n const normalized: RunCredentialAuthNeeded[] = [];\n if (required && rawNotices.length === 0) {\n throw new RunCredentialValidationError(\"auth_needed resolution must contain a notice\");\n }\n if (rawNotices.length > MAX_AUTH_NEEDED_NOTICES) {\n throw new RunCredentialValidationError(\n `auth-needed notice count exceeds ${MAX_AUTH_NEEDED_NOTICES}`,\n );\n }\n for (const [index, notice] of rawNotices.entries()) {\n if (!isRecord(notice)) {\n throw new RunCredentialValidationError(`authNeeded[${index}] must be an object`);\n }\n const reason = notice.reason;\n if (typeof reason !== \"string\" || !AUTH_NEEDED_REASONS.has(reason)) {\n throw new RunCredentialValidationError(`authNeeded[${index}].reason is invalid`);\n }\n assertOptionalNonEmptyString(notice.providerDomain, `authNeeded[${index}].providerDomain`, 512);\n assertOptionalNonEmptyString(notice.connectionId, `authNeeded[${index}].connectionId`, 512);\n assertOptionalNonEmptyString(notice.resource, `authNeeded[${index}].resource`, 2_048);\n assertOptionalNonEmptyString(notice.message, `authNeeded[${index}].message`, 2_048);\n if (notice.scopes !== undefined && !Array.isArray(notice.scopes)) {\n throw new RunCredentialValidationError(`authNeeded[${index}].scopes must be an array`);\n }\n const scopes = notice.scopes ?? [];\n if (scopes.length > 128) {\n throw new RunCredentialValidationError(`authNeeded[${index}].scopes exceeds 128 entries`);\n }\n for (const scope of scopes) {\n requiredBoundedString(scope, `authNeeded[${index}].scope`, 512);\n if (!scope.trim()) {\n throw new RunCredentialValidationError(`authNeeded[${index}].scope must not be empty`);\n }\n }\n if (notice.authorizationUrl !== undefined) {\n const authorizationUrl = requiredBoundedString(\n notice.authorizationUrl,\n `authNeeded[${index}].authorizationUrl`,\n 4_096,\n );\n let url: URL;\n try {\n url = new URL(authorizationUrl);\n } catch {\n throw new RunCredentialValidationError(`authNeeded[${index}].authorizationUrl is invalid`);\n }\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw new RunCredentialValidationError(\n `authNeeded[${index}].authorizationUrl must use http or https`,\n );\n }\n }\n normalized.push({\n reason: reason as RunCredentialAuthNeeded[\"reason\"],\n ...(typeof notice.providerDomain === \"string\"\n ? { providerDomain: notice.providerDomain }\n : {}),\n ...(typeof notice.connectionId === \"string\" ? { connectionId: notice.connectionId } : {}),\n ...(scopes.length > 0 ? { scopes: scopes as string[] } : {}),\n ...(typeof notice.resource === \"string\" ? { resource: notice.resource } : {}),\n ...(typeof notice.authorizationUrl === \"string\"\n ? { authorizationUrl: notice.authorizationUrl }\n : {}),\n ...(typeof notice.message === \"string\" ? { message: notice.message } : {}),\n });\n }\n return normalized;\n}\n\nfunction assertResolutionScope(\n resolution: Record<string, unknown>,\n expected: RunCredentialExpectedScope,\n): void {\n if (\n resolution.accountId !== expected.accountId ||\n resolution.workspaceId !== expected.workspaceId ||\n resolution.sessionId !== expected.sessionId\n ) {\n throw new RunCredentialValidationError(\"run credential provider returned a scope mismatch\");\n }\n}\n\nfunction normalizeRelativeFilePath(path: string): string {\n if (\n path.length === 0 ||\n path.length > 240 ||\n path.startsWith(\"/\") ||\n path.includes(\"\\\\\") ||\n path.includes(\"\\0\")\n ) {\n throw new RunCredentialValidationError(`invalid run credential file path: ${path}`);\n }\n const segments = path.split(\"/\");\n if (segments.some((segment) => segment.length === 0 || segment === \".\" || segment === \"..\")) {\n throw new RunCredentialValidationError(`invalid run credential file path: ${path}`);\n }\n return path;\n}\n\nfunction assertEnvironmentName(name: string, label: string): void {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n throw new RunCredentialValidationError(`invalid ${label}: ${name}`);\n }\n}\n\n/**\n * Validate the untrusted host-port response before any secret is written to a\n * box. The host owns credential selection; Opengeni owns scope checks, bounds,\n * path safety, and the transport lifecycle.\n */\nexport function normalizeRunCredentialsResolution(\n resolution: Extract<RunCredentialsResolution, { status: \"not_applicable\" }>,\n expected: RunCredentialExpectedScope,\n now?: Date,\n): null;\nexport function normalizeRunCredentialsResolution(\n resolution: Exclude<RunCredentialsResolution, { status: \"not_applicable\" }>,\n expected: RunCredentialExpectedScope,\n now?: Date,\n): NormalizedRunCredentialMaterial;\nexport function normalizeRunCredentialsResolution(\n resolution: RunCredentialsResolution,\n expected: RunCredentialExpectedScope,\n now?: Date,\n): NormalizedRunCredentialMaterial | null;\nexport function normalizeRunCredentialsResolution(\n resolution: RunCredentialsResolution,\n expected: RunCredentialExpectedScope,\n now: Date = new Date(),\n): NormalizedRunCredentialMaterial | null {\n if (!isRecord(resolution)) {\n throw new RunCredentialValidationError(\"run credential resolution must be an object\");\n }\n const candidate = resolution as unknown as Record<string, unknown>;\n if (\n candidate.status !== \"ok\" &&\n candidate.status !== \"auth_needed\" &&\n candidate.status !== \"not_applicable\"\n ) {\n throw new RunCredentialValidationError(\"run credential resolution status is invalid\");\n }\n assertResolutionScope(candidate, expected);\n if (candidate.status === \"not_applicable\") return null;\n const authNeeded = normalizeAuthNeeded(candidate.authNeeded, candidate.status === \"auth_needed\");\n if (candidate.status === \"auth_needed\") {\n return {\n environment: {},\n files: [],\n fileEnvironment: {},\n expiresAt: null,\n authNeeded,\n };\n }\n\n if (!isRecord(candidate.environment)) {\n throw new RunCredentialValidationError(\"run credential environment must be an object\");\n }\n const environmentEntries = Object.entries(candidate.environment);\n if (environmentEntries.length > MAX_ENVIRONMENT_ENTRIES) {\n throw new RunCredentialValidationError(\n `run credential environment exceeds ${MAX_ENVIRONMENT_ENTRIES} entries`,\n );\n }\n let totalBytes = 0;\n const environment: Record<string, string> = {};\n for (const [name, rawValue] of environmentEntries) {\n assertEnvironmentName(name, \"run credential environment name\");\n const value = requiredBoundedString(\n rawValue,\n `run credential environment value: ${name}`,\n MAX_ENVIRONMENT_VALUE_BYTES,\n );\n const valueBytes = byteLength(value);\n totalBytes += valueBytes;\n Object.defineProperty(environment, name, {\n value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n\n if (candidate.files !== undefined && !Array.isArray(candidate.files)) {\n throw new RunCredentialValidationError(\"run credential files must be an array\");\n }\n const files = candidate.files ?? [];\n if (files.length > MAX_CREDENTIAL_FILES) {\n throw new RunCredentialValidationError(\n `run credential file count exceeds ${MAX_CREDENTIAL_FILES}`,\n );\n }\n const paths = new Map<string, string>();\n const normalizedFiles = files.map((file, index) => {\n if (!isRecord(file)) {\n throw new RunCredentialValidationError(`run credential file ${index} must be an object`);\n }\n const path = normalizeRelativeFilePath(\n requiredBoundedString(file.path, `run credential file ${index} path`, 240),\n );\n const folded = path.toLocaleLowerCase(\"en-US\");\n const collision = paths.get(folded);\n if (collision !== undefined) {\n throw new RunCredentialValidationError(\n `run credential file path collision: ${collision} and ${path}`,\n );\n }\n paths.set(folded, path);\n const content = requiredBoundedString(\n file.content,\n `run credential file content: ${path}`,\n MAX_CREDENTIAL_FILE_BYTES,\n );\n const contentBytes = byteLength(content);\n if (file.mode !== undefined && file.mode !== \"0400\" && file.mode !== \"0600\") {\n throw new RunCredentialValidationError(`run credential file mode is invalid: ${path}`);\n }\n totalBytes += contentBytes;\n return { path, content, mode: file.mode ?? \"0600\" } as RunCredentialFile;\n });\n\n if (candidate.fileEnvironment !== undefined && !isRecord(candidate.fileEnvironment)) {\n throw new RunCredentialValidationError(\"run credential fileEnvironment must be an object\");\n }\n const fileEnvironment: Record<string, string> = {};\n for (const [name, unresolvedPath] of Object.entries(candidate.fileEnvironment ?? {})) {\n assertEnvironmentName(name, \"run credential file environment name\");\n if (Object.prototype.hasOwnProperty.call(environment, name)) {\n throw new RunCredentialValidationError(\n `run credential environment name is declared twice: ${name}`,\n );\n }\n const path = normalizeRelativeFilePath(\n requiredBoundedString(unresolvedPath, `run credential file environment path: ${name}`, 240),\n );\n if (!paths.has(path.toLocaleLowerCase(\"en-US\"))) {\n throw new RunCredentialValidationError(\n `run credential file environment references an unknown file: ${path}`,\n );\n }\n Object.defineProperty(fileEnvironment, name, {\n value: path,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n if (environmentEntries.length + Object.keys(fileEnvironment).length > MAX_ENVIRONMENT_ENTRIES) {\n throw new RunCredentialValidationError(\n `combined run credential environment exceeds ${MAX_ENVIRONMENT_ENTRIES} entries`,\n );\n }\n if (totalBytes > MAX_TOTAL_MATERIAL_BYTES) {\n throw new RunCredentialValidationError(\n `run credential material exceeds ${MAX_TOTAL_MATERIAL_BYTES} bytes`,\n );\n }\n\n let expiresAt: Date | null = null;\n if (candidate.expiresAt !== undefined && candidate.expiresAt !== null) {\n const expiry = requiredBoundedString(candidate.expiresAt, \"run credential expiry\", 128);\n expiresAt = new Date(expiry);\n if (!Number.isFinite(expiresAt.getTime()) || expiresAt.getTime() <= now.getTime()) {\n throw new RunCredentialValidationError(\"run credential expiry is invalid or already expired\");\n }\n }\n const parsedMcp = CredentialProviderMcpMaterial.safeParse(\n candidate.mcp === undefined ? [] : candidate.mcp,\n );\n if (!parsedMcp.success) {\n // Zod issues can contain untrusted inputs. Never expose credential values\n // through errors that a worker may publish or log.\n throw new RunCredentialValidationError(\"run MCP credential material is invalid\");\n }\n // Per-target expiry is enforced by the attempt-local MCP controller. A\n // stale or unselected entry must not prevent unrelated sandbox material.\n return {\n environment,\n files: normalizedFiles,\n fileEnvironment,\n expiresAt,\n authNeeded,\n ...(parsedMcp.data.length ? { mcp: parsedMcp.data } : {}),\n };\n}\n\nfunction assertPathIdentity(value: string, label: string): string {\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(value)) {\n throw new RunCredentialValidationError(`${label} is not safe for a credential path`);\n }\n return value;\n}\n\nexport function runCredentialRoot(sessionId: string): string {\n return `/tmp/opengeni-run-credentials/${assertPathIdentity(sessionId, \"sessionId\")}`;\n}\n\nexport function runCredentialPointerFile(sessionId: string): string {\n return `${runCredentialRoot(sessionId)}/current`;\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nfunction base64(value: string): string {\n return Buffer.from(value, \"utf8\").toString(\"base64\");\n}\n\nfunction portableBase64DecodeCommand(): string {\n return [\n \"{\",\n \"if printf %s QQ== | base64 -d >/dev/null 2>&1; then base64 -d\",\n \"elif printf %s QQ== | base64 -D >/dev/null 2>&1; then base64 -D\",\n \"elif command -v openssl >/dev/null 2>&1; then openssl base64 -d -A\",\n \"else exit 69\",\n \"fi\",\n \"}\",\n ].join(\"\\n\");\n}\n\n/** Prefer util-linux flock; fall back to an atomic, stale-reaped mkdir lock. */\nfunction pointerLockAcquireCommands(root: string): string[] {\n const lockFile = shellQuote(`${root}/.pointer.lock`);\n const lockDirectory = shellQuote(`${root}/.pointer.lockdir`);\n return [\n `if command -v flock >/dev/null 2>&1; then`,\n ` exec 9>${lockFile}`,\n \" flock -w 30 9\",\n \" _opengeni_pointer_lock_kind=flock\",\n \"else\",\n ` _opengeni_pointer_lock_dir=${lockDirectory}`,\n \" _opengeni_pointer_lock_deadline=$(($(date +%s) + 30))\",\n ' while ! mkdir \"$_opengeni_pointer_lock_dir\" 2>/dev/null; do',\n ` if find \"$_opengeni_pointer_lock_dir\" -prune -mmin +${PORTABLE_LOCK_STALE_MINUTES} -print 2>/dev/null | grep -q .; then`,\n ' _opengeni_stale_lock=\"${_opengeni_pointer_lock_dir}.stale.$$\"',\n ' if mv \"$_opengeni_pointer_lock_dir\" \"$_opengeni_stale_lock\" 2>/dev/null; then',\n ' rm -rf -- \"$_opengeni_stale_lock\"',\n \" continue\",\n \" fi\",\n \" fi\",\n ' [ \"$(date +%s)\" -lt \"$_opengeni_pointer_lock_deadline\" ] || exit 73',\n \" sleep 0.1\",\n \" done\",\n \" _opengeni_pointer_lock_kind=directory\",\n ` trap 'rmdir ${lockDirectory} 2>/dev/null || :' EXIT HUP INT TERM`,\n \"fi\",\n ];\n}\n\nfunction pointerLockReleaseCommands(): string[] {\n return [\n 'if [ \"${_opengeni_pointer_lock_kind:-}\" = directory ]; then',\n ' rmdir \"$_opengeni_pointer_lock_dir\" 2>/dev/null || :',\n \" trap - EXIT HUP INT TERM\",\n \"fi\",\n ];\n}\n\nfunction outputOf(result: unknown): string {\n if (typeof result === \"string\") return result;\n if (!result || typeof result !== \"object\") return \"\";\n const candidate = result as {\n output?: unknown;\n stdout?: unknown;\n stderr?: unknown;\n };\n return [candidate.output, candidate.stdout, candidate.stderr]\n .filter((value): value is string => typeof value === \"string\")\n .join(\"\\n\");\n}\n\nasync function runCredentialCommand(\n session: RunCredentialCommandSession,\n cmd: string,\n commandRunner?: RunCredentialCommandRunner,\n): Promise<void> {\n const marked = `set +x\\nset -eu\\n${cmd}\\nprintf '\\\\n${COMMAND_OK_MARKER}\\\\n'`;\n const args: ExecCommandArgs = {\n cmd: `set +x\\nenv -u BASH_ENV bash --noprofile --norc -c ${shellQuote(marked)}`,\n yieldTimeMs: 120_000,\n maxOutputTokens: 4_000,\n };\n const result = commandRunner\n ? await commandRunner(session, args)\n : session.exec\n ? await session.exec(args)\n : session.execCommand\n ? await session.execCommand(args)\n : undefined;\n if (!outputOf(result).includes(COMMAND_OK_MARKER)) {\n throw new Error(\"run credential materialization command failed\");\n }\n}\n\nasync function writeCredentialFile(\n session: RunCredentialCommandSession,\n directory: string,\n relativePath: string,\n content: string,\n commandRunner?: RunCredentialCommandRunner,\n): Promise<void> {\n await runCredentialCommand(\n session,\n credentialFileCommand(directory, relativePath, ': > \"$_opengeni_credential_path\"'),\n commandRunner,\n );\n const encoded = base64(content);\n for (let offset = 0; offset < encoded.length; offset += WRITE_CHUNK_BYTES) {\n const chunk = encoded.slice(offset, offset + WRITE_CHUNK_BYTES);\n await runCredentialCommand(\n session,\n credentialFileCommand(\n directory,\n relativePath,\n `printf %s ${shellQuote(chunk)} | ${portableBase64DecodeCommand()} >> \"$_opengeni_credential_path\"`,\n ),\n commandRunner,\n );\n }\n await runCredentialCommand(\n session,\n credentialFileCommand(\n directory,\n relativePath,\n `[ \"$(wc -c < \"$_opengeni_credential_path\" | tr -d '[:space:]')\" = ${shellQuote(String(byteLength(content)))} ]`,\n ),\n commandRunner,\n );\n}\n\nfunction credentialFileCommand(directory: string, relativePath: string, command: string): string {\n // Avoid multiplying accepted path quotes through nested shell wrappers. The\n // existing outer Bash decodes only literal UTF-8 bytes, including trailing\n // newlines, without evaluating host-provided text or invoking a path decoder.\n const escapedPath = [...Buffer.from(relativePath, \"utf8\")]\n .map((byte) => `\\\\x${byte.toString(16).padStart(2, \"0\")}`)\n .join(\"\");\n return [\n `printf -v _opengeni_credential_path %b ${shellQuote(escapedPath)}`,\n `_opengeni_credential_path=${shellQuote(directory)}/\"$_opengeni_credential_path\"`,\n command,\n ].join(\"\\n\");\n}\n\nexport type MaterializeRunCredentialsOptions = {\n sessionId: string;\n attemptId: string;\n executionGeneration: number;\n /** Initial provision after recovery may prune generations from older attempts. */\n pruneOtherAttempts?: boolean;\n /** An all-auth-needed replacement removes every prior readable generation. */\n prunePreviousGenerations?: boolean;\n /** Renewal keeps the active and immediately prior same-attempt generations. */\n pruneSupersededGenerations?: boolean;\n commandRunner?: RunCredentialCommandRunner;\n};\n\n/** Materialize one complete immutable generation, then atomically flip current. */\nexport async function materializeRunCredentials(\n session: RunCredentialCommandSession,\n material: NormalizedRunCredentialMaterial,\n options: MaterializeRunCredentialsOptions,\n): Promise<void> {\n const root = runCredentialRoot(options.sessionId);\n const attemptId = assertPathIdentity(options.attemptId, \"attemptId\");\n if (!Number.isSafeInteger(options.executionGeneration) || options.executionGeneration < 0) {\n throw new RunCredentialValidationError(\"executionGeneration must be a non-negative integer\");\n }\n const nonce = crypto.randomUUID();\n const prefix = `${attemptId}-${options.executionGeneration}-`;\n const versionName = `${attemptId}-${options.executionGeneration}-${nonce}`;\n const stage = `${root}/versions/.stage-${versionName}`;\n const version = `${root}/versions/${versionName}`;\n for (const file of material.files) {\n const mode = file.mode ?? \"0600\";\n if (mode !== \"0400\" && mode !== \"0600\") {\n throw new RunCredentialValidationError(`run credential file mode is invalid: ${file.path}`);\n }\n }\n await runCredentialCommand(\n session,\n [\n \"umask 077\",\n `mkdir -p -- ${shellQuote(`${root}/versions`)}`,\n `chmod -- 0700 ${shellQuote(root)} ${shellQuote(`${root}/versions`)}`,\n `rm -rf -- ${shellQuote(stage)}`,\n `mkdir -p -- ${shellQuote(`${stage}/files`)}`,\n ].join(\"\\n\"),\n options.commandRunner,\n );\n\n const environmentLines = [\n ...Object.entries(material.environment).map(\n ([name, value]) => `export ${name}=${shellQuote(value)}`,\n ),\n ...Object.entries(material.fileEnvironment).map(\n ([name, path]) => `export ${name}=${shellQuote(`${version}/files/${path}`)}`,\n ),\n ];\n await writeCredentialFile(\n session,\n stage,\n \"env\",\n environmentLines.length > 0 ? `${environmentLines.join(\"\\n\")}\\n` : \"\",\n options.commandRunner,\n );\n await runCredentialCommand(\n session,\n `chmod -- 0600 ${shellQuote(`${stage}/env`)}`,\n options.commandRunner,\n );\n\n for (const file of material.files) {\n const directory = `${stage}/files`;\n await runCredentialCommand(\n session,\n credentialFileCommand(directory, file.path, 'mkdir -p -- \"${_opengeni_credential_path%/*}\"'),\n options.commandRunner,\n );\n await writeCredentialFile(session, directory, file.path, file.content, options.commandRunner);\n await runCredentialCommand(\n session,\n credentialFileCommand(\n directory,\n file.path,\n `chmod -- ${shellQuote(file.mode ?? \"0600\")} \"$_opengeni_credential_path\"`,\n ),\n options.commandRunner,\n );\n }\n\n await runCredentialCommand(\n session,\n [\n // Bind validated identifiers once rather than repeatedly expanding long\n // paths through cancellation and SDK run-as shell quoting.\n `_opengeni_credential_root=${shellQuote(root)}`,\n `_opengeni_credential_version_name=${shellQuote(versionName)}`,\n `_opengeni_credential_prefix=${shellQuote(prefix)}`,\n ...pointerLockAcquireCommands(root),\n 'previous=$(cat -- \"$_opengeni_credential_root/current\" 2>/dev/null || :)',\n 'mv -- \"$_opengeni_credential_root/versions/.stage-$_opengeni_credential_version_name\" \"$_opengeni_credential_root/versions/$_opengeni_credential_version_name\"',\n 'printf \\'%s\\\\n\\' \"$_opengeni_credential_version_name\" > \"$_opengeni_credential_root/.next\"',\n 'mv -f -- \"$_opengeni_credential_root/.next\" \"$_opengeni_credential_root/current\"',\n ...(options.prunePreviousGenerations\n ? [\n 'find \"$_opengeni_credential_root/versions\" -mindepth 1 -maxdepth 1 ! -name \"$_opengeni_credential_version_name\" -exec rm -rf -- {} +',\n ]\n : options.pruneOtherAttempts\n ? [\n 'find \"$_opengeni_credential_root/versions\" -mindepth 1 -maxdepth 1 ! -name \"${_opengeni_credential_prefix}*\" -exec rm -rf -- {} +',\n ]\n : options.pruneSupersededGenerations\n ? [\n 'for candidate in \"$_opengeni_credential_root/versions/$_opengeni_credential_prefix\"*; do',\n ` [ -e \"$candidate\" ] || continue`,\n ` name=\\${candidate##*/}`,\n ' [ \"$name\" = \"$_opengeni_credential_version_name\" ] || [ \"$name\" = \"$previous\" ] || rm -rf -- \"$candidate\"',\n \"done\",\n ]\n : []),\n ...pointerLockReleaseCommands(),\n ].join(\"\\n\"),\n options.commandRunner,\n );\n}\n\nexport async function clearRunCredentials(\n session: RunCredentialCommandSession,\n sessionId: string,\n commandRunner?: RunCredentialCommandRunner,\n): Promise<void> {\n const root = runCredentialRoot(sessionId);\n await runCredentialCommand(\n session,\n [\n `if [ -d ${shellQuote(root)} ]; then`,\n ...pointerLockAcquireCommands(root).map((line) => ` ${line}`),\n ` rm -f -- ${shellQuote(`${root}/current`)} ${shellQuote(`${root}/.next`)}`,\n ` rm -rf -- ${shellQuote(`${root}/versions`)}`,\n ...pointerLockReleaseCommands().map((line) => ` ${line}`),\n \"fi\",\n ].join(\"\\n\"),\n commandRunner,\n );\n}\n\n/**\n * Remove only generations owned by one attempt. A successor may already have\n * atomically activated its own pointer after queue admission; this cleanup must\n * never clear or overwrite that newer generation.\n */\nexport async function clearRunCredentialsForAttempt(\n session: RunCredentialCommandSession,\n options: Pick<\n MaterializeRunCredentialsOptions,\n \"sessionId\" | \"attemptId\" | \"executionGeneration\"\n >,\n commandRunner?: RunCredentialCommandRunner,\n): Promise<void> {\n const root = runCredentialRoot(options.sessionId);\n const attemptId = assertPathIdentity(options.attemptId, \"attemptId\");\n if (!Number.isSafeInteger(options.executionGeneration) || options.executionGeneration < 0) {\n throw new RunCredentialValidationError(\"executionGeneration must be a non-negative integer\");\n }\n const prefix = `${attemptId}-${options.executionGeneration}-`;\n await runCredentialCommand(\n session,\n [\n `if [ -d ${shellQuote(root)} ]; then`,\n ...pointerLockAcquireCommands(root).map((line) => ` ${line}`),\n ` if [ -r ${shellQuote(`${root}/current`)} ]; then`,\n ` current=$(cat -- ${shellQuote(`${root}/current`)} 2>/dev/null || :)`,\n ` case \"$current\" in ${shellQuote(prefix)}*) rm -f -- ${shellQuote(`${root}/current`)} ;; esac`,\n \" fi\",\n ` if [ -d ${shellQuote(`${root}/versions`)} ]; then`,\n ` find ${shellQuote(`${root}/versions`)} -mindepth 1 -maxdepth 1 -name ${shellQuote(`${prefix}*`)} -exec rm -rf -- {} +`,\n ` find ${shellQuote(`${root}/versions`)} -mindepth 1 -maxdepth 1 -name ${shellQuote(`.stage-${prefix}*`)} -exec rm -rf -- {} +`,\n \" fi\",\n ...pointerLockReleaseCommands().map((line) => ` ${line}`),\n \"fi\",\n ].join(\"\\n\"),\n commandRunner,\n );\n}\n\n/** Prefix one sandbox command so every new process observes the active generation. */\nexport function withRunCredentialEnvironment(cmd: string, sessionId: string): string {\n const root = runCredentialRoot(sessionId);\n const pointerFile = runCredentialPointerFile(sessionId);\n return [\n `if [ -r ${shellQuote(pointerFile)} ]; then`,\n ` _opengeni_credential_version=$(cat -- ${shellQuote(pointerFile)} 2>/dev/null || :)`,\n ' case \"$_opengeni_credential_version\" in',\n \" ''|*[!A-Za-z0-9_-]*) ;;\",\n \" *)\",\n ` _opengeni_credential_env=${shellQuote(`${root}/versions`)}/\"$_opengeni_credential_version/env\"`,\n ' if [ -r \"$_opengeni_credential_env\" ]; then',\n \" set -a\",\n ' . \"$_opengeni_credential_env\"',\n \" set +a\",\n \" fi\",\n \" unset _opengeni_credential_env\",\n \" ;;\",\n \" esac\",\n \" unset _opengeni_credential_version\",\n \"fi\",\n cmd,\n ].join(\"\\n\");\n}\n\n/**\n * Preserve the provider session identity/capabilities while decorating only\n * command creation. Trailing invocation options stay unchanged; non-command\n * methods stay bound to the original instance.\n */\nexport function withRunCredentialsSession<T extends object>(session: T, sessionId: string): T {\n return new Proxy(session, {\n get(target, property, receiver) {\n if (property === \"exec\" || property === \"execCommand\") {\n const command = Reflect.get(target, property, target) as\n | ((args: ExecCommandArgs, ...callArgs: unknown[]) => Promise<unknown>)\n | undefined;\n if (!command) return undefined;\n return async (args: ExecCommandArgs, ...callArgs: unknown[]) =>\n await command.call(\n target,\n { ...args, cmd: withRunCredentialEnvironment(args.cmd, sessionId) },\n ...callArgs,\n );\n }\n const value = Reflect.get(target, property, receiver) as unknown;\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n });\n}\n\n/** Decorate every client-created/resumed session after the host seeds it. */\nexport function withRunCredentialsClient(\n client: SandboxClient,\n sessionId: string,\n onSessionReady?: RunCredentialSessionReady,\n): SandboxClient {\n const decorated = new WeakMap<object, SandboxSessionLike>();\n const wrap = async <T extends SandboxSessionLike>(session: T): Promise<T> => {\n const existing = decorated.get(session);\n if (existing) return existing as T;\n await onSessionReady?.(session);\n const wrapped = withRunCredentialsSession(session, sessionId);\n decorated.set(session, wrapped);\n return wrapped;\n };\n return {\n backendId: client.backendId,\n ...(client.supportsDefaultOptions !== undefined\n ? { supportsDefaultOptions: client.supportsDefaultOptions }\n : {}),\n ...(client.create\n ? {\n create: async (...args: any[]) => await wrap(await (client.create as any)(...args)),\n }\n : {}),\n ...(client.resume\n ? {\n resume: async (...args: any[]) => await wrap(await (client.resume as any)(...args)),\n }\n : {}),\n ...(client.delete\n ? {\n delete: async (state: SandboxSessionState) => await client.delete!(state),\n }\n : {}),\n ...(client.serializeSessionState\n ? {\n serializeSessionState: async (state: SandboxSessionState, options) =>\n await client.serializeSessionState!(state, options),\n }\n : {}),\n ...(client.canPersistOwnedSessionState\n ? {\n canPersistOwnedSessionState: async (state: SandboxSessionState) =>\n await client.canPersistOwnedSessionState!(state),\n }\n : {}),\n ...(client.canReusePreservedOwnedSession\n ? {\n canReusePreservedOwnedSession: async (state: SandboxSessionState) =>\n await client.canReusePreservedOwnedSession!(state),\n }\n : {}),\n ...(client.deserializeSessionState\n ? {\n deserializeSessionState: async (state: Record<string, unknown>) =>\n await client.deserializeSessionState!(state),\n }\n : {}),\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { posix as posixPath } from \"node:path\";\nimport { managedCodemodeClientEnvironment } from \"./codemode-client\";\n\nimport type {\n ExecCommandArgs,\n SandboxClient,\n SandboxSessionLike,\n SandboxSessionState,\n} from \"@openai/agents/sandbox\";\n\nconst MAX_CODEMODE_SESSION_ID_BYTES = 512;\n\nexport class CodemodeTokenPathError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CodemodeTokenPathError\";\n }\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nfunction assertCodemodeSessionId(sessionId: string): string {\n if (\n !sessionId ||\n sessionId.trim() !== sessionId ||\n new TextEncoder().encode(sessionId).byteLength > MAX_CODEMODE_SESSION_ID_BYTES ||\n sessionId.includes(\"\\0\")\n ) {\n throw new CodemodeTokenPathError(\"Codemode session id is invalid\");\n }\n return sessionId;\n}\n\nfunction assertCodemodeFilePath(value: string, label: string): string {\n if (!value || value.includes(\"\\0\") || !posixPath.isAbsolute(value)) {\n throw new CodemodeTokenPathError(`${label} must be absolute`);\n }\n return posixPath.normalize(value);\n}\n\nexport function shellCodemodePath(value: string): string {\n return shellQuote(assertCodemodeFilePath(value, \"Codemode token file\"));\n}\n\n/**\n * Derive the per-session token file beside the legacy manifest pointer.\n *\n * The manifest pointer stays box-global so an already-warm shared sandbox does\n * not receive an illegal environment delta. Every Opengeni command overrides\n * that pointer with this deterministic path. The hash is path hygiene and\n * avoids disclosing host/session ids in filenames; filesystem paths are not an\n * authorization boundary. The delegated bearer's session claim remains the\n * authority boundary for Codemode calls.\n */\nexport function codemodeTokenFileForSession(manifestTokenFile: string, sessionId: string): string {\n const normalizedManifestFile = assertCodemodeFilePath(\n manifestTokenFile,\n \"Codemode manifest token file\",\n );\n const digest = createHash(\"sha256\").update(assertCodemodeSessionId(sessionId)).digest(\"hex\");\n return posixPath.join(posixPath.dirname(normalizedManifestFile), \"codemode-tokens\", digest);\n}\n\nexport function codemodeTokenFileFromEnvironment(\n environment: Readonly<Record<string, string>>,\n sessionId: string,\n): string {\n const manifestTokenFile =\n environment.OPENGENI_CODEMODE_TOKEN_FILE ??\n `${environment.HOME ?? \"/workspace\"}/.opengeni/codemode-token`;\n return codemodeTokenFileForSession(manifestTokenFile, sessionId);\n}\n\n/**\n * Prefix one sandbox command with its attempt-current Codemode routing.\n *\n * The token pointer is session-specific. The URL is deliberately projected on\n * every exec too: a warm managed box keeps its baked manifest environment, but\n * the externally reachable deployment/tunnel origin may change between turns.\n * Per-command export makes a resumed box use the current route without an\n * illegal live-manifest environment mutation.\n */\nexport function withCodemodeTokenEnvironment(\n cmd: string,\n tokenFile: string,\n codemodeUrl?: string,\n clientDirectory?: string,\n): string {\n return [\n `export OPENGENI_CODEMODE_TOKEN_FILE=${shellCodemodePath(tokenFile)}`,\n ...(codemodeUrl ? [`export OPENGENI_CODEMODE_URL=${shellQuote(codemodeUrl)}`] : []),\n ...(clientDirectory ? managedCodemodeClientEnvironment(clientDirectory) : []),\n cmd,\n ].join(\"\\n\");\n}\n\n/** Decorate command creation without changing identity, capabilities or trailing options. */\nexport function withCodemodeTokenSession<T extends object>(\n session: T,\n tokenFile: string,\n codemodeUrl?: string,\n clientDirectory?: string,\n): T {\n return new Proxy(session, {\n get(target, property, receiver) {\n if (property === \"exec\" || property === \"execCommand\") {\n const command = Reflect.get(target, property, target) as\n | ((args: ExecCommandArgs, ...callArgs: unknown[]) => Promise<unknown>)\n | undefined;\n if (!command) return undefined;\n return async (args: ExecCommandArgs, ...callArgs: unknown[]) =>\n await command.call(\n target,\n {\n ...args,\n cmd: withCodemodeTokenEnvironment(args.cmd, tokenFile, codemodeUrl, clientDirectory),\n },\n ...callArgs,\n );\n }\n const value = Reflect.get(target, property, receiver) as unknown;\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n });\n}\n\n/** Decorate every client-created/resumed session with one session pointer. */\nexport function withCodemodeTokenClient(\n client: SandboxClient,\n tokenFile: string,\n codemodeUrl?: string,\n clientDirectory?: string,\n): SandboxClient {\n const decorated = new WeakMap<object, SandboxSessionLike>();\n const wrap = <T extends SandboxSessionLike>(session: T): T => {\n const existing = decorated.get(session);\n if (existing) return existing as T;\n const wrapped = withCodemodeTokenSession(session, tokenFile, codemodeUrl, clientDirectory);\n decorated.set(session, wrapped);\n return wrapped;\n };\n return {\n backendId: client.backendId,\n ...(client.supportsDefaultOptions !== undefined\n ? { supportsDefaultOptions: client.supportsDefaultOptions }\n : {}),\n ...(client.create\n ? { create: async (...args: any[]) => wrap(await (client.create as any)(...args)) }\n : {}),\n ...(client.resume\n ? { resume: async (...args: any[]) => wrap(await (client.resume as any)(...args)) }\n : {}),\n ...(client.delete\n ? { delete: async (state: SandboxSessionState) => await client.delete!(state) }\n : {}),\n ...(client.serializeSessionState\n ? {\n serializeSessionState: async (state: SandboxSessionState, options) =>\n await client.serializeSessionState!(state, options),\n }\n : {}),\n ...(client.canPersistOwnedSessionState\n ? {\n canPersistOwnedSessionState: async (state: SandboxSessionState) =>\n await client.canPersistOwnedSessionState!(state),\n }\n : {}),\n ...(client.canReusePreservedOwnedSession\n ? {\n canReusePreservedOwnedSession: async (state: SandboxSessionState) =>\n await client.canReusePreservedOwnedSession!(state),\n }\n : {}),\n ...(client.deserializeSessionState\n ? {\n deserializeSessionState: async (state: Record<string, unknown>) =>\n await client.deserializeSessionState!(state),\n }\n : {}),\n } as SandboxClient;\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join, posix, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { SandboxSessionLike } from \"@openai/agents/sandbox\";\nimport { sandboxCommandExitCode } from \"./command-result\";\n\n/** Data shipped with the worker, never fetched from a package registry at turn time. */\nexport type ManagedCodemodeClient = {\n version: 1;\n files: { ogtool: string; \"client.mjs\": string; \"package.json\": string };\n};\n\nexport function managedCodemodeClientDigest(client: ManagedCodemodeClient): string {\n return createHash(\"sha256\").update(JSON.stringify(client)).digest(\"hex\");\n}\n\nexport function managedCodemodeClientDirectory(\n client: ManagedCodemodeClient,\n workspaceRoot = \"/workspace\",\n): string {\n if (!posix.isAbsolute(workspaceRoot) || workspaceRoot.includes(\"\\0\")) {\n throw new Error(\"Managed Codemode client workspace root must be absolute\");\n }\n return posix.join(\n workspaceRoot,\n \".opengeni/codemode-clients\",\n managedCodemodeClientDigest(client),\n );\n}\n\nexport async function buildManagedCodemodeClient(root: string): Promise<ManagedCodemodeClient> {\n const bundle = async (entry: string, format: \"esm\" | \"cjs\", banner?: string) => {\n const result = await Bun.build({\n entrypoints: [join(root, entry)],\n target: \"node\",\n format,\n minify: true,\n sourcemap: \"none\",\n ...(banner ? { banner } : {}),\n });\n if (!result.success || result.outputs.length !== 1) {\n throw new Error(`Managed Codemode client build failed: ${entry}`);\n }\n return await result.outputs[0]!.text();\n };\n return {\n version: 1,\n files: {\n ogtool: await bundle(\"packages/ogtool/src/cli.ts\", \"cjs\", \"#!/usr/bin/env node\"),\n \"client.mjs\": await bundle(\"packages/codemode/src/index.ts\", \"esm\"),\n // The extensionless executable must not inherit a user's ESM workspace.\n \"package.json\": '{\"type\":\"commonjs\"}\\n',\n },\n };\n}\n\nlet releaseClient: Promise<ManagedCodemodeClient> | undefined;\nexport function loadManagedCodemodeClient(): Promise<ManagedCodemodeClient> {\n return (releaseClient ??= (async () => {\n const moduleDir = dirname(fileURLToPath(import.meta.url));\n // A checkout must not reuse stale dist assets after source changes.\n const root = resolve(moduleDir, \"../../../..\");\n if (\n import.meta.url.endsWith(\"/src/sandbox/codemode-client.ts\") &&\n existsSync(join(root, \"packages/ogtool/src/cli.ts\"))\n ) {\n return await buildManagedCodemodeClient(root);\n }\n const candidates = [\n join(moduleDir, \"assets/codemode-client.json\"),\n join(moduleDir, \"../assets/codemode-client.json\"),\n join(moduleDir, \"../../dist/assets/codemode-client.json\"),\n ];\n for (const path of candidates) {\n if (!existsSync(path)) continue;\n const value = JSON.parse(readFileSync(path, \"utf8\")) as ManagedCodemodeClient;\n if (\n !value ||\n typeof value !== \"object\" ||\n value.version !== 1 ||\n Object.keys(value).sort().join(\",\") !== \"files,version\" ||\n typeof value.files?.ogtool !== \"string\" ||\n typeof value.files?.[\"client.mjs\"] !== \"string\" ||\n value.files?.[\"package.json\"] !== '{\"type\":\"commonjs\"}\\n' ||\n Object.keys(value.files).sort().join(\",\") !== \"client.mjs,ogtool,package.json\"\n ) {\n throw new Error(\n \"Invalid deployment-owned managed Codemode client asset; rebuild the worker release\",\n );\n }\n return value;\n }\n // Published runtimes must carry their own exact bytes.\n throw new Error(\n \"Managed Codemode client asset missing; rebuild and deploy the matching worker/runtime package (do not install latest or replace the sandbox)\",\n );\n })());\n}\n\nfunction quote(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/** Immutable per-release paths permit old/new workers to share a warm box. */\nexport async function installManagedCodemodeClient(\n session: SandboxSessionLike,\n client: ManagedCodemodeClient,\n run: (cmd: string) => Promise<unknown>,\n runAs?: string,\n workspaceRoot = \"/workspace\",\n): Promise<void> {\n const directory = managedCodemodeClientDirectory(client, workspaceRoot);\n const digest = managedCodemodeClientDigest(client);\n const verify = `\nconst fs = require('node:fs'), crypto = require('node:crypto');\nconst root = ${JSON.stringify(directory)};\nif (!fs.lstatSync(root).isDirectory()) process.exit(1);\nfor (const name of ['ogtool', 'client.mjs', 'package.json']) {\n if (!fs.lstatSync(root + '/' + name).isFile()) process.exit(1);\n}\nfs.accessSync(root + '/ogtool', fs.constants.X_OK);\nconst files = {ogtool: fs.readFileSync(root + '/ogtool', 'utf8'), 'client.mjs': fs.readFileSync(root + '/client.mjs', 'utf8'), 'package.json': fs.readFileSync(root + '/package.json', 'utf8')};\nif (crypto.createHash('sha256').update(JSON.stringify({version: 1, files})).digest('hex') !== ${JSON.stringify(digest)}) process.exit(1);\n`;\n if (sandboxCommandExitCode(await run(`node -e ${quote(verify)} 2>/dev/null`)) === 0) return;\n const editor = session.createEditor?.(runAs);\n if (!editor)\n throw new Error(\n \"Managed Codemode client delivery requires sandbox file ingress; update the sandbox provider adapter\",\n );\n const stage = `${posix.dirname(directory)}/stage-${randomUUID()}.json`;\n let installationFailure: { error: unknown } | undefined;\n try {\n await editor.createFile({\n type: \"create_file\",\n path: stage,\n diff: `+${JSON.stringify(client)}`,\n });\n const install = `\nconst fs = require('node:fs'), crypto = require('node:crypto');\nconst raw = fs.readFileSync(${JSON.stringify(stage)}, 'utf8').trim();\nif (crypto.createHash('sha256').update(raw).digest('hex') !== ${JSON.stringify(digest)}) throw Error('Codemode client transfer integrity failure');\nconst data = JSON.parse(raw), root = ${JSON.stringify(directory)};\nfs.mkdirSync(root, {recursive: true});\nif (!fs.lstatSync(root).isDirectory()) throw Error('Codemode client directory must not be a symlink');\nfor (const name of ['package.json', 'ogtool', 'client.mjs']) {\n const tmp = root + '/' + name + '.' + crypto.randomUUID();\n fs.writeFileSync(tmp, data.files[name], {mode: 0o755, flag: 'wx'});\n fs.renameSync(tmp, root + '/' + name);\n}\n`;\n const result = await run(`node -e ${quote(install)} && node -e ${quote(verify)}`);\n if (sandboxCommandExitCode(result) !== 0) {\n throw new Error(\n \"Managed Codemode client delivery failed; verify Node and sandbox file ingress, then retry with the same worker release\",\n );\n }\n } catch (error) {\n installationFailure = { error };\n }\n try {\n await editor.deleteFile({ type: \"delete_file\", path: stage });\n } catch {\n // A provider can support ingress but lose its delete reply. Remove only\n // this exact attempt's staging file, through the same command fence.\n try {\n const cleanup = await run(\n `node -e ${quote(`require('node:fs').rmSync(${JSON.stringify(stage)}, {force: true})`)}`,\n );\n if (sandboxCommandExitCode(cleanup) !== 0) {\n throw new Error(\"Staging file removal failed\");\n }\n } catch {\n // This file contains only immutable, non-secret release bytes. Failed\n // housekeeping cannot invalidate a verified install or wrap its original\n // delivery error (especially pre-dispatch/outcome-unknown provenance).\n // Log one bounded identity, never provider errors, output, or client bytes.\n try {\n console.warn(\n \"Managed Codemode client staging cleanup failed; installation result preserved\",\n {\n stageFile: posix.basename(stage),\n installation: installationFailure ? \"failed\" : \"verified\",\n },\n );\n } catch {\n // Diagnostics must not change the installation result either.\n }\n }\n }\n if (installationFailure) throw installationFailure.error;\n}\n\nexport function managedCodemodeClientEnvironment(directory: string): string[] {\n return [\n // A routing proxy can switch to a Connected Machine during the attempt.\n // Its native client is projected by the connection-bound exec transport.\n 'if [ -z \"${OPENGENI_CODEMODE_NATIVE_CLIENT:-}\" ]; then',\n ` export PATH=${quote(directory)}:\"$PATH\"`,\n ` export OPENGENI_CODEMODE_CLIENT_MODULE=${quote(`${directory}/client.mjs`)}`,\n \"else\",\n \" unset OPENGENI_CODEMODE_CLIENT_MODULE\",\n \"fi\",\n ];\n}\n","import { resolveFirstPartyDelegationSecret, type Settings } from \"@opengeni/config\";\nimport { signDelegatedAccessToken } from \"@opengeni/contracts\";\n\nexport const CODEMODE_TOKEN_TTL_SECONDS = 60 * 60;\n\nexport type CodemodeAuthorityScope = {\n accountId: string;\n workspaceId: string;\n};\n\nexport type SandboxCodemodeAuthority = {\n sessionId: string;\n turnId: string;\n attemptId: string;\n executionGeneration: number;\n credentialRestriction?: \"developer_setup\";\n};\n\nexport type MintedSandboxCodemodeToken = {\n token: string;\n expiresAt: Date;\n};\n\n/**\n * Mint the one canonical exact-attempt Codemode bearer used by every compute\n * placement. Delivery is deliberately a separate concern: managed sandboxes\n * rotate it through a private file, while Connected Machines receive it only\n * in the environment of an authorized child process.\n */\nexport async function mintSandboxCodemodeToken(\n settings: Settings,\n scope: CodemodeAuthorityScope,\n authority: SandboxCodemodeAuthority,\n nowMs = Date.now(),\n): Promise<MintedSandboxCodemodeToken | undefined> {\n const delegationSecret = resolveFirstPartyDelegationSecret(settings);\n if (!delegationSecret) return undefined;\n const expiresAtSeconds = Math.floor(nowMs / 1000) + CODEMODE_TOKEN_TTL_SECONDS;\n const token = await signDelegatedAccessToken(delegationSecret, {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n subjectId: `sandbox:${authority.attemptId}`,\n subjectLabel: \"sandbox Codemode\",\n permissions: [\"codemode:call\"],\n sessionId: authority.sessionId,\n turnId: authority.turnId,\n attemptId: authority.attemptId,\n executionGeneration: authority.executionGeneration,\n ...(authority.credentialRestriction\n ? { credentialRestriction: authority.credentialRestriction }\n : {}),\n principalKind: \"agent_attempt\",\n exp: expiresAtSeconds,\n });\n return { token, expiresAt: new Date(expiresAtSeconds * 1000) };\n}\n","// @opengeni/runtime/sandbox — explicit desktop recording primitives.\n//\n// ffmpeg x11grab on :0 → mp4/webm artifact on the box → direct scoped PUT to\n// object storage → recording.available. ffmpeg reads exactly the :0 framebuffer\n// watched over Channel B (zero projection).\n//\n// These are PLAIN functions over a live, externally-owned session handle — NO\n// Temporal, NO worker RPC, NO actor. They live in the agent-loop-free leaf so the\n// SAME process that already holds the resumed-by-id box for an explicit manual or\n// on-verify capture authorizes a direct box-to-storage upload. Recording bytes never\n// enter worker memory or a Temporal payload (F10).\n//\n// ── Adversarial-review fixes folded in (module 05 §Adversarial) ──────────────\n// F1 exec is OPTIONAL on Modal (only execCommand) — every command dual-paths.\n// F3 exec/execCommand YIELDS — the stop and direct-upload commands are bounded.\n// F8 size is gated on the box first (stat); over-limit artifacts fail instead\n// of being uploaded partially.\n// FR curl reads the absolute /tmp artifact in the box and sends it directly to\n// the short-lived scoped URL. No workspace-root read API is involved.\n// F9 the box file is deleted ONLY after the storage PUT confirms — never\n// before (so a failed upload leaves the bytes recoverable for a retry).\n// F12 ffmpeg/x11vnc backgrounding does not block the yield (nohup … & echo $!).\n// F14 duration is computed from wall-clock (stop − start), not assumed.\n\nimport { DESKTOP_STREAM_PORT } from \"@opengeni/contracts\";\n\nexport { DESKTOP_STREAM_PORT };\n\nexport type RecordingCodec = \"h264-mp4\" | \"vp9-webm\";\nexport type RecordingContentType = \"video/mp4\" | \"video/webm\";\n\nconst DEFAULT_MAX_SECONDS = 600; // 10 min hard ceiling (the -t bound)\nconst DEFAULT_FRAMERATE = 15;\nconst DEFAULT_MAX_BYTES = 268_435_456; // 256 MB\nconst DEFAULT_DIMENSIONS: [number, number] = [1280, 800];\n// The SIGINT-and-wait loop is bounded well under the command yield window (F3).\nconst STOP_YIELD_MS = 20_000;\nconst EXEC_YIELD_MS = 15_000;\n\nexport function contentTypeForCodec(codec: RecordingCodec): RecordingContentType {\n return codec === \"vp9-webm\" ? \"video/webm\" : \"video/mp4\";\n}\nexport function extForCodec(codec: RecordingCodec): string {\n return codec === \"vp9-webm\" ? \"webm\" : \"mp4\";\n}\n\n/** No exec/execCommand on the session — the box cannot run ffmpeg. */\nexport class RecordingUnavailableError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RecordingUnavailableError\";\n }\n}\n/** ffmpeg failed, the file is missing, or the artifact is over its size limit. */\nexport class RecordingError extends Error {\n constructor(\n message: string,\n readonly reason: \"ffmpeg-error\" | \"box-death\" | \"max-bytes-exceeded\" | \"display-unavailable\",\n ) {\n super(message);\n this.name = \"RecordingError\";\n }\n}\n\n// The structural slice of a provider session the recording loop drives. exec and\n// execCommand are optional (Modal has only execCommand — F1).\ntype ExecResultLike = {\n output?: string;\n stdout?: string;\n stderr?: string;\n exitCode?: number | null;\n sessionId?: number;\n};\ntype RecordingSession = {\n exec?: (args: {\n cmd: string;\n runAs?: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<ExecResultLike>;\n execCommand?: (args: {\n cmd: string;\n runAs?: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n }) => Promise<string>;\n};\n\nfunction shq(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\nfunction resultOutput(result: ExecResultLike | string): string {\n if (typeof result === \"string\") return result;\n return [result.output, result.stderr, result.stdout]\n .filter((v): v is string => typeof v === \"string\" && v.length > 0)\n .join(\"\\n\");\n}\n\n// Default per-command output cap (tokens). Recording transfer does not use stdout.\nconst DEFAULT_MAX_OUTPUT_TOKENS = 4_000;\n\nasync function run(\n session: RecordingSession,\n cmd: string,\n runAs?: string,\n yieldTimeMs = EXEC_YIELD_MS,\n maxOutputTokens = DEFAULT_MAX_OUTPUT_TOKENS,\n): Promise<string> {\n const args: {\n cmd: string;\n runAs?: string;\n yieldTimeMs?: number;\n maxOutputTokens?: number;\n } = { cmd, ...(runAs ? { runAs } : {}), yieldTimeMs, maxOutputTokens };\n if (typeof session.exec === \"function\") {\n return resultOutput(await session.exec(args));\n }\n if (typeof session.execCommand === \"function\") {\n return resultOutput(await session.execCommand(args));\n }\n throw new RecordingUnavailableError(\n \"session cannot run commands (no exec/execCommand) — recording unavailable\",\n );\n}\n\n// Extract the command body from a provider exec banner. Modal's execCommand\n// returns \"<chunk banner>\\nProcess exited…\\nOutput:\\n<body>\"; the body is what\n// follows the last \"Output:\\n\" marker. Plain exec results (no banner) pass\n// through unchanged.\nfunction stripExecBanner(raw: string): string {\n const marker = raw.lastIndexOf(\"\\nOutput:\\n\");\n if (marker >= 0) return raw.slice(marker + \"\\nOutput:\\n\".length);\n if (raw.startsWith(\"Output:\\n\")) return raw.slice(\"Output:\\n\".length);\n return raw;\n}\n\nexport type StartRecordingInput = {\n recordingId: string;\n codec?: RecordingCodec;\n framerate?: number;\n maxSeconds?: number;\n dimensions?: [number, number];\n display?: string; // \":0\"\n runAs?: string;\n tmpDir?: string; // \"/tmp\"\n};\n\nexport type RecordingProcess = {\n recordingId: string;\n codec: RecordingCodec;\n boxPath: string;\n pidFile: string;\n dimensions: [number, number];\n framerate: number;\n /** epoch-ms when ffmpeg was launched (for duration computation, F14). */\n startedAt: number;\n display: string;\n runAs?: string;\n};\n\n/**\n * Launch ffmpeg x11grab on :0 → an mp4/webm file on the box. Backgrounded with\n * `nohup … & echo $!` so the launch returns immediately (F12 — the exec does not\n * block on the recording). A hard `-t <maxSeconds>` ceiling bounds a runaway file\n * across a multi-day turn. Returns the handle the caller carries to stop+finalize.\n */\nexport async function startRecording(\n session: unknown,\n input: StartRecordingInput,\n): Promise<RecordingProcess> {\n const s = session as RecordingSession;\n const codec = input.codec ?? \"h264-mp4\";\n const dimensions = input.dimensions ?? DEFAULT_DIMENSIONS;\n const framerate = input.framerate ?? DEFAULT_FRAMERATE;\n const maxSeconds = input.maxSeconds ?? DEFAULT_MAX_SECONDS;\n const display = input.display ?? \":0\";\n const tmp = input.tmpDir ?? \"/tmp\";\n const ext = extForCodec(codec);\n const boxPath = `${tmp}/og-rec-${input.recordingId}.${ext}`;\n const pidFile = `${tmp}/og-rec-${input.recordingId}.pid`;\n const logFile = `${tmp}/og-rec-${input.recordingId}.log`;\n const [w, h] = dimensions;\n const enc =\n codec === \"vp9-webm\"\n ? `-c:v libvpx-vp9 -b:v 0 -crf 32 -row-mt 1`\n : `-c:v libx264 -preset veryfast -pix_fmt yuv420p -movflags +faststart`;\n const ffmpeg =\n `nohup ffmpeg -hide_banner -loglevel error -f x11grab -draw_mouse 1 -framerate ${framerate} ` +\n `-video_size ${w}x${h} -i ${display}.0 -t ${maxSeconds} ${enc} ${boxPath} ` +\n `</dev/null >${logFile} 2>&1 & echo $! > ${pidFile}`;\n await run(s, `bash -lc ${shq(ffmpeg)}`, input.runAs);\n return {\n recordingId: input.recordingId,\n codec,\n boxPath,\n pidFile,\n dimensions,\n framerate,\n startedAt: Date.now(),\n display,\n ...(input.runAs ? { runAs: input.runAs } : {}),\n };\n}\n\n/**\n * SIGINT ffmpeg (so it writes a clean moov atom / webm trailer) and wait for the\n * pid to exit. Bounded well under the yield window (F3). Idempotent: a missing\n * pid file is a no-op.\n */\nexport async function stopRecording(session: unknown, proc: RecordingProcess): Promise<void> {\n const s = session as RecordingSession;\n const wait = `kill -INT \"$(cat ${proc.pidFile})\" 2>/dev/null; for i in $(seq 1 80); do kill -0 \"$(cat ${proc.pidFile})\" 2>/dev/null || break; sleep 0.1; done`;\n await run(s, `bash -lc ${shq(wait)}`, proc.runAs, STOP_YIELD_MS).catch(() => undefined);\n}\n\nexport type RecordingArtifactMetadata = {\n contentType: RecordingContentType;\n sizeBytes: number;\n durationSeconds: number;\n};\n\n/**\n * Inspect and size-gate the finalized recording while it is still on the box.\n * No recording bytes cross into the worker process.\n */\nexport async function inspectRecordingArtifact(\n session: unknown,\n proc: RecordingProcess,\n maxBytes = DEFAULT_MAX_BYTES,\n): Promise<RecordingArtifactMetadata> {\n const s = session as RecordingSession;\n if (typeof s.exec !== \"function\" && typeof s.execCommand !== \"function\") {\n throw new RecordingUnavailableError(\n \"session cannot run commands (no exec/execCommand) — recording finalize unavailable\",\n );\n }\n // F8: size-gate on the box before authorizing the upload.\n const sizeOut = (\n await run(\n s,\n `bash -lc ${shq(`stat -c %s ${proc.boxPath} 2>/dev/null || echo MISSING`)}`,\n proc.runAs,\n )\n ).trim();\n const sizeLine =\n sizeOut\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter(Boolean)\n .pop() ?? \"MISSING\";\n if (sizeLine === \"MISSING\" || sizeLine === \"\") {\n throw new RecordingError(`recording file missing on box: ${proc.boxPath}`, \"box-death\");\n }\n const size = Number(sizeLine);\n if (!Number.isFinite(size) || size <= 0) {\n throw new RecordingError(`recording file empty on box: ${proc.boxPath}`, \"ffmpeg-error\");\n }\n if (size > maxBytes) {\n throw new RecordingError(`recording ${size}B exceeds max ${maxBytes}B`, \"max-bytes-exceeded\");\n }\n return {\n contentType: contentTypeForCodec(proc.codec),\n sizeBytes: size,\n durationSeconds: Math.max(0, Math.round((Date.now() - proc.startedAt) / 1000)),\n };\n}\n\nconst RECORDING_UPLOAD_OK = \"OPENGENI_RECORDING_UPLOAD_OK\";\nconst RECORDING_UPLOAD_MAX_SECONDS = 300;\n\n/**\n * Upload the finalized artifact directly from the sandbox to a scoped object-\n * storage URL. The worker carries only the short URL/headers and metadata; it\n * never materializes a base64 string or Uint8Array for a recording that may be\n * hundreds of megabytes. curl's success marker makes an exec transport that\n * returns non-zero command output instead of throwing still fail closed.\n */\nexport async function uploadRecordingArtifact(\n session: unknown,\n proc: RecordingProcess,\n input: {\n url: string;\n requiredHeaders: Record<string, string>;\n maxBytes?: number;\n maxSeconds?: number;\n },\n): Promise<RecordingArtifactMetadata> {\n const maxSeconds = input.maxSeconds ?? RECORDING_UPLOAD_MAX_SECONDS;\n if (!Number.isSafeInteger(maxSeconds) || maxSeconds <= 0 || maxSeconds > 300) {\n throw new Error(\"recording upload maxSeconds must be an integer between 1 and 300\");\n }\n const metadata = await inspectRecordingArtifact(session, proc, input.maxBytes);\n const headers = Object.entries(input.requiredHeaders)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([name, value]) => `--header ${shq(`${name}: ${value}`)}`)\n .join(\" \");\n const upload = [\n \"set -euo pipefail\",\n `curl --fail --silent --show-error --connect-timeout 20 --max-time ${maxSeconds} --request PUT ${headers} --upload-file ${shq(proc.boxPath)} ${shq(input.url)}`,\n `printf '${RECORDING_UPLOAD_OK}\\\\n'`,\n ].join(\"; \");\n const output = stripExecBanner(\n await run(\n session as RecordingSession,\n `bash -lc ${shq(upload)}`,\n proc.runAs,\n (maxSeconds + 10) * 1_000,\n ),\n );\n if (!output.includes(RECORDING_UPLOAD_OK)) {\n throw new Error(\"recording upload did not confirm success\");\n }\n return metadata;\n}\n\n/**\n * Delete the box artifacts. F9: call this ONLY after the storage PUT confirmed\n * and the `available` row committed — never before. Best-effort; never throws.\n */\nexport async function deleteRecordingArtifacts(\n session: unknown,\n proc: RecordingProcess,\n): Promise<void> {\n const s = session as RecordingSession;\n const logFile = proc.boxPath.replace(/\\.(mp4|webm)$/, \".log\");\n await run(s, `rm -f ${proc.boxPath} ${proc.pidFile} ${logFile}`, proc.runAs).catch(\n () => undefined,\n );\n}\n\n/** The storage object key for a recording artifact (parallels the file-asset layout). */\nexport function recordingStorageKey(\n workspaceId: string,\n sessionId: string,\n recordingId: string,\n codec: RecordingCodec,\n): string {\n return `recordings/${workspaceId}/${sessionId}/${recordingId}.${extForCodec(codec)}`;\n}\n","// Selfhosted capability negotiation (M3, item 4).\n//\n// `negotiateSelfhostedCapabilities` resolves the selfhosted-specific cells from\n// (a) the M2 enrollment row (consent / display / status / lastSeenAt), and\n// (b) a LIVENESS PROBE (a `ControlRpc` Ping, mockable) — \"is there a responder\n// on the subject right now?\"\n// into the right `SessionCapabilities` cells with the selfhosted reasons:\n// - online → responder + consented: cells available.\n// - offline → no enrollment / revoked / no responder: agent_offline.\n// - reconnecting → a transient blip (a recent lastSeenAt but the probe\n// missed): agent_reconnecting.\n// - consent_required → enrolled but whole-machine / screen-control not acked:\n// the interactive desktop stream becomes read-only.\n// - display_unavailable → online but the machine has no display (headless, no\n// Xvfb): desktop and recording degrade with\n// display_unavailable.\n//\n// It REUSES `negotiateCapabilities` for the descriptor-shaped cells (so the\n// \"every cell present, degradation is a value\" rule and the FS/Terminal/Git\n// surface stay identical to Modal), then overlays the selfhosted liveness/consent\n// /display reasons. The base function stays pure + synchronous; this is the\n// selfhosted-aware entrypoint the API/worker call.\n\nimport type {\n CapabilityUnavailableReason,\n SandboxOs,\n SessionCapabilities,\n} from \"@opengeni/contracts\";\nimport { negotiateCapabilities, type NegotiationContext } from \"../select\";\nimport type { SelfhostedSession } from \"./session\";\n\n/**\n * The structural slice of the M2 `@opengeni/db` `EnrollmentRecord` the selfhosted\n * negotiation reads. Defined STRUCTURALLY (not imported from `@opengeni/db`) so\n * the agent-loop-free sandbox leaf does not couple to the DB package's graph —\n * the API/worker pass an `EnrollmentRecord`, which satisfies this shape. The\n * fields: `status` (active gates reachability), `exposure` +\n * `allowScreenControl` (whole-machine + screen-control consent),`hasDisplay`\n * (the display plane), `lastSeenAt` (the reconnecting-window disambiguator).\n */\nexport interface SelfhostedEnrollment {\n status: string;\n exposure: string;\n allowScreenControl: boolean;\n hasDisplay: boolean;\n /** Exact normalized launch root persisted from the authoritative Hello. */\n workspaceRoot?: string | null;\n lastSeenAt: string | null;\n /** An un-cleared clean going-offline marker (the machine announced a typed\n * GoingOffline). When set, the derivation reads the machine OFFLINE immediately,\n * regardless of a still-fresh `lastSeenAt`. NULL ⇒ no pending goodbye. */\n wentOfflineAt: string | null;\n /** The typed reason string of the pending goodbye (rides alongside\n * `wentOfflineAt`; NULL when there is no un-cleared marker). */\n wentOfflineReason: string | null;\n}\n\n/** The derived liveness state of a selfhosted machine (the online/offline/\n * reconnecting/consent/display matrix). */\nexport interface SelfhostedLivenessState {\n /** The dominant machine state. */\n state: \"online\" | \"reconnecting\" | \"offline\";\n /** Whole-machine + screen-control consent acknowledged (gates desktop input). */\n consented: boolean;\n /** A display (real or Xvfb) is present (gates the desktop pixel plane). */\n hasDisplay: boolean;\n}\n\n/**\n * The window after `lastSeenAt` within which a missed liveness probe is read as a\n * transient BLIP (`reconnecting`) rather than a hard `offline`. Mirrors the\n * resiliency model (§10.6: reconnecting after 1 missed window, offline after\n * ~30s). A probe miss with a lastSeenAt inside this window → reconnecting.\n */\nexport const SELFHOSTED_RECONNECT_WINDOW_MS = 30_000;\n\n/**\n * Derive the selfhosted liveness state from the enrollment row + a liveness probe\n * outcome. The probe is the authoritative \"is the agent answering NOW\" signal;\n * `lastSeenAt` disambiguates a probe-miss into reconnecting (recent) vs offline\n * (stale / never seen).\n *\n * - no enrollment / revoked → offline (the machine isn't enrolled).\n * - un-cleared clean goodbye → offline (an announced GoingOffline beats\n * last_seen aging AND a lingering probe).\n * - probe responded → online.\n * - probe missed, lastSeenAt recent → reconnecting (a transient blip).\n * - probe missed, lastSeenAt stale → offline.\n */\nexport function selfhostedLiveness(input: {\n enrollment: SelfhostedEnrollment | null;\n /** The ControlRpc Ping outcome: true iff a responder answered. */\n probeResponded: boolean;\n /** Override the clock (tests). */\n now?: Date;\n}): SelfhostedLivenessState {\n const { enrollment } = input;\n if (!enrollment || enrollment.status !== \"active\") {\n return { state: \"offline\", consented: false, hasDisplay: false };\n }\n const consented = enrollment.exposure === \"whole-machine\" && enrollment.allowScreenControl;\n const hasDisplay = enrollment.hasDisplay;\n // A CLEAN going-offline the machine announced takes precedence over BOTH\n // last_seen aging and a lingering probe: a machine that said \"I'm stopping\" must\n // read offline immediately (so no new work is routed at it) until a NEWER\n // liveness signal — a reconnect Hello or a fresher heartbeat — clears the marker\n // in the row. `status: \"revoked\"` above still trumps this (a revoked machine is\n // offline regardless). This is the #348 lease-waits-on-dead-detect fix.\n if (enrollment.wentOfflineAt) {\n return { state: \"offline\", consented, hasDisplay };\n }\n if (input.probeResponded) {\n return { state: \"online\", consented, hasDisplay };\n }\n // Probe missed → reconnecting if we saw it recently, else offline.\n const now = (input.now ?? new Date()).getTime();\n const lastSeen = enrollment.lastSeenAt ? new Date(enrollment.lastSeenAt).getTime() : null;\n if (lastSeen !== null && now - lastSeen <= SELFHOSTED_RECONNECT_WINDOW_MS) {\n return { state: \"reconnecting\", consented, hasDisplay };\n }\n return { state: \"offline\", consented, hasDisplay };\n}\n\n/**\n * Dashboard/list liveness: heartbeat + goodbye only. Fresh `lastSeenAt` (inside\n * the reconnect window) is online. There is no ControlRpc ping here — attach,\n * capability negotiation, and fleet tools still probe when they must know\n * whether a responder is answering now.\n */\nexport function selfhostedHeartbeatLiveness(input: {\n enrollment: SelfhostedEnrollment | null;\n now?: Date;\n}): SelfhostedLivenessState {\n const { enrollment } = input;\n if (!enrollment || enrollment.status !== \"active\") {\n return { state: \"offline\", consented: false, hasDisplay: false };\n }\n const now = input.now ?? new Date();\n const lastSeen = enrollment.lastSeenAt ? new Date(enrollment.lastSeenAt).getTime() : null;\n const heartbeatFresh =\n lastSeen !== null && now.getTime() - lastSeen <= SELFHOSTED_RECONNECT_WINDOW_MS;\n return selfhostedLiveness({\n enrollment,\n probeResponded: heartbeatFresh,\n now,\n });\n}\n\nexport interface SelfhostedNegotiationInput {\n sessionId: string;\n os?: SandboxOs;\n leaseEpoch: number;\n /** The M2 enrollment row for the machine (null → never enrolled → offline). */\n enrollment: SelfhostedEnrollment | null;\n /** A live liveness probe — typically `session.ping()`. When a session is\n * provided this is called; otherwise pass `probeResponded` explicitly. */\n session?: Pick<SelfhostedSession, \"ping\">;\n /** Explicit probe outcome (when no session is given, e.g. a pure read). */\n probeResponded?: boolean;\n /** The deployment desktop/terminal policy toggles (threaded through to the\n * base negotiation). */\n desktopEnabled?: boolean;\n desktopInteractive?: boolean;\n terminalEnabled?: boolean;\n streamTokenSecretAvailable?: boolean;\n /** Whether the calling principal acknowledged the un-redacted desktop. */\n desktopAcknowledged?: boolean;\n shared?: boolean;\n sharedSessionIds?: string[];\n /** Override the clock (tests). */\n now?: Date;\n}\n\n/**\n * Negotiate the full `SessionCapabilities` document for a selfhosted machine,\n * with the online/offline/reconnecting/consent_required/display_unavailable cells\n * correctly decided. Async because it issues the liveness probe.\n */\nexport async function negotiateSelfhostedCapabilities(\n input: SelfhostedNegotiationInput,\n): Promise<SessionCapabilities> {\n const probeResponded =\n input.probeResponded ?? (input.session ? await input.session.ping() : false);\n const liveness = selfhostedLiveness({\n enrollment: input.enrollment,\n probeResponded,\n ...(input.now ? { now: input.now } : {}),\n });\n\n // The base context: map the machine state onto the lease `liveness` axis so the\n // descriptor-shaped cells (FS/Terminal/Git/Desktop) negotiate as on a warm box\n // when online, and a cold box when not reachable (no live tunnel). The\n // selfhosted overlay below then stamps the selfhosted-specific reasons.\n const baseLiveness: NegotiationContext[\"liveness\"] =\n liveness.state === \"online\" ? \"warm\" : \"cold\";\n const base: NegotiationContext = {\n sessionId: input.sessionId,\n backend: \"selfhosted\",\n os: input.os ?? \"linux\",\n liveness: baseLiveness,\n leaseEpoch: input.leaseEpoch,\n desktopEnabled: input.desktopEnabled ?? true,\n desktopInteractive: input.desktopInteractive ?? true,\n terminalEnabled: input.terminalEnabled ?? true,\n streamTokenSecretAvailable: input.streamTokenSecretAvailable ?? true,\n ...(input.desktopAcknowledged !== undefined\n ? { desktopAcknowledged: input.desktopAcknowledged }\n : {}),\n ...(input.shared !== undefined ? { shared: input.shared } : {}),\n ...(input.sharedSessionIds !== undefined ? { sharedSessionIds: input.sharedSessionIds } : {}),\n ...(input.now ? { now: input.now } : {}),\n };\n const negotiated = negotiateCapabilities(base);\n const caps: SessionCapabilities = {\n ...negotiated,\n FileSystem: {\n ...negotiated.FileSystem,\n root: input.enrollment?.workspaceRoot ?? \".\",\n },\n };\n\n // ── Overlay the selfhosted liveness/consent/display reasons ────────────────\n\n // When the machine is not online, the Channel-A surface (FS/Terminal/Git) and\n // the desktop plane cannot be reached — stamp the machine-liveness reason. This\n // is the dominant degrade (like os_unsupported): an offline/reconnecting agent\n // knocks out every reachable capability with the single coherent reason.\n if (liveness.state !== \"online\") {\n const reason: CapabilityUnavailableReason =\n liveness.state === \"offline\" ? \"agent_offline\" : \"agent_reconnecting\";\n return {\n ...caps,\n FileSystem: { ...caps.FileSystem, available: false, readOnly: true, reason },\n Terminal: {\n ...caps.Terminal,\n transport: null,\n url: null,\n token: null,\n expiresAt: null,\n reason,\n },\n Git: { ...caps.Git, available: false, reason },\n DesktopStream: {\n ...caps.DesktopStream,\n transport: null,\n client: null,\n mode: \"read-only\",\n url: null,\n token: null,\n expiresAt: null,\n requiresAcknowledgment: false,\n acknowledged: false,\n shared: false,\n sharedSessionIds: [],\n reason,\n },\n Recording: { ...caps.Recording, available: false, modes: [], codecs: [], reason },\n };\n }\n\n // Online: FS/Terminal/Git stay as the base negotiated them (the machine is\n // reachable). The desktop plane splits VIEW from CONTROL:\n // - VIEW (a read-only DesktopStream, Recording) requires a DISPLAY only. The\n // agent already holds whole-machine shell exec (it can `screencapture` the\n // screen itself), so passive viewing is within the exposure the user already\n // consented to; a missing display (headless, no Xvfb / no macOS Screen\n // Recording grant) is the only blocker.\n // - CONTROL — an INTERACTIVE stream — additionally requires the explicit\n // allowScreenControl consent (`consented`).\n // Precedence: a headless machine blocks everything (display_unavailable); a\n // displayed-but-unconsented machine can be VIEWED (read-only) + RECORDED but not\n // CONTROLLED (consent_required). (If the base already degraded a cell for a\n // policy reason — desktop disabled / no stream-token secret — that base reason\n // wins; we only stamp a selfhosted reason on a cell the base left AVAILABLE.)\n if (!liveness.hasDisplay) {\n const reason: CapabilityUnavailableReason = \"display_unavailable\";\n return {\n ...caps,\n DesktopStream:\n caps.DesktopStream.transport !== null\n ? {\n ...caps.DesktopStream,\n transport: null,\n client: null,\n mode: \"read-only\",\n url: null,\n token: null,\n expiresAt: null,\n requiresAcknowledgment: false,\n acknowledged: false,\n shared: false,\n sharedSessionIds: [],\n reason,\n }\n : caps.DesktopStream,\n Recording: caps.Recording.available\n ? { ...caps.Recording, available: false, modes: [], codecs: [], reason }\n : caps.Recording,\n };\n }\n\n if (!liveness.consented) {\n // Displayed but no screen-CONTROL consent: VIEW (read-only) + Recording stay\n // available; only interactive viewer CONTROL is withheld. Force the stream to read-only\n // so no input is forwarded even if the base offered an interactive mode.\n return {\n ...caps,\n DesktopStream:\n caps.DesktopStream.transport !== null\n ? { ...caps.DesktopStream, mode: \"read-only\" }\n : caps.DesktopStream,\n };\n }\n\n // Fully online + displayed + consented: the base negotiation already produced\n // the correct available viewer and recording cells.\n return caps;\n}\n","// `MockAgentResponder` — an in-process `ControlRpc` test double standing in for\n// a real enrolled agent over NATS (the live NATS transport is M4). It answers\n// the request/reply op table (ping / fs.read / fs.write / fs.list / fs.stat /\n// git / metrics / desktopEnsure) against an in-memory virtual filesystem, so\n// the non-exec `SelfhostedSession` surface and mocked-NATS\n// integration tests run with zero broker.\n//\n// It is shipped from the runtime package (a testing util, not test-only-private)\n// because the API/worker integration suites (M4+) reuse it to drive\n// `withChannelA`/viewer/swap end-to-end without a real machine.\n\nimport {\n AgentError,\n ControlRequest,\n ControlResponse,\n ErrorCode,\n FsEntryKind,\n type ExecRequest,\n type ExecResponse,\n type FsListResponse,\n type FsReadResponse,\n type FsStatResponse,\n type FsWriteResponse,\n} from \"@opengeni/agent-proto\";\nimport type { ControlRpc } from \"./control-rpc\";\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\n/** Test-only command behavior consumed by an op-stream fake runner. */\nexport type MockExecHandler = (req: ExecRequest) => ExecResponse | Promise<ExecResponse>;\n\nexport interface MockAgentResponderOptions {\n /** Whether a responder exists at all. When false EVERY request yields an\n * AGENT_OFFLINE error (the \"machine is offline\" condition) — used to drive the\n * agent_offline capability + the isProviderSandboxNotFoundError test. */\n online?: boolean;\n /** Whether the agent has acknowledged whole-machine / screen-control consent.\n * When false, an op gated on consent yields CONSENT_REQUIRED. Defaults true. */\n consented?: boolean;\n /** Force the agent into a draining posture (every op → DRAINING). */\n draining?: boolean;\n /** Seed files (path → string|Uint8Array) into the virtual filesystem. */\n files?: Record<string, string | Uint8Array>;\n /** Command behavior for an op-stream test harness. This responder never\n * exposes request/reply exec itself. */\n exec?: MockExecHandler;\n /** The hostname the mock reports (so PTY `$HOSTNAME`-style asserts work). */\n hostname?: string;\n}\n\n/**\n * An in-process `ControlRpc` answering the agent op table against an in-memory\n * virtual filesystem. Drive a `SelfhostedSession` with this to test readFile /\n * writeFile / list / stat round-trips without any NATS. Exec tests use the\n * op-stream fake runner from `op-testing.ts`.\n */\nexport class MockAgentResponder implements ControlRpc {\n private online: boolean;\n private readonly consented: boolean;\n private readonly draining: boolean;\n private readonly files = new Map<string, Uint8Array>();\n private readonly execHandler: MockExecHandler;\n readonly hostname: string;\n\n /** Every request seen, for assertion (subject + decoded ControlRequest). */\n readonly requests: Array<{ subject: string; req: ControlRequest }> = [];\n\n constructor(opts: MockAgentResponderOptions = {}) {\n this.online = opts.online ?? true;\n this.consented = opts.consented ?? true;\n this.draining = opts.draining ?? false;\n this.hostname = opts.hostname ?? \"mock-machine\";\n this.execHandler = opts.exec ?? ((req) => defaultEcho(req, this.hostname));\n for (const [path, content] of Object.entries(opts.files ?? {})) {\n this.files.set(\n normalize(path),\n typeof content === \"string\" ? encoder.encode(content) : content,\n );\n }\n }\n\n /** Flip the responder offline mid-test (a deliberate stop / blip). */\n setOnline(online: boolean): void {\n this.online = online;\n }\n\n /** Read a file the session wrote (test assertion helper). */\n fileText(path: string): string | undefined {\n const bytes = this.files.get(normalize(path));\n return bytes ? decoder.decode(bytes) : undefined;\n }\n\n /** Produce the command result used by an op-stream test runner. */\n async runExec(req: ExecRequest): Promise<ExecResponse> {\n return await this.execHandler(req);\n }\n\n async request(\n subject: string,\n req: ControlRequest,\n _opts: { timeoutMs: number },\n ): Promise<ControlResponse> {\n this.requests.push({ subject, req });\n if (!this.online) {\n return errorResponse(\n req.requestId,\n ErrorCode.ERROR_CODE_AGENT_OFFLINE,\n \"the enrolled agent is offline\",\n false,\n );\n }\n if (this.draining) {\n return errorResponse(\n req.requestId,\n ErrorCode.ERROR_CODE_DRAINING,\n \"the agent is draining\",\n true,\n );\n }\n const op = req.op;\n if (!op) {\n return errorResponse(req.requestId, ErrorCode.ERROR_CODE_PROTOCOL, \"empty op\", false);\n }\n const subjectParts = subject.split(\".\");\n const workspaceId = subjectParts[1] ?? \"\";\n const agentId = subjectParts[2] ?? \"\";\n switch (op.$case) {\n case \"ping\":\n return ok(req.requestId, {\n $case: \"ping\",\n ping: { nonce: op.ping.nonce, agentMonotonicMs: \"0\" },\n });\n case \"fsRead\": {\n const bytes = this.files.get(normalize(op.fsRead.path));\n if (!bytes) {\n return errorResponse(\n req.requestId,\n ErrorCode.ERROR_CODE_NOT_FOUND,\n `no such file: ${op.fsRead.path}`,\n false,\n );\n }\n const res: FsReadResponse = { content: bytes, totalSize: String(bytes.length) };\n return ok(req.requestId, { $case: \"fsRead\", fsRead: res });\n }\n case \"fsWrite\": {\n const path = normalize(op.fsWrite.path);\n const next = op.fsWrite.append\n ? concat(this.files.get(path) ?? new Uint8Array(0), op.fsWrite.content)\n : op.fsWrite.content;\n this.files.set(path, next);\n const res: FsWriteResponse = { bytesWritten: String(op.fsWrite.content.length) };\n return ok(req.requestId, { $case: \"fsWrite\", fsWrite: res });\n }\n case \"fsRemove\": {\n const path = normalize(op.fsRemove.path);\n if (!this.files.delete(path)) {\n return errorResponse(\n req.requestId,\n ErrorCode.ERROR_CODE_NOT_FOUND,\n `no such file: ${op.fsRemove.path}`,\n false,\n );\n }\n return ok(req.requestId, { $case: \"fsRemove\", fsRemove: {} });\n }\n case \"fsList\": {\n const prefix = normalize(op.fsList.path).replace(/\\/?$/, \"/\");\n const res: FsListResponse = {\n entries: [...this.files.keys()]\n .filter((p) => p.startsWith(prefix))\n .map((p) => {\n const bytes = this.files.get(p)!;\n const rel = p.slice(prefix.length);\n return {\n name: rel.split(\"/\").pop() ?? rel,\n path: rel,\n kind: FsEntryKind.FS_ENTRY_KIND_FILE,\n size: String(bytes.length),\n modifiedMs: \"0\",\n mode: 0o644,\n };\n }),\n };\n return ok(req.requestId, { $case: \"fsList\", fsList: res });\n }\n case \"fsStat\": {\n const bytes = this.files.get(normalize(op.fsStat.path));\n const res: FsStatResponse = bytes\n ? {\n exists: true,\n entry: {\n name: normalize(op.fsStat.path).split(\"/\").pop() ?? \"\",\n path: op.fsStat.path,\n kind: FsEntryKind.FS_ENTRY_KIND_FILE,\n size: String(bytes.length),\n modifiedMs: \"0\",\n mode: 0o644,\n },\n }\n : { exists: false, entry: undefined };\n return ok(req.requestId, { $case: \"fsStat\", fsStat: res });\n }\n case \"desktopEnsure\": {\n // The desktop STREAM (view) is DISPLAY-gated, not consent-gated: the real\n // agent registers the channel + captures frames regardless of screen-control\n // consent (`register_desktop` in hub.rs sets `allow_input` from consent and\n // the pump captures anyway) — only INPUT injection is gated. This stub has a\n // (mock) display and does not model viewer input injection, so\n // desktopEnsure always succeeds; `consented` only affects interactive control.\n return ok(req.requestId, {\n $case: \"desktopEnsure\",\n desktopEnsure: {\n channel: {\n channelId: \"mock-desktop\",\n workspaceId,\n agentId,\n kind: 1,\n port: 6080,\n },\n display: { id: \":99\", width: 1024, height: 768, virtual: true },\n },\n });\n }\n case \"ptyOpen\": {\n // The PTY plane is display-INDEPENDENT and has NO consent gate (unlike\n // desktopEnsure) — a terminal works on a headless machine. Returns a PTY\n // StreamChannel on the 7681 port.\n return ok(req.requestId, {\n $case: \"ptyOpen\",\n ptyOpen: {\n ptyId: \"mock-pty\",\n channel: { channelId: \"mock-pty\", workspaceId, agentId, kind: 1, port: 7681 },\n },\n });\n }\n case \"browserControlEnsure\":\n return ok(req.requestId, {\n $case: \"browserControlEnsure\",\n browserControlEnsure: { port: 17_321, sidecarGeneration: \"mock-sidecar-1\" },\n });\n case \"browserFramesOpen\": {\n return ok(req.requestId, {\n $case: \"browserFramesOpen\",\n browserFramesOpen: {\n channel: {\n channelId: `mock-browser-${op.browserFramesOpen.targetId}`,\n workspaceId,\n agentId,\n kind: 3,\n port: 20_000,\n },\n },\n });\n }\n case \"computerFramesOpen\": {\n return ok(req.requestId, {\n $case: \"computerFramesOpen\",\n computerFramesOpen: {\n channel: {\n channelId: `mock-computer-${op.computerFramesOpen.targetId}`,\n workspaceId,\n agentId,\n kind: 4,\n port: 20_001,\n },\n },\n });\n }\n default:\n return errorResponse(\n req.requestId,\n ErrorCode.ERROR_CODE_UNSUPPORTED,\n `mock does not implement ${op.$case}`,\n false,\n );\n }\n }\n}\n\nfunction defaultEcho(req: ExecRequest, hostname: string): ExecResponse {\n const joined = req.command.join(\" \");\n const stdout = /hostname|HOSTNAME/.test(joined) ? hostname : joined;\n return {\n exitCode: 0,\n stdout: encoder.encode(`${stdout}\\n`),\n stderr: new Uint8Array(0),\n timedOut: false,\n durationMs: \"1\",\n };\n}\n\nfunction ok(requestId: string, result: NonNullable<ControlResponse[\"result\"]>): ControlResponse {\n return { requestId, error: undefined, result };\n}\n\nfunction errorResponse(\n requestId: string,\n code: ErrorCode,\n message: string,\n retryable: boolean,\n): ControlResponse {\n const error: AgentError = { code, message, retryable, detail: {} };\n return { requestId, error, result: undefined };\n}\n\nfunction normalize(path: string): string {\n // Collapse to a leading-slash absolute form for stable keys.\n const trimmed = path.replace(/\\/+$/, \"\");\n return trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n}\n\nfunction concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n const out = new Uint8Array(a.length + b.length);\n out.set(a, 0);\n out.set(b, a.length);\n return out;\n}\n","// Test doubles for the op-stream exec client (op-stream.ts): an in-memory\n// transport and a scripted FAKE RUNNER that emulates the Rust runner's\n// protocol behavior faithfully enough to exercise every client path —\n// idempotent OpStart (dedup by op id, never re-runs), attach replay from\n// retention, live-emission fault injection (drops / duplicates / reordering),\n// OpQuery status, typed lost states, and DRAINING admission. The runner's own\n// half is proven by its Rust harness (the E-scenarios); this double exists so\n// the CLIENT's reassembly/heal/ack logic is unit-testable with no broker and\n// no binary, deterministically.\n//\n// Emission model (mirrors the real runner): frames live in RETENTION the\n// moment they exist. With `live: false` (the default) the op is already\n// COMPLETE at start — the client's initial attach replays everything (the\n// completed-op collection path, incl. re-dispatch attach-not-rerun). With\n// `live: true` the first attach replays nothing and triggers the LIVE\n// emission with the fault filters applied (drops/dups/reordering); any LATER\n// attach is a heal and replays from retention unfiltered — exactly how the\n// runner's ring/spool heals what the wire mangled.\n\nimport { blake3 } from \"@noble/hashes/blake3\";\nimport { bytesToHex } from \"@noble/hashes/utils\";\nimport {\n ControlRequest,\n ControlResponse,\n ErrorCode,\n type ExecRequest,\n type ExecResponse,\n OpAck,\n OpChannel,\n OpFrame,\n OpLostReason,\n OpState,\n type AgentError,\n type OpExit,\n type OpStart,\n type OpStatus,\n} from \"@opengeni/agent-proto\";\nimport type { ControlRpc } from \"./control-rpc\";\nimport {\n opFrameSubject,\n OpStreamUnavailableError,\n type OpStreamSubscription,\n type OpStreamTransport,\n} from \"./op-transport\";\n\n/**\n * An in-memory `OpStreamTransport`: subscriptions are a subject→handler map,\n * and everything the CLIENT publishes (its acks) is recorded for assertions\n * and mirrored to `onPublish` (the fake runner's ack intake). `available =\n * false` makes both primitives throw `OpStreamUnavailableError` so callers\n * can assert that exec fails closed before dispatch.\n */\nexport class InMemoryOpStreamTransport implements OpStreamTransport {\n available = true;\n readonly published: Array<{ subject: string; payload: Uint8Array }> = [];\n onPublish: ((subject: string, payload: Uint8Array) => void) | undefined;\n private readonly handlers = new Map<string, Set<(payload: Uint8Array) => void>>();\n\n async subscribe(\n subject: string,\n onMessage: (payload: Uint8Array) => void,\n ): Promise<OpStreamSubscription> {\n if (!this.available) {\n throw new OpStreamUnavailableError(\"in-memory transport marked unavailable\");\n }\n let set = this.handlers.get(subject);\n if (!set) {\n set = new Set();\n this.handlers.set(subject, set);\n }\n set.add(onMessage);\n return {\n unsubscribe: () => {\n set.delete(onMessage);\n },\n };\n }\n\n async publish(subject: string, payload: Uint8Array): Promise<void> {\n if (!this.available) {\n throw new OpStreamUnavailableError(\"in-memory transport marked unavailable\");\n }\n this.published.push({ subject, payload });\n this.onPublish?.(subject, payload);\n }\n\n /** Deliver a payload to the subject's subscribers (the runner→client leg). */\n deliver(subject: string, payload: Uint8Array): void {\n for (const handler of this.handlers.get(subject) ?? []) {\n handler(payload);\n }\n }\n\n /** Every OpAck the client published, decoded, in publish order. */\n decodedAcks(): OpAck[] {\n return this.published.map(({ payload }) => OpAck.decode(payload));\n }\n}\n\n/** One scripted data frame (the exit frame is synthesized from `exit`). */\nexport interface FakeOpDataFrame {\n channel: \"stdout\" | \"stderr\";\n bytes: Uint8Array | string;\n}\n\nexport interface FakeOpScript {\n /** Data/progress frames in emission order (seq 1..N; the exit takes N+1). */\n frames: Array<FakeOpDataFrame | \"progress\">;\n /** Exit overrides (exitCode/timedOut/failureCode/…). Digests and totals are\n * computed from the scripted data frames unless overridden. */\n exit?: Partial<OpExit>;\n /** LIVE mode: the first attach replays nothing and triggers the (faulty)\n * live emission; later attaches replay from retention unfiltered. Default\n * false = the op is COMPLETE at start (pure collection). */\n live?: boolean;\n /** Keep a live op RUNNING with no frames until OpCancel is received. */\n holdUntilCancel?: boolean;\n /** Seqs whose LIVE emission is dropped (retention keeps them). */\n dropLiveSeqs?: ReadonlySet<number>;\n /** Seqs whose LIVE emission is duplicated (delivered twice back-to-back). */\n duplicateLiveSeqs?: ReadonlySet<number>;\n /** Swap each adjacent live pair (1,2 → 2,1) to exercise the stash path. */\n reorderLivePairs?: boolean;\n /** The first N OpStarts answer a DRAINING AgentError (admission pressure). */\n drainingStarts?: number;\n /** Refuse every OpStart with this error (e.g. a PROTOCOL refusal from a\n * runner that does not speak the required op-stream protocol). */\n startError?: AgentError;\n}\n\ninterface FakeOpRun {\n connectionInstanceId: string;\n script: FakeOpScript;\n frames: OpFrame[];\n exitSeq: bigint;\n exit: OpExit;\n startCount: number;\n attachCount: number;\n drainingRemaining: number;\n liveEmitted: boolean;\n finalAcked: boolean;\n acks: OpAck[];\n highestGeneration: bigint;\n}\n\nconst encoder = new TextEncoder();\n\n/**\n * The scripted fake runner: a `ControlRpc` that answers the op-stream control\n * ops and emits frames through an `InMemoryOpStreamTransport`.\n */\nexport class FakeOpRunner implements ControlRpc {\n private readonly transport: InMemoryOpStreamTransport;\n private readonly workspaceId: string;\n private readonly agentId: string;\n private readonly connectionInstanceId: string;\n private readonly defaultScript:\n | ((exec: ExecRequest, opId: string) => FakeOpScript | Promise<FakeOpScript>)\n | undefined;\n private readonly scripts = new Map<string, FakeOpScript>();\n readonly runs = new Map<string, FakeOpRun>();\n readonly starts: Array<{ opId: string; exec: ExecRequest }> = [];\n /** Op ids that answer LOST (evicted) on query/attach — bounded-retention\n * collateral. */\n readonly lostOps = new Set<string>();\n private readonly cancelledBeforeStart = new Set<string>();\n\n constructor(opts: {\n transport: InMemoryOpStreamTransport;\n workspaceId: string;\n agentId: string;\n connectionInstanceId: string;\n defaultScript?: (exec: ExecRequest, opId: string) => FakeOpScript | Promise<FakeOpScript>;\n }) {\n this.transport = opts.transport;\n this.workspaceId = opts.workspaceId;\n this.agentId = opts.agentId;\n this.connectionInstanceId = opts.connectionInstanceId;\n this.defaultScript = opts.defaultScript;\n this.transport.onPublish = (_subject, payload) => this.onAck(payload);\n }\n\n /** Script the op the NEXT OpStart with this id will run. */\n script(opId: string, script: FakeOpScript): void {\n this.scripts.set(opId, script);\n }\n\n private onAck(payload: Uint8Array): void {\n let ack: OpAck;\n try {\n ack = OpAck.decode(payload);\n } catch {\n return;\n }\n const run = this.runs.get(ack.opId);\n if (!run) {\n return;\n }\n // Generation fencing exactly like the runner: only the highest generation\n // seen has any effect; `final` is honored only when it covers the exit.\n const generation = BigInt(ack.attachGeneration);\n if (generation === 0n || generation !== run.highestGeneration) {\n return;\n }\n run.acks.push(ack);\n if (ack.final && BigInt(ack.ackedSeq) >= run.exitSeq) {\n run.finalAcked = true;\n }\n }\n\n async request(\n subject: string,\n req: ControlRequest,\n _opts: { timeoutMs: number },\n ): Promise<ControlResponse> {\n const connectionInstanceId = connectionInstanceIdFromSubject(subject);\n if (!connectionInstanceId) {\n return errorResponse(\n req.requestId,\n ErrorCode.ERROR_CODE_PROTOCOL,\n \"request did not address an exact connection instance\",\n );\n }\n const op = req.op;\n if (!op) {\n return errorResponse(req.requestId, ErrorCode.ERROR_CODE_PROTOCOL, \"no op\");\n }\n switch (op.$case) {\n case \"opStart\":\n return await this.handleStart(req.requestId, op.opStart, connectionInstanceId);\n case \"opAttach\":\n return this.handleAttach(\n req.requestId,\n op.opAttach.opId,\n BigInt(op.opAttach.fromSeq),\n op.opAttach.attachGeneration,\n connectionInstanceId,\n );\n case \"opQuery\":\n return this.handleQuery(req.requestId, op.opQuery.opId, connectionInstanceId);\n case \"opCancel\":\n return this.handleCancel(req.requestId, op.opCancel.opId, connectionInstanceId);\n default: {\n return errorResponse(\n req.requestId,\n ErrorCode.ERROR_CODE_UNSUPPORTED,\n `fake runner: unscripted op ${op.$case}`,\n );\n }\n }\n }\n\n private async handleStart(\n opId: string,\n start: OpStart,\n connectionInstanceId: string,\n ): Promise<ControlResponse> {\n if (this.cancelledBeforeStart.has(opId)) {\n return startResponse(opId, cancelledStatus(opId), false);\n }\n const existing = this.runs.get(opId);\n if (existing) {\n if (existing.connectionInstanceId !== connectionInstanceId) {\n return errorResponse(\n opId,\n ErrorCode.ERROR_CODE_FENCED,\n \"operation belongs to a different connection instance\",\n );\n }\n // IDEMPOTENT BY OP ID: a known op answers its current status and NEVER\n // re-runs (the whole point of B1).\n existing.startCount += 1;\n return startResponse(opId, this.statusOf(opId, existing));\n }\n const exec = start.op?.$case === \"exec\" ? start.op.exec : undefined;\n if (!exec) {\n return errorResponse(\n opId,\n ErrorCode.ERROR_CODE_UNSUPPORTED,\n \"fake runner: only exec OpStart is supported\",\n );\n }\n this.starts.push({ opId, exec });\n const scripted = this.scripts.get(opId) ?? (await this.defaultScript?.(exec, opId));\n if (scripted && !this.scripts.has(opId)) this.scripts.set(opId, scripted);\n const script = this.scripts.get(opId);\n if (!script) {\n return errorResponse(\n opId,\n ErrorCode.ERROR_CODE_PROTOCOL,\n `fake runner: no script for op ${opId}`,\n );\n }\n if (script.startError) {\n return { requestId: opId, error: script.startError, result: undefined };\n }\n const pending = this.scripts.get(opId) as FakeOpScript;\n if ((pending.drainingStarts ?? 0) > 0) {\n // Admission pressure: count down across retries of the un-admitted op.\n this.scripts.set(opId, { ...pending, drainingStarts: (pending.drainingStarts ?? 0) - 1 });\n return {\n requestId: opId,\n error: {\n code: ErrorCode.ERROR_CODE_DRAINING,\n message: \"fake runner: admission pool full\",\n retryable: true,\n detail: {},\n },\n result: undefined,\n };\n }\n const run = this.buildRun(opId, this.scripts.get(opId) as FakeOpScript, connectionInstanceId);\n run.startCount = 1;\n this.runs.set(opId, run);\n return startResponse(opId, this.statusOf(opId, run));\n }\n\n private handleAttach(\n requestId: string,\n opId: string,\n fromSeq: bigint,\n generation: string,\n connectionInstanceId: string,\n ): ControlResponse {\n if (this.lostOps.has(opId)) {\n return statusOnly(requestId, lostStatus(opId));\n }\n const run = this.runs.get(opId);\n if (!run) {\n return statusOnly(requestId, lostStatus(opId));\n }\n if (run.connectionInstanceId !== connectionInstanceId) {\n return errorResponse(\n requestId,\n ErrorCode.ERROR_CODE_FENCED,\n \"operation belongs to a different connection instance\",\n );\n }\n run.attachCount += 1;\n const attachGeneration = BigInt(generation);\n // Rust apply_attach still returns status but refuses replay for generation\n // zero or an older consumer. Do not make stale clients appear healthy.\n if (attachGeneration === 0n || attachGeneration < run.highestGeneration) {\n return statusOnly(requestId, this.statusOf(opId, run));\n }\n if (attachGeneration > run.highestGeneration) {\n run.highestGeneration = attachGeneration;\n }\n const subject = opFrameSubject(this.workspaceId, this.agentId, opId, run.connectionInstanceId);\n if (run.script.live && !run.liveEmitted) {\n // First attach on a live op: nothing retained yet worth replaying — the\n // child \"runs now\" and the (faulty) live flow begins.\n if (!run.script.holdUntilCancel) this.emitLive(opId, run, subject);\n return statusOnly(requestId, this.statusOf(opId, run));\n }\n // A heal (or completed-op collection): replay from RETENTION — every frame\n // > fromSeq, in order, NO fault injection (the runner's ring/spool holds\n // them all under the credit-only ack policy).\n const replay = run.frames.filter((frame) => BigInt(frame.seq) > fromSeq);\n queueMicrotask(() => {\n for (const frame of replay) {\n this.transport.deliver(subject, OpFrame.encode(frame).finish());\n }\n });\n return statusOnly(requestId, this.statusOf(opId, run));\n }\n\n private handleQuery(\n requestId: string,\n opId: string,\n connectionInstanceId: string,\n ): ControlResponse {\n if (this.lostOps.has(opId)) {\n return statusOnly(requestId, lostStatus(opId));\n }\n const run = this.runs.get(opId);\n if (!run) {\n return statusOnly(requestId, lostStatus(opId));\n }\n if (run.connectionInstanceId !== connectionInstanceId) {\n return errorResponse(\n requestId,\n ErrorCode.ERROR_CODE_FENCED,\n \"operation belongs to a different connection instance\",\n );\n }\n return statusOnly(requestId, this.statusOf(opId, run));\n }\n\n private handleCancel(\n requestId: string,\n opId: string,\n connectionInstanceId: string,\n ): ControlResponse {\n const run = this.runs.get(opId);\n if (!run) {\n this.cancelledBeforeStart.add(opId);\n return statusOnly(requestId, cancelledStatus(opId));\n }\n if (run.connectionInstanceId !== connectionInstanceId) {\n return errorResponse(\n requestId,\n ErrorCode.ERROR_CODE_FENCED,\n \"operation belongs to a different connection instance\",\n );\n }\n if (!run.liveEmitted && run.script.holdUntilCancel) {\n run.exit.exitCode = -1;\n run.exit.cancelled = true;\n run.liveEmitted = true;\n const subject = opFrameSubject(\n this.workspaceId,\n this.agentId,\n opId,\n run.connectionInstanceId,\n );\n queueMicrotask(() => {\n for (const frame of run.frames) {\n this.transport.deliver(subject, OpFrame.encode(frame).finish());\n }\n });\n }\n return statusOnly(requestId, this.statusOf(opId, run));\n }\n\n /** The LIVE flow: fault filters applied (drops, duplicates, adjacent\n * reordering); retention still holds every frame for the heal replay. */\n private emitLive(opId: string, run: FakeOpRun, subject: string): void {\n run.liveEmitted = true;\n const { dropLiveSeqs, duplicateLiveSeqs, reorderLivePairs } = run.script;\n let sequence = [...run.frames];\n if (reorderLivePairs) {\n for (let i = 0; i + 1 < sequence.length; i += 2) {\n const a = sequence[i] as OpFrame;\n sequence[i] = sequence[i + 1] as OpFrame;\n sequence[i + 1] = a;\n }\n }\n sequence = sequence.filter((frame) => !dropLiveSeqs?.has(Number(frame.seq)));\n queueMicrotask(() => {\n for (const frame of sequence) {\n const payload = OpFrame.encode(frame).finish();\n this.transport.deliver(subject, payload);\n if (duplicateLiveSeqs?.has(Number(frame.seq))) {\n this.transport.deliver(subject, payload);\n }\n }\n });\n }\n\n private statusOf(opId: string, run: FakeOpRun): OpStatus {\n // The fake's ops are instant: COMPLETE the moment their frames exist. A\n // live op that has not yet emitted reads RUNNING with nothing produced;\n // once emission ran (even if the wire dropped frames), the runner-side\n // truth is COMPLETE with the full high watermark — exactly what a silence\n // probe needs to see to detect \"the runner is ahead of us\".\n const complete = !run.script.live || run.liveEmitted;\n return {\n opId,\n state: complete ? OpState.OP_STATE_COMPLETE : OpState.OP_STATE_RUNNING,\n nextSeq: complete ? (run.exitSeq + 1n).toString() : \"1\",\n writeOffset: \"0\",\n exit: complete ? run.exit : undefined,\n lostReason: OpLostReason.OP_LOST_REASON_UNSPECIFIED,\n };\n }\n\n private buildRun(opId: string, script: FakeOpScript, connectionInstanceId: string): FakeOpRun {\n const frames: OpFrame[] = [];\n const channelBytes: Record<\"stdout\" | \"stderr\", Uint8Array[]> = { stdout: [], stderr: [] };\n let seq = 0n;\n for (const spec of script.frames) {\n seq += 1n;\n if (spec === \"progress\") {\n frames.push({ opId, seq: seq.toString(), body: { $case: \"progress\", progress: {} } });\n continue;\n }\n const bytes = typeof spec.bytes === \"string\" ? encoder.encode(spec.bytes) : spec.bytes;\n channelBytes[spec.channel].push(bytes);\n frames.push({\n opId,\n seq: seq.toString(),\n body: {\n $case: \"data\",\n data: {\n channel:\n spec.channel === \"stdout\" ? OpChannel.OP_CHANNEL_STDOUT : OpChannel.OP_CHANNEL_STDERR,\n bytes,\n },\n },\n });\n }\n seq += 1n;\n const digests: Record<string, string> = {};\n const totals: Record<string, string> = {};\n for (const channel of [\"stdout\", \"stderr\"] as const) {\n const joined = concat(channelBytes[channel]);\n digests[channel] = bytesToHex(blake3(joined));\n totals[channel] = String(joined.byteLength);\n }\n const exit: OpExit = {\n exitCode: 0,\n timedOut: false,\n cancelled: false,\n durationMs: \"5\",\n digests,\n totals,\n failureCode: \"\",\n failureDetail: {},\n ...script.exit,\n };\n frames.push({ opId, seq: seq.toString(), body: { $case: \"exit\", exit } });\n return {\n connectionInstanceId,\n script,\n frames,\n exitSeq: seq,\n exit,\n startCount: 0,\n attachCount: 0,\n drainingRemaining: script.drainingStarts ?? 0,\n liveEmitted: false,\n finalAcked: false,\n acks: [],\n highestGeneration: 0n,\n };\n }\n}\n\nexport function createMockSelfhostedOpStream(input: {\n responder: ControlRpc & { runExec(exec: ExecRequest): Promise<ExecResponse> };\n workspaceId: string;\n agentId: string;\n connectionInstanceId: string;\n}) {\n const transport = new InMemoryOpStreamTransport();\n const runner = new FakeOpRunner({\n transport,\n workspaceId: input.workspaceId,\n agentId: input.agentId,\n connectionInstanceId: input.connectionInstanceId,\n defaultScript: async (exec) => {\n const response = await input.responder.runExec(exec);\n return {\n frames: [\n ...(response.stdout.length > 0\n ? [{ channel: \"stdout\" as const, bytes: response.stdout }]\n : []),\n ...(response.stderr.length > 0\n ? [{ channel: \"stderr\" as const, bytes: response.stderr }]\n : []),\n ],\n exit: {\n exitCode: response.exitCode,\n timedOut: response.timedOut,\n durationMs: response.durationMs,\n },\n };\n },\n });\n const controlRpc: ControlRpc = {\n request: async (subject, request, opts) => {\n const gate = await input.responder.request(subject, request, opts);\n if (gate.error?.code !== ErrorCode.ERROR_CODE_UNSUPPORTED) return gate;\n return await runner.request(subject, request, opts);\n },\n };\n return {\n controlRpc,\n opStream: { transport },\n runner,\n transport,\n };\n}\n\nfunction concat(chunks: Uint8Array[]): Uint8Array {\n const total = chunks.reduce((sum, c) => sum + c.byteLength, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return out;\n}\n\nfunction connectionInstanceIdFromSubject(subject: string): string | undefined {\n const parts = subject.split(\".\");\n const connectionIndex = parts.indexOf(\"connection\");\n return connectionIndex >= 0 ? parts[connectionIndex + 1] : undefined;\n}\n\nfunction errorResponse(requestId: string, code: ErrorCode, message: string): ControlResponse {\n return {\n requestId,\n error: { code, message, retryable: false, detail: {} },\n result: undefined,\n };\n}\n\nfunction startResponse(requestId: string, status: OpStatus, accepted = true): ControlResponse {\n return {\n requestId,\n error: undefined,\n result: { $case: \"opStart\", opStart: { accepted, status } },\n };\n}\n\nfunction statusOnly(requestId: string, status: OpStatus): ControlResponse {\n return {\n requestId,\n error: undefined,\n result: { $case: \"opStatus\", opStatus: status },\n };\n}\n\nfunction lostStatus(opId: string): OpStatus {\n return {\n opId,\n state: OpState.OP_STATE_LOST,\n writeOffset: \"0\",\n nextSeq: \"0\",\n exit: undefined,\n lostReason: OpLostReason.OP_LOST_REASON_EVICTED,\n };\n}\n\nfunction cancelledStatus(opId: string): OpStatus {\n return {\n opId,\n state: OpState.OP_STATE_COMPLETE,\n writeOffset: \"0\",\n nextSeq: \"1\",\n exit: {\n exitCode: -1,\n timedOut: false,\n cancelled: true,\n durationMs: \"0\",\n digests: {},\n totals: {},\n failureCode: \"\",\n failureDetail: {},\n },\n lostReason: OpLostReason.OP_LOST_REASON_UNSPECIFIED,\n };\n}\n","// `makeActiveBackendResolver` — builds the `resolveActiveBackend` closure the\n// `RoutingSandboxSession` calls to turn an active pointer into a live backend\n// session (M7). It is the heterogeneous-dispatch core: a pointer's target is\n// EITHER the session's own group sandbox (the default, `activeSandboxId === null`)\n// OR a first-class named sandbox the session swapped to — a sibling Modal box or\n// a selfhosted machine.\n//\n// This lives in the agent-loop-free leaf and depends ONLY on injected closures +\n// the selfhosted session builder, so the API/worker wire it to the real DB\n// (`getSandbox`/`getEnrollment`/`readActiveSandbox`) + the live NATS ControlRpc\n// without coupling the leaf to `@opengeni/db`.\n//\n// The DEFAULT target (the group box) is supplied as an already-established\n// session (the turn box `resumeBoxForTurn` produced, or the Channel-A established\n// handle) — the proxy does NOT re-establish it (the lease owns its lifecycle). A\n// NON-DEFAULT selfhosted target builds a `SelfhostedSession` bound to the target's\n// enrollment agentId, fenced under the swap's active_epoch. That cached session\n// re-resolves caller-owned authority and connection identity at the last boundary\n// before every provider operation. A non-default MODAL\n// target is established via the injected `establishModalTarget` resolver (the\n// API/worker pass a resume-by-id closure for the sibling box's lease).\n\nimport {\n buildSelfhostedBackendSession,\n type SelfhostedBackgroundCommandAdoption,\n type SelfhostedOpStreamDeps,\n type SelfhostedOperationAdmission,\n type SelfhostedRelayConfig,\n} from \"../selfhosted/session\";\nimport type { SelfhostedOpObserver } from \"../selfhosted/op-observer\";\nimport type { OpStreamOutputFrame } from \"../selfhosted/op-stream\";\nimport type { ControlRpc } from \"../selfhosted/control-rpc\";\nimport { resolveConnectedMachineWorkspaceRoot } from \"../selfhosted/workspace-path\";\nimport type {\n ActivePointer,\n RoutableBackendSession,\n ResolvedActiveBackend,\n} from \"./routing-session\";\n\n/** The structural slice of a first-class sandbox the resolver reads (mirror of\n * `@opengeni/db`'s `SandboxRecord`; structural so the leaf does not import DB). */\nexport interface RoutableSandbox {\n id: string;\n workspaceId: string;\n kind: \"modal\" | \"selfhosted\" | string;\n name: string;\n /** Authority scope projected by the DB resolver. Worker routes use this to\n * reassert an exact attempt's personal-machine grant immediately before use. */\n scope?: \"organization\" | \"workspace\" | \"user\";\n /** For a selfhosted sandbox this is its enrollment id (== the agent id the\n * exact generation-fenced control-plane subject addresses). Null for modal. */\n enrollmentId: string | null;\n}\n\n/** One atomically resolved live Connected Machine route. The process identity\n * and optional stream capability come from the same enrollment snapshot so a\n * build can never combine a successor's RPC subject with a predecessor's\n * capability state. */\nexport interface SelfhostedConnectionBinding {\n /** Physical machine-origin workspace used in the control-plane subject. */\n workspaceId?: string;\n connectionInstanceId: string;\n /** Absolute launch root persisted from this runner's authoritative Hello. */\n workspaceRoot: string | null;\n opStream?: SelfhostedOpStreamDeps;\n operationResourcePolicy: SelfhostedOperationAdmission[\"operationResourcePolicy\"];\n operationResourcePolicySupported: boolean;\n operationCpuQuotaSupported: boolean;\n transactionalFsWriteSupported?: boolean;\n browserControlHttpSupported?: boolean;\n}\n\nexport interface ActiveBackendResolverDeps {\n /** The workspace the session belongs to (the control-plane subject scope). */\n workspaceId: string;\n /** The session's own group sandbox session — the DEFAULT target\n * (`activeSandboxId === null`). Already established (lease-owned); the proxy\n * never re-establishes it. */\n defaultBackend: RoutableBackendSession;\n /** A label for the default backend (its backend id: \"modal\"/\"selfhosted\"/…). */\n defaultKind: string;\n /**\n * Re-resolve the session's HOME backend after the route cache is fenced.\n *\n * The normal path returns `defaultBackend` (the turn's already-established\n * handle), but an API-side same-target repair can rematerialize that lease\n * while a worker turn is still alive. Such a repair advances the route epoch\n * without changing the null pointer; callers that can resume the current\n * lease-owned identity may provide this callback so the next epoch does not\n * keep dispatching to the dead pre-repair object. This callback must never\n * create a provider or replay an operation.\n */\n resolveDefaultBackend?: (pointer: ActivePointer) => Promise<ResolvedActiveBackend>;\n /** Look up a first-class sandbox by id (the swap target). Returns null when the\n * id is unknown or not in this workspace (the caller 409s the swap). */\n getSandbox(sandboxId: string): Promise<RoutableSandbox | null>;\n /** Build a live `ControlRpc` for the selfhosted control plane (the request-\n * scoped NATS connection). Returns a ControlRpc whose offline/timeout maps to\n * agent_offline/agent_reconnecting (never a NotFound). */\n controlRpcFactory(): ControlRpc;\n /** Resolve the exact currently leased daemon instance and its optional stream\n * transport from one enrollment snapshot. Null means no live runner. */\n resolveSelfhostedConnection: (\n sandbox: RoutableSandbox,\n ) => Promise<SelfhostedConnectionBinding | null>;\n /** The relay-URL shape config for selfhosted stream endpoints. */\n relay: SelfhostedRelayConfig;\n /** Establish (resume-by-id) a NON-DEFAULT modal target's box session for a swap.\n * Supplied by the API/worker (a closure over the sibling sandbox's lease). When\n * absent, a modal swap target surfaces as unsupported (the caller validated\n * liveness, so this is the \"modal swap not wired in this context\" guard). */\n establishModalTarget?: (sandbox: RoutableSandbox) => Promise<RoutableBackendSession>;\n /** The selfhosted CONTROL-op timeout (ping/fs/desktop/pty) for a swap/pin target.\n * Absent ⇒ the session's 30s default. */\n selfhostedTimeoutMs?: number;\n /** The selfhosted EXEC process deadline for a swap/pin target, distinct from the\n * control timeout (a swapped-to machine runs real commands too). Absent ⇒ falls\n * back to the control timeout, as in the session leaf. */\n selfhostedExecTimeoutMs?: number;\n /** The per-op observer threaded into a selfhosted swap/pin target (out-of-band\n * telemetry — metrics + machine.* events). Absent ⇒ no-op. */\n selfhostedOnOp?: SelfhostedOpObserver;\n selfhostedAdoptBackgroundCommand?: (\n input: SelfhostedBackgroundCommandAdoption,\n ) => Promise<{ commandId: string }>;\n selfhostedCaptureBackgroundCommandOutput?: (\n commandId: string,\n frames: OpStreamOutputFrame[],\n ) => Promise<void>;\n selfhostedSettleBackgroundCommand?: (input: {\n commandId: string;\n controlWorkspaceId: string;\n enrollmentId: string;\n connectionInstanceId: string;\n opId: string;\n outcome: \"exited\" | \"lost\";\n exitCode: number | null;\n reason: string;\n failure?: import(\"@opengeni/contracts\").SessionCommandFailure;\n }) => void | Promise<void>;\n /**\n * The run's declared sandbox environment — the SAME `Record<string,string>` the\n * worker turn threads into the agent's TARGET manifest (and into the group box at\n * create). Threaded into a selfhosted swap target's session so its\n * `state.manifest.environment` EQUALS the turn's, making the SDK's per-turn\n * provided-session manifest-env delta empty (validateNoEnvironmentDelta).\n * WITHOUT this a pin-to-vm turn throws \"Live sandbox sessions cannot change\n * manifest environment variables\". Omitted → `{}` (the test/negotiation path).\n */\n environment?: Record<string, string>;\n /** Attempt-local values projected only onto selfhosted child exec requests. */\n transientExecEnvironment?: () => Readonly<Record<string, string>>;\n /**\n * A pre-established selfhosted session to PIN for the STEADY-STATE machine\n * pointer (the worker turn's machine-primary path, Stage D). When the pointer\n * targets THIS sandbox at THIS epoch, the resolver returns this SAME instance\n * instead of building a fresh `SelfhostedSession`. This is the instance-identity\n * pin: the SDK reads/writes `state.manifest` at turn START via the proxy's `state`\n * getter (which reads the default/last-resolved backend's state) and then reads it\n * per op via this resolver — those MUST land on ONE SelfhostedSession/manifest, or\n * a turn-start manifest write is invisible to the per-op reads (two-instance\n * divergence). A swap AWAY (a different sandbox id, or the same id at a moved epoch)\n * falls through to a fresh build under the new epoch. Omitted for the API/live-swap\n * path (which always builds fresh — it has no pre-established turn session).\n */\n pinnedSelfhosted?: {\n sandboxId: string;\n epoch: number;\n session: RoutableBackendSession;\n };\n /**\n * Whether `defaultBackend` IS the session's home box — i.e. whether the null pointer\n * (== home) may resolve to it. Defaults to TRUE (omitted): a genuine machine-HOME turn\n * (home IS the machine) and a Modal-home turn established on its group box both pass/omit\n * true, so null resolves to `defaultBackend` as before. Set explicitly FALSE only for a\n * machine-primary turn of a Modal-HOME session (pinned to a machine, group box never\n * established this turn): the null pointer then has nothing to resolve to THIS turn, so\n * rather than silently keep serving the pinned machine as if the detach never happened,\n * the null branch throws a typed `home_unavailable_this_turn` transition — the detach's\n * pointer commit stands, and worker failure settlement checkpoints completed work before\n * continuing the same logical turn in a fresh attempt. That attempt starts null and\n * establishes the home box normally. This makes the boundary typed-and-specific, never\n * a silent fallback to the machine.\n */\n defaultIsHome?: boolean;\n}\n\n/** Why a persisted pointer / swap target cannot be turned into a live backend. A\n * typed discriminant so callers (turn-start reconcile, the swap tool, future\n * reports) can distinguish a stale pointer from an unaddressable enrollment from a\n * backend the turn context simply cannot establish — instead of string-matching\n * one opaque message (issue #341: \"typed diagnostics that distinguish stale\n * pointer, offline enrollment, unsupported backend context, transient failure\").\n * - `stale_pointer` — the pointed-at sandbox row is gone (deleted/orphaned).\n * - `offline_enrollment` — a selfhosted target carries no enrollment/agent id to address.\n * - `unsupported_backend_context` — a target no turn routing context can establish\n * (a non-group Modal sibling; an unknown kind).\n * - `transient_establishment` — a momentary establish failure worth a retry (reserved;\n * control-plane timeouts surface as their own typed error).\n * - `home_unavailable_this_turn` — the pointer was cleared to the session default (home)\n * mid-turn, but this attempt started pinned to a machine and\n * never established the home box. The worker checkpoints the\n * attempt and continues the same logical turn on home.\n * - `workspace_root_unavailable` — the selected runner has not reported a\n * usable absolute launch root yet. */\nexport type BackendUnresolvableCode =\n | \"stale_pointer\"\n | \"offline_enrollment\"\n | \"unsupported_backend_context\"\n | \"transient_establishment\"\n | \"home_unavailable_this_turn\"\n | \"workspace_root_unavailable\";\n\n/** Thrown when a swap target cannot be resolved (unknown sandbox, or a modal\n * target with no establisher in this context). The caller maps it to a 409.\n * Carries a typed {@link BackendUnresolvableCode} in addition to the message. */\nexport class ActiveBackendUnresolvableError extends Error {\n readonly name = \"ActiveBackendUnresolvableError\";\n readonly code: BackendUnresolvableCode;\n constructor(code: BackendUnresolvableCode, message: string) {\n super(message);\n this.code = code;\n }\n}\n\n/** The outcome of {@link swapTargetEstablishability}. */\nexport type SwapTargetEstablishability =\n | { ok: true }\n | { ok: false; code: BackendUnresolvableCode; reason: string };\n\n/**\n * THE SINGLE SOURCE OF TRUTH for \"can a turn's routing context ESTABLISH this swap\n * target?\" — shared by swap/seed ADMISSION (`fleet.resolveTarget`, before the CAS\n * pointer commit) and turn-time ESTABLISHMENT (this resolver + `wrapTurnBoxWithRouting`).\n * Admission MUST reject any target this predicate calls unestablishable, so the\n * pointer is never committed to a backend no turn can resume (issue #341 Shape 1:\n * a Modal-sibling swap was admitted + epoch-bumped, then every following op\n * stranded because no context wires an establisher for it).\n *\n * - the session's OWN group box (`isSessionGroup`) is the null/home target and is\n * always establishable (it IS the default backend);\n * - a `selfhosted` machine target is establishable (`buildSelfhostedBackendSession`);\n * admission's separate liveness probe — not this predicate — gates online-ness;\n * - a NON-group `modal` target is NOT establishable: no turn context wires\n * `establishModalTarget` (cross-group Modal resume-by-id is a future, billing-\n * touching feature — sandbox-routing.ts). Wiring that establisher is the ONE\n * toggle that flips this branch; keep admission and the resolver in lockstep.\n */\nexport function swapTargetEstablishability(target: {\n kind: string;\n isSessionGroup: boolean;\n}): SwapTargetEstablishability {\n if (target.isSessionGroup) {\n return { ok: true };\n }\n if (target.kind === \"selfhosted\") {\n return { ok: true };\n }\n if (target.kind === \"modal\") {\n return {\n ok: false,\n code: \"unsupported_backend_context\",\n reason:\n \"a Modal sandbox other than this session's own box cannot be established by a turn yet; swap back to the session default or attach a Connected Machine\",\n };\n }\n return {\n ok: false,\n code: \"unsupported_backend_context\",\n reason: `a sandbox of kind \"${target.kind}\" cannot be established by a turn`,\n };\n}\n\n/**\n * Build the `resolveActiveBackend(pointer)` closure for a `RoutingSandboxSession`.\n * The returned closure is re-invoked by the proxy whenever the active_epoch moves\n * (the per-epoch cache miss), so it must be cheap-and-correct for the steady-state\n * (default pointer → the already-established group box) and build a fresh backend\n * for a swap target.\n *\n * - `activeSandboxId === null` → the default group backend (no re-establish).\n * - a selfhosted target → a `SelfhostedSession` bound to the enrollment agentId,\n * fenced under `pointer.activeEpoch` (echoed on every ControlRequest so the\n * agent can reject a stale op with ERROR_CODE_FENCED — the swap-race fence).\n * - a modal target → `establishModalTarget` (the resume-by-id closure), else\n * unresolvable.\n */\nexport function makeActiveBackendResolver(\n deps: ActiveBackendResolverDeps,\n): (pointer: ActivePointer) => Promise<ResolvedActiveBackend> {\n return async (pointer: ActivePointer): Promise<ResolvedActiveBackend> => {\n // NULL == the session's HOME backend (issue #341 invariant 1). `defaultBackend`\n // is the already-established home the wiring handed us — the Modal group box for a\n // Modal-home turn, or the machine itself for a machine-home turn. It is NEVER a\n // swap target's SelfhostedSession: a clear-to-null must re-land on the home, never\n // keep serving the machine a prior op swapped to. (The proxy caches by the FULL\n // pointer tuple, so a clear-to-null — epoch-bumped OR a same-epoch FK null —\n // invalidates the cached machine and re-enters this branch.) The lease owns the\n // home box lifecycle; the proxy does not re-establish it.\n if (pointer.activeSandboxId === null) {\n // A machine-pinned turn (Modal-home session pinned to a machine) never\n // established its home box, so a mid-turn clear-to-null has no home to resolve\n // THIS attempt. Fail typed-and-specific — the detach was accepted and its pointer\n // commit STANDS, allowing worker failure settlement to checkpoint and continue the\n // same logical turn in a new home-primary attempt — instead of silently serving the\n // pinned machine as if the clear never happened. Only an EXPLICIT `false` throws;\n // omitted (the common path) resolves to the home default as before.\n if (deps.defaultIsHome === false) {\n throw new ActiveBackendUnresolvableError(\n \"home_unavailable_this_turn\",\n \"the active sandbox was detached to the session default (home), but this turn started pinned to a machine and established no home box; the detach is accepted and takes effect on the next turn — this turn has no active home box\",\n );\n }\n if (deps.resolveDefaultBackend) {\n return await deps.resolveDefaultBackend(pointer);\n }\n return {\n session: deps.defaultBackend,\n sandboxId: null,\n kind: deps.defaultKind,\n };\n }\n\n // INSTANCE PIN (Stage D machine-primary): the steady-state machine pointer\n // returns the pre-established turn session BY REFERENCE — never a fresh build —\n // so the turn-start manifest write + the per-op reads land on ONE\n // SelfhostedSession/manifest. Matched on BOTH the sandbox id AND the epoch: a\n // swap away (different id) or a swap-back (same id, higher epoch) falls through\n // to a fresh build fenced under the CURRENT epoch (the stale pinned instance is\n // fenced at the old epoch and must not be reused).\n if (\n deps.pinnedSelfhosted &&\n pointer.activeSandboxId === deps.pinnedSelfhosted.sandboxId &&\n pointer.activeEpoch === deps.pinnedSelfhosted.epoch\n ) {\n return {\n session: deps.pinnedSelfhosted.session,\n sandboxId: pointer.activeSandboxId,\n kind: \"selfhosted\",\n };\n }\n\n const sandbox = await deps.getSandbox(pointer.activeSandboxId);\n if (!sandbox) {\n throw new ActiveBackendUnresolvableError(\n \"stale_pointer\",\n `active sandbox ${pointer.activeSandboxId} not found in workspace ${deps.workspaceId}`,\n );\n }\n\n if (sandbox.kind === \"selfhosted\") {\n if (!sandbox.enrollmentId) {\n throw new ActiveBackendUnresolvableError(\n \"offline_enrollment\",\n `selfhosted sandbox ${sandbox.id} has no enrollment (agent id) to address`,\n );\n }\n // Build a request-scoped selfhosted client bound to the target's workspace +\n // enrollment agentId, fenced under the swap's active_epoch. The agent echoes\n // the epoch and rejects a stale op with ERROR_CODE_FENCED → the proxy\n // re-resolves + retries against the new active sandbox. The SAME factory the\n // worker turn's machine-primary establish branch uses (one build shape).\n const connection = await deps.resolveSelfhostedConnection(sandbox);\n if (!connection) {\n throw new ActiveBackendUnresolvableError(\n \"offline_enrollment\",\n `selfhosted sandbox ${sandbox.id} has no live runner connection`,\n );\n }\n if (!connection.workspaceRoot) {\n throw new ActiveBackendUnresolvableError(\n \"workspace_root_unavailable\",\n `selfhosted sandbox ${sandbox.id} has not reported an absolute workspace root; reconnect it with a current agent`,\n );\n }\n const workspaceRoot = resolveConnectedMachineWorkspaceRoot(\n connection.workspaceRoot,\n pointer.workingDir,\n );\n const { session } = await buildSelfhostedBackendSession({\n workspaceId: deps.workspaceId,\n ...(connection.workspaceId !== undefined\n ? { controlWorkspaceId: connection.workspaceId }\n : {}),\n relay: deps.relay,\n controlRpcFactory: deps.controlRpcFactory,\n agentId: sandbox.enrollmentId,\n connectionInstanceId: connection.connectionInstanceId,\n workspaceRoot,\n epoch: pointer.activeEpoch,\n ...(deps.selfhostedTimeoutMs !== undefined ? { timeoutMs: deps.selfhostedTimeoutMs } : {}),\n ...(deps.selfhostedExecTimeoutMs !== undefined\n ? { execTimeoutMs: deps.selfhostedExecTimeoutMs }\n : {}),\n ...(deps.selfhostedOnOp !== undefined ? { onOp: deps.selfhostedOnOp } : {}),\n ...(deps.selfhostedAdoptBackgroundCommand !== undefined\n ? { adoptBackgroundCommand: deps.selfhostedAdoptBackgroundCommand }\n : {}),\n ...(deps.selfhostedSettleBackgroundCommand !== undefined\n ? { settleBackgroundCommand: deps.selfhostedSettleBackgroundCommand }\n : {}),\n ...(deps.selfhostedCaptureBackgroundCommandOutput\n ? { captureBackgroundCommandOutput: deps.selfhostedCaptureBackgroundCommandOutput }\n : {}),\n ...(connection.opStream !== undefined ? { opStream: connection.opStream } : {}),\n operationResourcePolicy: connection.operationResourcePolicy,\n operationResourcePolicySupported: connection.operationResourcePolicySupported,\n operationCpuQuotaSupported: connection.operationCpuQuotaSupported,\n transactionalFsWriteSupported: connection.transactionalFsWriteSupported === true,\n browserControlHttpSupported: connection.browserControlHttpSupported === true,\n // The routing proxy caches this session by sandbox+epoch, but command\n // policy and runner authority are mutable. Re-read one coherent DB\n // snapshot only when a new exec/Git is admitted.\n resolveOperationAdmission: async () => {\n const current = await deps.resolveSelfhostedConnection(sandbox);\n if (!current) return null;\n if (!current.workspaceRoot) {\n throw new ActiveBackendUnresolvableError(\n \"workspace_root_unavailable\",\n `selfhosted sandbox ${sandbox.id} no longer has a reported workspace root`,\n );\n }\n return {\n ...current,\n workspaceRoot: resolveConnectedMachineWorkspaceRoot(\n current.workspaceRoot,\n pointer.workingDir,\n ),\n };\n },\n // The turn's declared environment → the session's manifest.environment, so\n // the SDK's per-turn manifest-env delta is empty (no \"cannot change manifest\n // environment variables\" throw on a pin-to-vm turn).\n ...(deps.environment !== undefined ? { environment: deps.environment } : {}),\n ...(deps.transientExecEnvironment !== undefined\n ? { transientExecEnvironment: deps.transientExecEnvironment }\n : {}),\n });\n return {\n session: session as RoutableBackendSession,\n sandboxId: sandbox.id,\n kind: \"selfhosted\",\n };\n }\n\n if (sandbox.kind === \"modal\") {\n if (!deps.establishModalTarget) {\n throw new ActiveBackendUnresolvableError(\n \"unsupported_backend_context\",\n `modal swap target ${sandbox.id} cannot be established in this context (no establisher wired)`,\n );\n }\n const session = await deps.establishModalTarget(sandbox);\n return { session, sandboxId: sandbox.id, kind: \"modal\" };\n }\n\n throw new ActiveBackendUnresolvableError(\n \"unsupported_backend_context\",\n `unsupported swap target kind \"${sandbox.kind}\" for sandbox ${sandbox.id}`,\n );\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAS,2BAA2B,yBAAyB;;;AC/B7D,SAAS,cAAc;AACvB,SAAS,OAAO,SAAS,SAAS,UAAU,UAAU,UAAU,UAAU;AAC1E,SAAS,cAAc;AACvB,SAAS,YAAY;AAqBd,IAAM,gCAAgC;AACtC,IAAM,8CAA8C;AAC3D,IAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AACF;AAGA,SAAS,UAAU,QAAmC;AACpD,SAAO,IAAI,OAAO,MAAM,SAAS,2CAA2C;AAC9E;AACA,IAAM,cAAc,sBAAsB,IAAI,SAAS;AAIvD,eAAe,iBAAiB,KAA8C;AAC5E,MAAI;AACF,UAAM,O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;AACA,SAAO;AAAA,IACL,GAAI,cAAc,CAAC;AAAA;AAAA;AAAA;AAAA,IAInB,WAAW,YAAY;AAAA,IACvB;AAAA,EACF;AACF;","names":["createHash","constants","lstat","open","readdir","realpath","isAbsolute","join","lstat","readdir","join","decodeNativeSnapshotRef","WORKSPACE_ARCHIVE_DESCRIPTOR_VERSION","decodeNativeSnapshotRef","encodeNativeSnapshotRef","parseWorkspaceArchiveDescriptor","base64","status","shellQuote","lstat","readdir","join","run","resolve","descriptor","constants","isAbsolute","open","realpath","handle","readdir","lstat","createHash","sha256","join","encoder","decoder","BROWSER_CONTROL_PORT","DESKTOP_STREAM_PORT","OPENGENI_SANDBOX_PROVIDER_INSTANCE_ID_FIELD","TERMINAL_STREAM_PORT","parseWorkspaceArchiveObjectRef","parseWorkspaceArchiveDescriptor","SandboxBackend","execFile","isAbsolute","promisify","isAbsolute","join","resolve","constants","lstat","open","readdir","realpath","rm","invalid","isAbsolute","resolve","fingerprint","realpath","lstat","readdir","join","open","constants","rm","release","execFileAsync","promisify","execFile","isAbsolute","lstat","isAbsolute","isAbsolute","lstat","validateCredentialPair","process","output","absolutePath","status","ModalClient","image","resolve","isDeepStrictEqual","status","isDeepStrictEqual","quote","isDeepStrictEqual","resolve","isDeepStrictEqual","receipts","randomUUID","posix","status","delay","ModalRouterProviderCommand","result","resolve","ModalCommandControl","run","lookup","posix","randomUUID","status","delay","ModalRouterProviderCommand","ModalClient","createHash","ModalClient","workspaceRoot","status","requestId","observe","ModalCommandControl","binding","binding","sandbox","createHash","randomUUID","lstat","readdir","posix","DESKTOP_STREAM_PORT","DESKTOP_STREAM_PORT","StreamTokenPayload","DESKTOP_STREAM_PORT","decoder","encoder","frame","DEFAULT_EXEC_YIELD_TIME_MS","DEFAULT_WRITE_STDIN_YIELD_TIME_MS","createHash","posix","delay","resolve","process","randomUUID","status","sessionId","consumed","output","readText","lstat","readdir","ErrorCode","DESKTOP_STREAM_PORT","requestId","resolve","blake3","bytesToHex","OpState","requestId","status","OpState","blake3","resolve","frame","bytesToHex","injectedApplyDiff","workspaceRoot","ErrorCode","retries","frame","readText","reply","requestId","DESKTOP_STREAM_PORT","SandboxBackend","CAPABILITY_DESCRIPTORS","changed","collectSandboxEnvironment","parseExposedPorts","createHash","canonicalModalCheckpointProviderBinding","sha256","createHash","DESKTOP_STREAM_PORT","LEGACY_SANDBOX_PROVIDER_INSTANCE_ID_FIELDS","DESKTOP_STREAM_PORT","shellQuote","LEGACY_SANDBOX_PROVIDER_INSTANCE_ID_FIELDS","state","resolve","status","execResultOutput","execResultExitCode","inferExitFromOutput","shellQuote","createHash","randomUUID","posixPath","BROWSER_CONTROL_PORT","MARKER","quote","status","status","boundedPort","randomUUID","shellQuote","BROWSER_CONTROL_PORT","boundedTimeout","isRecord","binding","sha256","frame","createHash","posixPath","isRecord","shellQuote","outputOf","createHash","posixPath","createHash","randomUUID","join","posix","resolve","createHash","workspaceRoot","posix","join","resolve","run","randomUUID","shellQuote","posixPath","createHash","DESKTOP_STREAM_PORT","ErrorCode","FsEntryKind","encoder","decoder","requestId","blake3","bytesToHex","ErrorCode","OpAck","OpChannel","OpFrame","OpLostReason","OpState","OpAck","encoder","run","errorResponse","ErrorCode","requestId","frame","OpFrame","OpState","OpLostReason","OpChannel","concat","bytesToHex","blake3","status","workspaceRoot","DESKTOP_STREAM_PORT","TERMINAL_STREAM_PORT","BROWSER_CONTROL_PORT","decodeNativeSnapshotRef","run","result","resolve","OPENGENI_SANDBOX_PROVIDER_INSTANCE_ID_FIELD","parseWorkspaceArchiveObjectRef","parseWorkspaceArchiveDescriptor"]}