@opengeni/api-router 0.23.1 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/dist/app.d.ts +3 -2
  2. package/dist/app.js +5 -3
  3. package/dist/auth/canonical-human-session-admission.d.ts +27 -0
  4. package/dist/browser-auth-broker.d.ts +20 -0
  5. package/dist/browser-controller-authority.d.ts +61 -0
  6. package/dist/browser-network-route.d.ts +8 -0
  7. package/dist/browser-state-authority.d.ts +27 -0
  8. package/dist/{chunk-T4T2PGU4.js → chunk-2PQMSRCB.js} +37891 -17463
  9. package/dist/chunk-2PQMSRCB.js.map +1 -0
  10. package/dist/codemode.d.ts +23 -0
  11. package/dist/controller-data-plane.d.ts +12 -0
  12. package/dist/editable-artifact-live-hints.d.ts +11 -0
  13. package/dist/editable-artifact-native-kernel.d.ts +37 -0
  14. package/dist/editable-artifact-office-import.d.ts +22 -0
  15. package/dist/editable-artifact-production.d.ts +29 -0
  16. package/dist/editable-artifact-websocket.d.ts +49 -0
  17. package/dist/editable-artifact-workspace-files.d.ts +23 -0
  18. package/dist/github-browser-flow.d.ts +6 -0
  19. package/dist/http/auth.d.ts +1 -1
  20. package/dist/http/cors.d.ts +1 -0
  21. package/dist/http/sse.d.ts +18 -1
  22. package/dist/index.d.ts +3 -2
  23. package/dist/index.js +1796 -22
  24. package/dist/index.js.map +1 -1
  25. package/dist/integrations/api-integrations.d.ts +24 -0
  26. package/dist/integrations/atlassian.d.ts +176 -0
  27. package/dist/integrations/fiken.d.ts +233 -0
  28. package/dist/integrations/github-skill-source.d.ts +5 -0
  29. package/dist/integrations/google-drive.d.ts +85 -0
  30. package/dist/integrations/oauth-client.d.ts +22 -1
  31. package/dist/integrations/provider-oauth.d.ts +17 -0
  32. package/dist/integrations/slack-bot.d.ts +175 -1
  33. package/dist/integrations/slack-interactions.d.ts +24 -6
  34. package/dist/integrations/social-api.d.ts +2 -1
  35. package/dist/interaction-holder-heartbeat.d.ts +17 -0
  36. package/dist/interaction-metrics.d.ts +11 -0
  37. package/dist/mcp/editable-artifact-query-schema.d.ts +4 -0
  38. package/dist/mcp/editable-artifacts.d.ts +13 -0
  39. package/dist/mcp/scheduled-task-view.d.ts +168 -0
  40. package/dist/mcp/server.d.ts +16 -4
  41. package/dist/memory-slack-delivery.d.ts +9 -0
  42. package/dist/model-catalog.d.ts +1 -0
  43. package/dist/routes/api-integrations.d.ts +8 -0
  44. package/dist/routes/browser-identities.d.ts +5 -0
  45. package/dist/routes/browser-sessions.d.ts +6 -0
  46. package/dist/routes/canonical-human-identities.d.ts +3 -0
  47. package/dist/routes/channels.d.ts +3 -0
  48. package/dist/routes/company-profile.d.ts +3 -0
  49. package/dist/routes/computer-sessions.d.ts +6 -0
  50. package/dist/routes/editable-artifacts.d.ts +44 -0
  51. package/dist/routes/integration-facets.d.ts +3 -0
  52. package/dist/routes/interaction-resources.d.ts +5 -0
  53. package/dist/routes/memory-slack-publications.d.ts +6 -0
  54. package/dist/routes/organization-memberships.d.ts +3 -0
  55. package/dist/routes/plugins.d.ts +8 -0
  56. package/dist/routes/sessions.d.ts +18 -2
  57. package/dist/routes/skills.d.ts +6 -0
  58. package/dist/routes/slack-task-policy.d.ts +3 -0
  59. package/dist/routes/supergrok.d.ts +3 -0
  60. package/dist/routes/video-generation.d.ts +3 -0
  61. package/dist/sandbox/channel-a.d.ts +62 -2
  62. package/dist/sandbox/machines.d.ts +2 -2
  63. package/dist/sandbox/metrics-ingestion.d.ts +6 -1
  64. package/dist/sandbox/viewer.d.ts +7 -3
  65. package/dist/slack-reaction-files.d.ts +27 -0
  66. package/dist/temporal-schedule-cleanup.d.ts +26 -0
  67. package/dist/transcription/providers/xai-subscription.d.ts +8 -0
  68. package/dist/xai-realtime.d.ts +26 -0
  69. package/dist/xai-subscription-auth.d.ts +23 -0
  70. package/package.json +20 -14
  71. package/src/app.ts +604 -64
  72. package/src/auth/canonical-human-session-admission.ts +116 -0
  73. package/src/auth/managed-auth.ts +101 -0
  74. package/src/browser-auth-broker.ts +155 -0
  75. package/src/browser-controller-authority.ts +186 -0
  76. package/src/browser-network-route.ts +34 -0
  77. package/src/browser-state-authority.ts +236 -0
  78. package/src/codemode.ts +186 -0
  79. package/src/controller-data-plane.ts +35 -0
  80. package/src/editable-artifact-live-hints.ts +64 -0
  81. package/src/editable-artifact-native-kernel.ts +659 -0
  82. package/src/editable-artifact-office-import.ts +230 -0
  83. package/src/editable-artifact-production.ts +419 -0
  84. package/src/editable-artifact-websocket.ts +311 -0
  85. package/src/editable-artifact-workspace-files.ts +186 -0
  86. package/src/github-browser-flow.ts +35 -6
  87. package/src/http/auth.ts +29 -9
  88. package/src/http/cors.ts +3 -0
  89. package/src/http/sse.ts +229 -5
  90. package/src/index.ts +119 -20
  91. package/src/integrations/api-integrations.ts +365 -0
  92. package/src/integrations/atlassian.ts +1621 -0
  93. package/src/integrations/fiken.ts +1230 -0
  94. package/src/integrations/github-skill-source.ts +142 -0
  95. package/src/integrations/google-drive.ts +1005 -64
  96. package/src/integrations/oauth-client.ts +123 -33
  97. package/src/integrations/provider-oauth.ts +756 -0
  98. package/src/integrations/slack-bot.ts +669 -11
  99. package/src/integrations/slack-interactions.ts +2063 -93
  100. package/src/integrations/social-api.ts +11 -0
  101. package/src/interaction-holder-heartbeat.ts +95 -0
  102. package/src/interaction-metrics.ts +159 -0
  103. package/src/mcp/documents.ts +146 -6
  104. package/src/mcp/editable-artifact-query-schema.ts +236 -0
  105. package/src/mcp/editable-artifacts.ts +448 -0
  106. package/src/mcp/scheduled-task-view.ts +34 -0
  107. package/src/mcp/server.ts +1756 -355
  108. package/src/memory-slack-delivery.ts +209 -0
  109. package/src/model-catalog.ts +19 -6
  110. package/src/routes/api-integrations.ts +410 -0
  111. package/src/routes/browser-identities.ts +160 -0
  112. package/src/routes/browser-sessions.ts +4482 -0
  113. package/src/routes/canonical-human-identities.ts +156 -0
  114. package/src/routes/channels.ts +90 -0
  115. package/src/routes/company-profile.ts +255 -0
  116. package/src/routes/computer-sessions.ts +1602 -0
  117. package/src/routes/connections.ts +421 -99
  118. package/src/routes/documents.ts +22 -3
  119. package/src/routes/editable-artifacts.ts +1159 -0
  120. package/src/routes/files.ts +106 -4
  121. package/src/routes/github.ts +18 -2
  122. package/src/routes/install.ts +7 -1
  123. package/src/routes/integration-facets.ts +258 -0
  124. package/src/routes/interaction-resources.ts +595 -0
  125. package/src/routes/memory-slack-publications.ts +216 -0
  126. package/src/routes/organization-memberships.ts +53 -0
  127. package/src/routes/packs.ts +437 -7
  128. package/src/routes/plugins.ts +752 -0
  129. package/src/routes/rigs.ts +77 -20
  130. package/src/routes/scheduled-tasks.ts +67 -40
  131. package/src/routes/sessions.ts +830 -278
  132. package/src/routes/skills.ts +256 -0
  133. package/src/routes/slack-task-policy.ts +115 -0
  134. package/src/routes/supergrok.ts +717 -0
  135. package/src/routes/transcription-recordings.ts +9 -2
  136. package/src/routes/transcriptions.ts +2 -1
  137. package/src/routes/video-generation.ts +162 -0
  138. package/src/routes/workspaces.ts +68 -28
  139. package/src/sandbox/channel-a.ts +750 -116
  140. package/src/sandbox/machines.ts +5 -5
  141. package/src/sandbox/metrics-ingestion.ts +121 -3
  142. package/src/sandbox/rematerialize.ts +35 -47
  143. package/src/sandbox/viewer.ts +39 -12
  144. package/src/slack-reaction-files.ts +181 -0
  145. package/src/temporal-schedule-cleanup.ts +135 -0
  146. package/src/transcription/providers/xai-subscription.ts +110 -0
  147. package/src/transcription/service.ts +17 -2
  148. package/src/xai-realtime.ts +216 -0
  149. package/src/xai-subscription-auth.ts +132 -0
  150. package/dist/chunk-T4T2PGU4.js.map +0 -1
  151. package/dist/mcp/toolspace.d.ts +0 -71
  152. package/src/mcp/toolspace.ts +0 -1190
@@ -0,0 +1,659 @@
1
+ import { createHash } from "node:crypto";
2
+ import { pathToFileURL } from "node:url";
3
+ import {
4
+ createNativeArtifactSession,
5
+ openNativeArtifactSession,
6
+ type NativeArtifactSession,
7
+ type NativeSpreadsheetSession,
8
+ } from "@opengeni/artifact-tool/native";
9
+ import type { ArtifactKernelRuntime } from "@opengeni/artifact-tool/runtime";
10
+ import {
11
+ doctorConfiguredArtifactRuntime,
12
+ type ConfiguredArtifactRuntimeLocation,
13
+ } from "@opengeni/artifact-tool/runtime/development";
14
+ import {
15
+ decodeEditableArtifactCausalFrontier,
16
+ encodeEditableArtifactCausalFrontier,
17
+ } from "@opengeni/contracts/editable-artifact-causal-frontier";
18
+ import { decodeEditableArtifactSerializedCommit } from "@opengeni/contracts/editable-artifact-serialized-commit";
19
+ import { decodeEditableArtifactMutationIntent } from "@opengeni/contracts/editable-artifacts";
20
+ import {
21
+ MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES,
22
+ causalFrontiersEqual,
23
+ editableArtifactCausalFrontier,
24
+ editableArtifactContentHash,
25
+ editableArtifactReplicaId,
26
+ editableArtifactStateHash,
27
+ type ApplyAuthoritativeEditableArtifactKernelRequest,
28
+ type ApplyAuthoritativeEditableArtifactKernelResult,
29
+ type AuthoritativeEditableArtifactCompactionKernelPort,
30
+ type AuthoritativeEditableArtifactCompactionKernelResult,
31
+ type AuthoritativeEditableArtifactGenesisKernelPort,
32
+ type AuthoritativeEditableArtifactGenesisKernelResult,
33
+ type AuthoritativeEditableArtifactKernelPort,
34
+ type EditableArtifactAgentInspectionKernelPort,
35
+ type EditableArtifactKernelState,
36
+ type EditableArtifactSnapshotReplayPlan,
37
+ type IsolatedEditableArtifactSnapshotKernelPort,
38
+ type IsolatedEditableArtifactSnapshotKernelResult,
39
+ } from "@opengeni/core";
40
+ import type { BoundedObjectReadPort } from "@opengeni/storage";
41
+
42
+ const MODEL_SCHEMA_VERSION = 1;
43
+ const OPERATION_PROTOCOL_VERSION = 1;
44
+ const CRDT_STATE_VERSION = 1;
45
+ const SNAPSHOT_CHUNK_BYTES = 1024 * 1024;
46
+
47
+ type RuntimeFacadeModule = Readonly<{
48
+ getConfiguredArtifactRuntime?: () => unknown;
49
+ }> &
50
+ Readonly<Record<string, unknown>>;
51
+
52
+ export type VerifiedNativeArtifactRuntimeBinding = Readonly<{
53
+ runtime: ArtifactKernelRuntime;
54
+ location: ConfiguredArtifactRuntimeLocation;
55
+ facade: RuntimeFacadeModule;
56
+ }>;
57
+
58
+ /** Loads only the manifest-pinned, byte-verified native runtime. */
59
+ export async function loadVerifiedNativeArtifactRuntime(): Promise<ArtifactKernelRuntime> {
60
+ return (await loadVerifiedNativeArtifactRuntimeBinding()).runtime;
61
+ }
62
+
63
+ /** Same verified load plus the pinned package identity used by export profiles. */
64
+ export async function loadVerifiedNativeArtifactRuntimeBinding(): Promise<VerifiedNativeArtifactRuntimeBinding> {
65
+ const location = await doctorConfiguredArtifactRuntime();
66
+ const module = (await import(
67
+ /* @vite-ignore */ pathToFileURL(location.skillFacadeEntrypoint).href
68
+ )) as RuntimeFacadeModule;
69
+ const candidate = module.getConfiguredArtifactRuntime?.();
70
+ assertRuntime(candidate, location);
71
+ return Object.freeze({ runtime: candidate, location, facade: module });
72
+ }
73
+
74
+ /** Exact native authority shared by mutation, genesis, and snapshot verification. */
75
+ export class NativeEditableArtifactKernelAdapter
76
+ implements
77
+ AuthoritativeEditableArtifactKernelPort,
78
+ AuthoritativeEditableArtifactGenesisKernelPort,
79
+ AuthoritativeEditableArtifactCompactionKernelPort,
80
+ IsolatedEditableArtifactSnapshotKernelPort,
81
+ EditableArtifactAgentInspectionKernelPort
82
+ {
83
+ constructor(
84
+ readonly runtime: ArtifactKernelRuntime,
85
+ private readonly objects: BoundedObjectReadPort,
86
+ ) {
87
+ if (runtime.kind !== "native" || runtime.target === "wasm-web") {
88
+ throw new Error("Editable artifact authority requires a native kernel");
89
+ }
90
+ }
91
+
92
+ async applyTransaction(
93
+ request: ApplyAuthoritativeEditableArtifactKernelRequest,
94
+ ): Promise<ApplyAuthoritativeEditableArtifactKernelResult> {
95
+ const session = await this.openCurrentState(request.state);
96
+ try {
97
+ if (request.modality === "spreadsheet") {
98
+ if (session.modality !== "spreadsheet") throw new Error("Native modality mismatch");
99
+ const committedTransactionBytes = session.authorTransaction(
100
+ request.intentBytes,
101
+ encodeEditableArtifactCausalFrontier(request.resolvedCausalBase),
102
+ );
103
+ return Object.freeze({
104
+ modality: "spreadsheet" as const,
105
+ committedTransactionBytes,
106
+ kernelVersion: this.runtime.buildIdentity,
107
+ modelSchemaVersion: MODEL_SCHEMA_VERSION,
108
+ });
109
+ }
110
+ if (session.modality !== request.modality) {
111
+ throw new Error("Native modality mismatch");
112
+ }
113
+ const nativeReceiptBytes = session.applyCommands(request.intent.commandBytes);
114
+ return Object.freeze({
115
+ modality: request.modality,
116
+ nativeReceiptBytes,
117
+ resultingStateHash: editableArtifactStateHash(session.stateHash()),
118
+ kernelVersion: this.runtime.buildIdentity,
119
+ modelSchemaVersion: MODEL_SCHEMA_VERSION,
120
+ });
121
+ } finally {
122
+ session.dispose();
123
+ }
124
+ }
125
+
126
+ async query(
127
+ input: Parameters<EditableArtifactAgentInspectionKernelPort["query"]>[0],
128
+ ): ReturnType<EditableArtifactAgentInspectionKernelPort["query"]> {
129
+ const session = await this.openCurrentState(input.state);
130
+ try {
131
+ return Uint8Array.from(session.query(input.queryBytes));
132
+ } finally {
133
+ session.dispose();
134
+ }
135
+ }
136
+
137
+ private async openCurrentState(
138
+ state: EditableArtifactKernelState,
139
+ ): Promise<NativeArtifactSession> {
140
+ const snapshot = state.snapshot;
141
+ if (!snapshot) throw new Error("Editable artifact has no verified replay snapshot");
142
+ const snapshotBytes = await readVerifiedSnapshot(this.objects, snapshot);
143
+ const session = openNativeArtifactSession(this.runtime, {
144
+ modality: state.modality,
145
+ snapshot: snapshotBytes,
146
+ });
147
+ try {
148
+ verifySnapshotBoundary(session, state);
149
+ replayKernelTail(session, state);
150
+ verifyDurableHead(session, state);
151
+ return session;
152
+ } catch (error) {
153
+ session.dispose();
154
+ throw error;
155
+ }
156
+ }
157
+
158
+ async createCanonicalEmptySnapshot(input: {
159
+ scope: Parameters<
160
+ AuthoritativeEditableArtifactGenesisKernelPort["createCanonicalEmptySnapshot"]
161
+ >[0]["scope"];
162
+ artifactId: Parameters<
163
+ AuthoritativeEditableArtifactGenesisKernelPort["createCanonicalEmptySnapshot"]
164
+ >[0]["artifactId"];
165
+ modality: Parameters<
166
+ AuthoritativeEditableArtifactGenesisKernelPort["createCanonicalEmptySnapshot"]
167
+ >[0]["modality"];
168
+ signal?: AbortSignal;
169
+ }): Promise<AuthoritativeEditableArtifactGenesisKernelResult> {
170
+ throwIfAborted(input.signal);
171
+ const session = createNativeArtifactSession(this.runtime, {
172
+ modality: input.modality,
173
+ replicaNamespace: namespaceForArtifact(input.artifactId),
174
+ });
175
+ try {
176
+ const snapshot = session.snapshot();
177
+ throwIfAborted(input.signal);
178
+ const revision = safeRevision(session.revision());
179
+ if (revision !== 0) throw new Error("Native genesis revision is not zero");
180
+ const common = {
181
+ scope: input.scope,
182
+ artifactId: input.artifactId,
183
+ modality: input.modality,
184
+ canonicalChunks: fixedChunks(snapshot, input.signal),
185
+ canonicalByteSize: snapshot.byteLength,
186
+ canonicalContentHash: editableArtifactContentHash(
187
+ `sha256:${createHash("sha256").update(snapshot).digest("hex")}`,
188
+ ),
189
+ stateHash: editableArtifactStateHash(session.stateHash()),
190
+ coveredHeadSequence: 0 as const,
191
+ modelSchemaVersion: MODEL_SCHEMA_VERSION,
192
+ kernelVersion: this.runtime.buildIdentity,
193
+ };
194
+ if (session.modality === "spreadsheet") {
195
+ return Object.freeze({
196
+ ...common,
197
+ modality: "spreadsheet" as const,
198
+ coveredCausalFrontier: domainFrontier(session.frontier()),
199
+ operationProtocolVersion: OPERATION_PROTOCOL_VERSION,
200
+ crdtStateVersion: CRDT_STATE_VERSION,
201
+ });
202
+ }
203
+ return Object.freeze({
204
+ ...common,
205
+ modality: session.modality,
206
+ nativeRevision: 0 as const,
207
+ });
208
+ } finally {
209
+ session.dispose();
210
+ }
211
+ }
212
+
213
+ async createCanonicalSnapshot(input: {
214
+ state: EditableArtifactKernelState;
215
+ signal?: AbortSignal;
216
+ }): Promise<AuthoritativeEditableArtifactCompactionKernelResult> {
217
+ throwIfAborted(input.signal);
218
+ const snapshot = input.state.snapshot;
219
+ if (!snapshot) throw new Error("Editable artifact has no verified replay snapshot");
220
+ const snapshotBytes = await readVerifiedSnapshot(this.objects, snapshot, input.signal);
221
+ const session = openNativeArtifactSession(this.runtime, {
222
+ modality: input.state.modality,
223
+ snapshot: snapshotBytes,
224
+ });
225
+ try {
226
+ verifySnapshotBoundary(session, input.state);
227
+ replayKernelTail(session, input.state);
228
+ verifyDurableHead(session, input.state);
229
+ throwIfAborted(input.signal);
230
+ const canonical = session.snapshot();
231
+ const common = {
232
+ scope: input.state.artifact.scope,
233
+ artifactId: input.state.artifact.id,
234
+ modality: input.state.modality,
235
+ canonicalChunks: fixedChunks(canonical, input.signal),
236
+ canonicalByteSize: canonical.byteLength,
237
+ canonicalContentHash: editableArtifactContentHash(
238
+ `sha256:${createHash("sha256").update(canonical).digest("hex")}`,
239
+ ),
240
+ stateHash: editableArtifactStateHash(session.stateHash()),
241
+ coveredHeadSequence: input.state.artifact.headSequence,
242
+ modelSchemaVersion: MODEL_SCHEMA_VERSION,
243
+ kernelVersion: this.runtime.buildIdentity,
244
+ } as const;
245
+ if (session.modality === "spreadsheet") {
246
+ if (input.state.modality !== "spreadsheet") throw new Error("Native modality mismatch");
247
+ return Object.freeze({
248
+ ...common,
249
+ modality: session.modality,
250
+ coveredCausalFrontier: domainFrontier(session.frontier()),
251
+ operationProtocolVersion: OPERATION_PROTOCOL_VERSION,
252
+ crdtStateVersion: CRDT_STATE_VERSION,
253
+ });
254
+ }
255
+ if (session.modality !== input.state.modality) throw new Error("Native modality mismatch");
256
+ return Object.freeze({
257
+ ...common,
258
+ modality: session.modality,
259
+ nativeRevision: safeRevision(session.revision()),
260
+ });
261
+ } finally {
262
+ session.dispose();
263
+ }
264
+ }
265
+
266
+ async verifyAndReconstruct(
267
+ input: Parameters<IsolatedEditableArtifactSnapshotKernelPort["verifyAndReconstruct"]>[0],
268
+ ): Promise<IsolatedEditableArtifactSnapshotKernelResult> {
269
+ throwIfAborted(input.signal);
270
+ const bytes = await collectExact(
271
+ input.snapshotChunks,
272
+ input.expectedSnapshotByteSize,
273
+ input.signal,
274
+ );
275
+ const session = openNativeArtifactSession(this.runtime, {
276
+ modality: input.modality,
277
+ snapshot: bytes,
278
+ });
279
+ try {
280
+ const canonical = session.snapshot();
281
+ if (!equalBytes(canonical, bytes)) throw new Error("Native snapshot is not canonical");
282
+ const expected = input.expectedSnapshot;
283
+ if (expected.modality !== session.modality) throw new Error("Snapshot modality mismatch");
284
+ const coveredHeadSequence = expected.coveredHeadSequence;
285
+ const stateHash = editableArtifactStateHash(session.stateHash());
286
+ if (stateHash !== expected.stateHash) throw new Error("Snapshot state hash mismatch");
287
+ const canonicalContentHash = editableArtifactContentHash(
288
+ `sha256:${createHash("sha256").update(canonical).digest("hex")}`,
289
+ );
290
+ if (session.modality === "spreadsheet") {
291
+ const coveredCausalFrontier = domainFrontier(session.frontier());
292
+ if (
293
+ expected.modality !== "spreadsheet" ||
294
+ !causalFrontiersEqual(coveredCausalFrontier, expected.coveredCausalFrontier)
295
+ ) {
296
+ throw new Error("Snapshot causal coverage mismatch");
297
+ }
298
+ if (input.replayPlan && input.replayPlan.modality !== "spreadsheet") {
299
+ throw new Error("Replay modality mismatch");
300
+ }
301
+ const replayedTarget = input.replayPlan
302
+ ? await replaySpreadsheetPlan(session, input.replayPlan, input.signal)
303
+ : undefined;
304
+ return Object.freeze({
305
+ modality: "spreadsheet" as const,
306
+ canonicalReencodeVerified: true as const,
307
+ scope: input.scope,
308
+ artifactId: input.artifactId,
309
+ canonicalByteSize: canonical.byteLength,
310
+ canonicalContentHash,
311
+ coveredHeadSequence,
312
+ stateHash,
313
+ modelSchemaVersion: MODEL_SCHEMA_VERSION,
314
+ kernelVersion: this.runtime.buildIdentity,
315
+ fullCrdtStateVerified: true as const,
316
+ coveredCausalFrontier,
317
+ operationProtocolVersion: OPERATION_PROTOCOL_VERSION,
318
+ crdtStateVersion: CRDT_STATE_VERSION,
319
+ ...(replayedTarget ? { replayedTarget } : {}),
320
+ });
321
+ }
322
+ if (expected.modality === "spreadsheet") throw new Error("Snapshot modality mismatch");
323
+ const nativeRevision = safeRevision(session.revision());
324
+ if (nativeRevision !== expected.nativeRevision) {
325
+ throw new Error("Snapshot native revision mismatch");
326
+ }
327
+ if (input.replayPlan && input.replayPlan.modality === "spreadsheet") {
328
+ throw new Error("Replay modality mismatch");
329
+ }
330
+ const replayedTarget = input.replayPlan
331
+ ? await replaySerializedPlan(session, input.replayPlan, input.signal)
332
+ : undefined;
333
+ return Object.freeze({
334
+ modality: session.modality,
335
+ canonicalReencodeVerified: true as const,
336
+ scope: input.scope,
337
+ artifactId: input.artifactId,
338
+ canonicalByteSize: canonical.byteLength,
339
+ canonicalContentHash,
340
+ coveredHeadSequence,
341
+ stateHash,
342
+ modelSchemaVersion: MODEL_SCHEMA_VERSION,
343
+ kernelVersion: this.runtime.buildIdentity,
344
+ nativeRevision,
345
+ ...(replayedTarget ? { replayedTarget } : {}),
346
+ });
347
+ } finally {
348
+ session.dispose();
349
+ }
350
+ }
351
+ }
352
+
353
+ function assertRuntime(
354
+ candidate: unknown,
355
+ location: ConfiguredArtifactRuntimeLocation,
356
+ ): asserts candidate is ArtifactKernelRuntime {
357
+ if (typeof candidate !== "object" || candidate === null) {
358
+ throw new Error("Verified artifact facade returned no runtime");
359
+ }
360
+ const runtime = candidate as Partial<ArtifactKernelRuntime>;
361
+ if (
362
+ runtime.kind !== "native" ||
363
+ runtime.target === "wasm-web" ||
364
+ runtime.target !== location.target ||
365
+ runtime.buildIdentity !== location.kernel.buildIdentity ||
366
+ typeof runtime.createCollaborationSession !== "function" ||
367
+ typeof runtime.openCollaborationSession !== "function" ||
368
+ typeof runtime.createDocumentSession !== "function" ||
369
+ typeof runtime.openDocumentSession !== "function" ||
370
+ typeof runtime.createPresentationSession !== "function" ||
371
+ typeof runtime.openPresentationSession !== "function"
372
+ ) {
373
+ throw new Error("Verified artifact facade returned an incompatible runtime");
374
+ }
375
+ }
376
+
377
+ function verifySnapshotBoundary(
378
+ session: NativeArtifactSession,
379
+ state: EditableArtifactKernelState,
380
+ ): void {
381
+ const snapshot = state.snapshot;
382
+ if (!snapshot || session.modality !== state.modality)
383
+ throw new Error("Snapshot modality mismatch");
384
+ if (session.stateHash() !== snapshot.stateHash) {
385
+ throw new Error("Native snapshot boundary does not match durable metadata");
386
+ }
387
+ if (state.modality === "spreadsheet") {
388
+ if (
389
+ session.modality !== "spreadsheet" ||
390
+ snapshot.modality !== "spreadsheet" ||
391
+ !causalFrontiersEqual(domainFrontier(session.frontier()), snapshot.coveredCausalFrontier)
392
+ ) {
393
+ throw new Error("Native snapshot frontier does not match durable metadata");
394
+ }
395
+ } else if (
396
+ session.modality === "spreadsheet" ||
397
+ snapshot.modality === "spreadsheet" ||
398
+ safeRevision(session.revision()) !== snapshot.nativeRevision ||
399
+ state.baseNativeRevision !== snapshot.nativeRevision
400
+ ) {
401
+ throw new Error("Native snapshot revision does not match durable metadata");
402
+ }
403
+ }
404
+
405
+ function replayKernelTail(
406
+ session: NativeArtifactSession,
407
+ state: EditableArtifactKernelState,
408
+ ): void {
409
+ if (state.modality === "spreadsheet") {
410
+ if (session.modality !== "spreadsheet") throw new Error("Native modality mismatch");
411
+ for (const transaction of state.committedTransactionTail) {
412
+ const priorNativeRevision = safeRevision(session.revision());
413
+ if (session.stateHash() !== transaction.priorStateHash) {
414
+ throw new Error("Spreadsheet replay prior state mismatch");
415
+ }
416
+ session.applyCommitted(transaction.committedTransactionBytes);
417
+ if (
418
+ safeRevision(session.revision()) !== priorNativeRevision + 1 ||
419
+ session.stateHash() !== transaction.stateHash ||
420
+ !causalFrontiersEqual(
421
+ domainFrontier(session.frontier()),
422
+ transaction.resultingCausalFrontier,
423
+ )
424
+ ) {
425
+ throw new Error("Spreadsheet replay result mismatch");
426
+ }
427
+ }
428
+ return;
429
+ }
430
+ if (session.modality !== state.modality) {
431
+ throw new Error("Native modality mismatch");
432
+ }
433
+ for (const transaction of state.committedTransactionTail) {
434
+ if (
435
+ session.stateHash() !== transaction.priorStateHash ||
436
+ safeRevision(session.revision()) !== transaction.priorNativeRevision
437
+ ) {
438
+ throw new Error("Serialized replay prior state mismatch");
439
+ }
440
+ const commit = decodeEditableArtifactSerializedCommit(
441
+ transaction.committedTransactionBytes,
442
+ state.modality,
443
+ );
444
+ const intent = decodeEditableArtifactMutationIntent(commit.intentBytes);
445
+ const receipt = session.applyCommands(intent.commandBytes);
446
+ if (
447
+ !equalBytes(receipt, commit.nativeReceiptBytes) ||
448
+ !equalBytes(receipt, transaction.nativeReceiptBytes) ||
449
+ safeRevision(session.revision()) !== transaction.nativeRevision ||
450
+ session.stateHash() !== transaction.stateHash
451
+ ) {
452
+ throw new Error("Serialized replay result mismatch");
453
+ }
454
+ }
455
+ }
456
+
457
+ function verifyDurableHead(
458
+ session: NativeArtifactSession,
459
+ state: EditableArtifactKernelState,
460
+ ): void {
461
+ const snapshot = state.snapshot;
462
+ if (!snapshot) throw new Error("Editable artifact has no replay snapshot");
463
+ let durableSequence = snapshot.coveredHeadSequence;
464
+ for (const transaction of state.committedTransactionTail) {
465
+ if (transaction.sequenceStart !== durableSequence + 1) {
466
+ throw new Error("Durable transaction tail contains a sequence gap");
467
+ }
468
+ durableSequence = transaction.sequenceEnd;
469
+ }
470
+ if (
471
+ session.modality !== state.modality ||
472
+ durableSequence !== state.artifact.headSequence ||
473
+ session.stateHash() !== state.artifact.stateHash
474
+ ) {
475
+ throw new Error("Reconstructed native state does not match the durable head");
476
+ }
477
+ if (
478
+ state.modality === "spreadsheet" &&
479
+ (session.modality !== "spreadsheet" ||
480
+ !causalFrontiersEqual(domainFrontier(session.frontier()), state.artifact.causalFrontier))
481
+ ) {
482
+ throw new Error("Reconstructed native frontier does not match the durable head");
483
+ }
484
+ if (state.modality !== "spreadsheet") {
485
+ const expectedNativeRevision =
486
+ state.committedTransactionTail.at(-1)?.nativeRevision ?? state.baseNativeRevision;
487
+ if (safeRevision(session.revision()) !== expectedNativeRevision) {
488
+ throw new Error("Reconstructed native revision does not match the serialized tail");
489
+ }
490
+ }
491
+ }
492
+
493
+ async function replaySpreadsheetPlan(
494
+ session: NativeSpreadsheetSession,
495
+ plan: Extract<EditableArtifactSnapshotReplayPlan, { modality: "spreadsheet" }>,
496
+ signal: AbortSignal | undefined,
497
+ ): Promise<
498
+ Readonly<{
499
+ headSequence: number;
500
+ causalFrontier: ReturnType<typeof editableArtifactCausalFrontier>;
501
+ stateHash: ReturnType<typeof editableArtifactStateHash>;
502
+ }>
503
+ > {
504
+ let sequence = plan.baseHeadSequence;
505
+ for await (const segment of plan.segments) {
506
+ throwIfAborted(signal);
507
+ if (segment.sequenceStart !== sequence + 1) throw new Error("Replay sequence gap");
508
+ if (segment.modality !== "spreadsheet") throw new Error("Replay segment modality mismatch");
509
+ session.applyCommitted(segment.bytes);
510
+ sequence = segment.sequenceEnd;
511
+ }
512
+ if (sequence !== plan.targetHeadSequence || session.stateHash() !== plan.targetStateHash) {
513
+ throw new Error("Replay target mismatch");
514
+ }
515
+ const causalFrontier = domainFrontier(session.frontier());
516
+ if (!causalFrontiersEqual(causalFrontier, plan.targetCausalFrontier)) {
517
+ throw new Error("Replay frontier mismatch");
518
+ }
519
+ return Object.freeze({
520
+ headSequence: sequence,
521
+ causalFrontier,
522
+ stateHash: editableArtifactStateHash(session.stateHash()),
523
+ });
524
+ }
525
+
526
+ async function replaySerializedPlan(
527
+ session: Exclude<NativeArtifactSession, NativeSpreadsheetSession>,
528
+ plan: Exclude<EditableArtifactSnapshotReplayPlan, { modality: "spreadsheet" }>,
529
+ signal: AbortSignal | undefined,
530
+ ): Promise<
531
+ Readonly<{
532
+ headSequence: number;
533
+ nativeRevision: number;
534
+ stateHash: ReturnType<typeof editableArtifactStateHash>;
535
+ }>
536
+ > {
537
+ if (session.modality !== plan.modality) throw new Error("Replay modality mismatch");
538
+ let sequence = plan.baseHeadSequence;
539
+ for await (const segment of plan.segments) {
540
+ throwIfAborted(signal);
541
+ if (segment.sequenceStart !== sequence + 1 || segment.modality !== session.modality) {
542
+ throw new Error("Replay sequence or modality mismatch");
543
+ }
544
+ const commit = decodeEditableArtifactSerializedCommit(segment.bytes, session.modality);
545
+ const intent = decodeEditableArtifactMutationIntent(commit.intentBytes);
546
+ const receipt = session.applyCommands(intent.commandBytes);
547
+ if (!equalBytes(receipt, commit.nativeReceiptBytes)) throw new Error("Replay receipt mismatch");
548
+ sequence = segment.sequenceEnd;
549
+ }
550
+ if (sequence !== plan.targetHeadSequence || session.stateHash() !== plan.targetStateHash) {
551
+ throw new Error("Replay target mismatch");
552
+ }
553
+ if (safeRevision(session.revision()) !== plan.targetNativeRevision) {
554
+ throw new Error("Replay native revision mismatch");
555
+ }
556
+ return Object.freeze({
557
+ headSequence: sequence,
558
+ nativeRevision: plan.targetNativeRevision,
559
+ stateHash: editableArtifactStateHash(session.stateHash()),
560
+ });
561
+ }
562
+
563
+ function domainFrontier(bytes: Uint8Array): ReturnType<typeof editableArtifactCausalFrontier> {
564
+ return editableArtifactCausalFrontier(
565
+ decodeEditableArtifactCausalFrontier(bytes).map((entry) => ({
566
+ replicaId: editableArtifactReplicaId(entry.replicaId),
567
+ counter: entry.counter,
568
+ })),
569
+ );
570
+ }
571
+
572
+ async function readVerifiedSnapshot(
573
+ objects: BoundedObjectReadPort,
574
+ snapshot: NonNullable<EditableArtifactKernelState["snapshot"]>,
575
+ signal?: AbortSignal,
576
+ ): Promise<Uint8Array> {
577
+ const object = await objects.open({
578
+ opaqueReference: snapshot.blobReference,
579
+ maxBytes: MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES,
580
+ expectedByteSize: snapshot.byteSize,
581
+ ...(signal ? { signal } : {}),
582
+ });
583
+ try {
584
+ if (object.contentType !== undefined && object.contentType !== snapshot.mimeType) {
585
+ throw new Error("Snapshot content type mismatch");
586
+ }
587
+ const bytes = await collectExact(
588
+ object.chunks(signal ? { signal } : {}),
589
+ snapshot.byteSize,
590
+ signal,
591
+ );
592
+ const contentHash = `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
593
+ if (contentHash !== snapshot.contentHash) throw new Error("Snapshot content hash mismatch");
594
+ await object.assertUnchanged(signal);
595
+ return bytes;
596
+ } finally {
597
+ await object.close();
598
+ }
599
+ }
600
+
601
+ async function collectExact(
602
+ chunks: AsyncIterable<Uint8Array>,
603
+ expectedBytes: number,
604
+ signal?: AbortSignal,
605
+ ): Promise<Uint8Array> {
606
+ if (!Number.isSafeInteger(expectedBytes) || expectedBytes <= 0) {
607
+ throw new Error("Snapshot byte size is invalid");
608
+ }
609
+ const result = new Uint8Array(expectedBytes);
610
+ let offset = 0;
611
+ for await (const chunk of chunks) {
612
+ throwIfAborted(signal);
613
+ if (!(chunk instanceof Uint8Array) || chunk.byteLength === 0) {
614
+ throw new Error("Snapshot stream is truncated");
615
+ }
616
+ if (offset + chunk.byteLength > result.byteLength) {
617
+ throw new Error("Snapshot stream exceeds its declared size");
618
+ }
619
+ result.set(chunk, offset);
620
+ offset += chunk.byteLength;
621
+ }
622
+ throwIfAborted(signal);
623
+ if (offset !== result.byteLength) throw new Error("Snapshot stream is truncated");
624
+ return result;
625
+ }
626
+
627
+ async function* fixedChunks(bytes: Uint8Array, signal?: AbortSignal): AsyncIterable<Uint8Array> {
628
+ for (let offset = 0; offset < bytes.byteLength; offset += SNAPSHOT_CHUNK_BYTES) {
629
+ throwIfAborted(signal);
630
+ yield bytes.subarray(offset, Math.min(bytes.byteLength, offset + SNAPSHOT_CHUNK_BYTES));
631
+ }
632
+ }
633
+
634
+ function namespaceForArtifact(artifactId: string): bigint {
635
+ const digest = createHash("sha256").update(artifactId).digest();
636
+ let value = 0n;
637
+ for (let index = 0; index < 8; index += 1) value = (value << 8n) | BigInt(digest[index]!);
638
+ return value === 0n ? 1n : value;
639
+ }
640
+
641
+ function safeRevision(value: bigint): number {
642
+ if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) {
643
+ throw new Error("Native revision exceeds the safe integer range");
644
+ }
645
+ return Number(value);
646
+ }
647
+
648
+ function equalBytes(left: Uint8Array, right: Uint8Array): boolean {
649
+ if (left.byteLength !== right.byteLength) return false;
650
+ let difference = 0;
651
+ for (let index = 0; index < left.byteLength; index += 1) {
652
+ difference |= left[index]! ^ right[index]!;
653
+ }
654
+ return difference === 0;
655
+ }
656
+
657
+ function throwIfAborted(signal: AbortSignal | undefined): void {
658
+ if (signal?.aborted) throw new Error("Editable artifact native operation was cancelled");
659
+ }