@draht/durable 2026.11.27 → 2026.12.3-2

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 (119) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/codemode/codemode.d.ts.map +1 -1
  3. package/dist/codemode/codemode.js +39 -0
  4. package/dist/codemode/codemode.js.map +1 -1
  5. package/dist/documents.d.ts.map +1 -1
  6. package/dist/documents.js +7 -2
  7. package/dist/documents.js.map +1 -1
  8. package/dist/env/index.d.ts +11 -0
  9. package/dist/env/index.d.ts.map +1 -1
  10. package/dist/env/index.js.map +1 -1
  11. package/dist/env/node.d.ts +1 -0
  12. package/dist/env/node.d.ts.map +1 -1
  13. package/dist/env/node.js +114 -34
  14. package/dist/env/node.js.map +1 -1
  15. package/dist/harness/task-graph.d.ts.map +1 -1
  16. package/dist/harness/task-graph.js +26 -13
  17. package/dist/harness/task-graph.js.map +1 -1
  18. package/dist/harness/usage.d.ts.map +1 -1
  19. package/dist/harness/usage.js +2 -0
  20. package/dist/harness/usage.js.map +1 -1
  21. package/dist/harness/view.d.ts +5 -1
  22. package/dist/harness/view.d.ts.map +1 -1
  23. package/dist/harness/view.js +36 -24
  24. package/dist/harness/view.js.map +1 -1
  25. package/dist/ids.d.ts +10 -0
  26. package/dist/ids.d.ts.map +1 -1
  27. package/dist/ids.js +21 -0
  28. package/dist/ids.js.map +1 -1
  29. package/dist/images/encode.d.ts +33 -0
  30. package/dist/images/encode.d.ts.map +1 -0
  31. package/dist/images/encode.js +69 -0
  32. package/dist/images/encode.js.map +1 -0
  33. package/dist/images/index.d.ts +4 -4
  34. package/dist/images/index.d.ts.map +1 -1
  35. package/dist/images/index.js +41 -58
  36. package/dist/images/index.js.map +1 -1
  37. package/dist/images/node-worker.d.ts +1 -18
  38. package/dist/images/node-worker.d.ts.map +1 -1
  39. package/dist/images/node-worker.js +2 -12
  40. package/dist/images/node-worker.js.map +1 -1
  41. package/dist/images/node.d.ts.map +1 -1
  42. package/dist/images/node.js +4 -103
  43. package/dist/images/node.js.map +1 -1
  44. package/dist/images/pi-images/cloudflare.d.ts +8 -0
  45. package/dist/images/pi-images/cloudflare.d.ts.map +1 -0
  46. package/dist/images/pi-images/cloudflare.js +14 -0
  47. package/dist/images/pi-images/cloudflare.js.map +1 -0
  48. package/dist/images/pi-images/index.d.ts +37 -0
  49. package/dist/images/pi-images/index.d.ts.map +1 -0
  50. package/dist/images/pi-images/index.js +22 -0
  51. package/dist/images/pi-images/index.js.map +1 -0
  52. package/dist/images/pi-images/installed.d.ts +8 -0
  53. package/dist/images/pi-images/installed.d.ts.map +1 -0
  54. package/dist/images/pi-images/installed.js +24 -0
  55. package/dist/images/pi-images/installed.js.map +1 -0
  56. package/dist/images/pi-images/node-worker.d.ts +2 -0
  57. package/dist/images/pi-images/node-worker.d.ts.map +1 -0
  58. package/dist/images/pi-images/node-worker.js +7 -0
  59. package/dist/images/pi-images/node-worker.js.map +1 -0
  60. package/dist/images/pi-images/node.d.ts +24 -0
  61. package/dist/images/pi-images/node.d.ts.map +1 -0
  62. package/dist/images/pi-images/node.js +18 -0
  63. package/dist/images/pi-images/node.js.map +1 -0
  64. package/dist/images/pi-images/processor.d.ts +21 -0
  65. package/dist/images/pi-images/processor.d.ts.map +1 -0
  66. package/dist/images/pi-images/processor.js +117 -0
  67. package/dist/images/pi-images/processor.js.map +1 -0
  68. package/dist/images/thread.d.ts +27 -0
  69. package/dist/images/thread.d.ts.map +1 -0
  70. package/dist/images/thread.js +131 -0
  71. package/dist/images/thread.js.map +1 -0
  72. package/dist/session/session.js +32 -6
  73. package/dist/session/session.js.map +1 -1
  74. package/dist/session/transaction.d.ts.map +1 -1
  75. package/dist/session/transaction.js +3 -0
  76. package/dist/session/transaction.js.map +1 -1
  77. package/dist/storage/jsonl/storage.d.ts +6 -0
  78. package/dist/storage/jsonl/storage.d.ts.map +1 -1
  79. package/dist/storage/jsonl/storage.js +65 -0
  80. package/dist/storage/jsonl/storage.js.map +1 -1
  81. package/dist/storage/sqlite/commit.d.ts.map +1 -1
  82. package/dist/storage/sqlite/commit.js +3 -3
  83. package/dist/storage/sqlite/commit.js.map +1 -1
  84. package/dist/storage/sqlite/migrations.d.ts.map +1 -1
  85. package/dist/storage/sqlite/migrations.js +20 -0
  86. package/dist/storage/sqlite/migrations.js.map +1 -1
  87. package/dist/storage/sqlite/rows.d.ts +0 -2
  88. package/dist/storage/sqlite/rows.d.ts.map +1 -1
  89. package/dist/storage/sqlite/rows.js +3 -5
  90. package/dist/storage/sqlite/rows.js.map +1 -1
  91. package/dist/storage/sqlite/storage.d.ts +1 -1
  92. package/dist/storage/sqlite/storage.d.ts.map +1 -1
  93. package/dist/storage/sqlite/storage.js +11 -10
  94. package/dist/storage/sqlite/storage.js.map +1 -1
  95. package/dist/storage/store/documents.d.ts.map +1 -1
  96. package/dist/storage/store/documents.js +4 -6
  97. package/dist/storage/store/documents.js.map +1 -1
  98. package/dist/storage/store/migrations.d.ts +10 -0
  99. package/dist/storage/store/migrations.d.ts.map +1 -0
  100. package/dist/storage/store/migrations.js +44 -0
  101. package/dist/storage/store/migrations.js.map +1 -0
  102. package/dist/storage/store/storage.d.ts +3 -2
  103. package/dist/storage/store/storage.d.ts.map +1 -1
  104. package/dist/storage/store/storage.js +9 -6
  105. package/dist/storage/store/storage.js.map +1 -1
  106. package/dist/storage/store/tables.d.ts +21 -3
  107. package/dist/storage/store/tables.d.ts.map +1 -1
  108. package/dist/storage/store/tables.js +14 -10
  109. package/dist/storage/store/tables.js.map +1 -1
  110. package/dist/tasks.d.ts.map +1 -1
  111. package/dist/tasks.js +2 -0
  112. package/dist/tasks.js.map +1 -1
  113. package/dist/testing/storage-conformance.d.ts.map +1 -1
  114. package/dist/testing/storage-conformance.js +0 -74
  115. package/dist/testing/storage-conformance.js.map +1 -1
  116. package/dist/types.d.ts +4 -1
  117. package/dist/types.d.ts.map +1 -1
  118. package/dist/types.js.map +1 -1
  119. package/package.json +26 -6
@@ -1 +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,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,CAAC;gBAC5D,GAAG,CAAC,KAAK,CAAC,OAAO,KAAK,SAAS;oBAC9B,CAAC,CAAC,EAAE;oBACJ,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC;aAC1E,CAAC;QACH,2DAA2D;QAC3D,KAAK,YAAY,CAAC;QAClB,KAAK,UAAU;YACd,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;IACjE,CAAC;AACF,CAAC;AAED,SAAS,OAAO,CAAC,UAAqB;IACrC,OAAQ,UAAyC,CAAC,KAAK,CAAC;AACzD,CAAC","sourcesContent":["import { BACKGROUND_CONTEXT, type Context, withoutAbortSignal } from \"@draht/chord/context\";\nimport { applyImmutable, type Op } from \"@draht/chord/delta\";\nimport type { JsonValue } from \"@draht/chord/json\";\nimport { Watch, type WatchCall, type WatchHandle } from \"@draht/chord/watch\";\nimport {\n\tcloseEndOf,\n\tcloseEnds,\n\tcontained,\n\tguardObserver,\n\ttype ObservedCommit,\n\tobservation,\n\ttype SessionImpl,\n} from \"../session/session.ts\";\nimport type {\n\tConversationId,\n\tJoinPolicy,\n\tObservation,\n\tObserver,\n\tStorage,\n\tTaskId,\n\tTaskOutcome,\n\tTaskRecord,\n} from \"../types.ts\";\nimport { type BlockedReason, type BlockedSubject, blockedSubject } from \"./scheduler.ts\";\nimport { closedError, scanAll } from \"./util.ts\";\n\n/** A live task's durable status without its checkpoint and outcome payloads (spec §9.4). */\nexport type TaskGraphState =\n\t| { readonly status: \"pending\" | \"running\"; readonly phase: string }\n\t| {\n\t\t\treadonly status: \"waiting\";\n\t\t\treadonly phase: string;\n\t\t\treadonly on: readonly TaskId[];\n\t\t\treadonly policy: JoinPolicy;\n\t }\n\t/** Asleep until the Harness clock reaches `until`, or one of `signals` holds a value no wake used. */\n\t| {\n\t\t\treadonly status: \"sleeping\";\n\t\t\treadonly phase: string;\n\t\t\treadonly until?: number;\n\t\t\treadonly signals?: readonly { readonly signal: string; readonly key: string }[];\n\t }\n\t/** Outcome held until its ordinary owned work drains. */\n\t| { readonly status: \"completing\"; readonly outcome: TaskOutcome<JsonValue>[\"status\"] };\n\nexport type TaskGraphNode = {\n\treadonly id: TaskId;\n\treadonly kind: string;\n\treadonly conversationId: ConversationId;\n\t/** Owner task; absent for a conversation-owned task. */\n\treadonly owner?: TaskId;\n\treadonly background: boolean;\n\treadonly abortRequested: boolean;\n\treadonly state: TaskGraphState;\n\t/**\n\t * Why it cannot run here, when it cannot: no registered definition takes it (`missing_task`, `task_too_old`,\n\t * `migration_failed`). Follows registry changes.\n\t */\n\treadonly blocked?: BlockedReason;\n\t/** Conversations this task owns, in ID order. */\n\treadonly conversations: readonly ConversationId[];\n};\n\n/** Every live task of the Session (spec §9.4). */\nexport type TaskGraph = {\n\t/** Every live task, keyed by its decimal ID. */\n\treadonly tasks: Readonly<Record<string, TaskGraphNode>>;\n};\n\nexport type TaskGraphWatch = WatchHandle<TaskGraph>;\n\ntype AnyTaskRecord = TaskRecord<JsonValue, JsonValue, JsonValue>;\ntype Mount = {\n\tvalue: TaskGraph;\n\t/** Watches and guarded host observers (`observeTaskGraph()`). */\n\treadonly observers: Set<Observer<TaskGraph>>;\n\t/** What the blocked reason reads of each live task, so a registry change can derive it again without payloads. */\n\treadonly records: Map<string, BlockedSubject>;\n};\n\n/** What the graph asks the scheduler: a task's blocked reason, and when reasons may change without a commit. */\nexport type TaskGraphBlocking = {\n\treadonly blocked: (record: BlockedSubject) => BlockedReason | undefined;\n\treadonly subscribeBlocked: (listener: () => void) => () => void;\n};\n\nconst LIVE_STATUSES = [\"pending\", \"running\", \"waiting\", \"sleeping\", \"completing\"] as const;\nconst SCAN_PAGE_SIZE = 256;\n\n/**\n * The Harness's task graph mount: built on the Session line by its first observer and dropped with its last. It\n * advances from the Session's commit publications, which are durable.\n */\nexport class TaskGraphView {\n\treadonly #session: SessionImpl;\n\treadonly #blocking: TaskGraphBlocking;\n\t#mount: Mount | undefined;\n\t#closed = false;\n\n\tconstructor(session: SessionImpl, blocking: TaskGraphBlocking) {\n\t\tthis.#session = session;\n\t\tthis.#blocking = blocking;\n\t\tsession.followCommits((publication, context) => {\n\t\t\t// A commit held in memory changes documents only, which the graph does not show.\n\t\t\tif (this.#mount === undefined || publication.kind === \"memory\") return;\n\t\t\tadvance(this.#mount, publication, context, blocking.blocked, (error) => session.report(error));\n\t\t});\n\t\tblocking.subscribeBlocked(() => this.#refreshBlocked());\n\t\tsession.subscribeClose(() => {\n\t\t\tthis.#closed = true;\n\t\t\tconst ends = closeEnds(this.#session.failure);\n\t\t\tfor (const observer of [...(this.#mount?.observers ?? [])]) {\n\t\t\t\tcontained(\n\t\t\t\t\t() => observer.end(closeEndOf(observer, ends)),\n\t\t\t\t\t(error) => session.report(error),\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.#mount = undefined;\n\t\t});\n\t}\n\n\t/**\n\t * Attach a synchronous observer of the graph (`Harness.observeTaskGraph()`), behind `guardObserver()`; `context`\n\t * governs only the attachment.\n\t */\n\tasync observe(observer: Observer<TaskGraph>, context: Context): Promise<Observation<TaskGraph>> {\n\t\tlet value!: TaskGraph;\n\t\tconst attached = await this.#attach((current, release) => {\n\t\t\tvalue = current;\n\t\t\treturn guardObserver(observer, release, (error) => this.#session.report(error));\n\t\t}, context);\n\t\tconst signal = context.abortSignal;\n\t\tif (signal?.aborted) {\n\t\t\tattached.detach();\n\t\t\tthrow signal.reason;\n\t\t}\n\t\treturn observation(value, attached.observer);\n\t}\n\n\t/** A serialized watch of the graph, an observer of its mount; aborting `context` ends it `aborted`. */\n\tasync watch(context: Context): Promise<TaskGraphWatch> {\n\t\tconst { observer } = await this.#attach(\n\t\t\t(value, release) => new Watch<TaskGraph>(value, release, (error) => this.#session.report(error)),\n\t\t\tcontext,\n\t\t);\n\t\tconst signal = context.abortSignal;\n\t\tif (signal?.aborted) {\n\t\t\tobserver.abort();\n\t\t\tthrow signal.reason;\n\t\t}\n\t\tif (signal !== undefined) observer.observeAbort(signal);\n\t\treturn observer;\n\t}\n\n\t/** Register an observer created from the current revision, atomically on the Session line. */\n\t#attach<O extends Observer<TaskGraph>>(\n\t\tcreate: (value: TaskGraph, release: () => void) => O,\n\t\tcontext: Context,\n\t): Promise<{ observer: O; detach: () => void }> {\n\t\treturn this.#session.readOnLine(async (storage) => {\n\t\t\tconst mount = this.#mount ?? {\n\t\t\t\t...(await this.#build(storage, context)),\n\t\t\t\tobservers: new Set<Observer<TaskGraph>>(),\n\t\t\t};\n\t\t\tconst detach = (): void => {\n\t\t\t\tmount.observers.delete(observer);\n\t\t\t\tif (mount.observers.size === 0 && this.#mount === mount) this.#mount = undefined;\n\t\t\t};\n\t\t\tconst observer = create(mount.value, detach);\n\t\t\t// Close or cancellation may begin while the mount builds; register nothing then.\n\t\t\tif (this.#closed) throw closedError(this.#session);\n\t\t\tcontext.abortSignal?.throwIfAborted();\n\t\t\tthis.#mount = mount;\n\t\t\tmount.observers.add(observer);\n\t\t\treturn { observer, detach };\n\t\t});\n\t}\n\n\t/** On the Session line: derive every node's blocked reason again, and publish the ones that changed. */\n\t#refreshBlocked(): void {\n\t\tif (this.#mount === undefined || this.#closed) return;\n\t\tthis.#session\n\t\t\t.readOnLine(async () => {\n\t\t\t\tconst mount = this.#mount;\n\t\t\t\tif (mount === undefined) return;\n\t\t\t\tconst ops: Op[] = [];\n\t\t\t\tfor (const [key, record] of mount.records) {\n\t\t\t\t\tconst blocked = this.#blocking.blocked(record);\n\t\t\t\t\tif (blocked === mount.value.tasks[key]?.blocked) continue;\n\t\t\t\t\tops.push(\n\t\t\t\t\t\tblocked === undefined ? [\"d\", [\"tasks\", key, \"blocked\"]] : [\"s\", [\"tasks\", key, \"blocked\"], blocked],\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tpublish(mount, ops, BACKGROUND_CONTEXT, (error) => this.#session.report(error));\n\t\t\t})\n\t\t\t// Rejected only once the Session is closing or failed.\n\t\t\t.catch(() => {});\n\t}\n\n\t/** Read the graph on the line, through the line's `storage`. */\n\tasync #build(storage: Storage, context: Context): Promise<Omit<Mount, \"observers\">> {\n\t\tconst tasks: Record<string, TaskGraphNode> = {};\n\t\tconst live = new Map<string, BlockedSubject>();\n\t\tconst records: AnyTaskRecord[] = [];\n\t\tfor (const status of LIVE_STATUSES) {\n\t\t\trecords.push(...(await scanAll((cursor) => storage.scanTasks({ status }, SCAN_PAGE_SIZE, cursor, context))));\n\t\t}\n\t\trecords.sort((a, b) => a.id - b.id);\n\t\tfor (const record of records) {\n\t\t\tconst owned = await scanAll((cursor) =>\n\t\t\t\tstorage.scanConversations({ ownerTaskId: record.id }, SCAN_PAGE_SIZE, cursor, context),\n\t\t\t);\n\t\t\tconst conversations = owned.map((conversation) => conversation.id).sort((a, b) => a - b);\n\t\t\tconst subject = blockedSubject(record);\n\t\t\ttasks[String(record.id)] = nodeOf(record, conversations, this.#blocking.blocked(subject));\n\t\t\tlive.set(String(record.id), subject);\n\t\t}\n\t\treturn { value: { tasks }, records: live };\n\t}\n}\n\n/**\n * Derive the mount's operations from one publication, apply them, and hand the revision to every observer; one that\n * throws is reported through `report`, and the others still get it.\n */\nfunction advance(\n\tmount: Mount,\n\tpublication: ObservedCommit,\n\tcontext: Context,\n\tblocked: TaskGraphBlocking[\"blocked\"],\n\treport: (error: unknown) => void,\n): void {\n\tconst ops: Op[] = [];\n\t// Nodes this publication set or deleted, over the mount's value.\n\tconst changed = new Map<string, TaskGraphNode | undefined>();\n\tconst node = (key: string): TaskGraphNode | undefined =>\n\t\tchanged.has(key) ? changed.get(key) : mount.value.tasks[key];\n\tfor (const change of publication.changes) {\n\t\tif (change.type !== \"task\") continue;\n\t\tconst record = change.value;\n\t\tconst key = String(record.id);\n\t\tconst previous = node(key);\n\t\tif (record.state.status === \"terminal\") {\n\t\t\tmount.records.delete(key);\n\t\t\tif (previous === undefined) continue;\n\t\t\tops.push([\"d\", [\"tasks\", key]]);\n\t\t\tchanged.set(key, undefined);\n\t\t\tcontinue;\n\t\t}\n\t\tconst subject = blockedSubject(record);\n\t\tmount.records.set(key, subject);\n\t\tconst next = nodeOf(record, previous?.conversations ?? [], blocked(subject));\n\t\tif (previous !== undefined && JSON.stringify(next) === JSON.stringify(previous)) continue;\n\t\tops.push([\"s\", [\"tasks\", key], next as unknown as JsonValue]);\n\t\tchanged.set(key, next);\n\t}\n\t// After the tasks, so a conversation created with its owner task in one commit finds the owner's node. Change order\n\t// within a publication is unspecified, so each owner's list is sorted again.\n\tconst created = new Map<string, ConversationId[]>();\n\tfor (const change of publication.changes) {\n\t\tif (change.type !== \"conversation\" || change.value.owner === undefined) continue;\n\t\tconst key = String(change.value.owner.taskId);\n\t\tif (node(key) !== undefined) created.set(key, [...(created.get(key) ?? []), change.value.id]);\n\t}\n\tfor (const [key, ids] of created) {\n\t\tconst conversations = [...node(key)!.conversations, ...ids].sort((a, b) => a - b);\n\t\tops.push([\"s\", [\"tasks\", key, \"conversations\"], conversations]);\n\t}\n\tpublish(mount, ops, context, report);\n}\n\n/** Apply `ops` to the mount and hand the revision to every observer; one that throws is reported. */\nfunction publish(mount: Mount, ops: Op[], context: Context, report: (error: unknown) => void): void {\n\tif (ops.length === 0) return;\n\tmount.value = applyImmutable(mount.value, ops);\n\tconst frameContext = withoutAbortSignal(context);\n\tconst call: WatchCall<TaskGraph> = { kind: \"value\", value: mount.value, ops, retired: false };\n\tfor (const observer of [...mount.observers]) contained(() => observer.advance(call, frameContext), report);\n}\n\nfunction nodeOf(\n\trecord: AnyTaskRecord,\n\tconversations: readonly ConversationId[],\n\tblocked: BlockedReason | undefined,\n): TaskGraphNode {\n\treturn {\n\t\tid: record.id,\n\t\tkind: record.kind,\n\t\tconversationId: record.conversationId,\n\t\t...(record.owner === undefined ? {} : { owner: record.owner }),\n\t\tbackground: record.background,\n\t\tabortRequested: record.abortRequested,\n\t\tstate: stateOf(record),\n\t\tconversations,\n\t\t...(blocked === undefined ? {} : { blocked }),\n\t};\n}\n\nfunction stateOf(record: AnyTaskRecord): TaskGraphState {\n\tconst state = record.state;\n\tswitch (state.status) {\n\t\tcase \"pending\":\n\t\tcase \"running\":\n\t\t\treturn { status: state.status, phase: phaseOf(state.checkpoint) };\n\t\tcase \"waiting\":\n\t\t\treturn { status: \"waiting\", phase: phaseOf(state.checkpoint), on: [...state.on], policy: state.policy };\n\t\tcase \"sleeping\":\n\t\t\treturn {\n\t\t\t\tstatus: \"sleeping\",\n\t\t\t\tphase: phaseOf(state.checkpoint),\n\t\t\t\t...(state.until === undefined ? {} : { until: state.until }),\n\t\t\t\t...(state.signals === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { signals: state.signals.map(({ signal, key }) => ({ signal, key })) }),\n\t\t\t};\n\t\t// Terminal records never reach here: they leave the graph.\n\t\tcase \"completing\":\n\t\tcase \"terminal\":\n\t\t\treturn { status: \"completing\", outcome: state.outcome.status };\n\t}\n}\n\nfunction phaseOf(checkpoint: JsonValue): string {\n\treturn (checkpoint as { readonly phase: string }).phase;\n}\n"]}
1
+ {"version":3,"file":"task-graph.js","sourceRoot":"","sources":["../../src/harness/task-graph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAgB,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC5F,OAAO,EAAE,cAAc,EAAW,MAAM,oBAAoB,CAAC;AAE7D,OAAO,EAAE,KAAK,EAAoC,MAAM,oBAAoB,CAAC;AAC7E,OAAO,EACN,UAAU,EACV,SAAS,EACT,SAAS,EACT,aAAa,EAEb,WAAW,GAEX,MAAM,uBAAuB,CAAC;AAW/B,OAAO,EAA2C,cAAc,EAAE,MAAM,gBAAgB,CAAC;AACzF,OAAO,EAAE,WAAW,EAAE,OAAO,E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AC,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC;aAC1E,CAAC;QACH,2DAA2D;QAC3D,KAAK,YAAY,CAAC;QAClB,KAAK,UAAU;YACd,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;IACjE,CAAC;AACF,CAAC;AAED,SAAS,OAAO,CAAC,UAAqB;IACrC,OAAQ,UAAyC,CAAC,KAAK,CAAC;AACzD,CAAC","sourcesContent":["import { BACKGROUND_CONTEXT, type Context, withoutAbortSignal } from \"@draht/chord/context\";\nimport { applyImmutable, type Op } from \"@draht/chord/delta\";\nimport type { JsonValue } from \"@draht/chord/json\";\nimport { Watch, type WatchCall, type WatchHandle } from \"@draht/chord/watch\";\nimport {\n\tcloseEndOf,\n\tcloseEnds,\n\tcontained,\n\tguardObserver,\n\ttype ObservedCommit,\n\tobservation,\n\ttype SessionImpl,\n} from \"../session/session.ts\";\nimport type {\n\tConversationId,\n\tJoinPolicy,\n\tObservation,\n\tObserver,\n\tStorage,\n\tTaskId,\n\tTaskOutcome,\n\tTaskRecord,\n} from \"../types.ts\";\nimport { type BlockedReason, type BlockedSubject, blockedSubject } from \"./scheduler.ts\";\nimport { closedError, scanAll } from \"./util.ts\";\n\n/** A live task's durable status without its checkpoint and outcome payloads (spec §9.4). */\nexport type TaskGraphState =\n\t| { readonly status: \"pending\" | \"running\"; readonly phase: string }\n\t| {\n\t\t\treadonly status: \"waiting\";\n\t\t\treadonly phase: string;\n\t\t\treadonly on: readonly TaskId[];\n\t\t\treadonly policy: JoinPolicy;\n\t }\n\t/** Asleep until the Harness clock reaches `until`, or one of `signals` holds a value no wake used. */\n\t| {\n\t\t\treadonly status: \"sleeping\";\n\t\t\treadonly phase: string;\n\t\t\treadonly until?: number;\n\t\t\treadonly signals?: readonly { readonly signal: string; readonly key: string }[];\n\t }\n\t/** Outcome held until its ordinary owned work drains. */\n\t| { readonly status: \"completing\"; readonly outcome: TaskOutcome<JsonValue>[\"status\"] };\n\nexport type TaskGraphNode = {\n\treadonly id: TaskId;\n\treadonly kind: string;\n\treadonly conversationId: ConversationId;\n\t/** Owner task; absent for a conversation-owned task. */\n\treadonly owner?: TaskId;\n\treadonly background: boolean;\n\treadonly abortRequested: boolean;\n\treadonly state: TaskGraphState;\n\t/**\n\t * Why it cannot run here, when it cannot: no registered definition takes it (`missing_task`, `task_too_old`,\n\t * `migration_failed`). Follows registry changes.\n\t */\n\treadonly blocked?: BlockedReason;\n\t/** Conversations this task owns, in ID order. */\n\treadonly conversations: readonly ConversationId[];\n};\n\n/** Every live task of the Session (spec §9.4). */\nexport type TaskGraph = {\n\t/** Every live task, keyed by its decimal ID. */\n\treadonly tasks: Readonly<Record<string, TaskGraphNode>>;\n};\n\nexport type TaskGraphWatch = WatchHandle<TaskGraph>;\n\ntype AnyTaskRecord = TaskRecord<JsonValue, JsonValue, JsonValue>;\ntype Mount = {\n\tvalue: TaskGraph;\n\t/** Watches and guarded host observers (`observeTaskGraph()`). */\n\treadonly observers: Set<Observer<TaskGraph>>;\n\t/** What the blocked reason reads of each live task, so a registry change can derive it again without payloads. */\n\treadonly records: Map<string, BlockedSubject>;\n};\n\n/**\n * Where an observer's release finds its observer: none until it is registered;\n * a release before that drops nothing.\n */\ntype ObserverSlot = { observer: Observer<TaskGraph> | undefined };\n\n/** What the graph asks the scheduler: a task's blocked reason, and when reasons may change without a commit. */\nexport type TaskGraphBlocking = {\n\treadonly blocked: (record: BlockedSubject) => BlockedReason | undefined;\n\treadonly subscribeBlocked: (listener: () => void) => () => void;\n};\n\nconst LIVE_STATUSES = [\"pending\", \"running\", \"waiting\", \"sleeping\", \"completing\"] as const;\nconst SCAN_PAGE_SIZE = 256;\n\n/**\n * The Harness's task graph mount: built on the Session line by its first observer and dropped with its last. It\n * advances from the Session's commit publications, which are durable.\n */\nexport class TaskGraphView {\n\treadonly #session: SessionImpl;\n\treadonly #blocking: TaskGraphBlocking;\n\t#mount: Mount | undefined;\n\t#closed = false;\n\n\tconstructor(session: SessionImpl, blocking: TaskGraphBlocking) {\n\t\tthis.#session = session;\n\t\tthis.#blocking = blocking;\n\t\tsession.followCommits((publication, context) => {\n\t\t\t// A commit held in memory changes documents only, which the graph does not show.\n\t\t\tif (this.#mount === undefined || publication.kind === \"memory\") return;\n\t\t\tadvance(this.#mount, publication, context, blocking.blocked, (error) => session.report(error));\n\t\t});\n\t\tblocking.subscribeBlocked(() => this.#refreshBlocked());\n\t\tsession.subscribeClose(() => {\n\t\t\tthis.#closed = true;\n\t\t\tconst ends = closeEnds(this.#session.failure);\n\t\t\tfor (const observer of [...(this.#mount?.observers ?? [])]) {\n\t\t\t\tcontained(\n\t\t\t\t\t() => observer.end(closeEndOf(observer, ends)),\n\t\t\t\t\t(error) => session.report(error),\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.#mount = undefined;\n\t\t});\n\t}\n\n\t/**\n\t * Attach a synchronous observer of the graph (`Harness.observeTaskGraph()`), behind `guardObserver()`; `context`\n\t * governs only the attachment.\n\t */\n\tasync observe(observer: Observer<TaskGraph>, context: Context): Promise<Observation<TaskGraph>> {\n\t\t// The first revision comes back from `#attach`, never captured here: a closure made in this scope keeps the scope,\n\t\t// and with it a captured revision, for as long as it is kept: the guard's report for the observer's life (and\n\t\t// `create`, were anything to keep it) (ERNDL-1289).\n\t\tconst attached = await this.#attach(\n\t\t\t(_value, release) => guardObserver(observer, release, (error) => this.#session.report(error)),\n\t\t\tcontext,\n\t\t);\n\t\tconst signal = context.abortSignal;\n\t\tif (signal?.aborted) {\n\t\t\tattached.detach();\n\t\t\tthrow signal.reason;\n\t\t}\n\t\treturn observation(attached.value, attached.observer);\n\t}\n\n\t/** A serialized watch of the graph, an observer of its mount; aborting `context` ends it `aborted`. */\n\tasync watch(context: Context): Promise<TaskGraphWatch> {\n\t\tconst { observer } = await this.#attach(\n\t\t\t(value, release) => new Watch<TaskGraph>(value, release, (error) => this.#session.report(error)),\n\t\t\tcontext,\n\t\t);\n\t\tconst signal = context.abortSignal;\n\t\tif (signal?.aborted) {\n\t\t\tobserver.abort();\n\t\t\tthrow signal.reason;\n\t\t}\n\t\tif (signal !== undefined) observer.observeAbort(signal);\n\t\treturn observer;\n\t}\n\n\t/**\n\t * Register an observer created from the current revision, atomically on the Session line. Resolves with the\n\t * observer, its release as `detach`, and that revision.\n\t */\n\t#attach<O extends Observer<TaskGraph>>(\n\t\tcreate: (value: TaskGraph, release: () => void) => O,\n\t\tcontext: Context,\n\t): Promise<{ observer: O; detach: () => void; value: TaskGraph }> {\n\t\treturn this.#session.readOnLine(async (storage) => {\n\t\t\tconst mount = this.#mount ?? {\n\t\t\t\t...(await this.#build(storage, context)),\n\t\t\t\tobservers: new Set<Observer<TaskGraph>>(),\n\t\t\t};\n\t\t\tconst slot: ObserverSlot = { observer: undefined };\n\t\t\tconst detach = this.#release(mount, slot);\n\t\t\tconst observer = create(mount.value, detach);\n\t\t\t// Close or cancellation may begin while the mount builds; register nothing then.\n\t\t\tif (this.#closed) throw closedError(this.#session);\n\t\t\tcontext.abortSignal?.throwIfAborted();\n\t\t\tslot.observer = observer;\n\t\t\tthis.#mount = mount;\n\t\t\tmount.observers.add(observer);\n\t\t\treturn { observer, detach, value: mount.value };\n\t\t});\n\t}\n\n\t/**\n\t * The release of the observer `slot` will hold: it drops that observer, and `mount` with its last one. Made here,\n\t * not in `#attach`: a closure there would keep `#attach`'s scope for the observer's life, with the attachment's\n\t * context and `create` (ERNDL-1289).\n\t */\n\t#release(mount: Mount, slot: ObserverSlot): () => void {\n\t\treturn () => {\n\t\t\tif (slot.observer !== undefined) mount.observers.delete(slot.observer);\n\t\t\tif (mount.observers.size === 0 && this.#mount === mount) this.#mount = undefined;\n\t\t};\n\t}\n\n\t/** On the Session line: derive every node's blocked reason again, and publish the ones that changed. */\n\t#refreshBlocked(): void {\n\t\tif (this.#mount === undefined || this.#closed) return;\n\t\tthis.#session\n\t\t\t.readOnLine(async () => {\n\t\t\t\tconst mount = this.#mount;\n\t\t\t\tif (mount === undefined) return;\n\t\t\t\tconst ops: Op[] = [];\n\t\t\t\tfor (const [key, record] of mount.records) {\n\t\t\t\t\tconst blocked = this.#blocking.blocked(record);\n\t\t\t\t\tif (blocked === mount.value.tasks[key]?.blocked) continue;\n\t\t\t\t\tops.push(\n\t\t\t\t\t\tblocked === undefined ? [\"d\", [\"tasks\", key, \"blocked\"]] : [\"s\", [\"tasks\", key, \"blocked\"], blocked],\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tpublish(mount, ops, BACKGROUND_CONTEXT, (error) => this.#session.report(error));\n\t\t\t})\n\t\t\t// Rejected only once the Session is closing or failed.\n\t\t\t.catch(() => {});\n\t}\n\n\t/** Read the graph on the line, through the line's `storage`. */\n\tasync #build(storage: Storage, context: Context): Promise<Omit<Mount, \"observers\">> {\n\t\tconst tasks: Record<string, TaskGraphNode> = {};\n\t\tconst live = new Map<string, BlockedSubject>();\n\t\tconst records: AnyTaskRecord[] = [];\n\t\tfor (const status of LIVE_STATUSES) {\n\t\t\trecords.push(...(await scanAll((cursor) => storage.scanTasks({ status }, SCAN_PAGE_SIZE, cursor, context))));\n\t\t}\n\t\trecords.sort((a, b) => a.id - b.id);\n\t\tfor (const record of records) {\n\t\t\tconst owned = await scanAll((cursor) =>\n\t\t\t\tstorage.scanConversations({ ownerTaskId: record.id }, SCAN_PAGE_SIZE, cursor, context),\n\t\t\t);\n\t\t\tconst conversations = owned.map((conversation) => conversation.id).sort((a, b) => a - b);\n\t\t\tconst subject = blockedSubject(record);\n\t\t\ttasks[String(record.id)] = nodeOf(record, conversations, this.#blocking.blocked(subject));\n\t\t\tlive.set(String(record.id), subject);\n\t\t}\n\t\treturn { value: { tasks }, records: live };\n\t}\n}\n\n/**\n * Derive the mount's operations from one publication, apply them, and hand the revision to every observer; one that\n * throws is reported through `report`, and the others still get it.\n */\nfunction advance(\n\tmount: Mount,\n\tpublication: ObservedCommit,\n\tcontext: Context,\n\tblocked: TaskGraphBlocking[\"blocked\"],\n\treport: (error: unknown) => void,\n): void {\n\tconst ops: Op[] = [];\n\t// Nodes this publication set or deleted, over the mount's value.\n\tconst changed = new Map<string, TaskGraphNode | undefined>();\n\tconst node = (key: string): TaskGraphNode | undefined =>\n\t\tchanged.has(key) ? changed.get(key) : mount.value.tasks[key];\n\tfor (const change of publication.changes) {\n\t\tif (change.type !== \"task\") continue;\n\t\tconst record = change.value;\n\t\tconst key = String(record.id);\n\t\tconst previous = node(key);\n\t\tif (record.state.status === \"terminal\") {\n\t\t\tmount.records.delete(key);\n\t\t\tif (previous === undefined) continue;\n\t\t\tops.push([\"d\", [\"tasks\", key]]);\n\t\t\tchanged.set(key, undefined);\n\t\t\tcontinue;\n\t\t}\n\t\tconst subject = blockedSubject(record);\n\t\tmount.records.set(key, subject);\n\t\tconst next = nodeOf(record, previous?.conversations ?? [], blocked(subject));\n\t\tif (previous !== undefined && JSON.stringify(next) === JSON.stringify(previous)) continue;\n\t\tops.push([\"s\", [\"tasks\", key], next as unknown as JsonValue]);\n\t\tchanged.set(key, next);\n\t}\n\t// After the tasks, so a conversation created with its owner task in one commit finds the owner's node. Change order\n\t// within a publication is unspecified, so each owner's list is sorted again.\n\tconst created = new Map<string, ConversationId[]>();\n\tfor (const change of publication.changes) {\n\t\tif (change.type !== \"conversation\" || change.value.owner === undefined) continue;\n\t\tconst key = String(change.value.owner.taskId);\n\t\tif (node(key) !== undefined) created.set(key, [...(created.get(key) ?? []), change.value.id]);\n\t}\n\tfor (const [key, ids] of created) {\n\t\tconst conversations = [...node(key)!.conversations, ...ids].sort((a, b) => a - b);\n\t\tops.push([\"s\", [\"tasks\", key, \"conversations\"], conversations]);\n\t}\n\tpublish(mount, ops, context, report);\n}\n\n/** Apply `ops` to the mount and hand the revision to every observer; one that throws is reported. */\nfunction publish(mount: Mount, ops: Op[], context: Context, report: (error: unknown) => void): void {\n\tif (ops.length === 0) return;\n\tmount.value = applyImmutable(mount.value, ops);\n\tconst frameContext = withoutAbortSignal(context);\n\tconst call: WatchCall<TaskGraph> = { kind: \"value\", value: mount.value, ops, retired: false };\n\tfor (const observer of [...mount.observers]) contained(() => observer.advance(call, frameContext), report);\n}\n\nfunction nodeOf(\n\trecord: AnyTaskRecord,\n\tconversations: readonly ConversationId[],\n\tblocked: BlockedReason | undefined,\n): TaskGraphNode {\n\treturn {\n\t\tid: record.id,\n\t\tkind: record.kind,\n\t\tconversationId: record.conversationId,\n\t\t...(record.owner === undefined ? {} : { owner: record.owner }),\n\t\tbackground: record.background,\n\t\tabortRequested: record.abortRequested,\n\t\tstate: stateOf(record),\n\t\tconversations,\n\t\t...(blocked === undefined ? {} : { blocked }),\n\t};\n}\n\nfunction stateOf(record: AnyTaskRecord): TaskGraphState {\n\tconst state = record.state;\n\tswitch (state.status) {\n\t\tcase \"pending\":\n\t\tcase \"running\":\n\t\t\treturn { status: state.status, phase: phaseOf(state.checkpoint) };\n\t\tcase \"waiting\":\n\t\t\treturn { status: \"waiting\", phase: phaseOf(state.checkpoint), on: [...state.on], policy: state.policy };\n\t\tcase \"sleeping\":\n\t\t\treturn {\n\t\t\t\tstatus: \"sleeping\",\n\t\t\t\tphase: phaseOf(state.checkpoint),\n\t\t\t\t...(state.until === undefined ? {} : { until: state.until }),\n\t\t\t\t...(state.signals === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { signals: state.signals.map(({ signal, key }) => ({ signal, key })) }),\n\t\t\t};\n\t\t// Terminal records never reach here: they leave the graph.\n\t\tcase \"completing\":\n\t\tcase \"terminal\":\n\t\t\treturn { status: \"completing\", outcome: state.outcome.status };\n\t}\n}\n\nfunction phaseOf(checkpoint: JsonValue): string {\n\treturn (checkpoint as { readonly phase: string }).phase;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"usage.d.ts","sourceRoot":"","sources":["../../src/harness/usage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAY,KAAK,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAEtE,OAAO,KAAK,EAAE,cAAc,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAEtD,mHAAmH;AACnH,MAAM,MAAM,UAAU,GAAG;IACxB,8EAA8E;IAC9E,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC;IAClD,2EAA2E;IAC3E,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC;CACjD,CAAC;AAEF,eAAO,MAAM,QAAQ,wDAQnB,CAAC;AAEH,2GAA2G;AAC3G,wBAAsB,WAAW,CAChC,EAAE,EAAE,EAAE,EACN,cAAc,EAAE,cAAc,EAC9B,MAAM,EAAE,MAAM,UAAU,EACxB,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,KAAK,GACV,OAAO,CAAC,IAAI,CAAC,CAQf;AAED,0GAA0G;AAC1G,wBAAgB,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,EAAE,KAAK,EAAE,KAAK,GAAG,IAAI,CAaxE;AAED,8CAA8C;AAC9C,wBAAgB,aAAa,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,QAAQ,CAAC,UAAU,CAAC,GAAG,IAAI,CAchF"}
1
+ {"version":3,"file":"usage.d.ts","sourceRoot":"","sources":["../../src/harness/usage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAY,KAAK,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAEtE,OAAO,KAAK,EAAE,cAAc,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAEtD,mHAAmH;AACnH,MAAM,MAAM,UAAU,GAAG;IACxB,8EAA8E;IAC9E,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC;IAClD,2EAA2E;IAC3E,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC;CACjD,CAAC;AAEF,eAAO,MAAM,QAAQ,wDAQnB,CAAC;AAEH,2GAA2G;AAC3G,wBAAsB,WAAW,CAChC,EAAE,EAAE,EAAE,EACN,cAAc,EAAE,cAAc,EAC9B,MAAM,EAAE,MAAM,UAAU,EACxB,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,KAAK,GACV,OAAO,CAAC,IAAI,CAAC,CAQf;AAED,0GAA0G;AAC1G,wBAAgB,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,EAAE,KAAK,EAAE,KAAK,GAAG,IAAI,CAcxE;AAED,8CAA8C;AAC9C,wBAAgB,aAAa,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,QAAQ,CAAC,UAAU,CAAC,GAAG,IAAI,CAchF"}
@@ -31,6 +31,8 @@ export function addUsage(total, usage) {
31
31
  total.cacheWrite1h = (total.cacheWrite1h ?? 0) + usage.cacheWrite1h;
32
32
  if (usage.reasoning !== undefined)
33
33
  total.reasoning = (total.reasoning ?? 0) + usage.reasoning;
34
+ if (usage.imageOutput !== undefined)
35
+ total.imageOutput = (total.imageOutput ?? 0) + usage.imageOutput;
34
36
  total.cost.input += usage.cost.input;
35
37
  total.cost.output += usage.cost.output;
36
38
  total.cost.cacheRead += usage.cost.cacheRead;
@@ -1 +1 @@
1
- {"version":3,"file":"usage.js","sourceRoot":"","sources":["../../src/harness/usage.ts"],"names":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AAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;YAC7E,yFAAyF;YACzF,IAAI,KAAK,KAAK,SAAS;gBAAE,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;;gBAE/C,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE;oBACvC,KAAK,EAAE,eAAe,CAAC,KAAK,CAAC;oBAC7B,UAAU,EAAE,IAAI;oBAChB,QAAQ,EAAE,IAAI;iBACd,CAAC,CAAC;QACL,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["import type { Usage } from \"@draht/ai\";\nimport type { Draft } from \"@draht/chord/delta\";\nimport { copyJson, type JsonRepresentation } from \"@draht/chord/json\";\nimport { defineDoc } from \"../documents.ts\";\nimport type { ConversationId, Tx } from \"../types.ts\";\n\n/** Ledger of one conversation's own spend: its entries, and compaction summarization attempts, which have none. */\nexport type UsageState = {\n\t/** Assistant entries and summarization attempts, keyed `provider/modelId`. */\n\tmodels: Record<string, JsonRepresentation<Usage>>;\n\t/** Tool results, keyed by tool name; their usage has no model identity. */\n\ttools: Record<string, JsonRepresentation<Usage>>;\n};\n\nexport const UsageDoc = defineDoc<UsageState>({\n\tkind: \"pi.usage\",\n\tversion: 1,\n\tscope: \"conversation\",\n\thistory: \"latest\",\n\tfork: \"initial\",\n\tinitial: () => ({ models: {}, tools: {} }),\n\tcheckpointWhen: () => true,\n});\n\n/** Add `usage` to one bucket of the conversation's `pi.usage`, in the commit that records the response. */\nexport async function recordUsage(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tbucket: keyof UsageState,\n\tkey: string,\n\tusage: Usage,\n): Promise<void> {\n\tconst totals = (await tx.doc(UsageDoc, conversationId))[bucket];\n\t// Own keys only: a tool may be called `toString`.\n\tconst total = Object.hasOwn(totals, key) ? totals[key] : undefined;\n\t// Providers may leave optional counters `undefined`; drafts take strict JSON.\n\tif (total === undefined)\n\t\ttotals[key] = copyJson(usage, { omitUndefinedProperties: true }) as JsonRepresentation<Usage>;\n\telse addUsage(total, usage);\n}\n\n/** Add every counter of `usage` to `total`; optional counters are added once either side reports them. */\nexport function addUsage(total: Draft<Usage> | Usage, usage: Usage): void {\n\ttotal.input += usage.input;\n\ttotal.output += usage.output;\n\ttotal.cacheRead += usage.cacheRead;\n\ttotal.cacheWrite += usage.cacheWrite;\n\ttotal.totalTokens += usage.totalTokens;\n\tif (usage.cacheWrite1h !== undefined) total.cacheWrite1h = (total.cacheWrite1h ?? 0) + usage.cacheWrite1h;\n\tif (usage.reasoning !== undefined) total.reasoning = (total.reasoning ?? 0) + usage.reasoning;\n\ttotal.cost.input += usage.cost.input;\n\ttotal.cost.output += usage.cost.output;\n\ttotal.cost.cacheRead += usage.cost.cacheRead;\n\ttotal.cost.cacheWrite += usage.cost.cacheWrite;\n\ttotal.cost.total += usage.cost.total;\n}\n\n/** Add every bucket of `state` into `sum`. */\nexport function addUsageState(sum: UsageState, state: Readonly<UsageState>): void {\n\tfor (const bucket of [\"models\", \"tools\"] as const) {\n\t\tfor (const [key, usage] of Object.entries(state[bucket])) {\n\t\t\tconst total = Object.hasOwn(sum[bucket], key) ? sum[bucket][key] : undefined;\n\t\t\t// Define rather than assign: assigning a tool named `__proto__` would set the prototype.\n\t\t\tif (total !== undefined) addUsage(total, usage);\n\t\t\telse\n\t\t\t\tObject.defineProperty(sum[bucket], key, {\n\t\t\t\t\tvalue: structuredClone(usage),\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\twritable: true,\n\t\t\t\t});\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"usage.js","sourceRoot":"","sources":["../../src/harness/usage.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAA2B,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAW5C,MAAM,CAAC,MAAM,QAAQ,GAAG,SAAS,CAAa;IAC7C,IAAI,E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,CAAC,CAAC,CAAC,SAAS,CAAC;YAC7E,yFAAyF;YACzF,IAAI,KAAK,KAAK,SAAS;gBAAE,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;;gBAE/C,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE;oBACvC,KAAK,EAAE,eAAe,CAAC,KAAK,CAAC;oBAC7B,UAAU,EAAE,IAAI;oBAChB,QAAQ,EAAE,IAAI;iBACd,CAAC,CAAC;QACL,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["import type { Usage } from \"@draht/ai\";\nimport type { Draft } from \"@draht/chord/delta\";\nimport { copyJson, type JsonRepresentation } from \"@draht/chord/json\";\nimport { defineDoc } from \"../documents.ts\";\nimport type { ConversationId, Tx } from \"../types.ts\";\n\n/** Ledger of one conversation's own spend: its entries, and compaction summarization attempts, which have none. */\nexport type UsageState = {\n\t/** Assistant entries and summarization attempts, keyed `provider/modelId`. */\n\tmodels: Record<string, JsonRepresentation<Usage>>;\n\t/** Tool results, keyed by tool name; their usage has no model identity. */\n\ttools: Record<string, JsonRepresentation<Usage>>;\n};\n\nexport const UsageDoc = defineDoc<UsageState>({\n\tkind: \"pi.usage\",\n\tversion: 1,\n\tscope: \"conversation\",\n\thistory: \"latest\",\n\tfork: \"initial\",\n\tinitial: () => ({ models: {}, tools: {} }),\n\tcheckpointWhen: () => true,\n});\n\n/** Add `usage` to one bucket of the conversation's `pi.usage`, in the commit that records the response. */\nexport async function recordUsage(\n\ttx: Tx,\n\tconversationId: ConversationId,\n\tbucket: keyof UsageState,\n\tkey: string,\n\tusage: Usage,\n): Promise<void> {\n\tconst totals = (await tx.doc(UsageDoc, conversationId))[bucket];\n\t// Own keys only: a tool may be called `toString`.\n\tconst total = Object.hasOwn(totals, key) ? totals[key] : undefined;\n\t// Providers may leave optional counters `undefined`; drafts take strict JSON.\n\tif (total === undefined)\n\t\ttotals[key] = copyJson(usage, { omitUndefinedProperties: true }) as JsonRepresentation<Usage>;\n\telse addUsage(total, usage);\n}\n\n/** Add every counter of `usage` to `total`; optional counters are added once either side reports them. */\nexport function addUsage(total: Draft<Usage> | Usage, usage: Usage): void {\n\ttotal.input += usage.input;\n\ttotal.output += usage.output;\n\ttotal.cacheRead += usage.cacheRead;\n\ttotal.cacheWrite += usage.cacheWrite;\n\ttotal.totalTokens += usage.totalTokens;\n\tif (usage.cacheWrite1h !== undefined) total.cacheWrite1h = (total.cacheWrite1h ?? 0) + usage.cacheWrite1h;\n\tif (usage.reasoning !== undefined) total.reasoning = (total.reasoning ?? 0) + usage.reasoning;\n\tif (usage.imageOutput !== undefined) total.imageOutput = (total.imageOutput ?? 0) + usage.imageOutput;\n\ttotal.cost.input += usage.cost.input;\n\ttotal.cost.output += usage.cost.output;\n\ttotal.cost.cacheRead += usage.cost.cacheRead;\n\ttotal.cost.cacheWrite += usage.cost.cacheWrite;\n\ttotal.cost.total += usage.cost.total;\n}\n\n/** Add every bucket of `state` into `sum`. */\nexport function addUsageState(sum: UsageState, state: Readonly<UsageState>): void {\n\tfor (const bucket of [\"models\", \"tools\"] as const) {\n\t\tfor (const [key, usage] of Object.entries(state[bucket])) {\n\t\t\tconst total = Object.hasOwn(sum[bucket], key) ? sum[bucket][key] : undefined;\n\t\t\t// Define rather than assign: assigning a tool named `__proto__` would set the prototype.\n\t\t\tif (total !== undefined) addUsage(total, usage);\n\t\t\telse\n\t\t\t\tObject.defineProperty(sum[bucket], key, {\n\t\t\t\t\tvalue: structuredClone(usage),\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\twritable: true,\n\t\t\t\t});\n\t\t}\n\t}\n}\n"]}
@@ -59,11 +59,15 @@ export declare class ConversationViews {
59
59
  watch(id: ConversationId, context: Context, window?: ConversationWindow): Promise<WatchHandle<ConversationView>>;
60
60
  /**
61
61
  * Register an observer created from its window's first revision, atomically on the Session line: it sees every later
62
- * publication and nothing earlier. `release` drops it, and the mount with its last observer.
62
+ * publication and nothing earlier. `release` drops it, and the mount with its last observer. Resolves with the
63
+ * observer, its release as `detach`, and that first revision, which the mount stops keeping at the next one. The
64
+ * mount is looked up after the window's read: one its last observer let go of meanwhile missed the publications
65
+ * since, so it is hydrated again rather than put back stale. An absent conversation is rejected before the read.
63
66
  */
64
67
  attach<O extends ViewObserver>(id: ConversationId, window: ConversationWindow | undefined, create: (value: ConversationView, release: () => void) => O, context: Context): Promise<{
65
68
  observer: O;
66
69
  detach: () => void;
70
+ value: ConversationView;
67
71
  }>;
68
72
  }
69
73
  //# sourceMappingURL=view.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"view.d.ts","sourceRoot":"","sources":["../../src/harness/view.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,OAAO,EAAsB,MAAM,sBAAsB,CAAC;AAGxE,OAAO,EAAS,KAAK,SAAS,EAAE,KAAK,QAAQ,EAAE,KAAK,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAE5F,OAAO,EAON,KAAK,WAAW,EAChB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAEX,cAAc,EACd,kBAAkB,EAGlB,OAAO,EAEP,WAAW,EACX,UAAU,EACV,WAAW,EACX,QAAQ,EAER,MAAM,aAAa,CAAC;AAQrB,gHAAgH;AAChH,MAAM,MAAM,gBAAgB,GAAG;IAC9B,QAAQ,CAAC,YAAY,EAAE,kBAAkB,CAAC;IAC1C;;;OAGG;IACH,QAAQ,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;IACzC,4FAA4F;IAC5F,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B,kFAAkF;IAClF,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC;CACpD,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAChC;;;;OAIG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;IACx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0DAA0D;IAC1D,GAAG,CAAC,GAAG,EAAE,QAAQ,GAAG,IAAI,CAAC;CACzB,CAAC;AA4CF,gEAAgE;AAChE,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,iBAAiB,CAIpE;AAoBD;;;;GAIG;AACH,qBAAa,iBAAiB;;IAK7B,YAAY,OAAO,EAAE,WAAW,EAmB/B;IAED,+DAA+D;IAC/D,MAAM,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAE3B;IAED;;;OAGG;IACG,OAAO,CACZ,EAAE,EAAE,cAAc,EAClB,QAAQ,EAAE,QAAQ,CAAC,gBAAgB,CAAC,EACpC,OAAO,EAAE,OAAO,EAChB,MAAM,CAAC,EAAE,kBAAkB,GACzB,OAAO,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC,CAgBxC;IAED,sGAAsG;IAChG,KAAK,CACV,EAAE,EAAE,cAAc,EAClB,OAAO,EAAE,OAAO,EAChB,MAAM,CAAC,EAAE,kBAAkB,GACzB,OAAO,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC,CAcxC;IAED;;;;;;OAMG;IACG,MAAM,CAAC,CAAC,SAAS,YAAY,EAClC,EAAE,EAAE,cAAc,EAClB,MAAM,EAAE,kBAAkB,GAAG,SAAS,EACtC,MAAM,EAAE,CAAC,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,IAAI,KAAK,CAAC,EAC3D,OAAO,EAAE,OAAO,GACd,OAAO,CAAC;QAAE,QAAQ,EAAE,CAAC,CAAC;QAAC,MAAM,EAAE,MAAM,IAAI,CAAC;QAAC,KAAK,EAAE,gBAAgB,CAAA;KAAE,CAAC,CAqBvE;CA0BD"}
@@ -78,17 +78,16 @@ export class ConversationViews {
78
78
  * governs only the attachment.
79
79
  */
80
80
  async observe(id, observer, context, window) {
81
- let value;
82
- const attached = await this.attach(id, window, (current, release) => {
83
- value = current;
84
- return guardObserver(observer, release, (error) => this.report(error));
85
- }, context);
81
+ // The first revision comes back from `attach`, never captured here: a closure made in this scope keeps the scope,
82
+ // and with it a captured revision, for as long as it is kept: the guard's report for the observer's life (and
83
+ // `create`, were anything to keep it) (ERNDL-1289).
84
+ const attached = await this.attach(id, window, (_value, release) => guardObserver(observer, release, (error) => this.report(error)), context);
86
85
  const signal = context.abortSignal;
87
86
  if (signal?.aborted) {
88
87
  attached.detach();
89
88
  throw signal.reason;
90
89
  }
91
- return observation(value, attached.observer);
90
+ return observation(attached.value, attached.observer);
92
91
  }
93
92
  /** A serialized watch of the view, an observer of its mount; aborting `context` ends it `aborted`. */
94
93
  async watch(id, context, window) {
@@ -104,41 +103,54 @@ export class ConversationViews {
104
103
  }
105
104
  /**
106
105
  * Register an observer created from its window's first revision, atomically on the Session line: it sees every later
107
- * publication and nothing earlier. `release` drops it, and the mount with its last observer.
106
+ * publication and nothing earlier. `release` drops it, and the mount with its last observer. Resolves with the
107
+ * observer, its release as `detach`, and that first revision, which the mount stops keeping at the next one. The
108
+ * mount is looked up after the window's read: one its last observer let go of meanwhile missed the publications
109
+ * since, so it is hydrated again rather than put back stale. An absent conversation is rejected before the read.
108
110
  */
109
111
  async attach(id, window, create, context) {
110
112
  const bounds = resolveWindow(window);
111
113
  return this.#session.readOnLine(async (storage) => {
112
- const mount = this.#mounts.get(id) ?? (await this.#build(storage, id, context));
114
+ // The record never changes: a mount's, else the stored one (the read `#build` made before), absent rejected first.
115
+ const conversation = this.#mounts.get(id)?.conversation ?? (await storage.conversation(id, context));
116
+ if (conversation === undefined)
117
+ throw new Error(`Conversation ${id} does not exist`);
113
118
  const { entries, before } = await loadWindow(storage, id, bounds, context);
119
+ // No await between this lookup and the registration below: a mount found here is the one publications advance.
120
+ const mount = this.#mounts.get(id) ?? (await this.#build(conversation, context));
114
121
  const value = view(mount.conversation, entries, before, mount.docs);
115
- let windowed;
116
- const detach = () => {
117
- if (windowed !== undefined)
118
- mount.observers.delete(windowed);
119
- if (mount.observers.size === 0 && this.#mounts.get(id) === mount)
120
- this.#mounts.delete(id);
121
- };
122
+ const slot = { windowed: undefined };
123
+ const detach = this.#release(id, mount, slot);
122
124
  const observer = create(value, detach);
123
125
  // Close or cancellation may begin while the mount hydrates; register nothing then.
124
126
  if (this.#closed)
125
127
  throw closedError(this.#session);
126
128
  context.abortSignal?.throwIfAborted();
127
- windowed = { min: bounds.min, max: bounds.max, value, observer };
129
+ slot.windowed = { min: bounds.min, max: bounds.max, value, observer };
128
130
  this.#mounts.set(id, mount);
129
- mount.observers.add(windowed);
130
- return { observer, detach };
131
+ mount.observers.add(slot.windowed);
132
+ return { observer, detach, value };
131
133
  });
132
134
  }
133
- /** Hydrate a mount on the line, through the line's `storage`. */
134
- async #build(storage, id, context) {
135
- const conversation = await storage.conversation(id, context);
136
- if (conversation === undefined)
137
- throw new Error(`Conversation ${id} does not exist`);
135
+ /**
136
+ * The release of the observer `slot` will hold: it drops that observer, and `mount` with its last one. Made here,
137
+ * not in `attach`: a closure there would keep `attach`'s scope for the observer's life, with the attachment's
138
+ * context and `create` (ERNDL-1289).
139
+ */
140
+ #release(id, mount, slot) {
141
+ return () => {
142
+ if (slot.windowed !== undefined)
143
+ mount.observers.delete(slot.windowed);
144
+ if (mount.observers.size === 0 && this.#mounts.get(id) === mount)
145
+ this.#mounts.delete(id);
146
+ };
147
+ }
148
+ /** Hydrate a mount of `conversation` on the line: its documents, read through the line. */
149
+ async #build(conversation, context) {
138
150
  const docs = {};
139
151
  const incarnations = new Map();
140
152
  for (const token of MOUNTED) {
141
- const loaded = await this.#session.conversationDocumentOnLine(token, id, context);
153
+ const loaded = await this.#session.conversationDocumentOnLine(token, conversation.id, context);
142
154
  if (loaded === undefined)
143
155
  continue;
144
156
  docs[token.definition.kind] = loaded.value;
@@ -1 +1 @@
1
- {"version":3,"file":"view.js","sourceRoot":"","sources":["../../src/harness/view.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,cAAc,EAAy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EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IACjC,CAAC;AACF,CAAC","sourcesContent":["import { type Context, withoutAbortSignal } from \"@draht/chord/context\";\nimport { applyImmutable, type NonEmptyPath, type Op, type Path } from \"@draht/chord/delta\";\nimport type { JsonValue } from \"@draht/chord/json\";\nimport { Watch, type WatchCall, type WatchEnd, type WatchHandle } from \"@draht/chord/watch\";\nimport { idFromNumber } from \"../ids.ts\";\nimport {\n\tcloseEndOf,\n\tcloseEnds,\n\tcontained,\n\tguardObserver,\n\ttype ObservedCommit,\n\tobservation,\n\ttype SessionImpl,\n} from \"../session/session.ts\";\nimport type {\n\tConversationDocToken,\n\tConversationId,\n\tConversationRecord,\n\tCursor,\n\tDocumentId,\n\tEntryId,\n\tEntryQuery,\n\tEntryRecord,\n\tJsonObject,\n\tObservation,\n\tObserver,\n\tStorage,\n} from \"../types.ts\";\nimport { AgentDoc } from \"./agent.ts\";\nimport { InboxDoc } from \"./inbox.ts\";\nimport { LiveDoc } from \"./live.ts\";\nimport { ProviderDoc } from \"./provider.ts\";\nimport { UsageDoc } from \"./usage.ts\";\nimport { closedError } from \"./util.ts\";\n\n/** Structural view of one conversation: a window over its transcript and its built-in documents (spec §9.3). */\nexport type ConversationView = {\n\treadonly conversation: ConversationRecord;\n\t/**\n\t * A window over the transcript, its fork-aware history (`Conversation.entries()`), in entry ID order. Head markers\n\t * such as compaction summaries sit where they were written; their `head` tells where the entries they summarize end.\n\t */\n\treadonly entries: readonly EntryRecord[];\n\t/** ID of the entry just before the window; absent when the window starts the transcript. */\n\treadonly before?: EntryId;\n\t/** Built-in conversation documents keyed by kind; absent documents are absent. */\n\treadonly docs: Readonly<Record<string, JsonObject>>;\n};\n\n/**\n * Which entries a view's window holds (spec §9.3). The window holds between `min` and `max` entries: it starts with\n * the newest `min` entries, takes appends, and once it would hold more than `max`, drops its oldest in one splice down\n * to `min`. With `from`, it starts at `from` instead when at most `max` entries are at or after it.\n */\nexport type ConversationWindow = {\n\t/**\n\t * Where the first value's window starts, inclusive, such as right after the newest entry a client has\n\t * (`ConversationTranscript.resume`). It selects only that first value: every entry committed after the attachment is\n\t * appended, whatever its ID. A `from` past the newest entry starts the window empty, with `before` the newest entry.\n\t */\n\treadonly from?: EntryId;\n\t/** Default 50; an integer, at least 1. */\n\treadonly min?: number;\n\t/** Default `2 * min`; an integer, at least `min`. */\n\treadonly max?: number;\n};\n\n/** Default `ConversationWindow.min`. */\nconst DEFAULT_WINDOW_MIN = 50;\n\n/** Receives each next revision of one observer's window, and the Session's close. */\nexport type ViewObserver = {\n\tadvance(call: WatchCall<ConversationView>, context: Context): void;\n\t/** The Session closed (`ended`), or failed (`failed`). */\n\tend(end: WatchEnd): void;\n};\n\nconst MOUNTED = [\n\tAgentDoc,\n\tLiveDoc,\n\tInboxDoc,\n\tProviderDoc,\n\tUsageDoc,\n] as unknown as readonly ConversationDocToken<JsonObject>[];\nconst MOUNTED_KINDS: ReadonlySet<string> = new Set(MOUNTED.map((token) => token.definition.kind));\nconst SCAN_PAGE_SIZE = 256;\n\n/** One observer of a mount and its window: the bounds and the revision it was last given. */\ntype Windowed = {\n\treadonly min: number;\n\treadonly max: number;\n\tvalue: ConversationView;\n\treadonly observer: ViewObserver;\n};\n\n/**\n * One conversation's mount: the documents it shows, shared by every observer, and the observers, each with its own\n * window over the entries.\n */\ntype Mount = {\n\treadonly conversation: ConversationRecord;\n\tdocs: Readonly<Record<string, JsonObject>>;\n\t/** Mounted incarnation and definition version per kind; another incarnation or version is set whole. */\n\treadonly incarnations: Map<string, { id: DocumentId; version: number }>;\n\treadonly observers: Set<Windowed>;\n};\n\nconst VIEWS = new WeakMap<object, ConversationViews>();\n\n/** The view mounts of a Harness, for adapters built on them. */\nexport function conversationViews(harness: object): ConversationViews {\n\tconst views = VIEWS.get(harness);\n\tif (views === undefined) throw new Error(\"Not a Harness\");\n\treturn views;\n}\n\n/** A window with its defaults applied. */\ntype WindowBounds = { readonly from: EntryId | undefined; readonly min: number; readonly max: number };\n\n/** `window` with its defaults; throws a `RangeError` for bounds that are not integers or `max` below `min`. */\nfunction resolveWindow(window: ConversationWindow | undefined): WindowBounds {\n\tconst min = window?.min ?? DEFAULT_WINDOW_MIN;\n\tif (!Number.isSafeInteger(min) || min < 1) throw new RangeError(`Window min must be an integer >= 1, got ${min}`);\n\tconst max = window?.max ?? 2 * min;\n\tif (!Number.isSafeInteger(max) || max < min) {\n\t\tthrow new RangeError(`Window max must be an integer >= min (${min}), got ${max}`);\n\t}\n\tconst from = window?.from;\n\tif (from !== undefined && !Number.isSafeInteger(from)) {\n\t\tthrow new RangeError(`Window from must be an entry ID, got ${from}`);\n\t}\n\treturn { from, min, max };\n}\n\n/**\n * The Harness's conversation view mounts: at most one per conversation, built on the Session line by its first\n * observer and dropped with its last. Each mount advances from the Session's commits as memory adopts them, deferred ones\n * (`CommitPersistence`) before they are stored, and hands each observer the next revision of its own window.\n */\nexport class ConversationViews {\n\treadonly #session: SessionImpl;\n\treadonly #mounts = new Map<ConversationId, Mount>();\n\t#closed = false;\n\n\tconstructor(session: SessionImpl) {\n\t\tthis.#session = session;\n\t\tVIEWS.set(session, this);\n\t\tsession.followCommits((publication, context) => {\n\t\t\tfor (const [id, mount] of this.#mounts)\n\t\t\t\tadvance(id, mount, publication, context, (error) => this.report(error));\n\t\t});\n\t\tsession.subscribeClose(() => {\n\t\t\tthis.#closed = true;\n\t\t\tconst ends = closeEnds(this.#session.failure);\n\t\t\tfor (const mount of this.#mounts.values())\n\t\t\t\tfor (const windowed of [...mount.observers]) {\n\t\t\t\t\tcontained(\n\t\t\t\t\t\t() => windowed.observer.end(closeEndOf(windowed.observer, ends)),\n\t\t\t\t\t\t(error) => this.report(error),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\tthis.#mounts.clear();\n\t\t});\n\t}\n\n\t/** Report an observer's listener error through the Harness. */\n\treport(error: unknown): void {\n\t\tthis.#session.report(error);\n\t}\n\n\t/**\n\t * Attach a synchronous observer of the view (`Harness.observeConversation()`), behind `guardObserver()`; `context`\n\t * governs only the attachment.\n\t */\n\tasync observe(\n\t\tid: ConversationId,\n\t\tobserver: Observer<ConversationView>,\n\t\tcontext: Context,\n\t\twindow?: ConversationWindow,\n\t): Promise<Observation<ConversationView>> {\n\t\tlet value!: ConversationView;\n\t\tconst attached = await this.attach(\n\t\t\tid,\n\t\t\twindow,\n\t\t\t(current, release) => {\n\t\t\t\tvalue = current;\n\t\t\t\treturn guardObserver(observer, release, (error) => this.report(error));\n\t\t\t},\n\t\t\tcontext,\n\t\t);\n\t\tconst signal = context.abortSignal;\n\t\tif (signal?.aborted) {\n\t\t\tattached.detach();\n\t\t\tthrow signal.reason;\n\t\t}\n\t\treturn observation(value, attached.observer);\n\t}\n\n\t/** A serialized watch of the view, an observer of its mount; aborting `context` ends it `aborted`. */\n\tasync watch(\n\t\tid: ConversationId,\n\t\tcontext: Context,\n\t\twindow?: ConversationWindow,\n\t): Promise<WatchHandle<ConversationView>> {\n\t\tconst { observer } = await this.attach(\n\t\t\tid,\n\t\t\twindow,\n\t\t\t(value, release) => new Watch<ConversationView>(value, release, (error) => this.#session.report(error)),\n\t\t\tcontext,\n\t\t);\n\t\tconst signal = context.abortSignal;\n\t\tif (signal?.aborted) {\n\t\t\tobserver.abort();\n\t\t\tthrow signal.reason;\n\t\t}\n\t\tif (signal !== undefined) observer.observeAbort(signal);\n\t\treturn observer;\n\t}\n\n\t/**\n\t * Register an observer created from its window's first revision, atomically on the Session line: it sees every later\n\t * publication and nothing earlier. `release` drops it, and the mount with its last observer.\n\t */\n\tasync attach<O extends ViewObserver>(\n\t\tid: ConversationId,\n\t\twindow: ConversationWindow | undefined,\n\t\tcreate: (value: ConversationView, release: () => void) => O,\n\t\tcontext: Context,\n\t): Promise<{ observer: O; detach: () => void }> {\n\t\tconst bounds = resolveWindow(window);\n\t\treturn this.#session.readOnLine(async (storage) => {\n\t\t\tconst mount = this.#mounts.get(id) ?? (await this.#build(storage, id, context));\n\t\t\tconst { entries, before } = await loadWindow(storage, id, bounds, context);\n\t\t\tconst value = view(mount.conversation, entries, before, mount.docs);\n\t\t\tlet windowed: Windowed | undefined;\n\t\t\tconst detach = (): void => {\n\t\t\t\tif (windowed !== undefined) mount.observers.delete(windowed);\n\t\t\t\tif (mount.observers.size === 0 && this.#mounts.get(id) === mount) this.#mounts.delete(id);\n\t\t\t};\n\t\t\tconst observer = create(value, detach);\n\t\t\t// Close or cancellation may begin while the mount hydrates; register nothing then.\n\t\t\tif (this.#closed) throw closedError(this.#session);\n\t\t\tcontext.abortSignal?.throwIfAborted();\n\t\t\twindowed = { min: bounds.min, max: bounds.max, value, observer };\n\t\t\tthis.#mounts.set(id, mount);\n\t\t\tmount.observers.add(windowed);\n\t\t\treturn { observer, detach };\n\t\t});\n\t}\n\n\t/** Hydrate a mount on the line, through the line's `storage`. */\n\tasync #build(storage: Storage, id: ConversationId, context: Context): Promise<Mount> {\n\t\tconst conversation = await storage.conversation(id, context);\n\t\tif (conversation === undefined) throw new Error(`Conversation ${id} does not exist`);\n\t\tconst docs: Record<string, JsonObject> = {};\n\t\tconst incarnations = new Map<string, { id: DocumentId; version: number }>();\n\t\tfor (const token of MOUNTED) {\n\t\t\tconst loaded = await this.#session.conversationDocumentOnLine(token, id, context);\n\t\t\tif (loaded === undefined) continue;\n\t\t\tdocs[token.definition.kind] = loaded.value;\n\t\t\tincarnations.set(token.definition.kind, { id: loaded.record.id, version: loaded.version });\n\t\t}\n\t\treturn { conversation, docs, incarnations, observers: new Set() };\n\t}\n}\n\n/** A view revision; `before` is a key only when set. */\nfunction view(\n\tconversation: ConversationRecord,\n\tentries: readonly EntryRecord[],\n\tbefore: EntryId | undefined,\n\tdocs: Readonly<Record<string, JsonObject>>,\n): ConversationView {\n\treturn before === undefined ? { conversation, entries, docs } : { conversation, entries, before, docs };\n}\n\n/**\n * A new observer's window, read on the Session line with bounded scans: the entries from `from` when at most `max` are\n * at or after it, otherwise the newest `min`, and the entry before them.\n */\nasync function loadWindow(\n\tstorage: Storage,\n\tconversationId: ConversationId,\n\tbounds: WindowBounds,\n\tcontext: Context,\n): Promise<{ entries: readonly EntryRecord[]; before: EntryId | undefined }> {\n\tconst { from, min, max } = bounds;\n\tif (from !== undefined) {\n\t\tconst since = await scanUpTo(storage, { conversationId, minEntryId: from, order: \"ascending\" }, max + 1, context);\n\t\tif (since.length <= max) {\n\t\t\tconst query = { conversationId, maxEntryId: idFromNumber<EntryId>(from - 1) };\n\t\t\tconst previous = (await storage.scanEntries(query, 1, undefined, context)).items[0];\n\t\t\treturn { entries: since, before: previous?.id };\n\t\t}\n\t}\n\tconst newest = await scanUpTo(storage, { conversationId }, min + 1, context);\n\tconst before = newest.length > min ? newest.pop()!.id : undefined;\n\treturn { entries: newest.reverse(), before };\n}\n\n/** Up to `limit` entries of `query`, following cursors past short pages. */\nasync function scanUpTo(storage: Storage, query: EntryQuery, limit: number, context: Context): Promise<EntryRecord[]> {\n\tconst entries: EntryRecord[] = [];\n\tlet cursor: Cursor | undefined;\n\tdo {\n\t\tconst page = await storage.scanEntries(query, Math.min(SCAN_PAGE_SIZE, limit - entries.length), cursor, context);\n\t\tentries.push(...page.items);\n\t\tcursor = page.next;\n\t} while (cursor !== undefined && entries.length < limit);\n\treturn entries;\n}\n\n/**\n * Derive the mount's operations from one publication and hand each observer the next revision of its window; one that\n * throws is reported through `report`, and the others still get theirs. Documents are applied once and shared; each\n * window takes the appended entries and, past its `max`, drops its oldest down to its `min` in one splice.\n */\nfunction advance(\n\tid: ConversationId,\n\tmount: Mount,\n\tpublication: ObservedCommit,\n\tcontext: Context,\n\treport: (error: unknown) => void,\n): void {\n\tconst docOps: Op[] = [];\n\t// Entry writes are published in ID order.\n\tconst appended: EntryRecord[] = [];\n\tfor (const change of publication.changes) {\n\t\tif (change.type === \"entry\" && change.value.conversationId === id) {\n\t\t\tappended.push(change.value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (change.type !== \"document\" || change.conversationId !== id) continue;\n\t\tconst kind = change.record.kind;\n\t\tif (!MOUNTED_KINDS.has(kind) || change.record.key !== undefined) continue;\n\t\tconst path: NonEmptyPath = [\"docs\", kind];\n\t\tconst mounted = mount.incarnations.get(kind);\n\t\tif (change.kind === \"retire\") {\n\t\t\tif (mounted?.id !== change.record.id) continue;\n\t\t\tmount.incarnations.delete(kind);\n\t\t\tdocOps.push([\"d\", path]);\n\t\t} else if (mounted?.id === change.record.id && mounted.version === change.version) {\n\t\t\tfor (const op of change.ops) docOps.push(prefixed(op, path));\n\t\t} else {\n\t\t\tmount.incarnations.set(kind, { id: change.record.id, version: change.version });\n\t\t\tdocOps.push([\"s\", path, change.value]);\n\t\t}\n\t}\n\tif (docOps.length === 0 && appended.length === 0) return;\n\tif (docOps.length > 0) mount.docs = applyImmutable({ docs: mount.docs }, docOps).docs;\n\tconst frameContext = withoutAbortSignal(context);\n\tconst inserted = appended as unknown as JsonValue[];\n\tfor (const windowed of [...mount.observers]) {\n\t\tconst previous = windowed.value;\n\t\tlet entries = previous.entries;\n\t\tlet before = previous.before;\n\t\tlet ops: Op[] = docOps;\n\t\tif (appended.length > 0) {\n\t\t\tops = [...docOps, [\"p\", [\"entries\"], entries.length, 0, inserted]];\n\t\t\tentries = entries.concat(appended);\n\t\t\tif (entries.length > windowed.max) {\n\t\t\t\tconst drop = entries.length - windowed.min;\n\t\t\t\tbefore = entries[drop - 1]!.id;\n\t\t\t\tentries = entries.slice(drop);\n\t\t\t\tops.push([\"p\", [\"entries\"], 0, drop, []], [\"s\", [\"before\"], before]);\n\t\t\t}\n\t\t}\n\t\twindowed.value = view(mount.conversation, entries, before, mount.docs);\n\t\tconst call: WatchCall<ConversationView> = { kind: \"value\", value: windowed.value, ops, retired: false };\n\t\tcontained(() => windowed.observer.advance(call, frameContext), report);\n\t}\n}\n\n/** `op` moved under `prefix`; a root replacement becomes a set of the prefix. */\nfunction prefixed(op: Op, prefix: NonEmptyPath): Op {\n\tconst at = (path: Path): NonEmptyPath => [...prefix, ...path] as unknown as NonEmptyPath;\n\tswitch (op[0]) {\n\t\tcase \"r\":\n\t\t\treturn [\"s\", prefix, op[1]];\n\t\tcase \"p\":\n\t\t\treturn [\"p\", at(op[1]), op[2], op[3], op[4]];\n\t\tcase \"m\":\n\t\t\treturn [\"m\", at(op[1]), op[2]];\n\t\tcase \"s\":\n\t\t\treturn [\"s\", at(op[1]), op[2]];\n\t\tcase \"d\":\n\t\t\treturn [\"d\", at(op[1])];\n\t\tcase \"a\":\n\t\t\treturn [\"a\", at(op[1]), op[2]];\n\t\tcase \"t\":\n\t\t\treturn [\"t\", at(op[1]), op[2]];\n\t}\n}\n"]}
1
+ {"version":3,"file":"view.js","sourceRoot":"","sources":["../../src/harness/view.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,cAAc,EAAyC,MAAM,oBAAoB,CAAC;AAE3F,OAAO,EAAE,KAAK,EAAmD,MAAM,oBAAoB,CAAC;AAC5F,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EACN,UAAU,EACV,SAAS,EACT,SAAS,EACT,aAAa,EAEb,WAAW,GAEX,MAAM,uBAAuB,CAAC;AAe/B,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAkCxC,wCAAwC;AACxC,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAS9B,MAAM,OAAO,GAAG;IACf,QAAQ;IACR,OAAO;IACP,QAAQ;IACR,WAAW;IACX,QAAQ;CACkD,CAAC;AAC5D,MAAM,aAAa,GAAwB,IAAI,GAAG,CAAC,OA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AAC,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7B,KAAK,GAAG;YACP,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAC9C,KAAK,GAAG;YACP,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAChC,KAAK,GAAG;YACP,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAChC,KAAK,GAAG;YACP,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACzB,KAAK,GAAG;YACP,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QAChC,KAAK,GAAG;YACP,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IACjC,CAAC;AACF,CAAC","sourcesContent":["import { type Context, withoutAbortSignal } from \"@draht/chord/context\";\nimport { applyImmutable, type NonEmptyPath, type Op, type Path } from \"@draht/chord/delta\";\nimport type { JsonValue } from \"@draht/chord/json\";\nimport { Watch, type WatchCall, type WatchEnd, type WatchHandle } from \"@draht/chord/watch\";\nimport { idFromNumber } from \"../ids.ts\";\nimport {\n\tcloseEndOf,\n\tcloseEnds,\n\tcontained,\n\tguardObserver,\n\ttype ObservedCommit,\n\tobservation,\n\ttype SessionImpl,\n} from \"../session/session.ts\";\nimport type {\n\tConversationDocToken,\n\tConversationId,\n\tConversationRecord,\n\tCursor,\n\tDocumentId,\n\tEntryId,\n\tEntryQuery,\n\tEntryRecord,\n\tJsonObject,\n\tObservation,\n\tObserver,\n\tStorage,\n} from \"../types.ts\";\nimport { AgentDoc } from \"./agent.ts\";\nimport { InboxDoc } from \"./inbox.ts\";\nimport { LiveDoc } from \"./live.ts\";\nimport { ProviderDoc } from \"./provider.ts\";\nimport { UsageDoc } from \"./usage.ts\";\nimport { closedError } from \"./util.ts\";\n\n/** Structural view of one conversation: a window over its transcript and its built-in documents (spec §9.3). */\nexport type ConversationView = {\n\treadonly conversation: ConversationRecord;\n\t/**\n\t * A window over the transcript, its fork-aware history (`Conversation.entries()`), in entry ID order. Head markers\n\t * such as compaction summaries sit where they were written; their `head` tells where the entries they summarize end.\n\t */\n\treadonly entries: readonly EntryRecord[];\n\t/** ID of the entry just before the window; absent when the window starts the transcript. */\n\treadonly before?: EntryId;\n\t/** Built-in conversation documents keyed by kind; absent documents are absent. */\n\treadonly docs: Readonly<Record<string, JsonObject>>;\n};\n\n/**\n * Which entries a view's window holds (spec §9.3). The window holds between `min` and `max` entries: it starts with\n * the newest `min` entries, takes appends, and once it would hold more than `max`, drops its oldest in one splice down\n * to `min`. With `from`, it starts at `from` instead when at most `max` entries are at or after it.\n */\nexport type ConversationWindow = {\n\t/**\n\t * Where the first value's window starts, inclusive, such as right after the newest entry a client has\n\t * (`ConversationTranscript.resume`). It selects only that first value: every entry committed after the attachment is\n\t * appended, whatever its ID. A `from` past the newest entry starts the window empty, with `before` the newest entry.\n\t */\n\treadonly from?: EntryId;\n\t/** Default 50; an integer, at least 1. */\n\treadonly min?: number;\n\t/** Default `2 * min`; an integer, at least `min`. */\n\treadonly max?: number;\n};\n\n/** Default `ConversationWindow.min`. */\nconst DEFAULT_WINDOW_MIN = 50;\n\n/** Receives each next revision of one observer's window, and the Session's close. */\nexport type ViewObserver = {\n\tadvance(call: WatchCall<ConversationView>, context: Context): void;\n\t/** The Session closed (`ended`), or failed (`failed`). */\n\tend(end: WatchEnd): void;\n};\n\nconst MOUNTED = [\n\tAgentDoc,\n\tLiveDoc,\n\tInboxDoc,\n\tProviderDoc,\n\tUsageDoc,\n] as unknown as readonly ConversationDocToken<JsonObject>[];\nconst MOUNTED_KINDS: ReadonlySet<string> = new Set(MOUNTED.map((token) => token.definition.kind));\nconst SCAN_PAGE_SIZE = 256;\n\n/**\n * One observer of a mount and its window: the bounds and the revision it was last given, from which the next one is\n * derived (its entries and `before`: a publication's splices are positions in it). Its `value` is replaced at each\n * revision, so the mount keeps no earlier one.\n */\ntype Windowed = {\n\treadonly min: number;\n\treadonly max: number;\n\tvalue: ConversationView;\n\treadonly observer: ViewObserver;\n};\n\n/**\n * Where an observer's release finds its `Windowed`: none until it is registered;\n * a release before that drops nothing.\n */\ntype WindowSlot = { windowed: Windowed | undefined };\n\n/**\n * One conversation's mount: the documents it shows, shared by every observer, and the observers, each with its own\n * window over the entries.\n */\ntype Mount = {\n\treadonly conversation: ConversationRecord;\n\tdocs: Readonly<Record<string, JsonObject>>;\n\t/** Mounted incarnation and definition version per kind; another incarnation or version is set whole. */\n\treadonly incarnations: Map<string, { id: DocumentId; version: number }>;\n\treadonly observers: Set<Windowed>;\n};\n\nconst VIEWS = new WeakMap<object, ConversationViews>();\n\n/** The view mounts of a Harness, for adapters built on them. */\nexport function conversationViews(harness: object): ConversationViews {\n\tconst views = VIEWS.get(harness);\n\tif (views === undefined) throw new Error(\"Not a Harness\");\n\treturn views;\n}\n\n/** A window with its defaults applied. */\ntype WindowBounds = { readonly from: EntryId | undefined; readonly min: number; readonly max: number };\n\n/** `window` with its defaults; throws a `RangeError` for bounds that are not integers or `max` below `min`. */\nfunction resolveWindow(window: ConversationWindow | undefined): WindowBounds {\n\tconst min = window?.min ?? DEFAULT_WINDOW_MIN;\n\tif (!Number.isSafeInteger(min) || min < 1) throw new RangeError(`Window min must be an integer >= 1, got ${min}`);\n\tconst max = window?.max ?? 2 * min;\n\tif (!Number.isSafeInteger(max) || max < min) {\n\t\tthrow new RangeError(`Window max must be an integer >= min (${min}), got ${max}`);\n\t}\n\tconst from = window?.from;\n\tif (from !== undefined && !Number.isSafeInteger(from)) {\n\t\tthrow new RangeError(`Window from must be an entry ID, got ${from}`);\n\t}\n\treturn { from, min, max };\n}\n\n/**\n * The Harness's conversation view mounts: at most one per conversation, built on the Session line by its first\n * observer and dropped with its last. Each mount advances from the Session's commits as memory adopts them, deferred ones\n * (`CommitPersistence`) before they are stored, and hands each observer the next revision of its own window.\n */\nexport class ConversationViews {\n\treadonly #session: SessionImpl;\n\treadonly #mounts = new Map<ConversationId, Mount>();\n\t#closed = false;\n\n\tconstructor(session: SessionImpl) {\n\t\tthis.#session = session;\n\t\tVIEWS.set(session, this);\n\t\tsession.followCommits((publication, context) => {\n\t\t\tfor (const [id, mount] of this.#mounts)\n\t\t\t\tadvance(id, mount, publication, context, (error) => this.report(error));\n\t\t});\n\t\tsession.subscribeClose(() => {\n\t\t\tthis.#closed = true;\n\t\t\tconst ends = closeEnds(this.#session.failure);\n\t\t\tfor (const mount of this.#mounts.values())\n\t\t\t\tfor (const windowed of [...mount.observers]) {\n\t\t\t\t\tcontained(\n\t\t\t\t\t\t() => windowed.observer.end(closeEndOf(windowed.observer, ends)),\n\t\t\t\t\t\t(error) => this.report(error),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\tthis.#mounts.clear();\n\t\t});\n\t}\n\n\t/** Report an observer's listener error through the Harness. */\n\treport(error: unknown): void {\n\t\tthis.#session.report(error);\n\t}\n\n\t/**\n\t * Attach a synchronous observer of the view (`Harness.observeConversation()`), behind `guardObserver()`; `context`\n\t * governs only the attachment.\n\t */\n\tasync observe(\n\t\tid: ConversationId,\n\t\tobserver: Observer<ConversationView>,\n\t\tcontext: Context,\n\t\twindow?: ConversationWindow,\n\t): Promise<Observation<ConversationView>> {\n\t\t// The first revision comes back from `attach`, never captured here: a closure made in this scope keeps the scope,\n\t\t// and with it a captured revision, for as long as it is kept: the guard's report for the observer's life (and\n\t\t// `create`, were anything to keep it) (ERNDL-1289).\n\t\tconst attached = await this.attach(\n\t\t\tid,\n\t\t\twindow,\n\t\t\t(_value, release) => guardObserver(observer, release, (error) => this.report(error)),\n\t\t\tcontext,\n\t\t);\n\t\tconst signal = context.abortSignal;\n\t\tif (signal?.aborted) {\n\t\t\tattached.detach();\n\t\t\tthrow signal.reason;\n\t\t}\n\t\treturn observation(attached.value, attached.observer);\n\t}\n\n\t/** A serialized watch of the view, an observer of its mount; aborting `context` ends it `aborted`. */\n\tasync watch(\n\t\tid: ConversationId,\n\t\tcontext: Context,\n\t\twindow?: ConversationWindow,\n\t): Promise<WatchHandle<ConversationView>> {\n\t\tconst { observer } = await this.attach(\n\t\t\tid,\n\t\t\twindow,\n\t\t\t(value, release) => new Watch<ConversationView>(value, release, (error) => this.#session.report(error)),\n\t\t\tcontext,\n\t\t);\n\t\tconst signal = context.abortSignal;\n\t\tif (signal?.aborted) {\n\t\t\tobserver.abort();\n\t\t\tthrow signal.reason;\n\t\t}\n\t\tif (signal !== undefined) observer.observeAbort(signal);\n\t\treturn observer;\n\t}\n\n\t/**\n\t * Register an observer created from its window's first revision, atomically on the Session line: it sees every later\n\t * publication and nothing earlier. `release` drops it, and the mount with its last observer. Resolves with the\n\t * observer, its release as `detach`, and that first revision, which the mount stops keeping at the next one. The\n\t * mount is looked up after the window's read: one its last observer let go of meanwhile missed the publications\n\t * since, so it is hydrated again rather than put back stale. An absent conversation is rejected before the read.\n\t */\n\tasync attach<O extends ViewObserver>(\n\t\tid: ConversationId,\n\t\twindow: ConversationWindow | undefined,\n\t\tcreate: (value: ConversationView, release: () => void) => O,\n\t\tcontext: Context,\n\t): Promise<{ observer: O; detach: () => void; value: ConversationView }> {\n\t\tconst bounds = resolveWindow(window);\n\t\treturn this.#session.readOnLine(async (storage) => {\n\t\t\t// The record never changes: a mount's, else the stored one (the read `#build` made before), absent rejected first.\n\t\t\tconst conversation = this.#mounts.get(id)?.conversation ?? (await storage.conversation(id, context));\n\t\t\tif (conversation === undefined) throw new Error(`Conversation ${id} does not exist`);\n\t\t\tconst { entries, before } = await loadWindow(storage, id, bounds, context);\n\t\t\t// No await between this lookup and the registration below: a mount found here is the one publications advance.\n\t\t\tconst mount = this.#mounts.get(id) ?? (await this.#build(conversation, context));\n\t\t\tconst value = view(mount.conversation, entries, before, mount.docs);\n\t\t\tconst slot: WindowSlot = { windowed: undefined };\n\t\t\tconst detach = this.#release(id, mount, slot);\n\t\t\tconst observer = create(value, detach);\n\t\t\t// Close or cancellation may begin while the mount hydrates; register nothing then.\n\t\t\tif (this.#closed) throw closedError(this.#session);\n\t\t\tcontext.abortSignal?.throwIfAborted();\n\t\t\tslot.windowed = { min: bounds.min, max: bounds.max, value, observer };\n\t\t\tthis.#mounts.set(id, mount);\n\t\t\tmount.observers.add(slot.windowed);\n\t\t\treturn { observer, detach, value };\n\t\t});\n\t}\n\n\t/**\n\t * The release of the observer `slot` will hold: it drops that observer, and `mount` with its last one. Made here,\n\t * not in `attach`: a closure there would keep `attach`'s scope for the observer's life, with the attachment's\n\t * context and `create` (ERNDL-1289).\n\t */\n\t#release(id: ConversationId, mount: Mount, slot: WindowSlot): () => void {\n\t\treturn () => {\n\t\t\tif (slot.windowed !== undefined) mount.observers.delete(slot.windowed);\n\t\t\tif (mount.observers.size === 0 && this.#mounts.get(id) === mount) this.#mounts.delete(id);\n\t\t};\n\t}\n\n\t/** Hydrate a mount of `conversation` on the line: its documents, read through the line. */\n\tasync #build(conversation: ConversationRecord, context: Context): Promise<Mount> {\n\t\tconst docs: Record<string, JsonObject> = {};\n\t\tconst incarnations = new Map<string, { id: DocumentId; version: number }>();\n\t\tfor (const token of MOUNTED) {\n\t\t\tconst loaded = await this.#session.conversationDocumentOnLine(token, conversation.id, context);\n\t\t\tif (loaded === undefined) continue;\n\t\t\tdocs[token.definition.kind] = loaded.value;\n\t\t\tincarnations.set(token.definition.kind, { id: loaded.record.id, version: loaded.version });\n\t\t}\n\t\treturn { conversation, docs, incarnations, observers: new Set() };\n\t}\n}\n\n/** A view revision; `before` is a key only when set. */\nfunction view(\n\tconversation: ConversationRecord,\n\tentries: readonly EntryRecord[],\n\tbefore: EntryId | undefined,\n\tdocs: Readonly<Record<string, JsonObject>>,\n): ConversationView {\n\treturn before === undefined ? { conversation, entries, docs } : { conversation, entries, before, docs };\n}\n\n/**\n * A new observer's window, read on the Session line with bounded scans: the entries from `from` when at most `max` are\n * at or after it, otherwise the newest `min`, and the entry before them.\n */\nasync function loadWindow(\n\tstorage: Storage,\n\tconversationId: ConversationId,\n\tbounds: WindowBounds,\n\tcontext: Context,\n): Promise<{ entries: readonly EntryRecord[]; before: EntryId | undefined }> {\n\tconst { from, min, max } = bounds;\n\tif (from !== undefined) {\n\t\tconst since = await scanUpTo(storage, { conversationId, minEntryId: from, order: \"ascending\" }, max + 1, context);\n\t\tif (since.length <= max) {\n\t\t\tconst query = { conversationId, maxEntryId: idFromNumber<EntryId>(from - 1) };\n\t\t\tconst previous = (await storage.scanEntries(query, 1, undefined, context)).items[0];\n\t\t\treturn { entries: since, before: previous?.id };\n\t\t}\n\t}\n\tconst newest = await scanUpTo(storage, { conversationId }, min + 1, context);\n\tconst before = newest.length > min ? newest.pop()!.id : undefined;\n\treturn { entries: newest.reverse(), before };\n}\n\n/** Up to `limit` entries of `query`, following cursors past short pages. */\nasync function scanUpTo(storage: Storage, query: EntryQuery, limit: number, context: Context): Promise<EntryRecord[]> {\n\tconst entries: EntryRecord[] = [];\n\tlet cursor: Cursor | undefined;\n\tdo {\n\t\tconst page = await storage.scanEntries(query, Math.min(SCAN_PAGE_SIZE, limit - entries.length), cursor, context);\n\t\tentries.push(...page.items);\n\t\tcursor = page.next;\n\t} while (cursor !== undefined && entries.length < limit);\n\treturn entries;\n}\n\n/**\n * Derive the mount's operations from one publication and hand each observer the next revision of its window; one that\n * throws is reported through `report`, and the others still get theirs. Documents are applied once and shared; each\n * window takes the appended entries and, past its `max`, drops its oldest down to its `min` in one splice.\n */\nfunction advance(\n\tid: ConversationId,\n\tmount: Mount,\n\tpublication: ObservedCommit,\n\tcontext: Context,\n\treport: (error: unknown) => void,\n): void {\n\tconst docOps: Op[] = [];\n\t// Entry writes are published in ID order.\n\tconst appended: EntryRecord[] = [];\n\tfor (const change of publication.changes) {\n\t\tif (change.type === \"entry\" && change.value.conversationId === id) {\n\t\t\tappended.push(change.value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (change.type !== \"document\" || change.conversationId !== id) continue;\n\t\tconst kind = change.record.kind;\n\t\tif (!MOUNTED_KINDS.has(kind) || change.record.key !== undefined) continue;\n\t\tconst path: NonEmptyPath = [\"docs\", kind];\n\t\tconst mounted = mount.incarnations.get(kind);\n\t\tif (change.kind === \"retire\") {\n\t\t\tif (mounted?.id !== change.record.id) continue;\n\t\t\tmount.incarnations.delete(kind);\n\t\t\tdocOps.push([\"d\", path]);\n\t\t} else if (mounted?.id === change.record.id && mounted.version === change.version) {\n\t\t\tfor (const op of change.ops) docOps.push(prefixed(op, path));\n\t\t} else {\n\t\t\tmount.incarnations.set(kind, { id: change.record.id, version: change.version });\n\t\t\tdocOps.push([\"s\", path, change.value]);\n\t\t}\n\t}\n\tif (docOps.length === 0 && appended.length === 0) return;\n\tif (docOps.length > 0) mount.docs = applyImmutable({ docs: mount.docs }, docOps).docs;\n\tconst frameContext = withoutAbortSignal(context);\n\tconst inserted = appended as unknown as JsonValue[];\n\tfor (const windowed of [...mount.observers]) {\n\t\tconst previous = windowed.value;\n\t\tlet entries = previous.entries;\n\t\tlet before = previous.before;\n\t\tlet ops: Op[] = docOps;\n\t\tif (appended.length > 0) {\n\t\t\tops = [...docOps, [\"p\", [\"entries\"], entries.length, 0, inserted]];\n\t\t\tentries = entries.concat(appended);\n\t\t\tif (entries.length > windowed.max) {\n\t\t\t\tconst drop = entries.length - windowed.min;\n\t\t\t\tbefore = entries[drop - 1]!.id;\n\t\t\t\tentries = entries.slice(drop);\n\t\t\t\tops.push([\"p\", [\"entries\"], 0, drop, []], [\"s\", [\"before\"], before]);\n\t\t\t}\n\t\t}\n\t\twindowed.value = view(mount.conversation, entries, before, mount.docs);\n\t\tconst call: WatchCall<ConversationView> = { kind: \"value\", value: windowed.value, ops, retired: false };\n\t\tcontained(() => windowed.observer.advance(call, frameContext), report);\n\t}\n}\n\n/** `op` moved under `prefix`; a root replacement becomes a set of the prefix. */\nfunction prefixed(op: Op, prefix: NonEmptyPath): Op {\n\tconst at = (path: Path): NonEmptyPath => [...prefix, ...path] as unknown as NonEmptyPath;\n\tswitch (op[0]) {\n\t\tcase \"r\":\n\t\t\treturn [\"s\", prefix, op[1]];\n\t\tcase \"p\":\n\t\t\treturn [\"p\", at(op[1]), op[2], op[3], op[4]];\n\t\tcase \"m\":\n\t\t\treturn [\"m\", at(op[1]), op[2]];\n\t\tcase \"s\":\n\t\t\treturn [\"s\", at(op[1]), op[2]];\n\t\tcase \"d\":\n\t\t\treturn [\"d\", at(op[1])];\n\t\tcase \"a\":\n\t\t\treturn [\"a\", at(op[1]), op[2]];\n\t\tcase \"t\":\n\t\t\treturn [\"t\", at(op[1]), op[2]];\n\t}\n}\n"]}
package/dist/ids.d.ts CHANGED
@@ -3,4 +3,14 @@ import type { Id, Seq } from "./types.ts";
3
3
  export declare function idFromNumber<I extends Id<string>>(value: number): I;
4
4
  /** Apply the erased commit-sequence brand at a trusted storage boundary. */
5
5
  export declare function seqFromNumber(value: number): Seq;
6
+ /** An identity string, by what it names. */
7
+ export type Identity = "Task kind" | "Request ID" | "Document kind" | "Document key";
8
+ /**
9
+ * Why `value` cannot be the identity `what`, or `undefined` when it can. Backends keep identities as plain text: a lone
10
+ * surrogate becomes U+FFFD in some SQLite bindings and Chord's store refuses NUL. An empty request ID or document key
11
+ * would match Chord's `""` for an absent one.
12
+ */
13
+ export declare function identityProblem(what: Identity, value: string): string | undefined;
14
+ /** Throws a `TypeError` for an identity `identityProblem` refuses, where it enters Durable. */
15
+ export declare function checkIdentity(what: Identity, value: string): void;
6
16
  //# sourceMappingURL=ids.d.ts.map
package/dist/ids.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ids.d.ts","sourceRoot":"","sources":["../src/ids.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAE1C,qFAAqF;AACrF,wBAAgB,YAAY,CAAC,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,GAAG,CAAC,CAEnE;AAED,4EAA4E;AAC5E,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,CAEhD"}
1
+ {"version":3,"file":"ids.d.ts","sourceRoot":"","sources":["../src/ids.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,EAAE,EAAE,GAAG,EAAE,MAAM,YAAY,CAAC;AAE1C,qFAAqF;AACrF,wBAAgB,YAAY,CAAC,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,GAAG,CAAC,CAEnE;AAED,4EAA4E;AAC5E,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,CAEhD;AAED,4CAA4C;AAC5C,MAAM,MAAM,QAAQ,GAAG,WAAW,GAAG,YAAY,GAAG,eAAe,GAAG,cAAc,CAAC;AAErF;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAMjF;AAED,+FAA+F;AAC/F,wBAAgB,aAAa,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAGjE"}
package/dist/ids.js CHANGED
@@ -1,3 +1,5 @@
1
+ // Durable's identifiers: numeric record IDs and seqs given their brands at a trusted boundary, and the strings Storage
2
+ // indexes as plain text (task kinds, request IDs, document kinds and keys) with what they may hold.
1
3
  /** Apply an erased ID brand at a trusted numeric allocation or decoding boundary. */
2
4
  export function idFromNumber(value) {
3
5
  return value;
@@ -6,4 +8,23 @@ export function idFromNumber(value) {
6
8
  export function seqFromNumber(value) {
7
9
  return value;
8
10
  }
11
+ /**
12
+ * Why `value` cannot be the identity `what`, or `undefined` when it can. Backends keep identities as plain text: a lone
13
+ * surrogate becomes U+FFFD in some SQLite bindings and Chord's store refuses NUL. An empty request ID or document key
14
+ * would match Chord's `""` for an absent one.
15
+ */
16
+ export function identityProblem(what, value) {
17
+ if (value === "" && (what === "Request ID" || what === "Document key"))
18
+ return `${what} must not be empty`;
19
+ if (!value.isWellFormed() || value.includes("\0")) {
20
+ return `${what} ${JSON.stringify(value)} contains a lone surrogate or NUL`;
21
+ }
22
+ return undefined;
23
+ }
24
+ /** Throws a `TypeError` for an identity `identityProblem` refuses, where it enters Durable. */
25
+ export function checkIdentity(what, value) {
26
+ const problem = identityProblem(what, value);
27
+ if (problem !== undefined)
28
+ throw new TypeError(problem);
29
+ }
9
30
  //# sourceMappingURL=ids.js.map
package/dist/ids.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ids.js","sourceRoot":"","sources":["../src/ids.ts"],"names":[],"mappings":"AAEA,qFAAqF;AACrF,MAAM,UAAU,YAAY,CAAuB,KAAa;IAC/D,OAAO,KAAU,CAAC;AACnB,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,aAAa,CAAC,KAAa;IAC1C,OAAO,KAAY,CAAC;AACrB,CAAC","sourcesContent":["import type { Id, Seq } from \"./types.ts\";\n\n/** Apply an erased ID brand at a trusted numeric allocation or decoding boundary. */\nexport function idFromNumber<I extends Id<string>>(value: number): I {\n\treturn value as I;\n}\n\n/** Apply the erased commit-sequence brand at a trusted storage boundary. */\nexport function seqFromNumber(value: number): Seq {\n\treturn value as Seq;\n}\n"]}
1
+ {"version":3,"file":"ids.js","sourceRoot":"","sources":["../src/ids.ts"],"names":[],"mappings":"AAAA,uHAAuH;AACvH,oGAAoG;AAIpG,qFAAqF;AACrF,MAAM,UAAU,YAAY,CAAuB,KAAa;IAC/D,OAAO,KAAU,CAAC;AACnB,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,aAAa,CAAC,KAAa;IAC1C,OAAO,KAAY,CAAC;AACrB,CAAC;AAKD;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,IAAc,EAAE,KAAa;IAC5D,IAAI,KAAK,KAAK,EAAE,IAAI,CAAC,IAAI,KAAK,YAAY,IAAI,IAAI,KAAK,cAAc,CAAC;QAAE,OAAO,GAAG,IAAI,oBAAoB,CAAC;IAC3G,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QACnD,OAAO,GAAG,IAAI,IAAI,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,mCAAmC,CAAC;IAC5E,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CAAC;AAED,+FAA+F;AAC/F,MAAM,UAAU,aAAa,CAAC,IAAc,EAAE,KAAa;IAC1D,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAC7C,IAAI,OAAO,KAAK,SAAS;QAAE,MAAM,IAAI,SAAS,CAAC,OAAO,CAAC,CAAC;AACzD,CAAC","sourcesContent":["// Durable's identifiers: numeric record IDs and seqs given their brands at a trusted boundary, and the strings Storage\n// indexes as plain text (task kinds, request IDs, document kinds and keys) with what they may hold.\n\nimport type { Id, Seq } from \"./types.ts\";\n\n/** Apply an erased ID brand at a trusted numeric allocation or decoding boundary. */\nexport function idFromNumber<I extends Id<string>>(value: number): I {\n\treturn value as I;\n}\n\n/** Apply the erased commit-sequence brand at a trusted storage boundary. */\nexport function seqFromNumber(value: number): Seq {\n\treturn value as Seq;\n}\n\n/** An identity string, by what it names. */\nexport type Identity = \"Task kind\" | \"Request ID\" | \"Document kind\" | \"Document key\";\n\n/**\n * Why `value` cannot be the identity `what`, or `undefined` when it can. Backends keep identities as plain text: a lone\n * surrogate becomes U+FFFD in some SQLite bindings and Chord's store refuses NUL. An empty request ID or document key\n * would match Chord's `\"\"` for an absent one.\n */\nexport function identityProblem(what: Identity, value: string): string | undefined {\n\tif (value === \"\" && (what === \"Request ID\" || what === \"Document key\")) return `${what} must not be empty`;\n\tif (!value.isWellFormed() || value.includes(\"\\0\")) {\n\t\treturn `${what} ${JSON.stringify(value)} contains a lone surrogate or NUL`;\n\t}\n\treturn undefined;\n}\n\n/** Throws a `TypeError` for an identity `identityProblem` refuses, where it enters Durable. */\nexport function checkIdentity(what: Identity, value: string): void {\n\tconst problem = identityProblem(what, value);\n\tif (problem !== undefined) throw new TypeError(problem);\n}\n"]}
@@ -0,0 +1,33 @@
1
+ import { type ImageLimits, type PreparedImage } from "../tools/image-processor.ts";
2
+ /** A width and height in pixels. */
3
+ export type ImageSize = {
4
+ readonly width: number;
5
+ readonly height: number;
6
+ };
7
+ /** A processor's upright image, starting at the fitted size, encoded at the sizes `encodeToFit` asks for. */
8
+ export type ImageEncoder = {
9
+ /** Scales the image down to `size`, smaller than its current one, for the next encodings. */
10
+ shrink(size: ImageSize): void;
11
+ /** The image as PNG, read before the next call; `undefined` when it cannot be encoded. */
12
+ png(): Uint8Array | undefined;
13
+ /** The image as JPEG at `quality`, as `png()` returns it. */
14
+ jpeg(quality: number): Uint8Array | undefined;
15
+ };
16
+ /**
17
+ * Whether an image may go back as it is, its size aside: a type providers take inline that its bytes are (an image
18
+ * declared as another type goes back re-encoded, never under the wrong type), already upright (EXIF `orientation` 1),
19
+ * and its base64 within the byte limit.
20
+ */
21
+ export declare function mayReturnAsIs(bytes: Uint8Array, mimeType: string, orientation: number, limits: ImageLimits): boolean;
22
+ /** Whether `size` is within the limits' width and height. */
23
+ export declare function withinLimits(size: ImageSize, limits: ImageLimits): boolean;
24
+ /** The largest size within the limits' width and height with `size`'s aspect, never larger, at least 1x1. */
25
+ export declare function fittedSize(size: ImageSize, limits: ImageLimits): ImageSize;
26
+ /**
27
+ * `encoder`'s image, upright at `from` before resizing, as the first encoding whose base64 fits `maxBytes`: at
28
+ * `first`, the encoder's starting size, then 3/4 smaller each round, down to 1x1; `undefined` when not even that fits.
29
+ * `resized` is set when the size changed, `convertedFrom` when the format differs from `mimeType`, the source's
30
+ * declared type.
31
+ */
32
+ export declare function encodeToFit(encoder: ImageEncoder, from: ImageSize, first: ImageSize, mimeType: string, maxBytes: number): PreparedImage | undefined;
33
+ //# sourceMappingURL=encode.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encode.d.ts","sourceRoot":"","sources":["../../src/images/encode.ts"],"names":[],"mappings":"AAMA,OAAO,EAEN,KAAK,WAAW,EAEhB,KAAK,aAAa,EAElB,MAAM,6BAA6B,CAAC;AAErC,oCAAoC;AACpC,MAAM,MAAM,SAAS,GAAG;IAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAE5E,6GAA6G;AAC7G,MAAM,MAAM,YAAY,GAAG;IAC1B,6FAA6F;IAC7F,MAAM,CAAC,IAAI,EAAE,SAAS,GAAG,IAAI,CAAC;IAC9B,0FAA0F;IAC1F,GAAG,IAAI,UAAU,GAAG,SAAS,CAAC;IAC9B,6DAA6D;IAC7D,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,CAAC;CAC9C,CAAC;AAKF;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAOpH;AAED,6DAA6D;AAC7D,wBAAgB,YAAY,CAAC,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAE1E;AAED,6GAA6G;AAC7G,wBAAgB,UAAU,CAAC,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,GAAG,SAAS,CAG1E;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAC1B,OAAO,EAAE,YAAY,EACrB,IAAI,EAAE,SAAS,EACf,KAAK,EAAE,SAAS,EAChB,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,GACd,aAAa,GAAG,SAAS,CAa3B"}