agents 0.0.0-7978d71 → 0.0.0-79843bd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +378 -27
  2. package/dist/ai-chat-agent.d.ts +236 -24
  3. package/dist/ai-chat-agent.js +1118 -230
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-DguhuLKF.js +155 -0
  6. package/dist/ai-chat-v5-migration-DguhuLKF.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +155 -0
  8. package/dist/ai-chat-v5-migration.js +3 -0
  9. package/dist/ai-react.d.ts +202 -85
  10. package/dist/ai-react.js +574 -199
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-DEtF_8Km.js +28 -0
  13. package/dist/ai-types-DEtF_8Km.js.map +1 -0
  14. package/dist/ai-types-U8lYA0o8.d.ts +127 -0
  15. package/dist/ai-types.d.ts +6 -74
  16. package/dist/ai-types.js +3 -1
  17. package/dist/cli/index.d.ts +1 -0
  18. package/dist/cli/index.js +28 -0
  19. package/dist/cli/index.js.map +1 -0
  20. package/dist/client-BZVYeBmf.d.ts +834 -0
  21. package/dist/client-ClORm6f0.d.ts +104 -0
  22. package/dist/client-DjTPRM8-.js +117 -0
  23. package/dist/client-DjTPRM8-.js.map +1 -0
  24. package/dist/client-QZa2Rq0l.js +1105 -0
  25. package/dist/client-QZa2Rq0l.js.map +1 -0
  26. package/dist/client.d.ts +12 -93
  27. package/dist/client.js +4 -11
  28. package/dist/codemode/ai.d.ts +27 -0
  29. package/dist/codemode/ai.js +152 -0
  30. package/dist/codemode/ai.js.map +1 -0
  31. package/dist/context-BkKbAa1R.js +8 -0
  32. package/dist/context-BkKbAa1R.js.map +1 -0
  33. package/dist/context-_sPQqJWv.d.ts +24 -0
  34. package/dist/context.d.ts +6 -0
  35. package/dist/context.js +3 -0
  36. package/dist/do-oauth-client-provider-B-ryFIPr.d.ts +70 -0
  37. package/dist/do-oauth-client-provider-B1fVIshX.js +155 -0
  38. package/dist/do-oauth-client-provider-B1fVIshX.js.map +1 -0
  39. package/dist/index-B6XHf8p0.d.ts +577 -0
  40. package/dist/index-CyDpAVHZ.d.ts +58 -0
  41. package/dist/index.d.ts +61 -402
  42. package/dist/index.js +8 -22
  43. package/dist/mcp/client.d.ts +4 -783
  44. package/dist/mcp/client.js +4 -9
  45. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  46. package/dist/mcp/do-oauth-client-provider.js +3 -7
  47. package/dist/mcp/index.d.ts +200 -81
  48. package/dist/mcp/index.js +1429 -770
  49. package/dist/mcp/index.js.map +1 -1
  50. package/dist/mcp/x402.d.ts +34 -0
  51. package/dist/mcp/x402.js +198 -0
  52. package/dist/mcp/x402.js.map +1 -0
  53. package/dist/mcp-CzbSsLfc.d.ts +61 -0
  54. package/dist/observability/index.d.ts +3 -0
  55. package/dist/observability/index.js +8 -0
  56. package/dist/react-DYwejKBr.d.ts +131 -0
  57. package/dist/react.d.ts +15 -119
  58. package/dist/react.js +183 -110
  59. package/dist/react.js.map +1 -1
  60. package/dist/schedule.d.ts +87 -10
  61. package/dist/schedule.js +46 -21
  62. package/dist/schedule.js.map +1 -1
  63. package/dist/serializable-C4GLimgv.d.ts +39 -0
  64. package/dist/serializable.d.ts +7 -32
  65. package/dist/serializable.js +1 -1
  66. package/dist/src-BZDh910Z.js +1181 -0
  67. package/dist/src-BZDh910Z.js.map +1 -0
  68. package/package.json +83 -29
  69. package/dist/ai-types.js.map +0 -1
  70. package/dist/chunk-767EASBA.js +0 -106
  71. package/dist/chunk-767EASBA.js.map +0 -1
  72. package/dist/chunk-E3LCYPCB.js +0 -469
  73. package/dist/chunk-E3LCYPCB.js.map +0 -1
  74. package/dist/chunk-NKZZ66QY.js +0 -116
  75. package/dist/chunk-NKZZ66QY.js.map +0 -1
  76. package/dist/chunk-ZRRXJUAA.js +0 -788
  77. package/dist/chunk-ZRRXJUAA.js.map +0 -1
  78. package/dist/client.js.map +0 -1
  79. package/dist/index.js.map +0 -1
  80. package/dist/mcp/client.js.map +0 -1
  81. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  82. package/dist/serializable.js.map +0 -1
  83. package/src/index.ts +0 -1255
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ai-react.tsx"],"sourcesContent":["import { useChat } from \"@ai-sdk/react\";\nimport type { Message } from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport { use, useEffect } from \"react\";\nimport type { OutgoingMessage } from \"./ai-types\";\nimport type { useAgent } from \"./react\";\n\ntype GetInitialMessagesOptions = {\n agent: string;\n name: string;\n url: string;\n};\n\n/**\n * Options for the useAgentChat hook\n */\ntype UseAgentChatOptions<State> = Omit<\n Parameters<typeof useChat>[0] & {\n /** Agent connection from useAgent */\n agent: ReturnType<typeof useAgent<State>>;\n getInitialMessages?:\n | undefined\n | null\n // | (() => Message[])\n | ((options: GetInitialMessagesOptions) => Promise<Message[]>);\n },\n \"fetch\"\n>;\n\nconst requestCache = new Map<string, Promise<Message[]>>();\n\n/**\n * React hook for building AI chat interfaces using an Agent\n * @param options Chat options including the agent connection\n * @returns Chat interface controls and state with added clearHistory method\n */\nexport function useAgentChat<State = unknown>(\n options: UseAgentChatOptions<State>\n) {\n const { agent, getInitialMessages, ...rest } = options;\n\n const agentUrl = new URL(\n `${// @ts-expect-error we're using a protected _url property that includes query params\n ((agent._url as string | null) || agent._pkurl)\n ?.replace(\"ws://\", \"http://\")\n .replace(\"wss://\", \"https://\")}`\n );\n\n // delete the _pk query param\n agentUrl.searchParams.delete(\"_pk\");\n const agentUrlString = agentUrl.toString();\n\n async function defaultGetInitialMessagesFetch({\n url,\n }: GetInitialMessagesOptions) {\n const getMessagesUrl = new URL(url);\n getMessagesUrl.pathname += \"/get-messages\";\n const response = await fetch(getMessagesUrl.toString(), {\n credentials: options.credentials,\n headers: options.headers,\n });\n return response.json<Message[]>();\n }\n\n const getInitialMessagesFetch =\n getInitialMessages || defaultGetInitialMessagesFetch;\n\n function doGetInitialMessages(\n getInitialMessagesOptions: GetInitialMessagesOptions\n ) {\n if (requestCache.has(agentUrlString)) {\n return requestCache.get(agentUrlString)!;\n }\n const promise = getInitialMessagesFetch(getInitialMessagesOptions);\n // immediately cache the promise so that we don't\n // create multiple requests for the same agent during multiple\n // concurrent renders\n requestCache.set(agentUrlString, promise);\n return promise;\n }\n\n const initialMessagesPromise =\n getInitialMessages === null\n ? null\n : doGetInitialMessages({\n agent: agent.agent,\n name: agent.name,\n url: agentUrlString,\n });\n const initialMessages = initialMessagesPromise\n ? use(initialMessagesPromise)\n : (rest.initialMessages ?? []);\n\n // manages adding and removing the promise from the cache\n useEffect(() => {\n if (!initialMessagesPromise) {\n return;\n }\n // this effect is responsible for removing the promise from the cache\n // when the component unmounts or the promise changes,\n // but that means it also must add the promise to the cache\n // so that multiple arbitrary effect runs produce the expected state\n // when resolved.\n requestCache.set(agentUrlString, initialMessagesPromise!);\n return () => {\n if (requestCache.get(agentUrlString) === initialMessagesPromise) {\n requestCache.delete(agentUrlString);\n }\n };\n }, [agentUrlString, initialMessagesPromise]);\n\n async function aiFetch(\n request: RequestInfo | URL,\n options: RequestInit = {}\n ) {\n // we're going to use a websocket to do the actual \"fetching\"\n // but still satisfy the type signature of the fetch function\n // so we'll return a promise that resolves to a response\n\n const {\n method,\n keepalive,\n headers,\n body,\n redirect,\n integrity,\n signal,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window,\n // dispatcher, duplex\n } = options;\n const id = nanoid(8);\n const abortController = new AbortController();\n\n signal?.addEventListener(\"abort\", () => {\n // Propagate request cancellation to the Agent\n // We need to communciate cancellation as a websocket message, instead of a request signal\n agent.send(\n JSON.stringify({\n id,\n type: \"cf_agent_chat_request_cancel\",\n })\n );\n\n // NOTE - If we wanted to, we could preserve the \"interrupted\" message here, with the code below\n // However, I think it might be the responsibility of the library user to implement that behavior manually?\n // Reasoning: This code could be subject to collisions, as it \"force saves\" the messages we have locally\n //\n // agent.send(JSON.stringify({\n // type: \"cf_agent_chat_messages\",\n // messages: ... /* some way of getting current messages ref? */\n // }))\n\n abortController.abort();\n // Make sure to also close the stream (cf. https://github.com/cloudflare/agents-starter/issues/69)\n controller.close();\n });\n\n agent.addEventListener(\n \"message\",\n (event) => {\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_use_chat_response\") {\n if (data.id === id) {\n controller.enqueue(new TextEncoder().encode(data.body));\n if (data.done) {\n controller.close();\n abortController.abort();\n }\n }\n }\n },\n { signal: abortController.signal }\n );\n\n let controller: ReadableStreamDefaultController;\n\n const stream = new ReadableStream({\n start(c) {\n controller = c;\n },\n });\n\n agent.send(\n JSON.stringify({\n id,\n init: {\n body,\n credentials,\n headers,\n integrity,\n keepalive,\n method,\n mode,\n redirect,\n referrer,\n referrerPolicy,\n window,\n // dispatcher,\n // duplex\n },\n type: \"cf_agent_use_chat_request\",\n url: request.toString(),\n })\n );\n\n return new Response(stream);\n }\n const useChatHelpers = useChat({\n fetch: aiFetch,\n initialMessages,\n sendExtraMessageFields: true,\n ...rest,\n });\n\n useEffect(() => {\n function onClearHistory(event: MessageEvent) {\n if (typeof event.data !== \"string\") {\n return;\n }\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_chat_clear\") {\n useChatHelpers.setMessages([]);\n }\n }\n\n function onMessages(event: MessageEvent) {\n if (typeof event.data !== \"string\") {\n return;\n }\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_chat_messages\") {\n useChatHelpers.setMessages(data.messages);\n }\n }\n\n agent.addEventListener(\"message\", onClearHistory);\n agent.addEventListener(\"message\", onMessages);\n\n return () => {\n agent.removeEventListener(\"message\", onClearHistory);\n agent.removeEventListener(\"message\", onMessages);\n };\n }, [agent, useChatHelpers.setMessages]);\n\n return {\n ...useChatHelpers,\n /**\n * Clear chat history on both client and Agent\n */\n clearHistory: () => {\n useChatHelpers.setMessages([]);\n agent.send(\n JSON.stringify({\n type: \"cf_agent_chat_clear\",\n })\n );\n },\n /**\n * Set the chat messages and synchronize with the Agent\n * @param messages New messages to set\n */\n setMessages: (messages: Message[]) => {\n useChatHelpers.setMessages(messages);\n agent.send(\n JSON.stringify({\n messages,\n type: \"cf_agent_chat_messages\",\n })\n );\n },\n };\n}\n"],"mappings":";AAAA,SAAS,eAAe;AAExB,SAAS,cAAc;AACvB,SAAS,KAAK,iBAAiB;AA0B/B,IAAM,eAAe,oBAAI,IAAgC;AAOlD,SAAS,aACd,SACA;AACA,QAAM,EAAE,OAAO,oBAAoB,GAAG,KAAK,IAAI;AAE/C,QAAM,WAAW,IAAI;AAAA,IACnB;AAAA,KACE,MAAM,QAA0B,MAAM,SACpC,QAAQ,SAAS,SAAS,EAC3B,QAAQ,UAAU,UAAU,CAAC;AAAA,EAClC;AAGA,WAAS,aAAa,OAAO,KAAK;AAClC,QAAM,iBAAiB,SAAS,SAAS;AAEzC,iBAAe,+BAA+B;AAAA,IAC5C;AAAA,EACF,GAA8B;AAC5B,UAAM,iBAAiB,IAAI,IAAI,GAAG;AAClC,mBAAe,YAAY;AAC3B,UAAM,WAAW,MAAM,MAAM,eAAe,SAAS,GAAG;AAAA,MACtD,aAAa,QAAQ;AAAA,MACrB,SAAS,QAAQ;AAAA,IACnB,CAAC;AACD,WAAO,SAAS,KAAgB;AAAA,EAClC;AAEA,QAAM,0BACJ,sBAAsB;AAExB,WAAS,qBACP,2BACA;AACA,QAAI,aAAa,IAAI,cAAc,GAAG;AACpC,aAAO,aAAa,IAAI,cAAc;AAAA,IACxC;AACA,UAAM,UAAU,wBAAwB,yBAAy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,KAAK,QAAQ;AAAA,MAC1C;AAAA,IACF;AAEA,UAAM,iBAAiB,WAAW,cAAc;AAChD,UAAM,iBAAiB,WAAW,UAAU;AAE5C,WAAO,MAAM;AACX,YAAM,oBAAoB,WAAW,cAAc;AACnD,YAAM,oBAAoB,WAAW,UAAU;AAAA,IACjD;AAAA,EACF,GAAG,CAAC,OAAO,eAAe,WAAW,CAAC;AAEtC,SAAO;AAAA,IACL,GAAG;AAAA;AAAA;AAAA;AAAA,IAIH,cAAc,MAAM;AAClB,qBAAe,YAAY,CAAC,CAAC;AAC7B,YAAM;AAAA,QACJ,KAAK,UAAU;AAAA,UACb,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,aAAa,CAAC,aAAwB;AACpC,qBAAe,YAAY,QAAQ;AACnC,YAAM;AAAA,QACJ,KAAK,UAAU;AAAA,UACb;AAAA,UACA,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;","names":["options"]}
1
+ {"version":3,"file":"ai-react.js","names":["schemas: ClientToolSchema[]","tool","options","controller: ReadableStreamDefaultController","data: OutgoingMessage<ChatMessage>","customTransport: ChatTransport<ChatMessage>","body: Record<string, unknown>","headers: HeadersInit | undefined","credentials: RequestCredentials | undefined","api: string | undefined","lastMessage","toolResults: Array<{\n toolCallId: string;\n toolName: string;\n output: unknown;\n }>","toolOutput: unknown","existingParts: ChatMessage[\"parts\"]","addToolResultAndSendMessage: typeof useChatHelpers.addToolResult"],"sources":["../src/ai-react.tsx"],"sourcesContent":["import { useChat, type UseChatOptions } from \"@ai-sdk/react\";\nimport { getToolName, isToolUIPart } from \"ai\";\nimport type {\n ChatInit,\n ChatTransport,\n JSONSchema7,\n Tool,\n UIMessage as Message,\n UIMessage\n} from \"ai\";\nimport { DefaultChatTransport } from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport { use, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { OutgoingMessage } from \"./ai-types\";\nimport { MessageType } from \"./ai-types\";\nimport type { useAgent } from \"./react\";\n\n/**\n * JSON Schema type for tool parameters.\n * Re-exported from the AI SDK for convenience.\n * @deprecated Import JSONSchema7 directly from \"ai\" instead.\n */\nexport type JSONSchemaType = JSONSchema7;\n\n/**\n * Definition for a tool that can be executed on the client.\n * Tools with an `execute` function are automatically registered with the server.\n *\n * Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema` (FlexibleSchema)\n * because client tools must be serializable for the wire format. Zod schemas cannot be\n * serialized, so we require raw JSON Schema here.\n */\nexport type AITool<Input = unknown, Output = unknown> = {\n /** Human-readable description of what the tool does */\n description?: Tool[\"description\"];\n /** JSON Schema defining the tool's input parameters */\n parameters?: JSONSchema7;\n /**\n * @deprecated Use `parameters` instead. Will be removed in a future version.\n */\n inputSchema?: JSONSchema7;\n /**\n * Function to execute the tool on the client.\n * If provided, the tool schema is automatically sent to the server.\n */\n execute?: (input: Input) => Output | Promise<Output>;\n};\n\n/**\n * Schema for a client tool sent to the server.\n * This is the wire format - what gets sent in the request body.\n * Must match the server-side ClientToolSchema type in ai-chat-agent.ts.\n */\nexport type ClientToolSchema = {\n /** Unique name for the tool */\n name: string;\n /** Human-readable description of what the tool does */\n description?: Tool[\"description\"];\n /** JSON Schema defining the tool's input parameters */\n parameters?: JSONSchema7;\n};\n\n/**\n * Extracts tool schemas from tools that have client-side execute functions.\n * These schemas are automatically sent to the server with each request.\n * @param tools - Record of tool name to tool definition\n * @returns Array of tool schemas to send to server, or undefined if none\n */\nexport function extractClientToolSchemas(\n tools?: Record<string, AITool<unknown, unknown>>\n): ClientToolSchema[] | undefined {\n if (!tools) return undefined;\n\n const schemas: ClientToolSchema[] = Object.entries(tools)\n .filter(([_, tool]) => tool.execute) // Only tools with client-side execute\n .map(([name, tool]) => {\n if (tool.inputSchema && !tool.parameters) {\n console.warn(\n `[useAgentChat] Tool \"${name}\" uses deprecated 'inputSchema'. Please migrate to 'parameters'.`\n );\n }\n return {\n name,\n description: tool.description,\n parameters: tool.parameters ?? tool.inputSchema\n };\n });\n\n return schemas.length > 0 ? schemas : undefined;\n}\n\ntype GetInitialMessagesOptions = {\n agent: string;\n name: string;\n url: string;\n};\n\n// v5 useChat parameters\ntype UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &\n UseChatOptions<M>;\n\n/**\n * Options for preparing the send messages request.\n * Used by prepareSendMessagesRequest callback.\n */\nexport type PrepareSendMessagesRequestOptions<\n ChatMessage extends UIMessage = UIMessage\n> = {\n /** The chat ID */\n id: string;\n /** Messages to send */\n messages: ChatMessage[];\n /** What triggered this request */\n trigger: \"submit-message\" | \"regenerate-message\";\n /** ID of the message being sent (if applicable) */\n messageId?: string;\n /** Request metadata */\n requestMetadata?: unknown;\n /** Current body (if any) */\n body?: Record<string, unknown>;\n /** Current credentials (if any) */\n credentials?: RequestCredentials;\n /** Current headers (if any) */\n headers?: HeadersInit;\n /** API endpoint */\n api?: string;\n};\n\n/**\n * Return type for prepareSendMessagesRequest callback.\n * Allows customizing headers, body, and credentials for each request.\n * All fields are optional; only specify what you need to customize.\n */\nexport type PrepareSendMessagesRequestResult = {\n /** Custom headers to send with the request */\n headers?: HeadersInit;\n /** Custom body data to merge with the request */\n body?: Record<string, unknown>;\n /** Custom credentials option */\n credentials?: RequestCredentials;\n /** Custom API endpoint */\n api?: string;\n};\n\n/**\n * Internal type for AI SDK transport\n * @internal\n */\ntype InternalPrepareResult = {\n body: Record<string, unknown>;\n headers?: HeadersInit;\n credentials?: RequestCredentials;\n api?: string;\n};\n\n/**\n * Options for the useAgentChat hook\n */\ntype UseAgentChatOptions<\n State,\n ChatMessage extends UIMessage = UIMessage\n> = Omit<UseChatParams<ChatMessage>, \"fetch\"> & {\n /** Agent connection from useAgent */\n agent: ReturnType<typeof useAgent<State>>;\n getInitialMessages?:\n | undefined\n | null\n | ((options: GetInitialMessagesOptions) => Promise<ChatMessage[]>);\n /** Request credentials */\n credentials?: RequestCredentials;\n /** Request headers */\n headers?: HeadersInit;\n /**\n * @description Whether to automatically resolve tool calls that do not require human interaction.\n * @experimental\n */\n experimental_automaticToolResolution?: boolean;\n /**\n * Tools that can be executed on the client.\n\n */\n tools?: Record<string, AITool<unknown, unknown>>;\n /**\n * @description Manual override for tools requiring confirmation.\n * If not provided, will auto-detect from tools object (tools without execute require confirmation).\n */\n toolsRequiringConfirmation?: string[];\n /**\n * When true, the server automatically continues the conversation after\n * receiving client-side tool results, similar to how server-executed tools\n * work with maxSteps in streamText. The continuation is merged into the\n * same assistant message.\n *\n * When false (default), the client calls sendMessage() after tool results\n * to continue the conversation, which creates a new assistant message.\n *\n * @default false\n */\n autoContinueAfterToolResult?: boolean;\n /**\n * When true (default), automatically sends the next message only after\n * all pending confirmation-required tool calls have been resolved.\n * When false, sends immediately after each tool result.\n *\n * Only applies when `autoContinueAfterToolResult` is false.\n *\n * @default true\n */\n autoSendAfterAllConfirmationsResolved?: boolean;\n /**\n * Set to false to disable automatic stream resumption.\n * @default true\n */\n resume?: boolean;\n /**\n * Callback to customize the request before sending messages.\n * Use this for advanced scenarios like adding custom headers or dynamic context.\n *\n * Note: Client tool schemas are automatically sent when tools have `execute` functions.\n * This callback can add additional data alongside the auto-extracted schemas.\n */\n prepareSendMessagesRequest?: (\n options: PrepareSendMessagesRequestOptions<ChatMessage>\n ) =>\n | PrepareSendMessagesRequestResult\n | Promise<PrepareSendMessagesRequestResult>;\n};\n\nconst requestCache = new Map<string, Promise<Message[]>>();\n\n/**\n * React hook for building AI chat interfaces using an Agent\n * @param options Chat options including the agent connection\n * @returns Chat interface controls and state with added clearHistory method\n */\n/**\n * Automatically detects which tools require confirmation based on their configuration.\n * Tools require confirmation if they have no execute function AND are not server-executed.\n * @param tools - Record of tool name to tool definition\n * @returns Array of tool names that require confirmation\n */\nexport function detectToolsRequiringConfirmation(\n tools?: Record<string, AITool<unknown, unknown>>\n): string[] {\n if (!tools) return [];\n\n return Object.entries(tools)\n .filter(([_name, tool]) => !tool.execute)\n .map(([name]) => name);\n}\n\nexport function useAgentChat<\n State = unknown,\n ChatMessage extends UIMessage = UIMessage\n>(\n options: UseAgentChatOptions<State, ChatMessage>\n): ReturnType<typeof useChat<ChatMessage>> & {\n clearHistory: () => void;\n} {\n const {\n agent,\n getInitialMessages,\n messages: optionsInitialMessages,\n experimental_automaticToolResolution,\n tools,\n toolsRequiringConfirmation: manualToolsRequiringConfirmation,\n autoContinueAfterToolResult = false, // Opt-in to server auto-continuation\n autoSendAfterAllConfirmationsResolved = true, // Legacy option for client-side batching\n resume = true, // Enable stream resumption by default\n prepareSendMessagesRequest,\n ...rest\n } = options;\n\n // Auto-detect tools requiring confirmation, or use manual override\n const toolsRequiringConfirmation =\n manualToolsRequiringConfirmation ?? detectToolsRequiringConfirmation(tools);\n\n const agentUrl = new URL(\n `${// @ts-expect-error we're using a protected _url property that includes query params\n ((agent._url as string | null) || agent._pkurl)\n ?.replace(\"ws://\", \"http://\")\n .replace(\"wss://\", \"https://\")}`\n );\n\n agentUrl.searchParams.delete(\"_pk\");\n const agentUrlString = agentUrl.toString();\n\n // we need to include agent.name in cache key to prevent collisions during agent switching.\n // The URL may be stale between updateProperties() and reconnect(), but agent.name\n // is updated synchronously, so each thread gets its own cache entry\n const initialMessagesCacheKey = `${agentUrlString}|${agent.agent ?? \"\"}|${agent.name ?? \"\"}`;\n\n // Keep a ref to always point to the latest agent instance\n const agentRef = useRef(agent);\n useEffect(() => {\n agentRef.current = agent;\n }, [agent]);\n\n async function defaultGetInitialMessagesFetch({\n url\n }: GetInitialMessagesOptions) {\n const getMessagesUrl = new URL(url);\n getMessagesUrl.pathname += \"/get-messages\";\n const response = await fetch(getMessagesUrl.toString(), {\n credentials: options.credentials,\n headers: options.headers\n });\n\n if (!response.ok) {\n console.warn(\n `Failed to fetch initial messages: ${response.status} ${response.statusText}`\n );\n return [];\n }\n\n const text = await response.text();\n if (!text.trim()) {\n return [];\n }\n\n try {\n return JSON.parse(text) as ChatMessage[];\n } catch (error) {\n console.warn(\"Failed to parse initial messages JSON:\", error);\n return [];\n }\n }\n\n const getInitialMessagesFetch =\n getInitialMessages || defaultGetInitialMessagesFetch;\n\n function doGetInitialMessages(\n getInitialMessagesOptions: GetInitialMessagesOptions,\n cacheKey: string\n ) {\n if (requestCache.has(cacheKey)) {\n return requestCache.get(cacheKey)! as Promise<ChatMessage[]>;\n }\n const promise = getInitialMessagesFetch(getInitialMessagesOptions);\n requestCache.set(cacheKey, promise);\n return promise;\n }\n\n const initialMessagesPromise =\n getInitialMessages === null\n ? null\n : doGetInitialMessages(\n {\n agent: agent.agent,\n name: agent.name,\n url: agentUrlString\n },\n initialMessagesCacheKey\n );\n const initialMessages = initialMessagesPromise\n ? use(initialMessagesPromise)\n : (optionsInitialMessages ?? []);\n\n useEffect(() => {\n if (!initialMessagesPromise) {\n return;\n }\n requestCache.set(initialMessagesCacheKey, initialMessagesPromise!);\n return () => {\n if (\n requestCache.get(initialMessagesCacheKey) === initialMessagesPromise\n ) {\n requestCache.delete(initialMessagesCacheKey);\n }\n };\n }, [initialMessagesCacheKey, initialMessagesPromise]);\n\n const aiFetch = useCallback(\n async (request: RequestInfo | URL, options: RequestInit = {}) => {\n const {\n method,\n keepalive,\n headers,\n body,\n redirect,\n integrity,\n signal,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window\n } = options;\n const id = nanoid(8);\n const abortController = new AbortController();\n let controller: ReadableStreamDefaultController;\n const currentAgent = agentRef.current;\n\n // Track this request ID so the onAgentMessage handler knows to skip it\n // (this tab's aiFetch listener handles its own stream)\n localRequestIdsRef.current.add(id);\n\n signal?.addEventListener(\"abort\", () => {\n currentAgent.send(\n JSON.stringify({\n id,\n type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL\n })\n );\n\n // NOTE - If we wanted to, we could preserve the \"interrupted\" message here, with the code below\n // However, I think it might be the responsibility of the library user to implement that behavior manually?\n // Reasoning: This code could be subject to collisions, as it \"force saves\" the messages we have locally\n //\n // agent.send(JSON.stringify({\n // type: MessageType.CF_AGENT_CHAT_MESSAGES,\n // messages: ... /* some way of getting current messages ref? */\n // }))\n abortController.abort();\n // Make sure to also close the stream (cf. https://github.com/cloudflare/agents-starter/issues/69)\n try {\n controller.close();\n } catch {\n // Stream may already be errored or closed\n }\n // Clean up the request ID tracking\n localRequestIdsRef.current.delete(id);\n });\n\n currentAgent.addEventListener(\n \"message\",\n (event) => {\n let data: OutgoingMessage<ChatMessage>;\n try {\n data = JSON.parse(event.data) as OutgoingMessage<ChatMessage>;\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE) {\n if (data.id === id) {\n if (data.error) {\n controller.error(new Error(data.body));\n abortController.abort();\n // Clean up the request ID tracking\n localRequestIdsRef.current.delete(id);\n } else {\n // Only enqueue non-empty data to prevent JSON parsing errors\n if (data.body?.trim()) {\n controller.enqueue(\n new TextEncoder().encode(`data: ${data.body}\\n\\n`)\n );\n }\n if (data.done) {\n try {\n controller.close();\n } catch {\n // Stream may already be errored or closed\n }\n abortController.abort();\n // Clean up the request ID tracking\n localRequestIdsRef.current.delete(id);\n }\n }\n }\n }\n },\n { signal: abortController.signal }\n );\n\n const stream = new ReadableStream({\n start(c) {\n controller = c;\n },\n cancel(reason?: unknown) {\n console.warn(\n \"[agents/ai-react] cancelling stream\",\n id,\n reason || \"no reason\"\n );\n }\n });\n\n currentAgent.send(\n JSON.stringify({\n id,\n init: {\n body,\n credentials,\n headers,\n integrity,\n keepalive,\n method,\n mode,\n redirect,\n referrer,\n referrerPolicy,\n window\n },\n type: MessageType.CF_AGENT_USE_CHAT_REQUEST,\n url: request.toString()\n })\n );\n\n return new Response(stream);\n },\n []\n );\n\n // Use synchronous ref updates to avoid race conditions between effect runs.\n // This ensures the ref always has the latest value before any effect reads it.\n const toolsRef = useRef(tools);\n toolsRef.current = tools;\n\n const prepareSendMessagesRequestRef = useRef(prepareSendMessagesRequest);\n prepareSendMessagesRequestRef.current = prepareSendMessagesRequest;\n\n const customTransport: ChatTransport<ChatMessage> = useMemo(\n () => ({\n sendMessages: async (\n sendMessageOptions: Parameters<\n typeof DefaultChatTransport.prototype.sendMessages\n >[0]\n ) => {\n // Extract schemas from tools with execute functions\n const clientToolSchemas = extractClientToolSchemas(toolsRef.current);\n\n const combinedPrepare =\n clientToolSchemas || prepareSendMessagesRequestRef.current\n ? async (\n prepareOptions: PrepareSendMessagesRequestOptions<ChatMessage>\n ): Promise<InternalPrepareResult> => {\n // Start with auto-extracted client tool schemas\n let body: Record<string, unknown> = {};\n let headers: HeadersInit | undefined;\n let credentials: RequestCredentials | undefined;\n let api: string | undefined;\n\n if (clientToolSchemas) {\n body = {\n id: prepareOptions.id,\n messages: prepareOptions.messages,\n trigger: prepareOptions.trigger,\n clientTools: clientToolSchemas\n };\n }\n\n // Apply prepareSendMessagesRequest callback for additional customization\n if (prepareSendMessagesRequestRef.current) {\n const userResult =\n await prepareSendMessagesRequestRef.current(prepareOptions);\n\n // user's callback can override or extend\n headers = userResult.headers;\n credentials = userResult.credentials;\n api = userResult.api;\n body = {\n ...body,\n ...(userResult.body ?? {})\n };\n }\n\n return { body, headers, credentials, api };\n }\n : undefined;\n\n const transport = new DefaultChatTransport<ChatMessage>({\n api: agentUrlString,\n fetch: aiFetch,\n prepareSendMessagesRequest: combinedPrepare\n });\n return transport.sendMessages(sendMessageOptions);\n },\n reconnectToStream: async () => null\n }),\n [agentUrlString, aiFetch]\n );\n\n const useChatHelpers = useChat<ChatMessage>({\n ...rest,\n messages: initialMessages,\n transport: customTransport,\n id: agent._pk\n // Note: We handle stream resumption via WebSocket instead of HTTP,\n // so we don't pass 'resume' to useChat. The onStreamResuming handler\n // automatically resumes active streams when the WebSocket reconnects.\n });\n\n const processedToolCalls = useRef(new Set<string>());\n const isResolvingToolsRef = useRef(false);\n\n // Fix for issue #728: Track client-side tool results in local state\n // to ensure tool parts show output-available immediately after execution.\n const [clientToolResults, setClientToolResults] = useState<\n Map<string, unknown>\n >(new Map());\n\n // Ref to access current messages in callbacks without stale closures\n const messagesRef = useRef(useChatHelpers.messages);\n messagesRef.current = useChatHelpers.messages;\n\n // Calculate pending confirmations for the latest assistant message\n const lastMessage =\n useChatHelpers.messages[useChatHelpers.messages.length - 1];\n\n const pendingConfirmations = (() => {\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n return { messageId: undefined, toolCallIds: new Set<string>() };\n }\n\n const pendingIds = new Set<string>();\n for (const part of lastMessage.parts ?? []) {\n if (\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n toolsRequiringConfirmation.includes(getToolName(part))\n ) {\n pendingIds.add(part.toolCallId);\n }\n }\n return { messageId: lastMessage.id, toolCallIds: pendingIds };\n })();\n\n const pendingConfirmationsRef = useRef(pendingConfirmations);\n pendingConfirmationsRef.current = pendingConfirmations;\n\n // Automatic tool resolution effect.\n useEffect(() => {\n if (!experimental_automaticToolResolution) {\n return;\n }\n\n // Prevent re-entry while async operations are in progress\n if (isResolvingToolsRef.current) {\n return;\n }\n\n const lastMessage =\n useChatHelpers.messages[useChatHelpers.messages.length - 1];\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n return;\n }\n\n const toolCalls = lastMessage.parts.filter(\n (part) =>\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n !processedToolCalls.current.has(part.toolCallId)\n );\n\n if (toolCalls.length > 0) {\n // Capture tools synchronously before async work\n const currentTools = toolsRef.current;\n const toolCallsToResolve = toolCalls.filter(\n (part) =>\n isToolUIPart(part) &&\n !toolsRequiringConfirmation.includes(getToolName(part)) &&\n currentTools?.[getToolName(part)]?.execute\n );\n\n if (toolCallsToResolve.length > 0) {\n isResolvingToolsRef.current = true;\n\n (async () => {\n try {\n const toolResults: Array<{\n toolCallId: string;\n toolName: string;\n output: unknown;\n }> = [];\n\n for (const part of toolCallsToResolve) {\n if (isToolUIPart(part)) {\n let toolOutput: unknown = null;\n const toolName = getToolName(part);\n const tool = currentTools?.[toolName];\n\n if (tool?.execute && part.input !== undefined) {\n try {\n toolOutput = await tool.execute(part.input);\n } catch (error) {\n toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;\n }\n }\n\n processedToolCalls.current.add(part.toolCallId);\n\n toolResults.push({\n toolCallId: part.toolCallId,\n toolName,\n output: toolOutput\n });\n }\n }\n\n if (toolResults.length > 0) {\n // Send tool results to server first (server is source of truth)\n for (const result of toolResults) {\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_RESULT,\n toolCallId: result.toolCallId,\n toolName: result.toolName,\n output: result.output,\n autoContinue: autoContinueAfterToolResult\n })\n );\n }\n\n // Also update local state via AI SDK for immediate UI feedback\n await Promise.all(\n toolResults.map((result) =>\n useChatHelpers.addToolResult({\n tool: result.toolName,\n toolCallId: result.toolCallId,\n output: result.output\n })\n )\n );\n\n setClientToolResults((prev) => {\n const newMap = new Map(prev);\n for (const result of toolResults) {\n newMap.set(result.toolCallId, result.output);\n }\n return newMap;\n });\n }\n\n // Note: We don't call sendMessage() here anymore.\n // The server will continue the conversation after applying tool results.\n } finally {\n isResolvingToolsRef.current = false;\n }\n })();\n }\n }\n }, [\n useChatHelpers.messages,\n experimental_automaticToolResolution,\n useChatHelpers.addToolResult,\n toolsRequiringConfirmation,\n autoContinueAfterToolResult\n ]);\n\n /**\n * Contains the request ID, accumulated message parts, and a unique message ID.\n * Used for both resumed streams and real-time broadcasts from other tabs.\n */\n const activeStreamRef = useRef<{\n id: string;\n messageId: string;\n parts: ChatMessage[\"parts\"];\n } | null>(null);\n\n /**\n * Tracks request IDs initiated by this tab via aiFetch.\n * Used to distinguish local requests from broadcasts.\n */\n const localRequestIdsRef = useRef<Set<string>>(new Set());\n\n useEffect(() => {\n /**\n * Unified message handler that parses JSON once and dispatches based on type.\n * Avoids duplicate parsing overhead from separate listeners.\n */\n function onAgentMessage(event: MessageEvent) {\n if (typeof event.data !== \"string\") return;\n\n let data: OutgoingMessage<ChatMessage>;\n try {\n data = JSON.parse(event.data) as OutgoingMessage<ChatMessage>;\n } catch (_error) {\n return;\n }\n\n switch (data.type) {\n case MessageType.CF_AGENT_CHAT_CLEAR:\n useChatHelpers.setMessages([]);\n break;\n\n case MessageType.CF_AGENT_CHAT_MESSAGES:\n useChatHelpers.setMessages(data.messages);\n break;\n\n case MessageType.CF_AGENT_MESSAGE_UPDATED:\n // Server updated a message (e.g., applied tool result)\n // Update the specific message in local state\n useChatHelpers.setMessages((prevMessages: ChatMessage[]) => {\n const updatedMessage = data.message;\n\n // First try to find by message ID\n let idx = prevMessages.findIndex((m) => m.id === updatedMessage.id);\n\n // If not found by ID, try to find by toolCallId\n // This handles the case where client has AI SDK-generated IDs\n // but server has server-generated IDs\n if (idx < 0) {\n const updatedToolCallIds = new Set(\n updatedMessage.parts\n .filter(\n (p: ChatMessage[\"parts\"][number]) =>\n \"toolCallId\" in p && p.toolCallId\n )\n .map(\n (p: ChatMessage[\"parts\"][number]) =>\n (p as { toolCallId: string }).toolCallId\n )\n );\n\n if (updatedToolCallIds.size > 0) {\n idx = prevMessages.findIndex((m) =>\n m.parts.some(\n (p) =>\n \"toolCallId\" in p &&\n updatedToolCallIds.has(\n (p as { toolCallId: string }).toolCallId\n )\n )\n );\n }\n }\n\n if (idx >= 0) {\n const updated = [...prevMessages];\n // Preserve the client's message ID but update the content\n updated[idx] = {\n ...updatedMessage,\n id: prevMessages[idx].id\n };\n return updated;\n }\n // Message not found, append it\n return [...prevMessages, updatedMessage];\n });\n break;\n\n case MessageType.CF_AGENT_STREAM_RESUMING:\n if (!resume) return;\n // Clear any previous incomplete active stream to prevent memory leak\n activeStreamRef.current = null;\n // Initialize active stream state with unique ID\n activeStreamRef.current = {\n id: data.id,\n messageId: nanoid(),\n parts: []\n };\n // Send ACK to server - we're ready to receive chunks\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_ACK,\n id: data.id\n })\n );\n break;\n\n case MessageType.CF_AGENT_USE_CHAT_RESPONSE: {\n // Skip if this is a response to a request this tab initiated\n // (handled by the aiFetch listener instead)\n if (localRequestIdsRef.current.has(data.id)) return;\n\n // For continuations, find the last assistant message ID to append to\n const isContinuation = data.continuation === true;\n\n // Initialize stream state for broadcasts from other tabs\n if (\n !activeStreamRef.current ||\n activeStreamRef.current.id !== data.id\n ) {\n let messageId = nanoid();\n let existingParts: ChatMessage[\"parts\"] = [];\n\n // For continuations, use the last assistant message's ID and parts\n if (isContinuation) {\n const currentMessages = messagesRef.current;\n for (let i = currentMessages.length - 1; i >= 0; i--) {\n if (currentMessages[i].role === \"assistant\") {\n messageId = currentMessages[i].id;\n existingParts = [...currentMessages[i].parts];\n break;\n }\n }\n }\n\n activeStreamRef.current = {\n id: data.id,\n messageId,\n parts: existingParts\n };\n }\n\n const activeMsg = activeStreamRef.current;\n\n if (data.body?.trim()) {\n try {\n const chunkData = JSON.parse(data.body);\n\n // Handle all chunk types for complete message reconstruction\n switch (chunkData.type) {\n case \"text-start\": {\n activeMsg.parts.push({\n type: \"text\",\n text: \"\",\n state: \"streaming\"\n });\n break;\n }\n case \"text-delta\": {\n const lastTextPart = [...activeMsg.parts]\n .reverse()\n .find((p) => p.type === \"text\");\n if (lastTextPart && lastTextPart.type === \"text\") {\n lastTextPart.text += chunkData.delta;\n } else {\n // Handle plain text responses (no text-start)\n activeMsg.parts.push({\n type: \"text\",\n text: chunkData.delta\n });\n }\n break;\n }\n case \"text-end\": {\n const lastTextPart = [...activeMsg.parts]\n .reverse()\n .find((p) => p.type === \"text\");\n if (lastTextPart && \"state\" in lastTextPart) {\n lastTextPart.state = \"done\";\n }\n break;\n }\n case \"reasoning-start\": {\n activeMsg.parts.push({\n type: \"reasoning\",\n text: \"\",\n state: \"streaming\"\n });\n break;\n }\n case \"reasoning-delta\": {\n const lastReasoningPart = [...activeMsg.parts]\n .reverse()\n .find((p) => p.type === \"reasoning\");\n if (\n lastReasoningPart &&\n lastReasoningPart.type === \"reasoning\"\n ) {\n lastReasoningPart.text += chunkData.delta;\n }\n break;\n }\n case \"reasoning-end\": {\n const lastReasoningPart = [...activeMsg.parts]\n .reverse()\n .find((p) => p.type === \"reasoning\");\n if (lastReasoningPart && \"state\" in lastReasoningPart) {\n lastReasoningPart.state = \"done\";\n }\n break;\n }\n case \"file\": {\n activeMsg.parts.push({\n type: \"file\",\n mediaType: chunkData.mediaType,\n url: chunkData.url\n });\n break;\n }\n case \"source-url\": {\n activeMsg.parts.push({\n type: \"source-url\",\n sourceId: chunkData.sourceId,\n url: chunkData.url,\n title: chunkData.title\n });\n break;\n }\n case \"source-document\": {\n activeMsg.parts.push({\n type: \"source-document\",\n sourceId: chunkData.sourceId,\n mediaType: chunkData.mediaType,\n title: chunkData.title,\n filename: chunkData.filename\n });\n break;\n }\n case \"tool-input-available\": {\n // Add tool call part when input is available\n activeMsg.parts.push({\n type: `tool-${chunkData.toolName}`,\n toolCallId: chunkData.toolCallId,\n toolName: chunkData.toolName,\n state: \"input-available\",\n input: chunkData.input\n } as ChatMessage[\"parts\"][number]);\n break;\n }\n case \"tool-output-available\": {\n // Update existing tool part with output using immutable pattern\n activeMsg.parts = activeMsg.parts.map((p) => {\n if (\n \"toolCallId\" in p &&\n p.toolCallId === chunkData.toolCallId &&\n \"state\" in p\n ) {\n return {\n ...p,\n state: \"output-available\",\n output: chunkData.output\n } as ChatMessage[\"parts\"][number];\n }\n return p;\n });\n break;\n }\n case \"step-start\": {\n activeMsg.parts.push({ type: \"step-start\" });\n break;\n }\n // Other chunk types (tool-input-start, tool-input-delta, etc.)\n // are intermediate states - the final state will be captured above\n }\n\n // Update messages with the partial response\n useChatHelpers.setMessages((prevMessages: ChatMessage[]) => {\n if (!activeMsg) return prevMessages;\n\n const existingIdx = prevMessages.findIndex(\n (m) => m.id === activeMsg.messageId\n );\n\n const partialMessage = {\n id: activeMsg.messageId,\n role: \"assistant\" as const,\n parts: [...activeMsg.parts]\n } as unknown as ChatMessage;\n\n if (existingIdx >= 0) {\n const updated = [...prevMessages];\n updated[existingIdx] = partialMessage;\n return updated;\n }\n return [...prevMessages, partialMessage];\n });\n } catch (parseError) {\n // Log corrupted chunk for debugging - could indicate data loss\n console.warn(\n \"[useAgentChat] Failed to parse stream chunk:\",\n parseError instanceof Error ? parseError.message : parseError,\n \"body:\",\n data.body?.slice(0, 100) // Truncate for logging\n );\n }\n }\n\n // Clear on completion or error\n if (data.done || data.error) {\n activeStreamRef.current = null;\n }\n break;\n }\n }\n }\n\n agent.addEventListener(\"message\", onAgentMessage);\n return () => {\n agent.removeEventListener(\"message\", onAgentMessage);\n // Clear active stream state on cleanup to prevent memory leak\n activeStreamRef.current = null;\n };\n }, [agent, useChatHelpers.setMessages, resume]);\n\n // Wrapper that sends tool result to server and optionally continues conversation.\n const addToolResultAndSendMessage: typeof useChatHelpers.addToolResult =\n async (args) => {\n const { toolCallId } = args;\n const toolName = \"tool\" in args ? args.tool : \"\";\n const output = \"output\" in args ? args.output : undefined;\n\n // Send tool result to server (server is source of truth)\n // Include flag to tell server whether to auto-continue\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_RESULT,\n toolCallId,\n toolName,\n output,\n autoContinue: autoContinueAfterToolResult\n })\n );\n\n setClientToolResults((prev) => new Map(prev).set(toolCallId, output));\n\n // Call AI SDK's addToolResult for local state update (non-blocking)\n // We don't await this since clientToolResults provides immediate UI feedback\n useChatHelpers.addToolResult(args);\n\n // If server auto-continuation is disabled, client needs to trigger continuation\n if (!autoContinueAfterToolResult) {\n // Use legacy behavior: batch confirmations or send immediately\n if (!autoSendAfterAllConfirmationsResolved) {\n // Always send immediately\n useChatHelpers.sendMessage();\n return;\n }\n\n // Wait for all confirmations before sending\n const pending = pendingConfirmationsRef.current?.toolCallIds;\n if (!pending) {\n useChatHelpers.sendMessage();\n return;\n }\n\n const wasLast = pending.size === 1 && pending.has(toolCallId);\n if (pending.has(toolCallId)) {\n pending.delete(toolCallId);\n }\n\n if (wasLast || pending.size === 0) {\n useChatHelpers.sendMessage();\n }\n }\n // If autoContinueAfterToolResult is true, server handles continuation\n };\n\n // Fix for issue #728: Merge client-side tool results with messages\n // so tool parts show output-available immediately after execution\n const messagesWithToolResults = useMemo(() => {\n if (clientToolResults.size === 0) {\n return useChatHelpers.messages;\n }\n return useChatHelpers.messages.map((msg) => ({\n ...msg,\n parts: msg.parts.map((p) => {\n if (\n !(\"toolCallId\" in p) ||\n !(\"state\" in p) ||\n p.state !== \"input-available\" ||\n !clientToolResults.has(p.toolCallId)\n ) {\n return p;\n }\n return {\n ...p,\n state: \"output-available\" as const,\n output: clientToolResults.get(p.toolCallId)\n };\n })\n })) as ChatMessage[];\n }, [useChatHelpers.messages, clientToolResults]);\n\n // Cleanup stale entries from clientToolResults when messages change\n // to prevent memory leak in long conversations.\n // Note: We intentionally exclude clientToolResults from deps to avoid infinite loops.\n // The functional update form gives us access to the previous state.\n useEffect(() => {\n // Collect all current toolCallIds from messages\n const currentToolCallIds = new Set<string>();\n for (const msg of useChatHelpers.messages) {\n for (const part of msg.parts) {\n if (\"toolCallId\" in part && part.toolCallId) {\n currentToolCallIds.add(part.toolCallId);\n }\n }\n }\n\n // Use functional update to check and clean stale entries atomically\n setClientToolResults((prev) => {\n if (prev.size === 0) return prev;\n\n // Check if any entries are stale\n let hasStaleEntries = false;\n for (const toolCallId of prev.keys()) {\n if (!currentToolCallIds.has(toolCallId)) {\n hasStaleEntries = true;\n break;\n }\n }\n\n // Only create new Map if there are stale entries to remove\n if (!hasStaleEntries) return prev;\n\n const newMap = new Map<string, unknown>();\n for (const [id, output] of prev) {\n if (currentToolCallIds.has(id)) {\n newMap.set(id, output);\n }\n }\n return newMap;\n });\n\n // Also cleanup processedToolCalls to prevent issues in long conversations\n for (const toolCallId of processedToolCalls.current) {\n if (!currentToolCallIds.has(toolCallId)) {\n processedToolCalls.current.delete(toolCallId);\n }\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [useChatHelpers.messages]);\n\n return {\n ...useChatHelpers,\n messages: messagesWithToolResults,\n addToolResult: addToolResultAndSendMessage,\n clearHistory: () => {\n useChatHelpers.setMessages([]);\n setClientToolResults(new Map());\n processedToolCalls.current.clear();\n agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_CHAT_CLEAR\n })\n );\n },\n setMessages: (\n messages: Parameters<typeof useChatHelpers.setMessages>[0]\n ) => {\n useChatHelpers.setMessages(messages);\n agent.send(\n JSON.stringify({\n messages: Array.isArray(messages) ? messages : [],\n type: MessageType.CF_AGENT_CHAT_MESSAGES\n })\n );\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAoEA,SAAgB,yBACd,OACgC;AAChC,KAAI,CAAC,MAAO,QAAO;CAEnB,MAAMA,UAA8B,OAAO,QAAQ,MAAM,CACtD,QAAQ,CAAC,GAAGC,YAAUA,OAAK,QAAQ,CACnC,KAAK,CAAC,MAAMA,YAAU;AACrB,MAAIA,OAAK,eAAe,CAACA,OAAK,WAC5B,SAAQ,KACN,wBAAwB,KAAK,kEAC9B;AAEH,SAAO;GACL;GACA,aAAaA,OAAK;GAClB,YAAYA,OAAK,cAAcA,OAAK;GACrC;GACD;AAEJ,QAAO,QAAQ,SAAS,IAAI,UAAU;;AA4IxC,MAAM,+BAAe,IAAI,KAAiC;;;;;;;;;;;;AAa1D,SAAgB,iCACd,OACU;AACV,KAAI,CAAC,MAAO,QAAO,EAAE;AAErB,QAAO,OAAO,QAAQ,MAAM,CACzB,QAAQ,CAAC,OAAOA,YAAU,CAACA,OAAK,QAAQ,CACxC,KAAK,CAAC,UAAU,KAAK;;AAG1B,SAAgB,aAId,SAGA;CACA,MAAM,EACJ,OACA,oBACA,UAAU,wBACV,sCACA,OACA,4BAA4B,kCAC5B,8BAA8B,OAC9B,wCAAwC,MACxC,SAAS,MACT,4BACA,GAAG,SACD;CAGJ,MAAM,6BACJ,oCAAoC,iCAAiC,MAAM;CAE7E,MAAM,WAAW,IAAI,IACnB,IACE,MAAM,QAA0B,MAAM,SACpC,QAAQ,SAAS,UA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qB,IAAI,KAAa;AAC5C,OAAK,MAAM,OAAO,eAAe,SAC/B,MAAK,MAAM,QAAQ,IAAI,MACrB,KAAI,gBAAgB,QAAQ,KAAK,WAC/B,oBAAmB,IAAI,KAAK,WAAW;AAM7C,wBAAsB,SAAS;AAC7B,OAAI,KAAK,SAAS,EAAG,QAAO;GAG5B,IAAI,kBAAkB;AACtB,QAAK,MAAM,cAAc,KAAK,MAAM,CAClC,KAAI,CAAC,mBAAmB,IAAI,WAAW,EAAE;AACvC,sBAAkB;AAClB;;AAKJ,OAAI,CAAC,gBAAiB,QAAO;GAE7B,MAAM,yBAAS,IAAI,KAAsB;AACzC,QAAK,MAAM,CAAC,IAAI,WAAW,KACzB,KAAI,mBAAmB,IAAI,GAAG,CAC5B,QAAO,IAAI,IAAI,OAAO;AAG1B,UAAO;IACP;AAGF,OAAK,MAAM,cAAc,mBAAmB,QAC1C,KAAI,CAAC,mBAAmB,IAAI,WAAW,CACrC,oBAAmB,QAAQ,OAAO,WAAW;IAIhD,CAAC,eAAe,SAAS,CAAC;AAE7B,QAAO;EACL,GAAG;EACH,UAAU;EACV,eAAe;EACf,oBAAoB;AAClB,kBAAe,YAAY,EAAE,CAAC;AAC9B,wCAAqB,IAAI,KAAK,CAAC;AAC/B,sBAAmB,QAAQ,OAAO;AAClC,SAAM,KACJ,KAAK,UAAU,EACb,MAAM,YAAY,qBACnB,CAAC,CACH;;EAEH,cACE,aACG;AACH,kBAAe,YAAY,SAAS;AACpC,SAAM,KACJ,KAAK,UAAU;IACb,UAAU,MAAM,QAAQ,SAAS,GAAG,WAAW,EAAE;IACjD,MAAM,YAAY;IACnB,CAAC,CACH;;EAEJ"}
@@ -0,0 +1,28 @@
1
+ //#region src/ai-types.ts
2
+ /**
3
+ * Enum for message types to improve type safety and maintainability
4
+ */
5
+ let MessageType = /* @__PURE__ */ function(MessageType$1) {
6
+ MessageType$1["CF_AGENT_CHAT_MESSAGES"] = "cf_agent_chat_messages";
7
+ MessageType$1["CF_AGENT_USE_CHAT_REQUEST"] = "cf_agent_use_chat_request";
8
+ MessageType$1["CF_AGENT_USE_CHAT_RESPONSE"] = "cf_agent_use_chat_response";
9
+ MessageType$1["CF_AGENT_CHAT_CLEAR"] = "cf_agent_chat_clear";
10
+ MessageType$1["CF_AGENT_CHAT_REQUEST_CANCEL"] = "cf_agent_chat_request_cancel";
11
+ /** Sent by server when client connects and there's an active stream to resume */
12
+ MessageType$1["CF_AGENT_STREAM_RESUMING"] = "cf_agent_stream_resuming";
13
+ /** Sent by client to acknowledge stream resuming notification and request chunks */
14
+ MessageType$1["CF_AGENT_STREAM_RESUME_ACK"] = "cf_agent_stream_resume_ack";
15
+ MessageType$1["CF_AGENT_MCP_SERVERS"] = "cf_agent_mcp_servers";
16
+ MessageType$1["CF_MCP_AGENT_EVENT"] = "cf_mcp_agent_event";
17
+ MessageType$1["CF_AGENT_STATE"] = "cf_agent_state";
18
+ MessageType$1["RPC"] = "rpc";
19
+ /** Client sends tool result to server (for client-side tools) */
20
+ MessageType$1["CF_AGENT_TOOL_RESULT"] = "cf_agent_tool_result";
21
+ /** Server notifies client that a message was updated (e.g., tool result applied) */
22
+ MessageType$1["CF_AGENT_MESSAGE_UPDATED"] = "cf_agent_message_updated";
23
+ return MessageType$1;
24
+ }({});
25
+
26
+ //#endregion
27
+ export { MessageType as t };
28
+ //# sourceMappingURL=ai-types-DEtF_8Km.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-types-DEtF_8Km.js","names":[],"sources":["../src/ai-types.ts"],"sourcesContent":["import type { UIMessage } from \"ai\";\n\n/**\n * Enum for message types to improve type safety and maintainability\n */\nexport enum MessageType {\n CF_AGENT_CHAT_MESSAGES = \"cf_agent_chat_messages\",\n CF_AGENT_USE_CHAT_REQUEST = \"cf_agent_use_chat_request\",\n CF_AGENT_USE_CHAT_RESPONSE = \"cf_agent_use_chat_response\",\n CF_AGENT_CHAT_CLEAR = \"cf_agent_chat_clear\",\n CF_AGENT_CHAT_REQUEST_CANCEL = \"cf_agent_chat_request_cancel\",\n\n /** Sent by server when client connects and there's an active stream to resume */\n CF_AGENT_STREAM_RESUMING = \"cf_agent_stream_resuming\",\n /** Sent by client to acknowledge stream resuming notification and request chunks */\n CF_AGENT_STREAM_RESUME_ACK = \"cf_agent_stream_resume_ack\",\n\n CF_AGENT_MCP_SERVERS = \"cf_agent_mcp_servers\",\n CF_MCP_AGENT_EVENT = \"cf_mcp_agent_event\",\n CF_AGENT_STATE = \"cf_agent_state\",\n RPC = \"rpc\",\n\n /** Client sends tool result to server (for client-side tools) */\n CF_AGENT_TOOL_RESULT = \"cf_agent_tool_result\",\n /** Server notifies client that a message was updated (e.g., tool result applied) */\n CF_AGENT_MESSAGE_UPDATED = \"cf_agent_message_updated\"\n}\n\n/**\n * Types of messages sent from the Agent to clients\n */\nexport type OutgoingMessage<ChatMessage extends UIMessage = UIMessage> =\n | {\n /** Indicates this message is a command to clear chat history */\n type: MessageType.CF_AGENT_CHAT_CLEAR;\n }\n | {\n /** Indicates this message contains updated chat messages */\n type: MessageType.CF_AGENT_CHAT_MESSAGES;\n /** Array of chat messages */\n messages: ChatMessage[];\n }\n | {\n /** Indicates this message is a response to a chat request */\n type: MessageType.CF_AGENT_USE_CHAT_RESPONSE;\n /** Unique ID of the request this response corresponds to */\n id: string;\n /** Content body of the response */\n body: string;\n /** Whether this is the final chunk of the response */\n done: boolean;\n /** Whether this response contains an error */\n error?: boolean;\n /** Whether this is a continuation (append to last assistant message) */\n continuation?: boolean;\n }\n | {\n /** Indicates the server is resuming an active stream */\n type: MessageType.CF_AGENT_STREAM_RESUMING;\n /** The request ID of the stream being resumed */\n id: string;\n }\n | {\n /** Server notifies client that a message was updated (e.g., tool result applied) */\n type: MessageType.CF_AGENT_MESSAGE_UPDATED;\n /** The updated message */\n message: ChatMessage;\n };\n\n/**\n * Types of messages sent from clients to the Agent\n */\nexport type IncomingMessage<ChatMessage extends UIMessage = UIMessage> =\n | {\n /** Indicates this message is a command to clear chat history */\n type: MessageType.CF_AGENT_CHAT_CLEAR;\n }\n | {\n /** Indicates this message is a request to the chat API */\n type: MessageType.CF_AGENT_USE_CHAT_REQUEST;\n /** Unique ID for this request */\n id: string;\n /** Request initialization options */\n init: Pick<\n RequestInit,\n | \"method\"\n | \"keepalive\"\n | \"headers\"\n | \"body\"\n | \"redirect\"\n | \"integrity\"\n | \"credentials\"\n | \"mode\"\n | \"referrer\"\n | \"referrerPolicy\"\n | \"window\"\n >;\n }\n | {\n /** Indicates this message contains updated chat messages */\n type: MessageType.CF_AGENT_CHAT_MESSAGES;\n /** Array of chat messages */\n messages: ChatMessage[];\n }\n | {\n /** Indicates the user wants to stop generation of this message */\n type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL;\n id: string;\n }\n | {\n /** Client acknowledges stream resuming notification and is ready to receive chunks */\n type: MessageType.CF_AGENT_STREAM_RESUME_ACK;\n /** The request ID of the stream being resumed */\n id: string;\n }\n | {\n /** Client sends tool result to server (for client-side tools) */\n type: MessageType.CF_AGENT_TOOL_RESULT;\n /** The tool call ID this result is for */\n toolCallId: string;\n /** The name of the tool */\n toolName: string;\n /** The output from the tool execution */\n output: unknown;\n /** Whether server should auto-continue the conversation after applying result */\n autoContinue?: boolean;\n };\n"],"mappings":";;;;AAKA,IAAY,sDAAL;AACL;AACA;AACA;AACA;AACA;;AAGA;;AAEA;AAEA;AACA;AACA;AACA;;AAGA;;AAEA"}
@@ -0,0 +1,127 @@
1
+ import { UIMessage } from "ai";
2
+
3
+ //#region src/ai-types.d.ts
4
+
5
+ /**
6
+ * Enum for message types to improve type safety and maintainability
7
+ */
8
+ declare enum MessageType {
9
+ CF_AGENT_CHAT_MESSAGES = "cf_agent_chat_messages",
10
+ CF_AGENT_USE_CHAT_REQUEST = "cf_agent_use_chat_request",
11
+ CF_AGENT_USE_CHAT_RESPONSE = "cf_agent_use_chat_response",
12
+ CF_AGENT_CHAT_CLEAR = "cf_agent_chat_clear",
13
+ CF_AGENT_CHAT_REQUEST_CANCEL = "cf_agent_chat_request_cancel",
14
+ /** Sent by server when client connects and there's an active stream to resume */
15
+ CF_AGENT_STREAM_RESUMING = "cf_agent_stream_resuming",
16
+ /** Sent by client to acknowledge stream resuming notification and request chunks */
17
+ CF_AGENT_STREAM_RESUME_ACK = "cf_agent_stream_resume_ack",
18
+ CF_AGENT_MCP_SERVERS = "cf_agent_mcp_servers",
19
+ CF_MCP_AGENT_EVENT = "cf_mcp_agent_event",
20
+ CF_AGENT_STATE = "cf_agent_state",
21
+ RPC = "rpc",
22
+ /** Client sends tool result to server (for client-side tools) */
23
+ CF_AGENT_TOOL_RESULT = "cf_agent_tool_result",
24
+ /** Server notifies client that a message was updated (e.g., tool result applied) */
25
+ CF_AGENT_MESSAGE_UPDATED = "cf_agent_message_updated"
26
+ }
27
+ /**
28
+ * Types of messages sent from the Agent to clients
29
+ */
30
+ type OutgoingMessage<ChatMessage extends UIMessage = UIMessage> =
31
+ | {
32
+ /** Indicates this message is a command to clear chat history */
33
+ type: MessageType.CF_AGENT_CHAT_CLEAR;
34
+ }
35
+ | {
36
+ /** Indicates this message contains updated chat messages */
37
+ type: MessageType.CF_AGENT_CHAT_MESSAGES;
38
+ /** Array of chat messages */
39
+ messages: ChatMessage[];
40
+ }
41
+ | {
42
+ /** Indicates this message is a response to a chat request */
43
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE;
44
+ /** Unique ID of the request this response corresponds to */
45
+ id: string;
46
+ /** Content body of the response */
47
+ body: string;
48
+ /** Whether this is the final chunk of the response */
49
+ done: boolean;
50
+ /** Whether this response contains an error */
51
+ error?: boolean;
52
+ /** Whether this is a continuation (append to last assistant message) */
53
+ continuation?: boolean;
54
+ }
55
+ | {
56
+ /** Indicates the server is resuming an active stream */
57
+ type: MessageType.CF_AGENT_STREAM_RESUMING;
58
+ /** The request ID of the stream being resumed */
59
+ id: string;
60
+ }
61
+ | {
62
+ /** Server notifies client that a message was updated (e.g., tool result applied) */
63
+ type: MessageType.CF_AGENT_MESSAGE_UPDATED;
64
+ /** The updated message */
65
+ message: ChatMessage;
66
+ };
67
+ /**
68
+ * Types of messages sent from clients to the Agent
69
+ */
70
+ type IncomingMessage<ChatMessage extends UIMessage = UIMessage> =
71
+ | {
72
+ /** Indicates this message is a command to clear chat history */
73
+ type: MessageType.CF_AGENT_CHAT_CLEAR;
74
+ }
75
+ | {
76
+ /** Indicates this message is a request to the chat API */
77
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST;
78
+ /** Unique ID for this request */
79
+ id: string;
80
+ /** Request initialization options */
81
+ init: Pick<
82
+ RequestInit,
83
+ | "method"
84
+ | "keepalive"
85
+ | "headers"
86
+ | "body"
87
+ | "redirect"
88
+ | "integrity"
89
+ | "credentials"
90
+ | "mode"
91
+ | "referrer"
92
+ | "referrerPolicy"
93
+ | "window"
94
+ >;
95
+ }
96
+ | {
97
+ /** Indicates this message contains updated chat messages */
98
+ type: MessageType.CF_AGENT_CHAT_MESSAGES;
99
+ /** Array of chat messages */
100
+ messages: ChatMessage[];
101
+ }
102
+ | {
103
+ /** Indicates the user wants to stop generation of this message */
104
+ type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL;
105
+ id: string;
106
+ }
107
+ | {
108
+ /** Client acknowledges stream resuming notification and is ready to receive chunks */
109
+ type: MessageType.CF_AGENT_STREAM_RESUME_ACK;
110
+ /** The request ID of the stream being resumed */
111
+ id: string;
112
+ }
113
+ | {
114
+ /** Client sends tool result to server (for client-side tools) */
115
+ type: MessageType.CF_AGENT_TOOL_RESULT;
116
+ /** The tool call ID this result is for */
117
+ toolCallId: string;
118
+ /** The name of the tool */
119
+ toolName: string;
120
+ /** The output from the tool execution */
121
+ output: unknown;
122
+ /** Whether server should auto-continue the conversation after applying result */
123
+ autoContinue?: boolean;
124
+ };
125
+ //#endregion
126
+ export { MessageType as n, OutgoingMessage as r, IncomingMessage as t };
127
+ //# sourceMappingURL=ai-types-U8lYA0o8.d.ts.map
@@ -1,74 +1,6 @@
1
- import { Message } from "ai";
2
-
3
- /**
4
- * Types of messages sent from the Agent to clients
5
- */
6
- type OutgoingMessage =
7
- | {
8
- /** Indicates this message contains updated chat messages */
9
- type: "cf_agent_chat_messages";
10
- /** Array of chat messages */
11
- messages: Message[];
12
- }
13
- | {
14
- /** Indicates this message is a response to a chat request */
15
- type: "cf_agent_use_chat_response";
16
- /** Unique ID of the request this response corresponds to */
17
- id: string;
18
- /** Content body of the response */
19
- body: string;
20
- /** Whether this is the final chunk of the response */
21
- done: boolean;
22
- }
23
- | {
24
- /** Indicates this message contains updated chat messages */
25
- type: "cf_agent_chat_messages";
26
- /** Array of chat messages */
27
- messages: Message[];
28
- }
29
- | {
30
- /** Indicates this message is a command to clear chat history */
31
- type: "cf_agent_chat_clear";
32
- };
33
- /**
34
- * Types of messages sent from clients to the Agent
35
- */
36
- type IncomingMessage =
37
- | {
38
- /** Indicates this message is a request to the chat API */
39
- type: "cf_agent_use_chat_request";
40
- /** Unique ID for this request */
41
- id: string;
42
- /** Request initialization options */
43
- init: Pick<
44
- RequestInit,
45
- | "method"
46
- | "keepalive"
47
- | "headers"
48
- | "body"
49
- | "redirect"
50
- | "integrity"
51
- | "credentials"
52
- | "mode"
53
- | "referrer"
54
- | "referrerPolicy"
55
- | "window"
56
- >;
57
- }
58
- | {
59
- /** Indicates this message is a command to clear chat history */
60
- type: "cf_agent_chat_clear";
61
- }
62
- | {
63
- /** Indicates this message contains updated chat messages */
64
- type: "cf_agent_chat_messages";
65
- /** Array of chat messages */
66
- messages: Message[];
67
- }
68
- | {
69
- /** Indicates the user wants to stop generation of this message */
70
- type: "cf_agent_chat_request_cancel";
71
- id: string;
72
- };
73
-
74
- export type { IncomingMessage, OutgoingMessage };
1
+ import {
2
+ n as MessageType,
3
+ r as OutgoingMessage,
4
+ t as IncomingMessage
5
+ } from "./ai-types-U8lYA0o8.js";
6
+ export { IncomingMessage, MessageType, OutgoingMessage };
package/dist/ai-types.js CHANGED
@@ -1 +1,3 @@
1
- //# sourceMappingURL=ai-types.js.map
1
+ import { t as MessageType } from "./ai-types-DEtF_8Km.js";
2
+
3
+ export { MessageType };
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ import yargs from "yargs";
3
+ import { hideBin } from "yargs/helpers";
4
+
5
+ //#region src/cli/create.ts
6
+ function createCli(argv = process.argv) {
7
+ return yargs(hideBin(argv)).scriptName("agents").usage("$0 <command> [options]").command(["init", "create"], "Initialize an agents project", (cmd) => cmd, async () => {
8
+ console.log("agents init: not implemented yet");
9
+ process.exit(0);
10
+ }).command("dev", "Start development server", (cmd) => cmd, async () => {
11
+ console.log("agents dev: not implemented yet");
12
+ process.exit(0);
13
+ }).command("deploy", "Deploy agents to Cloudflare", (cmd) => cmd, async () => {
14
+ console.log("agents deploy: not implemented yet");
15
+ process.exit(0);
16
+ }).command("mcp", "The agents mcp server", (cmd) => cmd, async () => {
17
+ console.log("agents mcp: not implemented yet");
18
+ process.exit(0);
19
+ }).demandCommand(1, "Please provide a command").strict().help();
20
+ }
21
+
22
+ //#endregion
23
+ //#region src/cli/index.ts
24
+ createCli().parse();
25
+
26
+ //#endregion
27
+ export { };
28
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/cli/create.ts","../../src/cli/index.ts"],"sourcesContent":["import yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\n\nexport function createCli(argv = process.argv) {\n return yargs(hideBin(argv))\n .scriptName(\"agents\")\n .usage(\"$0 <command> [options]\")\n .command(\n [\"init\", \"create\"],\n \"Initialize an agents project\",\n (cmd) => cmd,\n async () => {\n console.log(\"agents init: not implemented yet\");\n process.exit(0);\n }\n )\n .command(\n \"dev\",\n \"Start development server\",\n (cmd) => cmd,\n async () => {\n console.log(\"agents dev: not implemented yet\");\n process.exit(0);\n }\n )\n .command(\n \"deploy\",\n \"Deploy agents to Cloudflare\",\n (cmd) => cmd,\n async () => {\n console.log(\"agents deploy: not implemented yet\");\n process.exit(0);\n }\n )\n .command(\n \"mcp\",\n \"The agents mcp server\",\n (cmd) => cmd,\n async () => {\n console.log(\"agents mcp: not implemented yet\");\n process.exit(0);\n }\n )\n .demandCommand(1, \"Please provide a command\")\n .strict()\n .help();\n}\n","#!/usr/bin/env node\n\nimport { createCli } from \"./create\";\n\nvoid createCli().parse();\n"],"mappings":";;;;;AAGA,SAAgB,UAAU,OAAO,QAAQ,MAAM;AAC7C,QAAO,MAAM,QAAQ,KAAK,CAAC,CACxB,WAAW,SAAS,CACpB,MAAM,yBAAyB,CAC/B,QACC,CAAC,QAAQ,SAAS,EAClB,iCACC,QAAQ,KACT,YAAY;AACV,UAAQ,IAAI,mCAAmC;AAC/C,UAAQ,KAAK,EAAE;GAElB,CACA,QACC,OACA,6BACC,QAAQ,KACT,YAAY;AACV,UAAQ,IAAI,kCAAkC;AAC9C,UAAQ,KAAK,EAAE;GAElB,CACA,QACC,UACA,gCACC,QAAQ,KACT,YAAY;AACV,UAAQ,IAAI,qCAAqC;AACjD,UAAQ,KAAK,EAAE;GAElB,CACA,QACC,OACA,0BACC,QAAQ,KACT,YAAY;AACV,UAAQ,IAAI,kCAAkC;AAC9C,UAAQ,KAAK,EAAE;GAElB,CACA,cAAc,GAAG,2BAA2B,CAC5C,QAAQ,CACR,MAAM;;;;;ACzCN,WAAW,CAAC,OAAO"}