@agents24/chat-react 0.5.44 → 0.5.45
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.
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"title": "Agents24 Chat",
|
|
6
6
|
"description": "Complete editable Agents24 chat, inheriting your application's theme.",
|
|
7
7
|
"dependencies": [
|
|
8
|
-
"@agents24/chat-react@0.5.
|
|
8
|
+
"@agents24/chat-react@0.5.45",
|
|
9
9
|
"@agents24/client@0.2.23",
|
|
10
10
|
"@agents24/react@0.2.29",
|
|
11
11
|
"@shadcn/react@^0.2.1",
|
|
@@ -254,13 +254,13 @@
|
|
|
254
254
|
}
|
|
255
255
|
],
|
|
256
256
|
"meta": {
|
|
257
|
-
"version": "0.5.
|
|
257
|
+
"version": "0.5.45",
|
|
258
258
|
"source": "packages/agents24-chat-react/scaffold",
|
|
259
259
|
"source_sha256": "411a13a78466b84a923ae81a16d1b032deb758e7f44c1df5915cfdff71df6d62",
|
|
260
260
|
"agents24": {
|
|
261
261
|
"@agents24/client": "0.2.23",
|
|
262
262
|
"@agents24/react": "0.2.29",
|
|
263
|
-
"@agents24/chat-react": "0.5.
|
|
263
|
+
"@agents24/chat-react": "0.5.45"
|
|
264
264
|
}
|
|
265
265
|
},
|
|
266
266
|
"docs": "Import the installed styles.css from your application stylesheet. Pass your configured AgentClient to Agents24ChatScaffold. Authentication and URLs remain host-owned. Installed UI is editable; review changes before reinstalling and do not use --overwrite on customized files."
|
package/dist/runtime/index.cjs
CHANGED
|
@@ -625,6 +625,7 @@ function useAgentChatRuntime(options) {
|
|
|
625
625
|
setIsSubmitting(true);
|
|
626
626
|
const request = (async () => {
|
|
627
627
|
try {
|
|
628
|
+
if (controller.activeThread?.read_only) throw new Error("This conversation is read-only. Start a new chat.");
|
|
628
629
|
await agentChangePromiseRef.current;
|
|
629
630
|
const activeBootstrap = bootstrapRef.current;
|
|
630
631
|
if (!activeBootstrap) throw new Error("The agent input contract is unavailable.");
|
|
@@ -659,7 +660,7 @@ function useAgentChatRuntime(options) {
|
|
|
659
660
|
};
|
|
660
661
|
void request.then(clearRequest, clearRequest);
|
|
661
662
|
return request;
|
|
662
|
-
}, [bootstrap, clearOperationError, controller.activeThreadId, controller.submit, refreshEffectivePolicy]);
|
|
663
|
+
}, [bootstrap, clearOperationError, controller.activeThreadId, controller.activeThread?.read_only, controller.submit, refreshEffectivePolicy]);
|
|
663
664
|
const { onHitlAction, getHitlActionState } = useAgentChatHitl({
|
|
664
665
|
client,
|
|
665
666
|
bootstrap,
|
|
@@ -685,7 +686,7 @@ function useAgentChatRuntime(options) {
|
|
|
685
686
|
const detail = await client.threads.get({ threadId });
|
|
686
687
|
if (requestGeneration !== threadSelectionGenerationRef.current) return;
|
|
687
688
|
const preferredAgentId = detail.runtime_selection?.agent_alias || detail.runtime_selection?.agent_id || null;
|
|
688
|
-
if (preferredAgentId) {
|
|
689
|
+
if (preferredAgentId && !detail.read_only) {
|
|
689
690
|
const result = await client.bootstrap({ agentId: preferredAgentId });
|
|
690
691
|
if (requestGeneration !== threadSelectionGenerationRef.current) return;
|
|
691
692
|
const resolvedAgentId = agentIdFromBootstrap(result, preferredAgentId);
|
|
@@ -796,7 +797,8 @@ function useAgentChatRuntime(options) {
|
|
|
796
797
|
return {
|
|
797
798
|
agent: agentOverride || { name: bootstrap?.deployment.name || "Agent" },
|
|
798
799
|
inputContract: bootstrap?.features.inputs || null,
|
|
799
|
-
allowFeedback: Boolean(bootstrap?.capabilities.includes("feedback.write")),
|
|
800
|
+
allowFeedback: Boolean(bootstrap?.capabilities.includes("feedback.write")) && !controller.activeThread?.read_only,
|
|
801
|
+
isReadOnly: controller.activeThread?.read_only === true,
|
|
800
802
|
backgroundError: bootstrap && bootstrapError || controller.backgroundError?.cause || null,
|
|
801
803
|
bootstrap,
|
|
802
804
|
capabilities: bootstrap?.capabilities || [],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/index.ts","../../src/runtime/use-agent-chat-runtime.ts","../../src/runtime/use-agent-chat-hitl.ts","../../src/mcp-oauth.ts","../../src/runtime/input-contract.ts","../../src/runtime/use-delegation-tasks.ts"],"sourcesContent":["export * from \"./use-agent-chat-runtime\";\nexport * from \"./input-contract\";\n\nexport * from \"./use-delegation-tasks\";\nexport type * from \"../generated/delegation-types\";\n","import type {\n AgentClient,\n Agents24ClientError,\n ClientBootstrap,\n EffectiveResourcePolicy,\n HitlResponse,\n PortableUpload,\n} from \"@agents24/client\";\nimport type { ContextCompression, ContextWindow } from \"@agents24/client/protocol\";\nimport {\n type AgentChatController,\n type ChatAttachment,\n type ChatHitlPart,\n type HitlSubmissionOptions,\n type HitlSubmissionState,\n useAgentAttachments,\n useAgentChat,\n} from \"@agents24/react\";\nimport * as React from \"react\";\n\nimport { useAgentChatHitl } from \"./use-agent-chat-hitl\";\nimport type { ChatMcpOauthCompletion } from \"../types\";\nimport { validateAgentChatSubmission } from \"./input-contract\";\n\nexport type AgentChatRuntimeAgent = {\n name: string;\n description?: string | null;\n handle?: string | null;\n avatarUrl?: string | null;\n};\n\nexport type AgentChatRuntimeModel = {\n id: string;\n label: string;\n};\n\nexport type AgentChatRuntimeAgentOption = { id: string; label: string };\n\nexport type AgentChatRuntimeViewState =\n | \"ready\"\n | \"loading\"\n | \"uploading\"\n | \"streaming\"\n | \"reconnecting\"\n | \"paused\"\n | \"cancelling\"\n | \"cancelled\"\n | \"offline\"\n | \"denied\"\n | \"quota\"\n | \"failed\"\n | \"expired\";\n\nexport type AgentChatRuntimeConnectionState =\n | \"connected\"\n | \"connecting\"\n | \"reconnecting\"\n | \"offline\"\n | \"expired\";\n\nexport type AgentChatThreadChangeReason = \"created\" | \"opened\" | \"new\" | \"deleted\";\n\nexport type AgentChatActiveThreadChange = {\n threadId: string | null;\n reason: AgentChatThreadChangeReason;\n};\n\nexport type AgentChatActiveThreadChangeHandler = (\n change: AgentChatActiveThreadChange,\n) => void;\n\nexport type AgentChatMcpAuthorizationCompletion = (input: {\n completion: ChatMcpOauthCompletion;\n codeVerifier: string;\n serverId: string;\n}) => Promise<void>;\n\nexport type AgentChatRuntimeSubmit = {\n text: string;\n files?: readonly PortableUpload[];\n attachments?: ChatAttachment[];\n attachmentIds?: readonly string[];\n};\n\nexport type AgentChatRuntimeHitlActionState = Omit<HitlSubmissionState, \"status\"> & {\n status: HitlSubmissionState[\"status\"] | \"connecting\" | \"resuming\";\n};\n\nexport type UseAgentChatRuntimeOptions = {\n activeThreadId?: string | null;\n agent?: AgentChatRuntimeAgent;\n client: AgentClient;\n completeMcpAuthorization?: AgentChatMcpAuthorizationCompletion;\n mcpRedirectUri?: string;\n modelId?: string | null;\n onActiveThreadIdChange?: AgentChatActiveThreadChangeHandler;\n onModelChange?: (modelId: string) => void;\n};\n\nexport type AgentChatRuntime = {\n agent: AgentChatRuntimeAgent;\n inputContract: ClientBootstrap[\"features\"][\"inputs\"] | null;\n allowFeedback: boolean;\n backgroundError: unknown;\n bootstrap: ClientBootstrap | null;\n capabilities: readonly string[];\n agentId: string | null;\n agents: AgentChatRuntimeAgentOption[];\n changeAgent(agentId: string): Promise<void>;\n changeModel(modelId: string): void;\n clearOperationError(): void;\n connectionState: AgentChatRuntimeConnectionState;\n contextWindow: ContextWindow | null;\n contextCompression: ContextCompression | null;\n controller: AgentChatController;\n deleteThread(threadId: string): Promise<void>;\n errorMessage: string | null;\n fatalError: unknown;\n getHitlActionState(part: ChatHitlPart): AgentChatRuntimeHitlActionState | undefined;\n isBootstrapping: boolean;\n isChangingAgent: boolean;\n isSubmitting: boolean;\n isUploading: boolean;\n modelId: string | null;\n models: AgentChatRuntimeModel[];\n newThread(): void;\n onHitlAction(part: ChatHitlPart, response: HitlResponse, options?: HitlSubmissionOptions): Promise<void>;\n openThread(threadId: string): Promise<void>;\n operationError: unknown;\n retryBootstrap(): Promise<void>;\n resolveAttachmentContent(\n attachment: ChatAttachment,\n signal: AbortSignal,\n ): Promise<{ url: string; validUntil: string | null }>;\n state: AgentChatRuntimeViewState;\n submit(input: AgentChatRuntimeSubmit): Promise<void>;\n};\n\ntype PendingThreadTransition = {\n reason: \"opened\" | \"deleted\";\n value: string | null;\n};\n\nexport function agentChatRuntimeStateFromError(error: unknown): AgentChatRuntimeViewState {\n const typed = error as Partial<Agents24ClientError> | null;\n if (typed?.kind === \"authentication\") return \"expired\";\n if (typed?.kind === \"authorization\") return \"denied\";\n if (typed?.kind === \"quota\" || typed?.kind === \"rate_limit\") return \"quota\";\n if (typed?.kind === \"network\") return \"offline\";\n return \"failed\";\n}\n\nexport function agentChatRuntimeErrorMessage(error: unknown): string | null {\n if (!error) return null;\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function canChangeAgentRuntime(\n runState: AgentChatController[\"runState\"],\n activeRunId: string | null,\n): boolean {\n return !activeRunId && ![\"uploading\", \"streaming\", \"reconnecting\", \"paused\", \"cancelling\"].includes(runState);\n}\n\nexport function agentIdFromBootstrap(\n bootstrap: ClientBootstrap,\n requestedAgentId: string | null,\n): string | null {\n const feature = bootstrap.features.agents;\n if (!feature) return null;\n return feature.options.some((item) => item.id === requestedAgentId)\n ? requestedAgentId\n : feature.default_id || null;\n}\n\nexport function modelsFromAgentChatBootstrap(bootstrap: ClientBootstrap): {\n defaultModelId: string | null;\n models: AgentChatRuntimeModel[];\n} {\n const modelFeatures = bootstrap.features.models;\n const selectable = bootstrap.capabilities.includes(\"models.select\") && modelFeatures?.selectable === true;\n if (!selectable) return { defaultModelId: null, models: [] };\n const models = Array.isArray(modelFeatures.options)\n ? modelFeatures.options.flatMap((option) => (\n typeof option?.id === \"string\" && option.id.trim()\n ? [{ id: option.id, label: typeof option.label === \"string\" && option.label.trim() ? option.label : option.id }]\n : []\n ))\n : [];\n const configuredDefault = models.some((model) => model.id === modelFeatures.default_id)\n ? modelFeatures.default_id\n : null;\n return {\n defaultModelId: configuredDefault,\n models,\n };\n}\n\nfunction modelsFromEffectivePolicy(policy: EffectiveResourcePolicy): {\n defaultModelId: string | null;\n models: AgentChatRuntimeModel[];\n} {\n const models = policy.model_selection.selectable\n ? policy.model_selection.options.map((option) => ({ id: option.id, label: option.label }))\n : [];\n return {\n defaultModelId: models.some((model) => model.id === policy.model_selection.default_id)\n ? policy.model_selection.default_id\n : null,\n models,\n };\n}\n\nexport function useAgentChatRuntime(options: UseAgentChatRuntimeOptions): AgentChatRuntime {\n const {\n activeThreadId,\n agent: agentOverride,\n client,\n completeMcpAuthorization,\n mcpRedirectUri,\n modelId,\n onActiveThreadIdChange,\n onModelChange,\n } = options;\n const controller = useAgentChat(\n activeThreadId === undefined ? { client } : { activeThreadId, client },\n );\n const attachments = useAgentAttachments();\n const bootstrapOwnerRef = React.useRef<AgentClient | null>(null);\n const [bootstrapState, setBootstrap] = React.useState<ClientBootstrap | null>(null);\n const bootstrap = bootstrapOwnerRef.current === client ? bootstrapState : null;\n const bootstrapRef = React.useRef<ClientBootstrap | null>(bootstrap);\n bootstrapRef.current = bootstrap;\n const [effectivePolicyState, setEffectivePolicy] = React.useState<EffectiveResourcePolicy | null>(null);\n const effectivePolicy = bootstrapOwnerRef.current === client ? effectivePolicyState : null;\n const [isBootstrapping, setIsBootstrapping] = React.useState(true);\n const [bootstrapError, setBootstrapError] = React.useState<unknown>(null);\n const [localOperationError, setLocalOperationError] = React.useState<unknown>(null);\n const [selectedModelId, setSelectedModelId] = React.useState<string | null>(modelId ?? null);\n const selectedModelIdRef = React.useRef<string | null>(selectedModelId);\n selectedModelIdRef.current = selectedModelId;\n const [selectedAgentId, setSelectedAgentId] = React.useState<string | null>(null);\n const selectedAgentIdRef = React.useRef<string | null>(null);\n selectedAgentIdRef.current = selectedAgentId;\n const [isChangingAgent, setIsChangingAgent] = React.useState(false);\n const agentChangePromiseRef = React.useRef<Promise<void> | null>(null);\n const [isSubmitting, setIsSubmitting] = React.useState(false);\n const submitPromiseRef = React.useRef<Promise<void> | null>(null);\n\n const mountedRef = React.useRef(true);\n const clientRef = React.useRef(client);\n clientRef.current = client;\n const bootstrapRetryRef = React.useRef(0);\n const bootstrapPromiseRef = React.useRef<{ client: AgentClient; promise: Promise<void> } | null>(null);\n React.useEffect(() => {\n mountedRef.current = true;\n return () => { mountedRef.current = false; };\n }, []);\n\n const previousControlledThreadRef = React.useRef(activeThreadId);\n const threadSelectionGenerationRef = React.useRef(0);\n const controlledSyncTargetRef = React.useRef<{ value: string | null } | null>(null);\n const previousControllerThreadRef = React.useRef(controller.activeThreadId);\n const pendingThreadTransitionRef = React.useRef<PendingThreadTransition | null>(null);\n const lastReportedThreadRef = React.useRef<string | null>(activeThreadId ?? controller.activeThreadId);\n if (activeThreadId !== previousControlledThreadRef.current) {\n threadSelectionGenerationRef.current += 1;\n previousControlledThreadRef.current = activeThreadId;\n if (activeThreadId !== undefined) {\n controlledSyncTargetRef.current = { value: activeThreadId };\n lastReportedThreadRef.current = activeThreadId;\n }\n }\n\n const reportActiveThread = React.useCallback((\n threadId: string | null,\n reason: AgentChatThreadChangeReason,\n ) => {\n if (lastReportedThreadRef.current === threadId) return;\n lastReportedThreadRef.current = threadId;\n onActiveThreadIdChange?.({ threadId, reason });\n }, [onActiveThreadIdChange]);\n\n const retryBootstrap = React.useCallback((): Promise<void> => {\n if (bootstrapPromiseRef.current?.client === client) return bootstrapPromiseRef.current.promise;\n const requestClient = client;\n const request = (async () => {\n if (mountedRef.current) {\n const identityChanged = bootstrapOwnerRef.current !== requestClient;\n setIsBootstrapping(identityChanged || !bootstrapRef.current);\n setBootstrapError(null);\n if (identityChanged) {\n setBootstrap(null);\n setEffectivePolicy(null);\n setSelectedAgentId(null);\n setSelectedModelId(null);\n }\n }\n try {\n const requestedAgentId = selectedAgentIdRef.current;\n const result = await requestClient.bootstrap({ agentId: requestedAgentId || undefined });\n if (!mountedRef.current || clientRef.current !== requestClient) return;\n bootstrapOwnerRef.current = requestClient;\n bootstrapRetryRef.current = 0;\n setBootstrap(result);\n const agentFeature = result.features.agents;\n const resolvedAgentId = agentIdFromBootstrap(result, requestedAgentId);\n setSelectedAgentId(resolvedAgentId);\n const entitlement = agentFeature ? null : await requestClient.resourcePolicies.getEffective();\n if (!mountedRef.current || clientRef.current !== requestClient) return;\n setEffectivePolicy(entitlement);\n const availableModels = entitlement ? modelsFromEffectivePolicy(entitlement) : modelsFromAgentChatBootstrap(result);\n if (modelId === undefined) {\n setSelectedModelId((current) => availableModels.models.some((item) => item.id === current)\n ? current\n : availableModels.defaultModelId);\n }\n void controller.refreshThreads().catch(() => undefined);\n } catch (error) {\n if (mountedRef.current && clientRef.current === requestClient) {\n const status = (error as Agents24ClientError)?.status;\n if (status === 401 || status === 403 || status === 404) {\n setBootstrap(null);\n setEffectivePolicy(null);\n bootstrapOwnerRef.current = null;\n }\n setBootstrapError(error);\n }\n } finally {\n if (mountedRef.current && clientRef.current === requestClient) setIsBootstrapping(false);\n }\n })();\n bootstrapPromiseRef.current = { client: requestClient, promise: request };\n void request.finally(() => {\n if (bootstrapPromiseRef.current?.promise === request) bootstrapPromiseRef.current = null;\n });\n return request;\n }, [client, controller.refreshThreads, modelId]);\n\n React.useEffect(() => {\n if (!bootstrapError || bootstrapRetryRef.current >= 4) return;\n const error = bootstrapError as Agents24ClientError;\n if (!(error.retryable || error.kind === \"network\" || (error.status || 0) >= 500)) return;\n const attempt = bootstrapRetryRef.current++;\n const hint = error.retryAfterMs;\n const delay = Math.max(500 * 2 ** attempt + Math.random() * 250,\n typeof hint === \"number\" && Number.isFinite(hint) && hint >= 0 ? Math.min(hint, 60_000) : 0);\n const timer = setTimeout(() => { void retryBootstrap(); }, delay);\n return () => clearTimeout(timer);\n }, [bootstrapError, retryBootstrap]);\n\n const refreshEffectivePolicy = React.useCallback(async () => {\n if (bootstrap?.features.agents) {\n const refreshed = await client.bootstrap({ agentId: selectedAgentIdRef.current || undefined });\n if (!mountedRef.current || clientRef.current !== client) return;\n setBootstrap(refreshed);\n const available = modelsFromAgentChatBootstrap(refreshed);\n setSelectedModelId((current) => available.models.some((item) => item.id === current)\n ? current\n : available.defaultModelId);\n return;\n }\n const entitlement = await client.resourcePolicies.getEffective();\n if (!mountedRef.current || clientRef.current !== client) return;\n setEffectivePolicy(entitlement);\n if (modelId === undefined) {\n const available = modelsFromEffectivePolicy(entitlement);\n setSelectedModelId((current) => available.models.some((item) => item.id === current)\n ? current\n : available.defaultModelId);\n }\n }, [bootstrap, client, modelId]);\n\n React.useEffect(() => {\n void retryBootstrap();\n }, [retryBootstrap]);\n\n React.useEffect(() => {\n if (modelId !== undefined) setSelectedModelId(modelId);\n }, [modelId]);\n\n React.useEffect(() => {\n if (controlledSyncTargetRef.current?.value === null && controller.activeThreadId) {\n controller.startNewThread();\n }\n }, [activeThreadId, controller.activeThreadId, controller.startNewThread]);\n\n React.useEffect(() => {\n const previous = previousControllerThreadRef.current;\n const current = controller.activeThreadId;\n previousControllerThreadRef.current = current;\n const controlledTarget = controlledSyncTargetRef.current;\n if (controlledTarget) {\n if (current === controlledTarget.value) controlledSyncTargetRef.current = null;\n return;\n }\n const pendingTransition = pendingThreadTransitionRef.current;\n if (pendingTransition && current === pendingTransition.value) return;\n if (previous === null && current !== null) reportActiveThread(current, \"created\");\n }, [activeThreadId, controller.activeThreadId, reportActiveThread]);\n\n const clearOperationError = React.useCallback(() => {\n setLocalOperationError(null);\n controller.clearOperationError();\n }, [controller.clearOperationError]);\n\n const submit = React.useCallback((input: AgentChatRuntimeSubmit): Promise<void> => {\n if (submitPromiseRef.current) return submitPromiseRef.current;\n clearOperationError();\n setIsSubmitting(true);\n const request = (async () => {\n try {\n await agentChangePromiseRef.current;\n const activeBootstrap = bootstrapRef.current;\n if (!activeBootstrap) throw new Error(\"The agent input contract is unavailable.\");\n const retained = (input.attachments || []).filter((attachment) => input.attachmentIds?.includes(attachment.id || \"\"));\n const inputError = validateAgentChatSubmission(activeBootstrap.features.inputs, input.text, [\n ...(input.files || []),\n ...retained.map((attachment) => ({ data: new Uint8Array(), mediaType: attachment.mediaType || \"application/octet-stream\" })),\n ]);\n if (inputError) throw new Error(inputError);\n await controller.submit({\n text: input.text,\n attachments: input.attachments,\n uploads: input.files,\n attachmentIds: input.attachmentIds,\n requestedModelId: selectedModelIdRef.current || undefined,\n requestedAgentId: selectedAgentIdRef.current || undefined,\n });\n } catch (error) {\n setLocalOperationError(error);\n const typed = error as Partial<Agents24ClientError>;\n if (typed.kind === \"quota\" || typed.kind === \"authorization\") {\n await refreshEffectivePolicy().catch(() => undefined);\n }\n throw error;\n } finally {\n setIsSubmitting(false);\n }\n })();\n submitPromiseRef.current = request;\n const clearRequest = () => {\n if (submitPromiseRef.current === request) submitPromiseRef.current = null;\n };\n void request.then(clearRequest, clearRequest);\n return request;\n }, [bootstrap, clearOperationError, controller.activeThreadId, controller.submit, refreshEffectivePolicy]);\n\n const { onHitlAction, getHitlActionState } = useAgentChatHitl({\n client, bootstrap, controller, selectionGeneration: threadSelectionGenerationRef,\n completeMcpAuthorization, mcpRedirectUri, clearOperationError, onError: setLocalOperationError,\n });\n\n const newThread = React.useCallback(() => {\n threadSelectionGenerationRef.current += 1;\n clearOperationError();\n pendingThreadTransitionRef.current = null;\n reportActiveThread(null, \"new\");\n controller.startNewThread();\n }, [clearOperationError, controller.startNewThread, reportActiveThread]);\n\n const openThread = React.useCallback(async (threadId: string) => {\n const requestGeneration = ++threadSelectionGenerationRef.current;\n clearOperationError();\n pendingThreadTransitionRef.current = { reason: \"opened\", value: threadId };\n try {\n const detail = await client.threads.get({ threadId });\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n const preferredAgentId = detail.runtime_selection?.agent_alias || detail.runtime_selection?.agent_id || null;\n if (preferredAgentId) {\n const result = await client.bootstrap({ agentId: preferredAgentId });\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n const resolvedAgentId = agentIdFromBootstrap(result, preferredAgentId);\n setBootstrap(result);\n setEffectivePolicy(null);\n setSelectedAgentId(resolvedAgentId);\n const available = modelsFromAgentChatBootstrap(result);\n const preferredModelId = detail.runtime_selection?.model_id || null;\n setSelectedModelId(available.models.some((item) => item.id === preferredModelId)\n ? preferredModelId\n : available.defaultModelId);\n }\n await controller.openThread(threadId);\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n reportActiveThread(threadId, \"opened\");\n } catch (error) {\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n setLocalOperationError(error);\n throw error;\n } finally {\n if (requestGeneration === threadSelectionGenerationRef.current) pendingThreadTransitionRef.current = null;\n }\n }, [clearOperationError, client, controller.openThread, reportActiveThread]);\n\n const deleteThread = React.useCallback(async (threadId: string) => {\n clearOperationError();\n const wasActive = controller.activeThreadId === threadId;\n if (wasActive) threadSelectionGenerationRef.current += 1;\n if (wasActive) pendingThreadTransitionRef.current = { reason: \"deleted\", value: null };\n try {\n await controller.deleteThread(threadId);\n if (wasActive) reportActiveThread(null, \"deleted\");\n } catch (error) {\n setLocalOperationError(error);\n throw error;\n } finally {\n if (wasActive && pendingThreadTransitionRef.current?.reason === \"deleted\") {\n pendingThreadTransitionRef.current = null;\n }\n }\n }, [clearOperationError, controller.activeThreadId, controller.deleteThread, reportActiveThread]);\n\n const changeModel = React.useCallback((nextModelId: string) => {\n if (modelId === undefined) setSelectedModelId(nextModelId);\n onModelChange?.(nextModelId);\n if (controller.activeThreadId && selectedAgentId && client.threads.setRuntimeSelection) {\n void client.threads.setRuntimeSelection({\n threadId: controller.activeThreadId,\n preferredAgentId: selectedAgentId,\n preferredModelId: nextModelId,\n }).catch(setLocalOperationError);\n }\n }, [client.threads, controller.activeThreadId, modelId, onModelChange, selectedAgentId]);\n\n const resolveAttachmentContent = React.useCallback(async (\n attachment: ChatAttachment,\n signal: AbortSignal,\n ) => {\n const attachmentId = typeof attachment.id === \"string\" ? attachment.id.trim() : \"\";\n if (!attachmentId) throw new Error(\"Attachment content identity is unavailable.\");\n const access = await attachments.createContentAccess({\n attachmentId,\n disposition: \"inline\",\n signal,\n });\n return { url: access.url, validUntil: access.valid_until || null };\n }, [attachments.createContentAccess]);\n\n const changeAgent = React.useCallback((nextAgentId: string): Promise<void> => {\n if (agentChangePromiseRef.current) return agentChangePromiseRef.current;\n if (\n nextAgentId === selectedAgentIdRef.current\n || !canChangeAgentRuntime(controller.runState, controller.activeRunId)\n ) return Promise.resolve();\n clearOperationError();\n setIsChangingAgent(true);\n const request = (async () => {\n try {\n const result = await client.bootstrap({ agentId: nextAgentId });\n const resolvedAgentId = agentIdFromBootstrap(result, nextAgentId);\n if (!resolvedAgentId) throw new Error(\"The requested Agent is no longer available.\");\n const available = modelsFromAgentChatBootstrap(result);\n const currentModelId = selectedModelIdRef.current;\n const nextModelId = available.models.some((item) => item.id === currentModelId)\n ? currentModelId\n : available.defaultModelId;\n if (controller.activeThreadId && client.threads.setRuntimeSelection) {\n const persisted = await client.threads.setRuntimeSelection({\n threadId: controller.activeThreadId,\n preferredAgentId: resolvedAgentId,\n preferredModelId: nextModelId,\n });\n selectedModelIdRef.current = persisted.runtime_selection.model_id;\n setSelectedModelId(persisted.runtime_selection.model_id);\n } else {\n selectedModelIdRef.current = nextModelId;\n setSelectedModelId(nextModelId);\n }\n selectedAgentIdRef.current = resolvedAgentId;\n bootstrapRef.current = result;\n setSelectedAgentId(resolvedAgentId);\n setBootstrap(result);\n setEffectivePolicy(null);\n } catch (error) {\n setLocalOperationError(error);\n throw error;\n }\n })();\n agentChangePromiseRef.current = request;\n const clearRequest = () => {\n if (agentChangePromiseRef.current === request) agentChangePromiseRef.current = null;\n if (mountedRef.current) setIsChangingAgent(false);\n };\n void request.then(clearRequest, clearRequest);\n return request;\n }, [clearOperationError, client, controller.activeRunId, controller.activeThreadId, controller.runState]);\n\n const modelOptions = effectivePolicy\n ? modelsFromEffectivePolicy(effectivePolicy).models\n : bootstrap\n ? modelsFromAgentChatBootstrap(bootstrap).models\n : [];\n const fatalError = (!bootstrap ? bootstrapError : null) || controller.error;\n const operationError = localOperationError || controller.operationError?.cause;\n const state: AgentChatRuntimeViewState = isBootstrapping\n ? \"loading\"\n : fatalError\n ? agentChatRuntimeStateFromError(fatalError)\n : controller.runState === \"uploading\"\n ? \"uploading\"\n : controller.runState === \"streaming\"\n ? \"streaming\"\n : controller.runState === \"reconnecting\"\n ? \"reconnecting\"\n : controller.runState === \"paused\"\n ? \"paused\"\n : controller.runState === \"cancelling\"\n ? \"cancelling\"\n : controller.runState === \"cancelled\"\n ? \"cancelled\"\n : \"ready\";\n const connectionState: AgentChatRuntimeConnectionState = bootstrapError && bootstrap ? \"reconnecting\" : state === \"offline\"\n ? \"offline\"\n : state === \"expired\"\n ? \"expired\"\n : state === \"reconnecting\"\n ? \"reconnecting\"\n : isBootstrapping\n ? \"connecting\"\n : \"connected\";\n return {\n agent: agentOverride || { name: bootstrap?.deployment.name || \"Agent\" },\n inputContract: bootstrap?.features.inputs || null,\n allowFeedback: Boolean(bootstrap?.capabilities.includes(\"feedback.write\")),\n backgroundError: (bootstrap && bootstrapError) || controller.backgroundError?.cause || null,\n bootstrap,\n capabilities: bootstrap?.capabilities || [],\n agentId: bootstrap ? selectedAgentId : null,\n agents: bootstrap?.features.agents?.options.map((item) => ({ id: item.id, label: item.label })) || [],\n changeAgent,\n changeModel,\n clearOperationError,\n connectionState,\n contextWindow: controller.contextWindow,\n contextCompression: controller.contextCompression,\n controller,\n deleteThread,\n errorMessage: agentChatRuntimeErrorMessage(fatalError || operationError),\n fatalError,\n getHitlActionState,\n isBootstrapping,\n isChangingAgent,\n isSubmitting: isSubmitting || controller.isSubmitting,\n isUploading: attachments.isUploading || controller.runState === \"uploading\",\n modelId: bootstrap ? selectedModelId : null,\n models: modelOptions,\n newThread,\n onHitlAction,\n openThread,\n operationError,\n retryBootstrap,\n resolveAttachmentContent,\n state,\n submit,\n };\n}\n","import type { AgentClient, ClientBootstrap, HitlResponse } from \"@agents24/client\";\nimport { type AgentChatController, type ChatHitlPart, type HitlSubmissionOptions, useAgentMcp } from \"@agents24/react\";\nimport * as React from \"react\";\nimport { browserChatCrypto, createMcpPkceProof, validateMcpCallbackResult, waitForMcpOauthComplete } from \"../mcp-oauth\";\nimport type { AgentChatMcpAuthorizationCompletion, AgentChatRuntimeHitlActionState } from \"./use-agent-chat-runtime\";\n\ntype HitlOptions = {\n client: AgentClient;\n bootstrap: ClientBootstrap | null;\n controller: AgentChatController;\n selectionGeneration: React.MutableRefObject<number>;\n completeMcpAuthorization?: AgentChatMcpAuthorizationCompletion;\n mcpRedirectUri?: string;\n clearOperationError(): void;\n onError(error: unknown): void;\n};\n\ntype HitlOperation = {\n abort: AbortController;\n isCurrent(): boolean;\n phase: \"connecting\" | \"resuming\";\n popup?: Window;\n};\n\nfunction detach(operation: HitlOperation) {\n operation.abort.abort();\n operation.popup?.close();\n}\n\nexport function useAgentChatHitl(options: HitlOptions) {\n const mcp = useAgentMcp();\n const latest = React.useRef(options);\n latest.current = options;\n const mounted = React.useRef(true);\n const operations = React.useRef(new Map<string, HitlOperation>());\n const [states, setStates] = React.useState<Record<string, AgentChatRuntimeHitlActionState>>({});\n\n React.useEffect(() => {\n mounted.current = true;\n const active = operations.current;\n return () => {\n mounted.current = false;\n for (const operation of active.values()) detach(operation);\n active.clear();\n };\n }, []);\n React.useEffect(() => {\n for (const [key, operation] of operations.current) {\n if (operation.isCurrent()) continue;\n detach(operation);\n operations.current.delete(key);\n setStates((current) => {\n const next = { ...current };\n delete next[key];\n return next;\n });\n }\n });\n React.useEffect(() => { setStates({}); }, [options.client, options.controller.activeThreadId]);\n\n const onHitlAction = React.useCallback(async (part: ChatHitlPart, response: HitlResponse, submission?: HitlSubmissionOptions) => {\n const captured = latest.current;\n const { controller, client, bootstrap, selectionGeneration } = captured;\n const generation = selectionGeneration.current;\n const threadId = controller.activeThreadId;\n const runId = part.runId || controller.messages.find((message) => message.parts.some(candidate => candidate.id === part.id))?.runId || controller.activeRunId;\n const key = `${generation}:${threadId}:${runId}:${part.interruptId || part.id}`;\n if (part.hitlKind !== \"mcp_auth\" || response.action !== \"connect\") {\n captured.clearOperationError();\n // All normal decisions, including host preparation, have one headless owner.\n return controller.resumeHitl(part, response, submission).catch(error => {\n const current = latest.current;\n if (mounted.current && current.client === client && current.selectionGeneration.current === generation\n && current.controller.activeThreadId === threadId) captured.onError(error);\n throw error;\n });\n }\n const previous = operations.current.get(key);\n if (previous?.isCurrent()) return;\n if (previous) { detach(previous); operations.current.delete(key); }\n const operation: HitlOperation = {\n abort: new AbortController(),\n phase: part.hitlKind === \"mcp_auth\" && response.action === \"connect\" ? \"connecting\" : \"resuming\",\n isCurrent() {\n const current = latest.current;\n return mounted.current && !operation.abort.signal.aborted\n && current.client === client && current.selectionGeneration.current === generation\n && current.controller.activeThreadId === threadId\n && (!current.controller.activeRunId || current.controller.activeRunId === runId)\n && ![\"cancelling\", \"cancelled\", \"failed\", \"completed\"].includes(current.controller.runState)\n && (operation.phase === \"resuming\" || current.controller.messages.some((message) =>\n message.runId === runId && message.parts.some((candidate) => candidate.type === \"hitl\"\n && candidate.interruptId === part.interruptId && candidate.status === \"pending\")));\n },\n };\n if (!operation.isCurrent()) return;\n captured.clearOperationError();\n operations.current.set(key, operation);\n setStates((current) => ({ ...current, [key]: { action: response.action, status: operation.phase } }));\n try {\n if (operation.phase === \"connecting\") {\n if (!runId) throw new Error(\"MCP authorization is missing its paused run.\");\n if (!bootstrap) throw new Error(\"MCP authorization requires runtime bootstrap.\");\n if (!captured.mcpRedirectUri) throw new Error(\"mcpRedirectUri is required for MCP Connect.\");\n const serverId = String(part.presentation.server_id || \"\").trim();\n if (!serverId) throw new Error(\"MCP authorization is missing its server identity.\");\n const serverEmbed = bootstrap.authentication.modes.includes(\"server_embed\");\n const popupNonce = browserChatCrypto().randomUUID();\n // Open within the click before awaiting crypto or the network.\n const popup = window.open(\"about:blank\", \"agents24-mcp\", \"popup,width=560,height=720\");\n if (!popup) throw new Error(\"Allow popups to connect this MCP account.\");\n operation.popup = popup;\n popup.document.title = \"Connecting to MCP\";\n popup.document.body.textContent = \"Opening secure connection…\";\n const proof = await createMcpPkceProof();\n if (!operation.isCurrent()) return;\n const started = await mcp.startAuthorization({\n runId, serverId, interruptId: part.interruptId, redirectUri: captured.mcpRedirectUri,\n popupNonce, codeChallenge: proof.challenge, signal: operation.abort.signal,\n });\n if (!operation.isCurrent()) return;\n if (!started.callback_origin) throw new Error(\"MCP authorization did not return a callback origin.\");\n const completionPromise = waitForMcpOauthComplete({\n popup, callbackOrigin: started.callback_origin, popupNonce, serverId,\n runId, interruptId: part.interruptId, signal: operation.abort.signal,\n requireConnectionId: serverEmbed || Boolean(captured.completeMcpAuthorization),\n });\n // Ensure a navigation exception cannot leave a rejected waiter unobserved.\n void completionPromise.catch(() => undefined);\n popup.location.replace(started.authorization_url);\n const completion = await completionPromise;\n if (!operation.isCurrent()) return;\n if (captured.completeMcpAuthorization) {\n await captured.completeMcpAuthorization({ completion, codeVerifier: proof.verifier, serverId });\n } else if (serverEmbed) {\n validateMcpCallbackResult({ server_id: completion.serverId, connection_id: completion.connectionId || \"\" }, serverId);\n } else {\n const redeemed = await mcp.redeemCallback({\n code: completion.code, codeVerifier: proof.verifier, signal: operation.abort.signal,\n });\n if (!operation.isCurrent()) return;\n validateMcpCallbackResult(redeemed, serverId);\n }\n popup.close();\n }\n if (!operation.isCurrent()) return;\n operation.phase = \"resuming\";\n setStates((current) => ({ ...current, [key]: { action: response.action, status: \"resuming\" } }));\n await controller.resumeHitl(part, response, submission);\n } catch (error) {\n if (!operation.isCurrent()) return;\n captured.onError(error);\n setStates((current) => ({ ...current, [key]: {\n action: response.action, status: \"error\", error: error instanceof Error ? error.message : String(error),\n } }));\n throw error;\n } finally {\n const ownsState = operation.isCurrent();\n // Abort the waiter and any in-flight transport, and always release the popup.\n detach(operation);\n if (operations.current.get(key) === operation) {\n operations.current.delete(key);\n if (ownsState) setStates((current) => {\n if (current[key]?.status === \"error\") return current;\n const next = { ...current };\n delete next[key];\n return next;\n });\n }\n }\n }, [mcp]);\n\n return { onHitlAction, getHitlActionState: (part: ChatHitlPart) => {\n const { controller, selectionGeneration } = latest.current;\n const runId = part.runId || controller.messages.find(message => message.parts.some(candidate => candidate.id === part.id))?.runId || controller.activeRunId;\n return controller.getHitlSubmissionState(part)\n || states[`${selectionGeneration.current}:${controller.activeThreadId}:${runId}:${part.interruptId || part.id}`];\n } };\n}\n","import type { McpCallbackResult } from \"@agents24/client\";\nimport type { ChatMcpOauthCompletion, WaitForMcpOauthCompleteInput } from \"./types\";\n\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\ntype CryptoLike = {\n getRandomValues<T extends Uint8Array>(array: T): T;\n randomUUID(): string;\n subtle: { digest(algorithm: string, data: Uint8Array): Promise<ArrayBuffer> };\n};\n\nexport function browserChatCrypto(): CryptoLike {\n const value = (globalThis as unknown as { crypto?: CryptoLike }).crypto;\n if (!value?.subtle || !value.randomUUID) {\n throw new Error(\"Secure browser crypto is required for MCP authorization.\");\n }\n return value;\n}\n\nfunction base64Url(bytes: Uint8Array): string {\n let binary = \"\";\n bytes.forEach((byte) => { binary += String.fromCharCode(byte); });\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/g, \"\");\n}\n\nexport async function createMcpPkceProof(): Promise<{ challenge: string; verifier: string }> {\n const crypto = browserChatCrypto();\n const verifier = base64Url(crypto.getRandomValues(new Uint8Array(32)));\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(verifier));\n return { challenge: base64Url(new Uint8Array(digest)), verifier };\n}\n\nfunction isLoopback(hostname: string): boolean {\n return hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"[::1]\";\n}\n\nfunction normalizedOrigin(value: string): string {\n try {\n const url = new URL(value);\n if (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && isLoopback(url.hostname))) {\n throw new Error(\"unsafe callback origin\");\n }\n if (url.origin === \"null\") throw new Error(\"opaque callback origin\");\n return url.origin;\n } catch {\n throw new Error(\"MCP authorization returned an invalid callback origin.\");\n }\n}\n\nexport function validateMcpCallbackResult(\n result: McpCallbackResult,\n expectedServerId: string,\n): McpCallbackResult {\n const serverId = String(result.server_id || \"\").trim();\n const connectionId = String(result.connection_id || \"\").trim();\n if (!serverId || serverId !== expectedServerId) {\n throw new Error(\"MCP authorization completed for an unexpected server.\");\n }\n if (!UUID_PATTERN.test(connectionId)) {\n throw new Error(\"MCP authorization returned an invalid connection identity.\");\n }\n return result;\n}\n\nexport function waitForMcpOauthComplete({\n popup,\n callbackOrigin,\n popupNonce,\n requireConnectionId = false,\n serverId,\n runId,\n interruptId,\n signal,\n timeoutMs = 120_000,\n}: WaitForMcpOauthCompleteInput): Promise<ChatMcpOauthCompletion> {\n if (!popup) return Promise.reject(new Error(\"Could not open the MCP authorization popup.\"));\n const expectedOrigin = normalizedOrigin(callbackOrigin);\n const expectedServerId = String(serverId || \"\").trim();\n const expectedPopupNonce = String(popupNonce || \"\").trim();\n if (!expectedServerId) return Promise.reject(new Error(\"MCP authorization is missing its server identity.\"));\n if (!expectedPopupNonce) return Promise.reject(new Error(\"MCP authorization is missing its popup binding.\"));\n const aborted = () => new DOMException(\"MCP authorization detached.\", \"AbortError\");\n if (signal?.aborted) return Promise.reject(aborted());\n const returnFocusTo = typeof document !== \"undefined\"\n ? document.activeElement as { focus?: () => void } | null\n : null;\n\n return new Promise((resolve, reject) => {\n let settled = false;\n const finish = (result: ChatMcpOauthCompletion | Error) => {\n if (settled) return;\n settled = true;\n window.clearTimeout(timeout);\n window.clearInterval(closeTimer);\n window.removeEventListener(\"message\", onMessage);\n signal?.removeEventListener(\"abort\", onAbort);\n if (!signal?.aborted) returnFocusTo?.focus?.();\n if (result instanceof Error) reject(result);\n else resolve(result);\n };\n const onAbort = () => finish(aborted());\n const onMessage = (event: MessageEvent) => {\n if (event.source !== popup || event.origin !== expectedOrigin) return;\n const data = event.data as {\n type?: string;\n code?: string;\n connection_id?: string;\n popup_nonce?: string;\n server_id?: string;\n run_id?: string;\n interrupt_id?: string;\n success?: boolean;\n } | null;\n if (\n data?.type !== \"agents24.mcp.callback\" ||\n data.server_id !== expectedServerId ||\n data.popup_nonce !== expectedPopupNonce ||\n (runId !== undefined && data.run_id !== runId) ||\n (interruptId !== undefined && data.interrupt_id !== interruptId)\n ) return;\n if (data.success === false) {\n finish(new Error(\"MCP authorization could not be completed.\"));\n return;\n }\n const code = String(data.code || \"\").trim();\n if (!code || code.length > 2048) return;\n const connectionId = String(data.connection_id || \"\").trim();\n if ((requireConnectionId || connectionId) && !UUID_PATTERN.test(connectionId)) return;\n finish({\n code,\n ...(connectionId ? { connectionId } : {}),\n popupNonce: expectedPopupNonce,\n serverId: expectedServerId,\n });\n };\n const timeout = window.setTimeout(\n () => finish(new Error(\"MCP authorization timed out.\")),\n Math.max(1, timeoutMs),\n );\n const closeTimer = window.setInterval(() => {\n if (popup.closed) finish(new Error(\"MCP authorization window was closed before connecting.\"));\n }, 500);\n window.addEventListener(\"message\", onMessage);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","import { normalizeAttachmentMimeType, SUPPORTED_ATTACHMENT_MIME_TYPES, type ClientInputFeature, type PortableUpload } from \"@agents24/client\";\nexport { attachmentFileAccept, normalizeAttachmentMimeType } from \"@agents24/client\";\n\nexport type AgentChatInputContract = ClientInputFeature;\n\nexport const SUPPORTED_INPUT_MIME_TYPES = SUPPORTED_ATTACHMENT_MIME_TYPES;\n\nexport type WorkflowInputRule = {\n key: string;\n enabled?: boolean;\n required?: boolean;\n};\n\nexport function workflowInputRule(\n inputs: readonly WorkflowInputRule[] | null | undefined,\n key: string,\n): { enabled: boolean; required: boolean } {\n const input = inputs?.find((candidate) => candidate.key === key);\n return {\n enabled: input?.enabled !== false,\n required: input?.required === true,\n };\n}\n\nexport function validateWorkflowInputSubmission(\n inputs: readonly WorkflowInputRule[] | null | undefined,\n text: string,\n attachmentMimeTypes: readonly string[],\n): string | null {\n const present = { files: false, images: false, audio: false };\n if (text.trim() && !workflowInputRule(inputs, \"text\").enabled) {\n return \"This workflow does not accept text input.\";\n }\n for (const rawMimeType of attachmentMimeTypes) {\n const mimeType = canonicalInputMimeType(rawMimeType);\n const modality = mimeType.startsWith(\"image/\") ? \"images\" : mimeType.startsWith(\"audio/\") ? \"audio\" : \"files\";\n const supported = (SUPPORTED_INPUT_MIME_TYPES[modality] as readonly string[]).includes(mimeType);\n if (!supported || !workflowInputRule(inputs, modality).enabled) {\n return `The attachment type ${mimeType || \"unknown\"} is not accepted.`;\n }\n present[modality] = true;\n }\n if (workflowInputRule(inputs, \"text\").required && !text.trim()) return \"Text input is required.\";\n for (const modality of [\"files\", \"images\", \"audio\"] as const) {\n if (workflowInputRule(inputs, modality).required && !present[modality]) {\n return `${modality[0].toUpperCase()}${modality.slice(1)} input is required.`;\n }\n }\n return null;\n}\n\nexport const canonicalInputMimeType = normalizeAttachmentMimeType;\n\nfunction uploadByteSize(data: PortableUpload[\"data\"]): number {\n if (data instanceof Uint8Array || data instanceof ArrayBuffer) return data.byteLength;\n return data.size;\n}\n\nexport function inputMimeTypes(contract: AgentChatInputContract | null | undefined): string[] {\n if (!contract) return [];\n return [\n ...([\"files\", \"images\", \"audio\"] as const).flatMap(key => contract.modalities[key].enabled ? contract.modalities[key].allowed_mime_types : []),\n ];\n}\n\nexport function validateAgentChatSubmission(\n contract: AgentChatInputContract,\n text: string,\n files: readonly (Pick<PortableUpload, \"mediaType\" | \"data\"> & Partial<Pick<PortableUpload, \"name\">> & { byteSize?: number })[],\n): string | null {\n const { modalities, limits } = contract;\n if (files.length && contract.validation_issues?.length) return contract.validation_issues[0].message;\n const normalizedText = text.trim();\n if (normalizedText && !modalities.text.enabled) return \"This agent does not accept text input.\";\n if (modalities.text.required && !normalizedText) return \"Text input is required.\";\n if (files.length > limits.max_attachments_per_turn) {\n return `You can attach up to ${limits.max_attachments_per_turn} items per message.`;\n }\n let totalBytes = 0;\n const present = { files: false, images: false, audio: false };\n for (const file of files) {\n const mediaType = normalizeAttachmentMimeType(file.mediaType, file.name);\n const modality = mediaType.startsWith(\"image/\") ? \"images\" : mediaType.startsWith(\"audio/\") ? \"audio\" : \"files\";\n const rule = modalities[modality];\n if (!rule.enabled || !rule.allowed_mime_types.includes(mediaType)) {\n return `The attachment type ${mediaType || \"unknown\"} is not accepted.`;\n }\n const byteSize = file.byteSize ?? uploadByteSize(file.data);\n if (byteSize > limits.max_file_bytes) return \"An attachment exceeds the per-file size limit.\";\n totalBytes += byteSize;\n present[modality] = true;\n }\n if (totalBytes > limits.max_total_bytes) return \"Attachments exceed the total size limit.\";\n for (const modality of [\"files\", \"images\", \"audio\"] as const) {\n if (modalities[modality].required && !present[modality]) return `${modality[0].toUpperCase()}${modality.slice(1)} input is required.`;\n }\n return null;\n}\n","import * as React from \"react\";\nimport type { DelegationEvents, DelegationTask } from \"../generated/delegation-types\";\n\nexport type DelegationTaskSource = {\n events(input: { threadId: string; after: number; signal: AbortSignal }): Promise<DelegationEvents>;\n};\n\n/** Authoritative snapshots keep task discovery alive after the run stream ends. */\nexport function useDelegationTasks({ threadId, source, pollIntervalMs = 2000 }: {\n threadId: string | null;\n source: DelegationTaskSource;\n pollIntervalMs?: number;\n}) {\n const [state, setState] = React.useState<{\n threadId: string | null; tasks: DelegationTask[]; error: unknown; loading: boolean;\n }>({ threadId: null, tasks: [], error: null, loading: false });\n const [revision, refresh] = React.useReducer((value: number) => value + 1, 0);\n React.useEffect(() => {\n if (!threadId) {\n setState({ threadId: null, tasks: [], error: null, loading: false });\n return;\n }\n const controller = new AbortController();\n let cursor = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let failures = 0;\n setState((previous) => ({ threadId, tasks: previous.threadId === threadId ? previous.tasks : [],\n error: null, loading: true }));\n const poll = async () => {\n try {\n const result = await source.events({ threadId, after: cursor, signal: controller.signal });\n if (controller.signal.aborted) return;\n cursor = result.cursor;\n failures = 0;\n setState({ threadId, tasks: result.snapshot, error: null, loading: false });\n } catch (error) {\n if (controller.signal.aborted) return;\n failures += 1;\n setState((previous) => ({ ...previous, error, loading: false }));\n }\n if (!controller.signal.aborted) {\n timer = setTimeout(poll, Math.min(30000, Math.max(250, pollIntervalMs) * 2 ** Math.min(failures, 4)));\n }\n };\n void poll();\n return () => {\n controller.abort();\n if (timer) clearTimeout(timer);\n };\n }, [threadId, source, pollIntervalMs, revision]);\n return { tasks: state.threadId === threadId ? state.tasks : [],\n error: state.threadId === threadId ? state.error : null,\n loading: Boolean(threadId) && (state.threadId !== threadId || state.loading), refresh };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSA,IAAAA,gBAQO;AACP,IAAAC,SAAuB;;;ACjBvB,mBAAqG;AACrG,YAAuB;;;ACCvB,IAAM,eAAe;AAQd,SAAS,oBAAgC;AAC9C,QAAM,QAAS,WAAkD;AACjE,MAAI,CAAC,OAAO,UAAU,CAAC,MAAM,YAAY;AACvC,UAAM,IAAI,MAAM,0DAA0D;AAAA,EAC5E;AACA,SAAO;AACT;AAEA,SAAS,UAAU,OAA2B;AAC5C,MAAI,SAAS;AACb,QAAM,QAAQ,CAAC,SAAS;AAAE,cAAU,OAAO,aAAa,IAAI;AAAA,EAAG,CAAC;AAChE,SAAO,KAAK,MAAM,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,QAAQ,EAAE;AAChF;AAEA,eAAsB,qBAAuE;AAC3F,QAAM,SAAS,kBAAkB;AACjC,QAAM,WAAW,UAAU,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC,CAAC;AACrE,QAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,IAAI,YAAY,EAAE,OAAO,QAAQ,CAAC;AACvF,SAAO,EAAE,WAAW,UAAU,IAAI,WAAW,MAAM,CAAC,GAAG,SAAS;AAClE;AAEA,SAAS,WAAW,UAA2B;AAC7C,SAAO,aAAa,eAAe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BAAS,EAAE,UAAU,OAAO,OAAO,UAAU,OAAO,MAAM,SAAS,MAAM,CAAC;AAAA,MAC5E,SAAS,OAAO;AACd,YAAI,WAAW,OAAO,QAAS;AAC/B,oBAAY;AACZ,iBAAS,CAAC,cAAc,EAAE,GAAG,UAAU,OAAO,SAAS,MAAM,EAAE;AAAA,MACjE;AACA,UAAI,CAAC,WAAW,OAAO,SAAS;AAC9B,gBAAQ,WAAW,MAAM,KAAK,IAAI,KAAO,KAAK,IAAI,KAAK,cAAc,IAAI,KAAK,KAAK,IAAI,UAAU,CAAC,CAAC,CAAC;AAAA,MACtG;AAAA,IACF;AACA,SAAK,KAAK;AACV,WAAO,MAAM;AACX,iBAAW,MAAM;AACjB,UAAI,MAAO,cAAa,KAAK;AAAA,IAC/B;AAAA,EACF,GAAG,CAAC,UAAU,QAAQ,gBAAgB,QAAQ,CAAC;AAC/C,SAAO;AAAA,IAAE,OAAO,MAAM,aAAa,WAAW,MAAM,QAAQ,CAAC;AAAA,IAC3D,OAAO,MAAM,aAAa,WAAW,MAAM,QAAQ;AAAA,IACnD,SAAS,QAAQ,QAAQ,MAAM,MAAM,aAAa,YAAY,MAAM;AAAA,IAAU;AAAA,EAAQ;AAC1F;","names":["import_react","React","import_client","React"]}
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/index.ts","../../src/runtime/use-agent-chat-runtime.ts","../../src/runtime/use-agent-chat-hitl.ts","../../src/mcp-oauth.ts","../../src/runtime/input-contract.ts","../../src/runtime/use-delegation-tasks.ts"],"sourcesContent":["export * from \"./use-agent-chat-runtime\";\nexport * from \"./input-contract\";\n\nexport * from \"./use-delegation-tasks\";\nexport type * from \"../generated/delegation-types\";\n","import type {\n AgentClient,\n Agents24ClientError,\n ClientBootstrap,\n EffectiveResourcePolicy,\n HitlResponse,\n PortableUpload,\n} from \"@agents24/client\";\nimport type { ContextCompression, ContextWindow } from \"@agents24/client/protocol\";\nimport {\n type AgentChatController,\n type ChatAttachment,\n type ChatHitlPart,\n type HitlSubmissionOptions,\n type HitlSubmissionState,\n useAgentAttachments,\n useAgentChat,\n} from \"@agents24/react\";\nimport * as React from \"react\";\n\nimport { useAgentChatHitl } from \"./use-agent-chat-hitl\";\nimport type { ChatMcpOauthCompletion } from \"../types\";\nimport { validateAgentChatSubmission } from \"./input-contract\";\n\nexport type AgentChatRuntimeAgent = {\n name: string;\n description?: string | null;\n handle?: string | null;\n avatarUrl?: string | null;\n};\n\nexport type AgentChatRuntimeModel = {\n id: string;\n label: string;\n};\n\nexport type AgentChatRuntimeAgentOption = { id: string; label: string };\n\nexport type AgentChatRuntimeViewState =\n | \"ready\"\n | \"loading\"\n | \"uploading\"\n | \"streaming\"\n | \"reconnecting\"\n | \"paused\"\n | \"cancelling\"\n | \"cancelled\"\n | \"offline\"\n | \"denied\"\n | \"quota\"\n | \"failed\"\n | \"expired\";\n\nexport type AgentChatRuntimeConnectionState =\n | \"connected\"\n | \"connecting\"\n | \"reconnecting\"\n | \"offline\"\n | \"expired\";\n\nexport type AgentChatThreadChangeReason = \"created\" | \"opened\" | \"new\" | \"deleted\";\n\nexport type AgentChatActiveThreadChange = {\n threadId: string | null;\n reason: AgentChatThreadChangeReason;\n};\n\nexport type AgentChatActiveThreadChangeHandler = (\n change: AgentChatActiveThreadChange,\n) => void;\n\nexport type AgentChatMcpAuthorizationCompletion = (input: {\n completion: ChatMcpOauthCompletion;\n codeVerifier: string;\n serverId: string;\n}) => Promise<void>;\n\nexport type AgentChatRuntimeSubmit = {\n text: string;\n files?: readonly PortableUpload[];\n attachments?: ChatAttachment[];\n attachmentIds?: readonly string[];\n};\n\nexport type AgentChatRuntimeHitlActionState = Omit<HitlSubmissionState, \"status\"> & {\n status: HitlSubmissionState[\"status\"] | \"connecting\" | \"resuming\";\n};\n\nexport type UseAgentChatRuntimeOptions = {\n activeThreadId?: string | null;\n agent?: AgentChatRuntimeAgent;\n client: AgentClient;\n completeMcpAuthorization?: AgentChatMcpAuthorizationCompletion;\n mcpRedirectUri?: string;\n modelId?: string | null;\n onActiveThreadIdChange?: AgentChatActiveThreadChangeHandler;\n onModelChange?: (modelId: string) => void;\n};\n\nexport type AgentChatRuntime = {\n agent: AgentChatRuntimeAgent;\n inputContract: ClientBootstrap[\"features\"][\"inputs\"] | null;\n allowFeedback: boolean;\n isReadOnly: boolean;\n backgroundError: unknown;\n bootstrap: ClientBootstrap | null;\n capabilities: readonly string[];\n agentId: string | null;\n agents: AgentChatRuntimeAgentOption[];\n changeAgent(agentId: string): Promise<void>;\n changeModel(modelId: string): void;\n clearOperationError(): void;\n connectionState: AgentChatRuntimeConnectionState;\n contextWindow: ContextWindow | null;\n contextCompression: ContextCompression | null;\n controller: AgentChatController;\n deleteThread(threadId: string): Promise<void>;\n errorMessage: string | null;\n fatalError: unknown;\n getHitlActionState(part: ChatHitlPart): AgentChatRuntimeHitlActionState | undefined;\n isBootstrapping: boolean;\n isChangingAgent: boolean;\n isSubmitting: boolean;\n isUploading: boolean;\n modelId: string | null;\n models: AgentChatRuntimeModel[];\n newThread(): void;\n onHitlAction(part: ChatHitlPart, response: HitlResponse, options?: HitlSubmissionOptions): Promise<void>;\n openThread(threadId: string): Promise<void>;\n operationError: unknown;\n retryBootstrap(): Promise<void>;\n resolveAttachmentContent(\n attachment: ChatAttachment,\n signal: AbortSignal,\n ): Promise<{ url: string; validUntil: string | null }>;\n state: AgentChatRuntimeViewState;\n submit(input: AgentChatRuntimeSubmit): Promise<void>;\n};\n\ntype PendingThreadTransition = {\n reason: \"opened\" | \"deleted\";\n value: string | null;\n};\n\nexport function agentChatRuntimeStateFromError(error: unknown): AgentChatRuntimeViewState {\n const typed = error as Partial<Agents24ClientError> | null;\n if (typed?.kind === \"authentication\") return \"expired\";\n if (typed?.kind === \"authorization\") return \"denied\";\n if (typed?.kind === \"quota\" || typed?.kind === \"rate_limit\") return \"quota\";\n if (typed?.kind === \"network\") return \"offline\";\n return \"failed\";\n}\n\nexport function agentChatRuntimeErrorMessage(error: unknown): string | null {\n if (!error) return null;\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function canChangeAgentRuntime(\n runState: AgentChatController[\"runState\"],\n activeRunId: string | null,\n): boolean {\n return !activeRunId && ![\"uploading\", \"streaming\", \"reconnecting\", \"paused\", \"cancelling\"].includes(runState);\n}\n\nexport function agentIdFromBootstrap(\n bootstrap: ClientBootstrap,\n requestedAgentId: string | null,\n): string | null {\n const feature = bootstrap.features.agents;\n if (!feature) return null;\n return feature.options.some((item) => item.id === requestedAgentId)\n ? requestedAgentId\n : feature.default_id || null;\n}\n\nexport function modelsFromAgentChatBootstrap(bootstrap: ClientBootstrap): {\n defaultModelId: string | null;\n models: AgentChatRuntimeModel[];\n} {\n const modelFeatures = bootstrap.features.models;\n const selectable = bootstrap.capabilities.includes(\"models.select\") && modelFeatures?.selectable === true;\n if (!selectable) return { defaultModelId: null, models: [] };\n const models = Array.isArray(modelFeatures.options)\n ? modelFeatures.options.flatMap((option) => (\n typeof option?.id === \"string\" && option.id.trim()\n ? [{ id: option.id, label: typeof option.label === \"string\" && option.label.trim() ? option.label : option.id }]\n : []\n ))\n : [];\n const configuredDefault = models.some((model) => model.id === modelFeatures.default_id)\n ? modelFeatures.default_id\n : null;\n return {\n defaultModelId: configuredDefault,\n models,\n };\n}\n\nfunction modelsFromEffectivePolicy(policy: EffectiveResourcePolicy): {\n defaultModelId: string | null;\n models: AgentChatRuntimeModel[];\n} {\n const models = policy.model_selection.selectable\n ? policy.model_selection.options.map((option) => ({ id: option.id, label: option.label }))\n : [];\n return {\n defaultModelId: models.some((model) => model.id === policy.model_selection.default_id)\n ? policy.model_selection.default_id\n : null,\n models,\n };\n}\n\nexport function useAgentChatRuntime(options: UseAgentChatRuntimeOptions): AgentChatRuntime {\n const {\n activeThreadId,\n agent: agentOverride,\n client,\n completeMcpAuthorization,\n mcpRedirectUri,\n modelId,\n onActiveThreadIdChange,\n onModelChange,\n } = options;\n const controller = useAgentChat(\n activeThreadId === undefined ? { client } : { activeThreadId, client },\n );\n const attachments = useAgentAttachments();\n const bootstrapOwnerRef = React.useRef<AgentClient | null>(null);\n const [bootstrapState, setBootstrap] = React.useState<ClientBootstrap | null>(null);\n const bootstrap = bootstrapOwnerRef.current === client ? bootstrapState : null;\n const bootstrapRef = React.useRef<ClientBootstrap | null>(bootstrap);\n bootstrapRef.current = bootstrap;\n const [effectivePolicyState, setEffectivePolicy] = React.useState<EffectiveResourcePolicy | null>(null);\n const effectivePolicy = bootstrapOwnerRef.current === client ? effectivePolicyState : null;\n const [isBootstrapping, setIsBootstrapping] = React.useState(true);\n const [bootstrapError, setBootstrapError] = React.useState<unknown>(null);\n const [localOperationError, setLocalOperationError] = React.useState<unknown>(null);\n const [selectedModelId, setSelectedModelId] = React.useState<string | null>(modelId ?? null);\n const selectedModelIdRef = React.useRef<string | null>(selectedModelId);\n selectedModelIdRef.current = selectedModelId;\n const [selectedAgentId, setSelectedAgentId] = React.useState<string | null>(null);\n const selectedAgentIdRef = React.useRef<string | null>(null);\n selectedAgentIdRef.current = selectedAgentId;\n const [isChangingAgent, setIsChangingAgent] = React.useState(false);\n const agentChangePromiseRef = React.useRef<Promise<void> | null>(null);\n const [isSubmitting, setIsSubmitting] = React.useState(false);\n const submitPromiseRef = React.useRef<Promise<void> | null>(null);\n\n const mountedRef = React.useRef(true);\n const clientRef = React.useRef(client);\n clientRef.current = client;\n const bootstrapRetryRef = React.useRef(0);\n const bootstrapPromiseRef = React.useRef<{ client: AgentClient; promise: Promise<void> } | null>(null);\n React.useEffect(() => {\n mountedRef.current = true;\n return () => { mountedRef.current = false; };\n }, []);\n\n const previousControlledThreadRef = React.useRef(activeThreadId);\n const threadSelectionGenerationRef = React.useRef(0);\n const controlledSyncTargetRef = React.useRef<{ value: string | null } | null>(null);\n const previousControllerThreadRef = React.useRef(controller.activeThreadId);\n const pendingThreadTransitionRef = React.useRef<PendingThreadTransition | null>(null);\n const lastReportedThreadRef = React.useRef<string | null>(activeThreadId ?? controller.activeThreadId);\n if (activeThreadId !== previousControlledThreadRef.current) {\n threadSelectionGenerationRef.current += 1;\n previousControlledThreadRef.current = activeThreadId;\n if (activeThreadId !== undefined) {\n controlledSyncTargetRef.current = { value: activeThreadId };\n lastReportedThreadRef.current = activeThreadId;\n }\n }\n\n const reportActiveThread = React.useCallback((\n threadId: string | null,\n reason: AgentChatThreadChangeReason,\n ) => {\n if (lastReportedThreadRef.current === threadId) return;\n lastReportedThreadRef.current = threadId;\n onActiveThreadIdChange?.({ threadId, reason });\n }, [onActiveThreadIdChange]);\n\n const retryBootstrap = React.useCallback((): Promise<void> => {\n if (bootstrapPromiseRef.current?.client === client) return bootstrapPromiseRef.current.promise;\n const requestClient = client;\n const request = (async () => {\n if (mountedRef.current) {\n const identityChanged = bootstrapOwnerRef.current !== requestClient;\n setIsBootstrapping(identityChanged || !bootstrapRef.current);\n setBootstrapError(null);\n if (identityChanged) {\n setBootstrap(null);\n setEffectivePolicy(null);\n setSelectedAgentId(null);\n setSelectedModelId(null);\n }\n }\n try {\n const requestedAgentId = selectedAgentIdRef.current;\n const result = await requestClient.bootstrap({ agentId: requestedAgentId || undefined });\n if (!mountedRef.current || clientRef.current !== requestClient) return;\n bootstrapOwnerRef.current = requestClient;\n bootstrapRetryRef.current = 0;\n setBootstrap(result);\n const agentFeature = result.features.agents;\n const resolvedAgentId = agentIdFromBootstrap(result, requestedAgentId);\n setSelectedAgentId(resolvedAgentId);\n const entitlement = agentFeature ? null : await requestClient.resourcePolicies.getEffective();\n if (!mountedRef.current || clientRef.current !== requestClient) return;\n setEffectivePolicy(entitlement);\n const availableModels = entitlement ? modelsFromEffectivePolicy(entitlement) : modelsFromAgentChatBootstrap(result);\n if (modelId === undefined) {\n setSelectedModelId((current) => availableModels.models.some((item) => item.id === current)\n ? current\n : availableModels.defaultModelId);\n }\n void controller.refreshThreads().catch(() => undefined);\n } catch (error) {\n if (mountedRef.current && clientRef.current === requestClient) {\n const status = (error as Agents24ClientError)?.status;\n if (status === 401 || status === 403 || status === 404) {\n setBootstrap(null);\n setEffectivePolicy(null);\n bootstrapOwnerRef.current = null;\n }\n setBootstrapError(error);\n }\n } finally {\n if (mountedRef.current && clientRef.current === requestClient) setIsBootstrapping(false);\n }\n })();\n bootstrapPromiseRef.current = { client: requestClient, promise: request };\n void request.finally(() => {\n if (bootstrapPromiseRef.current?.promise === request) bootstrapPromiseRef.current = null;\n });\n return request;\n }, [client, controller.refreshThreads, modelId]);\n\n React.useEffect(() => {\n if (!bootstrapError || bootstrapRetryRef.current >= 4) return;\n const error = bootstrapError as Agents24ClientError;\n if (!(error.retryable || error.kind === \"network\" || (error.status || 0) >= 500)) return;\n const attempt = bootstrapRetryRef.current++;\n const hint = error.retryAfterMs;\n const delay = Math.max(500 * 2 ** attempt + Math.random() * 250,\n typeof hint === \"number\" && Number.isFinite(hint) && hint >= 0 ? Math.min(hint, 60_000) : 0);\n const timer = setTimeout(() => { void retryBootstrap(); }, delay);\n return () => clearTimeout(timer);\n }, [bootstrapError, retryBootstrap]);\n\n const refreshEffectivePolicy = React.useCallback(async () => {\n if (bootstrap?.features.agents) {\n const refreshed = await client.bootstrap({ agentId: selectedAgentIdRef.current || undefined });\n if (!mountedRef.current || clientRef.current !== client) return;\n setBootstrap(refreshed);\n const available = modelsFromAgentChatBootstrap(refreshed);\n setSelectedModelId((current) => available.models.some((item) => item.id === current)\n ? current\n : available.defaultModelId);\n return;\n }\n const entitlement = await client.resourcePolicies.getEffective();\n if (!mountedRef.current || clientRef.current !== client) return;\n setEffectivePolicy(entitlement);\n if (modelId === undefined) {\n const available = modelsFromEffectivePolicy(entitlement);\n setSelectedModelId((current) => available.models.some((item) => item.id === current)\n ? current\n : available.defaultModelId);\n }\n }, [bootstrap, client, modelId]);\n\n React.useEffect(() => {\n void retryBootstrap();\n }, [retryBootstrap]);\n\n React.useEffect(() => {\n if (modelId !== undefined) setSelectedModelId(modelId);\n }, [modelId]);\n\n React.useEffect(() => {\n if (controlledSyncTargetRef.current?.value === null && controller.activeThreadId) {\n controller.startNewThread();\n }\n }, [activeThreadId, controller.activeThreadId, controller.startNewThread]);\n\n React.useEffect(() => {\n const previous = previousControllerThreadRef.current;\n const current = controller.activeThreadId;\n previousControllerThreadRef.current = current;\n const controlledTarget = controlledSyncTargetRef.current;\n if (controlledTarget) {\n if (current === controlledTarget.value) controlledSyncTargetRef.current = null;\n return;\n }\n const pendingTransition = pendingThreadTransitionRef.current;\n if (pendingTransition && current === pendingTransition.value) return;\n if (previous === null && current !== null) reportActiveThread(current, \"created\");\n }, [activeThreadId, controller.activeThreadId, reportActiveThread]);\n\n const clearOperationError = React.useCallback(() => {\n setLocalOperationError(null);\n controller.clearOperationError();\n }, [controller.clearOperationError]);\n\n const submit = React.useCallback((input: AgentChatRuntimeSubmit): Promise<void> => {\n if (submitPromiseRef.current) return submitPromiseRef.current;\n clearOperationError();\n setIsSubmitting(true);\n const request = (async () => {\n try {\n if(controller.activeThread?.read_only)throw new Error(\"This conversation is read-only. Start a new chat.\");\n await agentChangePromiseRef.current;\n const activeBootstrap = bootstrapRef.current;\n if (!activeBootstrap) throw new Error(\"The agent input contract is unavailable.\");\n const retained = (input.attachments || []).filter((attachment) => input.attachmentIds?.includes(attachment.id || \"\"));\n const inputError = validateAgentChatSubmission(activeBootstrap.features.inputs, input.text, [\n ...(input.files || []),\n ...retained.map((attachment) => ({ data: new Uint8Array(), mediaType: attachment.mediaType || \"application/octet-stream\" })),\n ]);\n if (inputError) throw new Error(inputError);\n await controller.submit({\n text: input.text,\n attachments: input.attachments,\n uploads: input.files,\n attachmentIds: input.attachmentIds,\n requestedModelId: selectedModelIdRef.current || undefined,\n requestedAgentId: selectedAgentIdRef.current || undefined,\n });\n } catch (error) {\n setLocalOperationError(error);\n const typed = error as Partial<Agents24ClientError>;\n if (typed.kind === \"quota\" || typed.kind === \"authorization\") {\n await refreshEffectivePolicy().catch(() => undefined);\n }\n throw error;\n } finally {\n setIsSubmitting(false);\n }\n })();\n submitPromiseRef.current = request;\n const clearRequest = () => {\n if (submitPromiseRef.current === request) submitPromiseRef.current = null;\n };\n void request.then(clearRequest, clearRequest);\n return request;\n }, [bootstrap, clearOperationError, controller.activeThreadId, controller.activeThread?.read_only, controller.submit, refreshEffectivePolicy]);\n\n const { onHitlAction, getHitlActionState } = useAgentChatHitl({\n client, bootstrap, controller, selectionGeneration: threadSelectionGenerationRef,\n completeMcpAuthorization, mcpRedirectUri, clearOperationError, onError: setLocalOperationError,\n });\n\n const newThread = React.useCallback(() => {\n threadSelectionGenerationRef.current += 1;\n clearOperationError();\n pendingThreadTransitionRef.current = null;\n reportActiveThread(null, \"new\");\n controller.startNewThread();\n }, [clearOperationError, controller.startNewThread, reportActiveThread]);\n\n const openThread = React.useCallback(async (threadId: string) => {\n const requestGeneration = ++threadSelectionGenerationRef.current;\n clearOperationError();\n pendingThreadTransitionRef.current = { reason: \"opened\", value: threadId };\n try {\n const detail = await client.threads.get({ threadId });\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n const preferredAgentId = detail.runtime_selection?.agent_alias || detail.runtime_selection?.agent_id || null;\n if (preferredAgentId && !detail.read_only) {\n const result = await client.bootstrap({ agentId: preferredAgentId });\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n const resolvedAgentId = agentIdFromBootstrap(result, preferredAgentId);\n setBootstrap(result);\n setEffectivePolicy(null);\n setSelectedAgentId(resolvedAgentId);\n const available = modelsFromAgentChatBootstrap(result);\n const preferredModelId = detail.runtime_selection?.model_id || null;\n setSelectedModelId(available.models.some((item) => item.id === preferredModelId)\n ? preferredModelId\n : available.defaultModelId);\n }\n await controller.openThread(threadId);\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n reportActiveThread(threadId, \"opened\");\n } catch (error) {\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n setLocalOperationError(error);\n throw error;\n } finally {\n if (requestGeneration === threadSelectionGenerationRef.current) pendingThreadTransitionRef.current = null;\n }\n }, [clearOperationError, client, controller.openThread, reportActiveThread]);\n\n const deleteThread = React.useCallback(async (threadId: string) => {\n clearOperationError();\n const wasActive = controller.activeThreadId === threadId;\n if (wasActive) threadSelectionGenerationRef.current += 1;\n if (wasActive) pendingThreadTransitionRef.current = { reason: \"deleted\", value: null };\n try {\n await controller.deleteThread(threadId);\n if (wasActive) reportActiveThread(null, \"deleted\");\n } catch (error) {\n setLocalOperationError(error);\n throw error;\n } finally {\n if (wasActive && pendingThreadTransitionRef.current?.reason === \"deleted\") {\n pendingThreadTransitionRef.current = null;\n }\n }\n }, [clearOperationError, controller.activeThreadId, controller.deleteThread, reportActiveThread]);\n\n const changeModel = React.useCallback((nextModelId: string) => {\n if (modelId === undefined) setSelectedModelId(nextModelId);\n onModelChange?.(nextModelId);\n if (controller.activeThreadId && selectedAgentId && client.threads.setRuntimeSelection) {\n void client.threads.setRuntimeSelection({\n threadId: controller.activeThreadId,\n preferredAgentId: selectedAgentId,\n preferredModelId: nextModelId,\n }).catch(setLocalOperationError);\n }\n }, [client.threads, controller.activeThreadId, modelId, onModelChange, selectedAgentId]);\n\n const resolveAttachmentContent = React.useCallback(async (\n attachment: ChatAttachment,\n signal: AbortSignal,\n ) => {\n const attachmentId = typeof attachment.id === \"string\" ? attachment.id.trim() : \"\";\n if (!attachmentId) throw new Error(\"Attachment content identity is unavailable.\");\n const access = await attachments.createContentAccess({\n attachmentId,\n disposition: \"inline\",\n signal,\n });\n return { url: access.url, validUntil: access.valid_until || null };\n }, [attachments.createContentAccess]);\n\n const changeAgent = React.useCallback((nextAgentId: string): Promise<void> => {\n if (agentChangePromiseRef.current) return agentChangePromiseRef.current;\n if (\n nextAgentId === selectedAgentIdRef.current\n || !canChangeAgentRuntime(controller.runState, controller.activeRunId)\n ) return Promise.resolve();\n clearOperationError();\n setIsChangingAgent(true);\n const request = (async () => {\n try {\n const result = await client.bootstrap({ agentId: nextAgentId });\n const resolvedAgentId = agentIdFromBootstrap(result, nextAgentId);\n if (!resolvedAgentId) throw new Error(\"The requested Agent is no longer available.\");\n const available = modelsFromAgentChatBootstrap(result);\n const currentModelId = selectedModelIdRef.current;\n const nextModelId = available.models.some((item) => item.id === currentModelId)\n ? currentModelId\n : available.defaultModelId;\n if (controller.activeThreadId && client.threads.setRuntimeSelection) {\n const persisted = await client.threads.setRuntimeSelection({\n threadId: controller.activeThreadId,\n preferredAgentId: resolvedAgentId,\n preferredModelId: nextModelId,\n });\n selectedModelIdRef.current = persisted.runtime_selection.model_id;\n setSelectedModelId(persisted.runtime_selection.model_id);\n } else {\n selectedModelIdRef.current = nextModelId;\n setSelectedModelId(nextModelId);\n }\n selectedAgentIdRef.current = resolvedAgentId;\n bootstrapRef.current = result;\n setSelectedAgentId(resolvedAgentId);\n setBootstrap(result);\n setEffectivePolicy(null);\n } catch (error) {\n setLocalOperationError(error);\n throw error;\n }\n })();\n agentChangePromiseRef.current = request;\n const clearRequest = () => {\n if (agentChangePromiseRef.current === request) agentChangePromiseRef.current = null;\n if (mountedRef.current) setIsChangingAgent(false);\n };\n void request.then(clearRequest, clearRequest);\n return request;\n }, [clearOperationError, client, controller.activeRunId, controller.activeThreadId, controller.runState]);\n\n const modelOptions = effectivePolicy\n ? modelsFromEffectivePolicy(effectivePolicy).models\n : bootstrap\n ? modelsFromAgentChatBootstrap(bootstrap).models\n : [];\n const fatalError = (!bootstrap ? bootstrapError : null) || controller.error;\n const operationError = localOperationError || controller.operationError?.cause;\n const state: AgentChatRuntimeViewState = isBootstrapping\n ? \"loading\"\n : fatalError\n ? agentChatRuntimeStateFromError(fatalError)\n : controller.runState === \"uploading\"\n ? \"uploading\"\n : controller.runState === \"streaming\"\n ? \"streaming\"\n : controller.runState === \"reconnecting\"\n ? \"reconnecting\"\n : controller.runState === \"paused\"\n ? \"paused\"\n : controller.runState === \"cancelling\"\n ? \"cancelling\"\n : controller.runState === \"cancelled\"\n ? \"cancelled\"\n : \"ready\";\n const connectionState: AgentChatRuntimeConnectionState = bootstrapError && bootstrap ? \"reconnecting\" : state === \"offline\"\n ? \"offline\"\n : state === \"expired\"\n ? \"expired\"\n : state === \"reconnecting\"\n ? \"reconnecting\"\n : isBootstrapping\n ? \"connecting\"\n : \"connected\";\n return {\n agent: agentOverride || { name: bootstrap?.deployment.name || \"Agent\" },\n inputContract: bootstrap?.features.inputs || null,\n allowFeedback: Boolean(bootstrap?.capabilities.includes(\"feedback.write\")) && !controller.activeThread?.read_only,\n isReadOnly:controller.activeThread?.read_only===true,\n backgroundError: (bootstrap && bootstrapError) || controller.backgroundError?.cause || null,\n bootstrap,\n capabilities: bootstrap?.capabilities || [],\n agentId: bootstrap ? selectedAgentId : null,\n agents: bootstrap?.features.agents?.options.map((item) => ({ id: item.id, label: item.label })) || [],\n changeAgent,\n changeModel,\n clearOperationError,\n connectionState,\n contextWindow: controller.contextWindow,\n contextCompression: controller.contextCompression,\n controller,\n deleteThread,\n errorMessage: agentChatRuntimeErrorMessage(fatalError || operationError),\n fatalError,\n getHitlActionState,\n isBootstrapping,\n isChangingAgent,\n isSubmitting: isSubmitting || controller.isSubmitting,\n isUploading: attachments.isUploading || controller.runState === \"uploading\",\n modelId: bootstrap ? selectedModelId : null,\n models: modelOptions,\n newThread,\n onHitlAction,\n openThread,\n operationError,\n retryBootstrap,\n resolveAttachmentContent,\n state,\n submit,\n };\n}\n","import type { AgentClient, ClientBootstrap, HitlResponse } from \"@agents24/client\";\nimport { type AgentChatController, type ChatHitlPart, type HitlSubmissionOptions, useAgentMcp } from \"@agents24/react\";\nimport * as React from \"react\";\nimport { browserChatCrypto, createMcpPkceProof, validateMcpCallbackResult, waitForMcpOauthComplete } from \"../mcp-oauth\";\nimport type { AgentChatMcpAuthorizationCompletion, AgentChatRuntimeHitlActionState } from \"./use-agent-chat-runtime\";\n\ntype HitlOptions = {\n client: AgentClient;\n bootstrap: ClientBootstrap | null;\n controller: AgentChatController;\n selectionGeneration: React.MutableRefObject<number>;\n completeMcpAuthorization?: AgentChatMcpAuthorizationCompletion;\n mcpRedirectUri?: string;\n clearOperationError(): void;\n onError(error: unknown): void;\n};\n\ntype HitlOperation = {\n abort: AbortController;\n isCurrent(): boolean;\n phase: \"connecting\" | \"resuming\";\n popup?: Window;\n};\n\nfunction detach(operation: HitlOperation) {\n operation.abort.abort();\n operation.popup?.close();\n}\n\nexport function useAgentChatHitl(options: HitlOptions) {\n const mcp = useAgentMcp();\n const latest = React.useRef(options);\n latest.current = options;\n const mounted = React.useRef(true);\n const operations = React.useRef(new Map<string, HitlOperation>());\n const [states, setStates] = React.useState<Record<string, AgentChatRuntimeHitlActionState>>({});\n\n React.useEffect(() => {\n mounted.current = true;\n const active = operations.current;\n return () => {\n mounted.current = false;\n for (const operation of active.values()) detach(operation);\n active.clear();\n };\n }, []);\n React.useEffect(() => {\n for (const [key, operation] of operations.current) {\n if (operation.isCurrent()) continue;\n detach(operation);\n operations.current.delete(key);\n setStates((current) => {\n const next = { ...current };\n delete next[key];\n return next;\n });\n }\n });\n React.useEffect(() => { setStates({}); }, [options.client, options.controller.activeThreadId]);\n\n const onHitlAction = React.useCallback(async (part: ChatHitlPart, response: HitlResponse, submission?: HitlSubmissionOptions) => {\n const captured = latest.current;\n const { controller, client, bootstrap, selectionGeneration } = captured;\n const generation = selectionGeneration.current;\n const threadId = controller.activeThreadId;\n const runId = part.runId || controller.messages.find((message) => message.parts.some(candidate => candidate.id === part.id))?.runId || controller.activeRunId;\n const key = `${generation}:${threadId}:${runId}:${part.interruptId || part.id}`;\n if (part.hitlKind !== \"mcp_auth\" || response.action !== \"connect\") {\n captured.clearOperationError();\n // All normal decisions, including host preparation, have one headless owner.\n return controller.resumeHitl(part, response, submission).catch(error => {\n const current = latest.current;\n if (mounted.current && current.client === client && current.selectionGeneration.current === generation\n && current.controller.activeThreadId === threadId) captured.onError(error);\n throw error;\n });\n }\n const previous = operations.current.get(key);\n if (previous?.isCurrent()) return;\n if (previous) { detach(previous); operations.current.delete(key); }\n const operation: HitlOperation = {\n abort: new AbortController(),\n phase: part.hitlKind === \"mcp_auth\" && response.action === \"connect\" ? \"connecting\" : \"resuming\",\n isCurrent() {\n const current = latest.current;\n return mounted.current && !operation.abort.signal.aborted\n && current.client === client && current.selectionGeneration.current === generation\n && current.controller.activeThreadId === threadId\n && (!current.controller.activeRunId || current.controller.activeRunId === runId)\n && ![\"cancelling\", \"cancelled\", \"failed\", \"completed\"].includes(current.controller.runState)\n && (operation.phase === \"resuming\" || current.controller.messages.some((message) =>\n message.runId === runId && message.parts.some((candidate) => candidate.type === \"hitl\"\n && candidate.interruptId === part.interruptId && candidate.status === \"pending\")));\n },\n };\n if (!operation.isCurrent()) return;\n captured.clearOperationError();\n operations.current.set(key, operation);\n setStates((current) => ({ ...current, [key]: { action: response.action, status: operation.phase } }));\n try {\n if (operation.phase === \"connecting\") {\n if (!runId) throw new Error(\"MCP authorization is missing its paused run.\");\n if (!bootstrap) throw new Error(\"MCP authorization requires runtime bootstrap.\");\n if (!captured.mcpRedirectUri) throw new Error(\"mcpRedirectUri is required for MCP Connect.\");\n const serverId = String(part.presentation.server_id || \"\").trim();\n if (!serverId) throw new Error(\"MCP authorization is missing its server identity.\");\n const serverEmbed = bootstrap.authentication.modes.includes(\"server_embed\");\n const popupNonce = browserChatCrypto().randomUUID();\n // Open within the click before awaiting crypto or the network.\n const popup = window.open(\"about:blank\", \"agents24-mcp\", \"popup,width=560,height=720\");\n if (!popup) throw new Error(\"Allow popups to connect this MCP account.\");\n operation.popup = popup;\n popup.document.title = \"Connecting to MCP\";\n popup.document.body.textContent = \"Opening secure connection…\";\n const proof = await createMcpPkceProof();\n if (!operation.isCurrent()) return;\n const started = await mcp.startAuthorization({\n runId, serverId, interruptId: part.interruptId, redirectUri: captured.mcpRedirectUri,\n popupNonce, codeChallenge: proof.challenge, signal: operation.abort.signal,\n });\n if (!operation.isCurrent()) return;\n if (!started.callback_origin) throw new Error(\"MCP authorization did not return a callback origin.\");\n const completionPromise = waitForMcpOauthComplete({\n popup, callbackOrigin: started.callback_origin, popupNonce, serverId,\n runId, interruptId: part.interruptId, signal: operation.abort.signal,\n requireConnectionId: serverEmbed || Boolean(captured.completeMcpAuthorization),\n });\n // Ensure a navigation exception cannot leave a rejected waiter unobserved.\n void completionPromise.catch(() => undefined);\n popup.location.replace(started.authorization_url);\n const completion = await completionPromise;\n if (!operation.isCurrent()) return;\n if (captured.completeMcpAuthorization) {\n await captured.completeMcpAuthorization({ completion, codeVerifier: proof.verifier, serverId });\n } else if (serverEmbed) {\n validateMcpCallbackResult({ server_id: completion.serverId, connection_id: completion.connectionId || \"\" }, serverId);\n } else {\n const redeemed = await mcp.redeemCallback({\n code: completion.code, codeVerifier: proof.verifier, signal: operation.abort.signal,\n });\n if (!operation.isCurrent()) return;\n validateMcpCallbackResult(redeemed, serverId);\n }\n popup.close();\n }\n if (!operation.isCurrent()) return;\n operation.phase = \"resuming\";\n setStates((current) => ({ ...current, [key]: { action: response.action, status: \"resuming\" } }));\n await controller.resumeHitl(part, response, submission);\n } catch (error) {\n if (!operation.isCurrent()) return;\n captured.onError(error);\n setStates((current) => ({ ...current, [key]: {\n action: response.action, status: \"error\", error: error instanceof Error ? error.message : String(error),\n } }));\n throw error;\n } finally {\n const ownsState = operation.isCurrent();\n // Abort the waiter and any in-flight transport, and always release the popup.\n detach(operation);\n if (operations.current.get(key) === operation) {\n operations.current.delete(key);\n if (ownsState) setStates((current) => {\n if (current[key]?.status === \"error\") return current;\n const next = { ...current };\n delete next[key];\n return next;\n });\n }\n }\n }, [mcp]);\n\n return { onHitlAction, getHitlActionState: (part: ChatHitlPart) => {\n const { controller, selectionGeneration } = latest.current;\n const runId = part.runId || controller.messages.find(message => message.parts.some(candidate => candidate.id === part.id))?.runId || controller.activeRunId;\n return controller.getHitlSubmissionState(part)\n || states[`${selectionGeneration.current}:${controller.activeThreadId}:${runId}:${part.interruptId || part.id}`];\n } };\n}\n","import type { McpCallbackResult } from \"@agents24/client\";\nimport type { ChatMcpOauthCompletion, WaitForMcpOauthCompleteInput } from \"./types\";\n\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\ntype CryptoLike = {\n getRandomValues<T extends Uint8Array>(array: T): T;\n randomUUID(): string;\n subtle: { digest(algorithm: string, data: Uint8Array): Promise<ArrayBuffer> };\n};\n\nexport function browserChatCrypto(): CryptoLike {\n const value = (globalThis as unknown as { crypto?: CryptoLike }).crypto;\n if (!value?.subtle || !value.randomUUID) {\n throw new Error(\"Secure browser crypto is required for MCP authorization.\");\n }\n return value;\n}\n\nfunction base64Url(bytes: Uint8Array): string {\n let binary = \"\";\n bytes.forEach((byte) => { binary += String.fromCharCode(byte); });\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/g, \"\");\n}\n\nexport async function createMcpPkceProof(): Promise<{ challenge: string; verifier: string }> {\n const crypto = browserChatCrypto();\n const verifier = base64Url(crypto.getRandomValues(new Uint8Array(32)));\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(verifier));\n return { challenge: base64Url(new Uint8Array(digest)), verifier };\n}\n\nfunction isLoopback(hostname: string): boolean {\n return hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"[::1]\";\n}\n\nfunction normalizedOrigin(value: string): string {\n try {\n const url = new URL(value);\n if (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && isLoopback(url.hostname))) {\n throw new Error(\"unsafe callback origin\");\n }\n if (url.origin === \"null\") throw new Error(\"opaque callback origin\");\n return url.origin;\n } catch {\n throw new Error(\"MCP authorization returned an invalid callback origin.\");\n }\n}\n\nexport function validateMcpCallbackResult(\n result: McpCallbackResult,\n expectedServerId: string,\n): McpCallbackResult {\n const serverId = String(result.server_id || \"\").trim();\n const connectionId = String(result.connection_id || \"\").trim();\n if (!serverId || serverId !== expectedServerId) {\n throw new Error(\"MCP authorization completed for an unexpected server.\");\n }\n if (!UUID_PATTERN.test(connectionId)) {\n throw new Error(\"MCP authorization returned an invalid connection identity.\");\n }\n return result;\n}\n\nexport function waitForMcpOauthComplete({\n popup,\n callbackOrigin,\n popupNonce,\n requireConnectionId = false,\n serverId,\n runId,\n interruptId,\n signal,\n timeoutMs = 120_000,\n}: WaitForMcpOauthCompleteInput): Promise<ChatMcpOauthCompletion> {\n if (!popup) return Promise.reject(new Error(\"Could not open the MCP authorization popup.\"));\n const expectedOrigin = normalizedOrigin(callbackOrigin);\n const expectedServerId = String(serverId || \"\").trim();\n const expectedPopupNonce = String(popupNonce || \"\").trim();\n if (!expectedServerId) return Promise.reject(new Error(\"MCP authorization is missing its server identity.\"));\n if (!expectedPopupNonce) return Promise.reject(new Error(\"MCP authorization is missing its popup binding.\"));\n const aborted = () => new DOMException(\"MCP authorization detached.\", \"AbortError\");\n if (signal?.aborted) return Promise.reject(aborted());\n const returnFocusTo = typeof document !== \"undefined\"\n ? document.activeElement as { focus?: () => void } | null\n : null;\n\n return new Promise((resolve, reject) => {\n let settled = false;\n const finish = (result: ChatMcpOauthCompletion | Error) => {\n if (settled) return;\n settled = true;\n window.clearTimeout(timeout);\n window.clearInterval(closeTimer);\n window.removeEventListener(\"message\", onMessage);\n signal?.removeEventListener(\"abort\", onAbort);\n if (!signal?.aborted) returnFocusTo?.focus?.();\n if (result instanceof Error) reject(result);\n else resolve(result);\n };\n const onAbort = () => finish(aborted());\n const onMessage = (event: MessageEvent) => {\n if (event.source !== popup || event.origin !== expectedOrigin) return;\n const data = event.data as {\n type?: string;\n code?: string;\n connection_id?: string;\n popup_nonce?: string;\n server_id?: string;\n run_id?: string;\n interrupt_id?: string;\n success?: boolean;\n } | null;\n if (\n data?.type !== \"agents24.mcp.callback\" ||\n data.server_id !== expectedServerId ||\n data.popup_nonce !== expectedPopupNonce ||\n (runId !== undefined && data.run_id !== runId) ||\n (interruptId !== undefined && data.interrupt_id !== interruptId)\n ) return;\n if (data.success === false) {\n finish(new Error(\"MCP authorization could not be completed.\"));\n return;\n }\n const code = String(data.code || \"\").trim();\n if (!code || code.length > 2048) return;\n const connectionId = String(data.connection_id || \"\").trim();\n if ((requireConnectionId || connectionId) && !UUID_PATTERN.test(connectionId)) return;\n finish({\n code,\n ...(connectionId ? { connectionId } : {}),\n popupNonce: expectedPopupNonce,\n serverId: expectedServerId,\n });\n };\n const timeout = window.setTimeout(\n () => finish(new Error(\"MCP authorization timed out.\")),\n Math.max(1, timeoutMs),\n );\n const closeTimer = window.setInterval(() => {\n if (popup.closed) finish(new Error(\"MCP authorization window was closed before connecting.\"));\n }, 500);\n window.addEventListener(\"message\", onMessage);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","import { normalizeAttachmentMimeType, SUPPORTED_ATTACHMENT_MIME_TYPES, type ClientInputFeature, type PortableUpload } from \"@agents24/client\";\nexport { attachmentFileAccept, normalizeAttachmentMimeType } from \"@agents24/client\";\n\nexport type AgentChatInputContract = ClientInputFeature;\n\nexport const SUPPORTED_INPUT_MIME_TYPES = SUPPORTED_ATTACHMENT_MIME_TYPES;\n\nexport type WorkflowInputRule = {\n key: string;\n enabled?: boolean;\n required?: boolean;\n};\n\nexport function workflowInputRule(\n inputs: readonly WorkflowInputRule[] | null | undefined,\n key: string,\n): { enabled: boolean; required: boolean } {\n const input = inputs?.find((candidate) => candidate.key === key);\n return {\n enabled: input?.enabled !== false,\n required: input?.required === true,\n };\n}\n\nexport function validateWorkflowInputSubmission(\n inputs: readonly WorkflowInputRule[] | null | undefined,\n text: string,\n attachmentMimeTypes: readonly string[],\n): string | null {\n const present = { files: false, images: false, audio: false };\n if (text.trim() && !workflowInputRule(inputs, \"text\").enabled) {\n return \"This workflow does not accept text input.\";\n }\n for (const rawMimeType of attachmentMimeTypes) {\n const mimeType = canonicalInputMimeType(rawMimeType);\n const modality = mimeType.startsWith(\"image/\") ? \"images\" : mimeType.startsWith(\"audio/\") ? \"audio\" : \"files\";\n const supported = (SUPPORTED_INPUT_MIME_TYPES[modality] as readonly string[]).includes(mimeType);\n if (!supported || !workflowInputRule(inputs, modality).enabled) {\n return `The attachment type ${mimeType || \"unknown\"} is not accepted.`;\n }\n present[modality] = true;\n }\n if (workflowInputRule(inputs, \"text\").required && !text.trim()) return \"Text input is required.\";\n for (const modality of [\"files\", \"images\", \"audio\"] as const) {\n if (workflowInputRule(inputs, modality).required && !present[modality]) {\n return `${modality[0].toUpperCase()}${modality.slice(1)} input is required.`;\n }\n }\n return null;\n}\n\nexport const canonicalInputMimeType = normalizeAttachmentMimeType;\n\nfunction uploadByteSize(data: PortableUpload[\"data\"]): number {\n if (data instanceof Uint8Array || data instanceof ArrayBuffer) return data.byteLength;\n return data.size;\n}\n\nexport function inputMimeTypes(contract: AgentChatInputContract | null | undefined): string[] {\n if (!contract) return [];\n return [\n ...([\"files\", \"images\", \"audio\"] as const).flatMap(key => contract.modalities[key].enabled ? contract.modalities[key].allowed_mime_types : []),\n ];\n}\n\nexport function validateAgentChatSubmission(\n contract: AgentChatInputContract,\n text: string,\n files: readonly (Pick<PortableUpload, \"mediaType\" | \"data\"> & Partial<Pick<PortableUpload, \"name\">> & { byteSize?: number })[],\n): string | null {\n const { modalities, limits } = contract;\n if (files.length && contract.validation_issues?.length) return contract.validation_issues[0].message;\n const normalizedText = text.trim();\n if (normalizedText && !modalities.text.enabled) return \"This agent does not accept text input.\";\n if (modalities.text.required && !normalizedText) return \"Text input is required.\";\n if (files.length > limits.max_attachments_per_turn) {\n return `You can attach up to ${limits.max_attachments_per_turn} items per message.`;\n }\n let totalBytes = 0;\n const present = { files: false, images: false, audio: false };\n for (const file of files) {\n const mediaType = normalizeAttachmentMimeType(file.mediaType, file.name);\n const modality = mediaType.startsWith(\"image/\") ? \"images\" : mediaType.startsWith(\"audio/\") ? \"audio\" : \"files\";\n const rule = modalities[modality];\n if (!rule.enabled || !rule.allowed_mime_types.includes(mediaType)) {\n return `The attachment type ${mediaType || \"unknown\"} is not accepted.`;\n }\n const byteSize = file.byteSize ?? uploadByteSize(file.data);\n if (byteSize > limits.max_file_bytes) return \"An attachment exceeds the per-file size limit.\";\n totalBytes += byteSize;\n present[modality] = true;\n }\n if (totalBytes > limits.max_total_bytes) return \"Attachments exceed the total size limit.\";\n for (const modality of [\"files\", \"images\", \"audio\"] as const) {\n if (modalities[modality].required && !present[modality]) return `${modality[0].toUpperCase()}${modality.slice(1)} input is required.`;\n }\n return null;\n}\n","import * as React from \"react\";\nimport type { DelegationEvents, DelegationTask } from \"../generated/delegation-types\";\n\nexport type DelegationTaskSource = {\n events(input: { threadId: string; after: number; signal: AbortSignal }): Promise<DelegationEvents>;\n};\n\n/** Authoritative snapshots keep task discovery alive after the run stream ends. */\nexport function useDelegationTasks({ threadId, source, pollIntervalMs = 2000 }: {\n threadId: string | null;\n source: DelegationTaskSource;\n pollIntervalMs?: number;\n}) {\n const [state, setState] = React.useState<{\n threadId: string | null; tasks: DelegationTask[]; error: unknown; loading: boolean;\n }>({ threadId: null, tasks: [], error: null, loading: false });\n const [revision, refresh] = React.useReducer((value: number) => value + 1, 0);\n React.useEffect(() => {\n if (!threadId) {\n setState({ threadId: null, tasks: [], error: null, loading: false });\n return;\n }\n const controller = new AbortController();\n let cursor = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let failures = 0;\n setState((previous) => ({ threadId, tasks: previous.threadId === threadId ? previous.tasks : [],\n error: null, loading: true }));\n const poll = async () => {\n try {\n const result = await source.events({ threadId, after: cursor, signal: controller.signal });\n if (controller.signal.aborted) return;\n cursor = result.cursor;\n failures = 0;\n setState({ threadId, tasks: result.snapshot, error: null, loading: false });\n } catch (error) {\n if (controller.signal.aborted) return;\n failures += 1;\n setState((previous) => ({ ...previous, error, loading: false }));\n }\n if (!controller.signal.aborted) {\n timer = setTimeout(poll, Math.min(30000, Math.max(250, pollIntervalMs) * 2 ** Math.min(failures, 4)));\n }\n };\n void poll();\n return () => {\n controller.abort();\n if (timer) clearTimeout(timer);\n };\n }, [threadId, source, pollIntervalMs, revision]);\n return { tasks: state.threadId === threadId ? state.tasks : [],\n error: state.threadId === threadId ? state.error : null,\n loading: Boolean(threadId) && (state.threadId !== threadId || state.loading), refresh };\n}\n"],"mappings":";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C/B,oBAAY;AACZ,iBAAS,CAAC,cAAc,EAAE,GAAG,UAAU,OAAO,SAAS,MAAM,EAAE;AAAA,MACjE;AACA,UAAI,CAAC,WAAW,OAAO,SAAS;AAC9B,gBAAQ,WAAW,MAAM,KAAK,IAAI,KAAO,KAAK,IAAI,KAAK,cAAc,IAAI,KAAK,KAAK,IAAI,UAAU,CAAC,CAAC,CAAC;AAAA,MACtG;AAAA,IACF;AACA,SAAK,KAAK;AACV,WAAO,MAAM;AACX,iBAAW,MAAM;AACjB,UAAI,MAAO,cAAa,KAAK;AAAA,IAC/B;AAAA,EACF,GAAG,CAAC,UAAU,QAAQ,gBAAgB,QAAQ,CAAC;AAC/C,SAAO;AAAA,IAAE,OAAO,MAAM,aAAa,WAAW,MAAM,QAAQ,CAAC;AAAA,IAC3D,OAAO,MAAM,aAAa,WAAW,MAAM,QAAQ;AAAA,IACnD,SAAS,QAAQ,QAAQ,MAAM,MAAM,aAAa,YAAY,MAAM;AAAA,IAAU;AAAA,EAAQ;AAC1F;","names":["import_react","React","import_client","React"]}
|
package/dist/runtime/index.js
CHANGED
|
@@ -406,6 +406,7 @@ function useAgentChatRuntime(options) {
|
|
|
406
406
|
setIsSubmitting(true);
|
|
407
407
|
const request = (async () => {
|
|
408
408
|
try {
|
|
409
|
+
if (controller.activeThread?.read_only) throw new Error("This conversation is read-only. Start a new chat.");
|
|
409
410
|
await agentChangePromiseRef.current;
|
|
410
411
|
const activeBootstrap = bootstrapRef.current;
|
|
411
412
|
if (!activeBootstrap) throw new Error("The agent input contract is unavailable.");
|
|
@@ -440,7 +441,7 @@ function useAgentChatRuntime(options) {
|
|
|
440
441
|
};
|
|
441
442
|
void request.then(clearRequest, clearRequest);
|
|
442
443
|
return request;
|
|
443
|
-
}, [bootstrap, clearOperationError, controller.activeThreadId, controller.submit, refreshEffectivePolicy]);
|
|
444
|
+
}, [bootstrap, clearOperationError, controller.activeThreadId, controller.activeThread?.read_only, controller.submit, refreshEffectivePolicy]);
|
|
444
445
|
const { onHitlAction, getHitlActionState } = useAgentChatHitl({
|
|
445
446
|
client,
|
|
446
447
|
bootstrap,
|
|
@@ -466,7 +467,7 @@ function useAgentChatRuntime(options) {
|
|
|
466
467
|
const detail = await client.threads.get({ threadId });
|
|
467
468
|
if (requestGeneration !== threadSelectionGenerationRef.current) return;
|
|
468
469
|
const preferredAgentId = detail.runtime_selection?.agent_alias || detail.runtime_selection?.agent_id || null;
|
|
469
|
-
if (preferredAgentId) {
|
|
470
|
+
if (preferredAgentId && !detail.read_only) {
|
|
470
471
|
const result = await client.bootstrap({ agentId: preferredAgentId });
|
|
471
472
|
if (requestGeneration !== threadSelectionGenerationRef.current) return;
|
|
472
473
|
const resolvedAgentId = agentIdFromBootstrap(result, preferredAgentId);
|
|
@@ -577,7 +578,8 @@ function useAgentChatRuntime(options) {
|
|
|
577
578
|
return {
|
|
578
579
|
agent: agentOverride || { name: bootstrap?.deployment.name || "Agent" },
|
|
579
580
|
inputContract: bootstrap?.features.inputs || null,
|
|
580
|
-
allowFeedback: Boolean(bootstrap?.capabilities.includes("feedback.write")),
|
|
581
|
+
allowFeedback: Boolean(bootstrap?.capabilities.includes("feedback.write")) && !controller.activeThread?.read_only,
|
|
582
|
+
isReadOnly: controller.activeThread?.read_only === true,
|
|
581
583
|
backgroundError: bootstrap && bootstrapError || controller.backgroundError?.cause || null,
|
|
582
584
|
bootstrap,
|
|
583
585
|
capabilities: bootstrap?.capabilities || [],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/use-agent-chat-runtime.ts","../../src/runtime/use-agent-chat-hitl.ts","../../src/runtime/use-delegation-tasks.ts"],"sourcesContent":["import type {\n AgentClient,\n Agents24ClientError,\n ClientBootstrap,\n EffectiveResourcePolicy,\n HitlResponse,\n PortableUpload,\n} from \"@agents24/client\";\nimport type { ContextCompression, ContextWindow } from \"@agents24/client/protocol\";\nimport {\n type AgentChatController,\n type ChatAttachment,\n type ChatHitlPart,\n type HitlSubmissionOptions,\n type HitlSubmissionState,\n useAgentAttachments,\n useAgentChat,\n} from \"@agents24/react\";\nimport * as React from \"react\";\n\nimport { useAgentChatHitl } from \"./use-agent-chat-hitl\";\nimport type { ChatMcpOauthCompletion } from \"../types\";\nimport { validateAgentChatSubmission } from \"./input-contract\";\n\nexport type AgentChatRuntimeAgent = {\n name: string;\n description?: string | null;\n handle?: string | null;\n avatarUrl?: string | null;\n};\n\nexport type AgentChatRuntimeModel = {\n id: string;\n label: string;\n};\n\nexport type AgentChatRuntimeAgentOption = { id: string; label: string };\n\nexport type AgentChatRuntimeViewState =\n | \"ready\"\n | \"loading\"\n | \"uploading\"\n | \"streaming\"\n | \"reconnecting\"\n | \"paused\"\n | \"cancelling\"\n | \"cancelled\"\n | \"offline\"\n | \"denied\"\n | \"quota\"\n | \"failed\"\n | \"expired\";\n\nexport type AgentChatRuntimeConnectionState =\n | \"connected\"\n | \"connecting\"\n | \"reconnecting\"\n | \"offline\"\n | \"expired\";\n\nexport type AgentChatThreadChangeReason = \"created\" | \"opened\" | \"new\" | \"deleted\";\n\nexport type AgentChatActiveThreadChange = {\n threadId: string | null;\n reason: AgentChatThreadChangeReason;\n};\n\nexport type AgentChatActiveThreadChangeHandler = (\n change: AgentChatActiveThreadChange,\n) => void;\n\nexport type AgentChatMcpAuthorizationCompletion = (input: {\n completion: ChatMcpOauthCompletion;\n codeVerifier: string;\n serverId: string;\n}) => Promise<void>;\n\nexport type AgentChatRuntimeSubmit = {\n text: string;\n files?: readonly PortableUpload[];\n attachments?: ChatAttachment[];\n attachmentIds?: readonly string[];\n};\n\nexport type AgentChatRuntimeHitlActionState = Omit<HitlSubmissionState, \"status\"> & {\n status: HitlSubmissionState[\"status\"] | \"connecting\" | \"resuming\";\n};\n\nexport type UseAgentChatRuntimeOptions = {\n activeThreadId?: string | null;\n agent?: AgentChatRuntimeAgent;\n client: AgentClient;\n completeMcpAuthorization?: AgentChatMcpAuthorizationCompletion;\n mcpRedirectUri?: string;\n modelId?: string | null;\n onActiveThreadIdChange?: AgentChatActiveThreadChangeHandler;\n onModelChange?: (modelId: string) => void;\n};\n\nexport type AgentChatRuntime = {\n agent: AgentChatRuntimeAgent;\n inputContract: ClientBootstrap[\"features\"][\"inputs\"] | null;\n allowFeedback: boolean;\n backgroundError: unknown;\n bootstrap: ClientBootstrap | null;\n capabilities: readonly string[];\n agentId: string | null;\n agents: AgentChatRuntimeAgentOption[];\n changeAgent(agentId: string): Promise<void>;\n changeModel(modelId: string): void;\n clearOperationError(): void;\n connectionState: AgentChatRuntimeConnectionState;\n contextWindow: ContextWindow | null;\n contextCompression: ContextCompression | null;\n controller: AgentChatController;\n deleteThread(threadId: string): Promise<void>;\n errorMessage: string | null;\n fatalError: unknown;\n getHitlActionState(part: ChatHitlPart): AgentChatRuntimeHitlActionState | undefined;\n isBootstrapping: boolean;\n isChangingAgent: boolean;\n isSubmitting: boolean;\n isUploading: boolean;\n modelId: string | null;\n models: AgentChatRuntimeModel[];\n newThread(): void;\n onHitlAction(part: ChatHitlPart, response: HitlResponse, options?: HitlSubmissionOptions): Promise<void>;\n openThread(threadId: string): Promise<void>;\n operationError: unknown;\n retryBootstrap(): Promise<void>;\n resolveAttachmentContent(\n attachment: ChatAttachment,\n signal: AbortSignal,\n ): Promise<{ url: string; validUntil: string | null }>;\n state: AgentChatRuntimeViewState;\n submit(input: AgentChatRuntimeSubmit): Promise<void>;\n};\n\ntype PendingThreadTransition = {\n reason: \"opened\" | \"deleted\";\n value: string | null;\n};\n\nexport function agentChatRuntimeStateFromError(error: unknown): AgentChatRuntimeViewState {\n const typed = error as Partial<Agents24ClientError> | null;\n if (typed?.kind === \"authentication\") return \"expired\";\n if (typed?.kind === \"authorization\") return \"denied\";\n if (typed?.kind === \"quota\" || typed?.kind === \"rate_limit\") return \"quota\";\n if (typed?.kind === \"network\") return \"offline\";\n return \"failed\";\n}\n\nexport function agentChatRuntimeErrorMessage(error: unknown): string | null {\n if (!error) return null;\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function canChangeAgentRuntime(\n runState: AgentChatController[\"runState\"],\n activeRunId: string | null,\n): boolean {\n return !activeRunId && ![\"uploading\", \"streaming\", \"reconnecting\", \"paused\", \"cancelling\"].includes(runState);\n}\n\nexport function agentIdFromBootstrap(\n bootstrap: ClientBootstrap,\n requestedAgentId: string | null,\n): string | null {\n const feature = bootstrap.features.agents;\n if (!feature) return null;\n return feature.options.some((item) => item.id === requestedAgentId)\n ? requestedAgentId\n : feature.default_id || null;\n}\n\nexport function modelsFromAgentChatBootstrap(bootstrap: ClientBootstrap): {\n defaultModelId: string | null;\n models: AgentChatRuntimeModel[];\n} {\n const modelFeatures = bootstrap.features.models;\n const selectable = bootstrap.capabilities.includes(\"models.select\") && modelFeatures?.selectable === true;\n if (!selectable) return { defaultModelId: null, models: [] };\n const models = Array.isArray(modelFeatures.options)\n ? modelFeatures.options.flatMap((option) => (\n typeof option?.id === \"string\" && option.id.trim()\n ? [{ id: option.id, label: typeof option.label === \"string\" && option.label.trim() ? option.label : option.id }]\n : []\n ))\n : [];\n const configuredDefault = models.some((model) => model.id === modelFeatures.default_id)\n ? modelFeatures.default_id\n : null;\n return {\n defaultModelId: configuredDefault,\n models,\n };\n}\n\nfunction modelsFromEffectivePolicy(policy: EffectiveResourcePolicy): {\n defaultModelId: string | null;\n models: AgentChatRuntimeModel[];\n} {\n const models = policy.model_selection.selectable\n ? policy.model_selection.options.map((option) => ({ id: option.id, label: option.label }))\n : [];\n return {\n defaultModelId: models.some((model) => model.id === policy.model_selection.default_id)\n ? policy.model_selection.default_id\n : null,\n models,\n };\n}\n\nexport function useAgentChatRuntime(options: UseAgentChatRuntimeOptions): AgentChatRuntime {\n const {\n activeThreadId,\n agent: agentOverride,\n client,\n completeMcpAuthorization,\n mcpRedirectUri,\n modelId,\n onActiveThreadIdChange,\n onModelChange,\n } = options;\n const controller = useAgentChat(\n activeThreadId === undefined ? { client } : { activeThreadId, client },\n );\n const attachments = useAgentAttachments();\n const bootstrapOwnerRef = React.useRef<AgentClient | null>(null);\n const [bootstrapState, setBootstrap] = React.useState<ClientBootstrap | null>(null);\n const bootstrap = bootstrapOwnerRef.current === client ? bootstrapState : null;\n const bootstrapRef = React.useRef<ClientBootstrap | null>(bootstrap);\n bootstrapRef.current = bootstrap;\n const [effectivePolicyState, setEffectivePolicy] = React.useState<EffectiveResourcePolicy | null>(null);\n const effectivePolicy = bootstrapOwnerRef.current === client ? effectivePolicyState : null;\n const [isBootstrapping, setIsBootstrapping] = React.useState(true);\n const [bootstrapError, setBootstrapError] = React.useState<unknown>(null);\n const [localOperationError, setLocalOperationError] = React.useState<unknown>(null);\n const [selectedModelId, setSelectedModelId] = React.useState<string | null>(modelId ?? null);\n const selectedModelIdRef = React.useRef<string | null>(selectedModelId);\n selectedModelIdRef.current = selectedModelId;\n const [selectedAgentId, setSelectedAgentId] = React.useState<string | null>(null);\n const selectedAgentIdRef = React.useRef<string | null>(null);\n selectedAgentIdRef.current = selectedAgentId;\n const [isChangingAgent, setIsChangingAgent] = React.useState(false);\n const agentChangePromiseRef = React.useRef<Promise<void> | null>(null);\n const [isSubmitting, setIsSubmitting] = React.useState(false);\n const submitPromiseRef = React.useRef<Promise<void> | null>(null);\n\n const mountedRef = React.useRef(true);\n const clientRef = React.useRef(client);\n clientRef.current = client;\n const bootstrapRetryRef = React.useRef(0);\n const bootstrapPromiseRef = React.useRef<{ client: AgentClient; promise: Promise<void> } | null>(null);\n React.useEffect(() => {\n mountedRef.current = true;\n return () => { mountedRef.current = false; };\n }, []);\n\n const previousControlledThreadRef = React.useRef(activeThreadId);\n const threadSelectionGenerationRef = React.useRef(0);\n const controlledSyncTargetRef = React.useRef<{ value: string | null } | null>(null);\n const previousControllerThreadRef = React.useRef(controller.activeThreadId);\n const pendingThreadTransitionRef = React.useRef<PendingThreadTransition | null>(null);\n const lastReportedThreadRef = React.useRef<string | null>(activeThreadId ?? controller.activeThreadId);\n if (activeThreadId !== previousControlledThreadRef.current) {\n threadSelectionGenerationRef.current += 1;\n previousControlledThreadRef.current = activeThreadId;\n if (activeThreadId !== undefined) {\n controlledSyncTargetRef.current = { value: activeThreadId };\n lastReportedThreadRef.current = activeThreadId;\n }\n }\n\n const reportActiveThread = React.useCallback((\n threadId: string | null,\n reason: AgentChatThreadChangeReason,\n ) => {\n if (lastReportedThreadRef.current === threadId) return;\n lastReportedThreadRef.current = threadId;\n onActiveThreadIdChange?.({ threadId, reason });\n }, [onActiveThreadIdChange]);\n\n const retryBootstrap = React.useCallback((): Promise<void> => {\n if (bootstrapPromiseRef.current?.client === client) return bootstrapPromiseRef.current.promise;\n const requestClient = client;\n const request = (async () => {\n if (mountedRef.current) {\n const identityChanged = bootstrapOwnerRef.current !== requestClient;\n setIsBootstrapping(identityChanged || !bootstrapRef.current);\n setBootstrapError(null);\n if (identityChanged) {\n setBootstrap(null);\n setEffectivePolicy(null);\n setSelectedAgentId(null);\n setSelectedModelId(null);\n }\n }\n try {\n const requestedAgentId = selectedAgentIdRef.current;\n const result = await requestClient.bootstrap({ agentId: requestedAgentId || undefined });\n if (!mountedRef.current || clientRef.current !== requestClient) return;\n bootstrapOwnerRef.current = requestClient;\n bootstrapRetryRef.current = 0;\n setBootstrap(result);\n const agentFeature = result.features.agents;\n const resolvedAgentId = agentIdFromBootstrap(result, requestedAgentId);\n setSelectedAgentId(resolvedAgentId);\n const entitlement = agentFeature ? null : await requestClient.resourcePolicies.getEffective();\n if (!mountedRef.current || clientRef.current !== requestClient) return;\n setEffectivePolicy(entitlement);\n const availableModels = entitlement ? modelsFromEffectivePolicy(entitlement) : modelsFromAgentChatBootstrap(result);\n if (modelId === undefined) {\n setSelectedModelId((current) => availableModels.models.some((item) => item.id === current)\n ? current\n : availableModels.defaultModelId);\n }\n void controller.refreshThreads().catch(() => undefined);\n } catch (error) {\n if (mountedRef.current && clientRef.current === requestClient) {\n const status = (error as Agents24ClientError)?.status;\n if (status === 401 || status === 403 || status === 404) {\n setBootstrap(null);\n setEffectivePolicy(null);\n bootstrapOwnerRef.current = null;\n }\n setBootstrapError(error);\n }\n } finally {\n if (mountedRef.current && clientRef.current === requestClient) setIsBootstrapping(false);\n }\n })();\n bootstrapPromiseRef.current = { client: requestClient, promise: request };\n void request.finally(() => {\n if (bootstrapPromiseRef.current?.promise === request) bootstrapPromiseRef.current = null;\n });\n return request;\n }, [client, controller.refreshThreads, modelId]);\n\n React.useEffect(() => {\n if (!bootstrapError || bootstrapRetryRef.current >= 4) return;\n const error = bootstrapError as Agents24ClientError;\n if (!(error.retryable || error.kind === \"network\" || (error.status || 0) >= 500)) return;\n const attempt = bootstrapRetryRef.current++;\n const hint = error.retryAfterMs;\n const delay = Math.max(500 * 2 ** attempt + Math.random() * 250,\n typeof hint === \"number\" && Number.isFinite(hint) && hint >= 0 ? Math.min(hint, 60_000) : 0);\n const timer = setTimeout(() => { void retryBootstrap(); }, delay);\n return () => clearTimeout(timer);\n }, [bootstrapError, retryBootstrap]);\n\n const refreshEffectivePolicy = React.useCallback(async () => {\n if (bootstrap?.features.agents) {\n const refreshed = await client.bootstrap({ agentId: selectedAgentIdRef.current || undefined });\n if (!mountedRef.current || clientRef.current !== client) return;\n setBootstrap(refreshed);\n const available = modelsFromAgentChatBootstrap(refreshed);\n setSelectedModelId((current) => available.models.some((item) => item.id === current)\n ? current\n : available.defaultModelId);\n return;\n }\n const entitlement = await client.resourcePolicies.getEffective();\n if (!mountedRef.current || clientRef.current !== client) return;\n setEffectivePolicy(entitlement);\n if (modelId === undefined) {\n const available = modelsFromEffectivePolicy(entitlement);\n setSelectedModelId((current) => available.models.some((item) => item.id === current)\n ? current\n : available.defaultModelId);\n }\n }, [bootstrap, client, modelId]);\n\n React.useEffect(() => {\n void retryBootstrap();\n }, [retryBootstrap]);\n\n React.useEffect(() => {\n if (modelId !== undefined) setSelectedModelId(modelId);\n }, [modelId]);\n\n React.useEffect(() => {\n if (controlledSyncTargetRef.current?.value === null && controller.activeThreadId) {\n controller.startNewThread();\n }\n }, [activeThreadId, controller.activeThreadId, controller.startNewThread]);\n\n React.useEffect(() => {\n const previous = previousControllerThreadRef.current;\n const current = controller.activeThreadId;\n previousControllerThreadRef.current = current;\n const controlledTarget = controlledSyncTargetRef.current;\n if (controlledTarget) {\n if (current === controlledTarget.value) controlledSyncTargetRef.current = null;\n return;\n }\n const pendingTransition = pendingThreadTransitionRef.current;\n if (pendingTransition && current === pendingTransition.value) return;\n if (previous === null && current !== null) reportActiveThread(current, \"created\");\n }, [activeThreadId, controller.activeThreadId, reportActiveThread]);\n\n const clearOperationError = React.useCallback(() => {\n setLocalOperationError(null);\n controller.clearOperationError();\n }, [controller.clearOperationError]);\n\n const submit = React.useCallback((input: AgentChatRuntimeSubmit): Promise<void> => {\n if (submitPromiseRef.current) return submitPromiseRef.current;\n clearOperationError();\n setIsSubmitting(true);\n const request = (async () => {\n try {\n await agentChangePromiseRef.current;\n const activeBootstrap = bootstrapRef.current;\n if (!activeBootstrap) throw new Error(\"The agent input contract is unavailable.\");\n const retained = (input.attachments || []).filter((attachment) => input.attachmentIds?.includes(attachment.id || \"\"));\n const inputError = validateAgentChatSubmission(activeBootstrap.features.inputs, input.text, [\n ...(input.files || []),\n ...retained.map((attachment) => ({ data: new Uint8Array(), mediaType: attachment.mediaType || \"application/octet-stream\" })),\n ]);\n if (inputError) throw new Error(inputError);\n await controller.submit({\n text: input.text,\n attachments: input.attachments,\n uploads: input.files,\n attachmentIds: input.attachmentIds,\n requestedModelId: selectedModelIdRef.current || undefined,\n requestedAgentId: selectedAgentIdRef.current || undefined,\n });\n } catch (error) {\n setLocalOperationError(error);\n const typed = error as Partial<Agents24ClientError>;\n if (typed.kind === \"quota\" || typed.kind === \"authorization\") {\n await refreshEffectivePolicy().catch(() => undefined);\n }\n throw error;\n } finally {\n setIsSubmitting(false);\n }\n })();\n submitPromiseRef.current = request;\n const clearRequest = () => {\n if (submitPromiseRef.current === request) submitPromiseRef.current = null;\n };\n void request.then(clearRequest, clearRequest);\n return request;\n }, [bootstrap, clearOperationError, controller.activeThreadId, controller.submit, refreshEffectivePolicy]);\n\n const { onHitlAction, getHitlActionState } = useAgentChatHitl({\n client, bootstrap, controller, selectionGeneration: threadSelectionGenerationRef,\n completeMcpAuthorization, mcpRedirectUri, clearOperationError, onError: setLocalOperationError,\n });\n\n const newThread = React.useCallback(() => {\n threadSelectionGenerationRef.current += 1;\n clearOperationError();\n pendingThreadTransitionRef.current = null;\n reportActiveThread(null, \"new\");\n controller.startNewThread();\n }, [clearOperationError, controller.startNewThread, reportActiveThread]);\n\n const openThread = React.useCallback(async (threadId: string) => {\n const requestGeneration = ++threadSelectionGenerationRef.current;\n clearOperationError();\n pendingThreadTransitionRef.current = { reason: \"opened\", value: threadId };\n try {\n const detail = await client.threads.get({ threadId });\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n const preferredAgentId = detail.runtime_selection?.agent_alias || detail.runtime_selection?.agent_id || null;\n if (preferredAgentId) {\n const result = await client.bootstrap({ agentId: preferredAgentId });\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n const resolvedAgentId = agentIdFromBootstrap(result, preferredAgentId);\n setBootstrap(result);\n setEffectivePolicy(null);\n setSelectedAgentId(resolvedAgentId);\n const available = modelsFromAgentChatBootstrap(result);\n const preferredModelId = detail.runtime_selection?.model_id || null;\n setSelectedModelId(available.models.some((item) => item.id === preferredModelId)\n ? preferredModelId\n : available.defaultModelId);\n }\n await controller.openThread(threadId);\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n reportActiveThread(threadId, \"opened\");\n } catch (error) {\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n setLocalOperationError(error);\n throw error;\n } finally {\n if (requestGeneration === threadSelectionGenerationRef.current) pendingThreadTransitionRef.current = null;\n }\n }, [clearOperationError, client, controller.openThread, reportActiveThread]);\n\n const deleteThread = React.useCallback(async (threadId: string) => {\n clearOperationError();\n const wasActive = controller.activeThreadId === threadId;\n if (wasActive) threadSelectionGenerationRef.current += 1;\n if (wasActive) pendingThreadTransitionRef.current = { reason: \"deleted\", value: null };\n try {\n await controller.deleteThread(threadId);\n if (wasActive) reportActiveThread(null, \"deleted\");\n } catch (error) {\n setLocalOperationError(error);\n throw error;\n } finally {\n if (wasActive && pendingThreadTransitionRef.current?.reason === \"deleted\") {\n pendingThreadTransitionRef.current = null;\n }\n }\n }, [clearOperationError, controller.activeThreadId, controller.deleteThread, reportActiveThread]);\n\n const changeModel = React.useCallback((nextModelId: string) => {\n if (modelId === undefined) setSelectedModelId(nextModelId);\n onModelChange?.(nextModelId);\n if (controller.activeThreadId && selectedAgentId && client.threads.setRuntimeSelection) {\n void client.threads.setRuntimeSelection({\n threadId: controller.activeThreadId,\n preferredAgentId: selectedAgentId,\n preferredModelId: nextModelId,\n }).catch(setLocalOperationError);\n }\n }, [client.threads, controller.activeThreadId, modelId, onModelChange, selectedAgentId]);\n\n const resolveAttachmentContent = React.useCallback(async (\n attachment: ChatAttachment,\n signal: AbortSignal,\n ) => {\n const attachmentId = typeof attachment.id === \"string\" ? attachment.id.trim() : \"\";\n if (!attachmentId) throw new Error(\"Attachment content identity is unavailable.\");\n const access = await attachments.createContentAccess({\n attachmentId,\n disposition: \"inline\",\n signal,\n });\n return { url: access.url, validUntil: access.valid_until || null };\n }, [attachments.createContentAccess]);\n\n const changeAgent = React.useCallback((nextAgentId: string): Promise<void> => {\n if (agentChangePromiseRef.current) return agentChangePromiseRef.current;\n if (\n nextAgentId === selectedAgentIdRef.current\n || !canChangeAgentRuntime(controller.runState, controller.activeRunId)\n ) return Promise.resolve();\n clearOperationError();\n setIsChangingAgent(true);\n const request = (async () => {\n try {\n const result = await client.bootstrap({ agentId: nextAgentId });\n const resolvedAgentId = agentIdFromBootstrap(result, nextAgentId);\n if (!resolvedAgentId) throw new Error(\"The requested Agent is no longer available.\");\n const available = modelsFromAgentChatBootstrap(result);\n const currentModelId = selectedModelIdRef.current;\n const nextModelId = available.models.some((item) => item.id === currentModelId)\n ? currentModelId\n : available.defaultModelId;\n if (controller.activeThreadId && client.threads.setRuntimeSelection) {\n const persisted = await client.threads.setRuntimeSelection({\n threadId: controller.activeThreadId,\n preferredAgentId: resolvedAgentId,\n preferredModelId: nextModelId,\n });\n selectedModelIdRef.current = persisted.runtime_selection.model_id;\n setSelectedModelId(persisted.runtime_selection.model_id);\n } else {\n selectedModelIdRef.current = nextModelId;\n setSelectedModelId(nextModelId);\n }\n selectedAgentIdRef.current = resolvedAgentId;\n bootstrapRef.current = result;\n setSelectedAgentId(resolvedAgentId);\n setBootstrap(result);\n setEffectivePolicy(null);\n } catch (error) {\n setLocalOperationError(error);\n throw error;\n }\n })();\n agentChangePromiseRef.current = request;\n const clearRequest = () => {\n if (agentChangePromiseRef.current === request) agentChangePromiseRef.current = null;\n if (mountedRef.current) setIsChangingAgent(false);\n };\n void request.then(clearRequest, clearRequest);\n return request;\n }, [clearOperationError, client, controller.activeRunId, controller.activeThreadId, controller.runState]);\n\n const modelOptions = effectivePolicy\n ? modelsFromEffectivePolicy(effectivePolicy).models\n : bootstrap\n ? modelsFromAgentChatBootstrap(bootstrap).models\n : [];\n const fatalError = (!bootstrap ? bootstrapError : null) || controller.error;\n const operationError = localOperationError || controller.operationError?.cause;\n const state: AgentChatRuntimeViewState = isBootstrapping\n ? \"loading\"\n : fatalError\n ? agentChatRuntimeStateFromError(fatalError)\n : controller.runState === \"uploading\"\n ? \"uploading\"\n : controller.runState === \"streaming\"\n ? \"streaming\"\n : controller.runState === \"reconnecting\"\n ? \"reconnecting\"\n : controller.runState === \"paused\"\n ? \"paused\"\n : controller.runState === \"cancelling\"\n ? \"cancelling\"\n : controller.runState === \"cancelled\"\n ? \"cancelled\"\n : \"ready\";\n const connectionState: AgentChatRuntimeConnectionState = bootstrapError && bootstrap ? \"reconnecting\" : state === \"offline\"\n ? \"offline\"\n : state === \"expired\"\n ? \"expired\"\n : state === \"reconnecting\"\n ? \"reconnecting\"\n : isBootstrapping\n ? \"connecting\"\n : \"connected\";\n return {\n agent: agentOverride || { name: bootstrap?.deployment.name || \"Agent\" },\n inputContract: bootstrap?.features.inputs || null,\n allowFeedback: Boolean(bootstrap?.capabilities.includes(\"feedback.write\")),\n backgroundError: (bootstrap && bootstrapError) || controller.backgroundError?.cause || null,\n bootstrap,\n capabilities: bootstrap?.capabilities || [],\n agentId: bootstrap ? selectedAgentId : null,\n agents: bootstrap?.features.agents?.options.map((item) => ({ id: item.id, label: item.label })) || [],\n changeAgent,\n changeModel,\n clearOperationError,\n connectionState,\n contextWindow: controller.contextWindow,\n contextCompression: controller.contextCompression,\n controller,\n deleteThread,\n errorMessage: agentChatRuntimeErrorMessage(fatalError || operationError),\n fatalError,\n getHitlActionState,\n isBootstrapping,\n isChangingAgent,\n isSubmitting: isSubmitting || controller.isSubmitting,\n isUploading: attachments.isUploading || controller.runState === \"uploading\",\n modelId: bootstrap ? selectedModelId : null,\n models: modelOptions,\n newThread,\n onHitlAction,\n openThread,\n operationError,\n retryBootstrap,\n resolveAttachmentContent,\n state,\n submit,\n };\n}\n","import type { AgentClient, ClientBootstrap, HitlResponse } from \"@agents24/client\";\nimport { type AgentChatController, type ChatHitlPart, type HitlSubmissionOptions, useAgentMcp } from \"@agents24/react\";\nimport * as React from \"react\";\nimport { browserChatCrypto, createMcpPkceProof, validateMcpCallbackResult, waitForMcpOauthComplete } from \"../mcp-oauth\";\nimport type { AgentChatMcpAuthorizationCompletion, AgentChatRuntimeHitlActionState } from \"./use-agent-chat-runtime\";\n\ntype HitlOptions = {\n client: AgentClient;\n bootstrap: ClientBootstrap | null;\n controller: AgentChatController;\n selectionGeneration: React.MutableRefObject<number>;\n completeMcpAuthorization?: AgentChatMcpAuthorizationCompletion;\n mcpRedirectUri?: string;\n clearOperationError(): void;\n onError(error: unknown): void;\n};\n\ntype HitlOperation = {\n abort: AbortController;\n isCurrent(): boolean;\n phase: \"connecting\" | \"resuming\";\n popup?: Window;\n};\n\nfunction detach(operation: HitlOperation) {\n operation.abort.abort();\n operation.popup?.close();\n}\n\nexport function useAgentChatHitl(options: HitlOptions) {\n const mcp = useAgentMcp();\n const latest = React.useRef(options);\n latest.current = options;\n const mounted = React.useRef(true);\n const operations = React.useRef(new Map<string, HitlOperation>());\n const [states, setStates] = React.useState<Record<string, AgentChatRuntimeHitlActionState>>({});\n\n React.useEffect(() => {\n mounted.current = true;\n const active = operations.current;\n return () => {\n mounted.current = false;\n for (const operation of active.values()) detach(operation);\n active.clear();\n };\n }, []);\n React.useEffect(() => {\n for (const [key, operation] of operations.current) {\n if (operation.isCurrent()) continue;\n detach(operation);\n operations.current.delete(key);\n setStates((current) => {\n const next = { ...current };\n delete next[key];\n return next;\n });\n }\n });\n React.useEffect(() => { setStates({}); }, [options.client, options.controller.activeThreadId]);\n\n const onHitlAction = React.useCallback(async (part: ChatHitlPart, response: HitlResponse, submission?: HitlSubmissionOptions) => {\n const captured = latest.current;\n const { controller, client, bootstrap, selectionGeneration } = captured;\n const generation = selectionGeneration.current;\n const threadId = controller.activeThreadId;\n const runId = part.runId || controller.messages.find((message) => message.parts.some(candidate => candidate.id === part.id))?.runId || controller.activeRunId;\n const key = `${generation}:${threadId}:${runId}:${part.interruptId || part.id}`;\n if (part.hitlKind !== \"mcp_auth\" || response.action !== \"connect\") {\n captured.clearOperationError();\n // All normal decisions, including host preparation, have one headless owner.\n return controller.resumeHitl(part, response, submission).catch(error => {\n const current = latest.current;\n if (mounted.current && current.client === client && current.selectionGeneration.current === generation\n && current.controller.activeThreadId === threadId) captured.onError(error);\n throw error;\n });\n }\n const previous = operations.current.get(key);\n if (previous?.isCurrent()) return;\n if (previous) { detach(previous); operations.current.delete(key); }\n const operation: HitlOperation = {\n abort: new AbortController(),\n phase: part.hitlKind === \"mcp_auth\" && response.action === \"connect\" ? \"connecting\" : \"resuming\",\n isCurrent() {\n const current = latest.current;\n return mounted.current && !operation.abort.signal.aborted\n && current.client === client && current.selectionGeneration.current === generation\n && current.controller.activeThreadId === threadId\n && (!current.controller.activeRunId || current.controller.activeRunId === runId)\n && ![\"cancelling\", \"cancelled\", \"failed\", \"completed\"].includes(current.controller.runState)\n && (operation.phase === \"resuming\" || current.controller.messages.some((message) =>\n message.runId === runId && message.parts.some((candidate) => candidate.type === \"hitl\"\n && candidate.interruptId === part.interruptId && candidate.status === \"pending\")));\n },\n };\n if (!operation.isCurrent()) return;\n captured.clearOperationError();\n operations.current.set(key, operation);\n setStates((current) => ({ ...current, [key]: { action: response.action, status: operation.phase } }));\n try {\n if (operation.phase === \"connecting\") {\n if (!runId) throw new Error(\"MCP authorization is missing its paused run.\");\n if (!bootstrap) throw new Error(\"MCP authorization requires runtime bootstrap.\");\n if (!captured.mcpRedirectUri) throw new Error(\"mcpRedirectUri is required for MCP Connect.\");\n const serverId = String(part.presentation.server_id || \"\").trim();\n if (!serverId) throw new Error(\"MCP authorization is missing its server identity.\");\n const serverEmbed = bootstrap.authentication.modes.includes(\"server_embed\");\n const popupNonce = browserChatCrypto().randomUUID();\n // Open within the click before awaiting crypto or the network.\n const popup = window.open(\"about:blank\", \"agents24-mcp\", \"popup,width=560,height=720\");\n if (!popup) throw new Error(\"Allow popups to connect this MCP account.\");\n operation.popup = popup;\n popup.document.title = \"Connecting to MCP\";\n popup.document.body.textContent = \"Opening secure connection…\";\n const proof = await createMcpPkceProof();\n if (!operation.isCurrent()) return;\n const started = await mcp.startAuthorization({\n runId, serverId, interruptId: part.interruptId, redirectUri: captured.mcpRedirectUri,\n popupNonce, codeChallenge: proof.challenge, signal: operation.abort.signal,\n });\n if (!operation.isCurrent()) return;\n if (!started.callback_origin) throw new Error(\"MCP authorization did not return a callback origin.\");\n const completionPromise = waitForMcpOauthComplete({\n popup, callbackOrigin: started.callback_origin, popupNonce, serverId,\n runId, interruptId: part.interruptId, signal: operation.abort.signal,\n requireConnectionId: serverEmbed || Boolean(captured.completeMcpAuthorization),\n });\n // Ensure a navigation exception cannot leave a rejected waiter unobserved.\n void completionPromise.catch(() => undefined);\n popup.location.replace(started.authorization_url);\n const completion = await completionPromise;\n if (!operation.isCurrent()) return;\n if (captured.completeMcpAuthorization) {\n await captured.completeMcpAuthorization({ completion, codeVerifier: proof.verifier, serverId });\n } else if (serverEmbed) {\n validateMcpCallbackResult({ server_id: completion.serverId, connection_id: completion.connectionId || \"\" }, serverId);\n } else {\n const redeemed = await mcp.redeemCallback({\n code: completion.code, codeVerifier: proof.verifier, signal: operation.abort.signal,\n });\n if (!operation.isCurrent()) return;\n validateMcpCallbackResult(redeemed, serverId);\n }\n popup.close();\n }\n if (!operation.isCurrent()) return;\n operation.phase = \"resuming\";\n setStates((current) => ({ ...current, [key]: { action: response.action, status: \"resuming\" } }));\n await controller.resumeHitl(part, response, submission);\n } catch (error) {\n if (!operation.isCurrent()) return;\n captured.onError(error);\n setStates((current) => ({ ...current, [key]: {\n action: response.action, status: \"error\", error: error instanceof Error ? error.message : String(error),\n } }));\n throw error;\n } finally {\n const ownsState = operation.isCurrent();\n // Abort the waiter and any in-flight transport, and always release the popup.\n detach(operation);\n if (operations.current.get(key) === operation) {\n operations.current.delete(key);\n if (ownsState) setStates((current) => {\n if (current[key]?.status === \"error\") return current;\n const next = { ...current };\n delete next[key];\n return next;\n });\n }\n }\n }, [mcp]);\n\n return { onHitlAction, getHitlActionState: (part: ChatHitlPart) => {\n const { controller, selectionGeneration } = latest.current;\n const runId = part.runId || controller.messages.find(message => message.parts.some(candidate => candidate.id === part.id))?.runId || controller.activeRunId;\n return controller.getHitlSubmissionState(part)\n || states[`${selectionGeneration.current}:${controller.activeThreadId}:${runId}:${part.interruptId || part.id}`];\n } };\n}\n","import * as React from \"react\";\nimport type { DelegationEvents, DelegationTask } from \"../generated/delegation-types\";\n\nexport type DelegationTaskSource = {\n events(input: { threadId: string; after: number; signal: AbortSignal }): Promise<DelegationEvents>;\n};\n\n/** Authoritative snapshots keep task discovery alive after the run stream ends. */\nexport function useDelegationTasks({ threadId, source, pollIntervalMs = 2000 }: {\n threadId: string | null;\n source: DelegationTaskSource;\n pollIntervalMs?: number;\n}) {\n const [state, setState] = React.useState<{\n threadId: string | null; tasks: DelegationTask[]; error: unknown; loading: boolean;\n }>({ threadId: null, tasks: [], error: null, loading: false });\n const [revision, refresh] = React.useReducer((value: number) => value + 1, 0);\n React.useEffect(() => {\n if (!threadId) {\n setState({ threadId: null, tasks: [], error: null, loading: false });\n return;\n }\n const controller = new AbortController();\n let cursor = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let failures = 0;\n setState((previous) => ({ threadId, tasks: previous.threadId === threadId ? previous.tasks : [],\n error: null, loading: true }));\n const poll = async () => {\n try {\n const result = await source.events({ threadId, after: cursor, signal: controller.signal });\n if (controller.signal.aborted) return;\n cursor = result.cursor;\n failures = 0;\n setState({ threadId, tasks: result.snapshot, error: null, loading: false });\n } catch (error) {\n if (controller.signal.aborted) return;\n failures += 1;\n setState((previous) => ({ ...previous, error, loading: false }));\n }\n if (!controller.signal.aborted) {\n timer = setTimeout(poll, Math.min(30000, Math.max(250, pollIntervalMs) * 2 ** Math.min(failures, 4)));\n }\n };\n void poll();\n return () => {\n controller.abort();\n if (timer) clearTimeout(timer);\n };\n }, [threadId, source, pollIntervalMs, revision]);\n return { tasks: state.threadId === threadId ? state.tasks : [],\n error: state.threadId === threadId ? state.error : null,\n loading: Boolean(threadId) && (state.threadId !== threadId || state.loading), refresh };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AASA;AAAA,EAME;AAAA,EACA;AAAA,OACK;AACP,YAAYA,YAAW;;;ACjBvB,SAAkF,mBAAmB;AACrG,YAAY,WAAW;AAsBvB,SAAS,OAAO,WAA0B;AACxC,YAAU,MAAM,MAAM;AACtB,YAAU,OAAO,MAAM;AACzB;AAEO,SAAS,iBAAiB,SAAsB;AACrD,QAAM,MAAM,YAAY;AACxB,QAAM,SAAe,aAAO,OAAO;AACnC,SAAO,UAAU;AACjB,QAAM,UAAgB,aAAO,IAAI;AACjC,QAAM,aAAmB,aAAO,oBAAI,IAA2B,CAAC;AAChE,QAAM,CAAC,QAAQ,SAAS,IAAU,eAA0D,CAAC,CAAC;AAE9F,EAAM,gBAA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3,"sources":["../../src/runtime/use-agent-chat-runtime.ts","../../src/runtime/use-agent-chat-hitl.ts","../../src/runtime/use-delegation-tasks.ts"],"sourcesContent":["import type {\n AgentClient,\n Agents24ClientError,\n ClientBootstrap,\n EffectiveResourcePolicy,\n HitlResponse,\n PortableUpload,\n} from \"@agents24/client\";\nimport type { ContextCompression, ContextWindow } from \"@agents24/client/protocol\";\nimport {\n type AgentChatController,\n type ChatAttachment,\n type ChatHitlPart,\n type HitlSubmissionOptions,\n type HitlSubmissionState,\n useAgentAttachments,\n useAgentChat,\n} from \"@agents24/react\";\nimport * as React from \"react\";\n\nimport { useAgentChatHitl } from \"./use-agent-chat-hitl\";\nimport type { ChatMcpOauthCompletion } from \"../types\";\nimport { validateAgentChatSubmission } from \"./input-contract\";\n\nexport type AgentChatRuntimeAgent = {\n name: string;\n description?: string | null;\n handle?: string | null;\n avatarUrl?: string | null;\n};\n\nexport type AgentChatRuntimeModel = {\n id: string;\n label: string;\n};\n\nexport type AgentChatRuntimeAgentOption = { id: string; label: string };\n\nexport type AgentChatRuntimeViewState =\n | \"ready\"\n | \"loading\"\n | \"uploading\"\n | \"streaming\"\n | \"reconnecting\"\n | \"paused\"\n | \"cancelling\"\n | \"cancelled\"\n | \"offline\"\n | \"denied\"\n | \"quota\"\n | \"failed\"\n | \"expired\";\n\nexport type AgentChatRuntimeConnectionState =\n | \"connected\"\n | \"connecting\"\n | \"reconnecting\"\n | \"offline\"\n | \"expired\";\n\nexport type AgentChatThreadChangeReason = \"created\" | \"opened\" | \"new\" | \"deleted\";\n\nexport type AgentChatActiveThreadChange = {\n threadId: string | null;\n reason: AgentChatThreadChangeReason;\n};\n\nexport type AgentChatActiveThreadChangeHandler = (\n change: AgentChatActiveThreadChange,\n) => void;\n\nexport type AgentChatMcpAuthorizationCompletion = (input: {\n completion: ChatMcpOauthCompletion;\n codeVerifier: string;\n serverId: string;\n}) => Promise<void>;\n\nexport type AgentChatRuntimeSubmit = {\n text: string;\n files?: readonly PortableUpload[];\n attachments?: ChatAttachment[];\n attachmentIds?: readonly string[];\n};\n\nexport type AgentChatRuntimeHitlActionState = Omit<HitlSubmissionState, \"status\"> & {\n status: HitlSubmissionState[\"status\"] | \"connecting\" | \"resuming\";\n};\n\nexport type UseAgentChatRuntimeOptions = {\n activeThreadId?: string | null;\n agent?: AgentChatRuntimeAgent;\n client: AgentClient;\n completeMcpAuthorization?: AgentChatMcpAuthorizationCompletion;\n mcpRedirectUri?: string;\n modelId?: string | null;\n onActiveThreadIdChange?: AgentChatActiveThreadChangeHandler;\n onModelChange?: (modelId: string) => void;\n};\n\nexport type AgentChatRuntime = {\n agent: AgentChatRuntimeAgent;\n inputContract: ClientBootstrap[\"features\"][\"inputs\"] | null;\n allowFeedback: boolean;\n isReadOnly: boolean;\n backgroundError: unknown;\n bootstrap: ClientBootstrap | null;\n capabilities: readonly string[];\n agentId: string | null;\n agents: AgentChatRuntimeAgentOption[];\n changeAgent(agentId: string): Promise<void>;\n changeModel(modelId: string): void;\n clearOperationError(): void;\n connectionState: AgentChatRuntimeConnectionState;\n contextWindow: ContextWindow | null;\n contextCompression: ContextCompression | null;\n controller: AgentChatController;\n deleteThread(threadId: string): Promise<void>;\n errorMessage: string | null;\n fatalError: unknown;\n getHitlActionState(part: ChatHitlPart): AgentChatRuntimeHitlActionState | undefined;\n isBootstrapping: boolean;\n isChangingAgent: boolean;\n isSubmitting: boolean;\n isUploading: boolean;\n modelId: string | null;\n models: AgentChatRuntimeModel[];\n newThread(): void;\n onHitlAction(part: ChatHitlPart, response: HitlResponse, options?: HitlSubmissionOptions): Promise<void>;\n openThread(threadId: string): Promise<void>;\n operationError: unknown;\n retryBootstrap(): Promise<void>;\n resolveAttachmentContent(\n attachment: ChatAttachment,\n signal: AbortSignal,\n ): Promise<{ url: string; validUntil: string | null }>;\n state: AgentChatRuntimeViewState;\n submit(input: AgentChatRuntimeSubmit): Promise<void>;\n};\n\ntype PendingThreadTransition = {\n reason: \"opened\" | \"deleted\";\n value: string | null;\n};\n\nexport function agentChatRuntimeStateFromError(error: unknown): AgentChatRuntimeViewState {\n const typed = error as Partial<Agents24ClientError> | null;\n if (typed?.kind === \"authentication\") return \"expired\";\n if (typed?.kind === \"authorization\") return \"denied\";\n if (typed?.kind === \"quota\" || typed?.kind === \"rate_limit\") return \"quota\";\n if (typed?.kind === \"network\") return \"offline\";\n return \"failed\";\n}\n\nexport function agentChatRuntimeErrorMessage(error: unknown): string | null {\n if (!error) return null;\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function canChangeAgentRuntime(\n runState: AgentChatController[\"runState\"],\n activeRunId: string | null,\n): boolean {\n return !activeRunId && ![\"uploading\", \"streaming\", \"reconnecting\", \"paused\", \"cancelling\"].includes(runState);\n}\n\nexport function agentIdFromBootstrap(\n bootstrap: ClientBootstrap,\n requestedAgentId: string | null,\n): string | null {\n const feature = bootstrap.features.agents;\n if (!feature) return null;\n return feature.options.some((item) => item.id === requestedAgentId)\n ? requestedAgentId\n : feature.default_id || null;\n}\n\nexport function modelsFromAgentChatBootstrap(bootstrap: ClientBootstrap): {\n defaultModelId: string | null;\n models: AgentChatRuntimeModel[];\n} {\n const modelFeatures = bootstrap.features.models;\n const selectable = bootstrap.capabilities.includes(\"models.select\") && modelFeatures?.selectable === true;\n if (!selectable) return { defaultModelId: null, models: [] };\n const models = Array.isArray(modelFeatures.options)\n ? modelFeatures.options.flatMap((option) => (\n typeof option?.id === \"string\" && option.id.trim()\n ? [{ id: option.id, label: typeof option.label === \"string\" && option.label.trim() ? option.label : option.id }]\n : []\n ))\n : [];\n const configuredDefault = models.some((model) => model.id === modelFeatures.default_id)\n ? modelFeatures.default_id\n : null;\n return {\n defaultModelId: configuredDefault,\n models,\n };\n}\n\nfunction modelsFromEffectivePolicy(policy: EffectiveResourcePolicy): {\n defaultModelId: string | null;\n models: AgentChatRuntimeModel[];\n} {\n const models = policy.model_selection.selectable\n ? policy.model_selection.options.map((option) => ({ id: option.id, label: option.label }))\n : [];\n return {\n defaultModelId: models.some((model) => model.id === policy.model_selection.default_id)\n ? policy.model_selection.default_id\n : null,\n models,\n };\n}\n\nexport function useAgentChatRuntime(options: UseAgentChatRuntimeOptions): AgentChatRuntime {\n const {\n activeThreadId,\n agent: agentOverride,\n client,\n completeMcpAuthorization,\n mcpRedirectUri,\n modelId,\n onActiveThreadIdChange,\n onModelChange,\n } = options;\n const controller = useAgentChat(\n activeThreadId === undefined ? { client } : { activeThreadId, client },\n );\n const attachments = useAgentAttachments();\n const bootstrapOwnerRef = React.useRef<AgentClient | null>(null);\n const [bootstrapState, setBootstrap] = React.useState<ClientBootstrap | null>(null);\n const bootstrap = bootstrapOwnerRef.current === client ? bootstrapState : null;\n const bootstrapRef = React.useRef<ClientBootstrap | null>(bootstrap);\n bootstrapRef.current = bootstrap;\n const [effectivePolicyState, setEffectivePolicy] = React.useState<EffectiveResourcePolicy | null>(null);\n const effectivePolicy = bootstrapOwnerRef.current === client ? effectivePolicyState : null;\n const [isBootstrapping, setIsBootstrapping] = React.useState(true);\n const [bootstrapError, setBootstrapError] = React.useState<unknown>(null);\n const [localOperationError, setLocalOperationError] = React.useState<unknown>(null);\n const [selectedModelId, setSelectedModelId] = React.useState<string | null>(modelId ?? null);\n const selectedModelIdRef = React.useRef<string | null>(selectedModelId);\n selectedModelIdRef.current = selectedModelId;\n const [selectedAgentId, setSelectedAgentId] = React.useState<string | null>(null);\n const selectedAgentIdRef = React.useRef<string | null>(null);\n selectedAgentIdRef.current = selectedAgentId;\n const [isChangingAgent, setIsChangingAgent] = React.useState(false);\n const agentChangePromiseRef = React.useRef<Promise<void> | null>(null);\n const [isSubmitting, setIsSubmitting] = React.useState(false);\n const submitPromiseRef = React.useRef<Promise<void> | null>(null);\n\n const mountedRef = React.useRef(true);\n const clientRef = React.useRef(client);\n clientRef.current = client;\n const bootstrapRetryRef = React.useRef(0);\n const bootstrapPromiseRef = React.useRef<{ client: AgentClient; promise: Promise<void> } | null>(null);\n React.useEffect(() => {\n mountedRef.current = true;\n return () => { mountedRef.current = false; };\n }, []);\n\n const previousControlledThreadRef = React.useRef(activeThreadId);\n const threadSelectionGenerationRef = React.useRef(0);\n const controlledSyncTargetRef = React.useRef<{ value: string | null } | null>(null);\n const previousControllerThreadRef = React.useRef(controller.activeThreadId);\n const pendingThreadTransitionRef = React.useRef<PendingThreadTransition | null>(null);\n const lastReportedThreadRef = React.useRef<string | null>(activeThreadId ?? controller.activeThreadId);\n if (activeThreadId !== previousControlledThreadRef.current) {\n threadSelectionGenerationRef.current += 1;\n previousControlledThreadRef.current = activeThreadId;\n if (activeThreadId !== undefined) {\n controlledSyncTargetRef.current = { value: activeThreadId };\n lastReportedThreadRef.current = activeThreadId;\n }\n }\n\n const reportActiveThread = React.useCallback((\n threadId: string | null,\n reason: AgentChatThreadChangeReason,\n ) => {\n if (lastReportedThreadRef.current === threadId) return;\n lastReportedThreadRef.current = threadId;\n onActiveThreadIdChange?.({ threadId, reason });\n }, [onActiveThreadIdChange]);\n\n const retryBootstrap = React.useCallback((): Promise<void> => {\n if (bootstrapPromiseRef.current?.client === client) return bootstrapPromiseRef.current.promise;\n const requestClient = client;\n const request = (async () => {\n if (mountedRef.current) {\n const identityChanged = bootstrapOwnerRef.current !== requestClient;\n setIsBootstrapping(identityChanged || !bootstrapRef.current);\n setBootstrapError(null);\n if (identityChanged) {\n setBootstrap(null);\n setEffectivePolicy(null);\n setSelectedAgentId(null);\n setSelectedModelId(null);\n }\n }\n try {\n const requestedAgentId = selectedAgentIdRef.current;\n const result = await requestClient.bootstrap({ agentId: requestedAgentId || undefined });\n if (!mountedRef.current || clientRef.current !== requestClient) return;\n bootstrapOwnerRef.current = requestClient;\n bootstrapRetryRef.current = 0;\n setBootstrap(result);\n const agentFeature = result.features.agents;\n const resolvedAgentId = agentIdFromBootstrap(result, requestedAgentId);\n setSelectedAgentId(resolvedAgentId);\n const entitlement = agentFeature ? null : await requestClient.resourcePolicies.getEffective();\n if (!mountedRef.current || clientRef.current !== requestClient) return;\n setEffectivePolicy(entitlement);\n const availableModels = entitlement ? modelsFromEffectivePolicy(entitlement) : modelsFromAgentChatBootstrap(result);\n if (modelId === undefined) {\n setSelectedModelId((current) => availableModels.models.some((item) => item.id === current)\n ? current\n : availableModels.defaultModelId);\n }\n void controller.refreshThreads().catch(() => undefined);\n } catch (error) {\n if (mountedRef.current && clientRef.current === requestClient) {\n const status = (error as Agents24ClientError)?.status;\n if (status === 401 || status === 403 || status === 404) {\n setBootstrap(null);\n setEffectivePolicy(null);\n bootstrapOwnerRef.current = null;\n }\n setBootstrapError(error);\n }\n } finally {\n if (mountedRef.current && clientRef.current === requestClient) setIsBootstrapping(false);\n }\n })();\n bootstrapPromiseRef.current = { client: requestClient, promise: request };\n void request.finally(() => {\n if (bootstrapPromiseRef.current?.promise === request) bootstrapPromiseRef.current = null;\n });\n return request;\n }, [client, controller.refreshThreads, modelId]);\n\n React.useEffect(() => {\n if (!bootstrapError || bootstrapRetryRef.current >= 4) return;\n const error = bootstrapError as Agents24ClientError;\n if (!(error.retryable || error.kind === \"network\" || (error.status || 0) >= 500)) return;\n const attempt = bootstrapRetryRef.current++;\n const hint = error.retryAfterMs;\n const delay = Math.max(500 * 2 ** attempt + Math.random() * 250,\n typeof hint === \"number\" && Number.isFinite(hint) && hint >= 0 ? Math.min(hint, 60_000) : 0);\n const timer = setTimeout(() => { void retryBootstrap(); }, delay);\n return () => clearTimeout(timer);\n }, [bootstrapError, retryBootstrap]);\n\n const refreshEffectivePolicy = React.useCallback(async () => {\n if (bootstrap?.features.agents) {\n const refreshed = await client.bootstrap({ agentId: selectedAgentIdRef.current || undefined });\n if (!mountedRef.current || clientRef.current !== client) return;\n setBootstrap(refreshed);\n const available = modelsFromAgentChatBootstrap(refreshed);\n setSelectedModelId((current) => available.models.some((item) => item.id === current)\n ? current\n : available.defaultModelId);\n return;\n }\n const entitlement = await client.resourcePolicies.getEffective();\n if (!mountedRef.current || clientRef.current !== client) return;\n setEffectivePolicy(entitlement);\n if (modelId === undefined) {\n const available = modelsFromEffectivePolicy(entitlement);\n setSelectedModelId((current) => available.models.some((item) => item.id === current)\n ? current\n : available.defaultModelId);\n }\n }, [bootstrap, client, modelId]);\n\n React.useEffect(() => {\n void retryBootstrap();\n }, [retryBootstrap]);\n\n React.useEffect(() => {\n if (modelId !== undefined) setSelectedModelId(modelId);\n }, [modelId]);\n\n React.useEffect(() => {\n if (controlledSyncTargetRef.current?.value === null && controller.activeThreadId) {\n controller.startNewThread();\n }\n }, [activeThreadId, controller.activeThreadId, controller.startNewThread]);\n\n React.useEffect(() => {\n const previous = previousControllerThreadRef.current;\n const current = controller.activeThreadId;\n previousControllerThreadRef.current = current;\n const controlledTarget = controlledSyncTargetRef.current;\n if (controlledTarget) {\n if (current === controlledTarget.value) controlledSyncTargetRef.current = null;\n return;\n }\n const pendingTransition = pendingThreadTransitionRef.current;\n if (pendingTransition && current === pendingTransition.value) return;\n if (previous === null && current !== null) reportActiveThread(current, \"created\");\n }, [activeThreadId, controller.activeThreadId, reportActiveThread]);\n\n const clearOperationError = React.useCallback(() => {\n setLocalOperationError(null);\n controller.clearOperationError();\n }, [controller.clearOperationError]);\n\n const submit = React.useCallback((input: AgentChatRuntimeSubmit): Promise<void> => {\n if (submitPromiseRef.current) return submitPromiseRef.current;\n clearOperationError();\n setIsSubmitting(true);\n const request = (async () => {\n try {\n if(controller.activeThread?.read_only)throw new Error(\"This conversation is read-only. Start a new chat.\");\n await agentChangePromiseRef.current;\n const activeBootstrap = bootstrapRef.current;\n if (!activeBootstrap) throw new Error(\"The agent input contract is unavailable.\");\n const retained = (input.attachments || []).filter((attachment) => input.attachmentIds?.includes(attachment.id || \"\"));\n const inputError = validateAgentChatSubmission(activeBootstrap.features.inputs, input.text, [\n ...(input.files || []),\n ...retained.map((attachment) => ({ data: new Uint8Array(), mediaType: attachment.mediaType || \"application/octet-stream\" })),\n ]);\n if (inputError) throw new Error(inputError);\n await controller.submit({\n text: input.text,\n attachments: input.attachments,\n uploads: input.files,\n attachmentIds: input.attachmentIds,\n requestedModelId: selectedModelIdRef.current || undefined,\n requestedAgentId: selectedAgentIdRef.current || undefined,\n });\n } catch (error) {\n setLocalOperationError(error);\n const typed = error as Partial<Agents24ClientError>;\n if (typed.kind === \"quota\" || typed.kind === \"authorization\") {\n await refreshEffectivePolicy().catch(() => undefined);\n }\n throw error;\n } finally {\n setIsSubmitting(false);\n }\n })();\n submitPromiseRef.current = request;\n const clearRequest = () => {\n if (submitPromiseRef.current === request) submitPromiseRef.current = null;\n };\n void request.then(clearRequest, clearRequest);\n return request;\n }, [bootstrap, clearOperationError, controller.activeThreadId, controller.activeThread?.read_only, controller.submit, refreshEffectivePolicy]);\n\n const { onHitlAction, getHitlActionState } = useAgentChatHitl({\n client, bootstrap, controller, selectionGeneration: threadSelectionGenerationRef,\n completeMcpAuthorization, mcpRedirectUri, clearOperationError, onError: setLocalOperationError,\n });\n\n const newThread = React.useCallback(() => {\n threadSelectionGenerationRef.current += 1;\n clearOperationError();\n pendingThreadTransitionRef.current = null;\n reportActiveThread(null, \"new\");\n controller.startNewThread();\n }, [clearOperationError, controller.startNewThread, reportActiveThread]);\n\n const openThread = React.useCallback(async (threadId: string) => {\n const requestGeneration = ++threadSelectionGenerationRef.current;\n clearOperationError();\n pendingThreadTransitionRef.current = { reason: \"opened\", value: threadId };\n try {\n const detail = await client.threads.get({ threadId });\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n const preferredAgentId = detail.runtime_selection?.agent_alias || detail.runtime_selection?.agent_id || null;\n if (preferredAgentId && !detail.read_only) {\n const result = await client.bootstrap({ agentId: preferredAgentId });\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n const resolvedAgentId = agentIdFromBootstrap(result, preferredAgentId);\n setBootstrap(result);\n setEffectivePolicy(null);\n setSelectedAgentId(resolvedAgentId);\n const available = modelsFromAgentChatBootstrap(result);\n const preferredModelId = detail.runtime_selection?.model_id || null;\n setSelectedModelId(available.models.some((item) => item.id === preferredModelId)\n ? preferredModelId\n : available.defaultModelId);\n }\n await controller.openThread(threadId);\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n reportActiveThread(threadId, \"opened\");\n } catch (error) {\n if (requestGeneration !== threadSelectionGenerationRef.current) return;\n setLocalOperationError(error);\n throw error;\n } finally {\n if (requestGeneration === threadSelectionGenerationRef.current) pendingThreadTransitionRef.current = null;\n }\n }, [clearOperationError, client, controller.openThread, reportActiveThread]);\n\n const deleteThread = React.useCallback(async (threadId: string) => {\n clearOperationError();\n const wasActive = controller.activeThreadId === threadId;\n if (wasActive) threadSelectionGenerationRef.current += 1;\n if (wasActive) pendingThreadTransitionRef.current = { reason: \"deleted\", value: null };\n try {\n await controller.deleteThread(threadId);\n if (wasActive) reportActiveThread(null, \"deleted\");\n } catch (error) {\n setLocalOperationError(error);\n throw error;\n } finally {\n if (wasActive && pendingThreadTransitionRef.current?.reason === \"deleted\") {\n pendingThreadTransitionRef.current = null;\n }\n }\n }, [clearOperationError, controller.activeThreadId, controller.deleteThread, reportActiveThread]);\n\n const changeModel = React.useCallback((nextModelId: string) => {\n if (modelId === undefined) setSelectedModelId(nextModelId);\n onModelChange?.(nextModelId);\n if (controller.activeThreadId && selectedAgentId && client.threads.setRuntimeSelection) {\n void client.threads.setRuntimeSelection({\n threadId: controller.activeThreadId,\n preferredAgentId: selectedAgentId,\n preferredModelId: nextModelId,\n }).catch(setLocalOperationError);\n }\n }, [client.threads, controller.activeThreadId, modelId, onModelChange, selectedAgentId]);\n\n const resolveAttachmentContent = React.useCallback(async (\n attachment: ChatAttachment,\n signal: AbortSignal,\n ) => {\n const attachmentId = typeof attachment.id === \"string\" ? attachment.id.trim() : \"\";\n if (!attachmentId) throw new Error(\"Attachment content identity is unavailable.\");\n const access = await attachments.createContentAccess({\n attachmentId,\n disposition: \"inline\",\n signal,\n });\n return { url: access.url, validUntil: access.valid_until || null };\n }, [attachments.createContentAccess]);\n\n const changeAgent = React.useCallback((nextAgentId: string): Promise<void> => {\n if (agentChangePromiseRef.current) return agentChangePromiseRef.current;\n if (\n nextAgentId === selectedAgentIdRef.current\n || !canChangeAgentRuntime(controller.runState, controller.activeRunId)\n ) return Promise.resolve();\n clearOperationError();\n setIsChangingAgent(true);\n const request = (async () => {\n try {\n const result = await client.bootstrap({ agentId: nextAgentId });\n const resolvedAgentId = agentIdFromBootstrap(result, nextAgentId);\n if (!resolvedAgentId) throw new Error(\"The requested Agent is no longer available.\");\n const available = modelsFromAgentChatBootstrap(result);\n const currentModelId = selectedModelIdRef.current;\n const nextModelId = available.models.some((item) => item.id === currentModelId)\n ? currentModelId\n : available.defaultModelId;\n if (controller.activeThreadId && client.threads.setRuntimeSelection) {\n const persisted = await client.threads.setRuntimeSelection({\n threadId: controller.activeThreadId,\n preferredAgentId: resolvedAgentId,\n preferredModelId: nextModelId,\n });\n selectedModelIdRef.current = persisted.runtime_selection.model_id;\n setSelectedModelId(persisted.runtime_selection.model_id);\n } else {\n selectedModelIdRef.current = nextModelId;\n setSelectedModelId(nextModelId);\n }\n selectedAgentIdRef.current = resolvedAgentId;\n bootstrapRef.current = result;\n setSelectedAgentId(resolvedAgentId);\n setBootstrap(result);\n setEffectivePolicy(null);\n } catch (error) {\n setLocalOperationError(error);\n throw error;\n }\n })();\n agentChangePromiseRef.current = request;\n const clearRequest = () => {\n if (agentChangePromiseRef.current === request) agentChangePromiseRef.current = null;\n if (mountedRef.current) setIsChangingAgent(false);\n };\n void request.then(clearRequest, clearRequest);\n return request;\n }, [clearOperationError, client, controller.activeRunId, controller.activeThreadId, controller.runState]);\n\n const modelOptions = effectivePolicy\n ? modelsFromEffectivePolicy(effectivePolicy).models\n : bootstrap\n ? modelsFromAgentChatBootstrap(bootstrap).models\n : [];\n const fatalError = (!bootstrap ? bootstrapError : null) || controller.error;\n const operationError = localOperationError || controller.operationError?.cause;\n const state: AgentChatRuntimeViewState = isBootstrapping\n ? \"loading\"\n : fatalError\n ? agentChatRuntimeStateFromError(fatalError)\n : controller.runState === \"uploading\"\n ? \"uploading\"\n : controller.runState === \"streaming\"\n ? \"streaming\"\n : controller.runState === \"reconnecting\"\n ? \"reconnecting\"\n : controller.runState === \"paused\"\n ? \"paused\"\n : controller.runState === \"cancelling\"\n ? \"cancelling\"\n : controller.runState === \"cancelled\"\n ? \"cancelled\"\n : \"ready\";\n const connectionState: AgentChatRuntimeConnectionState = bootstrapError && bootstrap ? \"reconnecting\" : state === \"offline\"\n ? \"offline\"\n : state === \"expired\"\n ? \"expired\"\n : state === \"reconnecting\"\n ? \"reconnecting\"\n : isBootstrapping\n ? \"connecting\"\n : \"connected\";\n return {\n agent: agentOverride || { name: bootstrap?.deployment.name || \"Agent\" },\n inputContract: bootstrap?.features.inputs || null,\n allowFeedback: Boolean(bootstrap?.capabilities.includes(\"feedback.write\")) && !controller.activeThread?.read_only,\n isReadOnly:controller.activeThread?.read_only===true,\n backgroundError: (bootstrap && bootstrapError) || controller.backgroundError?.cause || null,\n bootstrap,\n capabilities: bootstrap?.capabilities || [],\n agentId: bootstrap ? selectedAgentId : null,\n agents: bootstrap?.features.agents?.options.map((item) => ({ id: item.id, label: item.label })) || [],\n changeAgent,\n changeModel,\n clearOperationError,\n connectionState,\n contextWindow: controller.contextWindow,\n contextCompression: controller.contextCompression,\n controller,\n deleteThread,\n errorMessage: agentChatRuntimeErrorMessage(fatalError || operationError),\n fatalError,\n getHitlActionState,\n isBootstrapping,\n isChangingAgent,\n isSubmitting: isSubmitting || controller.isSubmitting,\n isUploading: attachments.isUploading || controller.runState === \"uploading\",\n modelId: bootstrap ? selectedModelId : null,\n models: modelOptions,\n newThread,\n onHitlAction,\n openThread,\n operationError,\n retryBootstrap,\n resolveAttachmentContent,\n state,\n submit,\n };\n}\n","import type { AgentClient, ClientBootstrap, HitlResponse } from \"@agents24/client\";\nimport { type AgentChatController, type ChatHitlPart, type HitlSubmissionOptions, useAgentMcp } from \"@agents24/react\";\nimport * as React from \"react\";\nimport { browserChatCrypto, createMcpPkceProof, validateMcpCallbackResult, waitForMcpOauthComplete } from \"../mcp-oauth\";\nimport type { AgentChatMcpAuthorizationCompletion, AgentChatRuntimeHitlActionState } from \"./use-agent-chat-runtime\";\n\ntype HitlOptions = {\n client: AgentClient;\n bootstrap: ClientBootstrap | null;\n controller: AgentChatController;\n selectionGeneration: React.MutableRefObject<number>;\n completeMcpAuthorization?: AgentChatMcpAuthorizationCompletion;\n mcpRedirectUri?: string;\n clearOperationError(): void;\n onError(error: unknown): void;\n};\n\ntype HitlOperation = {\n abort: AbortController;\n isCurrent(): boolean;\n phase: \"connecting\" | \"resuming\";\n popup?: Window;\n};\n\nfunction detach(operation: HitlOperation) {\n operation.abort.abort();\n operation.popup?.close();\n}\n\nexport function useAgentChatHitl(options: HitlOptions) {\n const mcp = useAgentMcp();\n const latest = React.useRef(options);\n latest.current = options;\n const mounted = React.useRef(true);\n const operations = React.useRef(new Map<string, HitlOperation>());\n const [states, setStates] = React.useState<Record<string, AgentChatRuntimeHitlActionState>>({});\n\n React.useEffect(() => {\n mounted.current = true;\n const active = operations.current;\n return () => {\n mounted.current = false;\n for (const operation of active.values()) detach(operation);\n active.clear();\n };\n }, []);\n React.useEffect(() => {\n for (const [key, operation] of operations.current) {\n if (operation.isCurrent()) continue;\n detach(operation);\n operations.current.delete(key);\n setStates((current) => {\n const next = { ...current };\n delete next[key];\n return next;\n });\n }\n });\n React.useEffect(() => { setStates({}); }, [options.client, options.controller.activeThreadId]);\n\n const onHitlAction = React.useCallback(async (part: ChatHitlPart, response: HitlResponse, submission?: HitlSubmissionOptions) => {\n const captured = latest.current;\n const { controller, client, bootstrap, selectionGeneration } = captured;\n const generation = selectionGeneration.current;\n const threadId = controller.activeThreadId;\n const runId = part.runId || controller.messages.find((message) => message.parts.some(candidate => candidate.id === part.id))?.runId || controller.activeRunId;\n const key = `${generation}:${threadId}:${runId}:${part.interruptId || part.id}`;\n if (part.hitlKind !== \"mcp_auth\" || response.action !== \"connect\") {\n captured.clearOperationError();\n // All normal decisions, including host preparation, have one headless owner.\n return controller.resumeHitl(part, response, submission).catch(error => {\n const current = latest.current;\n if (mounted.current && current.client === client && current.selectionGeneration.current === generation\n && current.controller.activeThreadId === threadId) captured.onError(error);\n throw error;\n });\n }\n const previous = operations.current.get(key);\n if (previous?.isCurrent()) return;\n if (previous) { detach(previous); operations.current.delete(key); }\n const operation: HitlOperation = {\n abort: new AbortController(),\n phase: part.hitlKind === \"mcp_auth\" && response.action === \"connect\" ? \"connecting\" : \"resuming\",\n isCurrent() {\n const current = latest.current;\n return mounted.current && !operation.abort.signal.aborted\n && current.client === client && current.selectionGeneration.current === generation\n && current.controller.activeThreadId === threadId\n && (!current.controller.activeRunId || current.controller.activeRunId === runId)\n && ![\"cancelling\", \"cancelled\", \"failed\", \"completed\"].includes(current.controller.runState)\n && (operation.phase === \"resuming\" || current.controller.messages.some((message) =>\n message.runId === runId && message.parts.some((candidate) => candidate.type === \"hitl\"\n && candidate.interruptId === part.interruptId && candidate.status === \"pending\")));\n },\n };\n if (!operation.isCurrent()) return;\n captured.clearOperationError();\n operations.current.set(key, operation);\n setStates((current) => ({ ...current, [key]: { action: response.action, status: operation.phase } }));\n try {\n if (operation.phase === \"connecting\") {\n if (!runId) throw new Error(\"MCP authorization is missing its paused run.\");\n if (!bootstrap) throw new Error(\"MCP authorization requires runtime bootstrap.\");\n if (!captured.mcpRedirectUri) throw new Error(\"mcpRedirectUri is required for MCP Connect.\");\n const serverId = String(part.presentation.server_id || \"\").trim();\n if (!serverId) throw new Error(\"MCP authorization is missing its server identity.\");\n const serverEmbed = bootstrap.authentication.modes.includes(\"server_embed\");\n const popupNonce = browserChatCrypto().randomUUID();\n // Open within the click before awaiting crypto or the network.\n const popup = window.open(\"about:blank\", \"agents24-mcp\", \"popup,width=560,height=720\");\n if (!popup) throw new Error(\"Allow popups to connect this MCP account.\");\n operation.popup = popup;\n popup.document.title = \"Connecting to MCP\";\n popup.document.body.textContent = \"Opening secure connection…\";\n const proof = await createMcpPkceProof();\n if (!operation.isCurrent()) return;\n const started = await mcp.startAuthorization({\n runId, serverId, interruptId: part.interruptId, redirectUri: captured.mcpRedirectUri,\n popupNonce, codeChallenge: proof.challenge, signal: operation.abort.signal,\n });\n if (!operation.isCurrent()) return;\n if (!started.callback_origin) throw new Error(\"MCP authorization did not return a callback origin.\");\n const completionPromise = waitForMcpOauthComplete({\n popup, callbackOrigin: started.callback_origin, popupNonce, serverId,\n runId, interruptId: part.interruptId, signal: operation.abort.signal,\n requireConnectionId: serverEmbed || Boolean(captured.completeMcpAuthorization),\n });\n // Ensure a navigation exception cannot leave a rejected waiter unobserved.\n void completionPromise.catch(() => undefined);\n popup.location.replace(started.authorization_url);\n const completion = await completionPromise;\n if (!operation.isCurrent()) return;\n if (captured.completeMcpAuthorization) {\n await captured.completeMcpAuthorization({ completion, codeVerifier: proof.verifier, serverId });\n } else if (serverEmbed) {\n validateMcpCallbackResult({ server_id: completion.serverId, connection_id: completion.connectionId || \"\" }, serverId);\n } else {\n const redeemed = await mcp.redeemCallback({\n code: completion.code, codeVerifier: proof.verifier, signal: operation.abort.signal,\n });\n if (!operation.isCurrent()) return;\n validateMcpCallbackResult(redeemed, serverId);\n }\n popup.close();\n }\n if (!operation.isCurrent()) return;\n operation.phase = \"resuming\";\n setStates((current) => ({ ...current, [key]: { action: response.action, status: \"resuming\" } }));\n await controller.resumeHitl(part, response, submission);\n } catch (error) {\n if (!operation.isCurrent()) return;\n captured.onError(error);\n setStates((current) => ({ ...current, [key]: {\n action: response.action, status: \"error\", error: error instanceof Error ? error.message : String(error),\n } }));\n throw error;\n } finally {\n const ownsState = operation.isCurrent();\n // Abort the waiter and any in-flight transport, and always release the popup.\n detach(operation);\n if (operations.current.get(key) === operation) {\n operations.current.delete(key);\n if (ownsState) setStates((current) => {\n if (current[key]?.status === \"error\") return current;\n const next = { ...current };\n delete next[key];\n return next;\n });\n }\n }\n }, [mcp]);\n\n return { onHitlAction, getHitlActionState: (part: ChatHitlPart) => {\n const { controller, selectionGeneration } = latest.current;\n const runId = part.runId || controller.messages.find(message => message.parts.some(candidate => candidate.id === part.id))?.runId || controller.activeRunId;\n return controller.getHitlSubmissionState(part)\n || states[`${selectionGeneration.current}:${controller.activeThreadId}:${runId}:${part.interruptId || part.id}`];\n } };\n}\n","import * as React from \"react\";\nimport type { DelegationEvents, DelegationTask } from \"../generated/delegation-types\";\n\nexport type DelegationTaskSource = {\n events(input: { threadId: string; after: number; signal: AbortSignal }): Promise<DelegationEvents>;\n};\n\n/** Authoritative snapshots keep task discovery alive after the run stream ends. */\nexport function useDelegationTasks({ threadId, source, pollIntervalMs = 2000 }: {\n threadId: string | null;\n source: DelegationTaskSource;\n pollIntervalMs?: number;\n}) {\n const [state, setState] = React.useState<{\n threadId: string | null; tasks: DelegationTask[]; error: unknown; loading: boolean;\n }>({ threadId: null, tasks: [], error: null, loading: false });\n const [revision, refresh] = React.useReducer((value: number) => value + 1, 0);\n React.useEffect(() => {\n if (!threadId) {\n setState({ threadId: null, tasks: [], error: null, loading: false });\n return;\n }\n const controller = new AbortController();\n let cursor = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let failures = 0;\n setState((previous) => ({ threadId, tasks: previous.threadId === threadId ? previous.tasks : [],\n error: null, loading: true }));\n const poll = async () => {\n try {\n const result = await source.events({ threadId, after: cursor, signal: controller.signal });\n if (controller.signal.aborted) return;\n cursor = result.cursor;\n failures = 0;\n setState({ threadId, tasks: result.snapshot, error: null, loading: false });\n } catch (error) {\n if (controller.signal.aborted) return;\n failures += 1;\n setState((previous) => ({ ...previous, error, loading: false }));\n }\n if (!controller.signal.aborted) {\n timer = setTimeout(poll, Math.min(30000, Math.max(250, pollIntervalMs) * 2 ** Math.min(failures, 4)));\n }\n };\n void poll();\n return () => {\n controller.abort();\n if (timer) clearTimeout(timer);\n };\n }, [threadId, source, pollIntervalMs, revision]);\n return { tasks: state.threadId === threadId ? state.tasks : [],\n error: state.threadId === threadId ? state.error : null,\n loading: Boolean(threadId) && (state.threadId !== threadId || state.loading), refresh };\n}\n"],"mappings":";;;;;;;;;;;;;;;;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E;AAAA,MACjE;AACA,UAAI,CAAC,WAAW,OAAO,SAAS;AAC9B,gBAAQ,WAAW,MAAM,KAAK,IAAI,KAAO,KAAK,IAAI,KAAK,cAAc,IAAI,KAAK,KAAK,IAAI,UAAU,CAAC,CAAC,CAAC;AAAA,MACtG;AAAA,IACF;AACA,SAAK,KAAK;AACV,WAAO,MAAM;AACX,iBAAW,MAAM;AACjB,UAAI,MAAO,cAAa,KAAK;AAAA,IAC/B;AAAA,EACF,GAAG,CAAC,UAAU,QAAQ,gBAAgB,QAAQ,CAAC;AAC/C,SAAO;AAAA,IAAE,OAAO,MAAM,aAAa,WAAW,MAAM,QAAQ,CAAC;AAAA,IAC3D,OAAO,MAAM,aAAa,WAAW,MAAM,QAAQ;AAAA,IACnD,SAAS,QAAQ,QAAQ,MAAM,MAAM,aAAa,YAAY,MAAM;AAAA,IAAU;AAAA,EAAQ;AAC1F;","names":["React","React"]}
|
|
@@ -52,6 +52,7 @@ export type AgentChatRuntime = {
|
|
|
52
52
|
agent: AgentChatRuntimeAgent;
|
|
53
53
|
inputContract: ClientBootstrap["features"]["inputs"] | null;
|
|
54
54
|
allowFeedback: boolean;
|
|
55
|
+
isReadOnly: boolean;
|
|
55
56
|
backgroundError: unknown;
|
|
56
57
|
bootstrap: ClientBootstrap | null;
|
|
57
58
|
capabilities: readonly string[];
|