@waniwani/sdk 0.21.3 → 0.21.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp/index.js CHANGED
@@ -1,8 +1,8 @@
1
- function an(e){if(!(typeof e!="object"||e===null))return e}function De(e){return an(e?.ui)}function Ke(e){if(!e)return;let t=De(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 cn(e){return De(e)?.autoHeight===!0}function je(e){return Ke(e?._meta)}function dn(e){return je(e)!==void 0}function Le(){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 Be(){return Le()!==null}function un(){return{url:location.href,title:document.title}}async function $e(e){let{endpoint:t,headers:n,sessionId:r,visitorId:o,channelId:i,onWidget:s}=e,a=e.logger??console,d=Le();if(!d)return null;let c=new AbortController,u=()=>c.abort();window.addEventListener("pagehide",u);let l=!1,p=()=>{l||(l=!0,window.removeEventListener("pagehide",u),c.abort())};function R(){return{sessionId:r,visitorId:o,channelId:i,page:un()}}async function m(S,y){let k=await fetch(t,{method:"POST",headers:{"content-type":"application/json",...n},body:JSON.stringify(S),...y?{signal:y}:{}});if(!k.ok)throw new Error(`webmcp ${S.action} failed: ${k.status}`);return await k.json()}let T=[];try{T=(await m({...R(),action:"list"}))?.tools??[]}catch(S){return a.error("[webmcp] could not list site tools",S),p(),null}let h=[];return await Promise.all(T.map(async S=>{try{await d.registerTool({name:S.name,description:S.description??"",...S.inputSchema?{inputSchema:S.inputSchema}:{},...S.annotations?{annotations:S.annotations}:{},execute:async(y,k)=>{let f=await m({...R(),action:"call",name:S.name,arguments:y??{}},k?.signal);return f?.widget&&s?.(f.widget),{content:f?.content??[]}}},{signal:c.signal}),h.push(S)}catch(y){a.error(`[webmcp] could not register ${S.name}`,y)}})),a.info(`[webmcp] registered ${h.length} site tool(s)`),{get tools(){return h},dispose:p}}function Ve(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 ln='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".',pn='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".',fn="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 qe(e,t){let{tool:n,description:r,...o}=e.payload;return{...o,status:t?"widget_shown":"widget_unavailable",instructions:t?e.interactive?ln:pn:fn}}var A="__start__",N="__end__",He=Symbol.for("waniwani.flow.interrupt"),ze=Symbol.for("waniwani.flow.widget");function Ye(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:He,questions:r,context:n}}function Ge(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:ze,tool:typeof r=="string"?r:r.id,...i!==void 0?{data:i}:{},...s!==void 0?{interactive:s}:{},...a!==void 0?{field:a}:{}}}function Ze(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===He}function Je(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===ze}import{z as j}from"zod";var B=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var gn="@waniwani/sdk",wn="/api/mcp/modules/documents/extract";function mn(e,t){try{let n=JSON.parse(e);if(n!==null&&typeof n=="object"){let r="message"in n&&typeof n.message=="string"?n.message:"",o="detail"in n&&typeof n.detail=="string"?n.detail:"";if(r&&o)return`${r}: ${o}`;if(r)return r;if(o)return o}}catch{}return e||`Documents API error: HTTP ${t}`}function hn(e){return"documentId"in e&&typeof e.documentId=="string"}function yn(e){return hn(e)?{documentId:e.documentId}:{url:e.url,filename:e.filename}}function ee(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(/\/$/,"")}${wn}`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-WaniWani-SDK":gn},body:JSON.stringify({...yn(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 B(mn(l,i.status),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}}}}function te(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 ne="https://app.waniwani.ai";var Tn=["documentId","document_id"],Sn=["filename","file_name","fileName","name"],kn=["mediaType","media_type","mimeType","mime_type","contentType","content_type"],vn="document",xn="application/octet-stream";function $(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Te(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function In(e){if(!$(e))return;let t=Te(e,Tn);if(t)return{documentId:t,filename:Te(e,Sn)??vn,mediaType:Te(e,kn)??xn}}function Xe(e){let t=[],n=new Set;for(let r of Array.isArray(e)?e:[e]){let o=In(r);o&&!n.has(o.documentId)&&(n.add(o.documentId),t.push(o))}return t}function En(e){if(!Array.isArray(e))return[];let t=[...e].reverse().find(n=>$(n)&&n.role==="user");return!$(t)||!Array.isArray(t.parts)?[]:Xe(t.parts.flatMap(n=>$(n)&&$(n.data)?[n,n.data]:[n]))}function Qe(e){let t=$(e)?e:void 0,n=Xe(t?t.documents:e);return n.length>0?n:En(t?t.messages:e)}var Se="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 Rn=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],bn=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Cn=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],_n=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],Fn=["waniwani/visitorId","visitorId"],An=["correlationId","openai/requestId"];var Wn=["waniwani/fileParams","openai/fileParams"],Pn=["url","uri","download_url","downloadUrl","file_url","fileUrl","signed_url","signedUrl"],Mn=["filename","file_name","fileName","name"],V="waniwani/flow",re="waniwani/widget";function P(e){return e?U(e,Rn):void 0}function tt(e){return e?U(e,bn):void 0}function nt(e){return e?U(e,Cn):void 0}function oe(e){return e?U(e,_n):void 0}function ie(e){return e?U(e,Fn):void 0}function se(e){return e?U(e,An):void 0}function rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nn(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 Un(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 On(e){if(!rt(e))return;let t=Nn(U(e,Pn));if(!t)return;let n=U(e,Mn);return{url:t,filename:n??Un(t)}}function ot(e){if(!e)return[];for(let t of Wn){let n=Dn(e[t]);if(n.length>0)return n}return[]}function Dn(e){let t=[],n=new Set,r=o=>{if(Array.isArray(o)){for(let s of o)r(s);return}let i=On(o);if(i){n.has(i.url)||(n.add(i.url),t.push(i));return}if(rt(o))for(let s of Object.values(o))r(s)};return r(e),t}var Kn="waniwani/documents";function it(e){if(!e)return[];let t=e[Kn];return Qe(Array.isArray(t)?t:[t])}var jn=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],Ln=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function O(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 jn){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 Ln)if(r.includes(o))return i}}function et(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 st(e){if(!e)return;let t=et(e,"user-agent"),n=et(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 ae="waniwani/client";function ke(e){if(typeof e=="object"&&e!==null)return e[ae]}function at(e,t,n){let r=a=>e.track({...a,meta:{...t,...a.meta}}),o=P(t),i=se(t),s=ee({apiUrl:n?.apiUrl??process.env.WANIWANI_API_URL??ne,apiKey:n?.apiKey});return{sessionId:o,visitorId:ie(t),externalUserId:oe(t),track:Object.assign(r,te(r)),identify(a,d){return e.identify(a,d,t)},kb:e.kb,attachedFiles:ot(t),attachedDocuments:it(t),documents:{extract(a){return s.extract({...a,sessionId:a.sessionId??o,correlationId:a.correlationId??i})}},_config:n}}import{z as ve}from"zod";var Bn=ve.object({status:ve.number().optional(),statusCode:ve.number().optional()});function $n(e){let t=Bn.safeParse(e);if(t.success)return t.data.status??t.data.statusCode}var Vn=["fetch failed","failed to fetch","networkerror when attempting to fetch"];function D({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=$n(e);return t===429?"rate_limited":t!==void 0&&t>=500?"upstream_5xx":t!==void 0&&t>=400?"upstream_4xx":e instanceof TypeError&&Vn.some(n=>e.message.toLowerCase().includes(n))?"network":"unknown"}function F({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 ct(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function G(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 qn(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 dt(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 ce(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?qn(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 lt(e){return e._zod?.def}function Hn(e){let t=e,n=!1;for(let r=0;r<8;r++){let o=lt(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 ut(e){let{inner:t,optional:n}=Hn(e),r=t.description??e.description??void 0,o=lt(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 xe(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=ct(s)?.[i];return d?ut(d):void 0}let n=e[t];if(n)return ut(n)}function Ie(e){return e!=null&&e!==""}async function L(e,t){return e.type==="direct"?e.to:e.condition(t)}function pt(e,t,n,r,o){if(e.every(c=>Ie(G(r,c.field))))return null;let i=e.filter(c=>!Ie(G(r,c.field))).map(c=>{let u=xe(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 ft(e,t,n,r,o,i,s,a,d){let c=e,u={...t},l=[],p=50,R=0;for(;R++<p;){if(c===N)return{content:{status:"complete"},flowTokenContent:{state:u},nodesVisited:l};let m=n.get(c);if(!m)return F({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 h=await m({state:u,meta:i,interrupt:Ye,showWidget:Ge,waniwani:s});if(Ze(h)){for(let f of h.questions)f.validate&&o.set(`${c}:${f.field}`,f.validate);let y=pt(h.questions,h.context,c,u,d);if(y)return{...y,nodesVisited:l};for(let f of h.questions){let b=o.get(`${c}:${f.field}`);if(b)try{let v=G(u,f.field),x=await b(v);x&&typeof x=="object"&&(u=K(u,x))}catch(v){let x=v instanceof Error?v.message:String(v);dt(u,f.field);let W=h.questions.map(C=>C.field===f.field?{...C,context:C.context?`ERROR: ${x}
1
+ function dn(e){if(!(typeof e!="object"||e===null))return e}function je(e){return dn(e?.ui)}function Le(e){if(!e)return;let t=je(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 ln(e){return je(e)?.autoHeight===!0}function Be(e){return Le(e?._meta)}function un(e){return Be(e)!==void 0}function $e(){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 Ve(){return $e()!==null}function pn(){return{url:location.href,title:document.title}}async function qe(e){let{endpoint:t,headers:n,sessionId:r,visitorId:o,channelId:i,onWidget:s}=e,a=e.logger??console,d=$e();if(!d)return null;let c=new AbortController,l=()=>c.abort();window.addEventListener("pagehide",l);let u=!1,p=()=>{u||(u=!0,window.removeEventListener("pagehide",l),c.abort())};function R(){return{sessionId:r,visitorId:o,channelId:i,page:pn()}}async function w(S,y){let k=await fetch(t,{method:"POST",headers:{"content-type":"application/json",...n},body:JSON.stringify(S),...y?{signal:y}:{}});if(!k.ok)throw new Error(`webmcp ${S.action} failed: ${k.status}`);return await k.json()}let T=[];try{T=(await w({...R(),action:"list"}))?.tools??[]}catch(S){return a.error("[webmcp] could not list site tools",S),p(),null}let h=[];return await Promise.all(T.map(async S=>{try{await d.registerTool({name:S.name,description:S.description??"",...S.inputSchema?{inputSchema:S.inputSchema}:{},...S.annotations?{annotations:S.annotations}:{},execute:async(y,k)=>{let f=await w({...R(),action:"call",name:S.name,arguments:y??{}},k?.signal);return f?.widget&&s?.(f.widget),{content:f?.content??[]}}},{signal:c.signal}),h.push(S)}catch(y){a.error(`[webmcp] could not register ${S.name}`,y)}})),a.info(`[webmcp] registered ${h.length} site tool(s)`),{get tools(){return h},dispose:p}}function He(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 fn='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".',gn='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".',mn="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?fn:gn:mn}}var A="__start__",N="__end__",Ye=Symbol.for("waniwani.flow.interrupt"),Ge=Symbol.for("waniwani.flow.widget");function Ze(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:Ye,questions:r,context:n}}function Je(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:Ge,tool:typeof r=="string"?r:r.id,...i!==void 0?{data:i}:{},...s!==void 0?{interactive:s}:{},...a!==void 0?{field:a}:{}}}function Xe(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Ye}function Qe(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Ge}import{z as L}from"zod";var U=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};function ee(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 wn="@waniwani/sdk",hn="/api/mcp/modules/documents/extract";function yn(e){return"documentId"in e&&typeof e.documentId=="string"}function Tn(e){return yn(e)?{documentId:e.documentId}:{url:e.url,filename:e.filename}}function te(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(/\/$/,"")}${hn}`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-WaniWani-SDK":wn},body:JSON.stringify({...Tn(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 U(ee(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 Sn="@waniwani/sdk",kn="/api/mcp/modules/email/send";function ne(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(/\/$/,"")}${kn}`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-WaniWani-SDK":Sn},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 U(ee(s,o.status,"Email API"),o.status)}return{id:(await o.json()).data.id}}}}function re(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 oe="https://app.waniwani.ai";var vn=["documentId","document_id"],xn=["filename","file_name","fileName","name"],In=["mediaType","media_type","mimeType","mime_type","contentType","content_type"],En="document",Rn="application/octet-stream";function $(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ke(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function bn(e){if(!$(e))return;let t=ke(e,vn);if(t)return{documentId:t,filename:ke(e,xn)??En,mediaType:ke(e,In)??Rn}}function et(e){let t=[],n=new Set;for(let r of Array.isArray(e)?e:[e]){let o=bn(r);o&&!n.has(o.documentId)&&(n.add(o.documentId),t.push(o))}return t}function Cn(e){if(!Array.isArray(e))return[];let t=[...e].reverse().find(n=>$(n)&&n.role==="user");return!$(t)||!Array.isArray(t.parts)?[]:et(t.parts.flatMap(n=>$(n)&&$(n.data)?[n,n.data]:[n]))}function tt(e){let t=$(e)?e:void 0,n=et(t?t.documents:e);return n.length>0?n:Cn(t?t.messages:e)}var ve="waniwani/suggestions";function O(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var _n=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],Fn=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],An=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],Pn=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],Wn=["waniwani/visitorId","visitorId"],Mn=["correlationId","openai/requestId"];var Nn=["waniwani/fileParams","openai/fileParams"],Un=["url","uri","download_url","downloadUrl","file_url","fileUrl","signed_url","signedUrl"],On=["filename","file_name","fileName","name"],V="waniwani/flow",ie="waniwani/widget";function W(e){return e?O(e,_n):void 0}function rt(e){return e?O(e,Fn):void 0}function ot(e){return e?O(e,An):void 0}function se(e){return e?O(e,Pn):void 0}function ae(e){return e?O(e,Wn):void 0}function ce(e){return e?O(e,Mn):void 0}function it(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dn(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 Kn(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 jn(e){if(!it(e))return;let t=Dn(O(e,Un));if(!t)return;let n=O(e,On);return{url:t,filename:n??Kn(t)}}function st(e){if(!e)return[];for(let t of Nn){let n=Ln(e[t]);if(n.length>0)return n}return[]}function Ln(e){let t=[],n=new Set,r=o=>{if(Array.isArray(o)){for(let s of o)r(s);return}let i=jn(o);if(i){n.has(i.url)||(n.add(i.url),t.push(i));return}if(it(o))for(let s of Object.values(o))r(s)};return r(e),t}var Bn="waniwani/documents";function at(e){if(!e)return[];let t=e[Bn];return tt(Array.isArray(t)?t:[t])}var $n=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],Vn=[{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 $n){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 Vn)if(r.includes(o))return i}}function nt(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 ct(e){if(!e)return;let t=nt(e,"user-agent"),n=nt(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 de="waniwani/client";function xe(e){if(typeof e=="object"&&e!==null)return e[de]}function dt(e,t,n){let r=c=>e.track({...c,meta:{...t,...c.meta}}),o=W(t),i=ce(t),s={apiUrl:n?.apiUrl??process.env.WANIWANI_API_URL??oe,apiKey:n?.apiKey},a=te(s),d=ne(s);return{sessionId:o,visitorId:ae(t),externalUserId:se(t),track:Object.assign(r,re(r)),identify(c,l){return e.identify(c,l,t)},kb:e.kb,attachedFiles:st(t),attachedDocuments:at(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 Ie}from"zod";var qn=Ie.object({status:Ie.number().optional(),statusCode:Ie.number().optional()});function Hn(e){let t=qn.safeParse(e);if(t.success)return t.data.status??t.data.statusCode}var zn=["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=Hn(e);return t===429?"rate_limited":t!==void 0&&t>=500?"upstream_5xx":t!==void 0&&t>=400?"upstream_4xx":e instanceof TypeError&&zn.some(n=>e.message.toLowerCase().includes(n))?"network":"unknown"}function F({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 lt(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function G(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 Yn(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 ut(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 le(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?Yn(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 ft(e){return e._zod?.def}function Gn(e){let t=e,n=!1;for(let r=0;r<8;r++){let o=ft(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 pt(e){let{inner:t,optional:n}=Gn(e),r=t.description??e.description??void 0,o=ft(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 Ee(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=lt(s)?.[i];return d?pt(d):void 0}let n=e[t];if(n)return pt(n)}function Re(e){return e!=null&&e!==""}async function B(e,t){return e.type==="direct"?e.to:e.condition(t)}function gt(e,t,n,r,o){if(e.every(c=>Re(G(r,c.field))))return null;let i=e.filter(c=>!Re(G(r,c.field))).map(c=>{let l=Ee(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 mt(e,t,n,r,o,i,s,a,d){let c=e,l={...t},u=[],p=50,R=0;for(;R++<p;){if(c===N)return{content:{status:"complete"},flowTokenContent:{state:l},nodesVisited:u};let w=n.get(c);if(!w)return F({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 h=await w({state:l,meta:i,interrupt:Ze,showWidget:Je,waniwani:s});if(Xe(h)){for(let f of h.questions)f.validate&&o.set(`${c}:${f.field}`,f.validate);let y=gt(h.questions,h.context,c,l,d);if(y)return{...y,nodesVisited:u};for(let f of h.questions){let b=o.get(`${c}:${f.field}`);if(b)try{let v=G(l,f.field),x=await b(v);x&&typeof x=="object"&&(l=j(l,x))}catch(v){let x=v instanceof Error?v.message:String(v);ut(l,f.field);let P=h.questions.map(C=>C.field===f.field?{...C,context:C.context?`ERROR: ${x}
2
2
 
3
- ${C.context}`:`ERROR: ${x}`}:C),_=pt(W,h.context,c,u,d);if(_)return{..._,nodesVisited:l};break}}let k=r.get(c);if(!k)return F({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 L(k,u);continue}if(Je(h)){let y=h.field;if(y&&Ie(G(u,y))){let b=r.get(c);if(!b)return F({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 L(b,u);continue}let k=y?xe(d,y):void 0,f=h.interactive!==!1;return{content:{status:"widget",tool:h.tool,...h.data!==void 0?{data:h.data}:{},description:f?`IMPORTANT: You MUST now call the ${h.tool} tool to display the widget. Do NOT skip this step`:`IMPORTANT \u2014 two ordered steps. STEP 1: call the ${h.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 ${h.tool} has been called, call this flow again with action:"continue".`,interactive:f,...y?{field:y}:{},...k?{fieldSchema:k}:{}},flowTokenContent:{step:c,state:u,field:y,widgetId:h.tool},nodesVisited:l}}u=K(u,h);let S=r.get(c);if(!S)return F({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 L(S,u)}catch(T){let h=T instanceof Error?T.message:String(T);return F({waniwani:s,code:"agent_failed",cause:D({error:T}),properties:{node:c}}),{content:{status:"error",error:h},flowTokenContent:{step:c,state:u},nodesVisited:l}}}return F({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 Ee(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var gt=new Map;async function wt(e){let t=gt.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 gt.set(e,r),r}async function mt(e,t){let n=await wt(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 ht(e,t){let n=await wt(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 zn={debug:0,warn:1,error:2,none:3};function Yn(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in zn?e:process.env.WANIWANI_DEBUG?"debug":"none"}function q(e,t){return t??Yn()==="debug"?(...r)=>console.log(`[waniwani:${e}]`,...r):()=>{}}var Gn="@waniwani/sdk",Zn="https://app.waniwani.ai",Jn=q("kv"),H=class{get baseUrl(){return(process.env.WANIWANI_API_URL??Zn).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(Ee(n)){if(!this.encryptionKey)throw new Error("[Waniwani KV] Encrypted data found but WANIWANI_ENCRYPTION_KEY is not set.");return ht(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;Jn(`set "${t}" \u2014 encryption ${o?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let i=o?await mt(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":Gn},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 de=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 Z=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 Xn(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function yt(e,t,n,r){let o=[];for(let[s,a]of t){let d=r.get(s);o.push({id:s,type:Xn(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 Tt(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 Qn={intro:e=>Tt(e.intro,e.id)};function St(e){let t=Object.entries(Qn).map(([n,r])=>[n,r(e)]).filter(([,n])=>n!==void 0);return Object.fromEntries(t)}async function kt(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 vt(e,t){let{[t]:n,...r}=e??{};return{value:n,internal:r}}function xt(e,t){return Object.keys(t).length===0?e:{...e,internal:t}}import{z as I}from"zod";var It=I.object({type:I.enum(["enum","string","number","boolean","object","array","unknown"]),values:I.array(I.string()).optional(),description:I.string().optional(),optional:I.boolean().optional()}).describe("JIT schema fragment for a state field \u2014 type, allowed values, and description."),er=I.object({verbatim:I.string().optional().describe("Text to reproduce word for word, before anything else in the reply."),instructions:I.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."),tr=I.object({question:I.string(),field:I.string(),suggestions:I.array(I.string()).optional(),context:I.string().optional(),fieldSchema:It.optional()}).describe("One question within a multi-question interrupt."),Re={intro:er.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:I.enum(["interrupt","widget","complete","error"]).describe("Current flow status and the next action the assistant should take."),question:I.string().optional().describe("Single question to ask the user when status is interrupt."),field:I.string().optional().describe("State field to fill with the user's answer on the next continue call."),fieldSchema:It.optional().describe("JIT schema fragment for the single-question shorthand."),suggestions:I.array(I.string()).optional().describe("Suggested answers for the single-question shorthand."),questions:I.array(tr).optional().describe("Multiple questions to ask the user when status is interrupt."),context:I.string().optional().describe("Private instruction context for the assistant."),tool:I.string().optional().describe("Widget tool to call when status is widget."),data:I.record(I.string(),I.unknown()).optional().describe("Input data to pass to the widget tool."),description:I.string().optional().describe("Instruction for rendering the requested widget."),interactive:I.boolean().optional().describe("Whether the widget requires user interaction before continuing."),sessionId:I.string().optional().describe("Session identifier to pass on future continue and reset calls."),error:I.string().optional().describe("Error message when status is error."),nextStep:I.string().optional().describe("How to handle this response and what the next call to this tool contains. Scoped to the status returned above.")};var Et='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`.',nr="`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 rr(){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 or(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 Rt(e){let t=[];switch(e.status){case"interrupt":t.push(...rr(),Et);break;case"widget":t.push(...or(e),Et);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(nr),t.length>0?t.join(`
4
- `):void 0}function be(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function bt(e){let t=Ct(e),n=be(t.waniwani)?t.waniwani:{};return e.meta({...t,waniwani:{...n,redacted:!0}})}function ir(e){let n=Ct(e).waniwani;return be(n)&&n.redacted===!0}function Ct(e){let t=e.meta;if(typeof t!="function")return{};let n=t.call(e);return be(n)?n:{}}function _t(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))ir(r)&&t.push(n);return t}var ue="waniwani/redactedStateUpdateFields";function sr(e){let t=e.omitIntentPII?" Do not include PII (names, emails, phones, addresses, IDs, ages, birthdates) \u2014 summarize abstractly.":"",r=e.state&&Object.keys(e.state).length>0?j.object(e.state).partial().passthrough():j.record(j.string(),j.unknown());return{action:j.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:j.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:j.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:j.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 ar(e){if(process.env.WANIWANI_API_KEY)return new Z;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 Ft(e){let{config:t,nodes:n,edges:r}=e,o=sr(t),i=yt(t,n,r,e.nodeOptions),s=`${t.description}
3
+ ${C.context}`:`ERROR: ${x}`}:C),_=gt(P,h.context,c,l,d);if(_)return{..._,nodesVisited:u};break}}let k=r.get(c);if(!k)return F({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(k,l);continue}if(Qe(h)){let y=h.field;if(y&&Re(G(l,y))){let b=r.get(c);if(!b)return F({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(b,l);continue}let k=y?Ee(d,y):void 0,f=h.interactive!==!1;return{content:{status:"widget",tool:h.tool,...h.data!==void 0?{data:h.data}:{},description:f?`IMPORTANT: You MUST now call the ${h.tool} tool to display the widget. Do NOT skip this step`:`IMPORTANT \u2014 two ordered steps. STEP 1: call the ${h.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 ${h.tool} has been called, call this flow again with action:"continue".`,interactive:f,...y?{field:y}:{},...k?{fieldSchema:k}:{}},flowTokenContent:{step:c,state:l,field:y,widgetId:h.tool},nodesVisited:u}}l=j(l,h);let S=r.get(c);if(!S)return F({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(S,l)}catch(T){let h=T instanceof Error?T.message:String(T);return F({waniwani:s,code:"agent_failed",cause:K({error:T}),properties:{node:c}}),{content:{status:"error",error:h},flowTokenContent:{step:c,state:l},nodesVisited:u}}}return F({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 be(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var wt=new Map;async function ht(e){let t=wt.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 wt.set(e,r),r}async function yt(e,t){let n=await ht(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 Tt(e,t){let n=await ht(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 Zn={debug:0,warn:1,error:2,none:3};function Jn(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in Zn?e:process.env.WANIWANI_DEBUG?"debug":"none"}function q(e,t){return t??Jn()==="debug"?(...r)=>console.log(`[waniwani:${e}]`,...r):()=>{}}var Xn="@waniwani/sdk",Qn="https://app.waniwani.ai",er=q("kv"),H=class{get baseUrl(){return(process.env.WANIWANI_API_URL??Qn).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(be(n)){if(!this.encryptionKey)throw new Error("[Waniwani KV] Encrypted data found but WANIWANI_ENCRYPTION_KEY is not set.");return Tt(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;er(`set "${t}" \u2014 encryption ${o?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let i=o?await yt(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":Xn},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 ue=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 Z=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 tr(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function St(e,t,n,r){let o=[];for(let[s,a]of t){let d=r.get(s);o.push({id:s,type:tr(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 kt(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 nr={intro:e=>kt(e.intro,e.id)};function vt(e){let t=Object.entries(nr).map(([n,r])=>[n,r(e)]).filter(([,n])=>n!==void 0);return Object.fromEntries(t)}async function xt(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 It(e,t){let{[t]:n,...r}=e??{};return{value:n,internal:r}}function Et(e,t){return Object.keys(t).length===0?e:{...e,internal:t}}import{z as I}from"zod";var Rt=I.object({type:I.enum(["enum","string","number","boolean","object","array","unknown"]),values:I.array(I.string()).optional(),description:I.string().optional(),optional:I.boolean().optional()}).describe("JIT schema fragment for a state field \u2014 type, allowed values, and description."),rr=I.object({verbatim:I.string().optional().describe("Text to reproduce word for word, before anything else in the reply."),instructions:I.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."),or=I.object({question:I.string(),field:I.string(),suggestions:I.array(I.string()).optional(),context:I.string().optional(),fieldSchema:Rt.optional()}).describe("One question within a multi-question interrupt."),Ce={intro:rr.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:I.enum(["interrupt","widget","complete","error"]).describe("Current flow status and the next action the assistant should take."),question:I.string().optional().describe("Single question to ask the user when status is interrupt."),field:I.string().optional().describe("State field to fill with the user's answer on the next continue call."),fieldSchema:Rt.optional().describe("JIT schema fragment for the single-question shorthand."),suggestions:I.array(I.string()).optional().describe("Suggested answers for the single-question shorthand."),questions:I.array(or).optional().describe("Multiple questions to ask the user when status is interrupt."),context:I.string().optional().describe("Private instruction context for the assistant."),tool:I.string().optional().describe("Widget tool to call when status is widget."),data:I.record(I.string(),I.unknown()).optional().describe("Input data to pass to the widget tool."),description:I.string().optional().describe("Instruction for rendering the requested widget."),interactive:I.boolean().optional().describe("Whether the widget requires user interaction before continuing."),sessionId:I.string().optional().describe("Session identifier to pass on future continue and reset calls."),error:I.string().optional().describe("Error message when status is error."),nextStep:I.string().optional().describe("How to handle this response and what the next call to this tool contains. Scoped to the status returned above.")};var bt='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`.',ir="`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 sr(){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 ar(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 Ct(e){let t=[];switch(e.status){case"interrupt":t.push(...sr(),bt);break;case"widget":t.push(...ar(e),bt);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(ir),t.length>0?t.join(`
4
+ `):void 0}function _e(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function _t(e){let t=Ft(e),n=_e(t.waniwani)?t.waniwani:{};return e.meta({...t,waniwani:{...n,redacted:!0}})}function cr(e){let n=Ft(e).waniwani;return _e(n)&&n.redacted===!0}function Ft(e){let t=e.meta;if(typeof t!="function")return{};let n=t.call(e);return _e(n)?n:{}}function At(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))cr(r)&&t.push(n);return t}var pe="waniwani/redactedStateUpdateFields";function dr(e){let t=e.omitIntentPII?" Do not include PII (names, emails, phones, addresses, IDs, ages, birthdates) \u2014 summarize abstractly.":"",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 lr(e){if(process.env.WANIWANI_API_KEY)return new Z;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 Pt(e){let{config:t,nodes:n,edges:r}=e,o=dr(t),i=St(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??ar(t.id),d=St(t),c=new Map;async function u(m,T,h,S,y){let k=(f,b,v)=>ft(f,b,n,r,c,S,y,e.nodeOptions,t.state).then(x=>({...x,internal:v}));if(m.action==="start"){let f=typeof m.intent=="string"?m.intent.trim():void 0;if(m.intent=f||void 0,typeof m.context=="string"){let _=m.context.trim();m.context=_||void 0}let b=r.get(A);if(!b)return F({waniwani:y,code:"agent_failed",cause:"flow_dead_end",properties:{node:A}}),{content:{status:"error",error:"No start edge"}};let v=await kt({store:a,sessionId:T,sessionIsPreexisting:h,seed:d}),x=ce(m.stateUpdates??{}),W=await L(b,x);return k(W,x,v)}if(m.action==="continue"){if(!T)return{content:{status:"error",error:"No session ID available for continue action."}};let f;try{f=await a.get(T)}catch(_){let C=_ instanceof Error?_.message:String(_);return F({waniwani:y,code:"upstream_failed",cause:D({error:_})}),{content:{status:"error",error:`Failed to load flow state (session "${T}"): ${C}`}}}if(!f)return{content:{status:"error",error:`Flow state not found for session "${T}". The flow may have expired.`}};let b=f.state,v=f.step;if(!v)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let x=K(b,ce(m.stateUpdates??{})),W=f.internal??{};if(f.widgetId){let _=r.get(v);if(!_)return F({waniwani:y,code:"agent_failed",cause:"flow_dead_end",properties:{node:v}}),{content:{status:"error",error:`No edge from step "${v}"`}};let C=await L(_,x);return k(C,x,W)}return k(v,x,W)}if(m.action==="reset"){if(!T)return{content:{status:"error",error:"No session ID available for reset action."}};let f;try{f=await a.get(T)}catch(C){let X=C instanceof Error?C.message:String(C);return F({waniwani:y,code:"upstream_failed",cause:D({error:C})}),{content:{status:"error",error:`Failed to load flow state (session "${T}"): ${X}`}}}if(!f)return{content:{status:"error",error:`Flow state not found for session "${T}". The flow may have completed or expired. Use action "start" to begin a new flow.`}};if(!f.step)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};if(!m.stateUpdates||Object.keys(m.stateUpdates).length===0)return{content:{status:"error",error:'Missing "stateUpdates" for action "reset". Include the corrected field(s).'}};let b=r.get(A);if(!b)return F({waniwani:y,code:"agent_failed",cause:"flow_dead_end",properties:{node:A}}),{content:{status:"error",error:"No start edge"}};let v=f.state,x=K(v,ce(m.stateUpdates)),W=f.internal??{},_=await L(b,x);return k(_,x,W)}return{content:{status:"error",error:`Unknown action: "${m.action}"`}}}let l=_t(t.state),p={title:t.title,description:s,inputSchema:o,outputSchema:Re,annotations:t.annotations,...l.length>0&&{_meta:{[ue]:l}}},R=(async(m,T)=>{let h=T,S=h._meta??{},y=P(S),k=y??m.sessionId,f=!!k;!k&&m.action==="start"&&(k=crypto.randomUUID()),k&&!y&&(S["waniwani/sessionId"]=k);let b=ke(h),v=await u(m,k,f,S,b),x=!y&&k?{...v.content,sessionId:k}:v.content,{value:W,internal:_}=x.status==="error"?{value:void 0,internal:v.internal??{}}:vt(v.internal,"intro"),C=Rt({status:x.status,tool:"tool"in x?x.tool:void 0,interactive:"interactive"in x?x.interactive:void 0,hasIntro:!!W,echoSessionId:!y&&!!k}),X={...W?{intro:W}:{},...x,...C?{nextStep:C}:{}};if(S[Se]={suggestions:x.status==="interrupt"?x.suggestions??[]:[]},k&&v.flowTokenContent){let on=xt(v.flowTokenContent,_);try{await a.set(k,on)}catch(Q){let sn=Q instanceof Error?Q.message:String(Q);return F({waniwani:b,code:"upstream_failed",cause:D({error:Q}),properties:{node:v.flowTokenContent.step}}),{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${k}"): ${sn}`},null,2)}],_meta:S,isError:!0}}}let rn=[{type:"text",text:JSON.stringify(X,null,2)}];return v.nodesVisited?.length&&(S[V]={flowId:t.id,nodesVisited:v.nodesVisited}),{content:rn,structuredContent:X,_meta:S,...v.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:p,handler:R,async register(m){let T={...p,_meta:{...p._meta,_flowGraph:i}};m.registerTool(t.id,T,R)},graph:e.graph,flowGraph:i}}function At(e,t){let n=["flowchart TD"];n.push(` ${A}((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 z=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===A||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 At(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return Ft({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>At(n,r),nodeOptions:new Map(this.nodeOptions)})}validate(){if(!this.edges.has(A))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(A);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!==A&&!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 Wt(e){return new z(e)}function Ce(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function Pt(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 p=await s({action:"start",intent:c,...l?{context:l}:{},...u?{stateUpdates:u}:{}},a);return d(Ce(p))},async continueWith(c){let u=await s({action:"continue",...c?{stateUpdates:c}:{}},a);return d(Ce(u))},async resetWith(c){let u=await s({action:"reset",stateUpdates:c},a);return d(Ce(u))},async lastState(){return n?n.get(o):null}}}import{AsyncLocalStorage as cr}from"async_hooks";var Mt=globalThis,le=Mt.__waniwaniKbRetrievalStore;le||(le=new cr,Mt.__waniwaniKbRetrievalStore=le);var _e=le;function Nt(e){try{_e.getStore()?.searches.push(e)}catch{}}var dr="@waniwani/sdk";function Ut(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":dr},l={method:i,headers:u};a!==void 0&&(u["Content-Type"]="application/json",l.body=JSON.stringify(a));let p=await fetch(c,l);if(!p.ok){let m=await p.text().catch(()=>"");throw new B(m||`KB API error: HTTP ${p.status}`,p.status)}return(await p.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 Nt({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 ur,readFileSync as lr}from"fs";import{resolve as pr}from"path";var fr="waniwani.json",Y;function Ot(){if(Y!==void 0)return Y;try{let e=pr(process.cwd(),fr);if(!ur(e))return Y=null,null;let t=lr(e,"utf-8");return Y=JSON.parse(t),Y}catch{return Y=null,null}}var gr="__waniwani_config__";function Dt(){return globalThis[gr]}var wr="@waniwani/sdk";function fe(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??Kt,o=yr(e),i=pe(e.meta),s=pe(e.metadata),a=Tr(e,i),d=M(e.eventId)??r(),c=Sr(e.timestamp,n),u=M(e.source)??O(i)??t.source??wr,l=Fe(e)?{...e}:void 0,p={...s};return Object.keys(i).length>0&&(p.meta=i),l&&(p.rawLegacy=l),{id:d,type:"mcp.event",name:o,source:u,timestamp:c,correlation:a,properties:mr(e,o),metadata:p,rawLegacy:l}}function Kt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function mr(e,t){if(!Fe(e))return pe(e.properties);let n=hr(e,t),r=pe(e.properties);return{...n,...r}}function hr(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 yr(e){return Fe(e)?e.eventType:e.event}function Tr(e,t){let n=M(e.requestId)??tt(t),r=M(e.sessionId)??P(t),o=M(e.traceId)??nt(t),i=M(e.externalUserId)??oe(t),s=M(e.visitorId)??ie(t),a=M(e.correlationId)??se(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 Sr(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 pe(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function M(e){if(typeof e=="string"&&e.trim().length!==0)return e}function Fe(e){return"eventType"in e}var kr="/api/mcp/events/v2/batch";var jt="@waniwani/sdk";var vr=new Set([401,403]),xr=new Set([408,425,429,500,502,503,504]),Ir=(e,t)=>globalThis.fetch(e,t);function Lt(e){return new Ae(e)}var Ae=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=br(t.apiUrl,t.endpointPath??kr),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??Ir,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":jt};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:Cr(i)}}if(vr.has(n.status))return{kind:"auth",status:n.status};if(xr.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await Rr(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:jt,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(Er(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 Er(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 Rr(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function br(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function Cr(e){return e instanceof Error?e.message:String(e)}function Bt(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?Lt({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=fe(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,te(a)),c={async identify(u,l,p){o();let R=fe({event:"user.identified",externalUserId:u,properties:l,meta:p});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&&_r(c,r.shutdownTimeoutMs),c}function _r(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 ge(e){let n=e??Ot()??Dt(),r=n?.apiUrl??process.env.WANIWANI_API_URL??ne,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=Bt(s),d=Ut(s),c=ee(s);return{...a,kb:d,documents:c,_config:s}}function Fr(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 Ar(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=ge(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(Fr(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 We=q("widget-token"),Wr=120*1e3,we=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-Wr?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=Pr(this.config.apiUrl,"/api/mcp/widget-tokens");We("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(We("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 We("mint failed:",i),null}}};function Pr(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function $t(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 Mr(e){return $t(JSON.stringify({nodes:e.nodes,edges:e.edges}))}async function Vt(e){if(e.length===0)return null;let t=[...e].sort((o,i)=>o.flowId.localeCompare(i.flowId)),n=await $t(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 Mr(o),nodes:o.nodes,edges:o.edges})));return{compositeHash:n,flows:r}}var qt="waniwani/sessionId",me="waniwani/geoLocation",he="waniwani/userLocation",Nr="openai/userLocation",Ur=[Nr,me,he];function Ht(e,t){if(t.length===0)return e;let n;for(let r of Ur){let o=e[r];if(!E(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 E(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function J(e){if(!E(e))return;let t=e._meta;return E(t)?t:void 0}function Pe(e){if(!E(e))return;let t=e.content;return Array.isArray(t)?t.find(r=>E(r)&&r.type==="text"&&typeof r.text=="string")?.text:void 0}function Or(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function Me(e,t,n,r,o,i,s){let a=Or(e,n.toolType),d=n.stripLocationFields,c=d&&d.length>0,u=J(t),l=u&&c?Ht(u,d):u,p=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,R=c&&E(i?.output)&&E(i.output._meta)?{...i.output,_meta:Ht(i.output._meta,d)}:i?.output,T=(E(i?.output)&&E(i.output._meta)?i.output._meta:void 0)?.[V],h=T&&l?{...l,[V]:T}:T?{[V]:T}:l,S=E(i?.input)&&typeof i.input.sessionId=="string"&&i.input.sessionId.length>0?i.input.sessionId:void 0,y=S&&!P(h??void 0)?{...h??{},"waniwani/sessionId":S}:h;return{event:"tool.called",properties:{name:e,type:a,...r??{},...p!==void 0&&{input:p},...R!==void 0&&{output:R},...s&&s.length>0&&{kbSearch:s}},meta:y,source:O(y??l,o),metadata:{...n.metadata??{},...o&&{clientInfo:o},...n.funnelSync&&{funnelSync:n.funnelSync}}}}async function Ne(e,t,n){try{await e.track(t)}catch(r){n?.(Oe(r))}}async function Ue(e,t){try{await e.flush()}catch(n){t?.(Oe(n))}}async function Yt(e,t,n,r,o,i){if(!E(e))return;E(e._meta)||(e._meta={});let s=e._meta,a=E(s[re])?s[re]:void 0,d={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let p=await t.getToken();p&&(d.token=p)}catch(p){o?.(Oe(p))}let c=P(s);c&&(d.sessionId||(d.sessionId=c));let u=Jt(s);u!==void 0&&(d.geoLocation||(d.geoLocation=u));let l=O(J(r),i);l&&!d.source&&(d.source=l),s[re]=d}var zt=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function Gt(e,t){if(!t||!E(e))return;let n=!1;for(let o of zt)if(o in t){n=!0;break}if(!n)return;E(e._meta)||(e._meta={});let r=e._meta;for(let o of zt)o in t&&(o in r||(r[o]=t[o]))}function Zt(e,t){let n=J(t);if(!n||!E(e))return;E(e._meta)||(e._meta={});let r=e._meta,o=P(n);o&&!r[qt]&&(r[qt]=o);let i=Jt(n);i&&(r[me]||(r[me]=i),r[he]||(r[he]=i))}function Jt(e){if(!e)return;let t=e[me]??e[he];if(E(t)||typeof t=="string")return t}function Oe(e){return e instanceof Error?e:new Error(String(e))}function Xt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qt(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(Xt(e.requestInfo)){let t=e.requestInfo.headers;if(Xt(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 tn=Symbol.for("waniwani.wrappedHandler"),ye=q("mcp"),nn="https://app.waniwani.ai",Dr="REDACTED";function Kr(e){if(!e)return;let t=e[ue];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(!E(r))return r;let o=r.stateUpdates;if(!E(o))return r;let i=!1,s={...o};for(let a of n)a in s&&(s[a]=Dr,i=!0);return i?{...r,stateUpdates:s}:r}}function en(e,t,n,r){let{server:o,tracker:i,opts:s,tokenCache:a,injectToken:d}=n,c=s.applyFieldRedactions===!0?Kr(r):void 0,u=async(l,p)=>{let R=c?{...s,redactInput:c,funnelSync:n.funnelSync}:{...s,funnelSync:n.funnelSync},m=J(p)??{},T=o.server?.getClientVersion?.();if(!P(m)&&E(p)){let f=Qt(p);f&&(m["waniwani/sessionId"]=f,p._meta=m)}if(!O(m)&&E(p)){let f=p.requestInfo?.headers,b=O(m,T)??st(f);b&&(m["waniwani/source"]=b,p._meta=m)}let S=at(i,m,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});E(p)&&(p[ae]=S);let y={searches:[]},k=performance.now();try{let f=await _e.run(y,()=>t(l,p)),b=Math.round(performance.now()-k);ye(`tool "${e}" handler returned in ${b}ms, running post-processing...`);let v=E(f)&&f.isError===!0;if(v){let x=Pe(f);console.error(`[waniwani] Tool "${e}" returned error${x?`: ${x}`:""}`)}return await Ne(i,Me(e,p,R,{durationMs:b,status:v?"error":"ok",...v&&{errorMessage:Pe(f)??"Unknown tool error"}},T,{input:l,output:f},y.searches),s.onError),ye(`tool "${e}" tracking done`),s.flushAfterToolCall&&await Ue(i,s.onError),Zt(f,p),Gt(f,r),d&&(await Yt(f,a,i._config.apiUrl??nn,p,s.onError,T),ye(`tool "${e}" widget config injected`)),ye(`tool "${e}" post-processing complete, returning result`),f}catch(f){let b=Math.round(performance.now()-k);throw await Ne(i,Me(e,p,R,{durationMs:b,status:"error",errorMessage:f instanceof Error?f.message:String(f),cause:D({error:f})},T,{input:l},y.searches),s.onError),s.flushAfterToolCall&&await Ue(i,s.onError),f}};return u[tn]=!0,u}async function jr(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??ge(),i=r.injectWidgetToken!==!1,s=o._config.apiKey?new we({apiUrl:o._config.apiUrl??nn,apiKey:o._config.apiKey}):null,a={server:e,tracker:o,opts:r,tokenCache:s,injectToken:i,funnelSync:null},d=e.registerTool.bind(e);n.registerTool=((...u)=>{let[l,p,R]=u;if(typeof R!="function")return d(...u);let m=typeof l=="string"&&l.trim().length>0?l:"unknown",T=E(p)&&E(p._meta)?p._meta:void 0,h=en(m,R,a,T);return d(l,p,h)});let c=e._registeredTools;if(E(c))for(let[u,l]of Object.entries(c)){if(!E(l))continue;let p=l.handler;if(typeof p!="function"||p[tn])continue;let R=E(l._meta)?l._meta:void 0;l.handler=en(u,p,a,R)}if(o._config.apiKey){let u=e._registeredTools,l=[];if(u&&typeof u=="object"){for(let p of Object.values(u))if(p&&typeof p=="object"){let R=p._meta,m=R&&typeof R=="object"?R._flowGraph:void 0;m?.nodes?.length&&l.push(m)}}l.length>0&&(a.funnelSync=await Vt(l))}return n}export{N as END,de as MemoryKvStore,ae as SCOPED_CLIENT_KEY,A as START,z as StateGraph,H as WaniwaniKvStore,cn as autoHeightFromMeta,Wt as createFlow,Pt as createFlowTestHarness,Ar as createTrackingRoute,$e as createWebMcpBridge,ke as extractScopedClient,dn as isDisplayTool,Ve as readWidgetStep,bt as redacted,Ke as resourceUriFromMeta,qe as rewriteForAgent,Be as supportsWebMcp,je as viewUriFor,jr 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??lr(t.id),d=vt(t),c=new Map;async function l(w,T,h,S,y){let k=(f,b,v)=>mt(f,b,n,r,c,S,y,e.nodeOptions,t.state).then(x=>({...x,internal:v}));if(w.action==="start"){let f=typeof w.intent=="string"?w.intent.trim():void 0;if(w.intent=f||void 0,typeof w.context=="string"){let _=w.context.trim();w.context=_||void 0}let b=r.get(A);if(!b)return F({waniwani:y,code:"agent_failed",cause:"flow_dead_end",properties:{node:A}}),{content:{status:"error",error:"No start edge"}};let v=await xt({store:a,sessionId:T,sessionIsPreexisting:h,seed:d}),x=le(w.stateUpdates??{}),P=await B(b,x);return k(P,x,v)}if(w.action==="continue"){if(!T)return{content:{status:"error",error:"No session ID available for continue action."}};let f;try{f=await a.get(T)}catch(_){let C=_ instanceof Error?_.message:String(_);return F({waniwani:y,code:"upstream_failed",cause:K({error:_})}),{content:{status:"error",error:`Failed to load flow state (session "${T}"): ${C}`}}}if(!f)return{content:{status:"error",error:`Flow state not found for session "${T}". The flow may have expired.`}};let b=f.state,v=f.step;if(!v)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let x=j(b,le(w.stateUpdates??{})),P=f.internal??{};if(f.widgetId){let _=r.get(v);if(!_)return F({waniwani:y,code:"agent_failed",cause:"flow_dead_end",properties:{node:v}}),{content:{status:"error",error:`No edge from step "${v}"`}};let C=await B(_,x);return k(C,x,P)}return k(v,x,P)}if(w.action==="reset"){if(!T)return{content:{status:"error",error:"No session ID available for reset action."}};let f;try{f=await a.get(T)}catch(C){let X=C instanceof Error?C.message:String(C);return F({waniwani:y,code:"upstream_failed",cause:K({error:C})}),{content:{status:"error",error:`Failed to load flow state (session "${T}"): ${X}`}}}if(!f)return{content:{status:"error",error:`Flow state not found for session "${T}". The flow may have completed or expired. Use action "start" to begin a new flow.`}};if(!f.step)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};if(!w.stateUpdates||Object.keys(w.stateUpdates).length===0)return{content:{status:"error",error:'Missing "stateUpdates" for action "reset". Include the corrected field(s).'}};let b=r.get(A);if(!b)return F({waniwani:y,code:"agent_failed",cause:"flow_dead_end",properties:{node:A}}),{content:{status:"error",error:"No start edge"}};let v=f.state,x=j(v,le(w.stateUpdates)),P=f.internal??{},_=await B(b,x);return k(_,x,P)}return{content:{status:"error",error:`Unknown action: "${w.action}"`}}}let u=At(t.state),p={title:t.title,description:s,inputSchema:o,outputSchema:Ce,annotations:t.annotations,...u.length>0&&{_meta:{[pe]:u}}},R=(async(w,T)=>{let h=T,S=h._meta??{},y=W(S),k=y??w.sessionId,f=!!k;!k&&w.action==="start"&&(k=crypto.randomUUID()),k&&!y&&(S["waniwani/sessionId"]=k);let b=xe(h),v=await l(w,k,f,S,b),x=!y&&k?{...v.content,sessionId:k}:v.content,{value:P,internal:_}=x.status==="error"?{value:void 0,internal:v.internal??{}}:It(v.internal,"intro"),C=Ct({status:x.status,tool:"tool"in x?x.tool:void 0,interactive:"interactive"in x?x.interactive:void 0,hasIntro:!!P,echoSessionId:!y&&!!k}),X={...P?{intro:P}:{},...x,...C?{nextStep:C}:{}};if(S[ve]={suggestions:x.status==="interrupt"?x.suggestions??[]:[]},k&&v.flowTokenContent){let an=Et(v.flowTokenContent,_);try{await a.set(k,an)}catch(Q){let cn=Q instanceof Error?Q.message:String(Q);return F({waniwani:b,code:"upstream_failed",cause:K({error:Q}),properties:{node:v.flowTokenContent.step}}),{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${k}"): ${cn}`},null,2)}],_meta:S,isError:!0}}}let sn=[{type:"text",text:JSON.stringify(X,null,2)}];return v.nodesVisited?.length&&(S[V]={flowId:t.id,nodesVisited:v.nodesVisited}),{content:sn,structuredContent:X,_meta:S,...v.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:p,handler:R,async register(w){let T={...p,_meta:{...p._meta,_flowGraph:i}};w.registerTool(t.id,T,R)},graph:e.graph,flowGraph:i}}function Wt(e,t){let n=["flowchart TD"];n.push(` ${A}((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 z=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===A||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 Wt(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return Pt({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>Wt(n,r),nodeOptions:new Map(this.nodeOptions)})}validate(){if(!this.edges.has(A))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(A);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!==A&&!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 Mt(e){return new z(e)}function Fe(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function Nt(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 p=await s({action:"start",intent:c,...u?{context:u}:{},...l?{stateUpdates:l}:{}},a);return d(Fe(p))},async continueWith(c){let l=await s({action:"continue",...c?{stateUpdates:c}:{}},a);return d(Fe(l))},async resetWith(c){let l=await s({action:"reset",stateUpdates:c},a);return d(Fe(l))},async lastState(){return n?n.get(o):null}}}import{AsyncLocalStorage as ur}from"async_hooks";var Ut=globalThis,fe=Ut.__waniwaniKbRetrievalStore;fe||(fe=new ur,Ut.__waniwaniKbRetrievalStore=fe);var Ae=fe;function Ot(e){try{Ae.getStore()?.searches.push(e)}catch{}}var pr="@waniwani/sdk";function Dt(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":pr},u={method:i,headers:l};a!==void 0&&(l["Content-Type"]="application/json",u.body=JSON.stringify(a));let p=await fetch(c,u);if(!p.ok){let w=await p.text().catch(()=>"");throw new U(w||`KB API error: HTTP ${p.status}`,p.status)}return(await p.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 Ot({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 fr,readFileSync as gr}from"fs";import{resolve as mr}from"path";var wr="waniwani.json",Y;function Kt(){if(Y!==void 0)return Y;try{let e=mr(process.cwd(),wr);if(!fr(e))return Y=null,null;let t=gr(e,"utf-8");return Y=JSON.parse(t),Y}catch{return Y=null,null}}var hr="__waniwani_config__";function jt(){return globalThis[hr]}var yr="@waniwani/sdk";function me(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??Lt,o=kr(e),i=ge(e.meta),s=ge(e.metadata),a=vr(e,i),d=M(e.eventId)??r(),c=xr(e.timestamp,n),l=M(e.source)??D(i)??t.source??yr,u=Pe(e)?{...e}:void 0,p={...s};return Object.keys(i).length>0&&(p.meta=i),u&&(p.rawLegacy=u),{id:d,type:"mcp.event",name:o,source:l,timestamp:c,correlation:a,properties:Tr(e,o),metadata:p,rawLegacy:u}}function Lt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function Tr(e,t){if(!Pe(e))return ge(e.properties);let n=Sr(e,t),r=ge(e.properties);return{...n,...r}}function Sr(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 kr(e){return Pe(e)?e.eventType:e.event}function vr(e,t){let n=M(e.requestId)??rt(t),r=M(e.sessionId)??W(t),o=M(e.traceId)??ot(t),i=M(e.externalUserId)??se(t),s=M(e.visitorId)??ae(t),a=M(e.correlationId)??ce(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 xr(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 ge(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function M(e){if(typeof e=="string"&&e.trim().length!==0)return e}function Pe(e){return"eventType"in e}var Ir="/api/mcp/events/v2/batch";var Bt="@waniwani/sdk";var Er=new Set([401,403]),Rr=new Set([408,425,429,500,502,503,504]),br=(e,t)=>globalThis.fetch(e,t);function $t(e){return new We(e)}var We=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=Fr(t.apiUrl,t.endpointPath??Ir),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??br,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":Bt};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:Ar(i)}}if(Er.has(n.status))return{kind:"auth",status:n.status};if(Rr.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await _r(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:Bt,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(Cr(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 Cr(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 _r(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function Fr(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function Ar(e){return e instanceof Error?e.message:String(e)}function Vt(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?$t({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=me(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,re(a)),c={async identify(l,u,p){o();let R=me({event:"user.identified",externalUserId:l,properties:u,meta:p});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&&Pr(c,r.shutdownTimeoutMs),c}function Pr(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 we(e){let n=e??Kt()??jt(),r=n?.apiUrl??process.env.WANIWANI_API_URL??oe,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=Vt(s),d=Dt(s),c=te(s),l=ne(s);return{...a,kb:d,documents:c,email:l,_config:s}}function Wr(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 Mr(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=we(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(Wr(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 Me=q("widget-token"),Nr=120*1e3,he=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-Nr?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=Ur(this.config.apiUrl,"/api/mcp/widget-tokens");Me("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(Me("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 Me("mint failed:",i),null}}};function Ur(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function qt(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 Or(e){return qt(JSON.stringify({nodes:e.nodes,edges:e.edges}))}async function Ht(e){if(e.length===0)return null;let t=[...e].sort((o,i)=>o.flowId.localeCompare(i.flowId)),n=await qt(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 Or(o),nodes:o.nodes,edges:o.edges})));return{compositeHash:n,flows:r}}var zt="waniwani/sessionId",ye="waniwani/geoLocation",Te="waniwani/userLocation",Dr="openai/userLocation",Kr=[Dr,ye,Te];function Yt(e,t){if(t.length===0)return e;let n;for(let r of Kr){let o=e[r];if(!E(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 E(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function J(e){if(!E(e))return;let t=e._meta;return E(t)?t:void 0}function Ne(e){if(!E(e))return;let t=e.content;return Array.isArray(t)?t.find(r=>E(r)&&r.type==="text"&&typeof r.text=="string")?.text:void 0}function jr(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function Ue(e,t,n,r,o,i,s){let a=jr(e,n.toolType),d=n.stripLocationFields,c=d&&d.length>0,l=J(t),u=l&&c?Yt(l,d):l,p=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,R=c&&E(i?.output)&&E(i.output._meta)?{...i.output,_meta:Yt(i.output._meta,d)}:i?.output,T=(E(i?.output)&&E(i.output._meta)?i.output._meta:void 0)?.[V],h=T&&u?{...u,[V]:T}:T?{[V]:T}:u,S=E(i?.input)&&typeof i.input.sessionId=="string"&&i.input.sessionId.length>0?i.input.sessionId:void 0,y=S&&!W(h??void 0)?{...h??{},"waniwani/sessionId":S}:h;return{event:"tool.called",properties:{name:e,type:a,...r??{},...p!==void 0&&{input:p},...R!==void 0&&{output:R},...s&&s.length>0&&{kbSearch:s}},meta:y,source:D(y??u,o),metadata:{...n.metadata??{},...o&&{clientInfo:o},...n.funnelSync&&{funnelSync:n.funnelSync}}}}async function Oe(e,t,n){try{await e.track(t)}catch(r){n?.(Ke(r))}}async function De(e,t){try{await e.flush()}catch(n){t?.(Ke(n))}}async function Zt(e,t,n,r,o,i){if(!E(e))return;E(e._meta)||(e._meta={});let s=e._meta,a=E(s[ie])?s[ie]:void 0,d={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let p=await t.getToken();p&&(d.token=p)}catch(p){o?.(Ke(p))}let c=W(s);c&&(d.sessionId||(d.sessionId=c));let l=Qt(s);l!==void 0&&(d.geoLocation||(d.geoLocation=l));let u=D(J(r),i);u&&!d.source&&(d.source=u),s[ie]=d}var Gt=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function Jt(e,t){if(!t||!E(e))return;let n=!1;for(let o of Gt)if(o in t){n=!0;break}if(!n)return;E(e._meta)||(e._meta={});let r=e._meta;for(let o of Gt)o in t&&(o in r||(r[o]=t[o]))}function Xt(e,t){let n=J(t);if(!n||!E(e))return;E(e._meta)||(e._meta={});let r=e._meta,o=W(n);o&&!r[zt]&&(r[zt]=o);let i=Qt(n);i&&(r[ye]||(r[ye]=i),r[Te]||(r[Te]=i))}function Qt(e){if(!e)return;let t=e[ye]??e[Te];if(E(t)||typeof t=="string")return t}function Ke(e){return e instanceof Error?e:new Error(String(e))}function en(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tn(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(en(e.requestInfo)){let t=e.requestInfo.headers;if(en(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 rn=Symbol.for("waniwani.wrappedHandler"),Se=q("mcp"),on="https://app.waniwani.ai",Lr="REDACTED";function Br(e){if(!e)return;let t=e[pe];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(!E(r))return r;let o=r.stateUpdates;if(!E(o))return r;let i=!1,s={...o};for(let a of n)a in s&&(s[a]=Lr,i=!0);return i?{...r,stateUpdates:s}:r}}function nn(e,t,n,r){let{server:o,tracker:i,opts:s,tokenCache:a,injectToken:d}=n,c=s.applyFieldRedactions===!0?Br(r):void 0,l=async(u,p)=>{let R=c?{...s,redactInput:c,funnelSync:n.funnelSync}:{...s,funnelSync:n.funnelSync},w=J(p)??{},T=o.server?.getClientVersion?.();if(!W(w)&&E(p)){let f=tn(p);f&&(w["waniwani/sessionId"]=f,p._meta=w)}if(!D(w)&&E(p)){let f=p.requestInfo?.headers,b=D(w,T)??ct(f);b&&(w["waniwani/source"]=b,p._meta=w)}let S=dt(i,w,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});E(p)&&(p[de]=S);let y={searches:[]},k=performance.now();try{let f=await Ae.run(y,()=>t(u,p)),b=Math.round(performance.now()-k);Se(`tool "${e}" handler returned in ${b}ms, running post-processing...`);let v=E(f)&&f.isError===!0;if(v){let x=Ne(f);console.error(`[waniwani] Tool "${e}" returned error${x?`: ${x}`:""}`)}return await Oe(i,Ue(e,p,R,{durationMs:b,status:v?"error":"ok",...v&&{errorMessage:Ne(f)??"Unknown tool error"}},T,{input:u,output:f},y.searches),s.onError),Se(`tool "${e}" tracking done`),s.flushAfterToolCall&&await De(i,s.onError),Xt(f,p),Jt(f,r),d&&(await Zt(f,a,i._config.apiUrl??on,p,s.onError,T),Se(`tool "${e}" widget config injected`)),Se(`tool "${e}" post-processing complete, returning result`),f}catch(f){let b=Math.round(performance.now()-k);throw await Oe(i,Ue(e,p,R,{durationMs:b,status:"error",errorMessage:f instanceof Error?f.message:String(f),cause:K({error:f})},T,{input:u},y.searches),s.onError),s.flushAfterToolCall&&await De(i,s.onError),f}};return l[rn]=!0,l}async function $r(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??we(),i=r.injectWidgetToken!==!1,s=o._config.apiKey?new he({apiUrl:o._config.apiUrl??on,apiKey:o._config.apiKey}):null,a={server:e,tracker:o,opts:r,tokenCache:s,injectToken:i,funnelSync:null},d=e.registerTool.bind(e);n.registerTool=((...l)=>{let[u,p,R]=l;if(typeof R!="function")return d(...l);let w=typeof u=="string"&&u.trim().length>0?u:"unknown",T=E(p)&&E(p._meta)?p._meta:void 0,h=nn(w,R,a,T);return d(u,p,h)});let c=e._registeredTools;if(E(c))for(let[l,u]of Object.entries(c)){if(!E(u))continue;let p=u.handler;if(typeof p!="function"||p[rn])continue;let R=E(u._meta)?u._meta:void 0;u.handler=nn(l,p,a,R)}if(o._config.apiKey){let l=e._registeredTools,u=[];if(l&&typeof l=="object"){for(let p of Object.values(l))if(p&&typeof p=="object"){let R=p._meta,w=R&&typeof R=="object"?R._flowGraph:void 0;w?.nodes?.length&&u.push(w)}}u.length>0&&(a.funnelSync=await Ht(u))}return n}export{N as END,ue as MemoryKvStore,de as SCOPED_CLIENT_KEY,A as START,z as StateGraph,H as WaniwaniKvStore,ln as autoHeightFromMeta,Mt as createFlow,Nt as createFlowTestHarness,Mr as createTrackingRoute,qe as createWebMcpBridge,xe as extractScopedClient,un as isDisplayTool,He as readWidgetStep,_t as redacted,Le as resourceUriFromMeta,ze as rewriteForAgent,Ve as supportsWebMcp,Be as viewUriFor,$r as withWaniwani};
8
8
  //# sourceMappingURL=index.js.map