10xgraph-client 0.0.0-stage → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +276 -0
- package/LICENSE +21 -0
- package/README.md +400 -2
- package/dist/agent.d.ts +22 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/client.d.ts +479 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/compat.d.ts +28 -0
- package/dist/compat.d.ts.map +1 -0
- package/dist/endpoints/addThreadMessages.d.ts +22 -0
- package/dist/endpoints/addThreadMessages.d.ts.map +1 -0
- package/dist/endpoints/clearThreadState.d.ts +15 -0
- package/dist/endpoints/clearThreadState.d.ts.map +1 -0
- package/dist/endpoints/deleteMemory.d.ts +19 -0
- package/dist/endpoints/deleteMemory.d.ts.map +1 -0
- package/dist/endpoints/deleteThread.d.ts +19 -0
- package/dist/endpoints/deleteThread.d.ts.map +1 -0
- package/dist/endpoints/deleteThreadMessage.d.ts +20 -0
- package/dist/endpoints/deleteThreadMessage.d.ts.map +1 -0
- package/dist/endpoints/files.d.ts +83 -0
- package/dist/endpoints/files.d.ts.map +1 -0
- package/dist/endpoints/fixGraph.d.ts +29 -0
- package/dist/endpoints/fixGraph.d.ts.map +1 -0
- package/dist/endpoints/forgetMemories.d.ts +22 -0
- package/dist/endpoints/forgetMemories.d.ts.map +1 -0
- package/dist/endpoints/getMemory.d.ts +19 -0
- package/dist/endpoints/getMemory.d.ts.map +1 -0
- package/dist/endpoints/graph.d.ts +39 -0
- package/dist/endpoints/graph.d.ts.map +1 -0
- package/dist/endpoints/graphTools.d.ts +32 -0
- package/dist/endpoints/graphTools.d.ts.map +1 -0
- package/dist/endpoints/invoke.d.ts +59 -0
- package/dist/endpoints/invoke.d.ts.map +1 -0
- package/dist/endpoints/listMemories.d.ts +19 -0
- package/dist/endpoints/listMemories.d.ts.map +1 -0
- package/dist/endpoints/metadata.d.ts +6 -0
- package/dist/endpoints/metadata.d.ts.map +1 -0
- package/dist/endpoints/observability.d.ts +58 -0
- package/dist/endpoints/observability.d.ts.map +1 -0
- package/dist/endpoints/ping.d.ts +10 -0
- package/dist/endpoints/ping.d.ts.map +1 -0
- package/dist/endpoints/realtime.d.ts +134 -0
- package/dist/endpoints/realtime.d.ts.map +1 -0
- package/dist/endpoints/searchMemory.d.ts +57 -0
- package/dist/endpoints/searchMemory.d.ts.map +1 -0
- package/dist/endpoints/stateSchema.d.ts +50 -0
- package/dist/endpoints/stateSchema.d.ts.map +1 -0
- package/dist/endpoints/stopGraph.d.ts +26 -0
- package/dist/endpoints/stopGraph.d.ts.map +1 -0
- package/dist/endpoints/storeMemory.d.ts +33 -0
- package/dist/endpoints/storeMemory.d.ts.map +1 -0
- package/dist/endpoints/stream.d.ts +60 -0
- package/dist/endpoints/stream.d.ts.map +1 -0
- package/dist/endpoints/threadDetails.d.ts +19 -0
- package/dist/endpoints/threadDetails.d.ts.map +1 -0
- package/dist/endpoints/threadMessage.d.ts +17 -0
- package/dist/endpoints/threadMessage.d.ts.map +1 -0
- package/dist/endpoints/threadMessages.d.ts +23 -0
- package/dist/endpoints/threadMessages.d.ts.map +1 -0
- package/dist/endpoints/threadState.d.ts +14 -0
- package/dist/endpoints/threadState.d.ts.map +1 -0
- package/dist/endpoints/threads.d.ts +30 -0
- package/dist/endpoints/threads.d.ts.map +1 -0
- package/dist/endpoints/updateMemory.d.ts +21 -0
- package/dist/endpoints/updateMemory.d.ts.map +1 -0
- package/dist/endpoints/updateThreadState.d.ts +18 -0
- package/dist/endpoints/updateThreadState.d.ts.map +1 -0
- package/dist/endpoints/wsStream.d.ts +33 -0
- package/dist/endpoints/wsStream.d.ts.map +1 -0
- package/dist/errors.d.ts +155 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/index.cjs +6 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +39 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2664 -0
- package/dist/index.js.map +1 -0
- package/dist/message.d.ts +174 -0
- package/dist/message.d.ts.map +1 -0
- package/dist/request.d.ts +33 -0
- package/dist/request.d.ts.map +1 -0
- package/dist/tools.d.ts +67 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/ws.d.ts +48 -0
- package/dist/ws.d.ts.map +1 -0
- package/package.json +99 -4
- package/src/agent.ts +43 -0
- package/src/client.ts +1044 -0
- package/src/compat.ts +35 -0
- package/src/endpoints/addThreadMessages.ts +83 -0
- package/src/endpoints/clearThreadState.ts +75 -0
- package/src/endpoints/deleteMemory.ts +91 -0
- package/src/endpoints/deleteThread.ts +78 -0
- package/src/endpoints/deleteThreadMessage.ts +83 -0
- package/src/endpoints/files.ts +274 -0
- package/src/endpoints/fixGraph.ts +91 -0
- package/src/endpoints/forgetMemories.ts +95 -0
- package/src/endpoints/getMemory.ts +82 -0
- package/src/endpoints/graph.ts +97 -0
- package/src/endpoints/graphTools.ts +90 -0
- package/src/endpoints/invoke.ts +318 -0
- package/src/endpoints/listMemories.ts +97 -0
- package/src/endpoints/metadata.ts +6 -0
- package/src/endpoints/observability.ts +107 -0
- package/src/endpoints/ping.ts +58 -0
- package/src/endpoints/realtime.ts +326 -0
- package/src/endpoints/searchMemory.ts +132 -0
- package/src/endpoints/stateSchema.ts +106 -0
- package/src/endpoints/stopGraph.ts +85 -0
- package/src/endpoints/storeMemory.ts +98 -0
- package/src/endpoints/stream.ts +440 -0
- package/src/endpoints/threadDetails.ts +78 -0
- package/src/endpoints/threadMessage.ts +76 -0
- package/src/endpoints/threadMessages.ts +97 -0
- package/src/endpoints/threadState.ts +74 -0
- package/src/endpoints/threads.ts +112 -0
- package/src/endpoints/updateMemory.ts +90 -0
- package/src/endpoints/updateThreadState.ts +82 -0
- package/src/endpoints/wsStream.ts +251 -0
- package/src/errors.ts +553 -0
- package/src/index.ts +108 -0
- package/src/message.ts +436 -0
- package/src/request.ts +168 -0
- package/src/tools.ts +225 -0
- package/src/ws.ts +100 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../src/message.ts","../src/tools.ts","../src/errors.ts","../src/request.ts","../src/endpoints/ping.ts","../src/endpoints/graph.ts","../src/endpoints/graphTools.ts","../src/endpoints/observability.ts","../src/endpoints/stateSchema.ts","../src/endpoints/threadState.ts","../src/endpoints/updateThreadState.ts","../src/endpoints/clearThreadState.ts","../src/endpoints/threadMessages.ts","../src/endpoints/addThreadMessages.ts","../src/endpoints/threadMessage.ts","../src/endpoints/threadDetails.ts","../src/endpoints/deleteThreadMessage.ts","../src/endpoints/deleteThread.ts","../src/endpoints/threads.ts","../src/endpoints/invoke.ts","../src/endpoints/stream.ts","../src/ws.ts","../src/endpoints/wsStream.ts","../src/endpoints/realtime.ts","../src/endpoints/storeMemory.ts","../src/endpoints/searchMemory.ts","../src/endpoints/getMemory.ts","../src/endpoints/updateMemory.ts","../src/endpoints/deleteMemory.ts","../src/endpoints/listMemories.ts","../src/endpoints/forgetMemories.ts","../src/endpoints/stopGraph.ts","../src/endpoints/fixGraph.ts","../src/endpoints/files.ts","../src/client.ts","../src/agent.ts","../src/compat.ts"],"sourcesContent":["// Removed incorrect import of Literal and Union from 'typescript'\n\n// Define MediaRef type\nexport class MediaRef {\n kind: 'url' | 'file_id' | 'data' = 'url';\n url?: string;\n file_id?: string;\n data_base64?: string;\n mime_type?: string;\n size_bytes?: number;\n sha256?: string;\n filename?: string;\n width?: number;\n height?: number;\n duration_ms?: number;\n page?: number;\n\n constructor(\n kind: 'url' | 'file_id' | 'data' = 'url',\n url?: string,\n file_id?: string,\n data_base64?: string,\n mime_type?: string,\n size_bytes?: number,\n sha256?: string,\n filename?: string,\n width?: number,\n height?: number,\n duration_ms?: number,\n page?: number\n ) {\n this.kind = kind;\n this.url = url;\n this.file_id = file_id;\n this.data_base64 = data_base64;\n this.mime_type = mime_type;\n this.size_bytes = size_bytes;\n this.sha256 = sha256;\n this.filename = filename;\n this.width = width;\n this.height = height;\n this.duration_ms = duration_ms;\n this.page = page;\n }\n}\n\n// Define AnnotationRef type\nexport class AnnotationRef {\n url?: string;\n file_id?: string;\n page?: number;\n index?: number;\n title?: string;\n\n constructor(url?: string, file_id?: string, page?: number, index?: number, title?: string) {\n this.url = url;\n this.file_id = file_id;\n this.page = page;\n this.index = index;\n this.title = title;\n }\n}\n\n// Define TextBlock type\nexport class TextBlock {\n type: 'text' = 'text';\n text: string = '';\n annotations: AnnotationRef[] = [];\n\n constructor(text: string = '', annotations: AnnotationRef[] = []) {\n this.text = text;\n this.annotations = annotations;\n }\n}\n\n// Define ImageBlock type\nexport class ImageBlock {\n type: 'image' = 'image';\n media: MediaRef = new MediaRef();\n alt_text?: string;\n bbox?: number[];\n\n constructor(media: MediaRef = new MediaRef(), alt_text?: string, bbox?: number[]) {\n this.media = media;\n this.alt_text = alt_text;\n this.bbox = bbox;\n }\n}\n\n// Define AudioBlock type\nexport class AudioBlock {\n type: 'audio' = 'audio';\n media: MediaRef = new MediaRef();\n transcript?: string;\n sample_rate?: number;\n channels?: number;\n\n constructor(\n media: MediaRef = new MediaRef(),\n transcript?: string,\n sample_rate?: number,\n channels?: number\n ) {\n this.media = media;\n this.transcript = transcript;\n this.sample_rate = sample_rate;\n this.channels = channels;\n }\n}\n\n// Define VideoBlock type\nexport class VideoBlock {\n type: 'video' = 'video';\n media: MediaRef = new MediaRef();\n thumbnail?: MediaRef;\n\n constructor(media: MediaRef = new MediaRef(), thumbnail?: MediaRef) {\n this.media = media;\n this.thumbnail = thumbnail;\n }\n}\n\n// Define DocumentBlock type\nexport class DocumentBlock {\n type: 'document' = 'document';\n media: MediaRef = new MediaRef();\n pages?: number[];\n excerpt?: string;\n\n constructor(media: MediaRef = new MediaRef(), pages?: number[], excerpt?: string) {\n this.media = media;\n this.pages = pages;\n this.excerpt = excerpt;\n }\n}\n\n// Define DataBlock type\nexport class DataBlock {\n type: 'data' = 'data';\n mime_type: string = '';\n data_base64?: string;\n media?: MediaRef;\n\n constructor(mime_type: string = '', data_base64?: string, media?: MediaRef) {\n this.mime_type = mime_type;\n this.data_base64 = data_base64;\n this.media = media;\n }\n}\n\n// Define ToolCallBlock type\nexport class ToolCallBlock {\n type: 'tool_call' = 'tool_call';\n id: string = '';\n name: string = '';\n args: Record<string, any> = {};\n tool_type?: string;\n\n constructor(\n id: string = '',\n name: string = '',\n args: Record<string, any> = {},\n tool_type?: string\n ) {\n this.id = id;\n this.name = name;\n this.args = args;\n this.tool_type = tool_type;\n }\n}\n\n// Define RemoteToolCallBlock type\nexport class RemoteToolCallBlock {\n type: 'remote_tool_call' = 'remote_tool_call';\n id: string = '';\n name: string = '';\n args: Record<string, any> = {};\n tool_type: string = 'remote';\n\n constructor(\n id: string = '',\n name: string = '',\n args: Record<string, any> = {},\n tool_type: string = 'remote'\n ) {\n this.id = id;\n this.name = name;\n this.args = args;\n this.tool_type = tool_type;\n }\n}\n\n// Define ToolResultBlock type\nexport class ToolResultBlock {\n type: 'tool_result' = 'tool_result';\n call_id: string = '';\n output: any;\n is_error: boolean = false;\n status?: 'completed' | 'failed';\n\n constructor(props: {\n call_id: string;\n output: any;\n status: 'completed' | 'failed';\n is_error: boolean;\n }) {\n this.call_id = props.call_id;\n this.output = props.output;\n this.status = props.status;\n this.is_error = props.is_error;\n }\n}\n\n// Define ReasoningBlock type\nexport class ReasoningBlock {\n type: 'reasoning' = 'reasoning';\n summary: string = '';\n details?: string[];\n\n constructor(summary: string = '', details?: string[]) {\n this.summary = summary;\n this.details = details;\n }\n}\n\n// Define AnnotationBlock type\nexport class AnnotationBlock {\n type: 'annotation' = 'annotation';\n kind: 'citation' | 'note' = 'citation';\n refs: AnnotationRef[] = [];\n spans?: [number, number][];\n\n constructor(\n kind: 'citation' | 'note' = 'citation',\n refs: AnnotationRef[] = [],\n spans?: [number, number][]\n ) {\n this.kind = kind;\n this.refs = refs;\n this.spans = spans;\n }\n}\n\n// Define ErrorBlock type\nexport class ErrorBlock {\n type: 'error' = 'error';\n message: string = '';\n code?: string;\n data?: Record<string, any>;\n\n constructor(message: string = '', code?: string, data?: Record<string, any>) {\n this.message = message;\n this.code = code;\n this.data = data;\n }\n}\n\n// Define ContentBlock union type\nexport type ContentBlock =\n | TextBlock\n | ImageBlock\n | AudioBlock\n | VideoBlock\n | DocumentBlock\n | DataBlock\n | ToolCallBlock\n | RemoteToolCallBlock\n | ToolResultBlock\n | ReasoningBlock\n | AnnotationBlock\n | ErrorBlock;\n\n// Define TokenUsages type\nexport class TokenUsages {\n completion_tokens: number = 0;\n prompt_tokens: number = 0;\n total_tokens: number = 0;\n reasoning_tokens: number = 0;\n cache_creation_input_tokens: number = 0;\n cache_read_input_tokens: number = 0;\n image_tokens?: number = 0;\n audio_tokens?: number = 0;\n}\n\n// Define Message class\nexport class Message {\n message_id: string | null = null;\n role: 'user' | 'assistant' | 'system' | 'tool';\n content: ContentBlock[] = [];\n delta: boolean = false;\n tools_calls?: Record<string, any>[];\n timestamp: number = Date.now();\n metadata: Record<string, any> = {};\n usages?: TokenUsages;\n raw?: Record<string, any>;\n\n constructor(\n role: 'user' | 'assistant' | 'system' | 'tool',\n content: ContentBlock[],\n message_id: string | null = null\n ) {\n this.role = role;\n this.content = content;\n this.message_id = message_id;\n }\n\n static text_message(\n content: string,\n role: 'user' | 'assistant' | 'system' | 'tool' = 'user',\n message_id: string | null = null\n ): Message {\n return new Message(role, [{ type: 'text', text: content } as TextBlock], message_id);\n }\n\n static tool_message(\n content: ContentBlock[],\n message_id: string | null = null,\n meta: Record<string, any> = {}\n ): Message {\n const message = new Message('tool', content, message_id);\n message.metadata = meta;\n return message;\n }\n\n text(): string {\n return this.content\n .map((block) => {\n if (block.type === 'text') {\n return (block as TextBlock).text;\n } else if (block.type === 'tool_result') {\n const output = (block as ToolResultBlock).output;\n return typeof output === 'string' ? output : JSON.stringify(output);\n }\n return '';\n })\n .join('');\n }\n\n attach_media(media: MediaRef, as_type: 'image' | 'audio' | 'video' | 'document'): void {\n let block: ContentBlock;\n switch (as_type) {\n case 'image':\n block = { type: 'image', media } as ImageBlock;\n break;\n case 'audio':\n block = { type: 'audio', media } as AudioBlock;\n break;\n case 'video':\n block = { type: 'video', media } as VideoBlock;\n break;\n case 'document':\n block = { type: 'document', media } as DocumentBlock;\n break;\n default:\n throw new Error(`Unsupported media type: ${as_type}`);\n }\n this.content.push(block);\n }\n\n // ------------------------------------------------------------------\n // Multimodal convenience constructors (Sprint 5.3)\n // ------------------------------------------------------------------\n\n /**\n * Create a message with an image (via URL or base64).\n *\n * @example\n * ```ts\n * const msg = Message.withImage('Describe this', 'https://example.com/photo.jpg');\n * const msg2 = Message.withImage('Describe this', 'data:image/png;base64,...');\n * ```\n */\n static withImage(\n text: string,\n imageUrl: string,\n role: 'user' | 'assistant' | 'system' = 'user'\n ): Message {\n return new Message(role, [\n new TextBlock(text),\n new ImageBlock(new MediaRef('url', imageUrl, undefined, undefined, undefined)),\n ]);\n }\n\n /**\n * Create a message with a file reference (e.g. from uploadFile result).\n *\n * @example\n * ```ts\n * const upload = await client.uploadFile(pdfFile);\n * const msg = Message.withFile('Summarize this PDF', upload.data.file_id, 'application/pdf');\n * ```\n */\n static withFile(\n text: string,\n fileId: string,\n mimeType?: string,\n role: 'user' | 'assistant' | 'system' = 'user'\n ): Message {\n const media = new MediaRef('file_id', undefined, fileId, undefined, mimeType);\n const isImage = mimeType?.startsWith('image/');\n const isAudio = mimeType?.startsWith('audio/');\n const isVideo = mimeType?.startsWith('video/');\n\n let block: ContentBlock;\n if (isImage) {\n block = new ImageBlock(media);\n } else if (isAudio) {\n block = new AudioBlock(media);\n } else if (isVideo) {\n block = new VideoBlock(media);\n } else {\n block = new DocumentBlock(media);\n }\n\n return new Message(role, [new TextBlock(text), block]);\n }\n\n /**\n * Create a multimodal message with arbitrary content blocks.\n *\n * @example\n * ```ts\n * const msg = Message.multimodal([\n * new TextBlock('Look at these'),\n * new ImageBlock(new MediaRef('url', 'https://...')),\n * new ImageBlock(new MediaRef('url', 'https://...')),\n * ]);\n * ```\n */\n static multimodal(\n blocks: ContentBlock[],\n role: 'user' | 'assistant' | 'system' = 'user'\n ): Message {\n return new Message(role, blocks);\n }\n}\n","import { Message, RemoteToolCallBlock, ToolResultBlock } from './message.js';\n\n// TOOL HANDLER\nexport interface ToolHandler {\n (args: any): Promise<any>;\n}\n\n/**\n * JSON Schema describing a tool's arguments.\n *\n * `properties` and `required` are optional, matching JSON Schema itself: a tool\n * whose arguments are all optional needs neither, and a tool that takes no\n * arguments can be declared as `{ type: 'object' }`. Additional JSON Schema\n * keywords (`additionalProperties`, `$defs`, ...) are passed through untouched.\n */\nexport interface ToolParameter {\n type: string;\n properties?: Record<string, any>;\n required?: string[];\n [key: string]: unknown;\n}\n\n/**\n * Fill in the JSON Schema defaults a tool declaration may leave out, so the\n * wire format sent to the server is always a complete object schema.\n */\nexport function normalizeToolParameters(parameters?: ToolParameter): ToolParameter {\n const source: Partial<ToolParameter> = parameters ?? {};\n const { type, properties, required, ...rest } = source;\n\n return {\n ...rest,\n type: type ?? 'object',\n properties: properties ?? {},\n required: required ?? [],\n };\n}\n\nexport interface Tool {\n type: string;\n function: {\n name: string;\n description: string;\n parameters: ToolParameter;\n };\n}\n\n// Tool Registration - what users provide when registering tools\nexport interface ToolRegistration {\n node?: string;\n name: string;\n description?: string;\n parameters?: ToolParameter;\n handler: ToolHandler;\n}\n\n// Internal tool definition (extends handler)\nexport interface ToolDefinition extends ToolHandler {\n name: string;\n description?: string;\n parameters?: ToolParameter;\n node?: string;\n}\n\nexport class ToolExecutor {\n private tools: Map<string, ToolDefinition>;\n private toolsByNode: Map<string, Map<string, ToolDefinition>>;\n\n constructor(tools: ToolDefinition[] = []) {\n this.tools = new Map<string, ToolDefinition>();\n this.toolsByNode = new Map<string, Map<string, ToolDefinition>>();\n\n for (const func of tools) {\n this.tools.set(func.name, func);\n\n // Also organize by node if specified\n if (func.node) {\n if (!this.toolsByNode.has(func.node)) {\n this.toolsByNode.set(func.node, new Map());\n }\n this.toolsByNode.get(func.node)!.set(func.name, func);\n }\n }\n }\n\n /**\n * Register a new tool\n */\n registerTool(registration: ToolRegistration): void {\n // Create a proper ToolDefinition by wrapping the handler\n const toolDef: ToolDefinition = async (args: any) => {\n return registration.handler(args);\n };\n\n // Use Object.defineProperty to add properties to the function\n Object.defineProperty(toolDef, 'name', {\n value: registration.name,\n writable: true,\n configurable: true,\n });\n Object.defineProperty(toolDef, 'description', {\n value: registration.description,\n writable: true,\n configurable: true,\n });\n Object.defineProperty(toolDef, 'parameters', {\n value: registration.parameters,\n writable: true,\n configurable: true,\n });\n Object.defineProperty(toolDef, 'node', {\n value: registration.node,\n writable: true,\n configurable: true,\n });\n\n this.tools.set(registration.name, toolDef);\n\n // Organize by node\n if (registration.node) {\n if (!this.toolsByNode.has(registration.node)) {\n this.toolsByNode.set(registration.node, new Map());\n }\n this.toolsByNode.get(registration.node)!.set(registration.name, toolDef);\n }\n }\n\n /**\n * Get tools for a specific node\n */\n getToolsForNode(node: string): ToolDefinition[] {\n const nodeTools = this.toolsByNode.get(node);\n return nodeTools ? Array.from(nodeTools.values()) : [];\n }\n\n /**\n * Get all tools in OpenAI-compatible format\n */\n all_tools(): Tool[] {\n const openaiTools: Tool[] = [];\n\n for (const [name, func] of this.tools) {\n const tool: Tool = {\n type: 'function',\n function: {\n name: name,\n description: func.description || `Execute ${name}`,\n parameters: normalizeToolParameters(func.parameters),\n },\n };\n openaiTools.push(tool);\n }\n\n return openaiTools;\n }\n\n /**\n * Extract and execute all tool calls from the response\n * Returns an array of tool result messages\n */\n async executeToolCalls(messages: Message[]): Promise<Message[]> {\n const toolCalls: RemoteToolCallBlock[] = [];\n\n // Extract all remote_tool_call blocks from messages\n for (const msg of messages) {\n if (msg.content) {\n for (const block of msg.content) {\n if (block.type === 'remote_tool_call') {\n toolCalls.push(block as RemoteToolCallBlock);\n }\n }\n }\n }\n\n const results: Message[] = [];\n\n // Execute each tool call\n for (const call of toolCalls) {\n const toolName = call.name;\n\n if (this.tools.has(toolName)) {\n const tool = this.tools.get(toolName)!;\n\n try {\n // Execute the tool\n const result = await tool(call.args);\n\n // Create a tool result message\n const toolResultBlock = new ToolResultBlock({\n call_id: call.id,\n output: result,\n status: 'completed',\n is_error: false,\n });\n\n results.push(Message.tool_message([toolResultBlock]));\n } catch (error) {\n // Handle errors\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n const toolResultBlock = new ToolResultBlock({\n call_id: call.id,\n output: { error: errorMessage },\n status: 'failed',\n is_error: true,\n });\n\n results.push(Message.tool_message([toolResultBlock]));\n }\n } else {\n // Tool not found error\n const toolResultBlock = new ToolResultBlock({\n call_id: call.id,\n output: { error: `Tool '${toolName}' not found` },\n status: 'failed',\n is_error: true,\n });\n\n results.push(Message.tool_message([toolResultBlock]));\n }\n }\n\n return results;\n }\n}\n","/**\n * Error handling for 10xGraph API\n * Provides structured error types for all HTTP status codes\n */\n\n// Error response structure from API\nexport interface ErrorDetail {\n loc?: string[];\n msg?: string;\n type?: string;\n}\n\nexport interface ApiErrorResponse {\n metadata: {\n message: string;\n request_id: string;\n timestamp: string;\n };\n error: {\n code: string;\n message: string;\n details: ErrorDetail[];\n };\n}\n\n/**\n * Base error class for all 10xGraph API errors\n */\nexport class TenxGraphError extends Error {\n public readonly statusCode: number;\n public readonly errorCode: string;\n public readonly requestId: string;\n public readonly timestamp: string;\n public readonly details: ErrorDetail[];\n public readonly context?: Record<string, any>;\n public readonly endpoint?: string;\n public readonly method?: string;\n public readonly recoverySuggestion?: string;\n\n constructor(\n message: string,\n statusCode: number,\n errorCode: string,\n requestId: string,\n timestamp: string,\n details: ErrorDetail[] = [],\n context?: Record<string, any>,\n endpoint?: string,\n method?: string,\n recoverySuggestion?: string\n ) {\n super(message);\n this.name = 'TenxGraphError';\n this.statusCode = statusCode;\n this.errorCode = errorCode;\n this.requestId = requestId;\n this.timestamp = timestamp;\n this.details = details;\n this.context = context;\n this.endpoint = endpoint;\n this.method = method;\n this.recoverySuggestion = recoverySuggestion;\n\n // Maintains proper stack trace for where our error was thrown (only available on V8).\n // Typed structurally so the build does not depend on @types/node.\n const captureStackTrace = (\n Error as ErrorConstructor & {\n captureStackTrace?: (target: object, ctor?: unknown) => void;\n }\n ).captureStackTrace;\n if (captureStackTrace) {\n captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Get a user-friendly error message with recovery suggestion\n */\n getUserMessage(): string {\n if (this.recoverySuggestion) {\n return `${this.message}\\n\\nSuggestion: ${this.recoverySuggestion}`;\n }\n return this.message;\n }\n\n /**\n * Get full error details for debugging\n */\n toJSON(): Record<string, any> {\n return {\n name: this.name,\n message: this.message,\n statusCode: this.statusCode,\n errorCode: this.errorCode,\n requestId: this.requestId,\n timestamp: this.timestamp,\n details: this.details,\n context: this.context,\n endpoint: this.endpoint,\n method: this.method,\n recoverySuggestion: this.recoverySuggestion,\n stack: this.stack,\n };\n }\n}\n\n/**\n * 400 Bad Request Error\n * Thrown when the request is malformed or contains invalid data\n */\nexport class BadRequestError extends TenxGraphError {\n constructor(message: string, requestId: string, timestamp: string, details: ErrorDetail[] = []) {\n super(message, 400, 'BAD_REQUEST', requestId, timestamp, details);\n this.name = 'BadRequestError';\n }\n}\n\n/**\n * 401 Unauthorized Error\n * Thrown when authentication credentials are missing or invalid\n */\nexport class AuthenticationError extends TenxGraphError {\n constructor(message: string, requestId: string, timestamp: string, details: ErrorDetail[] = []) {\n super(message, 401, 'AUTHENTICATION_FAILED', requestId, timestamp, details);\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * 403 Forbidden Error\n * Thrown when the user doesn't have permission to access the resource\n */\nexport class PermissionError extends TenxGraphError {\n constructor(message: string, requestId: string, timestamp: string, details: ErrorDetail[] = []) {\n super(message, 403, 'PERMISSION_ERROR', requestId, timestamp, details);\n this.name = 'PermissionError';\n }\n}\n\n/**\n * 404 Not Found Error\n * Thrown when the requested resource doesn't exist\n */\nexport class NotFoundError extends TenxGraphError {\n constructor(message: string, requestId: string, timestamp: string, details: ErrorDetail[] = []) {\n super(message, 404, 'RESOURCE_NOT_FOUND', requestId, timestamp, details);\n this.name = 'NotFoundError';\n }\n}\n\n/**\n * 422 Validation Error\n * Thrown when the request data fails validation\n */\nexport class ValidationError extends TenxGraphError {\n constructor(message: string, requestId: string, timestamp: string, details: ErrorDetail[] = []) {\n super(message, 422, 'VALIDATION_ERROR', requestId, timestamp, details);\n this.name = 'ValidationError';\n }\n}\n\n/**\n * 500 Server Error\n * Thrown when the server encounters an internal error\n */\nexport class ServerError extends TenxGraphError {\n constructor(\n message: string,\n requestId: string,\n timestamp: string,\n errorCode: string = 'INTERNAL_SERVER_ERROR',\n details: ErrorDetail[] = [],\n statusCode: number = 500\n ) {\n super(message, statusCode, errorCode, requestId, timestamp, details);\n this.name = 'ServerError';\n }\n}\n\n/**\n * Graph Error\n * Thrown when there's an error in graph execution\n */\nexport class GraphError extends TenxGraphError {\n constructor(\n message: string,\n requestId: string,\n timestamp: string,\n details: ErrorDetail[] = [],\n context?: Record<string, any>\n ) {\n super(\n message,\n 500,\n 'GRAPH_ERROR',\n requestId,\n timestamp,\n details,\n context,\n undefined,\n undefined,\n 'Check your graph configuration and ensure all nodes are properly connected.'\n );\n this.name = 'GraphError';\n }\n}\n\n/**\n * Node Error\n * Thrown when there's an error executing a specific node\n */\nexport class NodeError extends TenxGraphError {\n public readonly nodeName?: string;\n\n constructor(\n message: string,\n requestId: string,\n timestamp: string,\n details: ErrorDetail[] = [],\n context?: Record<string, any>,\n nodeName?: string\n ) {\n super(\n message,\n 500,\n 'NODE_ERROR',\n requestId,\n timestamp,\n details,\n context,\n undefined,\n undefined,\n 'Review the node implementation and ensure all required inputs are provided.'\n );\n this.name = 'NodeError';\n this.nodeName = nodeName;\n }\n}\n\n/**\n * Graph Recursion Error\n * Thrown when graph execution exceeds the recursion limit\n */\nexport class GraphRecursionError extends TenxGraphError {\n public readonly recursionLimit?: number;\n\n constructor(\n message: string,\n requestId: string,\n timestamp: string,\n details: ErrorDetail[] = [],\n context?: Record<string, any>,\n recursionLimit?: number\n ) {\n super(\n message,\n 500,\n 'GRAPH_RECURSION_ERROR',\n requestId,\n timestamp,\n details,\n context,\n undefined,\n undefined,\n 'Consider increasing the recursion_limit parameter or check for infinite loops in your graph.'\n );\n this.name = 'GraphRecursionError';\n this.recursionLimit = recursionLimit;\n }\n}\n\n/**\n * Storage Error\n * Thrown when there's an error accessing storage\n */\nexport class StorageError extends TenxGraphError {\n constructor(\n message: string,\n requestId: string,\n timestamp: string,\n details: ErrorDetail[] = [],\n context?: Record<string, any>\n ) {\n super(\n message,\n 500,\n 'STORAGE_ERROR',\n requestId,\n timestamp,\n details,\n context,\n undefined,\n undefined,\n 'Check your storage configuration and ensure the storage backend is accessible.'\n );\n this.name = 'StorageError';\n }\n}\n\n/**\n * Transient Storage Error\n * Thrown when there's a temporary storage issue (503 Service Unavailable)\n */\nexport class TransientStorageError extends TenxGraphError {\n constructor(\n message: string,\n requestId: string,\n timestamp: string,\n details: ErrorDetail[] = [],\n context?: Record<string, any>\n ) {\n super(\n message,\n 503,\n 'TRANSIENT_STORAGE_ERROR',\n requestId,\n timestamp,\n details,\n context,\n undefined,\n undefined,\n 'This is a temporary issue. Please retry your request after a short delay.'\n );\n this.name = 'TransientStorageError';\n }\n}\n\n/**\n * Metrics Error\n * Thrown when there's an error collecting or reporting metrics\n */\nexport class MetricsError extends TenxGraphError {\n constructor(\n message: string,\n requestId: string,\n timestamp: string,\n details: ErrorDetail[] = [],\n context?: Record<string, any>\n ) {\n super(\n message,\n 500,\n 'METRICS_ERROR',\n requestId,\n timestamp,\n details,\n context,\n undefined,\n undefined,\n \"Check your metrics configuration. This error typically doesn't affect core functionality.\"\n );\n this.name = 'MetricsError';\n }\n}\n\n/**\n * Schema Version Error\n * Thrown when there's a version mismatch in data schemas\n */\nexport class SchemaVersionError extends TenxGraphError {\n public readonly expectedVersion?: string;\n public readonly actualVersion?: string;\n\n constructor(\n message: string,\n requestId: string,\n timestamp: string,\n details: ErrorDetail[] = [],\n context?: Record<string, any>,\n expectedVersion?: string,\n actualVersion?: string\n ) {\n super(\n message,\n 422,\n 'SCHEMA_VERSION_ERROR',\n requestId,\n timestamp,\n details,\n context,\n undefined,\n undefined,\n 'Update your client to match the server schema version or contact support.'\n );\n this.name = 'SchemaVersionError';\n this.expectedVersion = expectedVersion;\n this.actualVersion = actualVersion;\n }\n}\n\n/**\n * Serialization Error\n * Thrown when there's an error serializing or deserializing data\n */\nexport class SerializationError extends TenxGraphError {\n constructor(\n message: string,\n requestId: string,\n timestamp: string,\n details: ErrorDetail[] = [],\n context?: Record<string, any>\n ) {\n super(\n message,\n 500,\n 'SERIALIZATION_ERROR',\n requestId,\n timestamp,\n details,\n context,\n undefined,\n undefined,\n 'Ensure your data format is compatible with the API schema.'\n );\n this.name = 'SerializationError';\n }\n}\n\n/**\n * Parse error response from API\n */\nexport async function parseErrorResponse(response: Response): Promise<ApiErrorResponse | null> {\n try {\n const contentType = response.headers.get('content-type');\n if (contentType && contentType.includes('application/json')) {\n return (await response.json()) as ApiErrorResponse;\n }\n return null;\n } catch {\n // If we can't parse the error response, return null\n return null;\n }\n}\n\n/**\n * Create appropriate error instance based on HTTP status code and error code\n */\nexport async function createErrorFromResponse(\n response: Response,\n fallbackMessage?: string,\n endpoint?: string,\n method?: string\n): Promise<TenxGraphError> {\n const errorData = await parseErrorResponse(response);\n\n // If we successfully parsed the error response\n if (errorData) {\n const { metadata, error } = errorData;\n const message = error.message || fallbackMessage || `HTTP error ${response.status}`;\n const requestId = metadata.request_id || 'unknown';\n const timestamp = metadata.timestamp || new Date().toISOString();\n const details = error.details || [];\n const errorCode = error.code || '';\n\n // Try to match specific error types by error code first (takes priority)\n if (errorCode.startsWith('GRAPH_RECURSION')) {\n return new GraphRecursionError(message, requestId, timestamp, details);\n } else if (errorCode.startsWith('GRAPH')) {\n return new GraphError(message, requestId, timestamp, details);\n } else if (errorCode.startsWith('NODE')) {\n return new NodeError(message, requestId, timestamp, details);\n } else if (errorCode.startsWith('TRANSIENT_STORAGE')) {\n return new TransientStorageError(message, requestId, timestamp, details);\n } else if (errorCode.startsWith('STORAGE')) {\n return new StorageError(message, requestId, timestamp, details);\n } else if (errorCode.startsWith('METRICS')) {\n return new MetricsError(message, requestId, timestamp, details);\n } else if (errorCode.startsWith('SCHEMA_VERSION')) {\n return new SchemaVersionError(message, requestId, timestamp, details);\n } else if (errorCode.startsWith('SERIALIZATION')) {\n return new SerializationError(message, requestId, timestamp, details);\n }\n\n // Match by HTTP status code\n switch (response.status) {\n case 400:\n return new BadRequestError(message, requestId, timestamp, details);\n case 401:\n return new AuthenticationError(message, requestId, timestamp, details);\n case 403:\n return new PermissionError(message, requestId, timestamp, details);\n case 404:\n return new NotFoundError(message, requestId, timestamp, details);\n case 422:\n return new ValidationError(message, requestId, timestamp, details);\n case 500:\n case 502:\n case 503:\n case 504:\n return new ServerError(\n message,\n requestId,\n timestamp,\n errorCode || 'INTERNAL_SERVER_ERROR',\n details,\n response.status\n );\n default:\n return new TenxGraphError(\n message,\n response.status,\n errorCode || 'UNKNOWN_ERROR',\n requestId,\n timestamp,\n details,\n undefined,\n endpoint,\n method\n );\n }\n }\n\n // Fallback if we couldn't parse the error response\n const message = fallbackMessage || `HTTP error! status: ${response.status}`;\n const timestamp = new Date().toISOString();\n\n switch (response.status) {\n case 400:\n return new BadRequestError(message, 'unknown', timestamp);\n case 401:\n return new AuthenticationError(message, 'unknown', timestamp);\n case 403:\n return new PermissionError(message, 'unknown', timestamp);\n case 404:\n return new NotFoundError(message, 'unknown', timestamp);\n case 422:\n return new ValidationError(message, 'unknown', timestamp);\n case 500:\n case 502:\n case 503:\n case 504:\n return new ServerError(\n message,\n 'unknown',\n timestamp,\n 'INTERNAL_SERVER_ERROR',\n [],\n response.status\n );\n default:\n return new TenxGraphError(\n message,\n response.status,\n 'UNKNOWN_ERROR',\n 'unknown',\n timestamp,\n [],\n undefined,\n endpoint,\n method\n );\n }\n}\n","import type { WebSocketImpl } from './ws.js';\n\nexport interface TenxGraphBearerAuth {\n type: 'bearer';\n token: string;\n}\n\nexport interface TenxGraphBasicAuth {\n type: 'basic';\n username: string;\n password: string;\n}\n\nexport interface TenxGraphHeaderAuth {\n type: 'header';\n name: string;\n value: string;\n prefix?: string | null;\n}\n\nexport type TenxGraphAuth = TenxGraphBearerAuth | TenxGraphBasicAuth | TenxGraphHeaderAuth;\n\nexport interface RequestContext {\n baseUrl: string;\n authToken?: string | null;\n auth?: TenxGraphAuth | null;\n headers?: HeadersInit;\n credentials?: RequestCredentials;\n timeout: number;\n debug: boolean;\n webSocketImpl?: WebSocketImpl;\n}\n\nfunction setHeader(\n target: Record<string, string>,\n name: string,\n value: string | null | undefined\n): void {\n if (value == null) {\n return;\n }\n\n for (const existingName of Object.keys(target)) {\n if (existingName.toLowerCase() === name.toLowerCase()) {\n delete target[existingName];\n }\n }\n\n target[name] = value;\n}\n\nfunction mergeHeaders(target: Record<string, string>, source?: HeadersInit | null): void {\n if (!source) {\n return;\n }\n\n if (source instanceof Headers) {\n source.forEach((value, name) => {\n setHeader(target, name, value);\n });\n return;\n }\n\n if (Array.isArray(source)) {\n for (const [name, value] of source) {\n setHeader(target, name, value);\n }\n return;\n }\n\n for (const [name, value] of Object.entries(source)) {\n if (value !== undefined) {\n setHeader(target, name, String(value));\n }\n }\n}\n\nfunction hasHeader(target: Record<string, string>, name: string): boolean {\n return Object.keys(target).some(\n (existingName) => existingName.toLowerCase() === name.toLowerCase()\n );\n}\n\nfunction encodeBase64(value: string): string {\n const bufferConstructor = (\n globalThis as {\n Buffer?: { from(input: string, encoding: string): { toString(encoding: string): string } };\n }\n ).Buffer;\n if (bufferConstructor) {\n return bufferConstructor.from(value, 'utf-8').toString('base64');\n }\n\n if (typeof btoa === 'function') {\n const bytes = new TextEncoder().encode(value);\n let binary = '';\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary);\n }\n\n throw new Error('Basic authentication is not supported in this runtime');\n}\n\nfunction applyAuth(target: Record<string, string>, auth?: TenxGraphAuth | null): void {\n if (!auth) {\n return;\n }\n\n if (auth.type === 'bearer') {\n setHeader(target, 'Authorization', `Bearer ${auth.token}`);\n return;\n }\n\n if (auth.type === 'basic') {\n const credentials = encodeBase64(`${auth.username}:${auth.password}`);\n setHeader(target, 'Authorization', `Basic ${credentials}`);\n return;\n }\n\n const headerValue = auth.prefix ? `${auth.prefix} ${auth.value}` : auth.value;\n setHeader(target, auth.name, headerValue);\n}\n\nexport function buildHeaders(\n context: Pick<RequestContext, 'authToken' | 'auth' | 'headers'>,\n defaults?: HeadersInit\n): Record<string, string> {\n const headers: Record<string, string> = {};\n\n mergeHeaders(headers, defaults);\n mergeHeaders(headers, context.headers);\n\n if (context.auth) {\n applyAuth(headers, context.auth);\n } else if (context.authToken && !hasHeader(headers, 'Authorization')) {\n setHeader(headers, 'Authorization', `Bearer ${context.authToken}`);\n }\n\n return headers;\n}\n\nexport function getRequestCredentials(\n context: Pick<RequestContext, 'credentials'>\n): Pick<RequestInit, 'credentials'> | Record<string, never> {\n if (!context.credentials) {\n return {};\n }\n\n return { credentials: context.credentials };\n}\n\nexport function bearerAuth(token: string): TenxGraphBearerAuth {\n return { type: 'bearer', token };\n}\n\nexport function basicAuth(username: string, password: string): TenxGraphBasicAuth {\n return { type: 'basic', username, password };\n}\n\nexport function headerAuth(\n name: string,\n value: string,\n prefix?: string | null\n): TenxGraphHeaderAuth {\n return { type: 'header', name, value, prefix };\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface PingContext extends RequestContext {}\n\nexport interface PingResponse {\n data: string;\n metadata: ResponseMetadata;\n}\n\nexport async function ping(context: PingContext): Promise<PingResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Pinging server at', context.baseUrl);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const response = await fetch(`${context.baseUrl}/ping`, {\n method: 'GET',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Ping failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(response, 'Ping request failed', '/ping', 'GET');\n throw error;\n }\n\n const data: PingResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Ping successful', data);\n }\n\n return data;\n } catch (error) {\n if (context.debug) {\n console.debug('TenxGraphClient: Ping failed:', error);\n }\n\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: Ping timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n\n console.error('TenxGraphClient: Ping failed:', error);\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface GraphContext extends RequestContext {}\n\nexport interface GraphNode {\n id: string;\n name: string;\n}\n\nexport interface GraphEdge {\n id: string;\n source: string;\n target: string;\n}\n\nexport interface GraphInfo {\n node_count: number;\n edge_count: number;\n checkpointer: boolean;\n checkpointer_type: string;\n publisher: boolean;\n store: boolean;\n interrupt_before: string[];\n interrupt_after: string[];\n context_type: string;\n id_generator: string;\n id_type: string;\n state_type: string;\n state_fields: string[];\n}\n\nexport interface GraphData {\n info: GraphInfo;\n nodes: GraphNode[];\n edges: GraphEdge[];\n}\n\nexport interface GraphResponse {\n data: GraphData;\n metadata: ResponseMetadata;\n}\n\nexport async function graph(context: GraphContext): Promise<GraphResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Fetching graph from', context.baseUrl);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const response = await fetch(`${context.baseUrl}/v1/graph`, {\n method: 'GET',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Graph fetch failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Graph fetch failed',\n '/v1/graph',\n 'GET'\n );\n throw error;\n }\n\n const data: GraphResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Graph fetch successful', data);\n }\n\n return data;\n } catch (error) {\n if (context.debug) {\n console.debug('TenxGraphClient: Graph fetch failed:', error);\n }\n\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: Graph fetch timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n\n console.error('TenxGraphClient: Graph fetch failed:', error);\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface GraphToolsContext extends RequestContext {}\n\nexport type ToolSource = 'local' | 'mcp' | 'remote';\n\nexport interface GraphTool {\n name: string;\n description: string;\n source: ToolSource;\n /** JSON Schema of the tool parameters (OpenAI function-calling shape). */\n parameters: Record<string, any>;\n}\n\nexport interface GraphToolNode {\n node_name: string;\n tool_count: number;\n tools: GraphTool[];\n}\n\nexport interface GraphToolsData {\n node_count: number;\n tool_count: number;\n nodes: GraphToolNode[];\n}\n\nexport interface GraphToolsResponse {\n data: GraphToolsData;\n metadata: ResponseMetadata;\n}\n\n/**\n * Fetch the tools exposed by every ToolNode in the graph, grouped by node.\n * Each tool is tagged with its source (local / mcp / remote).\n */\nexport async function graphTools(context: GraphToolsContext): Promise<GraphToolsResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Fetching graph tools from', context.baseUrl);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const response = await fetch(`${context.baseUrl}/v1/graph/tools`, {\n method: 'GET',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Graph tools fetch failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Graph tools fetch failed',\n '/v1/graph/tools',\n 'GET'\n );\n throw error;\n }\n\n const data: GraphToolsResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Graph tools fetch successful', data);\n }\n\n return data;\n } catch (error) {\n if (context.debug) {\n console.debug('TenxGraphClient: Graph tools fetch failed:', error);\n }\n\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: Graph tools fetch timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n\n console.error('TenxGraphClient: Graph tools fetch failed:', error);\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface ObservabilityContext extends RequestContext {}\n\nexport interface ObsSpan {\n id: string;\n name: string;\n kind: 'root' | 'node' | 'llm' | 'tool';\n parent: string | null;\n start_ms: number;\n duration_ms: number;\n model?: string | null;\n input_tokens?: number | null;\n output_tokens?: number | null;\n}\n\nexport interface ObsEvent {\n id: string;\n type: string;\n node: string;\n offset_ms: number;\n summary: string;\n}\n\nexport interface ObsTokenUsage {\n prompt_tokens: number;\n completion_tokens: number;\n reasoning_tokens: number;\n total_tokens: number;\n}\n\nexport interface ObsRun {\n run_id: string;\n thread_id: string;\n status: string;\n started_at: number | null;\n finished_at: number | null;\n duration_ms: number;\n spans: ObsSpan[];\n events: ObsEvent[];\n usage: ObsTokenUsage;\n llm_calls: number;\n tool_calls: number;\n iterations: number;\n}\n\nexport interface ObservabilityData {\n thread_id: string;\n run_count: number;\n run_ids: string[];\n run: ObsRun | null;\n}\n\nexport interface ObservabilityResponse {\n data: ObservabilityData;\n metadata: ResponseMetadata;\n}\n\n/**\n * Fetch the reconstructed observability trace (spans, events, cost) for a thread.\n * Returns the latest run by default, or a specific run when `runId` is given.\n */\nexport async function observability(\n context: ObservabilityContext,\n threadId: string,\n runId?: string\n): Promise<ObservabilityResponse> {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const query = runId ? `?run_id=${encodeURIComponent(runId)}` : '';\n const response = await fetch(\n `${context.baseUrl}/v1/observability/${encodeURIComponent(threadId)}${query}`,\n {\n method: 'GET',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n signal: controller.signal,\n }\n );\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const error = await createErrorFromResponse(\n response,\n 'Observability fetch failed',\n `/v1/observability/${threadId}`,\n 'GET'\n );\n throw error;\n }\n\n return (await response.json()) as ObservabilityResponse;\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface StateSchemaContext extends RequestContext {}\n\n/**\n * JSON Schema definition for a field in AgentState\n * Contains type information, description, validation rules, and default values\n */\nexport interface FieldSchema {\n type?: string | string[];\n description?: string;\n default?: any;\n items?: any;\n properties?: Record<string, FieldSchema>;\n required?: string[];\n enum?: any[];\n $ref?: string;\n $defs?: Record<string, any>;\n anyOf?: any[];\n allOf?: any[];\n oneOf?: any[];\n [key: string]: any;\n}\n\n/**\n * Complete JSON Schema for AgentState\n * Describes all available fields, their types, constraints, and meanings\n */\nexport interface AgentStateSchema {\n title?: string;\n description?: string;\n type?: string;\n properties: Record<string, FieldSchema>;\n required?: string[];\n $defs?: Record<string, any>;\n [key: string]: any;\n}\n\n/**\n * Response containing the complete AgentState schema\n * Users can use this to:\n * - Understand field types and structure\n * - Build dynamic forms or validation\n * - Know what fields are available and required\n * - See field descriptions and constraints\n */\nexport interface StateSchemaResponse {\n data: AgentStateSchema;\n metadata: ResponseMetadata;\n}\n\nexport async function stateSchema(context: StateSchemaContext): Promise<StateSchemaResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Fetching state schema from', context.baseUrl);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const response = await fetch(`${context.baseUrl}/v1/graph:StateSchema`, {\n method: 'GET',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: State schema fetch failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'State schema fetch failed',\n '/v1/state_schema',\n 'GET'\n );\n throw error;\n }\n\n const data: StateSchemaResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: State schema fetch successful', data);\n }\n\n return data;\n } catch (error) {\n if (context.debug) {\n console.debug('TenxGraphClient: State schema fetch failed:', error);\n }\n\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: State schema fetch timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n\n console.error('TenxGraphClient: State schema fetch failed:', error);\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { AgentState } from '../agent.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface ThreadStateContext extends RequestContext {}\n\nexport interface ThreadStateData {\n state: AgentState;\n}\n\nexport interface ThreadStateResponse {\n data: ThreadStateData;\n metadata: ResponseMetadata;\n}\n\nexport async function threadState(\n context: ThreadStateContext,\n threadId: string | number\n): Promise<ThreadStateResponse> {\n try {\n if (context.debug) {\n console.debug(`TenxGraphClient: Fetching thread state for thread ${threadId}`);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const response = await fetch(`${context.baseUrl}/v1/threads/${threadId}/state`, {\n method: 'GET',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Thread state fetch failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Thread state fetch failed',\n '/v1/threads/{thread_id}/state',\n 'GET'\n );\n throw error;\n }\n\n const data: ThreadStateResponse = await response.json();\n\n if (context.debug) {\n console.info(\n `TenxGraphClient: Thread state fetched successfully for thread ${threadId}`,\n data\n );\n }\n\n return data;\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: Thread state fetch timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n\n if (context.debug) {\n console.debug(`TenxGraphClient: Thread state fetch failed:`, error);\n }\n\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { AgentState } from '../agent.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface UpdateThreadStateContext extends RequestContext {}\n\nexport interface UpdateThreadStateRequest {\n config: Record<string, any>;\n state: AgentState;\n}\n\nexport interface UpdateThreadStateData {\n state: AgentState;\n}\n\nexport interface UpdateThreadStateResponse {\n data: UpdateThreadStateData;\n metadata: ResponseMetadata;\n}\n\nexport async function updateThreadState(\n context: UpdateThreadStateContext,\n threadId: string | number,\n request: UpdateThreadStateRequest\n): Promise<UpdateThreadStateResponse> {\n try {\n if (context.debug) {\n console.debug(`TenxGraphClient: Updating thread state for thread ${threadId}`);\n console.debug(`TenxGraphClient: Request payload:`, JSON.stringify(request, null, 2));\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const response = await fetch(`${context.baseUrl}/v1/threads/${threadId}/state`, {\n method: 'PUT',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n body: JSON.stringify(request),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Thread state update failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Thread state update failed',\n '/v1/threads/{thread_id}/state',\n 'PUT'\n );\n throw error;\n }\n\n const data: UpdateThreadStateResponse = await response.json();\n\n if (context.debug) {\n console.info(\n `TenxGraphClient: Thread state updated successfully for thread ${threadId}`,\n data\n );\n }\n\n return data;\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: Thread state update timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n\n if (context.debug) {\n console.debug(`TenxGraphClient: Thread state update failed:`, error);\n }\n\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface ClearThreadStateContext extends RequestContext {}\n\nexport interface ClearThreadStateData {\n success: boolean;\n message: string;\n data: boolean;\n}\n\nexport interface ClearThreadStateResponse {\n data: ClearThreadStateData;\n metadata: ResponseMetadata;\n}\n\nexport async function clearThreadState(\n context: ClearThreadStateContext,\n threadId: string | number\n): Promise<ClearThreadStateResponse> {\n try {\n if (context.debug) {\n console.debug(`TenxGraphClient: Clearing thread state for thread ${threadId}`);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const response = await fetch(`${context.baseUrl}/v1/threads/${threadId}/state`, {\n method: 'DELETE',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Thread state clear failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Thread state clear failed',\n '/v1/threads/{thread_id}/state',\n 'DELETE'\n );\n throw error;\n }\n\n const data: ClearThreadStateResponse = await response.json();\n\n if (context.debug) {\n console.info(\n `TenxGraphClient: Thread state cleared successfully for thread ${threadId}`,\n data\n );\n }\n\n return data;\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: Thread state clear timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n\n if (context.debug) {\n console.debug(`TenxGraphClient: Thread state clear failed:`, error);\n }\n\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { Message } from '../message.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface ThreadMessagesContext extends RequestContext {}\n\nexport interface ThreadMessagesRequest {\n threadId: string | number;\n search?: string;\n offset?: number;\n limit?: number;\n}\n\nexport interface ThreadMessagesData {\n messages: Message[];\n}\n\n// Backward compatibility alias\nexport type CheckpointMessagesData = ThreadMessagesData;\n\nexport interface ThreadMessagesResponse {\n data: ThreadMessagesData;\n metadata: ResponseMetadata;\n}\n\n// Backward compatibility alias\nexport type CheckpointMessagesResponse = ThreadMessagesResponse;\n\nexport async function threadMessages(\n context: ThreadMessagesContext,\n request: ThreadMessagesRequest\n): Promise<ThreadMessagesResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Fetching thread messages for thread', request.threadId);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n // Build query parameters\n const params = new URLSearchParams();\n if (request.search !== undefined) {\n params.append('search', request.search);\n }\n if (request.offset !== undefined) {\n params.append('offset', request.offset.toString());\n }\n if (request.limit !== undefined) {\n params.append('limit', request.limit.toString());\n }\n\n const queryString = params.toString();\n const url = `${context.baseUrl}/v1/threads/${request.threadId}/messages${queryString ? '?' + queryString : ''}`;\n\n const response = await fetch(url, {\n method: 'GET',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(\n `TenxGraphClient: Checkpoint messages fetch failed with HTTP ${response.status}`\n );\n const error = await createErrorFromResponse(\n response,\n 'Thread messages fetch failed',\n '/v1/threads/{thread_id}/messages',\n 'GET'\n );\n throw error;\n }\n\n const data: ThreadMessagesResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Thread messages fetched successfully', data);\n }\n\n return data;\n } catch (error) {\n if (context.debug) {\n console.debug('TenxGraphClient: Checkpoint messages fetch failed:', error);\n }\n throw error;\n }\n}\n\n// Backward compatibility alias\nexport const checkpointMessages = threadMessages;\n","import { ResponseMetadata } from './metadata.js';\nimport { Message } from '../message.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface AddThreadMessagesContext extends RequestContext {}\n\nexport interface AddThreadMessagesRequest {\n threadId: string | number;\n config: Record<string, any>;\n messages: Message[];\n metadata?: Record<string, any>;\n}\n\nexport interface AddThreadMessagesData {\n success: boolean;\n message: string;\n data: Record<string, any>;\n}\n\nexport interface AddThreadMessagesResponse {\n data: AddThreadMessagesData;\n metadata: ResponseMetadata;\n}\n\nexport async function addThreadMessages(\n context: AddThreadMessagesContext,\n request: AddThreadMessagesRequest\n): Promise<AddThreadMessagesResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Adding thread messages to thread', request.threadId);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const url = `${context.baseUrl}/v1/threads/${request.threadId}/messages`;\n\n // Prepare request body\n const body = {\n config: request.config,\n messages: request.messages,\n metadata: request.metadata || {},\n };\n\n const response = await fetch(url, {\n method: 'POST',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Add checkpoint messages failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Add thread messages failed',\n '/v1/threads/{thread_id}/messages',\n 'POST'\n );\n throw error;\n }\n\n const data: AddThreadMessagesResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Thread messages added successfully', data);\n }\n\n return data;\n } catch (error) {\n if (context.debug) {\n console.debug('TenxGraphClient: Add checkpoint messages failed:', error);\n }\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { Message } from '../message.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface ThreadMessageContext extends RequestContext {}\n\nexport interface ThreadMessageRequest {\n threadId: string | number;\n messageId: string;\n}\n\nexport interface ThreadMessageData extends Message {\n // This extends the Message class to ensure type compatibility\n // The API returns a message object directly as data\n}\n\nexport interface ThreadMessageResponse {\n data: ThreadMessageData;\n metadata: ResponseMetadata;\n}\n\nexport async function threadMessage(\n context: ThreadMessageContext,\n request: ThreadMessageRequest\n): Promise<ThreadMessageResponse> {\n try {\n if (context.debug) {\n console.debug(\n 'TenxGraphClient: Fetching thread message',\n `thread: ${request.threadId}`,\n `message: ${request.messageId}`\n );\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const url = `${context.baseUrl}/v1/threads/${request.threadId}/messages/${request.messageId}`;\n\n const response = await fetch(url, {\n method: 'GET',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Thread message fetch failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Thread message fetch failed',\n '/v1/threads/{thread_id}/messages/{message_id}',\n 'GET'\n );\n throw error;\n }\n\n const data: ThreadMessageResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Thread message fetched successfully', data);\n }\n\n return data;\n } catch (error) {\n if (context.debug) {\n console.debug('TenxGraphClient: Thread message fetch failed:', error);\n }\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface ThreadDetailsContext extends RequestContext {}\n\nexport interface ThreadDetailsData {\n thread_data: {\n thread: Record<string, any>;\n };\n}\n\nexport interface ThreadDetailsResponse {\n data: ThreadDetailsData;\n metadata: ResponseMetadata;\n}\n\n/**\n * Fetch details for a specific thread.\n * GET /v1/threads/{threadId}\n */\nexport async function threadDetails(\n context: ThreadDetailsContext,\n threadId: string | number\n): Promise<ThreadDetailsResponse> {\n try {\n if (context.debug) {\n console.debug(`TenxGraphClient: Fetching thread details for thread ${threadId}`);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const url = `${context.baseUrl}/v1/threads/${threadId}`;\n\n const response = await fetch(url, {\n method: 'GET',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Thread details fetch failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Thread details fetch failed',\n '/v1/threads/{thread_id}',\n 'GET'\n );\n throw error;\n }\n\n const data: ThreadDetailsResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Thread details fetched successfully', data);\n }\n\n return data;\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: Thread details fetch timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n\n if (context.debug) {\n console.debug('TenxGraphClient: Thread details fetch failed:', error);\n }\n\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface DeleteThreadMessageContext extends RequestContext {}\n\nexport interface DeleteThreadMessageRequest {\n threadId: string | number;\n messageId: string;\n config?: Record<string, any>;\n}\n\nexport interface DeleteThreadMessageData {\n success: boolean;\n message: string;\n data: Record<string, any>;\n}\n\nexport interface DeleteThreadMessageResponse {\n data: DeleteThreadMessageData;\n metadata: ResponseMetadata;\n}\n\nexport async function deleteThreadMessage(\n context: DeleteThreadMessageContext,\n request: DeleteThreadMessageRequest\n): Promise<DeleteThreadMessageResponse> {\n try {\n if (context.debug) {\n console.debug(\n 'TenxGraphClient: Deleting thread message',\n `thread: ${request.threadId}`,\n `message: ${request.messageId}`\n );\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const url = `${context.baseUrl}/v1/threads/${request.threadId}/messages/${request.messageId}`;\n\n const response = await fetch(url, {\n method: 'DELETE',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n body: JSON.stringify({ config: request.config || {} }),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Delete thread message failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Delete thread message failed',\n '/v1/threads/{thread_id}/messages/{message_id}',\n 'DELETE'\n );\n throw error;\n }\n\n const data: DeleteThreadMessageResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Thread message deleted successfully', data);\n }\n\n return data;\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: Delete thread message timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n if (context.debug) {\n console.debug('TenxGraphClient: Delete thread message failed:', error);\n }\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface DeleteThreadContext extends RequestContext {}\n\nexport interface DeleteThreadRequest {\n threadId: string | number;\n config?: Record<string, any>;\n}\n\nexport interface DeleteThreadData {\n success: boolean;\n message: string;\n data: boolean;\n}\n\nexport interface DeleteThreadResponse {\n data: DeleteThreadData;\n metadata: ResponseMetadata;\n}\n\nexport async function deleteThread(\n context: DeleteThreadContext,\n request: DeleteThreadRequest\n): Promise<DeleteThreadResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Deleting thread', `thread: ${request.threadId}`);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const url = `${context.baseUrl}/v1/threads/${request.threadId}`;\n\n const response = await fetch(url, {\n method: 'DELETE',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n body: JSON.stringify({ config: request.config || {} }),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Delete thread failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Delete thread failed',\n '/v1/threads/{thread_id}',\n 'DELETE'\n );\n throw error;\n }\n\n const data: DeleteThreadResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Thread deleted successfully', data);\n }\n\n return data;\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: Delete thread timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n if (context.debug) {\n console.debug('TenxGraphClient: Delete thread failed:', error);\n }\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface ThreadsContext extends RequestContext {}\n\nexport interface ThreadsRequest {\n search?: string;\n offset?: number;\n limit?: number;\n}\n\nexport interface ThreadItem {\n thread_id: string;\n thread_name: string | null;\n user_id: string | null;\n metadata: Record<string, any> | null;\n updated_at: string | null;\n run_id: string | null;\n}\n\nexport interface ThreadsData {\n threads: ThreadItem[];\n}\n\nexport interface ThreadsResponse {\n data: ThreadsData;\n metadata: ResponseMetadata;\n}\n\n/**\n * Fetch list of threads with optional search and pagination\n * GET /v1/threads\n */\nexport async function threads(\n context: ThreadsContext,\n request?: ThreadsRequest\n): Promise<ThreadsResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Fetching threads list');\n if (request?.search) {\n console.debug(` Search: ${request.search}`);\n }\n if (request?.offset !== undefined) {\n console.debug(` Offset: ${request.offset}`);\n }\n if (request?.limit !== undefined) {\n console.debug(` Limit: ${request.limit}`);\n }\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n // Build query parameters\n const params = new URLSearchParams();\n if (request?.search) {\n params.append('search', request.search);\n }\n if (request?.offset !== undefined) {\n params.append('offset', request.offset.toString());\n }\n if (request?.limit !== undefined) {\n params.append('limit', request.limit.toString());\n }\n\n const queryString = params.toString();\n const url = `${context.baseUrl}/v1/threads${queryString ? `?${queryString}` : ''}`;\n\n const response = await fetch(url, {\n method: 'GET',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Threads list fetch failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Threads list fetch failed',\n '/v1/threads',\n 'GET'\n );\n throw error;\n }\n\n const data: ThreadsResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Threads list fetched successfully', data);\n console.debug(` Found ${data.data.threads.length} threads`);\n }\n\n return data;\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: Threads list fetch timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n if (context.debug) {\n console.debug('TenxGraphClient: Threads list fetch failed:', error);\n }\n throw error;\n }\n}\n","import { Message } from '../message.js';\nimport { AgentState } from '../agent.js';\nimport { ToolExecutor } from '../tools.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface InvokeContext extends RequestContext {\n toolExecutor?: ToolExecutor;\n}\n\n// Invoke Request payload\nexport interface InvokeRequest {\n messages: any[]; // Will be serialized Message objects\n initial_state?: Record<string, any>;\n config?: Record<string, any>;\n recursion_limit?: number;\n response_granularity?: 'full' | 'partial' | 'low';\n}\n\n// Response metadata\nexport interface InvokeMetadata {\n is_new_thread: boolean;\n thread_id: string;\n}\n\n// Full invoke response from server (single call)\nexport interface InvokeResponse {\n data: {\n messages: Message[];\n state?: AgentState;\n context?: Message[];\n summary?: string | null;\n meta: InvokeMetadata;\n };\n metadata: {\n request_id: string;\n timestamp: string;\n message: string;\n };\n}\n\n// Result with all intermediate steps\nexport interface InvokeResult {\n messages: Message[];\n state?: AgentState;\n context?: Message[];\n summary?: string | null;\n meta: InvokeMetadata;\n all_messages: Message[]; // All messages including intermediate steps\n iterations: number;\n recursion_limit_reached: boolean;\n}\n\n// Partial result sent on each iteration\nexport interface InvokePartialResult {\n iteration: number;\n messages: Message[];\n state?: AgentState;\n context?: Message[];\n summary?: string | null;\n meta: InvokeMetadata;\n has_tool_calls: boolean;\n is_final: boolean;\n}\n\n// Callback type for receiving partial results\nexport type InvokeCallback = (partial: InvokePartialResult) => void | Promise<void>;\n\n/**\n * Make a single API call to /v1/graph/invoke\n */\nasync function makeSingleInvokeCall(\n context: InvokeContext,\n request: InvokeRequest\n): Promise<InvokeResponse> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n try {\n const response = await fetch(`${context.baseUrl}/v1/graph/invoke`, {\n method: 'POST',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n body: JSON.stringify(request),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Invoke failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Invoke request failed',\n '/v1/invoke',\n 'POST'\n );\n throw error;\n }\n\n const data: InvokeResponse = await response.json();\n return data;\n } catch (error) {\n clearTimeout(timeoutId);\n\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: Invoke timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n\n console.error('TenxGraphClient: Invoke failed:', error);\n throw error;\n }\n}\n\n/**\n * Check if response contains remote tool calls\n */\nfunction hasRemoteToolCalls(response: InvokeResponse): boolean {\n if (!response.data || !response.data.messages) return false;\n\n return response.data.messages.some(\n (msg: Message) =>\n msg.content && msg.content.some((block: any) => block.type === 'remote_tool_call')\n );\n}\n\n/**\n * Invoke the graph with automatic tool execution loop\n * @param onPartialResult - Optional callback to receive results as they arrive\n */\nexport async function invoke(\n context: InvokeContext,\n request: InvokeRequest,\n onPartialResult?: InvokeCallback\n): Promise<InvokeResult> {\n const recursion_limit = request.recursion_limit || 25;\n\n if (context.debug) {\n console.debug('TenxGraphClient: Starting invoke with recursion_limit:', recursion_limit);\n console.debug('TenxGraphClient: Initial request:', JSON.stringify(request, null, 2));\n }\n\n // Keep track of all messages across iterations\n const allMessages: Message[] = [];\n let currentMessages = request.messages;\n let iterations = 0;\n let recursionLimitReached = false;\n let lastResponse: InvokeResponse | undefined;\n const initial_state = request.initial_state;\n const config = request.config;\n const response_granularity = request.response_granularity;\n\n // Main recursion loop\n while (iterations < recursion_limit) {\n iterations++;\n\n if (context.debug) {\n console.debug(`TenxGraphClient: Iteration ${iterations}/${recursion_limit}`);\n }\n\n // Prepare request for this iteration\n const iterationRequest: InvokeRequest = {\n messages: currentMessages,\n initial_state: iterations === 1 ? initial_state : undefined,\n config,\n recursion_limit,\n response_granularity,\n };\n\n if (context.debug) {\n console.debug('TenxGraphClient: Request payload:', JSON.stringify(iterationRequest, null, 2));\n }\n\n // Make the API call\n const response = await makeSingleInvokeCall(context, iterationRequest);\n lastResponse = response;\n\n if (context.debug) {\n console.info('TenxGraphClient: Invoke successful');\n console.debug('TenxGraphClient: Response:', JSON.stringify(response, null, 2));\n }\n\n // Add response messages to our collection\n if (response.data.messages) {\n allMessages.push(...response.data.messages);\n }\n\n // Check if there are remote tool calls to execute\n const hasToolCalls = hasRemoteToolCalls(response);\n\n // Send partial result immediately if callback provided\n if (onPartialResult) {\n const partialResult: InvokePartialResult = {\n iteration: iterations,\n messages: response.data.messages,\n state: response.data.state,\n context: response.data.context,\n summary: response.data.summary,\n meta: response.data.meta,\n has_tool_calls: hasToolCalls,\n is_final: !hasToolCalls,\n };\n\n await onPartialResult(partialResult);\n }\n\n if (hasToolCalls && context.toolExecutor) {\n if (context.debug) {\n console.debug('TenxGraphClient: Found remote tool calls, executing...');\n }\n\n // Execute all tool calls using the ToolExecutor\n const toolResults = await context.toolExecutor.executeToolCalls(response.data.messages);\n\n if (context.debug) {\n console.debug(`TenxGraphClient: Executed ${toolResults.length} tool calls`);\n }\n\n // Add tool results to all messages\n allMessages.push(...toolResults);\n\n // Serialize tool results for next iteration\n currentMessages = toolResults.map((msg) => serializeMessage(msg));\n\n // Continue the loop\n continue;\n } else {\n // No more tool calls, we're done\n if (context.debug) {\n console.debug('TenxGraphClient: No remote tool calls found, finishing');\n }\n break;\n }\n }\n\n // Check if we hit the recursion limit\n if (iterations >= recursion_limit) {\n recursionLimitReached = true;\n if (context.debug) {\n console.warn(`TenxGraphClient: Recursion limit of ${recursion_limit} reached`);\n }\n }\n\n // Construct the result\n const result: InvokeResult = {\n messages: lastResponse?.data.messages || [],\n state: lastResponse?.data.state,\n context: lastResponse?.data.context,\n summary: lastResponse?.data.summary,\n meta: lastResponse?.data.meta || { is_new_thread: false, thread_id: '' },\n all_messages: allMessages,\n iterations,\n recursion_limit_reached: recursionLimitReached,\n };\n\n if (context.debug) {\n console.debug(`TenxGraphClient: Invoke completed after ${iterations} iterations`);\n console.debug(`TenxGraphClient: Total messages: ${allMessages.length}`);\n }\n\n return result;\n}\n\n/**\n * Clean content blocks by removing empty arrays and undefined values\n * Server requires array of content blocks\n */\nfunction cleanContent(content: any[]): any[] {\n // Always return as array of blocks (server requires this format)\n return content.map((block) => {\n const cleaned: any = {};\n\n for (const [key, value] of Object.entries(block)) {\n // Skip empty arrays\n if (Array.isArray(value) && value.length === 0) {\n continue;\n }\n // Skip undefined values\n if (value === undefined) {\n continue;\n }\n cleaned[key] = value;\n }\n\n return cleaned;\n });\n}\n\n/**\n * Serialize a Message object for API transmission\n */\nfunction serializeMessage(message: Message): any {\n const serialized: any = {\n role: message.role,\n content: cleanContent(message.content),\n };\n\n // message_id: use \"0\" if not set (server will generate one)\n if (message.message_id !== null && message.message_id !== undefined) {\n serialized.message_id = String(message.message_id);\n } else {\n serialized.message_id = '0';\n }\n\n // Only include optional fields if they are explicitly set\n if (message.tools_calls) {\n serialized.tools_calls = message.tools_calls;\n }\n if (message.metadata && Object.keys(message.metadata).length > 0) {\n serialized.metadata = message.metadata;\n }\n\n return serialized;\n}\n","import { Message } from '../message.js';\nimport { AgentState } from '../agent.js';\nimport { ToolExecutor } from '../tools.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface StreamContext extends RequestContext {\n toolExecutor?: ToolExecutor;\n}\n\n// Stream Request payload (same as Invoke)\nexport interface StreamRequest {\n messages: any[]; // Will be serialized Message objects\n initial_state?: Record<string, any>;\n config?: Record<string, any>;\n recursion_limit?: number;\n response_granularity?: 'full' | 'partial' | 'low';\n}\n\n// Stream Events\nexport enum StreamEventType {\n MESSAGE = 'message',\n UPDATES = 'updates',\n STATE = 'state',\n ERROR = 'error',\n}\n\n// Response metadata\nexport interface StreamMetadata {\n is_new_thread: boolean;\n thread_id: string;\n [key: string]: any;\n}\n\n// Individual stream chunk from server\nexport interface StreamChunk {\n event: StreamEventType | string;\n message?: Message | null;\n state?: AgentState | null;\n data?: any;\n thread_id?: string;\n run_id?: string;\n metadata?: StreamMetadata | Record<string, any>;\n timestamp?: number;\n}\n\n/**\n * Parse NDJSON stream and yield individual chunks immediately as they arrive\n * Handles streaming response body as async iterable\n * Supports both newline-separated and concatenated JSON objects\n */\nasync function* parseStreamChunks(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n debug: boolean\n): AsyncGenerator<StreamChunk, void, unknown> {\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n // Process any remaining data in buffer\n if (buffer.trim()) {\n yield* processBuffer(buffer, debug, true);\n }\n break;\n }\n\n // Append new data to buffer\n buffer += decoder.decode(value, { stream: true });\n\n // Immediately process and yield all complete chunks\n const result = yield* processBuffer(buffer, debug, false);\n buffer = result.remaining;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * Process buffer and yield all complete JSON chunks\n * Returns the remaining incomplete buffer\n */\nfunction* processBuffer(\n buffer: string,\n debug: boolean,\n isFinal: boolean\n): Generator<StreamChunk, { remaining: string }, unknown> {\n // First, try to process newline-separated lines (NDJSON format)\n while (buffer.includes('\\n')) {\n const newlineIndex = buffer.indexOf('\\n');\n const line = buffer.slice(0, newlineIndex).trim();\n buffer = buffer.slice(newlineIndex + 1);\n\n if (line) {\n try {\n const chunk = JSON.parse(line) as StreamChunk;\n if (debug) {\n console.debug('TenxGraphClient: Stream chunk received (NDJSON):', chunk.event);\n }\n yield chunk;\n } catch (error) {\n if (debug) {\n console.warn('TenxGraphClient: Failed to parse NDJSON line:', line.slice(0, 100), error);\n }\n }\n }\n }\n\n // Then, try to extract concatenated JSON objects (no newlines)\n while (buffer.trim()) {\n const extracted = extractFirstJSON(buffer);\n if (extracted) {\n try {\n const chunk = JSON.parse(extracted.json) as StreamChunk;\n if (debug) {\n console.debug('TenxGraphClient: Stream chunk received (concat):', chunk.event);\n }\n yield chunk;\n buffer = extracted.remaining;\n } catch (error) {\n if (debug) {\n console.warn(\n 'TenxGraphClient: Failed to parse concatenated JSON:',\n extracted.json.slice(0, 100),\n error\n );\n }\n break;\n }\n } else {\n // Incomplete JSON, keep in buffer\n if (isFinal && buffer.trim()) {\n // On final read, try to parse what's left\n try {\n const chunk = JSON.parse(buffer.trim()) as StreamChunk;\n if (debug) {\n console.debug('TenxGraphClient: Final stream chunk:', chunk.event);\n }\n yield chunk;\n buffer = '';\n } catch (error) {\n if (debug) {\n console.warn(\n 'TenxGraphClient: Failed to parse final buffer:',\n buffer.slice(0, 100),\n error\n );\n }\n }\n }\n break;\n }\n }\n\n return { remaining: buffer };\n}\n\n/**\n * Extract the first complete JSON object from a string that may contain multiple concatenated JSON objects\n * Returns the JSON string and the remaining buffer\n */\nfunction extractFirstJSON(buffer: string): { json: string; remaining: string } | null {\n buffer = buffer.trim();\n if (!buffer || buffer[0] !== '{') {\n return null;\n }\n\n let depth = 0;\n let inString = false;\n let escaped = false;\n\n for (let i = 0; i < buffer.length; i++) {\n const char = buffer[i];\n\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === '\\\\') {\n escaped = true;\n continue;\n }\n\n if (char === '\"') {\n inString = !inString;\n continue;\n }\n\n if (inString) {\n continue;\n }\n\n if (char === '{') {\n depth++;\n } else if (char === '}') {\n depth--;\n if (depth === 0) {\n // Found complete JSON object\n return {\n json: buffer.slice(0, i + 1),\n remaining: buffer.slice(i + 1).trim(),\n };\n }\n }\n }\n\n // Incomplete JSON object\n return null;\n}\n\n/**\n * Check if messages contain remote tool calls\n */\nfunction hasRemoteToolCalls(messages: Message[]): boolean {\n return messages.some(\n (msg: Message) =>\n msg.content && msg.content.some((block: any) => block.type === 'remote_tool_call')\n );\n}\n\n/**\n * Stream invoke to the graph with automatic tool execution loop\n * Returns an async iterable that yields stream chunks as they arrive\n *\n * This implements the same tool execution loop as invoke(), but uses\n * HTTP streaming instead of REST API calls.\n *\n * @example\n * ```ts\n * const stream = streamInvoke(context, request);\n * for await (const chunk of stream) {\n * if (chunk.event === 'message') {\n * console.log('Message:', chunk.message);\n * } else if (chunk.event === 'updates') {\n * console.log('State:', chunk.state);\n * }\n * }\n * ```\n */\nexport async function* streamInvoke(\n context: StreamContext,\n request: StreamRequest\n): AsyncGenerator<StreamChunk, void, unknown> {\n const recursion_limit = request.recursion_limit || 25;\n\n if (context.debug) {\n console.debug('TenxGraphClient: Starting stream invoke with recursion_limit:', recursion_limit);\n console.debug('TenxGraphClient: Initial request:', JSON.stringify(request, null, 2));\n }\n\n let currentMessages = request.messages;\n let iterations = 0;\n const initial_state = request.initial_state;\n const config = request.config;\n const response_granularity = request.response_granularity;\n\n // Main recursion loop (same as invoke, but using streaming)\n while (iterations < recursion_limit) {\n iterations++;\n\n if (context.debug) {\n console.debug(`TenxGraphClient: Stream iteration ${iterations}/${recursion_limit}`);\n }\n\n // Prepare request for this iteration\n const iterationRequest: StreamRequest = {\n messages: currentMessages,\n initial_state: iterations === 1 ? initial_state : undefined,\n config,\n recursion_limit,\n response_granularity,\n };\n\n if (context.debug) {\n console.debug(\n 'TenxGraphClient: Stream request payload:',\n JSON.stringify(iterationRequest, null, 2)\n );\n }\n\n // Open the stream and yield all chunks\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n try {\n const response = await fetch(`${context.baseUrl}/v1/graph/stream`, {\n method: 'POST',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n Accept: 'application/x-ndjson, application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n body: JSON.stringify(iterationRequest),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Stream failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Stream request failed',\n '/v1/stream',\n 'POST'\n );\n throw error;\n }\n\n if (!response.body) {\n throw new Error('No response body for stream');\n }\n\n // Collect messages while yielding chunks\n const responseMessages: Message[] = [];\n const reader = response.body.getReader();\n\n for await (const chunk of parseStreamChunks(reader, context.debug)) {\n // Yield every chunk to the caller\n yield chunk;\n\n // Also collect messages for tool execution check\n if (chunk.message) {\n responseMessages.push(chunk.message);\n }\n }\n\n if (context.debug) {\n console.info('TenxGraphClient: Stream iteration completed');\n console.debug('TenxGraphClient: Received', responseMessages.length, 'messages');\n }\n\n // Check if there are remote tool calls to execute\n const hasToolCalls = hasRemoteToolCalls(responseMessages);\n\n if (hasToolCalls && context.toolExecutor) {\n if (context.debug) {\n console.debug('TenxGraphClient: Found remote tool calls, executing...');\n }\n\n // Execute all tool calls using the ToolExecutor\n const toolResults = await context.toolExecutor.executeToolCalls(responseMessages);\n\n if (context.debug) {\n console.debug(`TenxGraphClient: Executed ${toolResults.length} tool calls`);\n }\n\n // Serialize tool results for next iteration\n currentMessages = toolResults.map((msg) => serializeMessage(msg));\n\n // Continue the loop with tool results\n continue;\n } else {\n // No more tool calls, we're done\n if (context.debug) {\n console.debug('TenxGraphClient: No remote tool calls found, finishing');\n }\n break;\n }\n } catch (error) {\n clearTimeout(timeoutId);\n\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: Stream timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n\n console.error('TenxGraphClient: Stream failed:', error);\n throw error;\n }\n }\n\n // Check if we hit the recursion limit\n if (iterations >= recursion_limit) {\n if (context.debug) {\n console.warn(`TenxGraphClient: Recursion limit of ${recursion_limit} reached`);\n }\n }\n\n if (context.debug) {\n console.debug(`TenxGraphClient: Stream invoke completed after ${iterations} iterations`);\n }\n}\n\n/**\n * Clean content blocks by removing empty arrays and undefined values\n * Server requires array of content blocks, not simplified string\n */\nfunction cleanContent(content: any[]): any[] {\n // Always return as array of blocks (server requires this format)\n return content.map((block) => {\n const cleaned: any = {};\n\n for (const [key, value] of Object.entries(block)) {\n // Skip empty arrays\n if (Array.isArray(value) && value.length === 0) {\n continue;\n }\n // Skip undefined values\n if (value === undefined) {\n continue;\n }\n cleaned[key] = value;\n }\n\n return cleaned;\n });\n}\n\n/**\n * Serialize a Message object for API transmission\n */\nexport function serializeMessage(message: Message): any {\n const serialized: any = {\n role: message.role,\n content: cleanContent(message.content),\n };\n\n // message_id: use \"0\" if not set (server will generate one)\n if (message.message_id !== null && message.message_id !== undefined) {\n serialized.message_id = String(message.message_id);\n } else {\n serialized.message_id = '0';\n }\n\n // Only include optional fields if they are explicitly set\n if (message.tools_calls) {\n serialized.tools_calls = message.tools_calls;\n }\n if (message.metadata && Object.keys(message.metadata).length > 0) {\n serialized.metadata = message.metadata;\n }\n\n return serialized;\n}\n","import { TenxGraphAuth, buildHeaders } from './request.js';\n\n/**\n * Sec-WebSocket-Protocol token the server recognizes for browser-safe bearer auth.\n * The client opens the socket with `[WS_BEARER_SUBPROTOCOL, \"<jwt>\"]`; the server\n * extracts the second protocol entry as the token. This works in browsers (which\n * cannot set request headers on a WebSocket) and avoids leaking the token in the URL.\n */\nexport const WS_BEARER_SUBPROTOCOL = '10xgraph-bearer';\n\n/** Minimal constructor shape shared by the browser `WebSocket` and the Node `ws` package. */\nexport type WebSocketImpl = new (\n url: string,\n protocols?: string | string[],\n options?: unknown\n) => WebSocket;\n\n/** The auth/transport fields the WS helpers read from a request context. */\nexport interface WsAuthContext {\n baseUrl: string;\n authToken?: string | null;\n auth?: TenxGraphAuth | null;\n headers?: HeadersInit;\n credentials?: RequestCredentials;\n debug?: boolean;\n /** Optional WebSocket implementation for runtimes without a global (Node < 21). */\n webSocketImpl?: WebSocketImpl;\n}\n\n/**\n * Resolve the bearer token with the same priority as `buildHeaders`.\n *\n * `auth` takes precedence over `authToken`, matching the HTTP path. When `auth`\n * is set to a non-bearer scheme (basic/header) there is no bearer token to send,\n * so this returns `null` rather than silently falling back to `authToken` — the\n * HTTP path would not send a bearer in that case either.\n */\nexport function resolveBearerToken(\n context: Pick<WsAuthContext, 'authToken' | 'auth'>\n): string | null {\n if (context.auth) {\n return context.auth.type === 'bearer' ? context.auth.token : null;\n }\n if (context.authToken) {\n return context.authToken;\n }\n return null;\n}\n\n/**\n * Convert the HTTP base URL to a WebSocket URL and append `path`.\n * The token is never placed in the URL — it travels via the `10xgraph-bearer`\n * subprotocol (browser-safe) and, in Node, the Authorization header.\n */\nexport function buildWsUrl(context: Pick<WsAuthContext, 'baseUrl'>, path: string): string {\n return (\n context.baseUrl\n .replace(/^https:/, 'wss:')\n .replace(/^http:/, 'ws:')\n .replace(/\\/$/, '') + path\n );\n}\n\n/**\n * Open a WebSocket with bearer auth.\n *\n * - If a token is present it is sent as the `10xgraph-bearer` subprotocol (works\n * in browsers and Node `ws`).\n * - In Node-style implementations that accept a third `options` argument, the\n * Authorization header is also passed (ignored by browsers).\n * - The implementation is taken from `context.webSocketImpl`, falling back to the\n * global `WebSocket`. If neither exists a descriptive error is thrown.\n */\nexport function openWebSocket(url: string, context: WsAuthContext): WebSocket {\n const Impl: WebSocketImpl | undefined =\n context.webSocketImpl ?? (globalThis as { WebSocket?: WebSocketImpl }).WebSocket;\n\n if (!Impl) {\n throw new Error(\n 'No WebSocket implementation available. In Node < 21 pass `webSocketImpl` ' +\n 'in the client config (e.g. the `ws` package: `new TenxGraphClient({ ..., webSocketImpl: WebSocket })`).'\n );\n }\n\n const token = resolveBearerToken(context);\n const protocols = token ? [WS_BEARER_SUBPROTOCOL, token] : undefined;\n\n const headers = buildHeaders(context);\n const authHeader = headers['Authorization'] ?? headers['authorization'];\n\n if (authHeader) {\n try {\n return new Impl(url, protocols, { headers: { Authorization: authHeader } });\n } catch {\n // Fall through: browser constructors reject the 3rd arg shape — retry plain.\n }\n }\n\n return new Impl(url, protocols);\n}\n","import { Message } from '../message.js';\nimport { ToolExecutor } from '../tools.js';\nimport { RequestContext } from '../request.js';\nimport { buildWsUrl, openWebSocket } from '../ws.js';\nimport { StreamChunk, StreamEventType, StreamRequest, serializeMessage } from './stream.js';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public types\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface WsStreamContext extends RequestContext {\n toolExecutor?: ToolExecutor;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal types (mirror the server's WsGraphInputSchema)\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface WsGraphInput {\n invoke_type: 'fresh' | 'resume';\n messages?: any[];\n tool_result?: any[];\n initial_state?: Record<string, any>;\n config?: Record<string, any>;\n recursion_limit?: number;\n response_granularity?: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** True when any collected message contains a remote_tool_call block. */\nfunction hasRemoteToolCalls(messages: Message[]): boolean {\n return messages.some(\n (msg) => msg.content && msg.content.some((block: any) => block.type === 'remote_tool_call')\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Core implementation\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Stream invoke via a persistent WebSocket connection.\n *\n * The protocol is:\n *\n * 1. Connect to ``/v1/graph/ws`` (auth via the ``10xgraph-bearer`` subprotocol or Authorization header).\n * 2. Send ``{ invoke_type:\"fresh\", messages:[…], config:{…}, … }``.\n * 3. Receive ``StreamChunk`` JSON messages; yield each to the caller.\n * 4. Server sends ``{ event:\"updates\", data:{ status:\"done\" } }`` after each run.\n * 5. If the run contained remote tool calls, execute them and send:\n * ``{ invoke_type:\"resume\", tool_result:[…], config:{ thread_id } }``.\n * 6. Repeat from step 3 until no more tool calls.\n * 7. Close the WebSocket.\n *\n * This replaces the HTTP loop in ``streamInvoke`` — the round-trip cost of\n * re-opening a new HTTP connection for each tool call is eliminated.\n *\n * @example\n * ```ts\n * const stream = wsStreamInvoke(context, request);\n * for await (const chunk of stream) {\n * if (chunk.event === 'message') console.log(chunk.message);\n * }\n * ```\n */\nexport async function* wsStreamInvoke(\n context: WsStreamContext,\n request: StreamRequest\n): AsyncGenerator<StreamChunk, void, unknown> {\n const url = buildWsUrl(context, '/v1/graph/ws');\n\n if (context.debug) {\n console.debug('TenxGraphClient [WS]: connecting to', url);\n }\n\n const ws = openWebSocket(url, context);\n\n // ── Queue bridge ──────────────────────────────────────────────────────────\n // WebSocket is event-based; async generators are pull-based.\n // We buffer incoming items in a queue and wake up the generator each time.\n const queue: Array<StreamChunk | Error | 'close'> = [];\n let wakeUp: (() => void) | null = null;\n\n const enqueue = (item: StreamChunk | Error | 'close'): void => {\n queue.push(item);\n if (wakeUp) {\n const fn = wakeUp;\n wakeUp = null;\n fn();\n }\n };\n\n const waitForItem = (): Promise<void> =>\n new Promise((resolve) => {\n if (queue.length > 0) {\n resolve();\n } else {\n wakeUp = resolve;\n }\n });\n\n ws.addEventListener('message', (event: MessageEvent) => {\n try {\n const chunk = JSON.parse(event.data as string) as StreamChunk;\n enqueue(chunk);\n } catch (e) {\n if (context.debug) {\n console.warn('TenxGraphClient [WS]: failed to parse chunk:', e);\n }\n }\n });\n\n ws.addEventListener('error', () => {\n enqueue(new Error('WebSocket error'));\n });\n\n ws.addEventListener('close', (event: CloseEvent) => {\n if (context.debug) {\n console.debug('TenxGraphClient [WS]: connection closed, code=', event.code);\n }\n enqueue('close');\n });\n\n // Wait for the connection to open (or fail)\n await new Promise<void>((resolve, reject) => {\n // Numeric readyState literals (OPEN===1) instead of WebSocket.OPEN: the\n // global WebSocket may be absent on Node < 21 when a custom impl is injected.\n if (ws.readyState === 1) {\n resolve();\n return;\n }\n ws.addEventListener('open', () => resolve(), { once: true });\n ws.addEventListener('error', () => reject(new Error('WebSocket connection failed')), {\n once: true,\n });\n });\n\n if (context.debug) {\n console.debug('TenxGraphClient [WS]: connected');\n }\n\n // ── Main loop ─────────────────────────────────────────────────────────────\n let threadId: string | undefined = (request.config as Record<string, any>)?.thread_id;\n\n let nextPayload: WsGraphInput = {\n invoke_type: 'fresh',\n messages: request.messages,\n initial_state: request.initial_state,\n config: request.config,\n recursion_limit: request.recursion_limit ?? 25,\n response_granularity: request.response_granularity,\n };\n\n try {\n outerLoop: while (true) {\n if (context.debug) {\n console.debug(\n `TenxGraphClient [WS]: sending ${nextPayload.invoke_type} request, thread_id=${threadId ?? 'new'}`\n );\n }\n\n ws.send(JSON.stringify(nextPayload));\n\n // ── Inner loop: receive chunks until the server sends \"done\" ──────\n const runMessages: Message[] = [];\n\n innerLoop: while (true) {\n await waitForItem();\n const item = queue.shift()!;\n\n if (item === 'close') {\n // Server closed the connection unexpectedly\n break outerLoop;\n }\n\n if (item instanceof Error) {\n throw item;\n }\n\n const chunk = item as StreamChunk;\n\n // Track thread_id for resume requests\n if (chunk.thread_id) {\n threadId = chunk.thread_id;\n }\n if ((chunk.metadata as Record<string, any>)?.thread_id) {\n threadId = (chunk.metadata as Record<string, any>).thread_id as string;\n }\n\n // \"done\" signal: current run is complete\n if (chunk.event === StreamEventType.UPDATES && (chunk.data as any)?.status === 'done') {\n break innerLoop;\n }\n\n // Accumulate messages for tool-call detection\n if (chunk.message) {\n runMessages.push(chunk.message);\n }\n\n // Yield every chunk to the caller (same as HTTP stream)\n yield chunk;\n }\n\n if (context.debug) {\n console.debug(\n `TenxGraphClient [WS]: run complete, ${runMessages.length} messages collected`\n );\n }\n\n // ── Tool-call detection & resume ──────────────────────────────────\n if (hasRemoteToolCalls(runMessages) && context.toolExecutor) {\n if (context.debug) {\n console.debug('TenxGraphClient [WS]: remote tool calls detected, executing…');\n }\n\n const toolResults = await context.toolExecutor.executeToolCalls(runMessages);\n\n if (context.debug) {\n console.debug(\n `TenxGraphClient [WS]: ${toolResults.length} tool result(s) ready, resuming`\n );\n }\n\n nextPayload = {\n invoke_type: 'resume',\n tool_result: toolResults.map(serializeMessage),\n config: { ...(request.config ?? {}), thread_id: threadId },\n recursion_limit: request.recursion_limit ?? 25,\n response_granularity: request.response_granularity,\n };\n // continue outerLoop → send resume request\n } else {\n // No tool calls — the full run is done\n break outerLoop;\n }\n }\n } finally {\n // CONNECTING===0, OPEN===1 (numeric literals; the global WebSocket may be\n // absent on Node < 21 when a custom impl is injected).\n if (ws.readyState === 1 || ws.readyState === 0) {\n ws.close(1000);\n }\n\n if (context.debug) {\n console.debug('TenxGraphClient [WS]: stream finished');\n }\n }\n}\n","import { RequestContext } from '../request.js';\nimport { buildWsUrl, openWebSocket, WsAuthContext } from '../ws.js';\n\n// ── Output audio sample rate (PCM16 mono @ 24 kHz), mirrors core OUTPUT_SAMPLE_RATE ──\nexport const REALTIME_OUTPUT_SAMPLE_RATE = 24000;\nexport const REALTIME_INPUT_SAMPLE_RATE = 16000;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Wire types (mirror tenxgraph.core.realtime; init keys verified against the\n// server's GraphService._realtime_overrides mapping)\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type ResponseModality = 'AUDIO' | 'TEXT';\n\nexport interface RealtimeVADConfig {\n enabled?: boolean;\n start_sensitivity?: string | null;\n end_sensitivity?: string | null;\n prefix_padding_ms?: number | null;\n silence_duration_ms?: number | null;\n}\n\nexport interface RealtimeInit {\n /**\n * e.g. \"gemini-2.5-flash-live\". Honoured only when the server lists it in\n * `websocket.realtime_models`; otherwise the agent's own model is used.\n */\n model?: string;\n /** Omit to let the session generate one (used for resume). */\n thread_id?: string;\n voice?: string;\n modalities?: ResponseModality | ResponseModality[];\n vad?: RealtimeVADConfig;\n system_prompt?: string;\n /** Can only narrow the agent's own tag filter. */\n tools_tags?: string[];\n /** Forward-compatible passthrough; unknown keys are ignored by the server. */\n [k: string]: unknown;\n}\n\n/** Downstream JSON events. Audio arrives separately as binary via the `audio` channel. */\nexport type RealtimeEvent =\n | { type: 'input_transcript'; text: string; finished: boolean }\n | { type: 'output_transcript'; text: string; finished: boolean }\n | { type: 'tool_call'; id: string; name: string; args: Record<string, unknown> }\n | { type: 'tool_result'; id: string; result: unknown }\n | { type: 'turn_complete' }\n | { type: 'interrupted' }\n | { type: 'session_update'; resumption_handle?: string | null }\n | { type: 'go_away'; time_left?: string | null }\n | { type: 'agent_changed'; author: string }\n | { type: 'error'; code?: string | null; message: string; fatal: boolean };\n\nexport type RealtimeEventType = RealtimeEvent['type'];\n\nexport interface RealtimeReconnectOptions {\n enabled?: boolean;\n baseDelay?: number;\n maxDelay?: number;\n maxAttempts?: number;\n}\n\nexport interface RealtimeOptions {\n reconnect?: RealtimeReconnectOptions;\n // Convenience handlers (sugar over `.on(...)`).\n onAudio?: (pcm16: Uint8Array, sampleRate: number) => void;\n onEvent?: (e: RealtimeEvent) => void;\n onError?: (e: Extract<RealtimeEvent, { type: 'error' }>) => void;\n}\n\nexport type RealtimeContext = RequestContext & WsAuthContext;\n\n// ── Lifecycle/event channels the emitter understands ─────────────────────────\ntype ChannelMap = {\n audio: (pcm16: Uint8Array, sampleRate: number) => void;\n event: (e: RealtimeEvent) => void;\n open: () => void;\n close: (code: number) => void;\n reconnecting: (attempt: number) => void;\n reconnected: () => void;\n} & {\n [K in RealtimeEventType]: (e: Extract<RealtimeEvent, { type: K }>) => void;\n};\n\ntype ChannelName = keyof ChannelMap;\n\n// The erased listener shape used for internal storage. Public `on`/`off` stay\n// fully typed via ChannelMap[K]; this only avoids the unsafe `Function` type.\ntype ChannelListener = (...args: never[]) => void;\n\nfunction genThreadId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n // Fallback: timestamp-free, index-free pseudo-id is not required here because a\n // dropped session reuses this same id; uniqueness across sessions is enough.\n return 'rt-' + Math.abs(hashString(String(Date.now()))).toString(36);\n}\n\nfunction hashString(s: string): number {\n let h = 0;\n for (let i = 0; i < s.length; i++) {\n h = (h << 5) - h + s.charCodeAt(i);\n h |= 0;\n }\n return h;\n}\n\n/** Normalize an incoming binary frame (ArrayBuffer / typed array / Buffer) to Uint8Array. */\nfunction toUint8(data: unknown): Uint8Array | null {\n if (data instanceof ArrayBuffer) {\n return new Uint8Array(data);\n }\n if (ArrayBuffer.isView(data)) {\n const view = data as ArrayBufferView;\n return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n }\n return null;\n}\n\n/**\n * A transport-only realtime audio session over `/v1/graph/live`.\n *\n * Send PCM16 input via `sendAudio`; receive PCM16 output via `.on('audio', ...)`.\n * All non-audio events arrive via `.on('event', ...)` and per-type channels.\n * Mic capture and audio playback are the caller's responsibility.\n */\nexport class RealtimeSession {\n readonly threadId: string;\n resumptionHandle: string | null = null;\n ready: Promise<void>;\n\n private ctx: RealtimeContext;\n private init: RealtimeInit;\n private ws: WebSocket | null = null;\n private listeners: Partial<Record<ChannelName, ChannelListener[]>> = {};\n private resolveReady!: () => void;\n private rejectReady!: (err: Error) => void;\n private readyResolved = false;\n private closedByUser = false;\n private fatal = false;\n private reconnectAttempts = 0;\n private readonly reconnectCfg: Required<RealtimeReconnectOptions>;\n\n constructor(ctx: RealtimeContext, init: RealtimeInit, options?: RealtimeOptions) {\n this.ctx = ctx;\n this.threadId = init.thread_id ?? genThreadId();\n this.init = { ...init, thread_id: this.threadId };\n\n this.reconnectCfg = {\n enabled: options?.reconnect?.enabled ?? true,\n baseDelay: options?.reconnect?.baseDelay ?? 0.5,\n maxDelay: options?.reconnect?.maxDelay ?? 10,\n maxAttempts: options?.reconnect?.maxAttempts ?? 5,\n };\n\n if (options?.onAudio) this.on('audio', options.onAudio);\n if (options?.onEvent) this.on('event', options.onEvent);\n if (options?.onError) this.on('error', options.onError as ChannelMap['error']);\n\n this.ready = new Promise<void>((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n\n this.connect();\n }\n\n // ── Public send API ─────────────────────────────────────────────────────────\n sendAudio(pcm16: Uint8Array | ArrayBuffer): void {\n this.ws?.send(pcm16 as ArrayBuffer);\n }\n sendText(text: string): void {\n this.sendControl({ type: 'text', text });\n }\n activityStart(): void {\n this.sendControl({ type: 'activity_start' });\n }\n activityEnd(): void {\n this.sendControl({ type: 'activity_end' });\n }\n close(): void {\n this.closedByUser = true;\n this.sendControl({ type: 'close' });\n const ws = this.ws;\n if (ws && (ws.readyState === 0 || ws.readyState === 1)) {\n ws.close(1000);\n }\n }\n\n // ── Subscription API ─────────────────────────────────────────────────────────\n on<K extends ChannelName>(event: K, listener: ChannelMap[K]): this {\n if (!this.listeners[event]) this.listeners[event] = [];\n (this.listeners[event] as ChannelListener[]).push(listener as ChannelListener);\n return this;\n }\n off<K extends ChannelName>(event: K, listener: ChannelMap[K]): this {\n this.listeners[event] = (this.listeners[event] ?? []).filter((f) => f !== listener);\n return this;\n }\n\n // ── Internals ────────────────────────────────────────────────────────────────\n private emit<K extends ChannelName>(event: K, ...args: Parameters<ChannelMap[K]>): void {\n (this.listeners[event] ?? []).forEach((f) => {\n try {\n (f as (...a: unknown[]) => void)(...args);\n } catch (err) {\n if (this.ctx.debug) console.warn('TenxGraphClient [realtime]: listener threw', err);\n }\n });\n }\n\n private sendControl(frame: Record<string, unknown>): void {\n this.ws?.send(JSON.stringify(frame));\n }\n\n private connect(): void {\n const url = buildWsUrl(this.ctx, '/v1/graph/live');\n if (this.ctx.debug) console.debug('TenxGraphClient [realtime]: connecting to', url);\n\n const ws = openWebSocket(url, this.ctx);\n try {\n // Receive audio as ArrayBuffer rather than Blob (browser default is \"blob\").\n (ws as { binaryType?: string }).binaryType = 'arraybuffer';\n } catch {\n /* some impls disallow setting before open; ignore */\n }\n this.ws = ws;\n\n ws.addEventListener('open', () => {\n if (this.ws !== ws) return; // stale socket from a previous connection; ignore\n this.sendControl(this.init);\n if (!this.readyResolved) {\n this.readyResolved = true;\n this.resolveReady();\n }\n this.emit('open');\n });\n\n ws.addEventListener('message', (event: MessageEvent) => {\n if (this.ws !== ws) return; // stale socket from a previous connection; ignore\n this.handleMessage(event.data);\n });\n\n ws.addEventListener('close', (event: CloseEvent) => {\n if (this.ws !== ws) return; // stale socket from a previous connection; ignore\n const code = event?.code ?? 1000;\n this.emit('close', code);\n this.maybeReconnect();\n });\n\n ws.addEventListener('error', () => {\n if (this.ws !== ws) return; // stale socket from a previous connection; ignore\n if (!this.readyResolved) {\n this.readyResolved = true;\n this.rejectReady(new Error('Realtime WebSocket connection failed'));\n }\n });\n }\n\n private handleMessage(data: unknown): void {\n const audio = toUint8(data);\n if (audio) {\n this.emit('audio', audio, REALTIME_OUTPUT_SAMPLE_RATE);\n return;\n }\n if (typeof data !== 'string') return;\n let parsed: RealtimeEvent;\n try {\n parsed = JSON.parse(data) as RealtimeEvent;\n } catch {\n if (this.ctx.debug) console.warn('TenxGraphClient [realtime]: bad JSON frame', data);\n return;\n }\n if (parsed.type === 'session_update') {\n this.resumptionHandle = parsed.resumption_handle ?? this.resumptionHandle;\n }\n if (parsed.type === 'error' && parsed.fatal) {\n this.fatal = true;\n }\n this.emit('event', parsed);\n // Per-type channel. Cast is safe: the discriminant matches the channel name.\n this.emit(parsed.type as ChannelName, parsed as never);\n }\n\n private maybeReconnect(): void {\n if (this.closedByUser || this.fatal || !this.reconnectCfg.enabled) {\n return;\n }\n if (this.reconnectAttempts >= this.reconnectCfg.maxAttempts) {\n // Latch fatal so a duplicate close on the final socket can't re-emit the failure.\n this.fatal = true;\n const failure = {\n type: 'error' as const,\n code: 'reconnect_failed',\n message: `Realtime reconnect gave up after ${this.reconnectCfg.maxAttempts} attempt(s)`,\n fatal: true,\n };\n this.emit('error', failure);\n this.emit('event', failure);\n return;\n }\n this.reconnectAttempts += 1;\n const attempt = this.reconnectAttempts;\n const delayMs =\n Math.min(this.reconnectCfg.baseDelay * 2 ** (attempt - 1), this.reconnectCfg.maxDelay) * 1000;\n this.emit('reconnecting', attempt);\n setTimeout(() => this.reconnect(), delayMs);\n }\n\n private reconnect(): void {\n // Forward the latest resumption handle so the provider can resume server-side.\n this.init = {\n ...this.init,\n thread_id: this.threadId,\n ...(this.resumptionHandle ? { resumption_handle: this.resumptionHandle } : {}),\n };\n const onceOpen = () => {\n this.reconnectAttempts = 0;\n this.emit('reconnected');\n };\n this.connect();\n this.ws?.addEventListener('open', onceOpen, { once: true } as AddEventListenerOptions);\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface StoreMemoryContext extends RequestContext {}\n\n/**\n * Types of memories that can be stored\n */\nexport enum MemoryType {\n EPISODIC = 'episodic', // Conversation memories\n SEMANTIC = 'semantic', // Facts and knowledge\n PROCEDURAL = 'procedural', // How-to knowledge\n ENTITY = 'entity', // Entity-based memories\n RELATIONSHIP = 'relationship', // Entity relationships\n CUSTOM = 'custom', // Custom memory types\n DECLARATIVE = 'declarative', // Explicit facts and events\n}\n\nexport interface StoreMemoryRequest {\n config?: Record<string, any>;\n options?: Record<string, any>;\n content: string;\n memory_type: MemoryType;\n category: string;\n metadata?: Record<string, any>;\n}\n\nexport interface StoreMemoryData {\n memory_id: string;\n}\n\nexport interface StoreMemoryResponse {\n data: StoreMemoryData;\n metadata: ResponseMetadata;\n}\n\nexport async function storeMemory(\n context: StoreMemoryContext,\n request: StoreMemoryRequest\n): Promise<StoreMemoryResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Storing memory with type', request.memory_type);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const url = `${context.baseUrl}/v1/store/memories`;\n\n // Prepare request body\n const body = {\n config: request.config || {},\n options: request.options || {},\n content: request.content,\n memory_type: request.memory_type,\n category: request.category,\n metadata: request.metadata || {},\n };\n\n const response = await fetch(url, {\n method: 'POST',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Store memory failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Store memory request failed',\n '/v1/memory',\n 'POST'\n );\n throw error;\n }\n\n const data: StoreMemoryResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Memory stored successfully', data);\n }\n\n return data;\n } catch (error) {\n if (context.debug) {\n console.debug('TenxGraphClient: Store memory failed:', error);\n }\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\nimport { MemoryType } from './storeMemory.js';\n\nexport interface SearchMemoryContext extends RequestContext {}\n\n/**\n * Memory retrieval strategies\n */\nexport enum RetrievalStrategy {\n SIMILARITY = 'similarity', // Vector similarity search\n TEMPORAL = 'temporal', // Time-based retrieval\n RELEVANCE = 'relevance', // Relevance scoring\n HYBRID = 'hybrid', // Combined approaches\n GRAPH_TRAVERSAL = 'graph_traversal', // Knowledge graph navigation\n}\n\n/**\n * Supported distance metrics for vector similarity\n */\nexport enum DistanceMetric {\n COSINE = 'cosine',\n EUCLIDEAN = 'euclidean',\n DOT_PRODUCT = 'dot_product',\n MANHATTAN = 'manhattan',\n}\n\nexport interface SearchMemoryRequest {\n config?: Record<string, any>;\n options?: Record<string, any>;\n query: string;\n memory_type?: MemoryType;\n category?: string;\n limit?: number;\n score_threshold?: number;\n filters?: Record<string, any>;\n retrieval_strategy?: RetrievalStrategy;\n distance_metric?: DistanceMetric;\n max_tokens?: number;\n}\n\nexport interface MemoryResult {\n id: string;\n content: string;\n score: number;\n memory_type: string;\n metadata: Record<string, any>;\n vector: number[];\n user_id: string;\n thread_id: string;\n timestamp: string;\n}\n\nexport interface SearchMemoryData {\n results: MemoryResult[];\n}\n\nexport interface SearchMemoryResponse {\n data: SearchMemoryData;\n metadata: ResponseMetadata;\n}\n\nexport async function searchMemory(\n context: SearchMemoryContext,\n request: SearchMemoryRequest\n): Promise<SearchMemoryResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Searching memories with query:', request.query);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const url = `${context.baseUrl}/v1/store/search`;\n\n // Prepare request body with defaults\n const body = {\n config: request.config || {},\n options: request.options || {},\n query: request.query,\n memory_type: request.memory_type || MemoryType.EPISODIC,\n category: request.category || '',\n limit: request.limit !== undefined ? request.limit : 10,\n score_threshold: request.score_threshold !== undefined ? request.score_threshold : 0,\n filters: request.filters || {},\n retrieval_strategy: request.retrieval_strategy || RetrievalStrategy.SIMILARITY,\n distance_metric: request.distance_metric || DistanceMetric.COSINE,\n max_tokens: request.max_tokens !== undefined ? request.max_tokens : 4000,\n };\n\n const response = await fetch(url, {\n method: 'POST',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Search memory failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Search memory request failed',\n '/v1/memory/search',\n 'POST'\n );\n throw error;\n }\n\n const data: SearchMemoryResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Memory search successful', {\n query: request.query,\n results_count: data.data.results.length,\n });\n }\n\n return data;\n } catch (error) {\n if (context.debug) {\n console.debug('TenxGraphClient: Search memory failed:', error);\n }\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\nimport { MemoryResult } from './searchMemory.js';\n\nexport interface GetMemoryContext extends RequestContext {}\n\nexport interface GetMemoryRequest {\n memoryId: string;\n config?: Record<string, any>;\n options?: Record<string, any>;\n}\n\nexport interface GetMemoryData {\n memory: MemoryResult;\n}\n\nexport interface GetMemoryResponse {\n data: GetMemoryData;\n metadata: ResponseMetadata;\n}\n\nexport async function getMemory(\n context: GetMemoryContext,\n request: GetMemoryRequest\n): Promise<GetMemoryResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Fetching memory with ID:', request.memoryId);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const url = `${context.baseUrl}/v1/store/memories/${request.memoryId}`;\n\n // Prepare request body\n const body = {\n config: request.config || {},\n options: request.options || {},\n };\n\n const response = await fetch(url, {\n method: 'POST',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Get memory failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Get memory request failed',\n '/v1/memory/{memory_id}',\n 'GET'\n );\n throw error;\n }\n\n const data: GetMemoryResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Memory fetched successfully', {\n memory_id: request.memoryId,\n content: data.data.memory.content.substring(0, 50),\n });\n }\n\n return data;\n } catch (error) {\n if (context.debug) {\n console.debug('TenxGraphClient: Get memory failed:', error);\n }\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface UpdateMemoryContext extends RequestContext {}\n\nexport interface UpdateMemoryRequest {\n memoryId: string;\n config?: Record<string, any>;\n options?: Record<string, any>;\n content: string;\n metadata?: Record<string, any>;\n}\n\nexport interface UpdateMemoryData {\n success: boolean;\n data: Record<string, any>;\n}\n\nexport interface UpdateMemoryResponse {\n data: UpdateMemoryData;\n metadata: ResponseMetadata;\n}\n\nexport async function updateMemory(\n context: UpdateMemoryContext,\n request: UpdateMemoryRequest\n): Promise<UpdateMemoryResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Updating memory with ID:', request.memoryId);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const url = `${context.baseUrl}/v1/store/memories/${request.memoryId}`;\n\n // Prepare request body\n const body = {\n config: request.config || {},\n options: request.options || {},\n content: request.content,\n metadata: request.metadata || {},\n };\n\n if (context.debug) {\n console.debug('TenxGraphClient: Request payload:', JSON.stringify(body, null, 2));\n }\n\n const response = await fetch(url, {\n method: 'PUT',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Update memory failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Update memory request failed',\n '/v1/memory/{memory_id}',\n 'PUT'\n );\n throw error;\n }\n\n const data: UpdateMemoryResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Memory updated successfully', {\n memory_id: request.memoryId,\n success: data.data.success,\n });\n }\n\n return data;\n } catch (error) {\n if (context.debug) {\n console.debug('TenxGraphClient: Update memory failed:', error);\n }\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface DeleteMemoryContext extends RequestContext {}\n\nexport interface DeleteMemoryRequest {\n memoryId: string;\n config?: Record<string, any>;\n options?: Record<string, any>;\n}\n\nexport interface DeleteMemoryData {\n success: boolean;\n data: string;\n}\n\nexport interface DeleteMemoryResponse {\n data: DeleteMemoryData;\n metadata: ResponseMetadata;\n}\n\nexport async function deleteMemory(\n context: DeleteMemoryContext,\n request: DeleteMemoryRequest\n): Promise<DeleteMemoryResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Deleting memory with ID:', request.memoryId);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const url = `${context.baseUrl}/v1/store/memories/${request.memoryId}`;\n\n // Prepare request body\n const body = {\n config: request.config || {},\n options: request.options || {},\n };\n\n if (context.debug) {\n console.debug('TenxGraphClient: Delete request payload:', JSON.stringify(body, null, 2));\n }\n\n const response = await fetch(url, {\n method: 'DELETE',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Delete memory failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Delete memory request failed',\n '/v1/memory/{memory_id}',\n 'DELETE'\n );\n throw error;\n }\n\n const data: DeleteMemoryResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Memory deleted successfully', {\n memory_id: request.memoryId,\n success: data.data.success,\n });\n }\n\n return data;\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: Delete memory timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n if (context.debug) {\n console.debug('TenxGraphClient: Delete memory failed:', error);\n }\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\nimport { MemoryResult } from './searchMemory.js';\n\nexport interface ListMemoriesContext extends RequestContext {}\n\nexport interface ListMemoriesRequest {\n config?: Record<string, any>;\n options?: Record<string, any>;\n limit?: number;\n}\n\nexport interface ListMemoriesData {\n memories: MemoryResult[];\n}\n\nexport interface ListMemoriesResponse {\n data: ListMemoriesData;\n metadata: ResponseMetadata;\n}\n\nexport async function listMemories(\n context: ListMemoriesContext,\n request: ListMemoriesRequest\n): Promise<ListMemoriesResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Fetching list of memories', {\n limit: request.limit,\n });\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const url = `${context.baseUrl}/v1/store/memories/list`;\n\n // Prepare request body\n const body = {\n config: request.config || {},\n options: request.options || {},\n limit: request.limit || 100,\n };\n\n if (context.debug) {\n console.debug(\n 'TenxGraphClient: List memories request payload:',\n JSON.stringify(body, null, 2)\n );\n }\n\n const response = await fetch(url, {\n method: 'POST',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: List memories failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'List memories request failed',\n '/v1/memory',\n 'GET'\n );\n throw error;\n }\n\n const data: ListMemoriesResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Memories list fetched successfully', {\n count: data.data.memories.length,\n limit: request.limit,\n });\n }\n\n return data;\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: List memories timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n if (context.debug) {\n console.debug('TenxGraphClient: List memories failed:', error);\n }\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { MemoryType } from './storeMemory.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface ForgetMemoriesContext extends RequestContext {}\n\nexport interface ForgetMemoriesRequest {\n config?: Record<string, any>;\n options?: Record<string, any>;\n memory_type?: MemoryType;\n category?: string;\n filters?: Record<string, any>;\n}\n\nexport interface ForgetMemoriesData {\n success: boolean;\n data: Record<string, any>;\n}\n\nexport interface ForgetMemoriesResponse {\n data: ForgetMemoriesData;\n metadata: ResponseMetadata;\n}\n\nexport async function forgetMemories(\n context: ForgetMemoriesContext,\n request: ForgetMemoriesRequest\n): Promise<ForgetMemoriesResponse> {\n try {\n const url = `${context.baseUrl}/v1/store/memories/forget`;\n\n // Prepare request body - only include optional fields if provided\n const body: Record<string, any> = {};\n\n if (request.config) {\n body.config = request.config;\n }\n if (request.options) {\n body.options = request.options;\n }\n if (request.memory_type) {\n body.memory_type = request.memory_type;\n }\n if (request.category) {\n body.category = request.category;\n }\n if (request.filters) {\n body.filters = request.filters;\n }\n\n if (context.debug) {\n console.log('[DEBUG] Forget memories request:', body);\n }\n\n const controller = new AbortController();\n // `ReturnType<typeof setTimeout>` rather than NodeJS.Timeout: this client runs in\n // browsers too, and the NodeJS namespace would force consumers to install @types/node.\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n if (context.timeout > 0) {\n timeoutId = setTimeout(() => controller.abort(), context.timeout);\n }\n\n const response = await fetch(url, {\n method: 'POST',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n body: JSON.stringify(body),\n ...(context.timeout > 0 && { signal: controller.signal }),\n });\n\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n if (!response.ok) {\n throw new Error(`Forget memories failed: ${response.status} ${response.statusText}`);\n }\n\n const data: ForgetMemoriesResponse = await response.json();\n\n if (context.debug) {\n console.log('[DEBUG] Forget memories response:', data);\n }\n\n return data;\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n throw error;\n }\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface StopGraphContext extends RequestContext {}\n\nexport interface StopGraphRequest {\n thread_id: string;\n config?: Record<string, any>;\n}\n\nexport interface StopGraphResponse {\n data: {\n success: boolean;\n message: string;\n thread_id: string;\n stopped_at?: string;\n };\n metadata: ResponseMetadata;\n}\n\n/**\n * Stop a running graph execution for a specific thread\n *\n * @param context - Request context with baseUrl, auth, timeout\n * @param request - Stop request with thread_id and optional config\n * @returns Promise<StopGraphResponse> with stop operation result\n */\nexport async function stopGraph(\n context: StopGraphContext,\n request: StopGraphRequest\n): Promise<StopGraphResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Stopping graph execution for thread:', request.thread_id);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const response = await fetch(`${context.baseUrl}/v1/graph/stop`, {\n method: 'POST',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n body: JSON.stringify(request),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Stop graph failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Stop graph execution failed',\n '/v1/graph/stop',\n 'POST'\n );\n throw error;\n }\n\n const data: StopGraphResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Graph execution stopped successfully', data);\n }\n\n return data;\n } catch (error) {\n if (context.debug) {\n console.debug('TenxGraphClient: Stop graph failed:', error);\n }\n\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: Stop graph timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n\n console.error('TenxGraphClient: Stop graph failed:', error);\n throw error;\n }\n}\n","import { ResponseMetadata } from './metadata.js';\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\nexport interface FixGraphContext extends RequestContext {}\n\nexport interface FixGraphRequest {\n thread_id: string;\n config?: Record<string, any>;\n}\n\nexport interface FixGraphResponse {\n data: {\n success: boolean;\n message: string;\n removed_count: number;\n state?: Record<string, any>;\n };\n metadata: ResponseMetadata;\n}\n\n/**\n * Fix graph state by removing messages with empty tool calls\n *\n * This is useful for cleaning up incomplete tool call messages that may have\n * failed or been interrupted during execution.\n *\n * @param context - Request context with baseUrl, auth, timeout\n * @param request - Fix request with thread_id and optional config\n * @returns Promise<FixGraphResponse> with fix operation result\n */\nexport async function fixGraph(\n context: FixGraphContext,\n request: FixGraphRequest\n): Promise<FixGraphResponse> {\n try {\n if (context.debug) {\n console.debug('TenxGraphClient: Fixing graph state for thread:', request.thread_id);\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), context.timeout);\n\n const response = await fetch(`${context.baseUrl}/v1/graph/fix`, {\n method: 'POST',\n headers: buildHeaders(context as RequestContext, {\n 'Content-Type': 'application/json',\n accept: 'application/json',\n }),\n ...getRequestCredentials(context as RequestContext),\n body: JSON.stringify(request),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`TenxGraphClient: Fix graph failed with HTTP ${response.status}`);\n const error = await createErrorFromResponse(\n response,\n 'Fix graph state failed',\n '/v1/graph/fix',\n 'POST'\n );\n throw error;\n }\n\n const data: FixGraphResponse = await response.json();\n\n if (context.debug) {\n console.info('TenxGraphClient: Graph state fixed successfully', {\n removed_count: data.data.removed_count,\n success: data.data.success,\n });\n }\n\n return data;\n } catch (error) {\n if (context.debug) {\n console.debug('TenxGraphClient: Fix graph failed:', error);\n }\n\n if ((error as Error).name === 'AbortError') {\n console.warn(`TenxGraphClient: Fix graph timeout after ${context.timeout}ms`);\n throw new Error(`Request timeout after ${context.timeout}ms`);\n }\n\n console.error('TenxGraphClient: Fix graph failed:', error);\n throw error;\n }\n}\n","/**\n * File upload and retrieval endpoints for multimodal messages.\n */\n\nimport { createErrorFromResponse } from '../errors.js';\nimport { buildHeaders, getRequestCredentials, RequestContext } from '../request.js';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\nexport interface FileUploadContext extends RequestContext {}\n\nexport interface FileUploadResponse {\n data: {\n file_id: string;\n mime_type: string;\n size_bytes: number;\n filename: string;\n extracted_text: string | null;\n url: string;\n direct_url?: string | null;\n direct_url_expires_at?: number | null;\n };\n metadata?: {\n request_id: string;\n timestamp: string;\n message: string;\n };\n}\n\nexport interface FileInfoResponse {\n data: {\n file_id: string;\n mime_type: string;\n size_bytes: number;\n filename?: string | null;\n extracted_text: string | null;\n direct_url?: string | null;\n direct_url_expires_at?: number | null;\n };\n metadata?: {\n request_id: string;\n timestamp: string;\n message: string;\n };\n}\n\nexport interface FileAccessUrlResponse {\n data: {\n file_id: string;\n url: string;\n expires_at?: number | null;\n mime_type: string;\n };\n metadata?: {\n request_id: string;\n timestamp: string;\n message: string;\n };\n}\n\nexport interface MultimodalConfigResponse {\n data: {\n media_storage_type: string;\n media_max_size_mb: number;\n document_handling: string;\n };\n metadata?: {\n request_id: string;\n timestamp: string;\n message: string;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Upload file\n// ---------------------------------------------------------------------------\n/**\n * Upload a file (image, audio, document) to the server.\n *\n * @param ctx - Connection context\n * @param file - A File, Blob, or { data: Blob; filename: string } object\n * @returns FileUploadResponse with file_id and metadata\n */\nexport async function uploadFile(\n ctx: FileUploadContext,\n file: File | Blob | { data: Blob; filename: string }\n): Promise<FileUploadResponse> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), ctx.timeout);\n\n try {\n const formData = new FormData();\n\n // `File` only became a global in Node 20; this package supports Node 18, where a bare\n // `instanceof File` throws ReferenceError. Guard before touching the global.\n if (typeof File !== 'undefined' && file instanceof File) {\n formData.append('file', file, file.name);\n } else if ('data' in file && 'filename' in file) {\n formData.append('file', file.data, file.filename);\n } else {\n formData.append('file', file, 'upload');\n }\n\n const response = await fetch(`${ctx.baseUrl}/v1/files/upload`, {\n method: 'POST',\n headers: buildHeaders(ctx as RequestContext),\n body: formData,\n ...getRequestCredentials(ctx as RequestContext),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const error = await createErrorFromResponse(\n response,\n 'File upload failed',\n '/v1/files/upload',\n 'POST'\n );\n throw error;\n }\n\n return (await response.json()) as FileUploadResponse;\n } finally {\n clearTimeout(timeoutId);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Get file (binary download)\n// ---------------------------------------------------------------------------\n/**\n * Download a file by its file_id. Returns raw Blob.\n */\nexport async function getFile(ctx: FileUploadContext, fileId: string): Promise<Blob> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), ctx.timeout);\n\n try {\n const response = await fetch(`${ctx.baseUrl}/v1/files/${encodeURIComponent(fileId)}`, {\n method: 'GET',\n headers: buildHeaders(ctx as RequestContext),\n ...getRequestCredentials(ctx as RequestContext),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const error = await createErrorFromResponse(\n response,\n 'File download failed',\n `/v1/files/${fileId}`,\n 'GET'\n );\n throw error;\n }\n\n return await response.blob();\n } finally {\n clearTimeout(timeoutId);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Get file info (metadata)\n// ---------------------------------------------------------------------------\nexport async function getFileInfo(\n ctx: FileUploadContext,\n fileId: string\n): Promise<FileInfoResponse> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), ctx.timeout);\n\n try {\n const response = await fetch(`${ctx.baseUrl}/v1/files/${encodeURIComponent(fileId)}/info`, {\n method: 'GET',\n headers: buildHeaders(ctx as RequestContext),\n ...getRequestCredentials(ctx as RequestContext),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const error = await createErrorFromResponse(\n response,\n 'File info request failed',\n `/v1/files/${fileId}/info`,\n 'GET'\n );\n throw error;\n }\n\n return (await response.json()) as FileInfoResponse;\n } finally {\n clearTimeout(timeoutId);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Get file access URL\n// ---------------------------------------------------------------------------\nexport async function getFileAccessUrl(\n ctx: FileUploadContext,\n fileId: string\n): Promise<FileAccessUrlResponse> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), ctx.timeout);\n\n try {\n const response = await fetch(`${ctx.baseUrl}/v1/files/${encodeURIComponent(fileId)}/url`, {\n method: 'GET',\n headers: buildHeaders(ctx as RequestContext),\n ...getRequestCredentials(ctx as RequestContext),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const error = await createErrorFromResponse(\n response,\n 'File access URL request failed',\n `/v1/files/${fileId}/url`,\n 'GET'\n );\n throw error;\n }\n\n return (await response.json()) as FileAccessUrlResponse;\n } finally {\n clearTimeout(timeoutId);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Get multimodal config\n// ---------------------------------------------------------------------------\nexport async function getMultimodalConfig(\n ctx: FileUploadContext\n): Promise<MultimodalConfigResponse> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), ctx.timeout);\n\n try {\n const response = await fetch(`${ctx.baseUrl}/v1/config/multimodal`, {\n method: 'GET',\n headers: buildHeaders(ctx as RequestContext, {\n accept: 'application/json',\n }),\n ...getRequestCredentials(ctx as RequestContext),\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n const error = await createErrorFromResponse(\n response,\n 'Multimodal config request failed',\n '/v1/config/multimodal',\n 'GET'\n );\n throw error;\n }\n\n return (await response.json()) as MultimodalConfigResponse;\n } finally {\n clearTimeout(timeoutId);\n }\n}\n","import { ToolHandler, ToolRegistration, ToolExecutor } from './tools.js';\nimport { Message } from './message.js';\nimport { ping, PingContext, PingResponse } from './endpoints/ping.js';\nimport { graph, GraphContext, GraphResponse } from './endpoints/graph.js';\nimport { graphTools, GraphToolsContext, GraphToolsResponse } from './endpoints/graphTools.js';\nimport {\n observability,\n ObservabilityContext,\n ObservabilityResponse,\n} from './endpoints/observability.js';\nimport { stateSchema, StateSchemaContext, StateSchemaResponse } from './endpoints/stateSchema.js';\nimport { threadState, ThreadStateContext, ThreadStateResponse } from './endpoints/threadState.js';\nimport {\n updateThreadState,\n UpdateThreadStateContext,\n UpdateThreadStateRequest,\n UpdateThreadStateResponse,\n} from './endpoints/updateThreadState.js';\nimport {\n clearThreadState,\n ClearThreadStateContext,\n ClearThreadStateResponse,\n} from './endpoints/clearThreadState.js';\nimport {\n threadMessages,\n ThreadMessagesContext,\n ThreadMessagesRequest,\n ThreadMessagesResponse,\n} from './endpoints/threadMessages.js';\nimport {\n addThreadMessages,\n AddThreadMessagesContext,\n AddThreadMessagesRequest,\n AddThreadMessagesResponse,\n} from './endpoints/addThreadMessages.js';\nimport {\n threadMessage,\n ThreadMessageContext,\n ThreadMessageRequest,\n ThreadMessageResponse,\n} from './endpoints/threadMessage.js';\nimport {\n threadDetails,\n ThreadDetailsContext,\n ThreadDetailsResponse,\n} from './endpoints/threadDetails.js';\nimport {\n deleteThreadMessage,\n DeleteThreadMessageContext,\n DeleteThreadMessageRequest,\n DeleteThreadMessageResponse,\n} from './endpoints/deleteThreadMessage.js';\nimport {\n deleteThread,\n DeleteThreadContext,\n DeleteThreadRequest,\n DeleteThreadResponse,\n} from './endpoints/deleteThread.js';\nimport { threads, ThreadsContext, ThreadsRequest, ThreadsResponse } from './endpoints/threads.js';\nimport {\n invoke as invokeEndpoint,\n InvokeContext,\n InvokeRequest,\n InvokeResult,\n InvokeCallback,\n} from './endpoints/invoke.js';\nimport {\n streamInvoke as streamInvokeEndpoint,\n StreamContext,\n StreamRequest,\n StreamChunk,\n} from './endpoints/stream.js';\nimport { wsStreamInvoke, WsStreamContext } from './endpoints/wsStream.js';\nimport {\n RealtimeSession,\n RealtimeInit,\n RealtimeOptions,\n RealtimeContext,\n} from './endpoints/realtime.js';\nimport type { WebSocketImpl } from './ws.js';\nimport {\n storeMemory as storeMemoryEndpoint,\n StoreMemoryContext,\n StoreMemoryRequest,\n StoreMemoryResponse,\n} from './endpoints/storeMemory.js';\nimport {\n searchMemory as searchMemoryEndpoint,\n SearchMemoryContext,\n SearchMemoryRequest,\n SearchMemoryResponse,\n} from './endpoints/searchMemory.js';\nimport {\n getMemory as getMemoryEndpoint,\n GetMemoryContext,\n GetMemoryRequest,\n GetMemoryResponse,\n} from './endpoints/getMemory.js';\nimport {\n updateMemory as updateMemoryEndpoint,\n UpdateMemoryContext,\n UpdateMemoryRequest,\n UpdateMemoryResponse,\n} from './endpoints/updateMemory.js';\nimport {\n deleteMemory as deleteMemoryEndpoint,\n DeleteMemoryContext,\n DeleteMemoryRequest,\n DeleteMemoryResponse,\n} from './endpoints/deleteMemory.js';\nimport {\n listMemories as listMemoriesEndpoint,\n ListMemoriesContext,\n ListMemoriesRequest,\n ListMemoriesResponse,\n} from './endpoints/listMemories.js';\nimport {\n forgetMemories as forgetMemoriesEndpoint,\n ForgetMemoriesContext,\n ForgetMemoriesRequest,\n ForgetMemoriesResponse,\n} from './endpoints/forgetMemories.js';\nimport {\n stopGraph as stopGraphEndpoint,\n StopGraphContext,\n StopGraphRequest,\n StopGraphResponse,\n} from './endpoints/stopGraph.js';\nimport {\n fixGraph as fixGraphEndpoint,\n FixGraphContext,\n FixGraphRequest,\n FixGraphResponse,\n} from './endpoints/fixGraph.js';\nimport {\n uploadFile as uploadFileEndpoint,\n getFile as getFileEndpoint,\n getFileInfo as getFileInfoEndpoint,\n getFileAccessUrl as getFileAccessUrlEndpoint,\n getMultimodalConfig as getMultimodalConfigEndpoint,\n FileUploadContext,\n FileUploadResponse,\n FileAccessUrlResponse,\n FileInfoResponse,\n MultimodalConfigResponse,\n} from './endpoints/files.js';\nimport { TenxGraphAuth, RequestContext } from './request.js';\n\nexport interface TenxGraphConfig {\n baseUrl: string;\n authToken?: string | null;\n auth?: TenxGraphAuth | null;\n headers?: HeadersInit;\n credentials?: RequestCredentials;\n timeout?: number; // default 5min\n debug?: boolean;\n webSocketImpl?: WebSocketImpl;\n}\n\nfunction isThreadsRequest(value?: string | ThreadsRequest): value is ThreadsRequest {\n return typeof value === 'object' && value !== null;\n}\n\nfunction normalizeThreadsRequest(\n value?: string | ThreadsRequest,\n offset?: number,\n limit?: number\n): ThreadsRequest {\n if (isThreadsRequest(value)) {\n return {\n search: value.search,\n offset: value.offset,\n limit: value.limit,\n };\n }\n\n return {\n search: value,\n offset,\n limit,\n };\n}\n\nfunction isThreadMessagesRequest(\n value?: string | Omit<ThreadMessagesRequest, 'threadId'>\n): value is Omit<ThreadMessagesRequest, 'threadId'> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction normalizeThreadMessagesRequest(\n threadId: string | number,\n value?: string | Omit<ThreadMessagesRequest, 'threadId'>,\n offset?: number,\n limit?: number\n): ThreadMessagesRequest {\n if (isThreadMessagesRequest(value)) {\n return {\n threadId,\n search: value.search,\n offset: value.offset,\n limit: value.limit,\n };\n }\n\n return {\n threadId,\n search: value,\n offset,\n limit,\n };\n}\n\nexport class TenxGraphClient {\n private baseUrl: string;\n private authToken?: string | null;\n private auth?: TenxGraphAuth | null;\n private headers?: HeadersInit;\n private credentials?: RequestCredentials;\n private timeout: number;\n private debug: boolean;\n private webSocketImpl?: WebSocketImpl;\n private toolExecutor: ToolExecutor;\n\n constructor(config: TenxGraphConfig) {\n this.baseUrl = config.baseUrl;\n this.authToken = config.authToken;\n this.auth = config.auth;\n this.headers = config.headers;\n this.credentials = config.credentials;\n this.timeout = config.timeout || 300000; // 5 min\n this.debug = config.debug || false;\n this.webSocketImpl = config.webSocketImpl;\n this.toolExecutor = new ToolExecutor([]);\n }\n\n private createContext<T extends RequestContext>(): T {\n return {\n baseUrl: this.baseUrl,\n authToken: this.authToken,\n auth: this.auth,\n headers: this.headers,\n credentials: this.credentials,\n timeout: this.timeout,\n debug: this.debug,\n webSocketImpl: this.webSocketImpl,\n } as T;\n }\n\n /**\n * Register a tool for remote execution\n */\n registerTool(registration: ToolRegistration): void {\n this.toolExecutor.registerTool(registration);\n\n if (this.debug) {\n console.debug(`TenxGraphClient: Registered remote tool handler '${registration.name}'`);\n }\n }\n\n /**\n * Register only the client-side implementation of a remote tool.\n * The trusted schema must be declared in the server's 10xgraph.json.\n */\n registerToolHandler(name: string, handler: ToolHandler): void {\n this.registerTool({ name, handler });\n }\n\n /**\n * Ping the server to check connectivity\n */\n async ping(): Promise<PingResponse> {\n const context = this.createContext<PingContext>();\n\n return ping(context);\n }\n\n /**\n * Fetch the agent graph\n */\n async graph(): Promise<GraphResponse> {\n const context = this.createContext<GraphContext>();\n\n return graph(context);\n }\n\n /**\n * Fetch the tools exposed by the graph's tool nodes, grouped by node.\n * Each tool is tagged with its source (local / mcp / remote).\n */\n async graphTools(): Promise<GraphToolsResponse> {\n const context = this.createContext<GraphToolsContext>();\n\n return graphTools(context);\n }\n\n /**\n * Fetch the reconstructed observability trace (spans, events, cost) for a\n * thread. Returns the latest run by default, or a specific run when given.\n */\n async observability(threadId: string, runId?: string): Promise<ObservabilityResponse> {\n const context = this.createContext<ObservabilityContext>();\n\n return observability(context, threadId, runId);\n }\n\n /**\n * Stop a running graph execution for a specific thread\n * @param threadId - The ID of the thread to stop execution for\n * @param config - Optional configuration for the stop operation\n * @returns StopGraphResponse with the stop operation result\n */\n async stopGraph(threadId: string, config?: Record<string, any>): Promise<StopGraphResponse> {\n const context = this.createContext<StopGraphContext>();\n\n const request: StopGraphRequest = {\n thread_id: threadId,\n config,\n };\n\n return stopGraphEndpoint(context, request);\n }\n\n /**\n * Fix graph state by removing messages with empty tool calls\n * This is useful for cleaning up incomplete tool call messages that may have\n * failed or been interrupted during execution.\n *\n * @param threadId - The ID of the thread to fix state for\n * @param config - Optional configuration for the fix operation\n * @returns FixGraphResponse with the fix operation result including removed_count\n */\n async fixGraph(threadId: string, config?: Record<string, any>): Promise<FixGraphResponse> {\n const context = this.createContext<FixGraphContext>();\n\n const request: FixGraphRequest = {\n thread_id: threadId,\n config,\n };\n\n return fixGraphEndpoint(context, request);\n }\n\n /**\n * \n\n /**\n * Fetch the state schema of the agent\n */\n async graphStateSchema(): Promise<StateSchemaResponse> {\n const context = this.createContext<StateSchemaContext>();\n\n return stateSchema(context);\n }\n\n /**\n * ***************** ALL THREAD APIS *****************\n */\n\n /**\n * Fetch the state of a specific thread\n * @param threadId - The ID of the thread to fetch state for\n * @returns ThreadStateResponse containing the thread's current state\n */\n async threadState(threadId: string | number): Promise<ThreadStateResponse> {\n const context = this.createContext<ThreadStateContext>();\n\n return threadState(context, threadId);\n }\n\n /**\n * Update the state of a specific thread (checkpoint)\n * @param threadId - The ID of the thread to update\n * @param config - Configuration map for the thread\n * @param state - New AgentState for the thread\n * @returns UpdateThreadStateResponse with the updated state\n */\n async updateThreadState(\n threadId: string | number,\n config: Record<string, any>,\n state: any // AgentState\n ): Promise<UpdateThreadStateResponse> {\n const context = this.createContext<UpdateThreadStateContext>();\n\n const request: UpdateThreadStateRequest = {\n config,\n state,\n };\n\n return updateThreadState(context, threadId, request);\n }\n\n /**\n * Clear the state of a specific thread (delete checkpoint)\n * @param threadId - The ID of the thread to clear state for\n * @returns ClearThreadStateResponse with the clear operation result\n */\n async clearThreadState(threadId: string | number): Promise<ClearThreadStateResponse> {\n const context = this.createContext<ClearThreadStateContext>();\n\n return clearThreadState(context, threadId);\n }\n\n /**\n * Fetch details for a specific thread\n * @param threadId - The ID of the thread to fetch\n * @returns ThreadDetailsResponse containing thread details\n */\n async threadDetails(threadId: string | number): Promise<ThreadDetailsResponse> {\n const context = this.createContext<ThreadDetailsContext>();\n\n return threadDetails(context, threadId);\n }\n\n /**\n * Fetch list of threads with optional search and pagination\n * @param search - Optional search term to filter threads\n * @param offset - Optional offset for pagination (default 0)\n * @param limit - Optional limit for pagination (default no limit)\n * @returns ThreadsResponse containing the list of threads and metadata\n */\n async threads(): Promise<ThreadsResponse>;\n async threads(request: ThreadsRequest): Promise<ThreadsResponse>;\n async threads(\n search?: string | ThreadsRequest,\n offset?: number,\n limit?: number\n ): Promise<ThreadsResponse> {\n const context = this.createContext<ThreadsContext>();\n const request = normalizeThreadsRequest(search, offset, limit);\n\n return threads(context, request);\n }\n\n /**\n * Fetch messages from a specific thread with optional search and pagination\n * @param threadId - The ID of the thread to fetch messages from\n * @param search - Optional search term to filter messages\n * @param offset - Optional offset for pagination (default 0)\n * @param limit - Optional limit for pagination (default no limit)\n * @returns ThreadMessagesResponse containing the messages and metadata\n */\n async threadMessages(\n threadId: string | number,\n request: Omit<ThreadMessagesRequest, 'threadId'>\n ): Promise<ThreadMessagesResponse>;\n async threadMessages(\n threadId: string | number,\n search?: string | Omit<ThreadMessagesRequest, 'threadId'>,\n offset?: number,\n limit?: number\n ): Promise<ThreadMessagesResponse> {\n const context = this.createContext<ThreadMessagesContext>();\n const request = normalizeThreadMessagesRequest(threadId, search, offset, limit);\n\n return threadMessages(context, request);\n }\n\n /**\n * Add messages to a specific thread checkpoint\n * @param threadId - The ID of the thread to add messages to\n * @param messages - Array of messages to add to the checkpoint\n * @param config - Configuration map for the checkpoint\n * @param metadata - Optional metadata for the checkpoint\n * @returns AddCheckpointMessagesResponse containing the operation result\n */\n async addThreadMessages(\n threadId: string | number,\n messages: Message[],\n config: Record<string, any> = {},\n metadata?: Record<string, any>\n ): Promise<AddThreadMessagesResponse> {\n const context = this.createContext<AddThreadMessagesContext>();\n\n const request: AddThreadMessagesRequest = {\n threadId,\n config,\n messages,\n metadata,\n };\n\n return addThreadMessages(context, request);\n }\n\n /**\n * Fetch a specific message from a thread by message ID\n * @param threadId - The ID of the thread\n * @param messageId - The ID of the message to fetch\n * @returns ThreadMessageResponse containing the message and metadata\n */\n async singleMessage(\n threadId: string | number,\n messageId: string\n ): Promise<ThreadMessageResponse> {\n const context = this.createContext<ThreadMessageContext>();\n\n const request: ThreadMessageRequest = {\n threadId,\n messageId,\n };\n\n return threadMessage(context, request);\n }\n\n /**\n * Delete a specific message from a thread\n * @param threadId - The ID of the thread\n * @param messageId - The ID of the message to delete\n * @param config - Optional configuration map to send with the request body\n * @returns DeleteThreadMessageResponse containing the deletion result\n */\n async deleteMessage(\n threadId: string | number,\n messageId: string,\n config?: Record<string, any>\n ): Promise<DeleteThreadMessageResponse> {\n const context = this.createContext<DeleteThreadMessageContext>();\n\n const request: DeleteThreadMessageRequest = {\n threadId,\n messageId,\n config,\n };\n\n return deleteThreadMessage(context, request);\n }\n\n /**\n * Delete a specific thread\n * @param threadId - The ID of the thread to delete\n * @param config - Optional configuration map to send with the request body\n * @returns DeleteThreadResponse containing the deletion result\n */\n async deleteThread(\n threadId: string | number,\n config?: Record<string, any>\n ): Promise<DeleteThreadResponse> {\n const context = this.createContext<DeleteThreadContext>();\n\n const request: DeleteThreadRequest = {\n threadId,\n config,\n };\n\n return deleteThread(context, request);\n }\n\n /**\n * Invoke the agent graph with automatic tool execution loop\n * @param messages - Array of messages to send\n * @param options - Invoke options\n * @returns InvokeResult with all messages and intermediate steps\n */\n async invoke(\n messages: Message[],\n options?: {\n initial_state?: Record<string, any>;\n config?: Record<string, any>;\n recursion_limit?: number;\n response_granularity?: 'full' | 'partial' | 'low';\n onPartialResult?: InvokeCallback;\n }\n ): Promise<InvokeResult> {\n const context: InvokeContext = {\n ...this.createContext<InvokeContext>(),\n toolExecutor: this.toolExecutor,\n };\n\n // Prepare request\n const request: InvokeRequest = {\n messages: messages.map((msg) => this.serializeMessage(msg)),\n initial_state: options?.initial_state,\n config: options?.config,\n recursion_limit: options?.recursion_limit || 25,\n response_granularity: options?.response_granularity || 'full',\n };\n\n // Call the invoke endpoint (which handles the recursion loop)\n return invokeEndpoint(context, request, options?.onPartialResult);\n }\n\n /**\n * Stream invoke to the agent graph\n * Returns an async iterable that yields stream chunks as they arrive\n *\n * @param messages - Array of messages to send\n * @param options - Stream options\n * @returns AsyncGenerator of StreamChunk objects\n *\n * @example\n * ```ts\n * const stream = client.streamInvoke([userMessage], {\n * initial_state: {},\n * response_granularity: 'low'\n * });\n *\n * for await (const chunk of stream) {\n * if (chunk.event === 'message') {\n * console.log('Message:', chunk.message?.content);\n * } else if (chunk.event === 'updates') {\n * console.log('State updated:', chunk.state);\n * }\n * }\n * ```\n */\n stream(\n messages: Message[],\n options?: {\n initial_state?: Record<string, any>;\n config?: Record<string, any>;\n recursion_limit?: number;\n response_granularity?: 'full' | 'partial' | 'low';\n }\n ): AsyncGenerator<StreamChunk, void, unknown> {\n const context: StreamContext = {\n ...this.createContext<StreamContext>(),\n toolExecutor: this.toolExecutor,\n };\n\n // Prepare request\n const request: StreamRequest = {\n messages: messages.map((msg) => this.serializeMessage(msg)),\n initial_state: options?.initial_state,\n config: options?.config,\n recursion_limit: options?.recursion_limit || 25,\n response_granularity: options?.response_granularity || 'low',\n };\n\n // Return async generator from the stream endpoint\n return streamInvokeEndpoint(context, request);\n }\n\n /**\n * Stream invoke via a persistent WebSocket connection.\n *\n * Identical API to ``stream()`` — same message types, same chunk format,\n * same tool-execution loop — but uses a single WebSocket instead of one\n * HTTP request per tool-call iteration. Switch from ``stream()`` to\n * ``wsStream()`` by changing one method name; everything else stays the\n * same.\n *\n * The WebSocket stays open for the full lifecycle of the call (fresh run +\n * any resume runs triggered by remote tool calls). The server sends a\n * ``{ event:\"updates\", data:{ status:\"done\" } }`` chunk after each run so\n * the client knows when to send the next resume request.\n *\n * Auth: the bearer token is sent via the ``10xgraph-bearer`` WebSocket\n * subprotocol (browser-safe; never placed in the URL), with the Authorization\n * header also set on Node runtimes.\n *\n * @param messages - Array of messages to send\n * @param options - Same options as ``stream()``\n * @returns AsyncGenerator of StreamChunk objects\n *\n * @example\n * ```ts\n * const stream = client.wsStream([userMessage], {\n * config: { thread_id: 'my-thread' },\n * response_granularity: 'low',\n * });\n *\n * for await (const chunk of stream) {\n * if (chunk.event === 'message') {\n * console.log('Message:', chunk.message?.content);\n * }\n * }\n * ```\n */\n wsStream(\n messages: Message[],\n options?: {\n initial_state?: Record<string, any>;\n config?: Record<string, any>;\n recursion_limit?: number;\n response_granularity?: 'full' | 'partial' | 'low';\n }\n ): AsyncGenerator<StreamChunk, void, unknown> {\n const context: WsStreamContext = {\n ...this.createContext<WsStreamContext>(),\n toolExecutor: this.toolExecutor,\n };\n\n const request: StreamRequest = {\n messages: messages.map((msg) => this.serializeMessage(msg)),\n initial_state: options?.initial_state,\n config: options?.config,\n recursion_limit: options?.recursion_limit ?? 25,\n response_granularity: options?.response_granularity ?? 'low',\n };\n\n return wsStreamInvoke(context, request);\n }\n\n /**\n * Open a realtime (audio-to-audio) session over ``/v1/graph/live``.\n *\n * Transport-only: send PCM16 input via ``session.sendAudio(...)`` and receive\n * PCM16 output via ``session.on('audio', ...)``. Mic capture and audio playback\n * are the caller's responsibility. The session auto-reconnects (with backoff)\n * on an unexpected drop and resumes the same ``thread_id``.\n *\n * @example\n * ```ts\n * const session = client.realtime({ model: 'gemini-2.5-flash-live' });\n * session.on('audio', (pcm) => speaker.write(pcm));\n * session.on('output_transcript', (e) => console.log(e.text));\n * await session.ready;\n * session.sendAudio(micChunk);\n * ```\n */\n realtime(init: RealtimeInit, options?: RealtimeOptions): RealtimeSession {\n const context = this.createContext<RealtimeContext>();\n return new RealtimeSession(context, init, options);\n }\n\n /**\n * Store a memory in the agent's memory system\n *\n * @param request - Memory storage request parameters\n * @returns Promise<StoreMemoryResponse> containing the memory_id\n *\n * @example\n * ```ts\n * const result = await client.storeMemory({\n * content: \"User prefers dark mode\",\n * memory_type: MemoryType.SEMANTIC,\n * category: \"preferences\",\n * metadata: { source: \"user_settings\" }\n * });\n * console.log('Memory stored with ID:', result.data.memory_id);\n * ```\n */\n async storeMemory(request: StoreMemoryRequest): Promise<StoreMemoryResponse> {\n const context = this.createContext<StoreMemoryContext>();\n\n return storeMemoryEndpoint(context, request);\n }\n\n /**\n * Search for memories in the agent's memory system\n *\n * @param request - Memory search request parameters\n * @returns Promise<SearchMemoryResponse> containing matching memories\n *\n * @example\n * ```ts\n * const results = await client.searchMemory({\n * query: \"dark mode preferences\",\n * memory_type: MemoryType.SEMANTIC,\n * limit: 5,\n * retrieval_strategy: RetrievalStrategy.SIMILARITY\n * });\n * results.data.results.forEach(result => {\n * console.log('Memory:', result.content, 'Score:', result.score);\n * });\n * ```\n */\n async searchMemory(request: SearchMemoryRequest): Promise<SearchMemoryResponse> {\n const context = this.createContext<SearchMemoryContext>();\n\n return searchMemoryEndpoint(context, request);\n }\n\n /**\n * Get a specific memory by ID\n *\n * @param memoryId - The ID of the memory to retrieve\n * @param options - Optional config and options\n * @returns Promise<GetMemoryResponse> containing the memory details\n *\n * @example\n * ```ts\n * const memory = await client.getMemory('mem-12345', {\n * config: { include_vector: true }\n * });\n * console.log('Memory:', memory.data.memory.content);\n * console.log('Score:', memory.data.memory.score);\n * ```\n */\n async getMemory(\n memoryId: string,\n options?: { config?: Record<string, any>; options?: Record<string, any> }\n ): Promise<GetMemoryResponse> {\n const context = this.createContext<GetMemoryContext>();\n\n const request: GetMemoryRequest = {\n memoryId,\n config: options?.config,\n options: options?.options,\n };\n\n return getMemoryEndpoint(context, request);\n }\n\n /**\n * Update an existing memory by ID\n *\n * @param memoryId - The ID of the memory to update\n * @param content - The updated content for the memory\n * @param options - Optional config, options, and metadata\n * @returns Promise<UpdateMemoryResponse> containing success status and updated data\n *\n * @example\n * ```ts\n * const result = await client.updateMemory('mem-12345', 'Updated content', {\n * metadata: { tags: ['important', 'updated'] }\n * });\n * console.log('Update success:', result.data.success);\n * ```\n */\n async updateMemory(\n memoryId: string,\n content: string,\n options?: {\n config?: Record<string, any>;\n options?: Record<string, any>;\n metadata?: Record<string, any>;\n }\n ): Promise<UpdateMemoryResponse> {\n const context = this.createContext<UpdateMemoryContext>();\n\n const request: UpdateMemoryRequest = {\n memoryId,\n content,\n config: options?.config,\n options: options?.options,\n metadata: options?.metadata,\n };\n\n return updateMemoryEndpoint(context, request);\n }\n\n /**\n * Delete a memory by ID\n *\n * @param memoryId - The ID of the memory to delete\n * @param options - Optional config and options\n * @returns Promise<DeleteMemoryResponse> containing success status and deletion confirmation\n *\n * @example\n * ```ts\n * const result = await client.deleteMemory('mem-12345', {\n * config: { soft_delete: true }\n * });\n * console.log('Delete success:', result.data.success);\n * console.log('Deleted:', result.data.data);\n * ```\n */\n async deleteMemory(\n memoryId: string,\n options?: { config?: Record<string, any>; options?: Record<string, any> }\n ): Promise<DeleteMemoryResponse> {\n const context = this.createContext<DeleteMemoryContext>();\n\n const request: DeleteMemoryRequest = {\n memoryId,\n config: options?.config,\n options: options?.options,\n };\n\n return deleteMemoryEndpoint(context, request);\n }\n\n /**\n * List all memories with optional pagination\n *\n * @param options - Optional config, options, and limit\n * @returns Promise<ListMemoriesResponse> containing array of memories\n *\n * @example\n * ```ts\n * const result = await client.listMemories({\n * limit: 50,\n * config: { include_vectors: false }\n * });\n * console.log('Found memories:', result.data.memories.length);\n * result.data.memories.forEach(memory => {\n * console.log('Memory:', memory.content, 'Type:', memory.memory_type);\n * });\n * ```\n */\n async listMemories(options?: {\n config?: Record<string, any>;\n options?: Record<string, any>;\n limit?: number;\n }): Promise<ListMemoriesResponse> {\n const context = this.createContext<ListMemoriesContext>();\n\n const request: ListMemoriesRequest = {\n config: options?.config,\n options: options?.options,\n limit: options?.limit,\n };\n\n return listMemoriesEndpoint(context, request);\n }\n\n /**\n * Forget (delete) memories based on filters and criteria\n *\n * @param options - Optional config, options, memory type, category, and filters\n * @returns Promise<ForgetMemoriesResponse> containing success status\n *\n * @example\n * ```ts\n * // Forget all episodic memories in a category\n * const result = await client.forgetMemories({\n * memory_type: MemoryType.EPISODIC,\n * category: 'temporary',\n * filters: { tag: 'delete-me' }\n * });\n * console.log('Forget success:', result.data.success);\n * ```\n */\n async forgetMemories(options?: {\n config?: Record<string, any>;\n options?: Record<string, any>;\n memory_type?: any;\n category?: string;\n filters?: Record<string, any>;\n }): Promise<ForgetMemoriesResponse> {\n const context = this.createContext<ForgetMemoriesContext>();\n\n const request: ForgetMemoriesRequest = {\n config: options?.config,\n options: options?.options,\n memory_type: options?.memory_type,\n category: options?.category,\n filters: options?.filters,\n };\n\n return forgetMemoriesEndpoint(context, request);\n }\n\n // ------------------------------------------------------------------\n // Files / Multimodal API\n // ------------------------------------------------------------------\n\n /**\n * Upload a file (image, audio, document) to the server.\n * Returns file metadata including file_id for use in multimodal messages.\n *\n * @param file - A File, Blob, or { data: Blob; filename: string } object\n * @returns FileUploadResponse with file_id and metadata\n *\n * @example\n * ```ts\n * const result = await client.uploadFile(file);\n * const msg = Message.withImage('Describe this', result.data.url);\n * ```\n */\n async uploadFile(\n file: File | Blob | { data: Blob; filename: string }\n ): Promise<FileUploadResponse> {\n const context = this.createContext<FileUploadContext>();\n return uploadFileEndpoint(context, file);\n }\n\n /**\n * Download a file by its file_id. Returns raw Blob.\n */\n async getFile(fileId: string): Promise<Blob> {\n const context = this.createContext<FileUploadContext>();\n return getFileEndpoint(context, fileId);\n }\n\n /**\n * Get metadata about a stored file.\n */\n async getFileInfo(fileId: string): Promise<FileInfoResponse> {\n const context = this.createContext<FileUploadContext>();\n return getFileInfoEndpoint(context, fileId);\n }\n\n /**\n * Get the best access URL for a stored file.\n * For cloud-backed media this will typically be a signed URL.\n * For local or memory-backed media this may fall back to the API file route.\n */\n async getFileAccessUrl(fileId: string): Promise<FileAccessUrlResponse> {\n const context = this.createContext<FileUploadContext>();\n return getFileAccessUrlEndpoint(context, fileId);\n }\n\n /**\n * Get the current multimodal configuration from the server.\n */\n async getMultimodalConfig(): Promise<MultimodalConfigResponse> {\n const context = this.createContext<FileUploadContext>();\n return getMultimodalConfigEndpoint(context);\n }\n\n /**\n * Serialize a Message object for API transmission\n * Converts Message class instances to plain objects\n */\n private serializeMessage(message: Message): any {\n const serialized: any = {\n role: message.role,\n content: this.cleanContent(message.content),\n };\n\n // message_id: use \"0\" if not set (server will generate one)\n if (message.message_id !== null && message.message_id !== undefined) {\n serialized.message_id = String(message.message_id);\n } else {\n serialized.message_id = '0';\n }\n\n // Only include optional fields if they are explicitly set\n if (message.tools_calls) {\n serialized.tools_calls = message.tools_calls;\n }\n if (message.metadata && Object.keys(message.metadata).length > 0) {\n serialized.metadata = message.metadata;\n }\n\n return serialized;\n }\n\n /**\n * Clean content blocks by removing empty arrays and undefined values\n * Server requires array of content blocks, not simplified string\n */\n private cleanContent(content: any[]): any[] {\n // Always return as array of blocks (server requires this format)\n return content.map((block) => {\n const cleaned: any = {};\n\n for (const [key, value] of Object.entries(block)) {\n // Skip empty arrays\n if (Array.isArray(value) && value.length === 0) {\n continue;\n }\n // Skip undefined values\n if (value === undefined) {\n continue;\n }\n cleaned[key] = value;\n }\n\n return cleaned;\n });\n }\n}\n","import { Message } from './message.js';\n\n// Define ExecutionMeta interface\ninterface ExecutionMeta {\n current_node: string;\n step: number;\n interrupt?: {\n node: string;\n reason: string;\n status: string;\n data?: Record<string, any>;\n };\n is_running: boolean;\n is_interrupted: boolean;\n is_stopped_requested: boolean;\n}\n\n// Define default ExecutionMeta implementation\nclass DefaultExecutionMeta implements ExecutionMeta {\n current_node: string = 'START';\n step: number = 0;\n is_running: boolean = true;\n is_interrupted: boolean = false;\n is_stopped_requested: boolean = false;\n\n interrupt?: {\n node: string;\n reason: string;\n status: string;\n data?: Record<string, any>;\n };\n}\n\n// Define AgentState class\nexport class AgentState {\n context: Message[] = [];\n context_summary: string | null = null;\n execution_meta: ExecutionMeta = new DefaultExecutionMeta();\n\n constructor(initialData: Partial<Record<string, any>> = {}) {\n Object.assign(this, initialData);\n }\n}\n","/**\n * Deprecated names from `@10xscale/agentflow-client`, kept so code written against the old\n * package keeps compiling after switching the import to `10xgraph-client`.\n * Each alias is the same class or type as its new name, so `instanceof` checks still work.\n * All of them will be removed in 2.0.\n */\nimport { TenxGraphClient, TenxGraphConfig } from './client.js';\nimport { TenxGraphError } from './errors.js';\nimport {\n TenxGraphAuth,\n TenxGraphBasicAuth,\n TenxGraphBearerAuth,\n TenxGraphHeaderAuth,\n} from './request.js';\n\n/** @deprecated Use `TenxGraphClient`. Removed in 2.0. */\nexport const AgentFlowClient = TenxGraphClient;\n/** @deprecated Use `TenxGraphClient`. Removed in 2.0. */\nexport type AgentFlowClient = TenxGraphClient;\n\n/** @deprecated Use `TenxGraphError`. Removed in 2.0. */\nexport const AgentFlowError = TenxGraphError;\n/** @deprecated Use `TenxGraphError`. Removed in 2.0. */\nexport type AgentFlowError = TenxGraphError;\n\n/** @deprecated Use `TenxGraphConfig`. Removed in 2.0. */\nexport type AgentFlowConfig = TenxGraphConfig;\n/** @deprecated Use `TenxGraphAuth`. Removed in 2.0. */\nexport type AgentFlowAuth = TenxGraphAuth;\n/** @deprecated Use `TenxGraphBearerAuth`. Removed in 2.0. */\nexport type AgentFlowBearerAuth = TenxGraphBearerAuth;\n/** @deprecated Use `TenxGraphBasicAuth`. Removed in 2.0. */\nexport type AgentFlowBasicAuth = TenxGraphBasicAuth;\n/** @deprecated Use `TenxGraphHeaderAuth`. Removed in 2.0. */\nexport type AgentFlowHeaderAuth = TenxGraphHeaderAuth;\n"],"names":["MediaRef","kind","url","file_id","data_base64","mime_type","size_bytes","sha256","filename","width","height","duration_ms","page","AnnotationRef","index","title","TextBlock","text","annotations","ImageBlock","media","alt_text","bbox","AudioBlock","transcript","sample_rate","channels","VideoBlock","thumbnail","DocumentBlock","pages","excerpt","DataBlock","ToolCallBlock","id","name","args","tool_type","RemoteToolCallBlock","ToolResultBlock","props","ReasoningBlock","summary","details","AnnotationBlock","refs","spans","ErrorBlock","message","code","data","TokenUsages","Message","role","content","message_id","meta","block","output","as_type","imageUrl","fileId","mimeType","isImage","isAudio","isVideo","blocks","normalizeToolParameters","parameters","source","type","properties","required","rest","ToolExecutor","tools","func","registration","toolDef","node","nodeTools","openaiTools","tool","messages","toolCalls","msg","results","call","toolName","result","toolResultBlock","error","errorMessage","TenxGraphError","statusCode","errorCode","requestId","timestamp","context","endpoint","method","recoverySuggestion","captureStackTrace","BadRequestError","AuthenticationError","PermissionError","NotFoundError","ValidationError","ServerError","GraphError","NodeError","nodeName","GraphRecursionError","recursionLimit","StorageError","TransientStorageError","MetricsError","SchemaVersionError","expectedVersion","actualVersion","SerializationError","parseErrorResponse","response","contentType","createErrorFromResponse","fallbackMessage","errorData","metadata","setHeader","target","value","existingName","mergeHeaders","hasHeader","encodeBase64","bufferConstructor","bytes","binary","byte","applyAuth","auth","credentials","headerValue","buildHeaders","defaults","headers","getRequestCredentials","bearerAuth","token","basicAuth","username","password","headerAuth","prefix","ping","controller","timeoutId","graph","graphTools","observability","threadId","runId","query","stateSchema","threadState","updateThreadState","request","clearThreadState","threadMessages","params","queryString","checkpointMessages","addThreadMessages","body","threadMessage","threadDetails","deleteThreadMessage","deleteThread","threads","makeSingleInvokeCall","hasRemoteToolCalls","invoke","onPartialResult","recursion_limit","allMessages","currentMessages","iterations","recursionLimitReached","lastResponse","initial_state","config","response_granularity","iterationRequest","hasToolCalls","partialResult","toolResults","serializeMessage","cleanContent","cleaned","key","serialized","StreamEventType","parseStreamChunks","reader","debug","decoder","buffer","done","processBuffer","isFinal","newlineIndex","line","chunk","extracted","extractFirstJSON","depth","inString","escaped","i","char","streamInvoke","responseMessages","WS_BEARER_SUBPROTOCOL","resolveBearerToken","buildWsUrl","path","openWebSocket","Impl","protocols","authHeader","wsStreamInvoke","ws","queue","wakeUp","enqueue","item","fn","waitForItem","resolve","event","e","reject","nextPayload","outerLoop","runMessages","innerLoop","REALTIME_OUTPUT_SAMPLE_RATE","REALTIME_INPUT_SAMPLE_RATE","genThreadId","c","hashString","s","h","toUint8","view","RealtimeSession","ctx","init","options","pcm16","listener","f","err","frame","audio","parsed","failure","attempt","delayMs","onceOpen","MemoryType","storeMemory","RetrievalStrategy","DistanceMetric","searchMemory","getMemory","updateMemory","deleteMemory","listMemories","forgetMemories","stopGraph","fixGraph","uploadFile","file","formData","getFile","getFileInfo","getFileAccessUrl","getMultimodalConfig","isThreadsRequest","normalizeThreadsRequest","offset","limit","isThreadMessagesRequest","normalizeThreadMessagesRequest","TenxGraphClient","handler","stopGraphEndpoint","fixGraphEndpoint","state","search","messageId","invokeEndpoint","streamInvokeEndpoint","storeMemoryEndpoint","searchMemoryEndpoint","memoryId","getMemoryEndpoint","updateMemoryEndpoint","deleteMemoryEndpoint","listMemoriesEndpoint","forgetMemoriesEndpoint","uploadFileEndpoint","getFileEndpoint","getFileInfoEndpoint","getFileAccessUrlEndpoint","getMultimodalConfigEndpoint","DefaultExecutionMeta","AgentState","initialData","AgentFlowClient","AgentFlowError"],"mappings":"gFAGO,MAAMA,CAAS,CAcpB,YACEC,EAAmC,MACnCC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACA,CA1BF,KAAA,KAAmC,MA2BjC,KAAK,KAAOX,EACZ,KAAK,IAAMC,EACX,KAAK,QAAUC,EACf,KAAK,YAAcC,EACnB,KAAK,UAAYC,EACjB,KAAK,WAAaC,EAClB,KAAK,OAASC,EACd,KAAK,SAAWC,EAChB,KAAK,MAAQC,EACb,KAAK,OAASC,EACd,KAAK,YAAcC,EACnB,KAAK,KAAOC,CACd,CACF,CAGO,MAAMC,EAAc,CAOzB,YAAYX,EAAcC,EAAkBS,EAAeE,EAAgBC,EAAgB,CACzF,KAAK,IAAMb,EACX,KAAK,QAAUC,EACf,KAAK,KAAOS,EACZ,KAAK,MAAQE,EACb,KAAK,MAAQC,CACf,CACF,CAGO,MAAMC,CAAU,CAKrB,YAAYC,EAAe,GAAIC,EAA+B,CAAA,EAAI,CAJlE,KAAA,KAAe,OACf,KAAA,KAAe,GACf,KAAA,YAA+B,CAAA,EAG7B,KAAK,KAAOD,EACZ,KAAK,YAAcC,CACrB,CACF,CAGO,MAAMC,CAAW,CAMtB,YAAYC,EAAkB,IAAIpB,EAAYqB,EAAmBC,EAAiB,CALlF,KAAA,KAAgB,QAChB,KAAA,MAAkB,IAAItB,EAKpB,KAAK,MAAQoB,EACb,KAAK,SAAWC,EAChB,KAAK,KAAOC,CACd,CACF,CAGO,MAAMC,CAAW,CAOtB,YACEH,EAAkB,IAAIpB,EACtBwB,EACAC,EACAC,EACA,CAXF,KAAA,KAAgB,QAChB,KAAA,MAAkB,IAAI1B,EAWpB,KAAK,MAAQoB,EACb,KAAK,WAAaI,EAClB,KAAK,YAAcC,E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AC,EACAtD,EAAyB,CAAA,EACzBuD,EACA,CACA,MACElD,EACA,IACA,cACAgD,EACAC,EACAtD,EACAuD,EACA,OACA,OACA,6EAAA,EAEF,KAAK,KAAO,YACd,CACF,CAMO,MAAMY,UAAkBjB,CAAe,CAG5C,YACE7C,EACAgD,EACAC,EACAtD,EAAyB,CAAA,EACzBuD,EACAa,EACA,CACA,MACE/D,EACA,IACA,aACAgD,EACAC,EACAtD,EACAuD,EACA,OACA,OACA,6EAAA,EAEF,KAAK,KAAO,YACZ,KAAK,SAAWa,CAClB,CACF,CAMO,MAAMC,UAA4BnB,CAAe,CAGtD,YACE7C,EACAgD,EACAC,EACAtD,EAAyB,CAAA,EACzBuD,EACAe,EACA,CACA,MACEjE,EACA,IACA,wBACAgD,EACAC,EACAtD,EACAuD,EACA,OACA,OACA,8FAAA,EAEF,KAAK,KAAO,sBACZ,KAAK,eAAiBe,CACxB,CACF,CAMO,MAAMC,UAAqBrB,CAAe,CAC/C,YACE7C,EACAgD,EACAC,EACAtD,EAAyB,CAAA,EACzBuD,EACA,CACA,MACElD,EACA,IACA,gBACAgD,EACAC,EACAtD,EACAuD,EACA,OACA,OACA,gFAAA,EAEF,KAAK,KAAO,cACd,CACF,CAMO,MAAMiB,UAA8BtB,CAAe,CACxD,YACE7C,EACAgD,EACAC,EACAtD,EAAyB,CAAA,EACzBuD,EACA,CACA,MACElD,EACA,IACA,0BACAgD,EACAC,EACAtD,EACAuD,EACA,OACA,OACA,2EAAA,EAEF,KAAK,KAAO,uBACd,CACF,CAMO,MAAMkB,UAAqBvB,CAAe,CAC/C,YACE7C,EACAgD,EACAC,EACAtD,EAAyB,CAAA,EACzBuD,EACA,CACA,MACElD,EACA,IACA,gBACAgD,EACAC,EACAtD,EACAuD,EACA,OACA,OACA,2FAAA,EAEF,KAAK,KAAO,cACd,CACF,CAMO,MAAMmB,UAA2BxB,CAAe,CAIrD,YACE7C,EACAgD,EACAC,EACAtD,EAAyB,GACzBuD,EACAoB,EACAC,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