@agentshouse/mdruntime 0.1.0-alpha.30 → 0.1.0-alpha.31

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.
@@ -1,11 +1,7 @@
1
1
  import type { ModelState } from './model.js';
2
2
  import type { Adapter, AdapterFailure, Authorization, DiscoveredRoom } from './adapter.js';
3
- import { type ConfirmedLayer } from './replica.js';
4
- import { type Unconfirmed } from './transfer.js';
5
- export type BootstrapOutcome = {
6
- kind: 'staged';
7
- confirmed: ConfirmedLayer;
8
- } | Unconfirmed | AdapterFailure;
3
+ import { type Staged } from './replica.js';
4
+ export type BootstrapOutcome = Staged | AdapterFailure;
9
5
  export declare function bootstrapRoom(adapter: Adapter, authorization: Authorization, room: DiscoveredRoom, models: {
10
6
  collection: ModelState;
11
7
  selection: ModelState;
@@ -1 +1 @@
1
- {"version":3,"file":"bootstrap.d.ts","sourceRoot":"","sources":["../src/bootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC3F,OAAO,EAAc,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAC/D,OAAO,EAAe,KAAK,WAAW,EAAE,MAAM,eAAe,CAAC;AAE9D,MAAM,MAAM,gBAAgB,GACxB;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,SAAS,EAAE,cAAc,CAAA;CAAE,GAC7C,WAAW,GACX,cAAc,CAAC;AAEnB,wBAAsB,aAAa,CACjC,OAAO,EAAE,OAAO,EAChB,aAAa,EAAE,aAAa,EAC5B,IAAI,EAAE,cAAc,EACpB,MAAM,EAAE;IAAE,UAAU,EAAE,UAAU,CAAC;IAAC,SAAS,EAAE,UAAU,CAAA;CAAE,GACxD,OAAO,CAAC,gBAAgB,CAAC,CAyC3B"}
1
+ {"version":3,"file":"bootstrap.d.ts","sourceRoot":"","sources":["../src/bootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC3F,OAAO,EAAc,KAAK,MAAM,EAAE,MAAM,cAAc,CAAC;AAGvD,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,cAAc,CAAC;AAEvD,wBAAsB,aAAa,CACjC,OAAO,EAAE,OAAO,EAChB,aAAa,EAAE,aAAa,EAC5B,IAAI,EAAE,cAAc,EACpB,MAAM,EAAE;IAAE,UAAU,EAAE,UAAU,CAAC;IAAC,SAAS,EAAE,UAAU,CAAA;CAAE,GACxD,OAAO,CAAC,gBAAgB,CAAC,CAwC3B"}
package/dist/bootstrap.js CHANGED
@@ -28,7 +28,7 @@ export async function bootstrapRoom(adapter, authorization, room, models) {
28
28
  for (const target of page.binaryTargets)binaryTargets.add(target);
29
29
  pageToken = page.pageToken;
30
30
  }
31
- const confirmed = readStaged({
31
+ return readStaged({
32
32
  locator: room.locator,
33
33
  collectionRoot: room.collectionRoot,
34
34
  name: room.name,
@@ -46,10 +46,6 @@ export async function bootstrapRoom(adapter, authorization, room, models) {
46
46
  ].sort(),
47
47
  revisions
48
48
  });
49
- return confirmed === null ? unconfirmed : {
50
- kind: 'staged',
51
- confirmed
52
- };
53
49
  }
54
50
 
55
51
  //# sourceMappingURL=bootstrap.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/bootstrap.ts"],"sourcesContent":["import type { ModelState } from './model.js';\nimport type { Adapter, AdapterFailure, Authorization, DiscoveredRoom } from './adapter.js';\nimport { readStaged, type ConfirmedLayer } from './replica.js';\nimport { unconfirmed, type Unconfirmed } from './transfer.js';\n\nexport type BootstrapOutcome =\n | { kind: 'staged'; confirmed: ConfirmedLayer }\n | Unconfirmed\n | AdapterFailure;\n\nexport async function bootstrapRoom(\n adapter: Adapter,\n authorization: Authorization,\n room: DiscoveredRoom,\n models: { collection: ModelState; selection: ModelState },\n): Promise<BootstrapOutcome> {\n const first = await adapter.bootstrap(authorization, {\n locator: room.locator,\n selection: room.replica.selection,\n });\n if (first.kind !== 'bootstrap') return first;\n const roomVersion = first.roomVersion;\n const documents: Record<string, string> = { ...first.documents };\n const revisions: Record<string, string> = { ...first.revisions };\n const binaryTargets = new Set(first.binaryTargets);\n let pageToken = first.pageToken;\n while (pageToken !== undefined) {\n const page = await adapter.bootstrap(authorization, {\n locator: room.locator,\n selection: room.replica.selection,\n pageToken,\n });\n if (page.kind !== 'bootstrap') return page;\n if (page.roomVersion !== roomVersion) return unconfirmed;\n Object.assign(documents, page.documents);\n Object.assign(revisions, page.revisions);\n for (const target of page.binaryTargets) binaryTargets.add(target);\n pageToken = page.pageToken;\n }\n const confirmed = readStaged({\n locator: room.locator,\n collectionRoot: room.collectionRoot,\n name: room.name,\n operations: room.operations,\n replica: room.replica,\n attachedModel: room.attachedModel,\n model: models.collection,\n typedSelection: room.typedSelection ?? null,\n selectionModel: models.selection,\n providerOwnedPaths: room.providerOwnedPaths,\n roomVersion,\n documents,\n binaryTargets: [...binaryTargets].sort(),\n revisions,\n });\n return confirmed === null ? unconfirmed : { kind: 'staged', confirmed };\n}\n"],"names":["readStaged","unconfirmed","bootstrapRoom","adapter","authorization","room","models","first","bootstrap","locator","selection","replica","kind","roomVersion","documents","revisions","binaryTargets","Set","pageToken","undefined","page","Object","assign","target","add","confirmed","collectionRoot","name","operations","attachedModel","model","collection","typedSelection","selectionModel","providerOwnedPaths","sort"],"mappings":"AAEA,SAASA,UAAU,QAA6B,eAAe;AAC/D,SAASC,WAAW,QAA0B,gBAAgB;AAO9D,OAAO,eAAeC,cACpBC,OAAgB,EAChBC,aAA4B,EAC5BC,IAAoB,EACpBC,MAAyD;IAEzD,MAAMC,QAAQ,MAAMJ,QAAQK,SAAS,CAAC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OU,cAAc,OAAOxB,cAAc;QAAEW,MAAM;QAAUa;IAAU;AACxE"}
1
+ {"version":3,"sources":["/workspace/packages/mdruntime/src/bootstrap.ts"],"sourcesContent":["import type { ModelState } from './model.js';\nimport type { Adapter, AdapterFailure, Authorization, DiscoveredRoom } from './adapter.js';\nimport { readStaged, type Staged } from './replica.js';\nimport { unconfirmed } from './transfer.js';\n\nexport type BootstrapOutcome = Staged | AdapterFailure;\n\nexport async function bootstrapRoom(\n adapter: Adapter,\n authorization: Authorization,\n room: DiscoveredRoom,\n models: { collection: ModelState; selection: ModelState },\n): Promise<BootstrapOutcome> {\n const first = await adapter.bootstrap(authorization, {\n locator: room.locator,\n selection: room.replica.selection,\n });\n if (first.kind !== 'bootstrap') return first;\n const roomVersion = first.roomVersion;\n const documents: Record<string, string> = { ...first.documents };\n const revisions: Record<string, string> = { ...first.revisions };\n const binaryTargets = new Set(first.binaryTargets);\n let pageToken = first.pageToken;\n while (pageToken !== undefined) {\n const page = await adapter.bootstrap(authorization, {\n locator: room.locator,\n selection: room.replica.selection,\n pageToken,\n });\n if (page.kind !== 'bootstrap') return page;\n if (page.roomVersion !== roomVersion) return unconfirmed;\n Object.assign(documents, page.documents);\n Object.assign(revisions, page.revisions);\n for (const target of page.binaryTargets) binaryTargets.add(target);\n pageToken = page.pageToken;\n }\n return readStaged({\n locator: room.locator,\n collectionRoot: room.collectionRoot,\n name: room.name,\n operations: room.operations,\n replica: room.replica,\n attachedModel: room.attachedModel,\n model: models.collection,\n typedSelection: room.typedSelection ?? null,\n selectionModel: models.selection,\n providerOwnedPaths: room.providerOwnedPaths,\n roomVersion,\n documents,\n binaryTargets: [...binaryTargets].sort(),\n revisions,\n });\n}\n"],"names":["readStaged","unconfirmed","bootstrapRoom","adapter","authorization","room","models","first","bootstrap","locator","selection","replica","kind","roomVersion","documents","revisions","binaryTargets","Set","pageToken","undefined","page","Object","assign","target","add","collectionRoot","name","operations","attachedModel","model","collection","typedSelection","selectionModel","providerOwnedPaths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AAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;QACpE,CACE,KAAK,EAAE,cAAc,EACrB,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC,CAAC;KAC3C,CAAC;IACF,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM,YAAY,GACpB,OAAO,GACP,oBAAoB,GACpB,cAAc,GACd,aAAa,GACb,OAAO,GACP,OAAO,GACP,aAAa,GACb,cAAc,GACd,cAAc,CAAC;AAEnB,MAAM,MAAM,eAAe,GAAG;IAC5B,EAAE,EAAE,SAAS,CAAC;IACd,KAAK,CACH,KAAK,EAAE,YAAY,EACnB,KAAK,EAAE,SAAS,OAAO,EAAE,EACzB,OAAO,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,GAClC,MAAM,IAAI,CAAC;CACf,CAAC;AAsBF,wBAAgB,eAAe,CAAC,OAAO,EAAE,gBAAgB,GAAG,SAAS,CAEpE;AAED,wBAAgB,cAAc,CAAC,OAAO,EAAE,gBAAgB,GAAG,eAAe,CAqhEzE"}
@@ -66,6 +66,7 @@ export function composeRuntime(options) {
66
66
  const discovered = new Map();
67
67
  let roomsListed = false;
68
68
  const scopedRefusals = new Map();
69
+ const sourceRefusals = new Map();
69
70
  function modelKey(locator, attached) {
70
71
  return `${attached} ${locator}`;
71
72
  }
@@ -423,7 +424,7 @@ export function composeRuntime(options) {
423
424
  providerOwnedPaths: room.providerOwnedPaths,
424
425
  roomVersion: replicas.get(room.locator)?.confirmed.record.roomVersion ?? null,
425
426
  synchronizationAvailable,
426
- refusal: scopedRefusals.get(room.locator) ?? null
427
+ refusal: scopedRefusals.get(room.locator) ?? sourceRefusals.get(room.locator) ?? null
427
428
  });
428
429
  }
429
430
  async function applyDiscovery(listed, local) {
@@ -475,6 +476,7 @@ export function composeRuntime(options) {
475
476
  roomDrafts.delete(locator);
476
477
  unreadable.delete(locator);
477
478
  scopedRefusals.delete(locator);
479
+ sourceRefusals.delete(locator);
478
480
  for (const attached of [
479
481
  'collection',
480
482
  'typed-selection'
@@ -729,6 +731,7 @@ export function composeRuntime(options) {
729
731
  room: true
730
732
  });
731
733
  unreadable.delete(room.locator);
734
+ sourceRefusals.delete(room.locator);
732
735
  list(room, true);
733
736
  publishChangeSet(set);
734
737
  moveTo({
@@ -984,6 +987,7 @@ export function composeRuntime(options) {
984
987
  if (held !== undefined) {
985
988
  const refreshed = await pullRefresh(authorized, held.confirmed);
986
989
  if (refreshed.kind === 'still-current') {
990
+ sourceRefusals.delete(room.locator);
987
991
  if (unreadable.delete(room.locator)) {
988
992
  list(room, true);
989
993
  emitRooms();
@@ -1013,12 +1017,33 @@ export function composeRuntime(options) {
1013
1017
  unreadable.add(room.locator);
1014
1018
  list(room, false);
1015
1019
  emitRooms();
1020
+ } else if (withheld.kind === 'refused') {
1021
+ refusedSource(room, withheld);
1016
1022
  } else if (withheld.kind === 'revoked-authorization') {
1017
1023
  await refuse('revoked-authorization');
1018
1024
  return 'stop';
1019
1025
  }
1020
1026
  return null;
1021
1027
  }
1028
+ function refusedSource(room, { refusal }) {
1029
+ sourceRefusals.set(room.locator, {
1030
+ code: refusal.rule,
1031
+ fields: {
1032
+ file: refusal.file,
1033
+ ...refusal.location === undefined ? {} : {
1034
+ location: refusal.location
1035
+ },
1036
+ version: refusal.version,
1037
+ ...refusal.referrers === undefined ? {} : {
1038
+ referrers: refusal.referrers
1039
+ }
1040
+ }
1041
+ });
1042
+ unreadable.add(room.locator);
1043
+ list(room, false);
1044
+ emitRooms();
1045
+ journal.record(`source refused ${room.locator} ${refusal.rule} ${refusal.file}`);
1046
+ }
1022
1047
  function leaving(batch, result) {
1023
1048
  if (result.kind === 'expired') {
1024
1049
  return {
@@ -1077,8 +1102,13 @@ export function composeRuntime(options) {
1077
1102
  selectionModel: modelOf(room.locator, 'typed-selection')
1078
1103
  }, base);
1079
1104
  if (retainedBase === null) return false;
1080
- const applied = overlay ? applyReturned(retainedBase, accepted.documents, accepted.revisions, accepted.removals, accepted.roomVersion) : retainedBase;
1081
- if (applied === null) return false;
1105
+ let applied = retainedBase;
1106
+ if (overlay) {
1107
+ const returned = applyReturned(retainedBase, accepted.documents, accepted.revisions, accepted.removals, accepted.roomVersion);
1108
+ if (returned.kind === 'refused') refusedSource(room, returned);
1109
+ if (returned.kind !== 'staged') return false;
1110
+ applied = returned.confirmed;
1111
+ }
1082
1112
  const acceptedOutcome = {
1083
1113
  kind: 'accepted',
1084
1114
  roomVersion: accepted.roomVersion,
@@ -1097,6 +1127,7 @@ export function composeRuntime(options) {
1097
1127
  room: true
1098
1128
  });
1099
1129
  unreadable.delete(room.locator);
1130
+ sourceRefusals.delete(room.locator);
1100
1131
  list(room, true);
1101
1132
  publishChangeSet(set);
1102
1133
  moveTo({
@@ -1250,6 +1281,8 @@ export function composeRuntime(options) {
1250
1281
  unreadable.add(room.locator);
1251
1282
  list(room, false);
1252
1283
  emitRooms();
1284
+ } else if (bootstrapped.kind === 'refused') {
1285
+ refusedSource(room, bootstrapped);
1253
1286
  }
1254
1287
  return null;
1255
1288
  }
@@ -1260,6 +1293,8 @@ export function composeRuntime(options) {
1260
1293
  unreadable.add(room.locator);
1261
1294
  list(room, false);
1262
1295
  emitRooms();
1296
+ } else if (pulled.kind === 'refused') {
1297
+ refusedSource(room, pulled);
1263
1298
  }
1264
1299
  return null;
1265
1300
  }
@@ -1704,10 +1739,19 @@ export function composeRuntime(options) {
1704
1739
  if (handed?.includes(locator) !== true) continue;
1705
1740
  const room = discovered.get(locator);
1706
1741
  const held = replicas.get(locator);
1707
- if (room === undefined || held === undefined) continue;
1742
+ if (room === undefined) continue;
1743
+ if (sourceRefusals.has(locator)) {
1744
+ void enqueue();
1745
+ continue;
1746
+ }
1747
+ if (held === undefined) continue;
1708
1748
  if (held.confirmed.record.roomVersion === roomVersion) continue;
1709
1749
  const withheld = await advance(room, local, authorization);
1710
1750
  if (withheld === null) continue;
1751
+ if (withheld.kind === 'refused') {
1752
+ void enqueue();
1753
+ continue;
1754
+ }
1711
1755
  if (withheld.kind === 'scoped-refusal') {
1712
1756
  await scoped(withheld, room, local);
1713
1757
  continue;
@@ -1 +1 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/connection.ts"],"sourcesContent":["import { verify } from '@agentshouse/mdmodel';\nimport {\n cached,\n modelTypes,\n NO_MODEL,\n sameModel,\n type ModelState,\n type TypesResult,\n} from './model.js';\nimport { opened, type Observation } from './observation.js';\nimport {\n filterOf,\n identityOf,\n planOf,\n type DocumentQuery,\n type DocumentResult,\n type GroupQuery,\n type GroupResult,\n type HeldRooms,\n} from './query.js';\nimport { createReadSide } from './read-side.js';\nimport {\n createSearchIndex,\n searchPlanOf,\n type SearchRequest,\n type SearchResult,\n} from './search.js';\nimport {\n ROOM_CONTRACT_VERSION,\n VERSION_1_CAPABILITIES,\n type ActionResult,\n type Adapter,\n type AdapterFailure,\n type Authorization,\n type Capability,\n type DiscoveredRoom,\n type Discovery,\n type HistoryResult,\n type MutationResult,\n type ProviderLimit,\n type ConversationCards,\n type ConversationAction,\n type ProviderRefusal,\n type TypedSelection,\n} from './adapter.js';\nimport { bootstrapRoom } from './bootstrap.js';\nimport { changeSet, mergeChangeSets, type ChangeSet } from './change-set.js';\nimport {\n createConversationStore,\n type ChatDraftSurface,\n type ConversationOptions,\n type ConversationStore,\n type ConversationSurface,\n type ConversationView,\n} from './conversation.js';\nimport type { ChangeBatch, WrittenBy } from './change.js';\nimport { MD_MODEL, validRoot, type Composition } from './collection.js';\nimport { createLog } from './log.js';\nimport type { CallResult, QueueEntry, Submission, SubmissionOutcome } from './outcome.js';\nimport { refreshRoom } from './refresh.js';\nimport { buildBatch, type Rewriting, type SaveRefusal } from './save.js';\nimport {\n applyReturned,\n compositionOf,\n readConfirmed,\n replicaOf,\n withdrawals,\n type ConfirmedLayer,\n type Replica,\n} from './replica.js';\nimport {\n changedParts,\n changesOf,\n held,\n readParts,\n returnedInto,\n underneath,\n type ReturnReason,\n type RoomDraft,\n type RoomDraftRecord,\n type RoomDraftWrite,\n type SavedDraft,\n} from './room-draft.js';\nimport {\n settled,\n same,\n saving,\n STARTING,\n transferring,\n type AttentionEntry,\n type CycleProgress,\n type SyncStatus,\n} from './status.js';\nimport { detectStorageLoss, nextGeneration, type RuntimeShell } from './durability.js';\nimport { roomDraftRevision } from './identity.js';\nimport { beneath, normalize } from './paths.js';\nimport {\n openRuntimeStore,\n type PendingState,\n type ReplicaRecord,\n type RuntimeStore,\n} from './store.js';\nimport { unconfirmed, type Unconfirmed } from './transfer.js';\n\nconst DEFAULT_DISCOVERY_INTERVAL_MS = 60_000;\n\nconst knownCapabilities = new Set<string>(VERSION_1_CAPABILITIES);\n\ntype Attached = 'collection' | 'typed-selection';\n\ntype RoomDeclaration = Omit<DiscoveredRoom, 'roomVersion' | 'typedSelection'> & {\n typedSelection?: TypedSelection | null;\n};\n\nfunction within(root: string, path: string): boolean {\n return root === '' || beneath(root, path);\n}\n\nfunction declaredIdentity(model: import('./model.js').ModelIdentity | null | undefined): boolean {\n if (model === undefined) return false;\n if (model === null) return true;\n return (\n typeof model.identity === 'string' &&\n model.identity.length > 0 &&\n typeof model.version === 'string' &&\n model.version.length > 0\n );\n}\n\nfunction declaredSelection(room: DiscoveredRoom): boolean {\n const selection = room.typedSelection;\n if (selection === undefined) return true;\n if (!Array.isArray(selection.roots) || selection.roots.length === 0) return false;\n if (!declaredIdentity(selection.attachedModel)) return false;\n return selection.roots.every(\n (root, index) =>\n validRoot(root) &&\n root !== '' &&\n !within(room.collectionRoot, root) &&\n selection.roots.every((other, at) => at === index || !within(other, root)),\n );\n}\n\nexport type AppTypedSelection = {\n roots: readonly string[];\n attachedModel: import('./model.js').ModelIdentity | null;\n model: TypesResult;\n};\n\nexport type AppRoom = {\n collectionRoot: string;\n name: string;\n locator: string;\n operations: import('./adapter.js').OperationScopes;\n replica: import('./adapter.js').ReplicaAdmission;\n attachedModel: import('./model.js').ModelIdentity | null;\n model: TypesResult;\n typedSelection: AppTypedSelection | null;\n providerOwnedPaths: readonly string[];\n roomVersion: string | null;\n synchronizationAvailable: boolean;\n refusal: ProviderRefusal | null;\n};\n\nexport type AppSlotEntry = {\n room: AppRoom;\n segment: string | null;\n};\n\nexport type AppSlot = {\n slot: string;\n entries: readonly AppSlotEntry[];\n};\n\nexport type RoomTypes = {\n collection: TypesResult;\n typedSelection: TypesResult | null;\n};\n\nexport type ConnectionRefusalReason =\n | 'no-matching-version'\n | 'missing-required-guarantee'\n | 'md-model-version-mismatch'\n | 'revoked-authorization'\n | 'client-host-protocol-mismatch';\n\nexport type ConnectionRefusal = {\n reason: ConnectionRefusalReason;\n reauthorizationOffered: boolean;\n refusal: ProviderRefusal | null;\n};\n\nexport type MdRuntimeOptions = {\n adapter: Adapter;\n shell: RuntimeShell;\n requiredGuarantees: readonly string[];\n authorization?: Authorization;\n discoveryIntervalMs?: number;\n signal?: AbortSignal;\n};\n\nexport type SaveResult =\n | { outcome: 'saved'; identifier: string }\n | ({ outcome: 'refused' } & SaveRefusal);\n\nexport type SavedRoomDraft = { readonly path: string; readonly revision: string };\n\nexport type RoomDraftSurface = {\n list(): Promise<readonly RoomDraft[]>;\n read(room: string, path: string): RoomDraft | null;\n write(\n room: string,\n path: string,\n revision: string | null,\n parts: unknown,\n ): Promise<RoomDraftWrite>;\n discard(room: string, path: string, revision: string): Promise<RoomDraftWrite>;\n};\n\nexport type PresentationSurface = {\n read(app: string): Promise<unknown>;\n write(app: string, value: unknown): Promise<void>;\n};\n\nexport type HistoryQuery = {\n revision?: string;\n pageToken?: string;\n};\n\nexport type MdRuntime = {\n loaded(): Promise<void>;\n rooms(): readonly AppRoom[];\n slots(): readonly AppSlot[];\n query: {\n (query: DocumentQuery): Promise<DocumentResult>;\n (query: GroupQuery): Promise<GroupResult>;\n };\n search(request: SearchRequest): Promise<SearchResult>;\n types(locator: string): RoomTypes;\n syncStatus(): SyncStatus;\n roomDraft: RoomDraftSurface;\n conversation: ConversationSurface;\n chatDraft: ChatDraftSurface;\n presentation: PresentationSurface;\n save(\n room: string,\n roomDrafts: readonly SavedRoomDraft[],\n writtenBy?: WrittenBy,\n ): Promise<SaveResult>;\n outcome(identifier: string): SubmissionOutcome | null;\n history(locator: string, path: string, query?: HistoryQuery): Promise<HistoryResult>;\n call(name: string, input: unknown): Promise<CallResult>;\n log(): string;\n storageLoss(): string | null;\n persistence(): boolean;\n observe: {\n (topic: 'rooms'): Promise<Observation<readonly AppRoom[]>>;\n (topic: 'connection-refusal'): Promise<Observation<ConnectionRefusal | null>>;\n (topic: 'storage-loss'): Promise<Observation<string | null>>;\n (topic: 'sync-status'): Promise<Observation<SyncStatus>>;\n (topic: 'query', query: DocumentQuery): Promise<Observation<DocumentResult>>;\n (topic: 'query', query: GroupQuery): Promise<Observation<GroupResult>>;\n (topic: 'queue', locator: string): Promise<Observation<readonly QueueEntry[]>>;\n (topic: 'room-drafts'): Promise<Observation<readonly RoomDraft[]>>;\n (topic: 'presentation', app: string): Promise<Observation<unknown>>;\n (\n topic: 'conversation',\n conversation: string,\n options: ConversationOptions,\n ): Promise<Observation<ConversationView>>;\n };\n reauthorize(): Promise<void>;\n};\n\nexport type RuntimeTopic =\n | 'rooms'\n | 'connection-refusal'\n | 'storage-loss'\n | 'sync-status'\n | 'query'\n | 'queue'\n | 'room-drafts'\n | 'presentation'\n | 'conversation';\n\nexport type ComposedRuntime = {\n md: MdRuntime;\n watch(\n topic: RuntimeTopic,\n input: readonly unknown[],\n deliver: (message: unknown) => void,\n ): () => void;\n};\n\ntype QueueSubscription = {\n locator: string;\n notify: (entries: readonly QueueEntry[]) => void;\n};\n\ntype RoomDraftSubscription = {\n notify: (roomDrafts: readonly RoomDraft[]) => void;\n ready: boolean;\n};\n\ntype Leaving = { batch: ChangeBatch; outcome: SubmissionOutcome; returned: ReturnReason };\n\ntype PresentationSubscription = {\n app: string;\n notify: (value: unknown) => void;\n ready: boolean;\n};\n\ntype Withheld = AdapterFailure | Unconfirmed;\n\nexport function createMdRuntime(options: MdRuntimeOptions): MdRuntime {\n return composeRuntime(options).md;\n}\n\nexport function composeRuntime(options: MdRuntimeOptions): ComposedRuntime {\n const period = options.discoveryIntervalMs ?? DEFAULT_DISCOVERY_INTERVAL_MS;\n let authorization: Authorization | undefined = options.authorization;\n let opening: Promise<RuntimeStore> | undefined;\n let store: RuntimeStore | undefined;\n const replicas = new Map<string, Replica>();\n const pendings = new Map<string, PendingState>();\n const roomDrafts = new Map<string, Map<string, RoomDraftRecord>>();\n const presentations = new Map<string, unknown>();\n const outcomes = new Map<string, SubmissionOutcome>();\n const outcomeRooms = new Map<string, string>();\n let limits: readonly ProviderLimit[] = [];\n let slots: NonNullable<Discovery['slots']> = [];\n let capabilities: readonly Capability[] = [];\n function rewriting(): Rewriting {\n return capabilities.some((capability) => capability.name === 'move-reference-rewrites')\n ? 'provider'\n : 'runtime';\n }\n const rooms = new Map<string, AppRoom>();\n const unreadable = new Set<string>();\n const models = new Map<string, ModelState>();\n const liveModels = new Map<string, string>();\n const invalidModels = new Set<string>();\n const modelEpoch = new Map<string, number>();\n const discovered = new Map<string, DiscoveredRoom>();\n let roomsListed = false;\n const scopedRefusals = new Map<string, ProviderRefusal>();\n function modelKey(locator: string, attached: Attached): string {\n return `${attached} ${locator}`;\n }\n function modelOf(locator: string, attached: Attached = 'collection'): ModelState {\n return models.get(modelKey(locator, attached)) ?? NO_MODEL;\n }\n function savedModel(locator: string, attached: Attached): ModelState {\n return invalidModels.has(modelKey(locator, attached))\n ? { status: 'unavailable', reason: 'revoked' }\n : modelOf(locator, attached);\n }\n function compositionFor(record: ReplicaRecord): Composition {\n return compositionOf({\n ...record,\n model: savedModel(record.locator, 'collection'),\n selectionModel: savedModel(record.locator, 'typed-selection'),\n });\n }\n\n const mismatchedRoots = new Set<string>();\n let refusal: ConnectionRefusal | null = null;\n let storageLoss: string | null = null;\n let status: SyncStatus = STARTING;\n let shown: SyncStatus = STARTING;\n let discoveryPaused = false;\n let timer: ReturnType<typeof setInterval> | undefined;\n let closed = false;\n let withdrawNotifications: (() => void) | undefined;\n let handed: readonly string[] | undefined;\n const notices = new Map<string, string>();\n let chain: Promise<void> = Promise.resolve();\n let mutations: Promise<unknown> = Promise.resolve();\n let inflight = false;\n let queued = false;\n const roomListeners = new Set<(rooms: readonly AppRoom[]) => void>();\n const refusalListeners = new Set<(refusal: ConnectionRefusal | null) => void>();\n const storageLossListeners = new Set<(statement: string | null) => void>();\n const statusListeners = new Set<(status: SyncStatus) => void>();\n const queueSubscriptions = new Set<QueueSubscription>();\n const roomDraftListeners = new Set<RoomDraftSubscription>();\n const presentationListeners = new Set<PresentationSubscription>();\n const readSide = createReadSide();\n let withdrawConversations: (() => void) | undefined;\n let currencyQueued = false;\n const conversations: ConversationStore = createConversationStore({\n cards: declaredCards,\n documents: (locator: string) =>\n readSide.query(\n planOf({ rooms: [locator], select: 'all' }, roomFacts()),\n ) as Promise<DocumentResult>,\n call: (name: ConversationAction, input: unknown) => invokeAction(name, input),\n durably,\n stream: () => options.adapter.conversations,\n publish: publishChangeSet,\n closed: () => closed,\n });\n const searchIndex = createSearchIndex({\n documents: () => readSide.documents(),\n document: (room, path) => readSide.document(room, path),\n messages: () => conversations.messages(),\n message: (conversation, identity) => conversations.message(conversation, identity),\n });\n const journal = createLog();\n let notifyReady = () => {};\n const ready = new Promise<void>((resolve) => {\n notifyReady = resolve;\n });\n function rememberRoomDraft(record: RoomDraftRecord) {\n const room = roomDrafts.get(record.locator) ?? new Map<string, RoomDraftRecord>();\n room.set(record.path, record);\n roomDrafts.set(record.locator, room);\n }\n\n function forgetRoomDraft(locator: string, path: string) {\n const room = roomDrafts.get(locator);\n if (room === undefined) return;\n room.delete(path);\n if (room.size === 0) roomDrafts.delete(locator);\n }\n\n function roomDraftOf(record: RoomDraftRecord): RoomDraft {\n return structuredClone({\n room: record.locator,\n path: record.path,\n revision: record.revision,\n parts: record.parts,\n changedUnderneath: underneath(\n record.parts,\n record.path,\n replicas.get(record.locator)?.visible,\n ),\n returned: record.returned,\n });\n }\n\n function snapshotRoomDrafts(): readonly RoomDraft[] {\n const records = [...roomDrafts.values()].flatMap((room) => [...room.values()]);\n records.sort((left, right) => {\n if (left.locator !== right.locator) return left.locator < right.locator ? -1 : 1;\n if (left.path !== right.path) return left.path < right.path ? -1 : 1;\n return 0;\n });\n return records.map(roomDraftOf);\n }\n\n function publishRoomDrafts(waitingOnly: boolean) {\n if (closed) return;\n const value = snapshotRoomDrafts();\n for (const listener of roomDraftListeners) {\n if (waitingOnly && listener.ready) continue;\n listener.ready = true;\n listener.notify(value);\n }\n }\n\n function presentationOf(app: string): unknown {\n const value = presentations.get(app);\n return value === undefined ? null : structuredClone(value);\n }\n\n function emitPresentation(app: string) {\n if (closed) return;\n for (const listener of presentationListeners) {\n if (listener.app === app && listener.ready) listener.notify(presentationOf(app));\n }\n }\n\n function pending() {\n return [...replicas.values()].some((replica) => replica.queue.length > 0);\n }\n\n function attention(): Pick<SyncStatus, 'attentionRequired' | 'reset'> {\n const attentionRequired: AttentionEntry[] = [];\n for (const record of [...roomDrafts.values()].flatMap((room) => [...room.values()])) {\n if (record.returned === null) continue;\n attentionRequired.push({\n room: record.locator,\n path: record.path,\n returned: structuredClone(record.returned),\n });\n }\n attentionRequired.sort((left, right) => {\n if (left.room !== right.room) return left.room < right.room ? -1 : 1;\n if (left.path !== right.path) return left.path < right.path ? -1 : 1;\n return 0;\n });\n let reset: string | null = null;\n for (const { submission } of pendings.values()) {\n if (submission.state !== 'reset') continue;\n if (reset === null || submission.reset < reset) reset = submission.reset;\n }\n return { attentionRequired, reset };\n }\n\n function listed(): readonly AppRoom[] {\n return structuredClone([...rooms.values()]);\n }\n\n function slotted(): readonly AppSlot[] {\n return structuredClone(\n slots.map(({ slot, entries }) => ({\n slot,\n entries: entries.flatMap(({ locator, segment }) => {\n const room = rooms.get(locator);\n return room === undefined ? [] : [{ room, segment }];\n }),\n })),\n );\n }\n\n function roomFacts(): HeldRooms {\n const held = [...rooms.values()].map((room) => {\n const attached = [\n modelOf(room.locator),\n ...(room.typedSelection === null ? [] : [modelOf(room.locator, 'typed-selection')]),\n ];\n return {\n locator: room.locator,\n available: attached.every((model) => model.status !== 'unavailable'),\n types: attached.flatMap((model) =>\n model.status === 'unavailable' ? [] : Object.values(model.types),\n ),\n };\n });\n return { listed: roomsListed, rooms: held };\n }\n\n function emitRooms() {\n const value = listed();\n for (const listener of roomListeners) listener(value);\n }\n\n function emitRefusal() {\n for (const listener of refusalListeners) listener(refusal);\n }\n\n function emitStorageLoss() {\n for (const listener of storageLossListeners) listener(storageLoss);\n }\n\n function moveTo(next: SyncStatus) {\n if (closed) return;\n status = next;\n show();\n }\n\n function show() {\n if (closed) return;\n const next: SyncStatus =\n status.state === 'synced' && !conversations.current()\n ? { ...status, state: 'syncing' }\n : status;\n if (same(shown, next)) return;\n shown = next;\n for (const listener of statusListeners) listener(shown);\n }\n\n function submissionOf(batch: ChangeBatch): Submission {\n return pendings.get(batch.id)?.submission ?? { state: 'waiting' };\n }\n\n function entriesOf(locator: string): readonly QueueEntry[] {\n const replica = replicas.get(locator);\n if (replica === undefined) return [];\n return replica.queue.map((batch) => Object.freeze({ batch, ...submissionOf(batch) }));\n }\n\n function emitQueue(locator: string) {\n const entries = entriesOf(locator);\n for (const subscription of queueSubscriptions) {\n if (subscription.locator === locator) subscription.notify(entries);\n }\n }\n\n function applyChangeSet(set: ChangeSet) {\n readSide.apply(set);\n searchIndex.changed(set);\n }\n\n function publishChangeSet(set: ChangeSet) {\n applyChangeSet(set);\n if (set.rooms.length > 0) emitRooms();\n for (const locator of set.queues) emitQueue(locator);\n if (\n set.drafts.length > 0 ||\n set.documents.some((change) => roomDrafts.get(change.locator)?.has(change.path) === true)\n ) {\n publishRoomDrafts(false);\n }\n for (const app of set.presentations) emitPresentation(app);\n conversations.changed(set);\n const cards = declaredCards();\n if (cards !== undefined && set.documents.some((change) => change.locator === cards.locator)) {\n scheduleCurrency();\n }\n }\n\n function stopTimer() {\n if (timer === undefined) return;\n clearInterval(timer);\n timer = undefined;\n }\n\n function startTimer() {\n if (timer !== undefined) return;\n timer = setInterval(() => {\n void enqueue();\n }, period);\n }\n\n async function refuse(reason: ConnectionRefusalReason, provider: ProviderRefusal | null = null) {\n stopTimer();\n discoveryPaused = true;\n try {\n if (reason === 'revoked-authorization') {\n await exclusive(async () => {\n const revoked: ModelState = { status: 'unavailable', reason: 'revoked' };\n try {\n const local = await openLocal();\n await local.revokeModels(\n [...replicas.values()].map((replica) => ({\n record: replica.confirmed.record,\n queue: replica.queue,\n })),\n );\n } catch {\n journal.record('model revocation persistence failed');\n }\n const keys = new Set(models.keys());\n for (const locator of rooms.keys()) {\n keys.add(modelKey(locator, 'collection'));\n keys.add(modelKey(locator, 'typed-selection'));\n }\n for (const key of keys) {\n invalidModels.add(key);\n modelEpoch.set(key, (modelEpoch.get(key) ?? 0) + 1);\n models.set(key, revoked);\n liveModels.delete(key);\n }\n const changed: ChangeSet[] = [];\n for (const [locator, room] of rooms) {\n const before = replicas.get(locator) ?? null;\n if (before !== null) {\n const record = {\n ...before.confirmed.record,\n model: revoked,\n selectionModel: revoked,\n };\n const confirmed = readConfirmed(record, before.confirmed);\n if (confirmed === null) throw new Error(`Cannot retype revoked Room ${locator}`);\n replicas.set(locator, replicaOf(confirmed, before.queue, rewriting(), before));\n }\n rooms.set(locator, {\n ...room,\n model: modelTypes(revoked),\n typedSelection:\n room.typedSelection === null\n ? null\n : { ...room.typedSelection, model: modelTypes(revoked) },\n });\n changed.push(changeSet(locator, before, replicas.get(locator) ?? null, { room: true }));\n }\n publishChangeSet(mergeChangeSets(changed));\n });\n }\n } finally {\n refusal = {\n reason,\n reauthorizationOffered: reason === 'revoked-authorization',\n refusal: provider,\n };\n journal.record(`connection refused ${reason}`);\n emitRefusal();\n }\n }\n\n function list(room: RoomDeclaration, synchronizationAvailable: boolean) {\n const selection = room.typedSelection ?? null;\n rooms.set(room.locator, {\n name: room.name,\n collectionRoot: room.collectionRoot,\n locator: room.locator,\n operations: room.operations,\n replica: room.replica,\n attachedModel: room.attachedModel,\n model: modelTypes(modelOf(room.locator)),\n typedSelection:\n selection === null\n ? null\n : {\n roots: selection.roots,\n attachedModel: selection.attachedModel,\n model: modelTypes(modelOf(room.locator, 'typed-selection')),\n },\n providerOwnedPaths: room.providerOwnedPaths,\n roomVersion: replicas.get(room.locator)?.confirmed.record.roomVersion ?? null,\n synchronizationAvailable,\n refusal: scopedRefusals.get(room.locator) ?? null,\n });\n }\n\n async function applyDiscovery(listed: readonly DiscoveredRoom[], local: RuntimeStore) {\n const listedLocators = new Set(listed.map((room) => room.locator));\n for (const locator of listedLocators) scopedRefusals.delete(locator);\n discovered.clear();\n for (const room of listed) discovered.set(room.locator, room);\n await dropUnlisted(listedLocators, local);\n for (const room of listed) {\n const held = replicas.get(room.locator)?.confirmed.record;\n if (held !== undefined && held.replica.selection !== room.replica.selection) {\n list(held, false);\n continue;\n }\n list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));\n }\n roomsListed = true;\n emitRooms();\n }\n\n function unlistedHeld(listed: ReadonlySet<string>): string[] {\n return [...new Set([...rooms.keys(), ...roomDrafts.keys()])].filter(\n (locator) => !listed.has(locator),\n );\n }\n\n async function dropUnlisted(listed: ReadonlySet<string>, local: RuntimeStore) {\n if (unlistedHeld(listed).length === 0) return;\n await exclusive(async () => {\n const unlisted = unlistedHeld(listed);\n await local.dropRooms(unlisted);\n for (const [batch, locator] of outcomeRooms) {\n if (listed.has(locator)) continue;\n outcomeRooms.delete(batch);\n outcomes.delete(batch);\n }\n const removed = unlisted.map((locator) =>\n changeSet(locator, replicas.get(locator) ?? null, null, {\n room: true,\n queue: true,\n drafts: [...(roomDrafts.get(locator)?.keys() ?? [])],\n }),\n );\n for (const locator of unlisted) {\n for (const batch of replicas.get(locator)?.queue ?? []) pendings.delete(batch.id);\n replicas.delete(locator);\n rooms.delete(locator);\n roomDrafts.delete(locator);\n unreadable.delete(locator);\n scopedRefusals.delete(locator);\n for (const attached of ['collection', 'typed-selection'] as const) {\n const key = modelKey(locator, attached);\n models.delete(key);\n liveModels.delete(key);\n invalidModels.delete(key);\n modelEpoch.delete(key);\n }\n journal.record(`room unlisted ${locator}`);\n }\n publishChangeSet(mergeChangeSets(removed));\n moveTo({ ...status, ...attention() });\n });\n }\n\n function restored(key: string, persisted: ModelState): ModelState {\n const prior = models.get(key);\n if (\n prior !== undefined &&\n prior.status !== 'unavailable' &&\n (persisted.status === 'unavailable' || !sameModel(prior.snapshot, persisted.snapshot))\n ) {\n modelEpoch.set(key, (modelEpoch.get(key) ?? 0) + 1);\n invalidModels.add(key);\n }\n const model =\n persisted.status === 'unavailable' ||\n liveModels.get(key) === JSON.stringify(persisted.snapshot)\n ? persisted\n : cached(persisted);\n models.set(key, model);\n if (model.status === 'unavailable') {\n liveModels.delete(key);\n invalidModels.delete(key);\n }\n return model;\n }\n\n async function hydrate(opened: RuntimeStore): Promise<{\n lastCompleted: string | null;\n locators: Set<string>;\n read: ChangeSet;\n }> {\n const [\n records,\n queues,\n recordedOutcomes,\n kept,\n presented,\n held,\n chatDrafts,\n lastCompleted,\n declared,\n named,\n listedSlots,\n ] = await Promise.all([\n opened.all(),\n opened.queues(),\n opened.outcomes(),\n opened.roomDrafts(),\n opened.presentation(),\n opened.conversations(),\n opened.chatDrafts(),\n opened.lastCompleted(),\n opened.providerLimits(),\n opened.capabilities(),\n opened.slots(),\n ]);\n limits = declared;\n capabilities = named;\n slots = listedSlots;\n roomDrafts.clear();\n for (const record of kept) rememberRoomDraft(record);\n presentations.clear();\n for (const record of presented) presentations.set(record.app, record.value);\n conversations.hydrate(held, chatDrafts);\n const queuedBatches = new Map(\n queues.map((queue) => [queue.locator, queue.pending.map(({ batch }) => batch)]),\n );\n pendings.clear();\n for (const queue of queues) {\n for (const { batch, state } of queue.pending) pendings.set(batch.id, state);\n }\n outcomes.clear();\n outcomeRooms.clear();\n for (const record of recordedOutcomes) {\n outcomes.set(record.id, record.outcome);\n outcomeRooms.set(record.id, record.locator);\n }\n const previousReplicas = new Map(replicas);\n replicas.clear();\n for (const record of records) {\n const model = restored(modelKey(record.locator, 'collection'), record.model);\n const selectionModel = restored(\n modelKey(record.locator, 'typed-selection'),\n record.selectionModel,\n );\n const prior = previousReplicas.get(record.locator);\n const confirmed = readConfirmed({ ...record, model, selectionModel }, prior?.confirmed);\n if (confirmed === null) continue;\n replicas.set(\n record.locator,\n replicaOf(confirmed, queuedBatches.get(record.locator) ?? [], rewriting(), prior),\n );\n const existing = rooms.get(record.locator);\n if (existing === undefined) list(record, false);\n else {\n rooms.set(record.locator, {\n ...existing,\n roomVersion: record.roomVersion,\n operations: record.operations,\n replica: record.replica,\n attachedModel: record.attachedModel,\n model: modelTypes(model),\n typedSelection:\n record.typedSelection === null\n ? null\n : {\n roots: record.typedSelection.roots,\n attachedModel: record.typedSelection.attachedModel,\n model: modelTypes(selectionModel),\n },\n });\n }\n }\n return {\n lastCompleted,\n locators: new Set([...queuedBatches.keys(), ...replicas.keys()]),\n read: mergeChangeSets(\n [...new Set([...previousReplicas.keys(), ...replicas.keys()])].map((locator) =>\n changeSet(locator, previousReplicas.get(locator) ?? null, replicas.get(locator) ?? null),\n ),\n ),\n };\n }\n\n async function readState(opened: RuntimeStore): Promise<string | null> {\n const { lastCompleted, locators, read } = await hydrate(opened);\n applyChangeSet(read);\n if (replicas.size > 0) emitRooms();\n for (const locator of locators) emitQueue(locator);\n publishRoomDrafts(false);\n return lastCompleted;\n }\n\n async function open(): Promise<RuntimeStore> {\n const opened = await openRuntimeStore();\n store = opened;\n const kept = options.shell.generation;\n const storedGeneration = await opened.generation();\n const loss = detectStorageLoss(storedGeneration, kept);\n const generation = nextGeneration(storedGeneration, kept);\n if (generation !== storedGeneration) await opened.rememberGeneration(generation);\n if (generation !== kept) await options.shell.keepGeneration(generation);\n if (loss !== null) {\n storageLoss = loss;\n emitStorageLoss();\n }\n const lastCompleted = await readState(opened);\n moveTo({ ...status, lastCompleted, ...attention() });\n return opened;\n }\n\n function durably<T>(work: (local: RuntimeStore) => Promise<T>): Promise<T> {\n return exclusive(async () => {\n const local = await openLocal();\n return work(local);\n });\n }\n\n function openLocal(): Promise<RuntimeStore> {\n opening ??= open().catch((error: unknown) => {\n opening = undefined;\n throw error;\n });\n return opening;\n }\n\n function exclusive<T>(work: () => Promise<T>): Promise<T> {\n const next = mutations.then(work, work);\n mutations = next.then(\n () => undefined,\n () => undefined,\n );\n return next;\n }\n\n function withdrawable(batch: ChangeBatch): boolean {\n const state = pendings.get(batch.id);\n return state !== undefined && state.submission.state !== 'submitted' && !state.lost;\n }\n\n async function settle(\n local: RuntimeStore,\n locator: string,\n before: Replica | undefined,\n confirmed: ConfirmedLayer,\n queue: readonly ChangeBatch[],\n settling: {\n accepted?: { id: string; outcome: SubmissionOutcome };\n leaving?: Leaving;\n room?: boolean;\n } = {},\n ): Promise<ChangeSet> {\n const withdrawn = withdrawals(confirmed, queue, withdrawable, rewriting());\n const kept = queue.filter((batch) => !withdrawn.includes(batch));\n const returning = [\n ...withdrawn.map((batch) => ({ batch, returned: { kind: 'withdrawn' } as const })).reverse(),\n ...(settling.leaving === undefined ? [] : [settling.leaving]),\n ];\n const written = new Map<string, RoomDraftRecord>();\n for (const { batch, returned } of returning) {\n for (const saved of pendings.get(batch.id)?.drafts ?? []) {\n const existing = written.get(saved.path) ?? roomDrafts.get(locator)?.get(saved.path);\n written.set(saved.path, {\n locator,\n path: saved.path,\n revision: roomDraftRevision(),\n parts: returnedInto(existing?.parts, saved.parts),\n returned,\n });\n }\n }\n const settledOutcomes: { id: string; outcome: SubmissionOutcome }[] = [\n ...(settling.accepted === undefined ? [] : [settling.accepted]),\n ...(settling.leaving === undefined\n ? []\n : [{ id: settling.leaving.batch.id, outcome: settling.leaving.outcome }]),\n ...withdrawn.map((batch) => ({ id: batch.id, outcome: { kind: 'withdrawn' as const } })),\n ];\n await local.write({\n next: confirmed.record,\n previous: before?.confirmed.record ?? null,\n queue: kept,\n previousQueue: before?.queue ?? [],\n outcomes: settledOutcomes,\n roomDrafts: [...written.values()],\n });\n for (const { id, outcome } of settledOutcomes) {\n outcomes.set(id, outcome);\n outcomeRooms.set(id, locator);\n pendings.delete(id);\n }\n for (const record of written.values()) rememberRoomDraft(record);\n for (const batch of withdrawn) journal.record(`outcome ${locator} ${batch.id} withdrawn`);\n replicas.set(locator, replicaOf(confirmed, kept, rewriting(), before));\n return changeSet(locator, before ?? null, replicas.get(locator) ?? null, {\n room: settling.room,\n queue: kept.length !== (before?.queue.length ?? 0),\n drafts: [...written.keys()],\n });\n }\n\n function publish(local: RuntimeStore, room: DiscoveredRoom, confirmed: ConfirmedLayer) {\n return exclusive(async () => {\n const prior = replicas.get(room.locator);\n const retained = readConfirmed(\n {\n ...confirmed.record,\n model: modelOf(room.locator),\n selectionModel: modelOf(room.locator, 'typed-selection'),\n },\n prior?.confirmed,\n );\n if (retained === null) {\n list(room, true);\n publishChangeSet(changeSet(room.locator, prior ?? null, prior ?? null, { room: true }));\n return;\n }\n const set = await settle(local, room.locator, prior, retained, prior?.queue ?? [], {\n room: true,\n });\n unreadable.delete(room.locator);\n list(room, true);\n publishChangeSet(set);\n moveTo({ ...status, ...attention() });\n });\n }\n\n async function saveRoomDrafts(\n locator: string,\n named: readonly SavedRoomDraft[],\n writtenBy: WrittenBy | undefined,\n ): Promise<SaveResult> {\n const local = await openLocal();\n const replica = replicas.get(locator);\n const room = rooms.get(locator);\n if (replica === undefined || room === undefined) {\n throw new Error(`No Local Replica for ${locator}`);\n }\n if (mismatchedRoots.has(locator))\n return { outcome: 'refused', rule: 'collection-root-mismatch' };\n const saved: SavedDraft[] = [];\n for (const { path, revision } of named) {\n const record = roomDrafts.get(locator)?.get(path);\n if (record === undefined || record.revision !== revision) {\n return { outcome: 'refused', rule: 'stale', file: path };\n }\n if (!saved.some((draft) => draft.path === path)) saved.push({ path, parts: record.parts });\n }\n const changed = saved.flatMap(({ path, parts }) =>\n changedParts(path, underneath(parts, path, replica.visible)),\n );\n if (changed.length > 0)\n return { outcome: 'refused', rule: 'changed-underneath', parts: changed };\n const parts = saved.map(({ path, parts }) => changesOf(path, parts));\n const built = buildBatch({\n baseRoomVersion: replica.confirmed.record.roomVersion,\n composition: compositionFor(replica.confirmed.record),\n operations: room.operations,\n providerOwnedPaths: room.providerOwnedPaths,\n providerLimits: limits,\n rewriting: rewriting(),\n visible: replica.visible,\n changes: parts.flatMap(({ changes }) => changes),\n bases: parts.flatMap(({ bases }) => bases),\n writtenBy,\n });\n if (built.kind === 'refused') return { outcome: 'refused', ...built.refusal };\n const batches = [...replica.queue, built.batch];\n const consumed = saved.map(({ path }) => path);\n try {\n await local.write({\n next: replica.confirmed.record,\n previous: replica.confirmed.record,\n queue: batches,\n previousQueue: replica.queue,\n saved,\n consumedRoomDrafts: consumed,\n });\n } catch {\n return { outcome: 'refused', rule: 'durable-write' };\n }\n pendings.set(built.batch.id, { drafts: saved, submission: { state: 'waiting' }, lost: false });\n for (const path of consumed) forgetRoomDraft(locator, path);\n replicas.set(locator, replicaOf(replica.confirmed, batches, rewriting(), replica));\n publishChangeSet(\n changeSet(locator, replica, replicas.get(locator) ?? null, {\n queue: true,\n drafts: consumed,\n }),\n );\n moveTo({ ...saving(status), ...attention() });\n void enqueue();\n return { outcome: 'saved', identifier: built.batch.id };\n }\n\n async function mark(\n local: RuntimeStore,\n locator: string,\n identifier: string,\n submission: Submission,\n lost: boolean,\n ) {\n const state = pendings.get(identifier);\n if (\n state === undefined ||\n (JSON.stringify(state.submission) === JSON.stringify(submission) && state.lost === lost)\n ) {\n return;\n }\n await local.submit(locator, identifier, submission, lost);\n pendings.set(identifier, { ...state, submission, lost });\n const replica = replicas.get(locator);\n if (replica !== undefined)\n publishChangeSet(changeSet(locator, replica, replica, { queue: true }));\n moveTo({ ...status, ...attention() });\n }\n\n async function readHistory(\n locator: string,\n path: string,\n query: HistoryQuery = {},\n ): Promise<HistoryResult> {\n if (closed || refusal !== null) return { kind: 'transport-uncertainty' };\n try {\n await ensureAuthorization();\n } catch {\n return { kind: 'transport-uncertainty' };\n }\n if (closed || authorization === undefined || refusal !== null) {\n return { kind: 'transport-uncertainty' };\n }\n const transfer = ['transfer', 'history', locator, path];\n if (query.revision !== undefined) transfer.push(query.revision);\n if (query.pageToken !== undefined) transfer.push(query.pageToken);\n journal.record(transfer.join(' '));\n try {\n const result = await options.adapter.history(authorization, {\n locator,\n path,\n ...(query.revision === undefined ? {} : { revision: query.revision }),\n ...(query.pageToken === undefined ? {} : { pageToken: query.pageToken }),\n });\n journal.record(`outcome history ${result.kind}`);\n if (result.kind === 'scoped-refusal') {\n const room = replicas.get(result.locator)?.confirmed.record;\n if (room !== undefined) await scoped(result, room, await openLocal());\n }\n if (result.kind === 'revoked-authorization') await refuse('revoked-authorization');\n return result;\n } catch {\n journal.record('outcome history transport-uncertainty');\n return { kind: 'transport-uncertainty' };\n }\n }\n\n function declaredCards(): ConversationCards | undefined {\n for (const capability of capabilities) {\n if (capability.conversationCards !== undefined) return capability.conversationCards;\n }\n return undefined;\n }\n\n function declaredAction(name: string) {\n for (const capability of capabilities) {\n for (const action of capability.actions ?? []) {\n if (action.name === name) return action;\n }\n }\n return undefined;\n }\n\n async function invokeAction(name: string, input: unknown): Promise<CallResult> {\n await ready;\n if (closed || refusal !== null) return { kind: 'transport-uncertainty' };\n if (declaredAction(name) === undefined) return { kind: 'undeclared' };\n try {\n await ensureAuthorization();\n } catch {\n return { kind: 'transport-uncertainty' };\n }\n if (closed || authorization === undefined || refusal !== null) {\n return { kind: 'transport-uncertainty' };\n }\n journal.record(`transfer action ${name}`);\n try {\n const result = await options.adapter.action(authorization, { name, input });\n if (result.kind === 'scoped-refusal') {\n const room = replicas.get(result.locator)?.confirmed.record;\n if (room !== undefined) await scoped(result, room, await openLocal());\n }\n if (result.kind === 'revoked-authorization') await refuse('revoked-authorization');\n journal.record(`outcome action ${result.kind}`);\n if (result.kind === 'rejected') journal.record(`refusal rejected ${result.code}`);\n return result;\n } catch {\n journal.record('outcome action transport-uncertainty');\n return { kind: 'transport-uncertainty' };\n }\n }\n\n async function pullRefresh(authorized: Authorization, confirmed: ConfirmedLayer) {\n try {\n const result = await refreshRoom(options.adapter, authorized, confirmed);\n const detail = result.kind === 'advanced' ? result.confirmed.record.roomVersion : result.kind;\n journal.record(`transfer refresh ${confirmed.record.locator} ${detail}`);\n return result;\n } catch (error) {\n journal.record(`transfer refresh ${confirmed.record.locator} transport-uncertainty`);\n throw error;\n }\n }\n\n async function pullBootstrap(authorized: Authorization, room: DiscoveredRoom) {\n try {\n const result = await bootstrapRoom(options.adapter, authorized, room, {\n collection: modelOf(room.locator),\n selection: modelOf(room.locator, 'typed-selection'),\n });\n const detail = result.kind === 'staged' ? result.confirmed.record.roomVersion : result.kind;\n journal.record(`transfer bootstrap ${room.locator} ${detail}`);\n return result;\n } catch (error) {\n journal.record(`transfer bootstrap ${room.locator} transport-uncertainty`);\n throw error;\n }\n }\n\n async function advance(\n room: DiscoveredRoom,\n local: RuntimeStore,\n authorized: Authorization,\n ): Promise<Withheld | null> {\n const held = replicas.get(room.locator);\n if (held !== undefined) {\n const refreshed = await pullRefresh(authorized, held.confirmed);\n if (refreshed.kind === 'still-current') {\n if (unreadable.delete(room.locator)) {\n list(room, true);\n emitRooms();\n }\n return null;\n }\n if (refreshed.kind === 'advanced') {\n if (closed) return unconfirmed;\n await publish(local, room, refreshed.confirmed);\n return null;\n }\n if (refreshed.kind !== 'beyond-horizon') return refreshed;\n }\n const bootstrapped = await pullBootstrap(authorized, room);\n if (bootstrapped.kind !== 'staged') return bootstrapped;\n if (closed) return unconfirmed;\n await publish(local, room, bootstrapped.confirmed);\n return null;\n }\n\n async function withhold(\n withheld: Withheld,\n room: DiscoveredRoom,\n local: RuntimeStore,\n progress: CycleProgress,\n ): Promise<'stop' | null> {\n progress.complete = false;\n if (withheld.kind === 'scoped-refusal') {\n await scoped(withheld, room, local);\n } else if (withheld.kind === 'transport-uncertainty') {\n progress.reachable = false;\n } else if (withheld.kind === 'room-not-readable') {\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n } else if (withheld.kind === 'revoked-authorization') {\n await refuse('revoked-authorization');\n return 'stop';\n }\n return null;\n }\n\n function leaving(\n batch: ChangeBatch,\n result: Extract<MutationResult, { kind: 'conflicted' | 'rejected' | 'expired' }>,\n ): Leaving {\n if (result.kind === 'expired') {\n return { batch, outcome: { kind: 'expired' }, returned: { kind: 'expired' } };\n }\n const refusal = { code: result.code, fields: result.fields };\n if (result.kind === 'conflicted') {\n return {\n batch,\n outcome: {\n kind: 'conflicted',\n ...(result.roomVersion === undefined ? {} : { roomVersion: result.roomVersion }),\n affected: result.affected,\n ...refusal,\n },\n returned: { kind: 'conflicted', ...refusal },\n };\n }\n return {\n batch,\n outcome: { kind: 'rejected', affected: result.affected, ...refusal },\n returned: { kind: 'rejected', ...refusal },\n };\n }\n\n async function commitAccept(\n room: DiscoveredRoom,\n local: RuntimeStore,\n submitted: ChangeBatch,\n accepted: Extract<MutationResult, { kind: 'accepted' }>,\n base: ConfirmedLayer,\n overlay: boolean,\n ): Promise<boolean> {\n const current = replicas.get(room.locator);\n if (current === undefined || !current.queue.some((batch) => batch.id === submitted.id)) {\n return true;\n }\n const remaining = current.queue.filter((batch) => batch.id !== submitted.id);\n const retainedBase = readConfirmed(\n {\n ...base.record,\n model: modelOf(room.locator),\n selectionModel: modelOf(room.locator, 'typed-selection'),\n },\n base,\n );\n if (retainedBase === null) return false;\n const applied = overlay\n ? applyReturned(\n retainedBase,\n accepted.documents,\n accepted.revisions,\n accepted.removals,\n accepted.roomVersion,\n )\n : retainedBase;\n if (applied === null) return false;\n const acceptedOutcome: SubmissionOutcome = {\n kind: 'accepted',\n roomVersion: accepted.roomVersion,\n ...(accepted.author === undefined ? {} : { author: accepted.author }),\n ...(accepted.time === undefined ? {} : { time: accepted.time }),\n };\n const set = await settle(local, room.locator, current, applied, remaining, {\n accepted: { id: submitted.id, outcome: acceptedOutcome },\n room: true,\n });\n unreadable.delete(room.locator);\n list(room, true);\n publishChangeSet(set);\n moveTo({ ...status, ...attention() });\n journal.record(\n `outcome ${room.locator} ${submitted.id} accepted ${accepted.roomVersion}` +\n (accepted.author === undefined ? '' : ` author ${accepted.author}`) +\n (accepted.time === undefined ? '' : ` time ${accepted.time}`),\n );\n return true;\n }\n\n async function submitRoom(\n room: DiscoveredRoom,\n local: RuntimeStore,\n authorized: Authorization,\n progress: CycleProgress,\n ): Promise<'stop' | null> {\n while (!closed && authorization !== undefined) {\n const replica = replicas.get(room.locator);\n const head = replica?.queue[0];\n if (replica === undefined || head === undefined) return null;\n const { submission, lost: earlier } = pendings.get(head.id) ?? {\n submission: { state: 'waiting' },\n lost: false,\n };\n if (submission.state === 'reset' && Date.now() < Date.parse(submission.reset)) {\n progress.complete = false;\n return null;\n }\n const lost = earlier || submission.state === 'submitted';\n let result: MutationResult;\n journal.record(`submission ${room.locator} ${head.id}`);\n await exclusive(() => mark(local, room.locator, head.id, { state: 'submitted' }, lost));\n try {\n result = await options.adapter.mutate(authorized, {\n locator: room.locator,\n changeBatch: head,\n });\n } catch {\n progress.complete = false;\n progress.reachable = false;\n return null;\n }\n if (closed) return null;\n if (result.kind === 'transport-uncertainty') {\n progress.complete = false;\n progress.reachable = false;\n return null;\n }\n if (result.kind === 'room-not-readable') {\n progress.complete = false;\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n return null;\n }\n if (result.kind === 'revoked-authorization') {\n await refuse('revoked-authorization');\n return 'stop';\n }\n if (result.kind === 'scoped-refusal') {\n await scoped(result, room, local);\n progress.complete = false;\n return null;\n }\n if (\n result.kind === 'conflicted' ||\n result.kind === 'rejected' ||\n result.kind === 'expired' ||\n result.kind === 'retryable-refusal'\n ) {\n journal.record(\n `outcome ${room.locator} ${head.id} ${result.kind}` +\n (result.kind === 'conflicted' && result.roomVersion !== undefined\n ? ` ${result.roomVersion}`\n : ''),\n );\n if (result.kind !== 'expired') journal.record(`refusal ${result.kind} ${result.code}`);\n }\n if (result.kind === 'retryable-refusal') {\n const reset = result.reset;\n progress.complete = false;\n await exclusive(() =>\n mark(\n local,\n room.locator,\n head.id,\n reset === undefined ? { state: 'waiting' } : { state: 'reset', reset },\n lost,\n ),\n );\n return null;\n }\n if (result.kind === 'conflicted' || result.kind === 'rejected' || result.kind === 'expired') {\n const left = leaving(head, result);\n await exclusive(async () => {\n const current = replicas.get(room.locator);\n if (current === undefined || !current.queue.some((batch) => batch.id === head.id)) {\n return;\n }\n const set = await settle(\n local,\n room.locator,\n current,\n current.confirmed,\n current.queue.filter((batch) => batch.id !== head.id),\n { leaving: left },\n );\n publishChangeSet(set);\n moveTo({ ...status, ...attention() });\n });\n const withheld = await advance(room, local, authorized);\n if (withheld !== null) return withhold(withheld, room, local, progress);\n continue;\n }\n const from = replicas.get(room.locator)?.confirmed;\n if (from === undefined) return null;\n const pulled = await pullRefresh(authorized, from);\n if (pulled.kind === 'revoked-authorization') {\n await refuse('revoked-authorization');\n return 'stop';\n }\n if (pulled.kind === 'scoped-refusal') {\n await scoped(pulled, room, local);\n progress.complete = false;\n return null;\n }\n if (pulled.kind === 'still-current') {\n const committed = await exclusive(() =>\n commitAccept(room, local, head, result, from, true),\n );\n if (!committed) {\n progress.complete = false;\n return null;\n }\n continue;\n }\n if (pulled.kind === 'advanced') {\n const overlay = pulled.confirmed.record.roomVersion === result.roomVersion;\n const committed = await exclusive(() =>\n commitAccept(room, local, head, result, pulled.confirmed, overlay),\n );\n if (!committed) {\n progress.complete = false;\n return null;\n }\n continue;\n }\n if (pulled.kind === 'beyond-horizon') {\n const bootstrapped = await pullBootstrap(authorized, room);\n if (bootstrapped.kind === 'revoked-authorization') {\n await refuse('revoked-authorization');\n return 'stop';\n }\n if (bootstrapped.kind === 'scoped-refusal') {\n await scoped(bootstrapped, room, local);\n progress.complete = false;\n return null;\n }\n if (bootstrapped.kind === 'staged') {\n const overlay = bootstrapped.confirmed.record.roomVersion === result.roomVersion;\n const committed = await exclusive(() =>\n commitAccept(room, local, head, result, bootstrapped.confirmed, overlay),\n );\n if (!committed) {\n progress.complete = false;\n return null;\n }\n continue;\n }\n progress.complete = false;\n if (bootstrapped.kind === 'transport-uncertainty') {\n progress.reachable = false;\n } else if (bootstrapped.kind === 'room-not-readable') {\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n }\n return null;\n }\n progress.complete = false;\n if (pulled.kind === 'transport-uncertainty') {\n progress.reachable = false;\n } else if (pulled.kind === 'room-not-readable') {\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n }\n return null;\n }\n return null;\n }\n\n async function retainModel(\n local: RuntimeStore,\n room: RoomDeclaration,\n attached: Attached,\n next: ModelState,\n ) {\n const key = modelKey(room.locator, attached);\n if (next.status === 'unavailable') modelEpoch.set(key, (modelEpoch.get(key) ?? 0) + 1);\n const epoch = modelEpoch.get(key) ?? 0;\n const previous = modelOf(room.locator, attached);\n const heldBefore = replicas.get(room.locator)?.confirmed.record;\n if (\n JSON.stringify(previous) === JSON.stringify(next) &&\n (heldBefore === undefined ||\n (JSON.stringify(heldBefore.operations) === JSON.stringify(room.operations) &&\n JSON.stringify(heldBefore.replica) === JSON.stringify(room.replica) &&\n JSON.stringify(heldBefore.attachedModel) === JSON.stringify(room.attachedModel) &&\n JSON.stringify(heldBefore.typedSelection) ===\n JSON.stringify(room.typedSelection ?? null)))\n )\n return;\n if (next.status === 'unavailable') {\n invalidModels.add(key);\n liveModels.delete(key);\n }\n await exclusive(async () => {\n if (next.status !== 'unavailable' && epoch !== (modelEpoch.get(key) ?? 0)) return;\n const held = replicas.get(room.locator);\n if (held !== undefined) {\n const record = {\n ...held.confirmed.record,\n operations: room.operations,\n replica: room.replica,\n attachedModel: room.attachedModel,\n typedSelection: room.typedSelection ?? null,\n ...(attached === 'collection' ? { model: next } : { selectionModel: next }),\n };\n await local.write({\n next: record,\n previous: held.confirmed.record,\n queue: held.queue,\n });\n const confirmed = readConfirmed(record, held.confirmed);\n if (confirmed !== null) {\n replicas.set(room.locator, replicaOf(confirmed, held.queue, rewriting(), held));\n }\n }\n models.set(key, next);\n if (next.status === 'current') {\n liveModels.set(key, JSON.stringify(next.snapshot));\n invalidModels.delete(key);\n }\n list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));\n if (held === undefined) emitRooms();\n else\n publishChangeSet(\n changeSet(room.locator, held, replicas.get(room.locator) ?? null, { room: true }),\n );\n });\n }\n\n async function acquireModel(\n local: RuntimeStore,\n room: DiscoveredRoom,\n authorized: Authorization,\n selection: TypedSelection | null,\n ) {\n const attached: Attached = selection === null ? 'collection' : 'typed-selection';\n const key = modelKey(room.locator, attached);\n const declared = selection === null ? room.attachedModel : selection.attachedModel;\n let previous = modelOf(room.locator, attached);\n if (\n previous.status !== 'unavailable' &&\n (declared === null || !sameModel(previous.snapshot, declared))\n ) {\n previous = { status: 'unavailable', reason: 'version-changed' };\n await retainModel(local, room, attached, previous);\n }\n const epoch = modelEpoch.get(key) ?? 0;\n let answer;\n try {\n answer = await options.adapter.model(\n authorized,\n selection === null\n ? {\n locator: room.locator,\n attached: 'collection',\n collectionRoot: room.collectionRoot,\n model: declared,\n }\n : {\n locator: room.locator,\n attached: 'typed-selection',\n roots: selection.roots,\n model: declared,\n },\n );\n } catch {\n answer = { kind: 'transport-uncertainty' as const };\n }\n if (epoch !== (modelEpoch.get(key) ?? 0)) return;\n if (answer.kind === 'revoked-authorization') {\n await refuse('revoked-authorization');\n return;\n }\n if (answer.kind === 'transport-uncertainty') {\n await retainModel(local, room, attached, cached(previous));\n return;\n }\n if (answer.kind === 'model-unavailable') {\n await retainModel(local, room, attached, {\n status: 'unavailable',\n reason: answer.reason,\n });\n return;\n }\n if (declared === null || !sameModel(answer.snapshot, declared)) {\n await retainModel(local, room, attached, {\n status: 'unavailable',\n reason: 'version-changed',\n });\n return;\n }\n if (\n previous.status !== 'unavailable' &&\n sameModel(previous.snapshot, answer.snapshot) &&\n JSON.stringify(Object.entries(previous.snapshot.definitions).sort()) !==\n JSON.stringify(Object.entries(answer.snapshot.definitions).sort())\n ) {\n await retainModel(local, room, attached, { status: 'unavailable', reason: 'invalid' });\n return;\n }\n const verified = verify(answer.snapshot.definitions);\n if (verified.verdict === 'refuse')\n journal.record(`model invalid ${room.locator} ${attached} ${verified.rule} ${verified.file}`);\n await retainModel(\n local,\n room,\n attached,\n verified.verdict === 'accept'\n ? {\n status: 'current',\n snapshot: structuredClone(answer.snapshot),\n verifiedWith: MD_MODEL,\n types: verified.model.types,\n }\n : { status: 'unavailable', reason: 'invalid' },\n );\n }\n\n async function scoped(\n result: import('./adapter.js').ScopedRefusal,\n room: RoomDeclaration,\n local: RuntimeStore,\n ) {\n scopedRefusals.set(room.locator, { code: result.code, fields: result.fields });\n let scopedAway = room;\n if (result.scope === 'model')\n await retainModel(local, room, 'collection', {\n status: 'unavailable',\n reason: 'not-readable',\n });\n else if (result.scope !== 'operation') {\n unreadable.add(room.locator);\n scopedAway = {\n ...room,\n replica: { ...room.replica, admission: 'unavailable' },\n operations: {\n ...room.operations,\n ...(result.scope === 'content' ? { read: [] } : {}),\n ...(result.scope === 'sync' ? { sync: [] } : {}),\n },\n };\n await retainModel(local, scopedAway, 'collection', modelOf(room.locator));\n }\n list(scopedAway, scopedAway.replica.admission === 'admitted' && !unreadable.has(room.locator));\n emitRooms();\n journal.record(`scoped refusal ${room.locator} ${result.scope} ${result.code}`);\n }\n\n async function synchronize(\n discovered: readonly DiscoveredRoom[],\n local: RuntimeStore,\n progress: CycleProgress,\n ) {\n for (const room of discovered) {\n if (closed || authorization === undefined) {\n progress.complete = false;\n return;\n }\n const prior = replicas.get(room.locator)?.confirmed.record;\n if (prior !== undefined && prior.replica.selection !== room.replica.selection) {\n list(prior, false);\n emitRooms();\n journal.record(`selection changed ${room.locator}`);\n progress.complete = false;\n continue;\n }\n await acquireModel(local, room, authorization, null);\n if (discoveryPaused) return;\n if (room.typedSelection !== undefined) {\n await acquireModel(local, room, authorization, room.typedSelection);\n if (discoveryPaused) return;\n }\n if (room.replica.admission !== 'admitted') {\n progress.complete = false;\n continue;\n }\n const held = replicas.get(room.locator);\n if (\n held !== undefined &&\n held.confirmed.record.replica.selection !== room.replica.selection\n ) {\n progress.complete = false;\n continue;\n }\n const withheld = await advance(room, local, authorization);\n if (withheld !== null) {\n if ((await withhold(withheld, room, local, progress)) === 'stop') return;\n continue;\n }\n if ((await submitRoom(room, local, authorization, progress)) === 'stop') return;\n }\n }\n\n async function cycle(local: RuntimeStore, progress: CycleProgress) {\n if (closed || authorization === undefined) {\n notifyReady();\n return;\n }\n moveTo(transferring(status));\n let result;\n try {\n result = await options.adapter.discover(authorization);\n } catch {\n result = { kind: 'transport-uncertainty' as const };\n }\n if (closed) {\n notifyReady();\n return;\n }\n journal.record(`connection discover ${result.kind}`);\n if (result.kind === 'transport-uncertainty') {\n for (const room of rooms.values()) {\n await retainModel(local, room, 'collection', cached(modelOf(room.locator)));\n if (room.typedSelection !== null) {\n await retainModel(\n local,\n room,\n 'typed-selection',\n cached(modelOf(room.locator, 'typed-selection')),\n );\n }\n }\n progress.reachable = false;\n notifyReady();\n return;\n }\n if (result.kind === 'contract-unavailable') {\n journal.record(`connection contract unavailable ${result.code}`);\n await refuse('missing-required-guarantee', { code: result.code, fields: result.fields });\n notifyReady();\n return;\n }\n if (result.kind === 'revoked-authorization') {\n await refuse('revoked-authorization');\n notifyReady();\n return;\n }\n if (!result.supportedVersions.includes(ROOM_CONTRACT_VERSION)) {\n await refuse('no-matching-version');\n notifyReady();\n return;\n }\n if (\n result.mdModel.identity !== MD_MODEL.identity ||\n result.mdModel.version !== MD_MODEL.version\n ) {\n await refuse('md-model-version-mismatch');\n notifyReady();\n return;\n }\n mismatchedRoots.clear();\n for (const room of result.rooms) {\n const held = replicas.get(room.locator)?.confirmed.record;\n const malformed = !validRoot(room.collectionRoot);\n if (\n room.operations === undefined ||\n !['read', 'sync', 'write', 'delete'].every(\n (operation) =>\n Array.isArray(room.operations[operation as keyof typeof room.operations]) &&\n room.operations[operation as keyof typeof room.operations].every(\n (scope) => typeof scope === 'string',\n ),\n ) ||\n room.replica === undefined ||\n typeof room.replica.selection !== 'string' ||\n room.replica.selection.length === 0 ||\n !['admitted', 'unavailable'].includes(room.replica.admission) ||\n !declaredIdentity(room.attachedModel)\n ) {\n journal.record(`invalid model or replica declaration ${room.locator}`);\n await refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n if (!declaredSelection(room)) {\n journal.record(`invalid typed selection declaration ${room.locator}`);\n await refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n if (malformed || (held !== undefined && held.collectionRoot !== room.collectionRoot)) {\n mismatchedRoots.add(room.locator);\n journal.record(`collection root ${malformed ? 'invalid' : 'changed'} ${room.locator}`);\n }\n }\n if (mismatchedRoots.size > 0) {\n await refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n const declared = new Set(result.capabilities.map((capability) => capability.name));\n for (const required of options.requiredGuarantees) {\n if (!knownCapabilities.has(required) || !declared.has(required)) {\n await refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n }\n if (refusal !== null) {\n refusal = null;\n emitRefusal();\n }\n const previousCapabilities = capabilities;\n capabilities = result.capabilities;\n notifyReady();\n if (declared.has('room-version-notifications')) observeRoomVersions();\n if (declared.has('provider-actions')) observeConversations();\n const discoveredSlots = result.slots ?? [];\n if (\n JSON.stringify(result.providerLimits) !== JSON.stringify(limits) ||\n JSON.stringify(result.capabilities) !== JSON.stringify(previousCapabilities) ||\n JSON.stringify(discoveredSlots) !== JSON.stringify(slots)\n ) {\n limits = result.providerLimits;\n slots = discoveredSlots;\n await local.declare(limits, capabilities, slots);\n }\n await applyDiscovery(result.rooms, local);\n handSelected(\n result.rooms\n .filter((room) => room.replica.admission === 'admitted')\n .map((room) => room.locator)\n .sort(),\n );\n progress.complete = true;\n await synchronize(result.rooms, local, progress);\n if (closed || discoveryPaused) return;\n await conversations.reconcile();\n if (status.providerUnreachable) conversations.reconnected();\n await conversations.catchUp(progress);\n }\n\n async function ensureAuthorization() {\n if (authorization !== undefined) return;\n try {\n authorization = await options.adapter.authorize();\n journal.record('connection authorize');\n } catch (error) {\n journal.record('connection authorize transport-uncertainty');\n throw error;\n }\n }\n\n async function connect() {\n if (closed || discoveryPaused) {\n notifyReady();\n return;\n }\n startTimer();\n const progress: CycleProgress = { complete: false, reachable: true };\n let completedAt = new Date().toISOString();\n try {\n const local = await openLocal();\n if (closed) return;\n await ensureAuthorization();\n if (closed) return;\n await cycle(local, progress);\n if (closed) return;\n if (progress.complete) {\n completedAt = new Date().toISOString();\n await local.complete(completedAt);\n }\n } catch {\n progress.complete = false;\n notifyReady();\n return;\n } finally {\n notifyReady();\n moveTo(settled(status, progress, completedAt, pending(), attention()));\n }\n }\n\n async function run() {\n try {\n await connect();\n } finally {\n inflight = false;\n if (queued && !closed) {\n queued = false;\n void enqueue();\n }\n }\n }\n\n function observeRoomVersions() {\n const path = options.adapter.roomVersions;\n if (path === undefined || withdrawNotifications !== undefined) return;\n withdrawNotifications = path.observe((notification) => {\n if (closed || discoveryPaused) return;\n notices.set(notification.locator, notification.roomVersion);\n chain = chain.then(runNotified, runNotified);\n });\n }\n\n function observeConversations() {\n const stream = options.adapter.conversations;\n if (stream === undefined || withdrawConversations !== undefined) return;\n withdrawConversations = stream.observe((event) => {\n conversations.receive(event);\n if (event.kind !== 'gap' || conversations.current()) return;\n show();\n scheduleCurrency();\n });\n }\n\n function scheduleCurrency() {\n if (currencyQueued || closed) return;\n currencyQueued = true;\n chain = chain.then(runCurrency, runCurrency);\n }\n\n async function runCurrency() {\n currencyQueued = false;\n if (closed || discoveryPaused) return;\n await conversations.reconcile();\n if (conversations.current()) {\n show();\n return;\n }\n const resting = status;\n const progress: CycleProgress = { complete: false, reachable: !resting.providerUnreachable };\n moveTo(transferring(resting));\n try {\n await conversations.catchUp(progress);\n } catch {\n progress.reachable = false;\n } finally {\n if (!closed) {\n moveTo(settled(resting, progress, resting.lastCompleted, pending(), attention()));\n }\n }\n }\n\n function handSelected(locators: readonly string[]) {\n const path = options.adapter.roomVersions;\n if (path === undefined || withdrawNotifications === undefined) return;\n if (handed !== undefined && JSON.stringify(locators) === JSON.stringify(handed)) return;\n handed = locators;\n path.select(locators);\n }\n\n async function runNotified() {\n const announced = [...notices];\n notices.clear();\n if (announced.length === 0 || closed || discoveryPaused) return;\n const resting = status;\n const progress: CycleProgress = { complete: false, reachable: !resting.providerUnreachable };\n moveTo(transferring(resting));\n try {\n const local = await openLocal();\n for (const [locator, roomVersion] of announced) {\n if (closed || discoveryPaused || authorization === undefined) return;\n if (handed?.includes(locator) !== true) continue;\n const room = discovered.get(locator);\n const held = replicas.get(locator);\n if (room === undefined || held === undefined) continue;\n if (held.confirmed.record.roomVersion === roomVersion) continue;\n const withheld = await advance(room, local, authorization);\n if (withheld === null) continue;\n if (withheld.kind === 'scoped-refusal') {\n await scoped(withheld, room, local);\n continue;\n }\n if (withheld.kind === 'transport-uncertainty') {\n progress.reachable = false;\n continue;\n }\n if (withheld.kind === 'room-not-readable') {\n unreadable.add(locator);\n list(room, false);\n emitRooms();\n continue;\n }\n if (withheld.kind === 'revoked-authorization') {\n await refuse('revoked-authorization');\n return;\n }\n }\n } catch {\n progress.reachable = false;\n } finally {\n if (!closed) {\n moveTo(settled(resting, progress, resting.lastCompleted, pending(), attention()));\n }\n }\n }\n\n function enqueue() {\n if (inflight) {\n queued = true;\n return chain;\n }\n inflight = true;\n chain = chain.then(run, run);\n return chain;\n }\n\n function close() {\n closed = true;\n withdrawNotifications?.();\n withdrawNotifications = undefined;\n withdrawConversations?.();\n withdrawConversations = undefined;\n conversations.close();\n stopTimer();\n store?.close();\n void opening?.then(\n (opened) => {\n opened.close();\n },\n () => {},\n );\n roomListeners.clear();\n refusalListeners.clear();\n storageLossListeners.clear();\n statusListeners.clear();\n readSide.close();\n queueSubscriptions.clear();\n roomDraftListeners.clear();\n presentationListeners.clear();\n }\n\n options.signal?.addEventListener('abort', close, { once: true });\n if (options.signal?.aborted) close();\n\n void openLocal().catch(() => {\n notifyReady();\n });\n void enqueue();\n\n function watch(\n topic: RuntimeTopic,\n input: readonly unknown[],\n deliver: (message: unknown) => void,\n ): () => void {\n if (topic === 'room-drafts') {\n const listener: RoomDraftSubscription = { notify: deliver, ready: false };\n roomDraftListeners.add(listener);\n void exclusive(async () => {\n await openLocal();\n if (closed || !roomDraftListeners.has(listener)) return;\n listener.ready = true;\n }).then(\n () => {\n if (closed || !listener.ready || !roomDraftListeners.has(listener)) return;\n listener.notify(snapshotRoomDrafts());\n },\n () => {},\n );\n return () => {\n roomDraftListeners.delete(listener);\n };\n }\n if (topic === 'conversation') {\n return conversations.watch(input[0] as string, input[1] as ConversationOptions, deliver);\n }\n if (topic === 'presentation') {\n const listener: PresentationSubscription = {\n app: input[0] as string,\n notify: deliver,\n ready: false,\n };\n presentationListeners.add(listener);\n void exclusive(async () => {\n await openLocal();\n }).then(\n () => {\n if (closed || !presentationListeners.has(listener)) return;\n listener.ready = true;\n listener.notify(presentationOf(listener.app));\n },\n () => {},\n );\n return () => {\n presentationListeners.delete(listener);\n };\n }\n if (topic === 'rooms') {\n roomListeners.add(deliver);\n deliver(listed());\n return () => {\n roomListeners.delete(deliver);\n };\n }\n if (topic === 'connection-refusal') {\n refusalListeners.add(deliver);\n deliver(refusal);\n return () => {\n refusalListeners.delete(deliver);\n };\n }\n if (topic === 'storage-loss') {\n storageLossListeners.add(deliver);\n deliver(storageLoss);\n return () => {\n storageLossListeners.delete(deliver);\n };\n }\n if (topic === 'sync-status') {\n statusListeners.add(deliver);\n deliver(shown);\n return () => {\n statusListeners.delete(deliver);\n };\n }\n if (topic === 'queue') {\n const queue: QueueSubscription = { locator: input[0] as string, notify: deliver };\n queueSubscriptions.add(queue);\n queue.notify(entriesOf(queue.locator));\n return () => {\n queueSubscriptions.delete(queue);\n };\n }\n const plan = planOf(input[0], roomFacts());\n return readSide.watch(plan, identityOf(plan), deliver);\n }\n\n const md: MdRuntime = {\n loaded() {\n return openLocal().then(() => undefined);\n },\n rooms() {\n return listed();\n },\n slots() {\n return slotted();\n },\n query: ((input: unknown) => readSide.query(planOf(input, roomFacts()))) as MdRuntime['query'],\n async search(input: unknown) {\n const plan = searchPlanOf(input);\n const selected =\n plan.documents === undefined\n ? null\n : ((await readSide.query(filterOf(plan.documents, roomFacts()))) as DocumentResult)\n .documents;\n return searchIndex.search(plan, selected);\n },\n types(locator: string): RoomTypes {\n return {\n collection: modelTypes(modelOf(locator)),\n typedSelection:\n rooms.get(locator)?.typedSelection === undefined ||\n rooms.get(locator)?.typedSelection === null\n ? null\n : modelTypes(modelOf(locator, 'typed-selection')),\n };\n },\n syncStatus() {\n return shown;\n },\n roomDraft: {\n list() {\n return exclusive(async () => {\n await openLocal();\n return snapshotRoomDrafts();\n }).then((listed) => {\n publishRoomDrafts(true);\n return listed;\n });\n },\n read(room: string, path: string) {\n const record = roomDrafts.get(room)?.get(path);\n return record === undefined ? null : roomDraftOf(record);\n },\n write(room: string, path: string, revision: string | null, input: unknown) {\n return exclusive(async (): Promise<RoomDraftWrite> => {\n const parts = readParts(input);\n if (path === '' || normalize(path) !== path) throw new Error('room-draft-malformed');\n const local = await openLocal();\n const current = roomDrafts.get(room)?.get(path);\n if ((current?.revision ?? null) !== revision) {\n return {\n outcome: 'stale',\n current: current === undefined ? null : roomDraftOf(current),\n };\n }\n const record: RoomDraftRecord = {\n locator: room,\n path,\n revision: roomDraftRevision(),\n parts: held(current?.parts, parts),\n returned: current?.returned ?? null,\n };\n await local.keepRoomDraft(record);\n rememberRoomDraft(record);\n publishChangeSet(changeSet(room, null, null, { drafts: [path] }));\n return { outcome: 'written', roomDraft: roomDraftOf(record) };\n });\n },\n discard(room: string, path: string, revision: string) {\n return exclusive(async (): Promise<RoomDraftWrite> => {\n const local = await openLocal();\n const current = roomDrafts.get(room)?.get(path);\n if (current === undefined || current.revision !== revision) {\n return {\n outcome: 'stale',\n current: current === undefined ? null : roomDraftOf(current),\n };\n }\n await local.discardRoomDraft(room, path);\n forgetRoomDraft(room, path);\n publishChangeSet(changeSet(room, null, null, { drafts: [path] }));\n moveTo({ ...status, ...attention() });\n return { outcome: 'written', roomDraft: null };\n });\n },\n },\n conversation: conversations.surface,\n chatDraft: conversations.chatDraft,\n presentation: {\n read(app: string) {\n return exclusive(async () => {\n await openLocal();\n return presentationOf(app);\n });\n },\n write(app: string, value: unknown) {\n return exclusive(async () => {\n const local = await openLocal();\n const stored = structuredClone(value);\n await local.present({ app, value: stored });\n presentations.set(app, stored);\n publishChangeSet(changeSet('', null, null, { presentation: app }));\n });\n },\n },\n save(\n room: string,\n named: readonly SavedRoomDraft[],\n writtenBy?: WrittenBy,\n ): Promise<SaveResult> {\n return exclusive(() => saveRoomDrafts(room, named, writtenBy));\n },\n outcome(identifier: string): SubmissionOutcome | null {\n return outcomes.get(identifier) ?? null;\n },\n history(locator: string, path: string, query?: HistoryQuery) {\n return readHistory(locator, path, query);\n },\n call(name: string, input: unknown) {\n return invokeAction(name, input);\n },\n log() {\n return journal.export();\n },\n storageLoss() {\n return storageLoss;\n },\n persistence() {\n return options.shell.persistentStorage;\n },\n observe: ((topic: RuntimeTopic, ...input: unknown[]) =>\n opened(\n (deliver) =>\n watch(topic, input, (message) => {\n deliver(structuredClone(message));\n }),\n topic === 'query',\n )) as MdRuntime['observe'],\n async reauthorize() {\n if (refusal === null || !refusal.reauthorizationOffered) return;\n journal.record('connection reauthorize');\n await mutations;\n authorization = undefined;\n discoveryPaused = false;\n await enqueue();\n },\n };\n return { md, watch };\n}\n"],"names":["verify","cached","modelTypes","NO_MODEL","sameModel","opened","filterOf","identityOf","planOf","createReadSide","createSearchIndex","searchPlanOf","ROOM_CONTRACT_VERSION","VERSION_1_CAPABILITIES","bootstrapRoom","changeSet","mergeChangeSets","createConversationStore","MD_MODEL","validRoot","createLog","refreshRoom","buildBatch","applyReturned","compositionOf","readConfirmed","replicaOf","withdrawals","changedParts","changesOf","held","readParts","returnedInto","underneath","settled","same","saving","STARTING","transferring","detectStorageLoss","nextGeneration","roomDraftRevision","beneath","normalize","openRuntimeStore","unconfirmed","DEFAULT_DISCOVERY_INTERVAL_MS","knownCapabilities","Set","within","root","path","declaredIdentity","model","undefined","identity","length","version","declaredSelection","room","selection","typedSelection","Array","isArray","roots","attachedModel","every","index","collectionRoot","other","at","createMdRuntime","options","composeRuntime","md","period","discoveryIntervalMs","authorization","opening","store","replicas","Map","pendings","roomDrafts","presentations","outcomes","outcomeRooms","limits","slots","capabilities","rewriting","some","capability","name","rooms","unreadable","models","liveModels","invalidModels","modelEpoch","discovered","roomsListed","scopedRefusals","modelKey","locator","attached","modelOf","get","savedModel","has","status","reason","compositionFor","record","selectionModel","mismatchedRoots","refusal","storageLoss","shown","discoveryPaused","timer","closed","withdrawNotifications","handed","notices","chain","Promise","resolve","mutations","inflight","queued","roomListeners","refusalListeners","storageLossListeners","statusListeners","queueSubscriptions","roomDraftListeners","presentationListeners","readSide","withdrawConversations","currencyQueued","conversations","cards","declaredCards","documents","query","select","roomFacts","call","input","invokeAction","durably","stream","adapter","publish","publishChangeSet","searchIndex","document","messages","message","conversation","journal","notifyReady","ready","rememberRoomDraft","set","forgetRoomDraft","delete","size","roomDraftOf","structuredClone","revision","parts","changedUnderneath","visible","returned","snapshotRoomDrafts","records","values","flatMap","sort","left","right","map","publishRoomDrafts","waitingOnly","value","listener","notify","presentationOf","app","emitPresentation","pending","replica","queue","attention","attentionRequired","push","reset","submission","state","listed","slotted","slot","entries","segment","available","types","Object","emitRooms","emitRefusal","emitStorageLoss","moveTo","next","show","current","submissionOf","batch","id","entriesOf","freeze","emitQueue","subscription","applyChangeSet","apply","changed","queues","drafts","change","scheduleCurrency","stopTimer","clearInterval","startTimer","setInterval","enqueue","refuse","provider","exclusive","revoked","local","openLocal","revokeModels","confirmed","keys","add","key","before","Error","reauthorizationOffered","list","synchronizationAvailable","operations","providerOwnedPaths","roomVersion","applyDiscovery","listedLocators","clear","dropUnlisted","admission","unlistedHeld","filter","unlisted","dropRooms","removed","restored","persisted","prior","snapshot","JSON","stringify","hydrate","recordedOutcomes","kept","presented","chatDrafts","lastCompleted","declared","named","listedSlots","all","presentation","providerLimits","queuedBatches","outcome","previousReplicas","existing","locators","read","readState","open","shell","generation","storedGeneration","loss","rememberGeneration","keepGeneration","work","catch","error","then","withdrawable","lost","settle","settling","withdrawn","includes","returning","kind","reverse","leaving","written","saved","settledOutcomes","accepted","write","previous","previousQueue","retained","saveRoomDrafts","writtenBy","rule","file","draft","built","baseRoomVersion","composition","changes","bases","batches","consumed","consumedRoomDrafts","identifier","mark","submit","readHistory","ensureAuthorization","transfer","pageToken","join","result","history","scoped","conversationCards","declaredAction","action","actions","code","pullRefresh","authorized","detail","pullBootstrap","collection","advance","refreshed","bootstrapped","withhold","withheld","progress","complete","reachable","fields","affected","commitAccept","submitted","base","overlay","remaining","retainedBase","applied","revisions","removals","acceptedOutcome","author","time","submitRoom","head","earlier","Date","now","parse","mutate","changeBatch","from","pulled","committed","retainModel","epoch","heldBefore","acquireModel","answer","definitions","verified","verdict","verifiedWith","scopedAway","scope","sync","synchronize","cycle","discover","supportedVersions","mdModel","malformed","operation","required","requiredGuarantees","previousCapabilities","observeRoomVersions","observeConversations","discoveredSlots","declare","handSelected","reconcile","providerUnreachable","reconnected","catchUp","authorize","connect","completedAt","toISOString","run","roomVersions","observe","notification","runNotified","event","receive","runCurrency","resting","announced","close","signal","addEventListener","once","aborted","watch","topic","deliver","plan","loaded","search","selected","syncStatus","roomDraft","keepRoomDraft","discard","discardRoomDraft","surface","chatDraft","stored","present","save","log","export","persistence","persistentStorage","reauthorize"],"mappings":"AAAA,SAASA,MAAM,QAAQ,uBAAuB;AAC9C,SACEC,MAAM,EACNC,UAAU,EACVC,QAAQ,EACRC,SAAS,QAGJ,aAAa;AACpB,SAASC,MAAM,QAA0B,mBAAmB;AAC5D,SACEC,QAAQ,EACRC,UAAU,EACVC,MAAM,QAMD,aAAa;AACpB,SAASC,cAAc,QAAQ,iBAAiB;AAChD,SACEC,i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AAM8F;QACpC;QACAG,MAAKvD,IAAY,EAAEwD,KAAc;YAC/B,OAAOC,aAAazD,MAAMwD;QAC5B;QACA+S;YACE,OAAOnS,QAAQoS,MAAM;QACvB;QACAhV;YACE,OAAOA;QACT;QACAiV;YACE,OAAO9X,QAAQ0N,KAAK,CAACqK,iBAAiB;QACxC;QACAjC,SAAU,CAACc,OAAqB,GAAG/R,QACjChJ,OACE,CAACgb,UACCF,MAAMC,OAAO/R,OAAO,CAACU;oBACnBsR,QAAQ3Q,gBAAgBX;gBAC1B,IACFqR,UAAU;QAEd,MAAMoB;YACJ,IAAIpV,YAAY,QAAQ,CAACA,QAAQoI,sBAAsB,EAAE;YACzDvF,QAAQhD,MAAM,CAAC;YACf,MAAMe;YACNnD,gBAAgBvB;YAChBiE,kBAAkB;YAClB,MAAMmH;QACR;IACF;IACA,OAAO;QAAEhK;QAAIyW;IAAM;AACrB"}
1
+ {"version":3,"sources":["/workspace/packages/mdruntime/src/connection.ts"],"sourcesContent":["import { verify } from '@agentshouse/mdmodel';\nimport {\n cached,\n modelTypes,\n NO_MODEL,\n sameModel,\n type ModelState,\n type TypesResult,\n} from './model.js';\nimport { opened, type Observation } from './observation.js';\nimport {\n filterOf,\n identityOf,\n planOf,\n type DocumentQuery,\n type DocumentResult,\n type GroupQuery,\n type GroupResult,\n type HeldRooms,\n} from './query.js';\nimport { createReadSide } from './read-side.js';\nimport {\n createSearchIndex,\n searchPlanOf,\n type SearchRequest,\n type SearchResult,\n} from './search.js';\nimport {\n ROOM_CONTRACT_VERSION,\n VERSION_1_CAPABILITIES,\n type ActionResult,\n type Adapter,\n type AdapterFailure,\n type Authorization,\n type Capability,\n type DiscoveredRoom,\n type Discovery,\n type HistoryResult,\n type MutationResult,\n type ProviderLimit,\n type ConversationCards,\n type ConversationAction,\n type ProviderRefusal,\n type TypedSelection,\n} from './adapter.js';\nimport { bootstrapRoom } from './bootstrap.js';\nimport { changeSet, mergeChangeSets, type ChangeSet } from './change-set.js';\nimport {\n createConversationStore,\n type ChatDraftSurface,\n type ConversationOptions,\n type ConversationStore,\n type ConversationSurface,\n type ConversationView,\n} from './conversation.js';\nimport type { ChangeBatch, WrittenBy } from './change.js';\nimport { MD_MODEL, validRoot, type Composition } from './collection.js';\nimport { createLog } from './log.js';\nimport type { CallResult, QueueEntry, Submission, SubmissionOutcome } from './outcome.js';\nimport { refreshRoom } from './refresh.js';\nimport { buildBatch, type Rewriting, type SaveRefusal } from './save.js';\nimport {\n applyReturned,\n compositionOf,\n readConfirmed,\n replicaOf,\n withdrawals,\n type ConfirmedLayer,\n type Replica,\n} from './replica.js';\nimport {\n changedParts,\n changesOf,\n held,\n readParts,\n returnedInto,\n underneath,\n type ReturnReason,\n type RoomDraft,\n type RoomDraftRecord,\n type RoomDraftWrite,\n type SavedDraft,\n} from './room-draft.js';\nimport {\n settled,\n same,\n saving,\n STARTING,\n transferring,\n type AttentionEntry,\n type CycleProgress,\n type SyncStatus,\n} from './status.js';\nimport { detectStorageLoss, nextGeneration, type RuntimeShell } from './durability.js';\nimport { roomDraftRevision } from './identity.js';\nimport { beneath, normalize } from './paths.js';\nimport {\n openRuntimeStore,\n type PendingState,\n type ReplicaRecord,\n type RuntimeStore,\n} from './store.js';\nimport { unconfirmed, type Refused, type Unconfirmed } from './transfer.js';\n\nconst DEFAULT_DISCOVERY_INTERVAL_MS = 60_000;\n\nconst knownCapabilities = new Set<string>(VERSION_1_CAPABILITIES);\n\ntype Attached = 'collection' | 'typed-selection';\n\ntype RoomDeclaration = Omit<DiscoveredRoom, 'roomVersion' | 'typedSelection'> & {\n typedSelection?: TypedSelection | null;\n};\n\nfunction within(root: string, path: string): boolean {\n return root === '' || beneath(root, path);\n}\n\nfunction declaredIdentity(model: import('./model.js').ModelIdentity | null | undefined): boolean {\n if (model === undefined) return false;\n if (model === null) return true;\n return (\n typeof model.identity === 'string' &&\n model.identity.length > 0 &&\n typeof model.version === 'string' &&\n model.version.length > 0\n );\n}\n\nfunction declaredSelection(room: DiscoveredRoom): boolean {\n const selection = room.typedSelection;\n if (selection === undefined) return true;\n if (!Array.isArray(selection.roots) || selection.roots.length === 0) return false;\n if (!declaredIdentity(selection.attachedModel)) return false;\n return selection.roots.every(\n (root, index) =>\n validRoot(root) &&\n root !== '' &&\n !within(room.collectionRoot, root) &&\n selection.roots.every((other, at) => at === index || !within(other, root)),\n );\n}\n\nexport type AppTypedSelection = {\n roots: readonly string[];\n attachedModel: import('./model.js').ModelIdentity | null;\n model: TypesResult;\n};\n\nexport type AppRoom = {\n collectionRoot: string;\n name: string;\n locator: string;\n operations: import('./adapter.js').OperationScopes;\n replica: import('./adapter.js').ReplicaAdmission;\n attachedModel: import('./model.js').ModelIdentity | null;\n model: TypesResult;\n typedSelection: AppTypedSelection | null;\n providerOwnedPaths: readonly string[];\n roomVersion: string | null;\n synchronizationAvailable: boolean;\n refusal: ProviderRefusal | null;\n};\n\nexport type AppSlotEntry = {\n room: AppRoom;\n segment: string | null;\n};\n\nexport type AppSlot = {\n slot: string;\n entries: readonly AppSlotEntry[];\n};\n\nexport type RoomTypes = {\n collection: TypesResult;\n typedSelection: TypesResult | null;\n};\n\nexport type ConnectionRefusalReason =\n | 'no-matching-version'\n | 'missing-required-guarantee'\n | 'md-model-version-mismatch'\n | 'revoked-authorization'\n | 'client-host-protocol-mismatch';\n\nexport type ConnectionRefusal = {\n reason: ConnectionRefusalReason;\n reauthorizationOffered: boolean;\n refusal: ProviderRefusal | null;\n};\n\nexport type MdRuntimeOptions = {\n adapter: Adapter;\n shell: RuntimeShell;\n requiredGuarantees: readonly string[];\n authorization?: Authorization;\n discoveryIntervalMs?: number;\n signal?: AbortSignal;\n};\n\nexport type SaveResult =\n | { outcome: 'saved'; identifier: string }\n | ({ outcome: 'refused' } & SaveRefusal);\n\nexport type SavedRoomDraft = { readonly path: string; readonly revision: string };\n\nexport type RoomDraftSurface = {\n list(): Promise<readonly RoomDraft[]>;\n read(room: string, path: string): RoomDraft | null;\n write(\n room: string,\n path: string,\n revision: string | null,\n parts: unknown,\n ): Promise<RoomDraftWrite>;\n discard(room: string, path: string, revision: string): Promise<RoomDraftWrite>;\n};\n\nexport type PresentationSurface = {\n read(app: string): Promise<unknown>;\n write(app: string, value: unknown): Promise<void>;\n};\n\nexport type HistoryQuery = {\n revision?: string;\n pageToken?: string;\n};\n\nexport type MdRuntime = {\n loaded(): Promise<void>;\n rooms(): readonly AppRoom[];\n slots(): readonly AppSlot[];\n query: {\n (query: DocumentQuery): Promise<DocumentResult>;\n (query: GroupQuery): Promise<GroupResult>;\n };\n search(request: SearchRequest): Promise<SearchResult>;\n types(locator: string): RoomTypes;\n syncStatus(): SyncStatus;\n roomDraft: RoomDraftSurface;\n conversation: ConversationSurface;\n chatDraft: ChatDraftSurface;\n presentation: PresentationSurface;\n save(\n room: string,\n roomDrafts: readonly SavedRoomDraft[],\n writtenBy?: WrittenBy,\n ): Promise<SaveResult>;\n outcome(identifier: string): SubmissionOutcome | null;\n history(locator: string, path: string, query?: HistoryQuery): Promise<HistoryResult>;\n call(name: string, input: unknown): Promise<CallResult>;\n log(): string;\n storageLoss(): string | null;\n persistence(): boolean;\n observe: {\n (topic: 'rooms'): Promise<Observation<readonly AppRoom[]>>;\n (topic: 'connection-refusal'): Promise<Observation<ConnectionRefusal | null>>;\n (topic: 'storage-loss'): Promise<Observation<string | null>>;\n (topic: 'sync-status'): Promise<Observation<SyncStatus>>;\n (topic: 'query', query: DocumentQuery): Promise<Observation<DocumentResult>>;\n (topic: 'query', query: GroupQuery): Promise<Observation<GroupResult>>;\n (topic: 'queue', locator: string): Promise<Observation<readonly QueueEntry[]>>;\n (topic: 'room-drafts'): Promise<Observation<readonly RoomDraft[]>>;\n (topic: 'presentation', app: string): Promise<Observation<unknown>>;\n (\n topic: 'conversation',\n conversation: string,\n options: ConversationOptions,\n ): Promise<Observation<ConversationView>>;\n };\n reauthorize(): Promise<void>;\n};\n\nexport type RuntimeTopic =\n | 'rooms'\n | 'connection-refusal'\n | 'storage-loss'\n | 'sync-status'\n | 'query'\n | 'queue'\n | 'room-drafts'\n | 'presentation'\n | 'conversation';\n\nexport type ComposedRuntime = {\n md: MdRuntime;\n watch(\n topic: RuntimeTopic,\n input: readonly unknown[],\n deliver: (message: unknown) => void,\n ): () => void;\n};\n\ntype QueueSubscription = {\n locator: string;\n notify: (entries: readonly QueueEntry[]) => void;\n};\n\ntype RoomDraftSubscription = {\n notify: (roomDrafts: readonly RoomDraft[]) => void;\n ready: boolean;\n};\n\ntype Leaving = { batch: ChangeBatch; outcome: SubmissionOutcome; returned: ReturnReason };\n\ntype PresentationSubscription = {\n app: string;\n notify: (value: unknown) => void;\n ready: boolean;\n};\n\ntype Withheld = AdapterFailure | Unconfirmed | Refused;\n\nexport function createMdRuntime(options: MdRuntimeOptions): MdRuntime {\n return composeRuntime(options).md;\n}\n\nexport function composeRuntime(options: MdRuntimeOptions): ComposedRuntime {\n const period = options.discoveryIntervalMs ?? DEFAULT_DISCOVERY_INTERVAL_MS;\n let authorization: Authorization | undefined = options.authorization;\n let opening: Promise<RuntimeStore> | undefined;\n let store: RuntimeStore | undefined;\n const replicas = new Map<string, Replica>();\n const pendings = new Map<string, PendingState>();\n const roomDrafts = new Map<string, Map<string, RoomDraftRecord>>();\n const presentations = new Map<string, unknown>();\n const outcomes = new Map<string, SubmissionOutcome>();\n const outcomeRooms = new Map<string, string>();\n let limits: readonly ProviderLimit[] = [];\n let slots: NonNullable<Discovery['slots']> = [];\n let capabilities: readonly Capability[] = [];\n function rewriting(): Rewriting {\n return capabilities.some((capability) => capability.name === 'move-reference-rewrites')\n ? 'provider'\n : 'runtime';\n }\n const rooms = new Map<string, AppRoom>();\n const unreadable = new Set<string>();\n const models = new Map<string, ModelState>();\n const liveModels = new Map<string, string>();\n const invalidModels = new Set<string>();\n const modelEpoch = new Map<string, number>();\n const discovered = new Map<string, DiscoveredRoom>();\n let roomsListed = false;\n const scopedRefusals = new Map<string, ProviderRefusal>();\n const sourceRefusals = new Map<string, ProviderRefusal>();\n function modelKey(locator: string, attached: Attached): string {\n return `${attached} ${locator}`;\n }\n function modelOf(locator: string, attached: Attached = 'collection'): ModelState {\n return models.get(modelKey(locator, attached)) ?? NO_MODEL;\n }\n function savedModel(locator: string, attached: Attached): ModelState {\n return invalidModels.has(modelKey(locator, attached))\n ? { status: 'unavailable', reason: 'revoked' }\n : modelOf(locator, attached);\n }\n function compositionFor(record: ReplicaRecord): Composition {\n return compositionOf({\n ...record,\n model: savedModel(record.locator, 'collection'),\n selectionModel: savedModel(record.locator, 'typed-selection'),\n });\n }\n\n const mismatchedRoots = new Set<string>();\n let refusal: ConnectionRefusal | null = null;\n let storageLoss: string | null = null;\n let status: SyncStatus = STARTING;\n let shown: SyncStatus = STARTING;\n let discoveryPaused = false;\n let timer: ReturnType<typeof setInterval> | undefined;\n let closed = false;\n let withdrawNotifications: (() => void) | undefined;\n let handed: readonly string[] | undefined;\n const notices = new Map<string, string>();\n let chain: Promise<void> = Promise.resolve();\n let mutations: Promise<unknown> = Promise.resolve();\n let inflight = false;\n let queued = false;\n const roomListeners = new Set<(rooms: readonly AppRoom[]) => void>();\n const refusalListeners = new Set<(refusal: ConnectionRefusal | null) => void>();\n const storageLossListeners = new Set<(statement: string | null) => void>();\n const statusListeners = new Set<(status: SyncStatus) => void>();\n const queueSubscriptions = new Set<QueueSubscription>();\n const roomDraftListeners = new Set<RoomDraftSubscription>();\n const presentationListeners = new Set<PresentationSubscription>();\n const readSide = createReadSide();\n let withdrawConversations: (() => void) | undefined;\n let currencyQueued = false;\n const conversations: ConversationStore = createConversationStore({\n cards: declaredCards,\n documents: (locator: string) =>\n readSide.query(\n planOf({ rooms: [locator], select: 'all' }, roomFacts()),\n ) as Promise<DocumentResult>,\n call: (name: ConversationAction, input: unknown) => invokeAction(name, input),\n durably,\n stream: () => options.adapter.conversations,\n publish: publishChangeSet,\n closed: () => closed,\n });\n const searchIndex = createSearchIndex({\n documents: () => readSide.documents(),\n document: (room, path) => readSide.document(room, path),\n messages: () => conversations.messages(),\n message: (conversation, identity) => conversations.message(conversation, identity),\n });\n const journal = createLog();\n let notifyReady = () => {};\n const ready = new Promise<void>((resolve) => {\n notifyReady = resolve;\n });\n function rememberRoomDraft(record: RoomDraftRecord) {\n const room = roomDrafts.get(record.locator) ?? new Map<string, RoomDraftRecord>();\n room.set(record.path, record);\n roomDrafts.set(record.locator, room);\n }\n\n function forgetRoomDraft(locator: string, path: string) {\n const room = roomDrafts.get(locator);\n if (room === undefined) return;\n room.delete(path);\n if (room.size === 0) roomDrafts.delete(locator);\n }\n\n function roomDraftOf(record: RoomDraftRecord): RoomDraft {\n return structuredClone({\n room: record.locator,\n path: record.path,\n revision: record.revision,\n parts: record.parts,\n changedUnderneath: underneath(\n record.parts,\n record.path,\n replicas.get(record.locator)?.visible,\n ),\n returned: record.returned,\n });\n }\n\n function snapshotRoomDrafts(): readonly RoomDraft[] {\n const records = [...roomDrafts.values()].flatMap((room) => [...room.values()]);\n records.sort((left, right) => {\n if (left.locator !== right.locator) return left.locator < right.locator ? -1 : 1;\n if (left.path !== right.path) return left.path < right.path ? -1 : 1;\n return 0;\n });\n return records.map(roomDraftOf);\n }\n\n function publishRoomDrafts(waitingOnly: boolean) {\n if (closed) return;\n const value = snapshotRoomDrafts();\n for (const listener of roomDraftListeners) {\n if (waitingOnly && listener.ready) continue;\n listener.ready = true;\n listener.notify(value);\n }\n }\n\n function presentationOf(app: string): unknown {\n const value = presentations.get(app);\n return value === undefined ? null : structuredClone(value);\n }\n\n function emitPresentation(app: string) {\n if (closed) return;\n for (const listener of presentationListeners) {\n if (listener.app === app && listener.ready) listener.notify(presentationOf(app));\n }\n }\n\n function pending() {\n return [...replicas.values()].some((replica) => replica.queue.length > 0);\n }\n\n function attention(): Pick<SyncStatus, 'attentionRequired' | 'reset'> {\n const attentionRequired: AttentionEntry[] = [];\n for (const record of [...roomDrafts.values()].flatMap((room) => [...room.values()])) {\n if (record.returned === null) continue;\n attentionRequired.push({\n room: record.locator,\n path: record.path,\n returned: structuredClone(record.returned),\n });\n }\n attentionRequired.sort((left, right) => {\n if (left.room !== right.room) return left.room < right.room ? -1 : 1;\n if (left.path !== right.path) return left.path < right.path ? -1 : 1;\n return 0;\n });\n let reset: string | null = null;\n for (const { submission } of pendings.values()) {\n if (submission.state !== 'reset') continue;\n if (reset === null || submission.reset < reset) reset = submission.reset;\n }\n return { attentionRequired, reset };\n }\n\n function listed(): readonly AppRoom[] {\n return structuredClone([...rooms.values()]);\n }\n\n function slotted(): readonly AppSlot[] {\n return structuredClone(\n slots.map(({ slot, entries }) => ({\n slot,\n entries: entries.flatMap(({ locator, segment }) => {\n const room = rooms.get(locator);\n return room === undefined ? [] : [{ room, segment }];\n }),\n })),\n );\n }\n\n function roomFacts(): HeldRooms {\n const held = [...rooms.values()].map((room) => {\n const attached = [\n modelOf(room.locator),\n ...(room.typedSelection === null ? [] : [modelOf(room.locator, 'typed-selection')]),\n ];\n return {\n locator: room.locator,\n available: attached.every((model) => model.status !== 'unavailable'),\n types: attached.flatMap((model) =>\n model.status === 'unavailable' ? [] : Object.values(model.types),\n ),\n };\n });\n return { listed: roomsListed, rooms: held };\n }\n\n function emitRooms() {\n const value = listed();\n for (const listener of roomListeners) listener(value);\n }\n\n function emitRefusal() {\n for (const listener of refusalListeners) listener(refusal);\n }\n\n function emitStorageLoss() {\n for (const listener of storageLossListeners) listener(storageLoss);\n }\n\n function moveTo(next: SyncStatus) {\n if (closed) return;\n status = next;\n show();\n }\n\n function show() {\n if (closed) return;\n const next: SyncStatus =\n status.state === 'synced' && !conversations.current()\n ? { ...status, state: 'syncing' }\n : status;\n if (same(shown, next)) return;\n shown = next;\n for (const listener of statusListeners) listener(shown);\n }\n\n function submissionOf(batch: ChangeBatch): Submission {\n return pendings.get(batch.id)?.submission ?? { state: 'waiting' };\n }\n\n function entriesOf(locator: string): readonly QueueEntry[] {\n const replica = replicas.get(locator);\n if (replica === undefined) return [];\n return replica.queue.map((batch) => Object.freeze({ batch, ...submissionOf(batch) }));\n }\n\n function emitQueue(locator: string) {\n const entries = entriesOf(locator);\n for (const subscription of queueSubscriptions) {\n if (subscription.locator === locator) subscription.notify(entries);\n }\n }\n\n function applyChangeSet(set: ChangeSet) {\n readSide.apply(set);\n searchIndex.changed(set);\n }\n\n function publishChangeSet(set: ChangeSet) {\n applyChangeSet(set);\n if (set.rooms.length > 0) emitRooms();\n for (const locator of set.queues) emitQueue(locator);\n if (\n set.drafts.length > 0 ||\n set.documents.some((change) => roomDrafts.get(change.locator)?.has(change.path) === true)\n ) {\n publishRoomDrafts(false);\n }\n for (const app of set.presentations) emitPresentation(app);\n conversations.changed(set);\n const cards = declaredCards();\n if (cards !== undefined && set.documents.some((change) => change.locator === cards.locator)) {\n scheduleCurrency();\n }\n }\n\n function stopTimer() {\n if (timer === undefined) return;\n clearInterval(timer);\n timer = undefined;\n }\n\n function startTimer() {\n if (timer !== undefined) return;\n timer = setInterval(() => {\n void enqueue();\n }, period);\n }\n\n async function refuse(reason: ConnectionRefusalReason, provider: ProviderRefusal | null = null) {\n stopTimer();\n discoveryPaused = true;\n try {\n if (reason === 'revoked-authorization') {\n await exclusive(async () => {\n const revoked: ModelState = { status: 'unavailable', reason: 'revoked' };\n try {\n const local = await openLocal();\n await local.revokeModels(\n [...replicas.values()].map((replica) => ({\n record: replica.confirmed.record,\n queue: replica.queue,\n })),\n );\n } catch {\n journal.record('model revocation persistence failed');\n }\n const keys = new Set(models.keys());\n for (const locator of rooms.keys()) {\n keys.add(modelKey(locator, 'collection'));\n keys.add(modelKey(locator, 'typed-selection'));\n }\n for (const key of keys) {\n invalidModels.add(key);\n modelEpoch.set(key, (modelEpoch.get(key) ?? 0) + 1);\n models.set(key, revoked);\n liveModels.delete(key);\n }\n const changed: ChangeSet[] = [];\n for (const [locator, room] of rooms) {\n const before = replicas.get(locator) ?? null;\n if (before !== null) {\n const record = {\n ...before.confirmed.record,\n model: revoked,\n selectionModel: revoked,\n };\n const confirmed = readConfirmed(record, before.confirmed);\n if (confirmed === null) throw new Error(`Cannot retype revoked Room ${locator}`);\n replicas.set(locator, replicaOf(confirmed, before.queue, rewriting(), before));\n }\n rooms.set(locator, {\n ...room,\n model: modelTypes(revoked),\n typedSelection:\n room.typedSelection === null\n ? null\n : { ...room.typedSelection, model: modelTypes(revoked) },\n });\n changed.push(changeSet(locator, before, replicas.get(locator) ?? null, { room: true }));\n }\n publishChangeSet(mergeChangeSets(changed));\n });\n }\n } finally {\n refusal = {\n reason,\n reauthorizationOffered: reason === 'revoked-authorization',\n refusal: provider,\n };\n journal.record(`connection refused ${reason}`);\n emitRefusal();\n }\n }\n\n function list(room: RoomDeclaration, synchronizationAvailable: boolean) {\n const selection = room.typedSelection ?? null;\n rooms.set(room.locator, {\n name: room.name,\n collectionRoot: room.collectionRoot,\n locator: room.locator,\n operations: room.operations,\n replica: room.replica,\n attachedModel: room.attachedModel,\n model: modelTypes(modelOf(room.locator)),\n typedSelection:\n selection === null\n ? null\n : {\n roots: selection.roots,\n attachedModel: selection.attachedModel,\n model: modelTypes(modelOf(room.locator, 'typed-selection')),\n },\n providerOwnedPaths: room.providerOwnedPaths,\n roomVersion: replicas.get(room.locator)?.confirmed.record.roomVersion ?? null,\n synchronizationAvailable,\n refusal: scopedRefusals.get(room.locator) ?? sourceRefusals.get(room.locator) ?? null,\n });\n }\n\n async function applyDiscovery(listed: readonly DiscoveredRoom[], local: RuntimeStore) {\n const listedLocators = new Set(listed.map((room) => room.locator));\n for (const locator of listedLocators) scopedRefusals.delete(locator);\n discovered.clear();\n for (const room of listed) discovered.set(room.locator, room);\n await dropUnlisted(listedLocators, local);\n for (const room of listed) {\n const held = replicas.get(room.locator)?.confirmed.record;\n if (held !== undefined && held.replica.selection !== room.replica.selection) {\n list(held, false);\n continue;\n }\n list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));\n }\n roomsListed = true;\n emitRooms();\n }\n\n function unlistedHeld(listed: ReadonlySet<string>): string[] {\n return [...new Set([...rooms.keys(), ...roomDrafts.keys()])].filter(\n (locator) => !listed.has(locator),\n );\n }\n\n async function dropUnlisted(listed: ReadonlySet<string>, local: RuntimeStore) {\n if (unlistedHeld(listed).length === 0) return;\n await exclusive(async () => {\n const unlisted = unlistedHeld(listed);\n await local.dropRooms(unlisted);\n for (const [batch, locator] of outcomeRooms) {\n if (listed.has(locator)) continue;\n outcomeRooms.delete(batch);\n outcomes.delete(batch);\n }\n const removed = unlisted.map((locator) =>\n changeSet(locator, replicas.get(locator) ?? null, null, {\n room: true,\n queue: true,\n drafts: [...(roomDrafts.get(locator)?.keys() ?? [])],\n }),\n );\n for (const locator of unlisted) {\n for (const batch of replicas.get(locator)?.queue ?? []) pendings.delete(batch.id);\n replicas.delete(locator);\n rooms.delete(locator);\n roomDrafts.delete(locator);\n unreadable.delete(locator);\n scopedRefusals.delete(locator);\n sourceRefusals.delete(locator);\n for (const attached of ['collection', 'typed-selection'] as const) {\n const key = modelKey(locator, attached);\n models.delete(key);\n liveModels.delete(key);\n invalidModels.delete(key);\n modelEpoch.delete(key);\n }\n journal.record(`room unlisted ${locator}`);\n }\n publishChangeSet(mergeChangeSets(removed));\n moveTo({ ...status, ...attention() });\n });\n }\n\n function restored(key: string, persisted: ModelState): ModelState {\n const prior = models.get(key);\n if (\n prior !== undefined &&\n prior.status !== 'unavailable' &&\n (persisted.status === 'unavailable' || !sameModel(prior.snapshot, persisted.snapshot))\n ) {\n modelEpoch.set(key, (modelEpoch.get(key) ?? 0) + 1);\n invalidModels.add(key);\n }\n const model =\n persisted.status === 'unavailable' ||\n liveModels.get(key) === JSON.stringify(persisted.snapshot)\n ? persisted\n : cached(persisted);\n models.set(key, model);\n if (model.status === 'unavailable') {\n liveModels.delete(key);\n invalidModels.delete(key);\n }\n return model;\n }\n\n async function hydrate(opened: RuntimeStore): Promise<{\n lastCompleted: string | null;\n locators: Set<string>;\n read: ChangeSet;\n }> {\n const [\n records,\n queues,\n recordedOutcomes,\n kept,\n presented,\n held,\n chatDrafts,\n lastCompleted,\n declared,\n named,\n listedSlots,\n ] = await Promise.all([\n opened.all(),\n opened.queues(),\n opened.outcomes(),\n opened.roomDrafts(),\n opened.presentation(),\n opened.conversations(),\n opened.chatDrafts(),\n opened.lastCompleted(),\n opened.providerLimits(),\n opened.capabilities(),\n opened.slots(),\n ]);\n limits = declared;\n capabilities = named;\n slots = listedSlots;\n roomDrafts.clear();\n for (const record of kept) rememberRoomDraft(record);\n presentations.clear();\n for (const record of presented) presentations.set(record.app, record.value);\n conversations.hydrate(held, chatDrafts);\n const queuedBatches = new Map(\n queues.map((queue) => [queue.locator, queue.pending.map(({ batch }) => batch)]),\n );\n pendings.clear();\n for (const queue of queues) {\n for (const { batch, state } of queue.pending) pendings.set(batch.id, state);\n }\n outcomes.clear();\n outcomeRooms.clear();\n for (const record of recordedOutcomes) {\n outcomes.set(record.id, record.outcome);\n outcomeRooms.set(record.id, record.locator);\n }\n const previousReplicas = new Map(replicas);\n replicas.clear();\n for (const record of records) {\n const model = restored(modelKey(record.locator, 'collection'), record.model);\n const selectionModel = restored(\n modelKey(record.locator, 'typed-selection'),\n record.selectionModel,\n );\n const prior = previousReplicas.get(record.locator);\n const confirmed = readConfirmed({ ...record, model, selectionModel }, prior?.confirmed);\n if (confirmed === null) continue;\n replicas.set(\n record.locator,\n replicaOf(confirmed, queuedBatches.get(record.locator) ?? [], rewriting(), prior),\n );\n const existing = rooms.get(record.locator);\n if (existing === undefined) list(record, false);\n else {\n rooms.set(record.locator, {\n ...existing,\n roomVersion: record.roomVersion,\n operations: record.operations,\n replica: record.replica,\n attachedModel: record.attachedModel,\n model: modelTypes(model),\n typedSelection:\n record.typedSelection === null\n ? null\n : {\n roots: record.typedSelection.roots,\n attachedModel: record.typedSelection.attachedModel,\n model: modelTypes(selectionModel),\n },\n });\n }\n }\n return {\n lastCompleted,\n locators: new Set([...queuedBatches.keys(), ...replicas.keys()]),\n read: mergeChangeSets(\n [...new Set([...previousReplicas.keys(), ...replicas.keys()])].map((locator) =>\n changeSet(locator, previousReplicas.get(locator) ?? null, replicas.get(locator) ?? null),\n ),\n ),\n };\n }\n\n async function readState(opened: RuntimeStore): Promise<string | null> {\n const { lastCompleted, locators, read } = await hydrate(opened);\n applyChangeSet(read);\n if (replicas.size > 0) emitRooms();\n for (const locator of locators) emitQueue(locator);\n publishRoomDrafts(false);\n return lastCompleted;\n }\n\n async function open(): Promise<RuntimeStore> {\n const opened = await openRuntimeStore();\n store = opened;\n const kept = options.shell.generation;\n const storedGeneration = await opened.generation();\n const loss = detectStorageLoss(storedGeneration, kept);\n const generation = nextGeneration(storedGeneration, kept);\n if (generation !== storedGeneration) await opened.rememberGeneration(generation);\n if (generation !== kept) await options.shell.keepGeneration(generation);\n if (loss !== null) {\n storageLoss = loss;\n emitStorageLoss();\n }\n const lastCompleted = await readState(opened);\n moveTo({ ...status, lastCompleted, ...attention() });\n return opened;\n }\n\n function durably<T>(work: (local: RuntimeStore) => Promise<T>): Promise<T> {\n return exclusive(async () => {\n const local = await openLocal();\n return work(local);\n });\n }\n\n function openLocal(): Promise<RuntimeStore> {\n opening ??= open().catch((error: unknown) => {\n opening = undefined;\n throw error;\n });\n return opening;\n }\n\n function exclusive<T>(work: () => Promise<T>): Promise<T> {\n const next = mutations.then(work, work);\n mutations = next.then(\n () => undefined,\n () => undefined,\n );\n return next;\n }\n\n function withdrawable(batch: ChangeBatch): boolean {\n const state = pendings.get(batch.id);\n return state !== undefined && state.submission.state !== 'submitted' && !state.lost;\n }\n\n async function settle(\n local: RuntimeStore,\n locator: string,\n before: Replica | undefined,\n confirmed: ConfirmedLayer,\n queue: readonly ChangeBatch[],\n settling: {\n accepted?: { id: string; outcome: SubmissionOutcome };\n leaving?: Leaving;\n room?: boolean;\n } = {},\n ): Promise<ChangeSet> {\n const withdrawn = withdrawals(confirmed, queue, withdrawable, rewriting());\n const kept = queue.filter((batch) => !withdrawn.includes(batch));\n const returning = [\n ...withdrawn.map((batch) => ({ batch, returned: { kind: 'withdrawn' } as const })).reverse(),\n ...(settling.leaving === undefined ? [] : [settling.leaving]),\n ];\n const written = new Map<string, RoomDraftRecord>();\n for (const { batch, returned } of returning) {\n for (const saved of pendings.get(batch.id)?.drafts ?? []) {\n const existing = written.get(saved.path) ?? roomDrafts.get(locator)?.get(saved.path);\n written.set(saved.path, {\n locator,\n path: saved.path,\n revision: roomDraftRevision(),\n parts: returnedInto(existing?.parts, saved.parts),\n returned,\n });\n }\n }\n const settledOutcomes: { id: string; outcome: SubmissionOutcome }[] = [\n ...(settling.accepted === undefined ? [] : [settling.accepted]),\n ...(settling.leaving === undefined\n ? []\n : [{ id: settling.leaving.batch.id, outcome: settling.leaving.outcome }]),\n ...withdrawn.map((batch) => ({ id: batch.id, outcome: { kind: 'withdrawn' as const } })),\n ];\n await local.write({\n next: confirmed.record,\n previous: before?.confirmed.record ?? null,\n queue: kept,\n previousQueue: before?.queue ?? [],\n outcomes: settledOutcomes,\n roomDrafts: [...written.values()],\n });\n for (const { id, outcome } of settledOutcomes) {\n outcomes.set(id, outcome);\n outcomeRooms.set(id, locator);\n pendings.delete(id);\n }\n for (const record of written.values()) rememberRoomDraft(record);\n for (const batch of withdrawn) journal.record(`outcome ${locator} ${batch.id} withdrawn`);\n replicas.set(locator, replicaOf(confirmed, kept, rewriting(), before));\n return changeSet(locator, before ?? null, replicas.get(locator) ?? null, {\n room: settling.room,\n queue: kept.length !== (before?.queue.length ?? 0),\n drafts: [...written.keys()],\n });\n }\n\n function publish(local: RuntimeStore, room: DiscoveredRoom, confirmed: ConfirmedLayer) {\n return exclusive(async () => {\n const prior = replicas.get(room.locator);\n const retained = readConfirmed(\n {\n ...confirmed.record,\n model: modelOf(room.locator),\n selectionModel: modelOf(room.locator, 'typed-selection'),\n },\n prior?.confirmed,\n );\n if (retained === null) {\n list(room, true);\n publishChangeSet(changeSet(room.locator, prior ?? null, prior ?? null, { room: true }));\n return;\n }\n const set = await settle(local, room.locator, prior, retained, prior?.queue ?? [], {\n room: true,\n });\n unreadable.delete(room.locator);\n sourceRefusals.delete(room.locator);\n list(room, true);\n publishChangeSet(set);\n moveTo({ ...status, ...attention() });\n });\n }\n\n async function saveRoomDrafts(\n locator: string,\n named: readonly SavedRoomDraft[],\n writtenBy: WrittenBy | undefined,\n ): Promise<SaveResult> {\n const local = await openLocal();\n const replica = replicas.get(locator);\n const room = rooms.get(locator);\n if (replica === undefined || room === undefined) {\n throw new Error(`No Local Replica for ${locator}`);\n }\n if (mismatchedRoots.has(locator))\n return { outcome: 'refused', rule: 'collection-root-mismatch' };\n const saved: SavedDraft[] = [];\n for (const { path, revision } of named) {\n const record = roomDrafts.get(locator)?.get(path);\n if (record === undefined || record.revision !== revision) {\n return { outcome: 'refused', rule: 'stale', file: path };\n }\n if (!saved.some((draft) => draft.path === path)) saved.push({ path, parts: record.parts });\n }\n const changed = saved.flatMap(({ path, parts }) =>\n changedParts(path, underneath(parts, path, replica.visible)),\n );\n if (changed.length > 0)\n return { outcome: 'refused', rule: 'changed-underneath', parts: changed };\n const parts = saved.map(({ path, parts }) => changesOf(path, parts));\n const built = buildBatch({\n baseRoomVersion: replica.confirmed.record.roomVersion,\n composition: compositionFor(replica.confirmed.record),\n operations: room.operations,\n providerOwnedPaths: room.providerOwnedPaths,\n providerLimits: limits,\n rewriting: rewriting(),\n visible: replica.visible,\n changes: parts.flatMap(({ changes }) => changes),\n bases: parts.flatMap(({ bases }) => bases),\n writtenBy,\n });\n if (built.kind === 'refused') return { outcome: 'refused', ...built.refusal };\n const batches = [...replica.queue, built.batch];\n const consumed = saved.map(({ path }) => path);\n try {\n await local.write({\n next: replica.confirmed.record,\n previous: replica.confirmed.record,\n queue: batches,\n previousQueue: replica.queue,\n saved,\n consumedRoomDrafts: consumed,\n });\n } catch {\n return { outcome: 'refused', rule: 'durable-write' };\n }\n pendings.set(built.batch.id, { drafts: saved, submission: { state: 'waiting' }, lost: false });\n for (const path of consumed) forgetRoomDraft(locator, path);\n replicas.set(locator, replicaOf(replica.confirmed, batches, rewriting(), replica));\n publishChangeSet(\n changeSet(locator, replica, replicas.get(locator) ?? null, {\n queue: true,\n drafts: consumed,\n }),\n );\n moveTo({ ...saving(status), ...attention() });\n void enqueue();\n return { outcome: 'saved', identifier: built.batch.id };\n }\n\n async function mark(\n local: RuntimeStore,\n locator: string,\n identifier: string,\n submission: Submission,\n lost: boolean,\n ) {\n const state = pendings.get(identifier);\n if (\n state === undefined ||\n (JSON.stringify(state.submission) === JSON.stringify(submission) && state.lost === lost)\n ) {\n return;\n }\n await local.submit(locator, identifier, submission, lost);\n pendings.set(identifier, { ...state, submission, lost });\n const replica = replicas.get(locator);\n if (replica !== undefined)\n publishChangeSet(changeSet(locator, replica, replica, { queue: true }));\n moveTo({ ...status, ...attention() });\n }\n\n async function readHistory(\n locator: string,\n path: string,\n query: HistoryQuery = {},\n ): Promise<HistoryResult> {\n if (closed || refusal !== null) return { kind: 'transport-uncertainty' };\n try {\n await ensureAuthorization();\n } catch {\n return { kind: 'transport-uncertainty' };\n }\n if (closed || authorization === undefined || refusal !== null) {\n return { kind: 'transport-uncertainty' };\n }\n const transfer = ['transfer', 'history', locator, path];\n if (query.revision !== undefined) transfer.push(query.revision);\n if (query.pageToken !== undefined) transfer.push(query.pageToken);\n journal.record(transfer.join(' '));\n try {\n const result = await options.adapter.history(authorization, {\n locator,\n path,\n ...(query.revision === undefined ? {} : { revision: query.revision }),\n ...(query.pageToken === undefined ? {} : { pageToken: query.pageToken }),\n });\n journal.record(`outcome history ${result.kind}`);\n if (result.kind === 'scoped-refusal') {\n const room = replicas.get(result.locator)?.confirmed.record;\n if (room !== undefined) await scoped(result, room, await openLocal());\n }\n if (result.kind === 'revoked-authorization') await refuse('revoked-authorization');\n return result;\n } catch {\n journal.record('outcome history transport-uncertainty');\n return { kind: 'transport-uncertainty' };\n }\n }\n\n function declaredCards(): ConversationCards | undefined {\n for (const capability of capabilities) {\n if (capability.conversationCards !== undefined) return capability.conversationCards;\n }\n return undefined;\n }\n\n function declaredAction(name: string) {\n for (const capability of capabilities) {\n for (const action of capability.actions ?? []) {\n if (action.name === name) return action;\n }\n }\n return undefined;\n }\n\n async function invokeAction(name: string, input: unknown): Promise<CallResult> {\n await ready;\n if (closed || refusal !== null) return { kind: 'transport-uncertainty' };\n if (declaredAction(name) === undefined) return { kind: 'undeclared' };\n try {\n await ensureAuthorization();\n } catch {\n return { kind: 'transport-uncertainty' };\n }\n if (closed || authorization === undefined || refusal !== null) {\n return { kind: 'transport-uncertainty' };\n }\n journal.record(`transfer action ${name}`);\n try {\n const result = await options.adapter.action(authorization, { name, input });\n if (result.kind === 'scoped-refusal') {\n const room = replicas.get(result.locator)?.confirmed.record;\n if (room !== undefined) await scoped(result, room, await openLocal());\n }\n if (result.kind === 'revoked-authorization') await refuse('revoked-authorization');\n journal.record(`outcome action ${result.kind}`);\n if (result.kind === 'rejected') journal.record(`refusal rejected ${result.code}`);\n return result;\n } catch {\n journal.record('outcome action transport-uncertainty');\n return { kind: 'transport-uncertainty' };\n }\n }\n\n async function pullRefresh(authorized: Authorization, confirmed: ConfirmedLayer) {\n try {\n const result = await refreshRoom(options.adapter, authorized, confirmed);\n const detail = result.kind === 'advanced' ? result.confirmed.record.roomVersion : result.kind;\n journal.record(`transfer refresh ${confirmed.record.locator} ${detail}`);\n return result;\n } catch (error) {\n journal.record(`transfer refresh ${confirmed.record.locator} transport-uncertainty`);\n throw error;\n }\n }\n\n async function pullBootstrap(authorized: Authorization, room: DiscoveredRoom) {\n try {\n const result = await bootstrapRoom(options.adapter, authorized, room, {\n collection: modelOf(room.locator),\n selection: modelOf(room.locator, 'typed-selection'),\n });\n const detail = result.kind === 'staged' ? result.confirmed.record.roomVersion : result.kind;\n journal.record(`transfer bootstrap ${room.locator} ${detail}`);\n return result;\n } catch (error) {\n journal.record(`transfer bootstrap ${room.locator} transport-uncertainty`);\n throw error;\n }\n }\n\n async function advance(\n room: DiscoveredRoom,\n local: RuntimeStore,\n authorized: Authorization,\n ): Promise<Withheld | null> {\n const held = replicas.get(room.locator);\n if (held !== undefined) {\n const refreshed = await pullRefresh(authorized, held.confirmed);\n if (refreshed.kind === 'still-current') {\n sourceRefusals.delete(room.locator);\n if (unreadable.delete(room.locator)) {\n list(room, true);\n emitRooms();\n }\n return null;\n }\n if (refreshed.kind === 'advanced') {\n if (closed) return unconfirmed;\n await publish(local, room, refreshed.confirmed);\n return null;\n }\n if (refreshed.kind !== 'beyond-horizon') return refreshed;\n }\n const bootstrapped = await pullBootstrap(authorized, room);\n if (bootstrapped.kind !== 'staged') return bootstrapped;\n if (closed) return unconfirmed;\n await publish(local, room, bootstrapped.confirmed);\n return null;\n }\n\n async function withhold(\n withheld: Withheld,\n room: DiscoveredRoom,\n local: RuntimeStore,\n progress: CycleProgress,\n ): Promise<'stop' | null> {\n progress.complete = false;\n if (withheld.kind === 'scoped-refusal') {\n await scoped(withheld, room, local);\n } else if (withheld.kind === 'transport-uncertainty') {\n progress.reachable = false;\n } else if (withheld.kind === 'room-not-readable') {\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n } else if (withheld.kind === 'refused') {\n refusedSource(room, withheld);\n } else if (withheld.kind === 'revoked-authorization') {\n await refuse('revoked-authorization');\n return 'stop';\n }\n return null;\n }\n\n function refusedSource(room: DiscoveredRoom, { refusal }: Refused) {\n sourceRefusals.set(room.locator, {\n code: refusal.rule,\n fields: {\n file: refusal.file,\n ...(refusal.location === undefined ? {} : { location: refusal.location }),\n version: refusal.version,\n ...(refusal.referrers === undefined ? {} : { referrers: refusal.referrers }),\n },\n });\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n journal.record(`source refused ${room.locator} ${refusal.rule} ${refusal.file}`);\n }\n\n function leaving(\n batch: ChangeBatch,\n result: Extract<MutationResult, { kind: 'conflicted' | 'rejected' | 'expired' }>,\n ): Leaving {\n if (result.kind === 'expired') {\n return { batch, outcome: { kind: 'expired' }, returned: { kind: 'expired' } };\n }\n const refusal = { code: result.code, fields: result.fields };\n if (result.kind === 'conflicted') {\n return {\n batch,\n outcome: {\n kind: 'conflicted',\n ...(result.roomVersion === undefined ? {} : { roomVersion: result.roomVersion }),\n affected: result.affected,\n ...refusal,\n },\n returned: { kind: 'conflicted', ...refusal },\n };\n }\n return {\n batch,\n outcome: { kind: 'rejected', affected: result.affected, ...refusal },\n returned: { kind: 'rejected', ...refusal },\n };\n }\n\n async function commitAccept(\n room: DiscoveredRoom,\n local: RuntimeStore,\n submitted: ChangeBatch,\n accepted: Extract<MutationResult, { kind: 'accepted' }>,\n base: ConfirmedLayer,\n overlay: boolean,\n ): Promise<boolean> {\n const current = replicas.get(room.locator);\n if (current === undefined || !current.queue.some((batch) => batch.id === submitted.id)) {\n return true;\n }\n const remaining = current.queue.filter((batch) => batch.id !== submitted.id);\n const retainedBase = readConfirmed(\n {\n ...base.record,\n model: modelOf(room.locator),\n selectionModel: modelOf(room.locator, 'typed-selection'),\n },\n base,\n );\n if (retainedBase === null) return false;\n let applied = retainedBase;\n if (overlay) {\n const returned = applyReturned(\n retainedBase,\n accepted.documents,\n accepted.revisions,\n accepted.removals,\n accepted.roomVersion,\n );\n if (returned.kind === 'refused') refusedSource(room, returned);\n if (returned.kind !== 'staged') return false;\n applied = returned.confirmed;\n }\n const acceptedOutcome: SubmissionOutcome = {\n kind: 'accepted',\n roomVersion: accepted.roomVersion,\n ...(accepted.author === undefined ? {} : { author: accepted.author }),\n ...(accepted.time === undefined ? {} : { time: accepted.time }),\n };\n const set = await settle(local, room.locator, current, applied, remaining, {\n accepted: { id: submitted.id, outcome: acceptedOutcome },\n room: true,\n });\n unreadable.delete(room.locator);\n sourceRefusals.delete(room.locator);\n list(room, true);\n publishChangeSet(set);\n moveTo({ ...status, ...attention() });\n journal.record(\n `outcome ${room.locator} ${submitted.id} accepted ${accepted.roomVersion}` +\n (accepted.author === undefined ? '' : ` author ${accepted.author}`) +\n (accepted.time === undefined ? '' : ` time ${accepted.time}`),\n );\n return true;\n }\n\n async function submitRoom(\n room: DiscoveredRoom,\n local: RuntimeStore,\n authorized: Authorization,\n progress: CycleProgress,\n ): Promise<'stop' | null> {\n while (!closed && authorization !== undefined) {\n const replica = replicas.get(room.locator);\n const head = replica?.queue[0];\n if (replica === undefined || head === undefined) return null;\n const { submission, lost: earlier } = pendings.get(head.id) ?? {\n submission: { state: 'waiting' },\n lost: false,\n };\n if (submission.state === 'reset' && Date.now() < Date.parse(submission.reset)) {\n progress.complete = false;\n return null;\n }\n const lost = earlier || submission.state === 'submitted';\n let result: MutationResult;\n journal.record(`submission ${room.locator} ${head.id}`);\n await exclusive(() => mark(local, room.locator, head.id, { state: 'submitted' }, lost));\n try {\n result = await options.adapter.mutate(authorized, {\n locator: room.locator,\n changeBatch: head,\n });\n } catch {\n progress.complete = false;\n progress.reachable = false;\n return null;\n }\n if (closed) return null;\n if (result.kind === 'transport-uncertainty') {\n progress.complete = false;\n progress.reachable = false;\n return null;\n }\n if (result.kind === 'room-not-readable') {\n progress.complete = false;\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n return null;\n }\n if (result.kind === 'revoked-authorization') {\n await refuse('revoked-authorization');\n return 'stop';\n }\n if (result.kind === 'scoped-refusal') {\n await scoped(result, room, local);\n progress.complete = false;\n return null;\n }\n if (\n result.kind === 'conflicted' ||\n result.kind === 'rejected' ||\n result.kind === 'expired' ||\n result.kind === 'retryable-refusal'\n ) {\n journal.record(\n `outcome ${room.locator} ${head.id} ${result.kind}` +\n (result.kind === 'conflicted' && result.roomVersion !== undefined\n ? ` ${result.roomVersion}`\n : ''),\n );\n if (result.kind !== 'expired') journal.record(`refusal ${result.kind} ${result.code}`);\n }\n if (result.kind === 'retryable-refusal') {\n const reset = result.reset;\n progress.complete = false;\n await exclusive(() =>\n mark(\n local,\n room.locator,\n head.id,\n reset === undefined ? { state: 'waiting' } : { state: 'reset', reset },\n lost,\n ),\n );\n return null;\n }\n if (result.kind === 'conflicted' || result.kind === 'rejected' || result.kind === 'expired') {\n const left = leaving(head, result);\n await exclusive(async () => {\n const current = replicas.get(room.locator);\n if (current === undefined || !current.queue.some((batch) => batch.id === head.id)) {\n return;\n }\n const set = await settle(\n local,\n room.locator,\n current,\n current.confirmed,\n current.queue.filter((batch) => batch.id !== head.id),\n { leaving: left },\n );\n publishChangeSet(set);\n moveTo({ ...status, ...attention() });\n });\n const withheld = await advance(room, local, authorized);\n if (withheld !== null) return withhold(withheld, room, local, progress);\n continue;\n }\n const from = replicas.get(room.locator)?.confirmed;\n if (from === undefined) return null;\n const pulled = await pullRefresh(authorized, from);\n if (pulled.kind === 'revoked-authorization') {\n await refuse('revoked-authorization');\n return 'stop';\n }\n if (pulled.kind === 'scoped-refusal') {\n await scoped(pulled, room, local);\n progress.complete = false;\n return null;\n }\n if (pulled.kind === 'still-current') {\n const committed = await exclusive(() =>\n commitAccept(room, local, head, result, from, true),\n );\n if (!committed) {\n progress.complete = false;\n return null;\n }\n continue;\n }\n if (pulled.kind === 'advanced') {\n const overlay = pulled.confirmed.record.roomVersion === result.roomVersion;\n const committed = await exclusive(() =>\n commitAccept(room, local, head, result, pulled.confirmed, overlay),\n );\n if (!committed) {\n progress.complete = false;\n return null;\n }\n continue;\n }\n if (pulled.kind === 'beyond-horizon') {\n const bootstrapped = await pullBootstrap(authorized, room);\n if (bootstrapped.kind === 'revoked-authorization') {\n await refuse('revoked-authorization');\n return 'stop';\n }\n if (bootstrapped.kind === 'scoped-refusal') {\n await scoped(bootstrapped, room, local);\n progress.complete = false;\n return null;\n }\n if (bootstrapped.kind === 'staged') {\n const overlay = bootstrapped.confirmed.record.roomVersion === result.roomVersion;\n const committed = await exclusive(() =>\n commitAccept(room, local, head, result, bootstrapped.confirmed, overlay),\n );\n if (!committed) {\n progress.complete = false;\n return null;\n }\n continue;\n }\n progress.complete = false;\n if (bootstrapped.kind === 'transport-uncertainty') {\n progress.reachable = false;\n } else if (bootstrapped.kind === 'room-not-readable') {\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n } else if (bootstrapped.kind === 'refused') {\n refusedSource(room, bootstrapped);\n }\n return null;\n }\n progress.complete = false;\n if (pulled.kind === 'transport-uncertainty') {\n progress.reachable = false;\n } else if (pulled.kind === 'room-not-readable') {\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n } else if (pulled.kind === 'refused') {\n refusedSource(room, pulled);\n }\n return null;\n }\n return null;\n }\n\n async function retainModel(\n local: RuntimeStore,\n room: RoomDeclaration,\n attached: Attached,\n next: ModelState,\n ) {\n const key = modelKey(room.locator, attached);\n if (next.status === 'unavailable') modelEpoch.set(key, (modelEpoch.get(key) ?? 0) + 1);\n const epoch = modelEpoch.get(key) ?? 0;\n const previous = modelOf(room.locator, attached);\n const heldBefore = replicas.get(room.locator)?.confirmed.record;\n if (\n JSON.stringify(previous) === JSON.stringify(next) &&\n (heldBefore === undefined ||\n (JSON.stringify(heldBefore.operations) === JSON.stringify(room.operations) &&\n JSON.stringify(heldBefore.replica) === JSON.stringify(room.replica) &&\n JSON.stringify(heldBefore.attachedModel) === JSON.stringify(room.attachedModel) &&\n JSON.stringify(heldBefore.typedSelection) ===\n JSON.stringify(room.typedSelection ?? null)))\n )\n return;\n if (next.status === 'unavailable') {\n invalidModels.add(key);\n liveModels.delete(key);\n }\n await exclusive(async () => {\n if (next.status !== 'unavailable' && epoch !== (modelEpoch.get(key) ?? 0)) return;\n const held = replicas.get(room.locator);\n if (held !== undefined) {\n const record = {\n ...held.confirmed.record,\n operations: room.operations,\n replica: room.replica,\n attachedModel: room.attachedModel,\n typedSelection: room.typedSelection ?? null,\n ...(attached === 'collection' ? { model: next } : { selectionModel: next }),\n };\n await local.write({\n next: record,\n previous: held.confirmed.record,\n queue: held.queue,\n });\n const confirmed = readConfirmed(record, held.confirmed);\n if (confirmed !== null) {\n replicas.set(room.locator, replicaOf(confirmed, held.queue, rewriting(), held));\n }\n }\n models.set(key, next);\n if (next.status === 'current') {\n liveModels.set(key, JSON.stringify(next.snapshot));\n invalidModels.delete(key);\n }\n list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));\n if (held === undefined) emitRooms();\n else\n publishChangeSet(\n changeSet(room.locator, held, replicas.get(room.locator) ?? null, { room: true }),\n );\n });\n }\n\n async function acquireModel(\n local: RuntimeStore,\n room: DiscoveredRoom,\n authorized: Authorization,\n selection: TypedSelection | null,\n ) {\n const attached: Attached = selection === null ? 'collection' : 'typed-selection';\n const key = modelKey(room.locator, attached);\n const declared = selection === null ? room.attachedModel : selection.attachedModel;\n let previous = modelOf(room.locator, attached);\n if (\n previous.status !== 'unavailable' &&\n (declared === null || !sameModel(previous.snapshot, declared))\n ) {\n previous = { status: 'unavailable', reason: 'version-changed' };\n await retainModel(local, room, attached, previous);\n }\n const epoch = modelEpoch.get(key) ?? 0;\n let answer;\n try {\n answer = await options.adapter.model(\n authorized,\n selection === null\n ? {\n locator: room.locator,\n attached: 'collection',\n collectionRoot: room.collectionRoot,\n model: declared,\n }\n : {\n locator: room.locator,\n attached: 'typed-selection',\n roots: selection.roots,\n model: declared,\n },\n );\n } catch {\n answer = { kind: 'transport-uncertainty' as const };\n }\n if (epoch !== (modelEpoch.get(key) ?? 0)) return;\n if (answer.kind === 'revoked-authorization') {\n await refuse('revoked-authorization');\n return;\n }\n if (answer.kind === 'transport-uncertainty') {\n await retainModel(local, room, attached, cached(previous));\n return;\n }\n if (answer.kind === 'model-unavailable') {\n await retainModel(local, room, attached, {\n status: 'unavailable',\n reason: answer.reason,\n });\n return;\n }\n if (declared === null || !sameModel(answer.snapshot, declared)) {\n await retainModel(local, room, attached, {\n status: 'unavailable',\n reason: 'version-changed',\n });\n return;\n }\n if (\n previous.status !== 'unavailable' &&\n sameModel(previous.snapshot, answer.snapshot) &&\n JSON.stringify(Object.entries(previous.snapshot.definitions).sort()) !==\n JSON.stringify(Object.entries(answer.snapshot.definitions).sort())\n ) {\n await retainModel(local, room, attached, { status: 'unavailable', reason: 'invalid' });\n return;\n }\n const verified = verify(answer.snapshot.definitions);\n if (verified.verdict === 'refuse')\n journal.record(`model invalid ${room.locator} ${attached} ${verified.rule} ${verified.file}`);\n await retainModel(\n local,\n room,\n attached,\n verified.verdict === 'accept'\n ? {\n status: 'current',\n snapshot: structuredClone(answer.snapshot),\n verifiedWith: MD_MODEL,\n types: verified.model.types,\n }\n : { status: 'unavailable', reason: 'invalid' },\n );\n }\n\n async function scoped(\n result: import('./adapter.js').ScopedRefusal,\n room: RoomDeclaration,\n local: RuntimeStore,\n ) {\n scopedRefusals.set(room.locator, { code: result.code, fields: result.fields });\n let scopedAway = room;\n if (result.scope === 'model')\n await retainModel(local, room, 'collection', {\n status: 'unavailable',\n reason: 'not-readable',\n });\n else if (result.scope !== 'operation') {\n unreadable.add(room.locator);\n scopedAway = {\n ...room,\n replica: { ...room.replica, admission: 'unavailable' },\n operations: {\n ...room.operations,\n ...(result.scope === 'content' ? { read: [] } : {}),\n ...(result.scope === 'sync' ? { sync: [] } : {}),\n },\n };\n await retainModel(local, scopedAway, 'collection', modelOf(room.locator));\n }\n list(scopedAway, scopedAway.replica.admission === 'admitted' && !unreadable.has(room.locator));\n emitRooms();\n journal.record(`scoped refusal ${room.locator} ${result.scope} ${result.code}`);\n }\n\n async function synchronize(\n discovered: readonly DiscoveredRoom[],\n local: RuntimeStore,\n progress: CycleProgress,\n ) {\n for (const room of discovered) {\n if (closed || authorization === undefined) {\n progress.complete = false;\n return;\n }\n const prior = replicas.get(room.locator)?.confirmed.record;\n if (prior !== undefined && prior.replica.selection !== room.replica.selection) {\n list(prior, false);\n emitRooms();\n journal.record(`selection changed ${room.locator}`);\n progress.complete = false;\n continue;\n }\n await acquireModel(local, room, authorization, null);\n if (discoveryPaused) return;\n if (room.typedSelection !== undefined) {\n await acquireModel(local, room, authorization, room.typedSelection);\n if (discoveryPaused) return;\n }\n if (room.replica.admission !== 'admitted') {\n progress.complete = false;\n continue;\n }\n const held = replicas.get(room.locator);\n if (\n held !== undefined &&\n held.confirmed.record.replica.selection !== room.replica.selection\n ) {\n progress.complete = false;\n continue;\n }\n const withheld = await advance(room, local, authorization);\n if (withheld !== null) {\n if ((await withhold(withheld, room, local, progress)) === 'stop') return;\n continue;\n }\n if ((await submitRoom(room, local, authorization, progress)) === 'stop') return;\n }\n }\n\n async function cycle(local: RuntimeStore, progress: CycleProgress) {\n if (closed || authorization === undefined) {\n notifyReady();\n return;\n }\n moveTo(transferring(status));\n let result;\n try {\n result = await options.adapter.discover(authorization);\n } catch {\n result = { kind: 'transport-uncertainty' as const };\n }\n if (closed) {\n notifyReady();\n return;\n }\n journal.record(`connection discover ${result.kind}`);\n if (result.kind === 'transport-uncertainty') {\n for (const room of rooms.values()) {\n await retainModel(local, room, 'collection', cached(modelOf(room.locator)));\n if (room.typedSelection !== null) {\n await retainModel(\n local,\n room,\n 'typed-selection',\n cached(modelOf(room.locator, 'typed-selection')),\n );\n }\n }\n progress.reachable = false;\n notifyReady();\n return;\n }\n if (result.kind === 'contract-unavailable') {\n journal.record(`connection contract unavailable ${result.code}`);\n await refuse('missing-required-guarantee', { code: result.code, fields: result.fields });\n notifyReady();\n return;\n }\n if (result.kind === 'revoked-authorization') {\n await refuse('revoked-authorization');\n notifyReady();\n return;\n }\n if (!result.supportedVersions.includes(ROOM_CONTRACT_VERSION)) {\n await refuse('no-matching-version');\n notifyReady();\n return;\n }\n if (\n result.mdModel.identity !== MD_MODEL.identity ||\n result.mdModel.version !== MD_MODEL.version\n ) {\n await refuse('md-model-version-mismatch');\n notifyReady();\n return;\n }\n mismatchedRoots.clear();\n for (const room of result.rooms) {\n const held = replicas.get(room.locator)?.confirmed.record;\n const malformed = !validRoot(room.collectionRoot);\n if (\n room.operations === undefined ||\n !['read', 'sync', 'write', 'delete'].every(\n (operation) =>\n Array.isArray(room.operations[operation as keyof typeof room.operations]) &&\n room.operations[operation as keyof typeof room.operations].every(\n (scope) => typeof scope === 'string',\n ),\n ) ||\n room.replica === undefined ||\n typeof room.replica.selection !== 'string' ||\n room.replica.selection.length === 0 ||\n !['admitted', 'unavailable'].includes(room.replica.admission) ||\n !declaredIdentity(room.attachedModel)\n ) {\n journal.record(`invalid model or replica declaration ${room.locator}`);\n await refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n if (!declaredSelection(room)) {\n journal.record(`invalid typed selection declaration ${room.locator}`);\n await refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n if (malformed || (held !== undefined && held.collectionRoot !== room.collectionRoot)) {\n mismatchedRoots.add(room.locator);\n journal.record(`collection root ${malformed ? 'invalid' : 'changed'} ${room.locator}`);\n }\n }\n if (mismatchedRoots.size > 0) {\n await refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n const declared = new Set(result.capabilities.map((capability) => capability.name));\n for (const required of options.requiredGuarantees) {\n if (!knownCapabilities.has(required) || !declared.has(required)) {\n await refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n }\n if (refusal !== null) {\n refusal = null;\n emitRefusal();\n }\n const previousCapabilities = capabilities;\n capabilities = result.capabilities;\n notifyReady();\n if (declared.has('room-version-notifications')) observeRoomVersions();\n if (declared.has('provider-actions')) observeConversations();\n const discoveredSlots = result.slots ?? [];\n if (\n JSON.stringify(result.providerLimits) !== JSON.stringify(limits) ||\n JSON.stringify(result.capabilities) !== JSON.stringify(previousCapabilities) ||\n JSON.stringify(discoveredSlots) !== JSON.stringify(slots)\n ) {\n limits = result.providerLimits;\n slots = discoveredSlots;\n await local.declare(limits, capabilities, slots);\n }\n await applyDiscovery(result.rooms, local);\n handSelected(\n result.rooms\n .filter((room) => room.replica.admission === 'admitted')\n .map((room) => room.locator)\n .sort(),\n );\n progress.complete = true;\n await synchronize(result.rooms, local, progress);\n if (closed || discoveryPaused) return;\n await conversations.reconcile();\n if (status.providerUnreachable) conversations.reconnected();\n await conversations.catchUp(progress);\n }\n\n async function ensureAuthorization() {\n if (authorization !== undefined) return;\n try {\n authorization = await options.adapter.authorize();\n journal.record('connection authorize');\n } catch (error) {\n journal.record('connection authorize transport-uncertainty');\n throw error;\n }\n }\n\n async function connect() {\n if (closed || discoveryPaused) {\n notifyReady();\n return;\n }\n startTimer();\n const progress: CycleProgress = { complete: false, reachable: true };\n let completedAt = new Date().toISOString();\n try {\n const local = await openLocal();\n if (closed) return;\n await ensureAuthorization();\n if (closed) return;\n await cycle(local, progress);\n if (closed) return;\n if (progress.complete) {\n completedAt = new Date().toISOString();\n await local.complete(completedAt);\n }\n } catch {\n progress.complete = false;\n notifyReady();\n return;\n } finally {\n notifyReady();\n moveTo(settled(status, progress, completedAt, pending(), attention()));\n }\n }\n\n async function run() {\n try {\n await connect();\n } finally {\n inflight = false;\n if (queued && !closed) {\n queued = false;\n void enqueue();\n }\n }\n }\n\n function observeRoomVersions() {\n const path = options.adapter.roomVersions;\n if (path === undefined || withdrawNotifications !== undefined) return;\n withdrawNotifications = path.observe((notification) => {\n if (closed || discoveryPaused) return;\n notices.set(notification.locator, notification.roomVersion);\n chain = chain.then(runNotified, runNotified);\n });\n }\n\n function observeConversations() {\n const stream = options.adapter.conversations;\n if (stream === undefined || withdrawConversations !== undefined) return;\n withdrawConversations = stream.observe((event) => {\n conversations.receive(event);\n if (event.kind !== 'gap' || conversations.current()) return;\n show();\n scheduleCurrency();\n });\n }\n\n function scheduleCurrency() {\n if (currencyQueued || closed) return;\n currencyQueued = true;\n chain = chain.then(runCurrency, runCurrency);\n }\n\n async function runCurrency() {\n currencyQueued = false;\n if (closed || discoveryPaused) return;\n await conversations.reconcile();\n if (conversations.current()) {\n show();\n return;\n }\n const resting = status;\n const progress: CycleProgress = { complete: false, reachable: !resting.providerUnreachable };\n moveTo(transferring(resting));\n try {\n await conversations.catchUp(progress);\n } catch {\n progress.reachable = false;\n } finally {\n if (!closed) {\n moveTo(settled(resting, progress, resting.lastCompleted, pending(), attention()));\n }\n }\n }\n\n function handSelected(locators: readonly string[]) {\n const path = options.adapter.roomVersions;\n if (path === undefined || withdrawNotifications === undefined) return;\n if (handed !== undefined && JSON.stringify(locators) === JSON.stringify(handed)) return;\n handed = locators;\n path.select(locators);\n }\n\n async function runNotified() {\n const announced = [...notices];\n notices.clear();\n if (announced.length === 0 || closed || discoveryPaused) return;\n const resting = status;\n const progress: CycleProgress = { complete: false, reachable: !resting.providerUnreachable };\n moveTo(transferring(resting));\n try {\n const local = await openLocal();\n for (const [locator, roomVersion] of announced) {\n if (closed || discoveryPaused || authorization === undefined) return;\n if (handed?.includes(locator) !== true) continue;\n const room = discovered.get(locator);\n const held = replicas.get(locator);\n if (room === undefined) continue;\n if (sourceRefusals.has(locator)) {\n void enqueue();\n continue;\n }\n if (held === undefined) continue;\n if (held.confirmed.record.roomVersion === roomVersion) continue;\n const withheld = await advance(room, local, authorization);\n if (withheld === null) continue;\n if (withheld.kind === 'refused') {\n void enqueue();\n continue;\n }\n if (withheld.kind === 'scoped-refusal') {\n await scoped(withheld, room, local);\n continue;\n }\n if (withheld.kind === 'transport-uncertainty') {\n progress.reachable = false;\n continue;\n }\n if (withheld.kind === 'room-not-readable') {\n unreadable.add(locator);\n list(room, false);\n emitRooms();\n continue;\n }\n if (withheld.kind === 'revoked-authorization') {\n await refuse('revoked-authorization');\n return;\n }\n }\n } catch {\n progress.reachable = false;\n } finally {\n if (!closed) {\n moveTo(settled(resting, progress, resting.lastCompleted, pending(), attention()));\n }\n }\n }\n\n function enqueue() {\n if (inflight) {\n queued = true;\n return chain;\n }\n inflight = true;\n chain = chain.then(run, run);\n return chain;\n }\n\n function close() {\n closed = true;\n withdrawNotifications?.();\n withdrawNotifications = undefined;\n withdrawConversations?.();\n withdrawConversations = undefined;\n conversations.close();\n stopTimer();\n store?.close();\n void opening?.then(\n (opened) => {\n opened.close();\n },\n () => {},\n );\n roomListeners.clear();\n refusalListeners.clear();\n storageLossListeners.clear();\n statusListeners.clear();\n readSide.close();\n queueSubscriptions.clear();\n roomDraftListeners.clear();\n presentationListeners.clear();\n }\n\n options.signal?.addEventListener('abort', close, { once: true });\n if (options.signal?.aborted) close();\n\n void openLocal().catch(() => {\n notifyReady();\n });\n void enqueue();\n\n function watch(\n topic: RuntimeTopic,\n input: readonly unknown[],\n deliver: (message: unknown) => void,\n ): () => void {\n if (topic === 'room-drafts') {\n const listener: RoomDraftSubscription = { notify: deliver, ready: false };\n roomDraftListeners.add(listener);\n void exclusive(async () => {\n await openLocal();\n if (closed || !roomDraftListeners.has(listener)) return;\n listener.ready = true;\n }).then(\n () => {\n if (closed || !listener.ready || !roomDraftListeners.has(listener)) return;\n listener.notify(snapshotRoomDrafts());\n },\n () => {},\n );\n return () => {\n roomDraftListeners.delete(listener);\n };\n }\n if (topic === 'conversation') {\n return conversations.watch(input[0] as string, input[1] as ConversationOptions, deliver);\n }\n if (topic === 'presentation') {\n const listener: PresentationSubscription = {\n app: input[0] as string,\n notify: deliver,\n ready: false,\n };\n presentationListeners.add(listener);\n void exclusive(async () => {\n await openLocal();\n }).then(\n () => {\n if (closed || !presentationListeners.has(listener)) return;\n listener.ready = true;\n listener.notify(presentationOf(listener.app));\n },\n () => {},\n );\n return () => {\n presentationListeners.delete(listener);\n };\n }\n if (topic === 'rooms') {\n roomListeners.add(deliver);\n deliver(listed());\n return () => {\n roomListeners.delete(deliver);\n };\n }\n if (topic === 'connection-refusal') {\n refusalListeners.add(deliver);\n deliver(refusal);\n return () => {\n refusalListeners.delete(deliver);\n };\n }\n if (topic === 'storage-loss') {\n storageLossListeners.add(deliver);\n deliver(storageLoss);\n return () => {\n storageLossListeners.delete(deliver);\n };\n }\n if (topic === 'sync-status') {\n statusListeners.add(deliver);\n deliver(shown);\n return () => {\n statusListeners.delete(deliver);\n };\n }\n if (topic === 'queue') {\n const queue: QueueSubscription = { locator: input[0] as string, notify: deliver };\n queueSubscriptions.add(queue);\n queue.notify(entriesOf(queue.locator));\n return () => {\n queueSubscriptions.delete(queue);\n };\n }\n const plan = planOf(input[0], roomFacts());\n return readSide.watch(plan, identityOf(plan), deliver);\n }\n\n const md: MdRuntime = {\n loaded() {\n return openLocal().then(() => undefined);\n },\n rooms() {\n return listed();\n },\n slots() {\n return slotted();\n },\n query: ((input: unknown) => readSide.query(planOf(input, roomFacts()))) as MdRuntime['query'],\n async search(input: unknown) {\n const plan = searchPlanOf(input);\n const selected =\n plan.documents === undefined\n ? null\n : ((await readSide.query(filterOf(plan.documents, roomFacts()))) as DocumentResult)\n .documents;\n return searchIndex.search(plan, selected);\n },\n types(locator: string): RoomTypes {\n return {\n collection: modelTypes(modelOf(locator)),\n typedSelection:\n rooms.get(locator)?.typedSelection === undefined ||\n rooms.get(locator)?.typedSelection === null\n ? null\n : modelTypes(modelOf(locator, 'typed-selection')),\n };\n },\n syncStatus() {\n return shown;\n },\n roomDraft: {\n list() {\n return exclusive(async () => {\n await openLocal();\n return snapshotRoomDrafts();\n }).then((listed) => {\n publishRoomDrafts(true);\n return listed;\n });\n },\n read(room: string, path: string) {\n const record = roomDrafts.get(room)?.get(path);\n return record === undefined ? null : roomDraftOf(record);\n },\n write(room: string, path: string, revision: string | null, input: unknown) {\n return exclusive(async (): Promise<RoomDraftWrite> => {\n const parts = readParts(input);\n if (path === '' || normalize(path) !== path) throw new Error('room-draft-malformed');\n const local = await openLocal();\n const current = roomDrafts.get(room)?.get(path);\n if ((current?.revision ?? null) !== revision) {\n return {\n outcome: 'stale',\n current: current === undefined ? null : roomDraftOf(current),\n };\n }\n const record: RoomDraftRecord = {\n locator: room,\n path,\n revision: roomDraftRevision(),\n parts: held(current?.parts, parts),\n returned: current?.returned ?? null,\n };\n await local.keepRoomDraft(record);\n rememberRoomDraft(record);\n publishChangeSet(changeSet(room, null, null, { drafts: [path] }));\n return { outcome: 'written', roomDraft: roomDraftOf(record) };\n });\n },\n discard(room: string, path: string, revision: string) {\n return exclusive(async (): Promise<RoomDraftWrite> => {\n const local = await openLocal();\n const current = roomDrafts.get(room)?.get(path);\n if (current === undefined || current.revision !== revision) {\n return {\n outcome: 'stale',\n current: current === undefined ? null : roomDraftOf(current),\n };\n }\n await local.discardRoomDraft(room, path);\n forgetRoomDraft(room, path);\n publishChangeSet(changeSet(room, null, null, { drafts: [path] }));\n moveTo({ ...status, ...attention() });\n return { outcome: 'written', roomDraft: null };\n });\n },\n },\n conversation: conversations.surface,\n chatDraft: conversations.chatDraft,\n presentation: {\n read(app: string) {\n return exclusive(async () => {\n await openLocal();\n return presentationOf(app);\n });\n },\n write(app: string, value: unknown) {\n return exclusive(async () => {\n const local = await openLocal();\n const stored = structuredClone(value);\n await local.present({ app, value: stored });\n presentations.set(app, stored);\n publishChangeSet(changeSet('', null, null, { presentation: app }));\n });\n },\n },\n save(\n room: string,\n named: readonly SavedRoomDraft[],\n writtenBy?: WrittenBy,\n ): Promise<SaveResult> {\n return exclusive(() => saveRoomDrafts(room, named, writtenBy));\n },\n outcome(identifier: string): SubmissionOutcome | null {\n return outcomes.get(identifier) ?? null;\n },\n history(locator: string, path: string, query?: HistoryQuery) {\n return readHistory(locator, path, query);\n },\n call(name: string, input: unknown) {\n return invokeAction(name, input);\n },\n log() {\n return journal.export();\n },\n storageLoss() {\n return storageLoss;\n },\n persistence() {\n return options.shell.persistentStorage;\n },\n observe: ((topic: RuntimeTopic, ...input: unknown[]) =>\n opened(\n (deliver) =>\n watch(topic, input, (message) => {\n deliver(structuredClone(message));\n }),\n topic === 'query',\n )) as MdRuntime['observe'],\n async reauthorize() {\n if (refusal === null || !refusal.reauthorizationOffered) return;\n journal.record('connection reauthorize');\n await mutations;\n authorization = undefined;\n discoveryPaused = false;\n await enqueue();\n },\n };\n return { md, watch };\n}\n"],"names":["verify","cached","modelTypes","NO_MODEL","sameModel","opened","filterOf","identityOf","planOf","createReadSide","createSearchIndex","searchPlanOf","ROOM_CONTRACT_VERSION","VERSION_1_CAPABILITIES","bootstrapRoom","changeSet","mergeChangeSets","createConversationStore","MD_MODEL","validRoot","createLog","refreshRoom","buildBatch","applyReturned","compositionOf","readConfirmed","replicaOf","withdrawals","changedParts","changesOf","held","readParts","returnedInto","underneath","settled","same","saving","STARTING","transferring","detectStorageLoss","nextGeneration","roomDraftRevision","beneath","normalize","openRuntimeStore","unconfirmed","DEFAULT_DISCOVERY_INTERVAL_MS","knownCapabilities","Set","within","root","path","declaredIdentity","model","undefined","identity","length","version","declaredSelection","room","selection","typedSelection","Array","isArray","roots","attachedModel","every","index","collectionRoot","other","at","createMdRuntime","options","composeRuntime","md","period","discoveryIntervalMs","authorization","opening","store","replicas","Map","pendings","roomDrafts","presentations","outcomes","outcomeRooms","limits","slots","capabilities","rewriting","some","capability","name","rooms","unreadable","models","liveModels","invalidModels","modelEpoch","discovered","roomsListed","scopedRefusals","sourceRefusals","modelKey","locator","attached","modelOf","get","savedModel","has","status","reason","compositionFor","record","selectionModel","mismatchedRoots","refusal","storageLoss","shown","discoveryPaused","timer","closed","withdrawNotifications","handed","notices","chain","Promise","resolve","mutations","inflight","queued","roomListeners","refusalListeners","storageLossListeners","statusListeners","queueSubscriptions","roomDraftListeners","presentationListeners","readSide","withdrawConversations","currencyQueued","conversations","cards","declaredCards","documents","query","select","roomFacts","call","input","invokeAction","durably","stream","adapter","publish","publishChangeSet","searchIndex","document","messages","message","conversation","journal","notifyReady","ready","rememberRoomDraft","set","forgetRoomDraft","delete","size","roomDraftOf","structuredClone","revision","parts","changedUnderneath","visible","returned","snapshotRoomDrafts","records","values","flatMap","sort","left","right","map","publishRoomDrafts","waitingOnly","value","listener","notify","presentationOf","app","emitPresentation","pending","replica","queue","attention","attentionRequired","push","reset","submission","state","listed","slotted","slot","entries","segment","available","types","Object","emitRooms","emitRefusal","emitStorageLoss","moveTo","next","show","current","submissionOf","batch","id","entriesOf","freeze","emitQueue","subscription","applyChangeSet","apply","changed","queues","drafts","change","scheduleCurrency","stopTimer","clearInterval","startTimer","setInterval","enqueue","refuse","provider","exclusive","revoked","local","openLocal","revokeModels","confirmed","keys","add","key","before","Error","reauthorizationOffered","list","synchronizationAvailable","operations","providerOwnedPaths","roomVersion","applyDiscovery","listedLocators","clear","dropUnlisted","admission","unlistedHeld","filter","unlisted","dropRooms","removed","restored","persisted","prior","snapshot","JSON","stringify","hydrate","recordedOutcomes","kept","presented","chatDrafts","lastCompleted","declared","named","listedSlots","all","presentation","providerLimits","queuedBatches","outcome","previousReplicas","existing","locators","read","readState","open","shell","generation","storedGeneration","loss","rememberGeneration","keepGeneration","work","catch","error","then","withdrawable","lost","settle","settling","withdrawn","includes","returning","kind","reverse","leaving","written","saved","settledOutcomes","accepted","write","previous","previousQueue","retained","saveRoomDrafts","writtenBy","rule","file","draft","built","baseRoomVersion","composition","changes","bases","batches","consumed","consumedRoomDrafts","identifier","mark","submit","readHistory","ensureAuthorization","transfer","pageToken","join","result","history","scoped","conversationCards","declaredAction","action","actions","code","pullRefresh","authorized","detail","pullBootstrap","collection","advance","refreshed","bootstrapped","withhold","withheld","progress","complete","reachable","refusedSource","fields","location","referrers","affected","commitAccept","submitted","base","overlay","remaining","retainedBase","applied","revisions","removals","acceptedOutcome","author","time","submitRoom","head","earlier","Date","now","parse","mutate","changeBatch","from","pulled","committed","retainModel","epoch","heldBefore","acquireModel","answer","definitions","verified","verdict","verifiedWith","scopedAway","scope","sync","synchronize","cycle","discover","supportedVersions","mdModel","malformed","operation","required","requiredGuarantees","previousCapabilities","observeRoomVersions","observeConversations","discoveredSlots","declare","handSelected","reconcile","providerUnreachable","reconnected","catchUp","authorize","connect","completedAt","toISOString","run","roomVersions","observe","notification","runNotified","event","receive","runCurrency","resting","announced","close","signal","addEventListener","once","aborted","watch","topic","deliver","plan","loaded","search","selected","syncStatus","roomDraft","keepRoomDraft","discard","discardRoomDraft","surface","chatDraft","stored","present","save","log","export","persistence","persistentStorage","reauthorize"],"mappings":"AAAA,SAASA,MAAM,QAAQ,uBAAuB;AAC9C,SACEC,MAAM,EACNC,UAAU,EACVC,QAAQ,EACRC,SAAS,QAGJ,aAAa;AACpB,SAASC,MAAM,QAA0B,mBAAmB;AAC5D,SACEC,QAAQ,EACRC,UAAU,EACVC,MAAM,QAMD,aAAa;AACpB,SAASC,cAAc,QAAQ,iBAAiB;AAChD,SACEC,iBAAiB,EACjBC,YAAY,QAGP,cAAc;AACrB,SACEC,qBAAqB,EACrBC,sBAAsB,QAejB,eAAe;AACtB,SAASC,aAAa,QAAQ,iBAAiB;AAC/C,SAASC,SAAS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AAEtD,IAAY,EAAE+F,KAAoB;YACzD,OAAO6L,YAAYtO,SAAStD,MAAM+F;QACpC;QACAG,MAAKxD,IAAY,EAAEyD,KAAc;YAC/B,OAAOC,aAAa1D,MAAMyD;QAC5B;QACAkT;YACE,OAAOtS,QAAQuS,MAAM;QACvB;QACAnV;YACE,OAAOA;QACT;QACAoV;YACE,OAAOlY,QAAQ2N,KAAK,CAACwK,iBAAiB;QACxC;QACAjC,SAAU,CAACc,OAAqB,GAAGlS,QACjCjJ,OACE,CAACob,UACCF,MAAMC,OAAOlS,OAAO,CAACU;oBACnByR,QAAQ9Q,gBAAgBX;gBAC1B,IACFwR,UAAU;QAEd,MAAMoB;YACJ,IAAIvV,YAAY,QAAQ,CAACA,QAAQoI,sBAAsB,EAAE;YACzDvF,QAAQhD,MAAM,CAAC;YACf,MAAMe;YACNpD,gBAAgBvB;YAChBkE,kBAAkB;YAClB,MAAMmH;QACR;IACF;IACA,OAAO;QAAEjK;QAAI6W;IAAM;AACrB"}
package/dist/refresh.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Adapter, AdapterFailure, Authorization } from './adapter.js';
2
2
  import { type ConfirmedLayer } from './replica.js';
3
- import { type Unconfirmed } from './transfer.js';
3
+ import { type Refused, type Unconfirmed } from './transfer.js';
4
4
  export type RefreshOutcome = {
5
5
  kind: 'still-current';
6
6
  } | {
@@ -8,6 +8,6 @@ export type RefreshOutcome = {
8
8
  confirmed: ConfirmedLayer;
9
9
  } | {
10
10
  kind: 'beyond-horizon';
11
- } | Unconfirmed | AdapterFailure;
11
+ } | Unconfirmed | Refused | AdapterFailure;
12
12
  export declare function refreshRoom(adapter: Adapter, authorization: Authorization, confirmed: ConfirmedLayer): Promise<RefreshOutcome>;
13
13
  //# sourceMappingURL=refresh.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"refresh.d.ts","sourceRoot":"","sources":["../src/refresh.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,aAAa,EAAe,MAAM,cAAc,CAAC;AACxF,OAAO,EAAc,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAC/D,OAAO,EAAe,KAAK,WAAW,EAAE,MAAM,eAAe,CAAC;AAE9D,MAAM,MAAM,cAAc,GACtB;IAAE,IAAI,EAAE,eAAe,CAAA;CAAE,GACzB;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,SAAS,EAAE,cAAc,CAAA;CAAE,GAC/C;IAAE,IAAI,EAAE,gBAAgB,CAAA;CAAE,GAC1B,WAAW,GACX,cAAc,CAAC;AAEnB,wBAAsB,WAAW,CAC/B,OAAO,EAAE,OAAO,EAChB,aAAa,EAAE,aAAa,EAC5B,SAAS,EAAE,cAAc,GACxB,OAAO,CAAC,cAAc,CAAC,CAsDzB"}
1
+ {"version":3,"file":"refresh.d.ts","sourceRoot":"","sources":["../src/refresh.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,aAAa,EAAe,MAAM,cAAc,CAAC;AACxF,OAAO,EAAc,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAC/D,OAAO,EAAe,KAAK,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5E,MAAM,MAAM,cAAc,GACtB;IAAE,IAAI,EAAE,eAAe,CAAA;CAAE,GACzB;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,SAAS,EAAE,cAAc,CAAA;CAAE,GAC/C;IAAE,IAAI,EAAE,gBAAgB,CAAA;CAAE,GAC1B,WAAW,GACX,OAAO,GACP,cAAc,CAAC;AAEnB,wBAAsB,WAAW,CAC/B,OAAO,EAAE,OAAO,EAChB,aAAa,EAAE,aAAa,EAC5B,SAAS,EAAE,cAAc,GACxB,OAAO,CAAC,cAAc,CAAC,CAsDzB"}
package/dist/refresh.js CHANGED
@@ -47,7 +47,7 @@ export async function refreshRoom(adapter, authorization, confirmed) {
47
47
  stage(page);
48
48
  pageToken = page.pageToken;
49
49
  }
50
- const advanced = readStaged({
50
+ const staged = readStaged({
51
51
  ...confirmed.record,
52
52
  roomVersion,
53
53
  documents,
@@ -56,10 +56,10 @@ export async function refreshRoom(adapter, authorization, confirmed) {
56
56
  ].sort(),
57
57
  revisions
58
58
  }, confirmed);
59
- return advanced === null ? unconfirmed : {
59
+ return staged.kind === 'staged' ? {
60
60
  kind: 'advanced',
61
- confirmed: advanced
62
- };
61
+ confirmed: staged.confirmed
62
+ } : staged;
63
63
  }
64
64
 
65
65
  //# sourceMappingURL=refresh.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/refresh.ts"],"sourcesContent":["import type { Adapter, AdapterFailure, Authorization, RefreshPage } from './adapter.js';\nimport { readStaged, type ConfirmedLayer } from './replica.js';\nimport { unconfirmed, type Unconfirmed } from './transfer.js';\n\nexport type RefreshOutcome =\n | { kind: 'still-current' }\n | { kind: 'advanced'; confirmed: ConfirmedLayer }\n | { kind: 'beyond-horizon' }\n | Unconfirmed\n | AdapterFailure;\n\nexport async function refreshRoom(\n adapter: Adapter,\n authorization: Authorization,\n confirmed: ConfirmedLayer,\n): Promise<RefreshOutcome> {\n const locator = confirmed.record.locator;\n const fromRoomVersion = confirmed.record.roomVersion;\n const first = await adapter.refresh(authorization, {\n locator,\n selection: confirmed.record.replica.selection,\n fromRoomVersion,\n });\n if (first.kind !== 'net-advancement') return first;\n const roomVersion = first.roomVersion;\n const documents: Record<string, string> = { ...confirmed.record.documents };\n const revisions: Record<string, string> = { ...confirmed.record.revisions };\n const binaryTargets = new Set(confirmed.record.binaryTargets);\n const stage = (page: RefreshPage) => {\n Object.assign(documents, page.documents);\n Object.assign(revisions, page.revisions);\n for (const path of Object.keys(page.documents)) binaryTargets.delete(path);\n for (const target of page.binaryTargets) {\n delete documents[target];\n delete revisions[target];\n binaryTargets.add(target);\n }\n for (const path of page.removals) {\n delete documents[path];\n delete revisions[path];\n binaryTargets.delete(path);\n }\n };\n stage(first);\n let pageToken = first.pageToken;\n while (pageToken !== undefined) {\n const page = await adapter.refresh(authorization, {\n locator,\n selection: confirmed.record.replica.selection,\n fromRoomVersion,\n pageToken,\n });\n if (page.kind === 'still-current' || page.kind === 'beyond-horizon') return unconfirmed;\n if (page.kind !== 'net-advancement') return page;\n if (page.roomVersion !== roomVersion) return unconfirmed;\n stage(page);\n pageToken = page.pageToken;\n }\n const advanced = readStaged(\n {\n ...confirmed.record,\n roomVersion,\n documents,\n binaryTargets: [...binaryTargets].sort(),\n revisions,\n },\n confirmed,\n );\n return advanced === null ? unconfirmed : { kind: 'advanced', confirmed: advanced };\n}\n"],"names":["readStaged","unconfirmed","refreshRoom","adapter","authorization","confirmed","locator","record","fromRoomVersion","roomVersion","first","refresh","selection","replica","kind","documents","revisions","binaryTargets","Set","stage","page","Object","assign","path","keys","delete","target","add","removals","pageToken","undefined","advanced","sort"],"mappings":"AACA,SAASA,UAAU,QAA6B,eAAe;AAC/D,SAASC,WAAW,QAA0B,gBAAgB;AAS9D,OAAO,eAAeC,YACpBC,OAAgB,EAChBC,aAA4B,EAC5BC,SAAyB;IAEzB,MAAMC,UAAUD,UAAUE,MAAM,CAACD,OAAO;IACxC,MAAME,kBAAkBH,UAAUE,MAAM,CAACE,WAAW;IACpD,MAAMC,QAAQ,MAAMP,QAAQQ,OAAO,CAACP,eAAe;QACjDE;QACAM,WAAWP,UAAUE,MAAM,CAACM,OAAO,CAACD,SAAS;QAC7CJ;IACF;IACA,IAAIE,MAAMI,IAAI,KAAK,mBAAmB,OAAOJ;IAC7C,MAAMD,cAAcC,MAAMD,WAAW;IACrC,MAAMM,YAAoC;QAAE,GAAGV,UAAUE,MAAM,CAACQ,SAAS;IAAC;IAC1E,MAAMC,YAAoC;QAAE,GAAGX,UAAUE,MAAM,CAACS,SAAS;IAAC;IAC1E,MAAMC,gBAAgB,IAAIC,IAAIb,UAAUE,MAAM,CAACU,aAAa;IAC5D,MAAME,QAAQ,CAACC;QACbC,OAAOC,MAAM,CAACP,WAAWK,KAAKL,SAAS;QACvCM,OAAOC,MAAM,CAACN,WAAWI,KAAKJ,SAAS;QACvC,KAAK,MAAMO,QAAQF,OAAOG,IAAI,CAACJ,KAAKL,SAAS,EAAGE,cAAcQ,MAAM,CAACF;QACrE,KAAK,MAAMG,UAAUN,KAAKH,aAAa,CAAE;YACvC,OAAOF,SAAS,CAACW,OAAO;YACxB,OAAOV,SAAS,CAACU,OAAO;YACxBT,cAAcU,GAAG,CAACD;QACpB;QACA,KAAK,MAAMH,QAAQH,KAAKQ,QAAQ,CAAE;YAChC,OAAOb,SAAS,CAACQ,KAAK;YACtB,OAAOP,SAAS,CAACO,KAAK;YACtBN,cAAcQ,MAAM,CAACF;QACvB;IACF;IACAJ,MAAMT;IACN,IAAImB,YAAYnB,MAAMmB,SAAS;IAC/B,MAAOA,cAAcC,UAAW;QAC9B,MAAMV,OAAO,MAAMjB,QAAQQ,OAAO,CAACP,eAAe;YAChDE;YACAM,WAAWP,UAAUE,MAAM,CAACM,OAAO,CAACD,SAAS;YAC7CJ;YACAqB;QACF;QACA,IAAIT,KAAKN,IAAI,KAAK,mBAAmBM,KAAKN,IAAI,KAAK,kBAAkB,OAAOb;QAC5E,IAAImB,KAAKN,IAAI,KAAK,mBAAmB,OAAOM;QAC5C,IAAIA,KAAKX,WAAW,KAAKA,aAAa,OAAOR;QAC7CkB,MAAMC;QACNS,YAAYT,KAAKS,SAAS;IAC5B;IACA,MAAME,WAAW/B,WACf;QACE,GAAGK,UAAUE,MAAM;QACnBE;QACAM;QACAE,eAAe;eAAIA;SAAc,CAACe,IAAI;QACtChB;IACF,GACAX;IAEF,OAAO0B,aAAa,OAAO9B,cAAc;QAAEa,MAAM;QAAYT,WAAW0B;IAAS;AACnF"}
1
+ {"version":3,"sources":["/workspace/packages/mdruntime/src/refresh.ts"],"sourcesContent":["import type { Adapter, AdapterFailure, Authorization, RefreshPage } from './adapter.js';\nimport { readStaged, type ConfirmedLayer } from './replica.js';\nimport { unconfirmed, type Refused, type Unconfirmed } from './transfer.js';\n\nexport type RefreshOutcome =\n | { kind: 'still-current' }\n | { kind: 'advanced'; confirmed: ConfirmedLayer }\n | { kind: 'beyond-horizon' }\n | Unconfirmed\n | Refused\n | AdapterFailure;\n\nexport async function refreshRoom(\n adapter: Adapter,\n authorization: Authorization,\n confirmed: ConfirmedLayer,\n): Promise<RefreshOutcome> {\n const locator = confirmed.record.locator;\n const fromRoomVersion = confirmed.record.roomVersion;\n const first = await adapter.refresh(authorization, {\n locator,\n selection: confirmed.record.replica.selection,\n fromRoomVersion,\n });\n if (first.kind !== 'net-advancement') return first;\n const roomVersion = first.roomVersion;\n const documents: Record<string, string> = { ...confirmed.record.documents };\n const revisions: Record<string, string> = { ...confirmed.record.revisions };\n const binaryTargets = new Set(confirmed.record.binaryTargets);\n const stage = (page: RefreshPage) => {\n Object.assign(documents, page.documents);\n Object.assign(revisions, page.revisions);\n for (const path of Object.keys(page.documents)) binaryTargets.delete(path);\n for (const target of page.binaryTargets) {\n delete documents[target];\n delete revisions[target];\n binaryTargets.add(target);\n }\n for (const path of page.removals) {\n delete documents[path];\n delete revisions[path];\n binaryTargets.delete(path);\n }\n };\n stage(first);\n let pageToken = first.pageToken;\n while (pageToken !== undefined) {\n const page = await adapter.refresh(authorization, {\n locator,\n selection: confirmed.record.replica.selection,\n fromRoomVersion,\n pageToken,\n });\n if (page.kind === 'still-current' || page.kind === 'beyond-horizon') return unconfirmed;\n if (page.kind !== 'net-advancement') return page;\n if (page.roomVersion !== roomVersion) return unconfirmed;\n stage(page);\n pageToken = page.pageToken;\n }\n const staged = readStaged(\n {\n ...confirmed.record,\n roomVersion,\n documents,\n binaryTargets: [...binaryTargets].sort(),\n revisions,\n },\n confirmed,\n );\n return staged.kind === 'staged' ? { kind: 'advanced', confirmed: staged.confirmed } : staged;\n}\n"],"names":["readStaged","unconfirmed","refreshRoom","adapter","authorization","confirmed","locator","record","fromRoomVersion","roomVersion","first","refresh","selection","replica","kind","documents","revisions","binaryTargets","Set","stage","page","Object","assign","path","keys","delete","target","add","removals","pageToken","undefined","staged","sort"],"mappings":"AACA,SAASA,UAAU,QAA6B,eAAe;AAC/D,SAASC,WAAW,QAAwC,gBAAgB;AAU5E,OAAO,eAAeC,YACpBC,OAAgB,EAChBC,aAA4B,EAC5BC,SAAyB;IAEzB,MAAMC,UAAUD,UAAUE,MAAM,CAACD,OAAO;IACxC,MAAME,kBAAkBH,UAAUE,MAAM,CAACE,WAAW;IACpD,MAAMC,QAAQ,MAAMP,QAAQQ,OAAO,CAACP,eAAe;QACjDE;QACAM,WAAWP,UAAUE,MAAM,CAACM,OAAO,CAACD,SAAS;QAC7CJ;IACF;IACA,IAAIE,MAAMI,IAAI,KAAK,mBAAmB,OAAOJ;IAC7C,MAAMD,cAAcC,MAAMD,WAAW;IACrC,MAAMM,YAAoC;QAAE,GAAGV,UAAUE,MAAM,CAACQ,SAAS;IAAC;IAC1E,MAAMC,YAAoC;QAAE,GAAGX,UAAUE,MAAM,CAACS,SAAS;IAAC;IAC1E,MAAMC,gBAAgB,IAAIC,IAAIb,UAAUE,MAAM,CAACU,aAAa;IAC5D,MAAME,QAAQ,CAACC;QACbC,OAAOC,MAAM,CAACP,WAAWK,KAAKL,SAAS;QACvCM,OAAOC,MAAM,CAACN,WAAWI,KAAKJ,SAAS;QACvC,KAAK,MAAMO,QAAQF,OAAOG,IAAI,CAACJ,KAAKL,SAAS,EAAGE,cAAcQ,MAAM,CAACF;QACrE,KAAK,MAAMG,UAAUN,KAAKH,aAAa,CAAE;YACvC,OAAOF,SAAS,CAACW,OAAO;YACxB,OAAOV,SAAS,CAACU,OAAO;YACxBT,cAAcU,GAAG,CAACD;QACpB;QACA,KAAK,MAAMH,QAAQH,KAAKQ,QAAQ,CAAE;YAChC,OAAOb,SAAS,CAACQ,KAAK;YACtB,OAAOP,SAAS,CAACO,KAAK;YACtBN,cAAcQ,MAAM,CAACF;QACvB;IACF;IACAJ,MAAMT;IACN,IAAImB,YAAYnB,MAAMmB,SAAS;IAC/B,MAAOA,cAAcC,UAAW;QAC9B,MAAMV,OAAO,MAAMjB,QAAQQ,OAAO,CAACP,eAAe;YAChDE;YACAM,WAAWP,UAAUE,MAAM,CAACM,OAAO,CAACD,SAAS;YAC7CJ;YACAqB;QACF;QACA,IAAIT,KAAKN,IAAI,KAAK,mBAAmBM,KAAKN,IAAI,KAAK,kBAAkB,OAAOb;QAC5E,IAAImB,KAAKN,IAAI,KAAK,mBAAmB,OAAOM;QAC5C,IAAIA,KAAKX,WAAW,KAAKA,aAAa,OAAOR;QAC7CkB,MAAMC;QACNS,YAAYT,KAAKS,SAAS;IAC5B;IACA,MAAME,SAAS/B,WACb;QACE,GAAGK,UAAUE,MAAM;QACnBE;QACAM;QACAE,eAAe;eAAIA;SAAc,CAACe,IAAI;QACtChB;IACF,GACAX;IAEF,OAAO0B,OAAOjB,IAAI,KAAK,WAAW;QAAEA,MAAM;QAAYT,WAAW0B,OAAO1B,SAAS;IAAC,IAAI0B;AACxF"}
package/dist/replica.d.ts CHANGED
@@ -3,6 +3,7 @@ import { type Collection, type Composition } from './collection.js';
3
3
  import { type Layer } from './overlay.js';
4
4
  import { type Rewriting } from './save.js';
5
5
  import type { ReplicaRecord } from './store.js';
6
+ import { type Refused, type Unconfirmed } from './transfer.js';
6
7
  export type ConfirmedLayer = {
7
8
  record: ReplicaRecord;
8
9
  collection: Collection;
@@ -10,6 +11,10 @@ export type ConfirmedLayer = {
10
11
  export type VisibleLayer = Layer & {
11
12
  collection: Collection;
12
13
  };
14
+ export type Staged = {
15
+ kind: 'staged';
16
+ confirmed: ConfirmedLayer;
17
+ } | Refused | Unconfirmed;
13
18
  export type Replica = {
14
19
  confirmed: ConfirmedLayer;
15
20
  queue: readonly ChangeBatch[];
@@ -25,8 +30,8 @@ type ReplayStep = {
25
30
  };
26
31
  export declare function compositionOf(record: ReplicaRecord): Composition;
27
32
  export declare function readConfirmed(record: ReplicaRecord, previous?: ConfirmedLayer): ConfirmedLayer | null;
28
- export declare function readStaged(record: ReplicaRecord, previous?: ConfirmedLayer): ConfirmedLayer | null;
29
- export declare function applyReturned(confirmed: ConfirmedLayer, documents: Readonly<Record<string, string>>, revisions: Readonly<Record<string, string>>, removals: readonly string[], roomVersion: string): ConfirmedLayer | null;
33
+ export declare function readStaged(record: ReplicaRecord, previous?: ConfirmedLayer): Staged;
34
+ export declare function applyReturned(confirmed: ConfirmedLayer, documents: Readonly<Record<string, string>>, revisions: Readonly<Record<string, string>>, removals: readonly string[], roomVersion: string): Staged;
30
35
  export declare function replicaOf(confirmed: ConfirmedLayer, queue: readonly ChangeBatch[], rewriting: Rewriting, previous?: Replica): Replica;
31
36
  export declare function withdrawals(confirmed: ConfirmedLayer, queue: readonly ChangeBatch[], withdrawable: (batch: ChangeBatch) => boolean, rewriting: Rewriting): readonly ChangeBatch[];
32
37
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"replica.d.ts","sourceRoot":"","sources":["../src/replica.ts"],"names":[],"mappings":"AACA,OAAO,EAAa,KAAK,WAAW,EAAqB,MAAM,aAAa,CAAC;AAC7E,OAAO,EAIL,KAAK,UAAU,EACf,KAAK,WAAW,EACjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAA0C,KAAK,KAAK,EAAE,MAAM,cAAc,CAAC;AAClF,OAAO,EAAqB,KAAK,SAAS,EAAE,MAAM,WAAW,CAAC;AAE9D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,MAAM,MAAM,cAAc,GAAG;IAC3B,MAAM,EAAE,aAAa,CAAC;IACtB,UAAU,EAAE,UAAU,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG,KAAK,GAAG;IACjC,UAAU,EAAE,UAAU,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG;IACpB,SAAS,EAAE,cAAc,CAAC;IAC1B,KAAK,EAAE,SAAS,WAAW,EAAE,CAAC;IAC9B,OAAO,EAAE,YAAY,CAA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;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,cAAc,GAAG,MAAM,CAmBnF;AAED,wBAAgB,aAAa,CAC3B,SAAS,EAAE,cAAc,EACzB,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,EAC3C,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,EAC3C,QAAQ,EAAE,SAAS,MAAM,EAAE,EAC3B,WAAW,EAAE,MAAM,GAClB,MAAM,CAmBR;AAuDD,wBAAgB,SAAS,CACvB,SAAS,EAAE,cAAc,EACzB,KAAK,EAAE,SAAS,WAAW,EAAE,EAC7B,SAAS,EAAE,SAAS,EACpB,QAAQ,CAAC,EAAE,OAAO,GACjB,OAAO,CA2CT;AAyCD,wBAAgB,WAAW,CACzB,SAAS,EAAE,cAAc,EACzB,KAAK,EAAE,SAAS,WAAW,EAAE,EAC7B,YAAY,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,OAAO,EAC7C,SAAS,EAAE,SAAS,GACnB,SAAS,WAAW,EAAE,CAoBxB"}
package/dist/replica.js CHANGED
@@ -4,6 +4,7 @@ import { parseCollection, readCollection, validateCollection } from './collectio
4
4
  import { overlay, overlayChanged, sameLayerText } from './overlay.js';
5
5
  import { providerRewritten } from './save.js';
6
6
  import { equalValue } from './room-draft.js';
7
+ import { unconfirmed } from './transfer.js';
7
8
  export function compositionOf(record) {
8
9
  return {
9
10
  collectionRoot: record.collectionRoot,
@@ -27,9 +28,18 @@ export function readConfirmed(record, previous) {
27
28
  export function readStaged(record, previous) {
28
29
  if ((record.model.status === 'current' || record.selectionModel.status === 'current') && (previous === undefined || !sameLayerText(record, previous.record) || record.model !== previous.record.model || record.selectionModel !== previous.record.selectionModel)) {
29
30
  const verdict = validateCollection(record.documents, record.binaryTargets, compositionOf(record));
30
- if (verdict.verdict === 'refuse' && verdict.rule !== 'model-unavailable') return null;
31
+ if (verdict.verdict === 'refuse' && verdict.rule !== 'model-unavailable') {
32
+ return {
33
+ kind: 'refused',
34
+ refusal: verdict
35
+ };
36
+ }
31
37
  }
32
- return readConfirmed(record, previous);
38
+ const confirmed = readConfirmed(record, previous);
39
+ return confirmed === null ? unconfirmed : {
40
+ kind: 'staged',
41
+ confirmed
42
+ };
33
43
  }
34
44
  export function applyReturned(confirmed, documents, revisions, removals, roomVersion) {
35
45
  const nextDocuments = {
@@ -1 +1 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/replica.ts"],"sourcesContent":["import { parse, type Document } from '@agentshouse/mdmodel';\nimport { immutable, type ChangeBatch, type Precondition } from './change.js';\nimport {\n parseCollection,\n readCollection,\n validateCollection,\n type Collection,\n type Composition,\n} from './collection.js';\nimport { overlay, overlayChanged, sameLayerText, type Layer } from './overlay.js';\nimport { providerRewritten, type Rewriting } from './save.js';\nimport { equalValue } from './room-draft.js';\nimport type { ReplicaRecord } from './store.js';\n\nexport type ConfirmedLayer = {\n record: ReplicaRecord;\n collection: Collection;\n};\n\nexport type VisibleLayer = Layer & {\n collection: Collection;\n};\n\nexport type Replica = {\n confirmed: ConfirmedLayer;\n queue: readonly ChangeBatch[];\n visible: VisibleLayer;\n replay: readonly ReplayStep[];\n};\n\ntype ReplayStep = {\n id: string;\n before: Layer;\n after: Layer;\n effective: ChangeBatch;\n collection?: Collection;\n};\n\nexport function compositionOf(record: ReplicaRecord): Composition {\n return {\n collectionRoot: record.collectionRoot,\n model: record.model,\n selection:\n record.typedSelection === null\n ? null\n : { roots: record.typedSelection.roots, model: record.selectionModel },\n };\n}\n\nexport function readConfirmed(\n record: ReplicaRecord,\n previous?: ConfirmedLayer,\n): ConfirmedLayer | null {\n const collection = readCollection(\n record.documents,\n compositionOf(record),\n previous === undefined\n ? undefined\n : { text: previous.record.documents, collection: previous.collection },\n );\n return collection === null ? null : { record, collection };\n}\n\nexport function readStaged(\n record: ReplicaRecord,\n previous?: ConfirmedLayer,\n): ConfirmedLayer | null {\n if (\n (record.model.status === 'current' || record.selectionModel.status === 'current') &&\n (previous === undefined ||\n !sameLayerText(record, previous.record) ||\n record.model !== previous.record.model ||\n record.selectionModel !== previous.record.selectionModel)\n ) {\n const verdict = validateCollection(\n record.documents,\n record.binaryTargets,\n compositionOf(record),\n );\n if (verdict.verdict === 'refuse' && verdict.rule !== 'model-unavailable') return null;\n }\n return readConfirmed(record, previous);\n}\n\nexport function applyReturned(\n confirmed: ConfirmedLayer,\n documents: Readonly<Record<string, string>>,\n revisions: Readonly<Record<string, string>>,\n removals: readonly string[],\n roomVersion: string,\n): ConfirmedLayer | null {\n const nextDocuments = { ...confirmed.record.documents, ...documents };\n const nextRevisions = { ...confirmed.record.revisions, ...revisions };\n const binaryTargets = new Set(confirmed.record.binaryTargets);\n for (const path of removals) {\n delete nextDocuments[path];\n delete nextRevisions[path];\n binaryTargets.delete(path);\n }\n return readStaged(\n {\n ...confirmed.record,\n roomVersion,\n documents: nextDocuments,\n revisions: nextRevisions,\n binaryTargets: [...binaryTargets].sort(),\n },\n confirmed,\n );\n}\n\nfunction predicted(\n confirmed: ConfirmedLayer,\n batches: readonly ChangeBatch[],\n previous?: Replica,\n): { layer: Layer; replay: readonly ReplayStep[] } {\n const composition = compositionOf(confirmed.record);\n let layer: Layer = confirmed.record;\n const replay: ReplayStep[] = [];\n const prior = new Map(previous?.replay.map((step) => [step.id, step]) ?? []);\n for (const batch of batches) {\n const before = layer;\n const old = prior.get(batch.id);\n const hasMove = batch.changes.some((change) => change.kind === 'move');\n const reuseRewrite =\n old?.collection !== undefined &&\n sameLayerText(before, old.before) &&\n old.collection.composition.collectionRoot === composition.collectionRoot &&\n old.collection.composition.model === composition.model &&\n old.collection.composition.selection?.model === composition.selection?.model &&\n JSON.stringify(old.collection.composition.selection?.roots) ===\n JSON.stringify(composition.selection?.roots);\n const collection = hasMove\n ? reuseRewrite\n ? old.collection\n : parseCollection(\n before.documents,\n composition,\n old?.collection === undefined\n ? { text: confirmed.record.documents, collection: confirmed.collection }\n : { text: old.before.documents, collection: old.collection },\n )\n : undefined;\n const effective =\n collection === undefined\n ? batch\n : reuseRewrite\n ? old.effective\n : providerRewritten(batch, { ...before, collection });\n layer =\n old === undefined\n ? overlay(before, [effective])\n : overlayChanged(before, [effective], old.before, [old.effective], old.after);\n replay.push({\n id: batch.id,\n before,\n after: layer,\n effective,\n ...(collection === undefined ? {} : { collection }),\n });\n }\n return { layer, replay };\n}\n\nexport function replicaOf(\n confirmed: ConfirmedLayer,\n queue: readonly ChangeBatch[],\n rewriting: Rewriting,\n previous?: Replica,\n): Replica {\n const batches = Object.freeze(queue.map(immutable));\n if (batches.length === 0) {\n return {\n confirmed,\n queue: batches,\n visible: {\n documents: confirmed.record.documents,\n binaryTargets: confirmed.record.binaryTargets,\n revisions: confirmed.record.revisions,\n collection: confirmed.collection,\n },\n replay: [],\n };\n }\n const predictedState = rewriting === 'provider' ? predicted(confirmed, batches, previous) : null;\n const layer =\n rewriting === 'provider'\n ? predictedState!.layer\n : previous === undefined\n ? overlay(confirmed.record, batches)\n : overlayChanged(\n confirmed.record,\n batches,\n previous.confirmed.record,\n previous.queue,\n previous.visible,\n );\n return {\n confirmed,\n queue: batches,\n replay: predictedState?.replay ?? [],\n visible: {\n ...layer,\n collection: parseCollection(\n layer.documents,\n compositionOf(confirmed.record),\n previous === undefined\n ? undefined\n : { text: previous.visible.documents, collection: previous.visible.collection },\n ),\n },\n };\n}\n\nfunction present(layer: Layer, path: string): boolean {\n return layer.documents[path] !== undefined || layer.binaryTargets.includes(path);\n}\n\nfunction holds(layer: Layer, preconditions: readonly Precondition[]): boolean {\n const parsed = new Map<string, Document | null>();\n const documentAt = (path: string) => {\n if (!parsed.has(path)) {\n const text = layer.documents[path];\n const opened = text === undefined ? null : parse(text, path);\n parsed.set(path, opened?.ok === true ? opened.document : null);\n }\n return parsed.get(path) ?? null;\n };\n return preconditions.every((precondition) => {\n const path = precondition.path;\n if (precondition.kind === 'absent') return !present(layer, path);\n if (precondition.kind === 'present') return present(layer, path);\n if (precondition.kind === 'revision') {\n return present(layer, path) && layer.revisions[path] === precondition.revision;\n }\n const document = documentAt(path);\n if (document === null) return false;\n if (precondition.kind === 'field') {\n const value = Object.hasOwn(document.fields, precondition.name)\n ? document.fields[precondition.name]\n : undefined;\n return equalValue(value, precondition.value);\n }\n if (precondition.kind === 'section') {\n return (\n Object.hasOwn(document.sections, precondition.name) &&\n document.sections[precondition.name] === precondition.value\n );\n }\n return document.preamble === precondition.value;\n });\n}\n\nexport function withdrawals(\n confirmed: ConfirmedLayer,\n queue: readonly ChangeBatch[],\n withdrawable: (batch: ChangeBatch) => boolean,\n rewriting: Rewriting,\n): readonly ChangeBatch[] {\n if (!queue.some(withdrawable)) return [];\n const composition = compositionOf(confirmed.record);\n let layer: Layer = confirmed.record;\n const withdrawn: ChangeBatch[] = [];\n for (const batch of queue) {\n if (withdrawable(batch) && !holds(layer, batch.preconditions)) {\n withdrawn.push(batch);\n continue;\n }\n const effective =\n rewriting === 'provider' && batch.changes.some((change) => change.kind === 'move')\n ? providerRewritten(batch, {\n ...layer,\n collection: parseCollection(layer.documents, composition),\n })\n : batch;\n layer = overlay(layer, [effective]);\n }\n return withdrawn;\n}\n"],"names":["parse","immutable","parseCollection","readCollection","validateCollection","overlay","overlayChanged","sameLayerText","providerRewritten","equalValue","compositionOf","record","collectionRoot","model","selection","typedSelection","roots","selectionModel","readConfirmed","previous","collection","documents","undefined","text","readStaged","status","verdict","binaryTargets","rule","applyReturned","confirmed","revisions","removals","roomVersion","nextDocuments","nextRevisions","Set","path","delete","sort","predicted","batches","composition","layer","replay","prior","Map","map","step","id","batch","before","old","get","hasMove","changes","some","change","kind","reuseRewrite","JSON","stringify","effective","after","push","replicaOf","queue","rewriting","Object","freeze","length","visible","predictedState","present","includes","holds","preconditions","parsed","documentAt","has","opened","set","ok","document","every","precondition","revision","value","hasOwn","fields","name","sections","preamble","withdrawals","withdrawable","withdrawn"],"mappings":"AAA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AAM;IACnC,MAAMoF,YAA2B,EAAE;IACnC,KAAK,MAAM7C,SAASgB,MAAO;QACzB,IAAI4B,aAAa5C,UAAU,CAACyB,MAAMhC,OAAOO,MAAM0B,aAAa,GAAG;YAC7DmB,UAAU/B,IAAI,CAACd;YACf;QACF;QACA,MAAMY,YACJK,cAAc,cAAcjB,MAAMK,OAAO,CAACC,IAAI,CAAC,CAACC,SAAWA,OAAOC,IAAI,KAAK,UACvElD,kBAAkB0C,OAAO;YACvB,GAAGP,KAAK;YACRvB,YAAYlB,gBAAgByC,MAAMtB,SAAS,EAAEqB;QAC/C,KACAQ;QACNP,QAAQtC,QAAQsC,OAAO;YAACmB;SAAU;IACpC;IACA,OAAOiC;AACT"}
1
+ {"version":3,"sources":["/workspace/packages/mdruntime/src/replica.ts"],"sourcesContent":["import { parse, type Document } from '@agentshouse/mdmodel';\nimport { immutable, type ChangeBatch, type Precondition } from './change.js';\nimport {\n parseCollection,\n readCollection,\n validateCollection,\n type Collection,\n type Composition,\n} from './collection.js';\nimport { overlay, overlayChanged, sameLayerText, type Layer } from './overlay.js';\nimport { providerRewritten, type Rewriting } from './save.js';\nimport { equalValue } from './room-draft.js';\nimport type { ReplicaRecord } from './store.js';\nimport { unconfirmed, type Refused, type Unconfirmed } from './transfer.js';\n\nexport type ConfirmedLayer = {\n record: ReplicaRecord;\n collection: Collection;\n};\n\nexport type VisibleLayer = Layer & {\n collection: Collection;\n};\n\nexport type Staged = { kind: 'staged'; confirmed: ConfirmedLayer } | Refused | Unconfirmed;\n\nexport type Replica = {\n confirmed: ConfirmedLayer;\n queue: readonly ChangeBatch[];\n visible: VisibleLayer;\n replay: readonly ReplayStep[];\n};\n\ntype ReplayStep = {\n id: string;\n before: Layer;\n after: Layer;\n effective: ChangeBatch;\n collection?: Collection;\n};\n\nexport function compositionOf(record: ReplicaRecord): Composition {\n return {\n collectionRoot: record.collectionRoot,\n model: record.model,\n selection:\n record.typedSelection === null\n ? null\n : { roots: record.typedSelection.roots, model: record.selectionModel },\n };\n}\n\nexport function readConfirmed(\n record: ReplicaRecord,\n previous?: ConfirmedLayer,\n): ConfirmedLayer | null {\n const collection = readCollection(\n record.documents,\n compositionOf(record),\n previous === undefined\n ? undefined\n : { text: previous.record.documents, collection: previous.collection },\n );\n return collection === null ? null : { record, collection };\n}\n\nexport function readStaged(record: ReplicaRecord, previous?: ConfirmedLayer): Staged {\n if (\n (record.model.status === 'current' || record.selectionModel.status === 'current') &&\n (previous === undefined ||\n !sameLayerText(record, previous.record) ||\n record.model !== previous.record.model ||\n record.selectionModel !== previous.record.selectionModel)\n ) {\n const verdict = validateCollection(\n record.documents,\n record.binaryTargets,\n compositionOf(record),\n );\n if (verdict.verdict === 'refuse' && verdict.rule !== 'model-unavailable') {\n return { kind: 'refused', refusal: verdict };\n }\n }\n const confirmed = readConfirmed(record, previous);\n return confirmed === null ? unconfirmed : { kind: 'staged', confirmed };\n}\n\nexport function applyReturned(\n confirmed: ConfirmedLayer,\n documents: Readonly<Record<string, string>>,\n revisions: Readonly<Record<string, string>>,\n removals: readonly string[],\n roomVersion: string,\n): Staged {\n const nextDocuments = { ...confirmed.record.documents, ...documents };\n const nextRevisions = { ...confirmed.record.revisions, ...revisions };\n const binaryTargets = new Set(confirmed.record.binaryTargets);\n for (const path of removals) {\n delete nextDocuments[path];\n delete nextRevisions[path];\n binaryTargets.delete(path);\n }\n return readStaged(\n {\n ...confirmed.record,\n roomVersion,\n documents: nextDocuments,\n revisions: nextRevisions,\n binaryTargets: [...binaryTargets].sort(),\n },\n confirmed,\n );\n}\n\nfunction predicted(\n confirmed: ConfirmedLayer,\n batches: readonly ChangeBatch[],\n previous?: Replica,\n): { layer: Layer; replay: readonly ReplayStep[] } {\n const composition = compositionOf(confirmed.record);\n let layer: Layer = confirmed.record;\n const replay: ReplayStep[] = [];\n const prior = new Map(previous?.replay.map((step) => [step.id, step]) ?? []);\n for (const batch of batches) {\n const before = layer;\n const old = prior.get(batch.id);\n const hasMove = batch.changes.some((change) => change.kind === 'move');\n const reuseRewrite =\n old?.collection !== undefined &&\n sameLayerText(before, old.before) &&\n old.collection.composition.collectionRoot === composition.collectionRoot &&\n old.collection.composition.model === composition.model &&\n old.collection.composition.selection?.model === composition.selection?.model &&\n JSON.stringify(old.collection.composition.selection?.roots) ===\n JSON.stringify(composition.selection?.roots);\n const collection = hasMove\n ? reuseRewrite\n ? old.collection\n : parseCollection(\n before.documents,\n composition,\n old?.collection === undefined\n ? { text: confirmed.record.documents, collection: confirmed.collection }\n : { text: old.before.documents, collection: old.collection },\n )\n : undefined;\n const effective =\n collection === undefined\n ? batch\n : reuseRewrite\n ? old.effective\n : providerRewritten(batch, { ...before, collection });\n layer =\n old === undefined\n ? overlay(before, [effective])\n : overlayChanged(before, [effective], old.before, [old.effective], old.after);\n replay.push({\n id: batch.id,\n before,\n after: layer,\n effective,\n ...(collection === undefined ? {} : { collection }),\n });\n }\n return { layer, replay };\n}\n\nexport function replicaOf(\n confirmed: ConfirmedLayer,\n queue: readonly ChangeBatch[],\n rewriting: Rewriting,\n previous?: Replica,\n): Replica {\n const batches = Object.freeze(queue.map(immutable));\n if (batches.length === 0) {\n return {\n confirmed,\n queue: batches,\n visible: {\n documents: confirmed.record.documents,\n binaryTargets: confirmed.record.binaryTargets,\n revisions: confirmed.record.revisions,\n collection: confirmed.collection,\n },\n replay: [],\n };\n }\n const predictedState = rewriting === 'provider' ? predicted(confirmed, batches, previous) : null;\n const layer =\n rewriting === 'provider'\n ? predictedState!.layer\n : previous === undefined\n ? overlay(confirmed.record, batches)\n : overlayChanged(\n confirmed.record,\n batches,\n previous.confirmed.record,\n previous.queue,\n previous.visible,\n );\n return {\n confirmed,\n queue: batches,\n replay: predictedState?.replay ?? [],\n visible: {\n ...layer,\n collection: parseCollection(\n layer.documents,\n compositionOf(confirmed.record),\n previous === undefined\n ? undefined\n : { text: previous.visible.documents, collection: previous.visible.collection },\n ),\n },\n };\n}\n\nfunction present(layer: Layer, path: string): boolean {\n return layer.documents[path] !== undefined || layer.binaryTargets.includes(path);\n}\n\nfunction holds(layer: Layer, preconditions: readonly Precondition[]): boolean {\n const parsed = new Map<string, Document | null>();\n const documentAt = (path: string) => {\n if (!parsed.has(path)) {\n const text = layer.documents[path];\n const opened = text === undefined ? null : parse(text, path);\n parsed.set(path, opened?.ok === true ? opened.document : null);\n }\n return parsed.get(path) ?? null;\n };\n return preconditions.every((precondition) => {\n const path = precondition.path;\n if (precondition.kind === 'absent') return !present(layer, path);\n if (precondition.kind === 'present') return present(layer, path);\n if (precondition.kind === 'revision') {\n return present(layer, path) && layer.revisions[path] === precondition.revision;\n }\n const document = documentAt(path);\n if (document === null) return false;\n if (precondition.kind === 'field') {\n const value = Object.hasOwn(document.fields, precondition.name)\n ? document.fields[precondition.name]\n : undefined;\n return equalValue(value, precondition.value);\n }\n if (precondition.kind === 'section') {\n return (\n Object.hasOwn(document.sections, precondition.name) &&\n document.sections[precondition.name] === precondition.value\n );\n }\n return document.preamble === precondition.value;\n });\n}\n\nexport function withdrawals(\n confirmed: ConfirmedLayer,\n queue: readonly ChangeBatch[],\n withdrawable: (batch: ChangeBatch) => boolean,\n rewriting: Rewriting,\n): readonly ChangeBatch[] {\n if (!queue.some(withdrawable)) return [];\n const composition = compositionOf(confirmed.record);\n let layer: Layer = confirmed.record;\n const withdrawn: ChangeBatch[] = [];\n for (const batch of queue) {\n if (withdrawable(batch) && !holds(layer, batch.preconditions)) {\n withdrawn.push(batch);\n continue;\n }\n const effective =\n rewriting === 'provider' && batch.changes.some((change) => change.kind === 'move')\n ? providerRewritten(batch, {\n ...layer,\n collection: parseCollection(layer.documents, composition),\n })\n : batch;\n layer = overlay(layer, [effective]);\n }\n return withdrawn;\n}\n"],"names":["parse","immutable","parseCollection","readCollection","validateCollection","overlay","overlayChanged","sameLayerText","providerRewritten","equalValue","unconfirmed","compositionOf","record","collectionRoot","model","selection","typedSelection","roots","selectionModel","readConfirmed","previous","collection","documents","undefined","text","readStaged","status","verdict","binaryTargets","rule","kind","refusal","confirmed","applyReturned","revisions","removals","roomVersion","nextDocuments","nextRevisions","Set","path","delete","sort","predicted","batches","composition","layer","replay","prior","Map","map","step","id","batch","before","old","get","hasMove","changes","some","change","reuseRewrite","JSON","stringify","effective","after","push","replicaOf","queue","rewriting","Object","freeze","length","visible","predictedState","present","includes","holds","preconditions","parsed","documentAt","has","opened","set","ok","document","every","precondition","revision","value","hasOwn","fields","name","sections","preamble","withdrawals","withdrawable","withdrawn"],"mappings":"AAAA,SAASA,KAAK,QAAuB,uBAAuB;AAC5D,SAASC,SAAS,QAA6C,cAAc;AAC7E,SACEC,eAAe,EACfC,cAAc,EACdC,kBAAkB,QAGb,kBAAkB;AACzB,SAASC,OAAO,EAAEC,cAAc,EAAEC,aAAa,QAAoB,eAAe;AAClF,SAASC,iBAAiB,QAAwB,YAAY;AAC9D,SAASC,UAAU,QAAQ,kBAAkB;AAE7C,SAASC,WAAW,QAAwC,gBAAgB;AA4B5E,OAAO,SAASC,cAAcC,MAAqB;IACjD,OAAO;QACLC,gBAAgBD,OAAOC,cAAc;QACrCC,OAAOF,OAAOE,KAAK;QACnBC,WACEH,OAAOI,cAAc,KAAK,OACtB,OACA;YAAEC,OAAOL,OAAOI,cAAc,CAACC,KAAK;YAAEH,OAAOF,OAAOM,cAAc;QAAC;IAC3E;AACF;AAEA,OAAO,SAASC,cACdP,MAAqB,EACrBQ,QAAyB;IAEzB,MAAMC,aAAalB,eACjBS,OAAOU,SAAS,EAChBX,cAAcC,SACdQ,aAAaG,YACTA,YACA;QAAEC,MAAMJ,SAASR,MAAM,CAACU,SAAS;QAAED,YAAYD,SAASC,UAAU;IAAC;IAEzE,OAAOA,eAAe,OAAO,OAAO;QAAET;QAAQS;IAAW;AAC3D;AAEA,OAAO,SAASI,WAAWb,MAAqB,EAAEQ,QAAyB;IACzE,IACE,AAACR,CAAAA,OAAOE,KAAK,CAACY,MAAM,KAAK,aAAad,OAAOM,cAAc,CAACQ,MAAM,KAAK,SAAQ,KAC9EN,CAA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IF,aAAazD,IAAI,KAAK,WAAW;YACnC,OACEwC,OAAOoB,MAAM,CAACL,SAASQ,QAAQ,EAAEN,aAAaK,IAAI,KAClDP,SAASQ,QAAQ,CAACN,aAAaK,IAAI,CAAC,KAAKL,aAAaE,KAAK;QAE/D;QACA,OAAOJ,SAASS,QAAQ,KAAKP,aAAaE,KAAK;IACjD;AACF;AAEA,OAAO,SAASM,YACd/D,SAAyB,EACzBoC,KAA6B,EAC7B4B,YAA6C,EAC7C3B,SAAoB;IAEpB,IAAI,CAACD,MAAMT,IAAI,CAACqC,eAAe,OAAO,EAAE;IACxC,MAAMnD,cAAclC,cAAcqB,UAAUpB,MAAM;IAClD,IAAIkC,QAAed,UAAUpB,MAAM;IACnC,MAAMqF,YAA2B,EAAE;IACnC,KAAK,MAAM5C,SAASe,MAAO;QACzB,IAAI4B,aAAa3C,UAAU,CAACwB,MAAM/B,OAAOO,MAAMyB,aAAa,GAAG;YAC7DmB,UAAU/B,IAAI,CAACb;YACf;QACF;QACA,MAAMW,YACJK,cAAc,cAAchB,MAAMK,OAAO,CAACC,IAAI,CAAC,CAACC,SAAWA,OAAO9B,IAAI,KAAK,UACvEtB,kBAAkB6C,OAAO;YACvB,GAAGP,KAAK;YACRzB,YAAYnB,gBAAgB4C,MAAMxB,SAAS,EAAEuB;QAC/C,KACAQ;QACNP,QAAQzC,QAAQyC,OAAO;YAACkB;SAAU;IACpC;IACA,OAAOiC;AACT"}
@@ -1,5 +1,10 @@
1
+ import type { Refusal } from '@agentshouse/mdmodel';
1
2
  export type Unconfirmed = {
2
3
  kind: 'unconfirmed';
3
4
  };
5
+ export type Refused = {
6
+ kind: 'refused';
7
+ refusal: Refusal;
8
+ };
4
9
  export declare const unconfirmed: Unconfirmed;
5
10
  //# sourceMappingURL=transfer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"transfer.d.ts","sourceRoot":"","sources":["../src/transfer.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,WAAW,GAAG;IAAE,IAAI,EAAE,aAAa,CAAA;CAAE,CAAC;AAElD,eAAO,MAAM,WAAW,EAAE,WAAqC,CAAC"}
1
+ {"version":3,"file":"transfer.d.ts","sourceRoot":"","sources":["../src/transfer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAEpD,MAAM,MAAM,WAAW,GAAG;IAAE,IAAI,EAAE,aAAa,CAAA;CAAE,CAAC;AAElD,MAAM,MAAM,OAAO,GAAG;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC;AAE5D,eAAO,MAAM,WAAW,EAAE,WAAqC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/transfer.ts"],"sourcesContent":["export type Unconfirmed = { kind: 'unconfirmed' };\n\nexport const unconfirmed: Unconfirmed = { kind: 'unconfirmed' };\n"],"names":["unconfirmed","kind"],"mappings":"AAEA,OAAO,MAAMA,cAA2B;IAAEC,MAAM;AAAc,EAAE"}
1
+ {"version":3,"sources":["/workspace/packages/mdruntime/src/transfer.ts"],"sourcesContent":["import type { Refusal } from '@agentshouse/mdmodel';\n\nexport type Unconfirmed = { kind: 'unconfirmed' };\n\nexport type Refused = { kind: 'refused'; refusal: Refusal };\n\nexport const unconfirmed: Unconfirmed = { kind: 'unconfirmed' };\n"],"names":["unconfirmed","kind"],"mappings":"AAMA,OAAO,MAAMA,cAA2B;IAAEC,MAAM;AAAc,EAAE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentshouse/mdruntime",
3
- "version": "0.1.0-alpha.30",
3
+ "version": "0.1.0-alpha.31",
4
4
  "description": "The headless core of MD App",
5
5
  "license": "MIT",
6
6
  "type": "module",