@agentshouse/mdruntime 0.1.0-alpha.9 → 0.1.0-c3903a68dcbbf

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/AGENTS.md +210 -0
  2. package/README.md +44 -0
  3. package/dist/adapter.d.ts +155 -12
  4. package/dist/adapter.d.ts.map +1 -1
  5. package/dist/adapter.js +2 -3
  6. package/dist/attachment.d.ts +3 -0
  7. package/dist/attachment.d.ts.map +1 -0
  8. package/dist/attachment.js +8 -0
  9. package/dist/bootstrap.d.ts +3 -7
  10. package/dist/bootstrap.d.ts.map +1 -1
  11. package/dist/bootstrap.js +29 -27
  12. package/dist/change-set.d.ts +33 -0
  13. package/dist/change-set.d.ts.map +1 -0
  14. package/dist/change-set.js +87 -0
  15. package/dist/change.d.ts +9 -0
  16. package/dist/change.d.ts.map +1 -1
  17. package/dist/change.js +6 -5
  18. package/dist/client.d.ts +40 -28
  19. package/dist/client.d.ts.map +1 -1
  20. package/dist/client.js +121 -177
  21. package/dist/collection.d.ts +15 -16
  22. package/dist/collection.d.ts.map +1 -1
  23. package/dist/collection.js +54 -87
  24. package/dist/connection.d.ts +57 -35
  25. package/dist/connection.d.ts.map +1 -1
  26. package/dist/connection.js +1475 -964
  27. package/dist/conversation.d.ts +41 -19
  28. package/dist/conversation.d.ts.map +1 -1
  29. package/dist/conversation.js +483 -327
  30. package/dist/durability.js +6 -6
  31. package/dist/file.d.ts +2 -2
  32. package/dist/file.d.ts.map +1 -1
  33. package/dist/file.js +48 -71
  34. package/dist/host.d.ts +7 -2
  35. package/dist/host.d.ts.map +1 -1
  36. package/dist/host.js +100 -102
  37. package/dist/identity.d.ts +1 -0
  38. package/dist/identity.d.ts.map +1 -1
  39. package/dist/identity.js +10 -9
  40. package/dist/index.d.ts +12 -10
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +1 -2
  43. package/dist/log.js +5 -6
  44. package/dist/memory.d.ts +6 -3
  45. package/dist/memory.d.ts.map +1 -1
  46. package/dist/memory.js +206 -210
  47. package/dist/model.d.ts +10 -25
  48. package/dist/model.d.ts.map +1 -1
  49. package/dist/model.js +18 -21
  50. package/dist/observation.d.ts +25 -0
  51. package/dist/observation.d.ts.map +1 -0
  52. package/dist/observation.js +85 -0
  53. package/dist/outcome.d.ts +17 -20
  54. package/dist/outcome.d.ts.map +1 -1
  55. package/dist/outcome.js +1 -23
  56. package/dist/overlay.d.ts +9 -2
  57. package/dist/overlay.d.ts.map +1 -1
  58. package/dist/overlay.js +187 -43
  59. package/dist/paths.d.ts +0 -1
  60. package/dist/paths.d.ts.map +1 -1
  61. package/dist/paths.js +12 -19
  62. package/dist/query.d.ts +210 -10
  63. package/dist/query.d.ts.map +1 -1
  64. package/dist/query.js +420 -15
  65. package/dist/read-side.d.ts +14 -0
  66. package/dist/read-side.d.ts.map +1 -0
  67. package/dist/read-side.js +371 -0
  68. package/dist/refresh.d.ts +4 -5
  69. package/dist/refresh.d.ts.map +1 -1
  70. package/dist/refresh.js +45 -30
  71. package/dist/replica.d.ts +25 -5
  72. package/dist/replica.d.ts.map +1 -1
  73. package/dist/replica.js +232 -38
  74. package/dist/room-draft.d.ts +124 -0
  75. package/dist/room-draft.d.ts.map +1 -0
  76. package/dist/room-draft.js +327 -0
  77. package/dist/rows.d.ts +41 -0
  78. package/dist/rows.d.ts.map +1 -0
  79. package/dist/rows.js +100 -0
  80. package/dist/save.d.ts +8 -4
  81. package/dist/save.d.ts.map +1 -1
  82. package/dist/save.js +265 -350
  83. package/dist/search.d.ts +61 -0
  84. package/dist/search.d.ts.map +1 -0
  85. package/dist/search.js +125 -0
  86. package/dist/status.d.ts +4 -6
  87. package/dist/status.d.ts.map +1 -1
  88. package/dist/status.js +9 -13
  89. package/dist/store.d.ts +68 -30
  90. package/dist/store.d.ts.map +1 -1
  91. package/dist/store.js +360 -134
  92. package/dist/transfer.d.ts +5 -0
  93. package/dist/transfer.d.ts.map +1 -1
  94. package/dist/transfer.js +1 -5
  95. package/dist/wire.d.ts +4 -3
  96. package/dist/wire.d.ts.map +1 -1
  97. package/dist/wire.js +50 -65
  98. package/package.json +6 -12
  99. package/dist/adapter.js.map +0 -1
  100. package/dist/bootstrap.js.map +0 -1
  101. package/dist/change.js.map +0 -1
  102. package/dist/client.js.map +0 -1
  103. package/dist/collection.js.map +0 -1
  104. package/dist/connection.js.map +0 -1
  105. package/dist/conversation.js.map +0 -1
  106. package/dist/durability.js.map +0 -1
  107. package/dist/file.js.map +0 -1
  108. package/dist/host.js.map +0 -1
  109. package/dist/identity.js.map +0 -1
  110. package/dist/index.js.map +0 -1
  111. package/dist/log.js.map +0 -1
  112. package/dist/memory.js.map +0 -1
  113. package/dist/model.js.map +0 -1
  114. package/dist/outcome.js.map +0 -1
  115. package/dist/overlay.js.map +0 -1
  116. package/dist/paths.js.map +0 -1
  117. package/dist/query.js.map +0 -1
  118. package/dist/refresh.js.map +0 -1
  119. package/dist/replica.js.map +0 -1
  120. package/dist/save.js.map +0 -1
  121. package/dist/status.js.map +0 -1
  122. package/dist/store.js.map +0 -1
  123. package/dist/transfer.js.map +0 -1
  124. package/dist/wire.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/connection.ts"],"sourcesContent":["import { rawQuery, type QueryBinding, type QueryInput } from './query.js';\nimport {\n cached,\n modelTypes,\n NO_MODEL,\n sameModel,\n type AttachedModelBinding,\n type ModelState,\n type TypesResult,\n} from './model.js';\nimport {\n query as evaluate,\n type QueryOptions,\n type QueryResult,\n type QueryRoom,\n} from '@agentshouse/query';\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 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 {\n createConversationStore,\n type ConversationStore,\n type ConversationSurface,\n type ConversationView,\n} from './conversation.js';\nimport type { Change, ChangeBatch } from './change.js';\nimport { MD_MODEL, PRESENTED, validRoot, type Composition, type MdType } from './collection.js';\nimport { createLog } from './log.js';\nimport {\n queuedOutcome,\n refusalOf,\n refused,\n withheldUntilReset,\n type CallResult,\n type QueueEntry,\n type QueueOutcome,\n type SubmissionOutcome,\n} from './outcome.js';\nimport { refreshRoom } from './refresh.js';\nimport { buildBatch, type SaveRefusal } from './save.js';\nimport {\n applyReturned,\n compositionOf,\n readConfirmed,\n replicaOf,\n type ConfirmedLayer,\n type Replica,\n} from './replica.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 { beneath } from './paths.js';\nimport { openRuntimeStore, type ReplicaRecord, type RuntimeStore } 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 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 modelBinding: AttachedModelBinding | null;\n queryBinding: QueryBinding | null;\n requiredGuarantees: readonly string[];\n authorization?: Authorization;\n discoveryIntervalMs?: number;\n signal?: AbortSignal;\n};\n\nexport type SaveResult = { outcome: 'saved'; id: string } | ({ outcome: 'refused' } & SaveRefusal);\n\nexport type DraftEntry = {\n readonly locator: string;\n readonly path: string;\n readonly content: unknown;\n};\n\nexport type DraftSurface = {\n list(): Promise<readonly DraftEntry[]>;\n read(locator: string, path: string): unknown;\n replace(locator: string, path: string, content: unknown): Promise<void>;\n discard(locator: string, path: string): Promise<void>;\n};\n\nexport type QueueSurface = {\n discard(locator: string, identifier: string): Promise<void>;\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 rooms(): readonly AppRoom[];\n query(options?: QueryOptions): QueryResult;\n types(locator: string): RoomTypes;\n syncStatus(): SyncStatus;\n draft: DraftSurface;\n conversation: ConversationSurface;\n presentation: PresentationSurface;\n save(locator: string, changes: readonly Change[], replacing?: string): Promise<SaveResult>;\n outcome(identifier: string): SubmissionOutcome | null;\n queue: QueueSurface;\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', listener: (rooms: readonly AppRoom[]) => void): () => void;\n (\n topic: 'connection-refusal',\n listener: (refusal: ConnectionRefusal | null) => void,\n ): () => void;\n (topic: 'storage-loss', listener: (statement: string | null) => void): () => void;\n (topic: 'sync-status', listener: (status: SyncStatus) => void): () => void;\n (topic: 'query', query: QueryOptions, listener: (result: QueryResult) => void): () => void;\n (\n topic: 'queue',\n locator: string,\n listener: (entries: readonly QueueEntry[]) => void,\n ): () => void;\n (topic: 'drafts', listener: (drafts: readonly DraftEntry[]) => void): () => void;\n (topic: 'presentation', app: string, listener: (value: unknown) => void): () => void;\n (\n topic: 'conversation',\n conversation: string,\n listener: (view: ConversationView) => void,\n ): () => void;\n };\n reauthorize(): Promise<void>;\n};\n\ntype QuerySubscription = {\n query: QueryOptions;\n notify: (result: QueryResult) => void;\n};\n\ntype QueueSubscription = {\n locator: string;\n notify: (entries: readonly QueueEntry[]) => void;\n};\n\ntype DraftSubscription = {\n notify: (drafts: readonly DraftEntry[]) => void;\n ready: boolean;\n};\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 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 drafts = new Map<string, Map<string, unknown>>();\n const presentations = new Map<string, unknown>();\n const outcomes = new Map<string, SubmissionOutcome>();\n let limits: readonly ProviderLimit[] = [];\n let capabilities: readonly Capability[] = [];\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 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 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 querySubscriptions = new Set<QuerySubscription>();\n const queueSubscriptions = new Set<QueueSubscription>();\n const draftListeners = new Set<DraftSubscription>();\n const presentationListeners = new Set<PresentationSubscription>();\n let withdrawConversations: (() => void) | undefined;\n const conversations: ConversationStore = createConversationStore({\n cards: declaredCards,\n documents: () => visible({}),\n call: (name: ConversationAction, input: unknown) => invokeAction(name, input),\n durably,\n path: () => options.adapter.conversations,\n closed: () => closed,\n });\n const journal = createLog();\n let notifyReady = () => {};\n const ready = new Promise<void>((resolve) => {\n notifyReady = resolve;\n });\n function draftContent(locator: string, path: string) {\n return drafts.get(locator)?.get(path);\n }\n\n function rememberDraft(locator: string, path: string, content: unknown) {\n const room = drafts.get(locator) ?? new Map<string, unknown>();\n room.set(path, content);\n drafts.set(locator, room);\n }\n\n function forgetDraft(locator: string, path: string) {\n const room = drafts.get(locator);\n if (room === undefined) return;\n room.delete(path);\n if (room.size === 0) drafts.delete(locator);\n }\n\n function snapshotDrafts(): readonly DraftEntry[] {\n const entries: DraftEntry[] = [];\n for (const [locator, room] of drafts) {\n for (const [path, content] of room) {\n entries.push({ locator, path, content: structuredClone(content) });\n }\n }\n entries.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 entries;\n }\n\n async function readDrafts(opened: RuntimeStore) {\n await hydrate(opened);\n return snapshotDrafts();\n }\n\n function publishDrafts(waitingOnly: boolean) {\n if (closed) return;\n const value = snapshotDrafts();\n for (const listener of draftListeners) {\n if (waitingOnly && listener.ready) continue;\n listener.ready = true;\n listener.notify(value);\n }\n }\n\n function emitDrafts() {\n publishDrafts(false);\n }\n\n function releaseWaitingDrafts() {\n publishDrafts(true);\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 commitDraft(work: (local: RuntimeStore) => Promise<void>) {\n return exclusive(async () => {\n const local = await openLocal();\n await hydrate(local);\n await work(local);\n }).then(() => {\n emitDrafts();\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 let reset: string | null = null;\n for (const [locator, replica] of replicas) {\n const head = replica.queue[0];\n if (head === undefined) continue;\n const outcome = outcomes.get(head.id);\n if (outcome?.kind === 'retryable-refusal') {\n if (outcome.reset !== undefined && (reset === null || outcome.reset < reset)) {\n reset = outcome.reset;\n }\n continue;\n }\n if (!refused(outcome)) continue;\n attentionRequired.push({\n locator,\n batch: head.id,\n outcome: outcome.kind,\n refusal: refusalOf(outcome),\n ...(outcome.kind === 'conflicted' && outcome.roomVersion !== undefined\n ? { roomVersion: outcome.roomVersion }\n : {}),\n });\n }\n return { attentionRequired, reset };\n }\n\n function storedOutcomes(batches: readonly ChangeBatch[]) {\n const stored: Record<string, QueueOutcome> = {};\n for (const batch of batches) {\n const outcome = queuedOutcome(outcomes.get(batch.id));\n if (outcome.kind !== 'pending') stored[batch.id] = outcome;\n }\n return stored;\n }\n\n async function persistQueue(\n local: RuntimeStore,\n locator: string,\n batches: readonly ChangeBatch[],\n ) {\n await local.writeQueue({\n locator,\n batches,\n outcomes: storedOutcomes(batches),\n });\n }\n\n function listed(): readonly AppRoom[] {\n return structuredClone([...rooms.values()]);\n }\n\n function queryRooms(): readonly QueryInput[] {\n return [...replicas.values()].map((replica) => ({\n room: replica.confirmed.record.locator,\n roomVersion: replica.confirmed.record.roomVersion,\n documents: replica.visible.collection.documents,\n model: modelTypes(modelOf(replica.confirmed.record.locator)),\n typedSelection:\n replica.confirmed.record.typedSelection === null\n ? null\n : modelTypes(modelOf(replica.confirmed.record.locator, 'typed-selection')),\n }));\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 || same(status, next)) return;\n status = next;\n for (const listener of statusListeners) listener(status);\n }\n\n function visible(request: QueryOptions): QueryResult {\n if (options.queryBinding === null) {\n if (Object.keys(request).length > 0) throw new Error('query-binding-unavailable');\n return rawQuery(queryRooms());\n }\n return options.queryBinding(queryRooms(), {\n ...request,\n selector: { $and: [PRESENTED, request.selector ?? {}] },\n });\n }\n\n function emitVisible() {\n for (const subscription of querySubscriptions) {\n subscription.notify(visible(subscription.query));\n }\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) =>\n Object.freeze({\n batch,\n outcome: queuedOutcome(outcomes.get(batch.id)),\n }),\n );\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 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 function refuse(reason: ConnectionRefusalReason, provider: ProviderRefusal | null = null) {\n if (reason === 'revoked-authorization') {\n const revoked: ModelState = { status: 'unavailable', reason: 'revoked' };\n const attachments: readonly Attached[] = ['collection', 'typed-selection'];\n const keys = new Set(models.keys());\n for (const locator of rooms.keys()) {\n for (const attached of attachments) keys.add(modelKey(locator, attached));\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 for (const [locator, room] of rooms)\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 emitRooms();\n void exclusive(async () => {\n const local = await openLocal();\n for (const record of await local.all())\n await local.publish({ ...record, model: revoked, selectionModel: revoked });\n }).catch(() => {\n journal.record('model invalidation durable-write failure');\n });\n }\n stopTimer();\n discoveryPaused = true;\n refusal = {\n reason,\n reauthorizationOffered: reason === 'revoked-authorization',\n refusal: provider,\n };\n journal.record(`connection refused ${reason}`);\n emitRefusal();\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 function applyDiscovery(listed: readonly DiscoveredRoom[]): ReadonlySet<string> {\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 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 for (const [locator, room] of rooms) {\n if (listedLocators.has(locator)) continue;\n rooms.set(locator, { ...room, synchronizationAvailable: false });\n }\n emitRooms();\n return listedLocators;\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 }> {\n const [records, queues, kept, presented, cached, unsent, lastCompleted, declared] =\n await Promise.all([\n opened.all(),\n opened.queues(),\n opened.drafts(),\n opened.presentation(),\n opened.conversations(),\n opened.instructions(),\n opened.lastCompleted(),\n opened.providerLimits(),\n ]);\n limits = declared;\n drafts.clear();\n for (const draft of kept) rememberDraft(draft.locator, draft.path, draft.content);\n presentations.clear();\n for (const record of presented) presentations.set(record.app, record.value);\n conversations.hydrate(cached, unsent);\n const queuedBatches = new Map(queues.map((queue) => [queue.locator, queue.batches]));\n for (const queue of queues) {\n for (const [id, outcome] of Object.entries(queue.outcomes)) {\n outcomes.set(id, outcome);\n }\n }\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 confirmed = readConfirmed({ ...record, model, selectionModel });\n if (confirmed === null) continue;\n replicas.set(record.locator, replicaOf(confirmed, queuedBatches.get(record.locator) ?? []));\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 };\n }\n\n async function readState(opened: RuntimeStore): Promise<string | null> {\n const { lastCompleted, locators } = await hydrate(opened);\n if (replicas.size > 0) {\n emitRooms();\n emitVisible();\n }\n for (const locator of locators) emitQueue(locator);\n emitDrafts();\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 await hydrate(local);\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 publish(local: RuntimeStore, room: DiscoveredRoom, confirmed: ConfirmedLayer) {\n return exclusive(async () => {\n await hydrate(local);\n const retained = readConfirmed({\n ...confirmed.record,\n model: modelOf(room.locator),\n selectionModel: modelOf(room.locator, 'typed-selection'),\n });\n if (retained !== null) {\n await local.publish(retained.record);\n unreadable.delete(room.locator);\n replicas.set(room.locator, replicaOf(retained, replicas.get(room.locator)?.queue ?? []));\n }\n list(room, true);\n emitRooms();\n emitVisible();\n });\n }\n\n async function write(\n locator: string,\n changes: readonly Change[],\n replacing?: string,\n ): Promise<SaveResult> {\n const local = await openLocal();\n await hydrate(local);\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 built = buildBatch({\n baseRoomVersion: replica.confirmed.record.roomVersion,\n composition: compositionFor(replica.confirmed.record),\n operations: room.operations,\n binding: options.modelBinding,\n providerOwnedPaths: room.providerOwnedPaths,\n providerLimits: limits,\n visible: replica.visible,\n changes,\n });\n if (built.kind === 'refused') return { outcome: 'refused', ...built.refusal };\n const head = replica.queue[0];\n if (replacing !== undefined) {\n if (head === undefined || head.id !== replacing || !refused(outcomes.get(head.id))) {\n return { outcome: 'refused', rule: 'no-refused-head' };\n }\n }\n const batches =\n replacing === undefined\n ? [...replica.queue, built.batch]\n : [built.batch, ...replica.queue.slice(1)];\n const consumed = [...new Set(changes.map((change) => change.path))];\n try {\n await local.append({ locator, batches, outcomes: storedOutcomes(batches) }, consumed);\n } catch {\n return { outcome: 'refused', rule: 'durable-write' };\n }\n if (replacing !== undefined) outcomes.delete(replacing);\n for (const path of consumed) forgetDraft(locator, path);\n replicas.set(locator, replicaOf(replica.confirmed, batches));\n emitQueue(locator);\n emitVisible();\n emitDrafts();\n moveTo({ ...saving(status), ...attention() });\n void enqueue();\n return { outcome: 'saved', id: built.batch.id };\n }\n\n async function discardHead(locator: string, identifier: string): Promise<void> {\n const local = await openLocal();\n await hydrate(local);\n const replica = replicas.get(locator);\n const head = replica?.queue[0];\n if (\n replica === undefined ||\n head === undefined ||\n head.id !== identifier ||\n !refused(outcomes.get(head.id))\n ) {\n return;\n }\n const batches = replica.queue.slice(1);\n outcomes.delete(identifier);\n await persistQueue(local, locator, batches);\n replicas.set(locator, replicaOf(replica.confirmed, batches));\n emitQueue(locator);\n emitVisible();\n moveTo({\n ...status,\n state: pending() ? 'pending' : status.state,\n ...attention(),\n });\n void enqueue();\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') 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') 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(\n options.adapter,\n authorized,\n confirmed,\n options.modelBinding,\n );\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(\n options.adapter,\n authorized,\n room,\n {\n collection: modelOf(room.locator),\n selection: modelOf(room.locator, 'typed-selection'),\n },\n options.modelBinding,\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 function recordRefusal(\n result: Extract<\n MutationResult,\n { kind: 'conflicted' | 'rejected' | 'expired' | 'retryable-refusal' }\n >,\n ): QueueOutcome {\n if (result.kind === 'expired') return { kind: 'expired' };\n if (result.kind === 'retryable-refusal') {\n return {\n kind: 'retryable-refusal',\n code: result.code,\n fields: result.fields,\n ...(result.reset === undefined ? {} : { reset: result.reset }),\n };\n }\n if (result.kind === 'conflicted') {\n return {\n kind: 'conflicted',\n ...(result.roomVersion === undefined ? {} : { roomVersion: result.roomVersion }),\n affected: result.affected,\n code: result.code,\n fields: result.fields,\n };\n }\n return {\n kind: 'rejected',\n affected: result.affected,\n code: result.code,\n fields: result.fields,\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 await hydrate(local);\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 ...base.record,\n model: modelOf(room.locator),\n selectionModel: modelOf(room.locator, 'typed-selection'),\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 options.modelBinding,\n )\n : retainedBase;\n if (applied === null) return false;\n await local.publish(applied.record);\n await persistQueue(local, room.locator, remaining);\n outcomes.set(submitted.id, {\n kind: 'accepted',\n roomVersion: accepted.roomVersion,\n ...(accepted.author === undefined ? {} : { author: accepted.author }),\n ...(accepted.time === undefined ? {} : { time: accepted.time }),\n });\n unreadable.delete(room.locator);\n replicas.set(room.locator, replicaOf(applied, remaining));\n list(room, true);\n emitRooms();\n emitQueue(room.locator);\n emitVisible();\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 held = outcomes.get(head.id);\n if (refused(held)) return null;\n if (held?.kind === 'retryable-refusal') {\n if (withheldUntilReset(held, Date.now())) {\n progress.complete = false;\n return null;\n }\n await exclusive(async () => {\n await hydrate(local);\n const current = replicas.get(room.locator);\n if (current === undefined || current.queue[0]?.id !== head.id) return;\n outcomes.delete(head.id);\n await persistQueue(local, room.locator, current.queue);\n emitQueue(room.locator);\n moveTo({ ...status, ...attention() });\n });\n }\n let result: MutationResult;\n journal.record(`submission ${room.locator} ${head.id}`);\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 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 if (result.kind === 'retryable-refusal') progress.complete = false;\n await exclusive(async () => {\n await hydrate(local);\n const current = replicas.get(room.locator);\n if (current === undefined || !current.queue.some((batch) => batch.id === head.id)) {\n return;\n }\n outcomes.set(head.id, recordRefusal(result));\n await persistQueue(local, room.locator, current.queue);\n emitQueue(room.locator);\n moveTo({ ...status, ...attention() });\n });\n return null;\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 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 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 const queryChanged =\n previous.status === 'unavailable' || next.status === 'unavailable'\n ? previous.status !== next.status\n : JSON.stringify(previous.types) !== JSON.stringify(next.types);\n if (next.status === 'unavailable') {\n invalidModels.add(key);\n liveModels.delete(key);\n }\n await exclusive(async () => {\n await hydrate(local);\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.publish(record);\n const confirmed = readConfirmed(record);\n if (confirmed !== null) replicas.set(room.locator, replicaOf(confirmed, held.queue));\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 emitRooms();\n if (queryChanged && held !== undefined) emitVisible();\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 retainModel(local, room, attached, { status: 'unavailable', reason: 'revoked' });\n 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 = options.modelBinding?.verify(answer.snapshot);\n await retainModel(\n local,\n room,\n attached,\n verified?.kind === 'verified'\n ? {\n status: 'current',\n snapshot: structuredClone(answer.snapshot),\n verifiedWith: MD_MODEL,\n types: verified.types,\n }\n : {\n status: 'unavailable',\n reason: verified === undefined ? 'binding-unavailable' : 'invalid',\n },\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 progress.complete = false;\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(room.locator);\n list(room, false);\n emitRooms();\n continue;\n }\n if (withheld.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n return;\n }\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 refuse('missing-required-guarantee', { code: result.code, fields: result.fields });\n notifyReady();\n return;\n }\n if (result.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n notifyReady();\n return;\n }\n if (!result.supportedVersions.includes(ROOM_CONTRACT_VERSION)) {\n 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 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 refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n if (!declaredSelection(room)) {\n journal.record(`invalid typed selection declaration ${room.locator}`);\n 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 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 refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n }\n if (refusal !== null) {\n refusal = null;\n emitRefusal();\n }\n capabilities = result.capabilities;\n notifyReady();\n if (declared.has('room-version-notifications')) observeRoomVersions();\n if (declared.has('provider-actions')) observeConversations();\n if (JSON.stringify(result.providerLimits) !== JSON.stringify(limits)) {\n limits = result.providerLimits;\n await local.declare(limits);\n }\n const listedLocators = applyDiscovery(result.rooms);\n handSelected(\n result.rooms\n .filter((room) => room.replica.admission === 'admitted')\n .map((room) => room.locator)\n .sort(),\n );\n progress.complete = [...replicas.keys()].every((locator) => listedLocators.has(locator));\n await synchronize(result.rooms, local, 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 path = options.adapter.conversations;\n if (path === undefined || withdrawConversations !== undefined) return;\n withdrawConversations = path.observe((event) => {\n conversations.receive(event);\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 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 querySubscriptions.clear();\n queueSubscriptions.clear();\n draftListeners.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 return {\n rooms() {\n return listed();\n },\n query(request: QueryOptions = {}) {\n return visible(request);\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 status;\n },\n draft: {\n list() {\n return exclusive(async () => {\n const local = await openLocal();\n return readDrafts(local);\n }).then((entries) => {\n releaseWaitingDrafts();\n return entries;\n });\n },\n read(locator: string, path: string) {\n const content = draftContent(locator, path);\n return content === undefined ? null : structuredClone(content);\n },\n replace(locator: string, path: string, content: unknown) {\n return commitDraft(async (local) => {\n const stored = structuredClone(content);\n await local.keep({ locator, path, content: stored });\n rememberDraft(locator, path, stored);\n });\n },\n discard(locator: string, path: string) {\n return commitDraft(async (local) => {\n await local.discard(locator, path);\n forgetDraft(locator, path);\n });\n },\n },\n conversation: conversations.surface,\n presentation: {\n read(app: string) {\n return exclusive(async () => {\n await hydrate(await openLocal());\n return presentationOf(app);\n });\n },\n write(app: string, value: unknown) {\n return exclusive(async () => {\n const local = await openLocal();\n await hydrate(local);\n const stored = structuredClone(value);\n await local.present({ app, value: stored });\n presentations.set(app, stored);\n }).then(() => {\n emitPresentation(app);\n });\n },\n },\n save(locator: string, changes: readonly Change[], replacing?: string): Promise<SaveResult> {\n return exclusive(() => write(locator, changes, replacing));\n },\n outcome(identifier: string): SubmissionOutcome | null {\n const recorded = outcomes.get(identifier);\n if (recorded !== undefined) return recorded;\n for (const replica of replicas.values()) {\n if (replica.queue.some((batch) => batch.id === identifier)) return { kind: 'pending' };\n }\n return null;\n },\n queue: {\n discard(locator: string, identifier: string) {\n return exclusive(() => discardHead(locator, identifier));\n },\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(\n topic:\n | 'rooms'\n | 'connection-refusal'\n | 'storage-loss'\n | 'sync-status'\n | 'query'\n | 'queue'\n | 'drafts'\n | 'presentation'\n | 'conversation',\n second: QueryOptions | string | ((value: never) => void),\n third?: (value: never) => void,\n ) {\n if (topic === 'drafts') {\n const notify = second as (value: readonly DraftEntry[]) => void;\n const listener: DraftSubscription = { notify, ready: false };\n draftListeners.add(listener);\n void exclusive(async () => {\n const local = await openLocal();\n await readDrafts(local);\n if (closed || !draftListeners.has(listener)) return;\n listener.ready = true;\n }).then(\n () => {\n if (closed || !listener.ready || !draftListeners.has(listener)) return;\n listener.notify(snapshotDrafts());\n },\n () => {},\n );\n return () => {\n draftListeners.delete(listener);\n };\n }\n if (topic === 'conversation') {\n return conversations.observe(second as string, third as (view: ConversationView) => void);\n }\n if (topic === 'presentation') {\n const listener: PresentationSubscription = {\n app: second as string,\n notify: third as (value: unknown) => void,\n ready: false,\n };\n presentationListeners.add(listener);\n void exclusive(async () => {\n await hydrate(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 const notify = second as (value: readonly AppRoom[]) => void;\n roomListeners.add(notify);\n notify(listed());\n return () => {\n roomListeners.delete(notify);\n };\n }\n if (topic === 'connection-refusal') {\n const notify = second as (value: ConnectionRefusal | null) => void;\n refusalListeners.add(notify);\n notify(refusal);\n return () => {\n refusalListeners.delete(notify);\n };\n }\n if (topic === 'storage-loss') {\n const notify = second as (value: string | null) => void;\n storageLossListeners.add(notify);\n notify(storageLoss);\n return () => {\n storageLossListeners.delete(notify);\n };\n }\n if (topic === 'sync-status') {\n const notify = second as (value: SyncStatus) => void;\n statusListeners.add(notify);\n notify(status);\n return () => {\n statusListeners.delete(notify);\n };\n }\n if (topic === 'queue') {\n const queue: QueueSubscription = {\n locator: second as string,\n notify: third as (entries: readonly QueueEntry[]) => void,\n };\n queueSubscriptions.add(queue);\n queue.notify(entriesOf(queue.locator));\n return () => {\n queueSubscriptions.delete(queue);\n };\n }\n const subscription: QuerySubscription = {\n query: second as QueryOptions,\n notify: third as (result: QueryResult) => void,\n };\n const first = visible(subscription.query);\n querySubscriptions.add(subscription);\n subscription.notify(first);\n return () => {\n querySubscriptions.delete(subscription);\n };\n },\n async reauthorize() {\n if (refusal === null || !refusal.reauthorizationOffered) return;\n journal.record('connection reauthorize');\n authorization = undefined;\n discoveryPaused = false;\n await enqueue();\n },\n };\n}\n"],"names":["rawQuery","cached","modelTypes","NO_MODEL","sameModel","ROOM_CONTRACT_VERSION","VERSION_1_CAPABILITIES","bootstrapRoom","createConversationStore","MD_MODEL","PRESENTED","validRoot","createLog","queuedOutcome","refusalOf","refused","withheldUntilReset","refreshRoom","buildBatch","applyReturned","compositionOf","readConfirmed","replicaOf","settled","same","saving","STARTING","transferring","detectStorageLoss","nextGeneration","beneath","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","period","discoveryIntervalMs","authorization","opening","store","replicas","Map","drafts","presentations","outcomes","limits","capabilities","rooms","unreadable","models","liveModels","invalidModels","modelEpoch","discovered","scopedRefusals","modelKey","locator","attached","modelOf","get","savedModel","has","status","reason","compositionFor","record","selectionModel","mismatchedRoots","refusal","storageLoss","discoveryPaused","timer","closed","withdrawNotifications","handed","notices","chain","Promise","resolve","mutations","inflight","queued","roomListeners","refusalListeners","storageLossListeners","statusListeners","querySubscriptions","queueSubscriptions","draftListeners","presentationListeners","withdrawConversations","conversations","cards","declaredCards","documents","visible","call","name","input","invokeAction","durably","adapter","journal","notifyReady","ready","draftContent","rememberDraft","content","set","forgetDraft","delete","size","snapshotDrafts","entries","push","structuredClone","sort","left","right","readDrafts","opened","hydrate","publishDrafts","waitingOnly","value","listener","notify","emitDrafts","releaseWaitingDrafts","presentationOf","app","emitPresentation","commitDraft","work","exclusive","local","openLocal","then","pending","values","some","replica","queue","attention","attentionRequired","reset","head","outcome","id","kind","batch","roomVersion","storedOutcomes","batches","stored","persistQueue","writeQueue","listed","queryRooms","map","confirmed","collection","emitRooms","emitRefusal","emitStorageLoss","moveTo","next","request","queryBinding","Object","keys","Error","selector","$and","emitVisible","subscription","query","entriesOf","freeze","emitQueue","stopTimer","clearInterval","startTimer","setInterval","enqueue","refuse","provider","revoked","attachments","add","key","all","publish","catch","reauthorizationOffered","list","synchronizationAvailable","operations","providerOwnedPaths","applyDiscovery","listedLocators","clear","held","admission","restored","persisted","prior","snapshot","JSON","stringify","records","queues","kept","presented","unsent","lastCompleted","declared","presentation","instructions","providerLimits","draft","queuedBatches","existing","locators","readState","open","shell","generation","storedGeneration","loss","rememberGeneration","keepGeneration","error","retained","write","changes","replacing","rule","built","baseRoomVersion","composition","binding","modelBinding","slice","consumed","change","append","discardHead","identifier","state","readHistory","ensureAuthorization","transfer","revision","pageToken","join","result","history","scoped","capability","conversationCards","declaredAction","action","actions","code","pullRefresh","authorized","detail","pullBootstrap","advance","refreshed","bootstrapped","recordRefusal","fields","affected","commitAccept","submitted","accepted","base","overlay","current","remaining","filter","retainedBase","applied","revisions","removals","author","time","submitRoom","progress","Date","now","complete","mutate","changeBatch","reachable","from","pulled","committed","retainModel","epoch","previous","heldBefore","queryChanged","types","acquireModel","answer","definitions","verified","verify","verifiedWith","scopedAway","scope","read","sync","synchronize","withheld","cycle","discover","supportedVersions","includes","mdModel","malformed","operation","required","requiredGuarantees","observeRoomVersions","observeConversations","declare","handSelected","authorize","connect","completedAt","toISOString","run","roomVersions","observe","notification","runNotified","event","receive","select","announced","resting","providerUnreachable","close","signal","addEventListener","once","aborted","syncStatus","replace","keep","discard","conversation","surface","present","save","recorded","log","export","persistence","persistentStorage","topic","second","third","first","reauthorize"],"mappings":"AAAA,SAASA,QAAQ,QAA4C,aAAa;AAC1E,SACEC,MAAM,EACNC,UAAU,EACVC,QAAQ,EACRC,SAAS,QAIJ,aAAa;AAOpB,SACEC,qBAAqB,EACrBC,sBAAsB,QAcjB,eAAe;AACtB,SAASC,aAAa,QAAQ,iBAAiB;AAC/C,SACEC,uBAAuB,QAIlB,oBAAoB;AAE3B,SAASC,QAAQ,EAAEC,SAAS,EAAEC,SAAS,QAAuC,kBAAkB;AAChG,SAASC,SAAS,QAAQ,WAAW;AACrC,SACEC,aAAa,EACbC,SAAS,EACTC,OAAO,EACPC,kBAAkB,QAKb,eAAe;AACtB,SAASC,WAAW,QAAQ,eAAe;AAC3C,SAASC,UAAU,QAA0B,YAAY;AACzD,SACEC,aAAa,EACbC,aAAa,EACbC,aAAa,EACbC,SAAS,QAGJ,eAAe;AACtB,SACEC,OAAO,EACPC,IAAI,EACJC,MAAM,EACNC,QAAQ,EACRC,YAAY,QAIP,cAAc;AACrB,SAASC,iBAAiB,EAAEC,cAAc,QAA2B,kBAAkB;AACvF,SAASC,OAAO,QAAQ,aAAa;AACrC,SAASC,gBAAgB,QAA+C,aAAa;AACrF,SAASC,WAAW,QAA0B,gBAAgB;AAE9D,MAAMC,gCAAgC;AAEtC,MAAMC,oBAAoB,IAAIC,IAAY7B;AAQ1C,SAAS8B,OAAOC,IAAY,EAAEC,IAAY;IACxC,OAAOD,SAAS,MAAMP,QAAQO,MAAMC;AACtC;AAEA,SAASC,iBAAiBC,KAA4D;IACpF,IAAIA,UAAUC,WAAW,OAAO;IAChC,IAAID,UAAU,MAAM,OAAO;IAC3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A,MAAMC,QAAQhR,QAAQgF,aAAaC,KAAK;YACxC1F,mBAAmBuG,GAAG,CAACd;YACvBA,aAAajD,MAAM,CAACiP;YACpB,OAAO;gBACLzR,mBAAmBwB,MAAM,CAACiE;YAC5B;QACF;QACA,MAAMiM;YACJ,IAAI5S,YAAY,QAAQ,CAACA,QAAQ8H,sBAAsB,EAAE;YACzD5F,QAAQrC,MAAM,CAAC;YACf5B,gBAAgBrB;YAChBsD,kBAAkB;YAClB,MAAMkH;QACR;IACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/conversation.ts"],"sourcesContent":["import type { QueryDocument, QueryResult } from '@agentshouse/query';\nimport type {\n ConversationAction,\n ConversationCards,\n ConversationEvent,\n ConversationMessage,\n ViewedConversations,\n} from './adapter.js';\nimport { declaredFile, type InstructionFile } from './file.js';\nimport type { CallResult } from './outcome.js';\nimport type { ConversationRecord, InstructionRecord, RuntimeStore } from './store.js';\n\nexport type ConversationEntry = {\n conversation: string;\n card: QueryDocument;\n agent: QueryDocument | null;\n};\n\nexport type GrowingText = { turn: string; text: string };\n\nexport type UnsentInstruction = {\n text: string;\n files: readonly InstructionFile[];\n};\n\nexport type ConversationView = {\n conversation: string;\n messages: readonly ConversationMessage[];\n olderPages: boolean;\n growingText: GrowingText | null;\n summary: unknown;\n instruction: UnsentInstruction | null;\n};\n\nexport type ConversationSurface = {\n list(): Promise<readonly ConversationEntry[]>;\n read(conversation: string): Promise<ConversationView>;\n older(conversation: string): Promise<CallResult | null>;\n compose(conversation: string, instruction: UnsentInstruction): Promise<void>;\n discard(conversation: string): Promise<void>;\n create(input: unknown): Promise<CallResult>;\n send(conversation: string): Promise<CallResult>;\n answer(conversation: string, answer: unknown): Promise<CallResult>;\n interrupt(conversation: string): Promise<CallResult>;\n kill(conversation: string): Promise<CallResult>;\n cancel(conversation: string, turn: string): Promise<CallResult>;\n delete(conversation: string): Promise<CallResult>;\n};\n\nexport type ConversationDependencies = {\n cards(): ConversationCards | undefined;\n documents(): QueryResult;\n call(name: ConversationAction, input: unknown): Promise<CallResult>;\n durably<T>(work: (local: RuntimeStore) => Promise<T>): Promise<T>;\n path(): ViewedConversations | undefined;\n closed(): boolean;\n};\n\nexport type ConversationStore = {\n surface: ConversationSurface;\n hydrate(\n conversations: readonly ConversationRecord[],\n instructions: readonly InstructionRecord[],\n ): void;\n observe(conversation: string, notify: (view: ConversationView) => void): () => void;\n receive(event: ConversationEvent): void;\n close(): void;\n};\n\ntype Held = {\n messages: readonly ConversationMessage[];\n cursor: string | null;\n summary: unknown;\n};\n\ntype Composed = {\n text: string;\n files: readonly InstructionFile[];\n turn: string | null;\n};\n\ntype Viewing = {\n conversation: string;\n notify: (view: ConversationView) => void;\n ready: boolean;\n};\n\ntype HistoryPage = {\n messages: readonly ConversationMessage[];\n cursor: string | null;\n};\n\nconst NO_TURNS: ReadonlySet<string> = new Set();\n\nfunction carriedMessage(value: unknown): ConversationMessage | null {\n if (typeof value !== 'object' || value === null) return null;\n const record = value as { turn?: unknown };\n if (typeof record.turn !== 'string') return null;\n return structuredClone(value) as ConversationMessage;\n}\n\nfunction historyPage(result: CallResult): HistoryPage | null {\n if (result.kind !== 'action') return null;\n const answer = result.result;\n if (typeof answer !== 'object' || answer === null) return null;\n const record = answer as { messages?: unknown; cursor?: unknown };\n if (!Array.isArray(record.messages)) return null;\n const messages: ConversationMessage[] = [];\n for (const entry of record.messages) {\n const carried = carriedMessage(entry);\n if (carried !== null) messages.push(carried);\n }\n return { messages, cursor: typeof record.cursor === 'string' ? record.cursor : null };\n}\n\nfunction turnOf(result: CallResult): string | null {\n if (result.kind !== 'action') return null;\n const answer = result.result;\n if (typeof answer !== 'object' || answer === null) return null;\n const record = answer as { turn?: unknown };\n return typeof record.turn === 'string' ? record.turn : null;\n}\n\nfunction newest(held: Held, page: HistoryPage, arrived: ReadonlySet<string>): Held {\n const arriving = new Set(page.messages.map((entry) => entry.turn));\n const overlap = held.messages.findIndex((entry) => arriving.has(entry.turn));\n const carried = overlap === -1 ? [] : held.messages.slice(0, overlap);\n const placed = new Set([...carried, ...page.messages].map((entry) => entry.turn));\n const live = held.messages.filter((entry) => arrived.has(entry.turn) && !placed.has(entry.turn));\n return {\n ...held,\n messages: [...carried, ...page.messages, ...live],\n cursor: overlap === -1 ? page.cursor : held.cursor,\n };\n}\n\nfunction older(held: Held, page: HistoryPage): Held {\n const present = new Set(held.messages.map((entry) => entry.turn));\n return {\n ...held,\n messages: [...page.messages.filter((entry) => !present.has(entry.turn)), ...held.messages],\n cursor: page.cursor,\n };\n}\n\nfunction sealed(held: Held, arriving: ConversationMessage): Held {\n const at = held.messages.findIndex((entry) => entry.turn === arriving.turn);\n if (at === -1) return { ...held, messages: [...held.messages, arriving] };\n const messages = [...held.messages];\n messages[at] = arriving;\n return { ...held, messages };\n}\n\nexport function createConversationStore(deps: ConversationDependencies): ConversationStore {\n const held = new Map<string, Held>();\n const composed = new Map<string, Composed>();\n const growing = new Map<string, GrowingText>();\n const viewers = new Set<Viewing>();\n const issued = new Map<string, number>();\n const live = new Map<string, Set<string>>();\n let handed: string | undefined;\n\n function heldOf(conversation: string): Held {\n return held.get(conversation) ?? { messages: [], cursor: null, summary: null };\n }\n\n function instructionOf(conversation: string): Composed {\n return composed.get(conversation) ?? { text: '', files: [], turn: null };\n }\n\n function viewOf(conversation: string): ConversationView {\n const carried = heldOf(conversation);\n const unsent = composed.get(conversation);\n return {\n conversation,\n messages: structuredClone(carried.messages),\n olderPages: carried.cursor !== null,\n growingText: growing.get(conversation) ?? null,\n summary: structuredClone(carried.summary),\n instruction:\n unsent === undefined || unsent.turn !== null\n ? null\n : { text: unsent.text, files: [...unsent.files] },\n };\n }\n\n function emit(conversation: string) {\n if (deps.closed()) return;\n for (const viewer of viewers) {\n if (viewer.conversation === conversation && viewer.ready) viewer.notify(viewOf(conversation));\n }\n }\n\n function viewed(): readonly string[] {\n return [...new Set([...viewers].map((viewer) => viewer.conversation))].sort();\n }\n\n function hand() {\n const path = deps.path();\n if (path === undefined) return;\n const open = viewed();\n const named = JSON.stringify(open);\n if (named === handed) return;\n handed = named;\n path.view(open);\n }\n\n function keptRecord(conversation: string): ConversationRecord {\n const carried = heldOf(conversation);\n return {\n conversation,\n messages: carried.messages,\n cursor: carried.cursor,\n summary: carried.summary,\n };\n }\n\n async function settle(local: RuntimeStore, conversation: string) {\n const sent = instructionOf(conversation).turn;\n if (sent === null) return;\n if (!heldOf(conversation).messages.some((entry) => entry.turn === sent)) return;\n composed.delete(conversation);\n await local.dropInstruction(conversation);\n }\n\n async function keep(\n conversation: string,\n next: (carried: Held) => Held | null,\n ): Promise<boolean> {\n const kept = await deps.durably(async (local) => {\n const following = next(heldOf(conversation));\n if (following === null) return false;\n held.set(conversation, following);\n await local.keepConversation(keptRecord(conversation));\n await settle(local, conversation);\n return true;\n });\n if (kept) emit(conversation);\n return kept;\n }\n\n async function keepInstruction(conversation: string, next: (unsent: Composed) => Composed) {\n await deps.durably(async (local) => {\n const stored = next(instructionOf(conversation));\n composed.set(conversation, stored);\n await local.keepInstruction({ conversation, ...stored });\n await settle(local, conversation);\n });\n emit(conversation);\n }\n\n async function dropInstruction(conversation: string) {\n await deps.durably(async (local) => {\n composed.delete(conversation);\n await local.dropInstruction(conversation);\n });\n emit(conversation);\n }\n\n function supersede(conversation: string) {\n issued.set(conversation, (issued.get(conversation) ?? 0) + 1);\n }\n\n async function fill(conversation: string, cursor: string | null): Promise<CallResult> {\n const generation = issued.get(conversation);\n const result = await deps.call('conversation.history', {\n conversation,\n ...(cursor === null ? {} : { cursor }),\n });\n const page = historyPage(result);\n if (page === null) return result;\n const landed = await keep(conversation, (carried) => {\n if (issued.get(conversation) !== generation) return null;\n if (cursor !== null) return carried.cursor === cursor ? older(carried, page) : null;\n return newest(carried, page, live.get(conversation) ?? NO_TURNS);\n });\n if (landed && cursor === null) live.delete(conversation);\n return result;\n }\n\n function invoke(\n name: ConversationAction,\n conversation: string,\n extra: Readonly<Record<string, unknown>> = {},\n ): Promise<CallResult> {\n return deps.call(name, { conversation, ...extra });\n }\n\n const surface: ConversationSurface = {\n list() {\n const declaration = deps.cards();\n if (declaration === undefined) return Promise.resolve([]);\n const documents = deps\n .documents()\n .documents.filter((document) => document.room === declaration.locator);\n const entries: ConversationEntry[] = [];\n for (const card of documents) {\n if (card.type !== declaration.type) continue;\n const identity = card.fields[declaration.identity];\n if (typeof identity !== 'string') continue;\n const agent = documents.find((document) =>\n document.backlinks.some(\n (backlink) => backlink.path === card.path && backlink.field === declaration.agent,\n ),\n );\n entries.push({ conversation: identity, card, agent: agent ?? null });\n }\n entries.sort((left, right) => (left.conversation < right.conversation ? -1 : 1));\n return Promise.resolve(entries);\n },\n read(conversation: string) {\n return deps.durably(() => Promise.resolve(viewOf(conversation)));\n },\n older(conversation: string) {\n const cursor = heldOf(conversation).cursor;\n if (cursor === null) return Promise.resolve(null);\n return fill(conversation, cursor);\n },\n compose(conversation: string, supplied: UnsentInstruction) {\n return keepInstruction(conversation, () => ({\n text: supplied.text,\n files: [...supplied.files],\n turn: null,\n }));\n },\n discard(conversation: string) {\n return dropInstruction(conversation);\n },\n create(input: unknown) {\n return deps.call('conversation.create', input);\n },\n async send(conversation: string) {\n const unsent = instructionOf(conversation);\n const files = await Promise.all(unsent.files.map(declaredFile));\n const result = await invoke('conversation.send', conversation, { text: unsent.text, files });\n const turn = turnOf(result);\n if (turn === null) return result;\n await keepInstruction(conversation, (stored) => ({ ...stored, turn }));\n return result;\n },\n answer(conversation: string, answer: unknown) {\n return invoke('conversation.answer', conversation, { answer });\n },\n interrupt(conversation: string) {\n return invoke('conversation.interrupt', conversation);\n },\n kill(conversation: string) {\n return invoke('conversation.kill', conversation);\n },\n async cancel(conversation: string, turn: string) {\n const result = await invoke('conversation.cancel', conversation, { turn });\n if (result.kind !== 'action') return result;\n if (instructionOf(conversation).turn === turn) {\n await keepInstruction(conversation, (stored) => ({ ...stored, turn: null }));\n }\n return result;\n },\n async delete(conversation: string) {\n const result = await invoke('conversation.delete', conversation);\n if (result.kind !== 'action') return result;\n growing.delete(conversation);\n live.delete(conversation);\n supersede(conversation);\n await deps.durably(async (local) => {\n held.delete(conversation);\n composed.delete(conversation);\n await local.dropConversation(conversation);\n await local.dropInstruction(conversation);\n });\n emit(conversation);\n return result;\n },\n };\n\n return {\n surface,\n hydrate(conversations, instructions) {\n held.clear();\n for (const stored of conversations) {\n held.set(stored.conversation, {\n messages: stored.messages,\n cursor: stored.cursor,\n summary: stored.summary,\n });\n }\n composed.clear();\n for (const stored of instructions) {\n composed.set(stored.conversation, {\n text: stored.text,\n files: stored.files,\n turn: stored.turn,\n });\n }\n },\n observe(conversation: string, notify: (view: ConversationView) => void) {\n const first = !viewed().includes(conversation);\n const viewer: Viewing = { conversation, notify, ready: false };\n viewers.add(viewer);\n if (first) {\n live.set(conversation, new Set());\n supersede(conversation);\n }\n hand();\n void deps\n .durably(() => Promise.resolve())\n .then(async () => {\n if (deps.closed() || !viewers.has(viewer)) return;\n viewer.ready = true;\n viewer.notify(viewOf(conversation));\n if (first) await fill(conversation, null);\n })\n .catch(() => {});\n return () => {\n if (!viewers.delete(viewer)) return;\n if (!viewed().includes(conversation)) {\n growing.delete(conversation);\n live.delete(conversation);\n }\n hand();\n };\n },\n receive(event: ConversationEvent) {\n if (deps.closed() || !viewed().includes(event.conversation)) return;\n if (event.kind === 'growing-text') {\n growing.set(event.conversation, { turn: event.turn, text: event.text });\n emit(event.conversation);\n return;\n }\n if (event.kind === 'session-summary') {\n const summary = structuredClone(event.summary);\n void keep(event.conversation, (carried) => ({ ...carried, summary })).catch(() => {});\n return;\n }\n const arriving = carriedMessage(event.message);\n if (arriving === null) return;\n live.get(event.conversation)?.add(arriving.turn);\n if (growing.get(event.conversation)?.turn === arriving.turn) {\n growing.delete(event.conversation);\n }\n void deps\n .durably(async (local) => {\n held.set(event.conversation, sealed(heldOf(event.conversation), arriving));\n await local.keepConversation(keptRecord(event.conversation));\n await settle(local, event.conversation);\n })\n .then(() => {\n emit(event.conversation);\n })\n .catch(() => {});\n },\n close() {\n viewers.clear();\n growing.clear();\n live.clear();\n },\n };\n}\n"],"names":["declaredFile","NO_TURNS","Set","carriedMessage","value","record","turn","structuredClone","historyPage","result","kind","answer","Array","isArray","messages","entry","carried","push","cursor","turnOf","newest","held","page","arrived","arriving","map","overlap","findIndex","has","slice","placed","live","filter","older","present","sealed","at","createConversationStore","deps","Map","composed","growing","viewers","issued","handed","heldOf","conversation","get","summary","instructionOf","text","files","viewOf","unsent","olderPages","growingText","instruction","undefined","emit","closed","viewer","ready","notify","viewed","sort","hand","path","open","named","JSON","stringify","view","keptRecord","settle","local","sent","some","delete","dropInstruction","keep","next","kept","durably","following","set","keepConversation","keepInstruction","stored","supersede","fill","generation","call","landed","invoke","name","extra","surface","list","declaration","cards","Promise","resolve","documents","document","room","locator","entries","card","type","identity","fields","agent","find","backlinks","backlink","field","left","right","read","compose","supplied","discard","create","input","send","all","interrupt","kill","cancel","dropConversation","hydrate","conversations","instructions","clear","observe","first","includes","add","then","catch","receive","event","message","close"],"mappings":"AAQA,SAASA,YAAY,QAA8B,YAAY;AAoF/D,MAAMC,WAAgC,IAAIC;AAE1C,SAASC,eAAeC,KAAc;IACpC,IAAI,OAAOA,UAAU,YAAYA,UAAU,MAAM,OAAO;IACxD,MAAMC,SAASD;IACf,IAAI,OAAOC,OAAOC,IAAI,KAAK,UAAU,OAAO;IAC5C,OAAOC,gBAAgBH;AACzB;AAEA,SAASI,YAAYC,MAAkB;IACrC,IAAIA,OAAOC,IAAI,KAAK,UAAU,OAAO;IACrC,MAAMC,SAASF,OAAOA,MAAM;IAC5B,IAAI,OAAOE,WAAW,YAAYA,WAAW,MAAM,OAAO;IAC1D,MAAMN,SAASM;IACf,IAAI,CAACC,MAAMC,OAAO,CAACR,OAAOS,QAAQ,GAAG,OAAO;IAC5C,MAAMA,WAAkC,EAAE;IAC1C,KAAK,MAAMC,SAASV,OAAOS,QAAQ,CAAE;QACnC,MAAME,UAAUb,eAAeY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mF,MAAM/F,YAAY;gBACvB;YACF;YACA,IAAI+F,MAAMnI,IAAI,KAAK,mBAAmB;gBACpC,MAAMsC,UAAUzC,gBAAgBsI,MAAM7F,OAAO;gBAC7C,KAAK+B,KAAK8D,MAAM/F,YAAY,EAAE,CAAC9B,UAAa,CAAA;wBAAE,GAAGA,OAAO;wBAAEgC;oBAAQ,CAAA,GAAI2F,KAAK,CAAC,KAAO;gBACnF;YACF;YACA,MAAMnH,WAAWrB,eAAe0I,MAAMC,OAAO;YAC7C,IAAItH,aAAa,MAAM;YACvBO,KAAKgB,GAAG,CAAC8F,MAAM/F,YAAY,GAAG2F,IAAIjH,SAASlB,IAAI;YAC/C,IAAImC,QAAQM,GAAG,CAAC8F,MAAM/F,YAAY,GAAGxC,SAASkB,SAASlB,IAAI,EAAE;gBAC3DmC,QAAQoC,MAAM,CAACgE,MAAM/F,YAAY;YACnC;YACA,KAAKR,KACF4C,OAAO,CAAC,OAAOR;gBACdrD,KAAK+D,GAAG,CAACyD,MAAM/F,YAAY,EAAEX,OAAOU,OAAOgG,MAAM/F,YAAY,GAAGtB;gBAChE,MAAMkD,MAAMW,gBAAgB,CAACb,WAAWqE,MAAM/F,YAAY;gBAC1D,MAAM2B,OAAOC,OAAOmE,MAAM/F,YAAY;YACxC,GACC4F,IAAI,CAAC;gBACJhF,KAAKmF,MAAM/F,YAAY;YACzB,GACC6F,KAAK,CAAC,KAAO;QAClB;QACAI;YACErG,QAAQ2F,KAAK;YACb5F,QAAQ4F,KAAK;YACbtG,KAAKsG,KAAK;QACZ;IACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/durability.ts"],"sourcesContent":["const STORAGE_LOSS_STATEMENT = 'Unsynchronized Drafts and Pending Changes were lost.';\n\nexport type RuntimeShell = {\n persistentStorage: boolean;\n generation: string | null;\n keepGeneration(value: string): void | Promise<void>;\n dropGeneration(): void | Promise<void>;\n};\n\nexport function detectStorageLoss(stored: string | null, reported: string | null): string | null {\n if (reported === null || reported === stored) return null;\n return STORAGE_LOSS_STATEMENT;\n}\n\nexport function nextGeneration(stored: string | null, reported: string | null): string {\n if (stored !== null && (reported === null || reported === stored)) return stored;\n return crypto.randomUUID();\n}\n"],"names":["STORAGE_LOSS_STATEMENT","detectStorageLoss","stored","reported","nextGeneration","crypto","randomUUID"],"mappings":"AAAA,MAAMA,yBAAyB;AAS/B,OAAO,SAASC,kBAAkBC,MAAqB,EAAEC,QAAuB;IAC9E,IAAIA,aAAa,QAAQA,aAAaD,QAAQ,OAAO;IACrD,OAAOF;AACT;AAEA,OAAO,SAASI,eAAeF,MAAqB,EAAEC,QAAuB;IAC3E,IAAID,WAAW,QAASC,CAAAA,aAAa,QAAQA,aAAaD,MAAK,GAAI,OAAOA;IAC1E,OAAOG,OAAOC,UAAU;AAC1B"}
package/dist/file.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/file.ts"],"sourcesContent":["export type InstructionFile = {\n name: string;\n blob: Blob;\n};\n\nexport type FileDeclaration = {\n name: string;\n mediaType: string;\n byteLength: number;\n contentHash: string;\n width?: number;\n height?: number;\n};\n\nexport type Extent = { width: number; height: number };\n\nconst PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\nconst WEBP_SYNC = [0x9d, 0x01, 0x2a];\nconst SHAPELESS_JPEG_MARKERS = new Set([0xc4, 0xc8, 0xcc]);\nconst BMFF_CONTAINERS = new Set(['meta', 'iprp', 'ipco']);\n\nfunction starts(bytes: Uint8Array, signature: readonly number[], at = 0): boolean {\n return signature.every((value, index) => bytes[at + index] === value);\n}\n\nfunction text(bytes: Uint8Array, at: number, length: number): string {\n return String.fromCharCode(...bytes.subarray(at, at + length));\n}\n\nfunction bigEndian(bytes: Uint8Array, at: number, length: number): number {\n let value = 0;\n for (let index = 0; index < length; index += 1) value = value * 256 + (bytes[at + index] ?? 0);\n return value;\n}\n\nfunction littleEndian(bytes: Uint8Array, at: number, length: number): number {\n let value = 0;\n for (let index = length - 1; index >= 0; index -= 1)\n value = value * 256 + (bytes[at + index] ?? 0);\n return value;\n}\n\nfunction pngExtent(bytes: Uint8Array): Extent | null {\n if (bytes.length < 24 || !starts(bytes, PNG_SIGNATURE)) return null;\n if (text(bytes, 12, 4) !== 'IHDR') return null;\n return { width: bigEndian(bytes, 16, 4), height: bigEndian(bytes, 20, 4) };\n}\n\nfunction gifExtent(bytes: Uint8Array): Extent | null {\n if (bytes.length < 10 || text(bytes, 0, 3) !== 'GIF') return null;\n return { width: littleEndian(bytes, 6, 2), height: littleEndian(bytes, 8, 2) };\n}\n\nfunction jpegExtent(bytes: Uint8Array): Extent | null {\n if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) return null;\n let at = 2;\n while (at + 9 < bytes.length) {\n if (bytes[at] !== 0xff) return null;\n const marker = bytes[at + 1] ?? 0;\n if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {\n at += 2;\n continue;\n }\n const length = bigEndian(bytes, at + 2, 2);\n if (marker >= 0xc0 && marker <= 0xcf && !SHAPELESS_JPEG_MARKERS.has(marker)) {\n return { width: bigEndian(bytes, at + 7, 2), height: bigEndian(bytes, at + 5, 2) };\n }\n if (length < 2) return null;\n at += 2 + length;\n }\n return null;\n}\n\nfunction webpExtent(bytes: Uint8Array): Extent | null {\n if (bytes.length < 30 || text(bytes, 0, 4) !== 'RIFF' || text(bytes, 8, 4) !== 'WEBP')\n return null;\n const chunk = text(bytes, 12, 4);\n if (chunk === 'VP8X') {\n return {\n width: littleEndian(bytes, 24, 3) + 1,\n height: littleEndian(bytes, 27, 3) + 1,\n };\n }\n if (chunk === 'VP8 ' && starts(bytes, WEBP_SYNC, 23)) {\n return {\n width: littleEndian(bytes, 26, 2) & 0x3fff,\n height: littleEndian(bytes, 28, 2) & 0x3fff,\n };\n }\n if (chunk === 'VP8L' && bytes[20] === 0x2f) {\n const packed = littleEndian(bytes, 21, 4);\n return { width: (packed & 0x3fff) + 1, height: ((packed >>> 14) & 0x3fff) + 1 };\n }\n return null;\n}\n\nfunction spatialExtent(bytes: Uint8Array, from: number, to: number): Extent | null {\n let at = from;\n while (at + 8 <= to) {\n const size = bigEndian(bytes, at, 4);\n const name = text(bytes, at + 4, 4);\n const end = size === 0 ? to : at + size;\n if (size === 1 || end <= at || end > to) return null;\n if (name === 'ispe') {\n if (end < at + 20) return null;\n return { width: bigEndian(bytes, at + 12, 4), height: bigEndian(bytes, at + 16, 4) };\n }\n if (BMFF_CONTAINERS.has(name)) {\n const inner = spatialExtent(bytes, at + (name === 'meta' ? 12 : 8), end);\n if (inner !== null) return inner;\n }\n at = end;\n }\n return null;\n}\n\nfunction bmffExtent(bytes: Uint8Array): Extent | null {\n if (bytes.length < 16 || text(bytes, 4, 4) !== 'ftyp') return null;\n return spatialExtent(bytes, 0, bytes.length);\n}\n\nexport function extentOf(bytes: Uint8Array): Extent | null {\n return (\n pngExtent(bytes) ??\n jpegExtent(bytes) ??\n gifExtent(bytes) ??\n webpExtent(bytes) ??\n bmffExtent(bytes)\n );\n}\n\nexport function hexDigest(digest: ArrayBuffer): string {\n return [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, '0')).join('');\n}\n\nexport async function declaredFile(file: InstructionFile): Promise<FileDeclaration> {\n const bytes = new Uint8Array(await file.blob.arrayBuffer());\n const extent = file.blob.type.startsWith('image/') ? extentOf(bytes) : null;\n return {\n name: file.name,\n mediaType: file.blob.type,\n byteLength: bytes.byteLength,\n contentHash: hexDigest(await crypto.subtle.digest('SHA-256', bytes)),\n ...(extent === null ? {} : extent),\n };\n}\n"],"names":["PNG_SIGNATURE","WEBP_SYNC","SHAPELESS_JPEG_MARKERS","Set","BMFF_CONTAINERS","starts","bytes","signature","at","every","value","index","text","length","String","fromCharCode","subarray","bigEndian","littleEndian","pngExtent","width","height","gifExtent","jpegExtent","marker","has","webpExtent","chunk","packed","spatialExtent","from","to","size","name","end","inner","bmffExtent","extentOf","hexDigest","digest","Uint8Array","map","toString","padStart","join","declaredFile","file","blob","arrayBuffer","extent","type","startsWith","mediaType","byteLength","contentHash","crypto","subtle"],"mappings":"AAgBA,MAAMA,gBAAgB;IAAC;IAAM;IAAM;IAAM;IAAM;IAAM;IAAM;IAAM;CAAK;AACtE,MAAMC,YAAY;IAAC;IAAM;IAAM;CAAK;AACpC,MAAMC,yBAAyB,IAAIC,IAAI;IAAC;IAAM;IAAM;CAAK;AACzD,MAAMC,kBAAkB,IAAID,IAAI;IAAC;IAAQ;IAAQ;CAAO;AAExD,SAASE,OAAOC,KAAiB,EAAEC,SAA4B,EAAEC,KAAK,CAAC;IACrE,OAAOD,UAAUE,KAAK,CAAC,CAACC,OAAOC,QAAUL,KAAK,CAACE,KAAKG,MAAM,KAAKD;AACjE;AAEA,SAASE,KAAKN,KAAiB,EAAEE,EAAU,EAAEK,MAAc;IACzD,OAAOC,OAAOC,YAAY,IAAIT,MAAMU,QAAQ,CAACR,IAAIA,KAAKK;AACxD;AAEA,SAASI,UAAUX,KAAiB,EAAEE,EAAU,EAAEK,MAAc;IAC9D,IAAIH,QAAQ;IACZ,IAAK,IAAIC,QAAQ,GAAGA,QAAQE,QAAQF,SAAS,EAAGD,QAAQA,QAAQ,MAAOJ,CAAAA,KAAK,CAACE,KAAKG,MAAM,IAAI,CAAA;IAC5F,OAAOD;AACT;AAEA,SAASQ,aAAaZ,KAAiB,EAAEE,EAAU,EAAEK,MAAc;IACjE,IAAIH,QAAQ;IACZ,IAAK,IAAIC,QAAQE,SAAS,GAAGF,SAAS,GAAGA,SAAS,EAChDD,QAAQA,QAAQ,MAAOJ,CAAAA,KAAK,CAACE,KAAKG,MAAM,IAAI,CAAA;IAC9C,OAAOD;AACT;AAEA,SAASS,UAAUb,KAAiB;IAClC,IAAIA,MAAMO,MAAM,GAAG,MAAM,CAACR,OAAOC,OAAON,gBAAgB,OAAO;IAC/D,IAAIY,KAAKN,OAAO,IAAI,OA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O,MAAM,GAAG,MAAMD,KAAKN,OAAO,GAAG,OAAO,QAAQ,OAAO;IAC9D,OAAOuB,cAAcvB,OAAO,GAAGA,MAAMO,MAAM;AAC7C;AAEA,OAAO,SAASwB,SAAS/B,KAAiB;IACxC,OACEa,UAAUb,UACViB,WAAWjB,UACXgB,UAAUhB,UACVoB,WAAWpB,UACX8B,WAAW9B;AAEf;AAEA,OAAO,SAASgC,UAAUC,MAAmB;IAC3C,OAAO;WAAI,IAAIC,WAAWD;KAAQ,CAACE,GAAG,CAAC,CAAC/B,QAAUA,MAAMgC,QAAQ,CAAC,IAAIC,QAAQ,CAAC,GAAG,MAAMC,IAAI,CAAC;AAC9F;AAEA,OAAO,eAAeC,aAAaC,IAAqB;IACtD,MAAMxC,QAAQ,IAAIkC,WAAW,MAAMM,KAAKC,IAAI,CAACC,WAAW;IACxD,MAAMC,SAASH,KAAKC,IAAI,CAACG,IAAI,CAACC,UAAU,CAAC,YAAYd,SAAS/B,SAAS;IACvE,OAAO;QACL2B,MAAMa,KAAKb,IAAI;QACfmB,WAAWN,KAAKC,IAAI,CAACG,IAAI;QACzBG,YAAY/C,MAAM+C,UAAU;QAC5BC,aAAahB,UAAU,MAAMiB,OAAOC,MAAM,CAACjB,MAAM,CAAC,WAAWjC;QAC7D,GAAI2C,WAAW,OAAO,CAAC,IAAIA,MAAM;IACnC;AACF"}
package/dist/host.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/host.ts"],"sourcesContent":["import type { QueryOptions } from '@agentshouse/query';\nimport type { Change } from './change.js';\nimport {\n createMdRuntime,\n type HistoryQuery,\n type MdRuntime,\n type MdRuntimeOptions,\n} from './connection.js';\nimport type { UnsentInstruction } from './conversation.js';\nimport { removeRuntimeStore } from './store.js';\nimport {\n AUTHORIZATION_ENDED,\n carried,\n envelope,\n PROTOCOL_MISMATCH,\n request,\n type RuntimePort,\n type WireAnswer,\n type WireMember,\n type WireRequest,\n type WireTopic,\n} from './wire.js';\n\nexport type MdRuntimeHost = {\n attach(port: RuntimePort, app: string): () => void;\n endAuthorization(): Promise<void>;\n};\n\nfunction answered(\n md: MdRuntime,\n app: string,\n member: WireMember,\n input: readonly unknown[],\n): unknown {\n switch (member) {\n case 'rooms':\n return md.rooms();\n case 'query':\n return md.query(input[0] as QueryOptions | undefined);\n case 'types':\n return md.types(input[0] as string);\n case 'syncStatus':\n return md.syncStatus();\n case 'save':\n return md.save(\n input[0] as string,\n input[1] as readonly Change[],\n input[2] as string | undefined,\n );\n case 'outcome':\n return md.outcome(input[0] as string);\n case 'history':\n return md.history(input[0] as string, input[1] as string, input[2] as HistoryQuery);\n case 'call':\n return md.call(input[0] as string, input[1]);\n case 'log':\n return md.log();\n case 'storageLoss':\n return md.storageLoss();\n case 'persistence':\n return md.persistence();\n case 'reauthorize':\n return md.reauthorize();\n case 'draft.list':\n return md.draft.list();\n case 'draft.read':\n return md.draft.read(input[0] as string, input[1] as string);\n case 'draft.replace':\n return md.draft.replace(input[0] as string, input[1] as string, input[2]);\n case 'draft.discard':\n return md.draft.discard(input[0] as string, input[1] as string);\n case 'queue.discard':\n return md.queue.discard(input[0] as string, input[1] as string);\n case 'presentation.read':\n return md.presentation.read(app);\n case 'presentation.write':\n return md.presentation.write(app, input[0]);\n case 'conversation.list':\n return md.conversation.list();\n case 'conversation.read':\n return md.conversation.read(input[0] as string);\n case 'conversation.older':\n return md.conversation.older(input[0] as string);\n case 'conversation.compose':\n return md.conversation.compose(input[0] as string, input[1] as UnsentInstruction);\n case 'conversation.discard':\n return md.conversation.discard(input[0] as string);\n case 'conversation.create':\n return md.conversation.create(input[0]);\n case 'conversation.send':\n return md.conversation.send(input[0] as string);\n case 'conversation.answer':\n return md.conversation.answer(input[0] as string, input[1]);\n case 'conversation.interrupt':\n return md.conversation.interrupt(input[0] as string);\n case 'conversation.kill':\n return md.conversation.kill(input[0] as string);\n case 'conversation.cancel':\n return md.conversation.cancel(input[0] as string, input[1] as string);\n case 'conversation.delete':\n return md.conversation.delete(input[0] as string);\n }\n}\n\nfunction subscribed(\n md: MdRuntime,\n app: string,\n topic: WireTopic,\n input: readonly unknown[],\n deliver: (value: unknown) => void,\n): () => void {\n switch (topic) {\n case 'rooms':\n return md.observe('rooms', deliver);\n case 'connection-refusal':\n return md.observe('connection-refusal', deliver);\n case 'storage-loss':\n return md.observe('storage-loss', deliver);\n case 'sync-status':\n return md.observe('sync-status', deliver);\n case 'drafts':\n return md.observe('drafts', deliver);\n case 'queue':\n return md.observe('queue', input[0] as string, deliver);\n case 'query':\n return md.observe('query', input[0] as QueryOptions, deliver);\n case 'presentation':\n return md.observe('presentation', app, deliver);\n case 'conversation':\n return md.observe('conversation', input[0] as string, deliver);\n }\n}\n\nexport function serveMdRuntime(options: MdRuntimeOptions): MdRuntimeHost {\n const stopping = new AbortController();\n const stop = () => {\n stopping.abort();\n };\n options.signal?.addEventListener('abort', stop, { once: true });\n if (options.signal?.aborted === true) stop();\n const md = createMdRuntime({ ...options, signal: stopping.signal });\n const attachments = new Map<() => void, (message: WireAnswer) => void>();\n let authorized = true;\n\n function attach(port: RuntimePort, app: string): () => void {\n if (!authorized) throw new Error(AUTHORIZATION_ENDED);\n const subscriptions = new Map<number, () => void>();\n let serving = true;\n const send = (message: WireAnswer) => {\n port.postMessage(envelope(message));\n };\n const detach = () => {\n if (!serving) return;\n serving = false;\n for (const end of subscriptions.values()) end();\n subscriptions.clear();\n attachments.delete(detach);\n };\n const serve = async (message: WireRequest) => {\n if (message.kind === 'hello') return;\n if (message.kind === 'stop') {\n subscriptions.get(message.id)?.();\n subscriptions.delete(message.id);\n return;\n }\n try {\n if (message.kind === 'observe') {\n subscriptions.set(\n message.id,\n subscribed(md, app, message.topic, message.input, (value) => {\n if (serving) send({ kind: 'event', id: message.id, value });\n }),\n );\n if (serving) send({ kind: 'result', id: message.id, value: null });\n return;\n }\n const value = await answered(md, app, message.member, message.input);\n if (serving) send({ kind: 'result', id: message.id, value });\n } catch (error) {\n if (serving) {\n send({\n kind: 'failure',\n id: message.id,\n message: error instanceof Error ? error.message : String(error),\n });\n }\n }\n };\n port.addEventListener('message', (event) => {\n if (!serving) return;\n const wire = carried(event.data);\n if (wire === null) return;\n if (!wire.matching) {\n send({ kind: 'refusal', refusal: PROTOCOL_MISMATCH });\n detach();\n return;\n }\n const message = request(wire.message);\n if (message === null) return;\n void serve(message);\n });\n port.addEventListener('close', detach);\n port.start();\n attachments.set(detach, send);\n return detach;\n }\n\n return {\n attach,\n async endAuthorization() {\n authorized = false;\n for (const [detach, send] of [...attachments]) {\n send({ kind: 'ended' });\n detach();\n }\n stop();\n await removeRuntimeStore();\n await options.shell.dropGeneration();\n },\n };\n}\n\nexport type { RuntimePort } from './wire.js';\n"],"names":["createMdRuntime","removeRuntimeStore","AUTHORIZATION_ENDED","carried","envelope","PROTOCOL_MISMATCH","request","answered","md","app","member","input","rooms","query","types","syncStatus","save","outcome","history","call","log","storageLoss","persistence","reauthorize","draft","list","read","replace","discard","queue","presentation","write","conversation","older","compose","create","send","answer","interrupt","kill","cancel","delete","subscribed","topic","deliver","observe","serveMdRuntime","options","stopping","AbortController","stop","abort","signal","addEventListener","once","aborted","attachments","Map","authorized","attach","port","Error","subscriptions","serving","message","postMessage","detach","end","values","clear","serve","kind","get","id","set","value","error","String","event","wire","data","matching","refusal","start","endAuthorization","shell","dropGeneration"],"mappings":"AAEA,SACEA,eAAe,QAIV,kBAAkB;AAEzB,SAASC,kBAAkB,QAAQ,aAAa;AAChD,SACEC,mBAAmB,EACnBC,OAAO,EACPC,QAAQ,EACRC,iBAAiB,EACjBC,OAAO,QAMF,YAAY;AAOnB,SAASC,SACPC,EAAa,EACbC,GAAW,EACXC,MAAkB,EAClBC,KAAyB;IAEzB,OAAQD;QACN,KAAK;YACH,OAAOF,GAAGI,KAAK;QACjB,KAAK;YACH,OAAOJ,GAAGK,KAAK,CAACF,KAAK,CAAC,EAAE;QAC1B,KAAK;YACH,OAAOH,GAAGM,KAAK,CAACH,KAAK,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B,KAAK;QACV3B,YAAYkB,GAAG,CAACR,QAAQ9B;QACxB,OAAO8B;IACT;IAEA,OAAO;QACLP;QACA,MAAMyB;YACJ1B,aAAa;YACb,KAAK,MAAM,CAACQ,QAAQ9B,KAAK,IAAI;mBAAIoB;aAAY,CAAE;gBAC7CpB,KAAK;oBAAEmC,MAAM;gBAAQ;gBACrBL;YACF;YACAhB;YACA,MAAMjD;YACN,MAAM8C,QAAQsC,KAAK,CAACC,cAAc;QACpC;IACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/identity.ts"],"sourcesContent":["export function changeBatchIdentity(at: number = Date.now()): string {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n const time = BigInt(at);\n for (let index = 0; index < 6; index += 1) {\n bytes[index] = Number((time >> BigInt(8 * (5 - index))) & 0xffn);\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x70;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n"],"names":["changeBatchIdentity","at","Date","now","bytes","Uint8Array","crypto","getRandomValues","time","BigInt","index","Number","hex","map","byte","toString","padStart","join","slice"],"mappings":"AAAA,OAAO,SAASA,oBAAoBC,KAAaC,KAAKC,GAAG,EAAE;IACzD,MAAMC,QAAQ,IAAIC,WAAW;IAC7BC,OAAOC,eAAe,CAACH;IACvB,MAAMI,OAAOC,OAAOR;IACpB,IAAK,IAAIS,QAAQ,GAAGA,QAAQ,GAAGA,SAAS,EAAG;QACzCN,KAAK,CAACM,MAAM,GAAGC,OAAO,AAACH,QAAQC,OAAO,IAAK,CAAA,IAAIC,KAAI,KAAO,KAAK;IACjE;IACAN,KAAK,CAAC,EAAE,GAAG,AAACA,KAAK,CAAC,EAAE,GAAG,OAAQ;IAC/BA,KAAK,CAAC,EAAE,GAAG,AAACA,KAAK,CAAC,EAAE,GAAG,OAAQ;IAC/B,MAAMQ,MAAM;WAAIR;KAAM,CAACS,GAAG,CAAC,CAACC,OAASA,KAAKC,QAAQ,CAAC,IAAIC,QAAQ,CAAC,GAAG,MAAMC,IAAI,CAAC;IAC9E,OAAO,GAAGL,IAAIM,KAAK,CAAC,GAAG,GAAG,CAAC,EAAEN,IAAIM,KAAK,CAAC,GAAG,IAAI,CAAC,EAAEN,IAAIM,KAAK,CAAC,IAAI,IAAI,CAAC,EAAEN,IAAIM,KAAK,CAAC,IAAI,IAAI,CAAC,EAAEN,IAAIM,KAAK,CAAC,KAAK;AAC5G"}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/index.ts"],"sourcesContent":["export type {\n ActionDeclaration,\n ActionRequest,\n ActionResult,\n Adapter,\n AdapterFailure,\n Authorization,\n BootstrapPage,\n BootstrapRequest,\n BootstrapResult,\n Capability,\n ContractUnavailable,\n ConversationAction,\n ConversationCards,\n ConversationEvent,\n ConversationMessage,\n DiscoverResult,\n DiscoveredRoom,\n Discovery,\n HistoryRequest,\n HistoryResult,\n HistoryRetention,\n HistoryRevision,\n MdModelIdentity,\n ModelRequest,\n MutationRequest,\n MutationResult,\n PageToken,\n ProviderLimit,\n ProviderRefusal,\n RefreshPage,\n RefreshRequest,\n RefreshResult,\n Retention,\n RetryableRefusal,\n RevokedAuthorization,\n RoomNotReadable,\n RoomVersionNotification,\n SelectedRooms,\n TransportUncertainty,\n TypedSelection,\n ViewedConversations,\n} from './adapter.js';\nexport type { Change, ChangeBatch, Precondition } from './change.js';\nexport type {\n ConversationEntry,\n ConversationSurface,\n ConversationView,\n GrowingText,\n UnsentInstruction,\n} from './conversation.js';\nexport type { FileDeclaration, InstructionFile } from './file.js';\nexport type { MdType } from './collection.js';\nexport type {\n AppRoom,\n AppTypedSelection,\n ConnectionRefusal,\n ConnectionRefusalReason,\n DraftEntry,\n DraftSurface,\n HistoryQuery,\n MdRuntime,\n MdRuntimeOptions,\n PresentationSurface,\n QueueSurface,\n RoomTypes,\n SaveResult,\n} from './connection.js';\nexport type {\n AcceptedOutcome,\n AffectedState,\n CallResult,\n QueueEntry,\n QueueOutcome,\n SubmissionOutcome,\n} from './outcome.js';\nexport type { SaveRefusal } from './save.js';\nexport { createMdRuntime } from './connection.js';\nexport type { RuntimeShell } from './durability.js';\nexport type { AttentionEntry, SyncStatus } from './status.js';\nexport type {\n Backlink,\n QueryDocument,\n QueryGroup,\n QueryOptions,\n QueryResult,\n Selector,\n} from '@agentshouse/query';\n\nexport type {\n AttachedModelBinding,\n ModelIdentity,\n ModelSnapshot,\n ModelState,\n ModelResult,\n ModelValidation,\n TypesResult,\n ValidationReceipt,\n} from './model.js';\nexport type { OperationScopes, ReplicaAdmission, ScopedRefusal } from './adapter.js';\nexport type { QueryBinding, QueryInput } from './query.js';\n"],"names":["createMdRuntime"],"mappings":"AA6EA,SAASA,eAAe,QAAQ,kBAAkB"}
package/dist/log.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/log.ts"],"sourcesContent":["const BOUND = 256;\n\nexport function createLog() {\n const events: string[] = [];\n return {\n record(event: string) {\n events.push(event);\n if (events.length > BOUND) events.splice(0, events.length - BOUND);\n },\n export() {\n return events.join('\\n');\n },\n };\n}\n"],"names":["BOUND","createLog","events","record","event","push","length","splice","export","join"],"mappings":"AAAA,MAAMA,QAAQ;AAEd,OAAO,SAASC;IACd,MAAMC,SAAmB,EAAE;IAC3B,OAAO;QACLC,QAAOC,KAAa;YAClBF,OAAOG,IAAI,CAACD;YACZ,IAAIF,OAAOI,MAAM,GAAGN,OAAOE,OAAOK,MAAM,CAAC,GAAGL,OAAOI,MAAM,GAAGN;QAC9D;QACAQ;YACE,OAAON,OAAOO,IAAI,CAAC;QACrB;IACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/memory.ts"],"sourcesContent":["import type { ModelResult } from './model.js';\nimport {\n ROOM_CONTRACT_VERSION,\n type ActionRequest,\n type ActionResult,\n type Adapter,\n type Authorization,\n type BootstrapRequest,\n type BootstrapResult,\n type Capability,\n type ConversationAction,\n type ConversationEvent,\n type ConversationMessage,\n type DiscoverResult,\n type DiscoveredRoom,\n type HistoryRequest,\n type HistoryResult,\n type MdModelIdentity,\n type MutationRequest,\n type MutationResult,\n type ProviderLimit,\n type RefreshRequest,\n type RefreshResult,\n type Retention,\n type RoomVersionNotification,\n} from './adapter.js';\nimport { MD_MODEL } from './collection.js';\n\nconst FIXTURE_RETENTION: Retention = {\n history: { kind: 'duration', seconds: 1 },\n outcome: 1,\n refreshHorizon: 1,\n};\n\nfunction declaredRetention(value: Retention | undefined): Retention {\n const retention = value ?? FIXTURE_RETENTION;\n if (retention.history.kind === 'no-declared-time-bound') return retention;\n if (Number.isFinite(retention.history.seconds) && retention.history.seconds > 0) {\n return retention;\n }\n throw new Error('history retention duration must be a finite positive number of seconds');\n}\n\nexport type MemoryRoom = DiscoveredRoom & {\n model?: ModelResult;\n selectionModel?: ModelResult;\n documents?: Readonly<Record<string, string>>;\n revisions?: Readonly<Record<string, string>>;\n binaryTargets?: readonly string[];\n};\n\nexport type MemoryConversation = {\n conversation: string;\n messages?: readonly ConversationMessage[];\n outcomes?: Partial<Record<ConversationAction, ActionResult>>;\n};\n\nexport type MemoryAdapterOptions = {\n rooms?: readonly MemoryRoom[];\n conversations?: readonly MemoryConversation[];\n historyPageSize?: number;\n pageSize?: number;\n mdModel?: MdModelIdentity;\n supportedVersions?: readonly number[];\n capabilities?: readonly Capability[];\n providerLimits?: readonly ProviderLimit[];\n retention?: Retention;\n};\n\nexport type MemoryAdapter = Adapter & {\n setRooms(rooms: readonly MemoryRoom[]): void;\n setConversations(conversations: readonly MemoryConversation[]): void;\n script(operation: keyof Adapter, answer: unknown): void;\n notifyRoomVersion(notification: RoomVersionNotification): void;\n notifyConversation(event: ConversationEvent): void;\n selectedRooms(): readonly string[];\n viewedConversations(): readonly string[];\n};\n\ntype Script<T, R> = T | ((request: R) => T | Promise<T>);\n\ntype RefreshContinuation = {\n room: MemoryRoom;\n from: MemoryRoom;\n at: number;\n};\n\nfunction named(\n source: Readonly<Record<string, string>>,\n paths: readonly string[],\n): Readonly<Record<string, string>> {\n const taken: Record<string, string> = {};\n for (const path of paths) {\n const value = source[path];\n if (value !== undefined) taken[path] = value;\n }\n return taken;\n}\n\nasync function resolveScript<T, R>(\n answer: Script<T, R> | undefined,\n fallback: () => T | Promise<T>,\n request: R,\n) {\n if (answer === undefined) return fallback();\n return typeof answer === 'function' ? (answer as (value: R) => T | Promise<T>)(request) : answer;\n}\n\nexport function createMemoryAdapter(options: MemoryAdapterOptions = {}): MemoryAdapter {\n let rooms = options.rooms === undefined ? [] : [...options.rooms];\n const mdModel = options.mdModel ?? MD_MODEL;\n const supportedVersions = options.supportedVersions ?? [ROOM_CONTRACT_VERSION];\n const capabilities = options.capabilities ?? [];\n const providerLimits = options.providerLimits ?? [];\n const retention = declaredRetention(options.retention);\n const pageSize = options.pageSize;\n const scripts: Partial<Record<keyof Adapter, unknown>> = {};\n const served = new Map<string, Map<string, MemoryRoom>>();\n const refreshPages = new Map<string, RefreshContinuation>();\n const observers = new Set<(notification: RoomVersionNotification) => void>();\n const listeners = new Set<(event: ConversationEvent) => void>();\n const scripted = new Map<string, MemoryConversation>();\n const unsealed = new Map<string, string>();\n const sealed = new Set<string>();\n const historyPageSize = options.historyPageSize;\n let selected: readonly string[] = [];\n let viewed: readonly string[] = [];\n let issued = 0;\n\n function scriptConversations(entries: readonly MemoryConversation[]) {\n scripted.clear();\n for (const entry of entries) scripted.set(entry.conversation, entry);\n }\n\n scriptConversations(options.conversations ?? []);\n\n function retain(entries: readonly MemoryRoom[]) {\n for (const room of entries) {\n const versions = served.get(room.locator) ?? new Map<string, MemoryRoom>();\n versions.set(room.roomVersion, room);\n served.set(room.locator, versions);\n }\n }\n\n retain(rooms);\n\n function declared(room: MemoryRoom): DiscoveredRoom {\n return {\n name: room.name,\n locator: room.locator,\n collectionRoot: room.collectionRoot,\n roomVersion: room.roomVersion,\n operations: room.operations,\n replica: room.replica,\n attachedModel: room.attachedModel,\n ...(room.typedSelection === undefined ? {} : { typedSelection: room.typedSelection }),\n providerOwnedPaths: room.providerOwnedPaths,\n };\n }\n\n function page(room: MemoryRoom, from: number): BootstrapResult {\n const paths = Object.keys(room.documents ?? {}).sort();\n const size = pageSize ?? paths.length;\n const taken = paths.slice(from, from + size);\n const next = from + taken.length;\n return {\n kind: 'bootstrap',\n roomVersion: room.roomVersion,\n documents: named(room.documents ?? {}, taken),\n revisions: named(room.revisions ?? {}, taken),\n binaryTargets: from === 0 ? (room.binaryTargets ?? []) : [],\n ...(next < paths.length ? { pageToken: String(next) } : {}),\n };\n }\n\n function advancement(room: MemoryRoom, from: MemoryRoom, at: number): RefreshResult {\n const current = room.documents ?? {};\n const previous = from.documents ?? {};\n const currentTargets = new Set(room.binaryTargets ?? []);\n const previousTargets = new Set(from.binaryTargets ?? []);\n const changed = Object.keys(current)\n .filter((path) => current[path] !== previous[path])\n .sort();\n const size = pageSize ?? changed.length;\n const taken = changed.slice(at, at + size);\n const next = at + taken.length;\n const opening = at === 0;\n const pageToken = next < changed.length ? `refresh-${refreshPages.size}` : undefined;\n if (pageToken !== undefined) refreshPages.set(pageToken, { room, from, at: next });\n return {\n kind: 'net-advancement',\n roomVersion: room.roomVersion,\n documents: named(current, taken),\n revisions: named(room.revisions ?? {}, taken),\n binaryTargets: opening\n ? [...currentTargets].filter((target) => !previousTargets.has(target))\n : [],\n removals: opening\n ? [\n ...Object.keys(previous).filter(\n (path) => !(path in current) && !currentTargets.has(path),\n ),\n ...[...previousTargets].filter(\n (target) => !currentTargets.has(target) && !(target in current),\n ),\n ].sort()\n : [],\n ...(pageToken === undefined ? {} : { pageToken }),\n };\n }\n\n function historyOf(conversation: MemoryConversation, cursor: unknown): ActionResult {\n const messages = conversation.messages ?? [];\n const until = typeof cursor === 'string' ? Number(cursor) : messages.length;\n if (!Number.isInteger(until) || until < 0 || until > messages.length) {\n return { kind: 'rejected', code: 'unknown-cursor', fields: { cursor } };\n }\n const size = historyPageSize ?? messages.length;\n const from = Math.max(0, until - size);\n return {\n kind: 'action',\n result: {\n messages: messages.slice(from, until),\n ...(from === 0 ? {} : { cursor: String(from) }),\n },\n };\n }\n\n function conversationAction(request: ActionRequest): ActionResult {\n const name = request.name as ConversationAction;\n const input = (request.input ?? {}) as {\n conversation?: unknown;\n turn?: unknown;\n cursor?: unknown;\n };\n if (name === 'conversation.create') {\n issued += 1;\n const conversation = `conversation-${issued}`;\n scripted.set(conversation, { conversation });\n return { kind: 'action', result: { conversation } };\n }\n const named = typeof input.conversation === 'string' ? input.conversation : '';\n const conversation = scripted.get(named);\n if (conversation === undefined) {\n return { kind: 'rejected', code: 'unknown-conversation', fields: { conversation: named } };\n }\n const outcome = conversation.outcomes?.[name];\n if (outcome !== undefined) return outcome;\n if (name === 'conversation.history') return historyOf(conversation, input.cursor);\n if (name === 'conversation.send') {\n issued += 1;\n const turn = `turn-${issued}`;\n unsealed.set(turn, named);\n return { kind: 'action', result: { turn } };\n }\n if (name === 'conversation.cancel') {\n const turn = typeof input.turn === 'string' ? input.turn : '';\n if (sealed.has(turn) || !unsealed.has(turn)) {\n return { kind: 'rejected', code: 'turn-sealed', fields: { turn } };\n }\n unsealed.delete(turn);\n return { kind: 'action', result: { turn, cancelled: true } };\n }\n if (name === 'conversation.delete') scripted.delete(named);\n return { kind: 'action', result: { conversation: named } };\n }\n\n function discovery(): DiscoverResult {\n return {\n kind: 'discovery',\n supportedVersions,\n mdModel,\n rooms: rooms.map(declared),\n capabilities,\n providerLimits,\n retention,\n };\n }\n\n return {\n setRooms(next) {\n rooms = [...next];\n retain(rooms);\n },\n setConversations(next) {\n scriptConversations(next);\n },\n notifyRoomVersion(notification) {\n for (const observer of observers) observer(notification);\n },\n notifyConversation(event) {\n if (event.kind === 'accepted-message') {\n sealed.add(event.message.turn);\n unsealed.delete(event.message.turn);\n }\n for (const listener of listeners) listener(event);\n },\n selectedRooms() {\n return selected;\n },\n viewedConversations() {\n return viewed;\n },\n conversations: {\n view(next) {\n viewed = [...next];\n },\n observe(notify) {\n listeners.add(notify);\n return () => {\n listeners.delete(notify);\n };\n },\n },\n roomVersions: {\n select(locators) {\n selected = [...locators];\n },\n observe(notify) {\n observers.add(notify);\n return () => {\n observers.delete(notify);\n };\n },\n },\n script(operation, answer) {\n if (answer === undefined) delete scripts[operation];\n else scripts[operation] = answer;\n },\n async model(_authorization, request) {\n return resolveScript(\n scripts.model as Script<ModelResult, typeof request> | undefined,\n () => {\n const room = rooms.find((entry) => entry.locator === request.locator);\n const answer = request.attached === 'collection' ? room?.model : room?.selectionModel;\n return answer ?? { kind: 'model-unavailable', reason: 'not-readable' };\n },\n request,\n );\n },\n async authorize() {\n return resolveScript<Authorization, void>(\n scripts.authorize as Script<Authorization, void> | undefined,\n () => ({}),\n undefined,\n );\n },\n async discover(_authorization: Authorization) {\n return resolveScript<DiscoverResult, void>(\n scripts.discover as Script<DiscoverResult, void> | undefined,\n discovery,\n undefined,\n );\n },\n async bootstrap(_authorization: Authorization, request: BootstrapRequest) {\n return resolveScript<BootstrapResult, BootstrapRequest>(\n scripts.bootstrap as Script<BootstrapResult, BootstrapRequest> | undefined,\n () => {\n const room = rooms.find((entry) => entry.locator === request.locator);\n if (room === undefined) {\n return { kind: 'room-not-readable', locator: request.locator };\n }\n return page(room, request.pageToken === undefined ? 0 : Number(request.pageToken));\n },\n request,\n );\n },\n async refresh(_authorization: Authorization, request: RefreshRequest) {\n return resolveScript<RefreshResult, RefreshRequest>(\n scripts.refresh as Script<RefreshResult, RefreshRequest> | undefined,\n () => {\n const room = rooms.find((entry) => entry.locator === request.locator);\n if (room === undefined) {\n return { kind: 'room-not-readable', locator: request.locator };\n }\n if (request.pageToken !== undefined) {\n const continuation = refreshPages.get(request.pageToken);\n if (\n continuation === undefined ||\n continuation.room.locator !== request.locator ||\n continuation.from.roomVersion !== request.fromRoomVersion\n ) {\n throw new Error('Invalid Refresh Page Token');\n }\n return advancement(continuation.room, continuation.from, continuation.at);\n }\n if (request.fromRoomVersion === room.roomVersion) {\n return { kind: 'still-current' };\n }\n const from = served.get(room.locator)?.get(request.fromRoomVersion);\n if (from === undefined) return { kind: 'beyond-horizon' };\n return advancement(room, from, 0);\n },\n request,\n );\n },\n async mutate(_authorization: Authorization, request: MutationRequest) {\n return resolveScript<MutationResult, MutationRequest>(\n scripts.mutate as Script<MutationResult, MutationRequest> | undefined,\n () => {\n const room = rooms.find((entry) => entry.locator === request.locator);\n if (room === undefined) {\n return { kind: 'room-not-readable', locator: request.locator };\n }\n return { kind: 'rejected', code: 'unscripted-mutation', fields: {}, affected: {} };\n },\n request,\n );\n },\n async history(_authorization: Authorization, request: HistoryRequest) {\n return resolveScript<HistoryResult, HistoryRequest>(\n scripts.history as Script<HistoryResult, HistoryRequest> | undefined,\n () => {\n const room = rooms.find((entry) => entry.locator === request.locator);\n if (room === undefined) {\n return { kind: 'room-not-readable', locator: request.locator };\n }\n return {\n kind: 'history',\n revisions: [],\n };\n },\n request,\n );\n },\n async action(_authorization: Authorization, request: ActionRequest) {\n return resolveScript<ActionResult, ActionRequest>(\n scripts.action as Script<ActionResult, ActionRequest> | undefined,\n () => {\n if (request.name.startsWith('conversation.')) return conversationAction(request);\n return { kind: 'rejected', code: 'unscripted-action', fields: {} };\n },\n request,\n );\n },\n };\n}\n"],"names":["ROOM_CONTRACT_VERSION","MD_MODEL","FIXTURE_RETENTION","history","kind","seconds","outcome","refreshHorizon","declaredRetention","value","retention","Number","isFinite","Error","named","source","paths","taken","path","undefined","resolveScript","answer","fallback","request","createMemoryAdapter","options","rooms","mdModel","supportedVersions","capabilities","providerLimits","pageSize","scripts","served","Map","refreshPages","observers","Set","listeners","scripted","unsealed","sealed","historyPageSize","selected","viewed","issued","scriptConversations","entries","clear","entry","set","conversation","conversations","retain","room","versions","get","locator","roomVersion","declared","name","collectionRoot","operations","replica","attachedModel","typedSelection","providerOwnedPaths","page","from","Object","keys","documents","sort","size","length","slice","next","revisions","binaryTargets","pageToken","String","advancement","at","current","previous","currentTargets","previousTargets","changed","filter","opening","target","has","removals","historyOf","cursor","messages","until","isInteger","code","fields","Math","max","result","conversationAction","input","outcomes","turn","delete","cancelled","discovery","map","setRooms","setConversations","notifyRoomVersion","notification","observer","notifyConversation","event","add","message","listener","selectedRooms","viewedConversations","view","observe","notify","roomVersions","select","locators","script","operation","model","_authorization","find","attached","selectionModel","reason","authorize","discover","bootstrap","refresh","continuation","fromRoomVersion","mutate","affected","action","startsWith"],"mappings":"AACA,SACEA,qBAAqB,QAuBhB,eAAe;AACtB,SAASC,QAAQ,QAAQ,kBAAkB;AAE3C,MAAMC,oBAA+B;IACnCC,SAAS;QAAEC,MAAM;QAAYC,SAAS;IAAE;IACxCC,SAAS;IACTC,gBAAgB;AAClB;AAEA,SAASC,kBAAkBC,KAA4B;IACrD,MAAMC,YAAYD,SAASP;IAC3B,IAAIQ,UAAUP,OAAO,CAACC,IAAI,KAAK,0BAA0B,OAAOM;IAChE,IAAIC,OAAOC,QAAQ,CAACF,UAAUP,OAAO,CAACE,OAAO,KAAKK,UAAUP,OAAO,CAACE,OAAO,GAAG,GAAG;QAC/E,OAAOK;IACT;IACA,MAAM,IAAIG,MAAM;AAClB;AA8CA,SAASC,MACPC,MAAwC,EACxCC,KAAwB;IAExB,MAAMC,QAAgC,CAAC;IACvC,KAAK,MAAMC,QAAQF,MAAO;QACxB,MAAMP,QAAQM,MAAM,CAACG,KAAK;QAC1B,IAAIT,UAAUU,WAAWF,KAAK,CAACC,KAAK,GAAGT;IACzC;IACA,OAAOQ;AACT;AAEA,eAAeG,cACbC,MAAgC,EAChCC,QAA8B,EAC9BC,OAAU;IAEV,IAAIF,WAAWF,WAAW,OAAOG;IACjC,OAAO,OAAOD,WAAW,aAAa,AAACA,OAAwCE,WAAWF;AAC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,cACLY,QAAQ+G,MAAM,EACd;gBACE,MAAMzF,OAAO5B,MAAM2G,IAAI,CAAC,CAACpF,QAAUA,MAAMQ,OAAO,KAAKlC,QAAQkC,OAAO;gBACpE,IAAIH,SAASnC,WAAW;oBACtB,OAAO;wBAAEf,MAAM;wBAAqBqD,SAASlC,QAAQkC,OAAO;oBAAC;gBAC/D;gBACA,OAAO;oBAAErD,MAAM;oBAAY8F,MAAM;oBAAuBC,QAAQ,CAAC;oBAAG6C,UAAU,CAAC;gBAAE;YACnF,GACAzH;QAEJ;QACA,MAAMpB,SAAQiI,cAA6B,EAAE7G,OAAuB;YAClE,OAAOH,cACLY,QAAQ7B,OAAO,EACf;gBACE,MAAMmD,OAAO5B,MAAM2G,IAAI,CAAC,CAACpF,QAAUA,MAAMQ,OAAO,KAAKlC,QAAQkC,OAAO;gBACpE,IAAIH,SAASnC,WAAW;oBACtB,OAAO;wBAAEf,MAAM;wBAAqBqD,SAASlC,QAAQkC,OAAO;oBAAC;gBAC/D;gBACA,OAAO;oBACLrD,MAAM;oBACNyE,WAAW,EAAE;gBACf;YACF,GACAtD;QAEJ;QACA,MAAM0H,QAAOb,cAA6B,EAAE7G,OAAsB;YAChE,OAAOH,cACLY,QAAQiH,MAAM,EACd;gBACE,IAAI1H,QAAQqC,IAAI,CAACsF,UAAU,CAAC,kBAAkB,OAAO3C,mBAAmBhF;gBACxE,OAAO;oBAAEnB,MAAM;oBAAY8F,MAAM;oBAAqBC,QAAQ,CAAC;gBAAE;YACnE,GACA5E;QAEJ;IACF;AACF"}
package/dist/model.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/model.ts"],"sourcesContent":["import type { Validation } from '@agentshouse/mdmodel';\nimport type { MdType } from './collection.js';\n\nexport type ModelIdentity = { identity: string; version: string };\nexport type ModelSnapshot = ModelIdentity & { definitions: Readonly<Record<string, string>> };\nexport type ModelUnavailableReason =\n | 'not-readable'\n | 'revoked'\n | 'not-acquired'\n | 'version-changed'\n | 'invalid'\n | 'binding-unavailable';\nexport type ModelResult =\n | { kind: 'model'; snapshot: ModelSnapshot }\n | { kind: 'model-unavailable'; reason: ModelUnavailableReason }\n | { kind: 'transport-uncertainty' }\n | { kind: 'revoked-authorization' };\nexport type ModelState =\n | { status: 'unavailable'; reason: ModelUnavailableReason }\n | {\n status: 'current' | 'cached';\n snapshot: ModelSnapshot;\n verifiedWith: ModelIdentity;\n types: readonly MdType[];\n };\nexport type TypesResult =\n | { status: 'unavailable'; reason: ModelUnavailableReason }\n | {\n status: 'current' | 'cached';\n identity: string;\n version: string;\n verifiedWith: ModelIdentity;\n types: readonly MdType[];\n };\nexport type ModelValidation =\n | { verdict: 'accept' }\n | (Extract<Validation, { verdict: 'refuse' }> & { source: 'content' | 'model' });\nexport type AttachedModelBinding = {\n verify(\n snapshot: ModelSnapshot,\n ): { kind: 'verified'; types: readonly MdType[] } | { kind: 'invalid' };\n validate(input: {\n model: ModelSnapshot;\n documents: Readonly<Record<string, string>>;\n binaryTargets: readonly string[];\n }): ModelValidation;\n};\nexport type ValidationReceipt = { identity: string; version: string; source: 'current' | 'cached' };\nexport const NO_MODEL: ModelState = { status: 'unavailable', reason: 'not-acquired' };\nexport function modelTypes(state: ModelState): TypesResult {\n return state.status === 'unavailable'\n ? { ...state }\n : {\n status: state.status,\n identity: state.snapshot.identity,\n version: state.snapshot.version,\n verifiedWith: { ...state.verifiedWith },\n types: structuredClone(state.types),\n };\n}\nexport function cached(state: ModelState): ModelState {\n return state.status === 'unavailable' ? state : { ...state, status: 'cached' };\n}\nexport function sameModel(left: ModelIdentity, right: ModelIdentity): boolean {\n return left.identity === right.identity && left.version === right.version;\n}\n"],"names":["NO_MODEL","status","reason","modelTypes","state","identity","snapshot","version","verifiedWith","types","structuredClone","cached","sameModel","left","right"],"mappings":"AAgDA,OAAO,MAAMA,WAAuB;IAAEC,QAAQ;IAAeC,QAAQ;AAAe,EAAE;AACtF,OAAO,SAASC,WAAWC,KAAiB;IAC1C,OAAOA,MAAMH,MAAM,KAAK,gBACpB;QAAE,GAAGG,KAAK;IAAC,IACX;QACEH,QAAQG,MAAMH,MAAM;QACpBI,UAAUD,MAAME,QAAQ,CAACD,QAAQ;QACjCE,SAASH,MAAME,QAAQ,CAACC,OAAO;QAC/BC,cAAc;YAAE,GAAGJ,MAAMI,YAAY;QAAC;QACtCC,OAAOC,gBAAgBN,MAAMK,KAAK;IACpC;AACN;AACA,OAAO,SAASE,OAAOP,KAAiB;IACtC,OAAOA,MAAMH,MAAM,KAAK,gBAAgBG,QAAQ;QAAE,GAAGA,KAAK;QAAEH,QAAQ;IAAS;AAC/E;AACA,OAAO,SAASW,UAAUC,IAAmB,EAAEC,KAAoB;IACjE,OAAOD,KAAKR,QAAQ,KAAKS,MAAMT,QAAQ,IAAIQ,KAAKN,OAAO,KAAKO,MAAMP,OAAO;AAC3E"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/outcome.ts"],"sourcesContent":["import type { ActionResult, ProviderRefusal, RetryableRefusal } from './adapter.js';\nimport type { ChangeBatch } from './change.js';\n\nexport type AffectedState = Readonly<Record<string, string>>;\n\nexport type CallResult = ActionResult | { kind: 'undeclared' };\n\nexport type QueueOutcome =\n | { kind: 'pending' }\n | (ProviderRefusal & {\n kind: 'conflicted';\n roomVersion?: string;\n affected: AffectedState;\n })\n | (ProviderRefusal & {\n kind: 'rejected';\n affected: AffectedState;\n })\n | RetryableRefusal\n | { kind: 'expired' };\n\nexport type AcceptedOutcome = {\n kind: 'accepted';\n roomVersion: string;\n author?: string;\n time?: string;\n};\n\nexport type SubmissionOutcome = QueueOutcome | AcceptedOutcome;\n\nexport type QueueEntry = {\n readonly batch: ChangeBatch;\n readonly outcome: QueueOutcome;\n};\n\nexport type RefusedOutcome = Extract<QueueOutcome, { kind: 'conflicted' | 'rejected' | 'expired' }>;\n\nexport function refused(outcome: SubmissionOutcome | undefined): outcome is RefusedOutcome {\n return (\n outcome?.kind === 'conflicted' || outcome?.kind === 'rejected' || outcome?.kind === 'expired'\n );\n}\n\nexport function withheldUntilReset(outcome: SubmissionOutcome | undefined, at: number): boolean {\n return (\n outcome?.kind === 'retryable-refusal' &&\n outcome.reset !== undefined &&\n at < Date.parse(outcome.reset)\n );\n}\n\nexport function refusalOf(outcome: RefusedOutcome): ProviderRefusal | null {\n if (outcome.kind === 'expired') return null;\n return { code: outcome.code, fields: outcome.fields };\n}\n\nexport function queuedOutcome(outcome: SubmissionOutcome | undefined): QueueOutcome {\n if (outcome === undefined || outcome.kind === 'accepted' || outcome.kind === 'pending') {\n return { kind: 'pending' };\n }\n return outcome;\n}\n"],"names":["refused","outcome","kind","withheldUntilReset","at","reset","undefined","Date","parse","refusalOf","code","fields","queuedOutcome"],"mappings":"AAqCA,OAAO,SAASA,QAAQC,OAAsC;IAC5D,OACEA,SAASC,SAAS,gBAAgBD,SAASC,SAAS,cAAcD,SAASC,SAAS;AAExF;AAEA,OAAO,SAASC,mBAAmBF,OAAsC,EAAEG,EAAU;IACnF,OACEH,SAASC,SAAS,uBAClBD,QAAQI,KAAK,KAAKC,aAClBF,KAAKG,KAAKC,KAAK,CAACP,QAAQI,KAAK;AAEjC;AAEA,OAAO,SAASI,UAAUR,OAAuB;IAC/C,IAAIA,QAAQC,IAAI,KAAK,WAAW,OAAO;IACvC,OAAO;QAAEQ,MAAMT,QAAQS,IAAI;QAAEC,QAAQV,QAAQU,MAAM;IAAC;AACtD;AAEA,OAAO,SAASC,cAAcX,OAAsC;IAClE,IAAIA,YAAYK,aAAaL,QAAQC,IAAI,KAAK,cAAcD,QAAQC,IAAI,KAAK,WAAW;QACtF,OAAO;YAAEA,MAAM;QAAU;IAC3B;IACA,OAAOD;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/overlay.ts"],"sourcesContent":["import { apply, parse, serialize, type Document } from '@agentshouse/mdmodel';\nimport type { Change, ChangeBatch, Precondition } from './change.js';\n\nexport type Layer = {\n documents: Readonly<Record<string, string>>;\n binaryTargets: readonly string[];\n revisions: Readonly<Record<string, string>>;\n};\n\ntype Staged = {\n documents: Record<string, string>;\n binaryTargets: Set<string>;\n revisions: Record<string, string>;\n};\n\ntype Priors = {\n field(path: string, name: string): unknown;\n section(path: string, name: string): string;\n preamble(path: string): string;\n};\n\nconst EMPTY_FRONTMATTER = '---\\n---\\n';\n\nfunction at(path: string, name: string) {\n return `${path} ${name}`;\n}\n\nfunction priorsOf(preconditions: readonly Precondition[]): Priors {\n const fields = new Map<string, unknown>();\n const sections = new Map<string, string>();\n const preambles = new Map<string, string>();\n for (const precondition of preconditions) {\n if (precondition.kind === 'field') {\n fields.set(at(precondition.path, precondition.name), precondition.value);\n }\n if (precondition.kind === 'section') {\n sections.set(at(precondition.path, precondition.name), precondition.value);\n }\n if (precondition.kind === 'preamble') {\n preambles.set(precondition.path, precondition.value);\n }\n }\n return {\n field: (path, name) => fields.get(at(path, name)),\n section: (path, name) => sections.get(at(path, name)) ?? '',\n preamble: (path) => preambles.get(path) ?? '',\n };\n}\n\nfunction compose(\n fields: Readonly<Record<string, unknown>>,\n sections: Readonly<Record<string, string>>,\n): string {\n const body = Object.entries(sections)\n .map(([name, value]) => `\\n## ${name}\\n${value}`)\n .join('');\n const skeleton = `${EMPTY_FRONTMATTER}${body}`;\n const opened = parse(skeleton);\n if (!opened.ok) return skeleton;\n let document: Document = opened.document;\n for (const [name, value] of Object.entries(fields)) {\n const next = apply(document, { kind: 'field', name, value, prior: undefined });\n if (next.outcome === 'applied') document = next.document;\n }\n return serialize(document);\n}\n\nfunction edited(document: Document, change: Change, priors: Priors) {\n if (change.kind === 'field') {\n return apply(document, {\n kind: 'field',\n name: change.name,\n value: change.value,\n prior: priors.field(change.path, change.name),\n });\n }\n if (change.kind === 'preamble') {\n return apply(document, {\n kind: 'preamble',\n value: change.value,\n prior: priors.preamble(change.path),\n });\n }\n if (change.kind !== 'section') return null;\n return apply(document, {\n kind: 'section',\n name: change.name,\n value: change.value,\n prior: priors.section(change.path, change.name),\n });\n}\n\nfunction edit(staged: Staged, change: Change, priors: Priors) {\n const text = staged.documents[change.path];\n if (text === undefined) return;\n const parsed = parse(text, change.path);\n if (!parsed.ok) return;\n const next = edited(parsed.document, change, priors);\n if (next?.outcome === 'applied') staged.documents[change.path] = serialize(next.document);\n}\n\nfunction relocate(staged: Staged, from: string, to: string) {\n const text = staged.documents[from];\n if (text !== undefined) {\n delete staged.documents[from];\n staged.documents[to] = text;\n } else if (staged.binaryTargets.delete(from)) {\n staged.binaryTargets.add(to);\n } else {\n return;\n }\n const revision = staged.revisions[from];\n if (revision === undefined) return;\n delete staged.revisions[from];\n staged.revisions[to] = revision;\n}\n\nfunction erase(staged: Staged, path: string) {\n delete staged.documents[path];\n delete staged.revisions[path];\n staged.binaryTargets.delete(path);\n}\n\nfunction stage(staged: Staged, change: Change, priors: Priors) {\n if (change.kind === 'field' || change.kind === 'section' || change.kind === 'preamble') {\n edit(staged, change, priors);\n return;\n }\n if (change.kind === 'create') {\n staged.documents[change.path] = compose(change.fields, change.sections);\n return;\n }\n if (change.kind === 'replace') {\n if (staged.documents[change.path] === undefined) return;\n staged.documents[change.path] = change.content;\n return;\n }\n if (change.kind === 'move') {\n relocate(staged, change.path, change.to);\n return;\n }\n erase(staged, change.path);\n}\n\nexport function overlay(base: Layer, queue: readonly ChangeBatch[]): Layer {\n const staged: Staged = {\n documents: { ...base.documents },\n binaryTargets: new Set(base.binaryTargets),\n revisions: { ...base.revisions },\n };\n for (const batch of queue) {\n const priors = priorsOf(batch.preconditions);\n for (const change of batch.changes) stage(staged, change, priors);\n }\n return {\n documents: staged.documents,\n binaryTargets: [...staged.binaryTargets].sort(),\n revisions: staged.revisions,\n };\n}\n"],"names":["apply","parse","serialize","EMPTY_FRONTMATTER","at","path","name","priorsOf","preconditions","fields","Map","sections","preambles","precondition","kind","set","value","field","get","section","preamble","compose","body","Object","entries","map","join","skeleton","opened","ok","document","next","prior","undefined","outcome","edited","change","priors","edit","staged","text","documents","parsed","relocate","from","to","binaryTargets","delete","add","revision","revisions","erase","stage","content","overlay","base","queue","Set","batch","changes","sort"],"mappings":"AAAA,SAASA,KAAK,EAAEC,KAAK,EAAEC,SAAS,QAAuB,uBAAuB;AAqB9E,MAAMC,oBAAoB;AAE1B,SAASC,GAAGC,IAAY,EAAEC,IAAY;IACpC,OAAO,GAAGD,KAAK,CAAC,EAAEC,MAAM;AAC1B;AAEA,SAASC,SAASC,aAAsC;IACtD,MAAMC,SAAS,IAAIC;IACnB,MAAMC,WAAW,IAAID;IACrB,MAAME,YAAY,IAAIF;IACtB,KAAK,MAAMG,gBAAgBL,cAAe;QACxC,IAAIK,aAAaC,IAAI,KAAK,SAAS;YACjCL,OAAOM,GAAG,CAACX,GAAGS,aAAaR,IAAI,EAAEQ,aAAaP,IAAI,GAAGO,aAAaG,KAAK;QACzE;QACA,IAAIH,aAAaC,IAAI,KAAK,WAAW;YACnCH,SAASI,GAAG,CAACX,GAAGS,aAAaR,IAAI,EAAEQ,aAAaP,IAAI,GAAGO,aAAaG,KAAK;QAC3E;QACA,IAAIH,aAAaC,IAAI,KAAK,YAAY;YACpCF,UAAUG,GAAG,CAACF,aAAaR,IAAI,EAAEQ,aAAaG,KAAK;QACrD;IACF;IACA,OAAO;QACLC,OAAO,CAACZ,MAAMC,OAASG,OAAOS,GAAG,CAACd,GAAGC,MAAMC;QAC3Ca,SAAS,CAACd,MAAMC,OAASK,SAASO,GAAG,CAACd,GAAGC,MAAMC,UAAU;QACzDc,UAAU,CAACf,OAASO,UAAUM,GAAG,CAACb,SAAS;IAC7C;AACF;AAEA,SAASgB,QACPZ,MAAyC,EACzCE,QAA0C;IAE1C,MAAMW,OAAOC,OAAOC,OAAO,CAACb,UACzBc,GAAG,CAAC,CAAC,CAACnB,MAAMU,MAAM,GAAK,CAAC,KAAK,EAAEV,KAAK,EAAE,EAAEU,OAAO,EAC/CU,IAAI,CAAC;IACR,MAAMC,WAAW,GAAGxB,oBAAoBmB,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AIyB,OAAOtB,IAAI,KAAK,WAAW;QAC7B,IAAIyB,OAAOE,SAAS,CAACL,OAAO/B,IAAI,CAAC,KAAK4B,WAAW;QACjDM,OAAOE,SAAS,CAACL,OAAO/B,IAAI,CAAC,GAAG+B,OAAOiB,OAAO;QAC9C;IACF;IACA,IAAIjB,OAAOtB,IAAI,KAAK,QAAQ;QAC1B6B,SAASJ,QAAQH,OAAO/B,IAAI,EAAE+B,OAAOS,EAAE;QACvC;IACF;IACAM,MAAMZ,QAAQH,OAAO/B,IAAI;AAC3B;AAEA,OAAO,SAASiD,QAAQC,IAAW,EAAEC,KAA6B;IAChE,MAAMjB,SAAiB;QACrBE,WAAW;YAAE,GAAGc,KAAKd,SAAS;QAAC;QAC/BK,eAAe,IAAIW,IAAIF,KAAKT,aAAa;QACzCI,WAAW;YAAE,GAAGK,KAAKL,SAAS;QAAC;IACjC;IACA,KAAK,MAAMQ,SAASF,MAAO;QACzB,MAAMnB,SAAS9B,SAASmD,MAAMlD,aAAa;QAC3C,KAAK,MAAM4B,UAAUsB,MAAMC,OAAO,CAAEP,MAAMb,QAAQH,QAAQC;IAC5D;IACA,OAAO;QACLI,WAAWF,OAAOE,SAAS;QAC3BK,eAAe;eAAIP,OAAOO,aAAa;SAAC,CAACc,IAAI;QAC7CV,WAAWX,OAAOW,SAAS;IAC7B;AACF"}
package/dist/paths.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/paths.ts"],"sourcesContent":["function dirname(path: string): string {\n const index = path.lastIndexOf('/');\n return index === -1 ? '' : path.slice(0, index);\n}\n\nexport function normalize(path: string): string | null {\n const parts: string[] = [];\n for (const part of path.split('/')) {\n if (part === '' || part === '.') continue;\n if (part === '..') {\n if (parts.length === 0) return null;\n parts.pop();\n continue;\n }\n parts.push(part);\n }\n return parts.join('/');\n}\n\nexport function resolve(from: string, reference: string): string | null {\n const base = dirname(from);\n return normalize(base === '' ? reference : `${base}/${reference}`);\n}\n\nexport function relative(from: string, target: string): string {\n const base = dirname(from)\n .split('/')\n .filter((part) => part !== '');\n const parts = target.split('/');\n let shared = 0;\n while (shared < base.length && shared + 1 < parts.length && base[shared] === parts[shared]) {\n shared += 1;\n }\n const up = Array.from({ length: base.length - shared }, () => '..');\n return [...up, ...parts.slice(shared)].join('/');\n}\n\nexport function beneath(prefix: string, path: string): boolean {\n return path === prefix || path.startsWith(`${prefix}/`);\n}\n\nexport function covered(prefixes: readonly string[], path: string): boolean {\n return prefixes.some((prefix) => {\n const normalized = normalize(prefix);\n return normalized !== null && (normalized === '' || beneath(normalized, path));\n });\n}\n"],"names":["dirname","path","index","lastIndexOf","slice","normalize","parts","part","split","length","pop","push","join","resolve","from","reference","base","relative","target","filter","shared","up","Array","beneath","prefix","startsWith","covered","prefixes","some","normalized"],"mappings":"AAAA,SAASA,QAAQC,IAAY;IAC3B,MAAMC,QAAQD,KAAKE,WAAW,CAAC;IAC/B,OAAOD,UAAU,CAAC,IAAI,KAAKD,KAAKG,KAAK,CAAC,GAAGF;AAC3C;AAEA,OAAO,SAASG,UAAUJ,IAAY;IACpC,MAAMK,QAAkB,EAAE;IAC1B,KAAK,MAAMC,QAAQN,KAAKO,KAAK,CAAC,KAAM;QAClC,IAAID,SAAS,MAAMA,SAAS,KAAK;QACjC,IAAIA,SAAS,MAAM;YACjB,IAAID,MAAMG,MAAM,KAAK,GAAG,OAAO;YAC/BH,MAAMI,GAAG;YACT;QACF;QACAJ,MAAMK,IAAI,CAACJ;IACb;IACA,OAAOD,MAAMM,IAAI,CAAC;AACpB;AAEA,OAAO,SAASC,QAAQC,IAAY,EAAEC,SAAiB;IACrD,MAAMC,OAAOhB,QAAQc;IACrB,OAAOT,UAAUW,SAAS,KAAKD,YAAY,GAAGC,KAAK,CAAC,EAAED,WAAW;AACnE;AAEA,OAAO,SAASE,SAASH,IAAY,EAAEI,MAAc;IACnD,MAAMF,OAAOhB,QAAQc,MAClBN,KAAK,CAAC,KACNW,MAAM,CAAC,CAACZ,OAASA,SAAS;IAC7B,MAAMD,QAAQY,OAAOV,KAAK,CAAC;IAC3B,IAAIY,SAAS;IACb,MAAOA,SAASJ,KAAKP,MAAM,IAAIW,SAAS,IAAId,MAAMG,MAAM,IAAIO,IAAI,CAACI,OAAO,KAAKd,KAAK,CAACc,OAAO,CAAE;QAC1FA,UAAU;IACZ;IACA,MAAMC,KAAKC,MAAMR,IAAI,CAAC;QAAEL,QAAQO,KAAKP,MAAM,GAAGW;IAAO,GAAG,IAAM;IAC9D,OAAO;WAAIC;WAAOf,MAAMF,KAAK,CAACgB;KAAQ,CAACR,IAAI,CAAC;AAC9C;AAEA,OAAO,SAASW,QAAQC,MAAc,EAAEvB,IAAY;IAClD,OAAOA,SAASuB,UAAUvB,KAAKwB,UAAU,CAAC,GAAGD,OAAO,CAAC,CAAC;AACxD;AAEA,OAAO,SAASE,QAAQC,QAA2B,EAAE1B,IAAY;IAC/D,OAAO0B,SAASC,IAAI,CAAC,CAACJ;QACpB,MAAMK,aAAaxB,UAAUmB;QAC7B,OAAOK,eAAe,QAASA,CAAAA,eAAe,MAAMN,QAAQM,YAAY5B,KAAI;IAC9E;AACF"}
package/dist/query.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/workspace/packages/mdruntime/src/query.ts"],"sourcesContent":["import type { QueryOptions, QueryResult } from '@agentshouse/query';\nimport type { Document } from '@agentshouse/mdmodel';\nimport type { TypesResult } from './model.js';\n\nexport type QueryInput = {\n room: string;\n roomVersion: string;\n documents: Readonly<Record<string, Document>>;\n model: TypesResult;\n typedSelection: TypesResult | null;\n};\nexport type QueryBinding = (rooms: readonly QueryInput[], options: QueryOptions) => QueryResult;\nexport function rawQuery(rooms: readonly QueryInput[]): QueryResult {\n return {\n roomVersions: Object.fromEntries(rooms.map((room) => [room.room, room.roomVersion])),\n groups: null,\n documents: rooms.flatMap((room) =>\n Object.entries(room.documents)\n .filter(([path]) => path.endsWith('.md'))\n .map(([path, document]) => ({\n ...structuredClone(document),\n type: document.type ?? 'any',\n room: room.room,\n path,\n backlinks: [],\n })),\n ),\n };\n}\n"],"names":["rawQuery","rooms","roomVersions","Object","fromEntries","map","room","roomVersion","groups","documents","flatMap","entries","filter","path","endsWith","document","structuredClone","type","backlinks"],"mappings":"AAYA,OAAO,SAASA,SAASC,KAA4B;IACnD,OAAO;QACLC,cAAcC,OAAOC,WAAW,CAACH,MAAMI,GAAG,CAAC,CAACC,OAAS;gBAACA,KAAKA,IAAI;gBAAEA,KAAKC,WAAW;aAAC;QAClFC,QAAQ;QACRC,WAAWR,MAAMS,OAAO,CAAC,CAACJ,OACxBH,OAAOQ,OAAO,CAACL,KAAKG,SAAS,EAC1BG,MAAM,CAAC,CAAC,CAACC,KAAK,GAAKA,KAAKC,QAAQ,CAAC,QACjCT,GAAG,CAAC,CAAC,CAACQ,MAAME,SAAS,GAAM,CAAA;oBAC1B,GAAGC,gBAAgBD,SAAS;oBAC5BE,MAAMF,SAASE,IAAI,IAAI;oBACvBX,MAAMA,KAAKA,IAAI;oBACfO;oBACAK,WAAW,EAAE;gBACf,CAAA;IAEN;AACF"}