@waniwani/sdk 0.7.2 → 0.7.4

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/mcp/react/widgets/platform.ts","../../src/mcp/server/flows/@types.ts","../../src/mcp/server/flows/compile.ts","../../src/mcp/server/scoped-client.ts","../../src/mcp/server/utils.ts","../../src/error.ts","../../src/kb/client.ts","../../src/project-config.ts","../../src/tracking/mapper.ts","../../src/tracking/transport.ts","../../src/tracking/index.ts","../../src/waniwani.ts","../../src/mcp/server/kv/kv-store.ts","../../src/mcp/server/flows/flow-store.ts","../../src/mcp/server/widget-token.ts","../../src/mcp/server/with-waniwani/helpers.ts","../../src/mcp/server/with-waniwani/index.ts","../../src/mcp/server/flows/nested.ts","../../src/mcp/server/flows/execute.ts","../../src/mcp/server/flows/protocol.ts","../../src/mcp/server/flows/state-graph.ts","../../src/mcp/server/flows/create-flow.ts","../../src/mcp/server/flows/test-utils.ts","../../src/mcp/server/resources/meta.ts","../../src/mcp/server/resources/create-resource.ts","../../src/mcp/server/tools/create-tool.ts","../../src/mcp/server/tracking-route.ts"],"sourcesContent":["/**\n * Widget platform types\n */\nexport type WidgetPlatform = \"openai\" | \"mcp-apps\";\n\n/**\n * Detects which platform the widget is running on.\n *\n * OpenAI injects a global `window.openai` object.\n * MCP Apps runs in a sandboxed iframe and uses postMessage.\n */\nexport function detectPlatform(): WidgetPlatform {\n\tif (typeof window !== \"undefined\" && \"openai\" in window) {\n\t\treturn \"openai\";\n\t}\n\treturn \"mcp-apps\";\n}\n\n/**\n * Check if running on OpenAI platform\n */\nexport function isOpenAI(): boolean {\n\treturn detectPlatform() === \"openai\";\n}\n\n/**\n * Check if running on MCP Apps platform\n */\nexport function isMCPApps(): boolean {\n\treturn detectPlatform() === \"mcp-apps\";\n}\n","import type { z } from \"zod\";\nimport type { McpServer } from \"../resources/types\";\nimport type { ScopedWaniWaniClient } from \"../scoped-client\";\nimport type { RegisteredTool } from \"../tools/types\";\nimport type { FlowStore } from \"./flow-store\";\n\nexport type { McpServer };\n\n// ============================================================================\n// Sentinel constants\n// ============================================================================\n\nexport const START = \"__start__\" as const;\nexport const END = \"__end__\" as const;\n\n// ============================================================================\n// Signal types — returned by node handlers to control flow behavior\n// ============================================================================\n\nconst INTERRUPT = Symbol.for(\"waniwani.flow.interrupt\");\nconst WIDGET = Symbol.for(\"waniwani.flow.widget\");\n\n/** A single question within an interrupt step */\nexport type InterruptQuestion = {\n\t/** Question to ask the user */\n\tquestion: string;\n\t/** State key where the answer will be stored */\n\tfield: string;\n\t/** Optional suggestions to present as options */\n\tsuggestions?: string[];\n\t/** Hidden context/instructions for this specific question (not shown to user directly) */\n\tcontext?: string;\n\t/** Validation function — runs after the user answers, before advancing to the next node */\n\t// biome-ignore lint/suspicious/noConfusingVoidType: void is needed so `async () => {}` compiles\n\tvalidate?: (value: unknown) => MaybePromise<Record<string, unknown> | void>;\n};\n\n/**\n * Interrupt signal — pauses the flow and asks the user one or more questions.\n * Single-question and multi-question interrupts use the same type.\n */\nexport type InterruptSignal = {\n\treadonly __type: typeof INTERRUPT;\n\t/** Questions to ask — ask all in one conversational message */\n\tquestions: InterruptQuestion[];\n\t/** Overall hidden context/instructions for the assistant (not shown to user directly) */\n\tcontext?: string;\n};\n\nexport type WidgetSignal = {\n\treadonly __type: typeof WIDGET;\n\t/** The display tool to delegate rendering to */\n\ttool: RegisteredTool;\n\t/** Data to pass to the display tool */\n\tdata: Record<string, unknown>;\n\t/** Description of what the widget does (for the AI's context) */\n\tdescription?: string;\n\t/**\n\t * Whether the user is expected to interact with the widget before the flow continues.\n\t * Defaults to true. Set to false for informational widgets that should render and then\n\t * immediately advance to the next flow step.\n\t */\n\tinteractive?: boolean;\n\t/**\n\t * State key this widget fills — enables auto-skip when the field is already in state.\n\t * Pass this so the engine can skip the widget step when the answer is already known.\n\t */\n\tfield?: string;\n};\n\n/**\n * Create an interrupt signal — pauses the flow and asks the user a question.\n * Used internally by the engine. Flow authors use the typed `interrupt` from the node context.\n *\n * Accepts an object where each key is a field name and the value describes the question.\n * The only reserved key is `context` (string) for overall hidden AI instructions.\n */\nexport function interrupt(\n\tfields: Record<string, unknown>,\n\tconfig?: { context?: string },\n): InterruptSignal {\n\tconst context = config?.context;\n\tconst questions: InterruptQuestion[] = [];\n\n\tfor (const [key, value] of Object.entries(fields)) {\n\t\tif (typeof value === \"object\" && value !== null && \"question\" in value) {\n\t\t\tconst q = value as {\n\t\t\t\tquestion: string;\n\t\t\t\tsuggestions?: string[];\n\t\t\t\tcontext?: string;\n\t\t\t\tvalidate?: (\n\t\t\t\t\tvalue: unknown,\n\t\t\t\t\t// biome-ignore lint/suspicious/noConfusingVoidType: void is needed so `async () => {}` compiles\n\t\t\t\t) => MaybePromise<Record<string, unknown> | void>;\n\t\t\t};\n\t\t\tquestions.push({\n\t\t\t\tquestion: q.question,\n\t\t\t\tfield: key,\n\t\t\t\tsuggestions: q.suggestions,\n\t\t\t\tcontext: q.context,\n\t\t\t\tvalidate: q.validate,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn {\n\t\t__type: INTERRUPT,\n\t\tquestions,\n\t\tcontext,\n\t};\n}\n\n/**\n * Create a widget signal — pauses the flow and delegates rendering to a display tool.\n * Used internally by the engine. Flow authors use the typed `showWidget` from the node context.\n */\nexport function showWidget(\n\ttool: RegisteredTool,\n\tconfig: {\n\t\tdata: Record<string, unknown>;\n\t\tdescription?: string;\n\t\tinteractive?: boolean;\n\t\tfield?: string;\n\t},\n): WidgetSignal {\n\treturn { __type: WIDGET, tool, ...config };\n}\n\nexport function isInterrupt(value: unknown): value is InterruptSignal {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t\"__type\" in value &&\n\t\t(value as InterruptSignal).__type === INTERRUPT\n\t);\n}\n\nexport function isWidget(value: unknown): value is WidgetSignal {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t\"__type\" in value &&\n\t\t(value as WidgetSignal).__type === WIDGET\n\t);\n}\n\n// ============================================================================\n// Node context & handler\n// ============================================================================\n\nexport type MaybePromise<T> = T | Promise<T>;\n\n// ============================================================================\n// Nested state utility types\n// ============================================================================\n\n/** Deep partial — allows partial updates at any nesting level (for z.object state fields). */\nexport type DeepPartial<T> = {\n\t[K in keyof T]?: T[K] extends Record<string, unknown>\n\t\t? DeepPartial<T[K]>\n\t\t: T[K];\n};\n\n/**\n * Extract known (non-index-signature) string keys from a type.\n * Zod v4's z.object() adds `[key: string]: unknown` to inferred types,\n * so we filter those out to get only the declared field names.\n */\ntype KnownStringKeys<T> = Extract<\n\tkeyof {\n\t\t[K in keyof T as string extends K\n\t\t\t? never\n\t\t\t: number extends K\n\t\t\t\t? never\n\t\t\t\t: K]: T[K];\n\t},\n\tstring\n>;\n\n/**\n * Union of all valid field paths for a state type.\n * - Flat fields produce their key: `\"email\"`\n * - `z.object()` fields produce dot-paths to sub-fields: `\"driver.name\"`, `\"driver.license\"`\n * - Arrays and general records (`z.record()`) are treated as flat fields.\n * - Only 1 level of nesting is supported.\n */\nexport type FieldPaths<TState> = {\n\t[K in Extract<keyof TState, string>]: NonNullable<TState[K]> extends unknown[]\n\t\t? K\n\t\t: NonNullable<TState[K]> extends Record<string, unknown>\n\t\t\t? KnownStringKeys<NonNullable<TState[K]>> extends never\n\t\t\t\t? K\n\t\t\t\t: K | `${K}.${KnownStringKeys<NonNullable<TState[K]>>}`\n\t\t\t: K;\n}[Extract<keyof TState, string>];\n\n/** Resolve a dot-path to the value type at that path in TState. */\nexport type ResolveFieldType<\n\tTState,\n\tP extends string,\n> = P extends `${infer Parent}.${infer Child}`\n\t? Parent extends keyof TState\n\t\t? Child extends keyof NonNullable<TState[Parent]>\n\t\t\t? NonNullable<TState[Parent]>[Child]\n\t\t\t: never\n\t\t: never\n\t: P extends keyof TState\n\t\t? TState[P]\n\t\t: never;\n\n// ============================================================================\n// Typed interrupt & showWidget\n// ============================================================================\n\n/**\n * Typed interrupt function — available on the node context.\n *\n * First argument: an object where each key is a field path and each value\n * describes the question for that field. Use dot-paths for nested state fields.\n * `validate` receives the field's value typed from the Zod schema.\n *\n * Second argument (optional): config with overall hidden AI instructions.\n *\n * @example\n * ```ts\n * // Flat field\n * interrupt({ breed: { question: \"What breed is your pet?\" } })\n *\n * // Nested field (z.object in state)\n * interrupt({ \"driver.name\": { question: \"Driver's name?\" } })\n *\n * // Multiple questions with context\n * interrupt(\n * {\n * \"driver.name\": { question: \"Name?\" },\n * \"driver.license\": { question: \"License?\" },\n * },\n * { context: \"Ask both questions naturally.\" },\n * )\n * ```\n */\nexport type TypedInterrupt<TState> = (\n\tfields: {\n\t\t[P in FieldPaths<TState>]?: {\n\t\t\tquestion: string;\n\t\t\tvalidate?: (\n\t\t\t\tvalue: ResolveFieldType<TState, P>,\n\t\t\t\t// biome-ignore lint/suspicious/noConfusingVoidType: void is needed so `async () => {}` compiles\n\t\t\t) => MaybePromise<DeepPartial<TState> | void>;\n\t\t\tsuggestions?: string[];\n\t\t\tcontext?: string;\n\t\t};\n\t},\n\tconfig?: {\n\t\t/** Overall hidden context/instructions for the assistant (not shown to user directly) */\n\t\tcontext?: string;\n\t},\n) => InterruptSignal;\n\n/**\n * Typed showWidget function — available on the node context.\n * The `field` parameter accepts field paths (flat or dot-path for nested state).\n */\nexport type TypedShowWidget<TState> = (\n\ttool: RegisteredTool,\n\tconfig: {\n\t\tdata: Record<string, unknown>;\n\t\tdescription?: string;\n\t\tinteractive?: boolean;\n\t\tfield?: FieldPaths<TState>;\n\t},\n) => WidgetSignal;\n\n/**\n * Context object passed to node handlers.\n * Provides state, metadata, and typed helper functions for creating signals.\n */\nexport type NodeContext<TState> = {\n\t/** Current flow state (partial — fields are filled as the flow progresses) */\n\tstate: Partial<TState>;\n\t/** Request metadata from the MCP call */\n\tmeta?: Record<string, unknown>;\n\t/** Create an interrupt signal — pause and ask the user questions */\n\tinterrupt: TypedInterrupt<TState>;\n\t/** Create a widget signal — pause and show a UI widget */\n\tshowWidget: TypedShowWidget<TState>;\n\t/** Session-scoped WaniWani client — available when the server is wrapped with withWaniwani() */\n\twaniwani?: ScopedWaniWaniClient;\n};\n\n/**\n * Node handler — receives a context object and returns a signal or state updates.\n * The return value determines behavior:\n * - `Partial<TState>` → action node (state merged, auto-advance)\n * - `InterruptSignal` → interrupt (pause, ask user one or more questions)\n * - `WidgetSignal` → widget step (pause, show widget)\n */\nexport type NodeHandler<TState> = (\n\tctx: NodeContext<TState>,\n) => MaybePromise<DeepPartial<TState> | InterruptSignal | WidgetSignal>;\n\n/**\n * Condition function for conditional edges.\n * Receives current state, returns the name of the next node.\n */\nexport type ConditionFn<TState> = (\n\tstate: Partial<TState>,\n) => string | Promise<string>;\n\nexport type Edge<TState> =\n\t| { type: \"direct\"; to: string }\n\t| { type: \"conditional\"; condition: ConditionFn<TState> };\n\n// ============================================================================\n// Flow config & compiled output\n// ============================================================================\n\nexport type FlowConfig = {\n\t/** Unique identifier for the flow (becomes the MCP tool name) */\n\tid: string;\n\t/** Display title */\n\ttitle: string;\n\t/** Description for the AI (explains when to use this flow) */\n\tdescription: string;\n\t/**\n\t * Define the flow's state — each field the flow collects.\n\t * Keys are the field names used in `interrupt({ field })`,\n\t * values are Zod schemas with `.describe()`.\n\t *\n\t * The state definition serves two purposes:\n\t * 1. Type inference — `TState` is automatically derived, no explicit generic needed\n\t * 2. AI protocol — field names, types, and descriptions are included in the tool\n\t * description so the AI can pre-fill answers via `_meta.flow.state`\n\t *\n\t * @example\n\t * ```ts\n\t * state: {\n\t * country: z.string().describe(\"Country the business is based in\"),\n\t * status: z.enum([\"registered\", \"unregistered\"]).describe(\"Business registration status\"),\n\t * }\n\t * ```\n\t */\n\tstate: Record<string, z.ZodType>;\n\t/** Optional tool annotations */\n\tannotations?: {\n\t\treadOnlyHint?: boolean;\n\t\tidempotentHint?: boolean;\n\t\topenWorldHint?: boolean;\n\t\tdestructiveHint?: boolean;\n\t};\n};\n\n/**\n * Infer the runtime state type from a flow's state schema definition.\n *\n * @example\n * ```ts\n * const config = {\n * state: {\n * country: z.enum([\"FR\", \"DE\"]),\n * status: z.enum([\"registered\", \"unregistered\"]),\n * }\n * };\n * type MyState = InferFlowState<typeof config.state>;\n * // { country: \"FR\" | \"DE\"; status: \"registered\" | \"unregistered\" }\n * ```\n */\nexport type InferFlowState<T extends Record<string, z.ZodType>> = {\n\t[K in keyof T]: z.infer<T[K]>;\n};\n\n/**\n * A compiled flow — can be registered on an McpServer.\n */\nexport type RegisteredFlow = {\n\tid: string;\n\ttitle: string;\n\tdescription: string;\n\tregister: (server: McpServer) => Promise<void>;\n\t/** Returns a Mermaid `flowchart TD` diagram of the flow graph. */\n\tgraph: () => string;\n};\n\nexport interface CompileInput<TState extends Record<string, unknown>> {\n\tconfig: FlowConfig;\n\tnodes: Map<string, NodeHandler<TState>>;\n\tedges: Map<string, Edge<TState>>;\n\tstore?: FlowStore;\n\tgraph: () => string;\n}\n\nexport type FlowToolInput = {\n\taction: \"start\" | \"continue\";\n\t/** Required when `action` is `\"start\"`. */\n\tintent?: string;\n\tstateUpdates?: Record<string, unknown>;\n};\n\nexport type FlowTokenContent = {\n\tstep?: string;\n\tstate: Record<string, unknown>;\n\tfield?: string;\n\twidgetId?: string;\n};\n\nexport type InterruptQuestionData = {\n\tquestion: string;\n\tfield: string;\n\tsuggestions?: string[];\n\tcontext?: string;\n};\n\nexport type FlowInterruptContent = {\n\tstatus: \"interrupt\";\n\t/** Single-question shorthand */\n\tquestion?: string;\n\tfield?: string;\n\tsuggestions?: string[];\n\t/** Multi-question */\n\tquestions?: InterruptQuestionData[];\n\tcontext?: string;\n};\n\nexport type FlowWidgetContent = {\n\tstatus: \"widget\";\n\t/** Display tool to call */\n\ttool: string;\n\t/** Data to pass to the display tool */\n\tdata: Record<string, unknown>;\n\tdescription?: string;\n\t/** Whether the widget expects user interaction before continuing */\n\tinteractive?: boolean;\n};\n\nexport type FlowCompleteContent = {\n\tstatus: \"complete\";\n};\n\nexport type FlowErrorContent = {\n\tstatus: \"error\";\n\terror: string;\n};\n\n/** Parsed response text from a flow tool call */\nexport type FlowContent =\n\t| FlowInterruptContent\n\t| FlowWidgetContent\n\t| FlowCompleteContent\n\t| FlowErrorContent;\n\nexport type ExecutionResult = {\n\tcontent: FlowContent;\n\tflowTokenContent?: FlowTokenContent;\n};\n","import type { ToolCallback } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n\tServerNotification,\n\tServerRequest,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport type { ScopedWaniWaniClient } from \"../scoped-client\";\nimport { extractScopedClient } from \"../scoped-client\";\nimport { extractSessionId } from \"../utils\";\nimport { FLOW_STORE_KEY } from \"../with-waniwani/index\";\nimport type {\n\tCompileInput,\n\tFlowToolInput,\n\tMcpServer,\n\tRegisteredFlow,\n} from \"./@types\";\nimport { START } from \"./@types\";\nimport { executeFrom, resolveNextNode, type ValidateFn } from \"./execute\";\nimport type { FlowStore } from \"./flow-store\";\nimport { deepMerge, expandDotPaths } from \"./nested\";\nimport { buildFlowProtocol } from \"./protocol\";\n\n// ============================================================================\n// Input schema\n// ============================================================================\n\nconst inputSchema = {\n\taction: z\n\t\t.enum([\"start\", \"continue\"])\n\t\t.describe(\n\t\t\t'\"start\" to begin the flow, \"continue\" to resume after a pause (interrupt or widget)',\n\t\t),\n\tintent: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Required when action is \"start\". Provide a brief summary of the user\\'s goal for this flow, including relevant prior context that led to triggering it, if available. Do not invent missing context.',\n\t\t),\n\tstateUpdates: z\n\t\t.record(z.string(), z.unknown())\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"State field values to set before processing the next node. Use this to pass the user's answer (keyed by the field name from the response) and any other values the user mentioned.\",\n\t\t),\n};\n\n// ============================================================================\n// Compile\n// ============================================================================\n\nexport function compileFlow<TState extends Record<string, unknown>>(\n\tinput: CompileInput<TState>,\n): RegisteredFlow {\n\tconst { config, nodes, edges } = input;\n\tconst protocol = buildFlowProtocol(config);\n\tconst fullDescription = `${config.description}\\n${protocol}`;\n\n\t// Validator storage — populated when handlers return interrupts with validate functions.\n\t// Keyed by \"nodeName:fieldName\", persists across tool calls within the same server.\n\tconst validators = new Map<string, ValidateFn>();\n\n\tasync function handleToolCall(\n\t\targs: FlowToolInput,\n\t\tsessionId: string | undefined,\n\t\tstore: FlowStore,\n\t\tmeta?: Record<string, unknown>,\n\t\twaniwani?: ScopedWaniWaniClient,\n\t) {\n\t\tif (args.action === \"start\") {\n\t\t\tconst intent =\n\t\t\t\ttypeof args.intent === \"string\" ? args.intent.trim() : undefined;\n\t\t\tif (!intent) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\t'Missing required \"intent\" for action \"start\". Include a brief summary of the user\\'s goal for this flow and any relevant prior context that led to triggering it, if available.',\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\targs.intent = intent;\n\n\t\t\tconst startEdge = edges.get(START);\n\t\t\tif (!startEdge) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: { status: \"error\" as const, error: \"No start edge\" },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst startState = expandDotPaths(args.stateUpdates ?? {}) as TState;\n\t\t\tconst firstNode = await resolveNextNode(startEdge, startState);\n\t\t\treturn executeFrom(\n\t\t\t\tfirstNode,\n\t\t\t\tstartState,\n\t\t\t\tnodes,\n\t\t\t\tedges,\n\t\t\t\tvalidators,\n\t\t\t\tmeta,\n\t\t\t\twaniwani,\n\t\t\t);\n\t\t}\n\n\t\tif (args.action === \"continue\") {\n\t\t\tif (!sessionId) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\terror: \"No session ID available for continue action.\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlet flowState: Awaited<ReturnType<typeof store.get>>;\n\t\t\ttry {\n\t\t\t\tflowState = await store.get(sessionId);\n\t\t\t} catch (err) {\n\t\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\terror: `Failed to load flow state (session \"${sessionId}\"): ${msg}`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (!flowState) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\terror: `Flow state not found for session \"${sessionId}\". The flow may have expired.`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst state = flowState.state as TState;\n\t\t\tconst step = flowState.step;\n\t\t\tif (!step) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\t'This flow has already completed. Use action \"start\" to begin a new flow.',\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst updatedState = deepMerge(\n\t\t\t\tstate as Record<string, unknown>,\n\t\t\t\texpandDotPaths(args.stateUpdates ?? {}),\n\t\t\t) as TState;\n\n\t\t\t// Widget continue: advance past the widget step (don't re-show it)\n\t\t\tif (flowState.widgetId) {\n\t\t\t\tconst edge = edges.get(step);\n\t\t\t\tif (!edge) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\t\terror: `No edge from step \"${step}\"`,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst nextNode = await resolveNextNode(edge, updatedState);\n\t\t\t\treturn executeFrom(\n\t\t\t\t\tnextNode,\n\t\t\t\t\tupdatedState,\n\t\t\t\t\tnodes,\n\t\t\t\t\tedges,\n\t\t\t\t\tvalidators,\n\t\t\t\t\tmeta,\n\t\t\t\t\twaniwani,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Interrupt continue: re-execute from current step.\n\t\t\t// The handler re-runs, filters answered questions, and runs\n\t\t\t// validators if all questions are filled.\n\t\t\treturn executeFrom(\n\t\t\t\tstep,\n\t\t\t\tupdatedState,\n\t\t\t\tnodes,\n\t\t\t\tedges,\n\t\t\t\tvalidators,\n\t\t\t\tmeta,\n\t\t\t\twaniwani,\n\t\t\t);\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: {\n\t\t\t\tstatus: \"error\" as const,\n\t\t\t\terror: `Unknown action: \"${args.action}\"`,\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {\n\t\tid: config.id,\n\t\ttitle: config.title,\n\t\tdescription: fullDescription,\n\t\tgraph: input.graph,\n\n\t\tasync register(server: McpServer): Promise<void> {\n\t\t\tserver.registerTool(\n\t\t\t\tconfig.id,\n\t\t\t\t{\n\t\t\t\t\ttitle: config.title,\n\t\t\t\t\tdescription: fullDescription,\n\t\t\t\t\tinputSchema,\n\t\t\t\t\tannotations: config.annotations,\n\t\t\t\t},\n\t\t\t\t(async (args: FlowToolInput, extra: unknown) => {\n\t\t\t\t\tconst requestExtra = extra as RequestHandlerExtra<\n\t\t\t\t\t\tServerRequest,\n\t\t\t\t\t\tServerNotification\n\t\t\t\t\t> & {\n\t\t\t\t\t\t[FLOW_STORE_KEY]?: FlowStore;\n\t\t\t\t\t};\n\n\t\t\t\t\tconst _meta: Record<string, unknown> = requestExtra._meta ?? {};\n\t\t\t\t\tconst sessionId = extractSessionId(_meta);\n\t\t\t\t\tconst waniwani = extractScopedClient(requestExtra);\n\t\t\t\t\tconst store = input.store ?? requestExtra[FLOW_STORE_KEY];\n\n\t\t\t\t\tif (!store) {\n\t\t\t\t\t\tconst errorContent = [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\t\t\t\t\terror:\n\t\t\t\t\t\t\t\t\t\t\t\"No flow store available. Wrap your MCP server with withWaniwani() or pass a store to .compile().\",\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t\t\t2,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t];\n\t\t\t\t\t\treturn { content: errorContent, _meta, isError: true };\n\t\t\t\t\t}\n\n\t\t\t\t\tconst result = await handleToolCall(\n\t\t\t\t\t\targs,\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\t_meta,\n\t\t\t\t\t\twaniwani,\n\t\t\t\t\t);\n\n\t\t\t\t\t// Persist flow state under session ID\n\t\t\t\t\tif (sessionId) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tresult.flowTokenContent &&\n\t\t\t\t\t\t\tresult.content.status !== \"complete\"\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait store.set(sessionId, result.flowTokenContent);\n\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\t\t\t\tconst errorContent = [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\t\t\t\t\t\t\terror: `Flow state failed to persist (session \"${sessionId}\"): ${msg}`,\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t\t\t\t\t2,\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tcontent: errorContent,\n\t\t\t\t\t\t\t\t\t_meta,\n\t\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (result.content.status === \"complete\") {\n\t\t\t\t\t\t\t// Clean up — flow is done, remove stale state so a subsequent\n\t\t\t\t\t\t\t// \"continue\" returns \"not found\" instead of a confusing step error.\n\t\t\t\t\t\t\tawait store.delete(sessionId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst content = [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\ttext: JSON.stringify(result.content, null, 2),\n\t\t\t\t\t\t},\n\t\t\t\t\t];\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t_meta,\n\t\t\t\t\t\t...(result.content.status === \"error\" ? { isError: true } : {}),\n\t\t\t\t\t};\n\t\t\t\t}) satisfies ToolCallback<typeof inputSchema>,\n\t\t\t);\n\t\t},\n\t};\n}\n","import type { KbClient } from \"../../kb/types.js\";\nimport type { TrackInput, TrackingClient } from \"../../tracking/@types.js\";\n\n/**\n * Well-known key used to attach the scoped client to the MCP `extra` object.\n * Read by `createTool` and flow compilation to surface it in handler contexts.\n */\nexport const SCOPED_CLIENT_KEY = \"waniwani/client\";\n\n/**\n * A request-scoped WaniWani client with meta pre-attached.\n *\n * Available as `context.waniwani` inside `createTool` handlers and flow nodes\n * when the server is wrapped with `withWaniwani()`.\n */\nexport interface ScopedWaniWaniClient {\n\t/** Track an event — request meta is automatically merged. */\n\ttrack(event: TrackInput): Promise<{ eventId: string }>;\n\t/** Identify a user — request meta is automatically merged. */\n\tidentify(\n\t\tuserId: string,\n\t\tproperties?: Record<string, unknown>,\n\t): Promise<{ eventId: string }>;\n\t/** Knowledge base client (no meta needed). */\n\treadonly kb: KbClient;\n\t/** @internal Resolved API config from withWaniwani(). */\n\treadonly _config?: { apiUrl?: string; apiKey?: string };\n}\n\n/**\n * Extract the scoped client from the MCP `extra` object.\n * Returns undefined if `withWaniwani()` is not wrapping the server.\n */\nexport function extractScopedClient(\n\textra: unknown,\n): ScopedWaniWaniClient | undefined {\n\tif (typeof extra === \"object\" && extra !== null) {\n\t\treturn (extra as Record<string, unknown>)[SCOPED_CLIENT_KEY] as\n\t\t\t| ScopedWaniWaniClient\n\t\t\t| undefined;\n\t}\n\treturn undefined;\n}\n\nexport function createScopedClient(\n\tbase: Pick<TrackingClient, \"track\" | \"identify\"> & { readonly kb: KbClient },\n\tmeta: Record<string, unknown>,\n\tconfig?: { apiUrl?: string; apiKey?: string },\n): ScopedWaniWaniClient {\n\treturn {\n\t\ttrack(event) {\n\t\t\treturn base.track({\n\t\t\t\t...event,\n\t\t\t\tmeta: { ...meta, ...event.meta },\n\t\t\t});\n\t\t},\n\t\tidentify(userId, properties) {\n\t\t\treturn base.identify(userId, properties, meta);\n\t\t},\n\t\tkb: base.kb,\n\t\t_config: config,\n\t};\n}\n","// ============================================================================\n// Meta key extraction helpers\n// ============================================================================\n\n/** Pick the first non-empty string value from `meta` matching the given keys. */\nfunction pickFirst(\n\tmeta: Record<string, unknown>,\n\tkeys: readonly string[],\n): string | undefined {\n\tfor (const key of keys) {\n\t\tconst value = meta[key];\n\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\treturn value;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n// --- Key lists (ordered by priority) ---\n\nconst SESSION_ID_KEYS = [\n\t\"waniwani/sessionId\",\n\t\"openai/sessionId\",\n\t\"openai/session\",\n\t\"sessionId\",\n\t\"conversationId\",\n\t\"anthropic/sessionId\",\n] as const;\n\nconst REQUEST_ID_KEYS = [\n\t\"waniwani/requestId\",\n\t\"openai/requestId\",\n\t\"requestId\",\n\t\"mcp/requestId\",\n] as const;\n\nconst TRACE_ID_KEYS = [\n\t\"waniwani/traceId\",\n\t\"openai/traceId\",\n\t\"traceId\",\n\t\"mcp/traceId\",\n\t\"openai/requestId\",\n\t\"requestId\",\n] as const;\n\nconst EXTERNAL_USER_ID_KEYS = [\n\t\"waniwani/userId\",\n\t\"openai/userId\",\n\t\"externalUserId\",\n\t\"userId\",\n\t\"actorId\",\n] as const;\n\nconst CORRELATION_ID_KEYS = [\"correlationId\", \"openai/requestId\"] as const;\n\n// --- Extractors ---\n\nexport function extractSessionId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, SESSION_ID_KEYS) : undefined;\n}\n\nexport function extractRequestId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, REQUEST_ID_KEYS) : undefined;\n}\n\nexport function extractTraceId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, TRACE_ID_KEYS) : undefined;\n}\n\nexport function extractExternalUserId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, EXTERNAL_USER_ID_KEYS) : undefined;\n}\n\nexport function extractCorrelationId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, CORRELATION_ID_KEYS) : undefined;\n}\n\nconst SOURCE_SESSION_KEYS = [\n\t{ key: \"waniwani/sessionId\", source: \"chatbar\" },\n\t{ key: \"openai/sessionId\", source: \"chatgpt\" },\n\t{ key: \"openai/session\", source: \"chatgpt\" },\n\t{ key: \"anthropic/sessionId\", source: \"claude\" },\n] as const;\n\nexport function extractSource(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\tif (!meta) {\n\t\treturn undefined;\n\t}\n\t// Explicit source set by the caller (e.g. chatbar name)\n\tconst explicit = meta[\"waniwani/source\"];\n\tif (typeof explicit === \"string\" && explicit.length > 0) {\n\t\treturn explicit;\n\t}\n\t// Derive from session ID key\n\tfor (const { key, source } of SOURCE_SESSION_KEYS) {\n\t\tconst value = meta[key];\n\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\treturn source;\n\t\t}\n\t}\n\treturn undefined;\n}\n","// WaniWani SDK - Errors\n\nexport class WaniWaniError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic status: number,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"WaniWaniError\";\n\t}\n}\n","// KB Client — thin HTTP wrapper for knowledge base API\n\nimport { WaniWaniError } from \"../error.js\";\nimport type { InternalConfig } from \"../types.js\";\nimport type {\n\tKbClient,\n\tKbIngestFile,\n\tKbIngestResult,\n\tKbSearchOptions,\n\tKbSource,\n\tSearchResult,\n} from \"./types.js\";\n\nconst SDK_NAME = \"@waniwani/sdk\";\n\nexport function createKbClient(config: InternalConfig): KbClient {\n\tconst { apiUrl, apiKey } = config;\n\n\tfunction requireApiKey(): string {\n\t\tif (!apiKey) {\n\t\t\tthrow new Error(\"WANIWANI_API_KEY is not set\");\n\t\t}\n\t\treturn apiKey;\n\t}\n\n\tasync function request<T>(\n\t\tmethod: \"GET\" | \"POST\",\n\t\tpath: string,\n\t\tbody?: unknown,\n\t): Promise<T> {\n\t\tconst key = requireApiKey();\n\t\tconst url = `${apiUrl.replace(/\\/$/, \"\")}${path}`;\n\n\t\tconst headers: Record<string, string> = {\n\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\"X-WaniWani-SDK\": SDK_NAME,\n\t\t};\n\n\t\tconst init: RequestInit = { method, headers };\n\n\t\tif (body !== undefined) {\n\t\t\theaders[\"Content-Type\"] = \"application/json\";\n\t\t\tinit.body = JSON.stringify(body);\n\t\t}\n\n\t\tconst response = await fetch(url, init);\n\n\t\tif (!response.ok) {\n\t\t\tconst text = await response.text().catch(() => \"\");\n\t\t\tthrow new WaniWaniError(\n\t\t\t\ttext || `KB API error: HTTP ${response.status}`,\n\t\t\t\tresponse.status,\n\t\t\t);\n\t\t}\n\n\t\tconst json = (await response.json()) as { data: T };\n\t\treturn json.data;\n\t}\n\n\treturn {\n\t\tasync ingest(files: KbIngestFile[]): Promise<KbIngestResult> {\n\t\t\treturn request<KbIngestResult>(\"POST\", \"/api/mcp/kb/ingest\", {\n\t\t\t\tfiles,\n\t\t\t});\n\t\t},\n\n\t\tasync search(\n\t\t\tquery: string,\n\t\t\toptions?: KbSearchOptions,\n\t\t): Promise<SearchResult[]> {\n\t\t\treturn request<SearchResult[]>(\"POST\", \"/api/mcp/kb/search\", {\n\t\t\t\tquery,\n\t\t\t\t...options,\n\t\t\t});\n\t\t},\n\n\t\tasync sources(): Promise<KbSource[]> {\n\t\t\treturn request<KbSource[]>(\"GET\", \"/api/mcp/kb/sources\");\n\t\t},\n\t};\n}\n","import type { TrackingConfig } from \"./tracking/@types.js\";\n\n/**\n * Project-level configuration for WaniWani MCP projects.\n *\n * This is the single source of truth for both CLI tools (`waniwani eval`,\n * `waniwani embed`, etc.) and the runtime SDK client (`waniwani()`).\n *\n * Create a `waniwani.config.ts` at the project root:\n * ```ts\n * import { defineConfig } from \"@waniwani/sdk\";\n *\n * export default defineConfig({\n * apiKey: process.env.WANIWANI_API_KEY,\n * evals: {\n * mcpServerUrl: \"http://localhost:3001\",\n * },\n * });\n * ```\n *\n * Then import it as a side-effect to register the config globally:\n * ```ts\n * import \"./waniwani.config\";\n * import { waniwani } from \"@waniwani/sdk\";\n *\n * const wani = waniwani(); // picks up config from defineConfig\n * ```\n */\nexport interface WaniWaniProjectConfig {\n\t/**\n\t * Your MCP environment API key.\n\t * Defaults to `process.env.WANIWANI_API_KEY` if not provided.\n\t */\n\tapiKey?: string;\n\t/**\n\t * The base URL of the WaniWani API.\n\t * Defaults to `https://app.waniwani.ai`.\n\t */\n\tapiUrl?: string;\n\t/** Tracking transport behavior. */\n\ttracking?: TrackingConfig;\n\tevals?: {\n\t\t/** Path to the evals directory (relative to project root).\n\t\t *\n\t\t * @default ./evals */\n\t\tdir?: string;\n\t\t/** MCP server URL to test against. */\n\t\tmcpServerUrl: string;\n\t};\n\tknowledgeBase?: {\n\t\t/** Path to the knowledge base directory (relative to project root).\n\t\t *\n\t\t * @default ./knowledge-base\n\t\t */\n\t\tdir?: string;\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Global singleton — uses globalThis so the config is shared across all\n// SDK entry points (e.g. @waniwani/sdk and @waniwani/sdk/mcp) even when\n// they are bundled as separate chunks with their own module scopes.\n// ---------------------------------------------------------------------------\n\nconst GLOBAL_KEY = \"__waniwani_config__\" as const;\n\n/**\n * Define and register a WaniWani project configuration.\n *\n * Calling this stores the config on `globalThis` so that\n * `waniwani()` and `withWaniwani()` can read from it automatically\n * when no explicit config is passed — even across different SDK\n * entry points (`@waniwani/sdk`, `@waniwani/sdk/mcp`, etc.).\n *\n * The config is also returned for direct use.\n */\nexport function defineConfig(\n\tconfig: WaniWaniProjectConfig,\n): WaniWaniProjectConfig {\n\t(globalThis as Record<string, unknown>)[GLOBAL_KEY] = config;\n\treturn config;\n}\n\n/**\n * Retrieve the globally registered config (set by `defineConfig`).\n * Returns `undefined` if `defineConfig` has not been called.\n * @internal\n */\nexport function getGlobalConfig(): WaniWaniProjectConfig | undefined {\n\treturn (globalThis as Record<string, unknown>)[GLOBAL_KEY] as\n\t\t| WaniWaniProjectConfig\n\t\t| undefined;\n}\n","import {\n\textractCorrelationId,\n\textractExternalUserId,\n\textractRequestId,\n\textractSessionId,\n\textractSource,\n\textractTraceId,\n} from \"../mcp/server/utils.js\";\nimport type { EventType, LegacyTrackEvent, TrackInput } from \"./@types.js\";\nimport type { V2CorrelationIds, V2EventEnvelope } from \"./v2-types.js\";\n\nconst DEFAULT_SOURCE = \"@waniwani/sdk\";\n\nexport interface MapTrackEventOptions {\n\tnow?: () => Date;\n\tgenerateId?: () => string;\n\tsource?: string;\n}\n\nexport function mapTrackEventToV2(\n\tinput: TrackInput,\n\toptions: MapTrackEventOptions = {},\n): V2EventEnvelope {\n\tconst now = options.now ?? (() => new Date());\n\tconst generateId = options.generateId ?? createEventId;\n\tconst eventName = resolveEventName(input);\n\tconst meta = toRecord(input.meta);\n\tconst metadata = toRecord(input.metadata);\n\tconst correlation = resolveCorrelationIds(input, meta);\n\tconst eventId = takeNonEmptyString(input.eventId) ?? generateId();\n\tconst timestamp = normalizeTimestamp(input.timestamp, now);\n\tconst source =\n\t\ttakeNonEmptyString(input.source) ??\n\t\textractSource(meta) ??\n\t\toptions.source ??\n\t\tDEFAULT_SOURCE;\n\tconst rawLegacy = isLegacyTrackEvent(input) ? { ...input } : undefined;\n\n\tconst mappedMetadata: Record<string, unknown> = {\n\t\t...metadata,\n\t};\n\tif (Object.keys(meta).length > 0) {\n\t\tmappedMetadata.meta = meta;\n\t}\n\tif (rawLegacy) {\n\t\tmappedMetadata.rawLegacy = rawLegacy;\n\t}\n\n\treturn {\n\t\tid: eventId,\n\t\ttype: \"mcp.event\",\n\t\tname: eventName,\n\t\tsource,\n\t\ttimestamp,\n\t\tcorrelation,\n\t\tproperties: mapProperties(input, eventName),\n\t\tmetadata: mappedMetadata,\n\t\trawLegacy,\n\t};\n}\n\nexport function createEventId(): string {\n\tif (\n\t\ttypeof crypto !== \"undefined\" &&\n\t\ttypeof crypto.randomUUID === \"function\"\n\t) {\n\t\treturn `evt_${crypto.randomUUID()}`;\n\t}\n\n\treturn `evt_${Math.random().toString(36).slice(2, 10)}_${Date.now().toString(36)}`;\n}\n\nfunction mapProperties(\n\tinput: TrackInput,\n\teventName: EventType,\n): Record<string, unknown> {\n\tif (!isLegacyTrackEvent(input)) {\n\t\treturn toRecord(input.properties);\n\t}\n\n\tconst legacyProperties = mapLegacyProperties(input, eventName);\n\tconst explicitProperties = toRecord(input.properties);\n\treturn {\n\t\t...legacyProperties,\n\t\t...explicitProperties,\n\t};\n}\n\nfunction mapLegacyProperties(\n\tinput: LegacyTrackEvent,\n\teventName: EventType,\n): Record<string, unknown> {\n\tswitch (eventName) {\n\t\tcase \"tool.called\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (takeNonEmptyString(input.toolName)) {\n\t\t\t\tproperties.name = input.toolName;\n\t\t\t}\n\t\t\tif (takeNonEmptyString(input.toolType)) {\n\t\t\t\tproperties.type = input.toolType;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tcase \"quote.succeeded\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (typeof input.quoteAmount === \"number\") {\n\t\t\t\tproperties.amount = input.quoteAmount;\n\t\t\t}\n\t\t\tif (takeNonEmptyString(input.quoteCurrency)) {\n\t\t\t\tproperties.currency = input.quoteCurrency;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tcase \"link.clicked\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (takeNonEmptyString(input.linkUrl)) {\n\t\t\t\tproperties.url = input.linkUrl;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tcase \"purchase.completed\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (typeof input.purchaseAmount === \"number\") {\n\t\t\t\tproperties.amount = input.purchaseAmount;\n\t\t\t}\n\t\t\tif (takeNonEmptyString(input.purchaseCurrency)) {\n\t\t\t\tproperties.currency = input.purchaseCurrency;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tdefault:\n\t\t\treturn {};\n\t}\n}\n\nfunction resolveEventName(input: TrackInput): EventType {\n\tif (isLegacyTrackEvent(input)) {\n\t\treturn input.eventType;\n\t}\n\treturn input.event;\n}\n\nfunction resolveCorrelationIds(\n\tinput: TrackInput,\n\tmeta: Record<string, unknown>,\n): V2CorrelationIds {\n\tconst requestId =\n\t\ttakeNonEmptyString(input.requestId) ?? extractRequestId(meta);\n\n\tconst sessionId =\n\t\ttakeNonEmptyString(input.sessionId) ?? extractSessionId(meta);\n\n\tconst traceId = takeNonEmptyString(input.traceId) ?? extractTraceId(meta);\n\n\tconst externalUserId =\n\t\ttakeNonEmptyString(input.externalUserId) ?? extractExternalUserId(meta);\n\n\tconst correlationId =\n\t\ttakeNonEmptyString(input.correlationId) ??\n\t\textractCorrelationId(meta) ??\n\t\trequestId;\n\n\tconst correlation: V2CorrelationIds = {};\n\tif (sessionId) {\n\t\tcorrelation.sessionId = sessionId;\n\t}\n\tif (traceId) {\n\t\tcorrelation.traceId = traceId;\n\t}\n\tif (requestId) {\n\t\tcorrelation.requestId = requestId;\n\t}\n\tif (correlationId) {\n\t\tcorrelation.correlationId = correlationId;\n\t}\n\tif (externalUserId) {\n\t\tcorrelation.externalUserId = externalUserId;\n\t}\n\treturn correlation;\n}\n\nfunction normalizeTimestamp(\n\tinput: string | Date | undefined,\n\tnow: () => Date,\n): string {\n\tif (input instanceof Date) {\n\t\treturn input.toISOString();\n\t}\n\tif (typeof input === \"string\") {\n\t\tconst date = new Date(input);\n\t\tif (!Number.isNaN(date.getTime())) {\n\t\t\treturn date.toISOString();\n\t\t}\n\t}\n\treturn now().toISOString();\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\treturn {};\n\t}\n\treturn value as Record<string, unknown>;\n}\n\nfunction takeNonEmptyString(value: unknown): string | undefined {\n\tif (typeof value !== \"string\") {\n\t\treturn undefined;\n\t}\n\tif (value.trim().length === 0) {\n\t\treturn undefined;\n\t}\n\treturn value;\n}\n\nfunction isLegacyTrackEvent(input: TrackInput): input is LegacyTrackEvent {\n\treturn \"eventType\" in input;\n}\n","import type {\n\tTrackingShutdownOptions,\n\tTrackingShutdownResult,\n} from \"./@types.js\";\nimport type {\n\tV2BatchRejectedEvent,\n\tV2BatchRequest,\n\tV2BatchResponse,\n\tV2EventEnvelope,\n} from \"./v2-types.js\";\n\nconst DEFAULT_ENDPOINT_PATH = \"/api/mcp/events/v2/batch\";\nconst DEFAULT_FLUSH_INTERVAL_MS = 1_000;\nconst DEFAULT_MAX_BATCH_SIZE = 20;\nconst DEFAULT_MAX_BUFFER_SIZE = 1_000;\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_RETRY_BASE_DELAY_MS = 200;\nconst DEFAULT_RETRY_MAX_DELAY_MS = 2_000;\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 2_000;\nconst SDK_NAME = \"@waniwani/sdk\";\n\nconst AUTH_FAILURE_STATUS = new Set([401, 403]);\nconst RETRYABLE_STATUS = new Set([408, 425, 429, 500, 502, 503, 504]);\n\ninterface Logger {\n\twarn: (message: string, ...args: unknown[]) => void;\n\terror: (message: string, ...args: unknown[]) => void;\n}\n\nexport interface V2TransportOptions {\n\tapiUrl: string;\n\tapiKey: string;\n\tendpointPath?: string;\n\tflushIntervalMs?: number;\n\tmaxBatchSize?: number;\n\tmaxBufferSize?: number;\n\tmaxRetries?: number;\n\tretryBaseDelayMs?: number;\n\tretryMaxDelayMs?: number;\n\tshutdownTimeoutMs?: number;\n\tsdkVersion?: string;\n\tfetchFn?: typeof fetch;\n\tlogger?: Logger;\n\tnow?: () => Date;\n\tsleep?: (delayMs: number) => Promise<void>;\n}\n\nexport interface V2BatchTransport {\n\tenqueue: (event: V2EventEnvelope) => void;\n\tflush: () => Promise<void>;\n\tshutdown: (\n\t\toptions?: TrackingShutdownOptions,\n\t) => Promise<TrackingShutdownResult>;\n\tpendingEvents: () => number;\n}\n\ntype SendBatchResult =\n\t| { kind: \"success\" }\n\t| { kind: \"retryable\"; reason: string }\n\t| { kind: \"permanent\"; reason: string }\n\t| { kind: \"auth\"; status: number }\n\t| {\n\t\t\tkind: \"partial\";\n\t\t\tretryable: V2EventEnvelope[];\n\t\t\tpermanent: V2EventEnvelope[];\n\t };\n\nexport function createV2BatchTransport(\n\toptions: V2TransportOptions,\n): V2BatchTransport {\n\treturn new BatchingV2Transport(options);\n}\n\nclass BatchingV2Transport implements V2BatchTransport {\n\tprivate readonly endpointUrl: string;\n\tprivate readonly flushIntervalMs: number;\n\tprivate readonly maxBatchSize: number;\n\tprivate readonly maxBufferSize: number;\n\tprivate readonly maxRetries: number;\n\tprivate readonly retryBaseDelayMs: number;\n\tprivate readonly retryMaxDelayMs: number;\n\tprivate readonly shutdownTimeoutMs: number;\n\tprivate readonly sdkVersion?: string;\n\tprivate readonly fetchFn: typeof fetch;\n\tprivate readonly logger: Logger;\n\tprivate readonly now: () => Date;\n\tprivate readonly sleep: (delayMs: number) => Promise<void>;\n\tprivate readonly apiKey: string;\n\n\tprivate readonly buffer: V2EventEnvelope[] = [];\n\tprivate flushTimer: ReturnType<typeof setInterval> | undefined;\n\tprivate flushScheduled = false;\n\tprivate flushScheduledTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate flushInFlight: Promise<void> | undefined;\n\tprivate inFlightCount = 0;\n\tprivate isStopped = false;\n\tprivate isShuttingDown = false;\n\n\tconstructor(options: V2TransportOptions) {\n\t\tthis.endpointUrl = joinUrl(\n\t\t\toptions.apiUrl,\n\t\t\toptions.endpointPath ?? DEFAULT_ENDPOINT_PATH,\n\t\t);\n\t\tthis.flushIntervalMs = options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;\n\t\tthis.maxBatchSize = options.maxBatchSize ?? DEFAULT_MAX_BATCH_SIZE;\n\t\tthis.maxBufferSize = options.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE;\n\t\tthis.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n\t\tthis.retryBaseDelayMs =\n\t\t\toptions.retryBaseDelayMs ?? DEFAULT_RETRY_BASE_DELAY_MS;\n\t\tthis.retryMaxDelayMs =\n\t\t\toptions.retryMaxDelayMs ?? DEFAULT_RETRY_MAX_DELAY_MS;\n\t\tthis.shutdownTimeoutMs =\n\t\t\toptions.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;\n\t\tthis.fetchFn = options.fetchFn ?? fetch;\n\t\tthis.logger = options.logger ?? console;\n\t\tthis.now = options.now ?? (() => new Date());\n\t\tthis.sleep =\n\t\t\toptions.sleep ??\n\t\t\t((delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)));\n\t\tthis.apiKey = options.apiKey;\n\t\tthis.sdkVersion = options.sdkVersion;\n\n\t\tif (this.flushIntervalMs > 0) {\n\t\t\tthis.flushTimer = setInterval(() => {\n\t\t\t\tvoid this.flush();\n\t\t\t}, this.flushIntervalMs);\n\t\t}\n\t}\n\n\tenqueue(event: V2EventEnvelope): void {\n\t\tif (this.isStopped || this.isShuttingDown) {\n\t\t\tthis.logger.warn(\n\t\t\t\t\"[WaniWani] Tracking transport is stopped, dropping event %s\",\n\t\t\t\tevent.id,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.buffer.length >= this.maxBufferSize) {\n\t\t\tconst dropCount = this.buffer.length - this.maxBufferSize + 1;\n\t\t\tthis.buffer.splice(0, dropCount);\n\t\t\tthis.logger.warn(\n\t\t\t\t\"[WaniWani] Tracking buffer overflow, dropped %d oldest event(s)\",\n\t\t\t\tdropCount,\n\t\t\t);\n\t\t}\n\n\t\tthis.buffer.push(event);\n\n\t\tif (this.buffer.length >= this.maxBatchSize) {\n\t\t\tvoid this.flush();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.scheduleMicroFlush();\n\t}\n\n\tpendingEvents(): number {\n\t\treturn this.buffer.length + this.inFlightCount;\n\t}\n\n\tasync flush(): Promise<void> {\n\t\tif (this.flushInFlight) {\n\t\t\treturn this.flushInFlight;\n\t\t}\n\t\tthis.flushInFlight = this.flushLoop().finally(() => {\n\t\t\tthis.flushInFlight = undefined;\n\t\t});\n\t\treturn this.flushInFlight;\n\t}\n\n\tasync shutdown(\n\t\toptions?: TrackingShutdownOptions,\n\t): Promise<TrackingShutdownResult> {\n\t\tthis.isShuttingDown = true;\n\t\tif (this.flushTimer) {\n\t\t\tclearInterval(this.flushTimer);\n\t\t\tthis.flushTimer = undefined;\n\t\t}\n\t\tif (this.flushScheduledTimer) {\n\t\t\tclearTimeout(this.flushScheduledTimer);\n\t\t\tthis.flushScheduledTimer = undefined;\n\t\t\tthis.flushScheduled = false;\n\t\t}\n\n\t\tconst timeoutMs = options?.timeoutMs ?? this.shutdownTimeoutMs;\n\t\tconst flushPromise = this.flush();\n\n\t\tif (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n\t\t\tawait flushPromise;\n\t\t\tthis.isStopped = true;\n\t\t\treturn { timedOut: false, pendingEvents: this.pendingEvents() };\n\t\t}\n\n\t\tconst timeoutSignal = Symbol(\"shutdown-timeout\");\n\t\tconst result = await Promise.race([\n\t\t\tflushPromise.then(() => \"flushed\" as const),\n\t\t\tthis.sleep(timeoutMs).then(() => timeoutSignal),\n\t\t]);\n\n\t\tif (result === timeoutSignal) {\n\t\t\tthis.isStopped = true;\n\t\t\treturn { timedOut: true, pendingEvents: this.pendingEvents() };\n\t\t}\n\n\t\tthis.isStopped = true;\n\t\treturn { timedOut: false, pendingEvents: this.pendingEvents() };\n\t}\n\n\tprivate scheduleMicroFlush(): void {\n\t\tif (this.flushScheduled) {\n\t\t\treturn;\n\t\t}\n\t\tthis.flushScheduled = true;\n\t\tthis.flushScheduledTimer = setTimeout(() => {\n\t\t\tthis.flushScheduledTimer = undefined;\n\t\t\tthis.flushScheduled = false;\n\t\t\tvoid this.flush();\n\t\t}, 0);\n\t}\n\n\tprivate async flushLoop(): Promise<void> {\n\t\twhile (this.buffer.length > 0 && !this.isStopped) {\n\t\t\tconst batch = this.buffer.splice(0, this.maxBatchSize);\n\t\t\tawait this.sendBatchWithRetry(batch);\n\t\t}\n\t}\n\n\tprivate async sendBatchWithRetry(batch: V2EventEnvelope[]): Promise<void> {\n\t\tlet attempt = 0;\n\t\tlet pendingBatch = batch;\n\n\t\twhile (pendingBatch.length > 0 && !this.isStopped) {\n\t\t\tthis.inFlightCount = pendingBatch.length;\n\t\t\tconst result = await this.sendBatchOnce(pendingBatch);\n\t\t\tthis.inFlightCount = 0;\n\n\t\t\tswitch (result.kind) {\n\t\t\t\tcase \"success\":\n\t\t\t\t\treturn;\n\t\t\t\tcase \"auth\":\n\t\t\t\t\tthis.stopTransportForAuthFailure(result.status, pendingBatch.length);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"permanent\":\n\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\"[WaniWani] Dropping %d event(s) after permanent failure: %s\",\n\t\t\t\t\t\tpendingBatch.length,\n\t\t\t\t\t\tresult.reason,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"retryable\":\n\t\t\t\t\tif (attempt >= this.maxRetries) {\n\t\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\t\"[WaniWani] Dropping %d event(s) after retry exhaustion: %s\",\n\t\t\t\t\t\t\tpendingBatch.length,\n\t\t\t\t\t\t\tresult.reason,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tawait this.sleep(this.backoffDelayMs(attempt));\n\t\t\t\t\tattempt += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\tcase \"partial\":\n\t\t\t\t\tif (result.permanent.length > 0) {\n\t\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\t\"[WaniWani] Dropping %d event(s) rejected as permanent\",\n\t\t\t\t\t\t\tresult.permanent.length,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (result.retryable.length === 0) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (attempt >= this.maxRetries) {\n\t\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\t\"[WaniWani] Dropping %d retryable event(s) after retry exhaustion\",\n\t\t\t\t\t\t\tresult.retryable.length,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tpendingBatch = result.retryable;\n\t\t\t\t\tawait this.sleep(this.backoffDelayMs(attempt));\n\t\t\t\t\tattempt += 1;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async sendBatchOnce(\n\t\tevents: V2EventEnvelope[],\n\t): Promise<SendBatchResult> {\n\t\tlet response: Response;\n\n\t\ttry {\n\t\t\tresponse = await this.fetchFn(this.endpointUrl, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tAuthorization: `Bearer ${this.apiKey}`,\n\t\t\t\t\t\"X-WaniWani-SDK\": SDK_NAME,\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(this.makeBatchRequest(events)),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tkind: \"retryable\",\n\t\t\t\treason: getErrorMessage(error),\n\t\t\t};\n\t\t}\n\n\t\tif (AUTH_FAILURE_STATUS.has(response.status)) {\n\t\t\treturn { kind: \"auth\", status: response.status };\n\t\t}\n\n\t\tif (RETRYABLE_STATUS.has(response.status)) {\n\t\t\treturn {\n\t\t\t\tkind: \"retryable\",\n\t\t\t\treason: `HTTP ${response.status}`,\n\t\t\t};\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\treturn {\n\t\t\t\tkind: \"permanent\",\n\t\t\t\treason: `HTTP ${response.status}`,\n\t\t\t};\n\t\t}\n\n\t\tconst data = await parseJsonResponse<V2BatchResponse>(response);\n\t\tif (!data?.rejected || data.rejected.length === 0) {\n\t\t\treturn { kind: \"success\" };\n\t\t}\n\n\t\tconst partial = this.classifyRejectedEvents(events, data.rejected);\n\t\tif (partial.retryable.length === 0 && partial.permanent.length === 0) {\n\t\t\treturn { kind: \"success\" };\n\t\t}\n\n\t\treturn {\n\t\t\tkind: \"partial\",\n\t\t\tretryable: partial.retryable,\n\t\t\tpermanent: partial.permanent,\n\t\t};\n\t}\n\n\tprivate makeBatchRequest(events: V2EventEnvelope[]): V2BatchRequest {\n\t\treturn {\n\t\t\tsentAt: this.now().toISOString(),\n\t\t\tsource: {\n\t\t\t\tsdk: SDK_NAME,\n\t\t\t\tversion: this.sdkVersion ?? \"0.0.0\",\n\t\t\t},\n\t\t\tevents,\n\t\t};\n\t}\n\n\tprivate classifyRejectedEvents(\n\t\tevents: V2EventEnvelope[],\n\t\trejected: V2BatchRejectedEvent[],\n\t): {\n\t\tretryable: V2EventEnvelope[];\n\t\tpermanent: V2EventEnvelope[];\n\t} {\n\t\tconst byId = new Map(events.map((event) => [event.id, event]));\n\t\tconst retryable: V2EventEnvelope[] = [];\n\t\tconst permanent: V2EventEnvelope[] = [];\n\n\t\tfor (const rejectedEvent of rejected) {\n\t\t\tconst event = byId.get(rejectedEvent.eventId);\n\t\t\tif (!event) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isRetryableRejectedEvent(rejectedEvent)) {\n\t\t\t\tretryable.push(event);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tpermanent.push(event);\n\t\t}\n\n\t\treturn { retryable, permanent };\n\t}\n\n\tprivate backoffDelayMs(attempt: number): number {\n\t\tconst rawDelay = this.retryBaseDelayMs * 2 ** attempt;\n\t\treturn Math.min(rawDelay, this.retryMaxDelayMs);\n\t}\n\n\tprivate stopTransportForAuthFailure(\n\t\tstatus: number,\n\t\trejectedCount: number,\n\t): void {\n\t\tthis.isStopped = true;\n\t\tconst buffered = this.buffer.length;\n\t\tthis.buffer.splice(0, buffered);\n\t\tthis.logger.error(\n\t\t\t\"[WaniWani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)\",\n\t\t\tstatus,\n\t\t\trejectedCount + buffered,\n\t\t);\n\t}\n}\n\nfunction isRetryableRejectedEvent(\n\trejectedEvent: V2BatchRejectedEvent,\n): boolean {\n\tif (rejectedEvent.retryable === true) {\n\t\treturn true;\n\t}\n\tconst code = rejectedEvent.code.toLowerCase();\n\treturn (\n\t\tcode.includes(\"timeout\") ||\n\t\tcode.includes(\"temporary\") ||\n\t\tcode.includes(\"unavailable\") ||\n\t\tcode.includes(\"rate_limit\") ||\n\t\tcode.includes(\"transient\") ||\n\t\tcode.includes(\"server\")\n\t);\n}\n\nasync function parseJsonResponse<T>(\n\tresponse: Response,\n): Promise<T | undefined> {\n\tconst body = await response.text();\n\tif (!body) {\n\t\treturn undefined;\n\t}\n\ttry {\n\t\treturn JSON.parse(body) as T;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction joinUrl(apiUrl: string, endpointPath: string): string {\n\tconst normalizedBase = apiUrl.endsWith(\"/\") ? apiUrl : `${apiUrl}/`;\n\tconst normalizedPath = endpointPath.startsWith(\"/\")\n\t\t? endpointPath.slice(1)\n\t\t: endpointPath;\n\treturn `${normalizedBase}${normalizedPath}`;\n}\n\nfunction getErrorMessage(error: unknown): string {\n\tif (error instanceof Error) {\n\t\treturn error.message;\n\t}\n\treturn String(error);\n}\n","// Tracking Module\n\nimport type { InternalConfig } from \"../types.js\";\nimport type {\n\tTrackInput,\n\tTrackingClient,\n\tTrackingShutdownOptions,\n} from \"./@types.js\";\nimport { mapTrackEventToV2 } from \"./mapper.js\";\nimport { createV2BatchTransport } from \"./transport.js\";\n\n// Re-export types\nexport type {\n\tEventType,\n\tLegacyTrackEvent,\n\tLinkClickedProperties,\n\tPurchaseCompletedProperties,\n\tQuoteSucceededProperties,\n\tToolCalledProperties,\n\tTrackEvent,\n\tTrackInput,\n\tTrackingClient,\n\tTrackingConfig,\n\tTrackingShutdownOptions,\n\tTrackingShutdownResult,\n} from \"./@types.js\";\nexport { createEventId, mapTrackEventToV2 } from \"./mapper.js\";\nexport type {\n\tV2BatchRejectedEvent,\n\tV2BatchRequest,\n\tV2BatchResponse,\n\tV2CorrelationIds,\n\tV2EnvelopeType,\n\tV2EventEnvelope,\n} from \"./v2-types.js\";\n\nexport function createTrackingClient(config: InternalConfig): TrackingClient {\n\tconst { apiUrl, apiKey, tracking } = config;\n\n\tfunction requireApiKey(): string {\n\t\tif (!apiKey) {\n\t\t\tthrow new Error(\"WANIWANI_API_KEY is not set\");\n\t\t}\n\t\treturn apiKey;\n\t}\n\n\tconst transport = apiKey\n\t\t? createV2BatchTransport({\n\t\t\t\tapiUrl,\n\t\t\t\tapiKey,\n\t\t\t\tendpointPath: tracking.endpointPath,\n\t\t\t\tflushIntervalMs: tracking.flushIntervalMs,\n\t\t\t\tmaxBatchSize: tracking.maxBatchSize,\n\t\t\t\tmaxBufferSize: tracking.maxBufferSize,\n\t\t\t\tmaxRetries: tracking.maxRetries,\n\t\t\t\tretryBaseDelayMs: tracking.retryBaseDelayMs,\n\t\t\t\tretryMaxDelayMs: tracking.retryMaxDelayMs,\n\t\t\t\tshutdownTimeoutMs: tracking.shutdownTimeoutMs,\n\t\t\t})\n\t\t: undefined;\n\n\tconst client: TrackingClient = {\n\t\tasync identify(\n\t\t\tuserId: string,\n\t\t\tproperties?: Record<string, unknown>,\n\t\t\tmeta?: Record<string, unknown>,\n\t\t): Promise<{ eventId: string }> {\n\t\t\trequireApiKey();\n\t\t\tconst mappedEvent = mapTrackEventToV2({\n\t\t\t\tevent: \"user.identified\",\n\t\t\t\texternalUserId: userId,\n\t\t\t\tproperties,\n\t\t\t\tmeta,\n\t\t\t});\n\t\t\ttransport?.enqueue(mappedEvent);\n\t\t\treturn { eventId: mappedEvent.id };\n\t\t},\n\t\tasync track(event: TrackInput): Promise<{ eventId: string }> {\n\t\t\trequireApiKey();\n\t\t\tconst mappedEvent = mapTrackEventToV2(event);\n\t\t\ttransport?.enqueue(mappedEvent);\n\t\t\treturn { eventId: mappedEvent.id };\n\t\t},\n\t\tasync flush(): Promise<void> {\n\t\t\trequireApiKey();\n\t\t\tawait transport?.flush();\n\t\t},\n\t\tasync shutdown(options?: TrackingShutdownOptions) {\n\t\t\trequireApiKey();\n\t\t\treturn (\n\t\t\t\t(await transport?.shutdown({\n\t\t\t\t\ttimeoutMs: options?.timeoutMs ?? tracking.shutdownTimeoutMs,\n\t\t\t\t})) ?? { timedOut: false, pendingEvents: 0 }\n\t\t\t);\n\t\t},\n\t};\n\n\tif (transport) {\n\t\tattachShutdownHooks(client, tracking.shutdownTimeoutMs);\n\t}\n\treturn client;\n}\n\nfunction attachShutdownHooks(\n\tclient: TrackingClient,\n\tdefaultTimeoutMs: number,\n): void {\n\tif (\n\t\ttypeof process === \"undefined\" ||\n\t\ttypeof process.once !== \"function\" ||\n\t\ttypeof process.on !== \"function\"\n\t) {\n\t\treturn;\n\t}\n\n\tconst shutdown = () => {\n\t\tvoid client.shutdown({ timeoutMs: defaultTimeoutMs });\n\t};\n\n\tprocess.once(\"beforeExit\", shutdown);\n\tprocess.once(\"SIGINT\", shutdown);\n\tprocess.once(\"SIGTERM\", shutdown);\n}\n","// WaniWani SDK - Main Entry\n\nimport { createKbClient } from \"./kb/client.js\";\nimport type { WaniWaniProjectConfig } from \"./project-config.js\";\nimport { getGlobalConfig } from \"./project-config.js\";\nimport { createTrackingClient } from \"./tracking/index.js\";\nimport type { WaniWaniClient, WaniWaniConfig } from \"./types.js\";\n\n/**\n * Create a WaniWani SDK client\n *\n * @param config - Configuration options. When omitted, reads from the global\n * config registered by `defineConfig()`, then falls back to env vars.\n * @returns A fully typed WaniWani client\n *\n * @example\n * ```typescript\n * import { waniwani } from \"@waniwani/sdk\";\n * import { toNextJsHandler } from \"@waniwani/sdk/next-js\";\n *\n * const wani = waniwani({ apiKey: \"...\" });\n *\n * // Next.js route handler\n * export const { GET, POST } = toNextJsHandler(wani, {\n * chat: { systemPrompt: \"You are a helpful assistant.\" },\n * });\n * ```\n */\nexport function waniwani(\n\tconfig?: WaniWaniConfig | WaniWaniProjectConfig,\n): WaniWaniClient {\n\tconst effective = config ?? getGlobalConfig();\n\n\tconst apiUrl = effective?.apiUrl ?? \"https://app.waniwani.ai\";\n\tconst apiKey = effective?.apiKey ?? process.env.WANIWANI_API_KEY;\n\tconst trackingConfig = {\n\t\tendpointPath:\n\t\t\teffective?.tracking?.endpointPath ?? \"/api/mcp/events/v2/batch\",\n\t\tflushIntervalMs: effective?.tracking?.flushIntervalMs ?? 1_000,\n\t\tmaxBatchSize: effective?.tracking?.maxBatchSize ?? 20,\n\t\tmaxBufferSize: effective?.tracking?.maxBufferSize ?? 1_000,\n\t\tmaxRetries: effective?.tracking?.maxRetries ?? 3,\n\t\tretryBaseDelayMs: effective?.tracking?.retryBaseDelayMs ?? 200,\n\t\tretryMaxDelayMs: effective?.tracking?.retryMaxDelayMs ?? 2_000,\n\t\tshutdownTimeoutMs: effective?.tracking?.shutdownTimeoutMs ?? 2_000,\n\t};\n\n\tconst internalConfig = { apiUrl, apiKey, tracking: trackingConfig };\n\n\t// Compose client from modules\n\tconst trackingClient = createTrackingClient(internalConfig);\n\tconst kbClient = createKbClient(internalConfig);\n\n\treturn {\n\t\t...trackingClient,\n\t\tkb: kbClient,\n\t\t_config: internalConfig,\n\t};\n}\n","/**\n * Generic key-value store backed by the WaniWani API.\n *\n * Values are stored as JSON objects (`Record<string, unknown>`) in the\n * `/api/mcp/redis/*` endpoints. Tenant isolation is handled by the API key.\n *\n * This is the generic version — `WaniwaniFlowStore` uses this under the hood\n * with `FlowTokenContent` as the value type.\n */\n\nimport { getGlobalConfig } from \"../../../project-config.js\";\n\n// ============================================================================\n// Interface\n// ============================================================================\n\nexport interface KvStore<T = Record<string, unknown>> {\n\tget(key: string): Promise<T | null>;\n\tset(key: string, value: T): Promise<void>;\n\tdelete(key: string): Promise<void>;\n}\n\n// ============================================================================\n// WaniWani API implementation\n// ============================================================================\n\nconst SDK_NAME = \"@waniwani/sdk\";\nconst DEFAULT_BASE_URL = \"https://app.waniwani.ai\";\n\nexport interface KvStoreOptions {\n\tapiUrl?: string;\n\tapiKey?: string;\n}\n\nexport class WaniwaniKvStore<T = Record<string, unknown>>\n\timplements KvStore<T>\n{\n\tprivate readonly baseUrl: string;\n\tprivate readonly apiKey: string | undefined;\n\n\tconstructor(options?: KvStoreOptions) {\n\t\tconst globalConfig = getGlobalConfig();\n\n\t\t// order: options.apiUrl, process.env.WANIWANI_API_URL, globalConfig?.apiUrl, DEFAULT_BASE_URL\n\t\tthis.baseUrl = (\n\t\t\toptions?.apiUrl ??\n\t\t\tprocess.env.WANIWANI_API_URL ??\n\t\t\tglobalConfig?.apiUrl ??\n\t\t\tDEFAULT_BASE_URL\n\t\t).replace(/\\/$/, \"\");\n\n\t\t// order: options.apiKey, process.env.WANIWANI_API_KEY, globalConfig?.apiKey\n\t\tthis.apiKey =\n\t\t\toptions?.apiKey ?? process.env.WANIWANI_API_KEY ?? globalConfig?.apiKey;\n\t}\n\n\tasync get(key: string): Promise<T | null> {\n\t\tif (!this.apiKey) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[WaniWani KV] No API key configured. Set WANIWANI_API_KEY or pass apiKey in options.\",\n\t\t\t);\n\t\t}\n\t\tconst data = await this.request<T | null>(\"/api/mcp/redis/get\", { key });\n\t\treturn data ?? null;\n\t}\n\n\tasync set(key: string, value: T): Promise<void> {\n\t\tif (!this.apiKey) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[WaniWani KV] No API key configured. Set WANIWANI_API_KEY or pass apiKey in options.\",\n\t\t\t);\n\t\t}\n\t\tawait this.request(\"/api/mcp/redis/set\", { key, value });\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\tif (!this.apiKey) {\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tawait this.request(\"/api/mcp/redis/delete\", { key });\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[WaniWani KV] delete failed for key:\", key, error);\n\t\t}\n\t}\n\n\tprivate async request<R>(path: string, body: unknown): Promise<R> {\n\t\tconst url = `${this.baseUrl}${path}`;\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${this.apiKey}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\"X-WaniWani-SDK\": SDK_NAME,\n\t\t\t},\n\t\t\tbody: JSON.stringify(body),\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst text = await response.text().catch(() => \"\");\n\t\t\tthrow new Error(text || `KV store API error: HTTP ${response.status}`);\n\t\t}\n\n\t\tconst json = (await response.json()) as { data: R };\n\t\treturn json.data;\n\t}\n}\n","/**\n * Server-side flow state store.\n *\n * Flow state is stored via the WaniWani API, keyed by session ID.\n * The session ID comes from _meta (provided by the MCP client on every call),\n * so the LLM doesn't need to round-trip anything.\n *\n * Tenant isolation is handled by the API key — no manual key prefixing needed.\n *\n * The `FlowStore` interface is exported for custom implementations.\n */\n\nimport { type KvStoreOptions, WaniwaniKvStore } from \"../kv\";\nimport type { FlowTokenContent } from \"./@types\";\n\n// ============================================================================\n// Interface\n// ============================================================================\n\nexport interface FlowStore {\n\tget(key: string): Promise<FlowTokenContent | null>;\n\tset(key: string, value: FlowTokenContent): Promise<void>;\n\tdelete(key: string): Promise<void>;\n}\n\n// ============================================================================\n// WaniWani API implementation\n// ============================================================================\n\nexport class WaniwaniFlowStore implements FlowStore {\n\tprivate readonly store: WaniwaniKvStore<FlowTokenContent>;\n\n\tconstructor(options?: KvStoreOptions) {\n\t\tthis.store = new WaniwaniKvStore<FlowTokenContent>(options);\n\t}\n\n\tget(key: string): Promise<FlowTokenContent | null> {\n\t\treturn this.store.get(key);\n\t}\n\n\tset(key: string, value: FlowTokenContent): Promise<void> {\n\t\treturn this.store.set(key, value);\n\t}\n\n\tdelete(key: string): Promise<void> {\n\t\treturn this.store.delete(key);\n\t}\n}\n","/**\n * Widget token minting — fetches short-lived JWTs from the WaniWani backend\n * so browser widgets can POST events directly.\n */\n\ninterface WidgetTokenConfig {\n\tapiUrl: string;\n\tapiKey: string;\n}\n\ninterface WidgetTokenResult {\n\ttoken: string;\n\texpiresAt: string;\n}\n\ninterface CachedToken {\n\ttoken: string;\n\t/** Unix ms when the token expires */\n\texpiresAt: number;\n}\n\n/** Re-mint when < 2 minutes remain to avoid using nearly-expired tokens. */\nconst EXPIRY_BUFFER_MS = 2 * 60 * 1000;\n\nexport class WidgetTokenCache {\n\tprivate cached: CachedToken | null = null;\n\tprivate pending: Promise<string | null> | null = null;\n\tprivate readonly config: WidgetTokenConfig;\n\n\tconstructor(config: WidgetTokenConfig) {\n\t\tthis.config = config;\n\t}\n\n\t/**\n\t * Get a valid widget token. Returns a cached token if still fresh,\n\t * otherwise mints a new one. Returns `null` on failure.\n\t */\n\tasync getToken(sessionId?: string, traceId?: string): Promise<string | null> {\n\t\tif (this.cached && Date.now() < this.cached.expiresAt - EXPIRY_BUFFER_MS) {\n\t\t\treturn this.cached.token;\n\t\t}\n\n\t\t// Deduplicate concurrent requests\n\t\tif (this.pending) {\n\t\t\treturn this.pending;\n\t\t}\n\n\t\tthis.pending = this.mint(sessionId, traceId).finally(() => {\n\t\t\tthis.pending = null;\n\t\t});\n\n\t\treturn this.pending;\n\t}\n\n\tprivate async mint(\n\t\tsessionId?: string,\n\t\ttraceId?: string,\n\t): Promise<string | null> {\n\t\tconst url = joinUrl(this.config.apiUrl, \"/api/mcp/widget-tokens\");\n\n\t\tconst body: Record<string, string> = {};\n\t\tif (sessionId) {\n\t\t\tbody.sessionId = sessionId;\n\t\t}\n\t\tif (traceId) {\n\t\t\tbody.traceId = traceId;\n\t\t}\n\n\t\ttry {\n\t\t\tconst response = await fetch(url, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tAuthorization: `Bearer ${this.config.apiKey}`,\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst json = (await response.json()) as Record<string, unknown>;\n\n\t\t\t// Support both flat { token, expiresAt } and nested { data: { token, expiresAt } }\n\t\t\tconst result = (\n\t\t\t\tjson.data && typeof json.data === \"object\" ? json.data : json\n\t\t\t) as WidgetTokenResult;\n\n\t\t\tconst expiresAtMs = new Date(result.expiresAt).getTime();\n\t\t\tif (!result.token || Number.isNaN(expiresAtMs)) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tthis.cached = {\n\t\t\t\ttoken: result.token,\n\t\t\t\texpiresAt: expiresAtMs,\n\t\t\t};\n\n\t\t\treturn result.token;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n}\n\nfunction joinUrl(apiUrl: string, path: string): string {\n\tconst base = apiUrl.endsWith(\"/\") ? apiUrl.slice(0, -1) : apiUrl;\n\treturn `${base}${path}`;\n}\n","import type {\n\tToolCalledProperties,\n\tTrackInput,\n} from \"../../../tracking/index.js\";\nimport type { WaniWaniClient } from \"../../../types.js\";\nimport { extractSessionId, extractSource } from \"../utils.js\";\nimport type { WidgetTokenCache } from \"../widget-token.js\";\n\ntype UnknownRecord = Record<string, unknown>;\n\nexport type WaniwaniTracker = Pick<\n\tWaniWaniClient,\n\t\"flush\" | \"track\" | \"identify\" | \"kb\" | \"_config\"\n>;\n\nconst SESSION_ID_KEY = \"waniwani/sessionId\";\nconst GEO_LOCATION_KEY = \"waniwani/geoLocation\";\nconst LEGACY_USER_LOCATION_KEY = \"waniwani/userLocation\";\n\nexport function isRecord(value: unknown): value is UnknownRecord {\n\treturn Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function extractMeta(extra: unknown): UnknownRecord | undefined {\n\tif (!isRecord(extra)) {\n\t\treturn undefined;\n\t}\n\tconst meta = extra._meta;\n\treturn isRecord(meta) ? meta : undefined;\n}\n\nexport function extractErrorText(result: unknown): string | undefined {\n\tif (!isRecord(result)) {\n\t\treturn undefined;\n\t}\n\tconst content = (result as UnknownRecord).content;\n\tif (!Array.isArray(content)) {\n\t\treturn undefined;\n\t}\n\tconst textPart = content.find(\n\t\t(c: unknown) =>\n\t\t\tisRecord(c) && c.type === \"text\" && typeof c.text === \"string\",\n\t) as UnknownRecord | undefined;\n\treturn textPart?.text as string | undefined;\n}\n\nexport function resolveToolType(\n\ttoolName: string,\n\ttoolTypeOption:\n\t\t| ToolCalledProperties[\"type\"]\n\t\t| ((toolName: string) => ToolCalledProperties[\"type\"] | undefined)\n\t\t| undefined,\n): ToolCalledProperties[\"type\"] {\n\tif (typeof toolTypeOption === \"function\") {\n\t\treturn toolTypeOption(toolName) ?? \"other\";\n\t}\n\treturn toolTypeOption ?? \"other\";\n}\n\nexport function buildTrackInput(\n\ttoolName: string,\n\textra: unknown,\n\toptions: {\n\t\ttoolType?: typeof resolveToolType extends (n: string, o: infer T) => unknown\n\t\t\t? T\n\t\t\t: never;\n\t\tmetadata?: UnknownRecord;\n\t},\n\ttiming?: { durationMs: number; status: string; errorMessage?: string },\n\tclientInfo?: { name: string; version: string },\n\tio?: { input?: unknown; output?: unknown },\n): TrackInput {\n\tconst toolType = resolveToolType(toolName, options.toolType);\n\tconst meta = extractMeta(extra);\n\tconsole.log(\n\t\t\"[waniwani:debug] buildTrackInput meta:\",\n\t\tJSON.stringify(meta),\n\t\t\"-> source:\",\n\t\textractSource(meta),\n\t);\n\n\treturn {\n\t\tevent: \"tool.called\",\n\t\tproperties: {\n\t\t\tname: toolName,\n\t\t\ttype: toolType,\n\t\t\t...(timing ?? {}),\n\t\t\t...(io?.input !== undefined && { input: io.input }),\n\t\t\t...(io?.output !== undefined && { output: io.output }),\n\t\t},\n\t\tmeta,\n\t\tsource: extractSource(meta),\n\t\tmetadata: {\n\t\t\t...(options.metadata ?? {}),\n\t\t\t...(clientInfo && { clientInfo }),\n\t\t},\n\t};\n}\n\nexport async function safeTrack(\n\ttracker: Pick<WaniWaniClient, \"track\">,\n\tinput: TrackInput,\n\tonError?: (error: Error) => void,\n): Promise<void> {\n\ttry {\n\t\tawait tracker.track(input);\n\t} catch (error) {\n\t\tonError?.(toError(error));\n\t}\n}\n\nexport async function safeFlush(\n\ttracker: Pick<WaniWaniClient, \"flush\">,\n\tonError?: (error: Error) => void,\n): Promise<void> {\n\ttry {\n\t\tawait tracker.flush();\n\t} catch (error) {\n\t\tonError?.(toError(error));\n\t}\n}\n\nexport async function injectWidgetConfig(\n\tresult: unknown,\n\tcache: WidgetTokenCache | null,\n\tapiUrl: string,\n\textra?: unknown,\n\tonError?: (error: Error) => void,\n): Promise<void> {\n\tif (!isRecord(result)) {\n\t\treturn;\n\t}\n\n\tif (!isRecord(result._meta)) {\n\t\t(result as UnknownRecord)._meta = {};\n\t}\n\n\tconst meta = (result as UnknownRecord)._meta as UnknownRecord;\n\tconst existingWaniwaniConfig = isRecord(meta.waniwani)\n\t\t? (meta.waniwani as UnknownRecord)\n\t\t: undefined;\n\tconst waniwaniConfig: UnknownRecord = {\n\t\t...(existingWaniwaniConfig ?? {}),\n\t\tendpoint:\n\t\t\texistingWaniwaniConfig?.endpoint ??\n\t\t\t`${apiUrl.replace(/\\/$/, \"\")}/api/mcp/events/v2/batch`,\n\t};\n\n\tif (cache) {\n\t\ttry {\n\t\t\tconst token = await cache.getToken();\n\t\t\tif (token) {\n\t\t\t\twaniwaniConfig.token = token;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tonError?.(toError(error));\n\t\t}\n\t}\n\n\tconst sessionId = extractSessionId(meta);\n\tif (sessionId) {\n\t\tif (!waniwaniConfig.sessionId) {\n\t\t\twaniwaniConfig.sessionId = sessionId;\n\t\t}\n\t}\n\n\tconst geoLocation = extractGeoLocation(meta);\n\tif (geoLocation !== undefined) {\n\t\tif (!waniwaniConfig.geoLocation) {\n\t\t\twaniwaniConfig.geoLocation = geoLocation;\n\t\t}\n\t}\n\n\tconst source = extractSource(extractMeta(extra));\n\tif (source && !waniwaniConfig.source) {\n\t\twaniwaniConfig.source = source;\n\t}\n\n\tmeta.waniwani = waniwaniConfig;\n}\n\nexport function injectRequestMetadata(result: unknown, extra: unknown): void {\n\tconst requestMeta = extractMeta(extra);\n\tif (!requestMeta) {\n\t\treturn;\n\t}\n\n\tif (!isRecord(result)) {\n\t\treturn;\n\t}\n\n\tif (!isRecord(result._meta)) {\n\t\t(result as UnknownRecord)._meta = {};\n\t}\n\n\tconst resultMeta = (result as UnknownRecord)._meta as UnknownRecord;\n\tconst sessionId = extractSessionId(requestMeta);\n\tif (sessionId && !resultMeta[SESSION_ID_KEY]) {\n\t\tresultMeta[SESSION_ID_KEY] = sessionId;\n\t}\n\n\tconst geoLocation = extractGeoLocation(requestMeta);\n\tif (!geoLocation) {\n\t\treturn;\n\t}\n\n\tif (!resultMeta[GEO_LOCATION_KEY]) {\n\t\tresultMeta[GEO_LOCATION_KEY] = geoLocation;\n\t}\n\n\tif (!resultMeta[LEGACY_USER_LOCATION_KEY]) {\n\t\tresultMeta[LEGACY_USER_LOCATION_KEY] = geoLocation;\n\t}\n}\n\nfunction extractGeoLocation(\n\tmeta: UnknownRecord | undefined,\n): UnknownRecord | string | undefined {\n\tif (!meta) {\n\t\treturn undefined;\n\t}\n\n\tconst geoLocation = meta[GEO_LOCATION_KEY] ?? meta[LEGACY_USER_LOCATION_KEY];\n\tif (isRecord(geoLocation) || typeof geoLocation === \"string\") {\n\t\treturn geoLocation;\n\t}\n\n\treturn undefined;\n}\n\nfunction toError(error: unknown): Error {\n\tif (error instanceof Error) {\n\t\treturn error;\n\t}\n\treturn new Error(String(error));\n}\n","import type { ToolCalledProperties } from \"../../../tracking/index.js\";\nimport { waniwani } from \"../../../waniwani.js\";\nimport { WaniwaniFlowStore } from \"../flows/flow-store.js\";\nimport { createScopedClient, SCOPED_CLIENT_KEY } from \"../scoped-client.js\";\nimport type { McpServer } from \"../tools/types\";\nimport { WidgetTokenCache } from \"../widget-token.js\";\nimport {\n\tbuildTrackInput,\n\textractErrorText,\n\textractMeta,\n\tinjectRequestMetadata,\n\tinjectWidgetConfig,\n\tisRecord,\n\tsafeFlush,\n\tsafeTrack,\n\ttype WaniwaniTracker,\n} from \"./helpers.js\";\n\ntype UnknownRecord = Record<string, unknown>;\n\nexport const FLOW_STORE_KEY = \"waniwani/flowStore\";\n\ntype WrappedServer = McpServer & {\n\t__waniwaniWrapped?: true;\n};\n\n/**\n * Options for withWaniwani().\n */\nexport type WithWaniwaniOptions = {\n\t/**\n\t * The WaniWani client instance. When omitted, a client is created\n\t * automatically using the global config registered by `defineConfig()`,\n\t * falling back to env vars.\n\t */\n\tclient?: WaniwaniTracker;\n\t/**\n\t * Optional explicit tool type. Defaults to `\"other\"`.\n\t */\n\ttoolType?:\n\t\t| ToolCalledProperties[\"type\"]\n\t\t| ((toolName: string) => ToolCalledProperties[\"type\"] | undefined);\n\t/**\n\t * Optional metadata merged into every tracked event.\n\t */\n\tmetadata?: UnknownRecord;\n\t/**\n\t * Flush tracking transport after each tool call.\n\t */\n\tflushAfterToolCall?: boolean;\n\t/**\n\t * Optional error callback for non-fatal tracking errors.\n\t */\n\tonError?: (error: Error) => void;\n\t/**\n\t * Inject widget tracking config into tool response `_meta.waniwani` so browser\n\t * widgets can send events directly to the WaniWani backend.\n\t *\n\t * Always injects `endpoint`. Injects `token` when an API key is configured\n\t * and token minting succeeds.\n\t *\n\t * @default true\n\t */\n\tinjectWidgetToken?: boolean;\n};\n\nconst DEFAULT_BASE_URL = \"https://app.waniwani.ai\";\n\n/**\n * Wrap an MCP server so tool handlers automatically emit `tool.called` events.\n *\n * The wrapper intercepts `server.registerTool(...)`, tracks each invocation,\n * then forwards execution to the original tool handler.\n *\n * When `injectWidgetToken` is enabled (default), tracking config is injected\n * into tool response `_meta.waniwani` so browser widgets can post events\n * directly to the WaniWani backend without a server-side proxy.\n */\nexport function withWaniwani(\n\tserver: McpServer,\n\toptions?: WithWaniwaniOptions,\n): McpServer {\n\tconst wrappedServer = server as WrappedServer;\n\tif (wrappedServer.__waniwaniWrapped) {\n\t\treturn wrappedServer;\n\t}\n\n\twrappedServer.__waniwaniWrapped = true;\n\n\tconst opts = options ?? {};\n\tconst tracker = opts.client ?? waniwani();\n\tconst injectToken = opts.injectWidgetToken !== false;\n\n\tconst tokenCache: WidgetTokenCache | null = tracker._config.apiKey\n\t\t? new WidgetTokenCache({\n\t\t\t\tapiUrl: tracker._config.apiUrl ?? DEFAULT_BASE_URL,\n\t\t\t\tapiKey: tracker._config.apiKey,\n\t\t\t})\n\t\t: null;\n\n\tconst flowStore = new WaniwaniFlowStore({\n\t\tapiUrl: tracker._config.apiUrl,\n\t\tapiKey: tracker._config.apiKey,\n\t});\n\n\tconst originalRegisterTool = server.registerTool.bind(server) as (\n\t\t...args: unknown[]\n\t) => unknown;\n\n\twrappedServer.registerTool = ((...args: unknown[]) => {\n\t\tconst [toolNameRaw, config, handlerRaw] = args;\n\t\tconst toolName =\n\t\t\ttypeof toolNameRaw === \"string\" && toolNameRaw.trim().length > 0\n\t\t\t\t? toolNameRaw\n\t\t\t\t: \"unknown\";\n\n\t\tif (typeof handlerRaw !== \"function\") {\n\t\t\treturn originalRegisterTool(...args);\n\t\t}\n\n\t\tconst handler = handlerRaw as (\n\t\t\tinput: unknown,\n\t\t\textra: unknown,\n\t\t) => Promise<unknown> | unknown;\n\n\t\tconst wrappedHandler = async (input: unknown, extra: unknown) => {\n\t\t\t// Inject scoped client into extra so createTool/flows can surface it\n\t\t\tconst meta = extractMeta(extra) ?? {};\n\t\t\tconst scopedClient = createScopedClient(tracker, meta, {\n\t\t\t\tapiUrl: tracker._config.apiUrl,\n\t\t\t\tapiKey: tracker._config.apiKey,\n\t\t\t});\n\t\t\tif (isRecord(extra)) {\n\t\t\t\textra[SCOPED_CLIENT_KEY] = scopedClient;\n\t\t\t\textra[FLOW_STORE_KEY] = flowStore;\n\t\t\t}\n\n\t\t\tconst startTime = performance.now();\n\t\t\tconst clientInfo = (\n\t\t\t\tserver as {\n\t\t\t\t\tserver?: {\n\t\t\t\t\t\tgetClientVersion?: () =>\n\t\t\t\t\t\t\t| { name: string; version: string }\n\t\t\t\t\t\t\t| undefined;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t).server?.getClientVersion?.();\n\t\t\ttry {\n\t\t\t\tconst result = await handler(input, extra);\n\t\t\t\tconst durationMs = Math.round(performance.now() - startTime);\n\n\t\t\t\tconst isErrorResult =\n\t\t\t\t\tisRecord(result) && (result as UnknownRecord).isError === true;\n\n\t\t\t\tif (isErrorResult) {\n\t\t\t\t\tconst errorText = extractErrorText(result);\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t`[waniwani] Tool \"${toolName}\" returned error${errorText ? `: ${errorText}` : \"\"}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tawait safeTrack(\n\t\t\t\t\ttracker,\n\t\t\t\t\tbuildTrackInput(\n\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\textra,\n\t\t\t\t\t\topts,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdurationMs,\n\t\t\t\t\t\t\tstatus: isErrorResult ? \"error\" : \"ok\",\n\t\t\t\t\t\t\t...(isErrorResult && {\n\t\t\t\t\t\t\t\terrorMessage: extractErrorText(result) ?? \"Unknown tool error\",\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclientInfo,\n\t\t\t\t\t\t{ input, output: result },\n\t\t\t\t\t),\n\t\t\t\t\topts.onError,\n\t\t\t\t);\n\n\t\t\t\tif (opts.flushAfterToolCall) {\n\t\t\t\t\tawait safeFlush(tracker, opts.onError);\n\t\t\t\t}\n\n\t\t\t\tinjectRequestMetadata(result, extra);\n\n\t\t\t\tif (injectToken) {\n\t\t\t\t\tawait injectWidgetConfig(\n\t\t\t\t\t\tresult,\n\t\t\t\t\t\ttokenCache,\n\t\t\t\t\t\ttracker._config.apiUrl ?? DEFAULT_BASE_URL,\n\t\t\t\t\t\textra,\n\t\t\t\t\t\topts.onError,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t} catch (error) {\n\t\t\t\tconst durationMs = Math.round(performance.now() - startTime);\n\n\t\t\t\tawait safeTrack(\n\t\t\t\t\ttracker,\n\t\t\t\t\tbuildTrackInput(\n\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\textra,\n\t\t\t\t\t\topts,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdurationMs,\n\t\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclientInfo,\n\t\t\t\t\t\t{ input },\n\t\t\t\t\t),\n\t\t\t\t\topts.onError,\n\t\t\t\t);\n\n\t\t\t\tif (opts.flushAfterToolCall) {\n\t\t\t\t\tawait safeFlush(tracker, opts.onError);\n\t\t\t\t}\n\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t};\n\n\t\treturn originalRegisterTool(toolNameRaw, config, wrappedHandler);\n\t}) as McpServer[\"registerTool\"];\n\n\treturn wrappedServer;\n}\n","import type { z } from \"zod\";\n\n// ============================================================================\n// Zod object schema detection\n// ============================================================================\n\n/** Check whether a Zod schema is a `z.object(...)`. */\nexport function isObjectSchema(schema: z.ZodType): boolean {\n\tconst def = (schema as unknown as { _zod?: { def?: { type?: string } } })._zod\n\t\t?.def;\n\treturn def?.type === \"object\";\n}\n\n/** Extract the shape of a `z.object(...)` schema, or null if not an object. */\nexport function getObjectShape(\n\tschema: z.ZodType,\n): Record<string, z.ZodType> | null {\n\tconst def = (\n\t\tschema as unknown as {\n\t\t\t_zod?: { def?: { type?: string; shape?: Record<string, z.ZodType> } };\n\t\t}\n\t)._zod?.def;\n\tif (def?.type === \"object\" && def.shape) {\n\t\treturn def.shape;\n\t}\n\treturn null;\n}\n\n// ============================================================================\n// Dot-path value access\n// ============================================================================\n\n/** Resolve a dot-path like `\"driver.name\"` to its value in a nested object. */\nexport function getNestedValue(\n\tobj: Record<string, unknown>,\n\tpath: string,\n): unknown {\n\tconst parts = path.split(\".\");\n\tlet current: unknown = obj;\n\tfor (const part of parts) {\n\t\tif (current == null || typeof current !== \"object\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tcurrent = (current as Record<string, unknown>)[part];\n\t}\n\treturn current;\n}\n\n/** Set a value at a dot-path, creating intermediate objects as needed. */\nexport function setNestedValue(\n\tobj: Record<string, unknown>,\n\tpath: string,\n\tvalue: unknown,\n): void {\n\tconst parts = path.split(\".\");\n\tconst lastKey = parts.pop();\n\tif (!lastKey) {\n\t\treturn;\n\t}\n\tlet current = obj;\n\tfor (const part of parts) {\n\t\tif (\n\t\t\tcurrent[part] == null ||\n\t\t\ttypeof current[part] !== \"object\" ||\n\t\t\tArray.isArray(current[part])\n\t\t) {\n\t\t\tcurrent[part] = {};\n\t\t}\n\t\tcurrent = current[part] as Record<string, unknown>;\n\t}\n\tcurrent[lastKey] = value;\n}\n\n/** Delete a value at a dot-path. Only removes the leaf key. */\nexport function deleteNestedValue(\n\tobj: Record<string, unknown>,\n\tpath: string,\n): void {\n\tconst parts = path.split(\".\");\n\tconst lastKey = parts.pop();\n\tif (!lastKey) {\n\t\treturn;\n\t}\n\tlet current: unknown = obj;\n\tfor (const part of parts) {\n\t\tif (current == null || typeof current !== \"object\") {\n\t\t\treturn;\n\t\t}\n\t\tcurrent = (current as Record<string, unknown>)[part];\n\t}\n\tif (current != null && typeof current === \"object\") {\n\t\tdelete (current as Record<string, unknown>)[lastKey];\n\t}\n}\n\n// ============================================================================\n// State merging\n// ============================================================================\n\n/**\n * Expand dot-path keys into nested objects.\n * `{ \"driver.name\": \"John\", \"email\": \"a@b.com\" }` → `{ driver: { name: \"John\" }, email: \"a@b.com\" }`\n */\nexport function expandDotPaths(\n\tflat: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst result: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(flat)) {\n\t\tif (key.includes(\".\")) {\n\t\t\tsetNestedValue(result, key, value);\n\t\t} else {\n\t\t\tresult[key] = value;\n\t\t}\n\t}\n\treturn result;\n}\n\n/**\n * Deep-merge source into target. Preserves existing nested keys.\n * Only merges plain objects — arrays and primitives are overwritten.\n */\nexport function deepMerge(\n\ttarget: Record<string, unknown>,\n\tsource: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst result = { ...target };\n\tfor (const [key, value] of Object.entries(source)) {\n\t\tif (\n\t\t\tvalue !== null &&\n\t\t\ttypeof value === \"object\" &&\n\t\t\t!Array.isArray(value) &&\n\t\t\tresult[key] !== null &&\n\t\t\ttypeof result[key] === \"object\" &&\n\t\t\t!Array.isArray(result[key])\n\t\t) {\n\t\t\tresult[key] = deepMerge(\n\t\t\t\tresult[key] as Record<string, unknown>,\n\t\t\t\tvalue as Record<string, unknown>,\n\t\t\t);\n\t\t} else {\n\t\t\tresult[key] = value;\n\t\t}\n\t}\n\treturn result;\n}\n","import type { ScopedWaniWaniClient } from \"../scoped-client\";\nimport type {\n\tEdge,\n\tExecutionResult,\n\tInterruptQuestionData,\n\tMaybePromise,\n\tNodeHandler,\n} from \"./@types\";\nimport { END, interrupt, isInterrupt, isWidget, showWidget } from \"./@types\";\nimport { deepMerge, deleteNestedValue, getNestedValue } from \"./nested\";\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/** Check whether a state value counts as \"filled\" (not empty/missing). */\nexport function isFilled(v: unknown): boolean {\n\treturn v !== undefined && v !== null && v !== \"\";\n}\n\nexport type ValidateFn = (\n\tvalue: unknown,\n\t// biome-ignore lint/suspicious/noConfusingVoidType: void needed for async () => {} validators\n) => MaybePromise<Record<string, unknown> | void>;\n\n// ============================================================================\n// Edge resolution\n// ============================================================================\n\nexport async function resolveNextNode<TState extends Record<string, unknown>>(\n\tedge: Edge<TState>,\n\tstate: Partial<TState>,\n): Promise<string> {\n\tif (edge.type === \"direct\") {\n\t\treturn edge.to;\n\t}\n\treturn edge.condition(state);\n}\n\n// ============================================================================\n// Interrupt result builder\n// ============================================================================\n\n/**\n * Build an interrupt ExecutionResult from a list of questions and current state.\n * Filters out already-answered questions and caches the full question list in\n * flowMeta so partial-answer continues can filter without re-executing the handler.\n *\n * Returns `null` when all questions are already filled (caller should advance).\n */\nexport function buildInterruptResult<TState extends Record<string, unknown>>(\n\tquestions: InterruptQuestionData[],\n\tcontext: string | undefined,\n\tcurrentNode: string,\n\tstate: TState,\n): ExecutionResult | null {\n\t// All filled — caller should advance to the next node\n\tif (\n\t\tquestions.every((q) =>\n\t\t\tisFilled(getNestedValue(state as Record<string, unknown>, q.field)),\n\t\t)\n\t) {\n\t\treturn null;\n\t}\n\n\t// Filter out questions whose fields are already answered\n\tconst unanswered = questions.filter(\n\t\t(q) => !isFilled(getNestedValue(state as Record<string, unknown>, q.field)),\n\t);\n\n\t// Single-question shorthand: unwrap for cleaner AI payload\n\tconst isSingle = unanswered.length === 1;\n\tconst q0 = unanswered[0];\n\tconst payload =\n\t\tisSingle && q0\n\t\t\t? {\n\t\t\t\t\tstatus: \"interrupt\" as const,\n\t\t\t\t\tquestion: q0.question,\n\t\t\t\t\tfield: q0.field,\n\t\t\t\t\t...(q0.suggestions ? { suggestions: q0.suggestions } : {}),\n\t\t\t\t\t...(q0.context || context ? { context: q0.context ?? context } : {}),\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tstatus: \"interrupt\" as const,\n\t\t\t\t\tquestions: unanswered,\n\t\t\t\t\t...(context ? { context } : {}),\n\t\t\t\t};\n\n\treturn {\n\t\tcontent: payload,\n\t\tflowTokenContent: {\n\t\t\tstep: currentNode,\n\t\t\tstate,\n\t\t\t...(isSingle && q0 ? { field: q0.field } : {}),\n\t\t},\n\t};\n}\n\n// ============================================================================\n// Execution engine\n// ============================================================================\n\nexport async function executeFrom<TState extends Record<string, unknown>>(\n\tstartNodeName: string,\n\tstartState: TState,\n\tnodes: Map<string, NodeHandler<TState>>,\n\tedges: Map<string, Edge<TState>>,\n\tvalidators: Map<string, ValidateFn>,\n\tmeta?: Record<string, unknown>,\n\twaniwani?: ScopedWaniWaniClient,\n): Promise<ExecutionResult> {\n\tlet currentNode = startNodeName;\n\tlet state = { ...startState };\n\n\t// Safety limit to prevent infinite loops\n\tconst MAX_ITERATIONS = 50;\n\tlet iterations = 0;\n\n\twhile (iterations++ < MAX_ITERATIONS) {\n\t\t// Reached END\n\t\tif (currentNode === END) {\n\t\t\treturn {\n\t\t\t\tcontent: { status: \"complete\" },\n\t\t\t\tflowTokenContent: { state },\n\t\t\t};\n\t\t}\n\n\t\tconst handler = nodes.get(currentNode);\n\t\tif (!handler) {\n\t\t\treturn {\n\t\t\t\tcontent: {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\terror: `Unknown node: \"${currentNode}\"`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\ttry {\n\t\t\t// Build context object for the handler\n\t\t\tconst ctx = {\n\t\t\t\tstate,\n\t\t\t\tmeta,\n\t\t\t\tinterrupt: interrupt as NodeHandler<TState> extends never\n\t\t\t\t\t? never\n\t\t\t\t\t: typeof interrupt,\n\t\t\t\tshowWidget: showWidget as NodeHandler<TState> extends never\n\t\t\t\t\t? never\n\t\t\t\t\t: typeof showWidget,\n\t\t\t\twaniwani,\n\t\t\t};\n\t\t\tconst result = await handler(ctx as Parameters<typeof handler>[0]);\n\n\t\t\t// Interrupt signal — pause and ask the user one or more questions\n\t\t\tif (isInterrupt(result)) {\n\t\t\t\t// Extract and store any validate functions from the interrupt questions\n\t\t\t\tfor (const q of result.questions) {\n\t\t\t\t\tif (q.validate) {\n\t\t\t\t\t\tvalidators.set(`${currentNode}:${q.field}`, q.validate);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst interruptResult = buildInterruptResult(\n\t\t\t\t\tresult.questions,\n\t\t\t\t\tresult.context,\n\t\t\t\t\tcurrentNode,\n\t\t\t\t\tstate,\n\t\t\t\t);\n\n\t\t\t\tif (interruptResult) {\n\t\t\t\t\treturn interruptResult;\n\t\t\t\t}\n\n\t\t\t\t// All questions filled — run validators before advancing\n\t\t\t\tfor (const q of result.questions) {\n\t\t\t\t\tconst fn = validators.get(`${currentNode}:${q.field}`);\n\t\t\t\t\tif (fn) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst value = getNestedValue(\n\t\t\t\t\t\t\t\tstate as Record<string, unknown>,\n\t\t\t\t\t\t\t\tq.field,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst vResult = await fn(value);\n\t\t\t\t\t\t\tif (vResult && typeof vResult === \"object\") {\n\t\t\t\t\t\t\t\tstate = deepMerge(\n\t\t\t\t\t\t\t\t\tstate as Record<string, unknown>,\n\t\t\t\t\t\t\t\t\tvResult as Record<string, unknown>,\n\t\t\t\t\t\t\t\t) as TState;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\t\t\tdeleteNestedValue(state as Record<string, unknown>, q.field);\n\t\t\t\t\t\t\tconst questionsWithError = result.questions.map((qq) =>\n\t\t\t\t\t\t\t\tqq.field === q.field\n\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t...qq,\n\t\t\t\t\t\t\t\t\t\t\tcontext: qq.context\n\t\t\t\t\t\t\t\t\t\t\t\t? `ERROR: ${msg}\\n\\n${qq.context}`\n\t\t\t\t\t\t\t\t\t\t\t\t: `ERROR: ${msg}`,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t: qq,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst errResult = buildInterruptResult(\n\t\t\t\t\t\t\t\tquestionsWithError,\n\t\t\t\t\t\t\t\tresult.context,\n\t\t\t\t\t\t\t\tcurrentNode,\n\t\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (errResult) {\n\t\t\t\t\t\t\t\treturn errResult;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// All questions filled and validated — advance to next node\n\t\t\t\tconst edge = edges.get(currentNode);\n\t\t\t\tif (!edge) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\t\terror: `No outgoing edge from node \"${currentNode}\"`,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tcurrentNode = await resolveNextNode(edge, state);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Widget signal — delegate to display tool\n\t\t\tif (isWidget(result)) {\n\t\t\t\tconst widgetField = result.field;\n\t\t\t\tif (widgetField) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tisFilled(\n\t\t\t\t\t\t\tgetNestedValue(state as Record<string, unknown>, widgetField),\n\t\t\t\t\t\t)\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst edge = edges.get(currentNode);\n\t\t\t\t\t\tif (!edge) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\t\t\t\terror: `No outgoing edge from node \"${currentNode}\"`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentNode = await resolveNextNode(edge, state);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tstatus: \"widget\",\n\t\t\t\t\t\ttool: result.tool.id,\n\t\t\t\t\t\tdata: result.data,\n\t\t\t\t\t\tdescription: result.description,\n\t\t\t\t\t\tinteractive: result.interactive !== false,\n\t\t\t\t\t},\n\t\t\t\t\tflowTokenContent: {\n\t\t\t\t\t\tstep: currentNode,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tfield: widgetField,\n\t\t\t\t\t\twidgetId: result.tool.id,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Action node — deep-merge state (preserves nested object siblings)\n\t\t\tstate = deepMerge(\n\t\t\t\tstate as Record<string, unknown>,\n\t\t\t\tresult as Record<string, unknown>,\n\t\t\t) as TState;\n\n\t\t\tconst edge = edges.get(currentNode);\n\t\t\tif (!edge) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\terror: `No outgoing edge from node \"${currentNode}\"`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tcurrentNode = await resolveNextNode(edge, state);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn {\n\t\t\t\tcontent: { status: \"error\", error: message },\n\t\t\t\tflowTokenContent: { step: currentNode, state },\n\t\t\t};\n\t\t}\n\t}\n\n\treturn {\n\t\tcontent: {\n\t\t\tstatus: \"error\",\n\t\t\terror: \"Flow exceeded maximum iterations (possible infinite loop)\",\n\t\t},\n\t};\n}\n","import type { z } from \"zod\";\nimport type { FlowConfig } from \"./@types\";\nimport { getObjectShape } from \"./nested\";\n\n/** Extract a human-readable label from a Zod schema for the AI protocol */\nfunction describeZodField(schema: z.ZodType): string {\n\tconst desc = schema.description ?? \"\";\n\tconst def = (\n\t\tschema as unknown as {\n\t\t\t_zod: { def: { type: string; entries?: Record<string, string> } };\n\t\t}\n\t)._zod?.def;\n\n\tif (def?.type === \"enum\" && def.entries) {\n\t\tconst vals = Object.keys(def.entries)\n\t\t\t.map((v) => `\"${v}\"`)\n\t\t\t.join(\" | \");\n\t\treturn desc ? `${vals} — ${desc}` : vals;\n\t}\n\n\treturn desc;\n}\n\nexport function buildFlowProtocol(config: FlowConfig): string {\n\tconst lines = [\n\t\t\"\",\n\t\t\"## FLOW EXECUTION PROTOCOL\",\n\t\t\"\",\n\t\t\"This tool implements a multi-step conversational flow. Follow this protocol exactly:\",\n\t\t\"\",\n\t\t'1. Call with `action: \"start\"` to begin and include `intent`.',\n\t\t\" `intent` must be a brief summary of the user's goal for this flow,\",\n\t\t\" including relevant prior context that led to triggering it, if available.\",\n\t\t\" Do NOT invent missing context.\",\n\t\t\" If the user's message already contains answers to likely questions,\",\n\t\t\" extract them into `stateUpdates` as `{ field: value }` pairs.\",\n\t\t\" The engine will auto-skip steps whose fields are already filled.\",\n\t\t\" Only extract values the user explicitly stated — do NOT guess or invent values.\",\n\t];\n\n\tif (config.state) {\n\t\tconst parts: string[] = [];\n\t\tfor (const [key, schema] of Object.entries(config.state)) {\n\t\t\tconst shape = getObjectShape(schema);\n\t\t\tif (shape) {\n\t\t\t\tconst groupDesc = schema.description ?? \"\";\n\t\t\t\tconst subFields = Object.entries(shape)\n\t\t\t\t\t.map(([subKey, subSchema]) => {\n\t\t\t\t\t\tconst info = describeZodField(subSchema);\n\t\t\t\t\t\treturn info\n\t\t\t\t\t\t\t? `\\`${key}.${subKey}\\` (${info})`\n\t\t\t\t\t\t\t: `\\`${key}.${subKey}\\``;\n\t\t\t\t\t})\n\t\t\t\t\t.join(\", \");\n\t\t\t\tparts.push(\n\t\t\t\t\tgroupDesc\n\t\t\t\t\t\t? `\\`${key}\\` (${groupDesc}): ${subFields}`\n\t\t\t\t\t\t: `\\`${key}\\`: ${subFields}`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst info = describeZodField(schema);\n\t\t\t\tparts.push(info ? `\\`${key}\\` (${info})` : `\\`${key}\\``);\n\t\t\t}\n\t\t}\n\t\tlines.push(` Known fields: ${parts.join(\", \")}.`);\n\t}\n\n\tlines.push(\n\t\t\" For grouped fields (shown as `group.subfield`), use dot-notation keys in `stateUpdates`:\",\n\t\t' e.g. `{ \"driver.name\": \"John\", \"driver.license\": \"ABC123\" }`.',\n\t\t\"2. The response JSON `status` field tells you what to do next:\",\n\t\t' - `\"interrupt\"`: Pause and ask the user. Two forms:',\n\t\t\" a. Single question: `{ question, field, context? }` — ask `question`, store answer in `field`.\",\n\t\t\" b. Multi-question: `{ questions: [{question, field}, ...], context? }` — ask ALL questions\",\n\t\t\" in one conversational message, collect all answers.\",\n\t\t\" `context` (if present) is hidden AI instructions — use to shape your response, do NOT show verbatim.\",\n\t\t\" Then call again with:\",\n\t\t' `action: \"continue\"`,',\n\t\t\" `stateUpdates` = answers keyed by their `field` names, plus any other fields the user mentioned.\",\n\t\t' - `\"widget\"`: The flow wants to show a UI widget. Call the tool named in the `tool`',\n\t\t\" field, passing the `data` object as the tool's input.\",\n\t\t\" Check the `interactive` field in the response:\",\n\t\t\" • `interactive: true` — The widget requires user interaction. After calling the display tool,\",\n\t\t\" STOP and WAIT for the user to interact with the widget. Do NOT call this flow tool again\",\n\t\t\" until the user has responded. When they do, call with:\",\n\t\t' `action: \"continue\"`,',\n\t\t\" `stateUpdates` = `{ [field]: <user's selection> }` plus any other fields the user mentioned.\",\n\t\t\" • `interactive: false` — The widget is display-only. Call the display tool, then immediately\",\n\t\t' call THIS flow tool again with `action: \"continue\"`. Do NOT wait for user interaction.',\n\t\t' - `\"complete\"`: The flow is done. Present the result to the user.',\n\t\t' - `\"error\"`: Something went wrong. Show the `error` message.',\n\t\t\"\",\n\t\t\"3. Do NOT invent state values. Only use `stateUpdates` for information the user explicitly provided.\",\n\t\t\"4. Include only the fields the user actually answered in `stateUpdates` — do NOT guess missing ones.\",\n\t\t\" If the user did not answer all pending questions, the engine will re-prompt for the remaining ones.\",\n\t\t\" If the user mentioned values for other known fields, include those too —\",\n\t\t\" they will be applied immediately and those steps will be auto-skipped.\",\n\t);\n\n\treturn lines.join(\"\\n\");\n}\n","import type { Edge, FlowConfig, NodeHandler, RegisteredFlow } from \"./@types\";\nimport { END, START } from \"./@types\";\nimport { compileFlow } from \"./compile\";\nimport type { FlowStore } from \"./flow-store\";\n\nfunction buildMermaidGraph(\n\tnodes: Map<string, unknown>,\n\tedges: Map<string, Edge<unknown>>,\n): string {\n\tconst lines: string[] = [\"flowchart TD\"];\n\tlines.push(` ${START}((Start))`);\n\tfor (const [name] of nodes) {\n\t\tlines.push(` ${name}[${name}]`);\n\t}\n\tlines.push(` ${END}((End))`);\n\tfor (const [from, edge] of edges) {\n\t\tif (edge.type === \"direct\") {\n\t\t\tlines.push(` ${from} --> ${edge.to}`);\n\t\t} else {\n\t\t\tlines.push(` ${from} -.-> ${from}_branch([?])`);\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * A LangGraph-inspired state graph builder for MCP tools.\n *\n * @example\n * ```ts\n * const flow = new StateGraph<MyState>({\n * id: \"onboarding\",\n * title: \"User Onboarding\",\n * description: \"Guides users through onboarding\",\n * })\n * .addNode(\"ask_name\", ({ interrupt }) => interrupt({ question: \"What's your name?\", field: \"name\" }))\n * .addNode(\"greet\", ({ state }) => ({ greeting: `Hello ${state.name}!` }))\n * .addEdge(START, \"ask_name\")\n * .addEdge(\"ask_name\", \"greet\")\n * .addEdge(\"greet\", END)\n * .compile();\n * ```\n */\nexport class StateGraph<\n\tTState extends Record<string, unknown>,\n\tTNodes extends string = never,\n> {\n\tprivate nodes = new Map<string, NodeHandler<TState>>();\n\tprivate edges = new Map<string, Edge<TState>>();\n\tprivate config: FlowConfig;\n\n\tconstructor(config: FlowConfig) {\n\t\tthis.config = config;\n\t}\n\n\t/**\n\t * Add a node with a handler.\n\t *\n\t * The handler receives a context object with `state`, `meta`, `interrupt`, and `showWidget`.\n\t */\n\taddNode<TName extends string>(\n\t\tname: TName,\n\t\thandler: NodeHandler<TState>,\n\t): StateGraph<TState, TNodes | TName> {\n\t\tif (name === START || name === END) {\n\t\t\tthrow new Error(\n\t\t\t\t`\"${name}\" is a reserved name and cannot be used as a node name`,\n\t\t\t);\n\t\t}\n\t\tif (this.nodes.has(name)) {\n\t\t\tthrow new Error(`Node \"${name}\" already exists`);\n\t\t}\n\n\t\tthis.nodes.set(name, handler);\n\t\treturn this as unknown as StateGraph<TState, TNodes | TName>;\n\t}\n\n\t/**\n\t * Add a direct edge between two nodes.\n\t *\n\t * Use `START` as `from` to set the entry point.\n\t * Use `END` as `to` to mark a terminal node.\n\t */\n\taddEdge(from: typeof START | TNodes, to: TNodes | typeof END): this {\n\t\tif (this.edges.has(from)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Node \"${from}\" already has an outgoing edge. Use addConditionalEdge for branching.`,\n\t\t\t);\n\t\t}\n\t\tthis.edges.set(from, { type: \"direct\", to });\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add a conditional edge from a node.\n\t *\n\t * The condition function receives current state and returns the name of the next node.\n\t */\n\taddConditionalEdge(\n\t\tfrom: TNodes,\n\t\tcondition: (\n\t\t\tstate: Partial<TState>,\n\t\t) => TNodes | typeof END | Promise<TNodes | typeof END>,\n\t): this {\n\t\tif (this.edges.has(from)) {\n\t\t\tthrow new Error(`Node \"${from}\" already has an outgoing edge.`);\n\t\t}\n\t\tthis.edges.set(from, { type: \"conditional\", condition });\n\t\treturn this;\n\t}\n\n\t/**\n\t * Generate a Mermaid `flowchart TD` diagram of the graph.\n\t *\n\t * Direct edges use solid arrows. Conditional edges use a dashed arrow\n\t * to a placeholder since branch targets are determined at runtime.\n\t *\n\t * @example\n\t * ```ts\n\t * console.log(graph.graph());\n\t * // flowchart TD\n\t * // __start__((Start))\n\t * // ask_name[ask_name]\n\t * // greet[greet]\n\t * // __end__((End))\n\t * // __start__ --> ask_name\n\t * // ask_name --> greet\n\t * // greet --> __end__\n\t * ```\n\t */\n\tgraph(): string {\n\t\treturn buildMermaidGraph(this.nodes, this.edges);\n\t}\n\n\t/**\n\t * Compile the graph into a RegisteredFlow that can be registered on an McpServer.\n\t *\n\t * Validates the graph structure and returns a registration-compatible object.\n\t */\n\tcompile(options?: { store?: FlowStore }): RegisteredFlow {\n\t\tthis.validate();\n\n\t\tconst nodesCopy = new Map(this.nodes);\n\t\tconst edgesCopy = new Map(this.edges);\n\n\t\treturn compileFlow<TState>({\n\t\t\tconfig: this.config,\n\t\t\tnodes: nodesCopy,\n\t\t\tedges: edgesCopy,\n\t\t\tstore: options?.store,\n\t\t\tgraph: () => buildMermaidGraph(nodesCopy, edgesCopy),\n\t\t});\n\t}\n\n\tprivate validate(): void {\n\t\t// Must have a START edge\n\t\tif (!this.edges.has(START)) {\n\t\t\tthrow new Error(\n\t\t\t\t'Flow must have an entry point. Add an edge from START: .addEdge(START, \"first_node\")',\n\t\t\t);\n\t\t}\n\n\t\t// START edge target must exist\n\t\tconst startEdge = this.edges.get(START);\n\t\tif (\n\t\t\tstartEdge?.type === \"direct\" &&\n\t\t\tstartEdge.to !== END &&\n\t\t\t!this.nodes.has(startEdge.to)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`START edge references non-existent node: \"${startEdge.to}\"`,\n\t\t\t);\n\t\t}\n\n\t\t// All static edge targets must reference existing nodes (or END)\n\t\tfor (const [from, edge] of this.edges) {\n\t\t\tif (from !== START && !this.nodes.has(from)) {\n\t\t\t\tthrow new Error(`Edge from non-existent node: \"${from}\"`);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tedge.type === \"direct\" &&\n\t\t\t\tedge.to !== END &&\n\t\t\t\t!this.nodes.has(edge.to)\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Edge from \"${from}\" references non-existent node: \"${edge.to}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Every node must have an outgoing edge\n\t\tfor (const [name] of this.nodes) {\n\t\t\tif (!this.edges.has(name)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Node \"${name}\" has no outgoing edge. Add one with .addEdge(\"${name}\", ...) or .addConditionalEdge(\"${name}\", ...)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n}\n","import type { z } from \"zod\";\nimport type { FlowConfig, InferFlowState } from \"./@types\";\nimport { StateGraph } from \"./state-graph\";\n\n/**\n * Create a new flow graph — convenience factory for `new StateGraph()`.\n *\n * The state type is automatically inferred from the `state` definition —\n * no explicit generic parameter needed.\n *\n * @example\n * ```ts\n * import { createFlow, interrupt, START, END } from \"@waniwani/sdk/mcp\";\n * import { z } from \"zod\";\n *\n * const flow = createFlow({\n * id: \"onboarding\",\n * title: \"User Onboarding\",\n * description: \"Guides users through onboarding. Use when a user wants to get started.\",\n * state: {\n * name: z.string().describe(\"The user's name\"),\n * email: z.string().describe(\"The user's email address\"),\n * },\n * })\n * .addNode(\"ask_name\", () => interrupt({ question: \"What's your name?\", field: \"name\" }))\n * .addNode(\"ask_email\", () => interrupt({ question: \"What's your email?\", field: \"email\" }))\n * .addEdge(START, \"ask_name\")\n * .addEdge(\"ask_name\", \"ask_email\")\n * .addEdge(\"ask_email\", END)\n * .compile();\n * ```\n */\nexport function createFlow<const TSchema extends Record<string, z.ZodType>>(\n\tconfig: Omit<FlowConfig, \"state\"> & { state: TSchema },\n): StateGraph<InferFlowState<TSchema>> {\n\treturn new StateGraph<InferFlowState<TSchema>>(config);\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type {\n\tFlowCompleteContent,\n\tFlowContent,\n\tFlowErrorContent,\n\tFlowInterruptContent,\n\tFlowTokenContent,\n\tFlowWidgetContent,\n\tRegisteredFlow,\n} from \"./@types\";\nimport type { FlowStore } from \"./flow-store\";\n\n// ============================================================================\n// Test harness for compiled flows\n// ============================================================================\n\ntype WithDecodedState = { decodedState: FlowTokenContent | null };\n\nexport type FlowTestResult =\n\t| (FlowInterruptContent & WithDecodedState)\n\t| (FlowWidgetContent & WithDecodedState)\n\t| (FlowCompleteContent & WithDecodedState)\n\t| (FlowErrorContent & WithDecodedState);\n\ntype Handler = (input: unknown, extra: unknown) => Promise<unknown>;\ntype RegisterToolArgs = [string, Record<string, unknown>, Handler];\n\nfunction parsePayload(result: Record<string, unknown>): FlowContent {\n\tconst content = result.content as Array<{ type: string; text?: string }>;\n\treturn JSON.parse(content[0]?.text ?? \"\") as FlowContent;\n}\n\nexport async function createFlowTestHarness(\n\tflow: RegisteredFlow,\n\toptions?: { stateStore?: FlowStore },\n) {\n\tconst store = options?.stateStore;\n\tconst registered: RegisterToolArgs[] = [];\n\tconst sessionId = `test-session-${Math.random().toString(36).slice(2, 10)}`;\n\n\tconst server = {\n\t\tregisterTool: (...args: unknown[]) => {\n\t\t\tregistered.push(args as RegisterToolArgs);\n\t\t},\n\t} as unknown as McpServer;\n\n\tawait flow.register(server);\n\n\tconst handler = registered[0]?.[2];\n\tif (!handler) {\n\t\tthrow new Error(`Flow \"${flow.id}\" did not register a handler`);\n\t}\n\n\tconst extra = { _meta: { sessionId } };\n\n\tasync function toResult(parsed: FlowContent): Promise<FlowTestResult> {\n\t\treturn {\n\t\t\t...parsed,\n\t\t\tdecodedState: store ? await store.get(sessionId) : null,\n\t\t} satisfies FlowTestResult;\n\t}\n\n\treturn {\n\t\tasync start(\n\t\t\tintent: string,\n\t\t\tstateUpdates?: Record<string, unknown>,\n\t\t): Promise<FlowTestResult> {\n\t\t\tconst result = (await handler(\n\t\t\t\t{\n\t\t\t\t\taction: \"start\",\n\t\t\t\t\tintent,\n\t\t\t\t\t...(stateUpdates ? { stateUpdates } : {}),\n\t\t\t\t},\n\t\t\t\textra,\n\t\t\t)) as Record<string, unknown>;\n\t\t\treturn toResult(parsePayload(result));\n\t\t},\n\n\t\tasync continueWith(\n\t\t\tstateUpdates?: Record<string, unknown>,\n\t\t): Promise<FlowTestResult> {\n\t\t\tconst result = (await handler(\n\t\t\t\t{\n\t\t\t\t\taction: \"continue\",\n\t\t\t\t\t...(stateUpdates ? { stateUpdates } : {}),\n\t\t\t\t},\n\t\t\t\textra,\n\t\t\t)) as Record<string, unknown>;\n\t\t\treturn toResult(parsePayload(result));\n\t\t},\n\n\t\tasync lastState(): Promise<FlowTokenContent | null> {\n\t\t\treturn store ? store.get(sessionId) : null;\n\t\t},\n\t};\n}\n","import type { WidgetCSP } from \"./types\";\n\n/**\n * MIME types for widget resources.\n * OpenAI Apps SDK uses \"text/html+skybridge\"\n * MCP Apps uses \"text/html;profile=mcp-app\"\n */\nexport const MIME_TYPE_OPENAI = \"text/html+skybridge\";\nexport const MIME_TYPE_MCP = \"text/html;profile=mcp-app\";\n\n// ---- HTML fetching ----\n\nexport const fetchHtml = async (\n\tbaseUrl: string,\n\tpath: string,\n): Promise<string> => {\n\tconst normalizedBase = baseUrl.endsWith(\"/\") ? baseUrl.slice(0, -1) : baseUrl;\n\tconst result = await fetch(`${normalizedBase}${path}`);\n\treturn await result.text();\n};\n\n// ---- OpenAI resource metadata ----\n\ninterface OpenAIResourceMeta {\n\t[key: string]: unknown;\n\t\"openai/widgetDescription\"?: string;\n\t\"openai/widgetPrefersBorder\"?: boolean;\n\t\"openai/widgetDomain\"?: string;\n\t\"openai/widgetCSP\"?: WidgetCSP;\n}\n\nexport function buildOpenAIResourceMeta(config: {\n\tdescription?: string;\n\tprefersBorder?: boolean;\n\twidgetDomain: string;\n\twidgetCSP?: WidgetCSP;\n}): OpenAIResourceMeta {\n\treturn {\n\t\t\"openai/widgetDescription\": config.description,\n\t\t\"openai/widgetPrefersBorder\": config.prefersBorder,\n\t\t\"openai/widgetDomain\": config.widgetDomain,\n\t\t...(config.widgetCSP && { \"openai/widgetCSP\": config.widgetCSP }),\n\t};\n}\n\n// ---- MCP Apps resource metadata ----\n\ninterface McpAppsResourceMeta {\n\t[key: string]: unknown;\n\tui?: {\n\t\tcsp?: {\n\t\t\tconnectDomains?: string[];\n\t\t\tresourceDomains?: string[];\n\t\t\tframeDomains?: string[];\n\t\t\tredirectDomains?: string[];\n\t\t};\n\t\tdomain?: string;\n\t\tprefersBorder?: boolean;\n\t};\n}\n\nexport function buildMcpAppsResourceMeta(config: {\n\tdescription?: string;\n\tprefersBorder?: boolean;\n\twidgetDomain?: string;\n\twidgetCSP?: WidgetCSP;\n}): McpAppsResourceMeta {\n\tconst csp = config.widgetCSP\n\t\t? {\n\t\t\t\tconnectDomains: config.widgetCSP.connect_domains,\n\t\t\t\tresourceDomains: config.widgetCSP.resource_domains,\n\t\t\t\tframeDomains: config.widgetCSP.frame_domains,\n\t\t\t\tredirectDomains: config.widgetCSP.redirect_domains,\n\t\t\t}\n\t\t: undefined;\n\n\treturn {\n\t\tui: {\n\t\t\t...(csp && { csp }),\n\t\t\t...(config.widgetDomain && { domain: config.widgetDomain }),\n\t\t\t...(config.prefersBorder !== undefined && {\n\t\t\t\tprefersBorder: config.prefersBorder,\n\t\t\t}),\n\t\t},\n\t};\n}\n\n// ---- Tool metadata (references resource URIs) ----\n\nexport function buildToolMeta(config: {\n\topenaiTemplateUri?: string;\n\tmcpTemplateUri?: string;\n\tinvoking: string;\n\tinvoked: string;\n\tautoHeight?: boolean;\n}) {\n\treturn {\n\t\t// OpenAI metadata\n\t\t...(config.openaiTemplateUri && {\n\t\t\t\"openai/outputTemplate\": config.openaiTemplateUri,\n\t\t}),\n\t\t\"openai/toolInvocation/invoking\": config.invoking,\n\t\t\"openai/toolInvocation/invoked\": config.invoked,\n\t\t\"openai/widgetAccessible\": true,\n\t\t\"openai/resultCanProduceWidget\": true,\n\t\t// MCP Apps metadata (nested)\n\t\t...(config.mcpTemplateUri && {\n\t\t\tui: {\n\t\t\t\tresourceUri: config.mcpTemplateUri,\n\t\t\t\t...(config.autoHeight && { autoHeight: true }),\n\t\t\t},\n\t\t}),\n\t\t// MCP Apps backward-compat flat key (for older hosts)\n\t\t...(config.mcpTemplateUri && {\n\t\t\t\"ui/resourceUri\": config.mcpTemplateUri,\n\t\t}),\n\t};\n}\n","import {\n\tbuildMcpAppsResourceMeta,\n\tbuildOpenAIResourceMeta,\n\tfetchHtml,\n\tMIME_TYPE_MCP,\n\tMIME_TYPE_OPENAI,\n} from \"./meta\";\nimport type { McpServer, RegisteredResource, ResourceConfig } from \"./types\";\n\n/**\n * Creates a reusable UI resource (HTML template) that can be attached\n * to tools or flow nodes.\n *\n * @example\n * ```ts\n * const pricingUI = createResource({\n * id: \"pricing_table\",\n * title: \"Pricing Table\",\n * baseUrl: \"https://my-app.com\",\n * htmlPath: \"/widgets/pricing\",\n * widgetDomain: \"my-app.com\",\n * });\n *\n * await pricingUI.register(server);\n * ```\n */\nexport function createResource(config: ResourceConfig): RegisteredResource {\n\tconst {\n\t\tid,\n\t\ttitle,\n\t\tdescription,\n\t\tbaseUrl,\n\t\thtmlPath,\n\t\twidgetDomain,\n\t\tprefersBorder = true,\n\t\tautoHeight = true,\n\t} = config;\n\n\t// Auto-generate CSP from baseUrl if not explicitly provided\n\tlet widgetCSP = config.widgetCSP ?? {\n\t\tconnect_domains: [baseUrl],\n\t\tresource_domains: [baseUrl],\n\t};\n\n\t// In development with localhost, add extra CSP domains for\n\t// Next.js dev features (WebSocket HMR, Turbopack font serving)\n\tif (process.env.NODE_ENV === \"development\") {\n\t\ttry {\n\t\t\tconst { hostname } = new URL(baseUrl);\n\t\t\tif (hostname === \"localhost\" || hostname === \"127.0.0.1\") {\n\t\t\t\twidgetCSP = {\n\t\t\t\t\t...widgetCSP,\n\t\t\t\t\tconnect_domains: [\n\t\t\t\t\t\t...(widgetCSP.connect_domains || []),\n\t\t\t\t\t\t`ws://${hostname}:*`,\n\t\t\t\t\t\t`wss://${hostname}:*`,\n\t\t\t\t\t],\n\t\t\t\t\tresource_domains: [\n\t\t\t\t\t\t...(widgetCSP.resource_domains || []),\n\t\t\t\t\t\t`http://${hostname}:*`,\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\t\t} catch {\n\t\t\t// Invalid baseUrl — skip dev CSP additions\n\t\t}\n\t}\n\n\tconst openaiUri = `ui://widgets/apps-sdk/${id}.html`;\n\tconst mcpUri = `ui://widgets/ext-apps/${id}.html`;\n\n\t// Lazy HTML — fetched once, shared across all calls\n\tlet htmlPromise: Promise<string> | null = null;\n\tconst getHtml = () => {\n\t\tif (!htmlPromise) {\n\t\t\thtmlPromise = fetchHtml(baseUrl, htmlPath);\n\t\t}\n\t\treturn htmlPromise;\n\t};\n\n\t// Use description for UI metadata\n\tconst uiDescription = description;\n\n\tasync function register(server: McpServer): Promise<void> {\n\t\tconst html = await getHtml();\n\n\t\t// Register OpenAI Apps SDK resource\n\t\tserver.registerResource(\n\t\t\t`${id}-openai-widget`,\n\t\t\topenaiUri,\n\t\t\t{\n\t\t\t\ttitle,\n\t\t\t\tdescription: uiDescription,\n\t\t\t\tmimeType: MIME_TYPE_OPENAI,\n\t\t\t\t_meta: {\n\t\t\t\t\t\"openai/widgetDescription\": uiDescription,\n\t\t\t\t\t\"openai/widgetPrefersBorder\": prefersBorder,\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync (uri) => ({\n\t\t\t\tcontents: [\n\t\t\t\t\t{\n\t\t\t\t\t\turi: uri.href,\n\t\t\t\t\t\tmimeType: MIME_TYPE_OPENAI,\n\t\t\t\t\t\ttext: html,\n\t\t\t\t\t\t_meta: buildOpenAIResourceMeta({\n\t\t\t\t\t\t\tdescription: uiDescription,\n\t\t\t\t\t\t\tprefersBorder,\n\t\t\t\t\t\t\twidgetDomain,\n\t\t\t\t\t\t\twidgetCSP,\n\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t}),\n\t\t);\n\n\t\t// Register MCP Apps resource\n\t\tserver.registerResource(\n\t\t\t`${id}-mcp-widget`,\n\t\t\tmcpUri,\n\t\t\t{\n\t\t\t\ttitle,\n\t\t\t\tdescription: uiDescription,\n\t\t\t\tmimeType: MIME_TYPE_MCP,\n\t\t\t\t_meta: {\n\t\t\t\t\tui: {\n\t\t\t\t\t\tprefersBorder,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync (uri) => ({\n\t\t\t\tcontents: [\n\t\t\t\t\t{\n\t\t\t\t\t\turi: uri.href,\n\t\t\t\t\t\tmimeType: MIME_TYPE_MCP,\n\t\t\t\t\t\ttext: html,\n\t\t\t\t\t\t_meta: buildMcpAppsResourceMeta({\n\t\t\t\t\t\t\tdescription: uiDescription,\n\t\t\t\t\t\t\tprefersBorder,\n\t\t\t\t\t\t\twidgetDomain,\n\t\t\t\t\t\t\twidgetCSP,\n\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t}),\n\t\t);\n\t}\n\n\treturn {\n\t\tid,\n\t\ttitle,\n\t\tdescription,\n\t\topenaiUri,\n\t\tmcpUri,\n\t\tautoHeight,\n\t\tregister,\n\t};\n}\n","import type { ToolCallback } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { ShapeOutput } from \"@modelcontextprotocol/sdk/server/zod-compat.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n\tServerNotification,\n\tServerRequest,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { z } from \"zod\";\nimport { buildToolMeta } from \"../resources/meta\";\nimport { extractScopedClient } from \"../scoped-client\";\nimport type {\n\tMcpServer,\n\tRegisteredTool,\n\tToolConfig,\n\tToolHandler,\n} from \"./types\";\n\n/**\n * Creates an MCP tool with minimal boilerplate.\n *\n * When `handler()` returns `data`, the tool includes it as MCP `structuredContent`.\n * When `config.resource` is provided, the tool also returns widget metadata.\n *\n * @example\n * ```ts\n * // Widget tool (with resource)\n * const pricingTool = createTool({\n * resource: pricingUI,\n * description: \"Show pricing comparison\",\n * inputSchema: { postalCode: z.string() },\n * }, async ({ postalCode }) => ({\n * text: \"Pricing loaded\",\n * data: { postalCode, prices: [] },\n * }));\n *\n * // Plain tool (no resource)\n * const searchTool = createTool({\n * id: \"search\",\n * title: \"Search\",\n * description: \"Search the knowledge base\",\n * inputSchema: { query: z.string() },\n * }, async ({ query }) => ({\n * text: `Results for \"${query}\"`,\n * }));\n * ```\n */\nexport function createTool<TInput extends z.ZodRawShape>(\n\tconfig: ToolConfig<TInput>,\n\thandler: ToolHandler<TInput>,\n): RegisteredTool {\n\tconst {\n\t\tresource,\n\t\tdescription,\n\t\tinputSchema,\n\t\tannotations,\n\t\tautoInjectResultText = true,\n\t} = config;\n\n\tconst id = config.id ?? resource?.id;\n\tconst title = config.title ?? resource?.title;\n\n\tif (!id) {\n\t\tthrow new Error(\n\t\t\t\"createTool: `id` is required when no resource is provided\",\n\t\t);\n\t}\n\tif (!title) {\n\t\tthrow new Error(\n\t\t\t\"createTool: `title` is required when no resource is provided\",\n\t\t);\n\t}\n\n\t// Build widget metadata only when resource is present\n\tconst toolMeta = resource\n\t\t? buildToolMeta({\n\t\t\t\topenaiTemplateUri: resource.openaiUri,\n\t\t\t\tmcpTemplateUri: resource.mcpUri,\n\t\t\t\tinvoking: config.invoking ?? \"Loading...\",\n\t\t\t\tinvoked: config.invoked ?? \"Loaded\",\n\t\t\t\tautoHeight: resource.autoHeight,\n\t\t\t})\n\t\t: undefined;\n\n\treturn {\n\t\tid,\n\t\ttitle,\n\t\tdescription,\n\n\t\tasync register(server: McpServer): Promise<void> {\n\t\t\tserver.registerTool(\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttitle,\n\t\t\t\t\tdescription,\n\t\t\t\t\tinputSchema,\n\t\t\t\t\tannotations,\n\t\t\t\t\t...(toolMeta && { _meta: toolMeta }),\n\t\t\t\t},\n\t\t\t\t(async (args: ShapeOutput<TInput>, extra: unknown) => {\n\t\t\t\t\tconst requestExtra = extra as RequestHandlerExtra<\n\t\t\t\t\t\tServerRequest,\n\t\t\t\t\t\tServerNotification\n\t\t\t\t\t>;\n\t\t\t\t\tconst _meta: Record<string, unknown> = requestExtra._meta ?? {};\n\t\t\t\t\tconst waniwani = extractScopedClient(requestExtra);\n\n\t\t\t\t\tconst result = await handler(args, { extra: { _meta }, waniwani });\n\n\t\t\t\t\t// Widget tool: return structuredContent + widget metadata\n\t\t\t\t\tif (resource && result.data) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: result.text }],\n\t\t\t\t\t\t\tstructuredContent: result.data,\n\t\t\t\t\t\t\t_meta: {\n\t\t\t\t\t\t\t\t...toolMeta,\n\t\t\t\t\t\t\t\t..._meta,\n\t\t\t\t\t\t\t\t...(autoInjectResultText === false\n\t\t\t\t\t\t\t\t\t? { \"waniwani/autoInjectResultText\": false }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\t// Plain tool: return text content, plus structuredContent when provided.\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: result.text }],\n\t\t\t\t\t\t...(result.data ? { structuredContent: result.data } : {}),\n\t\t\t\t\t\t...(autoInjectResultText === false\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t_meta: {\n\t\t\t\t\t\t\t\t\t\t\"waniwani/autoInjectResultText\": false,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t};\n\t\t\t\t}) as unknown as ToolCallback<TInput>,\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * Registers multiple tools on the server\n */\nexport async function registerTools(\n\tserver: McpServer,\n\ttools: RegisteredTool[],\n): Promise<void> {\n\tawait Promise.all(tools.map((t) => t.register(server)));\n}\n","/**\n * Server-side API route handler for widget tracking events.\n *\n * Receives batched events from the `useWaniwani` React hook and forwards them\n * to the WaniWani backend using the server-side SDK.\n *\n * @example Next.js App Router\n * ```typescript\n * // app/api/waniwani/track/route.ts\n * import { createTrackingRoute } from \"@waniwani/sdk/mcp\";\n *\n * const handler = createTrackingRoute({\n * apiKey: process.env.WANIWANI_API_KEY,\n * apiUrl: process.env.WANIWANI_API_URL,\n * });\n *\n * export { handler as POST };\n * ```\n */\n\nimport type { EventType, TrackInput } from \"../../tracking/@types.js\";\nimport type { WaniWaniConfig } from \"../../types.js\";\nimport { waniwani } from \"../../waniwani.js\";\n\nexport interface TrackingRouteOptions {\n\t/** API key for the WaniWani backend. Defaults to WANIWANI_API_KEY env var. */\n\tapiKey?: string;\n\t/** Base URL for the WaniWani backend. Defaults to https://app.waniwani.ai. */\n\tapiUrl?: string;\n}\n\n/** Shape of a single event from the WidgetTransport client. */\ninterface WidgetEventPayload {\n\tevent_id?: string;\n\tevent_type?: string;\n\ttimestamp?: string;\n\tsource?: string;\n\tsession_id?: string;\n\ttrace_id?: string;\n\tuser_id?: string;\n\tevent_name?: string;\n\tmetadata?: Record<string, unknown>;\n\t[key: string]: unknown;\n}\n\n/** Batch payload sent by WidgetTransport. */\ninterface BatchPayload {\n\tevents: WidgetEventPayload[];\n\tsentAt?: string;\n}\n\n/**\n * Map a WidgetEvent from the client to the SDK's TrackInput format.\n */\nfunction mapWidgetEvent(ev: WidgetEventPayload): TrackInput {\n\tconst eventType = ev.event_type ?? \"widget_click\";\n\n\t// For manual tracking methods (track, identify, step, conversion),\n\t// use \"widget_<type>\" as the event name. Auto-capture events already\n\t// have the \"widget_\" prefix.\n\tconst isAutoCapture = eventType.startsWith(\"widget_\");\n\tconst eventName: EventType = (\n\t\tisAutoCapture ? eventType : `widget_${eventType}`\n\t) as EventType;\n\n\t// Merge metadata + any extra properties from the event\n\tconst properties: Record<string, unknown> = {\n\t\t...(ev.metadata ?? {}),\n\t};\n\tif (ev.event_name) {\n\t\tproperties.event_name = ev.event_name;\n\t}\n\n\treturn {\n\t\tevent: eventName,\n\t\tproperties,\n\t\tsessionId: ev.session_id,\n\t\ttraceId: ev.trace_id,\n\t\texternalUserId: ev.user_id,\n\t\teventId: ev.event_id,\n\t\ttimestamp: ev.timestamp,\n\t\tsource: ev.source ?? \"widget\",\n\t} as TrackInput;\n}\n\n/**\n * Creates a POST handler that receives tracking events from `useWaniwani`\n * and forwards them to the WaniWani backend.\n */\nexport function createTrackingRoute(options?: TrackingRouteOptions) {\n\tconst config: WaniWaniConfig = {\n\t\tapiKey: options?.apiKey,\n\t\tapiUrl: options?.apiUrl,\n\t};\n\n\t// Lazy singleton — created on first request\n\tlet client: ReturnType<typeof waniwani> | undefined;\n\n\tfunction getClient() {\n\t\tif (!client) {\n\t\t\tclient = waniwani(config);\n\t\t}\n\t\treturn client;\n\t}\n\n\treturn async function handler(request: Request): Promise<Response> {\n\t\tlet body: BatchPayload;\n\t\ttry {\n\t\t\tbody = (await request.json()) as BatchPayload;\n\t\t} catch {\n\t\t\treturn new Response(JSON.stringify({ error: \"Invalid JSON\" }), {\n\t\t\t\tstatus: 400,\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t});\n\t\t}\n\n\t\tif (!Array.isArray(body.events) || body.events.length === 0) {\n\t\t\treturn new Response(\n\t\t\t\tJSON.stringify({ error: \"Missing or empty events array\" }),\n\t\t\t\t{\n\t\t\t\t\tstatus: 400,\n\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\tconst c = getClient();\n\t\t\tconst results: string[] = [];\n\n\t\t\tfor (const ev of body.events) {\n\t\t\t\tconst trackInput = mapWidgetEvent(ev);\n\t\t\t\tconst result = await c.track(trackInput);\n\t\t\t\tresults.push(result.eventId);\n\t\t\t}\n\n\t\t\tawait c.flush();\n\n\t\t\treturn new Response(\n\t\t\t\tJSON.stringify({ ok: true, accepted: results.length }),\n\t\t\t\t{\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t},\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"Unknown error\";\n\t\t\treturn new Response(JSON.stringify({ error: message }), {\n\t\t\t\tstatus: 500,\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t});\n\t\t}\n\t};\n}\n"],"mappings":"AAWO,SAASA,GAAiC,CAChD,OAAI,OAAO,OAAW,KAAe,WAAY,OACzC,SAED,UACR,CAKO,SAASC,IAAoB,CACnC,OAAOD,EAAe,IAAM,QAC7B,CAKO,SAASE,IAAqB,CACpC,OAAOF,EAAe,IAAM,UAC7B,CClBO,IAAMG,EAAQ,YACRC,EAAM,UAMbC,GAAY,OAAO,IAAI,yBAAyB,EAChDC,GAAS,OAAO,IAAI,sBAAsB,EAyDzC,SAASC,GACfC,EACAC,EACkB,CAClB,IAAMC,EAAUD,GAAQ,QAClBE,EAAiC,CAAC,EAExC,OAAW,CAACC,EAAKC,CAAK,IAAK,OAAO,QAAQL,CAAM,EAC/C,GAAI,OAAOK,GAAU,UAAYA,IAAU,MAAQ,aAAcA,EAAO,CACvE,IAAMC,EAAID,EASVF,EAAU,KAAK,CACd,SAAUG,EAAE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AC,EAAG,CAC9D,OAAQ,IACR,QAAS,CAAE,eAAgB,kBAAmB,CAC/C,CAAC,CACF,CAEA,GAAI,CAAC,MAAM,QAAQC,EAAK,MAAM,GAAKA,EAAK,OAAO,SAAW,EACzD,OAAO,IAAI,SACV,KAAK,UAAU,CAAE,MAAO,+BAAgC,CAAC,EACzD,CACC,OAAQ,IACR,QAAS,CAAE,eAAgB,kBAAmB,CAC/C,CACD,EAGD,GAAI,CACH,IAAMC,EAAIJ,EAAU,EACdK,EAAoB,CAAC,EAE3B,QAAWb,KAAMW,EAAK,OAAQ,CAC7B,IAAMG,EAAaf,GAAeC,CAAE,EAC9Be,EAAS,MAAMH,EAAE,MAAME,CAAU,EACvCD,EAAQ,KAAKE,EAAO,OAAO,CAC5B,CAEA,aAAMH,EAAE,MAAM,EAEP,IAAI,SACV,KAAK,UAAU,CAAE,GAAI,GAAM,SAAUC,EAAQ,MAAO,CAAC,EACrD,CACC,OAAQ,IACR,QAAS,CAAE,eAAgB,kBAAmB,CAC/C,CACD,CACD,OAASG,EAAO,CACf,IAAMC,EAAUD,aAAiB,MAAQA,EAAM,QAAU,gBACzD,OAAO,IAAI,SAAS,KAAK,UAAU,CAAE,MAAOC,CAAQ,CAAC,EAAG,CACvD,OAAQ,IACR,QAAS,CAAE,eAAgB,kBAAmB,CAC/C,CAAC,CACF,CACD,CACD","names":["detectPlatform","isOpenAI","isMCPApps","START","END","INTERRUPT","WIDGET","interrupt","fields","config","context","questions","key","value","q","showWidget","tool","isInterrupt","isWidget","z","SCOPED_CLIENT_KEY","extractScopedClient","extra","createScopedClient","base","meta","config","event","userId","properties","pickFirst","meta","keys","key","value","SESSION_ID_KEYS","REQUEST_ID_KEYS","TRACE_ID_KEYS","EXTERNAL_USER_ID_KEYS","CORRELATION_ID_KEYS","extractSessionId","extractRequestId","extractTraceId","extractExternalUserId","extractCorrelationId","SOURCE_SESSION_KEYS","extractSource","explicit","source","WaniWaniError","message","status","SDK_NAME","createKbClient","config","apiUrl","apiKey","requireApiKey","request","method","path","body","key","url","headers","init","response","text","WaniWaniError","files","query","options","GLOBAL_KEY","getGlobalConfig","GLOBAL_KEY","DEFAULT_SOURCE","mapTrackEventToV2","input","options","now","generateId","createEventId","eventName","resolveEventName","meta","toRecord","metadata","correlation","resolveCorrelationIds","eventId","takeNonEmptyString","timestamp","normalizeTimestamp","source","extractSource","rawLegacy","isLegacyTrackEvent","mappedMetadata","mapProperties","legacyProperties","mapLegacyProperties","explicitProperties","properties","requestId","extractRequestId","sessionId","extractSessionId","traceId","extractTraceId","externalUserId","extractExternalUserId","correlationId","extractCorrelationId","date","value","DEFAULT_ENDPOINT_PATH","SDK_NAME","AUTH_FAILURE_STATUS","RETRYABLE_STATUS","createV2BatchTransport","options","BatchingV2Transport","joinUrl","DEFAULT_ENDPOINT_PATH","delayMs","resolve","event","dropCount","timeoutMs","flushPromise","timeoutSignal","batch","attempt","pendingBatch","result","events","response","error","getErrorMessage","data","parseJsonResponse","partial","rejected","byId","retryable","permanent","rejectedEvent","isRetryableRejectedEvent","rawDelay","status","rejectedCount","buffered","code","body","apiUrl","endpointPath","normalizedBase","normalizedPath","createTrackingClient","config","apiUrl","apiKey","tracking","requireApiKey","transport","createV2BatchTransport","client","userId","properties","meta","mappedEvent","mapTrackEventToV2","event","options","attachShutdownHooks","defaultTimeoutMs","shutdown","waniwani","config","effective","getGlobalConfig","apiUrl","apiKey","trackingConfig","internalConfig","trackingClient","createTrackingClient","kbClient","createKbClient","SDK_NAME","DEFAULT_BASE_URL","WaniwaniKvStore","options","globalConfig","getGlobalConfig","key","value","error","path","body","url","response","text","WaniwaniFlowStore","options","WaniwaniKvStore","key","value","WidgetTokenCache","config","sessionId","traceId","url","joinUrl","body","response","json","result","expiresAtMs","apiUrl","path","SESSION_ID_KEY","GEO_LOCATION_KEY","LEGACY_USER_LOCATION_KEY","isRecord","value","extractMeta","extra","meta","extractErrorText","result","content","c","resolveToolType","toolName","toolTypeOption","buildTrackInput","options","timing","clientInfo","io","toolType","extractSource","safeTrack","tracker","input","onError","error","toError","safeFlush","injectWidgetConfig","cache","apiUrl","existingWaniwaniConfig","waniwaniConfig","token","sessionId","extractSessionId","geoLocation","extractGeoLocation","source","injectRequestMetadata","requestMeta","resultMeta","FLOW_STORE_KEY","DEFAULT_BASE_URL","withWaniwani","server","options","wrappedServer","opts","tracker","waniwani","injectToken","tokenCache","WidgetTokenCache","flowStore","WaniwaniFlowStore","originalRegisterTool","args","toolNameRaw","config","handlerRaw","toolName","handler","input","extra","meta","extractMeta","scopedClient","createScopedClient","isRecord","SCOPED_CLIENT_KEY","startTime","clientInfo","result","durationMs","isErrorResult","errorText","extractErrorText","safeTrack","buildTrackInput","safeFlush","injectRequestMetadata","injectWidgetConfig","error","getObjectShape","schema","def","getNestedValue","obj","path","parts","current","part","setNestedValue","value","lastKey","deleteNestedValue","expandDotPaths","flat","result","key","deepMerge","target","source","isFilled","v","resolveNextNode","edge","state","buildInterruptResult","questions","context","currentNode","q","getNestedValue","unanswered","isSingle","q0","executeFrom","startNodeName","startState","nodes","edges","validators","meta","waniwani","MAX_ITERATIONS","iterations","END","handler","result","interrupt","showWidget","isInterrupt","interruptResult","fn","value","vResult","deepMerge","err","msg","deleteNestedValue","questionsWithError","qq","errResult","isWidget","widgetField","error","describeZodField","schema","desc","def","vals","v","buildFlowProtocol","config","lines","parts","key","shape","getObjectShape","groupDesc","subFields","subKey","subSchema","info","inputSchema","z","compileFlow","input","config","nodes","edges","protocol","buildFlowProtocol","fullDescription","validators","handleToolCall","args","sessionId","store","meta","waniwani","intent","startEdge","START","startState","expandDotPaths","firstNode","resolveNextNode","executeFrom","flowState","err","msg","state","step","updatedState","deepMerge","edge","nextNode","server","extra","requestExtra","_meta","extractSessionId","extractScopedClient","FLOW_STORE_KEY","result","buildMermaidGraph","nodes","edges","lines","START","name","END","from","edge","StateGraph","config","handler","to","condition","options","nodesCopy","edgesCopy","compileFlow","startEdge","createFlow","config","StateGraph","parsePayload","result","content","createFlowTestHarness","flow","options","store","registered","sessionId","server","args","handler","extra","toResult","parsed","intent","stateUpdates","MIME_TYPE_OPENAI","MIME_TYPE_MCP","fetchHtml","baseUrl","path","normalizedBase","buildOpenAIResourceMeta","config","buildMcpAppsResourceMeta","csp","buildToolMeta","createResource","config","id","title","description","baseUrl","htmlPath","widgetDomain","prefersBorder","autoHeight","widgetCSP","hostname","openaiUri","mcpUri","htmlPromise","getHtml","fetchHtml","uiDescription","register","server","html","MIME_TYPE_OPENAI","uri","buildOpenAIResourceMeta","MIME_TYPE_MCP","buildMcpAppsResourceMeta","createTool","config","handler","resource","description","inputSchema","annotations","autoInjectResultText","id","title","toolMeta","buildToolMeta","server","args","extra","requestExtra","_meta","waniwani","extractScopedClient","result","registerTools","tools","t","mapWidgetEvent","ev","eventType","eventName","properties","createTrackingRoute","options","config","client","getClient","waniwani","request","body","c","results","trackInput","result","error","message"]}
1
+ {"version":3,"sources":["../../src/mcp/react/widgets/platform.ts","../../src/mcp/server/flows/@types.ts","../../src/mcp/server/flows/compile.ts","../../src/mcp/server/scoped-client.ts","../../src/mcp/server/utils.ts","../../src/mcp/server/flows/nested.ts","../../src/mcp/server/flows/execute.ts","../../src/mcp/server/kv/kv-store.ts","../../src/mcp/server/flows/flow-store.ts","../../src/mcp/server/flows/protocol.ts","../../src/mcp/server/flows/state-graph.ts","../../src/mcp/server/flows/create-flow.ts","../../src/mcp/server/flows/test-utils.ts","../../src/mcp/server/resources/meta.ts","../../src/mcp/server/resources/create-resource.ts","../../src/mcp/server/tools/create-tool.ts","../../src/error.ts","../../src/kb/client.ts","../../src/tracking/mapper.ts","../../src/tracking/transport.ts","../../src/tracking/index.ts","../../src/waniwani.ts","../../src/mcp/server/tracking-route.ts","../../src/mcp/server/widget-token.ts","../../src/mcp/server/with-waniwani/helpers.ts","../../src/mcp/server/with-waniwani/index.ts"],"sourcesContent":["/**\n * Widget platform types\n */\nexport type WidgetPlatform = \"openai\" | \"mcp-apps\";\n\n/**\n * Detects which platform the widget is running on.\n *\n * OpenAI injects a global `window.openai` object.\n * MCP Apps runs in a sandboxed iframe and uses postMessage.\n */\nexport function detectPlatform(): WidgetPlatform {\n\tif (typeof window !== \"undefined\" && \"openai\" in window) {\n\t\treturn \"openai\";\n\t}\n\treturn \"mcp-apps\";\n}\n\n/**\n * Check if running on OpenAI platform\n */\nexport function isOpenAI(): boolean {\n\treturn detectPlatform() === \"openai\";\n}\n\n/**\n * Check if running on MCP Apps platform\n */\nexport function isMCPApps(): boolean {\n\treturn detectPlatform() === \"mcp-apps\";\n}\n","import type { z } from \"zod\";\nimport type { McpServer } from \"../resources/types\";\nimport type { ScopedWaniWaniClient } from \"../scoped-client\";\nimport type { RegisteredTool } from \"../tools/types\";\nimport type { FlowStore } from \"./flow-store\";\n\nexport type { McpServer };\n\n// ============================================================================\n// Sentinel constants\n// ============================================================================\n\nexport const START = \"__start__\" as const;\nexport const END = \"__end__\" as const;\n\n// ============================================================================\n// Signal types — returned by node handlers to control flow behavior\n// ============================================================================\n\nconst INTERRUPT = Symbol.for(\"waniwani.flow.interrupt\");\nconst WIDGET = Symbol.for(\"waniwani.flow.widget\");\n\n/** A single question within an interrupt step */\nexport type InterruptQuestion = {\n\t/** Question to ask the user */\n\tquestion: string;\n\t/** State key where the answer will be stored */\n\tfield: string;\n\t/** Optional suggestions to present as options */\n\tsuggestions?: string[];\n\t/** Hidden context/instructions for this specific question (not shown to user directly) */\n\tcontext?: string;\n\t/** Validation function — runs after the user answers, before advancing to the next node */\n\t// biome-ignore lint/suspicious/noConfusingVoidType: void is needed so `async () => {}` compiles\n\tvalidate?: (value: unknown) => MaybePromise<Record<string, unknown> | void>;\n};\n\n/**\n * Interrupt signal — pauses the flow and asks the user one or more questions.\n * Single-question and multi-question interrupts use the same type.\n */\nexport type InterruptSignal = {\n\treadonly __type: typeof INTERRUPT;\n\t/** Questions to ask — ask all in one conversational message */\n\tquestions: InterruptQuestion[];\n\t/** Overall hidden context/instructions for the assistant (not shown to user directly) */\n\tcontext?: string;\n};\n\nexport type WidgetSignal = {\n\treadonly __type: typeof WIDGET;\n\t/** The display tool to delegate rendering to */\n\ttool: RegisteredTool;\n\t/** Data to pass to the display tool */\n\tdata: Record<string, unknown>;\n\t/** Description of what the widget does (for the AI's context) */\n\tdescription?: string;\n\t/**\n\t * Whether the user is expected to interact with the widget before the flow continues.\n\t * Defaults to true. Set to false for informational widgets that should render and then\n\t * immediately advance to the next flow step.\n\t */\n\tinteractive?: boolean;\n\t/**\n\t * State key this widget fills — enables auto-skip when the field is already in state.\n\t * Pass this so the engine can skip the widget step when the answer is already known.\n\t */\n\tfield?: string;\n};\n\n/**\n * Create an interrupt signal — pauses the flow and asks the user a question.\n * Used internally by the engine. Flow authors use the typed `interrupt` from the node context.\n *\n * Accepts an object where each key is a field name and the value describes the question.\n * The only reserved key is `context` (string) for overall hidden AI instructions.\n */\nexport function interrupt(\n\tfields: Record<string, unknown>,\n\tconfig?: { context?: string },\n): InterruptSignal {\n\tconst context = config?.context;\n\tconst questions: InterruptQuestion[] = [];\n\n\tfor (const [key, value] of Object.entries(fields)) {\n\t\tif (typeof value === \"object\" && value !== null && \"question\" in value) {\n\t\t\tconst q = value as {\n\t\t\t\tquestion: string;\n\t\t\t\tsuggestions?: string[];\n\t\t\t\tcontext?: string;\n\t\t\t\tvalidate?: (\n\t\t\t\t\tvalue: unknown,\n\t\t\t\t\t// biome-ignore lint/suspicious/noConfusingVoidType: void is needed so `async () => {}` compiles\n\t\t\t\t) => MaybePromise<Record<string, unknown> | void>;\n\t\t\t};\n\t\t\tquestions.push({\n\t\t\t\tquestion: q.question,\n\t\t\t\tfield: key,\n\t\t\t\tsuggestions: q.suggestions,\n\t\t\t\tcontext: q.context,\n\t\t\t\tvalidate: q.validate,\n\t\t\t});\n\t\t}\n\t}\n\n\treturn {\n\t\t__type: INTERRUPT,\n\t\tquestions,\n\t\tcontext,\n\t};\n}\n\n/**\n * Create a widget signal — pauses the flow and delegates rendering to a display tool.\n * Used internally by the engine. Flow authors use the typed `showWidget` from the node context.\n */\nexport function showWidget(\n\ttool: RegisteredTool,\n\tconfig: {\n\t\tdata: Record<string, unknown>;\n\t\tdescription?: string;\n\t\tinteractive?: boolean;\n\t\tfield?: string;\n\t},\n): WidgetSignal {\n\treturn { __type: WIDGET, tool, ...config };\n}\n\nexport function isInterrupt(value: unknown): value is InterruptSignal {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t\"__type\" in value &&\n\t\t(value as InterruptSignal).__type === INTERRUPT\n\t);\n}\n\nexport function isWidget(value: unknown): value is WidgetSignal {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t\"__type\" in value &&\n\t\t(value as WidgetSignal).__type === WIDGET\n\t);\n}\n\n// ============================================================================\n// Node context & handler\n// ============================================================================\n\nexport type MaybePromise<T> = T | Promise<T>;\n\n// ============================================================================\n// Nested state utility types\n// ============================================================================\n\n/** Deep partial — allows partial updates at any nesting level (for z.object state fields). */\nexport type DeepPartial<T> = {\n\t[K in keyof T]?: T[K] extends Record<string, unknown>\n\t\t? DeepPartial<T[K]>\n\t\t: T[K];\n};\n\n/**\n * Extract known (non-index-signature) string keys from a type.\n * Zod v4's z.object() adds `[key: string]: unknown` to inferred types,\n * so we filter those out to get only the declared field names.\n */\ntype KnownStringKeys<T> = Extract<\n\tkeyof {\n\t\t[K in keyof T as string extends K\n\t\t\t? never\n\t\t\t: number extends K\n\t\t\t\t? never\n\t\t\t\t: K]: T[K];\n\t},\n\tstring\n>;\n\n/**\n * Union of all valid field paths for a state type.\n * - Flat fields produce their key: `\"email\"`\n * - `z.object()` fields produce dot-paths to sub-fields: `\"driver.name\"`, `\"driver.license\"`\n * - Arrays and general records (`z.record()`) are treated as flat fields.\n * - Only 1 level of nesting is supported.\n */\nexport type FieldPaths<TState> = {\n\t[K in Extract<keyof TState, string>]: NonNullable<TState[K]> extends unknown[]\n\t\t? K\n\t\t: NonNullable<TState[K]> extends Record<string, unknown>\n\t\t\t? KnownStringKeys<NonNullable<TState[K]>> extends never\n\t\t\t\t? K\n\t\t\t\t: K | `${K}.${KnownStringKeys<NonNullable<TState[K]>>}`\n\t\t\t: K;\n}[Extract<keyof TState, string>];\n\n/** Resolve a dot-path to the value type at that path in TState. */\nexport type ResolveFieldType<\n\tTState,\n\tP extends string,\n> = P extends `${infer Parent}.${infer Child}`\n\t? Parent extends keyof TState\n\t\t? Child extends keyof NonNullable<TState[Parent]>\n\t\t\t? NonNullable<TState[Parent]>[Child]\n\t\t\t: never\n\t\t: never\n\t: P extends keyof TState\n\t\t? TState[P]\n\t\t: never;\n\n// ============================================================================\n// Typed interrupt & showWidget\n// ============================================================================\n\n/**\n * Typed interrupt function — available on the node context.\n *\n * First argument: an object where each key is a field path and each value\n * describes the question for that field. Use dot-paths for nested state fields.\n * `validate` receives the field's value typed from the Zod schema.\n *\n * Second argument (optional): config with overall hidden AI instructions.\n *\n * @example\n * ```ts\n * // Flat field\n * interrupt({ breed: { question: \"What breed is your pet?\" } })\n *\n * // Nested field (z.object in state)\n * interrupt({ \"driver.name\": { question: \"Driver's name?\" } })\n *\n * // Multiple questions with context\n * interrupt(\n * {\n * \"driver.name\": { question: \"Name?\" },\n * \"driver.license\": { question: \"License?\" },\n * },\n * { context: \"Ask both questions naturally.\" },\n * )\n * ```\n */\nexport type TypedInterrupt<TState> = (\n\tfields: {\n\t\t[P in FieldPaths<TState>]?: {\n\t\t\tquestion: string;\n\t\t\tvalidate?: (\n\t\t\t\tvalue: ResolveFieldType<TState, P>,\n\t\t\t\t// biome-ignore lint/suspicious/noConfusingVoidType: void is needed so `async () => {}` compiles\n\t\t\t) => MaybePromise<DeepPartial<TState> | void>;\n\t\t\tsuggestions?: string[];\n\t\t\tcontext?: string;\n\t\t};\n\t},\n\tconfig?: {\n\t\t/** Overall hidden context/instructions for the assistant (not shown to user directly) */\n\t\tcontext?: string;\n\t},\n) => InterruptSignal;\n\n/**\n * Typed showWidget function — available on the node context.\n * The `field` parameter accepts field paths (flat or dot-path for nested state).\n */\nexport type TypedShowWidget<TState> = (\n\ttool: RegisteredTool,\n\tconfig: {\n\t\tdata: Record<string, unknown>;\n\t\tdescription?: string;\n\t\tinteractive?: boolean;\n\t\tfield?: FieldPaths<TState>;\n\t},\n) => WidgetSignal;\n\n/**\n * Context object passed to node handlers.\n * Provides state, metadata, and typed helper functions for creating signals.\n */\nexport type NodeContext<TState> = {\n\t/** Current flow state (partial — fields are filled as the flow progresses) */\n\tstate: Partial<TState>;\n\t/** Request metadata from the MCP call */\n\tmeta?: Record<string, unknown>;\n\t/** Create an interrupt signal — pause and ask the user questions */\n\tinterrupt: TypedInterrupt<TState>;\n\t/** Create a widget signal — pause and show a UI widget */\n\tshowWidget: TypedShowWidget<TState>;\n\t/** Session-scoped WaniWani client — available when the server is wrapped with withWaniwani() */\n\twaniwani?: ScopedWaniWaniClient;\n};\n\n/**\n * Node handler — receives a context object and returns a signal or state updates.\n * The return value determines behavior:\n * - `Partial<TState>` → action node (state merged, auto-advance)\n * - `InterruptSignal` → interrupt (pause, ask user one or more questions)\n * - `WidgetSignal` → widget step (pause, show widget)\n */\nexport type NodeHandler<TState> = (\n\tctx: NodeContext<TState>,\n) => MaybePromise<DeepPartial<TState> | InterruptSignal | WidgetSignal>;\n\n/**\n * Condition function for conditional edges.\n * Receives current state, returns the name of the next node.\n */\nexport type ConditionFn<TState> = (\n\tstate: Partial<TState>,\n) => string | Promise<string>;\n\nexport type Edge<TState> =\n\t| { type: \"direct\"; to: string }\n\t| { type: \"conditional\"; condition: ConditionFn<TState> };\n\n// ============================================================================\n// Flow config & compiled output\n// ============================================================================\n\nexport type FlowConfig = {\n\t/** Unique identifier for the flow (becomes the MCP tool name) */\n\tid: string;\n\t/** Display title */\n\ttitle: string;\n\t/** Description for the AI (explains when to use this flow) */\n\tdescription: string;\n\t/**\n\t * Define the flow's state — each field the flow collects.\n\t * Keys are the field names used in `interrupt({ field })`,\n\t * values are Zod schemas with `.describe()`.\n\t *\n\t * The state definition serves two purposes:\n\t * 1. Type inference — `TState` is automatically derived, no explicit generic needed\n\t * 2. AI protocol — field names, types, and descriptions are included in the tool\n\t * description so the AI can pre-fill answers via `_meta.flow.state`\n\t *\n\t * @example\n\t * ```ts\n\t * state: {\n\t * country: z.string().describe(\"Country the business is based in\"),\n\t * status: z.enum([\"registered\", \"unregistered\"]).describe(\"Business registration status\"),\n\t * }\n\t * ```\n\t */\n\tstate: Record<string, z.ZodType>;\n\t/** Optional tool annotations */\n\tannotations?: {\n\t\treadOnlyHint?: boolean;\n\t\tidempotentHint?: boolean;\n\t\topenWorldHint?: boolean;\n\t\tdestructiveHint?: boolean;\n\t};\n};\n\n/**\n * Infer the runtime state type from a flow's state schema definition.\n *\n * @example\n * ```ts\n * const config = {\n * state: {\n * country: z.enum([\"FR\", \"DE\"]),\n * status: z.enum([\"registered\", \"unregistered\"]),\n * }\n * };\n * type MyState = InferFlowState<typeof config.state>;\n * // { country: \"FR\" | \"DE\"; status: \"registered\" | \"unregistered\" }\n * ```\n */\nexport type InferFlowState<T extends Record<string, z.ZodType>> = {\n\t[K in keyof T]: z.infer<T[K]>;\n};\n\n/**\n * A compiled flow — can be registered on an McpServer.\n */\nexport type RegisteredFlow = {\n\tid: string;\n\ttitle: string;\n\tdescription: string;\n\tregister: (server: McpServer) => Promise<void>;\n\t/** Returns a Mermaid `flowchart TD` diagram of the flow graph. */\n\tgraph: () => string;\n};\n\nexport interface CompileInput<TState extends Record<string, unknown>> {\n\tconfig: FlowConfig;\n\tnodes: Map<string, NodeHandler<TState>>;\n\tedges: Map<string, Edge<TState>>;\n\tstore?: FlowStore;\n\tgraph: () => string;\n}\n\nexport type FlowToolInput = {\n\taction: \"start\" | \"continue\";\n\t/** Required when `action` is `\"start\"`. */\n\tintent?: string;\n\tstateUpdates?: Record<string, unknown>;\n};\n\nexport type FlowTokenContent = {\n\tstep?: string;\n\tstate: Record<string, unknown>;\n\tfield?: string;\n\twidgetId?: string;\n};\n\nexport type InterruptQuestionData = {\n\tquestion: string;\n\tfield: string;\n\tsuggestions?: string[];\n\tcontext?: string;\n};\n\nexport type FlowInterruptContent = {\n\tstatus: \"interrupt\";\n\t/** Single-question shorthand */\n\tquestion?: string;\n\tfield?: string;\n\tsuggestions?: string[];\n\t/** Multi-question */\n\tquestions?: InterruptQuestionData[];\n\tcontext?: string;\n};\n\nexport type FlowWidgetContent = {\n\tstatus: \"widget\";\n\t/** Display tool to call */\n\ttool: string;\n\t/** Data to pass to the display tool */\n\tdata: Record<string, unknown>;\n\tdescription?: string;\n\t/** Whether the widget expects user interaction before continuing */\n\tinteractive?: boolean;\n};\n\nexport type FlowCompleteContent = {\n\tstatus: \"complete\";\n};\n\nexport type FlowErrorContent = {\n\tstatus: \"error\";\n\terror: string;\n};\n\n/** Parsed response text from a flow tool call */\nexport type FlowContent =\n\t| FlowInterruptContent\n\t| FlowWidgetContent\n\t| FlowCompleteContent\n\t| FlowErrorContent;\n\nexport type ExecutionResult = {\n\tcontent: FlowContent;\n\tflowTokenContent?: FlowTokenContent;\n};\n","import type { ToolCallback } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n\tServerNotification,\n\tServerRequest,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport type { ScopedWaniWaniClient } from \"../scoped-client\";\nimport { extractScopedClient } from \"../scoped-client\";\nimport { extractSessionId } from \"../utils\";\nimport type {\n\tCompileInput,\n\tFlowToolInput,\n\tMcpServer,\n\tRegisteredFlow,\n} from \"./@types\";\nimport { START } from \"./@types\";\nimport { executeFrom, resolveNextNode, type ValidateFn } from \"./execute\";\nimport { type FlowStore, WaniwaniFlowStore } from \"./flow-store\";\nimport { deepMerge, expandDotPaths } from \"./nested\";\nimport { buildFlowProtocol } from \"./protocol\";\n\n// ============================================================================\n// Input schema\n// ============================================================================\n\nconst inputSchema = {\n\taction: z\n\t\t.enum([\"start\", \"continue\"])\n\t\t.describe(\n\t\t\t'\"start\" to begin the flow, \"continue\" to resume after a pause (interrupt or widget)',\n\t\t),\n\tintent: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\n\t\t\t'Required when action is \"start\". Provide a brief summary of the user\\'s goal for this flow, including relevant prior context that led to triggering it, if available. Do not invent missing context.',\n\t\t),\n\tstateUpdates: z\n\t\t.record(z.string(), z.unknown())\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"State field values to set before processing the next node. Use this to pass the user's answer (keyed by the field name from the response) and any other values the user mentioned.\",\n\t\t),\n};\n\n// ============================================================================\n// Compile\n// ============================================================================\n\nexport function compileFlow<TState extends Record<string, unknown>>(\n\tinput: CompileInput<TState>,\n): RegisteredFlow {\n\tconst { config, nodes, edges } = input;\n\tconst protocol = buildFlowProtocol(config);\n\tconst fullDescription = `${config.description}\\n${protocol}`;\n\n\tconst store: FlowStore = input.store ?? new WaniwaniFlowStore();\n\n\t// Validator storage — populated when handlers return interrupts with validate functions.\n\t// Keyed by \"nodeName:fieldName\", persists across tool calls within the same server.\n\tconst validators = new Map<string, ValidateFn>();\n\n\tasync function handleToolCall(\n\t\targs: FlowToolInput,\n\t\tsessionId: string | undefined,\n\t\tmeta?: Record<string, unknown>,\n\t\twaniwani?: ScopedWaniWaniClient,\n\t) {\n\t\tif (args.action === \"start\") {\n\t\t\tconst intent =\n\t\t\t\ttypeof args.intent === \"string\" ? args.intent.trim() : undefined;\n\t\t\tif (!intent) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\t'Missing required \"intent\" for action \"start\". Include a brief summary of the user\\'s goal for this flow and any relevant prior context that led to triggering it, if available.',\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\targs.intent = intent;\n\n\t\t\tconst startEdge = edges.get(START);\n\t\t\tif (!startEdge) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: { status: \"error\" as const, error: \"No start edge\" },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst startState = expandDotPaths(args.stateUpdates ?? {}) as TState;\n\t\t\tconst firstNode = await resolveNextNode(startEdge, startState);\n\t\t\treturn executeFrom(\n\t\t\t\tfirstNode,\n\t\t\t\tstartState,\n\t\t\t\tnodes,\n\t\t\t\tedges,\n\t\t\t\tvalidators,\n\t\t\t\tmeta,\n\t\t\t\twaniwani,\n\t\t\t);\n\t\t}\n\n\t\tif (args.action === \"continue\") {\n\t\t\tif (!sessionId) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\terror: \"No session ID available for continue action.\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlet flowState: Awaited<ReturnType<typeof store.get>>;\n\t\t\ttry {\n\t\t\t\tflowState = await store.get(sessionId);\n\t\t\t} catch (err) {\n\t\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\terror: `Failed to load flow state (session \"${sessionId}\"): ${msg}`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (!flowState) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\terror: `Flow state not found for session \"${sessionId}\". The flow may have expired.`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst state = flowState.state as TState;\n\t\t\tconst step = flowState.step;\n\t\t\tif (!step) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\t'This flow has already completed. Use action \"start\" to begin a new flow.',\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst updatedState = deepMerge(\n\t\t\t\tstate as Record<string, unknown>,\n\t\t\t\texpandDotPaths(args.stateUpdates ?? {}),\n\t\t\t) as TState;\n\n\t\t\t// Widget continue: advance past the widget step (don't re-show it)\n\t\t\tif (flowState.widgetId) {\n\t\t\t\tconst edge = edges.get(step);\n\t\t\t\tif (!edge) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\tstatus: \"error\" as const,\n\t\t\t\t\t\t\terror: `No edge from step \"${step}\"`,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst nextNode = await resolveNextNode(edge, updatedState);\n\t\t\t\treturn executeFrom(\n\t\t\t\t\tnextNode,\n\t\t\t\t\tupdatedState,\n\t\t\t\t\tnodes,\n\t\t\t\t\tedges,\n\t\t\t\t\tvalidators,\n\t\t\t\t\tmeta,\n\t\t\t\t\twaniwani,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Interrupt continue: re-execute from current step.\n\t\t\t// The handler re-runs, filters answered questions, and runs\n\t\t\t// validators if all questions are filled.\n\t\t\treturn executeFrom(\n\t\t\t\tstep,\n\t\t\t\tupdatedState,\n\t\t\t\tnodes,\n\t\t\t\tedges,\n\t\t\t\tvalidators,\n\t\t\t\tmeta,\n\t\t\t\twaniwani,\n\t\t\t);\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: {\n\t\t\t\tstatus: \"error\" as const,\n\t\t\t\terror: `Unknown action: \"${args.action}\"`,\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {\n\t\tid: config.id,\n\t\ttitle: config.title,\n\t\tdescription: fullDescription,\n\t\tgraph: input.graph,\n\n\t\tasync register(server: McpServer): Promise<void> {\n\t\t\tserver.registerTool(\n\t\t\t\tconfig.id,\n\t\t\t\t{\n\t\t\t\t\ttitle: config.title,\n\t\t\t\t\tdescription: fullDescription,\n\t\t\t\t\tinputSchema,\n\t\t\t\t\tannotations: config.annotations,\n\t\t\t\t},\n\t\t\t\t(async (args: FlowToolInput, extra: unknown) => {\n\t\t\t\t\tconst requestExtra = extra as RequestHandlerExtra<\n\t\t\t\t\t\tServerRequest,\n\t\t\t\t\t\tServerNotification\n\t\t\t\t\t>;\n\t\t\t\t\tconst _meta: Record<string, unknown> = requestExtra._meta ?? {};\n\t\t\t\t\tconst sessionId = extractSessionId(_meta);\n\t\t\t\t\tconst waniwani = extractScopedClient(requestExtra);\n\n\t\t\t\t\tconst result = await handleToolCall(args, sessionId, _meta, waniwani);\n\n\t\t\t\t\t// Persist flow state under session ID\n\t\t\t\t\tif (sessionId) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tresult.flowTokenContent &&\n\t\t\t\t\t\t\tresult.content.status !== \"complete\"\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait store.set(sessionId, result.flowTokenContent);\n\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\t\t\t\tconst errorContent = [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\t\t\t\t\t\t\terror: `Flow state failed to persist (session \"${sessionId}\"): ${msg}`,\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t\t\t\t\t\t2,\n\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tcontent: errorContent,\n\t\t\t\t\t\t\t\t\t_meta,\n\t\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (result.content.status === \"complete\") {\n\t\t\t\t\t\t\t// Clean up — flow is done, remove stale state so a subsequent\n\t\t\t\t\t\t\t// \"continue\" returns \"not found\" instead of a confusing step error.\n\t\t\t\t\t\t\tawait store.delete(sessionId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst content = [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\t\ttext: JSON.stringify(result.content, null, 2),\n\t\t\t\t\t\t},\n\t\t\t\t\t];\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent,\n\t\t\t\t\t\t_meta,\n\t\t\t\t\t\t...(result.content.status === \"error\" ? { isError: true } : {}),\n\t\t\t\t\t};\n\t\t\t\t}) satisfies ToolCallback<typeof inputSchema>,\n\t\t\t);\n\t\t},\n\t};\n}\n","import type { KbClient } from \"../../kb/types.js\";\nimport type { TrackInput, TrackingClient } from \"../../tracking/@types.js\";\n\n/**\n * Well-known key used to attach the scoped client to the MCP `extra` object.\n * Read by `createTool` and flow compilation to surface it in handler contexts.\n */\nexport const SCOPED_CLIENT_KEY = \"waniwani/client\";\n\n/**\n * A request-scoped WaniWani client with meta pre-attached.\n *\n * Available as `context.waniwani` inside `createTool` handlers and flow nodes\n * when the server is wrapped with `withWaniwani()`.\n */\nexport interface ScopedWaniWaniClient {\n\t/** Track an event — request meta is automatically merged. */\n\ttrack(event: TrackInput): Promise<{ eventId: string }>;\n\t/** Identify a user — request meta is automatically merged. */\n\tidentify(\n\t\tuserId: string,\n\t\tproperties?: Record<string, unknown>,\n\t): Promise<{ eventId: string }>;\n\t/** Knowledge base client (no meta needed). */\n\treadonly kb: KbClient;\n\t/** @internal Resolved API config from withWaniwani(). */\n\treadonly _config?: { apiUrl?: string; apiKey?: string };\n}\n\n/**\n * Extract the scoped client from the MCP `extra` object.\n * Returns undefined if `withWaniwani()` is not wrapping the server.\n */\nexport function extractScopedClient(\n\textra: unknown,\n): ScopedWaniWaniClient | undefined {\n\tif (typeof extra === \"object\" && extra !== null) {\n\t\treturn (extra as Record<string, unknown>)[SCOPED_CLIENT_KEY] as\n\t\t\t| ScopedWaniWaniClient\n\t\t\t| undefined;\n\t}\n\treturn undefined;\n}\n\nexport function createScopedClient(\n\tbase: Pick<TrackingClient, \"track\" | \"identify\"> & { readonly kb: KbClient },\n\tmeta: Record<string, unknown>,\n\tconfig?: { apiUrl?: string; apiKey?: string },\n): ScopedWaniWaniClient {\n\treturn {\n\t\ttrack(event) {\n\t\t\treturn base.track({\n\t\t\t\t...event,\n\t\t\t\tmeta: { ...meta, ...event.meta },\n\t\t\t});\n\t\t},\n\t\tidentify(userId, properties) {\n\t\t\treturn base.identify(userId, properties, meta);\n\t\t},\n\t\tkb: base.kb,\n\t\t_config: config,\n\t};\n}\n","// ============================================================================\n// Meta key extraction helpers\n// ============================================================================\n\n/** Pick the first non-empty string value from `meta` matching the given keys. */\nfunction pickFirst(\n\tmeta: Record<string, unknown>,\n\tkeys: readonly string[],\n): string | undefined {\n\tfor (const key of keys) {\n\t\tconst value = meta[key];\n\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\treturn value;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n// --- Key lists (ordered by priority) ---\n\nconst SESSION_ID_KEYS = [\n\t\"waniwani/sessionId\",\n\t\"openai/sessionId\",\n\t\"openai/session\",\n\t\"sessionId\",\n\t\"conversationId\",\n\t\"anthropic/sessionId\",\n] as const;\n\nconst REQUEST_ID_KEYS = [\n\t\"waniwani/requestId\",\n\t\"openai/requestId\",\n\t\"requestId\",\n\t\"mcp/requestId\",\n] as const;\n\nconst TRACE_ID_KEYS = [\n\t\"waniwani/traceId\",\n\t\"openai/traceId\",\n\t\"traceId\",\n\t\"mcp/traceId\",\n\t\"openai/requestId\",\n\t\"requestId\",\n] as const;\n\nconst EXTERNAL_USER_ID_KEYS = [\n\t\"waniwani/userId\",\n\t\"openai/userId\",\n\t\"externalUserId\",\n\t\"userId\",\n\t\"actorId\",\n] as const;\n\nconst CORRELATION_ID_KEYS = [\"correlationId\", \"openai/requestId\"] as const;\n\n// --- Extractors ---\n\nexport function extractSessionId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, SESSION_ID_KEYS) : undefined;\n}\n\nexport function extractRequestId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, REQUEST_ID_KEYS) : undefined;\n}\n\nexport function extractTraceId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, TRACE_ID_KEYS) : undefined;\n}\n\nexport function extractExternalUserId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, EXTERNAL_USER_ID_KEYS) : undefined;\n}\n\nexport function extractCorrelationId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, CORRELATION_ID_KEYS) : undefined;\n}\n\nconst SOURCE_SESSION_KEYS = [\n\t{ key: \"waniwani/sessionId\", source: \"chatbar\" },\n\t{ key: \"openai/sessionId\", source: \"chatgpt\" },\n\t{ key: \"openai/session\", source: \"chatgpt\" },\n\t{ key: \"anthropic/sessionId\", source: \"claude\" },\n] as const;\n\nexport function extractSource(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\tif (!meta) {\n\t\treturn undefined;\n\t}\n\t// Explicit source set by the caller (e.g. chatbar name)\n\tconst explicit = meta[\"waniwani/source\"];\n\tif (typeof explicit === \"string\" && explicit.length > 0) {\n\t\treturn explicit;\n\t}\n\t// Derive from session ID key\n\tfor (const { key, source } of SOURCE_SESSION_KEYS) {\n\t\tconst value = meta[key];\n\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\treturn source;\n\t\t}\n\t}\n\treturn undefined;\n}\n","import type { z } from \"zod\";\n\n// ============================================================================\n// Zod object schema detection\n// ============================================================================\n\n/** Check whether a Zod schema is a `z.object(...)`. */\nexport function isObjectSchema(schema: z.ZodType): boolean {\n\tconst def = (schema as unknown as { _zod?: { def?: { type?: string } } })._zod\n\t\t?.def;\n\treturn def?.type === \"object\";\n}\n\n/** Extract the shape of a `z.object(...)` schema, or null if not an object. */\nexport function getObjectShape(\n\tschema: z.ZodType,\n): Record<string, z.ZodType> | null {\n\tconst def = (\n\t\tschema as unknown as {\n\t\t\t_zod?: { def?: { type?: string; shape?: Record<string, z.ZodType> } };\n\t\t}\n\t)._zod?.def;\n\tif (def?.type === \"object\" && def.shape) {\n\t\treturn def.shape;\n\t}\n\treturn null;\n}\n\n// ============================================================================\n// Dot-path value access\n// ============================================================================\n\n/** Resolve a dot-path like `\"driver.name\"` to its value in a nested object. */\nexport function getNestedValue(\n\tobj: Record<string, unknown>,\n\tpath: string,\n): unknown {\n\tconst parts = path.split(\".\");\n\tlet current: unknown = obj;\n\tfor (const part of parts) {\n\t\tif (current == null || typeof current !== \"object\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tcurrent = (current as Record<string, unknown>)[part];\n\t}\n\treturn current;\n}\n\n/** Set a value at a dot-path, creating intermediate objects as needed. */\nexport function setNestedValue(\n\tobj: Record<string, unknown>,\n\tpath: string,\n\tvalue: unknown,\n): void {\n\tconst parts = path.split(\".\");\n\tconst lastKey = parts.pop();\n\tif (!lastKey) {\n\t\treturn;\n\t}\n\tlet current = obj;\n\tfor (const part of parts) {\n\t\tif (\n\t\t\tcurrent[part] == null ||\n\t\t\ttypeof current[part] !== \"object\" ||\n\t\t\tArray.isArray(current[part])\n\t\t) {\n\t\t\tcurrent[part] = {};\n\t\t}\n\t\tcurrent = current[part] as Record<string, unknown>;\n\t}\n\tcurrent[lastKey] = value;\n}\n\n/** Delete a value at a dot-path. Only removes the leaf key. */\nexport function deleteNestedValue(\n\tobj: Record<string, unknown>,\n\tpath: string,\n): void {\n\tconst parts = path.split(\".\");\n\tconst lastKey = parts.pop();\n\tif (!lastKey) {\n\t\treturn;\n\t}\n\tlet current: unknown = obj;\n\tfor (const part of parts) {\n\t\tif (current == null || typeof current !== \"object\") {\n\t\t\treturn;\n\t\t}\n\t\tcurrent = (current as Record<string, unknown>)[part];\n\t}\n\tif (current != null && typeof current === \"object\") {\n\t\tdelete (current as Record<string, unknown>)[lastKey];\n\t}\n}\n\n// ============================================================================\n// State merging\n// ============================================================================\n\n/**\n * Expand dot-path keys into nested objects.\n * `{ \"driver.name\": \"John\", \"email\": \"a@b.com\" }` → `{ driver: { name: \"John\" }, email: \"a@b.com\" }`\n */\nexport function expandDotPaths(\n\tflat: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst result: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(flat)) {\n\t\tif (key.includes(\".\")) {\n\t\t\tsetNestedValue(result, key, value);\n\t\t} else {\n\t\t\tresult[key] = value;\n\t\t}\n\t}\n\treturn result;\n}\n\n/**\n * Deep-merge source into target. Preserves existing nested keys.\n * Only merges plain objects — arrays and primitives are overwritten.\n */\nexport function deepMerge(\n\ttarget: Record<string, unknown>,\n\tsource: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst result = { ...target };\n\tfor (const [key, value] of Object.entries(source)) {\n\t\tif (\n\t\t\tvalue !== null &&\n\t\t\ttypeof value === \"object\" &&\n\t\t\t!Array.isArray(value) &&\n\t\t\tresult[key] !== null &&\n\t\t\ttypeof result[key] === \"object\" &&\n\t\t\t!Array.isArray(result[key])\n\t\t) {\n\t\t\tresult[key] = deepMerge(\n\t\t\t\tresult[key] as Record<string, unknown>,\n\t\t\t\tvalue as Record<string, unknown>,\n\t\t\t);\n\t\t} else {\n\t\t\tresult[key] = value;\n\t\t}\n\t}\n\treturn result;\n}\n","import type { ScopedWaniWaniClient } from \"../scoped-client\";\nimport type {\n\tEdge,\n\tExecutionResult,\n\tInterruptQuestionData,\n\tMaybePromise,\n\tNodeHandler,\n} from \"./@types\";\nimport { END, interrupt, isInterrupt, isWidget, showWidget } from \"./@types\";\nimport { deepMerge, deleteNestedValue, getNestedValue } from \"./nested\";\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/** Check whether a state value counts as \"filled\" (not empty/missing). */\nexport function isFilled(v: unknown): boolean {\n\treturn v !== undefined && v !== null && v !== \"\";\n}\n\nexport type ValidateFn = (\n\tvalue: unknown,\n\t// biome-ignore lint/suspicious/noConfusingVoidType: void needed for async () => {} validators\n) => MaybePromise<Record<string, unknown> | void>;\n\n// ============================================================================\n// Edge resolution\n// ============================================================================\n\nexport async function resolveNextNode<TState extends Record<string, unknown>>(\n\tedge: Edge<TState>,\n\tstate: Partial<TState>,\n): Promise<string> {\n\tif (edge.type === \"direct\") {\n\t\treturn edge.to;\n\t}\n\treturn edge.condition(state);\n}\n\n// ============================================================================\n// Interrupt result builder\n// ============================================================================\n\n/**\n * Build an interrupt ExecutionResult from a list of questions and current state.\n * Filters out already-answered questions and caches the full question list in\n * flowMeta so partial-answer continues can filter without re-executing the handler.\n *\n * Returns `null` when all questions are already filled (caller should advance).\n */\nexport function buildInterruptResult<TState extends Record<string, unknown>>(\n\tquestions: InterruptQuestionData[],\n\tcontext: string | undefined,\n\tcurrentNode: string,\n\tstate: TState,\n): ExecutionResult | null {\n\t// All filled — caller should advance to the next node\n\tif (\n\t\tquestions.every((q) =>\n\t\t\tisFilled(getNestedValue(state as Record<string, unknown>, q.field)),\n\t\t)\n\t) {\n\t\treturn null;\n\t}\n\n\t// Filter out questions whose fields are already answered\n\tconst unanswered = questions.filter(\n\t\t(q) => !isFilled(getNestedValue(state as Record<string, unknown>, q.field)),\n\t);\n\n\t// Single-question shorthand: unwrap for cleaner AI payload\n\tconst isSingle = unanswered.length === 1;\n\tconst q0 = unanswered[0];\n\tconst payload =\n\t\tisSingle && q0\n\t\t\t? {\n\t\t\t\t\tstatus: \"interrupt\" as const,\n\t\t\t\t\tquestion: q0.question,\n\t\t\t\t\tfield: q0.field,\n\t\t\t\t\t...(q0.suggestions ? { suggestions: q0.suggestions } : {}),\n\t\t\t\t\t...(q0.context || context ? { context: q0.context ?? context } : {}),\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tstatus: \"interrupt\" as const,\n\t\t\t\t\tquestions: unanswered,\n\t\t\t\t\t...(context ? { context } : {}),\n\t\t\t\t};\n\n\treturn {\n\t\tcontent: payload,\n\t\tflowTokenContent: {\n\t\t\tstep: currentNode,\n\t\t\tstate,\n\t\t\t...(isSingle && q0 ? { field: q0.field } : {}),\n\t\t},\n\t};\n}\n\n// ============================================================================\n// Execution engine\n// ============================================================================\n\nexport async function executeFrom<TState extends Record<string, unknown>>(\n\tstartNodeName: string,\n\tstartState: TState,\n\tnodes: Map<string, NodeHandler<TState>>,\n\tedges: Map<string, Edge<TState>>,\n\tvalidators: Map<string, ValidateFn>,\n\tmeta?: Record<string, unknown>,\n\twaniwani?: ScopedWaniWaniClient,\n): Promise<ExecutionResult> {\n\tlet currentNode = startNodeName;\n\tlet state = { ...startState };\n\n\t// Safety limit to prevent infinite loops\n\tconst MAX_ITERATIONS = 50;\n\tlet iterations = 0;\n\n\twhile (iterations++ < MAX_ITERATIONS) {\n\t\t// Reached END\n\t\tif (currentNode === END) {\n\t\t\treturn {\n\t\t\t\tcontent: { status: \"complete\" },\n\t\t\t\tflowTokenContent: { state },\n\t\t\t};\n\t\t}\n\n\t\tconst handler = nodes.get(currentNode);\n\t\tif (!handler) {\n\t\t\treturn {\n\t\t\t\tcontent: {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\terror: `Unknown node: \"${currentNode}\"`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\ttry {\n\t\t\t// Build context object for the handler\n\t\t\tconst ctx = {\n\t\t\t\tstate,\n\t\t\t\tmeta,\n\t\t\t\tinterrupt: interrupt as NodeHandler<TState> extends never\n\t\t\t\t\t? never\n\t\t\t\t\t: typeof interrupt,\n\t\t\t\tshowWidget: showWidget as NodeHandler<TState> extends never\n\t\t\t\t\t? never\n\t\t\t\t\t: typeof showWidget,\n\t\t\t\twaniwani,\n\t\t\t};\n\t\t\tconst result = await handler(ctx as Parameters<typeof handler>[0]);\n\n\t\t\t// Interrupt signal — pause and ask the user one or more questions\n\t\t\tif (isInterrupt(result)) {\n\t\t\t\t// Extract and store any validate functions from the interrupt questions\n\t\t\t\tfor (const q of result.questions) {\n\t\t\t\t\tif (q.validate) {\n\t\t\t\t\t\tvalidators.set(`${currentNode}:${q.field}`, q.validate);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst interruptResult = buildInterruptResult(\n\t\t\t\t\tresult.questions,\n\t\t\t\t\tresult.context,\n\t\t\t\t\tcurrentNode,\n\t\t\t\t\tstate,\n\t\t\t\t);\n\n\t\t\t\tif (interruptResult) {\n\t\t\t\t\treturn interruptResult;\n\t\t\t\t}\n\n\t\t\t\t// All questions filled — run validators before advancing\n\t\t\t\tfor (const q of result.questions) {\n\t\t\t\t\tconst fn = validators.get(`${currentNode}:${q.field}`);\n\t\t\t\t\tif (fn) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst value = getNestedValue(\n\t\t\t\t\t\t\t\tstate as Record<string, unknown>,\n\t\t\t\t\t\t\t\tq.field,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst vResult = await fn(value);\n\t\t\t\t\t\t\tif (vResult && typeof vResult === \"object\") {\n\t\t\t\t\t\t\t\tstate = deepMerge(\n\t\t\t\t\t\t\t\t\tstate as Record<string, unknown>,\n\t\t\t\t\t\t\t\t\tvResult as Record<string, unknown>,\n\t\t\t\t\t\t\t\t) as TState;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\t\t\tdeleteNestedValue(state as Record<string, unknown>, q.field);\n\t\t\t\t\t\t\tconst questionsWithError = result.questions.map((qq) =>\n\t\t\t\t\t\t\t\tqq.field === q.field\n\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t...qq,\n\t\t\t\t\t\t\t\t\t\t\tcontext: qq.context\n\t\t\t\t\t\t\t\t\t\t\t\t? `ERROR: ${msg}\\n\\n${qq.context}`\n\t\t\t\t\t\t\t\t\t\t\t\t: `ERROR: ${msg}`,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t: qq,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst errResult = buildInterruptResult(\n\t\t\t\t\t\t\t\tquestionsWithError,\n\t\t\t\t\t\t\t\tresult.context,\n\t\t\t\t\t\t\t\tcurrentNode,\n\t\t\t\t\t\t\t\tstate,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (errResult) {\n\t\t\t\t\t\t\t\treturn errResult;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// All questions filled and validated — advance to next node\n\t\t\t\tconst edge = edges.get(currentNode);\n\t\t\t\tif (!edge) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\t\terror: `No outgoing edge from node \"${currentNode}\"`,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tcurrentNode = await resolveNextNode(edge, state);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Widget signal — delegate to display tool\n\t\t\tif (isWidget(result)) {\n\t\t\t\tconst widgetField = result.field;\n\t\t\t\tif (widgetField) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tisFilled(\n\t\t\t\t\t\t\tgetNestedValue(state as Record<string, unknown>, widgetField),\n\t\t\t\t\t\t)\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst edge = edges.get(currentNode);\n\t\t\t\t\t\tif (!edge) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\t\t\t\terror: `No outgoing edge from node \"${currentNode}\"`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentNode = await resolveNextNode(edge, state);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tstatus: \"widget\",\n\t\t\t\t\t\ttool: result.tool.id,\n\t\t\t\t\t\tdata: result.data,\n\t\t\t\t\t\tdescription: result.description,\n\t\t\t\t\t\tinteractive: result.interactive !== false,\n\t\t\t\t\t},\n\t\t\t\t\tflowTokenContent: {\n\t\t\t\t\t\tstep: currentNode,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\tfield: widgetField,\n\t\t\t\t\t\twidgetId: result.tool.id,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Action node — deep-merge state (preserves nested object siblings)\n\t\t\tstate = deepMerge(\n\t\t\t\tstate as Record<string, unknown>,\n\t\t\t\tresult as Record<string, unknown>,\n\t\t\t) as TState;\n\n\t\t\tconst edge = edges.get(currentNode);\n\t\t\tif (!edge) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\terror: `No outgoing edge from node \"${currentNode}\"`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tcurrentNode = await resolveNextNode(edge, state);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn {\n\t\t\t\tcontent: { status: \"error\", error: message },\n\t\t\t\tflowTokenContent: { step: currentNode, state },\n\t\t\t};\n\t\t}\n\t}\n\n\treturn {\n\t\tcontent: {\n\t\t\tstatus: \"error\",\n\t\t\terror: \"Flow exceeded maximum iterations (possible infinite loop)\",\n\t\t},\n\t};\n}\n","/**\n * Generic key-value store backed by the WaniWani API.\n *\n * Values are stored as JSON objects (`Record<string, unknown>`) in the\n * `/api/mcp/redis/*` endpoints. Tenant isolation is handled by the API key.\n *\n * Config is read from env vars:\n * - `WANIWANI_API_KEY` (required)\n * - `WANIWANI_API_URL` (optional, defaults to https://app.waniwani.ai)\n */\n\n// ============================================================================\n// Interface\n// ============================================================================\n\nexport interface KvStore<T = Record<string, unknown>> {\n\tget(key: string): Promise<T | null>;\n\tset(key: string, value: T): Promise<void>;\n\tdelete(key: string): Promise<void>;\n}\n\n// ============================================================================\n// WaniWani API implementation\n// ============================================================================\n\nconst SDK_NAME = \"@waniwani/sdk\";\nconst DEFAULT_BASE_URL = \"https://app.waniwani.ai\";\n\nexport class WaniwaniKvStore<T = Record<string, unknown>>\n\timplements KvStore<T>\n{\n\tprivate get baseUrl(): string {\n\t\treturn (process.env.WANIWANI_API_URL ?? DEFAULT_BASE_URL).replace(\n\t\t\t/\\/$/,\n\t\t\t\"\",\n\t\t);\n\t}\n\n\tprivate get apiKey(): string | undefined {\n\t\treturn process.env.WANIWANI_API_KEY;\n\t}\n\n\tasync get(key: string): Promise<T | null> {\n\t\tif (!this.apiKey) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[WaniWani KV] No API key configured. Set WANIWANI_API_KEY env var.\",\n\t\t\t);\n\t\t}\n\t\tconst data = await this.request<T | null>(\"/api/mcp/redis/get\", { key });\n\t\treturn data ?? null;\n\t}\n\n\tasync set(key: string, value: T): Promise<void> {\n\t\tif (!this.apiKey) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[WaniWani KV] No API key configured. Set WANIWANI_API_KEY env var.\",\n\t\t\t);\n\t\t}\n\t\tawait this.request(\"/api/mcp/redis/set\", { key, value });\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\tif (!this.apiKey) {\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tawait this.request(\"/api/mcp/redis/delete\", { key });\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[WaniWani KV] delete failed for key:\", key, error);\n\t\t}\n\t}\n\n\tprivate async request<R>(path: string, body: unknown): Promise<R> {\n\t\tconst url = `${this.baseUrl}${path}`;\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${this.apiKey}`,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\"X-WaniWani-SDK\": SDK_NAME,\n\t\t\t},\n\t\t\tbody: JSON.stringify(body),\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tconst text = await response.text().catch(() => \"\");\n\t\t\tthrow new Error(text || `KV store API error: HTTP ${response.status}`);\n\t\t}\n\n\t\tconst json = (await response.json()) as { data: R };\n\t\treturn json.data;\n\t}\n}\n","/**\n * Server-side flow state store.\n *\n * Flow state is stored via the WaniWani API, keyed by session ID.\n * Config comes from env vars (WANIWANI_API_KEY, WANIWANI_API_URL).\n */\n\nimport { WaniwaniKvStore } from \"../kv\";\nimport type { FlowTokenContent } from \"./@types\";\n\n// ============================================================================\n// Interface\n// ============================================================================\n\nexport interface FlowStore {\n\tget(key: string): Promise<FlowTokenContent | null>;\n\tset(key: string, value: FlowTokenContent): Promise<void>;\n\tdelete(key: string): Promise<void>;\n}\n\n// ============================================================================\n// WaniWani API implementation\n// ============================================================================\n\nexport class WaniwaniFlowStore implements FlowStore {\n\tprivate readonly store = new WaniwaniKvStore<FlowTokenContent>();\n\n\tget(key: string): Promise<FlowTokenContent | null> {\n\t\treturn this.store.get(key);\n\t}\n\n\tset(key: string, value: FlowTokenContent): Promise<void> {\n\t\treturn this.store.set(key, value);\n\t}\n\n\tdelete(key: string): Promise<void> {\n\t\treturn this.store.delete(key);\n\t}\n}\n","import type { z } from \"zod\";\nimport type { FlowConfig } from \"./@types\";\nimport { getObjectShape } from \"./nested\";\n\n/** Extract a human-readable label from a Zod schema for the AI protocol */\nfunction describeZodField(schema: z.ZodType): string {\n\tconst desc = schema.description ?? \"\";\n\tconst def = (\n\t\tschema as unknown as {\n\t\t\t_zod: { def: { type: string; entries?: Record<string, string> } };\n\t\t}\n\t)._zod?.def;\n\n\tif (def?.type === \"enum\" && def.entries) {\n\t\tconst vals = Object.keys(def.entries)\n\t\t\t.map((v) => `\"${v}\"`)\n\t\t\t.join(\" | \");\n\t\treturn desc ? `${vals} — ${desc}` : vals;\n\t}\n\n\treturn desc;\n}\n\nexport function buildFlowProtocol(config: FlowConfig): string {\n\tconst lines = [\n\t\t\"\",\n\t\t\"## FLOW EXECUTION PROTOCOL\",\n\t\t\"\",\n\t\t\"This tool implements a multi-step conversational flow. Follow this protocol exactly:\",\n\t\t\"\",\n\t\t'1. Call with `action: \"start\"` to begin and include `intent`.',\n\t\t\" `intent` must be a brief summary of the user's goal for this flow,\",\n\t\t\" including relevant prior context that led to triggering it, if available.\",\n\t\t\" Do NOT invent missing context.\",\n\t\t\" If the user's message already contains answers to likely questions,\",\n\t\t\" extract them into `stateUpdates` as `{ field: value }` pairs.\",\n\t\t\" The engine will auto-skip steps whose fields are already filled.\",\n\t\t\" Only extract values the user explicitly stated — do NOT guess or invent values.\",\n\t];\n\n\tif (config.state) {\n\t\tconst parts: string[] = [];\n\t\tfor (const [key, schema] of Object.entries(config.state)) {\n\t\t\tconst shape = getObjectShape(schema);\n\t\t\tif (shape) {\n\t\t\t\tconst groupDesc = schema.description ?? \"\";\n\t\t\t\tconst subFields = Object.entries(shape)\n\t\t\t\t\t.map(([subKey, subSchema]) => {\n\t\t\t\t\t\tconst info = describeZodField(subSchema);\n\t\t\t\t\t\treturn info\n\t\t\t\t\t\t\t? `\\`${key}.${subKey}\\` (${info})`\n\t\t\t\t\t\t\t: `\\`${key}.${subKey}\\``;\n\t\t\t\t\t})\n\t\t\t\t\t.join(\", \");\n\t\t\t\tparts.push(\n\t\t\t\t\tgroupDesc\n\t\t\t\t\t\t? `\\`${key}\\` (${groupDesc}): ${subFields}`\n\t\t\t\t\t\t: `\\`${key}\\`: ${subFields}`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst info = describeZodField(schema);\n\t\t\t\tparts.push(info ? `\\`${key}\\` (${info})` : `\\`${key}\\``);\n\t\t\t}\n\t\t}\n\t\tlines.push(` Known fields: ${parts.join(\", \")}.`);\n\t}\n\n\tlines.push(\n\t\t\" For grouped fields (shown as `group.subfield`), use dot-notation keys in `stateUpdates`:\",\n\t\t' e.g. `{ \"driver.name\": \"John\", \"driver.license\": \"ABC123\" }`.',\n\t\t\"2. The response JSON `status` field tells you what to do next:\",\n\t\t' - `\"interrupt\"`: Pause and ask the user. Two forms:',\n\t\t\" a. Single question: `{ question, field, context? }` — ask `question`, store answer in `field`.\",\n\t\t\" b. Multi-question: `{ questions: [{question, field}, ...], context? }` — ask ALL questions\",\n\t\t\" in one conversational message, collect all answers.\",\n\t\t\" `context` (if present) is hidden AI instructions — use to shape your response, do NOT show verbatim.\",\n\t\t\" Then call again with:\",\n\t\t' `action: \"continue\"`,',\n\t\t\" `stateUpdates` = answers keyed by their `field` names, plus any other fields the user mentioned.\",\n\t\t' - `\"widget\"`: The flow wants to show a UI widget. Call the tool named in the `tool`',\n\t\t\" field, passing the `data` object as the tool's input.\",\n\t\t\" Check the `interactive` field in the response:\",\n\t\t\" • `interactive: true` — The widget requires user interaction. After calling the display tool,\",\n\t\t\" STOP and WAIT for the user to interact with the widget. Do NOT call this flow tool again\",\n\t\t\" until the user has responded. When they do, call with:\",\n\t\t' `action: \"continue\"`,',\n\t\t\" `stateUpdates` = `{ [field]: <user's selection> }` plus any other fields the user mentioned.\",\n\t\t\" • `interactive: false` — The widget is display-only. Call the display tool, then immediately\",\n\t\t' call THIS flow tool again with `action: \"continue\"`. Do NOT wait for user interaction.',\n\t\t' - `\"complete\"`: The flow is done. Present the result to the user.',\n\t\t' - `\"error\"`: Something went wrong. Show the `error` message.',\n\t\t\"\",\n\t\t\"3. Do NOT invent state values. Only use `stateUpdates` for information the user explicitly provided.\",\n\t\t\"4. Include only the fields the user actually answered in `stateUpdates` — do NOT guess missing ones.\",\n\t\t\" If the user did not answer all pending questions, the engine will re-prompt for the remaining ones.\",\n\t\t\" If the user mentioned values for other known fields, include those too —\",\n\t\t\" they will be applied immediately and those steps will be auto-skipped.\",\n\t);\n\n\treturn lines.join(\"\\n\");\n}\n","import type { Edge, FlowConfig, NodeHandler, RegisteredFlow } from \"./@types\";\nimport { END, START } from \"./@types\";\nimport { compileFlow } from \"./compile\";\nimport type { FlowStore } from \"./flow-store\";\n\nfunction buildMermaidGraph(\n\tnodes: Map<string, unknown>,\n\tedges: Map<string, Edge<unknown>>,\n): string {\n\tconst lines: string[] = [\"flowchart TD\"];\n\tlines.push(` ${START}((Start))`);\n\tfor (const [name] of nodes) {\n\t\tlines.push(` ${name}[${name}]`);\n\t}\n\tlines.push(` ${END}((End))`);\n\tfor (const [from, edge] of edges) {\n\t\tif (edge.type === \"direct\") {\n\t\t\tlines.push(` ${from} --> ${edge.to}`);\n\t\t} else {\n\t\t\tlines.push(` ${from} -.-> ${from}_branch([?])`);\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * A LangGraph-inspired state graph builder for MCP tools.\n *\n * @example\n * ```ts\n * const flow = new StateGraph<MyState>({\n * id: \"onboarding\",\n * title: \"User Onboarding\",\n * description: \"Guides users through onboarding\",\n * })\n * .addNode(\"ask_name\", ({ interrupt }) => interrupt({ question: \"What's your name?\", field: \"name\" }))\n * .addNode(\"greet\", ({ state }) => ({ greeting: `Hello ${state.name}!` }))\n * .addEdge(START, \"ask_name\")\n * .addEdge(\"ask_name\", \"greet\")\n * .addEdge(\"greet\", END)\n * .compile();\n * ```\n */\nexport class StateGraph<\n\tTState extends Record<string, unknown>,\n\tTNodes extends string = never,\n> {\n\tprivate nodes = new Map<string, NodeHandler<TState>>();\n\tprivate edges = new Map<string, Edge<TState>>();\n\tprivate config: FlowConfig;\n\n\tconstructor(config: FlowConfig) {\n\t\tthis.config = config;\n\t}\n\n\t/**\n\t * Add a node with a handler.\n\t *\n\t * The handler receives a context object with `state`, `meta`, `interrupt`, and `showWidget`.\n\t */\n\taddNode<TName extends string>(\n\t\tname: TName,\n\t\thandler: NodeHandler<TState>,\n\t): StateGraph<TState, TNodes | TName> {\n\t\tif (name === START || name === END) {\n\t\t\tthrow new Error(\n\t\t\t\t`\"${name}\" is a reserved name and cannot be used as a node name`,\n\t\t\t);\n\t\t}\n\t\tif (this.nodes.has(name)) {\n\t\t\tthrow new Error(`Node \"${name}\" already exists`);\n\t\t}\n\n\t\tthis.nodes.set(name, handler);\n\t\treturn this as unknown as StateGraph<TState, TNodes | TName>;\n\t}\n\n\t/**\n\t * Add a direct edge between two nodes.\n\t *\n\t * Use `START` as `from` to set the entry point.\n\t * Use `END` as `to` to mark a terminal node.\n\t */\n\taddEdge(from: typeof START | TNodes, to: TNodes | typeof END): this {\n\t\tif (this.edges.has(from)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Node \"${from}\" already has an outgoing edge. Use addConditionalEdge for branching.`,\n\t\t\t);\n\t\t}\n\t\tthis.edges.set(from, { type: \"direct\", to });\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add a conditional edge from a node.\n\t *\n\t * The condition function receives current state and returns the name of the next node.\n\t */\n\taddConditionalEdge(\n\t\tfrom: TNodes,\n\t\tcondition: (\n\t\t\tstate: Partial<TState>,\n\t\t) => TNodes | typeof END | Promise<TNodes | typeof END>,\n\t): this {\n\t\tif (this.edges.has(from)) {\n\t\t\tthrow new Error(`Node \"${from}\" already has an outgoing edge.`);\n\t\t}\n\t\tthis.edges.set(from, { type: \"conditional\", condition });\n\t\treturn this;\n\t}\n\n\t/**\n\t * Generate a Mermaid `flowchart TD` diagram of the graph.\n\t *\n\t * Direct edges use solid arrows. Conditional edges use a dashed arrow\n\t * to a placeholder since branch targets are determined at runtime.\n\t *\n\t * @example\n\t * ```ts\n\t * console.log(graph.graph());\n\t * // flowchart TD\n\t * // __start__((Start))\n\t * // ask_name[ask_name]\n\t * // greet[greet]\n\t * // __end__((End))\n\t * // __start__ --> ask_name\n\t * // ask_name --> greet\n\t * // greet --> __end__\n\t * ```\n\t */\n\tgraph(): string {\n\t\treturn buildMermaidGraph(this.nodes, this.edges);\n\t}\n\n\t/**\n\t * Compile the graph into a RegisteredFlow that can be registered on an McpServer.\n\t *\n\t * Validates the graph structure and returns a registration-compatible object.\n\t */\n\tcompile(options?: { store?: FlowStore }): RegisteredFlow {\n\t\tthis.validate();\n\n\t\tconst nodesCopy = new Map(this.nodes);\n\t\tconst edgesCopy = new Map(this.edges);\n\n\t\treturn compileFlow<TState>({\n\t\t\tconfig: this.config,\n\t\t\tnodes: nodesCopy,\n\t\t\tedges: edgesCopy,\n\t\t\tstore: options?.store,\n\t\t\tgraph: () => buildMermaidGraph(nodesCopy, edgesCopy),\n\t\t});\n\t}\n\n\tprivate validate(): void {\n\t\t// Must have a START edge\n\t\tif (!this.edges.has(START)) {\n\t\t\tthrow new Error(\n\t\t\t\t'Flow must have an entry point. Add an edge from START: .addEdge(START, \"first_node\")',\n\t\t\t);\n\t\t}\n\n\t\t// START edge target must exist\n\t\tconst startEdge = this.edges.get(START);\n\t\tif (\n\t\t\tstartEdge?.type === \"direct\" &&\n\t\t\tstartEdge.to !== END &&\n\t\t\t!this.nodes.has(startEdge.to)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`START edge references non-existent node: \"${startEdge.to}\"`,\n\t\t\t);\n\t\t}\n\n\t\t// All static edge targets must reference existing nodes (or END)\n\t\tfor (const [from, edge] of this.edges) {\n\t\t\tif (from !== START && !this.nodes.has(from)) {\n\t\t\t\tthrow new Error(`Edge from non-existent node: \"${from}\"`);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tedge.type === \"direct\" &&\n\t\t\t\tedge.to !== END &&\n\t\t\t\t!this.nodes.has(edge.to)\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Edge from \"${from}\" references non-existent node: \"${edge.to}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Every node must have an outgoing edge\n\t\tfor (const [name] of this.nodes) {\n\t\t\tif (!this.edges.has(name)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Node \"${name}\" has no outgoing edge. Add one with .addEdge(\"${name}\", ...) or .addConditionalEdge(\"${name}\", ...)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n}\n","import type { z } from \"zod\";\nimport type { FlowConfig, InferFlowState } from \"./@types\";\nimport { StateGraph } from \"./state-graph\";\n\n/**\n * Create a new flow graph — convenience factory for `new StateGraph()`.\n *\n * The state type is automatically inferred from the `state` definition —\n * no explicit generic parameter needed.\n *\n * @example\n * ```ts\n * import { createFlow, interrupt, START, END } from \"@waniwani/sdk/mcp\";\n * import { z } from \"zod\";\n *\n * const flow = createFlow({\n * id: \"onboarding\",\n * title: \"User Onboarding\",\n * description: \"Guides users through onboarding. Use when a user wants to get started.\",\n * state: {\n * name: z.string().describe(\"The user's name\"),\n * email: z.string().describe(\"The user's email address\"),\n * },\n * })\n * .addNode(\"ask_name\", () => interrupt({ question: \"What's your name?\", field: \"name\" }))\n * .addNode(\"ask_email\", () => interrupt({ question: \"What's your email?\", field: \"email\" }))\n * .addEdge(START, \"ask_name\")\n * .addEdge(\"ask_name\", \"ask_email\")\n * .addEdge(\"ask_email\", END)\n * .compile();\n * ```\n */\nexport function createFlow<const TSchema extends Record<string, z.ZodType>>(\n\tconfig: Omit<FlowConfig, \"state\"> & { state: TSchema },\n): StateGraph<InferFlowState<TSchema>> {\n\treturn new StateGraph<InferFlowState<TSchema>>(config);\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type {\n\tFlowCompleteContent,\n\tFlowContent,\n\tFlowErrorContent,\n\tFlowInterruptContent,\n\tFlowTokenContent,\n\tFlowWidgetContent,\n\tRegisteredFlow,\n} from \"./@types\";\nimport type { FlowStore } from \"./flow-store\";\n\n// ============================================================================\n// Test harness for compiled flows\n// ============================================================================\n\ntype WithDecodedState = { decodedState: FlowTokenContent | null };\n\nexport type FlowTestResult =\n\t| (FlowInterruptContent & WithDecodedState)\n\t| (FlowWidgetContent & WithDecodedState)\n\t| (FlowCompleteContent & WithDecodedState)\n\t| (FlowErrorContent & WithDecodedState);\n\ntype Handler = (input: unknown, extra: unknown) => Promise<unknown>;\ntype RegisterToolArgs = [string, Record<string, unknown>, Handler];\n\nfunction parsePayload(result: Record<string, unknown>): FlowContent {\n\tconst content = result.content as Array<{ type: string; text?: string }>;\n\treturn JSON.parse(content[0]?.text ?? \"\") as FlowContent;\n}\n\nexport async function createFlowTestHarness(\n\tflow: RegisteredFlow,\n\toptions?: { stateStore?: FlowStore },\n) {\n\tconst store = options?.stateStore;\n\tconst registered: RegisterToolArgs[] = [];\n\tconst sessionId = `test-session-${Math.random().toString(36).slice(2, 10)}`;\n\n\tconst server = {\n\t\tregisterTool: (...args: unknown[]) => {\n\t\t\tregistered.push(args as RegisterToolArgs);\n\t\t},\n\t} as unknown as McpServer;\n\n\tawait flow.register(server);\n\n\tconst handler = registered[0]?.[2];\n\tif (!handler) {\n\t\tthrow new Error(`Flow \"${flow.id}\" did not register a handler`);\n\t}\n\n\tconst extra = { _meta: { sessionId } };\n\n\tasync function toResult(parsed: FlowContent): Promise<FlowTestResult> {\n\t\treturn {\n\t\t\t...parsed,\n\t\t\tdecodedState: store ? await store.get(sessionId) : null,\n\t\t} satisfies FlowTestResult;\n\t}\n\n\treturn {\n\t\tasync start(\n\t\t\tintent: string,\n\t\t\tstateUpdates?: Record<string, unknown>,\n\t\t): Promise<FlowTestResult> {\n\t\t\tconst result = (await handler(\n\t\t\t\t{\n\t\t\t\t\taction: \"start\",\n\t\t\t\t\tintent,\n\t\t\t\t\t...(stateUpdates ? { stateUpdates } : {}),\n\t\t\t\t},\n\t\t\t\textra,\n\t\t\t)) as Record<string, unknown>;\n\t\t\treturn toResult(parsePayload(result));\n\t\t},\n\n\t\tasync continueWith(\n\t\t\tstateUpdates?: Record<string, unknown>,\n\t\t): Promise<FlowTestResult> {\n\t\t\tconst result = (await handler(\n\t\t\t\t{\n\t\t\t\t\taction: \"continue\",\n\t\t\t\t\t...(stateUpdates ? { stateUpdates } : {}),\n\t\t\t\t},\n\t\t\t\textra,\n\t\t\t)) as Record<string, unknown>;\n\t\t\treturn toResult(parsePayload(result));\n\t\t},\n\n\t\tasync lastState(): Promise<FlowTokenContent | null> {\n\t\t\treturn store ? store.get(sessionId) : null;\n\t\t},\n\t};\n}\n","import type { WidgetCSP } from \"./types\";\n\n/**\n * MIME types for widget resources.\n * OpenAI Apps SDK uses \"text/html+skybridge\"\n * MCP Apps uses \"text/html;profile=mcp-app\"\n */\nexport const MIME_TYPE_OPENAI = \"text/html+skybridge\";\nexport const MIME_TYPE_MCP = \"text/html;profile=mcp-app\";\n\n// ---- HTML fetching ----\n\nexport const fetchHtml = async (\n\tbaseUrl: string,\n\tpath: string,\n): Promise<string> => {\n\tconst normalizedBase = baseUrl.endsWith(\"/\") ? baseUrl.slice(0, -1) : baseUrl;\n\tconst result = await fetch(`${normalizedBase}${path}`);\n\treturn await result.text();\n};\n\n// ---- OpenAI resource metadata ----\n\ninterface OpenAIResourceMeta {\n\t[key: string]: unknown;\n\t\"openai/widgetDescription\"?: string;\n\t\"openai/widgetPrefersBorder\"?: boolean;\n\t\"openai/widgetDomain\"?: string;\n\t\"openai/widgetCSP\"?: WidgetCSP;\n}\n\nexport function buildOpenAIResourceMeta(config: {\n\tdescription?: string;\n\tprefersBorder?: boolean;\n\twidgetDomain: string;\n\twidgetCSP?: WidgetCSP;\n}): OpenAIResourceMeta {\n\treturn {\n\t\t\"openai/widgetDescription\": config.description,\n\t\t\"openai/widgetPrefersBorder\": config.prefersBorder,\n\t\t\"openai/widgetDomain\": config.widgetDomain,\n\t\t...(config.widgetCSP && { \"openai/widgetCSP\": config.widgetCSP }),\n\t};\n}\n\n// ---- MCP Apps resource metadata ----\n\ninterface McpAppsResourceMeta {\n\t[key: string]: unknown;\n\tui?: {\n\t\tcsp?: {\n\t\t\tconnectDomains?: string[];\n\t\t\tresourceDomains?: string[];\n\t\t\tframeDomains?: string[];\n\t\t\tredirectDomains?: string[];\n\t\t};\n\t\tdomain?: string;\n\t\tprefersBorder?: boolean;\n\t};\n}\n\nexport function buildMcpAppsResourceMeta(config: {\n\tdescription?: string;\n\tprefersBorder?: boolean;\n\twidgetDomain?: string;\n\twidgetCSP?: WidgetCSP;\n}): McpAppsResourceMeta {\n\tconst csp = config.widgetCSP\n\t\t? {\n\t\t\t\tconnectDomains: config.widgetCSP.connect_domains,\n\t\t\t\tresourceDomains: config.widgetCSP.resource_domains,\n\t\t\t\tframeDomains: config.widgetCSP.frame_domains,\n\t\t\t\tredirectDomains: config.widgetCSP.redirect_domains,\n\t\t\t}\n\t\t: undefined;\n\n\treturn {\n\t\tui: {\n\t\t\t...(csp && { csp }),\n\t\t\t...(config.widgetDomain && { domain: config.widgetDomain }),\n\t\t\t...(config.prefersBorder !== undefined && {\n\t\t\t\tprefersBorder: config.prefersBorder,\n\t\t\t}),\n\t\t},\n\t};\n}\n\n// ---- Tool metadata (references resource URIs) ----\n\nexport function buildToolMeta(config: {\n\topenaiTemplateUri?: string;\n\tmcpTemplateUri?: string;\n\tinvoking: string;\n\tinvoked: string;\n\tautoHeight?: boolean;\n}) {\n\treturn {\n\t\t// OpenAI metadata\n\t\t...(config.openaiTemplateUri && {\n\t\t\t\"openai/outputTemplate\": config.openaiTemplateUri,\n\t\t}),\n\t\t\"openai/toolInvocation/invoking\": config.invoking,\n\t\t\"openai/toolInvocation/invoked\": config.invoked,\n\t\t\"openai/widgetAccessible\": true,\n\t\t\"openai/resultCanProduceWidget\": true,\n\t\t// MCP Apps metadata (nested)\n\t\t...(config.mcpTemplateUri && {\n\t\t\tui: {\n\t\t\t\tresourceUri: config.mcpTemplateUri,\n\t\t\t\t...(config.autoHeight && { autoHeight: true }),\n\t\t\t},\n\t\t}),\n\t\t// MCP Apps backward-compat flat key (for older hosts)\n\t\t...(config.mcpTemplateUri && {\n\t\t\t\"ui/resourceUri\": config.mcpTemplateUri,\n\t\t}),\n\t};\n}\n","import {\n\tbuildMcpAppsResourceMeta,\n\tbuildOpenAIResourceMeta,\n\tfetchHtml,\n\tMIME_TYPE_MCP,\n\tMIME_TYPE_OPENAI,\n} from \"./meta\";\nimport type { McpServer, RegisteredResource, ResourceConfig } from \"./types\";\n\n/**\n * Creates a reusable UI resource (HTML template) that can be attached\n * to tools or flow nodes.\n *\n * @example\n * ```ts\n * const pricingUI = createResource({\n * id: \"pricing_table\",\n * title: \"Pricing Table\",\n * baseUrl: \"https://my-app.com\",\n * htmlPath: \"/widgets/pricing\",\n * widgetDomain: \"my-app.com\",\n * });\n *\n * await pricingUI.register(server);\n * ```\n */\nexport function createResource(config: ResourceConfig): RegisteredResource {\n\tconst {\n\t\tid,\n\t\ttitle,\n\t\tdescription,\n\t\tbaseUrl,\n\t\thtmlPath,\n\t\twidgetDomain,\n\t\tprefersBorder = true,\n\t\tautoHeight = true,\n\t} = config;\n\n\t// Auto-generate CSP from baseUrl if not explicitly provided\n\tlet widgetCSP = config.widgetCSP ?? {\n\t\tconnect_domains: [baseUrl],\n\t\tresource_domains: [baseUrl],\n\t};\n\n\t// In development with localhost, add extra CSP domains for\n\t// Next.js dev features (WebSocket HMR, Turbopack font serving)\n\tif (process.env.NODE_ENV === \"development\") {\n\t\ttry {\n\t\t\tconst { hostname } = new URL(baseUrl);\n\t\t\tif (hostname === \"localhost\" || hostname === \"127.0.0.1\") {\n\t\t\t\twidgetCSP = {\n\t\t\t\t\t...widgetCSP,\n\t\t\t\t\tconnect_domains: [\n\t\t\t\t\t\t...(widgetCSP.connect_domains || []),\n\t\t\t\t\t\t`ws://${hostname}:*`,\n\t\t\t\t\t\t`wss://${hostname}:*`,\n\t\t\t\t\t],\n\t\t\t\t\tresource_domains: [\n\t\t\t\t\t\t...(widgetCSP.resource_domains || []),\n\t\t\t\t\t\t`http://${hostname}:*`,\n\t\t\t\t\t],\n\t\t\t\t};\n\t\t\t}\n\t\t} catch {\n\t\t\t// Invalid baseUrl — skip dev CSP additions\n\t\t}\n\t}\n\n\tconst openaiUri = `ui://widgets/apps-sdk/${id}.html`;\n\tconst mcpUri = `ui://widgets/ext-apps/${id}.html`;\n\n\t// Lazy HTML — fetched once, shared across all calls\n\tlet htmlPromise: Promise<string> | null = null;\n\tconst getHtml = () => {\n\t\tif (!htmlPromise) {\n\t\t\thtmlPromise = fetchHtml(baseUrl, htmlPath);\n\t\t}\n\t\treturn htmlPromise;\n\t};\n\n\t// Use description for UI metadata\n\tconst uiDescription = description;\n\n\tasync function register(server: McpServer): Promise<void> {\n\t\tconst html = await getHtml();\n\n\t\t// Register OpenAI Apps SDK resource\n\t\tserver.registerResource(\n\t\t\t`${id}-openai-widget`,\n\t\t\topenaiUri,\n\t\t\t{\n\t\t\t\ttitle,\n\t\t\t\tdescription: uiDescription,\n\t\t\t\tmimeType: MIME_TYPE_OPENAI,\n\t\t\t\t_meta: {\n\t\t\t\t\t\"openai/widgetDescription\": uiDescription,\n\t\t\t\t\t\"openai/widgetPrefersBorder\": prefersBorder,\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync (uri) => ({\n\t\t\t\tcontents: [\n\t\t\t\t\t{\n\t\t\t\t\t\turi: uri.href,\n\t\t\t\t\t\tmimeType: MIME_TYPE_OPENAI,\n\t\t\t\t\t\ttext: html,\n\t\t\t\t\t\t_meta: buildOpenAIResourceMeta({\n\t\t\t\t\t\t\tdescription: uiDescription,\n\t\t\t\t\t\t\tprefersBorder,\n\t\t\t\t\t\t\twidgetDomain,\n\t\t\t\t\t\t\twidgetCSP,\n\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t}),\n\t\t);\n\n\t\t// Register MCP Apps resource\n\t\tserver.registerResource(\n\t\t\t`${id}-mcp-widget`,\n\t\t\tmcpUri,\n\t\t\t{\n\t\t\t\ttitle,\n\t\t\t\tdescription: uiDescription,\n\t\t\t\tmimeType: MIME_TYPE_MCP,\n\t\t\t\t_meta: {\n\t\t\t\t\tui: {\n\t\t\t\t\t\tprefersBorder,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tasync (uri) => ({\n\t\t\t\tcontents: [\n\t\t\t\t\t{\n\t\t\t\t\t\turi: uri.href,\n\t\t\t\t\t\tmimeType: MIME_TYPE_MCP,\n\t\t\t\t\t\ttext: html,\n\t\t\t\t\t\t_meta: buildMcpAppsResourceMeta({\n\t\t\t\t\t\t\tdescription: uiDescription,\n\t\t\t\t\t\t\tprefersBorder,\n\t\t\t\t\t\t\twidgetDomain,\n\t\t\t\t\t\t\twidgetCSP,\n\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t}),\n\t\t);\n\t}\n\n\treturn {\n\t\tid,\n\t\ttitle,\n\t\tdescription,\n\t\topenaiUri,\n\t\tmcpUri,\n\t\tautoHeight,\n\t\tregister,\n\t};\n}\n","import type { ToolCallback } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { ShapeOutput } from \"@modelcontextprotocol/sdk/server/zod-compat.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n\tServerNotification,\n\tServerRequest,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { z } from \"zod\";\nimport { buildToolMeta } from \"../resources/meta\";\nimport { extractScopedClient } from \"../scoped-client\";\nimport type {\n\tMcpServer,\n\tRegisteredTool,\n\tToolConfig,\n\tToolHandler,\n} from \"./types\";\n\n/**\n * Creates an MCP tool with minimal boilerplate.\n *\n * When `handler()` returns `data`, the tool includes it as MCP `structuredContent`.\n * When `config.resource` is provided, the tool also returns widget metadata.\n *\n * @example\n * ```ts\n * // Widget tool (with resource)\n * const pricingTool = createTool({\n * resource: pricingUI,\n * description: \"Show pricing comparison\",\n * inputSchema: { postalCode: z.string() },\n * }, async ({ postalCode }) => ({\n * text: \"Pricing loaded\",\n * data: { postalCode, prices: [] },\n * }));\n *\n * // Plain tool (no resource)\n * const searchTool = createTool({\n * id: \"search\",\n * title: \"Search\",\n * description: \"Search the knowledge base\",\n * inputSchema: { query: z.string() },\n * }, async ({ query }) => ({\n * text: `Results for \"${query}\"`,\n * }));\n * ```\n */\nexport function createTool<TInput extends z.ZodRawShape>(\n\tconfig: ToolConfig<TInput>,\n\thandler: ToolHandler<TInput>,\n): RegisteredTool {\n\tconst {\n\t\tresource,\n\t\tdescription,\n\t\tinputSchema,\n\t\tannotations,\n\t\tautoInjectResultText = true,\n\t} = config;\n\n\tconst id = config.id ?? resource?.id;\n\tconst title = config.title ?? resource?.title;\n\n\tif (!id) {\n\t\tthrow new Error(\n\t\t\t\"createTool: `id` is required when no resource is provided\",\n\t\t);\n\t}\n\tif (!title) {\n\t\tthrow new Error(\n\t\t\t\"createTool: `title` is required when no resource is provided\",\n\t\t);\n\t}\n\n\t// Build widget metadata only when resource is present\n\tconst toolMeta = resource\n\t\t? buildToolMeta({\n\t\t\t\topenaiTemplateUri: resource.openaiUri,\n\t\t\t\tmcpTemplateUri: resource.mcpUri,\n\t\t\t\tinvoking: config.invoking ?? \"Loading...\",\n\t\t\t\tinvoked: config.invoked ?? \"Loaded\",\n\t\t\t\tautoHeight: resource.autoHeight,\n\t\t\t})\n\t\t: undefined;\n\n\treturn {\n\t\tid,\n\t\ttitle,\n\t\tdescription,\n\n\t\tasync register(server: McpServer): Promise<void> {\n\t\t\tserver.registerTool(\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttitle,\n\t\t\t\t\tdescription,\n\t\t\t\t\tinputSchema,\n\t\t\t\t\tannotations,\n\t\t\t\t\t...(toolMeta && { _meta: toolMeta }),\n\t\t\t\t},\n\t\t\t\t(async (args: ShapeOutput<TInput>, extra: unknown) => {\n\t\t\t\t\tconst requestExtra = extra as RequestHandlerExtra<\n\t\t\t\t\t\tServerRequest,\n\t\t\t\t\t\tServerNotification\n\t\t\t\t\t>;\n\t\t\t\t\tconst _meta: Record<string, unknown> = requestExtra._meta ?? {};\n\t\t\t\t\tconst waniwani = extractScopedClient(requestExtra);\n\n\t\t\t\t\tconst result = await handler(args, { extra: { _meta }, waniwani });\n\n\t\t\t\t\t// Widget tool: return structuredContent + widget metadata\n\t\t\t\t\tif (resource && result.data) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [{ type: \"text\", text: result.text }],\n\t\t\t\t\t\t\tstructuredContent: result.data,\n\t\t\t\t\t\t\t_meta: {\n\t\t\t\t\t\t\t\t...toolMeta,\n\t\t\t\t\t\t\t\t..._meta,\n\t\t\t\t\t\t\t\t...(autoInjectResultText === false\n\t\t\t\t\t\t\t\t\t? { \"waniwani/autoInjectResultText\": false }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\t// Plain tool: return text content, plus structuredContent when provided.\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: result.text }],\n\t\t\t\t\t\t...(result.data ? { structuredContent: result.data } : {}),\n\t\t\t\t\t\t...(autoInjectResultText === false\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t_meta: {\n\t\t\t\t\t\t\t\t\t\t\"waniwani/autoInjectResultText\": false,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t};\n\t\t\t\t}) as unknown as ToolCallback<TInput>,\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * Registers multiple tools on the server\n */\nexport async function registerTools(\n\tserver: McpServer,\n\ttools: RegisteredTool[],\n): Promise<void> {\n\tawait Promise.all(tools.map((t) => t.register(server)));\n}\n","// WaniWani SDK - Errors\n\nexport class WaniWaniError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic status: number,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"WaniWaniError\";\n\t}\n}\n","// KB Client — thin HTTP wrapper for knowledge base API\n\nimport { WaniWaniError } from \"../error.js\";\nimport type { InternalConfig } from \"../types.js\";\nimport type {\n\tKbClient,\n\tKbIngestFile,\n\tKbIngestResult,\n\tKbSearchOptions,\n\tKbSource,\n\tSearchResult,\n} from \"./types.js\";\n\nconst SDK_NAME = \"@waniwani/sdk\";\n\nexport function createKbClient(config: InternalConfig): KbClient {\n\tconst { apiUrl, apiKey } = config;\n\n\tfunction requireApiKey(): string {\n\t\tif (!apiKey) {\n\t\t\tthrow new Error(\"WANIWANI_API_KEY is not set\");\n\t\t}\n\t\treturn apiKey;\n\t}\n\n\tasync function request<T>(\n\t\tmethod: \"GET\" | \"POST\",\n\t\tpath: string,\n\t\tbody?: unknown,\n\t): Promise<T> {\n\t\tconst key = requireApiKey();\n\t\tconst url = `${apiUrl.replace(/\\/$/, \"\")}${path}`;\n\n\t\tconst headers: Record<string, string> = {\n\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\"X-WaniWani-SDK\": SDK_NAME,\n\t\t};\n\n\t\tconst init: RequestInit = { method, headers };\n\n\t\tif (body !== undefined) {\n\t\t\theaders[\"Content-Type\"] = \"application/json\";\n\t\t\tinit.body = JSON.stringify(body);\n\t\t}\n\n\t\tconst response = await fetch(url, init);\n\n\t\tif (!response.ok) {\n\t\t\tconst text = await response.text().catch(() => \"\");\n\t\t\tthrow new WaniWaniError(\n\t\t\t\ttext || `KB API error: HTTP ${response.status}`,\n\t\t\t\tresponse.status,\n\t\t\t);\n\t\t}\n\n\t\tconst json = (await response.json()) as { data: T };\n\t\treturn json.data;\n\t}\n\n\treturn {\n\t\tasync ingest(files: KbIngestFile[]): Promise<KbIngestResult> {\n\t\t\treturn request<KbIngestResult>(\"POST\", \"/api/mcp/kb/ingest\", {\n\t\t\t\tfiles,\n\t\t\t});\n\t\t},\n\n\t\tasync search(\n\t\t\tquery: string,\n\t\t\toptions?: KbSearchOptions,\n\t\t): Promise<SearchResult[]> {\n\t\t\treturn request<SearchResult[]>(\"POST\", \"/api/mcp/kb/search\", {\n\t\t\t\tquery,\n\t\t\t\t...options,\n\t\t\t});\n\t\t},\n\n\t\tasync sources(): Promise<KbSource[]> {\n\t\t\treturn request<KbSource[]>(\"GET\", \"/api/mcp/kb/sources\");\n\t\t},\n\t};\n}\n","import {\n\textractCorrelationId,\n\textractExternalUserId,\n\textractRequestId,\n\textractSessionId,\n\textractSource,\n\textractTraceId,\n} from \"../mcp/server/utils.js\";\nimport type { EventType, LegacyTrackEvent, TrackInput } from \"./@types.js\";\nimport type { V2CorrelationIds, V2EventEnvelope } from \"./v2-types.js\";\n\nconst DEFAULT_SOURCE = \"@waniwani/sdk\";\n\nexport interface MapTrackEventOptions {\n\tnow?: () => Date;\n\tgenerateId?: () => string;\n\tsource?: string;\n}\n\nexport function mapTrackEventToV2(\n\tinput: TrackInput,\n\toptions: MapTrackEventOptions = {},\n): V2EventEnvelope {\n\tconst now = options.now ?? (() => new Date());\n\tconst generateId = options.generateId ?? createEventId;\n\tconst eventName = resolveEventName(input);\n\tconst meta = toRecord(input.meta);\n\tconst metadata = toRecord(input.metadata);\n\tconst correlation = resolveCorrelationIds(input, meta);\n\tconst eventId = takeNonEmptyString(input.eventId) ?? generateId();\n\tconst timestamp = normalizeTimestamp(input.timestamp, now);\n\tconst source =\n\t\ttakeNonEmptyString(input.source) ??\n\t\textractSource(meta) ??\n\t\toptions.source ??\n\t\tDEFAULT_SOURCE;\n\tconst rawLegacy = isLegacyTrackEvent(input) ? { ...input } : undefined;\n\n\tconst mappedMetadata: Record<string, unknown> = {\n\t\t...metadata,\n\t};\n\tif (Object.keys(meta).length > 0) {\n\t\tmappedMetadata.meta = meta;\n\t}\n\tif (rawLegacy) {\n\t\tmappedMetadata.rawLegacy = rawLegacy;\n\t}\n\n\treturn {\n\t\tid: eventId,\n\t\ttype: \"mcp.event\",\n\t\tname: eventName,\n\t\tsource,\n\t\ttimestamp,\n\t\tcorrelation,\n\t\tproperties: mapProperties(input, eventName),\n\t\tmetadata: mappedMetadata,\n\t\trawLegacy,\n\t};\n}\n\nexport function createEventId(): string {\n\tif (\n\t\ttypeof crypto !== \"undefined\" &&\n\t\ttypeof crypto.randomUUID === \"function\"\n\t) {\n\t\treturn `evt_${crypto.randomUUID()}`;\n\t}\n\n\treturn `evt_${Math.random().toString(36).slice(2, 10)}_${Date.now().toString(36)}`;\n}\n\nfunction mapProperties(\n\tinput: TrackInput,\n\teventName: EventType,\n): Record<string, unknown> {\n\tif (!isLegacyTrackEvent(input)) {\n\t\treturn toRecord(input.properties);\n\t}\n\n\tconst legacyProperties = mapLegacyProperties(input, eventName);\n\tconst explicitProperties = toRecord(input.properties);\n\treturn {\n\t\t...legacyProperties,\n\t\t...explicitProperties,\n\t};\n}\n\nfunction mapLegacyProperties(\n\tinput: LegacyTrackEvent,\n\teventName: EventType,\n): Record<string, unknown> {\n\tswitch (eventName) {\n\t\tcase \"tool.called\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (takeNonEmptyString(input.toolName)) {\n\t\t\t\tproperties.name = input.toolName;\n\t\t\t}\n\t\t\tif (takeNonEmptyString(input.toolType)) {\n\t\t\t\tproperties.type = input.toolType;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tcase \"quote.succeeded\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (typeof input.quoteAmount === \"number\") {\n\t\t\t\tproperties.amount = input.quoteAmount;\n\t\t\t}\n\t\t\tif (takeNonEmptyString(input.quoteCurrency)) {\n\t\t\t\tproperties.currency = input.quoteCurrency;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tcase \"link.clicked\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (takeNonEmptyString(input.linkUrl)) {\n\t\t\t\tproperties.url = input.linkUrl;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tcase \"purchase.completed\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (typeof input.purchaseAmount === \"number\") {\n\t\t\t\tproperties.amount = input.purchaseAmount;\n\t\t\t}\n\t\t\tif (takeNonEmptyString(input.purchaseCurrency)) {\n\t\t\t\tproperties.currency = input.purchaseCurrency;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tdefault:\n\t\t\treturn {};\n\t}\n}\n\nfunction resolveEventName(input: TrackInput): EventType {\n\tif (isLegacyTrackEvent(input)) {\n\t\treturn input.eventType;\n\t}\n\treturn input.event;\n}\n\nfunction resolveCorrelationIds(\n\tinput: TrackInput,\n\tmeta: Record<string, unknown>,\n): V2CorrelationIds {\n\tconst requestId =\n\t\ttakeNonEmptyString(input.requestId) ?? extractRequestId(meta);\n\n\tconst sessionId =\n\t\ttakeNonEmptyString(input.sessionId) ?? extractSessionId(meta);\n\n\tconst traceId = takeNonEmptyString(input.traceId) ?? extractTraceId(meta);\n\n\tconst externalUserId =\n\t\ttakeNonEmptyString(input.externalUserId) ?? extractExternalUserId(meta);\n\n\tconst correlationId =\n\t\ttakeNonEmptyString(input.correlationId) ??\n\t\textractCorrelationId(meta) ??\n\t\trequestId;\n\n\tconst correlation: V2CorrelationIds = {};\n\tif (sessionId) {\n\t\tcorrelation.sessionId = sessionId;\n\t}\n\tif (traceId) {\n\t\tcorrelation.traceId = traceId;\n\t}\n\tif (requestId) {\n\t\tcorrelation.requestId = requestId;\n\t}\n\tif (correlationId) {\n\t\tcorrelation.correlationId = correlationId;\n\t}\n\tif (externalUserId) {\n\t\tcorrelation.externalUserId = externalUserId;\n\t}\n\treturn correlation;\n}\n\nfunction normalizeTimestamp(\n\tinput: string | Date | undefined,\n\tnow: () => Date,\n): string {\n\tif (input instanceof Date) {\n\t\treturn input.toISOString();\n\t}\n\tif (typeof input === \"string\") {\n\t\tconst date = new Date(input);\n\t\tif (!Number.isNaN(date.getTime())) {\n\t\t\treturn date.toISOString();\n\t\t}\n\t}\n\treturn now().toISOString();\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\treturn {};\n\t}\n\treturn value as Record<string, unknown>;\n}\n\nfunction takeNonEmptyString(value: unknown): string | undefined {\n\tif (typeof value !== \"string\") {\n\t\treturn undefined;\n\t}\n\tif (value.trim().length === 0) {\n\t\treturn undefined;\n\t}\n\treturn value;\n}\n\nfunction isLegacyTrackEvent(input: TrackInput): input is LegacyTrackEvent {\n\treturn \"eventType\" in input;\n}\n","import type {\n\tTrackingShutdownOptions,\n\tTrackingShutdownResult,\n} from \"./@types.js\";\nimport type {\n\tV2BatchRejectedEvent,\n\tV2BatchRequest,\n\tV2BatchResponse,\n\tV2EventEnvelope,\n} from \"./v2-types.js\";\n\nconst DEFAULT_ENDPOINT_PATH = \"/api/mcp/events/v2/batch\";\nconst DEFAULT_FLUSH_INTERVAL_MS = 1_000;\nconst DEFAULT_MAX_BATCH_SIZE = 20;\nconst DEFAULT_MAX_BUFFER_SIZE = 1_000;\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_RETRY_BASE_DELAY_MS = 200;\nconst DEFAULT_RETRY_MAX_DELAY_MS = 2_000;\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 2_000;\nconst SDK_NAME = \"@waniwani/sdk\";\n\nconst AUTH_FAILURE_STATUS = new Set([401, 403]);\nconst RETRYABLE_STATUS = new Set([408, 425, 429, 500, 502, 503, 504]);\n\ninterface Logger {\n\twarn: (message: string, ...args: unknown[]) => void;\n\terror: (message: string, ...args: unknown[]) => void;\n}\n\nexport interface V2TransportOptions {\n\tapiUrl: string;\n\tapiKey: string;\n\tendpointPath?: string;\n\tflushIntervalMs?: number;\n\tmaxBatchSize?: number;\n\tmaxBufferSize?: number;\n\tmaxRetries?: number;\n\tretryBaseDelayMs?: number;\n\tretryMaxDelayMs?: number;\n\tshutdownTimeoutMs?: number;\n\tsdkVersion?: string;\n\tfetchFn?: typeof fetch;\n\tlogger?: Logger;\n\tnow?: () => Date;\n\tsleep?: (delayMs: number) => Promise<void>;\n}\n\nexport interface V2BatchTransport {\n\tenqueue: (event: V2EventEnvelope) => void;\n\tflush: () => Promise<void>;\n\tshutdown: (\n\t\toptions?: TrackingShutdownOptions,\n\t) => Promise<TrackingShutdownResult>;\n\tpendingEvents: () => number;\n}\n\ntype SendBatchResult =\n\t| { kind: \"success\" }\n\t| { kind: \"retryable\"; reason: string }\n\t| { kind: \"permanent\"; reason: string }\n\t| { kind: \"auth\"; status: number }\n\t| {\n\t\t\tkind: \"partial\";\n\t\t\tretryable: V2EventEnvelope[];\n\t\t\tpermanent: V2EventEnvelope[];\n\t };\n\nexport function createV2BatchTransport(\n\toptions: V2TransportOptions,\n): V2BatchTransport {\n\treturn new BatchingV2Transport(options);\n}\n\nclass BatchingV2Transport implements V2BatchTransport {\n\tprivate readonly endpointUrl: string;\n\tprivate readonly flushIntervalMs: number;\n\tprivate readonly maxBatchSize: number;\n\tprivate readonly maxBufferSize: number;\n\tprivate readonly maxRetries: number;\n\tprivate readonly retryBaseDelayMs: number;\n\tprivate readonly retryMaxDelayMs: number;\n\tprivate readonly shutdownTimeoutMs: number;\n\tprivate readonly sdkVersion?: string;\n\tprivate readonly fetchFn: typeof fetch;\n\tprivate readonly logger: Logger;\n\tprivate readonly now: () => Date;\n\tprivate readonly sleep: (delayMs: number) => Promise<void>;\n\tprivate readonly apiKey: string;\n\n\tprivate readonly buffer: V2EventEnvelope[] = [];\n\tprivate flushTimer: ReturnType<typeof setInterval> | undefined;\n\tprivate flushScheduled = false;\n\tprivate flushScheduledTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate flushInFlight: Promise<void> | undefined;\n\tprivate inFlightCount = 0;\n\tprivate isStopped = false;\n\tprivate isShuttingDown = false;\n\n\tconstructor(options: V2TransportOptions) {\n\t\tthis.endpointUrl = joinUrl(\n\t\t\toptions.apiUrl,\n\t\t\toptions.endpointPath ?? DEFAULT_ENDPOINT_PATH,\n\t\t);\n\t\tthis.flushIntervalMs = options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;\n\t\tthis.maxBatchSize = options.maxBatchSize ?? DEFAULT_MAX_BATCH_SIZE;\n\t\tthis.maxBufferSize = options.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE;\n\t\tthis.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n\t\tthis.retryBaseDelayMs =\n\t\t\toptions.retryBaseDelayMs ?? DEFAULT_RETRY_BASE_DELAY_MS;\n\t\tthis.retryMaxDelayMs =\n\t\t\toptions.retryMaxDelayMs ?? DEFAULT_RETRY_MAX_DELAY_MS;\n\t\tthis.shutdownTimeoutMs =\n\t\t\toptions.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;\n\t\tthis.fetchFn = options.fetchFn ?? fetch;\n\t\tthis.logger = options.logger ?? console;\n\t\tthis.now = options.now ?? (() => new Date());\n\t\tthis.sleep =\n\t\t\toptions.sleep ??\n\t\t\t((delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)));\n\t\tthis.apiKey = options.apiKey;\n\t\tthis.sdkVersion = options.sdkVersion;\n\n\t\tif (this.flushIntervalMs > 0) {\n\t\t\tthis.flushTimer = setInterval(() => {\n\t\t\t\tvoid this.flush();\n\t\t\t}, this.flushIntervalMs);\n\t\t}\n\t}\n\n\tenqueue(event: V2EventEnvelope): void {\n\t\tif (this.isStopped || this.isShuttingDown) {\n\t\t\tthis.logger.warn(\n\t\t\t\t\"[WaniWani] Tracking transport is stopped, dropping event %s\",\n\t\t\t\tevent.id,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.buffer.length >= this.maxBufferSize) {\n\t\t\tconst dropCount = this.buffer.length - this.maxBufferSize + 1;\n\t\t\tthis.buffer.splice(0, dropCount);\n\t\t\tthis.logger.warn(\n\t\t\t\t\"[WaniWani] Tracking buffer overflow, dropped %d oldest event(s)\",\n\t\t\t\tdropCount,\n\t\t\t);\n\t\t}\n\n\t\tthis.buffer.push(event);\n\n\t\tif (this.buffer.length >= this.maxBatchSize) {\n\t\t\tvoid this.flush();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.scheduleMicroFlush();\n\t}\n\n\tpendingEvents(): number {\n\t\treturn this.buffer.length + this.inFlightCount;\n\t}\n\n\tasync flush(): Promise<void> {\n\t\tif (this.flushInFlight) {\n\t\t\treturn this.flushInFlight;\n\t\t}\n\t\tthis.flushInFlight = this.flushLoop().finally(() => {\n\t\t\tthis.flushInFlight = undefined;\n\t\t});\n\t\treturn this.flushInFlight;\n\t}\n\n\tasync shutdown(\n\t\toptions?: TrackingShutdownOptions,\n\t): Promise<TrackingShutdownResult> {\n\t\tthis.isShuttingDown = true;\n\t\tif (this.flushTimer) {\n\t\t\tclearInterval(this.flushTimer);\n\t\t\tthis.flushTimer = undefined;\n\t\t}\n\t\tif (this.flushScheduledTimer) {\n\t\t\tclearTimeout(this.flushScheduledTimer);\n\t\t\tthis.flushScheduledTimer = undefined;\n\t\t\tthis.flushScheduled = false;\n\t\t}\n\n\t\tconst timeoutMs = options?.timeoutMs ?? this.shutdownTimeoutMs;\n\t\tconst flushPromise = this.flush();\n\n\t\tif (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n\t\t\tawait flushPromise;\n\t\t\tthis.isStopped = true;\n\t\t\treturn { timedOut: false, pendingEvents: this.pendingEvents() };\n\t\t}\n\n\t\tconst timeoutSignal = Symbol(\"shutdown-timeout\");\n\t\tconst result = await Promise.race([\n\t\t\tflushPromise.then(() => \"flushed\" as const),\n\t\t\tthis.sleep(timeoutMs).then(() => timeoutSignal),\n\t\t]);\n\n\t\tif (result === timeoutSignal) {\n\t\t\tthis.isStopped = true;\n\t\t\treturn { timedOut: true, pendingEvents: this.pendingEvents() };\n\t\t}\n\n\t\tthis.isStopped = true;\n\t\treturn { timedOut: false, pendingEvents: this.pendingEvents() };\n\t}\n\n\tprivate scheduleMicroFlush(): void {\n\t\tif (this.flushScheduled) {\n\t\t\treturn;\n\t\t}\n\t\tthis.flushScheduled = true;\n\t\tthis.flushScheduledTimer = setTimeout(() => {\n\t\t\tthis.flushScheduledTimer = undefined;\n\t\t\tthis.flushScheduled = false;\n\t\t\tvoid this.flush();\n\t\t}, 0);\n\t}\n\n\tprivate async flushLoop(): Promise<void> {\n\t\twhile (this.buffer.length > 0 && !this.isStopped) {\n\t\t\tconst batch = this.buffer.splice(0, this.maxBatchSize);\n\t\t\tawait this.sendBatchWithRetry(batch);\n\t\t}\n\t}\n\n\tprivate async sendBatchWithRetry(batch: V2EventEnvelope[]): Promise<void> {\n\t\tlet attempt = 0;\n\t\tlet pendingBatch = batch;\n\n\t\twhile (pendingBatch.length > 0 && !this.isStopped) {\n\t\t\tthis.inFlightCount = pendingBatch.length;\n\t\t\tconst result = await this.sendBatchOnce(pendingBatch);\n\t\t\tthis.inFlightCount = 0;\n\n\t\t\tswitch (result.kind) {\n\t\t\t\tcase \"success\":\n\t\t\t\t\treturn;\n\t\t\t\tcase \"auth\":\n\t\t\t\t\tthis.stopTransportForAuthFailure(result.status, pendingBatch.length);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"permanent\":\n\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\"[WaniWani] Dropping %d event(s) after permanent failure: %s\",\n\t\t\t\t\t\tpendingBatch.length,\n\t\t\t\t\t\tresult.reason,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"retryable\":\n\t\t\t\t\tif (attempt >= this.maxRetries) {\n\t\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\t\"[WaniWani] Dropping %d event(s) after retry exhaustion: %s\",\n\t\t\t\t\t\t\tpendingBatch.length,\n\t\t\t\t\t\t\tresult.reason,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tawait this.sleep(this.backoffDelayMs(attempt));\n\t\t\t\t\tattempt += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\tcase \"partial\":\n\t\t\t\t\tif (result.permanent.length > 0) {\n\t\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\t\"[WaniWani] Dropping %d event(s) rejected as permanent\",\n\t\t\t\t\t\t\tresult.permanent.length,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (result.retryable.length === 0) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (attempt >= this.maxRetries) {\n\t\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\t\"[WaniWani] Dropping %d retryable event(s) after retry exhaustion\",\n\t\t\t\t\t\t\tresult.retryable.length,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tpendingBatch = result.retryable;\n\t\t\t\t\tawait this.sleep(this.backoffDelayMs(attempt));\n\t\t\t\t\tattempt += 1;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async sendBatchOnce(\n\t\tevents: V2EventEnvelope[],\n\t): Promise<SendBatchResult> {\n\t\tlet response: Response;\n\n\t\ttry {\n\t\t\tresponse = await this.fetchFn(this.endpointUrl, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tAuthorization: `Bearer ${this.apiKey}`,\n\t\t\t\t\t\"X-WaniWani-SDK\": SDK_NAME,\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(this.makeBatchRequest(events)),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tkind: \"retryable\",\n\t\t\t\treason: getErrorMessage(error),\n\t\t\t};\n\t\t}\n\n\t\tif (AUTH_FAILURE_STATUS.has(response.status)) {\n\t\t\treturn { kind: \"auth\", status: response.status };\n\t\t}\n\n\t\tif (RETRYABLE_STATUS.has(response.status)) {\n\t\t\treturn {\n\t\t\t\tkind: \"retryable\",\n\t\t\t\treason: `HTTP ${response.status}`,\n\t\t\t};\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\treturn {\n\t\t\t\tkind: \"permanent\",\n\t\t\t\treason: `HTTP ${response.status}`,\n\t\t\t};\n\t\t}\n\n\t\tconst data = await parseJsonResponse<V2BatchResponse>(response);\n\t\tif (!data?.rejected || data.rejected.length === 0) {\n\t\t\treturn { kind: \"success\" };\n\t\t}\n\n\t\tconst partial = this.classifyRejectedEvents(events, data.rejected);\n\t\tif (partial.retryable.length === 0 && partial.permanent.length === 0) {\n\t\t\treturn { kind: \"success\" };\n\t\t}\n\n\t\treturn {\n\t\t\tkind: \"partial\",\n\t\t\tretryable: partial.retryable,\n\t\t\tpermanent: partial.permanent,\n\t\t};\n\t}\n\n\tprivate makeBatchRequest(events: V2EventEnvelope[]): V2BatchRequest {\n\t\treturn {\n\t\t\tsentAt: this.now().toISOString(),\n\t\t\tsource: {\n\t\t\t\tsdk: SDK_NAME,\n\t\t\t\tversion: this.sdkVersion ?? \"0.0.0\",\n\t\t\t},\n\t\t\tevents,\n\t\t};\n\t}\n\n\tprivate classifyRejectedEvents(\n\t\tevents: V2EventEnvelope[],\n\t\trejected: V2BatchRejectedEvent[],\n\t): {\n\t\tretryable: V2EventEnvelope[];\n\t\tpermanent: V2EventEnvelope[];\n\t} {\n\t\tconst byId = new Map(events.map((event) => [event.id, event]));\n\t\tconst retryable: V2EventEnvelope[] = [];\n\t\tconst permanent: V2EventEnvelope[] = [];\n\n\t\tfor (const rejectedEvent of rejected) {\n\t\t\tconst event = byId.get(rejectedEvent.eventId);\n\t\t\tif (!event) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isRetryableRejectedEvent(rejectedEvent)) {\n\t\t\t\tretryable.push(event);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tpermanent.push(event);\n\t\t}\n\n\t\treturn { retryable, permanent };\n\t}\n\n\tprivate backoffDelayMs(attempt: number): number {\n\t\tconst rawDelay = this.retryBaseDelayMs * 2 ** attempt;\n\t\treturn Math.min(rawDelay, this.retryMaxDelayMs);\n\t}\n\n\tprivate stopTransportForAuthFailure(\n\t\tstatus: number,\n\t\trejectedCount: number,\n\t): void {\n\t\tthis.isStopped = true;\n\t\tconst buffered = this.buffer.length;\n\t\tthis.buffer.splice(0, buffered);\n\t\tthis.logger.error(\n\t\t\t\"[WaniWani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)\",\n\t\t\tstatus,\n\t\t\trejectedCount + buffered,\n\t\t);\n\t}\n}\n\nfunction isRetryableRejectedEvent(\n\trejectedEvent: V2BatchRejectedEvent,\n): boolean {\n\tif (rejectedEvent.retryable === true) {\n\t\treturn true;\n\t}\n\tconst code = rejectedEvent.code.toLowerCase();\n\treturn (\n\t\tcode.includes(\"timeout\") ||\n\t\tcode.includes(\"temporary\") ||\n\t\tcode.includes(\"unavailable\") ||\n\t\tcode.includes(\"rate_limit\") ||\n\t\tcode.includes(\"transient\") ||\n\t\tcode.includes(\"server\")\n\t);\n}\n\nasync function parseJsonResponse<T>(\n\tresponse: Response,\n): Promise<T | undefined> {\n\tconst body = await response.text();\n\tif (!body) {\n\t\treturn undefined;\n\t}\n\ttry {\n\t\treturn JSON.parse(body) as T;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction joinUrl(apiUrl: string, endpointPath: string): string {\n\tconst normalizedBase = apiUrl.endsWith(\"/\") ? apiUrl : `${apiUrl}/`;\n\tconst normalizedPath = endpointPath.startsWith(\"/\")\n\t\t? endpointPath.slice(1)\n\t\t: endpointPath;\n\treturn `${normalizedBase}${normalizedPath}`;\n}\n\nfunction getErrorMessage(error: unknown): string {\n\tif (error instanceof Error) {\n\t\treturn error.message;\n\t}\n\treturn String(error);\n}\n","// Tracking Module\n\nimport type { InternalConfig } from \"../types.js\";\nimport type {\n\tTrackInput,\n\tTrackingClient,\n\tTrackingShutdownOptions,\n} from \"./@types.js\";\nimport { mapTrackEventToV2 } from \"./mapper.js\";\nimport { createV2BatchTransport } from \"./transport.js\";\n\n// Re-export types\nexport type {\n\tEventType,\n\tLegacyTrackEvent,\n\tLinkClickedProperties,\n\tPurchaseCompletedProperties,\n\tQuoteSucceededProperties,\n\tToolCalledProperties,\n\tTrackEvent,\n\tTrackInput,\n\tTrackingClient,\n\tTrackingConfig,\n\tTrackingShutdownOptions,\n\tTrackingShutdownResult,\n} from \"./@types.js\";\nexport { createEventId, mapTrackEventToV2 } from \"./mapper.js\";\nexport type {\n\tV2BatchRejectedEvent,\n\tV2BatchRequest,\n\tV2BatchResponse,\n\tV2CorrelationIds,\n\tV2EnvelopeType,\n\tV2EventEnvelope,\n} from \"./v2-types.js\";\n\nexport function createTrackingClient(config: InternalConfig): TrackingClient {\n\tconst { apiUrl, apiKey, tracking } = config;\n\n\tfunction requireApiKey(): string {\n\t\tif (!apiKey) {\n\t\t\tthrow new Error(\"WANIWANI_API_KEY is not set\");\n\t\t}\n\t\treturn apiKey;\n\t}\n\n\tconst transport = apiKey\n\t\t? createV2BatchTransport({\n\t\t\t\tapiUrl,\n\t\t\t\tapiKey,\n\t\t\t\tendpointPath: tracking.endpointPath,\n\t\t\t\tflushIntervalMs: tracking.flushIntervalMs,\n\t\t\t\tmaxBatchSize: tracking.maxBatchSize,\n\t\t\t\tmaxBufferSize: tracking.maxBufferSize,\n\t\t\t\tmaxRetries: tracking.maxRetries,\n\t\t\t\tretryBaseDelayMs: tracking.retryBaseDelayMs,\n\t\t\t\tretryMaxDelayMs: tracking.retryMaxDelayMs,\n\t\t\t\tshutdownTimeoutMs: tracking.shutdownTimeoutMs,\n\t\t\t})\n\t\t: undefined;\n\n\tconst client: TrackingClient = {\n\t\tasync identify(\n\t\t\tuserId: string,\n\t\t\tproperties?: Record<string, unknown>,\n\t\t\tmeta?: Record<string, unknown>,\n\t\t): Promise<{ eventId: string }> {\n\t\t\trequireApiKey();\n\t\t\tconst mappedEvent = mapTrackEventToV2({\n\t\t\t\tevent: \"user.identified\",\n\t\t\t\texternalUserId: userId,\n\t\t\t\tproperties,\n\t\t\t\tmeta,\n\t\t\t});\n\t\t\ttransport?.enqueue(mappedEvent);\n\t\t\treturn { eventId: mappedEvent.id };\n\t\t},\n\t\tasync track(event: TrackInput): Promise<{ eventId: string }> {\n\t\t\trequireApiKey();\n\t\t\tconst mappedEvent = mapTrackEventToV2(event);\n\t\t\ttransport?.enqueue(mappedEvent);\n\t\t\treturn { eventId: mappedEvent.id };\n\t\t},\n\t\tasync flush(): Promise<void> {\n\t\t\trequireApiKey();\n\t\t\tawait transport?.flush();\n\t\t},\n\t\tasync shutdown(options?: TrackingShutdownOptions) {\n\t\t\trequireApiKey();\n\t\t\treturn (\n\t\t\t\t(await transport?.shutdown({\n\t\t\t\t\ttimeoutMs: options?.timeoutMs ?? tracking.shutdownTimeoutMs,\n\t\t\t\t})) ?? { timedOut: false, pendingEvents: 0 }\n\t\t\t);\n\t\t},\n\t};\n\n\tif (transport) {\n\t\tattachShutdownHooks(client, tracking.shutdownTimeoutMs);\n\t}\n\treturn client;\n}\n\nfunction attachShutdownHooks(\n\tclient: TrackingClient,\n\tdefaultTimeoutMs: number,\n): void {\n\tif (\n\t\ttypeof process === \"undefined\" ||\n\t\ttypeof process.once !== \"function\" ||\n\t\ttypeof process.on !== \"function\"\n\t) {\n\t\treturn;\n\t}\n\n\tconst shutdown = () => {\n\t\tvoid client.shutdown({ timeoutMs: defaultTimeoutMs });\n\t};\n\n\tprocess.once(\"beforeExit\", shutdown);\n\tprocess.once(\"SIGINT\", shutdown);\n\tprocess.once(\"SIGTERM\", shutdown);\n}\n","// WaniWani SDK - Main Entry\n\nimport { createKbClient } from \"./kb/client.js\";\nimport type { WaniWaniProjectConfig } from \"./project-config.js\";\nimport { createTrackingClient } from \"./tracking/index.js\";\nimport type { WaniWaniClient, WaniWaniConfig } from \"./types.js\";\n\n/**\n * Create a WaniWani SDK client\n *\n * @param config - Configuration options. When omitted, reads from the global\n * config registered by `defineConfig()`, then falls back to env vars.\n * @returns A fully typed WaniWani client\n *\n * @example\n * ```typescript\n * import { waniwani } from \"@waniwani/sdk\";\n * import { toNextJsHandler } from \"@waniwani/sdk/next-js\";\n *\n * const wani = waniwani({ apiKey: \"...\" });\n *\n * // Next.js route handler\n * export const { GET, POST } = toNextJsHandler(wani, {\n * chat: { systemPrompt: \"You are a helpful assistant.\" },\n * });\n * ```\n */\nexport function waniwani(\n\tconfig?: WaniWaniConfig | WaniWaniProjectConfig,\n): WaniWaniClient {\n\tconst effective = config;\n\n\tconst apiUrl = effective?.apiUrl ?? \"https://app.waniwani.ai\";\n\tconst apiKey = effective?.apiKey ?? process.env.WANIWANI_API_KEY;\n\tconst trackingConfig = {\n\t\tendpointPath:\n\t\t\teffective?.tracking?.endpointPath ?? \"/api/mcp/events/v2/batch\",\n\t\tflushIntervalMs: effective?.tracking?.flushIntervalMs ?? 1_000,\n\t\tmaxBatchSize: effective?.tracking?.maxBatchSize ?? 20,\n\t\tmaxBufferSize: effective?.tracking?.maxBufferSize ?? 1_000,\n\t\tmaxRetries: effective?.tracking?.maxRetries ?? 3,\n\t\tretryBaseDelayMs: effective?.tracking?.retryBaseDelayMs ?? 200,\n\t\tretryMaxDelayMs: effective?.tracking?.retryMaxDelayMs ?? 2_000,\n\t\tshutdownTimeoutMs: effective?.tracking?.shutdownTimeoutMs ?? 2_000,\n\t};\n\n\tconst internalConfig = { apiUrl, apiKey, tracking: trackingConfig };\n\n\t// Compose client from modules\n\tconst trackingClient = createTrackingClient(internalConfig);\n\tconst kbClient = createKbClient(internalConfig);\n\n\treturn {\n\t\t...trackingClient,\n\t\tkb: kbClient,\n\t\t_config: internalConfig,\n\t};\n}\n","/**\n * Server-side API route handler for widget tracking events.\n *\n * Receives batched events from the `useWaniwani` React hook and forwards them\n * to the WaniWani backend using the server-side SDK.\n *\n * @example Next.js App Router\n * ```typescript\n * // app/api/waniwani/track/route.ts\n * import { createTrackingRoute } from \"@waniwani/sdk/mcp\";\n *\n * const handler = createTrackingRoute({\n * apiKey: process.env.WANIWANI_API_KEY,\n * apiUrl: process.env.WANIWANI_API_URL,\n * });\n *\n * export { handler as POST };\n * ```\n */\n\nimport type { EventType, TrackInput } from \"../../tracking/@types.js\";\nimport type { WaniWaniConfig } from \"../../types.js\";\nimport { waniwani } from \"../../waniwani.js\";\n\nexport interface TrackingRouteOptions {\n\t/** API key for the WaniWani backend. Defaults to WANIWANI_API_KEY env var. */\n\tapiKey?: string;\n\t/** Base URL for the WaniWani backend. Defaults to https://app.waniwani.ai. */\n\tapiUrl?: string;\n}\n\n/** Shape of a single event from the WidgetTransport client. */\ninterface WidgetEventPayload {\n\tevent_id?: string;\n\tevent_type?: string;\n\ttimestamp?: string;\n\tsource?: string;\n\tsession_id?: string;\n\ttrace_id?: string;\n\tuser_id?: string;\n\tevent_name?: string;\n\tmetadata?: Record<string, unknown>;\n\t[key: string]: unknown;\n}\n\n/** Batch payload sent by WidgetTransport. */\ninterface BatchPayload {\n\tevents: WidgetEventPayload[];\n\tsentAt?: string;\n}\n\n/**\n * Map a WidgetEvent from the client to the SDK's TrackInput format.\n */\nfunction mapWidgetEvent(ev: WidgetEventPayload): TrackInput {\n\tconst eventType = ev.event_type ?? \"widget_click\";\n\n\t// For manual tracking methods (track, identify, step, conversion),\n\t// use \"widget_<type>\" as the event name. Auto-capture events already\n\t// have the \"widget_\" prefix.\n\tconst isAutoCapture = eventType.startsWith(\"widget_\");\n\tconst eventName: EventType = (\n\t\tisAutoCapture ? eventType : `widget_${eventType}`\n\t) as EventType;\n\n\t// Merge metadata + any extra properties from the event\n\tconst properties: Record<string, unknown> = {\n\t\t...(ev.metadata ?? {}),\n\t};\n\tif (ev.event_name) {\n\t\tproperties.event_name = ev.event_name;\n\t}\n\n\treturn {\n\t\tevent: eventName,\n\t\tproperties,\n\t\tsessionId: ev.session_id,\n\t\ttraceId: ev.trace_id,\n\t\texternalUserId: ev.user_id,\n\t\teventId: ev.event_id,\n\t\ttimestamp: ev.timestamp,\n\t\tsource: ev.source ?? \"widget\",\n\t} as TrackInput;\n}\n\n/**\n * Creates a POST handler that receives tracking events from `useWaniwani`\n * and forwards them to the WaniWani backend.\n */\nexport function createTrackingRoute(options?: TrackingRouteOptions) {\n\tconst config: WaniWaniConfig = {\n\t\tapiKey: options?.apiKey,\n\t\tapiUrl: options?.apiUrl,\n\t};\n\n\t// Lazy singleton — created on first request\n\tlet client: ReturnType<typeof waniwani> | undefined;\n\n\tfunction getClient() {\n\t\tif (!client) {\n\t\t\tclient = waniwani(config);\n\t\t}\n\t\treturn client;\n\t}\n\n\treturn async function handler(request: Request): Promise<Response> {\n\t\tlet body: BatchPayload;\n\t\ttry {\n\t\t\tbody = (await request.json()) as BatchPayload;\n\t\t} catch {\n\t\t\treturn new Response(JSON.stringify({ error: \"Invalid JSON\" }), {\n\t\t\t\tstatus: 400,\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t});\n\t\t}\n\n\t\tif (!Array.isArray(body.events) || body.events.length === 0) {\n\t\t\treturn new Response(\n\t\t\t\tJSON.stringify({ error: \"Missing or empty events array\" }),\n\t\t\t\t{\n\t\t\t\t\tstatus: 400,\n\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\tconst c = getClient();\n\t\t\tconst results: string[] = [];\n\n\t\t\tfor (const ev of body.events) {\n\t\t\t\tconst trackInput = mapWidgetEvent(ev);\n\t\t\t\tconst result = await c.track(trackInput);\n\t\t\t\tresults.push(result.eventId);\n\t\t\t}\n\n\t\t\tawait c.flush();\n\n\t\t\treturn new Response(\n\t\t\t\tJSON.stringify({ ok: true, accepted: results.length }),\n\t\t\t\t{\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t},\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"Unknown error\";\n\t\t\treturn new Response(JSON.stringify({ error: message }), {\n\t\t\t\tstatus: 500,\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t});\n\t\t}\n\t};\n}\n","/**\n * Widget token minting — fetches short-lived JWTs from the WaniWani backend\n * so browser widgets can POST events directly.\n */\n\ninterface WidgetTokenConfig {\n\tapiUrl: string;\n\tapiKey: string;\n}\n\ninterface WidgetTokenResult {\n\ttoken: string;\n\texpiresAt: string;\n}\n\ninterface CachedToken {\n\ttoken: string;\n\t/** Unix ms when the token expires */\n\texpiresAt: number;\n}\n\n/** Re-mint when < 2 minutes remain to avoid using nearly-expired tokens. */\nconst EXPIRY_BUFFER_MS = 2 * 60 * 1000;\n\nexport class WidgetTokenCache {\n\tprivate cached: CachedToken | null = null;\n\tprivate pending: Promise<string | null> | null = null;\n\tprivate readonly config: WidgetTokenConfig;\n\n\tconstructor(config: WidgetTokenConfig) {\n\t\tthis.config = config;\n\t}\n\n\t/**\n\t * Get a valid widget token. Returns a cached token if still fresh,\n\t * otherwise mints a new one. Returns `null` on failure.\n\t */\n\tasync getToken(sessionId?: string, traceId?: string): Promise<string | null> {\n\t\tif (this.cached && Date.now() < this.cached.expiresAt - EXPIRY_BUFFER_MS) {\n\t\t\treturn this.cached.token;\n\t\t}\n\n\t\t// Deduplicate concurrent requests\n\t\tif (this.pending) {\n\t\t\treturn this.pending;\n\t\t}\n\n\t\tthis.pending = this.mint(sessionId, traceId).finally(() => {\n\t\t\tthis.pending = null;\n\t\t});\n\n\t\treturn this.pending;\n\t}\n\n\tprivate async mint(\n\t\tsessionId?: string,\n\t\ttraceId?: string,\n\t): Promise<string | null> {\n\t\tconst url = joinUrl(this.config.apiUrl, \"/api/mcp/widget-tokens\");\n\n\t\tconst body: Record<string, string> = {};\n\t\tif (sessionId) {\n\t\t\tbody.sessionId = sessionId;\n\t\t}\n\t\tif (traceId) {\n\t\t\tbody.traceId = traceId;\n\t\t}\n\n\t\ttry {\n\t\t\tconst response = await fetch(url, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tAuthorization: `Bearer ${this.config.apiKey}`,\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tconst json = (await response.json()) as Record<string, unknown>;\n\n\t\t\t// Support both flat { token, expiresAt } and nested { data: { token, expiresAt } }\n\t\t\tconst result = (\n\t\t\t\tjson.data && typeof json.data === \"object\" ? json.data : json\n\t\t\t) as WidgetTokenResult;\n\n\t\t\tconst expiresAtMs = new Date(result.expiresAt).getTime();\n\t\t\tif (!result.token || Number.isNaN(expiresAtMs)) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tthis.cached = {\n\t\t\t\ttoken: result.token,\n\t\t\t\texpiresAt: expiresAtMs,\n\t\t\t};\n\n\t\t\treturn result.token;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n}\n\nfunction joinUrl(apiUrl: string, path: string): string {\n\tconst base = apiUrl.endsWith(\"/\") ? apiUrl.slice(0, -1) : apiUrl;\n\treturn `${base}${path}`;\n}\n","import type {\n\tToolCalledProperties,\n\tTrackInput,\n} from \"../../../tracking/index.js\";\nimport type { WaniWaniClient } from \"../../../types.js\";\nimport { extractSessionId, extractSource } from \"../utils.js\";\nimport type { WidgetTokenCache } from \"../widget-token.js\";\n\ntype UnknownRecord = Record<string, unknown>;\n\nexport type WaniwaniTracker = Pick<\n\tWaniWaniClient,\n\t\"flush\" | \"track\" | \"identify\" | \"kb\" | \"_config\"\n>;\n\nconst SESSION_ID_KEY = \"waniwani/sessionId\";\nconst GEO_LOCATION_KEY = \"waniwani/geoLocation\";\nconst LEGACY_USER_LOCATION_KEY = \"waniwani/userLocation\";\n\nexport function isRecord(value: unknown): value is UnknownRecord {\n\treturn Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function extractMeta(extra: unknown): UnknownRecord | undefined {\n\tif (!isRecord(extra)) {\n\t\treturn undefined;\n\t}\n\tconst meta = extra._meta;\n\treturn isRecord(meta) ? meta : undefined;\n}\n\nexport function extractErrorText(result: unknown): string | undefined {\n\tif (!isRecord(result)) {\n\t\treturn undefined;\n\t}\n\tconst content = (result as UnknownRecord).content;\n\tif (!Array.isArray(content)) {\n\t\treturn undefined;\n\t}\n\tconst textPart = content.find(\n\t\t(c: unknown) =>\n\t\t\tisRecord(c) && c.type === \"text\" && typeof c.text === \"string\",\n\t) as UnknownRecord | undefined;\n\treturn textPart?.text as string | undefined;\n}\n\nexport function resolveToolType(\n\ttoolName: string,\n\ttoolTypeOption:\n\t\t| ToolCalledProperties[\"type\"]\n\t\t| ((toolName: string) => ToolCalledProperties[\"type\"] | undefined)\n\t\t| undefined,\n): ToolCalledProperties[\"type\"] {\n\tif (typeof toolTypeOption === \"function\") {\n\t\treturn toolTypeOption(toolName) ?? \"other\";\n\t}\n\treturn toolTypeOption ?? \"other\";\n}\n\nexport function buildTrackInput(\n\ttoolName: string,\n\textra: unknown,\n\toptions: {\n\t\ttoolType?: typeof resolveToolType extends (n: string, o: infer T) => unknown\n\t\t\t? T\n\t\t\t: never;\n\t\tmetadata?: UnknownRecord;\n\t},\n\ttiming?: { durationMs: number; status: string; errorMessage?: string },\n\tclientInfo?: { name: string; version: string },\n\tio?: { input?: unknown; output?: unknown },\n): TrackInput {\n\tconst toolType = resolveToolType(toolName, options.toolType);\n\tconst meta = extractMeta(extra);\n\tconsole.log(\n\t\t\"[waniwani:debug] buildTrackInput meta:\",\n\t\tJSON.stringify(meta),\n\t\t\"-> source:\",\n\t\textractSource(meta),\n\t);\n\n\treturn {\n\t\tevent: \"tool.called\",\n\t\tproperties: {\n\t\t\tname: toolName,\n\t\t\ttype: toolType,\n\t\t\t...(timing ?? {}),\n\t\t\t...(io?.input !== undefined && { input: io.input }),\n\t\t\t...(io?.output !== undefined && { output: io.output }),\n\t\t},\n\t\tmeta,\n\t\tsource: extractSource(meta),\n\t\tmetadata: {\n\t\t\t...(options.metadata ?? {}),\n\t\t\t...(clientInfo && { clientInfo }),\n\t\t},\n\t};\n}\n\nexport async function safeTrack(\n\ttracker: Pick<WaniWaniClient, \"track\">,\n\tinput: TrackInput,\n\tonError?: (error: Error) => void,\n): Promise<void> {\n\ttry {\n\t\tawait tracker.track(input);\n\t} catch (error) {\n\t\tonError?.(toError(error));\n\t}\n}\n\nexport async function safeFlush(\n\ttracker: Pick<WaniWaniClient, \"flush\">,\n\tonError?: (error: Error) => void,\n): Promise<void> {\n\ttry {\n\t\tawait tracker.flush();\n\t} catch (error) {\n\t\tonError?.(toError(error));\n\t}\n}\n\nexport async function injectWidgetConfig(\n\tresult: unknown,\n\tcache: WidgetTokenCache | null,\n\tapiUrl: string,\n\textra?: unknown,\n\tonError?: (error: Error) => void,\n): Promise<void> {\n\tif (!isRecord(result)) {\n\t\treturn;\n\t}\n\n\tif (!isRecord(result._meta)) {\n\t\t(result as UnknownRecord)._meta = {};\n\t}\n\n\tconst meta = (result as UnknownRecord)._meta as UnknownRecord;\n\tconst existingWaniwaniConfig = isRecord(meta.waniwani)\n\t\t? (meta.waniwani as UnknownRecord)\n\t\t: undefined;\n\tconst waniwaniConfig: UnknownRecord = {\n\t\t...(existingWaniwaniConfig ?? {}),\n\t\tendpoint:\n\t\t\texistingWaniwaniConfig?.endpoint ??\n\t\t\t`${apiUrl.replace(/\\/$/, \"\")}/api/mcp/events/v2/batch`,\n\t};\n\n\tif (cache) {\n\t\ttry {\n\t\t\tconst token = await cache.getToken();\n\t\t\tif (token) {\n\t\t\t\twaniwaniConfig.token = token;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tonError?.(toError(error));\n\t\t}\n\t}\n\n\tconst sessionId = extractSessionId(meta);\n\tif (sessionId) {\n\t\tif (!waniwaniConfig.sessionId) {\n\t\t\twaniwaniConfig.sessionId = sessionId;\n\t\t}\n\t}\n\n\tconst geoLocation = extractGeoLocation(meta);\n\tif (geoLocation !== undefined) {\n\t\tif (!waniwaniConfig.geoLocation) {\n\t\t\twaniwaniConfig.geoLocation = geoLocation;\n\t\t}\n\t}\n\n\tconst source = extractSource(extractMeta(extra));\n\tif (source && !waniwaniConfig.source) {\n\t\twaniwaniConfig.source = source;\n\t}\n\n\tmeta.waniwani = waniwaniConfig;\n}\n\nexport function injectRequestMetadata(result: unknown, extra: unknown): void {\n\tconst requestMeta = extractMeta(extra);\n\tif (!requestMeta) {\n\t\treturn;\n\t}\n\n\tif (!isRecord(result)) {\n\t\treturn;\n\t}\n\n\tif (!isRecord(result._meta)) {\n\t\t(result as UnknownRecord)._meta = {};\n\t}\n\n\tconst resultMeta = (result as UnknownRecord)._meta as UnknownRecord;\n\tconst sessionId = extractSessionId(requestMeta);\n\tif (sessionId && !resultMeta[SESSION_ID_KEY]) {\n\t\tresultMeta[SESSION_ID_KEY] = sessionId;\n\t}\n\n\tconst geoLocation = extractGeoLocation(requestMeta);\n\tif (!geoLocation) {\n\t\treturn;\n\t}\n\n\tif (!resultMeta[GEO_LOCATION_KEY]) {\n\t\tresultMeta[GEO_LOCATION_KEY] = geoLocation;\n\t}\n\n\tif (!resultMeta[LEGACY_USER_LOCATION_KEY]) {\n\t\tresultMeta[LEGACY_USER_LOCATION_KEY] = geoLocation;\n\t}\n}\n\nfunction extractGeoLocation(\n\tmeta: UnknownRecord | undefined,\n): UnknownRecord | string | undefined {\n\tif (!meta) {\n\t\treturn undefined;\n\t}\n\n\tconst geoLocation = meta[GEO_LOCATION_KEY] ?? meta[LEGACY_USER_LOCATION_KEY];\n\tif (isRecord(geoLocation) || typeof geoLocation === \"string\") {\n\t\treturn geoLocation;\n\t}\n\n\treturn undefined;\n}\n\nfunction toError(error: unknown): Error {\n\tif (error instanceof Error) {\n\t\treturn error;\n\t}\n\treturn new Error(String(error));\n}\n","import type { ToolCalledProperties } from \"../../../tracking/index.js\";\nimport { waniwani } from \"../../../waniwani.js\";\nimport { createScopedClient, SCOPED_CLIENT_KEY } from \"../scoped-client.js\";\nimport type { McpServer } from \"../tools/types\";\nimport { WidgetTokenCache } from \"../widget-token.js\";\nimport {\n\tbuildTrackInput,\n\textractErrorText,\n\textractMeta,\n\tinjectRequestMetadata,\n\tinjectWidgetConfig,\n\tisRecord,\n\tsafeFlush,\n\tsafeTrack,\n\ttype WaniwaniTracker,\n} from \"./helpers.js\";\n\ntype UnknownRecord = Record<string, unknown>;\n\ntype WrappedServer = McpServer & {\n\t__waniwaniWrapped?: true;\n};\n\n/**\n * Options for withWaniwani().\n */\nexport type WithWaniwaniOptions = {\n\t/**\n\t * The WaniWani client instance. When omitted, a client is created\n\t * automatically using the global config registered by `defineConfig()`,\n\t * falling back to env vars.\n\t */\n\tclient?: WaniwaniTracker;\n\t/**\n\t * Optional explicit tool type. Defaults to `\"other\"`.\n\t */\n\ttoolType?:\n\t\t| ToolCalledProperties[\"type\"]\n\t\t| ((toolName: string) => ToolCalledProperties[\"type\"] | undefined);\n\t/**\n\t * Optional metadata merged into every tracked event.\n\t */\n\tmetadata?: UnknownRecord;\n\t/**\n\t * Flush tracking transport after each tool call.\n\t */\n\tflushAfterToolCall?: boolean;\n\t/**\n\t * Optional error callback for non-fatal tracking errors.\n\t */\n\tonError?: (error: Error) => void;\n\t/**\n\t * Inject widget tracking config into tool response `_meta.waniwani` so browser\n\t * widgets can send events directly to the WaniWani backend.\n\t *\n\t * Always injects `endpoint`. Injects `token` when an API key is configured\n\t * and token minting succeeds.\n\t *\n\t * @default true\n\t */\n\tinjectWidgetToken?: boolean;\n};\n\nconst DEFAULT_BASE_URL = \"https://app.waniwani.ai\";\n\n/**\n * Wrap an MCP server so tool handlers automatically emit `tool.called` events.\n *\n * The wrapper intercepts `server.registerTool(...)`, tracks each invocation,\n * then forwards execution to the original tool handler.\n *\n * When `injectWidgetToken` is enabled (default), tracking config is injected\n * into tool response `_meta.waniwani` so browser widgets can post events\n * directly to the WaniWani backend without a server-side proxy.\n */\nexport function withWaniwani(\n\tserver: McpServer,\n\toptions?: WithWaniwaniOptions,\n): McpServer {\n\tconst wrappedServer = server as WrappedServer;\n\tif (wrappedServer.__waniwaniWrapped) {\n\t\treturn wrappedServer;\n\t}\n\n\twrappedServer.__waniwaniWrapped = true;\n\n\tconst opts = options ?? {};\n\tconst tracker = opts.client ?? waniwani();\n\tconst injectToken = opts.injectWidgetToken !== false;\n\n\tconst tokenCache: WidgetTokenCache | null = tracker._config.apiKey\n\t\t? new WidgetTokenCache({\n\t\t\t\tapiUrl: tracker._config.apiUrl ?? DEFAULT_BASE_URL,\n\t\t\t\tapiKey: tracker._config.apiKey,\n\t\t\t})\n\t\t: null;\n\n\tconst originalRegisterTool = server.registerTool.bind(server) as (\n\t\t...args: unknown[]\n\t) => unknown;\n\n\twrappedServer.registerTool = ((...args: unknown[]) => {\n\t\tconst [toolNameRaw, config, handlerRaw] = args;\n\t\tconst toolName =\n\t\t\ttypeof toolNameRaw === \"string\" && toolNameRaw.trim().length > 0\n\t\t\t\t? toolNameRaw\n\t\t\t\t: \"unknown\";\n\n\t\tif (typeof handlerRaw !== \"function\") {\n\t\t\treturn originalRegisterTool(...args);\n\t\t}\n\n\t\tconst handler = handlerRaw as (\n\t\t\tinput: unknown,\n\t\t\textra: unknown,\n\t\t) => Promise<unknown> | unknown;\n\n\t\tconst wrappedHandler = async (input: unknown, extra: unknown) => {\n\t\t\t// Inject scoped client into extra so createTool/flows can surface it\n\t\t\tconst meta = extractMeta(extra) ?? {};\n\t\t\tconst scopedClient = createScopedClient(tracker, meta, {\n\t\t\t\tapiUrl: tracker._config.apiUrl,\n\t\t\t\tapiKey: tracker._config.apiKey,\n\t\t\t});\n\t\t\tif (isRecord(extra)) {\n\t\t\t\textra[SCOPED_CLIENT_KEY] = scopedClient;\n\t\t\t}\n\n\t\t\tconst startTime = performance.now();\n\t\t\tconst clientInfo = (\n\t\t\t\tserver as {\n\t\t\t\t\tserver?: {\n\t\t\t\t\t\tgetClientVersion?: () =>\n\t\t\t\t\t\t\t| { name: string; version: string }\n\t\t\t\t\t\t\t| undefined;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t).server?.getClientVersion?.();\n\t\t\ttry {\n\t\t\t\tconst result = await handler(input, extra);\n\t\t\t\tconst durationMs = Math.round(performance.now() - startTime);\n\n\t\t\t\tconst isErrorResult =\n\t\t\t\t\tisRecord(result) && (result as UnknownRecord).isError === true;\n\n\t\t\t\tif (isErrorResult) {\n\t\t\t\t\tconst errorText = extractErrorText(result);\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t`[waniwani] Tool \"${toolName}\" returned error${errorText ? `: ${errorText}` : \"\"}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tawait safeTrack(\n\t\t\t\t\ttracker,\n\t\t\t\t\tbuildTrackInput(\n\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\textra,\n\t\t\t\t\t\topts,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdurationMs,\n\t\t\t\t\t\t\tstatus: isErrorResult ? \"error\" : \"ok\",\n\t\t\t\t\t\t\t...(isErrorResult && {\n\t\t\t\t\t\t\t\terrorMessage: extractErrorText(result) ?? \"Unknown tool error\",\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclientInfo,\n\t\t\t\t\t\t{ input, output: result },\n\t\t\t\t\t),\n\t\t\t\t\topts.onError,\n\t\t\t\t);\n\n\t\t\t\tif (opts.flushAfterToolCall) {\n\t\t\t\t\tawait safeFlush(tracker, opts.onError);\n\t\t\t\t}\n\n\t\t\t\tinjectRequestMetadata(result, extra);\n\n\t\t\t\tif (injectToken) {\n\t\t\t\t\tawait injectWidgetConfig(\n\t\t\t\t\t\tresult,\n\t\t\t\t\t\ttokenCache,\n\t\t\t\t\t\ttracker._config.apiUrl ?? DEFAULT_BASE_URL,\n\t\t\t\t\t\textra,\n\t\t\t\t\t\topts.onError,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t} catch (error) {\n\t\t\t\tconst durationMs = Math.round(performance.now() - startTime);\n\n\t\t\t\tawait safeTrack(\n\t\t\t\t\ttracker,\n\t\t\t\t\tbuildTrackInput(\n\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\textra,\n\t\t\t\t\t\topts,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdurationMs,\n\t\t\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclientInfo,\n\t\t\t\t\t\t{ input },\n\t\t\t\t\t),\n\t\t\t\t\topts.onError,\n\t\t\t\t);\n\n\t\t\t\tif (opts.flushAfterToolCall) {\n\t\t\t\t\tawait safeFlush(tracker, opts.onError);\n\t\t\t\t}\n\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t};\n\n\t\treturn originalRegisterTool(toolNameRaw, config, wrappedHandler);\n\t}) as McpServer[\"registerTool\"];\n\n\treturn wrappedServer;\n}\n"],"mappings":"AAWO,SAASA,GAAiC,CAChD,OAAI,OAAO,OAAW,KAAe,WAAY,OACzC,SAED,UACR,CAKO,SAASC,IAAoB,CACnC,OAAOD,EAAe,IAAM,QAC7B,CAKO,SAASE,IAAqB,CACpC,OAAOF,EAAe,IAAM,UAC7B,CClBO,IAAMG,EAAQ,YACRC,EAAM,UAMbC,GAAY,OAAO,IAAI,yBAAyB,EAChDC,GAAS,OAAO,IAAI,sBAAsB,EAyDzC,SAASC,GACfC,EACAC,EACkB,CAClB,IAAMC,EAAUD,GAAQ,QAClBE,EAAiC,CAAC,EAExC,OAAW,CAACC,EAAKC,CAAK,IAAK,OAAO,QAAQL,CAAM,EAC/C,GAAI,OAAOK,GAAU,UAAYA,IAAU,MAAQ,aAAcA,EAAO,CACvE,IAAMC,EAAID,EASVF,EAAU,KAAK,CACd,SAAUG,EAAE,SACZ,MAAOF,EACP,YAAaE,EAAE,YACf,QAASA,EAAE,QACX,SAAUA,EAAE,QACb,CAAC,CACF,CAGD,MAAO,CACN,OAAQT,GACR,UAAAM,EACA,QAAAD,CACD,CACD,CAMO,SAASK,GACfC,EACAP,EAMe,CACf,MAAO,CAAE,OAAQH,GAAQ,KAAAU,EAA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7B,EAASD,EAAK,OAAO,EAGhCiC,CACP,CACD,CAE+D,CAChE,GAEOlC,CACR","names":["detectPlatform","isOpenAI","isMCPApps","START","END","INTERRUPT","WIDGET","interrupt","fields","config","context","questions","key","value","q","showWidget","tool","isInterrupt","isWidget","z","SCOPED_CLIENT_KEY","extractScopedClient","extra","createScopedClient","base","meta","config","event","userId","properties","pickFirst","meta","keys","key","value","SESSION_ID_KEYS","REQUEST_ID_KEYS","TRACE_ID_KEYS","EXTERNAL_USER_ID_KEYS","CORRELATION_ID_KEYS","extractSessionId","extractRequestId","extractTraceId","extractExternalUserId","extractCorrelationId","SOURCE_SESSION_KEYS","extractSource","explicit","source","getObjectShape","schema","def","getNestedValue","obj","path","parts","current","part","setNestedValue","value","lastKey","deleteNestedValue","expandDotPaths","flat","result","key","deepMerge","target","source","isFilled","v","resolveNextNode","edge","state","buildInterruptResult","questions","context","currentNode","q","getNestedValue","unanswered","isSingle","q0","executeFrom","startNodeName","startState","nodes","edges","validators","meta","waniwani","MAX_ITERATIONS","iterations","END","handler","result","interrupt","showWidget","isInterrupt","interruptResult","fn","value","vResult","deepMerge","err","msg","deleteNestedValue","questionsWithError","qq","errResult","isWidget","widgetField","error","SDK_NAME","DEFAULT_BASE_URL","WaniwaniKvStore","key","value","error","path","body","url","response","text","WaniwaniFlowStore","WaniwaniKvStore","key","value","describeZodField","schema","desc","def","vals","v","buildFlowProtocol","config","lines","parts","key","shape","getObjectShape","groupDesc","subFields","subKey","subSchema","info","inputSchema","z","compileFlow","input","config","nodes","edges","protocol","buildFlowProtocol","fullDescription","store","WaniwaniFlowStore","validators","handleToolCall","args","sessionId","meta","waniwani","intent","startEdge","START","startState","expandDotPaths","firstNode","resolveNextNode","executeFrom","flowState","err","msg","state","step","updatedState","deepMerge","edge","nextNode","server","extra","requestExtra","_meta","extractSessionId","extractScopedClient","result","buildMermaidGraph","nodes","edges","lines","START","name","END","from","edge","StateGraph","config","handler","to","condition","options","nodesCopy","edgesCopy","compileFlow","startEdge","createFlow","config","StateGraph","parsePayload","result","content","createFlowTestHarness","flow","options","store","registered","sessionId","server","args","handler","extra","toResult","parsed","intent","stateUpdates","MIME_TYPE_OPENAI","MIME_TYPE_MCP","fetchHtml","baseUrl","path","normalizedBase","buildOpenAIResourceMeta","config","buildMcpAppsResourceMeta","csp","buildToolMeta","createResource","config","id","title","description","baseUrl","htmlPath","widgetDomain","prefersBorder","autoHeight","widgetCSP","hostname","openaiUri","mcpUri","htmlPromise","getHtml","fetchHtml","uiDescription","register","server","html","MIME_TYPE_OPENAI","uri","buildOpenAIResourceMeta","MIME_TYPE_MCP","buildMcpAppsResourceMeta","createTool","config","handler","resource","description","inputSchema","annotations","autoInjectResultText","id","title","toolMeta","buildToolMeta","server","args","extra","requestExtra","_meta","waniwani","extractScopedClient","result","registerTools","tools","t","WaniWaniError","message","status","SDK_NAME","createKbClient","config","apiUrl","apiKey","requireApiKey","request","method","path","body","key","url","headers","init","response","text","WaniWaniError","files","query","options","DEFAULT_SOURCE","mapTrackEventToV2","input","options","now","generateId","createEventId","eventName","resolveEventName","meta","toRecord","metadata","correlation","resolveCorrelationIds","eventId","takeNonEmptyString","timestamp","normalizeTimestamp","source","extractSource","rawLegacy","isLegacyTrackEvent","mappedMetadata","mapProperties","legacyProperties","mapLegacyProperties","explicitProperties","properties","requestId","extractRequestId","sessionId","extractSessionId","traceId","extractTraceId","externalUserId","extractExternalUserId","correlationId","extractCorrelationId","date","value","DEFAULT_ENDPOINT_PATH","SDK_NAME","AUTH_FAILURE_STATUS","RETRYABLE_STATUS","createV2BatchTransport","options","BatchingV2Transport","joinUrl","DEFAULT_ENDPOINT_PATH","delayMs","resolve","event","dropCount","timeoutMs","flushPromise","timeoutSignal","batch","attempt","pendingBatch","result","events","response","error","getErrorMessage","data","parseJsonResponse","partial","rejected","byId","retryable","permanent","rejectedEvent","isRetryableRejectedEvent","rawDelay","status","rejectedCount","buffered","code","body","apiUrl","endpointPath","normalizedBase","normalizedPath","createTrackingClient","config","apiUrl","apiKey","tracking","requireApiKey","transport","createV2BatchTransport","client","userId","properties","meta","mappedEvent","mapTrackEventToV2","event","options","attachShutdownHooks","defaultTimeoutMs","shutdown","waniwani","config","effective","apiUrl","apiKey","trackingConfig","internalConfig","trackingClient","createTrackingClient","kbClient","createKbClient","mapWidgetEvent","ev","eventType","eventName","properties","createTrackingRoute","options","config","client","getClient","waniwani","request","body","c","results","trackInput","result","error","message","WidgetTokenCache","config","sessionId","traceId","url","joinUrl","body","response","json","result","expiresAtMs","apiUrl","path","SESSION_ID_KEY","GEO_LOCATION_KEY","LEGACY_USER_LOCATION_KEY","isRecord","value","extractMeta","extra","meta","extractErrorText","result","content","c","resolveToolType","toolName","toolTypeOption","buildTrackInput","options","timing","clientInfo","io","toolType","extractSource","safeTrack","tracker","input","onError","error","toError","safeFlush","injectWidgetConfig","cache","apiUrl","existingWaniwaniConfig","waniwaniConfig","token","sessionId","extractSessionId","geoLocation","extractGeoLocation","source","injectRequestMetadata","requestMeta","resultMeta","DEFAULT_BASE_URL","withWaniwani","server","options","wrappedServer","opts","tracker","waniwani","injectToken","tokenCache","WidgetTokenCache","originalRegisterTool","args","toolNameRaw","config","handlerRaw","toolName","handler","input","extra","meta","extractMeta","scopedClient","createScopedClient","isRecord","SCOPED_CLIENT_KEY","startTime","clientInfo","result","durationMs","isErrorResult","errorText","extractErrorText","safeTrack","buildTrackInput","safeFlush","injectRequestMetadata","injectWidgetConfig","error"]}