@athenaintel/react 0.60.0 → 0.61.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 (137) hide show
  1. package/README.md +225 -2
  2. package/dist/agent-runtime/src/client-tool-bridge.cjs +20 -2
  3. package/dist/agent-runtime/src/client-tool-bridge.cjs.map +1 -1
  4. package/dist/agent-runtime/src/client-tool-bridge.d.ts +9 -4
  5. package/dist/agent-runtime/src/client-tool-bridge.js +20 -2
  6. package/dist/agent-runtime/src/client-tool-bridge.js.map +1 -1
  7. package/dist/agent-runtime/src/client-tools.cjs.map +1 -1
  8. package/dist/agent-runtime/src/client-tools.d.ts +9 -0
  9. package/dist/agent-runtime/src/client-tools.js.map +1 -1
  10. package/dist/agent-ui/AgentTarget.cjs +11 -0
  11. package/dist/agent-ui/AgentTarget.cjs.map +1 -0
  12. package/dist/agent-ui/AgentTarget.d.ts +17 -0
  13. package/dist/agent-ui/AgentTarget.js +11 -0
  14. package/dist/agent-ui/AgentTarget.js.map +1 -0
  15. package/dist/agent-ui/AgentUiLayer.cjs +387 -0
  16. package/dist/agent-ui/AgentUiLayer.cjs.map +1 -0
  17. package/dist/agent-ui/AgentUiLayer.d.ts +40 -0
  18. package/dist/agent-ui/AgentUiLayer.js +387 -0
  19. package/dist/agent-ui/AgentUiLayer.js.map +1 -0
  20. package/dist/agent-ui/contract.cjs +104 -0
  21. package/dist/agent-ui/contract.cjs.map +1 -0
  22. package/dist/agent-ui/contract.d.ts +113 -0
  23. package/dist/agent-ui/contract.js +104 -0
  24. package/dist/agent-ui/contract.js.map +1 -0
  25. package/dist/agent-ui/driver.cjs +335 -0
  26. package/dist/agent-ui/driver.cjs.map +1 -0
  27. package/dist/agent-ui/driver.d.ts +66 -0
  28. package/dist/agent-ui/driver.js +335 -0
  29. package/dist/agent-ui/driver.js.map +1 -0
  30. package/dist/agent-ui/index.cjs +33 -0
  31. package/dist/agent-ui/index.cjs.map +1 -0
  32. package/dist/agent-ui/index.d.ts +19 -0
  33. package/dist/agent-ui/index.js +33 -0
  34. package/dist/agent-ui/index.js.map +1 -0
  35. package/dist/agent-ui/pace.cjs +121 -0
  36. package/dist/agent-ui/pace.cjs.map +1 -0
  37. package/dist/agent-ui/pace.d.ts +66 -0
  38. package/dist/agent-ui/pace.js +121 -0
  39. package/dist/agent-ui/pace.js.map +1 -0
  40. package/dist/agent-ui/screen.cjs +471 -0
  41. package/dist/agent-ui/screen.cjs.map +1 -0
  42. package/dist/agent-ui/screen.d.ts +97 -0
  43. package/dist/agent-ui/screen.js +471 -0
  44. package/dist/agent-ui/screen.js.map +1 -0
  45. package/dist/agent-ui/secret-fields.cjs +50 -0
  46. package/dist/agent-ui/secret-fields.cjs.map +1 -0
  47. package/dist/agent-ui/secret-fields.d.ts +15 -0
  48. package/dist/agent-ui/secret-fields.js +50 -0
  49. package/dist/agent-ui/secret-fields.js.map +1 -0
  50. package/dist/agent-ui/stage.cjs +196 -0
  51. package/dist/agent-ui/stage.cjs.map +1 -0
  52. package/dist/agent-ui/stage.d.ts +110 -0
  53. package/dist/agent-ui/stage.js +196 -0
  54. package/dist/agent-ui/stage.js.map +1 -0
  55. package/dist/agent-ui/tools.cjs +448 -0
  56. package/dist/agent-ui/tools.cjs.map +1 -0
  57. package/dist/agent-ui/tools.d.ts +103 -0
  58. package/dist/agent-ui/tools.js +448 -0
  59. package/dist/agent-ui/tools.js.map +1 -0
  60. package/dist/agent-ui/use-agent-target.cjs +63 -0
  61. package/dist/agent-ui/use-agent-target.cjs.map +1 -0
  62. package/dist/agent-ui/use-agent-target.d.ts +27 -0
  63. package/dist/agent-ui/use-agent-target.js +63 -0
  64. package/dist/agent-ui/use-agent-target.js.map +1 -0
  65. package/dist/agent-ui/use-agent-ui.cjs +15 -0
  66. package/dist/agent-ui/use-agent-ui.cjs.map +1 -0
  67. package/dist/agent-ui/use-agent-ui.d.ts +24 -0
  68. package/dist/agent-ui/use-agent-ui.js +15 -0
  69. package/dist/agent-ui/use-agent-ui.js.map +1 -0
  70. package/dist/chat/AthenaChat.cjs +19 -4
  71. package/dist/chat/AthenaChat.cjs.map +1 -1
  72. package/dist/chat/AthenaChat.d.ts +13 -0
  73. package/dist/chat/AthenaChat.js +19 -4
  74. package/dist/chat/AthenaChat.js.map +1 -1
  75. package/dist/chat/StatewireClientToolBridge.cjs +74 -1
  76. package/dist/chat/StatewireClientToolBridge.cjs.map +1 -1
  77. package/dist/chat/StatewireClientToolBridge.d.ts +16 -1
  78. package/dist/chat/StatewireClientToolBridge.js +75 -2
  79. package/dist/chat/StatewireClientToolBridge.js.map +1 -1
  80. package/dist/chat/StatewireClientToolConsentCard.cjs +66 -0
  81. package/dist/chat/StatewireClientToolConsentCard.cjs.map +1 -0
  82. package/dist/chat/StatewireClientToolConsentCard.d.ts +25 -0
  83. package/dist/chat/StatewireClientToolConsentCard.js +66 -0
  84. package/dist/chat/StatewireClientToolConsentCard.js.map +1 -0
  85. package/dist/chat/chat-voice-controls.cjs +5 -2
  86. package/dist/chat/chat-voice-controls.cjs.map +1 -1
  87. package/dist/chat/chat-voice-controls.d.ts +6 -1
  88. package/dist/chat/chat-voice-controls.js +6 -3
  89. package/dist/chat/chat-voice-controls.js.map +1 -1
  90. package/dist/chat/client-tool-write-consent.cjs +122 -0
  91. package/dist/chat/client-tool-write-consent.cjs.map +1 -0
  92. package/dist/chat/client-tool-write-consent.d.ts +79 -0
  93. package/dist/chat/client-tool-write-consent.js +122 -0
  94. package/dist/chat/client-tool-write-consent.js.map +1 -0
  95. package/dist/chat/statewire-client-tools.cjs +30 -5
  96. package/dist/chat/statewire-client-tools.cjs.map +1 -1
  97. package/dist/chat/statewire-client-tools.d.ts +34 -2
  98. package/dist/chat/statewire-client-tools.js +30 -5
  99. package/dist/chat/statewire-client-tools.js.map +1 -1
  100. package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.cjs +13 -0
  101. package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.cjs.map +1 -1
  102. package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.d.ts +12 -0
  103. package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.js +13 -0
  104. package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.js.map +1 -1
  105. package/dist/chat-ui/mentions/suggestions/data/sources/index.cjs +2 -1
  106. package/dist/chat-ui/mentions/suggestions/data/sources/index.cjs.map +1 -1
  107. package/dist/chat-ui/mentions/suggestions/data/sources/index.js +3 -2
  108. package/dist/chat-ui/mentions/suggestions/data/sources/index.js.map +1 -1
  109. package/dist/chat-ui/mentions/use-asset-icon-app-url.cjs +2 -1
  110. package/dist/chat-ui/mentions/use-asset-icon-app-url.cjs.map +1 -1
  111. package/dist/chat-ui/mentions/use-asset-icon-app-url.d.ts +2 -1
  112. package/dist/chat-ui/mentions/use-asset-icon-app-url.js +2 -1
  113. package/dist/chat-ui/mentions/use-asset-icon-app-url.js.map +1 -1
  114. package/dist/chat-ui/messages/message-components.cjs +1 -1
  115. package/dist/chat-ui/messages/message-components.cjs.map +1 -1
  116. package/dist/chat-ui/messages/message-components.d.ts +2 -2
  117. package/dist/chat-ui/messages/message-components.js +1 -1
  118. package/dist/chat-ui/messages/message-components.js.map +1 -1
  119. package/dist/chat-ui/statewire.cjs +4 -0
  120. package/dist/chat-ui/statewire.cjs.map +1 -1
  121. package/dist/chat-ui/statewire.d.ts +2 -0
  122. package/dist/chat-ui/statewire.js +4 -0
  123. package/dist/chat-ui/statewire.js.map +1 -1
  124. package/dist/index.cjs +12 -0
  125. package/dist/index.cjs.map +1 -1
  126. package/dist/index.d.ts +12 -2
  127. package/dist/index.js +13 -1
  128. package/dist/index.js.map +1 -1
  129. package/dist/provider/AthenaProvider.cjs +59 -11
  130. package/dist/provider/AthenaProvider.cjs.map +1 -1
  131. package/dist/provider/AthenaProvider.d.ts +25 -1
  132. package/dist/provider/AthenaProvider.js +55 -7
  133. package/dist/provider/AthenaProvider.js.map +1 -1
  134. package/dist/react/package.json.cjs +1 -1
  135. package/dist/react/package.json.js +1 -1
  136. package/dist/styles.css +1 -1
  137. package/package.json +6 -1
package/README.md CHANGED
@@ -318,6 +318,13 @@ function AddMenu() {
318
318
  - `useAthenaComposerActions()` is `null` outside a composer slot. Both default
319
319
  to `true`: a host that sets neither sees no change.
320
320
 
321
+ ### A welcome of your own
322
+
323
+ `welcomeContent` replaces the greeting (`welcomeMessage`, `welcomeSubtext`) in
324
+ the empty thread with what the host renders, in the same place: Athena Desktop
325
+ draws one centred line there whose project name opens its project menu. Absent,
326
+ the greeting shows as before.
327
+
321
328
  ### Composer slash commands
322
329
 
323
330
  `AthenaChat`'s `composer.slashCommands` (and `TiptapComposer`'s
@@ -470,7 +477,9 @@ What the statewire transport wires up in `AthenaChat`:
470
477
  `@athenaintel/agent-runtime/typed-interrupt-kinds`'.
471
478
  - **Frontend tools:** tools in `frontendTools` with a local `execute` are
472
479
  declared to the backend as `client_tools` and executed by the mounted
473
- client-tool bridge, which resumes the run with each tool's result.
480
+ client-tool bridge, which resumes the run with each tool's result. One that
481
+ changes something can ask the person first, and every one can be stopped
482
+ (see [Frontend tools that ask first, and stop](#frontend-tools-that-ask-first-and-stop)).
474
483
  - **Mid-run sends and the queue:** a message sent while a run is active
475
484
  queues on the server. The queue panel above the composer
476
485
  (`StatewireQueuedMessages`) lists queued entries with remove, "Send now"
@@ -1147,6 +1156,198 @@ reference standard's kinds (`@athenaintel/references`):
1147
1156
  - **Not yet:** a table row (a lakehouse or Kronos row, by key) waits for a
1148
1157
  permission-checked row reader on the server (#54759).
1149
1158
 
1159
+ ## Frontend tools that ask first, and stop
1160
+
1161
+ A tool in `frontendTools` with an `execute` runs in the person's browser, as
1162
+ your app's own code, and by default it runs without asking. Two things let it
1163
+ behave like the rest of the chat.
1164
+
1165
+ **Ask before a tool that changes something.** Wrap the entry in
1166
+ `requiresWriteConsent`:
1167
+
1168
+ ```tsx
1169
+ import { AthenaProvider, requiresWriteConsent } from '@athenaintel/react';
1170
+
1171
+ const frontendTools = {
1172
+ get_note: { description: '…', parameters, execute: readNote },
1173
+ save_note: requiresWriteConsent(
1174
+ { description: '…', parameters, execute: saveNote },
1175
+ { summary: 'save a note on this record' },
1176
+ ),
1177
+ };
1178
+ ```
1179
+
1180
+ Before the tool's first call in a conversation runs, `AthenaChat` shows a card
1181
+ above the composer ("The agent wants to save a note on this record.") with
1182
+ **Allow** and **Decline**. Allow covers that tool for the rest of the
1183
+ conversation, and no other: a second marked tool asks for itself. Decline
1184
+ answers the agent with an error for the waiting calls, and a later call asks
1185
+ again. Calls to unmarked tools in the same turn still run. The answer is the
1186
+ person's own: nothing is remembered across a reload, and someone else signing
1187
+ in to the same mounted chat is asked for themselves. The mark also reaches
1188
+ Athena (`requires_write`), which then never answers the call for the person
1189
+ while their tab is away.
1190
+
1191
+ - The card names who is asking with the name you gave the agent
1192
+ (`agentUi={{ agentName }}`), else "The agent".
1193
+ - A host with its own chat mounts `StatewireClientToolConsentCard` (also in
1194
+ `@athenaintel/react/chat-ui/statewire`; its `agentName` prop overrides the
1195
+ name), or draws its own on `useClientToolWriteConsent()`:
1196
+ `{ request, allow, decline }`, `request` holding the waiting tools (`name`,
1197
+ `summary`) and that `agentName`, or `null`.
1198
+ - To ask in a dialog of your own instead, pass `confirmClientToolWrites` on
1199
+ `<AthenaProvider>`: it receives the same request plus a `signal`, and
1200
+ resolves `true` (allow those tools for the conversation) or `false`
1201
+ (decline). The signal
1202
+ aborts when the question has no call left to answer: close the dialog then
1203
+ (its promise need not settle, and a late answer is ignored). A confirmer
1204
+ that throws counts as a decline.
1205
+ - With no card mounted and no confirmer, the run waits and an
1206
+ `sdk.config.warning` says so.
1207
+
1208
+ The consent is asked in the browser. It is a courtesy to the person, never a
1209
+ permission boundary: your tool still calls your backend, or Athena's, as the
1210
+ signed-in person, and those checks decide what it may do.
1211
+
1212
+ **Stop when the run stops.** `execute` receives `abortSignal` in its second
1213
+ argument. It aborts when the call's run is stopped, the call is answered
1214
+ elsewhere, or the person opens another conversation; whatever the tool returns
1215
+ after that is discarded. A tool that takes visible time (a paced walkthrough,
1216
+ typing shown to the person) should watch it:
1217
+
1218
+ ```tsx
1219
+ execute: async (args, { abortSignal }) => {
1220
+ for (const step of steps) {
1221
+ if (abortSignal.aborted) return { stopped: true };
1222
+ await show(step);
1223
+ }
1224
+ return { shown: steps.length };
1225
+ },
1226
+ ```
1227
+
1228
+ ## Agent-drivable UI
1229
+
1230
+ An app can let its agent work on the screen the person has open: read what is
1231
+ there, point at something, walk the person through steps and, when asked,
1232
+ operate a control. Everything the agent does is shown on the page as it
1233
+ happens: it scrolls there, outlines the element, says what it is doing and
1234
+ types character by character, so the person can follow and learn. Ask "how do
1235
+ I filter this list?" and the agent shows it on the list itself.
1236
+
1237
+ The app decides what the agent can see and touch. Nothing is discovered: an
1238
+ element the app did not mark does not exist for the agent.
1239
+
1240
+ ```tsx
1241
+ import { AthenaProvider, agentRegion, agentTarget } from '@athenaintel/react';
1242
+
1243
+ <AthenaProvider agentUi={{ agentName: 'Jichard' }} appId={publicAppId}>
1244
+ <div {...agentRegion({ id: 'filters', label: 'Search and filters' })}>
1245
+ <input
1246
+ aria-label="Search investors"
1247
+ {...agentTarget({ id: 'search', description: 'Narrows the table as it is typed into.' })}
1248
+ />
1249
+ <button {...agentTarget({ id: 'filters.clear' })}>Clear filters</button>
1250
+ </div>
1251
+ {rows.map((row) => (
1252
+ <a key={row.id} href={row.href} {...agentTarget({ id: 'investor.open', key: row.id, label: row.name })}>
1253
+ {row.name}
1254
+ </a>
1255
+ ))}
1256
+ <AthenaChat />
1257
+ </AthenaProvider>
1258
+ ```
1259
+
1260
+ **Marking targets.** A target is a few `data-agent-*` attributes on the
1261
+ element itself, so any component that passes `data-*` props to its DOM node
1262
+ works, a plain web component included. `agentTarget(options)` writes them:
1263
+
1264
+ | Option | What it says |
1265
+ |--------|--------------|
1266
+ | `id` | What the agent names the target by: lowercase words joined by `.`, `-` or `_`, stable across renders (`filters.stage`). An id that is not one leaves the element unmarked and logs why. |
1267
+ | `key` | Which one, when several targets share an id (a row's key). The agent names it `investor.open[asset_1]`. |
1268
+ | `label` | What a person calls it. Defaults to the element's accessible name (`aria-label`, its `<label>`, its placeholder, its text). |
1269
+ | `description` | One line for the agent on what it is for. |
1270
+ | `actions` | What the agent may do to it: `click`, `type`, `select`, `toggle`, `clear`. Defaults to what the element allows by nature (a button is clicked, a text field typed into). `[]`: it may only be pointed at. |
1271
+ | `danger` | Acting on it changes or destroys something: the person confirms every time, and only the actions you list are allowed. |
1272
+ | `sensitive` | Its value is never read back to the agent and never typed by it, and its own text never names it. Password, one-time-code and card fields are treated this way without being marked. |
1273
+
1274
+ `agentRegion({ id, label })` names a part of the screen; its targets are
1275
+ grouped under it. For a control that clicks and keystrokes cannot drive (a
1276
+ custom select, a date picker), `useAgentTarget` takes `handlers` that replace
1277
+ the tool's own input, and `<AgentTarget>` marks the element inside it without
1278
+ touching that element's component:
1279
+
1280
+ ```tsx
1281
+ import { AgentTarget, useAgentTarget } from '@athenaintel/react';
1282
+
1283
+ const stage = useAgentTarget({
1284
+ id: 'filters.stage',
1285
+ label: 'Stage filter',
1286
+ handlers: { select: ({ option }) => setStage(option), options: () => STAGES, value: () => stage },
1287
+ });
1288
+ <StagePicker {...stage} />
1289
+
1290
+ <AgentTarget id="deal.save" label="Save deal">
1291
+ <Button onClick={save}>Save</Button>
1292
+ </AgentTarget>
1293
+ ```
1294
+
1295
+ **What the agent gets.** A fixed handful of tools that name targets by id,
1296
+ declared with every message like any `frontendTools` entry (so `appId` must
1297
+ be a recognised one):
1298
+
1299
+ | Tool | What it does | Changes something |
1300
+ |------|--------------|-------------------|
1301
+ | `read_screen` | Lists the targets on screen: id, role, label, value, state and allowed actions, grouped by region. `region` and `query` narrow it; a long table lists its first 25 rows and counts the rest. | no |
1302
+ | `point_at` | Scrolls to a target, outlines it and shows a note beside it for a few seconds (5 by default, 30 at most). `spotlight` dims the rest of the page. | no |
1303
+ | `show_steps` | A walkthrough of up to 12 steps, each a target and a sentence or two. It advances by itself; the person can pause, go back, skip ahead or close it. | no |
1304
+ | `act_on` | Operates one target: scrolls there, outlines it, moves a cursor onto it, then clicks, types, chooses an option, flips a switch or clears a field, through the element's own events, so your handlers, validation and undo run as they do for a person. | yes |
1305
+ | `go_to` | Opens one of the pages you list. Declared only when you pass `routes` and `navigate`. | no |
1306
+
1307
+ Your own tools stay the way to do a whole job (set these filters, open that
1308
+ record): they take one call and say what changed. The screen tools are for
1309
+ showing, and for the controls no tool of yours covers.
1310
+
1311
+ **Asking first, and stopping.** `act_on` is marked `requiresWriteConsent`, so
1312
+ the chat's consent card asks before the agent first acts in a conversation
1313
+ (see [Frontend tools that ask first, and stop](#frontend-tools-that-ask-first-and-stop)).
1314
+ A `danger` target is asked about on the page itself, every time. The agent
1315
+ acts on the one element it named, as that element is at the moment of acting:
1316
+ several rows sharing an id must be named by key, and an element that changed
1317
+ while the person read the question (another row, disabled, now a password
1318
+ field) is refused. What a keyboard could not do, it does not do: a read-only
1319
+ field is not typed into, nor a field past its `maxlength`. The person's own
1320
+ click, keypress or scroll stops an action in flight and holds back whatever
1321
+ else the agent asked for in the same turn, as does stopping the run; Escape
1322
+ closes whatever the agent is showing, and the keyboard goes back to where it
1323
+ was. With `prefers-reduced-motion` the same steps play without motion: scrolls
1324
+ jump, the cursor lands in place and typed text arrives whole.
1325
+
1326
+ **Options** (`agentUi={{ … }}`; `true` takes the defaults):
1327
+
1328
+ | Option | Default | Purpose |
1329
+ |--------|---------|---------|
1330
+ | `agentName` | `"The agent"` | Who the overlay says is acting, and who the chat's consent card says is asking. |
1331
+ | `speed` | `"normal"` | `"quick"` halves the waits; `"instant"` removes them. |
1332
+ | `allowActing` | `true` | `false` declares no `act_on`: the agent looks and points only (a read-only or "ask" mode). |
1333
+ | `actConsent` | `"host"` | `"overlay"` asks on the page (once per visit) instead of through the chat's consent card. |
1334
+ | `routes`, `navigate` | none | The pages `go_to` may open, and how to open one. |
1335
+ | `describePage` | none | Facts about the page on screen that `read_screen` passes on (its name, the record open). |
1336
+ | `classNames` | none | Restyle the overlay's pieces: `mark`, `caption`, `cursor`, `tour`, `question`. |
1337
+
1338
+ The overlay uses the SDK's own tokens (`primary`, `popover`, `border`), so it
1339
+ follows your theme. To wire the pieces yourself, or draw your own overlay, use
1340
+ `@athenaintel/react/agent-ui`: `useAgentUi(options)` returns `{ agentUi, tools }`
1341
+ (spread `tools` into `frontendTools`), `<AgentUiLayer agentUi={agentUi} />`
1342
+ draws the stage, and `agentUi.stage` (`getState`, `subscribe`) is everything
1343
+ the overlay shows, for a layer of your own.
1344
+
1345
+ **What it does not do.** It works inside one document: a target in an iframe
1346
+ is not seen. A row a virtualized list has not rendered is not on the screen.
1347
+ Nothing is discovered without a mark. None of it is a permission boundary:
1348
+ the tools run in the person's tab as the signed-in person, and your backend's
1349
+ checks, or Athena's, decide what any click may do.
1350
+
1150
1351
  ## Chat voice in AthenaChat
1151
1352
 
1152
1353
  `AthenaChat` includes realtime voice alongside dictation where the deployment
@@ -1180,6 +1381,12 @@ or a typed send. A host's own "Continue on…" control offers to send the
1180
1381
  conversation in voice mode only while `useChatVoiceEnabled({ enabled })` is
1181
1382
  true: the same workspace gate the composer's voice control uses.
1182
1383
 
1384
+ A host can fold voice into Send, as ChatGPT's composer does, with
1385
+ `composer={{ voiceInSend: true }}`: while the draft is empty and no run or call
1386
+ is live, one ink circle with a waveform starts the call; once the person types,
1387
+ Send takes its place. A call that is connecting or live keeps its own cancel or
1388
+ mute beside Send or Stop. Default `false`: voice and Send side by side.
1389
+
1183
1390
  Use `<AthenaChat voice={false} />` to omit realtime voice in a host that cannot
1184
1391
  support it, or `voice={{ model: 'gemini-3.8-live' }}` to request a host-offered
1185
1392
  voice model. A custom `livekit` adapter and `onDiagnostic` observer are accepted
@@ -1343,6 +1550,21 @@ Both use the same bearer / API key as session creation. The full recipe
1343
1550
  template skill `voice-session-guide.md`. `createAthenaVoiceSession` is also
1344
1551
  exported if you hold the bridge state yourself.
1345
1552
 
1553
+ ## What's new in 0.61.0
1554
+
1555
+ **An app can let its agent work on the screen the person has open.** With `agentUi` on `<AthenaProvider>`, the agent reads the controls your app marks (`agentTarget`, `useAgentTarget`, `<AgentTarget>`), points at one, walks the person through steps on the page, and operates a control once the person allows it. Everything it does is drawn on the page: an outline, a note, a cursor. Nothing unmarked exists for the agent, and password-like fields are never read or typed into. See [Agent-drivable UI](#agent-drivable-ui); the rest of the module is `@athenaintel/react/agent-ui`.
1556
+
1557
+ **A yes to one frontend tool is no longer a yes to another.** A tool marked `requiresWriteConsent` is asked about once per conversation, by itself. In 0.60.1, one Allow covered every marked tool for the rest of that conversation.
1558
+
1559
+ Also in this release:
1560
+ - The consent card names the agent when the app names it (`agentUi={{ agentName }}`), and the request a host's own consent UI receives carries that `agentName`.
1561
+ - `AthenaChat` takes `welcomeContent`, the host's own empty-state welcome in place of the greeting, and `composer={{ voiceInSend: true }}`, one button for voice and Send.
1562
+ - The composer's border darkens a step while it holds focus, in place of the focus ring.
1563
+
1564
+ ## What's new in 0.60.1
1565
+
1566
+ **The `@` menu's asset icons draw in apps a computer serves.** In those apps, Marathon's `/_athena/auth` mints `appUrl` as the app's own origin, which serves no Athena icons. So 0.60.0 asked the app itself for the SVGs, and every row fell back to its type's Lucide icon. The icons, mailbox logos, chips and drive cards now load from the deployment's frontend there (`staging-app.athenaintel.com`, `app.athenaintel.com`), the same frontend "Open in Athena" links go to (`assetIconAppUrl`, on `athenaLinkAppUrl`).
1567
+
1346
1568
  ## What's new in 0.60.0
1347
1569
 
1348
1570
  **The `@` menu draws each asset's type icon, as Olympus does.** Asset rows used to show the same generic file icon in every app that didn't serve Athena's icon files itself. Now each row shows the icon Olympus draws for its type, from Olympus's own type → icon table. An email whose mailbox is recorded on it (a Gmail or Outlook draft or message) shows that mailbox's logo. The SVGs load from the Athena web app the chat talks to (`<appUrl>/assets/icons/files/`), so there's nothing to configure. Each chat uses its own provider's app, and a host that ships its own copy still points at it with `configureAssetIconBasePath`. Where an SVG can't load (a strict `img-src` CSP, offline), the row shows the type's Lucide icon. The mention chips and the drive cards draw the same icons. A renderer of your own draws them with `assetTypeToThumb(type, { appUrl: useAssetIconAppUrl() })`. The search reads no metadata; a page with email rows reads theirs alone (`getAssetsByIds`).
@@ -2548,7 +2770,8 @@ app. `AthenaChat` renders them as chips with nothing to configure, and so do `Ch
2548
2770
 
2549
2771
  - **the asset type's icon**, the one Olympus draws for that type. The SVGs load from the Athena web
2550
2772
  app the chat talks to (`<appUrl>/assets/icons/files/`, public files, no credential), each chat
2551
- from its own provider's. A host that ships its own copy of the type glyphs points the chips at it
2773
+ from its own provider's; in an app a computer serves, where Marathon mints `appUrl` as the app's
2774
+ own origin, from the deployment's frontend, as "Open in Athena" links do. A host that ships its own copy of the type glyphs points the chips at it
2552
2775
  with `configureAssetIconBasePath({ basePath })`; brand logos (Gmail, Outlook, Power BI, Slack)
2553
2776
  still come from the app. Outside a provider, or where the SVG cannot load (a strict `img-src`
2554
2777
  CSP, offline), the chip draws a Lucide icon for the type. A renderer of your own draws the same
@@ -35,7 +35,8 @@ async function executeClientToolBatch(options) {
35
35
  writeDeclinedMessage = CLIENT_TOOL_WRITE_DECLINED_MESSAGE,
36
36
  missingToolMessage = defaultMissingClientToolMessage,
37
37
  onCallSettled,
38
- onExecutionStart
38
+ onExecutionStart,
39
+ signal
39
40
  } = options;
40
41
  const registry = new Map(tools.map((tool) => [tool.name, tool]));
41
42
  let writesDeclined = false;
@@ -70,7 +71,8 @@ async function executeClientToolBatch(options) {
70
71
  envelope = clientTools.clientToolSuccessEnvelope(
71
72
  jsonSafeClientToolResult(
72
73
  await tool.run(clientTools.clientToolCallArgs(call), {
73
- toolCallId: call.interrupt_id
74
+ toolCallId: call.interrupt_id,
75
+ ...signal ? { signal } : {}
74
76
  })
75
77
  )
76
78
  );
@@ -143,6 +145,15 @@ function useStatewireClientToolBridge(options) {
143
145
  }, [stopResumeReplay, tracker]);
144
146
  const liveRequestIdsRef = require$$0.useRef(/* @__PURE__ */ new Set());
145
147
  liveRequestIdsRef.current = new Set((inputRequests ?? []).map((request) => request.id));
148
+ const abortControllersRef = require$$0.useRef(/* @__PURE__ */ new Map());
149
+ require$$0.useEffect(() => {
150
+ const liveRequestIds = new Set((inputRequests ?? []).map((request) => request.id));
151
+ for (const [requestId, controller] of abortControllersRef.current) {
152
+ if (liveRequestIds.has(requestId)) continue;
153
+ abortControllersRef.current.delete(requestId);
154
+ controller.abort();
155
+ }
156
+ }, [inputRequests]);
146
157
  const startResumeReplay = require$$0.useCallback(
147
158
  (claim, requestId) => {
148
159
  if (!activeRef.current || resumeClaimsRef.current.has(claim)) return;
@@ -200,9 +211,12 @@ function useStatewireClientToolBridge(options) {
200
211
  onCallSettled,
201
212
  sendResume
202
213
  } = optionsRef.current;
214
+ const abortController = new AbortController();
215
+ abortControllersRef.current.set(request.id, abortController);
203
216
  const results = await executeClientToolBatch({
204
217
  calls: payload.context.requests,
205
218
  tools,
219
+ signal: abortController.signal,
206
220
  // Live while the request still exists AND this surface may answer it:
207
221
  // mounted, or already past the point of no return (handlers started —
208
222
  // the detached execution must finish and settle, never re-execute).
@@ -218,6 +232,10 @@ function useStatewireClientToolBridge(options) {
218
232
  ...writeDeclinedMessage !== void 0 ? { writeDeclinedMessage } : {},
219
233
  ...missingToolMessage ? { missingToolMessage } : {},
220
234
  ...onCallSettled ? { onCallSettled } : {}
235
+ }).finally(() => {
236
+ if (abortControllersRef.current.get(request.id) === abortController) {
237
+ abortControllersRef.current.delete(request.id);
238
+ }
221
239
  });
222
240
  if (results === null) {
223
241
  releaseClaim(claim);
@@ -1 +1 @@
1
- {"version":3,"file":"client-tool-bridge.cjs","sources":["../../../../agent-runtime/src/client-tool-bridge.ts"],"sourcesContent":["/**\n * The statewire client-tool bridge loop, shared by every surface that executes\n * frontend tool calls (Olympus, the React SDK, the Office add-in, mobile).\n *\n * Tools declared through `runConfig.custom.client_tools` have no backend\n * implementation: a call parks the run on an interrupt that arrives as a\n * statewire input request. A bridge with handlers for the whole batch claims\n * it (exactly-once per ownership domain), runs those handlers, and resumes\n * with per-call result envelopes. Other attached tabs leave it for the\n * executing surface; a thrown handler still returns an actionable error.\n *\n * Wire-adjacent correctness invariants this module owns, so they can never\n * drift apart per surface again:\n * - exactly-once claim per request, with un-claim on every path that did NOT\n * run any handler (abandoned before execution, consent dismissed, unmount\n * before the first handler) so a re-emitted request is executable instead\n * of stranding the run;\n * - once a batch has STARTED executing handlers, its claim is never released\n * by unmount: handlers cannot be cancelled, so releasing would let another\n * mount re-claim the re-emitted request and re-execute side effects that\n * already ran (double-executing a mutating tool). The completed wire-safe\n * result is cached and may be replayed across reconnects/remounts instead;\n * - liveness checks between awaits (the run can be stopped or answered\n * elsewhere while a handler runs) so a stale request is never resumed;\n * - per-call JSON wire-safety, so one unrepresentable handler result answers\n * that one call with an error instead of failing the whole batch.\n *\n * Like `interrupts.ts`, this is parameterized rather than self-wiring: the\n * host component reads `useStatewireRuns().inputRequests` and\n * `useStatewireSendCommand()` itself (both mockable per surface) and passes\n * them in, together with its ownership tracker and write-consent policy.\n */\n\nimport type { StatewireThread } from '@assistant-ui/react-statewire';\nimport { useCallback, useEffect, useRef } from 'react';\nimport {\n type ClientToolCallRequest,\n type ClientToolRequestTracker,\n type ClientToolResultEnvelope,\n clientToolCallArgs,\n clientToolErrorEnvelope,\n clientToolResultsResumeValue,\n clientToolSuccessEnvelope,\n isClientToolInterrupt,\n} from './client-tools';\n\n/** A locally executable tool, normalized across the per-surface tool shapes. */\nexport interface ClientToolBridgeTool {\n /** Snake_case tool id the model calls (e.g. `update_sheet_range`). */\n name: string;\n /** Mutating tools gate on the surface's write-consent flow (`confirmWrites`). */\n requiresWrite?: boolean;\n run: (\n args: Record<string, unknown>,\n context: { toolCallId: string },\n ) => Promise<unknown>;\n}\n\n/**\n * Batch write-consent outcome. `proceed` runs the write calls, `declined`\n * answers them with the declined message while reads still run, `abandoned`\n * releases the claim without resuming (the request died, or the consent UI was\n * dismissed by the run moving on). Grant persistence (a thread set, a stored\n * preference) is the surface's own policy, applied inside its callback.\n */\nexport type ClientToolWriteConsentDecision = 'proceed' | 'declined' | 'abandoned';\n\nexport interface ClientToolCallSettledEvent {\n toolName: string;\n status: 'success' | 'error' | 'declined';\n errorType?: string;\n}\n\n/** Default resume error for a write call the user declined. */\nexport const CLIENT_TOOL_WRITE_DECLINED_MESSAGE =\n 'The user declined this edit. Do not retry it; ask the user how to proceed.';\n\n/** Default resume error for a call naming a tool this surface does not have. */\nexport function defaultMissingClientToolMessage(toolName: string): string {\n return `This surface has no tool named '${toolName}'.`;\n}\n\n/** Statewire request ids are unique per run, but a thread scope keeps a\n * process-wide claim unambiguous when two conversations are open at once. */\nexport function clientToolClaimKey(threadId: string, requestId: string): string {\n return `${threadId}:${requestId}`;\n}\n\nconst CLIENT_TOOL_RESUME_RETRY_DELAYS_MS = [2_000, 5_000, 10_000, 15_000, 30_000];\nconst MAX_CLIENT_TOOL_RESUME_ATTEMPTS = 25;\n\nfunction clientToolResumeRetryDelayMs(attemptNumber: number): number {\n const index = Math.min(\n Math.max(attemptNumber - 1, 0),\n CLIENT_TOOL_RESUME_RETRY_DELAYS_MS.length - 1,\n );\n return CLIENT_TOOL_RESUME_RETRY_DELAYS_MS[index] ?? 30_000;\n}\n\n/**\n * A wire-safe copy of a handler's return value: handlers can return values\n * JSON cannot represent (DOM nodes, host objects, bigints), which must never\n * reach the transport. Throws for an unrepresentable value so the caller can\n * answer that one call with an error instead of stranding the whole batch.\n */\nexport function jsonSafeClientToolResult(value: unknown): unknown {\n const serialized = JSON.stringify(value);\n return serialized === undefined ? null : JSON.parse(serialized);\n}\n\n/** A parked, unanswered client-tool input request. */\nexport function isPendingClientToolRequest(\n request: StatewireThread.InputRequestState,\n): request is StatewireThread.CustomInputRequest {\n if (request.type !== 'interrupt' || 'response' in request) return false;\n return isClientToolInterrupt((request as { payload?: unknown }).payload);\n}\n\nexport interface ExecuteClientToolBatchOptions {\n calls: readonly ClientToolCallRequest[];\n tools: readonly ClientToolBridgeTool[];\n /** Whether the parked request still exists and this surface may answer it.\n * Checked before consent resolution, before every call, and before the\n * results are handed back for resume. */\n isLive: () => boolean;\n /** Batch write gate; absent means writes run without consent (surfaces that\n * only register read tools). Called once per batch, before any handler. */\n confirmWrites?: (batch: {\n writeToolNames: readonly string[];\n }) => Promise<ClientToolWriteConsentDecision>;\n writeDeclinedMessage?: string;\n missingToolMessage?: (toolName: string) => string;\n /** Per-call telemetry (the Office add-in's tool events). */\n onCallSettled?: (event: ClientToolCallSettledEvent) => void;\n /**\n * Called once, after the write-consent gate resolves and immediately before\n * the first handler runs — the point where side effects begin. There is no\n * await between this callback and the first handler invocation, so a caller\n * marking \"execution started\" here can never miss a handler that ran.\n */\n onExecutionStart?: () => void;\n}\n\n/**\n * Execute one batched client-tool park: consent, per-call execution with\n * wire-safe envelopes, liveness aborts. Returns the per-interrupt result map\n * to resume with, or `null` when the batch was abandoned (the request died,\n * consent was abandoned, or the surface went away) — the caller must release\n * its claim and must NOT resume.\n */\nexport async function executeClientToolBatch(\n options: ExecuteClientToolBatchOptions,\n): Promise<Record<string, ClientToolResultEnvelope> | null> {\n const {\n calls,\n tools,\n isLive,\n confirmWrites,\n writeDeclinedMessage = CLIENT_TOOL_WRITE_DECLINED_MESSAGE,\n missingToolMessage = defaultMissingClientToolMessage,\n onCallSettled,\n onExecutionStart,\n } = options;\n const registry = new Map(tools.map((tool) => [tool.name, tool]));\n\n // One consent covers the whole batch (and whatever scope the surface's\n // callback persists): writes are declined together while reads still run.\n let writesDeclined = false;\n const writeToolNames = calls\n .filter((call) => registry.get(call.tool_name)?.requiresWrite === true)\n .map((call) => call.tool_name);\n if (writeToolNames.length > 0 && confirmWrites) {\n const decision = await confirmWrites({ writeToolNames });\n if (decision === 'abandoned' || !isLive()) {\n // The run was stopped (or answered elsewhere) while consent was\n // pending: abort before any handler mutates the user's asset.\n return null;\n }\n writesDeclined = decision === 'declined';\n }\n\n onExecutionStart?.();\n\n const results: Record<string, ClientToolResultEnvelope> = {};\n for (const call of calls) {\n if (!isLive()) return null;\n const tool = registry.get(call.tool_name);\n let envelope: ClientToolResultEnvelope;\n let status: ClientToolCallSettledEvent['status'] = 'success';\n let errorType: string | undefined;\n if (!tool) {\n envelope = clientToolErrorEnvelope(missingToolMessage(call.tool_name));\n status = 'error';\n errorType = 'UnknownClientTool';\n } else if (tool.requiresWrite === true && writesDeclined) {\n envelope = clientToolErrorEnvelope(writeDeclinedMessage);\n status = 'declined';\n } else {\n try {\n envelope = clientToolSuccessEnvelope(\n jsonSafeClientToolResult(\n await tool.run(clientToolCallArgs(call), {\n toolCallId: call.interrupt_id,\n }),\n ),\n );\n } catch (error) {\n envelope = clientToolErrorEnvelope(error);\n status = 'error';\n errorType = error instanceof Error ? error.name : typeof error;\n }\n }\n results[call.interrupt_id] = envelope;\n onCallSettled?.({\n toolName: call.tool_name,\n status,\n ...(errorType !== undefined ? { errorType } : {}),\n });\n }\n\n // Abandoned mid-flight: resuming a dead request would error, and a\n // re-emitted one must be executable again.\n return isLive() ? results : null;\n}\n\nexport interface UseStatewireClientToolBridgeOptions {\n threadId: string;\n tools: readonly ClientToolBridgeTool[];\n /**\n * Ownership domain for parked-request claims. Pass a module-scoped tracker\n * to make ownership process-wide across every mount of the surface (two\n * mounted surfaces of one conversation execute each request exactly once),\n * or a per-mount tracker to scope ownership to one mounted bridge.\n */\n tracker: ClientToolRequestTracker;\n /** The surface's `useStatewireRuns().inputRequests` read. */\n inputRequests: readonly StatewireThread.InputRequestState[] | undefined;\n /** Dispatch the `run/input` resume on the surface's transport. The value is\n * already wire-safe (per-call JSON round-trip inside the batch engine). */\n /** Dispatch the answer and settle only once the Statewire host accepts or\n * rejects the command. The bridge deliberately keeps replaying while this\n * promise is pending: `run/input` removes the request optimistically before\n * the server has accepted the answer. */\n sendResume: (\n requestId: string,\n value: Record<string, unknown>,\n ) => PromiseLike<unknown>;\n /** Batch write gate, with the parked request's id so the surface can close\n * its consent UI the instant that request disappears. */\n confirmWrites?: (batch: {\n requestId: string;\n writeToolNames: readonly string[];\n }) => Promise<ClientToolWriteConsentDecision>;\n writeDeclinedMessage?: string;\n missingToolMessage?: (toolName: string) => string;\n onCallSettled?: (event: ClientToolCallSettledEvent) => void;\n /** Log prefix for resume-dispatch failures. */\n logLabel?: string;\n}\n\n/**\n * The claim lifecycle around {@link executeClientToolBatch}: claim the pending\n * request once per ownership domain, execute, resume — releasing the claim on\n * every path that ran no handler, so re-emitted requests recover.\n *\n * Unmount splits by whether side effects began:\n * - a claim whose batch has NOT started executing (claimed this tick, or\n * parked on write consent) is released, so another mount — or a remount —\n * can execute the re-emitted request instead of stranding the parked run;\n * - a claim whose batch HAS started stays held: handlers cannot be cancelled,\n * so releasing would let a sibling mount re-claim and re-execute a mutation\n * whose side effects already ran. The detached execution caches its result\n * and attempts one resume through its captured transport; a later mount can\n * replay the same result without repeating the side effect.\n */\nexport function useStatewireClientToolBridge(\n options: UseStatewireClientToolBridgeOptions,\n): void {\n const { threadId, tracker, inputRequests, logLabel = '[AthenaSDK]' } = options;\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const toolNames = new Set(options.tools.map((tool) => tool.name));\n const pendingRequest = inputRequests?.find((request) => {\n if (!isPendingClientToolRequest(request)) return false;\n const payload = (request as StatewireThread.CustomInputRequest).payload;\n if (!isClientToolInterrupt(payload)) return false;\n // Every attached tab sees the same park. An observer without these tools\n // must not claim it and race the executing surface with an unknown-tool\n // error (for example, Olympus watching an Excel conversation).\n // A cached result already belongs to this tracker and can be replayed\n // without loading its handlers again.\n return (\n tracker.getCachedResume(clientToolClaimKey(threadId, request.id)) !== undefined ||\n payload.context.requests.every((call) => toolNames.has(call.tool_name))\n );\n });\n\n // Claims this bridge holds but has not resumed, split by whether their\n // batch has begun running handlers. The ref Set instances are stable (only\n // their contents mutate), so the unmount cleanup sees every claim.\n const ownedClaimsRef = useRef<Set<string>>(new Set());\n const startedClaimsRef = useRef<Set<string>>(new Set());\n const resumeOwnerRef = useRef(Symbol('client-tool-resume-owner'));\n const resumeClaimsRef = useRef<Set<string>>(new Set());\n const resumeTimersRef = useRef<\n Map<string, { requestId: string; timer: ReturnType<typeof setTimeout> }>\n >(new Map());\n const activeRef = useRef(true);\n const releaseClaim = useCallback(\n (claim: string) => {\n // Release the shared tracker entry only while THIS mount still owns it.\n // A detached batch can settle after the unmount cleanup already released\n // (and disowned) its claim; by then the tracker entry may belong to\n // another mount that claimed, executed, and resumed — releasing it here\n // would let a stale re-emission of the same request execute again.\n const owned = ownedClaimsRef.current.delete(claim);\n startedClaimsRef.current.delete(claim);\n if (owned) tracker.release(claim);\n },\n [tracker],\n );\n const stopResumeReplay = useCallback(\n (claim: string) => {\n const timerEntry = resumeTimersRef.current.get(claim);\n if (timerEntry) clearTimeout(timerEntry.timer);\n resumeTimersRef.current.delete(claim);\n if (resumeClaimsRef.current.delete(claim)) {\n tracker.releaseResumeReplay(claim, resumeOwnerRef.current);\n }\n },\n [tracker],\n );\n useEffect(() => {\n activeRef.current = true;\n const ownedClaims = ownedClaimsRef.current;\n const startedClaims = startedClaimsRef.current;\n return () => {\n activeRef.current = false;\n for (const claim of Array.from(resumeClaimsRef.current)) {\n stopResumeReplay(claim);\n }\n for (const claim of ownedClaims) {\n // Started batches keep their claim — their detached execution settles\n // it (resume, or release on a failed dispatch). Releasing here would\n // double-execute the side effects that already ran.\n if (startedClaims.has(claim)) continue;\n ownedClaims.delete(claim);\n tracker.release(claim);\n }\n };\n }, [stopResumeReplay, tracker]);\n\n // Handlers (and consent) are async, so the run can be stopped or the request\n // answered elsewhere while we await. The live ids let us abandon an\n // unfinished local execution when its request is no longer present. Once a\n // result is cached, only command settlement may stop its replay: Statewire\n // removes submitted requests optimistically before the host accepts them.\n const liveRequestIdsRef = useRef<ReadonlySet<string>>(new Set());\n liveRequestIdsRef.current = new Set((inputRequests ?? []).map((request) => request.id));\n\n const startResumeReplay = useCallback(\n (claim: string, requestId: string) => {\n if (!activeRef.current || resumeClaimsRef.current.has(claim)) return;\n if (!tracker.claimResumeReplay(claim, resumeOwnerRef.current)) return;\n resumeClaimsRef.current.add(claim);\n\n const dispatch = (): void => {\n resumeTimersRef.current.delete(claim);\n if (!activeRef.current) {\n stopResumeReplay(claim);\n return;\n }\n const attempt = tracker.takeResumeAttempt(claim, {\n owner: resumeOwnerRef.current,\n maxAttempts: MAX_CLIENT_TOOL_RESUME_ATTEMPTS,\n });\n if (!attempt) {\n stopResumeReplay(claim);\n return;\n }\n\n try {\n const settled = optionsRef.current.sendResume(requestId, attempt.value);\n // A fulfilled command result is the authoritative acknowledgement:\n // the host accepted and applied the answer. The local input request\n // disappearing is NOT an acknowledgement because the Statewire\n // reducer does that optimistically as soon as the command is\n // submitted.\n void Promise.resolve(settled).then(\n () => {\n // Keep the execution claim, but discard the cached result once\n // the host accepts it. A stale pending-request render can no\n // longer replay the command or re-execute the local mutation.\n tracker.settleResume(claim);\n stopResumeReplay(claim);\n },\n (error) => {\n // A rejected attempt may have raced another still-pending\n // replay. Keep the bounded loop alive; any accepted sibling\n // stops it, while the global attempt cap prevents storms.\n console.error(`${logLabel} failed to resume client tool results:`, error);\n },\n );\n } catch (error) {\n // Keep the cached result and retry it. Re-executing a mutating local\n // handler would be unsafe; replaying its id-stamped result is safe.\n console.error(`${logLabel} failed to resume client tool results:`, error);\n }\n\n if (\n attempt.attemptNumber >= MAX_CLIENT_TOOL_RESUME_ATTEMPTS ||\n !activeRef.current ||\n !resumeClaimsRef.current.has(claim)\n ) {\n stopResumeReplay(claim);\n return;\n }\n const timer = setTimeout(dispatch, clientToolResumeRetryDelayMs(attempt.attemptNumber));\n resumeTimersRef.current.set(claim, { requestId, timer });\n };\n\n dispatch();\n },\n [logLabel, stopResumeReplay, tracker],\n );\n\n const executeRequest = useCallback(\n async (request: StatewireThread.CustomInputRequest) => {\n const payload = request.payload;\n if (!isClientToolInterrupt(payload)) return;\n const claim = clientToolClaimKey(threadId, request.id);\n const {\n tools,\n confirmWrites,\n writeDeclinedMessage,\n missingToolMessage,\n onCallSettled,\n sendResume,\n } = optionsRef.current;\n\n const results = await executeClientToolBatch({\n calls: payload.context.requests,\n tools,\n // Live while the request still exists AND this surface may answer it:\n // mounted, or already past the point of no return (handlers started —\n // the detached execution must finish and settle, never re-execute).\n // After unmount the request-id snapshot freezes at its last observed\n // state, which keeps a started batch's own request visible to it.\n isLive: () =>\n liveRequestIdsRef.current.has(request.id) &&\n (activeRef.current || startedClaimsRef.current.has(claim)),\n onExecutionStart: () => {\n startedClaimsRef.current.add(claim);\n },\n ...(confirmWrites\n ? {\n confirmWrites: ({ writeToolNames }: { writeToolNames: readonly string[] }) =>\n confirmWrites({ requestId: request.id, writeToolNames }),\n }\n : {}),\n ...(writeDeclinedMessage !== undefined ? { writeDeclinedMessage } : {}),\n ...(missingToolMessage ? { missingToolMessage } : {}),\n ...(onCallSettled ? { onCallSettled } : {}),\n });\n if (results === null) {\n releaseClaim(claim);\n return;\n }\n\n const resumeValue = clientToolResultsResumeValue(results);\n tracker.cacheResume(claim, resumeValue);\n // Execution is complete, but the exactly-once claim remains. A pending\n // re-emission must replay this cached value, never run the handlers again.\n ownedClaimsRef.current.delete(claim);\n startedClaimsRef.current.delete(claim);\n\n if (!activeRef.current) {\n // The handler crossed an unmount. Preserve the pre-existing best-effort\n // settle through its captured transport, but leave the cached result\n // available for a later mount if this dispatch is lost.\n if (tracker.claimResumeReplay(claim, resumeOwnerRef.current)) {\n const attempt = tracker.takeResumeAttempt(claim, {\n owner: resumeOwnerRef.current,\n maxAttempts: MAX_CLIENT_TOOL_RESUME_ATTEMPTS,\n });\n if (attempt) {\n try {\n void Promise.resolve(sendResume(request.id, attempt.value)).then(\n () => tracker.settleResume(claim),\n (error) => {\n console.error(`${logLabel} failed to resume client tool results:`, error);\n },\n );\n } catch (error) {\n console.error(`${logLabel} failed to resume client tool results:`, error);\n }\n }\n // Ownership only fences this best-effort dispatch; a future mount\n // may claim and replay the cached value if it did not settle.\n tracker.releaseResumeReplay(claim, resumeOwnerRef.current);\n }\n return;\n }\n\n startResumeReplay(claim, request.id);\n },\n [logLabel, releaseClaim, startResumeReplay, threadId, tracker],\n );\n\n useEffect(() => {\n if (!pendingRequest) return;\n const claim = clientToolClaimKey(threadId, pendingRequest.id);\n if (!tracker.claim(claim)) {\n // The local handler already ran. This is the reconnect/remount path:\n // replay its cached answer instead of double-executing the side effect.\n if (tracker.getCachedResume(claim)) {\n startResumeReplay(claim, pendingRequest.id);\n }\n return;\n }\n ownedClaimsRef.current.add(claim);\n void executeRequest(pendingRequest);\n }, [executeRequest, pendingRequest, startResumeReplay, threadId, tracker]);\n}\n"],"names":["isClientToolInterrupt","clientToolErrorEnvelope","clientToolSuccessEnvelope","clientToolCallArgs","useRef","useCallback","useEffect","clientToolResultsResumeValue"],"mappings":";;;;AA0EO,MAAM,qCACX;AAGK,SAAS,gCAAgC,UAA0B;AACxE,SAAO,mCAAmC,QAAQ;AACpD;AAIO,SAAS,mBAAmB,UAAkB,WAA2B;AAC9E,SAAO,GAAG,QAAQ,IAAI,SAAS;AACjC;AAEA,MAAM,qCAAqC,CAAC,KAAO,KAAO,KAAQ,MAAQ,GAAM;AAChF,MAAM,kCAAkC;AAExC,SAAS,6BAA6B,eAA+B;AACnE,QAAM,QAAQ,KAAK;AAAA,IACjB,KAAK,IAAI,gBAAgB,GAAG,CAAC;AAAA,IAC7B,mCAAmC,SAAS;AAAA,EAAA;AAE9C,SAAO,mCAAmC,KAAK,KAAK;AACtD;AAQO,SAAS,yBAAyB,OAAyB;AAChE,QAAM,aAAa,KAAK,UAAU,KAAK;AACvC,SAAO,eAAe,SAAY,OAAO,KAAK,MAAM,UAAU;AAChE;AAGO,SAAS,2BACd,SAC+C;AAC/C,MAAI,QAAQ,SAAS,eAAe,cAAc,QAAS,QAAO;AAClE,SAAOA,YAAAA,sBAAuB,QAAkC,OAAO;AACzE;AAkCA,eAAsB,uBACpB,SAC0D;AAC1D,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA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B,OAAO,QAAQ,EAAE;AAAA,IACrC;AAAA,IACA,CAAC,UAAU,cAAc,mBAAmB,UAAU,OAAO;AAAA,EAAA;AAG/DD,aAAAA,UAAU,MAAM;AACd,QAAI,CAAC,eAAgB;AACrB,UAAM,QAAQ,mBAAmB,UAAU,eAAe,EAAE;AAC5D,QAAI,CAAC,QAAQ,MAAM,KAAK,GAAG;AAGzB,UAAI,QAAQ,gBAAgB,KAAK,GAAG;AAClC,0BAAkB,OAAO,eAAe,EAAE;AAAA,MAC5C;AACA;AAAA,IACF;AACA,mBAAe,QAAQ,IAAI,KAAK;AAChC,SAAK,eAAe,cAAc;AAAA,EACpC,GAAG,CAAC,gBAAgB,gBAAgB,mBAAmB,UAAU,OAAO,CAAC;AAC3E;;;;;;;;"}
1
+ {"version":3,"file":"client-tool-bridge.cjs","sources":["../../../../agent-runtime/src/client-tool-bridge.ts"],"sourcesContent":["/**\n * The statewire client-tool bridge loop, shared by every surface that executes\n * frontend tool calls (Olympus, the React SDK, the Office add-in, mobile).\n *\n * Tools declared through `runConfig.custom.client_tools` have no backend\n * implementation: a call parks the run on an interrupt that arrives as a\n * statewire input request. A bridge with handlers for the whole batch claims\n * it (exactly-once per ownership domain), runs those handlers, and resumes\n * with per-call result envelopes. Other attached tabs leave it for the\n * executing surface; a thrown handler still returns an actionable error.\n *\n * Wire-adjacent correctness invariants this module owns, so they can never\n * drift apart per surface again:\n * - exactly-once claim per request, with un-claim on every path that did NOT\n * run any handler (abandoned before execution, consent dismissed, unmount\n * before the first handler) so a re-emitted request is executable instead\n * of stranding the run;\n * - once a batch has STARTED executing handlers, its claim is never released\n * by unmount: handlers cannot be cancelled, so releasing would let another\n * mount re-claim the re-emitted request and re-execute side effects that\n * already ran (double-executing a mutating tool). The completed wire-safe\n * result is cached and may be replayed across reconnects/remounts instead;\n * - liveness checks between awaits (the run can be stopped or answered\n * elsewhere while a handler runs) so a stale request is never resumed;\n * - per-call JSON wire-safety, so one unrepresentable handler result answers\n * that one call with an error instead of failing the whole batch.\n *\n * Like `interrupts.ts`, this is parameterized rather than self-wiring: the\n * host component reads `useStatewireRuns().inputRequests` and\n * `useStatewireSendCommand()` itself (both mockable per surface) and passes\n * them in, together with its ownership tracker and write-consent policy.\n */\n\nimport type { StatewireThread } from '@assistant-ui/react-statewire';\nimport { useCallback, useEffect, useRef } from 'react';\nimport {\n type ClientToolCallRequest,\n type ClientToolHandlerContext,\n type ClientToolRequestTracker,\n type ClientToolResultEnvelope,\n clientToolCallArgs,\n clientToolErrorEnvelope,\n clientToolResultsResumeValue,\n clientToolSuccessEnvelope,\n isClientToolInterrupt,\n} from './client-tools';\n\n/** A locally executable tool, normalized across the per-surface tool shapes. */\nexport interface ClientToolBridgeTool {\n /** Snake_case tool id the model calls (e.g. `update_sheet_range`). */\n name: string;\n /** Mutating tools gate on the surface's write-consent flow (`confirmWrites`). */\n requiresWrite?: boolean;\n run: (\n args: Record<string, unknown>,\n context: ClientToolHandlerContext,\n ) => Promise<unknown>;\n}\n\n/**\n * Batch write-consent outcome. `proceed` runs the write calls, `declined`\n * answers them with the declined message while reads still run, `abandoned`\n * releases the claim without resuming (the request died, or the consent UI was\n * dismissed by the run moving on). Grant persistence (a thread set, a stored\n * preference) is the surface's own policy, applied inside its callback.\n */\nexport type ClientToolWriteConsentDecision = 'proceed' | 'declined' | 'abandoned';\n\nexport interface ClientToolCallSettledEvent {\n toolName: string;\n status: 'success' | 'error' | 'declined';\n errorType?: string;\n}\n\n/** Default resume error for a write call the user declined. */\nexport const CLIENT_TOOL_WRITE_DECLINED_MESSAGE =\n 'The user declined this edit. Do not retry it; ask the user how to proceed.';\n\n/** Default resume error for a call naming a tool this surface does not have. */\nexport function defaultMissingClientToolMessage(toolName: string): string {\n return `This surface has no tool named '${toolName}'.`;\n}\n\n/** Statewire request ids are unique per run, but a thread scope keeps a\n * process-wide claim unambiguous when two conversations are open at once. */\nexport function clientToolClaimKey(threadId: string, requestId: string): string {\n return `${threadId}:${requestId}`;\n}\n\nconst CLIENT_TOOL_RESUME_RETRY_DELAYS_MS = [2_000, 5_000, 10_000, 15_000, 30_000];\nconst MAX_CLIENT_TOOL_RESUME_ATTEMPTS = 25;\n\nfunction clientToolResumeRetryDelayMs(attemptNumber: number): number {\n const index = Math.min(\n Math.max(attemptNumber - 1, 0),\n CLIENT_TOOL_RESUME_RETRY_DELAYS_MS.length - 1,\n );\n return CLIENT_TOOL_RESUME_RETRY_DELAYS_MS[index] ?? 30_000;\n}\n\n/**\n * A wire-safe copy of a handler's return value: handlers can return values\n * JSON cannot represent (DOM nodes, host objects, bigints), which must never\n * reach the transport. Throws for an unrepresentable value so the caller can\n * answer that one call with an error instead of stranding the whole batch.\n */\nexport function jsonSafeClientToolResult(value: unknown): unknown {\n const serialized = JSON.stringify(value);\n return serialized === undefined ? null : JSON.parse(serialized);\n}\n\n/** A parked, unanswered client-tool input request. */\nexport function isPendingClientToolRequest(\n request: StatewireThread.InputRequestState,\n): request is StatewireThread.CustomInputRequest {\n if (request.type !== 'interrupt' || 'response' in request) return false;\n return isClientToolInterrupt((request as { payload?: unknown }).payload);\n}\n\nexport interface ExecuteClientToolBatchOptions {\n calls: readonly ClientToolCallRequest[];\n tools: readonly ClientToolBridgeTool[];\n /** Whether the parked request still exists and this surface may answer it.\n * Checked before consent resolution, before every call, and before the\n * results are handed back for resume. */\n isLive: () => boolean;\n /** Batch write gate; absent means writes run without consent (surfaces that\n * only register read tools). Called once per batch, before any handler. */\n confirmWrites?: (batch: {\n writeToolNames: readonly string[];\n }) => Promise<ClientToolWriteConsentDecision>;\n writeDeclinedMessage?: string;\n missingToolMessage?: (toolName: string) => string;\n /** Per-call telemetry (the Office add-in's tool events). */\n onCallSettled?: (event: ClientToolCallSettledEvent) => void;\n /**\n * Called once, after the write-consent gate resolves and immediately before\n * the first handler runs — the point where side effects begin. There is no\n * await between this callback and the first handler invocation, so a caller\n * marking \"execution started\" here can never miss a handler that ran.\n */\n onExecutionStart?: () => void;\n /**\n * Handed to every handler of the batch (`context.signal`). The caller aborts\n * it when the parked request goes away mid-execution, so a handler that\n * takes visible time can stop; the batch's results are discarded either way\n * (`isLive` is what decides that).\n */\n signal?: AbortSignal;\n}\n\n/**\n * Execute one batched client-tool park: consent, per-call execution with\n * wire-safe envelopes, liveness aborts. Returns the per-interrupt result map\n * to resume with, or `null` when the batch was abandoned (the request died,\n * consent was abandoned, or the surface went away) — the caller must release\n * its claim and must NOT resume.\n */\nexport async function executeClientToolBatch(\n options: ExecuteClientToolBatchOptions,\n): Promise<Record<string, ClientToolResultEnvelope> | null> {\n const {\n calls,\n tools,\n isLive,\n confirmWrites,\n writeDeclinedMessage = CLIENT_TOOL_WRITE_DECLINED_MESSAGE,\n missingToolMessage = defaultMissingClientToolMessage,\n onCallSettled,\n onExecutionStart,\n signal,\n } = options;\n const registry = new Map(tools.map((tool) => [tool.name, tool]));\n\n // One consent covers the whole batch (and whatever scope the surface's\n // callback persists): writes are declined together while reads still run.\n let writesDeclined = false;\n const writeToolNames = calls\n .filter((call) => registry.get(call.tool_name)?.requiresWrite === true)\n .map((call) => call.tool_name);\n if (writeToolNames.length > 0 && confirmWrites) {\n const decision = await confirmWrites({ writeToolNames });\n if (decision === 'abandoned' || !isLive()) {\n // The run was stopped (or answered elsewhere) while consent was\n // pending: abort before any handler mutates the user's asset.\n return null;\n }\n writesDeclined = decision === 'declined';\n }\n\n onExecutionStart?.();\n\n const results: Record<string, ClientToolResultEnvelope> = {};\n for (const call of calls) {\n if (!isLive()) return null;\n const tool = registry.get(call.tool_name);\n let envelope: ClientToolResultEnvelope;\n let status: ClientToolCallSettledEvent['status'] = 'success';\n let errorType: string | undefined;\n if (!tool) {\n envelope = clientToolErrorEnvelope(missingToolMessage(call.tool_name));\n status = 'error';\n errorType = 'UnknownClientTool';\n } else if (tool.requiresWrite === true && writesDeclined) {\n envelope = clientToolErrorEnvelope(writeDeclinedMessage);\n status = 'declined';\n } else {\n try {\n envelope = clientToolSuccessEnvelope(\n jsonSafeClientToolResult(\n await tool.run(clientToolCallArgs(call), {\n toolCallId: call.interrupt_id,\n ...(signal ? { signal } : {}),\n }),\n ),\n );\n } catch (error) {\n envelope = clientToolErrorEnvelope(error);\n status = 'error';\n errorType = error instanceof Error ? error.name : typeof error;\n }\n }\n results[call.interrupt_id] = envelope;\n onCallSettled?.({\n toolName: call.tool_name,\n status,\n ...(errorType !== undefined ? { errorType } : {}),\n });\n }\n\n // Abandoned mid-flight: resuming a dead request would error, and a\n // re-emitted one must be executable again.\n return isLive() ? results : null;\n}\n\nexport interface UseStatewireClientToolBridgeOptions {\n threadId: string;\n tools: readonly ClientToolBridgeTool[];\n /**\n * Ownership domain for parked-request claims. Pass a module-scoped tracker\n * to make ownership process-wide across every mount of the surface (two\n * mounted surfaces of one conversation execute each request exactly once),\n * or a per-mount tracker to scope ownership to one mounted bridge.\n */\n tracker: ClientToolRequestTracker;\n /** The surface's `useStatewireRuns().inputRequests` read. */\n inputRequests: readonly StatewireThread.InputRequestState[] | undefined;\n /** Dispatch the `run/input` resume on the surface's transport. The value is\n * already wire-safe (per-call JSON round-trip inside the batch engine). */\n /** Dispatch the answer and settle only once the Statewire host accepts or\n * rejects the command. The bridge deliberately keeps replaying while this\n * promise is pending: `run/input` removes the request optimistically before\n * the server has accepted the answer. */\n sendResume: (\n requestId: string,\n value: Record<string, unknown>,\n ) => PromiseLike<unknown>;\n /** Batch write gate, with the parked request's id so the surface can close\n * its consent UI the instant that request disappears. */\n confirmWrites?: (batch: {\n requestId: string;\n writeToolNames: readonly string[];\n }) => Promise<ClientToolWriteConsentDecision>;\n writeDeclinedMessage?: string;\n missingToolMessage?: (toolName: string) => string;\n onCallSettled?: (event: ClientToolCallSettledEvent) => void;\n /** Log prefix for resume-dispatch failures. */\n logLabel?: string;\n}\n\n/**\n * The claim lifecycle around {@link executeClientToolBatch}: claim the pending\n * request once per ownership domain, execute, resume — releasing the claim on\n * every path that ran no handler, so re-emitted requests recover.\n *\n * Unmount splits by whether side effects began:\n * - a claim whose batch has NOT started executing (claimed this tick, or\n * parked on write consent) is released, so another mount — or a remount —\n * can execute the re-emitted request instead of stranding the parked run;\n * - a claim whose batch HAS started stays held: handlers cannot be cancelled,\n * so releasing would let a sibling mount re-claim and re-execute a mutation\n * whose side effects already ran. The detached execution caches its result\n * and attempts one resume through its captured transport; a later mount can\n * replay the same result without repeating the side effect.\n */\nexport function useStatewireClientToolBridge(\n options: UseStatewireClientToolBridgeOptions,\n): void {\n const { threadId, tracker, inputRequests, logLabel = '[AthenaSDK]' } = options;\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const toolNames = new Set(options.tools.map((tool) => tool.name));\n const pendingRequest = inputRequests?.find((request) => {\n if (!isPendingClientToolRequest(request)) return false;\n const payload = (request as StatewireThread.CustomInputRequest).payload;\n if (!isClientToolInterrupt(payload)) return false;\n // Every attached tab sees the same park. An observer without these tools\n // must not claim it and race the executing surface with an unknown-tool\n // error (for example, Olympus watching an Excel conversation).\n // A cached result already belongs to this tracker and can be replayed\n // without loading its handlers again.\n return (\n tracker.getCachedResume(clientToolClaimKey(threadId, request.id)) !== undefined ||\n payload.context.requests.every((call) => toolNames.has(call.tool_name))\n );\n });\n\n // Claims this bridge holds but has not resumed, split by whether their\n // batch has begun running handlers. The ref Set instances are stable (only\n // their contents mutate), so the unmount cleanup sees every claim.\n const ownedClaimsRef = useRef<Set<string>>(new Set());\n const startedClaimsRef = useRef<Set<string>>(new Set());\n const resumeOwnerRef = useRef(Symbol('client-tool-resume-owner'));\n const resumeClaimsRef = useRef<Set<string>>(new Set());\n const resumeTimersRef = useRef<\n Map<string, { requestId: string; timer: ReturnType<typeof setTimeout> }>\n >(new Map());\n const activeRef = useRef(true);\n const releaseClaim = useCallback(\n (claim: string) => {\n // Release the shared tracker entry only while THIS mount still owns it.\n // A detached batch can settle after the unmount cleanup already released\n // (and disowned) its claim; by then the tracker entry may belong to\n // another mount that claimed, executed, and resumed — releasing it here\n // would let a stale re-emission of the same request execute again.\n const owned = ownedClaimsRef.current.delete(claim);\n startedClaimsRef.current.delete(claim);\n if (owned) tracker.release(claim);\n },\n [tracker],\n );\n const stopResumeReplay = useCallback(\n (claim: string) => {\n const timerEntry = resumeTimersRef.current.get(claim);\n if (timerEntry) clearTimeout(timerEntry.timer);\n resumeTimersRef.current.delete(claim);\n if (resumeClaimsRef.current.delete(claim)) {\n tracker.releaseResumeReplay(claim, resumeOwnerRef.current);\n }\n },\n [tracker],\n );\n useEffect(() => {\n activeRef.current = true;\n const ownedClaims = ownedClaimsRef.current;\n const startedClaims = startedClaimsRef.current;\n return () => {\n activeRef.current = false;\n for (const claim of Array.from(resumeClaimsRef.current)) {\n stopResumeReplay(claim);\n }\n for (const claim of ownedClaims) {\n // Started batches keep their claim — their detached execution settles\n // it (resume, or release on a failed dispatch). Releasing here would\n // double-execute the side effects that already ran.\n if (startedClaims.has(claim)) continue;\n ownedClaims.delete(claim);\n tracker.release(claim);\n }\n };\n }, [stopResumeReplay, tracker]);\n\n // Handlers (and consent) are async, so the run can be stopped or the request\n // answered elsewhere while we await. The live ids let us abandon an\n // unfinished local execution when its request is no longer present. Once a\n // result is cached, only command settlement may stop its replay: Statewire\n // removes submitted requests optimistically before the host accepts them.\n const liveRequestIdsRef = useRef<ReadonlySet<string>>(new Set());\n liveRequestIdsRef.current = new Set((inputRequests ?? []).map((request) => request.id));\n\n // One abort signal per executing request, handed to its handlers. It fires\n // when the request leaves the mounted surface's view (stop, an answer from\n // elsewhere, another conversation opened): the results would be discarded,\n // so a handler that is still showing the person something can stop. It does\n // not fire on unmount: a started batch finishes and settles (see above).\n const abortControllersRef = useRef<Map<string, AbortController>>(new Map());\n useEffect(() => {\n const liveRequestIds = new Set((inputRequests ?? []).map((request) => request.id));\n for (const [requestId, controller] of abortControllersRef.current) {\n if (liveRequestIds.has(requestId)) continue;\n abortControllersRef.current.delete(requestId);\n controller.abort();\n }\n }, [inputRequests]);\n\n const startResumeReplay = useCallback(\n (claim: string, requestId: string) => {\n if (!activeRef.current || resumeClaimsRef.current.has(claim)) return;\n if (!tracker.claimResumeReplay(claim, resumeOwnerRef.current)) return;\n resumeClaimsRef.current.add(claim);\n\n const dispatch = (): void => {\n resumeTimersRef.current.delete(claim);\n if (!activeRef.current) {\n stopResumeReplay(claim);\n return;\n }\n const attempt = tracker.takeResumeAttempt(claim, {\n owner: resumeOwnerRef.current,\n maxAttempts: MAX_CLIENT_TOOL_RESUME_ATTEMPTS,\n });\n if (!attempt) {\n stopResumeReplay(claim);\n return;\n }\n\n try {\n const settled = optionsRef.current.sendResume(requestId, attempt.value);\n // A fulfilled command result is the authoritative acknowledgement:\n // the host accepted and applied the answer. The local input request\n // disappearing is NOT an acknowledgement because the Statewire\n // reducer does that optimistically as soon as the command is\n // submitted.\n void Promise.resolve(settled).then(\n () => {\n // Keep the execution claim, but discard the cached result once\n // the host accepts it. A stale pending-request render can no\n // longer replay the command or re-execute the local mutation.\n tracker.settleResume(claim);\n stopResumeReplay(claim);\n },\n (error) => {\n // A rejected attempt may have raced another still-pending\n // replay. Keep the bounded loop alive; any accepted sibling\n // stops it, while the global attempt cap prevents storms.\n console.error(`${logLabel} failed to resume client tool results:`, error);\n },\n );\n } catch (error) {\n // Keep the cached result and retry it. Re-executing a mutating local\n // handler would be unsafe; replaying its id-stamped result is safe.\n console.error(`${logLabel} failed to resume client tool results:`, error);\n }\n\n if (\n attempt.attemptNumber >= MAX_CLIENT_TOOL_RESUME_ATTEMPTS ||\n !activeRef.current ||\n !resumeClaimsRef.current.has(claim)\n ) {\n stopResumeReplay(claim);\n return;\n }\n const timer = setTimeout(dispatch, clientToolResumeRetryDelayMs(attempt.attemptNumber));\n resumeTimersRef.current.set(claim, { requestId, timer });\n };\n\n dispatch();\n },\n [logLabel, stopResumeReplay, tracker],\n );\n\n const executeRequest = useCallback(\n async (request: StatewireThread.CustomInputRequest) => {\n const payload = request.payload;\n if (!isClientToolInterrupt(payload)) return;\n const claim = clientToolClaimKey(threadId, request.id);\n const {\n tools,\n confirmWrites,\n writeDeclinedMessage,\n missingToolMessage,\n onCallSettled,\n sendResume,\n } = optionsRef.current;\n\n const abortController = new AbortController();\n abortControllersRef.current.set(request.id, abortController);\n const results = await executeClientToolBatch({\n calls: payload.context.requests,\n tools,\n signal: abortController.signal,\n // Live while the request still exists AND this surface may answer it:\n // mounted, or already past the point of no return (handlers started —\n // the detached execution must finish and settle, never re-execute).\n // After unmount the request-id snapshot freezes at its last observed\n // state, which keeps a started batch's own request visible to it.\n isLive: () =>\n liveRequestIdsRef.current.has(request.id) &&\n (activeRef.current || startedClaimsRef.current.has(claim)),\n onExecutionStart: () => {\n startedClaimsRef.current.add(claim);\n },\n ...(confirmWrites\n ? {\n confirmWrites: ({ writeToolNames }: { writeToolNames: readonly string[] }) =>\n confirmWrites({ requestId: request.id, writeToolNames }),\n }\n : {}),\n ...(writeDeclinedMessage !== undefined ? { writeDeclinedMessage } : {}),\n ...(missingToolMessage ? { missingToolMessage } : {}),\n ...(onCallSettled ? { onCallSettled } : {}),\n }).finally(() => {\n if (abortControllersRef.current.get(request.id) === abortController) {\n abortControllersRef.current.delete(request.id);\n }\n });\n if (results === null) {\n releaseClaim(claim);\n return;\n }\n\n const resumeValue = clientToolResultsResumeValue(results);\n tracker.cacheResume(claim, resumeValue);\n // Execution is complete, but the exactly-once claim remains. A pending\n // re-emission must replay this cached value, never run the handlers again.\n ownedClaimsRef.current.delete(claim);\n startedClaimsRef.current.delete(claim);\n\n if (!activeRef.current) {\n // The handler crossed an unmount. Preserve the pre-existing best-effort\n // settle through its captured transport, but leave the cached result\n // available for a later mount if this dispatch is lost.\n if (tracker.claimResumeReplay(claim, resumeOwnerRef.current)) {\n const attempt = tracker.takeResumeAttempt(claim, {\n owner: resumeOwnerRef.current,\n maxAttempts: MAX_CLIENT_TOOL_RESUME_ATTEMPTS,\n });\n if (attempt) {\n try {\n void Promise.resolve(sendResume(request.id, attempt.value)).then(\n () => tracker.settleResume(claim),\n (error) => {\n console.error(`${logLabel} failed to resume client tool results:`, error);\n },\n );\n } catch (error) {\n console.error(`${logLabel} failed to resume client tool results:`, error);\n }\n }\n // Ownership only fences this best-effort dispatch; a future mount\n // may claim and replay the cached value if it did not settle.\n tracker.releaseResumeReplay(claim, resumeOwnerRef.current);\n }\n return;\n }\n\n startResumeReplay(claim, request.id);\n },\n [logLabel, releaseClaim, startResumeReplay, threadId, tracker],\n );\n\n useEffect(() => {\n if (!pendingRequest) return;\n const claim = clientToolClaimKey(threadId, pendingRequest.id);\n if (!tracker.claim(claim)) {\n // The local handler already ran. This is the reconnect/remount path:\n // replay its cached answer instead of double-executing the side effect.\n if (tracker.getCachedResume(claim)) {\n startResumeReplay(claim, pendingRequest.id);\n }\n return;\n }\n ownedClaimsRef.current.add(claim);\n void executeRequest(pendingRequest);\n }, [executeRequest, pendingRequest, startResumeReplay, threadId, tracker]);\n}\n"],"names":["isClientToolInterrupt","clientToolErrorEnvelope","clientToolSuccessEnvelope","clientToolCallArgs","useRef","useCallback","useEffect","clientToolResultsResumeValue"],"mappings":";;;;AA2EO,MAAM,qCACX;AAGK,SAAS,gCAAgC,UAA0B;AACxE,SAAO,mCAAmC,QAAQ;AACpD;AAIO,SAAS,mBAAmB,UAAkB,WAA2B;AAC9E,SAAO,GAAG,QAAQ,IAAI,SAAS;AACjC;AAEA,MAAM,qCAAqC,CAAC,KAAO,KAAO,KAAQ,MAAQ,GAAM;AAChF,MAAM,kCAAkC;AAExC,SAAS,6BAA6B,eAA+B;AACnE,QAAM,QAAQ,KAAK;AAAA,IACjB,KAAK,IAAI,gBAAgB,GAAG,CAAC;AAAA,IAC7B,mCAAmC,SAAS;AAAA,EAAA;AAE9C,SAAO,mCAAmC,KAAK,KAAK;AACtD;AAQO,SAAS,yBAAyB,OAAyB;AAChE,QAAM,aAAa,KAAK,UAAU,KAAK;AACvC,SAAO,eAAe,SAAY,OAAO,KAAK,MAAM,UAAU;AAChE;AAGO,SAAS,2BACd,SAC+C;AAC/C,MAAI,QAAQ,SAAS,eAAe,cAAc,QAAS,QAAO;AACl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gB,gBAAgB,mBAAmB,UAAU,OAAO,CAAC;AAC3E;;;;;;;;"}
@@ -31,16 +31,14 @@
31
31
  * them in, together with its ownership tracker and write-consent policy.
32
32
  */
33
33
  import type { StatewireThread } from '@assistant-ui/react-statewire';
34
- import { type ClientToolCallRequest, type ClientToolRequestTracker, type ClientToolResultEnvelope } from './client-tools';
34
+ import { type ClientToolCallRequest, type ClientToolHandlerContext, type ClientToolRequestTracker, type ClientToolResultEnvelope } from './client-tools';
35
35
  /** A locally executable tool, normalized across the per-surface tool shapes. */
36
36
  export interface ClientToolBridgeTool {
37
37
  /** Snake_case tool id the model calls (e.g. `update_sheet_range`). */
38
38
  name: string;
39
39
  /** Mutating tools gate on the surface's write-consent flow (`confirmWrites`). */
40
40
  requiresWrite?: boolean;
41
- run: (args: Record<string, unknown>, context: {
42
- toolCallId: string;
43
- }) => Promise<unknown>;
41
+ run: (args: Record<string, unknown>, context: ClientToolHandlerContext) => Promise<unknown>;
44
42
  }
45
43
  /**
46
44
  * Batch write-consent outcome. `proceed` runs the write calls, `declined`
@@ -94,6 +92,13 @@ export interface ExecuteClientToolBatchOptions {
94
92
  * marking "execution started" here can never miss a handler that ran.
95
93
  */
96
94
  onExecutionStart?: () => void;
95
+ /**
96
+ * Handed to every handler of the batch (`context.signal`). The caller aborts
97
+ * it when the parked request goes away mid-execution, so a handler that
98
+ * takes visible time can stop; the batch's results are discarded either way
99
+ * (`isLive` is what decides that).
100
+ */
101
+ signal?: AbortSignal;
97
102
  }
98
103
  /**
99
104
  * Execute one batched client-tool park: consent, per-call execution with
@@ -33,7 +33,8 @@ async function executeClientToolBatch(options) {
33
33
  writeDeclinedMessage = CLIENT_TOOL_WRITE_DECLINED_MESSAGE,
34
34
  missingToolMessage = defaultMissingClientToolMessage,
35
35
  onCallSettled,
36
- onExecutionStart
36
+ onExecutionStart,
37
+ signal
37
38
  } = options;
38
39
  const registry = new Map(tools.map((tool) => [tool.name, tool]));
39
40
  let writesDeclined = false;
@@ -68,7 +69,8 @@ async function executeClientToolBatch(options) {
68
69
  envelope = clientToolSuccessEnvelope(
69
70
  jsonSafeClientToolResult(
70
71
  await tool.run(clientToolCallArgs(call), {
71
- toolCallId: call.interrupt_id
72
+ toolCallId: call.interrupt_id,
73
+ ...signal ? { signal } : {}
72
74
  })
73
75
  )
74
76
  );
@@ -141,6 +143,15 @@ function useStatewireClientToolBridge(options) {
141
143
  }, [stopResumeReplay, tracker]);
142
144
  const liveRequestIdsRef = useRef(/* @__PURE__ */ new Set());
143
145
  liveRequestIdsRef.current = new Set((inputRequests ?? []).map((request) => request.id));
146
+ const abortControllersRef = useRef(/* @__PURE__ */ new Map());
147
+ useEffect(() => {
148
+ const liveRequestIds = new Set((inputRequests ?? []).map((request) => request.id));
149
+ for (const [requestId, controller] of abortControllersRef.current) {
150
+ if (liveRequestIds.has(requestId)) continue;
151
+ abortControllersRef.current.delete(requestId);
152
+ controller.abort();
153
+ }
154
+ }, [inputRequests]);
144
155
  const startResumeReplay = useCallback(
145
156
  (claim, requestId) => {
146
157
  if (!activeRef.current || resumeClaimsRef.current.has(claim)) return;
@@ -198,9 +209,12 @@ function useStatewireClientToolBridge(options) {
198
209
  onCallSettled,
199
210
  sendResume
200
211
  } = optionsRef.current;
212
+ const abortController = new AbortController();
213
+ abortControllersRef.current.set(request.id, abortController);
201
214
  const results = await executeClientToolBatch({
202
215
  calls: payload.context.requests,
203
216
  tools,
217
+ signal: abortController.signal,
204
218
  // Live while the request still exists AND this surface may answer it:
205
219
  // mounted, or already past the point of no return (handlers started —
206
220
  // the detached execution must finish and settle, never re-execute).
@@ -216,6 +230,10 @@ function useStatewireClientToolBridge(options) {
216
230
  ...writeDeclinedMessage !== void 0 ? { writeDeclinedMessage } : {},
217
231
  ...missingToolMessage ? { missingToolMessage } : {},
218
232
  ...onCallSettled ? { onCallSettled } : {}
233
+ }).finally(() => {
234
+ if (abortControllersRef.current.get(request.id) === abortController) {
235
+ abortControllersRef.current.delete(request.id);
236
+ }
219
237
  });
220
238
  if (results === null) {
221
239
  releaseClaim(claim);