@athenaintel/react 0.24.0 → 0.24.1

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 (61) hide show
  1. package/README.md +11 -4
  2. package/dist/chat/StatewireApprovalCard.cjs +31 -6
  3. package/dist/chat/StatewireApprovalCard.cjs.map +1 -1
  4. package/dist/chat/StatewireApprovalCard.d.ts +34 -4
  5. package/dist/chat/StatewireApprovalCard.js +33 -8
  6. package/dist/chat/StatewireApprovalCard.js.map +1 -1
  7. package/dist/chat-ui/index.d.ts +1 -1
  8. package/dist/chat-ui/statewire.d.ts +1 -1
  9. package/dist/index.cjs +1 -0
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.ts +2 -2
  12. package/dist/index.js +2 -1
  13. package/dist/packages/agent-runtime/src/conversation-list.cjs.map +1 -1
  14. package/dist/packages/agent-runtime/src/conversation-list.js.map +1 -1
  15. package/dist/packages/agent-runtime/src/generated/runconfig-contract.cjs +1 -0
  16. package/dist/packages/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
  17. package/dist/packages/agent-runtime/src/generated/runconfig-contract.js +1 -0
  18. package/dist/packages/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
  19. package/dist/packages/agent-runtime/src/interrupts.cjs +22 -2
  20. package/dist/packages/agent-runtime/src/interrupts.cjs.map +1 -1
  21. package/dist/packages/agent-runtime/src/interrupts.js +22 -2
  22. package/dist/packages/agent-runtime/src/interrupts.js.map +1 -1
  23. package/dist/packages/agent-runtime/src/messages.cjs +2 -1
  24. package/dist/packages/agent-runtime/src/messages.cjs.map +1 -1
  25. package/dist/packages/agent-runtime/src/messages.js +2 -1
  26. package/dist/packages/agent-runtime/src/messages.js.map +1 -1
  27. package/dist/packages/agent-runtime/src/voice-presentation.cjs +6 -0
  28. package/dist/packages/agent-runtime/src/voice-presentation.cjs.map +1 -1
  29. package/dist/packages/agent-runtime/src/voice-presentation.js +6 -0
  30. package/dist/packages/agent-runtime/src/voice-presentation.js.map +1 -1
  31. package/dist/packages/agent-runtime/src/voice-turn-grouping.cjs +68 -0
  32. package/dist/packages/agent-runtime/src/voice-turn-grouping.cjs.map +1 -0
  33. package/dist/packages/agent-runtime/src/voice-turn-grouping.js +68 -0
  34. package/dist/packages/agent-runtime/src/voice-turn-grouping.js.map +1 -0
  35. package/dist/packages/react/package.json.cjs +1 -1
  36. package/dist/packages/react/package.json.js +1 -1
  37. package/dist/provider/AthenaProvider.cjs +2 -1
  38. package/dist/provider/AthenaProvider.cjs.map +1 -1
  39. package/dist/provider/AthenaProvider.js +2 -1
  40. package/dist/provider/AthenaProvider.js.map +1 -1
  41. package/dist/provider/theme-style-context.cjs +12 -0
  42. package/dist/provider/theme-style-context.cjs.map +1 -0
  43. package/dist/provider/theme-style-context.d.ts +8 -0
  44. package/dist/provider/theme-style-context.js +12 -0
  45. package/dist/provider/theme-style-context.js.map +1 -0
  46. package/dist/styles.css +1 -1
  47. package/dist/threads/SessionList.cjs +87 -16
  48. package/dist/threads/SessionList.cjs.map +1 -1
  49. package/dist/threads/SessionList.js +88 -17
  50. package/dist/threads/SessionList.js.map +1 -1
  51. package/dist/threads/session-list-model.cjs +13 -5
  52. package/dist/threads/session-list-model.cjs.map +1 -1
  53. package/dist/threads/session-list-model.d.ts +10 -3
  54. package/dist/threads/session-list-model.js +13 -5
  55. package/dist/threads/session-list-model.js.map +1 -1
  56. package/dist/ui/popover.cjs +46 -0
  57. package/dist/ui/popover.cjs.map +1 -0
  58. package/dist/ui/popover.d.ts +6 -0
  59. package/dist/ui/popover.js +46 -0
  60. package/dist/ui/popover.js.map +1 -0
  61. package/package.json +2 -2
@@ -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 /**\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\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\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 }]\n : [];\n return requests.map((request) => ({\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 }));\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\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/** 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: (requestId: string, value: TValue) => 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) => 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): 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);\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);\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":";;;;;;AAmEA,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,OA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;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 * 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 }[];\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\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}\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 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 }));\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\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/** 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: (requestId: string, value: TValue) => 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) => 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): 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);\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);\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":";;;;;;AAyEA,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,eAA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ED_MESSAGE
33
33
  function pendingActionRequests(hitl) {
34
34
  const context = hitl == null ? void 0 : hitl.context;
35
35
  if (!context) return [];
36
- 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 }] : [];
36
+ 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 }] : [];
37
37
  return requests.map((request) => ({
38
38
  name: typeof request.name === "string" ? request.name : "tool",
39
39
  args: isRecord(request.args) ? request.args : {},
40
40
  ...typeof request.tool_call_id === "string" && { toolCallId: request.tool_call_id },
41
41
  ...typeof request.interrupt_id === "string" && { interruptId: request.interrupt_id },
42
- ...request.session_approval_allowed === true && { sessionApprovalAllowed: true }
42
+ ...request.session_approval_allowed === true && { sessionApprovalAllowed: true },
43
+ ...Array.isArray(request.allowed_decisions) && request.allowed_decisions.includes("edit") && { editAllowed: true }
43
44
  }));
44
45
  }
45
46
  function canApproveForSession(actionRequests) {
@@ -95,6 +96,23 @@ function hitlResumeApproveForSession() {
95
96
  function hitlResumeReject(reason = HITL_REJECT_REASON) {
96
97
  return { action: "reject", reason };
97
98
  }
99
+ function actionRequestToolCallIds(actionRequests) {
100
+ if (actionRequests.length === 0) return null;
101
+ const ids = [];
102
+ for (const request of actionRequests) {
103
+ if (request.toolCallId === void 0 || ids.includes(request.toolCallId)) return null;
104
+ ids.push(request.toolCallId);
105
+ }
106
+ return ids;
107
+ }
108
+ function hitlResumeActionDecisions(decisions) {
109
+ const [anchorId, anchor] = Object.entries(decisions)[0] ?? [];
110
+ return {
111
+ action: (anchor == null ? void 0 : anchor.action) === "reject" ? "reject" : "approve",
112
+ ...anchorId !== void 0 && { tool_call_id: anchorId },
113
+ action_decisions: decisions
114
+ };
115
+ }
98
116
  const INTERRUPT_DECLINE_REASON = "User declined the request.";
99
117
  function interruptResumeDecline(reason = INTERRUPT_DECLINE_REASON) {
100
118
  return { action: "reject", reason };
@@ -205,10 +223,12 @@ export {
205
223
  HITL_REJECT_REASON,
206
224
  HITL_RESUME_TRANSPORT_RETRIES,
207
225
  INTERRUPT_DECLINE_REASON,
226
+ actionRequestToolCallIds,
208
227
  asHitlApproval,
209
228
  canApproveForSession,
210
229
  fanLaneDecision,
211
230
  findAbandonedInterrupt,
231
+ hitlResumeActionDecisions,
212
232
  hitlResumeApprove,
213
233
  hitlResumeApproveForSession,
214
234
  hitlResumeReject,
@@ -1 +1 @@
1
- {"version":3,"file":"interrupts.js","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 /**\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\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\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 }]\n : [];\n return requests.map((request) => ({\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 }));\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\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/** 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: (requestId: string, value: TValue) => 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) => 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): 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);\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);\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":[],"mappings":";;;;AAmEA,SAAS,SAAS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AAW,IAAI;AACf,yBAAW,UAAU;AACrB,yBAAW,IAAI;AACf,oBAAM,SAAkB,cAAc,QAAQ,WAAW,KAAK;AAC9D,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.js","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 }[];\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\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}\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 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 }));\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\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/** 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: (requestId: string, value: TValue) => 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) => 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): 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);\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);\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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messageWindow = require("./message-window.cjs");
10
10
  const optimisticContent = require("./optimistic-content.cjs");
11
11
  const statewireState = require("./statewire-state.cjs");
12
+ const voiceTurnGrouping = require("./voice-turn-grouping.cjs");
12
13
  const messageConverter = react.createMessageConverter(convertLangChainMessages.convertLangChainMessages);
13
14
  const wirePartsToOptimisticParts = (parts) => parts.flatMap((part) => {
14
15
  if (part.type === "text") return [part];
@@ -416,7 +417,7 @@ function convertDeepAgentState(state, {
416
417
  const sanitized = isLangGraphState(values) ? sanitizeLangChainMessages(values.messages, { toolOutputs }) : [];
417
418
  const tail = sanitized[sanitized.length - 1];
418
419
  const tailWithdrawn = tail !== void 0 && isWithdrawn(tail);
419
- const stateMessages = sanitized.filter((message) => !isWithdrawn(message));
420
+ const stateMessages = voiceTurnGrouping.groupSpokenUserTurns(sanitized.filter((message) => !isWithdrawn(message)));
420
421
  return {
421
422
  messages: messageConverter.toThreadMessages(
422
423
  [...withPendingAssistantMessage(stateMessages, isRunning && !tailWithdrawn), ...laneTail],