@athenaintel/react 0.55.0 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/README.md +84 -1
  2. package/dist/agent-runtime/src/answer-label.cjs +8 -2
  3. package/dist/agent-runtime/src/answer-label.cjs.map +1 -1
  4. package/dist/agent-runtime/src/answer-label.d.ts +10 -4
  5. package/dist/agent-runtime/src/answer-label.js +8 -2
  6. package/dist/agent-runtime/src/answer-label.js.map +1 -1
  7. package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs +6 -3
  8. package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs.map +1 -1
  9. package/dist/agent-runtime/src/deep-agent-transport-recipe.js +6 -3
  10. package/dist/agent-runtime/src/deep-agent-transport-recipe.js.map +1 -1
  11. package/dist/agent-runtime/src/edit-command.cjs +40 -19
  12. package/dist/agent-runtime/src/edit-command.cjs.map +1 -1
  13. package/dist/agent-runtime/src/edit-command.d.ts +2 -0
  14. package/dist/agent-runtime/src/edit-command.js +41 -20
  15. package/dist/agent-runtime/src/edit-command.js.map +1 -1
  16. package/dist/agent-runtime/src/generated/runconfig-contract.cjs +8 -0
  17. package/dist/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
  18. package/dist/agent-runtime/src/generated/runconfig-contract.d.ts +9 -0
  19. package/dist/agent-runtime/src/generated/runconfig-contract.js +8 -0
  20. package/dist/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
  21. package/dist/agent-runtime/src/history-store.cjs +426 -0
  22. package/dist/agent-runtime/src/history-store.cjs.map +1 -0
  23. package/dist/agent-runtime/src/history-store.d.ts +282 -0
  24. package/dist/agent-runtime/src/history-store.js +426 -0
  25. package/dist/agent-runtime/src/history-store.js.map +1 -0
  26. package/dist/agent-runtime/src/inbound-channel.cjs +96 -0
  27. package/dist/agent-runtime/src/inbound-channel.cjs.map +1 -0
  28. package/dist/agent-runtime/src/inbound-channel.d.ts +75 -0
  29. package/dist/agent-runtime/src/inbound-channel.js +96 -0
  30. package/dist/agent-runtime/src/inbound-channel.js.map +1 -0
  31. package/dist/agent-runtime/src/index.d.ts +6 -5
  32. package/dist/agent-runtime/src/interrupts.cjs +45 -3
  33. package/dist/agent-runtime/src/interrupts.cjs.map +1 -1
  34. package/dist/agent-runtime/src/interrupts.d.ts +51 -4
  35. package/dist/agent-runtime/src/interrupts.js +46 -4
  36. package/dist/agent-runtime/src/interrupts.js.map +1 -1
  37. package/dist/agent-runtime/src/message-window.cjs +43 -5
  38. package/dist/agent-runtime/src/message-window.cjs.map +1 -1
  39. package/dist/agent-runtime/src/message-window.d.ts +26 -2
  40. package/dist/agent-runtime/src/message-window.js +44 -6
  41. package/dist/agent-runtime/src/message-window.js.map +1 -1
  42. package/dist/agent-runtime/src/offline-status.cjs.map +1 -1
  43. package/dist/agent-runtime/src/offline-status.d.ts +110 -4
  44. package/dist/agent-runtime/src/offline-status.js.map +1 -1
  45. package/dist/agent-runtime/src/runtime.d.ts +1 -0
  46. package/dist/agent-runtime/src/thread-handoff-flow-machine.d.ts +8 -8
  47. package/dist/agent-runtime/src/tool-metadata.cjs +16 -0
  48. package/dist/agent-runtime/src/tool-metadata.cjs.map +1 -1
  49. package/dist/agent-runtime/src/tool-metadata.js +16 -0
  50. package/dist/agent-runtime/src/tool-metadata.js.map +1 -1
  51. package/dist/agent-runtime/src/use-deep-agent-thread.cjs +8 -16
  52. package/dist/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
  53. package/dist/agent-runtime/src/use-deep-agent-thread.d.ts +1 -9
  54. package/dist/agent-runtime/src/use-deep-agent-thread.js +9 -17
  55. package/dist/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
  56. package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs +86 -79
  57. package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs.map +1 -1
  58. package/dist/agent-runtime/src/use-deep-agent-window-sync.d.ts +2 -27
  59. package/dist/agent-runtime/src/use-deep-agent-window-sync.js +89 -82
  60. package/dist/agent-runtime/src/use-deep-agent-window-sync.js.map +1 -1
  61. package/dist/auth/AthenaSSOProvider.cjs +54 -12
  62. package/dist/auth/AthenaSSOProvider.cjs.map +1 -1
  63. package/dist/auth/AthenaSSOProvider.d.ts +23 -2
  64. package/dist/auth/AthenaSSOProvider.js +54 -12
  65. package/dist/auth/AthenaSSOProvider.js.map +1 -1
  66. package/dist/auth/index.cjs +2 -0
  67. package/dist/auth/index.cjs.map +1 -1
  68. package/dist/auth/index.d.ts +1 -0
  69. package/dist/auth/index.js +2 -0
  70. package/dist/auth/index.js.map +1 -1
  71. package/dist/auth/sign-back-in.cjs +141 -0
  72. package/dist/auth/sign-back-in.cjs.map +1 -0
  73. package/dist/auth/sign-back-in.d.ts +117 -0
  74. package/dist/auth/sign-back-in.js +141 -0
  75. package/dist/auth/sign-back-in.js.map +1 -0
  76. package/dist/chat/AthenaChat.cjs +7 -2
  77. package/dist/chat/AthenaChat.cjs.map +1 -1
  78. package/dist/chat/AthenaChat.js +7 -2
  79. package/dist/chat/AthenaChat.js.map +1 -1
  80. package/dist/chat/StatewireApprovalCard.cjs +6 -2
  81. package/dist/chat/StatewireApprovalCard.cjs.map +1 -1
  82. package/dist/chat/StatewireApprovalCard.d.ts +8 -1
  83. package/dist/chat/StatewireApprovalCard.js +7 -3
  84. package/dist/chat/StatewireApprovalCard.js.map +1 -1
  85. package/dist/chat/super-grouping/CollapsibleGroup.cjs +1 -1
  86. package/dist/chat/super-grouping/CollapsibleGroup.cjs.map +1 -1
  87. package/dist/chat/super-grouping/CollapsibleGroup.d.ts +6 -5
  88. package/dist/chat/super-grouping/CollapsibleGroup.js +1 -1
  89. package/dist/chat/super-grouping/CollapsibleGroup.js.map +1 -1
  90. package/dist/chat/super-grouping/earlier-steps-button.cjs +5 -6
  91. package/dist/chat/super-grouping/earlier-steps-button.cjs.map +1 -1
  92. package/dist/chat/super-grouping/earlier-steps-button.d.ts +6 -6
  93. package/dist/chat/super-grouping/earlier-steps-button.js +5 -6
  94. package/dist/chat/super-grouping/earlier-steps-button.js.map +1 -1
  95. package/dist/chat/super-grouping/toolkit-map.cjs +1 -0
  96. package/dist/chat/super-grouping/toolkit-map.cjs.map +1 -1
  97. package/dist/chat/super-grouping/toolkit-map.js +1 -0
  98. package/dist/chat/super-grouping/toolkit-map.js.map +1 -1
  99. package/dist/chat/super-grouping/use-turn-steps.cjs +3 -3
  100. package/dist/chat/super-grouping/use-turn-steps.js +1 -1
  101. package/dist/chat-ui/index.cjs +4 -0
  102. package/dist/chat-ui/index.cjs.map +1 -1
  103. package/dist/chat-ui/index.d.ts +1 -0
  104. package/dist/chat-ui/index.js +5 -1
  105. package/dist/chat-ui/index.js.map +1 -1
  106. package/dist/chat-ui/messages/inbound-channel-message.cjs +219 -0
  107. package/dist/chat-ui/messages/inbound-channel-message.cjs.map +1 -0
  108. package/dist/chat-ui/messages/inbound-channel-message.d.ts +60 -0
  109. package/dist/chat-ui/messages/inbound-channel-message.js +219 -0
  110. package/dist/chat-ui/messages/inbound-channel-message.js.map +1 -0
  111. package/dist/chat-ui/messages/inbound-channel-reader.cjs +184 -0
  112. package/dist/chat-ui/messages/inbound-channel-reader.cjs.map +1 -0
  113. package/dist/chat-ui/messages/inbound-channel-reader.d.ts +65 -0
  114. package/dist/chat-ui/messages/inbound-channel-reader.js +184 -0
  115. package/dist/chat-ui/messages/inbound-channel-reader.js.map +1 -0
  116. package/dist/chat-ui/messages/message-components.cjs +18 -14
  117. package/dist/chat-ui/messages/message-components.cjs.map +1 -1
  118. package/dist/chat-ui/messages/message-components.d.ts +7 -0
  119. package/dist/chat-ui/messages/message-components.js +19 -15
  120. package/dist/chat-ui/messages/message-components.js.map +1 -1
  121. package/dist/chat-ui/thread/statewire-history-edge.cjs +0 -4
  122. package/dist/chat-ui/thread/statewire-history-edge.cjs.map +1 -1
  123. package/dist/chat-ui/thread/statewire-history-edge.d.ts +5 -7
  124. package/dist/chat-ui/thread/statewire-history-edge.js +1 -5
  125. package/dist/chat-ui/thread/statewire-history-edge.js.map +1 -1
  126. package/dist/composer/sign-back-in-draft.cjs +62 -0
  127. package/dist/composer/sign-back-in-draft.cjs.map +1 -0
  128. package/dist/composer/sign-back-in-draft.d.ts +34 -0
  129. package/dist/composer/sign-back-in-draft.js +62 -0
  130. package/dist/composer/sign-back-in-draft.js.map +1 -0
  131. package/dist/diagnostics/athena-diagnostics.cjs.map +1 -1
  132. package/dist/diagnostics/athena-diagnostics.d.ts +6 -1
  133. package/dist/diagnostics/athena-diagnostics.js.map +1 -1
  134. package/dist/index.cjs +8 -0
  135. package/dist/index.cjs.map +1 -1
  136. package/dist/index.d.ts +2 -0
  137. package/dist/index.js +8 -0
  138. package/dist/index.js.map +1 -1
  139. package/dist/provider/AthenaProvider.cjs +60 -14
  140. package/dist/provider/AthenaProvider.cjs.map +1 -1
  141. package/dist/provider/AthenaProvider.js +60 -14
  142. package/dist/provider/AthenaProvider.js.map +1 -1
  143. package/dist/provider/statewire-window-context.cjs.map +1 -1
  144. package/dist/provider/statewire-window-context.d.ts +8 -8
  145. package/dist/provider/statewire-window-context.js.map +1 -1
  146. package/dist/react/package.json.cjs +1 -1
  147. package/dist/react/package.json.js +1 -1
  148. package/dist/runtime/auth.cjs +11 -0
  149. package/dist/runtime/auth.cjs.map +1 -1
  150. package/dist/runtime/auth.d.ts +18 -1
  151. package/dist/runtime/auth.js +11 -0
  152. package/dist/runtime/auth.js.map +1 -1
  153. package/dist/runtime/useAthenaStatewireRuntime.cjs +0 -2
  154. package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
  155. package/dist/runtime/useAthenaStatewireRuntime.d.ts +5 -5
  156. package/dist/runtime/useAthenaStatewireRuntime.js +0 -2
  157. package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
  158. package/dist/styles.css +1 -1
  159. package/package.json +1 -1
  160. package/dist/agent-runtime/src/history-pages.cjs +0 -279
  161. package/dist/agent-runtime/src/history-pages.cjs.map +0 -1
  162. package/dist/agent-runtime/src/history-pages.d.ts +0 -252
  163. package/dist/agent-runtime/src/history-pages.js +0 -279
  164. package/dist/agent-runtime/src/history-pages.js.map +0 -1
@@ -0,0 +1,75 @@
1
+ /**
2
+ * A user turn that reached the agent through a channel (Slack, email, a
3
+ * text, Microsoft Teams, the Programmatic API, a voice memo): the reading
4
+ * every client needs on every user bubble, kept small.
5
+ *
6
+ * Two things arrive with such a turn (agora
7
+ * `services/channels/inbound_channel.py`):
8
+ *
9
+ * - The `inbound_channel` envelope in its message metadata, which the shipped
10
+ * converter exposes as `metadata.custom.inbound_channel`: the channel, who
11
+ * sent it (a name and an address or number), an email's subject and the
12
+ * files the channel imported. Metadata never reaches the model.
13
+ * - A routing block at the very start of its text, between
14
+ * `<inbound-message-context>` tags: one `key: value` line per fact the agent
15
+ * is told (the Slack channel and ids, the numbers a text went between, an
16
+ * email's recipients, how a reply is delivered). Text is the model's only
17
+ * way to know where a message came from, so the block stays in it.
18
+ *
19
+ * A person reads the words that were sent ({@link inboundMessageBody}), marked
20
+ * with the channel and the sender; what the agent read is there on request
21
+ * (the SDK's channel line, which loads its full reading only when a channel
22
+ * message is shown). A message is a channel message only when it carries the
23
+ * envelope: anyone can type the tags at the start of a chat message, and
24
+ * their words then show as typed.
25
+ */
26
+ /** `metadata.custom` key the channel routers stamp on an inbound user turn. */
27
+ export declare const INBOUND_CHANNEL_KEY = "inbound_channel";
28
+ /** The routing block's tags (agora `INBOUND_CONTEXT_OPEN` / `INBOUND_CONTEXT_CLOSE`). */
29
+ export declare const INBOUND_CONTEXT_OPEN = "<inbound-message-context>";
30
+ export declare const INBOUND_CONTEXT_CLOSE = "</inbound-message-context>";
31
+ /** The `source:` a group text's block names (agora `sms_group_router`). */
32
+ export declare const GROUP_TEXT_SOURCE = "Group SMS text message";
33
+ /** The routing block at the start of a message's text, as read without labels. */
34
+ export interface LeadingInboundContext {
35
+ /** The block exactly as the agent read it, tags included. */
36
+ readonly raw: string;
37
+ /** The `key: value` lines between the tags. */
38
+ readonly lines: string;
39
+ /** The text after the block. */
40
+ readonly rest: string;
41
+ }
42
+ /** The routing block at the start of `text`, or `null` when the text does not start with one. */
43
+ export declare function leadingInboundContext(text: string): LeadingInboundContext | null;
44
+ /** The block's value for `key` (its first `key: value` line), or `null`. */
45
+ export declare function inboundContextValue(lines: string, key: string): string | null;
46
+ /** The text with a leading routing block removed (agora `strip_inbound_context`). */
47
+ export declare function stripInboundContext(text: string): string;
48
+ /**
49
+ * The words after the block, without what a channel put ahead of them for
50
+ * the agent: the Slack thread a mention came in (returned as `quoted`), a
51
+ * group text's "<name> said:" line.
52
+ */
53
+ export declare function splitInboundBody(context: LeadingInboundContext): {
54
+ readonly body: string;
55
+ readonly quoted: string | null;
56
+ };
57
+ /**
58
+ * Whether a thread message came in over a channel: it carries the
59
+ * `inbound_channel` envelope with a channel. A primitive, so safe as a
60
+ * `useAuiState` selector.
61
+ */
62
+ export declare function isInboundChannelMessage(custom: Record<string, unknown> | null | undefined): boolean;
63
+ /**
64
+ * What the person wrote: a channel message's `text` without its leading
65
+ * routing block and what the channel quoted ahead of the words. Any other
66
+ * text comes back unchanged: a message without the envelope (tags someone
67
+ * typed stay as typed), and text without a block. Safe on every user turn and
68
+ * on its own output.
69
+ */
70
+ export declare function inboundMessageBody({ custom, text, }: {
71
+ custom: Record<string, unknown> | null | undefined;
72
+ text: string;
73
+ }): string;
74
+ /** An email's subject, from the envelope; `null` for any other message. */
75
+ export declare function inboundEmailSubject(custom: Record<string, unknown> | null | undefined): string | null;
@@ -0,0 +1,96 @@
1
+ const INBOUND_CHANNEL_KEY = "inbound_channel";
2
+ const INBOUND_CONTEXT_OPEN = "<inbound-message-context>";
3
+ const LEADING_CONTEXT = /^<inbound-message-context>([\s\S]*?)<\/inbound-message-context>\n*/;
4
+ const SLACK_QUOTED_THREAD_OPEN = "Earlier messages in this Slack thread (oldest first):";
5
+ const SLACK_QUOTED_THREAD_MESSAGE = "The message that mentioned you:";
6
+ const GROUP_TEXT_SOURCE = "Group SMS text message";
7
+ function leadingInboundContext(text) {
8
+ if (!text.startsWith(INBOUND_CONTEXT_OPEN)) return null;
9
+ const match = LEADING_CONTEXT.exec(text);
10
+ if (match === null) return null;
11
+ return {
12
+ raw: match[0].trimEnd(),
13
+ lines: match[1] ?? "",
14
+ rest: text.slice(match[0].length).trimStart()
15
+ };
16
+ }
17
+ function inboundContextValue(lines, key) {
18
+ for (const line of lines.split("\n")) {
19
+ const separator = line.indexOf(":");
20
+ if (separator > 0 && line.slice(0, separator).trim() === key) {
21
+ return line.slice(separator + 1).trim() || null;
22
+ }
23
+ }
24
+ return null;
25
+ }
26
+ function stripInboundContext(text) {
27
+ var _a;
28
+ return ((_a = leadingInboundContext(text)) == null ? void 0 : _a.rest) ?? text;
29
+ }
30
+ function splitInboundBody(context) {
31
+ const { lines, rest } = context;
32
+ const source = inboundContextValue(lines, "source");
33
+ if (source === "Slack" && rest.startsWith(`${SLACK_QUOTED_THREAD_OPEN}
34
+ `)) {
35
+ const marker = `
36
+
37
+ ${SLACK_QUOTED_THREAD_MESSAGE}`;
38
+ const at = rest.indexOf(marker);
39
+ if (at !== -1) {
40
+ const quoted = rest.slice(SLACK_QUOTED_THREAD_OPEN.length, at).trim();
41
+ return { body: rest.slice(at + marker.length).trimStart(), quoted: quoted || null };
42
+ }
43
+ }
44
+ if (source === GROUP_TEXT_SOURCE) {
45
+ const sender = inboundContextValue(lines, "sender_name");
46
+ const newline = rest.indexOf("\n");
47
+ const firstLine = newline === -1 ? rest : rest.slice(0, newline);
48
+ if (sender && firstLine.endsWith(GROUP_TEXT_SAID) && collapseWhitespace(firstLine.slice(0, -GROUP_TEXT_SAID.length)) === sender) {
49
+ return { body: newline === -1 ? "" : rest.slice(newline + 1), quoted: null };
50
+ }
51
+ }
52
+ return { body: rest, quoted: null };
53
+ }
54
+ const GROUP_TEXT_SAID = " said:";
55
+ function collapseWhitespace(value) {
56
+ return value.split(/\s+/).filter((word) => word.length > 0).join(" ");
57
+ }
58
+ function envelopeOf(custom) {
59
+ const raw = custom == null ? void 0 : custom[INBOUND_CHANNEL_KEY];
60
+ return typeof raw === "object" && raw !== null && !Array.isArray(raw) ? raw : null;
61
+ }
62
+ function envelopeString(envelope, key) {
63
+ const value = envelope[key];
64
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
65
+ }
66
+ function isInboundChannelMessage(custom) {
67
+ const envelope = envelopeOf(custom);
68
+ return envelope !== null && envelopeString(envelope, "channel") !== null;
69
+ }
70
+ function inboundMessageBody({
71
+ custom,
72
+ text
73
+ }) {
74
+ if (!isInboundChannelMessage(custom)) return text;
75
+ const context = leadingInboundContext(text);
76
+ return context === null ? text : splitInboundBody(context).body;
77
+ }
78
+ function inboundEmailSubject(custom) {
79
+ const envelope = envelopeOf(custom);
80
+ if (envelope === null) return null;
81
+ const channel = envelopeString(envelope, "channel");
82
+ return channel === "email" || channel === "agent_email" ? envelopeString(envelope, "subject") : null;
83
+ }
84
+ export {
85
+ GROUP_TEXT_SOURCE,
86
+ INBOUND_CHANNEL_KEY,
87
+ INBOUND_CONTEXT_OPEN,
88
+ inboundContextValue,
89
+ inboundEmailSubject,
90
+ inboundMessageBody,
91
+ isInboundChannelMessage,
92
+ leadingInboundContext,
93
+ splitInboundBody,
94
+ stripInboundContext
95
+ };
96
+ //# sourceMappingURL=inbound-channel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inbound-channel.js","sources":["../../../../agent-runtime/src/inbound-channel.ts"],"sourcesContent":["/**\n * A user turn that reached the agent through a channel (Slack, email, a\n * text, Microsoft Teams, the Programmatic API, a voice memo): the reading\n * every client needs on every user bubble, kept small.\n *\n * Two things arrive with such a turn (agora\n * `services/channels/inbound_channel.py`):\n *\n * - The `inbound_channel` envelope in its message metadata, which the shipped\n * converter exposes as `metadata.custom.inbound_channel`: the channel, who\n * sent it (a name and an address or number), an email's subject and the\n * files the channel imported. Metadata never reaches the model.\n * - A routing block at the very start of its text, between\n * `<inbound-message-context>` tags: one `key: value` line per fact the agent\n * is told (the Slack channel and ids, the numbers a text went between, an\n * email's recipients, how a reply is delivered). Text is the model's only\n * way to know where a message came from, so the block stays in it.\n *\n * A person reads the words that were sent ({@link inboundMessageBody}), marked\n * with the channel and the sender; what the agent read is there on request\n * (the SDK's channel line, which loads its full reading only when a channel\n * message is shown). A message is a channel message only when it carries the\n * envelope: anyone can type the tags at the start of a chat message, and\n * their words then show as typed.\n */\n\n/** `metadata.custom` key the channel routers stamp on an inbound user turn. */\nexport const INBOUND_CHANNEL_KEY = 'inbound_channel';\n\n/** The routing block's tags (agora `INBOUND_CONTEXT_OPEN` / `INBOUND_CONTEXT_CLOSE`). */\nexport const INBOUND_CONTEXT_OPEN = '<inbound-message-context>';\nexport const INBOUND_CONTEXT_CLOSE = '</inbound-message-context>';\n\n/**\n * Anchored to the start: routers only ever prepend the block, so a sender who\n * types the tags inside their own words keeps that text (agora\n * `_LEADING_CONTEXT_RE`, Olympus `stripInboundContext`).\n */\nconst LEADING_CONTEXT = /^<inbound-message-context>([\\s\\S]*?)<\\/inbound-message-context>\\n*/;\n\n/**\n * The lines the Slack router puts around the thread a mention came in, when\n * the mention starts a conversation (agora `slack_router._build_message_text`).\n */\nconst SLACK_QUOTED_THREAD_OPEN = 'Earlier messages in this Slack thread (oldest first):';\nconst SLACK_QUOTED_THREAD_MESSAGE = 'The message that mentioned you:';\n\n/** The `source:` a group text's block names (agora `sms_group_router`). */\nexport const GROUP_TEXT_SOURCE = 'Group SMS text message';\n\n/** The routing block at the start of a message's text, as read without labels. */\nexport interface LeadingInboundContext {\n /** The block exactly as the agent read it, tags included. */\n readonly raw: string;\n /** The `key: value` lines between the tags. */\n readonly lines: string;\n /** The text after the block. */\n readonly rest: string;\n}\n\n/** The routing block at the start of `text`, or `null` when the text does not start with one. */\nexport function leadingInboundContext(text: string): LeadingInboundContext | null {\n if (!text.startsWith(INBOUND_CONTEXT_OPEN)) return null;\n const match = LEADING_CONTEXT.exec(text);\n if (match === null) return null;\n return {\n raw: match[0].trimEnd(),\n lines: match[1] ?? '',\n rest: text.slice(match[0].length).trimStart(),\n };\n}\n\n/** The block's value for `key` (its first `key: value` line), or `null`. */\nexport function inboundContextValue(lines: string, key: string): string | null {\n for (const line of lines.split('\\n')) {\n const separator = line.indexOf(':');\n if (separator > 0 && line.slice(0, separator).trim() === key) {\n return line.slice(separator + 1).trim() || null;\n }\n }\n return null;\n}\n\n/** The text with a leading routing block removed (agora `strip_inbound_context`). */\nexport function stripInboundContext(text: string): string {\n return leadingInboundContext(text)?.rest ?? text;\n}\n\n/**\n * The words after the block, without what a channel put ahead of them for\n * the agent: the Slack thread a mention came in (returned as `quoted`), a\n * group text's \"<name> said:\" line.\n */\nexport function splitInboundBody(context: LeadingInboundContext): {\n readonly body: string;\n readonly quoted: string | null;\n} {\n const { lines, rest } = context;\n const source = inboundContextValue(lines, 'source');\n if (source === 'Slack' && rest.startsWith(`${SLACK_QUOTED_THREAD_OPEN}\\n`)) {\n const marker = `\\n\\n${SLACK_QUOTED_THREAD_MESSAGE}`;\n const at = rest.indexOf(marker);\n if (at !== -1) {\n const quoted = rest.slice(SLACK_QUOTED_THREAD_OPEN.length, at).trim();\n return { body: rest.slice(at + marker.length).trimStart(), quoted: quoted || null };\n }\n }\n if (source === GROUP_TEXT_SOURCE) {\n // The block's values have their whitespace collapsed (agora\n // `build_inbound_context_block`); the \"<name> said:\" line keeps the name\n // as saved, so the two compare collapsed.\n const sender = inboundContextValue(lines, 'sender_name');\n const newline = rest.indexOf('\\n');\n const firstLine = newline === -1 ? rest : rest.slice(0, newline);\n if (sender && firstLine.endsWith(GROUP_TEXT_SAID) && collapseWhitespace(firstLine.slice(0, -GROUP_TEXT_SAID.length)) === sender) {\n return { body: newline === -1 ? '' : rest.slice(newline + 1), quoted: null };\n }\n }\n return { body: rest, quoted: null };\n}\n\n/** What follows the sender's name on a group text's first line (agora `_build_group_message_text`). */\nconst GROUP_TEXT_SAID = ' said:';\n\nfunction collapseWhitespace(value: string): string {\n return value.split(/\\s+/).filter((word) => word.length > 0).join(' ');\n}\n\nfunction envelopeOf(custom: Record<string, unknown> | null | undefined): Record<string, unknown> | null {\n const raw = custom?.[INBOUND_CHANNEL_KEY];\n return typeof raw === 'object' && raw !== null && !Array.isArray(raw)\n ? (raw as Record<string, unknown>)\n : null;\n}\n\nfunction envelopeString(envelope: Record<string, unknown>, key: string): string | null {\n const value = envelope[key];\n return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;\n}\n\n/**\n * Whether a thread message came in over a channel: it carries the\n * `inbound_channel` envelope with a channel. A primitive, so safe as a\n * `useAuiState` selector.\n */\nexport function isInboundChannelMessage(custom: Record<string, unknown> | null | undefined): boolean {\n const envelope = envelopeOf(custom);\n return envelope !== null && envelopeString(envelope, 'channel') !== null;\n}\n\n/**\n * What the person wrote: a channel message's `text` without its leading\n * routing block and what the channel quoted ahead of the words. Any other\n * text comes back unchanged: a message without the envelope (tags someone\n * typed stay as typed), and text without a block. Safe on every user turn and\n * on its own output.\n */\nexport function inboundMessageBody({\n custom,\n text,\n}: {\n custom: Record<string, unknown> | null | undefined;\n text: string;\n}): string {\n if (!isInboundChannelMessage(custom)) return text;\n const context = leadingInboundContext(text);\n return context === null ? text : splitInboundBody(context).body;\n}\n\n/** An email's subject, from the envelope; `null` for any other message. */\nexport function inboundEmailSubject(custom: Record<string, unknown> | null | undefined): string | null {\n const envelope = envelopeOf(custom);\n if (envelope === null) return null;\n const channel = envelopeString(envelope, 'channel');\n return channel === 'email' || channel === 'agent_email' ? envelopeString(envelope, 'subject') : null;\n}\n"],"names":[],"mappings":"AA2BO,MAAM,sBAAsB;AAG5B,MAAM,uBAAuB;AAQpC,MAAM,kBAAkB;AAMxB,MAAM,2BAA2B;AACjC,MAAM,8BAA8B;AAG7B,MAAM,oBAAoB;AAa1B,SAAS,sBAAsB,MAA4C;AAChF,MAAI,CAAC,KAAK,WAAW,oBAAoB,EAAG,QAAO;AACnD,QAAM,QAAQ,gBAAgB,KAAK,IA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, typ
8
8
  export { CATEGORY_EMOJI, defaultToolDisplayMeta, describeDelegation, describeNamed, describePackage, describePath, describeQuery, describeRange, describeSql, describeTable, describeToolArgs, describeUrl, formatToolName, getCategoryEmoji, getToolDisplayMeta, hasToolDisplayMeta, isInlineTool, knownToolNames, TOOL_DISPLAY_META, type ToolArgsDescriber, type ToolCategory, toolActiveLabel, toolCompletedLabel, type ToolDisplayMeta, type ToolDisplayMetaEntry, type ToolIconKey, toolStatusLabel, type ToolStatusLabelState, truncateLine, } from "./tool-metadata";
9
9
  export { classifyToolResult, isRecord, isRejectedToolResult, isToolResultSuccess, parseJsonRecord, readRejectedToolResult, type RejectedToolResult, resultMessage, resultRecord, stringField, type ToolCallStatusLike, toolFailure, type ToolFailure, type ToolResultClassification, type ToolResultState, } from "./tool-result";
10
10
  export { type ConversationListController, useConversationList, type UseConversationListOptions, } from "./use-conversation-list";
11
- export { CLIENT_TOOL_RESULT_STATUS_ERROR, CLIENT_TOOL_RESULT_STATUS_SUCCESS, CLIENT_TOOL_RESULT_STATUSES, type ClientToolResultEnvelopeContract, type ClientToolResultStatus, DEEP_AGENT_CONTEXT_PROTOCOL, DEEP_AGENT_CUT_LANE_DOCUMENT, DEEP_AGENT_DEFAULT_MESSAGE_WINDOW, DEEP_AGENT_FOLLOW_TOOL_CALL_ID_KEY, DEEP_AGENT_INTEREST_PROTOCOL, DEEP_AGENT_LANE_CUT_PROTOCOL_VERSION, DEEP_AGENT_LANE_FOLLOW_PROTOCOL_VERSION, DEEP_AGENT_MAIN_NS, DEEP_AGENT_MAX_FOLLOWED_STEPS, DEEP_AGENT_MAX_LANE_PAGE, DEEP_AGENT_HISTORY_IMAGE_COMMAND, DEEP_AGENT_HISTORY_LANE_COMMAND, DEEP_AGENT_HISTORY_LANE_IMAGE_COMMAND, DEEP_AGENT_HISTORY_LANE_PAGE_CHARS, DEEP_AGENT_HISTORY_MESSAGE_COMMAND, DEEP_AGENT_HISTORY_TOOL_OUTPUT_COMMAND, DEEP_AGENT_INLINE_IMAGE_WIRE_BUDGET, DEEP_AGENT_MAX_INTERESTS, DEEP_AGENT_MAX_MESSAGE_WINDOW, DEEP_AGENT_MESSAGE_WINDOW_HEADER, DEEP_AGENT_MIN_MESSAGE_WINDOW, DEEP_AGENT_OMITTED_IMAGE_KEY, DEEP_AGENT_OMITTED_IMAGE_PLACEHOLDER_URL, DEEP_AGENT_PROTOCOL_STATE_KEY, DEEP_AGENT_PROTOCOL_VERSION, DEEP_AGENT_PROTOCOL_VERSION_HEADER, DEEP_AGENT_REPEATS_RESULT_KEY, DEEP_AGENT_RUNNING_LANE_WIRE_MESSAGES, DEEP_AGENT_RUNTIME_MARKER, DEEP_AGENT_TRUNCATED_CONTENT_KEY, DEEP_AGENT_TRUNCATED_LANE_KEY, KNOWN_START_CHANNEL_SET, KNOWN_START_CHANNELS, type KnownStartChannel, RUN_CONFIG_COMPANION_CUSTOM_KEYS, RUN_CONFIG_CUSTOM_KEY_SET, RUN_CONFIG_CUSTOM_KEYS, RUN_CONFIG_PARSED_CUSTOM_KEYS, RUN_CONFIG_PER_SEND_CUSTOM_KEY_SET, RUN_CONFIG_PER_SEND_CUSTOM_KEYS, type RunConfigCustomKey, type RunConfigPerSendCustomKey, DEEP_AGENT_CONFIG_COMMANDS, DEEP_AGENT_CONFIG_STATE_KEY, THREAD_CONFIG_CUSTOM_KEY_SET, THREAD_CONFIG_CUSTOM_KEYS, type ThreadConfigCustomKey, } from "./generated/runconfig-contract";
11
+ export { CLIENT_TOOL_RESULT_STATUS_ERROR, CLIENT_TOOL_RESULT_STATUS_SUCCESS, CLIENT_TOOL_RESULT_STATUSES, type ClientToolResultEnvelopeContract, type ClientToolResultStatus, DEEP_AGENT_CONTEXT_PROTOCOL, DEEP_AGENT_CUT_LANE_DOCUMENT, DEEP_AGENT_DEFAULT_MESSAGE_WINDOW, DEEP_AGENT_FOLLOW_TOOL_CALL_ID_KEY, DEEP_AGENT_INTEREST_PROTOCOL, DEEP_AGENT_LANE_CUT_PROTOCOL_VERSION, DEEP_AGENT_LANE_FOLLOW_PROTOCOL_VERSION, DEEP_AGENT_MAIN_NS, DEEP_AGENT_MAX_FOLLOWED_STEPS, DEEP_AGENT_MAX_LANE_PAGE, DEEP_AGENT_HISTORY_IMAGE_COMMAND, DEEP_AGENT_HISTORY_LANE_COMMAND, DEEP_AGENT_HISTORY_LANE_IMAGE_COMMAND, DEEP_AGENT_HISTORY_LANE_PAGE_CHARS, DEEP_AGENT_HISTORY_MESSAGE_COMMAND, DEEP_AGENT_HISTORY_PAGE_COMMAND, DEEP_AGENT_HISTORY_PAGE_PROTOCOL_VERSION, DEEP_AGENT_HISTORY_TOOL_OUTPUT_COMMAND, DEEP_AGENT_INLINE_IMAGE_WIRE_BUDGET, DEEP_AGENT_MAX_HELD_HEAD, DEEP_AGENT_MAX_HISTORY_PAGE_STEPS, DEEP_AGENT_MAX_HISTORY_PAGE_TURNS, DEEP_AGENT_MESSAGE_HISTORY_HEADER, DEEP_AGENT_MESSAGE_HISTORY_PAGED, DEEP_AGENT_MAX_INTERESTS, DEEP_AGENT_MAX_MESSAGE_WINDOW, DEEP_AGENT_MESSAGE_WINDOW_HEADER, DEEP_AGENT_MIN_MESSAGE_WINDOW, DEEP_AGENT_OMITTED_IMAGE_KEY, DEEP_AGENT_OMITTED_IMAGE_PLACEHOLDER_URL, DEEP_AGENT_PROTOCOL_STATE_KEY, DEEP_AGENT_PROTOCOL_VERSION, DEEP_AGENT_PROTOCOL_VERSION_HEADER, DEEP_AGENT_REPEATS_RESULT_KEY, DEEP_AGENT_RUNNING_LANE_WIRE_MESSAGES, DEEP_AGENT_RUNTIME_MARKER, DEEP_AGENT_TRUNCATED_CONTENT_KEY, DEEP_AGENT_TRUNCATED_LANE_KEY, KNOWN_START_CHANNEL_SET, KNOWN_START_CHANNELS, type KnownStartChannel, RUN_CONFIG_COMPANION_CUSTOM_KEYS, RUN_CONFIG_CUSTOM_KEY_SET, RUN_CONFIG_CUSTOM_KEYS, RUN_CONFIG_PARSED_CUSTOM_KEYS, RUN_CONFIG_PER_SEND_CUSTOM_KEY_SET, RUN_CONFIG_PER_SEND_CUSTOM_KEYS, type RunConfigCustomKey, type RunConfigPerSendCustomKey, DEEP_AGENT_CONFIG_COMMANDS, DEEP_AGENT_CONFIG_STATE_KEY, THREAD_CONFIG_CUSTOM_KEY_SET, THREAD_CONFIG_CUSTOM_KEYS, type ThreadConfigCustomKey, } from "./generated/runconfig-contract";
12
12
  export { COLLAB_AGENT_CHANNEL_SESSION_MISMATCH, CONVERSATION_ARCHIVED, CONVERSATION_ARCHIVED_MESSAGE, isConversationArchivedRejection, isLegacyThreadReadOnlyRejection, isStatewireChannelTeardown, isStatewireCommandAuthContextExpired, isStatewireExpiredVerdict, isStatewireRewindAnchorRejection, projectDeepAgentConnection, readRetryableCommandRejection, readRetryableRunRefusal, readRunStartRefusal, type RetryableCommandRejection, type RetryableRunRefusal, type RunStartRefusal, STATEWIRE_COMMAND_AUTH_CONTEXT_EXPIRED, statewireRejectionCode, isVoiceCommandRejection, statewireRejectionDetailMessage, statewireRejectionPayload, type StatewireRejectionPayload, statewireTransportOutcome, } from "./errors";
13
13
  export { type ParsedExecuteOutput, parseExecuteOutput, type ShellCommandSummary, summarizeShellCommand, } from "./execute-output";
14
- export { type AbandonedInputRequest, type ApprovalResumeLock, asHitlApproval, canApproveForSession, DEFAULT_INTERRUPT_PAUSED_MESSAGE, fanLaneDecision, findAbandonedInterrupt, HITL_PENDING_RESUME_GRACE_MS, HITL_REJECT_REASON, HITL_RESUME_TRANSPORT_RETRIES, type HitlActionDecision, type HitlApprovalPayload, actionRequestToolCallIds, hitlResumeActionDecisions, hitlResumeApprove, hitlResumeApproveForSession, INTERRUPT_DECLINE_REASON, interruptMirrorPayload, interruptResumeDecline, hitlResumeReject, isApprovalCardInterrupt, isPendingInterrupt, isResumeTransportLoss, isSystemPauseInterrupt, laneInterruptIds, type PendingActionRequest, type PendingApprovalContext, type PendingApprovalFact, type PendingApprovalTitle, type PendingApprovalWarning, parsePendingApprovalContext, pendingActionRequests, pendingApprovalTitle, readAbandonedInputRequests, readInterruptMessage, readInterruptMirror, readQueuedLaneDecisions, type ResumeExtras, resumeValueApproves, toolCallIdsAwaitingApproval, useApprovalResumeLock, type UseApprovalResumeLockOptions, } from "./interrupts";
14
+ export { type AbandonedInputRequest, type ApprovalResumeLock, asHitlApproval, canApproveForSession, DEFAULT_INTERRUPT_PAUSED_MESSAGE, fanLaneDecision, findAbandonedInterrupt, HITL_PENDING_RESUME_GRACE_MS, HITL_REJECT_REASON, HITL_RESUME_TRANSPORT_RETRIES, type HitlActionDecision, type HitlApprovalPayload, actionRequestToolCallIds, hitlResumeActionDecisions, hitlResumeApprove, hitlResumeApproveForSession, INTERRUPT_DECLINE_REASON, interruptMirrorPayload, interruptResumeDecline, hitlResumeReject, isApprovalCardInterrupt, isPendingInterrupt, isResumeTransportLoss, isSystemPauseInterrupt, laneInterruptIds, type PendingActionRequest, type PendingApprovalContext, type PendingApprovalFact, type PendingApprovalTitle, type PendingApprovalWarning, parsePendingApprovalContext, pendingActionRequests, pendingApprovalTitle, readAbandonedInputRequests, readInterruptMessage, readInterruptMirror, readQueuedLaneDecisions, type ResumeExtras, resumeValueApproves, type SessionApprovalOffer, sessionApprovalLabel, sessionApprovalOffer, toolCallIdsAwaitingApproval, useApprovalResumeLock, type UseApprovalResumeLockOptions, visibleText, } from "./interrupts";
15
15
  export { type AgoraFetch, bareDecisionThreadId, type BrowserDecisionCheckOutcome, DECISION_CHECK_HEADER, type DecisionCheckClient, type DecisionCheckClientKind, type DecisionCheckDescriptor, DecisionCheckKind, MAX_DECISIONS_PER_CHECK, type PendingBrowserDecisionCheck, respondDecisionDescriptor, type RunBrowserDecisionCheckOptions, runBrowserDecisionCheck, type StatewireAnswerForCheck, statewireAnswerDescriptors, } from "./decision-checks";
16
16
  export { buildQueueEditCommand, buildStatewireQueueRows, describeQueueSendFailure, isFailedSendEntryRace, isQueueEntryUnsettled, QUEUE_AUTO_CONTINUE_DELAY_MS, type QueueEditCommand, queueEntryText, queueLaneFlags, type QueueLaneFlags, readPrioritizedQueueIds, showQueueRowSendNow, showQueueRowSteer, type StatewireQueueRow, userStopBlocksQueueAutoContinue, } from "./queue";
17
17
  export { createDeepAgentSendRecovery, type DeepAgentSendRecovery, type DeepAgentSendRecoveryOptions, shouldAutoRetryFailedSend, } from "./send-recovery";
18
18
  export { hasStatewireThreadExtras, readStatewireFailedSendLane, requireStatewireFailedActions, type StatewireFailedActions, type StatewireFailedSendEntry, type StatewireFailedSendLane, } from "./thread-extras";
19
19
  export { applyRunErrorStatus, ATHENA_ERRORS_KEY, ATHENA_HANDOFF_KEY, ATHENA_QUEUED_LANE_KEY, ATHENA_RUN_MARKER_CANCELLED, ATHENA_RUN_MARKER_FAILED, ATHENA_RUN_MARKER_KEY, ATHENA_RUN_MARKER_SOURCE_KEY, ATHENA_STOP_SOURCE_INSTANCE_CLOSED, ATHENA_STOP_SOURCE_POD_DRAIN, ATHENA_STOP_SOURCE_SEND_NOW, ATHENA_STOP_SOURCE_VOICE_STEER, ATHENA_TERMINATION_REASON_KEY, convertDeepAgentLangChainMessage, convertDeepAgentState, type ConvertDeepAgentStateOptions, type DeepAgentMessageConversionOptions, createDeepAgentMaterialize, createDeepAgentMessageConversionCache, type DeepAgentConversionMemory, deepAgentMaterialize, type DeepAgentMaterializeOptions, DeepAgentMessageConversionCache, deepAgentRowKey, isConvertibleChatMessage, isDrainRunMarker, isLangGraphState, isMessageHiddenFromFrontend, isQueuedLaneMessage, isServerUpdateStopSource, isSilentRunMarker, laneTailMessages, liftBranchIntoMetadata, liftCompactionBoundaryIntoMetadata, liftConversationStatsIntoMetadata, liftErrorsIntoMetadata, liftHandoffSummaryIntoMetadata, liftModelIntoMetadata, liftPlaceInstructionsIntoMetadata, liftRunMarkerIntoMetadata, liftTerminationIntoMetadata, liftToolMessageMetadataIntoArtifact, liftTruncatedToolOutputIntoArtifact, convertDeepAgentMessage, markPreliminaryToolResults, messageConverter, nativeStepUsage, PENDING_ASSISTANT_MESSAGE_ID, PLACE_INSTRUCTIONS_STAMP_KEY, readMessageErrorsFromSourceMessages, readRunMarkerFromSourceMessages, readSoleRunMarker, type RunMarkerInfo, sanitizeLangChainMessages, substituteToolOutput, withPendingAssistantMessage, } from "./messages";
20
- export { ATHENA_TRUNCATED_TOOL_OUTPUT_ARTIFACT_KEY, buildHistoryMessageCommand, buildToolOutputCommand, clampMessageWindowSize, type DeepAgentInterestChainEntry, type DeepAgentInterestDeclaration, type DeepAgentInterestRequest, type DeepAgentInterestResolution, type DeepAgentMessageWindow, type DeepAgentMessageWindowDeclaration, headInterestRequest, type HistoryMessageCommand, type HistoryMessageResult, messageWindowCarries, pageInterestRequest, pageInterestRequests, readDeepAgentInterestDeclaration, readDeepAgentInterestDocument, readDeepAgentInterestResolution, readDeepAgentMessageWindow, readHistoryMessageResult, readToolOutputResult, readTruncatedToolContent, readTruncatedToolOutputArtifact, restatedInterestRequests, type ToolOutputCommand, type ToolOutputResult, type TruncatedToolContent, type TruncatedToolOutputArtifact, withDeclaredInterests, withDeclaredMessageWindow, } from "./message-window";
20
+ export { ATHENA_TRUNCATED_TOOL_OUTPUT_ARTIFACT_KEY, buildHistoryMessageCommand, buildToolOutputCommand, clampMessageWindowSize, type DeepAgentInterestChainEntry, type DeepAgentInterestDeclaration, type DeepAgentInterestRequest, type DeepAgentInterestResolution, type DeepAgentMessageWindow, type DeepAgentMessageWindowDeclaration, headInterestRequest, type HistoryMessageCommand, type HistoryMessageResult, messageWindowCarries, pageInterestRequest, pageInterestRequests, readDeepAgentInterestDeclaration, readDeepAgentInterestDocument, readDeepAgentInterestResolution, readDeepAgentMessageWindow, readHistoryMessageResult, readToolOutputResult, readTruncatedToolContent, readTruncatedToolOutputArtifact, restatedInterestRequests, type ToolOutputCommand, type ToolOutputResult, type TruncatedToolContent, type TruncatedToolOutputArtifact, type ReadDeepAgentMessageWindowOptions, withDeclaredInterests, withDeclaredMessageWindow, } from "./message-window";
21
+ export { buildHistoryPageCommand, buildTurnStepsCommand, clearDeepAgentHistoryStores, createDeepAgentHistoryStore, DEEP_AGENT_HISTORY_PAGE_TURNS, DEEP_AGENT_HISTORY_STORE_LIMIT, DEEP_AGENT_TURN_STEPS_KEY, DEEP_AGENT_TURN_STEPS_PAGE, type DeepAgentHistoryOlder, type DeepAgentHistoryPage, type DeepAgentHistorySend, type DeepAgentHistoryStore, type DeepAgentHistorySummarizedTurn, type DeepAgentHistoryTurnSteps, type DeepAgentTurnStepsMarker, type DeepAgentTurnStepsPage, deepAgentHistoryStore, deepAgentHistoryVersion, type HistoryPageCommand, historyPageAsInterestRequest, hostServesHistoryPage, isHistoryPageUnserved, isLoadingDeepAgentTurnSteps, loadDeepAgentTurnSteps, peekDeepAgentHistoryStore, readHistoryPageResult, readTurnStepsMarker, readTurnStepsResult, subscribeDeepAgentHistory, type TurnStepsCommand, withDeclaredPagedHistory, } from "./history-store";
21
22
  export { buildHistoryLaneCommand, type DeepAgentLaneHistoryState, type DeepAgentLaneTarget, deepAgentLaneHistoryQueryKey, type HistoryLaneCommand, type HistoryLanePage, isWholeCardRefusal, mergeLaneHistory, readHistoryLanePage, useDeepAgentLaneHistory, } from "./lane-history";
22
23
  export { buildHistoryLaneImageCommand, type DeepAgentLaneImagesState, deepAgentLaneImageQueryKey, type HistoryLaneImageChunk, type HistoryLaneImageCommand, type InlineImage, type InlineImageChunk, type LaneImageRef, laneImageKey, omittedLaneImages, readChunkedInlineImage, readHistoryLaneImageChunk, readInlineImageChunk, readLaneImage, readLaneImageTile, showLaneImages, useDeepAgentLaneImages, } from "./lane-images";
23
24
  export { createDeepAgentLaneFollowRegistry, type DeepAgentLaneFollowRegistry, type DeepAgentLaneFollowRequest, type DeepAgentLaneFollows, isLaneFollowRequest, laneFollowRequest, mergeFollowedLane, readDeepAgentFollowedWindow, readDeepAgentLaneFollows, useDeepAgentLaneFollow, useDeepAgentLaneFollowSync, type UseDeepAgentLaneFollowSyncOptions, } from "./lane-follow";
24
25
  export { buildDeepAgentEditCommand, deepAgentHistoryHasOlder, type DeepAgentPreparedMessageMetadata, type DeepAgentStatewireExtras, isHistoryPageLostToReconnect, isSourceBelowLoadedWindow, loadOlderDeepAgentHistoryPage, MAX_EDIT_ANCHOR_HISTORY_LOADS, readDeepAgentStatewireExtras, resolveDeepAgentEditCommand, resolveWireAnchorMessageId, } from "./edit-command";
25
- export { buildHistoryPageCommand, buildTurnStepsCommand, createDeepAgentHistoryStore, DEEP_AGENT_HISTORY_PAGE_TURNS, DEEP_AGENT_HISTORY_START_KEY, DEEP_AGENT_TURN_STEPS_KEY, DEEP_AGENT_TURN_STEPS_PAGE, type DeepAgentHistoryPageAnswer, type DeepAgentHistorySend, type DeepAgentHistorySnapshot, type DeepAgentHistoryStore, type DeepAgentHistoryTurn, type DeepAgentHistoryTurnSteps, type DeepAgentHistoryTurnStepsLoaded, type DeepAgentTurnStepsAnswer, type DeepAgentTurnStepsMarker, type HistoryPageCommand, isDeepAgentHistoryAtStart, isDeepAgentHistoryDetached, joinDeepAgentHistory, readHistoryPageAnswer, readTurnStepsAnswer, readTurnStepsMarker, type TurnStepsCommand, } from "./history-pages";
26
- export { DEEP_AGENT_MAX_CHAINED_HISTORY_LOADS, type DeepAgentHistoryLoadEvent, type DeepAgentHistoryPageEvent, type DeepAgentWindowSyncMessage, type DeepAgentWindowSyncState, useDeepAgentMessageWindow, useDeepAgentWindowSync, type UseDeepAgentWindowSyncOptions, } from "./use-deep-agent-window-sync";
26
+ export { DEEP_AGENT_MAX_CHAINED_HISTORY_LOADS, type DeepAgentHistoryLoadEvent, type DeepAgentWindowSyncMessage, type DeepAgentWindowSyncState, useDeepAgentMessageWindow, useDeepAgentWindowSync, type UseDeepAgentWindowSyncOptions, } from "./use-deep-agent-window-sync";
27
27
  export { useDeepAgentMessageEditSubmit } from "./use-deep-agent-edit-submit";
28
28
  export { createDeepAgentToolOutputStore, type DeepAgentToolOutputEntry, type DeepAgentToolOutputStore, type DeepAgentToolOutputStoreOptions, } from "./tool-outputs";
29
29
  export { claimDeepAgentFailedSendText, type DeepAgentFailedSend, type DeepAgentWithdrawableTurn, type DeepAgentWithdrawnFromRun, type DeepAgentWithdrawnTurns, type DeepAgentWithdrawnTurnVerdict, readDeepAgentFailedSends, readDeepAgentWithdrawableTurn, readDeepAgentWithdrawnTurnVerdict, } from "./withdrawn-turns";
@@ -74,6 +74,7 @@ export { CALL_RECAP_APPROVAL_LABEL, CALL_RECAP_TITLE, type CallRecap, type CallR
74
74
  export { canPersistDeepAgentSession, type DeepAgentPendingSession, type DeepAgentRunConfigRegistration, type DeepAgentSessionPersistence, type DeepAgentThreadElement, type DeepAgentThreadStateClientHost, logUnhandledStatewireError, useDeepAgentRuntime, type UseDeepAgentRuntimeOptions, } from "./use-deep-agent-runtime";
75
75
  export { type DeepAgentAttachSource, type DeepAgentHeadersResolver, readSessionPersisted, type RunningSnapshot, shouldNotifyRunningChange, useDeepAgentThread, type UseDeepAgentThreadOptions, } from "./use-deep-agent-thread";
76
76
  export { GITHUB_EVENT_SOURCE_KEY, type GithubWakeEvent, githubWakeEventLabel, githubWakeEventUrl, githubWakeMarkerText, githubWakeReference, isGithubWakeMessage, readGithubWakeEvent, } from "./github-wake-event";
77
+ export { GROUP_TEXT_SOURCE, INBOUND_CHANNEL_KEY, INBOUND_CONTEXT_CLOSE, INBOUND_CONTEXT_OPEN, inboundContextValue, inboundEmailSubject, inboundMessageBody, isInboundChannelMessage, type LeadingInboundContext, leadingInboundContext, splitInboundBody, stripInboundContext, } from "./inbound-channel";
77
78
  export { githubSubscriptionHeadline, isSubscriptionWakeMessage, readSubscriptionWakeEvent, SUBSCRIPTION_EVENT_KEY, type SubscriptionWakeChange, type SubscriptionWakeEvent, type SubscriptionWakeGithub, subscriptionPlaceWords, subscriptionWakeDetail, subscriptionWakeGithub, subscriptionWakeHeadline, } from "./subscription-wake-event";
78
79
  export { describeTerminationReason, readRuntimeMessageFromSourceMessages, readSoleRuntimeMessageKind, readTerminationReason, runtimeMessageMarkerText, TERMINATION_REASONS, type AthenaRuntimeMessage, type AthenaRuntimeMessageKind, type AthenaRuntimeMessageSeverity, type AthenaTerminationReason, type TerminationDescription, } from "./runtime-messages";
79
80
  export { buildHandoffQrSvg, buildMobileHandoffSchemeUrl, classifyHandoffTransportError, type CreateThreadHandoffInput, type CreateThreadHandoffResponse, createThreadHandoffResponseSchema, describeHandoffTransportError, type DestinationReadiness, HANDOFF_DESTINATION_LABELS, HANDOFF_DESTINATIONS, HANDOFF_EXPIRY_GRACE_MS, HANDOFF_TICKET_LIFETIME_MS, HANDOFF_URL_PARAM, type HandoffDestination, type HandoffDestinationPresentation, type HandoffEnvironment, HandoffGoneError, type HandoffLaunch, type HandoffOutcome, HandoffPermanentError, type HandoffReadinessResponse, type HandoffReadinessState, type HandoffSource, type HandoffState, type HandoffTransportErrorKind, handoffHttpError, handoffReadinessResponseSchema, handoffStateSchema, handoffTicketLifetimeMs, isHandoffGoneError, isHandoffPermanentError, isRetryableHandoffHttpStatus, isOfficeHandoffDestination, isServerHandoffDestination, isTerminalHandoffState, type MobileHandoffLaunch, type MobileLaunchMode, mobileHandoffLaunchSchema, OFFICE_HANDOFF_DESTINATIONS, type OfficeHandoffDestination, type OfficeHandoffLaunch, officeHandoffLaunchSchema, type OfficeInvitationLaunch, officeInvitationLaunchSchema, type OfficeLaunchMode, officeLaunchModeSchema, threadHandoffCreateBody, parseHandoffIdParam, presentHandoffDestination, readinessByDestination, SERVER_HANDOFF_DESTINATIONS, type ServerHandoffDestination, selectMobileLaunchMode, supportsDesktopHandoffSource, type ThreadHandoffTransport, type ThreadHandoffView, threadHandoffViewSchema, waitForHandoffOutcome, type WaitForHandoffOutcomeOptions, type ClaimThreadHandoffResponse, claimThreadHandoffResponseSchema, clampHandoffDraft, handoffDraftToCarry, continuedFromLabel, pickUpFromLabel, pickUpOfferLabel, type DesktopThreadHandoffLaunch, desktopThreadHandoffLaunchSchema, driverSurfaceForChannel, drivingOnLabel, type HandoffLanding, handoffLandingFromView, isPickupSurface, MAX_HANDOFF_DRAFT_LENGTH, nextHandoffLaunchSchema, parseThreadHandoffCreateResponse, pendingThreadHandoffResponseSchema, pickedUpOnLabel, PICKUP_SURFACES, type PickupSurface, shouldOfferPendingHandoff, IMPLICIT_PICKUP_ACTIVATION_WINDOW_MS, IMPLICIT_PICKUP_DECLINE_HOLD_MS, type ImplicitPickupAnswer, type ImplicitPickupContext, implicitPickupAllowed, isImplicitHandoff, nextImplicitPickupAnswer, SPACES_HANDOFF_URL_PARAM, type SpacesHandoffLaunch, spacesHandoffLaunchSchema, SURFACE_HANDOFF_DESTINATIONS, type SurfaceHandoffDestination, supportsSurfaceHandoffDestinations, THREAD_HANDOFF_DESTINATION_LABELS, THREAD_HANDOFF_DESTINATIONS, threadHandoffClaimBody, threadHandoffCreateRequest, type ThreadHandoffDestination, type ThreadHandoffReceiverTransport, MAX_PENDING_EXCLUDE, handoffDeclineKey, pendingExcludeIds, pickupExcludeIds, pendingHandoffPath, type HandoffMode, handoffModeSchema, isVoiceHandoffDestination, MAX_HANDOFF_CURSOR_LENGTH, parseHandoffCursor, supportsHandoffCursor, livenessAgo, presentSurfaceLiveness, type SurfaceLiveness, type SurfaceLivenessBasis, surfaceLivenessBasisSchema, surfaceLivenessBySurface, type SurfaceLivenessPresentation, surfaceLivenessSchema, type SurfaceLivenessState, surfaceLivenessStateSchema, type SurfaceLivenessTone, supportsSurfaceLiveness, } from "./thread-handoff";
@@ -87,12 +87,16 @@ function pendingActionRequests(hitl) {
87
87
  const requests = Array.isArray(context.action_requests) ? context.action_requests.filter(isRecord) : context.tool_name && context.tool_args ? [{ name: context.tool_name, args: context.tool_args, tool_call_id: context.tool_call_id }] : [];
88
88
  return requests.map((request) => {
89
89
  const approvalContext = parsePendingApprovalContext(request.approval_context);
90
+ const sessionApprovalRecipients = parseSessionApprovalRecipients(
91
+ request.session_approval_recipients
92
+ );
90
93
  return {
91
94
  name: typeof request.name === "string" ? request.name : "tool",
92
95
  args: isRecord(request.args) ? request.args : {},
93
96
  ...typeof request.tool_call_id === "string" && { toolCallId: request.tool_call_id },
94
97
  ...typeof request.interrupt_id === "string" && { interruptId: request.interrupt_id },
95
98
  ...request.session_approval_allowed === true && { sessionApprovalAllowed: true },
99
+ ...sessionApprovalRecipients && { sessionApprovalRecipients },
96
100
  ...Array.isArray(request.allowed_decisions) && request.allowed_decisions.includes("edit") && { editAllowed: true },
97
101
  ...approvalContext && { approvalContext }
98
102
  };
@@ -111,8 +115,44 @@ function pendingApprovalTitle({
111
115
  if ((envelope == null ? void 0 : envelope.headline) === void 0) return void 0;
112
116
  return envelope.summary === void 0 ? { headline: envelope.headline } : { headline: envelope.headline, summary: envelope.summary };
113
117
  }
114
- function canApproveForSession(actionRequests) {
115
- return actionRequests.length > 0 && actionRequests.every((request) => request.sessionApprovalAllowed === true);
118
+ function visibleText(text) {
119
+ return text.replace(
120
+ /[\p{C}\p{Z}]/gu,
121
+ (character) => character === " " ? character : `<U+${(character.codePointAt(0) ?? 0).toString(16).toUpperCase().padStart(4, "0")}>`
122
+ );
123
+ }
124
+ function parseSessionApprovalRecipients(value) {
125
+ if (!Array.isArray(value) || value.length === 0) return void 0;
126
+ const names = [];
127
+ for (const name of value) {
128
+ if (typeof name !== "string" || name.trim() === "") return void 0;
129
+ names.push(visibleText(name));
130
+ }
131
+ return names;
132
+ }
133
+ function sessionApprovalOffer(actionRequests) {
134
+ if (actionRequests.length === 0) return void 0;
135
+ if (actionRequests.every(
136
+ (request) => request.sessionApprovalAllowed === true && request.sessionApprovalRecipients === void 0
137
+ )) {
138
+ return { kind: "tools" };
139
+ }
140
+ const recipients = [];
141
+ for (const request of actionRequests) {
142
+ if (request.sessionApprovalRecipients === void 0) return void 0;
143
+ for (const name of request.sessionApprovalRecipients) {
144
+ if (!recipients.includes(name)) recipients.push(name);
145
+ }
146
+ }
147
+ return { kind: "recipients", recipients };
148
+ }
149
+ function namesInProse(names) {
150
+ if (names.length <= 1) return names.join("");
151
+ return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
152
+ }
153
+ function sessionApprovalLabel(offer) {
154
+ if (offer.kind === "tools") return "Approve all for this session";
155
+ return `Approve for this session: only ${namesInProse(offer.recipients)}`;
116
156
  }
117
157
  function readAbandonedInputRequests(state) {
118
158
  const abandoned = statewireState.readDeepAgentStreamValues(state).abandonedInputRequests;
@@ -332,7 +372,6 @@ exports.HITL_RESUME_TRANSPORT_RETRIES = HITL_RESUME_TRANSPORT_RETRIES;
332
372
  exports.INTERRUPT_DECLINE_REASON = INTERRUPT_DECLINE_REASON;
333
373
  exports.actionRequestToolCallIds = actionRequestToolCallIds;
334
374
  exports.asHitlApproval = asHitlApproval;
335
- exports.canApproveForSession = canApproveForSession;
336
375
  exports.fanLaneDecision = fanLaneDecision;
337
376
  exports.findAbandonedInterrupt = findAbandonedInterrupt;
338
377
  exports.hitlResumeActionDecisions = hitlResumeActionDecisions;
@@ -354,6 +393,9 @@ exports.readInterruptMessage = readInterruptMessage;
354
393
  exports.readInterruptMirror = readInterruptMirror;
355
394
  exports.readQueuedLaneDecisions = readQueuedLaneDecisions;
356
395
  exports.resumeValueApproves = resumeValueApproves;
396
+ exports.sessionApprovalLabel = sessionApprovalLabel;
397
+ exports.sessionApprovalOffer = sessionApprovalOffer;
357
398
  exports.toolCallIdsAwaitingApproval = toolCallIdsAwaitingApproval;
358
399
  exports.useApprovalResumeLock = useApprovalResumeLock;
400
+ exports.visibleText = visibleText;
359
401
  //# sourceMappingURL=interrupts.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"interrupts.cjs","sources":["../../../../agent-runtime/src/interrupts.ts"],"sourcesContent":["/**\n * Human-in-the-loop interrupt primitives shared by every statewire chat\n * surface (Olympus, the React SDK, the Office add-in, the Chrome extension,\n * mobile).\n *\n * The agora deep-agent runtime parks a gated run on an `interrupt` input\n * request whose payload carries the Athena `hitl_approval` shape\n * (`athena_deep_agent/hitl_bridge.py`). A surface answers it with\n * `{ type: 'run/input', requestId, response: { type: 'resume', value } }` —\n * the exact command the backend's resume path consumes. This module holds the\n * payload contract (narrowing, resume values) and the shared resume-lock state\n * machine; rendering stays with each surface.\n *\n * Deliberately parameterized rather than self-wiring: these helpers never call\n * `useStatewireRuns`/`useAuiState` themselves. Each surface reads its own\n * statewire hooks (which its tests already mock) and passes the values in, so\n * the shared semantics cannot drift while per-surface wiring stays testable.\n */\n\nimport type { StatewireThread } from '@assistant-ui/react-statewire';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { hasClientToolInterruptSource } from './client-tools';\nimport { statewireTransportOutcome } from './errors';\nimport { readDeepAgentStreamValues } from './statewire-state';\n\n/** Human-in-the-loop approval payload the agora deep-agent runtime parks a run\n * on (shaped by `athena_deep_agent/hitl_bridge.py`). */\nexport interface HitlApprovalPayload {\n source: string;\n type: string;\n message: string;\n /** Risk headline/facts/warnings, when the host includes them. */\n approval_context?: unknown;\n context?: {\n tool_name?: string;\n tool_id?: string;\n tool_call_id?: string;\n tool_args?: Record<string, unknown>;\n pending_action_count?: number;\n approval_context?: unknown;\n /**\n * Every pending gated call (name + args), in decision order. Absent on\n * older backends — fall back to the single `tool_name`/`tool_args` pair.\n * Per-dispatch payloads also carry each lane's `tool_call_id` (the lane\n * card key) and `interrupt_id` (the lane resume key).\n */\n action_requests?: {\n name?: string;\n args?: Record<string, unknown>;\n tool_call_id?: string;\n interrupt_id?: string;\n /**\n * True when \"approve all for this session\" would take effect for this\n * tool (the workspace allows overriding its approval). Absent on older\n * backends and on non-overridable tools: the option is not offered.\n */\n session_approval_allowed?: boolean;\n /**\n * The decision types the parked gate accepts for this call (`approve`,\n * `reject`, `edit`). Absent on older backends: only approve / reject\n * are known to be accepted.\n */\n allowed_decisions?: string[];\n /** What the backend resolved about this call before asking (display-only). */\n approval_context?: unknown;\n }[];\n /**\n * True when each dispatch parked on its own interrupt: decisions submit\n * per lane via `lane_decisions` and each approved lane starts immediately,\n * instead of the legacy batch where one resume must answer every lane.\n */\n per_dispatch?: boolean;\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** A pending `interrupt` input request; a present `response` key marks it answered. */\nexport function isPendingInterrupt(\n request: StatewireThread.InputRequestState,\n): request is StatewireThread.CustomInputRequest {\n return request.type === 'interrupt' && !('response' in request);\n}\n\n/**\n * Interrupt sources that were system pauses before the host stamped\n * `requires_user_action: false` on them (a background deep-research wait). Kept\n * only for the deploy skew between an older agora and a newer client; delete\n * once every deployment's raiser stamps the flag.\n */\nconst LEGACY_SYSTEM_PAUSE_INTERRUPT_SOURCES: ReadonlySet<string> = new Set(['deep_research_pending']);\n\n/**\n * A park nobody answers: the agent is still working (a background research\n * wait) and the backend resumes it itself. The raiser stamps\n * `requires_user_action: false`; older raisers are recognised by source.\n */\nexport function isSystemPauseInterrupt(payload: unknown): boolean {\n if (!isRecord(payload)) return false;\n if (payload.requires_user_action === false) return true;\n return (\n typeof payload.source === 'string' && LEGACY_SYSTEM_PAUSE_INTERRUPT_SOURCES.has(payload.source)\n );\n}\n\n/**\n * A pending interrupt an approval card may answer. Two kinds are excluded —\n * client-tool parks (the client-tool bridge owns those, and a generic resume\n * would corrupt the parked tool call) and system pauses (nothing to answer; the\n * backend resumes them). The source checks are deliberately loose so a skewed\n * deploy can never route one here.\n */\nexport function isApprovalCardInterrupt(\n request: StatewireThread.InputRequestState,\n): request is StatewireThread.CustomInputRequest {\n if (!isPendingInterrupt(request)) return false;\n const payload = (request as { payload?: unknown }).payload;\n return !hasClientToolInterruptSource(payload) && !isSystemPauseInterrupt(payload);\n}\n\n/** Narrow an interrupt payload to the Athena HITL approval shape. */\nexport function asHitlApproval(value: unknown): HitlApprovalPayload | null {\n if (!isRecord(value)) return null;\n return value.type === 'hitl' &&\n value.source === 'hitl_approval' &&\n typeof value.message === 'string'\n ? (value as unknown as HitlApprovalPayload)\n : null;\n}\n\n/** Default paused-run copy when an interrupt payload carries no message. */\nexport const DEFAULT_INTERRUPT_PAUSED_MESSAGE =\n 'The agent is paused and waiting for input.';\n\n/** Best-effort human-readable message from any interrupt payload. */\nexport function readInterruptMessage(\n value: unknown,\n fallback: string = DEFAULT_INTERRUPT_PAUSED_MESSAGE,\n): string {\n if (isRecord(value) && typeof value.message === 'string' && value.message.length > 0) {\n return value.message;\n }\n return fallback;\n}\n\n/** One label/value row of a call's resolved approval facts. */\nexport interface PendingApprovalFact {\n label: string;\n value: string;\n}\n\n/** One caution of a call's resolved approval facts. */\nexport interface PendingApprovalWarning {\n severity: 'info' | 'warning' | 'critical';\n message: string;\n}\n\nexport interface PendingApprovalSlackTarget {\n catalog_id: string;\n conversation_id: string | null;\n thread_ts: string | null;\n team_url: string | null;\n people: string[];\n}\n\n/**\n * What the backend resolved about a gated call before asking — e.g. where a\n * Slack write goes and as whom (agora `services/interrupts/approval_context.py`).\n * Display-only; the decision still answers the parked call.\n */\nexport interface PendingApprovalContext {\n facts: PendingApprovalFact[];\n warnings: PendingApprovalWarning[];\n /** The question the approval asks, in a line (\"Use Studio Mac in this conversation?\"). */\n headline?: string;\n /** What approving lets happen, a sentence or two under the headline. */\n summary?: string;\n slack_target?: PendingApprovalSlackTarget;\n}\n\nconst APPROVAL_WARNING_SEVERITIES = new Set(['info', 'warning', 'critical']);\n\nfunction isNullableString(value: unknown): value is string | null {\n return value === null || typeof value === 'string';\n}\n\n/** Display text: a string, trimmed; a blank or anything that is not a string is absent. */\nfunction displayText(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const text = value.trim();\n return text.length > 0 ? text : undefined;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((entry) => typeof entry === 'string');\n}\n\nfunction parsePendingApprovalSlackTarget(value: unknown): PendingApprovalSlackTarget | undefined {\n if (!isRecord(value) || typeof value.catalog_id !== 'string') return undefined;\n const conversationId = value.conversation_id;\n const threadTs = value.thread_ts;\n const teamUrl = value.team_url;\n const people = value.people === undefined ? [] : value.people;\n if (\n !isNullableString(conversationId) ||\n !isNullableString(threadTs) ||\n !isNullableString(teamUrl) ||\n !isStringArray(people)\n )\n return undefined;\n return {\n catalog_id: value.catalog_id,\n conversation_id: conversationId,\n thread_ts: threadTs,\n team_url: teamUrl,\n people,\n };\n}\n\n/** A call's `approval_context`, or `undefined` when absent or empty. */\nexport function parsePendingApprovalContext(value: unknown): PendingApprovalContext | undefined {\n if (!isRecord(value)) return undefined;\n const facts: PendingApprovalFact[] = Array.isArray(value.facts)\n ? value.facts.flatMap((fact) =>\n isRecord(fact) && typeof fact.label === 'string' && typeof fact.value === 'string'\n ? [{ label: fact.label, value: fact.value }]\n : [],\n )\n : [];\n const warnings: PendingApprovalWarning[] = Array.isArray(value.warnings)\n ? value.warnings.flatMap((warning) => {\n if (!isRecord(warning) || typeof warning.message !== 'string') return [];\n const severity =\n typeof warning.severity === 'string' && APPROVAL_WARNING_SEVERITIES.has(warning.severity)\n ? (warning.severity as PendingApprovalWarning['severity'])\n : 'info';\n return [{ severity, message: warning.message }];\n })\n : [];\n const headline = displayText(value.headline);\n const summary = displayText(value.summary);\n const slackTarget = parsePendingApprovalSlackTarget(value.slack_target);\n return facts.length > 0 || warnings.length > 0 || headline || summary || slackTarget\n ? {\n facts,\n warnings,\n ...(headline ? { headline } : {}),\n ...(summary ? { summary } : {}),\n ...(slackTarget ? { slack_target: slackTarget } : {}),\n }\n : undefined;\n}\n\nexport interface PendingActionRequest {\n name: string;\n args: Record<string, unknown>;\n /** The lane's `task` tool-call id (present on per-dispatch payloads). */\n toolCallId?: string;\n /** The lane's langgraph interrupt id — the `lane_decisions` resume key. */\n interruptId?: string;\n /** Present (true) when a session-wide approval would cover later calls of this tool. */\n sessionApprovalAllowed?: true;\n /** Present (true) when the gate accepts an `edit` decision for this call. */\n editAllowed?: true;\n /** Present when the backend resolved anything about this call before asking (facts, a headline). */\n approvalContext?: PendingApprovalContext;\n}\n\n/**\n * Every gated call this approval covers, in decision order. One resume answers\n * ALL of them, so every entry must stay reviewable somewhere. Falls back to\n * the single first-call fields on older backends without `action_requests`.\n */\nexport function pendingActionRequests(hitl: HitlApprovalPayload | null): PendingActionRequest[] {\n const context = hitl?.context;\n if (!context) return [];\n // The payload crosses the wire with only its top-level shape narrowed\n // (`asHitlApproval`), so the nested collection must be validated before any\n // array/property access: a malformed host value must degrade to \"no\n // reviewable entries\", never crash the approval surface.\n const requests: Record<string, unknown>[] = Array.isArray(context.action_requests)\n ? context.action_requests.filter(isRecord)\n : context.tool_name && context.tool_args\n ? [{ name: context.tool_name, args: context.tool_args, tool_call_id: context.tool_call_id }]\n : [];\n return requests.map((request) => {\n const approvalContext = parsePendingApprovalContext(request.approval_context);\n return {\n name: typeof request.name === 'string' ? request.name : 'tool',\n args: isRecord(request.args) ? request.args : {},\n ...(typeof request.tool_call_id === 'string' && { toolCallId: request.tool_call_id }),\n ...(typeof request.interrupt_id === 'string' && { interruptId: request.interrupt_id }),\n ...(request.session_approval_allowed === true && { sessionApprovalAllowed: true }),\n ...(Array.isArray(request.allowed_decisions) &&\n request.allowed_decisions.includes('edit') && { editAllowed: true }),\n ...(approvalContext && { approvalContext }),\n };\n });\n}\n\n/** The headline (and summary) that title a pending approval in place of the generic copy. */\nexport interface PendingApprovalTitle {\n headline: string;\n summary?: string;\n}\n\n/**\n * The title of a pending approval: the headline and summary of its one gated\n * call's resolved envelope (the call's own `approval_context`, else the copy\n * the host lifted to `context.approval_context`). A batch has none: one\n * decision answers every call, so no one call's headline may speak for it.\n * Display-only, like the envelope.\n */\nexport function pendingApprovalTitle({\n hitl,\n actionRequests,\n}: {\n hitl: HitlApprovalPayload | null;\n actionRequests: readonly PendingActionRequest[];\n}): PendingApprovalTitle | undefined {\n const [call, ...others] = actionRequests;\n if (hitl === null || call === undefined || others.length > 0) return undefined;\n // An older backend lists only the first call and counts the rest here; a\n // count that is not plainly one keeps the generic copy.\n const pendingCount = hitl.context?.pending_action_count;\n if (pendingCount !== undefined && pendingCount !== 1) return undefined;\n const envelope =\n call.approvalContext ?? parsePendingApprovalContext(hitl.context?.approval_context);\n if (envelope?.headline === undefined) return undefined;\n return envelope.summary === undefined\n ? { headline: envelope.headline }\n : { headline: envelope.headline, summary: envelope.summary };\n}\n\n/**\n * Whether the card may offer \"approve all for this session\": every pending\n * call must be one the backend stamped as session-approvable, so a batch that\n * mixes in a tool the workspace pinned as always-prompt only offers the\n * one-time answer.\n */\nexport function canApproveForSession(actionRequests: readonly PendingActionRequest[]): boolean {\n return (\n actionRequests.length > 0 &&\n actionRequests.every((request) => request.sessionApprovalAllowed === true)\n );\n}\n\n/** An interrupt a non-resume dispatch dropped, published by the host. */\nexport interface AbandonedInputRequest {\n id: string;\n type: string;\n}\n\n/**\n * `useStatewireState` selector body for the host-published abandoned input\n * requests. Reads through {@link readDeepAgentStreamValues} so the selector is\n * safe on the pre-attach (`undefined`) wire state, and returns the raw array\n * reference so the subscription stays shallow-stable — derive (`.find`) on the\n * result, never inside the selector.\n */\nexport function readAbandonedInputRequests(\n state: unknown,\n): readonly AbandonedInputRequest[] | undefined {\n const abandoned = readDeepAgentStreamValues(state).abandonedInputRequests;\n // Wire value: anything non-array (including a malformed host publication)\n // reads as \"none\" rather than crashing the consuming surface. Identity-\n // preserving for the valid case, so it stays selector-safe.\n return Array.isArray(abandoned)\n ? (abandoned as readonly AbandonedInputRequest[])\n : undefined;\n}\n\n/**\n * `useStatewireState` selector body for the host's mirrored interrupt\n * (`__interrupt__`, the LangGraph `{value, resumable}` wrapper). The mirror\n * is published the moment a lane parks on its gate — while sibling lanes are\n * still streaming and the run manager has NOT yet published an answerable\n * input request. Raw reference, selector-safe; unwrap with\n * {@link interruptMirrorPayload}.\n */\nexport function readInterruptMirror(state: unknown): unknown {\n return readDeepAgentStreamValues(state).__interrupt__;\n}\n\n/** The payload of a mirrored interrupt wrapper, or `undefined` for anything else. */\nexport function interruptMirrorPayload(mirror: unknown): unknown {\n return isRecord(mirror) ? mirror.value : undefined;\n}\n\n/**\n * `useStatewireState` selector body for the per-dispatch lane decisions the\n * host accepted through `run/lane-input` while the run was still streaming\n * (`queuedLaneDecisions`, keyed by langgraph interrupt id). Held until the\n * run parks, then answered as a native `lane_decisions` resume; every attached\n * client reads a queued lane as decided. Raw reference, selector-safe.\n */\nexport function readQueuedLaneDecisions(\n state: unknown,\n): Readonly<Record<string, unknown>> | undefined {\n const queued = readDeepAgentStreamValues(state).queuedLaneDecisions;\n return isRecord(queued) ? queued : undefined;\n}\n\n/**\n * The distinct langgraph interrupt ids a `lane_decisions` resume answers for\n * these gated calls, in first-seen order — or `null` when any call lacks its\n * stamp (a legacy batch payload only a positional resume can answer). A\n * nested HITL request gating several calls contributes one id: the lane is\n * the interrupt, and one decision fans across its calls server-side.\n */\nexport function laneInterruptIds(actionRequests: readonly PendingActionRequest[]): string[] | null {\n if (actionRequests.length === 0) return null;\n const ids: string[] = [];\n for (const request of actionRequests) {\n if (request.interruptId === undefined) return null;\n if (!ids.includes(request.interruptId)) ids.push(request.interruptId);\n }\n return ids;\n}\n\nconst NO_TOOL_CALL_IDS: ReadonlySet<string> = new Set();\n\n/**\n * The gated calls still waiting on a person, by `tool_call_id`: every call of\n * the approval on screen (the parked request's, or the host's mirror while\n * sibling lanes still stream), less the lanes whose decision the host already\n * holds (`queuedLaneDecisions`, keyed by interrupt id): a lane decided live\n * waits for the run to park, not for anyone. The id is the one join between an\n * approval and the call it gates (a payload names no lane), so a call without\n * one counts for nothing.\n */\nexport function toolCallIdsAwaitingApproval({\n actionRequests,\n queuedLaneDecisions,\n}: {\n actionRequests: readonly PendingActionRequest[];\n queuedLaneDecisions?: Readonly<Record<string, unknown>>;\n}): ReadonlySet<string> {\n let ids: Set<string> | undefined;\n for (const request of actionRequests) {\n if (request.toolCallId === undefined) continue;\n if (\n request.interruptId !== undefined &&\n queuedLaneDecisions !== undefined &&\n request.interruptId in queuedLaneDecisions\n ) {\n continue;\n }\n ids ??= new Set();\n ids.add(request.toolCallId);\n }\n return ids ?? NO_TOOL_CALL_IDS;\n}\n\n/** One decision for every lane — the `lane_decisions` map a run-wide approve or reject sends. */\nexport function fanLaneDecision<T>({\n interruptIds,\n decision,\n}: {\n interruptIds: readonly string[];\n decision: T;\n}): Record<string, T> {\n return Object.fromEntries(interruptIds.map((id) => [id, decision]));\n}\n\n/** The abandoned `interrupt` entry, if any — the \"approval was cancelled\" notice. */\nexport function findAbandonedInterrupt(\n abandoned: readonly AbandonedInputRequest[] | undefined,\n): AbandonedInputRequest | undefined {\n return abandoned?.find(\n (request) => isRecord(request) && request.type === 'interrupt' && typeof request.id === 'string',\n );\n}\n\n/** Canonical reason string carried by a user rejection. */\nexport const HITL_REJECT_REASON = 'User rejected the action.';\n\n/**\n * Default {@link UseApprovalResumeLockOptions.pendingResumeGraceMs} for every\n * approval surface: how long a clicked decision waits for its resume run to\n * start before the actions unlock again. Covers a `run/input` the host\n * rejected or a disconnected transport swallowed before any run began — the\n * one failure neither identity-change nor observed-run recovery can detect.\n */\nexport const HITL_PENDING_RESUME_GRACE_MS = 15_000;\n\n/**\n * Default {@link UseApprovalResumeLockOptions.maxTransportRetries}: how many\n * times a decision the transport lost (the websocket dropped or the statewire\n * session reset while the `run/input` was in flight) is re-sent on its own\n * before the user is asked to click again.\n */\nexport const HITL_RESUME_TRANSPORT_RETRIES = 3;\n\n/**\n * The dispatch died client-side without the host ever seeing it — a proven\n * session loss or a gone stream. Safe to re-send the same decision for the\n * same still-parked request. The complement (a server verdict, or the surface\n * unmounting) is not.\n */\nexport function isResumeTransportLoss(error: unknown): boolean {\n const outcome = statewireTransportOutcome(error);\n return outcome === 'session-lost' || outcome === 'stream-gone';\n}\n\n/** `run/input` resume value approving the gated call(s). */\nexport function hitlResumeApprove(): Record<string, string> {\n return { action: 'approve' };\n}\n\n/**\n * `run/input` resume value approving the gated call(s) AND every later call of\n * the same tool(s) on this thread. The backend records the tools from its own\n * parked interrupt (never from this payload), so the value carries no names.\n */\nexport function hitlResumeApproveForSession(): Record<string, string> {\n return { action: 'approve', scope: 'session' };\n}\n\n/** `run/input` resume value rejecting the gated call(s). */\nexport function hitlResumeReject(reason: string = HITL_REJECT_REASON): Record<string, string> {\n return { action: 'reject', reason };\n}\n\n/** One gated call's own answer inside a per-action resume ({@link hitlResumeActionDecisions}). */\nexport type HitlActionDecision =\n | { action: 'approve' }\n | { action: 'reject'; reason: string }\n | { action: 'edit'; edited_args: Record<string, unknown> };\n\n/**\n * The `tool_call_id` of every gated call, in decision order — or `null` when\n * any call lacks one or two calls share one, in which case no per-action\n * resume can be bound to the batch and only the batch answers above apply.\n */\nexport function actionRequestToolCallIds(\n actionRequests: readonly PendingActionRequest[],\n): string[] | null {\n if (actionRequests.length === 0) return null;\n const ids: string[] = [];\n for (const request of actionRequests) {\n if (request.toolCallId === undefined || ids.includes(request.toolCallId)) return null;\n ids.push(request.toolCallId);\n }\n return ids;\n}\n\n/**\n * `run/input` resume value deciding each gated call by its `tool_call_id` —\n * the only channel that carries an edited call. The backend binds every entry\n * to the parked request with that id, takes the tool NAME from its own\n * request (an edit can change a call's arguments, never which tool runs), and\n * refuses the whole answer — nothing runs — unless the map names exactly the\n * parked calls. `edited_args` is the complete argument set the call runs\n * with, not a patch. The envelope `action` mirrors the first entry for hosts\n * that only read the envelope; `action_decisions` is authoritative.\n */\nexport function hitlResumeActionDecisions(\n decisions: Readonly<Record<string, HitlActionDecision>>,\n): Record<string, unknown> {\n const [anchorId, anchor] = Object.entries(decisions)[0] ?? [];\n return {\n action: anchor?.action === 'reject' ? 'reject' : 'approve',\n ...(anchorId !== undefined && { tool_call_id: anchorId }),\n action_decisions: decisions,\n };\n}\n\n/** Answers that let nothing run: rejecting, or the timeout handler's answer. */\nconst NON_APPROVING_ACTIONS: ReadonlySet<string> = new Set(['reject', 'timeout']);\n\n/**\n * Whether a `run/input` resume value (or one lane's decision) lets anything\n * run: approving, approving for the session, an edit, or anything this cannot\n * read as a reject. Mirrors the host's `_decision_approves`, which fails\n * closed the same way, so a surface asks for a passkey check exactly where\n * the host will want one. Rejecting never needs a check (identity 0b.9,\n * call 9). A `lane_decisions` map approves when any of its lanes does.\n */\nexport function resumeValueApproves(value: unknown): boolean {\n if (!isRecord(value)) return true;\n const decisions = value.decisions;\n if (Array.isArray(decisions)) {\n return decisions.length === 0 || decisions.some(resumeValueApproves);\n }\n const perAction = value.action_decisions;\n if (perAction !== undefined) {\n if (!isRecord(perAction)) return true;\n const answers = Object.values(perAction);\n return answers.length === 0 || answers.some(resumeValueApproves);\n }\n const lanes = value.lane_decisions;\n if (lanes !== undefined) {\n if (!isRecord(lanes)) return true;\n const answers = Object.values(lanes);\n return answers.length === 0 || answers.some(resumeValueApproves);\n }\n const kind = value.type;\n if (typeof kind === 'string') return !NON_APPROVING_ACTIONS.has(kind);\n const action = value.action;\n return typeof action !== 'string' || !NON_APPROVING_ACTIONS.has(action);\n}\n\n/**\n * What rides beside a resume value on the `run/input` command. Today only the\n * passkey decision check (`decisionCheck`, identity 0b.9): the token a person\n * minted for exactly this answer, which the host classifies and spends.\n */\nexport interface ResumeExtras {\n readonly decisionCheck?: string;\n}\n\n/** Canonical reason string carried by a user declining a non-HITL park. */\nexport const INTERRUPT_DECLINE_REASON = 'User declined the request.';\n\n/**\n * `run/input` resume value declining a non-HITL park. `{ action: 'reject' }`\n * is the one value every typed raiser treats as a clean user decline\n * (`FormCancelledError` / `ToolRejectedError`); a generic `continue` would be\n * rejected by their resume schemas and surface as a tool error the agent then\n * improvises around.\n */\nexport function interruptResumeDecline(\n reason: string = INTERRUPT_DECLINE_REASON,\n): Record<string, string> {\n return { action: 'reject', reason };\n}\n\nexport interface UseApprovalResumeLockOptions<TValue> {\n /** The pending interrupt's request id (`undefined` when nothing is parked). */\n requestId: string | undefined;\n /** The surface's thread `isRunning` read (mockable per surface). */\n isRunning: boolean;\n /**\n * Dispatch the `run/input` resume for `requestId` on the surface's transport.\n * Return the dispatch promise so a refused or lost command releases the lock\n * at once and reaches `onResumeRejected`; a `void` return leaves the\n * recovery paths below as the only release.\n */\n sendResume: (\n requestId: string,\n value: TValue,\n extras?: ResumeExtras,\n ) => void | Promise<unknown>;\n /**\n * The dispatch `sendResume` returned rejected — the host refused the\n * `run/input` or the transport lost it. The lock is already released when\n * this fires; the surface tells the user, since the request is back on\n * screen with nothing else saying why.\n */\n onResumeRejected?: (error: unknown, requestId: string) => void;\n /**\n * A dispatch the transport lost is being re-sent for the still-parked\n * request; `attempt` counts the retries so far (1-based). Diagnostics only —\n * the lock stays held across the retry.\n */\n onResumeRetry?: (error: unknown, requestId: string, attempt: number) => void;\n /**\n * Automatic re-sends of a decision the transport lost\n * ({@link isResumeTransportLoss}) while the request is still parked. `0`\n * disables retries. Defaults to {@link HITL_RESUME_TRANSPORT_RETRIES}.\n */\n maxTransportRetries?: number;\n /**\n * Re-enable the actions when no resume run started within this window —\n * covers a `run/input` that was rejected or lost before any run began, so\n * neither reset path below can fire. Omit to keep the pre-existing surface\n * behavior of staying locked until a resume run is observed.\n */\n pendingResumeGraceMs?: number;\n}\n\nexport interface ApprovalResumeLock<TValue> {\n /** True after a resume until the request identity changes (or recovery fires). */\n pending: boolean;\n /**\n * Send the resume value, locking the actions. No-op (returns `undefined`)\n * while pending or unparked. Returns the dispatch promise when `sendResume`\n * produced one, so a surface can hold its own state until the host settles.\n */\n resume: (value: TValue, extras?: ResumeExtras) => Promise<unknown> | undefined;\n}\n\n/**\n * Optimistic action lock shared by every approval surface: disable the\n * decision buttons the moment one is clicked, until the request identity\n * changes (it clears after the resume, or a fresh interrupt arrives). This\n * closes the double-click → duplicate-resume window.\n *\n * Recovery paths, in order of specificity:\n * 0. The dispatch itself rejected (a `sendResume` that returned a promise) —\n * released at once, and reported through `onResumeRejected`. A rejection\n * that is a transport loss (the socket dropped mid-flight) is re-sent up to\n * `maxTransportRetries` times first, the lock held throughout, so a flaky\n * connection does not hand the card back to the user for another click.\n * The returned promise settles with the final attempt.\n * 1. Identity change — the resume landed (or a new interrupt replaced the\n * request). Reset during render via React's \"previous value\" pattern.\n * 2. A resume run was observed starting and then settling with the request\n * still pending (failed/cancelled resume) — clear the lock so the user can\n * answer again.\n * 3. Optional grace window ({@link UseApprovalResumeLockOptions.pendingResumeGraceMs})\n * for a `run/input` that never started a run at all.\n */\nexport function useApprovalResumeLock<TValue = Record<string, string>>(\n options: UseApprovalResumeLockOptions<TValue>,\n): ApprovalResumeLock<TValue> {\n const {\n requestId,\n isRunning,\n sendResume,\n pendingResumeGraceMs,\n onResumeRejected,\n onResumeRetry,\n maxTransportRetries = HITL_RESUME_TRANSPORT_RETRIES,\n } = options;\n\n const [pending, setPending] = useState(false);\n // Bumped per re-send so the grace window restarts with each attempt.\n const [attempt, setAttempt] = useState(0);\n const prevRequestIdRef = useRef(requestId);\n if (prevRequestIdRef.current !== requestId) {\n prevRequestIdRef.current = requestId;\n if (pending) setPending(false);\n }\n\n // Track the resume run we kicked off (isRunning observed true→false while\n // pending) and clear `pending` when it ends with the request unresolved.\n const sawResumeRunRef = useRef(false);\n useEffect(() => {\n if (!pending) {\n sawResumeRunRef.current = false;\n return;\n }\n if (isRunning) {\n sawResumeRunRef.current = true;\n return;\n }\n if (sawResumeRunRef.current) {\n sawResumeRunRef.current = false;\n setPending(false);\n }\n }, [pending, isRunning]);\n\n // Pre-start failure recovery: re-enable after the grace window when no\n // resume run began; answering the still-parked request again is exactly\n // what the user needs to be able to do.\n useEffect(() => {\n if (!pending || pendingResumeGraceMs === undefined) return;\n const timer = setTimeout(() => {\n if (!sawResumeRunRef.current) setPending(false);\n }, pendingResumeGraceMs);\n return () => clearTimeout(timer);\n }, [pending, requestId, pendingResumeGraceMs, attempt]);\n\n const sendResumeRef = useRef(sendResume);\n sendResumeRef.current = sendResume;\n const onResumeRejectedRef = useRef(onResumeRejected);\n onResumeRejectedRef.current = onResumeRejected;\n const onResumeRetryRef = useRef(onResumeRetry);\n onResumeRetryRef.current = onResumeRetry;\n const maxTransportRetriesRef = useRef(maxTransportRetries);\n maxTransportRetriesRef.current = maxTransportRetries;\n const currentRequestIdRef = useRef(requestId);\n currentRequestIdRef.current = requestId;\n const pendingRef = useRef(pending);\n pendingRef.current = pending;\n // One token per `resume` call: a settle from an earlier submission must not\n // retry over, or release, a newer one for the same request.\n const submissionRef = useRef(0);\n\n const resume = useCallback(\n (value: TValue, extras?: ResumeExtras): Promise<unknown> | undefined => {\n if (requestId === undefined || pendingRef.current) return undefined;\n const submission = ++submissionRef.current;\n setPending(true);\n pendingRef.current = true;\n setAttempt(0);\n const first: unknown = sendResumeRef.current(requestId, value, extras);\n if (!(first instanceof Promise)) return undefined;\n // The final failure is already reported through `onResumeRejected`;\n // callers that drop the promise must not get an unhandled rejection.\n const outcome = new Promise<unknown>((resolve, reject) => {\n const settle = (dispatched: Promise<unknown>, retries: number) => {\n dispatched.then(resolve, (error: unknown) => {\n // A late refusal for a request the lock has since moved past (the\n // park was re-keyed, or a newer answer is in flight) must neither\n // release that answer's lock nor be reported as a failure of it.\n // The optimistic fold hides the answered request until the fold\n // rolls back, so `undefined` here is not a departure.\n const current = currentRequestIdRef.current;\n if (\n submission !== submissionRef.current ||\n (current !== undefined && current !== requestId)\n ) {\n reject(error);\n return;\n }\n if (retries < maxTransportRetriesRef.current && isResumeTransportLoss(error)) {\n const next = retries + 1;\n onResumeRetryRef.current?.(error, requestId, next);\n setPending(true);\n pendingRef.current = true;\n setAttempt(next);\n const resent: unknown = sendResumeRef.current(requestId, value, extras);\n if (resent instanceof Promise) {\n settle(resent, next);\n return;\n }\n resolve(undefined);\n return;\n }\n setPending(false);\n pendingRef.current = false;\n onResumeRejectedRef.current?.(error, requestId);\n reject(error);\n });\n };\n settle(first, 0);\n });\n outcome.catch(() => {});\n return outcome;\n },\n [requestId],\n );\n\n return { pending, resume };\n}\n"],"names":["hasClientToolInterruptSource","readDeepAgentStreamValues","statewireTransportOutcome","useState","useRef","useEffect","useCallback"],"mappings":";;;;;;AA2EA,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;A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,WAAW,QAAS,QAAO;AAC1D,YAAM,aAAa,EAAE,cAAc;AACnC,iBAAW,IAAI;AACf,iBAAW,UAAU;AACrB,iBAAW,CAAC;AACZ,YAAM,QAAiB,cAAc,QAAQ,WAAW,OAAO,MAAM;AACrE,UAAI,EAAE,iBAAiB,SAAU,QAAO;AAGxC,YAAM,UAAU,IAAI,QAAiB,CAAC,SAAS,WAAW;AACxD,cAAM,SAAS,CAAC,YAA8B,YAAoB;AAChE,qBAAW,KAAK,SAAS,CAAC,UAAmB;;AAM3C,kBAAM,UAAU,oBAAoB;AACpC,gBACE,eAAe,cAAc,WAC5B,YAAY,UAAa,YAAY,WACtC;AACA,qBAAO,KAAK;AACZ;AAAA,YACF;AACA,gBAAI,UAAU,uBAAuB,WAAW,sBAAsB,KAAK,GAAG;AAC5E,oBAAM,OAAO,UAAU;AACvB,qCAAiB,YAAjB,0CAA2B,OAAO,WAAW;AAC7C,yBAAW,IAAI;AACf,yBAAW,UAAU;AACrB,yBAAW,IAAI;AACf,oBAAM,SAAkB,cAAc,QAAQ,WAAW,OAAO,MAAM;AACtE,kBAAI,kBAAkB,SAAS;AAC7B,uBAAO,QAAQ,IAAI;AACnB;AAAA,cACF;AACA,sBAAQ,MAAS;AACjB;AAAA,YACF;AACA,uBAAW,KAAK;AAChB,uBAAW,UAAU;AACrB,sCAAoB,YAApB,6CAA8B,OAAO;AACrC,mBAAO,KAAK;AAAA,UACd,CAAC;AAAA,QACH;AACA,eAAO,OAAO,CAAC;AAAA,MACjB,CAAC;AACD,cAAQ,MAAM,MAAM;AAAA,MAAC,CAAC;AACtB,aAAO;AAAA,IACT;AAAA,IACA,CAAC,SAAS;AAAA,EAAA;AAGZ,SAAO,EAAE,SAAS,OAAA;AACpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"interrupts.cjs","sources":["../../../../agent-runtime/src/interrupts.ts"],"sourcesContent":["/**\n * Human-in-the-loop interrupt primitives shared by every statewire chat\n * surface (Olympus, the React SDK, the Office add-in, the Chrome extension,\n * mobile).\n *\n * The agora deep-agent runtime parks a gated run on an `interrupt` input\n * request whose payload carries the Athena `hitl_approval` shape\n * (`athena_deep_agent/hitl_bridge.py`). A surface answers it with\n * `{ type: 'run/input', requestId, response: { type: 'resume', value } }` —\n * the exact command the backend's resume path consumes. This module holds the\n * payload contract (narrowing, resume values) and the shared resume-lock state\n * machine; rendering stays with each surface.\n *\n * Deliberately parameterized rather than self-wiring: these helpers never call\n * `useStatewireRuns`/`useAuiState` themselves. Each surface reads its own\n * statewire hooks (which its tests already mock) and passes the values in, so\n * the shared semantics cannot drift while per-surface wiring stays testable.\n */\n\nimport type { StatewireThread } from '@assistant-ui/react-statewire';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { hasClientToolInterruptSource } from './client-tools';\nimport { statewireTransportOutcome } from './errors';\nimport { readDeepAgentStreamValues } from './statewire-state';\n\n/** Human-in-the-loop approval payload the agora deep-agent runtime parks a run\n * on (shaped by `athena_deep_agent/hitl_bridge.py`). */\nexport interface HitlApprovalPayload {\n source: string;\n type: string;\n message: string;\n /** Risk headline/facts/warnings, when the host includes them. */\n approval_context?: unknown;\n context?: {\n tool_name?: string;\n tool_id?: string;\n tool_call_id?: string;\n tool_args?: Record<string, unknown>;\n pending_action_count?: number;\n approval_context?: unknown;\n /**\n * Every pending gated call (name + args), in decision order. Absent on\n * older backends — fall back to the single `tool_name`/`tool_args` pair.\n * Per-dispatch payloads also carry each lane's `tool_call_id` (the lane\n * card key) and `interrupt_id` (the lane resume key).\n */\n action_requests?: {\n name?: string;\n args?: Record<string, unknown>;\n tool_call_id?: string;\n interrupt_id?: string;\n /**\n * True when \"approve all for this session\" would take effect for this\n * tool (the workspace allows overriding its approval). Absent on older\n * backends and on non-overridable tools: the option is not offered.\n */\n session_approval_allowed?: boolean;\n /**\n * On a send with an act adapter: the people a session-wide approval of\n * it covers, and only them, by the name the card shows (the address or\n * number). Such a send carries `session_approval_allowed: false`, so a\n * client that predates this field never offers a tool-wide answer.\n */\n session_approval_recipients?: string[];\n /**\n * The decision types the parked gate accepts for this call (`approve`,\n * `reject`, `edit`). Absent on older backends: only approve / reject\n * are known to be accepted.\n */\n allowed_decisions?: string[];\n /** What the backend resolved about this call before asking (display-only). */\n approval_context?: unknown;\n }[];\n /**\n * True when each dispatch parked on its own interrupt: decisions submit\n * per lane via `lane_decisions` and each approved lane starts immediately,\n * instead of the legacy batch where one resume must answer every lane.\n */\n per_dispatch?: boolean;\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** A pending `interrupt` input request; a present `response` key marks it answered. */\nexport function isPendingInterrupt(\n request: StatewireThread.InputRequestState,\n): request is StatewireThread.CustomInputRequest {\n return request.type === 'interrupt' && !('response' in request);\n}\n\n/**\n * Interrupt sources that were system pauses before the host stamped\n * `requires_user_action: false` on them (a background deep-research wait). Kept\n * only for the deploy skew between an older agora and a newer client; delete\n * once every deployment's raiser stamps the flag.\n */\nconst LEGACY_SYSTEM_PAUSE_INTERRUPT_SOURCES: ReadonlySet<string> = new Set(['deep_research_pending']);\n\n/**\n * A park nobody answers: the agent is still working (a background research\n * wait) and the backend resumes it itself. The raiser stamps\n * `requires_user_action: false`; older raisers are recognised by source.\n */\nexport function isSystemPauseInterrupt(payload: unknown): boolean {\n if (!isRecord(payload)) return false;\n if (payload.requires_user_action === false) return true;\n return (\n typeof payload.source === 'string' && LEGACY_SYSTEM_PAUSE_INTERRUPT_SOURCES.has(payload.source)\n );\n}\n\n/**\n * A pending interrupt an approval card may answer. Two kinds are excluded —\n * client-tool parks (the client-tool bridge owns those, and a generic resume\n * would corrupt the parked tool call) and system pauses (nothing to answer; the\n * backend resumes them). The source checks are deliberately loose so a skewed\n * deploy can never route one here.\n */\nexport function isApprovalCardInterrupt(\n request: StatewireThread.InputRequestState,\n): request is StatewireThread.CustomInputRequest {\n if (!isPendingInterrupt(request)) return false;\n const payload = (request as { payload?: unknown }).payload;\n return !hasClientToolInterruptSource(payload) && !isSystemPauseInterrupt(payload);\n}\n\n/** Narrow an interrupt payload to the Athena HITL approval shape. */\nexport function asHitlApproval(value: unknown): HitlApprovalPayload | null {\n if (!isRecord(value)) return null;\n return value.type === 'hitl' &&\n value.source === 'hitl_approval' &&\n typeof value.message === 'string'\n ? (value as unknown as HitlApprovalPayload)\n : null;\n}\n\n/** Default paused-run copy when an interrupt payload carries no message. */\nexport const DEFAULT_INTERRUPT_PAUSED_MESSAGE =\n 'The agent is paused and waiting for input.';\n\n/** Best-effort human-readable message from any interrupt payload. */\nexport function readInterruptMessage(\n value: unknown,\n fallback: string = DEFAULT_INTERRUPT_PAUSED_MESSAGE,\n): string {\n if (isRecord(value) && typeof value.message === 'string' && value.message.length > 0) {\n return value.message;\n }\n return fallback;\n}\n\n/** One label/value row of a call's resolved approval facts. */\nexport interface PendingApprovalFact {\n label: string;\n value: string;\n}\n\n/** One caution of a call's resolved approval facts. */\nexport interface PendingApprovalWarning {\n severity: 'info' | 'warning' | 'critical';\n message: string;\n}\n\nexport interface PendingApprovalSlackTarget {\n catalog_id: string;\n conversation_id: string | null;\n thread_ts: string | null;\n team_url: string | null;\n people: string[];\n}\n\n/**\n * What the backend resolved about a gated call before asking — e.g. where a\n * Slack write goes and as whom (agora `services/interrupts/approval_context.py`).\n * Display-only; the decision still answers the parked call.\n */\nexport interface PendingApprovalContext {\n facts: PendingApprovalFact[];\n warnings: PendingApprovalWarning[];\n /** The question the approval asks, in a line (\"Use Studio Mac in this conversation?\"). */\n headline?: string;\n /** What approving lets happen, a sentence or two under the headline. */\n summary?: string;\n slack_target?: PendingApprovalSlackTarget;\n}\n\nconst APPROVAL_WARNING_SEVERITIES = new Set(['info', 'warning', 'critical']);\n\nfunction isNullableString(value: unknown): value is string | null {\n return value === null || typeof value === 'string';\n}\n\n/** Display text: a string, trimmed; a blank or anything that is not a string is absent. */\nfunction displayText(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const text = value.trim();\n return text.length > 0 ? text : undefined;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((entry) => typeof entry === 'string');\n}\n\nfunction parsePendingApprovalSlackTarget(value: unknown): PendingApprovalSlackTarget | undefined {\n if (!isRecord(value) || typeof value.catalog_id !== 'string') return undefined;\n const conversationId = value.conversation_id;\n const threadTs = value.thread_ts;\n const teamUrl = value.team_url;\n const people = value.people === undefined ? [] : value.people;\n if (\n !isNullableString(conversationId) ||\n !isNullableString(threadTs) ||\n !isNullableString(teamUrl) ||\n !isStringArray(people)\n )\n return undefined;\n return {\n catalog_id: value.catalog_id,\n conversation_id: conversationId,\n thread_ts: threadTs,\n team_url: teamUrl,\n people,\n };\n}\n\n/** A call's `approval_context`, or `undefined` when absent or empty. */\nexport function parsePendingApprovalContext(value: unknown): PendingApprovalContext | undefined {\n if (!isRecord(value)) return undefined;\n const facts: PendingApprovalFact[] = Array.isArray(value.facts)\n ? value.facts.flatMap((fact) =>\n isRecord(fact) && typeof fact.label === 'string' && typeof fact.value === 'string'\n ? [{ label: fact.label, value: fact.value }]\n : [],\n )\n : [];\n const warnings: PendingApprovalWarning[] = Array.isArray(value.warnings)\n ? value.warnings.flatMap((warning) => {\n if (!isRecord(warning) || typeof warning.message !== 'string') return [];\n const severity =\n typeof warning.severity === 'string' && APPROVAL_WARNING_SEVERITIES.has(warning.severity)\n ? (warning.severity as PendingApprovalWarning['severity'])\n : 'info';\n return [{ severity, message: warning.message }];\n })\n : [];\n const headline = displayText(value.headline);\n const summary = displayText(value.summary);\n const slackTarget = parsePendingApprovalSlackTarget(value.slack_target);\n return facts.length > 0 || warnings.length > 0 || headline || summary || slackTarget\n ? {\n facts,\n warnings,\n ...(headline ? { headline } : {}),\n ...(summary ? { summary } : {}),\n ...(slackTarget ? { slack_target: slackTarget } : {}),\n }\n : undefined;\n}\n\nexport interface PendingActionRequest {\n name: string;\n args: Record<string, unknown>;\n /** The lane's `task` tool-call id (present on per-dispatch payloads). */\n toolCallId?: string;\n /** The lane's langgraph interrupt id — the `lane_decisions` resume key. */\n interruptId?: string;\n /** Present (true) when a session-wide approval would cover later calls of this tool. */\n sessionApprovalAllowed?: true;\n /**\n * Present on a send whose session-wide approval covers only the people it\n * reaches (`session_approval_recipients`): what the card names for each of\n * them, every hidden or control character written out as `<U+XXXX>`. Such a\n * send never carries `sessionApprovalAllowed`.\n */\n sessionApprovalRecipients?: string[];\n /** Present (true) when the gate accepts an `edit` decision for this call. */\n editAllowed?: true;\n /** Present when the backend resolved anything about this call before asking (facts, a headline). */\n approvalContext?: PendingApprovalContext;\n}\n\n/**\n * Every gated call this approval covers, in decision order. One resume answers\n * ALL of them, so every entry must stay reviewable somewhere. Falls back to\n * the single first-call fields on older backends without `action_requests`.\n */\nexport function pendingActionRequests(hitl: HitlApprovalPayload | null): PendingActionRequest[] {\n const context = hitl?.context;\n if (!context) return [];\n // The payload crosses the wire with only its top-level shape narrowed\n // (`asHitlApproval`), so the nested collection must be validated before any\n // array/property access: a malformed host value must degrade to \"no\n // reviewable entries\", never crash the approval surface.\n const requests: Record<string, unknown>[] = Array.isArray(context.action_requests)\n ? context.action_requests.filter(isRecord)\n : context.tool_name && context.tool_args\n ? [{ name: context.tool_name, args: context.tool_args, tool_call_id: context.tool_call_id }]\n : [];\n return requests.map((request) => {\n const approvalContext = parsePendingApprovalContext(request.approval_context);\n const sessionApprovalRecipients = parseSessionApprovalRecipients(\n request.session_approval_recipients,\n );\n return {\n name: typeof request.name === 'string' ? request.name : 'tool',\n args: isRecord(request.args) ? request.args : {},\n ...(typeof request.tool_call_id === 'string' && { toolCallId: request.tool_call_id }),\n ...(typeof request.interrupt_id === 'string' && { interruptId: request.interrupt_id }),\n ...(request.session_approval_allowed === true && { sessionApprovalAllowed: true }),\n ...(sessionApprovalRecipients && { sessionApprovalRecipients }),\n ...(Array.isArray(request.allowed_decisions) &&\n request.allowed_decisions.includes('edit') && { editAllowed: true }),\n ...(approvalContext && { approvalContext }),\n };\n });\n}\n\n/** The headline (and summary) that title a pending approval in place of the generic copy. */\nexport interface PendingApprovalTitle {\n headline: string;\n summary?: string;\n}\n\n/**\n * The title of a pending approval: the headline and summary of its one gated\n * call's resolved envelope (the call's own `approval_context`, else the copy\n * the host lifted to `context.approval_context`). A batch has none: one\n * decision answers every call, so no one call's headline may speak for it.\n * Display-only, like the envelope.\n */\nexport function pendingApprovalTitle({\n hitl,\n actionRequests,\n}: {\n hitl: HitlApprovalPayload | null;\n actionRequests: readonly PendingActionRequest[];\n}): PendingApprovalTitle | undefined {\n const [call, ...others] = actionRequests;\n if (hitl === null || call === undefined || others.length > 0) return undefined;\n // An older backend lists only the first call and counts the rest here; a\n // count that is not plainly one keeps the generic copy.\n const pendingCount = hitl.context?.pending_action_count;\n if (pendingCount !== undefined && pendingCount !== 1) return undefined;\n const envelope =\n call.approvalContext ?? parsePendingApprovalContext(hitl.context?.approval_context);\n if (envelope?.headline === undefined) return undefined;\n return envelope.summary === undefined\n ? { headline: envelope.headline }\n : { headline: envelope.headline, summary: envelope.summary };\n}\n\n/**\n * `text` with every character a person can't see (control and format\n * characters such as zero-width spaces, bidi overrides and Unicode tag\n * characters, private-use and unassigned code points, and any separator but\n * a plain space) written out as `<U+XXXX>`, so a name shows all of itself.\n */\nexport function visibleText(text: string): string {\n return text.replace(/[\\p{C}\\p{Z}]/gu, (character) =>\n character === ' '\n ? character\n : `<U+${(character.codePointAt(0) ?? 0).toString(16).toUpperCase().padStart(4, '0')}>`,\n );\n}\n\n/** A send's stamped recipient names: a non-empty list of non-empty strings, or nothing. */\nfunction parseSessionApprovalRecipients(value: unknown): string[] | undefined {\n if (!Array.isArray(value) || value.length === 0) return undefined;\n const names: string[] = [];\n for (const name of value) {\n if (typeof name !== 'string' || name.trim() === '') return undefined;\n names.push(visibleText(name));\n }\n return names;\n}\n\n/**\n * What \"approve for this session\" would cover for a pending approval:\n *\n * - `tools`: later calls of these tools (every call stamped\n * `sessionApprovalAllowed`).\n * - `recipients`: later sends to exactly these people, and nobody else\n * (every call is a send stamped `sessionApprovalRecipients`).\n */\nexport type SessionApprovalOffer =\n | { kind: 'tools' }\n | { kind: 'recipients'; recipients: readonly string[] };\n\n/**\n * The session-wide approval the card may offer, or `undefined` for the\n * one-time answer only: a batch that mixes in a tool the workspace pinned as\n * always-prompt, a call stamped neither way, or tools beside recipient-scoped\n * sends (no one label could say exactly what that answer covers).\n */\nexport function sessionApprovalOffer(\n actionRequests: readonly PendingActionRequest[],\n): SessionApprovalOffer | undefined {\n if (actionRequests.length === 0) return undefined;\n if (\n actionRequests.every(\n (request) =>\n request.sessionApprovalAllowed === true && request.sessionApprovalRecipients === undefined,\n )\n ) {\n return { kind: 'tools' };\n }\n const recipients: string[] = [];\n for (const request of actionRequests) {\n if (request.sessionApprovalRecipients === undefined) return undefined;\n for (const name of request.sessionApprovalRecipients) {\n if (!recipients.includes(name)) recipients.push(name);\n }\n }\n return { kind: 'recipients', recipients };\n}\n\n/** `a`, `a and b`, `a, b and c`. */\nfunction namesInProse(names: readonly string[]): string {\n if (names.length <= 1) return names.join('');\n return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;\n}\n\n/**\n * What the session option's button says: exactly what the answer covers.\n * \"Approve all for this session\" for tools; for sends, every recipient by\n * name: \"Approve for this session: only kyle@partner.example and\n * sam@partner.example\".\n */\nexport function sessionApprovalLabel(offer: SessionApprovalOffer): string {\n if (offer.kind === 'tools') return 'Approve all for this session';\n return `Approve for this session: only ${namesInProse(offer.recipients)}`;\n}\n\n/**\n * Whether the card may offer a session-wide approval at all\n * ({@link sessionApprovalOffer}).\n */\nexport function canApproveForSession(actionRequests: readonly PendingActionRequest[]): boolean {\n return sessionApprovalOffer(actionRequests) !== undefined;\n}\n\n/** An interrupt a non-resume dispatch dropped, published by the host. */\nexport interface AbandonedInputRequest {\n id: string;\n type: string;\n}\n\n/**\n * `useStatewireState` selector body for the host-published abandoned input\n * requests. Reads through {@link readDeepAgentStreamValues} so the selector is\n * safe on the pre-attach (`undefined`) wire state, and returns the raw array\n * reference so the subscription stays shallow-stable — derive (`.find`) on the\n * result, never inside the selector.\n */\nexport function readAbandonedInputRequests(\n state: unknown,\n): readonly AbandonedInputRequest[] | undefined {\n const abandoned = readDeepAgentStreamValues(state).abandonedInputRequests;\n // Wire value: anything non-array (including a malformed host publication)\n // reads as \"none\" rather than crashing the consuming surface. Identity-\n // preserving for the valid case, so it stays selector-safe.\n return Array.isArray(abandoned)\n ? (abandoned as readonly AbandonedInputRequest[])\n : undefined;\n}\n\n/**\n * `useStatewireState` selector body for the host's mirrored interrupt\n * (`__interrupt__`, the LangGraph `{value, resumable}` wrapper). The mirror\n * is published the moment a lane parks on its gate — while sibling lanes are\n * still streaming and the run manager has NOT yet published an answerable\n * input request. Raw reference, selector-safe; unwrap with\n * {@link interruptMirrorPayload}.\n */\nexport function readInterruptMirror(state: unknown): unknown {\n return readDeepAgentStreamValues(state).__interrupt__;\n}\n\n/** The payload of a mirrored interrupt wrapper, or `undefined` for anything else. */\nexport function interruptMirrorPayload(mirror: unknown): unknown {\n return isRecord(mirror) ? mirror.value : undefined;\n}\n\n/**\n * `useStatewireState` selector body for the per-dispatch lane decisions the\n * host accepted through `run/lane-input` while the run was still streaming\n * (`queuedLaneDecisions`, keyed by langgraph interrupt id). Held until the\n * run parks, then answered as a native `lane_decisions` resume; every attached\n * client reads a queued lane as decided. Raw reference, selector-safe.\n */\nexport function readQueuedLaneDecisions(\n state: unknown,\n): Readonly<Record<string, unknown>> | undefined {\n const queued = readDeepAgentStreamValues(state).queuedLaneDecisions;\n return isRecord(queued) ? queued : undefined;\n}\n\n/**\n * The distinct langgraph interrupt ids a `lane_decisions` resume answers for\n * these gated calls, in first-seen order — or `null` when any call lacks its\n * stamp (a legacy batch payload only a positional resume can answer). A\n * nested HITL request gating several calls contributes one id: the lane is\n * the interrupt, and one decision fans across its calls server-side.\n */\nexport function laneInterruptIds(actionRequests: readonly PendingActionRequest[]): string[] | null {\n if (actionRequests.length === 0) return null;\n const ids: string[] = [];\n for (const request of actionRequests) {\n if (request.interruptId === undefined) return null;\n if (!ids.includes(request.interruptId)) ids.push(request.interruptId);\n }\n return ids;\n}\n\nconst NO_TOOL_CALL_IDS: ReadonlySet<string> = new Set();\n\n/**\n * The gated calls still waiting on a person, by `tool_call_id`: every call of\n * the approval on screen (the parked request's, or the host's mirror while\n * sibling lanes still stream), less the lanes whose decision the host already\n * holds (`queuedLaneDecisions`, keyed by interrupt id): a lane decided live\n * waits for the run to park, not for anyone. The id is the one join between an\n * approval and the call it gates (a payload names no lane), so a call without\n * one counts for nothing.\n */\nexport function toolCallIdsAwaitingApproval({\n actionRequests,\n queuedLaneDecisions,\n}: {\n actionRequests: readonly PendingActionRequest[];\n queuedLaneDecisions?: Readonly<Record<string, unknown>>;\n}): ReadonlySet<string> {\n let ids: Set<string> | undefined;\n for (const request of actionRequests) {\n if (request.toolCallId === undefined) continue;\n if (\n request.interruptId !== undefined &&\n queuedLaneDecisions !== undefined &&\n request.interruptId in queuedLaneDecisions\n ) {\n continue;\n }\n ids ??= new Set();\n ids.add(request.toolCallId);\n }\n return ids ?? NO_TOOL_CALL_IDS;\n}\n\n/** One decision for every lane — the `lane_decisions` map a run-wide approve or reject sends. */\nexport function fanLaneDecision<T>({\n interruptIds,\n decision,\n}: {\n interruptIds: readonly string[];\n decision: T;\n}): Record<string, T> {\n return Object.fromEntries(interruptIds.map((id) => [id, decision]));\n}\n\n/** The abandoned `interrupt` entry, if any — the \"approval was cancelled\" notice. */\nexport function findAbandonedInterrupt(\n abandoned: readonly AbandonedInputRequest[] | undefined,\n): AbandonedInputRequest | undefined {\n return abandoned?.find(\n (request) => isRecord(request) && request.type === 'interrupt' && typeof request.id === 'string',\n );\n}\n\n/** Canonical reason string carried by a user rejection. */\nexport const HITL_REJECT_REASON = 'User rejected the action.';\n\n/**\n * Default {@link UseApprovalResumeLockOptions.pendingResumeGraceMs} for every\n * approval surface: how long a clicked decision waits for its resume run to\n * start before the actions unlock again. Covers a `run/input` the host\n * rejected or a disconnected transport swallowed before any run began — the\n * one failure neither identity-change nor observed-run recovery can detect.\n */\nexport const HITL_PENDING_RESUME_GRACE_MS = 15_000;\n\n/**\n * Default {@link UseApprovalResumeLockOptions.maxTransportRetries}: how many\n * times a decision the transport lost (the websocket dropped or the statewire\n * session reset while the `run/input` was in flight) is re-sent on its own\n * before the user is asked to click again.\n */\nexport const HITL_RESUME_TRANSPORT_RETRIES = 3;\n\n/**\n * The dispatch died client-side without the host ever seeing it — a proven\n * session loss or a gone stream. Safe to re-send the same decision for the\n * same still-parked request. The complement (a server verdict, or the surface\n * unmounting) is not.\n */\nexport function isResumeTransportLoss(error: unknown): boolean {\n const outcome = statewireTransportOutcome(error);\n return outcome === 'session-lost' || outcome === 'stream-gone';\n}\n\n/** `run/input` resume value approving the gated call(s). */\nexport function hitlResumeApprove(): Record<string, string> {\n return { action: 'approve' };\n}\n\n/**\n * `run/input` resume value approving the gated call(s) AND every later call of\n * the same tool(s) on this thread. The backend records the tools from its own\n * parked interrupt (never from this payload), so the value carries no names.\n */\nexport function hitlResumeApproveForSession(): Record<string, string> {\n return { action: 'approve', scope: 'session' };\n}\n\n/** `run/input` resume value rejecting the gated call(s). */\nexport function hitlResumeReject(reason: string = HITL_REJECT_REASON): Record<string, string> {\n return { action: 'reject', reason };\n}\n\n/** One gated call's own answer inside a per-action resume ({@link hitlResumeActionDecisions}). */\nexport type HitlActionDecision =\n | { action: 'approve' }\n | { action: 'reject'; reason: string }\n | { action: 'edit'; edited_args: Record<string, unknown> };\n\n/**\n * The `tool_call_id` of every gated call, in decision order — or `null` when\n * any call lacks one or two calls share one, in which case no per-action\n * resume can be bound to the batch and only the batch answers above apply.\n */\nexport function actionRequestToolCallIds(\n actionRequests: readonly PendingActionRequest[],\n): string[] | null {\n if (actionRequests.length === 0) return null;\n const ids: string[] = [];\n for (const request of actionRequests) {\n if (request.toolCallId === undefined || ids.includes(request.toolCallId)) return null;\n ids.push(request.toolCallId);\n }\n return ids;\n}\n\n/**\n * `run/input` resume value deciding each gated call by its `tool_call_id` —\n * the only channel that carries an edited call. The backend binds every entry\n * to the parked request with that id, takes the tool NAME from its own\n * request (an edit can change a call's arguments, never which tool runs), and\n * refuses the whole answer — nothing runs — unless the map names exactly the\n * parked calls. `edited_args` is the complete argument set the call runs\n * with, not a patch. The envelope `action` mirrors the first entry for hosts\n * that only read the envelope; `action_decisions` is authoritative.\n */\nexport function hitlResumeActionDecisions(\n decisions: Readonly<Record<string, HitlActionDecision>>,\n): Record<string, unknown> {\n const [anchorId, anchor] = Object.entries(decisions)[0] ?? [];\n return {\n action: anchor?.action === 'reject' ? 'reject' : 'approve',\n ...(anchorId !== undefined && { tool_call_id: anchorId }),\n action_decisions: decisions,\n };\n}\n\n/** Answers that let nothing run: rejecting, or the timeout handler's answer. */\nconst NON_APPROVING_ACTIONS: ReadonlySet<string> = new Set(['reject', 'timeout']);\n\n/**\n * Whether a `run/input` resume value (or one lane's decision) lets anything\n * run: approving, approving for the session, an edit, or anything this cannot\n * read as a reject. Mirrors the host's `_decision_approves`, which fails\n * closed the same way, so a surface asks for a passkey check exactly where\n * the host will want one. Rejecting never needs a check (identity 0b.9,\n * call 9). A `lane_decisions` map approves when any of its lanes does.\n */\nexport function resumeValueApproves(value: unknown): boolean {\n if (!isRecord(value)) return true;\n const decisions = value.decisions;\n if (Array.isArray(decisions)) {\n return decisions.length === 0 || decisions.some(resumeValueApproves);\n }\n const perAction = value.action_decisions;\n if (perAction !== undefined) {\n if (!isRecord(perAction)) return true;\n const answers = Object.values(perAction);\n return answers.length === 0 || answers.some(resumeValueApproves);\n }\n const lanes = value.lane_decisions;\n if (lanes !== undefined) {\n if (!isRecord(lanes)) return true;\n const answers = Object.values(lanes);\n return answers.length === 0 || answers.some(resumeValueApproves);\n }\n const kind = value.type;\n if (typeof kind === 'string') return !NON_APPROVING_ACTIONS.has(kind);\n const action = value.action;\n return typeof action !== 'string' || !NON_APPROVING_ACTIONS.has(action);\n}\n\n/**\n * What rides beside a resume value on the `run/input` command. Today only the\n * passkey decision check (`decisionCheck`, identity 0b.9): the token a person\n * minted for exactly this answer, which the host classifies and spends.\n */\nexport interface ResumeExtras {\n readonly decisionCheck?: string;\n}\n\n/** Canonical reason string carried by a user declining a non-HITL park. */\nexport const INTERRUPT_DECLINE_REASON = 'User declined the request.';\n\n/**\n * `run/input` resume value declining a non-HITL park. `{ action: 'reject' }`\n * is the one value every typed raiser treats as a clean user decline\n * (`FormCancelledError` / `ToolRejectedError`); a generic `continue` would be\n * rejected by their resume schemas and surface as a tool error the agent then\n * improvises around.\n */\nexport function interruptResumeDecline(\n reason: string = INTERRUPT_DECLINE_REASON,\n): Record<string, string> {\n return { action: 'reject', reason };\n}\n\nexport interface UseApprovalResumeLockOptions<TValue> {\n /** The pending interrupt's request id (`undefined` when nothing is parked). */\n requestId: string | undefined;\n /** The surface's thread `isRunning` read (mockable per surface). */\n isRunning: boolean;\n /**\n * Dispatch the `run/input` resume for `requestId` on the surface's transport.\n * Return the dispatch promise so a refused or lost command releases the lock\n * at once and reaches `onResumeRejected`; a `void` return leaves the\n * recovery paths below as the only release.\n */\n sendResume: (\n requestId: string,\n value: TValue,\n extras?: ResumeExtras,\n ) => void | Promise<unknown>;\n /**\n * The dispatch `sendResume` returned rejected — the host refused the\n * `run/input` or the transport lost it. The lock is already released when\n * this fires; the surface tells the user, since the request is back on\n * screen with nothing else saying why.\n */\n onResumeRejected?: (error: unknown, requestId: string) => void;\n /**\n * A dispatch the transport lost is being re-sent for the still-parked\n * request; `attempt` counts the retries so far (1-based). Diagnostics only —\n * the lock stays held across the retry.\n */\n onResumeRetry?: (error: unknown, requestId: string, attempt: number) => void;\n /**\n * Automatic re-sends of a decision the transport lost\n * ({@link isResumeTransportLoss}) while the request is still parked. `0`\n * disables retries. Defaults to {@link HITL_RESUME_TRANSPORT_RETRIES}.\n */\n maxTransportRetries?: number;\n /**\n * Re-enable the actions when no resume run started within this window —\n * covers a `run/input` that was rejected or lost before any run began, so\n * neither reset path below can fire. Omit to keep the pre-existing surface\n * behavior of staying locked until a resume run is observed.\n */\n pendingResumeGraceMs?: number;\n}\n\nexport interface ApprovalResumeLock<TValue> {\n /** True after a resume until the request identity changes (or recovery fires). */\n pending: boolean;\n /**\n * Send the resume value, locking the actions. No-op (returns `undefined`)\n * while pending or unparked. Returns the dispatch promise when `sendResume`\n * produced one, so a surface can hold its own state until the host settles.\n */\n resume: (value: TValue, extras?: ResumeExtras) => Promise<unknown> | undefined;\n}\n\n/**\n * Optimistic action lock shared by every approval surface: disable the\n * decision buttons the moment one is clicked, until the request identity\n * changes (it clears after the resume, or a fresh interrupt arrives). This\n * closes the double-click → duplicate-resume window.\n *\n * Recovery paths, in order of specificity:\n * 0. The dispatch itself rejected (a `sendResume` that returned a promise) —\n * released at once, and reported through `onResumeRejected`. A rejection\n * that is a transport loss (the socket dropped mid-flight) is re-sent up to\n * `maxTransportRetries` times first, the lock held throughout, so a flaky\n * connection does not hand the card back to the user for another click.\n * The returned promise settles with the final attempt.\n * 1. Identity change — the resume landed (or a new interrupt replaced the\n * request). Reset during render via React's \"previous value\" pattern.\n * 2. A resume run was observed starting and then settling with the request\n * still pending (failed/cancelled resume) — clear the lock so the user can\n * answer again.\n * 3. Optional grace window ({@link UseApprovalResumeLockOptions.pendingResumeGraceMs})\n * for a `run/input` that never started a run at all.\n */\nexport function useApprovalResumeLock<TValue = Record<string, string>>(\n options: UseApprovalResumeLockOptions<TValue>,\n): ApprovalResumeLock<TValue> {\n const {\n requestId,\n isRunning,\n sendResume,\n pendingResumeGraceMs,\n onResumeRejected,\n onResumeRetry,\n maxTransportRetries = HITL_RESUME_TRANSPORT_RETRIES,\n } = options;\n\n const [pending, setPending] = useState(false);\n // Bumped per re-send so the grace window restarts with each attempt.\n const [attempt, setAttempt] = useState(0);\n const prevRequestIdRef = useRef(requestId);\n if (prevRequestIdRef.current !== requestId) {\n prevRequestIdRef.current = requestId;\n if (pending) setPending(false);\n }\n\n // Track the resume run we kicked off (isRunning observed true→false while\n // pending) and clear `pending` when it ends with the request unresolved.\n const sawResumeRunRef = useRef(false);\n useEffect(() => {\n if (!pending) {\n sawResumeRunRef.current = false;\n return;\n }\n if (isRunning) {\n sawResumeRunRef.current = true;\n return;\n }\n if (sawResumeRunRef.current) {\n sawResumeRunRef.current = false;\n setPending(false);\n }\n }, [pending, isRunning]);\n\n // Pre-start failure recovery: re-enable after the grace window when no\n // resume run began; answering the still-parked request again is exactly\n // what the user needs to be able to do.\n useEffect(() => {\n if (!pending || pendingResumeGraceMs === undefined) return;\n const timer = setTimeout(() => {\n if (!sawResumeRunRef.current) setPending(false);\n }, pendingResumeGraceMs);\n return () => clearTimeout(timer);\n }, [pending, requestId, pendingResumeGraceMs, attempt]);\n\n const sendResumeRef = useRef(sendResume);\n sendResumeRef.current = sendResume;\n const onResumeRejectedRef = useRef(onResumeRejected);\n onResumeRejectedRef.current = onResumeRejected;\n const onResumeRetryRef = useRef(onResumeRetry);\n onResumeRetryRef.current = onResumeRetry;\n const maxTransportRetriesRef = useRef(maxTransportRetries);\n maxTransportRetriesRef.current = maxTransportRetries;\n const currentRequestIdRef = useRef(requestId);\n currentRequestIdRef.current = requestId;\n const pendingRef = useRef(pending);\n pendingRef.current = pending;\n // One token per `resume` call: a settle from an earlier submission must not\n // retry over, or release, a newer one for the same request.\n const submissionRef = useRef(0);\n\n const resume = useCallback(\n (value: TValue, extras?: ResumeExtras): Promise<unknown> | undefined => {\n if (requestId === undefined || pendingRef.current) return undefined;\n const submission = ++submissionRef.current;\n setPending(true);\n pendingRef.current = true;\n setAttempt(0);\n const first: unknown = sendResumeRef.current(requestId, value, extras);\n if (!(first instanceof Promise)) return undefined;\n // The final failure is already reported through `onResumeRejected`;\n // callers that drop the promise must not get an unhandled rejection.\n const outcome = new Promise<unknown>((resolve, reject) => {\n const settle = (dispatched: Promise<unknown>, retries: number) => {\n dispatched.then(resolve, (error: unknown) => {\n // A late refusal for a request the lock has since moved past (the\n // park was re-keyed, or a newer answer is in flight) must neither\n // release that answer's lock nor be reported as a failure of it.\n // The optimistic fold hides the answered request until the fold\n // rolls back, so `undefined` here is not a departure.\n const current = currentRequestIdRef.current;\n if (\n submission !== submissionRef.current ||\n (current !== undefined && current !== requestId)\n ) {\n reject(error);\n return;\n }\n if (retries < maxTransportRetriesRef.current && isResumeTransportLoss(error)) {\n const next = retries + 1;\n onResumeRetryRef.current?.(error, requestId, next);\n setPending(true);\n pendingRef.current = true;\n setAttempt(next);\n const resent: unknown = sendResumeRef.current(requestId, value, extras);\n if (resent instanceof Promise) {\n settle(resent, next);\n return;\n }\n resolve(undefined);\n return;\n }\n setPending(false);\n pendingRef.current = false;\n onResumeRejectedRef.current?.(error, requestId);\n reject(error);\n });\n };\n settle(first, 0);\n });\n outcome.catch(() => {});\n return outcome;\n },\n [requestId],\n );\n\n return { pending, resume };\n}\n"],"names":["hasClientToolInterruptSource","readDeepAgentStreamValues","statewireTransportOutcome","useState","useRef","useEffect","useCallback"],"mappings":";;;;;;AAkFA,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAGO,SAAS,mBACd,SAC+C;AAC/C,SAAO,QAAQ,SAAS,eAAe,EAAE,cAAc;AACzD;AAQA,MAAM,wCAA6D,oBAAI,IAAI,CAAC,uBAAuB,CAAC;AAO7F,SAAS,uBAAuB,SAA2B;AAChE,MAAI,CAAC,SAAS,OAAO,EAAG,QAAO;AAC/B,MAAI,QAAQ,yBAAyB,MAAO,QAAO;AACnD,SACE,OAAO,QAAQ,WAAW,YAAY,sCAAsC,IAAI,QAAQ,MAAM;AAElG;AASO,SAAS,wBACd,SAC+C;AAC/C,MAAI,CAAC,mBAAmB,OAAO,EAAG,QAAO;AACzC,QAAM,UAAW,QAAkC;AACnD,SAAO,CAACA,YAAAA,6BAA6B,OAAO,KAAK,CAAC,uBAAuB,OAAO;AAClF;AAGO,SAAS,eAAe,OAA4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