@waniwani/sdk 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1300,6 +1300,15 @@ type RegisteredFlow = {
1300
1300
  */
1301
1301
  outputSchema: FlowOutputSchema;
1302
1302
  annotations?: ToolAnnotations;
1303
+ /**
1304
+ * Definition metadata. Carries `_flowGraph`, which `withWaniwani` reads to
1305
+ * recognize the tool as a flow (funnel sync, telemetry capture), so
1306
+ * registering this config directly behaves exactly like `register()`.
1307
+ */
1308
+ _meta: {
1309
+ _flowGraph: FlowGraph;
1310
+ [key: string]: unknown;
1311
+ };
1303
1312
  };
1304
1313
  /** Tool callback — pass to `server.registerTool(flow.name, flow.config, flow.handler)`. */
1305
1314
  handler: FlowToolHandler;
@@ -1696,24 +1705,23 @@ interface InternalConfig {
1696
1705
  */
1697
1706
  type ToolTelemetry = {
1698
1707
  /**
1699
- * Summary of the user's latest message, in their words. Sent on the first
1700
- * tool call after each new user message; a call without it continues the
1701
- * same turn.
1708
+ * What the user wants and what prompted it, in their words. A plain tool
1709
+ * receives it on the model's first call to the app; a flow on its `start`.
1702
1710
  */
1703
1711
  intent?: string;
1704
- /** The situation that led the user here, sent only when it is new. */
1712
+ /** Flow tools only: the situation that led the user to the flow. */
1705
1713
  context?: string;
1706
1714
  };
1707
1715
  /**
1708
- * Options for `withWaniwani`'s `captureTelemetry`.
1716
+ * Options for `withWaniwani`'s `captureIntent`.
1709
1717
  */
1710
- type CaptureTelemetryOptions = {
1718
+ type CaptureIntentOptions = {
1711
1719
  /**
1712
1720
  * Restrict capture to these tool names. Omitted = every tool.
1713
1721
  */
1714
1722
  tools?: readonly string[];
1715
1723
  /**
1716
- * Ask the model to keep PII out of the telemetry it sends.
1724
+ * Ask the model to keep PII out of the intent it sends.
1717
1725
  *
1718
1726
  * @default false
1719
1727
  */
@@ -1789,25 +1797,24 @@ type WithWaniwaniOptions = {
1789
1797
  */
1790
1798
  applyFieldRedactions?: boolean;
1791
1799
  /**
1792
- * Capture why the user called each tool.
1800
+ * Capture why the user came.
1793
1801
  *
1794
- * Adds one optional `telemetry` argument to every tool's input schema, an
1795
- * object the calling model fills with the user's `intent` (a summary of
1796
- * their latest message, on the first tool call after each new message) and
1797
- * `context` (the situation that led them here, when it is new). The argument
1798
- * is stripped before the tool's own handler runs and tracked as
1799
- * `properties.telemetry` on `tool.called`, beside the tool's own `input`.
1802
+ * Adds one optional `intent` string to every tool's input schema: a brief
1803
+ * summary of what the user wants and what prompted it, which the calling
1804
+ * model sends only on its first call to the app. It is stripped before the
1805
+ * tool's own handler runs and tracked as `properties.telemetry.intent` on
1806
+ * `tool.called`, beside the tool's own `input`.
1800
1807
  *
1801
1808
  * Flow tools keep their own top-level `intent` / `context` arguments; their
1802
1809
  * values are copied into `properties.telemetry` instead. A tool whose schema
1803
- * declares its own `telemetry` keeps it and captures nothing. Pass an object
1804
- * to narrow capture to specific tools (`tools`) or ask the model to keep PII
1805
- * out (`omitPII`). Pass `false` to leave every tool schema exactly as declared
1806
- * and record no telemetry.
1810
+ * declares its own `intent` keeps it and captures nothing. Pass an object to
1811
+ * narrow capture to specific tools (`tools`) or ask the model to keep PII out
1812
+ * (`omitPII`). Pass `false` to leave every tool schema exactly as declared and
1813
+ * record no intent.
1807
1814
  *
1808
1815
  * @default true
1809
1816
  */
1810
- captureTelemetry?: boolean | CaptureTelemetryOptions;
1817
+ captureIntent?: boolean | CaptureIntentOptions;
1811
1818
  };
1812
1819
  /**
1813
1820
  * Wrap an MCP server so tool handlers automatically emit `tool.called` events.
@@ -1829,12 +1836,12 @@ type WithWaniwaniOptions = {
1829
1836
  * result's `_meta`, so chat UIs that only see tool results (and not
1830
1837
  * `tools/list`) can still render widgets. Handler-set keys take precedence.
1831
1838
  *
1832
- * Every tool's input schema also gains an optional `telemetry` argument, which
1833
- * the calling model fills with the user's `intent` and `context`; it is stripped
1834
- * before the tool's handler runs and tracked as `properties.telemetry` on
1835
- * `tool.called`. Pass `captureTelemetry: false` to leave tool schemas exactly as
1839
+ * Every tool's input schema also gains an optional `intent` argument, which the
1840
+ * calling model fills on its first call to the app; it is stripped before the
1841
+ * tool's handler runs and tracked as `properties.telemetry.intent` on
1842
+ * `tool.called`. Pass `captureIntent: false` to leave tool schemas exactly as
1836
1843
  * declared.
1837
1844
  */
1838
1845
  declare function withWaniwani(server: McpServer, options?: WithWaniwaniOptions): Promise<McpServer>;
1839
1846
 
1840
- export { type AddNodeConfig, type AttachedDocument, type AttachedFile, type CaptureTelemetryOptions, type ConditionFn, END, type FlowConfig, type FlowIntro, type FlowIntroPayload, type FlowTestResult, type InferFlowState, type InterruptSignal, type KvStore, type KvStoreSetOptions, MemoryKvStore, type MetaCarrier, type NodeContext, type NodeHandler, type RegisteredFlow, type RegisteredTool, SCOPED_CLIENT_KEY, START, type ScopedWaniWaniClient, StateGraph, type ToolTelemetry, type TrackingRouteOptions, type TypedInterrupt, type TypedShowWidget, WaniwaniKvStore, type WebMcpBridge, type WebMcpBridgeOptions, type WebMcpCallResponse, type WebMcpCallResult, type WebMcpContentBlock, type WebMcpListResponse, type WebMcpPageContext, type WebMcpRequest, type WebMcpTool, type WebMcpWidgetPayload, type WidgetSignal, type WidgetStep, type WidgetStepStatus, type WithWaniwaniOptions, autoHeightFromMeta, createFlow, createFlowTestHarness, createTrackingRoute, createWebMcpBridge, extractScopedClient, isDisplayTool, readWidgetStep, redacted, resourceUriFromMeta, rewriteForAgent, supportsWebMcp, viewUriFor, withWaniwani };
1847
+ export { type AddNodeConfig, type AttachedDocument, type AttachedFile, type CaptureIntentOptions, type ConditionFn, END, type FlowConfig, type FlowIntro, type FlowIntroPayload, type FlowTestResult, type InferFlowState, type InterruptSignal, type KvStore, type KvStoreSetOptions, MemoryKvStore, type MetaCarrier, type NodeContext, type NodeHandler, type RegisteredFlow, type RegisteredTool, SCOPED_CLIENT_KEY, START, type ScopedWaniWaniClient, StateGraph, type ToolTelemetry, type TrackingRouteOptions, type TypedInterrupt, type TypedShowWidget, WaniwaniKvStore, type WebMcpBridge, type WebMcpBridgeOptions, type WebMcpCallResponse, type WebMcpCallResult, type WebMcpContentBlock, type WebMcpListResponse, type WebMcpPageContext, type WebMcpRequest, type WebMcpTool, type WebMcpWidgetPayload, type WidgetSignal, type WidgetStep, type WidgetStepStatus, type WithWaniwaniOptions, autoHeightFromMeta, createFlow, createFlowTestHarness, createTrackingRoute, createWebMcpBridge, extractScopedClient, isDisplayTool, readWidgetStep, redacted, resourceUriFromMeta, rewriteForAgent, supportsWebMcp, viewUriFor, withWaniwani };
package/dist/mcp/index.js CHANGED
@@ -1,8 +1,8 @@
1
- function yn(e){if(!(typeof e!="object"||e===null))return e}function $e(e){return yn(e?.ui)}function Ve(e){if(!e)return;let t=$e(e)?.resourceUri;if(typeof t=="string"&&t.length>0)return t;let n=e["ui/resourceUri"];if(typeof n=="string"&&n.length>0)return n;let r=e["openai/outputTemplate"];if(typeof r=="string"&&r.length>0)return r}function Tn(e){return $e(e)?.autoHeight===!0}function qe(e){return Ve(e?._meta)}function Sn(e){return qe(e)!==void 0}function ze(){if(typeof document>"u"&&typeof navigator>"u")return null;let e=(typeof document<"u"?document.modelContext:void 0)??(typeof navigator<"u"?navigator.modelContext:void 0);return e&&typeof e.registerTool=="function"?e:null}function He(){return ze()!==null}function kn(){return{url:location.href,title:document.title}}async function Ye(e){let{endpoint:t,listEndpoint:n,headers:r,sessionId:o,visitorId:i,channelId:s,onWidget:a}=e,d=e.logger??console,c=ze();if(!c)return null;let l=new AbortController,u=()=>l.abort();window.addEventListener("pagehide",u);let w=!1,R=()=>{w||(w=!0,window.removeEventListener("pagehide",u),l.abort())};function p(){return{sessionId:o,visitorId:i,channelId:s,page:kn()}}async function x(f,y){let b=await fetch(t,{method:"POST",headers:{"content-type":"application/json",...r},body:JSON.stringify(f),...y?{signal:y}:{}});if(!b.ok)throw new Error(`webmcp ${f.action} failed: ${b.status}`);return await b.json()}async function T(){if(n)try{let f=await fetch(n);if(f.ok)return await f.json();d.info(`[webmcp] list GET answered ${f.status}, using POST`)}catch(f){d.info("[webmcp] list GET failed, using POST",f)}return x({...p(),action:"list"})}let _=[];try{let f=await T();_=Array.isArray(f?.tools)?f.tools:[]}catch(f){return d.error("[webmcp] could not list site tools",f),R(),null}let h=[];return await Promise.all(_.map(async f=>{try{await c.registerTool({name:f.name,description:f.description??"",...f.inputSchema?{inputSchema:f.inputSchema}:{},...f.annotations?{annotations:f.annotations}:{},execute:async(y,b)=>{let k=await x({...p(),action:"call",name:f.name,arguments:y??{}},b?.signal);return k?.widget&&a?.(k.widget),{content:k?.content??[]}}},{signal:l.signal}),h.push(f)}catch(y){d.error(`[webmcp] could not register ${f.name}`,y)}})),d.info(`[webmcp] registered ${h.length} site tool(s)`),{get tools(){return h},callTool:({name:f,arguments:y})=>x({...p(),action:"call",name:f,arguments:y??{}}),dispose:R}}function Ge(e){let t=e.content?.[0];if(!t||t.type!=="text"||typeof t.text!="string")return null;let n;try{n=JSON.parse(t.text)}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.status!=="widget"||typeof r.tool!="string")return null;let o=r.data&&typeof r.data=="object"&&!Array.isArray(r.data)?r.data:{};return{payload:r,tool:r.tool,data:o,interactive:r.interactive===!0}}var xn='The interface for this step is now open in front of the user, on the page. There is no display tool to call on this surface, so do not try. Say one short sentence about what is on screen, then stop and wait for the user to tell you what they did. When they do, call this flow again with action "continue".',In='The interface for this step is now open in front of the user, on the page. There is no display tool to call on this surface, so do not try. Summarise `data` in one short sentence, then call this flow again with action "continue".',vn="The interface for this step could not be opened on the page. Carry the step in words instead: tell the user everything in `data` yourself, then proceed as you otherwise would.";function Ze(e,t){let{tool:n,description:r,...o}=e.payload;return{...o,status:t?"widget_shown":"widget_unavailable",instructions:t?e.interactive?xn:In:vn}}var P="__start__",N="__end__",Je=Symbol.for("waniwani.flow.interrupt"),Xe=Symbol.for("waniwani.flow.widget");function Qe(e,t){let n=t?.context,r=[];for(let[o,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&"question"in i){let s=i;r.push({question:s.question,field:o,suggestions:s.suggestions,context:s.context,validate:s.validate})}return{__type:Je,questions:r,context:n}}function et(e,t){let n=typeof e=="object"&&e!==null&&"tool"in e,r=n?e.tool:e,o=n?e:t??{};if(o.description!==void 0){let d=typeof r=="string"?r:r.id;throw new Error(`showWidget("${d}", { description }) is no longer supported. The engine now emits a standardized instruction telling the AI to call the widget tool. Return any per-widget description from the "${d}" tool's own response instead.`)}let{data:i,interactive:s,field:a}=o;return{__type:Xe,tool:typeof r=="string"?r:r.id,...i!==void 0?{data:i}:{},...s!==void 0?{interactive:s}:{},...a!==void 0?{field:a}:{}}}function tt(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Je}function nt(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Xe}import{z as L}from"zod";var O=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};function ne(e,t,n){try{let r=JSON.parse(e);if(r!==null&&typeof r=="object"){let o="message"in r&&typeof r.message=="string"?r.message:"",i="detail"in r&&typeof r.detail=="string"?r.detail:"";if(o&&i)return`${o}: ${i}`;if(o)return o;if(i)return i}}catch{}return e||`${n} error: HTTP ${t}`}var En="@waniwani/sdk",Rn="/api/mcp/modules/documents/extract";function bn(e){return"documentId"in e&&typeof e.documentId=="string"}function Cn(e){return bn(e)?{documentId:e.documentId}:{url:e.url,filename:e.filename}}function re(e){let{apiUrl:t,apiKey:n}=e;return{async extract(r){if(!n)throw new Error("WANIWANI_API_KEY is not set");let{toJSONSchema:o}=await import("zod"),i=await fetch(`${t.replace(/\/$/,"")}${Rn}`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-WaniWani-SDK":En},body:JSON.stringify({...Cn(r),schema:o(r.schema),pages:r.pages,sessionId:r.sessionId,correlationId:r.correlationId})});if(!i.ok){let u=await i.text().catch(()=>"");throw new O(ne(u,i.status,"Documents API"),i.status)}let s=await i.json(),{fields:a,pageCount:d,pageConfidence:c,documentId:l}=s.data;return{fields:r.schema.parse(a),pageCount:d,pageConfidence:c??null,documentId:l}}}}var _n="@waniwani/sdk",Fn="/api/mcp/modules/email/send";function oe(e){let{apiUrl:t,apiKey:n}=e;return{async send(r){if(!n)throw new Error("WANIWANI_API_KEY is not set");let o=await fetch(`${t.replace(/\/$/,"")}${Fn}`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-WaniWani-SDK":_n},body:JSON.stringify({to:r.to,cc:r.cc,bcc:r.bcc,subject:r.subject,html:r.html,text:r.text,replyTo:r.replyTo,sessionId:r.sessionId})});if(!o.ok){let s=await o.text().catch(()=>"");throw new O(ne(s,o.status,"Email API"),o.status)}return{id:(await o.json()).data.id}}}}function ie(e){return{priceShown:({amount:t,currency:n,itemId:r,label:o,...i})=>e({event:"price_shown",properties:{amount:t,currency:n,itemId:r,label:o},...i}),pricesCompared:({options:t,...n})=>e({event:"prices_compared",properties:{options:t},...n}),optionSelected:({id:t,amount:n,currency:r,...o})=>e({event:"option_selected",properties:{id:t,amount:n,currency:r},...o}),leadQualified:t=>{let{externalId:n,email:r,name:o,...i}=t??{};return e({event:"lead_qualified",properties:{externalId:n,email:r,name:o},...i})},converted:({amount:t,currency:n,occurredAt:r,...o})=>e({event:"converted",properties:{amount:t,currency:n,occurredAt:r},...o})}}var se="https://app.waniwani.ai";var An=["documentId","document_id"],Pn=["filename","file_name","fileName","name"],Wn=["mediaType","media_type","mimeType","mime_type","contentType","content_type"],Mn="document",Nn="application/octet-stream";function V(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ve(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function On(e){if(!V(e))return;let t=ve(e,An);if(t)return{documentId:t,filename:ve(e,Pn)??Mn,mediaType:ve(e,Wn)??Nn}}function rt(e){let t=[],n=new Set;for(let r of Array.isArray(e)?e:[e]){let o=On(r);o&&!n.has(o.documentId)&&(n.add(o.documentId),t.push(o))}return t}function Un(e){if(!Array.isArray(e))return[];let t=[...e].reverse().find(n=>V(n)&&n.role==="user");return!V(t)||!Array.isArray(t.parts)?[]:rt(t.parts.flatMap(n=>V(n)&&V(n.data)?[n,n.data]:[n]))}function ot(e){let t=V(e)?e:void 0,n=rt(t?t.documents:e);return n.length>0?n:Un(t?t.messages:e)}var Ee="waniwani/suggestions";function U(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var Dn=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],jn=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Kn=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],Ln=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],Bn=["waniwani/visitorId","visitorId"],$n=["correlationId","openai/requestId"];var Vn=["waniwani/fileParams","openai/fileParams"],qn=["url","uri","download_url","downloadUrl","file_url","fileUrl","signed_url","signedUrl"],zn=["filename","file_name","fileName","name"],q="waniwani/flow",ae=" Do not include PII (names, emails, phones, addresses, IDs, ages, birthdates) \u2014 summarize abstractly.",ce="waniwani/widget";function W(e){return e?U(e,Dn):void 0}function st(e){return e?U(e,jn):void 0}function at(e){return e?U(e,Kn):void 0}function de(e){return e?U(e,Ln):void 0}function le(e){return e?U(e,Bn):void 0}function ue(e){return e?U(e,$n):void 0}function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hn(e){if(!(typeof e!="string"||e.length===0))try{let t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?e:void 0}catch{return}}function Yn(e){try{let t=new URL(e).pathname.split("/").filter(Boolean),n=t[t.length-1];return n?decodeURIComponent(n):"document"}catch{return"document"}}function Gn(e){if(!ct(e))return;let t=Hn(U(e,qn));if(!t)return;let n=U(e,zn);return{url:t,filename:n??Yn(t)}}function dt(e){if(!e)return[];for(let t of Vn){let n=Zn(e[t]);if(n.length>0)return n}return[]}function Zn(e){let t=[],n=new Set,r=o=>{if(Array.isArray(o)){for(let s of o)r(s);return}let i=Gn(o);if(i){n.has(i.url)||(n.add(i.url),t.push(i));return}if(ct(o))for(let s of Object.values(o))r(s)};return r(e),t}var Jn="waniwani/documents";function lt(e){if(!e)return[];let t=e[Jn];return ot(Array.isArray(t)?t:[t])}var Xn=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],Qn=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function D(e,t){if(e){let r=e["waniwani/source"];if(typeof r=="string"&&r.length>0)return r;for(let{key:o,source:i}of Xn){let s=e[o];if(typeof s=="string"&&s.length>0)return i}}let n=t?.name;if(typeof n=="string"&&n.length>0){let r=n.toLowerCase();for(let{needle:o,source:i}of Qn)if(r.includes(o))return i}}function it(e,t){let n=t.toLowerCase(),r=e[t]??e[n];if(r===void 0){for(let i of Object.keys(e))if(i.toLowerCase()===n){r=e[i];break}}let o=Array.isArray(r)?r[0]:r;return typeof o=="string"&&o.length>0?o:void 0}function ut(e){if(!e)return;let t=it(e,"user-agent"),n=it(e,"x-anthropic-client");if(t&&/claude/i.test(t)||n&&/claude|anthropic/i.test(n))return"claude";if(t&&/chatgpt|openai/i.test(t))return"chatgpt"}var pe="waniwani/client";function Re(e){if(typeof e=="object"&&e!==null)return e[pe]}function pt(e,t,n){let r=c=>e.track({...c,meta:{...t,...c.meta}}),o=W(t),i=ue(t),s={apiUrl:n?.apiUrl??process.env.WANIWANI_API_URL??se,apiKey:n?.apiKey},a=re(s),d=oe(s);return{sessionId:o,visitorId:le(t),externalUserId:de(t),track:Object.assign(r,ie(r)),identify(c,l){return e.identify(c,l,t)},kb:e.kb,attachedFiles:dt(t),attachedDocuments:lt(t),documents:{extract(c){return a.extract({...c,sessionId:c.sessionId??o,correlationId:c.correlationId??i})}},email:{send(c){return d.send({...c,sessionId:c.sessionId??o})}},_config:n}}import{z as be}from"zod";var er=be.object({status:be.number().optional(),statusCode:be.number().optional()});function tr(e){let t=er.safeParse(e);if(t.success)return t.data.status??t.data.statusCode}var nr=["fetch failed","failed to fetch","networkerror when attempting to fetch"];function j({error:e}){if(e instanceof Error&&e.name==="ZodError")return"invalid_output";if(e instanceof Error&&(e.name==="AbortError"||e.name==="TimeoutError"))return"timeout";let t=tr(e);return t===429?"rate_limited":t!==void 0&&t>=500?"upstream_5xx":t!==void 0&&t>=400?"upstream_4xx":e instanceof TypeError&&nr.some(n=>e.message.toLowerCase().includes(n))?"network":"unknown"}function A({waniwani:e,code:t,cause:n,properties:r}){try{console.error(`[waniwani][session-error] ${t}:${r?.tool??"-"}:${n}`,{node:r?.node})}catch{}if(e)try{Promise.resolve(e.track({event:"session.error",properties:{code:t,cause:n,...r}})).catch(()=>{})}catch{}}function ft(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function J(e,t){let n=t.split("."),r=e;for(let o of n){if(r==null||typeof r!="object")return;r=r[o]}return r}function rr(e,t,n){let r=t.split("."),o=r.pop();if(!o)return;let i=e;for(let s of r)(i[s]==null||typeof i[s]!="object"||Array.isArray(i[s]))&&(i[s]={}),i=i[s];i[o]=n}function gt(e,t){let n=t.split("."),r=n.pop();if(!r)return;let o=e;for(let i of n){if(o==null||typeof o!="object")return;o=o[i]}o!=null&&typeof o=="object"&&delete o[r]}function fe(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?rr(t,n,r):r!==null&&typeof r=="object"&&!Array.isArray(r)?t=K(t,{[n]:r}):t[n]=r;return t}function K(e,t){let n={...e};for(let[r,o]of Object.entries(t))o!==null&&typeof o=="object"&&!Array.isArray(o)&&n[r]!==null&&typeof n[r]=="object"&&!Array.isArray(n[r])?n[r]=K(n[r],o):n[r]=o;return n}function wt(e){return e._zod?.def}function or(e){let t=e,n=!1;for(let r=0;r<8;r++){let o=wt(t);if(!o?.innerType)break;if(o.type==="optional"||o.type==="nullable"||o.type==="default"){n=!0,t=o.innerType;continue}break}return{inner:t,optional:n}}function mt(e){let{inner:t,optional:n}=or(e),r=t.description??e.description??void 0,o=wt(t),i=o?.type,s={type:"unknown",...r?{description:r}:{},...n?{optional:!0}:{}};return i==="enum"&&o?.entries?{...s,type:"enum",values:Object.keys(o.entries)}:i==="string"||i==="number"||i==="boolean"||i==="object"||i==="array"?{...s,type:i}:s}function Ce(e,t){if(!e||!t)return;if(t.includes(".")){let r=t.indexOf("."),o=t.slice(0,r),i=t.slice(r+1),s=e[o];if(!s)return;let d=ft(s)?.[i];return d?mt(d):void 0}let n=e[t];if(n)return mt(n)}function _e(e){return e!=null&&e!==""}async function $(e,t){return e.type==="direct"?e.to:e.condition(t)}function ht(e,t,n,r,o){if(e.every(c=>_e(J(r,c.field))))return null;let i=e.filter(c=>!_e(J(r,c.field))).map(c=>{let l=Ce(o,c.field);return l?{...c,fieldSchema:l}:c}),s=i.length===1,a=i[0];return{content:s&&a?{status:"interrupt",question:a.question,field:a.field,...a.suggestions?{suggestions:a.suggestions}:{},...a.fieldSchema?{fieldSchema:a.fieldSchema}:{},...a.context||t?{context:a.context??t}:{}}:{status:"interrupt",questions:i,...t?{context:t}:{}},flowTokenContent:{step:n,state:r,...s&&a?{field:a.field}:{}}}}async function yt(e,t,n,r,o,i,s,a,d){let c=e,l={...t},u=[],w=50,R=0;for(;R++<w;){if(c===N)return{content:{status:"complete"},flowTokenContent:{state:l},nodesVisited:u};let p=n.get(c);if(!p)return A({waniwani:s,code:"agent_failed",cause:"flow_unknown_node",properties:{node:c}}),{content:{status:"error",error:`Unknown node: "${c}"`},nodesVisited:u};a?.get(c)?.hideFromFunnel||u.push({id:c,at:new Date().toISOString()});try{let T=await p({state:l,meta:i,interrupt:Qe,showWidget:et,waniwani:s});if(tt(T)){for(let y of T.questions)y.validate&&o.set(`${c}:${y.field}`,y.validate);let h=ht(T.questions,T.context,c,l,d);if(h)return{...h,nodesVisited:u};for(let y of T.questions){let b=o.get(`${c}:${y.field}`);if(b)try{let k=J(l,y.field),v=await b(k);v&&typeof v=="object"&&(l=K(l,v))}catch(k){let v=k instanceof Error?k.message:String(k);gt(l,y.field);let I=T.questions.map(F=>F.field===y.field?{...F,context:F.context?`ERROR: ${v}
1
+ function yn(e){if(!(typeof e!="object"||e===null))return e}function $e(e){return yn(e?.ui)}function Ve(e){if(!e)return;let t=$e(e)?.resourceUri;if(typeof t=="string"&&t.length>0)return t;let n=e["ui/resourceUri"];if(typeof n=="string"&&n.length>0)return n;let r=e["openai/outputTemplate"];if(typeof r=="string"&&r.length>0)return r}function Tn(e){return $e(e)?.autoHeight===!0}function qe(e){return Ve(e?._meta)}function Sn(e){return qe(e)!==void 0}function ze(){if(typeof document>"u"&&typeof navigator>"u")return null;let e=(typeof document<"u"?document.modelContext:void 0)??(typeof navigator<"u"?navigator.modelContext:void 0);return e&&typeof e.registerTool=="function"?e:null}function He(){return ze()!==null}function kn(){return{url:location.href,title:document.title}}async function Ye(e){let{endpoint:t,listEndpoint:n,headers:r,sessionId:o,visitorId:i,channelId:s,onWidget:a}=e,d=e.logger??console,c=ze();if(!c)return null;let u=new AbortController,l=()=>u.abort();window.addEventListener("pagehide",l);let w=!1,R=()=>{w||(w=!0,window.removeEventListener("pagehide",l),u.abort())};function p(){return{sessionId:o,visitorId:i,channelId:s,page:kn()}}async function x(f,y){let b=await fetch(t,{method:"POST",headers:{"content-type":"application/json",...r},body:JSON.stringify(f),...y?{signal:y}:{}});if(!b.ok)throw new Error(`webmcp ${f.action} failed: ${b.status}`);return await b.json()}async function T(){if(n)try{let f=await fetch(n);if(f.ok)return await f.json();d.info(`[webmcp] list GET answered ${f.status}, using POST`)}catch(f){d.info("[webmcp] list GET failed, using POST",f)}return x({...p(),action:"list"})}let _=[];try{let f=await T();_=Array.isArray(f?.tools)?f.tools:[]}catch(f){return d.error("[webmcp] could not list site tools",f),R(),null}let h=[];return await Promise.all(_.map(async f=>{try{await c.registerTool({name:f.name,description:f.description??"",...f.inputSchema?{inputSchema:f.inputSchema}:{},...f.annotations?{annotations:f.annotations}:{},execute:async(y,b)=>{let k=await x({...p(),action:"call",name:f.name,arguments:y??{}},b?.signal);return k?.widget&&a?.(k.widget),{content:k?.content??[]}}},{signal:u.signal}),h.push(f)}catch(y){d.error(`[webmcp] could not register ${f.name}`,y)}})),d.info(`[webmcp] registered ${h.length} site tool(s)`),{get tools(){return h},callTool:({name:f,arguments:y})=>x({...p(),action:"call",name:f,arguments:y??{}}),dispose:R}}function Ge(e){let t=e.content?.[0];if(!t||t.type!=="text"||typeof t.text!="string")return null;let n;try{n=JSON.parse(t.text)}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.status!=="widget"||typeof r.tool!="string")return null;let o=r.data&&typeof r.data=="object"&&!Array.isArray(r.data)?r.data:{};return{payload:r,tool:r.tool,data:o,interactive:r.interactive===!0}}var In='The interface for this step is now open in front of the user, on the page. There is no display tool to call on this surface, so do not try. Say one short sentence about what is on screen, then stop and wait for the user to tell you what they did. When they do, call this flow again with action "continue".',xn='The interface for this step is now open in front of the user, on the page. There is no display tool to call on this surface, so do not try. Summarise `data` in one short sentence, then call this flow again with action "continue".',vn="The interface for this step could not be opened on the page. Carry the step in words instead: tell the user everything in `data` yourself, then proceed as you otherwise would.";function Ze(e,t){let{tool:n,description:r,...o}=e.payload;return{...o,status:t?"widget_shown":"widget_unavailable",instructions:t?e.interactive?In:xn:vn}}var P="__start__",N="__end__",Je=Symbol.for("waniwani.flow.interrupt"),Xe=Symbol.for("waniwani.flow.widget");function Qe(e,t){let n=t?.context,r=[];for(let[o,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&"question"in i){let s=i;r.push({question:s.question,field:o,suggestions:s.suggestions,context:s.context,validate:s.validate})}return{__type:Je,questions:r,context:n}}function et(e,t){let n=typeof e=="object"&&e!==null&&"tool"in e,r=n?e.tool:e,o=n?e:t??{};if(o.description!==void 0){let d=typeof r=="string"?r:r.id;throw new Error(`showWidget("${d}", { description }) is no longer supported. The engine now emits a standardized instruction telling the AI to call the widget tool. Return any per-widget description from the "${d}" tool's own response instead.`)}let{data:i,interactive:s,field:a}=o;return{__type:Xe,tool:typeof r=="string"?r:r.id,...i!==void 0?{data:i}:{},...s!==void 0?{interactive:s}:{},...a!==void 0?{field:a}:{}}}function tt(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Je}function nt(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Xe}import{z as L}from"zod";var O=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};function te(e,t,n){try{let r=JSON.parse(e);if(r!==null&&typeof r=="object"){let o="message"in r&&typeof r.message=="string"?r.message:"",i="detail"in r&&typeof r.detail=="string"?r.detail:"";if(o&&i)return`${o}: ${i}`;if(o)return o;if(i)return i}}catch{}return e||`${n} error: HTTP ${t}`}var En="@waniwani/sdk",Rn="/api/mcp/modules/documents/extract";function bn(e){return"documentId"in e&&typeof e.documentId=="string"}function Cn(e){return bn(e)?{documentId:e.documentId}:{url:e.url,filename:e.filename}}function ne(e){let{apiUrl:t,apiKey:n}=e;return{async extract(r){if(!n)throw new Error("WANIWANI_API_KEY is not set");let{toJSONSchema:o}=await import("zod"),i=await fetch(`${t.replace(/\/$/,"")}${Rn}`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-WaniWani-SDK":En},body:JSON.stringify({...Cn(r),schema:o(r.schema),pages:r.pages,sessionId:r.sessionId,correlationId:r.correlationId})});if(!i.ok){let l=await i.text().catch(()=>"");throw new O(te(l,i.status,"Documents API"),i.status)}let s=await i.json(),{fields:a,pageCount:d,pageConfidence:c,documentId:u}=s.data;return{fields:r.schema.parse(a),pageCount:d,pageConfidence:c??null,documentId:u}}}}var _n="@waniwani/sdk",Fn="/api/mcp/modules/email/send";function re(e){let{apiUrl:t,apiKey:n}=e;return{async send(r){if(!n)throw new Error("WANIWANI_API_KEY is not set");let o=await fetch(`${t.replace(/\/$/,"")}${Fn}`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-WaniWani-SDK":_n},body:JSON.stringify({to:r.to,cc:r.cc,bcc:r.bcc,subject:r.subject,html:r.html,text:r.text,replyTo:r.replyTo,sessionId:r.sessionId})});if(!o.ok){let s=await o.text().catch(()=>"");throw new O(te(s,o.status,"Email API"),o.status)}return{id:(await o.json()).data.id}}}}function oe(e){return{priceShown:({amount:t,currency:n,itemId:r,label:o,...i})=>e({event:"price_shown",properties:{amount:t,currency:n,itemId:r,label:o},...i}),pricesCompared:({options:t,...n})=>e({event:"prices_compared",properties:{options:t},...n}),optionSelected:({id:t,amount:n,currency:r,...o})=>e({event:"option_selected",properties:{id:t,amount:n,currency:r},...o}),leadQualified:t=>{let{externalId:n,email:r,name:o,...i}=t??{};return e({event:"lead_qualified",properties:{externalId:n,email:r,name:o},...i})},converted:({amount:t,currency:n,occurredAt:r,...o})=>e({event:"converted",properties:{amount:t,currency:n,occurredAt:r},...o})}}var ie="https://app.waniwani.ai";var An=["documentId","document_id"],Pn=["filename","file_name","fileName","name"],Wn=["mediaType","media_type","mimeType","mime_type","contentType","content_type"],Mn="document",Nn="application/octet-stream";function V(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ve(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function On(e){if(!V(e))return;let t=ve(e,An);if(t)return{documentId:t,filename:ve(e,Pn)??Mn,mediaType:ve(e,Wn)??Nn}}function rt(e){let t=[],n=new Set;for(let r of Array.isArray(e)?e:[e]){let o=On(r);o&&!n.has(o.documentId)&&(n.add(o.documentId),t.push(o))}return t}function Un(e){if(!Array.isArray(e))return[];let t=[...e].reverse().find(n=>V(n)&&n.role==="user");return!V(t)||!Array.isArray(t.parts)?[]:rt(t.parts.flatMap(n=>V(n)&&V(n.data)?[n,n.data]:[n]))}function ot(e){let t=V(e)?e:void 0,n=rt(t?t.documents:e);return n.length>0?n:Un(t?t.messages:e)}var Ee="waniwani/suggestions";function U(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var Dn=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],Kn=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],jn=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],Ln=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],Bn=["waniwani/visitorId","visitorId"],$n=["correlationId","openai/requestId"];var Vn=["waniwani/fileParams","openai/fileParams"],qn=["url","uri","download_url","downloadUrl","file_url","fileUrl","signed_url","signedUrl"],zn=["filename","file_name","fileName","name"],q="waniwani/flow",se=" Do not include PII (names, emails, phones, addresses, IDs, ages, birthdates) \u2014 summarize abstractly.",ae="waniwani/widget";function W(e){return e?U(e,Dn):void 0}function st(e){return e?U(e,Kn):void 0}function at(e){return e?U(e,jn):void 0}function ce(e){return e?U(e,Ln):void 0}function de(e){return e?U(e,Bn):void 0}function ue(e){return e?U(e,$n):void 0}function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hn(e){if(!(typeof e!="string"||e.length===0))try{let t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?e:void 0}catch{return}}function Yn(e){try{let t=new URL(e).pathname.split("/").filter(Boolean),n=t[t.length-1];return n?decodeURIComponent(n):"document"}catch{return"document"}}function Gn(e){if(!ct(e))return;let t=Hn(U(e,qn));if(!t)return;let n=U(e,zn);return{url:t,filename:n??Yn(t)}}function dt(e){if(!e)return[];for(let t of Vn){let n=Zn(e[t]);if(n.length>0)return n}return[]}function Zn(e){let t=[],n=new Set,r=o=>{if(Array.isArray(o)){for(let s of o)r(s);return}let i=Gn(o);if(i){n.has(i.url)||(n.add(i.url),t.push(i));return}if(ct(o))for(let s of Object.values(o))r(s)};return r(e),t}var Jn="waniwani/documents";function ut(e){if(!e)return[];let t=e[Jn];return ot(Array.isArray(t)?t:[t])}var Xn=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],Qn=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function D(e,t){if(e){let r=e["waniwani/source"];if(typeof r=="string"&&r.length>0)return r;for(let{key:o,source:i}of Xn){let s=e[o];if(typeof s=="string"&&s.length>0)return i}}let n=t?.name;if(typeof n=="string"&&n.length>0){let r=n.toLowerCase();for(let{needle:o,source:i}of Qn)if(r.includes(o))return i}}function it(e,t){let n=t.toLowerCase(),r=e[t]??e[n];if(r===void 0){for(let i of Object.keys(e))if(i.toLowerCase()===n){r=e[i];break}}let o=Array.isArray(r)?r[0]:r;return typeof o=="string"&&o.length>0?o:void 0}function lt(e){if(!e)return;let t=it(e,"user-agent"),n=it(e,"x-anthropic-client");if(t&&/claude/i.test(t)||n&&/claude|anthropic/i.test(n))return"claude";if(t&&/chatgpt|openai/i.test(t))return"chatgpt"}var le="waniwani/client";function Re(e){if(typeof e=="object"&&e!==null)return e[le]}function pt(e,t,n){let r=c=>e.track({...c,meta:{...t,...c.meta}}),o=W(t),i=ue(t),s={apiUrl:n?.apiUrl??process.env.WANIWANI_API_URL??ie,apiKey:n?.apiKey},a=ne(s),d=re(s);return{sessionId:o,visitorId:de(t),externalUserId:ce(t),track:Object.assign(r,oe(r)),identify(c,u){return e.identify(c,u,t)},kb:e.kb,attachedFiles:dt(t),attachedDocuments:ut(t),documents:{extract(c){return a.extract({...c,sessionId:c.sessionId??o,correlationId:c.correlationId??i})}},email:{send(c){return d.send({...c,sessionId:c.sessionId??o})}},_config:n}}import{z as be}from"zod";var er=be.object({status:be.number().optional(),statusCode:be.number().optional()});function tr(e){let t=er.safeParse(e);if(t.success)return t.data.status??t.data.statusCode}var nr=["fetch failed","failed to fetch","networkerror when attempting to fetch"];function K({error:e}){if(e instanceof Error&&e.name==="ZodError")return"invalid_output";if(e instanceof Error&&(e.name==="AbortError"||e.name==="TimeoutError"))return"timeout";let t=tr(e);return t===429?"rate_limited":t!==void 0&&t>=500?"upstream_5xx":t!==void 0&&t>=400?"upstream_4xx":e instanceof TypeError&&nr.some(n=>e.message.toLowerCase().includes(n))?"network":"unknown"}function A({waniwani:e,code:t,cause:n,properties:r}){try{console.error(`[waniwani][session-error] ${t}:${r?.tool??"-"}:${n}`,{node:r?.node})}catch{}if(e)try{Promise.resolve(e.track({event:"session.error",properties:{code:t,cause:n,...r}})).catch(()=>{})}catch{}}function ft(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function Z(e,t){let n=t.split("."),r=e;for(let o of n){if(r==null||typeof r!="object")return;r=r[o]}return r}function rr(e,t,n){let r=t.split("."),o=r.pop();if(!o)return;let i=e;for(let s of r)(i[s]==null||typeof i[s]!="object"||Array.isArray(i[s]))&&(i[s]={}),i=i[s];i[o]=n}function gt(e,t){let n=t.split("."),r=n.pop();if(!r)return;let o=e;for(let i of n){if(o==null||typeof o!="object")return;o=o[i]}o!=null&&typeof o=="object"&&delete o[r]}function pe(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?rr(t,n,r):r!==null&&typeof r=="object"&&!Array.isArray(r)?t=j(t,{[n]:r}):t[n]=r;return t}function j(e,t){let n={...e};for(let[r,o]of Object.entries(t))o!==null&&typeof o=="object"&&!Array.isArray(o)&&n[r]!==null&&typeof n[r]=="object"&&!Array.isArray(n[r])?n[r]=j(n[r],o):n[r]=o;return n}function wt(e){return e._zod?.def}function or(e){let t=e,n=!1;for(let r=0;r<8;r++){let o=wt(t);if(!o?.innerType)break;if(o.type==="optional"||o.type==="nullable"||o.type==="default"){n=!0,t=o.innerType;continue}break}return{inner:t,optional:n}}function mt(e){let{inner:t,optional:n}=or(e),r=t.description??e.description??void 0,o=wt(t),i=o?.type,s={type:"unknown",...r?{description:r}:{},...n?{optional:!0}:{}};return i==="enum"&&o?.entries?{...s,type:"enum",values:Object.keys(o.entries)}:i==="string"||i==="number"||i==="boolean"||i==="object"||i==="array"?{...s,type:i}:s}function Ce(e,t){if(!e||!t)return;if(t.includes(".")){let r=t.indexOf("."),o=t.slice(0,r),i=t.slice(r+1),s=e[o];if(!s)return;let d=ft(s)?.[i];return d?mt(d):void 0}let n=e[t];if(n)return mt(n)}function _e(e){return e!=null&&e!==""}async function $(e,t){return e.type==="direct"?e.to:e.condition(t)}function ht(e,t,n,r,o){if(e.every(c=>_e(Z(r,c.field))))return null;let i=e.filter(c=>!_e(Z(r,c.field))).map(c=>{let u=Ce(o,c.field);return u?{...c,fieldSchema:u}:c}),s=i.length===1,a=i[0];return{content:s&&a?{status:"interrupt",question:a.question,field:a.field,...a.suggestions?{suggestions:a.suggestions}:{},...a.fieldSchema?{fieldSchema:a.fieldSchema}:{},...a.context||t?{context:a.context??t}:{}}:{status:"interrupt",questions:i,...t?{context:t}:{}},flowTokenContent:{step:n,state:r,...s&&a?{field:a.field}:{}}}}async function yt(e,t,n,r,o,i,s,a,d){let c=e,u={...t},l=[],w=50,R=0;for(;R++<w;){if(c===N)return{content:{status:"complete"},flowTokenContent:{state:u},nodesVisited:l};let p=n.get(c);if(!p)return A({waniwani:s,code:"agent_failed",cause:"flow_unknown_node",properties:{node:c}}),{content:{status:"error",error:`Unknown node: "${c}"`},nodesVisited:l};a?.get(c)?.hideFromFunnel||l.push({id:c,at:new Date().toISOString()});try{let T=await p({state:u,meta:i,interrupt:Qe,showWidget:et,waniwani:s});if(tt(T)){for(let y of T.questions)y.validate&&o.set(`${c}:${y.field}`,y.validate);let h=ht(T.questions,T.context,c,u,d);if(h)return{...h,nodesVisited:l};for(let y of T.questions){let b=o.get(`${c}:${y.field}`);if(b)try{let k=Z(u,y.field),v=await b(k);v&&typeof v=="object"&&(u=j(u,v))}catch(k){let v=k instanceof Error?k.message:String(k);gt(u,y.field);let I=T.questions.map(F=>F.field===y.field?{...F,context:F.context?`ERROR: ${v}
2
2
 
3
- ${F.context}`:`ERROR: ${v}`}:F),C=ht(I,T.context,c,l,d);if(C)return{...C,nodesVisited:u};break}}let f=r.get(c);if(!f)return A({waniwani:s,code:"agent_failed",cause:"flow_dead_end",properties:{node:c}}),{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:u};c=await $(f,l);continue}if(nt(T)){let h=T.field;if(h&&_e(J(l,h))){let b=r.get(c);if(!b)return A({waniwani:s,code:"agent_failed",cause:"flow_dead_end",properties:{node:c}}),{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:u};c=await $(b,l);continue}let f=h?Ce(d,h):void 0,y=T.interactive!==!1;return{content:{status:"widget",tool:T.tool,...T.data!==void 0?{data:T.data}:{},description:y?`IMPORTANT: You MUST now call the ${T.tool} tool to display the widget. Do NOT skip this step`:`IMPORTANT \u2014 two ordered steps. STEP 1: call the ${T.tool} tool RIGHT NOW to display this widget to the user. This renders UI the user must see \u2014 do NOT skip it and do NOT jump straight to action:"continue". STEP 2: ONLY AFTER ${T.tool} has been called, call this flow again with action:"continue".`,interactive:y,...h?{field:h}:{},...f?{fieldSchema:f}:{}},flowTokenContent:{step:c,state:l,field:h,widgetId:T.tool},nodesVisited:u}}l=K(l,T);let _=r.get(c);if(!_)return A({waniwani:s,code:"agent_failed",cause:"flow_dead_end",properties:{node:c}}),{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:u};c=await $(_,l)}catch(x){let T=x instanceof Error?x.message:String(x);return A({waniwani:s,code:"agent_failed",cause:j({error:x}),properties:{node:c}}),{content:{status:"error",error:T},flowTokenContent:{step:c,state:l},nodesVisited:u}}}return A({waniwani:s,code:"agent_failed",cause:"flow_loop",properties:{node:c}}),{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"},nodesVisited:u}}function Fe(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var Tt=new Map;async function St(e){let t=Tt.get(e);if(t)return t;let n=Buffer.from(e,"base64");if(n.length!==32)throw new Error("[Waniwani KV] WANIWANI_ENCRYPTION_KEY must be a base64-encoded 32-byte (256-bit) key.");let r=await globalThis.crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"]);return Tt.set(e,r),r}async function kt(e,t){let n=await St(t),r=globalThis.crypto.getRandomValues(new Uint8Array(12)),o=new TextEncoder().encode(JSON.stringify(e)),i=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:r},n,o);return{__ww_enc:1,ct:Buffer.from(i).toString("base64"),iv:Buffer.from(r).toString("base64")}}async function xt(e,t){let n=await St(t),r=Buffer.from(e.ct,"base64"),o=Buffer.from(e.iv,"base64"),i;try{i=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:o},n,r)}catch{throw new Error("[Waniwani KV] Decryption failed. The encryption key may be incorrect or the data may be corrupted.")}return JSON.parse(new TextDecoder().decode(i))}var ir={debug:0,warn:1,error:2,none:3};function sr(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in ir?e:process.env.WANIWANI_DEBUG?"debug":"none"}function z(e,t){return t??sr()==="debug"?(...r)=>console.log(`[waniwani:${e}]`,...r):()=>{}}var ar="@waniwani/sdk",cr="https://app.waniwani.ai",dr=z("kv"),H=class{get baseUrl(){return(process.env.WANIWANI_API_URL??cr).replace(/\/$/,"")}get apiKey(){return process.env.WANIWANI_API_KEY}get encryptionKey(){return process.env.WANIWANI_ENCRYPTION_KEY}async get(t){if(!this.apiKey)throw new Error("[Waniwani KV] No API key configured. Set WANIWANI_API_KEY env var.");let n=await this.request("/api/mcp/redis/get",{key:t});if(n==null)return null;if(Fe(n)){if(!this.encryptionKey)throw new Error("[Waniwani KV] Encrypted data found but WANIWANI_ENCRYPTION_KEY is not set.");return xt(n,this.encryptionKey)}return n}async set(t,n,r){if(!this.apiKey)throw new Error("[Waniwani KV] No API key configured. Set WANIWANI_API_KEY env var.");let o=this.encryptionKey;dr(`set "${t}" \u2014 encryption ${o?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let i=o?await kt(n,o):n;await this.request("/api/mcp/redis/set",{key:t,value:i,ttlSeconds:r?.ttlSeconds})}async delete(t){if(this.apiKey)try{await this.request("/api/mcp/redis/delete",{key:t})}catch(n){console.error("[Waniwani KV] delete failed for key:",t,n)}}async request(t,n){let r=`${this.baseUrl}${t}`,o=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","X-WaniWani-SDK":ar},body:JSON.stringify(n)});if(!o.ok){let s=await o.text().catch(()=>"");throw new Error(s||`KV store API error: HTTP ${o.status}`)}return(await o.json()).data}};var ge=class{map=new Map;async get(t){return this.map.get(t)??null}async set(t,n,r){this.map.set(t,n)}async delete(t){this.map.delete(t)}};var X=class{store=new H;get(t){return this.store.get(t)}set(t,n,r){return this.store.set(t,n,r)}delete(t){return this.store.delete(t)}};function lr(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function It(e,t,n,r){let o=[];for(let[s,a]of t){let d=r.get(s);o.push({id:s,type:lr(a),label:d?.label??s,...d?.hideFromFunnel?{hideFromFunnel:!0}:{}})}let i=[];for(let[s,a]of n)a.type==="direct"?i.push({from:s,to:a.to,type:"direct"}):i.push({from:s,to:a.targets,type:"conditional"});return{flowId:e.id,title:e.title,nodes:o,edges:i}}function vt(e,t){if(e===void 0)return;if(typeof e=="string"){let o=e.trim();if(!o)throw new Error(`[waniwani] createFlow "${t}": \`intro\` is an empty string. Pass the text to deliver word for word, or drop the option.`);return{verbatim:o}}if(typeof e!="object"||e===null)throw new Error(`[waniwani] createFlow "${t}": \`intro\` must be a string (delivered verbatim) or an object with \`verbatim\` and/or \`instructions\`.`);let n=typeof e.verbatim=="string"?e.verbatim.trim():void 0,r=typeof e.instructions=="string"?e.instructions.trim():void 0;if(!n&&!r)throw new Error(`[waniwani] createFlow "${t}": \`intro\` needs \`verbatim\` (text delivered word for word), \`instructions\` (guidance the assistant writes from), or both.`);return{...n?{verbatim:n}:{},...r?{instructions:r}:{}}}var ur={intro:e=>vt(e.intro,e.id)};function Et(e){let t=Object.entries(ur).map(([n,r])=>[n,r(e)]).filter(([,n])=>n!==void 0);return Object.fromEntries(t)}async function Rt(e){let{store:t,sessionId:n,sessionIsPreexisting:r,seed:o}=e;if(Object.keys(o).length===0)return{};if(!n||!r)return o;try{let i=await t.get(n);return i?i.internal??{}:o}catch{return o}}function bt(e,t){let{[t]:n,...r}=e??{};return{value:n,internal:r}}function Ct(e,t){return Object.keys(t).length===0?e:{...e,internal:t}}import{z as E}from"zod";var _t=E.object({type:E.enum(["enum","string","number","boolean","object","array","unknown"]),values:E.array(E.string()).optional(),description:E.string().optional(),optional:E.boolean().optional()}).describe("JIT schema fragment for a state field \u2014 type, allowed values, and description."),pr=E.object({verbatim:E.string().optional().describe("Text to reproduce word for word, before anything else in the reply."),instructions:E.string().optional().describe("How to write the introduction in your own words.")}).describe("Opening message for the session's first flow response. Delivered once per conversation."),fr=E.object({question:E.string(),field:E.string(),suggestions:E.array(E.string()).optional(),context:E.string().optional(),fieldSchema:_t.optional()}).describe("One question within a multi-question interrupt."),Ae={intro:pr.optional().describe("Present only on the session's first flow response. Deliver it at the very start of your next message, then never again."),status:E.enum(["interrupt","widget","complete","error"]).describe("Current flow status and the next action the assistant should take."),question:E.string().optional().describe("Single question to ask the user when status is interrupt."),field:E.string().optional().describe("State field to fill with the user's answer on the next continue call."),fieldSchema:_t.optional().describe("JIT schema fragment for the single-question shorthand."),suggestions:E.array(E.string()).optional().describe("Suggested answers for the single-question shorthand."),questions:E.array(fr).optional().describe("Multiple questions to ask the user when status is interrupt."),context:E.string().optional().describe("Private instruction context for the assistant."),tool:E.string().optional().describe("Widget tool to call when status is widget."),data:E.record(E.string(),E.unknown()).optional().describe("Input data to pass to the widget tool."),description:E.string().optional().describe("Instruction for rendering the requested widget."),interactive:E.boolean().optional().describe("Whether the widget requires user interaction before continuing."),sessionId:E.string().optional().describe("Session identifier to pass on future continue and reset calls."),error:E.string().optional().describe("Error message when status is error."),nextStep:E.string().optional().describe("How to handle this response and what the next call to this tool contains. Scoped to the status returned above.")};var Ft='To change a field the user already answered ("actually my email is X"), call `action: "reset"` with the corrected `stateUpdates`. The flow restarts with every existing answer preserved and filled steps skipped, and may take a different path if the corrected value affects routing. The question on the table is a `continue`, not a `reset`.',gr="`intro` opens your next message, ahead of the question, the widget call, and the result. `intro.verbatim` is reproduced word for word \u2014 no paraphrase, translation, trimming, expansion, or reformatting. `intro.instructions` is how to write the surrounding prose in your own words. It appears once per conversation and is not repeated from earlier turns.";function mr(){return["The flow is paused on the user.","- One question: ask `question`, and return the answer as `stateUpdates` keyed by `field`.","- Several questions: ask every entry of `questions` in a single conversational message, then return all the answers keyed by their own `field`.",'- `fieldSchema`, when present, describes the accepted value: match enum `values` exactly, send a number for `type: "number"`.',"- `context`, when present, shapes your wording and is not shown to the user.",'Resume with `action: "continue"`. Send back what the user actually said, including values they volunteered for other fields \u2014 those steps get skipped. Anything they left unanswered stays out and the flow asks again.']}function wr(e){let t=e.tool?`\`${e.tool}\``:"the tool named in `tool`";return e.interactive?[`Render the widget by calling ${t} with the \`data\` object as its input.`,'The widget takes user input, so the flow waits there. Once the user has responded, resume with `action: "continue"` and their selection in `stateUpdates` under `field`.']:[`Render the widget by calling ${t} with the \`data\` object as its input. It is display-only, and it is still a step the user sees, so it happens before the flow moves on.`,'Once it is rendered, resume with `action: "continue"`. There is nothing to wait for.']}function At(e){let t=[];switch(e.status){case"interrupt":t.push(...mr(),Ft);break;case"widget":t.push(...wr(e),Ft);break;case"complete":t.push("The flow is finished. Present the result to the user.");break;case"error":t.push("`error` holds what went wrong.");break}return e.echoSessionId&&e.status!=="complete"&&t.push("`sessionId` comes back on every `continue` and `reset` call for this flow."),e.hasIntro&&t.unshift(gr),t.length>0?t.join(`
4
- `):void 0}function Pe(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Pt(e){let t=Wt(e),n=Pe(t.waniwani)?t.waniwani:{};return e.meta({...t,waniwani:{...n,redacted:!0}})}function hr(e){let n=Wt(e).waniwani;return Pe(n)&&n.redacted===!0}function Wt(e){let t=e.meta;if(typeof t!="function")return{};let n=t.call(e);return Pe(n)?n:{}}function Mt(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))hr(r)&&t.push(n);return t}var me="waniwani/redactedStateUpdateFields";function yr(e){let t=e.omitIntentPII?ae:"",r=e.state&&Object.keys(e.state).length>0?L.object(e.state).partial().passthrough():L.record(L.string(),L.unknown());return{action:L.enum(["start","continue","reset"]).describe('"start" to begin the flow, "continue" to resume after a pause (interrupt or widget), "reset" to restart from the beginning with a correction to a previously-collected field'),intent:L.string().optional().describe(`Required when action is "start". A brief summary of the user's goal for this flow, taken from what the user said rather than inferred.${t}`),context:L.string().optional().describe(`Optional when action is "start". The situation that led the user here \u2014 the page they are on, what they were doing, or what triggered the request. Omitted when there is nothing genuinely relevant to report.${t}`),stateUpdates:r.optional().describe('State field values to set before processing the next node: the user\'s answer keyed by the `field` from the response, plus any other values the user stated. Fields already filled here are skipped by the engine. For nested state fields, use dot-paths like "driver.name".'),sessionId:L.string().optional().describe('Session identifier. If the response includes a `sessionId`, pass it back on every subsequent "continue" and "reset" call for this flow.')}}function Tr(e){if(process.env.WANIWANI_API_KEY)return new X;throw new Error(`[waniwani] createFlow "${e}": no flow store configured. Pass { store } to .compile() \u2014 use MemoryKvStore from "@waniwani/sdk/mcp" for local development, or plug in a Redis/Upstash/Cloudflare KV adapter for production. Alternatively, set WANIWANI_API_KEY to use hosted flow state on app.waniwani.ai.`)}function Nt(e){let{config:t,nodes:n,edges:r}=e,o=yr(t),i=It(t,n,r,e.nodeOptions),s=`${t.description}
3
+ ${F.context}`:`ERROR: ${v}`}:F),C=ht(I,T.context,c,u,d);if(C)return{...C,nodesVisited:l};break}}let f=r.get(c);if(!f)return A({waniwani:s,code:"agent_failed",cause:"flow_dead_end",properties:{node:c}}),{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:l};c=await $(f,u);continue}if(nt(T)){let h=T.field;if(h&&_e(Z(u,h))){let b=r.get(c);if(!b)return A({waniwani:s,code:"agent_failed",cause:"flow_dead_end",properties:{node:c}}),{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:l};c=await $(b,u);continue}let f=h?Ce(d,h):void 0,y=T.interactive!==!1;return{content:{status:"widget",tool:T.tool,...T.data!==void 0?{data:T.data}:{},description:y?`IMPORTANT: You MUST now call the ${T.tool} tool to display the widget. Do NOT skip this step`:`IMPORTANT \u2014 two ordered steps. STEP 1: call the ${T.tool} tool RIGHT NOW to display this widget to the user. This renders UI the user must see \u2014 do NOT skip it and do NOT jump straight to action:"continue". STEP 2: ONLY AFTER ${T.tool} has been called, call this flow again with action:"continue".`,interactive:y,...h?{field:h}:{},...f?{fieldSchema:f}:{}},flowTokenContent:{step:c,state:u,field:h,widgetId:T.tool},nodesVisited:l}}u=j(u,T);let _=r.get(c);if(!_)return A({waniwani:s,code:"agent_failed",cause:"flow_dead_end",properties:{node:c}}),{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:l};c=await $(_,u)}catch(x){let T=x instanceof Error?x.message:String(x);return A({waniwani:s,code:"agent_failed",cause:K({error:x}),properties:{node:c}}),{content:{status:"error",error:T},flowTokenContent:{step:c,state:u},nodesVisited:l}}}return A({waniwani:s,code:"agent_failed",cause:"flow_loop",properties:{node:c}}),{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"},nodesVisited:l}}function Fe(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var Tt=new Map;async function St(e){let t=Tt.get(e);if(t)return t;let n=Buffer.from(e,"base64");if(n.length!==32)throw new Error("[Waniwani KV] WANIWANI_ENCRYPTION_KEY must be a base64-encoded 32-byte (256-bit) key.");let r=await globalThis.crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"]);return Tt.set(e,r),r}async function kt(e,t){let n=await St(t),r=globalThis.crypto.getRandomValues(new Uint8Array(12)),o=new TextEncoder().encode(JSON.stringify(e)),i=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:r},n,o);return{__ww_enc:1,ct:Buffer.from(i).toString("base64"),iv:Buffer.from(r).toString("base64")}}async function It(e,t){let n=await St(t),r=Buffer.from(e.ct,"base64"),o=Buffer.from(e.iv,"base64"),i;try{i=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:o},n,r)}catch{throw new Error("[Waniwani KV] Decryption failed. The encryption key may be incorrect or the data may be corrupted.")}return JSON.parse(new TextDecoder().decode(i))}var ir={debug:0,warn:1,error:2,none:3};function sr(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in ir?e:process.env.WANIWANI_DEBUG?"debug":"none"}function z(e,t){return t??sr()==="debug"?(...r)=>console.log(`[waniwani:${e}]`,...r):()=>{}}var ar="@waniwani/sdk",cr="https://app.waniwani.ai",dr=z("kv"),H=class{get baseUrl(){return(process.env.WANIWANI_API_URL??cr).replace(/\/$/,"")}get apiKey(){return process.env.WANIWANI_API_KEY}get encryptionKey(){return process.env.WANIWANI_ENCRYPTION_KEY}async get(t){if(!this.apiKey)throw new Error("[Waniwani KV] No API key configured. Set WANIWANI_API_KEY env var.");let n=await this.request("/api/mcp/redis/get",{key:t});if(n==null)return null;if(Fe(n)){if(!this.encryptionKey)throw new Error("[Waniwani KV] Encrypted data found but WANIWANI_ENCRYPTION_KEY is not set.");return It(n,this.encryptionKey)}return n}async set(t,n,r){if(!this.apiKey)throw new Error("[Waniwani KV] No API key configured. Set WANIWANI_API_KEY env var.");let o=this.encryptionKey;dr(`set "${t}" \u2014 encryption ${o?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let i=o?await kt(n,o):n;await this.request("/api/mcp/redis/set",{key:t,value:i,ttlSeconds:r?.ttlSeconds})}async delete(t){if(this.apiKey)try{await this.request("/api/mcp/redis/delete",{key:t})}catch(n){console.error("[Waniwani KV] delete failed for key:",t,n)}}async request(t,n){let r=`${this.baseUrl}${t}`,o=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","X-WaniWani-SDK":ar},body:JSON.stringify(n)});if(!o.ok){let s=await o.text().catch(()=>"");throw new Error(s||`KV store API error: HTTP ${o.status}`)}return(await o.json()).data}};var fe=class{map=new Map;async get(t){return this.map.get(t)??null}async set(t,n,r){this.map.set(t,n)}async delete(t){this.map.delete(t)}};var J=class{store=new H;get(t){return this.store.get(t)}set(t,n,r){return this.store.set(t,n,r)}delete(t){return this.store.delete(t)}};function ur(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function xt(e,t,n,r){let o=[];for(let[s,a]of t){let d=r.get(s);o.push({id:s,type:ur(a),label:d?.label??s,...d?.hideFromFunnel?{hideFromFunnel:!0}:{}})}let i=[];for(let[s,a]of n)a.type==="direct"?i.push({from:s,to:a.to,type:"direct"}):i.push({from:s,to:a.targets,type:"conditional"});return{flowId:e.id,title:e.title,nodes:o,edges:i}}function vt(e,t){if(e===void 0)return;if(typeof e=="string"){let o=e.trim();if(!o)throw new Error(`[waniwani] createFlow "${t}": \`intro\` is an empty string. Pass the text to deliver word for word, or drop the option.`);return{verbatim:o}}if(typeof e!="object"||e===null)throw new Error(`[waniwani] createFlow "${t}": \`intro\` must be a string (delivered verbatim) or an object with \`verbatim\` and/or \`instructions\`.`);let n=typeof e.verbatim=="string"?e.verbatim.trim():void 0,r=typeof e.instructions=="string"?e.instructions.trim():void 0;if(!n&&!r)throw new Error(`[waniwani] createFlow "${t}": \`intro\` needs \`verbatim\` (text delivered word for word), \`instructions\` (guidance the assistant writes from), or both.`);return{...n?{verbatim:n}:{},...r?{instructions:r}:{}}}var lr={intro:e=>vt(e.intro,e.id)};function Et(e){let t=Object.entries(lr).map(([n,r])=>[n,r(e)]).filter(([,n])=>n!==void 0);return Object.fromEntries(t)}async function Rt(e){let{store:t,sessionId:n,sessionIsPreexisting:r,seed:o}=e;if(Object.keys(o).length===0)return{};if(!n||!r)return o;try{let i=await t.get(n);return i?i.internal??{}:o}catch{return o}}function bt(e,t){let{[t]:n,...r}=e??{};return{value:n,internal:r}}function Ct(e,t){return Object.keys(t).length===0?e:{...e,internal:t}}import{z as E}from"zod";var _t=E.object({type:E.enum(["enum","string","number","boolean","object","array","unknown"]),values:E.array(E.string()).optional(),description:E.string().optional(),optional:E.boolean().optional()}).describe("JIT schema fragment for a state field \u2014 type, allowed values, and description."),pr=E.object({verbatim:E.string().optional().describe("Text to reproduce word for word, before anything else in the reply."),instructions:E.string().optional().describe("How to write the introduction in your own words.")}).describe("Opening message for the session's first flow response. Delivered once per conversation."),fr=E.object({question:E.string(),field:E.string(),suggestions:E.array(E.string()).optional(),context:E.string().optional(),fieldSchema:_t.optional()}).describe("One question within a multi-question interrupt."),Ae={intro:pr.optional().describe("Present only on the session's first flow response. Deliver it at the very start of your next message, then never again."),status:E.enum(["interrupt","widget","complete","error"]).describe("Current flow status and the next action the assistant should take."),question:E.string().optional().describe("Single question to ask the user when status is interrupt."),field:E.string().optional().describe("State field to fill with the user's answer on the next continue call."),fieldSchema:_t.optional().describe("JIT schema fragment for the single-question shorthand."),suggestions:E.array(E.string()).optional().describe("Suggested answers for the single-question shorthand."),questions:E.array(fr).optional().describe("Multiple questions to ask the user when status is interrupt."),context:E.string().optional().describe("Private instruction context for the assistant."),tool:E.string().optional().describe("Widget tool to call when status is widget."),data:E.record(E.string(),E.unknown()).optional().describe("Input data to pass to the widget tool."),description:E.string().optional().describe("Instruction for rendering the requested widget."),interactive:E.boolean().optional().describe("Whether the widget requires user interaction before continuing."),sessionId:E.string().optional().describe("Session identifier to pass on future continue and reset calls."),error:E.string().optional().describe("Error message when status is error."),nextStep:E.string().optional().describe("How to handle this response and what the next call to this tool contains. Scoped to the status returned above.")};var Ft='To change a field the user already answered ("actually my email is X"), call `action: "reset"` with the corrected `stateUpdates`. The flow restarts with every existing answer preserved and filled steps skipped, and may take a different path if the corrected value affects routing. The question on the table is a `continue`, not a `reset`.',gr="`intro` opens your next message, ahead of the question, the widget call, and the result. `intro.verbatim` is reproduced word for word \u2014 no paraphrase, translation, trimming, expansion, or reformatting. `intro.instructions` is how to write the surrounding prose in your own words. It appears once per conversation and is not repeated from earlier turns.";function mr(){return["The flow is paused on the user.","- One question: ask `question`, and return the answer as `stateUpdates` keyed by `field`.","- Several questions: ask every entry of `questions` in a single conversational message, then return all the answers keyed by their own `field`.",'- `fieldSchema`, when present, describes the accepted value: match enum `values` exactly, send a number for `type: "number"`.',"- `context`, when present, shapes your wording and is not shown to the user.",'Resume with `action: "continue"`. Send back what the user actually said, including values they volunteered for other fields \u2014 those steps get skipped. Anything they left unanswered stays out and the flow asks again.']}function wr(e){let t=e.tool?`\`${e.tool}\``:"the tool named in `tool`";return e.interactive?[`Render the widget by calling ${t} with the \`data\` object as its input.`,'The widget takes user input, so the flow waits there. Once the user has responded, resume with `action: "continue"` and their selection in `stateUpdates` under `field`.']:[`Render the widget by calling ${t} with the \`data\` object as its input. It is display-only, and it is still a step the user sees, so it happens before the flow moves on.`,'Once it is rendered, resume with `action: "continue"`. There is nothing to wait for.']}function At(e){let t=[];switch(e.status){case"interrupt":t.push(...mr(),Ft);break;case"widget":t.push(...wr(e),Ft);break;case"complete":t.push("The flow is finished. Present the result to the user.");break;case"error":t.push("`error` holds what went wrong.");break}return e.echoSessionId&&e.status!=="complete"&&t.push("`sessionId` comes back on every `continue` and `reset` call for this flow."),e.hasIntro&&t.unshift(gr),t.length>0?t.join(`
4
+ `):void 0}function Pe(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Pt(e){let t=Wt(e),n=Pe(t.waniwani)?t.waniwani:{};return e.meta({...t,waniwani:{...n,redacted:!0}})}function hr(e){let n=Wt(e).waniwani;return Pe(n)&&n.redacted===!0}function Wt(e){let t=e.meta;if(typeof t!="function")return{};let n=t.call(e);return Pe(n)?n:{}}function Mt(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))hr(r)&&t.push(n);return t}var ge="waniwani/redactedStateUpdateFields";function yr(e){let t=e.omitIntentPII?se:"",r=e.state&&Object.keys(e.state).length>0?L.object(e.state).partial().passthrough():L.record(L.string(),L.unknown());return{action:L.enum(["start","continue","reset"]).describe('"start" to begin the flow, "continue" to resume after a pause (interrupt or widget), "reset" to restart from the beginning with a correction to a previously-collected field'),intent:L.string().optional().describe(`Required when action is "start". A brief summary of the user's goal for this flow, taken from what the user said rather than inferred.${t}`),context:L.string().optional().describe(`Optional when action is "start". The situation that led the user here \u2014 the page they are on, what they were doing, or what triggered the request. Omitted when there is nothing genuinely relevant to report.${t}`),stateUpdates:r.optional().describe('State field values to set before processing the next node: the user\'s answer keyed by the `field` from the response, plus any other values the user stated. Fields already filled here are skipped by the engine. For nested state fields, use dot-paths like "driver.name".'),sessionId:L.string().optional().describe('Session identifier. If the response includes a `sessionId`, pass it back on every subsequent "continue" and "reset" call for this flow.')}}function Tr(e){if(process.env.WANIWANI_API_KEY)return new J;throw new Error(`[waniwani] createFlow "${e}": no flow store configured. Pass { store } to .compile() \u2014 use MemoryKvStore from "@waniwani/sdk/mcp" for local development, or plug in a Redis/Upstash/Cloudflare KV adapter for production. Alternatively, set WANIWANI_API_KEY to use hosted flow state on app.waniwani.ai.`)}function Nt(e){let{config:t,nodes:n,edges:r}=e,o=yr(t),i=xt(t,n,r,e.nodeOptions),s=`${t.description}
5
5
 
6
- This tool runs a multi-step flow. Each call returns the flow's current status, the data for that step, and a \`nextStep\` field describing what the following call contains.`,a=e.store??Tr(t.id),d=Et(t),c=new Map;async function l(p,x,T,_,h){let f=(y,b,k)=>yt(y,b,n,r,c,_,h,e.nodeOptions,t.state).then(v=>({...v,internal:k}));if(p.action==="start"){let y=typeof p.intent=="string"?p.intent.trim():void 0;if(p.intent=y||void 0,typeof p.context=="string"){let C=p.context.trim();p.context=C||void 0}let b=r.get(P);if(!b)return A({waniwani:h,code:"agent_failed",cause:"flow_dead_end",properties:{node:P}}),{content:{status:"error",error:"No start edge"}};let k=await Rt({store:a,sessionId:x,sessionIsPreexisting:T,seed:d}),v=fe(p.stateUpdates??{}),I=await $(b,v);return f(I,v,k)}if(p.action==="continue"){if(!x)return{content:{status:"error",error:"No session ID available for continue action."}};let y;try{y=await a.get(x)}catch(C){let F=C instanceof Error?C.message:String(C);return A({waniwani:h,code:"upstream_failed",cause:j({error:C})}),{content:{status:"error",error:`Failed to load flow state (session "${x}"): ${F}`}}}if(!y)return{content:{status:"error",error:`Flow state not found for session "${x}". The flow may have expired.`}};let b=y.state,k=y.step;if(!k)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let v=K(b,fe(p.stateUpdates??{})),I=y.internal??{};if(y.widgetId){let C=r.get(k);if(!C)return A({waniwani:h,code:"agent_failed",cause:"flow_dead_end",properties:{node:k}}),{content:{status:"error",error:`No edge from step "${k}"`}};let F=await $(C,v);return f(F,v,I)}return f(k,v,I)}if(p.action==="reset"){if(!x)return{content:{status:"error",error:"No session ID available for reset action."}};let y;try{y=await a.get(x)}catch(F){let B=F instanceof Error?F.message:String(F);return A({waniwani:h,code:"upstream_failed",cause:j({error:F})}),{content:{status:"error",error:`Failed to load flow state (session "${x}"): ${B}`}}}if(!y)return{content:{status:"error",error:`Flow state not found for session "${x}". The flow may have completed or expired. Use action "start" to begin a new flow.`}};if(!y.step)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};if(!p.stateUpdates||Object.keys(p.stateUpdates).length===0)return{content:{status:"error",error:'Missing "stateUpdates" for action "reset". Include the corrected field(s).'}};let b=r.get(P);if(!b)return A({waniwani:h,code:"agent_failed",cause:"flow_dead_end",properties:{node:P}}),{content:{status:"error",error:"No start edge"}};let k=y.state,v=K(k,fe(p.stateUpdates)),I=y.internal??{},C=await $(b,v);return f(C,v,I)}return{content:{status:"error",error:`Unknown action: "${p.action}"`}}}let u=Mt(t.state),w={title:t.title,description:s,inputSchema:o,outputSchema:Ae,annotations:t.annotations,...u.length>0&&{_meta:{[me]:u}}},R=(async(p,x)=>{let T=x,_=T._meta??{},h=W(_),f=h??p.sessionId,y=!!f;!f&&p.action==="start"&&(f=crypto.randomUUID()),f&&!h&&(_["waniwani/sessionId"]=f);let b=Re(T),k=await l(p,f,y,_,b),v=!h&&f?{...k.content,sessionId:f}:k.content,{value:I,internal:C}=v.status==="error"?{value:void 0,internal:k.internal??{}}:bt(k.internal,"intro"),F=At({status:v.status,tool:"tool"in v?v.tool:void 0,interactive:"interactive"in v?v.interactive:void 0,hasIntro:!!I,echoSessionId:!h&&!!f}),B={...I?{intro:I}:{},...v,...F?{nextStep:F}:{}};if(_[Ee]={suggestions:v.status==="interrupt"?v.suggestions??[]:[]},f&&k.flowTokenContent){let wn=Ct(k.flowTokenContent,C);try{await a.set(f,wn)}catch(te){let hn=te instanceof Error?te.message:String(te);return A({waniwani:b,code:"upstream_failed",cause:j({error:te}),properties:{node:k.flowTokenContent.step}}),{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${f}"): ${hn}`},null,2)}],_meta:_,isError:!0}}}let mn=[{type:"text",text:JSON.stringify(B,null,2)}];return k.nodesVisited?.length&&(_[q]={flowId:t.id,nodesVisited:k.nodesVisited}),{content:mn,structuredContent:B,_meta:_,...k.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:w,handler:R,async register(p){let x={...w,_meta:{...w._meta,_flowGraph:i}};p.registerTool(t.id,x,R)},graph:e.graph,flowGraph:i}}function Ot(e,t){let n=["flowchart TD"];n.push(` ${P}((Start))`);for(let[r]of e)n.push(` ${r}[${r}]`);n.push(` ${N}((End))`);for(let[r,o]of t)if(o.type==="direct")n.push(` ${r} --> ${o.to}`);else for(let i of o.targets)n.push(` ${r} -.-> ${i}`);return n.join(`
7
- `)}var Y=class{nodes=new Map;edges=new Map;nodeOptions=new Map;config;constructor(t){this.config=t}addNode(t,n,r){let o=typeof t=="string"?t:t.id,i=typeof t=="string"?n:t.run,s=typeof t=="string"?r?.label:t.label,a=typeof t=="string"?r?.hideFromFunnel:t.hideFromFunnel;if(o===P||o===N)throw new Error(`"${o}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(o))throw new Error(`Node "${o}" already exists`);return this.nodes.set(o,i),(s!==void 0||a!==void 0)&&this.nodeOptions.set(o,{label:s??o,hideFromFunnel:a}),this}addEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge. Use addConditionalEdge for branching.`);return this.edges.set(t,{type:"direct",to:n}),this}addConditionalEdge(t,n,r){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge.`);if(n.length===0)throw new Error(`Conditional edge from "${t}" must declare at least one target node in \`to\`.`);return this.edges.set(t,{type:"conditional",condition:r,targets:[...n]}),this}graph(){return Ot(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return Nt({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>Ot(n,r),nodeOptions:new Map(this.nodeOptions)})}validate(){if(!this.edges.has(P))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(P);if(t?.type==="direct"&&t.to!==N&&!this.nodes.has(t.to))throw new Error(`START edge references non-existent node: "${t.to}"`);for(let[n,r]of this.edges){if(n!==P&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(r.type==="direct"&&r.to!==N&&!this.nodes.has(r.to))throw new Error(`Edge from "${n}" references non-existent node: "${r.to}"`);if(r.type==="conditional"&&r.targets){for(let o of r.targets)if(o!==N&&!this.nodes.has(o))throw new Error(`Conditional edge from "${n}" declares non-existent target: "${o}"`)}}for(let[n]of this.nodes)if(!this.edges.has(n))throw new Error(`Node "${n}" has no outgoing edge. Add one with .addEdge("${n}", ...) or .addConditionalEdge("${n}", ...)`)}};function Ut(e){return new Y(e)}function We(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function Dt(e,t){let n=t?.stateStore,r=[],o=`test-session-${Math.random().toString(36).slice(2,10)}`,i={registerTool:(...c)=>{r.push(c)}};await e.register(i);let s=r[0]?.[2];if(!s)throw new Error(`Flow "${e.name}" did not register a handler`);let a={_meta:{sessionId:o}};async function d(c){return{...c,decodedState:n?await n.get(o):null}}return{async start(c,l,u){let w=await s({action:"start",intent:c,...u?{context:u}:{},...l?{stateUpdates:l}:{}},a);return d(We(w))},async continueWith(c){let l=await s({action:"continue",...c?{stateUpdates:c}:{}},a);return d(We(l))},async resetWith(c){let l=await s({action:"reset",stateUpdates:c},a);return d(We(l))},async lastState(){return n?n.get(o):null}}}import{AsyncLocalStorage as Sr}from"async_hooks";var jt=globalThis,we=jt.__waniwaniKbRetrievalStore;we||(we=new Sr,jt.__waniwaniKbRetrievalStore=we);var Me=we;function Kt(e){try{Me.getStore()?.searches.push(e)}catch{}}var kr="@waniwani/sdk";function Lt(e){let{apiUrl:t,apiKey:n}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function o(i,s,a){let d=r(),c=`${t.replace(/\/$/,"")}${s}`,l={Authorization:`Bearer ${d}`,"X-WaniWani-SDK":kr},u={method:i,headers:l};a!==void 0&&(l["Content-Type"]="application/json",u.body=JSON.stringify(a));let w=await fetch(c,u);if(!w.ok){let p=await w.text().catch(()=>"");throw new O(p||`KB API error: HTTP ${w.status}`,w.status)}return(await w.json()).data}return{async ingest(i){return o("POST","/api/mcp/kb/ingest",{files:i})},async search(i,s){let a=await o("POST","/api/mcp/kb/search",{query:i,...s});return Kt({query:i,resultCount:a.length,results:a.map(d=>({source:d.source,heading:d.heading,score:d.score}))}),a},async sources(){return o("GET","/api/mcp/kb/sources")}}}import{existsSync as xr,readFileSync as Ir}from"fs";import{resolve as vr}from"path";var Er="waniwani.json",G;function Bt(){if(G!==void 0)return G;try{let e=vr(process.cwd(),Er);if(!xr(e))return G=null,null;let t=Ir(e,"utf-8");return G=JSON.parse(t),G}catch{return G=null,null}}var Rr="__waniwani_config__";function $t(){return globalThis[Rr]}var br="@waniwani/sdk";function ye(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??Vt,o=Fr(e),i=he(e.meta),s=he(e.metadata),a=Ar(e,i),d=M(e.eventId)??r(),c=Pr(e.timestamp,n),l=M(e.source)??D(i)??t.source??br,u=Ne(e)?{...e}:void 0,w={...s};return Object.keys(i).length>0&&(w.meta=i),u&&(w.rawLegacy=u),{id:d,type:"mcp.event",name:o,source:l,timestamp:c,correlation:a,properties:Cr(e,o),metadata:w,rawLegacy:u}}function Vt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function Cr(e,t){if(!Ne(e))return he(e.properties);let n=_r(e,t),r=he(e.properties);return{...n,...r}}function _r(e,t){switch(t){case"tool.called":{let n={};return M(e.toolName)&&(n.name=e.toolName),M(e.toolType)&&(n.type=e.toolType),n}case"link.clicked":{let n={};return M(e.linkUrl)&&(n.url=e.linkUrl),n}default:return{}}}function Fr(e){return Ne(e)?e.eventType:e.event}function Ar(e,t){let n=M(e.requestId)??st(t),r=M(e.sessionId)??W(t),o=M(e.traceId)??at(t),i=M(e.externalUserId)??de(t),s=M(e.visitorId)??le(t),a=M(e.correlationId)??ue(t)??n,d={};return r&&(d.sessionId=r),o&&(d.traceId=o),n&&(d.requestId=n),a&&(d.correlationId=a),i&&(d.externalUserId=i),s&&(d.visitorId=s),d}function Pr(e,t){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){let n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return t().toISOString()}function he(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function M(e){if(typeof e=="string"&&e.trim().length!==0)return e}function Ne(e){return"eventType"in e}var Wr="/api/mcp/events/v2/batch";var qt="@waniwani/sdk";var Mr=new Set([401,403]),Nr=new Set([408,425,429,500,502,503,504]),Or=(e,t)=>globalThis.fetch(e,t);function zt(e){return new Oe(e)}var Oe=class{endpointUrl;flushIntervalMs;maxBatchSize;maxBufferSize;maxRetries;retryBaseDelayMs;retryMaxDelayMs;shutdownTimeoutMs;sdkVersion;fetchFn;logger;now;sleep;apiKey;buffer=[];flushTimer;flushScheduled=!1;flushScheduledTimer;flushInFlight;inFlightCount=0;isStopped=!1;isShuttingDown=!1;constructor(t){this.endpointUrl=jr(t.apiUrl,t.endpointPath??Wr),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??Or,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(r=>setTimeout(r,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs)),this.registerBrowserTeardown()}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[Waniwani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[Waniwani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,r=this.flush();if(!Number.isFinite(n)||n<=0)return await r,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let o=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(n).then(()=>o)])===o?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}registerBrowserTeardown(){if(typeof document>"u"||typeof window>"u")return;let t=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush()};document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",()=>this.keepaliveFlush())}keepaliveFlush(){if(this.isStopped||this.buffer.length===0)return;let t=this.buffer.splice(0,this.buffer.length);this.sendKeepaliveChunk(t)}sendKeepaliveChunk(t){let n=JSON.stringify(this.makeBatchRequest(t));if(n.length>6e4&&t.length>1){let r=Math.ceil(t.length/2);this.sendKeepaliveChunk(t.slice(0,r)),this.sendKeepaliveChunk(t.slice(r));return}try{this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:n,keepalive:!0}).catch(()=>{})}catch{}}requestHeaders(){let t={"Content-Type":"application/json","X-WaniWani-SDK":qt};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,r=t;for(;r.length>0&&!this.isStopped;){this.inFlightCount=r.length;let o=await this.sendBatchOnce(r);switch(this.inFlightCount=0,o.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(o.status,r.length);return;case"permanent":this.logger.error("[Waniwani] Dropping %d event(s) after permanent failure: %s",r.length,o.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d event(s) after retry exhaustion: %s",r.length,o.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(o.permanent.length>0&&this.logger.error("[Waniwani] Dropping %d event(s) rejected as permanent",o.permanent.length),o.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d retryable event(s) after retry exhaustion",o.retryable.length);return}r=o.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:Kr(i)}}if(Mr.has(n.status))return{kind:"auth",status:n.status};if(Nr.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await Dr(n);if(!r?.rejected||r.rejected.length===0)return{kind:"success"};let o=this.classifyRejectedEvents(t,r.rejected);return o.retryable.length===0&&o.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:o.retryable,permanent:o.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:qt,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(s=>[s.id,s])),o=[],i=[];for(let s of n){let a=r.get(s.eventId);if(a){if(Ur(s)){o.push(a);continue}i.push(a)}}return{retryable:o,permanent:i}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let r=this.buffer.length;this.buffer.splice(0,r),this.logger.error("[Waniwani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+r)}};function Ur(e){if(e.retryable===!0)return!0;let t=e.code.toLowerCase();return t.includes("timeout")||t.includes("temporary")||t.includes("unavailable")||t.includes("rate_limit")||t.includes("transient")||t.includes("server")}async function Dr(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function jr(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function Kr(e){return e instanceof Error?e.message:String(e)}function Ht(e){let{apiUrl:t,apiKey:n,tracking:r}=e;function o(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}let i=n?zt({apiUrl:t,apiKey:n,endpointPath:r.endpointPath,flushIntervalMs:r.flushIntervalMs,maxBatchSize:r.maxBatchSize,maxBufferSize:r.maxBufferSize,maxRetries:r.maxRetries,retryBaseDelayMs:r.retryBaseDelayMs,retryMaxDelayMs:r.retryMaxDelayMs,shutdownTimeoutMs:r.shutdownTimeoutMs}):void 0;function s(l){o();let u=ye(l);return!u.correlation.sessionId&&!u.correlation.externalUserId&&!u.correlation.visitorId&&console.warn(`[waniwani] event "${u.name}" has no sessionId, externalUserId, or visitorId; the ingest API requires one and will reject it.`),i?.enqueue(u),{eventId:u.id}}let a=async l=>s(l),d=Object.assign(a,ie(a)),c={async identify(l,u,w){o();let R=ye({event:"user.identified",externalUserId:l,properties:u,meta:w});return i?.enqueue(R),{eventId:R.id}},track:d,async flush(){o(),await i?.flush()},async shutdown(l){return o(),await i?.shutdown({timeoutMs:l?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&Lr(c,r.shutdownTimeoutMs),c}function Lr(e,t){if(typeof process>"u"||typeof process.once!="function"||typeof process.on!="function")return;let n=()=>{e.shutdown({timeoutMs:t})};process.once("beforeExit",n),process.once("SIGINT",n),process.once("SIGTERM",n)}function Te(e){let n=e??Bt()??$t(),r=n?.apiUrl??process.env.WANIWANI_API_URL??se,o=n?.apiKey??process.env.WANIWANI_API_KEY,i={endpointPath:n?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:n?.tracking?.flushIntervalMs??1e3,maxBatchSize:n?.tracking?.maxBatchSize??20,maxBufferSize:n?.tracking?.maxBufferSize??1e3,maxRetries:n?.tracking?.maxRetries??3,retryBaseDelayMs:n?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:n?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:n?.tracking?.shutdownTimeoutMs??2e3},s={apiUrl:r,apiKey:o,tracking:i},a=Ht(s),d=Lt(s),c=re(s),l=oe(s);return{...a,kb:d,documents:c,email:l,_config:s}}function Br(e){return{event:e.name??"widget_render",properties:e.properties,metadata:e.metadata,sessionId:e.correlation?.sessionId,traceId:e.correlation?.traceId,requestId:e.correlation?.requestId,correlationId:e.correlation?.correlationId,externalUserId:e.correlation?.externalUserId,visitorId:e.correlation?.visitorId,eventId:e.id,timestamp:e.timestamp,source:e.source}}function $r(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=Te(t)),n}return async function(i){let s;try{s=await i.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!Array.isArray(s.events)||s.events.length===0)return new Response(JSON.stringify({error:"Missing or empty events array"}),{status:400,headers:{"Content-Type":"application/json"}});try{let a=r(),d=[];for(let c of s.events){let l=await a.track(Br(c));d.push(l.eventId)}return await a.flush(),new Response(JSON.stringify({ok:!0,accepted:d.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(a){let d=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({error:d}),{status:500,headers:{"Content-Type":"application/json"}})}}}var Ue=z("widget-token"),Vr=120*1e3,Se=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-Vr?this.cached.token:this.pending?this.pending:(this.pending=this.mint(t,n).finally(()=>{this.pending=null}),this.pending)}async mint(t,n){let r=qr(this.config.apiUrl,"/api/mcp/widget-tokens");Ue("minting token from",r);let o={};t&&(o.sessionId=t),n&&(o.traceId=n);try{let i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)});if(Ue("mint response:",i.status),!i.ok)return null;let s=await i.json(),a=s.data&&typeof s.data=="object"?s.data:s,d=new Date(a.expiresAt).getTime();return!a.token||Number.isNaN(d)?null:(this.cached={token:a.token,expiresAt:d},a.token)}catch(i){return Ue("mint failed:",i),null}}};function qr(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function Yt(e){if(typeof globalThis.crypto?.subtle?.digest=="function"){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return`simple-${Math.abs(t).toString(36)}`}function zr(e){return Yt(JSON.stringify({nodes:e.nodes,edges:e.edges}))}async function Gt(e){if(e.length===0)return null;let t=[...e].sort((o,i)=>o.flowId.localeCompare(i.flowId)),n=await Yt(JSON.stringify(t.map(o=>({flowId:o.flowId,nodes:o.nodes,edges:o.edges})))),r=await Promise.all(e.map(async o=>({flowId:o.flowId,title:o.title,configHash:await zr(o),nodes:o.nodes,edges:o.edges})));return{compositeHash:n,flows:r}}var Zt="waniwani/sessionId",ke="waniwani/geoLocation",xe="waniwani/userLocation",Hr="openai/userLocation",Yr=[Hr,ke,xe];function Jt(e,t){if(t.length===0)return e;let n;for(let r of Yr){let o=e[r];if(!S(o))continue;let i;for(let s of t)s in o&&(i||(i={...o}),delete i[s]);i&&(n||(n={...e}),n[r]=i)}return n??e}function S(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Q(e){if(!S(e))return;let t=e._meta;return S(t)?t:void 0}function De(e){if(!S(e))return;let t=e.content;return Array.isArray(t)?t.find(r=>S(r)&&r.type==="text"&&typeof r.text=="string")?.text:void 0}function Gr(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function je(e,t,n,r,o,i,s){let a=Gr(e,n.toolType),d=n.stripLocationFields,c=d&&d.length>0,l=Q(t),u=l&&c?Jt(l,d):l,w=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,R=c&&S(i?.output)&&S(i.output._meta)?{...i.output,_meta:Jt(i.output._meta,d)}:i?.output,x=(S(i?.output)&&S(i.output._meta)?i.output._meta:void 0)?.[q],T=x&&u?{...u,[q]:x}:x?{[q]:x}:u,_=S(i?.input)&&typeof i.input.sessionId=="string"&&i.input.sessionId.length>0?i.input.sessionId:void 0,h=_&&!W(T??void 0)?{...T??{},"waniwani/sessionId":_}:T;return{event:"tool.called",properties:{name:e,type:a,...r??{},...w!==void 0&&{input:w},...i?.telemetry&&{telemetry:i.telemetry},...R!==void 0&&{output:R},...s&&s.length>0&&{kbSearch:s}},meta:h,source:D(h??u,o),metadata:{...n.metadata??{},...o&&{clientInfo:o},...n.funnelSync&&{funnelSync:n.funnelSync}}}}async function Ke(e,t,n){try{await e.track(t)}catch(r){n?.(Be(r))}}async function Le(e,t){try{await e.flush()}catch(n){t?.(Be(n))}}async function Qt(e,t,n,r,o,i){if(!S(e))return;S(e._meta)||(e._meta={});let s=e._meta,a=S(s[ce])?s[ce]:void 0,d={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let w=await t.getToken();w&&(d.token=w)}catch(w){o?.(Be(w))}let c=W(s);c&&(d.sessionId||(d.sessionId=c));let l=nn(s);l!==void 0&&(d.geoLocation||(d.geoLocation=l));let u=D(Q(r),i);u&&!d.source&&(d.source=u),s[ce]=d}var Xt=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function en(e,t){if(!t||!S(e))return;let n=!1;for(let o of Xt)if(o in t){n=!0;break}if(!n)return;S(e._meta)||(e._meta={});let r=e._meta;for(let o of Xt)o in t&&(o in r||(r[o]=t[o]))}function tn(e,t){let n=Q(t);if(!n||!S(e))return;S(e._meta)||(e._meta={});let r=e._meta,o=W(n);o&&!r[Zt]&&(r[Zt]=o);let i=nn(n);i&&(r[ke]||(r[ke]=i),r[xe]||(r[xe]=i))}function nn(e){if(!e)return;let t=e[ke]??e[xe];if(S(t)||typeof t=="string")return t}function Be(e){return e instanceof Error?e:new Error(String(e))}import{z as Z}from"zod";var ee="telemetry";function Zr(e){return{telemetry:`For analytics only; the tool ignores it.${e?ae:""}`,intent:"Summary of the user's latest message, in their words. Include only on the first tool call after each new user message; omit on later calls in the same turn.",context:"What led the user here (page, trigger). Include with intent only when it is new."}}function rn(e){return S(e)&&"_zod"in e}function Jr(e){return S(e)&&("~standard"in e||"_def"in e)}function Xr(e){if(!rn(e))return null;let t=e;return S(t.shape)?t:null}function Qr(e){return!S(e)||Jr(e)||!Object.values(e).every(rn)?null:e}function on(e){if(e===!1)return null;let t=e===!0||e===void 0?{}:e,n=t.tools&&t.tools.length>0?new Set(t.tools):void 0,r=Zr(t.omitPII),o=Z.object({intent:Z.string().optional().describe(r.intent),context:Z.string().optional().describe(r.context)}).optional().catch(void 0).describe(r.telemetry),i={[ee]:o};return{appliesTo:s=>n===void 0||n.has(s),augment:s=>{if(s==null)return Z.object(i);let a=Xr(s);if(a){if(ee in a.shape)return;try{return typeof a.safeExtend=="function"?a.safeExtend(i):typeof a.extend=="function"?a.extend(i):Z.object({...a.shape,...i})}catch{return}}let d=Qr(s);if(d)return ee in d?void 0:Z.object({...d,...i})}}}function sn(e){if(!S(e))return;let t={};for(let n of["intent","context"]){let r=e[n];typeof r=="string"&&r.trim()!==""&&(t[n]=r.trim())}return Object.keys(t).length>0?t:void 0}function an(e){if(!S(e)||!(ee in e))return{input:e,telemetry:void 0};let{[ee]:t,...n}=e;return{input:n,telemetry:sn(t)}}function cn(e){return sn(e)}function dn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ln(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(dn(e.requestInfo)){let t=e.requestInfo.headers;if(dn(t)){let n={};for(let i of Object.keys(t))n[i.toLowerCase()]=t[i];let r=n["mcp-session-id"];if(typeof r=="string"&&r)return r;let o=n["x-waniwani-session-id"];if(typeof o=="string"&&o)return o}}}var fn=Symbol.for("waniwani.wrappedHandler"),Ie=z("mcp"),gn="https://app.waniwani.ai",eo="REDACTED";function to(e){if(!e)return;let t=e[me];if(!Array.isArray(t)||t.length===0)return;let n=new Set(t.filter(r=>typeof r=="string"));if(n.size!==0)return r=>{if(!S(r))return r;let o=r.stateUpdates;if(!S(o))return r;let i=!1,s={...o};for(let a of n)a in s&&(s[a]=eo,i=!0);return i?{...r,stateUpdates:s}:r}}function un(e,t,n,r){let o=r.telemetryCapture;if(!o?.appliesTo(e))return;if(S(n?._flowGraph))return{plan:{kind:"flow"}};let i=o.augment(t);if(i!==void 0)return{plan:{kind:"injected",schemaWasAbsent:t==null},schema:i}}function pn(e,t,n,r,o){let{server:i,tracker:s,opts:a,tokenCache:d,injectToken:c}=n,l=a.applyFieldRedactions===!0?to(r):void 0,u=o?.kind==="injected"&&o.schemaWasAbsent?(R,p)=>t(p===void 0?R:p):t,w=async(R,p)=>{let x={...a,funnelSync:n.funnelSync,...l&&{redactInput:l}},{input:T,telemetry:_}=o?.kind==="injected"?an(R):{input:R,telemetry:o?.kind==="flow"?cn(R):void 0},h=Q(p)??{},f=i.server?.getClientVersion?.();if(!W(h)&&S(p)){let I=ln(p);I&&(h["waniwani/sessionId"]=I,p._meta=h)}if(!D(h)&&S(p)){let I=p.requestInfo?.headers,C=D(h,f)??ut(I);C&&(h["waniwani/source"]=C,p._meta=h)}let b=pt(s,h,{apiUrl:s._config.apiUrl,apiKey:s._config.apiKey});S(p)&&(p[pe]=b);let k={searches:[]},v=performance.now();try{let I=await Me.run(k,()=>u(T,p)),C=Math.round(performance.now()-v);Ie(`tool "${e}" handler returned in ${C}ms, running post-processing...`);let F=S(I)&&I.isError===!0;if(F){let B=De(I);console.error(`[waniwani] Tool "${e}" returned error${B?`: ${B}`:""}`)}return await Ke(s,je(e,p,x,{durationMs:C,status:F?"error":"ok",...F&&{errorMessage:De(I)??"Unknown tool error"}},f,{input:T,output:I,telemetry:_},k.searches),a.onError),Ie(`tool "${e}" tracking done`),a.flushAfterToolCall&&await Le(s,a.onError),tn(I,p),en(I,r),c&&(await Qt(I,d,s._config.apiUrl??gn,p,a.onError,f),Ie(`tool "${e}" widget config injected`)),Ie(`tool "${e}" post-processing complete, returning result`),I}catch(I){let C=Math.round(performance.now()-v);throw await Ke(s,je(e,p,x,{durationMs:C,status:"error",errorMessage:I instanceof Error?I.message:String(I),cause:j({error:I})},f,{input:T,telemetry:_},k.searches),a.onError),a.flushAfterToolCall&&await Le(s,a.onError),I}};return w[fn]=!0,w}async function no(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??Te(),i=r.injectWidgetToken!==!1,s=o._config.apiKey?new Se({apiUrl:o._config.apiUrl??gn,apiKey:o._config.apiKey}):null,a={server:e,tracker:o,opts:r,tokenCache:s,injectToken:i,funnelSync:null,telemetryCapture:on(r.captureTelemetry)},d=e.registerTool.bind(e);n.registerTool=((...l)=>{let[u,w,R]=l;if(typeof R!="function")return d(...l);let p=typeof u=="string"&&u.trim().length>0?u:"unknown",x=S(w)&&S(w._meta)?w._meta:void 0,T=S(w)?un(p,w.inputSchema,x,a):void 0,_=pn(p,R,a,x,T?.plan),h=T?.schema!==void 0?{...w,inputSchema:T.schema}:w;return d(u,h,_)});let c=e._registeredTools;if(S(c))for(let[l,u]of Object.entries(c)){if(!S(u))continue;let w=u.handler;if(typeof w!="function"||w[fn])continue;let R=S(u._meta)?u._meta:void 0,p=un(l,u.inputSchema,R,a);p?.schema!==void 0&&(u.inputSchema=p.schema),u.handler=pn(l,w,a,R,p?.plan)}if(o._config.apiKey){let l=e._registeredTools,u=[];if(l&&typeof l=="object"){for(let w of Object.values(l))if(w&&typeof w=="object"){let R=w._meta,p=R&&typeof R=="object"?R._flowGraph:void 0;p?.nodes?.length&&u.push(p)}}u.length>0&&(a.funnelSync=await Gt(u))}return n}export{N as END,ge as MemoryKvStore,pe as SCOPED_CLIENT_KEY,P as START,Y as StateGraph,H as WaniwaniKvStore,Tn as autoHeightFromMeta,Ut as createFlow,Dt as createFlowTestHarness,$r as createTrackingRoute,Ye as createWebMcpBridge,Re as extractScopedClient,Sn as isDisplayTool,Ge as readWidgetStep,Pt as redacted,Ve as resourceUriFromMeta,Ze as rewriteForAgent,He as supportsWebMcp,qe as viewUriFor,no as withWaniwani};
6
+ This tool runs a multi-step flow. Each call returns the flow's current status, the data for that step, and a \`nextStep\` field describing what the following call contains.`,a=e.store??Tr(t.id),d=Et(t),c=new Map;async function u(p,x,T,_,h){let f=(y,b,k)=>yt(y,b,n,r,c,_,h,e.nodeOptions,t.state).then(v=>({...v,internal:k}));if(p.action==="start"){let y=typeof p.intent=="string"?p.intent.trim():void 0;if(p.intent=y||void 0,typeof p.context=="string"){let C=p.context.trim();p.context=C||void 0}let b=r.get(P);if(!b)return A({waniwani:h,code:"agent_failed",cause:"flow_dead_end",properties:{node:P}}),{content:{status:"error",error:"No start edge"}};let k=await Rt({store:a,sessionId:x,sessionIsPreexisting:T,seed:d}),v=pe(p.stateUpdates??{}),I=await $(b,v);return f(I,v,k)}if(p.action==="continue"){if(!x)return{content:{status:"error",error:"No session ID available for continue action."}};let y;try{y=await a.get(x)}catch(C){let F=C instanceof Error?C.message:String(C);return A({waniwani:h,code:"upstream_failed",cause:K({error:C})}),{content:{status:"error",error:`Failed to load flow state (session "${x}"): ${F}`}}}if(!y)return{content:{status:"error",error:`Flow state not found for session "${x}". The flow may have expired.`}};let b=y.state,k=y.step;if(!k)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let v=j(b,pe(p.stateUpdates??{})),I=y.internal??{};if(y.widgetId){let C=r.get(k);if(!C)return A({waniwani:h,code:"agent_failed",cause:"flow_dead_end",properties:{node:k}}),{content:{status:"error",error:`No edge from step "${k}"`}};let F=await $(C,v);return f(F,v,I)}return f(k,v,I)}if(p.action==="reset"){if(!x)return{content:{status:"error",error:"No session ID available for reset action."}};let y;try{y=await a.get(x)}catch(F){let B=F instanceof Error?F.message:String(F);return A({waniwani:h,code:"upstream_failed",cause:K({error:F})}),{content:{status:"error",error:`Failed to load flow state (session "${x}"): ${B}`}}}if(!y)return{content:{status:"error",error:`Flow state not found for session "${x}". The flow may have completed or expired. Use action "start" to begin a new flow.`}};if(!y.step)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};if(!p.stateUpdates||Object.keys(p.stateUpdates).length===0)return{content:{status:"error",error:'Missing "stateUpdates" for action "reset". Include the corrected field(s).'}};let b=r.get(P);if(!b)return A({waniwani:h,code:"agent_failed",cause:"flow_dead_end",properties:{node:P}}),{content:{status:"error",error:"No start edge"}};let k=y.state,v=j(k,pe(p.stateUpdates)),I=y.internal??{},C=await $(b,v);return f(C,v,I)}return{content:{status:"error",error:`Unknown action: "${p.action}"`}}}let l=Mt(t.state),w={title:t.title,description:s,inputSchema:o,outputSchema:Ae,annotations:t.annotations,_meta:{...l.length>0&&{[ge]:l},_flowGraph:i}},R=(async(p,x)=>{let T=x,_=T._meta??{},h=W(_),f=h??p.sessionId,y=!!f;!f&&p.action==="start"&&(f=crypto.randomUUID()),f&&!h&&(_["waniwani/sessionId"]=f);let b=Re(T),k=await u(p,f,y,_,b),v=!h&&f?{...k.content,sessionId:f}:k.content,{value:I,internal:C}=v.status==="error"?{value:void 0,internal:k.internal??{}}:bt(k.internal,"intro"),F=At({status:v.status,tool:"tool"in v?v.tool:void 0,interactive:"interactive"in v?v.interactive:void 0,hasIntro:!!I,echoSessionId:!h&&!!f}),B={...I?{intro:I}:{},...v,...F?{nextStep:F}:{}};if(_[Ee]={suggestions:v.status==="interrupt"?v.suggestions??[]:[]},f&&k.flowTokenContent){let wn=Ct(k.flowTokenContent,C);try{await a.set(f,wn)}catch(ee){let hn=ee instanceof Error?ee.message:String(ee);return A({waniwani:b,code:"upstream_failed",cause:K({error:ee}),properties:{node:k.flowTokenContent.step}}),{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${f}"): ${hn}`},null,2)}],_meta:_,isError:!0}}}let mn=[{type:"text",text:JSON.stringify(B,null,2)}];return k.nodesVisited?.length&&(_[q]={flowId:t.id,nodesVisited:k.nodesVisited}),{content:mn,structuredContent:B,_meta:_,...k.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:w,handler:R,async register(p){p.registerTool(t.id,w,R)},graph:e.graph,flowGraph:i}}function Ot(e,t){let n=["flowchart TD"];n.push(` ${P}((Start))`);for(let[r]of e)n.push(` ${r}[${r}]`);n.push(` ${N}((End))`);for(let[r,o]of t)if(o.type==="direct")n.push(` ${r} --> ${o.to}`);else for(let i of o.targets)n.push(` ${r} -.-> ${i}`);return n.join(`
7
+ `)}var Y=class{nodes=new Map;edges=new Map;nodeOptions=new Map;config;constructor(t){this.config=t}addNode(t,n,r){let o=typeof t=="string"?t:t.id,i=typeof t=="string"?n:t.run,s=typeof t=="string"?r?.label:t.label,a=typeof t=="string"?r?.hideFromFunnel:t.hideFromFunnel;if(o===P||o===N)throw new Error(`"${o}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(o))throw new Error(`Node "${o}" already exists`);return this.nodes.set(o,i),(s!==void 0||a!==void 0)&&this.nodeOptions.set(o,{label:s??o,hideFromFunnel:a}),this}addEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge. Use addConditionalEdge for branching.`);return this.edges.set(t,{type:"direct",to:n}),this}addConditionalEdge(t,n,r){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge.`);if(n.length===0)throw new Error(`Conditional edge from "${t}" must declare at least one target node in \`to\`.`);return this.edges.set(t,{type:"conditional",condition:r,targets:[...n]}),this}graph(){return Ot(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return Nt({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>Ot(n,r),nodeOptions:new Map(this.nodeOptions)})}validate(){if(!this.edges.has(P))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(P);if(t?.type==="direct"&&t.to!==N&&!this.nodes.has(t.to))throw new Error(`START edge references non-existent node: "${t.to}"`);for(let[n,r]of this.edges){if(n!==P&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(r.type==="direct"&&r.to!==N&&!this.nodes.has(r.to))throw new Error(`Edge from "${n}" references non-existent node: "${r.to}"`);if(r.type==="conditional"&&r.targets){for(let o of r.targets)if(o!==N&&!this.nodes.has(o))throw new Error(`Conditional edge from "${n}" declares non-existent target: "${o}"`)}}for(let[n]of this.nodes)if(!this.edges.has(n))throw new Error(`Node "${n}" has no outgoing edge. Add one with .addEdge("${n}", ...) or .addConditionalEdge("${n}", ...)`)}};function Ut(e){return new Y(e)}function We(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function Dt(e,t){let n=t?.stateStore,r=[],o=`test-session-${Math.random().toString(36).slice(2,10)}`,i={registerTool:(...c)=>{r.push(c)}};await e.register(i);let s=r[0]?.[2];if(!s)throw new Error(`Flow "${e.name}" did not register a handler`);let a={_meta:{sessionId:o}};async function d(c){return{...c,decodedState:n?await n.get(o):null}}return{async start(c,u,l){let w=await s({action:"start",intent:c,...l?{context:l}:{},...u?{stateUpdates:u}:{}},a);return d(We(w))},async continueWith(c){let u=await s({action:"continue",...c?{stateUpdates:c}:{}},a);return d(We(u))},async resetWith(c){let u=await s({action:"reset",stateUpdates:c},a);return d(We(u))},async lastState(){return n?n.get(o):null}}}import{AsyncLocalStorage as Sr}from"async_hooks";var Kt=globalThis,me=Kt.__waniwaniKbRetrievalStore;me||(me=new Sr,Kt.__waniwaniKbRetrievalStore=me);var Me=me;function jt(e){try{Me.getStore()?.searches.push(e)}catch{}}var kr="@waniwani/sdk";function Lt(e){let{apiUrl:t,apiKey:n}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function o(i,s,a){let d=r(),c=`${t.replace(/\/$/,"")}${s}`,u={Authorization:`Bearer ${d}`,"X-WaniWani-SDK":kr},l={method:i,headers:u};a!==void 0&&(u["Content-Type"]="application/json",l.body=JSON.stringify(a));let w=await fetch(c,l);if(!w.ok){let p=await w.text().catch(()=>"");throw new O(p||`KB API error: HTTP ${w.status}`,w.status)}return(await w.json()).data}return{async ingest(i){return o("POST","/api/mcp/kb/ingest",{files:i})},async search(i,s){let a=await o("POST","/api/mcp/kb/search",{query:i,...s});return jt({query:i,resultCount:a.length,results:a.map(d=>({source:d.source,heading:d.heading,score:d.score}))}),a},async sources(){return o("GET","/api/mcp/kb/sources")}}}import{existsSync as Ir,readFileSync as xr}from"fs";import{resolve as vr}from"path";var Er="waniwani.json",G;function Bt(){if(G!==void 0)return G;try{let e=vr(process.cwd(),Er);if(!Ir(e))return G=null,null;let t=xr(e,"utf-8");return G=JSON.parse(t),G}catch{return G=null,null}}var Rr="__waniwani_config__";function $t(){return globalThis[Rr]}var br="@waniwani/sdk";function he(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??Vt,o=Fr(e),i=we(e.meta),s=we(e.metadata),a=Ar(e,i),d=M(e.eventId)??r(),c=Pr(e.timestamp,n),u=M(e.source)??D(i)??t.source??br,l=Ne(e)?{...e}:void 0,w={...s};return Object.keys(i).length>0&&(w.meta=i),l&&(w.rawLegacy=l),{id:d,type:"mcp.event",name:o,source:u,timestamp:c,correlation:a,properties:Cr(e,o),metadata:w,rawLegacy:l}}function Vt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function Cr(e,t){if(!Ne(e))return we(e.properties);let n=_r(e,t),r=we(e.properties);return{...n,...r}}function _r(e,t){switch(t){case"tool.called":{let n={};return M(e.toolName)&&(n.name=e.toolName),M(e.toolType)&&(n.type=e.toolType),n}case"link.clicked":{let n={};return M(e.linkUrl)&&(n.url=e.linkUrl),n}default:return{}}}function Fr(e){return Ne(e)?e.eventType:e.event}function Ar(e,t){let n=M(e.requestId)??st(t),r=M(e.sessionId)??W(t),o=M(e.traceId)??at(t),i=M(e.externalUserId)??ce(t),s=M(e.visitorId)??de(t),a=M(e.correlationId)??ue(t)??n,d={};return r&&(d.sessionId=r),o&&(d.traceId=o),n&&(d.requestId=n),a&&(d.correlationId=a),i&&(d.externalUserId=i),s&&(d.visitorId=s),d}function Pr(e,t){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){let n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return t().toISOString()}function we(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function M(e){if(typeof e=="string"&&e.trim().length!==0)return e}function Ne(e){return"eventType"in e}var Wr="/api/mcp/events/v2/batch";var qt="@waniwani/sdk";var Mr=new Set([401,403]),Nr=new Set([408,425,429,500,502,503,504]),Or=(e,t)=>globalThis.fetch(e,t);function zt(e){return new Oe(e)}var Oe=class{endpointUrl;flushIntervalMs;maxBatchSize;maxBufferSize;maxRetries;retryBaseDelayMs;retryMaxDelayMs;shutdownTimeoutMs;sdkVersion;fetchFn;logger;now;sleep;apiKey;buffer=[];flushTimer;flushScheduled=!1;flushScheduledTimer;flushInFlight;inFlightCount=0;isStopped=!1;isShuttingDown=!1;constructor(t){this.endpointUrl=Kr(t.apiUrl,t.endpointPath??Wr),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??Or,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(r=>setTimeout(r,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs)),this.registerBrowserTeardown()}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[Waniwani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[Waniwani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,r=this.flush();if(!Number.isFinite(n)||n<=0)return await r,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let o=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(n).then(()=>o)])===o?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}registerBrowserTeardown(){if(typeof document>"u"||typeof window>"u")return;let t=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush()};document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",()=>this.keepaliveFlush())}keepaliveFlush(){if(this.isStopped||this.buffer.length===0)return;let t=this.buffer.splice(0,this.buffer.length);this.sendKeepaliveChunk(t)}sendKeepaliveChunk(t){let n=JSON.stringify(this.makeBatchRequest(t));if(n.length>6e4&&t.length>1){let r=Math.ceil(t.length/2);this.sendKeepaliveChunk(t.slice(0,r)),this.sendKeepaliveChunk(t.slice(r));return}try{this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:n,keepalive:!0}).catch(()=>{})}catch{}}requestHeaders(){let t={"Content-Type":"application/json","X-WaniWani-SDK":qt};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,r=t;for(;r.length>0&&!this.isStopped;){this.inFlightCount=r.length;let o=await this.sendBatchOnce(r);switch(this.inFlightCount=0,o.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(o.status,r.length);return;case"permanent":this.logger.error("[Waniwani] Dropping %d event(s) after permanent failure: %s",r.length,o.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d event(s) after retry exhaustion: %s",r.length,o.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(o.permanent.length>0&&this.logger.error("[Waniwani] Dropping %d event(s) rejected as permanent",o.permanent.length),o.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d retryable event(s) after retry exhaustion",o.retryable.length);return}r=o.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:jr(i)}}if(Mr.has(n.status))return{kind:"auth",status:n.status};if(Nr.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await Dr(n);if(!r?.rejected||r.rejected.length===0)return{kind:"success"};let o=this.classifyRejectedEvents(t,r.rejected);return o.retryable.length===0&&o.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:o.retryable,permanent:o.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:qt,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(s=>[s.id,s])),o=[],i=[];for(let s of n){let a=r.get(s.eventId);if(a){if(Ur(s)){o.push(a);continue}i.push(a)}}return{retryable:o,permanent:i}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let r=this.buffer.length;this.buffer.splice(0,r),this.logger.error("[Waniwani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+r)}};function Ur(e){if(e.retryable===!0)return!0;let t=e.code.toLowerCase();return t.includes("timeout")||t.includes("temporary")||t.includes("unavailable")||t.includes("rate_limit")||t.includes("transient")||t.includes("server")}async function Dr(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function Kr(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function jr(e){return e instanceof Error?e.message:String(e)}function Ht(e){let{apiUrl:t,apiKey:n,tracking:r}=e;function o(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}let i=n?zt({apiUrl:t,apiKey:n,endpointPath:r.endpointPath,flushIntervalMs:r.flushIntervalMs,maxBatchSize:r.maxBatchSize,maxBufferSize:r.maxBufferSize,maxRetries:r.maxRetries,retryBaseDelayMs:r.retryBaseDelayMs,retryMaxDelayMs:r.retryMaxDelayMs,shutdownTimeoutMs:r.shutdownTimeoutMs}):void 0;function s(u){o();let l=he(u);return!l.correlation.sessionId&&!l.correlation.externalUserId&&!l.correlation.visitorId&&console.warn(`[waniwani] event "${l.name}" has no sessionId, externalUserId, or visitorId; the ingest API requires one and will reject it.`),i?.enqueue(l),{eventId:l.id}}let a=async u=>s(u),d=Object.assign(a,oe(a)),c={async identify(u,l,w){o();let R=he({event:"user.identified",externalUserId:u,properties:l,meta:w});return i?.enqueue(R),{eventId:R.id}},track:d,async flush(){o(),await i?.flush()},async shutdown(u){return o(),await i?.shutdown({timeoutMs:u?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&Lr(c,r.shutdownTimeoutMs),c}function Lr(e,t){if(typeof process>"u"||typeof process.once!="function"||typeof process.on!="function")return;let n=()=>{e.shutdown({timeoutMs:t})};process.once("beforeExit",n),process.once("SIGINT",n),process.once("SIGTERM",n)}function ye(e){let n=e??Bt()??$t(),r=n?.apiUrl??process.env.WANIWANI_API_URL??ie,o=n?.apiKey??process.env.WANIWANI_API_KEY,i={endpointPath:n?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:n?.tracking?.flushIntervalMs??1e3,maxBatchSize:n?.tracking?.maxBatchSize??20,maxBufferSize:n?.tracking?.maxBufferSize??1e3,maxRetries:n?.tracking?.maxRetries??3,retryBaseDelayMs:n?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:n?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:n?.tracking?.shutdownTimeoutMs??2e3},s={apiUrl:r,apiKey:o,tracking:i},a=Ht(s),d=Lt(s),c=ne(s),u=re(s);return{...a,kb:d,documents:c,email:u,_config:s}}function Br(e){return{event:e.name??"widget_render",properties:e.properties,metadata:e.metadata,sessionId:e.correlation?.sessionId,traceId:e.correlation?.traceId,requestId:e.correlation?.requestId,correlationId:e.correlation?.correlationId,externalUserId:e.correlation?.externalUserId,visitorId:e.correlation?.visitorId,eventId:e.id,timestamp:e.timestamp,source:e.source}}function $r(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=ye(t)),n}return async function(i){let s;try{s=await i.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!Array.isArray(s.events)||s.events.length===0)return new Response(JSON.stringify({error:"Missing or empty events array"}),{status:400,headers:{"Content-Type":"application/json"}});try{let a=r(),d=[];for(let c of s.events){let u=await a.track(Br(c));d.push(u.eventId)}return await a.flush(),new Response(JSON.stringify({ok:!0,accepted:d.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(a){let d=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({error:d}),{status:500,headers:{"Content-Type":"application/json"}})}}}var Ue=z("widget-token"),Vr=120*1e3,Te=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-Vr?this.cached.token:this.pending?this.pending:(this.pending=this.mint(t,n).finally(()=>{this.pending=null}),this.pending)}async mint(t,n){let r=qr(this.config.apiUrl,"/api/mcp/widget-tokens");Ue("minting token from",r);let o={};t&&(o.sessionId=t),n&&(o.traceId=n);try{let i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)});if(Ue("mint response:",i.status),!i.ok)return null;let s=await i.json(),a=s.data&&typeof s.data=="object"?s.data:s,d=new Date(a.expiresAt).getTime();return!a.token||Number.isNaN(d)?null:(this.cached={token:a.token,expiresAt:d},a.token)}catch(i){return Ue("mint failed:",i),null}}};function qr(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function Yt(e){if(typeof globalThis.crypto?.subtle?.digest=="function"){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return`simple-${Math.abs(t).toString(36)}`}function zr(e){return Yt(JSON.stringify({nodes:e.nodes,edges:e.edges}))}async function Gt(e){if(e.length===0)return null;let t=[...e].sort((o,i)=>o.flowId.localeCompare(i.flowId)),n=await Yt(JSON.stringify(t.map(o=>({flowId:o.flowId,nodes:o.nodes,edges:o.edges})))),r=await Promise.all(e.map(async o=>({flowId:o.flowId,title:o.title,configHash:await zr(o),nodes:o.nodes,edges:o.edges})));return{compositeHash:n,flows:r}}var Zt="waniwani/sessionId",Se="waniwani/geoLocation",ke="waniwani/userLocation",Hr="openai/userLocation",Yr=[Hr,Se,ke];function Jt(e,t){if(t.length===0)return e;let n;for(let r of Yr){let o=e[r];if(!S(o))continue;let i;for(let s of t)s in o&&(i||(i={...o}),delete i[s]);i&&(n||(n={...e}),n[r]=i)}return n??e}function S(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function X(e){if(!S(e))return;let t=e._meta;return S(t)?t:void 0}function De(e){if(!S(e))return;let t=e.content;return Array.isArray(t)?t.find(r=>S(r)&&r.type==="text"&&typeof r.text=="string")?.text:void 0}function Gr(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function Ke(e,t,n,r,o,i,s){let a=Gr(e,n.toolType),d=n.stripLocationFields,c=d&&d.length>0,u=X(t),l=u&&c?Jt(u,d):u,w=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,R=c&&S(i?.output)&&S(i.output._meta)?{...i.output,_meta:Jt(i.output._meta,d)}:i?.output,x=(S(i?.output)&&S(i.output._meta)?i.output._meta:void 0)?.[q],T=x&&l?{...l,[q]:x}:x?{[q]:x}:l,_=S(i?.input)&&typeof i.input.sessionId=="string"&&i.input.sessionId.length>0?i.input.sessionId:void 0,h=_&&!W(T??void 0)?{...T??{},"waniwani/sessionId":_}:T;return{event:"tool.called",properties:{name:e,type:a,...r??{},...w!==void 0&&{input:w},...i?.telemetry&&{telemetry:i.telemetry},...R!==void 0&&{output:R},...s&&s.length>0&&{kbSearch:s}},meta:h,source:D(h??l,o),metadata:{...n.metadata??{},...o&&{clientInfo:o},...n.funnelSync&&{funnelSync:n.funnelSync}}}}async function je(e,t,n){try{await e.track(t)}catch(r){n?.(Be(r))}}async function Le(e,t){try{await e.flush()}catch(n){t?.(Be(n))}}async function Qt(e,t,n,r,o,i){if(!S(e))return;S(e._meta)||(e._meta={});let s=e._meta,a=S(s[ae])?s[ae]:void 0,d={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let w=await t.getToken();w&&(d.token=w)}catch(w){o?.(Be(w))}let c=W(s);c&&(d.sessionId||(d.sessionId=c));let u=nn(s);u!==void 0&&(d.geoLocation||(d.geoLocation=u));let l=D(X(r),i);l&&!d.source&&(d.source=l),s[ae]=d}var Xt=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function en(e,t){if(!t||!S(e))return;let n=!1;for(let o of Xt)if(o in t){n=!0;break}if(!n)return;S(e._meta)||(e._meta={});let r=e._meta;for(let o of Xt)o in t&&(o in r||(r[o]=t[o]))}function tn(e,t){let n=X(t);if(!n||!S(e))return;S(e._meta)||(e._meta={});let r=e._meta,o=W(n);o&&!r[Zt]&&(r[Zt]=o);let i=nn(n);i&&(r[Se]||(r[Se]=i),r[ke]||(r[ke]=i))}function nn(e){if(!e)return;let t=e[Se]??e[ke];if(S(t)||typeof t=="string")return t}function Be(e){return e instanceof Error?e:new Error(String(e))}import{z as Ie}from"zod";var Q="intent";function Zr(e){return`Brief summary of what the user wants and what prompted it, in their words. Send only on your first call to this app.${e?se:""}`}function rn(e){return S(e)&&"_zod"in e}function Jr(e){return S(e)&&("~standard"in e||"_def"in e)}function Xr(e){if(!rn(e))return null;let t=e;return S(t.shape)?t:null}function Qr(e){return!S(e)||Jr(e)||!Object.values(e).every(rn)?null:e}function on(e){if(e===!1)return null;let t=e===!0||e===void 0?{}:e,n=t.tools&&t.tools.length>0?new Set(t.tools):void 0,r=Ie.string().optional().catch(void 0).describe(Zr(t.omitPII)),o={[Q]:r};return{appliesTo:i=>n===void 0||n.has(i),augment:i=>{if(i==null)return Ie.object(o);let s=Xr(i);if(s){if(Q in s.shape)return;try{return typeof s.safeExtend=="function"?s.safeExtend(o):typeof s.extend=="function"?s.extend(o):Ie.object({...s.shape,...o})}catch{return}}let a=Qr(i);if(a)return Q in a?void 0:Ie.object({...a,...o})}}}function sn(e){if(!S(e))return;let t={};for(let n of["intent","context"]){let r=e[n];typeof r=="string"&&r.trim()!==""&&(t[n]=r.trim())}return Object.keys(t).length>0?t:void 0}function an(e){if(!S(e)||!(Q in e))return{input:e,telemetry:void 0};let{[Q]:t,...n}=e;return{input:n,telemetry:sn({intent:t})}}function cn(e){return sn(e)}function dn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function un(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(dn(e.requestInfo)){let t=e.requestInfo.headers;if(dn(t)){let n={};for(let i of Object.keys(t))n[i.toLowerCase()]=t[i];let r=n["mcp-session-id"];if(typeof r=="string"&&r)return r;let o=n["x-waniwani-session-id"];if(typeof o=="string"&&o)return o}}}var fn=Symbol.for("waniwani.wrappedHandler"),xe=z("mcp"),gn="https://app.waniwani.ai",eo="REDACTED";function to(e){if(!e)return;let t=e[ge];if(!Array.isArray(t)||t.length===0)return;let n=new Set(t.filter(r=>typeof r=="string"));if(n.size!==0)return r=>{if(!S(r))return r;let o=r.stateUpdates;if(!S(o))return r;let i=!1,s={...o};for(let a of n)a in s&&(s[a]=eo,i=!0);return i?{...r,stateUpdates:s}:r}}function ln(e,t,n,r){let o=r.intentCapture;if(!o?.appliesTo(e))return;if(S(n?._flowGraph))return{plan:{kind:"flow"}};let i=o.augment(t);if(i!==void 0)return{plan:{kind:"injected",schemaWasAbsent:t==null},schema:i}}function pn(e,t,n,r,o){let{server:i,tracker:s,opts:a,tokenCache:d,injectToken:c}=n,u=a.applyFieldRedactions===!0?to(r):void 0,l=o?.kind==="injected"&&o.schemaWasAbsent?(R,p)=>t(p===void 0?R:p):t,w=async(R,p)=>{let x={...a,funnelSync:n.funnelSync,...u&&{redactInput:u}},{input:T,telemetry:_}=o?.kind==="injected"?an(R):{input:R,telemetry:o?.kind==="flow"?cn(R):void 0},h=X(p)??{},f=i.server?.getClientVersion?.();if(!W(h)&&S(p)){let I=un(p);I&&(h["waniwani/sessionId"]=I,p._meta=h)}if(!D(h)&&S(p)){let I=p.requestInfo?.headers,C=D(h,f)??lt(I);C&&(h["waniwani/source"]=C,p._meta=h)}let b=pt(s,h,{apiUrl:s._config.apiUrl,apiKey:s._config.apiKey});S(p)&&(p[le]=b);let k={searches:[]},v=performance.now();try{let I=await Me.run(k,()=>l(T,p)),C=Math.round(performance.now()-v);xe(`tool "${e}" handler returned in ${C}ms, running post-processing...`);let F=S(I)&&I.isError===!0;if(F){let B=De(I);console.error(`[waniwani] Tool "${e}" returned error${B?`: ${B}`:""}`)}return await je(s,Ke(e,p,x,{durationMs:C,status:F?"error":"ok",...F&&{errorMessage:De(I)??"Unknown tool error"}},f,{input:T,output:I,telemetry:_},k.searches),a.onError),xe(`tool "${e}" tracking done`),a.flushAfterToolCall&&await Le(s,a.onError),tn(I,p),en(I,r),c&&(await Qt(I,d,s._config.apiUrl??gn,p,a.onError,f),xe(`tool "${e}" widget config injected`)),xe(`tool "${e}" post-processing complete, returning result`),I}catch(I){let C=Math.round(performance.now()-v);throw await je(s,Ke(e,p,x,{durationMs:C,status:"error",errorMessage:I instanceof Error?I.message:String(I),cause:K({error:I})},f,{input:T,telemetry:_},k.searches),a.onError),a.flushAfterToolCall&&await Le(s,a.onError),I}};return w[fn]=!0,w}async function no(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??ye(),i=r.injectWidgetToken!==!1,s=o._config.apiKey?new Te({apiUrl:o._config.apiUrl??gn,apiKey:o._config.apiKey}):null,a={server:e,tracker:o,opts:r,tokenCache:s,injectToken:i,funnelSync:null,intentCapture:on(r.captureIntent)},d=e.registerTool.bind(e);n.registerTool=((...u)=>{let[l,w,R]=u;if(typeof R!="function")return d(...u);let p=typeof l=="string"&&l.trim().length>0?l:"unknown",x=S(w)&&S(w._meta)?w._meta:void 0,T=S(w)?ln(p,w.inputSchema,x,a):void 0,_=pn(p,R,a,x,T?.plan),h=T?.schema!==void 0?{...w,inputSchema:T.schema}:w;return d(l,h,_)});let c=e._registeredTools;if(S(c))for(let[u,l]of Object.entries(c)){if(!S(l))continue;let w=l.handler;if(typeof w!="function"||w[fn])continue;let R=S(l._meta)?l._meta:void 0,p=ln(u,l.inputSchema,R,a);p?.schema!==void 0&&(l.inputSchema=p.schema),l.handler=pn(u,w,a,R,p?.plan)}if(o._config.apiKey){let u=e._registeredTools,l=[];if(u&&typeof u=="object"){for(let w of Object.values(u))if(w&&typeof w=="object"){let R=w._meta,p=R&&typeof R=="object"?R._flowGraph:void 0;p?.nodes?.length&&l.push(p)}}l.length>0&&(a.funnelSync=await Gt(l))}return n}export{N as END,fe as MemoryKvStore,le as SCOPED_CLIENT_KEY,P as START,Y as StateGraph,H as WaniwaniKvStore,Tn as autoHeightFromMeta,Ut as createFlow,Dt as createFlowTestHarness,$r as createTrackingRoute,Ye as createWebMcpBridge,Re as extractScopedClient,Sn as isDisplayTool,Ge as readWidgetStep,Pt as redacted,Ve as resourceUriFromMeta,Ze as rewriteForAgent,He as supportsWebMcp,qe as viewUriFor,no as withWaniwani};
8
8
  //# sourceMappingURL=index.js.map