@athenaintel/react 0.32.0 → 0.35.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 (134) hide show
  1. package/README.md +99 -9
  2. package/dist/agent-runtime/src/composer-markdown.cjs.map +1 -1
  3. package/dist/agent-runtime/src/composer-markdown.js.map +1 -1
  4. package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs +2 -3
  5. package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs.map +1 -1
  6. package/dist/agent-runtime/src/deep-agent-transport-recipe.js +3 -4
  7. package/dist/agent-runtime/src/deep-agent-transport-recipe.js.map +1 -1
  8. package/dist/agent-runtime/src/edit-command.cjs.map +1 -1
  9. package/dist/agent-runtime/src/edit-command.js.map +1 -1
  10. package/dist/agent-runtime/src/messages.cjs +57 -2
  11. package/dist/agent-runtime/src/messages.cjs.map +1 -1
  12. package/dist/agent-runtime/src/messages.js +57 -2
  13. package/dist/agent-runtime/src/messages.js.map +1 -1
  14. package/dist/agent-runtime/src/quota-safe-local-storage-session.cjs +24 -3
  15. package/dist/agent-runtime/src/quota-safe-local-storage-session.cjs.map +1 -1
  16. package/dist/agent-runtime/src/quota-safe-local-storage-session.js +24 -3
  17. package/dist/agent-runtime/src/quota-safe-local-storage-session.js.map +1 -1
  18. package/dist/agent-runtime/src/statewire-transport.cjs +4 -13
  19. package/dist/agent-runtime/src/statewire-transport.cjs.map +1 -1
  20. package/dist/agent-runtime/src/statewire-transport.js +5 -14
  21. package/dist/agent-runtime/src/statewire-transport.js.map +1 -1
  22. package/dist/agent-runtime/src/tool-metadata.cjs +1 -1
  23. package/dist/agent-runtime/src/tool-metadata.cjs.map +1 -1
  24. package/dist/agent-runtime/src/tool-metadata.js +1 -1
  25. package/dist/agent-runtime/src/tool-metadata.js.map +1 -1
  26. package/dist/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
  27. package/dist/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
  28. package/dist/assets/AthenaAssetEmbed.cjs +3 -1
  29. package/dist/assets/AthenaAssetEmbed.cjs.map +1 -1
  30. package/dist/assets/AthenaAssetEmbed.d.ts +7 -0
  31. package/dist/assets/AthenaAssetEmbed.js +4 -2
  32. package/dist/assets/AthenaAssetEmbed.js.map +1 -1
  33. package/dist/assets/use-asset-embed.cjs +71 -71
  34. package/dist/assets/use-asset-embed.cjs.map +1 -1
  35. package/dist/assets/use-asset-embed.d.ts +20 -7
  36. package/dist/assets/use-asset-embed.js +72 -72
  37. package/dist/assets/use-asset-embed.js.map +1 -1
  38. package/dist/catalog/agent-model-options.cjs +122 -0
  39. package/dist/catalog/agent-model-options.cjs.map +1 -0
  40. package/dist/catalog/agent-model-options.d.ts +115 -0
  41. package/dist/catalog/agent-model-options.js +122 -0
  42. package/dist/catalog/agent-model-options.js.map +1 -0
  43. package/dist/catalog/chat-pickers.cjs +184 -4
  44. package/dist/catalog/chat-pickers.cjs.map +1 -1
  45. package/dist/catalog/chat-pickers.d.ts +27 -3
  46. package/dist/catalog/chat-pickers.js +187 -7
  47. package/dist/catalog/chat-pickers.js.map +1 -1
  48. package/dist/catalog/runtime-catalog.cjs +117 -3
  49. package/dist/catalog/runtime-catalog.cjs.map +1 -1
  50. package/dist/catalog/runtime-catalog.d.ts +104 -0
  51. package/dist/catalog/runtime-catalog.js +119 -5
  52. package/dist/catalog/runtime-catalog.js.map +1 -1
  53. package/dist/chat/AthenaChat.cjs.map +1 -1
  54. package/dist/chat/AthenaChat.d.ts +8 -7
  55. package/dist/chat/AthenaChat.js.map +1 -1
  56. package/dist/chat/super-grouping/SuperGroupingCard.cjs +30 -3
  57. package/dist/chat/super-grouping/SuperGroupingCard.cjs.map +1 -1
  58. package/dist/chat/super-grouping/SuperGroupingCard.d.ts +12 -9
  59. package/dist/chat/super-grouping/SuperGroupingCard.js +31 -4
  60. package/dist/chat/super-grouping/SuperGroupingCard.js.map +1 -1
  61. package/dist/chat/super-grouping/SuperGroupingTranscript.cjs.map +1 -1
  62. package/dist/chat/super-grouping/SuperGroupingTranscript.d.ts +8 -8
  63. package/dist/chat/super-grouping/SuperGroupingTranscript.js.map +1 -1
  64. package/dist/chat/super-grouping/activity-timeline.cjs.map +1 -1
  65. package/dist/chat/super-grouping/activity-timeline.d.ts +4 -4
  66. package/dist/chat/super-grouping/activity-timeline.js.map +1 -1
  67. package/dist/chat/super-grouping/index.d.ts +6 -5
  68. package/dist/chat/super-grouping/toolkit-map.cjs +3 -1
  69. package/dist/chat/super-grouping/toolkit-map.cjs.map +1 -1
  70. package/dist/chat/super-grouping/toolkit-map.js +3 -1
  71. package/dist/chat/super-grouping/toolkit-map.js.map +1 -1
  72. package/dist/chat-ui/index.cjs +1 -0
  73. package/dist/chat-ui/index.cjs.map +1 -1
  74. package/dist/chat-ui/index.d.ts +1 -1
  75. package/dist/chat-ui/index.js +2 -1
  76. package/dist/chat-ui/mentions/suggestions/data/api-client.cjs +33 -2
  77. package/dist/chat-ui/mentions/suggestions/data/api-client.cjs.map +1 -1
  78. package/dist/chat-ui/mentions/suggestions/data/api-client.d.ts +14 -0
  79. package/dist/chat-ui/mentions/suggestions/data/api-client.js +33 -2
  80. package/dist/chat-ui/mentions/suggestions/data/api-client.js.map +1 -1
  81. package/dist/index.cjs +1 -0
  82. package/dist/index.cjs.map +1 -1
  83. package/dist/index.d.ts +3 -2
  84. package/dist/index.js +2 -1
  85. package/dist/lib/use-athena-rest-query.cjs +4 -0
  86. package/dist/lib/use-athena-rest-query.cjs.map +1 -1
  87. package/dist/lib/use-athena-rest-query.d.ts +6 -0
  88. package/dist/lib/use-athena-rest-query.js +4 -0
  89. package/dist/lib/use-athena-rest-query.js.map +1 -1
  90. package/dist/provider/AthenaProvider.cjs +29 -8
  91. package/dist/provider/AthenaProvider.cjs.map +1 -1
  92. package/dist/provider/AthenaProvider.d.ts +14 -4
  93. package/dist/provider/AthenaProvider.js +31 -10
  94. package/dist/provider/AthenaProvider.js.map +1 -1
  95. package/dist/provider/agent-selection-context.cjs +6 -0
  96. package/dist/provider/agent-selection-context.cjs.map +1 -0
  97. package/dist/provider/agent-selection-context.d.ts +14 -0
  98. package/dist/provider/agent-selection-context.js +6 -0
  99. package/dist/provider/agent-selection-context.js.map +1 -0
  100. package/dist/react/package.json.cjs +1 -1
  101. package/dist/react/package.json.js +1 -1
  102. package/dist/runtime/StatewireThreadConfigLaneSync.cjs +125 -0
  103. package/dist/runtime/StatewireThreadConfigLaneSync.cjs.map +1 -0
  104. package/dist/runtime/StatewireThreadConfigLaneSync.d.ts +54 -0
  105. package/dist/runtime/StatewireThreadConfigLaneSync.js +125 -0
  106. package/dist/runtime/StatewireThreadConfigLaneSync.js.map +1 -0
  107. package/dist/runtime/statewire-model-lane.cjs +0 -12
  108. package/dist/runtime/statewire-model-lane.cjs.map +1 -1
  109. package/dist/runtime/statewire-model-lane.d.ts +3 -1
  110. package/dist/runtime/statewire-model-lane.js +0 -12
  111. package/dist/runtime/statewire-model-lane.js.map +1 -1
  112. package/dist/runtime/statewire-server-lane-context.cjs.map +1 -1
  113. package/dist/runtime/statewire-server-lane-context.d.ts +2 -2
  114. package/dist/runtime/statewire-server-lane-context.js.map +1 -1
  115. package/dist/runtime/statewire-thread-config-lane.cjs +84 -0
  116. package/dist/runtime/statewire-thread-config-lane.cjs.map +1 -0
  117. package/dist/runtime/statewire-thread-config-lane.d.ts +94 -0
  118. package/dist/runtime/statewire-thread-config-lane.js +84 -0
  119. package/dist/runtime/statewire-thread-config-lane.js.map +1 -0
  120. package/dist/runtime/useAthenaStatewireRuntime.cjs +2 -2
  121. package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
  122. package/dist/runtime/useAthenaStatewireRuntime.js +2 -2
  123. package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
  124. package/dist/threads/use-athena-thread-model.cjs +11 -3
  125. package/dist/threads/use-athena-thread-model.cjs.map +1 -1
  126. package/dist/threads/use-athena-thread-model.d.ts +5 -0
  127. package/dist/threads/use-athena-thread-model.js +12 -4
  128. package/dist/threads/use-athena-thread-model.js.map +1 -1
  129. package/package.json +3 -3
  130. package/dist/runtime/StatewireModelLaneSync.cjs +0 -96
  131. package/dist/runtime/StatewireModelLaneSync.cjs.map +0 -1
  132. package/dist/runtime/StatewireModelLaneSync.d.ts +0 -45
  133. package/dist/runtime/StatewireModelLaneSync.js +0 -96
  134. package/dist/runtime/StatewireModelLaneSync.js.map +0 -1
@@ -50,17 +50,33 @@ const storedCommandCompatible = (protocol, command, current) => {
50
50
  const offer = current.protocols.find((p) => p.name === protocol);
51
51
  return produced !== void 0 && offer !== void 0 && inRange(produced.version, offer);
52
52
  };
53
+ const STORED_STATEMENT_WIRE_FLOOR = "2026-09-13";
54
+ const replayableOnCurrentWire = (protocol, command, current) => command.produced !== void 0 && inRange(command.produced.wire.version, {
55
+ version: current.wire.version,
56
+ minVersion: STORED_STATEMENT_WIRE_FLOOR
57
+ }) && storedCommandCompatible(
58
+ protocol,
59
+ { ...command, produced: { ...command.produced, wire: current.wire } },
60
+ current
61
+ );
53
62
  function parkIncompatibleSessionCommands(record, current, now = Date.now()) {
54
63
  let parked = 0;
64
+ let restamped = 0;
55
65
  const lanes = {};
56
66
  for (const [protocol, lane] of Object.entries(record.lanes)) {
57
67
  const kept = [];
58
68
  const failed = [];
69
+ let laneRestamped = 0;
59
70
  for (const command of lane.commands) {
60
71
  if (storedCommandCompatible(protocol, command, current)) {
61
72
  kept.push(command);
62
73
  continue;
63
74
  }
75
+ if (replayableOnCurrentWire(protocol, command, current)) {
76
+ kept.push({ ...command, produced: current });
77
+ laneRestamped += 1;
78
+ continue;
79
+ }
64
80
  failed.push({
65
81
  protocol,
66
82
  produced: current,
@@ -73,13 +89,16 @@ function parkIncompatibleSessionCommands(record, current, now = Date.now()) {
73
89
  });
74
90
  }
75
91
  parked += failed.length;
76
- lanes[protocol] = failed.length === 0 ? lane : {
92
+ restamped += laneRestamped;
93
+ lanes[protocol] = failed.length === 0 && laneRestamped === 0 ? lane : {
77
94
  ...lane,
78
95
  commands: kept,
79
- failed: [...lane.failed ?? [], ...failed]
96
+ ...(failed.length > 0 || lane.failed !== void 0) && {
97
+ failed: [...lane.failed ?? [], ...failed]
98
+ }
80
99
  };
81
100
  }
82
- return parked === 0 ? { record, parked } : { record: { ...record, lanes }, parked };
101
+ return parked === 0 && restamped === 0 ? { record, parked, restamped } : { record: { ...record, lanes }, parked, restamped };
83
102
  }
84
103
  function isStorageQuotaError(error) {
85
104
  if (typeof error !== "object" || error === null) return false;
@@ -370,6 +389,7 @@ const useQuotaSafeLocalStorageSession = ({
370
389
  const migrate = useCallback(
371
390
  (record, current) => {
372
391
  const migrated = parkIncompatibleSessionCommands(record, current);
392
+ if (migrated.parked === 0) return migrated.record;
373
393
  reportDegradation({
374
394
  operation: "migrate",
375
395
  key: storageKey,
@@ -430,6 +450,7 @@ const QuotaSafeLocalStorageSession = resource(
430
450
  );
431
451
  export {
432
452
  QuotaSafeLocalStorageSession,
453
+ STORED_STATEMENT_WIRE_FLOOR,
433
454
  isStorageQuotaError,
434
455
  parkIncompatibleSessionCommands,
435
456
  quotaTolerantBackend,
@@ -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 * statewire's `migrate` for a record whose queued commands were produced by\n * an earlier build: every incompatible 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 } {\n let parked = 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 for (const command of lane.commands) {\n if (storedCommandCompatible(protocol, command, current)) {\n kept.push(command);\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 lanes[protocol] =\n failed.length === 0\n ? lane\n : {\n ...lane,\n commands: kept,\n failed: [...(lane.failed ?? []), ...failed],\n };\n }\n return parked === 0\n ? { record, parked }\n : { record: { ...record, lanes }, parked };\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 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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hC,QAAM,iBAAiB;AAAA,IACrB,uBAAuB;AAAA,MACrB,SAAS,OAAO;AAAA,MAChB,KAAK;AAAA,MACL,WAAW;AAAA,MACX,UAAU;AAAA,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,SAAO;AAAA,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,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;"}
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;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yB;;AACnC,cAAM,YAAY,CAAC,UAA4B;AAC7C,cAAI,MAAM,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;"}
@@ -3,19 +3,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const statewire = require("statewire");
4
4
  const DEEP_AGENT_STATEWIRE_PROTOCOL = "athena";
5
5
  const DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION = "2026-09-13";
6
- function isQualifiedStatewireClient(client) {
7
- return "legacyContextWireVersion" in client && client.legacyContextWireVersion === DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION;
8
- }
9
- const QUALIFIED_STATEWIRE_CLIENT = isQualifiedStatewireClient(statewire.StatewireClient);
10
6
  const DEEP_AGENT_STATEWIRE_WIRE_VERSION = {
11
- version: "2026-09-30",
12
- ...QUALIFIED_STATEWIRE_CLIENT ? { minVersion: DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION } : {}
7
+ version: "2026-09-30"
13
8
  };
14
- function resolveStatewireTransportKind({
15
- sse,
16
- client = statewire.StatewireClient
17
- }) {
18
- return sse || !isQualifiedStatewireClient(client) ? "sse" : "websocket";
9
+ function resolveStatewireTransportKind({ sse }) {
10
+ return sse ? "sse" : "websocket";
19
11
  }
20
12
  const applicationProtocols = [
21
13
  {
@@ -23,7 +15,7 @@ const applicationProtocols = [
23
15
  version: DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION
24
16
  }
25
17
  ];
26
- const statewireTransport = (options, { sse = false, client } = {}) => resolveStatewireTransportKind({ sse, client }) === "sse" ? statewire.StatewireHttp({
18
+ const statewireTransport = (options, { sse = false } = {}) => resolveStatewireTransportKind({ sse }) === "sse" ? statewire.StatewireHttp({
27
19
  protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,
28
20
  wireVersion: DEEP_AGENT_STATEWIRE_WIRE_VERSION,
29
21
  applicationProtocols,
@@ -37,7 +29,6 @@ const statewireTransport = (options, { sse = false, client } = {}) => resolveSta
37
29
  exports.DEEP_AGENT_STATEWIRE_PROTOCOL = DEEP_AGENT_STATEWIRE_PROTOCOL;
38
30
  exports.DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION = DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION;
39
31
  exports.DEEP_AGENT_STATEWIRE_WIRE_VERSION = DEEP_AGENT_STATEWIRE_WIRE_VERSION;
40
- exports.isQualifiedStatewireClient = isQualifiedStatewireClient;
41
32
  exports.resolveStatewireTransportKind = resolveStatewireTransportKind;
42
33
  exports.statewireTransport = statewireTransport;
43
34
  //# sourceMappingURL=statewire-transport.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"statewire-transport.cjs","sources":["../../../../agent-runtime/src/statewire-transport.ts"],"sourcesContent":["import { type Statewire, StatewireClient, StatewireHttp, StatewireWebsocket } from 'statewire';\nimport type { DeepAgentStreamValues } from './types';\n\nexport type StatewireTransportOptions = StatewireClient.HttpOptions &\n StatewireClient.WebsocketOptions;\n\n/**\n * The application protocol the deep-agent transport stamps on every command.\n * The thread client must declare the same protocol: statewire's core applies\n * its optimistic folds only to commands of its own protocol, so a mismatch\n * leaves a send invisible until the server's frame lands.\n */\nexport const DEEP_AGENT_STATEWIRE_PROTOCOL = 'athena';\n\n/** Durable Athena commands keep their schema version across wire upgrades. */\nexport const DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION = '2026-09-13';\n\n/**\n * Whether a statewire client is the qualified one this repo installs\n * (`patches/statewire@0.20.0.patch`, which marks it with\n * `legacyContextWireVersion`). The same patch makes its WebSocket transport send\n * no empty client ping; a published upstream client (statewire 0.20.0) still\n * pings with `{}` frames, which Athena's Python 0.18/0.19 hosts reject on every\n * wire.\n */\nexport function isQualifiedStatewireClient(client: object): boolean {\n return (\n 'legacyContextWireVersion' in client &&\n client.legacyContextWireVersion === DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION\n );\n}\n\nconst QUALIFIED_STATEWIRE_CLIENT = isQualifiedStatewireClient(StatewireClient);\n\n/**\n * Only the qualified codec may advertise legacy context framing. Published\n * upstream peers stay on their native wire until the host installs that patch.\n */\nexport const DEEP_AGENT_STATEWIRE_WIRE_VERSION: NonNullable<\n StatewireTransportOptions['wireVersion']\n> = {\n version: '2026-09-30',\n ...(QUALIFIED_STATEWIRE_CLIENT ? { minVersion: DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION } : {}),\n};\n\nexport type StatewireTransportKind = 'sse' | 'websocket';\n\n/**\n * The transport a host gets over a statewire client: SSE when it asks for SSE,\n * and SSE when the client is not the qualified one. That client's WebSocket\n * transport would ping with empty frames the host rejects, closing the socket;\n * SSE sends no client ping. So public SDK installs, which take statewire from\n * npm without this repo's patch, chat over SSE, and bundled clients keep the\n * socket. Whatever instruments the transport must read this too, so it matches\n * the transport actually built.\n */\nexport function resolveStatewireTransportKind({\n sse,\n client = StatewireClient,\n}: {\n sse: boolean;\n /** The statewire client class whose qualification decides: the installed one unless given. */\n client?: object;\n}): StatewireTransportKind {\n return sse || !isQualifiedStatewireClient(client) ? 'sse' : 'websocket';\n}\n\nconst applicationProtocols = [\n {\n name: DEEP_AGENT_STATEWIRE_PROTOCOL,\n version: DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION,\n },\n];\n\n/**\n * Build the deep-agent statewire transport: WebSocket by default, SSE when the\n * host app's toggle asks for it or when the statewire client is not the\n * qualified one ({@link resolveStatewireTransportKind}). The toggle source is\n * host-specific (env var, extension flag, config store), so the caller resolves\n * it to a boolean.\n *\n * `TState` defaults to the deep-agent wire shape: the thread mounts that make\n * up nearly every caller get a typed state without naming it, and the other\n * mounts (the conversation index) name theirs.\n */\nexport const statewireTransport = <\n TState = DeepAgentStreamValues,\n TCommands extends Statewire.Commands = Statewire.Commands,\n>(\n options: StatewireTransportOptions,\n { sse = false, client }: { sse?: boolean; client?: object } = {}\n) =>\n resolveStatewireTransportKind({ sse, client }) === 'sse'\n ? StatewireHttp<TState, TCommands>({\n protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,\n wireVersion: DEEP_AGENT_STATEWIRE_WIRE_VERSION,\n applicationProtocols,\n ...options,\n })\n : StatewireWebsocket<TState, TCommands>({\n protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,\n wireVersion: DEEP_AGENT_STATEWIRE_WIRE_VERSION,\n applicationProtocols,\n ...options,\n });\n"],"names":["StatewireClient","StatewireHttp","StatewireWebsocket"],"mappings":";;;AAYO,MAAM,gCAAgC;AAGtC,MAAM,wCAAwC;AAU9C,SAAS,2BAA2B,QAAyB;AAClE,SACE,8BAA8B,UAC9B,OAAO,6BAA6B;AAExC;AAEA,MAAM,6BAA6B,2BAA2BA,yBAAe;AAMtE,MAAM,oCAET;AAAA,EACF,SAAS;AAAA,EACT,GAAI,6BAA6B,EAAE,YAAY,0CAA0C,CAAA;AAC3F;AAaO,SAAS,8BAA8B;AAAA,EAC5C;AAAA,EACA,SAASA,UAAAA;AACX,GAI2B;AACzB,SAAO,OAAO,CAAC,2BAA2B,MAAM,IAAI,QAAQ;AAC9D;AAEA,MAAM,uBAAuB;AAAA,EAC3B;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,EAAA;AAEb;AAaO,MAAM,qBAAqB,CAIhC,SACA,EAAE,MAAM,OAAO,OAAA,IAA+C,CAAA,MAE9D,8BAA8B,EAAE,KAAK,QAAQ,MAAM,QAC/CC,UAAAA,cAAiC;AAAA,EAC/B,UAAU;AAAA,EACV,aAAa;AAAA,EACb;AAAA,EACA,GAAG;AACL,CAAC,IACDC,UAAAA,mBAAsC;AAAA,EACpC,UAAU;AAAA,EACV,aAAa;AAAA,EACb;AAAA,EACA,GAAG;AACL,CAAC;;;;;;;"}
1
+ {"version":3,"file":"statewire-transport.cjs","sources":["../../../../agent-runtime/src/statewire-transport.ts"],"sourcesContent":["import { type Statewire, type StatewireClient, StatewireHttp, StatewireWebsocket } from 'statewire';\nimport type { DeepAgentStreamValues } from './types';\n\nexport type StatewireTransportOptions = StatewireClient.HttpOptions &\n StatewireClient.WebsocketOptions;\n\n/**\n * The application protocol the deep-agent transport stamps on every command.\n * The thread client must declare the same protocol: statewire's core applies\n * its optimistic folds only to commands of its own protocol, so a mismatch\n * leaves a send invisible until the server's frame lands.\n */\nexport const DEEP_AGENT_STATEWIRE_PROTOCOL = 'athena';\n\n/** Durable Athena commands keep their schema version across wire upgrades. */\nexport const DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION = '2026-09-13';\n\n/**\n * The wire contract every deep-agent transport offers. Athena's hosts (Python\n * statewire 0.20) speak 2026-09-30 natively, so no legacy context range is\n * advertised.\n */\nexport const DEEP_AGENT_STATEWIRE_WIRE_VERSION: NonNullable<\n StatewireTransportOptions['wireVersion']\n> = {\n version: '2026-09-30',\n};\n\nexport type StatewireTransportKind = 'sse' | 'websocket';\n\n/**\n * The transport a host gets: SSE when it asks for SSE, WebSocket otherwise.\n * Whatever instruments the transport must read this too, so it matches the\n * transport actually built.\n */\nexport function resolveStatewireTransportKind({ sse }: { sse: boolean }): StatewireTransportKind {\n return sse ? 'sse' : 'websocket';\n}\n\nconst applicationProtocols = [\n {\n name: DEEP_AGENT_STATEWIRE_PROTOCOL,\n version: DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION,\n },\n];\n\n/**\n * Build the deep-agent statewire transport: WebSocket by default, SSE when the\n * host app's toggle asks for it ({@link resolveStatewireTransportKind}). The\n * toggle source is host-specific (env var, extension flag, config store), so\n * the caller resolves it to a boolean.\n *\n * `TState` defaults to the deep-agent wire shape: the thread mounts that make\n * up nearly every caller get a typed state without naming it, and the other\n * mounts (the conversation index) name theirs.\n */\nexport const statewireTransport = <\n TState = DeepAgentStreamValues,\n TCommands extends Statewire.Commands = Statewire.Commands,\n>(\n options: StatewireTransportOptions,\n { sse = false }: { sse?: boolean } = {}\n) =>\n resolveStatewireTransportKind({ sse }) === 'sse'\n ? StatewireHttp<TState, TCommands>({\n protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,\n wireVersion: DEEP_AGENT_STATEWIRE_WIRE_VERSION,\n applicationProtocols,\n ...options,\n })\n : StatewireWebsocket<TState, TCommands>({\n protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,\n wireVersion: DEEP_AGENT_STATEWIRE_WIRE_VERSION,\n applicationProtocols,\n ...options,\n });\n"],"names":["StatewireHttp","StatewireWebsocket"],"mappings":";;;AAYO,MAAM,gCAAgC;AAGtC,MAAM,wCAAwC;AAO9C,MAAM,oCAET;AAAA,EACF,SAAS;AACX;AASO,SAAS,8BAA8B,EAAE,OAAiD;AAC/F,SAAO,MAAM,QAAQ;AACvB;AAEA,MAAM,uBAAuB;AAAA,EAC3B;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,EAAA;AAEb;AAYO,MAAM,qBAAqB,CAIhC,SACA,EAAE,MAAM,MAAA,IAA6B,OAErC,8BAA8B,EAAE,IAAA,CAAK,MAAM,QACvCA,UAAAA,cAAiC;AAAA,EAC/B,UAAU;AAAA,EACV,aAAa;AAAA,EACb;AAAA,EACA,GAAG;AACL,CAAC,IACDC,UAAAA,mBAAsC;AAAA,EACpC,UAAU;AAAA,EACV,aAAa;AAAA,EACb;AAAA,EACA,GAAG;AACL,CAAC;;;;;;"}
@@ -1,19 +1,11 @@
1
- import { StatewireHttp, StatewireWebsocket, StatewireClient } from "statewire";
1
+ import { StatewireHttp, StatewireWebsocket } from "statewire";
2
2
  const DEEP_AGENT_STATEWIRE_PROTOCOL = "athena";
3
3
  const DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION = "2026-09-13";
4
- function isQualifiedStatewireClient(client) {
5
- return "legacyContextWireVersion" in client && client.legacyContextWireVersion === DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION;
6
- }
7
- const QUALIFIED_STATEWIRE_CLIENT = isQualifiedStatewireClient(StatewireClient);
8
4
  const DEEP_AGENT_STATEWIRE_WIRE_VERSION = {
9
- version: "2026-09-30",
10
- ...QUALIFIED_STATEWIRE_CLIENT ? { minVersion: DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION } : {}
5
+ version: "2026-09-30"
11
6
  };
12
- function resolveStatewireTransportKind({
13
- sse,
14
- client = StatewireClient
15
- }) {
16
- return sse || !isQualifiedStatewireClient(client) ? "sse" : "websocket";
7
+ function resolveStatewireTransportKind({ sse }) {
8
+ return sse ? "sse" : "websocket";
17
9
  }
18
10
  const applicationProtocols = [
19
11
  {
@@ -21,7 +13,7 @@ const applicationProtocols = [
21
13
  version: DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION
22
14
  }
23
15
  ];
24
- const statewireTransport = (options, { sse = false, client } = {}) => resolveStatewireTransportKind({ sse, client }) === "sse" ? StatewireHttp({
16
+ const statewireTransport = (options, { sse = false } = {}) => resolveStatewireTransportKind({ sse }) === "sse" ? StatewireHttp({
25
17
  protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,
26
18
  wireVersion: DEEP_AGENT_STATEWIRE_WIRE_VERSION,
27
19
  applicationProtocols,
@@ -36,7 +28,6 @@ export {
36
28
  DEEP_AGENT_STATEWIRE_PROTOCOL,
37
29
  DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION,
38
30
  DEEP_AGENT_STATEWIRE_WIRE_VERSION,
39
- isQualifiedStatewireClient,
40
31
  resolveStatewireTransportKind,
41
32
  statewireTransport
42
33
  };
@@ -1 +1 @@
1
- {"version":3,"file":"statewire-transport.js","sources":["../../../../agent-runtime/src/statewire-transport.ts"],"sourcesContent":["import { type Statewire, StatewireClient, StatewireHttp, StatewireWebsocket } from 'statewire';\nimport type { DeepAgentStreamValues } from './types';\n\nexport type StatewireTransportOptions = StatewireClient.HttpOptions &\n StatewireClient.WebsocketOptions;\n\n/**\n * The application protocol the deep-agent transport stamps on every command.\n * The thread client must declare the same protocol: statewire's core applies\n * its optimistic folds only to commands of its own protocol, so a mismatch\n * leaves a send invisible until the server's frame lands.\n */\nexport const DEEP_AGENT_STATEWIRE_PROTOCOL = 'athena';\n\n/** Durable Athena commands keep their schema version across wire upgrades. */\nexport const DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION = '2026-09-13';\n\n/**\n * Whether a statewire client is the qualified one this repo installs\n * (`patches/statewire@0.20.0.patch`, which marks it with\n * `legacyContextWireVersion`). The same patch makes its WebSocket transport send\n * no empty client ping; a published upstream client (statewire 0.20.0) still\n * pings with `{}` frames, which Athena's Python 0.18/0.19 hosts reject on every\n * wire.\n */\nexport function isQualifiedStatewireClient(client: object): boolean {\n return (\n 'legacyContextWireVersion' in client &&\n client.legacyContextWireVersion === DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION\n );\n}\n\nconst QUALIFIED_STATEWIRE_CLIENT = isQualifiedStatewireClient(StatewireClient);\n\n/**\n * Only the qualified codec may advertise legacy context framing. Published\n * upstream peers stay on their native wire until the host installs that patch.\n */\nexport const DEEP_AGENT_STATEWIRE_WIRE_VERSION: NonNullable<\n StatewireTransportOptions['wireVersion']\n> = {\n version: '2026-09-30',\n ...(QUALIFIED_STATEWIRE_CLIENT ? { minVersion: DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION } : {}),\n};\n\nexport type StatewireTransportKind = 'sse' | 'websocket';\n\n/**\n * The transport a host gets over a statewire client: SSE when it asks for SSE,\n * and SSE when the client is not the qualified one. That client's WebSocket\n * transport would ping with empty frames the host rejects, closing the socket;\n * SSE sends no client ping. So public SDK installs, which take statewire from\n * npm without this repo's patch, chat over SSE, and bundled clients keep the\n * socket. Whatever instruments the transport must read this too, so it matches\n * the transport actually built.\n */\nexport function resolveStatewireTransportKind({\n sse,\n client = StatewireClient,\n}: {\n sse: boolean;\n /** The statewire client class whose qualification decides: the installed one unless given. */\n client?: object;\n}): StatewireTransportKind {\n return sse || !isQualifiedStatewireClient(client) ? 'sse' : 'websocket';\n}\n\nconst applicationProtocols = [\n {\n name: DEEP_AGENT_STATEWIRE_PROTOCOL,\n version: DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION,\n },\n];\n\n/**\n * Build the deep-agent statewire transport: WebSocket by default, SSE when the\n * host app's toggle asks for it or when the statewire client is not the\n * qualified one ({@link resolveStatewireTransportKind}). The toggle source is\n * host-specific (env var, extension flag, config store), so the caller resolves\n * it to a boolean.\n *\n * `TState` defaults to the deep-agent wire shape: the thread mounts that make\n * up nearly every caller get a typed state without naming it, and the other\n * mounts (the conversation index) name theirs.\n */\nexport const statewireTransport = <\n TState = DeepAgentStreamValues,\n TCommands extends Statewire.Commands = Statewire.Commands,\n>(\n options: StatewireTransportOptions,\n { sse = false, client }: { sse?: boolean; client?: object } = {}\n) =>\n resolveStatewireTransportKind({ sse, client }) === 'sse'\n ? StatewireHttp<TState, TCommands>({\n protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,\n wireVersion: DEEP_AGENT_STATEWIRE_WIRE_VERSION,\n applicationProtocols,\n ...options,\n })\n : StatewireWebsocket<TState, TCommands>({\n protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,\n wireVersion: DEEP_AGENT_STATEWIRE_WIRE_VERSION,\n applicationProtocols,\n ...options,\n });\n"],"names":[],"mappings":";AAYO,MAAM,gCAAgC;AAGtC,MAAM,wCAAwC;AAU9C,SAAS,2BAA2B,QAAyB;AAClE,SACE,8BAA8B,UAC9B,OAAO,6BAA6B;AAExC;AAEA,MAAM,6BAA6B,2BAA2B,eAAe;AAMtE,MAAM,oCAET;AAAA,EACF,SAAS;AAAA,EACT,GAAI,6BAA6B,EAAE,YAAY,0CAA0C,CAAA;AAC3F;AAaO,SAAS,8BAA8B;AAAA,EAC5C;AAAA,EACA,SAAS;AACX,GAI2B;AACzB,SAAO,OAAO,CAAC,2BAA2B,MAAM,IAAI,QAAQ;AAC9D;AAEA,MAAM,uBAAuB;AAAA,EAC3B;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,EAAA;AAEb;AAaO,MAAM,qBAAqB,CAIhC,SACA,EAAE,MAAM,OAAO,OAAA,IAA+C,CAAA,MAE9D,8BAA8B,EAAE,KAAK,QAAQ,MAAM,QAC/C,cAAiC;AAAA,EAC/B,UAAU;AAAA,EACV,aAAa;AAAA,EACb;AAAA,EACA,GAAG;AACL,CAAC,IACD,mBAAsC;AAAA,EACpC,UAAU;AAAA,EACV,aAAa;AAAA,EACb;AAAA,EACA,GAAG;AACL,CAAC;"}
1
+ {"version":3,"file":"statewire-transport.js","sources":["../../../../agent-runtime/src/statewire-transport.ts"],"sourcesContent":["import { type Statewire, type StatewireClient, StatewireHttp, StatewireWebsocket } from 'statewire';\nimport type { DeepAgentStreamValues } from './types';\n\nexport type StatewireTransportOptions = StatewireClient.HttpOptions &\n StatewireClient.WebsocketOptions;\n\n/**\n * The application protocol the deep-agent transport stamps on every command.\n * The thread client must declare the same protocol: statewire's core applies\n * its optimistic folds only to commands of its own protocol, so a mismatch\n * leaves a send invisible until the server's frame lands.\n */\nexport const DEEP_AGENT_STATEWIRE_PROTOCOL = 'athena';\n\n/** Durable Athena commands keep their schema version across wire upgrades. */\nexport const DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION = '2026-09-13';\n\n/**\n * The wire contract every deep-agent transport offers. Athena's hosts (Python\n * statewire 0.20) speak 2026-09-30 natively, so no legacy context range is\n * advertised.\n */\nexport const DEEP_AGENT_STATEWIRE_WIRE_VERSION: NonNullable<\n StatewireTransportOptions['wireVersion']\n> = {\n version: '2026-09-30',\n};\n\nexport type StatewireTransportKind = 'sse' | 'websocket';\n\n/**\n * The transport a host gets: SSE when it asks for SSE, WebSocket otherwise.\n * Whatever instruments the transport must read this too, so it matches the\n * transport actually built.\n */\nexport function resolveStatewireTransportKind({ sse }: { sse: boolean }): StatewireTransportKind {\n return sse ? 'sse' : 'websocket';\n}\n\nconst applicationProtocols = [\n {\n name: DEEP_AGENT_STATEWIRE_PROTOCOL,\n version: DEEP_AGENT_STATEWIRE_PROTOCOL_VERSION,\n },\n];\n\n/**\n * Build the deep-agent statewire transport: WebSocket by default, SSE when the\n * host app's toggle asks for it ({@link resolveStatewireTransportKind}). The\n * toggle source is host-specific (env var, extension flag, config store), so\n * the caller resolves it to a boolean.\n *\n * `TState` defaults to the deep-agent wire shape: the thread mounts that make\n * up nearly every caller get a typed state without naming it, and the other\n * mounts (the conversation index) name theirs.\n */\nexport const statewireTransport = <\n TState = DeepAgentStreamValues,\n TCommands extends Statewire.Commands = Statewire.Commands,\n>(\n options: StatewireTransportOptions,\n { sse = false }: { sse?: boolean } = {}\n) =>\n resolveStatewireTransportKind({ sse }) === 'sse'\n ? StatewireHttp<TState, TCommands>({\n protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,\n wireVersion: DEEP_AGENT_STATEWIRE_WIRE_VERSION,\n applicationProtocols,\n ...options,\n })\n : StatewireWebsocket<TState, TCommands>({\n protocol: DEEP_AGENT_STATEWIRE_PROTOCOL,\n wireVersion: DEEP_AGENT_STATEWIRE_WIRE_VERSION,\n applicationProtocols,\n ...options,\n });\n"],"names":[],"mappings":";AAYO,MAAM,gCAAgC;AAGtC,MAAM,wCAAwC;AAO9C,MAAM,oCAET;AAAA,EACF,SAAS;AACX;AASO,SAAS,8BAA8B,EAAE,OAAiD;AAC/F,SAAO,MAAM,QAAQ;AACvB;AAEA,MAAM,uBAAuB;AAAA,EAC3B;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,EAAA;AAEb;AAYO,MAAM,qBAAqB,CAIhC,SACA,EAAE,MAAM,MAAA,IAA6B,OAErC,8BAA8B,EAAE,IAAA,CAAK,MAAM,QACvC,cAAiC;AAAA,EAC/B,UAAU;AAAA,EACV,aAAa;AAAA,EACb;AAAA,EACA,GAAG;AACL,CAAC,IACD,mBAAsC;AAAA,EACpC,UAAU;AAAA,EACV,aAAa;AAAA,EACb;AAAA,EACA,GAAG;AACL,CAAC;"}
@@ -954,7 +954,7 @@ const TOOL_DISPLAY_META = {
954
954
  displayName: "Create Chart",
955
955
  activeLabel: "Creating chart",
956
956
  completedLabel: "Created chart",
957
- category: "Spreadsheet",
957
+ category: "Visualization",
958
958
  icon: "trending-up",
959
959
  emoji: "📈"
960
960
  },