@waniwani/sdk 0.19.6 → 0.19.7

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,7 +1,7 @@
1
- var _="__start__",F="__end__",Ae=Symbol.for("waniwani.flow.interrupt"),We=Symbol.for("waniwani.flow.widget");function Me(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:Ae,questions:r,context:n}}function Oe(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:We,tool:typeof r=="string"?r:r.id,...i!==void 0?{data:i}:{},...s!==void 0?{interactive:s}:{},...a!==void 0?{field:a}:{}}}function Ue(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Ae}function De(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===We}import{z as W}from"zod";function Z(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 we="waniwani/suggestions";function D(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var Ut=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],Dt=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Kt=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],jt=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],Lt=["waniwani/visitorId","visitorId"],Bt=["correlationId","openai/requestId"];var K="waniwani/flow",J="waniwani/widget";function C(e){return e?D(e,Ut):void 0}function je(e){return e?D(e,Dt):void 0}function Le(e){return e?D(e,Kt):void 0}function Q(e){return e?D(e,jt):void 0}function X(e){return e?D(e,Lt):void 0}function Be(e){return e?D(e,Bt):void 0}var qt=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],$t=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function N(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 qt){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 $t)if(r.includes(o))return i}}function Ke(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 qe(e){if(!e)return;let t=Ke(e,"user-agent"),n=Ke(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 ee="waniwani/client";function $(e){if(typeof e=="object"&&e!==null)return e[ee]}function $e(e,t,n){let r=o=>e.track({...o,meta:{...t,...o.meta}});return{sessionId:C(t),visitorId:X(t),externalUserId:Q(t),track:Object.assign(r,Z(r)),identify(o,i){return e.identify(o,i,t)},kb:e.kb,_config:n}}function Ve(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function V(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 Vt(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 He(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 te(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?Vt(t,n,r):r!==null&&typeof r=="object"&&!Array.isArray(r)?t=A(t,{[n]:r}):t[n]=r;return t}function A(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]=A(n[r],o):n[r]=o;return n}function Ye(e){return e._zod?.def}function Ht(e){let t=e,n=!1;for(let r=0;r<8;r++){let o=Ye(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 ze(e){let{inner:t,optional:n}=Ht(e),r=t.description??e.description??void 0,o=Ye(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 me(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=Ve(s)?.[i];return d?ze(d):void 0}let n=e[t];if(n)return ze(n)}function he(e){return e!=null&&e!==""}async function O(e,t){return e.type==="direct"?e.to:e.condition(t)}function Ge(e,t,n,r,o){if(e.every(c=>he(V(r,c.field))))return null;let i=e.filter(c=>!he(V(r,c.field))).map(c=>{let p=me(o,c.field);return p?{...c,fieldSchema:p}: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 H(e,t,n,r,o,i,s,a,d){let c=e,p={...t},l=[],u=50,v=0;for(;v++<u;){if(c===F)return{content:{status:"complete"},flowTokenContent:{state:p},nodesVisited:l};let f=n.get(c);if(!f)return{content:{status:"error",error:`Unknown node: "${c}"`},nodesVisited:l};a?.get(c)?.hideFromFunnel||l.push({id:c,at:new Date().toISOString()});try{let g=await f({state:p,meta:i,interrupt:Me,showWidget:Oe,waniwani:s});if(Ue(g)){for(let w of g.questions)w.validate&&o.set(`${c}:${w.field}`,w.validate);let y=Ge(g.questions,g.context,c,p,d);if(y)return{...y,nodesVisited:l};for(let w of g.questions){let S=o.get(`${c}:${w.field}`);if(S)try{let I=V(p,w.field),b=await S(I);b&&typeof b=="object"&&(p=A(p,b))}catch(I){let b=I instanceof Error?I.message:String(I);He(p,w.field);let M=g.questions.map(U=>U.field===w.field?{...U,context:U.context?`ERROR: ${b}
1
+ var _="__start__",A="__end__",Oe=Symbol.for("waniwani.flow.interrupt"),Ue=Symbol.for("waniwani.flow.widget");function De(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:Oe,questions:r,context:n}}function Ke(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:Ue,tool:typeof r=="string"?r:r.id,...i!==void 0?{data:i}:{},...s!==void 0?{interactive:s}:{},...a!==void 0?{field:a}:{}}}function je(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Oe}function Le(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Ue}import{z as U}from"zod";function Q(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 he="waniwani/suggestions";function j(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var jt=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],Lt=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Bt=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],$t=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],qt=["waniwani/visitorId","visitorId"],Vt=["correlationId","openai/requestId"];var L="waniwani/flow",X="waniwani/widget";function P(e){return e?j(e,jt):void 0}function $e(e){return e?j(e,Lt):void 0}function qe(e){return e?j(e,Bt):void 0}function ee(e){return e?j(e,$t):void 0}function te(e){return e?j(e,qt):void 0}function Ve(e){return e?j(e,Vt):void 0}var Ht=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],zt=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function W(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 Ht){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 zt)if(r.includes(o))return i}}function Be(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 He(e){if(!e)return;let t=Be(e,"user-agent"),n=Be(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 ne="waniwani/client";function H(e){if(typeof e=="object"&&e!==null)return e[ne]}function ze(e,t,n){let r=o=>e.track({...o,meta:{...t,...o.meta}});return{sessionId:P(t),visitorId:te(t),externalUserId:ee(t),track:Object.assign(r,Q(r)),identify(o,i){return e.identify(o,i,t)},kb:e.kb,_config:n}}import{z as ye}from"zod";var Yt=ye.object({status:ye.number().optional(),statusCode:ye.number().optional()});function Gt(e){let t=Yt.safeParse(e);if(t.success)return t.data.status??t.data.statusCode}var Zt=["fetch failed","failed to fetch","networkerror when attempting to fetch"];function M({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=Gt(e);return t===429?"rate_limited":t!==void 0&&t>=500?"upstream_5xx":t!==void 0&&t>=400?"upstream_4xx":e instanceof TypeError&&Zt.some(n=>e.message.toLowerCase().includes(n))?"network":"unknown"}function b({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 Ye(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function z(e,t){let n=t.split("."),r=e;for(let o of n){if(r==null||typeof r!="object")return;r=r[o]}return r}function Jt(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 Ge(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 re(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?Jt(t,n,r):r!==null&&typeof r=="object"&&!Array.isArray(r)?t=O(t,{[n]:r}):t[n]=r;return t}function O(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]=O(n[r],o):n[r]=o;return n}function Je(e){return e._zod?.def}function Qt(e){let t=e,n=!1;for(let r=0;r<8;r++){let o=Je(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 Ze(e){let{inner:t,optional:n}=Qt(e),r=t.description??e.description??void 0,o=Je(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 Te(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=Ye(s)?.[i];return d?Ze(d):void 0}let n=e[t];if(n)return Ze(n)}function Se(e){return e!=null&&e!==""}async function D(e,t){return e.type==="direct"?e.to:e.condition(t)}function Qe(e,t,n,r,o){if(e.every(c=>Se(z(r,c.field))))return null;let i=e.filter(c=>!Se(z(r,c.field))).map(c=>{let p=Te(o,c.field);return p?{...c,fieldSchema:p}: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 Y(e,t,n,r,o,i,s,a,d){let c=e,p={...t},l=[],u=50,v=0;for(;v++<u;){if(c===A)return{content:{status:"complete"},flowTokenContent:{state:p},nodesVisited:l};let g=n.get(c);if(!g)return b({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 f=await g({state:p,meta:i,interrupt:De,showWidget:Ke,waniwani:s});if(je(f)){for(let m of f.questions)m.validate&&o.set(`${c}:${m.field}`,m.validate);let y=Qe(f.questions,f.context,c,p,d);if(y)return{...y,nodesVisited:l};for(let m of f.questions){let S=o.get(`${c}:${m.field}`);if(S)try{let I=z(p,m.field),C=await S(I);C&&typeof C=="object"&&(p=O(p,C))}catch(I){let C=I instanceof Error?I.message:String(I);Ge(p,m.field);let N=f.questions.map(K=>K.field===m.field?{...K,context:K.context?`ERROR: ${C}
2
2
 
3
- ${U.context}`:`ERROR: ${b}`}:U),G=Ge(M,g.context,c,p,d);if(G)return{...G,nodesVisited:l};break}}let x=r.get(c);if(!x)return{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:l};c=await O(x,p);continue}if(De(g)){let y=g.field;if(y&&he(V(p,y))){let S=r.get(c);if(!S)return{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:l};c=await O(S,p);continue}let x=y?me(d,y):void 0,w=g.interactive!==!1;return{content:{status:"widget",tool:g.tool,...g.data!==void 0?{data:g.data}:{},description:w?`IMPORTANT: You MUST now call the ${g.tool} tool to display the widget. Do NOT skip this step`:`IMPORTANT \u2014 two ordered steps. STEP 1: call the ${g.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 ${g.tool} has been called, call this flow again with action:"continue".`,interactive:w,...y?{field:y}:{},...x?{fieldSchema:x}:{}},flowTokenContent:{step:c,state:p,field:y,widgetId:g.tool},nodesVisited:l}}p=A(p,g);let E=r.get(c);if(!E)return{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:l};c=await O(E,p)}catch(T){return{content:{status:"error",error:T instanceof Error?T.message:String(T)},flowTokenContent:{step:c,state:p},nodesVisited:l}}}return{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"},nodesVisited:l}}function ye(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var Ze=new Map;async function Je(e){let t=Ze.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 Ze.set(e,r),r}async function Qe(e,t){let n=await Je(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 Xe(e,t){let n=await Je(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 zt={debug:0,warn:1,error:2,none:3};function Yt(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in zt?e:process.env.WANIWANI_DEBUG?"debug":"none"}function j(e,t){return t??Yt()==="debug"?(...r)=>console.log(`[waniwani:${e}]`,...r):()=>{}}var Gt="@waniwani/sdk",Zt="https://app.waniwani.ai",Jt=j("kv"),L=class{get baseUrl(){return(process.env.WANIWANI_API_URL??Zt).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(ye(n)){if(!this.encryptionKey)throw new Error("[Waniwani KV] Encrypted data found but WANIWANI_ENCRYPTION_KEY is not set.");return Xe(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;Jt(`set "${t}" \u2014 encryption ${o?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let i=o?await Qe(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":Gt},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 ne=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 L;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 Qt(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function et(e,t,n,r){let o=[];for(let[s,a]of t){let d=r.get(s);o.push({id:s,type:Qt(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}}import{z as R}from"zod";var tt=R.object({type:R.enum(["enum","string","number","boolean","object","array","unknown"]),values:R.array(R.string()).optional(),description:R.string().optional(),optional:R.boolean().optional()}).describe("JIT schema fragment for a state field \u2014 type, allowed values, and description."),Xt=R.object({question:R.string(),field:R.string(),suggestions:R.array(R.string()).optional(),context:R.string().optional(),fieldSchema:tt.optional()}).describe("One question within a multi-question interrupt."),Te={status:R.enum(["interrupt","widget","complete","error"]).describe("Current flow status and the next action the assistant should take."),question:R.string().optional().describe("Single question to ask the user when status is interrupt."),field:R.string().optional().describe("State field to fill with the user's answer on the next continue call."),fieldSchema:tt.optional().describe("JIT schema fragment for the single-question shorthand."),suggestions:R.array(R.string()).optional().describe("Suggested answers for the single-question shorthand."),questions:R.array(Xt).optional().describe("Multiple questions to ask the user when status is interrupt."),context:R.string().optional().describe("Private instruction context for the assistant."),tool:R.string().optional().describe("Widget tool to call when status is widget."),data:R.record(R.string(),R.unknown()).optional().describe("Input data to pass to the widget tool."),description:R.string().optional().describe("Instruction for rendering the requested widget."),interactive:R.boolean().optional().describe("Whether the widget requires user interaction before continuing."),sessionId:R.string().optional().describe("Session identifier to pass on future continue and reset calls."),error:R.string().optional().describe("Error message when status is error.")};function nt(e){let t=["","## FLOW EXECUTION PROTOCOL","","This tool implements a multi-step conversational flow. Follow this protocol exactly:","",'1. Call with `action: "start"` to begin and include `intent`.'," `intent` must be a brief summary of the user's goal for this flow."," Do NOT invent missing intent."," Optionally include `context` \u2014 the situation or environment that led the user to start"," this flow (e.g. what page they are on, what they were doing, or what triggered the request)."," Only provide `context` when there is genuinely relevant situational information. Do NOT invent missing context."," If the user's message already contains answers to likely questions,"," extract them into `stateUpdates` as `{ field: value }` pairs (see the `stateUpdates` schema"," for the list of writable fields). The engine will auto-skip steps whose fields are already filled."," Only extract values the user explicitly stated \u2014 do NOT guess or invent values."];return e.omitIntentPII&&t.push(" Do NOT include PII in `intent` or `context` \u2014 no names, emails, phones, addresses, IDs, ages, or birthdates.",' Summarize the goal abstractly (e.g. "user wants a quote", not "Jane Doe wants a quote").'),t.push(" For grouped fields (z.object state), use dot-notation keys in `stateUpdates`:",' e.g. `{ "driver.name": "John", "driver.license": "ABC123" }`.',"2. The response JSON `status` field tells you what to do next:",' - `"interrupt"`: Pause and ask the user. Two forms:'," a. Single question: `{ question, field, fieldSchema?, context? }` \u2014 ask `question`, store answer in `field`."," b. Multi-question: `{ questions: [{question, field, fieldSchema?}, ...], context? }` \u2014 ask ALL questions"," in one conversational message, collect all answers."," `fieldSchema` (when present) describes the expected value: `{ type, values?, description?, optional? }`.",' Use it to validate before sending \u2014 match enum `values` exactly, coerce strings to numbers where `type: "number"`.'," `context` (if present) is hidden AI instructions \u2014 use to shape your response, do NOT show verbatim."," Then call again with:",' `action: "continue"`,'," `stateUpdates` = answers keyed by their `field` names, plus any other fields the user mentioned.",' - `"widget"`: The flow wants to show a UI widget. Call the tool named in the `tool`'," field, passing the `data` object as the tool's input."," Check the `interactive` field in the response:"," \u2022 `interactive: true` \u2014 The widget requires user interaction. After calling the display tool,"," STOP and WAIT for the user to interact with the widget. Do NOT call this flow tool again"," until the user has responded. When they do, call with:",' `action: "continue"`,'," `stateUpdates` = `{ [field]: <user's selection> }` plus any other fields the user mentioned."," \u2022 `interactive: false` \u2014 The widget is display-only. You MUST STILL call the display tool"," FIRST to render it for the user \u2014 this is a required, user-visible step. Do NOT skip it",' and do NOT jump straight to `action: "continue"`. ONLY AFTER you have called the display',' tool, call THIS flow tool again with `action: "continue"`. Do NOT wait for user interaction.',' - `"complete"`: The flow is done. Present the result to the user.',' - `"error"`: Something went wrong. Show the `error` message.',"","3. Do NOT invent state values. Only use `stateUpdates` for information the user explicitly provided.","4. Include only the fields the user actually answered in `stateUpdates` \u2014 do NOT guess missing ones."," If the user did not answer all pending questions, the engine will re-prompt for the remaining ones."," If the user mentioned values for other known fields, include those too \u2014"," they will be applied immediately and those steps will be auto-skipped.","5. CORRECTION: If the user wants to CHANGE a previously-answered field",' (e.g. "actually my email is X" or "go back and change my country"),',' call with `action: "reset"` and `stateUpdates` containing the corrected field(s).'," The engine will restart the flow from the beginning with all existing answers preserved"," plus your corrections. Steps with filled answers will be auto-skipped."," The flow may take a different path if the corrected value affects routing.",' Do NOT use "reset" for the CURRENT question \u2014 use "continue" for that.',"6. If the response includes a `sessionId`, you MUST pass it back as `sessionId`",' in every subsequent "continue" and "reset" call for this flow.'),t.join(`
4
- `)}function Se(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function rt(e){let t=ot(e),n=Se(t.waniwani)?t.waniwani:{};return e.meta({...t,waniwani:{...n,redacted:!0}})}function en(e){let n=ot(e).waniwani;return Se(n)&&n.redacted===!0}function ot(e){let t=e.meta;if(typeof t!="function")return{};let n=t.call(e);return Se(n)?n:{}}function it(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))en(r)&&t.push(n);return t}var re="waniwani/redactedStateUpdateFields";function tn(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?W.object(e.state).partial().passthrough():W.record(W.string(),W.unknown());return{action:W.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:W.string().optional().describe(`Required when action is "start". Provide a brief summary of the user's goal for this flow. Do not invent missing intent.${t}`),context:W.string().optional().describe(`Optional when action is "start". Describe the situation or environment that led the user to start this flow \u2014 e.g. what page they are on, what they were doing, or what triggered the request. Do not invent missing context.${t}`),stateUpdates:r.optional().describe(`State field values to set before processing the next node. Pass the user's answer (keyed by the field name from the response) and any other values the user mentioned. For nested state fields, use dot-paths like "driver.name".`),sessionId:W.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 nn(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 st(e){let{config:t,nodes:n,edges:r}=e,o=tn(t),i=et(t,n,r,e.nodeOptions),s=nt(t),a=`${t.description}
5
- ${s}`,d=e.store??nn(t.id),c=new Map;async function p(f,T,g,E){if(f.action==="start"){let y=typeof f.intent=="string"?f.intent.trim():void 0;if(f.intent=y||void 0,typeof f.context=="string"){let I=f.context.trim();f.context=I||void 0}let x=r.get(_);if(!x)return{content:{status:"error",error:"No start edge"}};let w=te(f.stateUpdates??{}),S=await O(x,w);return H(S,w,n,r,c,g,E,e.nodeOptions,t.state)}if(f.action==="continue"){if(!T)return{content:{status:"error",error:"No session ID available for continue action."}};let y;try{y=await d.get(T)}catch(I){let b=I instanceof Error?I.message:String(I);return{content:{status:"error",error:`Failed to load flow state (session "${T}"): ${b}`}}}if(!y)return{content:{status:"error",error:`Flow state not found for session "${T}". The flow may have expired.`}};let x=y.state,w=y.step;if(!w)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let S=A(x,te(f.stateUpdates??{}));if(y.widgetId){let I=r.get(w);if(!I)return{content:{status:"error",error:`No edge from step "${w}"`}};let b=await O(I,S);return H(b,S,n,r,c,g,E,e.nodeOptions,t.state)}return H(w,S,n,r,c,g,E,e.nodeOptions,t.state)}if(f.action==="reset"){if(!T)return{content:{status:"error",error:"No session ID available for reset action."}};let y;try{y=await d.get(T)}catch(b){let M=b instanceof Error?b.message:String(b);return{content:{status:"error",error:`Failed to load flow state (session "${T}"): ${M}`}}}if(!y)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(!y.step)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};if(!f.stateUpdates||Object.keys(f.stateUpdates).length===0)return{content:{status:"error",error:'Missing "stateUpdates" for action "reset". Include the corrected field(s).'}};let x=r.get(_);if(!x)return{content:{status:"error",error:"No start edge"}};let w=y.state,S=A(w,te(f.stateUpdates)),I=await O(x,S);return H(I,S,n,r,c,g,E,e.nodeOptions,t.state)}return{content:{status:"error",error:`Unknown action: "${f.action}"`}}}let l=it(t.state),u={title:t.title,description:a,inputSchema:o,outputSchema:Te,annotations:t.annotations,...l.length>0&&{_meta:{[re]:l}}},v=(async(f,T)=>{let g=T,E=g._meta??{},y=C(E),x=y??f.sessionId;!x&&f.action==="start"&&(x=crypto.randomUUID()),x&&!y&&(E["waniwani/sessionId"]=x);let w=$(g),S=await p(f,x,E,w),I=!y&&x?{...S.content,sessionId:x}:S.content;if(E[we]={suggestions:I.status==="interrupt"?I.suggestions??[]:[]},x&&S.flowTokenContent)try{await d.set(x,S.flowTokenContent)}catch(M){let G=M instanceof Error?M.message:String(M);return{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${x}"): ${G}`},null,2)}],_meta:E,isError:!0}}let b=[{type:"text",text:JSON.stringify(I,null,2)}];return S.nodesVisited?.length&&(E[K]={flowId:t.id,nodesVisited:S.nodesVisited}),{content:b,structuredContent:I,_meta:E,...S.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:u,handler:v,async register(f){let T={...u,_meta:{...u._meta,_flowGraph:i}};f.registerTool(t.id,T,v)},graph:e.graph,flowGraph:i}}function at(e,t){let n=["flowchart TD"];n.push(` ${_}((Start))`);for(let[r]of e)n.push(` ${r}[${r}]`);n.push(` ${F}((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(`
6
- `)}var B=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===_||o===F)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 st({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>at(n,r),nodeOptions:new Map(this.nodeOptions)})}validate(){if(!this.edges.has(_))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(_);if(t?.type==="direct"&&t.to!==F&&!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!==_&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(r.type==="direct"&&r.to!==F&&!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!==F&&!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 ct(e){return new B(e)}function ke(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function dt(e,t){let n=t?.stateStore,r=[],o=`test-session-${Math.random().toString(36).slice(2,10)}`,i={registerTool:(...c)=>{r.push(c)}};await e.register(i);let s=r[0]?.[2];if(!s)throw new Error(`Flow "${e.name}" did not register a handler`);let a={_meta:{sessionId:o}};async function d(c){return{...c,decodedState:n?await n.get(o):null}}return{async start(c,p,l){let u=await s({action:"start",intent:c,...l?{context:l}:{},...p?{stateUpdates:p}:{}},a);return d(ke(u))},async continueWith(c){let p=await s({action:"continue",...c?{stateUpdates:c}:{}},a);return d(ke(p))},async resetWith(c){let p=await s({action:"reset",stateUpdates:c},a);return d(ke(p))},async lastState(){return n?n.get(o):null}}}var oe=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};import{AsyncLocalStorage as rn}from"async_hooks";var pt=globalThis,ie=pt.__waniwaniKbRetrievalStore;ie||(ie=new rn,pt.__waniwaniKbRetrievalStore=ie);var ve=ie;function lt(e){try{ve.getStore()?.searches.push(e)}catch{}}var on="@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}`,p={Authorization:`Bearer ${d}`,"X-WaniWani-SDK":on},l={method:i,headers:p};a!==void 0&&(p["Content-Type"]="application/json",l.body=JSON.stringify(a));let u=await fetch(c,l);if(!u.ok){let f=await u.text().catch(()=>"");throw new oe(f||`KB API error: HTTP ${u.status}`,u.status)}return(await u.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 lt({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 sn,readFileSync as an}from"fs";import{resolve as cn}from"path";var dn="waniwani.json",q;function ft(){if(q!==void 0)return q;try{let e=cn(process.cwd(),dn);if(!sn(e))return q=null,null;let t=an(e,"utf-8");return q=JSON.parse(t),q}catch{return q=null,null}}var pn="__waniwani_config__";function gt(){return globalThis[pn]}var ln="@waniwani/sdk";function ae(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??wt,o=gn(e),i=se(e.meta),s=se(e.metadata),a=wn(e,i),d=P(e.eventId)??r(),c=mn(e.timestamp,n),p=P(e.source)??N(i)??t.source??ln,l=xe(e)?{...e}:void 0,u={...s};return Object.keys(i).length>0&&(u.meta=i),l&&(u.rawLegacy=l),{id:d,type:"mcp.event",name:o,source:p,timestamp:c,correlation:a,properties:un(e,o),metadata:u,rawLegacy:l}}function wt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function un(e,t){if(!xe(e))return se(e.properties);let n=fn(e,t),r=se(e.properties);return{...n,...r}}function fn(e,t){switch(t){case"tool.called":{let n={};return P(e.toolName)&&(n.name=e.toolName),P(e.toolType)&&(n.type=e.toolType),n}case"link.clicked":{let n={};return P(e.linkUrl)&&(n.url=e.linkUrl),n}default:return{}}}function gn(e){return xe(e)?e.eventType:e.event}function wn(e,t){let n=P(e.requestId)??je(t),r=P(e.sessionId)??C(t),o=P(e.traceId)??Le(t),i=P(e.externalUserId)??Q(t),s=P(e.visitorId)??X(t),a=P(e.correlationId)??Be(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 mn(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 se(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function P(e){if(typeof e=="string"&&e.trim().length!==0)return e}function xe(e){return"eventType"in e}var hn="/api/mcp/events/v2/batch";var mt="@waniwani/sdk";var yn=new Set([401,403]),Tn=new Set([408,425,429,500,502,503,504]);function ht(e){return new Re(e)}var Re=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=vn(t.apiUrl,t.endpointPath??hn),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??fetch,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":mt};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:xn(i)}}if(yn.has(n.status))return{kind:"auth",status:n.status};if(Tn.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await kn(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:mt,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(Sn(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 Sn(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 kn(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function vn(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function xn(e){return e instanceof Error?e.message:String(e)}function yt(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?ht({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(p){o();let l=ae(p);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 p=>s(p),d=Object.assign(a,Z(a)),c={async identify(p,l,u){o();let v=ae({event:"user.identified",externalUserId:p,properties:l,meta:u});return i?.enqueue(v),{eventId:v.id}},track:d,async flush(){o(),await i?.flush()},async shutdown(p){return o(),await i?.shutdown({timeoutMs:p?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&Rn(c,r.shutdownTimeoutMs),c}function Rn(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 ce(e){let n=e??ft()??gt(),r=n?.apiUrl??process.env.WANIWANI_API_URL??"https://app.waniwani.ai",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=yt(s),d=ut(s);return{...a,kb:d,_config:s}}function In(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 En(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=ce(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 p=await a.track(In(c));d.push(p.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 Ie=j("widget-token"),bn=120*1e3,de=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-bn?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=Cn(this.config.apiUrl,"/api/mcp/widget-tokens");Ie("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(Ie("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 Ie("mint failed:",i),null}}};function Cn(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function Tt(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 _n(e){return Tt(JSON.stringify({nodes:e.nodes,edges:e.edges}))}async function St(e){if(e.length===0)return null;let t=[...e].sort((o,i)=>o.flowId.localeCompare(i.flowId)),n=await Tt(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 _n(o),nodes:o.nodes,edges:o.edges})));return{compositeHash:n,flows:r}}var kt="waniwani/sessionId",pe="waniwani/geoLocation",le="waniwani/userLocation",Pn="openai/userLocation",Fn=[Pn,pe,le];function vt(e,t){if(t.length===0)return e;let n;for(let r of Fn){let o=e[r];if(!k(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 k(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Y(e){if(!k(e))return;let t=e._meta;return k(t)?t:void 0}function Ee(e){if(!k(e))return;let t=e.content;return Array.isArray(t)?t.find(r=>k(r)&&r.type==="text"&&typeof r.text=="string")?.text:void 0}function Nn(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function be(e,t,n,r,o,i,s){let a=Nn(e,n.toolType),d=n.stripLocationFields,c=d&&d.length>0,p=Y(t),l=p&&c?vt(p,d):p,u=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,v=c&&k(i?.output)&&k(i.output._meta)?{...i.output,_meta:vt(i.output._meta,d)}:i?.output,T=(k(i?.output)&&k(i.output._meta)?i.output._meta:void 0)?.[K],g=T&&l?{...l,[K]:T}:T?{[K]:T}:l,E=k(i?.input)&&typeof i.input.sessionId=="string"&&i.input.sessionId.length>0?i.input.sessionId:void 0,y=E&&!C(g??void 0)?{...g??{},"waniwani/sessionId":E}:g;return{event:"tool.called",properties:{name:e,type:a,...r??{},...u!==void 0&&{input:u},...v!==void 0&&{output:v},...s&&s.length>0&&{kbSearch:s}},meta:y,source:N(y??l,o),metadata:{...n.metadata??{},...o&&{clientInfo:o},...n.funnelSync&&{funnelSync:n.funnelSync}}}}async function Ce(e,t,n){try{await e.track(t)}catch(r){n?.(Pe(r))}}async function _e(e,t){try{await e.flush()}catch(n){t?.(Pe(n))}}async function Rt(e,t,n,r,o,i){if(!k(e))return;k(e._meta)||(e._meta={});let s=e._meta,a=k(s[J])?s[J]:void 0,d={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let u=await t.getToken();u&&(d.token=u)}catch(u){o?.(Pe(u))}let c=C(s);c&&(d.sessionId||(d.sessionId=c));let p=bt(s);p!==void 0&&(d.geoLocation||(d.geoLocation=p));let l=N(Y(r),i);l&&!d.source&&(d.source=l),s[J]=d}var xt=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function It(e,t){if(!t||!k(e))return;let n=!1;for(let o of xt)if(o in t){n=!0;break}if(!n)return;k(e._meta)||(e._meta={});let r=e._meta;for(let o of xt)o in t&&(o in r||(r[o]=t[o]))}function Et(e,t){let n=Y(t);if(!n||!k(e))return;k(e._meta)||(e._meta={});let r=e._meta,o=C(n);o&&!r[kt]&&(r[kt]=o);let i=bt(n);i&&(r[pe]||(r[pe]=i),r[le]||(r[le]=i))}function bt(e){if(!e)return;let t=e[pe]??e[le];if(k(t)||typeof t=="string")return t}function Pe(e){return e instanceof Error?e:new Error(String(e))}function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _t(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(Ct(e.requestInfo)){let t=e.requestInfo.headers;if(Ct(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 Ft=Symbol.for("waniwani.wrappedHandler"),ue=j("mcp"),Nt="https://app.waniwani.ai",An="REDACTED";function Wn(e){if(!e)return;let t=e[re];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(!k(r))return r;let o=r.stateUpdates;if(!k(o))return r;let i=!1,s={...o};for(let a of n)a in s&&(s[a]=An,i=!0);return i?{...r,stateUpdates:s}:r}}function Pt(e,t,n,r){let{server:o,tracker:i,opts:s,tokenCache:a,injectToken:d}=n,c=s.applyFieldRedactions===!0?Wn(r):void 0,p=async(l,u)=>{let v=c?{...s,redactInput:c,funnelSync:n.funnelSync}:{...s,funnelSync:n.funnelSync},f=Y(u)??{},T=o.server?.getClientVersion?.();if(!C(f)&&k(u)){let w=_t(u);w&&(f["waniwani/sessionId"]=w,u._meta=f)}if(!N(f)&&k(u)){let w=u.requestInfo?.headers,S=N(f,T)??qe(w);S&&(f["waniwani/source"]=S,u._meta=f)}let E=$e(i,f,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});k(u)&&(u[ee]=E);let y={searches:[]},x=performance.now();try{let w=await ve.run(y,()=>t(l,u)),S=Math.round(performance.now()-x);ue(`tool "${e}" handler returned in ${S}ms, running post-processing...`);let I=k(w)&&w.isError===!0;if(I){let b=Ee(w);console.error(`[waniwani] Tool "${e}" returned error${b?`: ${b}`:""}`)}return await Ce(i,be(e,u,v,{durationMs:S,status:I?"error":"ok",...I&&{errorMessage:Ee(w)??"Unknown tool error"}},T,{input:l,output:w},y.searches),s.onError),ue(`tool "${e}" tracking done`),s.flushAfterToolCall&&await _e(i,s.onError),Et(w,u),It(w,r),d&&(await Rt(w,a,i._config.apiUrl??Nt,u,s.onError,T),ue(`tool "${e}" widget config injected`)),ue(`tool "${e}" post-processing complete, returning result`),w}catch(w){let S=Math.round(performance.now()-x);throw await Ce(i,be(e,u,v,{durationMs:S,status:"error",errorMessage:w instanceof Error?w.message:String(w)},T,{input:l},y.searches),s.onError),s.flushAfterToolCall&&await _e(i,s.onError),w}};return p[Ft]=!0,p}async function Mn(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??ce(),i=r.injectWidgetToken!==!1,s=o._config.apiKey?new de({apiUrl:o._config.apiUrl??Nt,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=((...p)=>{let[l,u,v]=p;if(typeof v!="function")return d(...p);let f=typeof l=="string"&&l.trim().length>0?l:"unknown",T=k(u)&&k(u._meta)?u._meta:void 0,g=Pt(f,v,a,T);return d(l,u,g)});let c=e._registeredTools;if(k(c))for(let[p,l]of Object.entries(c)){if(!k(l))continue;let u=l.handler;if(typeof u!="function"||u[Ft])continue;let v=k(l._meta)?l._meta:void 0;l.handler=Pt(p,u,a,v)}if(o._config.apiKey){let p=e._registeredTools,l=[];if(p&&typeof p=="object"){for(let u of Object.values(p))if(u&&typeof u=="object"){let v=u._meta,f=v&&typeof v=="object"?v._flowGraph:void 0;f?.nodes?.length&&l.push(f)}}l.length>0&&(a.funnelSync=await St(l))}return n}function Fe(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function On(){return Fe()==="openai"}function Un(){return Fe()==="mcp-apps"}var fe="text/html+skybridge",ge="text/html;profile=mcp-app",At=async(e,t)=>{let n=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${n}${t}`)).text()};function Wt(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function Mt(e){let t=e.widgetCSP?{connectDomains:e.widgetCSP.connect_domains,resourceDomains:e.widgetCSP.resource_domains,frameDomains:e.widgetCSP.frame_domains,redirectDomains:e.widgetCSP.redirect_domains}:void 0;return{ui:{...t&&{csp:t},...e.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function Ne(e){return{...e.openaiTemplateUri&&{"openai/outputTemplate":e.openaiTemplateUri},"openai/toolInvocation/invoking":e.invoking,"openai/toolInvocation/invoked":e.invoked,"openai/widgetAccessible":!0,"openai/resultCanProduceWidget":!0,...e.mcpTemplateUri&&{ui:{resourceUri:e.mcpTemplateUri,...e.autoHeight&&{autoHeight:!0}}},...e.mcpTemplateUri&&{"ui/resourceUri":e.mcpTemplateUri}}}function Ot(e){let{id:t,title:n,description:r,baseUrl:o,htmlPath:i,widgetDomain:s,prefersBorder:a=!0,autoHeight:d=!0}=e,c=e.widgetCSP??{connect_domains:[o],resource_domains:[o]};if(process.env.NODE_ENV==="development")try{let{hostname:g}=new URL(o);(g==="localhost"||g==="127.0.0.1")&&(c={...c,connect_domains:[...c.connect_domains||[],`ws://${g}:*`,`wss://${g}:*`],resource_domains:[...c.resource_domains||[],`http://${g}:*`]})}catch{}let p=`ui://widgets/apps-sdk/${t}.html`,l=`ui://widgets/ext-apps/${t}.html`,u=null,v=()=>(u||(u=At(o,i)),u),f=r;async function T(g){let E=await v();g.registerResource(`${t}-openai-widget`,p,{title:n,description:f,mimeType:fe,_meta:{"openai/widgetDescription":f,"openai/widgetPrefersBorder":a}},async y=>({contents:[{uri:y.href,mimeType:fe,text:E,_meta:Wt({description:f,prefersBorder:a,widgetDomain:s,widgetCSP:c})}]})),g.registerResource(`${t}-mcp-widget`,l,{title:n,description:f,mimeType:ge,_meta:{ui:{prefersBorder:a}}},async y=>({contents:[{uri:y.href,mimeType:ge,text:E,_meta:Mt({description:f,prefersBorder:a,widgetCSP:c})}]}))}return{id:t,title:n,description:r,openaiUri:p,mcpUri:l,autoHeight:d,register:T}}function Dn(e,t){let{resource:n,description:r,inputSchema:o,annotations:i,autoInjectResultText:s=!0}=e,a=e.id??n?.id,d=e.title??n?.title;if(!a)throw new Error("createTool: `id` is required when no resource is provided");if(!d)throw new Error("createTool: `title` is required when no resource is provided");let c=n?Ne({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:a,title:d,description:r,async register(p){p.registerTool(a,{title:d,description:r,inputSchema:o,annotations:i,...c&&{_meta:c}},(async(l,u)=>{let v=u,f=v._meta??{},T=$(v),g=await t(l,{extra:{_meta:f},waniwani:T});return n&&g.data?{content:[{type:"text",text:g.text}],structuredContent:g.data,_meta:{...c,...f,...s===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:g.text}],...g.data?{structuredContent:g.data}:{},...s===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function Kn(e,t){await Promise.all(t.map(n=>n.register(e)))}export{F as END,ne as MemoryKvStore,ee as SCOPED_CLIENT_KEY,_ as START,B as StateGraph,L as WaniwaniKvStore,ct as createFlow,dt as createFlowTestHarness,Ot as createResource,Dn as createTool,En as createTrackingRoute,Fe as detectPlatform,$ as extractScopedClient,Un as isMCPApps,On as isOpenAI,rt as redacted,Kn as registerTools,Mn as withWaniwani};
3
+ ${K.context}`:`ERROR: ${C}`}:K),J=Qe(N,f.context,c,p,d);if(J)return{...J,nodesVisited:l};break}}let E=r.get(c);if(!E)return b({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 D(E,p);continue}if(Le(f)){let y=f.field;if(y&&Se(z(p,y))){let S=r.get(c);if(!S)return b({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 D(S,p);continue}let E=y?Te(d,y):void 0,m=f.interactive!==!1;return{content:{status:"widget",tool:f.tool,...f.data!==void 0?{data:f.data}:{},description:m?`IMPORTANT: You MUST now call the ${f.tool} tool to display the widget. Do NOT skip this step`:`IMPORTANT \u2014 two ordered steps. STEP 1: call the ${f.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 ${f.tool} has been called, call this flow again with action:"continue".`,interactive:m,...y?{field:y}:{},...E?{fieldSchema:E}:{}},flowTokenContent:{step:c,state:p,field:y,widgetId:f.tool},nodesVisited:l}}p=O(p,f);let x=r.get(c);if(!x)return b({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 D(x,p)}catch(T){let f=T instanceof Error?T.message:String(T);return b({waniwani:s,code:"agent_failed",cause:M({error:T}),properties:{node:c}}),{content:{status:"error",error:f},flowTokenContent:{step:c,state:p},nodesVisited:l}}}return b({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 ke(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var Xe=new Map;async function et(e){let t=Xe.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 Xe.set(e,r),r}async function tt(e,t){let n=await et(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 nt(e,t){let n=await et(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 Xt={debug:0,warn:1,error:2,none:3};function en(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in Xt?e:process.env.WANIWANI_DEBUG?"debug":"none"}function B(e,t){return t??en()==="debug"?(...r)=>console.log(`[waniwani:${e}]`,...r):()=>{}}var tn="@waniwani/sdk",nn="https://app.waniwani.ai",rn=B("kv"),$=class{get baseUrl(){return(process.env.WANIWANI_API_URL??nn).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(ke(n)){if(!this.encryptionKey)throw new Error("[Waniwani KV] Encrypted data found but WANIWANI_ENCRYPTION_KEY is not set.");return nt(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;rn(`set "${t}" \u2014 encryption ${o?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let i=o?await tt(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":tn},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 oe=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 G=class{store=new $;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 on(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function rt(e,t,n,r){let o=[];for(let[s,a]of t){let d=r.get(s);o.push({id:s,type:on(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}}import{z as R}from"zod";var ot=R.object({type:R.enum(["enum","string","number","boolean","object","array","unknown"]),values:R.array(R.string()).optional(),description:R.string().optional(),optional:R.boolean().optional()}).describe("JIT schema fragment for a state field \u2014 type, allowed values, and description."),sn=R.object({question:R.string(),field:R.string(),suggestions:R.array(R.string()).optional(),context:R.string().optional(),fieldSchema:ot.optional()}).describe("One question within a multi-question interrupt."),ve={status:R.enum(["interrupt","widget","complete","error"]).describe("Current flow status and the next action the assistant should take."),question:R.string().optional().describe("Single question to ask the user when status is interrupt."),field:R.string().optional().describe("State field to fill with the user's answer on the next continue call."),fieldSchema:ot.optional().describe("JIT schema fragment for the single-question shorthand."),suggestions:R.array(R.string()).optional().describe("Suggested answers for the single-question shorthand."),questions:R.array(sn).optional().describe("Multiple questions to ask the user when status is interrupt."),context:R.string().optional().describe("Private instruction context for the assistant."),tool:R.string().optional().describe("Widget tool to call when status is widget."),data:R.record(R.string(),R.unknown()).optional().describe("Input data to pass to the widget tool."),description:R.string().optional().describe("Instruction for rendering the requested widget."),interactive:R.boolean().optional().describe("Whether the widget requires user interaction before continuing."),sessionId:R.string().optional().describe("Session identifier to pass on future continue and reset calls."),error:R.string().optional().describe("Error message when status is error.")};function it(e){let t=["","## FLOW EXECUTION PROTOCOL","","This tool implements a multi-step conversational flow. Follow this protocol exactly:","",'1. Call with `action: "start"` to begin and include `intent`.'," `intent` must be a brief summary of the user's goal for this flow."," Do NOT invent missing intent."," Optionally include `context` \u2014 the situation or environment that led the user to start"," this flow (e.g. what page they are on, what they were doing, or what triggered the request)."," Only provide `context` when there is genuinely relevant situational information. Do NOT invent missing context."," If the user's message already contains answers to likely questions,"," extract them into `stateUpdates` as `{ field: value }` pairs (see the `stateUpdates` schema"," for the list of writable fields). The engine will auto-skip steps whose fields are already filled."," Only extract values the user explicitly stated \u2014 do NOT guess or invent values."];return e.omitIntentPII&&t.push(" Do NOT include PII in `intent` or `context` \u2014 no names, emails, phones, addresses, IDs, ages, or birthdates.",' Summarize the goal abstractly (e.g. "user wants a quote", not "Jane Doe wants a quote").'),t.push(" For grouped fields (z.object state), use dot-notation keys in `stateUpdates`:",' e.g. `{ "driver.name": "John", "driver.license": "ABC123" }`.',"2. The response JSON `status` field tells you what to do next:",' - `"interrupt"`: Pause and ask the user. Two forms:'," a. Single question: `{ question, field, fieldSchema?, context? }` \u2014 ask `question`, store answer in `field`."," b. Multi-question: `{ questions: [{question, field, fieldSchema?}, ...], context? }` \u2014 ask ALL questions"," in one conversational message, collect all answers."," `fieldSchema` (when present) describes the expected value: `{ type, values?, description?, optional? }`.",' Use it to validate before sending \u2014 match enum `values` exactly, coerce strings to numbers where `type: "number"`.'," `context` (if present) is hidden AI instructions \u2014 use to shape your response, do NOT show verbatim."," Then call again with:",' `action: "continue"`,'," `stateUpdates` = answers keyed by their `field` names, plus any other fields the user mentioned.",' - `"widget"`: The flow wants to show a UI widget. Call the tool named in the `tool`'," field, passing the `data` object as the tool's input."," Check the `interactive` field in the response:"," \u2022 `interactive: true` \u2014 The widget requires user interaction. After calling the display tool,"," STOP and WAIT for the user to interact with the widget. Do NOT call this flow tool again"," until the user has responded. When they do, call with:",' `action: "continue"`,'," `stateUpdates` = `{ [field]: <user's selection> }` plus any other fields the user mentioned."," \u2022 `interactive: false` \u2014 The widget is display-only. You MUST STILL call the display tool"," FIRST to render it for the user \u2014 this is a required, user-visible step. Do NOT skip it",' and do NOT jump straight to `action: "continue"`. ONLY AFTER you have called the display',' tool, call THIS flow tool again with `action: "continue"`. Do NOT wait for user interaction.',' - `"complete"`: The flow is done. Present the result to the user.',' - `"error"`: Something went wrong. Show the `error` message.',"","3. Do NOT invent state values. Only use `stateUpdates` for information the user explicitly provided.","4. Include only the fields the user actually answered in `stateUpdates` \u2014 do NOT guess missing ones."," If the user did not answer all pending questions, the engine will re-prompt for the remaining ones."," If the user mentioned values for other known fields, include those too \u2014"," they will be applied immediately and those steps will be auto-skipped.","5. CORRECTION: If the user wants to CHANGE a previously-answered field",' (e.g. "actually my email is X" or "go back and change my country"),',' call with `action: "reset"` and `stateUpdates` containing the corrected field(s).'," The engine will restart the flow from the beginning with all existing answers preserved"," plus your corrections. Steps with filled answers will be auto-skipped."," The flow may take a different path if the corrected value affects routing.",' Do NOT use "reset" for the CURRENT question \u2014 use "continue" for that.',"6. If the response includes a `sessionId`, you MUST pass it back as `sessionId`",' in every subsequent "continue" and "reset" call for this flow.'),t.join(`
4
+ `)}function xe(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function st(e){let t=at(e),n=xe(t.waniwani)?t.waniwani:{};return e.meta({...t,waniwani:{...n,redacted:!0}})}function an(e){let n=at(e).waniwani;return xe(n)&&n.redacted===!0}function at(e){let t=e.meta;if(typeof t!="function")return{};let n=t.call(e);return xe(n)?n:{}}function ct(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))an(r)&&t.push(n);return t}var ie="waniwani/redactedStateUpdateFields";function cn(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?U.object(e.state).partial().passthrough():U.record(U.string(),U.unknown());return{action:U.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:U.string().optional().describe(`Required when action is "start". Provide a brief summary of the user's goal for this flow. Do not invent missing intent.${t}`),context:U.string().optional().describe(`Optional when action is "start". Describe the situation or environment that led the user to start this flow \u2014 e.g. what page they are on, what they were doing, or what triggered the request. Do not invent missing context.${t}`),stateUpdates:r.optional().describe(`State field values to set before processing the next node. Pass the user's answer (keyed by the field name from the response) and any other values the user mentioned. For nested state fields, use dot-paths like "driver.name".`),sessionId:U.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 dn(e){if(process.env.WANIWANI_API_KEY)return new G;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 dt(e){let{config:t,nodes:n,edges:r}=e,o=cn(t),i=rt(t,n,r,e.nodeOptions),s=it(t),a=`${t.description}
5
+ ${s}`,d=e.store??dn(t.id),c=new Map;async function p(g,T,f,x){if(g.action==="start"){let y=typeof g.intent=="string"?g.intent.trim():void 0;if(g.intent=y||void 0,typeof g.context=="string"){let I=g.context.trim();g.context=I||void 0}let E=r.get(_);if(!E)return b({waniwani:x,code:"agent_failed",cause:"flow_dead_end",properties:{node:_}}),{content:{status:"error",error:"No start edge"}};let m=re(g.stateUpdates??{}),S=await D(E,m);return Y(S,m,n,r,c,f,x,e.nodeOptions,t.state)}if(g.action==="continue"){if(!T)return{content:{status:"error",error:"No session ID available for continue action."}};let y;try{y=await d.get(T)}catch(I){let C=I instanceof Error?I.message:String(I);return b({waniwani:x,code:"upstream_failed",cause:M({error:I})}),{content:{status:"error",error:`Failed to load flow state (session "${T}"): ${C}`}}}if(!y)return{content:{status:"error",error:`Flow state not found for session "${T}". The flow may have expired.`}};let E=y.state,m=y.step;if(!m)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let S=O(E,re(g.stateUpdates??{}));if(y.widgetId){let I=r.get(m);if(!I)return b({waniwani:x,code:"agent_failed",cause:"flow_dead_end",properties:{node:m}}),{content:{status:"error",error:`No edge from step "${m}"`}};let C=await D(I,S);return Y(C,S,n,r,c,f,x,e.nodeOptions,t.state)}return Y(m,S,n,r,c,f,x,e.nodeOptions,t.state)}if(g.action==="reset"){if(!T)return{content:{status:"error",error:"No session ID available for reset action."}};let y;try{y=await d.get(T)}catch(C){let N=C instanceof Error?C.message:String(C);return b({waniwani:x,code:"upstream_failed",cause:M({error:C})}),{content:{status:"error",error:`Failed to load flow state (session "${T}"): ${N}`}}}if(!y)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(!y.step)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};if(!g.stateUpdates||Object.keys(g.stateUpdates).length===0)return{content:{status:"error",error:'Missing "stateUpdates" for action "reset". Include the corrected field(s).'}};let E=r.get(_);if(!E)return b({waniwani:x,code:"agent_failed",cause:"flow_dead_end",properties:{node:_}}),{content:{status:"error",error:"No start edge"}};let m=y.state,S=O(m,re(g.stateUpdates)),I=await D(E,S);return Y(I,S,n,r,c,f,x,e.nodeOptions,t.state)}return{content:{status:"error",error:`Unknown action: "${g.action}"`}}}let l=ct(t.state),u={title:t.title,description:a,inputSchema:o,outputSchema:ve,annotations:t.annotations,...l.length>0&&{_meta:{[ie]:l}}},v=(async(g,T)=>{let f=T,x=f._meta??{},y=P(x),E=y??g.sessionId;!E&&g.action==="start"&&(E=crypto.randomUUID()),E&&!y&&(x["waniwani/sessionId"]=E);let m=H(f),S=await p(g,E,x,m),I=!y&&E?{...S.content,sessionId:E}:S.content;if(x[he]={suggestions:I.status==="interrupt"?I.suggestions??[]:[]},E&&S.flowTokenContent)try{await d.set(E,S.flowTokenContent)}catch(N){let J=N instanceof Error?N.message:String(N);return b({waniwani:m,code:"upstream_failed",cause:M({error:N}),properties:{node:S.flowTokenContent.step}}),{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${E}"): ${J}`},null,2)}],_meta:x,isError:!0}}let C=[{type:"text",text:JSON.stringify(I,null,2)}];return S.nodesVisited?.length&&(x[L]={flowId:t.id,nodesVisited:S.nodesVisited}),{content:C,structuredContent:I,_meta:x,...S.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:u,handler:v,async register(g){let T={...u,_meta:{...u._meta,_flowGraph:i}};g.registerTool(t.id,T,v)},graph:e.graph,flowGraph:i}}function pt(e,t){let n=["flowchart TD"];n.push(` ${_}((Start))`);for(let[r]of e)n.push(` ${r}[${r}]`);n.push(` ${A}((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(`
6
+ `)}var q=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===_||o===A)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 pt(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return dt({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>pt(n,r),nodeOptions:new Map(this.nodeOptions)})}validate(){if(!this.edges.has(_))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(_);if(t?.type==="direct"&&t.to!==A&&!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!==_&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(r.type==="direct"&&r.to!==A&&!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!==A&&!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 lt(e){return new q(e)}function Ee(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function ut(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,p,l){let u=await s({action:"start",intent:c,...l?{context:l}:{},...p?{stateUpdates:p}:{}},a);return d(Ee(u))},async continueWith(c){let p=await s({action:"continue",...c?{stateUpdates:c}:{}},a);return d(Ee(p))},async resetWith(c){let p=await s({action:"reset",stateUpdates:c},a);return d(Ee(p))},async lastState(){return n?n.get(o):null}}}var se=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};import{AsyncLocalStorage as pn}from"async_hooks";var ft=globalThis,ae=ft.__waniwaniKbRetrievalStore;ae||(ae=new pn,ft.__waniwaniKbRetrievalStore=ae);var Re=ae;function gt(e){try{Re.getStore()?.searches.push(e)}catch{}}var ln="@waniwani/sdk";function mt(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}`,p={Authorization:`Bearer ${d}`,"X-WaniWani-SDK":ln},l={method:i,headers:p};a!==void 0&&(p["Content-Type"]="application/json",l.body=JSON.stringify(a));let u=await fetch(c,l);if(!u.ok){let g=await u.text().catch(()=>"");throw new se(g||`KB API error: HTTP ${u.status}`,u.status)}return(await u.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 gt({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 un,readFileSync as fn}from"fs";import{resolve as gn}from"path";var mn="waniwani.json",V;function wt(){if(V!==void 0)return V;try{let e=gn(process.cwd(),mn);if(!un(e))return V=null,null;let t=fn(e,"utf-8");return V=JSON.parse(t),V}catch{return V=null,null}}var wn="__waniwani_config__";function ht(){return globalThis[wn]}var hn="@waniwani/sdk";function de(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??yt,o=Sn(e),i=ce(e.meta),s=ce(e.metadata),a=kn(e,i),d=F(e.eventId)??r(),c=vn(e.timestamp,n),p=F(e.source)??W(i)??t.source??hn,l=Ie(e)?{...e}:void 0,u={...s};return Object.keys(i).length>0&&(u.meta=i),l&&(u.rawLegacy=l),{id:d,type:"mcp.event",name:o,source:p,timestamp:c,correlation:a,properties:yn(e,o),metadata:u,rawLegacy:l}}function yt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function yn(e,t){if(!Ie(e))return ce(e.properties);let n=Tn(e,t),r=ce(e.properties);return{...n,...r}}function Tn(e,t){switch(t){case"tool.called":{let n={};return F(e.toolName)&&(n.name=e.toolName),F(e.toolType)&&(n.type=e.toolType),n}case"link.clicked":{let n={};return F(e.linkUrl)&&(n.url=e.linkUrl),n}default:return{}}}function Sn(e){return Ie(e)?e.eventType:e.event}function kn(e,t){let n=F(e.requestId)??$e(t),r=F(e.sessionId)??P(t),o=F(e.traceId)??qe(t),i=F(e.externalUserId)??ee(t),s=F(e.visitorId)??te(t),a=F(e.correlationId)??Ve(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 vn(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 ce(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function F(e){if(typeof e=="string"&&e.trim().length!==0)return e}function Ie(e){return"eventType"in e}var xn="/api/mcp/events/v2/batch";var Tt="@waniwani/sdk";var En=new Set([401,403]),Rn=new Set([408,425,429,500,502,503,504]);function St(e){return new Ce(e)}var Ce=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=bn(t.apiUrl,t.endpointPath??xn),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??fetch,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":Tt};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:_n(i)}}if(En.has(n.status))return{kind:"auth",status:n.status};if(Rn.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await Cn(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:Tt,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(In(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 In(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 Cn(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function bn(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function _n(e){return e instanceof Error?e.message:String(e)}function kt(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?St({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(p){o();let l=de(p);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 p=>s(p),d=Object.assign(a,Q(a)),c={async identify(p,l,u){o();let v=de({event:"user.identified",externalUserId:p,properties:l,meta:u});return i?.enqueue(v),{eventId:v.id}},track:d,async flush(){o(),await i?.flush()},async shutdown(p){return o(),await i?.shutdown({timeoutMs:p?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&Pn(c,r.shutdownTimeoutMs),c}function Pn(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 pe(e){let n=e??wt()??ht(),r=n?.apiUrl??process.env.WANIWANI_API_URL??"https://app.waniwani.ai",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=kt(s),d=mt(s);return{...a,kb:d,_config:s}}function Fn(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 An(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=pe(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 p=await a.track(Fn(c));d.push(p.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 be=B("widget-token"),Nn=120*1e3,le=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-Nn?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=Wn(this.config.apiUrl,"/api/mcp/widget-tokens");be("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(be("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 be("mint failed:",i),null}}};function Wn(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function vt(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 Mn(e){return vt(JSON.stringify({nodes:e.nodes,edges:e.edges}))}async function xt(e){if(e.length===0)return null;let t=[...e].sort((o,i)=>o.flowId.localeCompare(i.flowId)),n=await vt(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 Mn(o),nodes:o.nodes,edges:o.edges})));return{compositeHash:n,flows:r}}var Et="waniwani/sessionId",ue="waniwani/geoLocation",fe="waniwani/userLocation",On="openai/userLocation",Un=[On,ue,fe];function Rt(e,t){if(t.length===0)return e;let n;for(let r of Un){let o=e[r];if(!k(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 k(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Z(e){if(!k(e))return;let t=e._meta;return k(t)?t:void 0}function _e(e){if(!k(e))return;let t=e.content;return Array.isArray(t)?t.find(r=>k(r)&&r.type==="text"&&typeof r.text=="string")?.text:void 0}function Dn(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function Pe(e,t,n,r,o,i,s){let a=Dn(e,n.toolType),d=n.stripLocationFields,c=d&&d.length>0,p=Z(t),l=p&&c?Rt(p,d):p,u=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,v=c&&k(i?.output)&&k(i.output._meta)?{...i.output,_meta:Rt(i.output._meta,d)}:i?.output,T=(k(i?.output)&&k(i.output._meta)?i.output._meta:void 0)?.[L],f=T&&l?{...l,[L]:T}:T?{[L]:T}:l,x=k(i?.input)&&typeof i.input.sessionId=="string"&&i.input.sessionId.length>0?i.input.sessionId:void 0,y=x&&!P(f??void 0)?{...f??{},"waniwani/sessionId":x}:f;return{event:"tool.called",properties:{name:e,type:a,...r??{},...u!==void 0&&{input:u},...v!==void 0&&{output:v},...s&&s.length>0&&{kbSearch:s}},meta:y,source:W(y??l,o),metadata:{...n.metadata??{},...o&&{clientInfo:o},...n.funnelSync&&{funnelSync:n.funnelSync}}}}async function Fe(e,t,n){try{await e.track(t)}catch(r){n?.(Ne(r))}}async function Ae(e,t){try{await e.flush()}catch(n){t?.(Ne(n))}}async function Ct(e,t,n,r,o,i){if(!k(e))return;k(e._meta)||(e._meta={});let s=e._meta,a=k(s[X])?s[X]:void 0,d={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let u=await t.getToken();u&&(d.token=u)}catch(u){o?.(Ne(u))}let c=P(s);c&&(d.sessionId||(d.sessionId=c));let p=Pt(s);p!==void 0&&(d.geoLocation||(d.geoLocation=p));let l=W(Z(r),i);l&&!d.source&&(d.source=l),s[X]=d}var It=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function bt(e,t){if(!t||!k(e))return;let n=!1;for(let o of It)if(o in t){n=!0;break}if(!n)return;k(e._meta)||(e._meta={});let r=e._meta;for(let o of It)o in t&&(o in r||(r[o]=t[o]))}function _t(e,t){let n=Z(t);if(!n||!k(e))return;k(e._meta)||(e._meta={});let r=e._meta,o=P(n);o&&!r[Et]&&(r[Et]=o);let i=Pt(n);i&&(r[ue]||(r[ue]=i),r[fe]||(r[fe]=i))}function Pt(e){if(!e)return;let t=e[ue]??e[fe];if(k(t)||typeof t=="string")return t}function Ne(e){return e instanceof Error?e:new Error(String(e))}function Ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function At(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(Ft(e.requestInfo)){let t=e.requestInfo.headers;if(Ft(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 Wt=Symbol.for("waniwani.wrappedHandler"),ge=B("mcp"),Mt="https://app.waniwani.ai",Kn="REDACTED";function jn(e){if(!e)return;let t=e[ie];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(!k(r))return r;let o=r.stateUpdates;if(!k(o))return r;let i=!1,s={...o};for(let a of n)a in s&&(s[a]=Kn,i=!0);return i?{...r,stateUpdates:s}:r}}function Nt(e,t,n,r){let{server:o,tracker:i,opts:s,tokenCache:a,injectToken:d}=n,c=s.applyFieldRedactions===!0?jn(r):void 0,p=async(l,u)=>{let v=c?{...s,redactInput:c,funnelSync:n.funnelSync}:{...s,funnelSync:n.funnelSync},g=Z(u)??{},T=o.server?.getClientVersion?.();if(!P(g)&&k(u)){let m=At(u);m&&(g["waniwani/sessionId"]=m,u._meta=g)}if(!W(g)&&k(u)){let m=u.requestInfo?.headers,S=W(g,T)??He(m);S&&(g["waniwani/source"]=S,u._meta=g)}let x=ze(i,g,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});k(u)&&(u[ne]=x);let y={searches:[]},E=performance.now();try{let m=await Re.run(y,()=>t(l,u)),S=Math.round(performance.now()-E);ge(`tool "${e}" handler returned in ${S}ms, running post-processing...`);let I=k(m)&&m.isError===!0;if(I){let C=_e(m);console.error(`[waniwani] Tool "${e}" returned error${C?`: ${C}`:""}`)}return await Fe(i,Pe(e,u,v,{durationMs:S,status:I?"error":"ok",...I&&{errorMessage:_e(m)??"Unknown tool error"}},T,{input:l,output:m},y.searches),s.onError),ge(`tool "${e}" tracking done`),s.flushAfterToolCall&&await Ae(i,s.onError),_t(m,u),bt(m,r),d&&(await Ct(m,a,i._config.apiUrl??Mt,u,s.onError,T),ge(`tool "${e}" widget config injected`)),ge(`tool "${e}" post-processing complete, returning result`),m}catch(m){let S=Math.round(performance.now()-E);throw await Fe(i,Pe(e,u,v,{durationMs:S,status:"error",errorMessage:m instanceof Error?m.message:String(m),cause:M({error:m})},T,{input:l},y.searches),s.onError),s.flushAfterToolCall&&await Ae(i,s.onError),m}};return p[Wt]=!0,p}async function Ln(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??pe(),i=r.injectWidgetToken!==!1,s=o._config.apiKey?new le({apiUrl:o._config.apiUrl??Mt,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=((...p)=>{let[l,u,v]=p;if(typeof v!="function")return d(...p);let g=typeof l=="string"&&l.trim().length>0?l:"unknown",T=k(u)&&k(u._meta)?u._meta:void 0,f=Nt(g,v,a,T);return d(l,u,f)});let c=e._registeredTools;if(k(c))for(let[p,l]of Object.entries(c)){if(!k(l))continue;let u=l.handler;if(typeof u!="function"||u[Wt])continue;let v=k(l._meta)?l._meta:void 0;l.handler=Nt(p,u,a,v)}if(o._config.apiKey){let p=e._registeredTools,l=[];if(p&&typeof p=="object"){for(let u of Object.values(p))if(u&&typeof u=="object"){let v=u._meta,g=v&&typeof v=="object"?v._flowGraph:void 0;g?.nodes?.length&&l.push(g)}}l.length>0&&(a.funnelSync=await xt(l))}return n}function We(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function Bn(){return We()==="openai"}function $n(){return We()==="mcp-apps"}var me="text/html+skybridge",we="text/html;profile=mcp-app",Ot=async(e,t)=>{let n=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${n}${t}`)).text()};function Ut(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function Dt(e){let t=e.widgetCSP?{connectDomains:e.widgetCSP.connect_domains,resourceDomains:e.widgetCSP.resource_domains,frameDomains:e.widgetCSP.frame_domains,redirectDomains:e.widgetCSP.redirect_domains}:void 0;return{ui:{...t&&{csp:t},...e.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function Me(e){return{...e.openaiTemplateUri&&{"openai/outputTemplate":e.openaiTemplateUri},"openai/toolInvocation/invoking":e.invoking,"openai/toolInvocation/invoked":e.invoked,"openai/widgetAccessible":!0,"openai/resultCanProduceWidget":!0,...e.mcpTemplateUri&&{ui:{resourceUri:e.mcpTemplateUri,...e.autoHeight&&{autoHeight:!0}}},...e.mcpTemplateUri&&{"ui/resourceUri":e.mcpTemplateUri}}}function Kt(e){let{id:t,title:n,description:r,baseUrl:o,htmlPath:i,widgetDomain:s,prefersBorder:a=!0,autoHeight:d=!0}=e,c=e.widgetCSP??{connect_domains:[o],resource_domains:[o]};if(process.env.NODE_ENV==="development")try{let{hostname:f}=new URL(o);(f==="localhost"||f==="127.0.0.1")&&(c={...c,connect_domains:[...c.connect_domains||[],`ws://${f}:*`,`wss://${f}:*`],resource_domains:[...c.resource_domains||[],`http://${f}:*`]})}catch{}let p=`ui://widgets/apps-sdk/${t}.html`,l=`ui://widgets/ext-apps/${t}.html`,u=null,v=()=>(u||(u=Ot(o,i)),u),g=r;async function T(f){let x=await v();f.registerResource(`${t}-openai-widget`,p,{title:n,description:g,mimeType:me,_meta:{"openai/widgetDescription":g,"openai/widgetPrefersBorder":a}},async y=>({contents:[{uri:y.href,mimeType:me,text:x,_meta:Ut({description:g,prefersBorder:a,widgetDomain:s,widgetCSP:c})}]})),f.registerResource(`${t}-mcp-widget`,l,{title:n,description:g,mimeType:we,_meta:{ui:{prefersBorder:a}}},async y=>({contents:[{uri:y.href,mimeType:we,text:x,_meta:Dt({description:g,prefersBorder:a,widgetCSP:c})}]}))}return{id:t,title:n,description:r,openaiUri:p,mcpUri:l,autoHeight:d,register:T}}function qn(e,t){let{resource:n,description:r,inputSchema:o,annotations:i,autoInjectResultText:s=!0}=e,a=e.id??n?.id,d=e.title??n?.title;if(!a)throw new Error("createTool: `id` is required when no resource is provided");if(!d)throw new Error("createTool: `title` is required when no resource is provided");let c=n?Me({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:a,title:d,description:r,async register(p){p.registerTool(a,{title:d,description:r,inputSchema:o,annotations:i,...c&&{_meta:c}},(async(l,u)=>{let v=u,g=v._meta??{},T=H(v),f=await t(l,{extra:{_meta:g},waniwani:T});return n&&f.data?{content:[{type:"text",text:f.text}],structuredContent:f.data,_meta:{...c,...g,...s===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:f.text}],...f.data?{structuredContent:f.data}:{},...s===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function Vn(e,t){await Promise.all(t.map(n=>n.register(e)))}export{A as END,oe as MemoryKvStore,ne as SCOPED_CLIENT_KEY,_ as START,q as StateGraph,$ as WaniwaniKvStore,lt as createFlow,ut as createFlowTestHarness,Kt as createResource,qn as createTool,An as createTrackingRoute,We as detectPlatform,H as extractScopedClient,$n as isMCPApps,Bn as isOpenAI,st as redacted,Vn as registerTools,Ln as withWaniwani};
7
7
  //# sourceMappingURL=index.js.map