@oddington/sdk 0.1.76 → 0.1.78

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/dist/browser.js CHANGED
@@ -5998,8 +5998,8 @@ function parseRoutineDeclaration(value) {
5998
5998
  for (let key of Object.keys(repositories).sort())
5999
5999
  (!routineAlias(key) || !["read", "write"].includes(repositories[key])) && invalid(`access.repositories.${key}`), grants[key] = repositories[key];
6000
6000
  access.files !== void 0 && !["read", "read-write"].includes(access.files) && invalid("access.files");
6001
- let runtime = object2(v.runtime === void 0 ? {} : v.runtime, ["features", "resources", "maxDuration"], "runtime");
6002
- runtime.features !== void 0 && (!Array.isArray(runtime.features) || runtime.features.length !== 0) && invalid("runtime.features"), runtime.resources !== void 0 && runtime.resources !== "standard" && invalid("runtime.resources"), runtime.maxDuration !== void 0 && !["15m", "60m"].includes(runtime.maxDuration) && invalid("runtime.maxDuration");
6001
+ let runtime2 = object2(v.runtime === void 0 ? {} : v.runtime, ["features", "resources", "maxDuration"], "runtime");
6002
+ runtime2.features !== void 0 && (!Array.isArray(runtime2.features) || runtime2.features.length !== 0) && invalid("runtime.features"), runtime2.resources !== void 0 && runtime2.resources !== "standard" && invalid("runtime.resources"), runtime2.maxDuration !== void 0 && !["15m", "60m"].includes(runtime2.maxDuration) && invalid("runtime.maxDuration");
6003
6003
  let retry = object2(v.retry === void 0 ? {} : v.retry, ["maxAttempts"], "retry");
6004
6004
  retry.maxAttempts !== void 0 && retry.maxAttempts !== 1 && invalid("retry.maxAttempts");
6005
6005
  let assets = v.assets === void 0 ? [] : v.assets;
@@ -6015,7 +6015,7 @@ function parseRoutineDeclaration(value) {
6015
6015
  runtime: {
6016
6016
  features: [],
6017
6017
  resources: "standard",
6018
- maxDuration: runtime.maxDuration ?? "60m"
6018
+ maxDuration: runtime2.maxDuration ?? "60m"
6019
6019
  },
6020
6020
  retry: { maxAttempts: 1 },
6021
6021
  assets: [...assets].sort()
@@ -6449,8 +6449,8 @@ var schema = {
6449
6449
  steps: Object.freeze(executable),
6450
6450
  responses: Object.freeze(responses.map((handler) => defineHandler({
6451
6451
  ...handler,
6452
- async run(context, runtime) {
6453
- let active2 = !0, capabilities = runtime ? createCapabilityRuntime(contract, runtime, () => active2, "Response") : void 0;
6452
+ async run(context, runtime2) {
6453
+ let active2 = !0, capabilities = runtime2 ? createCapabilityRuntime(contract, runtime2, () => active2, "Response") : void 0;
6454
6454
  try {
6455
6455
  return await handler.run(context, capabilities?.os);
6456
6456
  } catch (error) {
@@ -6483,11 +6483,11 @@ function captureRoutineInput(definition, input) {
6483
6483
  let contract = inspectRoutineDefinition(definition);
6484
6484
  return capture2(contract.input, input === void 0 && Object.hasOwn(contract, "inputDefault") ? contract.inputDefault : input);
6485
6485
  }
6486
- function createCapabilityRuntime(contract, runtime, current2, owner) {
6486
+ function createCapabilityRuntime(contract, runtime2, current2, owner) {
6487
6487
  let aiWork = /* @__PURE__ */ new Set(), generate = (kind, value) => {
6488
6488
  let operation2 = (async () => {
6489
6489
  if (!current2() || contract.access.ai !== !0) throw new AIError("access_denied");
6490
- if (!runtime.ai) throw new AIError("capability_unavailable");
6490
+ if (!runtime2.ai) throw new AIError("capability_unavailable");
6491
6491
  let request3;
6492
6492
  try {
6493
6493
  assertRoutineFields(value, kind === "generateObject" ? ["instructions", "input", "schema", "tools"] : ["instructions", "input", "tools"]), request3 = parseRoutineAIRequest({
@@ -6500,7 +6500,7 @@ function createCapabilityRuntime(contract, runtime, current2, owner) {
6500
6500
  } catch (error) {
6501
6501
  throw error instanceof AIError ? error : new AIError("invalid_input");
6502
6502
  }
6503
- let result2 = await runtime.ai[kind](request3);
6503
+ let result2 = await runtime2.ai[kind](request3);
6504
6504
  if (!current2()) throw new AIError("access_denied");
6505
6505
  return parseRoutineAIResult(request3, result2);
6506
6506
  })();
@@ -6519,35 +6519,41 @@ function createCapabilityRuntime(contract, runtime, current2, owner) {
6519
6519
  return value;
6520
6520
  };
6521
6521
  return { os: Object.freeze({ ...guarded({
6522
- data: runtime.data,
6523
- files: runtime.files,
6522
+ data: runtime2.data,
6523
+ files: runtime2.files,
6524
6524
  ai: {
6525
6525
  generateText: (value) => generate("generateText", value),
6526
6526
  generateObject: (value) => generate("generateObject", value)
6527
6527
  },
6528
- connections: { ...runtime.connections, get: async (identity) => {
6528
+ connections: { ...runtime2.connections, get: async (identity) => {
6529
6529
  if (!current2() || !contract.access.connections?.includes(identity)) throw new Error("Connection unavailable");
6530
- let value = await runtime.connections.get(identity);
6530
+ let value = await runtime2.connections.get(identity);
6531
6531
  if (!current2()) throw new Error(`${owner} authority ended`);
6532
6532
  return value;
6533
6533
  } },
6534
- inbox: { ...runtime.inbox, publishAsk: (value, options) => runtime.inbox.publishAsk(validateHandlers(value), options) }
6534
+ inbox: { ...runtime2.inbox, publishAsk: (value, options) => runtime2.inbox.publishAsk(validateHandlers(value), options) },
6535
+ ...owner === "Response" ? { action: freezeRoutineMetadata({ async progress(value) {
6536
+ assertRoutineFields(value, ["label"]);
6537
+ let label = value.label;
6538
+ if (!routineTitle(label) || !runtime2.action) return invalid3();
6539
+ await runtime2.action.progress({ label });
6540
+ } }) } : {}
6535
6541
  }) }), guarded, async drain() {
6536
6542
  for (; aiWork.size; ) await Promise.allSettled([...aiWork]);
6537
6543
  } };
6538
6544
  }
6539
- async function executeRoutineDefinition(definition, input, runtime) {
6540
- let captured = captureRoutineInput(definition, input), { contract, steps, run } = definitions.get(definition), active2 = !0, accepting = !0, broken = !1, outputFailure, work = Promise.resolve(), capabilities = createCapabilityRuntime(contract, runtime, () => active2 && !broken, "Run"), called = /* @__PURE__ */ new Set(), reached = /* @__PURE__ */ new Set(), activeStep, progress2 = /* @__PURE__ */ new Map(), os2 = Object.freeze({
6545
+ async function executeRoutineDefinition(definition, input, runtime2) {
6546
+ let captured = captureRoutineInput(definition, input), { contract, steps, run } = definitions.get(definition), active2 = !0, accepting = !0, broken = !1, outputFailure, work = Promise.resolve(), capabilities = createCapabilityRuntime(contract, runtime2, () => active2 && !broken, "Run"), called = /* @__PURE__ */ new Set(), reached = /* @__PURE__ */ new Set(), activeStep, progress2 = /* @__PURE__ */ new Map(), os2 = Object.freeze({
6541
6547
  ...capabilities.os,
6542
6548
  ...capabilities.guarded({
6543
- run: freezeRoutineMetadata({ id: runtime.run.id, async progress(value) {
6549
+ run: freezeRoutineMetadata({ id: runtime2.run.id, async progress(value) {
6544
6550
  assertRoutineFields(value, ["completed", "total"]);
6545
6551
  let { completed: completed2, total } = value, prior = activeStep ? progress2.get(activeStep) : void 0;
6546
6552
  if (!active2 || broken || !activeStep || !Number.isSafeInteger(completed2) || !Number.isSafeInteger(total) || completed2 < 1 || completed2 > total || prior && (prior.total !== total || completed2 <= prior.completed)) return invalid3();
6547
6553
  let accepted = freezeRoutineMetadata({ step: activeStep, completed: completed2, total });
6548
- await runtime.run.progress(accepted), progress2.set(activeStep, accepted);
6554
+ await runtime2.run.progress(accepted), progress2.set(activeStep, accepted);
6549
6555
  } }),
6550
- ...runtime.artifact ? { artifact: runtime.artifact } : {}
6556
+ ...runtime2.artifact ? { artifact: runtime2.artifact } : {}
6551
6557
  }),
6552
6558
  step(id3, ...input2) {
6553
6559
  let saved;
@@ -6561,13 +6567,13 @@ async function executeRoutineDefinition(definition, input, runtime) {
6561
6567
  if (broken) return invalid3();
6562
6568
  reached.add(id3);
6563
6569
  try {
6564
- await runtime.step(id3, { status: "running" }), activeStep = id3;
6570
+ await runtime2.step(id3, { status: "running" }), activeStep = id3;
6565
6571
  let output = await steps[id3].run(saved, os2);
6566
6572
  if (assertRoutineFields(output, ["summary", "data"]), !Object.hasOwn(output, "summary") || !Object.hasOwn(output, "data")) return invalid3();
6567
6573
  let { summary: summary3, data: data3 } = captureRoutineStepOutput(id3, output.summary, output.data);
6568
- return await runtime.step(id3, { status: "completed", summary: summary3, data: data3 }), activeStep = void 0, freezeRoutineMetadata({ summary: summary3, data: data3 });
6574
+ return await runtime2.step(id3, { status: "completed", summary: summary3, data: data3 }), activeStep = void 0, freezeRoutineMetadata({ summary: summary3, data: data3 });
6569
6575
  } catch (error) {
6570
- throw error instanceof RoutineStepOutputError && (outputFailure ??= error), broken = !0, activeStep = void 0, await runtime.step(id3, { status: "failed" }), error;
6576
+ throw error instanceof RoutineStepOutputError && (outputFailure ??= error), broken = !0, activeStep = void 0, await runtime2.step(id3, { status: "failed" }), error;
6571
6577
  }
6572
6578
  });
6573
6579
  return work = next.then(() => {
@@ -6583,7 +6589,7 @@ async function executeRoutineDefinition(definition, input, runtime) {
6583
6589
  }
6584
6590
  accepting = !1, await work, await capabilities.drain(), active2 = !1;
6585
6591
  try {
6586
- for (let step of contract.steps) reached.has(step.id) || await runtime.step(step.id, { status: "skipped" });
6592
+ for (let step of contract.steps) reached.has(step.id) || await runtime2.step(step.id, { status: "skipped" });
6587
6593
  } catch (error) {
6588
6594
  throw outputFailure ?? error;
6589
6595
  }
@@ -7210,6 +7216,9 @@ function installMemberContext(resolve, retained = resolve, inbox2 = resolve) {
7210
7216
  memberContext === resolve && (memberLifetime?.abort(), memberContext = void 0, retainedContext = void 0, inboxContext = void 0);
7211
7217
  };
7212
7218
  }
7219
+ function memberContextSignal() {
7220
+ return memberLifetime?.signal;
7221
+ }
7213
7222
  async function resolveAppContext(retained = !1, inbox2 = !1) {
7214
7223
  let host = memberContext;
7215
7224
  if (!host) throw new Error("App context unavailable.");
@@ -8261,15 +8270,15 @@ function applySnapshotMutation(envelope, prior, mutation, installation) {
8261
8270
 
8262
8271
  var unavailable2 = () => {
8263
8272
  throw new DataOperationError("unavailable", !0);
8264
- };
8273
+ }, cacheUnavailable = () => new DataOperationError("unavailable", !0, void 0, "snapshot_cache");
8265
8274
  function request(value) {
8266
8275
  return new Promise((resolve, reject) => {
8267
- value.onsuccess = () => resolve(value.result), value.onerror = () => reject(new DataOperationError("unavailable", !0));
8276
+ value.onsuccess = () => resolve(value.result), value.onerror = () => reject(cacheUnavailable());
8268
8277
  });
8269
8278
  }
8270
8279
  function completed(transaction) {
8271
8280
  let done = new Promise((resolve, reject) => {
8272
- transaction.oncomplete = () => resolve(), transaction.onabort = transaction.onerror = () => reject(new DataOperationError("unavailable", !0));
8281
+ transaction.oncomplete = () => resolve(), transaction.onabort = transaction.onerror = () => reject(cacheUnavailable());
8273
8282
  });
8274
8283
  return done.catch(() => {
8275
8284
  }), done;
@@ -8288,28 +8297,54 @@ async function openSnapshotStore() {
8288
8297
  close() {
8289
8298
  database.close();
8290
8299
  },
8300
+ async compact() {
8301
+ let transaction = database.transaction(["current", "records", "changes", "bases"], "readwrite"), done = completed(transaction);
8302
+ try {
8303
+ let pointers = transaction.objectStore("current"), current2 = [];
8304
+ for (let key of await request(pointers.getAllKeys())) {
8305
+ let value = await request(pointers.get(key));
8306
+ value && current2.push(value);
8307
+ }
8308
+ let installationIds = new Set(current2.map((value) => value.id).filter(Boolean)), recordIds = new Set(current2.map((value) => value.recordsId ?? value.id).filter(Boolean)), artifactTokens = new Set(current2.map((value) => value.artifactToken).filter(Boolean)), changes = transaction.objectStore("changes"), stale2 = (await request(changes.getAllKeys())).filter((key) => typeof key == "string" && !installationIds.has(key));
8309
+ for (let id3 of stale2)
8310
+ changes.delete(id3), recordIds.has(id3) || transaction.objectStore("records").delete(IDBKeyRange.bound([id3], [id3, []]));
8311
+ let bases = transaction.objectStore("bases");
8312
+ for (let key of await request(bases.getAllKeys()))
8313
+ typeof key == "string" && !artifactTokens.has(key) && bases.delete(key);
8314
+ await done;
8315
+ } catch (error) {
8316
+ try {
8317
+ transaction.abort();
8318
+ } catch {
8319
+ }
8320
+ throw await done.catch(() => {
8321
+ }), error;
8322
+ }
8323
+ },
8291
8324
  async current(partition) {
8292
8325
  let transaction = database.transaction(["current", "records", "changes", "bases"], "readonly"), done = completed(transaction), value = await request(transaction.objectStore("current").get(partition));
8293
8326
  if (!value) {
8294
8327
  await done;
8295
8328
  return;
8296
8329
  }
8297
- if (value.format !== "data-snapshot.v2" || !Array.isArray(value.timelineCollections) || value.partition !== partition || !value.id || !value.snapshotId || value.pairToken !== "" && !validSnapshotPairToken(value.pairToken) || !validSnapshotArtifactToken(value.artifactToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
8330
+ let recordsId = value.recordsId ?? value.id;
8331
+ if (value.format !== "data-snapshot.v2" || !Array.isArray(value.timelineCollections) || value.partition !== partition || !value.id || !recordsId || !value.snapshotId || value.pairToken !== "" && !validSnapshotPairToken(value.pairToken) || !validSnapshotArtifactToken(value.artifactToken) || !value.version || !Array.isArray(value.catalogue) || !value.counts || !(value.cursorKey instanceof Uint8Array) || value.cursorKey.length !== 32) {
8298
8332
  await done;
8299
8333
  return;
8300
8334
  }
8301
8335
  let changes = await request(transaction.objectStore("changes").get(value.id)), complete = !!await request(transaction.objectStore("bases").getKey(value.artifactToken)) && Array.isArray(changes) && changes.length === value.changeCount;
8302
8336
  for (let collection of value.catalogue)
8303
- await request(transaction.objectStore("records").index("collection").count([value.id, collection.name])) !== value.counts[collection.name] && (complete = !1);
8304
- return await done, complete ? value : void 0;
8337
+ await request(transaction.objectStore("records").index("collection").count([recordsId, collection.name])) !== value.counts[collection.name] && (complete = !1);
8338
+ return await done, complete ? { ...value, recordsId } : void 0;
8305
8339
  },
8306
8340
  async base(installation) {
8307
8341
  let transaction = database.transaction("bases", "readonly"), done = completed(transaction), base = await request(transaction.objectStore("bases").get(installation.artifactToken));
8308
8342
  return await done, base;
8309
8343
  },
8310
8344
  async install(partition, pairToken, envelope, changes, assertCurrent, snapshotId, artifact, unchangedRecords) {
8311
- let installation = {
8312
- id: crypto.randomUUID(),
8345
+ let id3 = crypto.randomUUID(), recordsId = unchangedRecords?.recordsId ?? id3, installation = {
8346
+ id: id3,
8347
+ recordsId,
8313
8348
  partition,
8314
8349
  pairToken,
8315
8350
  version: envelope.version,
@@ -8329,8 +8364,8 @@ async function openSnapshotStore() {
8329
8364
  try {
8330
8365
  assertCurrent(), transaction.objectStore("bases").put(artifact.base, artifact.token);
8331
8366
  let records = transaction.objectStore("records");
8332
- for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
8333
- records.put({ installation: installation.id, collection, ref: record4.$ref, record: record4 });
8367
+ if (!unchangedRecords) for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
8368
+ records.put({ installation: recordsId, collection, ref: record4.$ref, record: record4 });
8334
8369
  return await request(transaction.objectStore("changes").put(changes, installation.id)), await request(transaction.objectStore("current").put(installation, partition)), assertCurrent(), await done, assertCurrent(), installation;
8335
8370
  } catch (error) {
8336
8371
  try {
@@ -8352,7 +8387,7 @@ async function openSnapshotStore() {
8352
8387
  let records = transaction.objectStore("records"), collections = {}, prior = await request(transaction.objectStore("changes").get(installation.id));
8353
8388
  if (!prior || prior.length !== installation.changeCount) return unavailable2();
8354
8389
  for (let c of installation.catalogue) {
8355
- let rows = await request(records.index("collection").getAll([installation.id, c.name]));
8390
+ let rows = await request(records.index("collection").getAll([installation.recordsId, c.name]));
8356
8391
  if (rows.length !== installation.counts[c.name]) return unavailable2();
8357
8392
  collections[c.name] = rows.map((r) => r.record);
8358
8393
  }
@@ -8365,17 +8400,18 @@ async function openSnapshotStore() {
8365
8400
  timelineCollections: installation.timelineCollections,
8366
8401
  catalogue: installation.catalogue,
8367
8402
  collections
8368
- }, prior, mutation, installation), id3 = crypto.randomUUID(), next = {
8403
+ }, prior, mutation, installation), id3 = crypto.randomUUID(), recordsId = mutation.kind === "publish" ? id3 : installation.recordsId, next = {
8369
8404
  ...installation,
8370
8405
  id: id3,
8406
+ recordsId,
8371
8407
  pairToken: "",
8372
8408
  version: envelope.version,
8373
8409
  queryIdentity: mutation.kind === "publish" ? id3 : installation.queryIdentity ?? installation.id,
8374
8410
  changeCount: changes.length,
8375
8411
  counts: Object.fromEntries(Object.entries(envelope.collections).map(([name2, rows]) => [name2, rows.length]))
8376
8412
  };
8377
- for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
8378
- records.put({ installation: id3, collection, ref: record4.$ref, record: record4 });
8413
+ if (mutation.kind === "publish") for (let [collection, rows] of Object.entries(envelope.collections)) for (let record4 of rows)
8414
+ records.put({ installation: recordsId, collection, ref: record4.$ref, record: record4 });
8379
8415
  return transaction.objectStore("changes").put(changes, id3), (await request(transaction.objectStore("current").get(installation.partition)))?.id === installation.id && transaction.objectStore("current").put(next, installation.partition), assertCurrent(), await done, assertCurrent(), next;
8380
8416
  } catch (error) {
8381
8417
  try {
@@ -8387,7 +8423,7 @@ async function openSnapshotStore() {
8387
8423
  }
8388
8424
  },
8389
8425
  async read(installation, ref) {
8390
- let transaction = database.transaction("records", "readonly"), done = completed(transaction), row = await request(transaction.objectStore("records").get([installation.id, ref])), collection = snapshotCollection(installation.catalogue, ref).name, count = await request(transaction.objectStore("records").index("collection").count([installation.id, collection]));
8426
+ let transaction = database.transaction("records", "readonly"), done = completed(transaction), row = await request(transaction.objectStore("records").get([installation.recordsId, ref])), collection = snapshotCollection(installation.catalogue, ref).name, count = await request(transaction.objectStore("records").index("collection").count([installation.recordsId, collection]));
8391
8427
  return await done, count !== installation.counts[collection] ? unavailable2() : row?.record ?? null;
8392
8428
  },
8393
8429
  async changes(installation) {
@@ -8415,11 +8451,11 @@ async function openSnapshotStore() {
8415
8451
  for (; !step.done; ) {
8416
8452
  let work = step.value, value;
8417
8453
  if (work.operation === "scan") {
8418
- let rows = await request(records().index("collection").getAll([installation.id, work.collection]));
8454
+ let rows = await request(records().index("collection").getAll([installation.recordsId, work.collection]));
8419
8455
  if (rows.length !== installation.counts[work.collection]) return unavailable2();
8420
8456
  value = rows.map((row) => row.record);
8421
8457
  } else if (work.operation === "lookup") {
8422
- let row = await request(records().get([installation.id, work.ref]));
8458
+ let row = await request(records().get([installation.recordsId, work.ref]));
8423
8459
  value = row && { record: row.record, collection: row.collection };
8424
8460
  } else if (await finish(), work.operation === "seal") {
8425
8461
  let iv = crypto.getRandomValues(new Uint8Array(12)), sealed = new Uint8Array(await crypto.subtle.encrypt(
@@ -8516,22 +8552,30 @@ async function acquireSnapshot(store, partition, url, headers, repository, snaps
8516
8552
  version = `snapshot-${Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
8517
8553
  }
8518
8554
  let materialized = materializeSnapshot(base, acquired.changes, version);
8519
- return assertCurrent(), { installation: await store.install(
8555
+ assertCurrent();
8556
+ let artifactBase = base, install = () => store.install(
8520
8557
  partition,
8521
8558
  pairToken,
8522
8559
  materialized,
8523
8560
  acquired.changes,
8524
8561
  assertCurrent,
8525
8562
  acquired.snapshot.id,
8526
- { token: artifactToken, base },
8563
+ { token: artifactToken, base: artifactBase },
8527
8564
  update.records ? void 0 : reusable
8528
- ), update };
8565
+ ), installation;
8566
+ try {
8567
+ installation = await install();
8568
+ } catch (error) {
8569
+ if (!(error instanceof DataOperationError) || error.component !== "snapshot_cache") throw error;
8570
+ await store.compact(), assertCurrent(), installation = await install();
8571
+ }
8572
+ return { installation, update };
8529
8573
  }
8530
8574
  unavailable3();
8531
8575
  }
8532
8576
 
8533
8577
  function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile, connect) {
8534
- let listeners = /* @__PURE__ */ new Set(), session, socket, retry, expiry, stopAuthority, stopCredentials, delay = 250, stop = () => {
8578
+ let listeners = /* @__PURE__ */ new Set(), session, socket, retry, expiry, stopAuthority, stopCredentials, pending = { records: !1, changes: !1 }, delay = 250, stop = () => {
8535
8579
  session?.abort(), session = void 0;
8536
8580
  let prior = socket;
8537
8581
  socket = void 0, prior?.close(), clearTimeout(retry), clearTimeout(expiry), retry = expiry = void 0, stopAuthority?.(), stopAuthority = void 0, stopCredentials?.(), stopCredentials = void 0;
@@ -8542,7 +8586,12 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
8542
8586
  return stop(), !1;
8543
8587
  }
8544
8588
  }, notify = (update) => {
8545
- if (!(!update.records && !update.changes || !current2()))
8589
+ if (!(!update.records && !update.changes || !current2())) {
8590
+ if (!listeners.size) {
8591
+ pending = { records: pending.records || update.records, changes: pending.changes || update.changes };
8592
+ return;
8593
+ }
8594
+ update = { records: pending.records || update.records, changes: pending.changes || update.changes }, pending = { records: !1, changes: !1 };
8546
8595
  for (let listener of [...listeners]) {
8547
8596
  if (!current2()) break;
8548
8597
  if (listeners.has(listener))
@@ -8551,6 +8600,7 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
8551
8600
  } catch {
8552
8601
  }
8553
8602
  }
8603
+ }
8554
8604
  }, start = () => {
8555
8605
  if (!listeners.size || !current2()) return;
8556
8606
  let owned = new AbortController();
@@ -8577,7 +8627,7 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
8577
8627
  }
8578
8628
  } catch (error) {
8579
8629
  if (session !== owned) return;
8580
- error instanceof DataOperationError && ["context_unavailable", "unauthenticated", "access_denied", "not_found"].includes(error.code) ? lostAuthority() : reconnect(socket);
8630
+ error instanceof DataOperationError && (["context_unavailable", "unauthenticated", "access_denied", "not_found"].includes(error.code) || error.component === "snapshot_cache") ? lostAuthority() : reconnect(socket);
8581
8631
  } finally {
8582
8632
  running = !1;
8583
8633
  }
@@ -8625,7 +8675,17 @@ function snapshotListeners(url, authority2, assertCurrent, invalidate, reconcile
8625
8675
  subscribe(listener) {
8626
8676
  if (assertCurrent(), typeof listener != "function") throw new DataOperationError("invalid_query");
8627
8677
  let owned = (update) => listener(update);
8628
- return listeners.add(owned), listeners.size === 1 && start(), () => {
8678
+ if (listeners.add(owned), listeners.size === 1 && start(), pending.records || pending.changes) {
8679
+ let update = pending;
8680
+ pending = { records: !1, changes: !1 }, queueMicrotask(() => {
8681
+ if (!(!listeners.has(owned) || !current2()))
8682
+ try {
8683
+ owned({ ...update });
8684
+ } catch {
8685
+ }
8686
+ });
8687
+ }
8688
+ return () => {
8629
8689
  listeners.delete(owned), listeners.size || stop();
8630
8690
  };
8631
8691
  }
@@ -8701,7 +8761,7 @@ function captureSnapshotAll(query, options) {
8701
8761
  }
8702
8762
  var safeName = (value) => typeof value == "string" && /^[a-z0-9][a-z0-9._-]{0,127}$/.test(value) && !value.includes("..");
8703
8763
  function createSnapshotInitializer(resolve = resolveSnapshotContext, open = openSnapshotStore, connect = (url, protocols) => new WebSocket(url, protocols)) {
8704
- let pending = /* @__PURE__ */ new WeakMap();
8764
+ let pending = /* @__PURE__ */ new WeakMap(), maintenance = /* @__PURE__ */ new WeakMap();
8705
8765
  return async function(input) {
8706
8766
  let properties = dataProperties(input), repository = properties.repository?.value, snapshot = properties.snapshot?.value;
8707
8767
  if (Object.keys(properties).sort().join(",") !== "repository,snapshot" || !safeName(repository) || !safeName(snapshot)) return invalid11();
@@ -8728,11 +8788,22 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8728
8788
  } catch (error) {
8729
8789
  throw assertCurrent(), error instanceof DataOperationError ? error : new DataOperationError("unavailable", !0);
8730
8790
  }
8791
+ let compacted = maintenance.get(authority2.binding);
8792
+ compacted || (compacted = (async () => {
8793
+ let store = await open();
8794
+ try {
8795
+ await store.compact();
8796
+ } finally {
8797
+ store.close();
8798
+ }
8799
+ })(), maintenance.set(authority2.binding, compacted), compacted.catch(() => {
8800
+ }));
8731
8801
  let installation;
8732
8802
  if (cached) installation = cached;
8733
8803
  else {
8734
8804
  let installing = work.get(partition);
8735
8805
  installing || (installing = (async () => {
8806
+ await compacted;
8736
8807
  let store = await open();
8737
8808
  try {
8738
8809
  return (await acquireSnapshot(
@@ -8768,7 +8839,7 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8768
8839
  return writes = result2.catch(() => {
8769
8840
  }), result2;
8770
8841
  }, reconcile = (signal) => serial(async () => {
8771
- await ensureAccess();
8842
+ await compacted, await ensureAccess();
8772
8843
  let headers = authority2.headers, fenced = () => {
8773
8844
  if (assertAccess(), signal.aborted || headers.authorization !== authority2.headers.authorization) throw new DataOperationError("unavailable", !0);
8774
8845
  };
@@ -8796,13 +8867,13 @@ function createSnapshotInitializer(resolve = resolveSnapshotContext, open = open
8796
8867
  if (stopLive = live2.stop, cached) {
8797
8868
  let refresh2 = reconcile(authority2.signal);
8798
8869
  initialRefresh = refresh2, refresh2.then(live2.notify).catch((error) => {
8799
- error instanceof DataOperationError && ["context_unavailable", "unauthenticated", "access_denied", "not_found"].includes(error.code) && (invalidated = !0, live2.stop());
8870
+ error instanceof DataOperationError && (["context_unavailable", "unauthenticated", "access_denied", "not_found"].includes(error.code) || error.component === "snapshot_cache") && (invalidated = !0, live2.stop());
8800
8871
  }).finally(() => {
8801
8872
  initialRefresh === refresh2 && (initialRefresh = void 0);
8802
8873
  });
8803
8874
  }
8804
8875
  let publications = /* @__PURE__ */ new Map(), mutate = async (kind, payload, selected, publication) => {
8805
- if (await ensureAccess(), publication?.complete) return [];
8876
+ if (await compacted, await ensureAccess(), publication?.complete) return [];
8806
8877
  let body = { snapshotId: installation.snapshotId, ...payload };
8807
8878
  checkDataRequestSize(body, 2 * 1024 * 1024);
8808
8879
  let dispatched = !1, applied = !1, store;
@@ -10079,6 +10150,14 @@ var source = {
10079
10150
  }
10080
10151
  };
10081
10152
 
10153
+ function parseInboxLiveSetup(value) {
10154
+ let v = value;
10155
+ if (!v || Object.keys(v).sort().join(",") !== "expiresAt,key,token,topic,url,viewerId,workspaceId" || !INBOX_UUID.test(v.workspaceId) || !INBOX_UUID.test(v.viewerId) || v.topic !== `inbox:${v.workspaceId}:${v.viewerId}` || typeof v.key != "string" || !v.key || typeof v.token != "string" || !/^[A-Za-z0-9._-]{1,8192}$/.test(v.token) || !Number.isSafeInteger(v.expiresAt) || v.expiresAt <= Date.now()) throw new Error("Invalid Inbox subscription");
10156
+ let url = new URL(v.url);
10157
+ if (url.protocol !== "wss:" || url.username || url.password || url.search || url.hash || url.pathname !== "/realtime/v1/websocket") throw new Error("Invalid Inbox subscription");
10158
+ return v;
10159
+ }
10160
+
10082
10161
  function parseInboxRecordRefs(value) {
10083
10162
  let refs = serializable(value);
10084
10163
  if (!Array.isArray(refs) || !refs.length || refs.length > 100) throw new Error("Invalid Record read");
@@ -10087,9 +10166,13 @@ function parseInboxRecordRefs(value) {
10087
10166
  return result2;
10088
10167
  }
10089
10168
  var recordKey = ({ repository, ref }) => JSON.stringify([repository, ref]);
10090
- function parseInboxRecords(value) {
10169
+ function authoredInboxRecordRefs(body) {
10170
+ let refs = body.flatMap((block) => block.kind === "record" ? [block.record] : block.kind === "records" ? block.records : []);
10171
+ return [...new Map(refs.map((ref) => [recordKey(ref), ref])).values()];
10172
+ }
10173
+ function parseInboxRecords(value, maximumRecords = 100) {
10091
10174
  let result2 = serializable(value), keys7 = result2 ? Object.keys(result2).sort().join() : "";
10092
- if (!result2 || !["records", "links,records"].includes(keys7) || !Array.isArray(result2.records) || result2.records.length > 100) throw new Error("Invalid Record result");
10175
+ if (!result2 || !["records", "links,records"].includes(keys7) || !Array.isArray(result2.records) || result2.records.length > maximumRecords) throw new Error("Invalid Record result");
10093
10176
  for (let entry of result2.records) {
10094
10177
  if (!entry || typeof entry != "object") throw new Error("Invalid current Record");
10095
10178
  if (validateQualifiedRecordRef({ repository: entry.repository, ref: entry.ref }), Object.keys(entry).sort().join() !== "record,ref,repository,schema" || (entry.record === null ? entry.schema !== null : !entry.schema || entry.record.$ref !== entry.ref || typeof entry.record.$version != "string" || !Array.isArray(entry.schema.fields) || typeof entry.schema.name != "string"))
@@ -10161,6 +10244,8 @@ function isAppQuestionOperation(operation2) {
10161
10244
  }
10162
10245
  var operations = {
10163
10246
  current: [],
10247
+ bootstrap: [],
10248
+ "live.connect": [],
10164
10249
  "items.list": [],
10165
10250
  "questions.list": [],
10166
10251
  "items.read": ["itemId"],
@@ -10349,12 +10434,12 @@ function parseInboxItem(value) {
10349
10434
  let execution = object8(question2.execution);
10350
10435
  if (assert(id2(execution.id) && ["pending", "running", "completed", "failed"].includes(String(execution.state)) && integer(execution.attempt, 0)), "consequence" in execution) {
10351
10436
  let consequence = object8(execution.consequence);
10352
- keys6(consequence, ["phase", "updatedAt", "evidence"]), assert((consequence.phase === null || ["loading", "invoking", "committing"].includes(String(consequence.phase))) && date(consequence.updatedAt)), array2(consequence.evidence).forEach((value3) => {
10437
+ keys6(consequence, ["phase", "progressLabel", "updatedAt", "evidence"], ["phase", "updatedAt", "evidence"]), assert((consequence.phase === null || ["loading", "invoking", "committing"].includes(String(consequence.phase))) && date(consequence.updatedAt)), "progressLabel" in consequence && assert(consequence.progressLabel === null || text4(consequence.progressLabel) && consequence.progressLabel.length <= 256), array2(consequence.evidence).forEach((value3) => {
10353
10438
  let receipt = object8(value3);
10354
10439
  receipt.provider === "airtable" ? (keys6(receipt, ["provider", "connection", "baseId", "table", "operation", "records"]), assert(text4(receipt.connection) && /^airtable\/[a-z0-9][a-z0-9-]*$/.test(receipt.connection) && text4(receipt.baseId) && text4(receipt.table) && ["create", "update", "delete"].includes(String(receipt.operation))), array2(receipt.records).forEach((value4) => {
10355
10440
  let record4 = object8(value4);
10356
10441
  keys6(record4, ["id"]), assert(text4(record4.id));
10357
- })) : (keys6(receipt, ["repository", "commit", "diff"]), assert(text4(receipt.repository) && text4(receipt.commit) && text4(receipt.diff, !0)));
10442
+ })) : (keys6(receipt, ["repository", "commit", "diff", "url"]), assert(text4(receipt.repository) && text4(receipt.commit) && text4(receipt.diff, !0)), "url" in receipt && assert(text4(receipt.url) && /^https:\/\/github\.com\/[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+\/commit\/[0-9a-f]{40}$/.test(receipt.url) && receipt.url.endsWith(`/commit/${receipt.commit}`)));
10358
10443
  });
10359
10444
  }
10360
10445
  }
@@ -10419,6 +10504,8 @@ function parseInboxAcceptance(value) {
10419
10504
  }
10420
10505
  function parseInboxResult(operation2, value, contract = INBOX_QUESTION_CONTRACT) {
10421
10506
  if (operation2 === "current") return parseInboxCurrent(value);
10507
+ if (operation2 === "bootstrap") return parseInboxBootstrap(value);
10508
+ if (operation2 === "live.connect") return parseInboxLiveSetup(value);
10422
10509
  if (operation2 === "questions.list") {
10423
10510
  let page = object8(value);
10424
10511
  keys6(page, ["questions", "nextBeforeNumber"]);
@@ -10470,6 +10557,156 @@ function parseInboxResult(operation2, value, contract = INBOX_QUESTION_CONTRACT)
10470
10557
  }
10471
10558
  throw new Error("File content is not a JSON result");
10472
10559
  }
10560
+ function parseInboxBootstrap(value) {
10561
+ let snapshot = object8(value);
10562
+ keys6(snapshot, ["current", "items", "hydrations"]);
10563
+ let current2 = parseInboxCurrent(snapshot.current), items = array2(snapshot.items).map(parseInboxItem);
10564
+ assert(items.every((item) => item.workspaceId === current2.workspace.id) && new Set(items.map((item) => item.id)).size === items.length && new Set(items.map((item) => item.number)).size === items.length);
10565
+ let entries = array2(snapshot.hydrations);
10566
+ assert(entries.length === items.length);
10567
+ let hydrations = entries.map((value2, index) => {
10568
+ let entry = object8(value2), item = items[index];
10569
+ assert(entry.itemId === item.id && entry.revision === item.revision);
10570
+ let refs = authoredInboxRecordRefs(item.body);
10571
+ if (entry.status === "unavailable")
10572
+ return keys6(entry, ["itemId", "revision", "status"]), assert(refs.length > 0), { itemId: item.id, revision: item.revision, status: "unavailable" };
10573
+ keys6(entry, ["itemId", "revision", "status", "result"]), assert(entry.status === "ready");
10574
+ let result2 = parseInboxRecords(entry.result, refs.length);
10575
+ return assert(result2.records.length === refs.length && result2.records.every((row, index2) => recordKey(row) === recordKey(refs[index2])) && result2.links.every((link) => refs.some((ref) => ref.repository === link.repository))), { itemId: item.id, revision: item.revision, status: "ready", result: result2 };
10576
+ });
10577
+ return assert(new TextEncoder().encode(JSON.stringify({ current: current2, items, hydrations })).byteLength <= INBOX_RESULT_BYTES), { current: current2, items, hydrations };
10578
+ }
10579
+
10580
+ var runtime = {
10581
+ connect: (url) => new WebSocket(url),
10582
+ later: (callback, delay) => setTimeout(callback, delay),
10583
+ cancel: (timer) => clearTimeout(timer),
10584
+ now: Date.now
10585
+ };
10586
+ function subscribeInbox(resolve, authorize, onDirty, onState, rt = runtime, signal) {
10587
+ let active2 = !0, generation = 0, failures2 = 0, sequence = 0, authority2, socket, unsubscribe, retry, heartbeat, renewal, deadline, heartbeatRef, notify = (state) => {
10588
+ if (active2)
10589
+ try {
10590
+ onState?.(state);
10591
+ } catch {
10592
+ }
10593
+ }, clear = () => {
10594
+ for (let timer of [retry, heartbeat, renewal, deadline]) timer !== void 0 && rt.cancel(timer);
10595
+ retry = heartbeat = renewal = deadline = void 0;
10596
+ let prior = socket;
10597
+ socket = void 0, prior?.close(), heartbeatRef = void 0;
10598
+ }, current2 = () => active2 && !!authority2?.isCurrent() && !authority2.signal.aborted, stop = () => {
10599
+ active2 && (active2 = !1, generation++, clear(), unsubscribe?.(), authority2?.signal.removeEventListener("abort", revoked), signal?.removeEventListener("abort", revoked));
10600
+ }, revoked = () => {
10601
+ notify("denied"), stop();
10602
+ };
10603
+ function reconnect() {
10604
+ if (active2) {
10605
+ if (!current2()) {
10606
+ revoked();
10607
+ return;
10608
+ }
10609
+ generation++, clear(), notify("unavailable"), retry = rt.later(() => {
10610
+ retry = void 0, open();
10611
+ }, Math.min(3e4, 500 * 2 ** Math.min(failures2++, 6)));
10612
+ }
10613
+ }
10614
+ async function open() {
10615
+ let started = ++generation;
10616
+ clear();
10617
+ try {
10618
+ let beat2 = function() {
10619
+ if (valid()) {
10620
+ if (heartbeatRef) {
10621
+ reconnect();
10622
+ return;
10623
+ }
10624
+ heartbeatRef = String(++sequence), send3("heartbeat", {}, heartbeatRef, "phoenix"), heartbeat = rt.later(beat2, 25e3);
10625
+ }
10626
+ };
10627
+ var beat = beat2;
10628
+ let setup = await authorize();
10629
+ if (!active2 || started !== generation) return;
10630
+ if (!current2()) {
10631
+ revoked();
10632
+ return;
10633
+ }
10634
+ if (setup.expiresAt <= rt.now()) throw new Error();
10635
+ let url = new URL(setup.url);
10636
+ url.searchParams.set("apikey", setup.key), url.searchParams.set("vsn", "1.0.0");
10637
+ let connection = rt.connect(url.href);
10638
+ socket = connection;
10639
+ let valid = () => active2 && current2() && started === generation && socket === connection, topic = `realtime:${setup.topic}`, join = String(++sequence), joined = !1, send3 = (event, payload, ref = String(++sequence), destination = topic) => connection.send(JSON.stringify({ topic: destination, event, payload, ref }));
10640
+ deadline = rt.later(reconnect, 15e3), connection.addEventListener("open", () => {
10641
+ valid() && send3("phx_join", {
10642
+ config: { private: !0, broadcast: { ack: !1, self: !1 }, presence: { enabled: !1 }, postgres_changes: [] },
10643
+ access_token: setup.token
10644
+ }, join);
10645
+ }), connection.addEventListener("message", (event) => {
10646
+ if (!valid() || typeof event.data != "string" || event.data.length > 8192) return;
10647
+ let value;
10648
+ try {
10649
+ value = JSON.parse(event.data);
10650
+ } catch {
10651
+ return;
10652
+ }
10653
+ if (!(!value || typeof value != "object" || Array.isArray(value))) {
10654
+ if (value.topic === "phoenix" && value.event === "phx_reply" && value.ref === heartbeatRef) {
10655
+ heartbeatRef = void 0;
10656
+ return;
10657
+ }
10658
+ if (value.topic === topic)
10659
+ if (value.event === "phx_reply" && value.ref === join && !joined) {
10660
+ if (value.payload?.status !== "ok") {
10661
+ reconnect();
10662
+ return;
10663
+ }
10664
+ if (joined = !0, failures2 = 0, deadline !== void 0 && rt.cancel(deadline), deadline = void 0, notify("connected"), !valid()) return;
10665
+ heartbeat = rt.later(beat2, 25e3), renewal = rt.later(() => {
10666
+ open();
10667
+ }, Math.max(0, setup.expiresAt - rt.now() - 6e4));
10668
+ } else if (joined && value.event === "broadcast" && value.payload?.event === "dirty" && value.payload.type === "broadcast" && value.payload.payload && typeof value.payload.payload == "object" && !Array.isArray(value.payload.payload) && Object.keys(value.payload.payload).length === 0)
10669
+ try {
10670
+ onDirty();
10671
+ } catch {
10672
+ }
10673
+ else (value.event === "phx_error" || value.event === "phx_close" || value.event === "system" && value.payload?.status === "error") && reconnect();
10674
+ }
10675
+ }), connection.addEventListener("close", () => {
10676
+ valid() && reconnect();
10677
+ }), connection.addEventListener("error", () => {
10678
+ valid() && reconnect();
10679
+ });
10680
+ } catch (error) {
10681
+ if (!active2 || started !== generation) return;
10682
+ if (error instanceof InboxOperationError && (error.status === 401 || error.status === 403)) {
10683
+ revoked();
10684
+ return;
10685
+ }
10686
+ reconnect();
10687
+ }
10688
+ }
10689
+ async function initialize() {
10690
+ if (active2)
10691
+ try {
10692
+ let result2 = await resolve();
10693
+ if (!active2) return;
10694
+ if (authority2 = result2, !current2()) {
10695
+ revoked();
10696
+ return;
10697
+ }
10698
+ authority2.signal.addEventListener("abort", revoked, { once: !0 }), unsubscribe = authority2.subscribe?.(() => {
10699
+ current2() ? open() : revoked();
10700
+ }), open();
10701
+ } catch (error) {
10702
+ if (!active2) return;
10703
+ error instanceof InboxOperationError && (error.status === 401 || error.status === 403) ? revoked() : (notify("unavailable"), retry = rt.later(() => {
10704
+ retry = void 0, initialize();
10705
+ }, Math.min(3e4, 500 * 2 ** Math.min(failures2++, 6))));
10706
+ }
10707
+ }
10708
+ return signal?.aborted ? revoked() : (signal?.addEventListener("abort", revoked, { once: !0 }), initialize()), stop;
10709
+ }
10473
10710
 
10474
10711
  async function limitedBody(request3, limit, timeoutMs) {
10475
10712
  if (!request3.body) return new Uint8Array();
@@ -10520,7 +10757,13 @@ function resolveHostedInboxContext(host, mode = "fresh") {
10520
10757
  return resolve || (resolve = hostedInboxContext(), contexts.set(host.binding, resolve)), resolve({ ...host, memberId: host.memberId }, mode);
10521
10758
  }
10522
10759
  function hostedInboxContext() {
10523
- let installed2, retained, pending, denied, revision = 0, issued = 0, settled = 0;
10760
+ let installed2, retained, pending, denied, revision = 0, issued = 0, settled = 0, observers = /* @__PURE__ */ new Set(), notify = () => {
10761
+ for (let observer2 of observers)
10762
+ try {
10763
+ observer2();
10764
+ } catch {
10765
+ }
10766
+ };
10524
10767
  return async (host, mode = "fresh") => {
10525
10768
  let check = () => {
10526
10769
  if (!host.isCurrent() || host.expiresAt <= Date.now()) throw new Error("Inbox context unavailable");
@@ -10535,7 +10778,7 @@ function hostedInboxContext() {
10535
10778
  return check(), bind(value);
10536
10779
  }
10537
10780
  let started = ++issued, valid = host.snapshot?.isCurrent ?? host.isCurrent, invalidate = (status) => {
10538
- installed2 = void 0, retained = void 0, pending = void 0, denied = { endpoint: host.endpoint, memberId: host.memberId, valid, status }, revision++, settled = ++issued;
10781
+ installed2 = void 0, retained = void 0, pending = void 0, denied = { endpoint: host.endpoint, memberId: host.memberId, valid, status }, revision++, settled = ++issued, notify();
10539
10782
  }, result2 = (async () => {
10540
10783
  let response2 = await fetch(`${host.endpoint}/api/inbox/context`, {
10541
10784
  method: "GET",
@@ -10553,8 +10796,19 @@ function hostedInboxContext() {
10553
10796
  if (context.memberId !== host.memberId || context.kind === "inbox" && !current2 || current2 && (context.kind !== "inbox" || current2.viewer.id !== host.memberId || current2.workspace.id !== context.workspaceId || host.endpoint !== `https://${current2.workspace.slug}.oddington.ai`))
10554
10797
  throw new Error("Inbox context unavailable");
10555
10798
  if (started < settled) throw new Error("Inbox context unavailable");
10556
- JSON.stringify(installed2) !== JSON.stringify(context) && (installed2 = context, revision++), settled = started, denied = void 0;
10557
- let generation = revision, startup = Object.freeze({ context, current: current2, invalidate, isCurrent: () => valid() && generation === revision });
10799
+ JSON.stringify(installed2) !== JSON.stringify(context) && (installed2 = context, revision++, notify()), settled = started, denied = void 0;
10800
+ let generation = revision, isRetainedCurrent = () => valid() && generation === revision, startup = Object.freeze({
10801
+ context,
10802
+ current: current2,
10803
+ invalidate,
10804
+ isCurrent: isRetainedCurrent,
10805
+ isRetainedCurrent,
10806
+ onInvalidate(listener) {
10807
+ return observers.add(listener), () => {
10808
+ observers.delete(listener);
10809
+ };
10810
+ }
10811
+ });
10558
10812
  return retained = current2 ? { value: startup, endpoint: host.endpoint, memberId: host.memberId, valid: startup.isCurrent } : void 0, startup;
10559
10813
  } finally {
10560
10814
  response2.body?.cancel().catch(() => {
@@ -11018,8 +11272,8 @@ var WorkspaceAccessError = class extends Error {
11018
11272
  };
11019
11273
 
11020
11274
  var unavailable5 = () => new InboxOperationError(503, "unavailable"), stale = () => new InboxOperationError(401, "authority_unavailable"), contextFailure = (error) => error instanceof WorkspaceAccessError ? new InboxOperationError(error.status, error.status === 401 ? "authority_unavailable" : error.status === 403 ? "access_denied" : "unavailable") : stale();
11021
- function hostFailure(error, context) {
11022
- return !context.isCurrent() || context.expiresAt <= Date.now() || error instanceof InboxContextError && error.status === 401 ? stale() : error instanceof InboxContextError && (error.status === 400 || error.status === 409) ? new InboxOperationError(error.status, error.status === 400 ? "invalid_input" : "conflict") : error instanceof InboxContextError && error.status === 403 ? new InboxOperationError(403, "access_denied") : unavailable5();
11275
+ function hostFailure(error, context, live2 = !1) {
11276
+ return live2 && context.snapshot?.isCurrent() && !context.signal?.aborted && !(error instanceof InboxContextError && (error.status === 401 || error.status === 403)) ? unavailable5() : !context.isCurrent() || context.expiresAt <= Date.now() || error instanceof InboxContextError && error.status === 401 ? stale() : error instanceof InboxContextError && (error.status === 400 || error.status === 409) ? new InboxOperationError(error.status, error.status === 400 ? "invalid_input" : "conflict") : error instanceof InboxContextError && error.status === 403 ? new InboxOperationError(403, "access_denied") : unavailable5();
11023
11277
  }
11024
11278
  async function send2(operation2, input, resolved, admitted) {
11025
11279
  let envelope = parseInboxRequest({
@@ -11030,7 +11284,7 @@ async function send2(operation2, input, resolved, admitted) {
11030
11284
  try {
11031
11285
  context = resolved ?? await resolveAppContext(!1, !isAppQuestionOperation(operation2));
11032
11286
  } catch (error) {
11033
- throw contextFailure(error);
11287
+ throw operation2 === "live.connect" && !(error instanceof WorkspaceAccessError) && !memberContextSignal()?.aborted ? unavailable5() : contextFailure(error);
11034
11288
  }
11035
11289
  if (context.kind === "local") {
11036
11290
  if (!isAppQuestionOperation(operation2)) throw new InboxOperationError(403, "access_denied");
@@ -11056,11 +11310,15 @@ async function send2(operation2, input, resolved, admitted) {
11056
11310
  try {
11057
11311
  host = admitted ?? await resolveHostedInboxContext(context, "member");
11058
11312
  } catch (error) {
11059
- throw hostFailure(error, context);
11313
+ throw hostFailure(error, context, operation2 === "live.connect");
11060
11314
  }
11061
11315
  if (!host) throw unavailable5();
11062
11316
  }
11063
11317
  let check = () => {
11318
+ if (operation2 === "live.connect" && context.snapshot) {
11319
+ if (!context.snapshot.isCurrent() || context.signal?.aborted || host && !host.isRetainedCurrent()) throw stale();
11320
+ return;
11321
+ }
11064
11322
  if (!context.isCurrent() || host && !host.isCurrent() || !Number.isFinite(context.expiresAt) || context.expiresAt <= Date.now()) throw stale();
11065
11323
  };
11066
11324
  if (check(), host?.context.kind === "focused")
@@ -11104,17 +11362,57 @@ async function send2(operation2, input, resolved, admitted) {
11104
11362
  let bytes = await limitedBody(response2, INBOX_RESULT_BYTES);
11105
11363
  if (check(), !bytes) throw unavailable5();
11106
11364
  let value = JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes)), parsed = parseInboxResult(operation2, value);
11107
- if (check(), operation2 === "current" && parsed.workspace.slug !== context.workspace) throw unavailable5();
11365
+ if (check(), operation2 === "bootstrap") {
11366
+ let snapshot = parsed;
11367
+ if (snapshot.current.workspace.slug !== context.workspace || snapshot.current.viewer.id !== context.memberId || snapshot.current.workspace.id !== host?.context.workspaceId) throw unavailable5();
11368
+ }
11369
+ if (operation2 === "live.connect") {
11370
+ let live2 = parsed;
11371
+ if (live2.workspaceId !== host?.context.workspaceId || live2.viewerId !== context.memberId) throw unavailable5();
11372
+ }
11373
+ if (operation2 === "current" && parsed.workspace.slug !== context.workspace) throw unavailable5();
11108
11374
  if ("itemId" in envelope.input) {
11109
11375
  let item = operation2 === "items.read" ? parsed : operation2 === "items.rename" || operation2 === "items.setLifecycle" || operation2 === "items.addRecipient" ? parsed.item : void 0;
11110
11376
  if (item && (item.id !== envelope.input.itemId || "revision" in envelope.input && item.revision !== envelope.input.revision) || operation2 === "items.addRecipient" && parsed.addedPersonId !== envelope.input.personId) throw unavailable5();
11111
11377
  }
11112
11378
  return parsed;
11113
11379
  } catch (error) {
11114
- throw check(), operation2 === "items.list" && error instanceof InboxOperationError && (error.status === 401 || error.status === 403) && host?.invalidate(error.status), error instanceof InboxOperationError ? error : unavailable5();
11380
+ throw check(), (operation2 === "items.list" || operation2 === "bootstrap" || operation2 === "live.connect") && error instanceof InboxOperationError && (error.status === 401 || error.status === 403) && host?.invalidate(error.status), error instanceof InboxOperationError ? error : unavailable5();
11115
11381
  }
11116
11382
  }
11117
11383
  var inbox = {
11384
+ subscribe: (onDirty, onState) => {
11385
+ let lifetime = memberContextSignal();
11386
+ return subscribeInbox(async () => {
11387
+ if (lifetime?.aborted) throw stale();
11388
+ let context;
11389
+ try {
11390
+ context = await resolveAppContext(!1, !0);
11391
+ } catch (error) {
11392
+ throw !(error instanceof WorkspaceAccessError) && lifetime && !lifetime.aborted ? unavailable5() : contextFailure(error);
11393
+ }
11394
+ if (context.kind === "local" || !lifetime) throw new InboxOperationError(403, "access_denied");
11395
+ let host;
11396
+ try {
11397
+ host = await resolveHostedInboxContext(context, "member");
11398
+ } catch (error) {
11399
+ throw hostFailure(error, context, !0);
11400
+ }
11401
+ if (host.context.kind !== "inbox") throw new InboxOperationError(403, "access_denied");
11402
+ let initial = context;
11403
+ return {
11404
+ signal: initial.signal ? AbortSignal.any([lifetime, initial.signal]) : lifetime,
11405
+ isCurrent: () => (initial.snapshot?.isCurrent() ?? initial.isCurrent()) && host.isRetainedCurrent() && !lifetime.aborted,
11406
+ subscribe(listener) {
11407
+ let credentials = initial.snapshot?.subscribe(listener), scope = host.onInvalidate(listener);
11408
+ return () => {
11409
+ credentials?.(), scope();
11410
+ };
11411
+ }
11412
+ };
11413
+ }, async () => await send2("live.connect", {}), onDirty, onState, void 0, lifetime);
11414
+ },
11415
+ bootstrap: async () => await send2("bootstrap", {}),
11118
11416
  async current() {
11119
11417
  let context;
11120
11418
  try {
@@ -11486,7 +11784,7 @@ function createLocalBrowserAuth(origin, failure) {
11486
11784
  }), handle2;
11487
11785
  }
11488
11786
 
11489
- function createBrowserAuth(runtime) {
11787
+ function createBrowserAuth(runtime2) {
11490
11788
  let coordinators2 = /* @__PURE__ */ new Map();
11491
11789
  function publish2(c, state) {
11492
11790
  c.state = Object.freeze(state);
@@ -11599,14 +11897,14 @@ function createBrowserAuth(runtime) {
11599
11897
  return c.ready = (async () => {
11600
11898
  let revision = c.revision;
11601
11899
  try {
11602
- if (!allowedOrigin(origin)) throw runtime.failure("unavailable");
11603
- runtime.prepare?.();
11900
+ if (!allowedOrigin(origin)) throw runtime2.failure("unavailable");
11901
+ runtime2.prepare?.();
11604
11902
  let response2 = await fetch(`${origin}/api/auth`, { method: "GET", credentials: "same-origin", redirect: "error", cache: "no-store" });
11605
- if (!response2.ok) throw runtime.failure("unavailable");
11903
+ if (!response2.ok) throw runtime2.failure("unavailable");
11606
11904
  let configuration = validateConfiguration(await response2.json());
11607
- if (configuration.authorization && origin !== "https://auth.oddington.ai" && origin !== "http://127.0.0.1:5176") throw runtime.failure("unavailable");
11905
+ if (configuration.authorization && origin !== "https://auth.oddington.ai" && origin !== "http://127.0.0.1:5176") throw runtime2.failure("unavailable");
11608
11906
  if (c.authorization = configuration.authorization, !c.active || globalThis.location?.origin !== origin) return;
11609
- if (c.provider = await runtime.provider(configuration, {
11907
+ if (c.provider = await runtime2.provider(configuration, {
11610
11908
  revision: () => c.revision,
11611
11909
  current: (revision2) => current2(c, origin, revision2),
11612
11910
  canPersistSession: () => c.active && (c.state.status === "initializing" || !!c.session || c.state.pending === "verify_code"),
@@ -11637,7 +11935,7 @@ function createBrowserAuth(runtime) {
11637
11935
  async function checkWorkspaceAccess(c, origin) {
11638
11936
  if (origin === "https://auth.oddington.ai" || origin === "http://127.0.0.1:5176") return;
11639
11937
  let revision = c.revision;
11640
- if (!current2(c, origin, revision) || !c.session || !validSession(c.session) || c.state.pending === "sign_out") throw runtime.failure("stale");
11938
+ if (!current2(c, origin, revision) || !c.session || !validSession(c.session) || c.state.pending === "sign_out") throw runtime2.failure("stale");
11641
11939
  if (c.workspaceAccess?.revision !== revision) {
11642
11940
  let token = c.session.access_token, result2 = (async () => {
11643
11941
  let status;
@@ -11657,16 +11955,16 @@ function createBrowserAuth(runtime) {
11657
11955
  } catch {
11658
11956
  status = 503;
11659
11957
  }
11660
- if (!current2(c, origin, revision) || c.state.pending === "sign_out") throw runtime.failure("stale");
11958
+ if (!current2(c, origin, revision) || c.state.pending === "sign_out") throw runtime2.failure("stale");
11661
11959
  if (status !== 200) throw new WorkspaceAccessError(status === 401 ? 401 : status === 403 ? 403 : 503);
11662
11960
  })();
11663
11961
  c.workspaceAccess = { revision, result: result2 };
11664
11962
  }
11665
- if (await c.workspaceAccess.result, !current2(c, origin, revision)) throw runtime.failure("stale");
11963
+ if (await c.workspaceAccess.result, !current2(c, origin, revision)) throw runtime2.failure("stale");
11666
11964
  }
11667
11965
  return { create() {
11668
11966
  let origin = globalThis.location?.origin ?? "";
11669
- if (isAppOrigin(origin) && origin !== "http://127.0.0.1:5176") return createLocalBrowserAuth(origin, runtime.failure);
11967
+ if (isAppOrigin(origin) && origin !== "http://127.0.0.1:5176") return createLocalBrowserAuth(origin, runtime2.failure);
11670
11968
  let c = coordinators2.get(origin);
11671
11969
  c || (c = createCoordinator(origin), coordinators2.set(origin, c));
11672
11970
  let coordinator = c;
@@ -11681,21 +11979,21 @@ function createBrowserAuth(runtime) {
11681
11979
  };
11682
11980
  coordinator.listeners.add(observation);
11683
11981
  let assertActive = () => {
11684
- if (!active2) throw runtime.failure("disposed");
11982
+ if (!active2) throw runtime2.failure("disposed");
11685
11983
  };
11686
11984
  async function action(kind, work) {
11687
- if (assertActive(), coordinator.action && kind !== "sign_out" || kind === "sign_out" && coordinator.state.pending === "sign_out") throw runtime.failure("busy");
11985
+ if (assertActive(), coordinator.action && kind !== "sign_out" || kind === "sign_out" && coordinator.state.pending === "sign_out") throw runtime2.failure("busy");
11688
11986
  kind === "sign_out" && (coordinator.revision++, coordinator.resolution?.cancel(), coordinator.timer && clearTimeout(coordinator.timer), coordinator.session = null, publish2(coordinator, { status: "signed_out", pending: "sign_out" }), notify(coordinator, "SIGNED_OUT"));
11689
11987
  let marker = {};
11690
11988
  coordinator.action = marker, ownedAction = marker;
11691
11989
  let revision = coordinator.revision;
11692
11990
  publish2(coordinator, { ...coordinator.state, error: void 0, pending: kind });
11693
11991
  try {
11694
- if (await ready(coordinator), assertActive(), !coordinator.provider || !coordinator.active || globalThis.location?.origin !== origin) throw runtime.failure("unavailable");
11695
- if (!current2(coordinator, origin, revision) || coordinator.action !== marker || (await work(coordinator.provider), assertActive(), coordinator.action !== marker) || !current2(coordinator, origin, revision) && kind !== "verify_code" && kind !== "sign_out") throw runtime.failure("stale");
11992
+ if (await ready(coordinator), assertActive(), !coordinator.provider || !coordinator.active || globalThis.location?.origin !== origin) throw runtime2.failure("unavailable");
11993
+ if (!current2(coordinator, origin, revision) || coordinator.action !== marker || (await work(coordinator.provider), assertActive(), coordinator.action !== marker) || !current2(coordinator, origin, revision) && kind !== "verify_code" && kind !== "sign_out") throw runtime2.failure("stale");
11696
11994
  } catch (error) {
11697
11995
  let reason = active2 ? current2(coordinator, origin, revision) ? safeReason(error) ?? "unavailable" : "stale" : "disposed";
11698
- throw active2 && current2(coordinator, origin, revision) && publish2(coordinator, { ...coordinator.state, error: reason }), runtime.failure(reason);
11996
+ throw active2 && current2(coordinator, origin, revision) && publish2(coordinator, { ...coordinator.state, error: reason }), runtime2.failure(reason);
11699
11997
  } finally {
11700
11998
  coordinator.action === marker && (coordinator.action = void 0, coordinator.active && (publish2(coordinator, { ...coordinator.state, pending: void 0 }), kind === "sign_out" && coordinator.session && notify(coordinator, "TOKEN_REFRESHED"))), ownedAction === marker && (ownedAction = void 0);
11701
11999
  }
@@ -11755,21 +12053,21 @@ function createBrowserAuth(runtime) {
11755
12053
  };
11756
12054
  },
11757
12055
  async sendCode(email) {
11758
- if (assertActive(), !validEmail(email)) throw runtime.failure("invalid_input");
12056
+ if (assertActive(), !validEmail(email)) throw runtime2.failure("invalid_input");
11759
12057
  await action("send_code", async (provider2) => {
11760
12058
  let { error } = await provider2.signInWithOtp({ email: email.trim(), options: {
11761
12059
  shouldCreateUser: origin !== "https://auth.oddington.ai" && origin !== "http://127.0.0.1:5176"
11762
12060
  } });
11763
- if (error && !accountRefusal(error)) throw runtime.failure("unavailable");
12061
+ if (error && !accountRefusal(error)) throw runtime2.failure("unavailable");
11764
12062
  });
11765
12063
  },
11766
12064
  async verifyCode(email, code) {
11767
- if (assertActive(), !validEmail(email) || typeof code != "string" || !/^\d{6}$/.test(code)) throw runtime.failure("invalid_input");
12065
+ if (assertActive(), !validEmail(email) || typeof code != "string" || !/^\d{6}$/.test(code)) throw runtime2.failure("invalid_input");
11768
12066
  await action("verify_code", async (provider2) => {
11769
12067
  let revision = coordinator.revision, { data: data3, error } = await provider2.verifyOtp({ email: email.trim(), token: code, type: "email" });
11770
- if (error) throw runtime.failure(accountRefusal(error) ? "invalid_code" : "unavailable");
11771
- if (!data3.session || !validSession(data3.session)) throw runtime.failure("invalid_code");
11772
- if (!current2(coordinator, origin, revision) && (coordinator.session?.access_token !== data3.session.access_token || coordinator.revision !== revision + 1 || coordinator.state.pending !== "verify_code")) throw runtime.failure("stale");
12068
+ if (error) throw runtime2.failure(accountRefusal(error) ? "invalid_code" : "unavailable");
12069
+ if (!data3.session || !validSession(data3.session)) throw runtime2.failure("invalid_code");
12070
+ if (!current2(coordinator, origin, revision) && (coordinator.session?.access_token !== data3.session.access_token || coordinator.revision !== revision + 1 || coordinator.state.pending !== "verify_code")) throw runtime2.failure("stale");
11773
12071
  accept(coordinator, "SIGNED_IN", data3.session);
11774
12072
  try {
11775
12073
  await checkWorkspaceAccess(coordinator, origin);
@@ -11781,8 +12079,8 @@ function createBrowserAuth(runtime) {
11781
12079
  async signOut() {
11782
12080
  assertActive(), await action("sign_out", async (provider2) => {
11783
12081
  let revision = coordinator.revision, { error } = await provider2.signOut({ scope: "local" });
11784
- if (error) throw runtime.failure("unavailable");
11785
- if (!current2(coordinator, origin, revision) && coordinator.session) throw runtime.failure("stale");
12082
+ if (error) throw runtime2.failure("unavailable");
12083
+ if (!current2(coordinator, origin, revision) && coordinator.session) throw runtime2.failure("stale");
11786
12084
  accept(coordinator, "SIGNED_OUT", null);
11787
12085
  });
11788
12086
  },
@@ -11817,7 +12115,7 @@ function createBrowserAuth(runtime) {
11817
12115
  async getSession() {
11818
12116
  assertActive(), await ready(coordinator), assertActive();
11819
12117
  let revision = coordinator.revision;
11820
- return !current2(coordinator, origin, revision) || !coordinator.provider || !coordinator.session || coordinator.state.pending === "sign_out" ? { data: { session: null }, error: null } : (await resolveSession(coordinator), active2 ? !current2(coordinator, origin, revision) || !coordinator.session || !validSession(coordinator.session) ? { data: { session: null }, error: runtime.failure("unavailable") } : { data: { session: coordinator.session }, error: null } : { data: { session: null }, error: runtime.failure("disposed") });
12118
+ return !current2(coordinator, origin, revision) || !coordinator.provider || !coordinator.session || coordinator.state.pending === "sign_out" ? { data: { session: null }, error: null } : (await resolveSession(coordinator), active2 ? !current2(coordinator, origin, revision) || !coordinator.session || !validSession(coordinator.session) ? { data: { session: null }, error: runtime2.failure("unavailable") } : { data: { session: coordinator.session }, error: null } : { data: { session: null }, error: runtime2.failure("disposed") });
11821
12119
  },
11822
12120
  onAuthStateChange(callback) {
11823
12121
  if (!active2)