@waniwani/sdk 0.10.11-beta.1 → 0.10.11-beta.2

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
- function re(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function kt(){return re()==="openai"}function St(){return re()==="mcp-apps"}var b="__start__",C="__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 oe="waniwani/client";function L(e){if(typeof e=="object"&&e!==null)return e[oe]}function _e(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 D(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var vt=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],Rt=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],xt=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],Et=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],It=["correlationId","openai/requestId"];function P(e){return e?D(e,vt):void 0}function Ce(e){return e?D(e,Rt):void 0}function be(e){return e?D(e,xt):void 0}function Pe(e){return e?D(e,Et):void 0}function We(e){return e?D(e,It):void 0}var _t=[{key:"waniwani/sessionId",source:"chatbar"},{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}];function O(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 _t){let o=e[n];if(typeof o=="string"&&o.length>0)return r}}function Fe(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function K(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 Ct(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 ie(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?Ct(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 se(e){return e!=null&&e!==""}async function F(e,t){return e.type==="direct"?e.to:e.condition(t)}function Me(e,t,n,r){if(e.every(p=>se(K(r,p.field))))return null;let o=e.filter(p=>!se(K(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 H(e,t,n,r,o,i,s,a,p){let c=e,d={...t},u=50,f=0;for(;f++<u;){if(c===C)return{content:{status:"complete"},flowTokenContent:{state:d}};let h=n.get(c);if(!h)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 h({state:d,meta:i,interrupt:Re,showWidget:xe,waniwani:s});if(Ee(l)){for(let k of l.questions)k.validate&&o.set(`${c}:${k.field}`,k.validate);let T=Me(l.questions,l.context,c,d);if(T)return T;for(let k of l.questions){let E=o.get(`${c}:${k.field}`);if(E)try{let v=K(d,k.field),I=await E(v);I&&typeof I=="object"&&(d=W(d,I))}catch(v){let I=v instanceof Error?v.message:String(v);Ae(d,k.field);let Te=l.questions.map(U=>U.field===k.field?{...U,context:U.context?`ERROR: ${I}
1
+ function re(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function St(){return re()==="openai"}function vt(){return re()==="mcp-apps"}var b="__start__",C="__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 oe="waniwani/client";function L(e){if(typeof e=="object"&&e!==null)return e[oe]}function _e(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 U(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var Rt=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],xt=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Et=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],It=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],_t=["correlationId","openai/requestId"];function P(e){return e?U(e,Rt):void 0}function Ce(e){return e?U(e,xt):void 0}function be(e){return e?U(e,Et):void 0}function Pe(e){return e?U(e,It):void 0}function We(e){return e?U(e,_t):void 0}var Ct=[{key:"waniwani/sessionId",source:"chatbar"},{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}];function O(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 Ct){let o=e[n];if(typeof o=="string"&&o.length>0)return r}}function Fe(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function K(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 bt(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 ie(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?bt(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 se(e){return e!=null&&e!==""}async function F(e,t){return e.type==="direct"?e.to:e.condition(t)}function Me(e,t,n,r){if(e.every(p=>se(K(r,p.field))))return null;let o=e.filter(p=>!se(K(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 H(e,t,n,r,o,i,s,a,p){let c=e,d={...t},u=50,f=0;for(;f++<u;){if(c===C)return{content:{status:"complete"},flowTokenContent:{state:d}};let h=n.get(c);if(!h)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 h({state:d,meta:i,interrupt:Re,showWidget:xe,waniwani:s});if(Ee(l)){for(let k of l.questions)k.validate&&o.set(`${c}:${k.field}`,k.validate);let T=Me(l.questions,l.context,c,d);if(T)return T;for(let k of l.questions){let E=o.get(`${c}:${k.field}`);if(E)try{let v=K(d,k.field),I=await E(v);I&&typeof I=="object"&&(d=W(d,I))}catch(v){let I=v instanceof Error?v.message:String(v);Ae(d,k.field);let Te=l.questions.map(D=>D.field===k.field?{...D,context:D.context?`ERROR: ${I}
2
2
 
3
- ${U.context}`:`ERROR: ${I}`}:U),ke=Me(Te,l.context,c,d);if(ke)return ke;break}}let y=r.get(c);if(!y)return{content:{status:"error",error:`No outgoing edge from node "${c}"`}};c=await F(y,d);continue}if(Ie(l)){let T=l.field;if(T&&se(K(d,T))){let y=r.get(c);if(!y)return{content:{status:"error",error:`No outgoing edge from node "${c}"`}};c=await F(y,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 x=r.get(c);if(!x)return{content:{status:"error",error:`No outgoing edge from node "${c}"`}};c=await F(x,d)}catch(R){return{content:{status:"error",error:R instanceof Error?R.message:String(R)},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 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 bt="@waniwani/sdk",Pt="https://app.waniwani.ai";function Wt(...e){process.env.WANIWANI_DEBUG&&console.log("[waniwani:kv]",...e)}var A=class{get baseUrl(){return(process.env.WANIWANI_API_URL??Pt).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 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;Wt(`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 j=class{store=new A;get(t){return this.store.get(t)}set(t,n){return this.store.set(t,n)}delete(t){return this.store.delete(t)}};function Ft(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function At(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(),C]),i=[];for(let[a,p]of t){let c=r.get(a);i.push({id:a,type:Ft(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=At(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=Fe(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."),t.join(`
4
- `)}function ce(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Be(e){let t=Le(e),n=ce(t.waniwani)?t.waniwani:{};return e.meta({...t,waniwani:{...n,redacted:!0}})}function Mt(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 He(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))Mt(r)&&t.push(n);return t}var q="waniwani/redactedStateUpdateFields";function Nt(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"]).describe('"start" to begin the flow, "continue" to resume after a pause (interrupt or widget)'),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.")}}function qe(e){let{config:t,nodes:n,edges:r}=e,o=Nt(t),i=Ke(t,n,r,e.nodeOptions),s=$e(t),a=`${t.description}
3
+ ${D.context}`:`ERROR: ${I}`}:D),ke=Me(Te,l.context,c,d);if(ke)return ke;break}}let y=r.get(c);if(!y)return{content:{status:"error",error:`No outgoing edge from node "${c}"`}};c=await F(y,d);continue}if(Ie(l)){let T=l.field;if(T&&se(K(d,T))){let y=r.get(c);if(!y)return{content:{status:"error",error:`No outgoing edge from node "${c}"`}};c=await F(y,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 x=r.get(c);if(!x)return{content:{status:"error",error:`No outgoing edge from node "${c}"`}};c=await F(x,d)}catch(R){return{content:{status:"error",error:R instanceof Error?R.message:String(R)},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 Ne=new Map;async function De(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 Ue(e,t){let n=await De(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 De(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 Pt="@waniwani/sdk",Wt="https://app.waniwani.ai";function Ft(...e){process.env.WANIWANI_DEBUG&&console.log("[waniwani:kv]",...e)}var A=class{get baseUrl(){return(process.env.WANIWANI_API_URL??Wt).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 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;Ft(`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":Pt},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 j=class{store=new A;get(t){return this.store.get(t)}set(t,n){return this.store.set(t,n)}delete(t){return this.store.delete(t)}};function At(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function Mt(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(),C]),i=[];for(let[a,p]of t){let c=r.get(a);i.push({id:a,type:At(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=Mt(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=Fe(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."),t.join(`
4
+ `)}function ce(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Be(e){let t=Le(e),n=ce(t.waniwani)?t.waniwani:{};return e.meta({...t,waniwani:{...n,redacted:!0}})}function Nt(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 He(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))Nt(r)&&t.push(n);return t}var q="waniwani/redactedStateUpdateFields";function Dt(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"]).describe('"start" to begin the flow, "continue" to resume after a pause (interrupt or widget)'),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.")}}function qe(e){let{config:t,nodes:n,edges:r}=e,o=Dt(t),i=Ke(t,n,r,e.nodeOptions),s=$e(t),a=`${t.description}
5
5
  ${s}`,p=e.store??new j,c=new Map;async function d(g,R,l,x){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 v=g.context.trim();g.context=v||void 0}let y=r.get(b);if(!y)return{content:{status:"error",error:"No start edge"}};let k=ie(g.stateUpdates??{}),E=await F(y,k);return H(E,k,n,r,c,l,x,e.nodeOptions,t.id)}if(g.action==="continue"){if(!R)return{content:{status:"error",error:"No session ID available for continue action."}};let T;try{T=await p.get(R)}catch(v){let I=v instanceof Error?v.message:String(v);return{content:{status:"error",error:`Failed to load flow state (session "${R}"): ${I}`}}}if(!T)return{content:{status:"error",error:`Flow state not found for session "${R}". The flow may have expired.`}};let y=T.state,k=T.step;if(!k)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let E=W(y,ie(g.stateUpdates??{}));if(T.widgetId){let v=r.get(k);if(!v)return{content:{status:"error",error:`No edge from step "${k}"`}};let I=await F(v,E);return H(I,E,n,r,c,l,x,e.nodeOptions,t.id)}return H(k,E,n,r,c,l,x,e.nodeOptions,t.id)}return{content:{status:"error",error:`Unknown action: "${g.action}"`}}}let u=He(t.state),f={title:t.title,description:a,inputSchema:o,annotations:t.annotations,...u.length>0&&{_meta:{[q]:u}}},h=(async(g,R)=>{let l=R,x=l._meta??{},T=P(x),y=L(l),k=await d(g,T,x,y);if(T)if(k.flowTokenContent&&k.content.status!=="complete")try{await p.set(T,k.flowTokenContent)}catch(v){let I=v instanceof Error?v.message:String(v);return{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${T}"): ${I}`},null,2)}],_meta:x,isError:!0}}else k.content.status==="complete"&&await p.delete(T);return{content:[{type:"text",text:JSON.stringify(k.content,null,2)}],_meta:x,...k.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:f,handler:h,async register(g){let R={...f,_meta:{...f._meta,_flowGraph:i}};g.registerTool(t.id,R,h)},graph:e.graph,flowGraph:i}}function Ve(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 N=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 Ve(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return qe({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>Ve(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 ze(e){return new N(e)}function Ge(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function Ye(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(Ge(f))},async continueWith(c){let d=await s({action:"continue",...c?{stateUpdates:c}:{}},a);return p(Ge(d))},async lastState(){return n?n.get(o):null}}}var V="text/html+skybridge",z="text/html;profile=mcp-app",Je=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 Xe(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 de(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}}}import{readFileSync as Ut}from"fs";import{dirname as Dt,resolve as Ot}from"path";import{fileURLToPath as Kt}from"url";var jt="__WANIWANI_WIDGET_BASE_URL__",$t="widgets-manifest.json",Bt=Ot(Dt(Kt(import.meta.url)),"..",$t);var $,Qe;function Lt(){if(Qe!==void 0)return Qe;if($!==void 0)return $;try{let e=Ut(Bt,"utf8");$=JSON.parse(e)}catch{$=null}return $}function Ht(e){return`/${e}`}function et(e,t){let n=t??Ht(e),r=Lt();return r?.byHtmlPath[n]??r?.byId[e]??n}function tt(e,t){let n=t.endsWith("/")?t.slice(0,-1):t;return e.replaceAll(jt,n)}function nt(e){let{id:t,title:n,description:r,baseUrl:o,widgetDomain:i,prefersBorder:s=!0,autoHeight:a=!0}=e,p=et(t,e.htmlPath),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,h=()=>(f||(f=Je(o,p).then(l=>tt(l,o))),f),g=r;async function R(l){let x=await h();l.registerResource(`${t}-openai-widget`,d,{title:n,description:g,mimeType:V,_meta:{"openai/widgetDescription":g,"openai/widgetPrefersBorder":s}},async T=>({contents:[{uri:T.href,mimeType:V,text:x,_meta:Ze({description:g,prefersBorder:s,widgetDomain:i,widgetCSP:c})}]})),l.registerResource(`${t}-mcp-widget`,u,{title:n,description:g,mimeType:z,_meta:{ui:{prefersBorder:s}}},async T=>({contents:[{uri:T.href,mimeType:z,text:x,_meta:Xe({description:g,prefersBorder:s,widgetDomain:i,widgetCSP:c})}]}))}return{id:t,title:n,description:r,openaiUri:d,mcpUri:u,autoHeight:a,register:R}}function qt(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?de({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 h=f,g=h._meta??{},R=L(h),l=await t(u,{extra:{_meta:g},waniwani:R});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 Vt(e,t){await Promise.all(t.map(n=>n.register(e)))}var G=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var zt="@waniwani/sdk";function rt(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":zt},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 G(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 Gt="@waniwani/sdk";function J(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??ot,o=Zt(e),i=Y(e.meta),s=Y(e.metadata),a=Xt(e,i),p=_(e.eventId)??r(),c=Qt(e.timestamp,n),d=_(e.source)??O(i)??t.source??Gt,u=pe(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:Yt(e,o),metadata:f,rawLegacy:u}}function ot(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function Yt(e,t){if(!pe(e))return Y(e.properties);let n=Jt(e,t),r=Y(e.properties);return{...n,...r}}function Jt(e,t){switch(t){case"tool.called":{let n={};return _(e.toolName)&&(n.name=e.toolName),_(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),_(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return _(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),_(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function Zt(e){return pe(e)?e.eventType:e.event}function Xt(e,t){let n=_(e.requestId)??Ce(t),r=_(e.sessionId)??P(t),o=_(e.traceId)??be(t),i=_(e.externalUserId)??Pe(t),s=_(e.correlationId)??We(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 Qt(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 Y(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function _(e){if(typeof e=="string"&&e.trim().length!==0)return e}function pe(e){return"eventType"in e}var en="/api/mcp/events/v2/batch";var it="@waniwani/sdk",tn=new Set([401,403]),nn=new Set([408,425,429,500,502,503,504]);function st(e){return new ue(e)}var ue=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=sn(t.apiUrl,t.endpointPath??en),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":it},body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:an(i)}}if(tn.has(n.status))return{kind:"auth",status:n.status};if(nn.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await on(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:it,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(rn(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 rn(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 on(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function sn(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function an(e){return e instanceof Error?e.message:String(e)}function at(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,s={async identify(a,p,c){o();let d=J({event:"user.identified",externalUserId:a,properties:p,meta:c});return i?.enqueue(d),{eventId:d.id}},async track(a){o();let p=J(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&&cn(s,r.shutdownTimeoutMs),s}function cn(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 Z(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=at(i),a=rt(i);return{...s,kb:a,_config:i}}function dn(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 pn(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=Z(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=dn(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"}})}}}function X(e,t){return t?(...n)=>console.log(`[waniwani:${e}]`,...n):()=>{}}var le=X("widget-token",!!process.env.WANIWANI_DEBUG),un=120*1e3,Q=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-un?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=ln(this.config.apiUrl,"/api/mcp/widget-tokens");le("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(le("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 le("mint failed:",i),null}}};function ln(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function fn(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 ct(e,t,n){if(e.length===0)return;let r=await Promise.all(e.map(async i=>({...i,configHash:await fn(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 dt="waniwani/sessionId",ee="waniwani/geoLocation",te="waniwani/userLocation",gn="openai/userLocation",wn=[gn,ee,te];function pt(e,t){if(t.length===0)return e;let n;for(let r of wn){let o=e[r];if(!S(o))continue;let i;for(let s of t)s in o&&(i||(i={...o}),delete i[s]);i&&(n||(n={...e}),n[r]=i)}return n??e}function S(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function B(e){if(!S(e))return;let t=e._meta;return S(t)?t:void 0}function fe(e){if(!S(e))return;let t=e.content;return Array.isArray(t)?t.find(r=>S(r)&&r.type==="text"&&typeof r.text=="string")?.text:void 0}function mn(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function ge(e,t,n,r,o,i){let s=mn(e,n.toolType),a=n.stripLocationFields,p=a&&a.length>0,c=B(t),d=c&&p?pt(c,a):c,u=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,f=p&&S(i?.output)&&S(i.output._meta)?{...i.output,_meta:pt(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:O(d),metadata:{...n.metadata??{},...o&&{clientInfo:o}}}}async function we(e,t,n){try{await e.track(t)}catch(r){n?.(he(r))}}async function me(e,t){try{await e.flush()}catch(n){t?.(he(n))}}async function lt(e,t,n,r,o){if(!S(e))return;S(e._meta)||(e._meta={});let i=e._meta,s=S(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?.(he(u))}let p=P(i);p&&(a.sessionId||(a.sessionId=p));let c=wt(i);c!==void 0&&(a.geoLocation||(a.geoLocation=c));let d=O(B(r));d&&!a.source&&(a.source=d),i.waniwani=a}var ut=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function ft(e,t){if(!t||!S(e))return;let n=!1;for(let o of ut)if(o in t){n=!0;break}if(!n)return;S(e._meta)||(e._meta={});let r=e._meta;for(let o of ut)o in t&&(o in r||(r[o]=t[o]))}function gt(e,t){let n=B(t);if(!n||!S(e))return;S(e._meta)||(e._meta={});let r=e._meta,o=P(n);o&&!r[dt]&&(r[dt]=o);let i=wt(n);i&&(r[ee]||(r[ee]=i),r[te]||(r[te]=i))}function wt(e){if(!e)return;let t=e[ee]??e[te];if(S(t)||typeof t=="string")return t}function he(e){return e instanceof Error?e:new Error(String(e))}function mt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ht(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(mt(e.requestInfo)){let t=e.requestInfo.headers;if(mt(t)){let n={};for(let o of Object.keys(t))n[o.toLowerCase()]=t[o];let r=n["mcp-session-id"];if(typeof r=="string"&&r)return r}}}var Tt=Symbol.for("waniwani.wrappedHandler"),ne=X("mcp",!!process.env.WANIWANI_DEBUG),ye="https://app.waniwani.ai",hn="REDACTED";function yn(e){if(!e)return;let t=e[q];if(!Array.isArray(t)||t.length===0)return;let n=new Set(t.filter(r=>typeof r=="string"));if(n.size!==0)return r=>{if(!S(r))return r;let o=r.stateUpdates;if(!S(o))return r;let i=!1,s={...o};for(let a of n)a in s&&(s[a]=hn,i=!0);return i?{...r,stateUpdates:s}:r}}function yt(e,t,n,r){let{server:o,tracker:i,opts:s,tokenCache:a,injectToken:p}=n,c=s.applyFieldRedactions===!0?yn(r):void 0,d=c?{...s,redactInput:c}:s,u=async(f,h)=>{let g=B(h)??{};if(!P(g)&&S(h)){let y=ht(h);y&&(g["waniwani/sessionId"]=y,h._meta=g)}let l=_e(i,g,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});S(h)&&(h[oe]=l);let x=performance.now(),T=o.server?.getClientVersion?.();try{let y=await t(f,h),k=Math.round(performance.now()-x);ne(`tool "${e}" handler returned in ${k}ms, running post-processing...`);let E=S(y)&&y.isError===!0;if(E){let v=fe(y);console.error(`[waniwani] Tool "${e}" returned error${v?`: ${v}`:""}`)}return await we(i,ge(e,h,d,{durationMs:k,status:E?"error":"ok",...E&&{errorMessage:fe(y)??"Unknown tool error"}},T,{input:f,output:y}),s.onError),ne(`tool "${e}" tracking done`),s.flushAfterToolCall&&await me(i,s.onError),gt(y,h),ft(y,r),p&&(await lt(y,a,i._config.apiUrl??ye,h,s.onError),ne(`tool "${e}" widget config injected`)),ne(`tool "${e}" post-processing complete, returning result`),y}catch(y){let k=Math.round(performance.now()-x);throw await we(i,ge(e,h,d,{durationMs:k,status:"error",errorMessage:y instanceof Error?y.message:String(y)},T,{input:f}),s.onError),s.flushAfterToolCall&&await me(i,s.onError),y}};return u[Tt]=!0,u}function Tn(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??Z(),i=r.injectWidgetToken!==!1,s=o._config.apiKey?new Q({apiUrl:o._config.apiUrl??ye,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,h]=d;if(typeof h!="function")return p(...d);let g=typeof u=="string"&&u.trim().length>0?u:"unknown",R=S(f)&&S(f._meta)?f._meta:void 0,l=yt(g,h,a,R);return p(u,f,l)});let c=e._registeredTools;if(S(c))for(let[d,u]of Object.entries(c)){if(!S(u))continue;let f=u.handler;if(typeof f!="function"||f[Tt])continue;let h=S(u._meta)?u._meta:void 0;u.handler=yt(d,f,a,h)}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 h=f._meta,g=h&&typeof h=="object"?h._flowGraph:void 0;g?.nodes?.length&&u.push(g)}}u.length>0&&ct(u,o._config.apiUrl??ye,o._config.apiKey)}return n}export{C as END,b as START,N as StateGraph,A as WaniwaniKvStore,ze as createFlow,Ye as createFlowTestHarness,nt as createResource,qt as createTool,pn as createTrackingRoute,re as detectPlatform,St as isMCPApps,kt as isOpenAI,Be as redacted,Vt as registerTools,Tn as withWaniwani};
6
+ `)}var N=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 Ve(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return qe({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>Ve(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 ze(e){return new N(e)}function Ge(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function Ye(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(Ge(f))},async continueWith(c){let d=await s({action:"continue",...c?{stateUpdates:c}:{}},a);return p(Ge(d))},async lastState(){return n?n.get(o):null}}}var V="text/html+skybridge",z="text/html;profile=mcp-app",Je=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 Xe(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 de(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}}}import{readFileSync as Ut}from"fs";import{resolve as Ot}from"path";var Kt="__WANIWANI_WIDGET_BASE_URL__",jt=".waniwani",$t="widgets-manifest.json",Bt=`${jt}/${$t}`;function Lt(e){return Ot(e??process.cwd(),Bt)}var Qe,$,et;function Ht(){if(et!==void 0)return et;let e=Lt();if(Qe===e&&$!==void 0)return $;Qe=e;try{let t=Ut(e,"utf8");$=JSON.parse(t)}catch{$=null}return $}function qt(e){return`/${e}`}function tt(e,t){let n=t??qt(e),r=Ht();return r?.byHtmlPath[n]??r?.byId[e]??n}function nt(e,t){let n=t.endsWith("/")?t.slice(0,-1):t;return e.replaceAll(Kt,n)}function rt(e){let{id:t,title:n,description:r,baseUrl:o,widgetDomain:i,prefersBorder:s=!0,autoHeight:a=!0}=e,p=tt(t,e.htmlPath),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,h=()=>(f||(f=Je(o,p).then(l=>nt(l,o))),f),g=r;async function R(l){let x=await h();l.registerResource(`${t}-openai-widget`,d,{title:n,description:g,mimeType:V,_meta:{"openai/widgetDescription":g,"openai/widgetPrefersBorder":s}},async T=>({contents:[{uri:T.href,mimeType:V,text:x,_meta:Ze({description:g,prefersBorder:s,widgetDomain:i,widgetCSP:c})}]})),l.registerResource(`${t}-mcp-widget`,u,{title:n,description:g,mimeType:z,_meta:{ui:{prefersBorder:s}}},async T=>({contents:[{uri:T.href,mimeType:z,text:x,_meta:Xe({description:g,prefersBorder:s,widgetDomain:i,widgetCSP:c})}]}))}return{id:t,title:n,description:r,openaiUri:d,mcpUri:u,autoHeight:a,register:R}}function Vt(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?de({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 h=f,g=h._meta??{},R=L(h),l=await t(u,{extra:{_meta:g},waniwani:R});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 zt(e,t){await Promise.all(t.map(n=>n.register(e)))}var G=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var Gt="@waniwani/sdk";function ot(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":Gt},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 G(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 Yt="@waniwani/sdk";function J(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??it,o=Xt(e),i=Y(e.meta),s=Y(e.metadata),a=Qt(e,i),p=_(e.eventId)??r(),c=en(e.timestamp,n),d=_(e.source)??O(i)??t.source??Yt,u=pe(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:Jt(e,o),metadata:f,rawLegacy:u}}function it(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function Jt(e,t){if(!pe(e))return Y(e.properties);let n=Zt(e,t),r=Y(e.properties);return{...n,...r}}function Zt(e,t){switch(t){case"tool.called":{let n={};return _(e.toolName)&&(n.name=e.toolName),_(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),_(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return _(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),_(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function Xt(e){return pe(e)?e.eventType:e.event}function Qt(e,t){let n=_(e.requestId)??Ce(t),r=_(e.sessionId)??P(t),o=_(e.traceId)??be(t),i=_(e.externalUserId)??Pe(t),s=_(e.correlationId)??We(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 en(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 Y(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function _(e){if(typeof e=="string"&&e.trim().length!==0)return e}function pe(e){return"eventType"in e}var tn="/api/mcp/events/v2/batch";var st="@waniwani/sdk",nn=new Set([401,403]),rn=new Set([408,425,429,500,502,503,504]);function at(e){return new ue(e)}var ue=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=an(t.apiUrl,t.endpointPath??tn),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":st},body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:cn(i)}}if(nn.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 sn(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:st,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(on(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 on(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 sn(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function an(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function cn(e){return e instanceof Error?e.message:String(e)}function ct(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?at({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=J({event:"user.identified",externalUserId:a,properties:p,meta:c});return i?.enqueue(d),{eventId:d.id}},async track(a){o();let p=J(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&&dn(s,r.shutdownTimeoutMs),s}function dn(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 Z(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=ct(i),a=ot(i);return{...s,kb:a,_config:i}}function pn(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 un(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=Z(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=pn(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"}})}}}function X(e,t){return t?(...n)=>console.log(`[waniwani:${e}]`,...n):()=>{}}var le=X("widget-token",!!process.env.WANIWANI_DEBUG),ln=120*1e3,Q=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-ln?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=fn(this.config.apiUrl,"/api/mcp/widget-tokens");le("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(le("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 le("mint failed:",i),null}}};function fn(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function gn(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 dt(e,t,n){if(e.length===0)return;let r=await Promise.all(e.map(async i=>({...i,configHash:await gn(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 pt="waniwani/sessionId",ee="waniwani/geoLocation",te="waniwani/userLocation",wn="openai/userLocation",mn=[wn,ee,te];function ut(e,t){if(t.length===0)return e;let n;for(let r of mn){let o=e[r];if(!S(o))continue;let i;for(let s of t)s in o&&(i||(i={...o}),delete i[s]);i&&(n||(n={...e}),n[r]=i)}return n??e}function S(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function B(e){if(!S(e))return;let t=e._meta;return S(t)?t:void 0}function fe(e){if(!S(e))return;let t=e.content;return Array.isArray(t)?t.find(r=>S(r)&&r.type==="text"&&typeof r.text=="string")?.text:void 0}function hn(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function ge(e,t,n,r,o,i){let s=hn(e,n.toolType),a=n.stripLocationFields,p=a&&a.length>0,c=B(t),d=c&&p?ut(c,a):c,u=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,f=p&&S(i?.output)&&S(i.output._meta)?{...i.output,_meta:ut(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:O(d),metadata:{...n.metadata??{},...o&&{clientInfo:o}}}}async function we(e,t,n){try{await e.track(t)}catch(r){n?.(he(r))}}async function me(e,t){try{await e.flush()}catch(n){t?.(he(n))}}async function ft(e,t,n,r,o){if(!S(e))return;S(e._meta)||(e._meta={});let i=e._meta,s=S(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?.(he(u))}let p=P(i);p&&(a.sessionId||(a.sessionId=p));let c=mt(i);c!==void 0&&(a.geoLocation||(a.geoLocation=c));let d=O(B(r));d&&!a.source&&(a.source=d),i.waniwani=a}var lt=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function gt(e,t){if(!t||!S(e))return;let n=!1;for(let o of lt)if(o in t){n=!0;break}if(!n)return;S(e._meta)||(e._meta={});let r=e._meta;for(let o of lt)o in t&&(o in r||(r[o]=t[o]))}function wt(e,t){let n=B(t);if(!n||!S(e))return;S(e._meta)||(e._meta={});let r=e._meta,o=P(n);o&&!r[pt]&&(r[pt]=o);let i=mt(n);i&&(r[ee]||(r[ee]=i),r[te]||(r[te]=i))}function mt(e){if(!e)return;let t=e[ee]??e[te];if(S(t)||typeof t=="string")return t}function he(e){return e instanceof Error?e:new Error(String(e))}function ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yt(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(ht(e.requestInfo)){let t=e.requestInfo.headers;if(ht(t)){let n={};for(let o of Object.keys(t))n[o.toLowerCase()]=t[o];let r=n["mcp-session-id"];if(typeof r=="string"&&r)return r}}}var kt=Symbol.for("waniwani.wrappedHandler"),ne=X("mcp",!!process.env.WANIWANI_DEBUG),ye="https://app.waniwani.ai",yn="REDACTED";function Tn(e){if(!e)return;let t=e[q];if(!Array.isArray(t)||t.length===0)return;let n=new Set(t.filter(r=>typeof r=="string"));if(n.size!==0)return r=>{if(!S(r))return r;let o=r.stateUpdates;if(!S(o))return r;let i=!1,s={...o};for(let a of n)a in s&&(s[a]=yn,i=!0);return i?{...r,stateUpdates:s}:r}}function Tt(e,t,n,r){let{server:o,tracker:i,opts:s,tokenCache:a,injectToken:p}=n,c=s.applyFieldRedactions===!0?Tn(r):void 0,d=c?{...s,redactInput:c}:s,u=async(f,h)=>{let g=B(h)??{};if(!P(g)&&S(h)){let y=yt(h);y&&(g["waniwani/sessionId"]=y,h._meta=g)}let l=_e(i,g,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});S(h)&&(h[oe]=l);let x=performance.now(),T=o.server?.getClientVersion?.();try{let y=await t(f,h),k=Math.round(performance.now()-x);ne(`tool "${e}" handler returned in ${k}ms, running post-processing...`);let E=S(y)&&y.isError===!0;if(E){let v=fe(y);console.error(`[waniwani] Tool "${e}" returned error${v?`: ${v}`:""}`)}return await we(i,ge(e,h,d,{durationMs:k,status:E?"error":"ok",...E&&{errorMessage:fe(y)??"Unknown tool error"}},T,{input:f,output:y}),s.onError),ne(`tool "${e}" tracking done`),s.flushAfterToolCall&&await me(i,s.onError),wt(y,h),gt(y,r),p&&(await ft(y,a,i._config.apiUrl??ye,h,s.onError),ne(`tool "${e}" widget config injected`)),ne(`tool "${e}" post-processing complete, returning result`),y}catch(y){let k=Math.round(performance.now()-x);throw await we(i,ge(e,h,d,{durationMs:k,status:"error",errorMessage:y instanceof Error?y.message:String(y)},T,{input:f}),s.onError),s.flushAfterToolCall&&await me(i,s.onError),y}};return u[kt]=!0,u}function kn(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??Z(),i=r.injectWidgetToken!==!1,s=o._config.apiKey?new Q({apiUrl:o._config.apiUrl??ye,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,h]=d;if(typeof h!="function")return p(...d);let g=typeof u=="string"&&u.trim().length>0?u:"unknown",R=S(f)&&S(f._meta)?f._meta:void 0,l=Tt(g,h,a,R);return p(u,f,l)});let c=e._registeredTools;if(S(c))for(let[d,u]of Object.entries(c)){if(!S(u))continue;let f=u.handler;if(typeof f!="function"||f[kt])continue;let h=S(u._meta)?u._meta:void 0;u.handler=Tt(d,f,a,h)}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 h=f._meta,g=h&&typeof h=="object"?h._flowGraph:void 0;g?.nodes?.length&&u.push(g)}}u.length>0&&dt(u,o._config.apiUrl??ye,o._config.apiKey)}return n}export{C as END,b as START,N as StateGraph,A as WaniwaniKvStore,ze as createFlow,Ye as createFlowTestHarness,rt as createResource,Vt as createTool,un as createTrackingRoute,re as detectPlatform,vt as isMCPApps,St as isOpenAI,Be as redacted,zt as registerTools,kn as withWaniwani};
7
7
  //# sourceMappingURL=index.js.map