@waniwani/sdk 0.11.2 → 0.11.3

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.
@@ -756,12 +756,16 @@ type NodeHandler<TState> = (ctx: NodeContext<TState>) => MaybePromise<DeepPartia
756
756
  */
757
757
  type ConditionFn<TState> = (state: Partial<TState>) => string | Promise<string>;
758
758
  type NodeOptions = {
759
- trackFunnel?: true | string;
759
+ /** Human-readable label for this node (used in funnel visualization and Graphs). */
760
+ label: string;
761
+ /** When true, this node is excluded from funnel analytics. */
762
+ hideFromFunnel?: boolean;
760
763
  };
761
764
  type FlowGraphNode = {
762
765
  id: string;
763
766
  type: "widget" | "interrupt" | "action";
764
- trackFunnel: false | true | string;
767
+ label: string;
768
+ hideFromFunnel?: boolean;
765
769
  };
766
770
  type FlowGraphEdge = {
767
771
  from: string;
package/dist/mcp/index.js CHANGED
@@ -1,7 +1,7 @@
1
- function ie(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function mt(){return ie()==="openai"}function ht(){return ie()==="mcp-apps"}var C="__start__",_="__end__",Se=Symbol.for("waniwani.flow.interrupt"),ve=Symbol.for("waniwani.flow.widget");function Re(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:Se,questions:r,context:n}}function xe(e,t){return{__type:ve,tool:typeof e=="string"?e:e.id,...t}}function Ee(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Se}function Ie(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===ve}import{z as M}from"zod";var se="waniwani/client";function V(e){if(typeof e=="object"&&e!==null)return e[se]}function be(e,t,n){return{track(r){return e.track({...r,meta:{...t,...r.meta}})},identify(r,o){return e.identify(r,o,t)},kb:e.kb,_config:n}}function K(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var yt=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],Tt=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],kt=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],St=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],vt=["correlationId","openai/requestId"];function P(e){return e?K(e,yt):void 0}function Ce(e){return e?K(e,Tt):void 0}function _e(e){return e?K(e,kt):void 0}function Pe(e){return e?K(e,St):void 0}function Fe(e){return e?K(e,vt):void 0}var Rt=[{key:"waniwani/sessionId",source:"chatbar"},{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}];function j(e){if(!e)return;let t=e["waniwani/source"];if(typeof t=="string"&&t.length>0)return t;for(let{key:n,source:r}of Rt){let o=e[n];if(typeof o=="string"&&o.length>0)return r}}function We(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function $(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 xt(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 Ae(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 z(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?xt(t,n,r):t[n]=r;return t}function W(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]=W(n[r],o):n[r]=o;return n}function ae(e){return e!=null&&e!==""}async function A(e,t){return e.type==="direct"?e.to:e.condition(t)}function Me(e,t,n,r){if(e.every(p=>ae($(r,p.field))))return null;let o=e.filter(p=>!ae($(r,p.field))),i=o.length===1,s=o[0];return{content:i&&s?{status:"interrupt",question:s.question,field:s.field,...s.suggestions?{suggestions:s.suggestions}:{},...s.context||t?{context:s.context??t}:{}}:{status:"interrupt",questions:o,...t?{context:t}:{}},flowTokenContent:{step:n,state:r,...i&&s?{field:s.field}:{}}}}async function L(e,t,n,r,o,i,s,a,p){let c=e,d={...t},u=50,f=0;for(;f++<u;){if(c===_)return{content:{status:"complete"},flowTokenContent:{state:d}};let y=n.get(c);if(!y)return{content:{status:"error",error:`Unknown node: "${c}"`}};a?.get(c)?.trackFunnel&&s&&s.track({event:"flow.node_reached",properties:{flowId:p??"unknown",nodeId:c}}).catch(()=>{});try{let l=await y({state:d,meta:i,interrupt:Re,showWidget:xe,waniwani:s});if(Ee(l)){for(let S of l.questions)S.validate&&o.set(`${c}:${S.field}`,S.validate);let T=Me(l.questions,l.context,c,d);if(T)return T;for(let S of l.questions){let R=o.get(`${c}:${S.field}`);if(R)try{let x=$(d,S.field),I=await R(x);I&&typeof I=="object"&&(d=W(d,I))}catch(x){let I=x instanceof Error?x.message:String(x);Ae(d,S.field);let F=l.questions.map(N=>N.field===S.field?{...N,context:N.context?`ERROR: ${I}
1
+ function oe(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function wt(){return oe()==="openai"}function mt(){return oe()==="mcp-apps"}var b="__start__",C="__end__",ke=Symbol.for("waniwani.flow.interrupt"),Se=Symbol.for("waniwani.flow.widget");function ve(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:ke,questions:r,context:n}}function Re(e,t){return{__type:Se,tool:typeof e=="string"?e:e.id,...t}}function xe(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===ke}function Ee(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Se}import{z as N}from"zod";var ie="waniwani/client";function H(e){if(typeof e=="object"&&e!==null)return e[ie]}function Ie(e,t,n){return{track(r){return e.track({...r,meta:{...t,...r.meta}})},identify(r,o){return e.identify(r,o,t)},kb:e.kb,_config:n}}function K(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var ht=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],yt=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Tt=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],kt=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],St=["correlationId","openai/requestId"];function F(e){return e?K(e,ht):void 0}function be(e){return e?K(e,yt):void 0}function Ce(e){return e?K(e,Tt):void 0}function _e(e){return e?K(e,kt):void 0}function Fe(e){return e?K(e,St):void 0}var vt=[{key:"waniwani/sessionId",source:"chatbar"},{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}];function j(e){if(!e)return;let t=e["waniwani/source"];if(typeof t=="string"&&t.length>0)return t;for(let{key:n,source:r}of vt){let o=e[n];if(typeof o=="string"&&o.length>0)return r}}function Pe(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function $(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 Rt(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 We(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 V(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?Rt(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 se(e){return e!=null&&e!==""}async function M(e,t){return e.type==="direct"?e.to:e.condition(t)}function Ae(e,t,n,r){if(e.every(p=>se($(r,p.field))))return null;let o=e.filter(p=>!se($(r,p.field))),i=o.length===1,s=o[0];return{content:i&&s?{status:"interrupt",question:s.question,field:s.field,...s.suggestions?{suggestions:s.suggestions}:{},...s.context||t?{context:s.context??t}:{}}:{status:"interrupt",questions:o,...t?{context:t}:{}},flowTokenContent:{step:n,state:r,...i&&s?{field:s.field}:{}}}}async function L(e,t,n,r,o,i,s,a,p){let c=e,d={...t},u=50,g=0;for(;g++<u;){if(c===C)return{content:{status:"complete"},flowTokenContent:{state:d}};let y=n.get(c);if(!y)return{content:{status:"error",error:`Unknown node: "${c}"`}};s&&!a?.get(c)?.hideFromFunnel&&s.track({event:"flow.node_reached",properties:{flowId:p??"unknown",nodeId:c}}).catch(()=>{});try{let w=await y({state:d,meta:i,interrupt:ve,showWidget:Re,waniwani:s});if(xe(w)){for(let f of w.questions)f.validate&&o.set(`${c}:${f.field}`,f.validate);let R=Ae(w.questions,w.context,c,d);if(R)return R;for(let f of w.questions){let E=o.get(`${c}:${f.field}`);if(E)try{let S=$(d,f.field),x=await E(S);x&&typeof x=="object"&&(d=A(d,x))}catch(S){let x=S instanceof Error?S.message:String(S);We(d,f.field);let _=w.questions.map(W=>W.field===f.field?{...W,context:W.context?`ERROR: ${x}
2
2
 
3
- ${N.context}`:`ERROR: ${I}`}:N),H=Me(F,l.context,c,d);if(H)return H;break}}let w=r.get(c);if(!w)return{content:{status:"error",error:`No outgoing edge from node "${c}"`}};c=await A(w,d);continue}if(Ie(l)){let T=l.field;if(T&&ae($(d,T))){let w=r.get(c);if(!w)return{content:{status:"error",error:`No outgoing edge from node "${c}"`}};c=await A(w,d);continue}return{content:{status:"widget",tool:l.tool,data:l.data,description:l.description,interactive:l.interactive!==!1},flowTokenContent:{step:c,state:d,field:T,widgetId:l.tool}}}d=W(d,l);let E=r.get(c);if(!E)return{content:{status:"error",error:`No outgoing edge from node "${c}"`}};c=await A(E,d)}catch(v){return{content:{status:"error",error:v instanceof Error?v.message:String(v)},flowTokenContent:{step:c,state:d}}}}return{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"}}}function ce(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var Ne=new Map;async function Ue(e){let t=Ne.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 Ne.set(e,r),r}async function De(e,t){let n=await Ue(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 Oe(e,t){let n=await Ue(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 Et={debug:0,warn:1,error:2,none:3};function It(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in Et?e:process.env.WANIWANI_DEBUG?"debug":"none"}function U(e,t){return t??It()==="debug"?(...r)=>console.log(`[waniwani:${e}]`,...r):()=>{}}var bt="@waniwani/sdk",Ct="https://app.waniwani.ai",_t=U("kv"),D=class{get baseUrl(){return(process.env.WANIWANI_API_URL??Ct).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(ce(n)){if(!this.encryptionKey)throw new Error("[WaniWani KV] Encrypted data found but WANIWANI_ENCRYPTION_KEY is not set.");return Oe(n,this.encryptionKey)}return n}async set(t,n){if(!this.apiKey)throw new Error("[WaniWani KV] No API key configured. Set WANIWANI_API_KEY env var.");let r=this.encryptionKey;_t(`set "${t}" \u2014 encryption ${r?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let o=r?await De(n,r):n;await this.request("/api/mcp/redis/set",{key:t,value:o})}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":bt},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 q=class{store=new D;get(t){return this.store.get(t)}set(t,n){return this.store.set(t,n)}delete(t){return this.store.delete(t)}};function Pt(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function Ft(e,t){let n=e.toString(),r=[];for(let o of t){let i=`"${o}"`,s=`'${o}'`,a=`\`${o}\``;(n.includes(i)||n.includes(s)||n.includes(a))&&r.push(o)}return r}function Ke(e,t,n,r){let o=new Set([...t.keys(),_]),i=[];for(let[a,p]of t){let c=r.get(a);i.push({id:a,type:Pt(p),trackFunnel:c?.trackFunnel??!1})}let s=[];for(let[a,p]of n)if(p.type==="direct")s.push({from:a,to:p.to,type:"direct"});else{let c=Ft(p.condition,o);s.push({from:a,to:c,type:"conditional"})}return{flowId:e.id,title:e.title,nodes:i,edges:s}}function je(e){let t=e.description??"",n=e._zod?.def;if(n?.type==="enum"&&n.entries){let r=Object.keys(n.entries).map(o=>`"${o}"`).join(" | ");return t?`${r} \u2014 ${t}`:r}return t}function $e(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."," 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."];if(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").'),e.state){let n=[];for(let[r,o]of Object.entries(e.state)){let i=We(o);if(i){let s=o.description??"",a=Object.entries(i).map(([p,c])=>{let d=je(c);return d?`\`${r}.${p}\` (${d})`:`\`${r}.${p}\``}).join(", ");n.push(s?`\`${r}\` (${s}): ${a}`:`\`${r}\`: ${a}`)}else{let s=je(o);n.push(s?`\`${r}\` (${s})`:`\`${r}\``)}}t.push(` Known fields: ${n.join(", ")}.`)}return t.push(" For grouped fields (shown as `group.subfield`), 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, context? }` \u2014 ask `question`, store answer in `field`."," b. Multi-question: `{ questions: [{question, field}, ...], context? }` \u2014 ask ALL questions"," in one conversational message, collect all answers."," `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. Call the display tool, then immediately",' 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 de(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Le(e){let t=qe(e),n=de(t.waniwani)?t.waniwani:{};return e.meta({...t,waniwani:{...n,redacted:!0}})}function Wt(e){let n=qe(e).waniwani;return de(n)&&n.redacted===!0}function qe(e){let t=e.meta;if(typeof t!="function")return{};let n=t.call(e);return de(n)?n:{}}function Be(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))Wt(r)&&t.push(n);return t}var G="waniwani/redactedStateUpdateFields";function At(e){let t=e.omitIntentPII?" Do not include PII (names, emails, phones, addresses, IDs, ages, birthdates) \u2014 summarize abstractly.":"";return{action:M.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:M.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:M.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:M.record(M.string(),M.unknown()).optional().describe("State field values to set before processing the next node. Use this to pass the user's answer (keyed by the field name from the response) and any other values the user mentioned."),sessionId:M.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 He(e){let{config:t,nodes:n,edges:r}=e,o=At(t),i=Ke(t,n,r,e.nodeOptions),s=$e(t),a=`${t.description}
5
- ${s}`,p=e.store??new q,c=new Map;async function d(g,v,l,E){if(g.action==="start"){let T=typeof g.intent=="string"?g.intent.trim():void 0;if(!T)return{content:{status:"error",error:`Missing required "intent" for action "start". Include a brief summary of the user's goal for this flow and any relevant prior context that led to triggering it, if available.`}};if(g.intent=T,typeof g.context=="string"){let x=g.context.trim();g.context=x||void 0}let w=r.get(C);if(!w)return{content:{status:"error",error:"No start edge"}};let S=z(g.stateUpdates??{}),R=await A(w,S);return L(R,S,n,r,c,l,E,e.nodeOptions,t.id)}if(g.action==="continue"){if(!v)return{content:{status:"error",error:"No session ID available for continue action."}};let T;try{T=await p.get(v)}catch(x){let I=x instanceof Error?x.message:String(x);return{content:{status:"error",error:`Failed to load flow state (session "${v}"): ${I}`}}}if(!T)return{content:{status:"error",error:`Flow state not found for session "${v}". The flow may have expired.`}};let w=T.state,S=T.step;if(!S)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let R=W(w,z(g.stateUpdates??{}));if(T.widgetId){let x=r.get(S);if(!x)return{content:{status:"error",error:`No edge from step "${S}"`}};let I=await A(x,R);return L(I,R,n,r,c,l,E,e.nodeOptions,t.id)}return L(S,R,n,r,c,l,E,e.nodeOptions,t.id)}if(g.action==="reset"){if(!v)return{content:{status:"error",error:"No session ID available for reset action."}};let T;try{T=await p.get(v)}catch(I){let F=I instanceof Error?I.message:String(I);return{content:{status:"error",error:`Failed to load flow state (session "${v}"): ${F}`}}}if(!T)return{content:{status:"error",error:`Flow state not found for session "${v}". The flow may have completed or expired. 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 w=r.get(C);if(!w)return{content:{status:"error",error:"No start edge"}};let S=T.state,R=W(S,z(g.stateUpdates)),x=await A(w,R);return L(x,R,n,r,c,l,E,e.nodeOptions,t.id)}return{content:{status:"error",error:`Unknown action: "${g.action}"`}}}let u=Be(t.state),f={title:t.title,description:a,inputSchema:o,annotations:t.annotations,...u.length>0&&{_meta:{[G]:u}}},y=(async(g,v)=>{let l=v,E=l._meta??{},T=P(E),w=T??g.sessionId;!w&&g.action==="start"&&(w=crypto.randomUUID(),E["waniwani/sessionId"]=w);let S=V(l),R=await d(g,w,E,S);if(w)if(R.flowTokenContent&&R.content.status!=="complete")try{await p.set(w,R.flowTokenContent)}catch(F){let H=F instanceof Error?F.message:String(F);return{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${w}"): ${H}`},null,2)}],_meta:E,isError:!0}}else R.content.status==="complete"&&await p.delete(w);let x=!T&&w?{...R.content,sessionId:w}:R.content;return{content:[{type:"text",text:JSON.stringify(x,null,2)}],_meta:E,...R.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:f,handler:y,async register(g){let v={...f,_meta:{...f._meta,_flowGraph:i}};g.registerTool(t.id,v,y)},graph:e.graph,flowGraph:i}}function Ve(e,t){let n=["flowchart TD"];n.push(` ${C}((Start))`);for(let[r]of e)n.push(` ${r}[${r}]`);n.push(` ${_}((End))`);for(let[r,o]of t)o.type==="direct"?n.push(` ${r} --> ${o.to}`):n.push(` ${r} -.-> ${r}_branch([?])`);return n.join(`
6
- `)}var O=class{nodes=new Map;edges=new Map;nodeOptions=new Map;config;constructor(t){this.config=t}addNode(t,n,r){if(t===C||t===_)throw new Error(`"${t}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(t))throw new Error(`Node "${t}" already exists`);return this.nodes.set(t,n),r&&this.nodeOptions.set(t,r),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){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge.`);return this.edges.set(t,{type:"conditional",condition:n}),this}graph(){return Ve(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return He({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>Ve(n,r),nodeOptions:new Map(this.nodeOptions)})}validate(){if(!this.edges.has(C))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(C);if(t?.type==="direct"&&t.to!==_&&!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!==C&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(r.type==="direct"&&r.to!==_&&!this.nodes.has(r.to))throw new Error(`Edge from "${n}" references non-existent node: "${r.to}"`)}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 ze(e){return new O(e)}function pe(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function Ge(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 p(c){return{...c,decodedState:n?await n.get(o):null}}return{async start(c,d,u){let f=await s({action:"start",intent:c,...u?{context:u}:{},...d?{stateUpdates:d}:{}},a);return p(pe(f))},async continueWith(c){let d=await s({action:"continue",...c?{stateUpdates:c}:{}},a);return p(pe(d))},async resetWith(c){let d=await s({action:"reset",stateUpdates:c},a);return p(pe(d))},async lastState(){return n?n.get(o):null}}}var Y="text/html+skybridge",Z="text/html;profile=mcp-app",Ye=async(e,t)=>{let n=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${n}${t}`)).text()};function Ze(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function Je(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.widgetDomain&&{domain:e.widgetDomain},...e.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function ue(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 Xe(e){let{id:t,title:n,description:r,baseUrl:o,htmlPath:i,widgetDomain:s,prefersBorder:a=!0,autoHeight:p=!0}=e,c=e.widgetCSP??{connect_domains:[o],resource_domains:[o]};if(process.env.NODE_ENV==="development")try{let{hostname:l}=new URL(o);(l==="localhost"||l==="127.0.0.1")&&(c={...c,connect_domains:[...c.connect_domains||[],`ws://${l}:*`,`wss://${l}:*`],resource_domains:[...c.resource_domains||[],`http://${l}:*`]})}catch{}let d=`ui://widgets/apps-sdk/${t}.html`,u=`ui://widgets/ext-apps/${t}.html`,f=null,y=()=>(f||(f=Ye(o,i)),f),g=r;async function v(l){let E=await y();l.registerResource(`${t}-openai-widget`,d,{title:n,description:g,mimeType:Y,_meta:{"openai/widgetDescription":g,"openai/widgetPrefersBorder":a}},async T=>({contents:[{uri:T.href,mimeType:Y,text:E,_meta:Ze({description:g,prefersBorder:a,widgetDomain:s,widgetCSP:c})}]})),l.registerResource(`${t}-mcp-widget`,u,{title:n,description:g,mimeType:Z,_meta:{ui:{prefersBorder:a}}},async T=>({contents:[{uri:T.href,mimeType:Z,text:E,_meta:Je({description:g,prefersBorder:a,widgetDomain:s,widgetCSP:c})}]}))}return{id:t,title:n,description:r,openaiUri:d,mcpUri:u,autoHeight:p,register:v}}function Mt(e,t){let{resource:n,description:r,inputSchema:o,annotations:i,autoInjectResultText:s=!0}=e,a=e.id??n?.id,p=e.title??n?.title;if(!a)throw new Error("createTool: `id` is required when no resource is provided");if(!p)throw new Error("createTool: `title` is required when no resource is provided");let c=n?ue({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:a,title:p,description:r,async register(d){d.registerTool(a,{title:p,description:r,inputSchema:o,annotations:i,...c&&{_meta:c}},(async(u,f)=>{let y=f,g=y._meta??{},v=V(y),l=await t(u,{extra:{_meta:g},waniwani:v});return n&&l.data?{content:[{type:"text",text:l.text}],structuredContent:l.data,_meta:{...c,...g,...s===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:l.text}],...l.data?{structuredContent:l.data}:{},...s===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function Nt(e,t){await Promise.all(t.map(n=>n.register(e)))}var J=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var Ut="@waniwani/sdk";function Qe(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 p=r(),c=`${t.replace(/\/$/,"")}${s}`,d={Authorization:`Bearer ${p}`,"X-WaniWani-SDK":Ut},u={method:i,headers:d};a!==void 0&&(d["Content-Type"]="application/json",u.body=JSON.stringify(a));let f=await fetch(c,u);if(!f.ok){let g=await f.text().catch(()=>"");throw new J(g||`KB API error: HTTP ${f.status}`,f.status)}return(await f.json()).data}return{async ingest(i){return o("POST","/api/mcp/kb/ingest",{files:i})},async search(i,s){return o("POST","/api/mcp/kb/search",{query:i,...s})},async sources(){return o("GET","/api/mcp/kb/sources")}}}var Dt="@waniwani/sdk";function Q(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??et,o=jt(e),i=X(e.meta),s=X(e.metadata),a=$t(e,i),p=b(e.eventId)??r(),c=Lt(e.timestamp,n),d=b(e.source)??j(i)??t.source??Dt,u=le(e)?{...e}:void 0,f={...s};return Object.keys(i).length>0&&(f.meta=i),u&&(f.rawLegacy=u),{id:p,type:"mcp.event",name:o,source:d,timestamp:c,correlation:a,properties:Ot(e,o),metadata:f,rawLegacy:u}}function et(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function Ot(e,t){if(!le(e))return X(e.properties);let n=Kt(e,t),r=X(e.properties);return{...n,...r}}function Kt(e,t){switch(t){case"tool.called":{let n={};return b(e.toolName)&&(n.name=e.toolName),b(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),b(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return b(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),b(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function jt(e){return le(e)?e.eventType:e.event}function $t(e,t){let n=b(e.requestId)??Ce(t),r=b(e.sessionId)??P(t),o=b(e.traceId)??_e(t),i=b(e.externalUserId)??Pe(t),s=b(e.correlationId)??Fe(t)??n,a={};return r&&(a.sessionId=r),o&&(a.traceId=o),n&&(a.requestId=n),s&&(a.correlationId=s),i&&(a.externalUserId=i),a}function Lt(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 X(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function b(e){if(typeof e=="string"&&e.trim().length!==0)return e}function le(e){return"eventType"in e}var qt="/api/mcp/events/v2/batch";var tt="@waniwani/sdk",Bt=new Set([401,403]),Ht=new Set([408,425,429,500,502,503,504]);function nt(e){return new fe(e)}var fe=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=Gt(t.apiUrl,t.endpointPath??qt),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))}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()})}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:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-WaniWani-SDK":tt},body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:Yt(i)}}if(Bt.has(n.status))return{kind:"auth",status:n.status};if(Ht.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await zt(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(Vt(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 Vt(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 zt(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function Gt(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function Yt(e){return e instanceof Error?e.message:String(e)}function rt(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?nt({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,s={async identify(a,p,c){o();let d=Q({event:"user.identified",externalUserId:a,properties:p,meta:c});return i?.enqueue(d),{eventId:d.id}},async track(a){o();let p=Q(a);return i?.enqueue(p),{eventId:p.id}},async flush(){o(),await i?.flush()},async shutdown(a){return o(),await i?.shutdown({timeoutMs:a?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&Zt(s,r.shutdownTimeoutMs),s}function Zt(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 ee(e){let t=e,n=t?.apiUrl??"https://app.waniwani.ai",r=t?.apiKey??process.env.WANIWANI_API_KEY,o={endpointPath:t?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:t?.tracking?.flushIntervalMs??1e3,maxBatchSize:t?.tracking?.maxBatchSize??20,maxBufferSize:t?.tracking?.maxBufferSize??1e3,maxRetries:t?.tracking?.maxRetries??3,retryBaseDelayMs:t?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:t?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:t?.tracking?.shutdownTimeoutMs??2e3},i={apiUrl:n,apiKey:r,tracking:o},s=rt(i),a=Qe(i);return{...s,kb:a,_config:i}}function Jt(e){let t=e.event_type??"widget_click",r=t.startsWith("widget_")?t:`widget_${t}`,o={...e.metadata??{}};return e.event_name&&(o.event_name=e.event_name),{event:r,properties:o,sessionId:e.session_id,traceId:e.trace_id,externalUserId:e.user_id,eventId:e.event_id,timestamp:e.timestamp,source:e.source??"widget"}}function Xt(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=ee(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(),p=[];for(let c of s.events){let d=Jt(c),u=await a.track(d);p.push(u.eventId)}return await a.flush(),new Response(JSON.stringify({ok:!0,accepted:p.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(a){let p=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({error:p}),{status:500,headers:{"Content-Type":"application/json"}})}}}var ge=U("widget-token"),Qt=120*1e3,te=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-Qt?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=en(this.config.apiUrl,"/api/mcp/widget-tokens");ge("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(ge("mint response:",i.status),!i.ok)return null;let s=await i.json(),a=s.data&&typeof s.data=="object"?s.data:s,p=new Date(a.expiresAt).getTime();return!a.token||Number.isNaN(p)?null:(this.cached={token:a.token,expiresAt:p},a.token)}catch(i){return ge("mint failed:",i),null}}};function en(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function tn(e){let t=JSON.stringify({nodes:e.nodes,edges:e.edges});if(typeof globalThis.crypto?.subtle?.digest=="function"){let r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}let n=0;for(let r=0;r<t.length;r++)n=(n<<5)-n+t.charCodeAt(r)|0;return`simple-${Math.abs(n).toString(36)}`}async function ot(e,t,n){if(e.length===0)return;let r=await Promise.all(e.map(async i=>({...i,configHash:await tn(i)}))),o=JSON.stringify({flows:r});try{let i=`${t}/api/mcp/funnel/sync`;fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:o}).catch(()=>{})}catch{}}var it="waniwani/sessionId",ne="waniwani/geoLocation",re="waniwani/userLocation",nn="openai/userLocation",rn=[nn,ne,re];function st(e,t){if(t.length===0)return e;let n;for(let r of rn){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 B(e){if(!k(e))return;let t=e._meta;return k(t)?t:void 0}function we(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 on(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function me(e,t,n,r,o,i){let s=on(e,n.toolType),a=n.stripLocationFields,p=a&&a.length>0,c=B(t),d=c&&p?st(c,a):c,u=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,f=p&&k(i?.output)&&k(i.output._meta)?{...i.output,_meta:st(i.output._meta,a)}:i?.output;return{event:"tool.called",properties:{name:e,type:s,...r??{},...u!==void 0&&{input:u},...f!==void 0&&{output:f}},meta:d,source:j(d),metadata:{...n.metadata??{},...o&&{clientInfo:o}}}}async function he(e,t,n){try{await e.track(t)}catch(r){n?.(Te(r))}}async function ye(e,t){try{await e.flush()}catch(n){t?.(Te(n))}}async function ct(e,t,n,r,o){if(!k(e))return;k(e._meta)||(e._meta={});let i=e._meta,s=k(i.waniwani)?i.waniwani:void 0,a={...s??{},endpoint:s?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let u=await t.getToken();u&&(a.token=u)}catch(u){o?.(Te(u))}let p=P(i);p&&(a.sessionId||(a.sessionId=p));let c=ut(i);c!==void 0&&(a.geoLocation||(a.geoLocation=c));let d=j(B(r));d&&!a.source&&(a.source=d),i.waniwani=a}var at=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function dt(e,t){if(!t||!k(e))return;let n=!1;for(let o of at)if(o in t){n=!0;break}if(!n)return;k(e._meta)||(e._meta={});let r=e._meta;for(let o of at)o in t&&(o in r||(r[o]=t[o]))}function pt(e,t){let n=B(t);if(!n||!k(e))return;k(e._meta)||(e._meta={});let r=e._meta,o=P(n);o&&!r[it]&&(r[it]=o);let i=ut(n);i&&(r[ne]||(r[ne]=i),r[re]||(r[re]=i))}function ut(e){if(!e)return;let t=e[ne]??e[re];if(k(t)||typeof t=="string")return t}function Te(e){return e instanceof Error?e:new Error(String(e))}function lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ft(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(lt(e.requestInfo)){let t=e.requestInfo.headers;if(lt(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"),oe=U("mcp"),ke="https://app.waniwani.ai",sn="REDACTED";function an(e){if(!e)return;let t=e[G];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]=sn,i=!0);return i?{...r,stateUpdates:s}:r}}function gt(e,t,n,r){let{server:o,tracker:i,opts:s,tokenCache:a,injectToken:p}=n,c=s.applyFieldRedactions===!0?an(r):void 0,d=c?{...s,redactInput:c}:s,u=async(f,y)=>{let g=B(y)??{};if(!P(g)&&k(y)){let w=ft(y);w&&(g["waniwani/sessionId"]=w,y._meta=g)}let l=be(i,g,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});k(y)&&(y[se]=l);let E=performance.now(),T=o.server?.getClientVersion?.();try{let w=await t(f,y),S=Math.round(performance.now()-E);oe(`tool "${e}" handler returned in ${S}ms, running post-processing...`);let R=k(w)&&w.isError===!0;if(R){let x=we(w);console.error(`[waniwani] Tool "${e}" returned error${x?`: ${x}`:""}`)}return await he(i,me(e,y,d,{durationMs:S,status:R?"error":"ok",...R&&{errorMessage:we(w)??"Unknown tool error"}},T,{input:f,output:w}),s.onError),oe(`tool "${e}" tracking done`),s.flushAfterToolCall&&await ye(i,s.onError),pt(w,y),dt(w,r),p&&(await ct(w,a,i._config.apiUrl??ke,y,s.onError),oe(`tool "${e}" widget config injected`)),oe(`tool "${e}" post-processing complete, returning result`),w}catch(w){let S=Math.round(performance.now()-E);throw await he(i,me(e,y,d,{durationMs:S,status:"error",errorMessage:w instanceof Error?w.message:String(w)},T,{input:f}),s.onError),s.flushAfterToolCall&&await ye(i,s.onError),w}};return u[wt]=!0,u}function cn(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??ee(),i=r.injectWidgetToken!==!1,s=o._config.apiKey?new te({apiUrl:o._config.apiUrl??ke,apiKey:o._config.apiKey}):null,a={server:e,tracker:o,opts:r,tokenCache:s,injectToken:i},p=e.registerTool.bind(e);n.registerTool=((...d)=>{let[u,f,y]=d;if(typeof y!="function")return p(...d);let g=typeof u=="string"&&u.trim().length>0?u:"unknown",v=k(f)&&k(f._meta)?f._meta:void 0,l=gt(g,y,a,v);return p(u,f,l)});let c=e._registeredTools;if(k(c))for(let[d,u]of Object.entries(c)){if(!k(u))continue;let f=u.handler;if(typeof f!="function"||f[wt])continue;let y=k(u._meta)?u._meta:void 0;u.handler=gt(d,f,a,y)}if(o._config.apiKey){let d=e._registeredTools,u=[];if(d&&typeof d=="object"){for(let f of Object.values(d))if(f&&typeof f=="object"){let y=f._meta,g=y&&typeof y=="object"?y._flowGraph:void 0;g?.nodes?.length&&u.push(g)}}u.length>0&&ot(u,o._config.apiUrl??ke,o._config.apiKey)}return n}export{_ as END,C as START,O as StateGraph,D as WaniwaniKvStore,ze as createFlow,Ge as createFlowTestHarness,Xe as createResource,Mt as createTool,Xt as createTrackingRoute,ie as detectPlatform,ht as isMCPApps,mt as isOpenAI,Le as redacted,Nt as registerTools,cn as withWaniwani};
3
+ ${W.context}`:`ERROR: ${x}`}:W),P=Ae(_,w.context,c,d);if(P)return P;break}}let k=r.get(c);if(!k)return{content:{status:"error",error:`No outgoing edge from node "${c}"`}};c=await M(k,d);continue}if(Ee(w)){let R=w.field;if(R&&se($(d,R))){let k=r.get(c);if(!k)return{content:{status:"error",error:`No outgoing edge from node "${c}"`}};c=await M(k,d);continue}return{content:{status:"widget",tool:w.tool,data:w.data,description:w.description,interactive:w.interactive!==!1},flowTokenContent:{step:c,state:d,field:R,widgetId:w.tool}}}d=A(d,w);let T=r.get(c);if(!T)return{content:{status:"error",error:`No outgoing edge from node "${c}"`}};c=await M(T,d)}catch(l){return{content:{status:"error",error:l instanceof Error?l.message:String(l)},flowTokenContent:{step:c,state:d}}}}return{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"}}}function ae(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var Me=new Map;async function Ne(e){let t=Me.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 Me.set(e,r),r}async function Ue(e,t){let n=await Ne(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 De(e,t){let n=await Ne(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 Et(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in xt?e:process.env.WANIWANI_DEBUG?"debug":"none"}function U(e,t){return t??Et()==="debug"?(...r)=>console.log(`[waniwani:${e}]`,...r):()=>{}}var It="@waniwani/sdk",bt="https://app.waniwani.ai",Ct=U("kv"),D=class{get baseUrl(){return(process.env.WANIWANI_API_URL??bt).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(ae(n)){if(!this.encryptionKey)throw new Error("[WaniWani KV] Encrypted data found but WANIWANI_ENCRYPTION_KEY is not set.");return De(n,this.encryptionKey)}return n}async set(t,n){if(!this.apiKey)throw new Error("[WaniWani KV] No API key configured. Set WANIWANI_API_KEY env var.");let r=this.encryptionKey;Ct(`set "${t}" \u2014 encryption ${r?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let o=r?await Ue(n,r):n;await this.request("/api/mcp/redis/set",{key:t,value:o})}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":It},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 q=class{store=new D;get(t){return this.store.get(t)}set(t,n){return this.store.set(t,n)}delete(t){return this.store.delete(t)}};function _t(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function Ft(e,t){let n=e.toString(),r=[];for(let o of t){let i=`"${o}"`,s=`'${o}'`,a=`\`${o}\``;(n.includes(i)||n.includes(s)||n.includes(a))&&r.push(o)}return r}function Oe(e,t,n,r){let o=new Set([...t.keys(),C]),i=[];for(let[a,p]of t){let c=r.get(a);i.push({id:a,type:_t(p),label:c?.label??a,...c?.hideFromFunnel?{hideFromFunnel:!0}:{}})}let s=[];for(let[a,p]of n)if(p.type==="direct")s.push({from:a,to:p.to,type:"direct"});else{let c=Ft(p.condition,o);s.push({from:a,to:c,type:"conditional"})}return{flowId:e.id,title:e.title,nodes:i,edges:s}}function Ke(e){let t=e.description??"",n=e._zod?.def;if(n?.type==="enum"&&n.entries){let r=Object.keys(n.entries).map(o=>`"${o}"`).join(" | ");return t?`${r} \u2014 ${t}`:r}return t}function je(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."," 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."];if(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").'),e.state){let n=[];for(let[r,o]of Object.entries(e.state)){let i=Pe(o);if(i){let s=o.description??"",a=Object.entries(i).map(([p,c])=>{let d=Ke(c);return d?`\`${r}.${p}\` (${d})`:`\`${r}.${p}\``}).join(", ");n.push(s?`\`${r}\` (${s}): ${a}`:`\`${r}\`: ${a}`)}else{let s=Ke(o);n.push(s?`\`${r}\` (${s})`:`\`${r}\``)}}t.push(` Known fields: ${n.join(", ")}.`)}return t.push(" For grouped fields (shown as `group.subfield`), 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, context? }` \u2014 ask `question`, store answer in `field`."," b. Multi-question: `{ questions: [{question, field}, ...], context? }` \u2014 ask ALL questions"," in one conversational message, collect all answers."," `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. Call the display tool, then immediately",' 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 ce(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function $e(e){let t=Le(e),n=ce(t.waniwani)?t.waniwani:{};return e.meta({...t,waniwani:{...n,redacted:!0}})}function Pt(e){let n=Le(e).waniwani;return ce(n)&&n.redacted===!0}function Le(e){let t=e.meta;if(typeof t!="function")return{};let n=t.call(e);return ce(n)?n:{}}function qe(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))Pt(r)&&t.push(n);return t}var z="waniwani/redactedStateUpdateFields";function Wt(e){let t=e.omitIntentPII?" Do not include PII (names, emails, phones, addresses, IDs, ages, birthdates) \u2014 summarize abstractly.":"";return{action:N.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:N.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:N.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:N.record(N.string(),N.unknown()).optional().describe("State field values to set before processing the next node. Use this to pass the user's answer (keyed by the field name from the response) and any other values the user mentioned."),sessionId:N.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 Be(e){let{config:t,nodes:n,edges:r}=e,o=Wt(t),i=Oe(t,n,r,e.nodeOptions),s=je(t),a=`${t.description}
5
+ ${s}`,p=e.store??new q,c=new Map;async function d(l,w,T,R){if(l.action==="start"){let k=typeof l.intent=="string"?l.intent.trim():void 0;if(!k)return{content:{status:"error",error:`Missing required "intent" for action "start". Include a brief summary of the user's goal for this flow and any relevant prior context that led to triggering it, if available.`}};if(l.intent=k,typeof l.context=="string"){let x=l.context.trim();l.context=x||void 0}let f=r.get(b);if(!f)return{content:{status:"error",error:"No start edge"}};let E=V(l.stateUpdates??{}),S=await M(f,E);return L(S,E,n,r,c,T,R,e.nodeOptions,t.id)}if(l.action==="continue"){if(!w)return{content:{status:"error",error:"No session ID available for continue action."}};let k;try{k=await p.get(w)}catch(x){let _=x instanceof Error?x.message:String(x);return{content:{status:"error",error:`Failed to load flow state (session "${w}"): ${_}`}}}if(!k)return{content:{status:"error",error:`Flow state not found for session "${w}". The flow may have expired.`}};let f=k.state,E=k.step;if(!E)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let S=A(f,V(l.stateUpdates??{}));if(k.widgetId){let x=r.get(E);if(!x)return{content:{status:"error",error:`No edge from step "${E}"`}};let _=await M(x,S);return L(_,S,n,r,c,T,R,e.nodeOptions,t.id)}return L(E,S,n,r,c,T,R,e.nodeOptions,t.id)}if(l.action==="reset"){if(!w)return{content:{status:"error",error:"No session ID available for reset action."}};let k;try{k=await p.get(w)}catch(_){let P=_ instanceof Error?_.message:String(_);return{content:{status:"error",error:`Failed to load flow state (session "${w}"): ${P}`}}}if(!k)return{content:{status:"error",error:`Flow state not found for session "${w}". The flow may have completed or expired. Use action "start" to begin a new flow.`}};if(!l.stateUpdates||Object.keys(l.stateUpdates).length===0)return{content:{status:"error",error:'Missing "stateUpdates" for action "reset". Include the corrected field(s).'}};let f=r.get(b);if(!f)return{content:{status:"error",error:"No start edge"}};let E=k.state,S=A(E,V(l.stateUpdates)),x=await M(f,S);return L(x,S,n,r,c,T,R,e.nodeOptions,t.id)}return{content:{status:"error",error:`Unknown action: "${l.action}"`}}}let u=qe(t.state),g={title:t.title,description:a,inputSchema:o,annotations:t.annotations,...u.length>0&&{_meta:{[z]:u}}},y=(async(l,w)=>{let T=w,R=T._meta??{},k=F(R),f=k??l.sessionId;!f&&l.action==="start"&&(f=crypto.randomUUID(),R["waniwani/sessionId"]=f);let E=H(T),S=await d(l,f,R,E);if(f)if(S.flowTokenContent&&S.content.status!=="complete")try{await p.set(f,S.flowTokenContent)}catch(P){let W=P instanceof Error?P.message:String(P);return{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${f}"): ${W}`},null,2)}],_meta:R,isError:!0}}else S.content.status==="complete"&&await p.delete(f);let x=!k&&f?{...S.content,sessionId:f}:S.content;return{content:[{type:"text",text:JSON.stringify(x,null,2)}],_meta:R,...S.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:g,handler:y,async register(l){let w={...g,_meta:{...g._meta,_flowGraph:i}};l.registerTool(t.id,w,y)},graph:e.graph,flowGraph:i}}function He(e,t){let n=["flowchart TD"];n.push(` ${b}((Start))`);for(let[r]of e)n.push(` ${r}[${r}]`);n.push(` ${C}((End))`);for(let[r,o]of t)o.type==="direct"?n.push(` ${r} --> ${o.to}`):n.push(` ${r} -.-> ${r}_branch([?])`);return n.join(`
6
+ `)}var O=class{nodes=new Map;edges=new Map;nodeOptions=new Map;config;constructor(t){this.config=t}addNode(t,n,r){if(t===b||t===C)throw new Error(`"${t}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(t))throw new Error(`Node "${t}" already exists`);return this.nodes.set(t,n),r&&this.nodeOptions.set(t,r),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){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge.`);return this.edges.set(t,{type:"conditional",condition:n}),this}graph(){return He(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return Be({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>He(n,r),nodeOptions:new Map(this.nodeOptions)})}validate(){if(!this.edges.has(b))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(b);if(t?.type==="direct"&&t.to!==C&&!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!==b&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(r.type==="direct"&&r.to!==C&&!this.nodes.has(r.to))throw new Error(`Edge from "${n}" references non-existent node: "${r.to}"`)}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 Ve(e){return new O(e)}function de(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function ze(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 p(c){return{...c,decodedState:n?await n.get(o):null}}return{async start(c,d,u){let g=await s({action:"start",intent:c,...u?{context:u}:{},...d?{stateUpdates:d}:{}},a);return p(de(g))},async continueWith(c){let d=await s({action:"continue",...c?{stateUpdates:c}:{}},a);return p(de(d))},async resetWith(c){let d=await s({action:"reset",stateUpdates:c},a);return p(de(d))},async lastState(){return n?n.get(o):null}}}var G="text/html+skybridge",Y="text/html;profile=mcp-app",Ge=async(e,t)=>{let n=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${n}${t}`)).text()};function Ye(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function Ze(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.widgetDomain&&{domain:e.widgetDomain},...e.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function pe(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 Je(e){let{id:t,title:n,description:r,baseUrl:o,htmlPath:i,widgetDomain:s,prefersBorder:a=!0,autoHeight:p=!0}=e,c=e.widgetCSP??{connect_domains:[o],resource_domains:[o]};if(process.env.NODE_ENV==="development")try{let{hostname:T}=new URL(o);(T==="localhost"||T==="127.0.0.1")&&(c={...c,connect_domains:[...c.connect_domains||[],`ws://${T}:*`,`wss://${T}:*`],resource_domains:[...c.resource_domains||[],`http://${T}:*`]})}catch{}let d=`ui://widgets/apps-sdk/${t}.html`,u=`ui://widgets/ext-apps/${t}.html`,g=null,y=()=>(g||(g=Ge(o,i)),g),l=r;async function w(T){let R=await y();T.registerResource(`${t}-openai-widget`,d,{title:n,description:l,mimeType:G,_meta:{"openai/widgetDescription":l,"openai/widgetPrefersBorder":a}},async k=>({contents:[{uri:k.href,mimeType:G,text:R,_meta:Ye({description:l,prefersBorder:a,widgetDomain:s,widgetCSP:c})}]})),T.registerResource(`${t}-mcp-widget`,u,{title:n,description:l,mimeType:Y,_meta:{ui:{prefersBorder:a}}},async k=>({contents:[{uri:k.href,mimeType:Y,text:R,_meta:Ze({description:l,prefersBorder:a,widgetDomain:s,widgetCSP:c})}]}))}return{id:t,title:n,description:r,openaiUri:d,mcpUri:u,autoHeight:p,register:w}}function At(e,t){let{resource:n,description:r,inputSchema:o,annotations:i,autoInjectResultText:s=!0}=e,a=e.id??n?.id,p=e.title??n?.title;if(!a)throw new Error("createTool: `id` is required when no resource is provided");if(!p)throw new Error("createTool: `title` is required when no resource is provided");let c=n?pe({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:a,title:p,description:r,async register(d){d.registerTool(a,{title:p,description:r,inputSchema:o,annotations:i,...c&&{_meta:c}},(async(u,g)=>{let y=g,l=y._meta??{},w=H(y),T=await t(u,{extra:{_meta:l},waniwani:w});return n&&T.data?{content:[{type:"text",text:T.text}],structuredContent:T.data,_meta:{...c,...l,...s===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:T.text}],...T.data?{structuredContent:T.data}:{},...s===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function Mt(e,t){await Promise.all(t.map(n=>n.register(e)))}var Z=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var Nt="@waniwani/sdk";function Xe(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 p=r(),c=`${t.replace(/\/$/,"")}${s}`,d={Authorization:`Bearer ${p}`,"X-WaniWani-SDK":Nt},u={method:i,headers:d};a!==void 0&&(d["Content-Type"]="application/json",u.body=JSON.stringify(a));let g=await fetch(c,u);if(!g.ok){let l=await g.text().catch(()=>"");throw new Z(l||`KB API error: HTTP ${g.status}`,g.status)}return(await g.json()).data}return{async ingest(i){return o("POST","/api/mcp/kb/ingest",{files:i})},async search(i,s){return o("POST","/api/mcp/kb/search",{query:i,...s})},async sources(){return o("GET","/api/mcp/kb/sources")}}}var Ut="@waniwani/sdk";function X(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??Qe,o=Kt(e),i=J(e.meta),s=J(e.metadata),a=jt(e,i),p=I(e.eventId)??r(),c=$t(e.timestamp,n),d=I(e.source)??j(i)??t.source??Ut,u=ue(e)?{...e}:void 0,g={...s};return Object.keys(i).length>0&&(g.meta=i),u&&(g.rawLegacy=u),{id:p,type:"mcp.event",name:o,source:d,timestamp:c,correlation:a,properties:Dt(e,o),metadata:g,rawLegacy:u}}function Qe(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function Dt(e,t){if(!ue(e))return J(e.properties);let n=Ot(e,t),r=J(e.properties);return{...n,...r}}function Ot(e,t){switch(t){case"tool.called":{let n={};return I(e.toolName)&&(n.name=e.toolName),I(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),I(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return I(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),I(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function Kt(e){return ue(e)?e.eventType:e.event}function jt(e,t){let n=I(e.requestId)??be(t),r=I(e.sessionId)??F(t),o=I(e.traceId)??Ce(t),i=I(e.externalUserId)??_e(t),s=I(e.correlationId)??Fe(t)??n,a={};return r&&(a.sessionId=r),o&&(a.traceId=o),n&&(a.requestId=n),s&&(a.correlationId=s),i&&(a.externalUserId=i),a}function $t(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 J(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function I(e){if(typeof e=="string"&&e.trim().length!==0)return e}function ue(e){return"eventType"in e}var Lt="/api/mcp/events/v2/batch";var et="@waniwani/sdk",qt=new Set([401,403]),Bt=new Set([408,425,429,500,502,503,504]);function tt(e){return new le(e)}var le=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=zt(t.apiUrl,t.endpointPath??Lt),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))}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()})}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:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-WaniWani-SDK":et},body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:Gt(i)}}if(qt.has(n.status))return{kind:"auth",status:n.status};if(Bt.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await Vt(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:et,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(Ht(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 Ht(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 Vt(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function zt(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function Gt(e){return e instanceof Error?e.message:String(e)}function nt(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?tt({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,s={async identify(a,p,c){o();let d=X({event:"user.identified",externalUserId:a,properties:p,meta:c});return i?.enqueue(d),{eventId:d.id}},async track(a){o();let p=X(a);return i?.enqueue(p),{eventId:p.id}},async flush(){o(),await i?.flush()},async shutdown(a){return o(),await i?.shutdown({timeoutMs:a?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&Yt(s,r.shutdownTimeoutMs),s}function Yt(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 Q(e){let t=e,n=t?.apiUrl??"https://app.waniwani.ai",r=t?.apiKey??process.env.WANIWANI_API_KEY,o={endpointPath:t?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:t?.tracking?.flushIntervalMs??1e3,maxBatchSize:t?.tracking?.maxBatchSize??20,maxBufferSize:t?.tracking?.maxBufferSize??1e3,maxRetries:t?.tracking?.maxRetries??3,retryBaseDelayMs:t?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:t?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:t?.tracking?.shutdownTimeoutMs??2e3},i={apiUrl:n,apiKey:r,tracking:o},s=nt(i),a=Xe(i);return{...s,kb:a,_config:i}}function Zt(e){let t=e.event_type??"widget_click",r=t.startsWith("widget_")?t:`widget_${t}`,o={...e.metadata??{}};return e.event_name&&(o.event_name=e.event_name),{event:r,properties:o,sessionId:e.session_id,traceId:e.trace_id,externalUserId:e.user_id,eventId:e.event_id,timestamp:e.timestamp,source:e.source??"widget"}}function Jt(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=Q(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(),p=[];for(let c of s.events){let d=Zt(c),u=await a.track(d);p.push(u.eventId)}return await a.flush(),new Response(JSON.stringify({ok:!0,accepted:p.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(a){let p=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({error:p}),{status:500,headers:{"Content-Type":"application/json"}})}}}var fe=U("widget-token"),Xt=120*1e3,ee=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-Xt?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=Qt(this.config.apiUrl,"/api/mcp/widget-tokens");fe("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(fe("mint response:",i.status),!i.ok)return null;let s=await i.json(),a=s.data&&typeof s.data=="object"?s.data:s,p=new Date(a.expiresAt).getTime();return!a.token||Number.isNaN(p)?null:(this.cached={token:a.token,expiresAt:p},a.token)}catch(i){return fe("mint failed:",i),null}}};function Qt(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function en(e){let t=JSON.stringify({nodes:e.nodes,edges:e.edges});if(typeof globalThis.crypto?.subtle?.digest=="function"){let r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}let n=0;for(let r=0;r<t.length;r++)n=(n<<5)-n+t.charCodeAt(r)|0;return`simple-${Math.abs(n).toString(36)}`}async function rt(e,t,n){if(e.length===0)return;let r=await Promise.all(e.map(async i=>({...i,configHash:await en(i)}))),o=JSON.stringify({flows:r});try{let i=`${t}/api/mcp/funnel/sync`;fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:o}).catch(()=>{})}catch{}}var ot="waniwani/sessionId",te="waniwani/geoLocation",ne="waniwani/userLocation",tn="openai/userLocation",nn=[tn,te,ne];function it(e,t){if(t.length===0)return e;let n;for(let r of nn){let o=e[r];if(!v(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 v(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function B(e){if(!v(e))return;let t=e._meta;return v(t)?t:void 0}function ge(e){if(!v(e))return;let t=e.content;return Array.isArray(t)?t.find(r=>v(r)&&r.type==="text"&&typeof r.text=="string")?.text:void 0}function rn(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function we(e,t,n,r,o,i){let s=rn(e,n.toolType),a=n.stripLocationFields,p=a&&a.length>0,c=B(t),d=c&&p?it(c,a):c,u=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,g=p&&v(i?.output)&&v(i.output._meta)?{...i.output,_meta:it(i.output._meta,a)}:i?.output;return{event:"tool.called",properties:{name:e,type:s,...r??{},...u!==void 0&&{input:u},...g!==void 0&&{output:g}},meta:d,source:j(d),metadata:{...n.metadata??{},...o&&{clientInfo:o}}}}async function me(e,t,n){try{await e.track(t)}catch(r){n?.(ye(r))}}async function he(e,t){try{await e.flush()}catch(n){t?.(ye(n))}}async function at(e,t,n,r,o){if(!v(e))return;v(e._meta)||(e._meta={});let i=e._meta,s=v(i.waniwani)?i.waniwani:void 0,a={...s??{},endpoint:s?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let u=await t.getToken();u&&(a.token=u)}catch(u){o?.(ye(u))}let p=F(i);p&&(a.sessionId||(a.sessionId=p));let c=pt(i);c!==void 0&&(a.geoLocation||(a.geoLocation=c));let d=j(B(r));d&&!a.source&&(a.source=d),i.waniwani=a}var st=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function ct(e,t){if(!t||!v(e))return;let n=!1;for(let o of st)if(o in t){n=!0;break}if(!n)return;v(e._meta)||(e._meta={});let r=e._meta;for(let o of st)o in t&&(o in r||(r[o]=t[o]))}function dt(e,t){let n=B(t);if(!n||!v(e))return;v(e._meta)||(e._meta={});let r=e._meta,o=F(n);o&&!r[ot]&&(r[ot]=o);let i=pt(n);i&&(r[te]||(r[te]=i),r[ne]||(r[ne]=i))}function pt(e){if(!e)return;let t=e[te]??e[ne];if(v(t)||typeof t=="string")return t}function ye(e){return e instanceof Error?e:new Error(String(e))}function ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lt(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(ut(e.requestInfo)){let t=e.requestInfo.headers;if(ut(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 gt=Symbol.for("waniwani.wrappedHandler"),re=U("mcp"),Te="https://app.waniwani.ai",on="REDACTED";function sn(e){if(!e)return;let t=e[z];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(!v(r))return r;let o=r.stateUpdates;if(!v(o))return r;let i=!1,s={...o};for(let a of n)a in s&&(s[a]=on,i=!0);return i?{...r,stateUpdates:s}:r}}function ft(e,t,n,r){let{server:o,tracker:i,opts:s,tokenCache:a,injectToken:p}=n,c=s.applyFieldRedactions===!0?sn(r):void 0,d=c?{...s,redactInput:c}:s,u=async(g,y)=>{let l=B(y)??{};if(!F(l)&&v(y)){let f=lt(y);f&&(l["waniwani/sessionId"]=f,y._meta=l)}let T=Ie(i,l,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});v(y)&&(y[ie]=T);let R=performance.now(),k=o.server?.getClientVersion?.();try{let f=await t(g,y),E=Math.round(performance.now()-R);re(`tool "${e}" handler returned in ${E}ms, running post-processing...`);let S=v(f)&&f.isError===!0;if(S){let x=ge(f);console.error(`[waniwani] Tool "${e}" returned error${x?`: ${x}`:""}`)}return await me(i,we(e,y,d,{durationMs:E,status:S?"error":"ok",...S&&{errorMessage:ge(f)??"Unknown tool error"}},k,{input:g,output:f}),s.onError),re(`tool "${e}" tracking done`),s.flushAfterToolCall&&await he(i,s.onError),dt(f,y),ct(f,r),p&&(await at(f,a,i._config.apiUrl??Te,y,s.onError),re(`tool "${e}" widget config injected`)),re(`tool "${e}" post-processing complete, returning result`),f}catch(f){let E=Math.round(performance.now()-R);throw await me(i,we(e,y,d,{durationMs:E,status:"error",errorMessage:f instanceof Error?f.message:String(f)},k,{input:g}),s.onError),s.flushAfterToolCall&&await he(i,s.onError),f}};return u[gt]=!0,u}function an(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??Q(),i=r.injectWidgetToken!==!1,s=o._config.apiKey?new ee({apiUrl:o._config.apiUrl??Te,apiKey:o._config.apiKey}):null,a={server:e,tracker:o,opts:r,tokenCache:s,injectToken:i},p=e.registerTool.bind(e);n.registerTool=((...d)=>{let[u,g,y]=d;if(typeof y!="function")return p(...d);let l=typeof u=="string"&&u.trim().length>0?u:"unknown",w=v(g)&&v(g._meta)?g._meta:void 0,T=ft(l,y,a,w);return p(u,g,T)});let c=e._registeredTools;if(v(c))for(let[d,u]of Object.entries(c)){if(!v(u))continue;let g=u.handler;if(typeof g!="function"||g[gt])continue;let y=v(u._meta)?u._meta:void 0;u.handler=ft(d,g,a,y)}if(o._config.apiKey){let d=e._registeredTools,u=[];if(d&&typeof d=="object"){for(let g of Object.values(d))if(g&&typeof g=="object"){let y=g._meta,l=y&&typeof y=="object"?y._flowGraph:void 0;l?.nodes?.length&&u.push(l)}}u.length>0&&rt(u,o._config.apiUrl??Te,o._config.apiKey)}return n}export{C as END,b as START,O as StateGraph,D as WaniwaniKvStore,Ve as createFlow,ze as createFlowTestHarness,Je as createResource,At as createTool,Jt as createTrackingRoute,oe as detectPlatform,mt as isMCPApps,wt as isOpenAI,$e as redacted,Mt as registerTools,an as withWaniwani};
7
7
  //# sourceMappingURL=index.js.map