@athenaintel/react 0.42.1 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +46 -7
  2. package/dist/agent-runtime/src/conversation-list-groups.d.ts +74 -0
  3. package/dist/agent-runtime/src/index.d.ts +3 -2
  4. package/dist/agent-runtime/src/messages.cjs +38 -7
  5. package/dist/agent-runtime/src/messages.cjs.map +1 -1
  6. package/dist/agent-runtime/src/messages.d.ts +26 -8
  7. package/dist/agent-runtime/src/messages.js +38 -7
  8. package/dist/agent-runtime/src/messages.js.map +1 -1
  9. package/dist/agent-runtime/src/quota-safe-local-storage-session.cjs +10 -0
  10. package/dist/agent-runtime/src/quota-safe-local-storage-session.cjs.map +1 -1
  11. package/dist/agent-runtime/src/quota-safe-local-storage-session.d.ts +7 -0
  12. package/dist/agent-runtime/src/quota-safe-local-storage-session.js +10 -0
  13. package/dist/agent-runtime/src/quota-safe-local-storage-session.js.map +1 -1
  14. package/dist/agent-runtime/src/session-lane-scope.cjs +25 -0
  15. package/dist/agent-runtime/src/session-lane-scope.cjs.map +1 -0
  16. package/dist/agent-runtime/src/session-lane-scope.d.ts +59 -0
  17. package/dist/agent-runtime/src/session-lane-scope.js +25 -0
  18. package/dist/agent-runtime/src/session-lane-scope.js.map +1 -0
  19. package/dist/agent-runtime/src/subagent-transcripts.cjs +2 -2
  20. package/dist/agent-runtime/src/subagent-transcripts.cjs.map +1 -1
  21. package/dist/agent-runtime/src/subagent-transcripts.d.ts +2 -2
  22. package/dist/agent-runtime/src/subagent-transcripts.js +3 -3
  23. package/dist/agent-runtime/src/subagent-transcripts.js.map +1 -1
  24. package/dist/agent-runtime/src/tool-metadata.cjs +0 -8
  25. package/dist/agent-runtime/src/tool-metadata.cjs.map +1 -1
  26. package/dist/agent-runtime/src/tool-metadata.js +0 -8
  27. package/dist/agent-runtime/src/tool-metadata.js.map +1 -1
  28. package/dist/agent-runtime/src/tool-names.cjs +4 -0
  29. package/dist/agent-runtime/src/tool-names.cjs.map +1 -1
  30. package/dist/agent-runtime/src/tool-names.d.ts +7 -0
  31. package/dist/agent-runtime/src/tool-names.js +4 -0
  32. package/dist/agent-runtime/src/tool-names.js.map +1 -1
  33. package/dist/agent-runtime/src/use-deep-agent-runtime.cjs +18 -1
  34. package/dist/agent-runtime/src/use-deep-agent-runtime.cjs.map +1 -1
  35. package/dist/agent-runtime/src/use-deep-agent-runtime.d.ts +19 -10
  36. package/dist/agent-runtime/src/use-deep-agent-runtime.js +19 -2
  37. package/dist/agent-runtime/src/use-deep-agent-runtime.js.map +1 -1
  38. package/dist/agent-runtime/src/use-deep-agent-thread.cjs +28 -10
  39. package/dist/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
  40. package/dist/agent-runtime/src/use-deep-agent-thread.d.ts +35 -3
  41. package/dist/agent-runtime/src/use-deep-agent-thread.js +28 -10
  42. package/dist/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
  43. package/dist/agent-runtime/src/use-deep-agent-voice.cjs +50 -15
  44. package/dist/agent-runtime/src/use-deep-agent-voice.cjs.map +1 -1
  45. package/dist/agent-runtime/src/use-deep-agent-voice.d.ts +8 -0
  46. package/dist/agent-runtime/src/use-deep-agent-voice.js +50 -15
  47. package/dist/agent-runtime/src/use-deep-agent-voice.js.map +1 -1
  48. package/dist/agent-runtime/src/voice-presentation.cjs +2 -0
  49. package/dist/agent-runtime/src/voice-presentation.cjs.map +1 -1
  50. package/dist/agent-runtime/src/voice-presentation.js +2 -0
  51. package/dist/agent-runtime/src/voice-presentation.js.map +1 -1
  52. package/dist/catalog/runtime-catalog.js +1 -1
  53. package/dist/chat/AthenaChat.cjs +125 -103
  54. package/dist/chat/AthenaChat.cjs.map +1 -1
  55. package/dist/chat/AthenaChat.d.ts +9 -0
  56. package/dist/chat/AthenaChat.js +126 -104
  57. package/dist/chat/AthenaChat.js.map +1 -1
  58. package/dist/chat/chat-voice-controls.cjs +128 -0
  59. package/dist/chat/chat-voice-controls.cjs.map +1 -0
  60. package/dist/chat/chat-voice-controls.d.ts +19 -0
  61. package/dist/chat/chat-voice-controls.js +128 -0
  62. package/dist/chat/chat-voice-controls.js.map +1 -0
  63. package/dist/chat/super-grouping/SuperGroupingCard.cjs +8 -2
  64. package/dist/chat/super-grouping/SuperGroupingCard.cjs.map +1 -1
  65. package/dist/chat/super-grouping/SuperGroupingCard.d.ts +6 -1
  66. package/dist/chat/super-grouping/SuperGroupingCard.js +8 -2
  67. package/dist/chat/super-grouping/SuperGroupingCard.js.map +1 -1
  68. package/dist/chat/super-grouping/ToolTimeline.cjs +27 -0
  69. package/dist/chat/super-grouping/ToolTimeline.cjs.map +1 -1
  70. package/dist/chat/super-grouping/ToolTimeline.d.ts +5 -1
  71. package/dist/chat/super-grouping/ToolTimeline.js +27 -0
  72. package/dist/chat/super-grouping/ToolTimeline.js.map +1 -1
  73. package/dist/chat/super-grouping/index.d.ts +1 -0
  74. package/dist/chat/super-grouping/timeline-step.cjs +61 -2
  75. package/dist/chat/super-grouping/timeline-step.cjs.map +1 -1
  76. package/dist/chat/super-grouping/timeline-step.d.ts +13 -1
  77. package/dist/chat/super-grouping/timeline-step.js +61 -2
  78. package/dist/chat/super-grouping/timeline-step.js.map +1 -1
  79. package/dist/chat/use-statewire-approval-request.js +1 -1
  80. package/dist/chat-ui/composer/tiptap-composer.cjs +42 -22
  81. package/dist/chat-ui/composer/tiptap-composer.cjs.map +1 -1
  82. package/dist/chat-ui/composer/tiptap-composer.d.ts +1 -0
  83. package/dist/chat-ui/composer/tiptap-composer.js +43 -23
  84. package/dist/chat-ui/composer/tiptap-composer.js.map +1 -1
  85. package/dist/chat-ui/mentions/mention-chip.cjs +144 -35
  86. package/dist/chat-ui/mentions/mention-chip.cjs.map +1 -1
  87. package/dist/chat-ui/mentions/mention-chip.d.ts +17 -1
  88. package/dist/chat-ui/mentions/mention-chip.js +146 -37
  89. package/dist/chat-ui/mentions/mention-chip.js.map +1 -1
  90. package/dist/chat-ui/mentions/suggestions/data/api-client.cjs +2 -1
  91. package/dist/chat-ui/mentions/suggestions/data/api-client.cjs.map +1 -1
  92. package/dist/chat-ui/mentions/suggestions/data/api-client.d.ts +3 -1
  93. package/dist/chat-ui/mentions/suggestions/data/api-client.js +2 -1
  94. package/dist/chat-ui/mentions/suggestions/data/api-client.js.map +1 -1
  95. package/dist/chat-ui/mentions/use-account-workspace-id.cjs +29 -51
  96. package/dist/chat-ui/mentions/use-account-workspace-id.cjs.map +1 -1
  97. package/dist/chat-ui/mentions/use-account-workspace-id.d.ts +2 -2
  98. package/dist/chat-ui/mentions/use-account-workspace-id.js +30 -52
  99. package/dist/chat-ui/mentions/use-account-workspace-id.js.map +1 -1
  100. package/dist/chat-ui/mentions/use-mention-asset.cjs +140 -0
  101. package/dist/chat-ui/mentions/use-mention-asset.cjs.map +1 -0
  102. package/dist/chat-ui/mentions/use-mention-asset.d.ts +16 -0
  103. package/dist/chat-ui/mentions/use-mention-asset.js +140 -0
  104. package/dist/chat-ui/mentions/use-mention-asset.js.map +1 -0
  105. package/dist/chat-ui/rich-text/chat-link.cjs +5 -4
  106. package/dist/chat-ui/rich-text/chat-link.cjs.map +1 -1
  107. package/dist/chat-ui/rich-text/chat-link.d.ts +2 -3
  108. package/dist/chat-ui/rich-text/chat-link.js +6 -5
  109. package/dist/chat-ui/rich-text/chat-link.js.map +1 -1
  110. package/dist/chat-ui/rich-text/chat-node-views.cjs +1 -0
  111. package/dist/chat-ui/rich-text/chat-node-views.cjs.map +1 -1
  112. package/dist/chat-ui/rich-text/chat-node-views.js +1 -0
  113. package/dist/chat-ui/rich-text/chat-node-views.js.map +1 -1
  114. package/dist/chat-ui/thread/composer-send-or-stop.cjs +2 -1
  115. package/dist/chat-ui/thread/composer-send-or-stop.cjs.map +1 -1
  116. package/dist/chat-ui/thread/composer-send-or-stop.d.ts +2 -0
  117. package/dist/chat-ui/thread/composer-send-or-stop.js +2 -1
  118. package/dist/chat-ui/thread/composer-send-or-stop.js.map +1 -1
  119. package/dist/diagnostics/athena-diagnostics.cjs.map +1 -1
  120. package/dist/diagnostics/athena-diagnostics.d.ts +1 -1
  121. package/dist/diagnostics/athena-diagnostics.js.map +1 -1
  122. package/dist/index.d.ts +1 -1
  123. package/dist/react/package.json.cjs +1 -1
  124. package/dist/react/package.json.js +1 -1
  125. package/dist/references/src/tool-option-schemas.d.ts +0 -34
  126. package/dist/runtime/statewire-session-key.cjs.map +1 -1
  127. package/dist/runtime/statewire-session-key.d.ts +8 -5
  128. package/dist/runtime/statewire-session-key.js.map +1 -1
  129. package/dist/runtime/useAthenaStatewireRuntime.cjs +5 -2
  130. package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
  131. package/dist/runtime/useAthenaStatewireRuntime.js +5 -2
  132. package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
  133. package/dist/styles.css +1 -1
  134. package/dist/threads/statewire-thread-list.cjs +6 -2
  135. package/dist/threads/statewire-thread-list.cjs.map +1 -1
  136. package/dist/threads/statewire-thread-list.js +6 -2
  137. package/dist/threads/statewire-thread-list.js.map +1 -1
  138. package/dist/tools/tool-summary.cjs +0 -2
  139. package/dist/tools/tool-summary.cjs.map +1 -1
  140. package/dist/tools/tool-summary.js +0 -2
  141. package/dist/tools/tool-summary.js.map +1 -1
  142. package/dist/voice/use-chat-voice-enabled.cjs +43 -0
  143. package/dist/voice/use-chat-voice-enabled.cjs.map +1 -0
  144. package/dist/voice/use-chat-voice-enabled.d.ts +9 -0
  145. package/dist/voice/use-chat-voice-enabled.js +43 -0
  146. package/dist/voice/use-chat-voice-enabled.js.map +1 -0
  147. package/package.json +4 -8
@@ -1 +1 @@
1
- {"version":3,"file":"quota-safe-local-storage-session.cjs","sources":["../../../../agent-runtime/src/quota-safe-local-storage-session.ts"],"sourcesContent":["import { resource, useResource } from \"@assistant-ui/tap\";\nimport type { StatewireClient, StatewireProtocol } from \"statewire\";\nimport { KeyValueSessionStorage } from \"statewire/storage\";\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { DEEP_AGENT_STATEWIRE_PROTOCOL } from \"./statewire-transport\";\n\nconst SESSION_PREFIX = \"aui:statewire-session:\";\nconst SESSION_LOCK_PREFIX = \"aui:statewire-session-lock:\";\nconst SESSION_ACTIVE_PREFIX = \"aui:statewire-session-active:\";\nconst DAY_MS = 24 * 60 * 60 * 1000;\n/** The stored-record formats the statewire this build ships reads (it writes 3). */\nconst READABLE_STORAGE_VERSIONS: ReadonlySet<unknown> = new Set([1, 2, 3]);\n\n/** Structural view of the browser storage global — this package compiles\n * without the DOM lib (React Native honesty; see `globals.d.ts`). */\ntype StorageLike = {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n key(index: number): string | null;\n readonly length: number;\n};\n\ntype LockGrant = object | null;\n\n/** The Web Locks API surface the session uses (`navigator.locks`). */\ntype LockManagerLike = {\n request<T>(\n name: string,\n callback: (lock: LockGrant) => T | Promise<T>\n ): Promise<T>;\n request<T>(\n name: string,\n options: { mode?: \"shared\" | \"exclusive\"; ifAvailable?: boolean },\n callback: (lock: LockGrant) => T | Promise<T>\n ): Promise<T>;\n};\n\ntype StorageEventLike = { key: string | null };\n\ntype BrowserGlobals = {\n localStorage?: StorageLike;\n navigator?: { locks?: LockManagerLike };\n addEventListener?: (\n type: \"storage\",\n listener: (event: StorageEventLike) => void\n ) => void;\n removeEventListener?: (\n type: \"storage\",\n listener: (event: StorageEventLike) => void\n ) => void;\n};\n\nconst browserGlobals = globalThis as BrowserGlobals;\n\n/** A persisted session record: per-lane failed entries (a pre-lane record carried them at the root). */\ntype SessionRecordLike = {\n failed?: unknown;\n lanes?: Record<string, { failed?: unknown } | null | undefined> | null;\n};\n\nexport function readPersistedFailedSendStamps(\n sessionKey: string\n): ReadonlyMap<string, number> | null {\n const storage = browserGlobals.localStorage;\n if (!storage) return null;\n let record: SessionRecordLike | null;\n try {\n const raw = storage.getItem(SESSION_PREFIX + sessionKey);\n record =\n raw === null ? null : (JSON.parse(raw) as SessionRecordLike | null);\n } catch {\n return null;\n }\n return readFailedSendStampsFromRecord(record);\n}\n\n/**\n * Send stamps (message id → epoch ms of the original send) off an already\n * loaded session record's failed lane — the storage-agnostic half of\n * {@link readPersistedFailedSendStamps}, for hosts whose session store is not\n * localStorage (the React Native AsyncStorage-backed store reads its record\n * synchronously through `SessionStorage.load()`).\n *\n * Returns `null` for no record (every failed entry then counts as fresh) and\n * an empty map for a record without failures.\n */\nexport function readFailedSendStampsFromRecord(\n record: SessionRecordLike | null | undefined\n): ReadonlyMap<string, number> | null {\n if (!record || typeof record !== \"object\") return null;\n const stamps = new Map<string, number>();\n const lanes =\n record.lanes && typeof record.lanes === \"object\" ? record.lanes : {};\n const failed = [\n ...(Array.isArray(record.failed) ? record.failed : []),\n ...Object.values(lanes).flatMap((lane) =>\n Array.isArray(lane?.failed) ? lane.failed : []\n ),\n ];\n for (const entry of failed) {\n const failed = entry as {\n ts?: unknown;\n params?: readonly { message?: { id?: unknown } }[];\n } | null;\n const messageId = failed?.params?.[0]?.message?.id;\n if (typeof messageId === \"string\" && typeof failed?.ts === \"number\") {\n stamps.set(messageId, failed.ts);\n }\n }\n return stamps;\n}\n\n/** A storage operation the session survived by degrading instead of failing. */\nexport type SessionStorageDegradation = {\n operation:\n | \"getItem\"\n | \"setItem\"\n | \"removeItem\"\n | \"getAllKeys\"\n | \"withUnused\"\n /** The lock manager refused the transaction fence; it ran unfenced. */\n | \"lock\"\n /**\n * The stored record is one this build cannot read (not JSON, or a newer\n * storage version): served as absent, and the key is shielded from being\n * overwritten so the record survives this tab.\n */\n | \"record\"\n /** statewire's own storage failure (a structurally invalid stored record). */\n | \"session\"\n /**\n * Queued commands persisted by an earlier statewire build no longer fit\n * the current wire/protocol range: parked in the lane's failed list (the\n * send-recovery sweep re-dispatches them) instead of blocking the mount.\n */\n | \"migrate\";\n key: string;\n error: unknown;\n};\n\ntype ProducedRange = NonNullable<StatewireClient.SessionCommand[\"produced\"]>;\n\nconst inRange = (value: string, range: StatewireProtocol.Range) =>\n value >= (range.minVersion ?? range.version) && value <= range.version;\n\n/** Mirrors statewire's own stored-command compatibility check. */\nconst storedCommandCompatible = (\n protocol: string,\n command: StatewireClient.SessionCommand,\n current: ProducedRange\n): boolean => {\n if (\n !command.produced ||\n !inRange(command.produced.wire.version, current.wire)\n )\n return false;\n if (current.protocols === \"*\") return true;\n if (command.produced.protocols === \"*\") return false;\n const produced = command.produced.protocols.find((p) => p.name === protocol);\n const offer = current.protocols.find((p) => p.name === protocol);\n return (\n produced !== undefined &&\n offer !== undefined &&\n inRange(produced.version, offer)\n );\n};\n\n/**\n * The oldest wire whose stored statements the current client still replays.\n * Bundled clients before #45143 offered 2026-09-13 through 2026-09-30 and\n * stamped every queued statement with 2026-09-13. The durable statement grammar\n * (protocol, method, params, meta, seq) is the same on 2026-09-30; only\n * frame-level context differs. So those statements ride the current wire\n * unchanged, while the network offer stays native 2026-09-30 only.\n */\nexport const STORED_STATEMENT_WIRE_FLOOR = \"2026-09-13\";\n\n/** A stored command the current wire replays as-is: re-stamp, don't park. */\nconst replayableOnCurrentWire = (\n protocol: string,\n command: StatewireClient.SessionCommand,\n current: ProducedRange\n): boolean =>\n command.produced !== undefined &&\n inRange(command.produced.wire.version, {\n version: current.wire.version,\n minVersion: STORED_STATEMENT_WIRE_FLOOR,\n }) &&\n storedCommandCompatible(\n protocol,\n { ...command, produced: { ...command.produced, wire: current.wire } },\n current\n );\n\n/**\n * statewire's `migrate` for a record whose queued commands were produced by\n * an earlier build. A command whose statement the current wire still replays\n * ({@link STORED_STATEMENT_WIRE_FLOOR}: an approval's `run/input` saved by a\n * previous bundled client, say) stays queued, re-stamped with the current\n * range, so it is delivered with its original seq. Every other incompatible\n * command leaves its lane's queue and is\n * retained as a `lost`/`session-lost` failed send re-stamped with the current\n * range. Client identity, lane clocks, compatible commands and existing failed\n * history are untouched, so the mount proceeds and the send-recovery sweep\n * (or the user, via the failed-send UI) re-dispatches the parked sends under\n * the negotiated format instead of the runtime throwing before it dials.\n *\n * Returns the record itself when nothing needed migrating, and the count of\n * parked commands otherwise.\n */\nexport function parkIncompatibleSessionCommands(\n record: StatewireClient.SessionRecord,\n current: ProducedRange,\n now: number = Date.now()\n): { record: StatewireClient.SessionRecord; parked: number; restamped: number } {\n let parked = 0;\n let restamped = 0;\n const lanes: Record<string, StatewireClient.SessionLane> = {};\n for (const [protocol, lane] of Object.entries(record.lanes)) {\n const kept: StatewireClient.SessionCommand[] = [];\n const failed: StatewireClient.FailedCommand[] = [];\n let laneRestamped = 0;\n for (const command of lane.commands) {\n if (storedCommandCompatible(protocol, command, current)) {\n kept.push(command);\n continue;\n }\n if (replayableOnCurrentWire(protocol, command, current)) {\n kept.push({ ...command, produced: current });\n laneRestamped += 1;\n continue;\n }\n failed.push({\n protocol,\n produced: current,\n command: command.method,\n params: command.params,\n ...(command.meta !== undefined && { meta: command.meta }),\n failure: { fate: \"lost\", cause: \"session-lost\" },\n ts: now,\n seq: command.seq,\n });\n }\n parked += failed.length;\n restamped += laneRestamped;\n lanes[protocol] =\n failed.length === 0 && laneRestamped === 0\n ? lane\n : {\n ...lane,\n commands: kept,\n ...((failed.length > 0 || lane.failed !== undefined) && {\n failed: [...(lane.failed ?? []), ...failed],\n }),\n };\n }\n return parked === 0 && restamped === 0\n ? { record, parked, restamped }\n : { record: { ...record, lanes }, parked, restamped };\n}\n\n/**\n * Whether `error` is the browser refusing a write for lack of room, under\n * every name the engines use — `QuotaExceededError` (Chromium, WebKit, current\n * Firefox), `NS_ERROR_DOM_QUOTA_REACHED` (older Firefox), the legacy\n * `DOMException` codes 22 (WebKit) and 1014 (Firefox) — or a plain error whose\n * message carries one of those (storage proxies and WebViews rewrap the\n * exception). Olympus's `isStorageQuotaError` recognises the same set; the two\n * stay in step.\n */\nexport function isStorageQuotaError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false;\n const { name, code, message } = error as {\n name?: unknown;\n code?: unknown;\n message?: unknown;\n };\n return (\n name === \"QuotaExceededError\" ||\n name === \"NS_ERROR_DOM_QUOTA_REACHED\" ||\n code === 22 ||\n code === 1014 ||\n (typeof message === \"string\" &&\n /exceeded the quota|quotaexceedederror|ns_error_dom_quota_reached/i.test(\n message\n ))\n );\n}\n\n/** The one quota shape statewire's retention sweep recognises. */\nfunction asStatewireQuotaError(error: unknown): Error {\n if (error instanceof Error && error.name === \"QuotaExceededError\")\n return error;\n const normalized = new Error(\n error instanceof Error ? error.message : \"storage quota exceeded\"\n );\n normalized.name = \"QuotaExceededError\";\n return normalized;\n}\n\n/**\n * Why `raw` is a stored record this build cannot read, or `undefined` when it\n * may be one. Mirrors the two decode failures statewire raises for a record it\n * cannot read — invalid JSON, and a `statewireStorageVersion` newer than the\n * ones this build's statewire decodes (a tab left open across a\n * statewire upgrade, reading the record a newer tab keeps) — because statewire\n * throws those out of the resource at mount instead of treating the record as\n * absent. A structurally invalid record of the right version still fails\n * inside statewire.\n */\nfunction unreadableRecord(raw: string): Error | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n return error instanceof Error\n ? error\n : new Error(\"stored session record is not JSON\");\n }\n if (typeof parsed !== \"object\" || parsed === null) {\n return new Error(\"stored session record is not an object\");\n }\n const version = (parsed as { statewireStorageVersion?: unknown })\n .statewireStorageVersion;\n if (version !== undefined && !READABLE_STORAGE_VERSIONS.has(version)) {\n return new Error(\n `stored session record uses storage version ${String(version)}`\n );\n }\n return undefined;\n}\n\ntype SyncBackend = {\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n getAllKeys: () => readonly string[];\n withUnused: (key: string, action: () => Promise<void>) => Promise<void>;\n};\n\n/**\n * The browser backend `@assistant-ui/react-statewire`'s `LocalStorageSession`\n * uses, reproduced here because that resource does not take a backend: raw\n * `localStorage`, with retention cleanup fenced by the same Web Locks so a\n * sweep never removes a record another tab is actively sharing.\n */\nfunction browserBackend({\n storage,\n locks,\n}: {\n storage: StorageLike;\n locks: LockManagerLike;\n}): SyncBackend {\n return {\n getItem: (key) => storage.getItem(key),\n setItem: (key, value) => storage.setItem(key, value),\n removeItem: (key) => storage.removeItem(key),\n getAllKeys: () =>\n Array.from({ length: storage.length }, (_, index) =>\n storage.key(index)\n ).filter((key): key is string => key !== null),\n withUnused: async (key, action) => {\n await locks.request(\n SESSION_ACTIVE_PREFIX + key,\n { ifAvailable: true },\n async (active) => {\n if (active === null) return;\n await locks.request(\n SESSION_LOCK_PREFIX + key.slice(SESSION_PREFIX.length),\n { ifAvailable: true },\n async (lock) => {\n if (lock === null) return;\n await action();\n }\n );\n }\n );\n },\n };\n}\n\n/**\n * Wraps a synchronous key-value backend so a failing origin degrades the\n * session to memory-only persistence instead of stopping the connection.\n *\n * statewire's session storage latches the first unrecognised write failure\n * and from then on rejects every send (`stopped/storage-error`, \"session\n * storage failed\" on the connection chip). It only recovers a\n * `QuotaExceededError` by that exact name — sweeping old session records and\n * retrying the write once — and latches again when the retry fails too. Here\n * the first quota failure per key is surfaced under that name so the sweep\n * runs; the retry that follows it and every other storage failure are absorbed\n * and reported through `onDegraded`, so chat keeps working.\n *\n * An absorbed write is kept in an in-memory overlay that `getItem` serves\n * first: statewire re-reads the record through `load()` on every shared-mode\n * transaction, so a stale persisted copy would otherwise win back its old\n * `nextSeq`, `clientId` and command journal. The overlay is per tab — another\n * tab sharing the thread still reads the last persisted copy, which is the\n * memory-only degradation this backend exists to allow. A later successful\n * write clears the overlay entry.\n *\n * A key whose read threw, or whose stored value this build cannot read (see\n * {@link unreadableRecord}), is served as absent and shielded: writes to it\n * stay in the overlay for good, so a fresh lane minted over an unreadable\n * record never overwrites what another tab or a newer build persisted.\n */\nexport function quotaTolerantBackend({\n inner,\n onDegraded,\n}: {\n inner: SyncBackend;\n onDegraded: (degradation: SessionStorageDegradation) => void;\n}): SyncBackend & KeyValueSessionStorage.Backend {\n // Keys whose write already surfaced a quota error to statewire: until a\n // write succeeds again, later failures on the key are absorbed instead of\n // surfaced, or every save would re-run statewire's sweep (which evicts\n // other threads' idle records) and the failure would latch on the retry.\n const quotaSurfaced = new Set<string>();\n // Absorbed writes, served ahead of the backend (see the function docs).\n const overlay = new Map<string, string>();\n // Keys served as absent and never written through (see the function docs).\n const shielded = new Set<string>();\n // statewire re-reads and re-decodes the record on every transaction; the\n // readability check is memoised on the raw string so it costs one string\n // comparison per read, not a second parse.\n const checked = new Map<\n string,\n { raw: string; verdict: Error | undefined }\n >();\n const readable = (key: string, raw: string): Error | undefined => {\n const previous = checked.get(key);\n if (previous !== undefined && previous.raw === raw) return previous.verdict;\n const verdict = unreadableRecord(raw);\n checked.set(key, { raw, verdict });\n return verdict;\n };\n return {\n getItem: (key) => {\n const shadowed = overlay.get(key);\n if (shadowed !== undefined) return shadowed;\n if (shielded.has(key)) return null;\n let raw: string | null;\n try {\n raw = inner.getItem(key);\n } catch (error) {\n shielded.add(key);\n onDegraded({ operation: \"getItem\", key, error });\n return null;\n }\n if (raw === null) return null;\n const unreadable = readable(key, raw);\n if (unreadable === undefined) return raw;\n shielded.add(key);\n onDegraded({ operation: \"record\", key, error: unreadable });\n return null;\n },\n setItem: (key, value) => {\n if (shielded.has(key)) {\n overlay.set(key, value);\n return;\n }\n try {\n inner.setItem(key, value);\n overlay.delete(key);\n quotaSurfaced.delete(key);\n } catch (error) {\n if (isStorageQuotaError(error) && !quotaSurfaced.has(key)) {\n quotaSurfaced.add(key);\n throw asStatewireQuotaError(error);\n }\n overlay.set(key, value);\n onDegraded({ operation: \"setItem\", key, error });\n }\n },\n removeItem: (key) => {\n overlay.delete(key);\n if (shielded.has(key)) return;\n try {\n inner.removeItem(key);\n } catch (error) {\n onDegraded({ operation: \"removeItem\", key, error });\n }\n },\n getAllKeys: () => {\n const keys = new Set<string>(overlay.keys());\n try {\n for (const key of inner.getAllKeys()) keys.add(key);\n } catch (error) {\n onDegraded({ operation: \"getAllKeys\", key: \"\", error });\n }\n return [...keys];\n },\n withUnused: async (key, action) => {\n try {\n await inner.withUnused(key, action);\n } catch (error) {\n onDegraded({ operation: \"withUnused\", key, error });\n }\n },\n };\n}\n\n/** A stored record's save stamp, or `undefined` when it carries none. */\nfunction savedAtOf(raw: string | null): number | undefined {\n if (raw === null) return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return undefined;\n }\n if (typeof parsed !== \"object\" || parsed === null) return undefined;\n const { savedAt, updatedAt } = parsed as {\n savedAt?: unknown;\n updatedAt?: unknown;\n };\n const stamp = savedAt ?? updatedAt;\n return typeof stamp === \"number\" && Number.isFinite(stamp)\n ? stamp\n : undefined;\n}\n\n/**\n * Removes session records last saved more than `maxAgeMs` ago, skipping the\n * keys mounted in this tab and, through `withUnused`, those another tab holds.\n *\n * statewire's own retention sweep only retires records with nothing queued and\n * nothing failed: a record still carrying an unconfirmed or failed send is\n * exempt from both its age and count bounds, so every thread left with one\n * kept its key forever. Past the TTL those sends are long out of send\n * recovery's auto-retry window, so the record goes the same way an empty one\n * does.\n */\nexport async function retireExpiredSessionRecords({\n backend,\n mounted,\n maxAgeMs,\n now = Date.now(),\n}: {\n backend: Pick<\n SyncBackend,\n \"getItem\" | \"removeItem\" | \"getAllKeys\" | \"withUnused\"\n >;\n mounted: ReadonlyMap<string, number>;\n maxAgeMs: number;\n now?: number;\n}): Promise<void> {\n for (const key of backend.getAllKeys()) {\n if (!key.startsWith(SESSION_PREFIX) || mounted.has(key)) continue;\n const savedAt = savedAtOf(backend.getItem(key));\n if (savedAt === undefined || now - savedAt <= maxAgeMs) continue;\n await backend.withUnused(key, async () => {\n if (mounted.has(key) || savedAtOf(backend.getItem(key)) !== savedAt)\n return;\n backend.removeItem(key);\n });\n }\n}\n\ntype DegradationListener = (degradation: SessionStorageDegradation) => void;\n\ntype SharedBackend = {\n backend: SyncBackend & KeyValueSessionStorage.Backend;\n listeners: Set<DegradationListener>;\n /** Storage keys of the sessions mounted in this tab, with mount counts. */\n mounted: Map<string, number>;\n};\n\n/**\n * One backend per storage object — per origin, in a browser — shared by every\n * session mounted in the tab, exactly as the upstream resource's module-level\n * backend is. statewire keys its in-tab \"active\" bookkeeping by backend\n * identity, so a mount's retention sweep only skips the records of other\n * mounts on the *same* backend; and the absorbed-write overlay has to outlive\n * a remount of the same thread (a thread switch and back) or the remount would\n * read the stale persisted copy. Degradations fan out to every mounted\n * session's reporter.\n */\nconst sharedBackends = new WeakMap<StorageLike, SharedBackend>();\n\nfunction sharedBackend({\n storage,\n locks,\n}: {\n storage: StorageLike;\n locks: LockManagerLike;\n}): SharedBackend {\n let shared = sharedBackends.get(storage);\n if (shared === undefined) {\n const listeners = new Set<DegradationListener>();\n shared = {\n listeners,\n mounted: new Map(),\n backend: quotaTolerantBackend({\n inner: browserBackend({ storage, locks }),\n onDegraded: (degradation) => {\n for (const listener of listeners) listener(degradation);\n },\n }),\n };\n sharedBackends.set(storage, shared);\n }\n return shared;\n}\n\n/**\n * Athena's browser session store: `@assistant-ui/react-statewire`'s\n * `LocalStorageSession` contract (per-thread key under the shared prefix,\n * cross-tab Web Lock, storage-event subscription, retention) on top of\n * {@link quotaTolerantBackend}, with Athena's protocol lane and retention\n * policy.\n */\nconst useQuotaSafeLocalStorageSession = ({\n threadId,\n key = (id) => id,\n ttl = 7 * DAY_MS,\n max = 50,\n onStorageDegraded,\n}: QuotaSafeLocalStorageSession.Options): StatewireClient.SessionStorage => {\n const storage = browserGlobals.localStorage;\n const locks = browserGlobals.navigator?.locks;\n if (!storage)\n throw new Error(\n \"statewire: QuotaSafeLocalStorageSession requires localStorage\"\n );\n if (!locks)\n throw new Error(\n \"statewire: QuotaSafeLocalStorageSession requires the Web Locks API (navigator.locks)\"\n );\n const sessionKey = key(threadId);\n const storageKey = SESSION_PREFIX + sessionKey;\n const lockName = SESSION_LOCK_PREFIX + sessionKey;\n\n const latestOnDegraded = useRef(onStorageDegraded);\n latestOnDegraded.current = onStorageDegraded;\n const reportDegradation = useMemo(() => {\n const reported = new Set<string>();\n return (degradation: SessionStorageDegradation) => {\n const handler = latestOnDegraded.current;\n if (handler) {\n try {\n handler(degradation);\n } catch {\n // Reporting runs inside the session's recovery path and must never\n // become the failure it is reporting.\n }\n return;\n }\n const dedupeKey = `${degradation.operation}:${degradation.key}`;\n if (reported.has(dedupeKey)) return;\n reported.add(dedupeKey);\n console.warn(\n `[statewire] session storage degraded to memory only (${degradation.operation} ${degradation.key})`,\n degradation.error\n );\n };\n }, []);\n\n const shared = sharedBackend({ storage, locks });\n // Registered during render as well as in the effect: the read statewire\n // makes while mounting below happens before any effect runs, and tap may\n // clean an effect up and re-run it within one commit.\n shared.listeners.add(reportDegradation);\n useEffect(() => {\n shared.listeners.add(reportDegradation);\n return () => {\n shared.listeners.delete(reportDegradation);\n };\n }, [shared, reportDegradation]);\n\n useEffect(() => {\n const { mounted } = shared;\n mounted.set(storageKey, (mounted.get(storageKey) ?? 0) + 1);\n retireExpiredSessionRecords({\n backend: shared.backend,\n mounted,\n maxAgeMs: ttl,\n }).catch((error: unknown) =>\n reportDegradation({ operation: \"withUnused\", key: storageKey, error })\n );\n return () => {\n const count = (mounted.get(storageKey) ?? 1) - 1;\n if (count === 0) mounted.delete(storageKey);\n else mounted.set(storageKey, count);\n };\n }, [shared, storageKey, ttl, reportDegradation]);\n\n // Hold the record's shared \"active\" lock while mounted so another tab's\n // retention sweep skips it (the same fence the upstream resource holds).\n useEffect(() => {\n let release: (() => void) | undefined;\n let disposed = false;\n Promise.resolve(\n locks.request(\n SESSION_ACTIVE_PREFIX + storageKey,\n { mode: \"shared\" },\n () => {\n if (disposed) return;\n return new Promise<void>((resolve) => {\n release = resolve;\n });\n }\n )\n ).catch((error: unknown) =>\n reportDegradation({ operation: \"lock\", key: storageKey, error })\n );\n return () => {\n disposed = true;\n release?.();\n };\n }, [locks, storageKey, reportDegradation]);\n\n // The storage resource includes migrate in its identity. A fresh callback\n // on every render replaces the store and prevents hydration from settling.\n const migrate = useCallback<\n NonNullable<StatewireClient.SessionStorage[\"migrate\"]>\n >(\n (record, current) => {\n const migrated = parkIncompatibleSessionCommands(record, current);\n if (migrated.parked === 0) return migrated.record;\n reportDegradation({\n operation: \"migrate\",\n key: storageKey,\n error: new Error(\n `${migrated.parked} queued statewire command(s) predate the current protocol range; parked as failed sends`\n ),\n });\n return migrated.record;\n },\n [reportDegradation, storageKey]\n );\n\n const sessionStorage = useResource(\n KeyValueSessionStorage({\n backend: shared.backend,\n key: sessionKey,\n namespace: SESSION_PREFIX,\n protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,\n migrate,\n retention: { maxAgeMs: ttl, maxEntries: max },\n // A failure statewire raises itself (a structurally invalid stored\n // record) still stops the session; it is at least reported the same way.\n onError: (error) =>\n reportDegradation({ operation: \"session\", key: storageKey, error }),\n })\n );\n\n return useMemo(\n () => ({\n ...sessionStorage,\n lock: async <T>(fn: () => T | Promise<T>): Promise<T> => {\n let granted = false;\n try {\n return await locks.request(lockName, async () => {\n granted = true;\n return fn();\n });\n } catch (error) {\n if (granted) throw error;\n // The lock manager refused the request itself (a detached or\n // back/forward-cached document, a lockdown-mode origin): the\n // transaction runs unfenced rather than stopping the session.\n reportDegradation({ operation: \"lock\", key: storageKey, error });\n return fn();\n }\n },\n subscribe: (listener: () => void) => {\n const onStorage = (event: StorageEventLike) => {\n if (event.key === storageKey) listener();\n };\n browserGlobals.addEventListener?.(\"storage\", onStorage);\n return () => browserGlobals.removeEventListener?.(\"storage\", onStorage);\n },\n }),\n [sessionStorage, locks, storageKey, lockName, reportDegradation]\n );\n};\n\n/** Athena's browser session keys and retention policy. */\nexport const QuotaSafeLocalStorageSession = resource(\n useQuotaSafeLocalStorageSession\n);\n\nexport namespace QuotaSafeLocalStorageSession {\n export type Options = {\n threadId: string;\n key?: (threadId: string) => string;\n ttl?: number;\n max?: number;\n /**\n * Called when a storage operation failed and the session carried on in\n * memory. Defaults to one `console.warn` per operation and key.\n */\n onStorageDegraded?: (degradation: SessionStorageDegradation) => void;\n };\n}\n"],"names":["storage","failed","useRef","useMemo","useEffect","useC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C,sBAAU;AACV,mBAAO,GAAA;AAAA,UACT,CAAC;AAAA,QACH,SAAS,OAAO;AACd,cAAI,QAAS,OAAM;AAInB,4BAAkB,EAAE,WAAW,QAAQ,KAAK,YAAY,OAAO;AAC/D,iBAAO,GAAA;AAAA,QACT;AAAA,MACF;AAAA,MACA,WAAW,CAAC,aAAyB;;AACnC,cAAM,YAAY,CAAC,UAA4B;AAC7C,cAAI,MAAM,QAAQ,WAAY,UAAA;AAAA,QAChC;AACA,SAAAM,MAAA,eAAe,qBAAf,gBAAAA,IAAA,qBAAkC,WAAW;AAC7C,eAAO;;AAAM,kBAAAA,MAAA,eAAe,wBAAf,gBAAAA,IAAA,qBAAqC,WAAW;AAAA;AAAA,MAC/D;AAAA,IAAA;AAAA,IAEF,CAAC,gBAAgB,OAAO,YAAY,UAAU,iBAAiB;AAAA,EAAA;AAEnE;AAGO,MAAM,+BAA+BC,IAAAA;AAAAA,EAC1C;AACF;;;;;;;;;"}
1
+ {"version":3,"file":"quota-safe-local-storage-session.cjs","sources":["../../../../agent-runtime/src/quota-safe-local-storage-session.ts"],"sourcesContent":["import { resource, useResource } from \"@assistant-ui/tap\";\nimport type { StatewireClient, StatewireProtocol } from \"statewire\";\nimport { KeyValueSessionStorage } from \"statewire/storage\";\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport {\n type DeepAgentSessionLaneScope,\n isSameSessionLaneScope,\n} from \"./session-lane-scope\";\nimport { DEEP_AGENT_STATEWIRE_PROTOCOL } from \"./statewire-transport\";\n\nconst SESSION_PREFIX = \"aui:statewire-session:\";\nconst SESSION_LOCK_PREFIX = \"aui:statewire-session-lock:\";\nconst SESSION_ACTIVE_PREFIX = \"aui:statewire-session-active:\";\nconst DAY_MS = 24 * 60 * 60 * 1000;\n/** The stored-record formats the statewire this build ships reads (it writes 3). */\nconst READABLE_STORAGE_VERSIONS: ReadonlySet<unknown> = new Set([1, 2, 3]);\n\n/** Structural view of the browser storage global — this package compiles\n * without the DOM lib (React Native honesty; see `globals.d.ts`). */\ntype StorageLike = {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n key(index: number): string | null;\n readonly length: number;\n};\n\ntype LockGrant = object | null;\n\n/** The Web Locks API surface the session uses (`navigator.locks`). */\ntype LockManagerLike = {\n request<T>(\n name: string,\n callback: (lock: LockGrant) => T | Promise<T>\n ): Promise<T>;\n request<T>(\n name: string,\n options: { mode?: \"shared\" | \"exclusive\"; ifAvailable?: boolean },\n callback: (lock: LockGrant) => T | Promise<T>\n ): Promise<T>;\n};\n\ntype StorageEventLike = { key: string | null };\n\ntype BrowserGlobals = {\n localStorage?: StorageLike;\n navigator?: { locks?: LockManagerLike };\n addEventListener?: (\n type: \"storage\",\n listener: (event: StorageEventLike) => void\n ) => void;\n removeEventListener?: (\n type: \"storage\",\n listener: (event: StorageEventLike) => void\n ) => void;\n};\n\nconst browserGlobals = globalThis as BrowserGlobals;\n\n/** A persisted session record: per-lane failed entries (a pre-lane record carried them at the root). */\ntype SessionRecordLike = {\n failed?: unknown;\n lanes?: Record<string, { failed?: unknown } | null | undefined> | null;\n};\n\nexport function readPersistedFailedSendStamps(\n sessionKey: string\n): ReadonlyMap<string, number> | null {\n const storage = browserGlobals.localStorage;\n if (!storage) return null;\n let record: SessionRecordLike | null;\n try {\n const raw = storage.getItem(SESSION_PREFIX + sessionKey);\n record =\n raw === null ? null : (JSON.parse(raw) as SessionRecordLike | null);\n } catch {\n return null;\n }\n return readFailedSendStampsFromRecord(record);\n}\n\n/**\n * Send stamps (message id → epoch ms of the original send) off an already\n * loaded session record's failed lane — the storage-agnostic half of\n * {@link readPersistedFailedSendStamps}, for hosts whose session store is not\n * localStorage (the React Native AsyncStorage-backed store reads its record\n * synchronously through `SessionStorage.load()`).\n *\n * Returns `null` for no record (every failed entry then counts as fresh) and\n * an empty map for a record without failures.\n */\nexport function readFailedSendStampsFromRecord(\n record: SessionRecordLike | null | undefined\n): ReadonlyMap<string, number> | null {\n if (!record || typeof record !== \"object\") return null;\n const stamps = new Map<string, number>();\n const lanes =\n record.lanes && typeof record.lanes === \"object\" ? record.lanes : {};\n const failed = [\n ...(Array.isArray(record.failed) ? record.failed : []),\n ...Object.values(lanes).flatMap((lane) =>\n Array.isArray(lane?.failed) ? lane.failed : []\n ),\n ];\n for (const entry of failed) {\n const failed = entry as {\n ts?: unknown;\n params?: readonly { message?: { id?: unknown } }[];\n } | null;\n const messageId = failed?.params?.[0]?.message?.id;\n if (typeof messageId === \"string\" && typeof failed?.ts === \"number\") {\n stamps.set(messageId, failed.ts);\n }\n }\n return stamps;\n}\n\n/** A storage operation the session survived by degrading instead of failing. */\nexport type SessionStorageDegradation = {\n operation:\n | \"getItem\"\n | \"setItem\"\n | \"removeItem\"\n | \"getAllKeys\"\n | \"withUnused\"\n /** The lock manager refused the transaction fence; it ran unfenced. */\n | \"lock\"\n /**\n * The stored record is one this build cannot read (not JSON, or a newer\n * storage version): served as absent, and the key is shielded from being\n * overwritten so the record survives this tab.\n */\n | \"record\"\n /** statewire's own storage failure (a structurally invalid stored record). */\n | \"session\"\n /**\n * Queued commands persisted by an earlier statewire build no longer fit\n * the current wire/protocol range: parked in the lane's failed list (the\n * send-recovery sweep re-dispatches them) instead of blocking the mount.\n */\n | \"migrate\";\n key: string;\n error: unknown;\n};\n\ntype ProducedRange = NonNullable<StatewireClient.SessionCommand[\"produced\"]>;\n\nconst inRange = (value: string, range: StatewireProtocol.Range) =>\n value >= (range.minVersion ?? range.version) && value <= range.version;\n\n/** Mirrors statewire's own stored-command compatibility check. */\nconst storedCommandCompatible = (\n protocol: string,\n command: StatewireClient.SessionCommand,\n current: ProducedRange\n): boolean => {\n if (\n !command.produced ||\n !inRange(command.produced.wire.version, current.wire)\n )\n return false;\n if (current.protocols === \"*\") return true;\n if (command.produced.protocols === \"*\") return false;\n const produced = command.produced.protocols.find((p) => p.name === protocol);\n const offer = current.protocols.find((p) => p.name === protocol);\n return (\n produced !== undefined &&\n offer !== undefined &&\n inRange(produced.version, offer)\n );\n};\n\n/**\n * The oldest wire whose stored statements the current client still replays.\n * Bundled clients before #45143 offered 2026-09-13 through 2026-09-30 and\n * stamped every queued statement with 2026-09-13. The durable statement grammar\n * (protocol, method, params, meta, seq) is the same on 2026-09-30; only\n * frame-level context differs. So those statements ride the current wire\n * unchanged, while the network offer stays native 2026-09-30 only.\n */\nexport const STORED_STATEMENT_WIRE_FLOOR = \"2026-09-13\";\n\n/** A stored command the current wire replays as-is: re-stamp, don't park. */\nconst replayableOnCurrentWire = (\n protocol: string,\n command: StatewireClient.SessionCommand,\n current: ProducedRange\n): boolean =>\n command.produced !== undefined &&\n inRange(command.produced.wire.version, {\n version: current.wire.version,\n minVersion: STORED_STATEMENT_WIRE_FLOOR,\n }) &&\n storedCommandCompatible(\n protocol,\n { ...command, produced: { ...command.produced, wire: current.wire } },\n current\n );\n\n/**\n * statewire's `migrate` for a record whose queued commands were produced by\n * an earlier build. A command whose statement the current wire still replays\n * ({@link STORED_STATEMENT_WIRE_FLOOR}: an approval's `run/input` saved by a\n * previous bundled client, say) stays queued, re-stamped with the current\n * range, so it is delivered with its original seq. Every other incompatible\n * command leaves its lane's queue and is\n * retained as a `lost`/`session-lost` failed send re-stamped with the current\n * range. Client identity, lane clocks, compatible commands and existing failed\n * history are untouched, so the mount proceeds and the send-recovery sweep\n * (or the user, via the failed-send UI) re-dispatches the parked sends under\n * the negotiated format instead of the runtime throwing before it dials.\n *\n * Returns the record itself when nothing needed migrating, and the count of\n * parked commands otherwise.\n */\nexport function parkIncompatibleSessionCommands(\n record: StatewireClient.SessionRecord,\n current: ProducedRange,\n now: number = Date.now()\n): { record: StatewireClient.SessionRecord; parked: number; restamped: number } {\n let parked = 0;\n let restamped = 0;\n const lanes: Record<string, StatewireClient.SessionLane> = {};\n for (const [protocol, lane] of Object.entries(record.lanes)) {\n const kept: StatewireClient.SessionCommand[] = [];\n const failed: StatewireClient.FailedCommand[] = [];\n let laneRestamped = 0;\n for (const command of lane.commands) {\n if (storedCommandCompatible(protocol, command, current)) {\n kept.push(command);\n continue;\n }\n if (replayableOnCurrentWire(protocol, command, current)) {\n kept.push({ ...command, produced: current });\n laneRestamped += 1;\n continue;\n }\n failed.push({\n protocol,\n produced: current,\n command: command.method,\n params: command.params,\n ...(command.meta !== undefined && { meta: command.meta }),\n failure: { fate: \"lost\", cause: \"session-lost\" },\n ts: now,\n seq: command.seq,\n });\n }\n parked += failed.length;\n restamped += laneRestamped;\n lanes[protocol] =\n failed.length === 0 && laneRestamped === 0\n ? lane\n : {\n ...lane,\n commands: kept,\n ...((failed.length > 0 || lane.failed !== undefined) && {\n failed: [...(lane.failed ?? []), ...failed],\n }),\n };\n }\n return parked === 0 && restamped === 0\n ? { record, parked, restamped }\n : { record: { ...record, lanes }, parked, restamped };\n}\n\n/**\n * Whether `error` is the browser refusing a write for lack of room, under\n * every name the engines use — `QuotaExceededError` (Chromium, WebKit, current\n * Firefox), `NS_ERROR_DOM_QUOTA_REACHED` (older Firefox), the legacy\n * `DOMException` codes 22 (WebKit) and 1014 (Firefox) — or a plain error whose\n * message carries one of those (storage proxies and WebViews rewrap the\n * exception). Olympus's `isStorageQuotaError` recognises the same set; the two\n * stay in step.\n */\nexport function isStorageQuotaError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false;\n const { name, code, message } = error as {\n name?: unknown;\n code?: unknown;\n message?: unknown;\n };\n return (\n name === \"QuotaExceededError\" ||\n name === \"NS_ERROR_DOM_QUOTA_REACHED\" ||\n code === 22 ||\n code === 1014 ||\n (typeof message === \"string\" &&\n /exceeded the quota|quotaexceedederror|ns_error_dom_quota_reached/i.test(\n message\n ))\n );\n}\n\n/** The one quota shape statewire's retention sweep recognises. */\nfunction asStatewireQuotaError(error: unknown): Error {\n if (error instanceof Error && error.name === \"QuotaExceededError\")\n return error;\n const normalized = new Error(\n error instanceof Error ? error.message : \"storage quota exceeded\"\n );\n normalized.name = \"QuotaExceededError\";\n return normalized;\n}\n\n/**\n * Why `raw` is a stored record this build cannot read, or `undefined` when it\n * may be one. Mirrors the two decode failures statewire raises for a record it\n * cannot read — invalid JSON, and a `statewireStorageVersion` newer than the\n * ones this build's statewire decodes (a tab left open across a\n * statewire upgrade, reading the record a newer tab keeps) — because statewire\n * throws those out of the resource at mount instead of treating the record as\n * absent. A structurally invalid record of the right version still fails\n * inside statewire.\n */\nfunction unreadableRecord(raw: string): Error | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n return error instanceof Error\n ? error\n : new Error(\"stored session record is not JSON\");\n }\n if (typeof parsed !== \"object\" || parsed === null) {\n return new Error(\"stored session record is not an object\");\n }\n const version = (parsed as { statewireStorageVersion?: unknown })\n .statewireStorageVersion;\n if (version !== undefined && !READABLE_STORAGE_VERSIONS.has(version)) {\n return new Error(\n `stored session record uses storage version ${String(version)}`\n );\n }\n return undefined;\n}\n\ntype SyncBackend = {\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n getAllKeys: () => readonly string[];\n withUnused: (key: string, action: () => Promise<void>) => Promise<void>;\n};\n\n/**\n * The browser backend `@assistant-ui/react-statewire`'s `LocalStorageSession`\n * uses, reproduced here because that resource does not take a backend: raw\n * `localStorage`, with retention cleanup fenced by the same Web Locks so a\n * sweep never removes a record another tab is actively sharing.\n */\nfunction browserBackend({\n storage,\n locks,\n}: {\n storage: StorageLike;\n locks: LockManagerLike;\n}): SyncBackend {\n return {\n getItem: (key) => storage.getItem(key),\n setItem: (key, value) => storage.setItem(key, value),\n removeItem: (key) => storage.removeItem(key),\n getAllKeys: () =>\n Array.from({ length: storage.length }, (_, index) =>\n storage.key(index)\n ).filter((key): key is string => key !== null),\n withUnused: async (key, action) => {\n await locks.request(\n SESSION_ACTIVE_PREFIX + key,\n { ifAvailable: true },\n async (active) => {\n if (active === null) return;\n await locks.request(\n SESSION_LOCK_PREFIX + key.slice(SESSION_PREFIX.length),\n { ifAvailable: true },\n async (lock) => {\n if (lock === null) return;\n await action();\n }\n );\n }\n );\n },\n };\n}\n\n/**\n * Wraps a synchronous key-value backend so a failing origin degrades the\n * session to memory-only persistence instead of stopping the connection.\n *\n * statewire's session storage latches the first unrecognised write failure\n * and from then on rejects every send (`stopped/storage-error`, \"session\n * storage failed\" on the connection chip). It only recovers a\n * `QuotaExceededError` by that exact name — sweeping old session records and\n * retrying the write once — and latches again when the retry fails too. Here\n * the first quota failure per key is surfaced under that name so the sweep\n * runs; the retry that follows it and every other storage failure are absorbed\n * and reported through `onDegraded`, so chat keeps working.\n *\n * An absorbed write is kept in an in-memory overlay that `getItem` serves\n * first: statewire re-reads the record through `load()` on every shared-mode\n * transaction, so a stale persisted copy would otherwise win back its old\n * `nextSeq`, `clientId` and command journal. The overlay is per tab — another\n * tab sharing the thread still reads the last persisted copy, which is the\n * memory-only degradation this backend exists to allow. A later successful\n * write clears the overlay entry.\n *\n * A key whose read threw, or whose stored value this build cannot read (see\n * {@link unreadableRecord}), is served as absent and shielded: writes to it\n * stay in the overlay for good, so a fresh lane minted over an unreadable\n * record never overwrites what another tab or a newer build persisted.\n */\nexport function quotaTolerantBackend({\n inner,\n onDegraded,\n}: {\n inner: SyncBackend;\n onDegraded: (degradation: SessionStorageDegradation) => void;\n}): SyncBackend & KeyValueSessionStorage.Backend {\n // Keys whose write already surfaced a quota error to statewire: until a\n // write succeeds again, later failures on the key are absorbed instead of\n // surfaced, or every save would re-run statewire's sweep (which evicts\n // other threads' idle records) and the failure would latch on the retry.\n const quotaSurfaced = new Set<string>();\n // Absorbed writes, served ahead of the backend (see the function docs).\n const overlay = new Map<string, string>();\n // Keys served as absent and never written through (see the function docs).\n const shielded = new Set<string>();\n // statewire re-reads and re-decodes the record on every transaction; the\n // readability check is memoised on the raw string so it costs one string\n // comparison per read, not a second parse.\n const checked = new Map<\n string,\n { raw: string; verdict: Error | undefined }\n >();\n const readable = (key: string, raw: string): Error | undefined => {\n const previous = checked.get(key);\n if (previous !== undefined && previous.raw === raw) return previous.verdict;\n const verdict = unreadableRecord(raw);\n checked.set(key, { raw, verdict });\n return verdict;\n };\n return {\n getItem: (key) => {\n const shadowed = overlay.get(key);\n if (shadowed !== undefined) return shadowed;\n if (shielded.has(key)) return null;\n let raw: string | null;\n try {\n raw = inner.getItem(key);\n } catch (error) {\n shielded.add(key);\n onDegraded({ operation: \"getItem\", key, error });\n return null;\n }\n if (raw === null) return null;\n const unreadable = readable(key, raw);\n if (unreadable === undefined) return raw;\n shielded.add(key);\n onDegraded({ operation: \"record\", key, error: unreadable });\n return null;\n },\n setItem: (key, value) => {\n if (shielded.has(key)) {\n overlay.set(key, value);\n return;\n }\n try {\n inner.setItem(key, value);\n overlay.delete(key);\n quotaSurfaced.delete(key);\n } catch (error) {\n if (isStorageQuotaError(error) && !quotaSurfaced.has(key)) {\n quotaSurfaced.add(key);\n throw asStatewireQuotaError(error);\n }\n overlay.set(key, value);\n onDegraded({ operation: \"setItem\", key, error });\n }\n },\n removeItem: (key) => {\n overlay.delete(key);\n if (shielded.has(key)) return;\n try {\n inner.removeItem(key);\n } catch (error) {\n onDegraded({ operation: \"removeItem\", key, error });\n }\n },\n getAllKeys: () => {\n const keys = new Set<string>(overlay.keys());\n try {\n for (const key of inner.getAllKeys()) keys.add(key);\n } catch (error) {\n onDegraded({ operation: \"getAllKeys\", key: \"\", error });\n }\n return [...keys];\n },\n withUnused: async (key, action) => {\n try {\n await inner.withUnused(key, action);\n } catch (error) {\n onDegraded({ operation: \"withUnused\", key, error });\n }\n },\n };\n}\n\n/** A stored record's save stamp, or `undefined` when it carries none. */\nfunction savedAtOf(raw: string | null): number | undefined {\n if (raw === null) return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return undefined;\n }\n if (typeof parsed !== \"object\" || parsed === null) return undefined;\n const { savedAt, updatedAt } = parsed as {\n savedAt?: unknown;\n updatedAt?: unknown;\n };\n const stamp = savedAt ?? updatedAt;\n return typeof stamp === \"number\" && Number.isFinite(stamp)\n ? stamp\n : undefined;\n}\n\n/**\n * Removes session records last saved more than `maxAgeMs` ago, skipping the\n * keys mounted in this tab and, through `withUnused`, those another tab holds.\n *\n * statewire's own retention sweep only retires records with nothing queued and\n * nothing failed: a record still carrying an unconfirmed or failed send is\n * exempt from both its age and count bounds, so every thread left with one\n * kept its key forever. Past the TTL those sends are long out of send\n * recovery's auto-retry window, so the record goes the same way an empty one\n * does.\n */\nexport async function retireExpiredSessionRecords({\n backend,\n mounted,\n maxAgeMs,\n now = Date.now(),\n}: {\n backend: Pick<\n SyncBackend,\n \"getItem\" | \"removeItem\" | \"getAllKeys\" | \"withUnused\"\n >;\n mounted: ReadonlyMap<string, number>;\n maxAgeMs: number;\n now?: number;\n}): Promise<void> {\n for (const key of backend.getAllKeys()) {\n if (!key.startsWith(SESSION_PREFIX) || mounted.has(key)) continue;\n const savedAt = savedAtOf(backend.getItem(key));\n if (savedAt === undefined || now - savedAt <= maxAgeMs) continue;\n await backend.withUnused(key, async () => {\n if (mounted.has(key) || savedAtOf(backend.getItem(key)) !== savedAt)\n return;\n backend.removeItem(key);\n });\n }\n}\n\ntype DegradationListener = (degradation: SessionStorageDegradation) => void;\n\ntype SharedBackend = {\n backend: SyncBackend & KeyValueSessionStorage.Backend;\n listeners: Set<DegradationListener>;\n /** Storage keys of the sessions mounted in this tab, with mount counts. */\n mounted: Map<string, number>;\n};\n\n/**\n * One backend per storage object — per origin, in a browser — shared by every\n * session mounted in the tab, exactly as the upstream resource's module-level\n * backend is. statewire keys its in-tab \"active\" bookkeeping by backend\n * identity, so a mount's retention sweep only skips the records of other\n * mounts on the *same* backend; and the absorbed-write overlay has to outlive\n * a remount of the same thread (a thread switch and back) or the remount would\n * read the stale persisted copy. Degradations fan out to every mounted\n * session's reporter.\n */\nconst sharedBackends = new WeakMap<StorageLike, SharedBackend>();\n\nfunction sharedBackend({\n storage,\n locks,\n}: {\n storage: StorageLike;\n locks: LockManagerLike;\n}): SharedBackend {\n let shared = sharedBackends.get(storage);\n if (shared === undefined) {\n const listeners = new Set<DegradationListener>();\n shared = {\n listeners,\n mounted: new Map(),\n backend: quotaTolerantBackend({\n inner: browserBackend({ storage, locks }),\n onDegraded: (degradation) => {\n for (const listener of listeners) listener(degradation);\n },\n }),\n };\n sharedBackends.set(storage, shared);\n }\n return shared;\n}\n\n/**\n * Athena's browser session store: `@assistant-ui/react-statewire`'s\n * `LocalStorageSession` contract (per-thread key under the shared prefix,\n * cross-tab Web Lock, storage-event subscription, retention) on top of\n * {@link quotaTolerantBackend}, with Athena's protocol lane and retention\n * policy.\n */\nconst useQuotaSafeLocalStorageSession = ({\n threadId,\n key = (id) => id,\n ttl = 7 * DAY_MS,\n max = 50,\n onStorageDegraded,\n}: QuotaSafeLocalStorageSession.Options): StatewireClient.SessionStorage => {\n const storage = browserGlobals.localStorage;\n const locks = browserGlobals.navigator?.locks;\n if (!storage)\n throw new Error(\n \"statewire: QuotaSafeLocalStorageSession requires localStorage\"\n );\n if (!locks)\n throw new Error(\n \"statewire: QuotaSafeLocalStorageSession requires the Web Locks API (navigator.locks)\"\n );\n const sessionKey = key(threadId);\n const storageKey = SESSION_PREFIX + sessionKey;\n const lockName = SESSION_LOCK_PREFIX + sessionKey;\n\n // One mounted store serves one lane scope (one principal, one backend) for\n // its whole life: the upstream `LocalStorageSession` contract, whose\n // principal guard this is. The statewire session over the store keeps the\n // client id, lane clocks and journal it loaded, so a store moved to another\n // principal's lane would carry them there and send the previous principal's\n // undelivered commands under the next one's credential. A thread switch keeps\n // the scope and re-targets the store; a change of scope refuses, and the host\n // remounts the account's thread (`useDeepAgentRuntime` does). The previous\n // principal's record is left as it is.\n const mountedScope = useRef<DeepAgentSessionLaneScope>({\n threadId,\n laneKey: sessionKey,\n });\n if (!isSameSessionLaneScope({ scope: mountedScope.current, key })) {\n throw new Error(\n \"statewire: principal changed; remount the account's thread/session\"\n );\n }\n\n const latestOnDegraded = useRef(onStorageDegraded);\n latestOnDegraded.current = onStorageDegraded;\n const reportDegradation = useMemo(() => {\n const reported = new Set<string>();\n return (degradation: SessionStorageDegradation) => {\n const handler = latestOnDegraded.current;\n if (handler) {\n try {\n handler(degradation);\n } catch {\n // Reporting runs inside the session's recovery path and must never\n // become the failure it is reporting.\n }\n return;\n }\n const dedupeKey = `${degradation.operation}:${degradation.key}`;\n if (reported.has(dedupeKey)) return;\n reported.add(dedupeKey);\n console.warn(\n `[statewire] session storage degraded to memory only (${degradation.operation} ${degradation.key})`,\n degradation.error\n );\n };\n }, []);\n\n const shared = sharedBackend({ storage, locks });\n // Registered during render as well as in the effect: the read statewire\n // makes while mounting below happens before any effect runs, and tap may\n // clean an effect up and re-run it within one commit.\n shared.listeners.add(reportDegradation);\n useEffect(() => {\n shared.listeners.add(reportDegradation);\n return () => {\n shared.listeners.delete(reportDegradation);\n };\n }, [shared, reportDegradation]);\n\n useEffect(() => {\n const { mounted } = shared;\n mounted.set(storageKey, (mounted.get(storageKey) ?? 0) + 1);\n retireExpiredSessionRecords({\n backend: shared.backend,\n mounted,\n maxAgeMs: ttl,\n }).catch((error: unknown) =>\n reportDegradation({ operation: \"withUnused\", key: storageKey, error })\n );\n return () => {\n const count = (mounted.get(storageKey) ?? 1) - 1;\n if (count === 0) mounted.delete(storageKey);\n else mounted.set(storageKey, count);\n };\n }, [shared, storageKey, ttl, reportDegradation]);\n\n // Hold the record's shared \"active\" lock while mounted so another tab's\n // retention sweep skips it (the same fence the upstream resource holds).\n useEffect(() => {\n let release: (() => void) | undefined;\n let disposed = false;\n Promise.resolve(\n locks.request(\n SESSION_ACTIVE_PREFIX + storageKey,\n { mode: \"shared\" },\n () => {\n if (disposed) return;\n return new Promise<void>((resolve) => {\n release = resolve;\n });\n }\n )\n ).catch((error: unknown) =>\n reportDegradation({ operation: \"lock\", key: storageKey, error })\n );\n return () => {\n disposed = true;\n release?.();\n };\n }, [locks, storageKey, reportDegradation]);\n\n // The storage resource includes migrate in its identity. A fresh callback\n // on every render replaces the store and prevents hydration from settling.\n const migrate = useCallback<\n NonNullable<StatewireClient.SessionStorage[\"migrate\"]>\n >(\n (record, current) => {\n const migrated = parkIncompatibleSessionCommands(record, current);\n if (migrated.parked === 0) return migrated.record;\n reportDegradation({\n operation: \"migrate\",\n key: storageKey,\n error: new Error(\n `${migrated.parked} queued statewire command(s) predate the current protocol range; parked as failed sends`\n ),\n });\n return migrated.record;\n },\n [reportDegradation, storageKey]\n );\n\n const sessionStorage = useResource(\n KeyValueSessionStorage({\n backend: shared.backend,\n key: sessionKey,\n namespace: SESSION_PREFIX,\n protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,\n migrate,\n retention: { maxAgeMs: ttl, maxEntries: max },\n // A failure statewire raises itself (a structurally invalid stored\n // record) still stops the session; it is at least reported the same way.\n onError: (error) =>\n reportDegradation({ operation: \"session\", key: storageKey, error }),\n })\n );\n\n return useMemo(\n () => ({\n ...sessionStorage,\n lock: async <T>(fn: () => T | Promise<T>): Promise<T> => {\n let granted = false;\n try {\n return await locks.request(lockName, async () => {\n granted = true;\n return fn();\n });\n } catch (error) {\n if (granted) throw error;\n // The lock manager refused the request itself (a detached or\n // back/forward-cached document, a lockdown-mode origin): the\n // transaction runs unfenced rather than stopping the session.\n reportDegradation({ operation: \"lock\", key: storageKey, error });\n return fn();\n }\n },\n subscribe: (listener: () => void) => {\n const onStorage = (event: StorageEventLike) => {\n if (event.key === storageKey) listener();\n };\n browserGlobals.addEventListener?.(\"storage\", onStorage);\n return () => browserGlobals.removeEventListener?.(\"storage\", onStorage);\n },\n }),\n [sessionStorage, locks, storageKey, lockName, reportDegradation]\n );\n};\n\n/** Athena's browser session keys and retention policy. */\nexport const QuotaSafeLocalStorageSession = resource(\n useQuotaSafeLocalStorageSession\n);\n\nexport namespace QuotaSafeLocalStorageSession {\n export type Options = {\n threadId: string;\n /**\n * The lane's storage key for a thread, scoped by the principal (and the\n * sync host) the lane belongs to. It must keep naming the same principal's\n * lanes for the life of the mounted store: a change throws (\"principal\n * changed\"), as the upstream `LocalStorageSession` does, and the host\n * remounts the account's thread.\n */\n key?: (threadId: string) => string;\n ttl?: number;\n max?: number;\n /**\n * Called when a storage operation failed and the session carried on in\n * memory. Defaults to one `console.warn` per operation and key.\n */\n onStorageDegraded?: (degradation: SessionStorageDegradation) => void;\n };\n}\n"],"names":["storage","failed","useRef","isSameSessionLaneScope","useMemo","useEffect","useCallback","useResource","KeyValueSessionStorage","DEEP_AGENT_STATEWIRE_PROTOCOL","_a","resource"],"mappings":";;;;;;;AAUA,MAAM,iBAAiB;AACvB,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAC9B,MAAM,SAAS,KAAK,KAAK,KAAK;AAE9B,MAAM,4BAAkD,oBAAI,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC;AA0CzE,MAAM,iBAAiB;AAQhB,SAAS,8BACd,YACoC;AACpC,QAAMA,WAAU,eAAe;AAC/B,MAAI,CAACA,SAAS,QAAO;AACrB,MAAI;AACJ,MAAI;AACF,UAAM,MAAMA,SAAQ,QAAQ,iBAAiB,UAAU;AACvD,aACE,QAAQ,OAAO,OAAQ,KAAK,MAAM,GAAG;AAAA,EACzC,QAAQ;AACN,WAAO;AAAA,EACT;AACA,SAAO,+BAA+B,MAAM;AAC9C;AAYO,SAAS,+BACd,QACoC;;AACpC,MAAI,CAAC,UAAU,OAAO,WAAW,SAAU,QAAO;AAClD,QAAM,6BAAa,IAAA;AACnB,QAAM,QACJ,OAAO,SAAS,OAAO,OAAO,UAAU,WAAW,OAAO,QAAQ,CAAA;AACpE,QAAM,SAAS;AAAA,IACb,GAAI,MAAM,QAAQ,OAAO,MAAM,IAAI,OAAO,SAAS,CAAA;AAAA,IACnD,GAAG,OAAO,OAAO,KAAK,EAAE;AAAA,MAAQ,CAAC,SAC/B,MAAM,QAAQ,6BAAM,MAAM,IAAI,KAAK,SAAS,CAAA;AAAA,IAAC;AAAA,EAC/C;AAEF,aAAW,SAAS,QAAQ;AAC1B,UAAMC,UAAS;AAIf,UAAM,aAAYA,oDAAQ,WAARA,mBAAiB,OAAjBA,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;AAAA,MAChB,KAAK;AAAA,MACL,WAAW;AAAA,MACX,UAAUC,mBAAAA;AAAAA,MACV;AAAA,MACA,WAAW,EAAE,UAAU,KAAK,YAAY,IAAA;AAAA;AAAA;AAAA,MAGxC,SAAS,CAAC,UACR,kBAAkB,EAAE,WAAW,WAAW,KAAK,YAAY,MAAA,CAAO;AAAA,IAAA,CACrE;AAAA,EAAA;AAGH,SAAOL,MAAAA;AAAAA,IACL,OAAO;AAAA,MACL,GAAG;AAAA,MACH,MAAM,OAAU,OAAyC;AACvD,YAAI,UAAU;AACd,YAAI;AACF,iBAAO,MAAM,MAAM,QAAQ,UAAU,YAAY;AAC/C,sBAAU;AACV,mBAAO,GAAA;AAAA,UACT,CAAC;AAAA,QACH,SAAS,OAAO;AACd,cAAI,QAAS,OAAM;AAInB,4BAAkB,EAAE,WAAW,QAAQ,KAAK,YAAY,OAAO;AAC/D,iBAAO,GAAA;AAAA,QACT;AAAA,MACF;AAAA,MACA,WAAW,CAAC,aAAyB;;AACnC,cAAM,YAAY,CAAC,UAA4B;AAC7C,cAAI,MAAM,QAAQ,WAAY,UAAA;AAAA,QAChC;AACA,SAAAM,MAAA,eAAe,qBAAf,gBAAAA,IAAA,qBAAkC,WAAW;AAC7C,eAAO;;AAAM,kBAAAA,MAAA,eAAe,wBAAf,gBAAAA,IAAA,qBAAqC,WAAW;AAAA;AAAA,MAC/D;AAAA,IAAA;AAAA,IAEF,CAAC,gBAAgB,OAAO,YAAY,UAAU,iBAAiB;AAAA,EAAA;AAEnE;AAGO,MAAM,+BAA+BC,IAAAA;AAAAA,EAC1C;AACF;;;;;;;;;"}
@@ -141,6 +141,13 @@ export declare const QuotaSafeLocalStorageSession: import("@assistant-ui/tap").R
141
141
  export declare namespace QuotaSafeLocalStorageSession {
142
142
  type Options = {
143
143
  threadId: string;
144
+ /**
145
+ * The lane's storage key for a thread, scoped by the principal (and the
146
+ * sync host) the lane belongs to. It must keep naming the same principal's
147
+ * lanes for the life of the mounted store: a change throws ("principal
148
+ * changed"), as the upstream `LocalStorageSession` does, and the host
149
+ * remounts the account's thread.
150
+ */
144
151
  key?: (threadId: string) => string;
145
152
  ttl?: number;
146
153
  max?: number;
@@ -1,6 +1,7 @@
1
1
  import { resource, useResource } from "@assistant-ui/tap";
2
2
  import { KeyValueSessionStorage } from "statewire/storage";
3
3
  import { useRef, useMemo, useEffect, useCallback } from "react";
4
+ import { isSameSessionLaneScope } from "./session-lane-scope.js";
4
5
  import { DEEP_AGENT_STATEWIRE_PROTOCOL } from "./statewire-transport.js";
5
6
  const SESSION_PREFIX = "aui:statewire-session:";
6
7
  const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:";
@@ -318,6 +319,15 @@ const useQuotaSafeLocalStorageSession = ({
318
319
  const sessionKey = key(threadId);
319
320
  const storageKey = SESSION_PREFIX + sessionKey;
320
321
  const lockName = SESSION_LOCK_PREFIX + sessionKey;
322
+ const mountedScope = useRef({
323
+ threadId,
324
+ laneKey: sessionKey
325
+ });
326
+ if (!isSameSessionLaneScope({ scope: mountedScope.current, key })) {
327
+ throw new Error(
328
+ "statewire: principal changed; remount the account's thread/session"
329
+ );
330
+ }
321
331
  const latestOnDegraded = useRef(onStorageDegraded);
322
332
  latestOnDegraded.current = onStorageDegraded;
323
333
  const reportDegradation = useMemo(() => {
@@ -1 +1 @@
1
- {"version":3,"file":"quota-safe-local-storage-session.js","sources":["../../../../agent-runtime/src/quota-safe-local-storage-session.ts"],"sourcesContent":["import { resource, useResource } from \"@assistant-ui/tap\";\nimport type { StatewireClient, StatewireProtocol } from \"statewire\";\nimport { KeyValueSessionStorage } from \"statewire/storage\";\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { DEEP_AGENT_STATEWIRE_PROTOCOL } from \"./statewire-transport\";\n\nconst SESSION_PREFIX = \"aui:statewire-session:\";\nconst SESSION_LOCK_PREFIX = \"aui:statewire-session-lock:\";\nconst SESSION_ACTIVE_PREFIX = \"aui:statewire-session-active:\";\nconst DAY_MS = 24 * 60 * 60 * 1000;\n/** The stored-record formats the statewire this build ships reads (it writes 3). */\nconst READABLE_STORAGE_VERSIONS: ReadonlySet<unknown> = new Set([1, 2, 3]);\n\n/** Structural view of the browser storage global — this package compiles\n * without the DOM lib (React Native honesty; see `globals.d.ts`). */\ntype StorageLike = {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n key(index: number): string | null;\n readonly length: number;\n};\n\ntype LockGrant = object | null;\n\n/** The Web Locks API surface the session uses (`navigator.locks`). */\ntype LockManagerLike = {\n request<T>(\n name: string,\n callback: (lock: LockGrant) => T | Promise<T>\n ): Promise<T>;\n request<T>(\n name: string,\n options: { mode?: \"shared\" | \"exclusive\"; ifAvailable?: boolean },\n callback: (lock: LockGrant) => T | Promise<T>\n ): Promise<T>;\n};\n\ntype StorageEventLike = { key: string | null };\n\ntype BrowserGlobals = {\n localStorage?: StorageLike;\n navigator?: { locks?: LockManagerLike };\n addEventListener?: (\n type: \"storage\",\n listener: (event: StorageEventLike) => void\n ) => void;\n removeEventListener?: (\n type: \"storage\",\n listener: (event: StorageEventLike) => void\n ) => void;\n};\n\nconst browserGlobals = globalThis as BrowserGlobals;\n\n/** A persisted session record: per-lane failed entries (a pre-lane record carried them at the root). */\ntype SessionRecordLike = {\n failed?: unknown;\n lanes?: Record<string, { failed?: unknown } | null | undefined> | null;\n};\n\nexport function readPersistedFailedSendStamps(\n sessionKey: string\n): ReadonlyMap<string, number> | null {\n const storage = browserGlobals.localStorage;\n if (!storage) return null;\n let record: SessionRecordLike | null;\n try {\n const raw = storage.getItem(SESSION_PREFIX + sessionKey);\n record =\n raw === null ? null : (JSON.parse(raw) as SessionRecordLike | null);\n } catch {\n return null;\n }\n return readFailedSendStampsFromRecord(record);\n}\n\n/**\n * Send stamps (message id → epoch ms of the original send) off an already\n * loaded session record's failed lane — the storage-agnostic half of\n * {@link readPersistedFailedSendStamps}, for hosts whose session store is not\n * localStorage (the React Native AsyncStorage-backed store reads its record\n * synchronously through `SessionStorage.load()`).\n *\n * Returns `null` for no record (every failed entry then counts as fresh) and\n * an empty map for a record without failures.\n */\nexport function readFailedSendStampsFromRecord(\n record: SessionRecordLike | null | undefined\n): ReadonlyMap<string, number> | null {\n if (!record || typeof record !== \"object\") return null;\n const stamps = new Map<string, number>();\n const lanes =\n record.lanes && typeof record.lanes === \"object\" ? record.lanes : {};\n const failed = [\n ...(Array.isArray(record.failed) ? record.failed : []),\n ...Object.values(lanes).flatMap((lane) =>\n Array.isArray(lane?.failed) ? lane.failed : []\n ),\n ];\n for (const entry of failed) {\n const failed = entry as {\n ts?: unknown;\n params?: readonly { message?: { id?: unknown } }[];\n } | null;\n const messageId = failed?.params?.[0]?.message?.id;\n if (typeof messageId === \"string\" && typeof failed?.ts === \"number\") {\n stamps.set(messageId, failed.ts);\n }\n }\n return stamps;\n}\n\n/** A storage operation the session survived by degrading instead of failing. */\nexport type SessionStorageDegradation = {\n operation:\n | \"getItem\"\n | \"setItem\"\n | \"removeItem\"\n | \"getAllKeys\"\n | \"withUnused\"\n /** The lock manager refused the transaction fence; it ran unfenced. */\n | \"lock\"\n /**\n * The stored record is one this build cannot read (not JSON, or a newer\n * storage version): served as absent, and the key is shielded from being\n * overwritten so the record survives this tab.\n */\n | \"record\"\n /** statewire's own storage failure (a structurally invalid stored record). */\n | \"session\"\n /**\n * Queued commands persisted by an earlier statewire build no longer fit\n * the current wire/protocol range: parked in the lane's failed list (the\n * send-recovery sweep re-dispatches them) instead of blocking the mount.\n */\n | \"migrate\";\n key: string;\n error: unknown;\n};\n\ntype ProducedRange = NonNullable<StatewireClient.SessionCommand[\"produced\"]>;\n\nconst inRange = (value: string, range: StatewireProtocol.Range) =>\n value >= (range.minVersion ?? range.version) && value <= range.version;\n\n/** Mirrors statewire's own stored-command compatibility check. */\nconst storedCommandCompatible = (\n protocol: string,\n command: StatewireClient.SessionCommand,\n current: ProducedRange\n): boolean => {\n if (\n !command.produced ||\n !inRange(command.produced.wire.version, current.wire)\n )\n return false;\n if (current.protocols === \"*\") return true;\n if (command.produced.protocols === \"*\") return false;\n const produced = command.produced.protocols.find((p) => p.name === protocol);\n const offer = current.protocols.find((p) => p.name === protocol);\n return (\n produced !== undefined &&\n offer !== undefined &&\n inRange(produced.version, offer)\n );\n};\n\n/**\n * The oldest wire whose stored statements the current client still replays.\n * Bundled clients before #45143 offered 2026-09-13 through 2026-09-30 and\n * stamped every queued statement with 2026-09-13. The durable statement grammar\n * (protocol, method, params, meta, seq) is the same on 2026-09-30; only\n * frame-level context differs. So those statements ride the current wire\n * unchanged, while the network offer stays native 2026-09-30 only.\n */\nexport const STORED_STATEMENT_WIRE_FLOOR = \"2026-09-13\";\n\n/** A stored command the current wire replays as-is: re-stamp, don't park. */\nconst replayableOnCurrentWire = (\n protocol: string,\n command: StatewireClient.SessionCommand,\n current: ProducedRange\n): boolean =>\n command.produced !== undefined &&\n inRange(command.produced.wire.version, {\n version: current.wire.version,\n minVersion: STORED_STATEMENT_WIRE_FLOOR,\n }) &&\n storedCommandCompatible(\n protocol,\n { ...command, produced: { ...command.produced, wire: current.wire } },\n current\n );\n\n/**\n * statewire's `migrate` for a record whose queued commands were produced by\n * an earlier build. A command whose statement the current wire still replays\n * ({@link STORED_STATEMENT_WIRE_FLOOR}: an approval's `run/input` saved by a\n * previous bundled client, say) stays queued, re-stamped with the current\n * range, so it is delivered with its original seq. Every other incompatible\n * command leaves its lane's queue and is\n * retained as a `lost`/`session-lost` failed send re-stamped with the current\n * range. Client identity, lane clocks, compatible commands and existing failed\n * history are untouched, so the mount proceeds and the send-recovery sweep\n * (or the user, via the failed-send UI) re-dispatches the parked sends under\n * the negotiated format instead of the runtime throwing before it dials.\n *\n * Returns the record itself when nothing needed migrating, and the count of\n * parked commands otherwise.\n */\nexport function parkIncompatibleSessionCommands(\n record: StatewireClient.SessionRecord,\n current: ProducedRange,\n now: number = Date.now()\n): { record: StatewireClient.SessionRecord; parked: number; restamped: number } {\n let parked = 0;\n let restamped = 0;\n const lanes: Record<string, StatewireClient.SessionLane> = {};\n for (const [protocol, lane] of Object.entries(record.lanes)) {\n const kept: StatewireClient.SessionCommand[] = [];\n const failed: StatewireClient.FailedCommand[] = [];\n let laneRestamped = 0;\n for (const command of lane.commands) {\n if (storedCommandCompatible(protocol, command, current)) {\n kept.push(command);\n continue;\n }\n if (replayableOnCurrentWire(protocol, command, current)) {\n kept.push({ ...command, produced: current });\n laneRestamped += 1;\n continue;\n }\n failed.push({\n protocol,\n produced: current,\n command: command.method,\n params: command.params,\n ...(command.meta !== undefined && { meta: command.meta }),\n failure: { fate: \"lost\", cause: \"session-lost\" },\n ts: now,\n seq: command.seq,\n });\n }\n parked += failed.length;\n restamped += laneRestamped;\n lanes[protocol] =\n failed.length === 0 && laneRestamped === 0\n ? lane\n : {\n ...lane,\n commands: kept,\n ...((failed.length > 0 || lane.failed !== undefined) && {\n failed: [...(lane.failed ?? []), ...failed],\n }),\n };\n }\n return parked === 0 && restamped === 0\n ? { record, parked, restamped }\n : { record: { ...record, lanes }, parked, restamped };\n}\n\n/**\n * Whether `error` is the browser refusing a write for lack of room, under\n * every name the engines use — `QuotaExceededError` (Chromium, WebKit, current\n * Firefox), `NS_ERROR_DOM_QUOTA_REACHED` (older Firefox), the legacy\n * `DOMException` codes 22 (WebKit) and 1014 (Firefox) — or a plain error whose\n * message carries one of those (storage proxies and WebViews rewrap the\n * exception). Olympus's `isStorageQuotaError` recognises the same set; the two\n * stay in step.\n */\nexport function isStorageQuotaError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false;\n const { name, code, message } = error as {\n name?: unknown;\n code?: unknown;\n message?: unknown;\n };\n return (\n name === \"QuotaExceededError\" ||\n name === \"NS_ERROR_DOM_QUOTA_REACHED\" ||\n code === 22 ||\n code === 1014 ||\n (typeof message === \"string\" &&\n /exceeded the quota|quotaexceedederror|ns_error_dom_quota_reached/i.test(\n message\n ))\n );\n}\n\n/** The one quota shape statewire's retention sweep recognises. */\nfunction asStatewireQuotaError(error: unknown): Error {\n if (error instanceof Error && error.name === \"QuotaExceededError\")\n return error;\n const normalized = new Error(\n error instanceof Error ? error.message : \"storage quota exceeded\"\n );\n normalized.name = \"QuotaExceededError\";\n return normalized;\n}\n\n/**\n * Why `raw` is a stored record this build cannot read, or `undefined` when it\n * may be one. Mirrors the two decode failures statewire raises for a record it\n * cannot read — invalid JSON, and a `statewireStorageVersion` newer than the\n * ones this build's statewire decodes (a tab left open across a\n * statewire upgrade, reading the record a newer tab keeps) — because statewire\n * throws those out of the resource at mount instead of treating the record as\n * absent. A structurally invalid record of the right version still fails\n * inside statewire.\n */\nfunction unreadableRecord(raw: string): Error | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n return error instanceof Error\n ? error\n : new Error(\"stored session record is not JSON\");\n }\n if (typeof parsed !== \"object\" || parsed === null) {\n return new Error(\"stored session record is not an object\");\n }\n const version = (parsed as { statewireStorageVersion?: unknown })\n .statewireStorageVersion;\n if (version !== undefined && !READABLE_STORAGE_VERSIONS.has(version)) {\n return new Error(\n `stored session record uses storage version ${String(version)}`\n );\n }\n return undefined;\n}\n\ntype SyncBackend = {\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n getAllKeys: () => readonly string[];\n withUnused: (key: string, action: () => Promise<void>) => Promise<void>;\n};\n\n/**\n * The browser backend `@assistant-ui/react-statewire`'s `LocalStorageSession`\n * uses, reproduced here because that resource does not take a backend: raw\n * `localStorage`, with retention cleanup fenced by the same Web Locks so a\n * sweep never removes a record another tab is actively sharing.\n */\nfunction browserBackend({\n storage,\n locks,\n}: {\n storage: StorageLike;\n locks: LockManagerLike;\n}): SyncBackend {\n return {\n getItem: (key) => storage.getItem(key),\n setItem: (key, value) => storage.setItem(key, value),\n removeItem: (key) => storage.removeItem(key),\n getAllKeys: () =>\n Array.from({ length: storage.length }, (_, index) =>\n storage.key(index)\n ).filter((key): key is string => key !== null),\n withUnused: async (key, action) => {\n await locks.request(\n SESSION_ACTIVE_PREFIX + key,\n { ifAvailable: true },\n async (active) => {\n if (active === null) return;\n await locks.request(\n SESSION_LOCK_PREFIX + key.slice(SESSION_PREFIX.length),\n { ifAvailable: true },\n async (lock) => {\n if (lock === null) return;\n await action();\n }\n );\n }\n );\n },\n };\n}\n\n/**\n * Wraps a synchronous key-value backend so a failing origin degrades the\n * session to memory-only persistence instead of stopping the connection.\n *\n * statewire's session storage latches the first unrecognised write failure\n * and from then on rejects every send (`stopped/storage-error`, \"session\n * storage failed\" on the connection chip). It only recovers a\n * `QuotaExceededError` by that exact name — sweeping old session records and\n * retrying the write once — and latches again when the retry fails too. Here\n * the first quota failure per key is surfaced under that name so the sweep\n * runs; the retry that follows it and every other storage failure are absorbed\n * and reported through `onDegraded`, so chat keeps working.\n *\n * An absorbed write is kept in an in-memory overlay that `getItem` serves\n * first: statewire re-reads the record through `load()` on every shared-mode\n * transaction, so a stale persisted copy would otherwise win back its old\n * `nextSeq`, `clientId` and command journal. The overlay is per tab — another\n * tab sharing the thread still reads the last persisted copy, which is the\n * memory-only degradation this backend exists to allow. A later successful\n * write clears the overlay entry.\n *\n * A key whose read threw, or whose stored value this build cannot read (see\n * {@link unreadableRecord}), is served as absent and shielded: writes to it\n * stay in the overlay for good, so a fresh lane minted over an unreadable\n * record never overwrites what another tab or a newer build persisted.\n */\nexport function quotaTolerantBackend({\n inner,\n onDegraded,\n}: {\n inner: SyncBackend;\n onDegraded: (degradation: SessionStorageDegradation) => void;\n}): SyncBackend & KeyValueSessionStorage.Backend {\n // Keys whose write already surfaced a quota error to statewire: until a\n // write succeeds again, later failures on the key are absorbed instead of\n // surfaced, or every save would re-run statewire's sweep (which evicts\n // other threads' idle records) and the failure would latch on the retry.\n const quotaSurfaced = new Set<string>();\n // Absorbed writes, served ahead of the backend (see the function docs).\n const overlay = new Map<string, string>();\n // Keys served as absent and never written through (see the function docs).\n const shielded = new Set<string>();\n // statewire re-reads and re-decodes the record on every transaction; the\n // readability check is memoised on the raw string so it costs one string\n // comparison per read, not a second parse.\n const checked = new Map<\n string,\n { raw: string; verdict: Error | undefined }\n >();\n const readable = (key: string, raw: string): Error | undefined => {\n const previous = checked.get(key);\n if (previous !== undefined && previous.raw === raw) return previous.verdict;\n const verdict = unreadableRecord(raw);\n checked.set(key, { raw, verdict });\n return verdict;\n };\n return {\n getItem: (key) => {\n const shadowed = overlay.get(key);\n if (shadowed !== undefined) return shadowed;\n if (shielded.has(key)) return null;\n let raw: string | null;\n try {\n raw = inner.getItem(key);\n } catch (error) {\n shielded.add(key);\n onDegraded({ operation: \"getItem\", key, error });\n return null;\n }\n if (raw === null) return null;\n const unreadable = readable(key, raw);\n if (unreadable === undefined) return raw;\n shielded.add(key);\n onDegraded({ operation: \"record\", key, error: unreadable });\n return null;\n },\n setItem: (key, value) => {\n if (shielded.has(key)) {\n overlay.set(key, value);\n return;\n }\n try {\n inner.setItem(key, value);\n overlay.delete(key);\n quotaSurfaced.delete(key);\n } catch (error) {\n if (isStorageQuotaError(error) && !quotaSurfaced.has(key)) {\n quotaSurfaced.add(key);\n throw asStatewireQuotaError(error);\n }\n overlay.set(key, value);\n onDegraded({ operation: \"setItem\", key, error });\n }\n },\n removeItem: (key) => {\n overlay.delete(key);\n if (shielded.has(key)) return;\n try {\n inner.removeItem(key);\n } catch (error) {\n onDegraded({ operation: \"removeItem\", key, error });\n }\n },\n getAllKeys: () => {\n const keys = new Set<string>(overlay.keys());\n try {\n for (const key of inner.getAllKeys()) keys.add(key);\n } catch (error) {\n onDegraded({ operation: \"getAllKeys\", key: \"\", error });\n }\n return [...keys];\n },\n withUnused: async (key, action) => {\n try {\n await inner.withUnused(key, action);\n } catch (error) {\n onDegraded({ operation: \"withUnused\", key, error });\n }\n },\n };\n}\n\n/** A stored record's save stamp, or `undefined` when it carries none. */\nfunction savedAtOf(raw: string | null): number | undefined {\n if (raw === null) return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return undefined;\n }\n if (typeof parsed !== \"object\" || parsed === null) return undefined;\n const { savedAt, updatedAt } = parsed as {\n savedAt?: unknown;\n updatedAt?: unknown;\n };\n const stamp = savedAt ?? updatedAt;\n return typeof stamp === \"number\" && Number.isFinite(stamp)\n ? stamp\n : undefined;\n}\n\n/**\n * Removes session records last saved more than `maxAgeMs` ago, skipping the\n * keys mounted in this tab and, through `withUnused`, those another tab holds.\n *\n * statewire's own retention sweep only retires records with nothing queued and\n * nothing failed: a record still carrying an unconfirmed or failed send is\n * exempt from both its age and count bounds, so every thread left with one\n * kept its key forever. Past the TTL those sends are long out of send\n * recovery's auto-retry window, so the record goes the same way an empty one\n * does.\n */\nexport async function retireExpiredSessionRecords({\n backend,\n mounted,\n maxAgeMs,\n now = Date.now(),\n}: {\n backend: Pick<\n SyncBackend,\n \"getItem\" | \"removeItem\" | \"getAllKeys\" | \"withUnused\"\n >;\n mounted: ReadonlyMap<string, number>;\n maxAgeMs: number;\n now?: number;\n}): Promise<void> {\n for (const key of backend.getAllKeys()) {\n if (!key.startsWith(SESSION_PREFIX) || mounted.has(key)) continue;\n const savedAt = savedAtOf(backend.getItem(key));\n if (savedAt === undefined || now - savedAt <= maxAgeMs) continue;\n await backend.withUnused(key, async () => {\n if (mounted.has(key) || savedAtOf(backend.getItem(key)) !== savedAt)\n return;\n backend.removeItem(key);\n });\n }\n}\n\ntype DegradationListener = (degradation: SessionStorageDegradation) => void;\n\ntype SharedBackend = {\n backend: SyncBackend & KeyValueSessionStorage.Backend;\n listeners: Set<DegradationListener>;\n /** Storage keys of the sessions mounted in this tab, with mount counts. */\n mounted: Map<string, number>;\n};\n\n/**\n * One backend per storage object — per origin, in a browser — shared by every\n * session mounted in the tab, exactly as the upstream resource's module-level\n * backend is. statewire keys its in-tab \"active\" bookkeeping by backend\n * identity, so a mount's retention sweep only skips the records of other\n * mounts on the *same* backend; and the absorbed-write overlay has to outlive\n * a remount of the same thread (a thread switch and back) or the remount would\n * read the stale persisted copy. Degradations fan out to every mounted\n * session's reporter.\n */\nconst sharedBackends = new WeakMap<StorageLike, SharedBackend>();\n\nfunction sharedBackend({\n storage,\n locks,\n}: {\n storage: StorageLike;\n locks: LockManagerLike;\n}): SharedBackend {\n let shared = sharedBackends.get(storage);\n if (shared === undefined) {\n const listeners = new Set<DegradationListener>();\n shared = {\n listeners,\n mounted: new Map(),\n backend: quotaTolerantBackend({\n inner: browserBackend({ storage, locks }),\n onDegraded: (degradation) => {\n for (const listener of listeners) listener(degradation);\n },\n }),\n };\n sharedBackends.set(storage, shared);\n }\n return shared;\n}\n\n/**\n * Athena's browser session store: `@assistant-ui/react-statewire`'s\n * `LocalStorageSession` contract (per-thread key under the shared prefix,\n * cross-tab Web Lock, storage-event subscription, retention) on top of\n * {@link quotaTolerantBackend}, with Athena's protocol lane and retention\n * policy.\n */\nconst useQuotaSafeLocalStorageSession = ({\n threadId,\n key = (id) => id,\n ttl = 7 * DAY_MS,\n max = 50,\n onStorageDegraded,\n}: QuotaSafeLocalStorageSession.Options): StatewireClient.SessionStorage => {\n const storage = browserGlobals.localStorage;\n const locks = browserGlobals.navigator?.locks;\n if (!storage)\n throw new Error(\n \"statewire: QuotaSafeLocalStorageSession requires localStorage\"\n );\n if (!locks)\n throw new Error(\n \"statewire: QuotaSafeLocalStorageSession requires the Web Locks API (navigator.locks)\"\n );\n const sessionKey = key(threadId);\n const storageKey = SESSION_PREFIX + sessionKey;\n const lockName = SESSION_LOCK_PREFIX + sessionKey;\n\n const latestOnDegraded = useRef(onStorageDegraded);\n latestOnDegraded.current = onStorageDegraded;\n const reportDegradation = useMemo(() => {\n const reported = new Set<string>();\n return (degradation: SessionStorageDegradation) => {\n const handler = latestOnDegraded.current;\n if (handler) {\n try {\n handler(degradation);\n } catch {\n // Reporting runs inside the session's recovery path and must never\n // become the failure it is reporting.\n }\n return;\n }\n const dedupeKey = `${degradation.operation}:${degradation.key}`;\n if (reported.has(dedupeKey)) return;\n reported.add(dedupeKey);\n console.warn(\n `[statewire] session storage degraded to memory only (${degradation.operation} ${degradation.key})`,\n degradation.error\n );\n };\n }, []);\n\n const shared = sharedBackend({ storage, locks });\n // Registered during render as well as in the effect: the read statewire\n // makes while mounting below happens before any effect runs, and tap may\n // clean an effect up and re-run it within one commit.\n shared.listeners.add(reportDegradation);\n useEffect(() => {\n shared.listeners.add(reportDegradation);\n return () => {\n shared.listeners.delete(reportDegradation);\n };\n }, [shared, reportDegradation]);\n\n useEffect(() => {\n const { mounted } = shared;\n mounted.set(storageKey, (mounted.get(storageKey) ?? 0) + 1);\n retireExpiredSessionRecords({\n backend: shared.backend,\n mounted,\n maxAgeMs: ttl,\n }).catch((error: unknown) =>\n reportDegradation({ operation: \"withUnused\", key: storageKey, error })\n );\n return () => {\n const count = (mounted.get(storageKey) ?? 1) - 1;\n if (count === 0) mounted.delete(storageKey);\n else mounted.set(storageKey, count);\n };\n }, [shared, storageKey, ttl, reportDegradation]);\n\n // Hold the record's shared \"active\" lock while mounted so another tab's\n // retention sweep skips it (the same fence the upstream resource holds).\n useEffect(() => {\n let release: (() => void) | undefined;\n let disposed = false;\n Promise.resolve(\n locks.request(\n SESSION_ACTIVE_PREFIX + storageKey,\n { mode: \"shared\" },\n () => {\n if (disposed) return;\n return new Promise<void>((resolve) => {\n release = resolve;\n });\n }\n )\n ).catch((error: unknown) =>\n reportDegradation({ operation: \"lock\", key: storageKey, error })\n );\n return () => {\n disposed = true;\n release?.();\n };\n }, [locks, storageKey, reportDegradation]);\n\n // The storage resource includes migrate in its identity. A fresh callback\n // on every render replaces the store and prevents hydration from settling.\n const migrate = useCallback<\n NonNullable<StatewireClient.SessionStorage[\"migrate\"]>\n >(\n (record, current) => {\n const migrated = parkIncompatibleSessionCommands(record, current);\n if (migrated.parked === 0) return migrated.record;\n reportDegradation({\n operation: \"migrate\",\n key: storageKey,\n error: new Error(\n `${migrated.parked} queued statewire command(s) predate the current protocol range; parked as failed sends`\n ),\n });\n return migrated.record;\n },\n [reportDegradation, storageKey]\n );\n\n const sessionStorage = useResource(\n KeyValueSessionStorage({\n backend: shared.backend,\n key: sessionKey,\n namespace: SESSION_PREFIX,\n protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,\n migrate,\n retention: { maxAgeMs: ttl, maxEntries: max },\n // A failure statewire raises itself (a structurally invalid stored\n // record) still stops the session; it is at least reported the same way.\n onError: (error) =>\n reportDegradation({ operation: \"session\", key: storageKey, error }),\n })\n );\n\n return useMemo(\n () => ({\n ...sessionStorage,\n lock: async <T>(fn: () => T | Promise<T>): Promise<T> => {\n let granted = false;\n try {\n return await locks.request(lockName, async () => {\n granted = true;\n return fn();\n });\n } catch (error) {\n if (granted) throw error;\n // The lock manager refused the request itself (a detached or\n // back/forward-cached document, a lockdown-mode origin): the\n // transaction runs unfenced rather than stopping the session.\n reportDegradation({ operation: \"lock\", key: storageKey, error });\n return fn();\n }\n },\n subscribe: (listener: () => void) => {\n const onStorage = (event: StorageEventLike) => {\n if (event.key === storageKey) listener();\n };\n browserGlobals.addEventListener?.(\"storage\", onStorage);\n return () => browserGlobals.removeEventListener?.(\"storage\", onStorage);\n },\n }),\n [sessionStorage, locks, storageKey, lockName, reportDegradation]\n );\n};\n\n/** Athena's browser session keys and retention policy. */\nexport const QuotaSafeLocalStorageSession = resource(\n useQuotaSafeLocalStorageSession\n);\n\nexport namespace QuotaSafeLocalStorageSession {\n export type Options = {\n threadId: string;\n key?: (threadId: string) => string;\n ttl?: number;\n max?: number;\n /**\n * Called when a storage operation failed and the session carried on in\n * memory. Defaults to one `console.warn` per operation and key.\n */\n onStorageDegraded?: (degradation: SessionStorageDegradation) => void;\n };\n}\n"],"names":["failed","_a"],"mappings":";;;;AAMA,MAAM,iBAAiB;AACvB,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAC9B,MAAM,SAAS,KAAK,KAAK,KAAK;AAE9B,MAAM,4BAAkD,oBAAI,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC;AA0CzE,MAAM,iBAAiB;AAQhB,SAAS,8BACd,YACoC;AACpC,QAAM,U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AA,qBAAqC,WAAW;AAAA;AAAA,MAC/D;AAAA,IAAA;AAAA,IAEF,CAAC,gBAAgB,OAAO,YAAY,UAAU,iBAAiB;AAAA,EAAA;AAEnE;AAGO,MAAM,+BAA+B;AAAA,EAC1C;AACF;"}
1
+ {"version":3,"file":"quota-safe-local-storage-session.js","sources":["../../../../agent-runtime/src/quota-safe-local-storage-session.ts"],"sourcesContent":["import { resource, useResource } from \"@assistant-ui/tap\";\nimport type { StatewireClient, StatewireProtocol } from \"statewire\";\nimport { KeyValueSessionStorage } from \"statewire/storage\";\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport {\n type DeepAgentSessionLaneScope,\n isSameSessionLaneScope,\n} from \"./session-lane-scope\";\nimport { DEEP_AGENT_STATEWIRE_PROTOCOL } from \"./statewire-transport\";\n\nconst SESSION_PREFIX = \"aui:statewire-session:\";\nconst SESSION_LOCK_PREFIX = \"aui:statewire-session-lock:\";\nconst SESSION_ACTIVE_PREFIX = \"aui:statewire-session-active:\";\nconst DAY_MS = 24 * 60 * 60 * 1000;\n/** The stored-record formats the statewire this build ships reads (it writes 3). */\nconst READABLE_STORAGE_VERSIONS: ReadonlySet<unknown> = new Set([1, 2, 3]);\n\n/** Structural view of the browser storage global — this package compiles\n * without the DOM lib (React Native honesty; see `globals.d.ts`). */\ntype StorageLike = {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n key(index: number): string | null;\n readonly length: number;\n};\n\ntype LockGrant = object | null;\n\n/** The Web Locks API surface the session uses (`navigator.locks`). */\ntype LockManagerLike = {\n request<T>(\n name: string,\n callback: (lock: LockGrant) => T | Promise<T>\n ): Promise<T>;\n request<T>(\n name: string,\n options: { mode?: \"shared\" | \"exclusive\"; ifAvailable?: boolean },\n callback: (lock: LockGrant) => T | Promise<T>\n ): Promise<T>;\n};\n\ntype StorageEventLike = { key: string | null };\n\ntype BrowserGlobals = {\n localStorage?: StorageLike;\n navigator?: { locks?: LockManagerLike };\n addEventListener?: (\n type: \"storage\",\n listener: (event: StorageEventLike) => void\n ) => void;\n removeEventListener?: (\n type: \"storage\",\n listener: (event: StorageEventLike) => void\n ) => void;\n};\n\nconst browserGlobals = globalThis as BrowserGlobals;\n\n/** A persisted session record: per-lane failed entries (a pre-lane record carried them at the root). */\ntype SessionRecordLike = {\n failed?: unknown;\n lanes?: Record<string, { failed?: unknown } | null | undefined> | null;\n};\n\nexport function readPersistedFailedSendStamps(\n sessionKey: string\n): ReadonlyMap<string, number> | null {\n const storage = browserGlobals.localStorage;\n if (!storage) return null;\n let record: SessionRecordLike | null;\n try {\n const raw = storage.getItem(SESSION_PREFIX + sessionKey);\n record =\n raw === null ? null : (JSON.parse(raw) as SessionRecordLike | null);\n } catch {\n return null;\n }\n return readFailedSendStampsFromRecord(record);\n}\n\n/**\n * Send stamps (message id → epoch ms of the original send) off an already\n * loaded session record's failed lane — the storage-agnostic half of\n * {@link readPersistedFailedSendStamps}, for hosts whose session store is not\n * localStorage (the React Native AsyncStorage-backed store reads its record\n * synchronously through `SessionStorage.load()`).\n *\n * Returns `null` for no record (every failed entry then counts as fresh) and\n * an empty map for a record without failures.\n */\nexport function readFailedSendStampsFromRecord(\n record: SessionRecordLike | null | undefined\n): ReadonlyMap<string, number> | null {\n if (!record || typeof record !== \"object\") return null;\n const stamps = new Map<string, number>();\n const lanes =\n record.lanes && typeof record.lanes === \"object\" ? record.lanes : {};\n const failed = [\n ...(Array.isArray(record.failed) ? record.failed : []),\n ...Object.values(lanes).flatMap((lane) =>\n Array.isArray(lane?.failed) ? lane.failed : []\n ),\n ];\n for (const entry of failed) {\n const failed = entry as {\n ts?: unknown;\n params?: readonly { message?: { id?: unknown } }[];\n } | null;\n const messageId = failed?.params?.[0]?.message?.id;\n if (typeof messageId === \"string\" && typeof failed?.ts === \"number\") {\n stamps.set(messageId, failed.ts);\n }\n }\n return stamps;\n}\n\n/** A storage operation the session survived by degrading instead of failing. */\nexport type SessionStorageDegradation = {\n operation:\n | \"getItem\"\n | \"setItem\"\n | \"removeItem\"\n | \"getAllKeys\"\n | \"withUnused\"\n /** The lock manager refused the transaction fence; it ran unfenced. */\n | \"lock\"\n /**\n * The stored record is one this build cannot read (not JSON, or a newer\n * storage version): served as absent, and the key is shielded from being\n * overwritten so the record survives this tab.\n */\n | \"record\"\n /** statewire's own storage failure (a structurally invalid stored record). */\n | \"session\"\n /**\n * Queued commands persisted by an earlier statewire build no longer fit\n * the current wire/protocol range: parked in the lane's failed list (the\n * send-recovery sweep re-dispatches them) instead of blocking the mount.\n */\n | \"migrate\";\n key: string;\n error: unknown;\n};\n\ntype ProducedRange = NonNullable<StatewireClient.SessionCommand[\"produced\"]>;\n\nconst inRange = (value: string, range: StatewireProtocol.Range) =>\n value >= (range.minVersion ?? range.version) && value <= range.version;\n\n/** Mirrors statewire's own stored-command compatibility check. */\nconst storedCommandCompatible = (\n protocol: string,\n command: StatewireClient.SessionCommand,\n current: ProducedRange\n): boolean => {\n if (\n !command.produced ||\n !inRange(command.produced.wire.version, current.wire)\n )\n return false;\n if (current.protocols === \"*\") return true;\n if (command.produced.protocols === \"*\") return false;\n const produced = command.produced.protocols.find((p) => p.name === protocol);\n const offer = current.protocols.find((p) => p.name === protocol);\n return (\n produced !== undefined &&\n offer !== undefined &&\n inRange(produced.version, offer)\n );\n};\n\n/**\n * The oldest wire whose stored statements the current client still replays.\n * Bundled clients before #45143 offered 2026-09-13 through 2026-09-30 and\n * stamped every queued statement with 2026-09-13. The durable statement grammar\n * (protocol, method, params, meta, seq) is the same on 2026-09-30; only\n * frame-level context differs. So those statements ride the current wire\n * unchanged, while the network offer stays native 2026-09-30 only.\n */\nexport const STORED_STATEMENT_WIRE_FLOOR = \"2026-09-13\";\n\n/** A stored command the current wire replays as-is: re-stamp, don't park. */\nconst replayableOnCurrentWire = (\n protocol: string,\n command: StatewireClient.SessionCommand,\n current: ProducedRange\n): boolean =>\n command.produced !== undefined &&\n inRange(command.produced.wire.version, {\n version: current.wire.version,\n minVersion: STORED_STATEMENT_WIRE_FLOOR,\n }) &&\n storedCommandCompatible(\n protocol,\n { ...command, produced: { ...command.produced, wire: current.wire } },\n current\n );\n\n/**\n * statewire's `migrate` for a record whose queued commands were produced by\n * an earlier build. A command whose statement the current wire still replays\n * ({@link STORED_STATEMENT_WIRE_FLOOR}: an approval's `run/input` saved by a\n * previous bundled client, say) stays queued, re-stamped with the current\n * range, so it is delivered with its original seq. Every other incompatible\n * command leaves its lane's queue and is\n * retained as a `lost`/`session-lost` failed send re-stamped with the current\n * range. Client identity, lane clocks, compatible commands and existing failed\n * history are untouched, so the mount proceeds and the send-recovery sweep\n * (or the user, via the failed-send UI) re-dispatches the parked sends under\n * the negotiated format instead of the runtime throwing before it dials.\n *\n * Returns the record itself when nothing needed migrating, and the count of\n * parked commands otherwise.\n */\nexport function parkIncompatibleSessionCommands(\n record: StatewireClient.SessionRecord,\n current: ProducedRange,\n now: number = Date.now()\n): { record: StatewireClient.SessionRecord; parked: number; restamped: number } {\n let parked = 0;\n let restamped = 0;\n const lanes: Record<string, StatewireClient.SessionLane> = {};\n for (const [protocol, lane] of Object.entries(record.lanes)) {\n const kept: StatewireClient.SessionCommand[] = [];\n const failed: StatewireClient.FailedCommand[] = [];\n let laneRestamped = 0;\n for (const command of lane.commands) {\n if (storedCommandCompatible(protocol, command, current)) {\n kept.push(command);\n continue;\n }\n if (replayableOnCurrentWire(protocol, command, current)) {\n kept.push({ ...command, produced: current });\n laneRestamped += 1;\n continue;\n }\n failed.push({\n protocol,\n produced: current,\n command: command.method,\n params: command.params,\n ...(command.meta !== undefined && { meta: command.meta }),\n failure: { fate: \"lost\", cause: \"session-lost\" },\n ts: now,\n seq: command.seq,\n });\n }\n parked += failed.length;\n restamped += laneRestamped;\n lanes[protocol] =\n failed.length === 0 && laneRestamped === 0\n ? lane\n : {\n ...lane,\n commands: kept,\n ...((failed.length > 0 || lane.failed !== undefined) && {\n failed: [...(lane.failed ?? []), ...failed],\n }),\n };\n }\n return parked === 0 && restamped === 0\n ? { record, parked, restamped }\n : { record: { ...record, lanes }, parked, restamped };\n}\n\n/**\n * Whether `error` is the browser refusing a write for lack of room, under\n * every name the engines use — `QuotaExceededError` (Chromium, WebKit, current\n * Firefox), `NS_ERROR_DOM_QUOTA_REACHED` (older Firefox), the legacy\n * `DOMException` codes 22 (WebKit) and 1014 (Firefox) — or a plain error whose\n * message carries one of those (storage proxies and WebViews rewrap the\n * exception). Olympus's `isStorageQuotaError` recognises the same set; the two\n * stay in step.\n */\nexport function isStorageQuotaError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false;\n const { name, code, message } = error as {\n name?: unknown;\n code?: unknown;\n message?: unknown;\n };\n return (\n name === \"QuotaExceededError\" ||\n name === \"NS_ERROR_DOM_QUOTA_REACHED\" ||\n code === 22 ||\n code === 1014 ||\n (typeof message === \"string\" &&\n /exceeded the quota|quotaexceedederror|ns_error_dom_quota_reached/i.test(\n message\n ))\n );\n}\n\n/** The one quota shape statewire's retention sweep recognises. */\nfunction asStatewireQuotaError(error: unknown): Error {\n if (error instanceof Error && error.name === \"QuotaExceededError\")\n return error;\n const normalized = new Error(\n error instanceof Error ? error.message : \"storage quota exceeded\"\n );\n normalized.name = \"QuotaExceededError\";\n return normalized;\n}\n\n/**\n * Why `raw` is a stored record this build cannot read, or `undefined` when it\n * may be one. Mirrors the two decode failures statewire raises for a record it\n * cannot read — invalid JSON, and a `statewireStorageVersion` newer than the\n * ones this build's statewire decodes (a tab left open across a\n * statewire upgrade, reading the record a newer tab keeps) — because statewire\n * throws those out of the resource at mount instead of treating the record as\n * absent. A structurally invalid record of the right version still fails\n * inside statewire.\n */\nfunction unreadableRecord(raw: string): Error | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n return error instanceof Error\n ? error\n : new Error(\"stored session record is not JSON\");\n }\n if (typeof parsed !== \"object\" || parsed === null) {\n return new Error(\"stored session record is not an object\");\n }\n const version = (parsed as { statewireStorageVersion?: unknown })\n .statewireStorageVersion;\n if (version !== undefined && !READABLE_STORAGE_VERSIONS.has(version)) {\n return new Error(\n `stored session record uses storage version ${String(version)}`\n );\n }\n return undefined;\n}\n\ntype SyncBackend = {\n getItem: (key: string) => string | null;\n setItem: (key: string, value: string) => void;\n removeItem: (key: string) => void;\n getAllKeys: () => readonly string[];\n withUnused: (key: string, action: () => Promise<void>) => Promise<void>;\n};\n\n/**\n * The browser backend `@assistant-ui/react-statewire`'s `LocalStorageSession`\n * uses, reproduced here because that resource does not take a backend: raw\n * `localStorage`, with retention cleanup fenced by the same Web Locks so a\n * sweep never removes a record another tab is actively sharing.\n */\nfunction browserBackend({\n storage,\n locks,\n}: {\n storage: StorageLike;\n locks: LockManagerLike;\n}): SyncBackend {\n return {\n getItem: (key) => storage.getItem(key),\n setItem: (key, value) => storage.setItem(key, value),\n removeItem: (key) => storage.removeItem(key),\n getAllKeys: () =>\n Array.from({ length: storage.length }, (_, index) =>\n storage.key(index)\n ).filter((key): key is string => key !== null),\n withUnused: async (key, action) => {\n await locks.request(\n SESSION_ACTIVE_PREFIX + key,\n { ifAvailable: true },\n async (active) => {\n if (active === null) return;\n await locks.request(\n SESSION_LOCK_PREFIX + key.slice(SESSION_PREFIX.length),\n { ifAvailable: true },\n async (lock) => {\n if (lock === null) return;\n await action();\n }\n );\n }\n );\n },\n };\n}\n\n/**\n * Wraps a synchronous key-value backend so a failing origin degrades the\n * session to memory-only persistence instead of stopping the connection.\n *\n * statewire's session storage latches the first unrecognised write failure\n * and from then on rejects every send (`stopped/storage-error`, \"session\n * storage failed\" on the connection chip). It only recovers a\n * `QuotaExceededError` by that exact name — sweeping old session records and\n * retrying the write once — and latches again when the retry fails too. Here\n * the first quota failure per key is surfaced under that name so the sweep\n * runs; the retry that follows it and every other storage failure are absorbed\n * and reported through `onDegraded`, so chat keeps working.\n *\n * An absorbed write is kept in an in-memory overlay that `getItem` serves\n * first: statewire re-reads the record through `load()` on every shared-mode\n * transaction, so a stale persisted copy would otherwise win back its old\n * `nextSeq`, `clientId` and command journal. The overlay is per tab — another\n * tab sharing the thread still reads the last persisted copy, which is the\n * memory-only degradation this backend exists to allow. A later successful\n * write clears the overlay entry.\n *\n * A key whose read threw, or whose stored value this build cannot read (see\n * {@link unreadableRecord}), is served as absent and shielded: writes to it\n * stay in the overlay for good, so a fresh lane minted over an unreadable\n * record never overwrites what another tab or a newer build persisted.\n */\nexport function quotaTolerantBackend({\n inner,\n onDegraded,\n}: {\n inner: SyncBackend;\n onDegraded: (degradation: SessionStorageDegradation) => void;\n}): SyncBackend & KeyValueSessionStorage.Backend {\n // Keys whose write already surfaced a quota error to statewire: until a\n // write succeeds again, later failures on the key are absorbed instead of\n // surfaced, or every save would re-run statewire's sweep (which evicts\n // other threads' idle records) and the failure would latch on the retry.\n const quotaSurfaced = new Set<string>();\n // Absorbed writes, served ahead of the backend (see the function docs).\n const overlay = new Map<string, string>();\n // Keys served as absent and never written through (see the function docs).\n const shielded = new Set<string>();\n // statewire re-reads and re-decodes the record on every transaction; the\n // readability check is memoised on the raw string so it costs one string\n // comparison per read, not a second parse.\n const checked = new Map<\n string,\n { raw: string; verdict: Error | undefined }\n >();\n const readable = (key: string, raw: string): Error | undefined => {\n const previous = checked.get(key);\n if (previous !== undefined && previous.raw === raw) return previous.verdict;\n const verdict = unreadableRecord(raw);\n checked.set(key, { raw, verdict });\n return verdict;\n };\n return {\n getItem: (key) => {\n const shadowed = overlay.get(key);\n if (shadowed !== undefined) return shadowed;\n if (shielded.has(key)) return null;\n let raw: string | null;\n try {\n raw = inner.getItem(key);\n } catch (error) {\n shielded.add(key);\n onDegraded({ operation: \"getItem\", key, error });\n return null;\n }\n if (raw === null) return null;\n const unreadable = readable(key, raw);\n if (unreadable === undefined) return raw;\n shielded.add(key);\n onDegraded({ operation: \"record\", key, error: unreadable });\n return null;\n },\n setItem: (key, value) => {\n if (shielded.has(key)) {\n overlay.set(key, value);\n return;\n }\n try {\n inner.setItem(key, value);\n overlay.delete(key);\n quotaSurfaced.delete(key);\n } catch (error) {\n if (isStorageQuotaError(error) && !quotaSurfaced.has(key)) {\n quotaSurfaced.add(key);\n throw asStatewireQuotaError(error);\n }\n overlay.set(key, value);\n onDegraded({ operation: \"setItem\", key, error });\n }\n },\n removeItem: (key) => {\n overlay.delete(key);\n if (shielded.has(key)) return;\n try {\n inner.removeItem(key);\n } catch (error) {\n onDegraded({ operation: \"removeItem\", key, error });\n }\n },\n getAllKeys: () => {\n const keys = new Set<string>(overlay.keys());\n try {\n for (const key of inner.getAllKeys()) keys.add(key);\n } catch (error) {\n onDegraded({ operation: \"getAllKeys\", key: \"\", error });\n }\n return [...keys];\n },\n withUnused: async (key, action) => {\n try {\n await inner.withUnused(key, action);\n } catch (error) {\n onDegraded({ operation: \"withUnused\", key, error });\n }\n },\n };\n}\n\n/** A stored record's save stamp, or `undefined` when it carries none. */\nfunction savedAtOf(raw: string | null): number | undefined {\n if (raw === null) return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return undefined;\n }\n if (typeof parsed !== \"object\" || parsed === null) return undefined;\n const { savedAt, updatedAt } = parsed as {\n savedAt?: unknown;\n updatedAt?: unknown;\n };\n const stamp = savedAt ?? updatedAt;\n return typeof stamp === \"number\" && Number.isFinite(stamp)\n ? stamp\n : undefined;\n}\n\n/**\n * Removes session records last saved more than `maxAgeMs` ago, skipping the\n * keys mounted in this tab and, through `withUnused`, those another tab holds.\n *\n * statewire's own retention sweep only retires records with nothing queued and\n * nothing failed: a record still carrying an unconfirmed or failed send is\n * exempt from both its age and count bounds, so every thread left with one\n * kept its key forever. Past the TTL those sends are long out of send\n * recovery's auto-retry window, so the record goes the same way an empty one\n * does.\n */\nexport async function retireExpiredSessionRecords({\n backend,\n mounted,\n maxAgeMs,\n now = Date.now(),\n}: {\n backend: Pick<\n SyncBackend,\n \"getItem\" | \"removeItem\" | \"getAllKeys\" | \"withUnused\"\n >;\n mounted: ReadonlyMap<string, number>;\n maxAgeMs: number;\n now?: number;\n}): Promise<void> {\n for (const key of backend.getAllKeys()) {\n if (!key.startsWith(SESSION_PREFIX) || mounted.has(key)) continue;\n const savedAt = savedAtOf(backend.getItem(key));\n if (savedAt === undefined || now - savedAt <= maxAgeMs) continue;\n await backend.withUnused(key, async () => {\n if (mounted.has(key) || savedAtOf(backend.getItem(key)) !== savedAt)\n return;\n backend.removeItem(key);\n });\n }\n}\n\ntype DegradationListener = (degradation: SessionStorageDegradation) => void;\n\ntype SharedBackend = {\n backend: SyncBackend & KeyValueSessionStorage.Backend;\n listeners: Set<DegradationListener>;\n /** Storage keys of the sessions mounted in this tab, with mount counts. */\n mounted: Map<string, number>;\n};\n\n/**\n * One backend per storage object — per origin, in a browser — shared by every\n * session mounted in the tab, exactly as the upstream resource's module-level\n * backend is. statewire keys its in-tab \"active\" bookkeeping by backend\n * identity, so a mount's retention sweep only skips the records of other\n * mounts on the *same* backend; and the absorbed-write overlay has to outlive\n * a remount of the same thread (a thread switch and back) or the remount would\n * read the stale persisted copy. Degradations fan out to every mounted\n * session's reporter.\n */\nconst sharedBackends = new WeakMap<StorageLike, SharedBackend>();\n\nfunction sharedBackend({\n storage,\n locks,\n}: {\n storage: StorageLike;\n locks: LockManagerLike;\n}): SharedBackend {\n let shared = sharedBackends.get(storage);\n if (shared === undefined) {\n const listeners = new Set<DegradationListener>();\n shared = {\n listeners,\n mounted: new Map(),\n backend: quotaTolerantBackend({\n inner: browserBackend({ storage, locks }),\n onDegraded: (degradation) => {\n for (const listener of listeners) listener(degradation);\n },\n }),\n };\n sharedBackends.set(storage, shared);\n }\n return shared;\n}\n\n/**\n * Athena's browser session store: `@assistant-ui/react-statewire`'s\n * `LocalStorageSession` contract (per-thread key under the shared prefix,\n * cross-tab Web Lock, storage-event subscription, retention) on top of\n * {@link quotaTolerantBackend}, with Athena's protocol lane and retention\n * policy.\n */\nconst useQuotaSafeLocalStorageSession = ({\n threadId,\n key = (id) => id,\n ttl = 7 * DAY_MS,\n max = 50,\n onStorageDegraded,\n}: QuotaSafeLocalStorageSession.Options): StatewireClient.SessionStorage => {\n const storage = browserGlobals.localStorage;\n const locks = browserGlobals.navigator?.locks;\n if (!storage)\n throw new Error(\n \"statewire: QuotaSafeLocalStorageSession requires localStorage\"\n );\n if (!locks)\n throw new Error(\n \"statewire: QuotaSafeLocalStorageSession requires the Web Locks API (navigator.locks)\"\n );\n const sessionKey = key(threadId);\n const storageKey = SESSION_PREFIX + sessionKey;\n const lockName = SESSION_LOCK_PREFIX + sessionKey;\n\n // One mounted store serves one lane scope (one principal, one backend) for\n // its whole life: the upstream `LocalStorageSession` contract, whose\n // principal guard this is. The statewire session over the store keeps the\n // client id, lane clocks and journal it loaded, so a store moved to another\n // principal's lane would carry them there and send the previous principal's\n // undelivered commands under the next one's credential. A thread switch keeps\n // the scope and re-targets the store; a change of scope refuses, and the host\n // remounts the account's thread (`useDeepAgentRuntime` does). The previous\n // principal's record is left as it is.\n const mountedScope = useRef<DeepAgentSessionLaneScope>({\n threadId,\n laneKey: sessionKey,\n });\n if (!isSameSessionLaneScope({ scope: mountedScope.current, key })) {\n throw new Error(\n \"statewire: principal changed; remount the account's thread/session\"\n );\n }\n\n const latestOnDegraded = useRef(onStorageDegraded);\n latestOnDegraded.current = onStorageDegraded;\n const reportDegradation = useMemo(() => {\n const reported = new Set<string>();\n return (degradation: SessionStorageDegradation) => {\n const handler = latestOnDegraded.current;\n if (handler) {\n try {\n handler(degradation);\n } catch {\n // Reporting runs inside the session's recovery path and must never\n // become the failure it is reporting.\n }\n return;\n }\n const dedupeKey = `${degradation.operation}:${degradation.key}`;\n if (reported.has(dedupeKey)) return;\n reported.add(dedupeKey);\n console.warn(\n `[statewire] session storage degraded to memory only (${degradation.operation} ${degradation.key})`,\n degradation.error\n );\n };\n }, []);\n\n const shared = sharedBackend({ storage, locks });\n // Registered during render as well as in the effect: the read statewire\n // makes while mounting below happens before any effect runs, and tap may\n // clean an effect up and re-run it within one commit.\n shared.listeners.add(reportDegradation);\n useEffect(() => {\n shared.listeners.add(reportDegradation);\n return () => {\n shared.listeners.delete(reportDegradation);\n };\n }, [shared, reportDegradation]);\n\n useEffect(() => {\n const { mounted } = shared;\n mounted.set(storageKey, (mounted.get(storageKey) ?? 0) + 1);\n retireExpiredSessionRecords({\n backend: shared.backend,\n mounted,\n maxAgeMs: ttl,\n }).catch((error: unknown) =>\n reportDegradation({ operation: \"withUnused\", key: storageKey, error })\n );\n return () => {\n const count = (mounted.get(storageKey) ?? 1) - 1;\n if (count === 0) mounted.delete(storageKey);\n else mounted.set(storageKey, count);\n };\n }, [shared, storageKey, ttl, reportDegradation]);\n\n // Hold the record's shared \"active\" lock while mounted so another tab's\n // retention sweep skips it (the same fence the upstream resource holds).\n useEffect(() => {\n let release: (() => void) | undefined;\n let disposed = false;\n Promise.resolve(\n locks.request(\n SESSION_ACTIVE_PREFIX + storageKey,\n { mode: \"shared\" },\n () => {\n if (disposed) return;\n return new Promise<void>((resolve) => {\n release = resolve;\n });\n }\n )\n ).catch((error: unknown) =>\n reportDegradation({ operation: \"lock\", key: storageKey, error })\n );\n return () => {\n disposed = true;\n release?.();\n };\n }, [locks, storageKey, reportDegradation]);\n\n // The storage resource includes migrate in its identity. A fresh callback\n // on every render replaces the store and prevents hydration from settling.\n const migrate = useCallback<\n NonNullable<StatewireClient.SessionStorage[\"migrate\"]>\n >(\n (record, current) => {\n const migrated = parkIncompatibleSessionCommands(record, current);\n if (migrated.parked === 0) return migrated.record;\n reportDegradation({\n operation: \"migrate\",\n key: storageKey,\n error: new Error(\n `${migrated.parked} queued statewire command(s) predate the current protocol range; parked as failed sends`\n ),\n });\n return migrated.record;\n },\n [reportDegradation, storageKey]\n );\n\n const sessionStorage = useResource(\n KeyValueSessionStorage({\n backend: shared.backend,\n key: sessionKey,\n namespace: SESSION_PREFIX,\n protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,\n migrate,\n retention: { maxAgeMs: ttl, maxEntries: max },\n // A failure statewire raises itself (a structurally invalid stored\n // record) still stops the session; it is at least reported the same way.\n onError: (error) =>\n reportDegradation({ operation: \"session\", key: storageKey, error }),\n })\n );\n\n return useMemo(\n () => ({\n ...sessionStorage,\n lock: async <T>(fn: () => T | Promise<T>): Promise<T> => {\n let granted = false;\n try {\n return await locks.request(lockName, async () => {\n granted = true;\n return fn();\n });\n } catch (error) {\n if (granted) throw error;\n // The lock manager refused the request itself (a detached or\n // back/forward-cached document, a lockdown-mode origin): the\n // transaction runs unfenced rather than stopping the session.\n reportDegradation({ operation: \"lock\", key: storageKey, error });\n return fn();\n }\n },\n subscribe: (listener: () => void) => {\n const onStorage = (event: StorageEventLike) => {\n if (event.key === storageKey) listener();\n };\n browserGlobals.addEventListener?.(\"storage\", onStorage);\n return () => browserGlobals.removeEventListener?.(\"storage\", onStorage);\n },\n }),\n [sessionStorage, locks, storageKey, lockName, reportDegradation]\n );\n};\n\n/** Athena's browser session keys and retention policy. */\nexport const QuotaSafeLocalStorageSession = resource(\n useQuotaSafeLocalStorageSession\n);\n\nexport namespace QuotaSafeLocalStorageSession {\n export type Options = {\n threadId: string;\n /**\n * The lane's storage key for a thread, scoped by the principal (and the\n * sync host) the lane belongs to. It must keep naming the same principal's\n * lanes for the life of the mounted store: a change throws (\"principal\n * changed\"), as the upstream `LocalStorageSession` does, and the host\n * remounts the account's thread.\n */\n key?: (threadId: string) => string;\n ttl?: number;\n max?: number;\n /**\n * Called when a storage operation failed and the session carried on in\n * memory. Defaults to one `console.warn` per operation and key.\n */\n onStorageDegraded?: (degradation: SessionStorageDegradation) => void;\n };\n}\n"],"names":["failed","_a"],"mappings":";;;;;AAUA,MAAM,iBAAiB;AACvB,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAC9B,MAAM,SAAS,KAAK,KAAK,KAAK;AAE9B,MAAM,4BAAkD,oBAAI,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC;AA0CzE,MAAM,iBAAiB;AAQhB,SAAS,8BACd,YACoC;AACpC,QAAM,UAAU,eAAe;AAC/B,MAAI,CAAC,QAAS,Q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AAM,QAAQ,WAAY,UAAA;AAAA,QAChC;AACA,SAAAC,MAAA,eAAe,qBAAf,gBAAAA,IAAA,qBAAkC,WAAW;AAC7C,eAAO;;AAAM,kBAAAA,MAAA,eAAe,wBAAf,gBAAAA,IAAA,qBAAqC,WAAW;AAAA;AAAA,MAC/D;AAAA,IAAA;AAAA,IAEF,CAAC,gBAAgB,OAAO,YAAY,UAAU,iBAAiB;AAAA,EAAA;AAEnE;AAGO,MAAM,+BAA+B;AAAA,EAC1C;AACF;"}
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ function isSameSessionLaneScope({
4
+ scope,
5
+ key
6
+ }) {
7
+ return key(scope.threadId) === scope.laneKey;
8
+ }
9
+ const INITIAL_SESSION_LANE_EPOCH = { scope: null, epoch: 0 };
10
+ function nextSessionLaneEpoch({
11
+ previous,
12
+ threadId,
13
+ key
14
+ }) {
15
+ if (key === null) return previous;
16
+ if (previous.scope === null) {
17
+ return { scope: { threadId, laneKey: key(threadId) }, epoch: previous.epoch };
18
+ }
19
+ if (isSameSessionLaneScope({ scope: previous.scope, key })) return previous;
20
+ return { scope: { threadId, laneKey: key(threadId) }, epoch: previous.epoch + 1 };
21
+ }
22
+ exports.INITIAL_SESSION_LANE_EPOCH = INITIAL_SESSION_LANE_EPOCH;
23
+ exports.isSameSessionLaneScope = isSameSessionLaneScope;
24
+ exports.nextSessionLaneEpoch = nextSessionLaneEpoch;
25
+ //# sourceMappingURL=session-lane-scope.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-lane-scope.cjs","sources":["../../../../agent-runtime/src/session-lane-scope.ts"],"sourcesContent":["/**\n * The scope of a thread's durable command lane, as the host names it: the\n * host's `key` maps a thread id to the lane's storage key, and folds into it\n * whatever the lane belongs to (the signed-in principal, the sync host). A lane\n * is one principal's: it holds that principal's client id, lane clocks and the\n * commands still waiting for a durable verdict, and everything in it is sent\n * under whatever credential the transport holds when it next attaches.\n *\n * The scope is the key the host's `key` gave one thread. Probing that same\n * thread again tells a change of scope (another principal, another backend)\n * apart from a thread switch, which moves to another lane of the same scope.\n */\nexport type DeepAgentSessionLaneScope = {\n /** The thread the scope was taken on. */\n threadId: string;\n /** The lane key the host's `key` gave that thread. */\n laneKey: string;\n};\n\n/** The host's lane key: thread id to the lane's storage key. */\nexport type DeepAgentSessionLaneKey = (threadId: string) => string;\n\n/**\n * Whether `key` still names the lanes of `scope`: a thread switch keeps the\n * scope, a principal change does not.\n */\nexport function isSameSessionLaneScope({\n scope,\n key,\n}: {\n scope: DeepAgentSessionLaneScope;\n key: DeepAgentSessionLaneKey;\n}): boolean {\n return key(scope.threadId) === scope.laneKey;\n}\n\n/**\n * A mounted thread's lane epoch: the scope its current lane belongs to, and how\n * many times that scope changed under the mount. `scope` is `null` until the\n * first lane is known (a `pending` lane waits for its principal).\n */\nexport type DeepAgentSessionLaneEpoch = {\n scope: DeepAgentSessionLaneScope | null;\n epoch: number;\n};\n\nexport const INITIAL_SESSION_LANE_EPOCH: DeepAgentSessionLaneEpoch = { scope: null, epoch: 0 };\n\n/**\n * The lane epoch after a render with the host's current lane key (`null` while\n * the host names no lane: `pending`, process-local or a host session store).\n *\n * The first lane a mount learns sets the scope without starting a new epoch:\n * a `pending` lane that resolves to its principal is that principal's first\n * lane, not a change. A key that maps the scope's thread to another lane starts\n * the next epoch: the lane now belongs to another principal (or another\n * backend), so nothing of the previous lane — its client id, clocks, journal,\n * the state it rendered — may carry over. A gap with no lane in between (the\n * previous principal signed out, the next one still loading) does not hide\n * the change, and a key with the same scope (a token refresh, a fresh `key`\n * function for the same principal, a thread switch) changes nothing.\n *\n * Returns `previous` itself when nothing changed.\n */\nexport function nextSessionLaneEpoch({\n previous,\n threadId,\n key,\n}: {\n previous: DeepAgentSessionLaneEpoch;\n threadId: string;\n key: DeepAgentSessionLaneKey | null;\n}): DeepAgentSessionLaneEpoch {\n if (key === null) return previous;\n if (previous.scope === null) {\n return { scope: { threadId, laneKey: key(threadId) }, epoch: previous.epoch };\n }\n if (isSameSessionLaneScope({ scope: previous.scope, key })) return previous;\n return { scope: { threadId, laneKey: key(threadId) }, epoch: previous.epoch + 1 };\n}\n"],"names":[],"mappings":";;AA0BO,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AACF,GAGY;AACV,SAAO,IAAI,MAAM,QAAQ,MAAM,MAAM;AACvC;AAYO,MAAM,6BAAwD,EAAE,OAAO,MAAM,OAAO,EAAA;AAkBpF,SAAS,qBAAqB;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AACF,GAI8B;AAC5B,MAAI,QAAQ,KAAM,QAAO;AACzB,MAAI,SAAS,UAAU,MAAM;AAC3B,WAAO,EAAE,OAAO,EAAE,UAAU,SAAS,IAAI,QAAQ,KAAK,OAAO,SAAS,MAAA;AAAA,EACxE;AACA,MAAI,uBAAuB,EAAE,OAAO,SAAS,OAAO,IAAA,CAAK,EAAG,QAAO;AACnE,SAAO,EAAE,OAAO,EAAE,UAAU,SAAS,IAAI,QAAQ,EAAA,GAAK,OAAO,SAAS,QAAQ,EAAA;AAChF;;;;"}
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The scope of a thread's durable command lane, as the host names it: the
3
+ * host's `key` maps a thread id to the lane's storage key, and folds into it
4
+ * whatever the lane belongs to (the signed-in principal, the sync host). A lane
5
+ * is one principal's: it holds that principal's client id, lane clocks and the
6
+ * commands still waiting for a durable verdict, and everything in it is sent
7
+ * under whatever credential the transport holds when it next attaches.
8
+ *
9
+ * The scope is the key the host's `key` gave one thread. Probing that same
10
+ * thread again tells a change of scope (another principal, another backend)
11
+ * apart from a thread switch, which moves to another lane of the same scope.
12
+ */
13
+ export type DeepAgentSessionLaneScope = {
14
+ /** The thread the scope was taken on. */
15
+ threadId: string;
16
+ /** The lane key the host's `key` gave that thread. */
17
+ laneKey: string;
18
+ };
19
+ /** The host's lane key: thread id to the lane's storage key. */
20
+ export type DeepAgentSessionLaneKey = (threadId: string) => string;
21
+ /**
22
+ * Whether `key` still names the lanes of `scope`: a thread switch keeps the
23
+ * scope, a principal change does not.
24
+ */
25
+ export declare function isSameSessionLaneScope({ scope, key, }: {
26
+ scope: DeepAgentSessionLaneScope;
27
+ key: DeepAgentSessionLaneKey;
28
+ }): boolean;
29
+ /**
30
+ * A mounted thread's lane epoch: the scope its current lane belongs to, and how
31
+ * many times that scope changed under the mount. `scope` is `null` until the
32
+ * first lane is known (a `pending` lane waits for its principal).
33
+ */
34
+ export type DeepAgentSessionLaneEpoch = {
35
+ scope: DeepAgentSessionLaneScope | null;
36
+ epoch: number;
37
+ };
38
+ export declare const INITIAL_SESSION_LANE_EPOCH: DeepAgentSessionLaneEpoch;
39
+ /**
40
+ * The lane epoch after a render with the host's current lane key (`null` while
41
+ * the host names no lane: `pending`, process-local or a host session store).
42
+ *
43
+ * The first lane a mount learns sets the scope without starting a new epoch:
44
+ * a `pending` lane that resolves to its principal is that principal's first
45
+ * lane, not a change. A key that maps the scope's thread to another lane starts
46
+ * the next epoch: the lane now belongs to another principal (or another
47
+ * backend), so nothing of the previous lane — its client id, clocks, journal,
48
+ * the state it rendered — may carry over. A gap with no lane in between (the
49
+ * previous principal signed out, the next one still loading) does not hide
50
+ * the change, and a key with the same scope (a token refresh, a fresh `key`
51
+ * function for the same principal, a thread switch) changes nothing.
52
+ *
53
+ * Returns `previous` itself when nothing changed.
54
+ */
55
+ export declare function nextSessionLaneEpoch({ previous, threadId, key, }: {
56
+ previous: DeepAgentSessionLaneEpoch;
57
+ threadId: string;
58
+ key: DeepAgentSessionLaneKey | null;
59
+ }): DeepAgentSessionLaneEpoch;
@@ -0,0 +1,25 @@
1
+ function isSameSessionLaneScope({
2
+ scope,
3
+ key
4
+ }) {
5
+ return key(scope.threadId) === scope.laneKey;
6
+ }
7
+ const INITIAL_SESSION_LANE_EPOCH = { scope: null, epoch: 0 };
8
+ function nextSessionLaneEpoch({
9
+ previous,
10
+ threadId,
11
+ key
12
+ }) {
13
+ if (key === null) return previous;
14
+ if (previous.scope === null) {
15
+ return { scope: { threadId, laneKey: key(threadId) }, epoch: previous.epoch };
16
+ }
17
+ if (isSameSessionLaneScope({ scope: previous.scope, key })) return previous;
18
+ return { scope: { threadId, laneKey: key(threadId) }, epoch: previous.epoch + 1 };
19
+ }
20
+ export {
21
+ INITIAL_SESSION_LANE_EPOCH,
22
+ isSameSessionLaneScope,
23
+ nextSessionLaneEpoch
24
+ };
25
+ //# sourceMappingURL=session-lane-scope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-lane-scope.js","sources":["../../../../agent-runtime/src/session-lane-scope.ts"],"sourcesContent":["/**\n * The scope of a thread's durable command lane, as the host names it: the\n * host's `key` maps a thread id to the lane's storage key, and folds into it\n * whatever the lane belongs to (the signed-in principal, the sync host). A lane\n * is one principal's: it holds that principal's client id, lane clocks and the\n * commands still waiting for a durable verdict, and everything in it is sent\n * under whatever credential the transport holds when it next attaches.\n *\n * The scope is the key the host's `key` gave one thread. Probing that same\n * thread again tells a change of scope (another principal, another backend)\n * apart from a thread switch, which moves to another lane of the same scope.\n */\nexport type DeepAgentSessionLaneScope = {\n /** The thread the scope was taken on. */\n threadId: string;\n /** The lane key the host's `key` gave that thread. */\n laneKey: string;\n};\n\n/** The host's lane key: thread id to the lane's storage key. */\nexport type DeepAgentSessionLaneKey = (threadId: string) => string;\n\n/**\n * Whether `key` still names the lanes of `scope`: a thread switch keeps the\n * scope, a principal change does not.\n */\nexport function isSameSessionLaneScope({\n scope,\n key,\n}: {\n scope: DeepAgentSessionLaneScope;\n key: DeepAgentSessionLaneKey;\n}): boolean {\n return key(scope.threadId) === scope.laneKey;\n}\n\n/**\n * A mounted thread's lane epoch: the scope its current lane belongs to, and how\n * many times that scope changed under the mount. `scope` is `null` until the\n * first lane is known (a `pending` lane waits for its principal).\n */\nexport type DeepAgentSessionLaneEpoch = {\n scope: DeepAgentSessionLaneScope | null;\n epoch: number;\n};\n\nexport const INITIAL_SESSION_LANE_EPOCH: DeepAgentSessionLaneEpoch = { scope: null, epoch: 0 };\n\n/**\n * The lane epoch after a render with the host's current lane key (`null` while\n * the host names no lane: `pending`, process-local or a host session store).\n *\n * The first lane a mount learns sets the scope without starting a new epoch:\n * a `pending` lane that resolves to its principal is that principal's first\n * lane, not a change. A key that maps the scope's thread to another lane starts\n * the next epoch: the lane now belongs to another principal (or another\n * backend), so nothing of the previous lane — its client id, clocks, journal,\n * the state it rendered — may carry over. A gap with no lane in between (the\n * previous principal signed out, the next one still loading) does not hide\n * the change, and a key with the same scope (a token refresh, a fresh `key`\n * function for the same principal, a thread switch) changes nothing.\n *\n * Returns `previous` itself when nothing changed.\n */\nexport function nextSessionLaneEpoch({\n previous,\n threadId,\n key,\n}: {\n previous: DeepAgentSessionLaneEpoch;\n threadId: string;\n key: DeepAgentSessionLaneKey | null;\n}): DeepAgentSessionLaneEpoch {\n if (key === null) return previous;\n if (previous.scope === null) {\n return { scope: { threadId, laneKey: key(threadId) }, epoch: previous.epoch };\n }\n if (isSameSessionLaneScope({ scope: previous.scope, key })) return previous;\n return { scope: { threadId, laneKey: key(threadId) }, epoch: previous.epoch + 1 };\n}\n"],"names":[],"mappings":"AA0BO,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AACF,GAGY;AACV,SAAO,IAAI,MAAM,QAAQ,MAAM,MAAM;AACvC;AAYO,MAAM,6BAAwD,EAAE,OAAO,MAAM,OAAO,EAAA;AAkBpF,SAAS,qBAAqB;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AACF,GAI8B;AAC5B,MAAI,QAAQ,KAAM,QAAO;AACzB,MAAI,SAAS,UAAU,MAAM;AAC3B,WAAO,EAAE,OAAO,EAAE,UAAU,SAAS,IAAI,QAAQ,KAAK,OAAO,SAAS,MAAA;AAAA,EACxE;AACA,MAAI,uBAAuB,EAAE,OAAO,SAAS,OAAO,IAAA,CAAK,EAAG,QAAO;AACnE,SAAO,EAAE,OAAO,EAAE,UAAU,SAAS,IAAI,QAAQ,EAAA,GAAK,OAAO,SAAS,QAAQ,EAAA;AAChF;"}
@@ -184,8 +184,8 @@ function subagentTranscriptAttacher() {
184
184
  return attached;
185
185
  };
186
186
  }
187
- function createSubagentTranscriptConversionCache() {
188
- const thread = messages.createDeepAgentMessageConversionCache();
187
+ function createSubagentTranscriptConversionCache(options = {}) {
188
+ const thread = messages.createDeepAgentMessageConversionCache(options);
189
189
  const attach = subagentTranscriptAttacher();
190
190
  let previousRows = null;
191
191
  let previous = [];