@athenaintel/react 0.20.0 → 0.21.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.
- package/README.md +74 -0
- package/dist/assets/use-asset-embed.cjs +8 -0
- package/dist/assets/use-asset-embed.cjs.map +1 -1
- package/dist/assets/use-asset-embed.js +8 -0
- package/dist/assets/use-asset-embed.js.map +1 -1
- package/dist/chat/StatewireApprovalCard.cjs +22 -4
- package/dist/chat/StatewireApprovalCard.cjs.map +1 -1
- package/dist/chat/StatewireApprovalCard.d.ts +14 -0
- package/dist/chat/StatewireApprovalCard.js +23 -5
- package/dist/chat/StatewireApprovalCard.js.map +1 -1
- package/dist/chat/StatewireClientToolBridge.cjs +2 -1
- package/dist/chat/StatewireClientToolBridge.cjs.map +1 -1
- package/dist/chat/StatewireClientToolBridge.js +2 -1
- package/dist/chat/StatewireClientToolBridge.js.map +1 -1
- package/dist/chat/StatewireQueuedMessages.cjs +2 -1
- package/dist/chat/StatewireQueuedMessages.cjs.map +1 -1
- package/dist/chat/StatewireQueuedMessages.js +2 -1
- package/dist/chat/StatewireQueuedMessages.js.map +1 -1
- package/dist/chat/athena-citation-links.cjs +17 -1
- package/dist/chat/athena-citation-links.cjs.map +1 -1
- package/dist/chat/athena-citation-links.js +17 -1
- package/dist/chat/athena-citation-links.js.map +1 -1
- package/dist/chat/statewire-client-tools.cjs +2 -1
- package/dist/chat/statewire-client-tools.cjs.map +1 -1
- package/dist/chat/statewire-client-tools.js +2 -1
- package/dist/chat/statewire-client-tools.js.map +1 -1
- package/dist/chat/super-grouping/SuperGroupingCard.cjs +69 -187
- package/dist/chat/super-grouping/SuperGroupingCard.cjs.map +1 -1
- package/dist/chat/super-grouping/SuperGroupingCard.d.ts +10 -6
- package/dist/chat/super-grouping/SuperGroupingCard.js +73 -191
- package/dist/chat/super-grouping/SuperGroupingCard.js.map +1 -1
- package/dist/chat/super-grouping/ToolTimeline.cjs +131 -0
- package/dist/chat/super-grouping/ToolTimeline.cjs.map +1 -0
- package/dist/chat/super-grouping/ToolTimeline.d.ts +16 -0
- package/dist/chat/super-grouping/ToolTimeline.js +131 -0
- package/dist/chat/super-grouping/ToolTimeline.js.map +1 -0
- package/dist/chat/super-grouping/activity-timeline.cjs +14 -8
- package/dist/chat/super-grouping/activity-timeline.cjs.map +1 -1
- package/dist/chat/super-grouping/activity-timeline.d.ts +3 -0
- package/dist/chat/super-grouping/activity-timeline.js +14 -8
- package/dist/chat/super-grouping/activity-timeline.js.map +1 -1
- package/dist/chat/super-grouping/timeline-step.cjs +65 -0
- package/dist/chat/super-grouping/timeline-step.cjs.map +1 -0
- package/dist/chat/super-grouping/timeline-step.d.ts +17 -0
- package/dist/chat/super-grouping/timeline-step.js +65 -0
- package/dist/chat/super-grouping/timeline-step.js.map +1 -0
- package/dist/chat/tiptap-text.cjs +8 -8
- package/dist/chat/tiptap-text.cjs.map +1 -1
- package/dist/chat/use-athena-run-live.cjs +2 -1
- package/dist/chat/use-athena-run-live.cjs.map +1 -1
- package/dist/chat/use-athena-run-live.js +2 -1
- package/dist/chat/use-athena-run-live.js.map +1 -1
- package/dist/chat/use-statewire-approval-request.cjs +7 -2
- package/dist/chat/use-statewire-approval-request.cjs.map +1 -1
- package/dist/chat/use-statewire-approval-request.d.ts +12 -2
- package/dist/chat/use-statewire-approval-request.js +8 -3
- package/dist/chat/use-statewire-approval-request.js.map +1 -1
- package/dist/chat-ui/composer/tiptap-composer.cjs +24 -65
- package/dist/chat-ui/composer/tiptap-composer.cjs.map +1 -1
- package/dist/chat-ui/composer/tiptap-composer.js +24 -65
- package/dist/chat-ui/composer/tiptap-composer.js.map +1 -1
- package/dist/chat-ui/index.cjs +2 -1
- package/dist/chat-ui/index.cjs.map +1 -1
- package/dist/chat-ui/index.js +2 -1
- package/dist/chat-ui/index.js.map +1 -1
- package/dist/chat-ui/mentions/mention-chip.cjs +49 -4
- package/dist/chat-ui/mentions/mention-chip.cjs.map +1 -1
- package/dist/chat-ui/mentions/mention-chip.d.ts +11 -0
- package/dist/chat-ui/mentions/mention-chip.js +50 -5
- package/dist/chat-ui/mentions/mention-chip.js.map +1 -1
- package/dist/chat-ui/mentions/mention-extension.cjs +18 -6
- package/dist/chat-ui/mentions/mention-extension.cjs.map +1 -1
- package/dist/chat-ui/mentions/mention-extension.d.ts +2 -0
- package/dist/chat-ui/mentions/mention-extension.js +18 -6
- package/dist/chat-ui/mentions/mention-extension.js.map +1 -1
- package/dist/chat-ui/mentions/suggestions/components/mention-suggestion-list.cjs +1 -1
- package/dist/chat-ui/mentions/suggestions/components/mention-suggestion-list.cjs.map +1 -1
- package/dist/chat-ui/mentions/suggestions/components/mention-suggestion-list.js +1 -1
- package/dist/chat-ui/mentions/suggestions/components/mention-suggestion-list.js.map +1 -1
- package/dist/chat-ui/mentions/suggestions/components/menu-item.cjs +9 -6
- package/dist/chat-ui/mentions/suggestions/components/menu-item.cjs.map +1 -1
- package/dist/chat-ui/mentions/suggestions/components/menu-item.d.ts +2 -2
- package/dist/chat-ui/mentions/suggestions/components/menu-item.js +10 -7
- package/dist/chat-ui/mentions/suggestions/components/menu-item.js.map +1 -1
- package/dist/chat-ui/mentions/suggestions/components/menu-list.cjs +2 -2
- package/dist/chat-ui/mentions/suggestions/components/menu-list.cjs.map +1 -1
- package/dist/chat-ui/mentions/suggestions/components/menu-list.d.ts +2 -2
- package/dist/chat-ui/mentions/suggestions/components/menu-list.js +2 -2
- package/dist/chat-ui/mentions/suggestions/components/menu-list.js.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/api-client.cjs +2 -1
- package/dist/chat-ui/mentions/suggestions/data/api-client.cjs.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/api-client.d.ts +3 -2
- package/dist/chat-ui/mentions/suggestions/data/api-client.js +2 -1
- package/dist/chat-ui/mentions/suggestions/data/api-client.js.map +1 -1
- package/dist/chat-ui/messages/message-components.cjs +6 -29
- package/dist/chat-ui/messages/message-components.cjs.map +1 -1
- package/dist/chat-ui/messages/message-components.d.ts +1 -13
- package/dist/chat-ui/messages/message-components.js +8 -31
- package/dist/chat-ui/messages/message-components.js.map +1 -1
- package/dist/chat-ui/messages/runtime-message.cjs +3 -2
- package/dist/chat-ui/messages/runtime-message.cjs.map +1 -1
- package/dist/chat-ui/messages/runtime-message.js +3 -2
- package/dist/chat-ui/messages/runtime-message.js.map +1 -1
- package/dist/chat-ui/messages/statewire-continue-run.cjs +23 -8
- package/dist/chat-ui/messages/statewire-continue-run.cjs.map +1 -1
- package/dist/chat-ui/messages/statewire-continue-run.d.ts +14 -4
- package/dist/chat-ui/messages/statewire-continue-run.js +23 -8
- package/dist/chat-ui/messages/statewire-continue-run.js.map +1 -1
- package/dist/chat-ui/messages/user-edit-composer.cjs +2 -1
- package/dist/chat-ui/messages/user-edit-composer.cjs.map +1 -1
- package/dist/chat-ui/messages/user-edit-composer.js +2 -1
- package/dist/chat-ui/messages/user-edit-composer.js.map +1 -1
- package/dist/chat-ui/rich-text/chat-message-body.cjs +76 -0
- package/dist/chat-ui/rich-text/chat-message-body.cjs.map +1 -0
- package/dist/chat-ui/rich-text/chat-message-body.d.ts +5 -0
- package/dist/chat-ui/rich-text/chat-message-body.js +76 -0
- package/dist/chat-ui/rich-text/chat-message-body.js.map +1 -0
- package/dist/chat-ui/rich-text/chat-node-views.cjs +51 -0
- package/dist/chat-ui/rich-text/chat-node-views.cjs.map +1 -0
- package/dist/chat-ui/rich-text/chat-node-views.d.ts +13 -0
- package/dist/chat-ui/rich-text/chat-node-views.js +51 -0
- package/dist/chat-ui/rich-text/chat-node-views.js.map +1 -0
- package/dist/chat-ui/rich-text/chat-text-schema.cjs +70 -0
- package/dist/chat-ui/rich-text/chat-text-schema.cjs.map +1 -0
- package/dist/chat-ui/rich-text/chat-text-schema.d.ts +7 -0
- package/dist/chat-ui/rich-text/chat-text-schema.js +70 -0
- package/dist/chat-ui/rich-text/chat-text-schema.js.map +1 -0
- package/dist/chat-ui/rich-text/dom-output-spec.cjs +83 -0
- package/dist/chat-ui/rich-text/dom-output-spec.cjs.map +1 -0
- package/dist/chat-ui/rich-text/dom-output-spec.d.ts +11 -0
- package/dist/chat-ui/rich-text/dom-output-spec.js +83 -0
- package/dist/chat-ui/rich-text/dom-output-spec.js.map +1 -0
- package/dist/chat-ui/statewire.cjs +2 -1
- package/dist/chat-ui/statewire.cjs.map +1 -1
- package/dist/chat-ui/statewire.js +2 -1
- package/dist/chat-ui/statewire.js.map +1 -1
- package/dist/chat-ui/thread/statewire-history-edge.cjs +2 -1
- package/dist/chat-ui/thread/statewire-history-edge.cjs.map +1 -1
- package/dist/chat-ui/thread/statewire-history-edge.js +2 -1
- package/dist/chat-ui/thread/statewire-history-edge.js.map +1 -1
- package/dist/index.cjs +2 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/node_modules/qrcode-generator/dist/qrcode.cjs +32 -0
- package/dist/node_modules/qrcode-generator/dist/qrcode.cjs.map +1 -0
- package/dist/node_modules/qrcode-generator/dist/qrcode.js +31 -0
- package/dist/node_modules/qrcode-generator/dist/qrcode.js.map +1 -0
- package/dist/node_modules/zod/v4/classic/errors.cjs +44 -0
- package/dist/node_modules/zod/v4/classic/errors.cjs.map +1 -0
- package/dist/node_modules/zod/v4/classic/errors.js +44 -0
- package/dist/node_modules/zod/v4/classic/errors.js.map +1 -0
- package/dist/node_modules/zod/v4/classic/iso.cjs +43 -0
- package/dist/node_modules/zod/v4/classic/iso.cjs.map +1 -0
- package/dist/node_modules/zod/v4/classic/iso.js +43 -0
- package/dist/node_modules/zod/v4/classic/iso.js.map +1 -0
- package/dist/node_modules/zod/v4/classic/parse.cjs +29 -0
- package/dist/node_modules/zod/v4/classic/parse.cjs.map +1 -0
- package/dist/node_modules/zod/v4/classic/parse.js +29 -0
- package/dist/node_modules/zod/v4/classic/parse.js.map +1 -0
- package/dist/node_modules/zod/v4/classic/schemas.cjs +871 -0
- package/dist/node_modules/zod/v4/classic/schemas.cjs.map +1 -0
- package/dist/node_modules/zod/v4/classic/schemas.js +871 -0
- package/dist/node_modules/zod/v4/classic/schemas.js.map +1 -0
- package/dist/node_modules/zod/v4/core/api.cjs +570 -0
- package/dist/node_modules/zod/v4/core/api.cjs.map +1 -0
- package/dist/node_modules/zod/v4/core/api.js +570 -0
- package/dist/node_modules/zod/v4/core/api.js.map +1 -0
- package/dist/node_modules/zod/v4/core/checks.cjs +411 -0
- package/dist/node_modules/zod/v4/core/checks.cjs.map +1 -0
- package/dist/node_modules/zod/v4/core/checks.js +411 -0
- package/dist/node_modules/zod/v4/core/checks.js.map +1 -0
- package/dist/node_modules/zod/v4/core/core.cjs +77 -0
- package/dist/node_modules/zod/v4/core/core.cjs.map +1 -0
- package/dist/node_modules/zod/v4/core/core.js +77 -0
- package/dist/node_modules/zod/v4/core/core.js.map +1 -0
- package/dist/node_modules/zod/v4/core/doc.cjs +38 -0
- package/dist/node_modules/zod/v4/core/doc.cjs.map +1 -0
- package/dist/node_modules/zod/v4/core/doc.js +38 -0
- package/dist/node_modules/zod/v4/core/doc.js.map +1 -0
- package/dist/node_modules/zod/v4/core/errors.cjs +76 -0
- package/dist/node_modules/zod/v4/core/errors.cjs.map +1 -0
- package/dist/node_modules/zod/v4/core/errors.js +76 -0
- package/dist/node_modules/zod/v4/core/errors.js.map +1 -0
- package/dist/node_modules/zod/v4/core/json-schema-processors.cjs +312 -0
- package/dist/node_modules/zod/v4/core/json-schema-processors.cjs.map +1 -0
- package/dist/node_modules/zod/v4/core/json-schema-processors.js +312 -0
- package/dist/node_modules/zod/v4/core/json-schema-processors.js.map +1 -0
- package/dist/node_modules/zod/v4/core/parse.cjs +96 -0
- package/dist/node_modules/zod/v4/core/parse.cjs.map +1 -0
- package/dist/node_modules/zod/v4/core/parse.js +96 -0
- package/dist/node_modules/zod/v4/core/parse.js.map +1 -0
- package/dist/node_modules/zod/v4/core/regexes.cjs +86 -0
- package/dist/node_modules/zod/v4/core/regexes.cjs.map +1 -0
- package/dist/node_modules/zod/v4/core/regexes.js +86 -0
- package/dist/node_modules/zod/v4/core/regexes.js.map +1 -0
- package/dist/node_modules/zod/v4/core/registries.cjs +52 -0
- package/dist/node_modules/zod/v4/core/registries.cjs.map +1 -0
- package/dist/node_modules/zod/v4/core/registries.js +52 -0
- package/dist/node_modules/zod/v4/core/registries.js.map +1 -0
- package/dist/node_modules/zod/v4/core/schemas.cjs +1412 -0
- package/dist/node_modules/zod/v4/core/schemas.cjs.map +1 -0
- package/dist/node_modules/zod/v4/core/schemas.js +1413 -0
- package/dist/node_modules/zod/v4/core/schemas.js.map +1 -0
- package/dist/node_modules/zod/v4/core/to-json-schema.cjs +370 -0
- package/dist/node_modules/zod/v4/core/to-json-schema.cjs.map +1 -0
- package/dist/node_modules/zod/v4/core/to-json-schema.js +370 -0
- package/dist/node_modules/zod/v4/core/to-json-schema.js.map +1 -0
- package/dist/node_modules/zod/v4/core/util.cjs +444 -0
- package/dist/node_modules/zod/v4/core/util.cjs.map +1 -0
- package/dist/node_modules/zod/v4/core/util.js +444 -0
- package/dist/node_modules/zod/v4/core/util.js.map +1 -0
- package/dist/node_modules/zod/v4/core/versions.cjs +9 -0
- package/dist/node_modules/zod/v4/core/versions.cjs.map +1 -0
- package/dist/node_modules/zod/v4/core/versions.js +9 -0
- package/dist/node_modules/zod/v4/core/versions.js.map +1 -0
- package/dist/packages/agent-runtime/src/client-tool-bridge.cjs +7 -1
- package/dist/packages/agent-runtime/src/client-tool-bridge.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/client-tool-bridge.js +7 -1
- package/dist/packages/agent-runtime/src/client-tool-bridge.js.map +1 -1
- package/dist/packages/agent-runtime/src/conversation-list.cjs +4 -0
- package/dist/packages/agent-runtime/src/conversation-list.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/conversation-list.js +4 -0
- package/dist/packages/agent-runtime/src/conversation-list.js.map +1 -1
- package/dist/packages/agent-runtime/src/edit-command.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/edit-command.js.map +1 -1
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.cjs +2 -0
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.js +2 -0
- package/dist/packages/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
- package/dist/packages/agent-runtime/src/interrupts.cjs +31 -7
- package/dist/packages/agent-runtime/src/interrupts.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/interrupts.js +31 -7
- package/dist/packages/agent-runtime/src/interrupts.js.map +1 -1
- package/dist/packages/agent-runtime/src/messages.cjs +35 -5
- package/dist/packages/agent-runtime/src/messages.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/messages.js +35 -5
- package/dist/packages/agent-runtime/src/messages.js.map +1 -1
- package/dist/packages/agent-runtime/src/protocol.cjs +4 -6
- package/dist/packages/agent-runtime/src/protocol.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/protocol.js +4 -6
- package/dist/packages/agent-runtime/src/protocol.js.map +1 -1
- package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.cjs +296 -14
- package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.js +293 -11
- package/dist/packages/agent-runtime/src/quota-safe-local-storage-session.js.map +1 -1
- package/dist/packages/agent-runtime/src/screen-point.cjs +68 -0
- package/dist/packages/agent-runtime/src/screen-point.cjs.map +1 -0
- package/dist/packages/agent-runtime/src/screen-point.js +68 -0
- package/dist/packages/agent-runtime/src/screen-point.js.map +1 -0
- package/dist/packages/agent-runtime/src/statewire-transport.cjs +6 -1
- package/dist/packages/agent-runtime/src/statewire-transport.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/statewire-transport.js +6 -1
- package/dist/packages/agent-runtime/src/statewire-transport.js.map +1 -1
- package/dist/packages/agent-runtime/src/thread-handoff.cjs +85 -0
- package/dist/packages/agent-runtime/src/thread-handoff.cjs.map +1 -0
- package/dist/packages/agent-runtime/src/thread-handoff.js +85 -0
- package/dist/packages/agent-runtime/src/thread-handoff.js.map +1 -0
- package/dist/packages/agent-runtime/src/thread-snapshot-cache.cjs +1 -1
- package/dist/packages/agent-runtime/src/thread-snapshot-cache.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/thread-snapshot-cache.js +1 -1
- package/dist/packages/agent-runtime/src/thread-snapshot-cache.js.map +1 -1
- package/dist/packages/agent-runtime/src/tool-metadata.cjs +0 -8
- package/dist/packages/agent-runtime/src/tool-metadata.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/tool-metadata.js +0 -8
- package/dist/packages/agent-runtime/src/tool-metadata.js.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-config.cjs +14 -0
- package/dist/packages/agent-runtime/src/use-deep-agent-config.cjs.map +1 -0
- package/dist/packages/agent-runtime/src/use-deep-agent-config.js +14 -0
- package/dist/packages/agent-runtime/src/use-deep-agent-config.js.map +1 -0
- package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.cjs +21 -5
- package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.js +21 -5
- package/dist/packages/agent-runtime/src/use-deep-agent-edit-submit.js.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-runtime.cjs +13 -3
- package/dist/packages/agent-runtime/src/use-deep-agent-runtime.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-runtime.js +14 -4
- package/dist/packages/agent-runtime/src/use-deep-agent-runtime.js.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-thread.cjs +35 -15
- package/dist/packages/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/use-deep-agent-thread.js +35 -15
- package/dist/packages/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
- package/dist/packages/agent-runtime/src/voice-presentation.cjs.map +1 -1
- package/dist/packages/agent-runtime/src/voice-presentation.js.map +1 -1
- package/dist/packages/react/package.json.cjs +1 -1
- package/dist/packages/react/package.json.js +1 -1
- package/dist/provider/AthenaProvider.cjs +2 -1
- package/dist/provider/AthenaProvider.cjs.map +1 -1
- package/dist/provider/AthenaProvider.js +2 -1
- package/dist/provider/AthenaProvider.js.map +1 -1
- package/dist/runtime/statewire-lifecycle.cjs +2 -1
- package/dist/runtime/statewire-lifecycle.cjs.map +1 -1
- package/dist/runtime/statewire-lifecycle.js +2 -1
- package/dist/runtime/statewire-lifecycle.js.map +1 -1
- package/dist/runtime/useAthenaStatewireRuntime.cjs +2 -1
- package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
- package/dist/runtime/useAthenaStatewireRuntime.js +2 -1
- package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
- package/dist/styles.css +1 -1
- package/dist/threads/conversation-list-fetcher.cjs +4 -0
- package/dist/threads/conversation-list-fetcher.cjs.map +1 -1
- package/dist/threads/conversation-list-fetcher.js +4 -0
- package/dist/threads/conversation-list-fetcher.js.map +1 -1
- package/dist/threads/statewire-thread-list.cjs +2 -1
- package/dist/threads/statewire-thread-list.cjs.map +1 -1
- package/dist/threads/statewire-thread-list.js +2 -1
- package/dist/threads/statewire-thread-list.js.map +1 -1
- package/dist/threads/use-rest-conversation-history.cjs +2 -1
- package/dist/threads/use-rest-conversation-history.cjs.map +1 -1
- package/dist/threads/use-rest-conversation-history.js +2 -1
- package/dist/threads/use-rest-conversation-history.js.map +1 -1
- package/dist/threads/use-statewire-conversation-history.cjs +2 -1
- package/dist/threads/use-statewire-conversation-history.cjs.map +1 -1
- package/dist/threads/use-statewire-conversation-history.d.ts +1 -0
- package/dist/threads/use-statewire-conversation-history.js +2 -1
- package/dist/threads/use-statewire-conversation-history.js.map +1 -1
- package/dist/tools/index.cjs +2 -1
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.js +2 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/misc-tool-uis.cjs +2 -1
- package/dist/tools/misc-tool-uis.cjs.map +1 -1
- package/dist/tools/misc-tool-uis.js +2 -1
- package/dist/tools/misc-tool-uis.js.map +1 -1
- package/dist/tools/primitives.cjs +2 -1
- package/dist/tools/primitives.cjs.map +1 -1
- package/dist/tools/primitives.js +2 -1
- package/dist/tools/primitives.js.map +1 -1
- package/dist/tools/tool-fallback.cjs +2 -1
- package/dist/tools/tool-fallback.cjs.map +1 -1
- package/dist/tools/tool-fallback.js +2 -1
- package/dist/tools/tool-fallback.js.map +1 -1
- package/dist/tools/voice-update-tool-ui.cjs +2 -1
- package/dist/tools/voice-update-tool-ui.cjs.map +1 -1
- package/dist/tools/voice-update-tool-ui.js +2 -1
- package/dist/tools/voice-update-tool-ui.js.map +1 -1
- package/dist/voice/index.cjs +6 -0
- package/dist/voice/index.cjs.map +1 -0
- package/dist/voice/index.d.ts +2 -0
- package/dist/voice/index.js +6 -0
- package/dist/voice/index.js.map +1 -0
- package/dist/voice/use-athena-voice-session.cjs +315 -0
- package/dist/voice/use-athena-voice-session.cjs.map +1 -0
- package/dist/voice/use-athena-voice-session.d.ts +145 -0
- package/dist/voice/use-athena-voice-session.js +315 -0
- package/dist/voice/use-athena-voice-session.js.map +1 -0
- package/package.json +17 -3
|
@@ -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. The bridge claims the request (exactly-once per\n * ownership domain), runs the matching local handlers, and resumes the run\n * with per-call result envelopes — so a missing tool or a thrown handler still\n * frees the run with an error the model can act on instead of hanging it.\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 pendingRequest = inputRequests?.find(isPendingClientToolRequest);\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,SA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AW,QAAQ,IAAI,QAAQ,KAAK,CAAC,EAAE;AAAA,gBAC1D,MAAM,QAAQ,aAAa,KAAK;AAAA,gBAChC,CAAC,UAAU;AACT,0BAAQ,MAAM,GAAG,QAAQ,0CAA0C,KAAK;AAAA,gBAC1E;AAAA,cAAA;AAAA,YAEJ,SAAS,OAAO;AACd,sBAAQ,MAAM,GAAG,QAAQ,0CAA0C,KAAK;AAAA,YAC1E;AAAA,UACF;AAGA,kBAAQ,oBAAoB,OAAO,eAAe,OAAO;AAAA,QAC3D;AACA;AAAA,MACF;AAEA,wBAAkB,OAAO,QAAQ,EAAE;AAAA,IACrC;AAAA,IACA,CAAC,UAAU,cAAc,mBAAmB,UAAU,OAAO;AAAA,EAAA;AAG/DD,QAAAA,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 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,uBAAuB;AAAA,IACvB,qBAAqB;AAAA,IACrB;AAAA,IACA;AAAA,EAAA,IACE;AACJ,QAAM,WAAW,IAAI,IAAI,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM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AAgB;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;;;;;;;;"}
|
|
@@ -91,7 +91,13 @@ function useStatewireClientToolBridge(options) {
|
|
|
91
91
|
const { threadId, tracker, inputRequests, logLabel = "[AthenaSDK]" } = options;
|
|
92
92
|
const optionsRef = useRef(options);
|
|
93
93
|
optionsRef.current = options;
|
|
94
|
-
const
|
|
94
|
+
const toolNames = new Set(options.tools.map((tool) => tool.name));
|
|
95
|
+
const pendingRequest = inputRequests == null ? void 0 : inputRequests.find((request) => {
|
|
96
|
+
if (!isPendingClientToolRequest(request)) return false;
|
|
97
|
+
const payload = request.payload;
|
|
98
|
+
if (!isClientToolInterrupt(payload)) return false;
|
|
99
|
+
return tracker.getCachedResume(clientToolClaimKey(threadId, request.id)) !== void 0 || payload.context.requests.every((call) => toolNames.has(call.tool_name));
|
|
100
|
+
});
|
|
95
101
|
const ownedClaimsRef = useRef(/* @__PURE__ */ new Set());
|
|
96
102
|
const startedClaimsRef = useRef(/* @__PURE__ */ new Set());
|
|
97
103
|
const resumeOwnerRef = useRef(Symbol("client-tool-resume-owner"));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-tool-bridge.js","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. The bridge claims the request (exactly-once per\n * ownership domain), runs the matching local handlers, and resumes the run\n * with per-call result envelopes — so a missing tool or a thrown handler still\n * frees the run with an error the model can act on instead of hanging it.\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 pendingRequest = inputRequests?.find(isPendingClientToolRequest);\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 }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C,CAAC,UAAU;AACT,0BAAQ,MAAM,GAAG,QAAQ,0CAA0C,KAAK;AAAA,gBAC1E;AAAA,cAAA;AAAA,YAEJ,SAAS,OAAO;AACd,sBAAQ,MAAM,GAAG,QAAQ,0CAA0C,KAAK;AAAA,YAC1E;AAAA,UACF;AAGA,kBAAQ,oBAAoB,OAAO,eAAe,OAAO;AAAA,QAC3D;AACA;AAAA,MACF;AAEA,wBAAkB,OAAO,QAAQ,EAAE;AAAA,IACrC;AAAA,IACA,CAAC,UAAU,cAAc,mBAAmB,UAAU,OAAO;AAAA,EAAA;AAG/D,YAAU,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.js","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":[],"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,SAAO,sBAAuB,QAAkC,OAAO;AACzE;AAkCA,eAAsB,uBACpB,SAC0D;AAC1D,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,uBAAuB;AAAA,IACvB,qBAAqB;AAAA,IACrB;AAAA,IACA;AAAA,EAAA,IACE;AACJ,QAAM,WAAW,IAAI,IAAI,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC,CAAC;AAI/D,MAAI,iBAAiB;AACrB,QAAM,iBAAiB,MACpB,OAAO,CAAC,SAAA;;AAAS,2BAAS,IAAI,KAAK,SAAS,MAA3B,mBAA8B,mBAAkB;AAAA,GAAI,EACrE,IAAI,CAAC,SAAS,KAAK,SAAS;AAC/B,MAAI,eAAe,SAA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annels && filter.sourceChannels.length > 0) {
|
|
14
14
|
normalized.sourceChannels = [...filter.sourceChannels].sort();
|
|
15
15
|
}
|
|
16
|
+
if (filter.excludeSourceChannels && filter.excludeSourceChannels.length > 0) {
|
|
17
|
+
normalized.excludeSourceChannels = [...filter.excludeSourceChannels].sort();
|
|
18
|
+
}
|
|
19
|
+
if (filter.computerAssetId) normalized.computerAssetId = filter.computerAssetId;
|
|
16
20
|
if (filter.states && filter.states.length > 0) {
|
|
17
21
|
normalized.states = [...filter.states].sort();
|
|
18
22
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversation-list.cjs","sources":["../../../../../agent-runtime/src/conversation-list.ts"],"sourcesContent":["import type { InfiniteData, QueryClient } from '@tanstack/react-query';\nimport type { ConversationIndexEntry } from './conversation-index';\n\n/**\n * Shared conversation/thread LIST contract (chat-stack unification —\n * thread-list-contract-convergence).\n *\n * Every chat surface lists \"my conversations\" against the same underlying\n * session assets, but historically each declared its own row shape, paging\n * model, and filter set (Olympus GraphQL `listConversations`, the SDK/Chrome\n * REST `/api/conversations/threads/list`, mobile's `/api/v0/sessions`). This\n * module is the ONE contract those surfaces converge on:\n *\n * - **Row shape**: {@link ConversationSummary} — the canonical camelCase\n * superset. Fields a transport cannot supply are `null`, never invented.\n * - **Ordering**: newest first by `updatedAt`, always. Ordering is part of the\n * contract, not a parameter — no surface sorts any other way.\n * - **Paging**: offset/limit with a LIVE newest page and explicitly-fetched\n * frozen history pages (see `useConversationList`). `hasMore` continues the\n * scan; `totalCount` is advisory and may be `null` for transports that do\n * not count.\n * - **Filtering**: {@link ConversationListFilter}. `appId` follows\n * `docs/SESSION_APP_ID_GUIDE.md`: exact match when set (legacy `null`\n * sessions excluded), no filter when unset. A fetcher that cannot express a\n * requested filter field MUST throw rather than silently ignore it — a\n * dropped filter returns wrong rows under a cache key that claims otherwise.\n * - **Freshness**: the per-user conversation-index statewire\n * (`conversation-index.ts`) is the push signal; these queries are the data\n * source. Push handlers call {@link invalidateConversationListCaches}.\n */\nexport interface ConversationSummary {\n /** LangGraph thread id — the cross-surface conversation identity. */\n threadId: string;\n title: string;\n /** ISO 8601 timestamp of last update (the contract's sort key). */\n updatedAt: string;\n /** ISO 8601 creation timestamp, when the transport reports it. */\n createdAt: string | null;\n /** Session lifecycle state from athena_metadata (e.g. running, completed). */\n state: string | null;\n /** Agent runtime marker (e.g. 'athena_deep_agent'), when reported. */\n runtime: string | null;\n /** Channel the session was started from (e.g. agent_email, web). */\n sourceChannel: string | null;\n /** Asset type (session, video_session, desktop_session, mobile_session). */\n assetType: string | null;\n /** Session asset id (`asset_<uuid>`), when the transport reports it. */\n assetId: string | null;\n /** Client app that created the session (SESSION_APP_ID_GUIDE). */\n appId: string | null;\n /** Trigger marker (`manual` remains user-initiated; other values are automated). */\n triggerType: string | null;\n /** Last-message preview used when a legacy session has no useful title. */\n preview: string | null;\n messageCount: number | null;\n /** Per-user unread flag derived server-side from the read receipt. */\n isUnread: boolean;\n /**\n * Canonical session status (status_v2: idle | active | needs_input | error),\n * or null when the transport does not report it.\n */\n sessionStatus: string | null;\n /**\n * Canonical status of the session's current run (status_v2: scheduled |\n * queued | running | needs_input | completed | failed | canceled). Null when\n * the transport does not report it — {@link isConversationRunning} then\n * falls back to the legacy `state`. Running badges on every surface derive\n * from this one helper so they cannot disagree.\n */\n runStatus: string | null;\n}\n\n/**\n * The canonical filter set. Semantics are defined here once; each fetcher\n * translates the fields its transport supports and throws on the rest.\n */\nexport interface ConversationListFilter {\n /** Exact-match client app filter; unset = all apps (SESSION_APP_ID_GUIDE). */\n appId?: string;\n /** Asset types to include (e.g. ['session']); unset = all session types. */\n assetTypes?: readonly string[];\n /** Case-insensitive title search. */\n search?: string;\n /** Hide triggered/background sessions (REST thread list only today). */\n excludeTriggered?: boolean;\n /** Start-channel filter (v0 sessions / REST thread list only today). */\n sourceChannels?: readonly string[];\n /**\n * Lifecycle-state filter (e.g. ['running'], ['completed']). Transports match\n * it with the shared status_v2 rule (running carries a 12-hour recency cutoff).\n */\n states?: readonly string[];\n /** Restrict to sessions run by any of these agents (athena_metadata.agent). */\n agentIds?: readonly string[];\n /**\n * Include branched sub-sessions and orchestration children, which every list\n * hides by default because they belong under their parent thread.\n */\n includeSubSessions?: boolean;\n}\n\nexport interface ConversationListPage {\n /** Rows in contract order (updatedAt desc). */\n items: ConversationSummary[];\n /** Whether another `offset + limit` scan would return more rows. */\n hasMore: boolean;\n /** Total matching rows, or null when the transport does not count. */\n totalCount: number | null;\n}\n\nexport interface ConversationListFetchParams {\n limit: number;\n offset: number;\n filter: ConversationListFilter;\n signal?: AbortSignal;\n}\n\n/**\n * One page fetch against some transport (GraphQL `listConversations`, the\n * REST thread list, …). Must reject on filter fields it cannot express.\n */\nexport type ConversationListFetcher = (\n params: ConversationListFetchParams\n) => Promise<ConversationListPage>;\n\n/** Root of every conversation-list query key (all surfaces, all filters). */\nexport const CONVERSATION_LIST_QUERY_KEY_ROOT = 'athena-conversation-list';\n\n/**\n * Scope used by `useConversationList` when the caller passes no `scopeKey`.\n * Exported so cache seeders (e.g. Olympus's spacesBootstrap adoption) can\n * address the exact keys default-scoped hooks read from.\n */\nexport const CONVERSATION_LIST_DEFAULT_SCOPE_KEY = 'default';\n\n/**\n * Normalize a filter to its semantic content: unset/empty fields are dropped\n * (so `{}` and `{ appId: undefined }` are the same filter) and array order is\n * canonicalized. Fetchers receive the normalized form, so what a cache entry\n * claims to hold is exactly what was fetched.\n */\nexport function normalizeConversationListFilter(\n filter: ConversationListFilter\n): ConversationListFilter {\n const normalized: ConversationListFilter = {};\n if (filter.appId) normalized.appId = filter.appId;\n if (filter.assetTypes && filter.assetTypes.length > 0) {\n normalized.assetTypes = [...filter.assetTypes].sort();\n }\n if (filter.search) normalized.search = filter.search;\n if (filter.excludeTriggered !== undefined) normalized.excludeTriggered = filter.excludeTriggered;\n if (filter.sourceChannels && filter.sourceChannels.length > 0) {\n normalized.sourceChannels = [...filter.sourceChannels].sort();\n }\n if (filter.states && filter.states.length > 0) {\n normalized.states = [...filter.states].sort();\n }\n if (filter.agentIds && filter.agentIds.length > 0) {\n normalized.agentIds = [...filter.agentIds].sort();\n }\n if (filter.includeSubSessions) normalized.includeSubSessions = true;\n return normalized;\n}\n\n/** status_v2 run statuses during which a session is actively working. */\nconst RUNNING_RUN_STATUSES: ReadonlySet<string> = new Set(['queued', 'running']);\n\n/**\n * THE running rule for every conversation-list surface (sidebar pane, recent\n * dropdown, workspace section, pushed index rows): the canonical status_v2 run\n * status when the transport reports one, else the legacy `state`. A session\n * paused on a human gate (`needs_input`) is not running.\n */\nexport function isConversationRunning(summary: {\n runStatus?: string | null;\n state?: string | null;\n}): boolean {\n if (summary.runStatus !== null && summary.runStatus !== undefined) {\n return RUNNING_RUN_STATUSES.has(summary.runStatus);\n }\n return summary.state === 'running';\n}\n\n/**\n * Stable cache identity for a filter: the normalized fields serialized in\n * sorted key order, so semantically equal filters share one cache entry.\n */\nexport function conversationListFilterKey(filter: ConversationListFilter): string {\n const normalized = normalizeConversationListFilter(filter) as Record<string, unknown>;\n return JSON.stringify(\n Object.keys(normalized)\n .sort()\n .map((key) => [key, normalized[key]])\n );\n}\n\n/**\n * Query keys for the two-tier pager. `scopeKey` isolates caches beyond the\n * filter — surfaces MUST include everything that changes whose list this is\n * (principal/user id, backend base URL) so a credential swap can never read\n * another identity's rows out of the cache.\n *\n * `pageSize` is part of the key because it is baked into every cached page's\n * offset boundaries: two hooks sharing a scope and filter but paging by\n * different sizes would otherwise reuse each other's incompatible boundaries\n * and skip or duplicate rows.\n */\nexport const conversationListQueryKeys = {\n root: [CONVERSATION_LIST_QUERY_KEY_ROOT] as const,\n scope: (scopeKey: string) => [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey] as const,\n firstPage: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'first-page'] as const,\n history: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'history'] as const,\n};\n\n/**\n * Flatten pages into one newest-first list, deduplicating by `threadId`.\n * The live first page wins over retained history copies of the same thread.\n */\nexport function mergeConversationPages(\n pages: readonly ConversationListPage[]\n): ConversationSummary[] {\n const seen = new Set<string>();\n const items: ConversationSummary[] = [];\n for (const page of pages) {\n for (const item of page.items) {\n if (seen.has(item.threadId)) continue;\n seen.add(item.threadId);\n items.push(item);\n }\n }\n return items;\n}\n\n/**\n * Prepend a conversation to a page unless its thread is already present\n * (optimistic \"new thread appears at the top\" write). Identity-preserving\n * no-op when present, so equal writes never notify subscribers.\n */\nexport function prependConversationToPage(\n page: ConversationListPage,\n item: ConversationSummary\n): ConversationListPage {\n if (page.items.some((existing) => existing.threadId === item.threadId)) return page;\n return {\n ...page,\n items: [item, ...page.items],\n totalCount: page.totalCount === null ? null : page.totalCount + 1,\n };\n}\n\n/** Remove a thread's row from a page; identity-preserving when absent. */\nexport function removeConversationFromPage(\n page: ConversationListPage,\n threadId: string\n): ConversationListPage {\n if (!page.items.some((item) => item.threadId === threadId)) return page;\n return { ...page, items: page.items.filter((item) => item.threadId !== threadId) };\n}\n\n/**\n * Patch every row matching `match`; identity-preserving when nothing matches\n * so cache writes cannot cause spurious re-renders.\n */\nexport function patchConversationsInPage(\n page: ConversationListPage,\n match: (item: ConversationSummary) => boolean,\n patch: Partial<ConversationSummary>\n): ConversationListPage {\n let changed = false;\n const items = page.items.map((item) => {\n if (!match(item)) return item;\n changed = true;\n return { ...item, ...patch };\n });\n return changed ? { ...page, items } : page;\n}\n\ntype CachedConversationList =\n | ConversationListPage\n | InfiniteData<ConversationListPage, number>\n | undefined;\n\nfunction isInfinitePages(\n data: ConversationListPage | InfiniteData<ConversationListPage, number>\n): data is InfiniteData<ConversationListPage, number> {\n return 'pages' in data;\n}\n\nfunction mapCachedPages(\n data: CachedConversationList,\n transform: (page: ConversationListPage) => ConversationListPage\n): CachedConversationList {\n if (!data) return data;\n if (isInfinitePages(data)) {\n let changed = false;\n const pages = data.pages.map((page) => {\n const next = transform(page);\n if (next !== page) changed = true;\n return next;\n });\n return changed ? { ...data, pages } : data;\n }\n return transform(data);\n}\n\ninterface ConversationListCacheScope {\n /** Restrict to one scope; omitted = every conversation-list cache. */\n scopeKey?: string;\n}\n\nfunction scopedKey(options?: ConversationListCacheScope): readonly string[] {\n return options?.scopeKey !== undefined\n ? conversationListQueryKeys.scope(options.scopeKey)\n : conversationListQueryKeys.root;\n}\n\n/**\n * Invalidate conversation-list caches (all filters, first page + history).\n * This is the hook for push signals — the conversation-index statewire, a\n * finished run, an archive/restore — anything that changed the server list.\n */\nexport function invalidateConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.invalidateQueries({ queryKey: scopedKey(options) });\n}\n\n/** Cancel in-flight list fetches so an optimistic write cannot be overwritten. */\nexport function cancelConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.cancelQueries({ queryKey: scopedKey(options) });\n}\n\n/**\n * Patch matching rows in every cached conversation list (first pages, history\n * pages, searches) so per-row state (read receipts, titles) flips in the same\n * frame as the interaction instead of after the next refetch.\n */\nexport function patchConversationListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & {\n match: (item: ConversationSummary) => boolean;\n patch: Partial<ConversationSummary>;\n }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => patchConversationsInPage(page, options.match, options.patch))\n );\n}\n\n/** Remove a thread's row from every cached conversation list in scope. */\nexport function removeConversationFromListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & { threadId: string }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => removeConversationFromPage(page, options.threadId))\n );\n}\n\nfunction timestampMs(value: string): number {\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? 0 : parsed;\n}\n\nfunction sameSummary(a: ConversationSummary, b: ConversationSummary): boolean {\n return (\n a.threadId === b.threadId &&\n a.title === b.title &&\n a.updatedAt === b.updatedAt &&\n a.createdAt === b.createdAt &&\n a.state === b.state &&\n a.runtime === b.runtime &&\n a.sourceChannel === b.sourceChannel &&\n a.assetType === b.assetType &&\n a.assetId === b.assetId &&\n a.appId === b.appId &&\n a.triggerType === b.triggerType &&\n a.preview === b.preview &&\n a.messageCount === b.messageCount &&\n a.isUnread === b.isUnread &&\n a.sessionStatus === b.sessionStatus &&\n a.runStatus === b.runStatus\n );\n}\n\n/**\n * Project one replicated conversation-index row onto the shared summary shape.\n * Fields the index never carries (`createdAt`) and viewer-specific fields a\n * lifecycle publish cannot know (`is_unread: null`) keep the row's previous\n * value. Canonical status is taken from the entry when the publishing pod\n * reports it; a snapshot from a pod that predates the fields falls back to the\n * legacy `state` (null status) rather than keeping a stale run status.\n */\nexport function summaryFromConversationIndexEntry(\n entry: ConversationIndexEntry,\n previous?: ConversationSummary\n): ConversationSummary {\n const carriesStatus = entry.run_status !== undefined || entry.session_status !== undefined;\n return {\n threadId: entry.thread_id,\n title: entry.title,\n updatedAt: entry.updated_at,\n createdAt: previous?.createdAt ?? null,\n state: entry.state,\n runtime: entry.runtime,\n sourceChannel: entry.start_channel,\n assetType: entry.asset_type,\n assetId: entry.asset_id ?? previous?.assetId ?? null,\n appId: entry.app_id,\n triggerType: entry.trigger_type,\n preview: entry.last_message_preview,\n messageCount: entry.message_count,\n isUnread: entry.is_unread ?? previous?.isUnread ?? false,\n sessionStatus: carriesStatus ? (entry.session_status ?? null) : null,\n runStatus: carriesStatus ? (entry.run_status ?? null) : null,\n };\n}\n\n/**\n * Fold the user's replicated conversation index (the newest-page window the\n * per-user statewire pushes) into a cached live first page, so a thread\n * created, renamed, finished, or read anywhere updates every list surface in\n * the same frame — without refetching the page.\n *\n * - Rows in the window are upserted (new threads appear, existing rows take\n * the pushed fields, see {@link summaryFromConversationIndexEntry}).\n * - Rows NOT in the window but at least as new as the window's oldest row\n * should have been in it, so they left the list (archived, hidden, shared\n * away) and are dropped. Older rows are beyond the window and are kept.\n * - When the index reports no further rows (`indexHasMore === false`) the\n * window IS the whole list, so every row outside it is dropped.\n *\n * Newest-first ordering is restored and the page identity is preserved when\n * nothing changed, so an equal push never notifies subscribers.\n */\nexport function mergeConversationIndexIntoPage(\n page: ConversationListPage,\n entries: readonly ConversationIndexEntry[],\n options: { indexHasMore: boolean }\n): ConversationListPage {\n const previousByThread = new Map(page.items.map((item) => [item.threadId, item]));\n const inWindow = new Set(entries.map((entry) => entry.thread_id));\n const windowTailMs =\n entries.length > 0 ? Math.min(...entries.map((entry) => timestampMs(entry.updated_at))) : null;\n\n const merged: ConversationSummary[] = entries.map((entry) => {\n const previous = previousByThread.get(entry.thread_id);\n const next = summaryFromConversationIndexEntry(entry, previous);\n return previous && sameSummary(previous, next) ? previous : next;\n });\n\n for (const item of page.items) {\n if (inWindow.has(item.threadId)) continue;\n if (!options.indexHasMore) continue;\n if (windowTailMs !== null && timestampMs(item.updatedAt) >= windowTailMs) continue;\n merged.push(item);\n }\n\n merged.sort((a, b) => timestampMs(b.updatedAt) - timestampMs(a.updatedAt));\n\n const unchanged =\n merged.length === page.items.length &&\n merged.every((item, index) => item === page.items[index]);\n if (unchanged) return page;\n\n return { ...page, items: merged };\n}\n"],"names":[],"mappings":";;AA8HO,MAAM,mCAAmC;AAOzC,MAAM,sCAAsC;AAQ5C,SAAS,gCACd,QACwB;AACxB,QAAM,aAAqC,CAAA;AAC3C,MAAI,OAAO,MAAO,YAAW,QAAQ,OAAO;AAC5C,MAAI,OAAO,cAAc,OAAO,WAAW,SAAS,GAAG;AACrD,eAAW,aAAa,CAAC,GAAG,OAAO,UAAU,EAAE,KAAA;AAAA,EACjD;AACA,MAAI,OAAO,OAAQ,YAAW,SAAS,OAAO;AAC9C,MAAI,OAAO,qBAAqB,OAAW,YAAW,mBAAmB,OAAO;AAChF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KAAK,QAAQ,EAAG,QAAO;AAC/E,SAAO;AAAA,IACL,GAAG;AAAA,IACH,OAAO,CAAC,MAAM,GAAG,KAAK,KAAK;AAAA,IAC3B,YAAY,KAAK,eAAe,OAAO,OAAO,KAAK,aAAa;AAAA,EAAA;AAEpE;AAGO,SAAS,2BACd,MACA,UACsB;AACtB,MAAI,CAAC,KAAK,MAAM,KAAK,CAAC,SAAS,KAAK,aAAa,QAAQ,EAAG,QAAO;AACnE,SAAO,EAAE,GAAG,MAAM,OAAO,KAAK,MAAM,OAAO,CAAC,SAAS,KAAK,aAAa,QAAQ,EAAA;AACjF;AAMO,SAAS,yBACd,MACA,OACA,OACsB;AACtB,MAAI,UAAU;AACd,QAAM,QAAQ,KAAK,MAAM,IAAI,CAAC,SAAS;AACrC,QAAI,CAAC,MAAM,IAAI,EAAG,QAAO;AACzB,cAAU;AACV,WAAO,EAAE,GAAG,MAAM,GAAG,MAAA;AAAA,EACvB,CAAC;AACD,SAAO,UAAU,EAAE,GAAG,MAAM,UAAU;AACxC;AAmCA,SAAS,UAAU,SAAyD;AAC1E,UAAO,mCAAS,cAAa,SACzB,0BAA0B,MAAM,QAAQ,QAAQ,IAChD,0BAA0B;AAChC;AAOO,SAAS,iCACd,aACA,SACe;AACf,SAAO,YAAY,kBAAkB,EAAE,UAAU,UAAU,OAAO,GAAG;AACvE;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"conversation-list.cjs","sources":["../../../../../agent-runtime/src/conversation-list.ts"],"sourcesContent":["import type { InfiniteData, QueryClient } from '@tanstack/react-query';\nimport type { ConversationIndexEntry } from './conversation-index';\n\n/**\n * Shared conversation/thread LIST contract (chat-stack unification —\n * thread-list-contract-convergence).\n *\n * Every chat surface lists \"my conversations\" against the same underlying\n * session assets, but historically each declared its own row shape, paging\n * model, and filter set (Olympus GraphQL `listConversations`, the SDK/Chrome\n * REST `/api/conversations/threads/list`, mobile's `/api/v0/sessions`). This\n * module is the ONE contract those surfaces converge on:\n *\n * - **Row shape**: {@link ConversationSummary} — the canonical camelCase\n * superset. Fields a transport cannot supply are `null`, never invented.\n * - **Ordering**: newest first by `updatedAt`, always. Ordering is part of the\n * contract, not a parameter — no surface sorts any other way.\n * - **Paging**: offset/limit with a LIVE newest page and explicitly-fetched\n * frozen history pages (see `useConversationList`). `hasMore` continues the\n * scan; `totalCount` is advisory and may be `null` for transports that do\n * not count.\n * - **Filtering**: {@link ConversationListFilter}. `appId` follows\n * `docs/SESSION_APP_ID_GUIDE.md`: exact match when set (legacy `null`\n * sessions excluded), no filter when unset. A fetcher that cannot express a\n * requested filter field MUST throw rather than silently ignore it — a\n * dropped filter returns wrong rows under a cache key that claims otherwise.\n * - **Freshness**: the per-user conversation-index statewire\n * (`conversation-index.ts`) is the push signal; these queries are the data\n * source. Push handlers call {@link invalidateConversationListCaches}.\n */\nexport interface ConversationSummary {\n /** LangGraph thread id — the cross-surface conversation identity. */\n threadId: string;\n title: string;\n /** ISO 8601 timestamp of last update (the contract's sort key). */\n updatedAt: string;\n /** ISO 8601 creation timestamp, when the transport reports it. */\n createdAt: string | null;\n /** Session lifecycle state from athena_metadata (e.g. running, completed). */\n state: string | null;\n /** Agent runtime marker (e.g. 'athena_deep_agent'), when reported. */\n runtime: string | null;\n /** Channel the session was started from (e.g. agent_email, web). */\n sourceChannel: string | null;\n /** Asset type (session, video_session, desktop_session, mobile_session). */\n assetType: string | null;\n /** Session asset id (`asset_<uuid>`), when the transport reports it. */\n assetId: string | null;\n /** Client app that created the session (SESSION_APP_ID_GUIDE). */\n appId: string | null;\n /** Computer asset whose sandbox started the session (`sourceChannel` 'computer'); omitted by surfaces that don't carry it. */\n computerAssetId?: string | null;\n /** Trigger marker (`manual` remains user-initiated; other values are automated). */\n triggerType: string | null;\n /** Last-message preview used when a legacy session has no useful title. */\n preview: string | null;\n messageCount: number | null;\n /** Per-user unread flag derived server-side from the read receipt. */\n isUnread: boolean;\n /**\n * Canonical session status (status_v2: idle | active | needs_input | error),\n * or null when the transport does not report it.\n */\n sessionStatus: string | null;\n /**\n * Canonical status of the session's current run (status_v2: scheduled |\n * queued | running | needs_input | completed | failed | canceled). Null when\n * the transport does not report it — {@link isConversationRunning} then\n * falls back to the legacy `state`. Running badges on every surface derive\n * from this one helper so they cannot disagree.\n */\n runStatus: string | null;\n}\n\n/**\n * The canonical filter set. Semantics are defined here once; each fetcher\n * translates the fields its transport supports and throws on the rest.\n */\nexport interface ConversationListFilter {\n /** Exact-match client app filter; unset = all apps (SESSION_APP_ID_GUIDE). */\n appId?: string;\n /** Asset types to include (e.g. ['session']); unset = all session types. */\n assetTypes?: readonly string[];\n /** Case-insensitive title search. */\n search?: string;\n /** Hide triggered/background sessions (REST thread list only today). */\n excludeTriggered?: boolean;\n /** Start-channel filter (v0 sessions / REST thread list only today). */\n sourceChannels?: readonly string[];\n /** Start channels to hide (e.g. ['api']); GraphQL `listConversations` only today. */\n excludeSourceChannels?: readonly string[];\n /** Exact computer asset whose sandbox started the session; GraphQL `listConversations` only today. */\n computerAssetId?: string;\n /**\n * Lifecycle-state filter (e.g. ['running'], ['completed']). Transports match\n * it with the shared status_v2 rule (running carries a 12-hour recency cutoff).\n */\n states?: readonly string[];\n /** Restrict to sessions run by any of these agents (athena_metadata.agent). */\n agentIds?: readonly string[];\n /**\n * Include branched sub-sessions and orchestration children, which every list\n * hides by default because they belong under their parent thread.\n */\n includeSubSessions?: boolean;\n}\n\nexport interface ConversationListPage {\n /** Rows in contract order (updatedAt desc). */\n items: ConversationSummary[];\n /** Whether another `offset + limit` scan would return more rows. */\n hasMore: boolean;\n /** Total matching rows, or null when the transport does not count. */\n totalCount: number | null;\n}\n\nexport interface ConversationListFetchParams {\n limit: number;\n offset: number;\n filter: ConversationListFilter;\n signal?: AbortSignal;\n}\n\n/**\n * One page fetch against some transport (GraphQL `listConversations`, the\n * REST thread list, …). Must reject on filter fields it cannot express.\n */\nexport type ConversationListFetcher = (\n params: ConversationListFetchParams\n) => Promise<ConversationListPage>;\n\n/** Root of every conversation-list query key (all surfaces, all filters). */\nexport const CONVERSATION_LIST_QUERY_KEY_ROOT = 'athena-conversation-list';\n\n/**\n * Scope used by `useConversationList` when the caller passes no `scopeKey`.\n * Exported so cache seeders (e.g. Olympus's spacesBootstrap adoption) can\n * address the exact keys default-scoped hooks read from.\n */\nexport const CONVERSATION_LIST_DEFAULT_SCOPE_KEY = 'default';\n\n/**\n * Normalize a filter to its semantic content: unset/empty fields are dropped\n * (so `{}` and `{ appId: undefined }` are the same filter) and array order is\n * canonicalized. Fetchers receive the normalized form, so what a cache entry\n * claims to hold is exactly what was fetched.\n */\nexport function normalizeConversationListFilter(\n filter: ConversationListFilter\n): ConversationListFilter {\n const normalized: ConversationListFilter = {};\n if (filter.appId) normalized.appId = filter.appId;\n if (filter.assetTypes && filter.assetTypes.length > 0) {\n normalized.assetTypes = [...filter.assetTypes].sort();\n }\n if (filter.search) normalized.search = filter.search;\n if (filter.excludeTriggered !== undefined) normalized.excludeTriggered = filter.excludeTriggered;\n if (filter.sourceChannels && filter.sourceChannels.length > 0) {\n normalized.sourceChannels = [...filter.sourceChannels].sort();\n }\n if (filter.excludeSourceChannels && filter.excludeSourceChannels.length > 0) {\n normalized.excludeSourceChannels = [...filter.excludeSourceChannels].sort();\n }\n if (filter.computerAssetId) normalized.computerAssetId = filter.computerAssetId;\n if (filter.states && filter.states.length > 0) {\n normalized.states = [...filter.states].sort();\n }\n if (filter.agentIds && filter.agentIds.length > 0) {\n normalized.agentIds = [...filter.agentIds].sort();\n }\n if (filter.includeSubSessions) normalized.includeSubSessions = true;\n return normalized;\n}\n\n/** status_v2 run statuses during which a session is actively working. */\nconst RUNNING_RUN_STATUSES: ReadonlySet<string> = new Set(['queued', 'running']);\n\n/**\n * THE running rule for every conversation-list surface (sidebar pane, recent\n * dropdown, workspace section, pushed index rows): the canonical status_v2 run\n * status when the transport reports one, else the legacy `state`. A session\n * paused on a human gate (`needs_input`) is not running.\n */\nexport function isConversationRunning(summary: {\n runStatus?: string | null;\n state?: string | null;\n}): boolean {\n if (summary.runStatus !== null && summary.runStatus !== undefined) {\n return RUNNING_RUN_STATUSES.has(summary.runStatus);\n }\n return summary.state === 'running';\n}\n\n/**\n * Stable cache identity for a filter: the normalized fields serialized in\n * sorted key order, so semantically equal filters share one cache entry.\n */\nexport function conversationListFilterKey(filter: ConversationListFilter): string {\n const normalized = normalizeConversationListFilter(filter) as Record<string, unknown>;\n return JSON.stringify(\n Object.keys(normalized)\n .sort()\n .map((key) => [key, normalized[key]])\n );\n}\n\n/**\n * Query keys for the two-tier pager. `scopeKey` isolates caches beyond the\n * filter — surfaces MUST include everything that changes whose list this is\n * (principal/user id, backend base URL) so a credential swap can never read\n * another identity's rows out of the cache.\n *\n * `pageSize` is part of the key because it is baked into every cached page's\n * offset boundaries: two hooks sharing a scope and filter but paging by\n * different sizes would otherwise reuse each other's incompatible boundaries\n * and skip or duplicate rows.\n */\nexport const conversationListQueryKeys = {\n root: [CONVERSATION_LIST_QUERY_KEY_ROOT] as const,\n scope: (scopeKey: string) => [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey] as const,\n firstPage: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'first-page'] as const,\n history: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'history'] as const,\n};\n\n/**\n * Flatten pages into one newest-first list, deduplicating by `threadId`.\n * The live first page wins over retained history copies of the same thread.\n */\nexport function mergeConversationPages(\n pages: readonly ConversationListPage[]\n): ConversationSummary[] {\n const seen = new Set<string>();\n const items: ConversationSummary[] = [];\n for (const page of pages) {\n for (const item of page.items) {\n if (seen.has(item.threadId)) continue;\n seen.add(item.threadId);\n items.push(item);\n }\n }\n return items;\n}\n\n/**\n * Prepend a conversation to a page unless its thread is already present\n * (optimistic \"new thread appears at the top\" write). Identity-preserving\n * no-op when present, so equal writes never notify subscribers.\n */\nexport function prependConversationToPage(\n page: ConversationListPage,\n item: ConversationSummary\n): ConversationListPage {\n if (page.items.some((existing) => existing.threadId === item.threadId)) return page;\n return {\n ...page,\n items: [item, ...page.items],\n totalCount: page.totalCount === null ? null : page.totalCount + 1,\n };\n}\n\n/** Remove a thread's row from a page; identity-preserving when absent. */\nexport function removeConversationFromPage(\n page: ConversationListPage,\n threadId: string\n): ConversationListPage {\n if (!page.items.some((item) => item.threadId === threadId)) return page;\n return { ...page, items: page.items.filter((item) => item.threadId !== threadId) };\n}\n\n/**\n * Patch every row matching `match`; identity-preserving when nothing matches\n * so cache writes cannot cause spurious re-renders.\n */\nexport function patchConversationsInPage(\n page: ConversationListPage,\n match: (item: ConversationSummary) => boolean,\n patch: Partial<ConversationSummary>\n): ConversationListPage {\n let changed = false;\n const items = page.items.map((item) => {\n if (!match(item)) return item;\n changed = true;\n return { ...item, ...patch };\n });\n return changed ? { ...page, items } : page;\n}\n\ntype CachedConversationList =\n | ConversationListPage\n | InfiniteData<ConversationListPage, number>\n | undefined;\n\nfunction isInfinitePages(\n data: ConversationListPage | InfiniteData<ConversationListPage, number>\n): data is InfiniteData<ConversationListPage, number> {\n return 'pages' in data;\n}\n\nfunction mapCachedPages(\n data: CachedConversationList,\n transform: (page: ConversationListPage) => ConversationListPage\n): CachedConversationList {\n if (!data) return data;\n if (isInfinitePages(data)) {\n let changed = false;\n const pages = data.pages.map((page) => {\n const next = transform(page);\n if (next !== page) changed = true;\n return next;\n });\n return changed ? { ...data, pages } : data;\n }\n return transform(data);\n}\n\ninterface ConversationListCacheScope {\n /** Restrict to one scope; omitted = every conversation-list cache. */\n scopeKey?: string;\n}\n\nfunction scopedKey(options?: ConversationListCacheScope): readonly string[] {\n return options?.scopeKey !== undefined\n ? conversationListQueryKeys.scope(options.scopeKey)\n : conversationListQueryKeys.root;\n}\n\n/**\n * Invalidate conversation-list caches (all filters, first page + history).\n * This is the hook for push signals — the conversation-index statewire, a\n * finished run, an archive/restore — anything that changed the server list.\n */\nexport function invalidateConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.invalidateQueries({ queryKey: scopedKey(options) });\n}\n\n/** Cancel in-flight list fetches so an optimistic write cannot be overwritten. */\nexport function cancelConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.cancelQueries({ queryKey: scopedKey(options) });\n}\n\n/**\n * Patch matching rows in every cached conversation list (first pages, history\n * pages, searches) so per-row state (read receipts, titles) flips in the same\n * frame as the interaction instead of after the next refetch.\n */\nexport function patchConversationListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & {\n match: (item: ConversationSummary) => boolean;\n patch: Partial<ConversationSummary>;\n }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => patchConversationsInPage(page, options.match, options.patch))\n );\n}\n\n/** Remove a thread's row from every cached conversation list in scope. */\nexport function removeConversationFromListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & { threadId: string }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => removeConversationFromPage(page, options.threadId))\n );\n}\n\nfunction timestampMs(value: string): number {\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? 0 : parsed;\n}\n\nfunction sameSummary(a: ConversationSummary, b: ConversationSummary): boolean {\n return (\n a.threadId === b.threadId &&\n a.title === b.title &&\n a.updatedAt === b.updatedAt &&\n a.createdAt === b.createdAt &&\n a.state === b.state &&\n a.runtime === b.runtime &&\n a.sourceChannel === b.sourceChannel &&\n a.assetType === b.assetType &&\n a.assetId === b.assetId &&\n a.appId === b.appId &&\n a.triggerType === b.triggerType &&\n a.preview === b.preview &&\n a.messageCount === b.messageCount &&\n a.isUnread === b.isUnread &&\n a.sessionStatus === b.sessionStatus &&\n a.runStatus === b.runStatus\n );\n}\n\n/**\n * Project one replicated conversation-index row onto the shared summary shape.\n * Fields the index never carries (`createdAt`) and viewer-specific fields a\n * lifecycle publish cannot know (`is_unread: null`) keep the row's previous\n * value. Canonical status is taken from the entry when the publishing pod\n * reports it; a snapshot from a pod that predates the fields falls back to the\n * legacy `state` (null status) rather than keeping a stale run status.\n */\nexport function summaryFromConversationIndexEntry(\n entry: ConversationIndexEntry,\n previous?: ConversationSummary\n): ConversationSummary {\n const carriesStatus = entry.run_status !== undefined || entry.session_status !== undefined;\n return {\n threadId: entry.thread_id,\n title: entry.title,\n updatedAt: entry.updated_at,\n createdAt: previous?.createdAt ?? null,\n state: entry.state,\n runtime: entry.runtime,\n sourceChannel: entry.start_channel,\n assetType: entry.asset_type,\n assetId: entry.asset_id ?? previous?.assetId ?? null,\n computerAssetId: previous?.computerAssetId ?? null,\n appId: entry.app_id,\n triggerType: entry.trigger_type,\n preview: entry.last_message_preview,\n messageCount: entry.message_count,\n isUnread: entry.is_unread ?? previous?.isUnread ?? false,\n sessionStatus: carriesStatus ? (entry.session_status ?? null) : null,\n runStatus: carriesStatus ? (entry.run_status ?? null) : null,\n };\n}\n\n/**\n * Fold the user's replicated conversation index (the newest-page window the\n * per-user statewire pushes) into a cached live first page, so a thread\n * created, renamed, finished, or read anywhere updates every list surface in\n * the same frame — without refetching the page.\n *\n * - Rows in the window are upserted (new threads appear, existing rows take\n * the pushed fields, see {@link summaryFromConversationIndexEntry}).\n * - Rows NOT in the window but at least as new as the window's oldest row\n * should have been in it, so they left the list (archived, hidden, shared\n * away) and are dropped. Older rows are beyond the window and are kept.\n * - When the index reports no further rows (`indexHasMore === false`) the\n * window IS the whole list, so every row outside it is dropped.\n *\n * Newest-first ordering is restored and the page identity is preserved when\n * nothing changed, so an equal push never notifies subscribers.\n */\nexport function mergeConversationIndexIntoPage(\n page: ConversationListPage,\n entries: readonly ConversationIndexEntry[],\n options: { indexHasMore: boolean }\n): ConversationListPage {\n const previousByThread = new Map(page.items.map((item) => [item.threadId, item]));\n const inWindow = new Set(entries.map((entry) => entry.thread_id));\n const windowTailMs =\n entries.length > 0 ? Math.min(...entries.map((entry) => timestampMs(entry.updated_at))) : null;\n\n const merged: ConversationSummary[] = entries.map((entry) => {\n const previous = previousByThread.get(entry.thread_id);\n const next = summaryFromConversationIndexEntry(entry, previous);\n return previous && sameSummary(previous, next) ? previous : next;\n });\n\n for (const item of page.items) {\n if (inWindow.has(item.threadId)) continue;\n if (!options.indexHasMore) continue;\n if (windowTailMs !== null && timestampMs(item.updatedAt) >= windowTailMs) continue;\n merged.push(item);\n }\n\n merged.sort((a, b) => timestampMs(b.updatedAt) - timestampMs(a.updatedAt));\n\n const unchanged =\n merged.length === page.items.length &&\n merged.every((item, index) => item === page.items[index]);\n if (unchanged) return page;\n\n return { ...page, items: merged };\n}\n"],"names":[],"mappings":";;AAoIO,MAAM,mCAAmC;AAOzC,MAAM,sCAAsC;AAQ5C,SAAS,gCACd,QACwB;AACxB,QAAM,aAAqC,CAAA;AAC3C,MAAI,OAAO,MAAO,YAAW,QAAQ,OAAO;AAC5C,MAAI,OAAO,cAAc,OAAO,WAAW,SAAS,GAAG;AACrD,eAAW,aAAa,CAAC,GAAG,OAAO,UAAU,EAAE,KAAA;AAAA,EACjD;AACA,MAAI,OAAO,OAAQ,YAAW,SAAS,OAAO;AAC9C,MAAI,OAAO,qBAAqB,OAAW,YAAW,mBAAmB,OAAO;AAChF,MAAI,OAAO,kBAAkB,OAAO,eAAe,SAAS,GAAG;AAC7D,eAAW,iBAAiB,CAAC,GAAG,OAAO,cAAc,EAAE,KAAA;AAAA,EACzD;AACA,MAAI,OAAO,yBAAyB,OAAO,sBAAsB,SAAS,GAAG;AAC3E,eAAW,wBAAwB,CAAC,GAAG,OAAO,qBAAqB,EAAE,KAAA;AAAA,EACvE;AACA,MAAI,OAAO,gBAAiB,YAAW,kBAAkB,OAAO;AAChE,MAAI,OAAO,UAAU,OAAO,OAAO,SAAS,GAAG;AAC7C,eAAW,SAAS,CAAC,GAAG,OAAO,MAAM,E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ACtB,MAAI,CAAC,KAAK,MAAM,KAAK,CAAC,SAAS,KAAK,aAAa,QAAQ,EAAG,QAAO;AACnE,SAAO,EAAE,GAAG,MAAM,OAAO,KAAK,MAAM,OAAO,CAAC,SAAS,KAAK,aAAa,QAAQ,EAAA;AACjF;AAMO,SAAS,yBACd,MACA,OACA,OACsB;AACtB,MAAI,UAAU;AACd,QAAM,QAAQ,KAAK,MAAM,IAAI,CAAC,SAAS;AACrC,QAAI,CAAC,MAAM,IAAI,EAAG,QAAO;AACzB,cAAU;AACV,WAAO,EAAE,GAAG,MAAM,GAAG,MAAA;AAAA,EACvB,CAAC;AACD,SAAO,UAAU,EAAE,GAAG,MAAM,UAAU;AACxC;AAmCA,SAAS,UAAU,SAAyD;AAC1E,UAAO,mCAAS,cAAa,SACzB,0BAA0B,MAAM,QAAQ,QAAQ,IAChD,0BAA0B;AAChC;AAOO,SAAS,iCACd,aACA,SACe;AACf,SAAO,YAAY,kBAAkB,EAAE,UAAU,UAAU,OAAO,GAAG;AACvE;;;;;;;;;;;"}
|
|
@@ -11,6 +11,10 @@ function normalizeConversationListFilter(filter) {
|
|
|
11
11
|
if (filter.sourceChannels && filter.sourceChannels.length > 0) {
|
|
12
12
|
normalized.sourceChannels = [...filter.sourceChannels].sort();
|
|
13
13
|
}
|
|
14
|
+
if (filter.excludeSourceChannels && filter.excludeSourceChannels.length > 0) {
|
|
15
|
+
normalized.excludeSourceChannels = [...filter.excludeSourceChannels].sort();
|
|
16
|
+
}
|
|
17
|
+
if (filter.computerAssetId) normalized.computerAssetId = filter.computerAssetId;
|
|
14
18
|
if (filter.states && filter.states.length > 0) {
|
|
15
19
|
normalized.states = [...filter.states].sort();
|
|
16
20
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversation-list.js","sources":["../../../../../agent-runtime/src/conversation-list.ts"],"sourcesContent":["import type { InfiniteData, QueryClient } from '@tanstack/react-query';\nimport type { ConversationIndexEntry } from './conversation-index';\n\n/**\n * Shared conversation/thread LIST contract (chat-stack unification —\n * thread-list-contract-convergence).\n *\n * Every chat surface lists \"my conversations\" against the same underlying\n * session assets, but historically each declared its own row shape, paging\n * model, and filter set (Olympus GraphQL `listConversations`, the SDK/Chrome\n * REST `/api/conversations/threads/list`, mobile's `/api/v0/sessions`). This\n * module is the ONE contract those surfaces converge on:\n *\n * - **Row shape**: {@link ConversationSummary} — the canonical camelCase\n * superset. Fields a transport cannot supply are `null`, never invented.\n * - **Ordering**: newest first by `updatedAt`, always. Ordering is part of the\n * contract, not a parameter — no surface sorts any other way.\n * - **Paging**: offset/limit with a LIVE newest page and explicitly-fetched\n * frozen history pages (see `useConversationList`). `hasMore` continues the\n * scan; `totalCount` is advisory and may be `null` for transports that do\n * not count.\n * - **Filtering**: {@link ConversationListFilter}. `appId` follows\n * `docs/SESSION_APP_ID_GUIDE.md`: exact match when set (legacy `null`\n * sessions excluded), no filter when unset. A fetcher that cannot express a\n * requested filter field MUST throw rather than silently ignore it — a\n * dropped filter returns wrong rows under a cache key that claims otherwise.\n * - **Freshness**: the per-user conversation-index statewire\n * (`conversation-index.ts`) is the push signal; these queries are the data\n * source. Push handlers call {@link invalidateConversationListCaches}.\n */\nexport interface ConversationSummary {\n /** LangGraph thread id — the cross-surface conversation identity. */\n threadId: string;\n title: string;\n /** ISO 8601 timestamp of last update (the contract's sort key). */\n updatedAt: string;\n /** ISO 8601 creation timestamp, when the transport reports it. */\n createdAt: string | null;\n /** Session lifecycle state from athena_metadata (e.g. running, completed). */\n state: string | null;\n /** Agent runtime marker (e.g. 'athena_deep_agent'), when reported. */\n runtime: string | null;\n /** Channel the session was started from (e.g. agent_email, web). */\n sourceChannel: string | null;\n /** Asset type (session, video_session, desktop_session, mobile_session). */\n assetType: string | null;\n /** Session asset id (`asset_<uuid>`), when the transport reports it. */\n assetId: string | null;\n /** Client app that created the session (SESSION_APP_ID_GUIDE). */\n appId: string | null;\n /** Trigger marker (`manual` remains user-initiated; other values are automated). */\n triggerType: string | null;\n /** Last-message preview used when a legacy session has no useful title. */\n preview: string | null;\n messageCount: number | null;\n /** Per-user unread flag derived server-side from the read receipt. */\n isUnread: boolean;\n /**\n * Canonical session status (status_v2: idle | active | needs_input | error),\n * or null when the transport does not report it.\n */\n sessionStatus: string | null;\n /**\n * Canonical status of the session's current run (status_v2: scheduled |\n * queued | running | needs_input | completed | failed | canceled). Null when\n * the transport does not report it — {@link isConversationRunning} then\n * falls back to the legacy `state`. Running badges on every surface derive\n * from this one helper so they cannot disagree.\n */\n runStatus: string | null;\n}\n\n/**\n * The canonical filter set. Semantics are defined here once; each fetcher\n * translates the fields its transport supports and throws on the rest.\n */\nexport interface ConversationListFilter {\n /** Exact-match client app filter; unset = all apps (SESSION_APP_ID_GUIDE). */\n appId?: string;\n /** Asset types to include (e.g. ['session']); unset = all session types. */\n assetTypes?: readonly string[];\n /** Case-insensitive title search. */\n search?: string;\n /** Hide triggered/background sessions (REST thread list only today). */\n excludeTriggered?: boolean;\n /** Start-channel filter (v0 sessions / REST thread list only today). */\n sourceChannels?: readonly string[];\n /**\n * Lifecycle-state filter (e.g. ['running'], ['completed']). Transports match\n * it with the shared status_v2 rule (running carries a 12-hour recency cutoff).\n */\n states?: readonly string[];\n /** Restrict to sessions run by any of these agents (athena_metadata.agent). */\n agentIds?: readonly string[];\n /**\n * Include branched sub-sessions and orchestration children, which every list\n * hides by default because they belong under their parent thread.\n */\n includeSubSessions?: boolean;\n}\n\nexport interface ConversationListPage {\n /** Rows in contract order (updatedAt desc). */\n items: ConversationSummary[];\n /** Whether another `offset + limit` scan would return more rows. */\n hasMore: boolean;\n /** Total matching rows, or null when the transport does not count. */\n totalCount: number | null;\n}\n\nexport interface ConversationListFetchParams {\n limit: number;\n offset: number;\n filter: ConversationListFilter;\n signal?: AbortSignal;\n}\n\n/**\n * One page fetch against some transport (GraphQL `listConversations`, the\n * REST thread list, …). Must reject on filter fields it cannot express.\n */\nexport type ConversationListFetcher = (\n params: ConversationListFetchParams\n) => Promise<ConversationListPage>;\n\n/** Root of every conversation-list query key (all surfaces, all filters). */\nexport const CONVERSATION_LIST_QUERY_KEY_ROOT = 'athena-conversation-list';\n\n/**\n * Scope used by `useConversationList` when the caller passes no `scopeKey`.\n * Exported so cache seeders (e.g. Olympus's spacesBootstrap adoption) can\n * address the exact keys default-scoped hooks read from.\n */\nexport const CONVERSATION_LIST_DEFAULT_SCOPE_KEY = 'default';\n\n/**\n * Normalize a filter to its semantic content: unset/empty fields are dropped\n * (so `{}` and `{ appId: undefined }` are the same filter) and array order is\n * canonicalized. Fetchers receive the normalized form, so what a cache entry\n * claims to hold is exactly what was fetched.\n */\nexport function normalizeConversationListFilter(\n filter: ConversationListFilter\n): ConversationListFilter {\n const normalized: ConversationListFilter = {};\n if (filter.appId) normalized.appId = filter.appId;\n if (filter.assetTypes && filter.assetTypes.length > 0) {\n normalized.assetTypes = [...filter.assetTypes].sort();\n }\n if (filter.search) normalized.search = filter.search;\n if (filter.excludeTriggered !== undefined) normalized.excludeTriggered = filter.excludeTriggered;\n if (filter.sourceChannels && filter.sourceChannels.length > 0) {\n normalized.sourceChannels = [...filter.sourceChannels].sort();\n }\n if (filter.states && filter.states.length > 0) {\n normalized.states = [...filter.states].sort();\n }\n if (filter.agentIds && filter.agentIds.length > 0) {\n normalized.agentIds = [...filter.agentIds].sort();\n }\n if (filter.includeSubSessions) normalized.includeSubSessions = true;\n return normalized;\n}\n\n/** status_v2 run statuses during which a session is actively working. */\nconst RUNNING_RUN_STATUSES: ReadonlySet<string> = new Set(['queued', 'running']);\n\n/**\n * THE running rule for every conversation-list surface (sidebar pane, recent\n * dropdown, workspace section, pushed index rows): the canonical status_v2 run\n * status when the transport reports one, else the legacy `state`. A session\n * paused on a human gate (`needs_input`) is not running.\n */\nexport function isConversationRunning(summary: {\n runStatus?: string | null;\n state?: string | null;\n}): boolean {\n if (summary.runStatus !== null && summary.runStatus !== undefined) {\n return RUNNING_RUN_STATUSES.has(summary.runStatus);\n }\n return summary.state === 'running';\n}\n\n/**\n * Stable cache identity for a filter: the normalized fields serialized in\n * sorted key order, so semantically equal filters share one cache entry.\n */\nexport function conversationListFilterKey(filter: ConversationListFilter): string {\n const normalized = normalizeConversationListFilter(filter) as Record<string, unknown>;\n return JSON.stringify(\n Object.keys(normalized)\n .sort()\n .map((key) => [key, normalized[key]])\n );\n}\n\n/**\n * Query keys for the two-tier pager. `scopeKey` isolates caches beyond the\n * filter — surfaces MUST include everything that changes whose list this is\n * (principal/user id, backend base URL) so a credential swap can never read\n * another identity's rows out of the cache.\n *\n * `pageSize` is part of the key because it is baked into every cached page's\n * offset boundaries: two hooks sharing a scope and filter but paging by\n * different sizes would otherwise reuse each other's incompatible boundaries\n * and skip or duplicate rows.\n */\nexport const conversationListQueryKeys = {\n root: [CONVERSATION_LIST_QUERY_KEY_ROOT] as const,\n scope: (scopeKey: string) => [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey] as const,\n firstPage: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'first-page'] as const,\n history: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'history'] as const,\n};\n\n/**\n * Flatten pages into one newest-first list, deduplicating by `threadId`.\n * The live first page wins over retained history copies of the same thread.\n */\nexport function mergeConversationPages(\n pages: readonly ConversationListPage[]\n): ConversationSummary[] {\n const seen = new Set<string>();\n const items: ConversationSummary[] = [];\n for (const page of pages) {\n for (const item of page.items) {\n if (seen.has(item.threadId)) continue;\n seen.add(item.threadId);\n items.push(item);\n }\n }\n return items;\n}\n\n/**\n * Prepend a conversation to a page unless its thread is already present\n * (optimistic \"new thread appears at the top\" write). Identity-preserving\n * no-op when present, so equal writes never notify subscribers.\n */\nexport function prependConversationToPage(\n page: ConversationListPage,\n item: ConversationSummary\n): ConversationListPage {\n if (page.items.some((existing) => existing.threadId === item.threadId)) return page;\n return {\n ...page,\n items: [item, ...page.items],\n totalCount: page.totalCount === null ? null : page.totalCount + 1,\n };\n}\n\n/** Remove a thread's row from a page; identity-preserving when absent. */\nexport function removeConversationFromPage(\n page: ConversationListPage,\n threadId: string\n): ConversationListPage {\n if (!page.items.some((item) => item.threadId === threadId)) return page;\n return { ...page, items: page.items.filter((item) => item.threadId !== threadId) };\n}\n\n/**\n * Patch every row matching `match`; identity-preserving when nothing matches\n * so cache writes cannot cause spurious re-renders.\n */\nexport function patchConversationsInPage(\n page: ConversationListPage,\n match: (item: ConversationSummary) => boolean,\n patch: Partial<ConversationSummary>\n): ConversationListPage {\n let changed = false;\n const items = page.items.map((item) => {\n if (!match(item)) return item;\n changed = true;\n return { ...item, ...patch };\n });\n return changed ? { ...page, items } : page;\n}\n\ntype CachedConversationList =\n | ConversationListPage\n | InfiniteData<ConversationListPage, number>\n | undefined;\n\nfunction isInfinitePages(\n data: ConversationListPage | InfiniteData<ConversationListPage, number>\n): data is InfiniteData<ConversationListPage, number> {\n return 'pages' in data;\n}\n\nfunction mapCachedPages(\n data: CachedConversationList,\n transform: (page: ConversationListPage) => ConversationListPage\n): CachedConversationList {\n if (!data) return data;\n if (isInfinitePages(data)) {\n let changed = false;\n const pages = data.pages.map((page) => {\n const next = transform(page);\n if (next !== page) changed = true;\n return next;\n });\n return changed ? { ...data, pages } : data;\n }\n return transform(data);\n}\n\ninterface ConversationListCacheScope {\n /** Restrict to one scope; omitted = every conversation-list cache. */\n scopeKey?: string;\n}\n\nfunction scopedKey(options?: ConversationListCacheScope): readonly string[] {\n return options?.scopeKey !== undefined\n ? conversationListQueryKeys.scope(options.scopeKey)\n : conversationListQueryKeys.root;\n}\n\n/**\n * Invalidate conversation-list caches (all filters, first page + history).\n * This is the hook for push signals — the conversation-index statewire, a\n * finished run, an archive/restore — anything that changed the server list.\n */\nexport function invalidateConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.invalidateQueries({ queryKey: scopedKey(options) });\n}\n\n/** Cancel in-flight list fetches so an optimistic write cannot be overwritten. */\nexport function cancelConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.cancelQueries({ queryKey: scopedKey(options) });\n}\n\n/**\n * Patch matching rows in every cached conversation list (first pages, history\n * pages, searches) so per-row state (read receipts, titles) flips in the same\n * frame as the interaction instead of after the next refetch.\n */\nexport function patchConversationListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & {\n match: (item: ConversationSummary) => boolean;\n patch: Partial<ConversationSummary>;\n }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => patchConversationsInPage(page, options.match, options.patch))\n );\n}\n\n/** Remove a thread's row from every cached conversation list in scope. */\nexport function removeConversationFromListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & { threadId: string }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => removeConversationFromPage(page, options.threadId))\n );\n}\n\nfunction timestampMs(value: string): number {\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? 0 : parsed;\n}\n\nfunction sameSummary(a: ConversationSummary, b: ConversationSummary): boolean {\n return (\n a.threadId === b.threadId &&\n a.title === b.title &&\n a.updatedAt === b.updatedAt &&\n a.createdAt === b.createdAt &&\n a.state === b.state &&\n a.runtime === b.runtime &&\n a.sourceChannel === b.sourceChannel &&\n a.assetType === b.assetType &&\n a.assetId === b.assetId &&\n a.appId === b.appId &&\n a.triggerType === b.triggerType &&\n a.preview === b.preview &&\n a.messageCount === b.messageCount &&\n a.isUnread === b.isUnread &&\n a.sessionStatus === b.sessionStatus &&\n a.runStatus === b.runStatus\n );\n}\n\n/**\n * Project one replicated conversation-index row onto the shared summary shape.\n * Fields the index never carries (`createdAt`) and viewer-specific fields a\n * lifecycle publish cannot know (`is_unread: null`) keep the row's previous\n * value. Canonical status is taken from the entry when the publishing pod\n * reports it; a snapshot from a pod that predates the fields falls back to the\n * legacy `state` (null status) rather than keeping a stale run status.\n */\nexport function summaryFromConversationIndexEntry(\n entry: ConversationIndexEntry,\n previous?: ConversationSummary\n): ConversationSummary {\n const carriesStatus = entry.run_status !== undefined || entry.session_status !== undefined;\n return {\n threadId: entry.thread_id,\n title: entry.title,\n updatedAt: entry.updated_at,\n createdAt: previous?.createdAt ?? null,\n state: entry.state,\n runtime: entry.runtime,\n sourceChannel: entry.start_channel,\n assetType: entry.asset_type,\n assetId: entry.asset_id ?? previous?.assetId ?? null,\n appId: entry.app_id,\n triggerType: entry.trigger_type,\n preview: entry.last_message_preview,\n messageCount: entry.message_count,\n isUnread: entry.is_unread ?? previous?.isUnread ?? false,\n sessionStatus: carriesStatus ? (entry.session_status ?? null) : null,\n runStatus: carriesStatus ? (entry.run_status ?? null) : null,\n };\n}\n\n/**\n * Fold the user's replicated conversation index (the newest-page window the\n * per-user statewire pushes) into a cached live first page, so a thread\n * created, renamed, finished, or read anywhere updates every list surface in\n * the same frame — without refetching the page.\n *\n * - Rows in the window are upserted (new threads appear, existing rows take\n * the pushed fields, see {@link summaryFromConversationIndexEntry}).\n * - Rows NOT in the window but at least as new as the window's oldest row\n * should have been in it, so they left the list (archived, hidden, shared\n * away) and are dropped. Older rows are beyond the window and are kept.\n * - When the index reports no further rows (`indexHasMore === false`) the\n * window IS the whole list, so every row outside it is dropped.\n *\n * Newest-first ordering is restored and the page identity is preserved when\n * nothing changed, so an equal push never notifies subscribers.\n */\nexport function mergeConversationIndexIntoPage(\n page: ConversationListPage,\n entries: readonly ConversationIndexEntry[],\n options: { indexHasMore: boolean }\n): ConversationListPage {\n const previousByThread = new Map(page.items.map((item) => [item.threadId, item]));\n const inWindow = new Set(entries.map((entry) => entry.thread_id));\n const windowTailMs =\n entries.length > 0 ? Math.min(...entries.map((entry) => timestampMs(entry.updated_at))) : null;\n\n const merged: ConversationSummary[] = entries.map((entry) => {\n const previous = previousByThread.get(entry.thread_id);\n const next = summaryFromConversationIndexEntry(entry, previous);\n return previous && sameSummary(previous, next) ? previous : next;\n });\n\n for (const item of page.items) {\n if (inWindow.has(item.threadId)) continue;\n if (!options.indexHasMore) continue;\n if (windowTailMs !== null && timestampMs(item.updatedAt) >= windowTailMs) continue;\n merged.push(item);\n }\n\n merged.sort((a, b) => timestampMs(b.updatedAt) - timestampMs(a.updatedAt));\n\n const unchanged =\n merged.length === page.items.length &&\n merged.every((item, index) => item === page.items[index]);\n if (unchanged) return page;\n\n return { ...page, items: merged };\n}\n"],"names":[],"mappings":"AA8HO,MAAM,mCAAmC;AAOzC,MAAM,sCAAsC;AAQ5C,SAAS,gCACd,QACwB;AACxB,QAAM,aAAqC,CAAA;AAC3C,MAAI,OAAO,MAAO,YAAW,QAAQ,OAAO;AAC5C,MAAI,OAAO,cAAc,OAAO,WAAW,SAAS,GAAG;AACrD,eAAW,aAAa,CAAC,GAAG,OAAO,UAAU,EAAE,KAAA;AAAA,EACjD;AACA,MAAI,OAAO,OAAQ,YAAW,SAAS,OAAO;AAC9C,MAAI,OAAO,qBAAqB,OAAW,YAAW,mBAAmB,OAAO;AAChF,MAAI,OAAO,kBAAkB,OAAO,eAAe,SAAS,GAAG;AAC7D,eAAW,iBAAiB,CAAC,GAAG,OAAO,cAAc,EAAE,KAAA;AAAA,EACzD;AACA,MAAI,OAAO,UAAU,OAAO,OAAO,SAAS,GAAG;AAC7C,eAAW,SAAS,CAAC,GAAG,OAAO,MAAM,EAAE,KAAA;AAAA,EACzC;AACA,MAAI,OAAO,YAAY,OAAO,SAAS,SAAS,GAAG;AACjD,eAAW,WAAW,CAAC,GAAG,OAAO,QAAQ,EAAE,KAAA;AAAA,EAC7C;AACA,MAAI,OAAO,mBAAoB,YAAW,qBAAqB;AAC/D,SAAO;AACT;AAyBO,SAAS,0BAA0B,QAAwC;AAChF,QAAM,aAAa,gCAAgC,MAAM;AACzD,SAAO,KAAK;AAAA,IACV,OAAO,KAAK,UAAU,EACnB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G,QAAO;AACzB,cAAU;AACV,WAAO,EAAE,GAAG,MAAM,GAAG,MAAA;AAAA,EACvB,CAAC;AACD,SAAO,UAAU,EAAE,GAAG,MAAM,UAAU;AACxC;AAmCA,SAAS,UAAU,SAAyD;AAC1E,UAAO,mCAAS,cAAa,SACzB,0BAA0B,MAAM,QAAQ,QAAQ,IAChD,0BAA0B;AAChC;AAOO,SAAS,iCACd,aACA,SACe;AACf,SAAO,YAAY,kBAAkB,EAAE,UAAU,UAAU,OAAO,GAAG;AACvE;"}
|
|
1
|
+
{"version":3,"file":"conversation-list.js","sources":["../../../../../agent-runtime/src/conversation-list.ts"],"sourcesContent":["import type { InfiniteData, QueryClient } from '@tanstack/react-query';\nimport type { ConversationIndexEntry } from './conversation-index';\n\n/**\n * Shared conversation/thread LIST contract (chat-stack unification —\n * thread-list-contract-convergence).\n *\n * Every chat surface lists \"my conversations\" against the same underlying\n * session assets, but historically each declared its own row shape, paging\n * model, and filter set (Olympus GraphQL `listConversations`, the SDK/Chrome\n * REST `/api/conversations/threads/list`, mobile's `/api/v0/sessions`). This\n * module is the ONE contract those surfaces converge on:\n *\n * - **Row shape**: {@link ConversationSummary} — the canonical camelCase\n * superset. Fields a transport cannot supply are `null`, never invented.\n * - **Ordering**: newest first by `updatedAt`, always. Ordering is part of the\n * contract, not a parameter — no surface sorts any other way.\n * - **Paging**: offset/limit with a LIVE newest page and explicitly-fetched\n * frozen history pages (see `useConversationList`). `hasMore` continues the\n * scan; `totalCount` is advisory and may be `null` for transports that do\n * not count.\n * - **Filtering**: {@link ConversationListFilter}. `appId` follows\n * `docs/SESSION_APP_ID_GUIDE.md`: exact match when set (legacy `null`\n * sessions excluded), no filter when unset. A fetcher that cannot express a\n * requested filter field MUST throw rather than silently ignore it — a\n * dropped filter returns wrong rows under a cache key that claims otherwise.\n * - **Freshness**: the per-user conversation-index statewire\n * (`conversation-index.ts`) is the push signal; these queries are the data\n * source. Push handlers call {@link invalidateConversationListCaches}.\n */\nexport interface ConversationSummary {\n /** LangGraph thread id — the cross-surface conversation identity. */\n threadId: string;\n title: string;\n /** ISO 8601 timestamp of last update (the contract's sort key). */\n updatedAt: string;\n /** ISO 8601 creation timestamp, when the transport reports it. */\n createdAt: string | null;\n /** Session lifecycle state from athena_metadata (e.g. running, completed). */\n state: string | null;\n /** Agent runtime marker (e.g. 'athena_deep_agent'), when reported. */\n runtime: string | null;\n /** Channel the session was started from (e.g. agent_email, web). */\n sourceChannel: string | null;\n /** Asset type (session, video_session, desktop_session, mobile_session). */\n assetType: string | null;\n /** Session asset id (`asset_<uuid>`), when the transport reports it. */\n assetId: string | null;\n /** Client app that created the session (SESSION_APP_ID_GUIDE). */\n appId: string | null;\n /** Computer asset whose sandbox started the session (`sourceChannel` 'computer'); omitted by surfaces that don't carry it. */\n computerAssetId?: string | null;\n /** Trigger marker (`manual` remains user-initiated; other values are automated). */\n triggerType: string | null;\n /** Last-message preview used when a legacy session has no useful title. */\n preview: string | null;\n messageCount: number | null;\n /** Per-user unread flag derived server-side from the read receipt. */\n isUnread: boolean;\n /**\n * Canonical session status (status_v2: idle | active | needs_input | error),\n * or null when the transport does not report it.\n */\n sessionStatus: string | null;\n /**\n * Canonical status of the session's current run (status_v2: scheduled |\n * queued | running | needs_input | completed | failed | canceled). Null when\n * the transport does not report it — {@link isConversationRunning} then\n * falls back to the legacy `state`. Running badges on every surface derive\n * from this one helper so they cannot disagree.\n */\n runStatus: string | null;\n}\n\n/**\n * The canonical filter set. Semantics are defined here once; each fetcher\n * translates the fields its transport supports and throws on the rest.\n */\nexport interface ConversationListFilter {\n /** Exact-match client app filter; unset = all apps (SESSION_APP_ID_GUIDE). */\n appId?: string;\n /** Asset types to include (e.g. ['session']); unset = all session types. */\n assetTypes?: readonly string[];\n /** Case-insensitive title search. */\n search?: string;\n /** Hide triggered/background sessions (REST thread list only today). */\n excludeTriggered?: boolean;\n /** Start-channel filter (v0 sessions / REST thread list only today). */\n sourceChannels?: readonly string[];\n /** Start channels to hide (e.g. ['api']); GraphQL `listConversations` only today. */\n excludeSourceChannels?: readonly string[];\n /** Exact computer asset whose sandbox started the session; GraphQL `listConversations` only today. */\n computerAssetId?: string;\n /**\n * Lifecycle-state filter (e.g. ['running'], ['completed']). Transports match\n * it with the shared status_v2 rule (running carries a 12-hour recency cutoff).\n */\n states?: readonly string[];\n /** Restrict to sessions run by any of these agents (athena_metadata.agent). */\n agentIds?: readonly string[];\n /**\n * Include branched sub-sessions and orchestration children, which every list\n * hides by default because they belong under their parent thread.\n */\n includeSubSessions?: boolean;\n}\n\nexport interface ConversationListPage {\n /** Rows in contract order (updatedAt desc). */\n items: ConversationSummary[];\n /** Whether another `offset + limit` scan would return more rows. */\n hasMore: boolean;\n /** Total matching rows, or null when the transport does not count. */\n totalCount: number | null;\n}\n\nexport interface ConversationListFetchParams {\n limit: number;\n offset: number;\n filter: ConversationListFilter;\n signal?: AbortSignal;\n}\n\n/**\n * One page fetch against some transport (GraphQL `listConversations`, the\n * REST thread list, …). Must reject on filter fields it cannot express.\n */\nexport type ConversationListFetcher = (\n params: ConversationListFetchParams\n) => Promise<ConversationListPage>;\n\n/** Root of every conversation-list query key (all surfaces, all filters). */\nexport const CONVERSATION_LIST_QUERY_KEY_ROOT = 'athena-conversation-list';\n\n/**\n * Scope used by `useConversationList` when the caller passes no `scopeKey`.\n * Exported so cache seeders (e.g. Olympus's spacesBootstrap adoption) can\n * address the exact keys default-scoped hooks read from.\n */\nexport const CONVERSATION_LIST_DEFAULT_SCOPE_KEY = 'default';\n\n/**\n * Normalize a filter to its semantic content: unset/empty fields are dropped\n * (so `{}` and `{ appId: undefined }` are the same filter) and array order is\n * canonicalized. Fetchers receive the normalized form, so what a cache entry\n * claims to hold is exactly what was fetched.\n */\nexport function normalizeConversationListFilter(\n filter: ConversationListFilter\n): ConversationListFilter {\n const normalized: ConversationListFilter = {};\n if (filter.appId) normalized.appId = filter.appId;\n if (filter.assetTypes && filter.assetTypes.length > 0) {\n normalized.assetTypes = [...filter.assetTypes].sort();\n }\n if (filter.search) normalized.search = filter.search;\n if (filter.excludeTriggered !== undefined) normalized.excludeTriggered = filter.excludeTriggered;\n if (filter.sourceChannels && filter.sourceChannels.length > 0) {\n normalized.sourceChannels = [...filter.sourceChannels].sort();\n }\n if (filter.excludeSourceChannels && filter.excludeSourceChannels.length > 0) {\n normalized.excludeSourceChannels = [...filter.excludeSourceChannels].sort();\n }\n if (filter.computerAssetId) normalized.computerAssetId = filter.computerAssetId;\n if (filter.states && filter.states.length > 0) {\n normalized.states = [...filter.states].sort();\n }\n if (filter.agentIds && filter.agentIds.length > 0) {\n normalized.agentIds = [...filter.agentIds].sort();\n }\n if (filter.includeSubSessions) normalized.includeSubSessions = true;\n return normalized;\n}\n\n/** status_v2 run statuses during which a session is actively working. */\nconst RUNNING_RUN_STATUSES: ReadonlySet<string> = new Set(['queued', 'running']);\n\n/**\n * THE running rule for every conversation-list surface (sidebar pane, recent\n * dropdown, workspace section, pushed index rows): the canonical status_v2 run\n * status when the transport reports one, else the legacy `state`. A session\n * paused on a human gate (`needs_input`) is not running.\n */\nexport function isConversationRunning(summary: {\n runStatus?: string | null;\n state?: string | null;\n}): boolean {\n if (summary.runStatus !== null && summary.runStatus !== undefined) {\n return RUNNING_RUN_STATUSES.has(summary.runStatus);\n }\n return summary.state === 'running';\n}\n\n/**\n * Stable cache identity for a filter: the normalized fields serialized in\n * sorted key order, so semantically equal filters share one cache entry.\n */\nexport function conversationListFilterKey(filter: ConversationListFilter): string {\n const normalized = normalizeConversationListFilter(filter) as Record<string, unknown>;\n return JSON.stringify(\n Object.keys(normalized)\n .sort()\n .map((key) => [key, normalized[key]])\n );\n}\n\n/**\n * Query keys for the two-tier pager. `scopeKey` isolates caches beyond the\n * filter — surfaces MUST include everything that changes whose list this is\n * (principal/user id, backend base URL) so a credential swap can never read\n * another identity's rows out of the cache.\n *\n * `pageSize` is part of the key because it is baked into every cached page's\n * offset boundaries: two hooks sharing a scope and filter but paging by\n * different sizes would otherwise reuse each other's incompatible boundaries\n * and skip or duplicate rows.\n */\nexport const conversationListQueryKeys = {\n root: [CONVERSATION_LIST_QUERY_KEY_ROOT] as const,\n scope: (scopeKey: string) => [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey] as const,\n firstPage: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'first-page'] as const,\n history: (scopeKey: string, filterKey: string, pageSize: number) =>\n [CONVERSATION_LIST_QUERY_KEY_ROOT, scopeKey, filterKey, pageSize, 'history'] as const,\n};\n\n/**\n * Flatten pages into one newest-first list, deduplicating by `threadId`.\n * The live first page wins over retained history copies of the same thread.\n */\nexport function mergeConversationPages(\n pages: readonly ConversationListPage[]\n): ConversationSummary[] {\n const seen = new Set<string>();\n const items: ConversationSummary[] = [];\n for (const page of pages) {\n for (const item of page.items) {\n if (seen.has(item.threadId)) continue;\n seen.add(item.threadId);\n items.push(item);\n }\n }\n return items;\n}\n\n/**\n * Prepend a conversation to a page unless its thread is already present\n * (optimistic \"new thread appears at the top\" write). Identity-preserving\n * no-op when present, so equal writes never notify subscribers.\n */\nexport function prependConversationToPage(\n page: ConversationListPage,\n item: ConversationSummary\n): ConversationListPage {\n if (page.items.some((existing) => existing.threadId === item.threadId)) return page;\n return {\n ...page,\n items: [item, ...page.items],\n totalCount: page.totalCount === null ? null : page.totalCount + 1,\n };\n}\n\n/** Remove a thread's row from a page; identity-preserving when absent. */\nexport function removeConversationFromPage(\n page: ConversationListPage,\n threadId: string\n): ConversationListPage {\n if (!page.items.some((item) => item.threadId === threadId)) return page;\n return { ...page, items: page.items.filter((item) => item.threadId !== threadId) };\n}\n\n/**\n * Patch every row matching `match`; identity-preserving when nothing matches\n * so cache writes cannot cause spurious re-renders.\n */\nexport function patchConversationsInPage(\n page: ConversationListPage,\n match: (item: ConversationSummary) => boolean,\n patch: Partial<ConversationSummary>\n): ConversationListPage {\n let changed = false;\n const items = page.items.map((item) => {\n if (!match(item)) return item;\n changed = true;\n return { ...item, ...patch };\n });\n return changed ? { ...page, items } : page;\n}\n\ntype CachedConversationList =\n | ConversationListPage\n | InfiniteData<ConversationListPage, number>\n | undefined;\n\nfunction isInfinitePages(\n data: ConversationListPage | InfiniteData<ConversationListPage, number>\n): data is InfiniteData<ConversationListPage, number> {\n return 'pages' in data;\n}\n\nfunction mapCachedPages(\n data: CachedConversationList,\n transform: (page: ConversationListPage) => ConversationListPage\n): CachedConversationList {\n if (!data) return data;\n if (isInfinitePages(data)) {\n let changed = false;\n const pages = data.pages.map((page) => {\n const next = transform(page);\n if (next !== page) changed = true;\n return next;\n });\n return changed ? { ...data, pages } : data;\n }\n return transform(data);\n}\n\ninterface ConversationListCacheScope {\n /** Restrict to one scope; omitted = every conversation-list cache. */\n scopeKey?: string;\n}\n\nfunction scopedKey(options?: ConversationListCacheScope): readonly string[] {\n return options?.scopeKey !== undefined\n ? conversationListQueryKeys.scope(options.scopeKey)\n : conversationListQueryKeys.root;\n}\n\n/**\n * Invalidate conversation-list caches (all filters, first page + history).\n * This is the hook for push signals — the conversation-index statewire, a\n * finished run, an archive/restore — anything that changed the server list.\n */\nexport function invalidateConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.invalidateQueries({ queryKey: scopedKey(options) });\n}\n\n/** Cancel in-flight list fetches so an optimistic write cannot be overwritten. */\nexport function cancelConversationListCaches(\n queryClient: QueryClient,\n options?: ConversationListCacheScope\n): Promise<void> {\n return queryClient.cancelQueries({ queryKey: scopedKey(options) });\n}\n\n/**\n * Patch matching rows in every cached conversation list (first pages, history\n * pages, searches) so per-row state (read receipts, titles) flips in the same\n * frame as the interaction instead of after the next refetch.\n */\nexport function patchConversationListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & {\n match: (item: ConversationSummary) => boolean;\n patch: Partial<ConversationSummary>;\n }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => patchConversationsInPage(page, options.match, options.patch))\n );\n}\n\n/** Remove a thread's row from every cached conversation list in scope. */\nexport function removeConversationFromListCaches(\n queryClient: QueryClient,\n options: ConversationListCacheScope & { threadId: string }\n): void {\n queryClient.setQueriesData<CachedConversationList>({ queryKey: scopedKey(options) }, (data) =>\n mapCachedPages(data, (page) => removeConversationFromPage(page, options.threadId))\n );\n}\n\nfunction timestampMs(value: string): number {\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? 0 : parsed;\n}\n\nfunction sameSummary(a: ConversationSummary, b: ConversationSummary): boolean {\n return (\n a.threadId === b.threadId &&\n a.title === b.title &&\n a.updatedAt === b.updatedAt &&\n a.createdAt === b.createdAt &&\n a.state === b.state &&\n a.runtime === b.runtime &&\n a.sourceChannel === b.sourceChannel &&\n a.assetType === b.assetType &&\n a.assetId === b.assetId &&\n a.appId === b.appId &&\n a.triggerType === b.triggerType &&\n a.preview === b.preview &&\n a.messageCount === b.messageCount &&\n a.isUnread === b.isUnread &&\n a.sessionStatus === b.sessionStatus &&\n a.runStatus === b.runStatus\n );\n}\n\n/**\n * Project one replicated conversation-index row onto the shared summary shape.\n * Fields the index never carries (`createdAt`) and viewer-specific fields a\n * lifecycle publish cannot know (`is_unread: null`) keep the row's previous\n * value. Canonical status is taken from the entry when the publishing pod\n * reports it; a snapshot from a pod that predates the fields falls back to the\n * legacy `state` (null status) rather than keeping a stale run status.\n */\nexport function summaryFromConversationIndexEntry(\n entry: ConversationIndexEntry,\n previous?: ConversationSummary\n): ConversationSummary {\n const carriesStatus = entry.run_status !== undefined || entry.session_status !== undefined;\n return {\n threadId: entry.thread_id,\n title: entry.title,\n updatedAt: entry.updated_at,\n createdAt: previous?.createdAt ?? null,\n state: entry.state,\n runtime: entry.runtime,\n sourceChannel: entry.start_channel,\n assetType: entry.asset_type,\n assetId: entry.asset_id ?? previous?.assetId ?? null,\n computerAssetId: previous?.computerAssetId ?? null,\n appId: entry.app_id,\n triggerType: entry.trigger_type,\n preview: entry.last_message_preview,\n messageCount: entry.message_count,\n isUnread: entry.is_unread ?? previous?.isUnread ?? false,\n sessionStatus: carriesStatus ? (entry.session_status ?? null) : null,\n runStatus: carriesStatus ? (entry.run_status ?? null) : null,\n };\n}\n\n/**\n * Fold the user's replicated conversation index (the newest-page window the\n * per-user statewire pushes) into a cached live first page, so a thread\n * created, renamed, finished, or read anywhere updates every list surface in\n * the same frame — without refetching the page.\n *\n * - Rows in the window are upserted (new threads appear, existing rows take\n * the pushed fields, see {@link summaryFromConversationIndexEntry}).\n * - Rows NOT in the window but at least as new as the window's oldest row\n * should have been in it, so they left the list (archived, hidden, shared\n * away) and are dropped. Older rows are beyond the window and are kept.\n * - When the index reports no further rows (`indexHasMore === false`) the\n * window IS the whole list, so every row outside it is dropped.\n *\n * Newest-first ordering is restored and the page identity is preserved when\n * nothing changed, so an equal push never notifies subscribers.\n */\nexport function mergeConversationIndexIntoPage(\n page: ConversationListPage,\n entries: readonly ConversationIndexEntry[],\n options: { indexHasMore: boolean }\n): ConversationListPage {\n const previousByThread = new Map(page.items.map((item) => [item.threadId, item]));\n const inWindow = new Set(entries.map((entry) => entry.thread_id));\n const windowTailMs =\n entries.length > 0 ? Math.min(...entries.map((entry) => timestampMs(entry.updated_at))) : null;\n\n const merged: ConversationSummary[] = entries.map((entry) => {\n const previous = previousByThread.get(entry.thread_id);\n const next = summaryFromConversationIndexEntry(entry, previous);\n return previous && sameSummary(previous, next) ? previous : next;\n });\n\n for (const item of page.items) {\n if (inWindow.has(item.threadId)) continue;\n if (!options.indexHasMore) continue;\n if (windowTailMs !== null && timestampMs(item.updatedAt) >= windowTailMs) continue;\n merged.push(item);\n }\n\n merged.sort((a, b) => timestampMs(b.updatedAt) - timestampMs(a.updatedAt));\n\n const unchanged =\n merged.length === page.items.length &&\n merged.every((item, index) => item === page.items[index]);\n if (unchanged) return page;\n\n return { ...page, items: merged };\n}\n"],"names":[],"mappings":"AAoIO,MAAM,mCAAmC;AAOzC,MAAM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