@opengeni/sdk 1.0.1 → 2.3.0-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +117 -2
- package/dist/artifacts.js +5 -5
- package/dist/automations-client.d.ts +17 -0
- package/dist/automations.d.ts +3 -0
- package/dist/automations.js +78 -0
- package/dist/automations.js.map +1 -0
- package/dist/{chunk-YGH5P47G.js → chunk-6IPZY27S.js} +744 -57
- package/dist/chunk-6IPZY27S.js.map +1 -0
- package/dist/{chunk-TYZ4JL4J.js → chunk-AGUKZAXR.js} +2 -2
- package/dist/{chunk-A5DC5WEM.js → chunk-C2H7HBNP.js} +22 -2
- package/dist/chunk-C2H7HBNP.js.map +1 -0
- package/dist/{chunk-GU6JF75T.js → chunk-C4DJPZRU.js} +1 -1
- package/dist/{chunk-GU6JF75T.js.map → chunk-C4DJPZRU.js.map} +1 -1
- package/dist/{chunk-ST5DDKJP.js → chunk-GW3EJ2GP.js} +52 -1
- package/dist/chunk-GW3EJ2GP.js.map +1 -0
- package/dist/{chunk-4DV37UUA.js → chunk-TW5MNHUX.js} +16 -2
- package/dist/chunk-TW5MNHUX.js.map +1 -0
- package/dist/{chunk-VWE2QIVO.js → chunk-XNG7YGR3.js} +23 -6
- package/dist/chunk-XNG7YGR3.js.map +1 -0
- package/dist/client.d.ts +159 -26
- package/dist/codex-realtime-controller.d.ts +1 -0
- package/dist/codex-realtime-controller.js +2 -2
- package/dist/company-brain.d.ts +32 -0
- package/dist/company-profile.d.ts +1 -1
- package/dist/core.js +4 -4
- package/dist/editable-artifacts/browser-session.d.ts +7 -3
- package/dist/editable-artifacts/controller.d.ts +4 -1
- package/dist/editable-artifacts/errors.d.ts +1 -1
- package/dist/editable-artifacts/http-live-transport.d.ts +6 -2
- package/dist/editable-artifacts/index.d.ts +2 -0
- package/dist/editable-artifacts/open-failure.d.ts +9 -0
- package/dist/editable-artifacts/types.d.ts +4 -3
- package/dist/editable-artifacts/worker/kernel-adapter.d.ts +1 -1
- package/dist/editable-artifacts-worker.js +44 -17
- package/dist/editable-artifacts-worker.js.map +1 -1
- package/dist/editable-artifacts.js +222 -119
- package/dist/editable-artifacts.js.map +1 -1
- package/dist/errors.d.ts +1 -1
- package/dist/index.d.ts +7 -4
- package/dist/index.js +61 -12
- package/dist/index.js.map +1 -1
- package/dist/interaction.d.ts +23 -0
- package/dist/interaction.js +4 -1
- package/dist/organization-private-session-settings.d.ts +6 -0
- package/dist/organization-private-session-settings.js +22 -0
- package/dist/organization-private-session-settings.js.map +1 -0
- package/dist/pr-review-client.d.ts +15 -0
- package/dist/pr-review.d.ts +4 -0
- package/dist/pr-review.js +56 -0
- package/dist/pr-review.js.map +1 -0
- package/dist/preference-registry.d.ts +8 -0
- package/dist/realtime.js +2 -2
- package/dist/retained-artifacts.d.ts +5 -1
- package/dist/types.d.ts +1023 -13
- package/dist/workspace-instruction-policies.d.ts +22 -0
- package/dist/workspace-learning.d.ts +124 -0
- package/package.json +14 -2
- package/src/automations-client.ts +118 -0
- package/src/automations.ts +15 -0
- package/src/client.ts +1049 -71
- package/src/codex-realtime-controller.ts +21 -0
- package/src/company-brain.ts +99 -0
- package/src/company-profile.ts +4 -1
- package/src/editable-artifacts/browser-session.ts +36 -22
- package/src/editable-artifacts/controller.ts +66 -45
- package/src/editable-artifacts/errors.ts +2 -0
- package/src/editable-artifacts/http-live-transport.ts +62 -37
- package/src/editable-artifacts/index.ts +6 -0
- package/src/editable-artifacts/open-failure.ts +79 -0
- package/src/editable-artifacts/storage.ts +31 -40
- package/src/editable-artifacts/types.ts +4 -3
- package/src/editable-artifacts/worker/kernel-adapter.ts +23 -7
- package/src/editable-artifacts/worker/runtime.ts +26 -13
- package/src/editable-artifacts/worker/wire-codec.ts +23 -5
- package/src/errors.ts +1 -1
- package/src/index.ts +134 -0
- package/src/interaction.ts +95 -0
- package/src/organization-private-session-settings.ts +33 -0
- package/src/pr-review-client.ts +84 -0
- package/src/pr-review.ts +15 -0
- package/src/preference-registry.ts +9 -0
- package/src/retained-artifacts.ts +101 -0
- package/src/stream.ts +13 -2
- package/src/types.ts +1174 -12
- package/src/workspace-instruction-policies.ts +24 -0
- package/src/workspace-learning.ts +138 -0
- package/dist/chunk-4DV37UUA.js.map +0 -1
- package/dist/chunk-A5DC5WEM.js.map +0 -1
- package/dist/chunk-ST5DDKJP.js.map +0 -1
- package/dist/chunk-VWE2QIVO.js.map +0 -1
- package/dist/chunk-YGH5P47G.js.map +0 -1
- /package/dist/{chunk-TYZ4JL4J.js.map → chunk-AGUKZAXR.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/editable-artifacts/worker/kernel-adapter.ts","../src/editable-artifacts/worker/runtime.ts","../src/editable-artifacts/worker/browser-entry.ts"],"sourcesContent":["import {\n EDITABLE_ARTIFACT_COMMAND_MAX_BYTES,\n EDITABLE_ARTIFACT_INTENT_MAX_BYTES,\n EDITABLE_ARTIFACT_INTENT_VERSION,\n EDITABLE_ARTIFACT_PRODUCT_MAX_SNAPSHOT_BYTES,\n SPREADSHEET_ARTIFACT_COMMAND_VERSION,\n} from \"@opengeni/contracts/editable-artifacts\";\nimport { MAX_COMMITTED_TRANSACTION_BYTES } from \"@opengeni/contracts/editable-artifact-committed-transaction\";\nimport type { ArtifactWorkerInitializeInput } from \"./wire-codec\";\nimport type { EditableArtifactModality } from \"../types\";\nimport { ArtifactWorkerProtocolError } from \"./rpc-protocol\";\n\nexport type ArtifactWorkerKernelSession = {\n readonly modality: EditableArtifactModality;\n /** Replays one exact whole canonical OGACO001 transaction. */\n applyCommitted: (committedTransactionBytes: Uint8Array) => void;\n /** Authors and applies one exact OGATX001 intent over the current frontier. */\n applyPending: (intentBytes: Uint8Array) => void;\n /** Applies one exact document/presentation command and returns its native receipt. */\n applyCommands: (commandBytes: Uint8Array) => Uint8Array;\n /** Native serialized-model revision; unavailable for spreadsheets. */\n nativeRevision: () => number;\n /** Stages an atomic candidate without serializing/reopening the model. */\n fork: () => ArtifactWorkerKernelSession;\n /** Kernel-defined canonical hash; never synthesized from transport bytes. */\n stateHash: () => Promise<string>;\n snapshot: () => Uint8Array;\n /** Canonical bounded OGAKQ request to canonical OGAKV projection. */\n query: (queryBytes: Uint8Array) => Uint8Array;\n dispose: () => void;\n};\n\n/** A valid local intent whose structural preconditions no longer project. */\nexport class ArtifactWorkerPendingProjectionError extends Error {\n readonly code: string;\n\n constructor(code: string, message = \"pending transaction cannot project over confirmed state\") {\n super(message);\n this.name = \"ArtifactWorkerPendingProjectionError\";\n this.code = requireErrorCode(code, \"pending projection code\");\n }\n}\n\n/** Entirely Worker-owned adapter over one compatible collaboration WASM build. */\nexport type ArtifactWorkerKernelAdapter = {\n readonly modality: EditableArtifactModality;\n readonly protocolVersion: number;\n readonly kernelVersion: string;\n readonly modelSchemaVersion: number;\n readonly commandVersion: number;\n readonly maximumSnapshotBytes: number;\n readonly maximumCommandBytes: number;\n readonly maximumIntentBytes: number;\n readonly maximumCommittedTransactionBytes: number;\n readonly maximumQueryBytes: number;\n readonly maximumQueryResponseBytes: number;\n canonicalizeSnapshot: (snapshotBytes: Uint8Array) => Uint8Array;\n open: (snapshotBytes: Uint8Array) => ArtifactWorkerKernelSession;\n dispose?: () => void;\n};\n\nexport type ArtifactWorkerKernelAdapterFactory = (\n input: ArtifactWorkerInitializeInput,\n) => Promise<ArtifactWorkerKernelAdapter>;\n\ntype WasmCollaborationSession = {\n authorTransaction: (intentBytes: Uint8Array, resolvedBaseBytes: Uint8Array) => Uint8Array;\n applyCommitted: (committedTransactionBytes: Uint8Array) => void;\n snapshot: () => Uint8Array;\n frontier: () => Uint8Array;\n fork: () => WasmCollaborationSession;\n stateHash: () => string;\n revision: () => bigint;\n query: (queryEnvelope: Uint8Array) => Uint8Array;\n isClosed?: () => boolean;\n close?: () => void;\n dispose?: () => void;\n free?: () => void;\n};\n\ntype WasmModalitySession = {\n applyCommands: (commandBytes: Uint8Array) => Uint8Array;\n snapshot: () => Uint8Array;\n revision: () => bigint;\n fork: () => WasmModalitySession;\n stateHash: () => string;\n query: (queryEnvelope: Uint8Array) => Uint8Array;\n isClosed?: () => boolean;\n close?: () => void;\n dispose?: () => void;\n free?: () => void;\n};\n\ntype WasmKernelModuleBase = {\n default?: (input: { module_or_path: string | URL }) => Promise<unknown>;\n capabilities: () => Uint8Array;\n buildIdentity: () => Uint8Array;\n};\n\ntype WasmKernelModule =\n | (WasmKernelModuleBase &\n Readonly<{\n modality: \"spreadsheet\";\n canonicalizeSnapshot: (snapshotBytes: Uint8Array) => Uint8Array;\n open: (snapshotBytes: Uint8Array) => WasmCollaborationSession;\n }>)\n | (WasmKernelModuleBase &\n Readonly<{\n modality: \"document\" | \"presentation\";\n canonicalizeSnapshot: (snapshotBytes: Uint8Array) => Uint8Array;\n open: (snapshotBytes: Uint8Array) => WasmModalitySession;\n }>);\n\ntype WasmCapabilities = Readonly<{\n abiVersion: number;\n buildIdentityFormat: \"utf8\";\n canonicalStateHash: \"sha256:canonical-snapshot\";\n collaboration: boolean;\n collaborationSnapshotVersion: number;\n commandSchemaVersion: number;\n committedTransactionVersion: number;\n document: boolean;\n documentCommandVersion: number;\n documentQueryResponseVersion: number;\n documentQueryVersion: number;\n documentReceiptVersion: number;\n documentSnapshotVersion: number;\n documentStatefulSessions: boolean;\n editableArtifactIntentVersion: number;\n kernelSnapshotVersion: number;\n spreadsheetCommandVersion: number;\n maxCellsPerBatch: number;\n maxCommandBytes: number;\n maxCommands: number;\n maxSnapshotBytes: number;\n maxSpreadsheetCommandBytes: number;\n maxIntentBytes: number;\n maxCommittedTransactionBytes: number;\n maxDocumentCommandBytes: number;\n maxDocumentCommands: number;\n maxDocumentQueryBytes: number;\n maxDocumentQueryResponseBytes: number;\n maxDocumentSnapshotBytes: number;\n maxMetadataScannedCells: number;\n maxQueryBytes: number;\n maxQueryResponseBytes: number;\n maxViewportArea: number;\n maxViewportCells: number;\n maxMetadataSheets: number;\n maxPresentationCommandBytes: number;\n maxPresentationQueryBytes: number;\n maxPresentationResponseBytes: number;\n maxPresentationSnapshotBytes: number;\n maxTextLayoutFontBundleBytes: number;\n maxTextLayoutRequestBytes: number;\n maxTextLayoutResponseBytes: number;\n presentation: boolean;\n presentationCommandVersion: number;\n presentationQueryResponseVersion: number;\n presentationQueryVersion: number;\n presentationSnapshotVersion: number;\n presentationStatefulSessions: boolean;\n queryResponseVersion: number;\n queryVersion: number;\n receiptSchemaVersion: number;\n retainedRenderPatchVersion: number;\n retainedRenderTileVersion: number;\n safeRust: true;\n statefulSessions: boolean;\n textLayout: boolean;\n textLayoutFontBundleVersion: number;\n textLayoutRequestVersion: number;\n textLayoutResponseVersion: number;\n textLayoutStatefulSessions: boolean;\n sessionForks: boolean;\n transport: \"bounded-uint8array\";\n workbookMetadataQueries: boolean;\n}>;\n\nconst MAX_BUILD_IDENTITY_BYTES = 512;\nconst MAX_CAPABILITIES_BYTES = 8 * 1024;\nconst MAX_FRONTIER_BYTES = 8 + 2 + 2 + 4 + 1_024 * 16 + 8;\nconst WASM_MAX_CELLS_PER_BATCH = 500_000;\nconst WASM_MAX_COMMAND_BYTES = 8 * 1024 * 1024;\nconst WASM_MAX_SNAPSHOT_BYTES = EDITABLE_ARTIFACT_PRODUCT_MAX_SNAPSHOT_BYTES;\nconst SHA256_PATTERN = /^sha256:[0-9a-f]{64}$/u;\n\nexport const loadBrowserWasmKernelAdapter: ArtifactWorkerKernelAdapterFactory = async (input) => {\n const rawWasm = await import(/* @vite-ignore */ input.wasmGlueUrl);\n const wasm = validateWasmModule(rawWasm, input.modality);\n if (wasm.default) await wasm.default({ module_or_path: input.wasmBinaryUrl });\n\n const buildIdentity = decodeUtf8(\n requireBoundedBytes(wasm.buildIdentity(), \"WASM build identity\", MAX_BUILD_IDENTITY_BYTES),\n \"WASM build identity\",\n );\n if (buildIdentity.length === 0) {\n throw adapterError(\"incompatible_wasm_build\", \"WASM build identity is empty\");\n }\n const capabilities = decodeCapabilities(\n requireBoundedBytes(wasm.capabilities(), \"WASM capabilities\", MAX_CAPABILITIES_BYTES),\n );\n assertRequestedLimits(input, capabilities);\n\n const profile = capabilityProfile(input.modality, capabilities);\n const adapter: ArtifactWorkerKernelAdapter = {\n modality: input.modality,\n protocolVersion: capabilities.editableArtifactIntentVersion,\n kernelVersion: buildIdentity,\n modelSchemaVersion: profile.modelSchemaVersion,\n commandVersion: profile.commandVersion,\n maximumSnapshotBytes: profile.maximumSnapshotBytes,\n maximumCommandBytes: profile.maximumCommandBytes,\n maximumIntentBytes: capabilities.maxIntentBytes,\n maximumCommittedTransactionBytes: capabilities.maxCommittedTransactionBytes,\n maximumQueryBytes: profile.maximumQueryBytes,\n maximumQueryResponseBytes: profile.maximumQueryResponseBytes,\n canonicalizeSnapshot(snapshotBytes) {\n return requireOwnedOutput(\n wasm.canonicalizeSnapshot(snapshotBytes),\n `canonical ${input.modality} snapshot`,\n input.maximumSnapshotBytes,\n );\n },\n open(snapshotBytes) {\n if (wasm.modality === \"spreadsheet\") {\n return wrapWasmCollaborationSession(wasm.open(snapshotBytes), input);\n }\n return wrapWasmModalitySession(wasm.open(snapshotBytes), input);\n },\n };\n return Object.freeze(adapter);\n};\n\nfunction wrapWasmCollaborationSession(\n session: WasmCollaborationSession,\n limits: ArtifactWorkerInitializeInput,\n): ArtifactWorkerKernelSession {\n requireSessionAbi(session);\n let disposed = false;\n const requireOpen = (): void => {\n if (disposed || session.isClosed?.() === true) {\n throw adapterError(\"session_closed\", \"artifact collaboration session is closed\");\n }\n };\n return {\n modality: \"spreadsheet\",\n applyCommitted(committedTransactionBytes) {\n requireOpen();\n requireInputBytes(\n committedTransactionBytes,\n \"committed transaction\",\n limits.maximumCommittedTransactionBytes,\n );\n session.applyCommitted(committedTransactionBytes);\n },\n applyPending(intentBytes) {\n requireOpen();\n requireInputBytes(intentBytes, \"pending intent\", limits.maximumIntentBytes);\n const frontier = requireOwnedOutput(\n session.frontier(),\n \"causal frontier\",\n MAX_FRONTIER_BYTES,\n );\n try {\n // The exact OGATX contains its sole OGASC mutation payload. The return\n // value is a whole OGACO proof for this speculative branch; validating\n // its bound is sufficient because speculative OGACO is never persisted.\n requireOwnedOutput(\n session.authorTransaction(intentBytes, frontier),\n \"speculative committed transaction\",\n limits.maximumCommittedTransactionBytes,\n );\n } catch (error) {\n const projectionCode = classifyProjectionFailure(error);\n if (projectionCode !== null) {\n throw new ArtifactWorkerPendingProjectionError(projectionCode);\n }\n throw error;\n }\n },\n applyCommands() {\n throw adapterError(\n \"unsupported_modality\",\n \"spreadsheet session does not apply serialized commands\",\n );\n },\n nativeRevision() {\n throw adapterError(\"unsupported_modality\", \"spreadsheet session has no native revision\");\n },\n fork() {\n requireOpen();\n return wrapWasmCollaborationSession(session.fork(), limits);\n },\n async stateHash() {\n requireOpen();\n const result = session.stateHash();\n if (!SHA256_PATTERN.test(result)) {\n throw adapterError(\"invalid_state_hash\", \"WASM kernel returned an invalid state hash\");\n }\n return result;\n },\n snapshot() {\n requireOpen();\n return requireOwnedOutput(\n session.snapshot(),\n \"collaboration snapshot\",\n limits.maximumSnapshotBytes,\n );\n },\n query(queryBytes) {\n requireOpen();\n requireInputBytes(queryBytes, \"kernel query\", limits.maximumQueryBytes);\n return requireOwnedOutput(\n session.query(queryBytes),\n \"kernel projection\",\n limits.maximumQueryResponseBytes,\n );\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n try {\n session.dispose?.();\n } finally {\n try {\n session.close?.();\n } finally {\n session.free?.();\n }\n }\n },\n };\n}\n\nfunction wrapWasmModalitySession(\n session: WasmModalitySession,\n limits: ArtifactWorkerInitializeInput,\n): ArtifactWorkerKernelSession {\n requireModalitySessionAbi(session);\n let disposed = false;\n const requireOpen = (): void => {\n if (disposed || session.isClosed?.() === true) {\n throw adapterError(\"session_closed\", `artifact ${limits.modality} session is closed`);\n }\n };\n return {\n modality: limits.modality,\n applyCommitted() {\n throw adapterError(\n \"unsupported_modality\",\n \"serialized session requires decoded OGAST replay\",\n );\n },\n applyPending() {\n throw adapterError(\"unsupported_modality\", \"serialized session requires exact command bytes\");\n },\n applyCommands(commandBytes) {\n requireOpen();\n requireInputBytes(commandBytes, `${limits.modality} command`, limits.maximumCommandBytes);\n return requireOwnedOutput(\n session.applyCommands(commandBytes),\n `${limits.modality} native receipt`,\n limits.maximumCommittedTransactionBytes,\n );\n },\n nativeRevision() {\n requireOpen();\n const revision = session.revision();\n if (revision < 0n || revision > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw adapterError(\"invalid_revision\", \"WASM kernel returned an unsafe native revision\");\n }\n return Number(revision);\n },\n fork() {\n requireOpen();\n return wrapWasmModalitySession(session.fork(), limits);\n },\n async stateHash() {\n requireOpen();\n const result = session.stateHash();\n if (!SHA256_PATTERN.test(result)) {\n throw adapterError(\"invalid_state_hash\", \"WASM kernel returned an invalid state hash\");\n }\n return result;\n },\n snapshot() {\n requireOpen();\n return requireOwnedOutput(\n session.snapshot(),\n `${limits.modality} snapshot`,\n limits.maximumSnapshotBytes,\n );\n },\n query(queryBytes) {\n requireOpen();\n requireInputBytes(queryBytes, `${limits.modality} query`, limits.maximumQueryBytes);\n return requireOwnedOutput(\n session.query(queryBytes),\n `${limits.modality} projection`,\n limits.maximumQueryResponseBytes,\n );\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n try {\n session.dispose?.();\n } finally {\n try {\n session.close?.();\n } finally {\n session.free?.();\n }\n }\n },\n };\n}\n\nfunction requireModalitySessionAbi(session: WasmModalitySession): void {\n if (\n !isObject(session) ||\n typeof session.applyCommands !== \"function\" ||\n typeof session.snapshot !== \"function\" ||\n typeof session.revision !== \"function\" ||\n typeof session.fork !== \"function\" ||\n typeof session.stateHash !== \"function\" ||\n typeof session.query !== \"function\"\n ) {\n session?.dispose?.();\n session?.close?.();\n session?.free?.();\n throw adapterError(\n \"incompatible_wasm_build\",\n \"WASM modality session lacks the required stateful ABI\",\n );\n }\n}\n\nfunction requireSessionAbi(session: WasmCollaborationSession): void {\n if (\n !isObject(session) ||\n typeof session.authorTransaction !== \"function\" ||\n typeof session.applyCommitted !== \"function\" ||\n typeof session.snapshot !== \"function\" ||\n typeof session.frontier !== \"function\" ||\n typeof session.fork !== \"function\" ||\n typeof session.stateHash !== \"function\" ||\n typeof session.revision !== \"function\" ||\n typeof session.query !== \"function\"\n ) {\n session?.dispose?.();\n session?.close?.();\n session?.free?.();\n throw adapterError(\n \"incompatible_wasm_build\",\n \"WASM collaboration session lacks the required stateful ABI\",\n );\n }\n}\n\nfunction validateWasmModule(input: unknown, modality: EditableArtifactModality): WasmKernelModule {\n if (!isObject(input)) throw adapterError(\"invalid_wasm_module\", \"WASM glue module is invalid\");\n const capabilities = callable(input, \"capabilities\");\n const buildIdentity = callable(input, \"buildIdentity\");\n const initializer = optionalCallable(input, \"default\");\n const base: WasmKernelModuleBase = {\n capabilities: capabilities as WasmKernelModuleBase[\"capabilities\"],\n buildIdentity: buildIdentity as WasmKernelModuleBase[\"buildIdentity\"],\n ...(initializer\n ? { default: initializer as NonNullable<WasmKernelModuleBase[\"default\"]> }\n : {}),\n };\n const canonicalizeName =\n modality === \"spreadsheet\"\n ? \"canonicalizeCollaborationSnapshot\"\n : modality === \"document\"\n ? \"canonicalizeDocumentSnapshot\"\n : \"canonicalizePresentationSnapshot\";\n const sessionName =\n modality === \"spreadsheet\"\n ? \"ArtifactCollaborationSession\"\n : modality === \"document\"\n ? \"ArtifactDocumentSession\"\n : \"ArtifactPresentationSession\";\n const canonicalizeSnapshot = callable(input, canonicalizeName);\n const sessionClass = data(input, sessionName);\n if (!isObject(sessionClass)) {\n throw adapterError(\"invalid_wasm_module\", `WASM glue has no ${sessionName} export`);\n }\n const open = callable(sessionClass, \"open\");\n if (modality === \"spreadsheet\") {\n return {\n ...base,\n modality,\n canonicalizeSnapshot: canonicalizeSnapshot as (snapshotBytes: Uint8Array) => Uint8Array,\n open: open as (snapshotBytes: Uint8Array) => WasmCollaborationSession,\n };\n }\n return {\n ...base,\n modality,\n canonicalizeSnapshot: canonicalizeSnapshot as (snapshotBytes: Uint8Array) => Uint8Array,\n open: open as (snapshotBytes: Uint8Array) => WasmModalitySession,\n };\n}\n\nfunction decodeCapabilities(bytes: Uint8Array): WasmCapabilities {\n let value: unknown;\n try {\n const text = decodeUtf8(bytes, \"WASM capabilities\");\n value = JSON.parse(text) as unknown;\n if (JSON.stringify(value) !== text) {\n throw new TypeError(\"capabilities JSON is not canonical\");\n }\n } catch (error) {\n throw new ArtifactWorkerProtocolError(\n \"incompatible_wasm_build\",\n \"WASM capabilities are not canonical UTF-8 JSON\",\n { cause: error },\n );\n }\n if (!isPlainRecord(value)) {\n throw adapterError(\"incompatible_wasm_build\", \"WASM capabilities must be a plain record\");\n }\n const expectedKeys = [\n \"abiVersion\",\n \"buildIdentityFormat\",\n \"canonicalStateHash\",\n \"collaboration\",\n \"collaborationSnapshotVersion\",\n \"commandSchemaVersion\",\n \"committedTransactionVersion\",\n \"document\",\n \"documentCommandVersion\",\n \"documentQueryResponseVersion\",\n \"documentQueryVersion\",\n \"documentReceiptVersion\",\n \"documentSnapshotVersion\",\n \"documentStatefulSessions\",\n \"editableArtifactIntentVersion\",\n \"kernelSnapshotVersion\",\n \"maxCellsPerBatch\",\n \"maxCommandBytes\",\n \"maxCommands\",\n \"maxCommittedTransactionBytes\",\n \"maxDocumentCommandBytes\",\n \"maxDocumentCommands\",\n \"maxDocumentQueryBytes\",\n \"maxDocumentQueryResponseBytes\",\n \"maxDocumentSnapshotBytes\",\n \"maxIntentBytes\",\n \"maxMetadataScannedCells\",\n \"maxMetadataSheets\",\n \"maxPresentationCommandBytes\",\n \"maxPresentationQueryBytes\",\n \"maxPresentationResponseBytes\",\n \"maxPresentationSnapshotBytes\",\n \"maxQueryBytes\",\n \"maxQueryResponseBytes\",\n \"maxSnapshotBytes\",\n \"maxSpreadsheetCommandBytes\",\n \"maxTextLayoutFontBundleBytes\",\n \"maxTextLayoutRequestBytes\",\n \"maxTextLayoutResponseBytes\",\n \"maxViewportArea\",\n \"maxViewportCells\",\n \"presentation\",\n \"presentationCommandVersion\",\n \"presentationQueryResponseVersion\",\n \"presentationQueryVersion\",\n \"presentationSnapshotVersion\",\n \"presentationStatefulSessions\",\n \"queryResponseVersion\",\n \"queryVersion\",\n \"receiptSchemaVersion\",\n \"retainedRenderPatchVersion\",\n \"retainedRenderTileVersion\",\n \"safeRust\",\n \"sessionForks\",\n \"spreadsheetCommandVersion\",\n \"statefulSessions\",\n \"textLayout\",\n \"textLayoutFontBundleVersion\",\n \"textLayoutRequestVersion\",\n \"textLayoutResponseVersion\",\n \"textLayoutStatefulSessions\",\n \"transport\",\n \"workbookMetadataQueries\",\n ] as const;\n const keys = Object.keys(value).sort();\n if (\n keys.length !== expectedKeys.length ||\n keys.some((key, index) => key !== expectedKeys[index])\n ) {\n throw adapterError(\n \"incompatible_wasm_build\",\n \"WASM collaboration capabilities have unknown or missing fields\",\n );\n }\n const normalized = {\n abiVersion: positiveInteger(value.abiVersion, \"abiVersion\"),\n buildIdentityFormat: value.buildIdentityFormat,\n canonicalStateHash: value.canonicalStateHash,\n collaboration: strictBoolean(value.collaboration, \"collaboration\"),\n collaborationSnapshotVersion: positiveInteger(\n value.collaborationSnapshotVersion,\n \"collaborationSnapshotVersion\",\n ),\n commandSchemaVersion: positiveInteger(value.commandSchemaVersion, \"commandSchemaVersion\"),\n committedTransactionVersion: positiveInteger(\n value.committedTransactionVersion,\n \"committedTransactionVersion\",\n ),\n document: strictBoolean(value.document, \"document\"),\n documentCommandVersion: positiveInteger(value.documentCommandVersion, \"documentCommandVersion\"),\n documentQueryResponseVersion: positiveInteger(\n value.documentQueryResponseVersion,\n \"documentQueryResponseVersion\",\n ),\n documentQueryVersion: positiveInteger(value.documentQueryVersion, \"documentQueryVersion\"),\n documentReceiptVersion: positiveInteger(value.documentReceiptVersion, \"documentReceiptVersion\"),\n documentSnapshotVersion: positiveInteger(\n value.documentSnapshotVersion,\n \"documentSnapshotVersion\",\n ),\n documentStatefulSessions: strictBoolean(\n value.documentStatefulSessions,\n \"documentStatefulSessions\",\n ),\n editableArtifactIntentVersion: positiveInteger(\n value.editableArtifactIntentVersion,\n \"editableArtifactIntentVersion\",\n ),\n kernelSnapshotVersion: positiveInteger(value.kernelSnapshotVersion, \"kernelSnapshotVersion\"),\n spreadsheetCommandVersion: positiveInteger(\n value.spreadsheetCommandVersion,\n \"spreadsheetCommandVersion\",\n ),\n maxCellsPerBatch: positiveInteger(value.maxCellsPerBatch, \"maxCellsPerBatch\"),\n maxCommands: positiveInteger(value.maxCommands, \"maxCommands\"),\n maxSnapshotBytes: positiveInteger(value.maxSnapshotBytes, \"maxSnapshotBytes\"),\n maxCommandBytes: positiveInteger(value.maxCommandBytes, \"maxCommandBytes\"),\n maxSpreadsheetCommandBytes: positiveInteger(\n value.maxSpreadsheetCommandBytes,\n \"maxSpreadsheetCommandBytes\",\n ),\n maxIntentBytes: positiveInteger(value.maxIntentBytes, \"maxIntentBytes\"),\n maxCommittedTransactionBytes: positiveInteger(\n value.maxCommittedTransactionBytes,\n \"maxCommittedTransactionBytes\",\n ),\n maxDocumentCommandBytes: positiveInteger(\n value.maxDocumentCommandBytes,\n \"maxDocumentCommandBytes\",\n ),\n maxDocumentCommands: positiveInteger(value.maxDocumentCommands, \"maxDocumentCommands\"),\n maxDocumentQueryBytes: positiveInteger(value.maxDocumentQueryBytes, \"maxDocumentQueryBytes\"),\n maxDocumentQueryResponseBytes: positiveInteger(\n value.maxDocumentQueryResponseBytes,\n \"maxDocumentQueryResponseBytes\",\n ),\n maxDocumentSnapshotBytes: positiveInteger(\n value.maxDocumentSnapshotBytes,\n \"maxDocumentSnapshotBytes\",\n ),\n maxMetadataScannedCells: positiveInteger(\n value.maxMetadataScannedCells,\n \"maxMetadataScannedCells\",\n ),\n maxQueryBytes: positiveInteger(value.maxQueryBytes, \"maxQueryBytes\"),\n maxQueryResponseBytes: positiveInteger(value.maxQueryResponseBytes, \"maxQueryResponseBytes\"),\n maxViewportArea: positiveInteger(value.maxViewportArea, \"maxViewportArea\"),\n maxViewportCells: positiveInteger(value.maxViewportCells, \"maxViewportCells\"),\n maxMetadataSheets: positiveInteger(value.maxMetadataSheets, \"maxMetadataSheets\"),\n maxPresentationCommandBytes: positiveInteger(\n value.maxPresentationCommandBytes,\n \"maxPresentationCommandBytes\",\n ),\n maxPresentationQueryBytes: positiveInteger(\n value.maxPresentationQueryBytes,\n \"maxPresentationQueryBytes\",\n ),\n maxPresentationResponseBytes: positiveInteger(\n value.maxPresentationResponseBytes,\n \"maxPresentationResponseBytes\",\n ),\n maxPresentationSnapshotBytes: positiveInteger(\n value.maxPresentationSnapshotBytes,\n \"maxPresentationSnapshotBytes\",\n ),\n maxTextLayoutFontBundleBytes: positiveInteger(\n value.maxTextLayoutFontBundleBytes,\n \"maxTextLayoutFontBundleBytes\",\n ),\n maxTextLayoutRequestBytes: positiveInteger(\n value.maxTextLayoutRequestBytes,\n \"maxTextLayoutRequestBytes\",\n ),\n maxTextLayoutResponseBytes: positiveInteger(\n value.maxTextLayoutResponseBytes,\n \"maxTextLayoutResponseBytes\",\n ),\n queryResponseVersion: positiveInteger(value.queryResponseVersion, \"queryResponseVersion\"),\n queryVersion: positiveInteger(value.queryVersion, \"queryVersion\"),\n receiptSchemaVersion: positiveInteger(value.receiptSchemaVersion, \"receiptSchemaVersion\"),\n retainedRenderPatchVersion: positiveInteger(\n value.retainedRenderPatchVersion,\n \"retainedRenderPatchVersion\",\n ),\n retainedRenderTileVersion: positiveInteger(\n value.retainedRenderTileVersion,\n \"retainedRenderTileVersion\",\n ),\n presentation: strictBoolean(value.presentation, \"presentation\"),\n presentationCommandVersion: positiveInteger(\n value.presentationCommandVersion,\n \"presentationCommandVersion\",\n ),\n presentationQueryResponseVersion: positiveInteger(\n value.presentationQueryResponseVersion,\n \"presentationQueryResponseVersion\",\n ),\n presentationQueryVersion: positiveInteger(\n value.presentationQueryVersion,\n \"presentationQueryVersion\",\n ),\n presentationSnapshotVersion: positiveInteger(\n value.presentationSnapshotVersion,\n \"presentationSnapshotVersion\",\n ),\n presentationStatefulSessions: strictBoolean(\n value.presentationStatefulSessions,\n \"presentationStatefulSessions\",\n ),\n safeRust: strictBoolean(value.safeRust, \"safeRust\"),\n statefulSessions: strictBoolean(value.statefulSessions, \"statefulSessions\"),\n textLayout: strictBoolean(value.textLayout, \"textLayout\"),\n textLayoutFontBundleVersion: positiveInteger(\n value.textLayoutFontBundleVersion,\n \"textLayoutFontBundleVersion\",\n ),\n textLayoutRequestVersion: positiveInteger(\n value.textLayoutRequestVersion,\n \"textLayoutRequestVersion\",\n ),\n textLayoutResponseVersion: positiveInteger(\n value.textLayoutResponseVersion,\n \"textLayoutResponseVersion\",\n ),\n textLayoutStatefulSessions: strictBoolean(\n value.textLayoutStatefulSessions,\n \"textLayoutStatefulSessions\",\n ),\n sessionForks: strictBoolean(value.sessionForks, \"sessionForks\"),\n transport: value.transport,\n workbookMetadataQueries: strictBoolean(\n value.workbookMetadataQueries,\n \"workbookMetadataQueries\",\n ),\n };\n if (\n normalized.abiVersion !== 1 ||\n normalized.buildIdentityFormat !== \"utf8\" ||\n normalized.canonicalStateHash !== \"sha256:canonical-snapshot\" ||\n normalized.editableArtifactIntentVersion !== EDITABLE_ARTIFACT_INTENT_VERSION ||\n normalized.spreadsheetCommandVersion !== SPREADSHEET_ARTIFACT_COMMAND_VERSION ||\n normalized.collaborationSnapshotVersion !== 1 ||\n normalized.commandSchemaVersion !== 1 ||\n normalized.committedTransactionVersion !== 1 ||\n normalized.documentCommandVersion !== 1 ||\n normalized.documentQueryResponseVersion !== 1 ||\n normalized.documentQueryVersion !== 1 ||\n normalized.documentReceiptVersion !== 1 ||\n normalized.documentSnapshotVersion !== 1 ||\n normalized.documentStatefulSessions !== normalized.document ||\n normalized.kernelSnapshotVersion !== 1 ||\n normalized.maxCellsPerBatch !== WASM_MAX_CELLS_PER_BATCH ||\n normalized.maxCommandBytes !== WASM_MAX_COMMAND_BYTES ||\n normalized.maxSpreadsheetCommandBytes !== EDITABLE_ARTIFACT_COMMAND_MAX_BYTES ||\n normalized.maxCommands !== 10_000 ||\n normalized.maxIntentBytes !== EDITABLE_ARTIFACT_INTENT_MAX_BYTES ||\n normalized.maxCommittedTransactionBytes !== MAX_COMMITTED_TRANSACTION_BYTES ||\n normalized.maxDocumentCommandBytes !== WASM_MAX_COMMAND_BYTES ||\n normalized.maxDocumentCommands !== 4_096 ||\n normalized.maxDocumentQueryBytes !== 256 ||\n normalized.maxDocumentQueryResponseBytes !== 8 * 1024 * 1024 ||\n normalized.maxDocumentSnapshotBytes !== WASM_MAX_SNAPSHOT_BYTES ||\n normalized.maxMetadataScannedCells !== 4_000_000 ||\n normalized.maxQueryBytes !== 68 ||\n normalized.maxQueryResponseBytes !== 8 * 1024 * 1024 ||\n normalized.maxViewportArea !== 1_048_576 ||\n normalized.maxViewportCells !== 262_144 ||\n normalized.maxMetadataSheets !== 10_000 ||\n normalized.maxPresentationCommandBytes !== 4 * 1024 * 1024 ||\n normalized.maxPresentationQueryBytes !== 96 ||\n normalized.maxPresentationResponseBytes !== 8 * 1024 * 1024 ||\n normalized.maxPresentationSnapshotBytes !== WASM_MAX_SNAPSHOT_BYTES ||\n normalized.maxTextLayoutFontBundleBytes !== 48 * 1024 * 1024 ||\n normalized.maxTextLayoutRequestBytes !== 4 * 1024 * 1024 ||\n normalized.maxTextLayoutResponseBytes !== 32 * 1024 * 1024 ||\n normalized.maxSnapshotBytes !== WASM_MAX_SNAPSHOT_BYTES ||\n normalized.queryResponseVersion !== 1 ||\n normalized.queryVersion !== 1 ||\n normalized.receiptSchemaVersion !== 1 ||\n normalized.retainedRenderPatchVersion !== 1 ||\n normalized.retainedRenderTileVersion !== 1 ||\n normalized.presentationCommandVersion !== 1 ||\n normalized.presentationQueryResponseVersion !== 1 ||\n normalized.presentationQueryVersion !== 1 ||\n normalized.presentationSnapshotVersion !== 1 ||\n normalized.presentationStatefulSessions !== normalized.presentation ||\n normalized.safeRust !== true ||\n normalized.statefulSessions !== true ||\n normalized.textLayoutFontBundleVersion !== 1 ||\n normalized.textLayoutRequestVersion !== 1 ||\n normalized.textLayoutResponseVersion !== 1 ||\n normalized.textLayoutStatefulSessions !== normalized.textLayout ||\n normalized.sessionForks !== true ||\n normalized.transport !== \"bounded-uint8array\" ||\n normalized.workbookMetadataQueries !== normalized.collaboration\n ) {\n throw adapterError(\n \"incompatible_wasm_build\",\n \"WASM capabilities do not match the SDK protocol\",\n );\n }\n return Object.freeze(normalized) as WasmCapabilities;\n}\n\nfunction assertRequestedLimits(\n input: ArtifactWorkerInitializeInput,\n capabilities: WasmCapabilities,\n): void {\n const profile = capabilityProfile(input.modality, capabilities);\n const pairs = [\n [\"maximumSnapshotBytes\", input.maximumSnapshotBytes, profile.maximumSnapshotBytes],\n [\"maximumCommandBytes\", input.maximumCommandBytes, profile.maximumCommandBytes],\n [\"maximumIntentBytes\", input.maximumIntentBytes, capabilities.maxIntentBytes],\n [\n \"maximumCommittedTransactionBytes\",\n input.maximumCommittedTransactionBytes,\n capabilities.maxCommittedTransactionBytes,\n ],\n [\"maximumQueryBytes\", input.maximumQueryBytes, profile.maximumQueryBytes],\n [\n \"maximumQueryResponseBytes\",\n input.maximumQueryResponseBytes,\n profile.maximumQueryResponseBytes,\n ],\n ] as const;\n for (const [label, requested, advertised] of pairs) {\n if (requested > advertised) {\n throw adapterError(\n \"incompatible_wasm_build\",\n `${label} exceeds the loaded WASM build capability`,\n );\n }\n }\n}\n\nfunction capabilityProfile(modality: EditableArtifactModality, capabilities: WasmCapabilities) {\n if (modality === \"spreadsheet\") {\n if (!capabilities.collaboration || !capabilities.workbookMetadataQueries) {\n throw adapterError(\n \"incompatible_wasm_build\",\n \"WASM module does not provide the spreadsheet collaboration ABI\",\n );\n }\n return {\n modelSchemaVersion: capabilities.collaborationSnapshotVersion,\n commandVersion: capabilities.spreadsheetCommandVersion,\n maximumSnapshotBytes: capabilities.maxSnapshotBytes,\n maximumCommandBytes: capabilities.maxSpreadsheetCommandBytes,\n maximumQueryBytes: capabilities.maxQueryBytes,\n maximumQueryResponseBytes: capabilities.maxQueryResponseBytes,\n } as const;\n }\n if (modality === \"document\") {\n if (!capabilities.document || !capabilities.documentStatefulSessions) {\n throw adapterError(\n \"incompatible_wasm_build\",\n \"WASM module does not provide the document ABI\",\n );\n }\n return {\n modelSchemaVersion: capabilities.documentSnapshotVersion,\n commandVersion: capabilities.documentCommandVersion,\n maximumSnapshotBytes: capabilities.maxDocumentSnapshotBytes,\n maximumCommandBytes: capabilities.maxDocumentCommandBytes,\n maximumQueryBytes: capabilities.maxDocumentQueryBytes,\n maximumQueryResponseBytes: capabilities.maxDocumentQueryResponseBytes,\n } as const;\n }\n if (!capabilities.presentation || !capabilities.presentationStatefulSessions) {\n throw adapterError(\n \"incompatible_wasm_build\",\n \"WASM module does not provide the presentation ABI\",\n );\n }\n return {\n modelSchemaVersion: capabilities.presentationSnapshotVersion,\n commandVersion: capabilities.presentationCommandVersion,\n maximumSnapshotBytes: capabilities.maxPresentationSnapshotBytes,\n maximumCommandBytes: capabilities.maxPresentationCommandBytes,\n maximumQueryBytes: capabilities.maxPresentationQueryBytes,\n maximumQueryResponseBytes: capabilities.maxPresentationResponseBytes,\n } as const;\n}\n\nfunction classifyProjectionFailure(error: unknown): string | null {\n const message = error instanceof Error ? error.message : \"\";\n const match = /^\\[([A-Z][A-Z0-9_]{0,127})\\]/u.exec(message);\n if (!match) return null;\n switch (match[1]) {\n case \"ARTIFACT_COLLABORATION_REJECTED\":\n return \"structural_conflict\";\n case \"ARTIFACT_PROJECTION_REJECTED\":\n return \"projection_conflict\";\n default:\n return null;\n }\n}\n\nfunction requireInputBytes(value: unknown, label: string, maximumBytes: number): Uint8Array {\n if (!(value instanceof Uint8Array) || value.byteLength === 0) {\n throw adapterError(\"invalid_kernel_input\", `${label} must be non-empty bytes`);\n }\n if (value.byteLength > maximumBytes) {\n throw adapterError(\"limit_exceeded\", `${label} exceeds its byte limit`);\n }\n return value;\n}\n\nfunction requireBoundedBytes(value: unknown, label: string, maximumBytes: number): Uint8Array {\n if (!(value instanceof Uint8Array) || value.byteLength === 0) {\n throw adapterError(\"invalid_kernel_output\", `${label} must be non-empty bytes`);\n }\n if (value.byteLength > maximumBytes) {\n throw adapterError(\"limit_exceeded\", `${label} exceeds its byte limit`);\n }\n return value;\n}\n\n/**\n * Wasm-bindgen returns a fresh Uint8Array. Keep its exact ArrayBuffer when\n * possible so the Worker can transfer it without another large copy; normalize\n * only aliased/subarray outputs from test or custom glue.\n */\nfunction requireOwnedOutput(value: unknown, label: string, maximumBytes: number): Uint8Array {\n const bytes = requireBoundedBytes(value, label, maximumBytes);\n if (\n bytes.buffer instanceof ArrayBuffer &&\n bytes.byteOffset === 0 &&\n bytes.byteLength === bytes.buffer.byteLength\n ) {\n return bytes;\n }\n return bytes.slice();\n}\n\nfunction decodeUtf8(bytes: Uint8Array, label: string): string {\n try {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch (error) {\n throw new ArtifactWorkerProtocolError(\"incompatible_wasm_build\", `${label} is not UTF-8`, {\n cause: error,\n });\n }\n}\n\nfunction callable(\n record: Record<PropertyKey, unknown>,\n key: string,\n): (...args: never[]) => unknown {\n const value = data(record, key);\n if (typeof value !== \"function\") {\n throw adapterError(\"invalid_wasm_module\", `${key} must be a function`);\n }\n return value as (...args: never[]) => unknown;\n}\n\nfunction optionalCallable(\n record: Record<PropertyKey, unknown>,\n key: string,\n): ((...args: never[]) => unknown) | undefined {\n const value = data(record, key, false);\n if (value === undefined) return undefined;\n if (typeof value !== \"function\") {\n throw adapterError(\"invalid_wasm_module\", `${key} must be a function`);\n }\n return value as (...args: never[]) => unknown;\n}\n\nfunction data(record: Record<PropertyKey, unknown>, key: string, required = true): unknown {\n const descriptor = Object.getOwnPropertyDescriptor(record, key);\n // ES module namespace exports are accessor descriptors by specification.\n if (descriptor) return \"value\" in descriptor ? descriptor.value : Reflect.get(record, key);\n if (required) throw adapterError(\"invalid_wasm_module\", `module is missing ${key}`);\n return undefined;\n}\n\nfunction isObject(value: unknown): value is Record<PropertyKey, unknown> {\n return value !== null && (typeof value === \"object\" || typeof value === \"function\");\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nfunction adapterError(code: string, message: string): ArtifactWorkerProtocolError {\n return new ArtifactWorkerProtocolError(code, message);\n}\n\nfunction requireErrorCode(value: unknown, label: string): string {\n if (typeof value !== \"string\" || !/^[a-z][a-z0-9_]{0,127}$/u.test(value)) {\n throw adapterError(\"invalid_wasm_module\", `${label} is invalid`);\n }\n return value;\n}\n\nfunction positiveInteger(value: unknown, label: string): number {\n if (!Number.isSafeInteger(value) || (value as number) <= 0) {\n throw adapterError(\"incompatible_wasm_build\", `${label} must be a positive safe integer`);\n }\n return value as number;\n}\n\nfunction strictBoolean(value: unknown, label: string): boolean {\n if (typeof value !== \"boolean\") {\n throw adapterError(\"incompatible_wasm_build\", `${label} must be a boolean`);\n }\n return value;\n}\n","import {\n EDITABLE_ARTIFACT_INTENT_MAX_BYTES,\n EDITABLE_ARTIFACT_INTENT_VERSION,\n assertCanonicalSpreadsheetArtifactCommandBytes,\n decodeEditableArtifactMutationIntent,\n hashEditableArtifactMutationIntent,\n} from \"@opengeni/contracts/editable-artifacts\";\nimport { decodeCommittedTransactionSummary } from \"@opengeni/contracts/editable-artifact-committed-transaction\";\nimport { editableArtifactCodecFor } from \"@opengeni/contracts/editable-artifact-codec-registry\";\nimport { decodeEditableArtifactSerializedCommit } from \"@opengeni/contracts/editable-artifact-serialized-commit\";\nimport type {\n EditableArtifactBlockedPending,\n EditableArtifactCausalFrontier,\n EditableArtifactCommittedTransaction,\n EditableArtifactPendingTransaction,\n} from \"../types\";\nimport type {\n ArtifactWorkerKernelAdapter,\n ArtifactWorkerKernelAdapterFactory,\n ArtifactWorkerKernelSession,\n} from \"./kernel-adapter\";\nimport { ArtifactWorkerPendingProjectionError } from \"./kernel-adapter\";\nimport {\n ArtifactWorkerProtocolError,\n ArtifactWorkerRpcKind,\n decodeArtifactWorkerRpcMessage,\n encodeArtifactWorkerRpcMessage,\n transferListForArtifactWorkerRpcMessage,\n type ArtifactWorkerRpcLimits,\n type ArtifactWorkerRpcMessage,\n} from \"./rpc-protocol\";\nimport {\n decodeAuthorPendingMetadata,\n decodeCommittedMetadata,\n decodeInitialize,\n decodePendingListMetadata,\n decodeReconcileMetadata,\n decodeSnapshotMetadata,\n encodeErrorPayload,\n encodePendingListMetadata,\n encodeProjectionResponse,\n encodeStateResponse,\n requireMatchingHash,\n sha256Hex,\n type ArtifactWorkerAuthorPendingInput,\n type ArtifactWorkerInitializeInput,\n} from \"./wire-codec\";\n\nexport type ArtifactWorkerMessageEvent = { data: unknown };\n\nexport type ArtifactWorkerRuntimeEndpoint = {\n addEventListener: (\n type: \"message\",\n listener: (event: ArtifactWorkerMessageEvent) => void,\n ) => void;\n removeEventListener: (\n type: \"message\",\n listener: (event: ArtifactWorkerMessageEvent) => void,\n ) => void;\n postMessage: (message: ArtifactWorkerRpcMessage, transfer: Transferable[]) => void;\n};\n\nexport type InstallArtifactWorkerRuntimeOptions = {\n endpoint: ArtifactWorkerRuntimeEndpoint;\n loadAdapter: ArtifactWorkerKernelAdapterFactory;\n rpcLimits?: Readonly<ArtifactWorkerRpcLimits>;\n onProtocolError?: (error: ArtifactWorkerProtocolError) => void;\n};\n\ntype InstalledStateCommon = {\n artifactId: string;\n sequence: number;\n protocolVersion: number;\n kernelVersion: string;\n modelSchemaVersion: number;\n stateHash: string;\n};\n\ntype InstalledState = InstalledStateCommon &\n (\n | { modality: \"spreadsheet\"; causalFrontier: EditableArtifactCausalFrontier }\n | { modality: \"document\" | \"presentation\"; nativeRevision: number }\n );\n\nconst MAX_KNOWN_REQUESTS = 64;\nconst MAX_QUEUED_REQUEST_BYTES = 192 * 1024 * 1024;\nconst MAX_PENDING_AGGREGATE_BYTES = 64 * 1024 * 1024;\n\n/** Owns all mutable artifact/WASM state inside one dedicated Worker. */\nexport class ArtifactWorkerRuntime {\n private readonly endpoint: ArtifactWorkerRuntimeEndpoint;\n private readonly loadAdapter: ArtifactWorkerKernelAdapterFactory;\n private readonly rpcLimits: Readonly<ArtifactWorkerRpcLimits> | undefined;\n private readonly onProtocolError: ((error: ArtifactWorkerProtocolError) => void) | undefined;\n private readonly cancelled = new Set<number>();\n private readonly knownRequests = new Map<number, { bytes: number; generation: number }>();\n private queuedRequestBytes = 0;\n private queue: Promise<void> = Promise.resolve();\n private generation: number | null = null;\n private initialization: ArtifactWorkerInitializeInput | null = null;\n private adapter: ArtifactWorkerKernelAdapter | null = null;\n private confirmed: ArtifactWorkerKernelSession | null = null;\n private speculative: ArtifactWorkerKernelSession | null = null;\n private installed: InstalledState | null = null;\n private pendingKeys: readonly string[] = Object.freeze([]);\n private blockedPending: readonly EditableArtifactBlockedPending[] = Object.freeze([]);\n private disposed = false;\n\n private readonly onMessage = (event: ArtifactWorkerMessageEvent): void => {\n if (this.disposed) return;\n let frame;\n try {\n frame = decodeArtifactWorkerRpcMessage(event.data, this.rpcLimits);\n } catch (error) {\n const failure = asProtocolError(error);\n this.reportProtocolError(failure);\n return;\n }\n if (frame.kind === ArtifactWorkerRpcKind.Cancel) {\n if (\n frame.flags === 0 &&\n frame.metadata.byteLength === 0 &&\n frame.segments.length === 0 &&\n this.knownRequests.get(frame.requestId)?.generation === frame.generation\n ) {\n this.cancelled.add(frame.requestId);\n }\n return;\n }\n if (frame.flags !== 0) {\n this.reportProtocolError(runtimeError(\"noncanonical\", \"unknown RPC flags are set\"));\n return;\n }\n if (this.knownRequests.has(frame.requestId)) {\n this.reportProtocolError(runtimeError(\"duplicate_request\", \"RPC request id is duplicated\"));\n return;\n }\n const requestBytes = retainedFrameBytes(frame);\n if (\n this.knownRequests.size >= MAX_KNOWN_REQUESTS ||\n this.queuedRequestBytes + requestBytes > MAX_QUEUED_REQUEST_BYTES\n ) {\n this.respondError(\n frame.requestId,\n runtimeError(\"request_limit\", \"artifact Worker request queue is full\"),\n frame.generation,\n );\n return;\n }\n this.knownRequests.set(frame.requestId, { bytes: requestBytes, generation: frame.generation });\n this.queuedRequestBytes += requestBytes;\n this.queue = this.queue\n .then(() => this.dispatch(frame))\n .catch((error: unknown) => this.reportProtocolError(asProtocolError(error)));\n };\n\n constructor(options: InstallArtifactWorkerRuntimeOptions) {\n this.endpoint = options.endpoint;\n this.loadAdapter = options.loadAdapter;\n this.rpcLimits = options.rpcLimits;\n this.onProtocolError = options.onProtocolError;\n this.endpoint.addEventListener(\"message\", this.onMessage);\n }\n\n async dispose(): Promise<void> {\n if (this.disposed) return;\n this.disposed = true;\n this.endpoint.removeEventListener(\"message\", this.onMessage);\n await this.queue.catch(() => {});\n this.releaseState();\n this.disposeAdapter(this.adapter);\n this.adapter = null;\n this.cancelled.clear();\n this.knownRequests.clear();\n this.queuedRequestBytes = 0;\n }\n\n private async dispatch(frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>): Promise<void> {\n try {\n if (frame.kind === ArtifactWorkerRpcKind.Initialize) {\n await this.initialize(frame);\n return;\n }\n this.requireInitialized(frame.generation);\n this.throwIfCancelled(frame.requestId);\n switch (frame.kind) {\n case ArtifactWorkerRpcKind.Reset:\n this.requireNoPayload(frame);\n this.releaseState();\n this.respond(frame.requestId);\n return;\n case ArtifactWorkerRpcKind.LoadSnapshot:\n await this.loadSnapshot(frame);\n return;\n case ArtifactWorkerRpcKind.ApplyRecovered:\n await this.applyRecovered(frame);\n return;\n case ArtifactWorkerRpcKind.ReconcileCommitted:\n await this.reconcileCommitted(frame);\n return;\n case ArtifactWorkerRpcKind.ReplacePending:\n await this.replacePending(frame);\n return;\n case ArtifactWorkerRpcKind.AuthorPending:\n await this.authorPending(frame);\n return;\n case ArtifactWorkerRpcKind.QuerySpreadsheet:\n this.queryArtifact(frame);\n return;\n case ArtifactWorkerRpcKind.Dispose:\n this.requireNoPayload(frame);\n this.releaseState();\n this.disposeAdapter(this.adapter);\n this.adapter = null;\n this.respond(frame.requestId);\n return;\n default:\n throw runtimeError(\"unknown_request\", `worker cannot execute RPC kind ${frame.kind}`);\n }\n } catch (error) {\n this.respondError(frame.requestId, error, frame.generation);\n } finally {\n this.cancelled.delete(frame.requestId);\n const retainedBytes = this.knownRequests.get(frame.requestId)?.bytes ?? 0;\n this.knownRequests.delete(frame.requestId);\n this.queuedRequestBytes -= retainedBytes;\n }\n }\n\n private async initialize(\n frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>,\n ): Promise<void> {\n if (this.generation !== null || this.adapter !== null) {\n throw runtimeError(\"already_initialized\", \"artifact Worker is already initialized\");\n }\n if (frame.segments.length !== 0)\n throw runtimeError(\"invalid_segment\", \"initialize has no segments\");\n const initialization = decodeInitialize(frame.metadata);\n this.throwIfCancelled(frame.requestId);\n let adapter: ArtifactWorkerKernelAdapter | null = null;\n try {\n adapter = await this.loadAdapter(initialization);\n this.throwIfCancelled(frame.requestId);\n } catch (error) {\n this.disposeAdapter(adapter);\n throw error;\n }\n assertAdapterCompatibility(adapter, initialization);\n this.generation = frame.generation;\n this.initialization = initialization;\n this.adapter = adapter;\n this.respond(frame.requestId);\n }\n\n private async loadSnapshot(\n frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>,\n ): Promise<void> {\n const initialization = this.requireInitialization();\n const adapter = this.requireAdapter();\n if (frame.segments.length !== 1)\n throw runtimeError(\"invalid_segment\", \"snapshot requires one segment\");\n const ownedBytes = requireBytesWithin(\n frame.segments[0]!,\n initialization.maximumSnapshotBytes,\n \"snapshot\",\n );\n const snapshot = decodeSnapshotMetadata(frame.metadata, ownedBytes);\n if (\n snapshot.modality !== initialization.modality ||\n snapshot.modality !== adapter.modality ||\n (snapshot.modality === \"spreadsheet\" &&\n snapshot.protocolVersion !== adapter.protocolVersion) ||\n snapshot.kernelVersion !== adapter.kernelVersion ||\n snapshot.modelSchemaVersion !== adapter.modelSchemaVersion\n ) {\n throw runtimeError(\n \"unsupported_protocol\",\n \"snapshot protocol/kernel/schema is incompatible with the loaded collaboration kernel\",\n );\n }\n const digest = await sha256Hex(ownedBytes);\n this.throwIfCancelled(frame.requestId);\n requireMatchingHash(digest, snapshot.digest, \"snapshot digest\");\n const canonical = requireBytesWithin(\n adapter.canonicalizeSnapshot(ownedBytes),\n initialization.maximumSnapshotBytes,\n \"canonical snapshot\",\n );\n if (!bytesEqual(canonical, ownedBytes)) {\n throw runtimeError(\n \"noncanonical_snapshot\",\n \"server snapshot bytes are not canonical; refusing to persist a different model\",\n );\n }\n const nextConfirmed = adapter.open(canonical);\n let nextSpeculative: ArtifactWorkerKernelSession | null = null;\n let stateHash: string;\n try {\n stateHash = await nextConfirmed.stateHash();\n this.throwIfCancelled(frame.requestId);\n requireMatchingHash(stateHash, snapshot.stateHash, \"snapshot state\");\n if (\n snapshot.modality !== \"spreadsheet\" &&\n nextConfirmed.nativeRevision() !== snapshot.nativeRevision\n ) {\n throw runtimeError(\n \"kernel_diverged\",\n \"serialized snapshot native revision does not match the WASM session\",\n );\n }\n nextSpeculative = nextConfirmed.fork();\n this.throwIfCancelled(frame.requestId);\n } catch (error) {\n this.disposeSession(nextConfirmed);\n this.disposeSession(nextSpeculative);\n throw error;\n }\n if (!nextSpeculative) throw runtimeError(\"kernel_failed\", \"kernel fork was not created\");\n this.installSessions(\n nextConfirmed,\n nextSpeculative,\n snapshot.modality === \"spreadsheet\"\n ? {\n artifactId: snapshot.artifactId,\n modality: \"spreadsheet\",\n sequence: snapshot.sequence,\n protocolVersion: snapshot.protocolVersion,\n kernelVersion: snapshot.kernelVersion,\n modelSchemaVersion: snapshot.modelSchemaVersion,\n stateHash,\n causalFrontier: snapshot.causalFrontier,\n }\n : {\n artifactId: snapshot.artifactId,\n modality: snapshot.modality,\n sequence: snapshot.sequence,\n protocolVersion: adapter.protocolVersion,\n kernelVersion: snapshot.kernelVersion,\n modelSchemaVersion: snapshot.modelSchemaVersion,\n stateHash,\n nativeRevision: snapshot.nativeRevision,\n },\n Object.freeze([]),\n Object.freeze([]),\n );\n this.respond(frame.requestId, encodeStateResponse(stateHash, digest));\n }\n\n private async applyRecovered(\n frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>,\n ): Promise<void> {\n const initialization = this.requireInitialization();\n if (frame.segments.length !== 1) {\n throw runtimeError(\"invalid_segment\", \"recovered transaction requires one operation segment\");\n }\n const committedTransactionBytes = requireBytesWithin(\n frame.segments[0]!,\n initialization.maximumCommittedTransactionBytes,\n \"committed transaction\",\n );\n const transaction = decodeCommittedMetadata(frame.metadata, committedTransactionBytes);\n const result = await this.buildCommittedCandidate(transaction, [], frame.requestId);\n this.installCommittedCandidate(result, transaction, []);\n this.respond(frame.requestId, encodeStateResponse(result.stateHash));\n }\n\n private async reconcileCommitted(\n frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>,\n ): Promise<void> {\n const initialization = this.requireInitialization();\n const decoded = decodeReconcileMetadata(\n frame.metadata,\n frame.segments,\n initialization.maximumPendingTransactions,\n );\n requireBytesWithin(\n decoded.committed.committedTransactionBytes,\n initialization.maximumCommittedTransactionBytes,\n \"committed transaction\",\n );\n await this.validatePending(decoded.pending);\n const result = await this.buildCommittedCandidate(\n decoded.committed,\n decoded.pending,\n frame.requestId,\n );\n this.installCommittedCandidate(result, decoded.committed, decoded.pending);\n this.respond(\n frame.requestId,\n encodeProjectionResponse(result.blockedPending, result.stateHash),\n );\n }\n\n private async replacePending(\n frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>,\n ): Promise<void> {\n const initialization = this.requireInitialization();\n const pending = decodePendingListMetadata(\n frame.metadata,\n frame.segments,\n initialization.maximumPendingTransactions,\n );\n await this.validatePending(pending);\n const keys = pending.map(pendingKey);\n if (arraysEqual(keys, this.pendingKeys)) {\n this.respond(frame.requestId, encodeProjectionResponse(this.blockedPending));\n return;\n }\n const candidate = this.requireConfirmed().fork();\n let blockedPending: readonly EditableArtifactBlockedPending[];\n try {\n blockedPending = this.applyPending(candidate, pending, frame.requestId);\n this.throwIfCancelled(frame.requestId);\n } catch (error) {\n this.disposeSession(candidate);\n throw error;\n }\n const previous = this.speculative;\n this.speculative = candidate;\n this.pendingKeys = Object.freeze(keys);\n this.blockedPending = blockedPending;\n this.disposeSession(previous);\n this.respond(frame.requestId, encodeProjectionResponse(blockedPending));\n }\n\n private async authorPending(\n frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>,\n ): Promise<void> {\n const initialization = this.requireInitialization();\n const adapter = this.requireAdapter();\n if (frame.segments.length !== 1)\n throw runtimeError(\"invalid_segment\", \"author requires one command segment\");\n const commandBytes = requireBytesWithin(\n frame.segments[0]!,\n initialization.maximumCommandBytes,\n \"pending command\",\n );\n const input = decodeAuthorPendingMetadata(frame.metadata, commandBytes);\n if (\n input.modality !== initialization.modality ||\n input.modality !== adapter.modality ||\n input.protocolVersion !== adapter.protocolVersion ||\n input.kernelVersion !== adapter.kernelVersion ||\n input.modelSchemaVersion !== adapter.modelSchemaVersion ||\n input.commandVersion !== adapter.commandVersion\n ) {\n throw runtimeError(\n \"unsupported_protocol\",\n \"pending authoring versions are incompatible with the loaded kernel\",\n );\n }\n if (this.installed && input.artifactId !== this.installed.artifactId) {\n throw runtimeError(\"artifact_mismatch\", \"pending transaction belongs to another artifact\");\n }\n try {\n if (input.modality === \"spreadsheet\") {\n assertCanonicalSpreadsheetArtifactCommandBytes(commandBytes);\n } else {\n editableArtifactCodecFor({\n durableModality: input.modality,\n modelSchemaVersion: input.modelSchemaVersion,\n commandProtocolVersion: input.commandVersion,\n }).command.assertCanonical(commandBytes);\n }\n } catch (error) {\n throw runtimeError(\n \"noncanonical_command\",\n `pending ${input.modality} command must be canonical before it receives an identity: ${\n error instanceof Error ? error.message : \"invalid command\"\n }`,\n );\n }\n const canonicalCommand = commandBytes;\n const authored = authorCanonicalPendingIntent(input, canonicalCommand);\n const intentBytes = requireBytesWithin(\n authored.bytes,\n EDITABLE_ARTIFACT_INTENT_MAX_BYTES,\n \"OGATX001 intent\",\n );\n this.throwIfCancelled(frame.requestId);\n const commonPending = {\n artifactId: input.artifactId,\n clientTransactionId: input.clientTransactionId,\n requestHash: authored.requestHash,\n protocolVersion: input.protocolVersion,\n modelSchemaVersion: input.modelSchemaVersion,\n commandVersion: input.commandVersion,\n replicaId: input.replicaId,\n replicaCounter: input.replicaCounter,\n previousLocalTransactionId: input.previousLocalTransactionId,\n observedHeadSequence: input.observedHeadSequence,\n commandBytes: canonicalCommand,\n intentBytes,\n createdAt: input.createdAt,\n } as const;\n let pending: EditableArtifactPendingTransaction;\n if (input.modality === \"spreadsheet\") {\n pending = Object.freeze({\n ...commonPending,\n modality: \"spreadsheet\",\n causalBase: input.causalBase ?? [],\n selectiveUndoTargets: input.selectiveUndoTargets ?? [],\n });\n } else {\n const installed = this.requireInstalled();\n if (installed.modality !== input.modality) {\n throw runtimeError(\"modality_mismatch\", \"pending modality does not match installed state\");\n }\n const expectedHeadSequence = installed.sequence + this.pendingKeys.length;\n if (input.observedHeadSequence !== expectedHeadSequence) {\n throw runtimeError(\n \"serialized_head_conflict\",\n \"serialized pending command was not authored over the speculative head\",\n );\n }\n pending = Object.freeze({\n ...commonPending,\n modality: input.modality,\n observedNativeRevision: this.requireSpeculative().nativeRevision(),\n });\n }\n const metadata = encodePendingListMetadata([pending]);\n // Both buffers are exclusively Worker-owned here: the command arrived by\n // transfer and OGATX authoring allocated the intent. Return them without a\n // second multi-megabyte copy.\n const command = transferableOwnedBuffer(canonicalCommand);\n const intent = transferableOwnedBuffer(intentBytes);\n this.respond(frame.requestId, metadata, [command, intent]);\n }\n\n private queryArtifact(frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>): void {\n if (frame.metadata.byteLength !== 0 || frame.segments.length !== 1) {\n throw runtimeError(\"invalid_segment\", \"artifact query requires one byte segment\");\n }\n const initialization = this.requireInitialization();\n const queryBytes = requireBytesWithin(\n frame.segments[0]!,\n initialization.maximumQueryBytes,\n `${initialization.modality} query`,\n );\n const result = requireBytesWithin(\n this.requireSpeculative().query(queryBytes),\n initialization.maximumQueryResponseBytes,\n `${initialization.modality} projection`,\n );\n this.throwIfCancelled(frame.requestId);\n this.respond(frame.requestId, undefined, [transferableOwnedBuffer(result)]);\n }\n\n private async buildCommittedCandidate(\n transaction: EditableArtifactCommittedTransaction,\n remainingPending: readonly EditableArtifactPendingTransaction[],\n requestId: number,\n ): Promise<{\n confirmed: ArtifactWorkerKernelSession;\n speculative: ArtifactWorkerKernelSession;\n stateHash: string;\n blockedPending: readonly EditableArtifactBlockedPending[];\n }> {\n const installed = this.requireInstalled();\n if (transaction.artifactId !== installed.artifactId) {\n throw runtimeError(\"artifact_mismatch\", \"committed transaction belongs to another artifact\");\n }\n if (transaction.modality !== installed.modality) {\n throw runtimeError(\"modality_mismatch\", \"committed transaction modality is incompatible\");\n }\n if (\n transaction.modality === \"spreadsheet\" &&\n transaction.protocolVersion !== installed.protocolVersion\n )\n throw runtimeError(\"unsupported_protocol\", \"committed transaction protocol is incompatible\");\n if (transaction.startSequence !== installed.sequence + 1) {\n throw runtimeError(\"invalid_sequence\", \"committed transaction is not contiguous\");\n }\n assertCommittedEnvelopeMatchesOuter(transaction);\n if (transaction.modality === \"spreadsheet\" && installed.modality === \"spreadsheet\") {\n requireFrontierAdvance(installed.causalFrontier, transaction.causalFrontier);\n } else if (transaction.modality !== \"spreadsheet\" && installed.modality !== \"spreadsheet\") {\n if (transaction.priorNativeRevision !== installed.nativeRevision) {\n throw runtimeError(\"invalid_revision\", \"serialized commit prior revision is not current\");\n }\n }\n requireMatchingHash(installed.stateHash, transaction.priorStateHash, \"transaction prior state\");\n const nextConfirmed = this.requireConfirmed().fork();\n let nextSpeculative: ArtifactWorkerKernelSession | null = null;\n try {\n if (transaction.modality === \"spreadsheet\") {\n nextConfirmed.applyCommitted(transaction.committedTransactionBytes);\n } else {\n const summary = decodeEditableArtifactSerializedCommit(\n transaction.committedTransactionBytes,\n transaction.modality,\n );\n const intent = decodeEditableArtifactMutationIntent(summary.intentBytes);\n const nativeReceipt = nextConfirmed.applyCommands(intent.commandBytes);\n if (!bytesEqual(nativeReceipt, summary.nativeReceiptBytes)) {\n throw runtimeError(\n \"kernel_diverged\",\n \"WASM native receipt differs from the exact durable OGAST receipt\",\n );\n }\n if (nextConfirmed.nativeRevision() !== transaction.nativeRevision) {\n throw runtimeError(\n \"kernel_diverged\",\n \"WASM native revision differs from the exact durable OGAST revision\",\n );\n }\n }\n const stateHash = await nextConfirmed.stateHash();\n this.throwIfCancelled(requestId);\n requireMatchingHash(stateHash, transaction.stateHash, \"committed state\");\n nextSpeculative = nextConfirmed.fork();\n const blockedPending = this.applyPending(\n nextSpeculative,\n remainingPending,\n requestId,\n transaction.endSequence,\n );\n this.throwIfCancelled(requestId);\n return {\n confirmed: nextConfirmed,\n speculative: nextSpeculative,\n stateHash,\n blockedPending,\n };\n } catch (error) {\n this.disposeSession(nextConfirmed);\n this.disposeSession(nextSpeculative);\n throw error;\n }\n }\n\n private installCommittedCandidate(\n candidate: {\n confirmed: ArtifactWorkerKernelSession;\n speculative: ArtifactWorkerKernelSession;\n stateHash: string;\n blockedPending: readonly EditableArtifactBlockedPending[];\n },\n transaction: EditableArtifactCommittedTransaction,\n pending: readonly EditableArtifactPendingTransaction[],\n ): void {\n const installed = this.requireInstalled();\n this.installSessions(\n candidate.confirmed,\n candidate.speculative,\n transaction.modality === \"spreadsheet\"\n ? {\n ...installed,\n modality: \"spreadsheet\",\n sequence: transaction.endSequence,\n stateHash: candidate.stateHash,\n causalFrontier: transaction.causalFrontier,\n }\n : {\n ...installed,\n modality: transaction.modality,\n sequence: transaction.endSequence,\n stateHash: candidate.stateHash,\n nativeRevision: transaction.nativeRevision,\n },\n Object.freeze(pending.map(pendingKey)),\n candidate.blockedPending,\n );\n }\n\n private applyPending(\n session: ArtifactWorkerKernelSession,\n pending: readonly EditableArtifactPendingTransaction[],\n requestId: number,\n baseSequence = this.requireInstalled().sequence,\n ): readonly EditableArtifactBlockedPending[] {\n const blocked: EditableArtifactBlockedPending[] = [];\n const blockedIds = new Set<string>();\n for (const transaction of pending) {\n this.throwIfCancelled(requestId);\n if (\n transaction.previousLocalTransactionId !== null &&\n blockedIds.has(transaction.previousLocalTransactionId)\n ) {\n blockedIds.add(transaction.clientTransactionId);\n blocked.push(\n Object.freeze({\n clientTransactionId: transaction.clientTransactionId,\n code: \"blocked_predecessor\",\n }),\n );\n continue;\n }\n try {\n if (transaction.modality === \"spreadsheet\") {\n session.applyPending(transaction.intentBytes);\n } else {\n if (\n transaction.observedHeadSequence !== baseSequence ||\n transaction.observedNativeRevision !== session.nativeRevision()\n ) {\n throw new ArtifactWorkerPendingProjectionError(\n \"serialized_head_conflict\",\n \"serialized pending transaction is stale\",\n );\n }\n session.applyCommands(transaction.commandBytes);\n baseSequence += 1;\n }\n } catch (error) {\n if (!(error instanceof ArtifactWorkerPendingProjectionError)) throw error;\n blockedIds.add(transaction.clientTransactionId);\n blocked.push(\n Object.freeze({ clientTransactionId: transaction.clientTransactionId, code: error.code }),\n );\n }\n }\n return Object.freeze(blocked);\n }\n\n private async validatePending(\n pending: readonly EditableArtifactPendingTransaction[],\n ): Promise<void> {\n const initialization = this.requireInitialization();\n const installed = this.requireInstalled();\n const adapter = this.requireAdapter();\n const ids = new Set<string>();\n let aggregateBytes = 0;\n for (const transaction of pending) {\n if (transaction.artifactId !== installed.artifactId) {\n throw runtimeError(\"artifact_mismatch\", \"pending transaction belongs to another artifact\");\n }\n if (transaction.modality !== installed.modality) {\n throw runtimeError(\"modality_mismatch\", \"pending transaction modality is incompatible\");\n }\n if (\n transaction.protocolVersion !== installed.protocolVersion ||\n transaction.modelSchemaVersion !== installed.modelSchemaVersion ||\n transaction.commandVersion !== adapter.commandVersion\n ) {\n throw runtimeError(\n \"unsupported_protocol\",\n \"pending transaction versions are incompatible with confirmed state\",\n );\n }\n if (ids.has(transaction.clientTransactionId)) {\n throw runtimeError(\"duplicate_transaction\", \"pending transaction id is duplicated\");\n }\n ids.add(transaction.clientTransactionId);\n requireBytesWithin(\n transaction.commandBytes,\n initialization.maximumCommandBytes,\n \"pending command\",\n );\n requireBytesWithin(\n transaction.intentBytes,\n initialization.maximumIntentBytes,\n \"pending intent\",\n );\n try {\n if (transaction.modality === \"spreadsheet\") {\n assertCanonicalSpreadsheetArtifactCommandBytes(transaction.commandBytes);\n } else {\n editableArtifactCodecFor({\n durableModality: transaction.modality,\n modelSchemaVersion: transaction.modelSchemaVersion,\n commandProtocolVersion: transaction.commandVersion,\n }).command.assertCanonical(transaction.commandBytes);\n }\n } catch (error) {\n throw new ArtifactWorkerProtocolError(\n \"noncanonical_command\",\n `pending transaction contains noncanonical ${transaction.modality} command bytes`,\n { cause: error },\n );\n }\n verifyCanonicalPendingIntent(transaction);\n aggregateBytes += transaction.commandBytes.byteLength + transaction.intentBytes.byteLength;\n if (!Number.isSafeInteger(aggregateBytes) || aggregateBytes > MAX_PENDING_AGGREGATE_BYTES) {\n throw runtimeError(\"limit_exceeded\", \"pending commands exceed their aggregate byte limit\");\n }\n }\n }\n\n private installSessions(\n confirmed: ArtifactWorkerKernelSession,\n speculative: ArtifactWorkerKernelSession,\n installed: InstalledState,\n pendingKeys: readonly string[],\n blockedPending: readonly EditableArtifactBlockedPending[],\n ): void {\n const previousConfirmed = this.confirmed;\n const previousSpeculative = this.speculative;\n this.confirmed = confirmed;\n this.speculative = speculative;\n this.installed = Object.freeze(installed);\n this.pendingKeys = pendingKeys;\n this.blockedPending = blockedPending;\n this.disposeSession(previousConfirmed);\n this.disposeSession(previousSpeculative);\n }\n\n private releaseState(): void {\n const confirmed = this.confirmed;\n const speculative = this.speculative;\n this.confirmed = null;\n this.speculative = null;\n this.installed = null;\n this.pendingKeys = Object.freeze([]);\n this.blockedPending = Object.freeze([]);\n this.disposeSession(confirmed);\n this.disposeSession(speculative);\n }\n\n private disposeSession(session: ArtifactWorkerKernelSession | null): void {\n if (!session) return;\n try {\n session.dispose();\n } catch (error) {\n this.reportProtocolError(asProtocolError(error));\n }\n }\n\n private disposeAdapter(adapter: ArtifactWorkerKernelAdapter | null): void {\n if (!adapter?.dispose) return;\n try {\n adapter.dispose();\n } catch (error) {\n this.reportProtocolError(asProtocolError(error));\n }\n }\n\n private reportProtocolError(error: ArtifactWorkerProtocolError): void {\n try {\n this.onProtocolError?.(error);\n } catch {\n // Diagnostics must never acquire authority over Worker state or cleanup.\n }\n }\n\n private requireNoPayload(frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>): void {\n if (frame.metadata.byteLength !== 0 || frame.segments.length !== 0) {\n throw runtimeError(\"unexpected_payload\", \"RPC operation must not contain a payload\");\n }\n }\n\n private requireInitialized(generation: number): void {\n if (this.generation === null || this.adapter === null || this.initialization === null) {\n throw runtimeError(\"not_initialized\", \"artifact Worker is not initialized\");\n }\n if (generation !== this.generation) {\n throw runtimeError(\"stale_generation\", \"RPC belongs to a retired Worker generation\");\n }\n }\n\n private requireInitialization(): ArtifactWorkerInitializeInput {\n if (!this.initialization)\n throw runtimeError(\"not_initialized\", \"artifact Worker is not initialized\");\n return this.initialization;\n }\n\n private requireAdapter(): ArtifactWorkerKernelAdapter {\n if (!this.adapter) throw runtimeError(\"not_initialized\", \"artifact Worker is not initialized\");\n return this.adapter;\n }\n\n private requireConfirmed(): ArtifactWorkerKernelSession {\n if (!this.confirmed)\n throw runtimeError(\"snapshot_required\", \"artifact Worker has no confirmed state\");\n return this.confirmed;\n }\n\n private requireSpeculative(): ArtifactWorkerKernelSession {\n if (!this.speculative) {\n throw runtimeError(\"snapshot_required\", \"artifact Worker has no speculative state\");\n }\n return this.speculative;\n }\n\n private requireInstalled(): InstalledState {\n if (!this.installed)\n throw runtimeError(\"snapshot_required\", \"artifact Worker has no installed snapshot\");\n return this.installed;\n }\n\n private throwIfCancelled(requestId: number): void {\n if (this.cancelled.has(requestId))\n throw runtimeError(\"cancelled\", \"artifact Worker request was cancelled\");\n }\n\n private respond(requestId: number, metadata?: Uint8Array, segments?: ArrayBuffer[]): void {\n if (this.generation === null || this.cancelled.has(requestId)) return;\n const response = encodeArtifactWorkerRpcMessage({\n kind: ArtifactWorkerRpcKind.Response,\n generation: this.generation,\n requestId,\n ...(metadata ? { metadata } : {}),\n ...(segments ? { segments } : {}),\n ...(this.rpcLimits ? { limits: this.rpcLimits } : {}),\n });\n this.endpoint.postMessage(response, transferListForArtifactWorkerRpcMessage(response));\n }\n\n private respondError(requestId: number, error: unknown, generation = this.generation): void {\n if (generation === null || this.cancelled.has(requestId)) return;\n const failure = asWorkerFailure(error);\n const response = encodeArtifactWorkerRpcMessage({\n kind: ArtifactWorkerRpcKind.Error,\n generation,\n requestId,\n metadata: encodeErrorPayload(failure),\n ...(this.rpcLimits ? { limits: this.rpcLimits } : {}),\n });\n this.endpoint.postMessage(response, transferListForArtifactWorkerRpcMessage(response));\n }\n}\n\nfunction authorCanonicalPendingIntent(\n input: ArtifactWorkerAuthorPendingInput,\n canonicalCommand: Uint8Array,\n): { bytes: Uint8Array; requestHash: string } {\n try {\n return hashEditableArtifactMutationIntent(canonicalMutationIntent(input, canonicalCommand));\n } catch (error) {\n throw new ArtifactWorkerProtocolError(\n \"invalid_intent\",\n \"pending transaction cannot be represented by canonical OGATX001\",\n { cause: error },\n );\n }\n}\n\nfunction transferableOwnedBuffer(bytes: Uint8Array): ArrayBuffer {\n if (\n bytes.buffer instanceof ArrayBuffer &&\n bytes.byteOffset === 0 &&\n bytes.byteLength === bytes.buffer.byteLength\n ) {\n return bytes.buffer;\n }\n return bytes.slice().buffer;\n}\n\nfunction verifyCanonicalPendingIntent(transaction: EditableArtifactPendingTransaction): void {\n let expected: { bytes: Uint8Array; requestHash: string };\n try {\n expected = hashEditableArtifactMutationIntent(\n canonicalMutationIntent(transaction, transaction.commandBytes),\n );\n } catch (error) {\n throw new ArtifactWorkerProtocolError(\n \"intent_mismatch\",\n \"pending transaction metadata is not valid canonical OGATX001 input\",\n { cause: error },\n );\n }\n if (\n expected.requestHash !== transaction.requestHash ||\n !bytesEqual(expected.bytes, transaction.intentBytes)\n ) {\n throw runtimeError(\n \"intent_mismatch\",\n \"pending transaction bytes do not bind its exact metadata and command\",\n );\n }\n}\n\nfunction assertAdapterCompatibility(\n adapter: ArtifactWorkerKernelAdapter,\n initialization: ArtifactWorkerInitializeInput,\n): void {\n if (adapter.modality !== initialization.modality) {\n throw runtimeError(\"modality_mismatch\", \"loaded kernel modality does not match initialization\");\n }\n if (\n adapter.kernelVersion !== initialization.kernelVersion ||\n adapter.protocolVersion !== initialization.protocolVersion ||\n adapter.modelSchemaVersion !== initialization.modelSchemaVersion ||\n adapter.commandVersion !== initialization.commandVersion\n ) {\n throw runtimeError(\n \"runtime_identity_mismatch\",\n \"loaded kernel build/protocol/model identity does not match its package\",\n );\n }\n const limits = [\n [adapter.maximumSnapshotBytes, initialization.maximumSnapshotBytes, \"snapshot\"],\n [adapter.maximumCommandBytes, initialization.maximumCommandBytes, \"command\"],\n [adapter.maximumIntentBytes, initialization.maximumIntentBytes, \"intent\"],\n [\n adapter.maximumCommittedTransactionBytes,\n initialization.maximumCommittedTransactionBytes,\n \"committed transaction\",\n ],\n [adapter.maximumQueryBytes, initialization.maximumQueryBytes, \"query\"],\n [adapter.maximumQueryResponseBytes, initialization.maximumQueryResponseBytes, \"query response\"],\n ] as const;\n for (const [advertised, requested, label] of limits) {\n if (advertised < requested) {\n throw runtimeError(\n \"unsupported_protocol\",\n `loaded collaboration kernel ${label} limit is below the requested Worker limit`,\n );\n }\n }\n}\n\n/**\n * Outer delivery/index fields remain useful for storage and routing, but every\n * semantic field duplicated by OGACO must agree exactly before Rust sees it.\n */\nfunction assertCommittedEnvelopeMatchesOuter(\n transaction: EditableArtifactCommittedTransaction,\n): void {\n if (transaction.modality !== \"spreadsheet\") {\n let summary: ReturnType<typeof decodeEditableArtifactSerializedCommit>;\n try {\n summary = decodeEditableArtifactSerializedCommit(\n transaction.committedTransactionBytes,\n transaction.modality,\n );\n } catch (error) {\n throw new ArtifactWorkerProtocolError(\n \"invalid_committed_transaction\",\n \"committed transaction is not canonical OGAST001\",\n { cause: error },\n );\n }\n if (\n summary.commitProtocolVersion !== transaction.commitProtocolVersion ||\n summary.transactionId !== transaction.transactionId ||\n summary.requestHash !== transaction.requestHash ||\n summary.parentHeadSequence + 1 !== transaction.startSequence ||\n summary.resultHeadSequence !== transaction.endSequence ||\n summary.priorNativeRevision !== transaction.priorNativeRevision ||\n summary.nativeReceipt.revision !== transaction.nativeRevision ||\n summary.priorStateHash !== transaction.priorStateHash ||\n summary.stateHash !== transaction.stateHash\n ) {\n throw runtimeError(\n \"committed_metadata_mismatch\",\n \"outer committed metadata disagrees with its exact OGAST001 envelope\",\n );\n }\n return;\n }\n let summary: ReturnType<typeof decodeCommittedTransactionSummary>;\n try {\n summary = decodeCommittedTransactionSummary(transaction.committedTransactionBytes);\n } catch (error) {\n throw new ArtifactWorkerProtocolError(\n \"invalid_committed_transaction\",\n \"committed transaction is not canonical OGACO001\",\n { cause: error },\n );\n }\n if (\n summary.operationProtocolVersion !== transaction.protocolVersion ||\n summary.transactionId !== transaction.transactionId ||\n summary.priorStateHash !== transaction.priorStateHash ||\n summary.stateHash !== transaction.stateHash ||\n !frontiersEqual(summary.resultingCausalFrontier, transaction.causalFrontier)\n ) {\n throw runtimeError(\n \"committed_metadata_mismatch\",\n \"outer committed metadata disagrees with its exact OGACO001 envelope\",\n );\n }\n}\n\nfunction frontiersEqual(\n left: readonly Readonly<{ replicaId: string; counter: number }>[],\n right: EditableArtifactCausalFrontier,\n): boolean {\n return (\n left.length === right.length &&\n left.every(\n (entry, index) =>\n entry.replicaId === right[index]?.replicaId && entry.counter === right[index]?.counter,\n )\n );\n}\n\nfunction canonicalMutationIntent(\n input: ArtifactWorkerAuthorPendingInput | EditableArtifactPendingTransaction,\n commandBytes: Uint8Array,\n) {\n return {\n envelopeVersion: EDITABLE_ARTIFACT_INTENT_VERSION,\n protocolVersion: input.protocolVersion,\n modelSchemaVersion: input.modelSchemaVersion,\n commandProtocolVersion: input.commandVersion,\n artifactId: input.artifactId,\n clientTransactionId: input.clientTransactionId,\n replicaId: input.replicaId,\n replicaCounter: input.replicaCounter,\n previousLocalTransactionId: input.previousLocalTransactionId,\n observedHeadSequence: input.observedHeadSequence,\n causalBase: input.modality === \"spreadsheet\" ? (input.causalBase ?? []) : [],\n selectiveUndoOperationIds:\n input.modality === \"spreadsheet\" ? (input.selectiveUndoTargets ?? []) : [],\n commandBytes,\n } as const;\n}\n\nfunction retainedFrameBytes(frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>): number {\n let bytes = frame.metadata.byteLength;\n for (const segment of frame.segments) bytes += segment.byteLength;\n if (!Number.isSafeInteger(bytes)) {\n throw runtimeError(\"size_overflow\", \"artifact Worker request byte count overflowed\");\n }\n return bytes;\n}\n\nfunction requireBytesWithin(bytes: Uint8Array, maximum: number, label: string): Uint8Array {\n if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) {\n throw runtimeError(\"invalid_bytes\", `${label} must be non-empty bytes`);\n }\n if (bytes.byteLength > maximum)\n throw runtimeError(\"limit_exceeded\", `${label} exceeds its byte limit`);\n return bytes;\n}\n\nfunction pendingKey(transaction: EditableArtifactPendingTransaction): string {\n return `${transaction.clientTransactionId}\\0${transaction.requestHash}`;\n}\n\nfunction arraysEqual(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index]);\n}\n\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n if (left.byteLength !== right.byteLength) return false;\n for (let index = 0; index < left.byteLength; index += 1) {\n if (left[index] !== right[index]) return false;\n }\n return true;\n}\n\nfunction requireFrontierAdvance(\n previous: EditableArtifactCausalFrontier,\n next: EditableArtifactCausalFrontier,\n): void {\n const nextByReplica = new Map(next.map((entry) => [entry.replicaId, entry.counter]));\n for (const entry of previous) {\n if ((nextByReplica.get(entry.replicaId) ?? -1) < entry.counter) {\n throw runtimeError(\"invalid_frontier\", \"committed causal frontier regresses\");\n }\n }\n}\n\ntype WorkerFailure = { code: string; message: string; retryable: boolean };\n\nfunction asWorkerFailure(error: unknown): WorkerFailure {\n if (error instanceof ArtifactWorkerProtocolError) {\n return {\n code: normalizeErrorCode(error.code),\n message: sanitizeErrorMessage(error.message),\n retryable: false,\n };\n }\n if (error instanceof Error) {\n return {\n code: \"kernel_failed\",\n message: sanitizeErrorMessage(error.message || \"artifact kernel failed\"),\n retryable: false,\n };\n }\n return { code: \"kernel_failed\", message: \"artifact kernel failed\", retryable: false };\n}\n\nfunction asProtocolError(error: unknown): ArtifactWorkerProtocolError {\n if (error instanceof ArtifactWorkerProtocolError) return error;\n return new ArtifactWorkerProtocolError(\n \"runtime_failed\",\n error instanceof Error ? error.message : \"artifact Worker runtime failed\",\n { cause: error },\n );\n}\n\nfunction normalizeErrorCode(value: string): string {\n return /^[a-z][a-z0-9_]{0,127}$/.test(value) ? value : \"kernel_failed\";\n}\n\nfunction sanitizeErrorMessage(value: string): string {\n let output = \"\";\n for (let index = 0; index < value.length && output.length < 2_000; index += 1) {\n const code = value.charCodeAt(index);\n if (code >= 0xd800 && code <= 0xdbff) {\n const following = value.charCodeAt(index + 1);\n if (following >= 0xdc00 && following <= 0xdfff) {\n output += value[index]! + value[index + 1]!;\n index += 1;\n } else {\n output += \"\\ufffd\";\n }\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n output += \"\\ufffd\";\n } else {\n output += value[index]!;\n }\n }\n return output || \"artifact kernel failed\";\n}\n\nfunction runtimeError(code: string, message: string): ArtifactWorkerProtocolError {\n return new ArtifactWorkerProtocolError(code, message);\n}\n","import { loadBrowserWasmKernelAdapter } from \"./kernel-adapter\";\nimport {\n ArtifactWorkerRuntime,\n type ArtifactWorkerMessageEvent,\n type ArtifactWorkerRuntimeEndpoint,\n} from \"./runtime\";\nimport type { ArtifactWorkerRpcMessage } from \"./rpc-protocol\";\n\ntype WorkerScopeCandidate = {\n document?: unknown;\n addEventListener?: unknown;\n removeEventListener?: unknown;\n postMessage?: unknown;\n};\n\n/**\n * Dedicated module-Worker entry. Hosts bundle and self-host this file under\n * their CSP, then pass its URL to `createBrowserEditableArtifactWorkerKernel`.\n */\nexport function installBrowserArtifactWorkerEntry(\n scope: ArtifactWorkerRuntimeEndpoint,\n): ArtifactWorkerRuntime {\n return new ArtifactWorkerRuntime({ endpoint: scope, loadAdapter: loadBrowserWasmKernelAdapter });\n}\n\nconst candidate = globalThis as WorkerScopeCandidate;\nif (\n candidate.document === undefined &&\n typeof candidate.addEventListener === \"function\" &&\n typeof candidate.removeEventListener === \"function\" &&\n typeof candidate.postMessage === \"function\"\n) {\n installBrowserArtifactWorkerEntry({\n addEventListener(type, listener) {\n (\n candidate.addEventListener as (\n event: string,\n callback: (event: ArtifactWorkerMessageEvent) => void,\n ) => void\n )(type, listener);\n },\n removeEventListener(type, listener) {\n (\n candidate.removeEventListener as (\n event: string,\n callback: (event: ArtifactWorkerMessageEvent) => void,\n ) => void\n )(type, listener);\n },\n postMessage(message: ArtifactWorkerRpcMessage, transfer: Transferable[]) {\n (candidate.postMessage as (message: unknown, transfer: Transferable[]) => void)(\n message,\n transfer,\n );\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uCAAuC;AA0BzC,IAAM,uCAAN,cAAmD,MAAM;AAAA,EACrD;AAAA,EAET,YAAY,MAAc,UAAU,2DAA2D;AAC7F,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO,iBAAiB,MAAM,yBAAyB;AAAA,EAC9D;AACF;AA0IA,IAAM,2BAA2B;AACjC,IAAM,yBAAyB,IAAI;AACnC,IAAM,qBAAqB,IAAI,IAAI,IAAI,IAAI,OAAQ,KAAK;AACxD,IAAM,2BAA2B;AACjC,IAAM,yBAAyB,IAAI,OAAO;AAC1C,IAAM,0BAA0B;AAChC,IAAM,iBAAiB;AAEhB,IAAM,+BAAmE,OAAO,UAAU;AAC/F,QAAM,UAAU,MAAM;AAAA;AAAA,IAA0B,MAAM;AAAA;AACtD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U,MAAM,KAAK,IAAK,MAAM,QAAQ,CAAC;AACzC,iBAAS;AAAA,MACX,OAAO;AACL,kBAAU;AAAA,MACZ;AAAA,IACF,WAAW,QAAQ,SAAU,QAAQ,OAAQ;AAC3C,gBAAU;AAAA,IACZ,OAAO;AACL,gBAAU,MAAM,KAAK;AAAA,IACvB;AAAA,EACF;AACA,SAAO,UAAU;AACnB;AAEA,SAAS,aAAa,MAAc,SAA8C;AAChF,SAAO,IAAI,4BAA4B,MAAM,OAAO;AACtD;;;AChqCO,SAAS,kCACd,OACuB;AACvB,SAAO,IAAI,sBAAsB,EAAE,UAAU,OAAO,aAAa,6BAA6B,CAAC;AACjG;AAEA,IAAM,YAAY;AAClB,IACE,UAAU,aAAa,UACvB,OAAO,UAAU,qBAAqB,cACtC,OAAO,UAAU,wBAAwB,cACzC,OAAO,UAAU,gBAAgB,YACjC;AACA,oCAAkC;AAAA,IAChC,iBAAiB,MAAM,UAAU;AAC/B,MACE,UAAU,iBAIV,MAAM,QAAQ;AAAA,IAClB;AAAA,IACA,oBAAoB,MAAM,UAAU;AAClC,MACE,UAAU,oBAIV,MAAM,QAAQ;AAAA,IAClB;AAAA,IACA,YAAY,SAAmC,UAA0B;AACvE,MAAC,UAAU;AAAA,QACT;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACH;","names":["EDITABLE_ARTIFACT_INTENT_MAX_BYTES","EDITABLE_ARTIFACT_INTENT_VERSION","candidate","EDITABLE_ARTIFACT_INTENT_MAX_BYTES","summary","EDITABLE_ARTIFACT_INTENT_VERSION"]}
|
|
1
|
+
{"version":3,"sources":["../src/editable-artifacts/worker/kernel-adapter.ts","../src/editable-artifacts/worker/runtime.ts","../src/editable-artifacts/worker/browser-entry.ts"],"sourcesContent":["import {\n EDITABLE_ARTIFACT_COMMAND_MAX_BYTES,\n EDITABLE_ARTIFACT_INTENT_MAX_BYTES,\n EDITABLE_ARTIFACT_INTENT_VERSION,\n EDITABLE_ARTIFACT_PRODUCT_MAX_SNAPSHOT_BYTES,\n SPREADSHEET_ARTIFACT_COMMAND_VERSION,\n SPREADSHEET_ARTIFACT_MODEL_SCHEMA_VERSION,\n} from \"@opengeni/contracts/editable-artifacts\";\nimport {\n SPREADSHEET_COLLABORATION_SNAPSHOT_VERSION,\n SPREADSHEET_KERNEL_COMMAND_VERSION,\n SPREADSHEET_KERNEL_SNAPSHOT_VERSION,\n} from \"@opengeni/contracts/editable-artifact-versions\";\nimport {\n COMMITTED_TRANSACTION_PROTOCOL_VERSION,\n MAX_COMMITTED_TRANSACTION_BYTES,\n} from \"@opengeni/contracts/editable-artifact-committed-transaction\";\nimport type { ArtifactWorkerInitializeInput } from \"./wire-codec\";\nimport type { EditableArtifactModality } from \"../types\";\nimport { ArtifactWorkerProtocolError } from \"./rpc-protocol\";\n\nexport type ArtifactWorkerKernelSession = {\n readonly modality: EditableArtifactModality;\n /** Replays one exact whole canonical OGACO002 transaction. */\n applyCommitted: (committedTransactionBytes: Uint8Array) => void;\n /** Authors and applies one exact OGATX001 intent over the current frontier. */\n applyPending: (intentBytes: Uint8Array) => void;\n /** Applies one exact document/presentation command and returns its native receipt. */\n applyCommands: (commandBytes: Uint8Array) => Uint8Array;\n /** Native serialized-model revision; unavailable for spreadsheets. */\n nativeRevision: () => number;\n /** Stages an atomic candidate without serializing/reopening the model. */\n fork: () => ArtifactWorkerKernelSession;\n /** Kernel-defined canonical hash; never synthesized from transport bytes. */\n stateHash: () => Promise<string>;\n snapshot: () => Uint8Array;\n /** Canonical bounded OGAKQ request to canonical OGAKV projection. */\n query: (queryBytes: Uint8Array) => Uint8Array;\n dispose: () => void;\n};\n\n/** A valid local intent whose structural preconditions no longer project. */\nexport class ArtifactWorkerPendingProjectionError extends Error {\n readonly code: string;\n\n constructor(code: string, message = \"pending transaction cannot project over confirmed state\") {\n super(message);\n this.name = \"ArtifactWorkerPendingProjectionError\";\n this.code = requireErrorCode(code, \"pending projection code\");\n }\n}\n\n/** Entirely Worker-owned adapter over one compatible collaboration WASM build. */\nexport type ArtifactWorkerKernelAdapter = {\n readonly modality: EditableArtifactModality;\n readonly protocolVersion: number;\n readonly kernelVersion: string;\n readonly modelSchemaVersion: number;\n readonly commandVersion: number;\n readonly maximumSnapshotBytes: number;\n readonly maximumCommandBytes: number;\n readonly maximumIntentBytes: number;\n readonly maximumCommittedTransactionBytes: number;\n readonly maximumQueryBytes: number;\n readonly maximumQueryResponseBytes: number;\n canonicalizeSnapshot: (snapshotBytes: Uint8Array) => Uint8Array;\n open: (snapshotBytes: Uint8Array) => ArtifactWorkerKernelSession;\n dispose?: () => void;\n};\n\nexport type ArtifactWorkerKernelAdapterFactory = (\n input: ArtifactWorkerInitializeInput,\n) => Promise<ArtifactWorkerKernelAdapter>;\n\ntype WasmCollaborationSession = {\n authorTransaction: (intentBytes: Uint8Array, resolvedBaseBytes: Uint8Array) => Uint8Array;\n applyCommitted: (committedTransactionBytes: Uint8Array) => void;\n snapshot: () => Uint8Array;\n frontier: () => Uint8Array;\n fork: () => WasmCollaborationSession;\n stateHash: () => string;\n revision: () => bigint;\n query: (queryEnvelope: Uint8Array) => Uint8Array;\n isClosed?: () => boolean;\n close?: () => void;\n dispose?: () => void;\n free?: () => void;\n};\n\ntype WasmModalitySession = {\n applyCommands: (commandBytes: Uint8Array) => Uint8Array;\n snapshot: () => Uint8Array;\n revision: () => bigint;\n fork: () => WasmModalitySession;\n stateHash: () => string;\n query: (queryEnvelope: Uint8Array) => Uint8Array;\n isClosed?: () => boolean;\n close?: () => void;\n dispose?: () => void;\n free?: () => void;\n};\n\ntype WasmKernelModuleBase = {\n default?: (input: { module_or_path: string | URL }) => Promise<unknown>;\n capabilities: () => Uint8Array;\n buildIdentity: () => Uint8Array;\n};\n\ntype WasmKernelModule =\n | (WasmKernelModuleBase &\n Readonly<{\n modality: \"spreadsheet\";\n canonicalizeSnapshot: (snapshotBytes: Uint8Array) => Uint8Array;\n open: (snapshotBytes: Uint8Array) => WasmCollaborationSession;\n }>)\n | (WasmKernelModuleBase &\n Readonly<{\n modality: \"document\" | \"presentation\";\n canonicalizeSnapshot: (snapshotBytes: Uint8Array) => Uint8Array;\n open: (snapshotBytes: Uint8Array) => WasmModalitySession;\n }>);\n\ntype WasmCapabilities = Readonly<{\n abiVersion: number;\n buildIdentityFormat: \"utf8\";\n canonicalStateHash: \"sha256:canonical-snapshot\";\n collaboration: boolean;\n collaborationSnapshotVersion: number;\n commandSchemaVersion: number;\n committedTransactionVersion: number;\n document: boolean;\n documentCommandVersion: number;\n documentQueryResponseVersion: number;\n documentQueryVersion: number;\n documentReceiptVersion: number;\n documentSnapshotVersion: number;\n documentStatefulSessions: boolean;\n editableArtifactIntentVersion: number;\n kernelSnapshotVersion: number;\n spreadsheetCommandVersion: number;\n spreadsheetModelSchemaVersion: number;\n maxCellsPerBatch: number;\n maxCommandBytes: number;\n maxCommands: number;\n maxSnapshotBytes: number;\n maxSpreadsheetCommandBytes: number;\n maxIntentBytes: number;\n maxCommittedTransactionBytes: number;\n maxDocumentCommandBytes: number;\n maxDocumentCommands: number;\n maxDocumentQueryBytes: number;\n maxDocumentQueryResponseBytes: number;\n maxDocumentSnapshotBytes: number;\n maxMetadataScannedCells: number;\n maxQueryBytes: number;\n maxQueryResponseBytes: number;\n maxViewportArea: number;\n maxViewportCells: number;\n maxMetadataSheets: number;\n maxPresentationCommandBytes: number;\n maxPresentationQueryBytes: number;\n maxPresentationResponseBytes: number;\n maxPresentationSnapshotBytes: number;\n maxTextLayoutFontBundleBytes: number;\n maxTextLayoutRequestBytes: number;\n maxTextLayoutResponseBytes: number;\n presentation: boolean;\n presentationCommandVersion: number;\n presentationQueryResponseVersion: number;\n presentationQueryVersion: number;\n presentationSnapshotVersion: number;\n presentationStatefulSessions: boolean;\n queryResponseVersion: number;\n queryVersion: number;\n receiptSchemaVersion: number;\n retainedRenderPatchVersion: number;\n retainedRenderTileVersion: number;\n safeRust: true;\n statefulSessions: boolean;\n textLayout: boolean;\n textLayoutFontBundleVersion: number;\n textLayoutRequestVersion: number;\n textLayoutResponseVersion: number;\n textLayoutStatefulSessions: boolean;\n sessionForks: boolean;\n transport: \"bounded-uint8array\";\n workbookMetadataQueries: boolean;\n}>;\n\nconst MAX_BUILD_IDENTITY_BYTES = 512;\nconst MAX_CAPABILITIES_BYTES = 8 * 1024;\nconst MAX_FRONTIER_BYTES = 8 + 2 + 2 + 4 + 1_024 * 16 + 8;\nconst WASM_MAX_CELLS_PER_BATCH = 500_000;\nconst WASM_MAX_COMMAND_BYTES = 8 * 1024 * 1024;\nconst WASM_MAX_SNAPSHOT_BYTES = EDITABLE_ARTIFACT_PRODUCT_MAX_SNAPSHOT_BYTES;\nconst SHA256_PATTERN = /^sha256:[0-9a-f]{64}$/u;\n\nexport const loadBrowserWasmKernelAdapter: ArtifactWorkerKernelAdapterFactory = async (input) => {\n const rawWasm = await import(/* @vite-ignore */ input.wasmGlueUrl);\n const wasm = validateWasmModule(rawWasm, input.modality);\n if (wasm.default) await wasm.default({ module_or_path: input.wasmBinaryUrl });\n\n const buildIdentity = decodeUtf8(\n requireBoundedBytes(wasm.buildIdentity(), \"WASM build identity\", MAX_BUILD_IDENTITY_BYTES),\n \"WASM build identity\",\n );\n if (buildIdentity.length === 0) {\n throw adapterError(\"incompatible_wasm_build\", \"WASM build identity is empty\");\n }\n const capabilities = decodeCapabilities(\n requireBoundedBytes(wasm.capabilities(), \"WASM capabilities\", MAX_CAPABILITIES_BYTES),\n );\n assertRequestedLimits(input, capabilities);\n\n const profile = capabilityProfile(input.modality, capabilities);\n const adapter: ArtifactWorkerKernelAdapter = {\n modality: input.modality,\n protocolVersion: capabilities.editableArtifactIntentVersion,\n kernelVersion: buildIdentity,\n modelSchemaVersion: profile.modelSchemaVersion,\n commandVersion: profile.commandVersion,\n maximumSnapshotBytes: profile.maximumSnapshotBytes,\n maximumCommandBytes: profile.maximumCommandBytes,\n maximumIntentBytes: capabilities.maxIntentBytes,\n maximumCommittedTransactionBytes: capabilities.maxCommittedTransactionBytes,\n maximumQueryBytes: profile.maximumQueryBytes,\n maximumQueryResponseBytes: profile.maximumQueryResponseBytes,\n canonicalizeSnapshot(snapshotBytes) {\n return requireOwnedOutput(\n wasm.canonicalizeSnapshot(snapshotBytes),\n `canonical ${input.modality} snapshot`,\n input.maximumSnapshotBytes,\n );\n },\n open(snapshotBytes) {\n if (wasm.modality === \"spreadsheet\") {\n return wrapWasmCollaborationSession(wasm.open(snapshotBytes), input);\n }\n return wrapWasmModalitySession(wasm.open(snapshotBytes), input);\n },\n };\n return Object.freeze(adapter);\n};\n\nfunction wrapWasmCollaborationSession(\n session: WasmCollaborationSession,\n limits: ArtifactWorkerInitializeInput,\n): ArtifactWorkerKernelSession {\n requireSessionAbi(session);\n let disposed = false;\n const requireOpen = (): void => {\n if (disposed || session.isClosed?.() === true) {\n throw adapterError(\"session_closed\", \"artifact collaboration session is closed\");\n }\n };\n return {\n modality: \"spreadsheet\",\n applyCommitted(committedTransactionBytes) {\n requireOpen();\n requireInputBytes(\n committedTransactionBytes,\n \"committed transaction\",\n limits.maximumCommittedTransactionBytes,\n );\n session.applyCommitted(committedTransactionBytes);\n },\n applyPending(intentBytes) {\n requireOpen();\n requireInputBytes(intentBytes, \"pending intent\", limits.maximumIntentBytes);\n const frontier = requireOwnedOutput(\n session.frontier(),\n \"causal frontier\",\n MAX_FRONTIER_BYTES,\n );\n try {\n // The exact OGATX contains its sole OGASC mutation payload. The return\n // value is a whole OGACO proof for this speculative branch; validating\n // its bound is sufficient because speculative OGACO is never persisted.\n requireOwnedOutput(\n session.authorTransaction(intentBytes, frontier),\n \"speculative committed transaction\",\n limits.maximumCommittedTransactionBytes,\n );\n } catch (error) {\n const projectionCode = classifyProjectionFailure(error);\n if (projectionCode !== null) {\n throw new ArtifactWorkerPendingProjectionError(projectionCode);\n }\n throw error;\n }\n },\n applyCommands() {\n throw adapterError(\n \"unsupported_modality\",\n \"spreadsheet session does not apply serialized commands\",\n );\n },\n nativeRevision() {\n throw adapterError(\"unsupported_modality\", \"spreadsheet session has no native revision\");\n },\n fork() {\n requireOpen();\n return wrapWasmCollaborationSession(session.fork(), limits);\n },\n async stateHash() {\n requireOpen();\n const result = session.stateHash();\n if (!SHA256_PATTERN.test(result)) {\n throw adapterError(\"invalid_state_hash\", \"WASM kernel returned an invalid state hash\");\n }\n return result;\n },\n snapshot() {\n requireOpen();\n return requireOwnedOutput(\n session.snapshot(),\n \"collaboration snapshot\",\n limits.maximumSnapshotBytes,\n );\n },\n query(queryBytes) {\n requireOpen();\n requireInputBytes(queryBytes, \"kernel query\", limits.maximumQueryBytes);\n return requireOwnedOutput(\n session.query(queryBytes),\n \"kernel projection\",\n limits.maximumQueryResponseBytes,\n );\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n try {\n session.dispose?.();\n } finally {\n try {\n session.close?.();\n } finally {\n session.free?.();\n }\n }\n },\n };\n}\n\nfunction wrapWasmModalitySession(\n session: WasmModalitySession,\n limits: ArtifactWorkerInitializeInput,\n): ArtifactWorkerKernelSession {\n requireModalitySessionAbi(session);\n let disposed = false;\n const requireOpen = (): void => {\n if (disposed || session.isClosed?.() === true) {\n throw adapterError(\"session_closed\", `artifact ${limits.modality} session is closed`);\n }\n };\n return {\n modality: limits.modality,\n applyCommitted() {\n throw adapterError(\n \"unsupported_modality\",\n \"serialized session requires decoded OGAST replay\",\n );\n },\n applyPending() {\n throw adapterError(\"unsupported_modality\", \"serialized session requires exact command bytes\");\n },\n applyCommands(commandBytes) {\n requireOpen();\n requireInputBytes(commandBytes, `${limits.modality} command`, limits.maximumCommandBytes);\n return requireOwnedOutput(\n session.applyCommands(commandBytes),\n `${limits.modality} native receipt`,\n limits.maximumCommittedTransactionBytes,\n );\n },\n nativeRevision() {\n requireOpen();\n const revision = session.revision();\n if (revision < 0n || revision > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw adapterError(\"invalid_revision\", \"WASM kernel returned an unsafe native revision\");\n }\n return Number(revision);\n },\n fork() {\n requireOpen();\n return wrapWasmModalitySession(session.fork(), limits);\n },\n async stateHash() {\n requireOpen();\n const result = session.stateHash();\n if (!SHA256_PATTERN.test(result)) {\n throw adapterError(\"invalid_state_hash\", \"WASM kernel returned an invalid state hash\");\n }\n return result;\n },\n snapshot() {\n requireOpen();\n return requireOwnedOutput(\n session.snapshot(),\n `${limits.modality} snapshot`,\n limits.maximumSnapshotBytes,\n );\n },\n query(queryBytes) {\n requireOpen();\n requireInputBytes(queryBytes, `${limits.modality} query`, limits.maximumQueryBytes);\n return requireOwnedOutput(\n session.query(queryBytes),\n `${limits.modality} projection`,\n limits.maximumQueryResponseBytes,\n );\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n try {\n session.dispose?.();\n } finally {\n try {\n session.close?.();\n } finally {\n session.free?.();\n }\n }\n },\n };\n}\n\nfunction requireModalitySessionAbi(session: WasmModalitySession): void {\n if (\n !isObject(session) ||\n typeof session.applyCommands !== \"function\" ||\n typeof session.snapshot !== \"function\" ||\n typeof session.revision !== \"function\" ||\n typeof session.fork !== \"function\" ||\n typeof session.stateHash !== \"function\" ||\n typeof session.query !== \"function\"\n ) {\n session?.dispose?.();\n session?.close?.();\n session?.free?.();\n throw adapterError(\n \"incompatible_wasm_build\",\n \"WASM modality session lacks the required stateful ABI\",\n );\n }\n}\n\nfunction requireSessionAbi(session: WasmCollaborationSession): void {\n if (\n !isObject(session) ||\n typeof session.authorTransaction !== \"function\" ||\n typeof session.applyCommitted !== \"function\" ||\n typeof session.snapshot !== \"function\" ||\n typeof session.frontier !== \"function\" ||\n typeof session.fork !== \"function\" ||\n typeof session.stateHash !== \"function\" ||\n typeof session.revision !== \"function\" ||\n typeof session.query !== \"function\"\n ) {\n session?.dispose?.();\n session?.close?.();\n session?.free?.();\n throw adapterError(\n \"incompatible_wasm_build\",\n \"WASM collaboration session lacks the required stateful ABI\",\n );\n }\n}\n\nfunction validateWasmModule(input: unknown, modality: EditableArtifactModality): WasmKernelModule {\n if (!isObject(input)) throw adapterError(\"invalid_wasm_module\", \"WASM glue module is invalid\");\n const capabilities = callable(input, \"capabilities\");\n const buildIdentity = callable(input, \"buildIdentity\");\n const initializer = optionalCallable(input, \"default\");\n const base: WasmKernelModuleBase = {\n capabilities: capabilities as WasmKernelModuleBase[\"capabilities\"],\n buildIdentity: buildIdentity as WasmKernelModuleBase[\"buildIdentity\"],\n ...(initializer\n ? { default: initializer as NonNullable<WasmKernelModuleBase[\"default\"]> }\n : {}),\n };\n const canonicalizeName =\n modality === \"spreadsheet\"\n ? \"canonicalizeCollaborationSnapshot\"\n : modality === \"document\"\n ? \"canonicalizeDocumentSnapshot\"\n : \"canonicalizePresentationSnapshot\";\n const sessionName =\n modality === \"spreadsheet\"\n ? \"ArtifactCollaborationSession\"\n : modality === \"document\"\n ? \"ArtifactDocumentSession\"\n : \"ArtifactPresentationSession\";\n const canonicalizeSnapshot = callable(input, canonicalizeName);\n const sessionClass = data(input, sessionName);\n if (!isObject(sessionClass)) {\n throw adapterError(\"invalid_wasm_module\", `WASM glue has no ${sessionName} export`);\n }\n const open = callable(sessionClass, \"open\");\n if (modality === \"spreadsheet\") {\n return {\n ...base,\n modality,\n canonicalizeSnapshot: canonicalizeSnapshot as (snapshotBytes: Uint8Array) => Uint8Array,\n open: open as (snapshotBytes: Uint8Array) => WasmCollaborationSession,\n };\n }\n return {\n ...base,\n modality,\n canonicalizeSnapshot: canonicalizeSnapshot as (snapshotBytes: Uint8Array) => Uint8Array,\n open: open as (snapshotBytes: Uint8Array) => WasmModalitySession,\n };\n}\n\nfunction decodeCapabilities(bytes: Uint8Array): WasmCapabilities {\n let value: unknown;\n try {\n const text = decodeUtf8(bytes, \"WASM capabilities\");\n value = JSON.parse(text) as unknown;\n if (JSON.stringify(value) !== text) {\n throw new TypeError(\"capabilities JSON is not canonical\");\n }\n } catch (error) {\n throw new ArtifactWorkerProtocolError(\n \"incompatible_wasm_build\",\n \"WASM capabilities are not canonical UTF-8 JSON\",\n { cause: error },\n );\n }\n if (!isPlainRecord(value)) {\n throw adapterError(\"incompatible_wasm_build\", \"WASM capabilities must be a plain record\");\n }\n const expectedKeys = [\n \"abiVersion\",\n \"buildIdentityFormat\",\n \"canonicalStateHash\",\n \"collaboration\",\n \"collaborationSnapshotVersion\",\n \"commandSchemaVersion\",\n \"committedTransactionVersion\",\n \"document\",\n \"documentCommandVersion\",\n \"documentQueryResponseVersion\",\n \"documentQueryVersion\",\n \"documentReceiptVersion\",\n \"documentSnapshotVersion\",\n \"documentStatefulSessions\",\n \"editableArtifactIntentVersion\",\n \"kernelSnapshotVersion\",\n \"maxCellsPerBatch\",\n \"maxCommandBytes\",\n \"maxCommands\",\n \"maxCommittedTransactionBytes\",\n \"maxDocumentCommandBytes\",\n \"maxDocumentCommands\",\n \"maxDocumentQueryBytes\",\n \"maxDocumentQueryResponseBytes\",\n \"maxDocumentSnapshotBytes\",\n \"maxIntentBytes\",\n \"maxMetadataScannedCells\",\n \"maxMetadataSheets\",\n \"maxPresentationCommandBytes\",\n \"maxPresentationQueryBytes\",\n \"maxPresentationResponseBytes\",\n \"maxPresentationSnapshotBytes\",\n \"maxQueryBytes\",\n \"maxQueryResponseBytes\",\n \"maxSnapshotBytes\",\n \"maxSpreadsheetCommandBytes\",\n \"maxTextLayoutFontBundleBytes\",\n \"maxTextLayoutRequestBytes\",\n \"maxTextLayoutResponseBytes\",\n \"maxViewportArea\",\n \"maxViewportCells\",\n \"presentation\",\n \"presentationCommandVersion\",\n \"presentationQueryResponseVersion\",\n \"presentationQueryVersion\",\n \"presentationSnapshotVersion\",\n \"presentationStatefulSessions\",\n \"queryResponseVersion\",\n \"queryVersion\",\n \"receiptSchemaVersion\",\n \"retainedRenderPatchVersion\",\n \"retainedRenderTileVersion\",\n \"safeRust\",\n \"sessionForks\",\n \"spreadsheetCommandVersion\",\n \"spreadsheetModelSchemaVersion\",\n \"statefulSessions\",\n \"textLayout\",\n \"textLayoutFontBundleVersion\",\n \"textLayoutRequestVersion\",\n \"textLayoutResponseVersion\",\n \"textLayoutStatefulSessions\",\n \"transport\",\n \"workbookMetadataQueries\",\n ] as const;\n const keys = Object.keys(value).sort();\n if (\n keys.length !== expectedKeys.length ||\n keys.some((key, index) => key !== expectedKeys[index])\n ) {\n throw adapterError(\n \"incompatible_wasm_build\",\n \"WASM collaboration capabilities have unknown or missing fields\",\n );\n }\n const normalized = {\n abiVersion: positiveInteger(value.abiVersion, \"abiVersion\"),\n buildIdentityFormat: value.buildIdentityFormat,\n canonicalStateHash: value.canonicalStateHash,\n collaboration: strictBoolean(value.collaboration, \"collaboration\"),\n collaborationSnapshotVersion: positiveInteger(\n value.collaborationSnapshotVersion,\n \"collaborationSnapshotVersion\",\n ),\n commandSchemaVersion: positiveInteger(value.commandSchemaVersion, \"commandSchemaVersion\"),\n committedTransactionVersion: positiveInteger(\n value.committedTransactionVersion,\n \"committedTransactionVersion\",\n ),\n document: strictBoolean(value.document, \"document\"),\n documentCommandVersion: positiveInteger(value.documentCommandVersion, \"documentCommandVersion\"),\n documentQueryResponseVersion: positiveInteger(\n value.documentQueryResponseVersion,\n \"documentQueryResponseVersion\",\n ),\n documentQueryVersion: positiveInteger(value.documentQueryVersion, \"documentQueryVersion\"),\n documentReceiptVersion: positiveInteger(value.documentReceiptVersion, \"documentReceiptVersion\"),\n documentSnapshotVersion: positiveInteger(\n value.documentSnapshotVersion,\n \"documentSnapshotVersion\",\n ),\n documentStatefulSessions: strictBoolean(\n value.documentStatefulSessions,\n \"documentStatefulSessions\",\n ),\n editableArtifactIntentVersion: positiveInteger(\n value.editableArtifactIntentVersion,\n \"editableArtifactIntentVersion\",\n ),\n kernelSnapshotVersion: positiveInteger(value.kernelSnapshotVersion, \"kernelSnapshotVersion\"),\n spreadsheetCommandVersion: positiveInteger(\n value.spreadsheetCommandVersion,\n \"spreadsheetCommandVersion\",\n ),\n spreadsheetModelSchemaVersion: positiveInteger(\n value.spreadsheetModelSchemaVersion,\n \"spreadsheetModelSchemaVersion\",\n ),\n maxCellsPerBatch: positiveInteger(value.maxCellsPerBatch, \"maxCellsPerBatch\"),\n maxCommands: positiveInteger(value.maxCommands, \"maxCommands\"),\n maxSnapshotBytes: positiveInteger(value.maxSnapshotBytes, \"maxSnapshotBytes\"),\n maxCommandBytes: positiveInteger(value.maxCommandBytes, \"maxCommandBytes\"),\n maxSpreadsheetCommandBytes: positiveInteger(\n value.maxSpreadsheetCommandBytes,\n \"maxSpreadsheetCommandBytes\",\n ),\n maxIntentBytes: positiveInteger(value.maxIntentBytes, \"maxIntentBytes\"),\n maxCommittedTransactionBytes: positiveInteger(\n value.maxCommittedTransactionBytes,\n \"maxCommittedTransactionBytes\",\n ),\n maxDocumentCommandBytes: positiveInteger(\n value.maxDocumentCommandBytes,\n \"maxDocumentCommandBytes\",\n ),\n maxDocumentCommands: positiveInteger(value.maxDocumentCommands, \"maxDocumentCommands\"),\n maxDocumentQueryBytes: positiveInteger(value.maxDocumentQueryBytes, \"maxDocumentQueryBytes\"),\n maxDocumentQueryResponseBytes: positiveInteger(\n value.maxDocumentQueryResponseBytes,\n \"maxDocumentQueryResponseBytes\",\n ),\n maxDocumentSnapshotBytes: positiveInteger(\n value.maxDocumentSnapshotBytes,\n \"maxDocumentSnapshotBytes\",\n ),\n maxMetadataScannedCells: positiveInteger(\n value.maxMetadataScannedCells,\n \"maxMetadataScannedCells\",\n ),\n maxQueryBytes: positiveInteger(value.maxQueryBytes, \"maxQueryBytes\"),\n maxQueryResponseBytes: positiveInteger(value.maxQueryResponseBytes, \"maxQueryResponseBytes\"),\n maxViewportArea: positiveInteger(value.maxViewportArea, \"maxViewportArea\"),\n maxViewportCells: positiveInteger(value.maxViewportCells, \"maxViewportCells\"),\n maxMetadataSheets: positiveInteger(value.maxMetadataSheets, \"maxMetadataSheets\"),\n maxPresentationCommandBytes: positiveInteger(\n value.maxPresentationCommandBytes,\n \"maxPresentationCommandBytes\",\n ),\n maxPresentationQueryBytes: positiveInteger(\n value.maxPresentationQueryBytes,\n \"maxPresentationQueryBytes\",\n ),\n maxPresentationResponseBytes: positiveInteger(\n value.maxPresentationResponseBytes,\n \"maxPresentationResponseBytes\",\n ),\n maxPresentationSnapshotBytes: positiveInteger(\n value.maxPresentationSnapshotBytes,\n \"maxPresentationSnapshotBytes\",\n ),\n maxTextLayoutFontBundleBytes: positiveInteger(\n value.maxTextLayoutFontBundleBytes,\n \"maxTextLayoutFontBundleBytes\",\n ),\n maxTextLayoutRequestBytes: positiveInteger(\n value.maxTextLayoutRequestBytes,\n \"maxTextLayoutRequestBytes\",\n ),\n maxTextLayoutResponseBytes: positiveInteger(\n value.maxTextLayoutResponseBytes,\n \"maxTextLayoutResponseBytes\",\n ),\n queryResponseVersion: positiveInteger(value.queryResponseVersion, \"queryResponseVersion\"),\n queryVersion: positiveInteger(value.queryVersion, \"queryVersion\"),\n receiptSchemaVersion: positiveInteger(value.receiptSchemaVersion, \"receiptSchemaVersion\"),\n retainedRenderPatchVersion: positiveInteger(\n value.retainedRenderPatchVersion,\n \"retainedRenderPatchVersion\",\n ),\n retainedRenderTileVersion: positiveInteger(\n value.retainedRenderTileVersion,\n \"retainedRenderTileVersion\",\n ),\n presentation: strictBoolean(value.presentation, \"presentation\"),\n presentationCommandVersion: positiveInteger(\n value.presentationCommandVersion,\n \"presentationCommandVersion\",\n ),\n presentationQueryResponseVersion: positiveInteger(\n value.presentationQueryResponseVersion,\n \"presentationQueryResponseVersion\",\n ),\n presentationQueryVersion: positiveInteger(\n value.presentationQueryVersion,\n \"presentationQueryVersion\",\n ),\n presentationSnapshotVersion: positiveInteger(\n value.presentationSnapshotVersion,\n \"presentationSnapshotVersion\",\n ),\n presentationStatefulSessions: strictBoolean(\n value.presentationStatefulSessions,\n \"presentationStatefulSessions\",\n ),\n safeRust: strictBoolean(value.safeRust, \"safeRust\"),\n statefulSessions: strictBoolean(value.statefulSessions, \"statefulSessions\"),\n textLayout: strictBoolean(value.textLayout, \"textLayout\"),\n textLayoutFontBundleVersion: positiveInteger(\n value.textLayoutFontBundleVersion,\n \"textLayoutFontBundleVersion\",\n ),\n textLayoutRequestVersion: positiveInteger(\n value.textLayoutRequestVersion,\n \"textLayoutRequestVersion\",\n ),\n textLayoutResponseVersion: positiveInteger(\n value.textLayoutResponseVersion,\n \"textLayoutResponseVersion\",\n ),\n textLayoutStatefulSessions: strictBoolean(\n value.textLayoutStatefulSessions,\n \"textLayoutStatefulSessions\",\n ),\n sessionForks: strictBoolean(value.sessionForks, \"sessionForks\"),\n transport: value.transport,\n workbookMetadataQueries: strictBoolean(\n value.workbookMetadataQueries,\n \"workbookMetadataQueries\",\n ),\n };\n if (\n normalized.abiVersion !== 1 ||\n normalized.buildIdentityFormat !== \"utf8\" ||\n normalized.canonicalStateHash !== \"sha256:canonical-snapshot\" ||\n normalized.editableArtifactIntentVersion !== EDITABLE_ARTIFACT_INTENT_VERSION ||\n normalized.spreadsheetCommandVersion !== SPREADSHEET_ARTIFACT_COMMAND_VERSION ||\n normalized.spreadsheetModelSchemaVersion !== SPREADSHEET_ARTIFACT_MODEL_SCHEMA_VERSION ||\n normalized.collaborationSnapshotVersion !== SPREADSHEET_COLLABORATION_SNAPSHOT_VERSION ||\n normalized.commandSchemaVersion !== SPREADSHEET_KERNEL_COMMAND_VERSION ||\n normalized.committedTransactionVersion !== COMMITTED_TRANSACTION_PROTOCOL_VERSION ||\n normalized.documentCommandVersion !== 1 ||\n normalized.documentQueryResponseVersion !== 1 ||\n normalized.documentQueryVersion !== 1 ||\n normalized.documentReceiptVersion !== 1 ||\n normalized.documentSnapshotVersion !== 1 ||\n normalized.documentStatefulSessions !== normalized.document ||\n normalized.kernelSnapshotVersion !== SPREADSHEET_KERNEL_SNAPSHOT_VERSION ||\n normalized.maxCellsPerBatch !== WASM_MAX_CELLS_PER_BATCH ||\n normalized.maxCommandBytes !== WASM_MAX_COMMAND_BYTES ||\n normalized.maxSpreadsheetCommandBytes !== EDITABLE_ARTIFACT_COMMAND_MAX_BYTES ||\n normalized.maxCommands !== 10_000 ||\n normalized.maxIntentBytes !== EDITABLE_ARTIFACT_INTENT_MAX_BYTES ||\n normalized.maxCommittedTransactionBytes !== MAX_COMMITTED_TRANSACTION_BYTES ||\n normalized.maxDocumentCommandBytes !== WASM_MAX_COMMAND_BYTES ||\n normalized.maxDocumentCommands !== 4_096 ||\n normalized.maxDocumentQueryBytes !== 256 ||\n normalized.maxDocumentQueryResponseBytes !== 8 * 1024 * 1024 ||\n normalized.maxDocumentSnapshotBytes !== WASM_MAX_SNAPSHOT_BYTES ||\n normalized.maxMetadataScannedCells !== 4_000_000 ||\n normalized.maxQueryBytes !== 68 ||\n normalized.maxQueryResponseBytes !== 8 * 1024 * 1024 ||\n normalized.maxViewportArea !== 1_048_576 ||\n normalized.maxViewportCells !== 262_144 ||\n normalized.maxMetadataSheets !== 10_000 ||\n normalized.maxPresentationCommandBytes !== 4 * 1024 * 1024 ||\n normalized.maxPresentationQueryBytes !== 96 ||\n normalized.maxPresentationResponseBytes !== 8 * 1024 * 1024 ||\n normalized.maxPresentationSnapshotBytes !== WASM_MAX_SNAPSHOT_BYTES ||\n normalized.maxTextLayoutFontBundleBytes !== 48 * 1024 * 1024 ||\n normalized.maxTextLayoutRequestBytes !== 4 * 1024 * 1024 ||\n normalized.maxTextLayoutResponseBytes !== 32 * 1024 * 1024 ||\n normalized.maxSnapshotBytes !== WASM_MAX_SNAPSHOT_BYTES ||\n normalized.queryResponseVersion !== 1 ||\n normalized.queryVersion !== 1 ||\n normalized.receiptSchemaVersion !== 1 ||\n normalized.retainedRenderPatchVersion !== 1 ||\n normalized.retainedRenderTileVersion !== 1 ||\n normalized.presentationCommandVersion !== 1 ||\n normalized.presentationQueryResponseVersion !== 1 ||\n normalized.presentationQueryVersion !== 1 ||\n normalized.presentationSnapshotVersion !== 1 ||\n normalized.presentationStatefulSessions !== normalized.presentation ||\n normalized.safeRust !== true ||\n normalized.statefulSessions !== true ||\n normalized.textLayoutFontBundleVersion !== 1 ||\n normalized.textLayoutRequestVersion !== 1 ||\n normalized.textLayoutResponseVersion !== 1 ||\n normalized.textLayoutStatefulSessions !== normalized.textLayout ||\n normalized.sessionForks !== true ||\n normalized.transport !== \"bounded-uint8array\" ||\n normalized.workbookMetadataQueries !== normalized.collaboration\n ) {\n throw adapterError(\n \"incompatible_wasm_build\",\n \"WASM capabilities do not match the SDK protocol\",\n );\n }\n return Object.freeze(normalized) as WasmCapabilities;\n}\n\nfunction assertRequestedLimits(\n input: ArtifactWorkerInitializeInput,\n capabilities: WasmCapabilities,\n): void {\n const profile = capabilityProfile(input.modality, capabilities);\n const pairs = [\n [\"maximumSnapshotBytes\", input.maximumSnapshotBytes, profile.maximumSnapshotBytes],\n [\"maximumCommandBytes\", input.maximumCommandBytes, profile.maximumCommandBytes],\n [\"maximumIntentBytes\", input.maximumIntentBytes, capabilities.maxIntentBytes],\n [\n \"maximumCommittedTransactionBytes\",\n input.maximumCommittedTransactionBytes,\n capabilities.maxCommittedTransactionBytes,\n ],\n [\"maximumQueryBytes\", input.maximumQueryBytes, profile.maximumQueryBytes],\n [\n \"maximumQueryResponseBytes\",\n input.maximumQueryResponseBytes,\n profile.maximumQueryResponseBytes,\n ],\n ] as const;\n for (const [label, requested, advertised] of pairs) {\n if (requested > advertised) {\n throw adapterError(\n \"incompatible_wasm_build\",\n `${label} exceeds the loaded WASM build capability`,\n );\n }\n }\n}\n\nfunction capabilityProfile(modality: EditableArtifactModality, capabilities: WasmCapabilities) {\n if (modality === \"spreadsheet\") {\n if (!capabilities.collaboration || !capabilities.workbookMetadataQueries) {\n throw adapterError(\n \"incompatible_wasm_build\",\n \"WASM module does not provide the spreadsheet collaboration ABI\",\n );\n }\n return {\n modelSchemaVersion: capabilities.spreadsheetModelSchemaVersion,\n commandVersion: capabilities.spreadsheetCommandVersion,\n maximumSnapshotBytes: capabilities.maxSnapshotBytes,\n maximumCommandBytes: capabilities.maxSpreadsheetCommandBytes,\n maximumQueryBytes: capabilities.maxQueryBytes,\n maximumQueryResponseBytes: capabilities.maxQueryResponseBytes,\n } as const;\n }\n if (modality === \"document\") {\n if (!capabilities.document || !capabilities.documentStatefulSessions) {\n throw adapterError(\n \"incompatible_wasm_build\",\n \"WASM module does not provide the document ABI\",\n );\n }\n return {\n modelSchemaVersion: capabilities.documentSnapshotVersion,\n commandVersion: capabilities.documentCommandVersion,\n maximumSnapshotBytes: capabilities.maxDocumentSnapshotBytes,\n maximumCommandBytes: capabilities.maxDocumentCommandBytes,\n maximumQueryBytes: capabilities.maxDocumentQueryBytes,\n maximumQueryResponseBytes: capabilities.maxDocumentQueryResponseBytes,\n } as const;\n }\n if (!capabilities.presentation || !capabilities.presentationStatefulSessions) {\n throw adapterError(\n \"incompatible_wasm_build\",\n \"WASM module does not provide the presentation ABI\",\n );\n }\n return {\n modelSchemaVersion: capabilities.presentationSnapshotVersion,\n commandVersion: capabilities.presentationCommandVersion,\n maximumSnapshotBytes: capabilities.maxPresentationSnapshotBytes,\n maximumCommandBytes: capabilities.maxPresentationCommandBytes,\n maximumQueryBytes: capabilities.maxPresentationQueryBytes,\n maximumQueryResponseBytes: capabilities.maxPresentationResponseBytes,\n } as const;\n}\n\nfunction classifyProjectionFailure(error: unknown): string | null {\n const message = error instanceof Error ? error.message : \"\";\n const match = /^\\[([A-Z][A-Z0-9_]{0,127})\\]/u.exec(message);\n if (!match) return null;\n switch (match[1]) {\n case \"ARTIFACT_COLLABORATION_REJECTED\":\n return \"structural_conflict\";\n case \"ARTIFACT_PROJECTION_REJECTED\":\n return \"projection_conflict\";\n default:\n return null;\n }\n}\n\nfunction requireInputBytes(value: unknown, label: string, maximumBytes: number): Uint8Array {\n if (!(value instanceof Uint8Array) || value.byteLength === 0) {\n throw adapterError(\"invalid_kernel_input\", `${label} must be non-empty bytes`);\n }\n if (value.byteLength > maximumBytes) {\n throw adapterError(\"limit_exceeded\", `${label} exceeds its byte limit`);\n }\n return value;\n}\n\nfunction requireBoundedBytes(value: unknown, label: string, maximumBytes: number): Uint8Array {\n if (!(value instanceof Uint8Array) || value.byteLength === 0) {\n throw adapterError(\"invalid_kernel_output\", `${label} must be non-empty bytes`);\n }\n if (value.byteLength > maximumBytes) {\n throw adapterError(\"limit_exceeded\", `${label} exceeds its byte limit`);\n }\n return value;\n}\n\n/**\n * Wasm-bindgen returns a fresh Uint8Array. Keep its exact ArrayBuffer when\n * possible so the Worker can transfer it without another large copy; normalize\n * only aliased/subarray outputs from test or custom glue.\n */\nfunction requireOwnedOutput(value: unknown, label: string, maximumBytes: number): Uint8Array {\n const bytes = requireBoundedBytes(value, label, maximumBytes);\n if (\n bytes.buffer instanceof ArrayBuffer &&\n bytes.byteOffset === 0 &&\n bytes.byteLength === bytes.buffer.byteLength\n ) {\n return bytes;\n }\n return bytes.slice();\n}\n\nfunction decodeUtf8(bytes: Uint8Array, label: string): string {\n try {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch (error) {\n throw new ArtifactWorkerProtocolError(\"incompatible_wasm_build\", `${label} is not UTF-8`, {\n cause: error,\n });\n }\n}\n\nfunction callable(\n record: Record<PropertyKey, unknown>,\n key: string,\n): (...args: never[]) => unknown {\n const value = data(record, key);\n if (typeof value !== \"function\") {\n throw adapterError(\"invalid_wasm_module\", `${key} must be a function`);\n }\n return value as (...args: never[]) => unknown;\n}\n\nfunction optionalCallable(\n record: Record<PropertyKey, unknown>,\n key: string,\n): ((...args: never[]) => unknown) | undefined {\n const value = data(record, key, false);\n if (value === undefined) return undefined;\n if (typeof value !== \"function\") {\n throw adapterError(\"invalid_wasm_module\", `${key} must be a function`);\n }\n return value as (...args: never[]) => unknown;\n}\n\nfunction data(record: Record<PropertyKey, unknown>, key: string, required = true): unknown {\n const descriptor = Object.getOwnPropertyDescriptor(record, key);\n // ES module namespace exports are accessor descriptors by specification.\n if (descriptor) return \"value\" in descriptor ? descriptor.value : Reflect.get(record, key);\n if (required) throw adapterError(\"invalid_wasm_module\", `module is missing ${key}`);\n return undefined;\n}\n\nfunction isObject(value: unknown): value is Record<PropertyKey, unknown> {\n return value !== null && (typeof value === \"object\" || typeof value === \"function\");\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nfunction adapterError(code: string, message: string): ArtifactWorkerProtocolError {\n return new ArtifactWorkerProtocolError(code, message);\n}\n\nfunction requireErrorCode(value: unknown, label: string): string {\n if (typeof value !== \"string\" || !/^[a-z][a-z0-9_]{0,127}$/u.test(value)) {\n throw adapterError(\"invalid_wasm_module\", `${label} is invalid`);\n }\n return value;\n}\n\nfunction positiveInteger(value: unknown, label: string): number {\n if (!Number.isSafeInteger(value) || (value as number) <= 0) {\n throw adapterError(\"incompatible_wasm_build\", `${label} must be a positive safe integer`);\n }\n return value as number;\n}\n\nfunction strictBoolean(value: unknown, label: string): boolean {\n if (typeof value !== \"boolean\") {\n throw adapterError(\"incompatible_wasm_build\", `${label} must be a boolean`);\n }\n return value;\n}\n","import {\n EDITABLE_ARTIFACT_INTENT_MAX_BYTES,\n EDITABLE_ARTIFACT_INTENT_VERSION,\n assertCanonicalSpreadsheetArtifactCommandBytes,\n decodeEditableArtifactMutationIntent,\n hashEditableArtifactMutationIntent,\n} from \"@opengeni/contracts/editable-artifacts\";\nimport {\n COMMITTED_TRANSACTION_PROTOCOL_VERSION,\n decodeCommittedTransactionSummary,\n} from \"@opengeni/contracts/editable-artifact-committed-transaction\";\nimport { editableArtifactCodecFor } from \"@opengeni/contracts/editable-artifact-codec-registry\";\nimport { decodeEditableArtifactSerializedCommit } from \"@opengeni/contracts/editable-artifact-serialized-commit\";\nimport { SPREADSHEET_COLLABORATION_SNAPSHOT_VERSION } from \"@opengeni/contracts/editable-artifact-versions\";\nimport type {\n EditableArtifactBlockedPending,\n EditableArtifactCausalFrontier,\n EditableArtifactCommittedTransaction,\n EditableArtifactPendingTransaction,\n} from \"../types\";\nimport type {\n ArtifactWorkerKernelAdapter,\n ArtifactWorkerKernelAdapterFactory,\n ArtifactWorkerKernelSession,\n} from \"./kernel-adapter\";\nimport { ArtifactWorkerPendingProjectionError } from \"./kernel-adapter\";\nimport {\n ArtifactWorkerProtocolError,\n ArtifactWorkerRpcKind,\n decodeArtifactWorkerRpcMessage,\n encodeArtifactWorkerRpcMessage,\n transferListForArtifactWorkerRpcMessage,\n type ArtifactWorkerRpcLimits,\n type ArtifactWorkerRpcMessage,\n} from \"./rpc-protocol\";\nimport {\n decodeAuthorPendingMetadata,\n decodeCommittedMetadata,\n decodeInitialize,\n decodePendingListMetadata,\n decodeReconcileMetadata,\n decodeSnapshotMetadata,\n encodeErrorPayload,\n encodePendingListMetadata,\n encodeProjectionResponse,\n encodeStateResponse,\n requireMatchingHash,\n sha256Hex,\n type ArtifactWorkerAuthorPendingInput,\n type ArtifactWorkerInitializeInput,\n} from \"./wire-codec\";\n\nexport type ArtifactWorkerMessageEvent = { data: unknown };\n\nexport type ArtifactWorkerRuntimeEndpoint = {\n addEventListener: (\n type: \"message\",\n listener: (event: ArtifactWorkerMessageEvent) => void,\n ) => void;\n removeEventListener: (\n type: \"message\",\n listener: (event: ArtifactWorkerMessageEvent) => void,\n ) => void;\n postMessage: (message: ArtifactWorkerRpcMessage, transfer: Transferable[]) => void;\n};\n\nexport type InstallArtifactWorkerRuntimeOptions = {\n endpoint: ArtifactWorkerRuntimeEndpoint;\n loadAdapter: ArtifactWorkerKernelAdapterFactory;\n rpcLimits?: Readonly<ArtifactWorkerRpcLimits>;\n onProtocolError?: (error: ArtifactWorkerProtocolError) => void;\n};\n\ntype InstalledStateCommon = {\n artifactId: string;\n sequence: number;\n protocolVersion: number;\n kernelVersion: string;\n modelSchemaVersion: number;\n stateHash: string;\n};\n\ntype InstalledState = InstalledStateCommon &\n (\n | { modality: \"spreadsheet\"; causalFrontier: EditableArtifactCausalFrontier }\n | { modality: \"document\" | \"presentation\"; nativeRevision: number }\n );\n\nconst MAX_KNOWN_REQUESTS = 64;\nconst MAX_QUEUED_REQUEST_BYTES = 192 * 1024 * 1024;\nconst MAX_PENDING_AGGREGATE_BYTES = 64 * 1024 * 1024;\n\n/** Owns all mutable artifact/WASM state inside one dedicated Worker. */\nexport class ArtifactWorkerRuntime {\n private readonly endpoint: ArtifactWorkerRuntimeEndpoint;\n private readonly loadAdapter: ArtifactWorkerKernelAdapterFactory;\n private readonly rpcLimits: Readonly<ArtifactWorkerRpcLimits> | undefined;\n private readonly onProtocolError: ((error: ArtifactWorkerProtocolError) => void) | undefined;\n private readonly cancelled = new Set<number>();\n private readonly knownRequests = new Map<number, { bytes: number; generation: number }>();\n private queuedRequestBytes = 0;\n private queue: Promise<void> = Promise.resolve();\n private generation: number | null = null;\n private initialization: ArtifactWorkerInitializeInput | null = null;\n private adapter: ArtifactWorkerKernelAdapter | null = null;\n private confirmed: ArtifactWorkerKernelSession | null = null;\n private speculative: ArtifactWorkerKernelSession | null = null;\n private installed: InstalledState | null = null;\n private pendingKeys: readonly string[] = Object.freeze([]);\n private blockedPending: readonly EditableArtifactBlockedPending[] = Object.freeze([]);\n private disposed = false;\n\n private readonly onMessage = (event: ArtifactWorkerMessageEvent): void => {\n if (this.disposed) return;\n let frame;\n try {\n frame = decodeArtifactWorkerRpcMessage(event.data, this.rpcLimits);\n } catch (error) {\n const failure = asProtocolError(error);\n this.reportProtocolError(failure);\n return;\n }\n if (frame.kind === ArtifactWorkerRpcKind.Cancel) {\n if (\n frame.flags === 0 &&\n frame.metadata.byteLength === 0 &&\n frame.segments.length === 0 &&\n this.knownRequests.get(frame.requestId)?.generation === frame.generation\n ) {\n this.cancelled.add(frame.requestId);\n }\n return;\n }\n if (frame.flags !== 0) {\n this.reportProtocolError(runtimeError(\"noncanonical\", \"unknown RPC flags are set\"));\n return;\n }\n if (this.knownRequests.has(frame.requestId)) {\n this.reportProtocolError(runtimeError(\"duplicate_request\", \"RPC request id is duplicated\"));\n return;\n }\n const requestBytes = retainedFrameBytes(frame);\n if (\n this.knownRequests.size >= MAX_KNOWN_REQUESTS ||\n this.queuedRequestBytes + requestBytes > MAX_QUEUED_REQUEST_BYTES\n ) {\n this.respondError(\n frame.requestId,\n runtimeError(\"request_limit\", \"artifact Worker request queue is full\"),\n frame.generation,\n );\n return;\n }\n this.knownRequests.set(frame.requestId, { bytes: requestBytes, generation: frame.generation });\n this.queuedRequestBytes += requestBytes;\n this.queue = this.queue\n .then(() => this.dispatch(frame))\n .catch((error: unknown) => this.reportProtocolError(asProtocolError(error)));\n };\n\n constructor(options: InstallArtifactWorkerRuntimeOptions) {\n this.endpoint = options.endpoint;\n this.loadAdapter = options.loadAdapter;\n this.rpcLimits = options.rpcLimits;\n this.onProtocolError = options.onProtocolError;\n this.endpoint.addEventListener(\"message\", this.onMessage);\n }\n\n async dispose(): Promise<void> {\n if (this.disposed) return;\n this.disposed = true;\n this.endpoint.removeEventListener(\"message\", this.onMessage);\n await this.queue.catch(() => {});\n this.releaseState();\n this.disposeAdapter(this.adapter);\n this.adapter = null;\n this.cancelled.clear();\n this.knownRequests.clear();\n this.queuedRequestBytes = 0;\n }\n\n private async dispatch(frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>): Promise<void> {\n try {\n if (frame.kind === ArtifactWorkerRpcKind.Initialize) {\n await this.initialize(frame);\n return;\n }\n this.requireInitialized(frame.generation);\n this.throwIfCancelled(frame.requestId);\n switch (frame.kind) {\n case ArtifactWorkerRpcKind.Reset:\n this.requireNoPayload(frame);\n this.releaseState();\n this.respond(frame.requestId);\n return;\n case ArtifactWorkerRpcKind.LoadSnapshot:\n await this.loadSnapshot(frame);\n return;\n case ArtifactWorkerRpcKind.ApplyRecovered:\n await this.applyRecovered(frame);\n return;\n case ArtifactWorkerRpcKind.ReconcileCommitted:\n await this.reconcileCommitted(frame);\n return;\n case ArtifactWorkerRpcKind.ReplacePending:\n await this.replacePending(frame);\n return;\n case ArtifactWorkerRpcKind.AuthorPending:\n await this.authorPending(frame);\n return;\n case ArtifactWorkerRpcKind.QuerySpreadsheet:\n this.queryArtifact(frame);\n return;\n case ArtifactWorkerRpcKind.Dispose:\n this.requireNoPayload(frame);\n this.releaseState();\n this.disposeAdapter(this.adapter);\n this.adapter = null;\n this.respond(frame.requestId);\n return;\n default:\n throw runtimeError(\"unknown_request\", `worker cannot execute RPC kind ${frame.kind}`);\n }\n } catch (error) {\n this.respondError(frame.requestId, error, frame.generation);\n } finally {\n this.cancelled.delete(frame.requestId);\n const retainedBytes = this.knownRequests.get(frame.requestId)?.bytes ?? 0;\n this.knownRequests.delete(frame.requestId);\n this.queuedRequestBytes -= retainedBytes;\n }\n }\n\n private async initialize(\n frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>,\n ): Promise<void> {\n if (this.generation !== null || this.adapter !== null) {\n throw runtimeError(\"already_initialized\", \"artifact Worker is already initialized\");\n }\n if (frame.segments.length !== 0)\n throw runtimeError(\"invalid_segment\", \"initialize has no segments\");\n const initialization = decodeInitialize(frame.metadata);\n this.throwIfCancelled(frame.requestId);\n let adapter: ArtifactWorkerKernelAdapter | null = null;\n try {\n adapter = await this.loadAdapter(initialization);\n this.throwIfCancelled(frame.requestId);\n } catch (error) {\n this.disposeAdapter(adapter);\n throw error;\n }\n assertAdapterCompatibility(adapter, initialization);\n this.generation = frame.generation;\n this.initialization = initialization;\n this.adapter = adapter;\n this.respond(frame.requestId);\n }\n\n private async loadSnapshot(\n frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>,\n ): Promise<void> {\n const initialization = this.requireInitialization();\n const adapter = this.requireAdapter();\n if (frame.segments.length !== 1)\n throw runtimeError(\"invalid_segment\", \"snapshot requires one segment\");\n const ownedBytes = requireBytesWithin(\n frame.segments[0]!,\n initialization.maximumSnapshotBytes,\n \"snapshot\",\n );\n const snapshot = decodeSnapshotMetadata(frame.metadata, ownedBytes);\n if (\n snapshot.modality !== initialization.modality ||\n snapshot.modality !== adapter.modality ||\n (snapshot.modality === \"spreadsheet\" &&\n (snapshot.operationProtocolVersion !== COMMITTED_TRANSACTION_PROTOCOL_VERSION ||\n snapshot.snapshotVersion !== SPREADSHEET_COLLABORATION_SNAPSHOT_VERSION)) ||\n snapshot.modelSchemaVersion !== adapter.modelSchemaVersion\n ) {\n throw runtimeError(\n \"unsupported_protocol\",\n \"snapshot protocol/schema is incompatible with the loaded collaboration kernel\",\n );\n }\n const digest = await sha256Hex(ownedBytes);\n this.throwIfCancelled(frame.requestId);\n if (digest !== snapshot.digest) {\n throw runtimeError(\"byte_corruption\", \"snapshot digest does not match its bytes\");\n }\n const canonical = requireBytesWithin(\n adapter.canonicalizeSnapshot(ownedBytes),\n initialization.maximumSnapshotBytes,\n \"canonical snapshot\",\n );\n if (!bytesEqual(canonical, ownedBytes)) {\n throw runtimeError(\n \"noncanonical_snapshot\",\n \"server snapshot bytes are not canonical; refusing to persist a different model\",\n );\n }\n const nextConfirmed = adapter.open(canonical);\n let nextSpeculative: ArtifactWorkerKernelSession | null = null;\n let stateHash: string;\n try {\n stateHash = await nextConfirmed.stateHash();\n this.throwIfCancelled(frame.requestId);\n if (stateHash !== snapshot.stateHash) {\n throw runtimeError(\n \"authored_causal_mismatch\",\n \"snapshot authored state does not match its state hash\",\n );\n }\n if (\n snapshot.modality !== \"spreadsheet\" &&\n nextConfirmed.nativeRevision() !== snapshot.nativeRevision\n ) {\n throw runtimeError(\n \"kernel_diverged\",\n \"serialized snapshot native revision does not match the WASM session\",\n );\n }\n nextSpeculative = nextConfirmed.fork();\n this.throwIfCancelled(frame.requestId);\n } catch (error) {\n this.disposeSession(nextConfirmed);\n this.disposeSession(nextSpeculative);\n throw error;\n }\n if (!nextSpeculative) throw runtimeError(\"kernel_failed\", \"kernel fork was not created\");\n this.installSessions(\n nextConfirmed,\n nextSpeculative,\n snapshot.modality === \"spreadsheet\"\n ? {\n artifactId: snapshot.artifactId,\n modality: \"spreadsheet\",\n sequence: snapshot.sequence,\n protocolVersion: adapter.protocolVersion,\n kernelVersion: snapshot.kernelVersion,\n modelSchemaVersion: snapshot.modelSchemaVersion,\n stateHash,\n causalFrontier: snapshot.causalFrontier,\n }\n : {\n artifactId: snapshot.artifactId,\n modality: snapshot.modality,\n sequence: snapshot.sequence,\n protocolVersion: adapter.protocolVersion,\n kernelVersion: snapshot.kernelVersion,\n modelSchemaVersion: snapshot.modelSchemaVersion,\n stateHash,\n nativeRevision: snapshot.nativeRevision,\n },\n Object.freeze([]),\n Object.freeze([]),\n );\n this.respond(frame.requestId, encodeStateResponse(stateHash, digest));\n }\n\n private async applyRecovered(\n frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>,\n ): Promise<void> {\n const initialization = this.requireInitialization();\n if (frame.segments.length !== 1) {\n throw runtimeError(\"invalid_segment\", \"recovered transaction requires one operation segment\");\n }\n const committedTransactionBytes = requireBytesWithin(\n frame.segments[0]!,\n initialization.maximumCommittedTransactionBytes,\n \"committed transaction\",\n );\n const transaction = decodeCommittedMetadata(frame.metadata, committedTransactionBytes);\n const result = await this.buildCommittedCandidate(transaction, [], frame.requestId);\n this.installCommittedCandidate(result, transaction, []);\n this.respond(frame.requestId, encodeStateResponse(result.stateHash));\n }\n\n private async reconcileCommitted(\n frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>,\n ): Promise<void> {\n const initialization = this.requireInitialization();\n const decoded = decodeReconcileMetadata(\n frame.metadata,\n frame.segments,\n initialization.maximumPendingTransactions,\n );\n requireBytesWithin(\n decoded.committed.committedTransactionBytes,\n initialization.maximumCommittedTransactionBytes,\n \"committed transaction\",\n );\n await this.validatePending(decoded.pending);\n const result = await this.buildCommittedCandidate(\n decoded.committed,\n decoded.pending,\n frame.requestId,\n );\n this.installCommittedCandidate(result, decoded.committed, decoded.pending);\n this.respond(\n frame.requestId,\n encodeProjectionResponse(result.blockedPending, result.stateHash),\n );\n }\n\n private async replacePending(\n frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>,\n ): Promise<void> {\n const initialization = this.requireInitialization();\n const pending = decodePendingListMetadata(\n frame.metadata,\n frame.segments,\n initialization.maximumPendingTransactions,\n );\n await this.validatePending(pending);\n const keys = pending.map(pendingKey);\n if (arraysEqual(keys, this.pendingKeys)) {\n this.respond(frame.requestId, encodeProjectionResponse(this.blockedPending));\n return;\n }\n const candidate = this.requireConfirmed().fork();\n let blockedPending: readonly EditableArtifactBlockedPending[];\n try {\n blockedPending = this.applyPending(candidate, pending, frame.requestId);\n this.throwIfCancelled(frame.requestId);\n } catch (error) {\n this.disposeSession(candidate);\n throw error;\n }\n const previous = this.speculative;\n this.speculative = candidate;\n this.pendingKeys = Object.freeze(keys);\n this.blockedPending = blockedPending;\n this.disposeSession(previous);\n this.respond(frame.requestId, encodeProjectionResponse(blockedPending));\n }\n\n private async authorPending(\n frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>,\n ): Promise<void> {\n const initialization = this.requireInitialization();\n const adapter = this.requireAdapter();\n if (frame.segments.length !== 1)\n throw runtimeError(\"invalid_segment\", \"author requires one command segment\");\n const commandBytes = requireBytesWithin(\n frame.segments[0]!,\n initialization.maximumCommandBytes,\n \"pending command\",\n );\n const input = decodeAuthorPendingMetadata(frame.metadata, commandBytes);\n if (\n input.modality !== initialization.modality ||\n input.modality !== adapter.modality ||\n input.protocolVersion !== adapter.protocolVersion ||\n input.kernelVersion !== adapter.kernelVersion ||\n input.modelSchemaVersion !== adapter.modelSchemaVersion ||\n input.commandVersion !== adapter.commandVersion\n ) {\n throw runtimeError(\n \"unsupported_protocol\",\n \"pending authoring versions are incompatible with the loaded kernel\",\n );\n }\n if (this.installed && input.artifactId !== this.installed.artifactId) {\n throw runtimeError(\"artifact_mismatch\", \"pending transaction belongs to another artifact\");\n }\n try {\n if (input.modality === \"spreadsheet\") {\n assertCanonicalSpreadsheetArtifactCommandBytes(commandBytes);\n } else {\n editableArtifactCodecFor({\n durableModality: input.modality,\n modelSchemaVersion: input.modelSchemaVersion,\n commandProtocolVersion: input.commandVersion,\n }).command.assertCanonical(commandBytes);\n }\n } catch (error) {\n throw runtimeError(\n \"noncanonical_command\",\n `pending ${input.modality} command must be canonical before it receives an identity: ${\n error instanceof Error ? error.message : \"invalid command\"\n }`,\n );\n }\n const canonicalCommand = commandBytes;\n const authored = authorCanonicalPendingIntent(input, canonicalCommand);\n const intentBytes = requireBytesWithin(\n authored.bytes,\n EDITABLE_ARTIFACT_INTENT_MAX_BYTES,\n \"OGATX001 intent\",\n );\n this.throwIfCancelled(frame.requestId);\n const commonPending = {\n artifactId: input.artifactId,\n clientTransactionId: input.clientTransactionId,\n requestHash: authored.requestHash,\n protocolVersion: input.protocolVersion,\n modelSchemaVersion: input.modelSchemaVersion,\n commandVersion: input.commandVersion,\n replicaId: input.replicaId,\n replicaCounter: input.replicaCounter,\n previousLocalTransactionId: input.previousLocalTransactionId,\n observedHeadSequence: input.observedHeadSequence,\n commandBytes: canonicalCommand,\n intentBytes,\n createdAt: input.createdAt,\n } as const;\n let pending: EditableArtifactPendingTransaction;\n if (input.modality === \"spreadsheet\") {\n pending = Object.freeze({\n ...commonPending,\n modality: \"spreadsheet\",\n causalBase: input.causalBase ?? [],\n selectiveUndoTargets: input.selectiveUndoTargets ?? [],\n });\n } else {\n const installed = this.requireInstalled();\n if (installed.modality !== input.modality) {\n throw runtimeError(\"modality_mismatch\", \"pending modality does not match installed state\");\n }\n const expectedHeadSequence = installed.sequence + this.pendingKeys.length;\n if (input.observedHeadSequence !== expectedHeadSequence) {\n throw runtimeError(\n \"serialized_head_conflict\",\n \"serialized pending command was not authored over the speculative head\",\n );\n }\n pending = Object.freeze({\n ...commonPending,\n modality: input.modality,\n observedNativeRevision: this.requireSpeculative().nativeRevision(),\n });\n }\n const metadata = encodePendingListMetadata([pending]);\n // Both buffers are exclusively Worker-owned here: the command arrived by\n // transfer and OGATX authoring allocated the intent. Return them without a\n // second multi-megabyte copy.\n const command = transferableOwnedBuffer(canonicalCommand);\n const intent = transferableOwnedBuffer(intentBytes);\n this.respond(frame.requestId, metadata, [command, intent]);\n }\n\n private queryArtifact(frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>): void {\n if (frame.metadata.byteLength !== 0 || frame.segments.length !== 1) {\n throw runtimeError(\"invalid_segment\", \"artifact query requires one byte segment\");\n }\n const initialization = this.requireInitialization();\n const queryBytes = requireBytesWithin(\n frame.segments[0]!,\n initialization.maximumQueryBytes,\n `${initialization.modality} query`,\n );\n const result = requireBytesWithin(\n this.requireSpeculative().query(queryBytes),\n initialization.maximumQueryResponseBytes,\n `${initialization.modality} projection`,\n );\n this.throwIfCancelled(frame.requestId);\n this.respond(frame.requestId, undefined, [transferableOwnedBuffer(result)]);\n }\n\n private async buildCommittedCandidate(\n transaction: EditableArtifactCommittedTransaction,\n remainingPending: readonly EditableArtifactPendingTransaction[],\n requestId: number,\n ): Promise<{\n confirmed: ArtifactWorkerKernelSession;\n speculative: ArtifactWorkerKernelSession;\n stateHash: string;\n blockedPending: readonly EditableArtifactBlockedPending[];\n }> {\n const installed = this.requireInstalled();\n if (transaction.artifactId !== installed.artifactId) {\n throw runtimeError(\"artifact_mismatch\", \"committed transaction belongs to another artifact\");\n }\n if (transaction.modality !== installed.modality) {\n throw runtimeError(\"modality_mismatch\", \"committed transaction modality is incompatible\");\n }\n if (\n transaction.modality === \"spreadsheet\" &&\n transaction.operationProtocolVersion !== COMMITTED_TRANSACTION_PROTOCOL_VERSION\n )\n throw runtimeError(\"unsupported_protocol\", \"committed transaction protocol is incompatible\");\n if (transaction.startSequence !== installed.sequence + 1) {\n throw runtimeError(\"invalid_sequence\", \"committed transaction is not contiguous\");\n }\n assertCommittedEnvelopeMatchesOuter(transaction);\n if (transaction.modality === \"spreadsheet\" && installed.modality === \"spreadsheet\") {\n requireFrontierAdvance(installed.causalFrontier, transaction.causalFrontier);\n } else if (transaction.modality !== \"spreadsheet\" && installed.modality !== \"spreadsheet\") {\n if (transaction.priorNativeRevision !== installed.nativeRevision) {\n throw runtimeError(\"invalid_revision\", \"serialized commit prior revision is not current\");\n }\n }\n requireMatchingHash(installed.stateHash, transaction.priorStateHash, \"transaction prior state\");\n const nextConfirmed = this.requireConfirmed().fork();\n let nextSpeculative: ArtifactWorkerKernelSession | null = null;\n try {\n if (transaction.modality === \"spreadsheet\") {\n nextConfirmed.applyCommitted(transaction.committedTransactionBytes);\n } else {\n const summary = decodeEditableArtifactSerializedCommit(\n transaction.committedTransactionBytes,\n transaction.modality,\n );\n const intent = decodeEditableArtifactMutationIntent(summary.intentBytes);\n const nativeReceipt = nextConfirmed.applyCommands(intent.commandBytes);\n if (!bytesEqual(nativeReceipt, summary.nativeReceiptBytes)) {\n throw runtimeError(\n \"kernel_diverged\",\n \"WASM native receipt differs from the exact durable OGAST receipt\",\n );\n }\n if (nextConfirmed.nativeRevision() !== transaction.nativeRevision) {\n throw runtimeError(\n \"kernel_diverged\",\n \"WASM native revision differs from the exact durable OGAST revision\",\n );\n }\n }\n const stateHash = await nextConfirmed.stateHash();\n this.throwIfCancelled(requestId);\n requireMatchingHash(stateHash, transaction.stateHash, \"committed state\");\n nextSpeculative = nextConfirmed.fork();\n const blockedPending = this.applyPending(\n nextSpeculative,\n remainingPending,\n requestId,\n transaction.endSequence,\n );\n this.throwIfCancelled(requestId);\n return {\n confirmed: nextConfirmed,\n speculative: nextSpeculative,\n stateHash,\n blockedPending,\n };\n } catch (error) {\n this.disposeSession(nextConfirmed);\n this.disposeSession(nextSpeculative);\n throw error;\n }\n }\n\n private installCommittedCandidate(\n candidate: {\n confirmed: ArtifactWorkerKernelSession;\n speculative: ArtifactWorkerKernelSession;\n stateHash: string;\n blockedPending: readonly EditableArtifactBlockedPending[];\n },\n transaction: EditableArtifactCommittedTransaction,\n pending: readonly EditableArtifactPendingTransaction[],\n ): void {\n const installed = this.requireInstalled();\n this.installSessions(\n candidate.confirmed,\n candidate.speculative,\n transaction.modality === \"spreadsheet\"\n ? {\n ...installed,\n modality: \"spreadsheet\",\n sequence: transaction.endSequence,\n stateHash: candidate.stateHash,\n causalFrontier: transaction.causalFrontier,\n }\n : {\n ...installed,\n modality: transaction.modality,\n sequence: transaction.endSequence,\n stateHash: candidate.stateHash,\n nativeRevision: transaction.nativeRevision,\n },\n Object.freeze(pending.map(pendingKey)),\n candidate.blockedPending,\n );\n }\n\n private applyPending(\n session: ArtifactWorkerKernelSession,\n pending: readonly EditableArtifactPendingTransaction[],\n requestId: number,\n baseSequence = this.requireInstalled().sequence,\n ): readonly EditableArtifactBlockedPending[] {\n const blocked: EditableArtifactBlockedPending[] = [];\n const blockedIds = new Set<string>();\n for (const transaction of pending) {\n this.throwIfCancelled(requestId);\n if (\n transaction.previousLocalTransactionId !== null &&\n blockedIds.has(transaction.previousLocalTransactionId)\n ) {\n blockedIds.add(transaction.clientTransactionId);\n blocked.push(\n Object.freeze({\n clientTransactionId: transaction.clientTransactionId,\n code: \"blocked_predecessor\",\n }),\n );\n continue;\n }\n try {\n if (transaction.modality === \"spreadsheet\") {\n session.applyPending(transaction.intentBytes);\n } else {\n if (\n transaction.observedHeadSequence !== baseSequence ||\n transaction.observedNativeRevision !== session.nativeRevision()\n ) {\n throw new ArtifactWorkerPendingProjectionError(\n \"serialized_head_conflict\",\n \"serialized pending transaction is stale\",\n );\n }\n session.applyCommands(transaction.commandBytes);\n baseSequence += 1;\n }\n } catch (error) {\n if (!(error instanceof ArtifactWorkerPendingProjectionError)) throw error;\n blockedIds.add(transaction.clientTransactionId);\n blocked.push(\n Object.freeze({ clientTransactionId: transaction.clientTransactionId, code: error.code }),\n );\n }\n }\n return Object.freeze(blocked);\n }\n\n private async validatePending(\n pending: readonly EditableArtifactPendingTransaction[],\n ): Promise<void> {\n const initialization = this.requireInitialization();\n const installed = this.requireInstalled();\n const adapter = this.requireAdapter();\n const ids = new Set<string>();\n let aggregateBytes = 0;\n for (const transaction of pending) {\n if (transaction.artifactId !== installed.artifactId) {\n throw runtimeError(\"artifact_mismatch\", \"pending transaction belongs to another artifact\");\n }\n if (transaction.modality !== installed.modality) {\n throw runtimeError(\"modality_mismatch\", \"pending transaction modality is incompatible\");\n }\n if (\n transaction.protocolVersion !== installed.protocolVersion ||\n transaction.modelSchemaVersion !== installed.modelSchemaVersion ||\n transaction.commandVersion !== adapter.commandVersion\n ) {\n throw runtimeError(\n \"unsupported_protocol\",\n \"pending transaction versions are incompatible with confirmed state\",\n );\n }\n if (ids.has(transaction.clientTransactionId)) {\n throw runtimeError(\"duplicate_transaction\", \"pending transaction id is duplicated\");\n }\n ids.add(transaction.clientTransactionId);\n requireBytesWithin(\n transaction.commandBytes,\n initialization.maximumCommandBytes,\n \"pending command\",\n );\n requireBytesWithin(\n transaction.intentBytes,\n initialization.maximumIntentBytes,\n \"pending intent\",\n );\n try {\n if (transaction.modality === \"spreadsheet\") {\n assertCanonicalSpreadsheetArtifactCommandBytes(transaction.commandBytes);\n } else {\n editableArtifactCodecFor({\n durableModality: transaction.modality,\n modelSchemaVersion: transaction.modelSchemaVersion,\n commandProtocolVersion: transaction.commandVersion,\n }).command.assertCanonical(transaction.commandBytes);\n }\n } catch (error) {\n throw new ArtifactWorkerProtocolError(\n \"noncanonical_command\",\n `pending transaction contains noncanonical ${transaction.modality} command bytes`,\n { cause: error },\n );\n }\n verifyCanonicalPendingIntent(transaction);\n aggregateBytes += transaction.commandBytes.byteLength + transaction.intentBytes.byteLength;\n if (!Number.isSafeInteger(aggregateBytes) || aggregateBytes > MAX_PENDING_AGGREGATE_BYTES) {\n throw runtimeError(\"limit_exceeded\", \"pending commands exceed their aggregate byte limit\");\n }\n }\n }\n\n private installSessions(\n confirmed: ArtifactWorkerKernelSession,\n speculative: ArtifactWorkerKernelSession,\n installed: InstalledState,\n pendingKeys: readonly string[],\n blockedPending: readonly EditableArtifactBlockedPending[],\n ): void {\n const previousConfirmed = this.confirmed;\n const previousSpeculative = this.speculative;\n this.confirmed = confirmed;\n this.speculative = speculative;\n this.installed = Object.freeze(installed);\n this.pendingKeys = pendingKeys;\n this.blockedPending = blockedPending;\n this.disposeSession(previousConfirmed);\n this.disposeSession(previousSpeculative);\n }\n\n private releaseState(): void {\n const confirmed = this.confirmed;\n const speculative = this.speculative;\n this.confirmed = null;\n this.speculative = null;\n this.installed = null;\n this.pendingKeys = Object.freeze([]);\n this.blockedPending = Object.freeze([]);\n this.disposeSession(confirmed);\n this.disposeSession(speculative);\n }\n\n private disposeSession(session: ArtifactWorkerKernelSession | null): void {\n if (!session) return;\n try {\n session.dispose();\n } catch (error) {\n this.reportProtocolError(asProtocolError(error));\n }\n }\n\n private disposeAdapter(adapter: ArtifactWorkerKernelAdapter | null): void {\n if (!adapter?.dispose) return;\n try {\n adapter.dispose();\n } catch (error) {\n this.reportProtocolError(asProtocolError(error));\n }\n }\n\n private reportProtocolError(error: ArtifactWorkerProtocolError): void {\n try {\n this.onProtocolError?.(error);\n } catch {\n // Diagnostics must never acquire authority over Worker state or cleanup.\n }\n }\n\n private requireNoPayload(frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>): void {\n if (frame.metadata.byteLength !== 0 || frame.segments.length !== 0) {\n throw runtimeError(\"unexpected_payload\", \"RPC operation must not contain a payload\");\n }\n }\n\n private requireInitialized(generation: number): void {\n if (this.generation === null || this.adapter === null || this.initialization === null) {\n throw runtimeError(\"not_initialized\", \"artifact Worker is not initialized\");\n }\n if (generation !== this.generation) {\n throw runtimeError(\"stale_generation\", \"RPC belongs to a retired Worker generation\");\n }\n }\n\n private requireInitialization(): ArtifactWorkerInitializeInput {\n if (!this.initialization)\n throw runtimeError(\"not_initialized\", \"artifact Worker is not initialized\");\n return this.initialization;\n }\n\n private requireAdapter(): ArtifactWorkerKernelAdapter {\n if (!this.adapter) throw runtimeError(\"not_initialized\", \"artifact Worker is not initialized\");\n return this.adapter;\n }\n\n private requireConfirmed(): ArtifactWorkerKernelSession {\n if (!this.confirmed)\n throw runtimeError(\"snapshot_required\", \"artifact Worker has no confirmed state\");\n return this.confirmed;\n }\n\n private requireSpeculative(): ArtifactWorkerKernelSession {\n if (!this.speculative) {\n throw runtimeError(\"snapshot_required\", \"artifact Worker has no speculative state\");\n }\n return this.speculative;\n }\n\n private requireInstalled(): InstalledState {\n if (!this.installed)\n throw runtimeError(\"snapshot_required\", \"artifact Worker has no installed snapshot\");\n return this.installed;\n }\n\n private throwIfCancelled(requestId: number): void {\n if (this.cancelled.has(requestId))\n throw runtimeError(\"cancelled\", \"artifact Worker request was cancelled\");\n }\n\n private respond(requestId: number, metadata?: Uint8Array, segments?: ArrayBuffer[]): void {\n if (this.generation === null || this.cancelled.has(requestId)) return;\n const response = encodeArtifactWorkerRpcMessage({\n kind: ArtifactWorkerRpcKind.Response,\n generation: this.generation,\n requestId,\n ...(metadata ? { metadata } : {}),\n ...(segments ? { segments } : {}),\n ...(this.rpcLimits ? { limits: this.rpcLimits } : {}),\n });\n this.endpoint.postMessage(response, transferListForArtifactWorkerRpcMessage(response));\n }\n\n private respondError(requestId: number, error: unknown, generation = this.generation): void {\n if (generation === null || this.cancelled.has(requestId)) return;\n const failure = asWorkerFailure(error);\n const response = encodeArtifactWorkerRpcMessage({\n kind: ArtifactWorkerRpcKind.Error,\n generation,\n requestId,\n metadata: encodeErrorPayload(failure),\n ...(this.rpcLimits ? { limits: this.rpcLimits } : {}),\n });\n this.endpoint.postMessage(response, transferListForArtifactWorkerRpcMessage(response));\n }\n}\n\nfunction authorCanonicalPendingIntent(\n input: ArtifactWorkerAuthorPendingInput,\n canonicalCommand: Uint8Array,\n): { bytes: Uint8Array; requestHash: string } {\n try {\n return hashEditableArtifactMutationIntent(canonicalMutationIntent(input, canonicalCommand));\n } catch (error) {\n throw new ArtifactWorkerProtocolError(\n \"invalid_intent\",\n \"pending transaction cannot be represented by canonical OGATX001\",\n { cause: error },\n );\n }\n}\n\nfunction transferableOwnedBuffer(bytes: Uint8Array): ArrayBuffer {\n if (\n bytes.buffer instanceof ArrayBuffer &&\n bytes.byteOffset === 0 &&\n bytes.byteLength === bytes.buffer.byteLength\n ) {\n return bytes.buffer;\n }\n return bytes.slice().buffer;\n}\n\nfunction verifyCanonicalPendingIntent(transaction: EditableArtifactPendingTransaction): void {\n let expected: { bytes: Uint8Array; requestHash: string };\n try {\n expected = hashEditableArtifactMutationIntent(\n canonicalMutationIntent(transaction, transaction.commandBytes),\n );\n } catch (error) {\n throw new ArtifactWorkerProtocolError(\n \"intent_mismatch\",\n \"pending transaction metadata is not valid canonical OGATX001 input\",\n { cause: error },\n );\n }\n if (\n expected.requestHash !== transaction.requestHash ||\n !bytesEqual(expected.bytes, transaction.intentBytes)\n ) {\n throw runtimeError(\n \"intent_mismatch\",\n \"pending transaction bytes do not bind its exact metadata and command\",\n );\n }\n}\n\nfunction assertAdapterCompatibility(\n adapter: ArtifactWorkerKernelAdapter,\n initialization: ArtifactWorkerInitializeInput,\n): void {\n if (adapter.modality !== initialization.modality) {\n throw runtimeError(\"modality_mismatch\", \"loaded kernel modality does not match initialization\");\n }\n if (\n adapter.kernelVersion !== initialization.kernelVersion ||\n adapter.protocolVersion !== initialization.protocolVersion ||\n adapter.modelSchemaVersion !== initialization.modelSchemaVersion ||\n adapter.commandVersion !== initialization.commandVersion\n ) {\n throw runtimeError(\n \"runtime_identity_mismatch\",\n \"loaded kernel build/protocol/model identity does not match its package\",\n );\n }\n const limits = [\n [adapter.maximumSnapshotBytes, initialization.maximumSnapshotBytes, \"snapshot\"],\n [adapter.maximumCommandBytes, initialization.maximumCommandBytes, \"command\"],\n [adapter.maximumIntentBytes, initialization.maximumIntentBytes, \"intent\"],\n [\n adapter.maximumCommittedTransactionBytes,\n initialization.maximumCommittedTransactionBytes,\n \"committed transaction\",\n ],\n [adapter.maximumQueryBytes, initialization.maximumQueryBytes, \"query\"],\n [adapter.maximumQueryResponseBytes, initialization.maximumQueryResponseBytes, \"query response\"],\n ] as const;\n for (const [advertised, requested, label] of limits) {\n if (advertised < requested) {\n throw runtimeError(\n \"unsupported_protocol\",\n `loaded collaboration kernel ${label} limit is below the requested Worker limit`,\n );\n }\n }\n}\n\n/**\n * Outer delivery/index fields remain useful for storage and routing, but every\n * semantic field duplicated by OGACO must agree exactly before Rust sees it.\n */\nfunction assertCommittedEnvelopeMatchesOuter(\n transaction: EditableArtifactCommittedTransaction,\n): void {\n if (transaction.modality !== \"spreadsheet\") {\n let summary: ReturnType<typeof decodeEditableArtifactSerializedCommit>;\n try {\n summary = decodeEditableArtifactSerializedCommit(\n transaction.committedTransactionBytes,\n transaction.modality,\n );\n } catch (error) {\n throw new ArtifactWorkerProtocolError(\n \"invalid_committed_transaction\",\n \"committed transaction is not canonical OGAST001\",\n { cause: error },\n );\n }\n if (\n summary.commitProtocolVersion !== transaction.commitProtocolVersion ||\n summary.transactionId !== transaction.transactionId ||\n summary.requestHash !== transaction.requestHash ||\n summary.parentHeadSequence + 1 !== transaction.startSequence ||\n summary.resultHeadSequence !== transaction.endSequence ||\n summary.priorNativeRevision !== transaction.priorNativeRevision ||\n summary.nativeReceipt.revision !== transaction.nativeRevision ||\n summary.priorStateHash !== transaction.priorStateHash ||\n summary.stateHash !== transaction.stateHash\n ) {\n throw runtimeError(\n \"committed_metadata_mismatch\",\n \"outer committed metadata disagrees with its exact OGAST001 envelope\",\n );\n }\n return;\n }\n let summary: ReturnType<typeof decodeCommittedTransactionSummary>;\n try {\n summary = decodeCommittedTransactionSummary(transaction.committedTransactionBytes);\n } catch (error) {\n throw new ArtifactWorkerProtocolError(\n \"invalid_committed_transaction\",\n \"committed transaction is not canonical OGACO002\",\n { cause: error },\n );\n }\n if (\n summary.operationProtocolVersion !== transaction.operationProtocolVersion ||\n summary.transactionId !== transaction.transactionId ||\n summary.priorStateHash !== transaction.priorStateHash ||\n summary.stateHash !== transaction.stateHash ||\n !frontiersEqual(summary.resultingCausalFrontier, transaction.causalFrontier)\n ) {\n throw runtimeError(\n \"committed_metadata_mismatch\",\n \"outer committed metadata disagrees with its exact OGACO002 envelope\",\n );\n }\n}\n\nfunction frontiersEqual(\n left: readonly Readonly<{ replicaId: string; counter: number }>[],\n right: EditableArtifactCausalFrontier,\n): boolean {\n return (\n left.length === right.length &&\n left.every(\n (entry, index) =>\n entry.replicaId === right[index]?.replicaId && entry.counter === right[index]?.counter,\n )\n );\n}\n\nfunction canonicalMutationIntent(\n input: ArtifactWorkerAuthorPendingInput | EditableArtifactPendingTransaction,\n commandBytes: Uint8Array,\n) {\n return {\n envelopeVersion: EDITABLE_ARTIFACT_INTENT_VERSION,\n protocolVersion: input.protocolVersion,\n modelSchemaVersion: input.modelSchemaVersion,\n commandProtocolVersion: input.commandVersion,\n artifactId: input.artifactId,\n clientTransactionId: input.clientTransactionId,\n replicaId: input.replicaId,\n replicaCounter: input.replicaCounter,\n previousLocalTransactionId: input.previousLocalTransactionId,\n observedHeadSequence: input.observedHeadSequence,\n causalBase: input.modality === \"spreadsheet\" ? (input.causalBase ?? []) : [],\n selectiveUndoOperationIds:\n input.modality === \"spreadsheet\" ? (input.selectiveUndoTargets ?? []) : [],\n commandBytes,\n } as const;\n}\n\nfunction retainedFrameBytes(frame: ReturnType<typeof decodeArtifactWorkerRpcMessage>): number {\n let bytes = frame.metadata.byteLength;\n for (const segment of frame.segments) bytes += segment.byteLength;\n if (!Number.isSafeInteger(bytes)) {\n throw runtimeError(\"size_overflow\", \"artifact Worker request byte count overflowed\");\n }\n return bytes;\n}\n\nfunction requireBytesWithin(bytes: Uint8Array, maximum: number, label: string): Uint8Array {\n if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) {\n throw runtimeError(\"invalid_bytes\", `${label} must be non-empty bytes`);\n }\n if (bytes.byteLength > maximum)\n throw runtimeError(\"limit_exceeded\", `${label} exceeds its byte limit`);\n return bytes;\n}\n\nfunction pendingKey(transaction: EditableArtifactPendingTransaction): string {\n return `${transaction.clientTransactionId}\\0${transaction.requestHash}`;\n}\n\nfunction arraysEqual(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index]);\n}\n\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n if (left.byteLength !== right.byteLength) return false;\n for (let index = 0; index < left.byteLength; index += 1) {\n if (left[index] !== right[index]) return false;\n }\n return true;\n}\n\nfunction requireFrontierAdvance(\n previous: EditableArtifactCausalFrontier,\n next: EditableArtifactCausalFrontier,\n): void {\n const nextByReplica = new Map(next.map((entry) => [entry.replicaId, entry.counter]));\n for (const entry of previous) {\n if ((nextByReplica.get(entry.replicaId) ?? -1) < entry.counter) {\n throw runtimeError(\"invalid_frontier\", \"committed causal frontier regresses\");\n }\n }\n}\n\ntype WorkerFailure = { code: string; message: string; retryable: boolean };\n\nfunction asWorkerFailure(error: unknown): WorkerFailure {\n if (error instanceof ArtifactWorkerProtocolError) {\n return {\n code: normalizeErrorCode(error.code),\n message: sanitizeErrorMessage(error.message),\n retryable: false,\n };\n }\n if (error instanceof Error) {\n const rawCode = (error as Error & { code?: unknown }).code;\n return {\n code: typeof rawCode === \"string\" ? normalizeErrorCode(rawCode) : \"kernel_failed\",\n message: sanitizeErrorMessage(error.message || \"artifact kernel failed\"),\n retryable: false,\n };\n }\n return { code: \"kernel_failed\", message: \"artifact kernel failed\", retryable: false };\n}\n\nfunction asProtocolError(error: unknown): ArtifactWorkerProtocolError {\n if (error instanceof ArtifactWorkerProtocolError) return error;\n return new ArtifactWorkerProtocolError(\n \"runtime_failed\",\n error instanceof Error ? error.message : \"artifact Worker runtime failed\",\n { cause: error },\n );\n}\n\nfunction normalizeErrorCode(value: string): string {\n const normalized = value.toLowerCase();\n return /^[a-z][a-z0-9_]{0,127}$/.test(normalized) ? normalized : \"kernel_failed\";\n}\n\nfunction sanitizeErrorMessage(value: string): string {\n let output = \"\";\n for (let index = 0; index < value.length && output.length < 2_000; index += 1) {\n const code = value.charCodeAt(index);\n if (code >= 0xd800 && code <= 0xdbff) {\n const following = value.charCodeAt(index + 1);\n if (following >= 0xdc00 && following <= 0xdfff) {\n output += value[index]! + value[index + 1]!;\n index += 1;\n } else {\n output += \"\\ufffd\";\n }\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n output += \"\\ufffd\";\n } else {\n output += value[index]!;\n }\n }\n return output || \"artifact kernel failed\";\n}\n\nfunction runtimeError(code: string, message: string): ArtifactWorkerProtocolError {\n return new ArtifactWorkerProtocolError(code, message);\n}\n","import { loadBrowserWasmKernelAdapter } from \"./kernel-adapter\";\nimport {\n ArtifactWorkerRuntime,\n type ArtifactWorkerMessageEvent,\n type ArtifactWorkerRuntimeEndpoint,\n} from \"./runtime\";\nimport type { ArtifactWorkerRpcMessage } from \"./rpc-protocol\";\n\ntype WorkerScopeCandidate = {\n document?: unknown;\n addEventListener?: unknown;\n removeEventListener?: unknown;\n postMessage?: unknown;\n};\n\n/**\n * Dedicated module-Worker entry. Hosts bundle and self-host this file under\n * their CSP, then pass its URL to `createBrowserEditableArtifactWorkerKernel`.\n */\nexport function installBrowserArtifactWorkerEntry(\n scope: ArtifactWorkerRuntimeEndpoint,\n): ArtifactWorkerRuntime {\n return new ArtifactWorkerRuntime({ endpoint: scope, loadAdapter: loadBrowserWasmKernelAdapter });\n}\n\nconst candidate = globalThis as WorkerScopeCandidate;\nif (\n candidate.document === undefined &&\n typeof candidate.addEventListener === \"function\" &&\n typeof candidate.removeEventListener === \"function\" &&\n typeof candidate.postMessage === \"function\"\n) {\n installBrowserArtifactWorkerEntry({\n addEventListener(type, listener) {\n (\n candidate.addEventListener as (\n event: string,\n callback: (event: ArtifactWorkerMessageEvent) => void,\n ) => void\n )(type, listener);\n },\n removeEventListener(type, listener) {\n (\n candidate.removeEventListener as (\n event: string,\n callback: (event: ArtifactWorkerMessageEvent) => void,\n ) => void\n )(type, listener);\n },\n postMessage(message: ArtifactWorkerRpcMessage, transfer: Transferable[]) {\n (candidate.postMessage as (message: unknown, transfer: Transferable[]) => void)(\n message,\n transfer,\n );\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AA0BA,IAAM,uCAAN,cAAmD,MAAM;AAAA,EACrD;AAAA,EAET,YAAY,MAAc,UAAU,2DAA2D;AAC7F,UAAM,OAAO;AACb,SAAK,OAAO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,iBAAiB,MAAM,UAAU;AAC/B,MACE,UAAU,iBAIV,MAAM,QAAQ;AAAA,IAClB;AAAA,IACA,oBAAoB,MAAM,UAAU;AAClC,MACE,UAAU,oBAIV,MAAM,QAAQ;AAAA,IAClB;AAAA,IACA,YAAY,SAAmC,UAA0B;AACvE,MAAC,UAAU;AAAA,QACT;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACH;","names":["EDITABLE_ARTIFACT_INTENT_MAX_BYTES","EDITABLE_ARTIFACT_INTENT_VERSION","COMMITTED_TRANSACTION_PROTOCOL_VERSION","SPREADSHEET_COLLABORATION_SNAPSHOT_VERSION","COMMITTED_TRANSACTION_PROTOCOL_VERSION","SPREADSHEET_COLLABORATION_SNAPSHOT_VERSION","candidate","EDITABLE_ARTIFACT_INTENT_MAX_BYTES","summary","EDITABLE_ARTIFACT_INTENT_VERSION"]}
|