@athenaintel/react 0.59.0 → 0.60.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.
- package/README.md +124 -20
- package/dist/agent-runtime/src/client-tool-bridge.cjs +20 -2
- package/dist/agent-runtime/src/client-tool-bridge.cjs.map +1 -1
- package/dist/agent-runtime/src/client-tool-bridge.d.ts +9 -4
- package/dist/agent-runtime/src/client-tool-bridge.js +20 -2
- package/dist/agent-runtime/src/client-tool-bridge.js.map +1 -1
- package/dist/agent-runtime/src/client-tools.cjs.map +1 -1
- package/dist/agent-runtime/src/client-tools.d.ts +9 -0
- package/dist/agent-runtime/src/client-tools.js.map +1 -1
- package/dist/agent-runtime/src/composer-markdown.cjs +0 -16
- package/dist/agent-runtime/src/composer-markdown.cjs.map +1 -1
- package/dist/agent-runtime/src/composer-markdown.js +1 -17
- package/dist/agent-runtime/src/composer-markdown.js.map +1 -1
- package/dist/agent-runtime/src/named-agents.js +1 -1
- package/dist/agent-runtime/src/offline-status.cjs.map +1 -1
- package/dist/agent-runtime/src/offline-status.d.ts +27 -0
- package/dist/agent-runtime/src/offline-status.js.map +1 -1
- package/dist/agent-runtime/src/tool-metadata.cjs +7 -0
- package/dist/agent-runtime/src/tool-metadata.cjs.map +1 -1
- package/dist/agent-runtime/src/tool-metadata.js +7 -0
- package/dist/agent-runtime/src/tool-metadata.js.map +1 -1
- package/dist/chat/AthenaChat.cjs +17 -5
- package/dist/chat/AthenaChat.cjs.map +1 -1
- package/dist/chat/AthenaChat.js +18 -6
- package/dist/chat/AthenaChat.js.map +1 -1
- package/dist/chat/StatewireClientToolBridge.cjs +69 -1
- package/dist/chat/StatewireClientToolBridge.cjs.map +1 -1
- package/dist/chat/StatewireClientToolBridge.d.ts +14 -1
- package/dist/chat/StatewireClientToolBridge.js +70 -2
- package/dist/chat/StatewireClientToolBridge.js.map +1 -1
- package/dist/chat/StatewireClientToolConsentCard.cjs +65 -0
- package/dist/chat/StatewireClientToolConsentCard.cjs.map +1 -0
- package/dist/chat/StatewireClientToolConsentCard.d.ts +24 -0
- package/dist/chat/StatewireClientToolConsentCard.js +65 -0
- package/dist/chat/StatewireClientToolConsentCard.js.map +1 -0
- package/dist/chat/client-tool-write-consent.cjs +111 -0
- package/dist/chat/client-tool-write-consent.cjs.map +1 -0
- package/dist/chat/client-tool-write-consent.d.ts +71 -0
- package/dist/chat/client-tool-write-consent.js +111 -0
- package/dist/chat/client-tool-write-consent.js.map +1 -0
- package/dist/chat/statewire-client-tools.cjs +30 -5
- package/dist/chat/statewire-client-tools.cjs.map +1 -1
- package/dist/chat/statewire-client-tools.d.ts +34 -2
- package/dist/chat/statewire-client-tools.js +30 -5
- package/dist/chat/statewire-client-tools.js.map +1 -1
- package/dist/chat-ui/index.cjs +2 -0
- package/dist/chat-ui/index.cjs.map +1 -1
- package/dist/chat-ui/index.d.ts +1 -0
- package/dist/chat-ui/index.js +2 -0
- package/dist/chat-ui/index.js.map +1 -1
- package/dist/chat-ui/mentions/mention-chip.cjs +9 -3
- package/dist/chat-ui/mentions/mention-chip.cjs.map +1 -1
- package/dist/chat-ui/mentions/mention-chip.js +9 -3
- package/dist/chat-ui/mentions/mention-chip.js.map +1 -1
- package/dist/chat-ui/mentions/suggestions/components/mention-icon.cjs +18 -2
- package/dist/chat-ui/mentions/suggestions/components/mention-icon.cjs.map +1 -1
- package/dist/chat-ui/mentions/suggestions/components/mention-icon.d.ts +10 -1
- package/dist/chat-ui/mentions/suggestions/components/mention-icon.js +19 -3
- package/dist/chat-ui/mentions/suggestions/components/mention-icon.js.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/api-client.cjs +9 -0
- package/dist/chat-ui/mentions/suggestions/data/api-client.cjs.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/api-client.d.ts +6 -0
- package/dist/chat-ui/mentions/suggestions/data/api-client.js +9 -0
- package/dist/chat-ui/mentions/suggestions/data/api-client.js.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icon-names.generated.cjs +89 -0
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icon-names.generated.cjs.map +1 -0
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icon-names.generated.d.ts +8 -0
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icon-names.generated.js +89 -0
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icon-names.generated.js.map +1 -0
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.cjs +153 -116
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.cjs.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.d.ts +58 -12
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.js +154 -117
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.js.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/sources/index.cjs +38 -6
- package/dist/chat-ui/mentions/suggestions/data/sources/index.cjs.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/sources/index.js +40 -8
- package/dist/chat-ui/mentions/suggestions/data/sources/index.js.map +1 -1
- package/dist/chat-ui/mentions/use-asset-icon-app-url.cjs +13 -0
- package/dist/chat-ui/mentions/use-asset-icon-app-url.cjs.map +1 -0
- package/dist/chat-ui/mentions/use-asset-icon-app-url.d.ts +9 -0
- package/dist/chat-ui/mentions/use-asset-icon-app-url.js +13 -0
- package/dist/chat-ui/mentions/use-asset-icon-app-url.js.map +1 -0
- package/dist/chat-ui/statewire.cjs +4 -0
- package/dist/chat-ui/statewire.cjs.map +1 -1
- package/dist/chat-ui/statewire.d.ts +2 -0
- package/dist/chat-ui/statewire.js +4 -0
- package/dist/chat-ui/statewire.js.map +1 -1
- package/dist/collab/client.cjs +24 -1
- package/dist/collab/client.cjs.map +1 -1
- package/dist/collab/client.d.ts +16 -0
- package/dist/collab/client.js +24 -1
- package/dist/collab/client.js.map +1 -1
- package/dist/composer/attached-references.js +1 -1
- package/dist/composer/staged-message-metadata.cjs +12 -0
- package/dist/composer/staged-message-metadata.cjs.map +1 -0
- package/dist/composer/staged-message-metadata.d.ts +15 -0
- package/dist/composer/staged-message-metadata.js +12 -0
- package/dist/composer/staged-message-metadata.js.map +1 -0
- package/dist/data/athena-request.cjs +2 -0
- package/dist/data/athena-request.cjs.map +1 -1
- package/dist/data/athena-request.js +2 -0
- package/dist/data/athena-request.js.map +1 -1
- package/dist/index.cjs +5 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/dist/provider/AthenaProvider.cjs +26 -6
- package/dist/provider/AthenaProvider.cjs.map +1 -1
- package/dist/provider/AthenaProvider.d.ts +8 -1
- package/dist/provider/AthenaProvider.js +27 -7
- package/dist/provider/AthenaProvider.js.map +1 -1
- package/dist/react/package.json.cjs +1 -1
- package/dist/react/package.json.js +1 -1
- package/dist/references/src/anchors/parse.cjs +11 -1
- package/dist/references/src/anchors/parse.cjs.map +1 -1
- package/dist/references/src/anchors/parse.js +11 -1
- package/dist/references/src/anchors/parse.js.map +1 -1
- package/dist/references/src/anchors/schemas.d.ts +1 -0
- package/dist/references/src/anchors/serialize.cjs +1 -0
- package/dist/references/src/anchors/serialize.cjs.map +1 -1
- package/dist/references/src/anchors/serialize.js +1 -0
- package/dist/references/src/anchors/serialize.js.map +1 -1
- package/dist/references/src/anchors/types.cjs.map +1 -1
- package/dist/references/src/anchors/types.d.ts +9 -0
- package/dist/references/src/anchors/types.js.map +1 -1
- package/dist/references/src/schemas.d.ts +2 -0
- package/dist/runtime/useAthenaStatewireRuntime.cjs +6 -8
- package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
- package/dist/runtime/useAthenaStatewireRuntime.js +6 -8
- package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
- package/dist/threads/statewire-thread-list.cjs +14 -2
- package/dist/threads/statewire-thread-list.cjs.map +1 -1
- package/dist/threads/statewire-thread-list.d.ts +11 -2
- package/dist/threads/statewire-thread-list.js +14 -2
- package/dist/threads/statewire-thread-list.js.map +1 -1
- package/dist/tools/drive-tool-uis.cjs +8 -4
- package/dist/tools/drive-tool-uis.cjs.map +1 -1
- package/dist/tools/drive-tool-uis.d.ts +5 -4
- package/dist/tools/drive-tool-uis.js +9 -5
- package/dist/tools/drive-tool-uis.js.map +1 -1
- package/dist/version.cjs +4 -0
- package/dist/version.cjs.map +1 -1
- package/dist/version.d.ts +9 -0
- package/dist/version.js +4 -0
- package/dist/version.js.map +1 -1
- package/dist/workbench/live-desktop-api.cjs +2 -1
- package/dist/workbench/live-desktop-api.cjs.map +1 -1
- package/dist/workbench/live-desktop-api.js +2 -1
- package/dist/workbench/live-desktop-api.js.map +1 -1
- package/dist/workbench/session-workspace-api.cjs +7 -2
- package/dist/workbench/session-workspace-api.cjs.map +1 -1
- package/dist/workbench/session-workspace-api.d.ts +10 -0
- package/dist/workbench/session-workspace-api.js +7 -2
- package/dist/workbench/session-workspace-api.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-tool-bridge.js","sources":["../../../../agent-runtime/src/client-tool-bridge.ts"],"sourcesContent":["/**\n * The statewire client-tool bridge loop, shared by every surface that executes\n * frontend tool calls (Olympus, the React SDK, the Office add-in, mobile).\n *\n * Tools declared through `runConfig.custom.client_tools` have no backend\n * implementation: a call parks the run on an interrupt that arrives as a\n * statewire input request. A bridge with handlers for the whole batch claims\n * it (exactly-once per ownership domain), runs those handlers, and resumes\n * with per-call result envelopes. Other attached tabs leave it for the\n * executing surface; a thrown handler still returns an actionable error.\n *\n * Wire-adjacent correctness invariants this module owns, so they can never\n * drift apart per surface again:\n * - exactly-once claim per request, with un-claim on every path that did NOT\n * run any handler (abandoned before execution, consent dismissed, unmount\n * before the first handler) so a re-emitted request is executable instead\n * of stranding the run;\n * - once a batch has STARTED executing handlers, its claim is never released\n * by unmount: handlers cannot be cancelled, so releasing would let another\n * mount re-claim the re-emitted request and re-execute side effects that\n * already ran (double-executing a mutating tool). The completed wire-safe\n * result is cached and may be replayed across reconnects/remounts instead;\n * - liveness checks between awaits (the run can be stopped or answered\n * elsewhere while a handler runs) so a stale request is never resumed;\n * - per-call JSON wire-safety, so one unrepresentable handler result answers\n * that one call with an error instead of failing the whole batch.\n *\n * Like `interrupts.ts`, this is parameterized rather than self-wiring: the\n * host component reads `useStatewireRuns().inputRequests` and\n * `useStatewireSendCommand()` itself (both mockable per surface) and passes\n * them in, together with its ownership tracker and write-consent policy.\n */\n\nimport type { StatewireThread } from '@assistant-ui/react-statewire';\nimport { useCallback, useEffect, useRef } from 'react';\nimport {\n type ClientToolCallRequest,\n type ClientToolRequestTracker,\n type ClientToolResultEnvelope,\n clientToolCallArgs,\n clientToolErrorEnvelope,\n clientToolResultsResumeValue,\n clientToolSuccessEnvelope,\n isClientToolInterrupt,\n} from './client-tools';\n\n/** A locally executable tool, normalized across the per-surface tool shapes. */\nexport interface ClientToolBridgeTool {\n /** Snake_case tool id the model calls (e.g. `update_sheet_range`). */\n name: string;\n /** Mutating tools gate on the surface's write-consent flow (`confirmWrites`). */\n requiresWrite?: boolean;\n run: (\n args: Record<string, unknown>,\n context: { toolCallId: string },\n ) => Promise<unknown>;\n}\n\n/**\n * Batch write-consent outcome. `proceed` runs the write calls, `declined`\n * answers them with the declined message while reads still run, `abandoned`\n * releases the claim without resuming (the request died, or the consent UI was\n * dismissed by the run moving on). Grant persistence (a thread set, a stored\n * preference) is the surface's own policy, applied inside its callback.\n */\nexport type ClientToolWriteConsentDecision = 'proceed' | 'declined' | 'abandoned';\n\nexport interface ClientToolCallSettledEvent {\n toolName: string;\n status: 'success' | 'error' | 'declined';\n errorType?: string;\n}\n\n/** Default resume error for a write call the user declined. */\nexport const CLIENT_TOOL_WRITE_DECLINED_MESSAGE =\n 'The user declined this edit. Do not retry it; ask the user how to proceed.';\n\n/** Default resume error for a call naming a tool this surface does not have. */\nexport function defaultMissingClientToolMessage(toolName: string): string {\n return `This surface has no tool named '${toolName}'.`;\n}\n\n/** Statewire request ids are unique per run, but a thread scope keeps a\n * process-wide claim unambiguous when two conversations are open at once. */\nexport function clientToolClaimKey(threadId: string, requestId: string): string {\n return `${threadId}:${requestId}`;\n}\n\nconst CLIENT_TOOL_RESUME_RETRY_DELAYS_MS = [2_000, 5_000, 10_000, 15_000, 30_000];\nconst MAX_CLIENT_TOOL_RESUME_ATTEMPTS = 25;\n\nfunction clientToolResumeRetryDelayMs(attemptNumber: number): number {\n const index = Math.min(\n Math.max(attemptNumber - 1, 0),\n CLIENT_TOOL_RESUME_RETRY_DELAYS_MS.length - 1,\n );\n return CLIENT_TOOL_RESUME_RETRY_DELAYS_MS[index] ?? 30_000;\n}\n\n/**\n * A wire-safe copy of a handler's return value: handlers can return values\n * JSON cannot represent (DOM nodes, host objects, bigints), which must never\n * reach the transport. Throws for an unrepresentable value so the caller can\n * answer that one call with an error instead of stranding the whole batch.\n */\nexport function jsonSafeClientToolResult(value: unknown): unknown {\n const serialized = JSON.stringify(value);\n return serialized === undefined ? null : JSON.parse(serialized);\n}\n\n/** A parked, unanswered client-tool input request. */\nexport function isPendingClientToolRequest(\n request: StatewireThread.InputRequestState,\n): request is StatewireThread.CustomInputRequest {\n if (request.type !== 'interrupt' || 'response' in request) return false;\n return isClientToolInterrupt((request as { payload?: unknown }).payload);\n}\n\nexport interface ExecuteClientToolBatchOptions {\n calls: readonly ClientToolCallRequest[];\n tools: readonly ClientToolBridgeTool[];\n /** Whether the parked request still exists and this surface may answer it.\n * Checked before consent resolution, before every call, and before the\n * results are handed back for resume. */\n isLive: () => boolean;\n /** Batch write gate; absent means writes run without consent (surfaces that\n * only register read tools). Called once per batch, before any handler. */\n confirmWrites?: (batch: {\n writeToolNames: readonly string[];\n }) => Promise<ClientToolWriteConsentDecision>;\n writeDeclinedMessage?: string;\n missingToolMessage?: (toolName: string) => string;\n /** Per-call telemetry (the Office add-in's tool events). */\n onCallSettled?: (event: ClientToolCallSettledEvent) => void;\n /**\n * Called once, after the write-consent gate resolves and immediately before\n * the first handler runs — the point where side effects begin. There is no\n * await between this callback and the first handler invocation, so a caller\n * marking \"execution started\" here can never miss a handler that ran.\n */\n onExecutionStart?: () => void;\n}\n\n/**\n * Execute one batched client-tool park: consent, per-call execution with\n * wire-safe envelopes, liveness aborts. Returns the per-interrupt result map\n * to resume with, or `null` when the batch was abandoned (the request died,\n * consent was abandoned, or the surface went away) — the caller must release\n * its claim and must NOT resume.\n */\nexport async function executeClientToolBatch(\n options: ExecuteClientToolBatchOptions,\n): Promise<Record<string, ClientToolResultEnvelope> | null> {\n const {\n calls,\n tools,\n isLive,\n confirmWrites,\n writeDeclinedMessage = CLIENT_TOOL_WRITE_DECLINED_MESSAGE,\n missingToolMessage = defaultMissingClientToolMessage,\n onCallSettled,\n onExecutionStart,\n } = options;\n const registry = new Map(tools.map((tool) => [tool.name, tool]));\n\n // One consent covers the whole batch (and whatever scope the surface's\n // callback persists): writes are declined together while reads still run.\n let writesDeclined = false;\n const writeToolNames = calls\n .filter((call) => registry.get(call.tool_name)?.requiresWrite === true)\n .map((call) => call.tool_name);\n if (writeToolNames.length > 0 && confirmWrites) {\n const decision = await confirmWrites({ writeToolNames });\n if (decision === 'abandoned' || !isLive()) {\n // The run was stopped (or answered elsewhere) while consent was\n // pending: abort before any handler mutates the user's asset.\n return null;\n }\n writesDeclined = decision === 'declined';\n }\n\n onExecutionStart?.();\n\n const results: Record<string, ClientToolResultEnvelope> = {};\n for (const call of calls) {\n if (!isLive()) return null;\n const tool = registry.get(call.tool_name);\n let envelope: ClientToolResultEnvelope;\n let status: ClientToolCallSettledEvent['status'] = 'success';\n let errorType: string | undefined;\n if (!tool) {\n envelope = clientToolErrorEnvelope(missingToolMessage(call.tool_name));\n status = 'error';\n errorType = 'UnknownClientTool';\n } else if (tool.requiresWrite === true && writesDeclined) {\n envelope = clientToolErrorEnvelope(writeDeclinedMessage);\n status = 'declined';\n } else {\n try {\n envelope = clientToolSuccessEnvelope(\n jsonSafeClientToolResult(\n await tool.run(clientToolCallArgs(call), {\n toolCallId: call.interrupt_id,\n }),\n ),\n );\n } catch (error) {\n envelope = clientToolErrorEnvelope(error);\n status = 'error';\n errorType = error instanceof Error ? error.name : typeof error;\n }\n }\n results[call.interrupt_id] = envelope;\n onCallSettled?.({\n toolName: call.tool_name,\n status,\n ...(errorType !== undefined ? { errorType } : {}),\n });\n }\n\n // Abandoned mid-flight: resuming a dead request would error, and a\n // re-emitted one must be executable again.\n return isLive() ? results : null;\n}\n\nexport interface UseStatewireClientToolBridgeOptions {\n threadId: string;\n tools: readonly ClientToolBridgeTool[];\n /**\n * Ownership domain for parked-request claims. Pass a module-scoped tracker\n * to make ownership process-wide across every mount of the surface (two\n * mounted surfaces of one conversation execute each request exactly once),\n * or a per-mount tracker to scope ownership to one mounted bridge.\n */\n tracker: ClientToolRequestTracker;\n /** The surface's `useStatewireRuns().inputRequests` read. */\n inputRequests: readonly StatewireThread.InputRequestState[] | undefined;\n /** Dispatch the `run/input` resume on the surface's transport. The value is\n * already wire-safe (per-call JSON round-trip inside the batch engine). */\n /** Dispatch the answer and settle only once the Statewire host accepts or\n * rejects the command. The bridge deliberately keeps replaying while this\n * promise is pending: `run/input` removes the request optimistically before\n * the server has accepted the answer. */\n sendResume: (\n requestId: string,\n value: Record<string, unknown>,\n ) => PromiseLike<unknown>;\n /** Batch write gate, with the parked request's id so the surface can close\n * its consent UI the instant that request disappears. */\n confirmWrites?: (batch: {\n requestId: string;\n writeToolNames: readonly string[];\n }) => Promise<ClientToolWriteConsentDecision>;\n writeDeclinedMessage?: string;\n missingToolMessage?: (toolName: string) => string;\n onCallSettled?: (event: ClientToolCallSettledEvent) => void;\n /** Log prefix for resume-dispatch failures. */\n logLabel?: string;\n}\n\n/**\n * The claim lifecycle around {@link executeClientToolBatch}: claim the pending\n * request once per ownership domain, execute, resume — releasing the claim on\n * every path that ran no handler, so re-emitted requests recover.\n *\n * Unmount splits by whether side effects began:\n * - a claim whose batch has NOT started executing (claimed this tick, or\n * parked on write consent) is released, so another mount — or a remount —\n * can execute the re-emitted request instead of stranding the parked run;\n * - a claim whose batch HAS started stays held: handlers cannot be cancelled,\n * so releasing would let a sibling mount re-claim and re-execute a mutation\n * whose side effects already ran. The detached execution caches its result\n * and attempts one resume through its captured transport; a later mount can\n * replay the same result without repeating the side effect.\n */\nexport function useStatewireClientToolBridge(\n options: UseStatewireClientToolBridgeOptions,\n): void {\n const { threadId, tracker, inputRequests, logLabel = '[AthenaSDK]' } = options;\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const toolNames = new Set(options.tools.map((tool) => tool.name));\n const pendingRequest = inputRequests?.find((request) => {\n if (!isPendingClientToolRequest(request)) return false;\n const payload = (request as StatewireThread.CustomInputRequest).payload;\n if (!isClientToolInterrupt(payload)) return false;\n // Every attached tab sees the same park. An observer without these tools\n // must not claim it and race the executing surface with an unknown-tool\n // error (for example, Olympus watching an Excel conversation).\n // A cached result already belongs to this tracker and can be replayed\n // without loading its handlers again.\n return (\n tracker.getCachedResume(clientToolClaimKey(threadId, request.id)) !== undefined ||\n payload.context.requests.every((call) => toolNames.has(call.tool_name))\n );\n });\n\n // Claims this bridge holds but has not resumed, split by whether their\n // batch has begun running handlers. The ref Set instances are stable (only\n // their contents mutate), so the unmount cleanup sees every claim.\n const ownedClaimsRef = useRef<Set<string>>(new Set());\n const startedClaimsRef = useRef<Set<string>>(new Set());\n const resumeOwnerRef = useRef(Symbol('client-tool-resume-owner'));\n const resumeClaimsRef = useRef<Set<string>>(new Set());\n const resumeTimersRef = useRef<\n Map<string, { requestId: string; timer: ReturnType<typeof setTimeout> }>\n >(new Map());\n const activeRef = useRef(true);\n const releaseClaim = useCallback(\n (claim: string) => {\n // Release the shared tracker entry only while THIS mount still owns it.\n // A detached batch can settle after the unmount cleanup already released\n // (and disowned) its claim; by then the tracker entry may belong to\n // another mount that claimed, executed, and resumed — releasing it here\n // would let a stale re-emission of the same request execute again.\n const owned = ownedClaimsRef.current.delete(claim);\n startedClaimsRef.current.delete(claim);\n if (owned) tracker.release(claim);\n },\n [tracker],\n );\n const stopResumeReplay = useCallback(\n (claim: string) => {\n const timerEntry = resumeTimersRef.current.get(claim);\n if (timerEntry) clearTimeout(timerEntry.timer);\n resumeTimersRef.current.delete(claim);\n if (resumeClaimsRef.current.delete(claim)) {\n tracker.releaseResumeReplay(claim, resumeOwnerRef.current);\n }\n },\n [tracker],\n );\n useEffect(() => {\n activeRef.current = true;\n const ownedClaims = ownedClaimsRef.current;\n const startedClaims = startedClaimsRef.current;\n return () => {\n activeRef.current = false;\n for (const claim of Array.from(resumeClaimsRef.current)) {\n stopResumeReplay(claim);\n }\n for (const claim of ownedClaims) {\n // Started batches keep their claim — their detached execution settles\n // it (resume, or release on a failed dispatch). Releasing here would\n // double-execute the side effects that already ran.\n if (startedClaims.has(claim)) continue;\n ownedClaims.delete(claim);\n tracker.release(claim);\n }\n };\n }, [stopResumeReplay, tracker]);\n\n // Handlers (and consent) are async, so the run can be stopped or the request\n // answered elsewhere while we await. The live ids let us abandon an\n // unfinished local execution when its request is no longer present. Once a\n // result is cached, only command settlement may stop its replay: Statewire\n // removes submitted requests optimistically before the host accepts them.\n const liveRequestIdsRef = useRef<ReadonlySet<string>>(new Set());\n liveRequestIdsRef.current = new Set((inputRequests ?? []).map((request) => request.id));\n\n const startResumeReplay = useCallback(\n (claim: string, requestId: string) => {\n if (!activeRef.current || resumeClaimsRef.current.has(claim)) return;\n if (!tracker.claimResumeReplay(claim, resumeOwnerRef.current)) return;\n resumeClaimsRef.current.add(claim);\n\n const dispatch = (): void => {\n resumeTimersRef.current.delete(claim);\n if (!activeRef.current) {\n stopResumeReplay(claim);\n return;\n }\n const attempt = tracker.takeResumeAttempt(claim, {\n owner: resumeOwnerRef.current,\n maxAttempts: MAX_CLIENT_TOOL_RESUME_ATTEMPTS,\n });\n if (!attempt) {\n stopResumeReplay(claim);\n return;\n }\n\n try {\n const settled = optionsRef.current.sendResume(requestId, attempt.value);\n // A fulfilled command result is the authoritative acknowledgement:\n // the host accepted and applied the answer. The local input request\n // disappearing is NOT an acknowledgement because the Statewire\n // reducer does that optimistically as soon as the command is\n // submitted.\n void Promise.resolve(settled).then(\n () => {\n // Keep the execution claim, but discard the cached result once\n // the host accepts it. A stale pending-request render can no\n // longer replay the command or re-execute the local mutation.\n tracker.settleResume(claim);\n stopResumeReplay(claim);\n },\n (error) => {\n // A rejected attempt may have raced another still-pending\n // replay. Keep the bounded loop alive; any accepted sibling\n // stops it, while the global attempt cap prevents storms.\n console.error(`${logLabel} failed to resume client tool results:`, error);\n },\n );\n } catch (error) {\n // Keep the cached result and retry it. Re-executing a mutating local\n // handler would be unsafe; replaying its id-stamped result is safe.\n console.error(`${logLabel} failed to resume client tool results:`, error);\n }\n\n if (\n attempt.attemptNumber >= MAX_CLIENT_TOOL_RESUME_ATTEMPTS ||\n !activeRef.current ||\n !resumeClaimsRef.current.has(claim)\n ) {\n stopResumeReplay(claim);\n return;\n }\n const timer = setTimeout(dispatch, clientToolResumeRetryDelayMs(attempt.attemptNumber));\n resumeTimersRef.current.set(claim, { requestId, timer });\n };\n\n dispatch();\n },\n [logLabel, stopResumeReplay, tracker],\n );\n\n const executeRequest = useCallback(\n async (request: StatewireThread.CustomInputRequest) => {\n const payload = request.payload;\n if (!isClientToolInterrupt(payload)) return;\n const claim = clientToolClaimKey(threadId, request.id);\n const {\n tools,\n confirmWrites,\n writeDeclinedMessage,\n missingToolMessage,\n onCallSettled,\n sendResume,\n } = optionsRef.current;\n\n const results = await executeClientToolBatch({\n calls: payload.context.requests,\n tools,\n // Live while the request still exists AND this surface may answer it:\n // mounted, or already past the point of no return (handlers started —\n // the detached execution must finish and settle, never re-execute).\n // After unmount the request-id snapshot freezes at its last observed\n // state, which keeps a started batch's own request visible to it.\n isLive: () =>\n liveRequestIdsRef.current.has(request.id) &&\n (activeRef.current || startedClaimsRef.current.has(claim)),\n onExecutionStart: () => {\n startedClaimsRef.current.add(claim);\n },\n ...(confirmWrites\n ? {\n confirmWrites: ({ writeToolNames }: { writeToolNames: readonly string[] }) =>\n confirmWrites({ requestId: request.id, writeToolNames }),\n }\n : {}),\n ...(writeDeclinedMessage !== undefined ? { writeDeclinedMessage } : {}),\n ...(missingToolMessage ? { missingToolMessage } : {}),\n ...(onCallSettled ? { onCallSettled } : {}),\n });\n if (results === null) {\n releaseClaim(claim);\n return;\n }\n\n const resumeValue = clientToolResultsResumeValue(results);\n tracker.cacheResume(claim, resumeValue);\n // Execution is complete, but the exactly-once claim remains. A pending\n // re-emission must replay this cached value, never run the handlers again.\n ownedClaimsRef.current.delete(claim);\n startedClaimsRef.current.delete(claim);\n\n if (!activeRef.current) {\n // The handler crossed an unmount. Preserve the pre-existing best-effort\n // settle through its captured transport, but leave the cached result\n // available for a later mount if this dispatch is lost.\n if (tracker.claimResumeReplay(claim, resumeOwnerRef.current)) {\n const attempt = tracker.takeResumeAttempt(claim, {\n owner: resumeOwnerRef.current,\n maxAttempts: MAX_CLIENT_TOOL_RESUME_ATTEMPTS,\n });\n if (attempt) {\n try {\n void Promise.resolve(sendResume(request.id, attempt.value)).then(\n () => tracker.settleResume(claim),\n (error) => {\n console.error(`${logLabel} failed to resume client tool results:`, error);\n },\n );\n } catch (error) {\n console.error(`${logLabel} failed to resume client tool results:`, error);\n }\n }\n // Ownership only fences this best-effort dispatch; a future mount\n // may claim and replay the cached value if it did not settle.\n tracker.releaseResumeReplay(claim, resumeOwnerRef.current);\n }\n return;\n }\n\n startResumeReplay(claim, request.id);\n },\n [logLabel, releaseClaim, startResumeReplay, threadId, tracker],\n );\n\n useEffect(() => {\n if (!pendingRequest) return;\n const claim = clientToolClaimKey(threadId, pendingRequest.id);\n if (!tracker.claim(claim)) {\n // The local handler already ran. This is the reconnect/remount path:\n // replay its cached answer instead of double-executing the side effect.\n if (tracker.getCachedResume(claim)) {\n startResumeReplay(claim, pendingRequest.id);\n }\n return;\n }\n ownedClaimsRef.current.add(claim);\n void executeRequest(pendingRequ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nC,uBAAiB,QAAQ,OAAO,KAAK;AAErC,UAAI,CAAC,UAAU,SAAS;AAItB,YAAI,QAAQ,kBAAkB,OAAO,eAAe,OAAO,GAAG;AAC5D,gBAAM,UAAU,QAAQ,kBAAkB,OAAO;AAAA,YAC/C,OAAO,eAAe;AAAA,YACtB,aAAa;AAAA,UAAA,CACd;AACD,cAAI,SAAS;AACX,gBAAI;AACF,mBAAK,QAAQ,QAAQ,WAAW,QAAQ,IAAI,QAAQ,KAAK,CAAC,EAAE;AAAA,gBAC1D,MAAM,QAAQ,aAAa,KAAK;AAAA,gBAChC,CAAC,UAAU;AACT,0BAAQ,MAAM,GAAG,QAAQ,0CAA0C,KAAK;AAAA,gBAC1E;AAAA,cAAA;AAAA,YAEJ,SAAS,OAAO;AACd,sBAAQ,MAAM,GAAG,QAAQ,0CAA0C,KAAK;AAAA,YAC1E;AAAA,UACF;AAGA,kBAAQ,oBAAoB,OAAO,eAAe,OAAO;AAAA,QAC3D;AACA;AAAA,MACF;AAEA,wBAAkB,OAAO,QAAQ,EAAE;AAAA,IACrC;AAAA,IACA,CAAC,UAAU,cAAc,mBAAmB,UAAU,OAAO;AAAA,EAAA;AAG/D,YAAU,MAAM;AACd,QAAI,CAAC,eAAgB;AACrB,UAAM,QAAQ,mBAAmB,UAAU,eAAe,EAAE;AAC5D,QAAI,CAAC,QAAQ,MAAM,KAAK,GAAG;AAGzB,UAAI,QAAQ,gBAAgB,KAAK,GAAG;AAClC,0BAAkB,OAAO,eAAe,EAAE;AAAA,MAC5C;AACA;AAAA,IACF;AACA,mBAAe,QAAQ,IAAI,KAAK;AAChC,SAAK,eAAe,cAAc;AAAA,EACpC,GAAG,CAAC,gBAAgB,gBAAgB,mBAAmB,UAAU,OAAO,CAAC;AAC3E;"}
|
|
1
|
+
{"version":3,"file":"client-tool-bridge.js","sources":["../../../../agent-runtime/src/client-tool-bridge.ts"],"sourcesContent":["/**\n * The statewire client-tool bridge loop, shared by every surface that executes\n * frontend tool calls (Olympus, the React SDK, the Office add-in, mobile).\n *\n * Tools declared through `runConfig.custom.client_tools` have no backend\n * implementation: a call parks the run on an interrupt that arrives as a\n * statewire input request. A bridge with handlers for the whole batch claims\n * it (exactly-once per ownership domain), runs those handlers, and resumes\n * with per-call result envelopes. Other attached tabs leave it for the\n * executing surface; a thrown handler still returns an actionable error.\n *\n * Wire-adjacent correctness invariants this module owns, so they can never\n * drift apart per surface again:\n * - exactly-once claim per request, with un-claim on every path that did NOT\n * run any handler (abandoned before execution, consent dismissed, unmount\n * before the first handler) so a re-emitted request is executable instead\n * of stranding the run;\n * - once a batch has STARTED executing handlers, its claim is never released\n * by unmount: handlers cannot be cancelled, so releasing would let another\n * mount re-claim the re-emitted request and re-execute side effects that\n * already ran (double-executing a mutating tool). The completed wire-safe\n * result is cached and may be replayed across reconnects/remounts instead;\n * - liveness checks between awaits (the run can be stopped or answered\n * elsewhere while a handler runs) so a stale request is never resumed;\n * - per-call JSON wire-safety, so one unrepresentable handler result answers\n * that one call with an error instead of failing the whole batch.\n *\n * Like `interrupts.ts`, this is parameterized rather than self-wiring: the\n * host component reads `useStatewireRuns().inputRequests` and\n * `useStatewireSendCommand()` itself (both mockable per surface) and passes\n * them in, together with its ownership tracker and write-consent policy.\n */\n\nimport type { StatewireThread } from '@assistant-ui/react-statewire';\nimport { useCallback, useEffect, useRef } from 'react';\nimport {\n type ClientToolCallRequest,\n type ClientToolHandlerContext,\n type ClientToolRequestTracker,\n type ClientToolResultEnvelope,\n clientToolCallArgs,\n clientToolErrorEnvelope,\n clientToolResultsResumeValue,\n clientToolSuccessEnvelope,\n isClientToolInterrupt,\n} from './client-tools';\n\n/** A locally executable tool, normalized across the per-surface tool shapes. */\nexport interface ClientToolBridgeTool {\n /** Snake_case tool id the model calls (e.g. `update_sheet_range`). */\n name: string;\n /** Mutating tools gate on the surface's write-consent flow (`confirmWrites`). */\n requiresWrite?: boolean;\n run: (\n args: Record<string, unknown>,\n context: ClientToolHandlerContext,\n ) => Promise<unknown>;\n}\n\n/**\n * Batch write-consent outcome. `proceed` runs the write calls, `declined`\n * answers them with the declined message while reads still run, `abandoned`\n * releases the claim without resuming (the request died, or the consent UI was\n * dismissed by the run moving on). Grant persistence (a thread set, a stored\n * preference) is the surface's own policy, applied inside its callback.\n */\nexport type ClientToolWriteConsentDecision = 'proceed' | 'declined' | 'abandoned';\n\nexport interface ClientToolCallSettledEvent {\n toolName: string;\n status: 'success' | 'error' | 'declined';\n errorType?: string;\n}\n\n/** Default resume error for a write call the user declined. */\nexport const CLIENT_TOOL_WRITE_DECLINED_MESSAGE =\n 'The user declined this edit. Do not retry it; ask the user how to proceed.';\n\n/** Default resume error for a call naming a tool this surface does not have. */\nexport function defaultMissingClientToolMessage(toolName: string): string {\n return `This surface has no tool named '${toolName}'.`;\n}\n\n/** Statewire request ids are unique per run, but a thread scope keeps a\n * process-wide claim unambiguous when two conversations are open at once. */\nexport function clientToolClaimKey(threadId: string, requestId: string): string {\n return `${threadId}:${requestId}`;\n}\n\nconst CLIENT_TOOL_RESUME_RETRY_DELAYS_MS = [2_000, 5_000, 10_000, 15_000, 30_000];\nconst MAX_CLIENT_TOOL_RESUME_ATTEMPTS = 25;\n\nfunction clientToolResumeRetryDelayMs(attemptNumber: number): number {\n const index = Math.min(\n Math.max(attemptNumber - 1, 0),\n CLIENT_TOOL_RESUME_RETRY_DELAYS_MS.length - 1,\n );\n return CLIENT_TOOL_RESUME_RETRY_DELAYS_MS[index] ?? 30_000;\n}\n\n/**\n * A wire-safe copy of a handler's return value: handlers can return values\n * JSON cannot represent (DOM nodes, host objects, bigints), which must never\n * reach the transport. Throws for an unrepresentable value so the caller can\n * answer that one call with an error instead of stranding the whole batch.\n */\nexport function jsonSafeClientToolResult(value: unknown): unknown {\n const serialized = JSON.stringify(value);\n return serialized === undefined ? null : JSON.parse(serialized);\n}\n\n/** A parked, unanswered client-tool input request. */\nexport function isPendingClientToolRequest(\n request: StatewireThread.InputRequestState,\n): request is StatewireThread.CustomInputRequest {\n if (request.type !== 'interrupt' || 'response' in request) return false;\n return isClientToolInterrupt((request as { payload?: unknown }).payload);\n}\n\nexport interface ExecuteClientToolBatchOptions {\n calls: readonly ClientToolCallRequest[];\n tools: readonly ClientToolBridgeTool[];\n /** Whether the parked request still exists and this surface may answer it.\n * Checked before consent resolution, before every call, and before the\n * results are handed back for resume. */\n isLive: () => boolean;\n /** Batch write gate; absent means writes run without consent (surfaces that\n * only register read tools). Called once per batch, before any handler. */\n confirmWrites?: (batch: {\n writeToolNames: readonly string[];\n }) => Promise<ClientToolWriteConsentDecision>;\n writeDeclinedMessage?: string;\n missingToolMessage?: (toolName: string) => string;\n /** Per-call telemetry (the Office add-in's tool events). */\n onCallSettled?: (event: ClientToolCallSettledEvent) => void;\n /**\n * Called once, after the write-consent gate resolves and immediately before\n * the first handler runs — the point where side effects begin. There is no\n * await between this callback and the first handler invocation, so a caller\n * marking \"execution started\" here can never miss a handler that ran.\n */\n onExecutionStart?: () => void;\n /**\n * Handed to every handler of the batch (`context.signal`). The caller aborts\n * it when the parked request goes away mid-execution, so a handler that\n * takes visible time can stop; the batch's results are discarded either way\n * (`isLive` is what decides that).\n */\n signal?: AbortSignal;\n}\n\n/**\n * Execute one batched client-tool park: consent, per-call execution with\n * wire-safe envelopes, liveness aborts. Returns the per-interrupt result map\n * to resume with, or `null` when the batch was abandoned (the request died,\n * consent was abandoned, or the surface went away) — the caller must release\n * its claim and must NOT resume.\n */\nexport async function executeClientToolBatch(\n options: ExecuteClientToolBatchOptions,\n): Promise<Record<string, ClientToolResultEnvelope> | null> {\n const {\n calls,\n tools,\n isLive,\n confirmWrites,\n writeDeclinedMessage = CLIENT_TOOL_WRITE_DECLINED_MESSAGE,\n missingToolMessage = defaultMissingClientToolMessage,\n onCallSettled,\n onExecutionStart,\n signal,\n } = options;\n const registry = new Map(tools.map((tool) => [tool.name, tool]));\n\n // One consent covers the whole batch (and whatever scope the surface's\n // callback persists): writes are declined together while reads still run.\n let writesDeclined = false;\n const writeToolNames = calls\n .filter((call) => registry.get(call.tool_name)?.requiresWrite === true)\n .map((call) => call.tool_name);\n if (writeToolNames.length > 0 && confirmWrites) {\n const decision = await confirmWrites({ writeToolNames });\n if (decision === 'abandoned' || !isLive()) {\n // The run was stopped (or answered elsewhere) while consent was\n // pending: abort before any handler mutates the user's asset.\n return null;\n }\n writesDeclined = decision === 'declined';\n }\n\n onExecutionStart?.();\n\n const results: Record<string, ClientToolResultEnvelope> = {};\n for (const call of calls) {\n if (!isLive()) return null;\n const tool = registry.get(call.tool_name);\n let envelope: ClientToolResultEnvelope;\n let status: ClientToolCallSettledEvent['status'] = 'success';\n let errorType: string | undefined;\n if (!tool) {\n envelope = clientToolErrorEnvelope(missingToolMessage(call.tool_name));\n status = 'error';\n errorType = 'UnknownClientTool';\n } else if (tool.requiresWrite === true && writesDeclined) {\n envelope = clientToolErrorEnvelope(writeDeclinedMessage);\n status = 'declined';\n } else {\n try {\n envelope = clientToolSuccessEnvelope(\n jsonSafeClientToolResult(\n await tool.run(clientToolCallArgs(call), {\n toolCallId: call.interrupt_id,\n ...(signal ? { signal } : {}),\n }),\n ),\n );\n } catch (error) {\n envelope = clientToolErrorEnvelope(error);\n status = 'error';\n errorType = error instanceof Error ? error.name : typeof error;\n }\n }\n results[call.interrupt_id] = envelope;\n onCallSettled?.({\n toolName: call.tool_name,\n status,\n ...(errorType !== undefined ? { errorType } : {}),\n });\n }\n\n // Abandoned mid-flight: resuming a dead request would error, and a\n // re-emitted one must be executable again.\n return isLive() ? results : null;\n}\n\nexport interface UseStatewireClientToolBridgeOptions {\n threadId: string;\n tools: readonly ClientToolBridgeTool[];\n /**\n * Ownership domain for parked-request claims. Pass a module-scoped tracker\n * to make ownership process-wide across every mount of the surface (two\n * mounted surfaces of one conversation execute each request exactly once),\n * or a per-mount tracker to scope ownership to one mounted bridge.\n */\n tracker: ClientToolRequestTracker;\n /** The surface's `useStatewireRuns().inputRequests` read. */\n inputRequests: readonly StatewireThread.InputRequestState[] | undefined;\n /** Dispatch the `run/input` resume on the surface's transport. The value is\n * already wire-safe (per-call JSON round-trip inside the batch engine). */\n /** Dispatch the answer and settle only once the Statewire host accepts or\n * rejects the command. The bridge deliberately keeps replaying while this\n * promise is pending: `run/input` removes the request optimistically before\n * the server has accepted the answer. */\n sendResume: (\n requestId: string,\n value: Record<string, unknown>,\n ) => PromiseLike<unknown>;\n /** Batch write gate, with the parked request's id so the surface can close\n * its consent UI the instant that request disappears. */\n confirmWrites?: (batch: {\n requestId: string;\n writeToolNames: readonly string[];\n }) => Promise<ClientToolWriteConsentDecision>;\n writeDeclinedMessage?: string;\n missingToolMessage?: (toolName: string) => string;\n onCallSettled?: (event: ClientToolCallSettledEvent) => void;\n /** Log prefix for resume-dispatch failures. */\n logLabel?: string;\n}\n\n/**\n * The claim lifecycle around {@link executeClientToolBatch}: claim the pending\n * request once per ownership domain, execute, resume — releasing the claim on\n * every path that ran no handler, so re-emitted requests recover.\n *\n * Unmount splits by whether side effects began:\n * - a claim whose batch has NOT started executing (claimed this tick, or\n * parked on write consent) is released, so another mount — or a remount —\n * can execute the re-emitted request instead of stranding the parked run;\n * - a claim whose batch HAS started stays held: handlers cannot be cancelled,\n * so releasing would let a sibling mount re-claim and re-execute a mutation\n * whose side effects already ran. The detached execution caches its result\n * and attempts one resume through its captured transport; a later mount can\n * replay the same result without repeating the side effect.\n */\nexport function useStatewireClientToolBridge(\n options: UseStatewireClientToolBridgeOptions,\n): void {\n const { threadId, tracker, inputRequests, logLabel = '[AthenaSDK]' } = options;\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const toolNames = new Set(options.tools.map((tool) => tool.name));\n const pendingRequest = inputRequests?.find((request) => {\n if (!isPendingClientToolRequest(request)) return false;\n const payload = (request as StatewireThread.CustomInputRequest).payload;\n if (!isClientToolInterrupt(payload)) return false;\n // Every attached tab sees the same park. An observer without these tools\n // must not claim it and race the executing surface with an unknown-tool\n // error (for example, Olympus watching an Excel conversation).\n // A cached result already belongs to this tracker and can be replayed\n // without loading its handlers again.\n return (\n tracker.getCachedResume(clientToolClaimKey(threadId, request.id)) !== undefined ||\n payload.context.requests.every((call) => toolNames.has(call.tool_name))\n );\n });\n\n // Claims this bridge holds but has not resumed, split by whether their\n // batch has begun running handlers. The ref Set instances are stable (only\n // their contents mutate), so the unmount cleanup sees every claim.\n const ownedClaimsRef = useRef<Set<string>>(new Set());\n const startedClaimsRef = useRef<Set<string>>(new Set());\n const resumeOwnerRef = useRef(Symbol('client-tool-resume-owner'));\n const resumeClaimsRef = useRef<Set<string>>(new Set());\n const resumeTimersRef = useRef<\n Map<string, { requestId: string; timer: ReturnType<typeof setTimeout> }>\n >(new Map());\n const activeRef = useRef(true);\n const releaseClaim = useCallback(\n (claim: string) => {\n // Release the shared tracker entry only while THIS mount still owns it.\n // A detached batch can settle after the unmount cleanup already released\n // (and disowned) its claim; by then the tracker entry may belong to\n // another mount that claimed, executed, and resumed — releasing it here\n // would let a stale re-emission of the same request execute again.\n const owned = ownedClaimsRef.current.delete(claim);\n startedClaimsRef.current.delete(claim);\n if (owned) tracker.release(claim);\n },\n [tracker],\n );\n const stopResumeReplay = useCallback(\n (claim: string) => {\n const timerEntry = resumeTimersRef.current.get(claim);\n if (timerEntry) clearTimeout(timerEntry.timer);\n resumeTimersRef.current.delete(claim);\n if (resumeClaimsRef.current.delete(claim)) {\n tracker.releaseResumeReplay(claim, resumeOwnerRef.current);\n }\n },\n [tracker],\n );\n useEffect(() => {\n activeRef.current = true;\n const ownedClaims = ownedClaimsRef.current;\n const startedClaims = startedClaimsRef.current;\n return () => {\n activeRef.current = false;\n for (const claim of Array.from(resumeClaimsRef.current)) {\n stopResumeReplay(claim);\n }\n for (const claim of ownedClaims) {\n // Started batches keep their claim — their detached execution settles\n // it (resume, or release on a failed dispatch). Releasing here would\n // double-execute the side effects that already ran.\n if (startedClaims.has(claim)) continue;\n ownedClaims.delete(claim);\n tracker.release(claim);\n }\n };\n }, [stopResumeReplay, tracker]);\n\n // Handlers (and consent) are async, so the run can be stopped or the request\n // answered elsewhere while we await. The live ids let us abandon an\n // unfinished local execution when its request is no longer present. Once a\n // result is cached, only command settlement may stop its replay: Statewire\n // removes submitted requests optimistically before the host accepts them.\n const liveRequestIdsRef = useRef<ReadonlySet<string>>(new Set());\n liveRequestIdsRef.current = new Set((inputRequests ?? []).map((request) => request.id));\n\n // One abort signal per executing request, handed to its handlers. It fires\n // when the request leaves the mounted surface's view (stop, an answer from\n // elsewhere, another conversation opened): the results would be discarded,\n // so a handler that is still showing the person something can stop. It does\n // not fire on unmount: a started batch finishes and settles (see above).\n const abortControllersRef = useRef<Map<string, AbortController>>(new Map());\n useEffect(() => {\n const liveRequestIds = new Set((inputRequests ?? []).map((request) => request.id));\n for (const [requestId, controller] of abortControllersRef.current) {\n if (liveRequestIds.has(requestId)) continue;\n abortControllersRef.current.delete(requestId);\n controller.abort();\n }\n }, [inputRequests]);\n\n const startResumeReplay = useCallback(\n (claim: string, requestId: string) => {\n if (!activeRef.current || resumeClaimsRef.current.has(claim)) return;\n if (!tracker.claimResumeReplay(claim, resumeOwnerRef.current)) return;\n resumeClaimsRef.current.add(claim);\n\n const dispatch = (): void => {\n resumeTimersRef.current.delete(claim);\n if (!activeRef.current) {\n stopResumeReplay(claim);\n return;\n }\n const attempt = tracker.takeResumeAttempt(claim, {\n owner: resumeOwnerRef.current,\n maxAttempts: MAX_CLIENT_TOOL_RESUME_ATTEMPTS,\n });\n if (!attempt) {\n stopResumeReplay(claim);\n return;\n }\n\n try {\n const settled = optionsRef.current.sendResume(requestId, attempt.value);\n // A fulfilled command result is the authoritative acknowledgement:\n // the host accepted and applied the answer. The local input request\n // disappearing is NOT an acknowledgement because the Statewire\n // reducer does that optimistically as soon as the command is\n // submitted.\n void Promise.resolve(settled).then(\n () => {\n // Keep the execution claim, but discard the cached result once\n // the host accepts it. A stale pending-request render can no\n // longer replay the command or re-execute the local mutation.\n tracker.settleResume(claim);\n stopResumeReplay(claim);\n },\n (error) => {\n // A rejected attempt may have raced another still-pending\n // replay. Keep the bounded loop alive; any accepted sibling\n // stops it, while the global attempt cap prevents storms.\n console.error(`${logLabel} failed to resume client tool results:`, error);\n },\n );\n } catch (error) {\n // Keep the cached result and retry it. Re-executing a mutating local\n // handler would be unsafe; replaying its id-stamped result is safe.\n console.error(`${logLabel} failed to resume client tool results:`, error);\n }\n\n if (\n attempt.attemptNumber >= MAX_CLIENT_TOOL_RESUME_ATTEMPTS ||\n !activeRef.current ||\n !resumeClaimsRef.current.has(claim)\n ) {\n stopResumeReplay(claim);\n return;\n }\n const timer = setTimeout(dispatch, clientToolResumeRetryDelayMs(attempt.attemptNumber));\n resumeTimersRef.current.set(claim, { requestId, timer });\n };\n\n dispatch();\n },\n [logLabel, stopResumeReplay, tracker],\n );\n\n const executeRequest = useCallback(\n async (request: StatewireThread.CustomInputRequest) => {\n const payload = request.payload;\n if (!isClientToolInterrupt(payload)) return;\n const claim = clientToolClaimKey(threadId, request.id);\n const {\n tools,\n confirmWrites,\n writeDeclinedMessage,\n missingToolMessage,\n onCallSettled,\n sendResume,\n } = optionsRef.current;\n\n const abortController = new AbortController();\n abortControllersRef.current.set(request.id, abortController);\n const results = await executeClientToolBatch({\n calls: payload.context.requests,\n tools,\n signal: abortController.signal,\n // Live while the request still exists AND this surface may answer it:\n // mounted, or already past the point of no return (handlers started —\n // the detached execution must finish and settle, never re-execute).\n // After unmount the request-id snapshot freezes at its last observed\n // state, which keeps a started batch's own request visible to it.\n isLive: () =>\n liveRequestIdsRef.current.has(request.id) &&\n (activeRef.current || startedClaimsRef.current.has(claim)),\n onExecutionStart: () => {\n startedClaimsRef.current.add(claim);\n },\n ...(confirmWrites\n ? {\n confirmWrites: ({ writeToolNames }: { writeToolNames: readonly string[] }) =>\n confirmWrites({ requestId: request.id, writeToolNames }),\n }\n : {}),\n ...(writeDeclinedMessage !== undefined ? { writeDeclinedMessage } : {}),\n ...(missingToolMessage ? { missingToolMessage } : {}),\n ...(onCallSettled ? { onCallSettled } : {}),\n }).finally(() => {\n if (abortControllersRef.current.get(request.id) === abortController) {\n abortControllersRef.current.delete(request.id);\n }\n });\n if (results === null) {\n releaseClaim(claim);\n return;\n }\n\n const resumeValue = clientToolResultsResumeValue(results);\n tracker.cacheResume(claim, resumeValue);\n // Execution is complete, but the exactly-once claim remains. A pending\n // re-emission must replay this cached value, never run the handlers again.\n ownedClaimsRef.current.delete(claim);\n startedClaimsRef.current.delete(claim);\n\n if (!activeRef.current) {\n // The handler crossed an unmount. Preserve the pre-existing best-effort\n // settle through its captured transport, but leave the cached result\n // available for a later mount if this dispatch is lost.\n if (tracker.claimResumeReplay(claim, resumeOwnerRef.current)) {\n const attempt = tracker.takeResumeAttempt(claim, {\n owner: resumeOwnerRef.current,\n maxAttempts: MAX_CLIENT_TOOL_RESUME_ATTEMPTS,\n });\n if (attempt) {\n try {\n void Promise.resolve(sendResume(request.id, attempt.value)).then(\n () => tracker.settleResume(claim),\n (error) => {\n console.error(`${logLabel} failed to resume client tool results:`, error);\n },\n );\n } catch (error) {\n console.error(`${logLabel} failed to resume client tool results:`, error);\n }\n }\n // Ownership only fences this best-effort dispatch; a future mount\n // may claim and replay the cached value if it did not settle.\n tracker.releaseResumeReplay(claim, resumeOwnerRef.current);\n }\n return;\n }\n\n startResumeReplay(claim, request.id);\n },\n [logLabel, releaseClaim, startResumeReplay, threadId, tracker],\n );\n\n useEffect(() => {\n if (!pendingRequest) return;\n const claim = clientToolClaimKey(threadId, pendingRequest.id);\n if (!tracker.claim(claim)) {\n // The local handler already ran. This is the reconnect/remount path:\n // replay its cached answer instead of double-executing the side effect.\n if (tracker.getCachedResume(claim)) {\n startResumeReplay(claim, pendingRequest.id);\n }\n return;\n }\n ownedClaimsRef.current.add(claim);\n void executeRequest(pendingRequest);\n }, [executeRequest, pendingRequest, startResumeReplay, threadId, tracker]);\n}\n"],"names":[],"mappings":";;AA2EO,MAAM,qCACX;AAGK,SAAS,gCAAgC,UAA0B;AACxE,SAAO,mCAAmC,QAAQ;AACpD;AAIO,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AAU,MAAM;AACd,QAAI,CAAC,eAAgB;AACrB,UAAM,QAAQ,mBAAmB,UAAU,eAAe,EAAE;AAC5D,QAAI,CAAC,QAAQ,MAAM,KAAK,GAAG;AAGzB,UAAI,QAAQ,gBAAgB,KAAK,GAAG;AAClC,0BAAkB,OAAO,eAAe,EAAE;AAAA,MAC5C;AACA;AAAA,IACF;AACA,mBAAe,QAAQ,IAAI,KAAK;AAChC,SAAK,eAAe,cAAc;AAAA,EACpC,GAAG,CAAC,gBAAgB,gBAAgB,mBAAmB,UAAU,OAAO,CAAC;AAC3E;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-tools.cjs","sources":["../../../../agent-runtime/src/client-tools.ts"],"sourcesContent":["/**\n * Client-executed tools for statewire deep-agent threads.\n *\n * A client (the Office add-in, the Chrome extension, …) declares tools it can\n * execute locally by sending their JSON-schema definitions through\n * `runConfig.custom.client_tools`. The deep-agent runtime binds them as\n * interrupt-backed tools: when the model calls one, the run parks on a\n * LangGraph interrupt whose payload carries the tool name and arguments, the\n * statewire host publishes it as an `interrupt` input request, and the client\n * executes the tool and resumes the run with the result envelope.\n *\n * This module is transport-agnostic: it holds the wire contract (definitions,\n * interrupt payload shape, result envelopes) and a duplicate-execution guard.\n * The React hook that watches input requests lives with each client, next to\n * its host-specific tool handlers.\n */\n\nimport {\n CLIENT_TOOL_INTERRUPT_SOURCE,\n CLIENT_TOOL_RESULT_STATUS_ERROR,\n CLIENT_TOOL_RESULT_STATUS_SUCCESS,\n} from './generated/runconfig-contract';\n\n/** `source`/`type` stamped on the interrupt payload by the agora runtime. */\nexport { CLIENT_TOOL_INTERRUPT_SOURCE } from './generated/runconfig-contract';\n\n/** JSON-schema description of one client-executed tool. */\nexport interface ClientToolDefinition {\n /** Snake_case tool id the model calls (e.g. `update_sheet_range`). */\n name: string;\n description: string;\n /** JSON schema for the tool arguments (`{\"type\": \"object\", ...}`). */\n parameters: Record<string, unknown>;\n /** Mutating tools gate on the client's write-approval flow before running. */\n requiresWrite: boolean;\n}\n\n/** Per-call context the client-tool bridge hands a handler; absent when a host\n * invokes a handler outside a parked run. */\nexport interface ClientToolHandlerContext {\n /** The model's tool-call id, for handlers that correlate calls. */\n toolCallId: string;\n}\n\nexport type ClientToolHandler = (\n args: Record<string, unknown>,\n context?: ClientToolHandlerContext,\n) => Promise<unknown>;\n\nexport interface RegisteredClientTool {\n definition: ClientToolDefinition;\n handler: ClientToolHandler;\n}\n\n/** One parked tool call inside a batched client-tool input request. */\nexport interface ClientToolCallRequest {\n /** LangGraph interrupt id — the key the resume result map must use. */\n interrupt_id: string;\n tool_name: string;\n tool_args: Record<string, unknown>;\n requires_write?: boolean;\n}\n\n/**\n * The input-request payload the agora runtime publishes for parked client\n * tool calls. A parallel model turn parks several interrupts at once; the\n * runtime batches them into one payload and the client answers once with\n * `{ client_tool_results: { <interrupt_id>: <result envelope> } }`.\n */\nexport interface ClientToolInterruptPayload {\n source: typeof CLIENT_TOOL_INTERRUPT_SOURCE;\n type: typeof CLIENT_TOOL_INTERRUPT_SOURCE;\n message: string;\n context: {\n requests: ClientToolCallRequest[];\n };\n}\n\nfunction isClientToolCallRequest(value: unknown): value is ClientToolCallRequest {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const candidate = value as Partial<ClientToolCallRequest>;\n return (\n typeof candidate.interrupt_id === 'string' &&\n candidate.interrupt_id.length > 0 &&\n typeof candidate.tool_name === 'string'\n );\n}\n\n/**\n * Loose source check for surfaces that must NOT handle a client-tool park\n * (e.g. the generic approval banner). Unlike `isClientToolInterrupt`, this\n * matches any payload stamped with the client-tool source — including shapes\n * from a mismatched client/server version — so a skewed deploy can never\n * surface a generic \"Continue\" resume that corrupts a parked tool call.\n */\nexport function hasClientToolInterruptSource(payload: unknown): boolean {\n return (\n !!payload &&\n typeof payload === 'object' &&\n !Array.isArray(payload) &&\n (payload as { source?: unknown }).source === CLIENT_TOOL_INTERRUPT_SOURCE\n );\n}\n\nexport function isClientToolInterrupt(\n payload: unknown,\n): payload is ClientToolInterruptPayload {\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {\n return false;\n }\n const candidate = payload as Partial<ClientToolInterruptPayload>;\n return (\n candidate.source === CLIENT_TOOL_INTERRUPT_SOURCE &&\n candidate.type === CLIENT_TOOL_INTERRUPT_SOURCE &&\n typeof candidate.context === 'object' &&\n candidate.context !== null &&\n Array.isArray(candidate.context.requests) &&\n candidate.context.requests.length > 0 &&\n candidate.context.requests.every(isClientToolCallRequest)\n );\n}\n\n/** Tool arguments from a call request, defaulting to an empty object. */\nexport function clientToolCallArgs(\n request: ClientToolCallRequest,\n): Record<string, unknown> {\n const args = request.tool_args;\n return args && typeof args === 'object' && !Array.isArray(args) ? args : {};\n}\n\n/** The `run/input` resume value answering a batched client-tool park. */\nexport function clientToolResultsResumeValue(\n results: Record<string, ClientToolResultEnvelope>,\n): Record<string, unknown> {\n return { client_tool_results: results };\n}\n\n/** Wire entries for `runConfig.custom.client_tools`. */\nexport function clientToolRunConfigEntries(\n tools: readonly RegisteredClientTool[],\n): Record<string, unknown>[] {\n return tools.map(({ definition }) => ({\n name: definition.name,\n description: definition.description,\n parameters: definition.parameters,\n requires_write: definition.requiresWrite,\n }));\n}\n\n/** Successful tool execution, resumed back into the parked run. */\nexport interface ClientToolSuccessEnvelope {\n status: typeof CLIENT_TOOL_RESULT_STATUS_SUCCESS;\n result: unknown;\n}\n\n/** Failed or declined tool execution, resumed back into the parked run. */\nexport interface ClientToolErrorEnvelope {\n status: typeof CLIENT_TOOL_RESULT_STATUS_ERROR;\n error: string;\n}\n\nexport type ClientToolResultEnvelope =\n | ClientToolSuccessEnvelope\n | ClientToolErrorEnvelope;\n\nexport function clientToolSuccessEnvelope(\n result: unknown,\n): ClientToolSuccessEnvelope {\n return {\n status: CLIENT_TOOL_RESULT_STATUS_SUCCESS,\n result: result === undefined ? null : result,\n };\n}\n\nexport function clientToolErrorEnvelope(error: unknown): ClientToolErrorEnvelope {\n const message =\n error instanceof Error\n ? error.message\n : typeof error === 'string'\n ? error\n : 'Client tool execution failed.';\n return { status: CLIENT_TOOL_RESULT_STATUS_ERROR, error: message };\n}\n\n/**\n * Once-per-request execution guard. Statewire re-emits the pending input\n * request on every state update, so an executor effect can observe the same\n * request many times; the tracker makes exactly one observation win.\n */\nexport interface ClientToolRequestTracker {\n /** True exactly once per request id; later calls return false. */\n claim(requestId: string): boolean;\n /** Un-claim a request that was NOT resumed (e.g. abandoned mid-approval),\n * so a re-emitted request can be executed instead of stranding the run. */\n release(requestId: string): void;\n has(requestId: string): boolean;\n /** Cache the completed, wire-safe resume value without releasing the\n * exactly-once execution claim. A reconnect may replay this value, but it\n * must never execute the local handler again. */\n cacheResume(requestId: string, value: Record<string, unknown>): void;\n getCachedResume(requestId: string): ClientToolCachedResume | undefined;\n /** Give one mounted bridge ownership of retrying a cached resume. */\n claimResumeReplay(requestId: string, owner: symbol): boolean;\n releaseResumeReplay(requestId: string, owner: symbol): void;\n /** Record authoritative host acceptance. The execution claim remains held\n * so a briefly stale request cannot execute its local side effects again. */\n settleResume(requestId: string): void;\n /** Atomically consume one bounded replay attempt for the current owner. */\n takeResumeAttempt(\n requestId: string,\n options: { owner: symbol; maxAttempts: number },\n ): ClientToolResumeAttempt | undefined;\n}\n\nexport interface ClientToolCachedResume {\n value: Record<string, unknown>;\n attemptCount: number;\n}\n\nexport interface ClientToolResumeAttempt {\n value: Record<string, unknown>;\n attemptNumber: number;\n}\n\nexport interface CreateClientToolRequestTrackerOptions {\n /** Maximum completed resume values retained for reconnect recovery. Active\n * executions are never evicted. */\n maxCachedResumes?: number;\n}\n\ninterface ClientToolRequestEntry {\n resumeValue?: Record<string, unknown>;\n resumeAttemptCount: number;\n resumeOwner?: symbol;\n settled?: boolean;\n}\n\nconst DEFAULT_MAX_CACHED_CLIENT_TOOL_RESUMES = 128;\n\nexport function createClientToolRequestTracker(\n options: CreateClientToolRequestTrackerOptions = {},\n): ClientToolRequestTracker {\n const maxCachedResumes = options.maxCachedResumes ?? DEFAULT_MAX_CACHED_CLIENT_TOOL_RESUMES;\n const requests = new Map<string, ClientToolRequestEntry>();\n\n const pruneCompletedRequests = (protectedRequestId?: string): void => {\n let completedCount = 0;\n for (const entry of requests.values()) {\n if (entry.resumeValue !== undefined || entry.settled === true) completedCount += 1;\n }\n if (completedCount <= maxCachedResumes) return;\n\n // Map iteration is insertion order. Only inactive, completed entries are\n // eligible: evicting an executing request could allow a document mutation\n // to run twice, evicting an active replay would split ownership, and the\n // newly completed request must survive long enough for its first dispatch.\n for (const [requestId, entry] of requests) {\n if (completedCount <= maxCachedResumes) break;\n if (\n requestId === protectedRequestId ||\n (entry.resumeValue === undefined && entry.settled !== true) ||\n entry.resumeOwner !== undefined\n ) {\n continue;\n }\n requests.delete(requestId);\n completedCount -= 1;\n }\n };\n\n return {\n claim(requestId: string): boolean {\n if (requests.has(requestId)) return false;\n requests.set(requestId, { resumeAttemptCount: 0 });\n return true;\n },\n release(requestId: string): void {\n requests.delete(requestId);\n },\n has(requestId: string): boolean {\n return requests.has(requestId);\n },\n cacheResume(requestId: string, value: Record<string, unknown>): void {\n const entry = requests.get(requestId) ?? { resumeAttemptCount: 0 };\n entry.resumeValue = value;\n entry.settled = false;\n requests.delete(requestId);\n requests.set(requestId, entry);\n pruneCompletedRequests(requestId);\n },\n getCachedResume(requestId: string): ClientToolCachedResume | undefined {\n const entry = requests.get(requestId);\n if (!entry || entry.resumeValue === undefined) return undefined;\n return {\n value: entry.resumeValue,\n attemptCount: entry.resumeAttemptCount,\n };\n },\n claimResumeReplay(requestId: string, owner: symbol): boolean {\n const entry = requests.get(requestId);\n if (!entry || entry.resumeValue === undefined) return false;\n if (entry.resumeOwner !== undefined && entry.resumeOwner !== owner) {\n return false;\n }\n entry.resumeOwner = owner;\n return true;\n },\n releaseResumeReplay(requestId: string, owner: symbol): void {\n const entry = requests.get(requestId);\n if (entry?.resumeOwner === owner) entry.resumeOwner = undefined;\n pruneCompletedRequests();\n },\n settleResume(requestId: string): void {\n const entry = requests.get(requestId);\n if (!entry) return;\n entry.resumeValue = undefined;\n entry.resumeOwner = undefined;\n entry.settled = true;\n requests.delete(requestId);\n requests.set(requestId, entry);\n pruneCompletedRequests(requestId);\n },\n takeResumeAttempt(\n requestId: string,\n attemptOptions: { owner: symbol; maxAttempts: number },\n ): ClientToolResumeAttempt | undefined {\n const entry = requests.get(requestId);\n if (\n !entry ||\n entry.resumeValue === undefined ||\n entry.resumeOwner !== attemptOptions.owner ||\n entry.resumeAttemptCount >= attemptOptions.maxAttempts\n ) {\n return undefined;\n }\n entry.resumeAttemptCount += 1;\n return {\n value: entry.resumeValue,\n attemptNumber: entry.resumeAttemptCount,\n };\n },\n };\n}\n"],"names":["CLIENT_TOOL_INTERRUPT_SOURCE","CLIENT_TOOL_RESULT_STATUS_SUCCESS","CLIENT_TOOL_RESULT_STATUS_ERROR"],"mappings":";;;AA8EA,SAAS,wBAAwB,OAAgD;AAC/E,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,EAAG,QAAO;AACxE,QAAM,YAAY;AAClB,SACE,OAAO,UAAU,iBAAiB,YAClC,UAAU,aAAa,SAAS,KAChC,OAAO,UAAU,cAAc;AAEnC;AASO,SAAS,6BAA6B,SAA2B;AACtE,SACE,CAAC,CAAC,WACF,OAAO,YAAY,YACnB,CAAC,MAAM,QAAQ,OAAO,KACrB,QAAiC,WAAWA,kBAAAA;AAEjD;AAEO,SAAS,sBACd,SACuC;AACvC,MAAI,CAAC,WAAW,OAAO,YAAY,YAAY,MAAM,QAAQ,OAAO,GAAG;AACrE,WAAO;AAAA,EACT;AACA,QAAM,YAAY;AAClB,SACE,UAAU,WAAWA,kBAAAA,gCACrB,UAAU,SAASA,kBAAAA,gCACnB,OAAO,UAAU,YAAY,YAC7B,UAAU,YAAY,QACtB,MAAM,QAAQ,UAAU,QAAQ,QAAQ,KACxC,UAAU,QAAQ,SAAS,SAAS,KACpC,UAAU,QAAQ,SAAS,MAA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,WAAW,KAAK;AAC7B,6BAAuB,SAAS;AAAA,IAClC;AAAA,IACA,kBACE,WACA,gBACqC;AACrC,YAAM,QAAQ,SAAS,IAAI,SAAS;AACpC,UACE,CAAC,SACD,MAAM,gBAAgB,UACtB,MAAM,gBAAgB,eAAe,SACrC,MAAM,sBAAsB,eAAe,aAC3C;AACA,eAAO;AAAA,MACT;AACA,YAAM,sBAAsB;AAC5B,aAAO;AAAA,QACL,OAAO,MAAM;AAAA,QACb,eAAe,MAAM;AAAA,MAAA;AAAA,IAEzB;AAAA,EAAA;AAEJ;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"client-tools.cjs","sources":["../../../../agent-runtime/src/client-tools.ts"],"sourcesContent":["/**\n * Client-executed tools for statewire deep-agent threads.\n *\n * A client (the Office add-in, the Chrome extension, …) declares tools it can\n * execute locally by sending their JSON-schema definitions through\n * `runConfig.custom.client_tools`. The deep-agent runtime binds them as\n * interrupt-backed tools: when the model calls one, the run parks on a\n * LangGraph interrupt whose payload carries the tool name and arguments, the\n * statewire host publishes it as an `interrupt` input request, and the client\n * executes the tool and resumes the run with the result envelope.\n *\n * This module is transport-agnostic: it holds the wire contract (definitions,\n * interrupt payload shape, result envelopes) and a duplicate-execution guard.\n * The React hook that watches input requests lives with each client, next to\n * its host-specific tool handlers.\n */\n\nimport {\n CLIENT_TOOL_INTERRUPT_SOURCE,\n CLIENT_TOOL_RESULT_STATUS_ERROR,\n CLIENT_TOOL_RESULT_STATUS_SUCCESS,\n} from './generated/runconfig-contract';\n\n/** `source`/`type` stamped on the interrupt payload by the agora runtime. */\nexport { CLIENT_TOOL_INTERRUPT_SOURCE } from './generated/runconfig-contract';\n\n/** JSON-schema description of one client-executed tool. */\nexport interface ClientToolDefinition {\n /** Snake_case tool id the model calls (e.g. `update_sheet_range`). */\n name: string;\n description: string;\n /** JSON schema for the tool arguments (`{\"type\": \"object\", ...}`). */\n parameters: Record<string, unknown>;\n /** Mutating tools gate on the client's write-approval flow before running. */\n requiresWrite: boolean;\n}\n\n/** Per-call context the client-tool bridge hands a handler; absent when a host\n * invokes a handler outside a parked run. */\nexport interface ClientToolHandlerContext {\n /** The model's tool-call id, for handlers that correlate calls. */\n toolCallId: string;\n /**\n * Aborts when the parked call's request goes away before the handler\n * finished: the run was stopped, the call was answered elsewhere, or the\n * person opened another conversation. Whatever the handler returns after\n * that is discarded, so a handler that takes visible time (a paced\n * walkthrough, typing shown to the person) should stop on it. Absent when a\n * host invokes the handler outside the bridge.\n */\n signal?: AbortSignal;\n}\n\nexport type ClientToolHandler = (\n args: Record<string, unknown>,\n context?: ClientToolHandlerContext,\n) => Promise<unknown>;\n\nexport interface RegisteredClientTool {\n definition: ClientToolDefinition;\n handler: ClientToolHandler;\n}\n\n/** One parked tool call inside a batched client-tool input request. */\nexport interface ClientToolCallRequest {\n /** LangGraph interrupt id — the key the resume result map must use. */\n interrupt_id: string;\n tool_name: string;\n tool_args: Record<string, unknown>;\n requires_write?: boolean;\n}\n\n/**\n * The input-request payload the agora runtime publishes for parked client\n * tool calls. A parallel model turn parks several interrupts at once; the\n * runtime batches them into one payload and the client answers once with\n * `{ client_tool_results: { <interrupt_id>: <result envelope> } }`.\n */\nexport interface ClientToolInterruptPayload {\n source: typeof CLIENT_TOOL_INTERRUPT_SOURCE;\n type: typeof CLIENT_TOOL_INTERRUPT_SOURCE;\n message: string;\n context: {\n requests: ClientToolCallRequest[];\n };\n}\n\nfunction isClientToolCallRequest(value: unknown): value is ClientToolCallRequest {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const candidate = value as Partial<ClientToolCallRequest>;\n return (\n typeof candidate.interrupt_id === 'string' &&\n candidate.interrupt_id.length > 0 &&\n typeof candidate.tool_name === 'string'\n );\n}\n\n/**\n * Loose source check for surfaces that must NOT handle a client-tool park\n * (e.g. the generic approval banner). Unlike `isClientToolInterrupt`, this\n * matches any payload stamped with the client-tool source — including shapes\n * from a mismatched client/server version — so a skewed deploy can never\n * surface a generic \"Continue\" resume that corrupts a parked tool call.\n */\nexport function hasClientToolInterruptSource(payload: unknown): boolean {\n return (\n !!payload &&\n typeof payload === 'object' &&\n !Array.isArray(payload) &&\n (payload as { source?: unknown }).source === CLIENT_TOOL_INTERRUPT_SOURCE\n );\n}\n\nexport function isClientToolInterrupt(\n payload: unknown,\n): payload is ClientToolInterruptPayload {\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {\n return false;\n }\n const candidate = payload as Partial<ClientToolInterruptPayload>;\n return (\n candidate.source === CLIENT_TOOL_INTERRUPT_SOURCE &&\n candidate.type === CLIENT_TOOL_INTERRUPT_SOURCE &&\n typeof candidate.context === 'object' &&\n candidate.context !== null &&\n Array.isArray(candidate.context.requests) &&\n candidate.context.requests.length > 0 &&\n candidate.context.requests.every(isClientToolCallRequest)\n );\n}\n\n/** Tool arguments from a call request, defaulting to an empty object. */\nexport function clientToolCallArgs(\n request: ClientToolCallRequest,\n): Record<string, unknown> {\n const args = request.tool_args;\n return args && typeof args === 'object' && !Array.isArray(args) ? args : {};\n}\n\n/** The `run/input` resume value answering a batched client-tool park. */\nexport function clientToolResultsResumeValue(\n results: Record<string, ClientToolResultEnvelope>,\n): Record<string, unknown> {\n return { client_tool_results: results };\n}\n\n/** Wire entries for `runConfig.custom.client_tools`. */\nexport function clientToolRunConfigEntries(\n tools: readonly RegisteredClientTool[],\n): Record<string, unknown>[] {\n return tools.map(({ definition }) => ({\n name: definition.name,\n description: definition.description,\n parameters: definition.parameters,\n requires_write: definition.requiresWrite,\n }));\n}\n\n/** Successful tool execution, resumed back into the parked run. */\nexport interface ClientToolSuccessEnvelope {\n status: typeof CLIENT_TOOL_RESULT_STATUS_SUCCESS;\n result: unknown;\n}\n\n/** Failed or declined tool execution, resumed back into the parked run. */\nexport interface ClientToolErrorEnvelope {\n status: typeof CLIENT_TOOL_RESULT_STATUS_ERROR;\n error: string;\n}\n\nexport type ClientToolResultEnvelope =\n | ClientToolSuccessEnvelope\n | ClientToolErrorEnvelope;\n\nexport function clientToolSuccessEnvelope(\n result: unknown,\n): ClientToolSuccessEnvelope {\n return {\n status: CLIENT_TOOL_RESULT_STATUS_SUCCESS,\n result: result === undefined ? null : result,\n };\n}\n\nexport function clientToolErrorEnvelope(error: unknown): ClientToolErrorEnvelope {\n const message =\n error instanceof Error\n ? error.message\n : typeof error === 'string'\n ? error\n : 'Client tool execution failed.';\n return { status: CLIENT_TOOL_RESULT_STATUS_ERROR, error: message };\n}\n\n/**\n * Once-per-request execution guard. Statewire re-emits the pending input\n * request on every state update, so an executor effect can observe the same\n * request many times; the tracker makes exactly one observation win.\n */\nexport interface ClientToolRequestTracker {\n /** True exactly once per request id; later calls return false. */\n claim(requestId: string): boolean;\n /** Un-claim a request that was NOT resumed (e.g. abandoned mid-approval),\n * so a re-emitted request can be executed instead of stranding the run. */\n release(requestId: string): void;\n has(requestId: string): boolean;\n /** Cache the completed, wire-safe resume value without releasing the\n * exactly-once execution claim. A reconnect may replay this value, but it\n * must never execute the local handler again. */\n cacheResume(requestId: string, value: Record<string, unknown>): void;\n getCachedResume(requestId: string): ClientToolCachedResume | undefined;\n /** Give one mounted bridge ownership of retrying a cached resume. */\n claimResumeReplay(requestId: string, owner: symbol): boolean;\n releaseResumeReplay(requestId: string, owner: symbol): void;\n /** Record authoritative host acceptance. The execution claim remains held\n * so a briefly stale request cannot execute its local side effects again. */\n settleResume(requestId: string): void;\n /** Atomically consume one bounded replay attempt for the current owner. */\n takeResumeAttempt(\n requestId: string,\n options: { owner: symbol; maxAttempts: number },\n ): ClientToolResumeAttempt | undefined;\n}\n\nexport interface ClientToolCachedResume {\n value: Record<string, unknown>;\n attemptCount: number;\n}\n\nexport interface ClientToolResumeAttempt {\n value: Record<string, unknown>;\n attemptNumber: number;\n}\n\nexport interface CreateClientToolRequestTrackerOptions {\n /** Maximum completed resume values retained for reconnect recovery. Active\n * executions are never evicted. */\n maxCachedResumes?: number;\n}\n\ninterface ClientToolRequestEntry {\n resumeValue?: Record<string, unknown>;\n resumeAttemptCount: number;\n resumeOwner?: symbol;\n settled?: boolean;\n}\n\nconst DEFAULT_MAX_CACHED_CLIENT_TOOL_RESUMES = 128;\n\nexport function createClientToolRequestTracker(\n options: CreateClientToolRequestTrackerOptions = {},\n): ClientToolRequestTracker {\n const maxCachedResumes = options.maxCachedResumes ?? DEFAULT_MAX_CACHED_CLIENT_TOOL_RESUMES;\n const requests = new Map<string, ClientToolRequestEntry>();\n\n const pruneCompletedRequests = (protectedRequestId?: string): void => {\n let completedCount = 0;\n for (const entry of requests.values()) {\n if (entry.resumeValue !== undefined || entry.settled === true) completedCount += 1;\n }\n if (completedCount <= maxCachedResumes) return;\n\n // Map iteration is insertion order. Only inactive, completed entries are\n // eligible: evicting an executing request could allow a document mutation\n // to run twice, evicting an active replay would split ownership, and the\n // newly completed request must survive long enough for its first dispatch.\n for (const [requestId, entry] of requests) {\n if (completedCount <= maxCachedResumes) break;\n if (\n requestId === protectedRequestId ||\n (entry.resumeValue === undefined && entry.settled !== true) ||\n entry.resumeOwner !== undefined\n ) {\n continue;\n }\n requests.delete(requestId);\n completedCount -= 1;\n }\n };\n\n return {\n claim(requestId: string): boolean {\n if (requests.has(requestId)) return false;\n requests.set(requestId, { resumeAttemptCount: 0 });\n return true;\n },\n release(requestId: string): void {\n requests.delete(requestId);\n },\n has(requestId: string): boolean {\n return requests.has(requestId);\n },\n cacheResume(requestId: string, value: Record<string, unknown>): void {\n const entry = requests.get(requestId) ?? { resumeAttemptCount: 0 };\n entry.resumeValue = value;\n entry.settled = false;\n requests.delete(requestId);\n requests.set(requestId, entry);\n pruneCompletedRequests(requestId);\n },\n getCachedResume(requestId: string): ClientToolCachedResume | undefined {\n const entry = requests.get(requestId);\n if (!entry || entry.resumeValue === undefined) return undefined;\n return {\n value: entry.resumeValue,\n attemptCount: entry.resumeAttemptCount,\n };\n },\n claimResumeReplay(requestId: string, owner: symbol): boolean {\n const entry = requests.get(requestId);\n if (!entry || entry.resumeValue === undefined) return false;\n if (entry.resumeOwner !== undefined && entry.resumeOwner !== owner) {\n return false;\n }\n entry.resumeOwner = owner;\n return true;\n },\n releaseResumeReplay(requestId: string, owner: symbol): void {\n const entry = requests.get(requestId);\n if (entry?.resumeOwner === owner) entry.resumeOwner = undefined;\n pruneCompletedRequests();\n },\n settleResume(requestId: string): void {\n const entry = requests.get(requestId);\n if (!entry) return;\n entry.resumeValue = undefined;\n entry.resumeOwner = undefined;\n entry.settled = true;\n requests.delete(requestId);\n requests.set(requestId, entry);\n pruneCompletedRequests(requestId);\n },\n takeResumeAttempt(\n requestId: string,\n attemptOptions: { owner: symbol; maxAttempts: number },\n ): ClientToolResumeAttempt | undefined {\n const entry = requests.get(requestId);\n if (\n !entry ||\n entry.resumeValue === undefined ||\n entry.resumeOwner !== attemptOptions.owner ||\n entry.resumeAttemptCount >= attemptOptions.maxAttempts\n ) {\n return undefined;\n }\n entry.resumeAttemptCount += 1;\n return {\n value: entry.resumeValue,\n attemptNumber: entry.resumeAttemptCount,\n };\n },\n };\n}\n"],"names":["CLIENT_TOOL_INTERRUPT_SOURCE","CLIENT_TOOL_RESULT_STATUS_SUCCESS","CLIENT_TOOL_RESULT_STATUS_ERROR"],"mappings":";;;AAuFA,SAAS,wBAAwB,OAAgD;AAC/E,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,EAAG,QAAO;AACxE,QAAM,YAAY;AAClB,SACE,OAAO,UAAU,iBAAiB,YAClC,UAAU,aAAa,SAAS,KAChC,OAAO,UAAU,cAAc;AAEnC;AASO,SAAS,6BAA6B,SAA2B;AACtE,SACE,CAAC,CAAC,WACF,OAAO,YAAY,YACnB,CAAC,MAAM,QAAQ,OAAO,KACrB,QAAiC,WAAWA,kBAAAA;AAEjD;AAEO,SAAS,sBACd,SACuC;AACvC,MAAI,CAAC,WAAW,OAAO,YAAY,YAAY,MAAM,QAAQ,OAAO,GAAG;AACrE,WAAO;AAAA,EACT;AACA,QAAM,YAAY;AAClB,SACE,UAAU,WAAWA,kBAAAA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ACA,aAAa,WAAyB;AACpC,YAAM,QAAQ,SAAS,IAAI,SAAS;AACpC,UAAI,CAAC,MAAO;AACZ,YAAM,cAAc;AACpB,YAAM,cAAc;AACpB,YAAM,UAAU;AAChB,eAAS,OAAO,SAAS;AACzB,eAAS,IAAI,WAAW,KAAK;AAC7B,6BAAuB,SAAS;AAAA,IAClC;AAAA,IACA,kBACE,WACA,gBACqC;AACrC,YAAM,QAAQ,SAAS,IAAI,SAAS;AACpC,UACE,CAAC,SACD,MAAM,gBAAgB,UACtB,MAAM,gBAAgB,eAAe,SACrC,MAAM,sBAAsB,eAAe,aAC3C;AACA,eAAO;AAAA,MACT;AACA,YAAM,sBAAsB;AAC5B,aAAO;AAAA,QACL,OAAO,MAAM;AAAA,QACb,eAAe,MAAM;AAAA,MAAA;AAAA,IAEzB;AAAA,EAAA;AAEJ;;;;;;;;;;"}
|
|
@@ -32,6 +32,15 @@ export interface ClientToolDefinition {
|
|
|
32
32
|
export interface ClientToolHandlerContext {
|
|
33
33
|
/** The model's tool-call id, for handlers that correlate calls. */
|
|
34
34
|
toolCallId: string;
|
|
35
|
+
/**
|
|
36
|
+
* Aborts when the parked call's request goes away before the handler
|
|
37
|
+
* finished: the run was stopped, the call was answered elsewhere, or the
|
|
38
|
+
* person opened another conversation. Whatever the handler returns after
|
|
39
|
+
* that is discarded, so a handler that takes visible time (a paced
|
|
40
|
+
* walkthrough, typing shown to the person) should stop on it. Absent when a
|
|
41
|
+
* host invokes the handler outside the bridge.
|
|
42
|
+
*/
|
|
43
|
+
signal?: AbortSignal;
|
|
35
44
|
}
|
|
36
45
|
export type ClientToolHandler = (args: Record<string, unknown>, context?: ClientToolHandlerContext) => Promise<unknown>;
|
|
37
46
|
export interface RegisteredClientTool {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-tools.js","sources":["../../../../agent-runtime/src/client-tools.ts"],"sourcesContent":["/**\n * Client-executed tools for statewire deep-agent threads.\n *\n * A client (the Office add-in, the Chrome extension, …) declares tools it can\n * execute locally by sending their JSON-schema definitions through\n * `runConfig.custom.client_tools`. The deep-agent runtime binds them as\n * interrupt-backed tools: when the model calls one, the run parks on a\n * LangGraph interrupt whose payload carries the tool name and arguments, the\n * statewire host publishes it as an `interrupt` input request, and the client\n * executes the tool and resumes the run with the result envelope.\n *\n * This module is transport-agnostic: it holds the wire contract (definitions,\n * interrupt payload shape, result envelopes) and a duplicate-execution guard.\n * The React hook that watches input requests lives with each client, next to\n * its host-specific tool handlers.\n */\n\nimport {\n CLIENT_TOOL_INTERRUPT_SOURCE,\n CLIENT_TOOL_RESULT_STATUS_ERROR,\n CLIENT_TOOL_RESULT_STATUS_SUCCESS,\n} from './generated/runconfig-contract';\n\n/** `source`/`type` stamped on the interrupt payload by the agora runtime. */\nexport { CLIENT_TOOL_INTERRUPT_SOURCE } from './generated/runconfig-contract';\n\n/** JSON-schema description of one client-executed tool. */\nexport interface ClientToolDefinition {\n /** Snake_case tool id the model calls (e.g. `update_sheet_range`). */\n name: string;\n description: string;\n /** JSON schema for the tool arguments (`{\"type\": \"object\", ...}`). */\n parameters: Record<string, unknown>;\n /** Mutating tools gate on the client's write-approval flow before running. */\n requiresWrite: boolean;\n}\n\n/** Per-call context the client-tool bridge hands a handler; absent when a host\n * invokes a handler outside a parked run. */\nexport interface ClientToolHandlerContext {\n /** The model's tool-call id, for handlers that correlate calls. */\n toolCallId: string;\n}\n\nexport type ClientToolHandler = (\n args: Record<string, unknown>,\n context?: ClientToolHandlerContext,\n) => Promise<unknown>;\n\nexport interface RegisteredClientTool {\n definition: ClientToolDefinition;\n handler: ClientToolHandler;\n}\n\n/** One parked tool call inside a batched client-tool input request. */\nexport interface ClientToolCallRequest {\n /** LangGraph interrupt id — the key the resume result map must use. */\n interrupt_id: string;\n tool_name: string;\n tool_args: Record<string, unknown>;\n requires_write?: boolean;\n}\n\n/**\n * The input-request payload the agora runtime publishes for parked client\n * tool calls. A parallel model turn parks several interrupts at once; the\n * runtime batches them into one payload and the client answers once with\n * `{ client_tool_results: { <interrupt_id>: <result envelope> } }`.\n */\nexport interface ClientToolInterruptPayload {\n source: typeof CLIENT_TOOL_INTERRUPT_SOURCE;\n type: typeof CLIENT_TOOL_INTERRUPT_SOURCE;\n message: string;\n context: {\n requests: ClientToolCallRequest[];\n };\n}\n\nfunction isClientToolCallRequest(value: unknown): value is ClientToolCallRequest {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const candidate = value as Partial<ClientToolCallRequest>;\n return (\n typeof candidate.interrupt_id === 'string' &&\n candidate.interrupt_id.length > 0 &&\n typeof candidate.tool_name === 'string'\n );\n}\n\n/**\n * Loose source check for surfaces that must NOT handle a client-tool park\n * (e.g. the generic approval banner). Unlike `isClientToolInterrupt`, this\n * matches any payload stamped with the client-tool source — including shapes\n * from a mismatched client/server version — so a skewed deploy can never\n * surface a generic \"Continue\" resume that corrupts a parked tool call.\n */\nexport function hasClientToolInterruptSource(payload: unknown): boolean {\n return (\n !!payload &&\n typeof payload === 'object' &&\n !Array.isArray(payload) &&\n (payload as { source?: unknown }).source === CLIENT_TOOL_INTERRUPT_SOURCE\n );\n}\n\nexport function isClientToolInterrupt(\n payload: unknown,\n): payload is ClientToolInterruptPayload {\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {\n return false;\n }\n const candidate = payload as Partial<ClientToolInterruptPayload>;\n return (\n candidate.source === CLIENT_TOOL_INTERRUPT_SOURCE &&\n candidate.type === CLIENT_TOOL_INTERRUPT_SOURCE &&\n typeof candidate.context === 'object' &&\n candidate.context !== null &&\n Array.isArray(candidate.context.requests) &&\n candidate.context.requests.length > 0 &&\n candidate.context.requests.every(isClientToolCallRequest)\n );\n}\n\n/** Tool arguments from a call request, defaulting to an empty object. */\nexport function clientToolCallArgs(\n request: ClientToolCallRequest,\n): Record<string, unknown> {\n const args = request.tool_args;\n return args && typeof args === 'object' && !Array.isArray(args) ? args : {};\n}\n\n/** The `run/input` resume value answering a batched client-tool park. */\nexport function clientToolResultsResumeValue(\n results: Record<string, ClientToolResultEnvelope>,\n): Record<string, unknown> {\n return { client_tool_results: results };\n}\n\n/** Wire entries for `runConfig.custom.client_tools`. */\nexport function clientToolRunConfigEntries(\n tools: readonly RegisteredClientTool[],\n): Record<string, unknown>[] {\n return tools.map(({ definition }) => ({\n name: definition.name,\n description: definition.description,\n parameters: definition.parameters,\n requires_write: definition.requiresWrite,\n }));\n}\n\n/** Successful tool execution, resumed back into the parked run. */\nexport interface ClientToolSuccessEnvelope {\n status: typeof CLIENT_TOOL_RESULT_STATUS_SUCCESS;\n result: unknown;\n}\n\n/** Failed or declined tool execution, resumed back into the parked run. */\nexport interface ClientToolErrorEnvelope {\n status: typeof CLIENT_TOOL_RESULT_STATUS_ERROR;\n error: string;\n}\n\nexport type ClientToolResultEnvelope =\n | ClientToolSuccessEnvelope\n | ClientToolErrorEnvelope;\n\nexport function clientToolSuccessEnvelope(\n result: unknown,\n): ClientToolSuccessEnvelope {\n return {\n status: CLIENT_TOOL_RESULT_STATUS_SUCCESS,\n result: result === undefined ? null : result,\n };\n}\n\nexport function clientToolErrorEnvelope(error: unknown): ClientToolErrorEnvelope {\n const message =\n error instanceof Error\n ? error.message\n : typeof error === 'string'\n ? error\n : 'Client tool execution failed.';\n return { status: CLIENT_TOOL_RESULT_STATUS_ERROR, error: message };\n}\n\n/**\n * Once-per-request execution guard. Statewire re-emits the pending input\n * request on every state update, so an executor effect can observe the same\n * request many times; the tracker makes exactly one observation win.\n */\nexport interface ClientToolRequestTracker {\n /** True exactly once per request id; later calls return false. */\n claim(requestId: string): boolean;\n /** Un-claim a request that was NOT resumed (e.g. abandoned mid-approval),\n * so a re-emitted request can be executed instead of stranding the run. */\n release(requestId: string): void;\n has(requestId: string): boolean;\n /** Cache the completed, wire-safe resume value without releasing the\n * exactly-once execution claim. A reconnect may replay this value, but it\n * must never execute the local handler again. */\n cacheResume(requestId: string, value: Record<string, unknown>): void;\n getCachedResume(requestId: string): ClientToolCachedResume | undefined;\n /** Give one mounted bridge ownership of retrying a cached resume. */\n claimResumeReplay(requestId: string, owner: symbol): boolean;\n releaseResumeReplay(requestId: string, owner: symbol): void;\n /** Record authoritative host acceptance. The execution claim remains held\n * so a briefly stale request cannot execute its local side effects again. */\n settleResume(requestId: string): void;\n /** Atomically consume one bounded replay attempt for the current owner. */\n takeResumeAttempt(\n requestId: string,\n options: { owner: symbol; maxAttempts: number },\n ): ClientToolResumeAttempt | undefined;\n}\n\nexport interface ClientToolCachedResume {\n value: Record<string, unknown>;\n attemptCount: number;\n}\n\nexport interface ClientToolResumeAttempt {\n value: Record<string, unknown>;\n attemptNumber: number;\n}\n\nexport interface CreateClientToolRequestTrackerOptions {\n /** Maximum completed resume values retained for reconnect recovery. Active\n * executions are never evicted. */\n maxCachedResumes?: number;\n}\n\ninterface ClientToolRequestEntry {\n resumeValue?: Record<string, unknown>;\n resumeAttemptCount: number;\n resumeOwner?: symbol;\n settled?: boolean;\n}\n\nconst DEFAULT_MAX_CACHED_CLIENT_TOOL_RESUMES = 128;\n\nexport function createClientToolRequestTracker(\n options: CreateClientToolRequestTrackerOptions = {},\n): ClientToolRequestTracker {\n const maxCachedResumes = options.maxCachedResumes ?? DEFAULT_MAX_CACHED_CLIENT_TOOL_RESUMES;\n const requests = new Map<string, ClientToolRequestEntry>();\n\n const pruneCompletedRequests = (protectedRequestId?: string): void => {\n let completedCount = 0;\n for (const entry of requests.values()) {\n if (entry.resumeValue !== undefined || entry.settled === true) completedCount += 1;\n }\n if (completedCount <= maxCachedResumes) return;\n\n // Map iteration is insertion order. Only inactive, completed entries are\n // eligible: evicting an executing request could allow a document mutation\n // to run twice, evicting an active replay would split ownership, and the\n // newly completed request must survive long enough for its first dispatch.\n for (const [requestId, entry] of requests) {\n if (completedCount <= maxCachedResumes) break;\n if (\n requestId === protectedRequestId ||\n (entry.resumeValue === undefined && entry.settled !== true) ||\n entry.resumeOwner !== undefined\n ) {\n continue;\n }\n requests.delete(requestId);\n completedCount -= 1;\n }\n };\n\n return {\n claim(requestId: string): boolean {\n if (requests.has(requestId)) return false;\n requests.set(requestId, { resumeAttemptCount: 0 });\n return true;\n },\n release(requestId: string): void {\n requests.delete(requestId);\n },\n has(requestId: string): boolean {\n return requests.has(requestId);\n },\n cacheResume(requestId: string, value: Record<string, unknown>): void {\n const entry = requests.get(requestId) ?? { resumeAttemptCount: 0 };\n entry.resumeValue = value;\n entry.settled = false;\n requests.delete(requestId);\n requests.set(requestId, entry);\n pruneCompletedRequests(requestId);\n },\n getCachedResume(requestId: string): ClientToolCachedResume | undefined {\n const entry = requests.get(requestId);\n if (!entry || entry.resumeValue === undefined) return undefined;\n return {\n value: entry.resumeValue,\n attemptCount: entry.resumeAttemptCount,\n };\n },\n claimResumeReplay(requestId: string, owner: symbol): boolean {\n const entry = requests.get(requestId);\n if (!entry || entry.resumeValue === undefined) return false;\n if (entry.resumeOwner !== undefined && entry.resumeOwner !== owner) {\n return false;\n }\n entry.resumeOwner = owner;\n return true;\n },\n releaseResumeReplay(requestId: string, owner: symbol): void {\n const entry = requests.get(requestId);\n if (entry?.resumeOwner === owner) entry.resumeOwner = undefined;\n pruneCompletedRequests();\n },\n settleResume(requestId: string): void {\n const entry = requests.get(requestId);\n if (!entry) return;\n entry.resumeValue = undefined;\n entry.resumeOwner = undefined;\n entry.settled = true;\n requests.delete(requestId);\n requests.set(requestId, entry);\n pruneCompletedRequests(requestId);\n },\n takeResumeAttempt(\n requestId: string,\n attemptOptions: { owner: symbol; maxAttempts: number },\n ): ClientToolResumeAttempt | undefined {\n const entry = requests.get(requestId);\n if (\n !entry ||\n entry.resumeValue === undefined ||\n entry.resumeOwner !== attemptOptions.owner ||\n entry.resumeAttemptCount >= attemptOptions.maxAttempts\n ) {\n return undefined;\n }\n entry.resumeAttemptCount += 1;\n return {\n value: entry.resumeValue,\n attemptNumber: entry.resumeAttemptCount,\n };\n },\n };\n}\n"],"names":[],"mappings":";AA8EA,SAAS,wBAAwB,OAAgD;AAC/E,MAAI,CAAC,SAAS,OA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AAA,MAAA;AAAA,IAExB;AAAA,IACA,kBAAkB,WAAmB,OAAwB;AAC3D,YAAM,QAAQ,SAAS,IAAI,SAAS;AACpC,UAAI,CAAC,SAAS,MAAM,gBAAgB,OAAW,QAAO;AACtD,UAAI,MAAM,gBAAgB,UAAa,MAAM,gBAAgB,OAAO;AAClE,eAAO;AAAA,MACT;AACA,YAAM,cAAc;AACpB,aAAO;AAAA,IACT;AAAA,IACA,oBAAoB,WAAmB,OAAqB;AAC1D,YAAM,QAAQ,SAAS,IAAI,SAAS;AACpC,WAAI,+BAAO,iBAAgB,MAAO,OAAM,cAAc;AACtD,6BAAA;AAAA,IACF;AAAA,IACA,aAAa,WAAyB;AACpC,YAAM,QAAQ,SAAS,IAAI,SAAS;AACpC,UAAI,CAAC,MAAO;AACZ,YAAM,cAAc;AACpB,YAAM,cAAc;AACpB,YAAM,UAAU;AAChB,eAAS,OAAO,SAAS;AACzB,eAAS,IAAI,WAAW,KAAK;AAC7B,6BAAuB,SAAS;AAAA,IAClC;AAAA,IACA,kBACE,WACA,gBACqC;AACrC,YAAM,QAAQ,SAAS,IAAI,SAAS;AACpC,UACE,CAAC,SACD,MAAM,gBAAgB,UACtB,MAAM,gBAAgB,eAAe,SACrC,MAAM,sBAAsB,eAAe,aAC3C;AACA,eAAO;AAAA,MACT;AACA,YAAM,sBAAsB;AAC5B,aAAO;AAAA,QACL,OAAO,MAAM;AAAA,QACb,eAAe,MAAM;AAAA,MAAA;AAAA,IAEzB;AAAA,EAAA;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"client-tools.js","sources":["../../../../agent-runtime/src/client-tools.ts"],"sourcesContent":["/**\n * Client-executed tools for statewire deep-agent threads.\n *\n * A client (the Office add-in, the Chrome extension, …) declares tools it can\n * execute locally by sending their JSON-schema definitions through\n * `runConfig.custom.client_tools`. The deep-agent runtime binds them as\n * interrupt-backed tools: when the model calls one, the run parks on a\n * LangGraph interrupt whose payload carries the tool name and arguments, the\n * statewire host publishes it as an `interrupt` input request, and the client\n * executes the tool and resumes the run with the result envelope.\n *\n * This module is transport-agnostic: it holds the wire contract (definitions,\n * interrupt payload shape, result envelopes) and a duplicate-execution guard.\n * The React hook that watches input requests lives with each client, next to\n * its host-specific tool handlers.\n */\n\nimport {\n CLIENT_TOOL_INTERRUPT_SOURCE,\n CLIENT_TOOL_RESULT_STATUS_ERROR,\n CLIENT_TOOL_RESULT_STATUS_SUCCESS,\n} from './generated/runconfig-contract';\n\n/** `source`/`type` stamped on the interrupt payload by the agora runtime. */\nexport { CLIENT_TOOL_INTERRUPT_SOURCE } from './generated/runconfig-contract';\n\n/** JSON-schema description of one client-executed tool. */\nexport interface ClientToolDefinition {\n /** Snake_case tool id the model calls (e.g. `update_sheet_range`). */\n name: string;\n description: string;\n /** JSON schema for the tool arguments (`{\"type\": \"object\", ...}`). */\n parameters: Record<string, unknown>;\n /** Mutating tools gate on the client's write-approval flow before running. */\n requiresWrite: boolean;\n}\n\n/** Per-call context the client-tool bridge hands a handler; absent when a host\n * invokes a handler outside a parked run. */\nexport interface ClientToolHandlerContext {\n /** The model's tool-call id, for handlers that correlate calls. */\n toolCallId: string;\n /**\n * Aborts when the parked call's request goes away before the handler\n * finished: the run was stopped, the call was answered elsewhere, or the\n * person opened another conversation. Whatever the handler returns after\n * that is discarded, so a handler that takes visible time (a paced\n * walkthrough, typing shown to the person) should stop on it. Absent when a\n * host invokes the handler outside the bridge.\n */\n signal?: AbortSignal;\n}\n\nexport type ClientToolHandler = (\n args: Record<string, unknown>,\n context?: ClientToolHandlerContext,\n) => Promise<unknown>;\n\nexport interface RegisteredClientTool {\n definition: ClientToolDefinition;\n handler: ClientToolHandler;\n}\n\n/** One parked tool call inside a batched client-tool input request. */\nexport interface ClientToolCallRequest {\n /** LangGraph interrupt id — the key the resume result map must use. */\n interrupt_id: string;\n tool_name: string;\n tool_args: Record<string, unknown>;\n requires_write?: boolean;\n}\n\n/**\n * The input-request payload the agora runtime publishes for parked client\n * tool calls. A parallel model turn parks several interrupts at once; the\n * runtime batches them into one payload and the client answers once with\n * `{ client_tool_results: { <interrupt_id>: <result envelope> } }`.\n */\nexport interface ClientToolInterruptPayload {\n source: typeof CLIENT_TOOL_INTERRUPT_SOURCE;\n type: typeof CLIENT_TOOL_INTERRUPT_SOURCE;\n message: string;\n context: {\n requests: ClientToolCallRequest[];\n };\n}\n\nfunction isClientToolCallRequest(value: unknown): value is ClientToolCallRequest {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const candidate = value as Partial<ClientToolCallRequest>;\n return (\n typeof candidate.interrupt_id === 'string' &&\n candidate.interrupt_id.length > 0 &&\n typeof candidate.tool_name === 'string'\n );\n}\n\n/**\n * Loose source check for surfaces that must NOT handle a client-tool park\n * (e.g. the generic approval banner). Unlike `isClientToolInterrupt`, this\n * matches any payload stamped with the client-tool source — including shapes\n * from a mismatched client/server version — so a skewed deploy can never\n * surface a generic \"Continue\" resume that corrupts a parked tool call.\n */\nexport function hasClientToolInterruptSource(payload: unknown): boolean {\n return (\n !!payload &&\n typeof payload === 'object' &&\n !Array.isArray(payload) &&\n (payload as { source?: unknown }).source === CLIENT_TOOL_INTERRUPT_SOURCE\n );\n}\n\nexport function isClientToolInterrupt(\n payload: unknown,\n): payload is ClientToolInterruptPayload {\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {\n return false;\n }\n const candidate = payload as Partial<ClientToolInterruptPayload>;\n return (\n candidate.source === CLIENT_TOOL_INTERRUPT_SOURCE &&\n candidate.type === CLIENT_TOOL_INTERRUPT_SOURCE &&\n typeof candidate.context === 'object' &&\n candidate.context !== null &&\n Array.isArray(candidate.context.requests) &&\n candidate.context.requests.length > 0 &&\n candidate.context.requests.every(isClientToolCallRequest)\n );\n}\n\n/** Tool arguments from a call request, defaulting to an empty object. */\nexport function clientToolCallArgs(\n request: ClientToolCallRequest,\n): Record<string, unknown> {\n const args = request.tool_args;\n return args && typeof args === 'object' && !Array.isArray(args) ? args : {};\n}\n\n/** The `run/input` resume value answering a batched client-tool park. */\nexport function clientToolResultsResumeValue(\n results: Record<string, ClientToolResultEnvelope>,\n): Record<string, unknown> {\n return { client_tool_results: results };\n}\n\n/** Wire entries for `runConfig.custom.client_tools`. */\nexport function clientToolRunConfigEntries(\n tools: readonly RegisteredClientTool[],\n): Record<string, unknown>[] {\n return tools.map(({ definition }) => ({\n name: definition.name,\n description: definition.description,\n parameters: definition.parameters,\n requires_write: definition.requiresWrite,\n }));\n}\n\n/** Successful tool execution, resumed back into the parked run. */\nexport interface ClientToolSuccessEnvelope {\n status: typeof CLIENT_TOOL_RESULT_STATUS_SUCCESS;\n result: unknown;\n}\n\n/** Failed or declined tool execution, resumed back into the parked run. */\nexport interface ClientToolErrorEnvelope {\n status: typeof CLIENT_TOOL_RESULT_STATUS_ERROR;\n error: string;\n}\n\nexport type ClientToolResultEnvelope =\n | ClientToolSuccessEnvelope\n | ClientToolErrorEnvelope;\n\nexport function clientToolSuccessEnvelope(\n result: unknown,\n): ClientToolSuccessEnvelope {\n return {\n status: CLIENT_TOOL_RESULT_STATUS_SUCCESS,\n result: result === undefined ? null : result,\n };\n}\n\nexport function clientToolErrorEnvelope(error: unknown): ClientToolErrorEnvelope {\n const message =\n error instanceof Error\n ? error.message\n : typeof error === 'string'\n ? error\n : 'Client tool execution failed.';\n return { status: CLIENT_TOOL_RESULT_STATUS_ERROR, error: message };\n}\n\n/**\n * Once-per-request execution guard. Statewire re-emits the pending input\n * request on every state update, so an executor effect can observe the same\n * request many times; the tracker makes exactly one observation win.\n */\nexport interface ClientToolRequestTracker {\n /** True exactly once per request id; later calls return false. */\n claim(requestId: string): boolean;\n /** Un-claim a request that was NOT resumed (e.g. abandoned mid-approval),\n * so a re-emitted request can be executed instead of stranding the run. */\n release(requestId: string): void;\n has(requestId: string): boolean;\n /** Cache the completed, wire-safe resume value without releasing the\n * exactly-once execution claim. A reconnect may replay this value, but it\n * must never execute the local handler again. */\n cacheResume(requestId: string, value: Record<string, unknown>): void;\n getCachedResume(requestId: string): ClientToolCachedResume | undefined;\n /** Give one mounted bridge ownership of retrying a cached resume. */\n claimResumeReplay(requestId: string, owner: symbol): boolean;\n releaseResumeReplay(requestId: string, owner: symbol): void;\n /** Record authoritative host acceptance. The execution claim remains held\n * so a briefly stale request cannot execute its local side effects again. */\n settleResume(requestId: string): void;\n /** Atomically consume one bounded replay attempt for the current owner. */\n takeResumeAttempt(\n requestId: string,\n options: { owner: symbol; maxAttempts: number },\n ): ClientToolResumeAttempt | undefined;\n}\n\nexport interface ClientToolCachedResume {\n value: Record<string, unknown>;\n attemptCount: number;\n}\n\nexport interface ClientToolResumeAttempt {\n value: Record<string, unknown>;\n attemptNumber: number;\n}\n\nexport interface CreateClientToolRequestTrackerOptions {\n /** Maximum completed resume values retained for reconnect recovery. Active\n * executions are never evicted. */\n maxCachedResumes?: number;\n}\n\ninterface ClientToolRequestEntry {\n resumeValue?: Record<string, unknown>;\n resumeAttemptCount: number;\n resumeOwner?: symbol;\n settled?: boolean;\n}\n\nconst DEFAULT_MAX_CACHED_CLIENT_TOOL_RESUMES = 128;\n\nexport function createClientToolRequestTracker(\n options: CreateClientToolRequestTrackerOptions = {},\n): ClientToolRequestTracker {\n const maxCachedResumes = options.maxCachedResumes ?? DEFAULT_MAX_CACHED_CLIENT_TOOL_RESUMES;\n const requests = new Map<string, ClientToolRequestEntry>();\n\n const pruneCompletedRequests = (protectedRequestId?: string): void => {\n let completedCount = 0;\n for (const entry of requests.values()) {\n if (entry.resumeValue !== undefined || entry.settled === true) completedCount += 1;\n }\n if (completedCount <= maxCachedResumes) return;\n\n // Map iteration is insertion order. Only inactive, completed entries are\n // eligible: evicting an executing request could allow a document mutation\n // to run twice, evicting an active replay would split ownership, and the\n // newly completed request must survive long enough for its first dispatch.\n for (const [requestId, entry] of requests) {\n if (completedCount <= maxCachedResumes) break;\n if (\n requestId === protectedRequestId ||\n (entry.resumeValue === undefined && entry.settled !== true) ||\n entry.resumeOwner !== undefined\n ) {\n continue;\n }\n requests.delete(requestId);\n completedCount -= 1;\n }\n };\n\n return {\n claim(requestId: string): boolean {\n if (requests.has(requestId)) return false;\n requests.set(requestId, { resumeAttemptCount: 0 });\n return true;\n },\n release(requestId: string): void {\n requests.delete(requestId);\n },\n has(requestId: string): boolean {\n return requests.has(requestId);\n },\n cacheResume(requestId: string, value: Record<string, unknown>): void {\n const entry = requests.get(requestId) ?? { resumeAttemptCount: 0 };\n entry.resumeValue = value;\n entry.settled = false;\n requests.delete(requestId);\n requests.set(requestId, entry);\n pruneCompletedRequests(requestId);\n },\n getCachedResume(requestId: string): ClientToolCachedResume | undefined {\n const entry = requests.get(requestId);\n if (!entry || entry.resumeValue === undefined) return undefined;\n return {\n value: entry.resumeValue,\n attemptCount: entry.resumeAttemptCount,\n };\n },\n claimResumeReplay(requestId: string, owner: symbol): boolean {\n const entry = requests.get(requestId);\n if (!entry || entry.resumeValue === undefined) return false;\n if (entry.resumeOwner !== undefined && entry.resumeOwner !== owner) {\n return false;\n }\n entry.resumeOwner = owner;\n return true;\n },\n releaseResumeReplay(requestId: string, owner: symbol): void {\n const entry = requests.get(requestId);\n if (entry?.resumeOwner === owner) entry.resumeOwner = undefined;\n pruneCompletedRequests();\n },\n settleResume(requestId: string): void {\n const entry = requests.get(requestId);\n if (!entry) return;\n entry.resumeValue = undefined;\n entry.resumeOwner = undefined;\n entry.settled = true;\n requests.delete(requestId);\n requests.set(requestId, entry);\n pruneCompletedRequests(requestId);\n },\n takeResumeAttempt(\n requestId: string,\n attemptOptions: { owner: symbol; maxAttempts: number },\n ): ClientToolResumeAttempt | undefined {\n const entry = requests.get(requestId);\n if (\n !entry ||\n entry.resumeValue === undefined ||\n entry.resumeOwner !== attemptOptions.owner ||\n entry.resumeAttemptCount >= attemptOptions.maxAttempts\n ) {\n return undefined;\n }\n entry.resumeAttemptCount += 1;\n return {\n value: entry.resumeValue,\n attemptNumber: entry.resumeAttemptCount,\n };\n },\n };\n}\n"],"names":[],"mappings":";AAuFA,SAAS,wBAAwB,OAAgD;AA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;AAAA,QACb,cAAc,MAAM;AAAA,MAAA;AAAA,IAExB;AAAA,IACA,kBAAkB,WAAmB,OAAwB;AAC3D,YAAM,QAAQ,SAAS,IAAI,SAAS;AACpC,UAAI,CAAC,SAAS,MAAM,gBAAgB,OAAW,QAAO;AACtD,UAAI,MAAM,gBAAgB,UAAa,MAAM,gBAAgB,OAAO;AAClE,eAAO;AAAA,MACT;AACA,YAAM,cAAc;AACpB,aAAO;AAAA,IACT;AAAA,IACA,oBAAoB,WAAmB,OAAqB;AAC1D,YAAM,QAAQ,SAAS,IAAI,SAAS;AACpC,WAAI,+BAAO,iBAAgB,MAAO,OAAM,cAAc;AACtD,6BAAA;AAAA,IACF;AAAA,IACA,aAAa,WAAyB;AACpC,YAAM,QAAQ,SAAS,IAAI,SAAS;AACpC,UAAI,CAAC,MAAO;AACZ,YAAM,cAAc;AACpB,YAAM,cAAc;AACpB,YAAM,UAAU;AAChB,eAAS,OAAO,SAAS;AACzB,eAAS,IAAI,WAAW,KAAK;AAC7B,6BAAuB,SAAS;AAAA,IAClC;AAAA,IACA,kBACE,WACA,gBACqC;AACrC,YAAM,QAAQ,SAAS,IAAI,SAAS;AACpC,UACE,CAAC,SACD,MAAM,gBAAgB,UACtB,MAAM,gBAAgB,eAAe,SACrC,MAAM,sBAAsB,eAAe,aAC3C;AACA,eAAO;AAAA,MACT;AACA,YAAM,sBAAsB;AAC5B,aAAO;AAAA,QACL,OAAO,MAAM;AAAA,QACb,eAAe,MAAM;AAAA,MAAA;AAAA,IAEzB;AAAA,EAAA;AAEJ;"}
|
|
@@ -98,21 +98,6 @@ function takeStagedComposerMarkdownMetadata(threadId, now = Date.now()) {
|
|
|
98
98
|
}
|
|
99
99
|
return { [DEEP_AGENT_COMPOSER_MARKDOWN_KEY]: entry.markdown };
|
|
100
100
|
}
|
|
101
|
-
function withStagedComposerMarkdown({
|
|
102
|
-
threadId,
|
|
103
|
-
getMessageMetadata
|
|
104
|
-
}) {
|
|
105
|
-
return () => {
|
|
106
|
-
const staged = takeStagedComposerMarkdownMetadata(threadId);
|
|
107
|
-
const captured = getMessageMetadata == null ? void 0 : getMessageMetadata();
|
|
108
|
-
if (staged === void 0) return captured;
|
|
109
|
-
const merge = (host) => ({
|
|
110
|
-
...host,
|
|
111
|
-
...staged
|
|
112
|
-
});
|
|
113
|
-
return captured instanceof Promise ? captured.then(merge) : merge(captured);
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
101
|
function withDeepAgentComposerMarkdown({
|
|
117
102
|
metadata,
|
|
118
103
|
text,
|
|
@@ -130,5 +115,4 @@ exports.stageComposerMarkdown = stageComposerMarkdown;
|
|
|
130
115
|
exports.takeStagedComposerMarkdownMetadata = takeStagedComposerMarkdownMetadata;
|
|
131
116
|
exports.trimComposerDraft = trimComposerDraft;
|
|
132
117
|
exports.withDeepAgentComposerMarkdown = withDeepAgentComposerMarkdown;
|
|
133
|
-
exports.withStagedComposerMarkdown = withStagedComposerMarkdown;
|
|
134
118
|
//# sourceMappingURL=composer-markdown.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"composer-markdown.cjs","sources":["../../../../agent-runtime/src/composer-markdown.ts"],"sourcesContent":["/**\n * The composer markdown a chat message was sent from.\n *\n * The chat composer sends a message's plain text exactly as typed, because the\n * model reads the text literally, and writes real formatting (bold, lists,\n * code, mention chips) as markdown. The sent text alone no longer says which\n * characters are formatting and which were typed: literal `**strong**` and\n * bold `strong` both send `**strong**`, and `List<T>`, `a\\\\b` or `2*3*4` read\n * as markup when the text is rendered as markdown. So the composer also\n * attaches the draft the text was serialized from (the same document with its\n * plain text escaped for markdown) under {@link DEEP_AGENT_COMPOSER_MARKDOWN_KEY}\n * in the message's metadata, and only when the two differ.\n *\n * It rides the statewire message, the queue and steer lanes and the persisted\n * HumanMessage (`additional_kwargs.metadata`, which the converter surfaces as\n * `metadata.custom`). It is display-only: the bubble renders it, and Edit,\n * branch-and-edit and a withdrawn turn load it back into the composer. The\n * model reads the message text, never this. A message without it (older\n * messages, other clients) renders its text as before.\n *\n * agora validates it with the same rule\n * (`agora/graphs/athena_deep_agent/composer_markdown.py`).\n */\nexport const DEEP_AGENT_COMPOSER_MARKDOWN_KEY = 'composer_markdown';\n\nconst DRAFT_CHARACTER_REFERENCES: Readonly<Record<string, string>> = {\n lt: '<',\n gt: '>',\n amp: '&',\n '#32': ' ',\n '#9': '\\t',\n};\n\n/**\n * A sent text in comparable form: every backslash dropped (the draft's\n * escapes, and the `\\` before a hard break's newline, are backslashes).\n */\nconst comparableText = (text: string): string => text.replace(/\\\\/g, '');\n\n/**\n * A draft in comparable form: every backslash dropped, then the character\n * references the draft serializer writes decoded in one pass (`<` and\n * `>` for typed `<` and `>`, `&` for a typed `&` that starts a\n * reference, so typed `<` is `&lt;`, and ` ` / `	` for the space\n * or tab a line starts with, which markdown would otherwise drop).\n */\nconst comparableDraft = (markdown: string): string =>\n comparableText(markdown).replace(\n /&(lt|gt|amp|#32|#9);/g,\n (reference, name: string) => DRAFT_CHARACTER_REFERENCES[name] ?? reference\n );\n\n/**\n * Escaping at most turns one character into four (`<` → `<`). A line's\n * first space becomes five (` `), but only once a line, so a whole line\n * with its line break stays under four a character; the slack covers short\n * texts. agora caps a stored draft the same way.\n */\nconst MAX_EXPANSION = 4;\nconst EXPANSION_SLACK_CHARS = 1024;\n\n/**\n * Whether `markdown` is the draft of `text`: no longer than escaping could make\n * it, and equal to it once backslashes are dropped and the draft's character\n * references decoded. A draft that would show other\n * words than the text the model read (another message's, a client's mistake) is\n * not taken; such a message renders its text as before.\n */\nexport function isComposerMarkdownOfText({\n markdown,\n text,\n}: {\n markdown: string;\n text: string;\n}): boolean {\n return (\n markdown.length <= text.length * MAX_EXPANSION + EXPANSION_SLACK_CHARS &&\n comparableDraft(markdown) === comparableText(text)\n );\n}\n\n/** The references a draft writes a line's first space or tab as. */\nconst DRAFT_WHITESPACE_REFERENCES: readonly string[] = [' ', '	'];\n\nconst isWhitespace = (character: string): boolean => /\\s/.test(character);\n\n/** A hard break in a draft: `\\` before the newline (the text holds the newline alone). */\nconst DRAFT_HARD_BREAK = '\\\\\\n';\n\n/** Whether an odd run of backslashes ends at `end`: its last one escapes what follows, not a typed `\\` (`\\\\`). */\nfunction endsInEscapingBackslash({\n markdown,\n start,\n end,\n}: {\n markdown: string;\n start: number;\n end: number;\n}): boolean {\n let backslashes = 0;\n while (end - backslashes > start && markdown.charAt(end - backslashes - 1) === '\\\\') {\n backslashes += 1;\n }\n return backslashes % 2 === 1;\n}\n\n/**\n * `markdown`, a draft, trimmed as its text is trimmed (`text.trim()`): a\n * send that trims its text stays a draft of it. `markdown.trim()` would keep\n * the ` ` a draft writes for the space its first line starts with, and the\n * `\\` of a line break whose newline it trims.\n */\nexport function trimComposerDraft(markdown: string): string {\n let start = 0;\n let end = markdown.length;\n for (;;) {\n while (start < end && isWhitespace(markdown.charAt(start))) start += 1;\n const reference = [...DRAFT_WHITESPACE_REFERENCES, DRAFT_HARD_BREAK].find(\n (candidate) => start + candidate.length <= end && markdown.startsWith(candidate, start)\n );\n if (reference === undefined) break;\n start += reference.length;\n }\n for (;;) {\n while (end > start && isWhitespace(markdown.charAt(end - 1))) end -= 1;\n const reference = DRAFT_WHITESPACE_REFERENCES.find(\n (candidate) => end - candidate.length >= start && markdown.endsWith(candidate, end)\n );\n if (reference !== undefined) {\n end -= reference.length;\n } else if (\n markdown.charAt(end) === '\\n' &&\n endsInEscapingBackslash({ markdown, start, end })\n ) {\n // The newline just trimmed was a line break's: its `\\` goes with it.\n end -= 1;\n } else {\n break;\n }\n }\n return markdown.slice(start, end);\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/**\n * The composer markdown to render or load for a message whose metadata is\n * `metadata` (a message's `metadata.custom`, or a lane entry's `metadata`) and\n * whose text is `text`; `null` when it carries none, or one that is not a\n * draft of `text`.\n */\nexport function readDeepAgentComposerMarkdown({\n metadata,\n text,\n}: {\n metadata: unknown;\n text: string;\n}): string | null {\n if (!isRecord(metadata)) return null;\n const markdown: unknown = metadata[DEEP_AGENT_COMPOSER_MARKDOWN_KEY];\n return typeof markdown === 'string' && isComposerMarkdownOfText({ markdown, text })\n ? markdown\n : null;\n}\n\n/**\n * How long a staged composer markdown waits for its submission\n * ({@link stageComposerMarkdown}).\n */\nexport const STAGED_COMPOSER_MARKDOWN_TTL_MS = 10_000;\n\ninterface StagedComposerMarkdown {\n readonly markdown: string;\n readonly stagedAt: number;\n}\n\n/**\n * The staged drafts live on `globalThis`, not in module scope, because two\n * copies of this module run in one page: the SDK bundles agent-runtime into its\n * dist, so its composer stages through the SDK's copy, while the Chrome\n * extension and the Office add-in build their runtime on agent-runtime directly\n * and take the draft through their own (see `asset-attachment.ts`).\n */\nconst STAGED_COMPOSER_MARKDOWN = Symbol.for('@athenaintel/agent-runtime/staged-composer-markdown');\n\ntype StagedComposerMarkdownHost = typeof globalThis & {\n [STAGED_COMPOSER_MARKDOWN]?: Map<string, StagedComposerMarkdown>;\n};\n\nfunction stagedComposerMarkdownByThread(): Map<string, StagedComposerMarkdown> {\n const host = globalThis as StagedComposerMarkdownHost;\n return (host[STAGED_COMPOSER_MARKDOWN] ??= new Map());\n}\n\n/**\n * Stage the draft `markdown` of `text` for `threadId`'s next submission.\n *\n * statewire captures message metadata once per new user message\n * (`getMessageMetadata`, patched into `@assistant-ui/react-statewire@0.33.0`)\n * without saying which message it is for, so a composer stages its draft right\n * before it sends and the runtime's getter takes it for the submission that\n * follows ({@link withStagedComposerMarkdown}). A draft equal to its text adds\n * nothing and clears the slot. A slot nobody takes within\n * {@link STAGED_COMPOSER_MARKDOWN_TTL_MS} expires; one a submission the\n * composer did not make takes is harmless, since a composer markdown that is\n * not a draft of the message's own text is neither kept by agora nor rendered.\n */\nexport function stageComposerMarkdown({\n threadId,\n text,\n markdown,\n now = Date.now(),\n}: {\n threadId: string;\n text: string;\n markdown: string;\n /** Test seam: the time of the send. */\n now?: number;\n}): void {\n const staged = stagedComposerMarkdownByThread();\n if (markdown === text) {\n staged.delete(threadId);\n return;\n }\n staged.set(threadId, { markdown, stagedAt: now });\n}\n\n/**\n * The message metadata for `threadId`'s submission now being journaled: the\n * staged composer markdown, if one is waiting and fresh. Takes the slot.\n */\nexport function takeStagedComposerMarkdownMetadata(\n threadId: string,\n now: number = Date.now()\n): Record<string, unknown> | undefined {\n const staged = stagedComposerMarkdownByThread();\n const entry = staged.get(threadId);\n staged.delete(threadId);\n if (entry === undefined || now - entry.stagedAt > STAGED_COMPOSER_MARKDOWN_TTL_MS) {\n return undefined;\n }\n return { [DEEP_AGENT_COMPOSER_MARKDOWN_KEY]: entry.markdown };\n}\n\ntype MessageMetadataGetter = () =>\n | Record<string, unknown>\n | undefined\n | Promise<Record<string, unknown> | undefined>;\n\n/**\n * A runtime's `getMessageMetadata` that also carries the composer markdown a\n * composer staged for `threadId` ({@link stageComposerMarkdown}), on top of the\n * host's own metadata (`getMessageMetadata`, when it has one). The slot is\n * taken synchronously at submission, before the host's capture resolves, so a\n * draft never rides a later message. With nothing staged the host's own value\n * is returned as is.\n */\nexport function withStagedComposerMarkdown({\n threadId,\n getMessageMetadata,\n}: {\n threadId: string;\n getMessageMetadata?: MessageMetadataGetter | undefined;\n}): MessageMetadataGetter {\n return () => {\n const staged = takeStagedComposerMarkdownMetadata(threadId);\n const captured = getMessageMetadata?.();\n if (staged === undefined) return captured;\n const merge = (host: Record<string, unknown> | undefined): Record<string, unknown> => ({\n ...host,\n ...staged,\n });\n return captured instanceof Promise ? captured.then(merge) : merge(captured);\n };\n}\n\n/** Test seam: drop every staged composer markdown. */\nexport function resetStagedComposerMarkdown(): void {\n stagedComposerMarkdownByThread().clear();\n}\n\n/**\n * `metadata` with the composer markdown set to the draft `markdown` of `text`,\n * or without it when the draft equals the text (it adds nothing then).\n * Returns `undefined` when nothing is left.\n */\nexport function withDeepAgentComposerMarkdown({\n metadata,\n text,\n markdown,\n}: {\n metadata: Readonly<Record<string, unknown>> | undefined;\n text: string;\n markdown: string;\n}): Record<string, unknown> | undefined {\n const { [DEEP_AGENT_COMPOSER_MARKDOWN_KEY]: _previous, ...rest } = metadata ?? {};\n const next: Record<string, unknown> =\n markdown === text ? rest : { ...rest, [DEEP_AGENT_COMPOSER_MARKDOWN_KEY]: markdown };\n return Object.keys(next).length > 0 ? next : undefined;\n}\n"],"names":[],"mappings":";;AAuBO,MAAM,mCAAmC;AAEhD,MAAM,6BAA+D;AAAA,EACnE,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,KAAK;AAAA,EACL,OAAO;AAAA,EACP,MAAM;AACR;AAMA,MAAM,iBAAiB,CAAC,SAAyB,KAAK,QAAQ,OAAO,EAAE;AASvE,MAAM,kBAAkB,CAAC,aACvB,eAAe,QAAQ,EAAE;AAAA,EACvB;AAAA,EACA,CAAC,WAAW,SAAiB,2BAA2B,IAAI,KAAK;AACnE;AAQF,MAAM,gBAAgB;AACtB,MAAM,wBAAwB;AASvB,SAAS,yBAAyB;AAAA,EACvC;AAAA,EACA;AACF,GAGY;AACV,SACE,SAAS,UAAU,KAAK,SAAS,gBAAgB,yBACjD,gBAAgB,QAAQ,MAAM,eAAe,IAAI;AAErD;AAGA,MAAM,8BAAiD,CAAC,SAAS,MAAM;AAEvE,MAAM,eAAe,CAAC,cAA+B,KAAK,KAAK,SAAS;AAGxE,MAAM,mBAAmB;AAGzB,SAAS,wBAAwB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AACF,GAIY;AACV,MAAI,cAAc;AAClB,SAAO,MAAM,cAAc,SAAS,SAAS,OAAO,MAAM,cAAc,CAAC,MAAM,MAAM;AACnF,mBAAe;AAAA,EACjB;AACA,SAAO,cAAc,MAAM;AAC7B;AAQO,SAAS,kBAAkB,UAA0B;AAC1D,MAAI,QAAQ;AACZ,MAAI,MAAM,SAAS;AACnB,aAAS;AACP,WAAO,QAAQ,OAAO,aAAa,SAAS,OAAO,KAAK,CAAC,EAAG,UAAS;AACrE,UAAM,YAAY,CAAC,G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,IAAI,UAAU,EAAE,UAAU,UAAU,KAAK;AAClD;AAMO,SAAS,mCACd,UACA,MAAc,KAAK,OACkB;AACrC,QAAM,SAAS,+BAAA;AACf,QAAM,QAAQ,OAAO,IAAI,QAAQ;AACjC,SAAO,OAAO,QAAQ;AACtB,MAAI,UAAU,UAAa,MAAM,MAAM,WAAW,iCAAiC;AACjF,WAAO;AAAA,EACT;AACA,SAAO,EAAE,CAAC,gCAAgC,GAAG,MAAM,SAAA;AACrD;AAeO,SAAS,2BAA2B;AAAA,EACzC;AAAA,EACA;AACF,GAG0B;AACxB,SAAO,MAAM;AACX,UAAM,SAAS,mCAAmC,QAAQ;AAC1D,UAAM,WAAW;AACjB,QAAI,WAAW,OAAW,QAAO;AACjC,UAAM,QAAQ,CAAC,UAAwE;AAAA,MACrF,GAAG;AAAA,MACH,GAAG;AAAA,IAAA;AAEL,WAAO,oBAAoB,UAAU,SAAS,KAAK,KAAK,IAAI,MAAM,QAAQ;AAAA,EAC5E;AACF;AAYO,SAAS,8BAA8B;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AACF,GAIwC;AACtC,QAAM,EAAE,CAAC,gCAAgC,GAAG,WAAW,GAAG,KAAA,IAAS,YAAY,CAAA;AAC/E,QAAM,OACJ,aAAa,OAAO,OAAO,EAAE,GAAG,MAAM,CAAC,gCAAgC,GAAG,SAAA;AAC5E,SAAO,OAAO,KAAK,IAAI,EAAE,SAAS,IAAI,OAAO;AAC/C;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"composer-markdown.cjs","sources":["../../../../agent-runtime/src/composer-markdown.ts"],"sourcesContent":["/**\n * The composer markdown a chat message was sent from.\n *\n * The chat composer sends a message's plain text exactly as typed, because the\n * model reads the text literally, and writes real formatting (bold, lists,\n * code, mention chips) as markdown. The sent text alone no longer says which\n * characters are formatting and which were typed: literal `**strong**` and\n * bold `strong` both send `**strong**`, and `List<T>`, `a\\\\b` or `2*3*4` read\n * as markup when the text is rendered as markdown. So the composer also\n * attaches the draft the text was serialized from (the same document with its\n * plain text escaped for markdown) under {@link DEEP_AGENT_COMPOSER_MARKDOWN_KEY}\n * in the message's metadata, and only when the two differ.\n *\n * It rides the statewire message, the queue and steer lanes and the persisted\n * HumanMessage (`additional_kwargs.metadata`, which the converter surfaces as\n * `metadata.custom`). It is display-only: the bubble renders it, and Edit,\n * branch-and-edit and a withdrawn turn load it back into the composer. The\n * model reads the message text, never this. A message without it (older\n * messages, other clients) renders its text as before.\n *\n * agora validates it with the same rule\n * (`agora/graphs/athena_deep_agent/composer_markdown.py`).\n */\nexport const DEEP_AGENT_COMPOSER_MARKDOWN_KEY = 'composer_markdown';\n\nconst DRAFT_CHARACTER_REFERENCES: Readonly<Record<string, string>> = {\n lt: '<',\n gt: '>',\n amp: '&',\n '#32': ' ',\n '#9': '\\t',\n};\n\n/**\n * A sent text in comparable form: every backslash dropped (the draft's\n * escapes, and the `\\` before a hard break's newline, are backslashes).\n */\nconst comparableText = (text: string): string => text.replace(/\\\\/g, '');\n\n/**\n * A draft in comparable form: every backslash dropped, then the character\n * references the draft serializer writes decoded in one pass (`<` and\n * `>` for typed `<` and `>`, `&` for a typed `&` that starts a\n * reference, so typed `<` is `&lt;`, and ` ` / `	` for the space\n * or tab a line starts with, which markdown would otherwise drop).\n */\nconst comparableDraft = (markdown: string): string =>\n comparableText(markdown).replace(\n /&(lt|gt|amp|#32|#9);/g,\n (reference, name: string) => DRAFT_CHARACTER_REFERENCES[name] ?? reference\n );\n\n/**\n * Escaping at most turns one character into four (`<` → `<`). A line's\n * first space becomes five (` `), but only once a line, so a whole line\n * with its line break stays under four a character; the slack covers short\n * texts. agora caps a stored draft the same way.\n */\nconst MAX_EXPANSION = 4;\nconst EXPANSION_SLACK_CHARS = 1024;\n\n/**\n * Whether `markdown` is the draft of `text`: no longer than escaping could make\n * it, and equal to it once backslashes are dropped and the draft's character\n * references decoded. A draft that would show other\n * words than the text the model read (another message's, a client's mistake) is\n * not taken; such a message renders its text as before.\n */\nexport function isComposerMarkdownOfText({\n markdown,\n text,\n}: {\n markdown: string;\n text: string;\n}): boolean {\n return (\n markdown.length <= text.length * MAX_EXPANSION + EXPANSION_SLACK_CHARS &&\n comparableDraft(markdown) === comparableText(text)\n );\n}\n\n/** The references a draft writes a line's first space or tab as. */\nconst DRAFT_WHITESPACE_REFERENCES: readonly string[] = [' ', '	'];\n\nconst isWhitespace = (character: string): boolean => /\\s/.test(character);\n\n/** A hard break in a draft: `\\` before the newline (the text holds the newline alone). */\nconst DRAFT_HARD_BREAK = '\\\\\\n';\n\n/** Whether an odd run of backslashes ends at `end`: its last one escapes what follows, not a typed `\\` (`\\\\`). */\nfunction endsInEscapingBackslash({\n markdown,\n start,\n end,\n}: {\n markdown: string;\n start: number;\n end: number;\n}): boolean {\n let backslashes = 0;\n while (end - backslashes > start && markdown.charAt(end - backslashes - 1) === '\\\\') {\n backslashes += 1;\n }\n return backslashes % 2 === 1;\n}\n\n/**\n * `markdown`, a draft, trimmed as its text is trimmed (`text.trim()`): a\n * send that trims its text stays a draft of it. `markdown.trim()` would keep\n * the ` ` a draft writes for the space its first line starts with, and the\n * `\\` of a line break whose newline it trims.\n */\nexport function trimComposerDraft(markdown: string): string {\n let start = 0;\n let end = markdown.length;\n for (;;) {\n while (start < end && isWhitespace(markdown.charAt(start))) start += 1;\n const reference = [...DRAFT_WHITESPACE_REFERENCES, DRAFT_HARD_BREAK].find(\n (candidate) => start + candidate.length <= end && markdown.startsWith(candidate, start)\n );\n if (reference === undefined) break;\n start += reference.length;\n }\n for (;;) {\n while (end > start && isWhitespace(markdown.charAt(end - 1))) end -= 1;\n const reference = DRAFT_WHITESPACE_REFERENCES.find(\n (candidate) => end - candidate.length >= start && markdown.endsWith(candidate, end)\n );\n if (reference !== undefined) {\n end -= reference.length;\n } else if (\n markdown.charAt(end) === '\\n' &&\n endsInEscapingBackslash({ markdown, start, end })\n ) {\n // The newline just trimmed was a line break's: its `\\` goes with it.\n end -= 1;\n } else {\n break;\n }\n }\n return markdown.slice(start, end);\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/**\n * The composer markdown to render or load for a message whose metadata is\n * `metadata` (a message's `metadata.custom`, or a lane entry's `metadata`) and\n * whose text is `text`; `null` when it carries none, or one that is not a\n * draft of `text`.\n */\nexport function readDeepAgentComposerMarkdown({\n metadata,\n text,\n}: {\n metadata: unknown;\n text: string;\n}): string | null {\n if (!isRecord(metadata)) return null;\n const markdown: unknown = metadata[DEEP_AGENT_COMPOSER_MARKDOWN_KEY];\n return typeof markdown === 'string' && isComposerMarkdownOfText({ markdown, text })\n ? markdown\n : null;\n}\n\n/**\n * How long a staged composer markdown waits for its submission\n * ({@link stageComposerMarkdown}).\n */\nexport const STAGED_COMPOSER_MARKDOWN_TTL_MS = 10_000;\n\ninterface StagedComposerMarkdown {\n readonly markdown: string;\n readonly stagedAt: number;\n}\n\n/**\n * The staged drafts live on `globalThis`, not in module scope, because two\n * copies of this module run in one page: the SDK bundles agent-runtime into its\n * dist, so its composer stages through the SDK's copy, while the Chrome\n * extension and the Office add-in build their runtime on agent-runtime directly\n * and take the draft through their own (see `asset-attachment.ts`).\n */\nconst STAGED_COMPOSER_MARKDOWN = Symbol.for('@athenaintel/agent-runtime/staged-composer-markdown');\n\ntype StagedComposerMarkdownHost = typeof globalThis & {\n [STAGED_COMPOSER_MARKDOWN]?: Map<string, StagedComposerMarkdown>;\n};\n\nfunction stagedComposerMarkdownByThread(): Map<string, StagedComposerMarkdown> {\n const host = globalThis as StagedComposerMarkdownHost;\n return (host[STAGED_COMPOSER_MARKDOWN] ??= new Map());\n}\n\n/**\n * Stage the draft `markdown` of `text` for `threadId`'s next submission.\n *\n * statewire captures message metadata once per new user message\n * (`getMessageMetadata`, patched into `@assistant-ui/react-statewire@0.33.0`)\n * without saying which message it is for, so a composer stages its draft right\n * before it sends and the runtime's getter takes it for the submission that\n * follows ({@link withStagedComposerMarkdown}). A draft equal to its text adds\n * nothing and clears the slot. A slot nobody takes within\n * {@link STAGED_COMPOSER_MARKDOWN_TTL_MS} expires; one a submission the\n * composer did not make takes is harmless, since a composer markdown that is\n * not a draft of the message's own text is neither kept by agora nor rendered.\n */\nexport function stageComposerMarkdown({\n threadId,\n text,\n markdown,\n now = Date.now(),\n}: {\n threadId: string;\n text: string;\n markdown: string;\n /** Test seam: the time of the send. */\n now?: number;\n}): void {\n const staged = stagedComposerMarkdownByThread();\n if (markdown === text) {\n staged.delete(threadId);\n return;\n }\n staged.set(threadId, { markdown, stagedAt: now });\n}\n\n/**\n * The message metadata for `threadId`'s submission now being journaled: the\n * staged composer markdown, if one is waiting and fresh. Takes the slot.\n */\nexport function takeStagedComposerMarkdownMetadata(\n threadId: string,\n now: number = Date.now()\n): Record<string, unknown> | undefined {\n const staged = stagedComposerMarkdownByThread();\n const entry = staged.get(threadId);\n staged.delete(threadId);\n if (entry === undefined || now - entry.stagedAt > STAGED_COMPOSER_MARKDOWN_TTL_MS) {\n return undefined;\n }\n return { [DEEP_AGENT_COMPOSER_MARKDOWN_KEY]: entry.markdown };\n}\n\ntype MessageMetadataGetter = () =>\n | Record<string, unknown>\n | undefined\n | Promise<Record<string, unknown> | undefined>;\n\n/**\n * A runtime's `getMessageMetadata` that also carries the composer markdown a\n * composer staged for `threadId` ({@link stageComposerMarkdown}), on top of the\n * host's own metadata (`getMessageMetadata`, when it has one). The slot is\n * taken synchronously at submission, before the host's capture resolves, so a\n * draft never rides a later message. With nothing staged the host's own value\n * is returned as is.\n */\nexport function withStagedComposerMarkdown({\n threadId,\n getMessageMetadata,\n}: {\n threadId: string;\n getMessageMetadata?: MessageMetadataGetter | undefined;\n}): MessageMetadataGetter {\n return () => {\n const staged = takeStagedComposerMarkdownMetadata(threadId);\n const captured = getMessageMetadata?.();\n if (staged === undefined) return captured;\n const merge = (host: Record<string, unknown> | undefined): Record<string, unknown> => ({\n ...host,\n ...staged,\n });\n return captured instanceof Promise ? captured.then(merge) : merge(captured);\n };\n}\n\n/** Test seam: drop every staged composer markdown. */\nexport function resetStagedComposerMarkdown(): void {\n stagedComposerMarkdownByThread().clear();\n}\n\n/**\n * `metadata` with the composer markdown set to the draft `markdown` of `text`,\n * or without it when the draft equals the text (it adds nothing then).\n * Returns `undefined` when nothing is left.\n */\nexport function withDeepAgentComposerMarkdown({\n metadata,\n text,\n markdown,\n}: {\n metadata: Readonly<Record<string, unknown>> | undefined;\n text: string;\n markdown: string;\n}): Record<string, unknown> | undefined {\n const { [DEEP_AGENT_COMPOSER_MARKDOWN_KEY]: _previous, ...rest } = metadata ?? {};\n const next: Record<string, unknown> =\n markdown === text ? rest : { ...rest, [DEEP_AGENT_COMPOSER_MARKDOWN_KEY]: markdown };\n return Object.keys(next).length > 0 ? next : undefined;\n}\n"],"names":[],"mappings":";;AAuBO,MAAM,mCAAmC;AAEhD,MAAM,6BAA+D;AAAA,EACnE,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,KAAK;AAAA,EACL,OAAO;AAAA,EACP,MAAM;AACR;AAMA,MAAM,iBAAiB,CAAC,SAAyB,KAAK,QAAQ,OAAO,EAAE;AASvE,MAAM,kBAAkB,CAAC,aACvB,eAAe,QAAQ,EAAE;AAAA,EACvB;AAAA,EACA,CAAC,WAAW,SAAiB,2BAA2B,IAAI,KAAK;AACnE;AAQF,MAAM,gBAAgB;AACtB,MAAM,wBAAwB;AASvB,SAAS,yBAAyB;AAAA,EACvC;AAAA,EACA;AACF,GAGY;AACV,SACE,SAAS,UAAU,KAAK,SAAS,gBAAgB,yBACjD,gBAAgB,QAAQ,MAAM,eAAe,IAAI;AAErD;AAGA,MAAM,8BAAiD,CAAC,SAAS,MAAM;AAEvE,MAAM,eAAe,CAAC,cAA+B,KAAK,KAAK,SAAS;AAGxE,MAAM,mBAAmB;AAGzB,SAAS,wBAAwB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AACF,GAIY;AACV,MAAI,cAAc;AAClB,SAAO,MAAM,cAAc,SAAS,SAAS,OAAO,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,iCAAsE;AAC7E,QAAM,OAAO;AACb,SAAQ,oEAAmC,oBAAI,IAAA;AACjD;AAeO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA,MAAM,KAAK,IAAA;AACb,GAMS;AACP,QAAM,SAAS,+BAAA;AACf,MAAI,aAAa,MAAM;AACrB,WAAO,OAAO,QAAQ;AACtB;AAAA,EACF;AACA,SAAO,IAAI,UAAU,EAAE,UAAU,UAAU,KAAK;AAClD;AAMO,SAAS,mCACd,UACA,MAAc,KAAK,OACkB;AACrC,QAAM,SAAS,+BAAA;AACf,QAAM,QAAQ,OAAO,IAAI,QAAQ;AACjC,SAAO,OAAO,QAAQ;AACtB,MAAI,UAAU,UAAa,MAAM,MAAM,WAAW,iCAAiC;AACjF,WAAO;AAAA,EACT;AACA,SAAO,EAAE,CAAC,gCAAgC,GAAG,MAAM,SAAA;AACrD;AA4CO,SAAS,8BAA8B;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AACF,GAIwC;AACtC,QAAM,EAAE,CAAC,gCAAgC,GAAG,WAAW,GAAG,KAAA,IAAS,YAAY,CAAA;AAC/E,QAAM,OACJ,aAAa,OAAO,OAAO,EAAE,GAAG,MAAM,CAAC,gCAAgC,GAAG,SAAA;AAC5E,SAAO,OAAO,KAAK,IAAI,EAAE,SAAS,IAAI,OAAO;AAC/C;;;;;;;;;"}
|
|
@@ -96,21 +96,6 @@ function takeStagedComposerMarkdownMetadata(threadId, now = Date.now()) {
|
|
|
96
96
|
}
|
|
97
97
|
return { [DEEP_AGENT_COMPOSER_MARKDOWN_KEY]: entry.markdown };
|
|
98
98
|
}
|
|
99
|
-
function withStagedComposerMarkdown({
|
|
100
|
-
threadId,
|
|
101
|
-
getMessageMetadata
|
|
102
|
-
}) {
|
|
103
|
-
return () => {
|
|
104
|
-
const staged = takeStagedComposerMarkdownMetadata(threadId);
|
|
105
|
-
const captured = getMessageMetadata == null ? void 0 : getMessageMetadata();
|
|
106
|
-
if (staged === void 0) return captured;
|
|
107
|
-
const merge = (host) => ({
|
|
108
|
-
...host,
|
|
109
|
-
...staged
|
|
110
|
-
});
|
|
111
|
-
return captured instanceof Promise ? captured.then(merge) : merge(captured);
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
99
|
function withDeepAgentComposerMarkdown({
|
|
115
100
|
metadata,
|
|
116
101
|
text,
|
|
@@ -128,7 +113,6 @@ export {
|
|
|
128
113
|
stageComposerMarkdown,
|
|
129
114
|
takeStagedComposerMarkdownMetadata,
|
|
130
115
|
trimComposerDraft,
|
|
131
|
-
withDeepAgentComposerMarkdown
|
|
132
|
-
withStagedComposerMarkdown
|
|
116
|
+
withDeepAgentComposerMarkdown
|
|
133
117
|
};
|
|
134
118
|
//# sourceMappingURL=composer-markdown.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"composer-markdown.js","sources":["../../../../agent-runtime/src/composer-markdown.ts"],"sourcesContent":["/**\n * The composer markdown a chat message was sent from.\n *\n * The chat composer sends a message's plain text exactly as typed, because the\n * model reads the text literally, and writes real formatting (bold, lists,\n * code, mention chips) as markdown. The sent text alone no longer says which\n * characters are formatting and which were typed: literal `**strong**` and\n * bold `strong` both send `**strong**`, and `List<T>`, `a\\\\b` or `2*3*4` read\n * as markup when the text is rendered as markdown. So the composer also\n * attaches the draft the text was serialized from (the same document with its\n * plain text escaped for markdown) under {@link DEEP_AGENT_COMPOSER_MARKDOWN_KEY}\n * in the message's metadata, and only when the two differ.\n *\n * It rides the statewire message, the queue and steer lanes and the persisted\n * HumanMessage (`additional_kwargs.metadata`, which the converter surfaces as\n * `metadata.custom`). It is display-only: the bubble renders it, and Edit,\n * branch-and-edit and a withdrawn turn load it back into the composer. The\n * model reads the message text, never this. A message without it (older\n * messages, other clients) renders its text as before.\n *\n * agora validates it with the same rule\n * (`agora/graphs/athena_deep_agent/composer_markdown.py`).\n */\nexport const DEEP_AGENT_COMPOSER_MARKDOWN_KEY = 'composer_markdown';\n\nconst DRAFT_CHARACTER_REFERENCES: Readonly<Record<string, string>> = {\n lt: '<',\n gt: '>',\n amp: '&',\n '#32': ' ',\n '#9': '\\t',\n};\n\n/**\n * A sent text in comparable form: every backslash dropped (the draft's\n * escapes, and the `\\` before a hard break's newline, are backslashes).\n */\nconst comparableText = (text: string): string => text.replace(/\\\\/g, '');\n\n/**\n * A draft in comparable form: every backslash dropped, then the character\n * references the draft serializer writes decoded in one pass (`<` and\n * `>` for typed `<` and `>`, `&` for a typed `&` that starts a\n * reference, so typed `<` is `&lt;`, and ` ` / `	` for the space\n * or tab a line starts with, which markdown would otherwise drop).\n */\nconst comparableDraft = (markdown: string): string =>\n comparableText(markdown).replace(\n /&(lt|gt|amp|#32|#9);/g,\n (reference, name: string) => DRAFT_CHARACTER_REFERENCES[name] ?? reference\n );\n\n/**\n * Escaping at most turns one character into four (`<` → `<`). A line's\n * first space becomes five (` `), but only once a line, so a whole line\n * with its line break stays under four a character; the slack covers short\n * texts. agora caps a stored draft the same way.\n */\nconst MAX_EXPANSION = 4;\nconst EXPANSION_SLACK_CHARS = 1024;\n\n/**\n * Whether `markdown` is the draft of `text`: no longer than escaping could make\n * it, and equal to it once backslashes are dropped and the draft's character\n * references decoded. A draft that would show other\n * words than the text the model read (another message's, a client's mistake) is\n * not taken; such a message renders its text as before.\n */\nexport function isComposerMarkdownOfText({\n markdown,\n text,\n}: {\n markdown: string;\n text: string;\n}): boolean {\n return (\n markdown.length <= text.length * MAX_EXPANSION + EXPANSION_SLACK_CHARS &&\n comparableDraft(markdown) === comparableText(text)\n );\n}\n\n/** The references a draft writes a line's first space or tab as. */\nconst DRAFT_WHITESPACE_REFERENCES: readonly string[] = [' ', '	'];\n\nconst isWhitespace = (character: string): boolean => /\\s/.test(character);\n\n/** A hard break in a draft: `\\` before the newline (the text holds the newline alone). */\nconst DRAFT_HARD_BREAK = '\\\\\\n';\n\n/** Whether an odd run of backslashes ends at `end`: its last one escapes what follows, not a typed `\\` (`\\\\`). */\nfunction endsInEscapingBackslash({\n markdown,\n start,\n end,\n}: {\n markdown: string;\n start: number;\n end: number;\n}): boolean {\n let backslashes = 0;\n while (end - backslashes > start && markdown.charAt(end - backslashes - 1) === '\\\\') {\n backslashes += 1;\n }\n return backslashes % 2 === 1;\n}\n\n/**\n * `markdown`, a draft, trimmed as its text is trimmed (`text.trim()`): a\n * send that trims its text stays a draft of it. `markdown.trim()` would keep\n * the ` ` a draft writes for the space its first line starts with, and the\n * `\\` of a line break whose newline it trims.\n */\nexport function trimComposerDraft(markdown: string): string {\n let start = 0;\n let end = markdown.length;\n for (;;) {\n while (start < end && isWhitespace(markdown.charAt(start))) start += 1;\n const reference = [...DRAFT_WHITESPACE_REFERENCES, DRAFT_HARD_BREAK].find(\n (candidate) => start + candidate.length <= end && markdown.startsWith(candidate, start)\n );\n if (reference === undefined) break;\n start += reference.length;\n }\n for (;;) {\n while (end > start && isWhitespace(markdown.charAt(end - 1))) end -= 1;\n const reference = DRAFT_WHITESPACE_REFERENCES.find(\n (candidate) => end - candidate.length >= start && markdown.endsWith(candidate, end)\n );\n if (reference !== undefined) {\n end -= reference.length;\n } else if (\n markdown.charAt(end) === '\\n' &&\n endsInEscapingBackslash({ markdown, start, end })\n ) {\n // The newline just trimmed was a line break's: its `\\` goes with it.\n end -= 1;\n } else {\n break;\n }\n }\n return markdown.slice(start, end);\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/**\n * The composer markdown to render or load for a message whose metadata is\n * `metadata` (a message's `metadata.custom`, or a lane entry's `metadata`) and\n * whose text is `text`; `null` when it carries none, or one that is not a\n * draft of `text`.\n */\nexport function readDeepAgentComposerMarkdown({\n metadata,\n text,\n}: {\n metadata: unknown;\n text: string;\n}): string | null {\n if (!isRecord(metadata)) return null;\n const markdown: unknown = metadata[DEEP_AGENT_COMPOSER_MARKDOWN_KEY];\n return typeof markdown === 'string' && isComposerMarkdownOfText({ markdown, text })\n ? markdown\n : null;\n}\n\n/**\n * How long a staged composer markdown waits for its submission\n * ({@link stageComposerMarkdown}).\n */\nexport const STAGED_COMPOSER_MARKDOWN_TTL_MS = 10_000;\n\ninterface StagedComposerMarkdown {\n readonly markdown: string;\n readonly stagedAt: number;\n}\n\n/**\n * The staged drafts live on `globalThis`, not in module scope, because two\n * copies of this module run in one page: the SDK bundles agent-runtime into its\n * dist, so its composer stages through the SDK's copy, while the Chrome\n * extension and the Office add-in build their runtime on agent-runtime directly\n * and take the draft through their own (see `asset-attachment.ts`).\n */\nconst STAGED_COMPOSER_MARKDOWN = Symbol.for('@athenaintel/agent-runtime/staged-composer-markdown');\n\ntype StagedComposerMarkdownHost = typeof globalThis & {\n [STAGED_COMPOSER_MARKDOWN]?: Map<string, StagedComposerMarkdown>;\n};\n\nfunction stagedComposerMarkdownByThread(): Map<string, StagedComposerMarkdown> {\n const host = globalThis as StagedComposerMarkdownHost;\n return (host[STAGED_COMPOSER_MARKDOWN] ??= new Map());\n}\n\n/**\n * Stage the draft `markdown` of `text` for `threadId`'s next submission.\n *\n * statewire captures message metadata once per new user message\n * (`getMessageMetadata`, patched into `@assistant-ui/react-statewire@0.33.0`)\n * without saying which message it is for, so a composer stages its draft right\n * before it sends and the runtime's getter takes it for the submission that\n * follows ({@link withStagedComposerMarkdown}). A draft equal to its text adds\n * nothing and clears the slot. A slot nobody takes within\n * {@link STAGED_COMPOSER_MARKDOWN_TTL_MS} expires; one a submission the\n * composer did not make takes is harmless, since a composer markdown that is\n * not a draft of the message's own text is neither kept by agora nor rendered.\n */\nexport function stageComposerMarkdown({\n threadId,\n text,\n markdown,\n now = Date.now(),\n}: {\n threadId: string;\n text: string;\n markdown: string;\n /** Test seam: the time of the send. */\n now?: number;\n}): void {\n const staged = stagedComposerMarkdownByThread();\n if (markdown === text) {\n staged.delete(threadId);\n return;\n }\n staged.set(threadId, { markdown, stagedAt: now });\n}\n\n/**\n * The message metadata for `threadId`'s submission now being journaled: the\n * staged composer markdown, if one is waiting and fresh. Takes the slot.\n */\nexport function takeStagedComposerMarkdownMetadata(\n threadId: string,\n now: number = Date.now()\n): Record<string, unknown> | undefined {\n const staged = stagedComposerMarkdownByThread();\n const entry = staged.get(threadId);\n staged.delete(threadId);\n if (entry === undefined || now - entry.stagedAt > STAGED_COMPOSER_MARKDOWN_TTL_MS) {\n return undefined;\n }\n return { [DEEP_AGENT_COMPOSER_MARKDOWN_KEY]: entry.markdown };\n}\n\ntype MessageMetadataGetter = () =>\n | Record<string, unknown>\n | undefined\n | Promise<Record<string, unknown> | undefined>;\n\n/**\n * A runtime's `getMessageMetadata` that also carries the composer markdown a\n * composer staged for `threadId` ({@link stageComposerMarkdown}), on top of the\n * host's own metadata (`getMessageMetadata`, when it has one). The slot is\n * taken synchronously at submission, before the host's capture resolves, so a\n * draft never rides a later message. With nothing staged the host's own value\n * is returned as is.\n */\nexport function withStagedComposerMarkdown({\n threadId,\n getMessageMetadata,\n}: {\n threadId: string;\n getMessageMetadata?: MessageMetadataGetter | undefined;\n}): MessageMetadataGetter {\n return () => {\n const staged = takeStagedComposerMarkdownMetadata(threadId);\n const captured = getMessageMetadata?.();\n if (staged === undefined) return captured;\n const merge = (host: Record<string, unknown> | undefined): Record<string, unknown> => ({\n ...host,\n ...staged,\n });\n return captured instanceof Promise ? captured.then(merge) : merge(captured);\n };\n}\n\n/** Test seam: drop every staged composer markdown. */\nexport function resetStagedComposerMarkdown(): void {\n stagedComposerMarkdownByThread().clear();\n}\n\n/**\n * `metadata` with the composer markdown set to the draft `markdown` of `text`,\n * or without it when the draft equals the text (it adds nothing then).\n * Returns `undefined` when nothing is left.\n */\nexport function withDeepAgentComposerMarkdown({\n metadata,\n text,\n markdown,\n}: {\n metadata: Readonly<Record<string, unknown>> | undefined;\n text: string;\n markdown: string;\n}): Record<string, unknown> | undefined {\n const { [DEEP_AGENT_COMPOSER_MARKDOWN_KEY]: _previous, ...rest } = metadata ?? {};\n const next: Record<string, unknown> =\n markdown === text ? rest : { ...rest, [DEEP_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jC,SAAO,OAAO,QAAQ;AACtB,MAAI,UAAU,UAAa,MAAM,MAAM,WAAW,iCAAiC;AACjF,WAAO;AAAA,EACT;AACA,SAAO,EAAE,CAAC,gCAAgC,GAAG,MAAM,SAAA;AACrD;AAeO,SAAS,2BAA2B;AAAA,EACzC;AAAA,EACA;AACF,GAG0B;AACxB,SAAO,MAAM;AACX,UAAM,SAAS,mCAAmC,QAAQ;AAC1D,UAAM,WAAW;AACjB,QAAI,WAAW,OAAW,QAAO;AACjC,UAAM,QAAQ,CAAC,UAAwE;AAAA,MACrF,GAAG;AAAA,MACH,GAAG;AAAA,IAAA;AAEL,WAAO,oBAAoB,UAAU,SAAS,KAAK,KAAK,IAAI,MAAM,QAAQ;AAAA,EAC5E;AACF;AAYO,SAAS,8BAA8B;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AACF,GAIwC;AACtC,QAAM,EAAE,CAAC,gCAAgC,GAAG,WAAW,GAAG,KAAA,IAAS,YAAY,CAAA;AAC/E,QAAM,OACJ,aAAa,OAAO,OAAO,EAAE,GAAG,MAAM,CAAC,gCAAgC,GAAG,SAAA;AAC5E,SAAO,OAAO,KAAK,IAAI,EAAE,SAAS,IAAI,OAAO;AAC/C;"}
|
|
1
|
+
{"version":3,"file":"composer-markdown.js","sources":["../../../../agent-runtime/src/composer-markdown.ts"],"sourcesContent":["/**\n * The composer markdown a chat message was sent from.\n *\n * The chat composer sends a message's plain text exactly as typed, because the\n * model reads the text literally, and writes real formatting (bold, lists,\n * code, mention chips) as markdown. The sent text alone no longer says which\n * characters are formatting and which were typed: literal `**strong**` and\n * bold `strong` both send `**strong**`, and `List<T>`, `a\\\\b` or `2*3*4` read\n * as markup when the text is rendered as markdown. So the composer also\n * attaches the draft the text was serialized from (the same document with its\n * plain text escaped for markdown) under {@link DEEP_AGENT_COMPOSER_MARKDOWN_KEY}\n * in the message's metadata, and only when the two differ.\n *\n * It rides the statewire message, the queue and steer lanes and the persisted\n * HumanMessage (`additional_kwargs.metadata`, which the converter surfaces as\n * `metadata.custom`). It is display-only: the bubble renders it, and Edit,\n * branch-and-edit and a withdrawn turn load it back into the composer. The\n * model reads the message text, never this. A message without it (older\n * messages, other clients) renders its text as before.\n *\n * agora validates it with the same rule\n * (`agora/graphs/athena_deep_agent/composer_markdown.py`).\n */\nexport const DEEP_AGENT_COMPOSER_MARKDOWN_KEY = 'composer_markdown';\n\nconst DRAFT_CHARACTER_REFERENCES: Readonly<Record<string, string>> = {\n lt: '<',\n gt: '>',\n amp: '&',\n '#32': ' ',\n '#9': '\\t',\n};\n\n/**\n * A sent text in comparable form: every backslash dropped (the draft's\n * escapes, and the `\\` before a hard break's newline, are backslashes).\n */\nconst comparableText = (text: string): string => text.replace(/\\\\/g, '');\n\n/**\n * A draft in comparable form: every backslash dropped, then the character\n * references the draft serializer writes decoded in one pass (`<` and\n * `>` for typed `<` and `>`, `&` for a typed `&` that starts a\n * reference, so typed `<` is `&lt;`, and ` ` / `	` for the space\n * or tab a line starts with, which markdown would otherwise drop).\n */\nconst comparableDraft = (markdown: string): string =>\n comparableText(markdown).replace(\n /&(lt|gt|amp|#32|#9);/g,\n (reference, name: string) => DRAFT_CHARACTER_REFERENCES[name] ?? reference\n );\n\n/**\n * Escaping at most turns one character into four (`<` → `<`). A line's\n * first space becomes five (` `), but only once a line, so a whole line\n * with its line break stays under four a character; the slack covers short\n * texts. agora caps a stored draft the same way.\n */\nconst MAX_EXPANSION = 4;\nconst EXPANSION_SLACK_CHARS = 1024;\n\n/**\n * Whether `markdown` is the draft of `text`: no longer than escaping could make\n * it, and equal to it once backslashes are dropped and the draft's character\n * references decoded. A draft that would show other\n * words than the text the model read (another message's, a client's mistake) is\n * not taken; such a message renders its text as before.\n */\nexport function isComposerMarkdownOfText({\n markdown,\n text,\n}: {\n markdown: string;\n text: string;\n}): boolean {\n return (\n markdown.length <= text.length * MAX_EXPANSION + EXPANSION_SLACK_CHARS &&\n comparableDraft(markdown) === comparableText(text)\n );\n}\n\n/** The references a draft writes a line's first space or tab as. */\nconst DRAFT_WHITESPACE_REFERENCES: readonly string[] = [' ', '	'];\n\nconst isWhitespace = (character: string): boolean => /\\s/.test(character);\n\n/** A hard break in a draft: `\\` before the newline (the text holds the newline alone). */\nconst DRAFT_HARD_BREAK = '\\\\\\n';\n\n/** Whether an odd run of backslashes ends at `end`: its last one escapes what follows, not a typed `\\` (`\\\\`). */\nfunction endsInEscapingBackslash({\n markdown,\n start,\n end,\n}: {\n markdown: string;\n start: number;\n end: number;\n}): boolean {\n let backslashes = 0;\n while (end - backslashes > start && markdown.charAt(end - backslashes - 1) === '\\\\') {\n backslashes += 1;\n }\n return backslashes % 2 === 1;\n}\n\n/**\n * `markdown`, a draft, trimmed as its text is trimmed (`text.trim()`): a\n * send that trims its text stays a draft of it. `markdown.trim()` would keep\n * the ` ` a draft writes for the space its first line starts with, and the\n * `\\` of a line break whose newline it trims.\n */\nexport function trimComposerDraft(markdown: string): string {\n let start = 0;\n let end = markdown.length;\n for (;;) {\n while (start < end && isWhitespace(markdown.charAt(start))) start += 1;\n const reference = [...DRAFT_WHITESPACE_REFERENCES, DRAFT_HARD_BREAK].find(\n (candidate) => start + candidate.length <= end && markdown.startsWith(candidate, start)\n );\n if (reference === undefined) break;\n start += reference.length;\n }\n for (;;) {\n while (end > start && isWhitespace(markdown.charAt(end - 1))) end -= 1;\n const reference = DRAFT_WHITESPACE_REFERENCES.find(\n (candidate) => end - candidate.length >= start && markdown.endsWith(candidate, end)\n );\n if (reference !== undefined) {\n end -= reference.length;\n } else if (\n markdown.charAt(end) === '\\n' &&\n endsInEscapingBackslash({ markdown, start, end })\n ) {\n // The newline just trimmed was a line break's: its `\\` goes with it.\n end -= 1;\n } else {\n break;\n }\n }\n return markdown.slice(start, end);\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/**\n * The composer markdown to render or load for a message whose metadata is\n * `metadata` (a message's `metadata.custom`, or a lane entry's `metadata`) and\n * whose text is `text`; `null` when it carries none, or one that is not a\n * draft of `text`.\n */\nexport function readDeepAgentComposerMarkdown({\n metadata,\n text,\n}: {\n metadata: unknown;\n text: string;\n}): string | null {\n if (!isRecord(metadata)) return null;\n const markdown: unknown = metadata[DEEP_AGENT_COMPOSER_MARKDOWN_KEY];\n return typeof markdown === 'string' && isComposerMarkdownOfText({ markdown, text })\n ? markdown\n : null;\n}\n\n/**\n * How long a staged composer markdown waits for its submission\n * ({@link stageComposerMarkdown}).\n */\nexport const STAGED_COMPOSER_MARKDOWN_TTL_MS = 10_000;\n\ninterface StagedComposerMarkdown {\n readonly markdown: string;\n readonly stagedAt: number;\n}\n\n/**\n * The staged drafts live on `globalThis`, not in module scope, because two\n * copies of this module run in one page: the SDK bundles agent-runtime into its\n * dist, so its composer stages through the SDK's copy, while the Chrome\n * extension and the Office add-in build their runtime on agent-runtime directly\n * and take the draft through their own (see `asset-attachment.ts`).\n */\nconst STAGED_COMPOSER_MARKDOWN = Symbol.for('@athenaintel/agent-runtime/staged-composer-markdown');\n\ntype StagedComposerMarkdownHost = typeof globalThis & {\n [STAGED_COMPOSER_MARKDOWN]?: Map<string, StagedComposerMarkdown>;\n};\n\nfunction stagedComposerMarkdownByThread(): Map<string, StagedComposerMarkdown> {\n const host = globalThis as StagedComposerMarkdownHost;\n return (host[STAGED_COMPOSER_MARKDOWN] ??= new Map());\n}\n\n/**\n * Stage the draft `markdown` of `text` for `threadId`'s next submission.\n *\n * statewire captures message metadata once per new user message\n * (`getMessageMetadata`, patched into `@assistant-ui/react-statewire@0.33.0`)\n * without saying which message it is for, so a composer stages its draft right\n * before it sends and the runtime's getter takes it for the submission that\n * follows ({@link withStagedComposerMarkdown}). A draft equal to its text adds\n * nothing and clears the slot. A slot nobody takes within\n * {@link STAGED_COMPOSER_MARKDOWN_TTL_MS} expires; one a submission the\n * composer did not make takes is harmless, since a composer markdown that is\n * not a draft of the message's own text is neither kept by agora nor rendered.\n */\nexport function stageComposerMarkdown({\n threadId,\n text,\n markdown,\n now = Date.now(),\n}: {\n threadId: string;\n text: string;\n markdown: string;\n /** Test seam: the time of the send. */\n now?: number;\n}): void {\n const staged = stagedComposerMarkdownByThread();\n if (markdown === text) {\n staged.delete(threadId);\n return;\n }\n staged.set(threadId, { markdown, stagedAt: now });\n}\n\n/**\n * The message metadata for `threadId`'s submission now being journaled: the\n * staged composer markdown, if one is waiting and fresh. Takes the slot.\n */\nexport function takeStagedComposerMarkdownMetadata(\n threadId: string,\n now: number = Date.now()\n): Record<string, unknown> | undefined {\n const staged = stagedComposerMarkdownByThread();\n const entry = staged.get(threadId);\n staged.delete(threadId);\n if (entry === undefined || now - entry.stagedAt > STAGED_COMPOSER_MARKDOWN_TTL_MS) {\n return undefined;\n }\n return { [DEEP_AGENT_COMPOSER_MARKDOWN_KEY]: entry.markdown };\n}\n\ntype MessageMetadataGetter = () =>\n | Record<string, unknown>\n | undefined\n | Promise<Record<string, unknown> | undefined>;\n\n/**\n * A runtime's `getMessageMetadata` that also carries the composer markdown a\n * composer staged for `threadId` ({@link stageComposerMarkdown}), on top of the\n * host's own metadata (`getMessageMetadata`, when it has one). The slot is\n * taken synchronously at submission, before the host's capture resolves, so a\n * draft never rides a later message. With nothing staged the host's own value\n * is returned as is.\n */\nexport function withStagedComposerMarkdown({\n threadId,\n getMessageMetadata,\n}: {\n threadId: string;\n getMessageMetadata?: MessageMetadataGetter | undefined;\n}): MessageMetadataGetter {\n return () => {\n const staged = takeStagedComposerMarkdownMetadata(threadId);\n const captured = getMessageMetadata?.();\n if (staged === undefined) return captured;\n const merge = (host: Record<string, unknown> | undefined): Record<string, unknown> => ({\n ...host,\n ...staged,\n });\n return captured instanceof Promise ? captured.then(merge) : merge(captured);\n };\n}\n\n/** Test seam: drop every staged composer markdown. */\nexport function resetStagedComposerMarkdown(): void {\n stagedComposerMarkdownByThread().clear();\n}\n\n/**\n * `metadata` with the composer markdown set to the draft `markdown` of `text`,\n * or without it when the draft equals the text (it adds nothing then).\n * Returns `undefined` when nothing is left.\n */\nexport function withDeepAgentComposerMarkdown({\n metadata,\n text,\n markdown,\n}: {\n metadata: Readonly<Record<string, unknown>> | undefined;\n text: string;\n markdown: string;\n}): Record<string, unknown> | undefined {\n const { [DEEP_AGENT_COMPOSER_MARKDOWN_KEY]: _previous, ...rest } = metadata ?? {};\n const next: Record<string, unknown> =\n markdown === text ? rest : { ...rest, [DEEP_AGENT_COMPOSER_MARKDOWN_KEY]: markdown };\n return Object.keys(next).length > 0 ? next : undefined;\n}\n"],"names":[],"mappings":"AAuBO,MAAM,mCAAmC;AAEhD,MAAM,6BAA+D;AAAA,EACnE,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,KAAK;AAAA,EACL,OAAO;AAAA,EACP,MAAM;AACR;AAMA,MAAM,iBAAiB,CAAC,SAAyB,KAAK,QAAQ,OAAO,EAAE;AASvE,MAAM,kBAAkB,CAAC,aACvB,eAAe,QAAQ,EAAE;AAAA,EACvB;AAAA,EACA,CAAC,WAAW,SAAiB,2BAA2B,IAAI,KAAK;AACnE;AAQF,MAAM,gBAAgB;AACtB,MAAM,wBAAwB;AASvB,SAAS,yBAAyB;AAAA,EACvC;AAAA,EACA;AACF,GAGY;AACV,SACE,SAAS,UAAU,KAAK,SAAS,gBAAgB,yBACjD,gBAAgB,QAAQ,MAAM,eAAe,IAAI;AAErD;AAGA,MAAM,8BAAiD,CAAC,SAAS,MAAM;AAEvE,MAAM,eAAe,CAAC,cAA+B,KAAK,KAAK,SAAS;AAGxE,MAAM,mBAAmB;AAGzB,SAAS,wBAAwB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AACF,GAIY;AACV,MAAI,cAAc;AAClB,SAAO,MAAM,cAAc,SAAS,SAAS,OAAO,MAAM,cAAc,CAAC,MAAM,MAAM;AACnF,mBAAe;AAAA,EACjB;AACA,SAAO,cAAc,MAAM;AAC7B;AAQO,SAAS,kBAAkB,UAA0B;AAC1D,MAAI,QAAQ;AACZ,MAAI,MAAM,SAAS;AACnB,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ACP,QAAM,SAAS,+BAAA;AACf,MAAI,aAAa,MAAM;AACrB,WAAO,OAAO,QAAQ;AACtB;AAAA,EACF;AACA,SAAO,IAAI,UAAU,EAAE,UAAU,UAAU,KAAK;AAClD;AAMO,SAAS,mCACd,UACA,MAAc,KAAK,OACkB;AACrC,QAAM,SAAS,+BAAA;AACf,QAAM,QAAQ,OAAO,IAAI,QAAQ;AACjC,SAAO,OAAO,QAAQ;AACtB,MAAI,UAAU,UAAa,MAAM,MAAM,WAAW,iCAAiC;AACjF,WAAO;AAAA,EACT;AACA,SAAO,EAAE,CAAC,gCAAgC,GAAG,MAAM,SAAA;AACrD;AA4CO,SAAS,8BAA8B;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AACF,GAIwC;AACtC,QAAM,EAAE,CAAC,gCAAgC,GAAG,WAAW,GAAG,KAAA,IAAS,YAAY,CAAA;AAC/E,QAAM,OACJ,aAAa,OAAO,OAAO,EAAE,GAAG,MAAM,CAAC,gCAAgC,GAAG,SAAA;AAC5E,SAAO,OAAO,KAAK,IAAI,EAAE,SAAS,IAAI,OAAO;AAC/C;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { useSyncExternalStore } from "react";
|
|
2
|
-
import {
|
|
2
|
+
import { withAddressedAgents, readAddressedAgents } from "./addressed-agents.js";
|
|
3
3
|
const MAX_DEEP_AGENT_NAMED_AGENTS = 8;
|
|
4
4
|
const OWN_ASSISTANT_AGENT_REF = "assistant";
|
|
5
5
|
const COLLAB_AGENT_REF_PREFIX = "collab_agent:";
|