@waniwani/sdk 0.20.0 → 0.20.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/chat/embed.js +70 -68
- package/dist/chat/embed.js.map +1 -1
- package/dist/chat/index.d.ts +128 -2
- package/dist/chat/index.js +9 -7
- package/dist/chat/index.js.map +1 -1
- package/dist/chat/styles.css +1 -1
- package/dist/documents/index.d.ts +104 -0
- package/dist/documents/index.js +2 -0
- package/dist/documents/index.js.map +1 -0
- package/dist/index.d.ts +79 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/mcp/index.d.ts +480 -1
- package/dist/mcp/index.js +5 -5
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/react/skybridge.js +1 -1
- package/dist/mcp/react/skybridge.js.map +1 -1
- package/dist/mcp/react.js +1 -1
- package/dist/mcp/react.js.map +1 -1
- package/package.json +6 -1
package/dist/mcp/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var _="__start__",N="__end__",Ne=Symbol.for("waniwani.flow.interrupt"),Ae=Symbol.for("waniwani.flow.widget");function We(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:Ne,questions:r,context:n}}function Oe(e,t){let n=typeof e=="object"&&e!==null&&"tool"in e,r=n?e.tool:e,o=n?e:t??{};if(o.description!==void 0){let c=typeof r=="string"?r:r.id;throw new Error(`showWidget("${c}", { description }) is no longer supported. The engine now emits a standardized instruction telling the AI to call the widget tool. Return any per-widget description from the "${c}" tool's own response instead.`)}let{data:i,interactive:s,field:a}=o;return{__type:Ae,tool:typeof r=="string"?r:r.id,...i!==void 0?{data:i}:{},...s!==void 0?{interactive:s}:{},...a!==void 0?{field:a}:{}}}function Me(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Ne}function Ue(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Ae}import{z as U}from"zod";function J(e){return{priceShown:({amount:t,currency:n,itemId:r,label:o,...i})=>e({event:"price_shown",properties:{amount:t,currency:n,itemId:r,label:o},...i}),pricesCompared:({options:t,...n})=>e({event:"prices_compared",properties:{options:t},...n}),optionSelected:({id:t,amount:n,currency:r,...o})=>e({event:"option_selected",properties:{id:t,amount:n,currency:r},...o}),leadQualified:t=>{let{externalId:n,email:r,name:o,...i}=t??{};return e({event:"lead_qualified",properties:{externalId:n,email:r,name:o},...i})},converted:({amount:t,currency:n,occurredAt:r,...o})=>e({event:"converted",properties:{amount:t,currency:n,occurredAt:r},...o})}}var ge="waniwani/suggestions";function j(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var Nt=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],At=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Wt=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],Ot=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],Mt=["waniwani/visitorId","visitorId"],Ut=["correlationId","openai/requestId"];var L="waniwani/flow",Q="waniwani/widget";function F(e){return e?j(e,Nt):void 0}function De(e){return e?j(e,At):void 0}function je(e){return e?j(e,Wt):void 0}function X(e){return e?j(e,Ot):void 0}function ee(e){return e?j(e,Mt):void 0}function Le(e){return e?j(e,Ut):void 0}var Kt=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],Dt=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function W(e,t){if(e){let r=e["waniwani/source"];if(typeof r=="string"&&r.length>0)return r;for(let{key:o,source:i}of Kt){let s=e[o];if(typeof s=="string"&&s.length>0)return i}}let n=t?.name;if(typeof n=="string"&&n.length>0){let r=n.toLowerCase();for(let{needle:o,source:i}of Dt)if(r.includes(o))return i}}function Ke(e,t){let n=t.toLowerCase(),r=e[t]??e[n];if(r===void 0){for(let i of Object.keys(e))if(i.toLowerCase()===n){r=e[i];break}}let o=Array.isArray(r)?r[0]:r;return typeof o=="string"&&o.length>0?o:void 0}function Be(e){if(!e)return;let t=Ke(e,"user-agent"),n=Ke(e,"x-anthropic-client");if(t&&/claude/i.test(t)||n&&/claude|anthropic/i.test(n))return"claude";if(t&&/chatgpt|openai/i.test(t))return"chatgpt"}var te="waniwani/client";function he(e){if(typeof e=="object"&&e!==null)return e[te]}function qe(e,t,n){let r=o=>e.track({...o,meta:{...t,...o.meta}});return{sessionId:F(t),visitorId:ee(t),externalUserId:X(t),track:Object.assign(r,J(r)),identify(o,i){return e.identify(o,i,t)},kb:e.kb,_config:n}}import{z as we}from"zod";var jt=we.object({status:we.number().optional(),statusCode:we.number().optional()});function Lt(e){let t=jt.safeParse(e);if(t.success)return t.data.status??t.data.statusCode}var Bt=["fetch failed","failed to fetch","networkerror when attempting to fetch"];function O({error:e}){if(e instanceof Error&&e.name==="ZodError")return"invalid_output";if(e instanceof Error&&(e.name==="AbortError"||e.name==="TimeoutError"))return"timeout";let t=Lt(e);return t===429?"rate_limited":t!==void 0&&t>=500?"upstream_5xx":t!==void 0&&t>=400?"upstream_4xx":e instanceof TypeError&&Bt.some(n=>e.message.toLowerCase().includes(n))?"network":"unknown"}function C({waniwani:e,code:t,cause:n,properties:r}){try{console.error(`[waniwani][session-error] ${t}:${r?.tool??"-"}:${n}`,{node:r?.node})}catch{}if(e)try{Promise.resolve(e.track({event:"session.error",properties:{code:t,cause:n,...r}})).catch(()=>{})}catch{}}function $e(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function z(e,t){let n=t.split("."),r=e;for(let o of n){if(r==null||typeof r!="object")return;r=r[o]}return r}function qt(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 Ve(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 ne(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?qt(t,n,r):r!==null&&typeof r=="object"&&!Array.isArray(r)?t=M(t,{[n]:r}):t[n]=r;return t}function M(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]=M(n[r],o):n[r]=o;return n}function He(e){return e._zod?.def}function $t(e){let t=e,n=!1;for(let r=0;r<8;r++){let o=He(t);if(!o?.innerType)break;if(o.type==="optional"||o.type==="nullable"||o.type==="default"){n=!0,t=o.innerType;continue}break}return{inner:t,optional:n}}function ze(e){let{inner:t,optional:n}=$t(e),r=t.description??e.description??void 0,o=He(t),i=o?.type,s={type:"unknown",...r?{description:r}:{},...n?{optional:!0}:{}};return i==="enum"&&o?.entries?{...s,type:"enum",values:Object.keys(o.entries)}:i==="string"||i==="number"||i==="boolean"||i==="object"||i==="array"?{...s,type:i}:s}function me(e,t){if(!e||!t)return;if(t.includes(".")){let r=t.indexOf("."),o=t.slice(0,r),i=t.slice(r+1),s=e[o];if(!s)return;let c=$e(s)?.[i];return c?ze(c):void 0}let n=e[t];if(n)return ze(n)}function ye(e){return e!=null&&e!==""}async function K(e,t){return e.type==="direct"?e.to:e.condition(t)}function Ge(e,t,n,r,o){if(e.every(d=>ye(z(r,d.field))))return null;let i=e.filter(d=>!ye(z(r,d.field))).map(d=>{let l=me(o,d.field);return l?{...d,fieldSchema:l}:d}),s=i.length===1,a=i[0];return{content:s&&a?{status:"interrupt",question:a.question,field:a.field,...a.suggestions?{suggestions:a.suggestions}:{},...a.fieldSchema?{fieldSchema:a.fieldSchema}:{},...a.context||t?{context:a.context??t}:{}}:{status:"interrupt",questions:i,...t?{context:t}:{}},flowTokenContent:{step:n,state:r,...s&&a?{field:a.field}:{}}}}async function H(e,t,n,r,o,i,s,a,c){let d=e,l={...t},u=[],p=50,I=0;for(;I++<p;){if(d===N)return{content:{status:"complete"},flowTokenContent:{state:l},nodesVisited:u};let g=n.get(d);if(!g)return C({waniwani:s,code:"agent_failed",cause:"flow_unknown_node",properties:{node:d}}),{content:{status:"error",error:`Unknown node: "${d}"`},nodesVisited:u};a?.get(d)?.hideFromFunnel||u.push({id:d,at:new Date().toISOString()});try{let m=await g({state:l,meta:i,interrupt:We,showWidget:Oe,waniwani:s});if(Me(m)){for(let f of m.questions)f.validate&&o.set(`${d}:${f.field}`,f.validate);let y=Ge(m.questions,m.context,d,l,c);if(y)return{...y,nodesVisited:u};for(let f of m.questions){let T=o.get(`${d}:${f.field}`);if(T)try{let x=z(l,f.field),b=await T(x);b&&typeof b=="object"&&(l=M(l,b))}catch(x){let b=x instanceof Error?x.message:String(x);Ve(l,f.field);let A=m.questions.map(D=>D.field===f.field?{...D,context:D.context?`ERROR: ${b}
|
|
1
|
+
function sn(e){if(!(typeof e!="object"||e===null))return e}function Ke(e){return sn(e?.ui)}function je(e){if(!e)return;let t=Ke(e)?.resourceUri;if(typeof t=="string"&&t.length>0)return t;let n=e["ui/resourceUri"];if(typeof n=="string"&&n.length>0)return n;let r=e["openai/outputTemplate"];if(typeof r=="string"&&r.length>0)return r}function an(e){return Ke(e)?.autoHeight===!0}function Le(e){return je(e?._meta)}function cn(e){return Le(e)!==void 0}function Be(){if(typeof document>"u"&&typeof navigator>"u")return null;let e=(typeof document<"u"?document.modelContext:void 0)??(typeof navigator<"u"?navigator.modelContext:void 0);return e&&typeof e.registerTool=="function"?e:null}function $e(){return Be()!==null}function dn(){return{url:location.href,title:document.title}}async function qe(e){let{endpoint:t,headers:n,sessionId:r,visitorId:o,channelId:i,onWidget:s}=e,a=e.logger??console,c=Be();if(!c)return null;let d=new AbortController,l=()=>d.abort();window.addEventListener("pagehide",l);let u=!1,p=()=>{u||(u=!0,window.removeEventListener("pagehide",l),d.abort())};function I(){return{sessionId:r,visitorId:o,channelId:i,page:dn()}}async function E(x,y){let R=await fetch(t,{method:"POST",headers:{"content-type":"application/json",...n},body:JSON.stringify(x),...y?{signal:y}:{}});if(!R.ok)throw new Error(`webmcp ${x.action} failed: ${R.status}`);return await R.json()}let h=[];try{h=(await E({...I(),action:"list"}))?.tools??[]}catch(x){return a.error("[webmcp] could not list site tools",x),p(),null}let w=[];return await Promise.all(h.map(async x=>{try{await c.registerTool({name:x.name,description:x.description??"",...x.inputSchema?{inputSchema:x.inputSchema}:{},...x.annotations?{annotations:x.annotations}:{},execute:async(y,R)=>{let f=await E({...I(),action:"call",name:x.name,arguments:y??{}},R?.signal);return f?.widget&&s?.(f.widget),{content:f?.content??[]}}},{signal:d.signal}),w.push(x)}catch(y){a.error(`[webmcp] could not register ${x.name}`,y)}})),a.info(`[webmcp] registered ${w.length} site tool(s)`),{get tools(){return w},dispose:p}}function Ve(e){let t=e.content?.[0];if(!t||t.type!=="text"||typeof t.text!="string")return null;let n;try{n=JSON.parse(t.text)}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.status!=="widget"||typeof r.tool!="string")return null;let o=r.data&&typeof r.data=="object"&&!Array.isArray(r.data)?r.data:{};return{payload:r,tool:r.tool,data:o,interactive:r.interactive===!0}}var ln='The interface for this step is now open in front of the user, on the page. There is no display tool to call on this surface, so do not try. Say one short sentence about what is on screen, then stop and wait for the user to tell you what they did. When they do, call this flow again with action "continue".',un='The interface for this step is now open in front of the user, on the page. There is no display tool to call on this surface, so do not try. Summarise `data` in one short sentence, then call this flow again with action "continue".',pn="The interface for this step could not be opened on the page. Carry the step in words instead: tell the user everything in `data` yourself, then proceed as you otherwise would.";function He(e,t){let{tool:n,description:r,...o}=e.payload;return{...o,status:t?"widget_shown":"widget_unavailable",instructions:t?e.interactive?ln:un:pn}}var A="__start__",O="__end__",ze=Symbol.for("waniwani.flow.interrupt"),Ye=Symbol.for("waniwani.flow.widget");function Ge(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:ze,questions:r,context:n}}function Ze(e,t){let n=typeof e=="object"&&e!==null&&"tool"in e,r=n?e.tool:e,o=n?e:t??{};if(o.description!==void 0){let c=typeof r=="string"?r:r.id;throw new Error(`showWidget("${c}", { description }) is no longer supported. The engine now emits a standardized instruction telling the AI to call the widget tool. Return any per-widget description from the "${c}" tool's own response instead.`)}let{data:i,interactive:s,field:a}=o;return{__type:Ye,tool:typeof r=="string"?r:r.id,...i!==void 0?{data:i}:{},...s!==void 0?{interactive:s}:{},...a!==void 0?{field:a}:{}}}function Je(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===ze}function Xe(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Ye}import{z as L}from"zod";var $=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var fn="@waniwani/sdk",gn="/api/mcp/modules/documents/extract";function mn(e,t){try{let n=JSON.parse(e);if(n!==null&&typeof n=="object"){let r="message"in n&&typeof n.message=="string"?n.message:"",o="detail"in n&&typeof n.detail=="string"?n.detail:"";if(r&&o)return`${r}: ${o}`;if(r)return r;if(o)return o}}catch{}return e||`Documents API error: HTTP ${t}`}function wn(e){return"documentId"in e&&typeof e.documentId=="string"}function hn(e){return wn(e)?{documentId:e.documentId}:{url:e.url,filename:e.filename}}function ee(e){let{apiUrl:t,apiKey:n}=e;return{async extract(r){if(!n)throw new Error("WANIWANI_API_KEY is not set");let{toJSONSchema:o}=await import("zod"),i=await fetch(`${t.replace(/\/$/,"")}${gn}`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-WaniWani-SDK":fn},body:JSON.stringify({...hn(r),schema:o(r.schema),pages:r.pages,sessionId:r.sessionId,correlationId:r.correlationId})});if(!i.ok){let u=await i.text().catch(()=>"");throw new $(mn(u,i.status),i.status)}let s=await i.json(),{fields:a,pageCount:c,pageConfidence:d,documentId:l}=s.data;return{fields:r.schema.parse(a),pageCount:c,pageConfidence:d??null,documentId:l}}}}function te(e){return{priceShown:({amount:t,currency:n,itemId:r,label:o,...i})=>e({event:"price_shown",properties:{amount:t,currency:n,itemId:r,label:o},...i}),pricesCompared:({options:t,...n})=>e({event:"prices_compared",properties:{options:t},...n}),optionSelected:({id:t,amount:n,currency:r,...o})=>e({event:"option_selected",properties:{id:t,amount:n,currency:r},...o}),leadQualified:t=>{let{externalId:n,email:r,name:o,...i}=t??{};return e({event:"lead_qualified",properties:{externalId:n,email:r,name:o},...i})},converted:({amount:t,currency:n,occurredAt:r,...o})=>e({event:"converted",properties:{amount:t,currency:n,occurredAt:r},...o})}}var ne="https://app.waniwani.ai";var yn=["documentId","document_id"],Tn=["filename","file_name","fileName","name"],Sn=["mediaType","media_type","mimeType","mime_type","contentType","content_type"],kn="document",vn="application/octet-stream";function q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Se(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function xn(e){if(!q(e))return;let t=Se(e,yn);if(t)return{documentId:t,filename:Se(e,Tn)??kn,mediaType:Se(e,Sn)??vn}}function Qe(e){let t=[],n=new Set;for(let r of Array.isArray(e)?e:[e]){let o=xn(r);o&&!n.has(o.documentId)&&(n.add(o.documentId),t.push(o))}return t}function In(e){if(!Array.isArray(e))return[];let t=[...e].reverse().find(n=>q(n)&&n.role==="user");return!q(t)||!Array.isArray(t.parts)?[]:Qe(t.parts.flatMap(n=>q(n)&&q(n.data)?[n,n.data]:[n]))}function et(e){let t=q(e)?e:void 0,n=Qe(t?t.documents:e);return n.length>0?n:In(t?t.messages:e)}var ke="waniwani/suggestions";function U(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var En=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],Rn=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],bn=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],Cn=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],_n=["waniwani/visitorId","visitorId"],Fn=["correlationId","openai/requestId"];var An=["waniwani/fileParams","openai/fileParams"],Pn=["url","uri","download_url","downloadUrl","file_url","fileUrl","signed_url","signedUrl"],Wn=["filename","file_name","fileName","name"],V="waniwani/flow",re="waniwani/widget";function W(e){return e?U(e,En):void 0}function nt(e){return e?U(e,Rn):void 0}function rt(e){return e?U(e,bn):void 0}function oe(e){return e?U(e,Cn):void 0}function ie(e){return e?U(e,_n):void 0}function se(e){return e?U(e,Fn):void 0}function ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nn(e){if(!(typeof e!="string"||e.length===0))try{let t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?e:void 0}catch{return}}function Mn(e){try{let t=new URL(e).pathname.split("/").filter(Boolean),n=t[t.length-1];return n?decodeURIComponent(n):"document"}catch{return"document"}}function On(e){if(!ot(e))return;let t=Nn(U(e,Pn));if(!t)return;let n=U(e,Wn);return{url:t,filename:n??Mn(t)}}function it(e){if(!e)return[];for(let t of An){let n=Un(e[t]);if(n.length>0)return n}return[]}function Un(e){let t=[],n=new Set,r=o=>{if(Array.isArray(o)){for(let s of o)r(s);return}let i=On(o);if(i){n.has(i.url)||(n.add(i.url),t.push(i));return}if(ot(o))for(let s of Object.values(o))r(s)};return r(e),t}var Dn="waniwani/documents";function st(e){if(!e)return[];let t=e[Dn];return et(Array.isArray(t)?t:[t])}var Kn=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],jn=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function D(e,t){if(e){let r=e["waniwani/source"];if(typeof r=="string"&&r.length>0)return r;for(let{key:o,source:i}of Kn){let s=e[o];if(typeof s=="string"&&s.length>0)return i}}let n=t?.name;if(typeof n=="string"&&n.length>0){let r=n.toLowerCase();for(let{needle:o,source:i}of jn)if(r.includes(o))return i}}function tt(e,t){let n=t.toLowerCase(),r=e[t]??e[n];if(r===void 0){for(let i of Object.keys(e))if(i.toLowerCase()===n){r=e[i];break}}let o=Array.isArray(r)?r[0]:r;return typeof o=="string"&&o.length>0?o:void 0}function at(e){if(!e)return;let t=tt(e,"user-agent"),n=tt(e,"x-anthropic-client");if(t&&/claude/i.test(t)||n&&/claude|anthropic/i.test(n))return"claude";if(t&&/chatgpt|openai/i.test(t))return"chatgpt"}var ae="waniwani/client";function ve(e){if(typeof e=="object"&&e!==null)return e[ae]}function ct(e,t,n){let r=a=>e.track({...a,meta:{...t,...a.meta}}),o=W(t),i=se(t),s=ee({apiUrl:n?.apiUrl??process.env.WANIWANI_API_URL??ne,apiKey:n?.apiKey});return{sessionId:o,visitorId:ie(t),externalUserId:oe(t),track:Object.assign(r,te(r)),identify(a,c){return e.identify(a,c,t)},kb:e.kb,attachedFiles:it(t),attachedDocuments:st(t),documents:{extract(a){return s.extract({...a,sessionId:a.sessionId??o,correlationId:a.correlationId??i})}},_config:n}}import{z as xe}from"zod";var Ln=xe.object({status:xe.number().optional(),statusCode:xe.number().optional()});function Bn(e){let t=Ln.safeParse(e);if(t.success)return t.data.status??t.data.statusCode}var $n=["fetch failed","failed to fetch","networkerror when attempting to fetch"];function K({error:e}){if(e instanceof Error&&e.name==="ZodError")return"invalid_output";if(e instanceof Error&&(e.name==="AbortError"||e.name==="TimeoutError"))return"timeout";let t=Bn(e);return t===429?"rate_limited":t!==void 0&&t>=500?"upstream_5xx":t!==void 0&&t>=400?"upstream_4xx":e instanceof TypeError&&$n.some(n=>e.message.toLowerCase().includes(n))?"network":"unknown"}function F({waniwani:e,code:t,cause:n,properties:r}){try{console.error(`[waniwani][session-error] ${t}:${r?.tool??"-"}:${n}`,{node:r?.node})}catch{}if(e)try{Promise.resolve(e.track({event:"session.error",properties:{code:t,cause:n,...r}})).catch(()=>{})}catch{}}function dt(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function Z(e,t){let n=t.split("."),r=e;for(let o of n){if(r==null||typeof r!="object")return;r=r[o]}return r}function qn(e,t,n){let r=t.split("."),o=r.pop();if(!o)return;let i=e;for(let s of r)(i[s]==null||typeof i[s]!="object"||Array.isArray(i[s]))&&(i[s]={}),i=i[s];i[o]=n}function lt(e,t){let n=t.split("."),r=n.pop();if(!r)return;let o=e;for(let i of n){if(o==null||typeof o!="object")return;o=o[i]}o!=null&&typeof o=="object"&&delete o[r]}function ce(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?qn(t,n,r):r!==null&&typeof r=="object"&&!Array.isArray(r)?t=j(t,{[n]:r}):t[n]=r;return t}function j(e,t){let n={...e};for(let[r,o]of Object.entries(t))o!==null&&typeof o=="object"&&!Array.isArray(o)&&n[r]!==null&&typeof n[r]=="object"&&!Array.isArray(n[r])?n[r]=j(n[r],o):n[r]=o;return n}function pt(e){return e._zod?.def}function Vn(e){let t=e,n=!1;for(let r=0;r<8;r++){let o=pt(t);if(!o?.innerType)break;if(o.type==="optional"||o.type==="nullable"||o.type==="default"){n=!0,t=o.innerType;continue}break}return{inner:t,optional:n}}function ut(e){let{inner:t,optional:n}=Vn(e),r=t.description??e.description??void 0,o=pt(t),i=o?.type,s={type:"unknown",...r?{description:r}:{},...n?{optional:!0}:{}};return i==="enum"&&o?.entries?{...s,type:"enum",values:Object.keys(o.entries)}:i==="string"||i==="number"||i==="boolean"||i==="object"||i==="array"?{...s,type:i}:s}function Ie(e,t){if(!e||!t)return;if(t.includes(".")){let r=t.indexOf("."),o=t.slice(0,r),i=t.slice(r+1),s=e[o];if(!s)return;let c=dt(s)?.[i];return c?ut(c):void 0}let n=e[t];if(n)return ut(n)}function Ee(e){return e!=null&&e!==""}async function B(e,t){return e.type==="direct"?e.to:e.condition(t)}function ft(e,t,n,r,o){if(e.every(d=>Ee(Z(r,d.field))))return null;let i=e.filter(d=>!Ee(Z(r,d.field))).map(d=>{let l=Ie(o,d.field);return l?{...d,fieldSchema:l}:d}),s=i.length===1,a=i[0];return{content:s&&a?{status:"interrupt",question:a.question,field:a.field,...a.suggestions?{suggestions:a.suggestions}:{},...a.fieldSchema?{fieldSchema:a.fieldSchema}:{},...a.context||t?{context:a.context??t}:{}}:{status:"interrupt",questions:i,...t?{context:t}:{}},flowTokenContent:{step:n,state:r,...s&&a?{field:a.field}:{}}}}async function gt(e,t,n,r,o,i,s,a,c){let d=e,l={...t},u=[],p=50,I=0;for(;I++<p;){if(d===O)return{content:{status:"complete"},flowTokenContent:{state:l},nodesVisited:u};let E=n.get(d);if(!E)return F({waniwani:s,code:"agent_failed",cause:"flow_unknown_node",properties:{node:d}}),{content:{status:"error",error:`Unknown node: "${d}"`},nodesVisited:u};a?.get(d)?.hideFromFunnel||u.push({id:d,at:new Date().toISOString()});try{let w=await E({state:l,meta:i,interrupt:Ge,showWidget:Ze,waniwani:s});if(Je(w)){for(let f of w.questions)f.validate&&o.set(`${d}:${f.field}`,f.validate);let y=ft(w.questions,w.context,d,l,c);if(y)return{...y,nodesVisited:u};for(let f of w.questions){let T=o.get(`${d}:${f.field}`);if(T)try{let b=Z(l,f.field),S=await T(b);S&&typeof S=="object"&&(l=j(l,S))}catch(b){let S=b instanceof Error?b.message:String(b);lt(l,f.field);let C=w.questions.map(_=>_.field===f.field?{..._,context:_.context?`ERROR: ${S}
|
|
2
2
|
|
|
3
|
-
${D.context}`:`ERROR: ${b}`}:D),Z=Ge(A,m.context,d,l,c);if(Z)return{...Z,nodesVisited:u};break}}let v=r.get(d);if(!v)return C({waniwani:s,code:"agent_failed",cause:"flow_dead_end",properties:{node:d}}),{content:{status:"error",error:`No outgoing edge from node "${d}"`},nodesVisited:u};d=await K(v,l);continue}if(Ue(m)){let y=m.field;if(y&&ye(z(l,y))){let T=r.get(d);if(!T)return C({waniwani:s,code:"agent_failed",cause:"flow_dead_end",properties:{node:d}}),{content:{status:"error",error:`No outgoing edge from node "${d}"`},nodesVisited:u};d=await K(T,l);continue}let v=y?me(c,y):void 0,f=m.interactive!==!1;return{content:{status:"widget",tool:m.tool,...m.data!==void 0?{data:m.data}:{},description:f?`IMPORTANT: You MUST now call the ${m.tool} tool to display the widget. Do NOT skip this step`:`IMPORTANT \u2014 two ordered steps. STEP 1: call the ${m.tool} tool RIGHT NOW to display this widget to the user. This renders UI the user must see \u2014 do NOT skip it and do NOT jump straight to action:"continue". STEP 2: ONLY AFTER ${m.tool} has been called, call this flow again with action:"continue".`,interactive:f,...y?{field:y}:{},...v?{fieldSchema:v}:{}},flowTokenContent:{step:d,state:l,field:y,widgetId:m.tool},nodesVisited:u}}l=M(l,m);let R=r.get(d);if(!R)return C({waniwani:s,code:"agent_failed",cause:"flow_dead_end",properties:{node:d}}),{content:{status:"error",error:`No outgoing edge from node "${d}"`},nodesVisited:u};d=await K(R,l)}catch(S){let m=S instanceof Error?S.message:String(S);return C({waniwani:s,code:"agent_failed",cause:O({error:S}),properties:{node:d}}),{content:{status:"error",error:m},flowTokenContent:{step:d,state:l},nodesVisited:u}}}return C({waniwani:s,code:"agent_failed",cause:"flow_loop",properties:{node:d}}),{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"},nodesVisited:u}}function Te(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var Ye=new Map;async function Ze(e){let t=Ye.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 Ye.set(e,r),r}async function Je(e,t){let n=await Ze(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 Qe(e,t){let n=await Ze(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 Vt={debug:0,warn:1,error:2,none:3};function zt(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in Vt?e:process.env.WANIWANI_DEBUG?"debug":"none"}function B(e,t){return t??zt()==="debug"?(...r)=>console.log(`[waniwani:${e}]`,...r):()=>{}}var Ht="@waniwani/sdk",Gt="https://app.waniwani.ai",Yt=B("kv"),q=class{get baseUrl(){return(process.env.WANIWANI_API_URL??Gt).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(Te(n)){if(!this.encryptionKey)throw new Error("[Waniwani KV] Encrypted data found but WANIWANI_ENCRYPTION_KEY is not set.");return Qe(n,this.encryptionKey)}return n}async set(t,n,r){if(!this.apiKey)throw new Error("[Waniwani KV] No API key configured. Set WANIWANI_API_KEY env var.");let o=this.encryptionKey;Yt(`set "${t}" \u2014 encryption ${o?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let i=o?await Je(n,o):n;await this.request("/api/mcp/redis/set",{key:t,value:i,ttlSeconds:r?.ttlSeconds})}async delete(t){if(this.apiKey)try{await this.request("/api/mcp/redis/delete",{key:t})}catch(n){console.error("[Waniwani KV] delete failed for key:",t,n)}}async request(t,n){let r=`${this.baseUrl}${t}`,o=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","X-WaniWani-SDK":Ht},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 re=class{map=new Map;async get(t){return this.map.get(t)??null}async set(t,n,r){this.map.set(t,n)}async delete(t){this.map.delete(t)}};var G=class{store=new q;get(t){return this.store.get(t)}set(t,n,r){return this.store.set(t,n,r)}delete(t){return this.store.delete(t)}};function Zt(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function Xe(e,t,n,r){let o=[];for(let[s,a]of t){let c=r.get(s);o.push({id:s,type:Zt(a),label:c?.label??s,...c?.hideFromFunnel?{hideFromFunnel:!0}:{}})}let i=[];for(let[s,a]of n)a.type==="direct"?i.push({from:s,to:a.to,type:"direct"}):i.push({from:s,to:a.targets,type:"conditional"});return{flowId:e.id,title:e.title,nodes:o,edges:i}}import{z as E}from"zod";var et=E.object({type:E.enum(["enum","string","number","boolean","object","array","unknown"]),values:E.array(E.string()).optional(),description:E.string().optional(),optional:E.boolean().optional()}).describe("JIT schema fragment for a state field \u2014 type, allowed values, and description."),Jt=E.object({question:E.string(),field:E.string(),suggestions:E.array(E.string()).optional(),context:E.string().optional(),fieldSchema:et.optional()}).describe("One question within a multi-question interrupt."),Se={status:E.enum(["interrupt","widget","complete","error"]).describe("Current flow status and the next action the assistant should take."),question:E.string().optional().describe("Single question to ask the user when status is interrupt."),field:E.string().optional().describe("State field to fill with the user's answer on the next continue call."),fieldSchema:et.optional().describe("JIT schema fragment for the single-question shorthand."),suggestions:E.array(E.string()).optional().describe("Suggested answers for the single-question shorthand."),questions:E.array(Jt).optional().describe("Multiple questions to ask the user when status is interrupt."),context:E.string().optional().describe("Private instruction context for the assistant."),tool:E.string().optional().describe("Widget tool to call when status is widget."),data:E.record(E.string(),E.unknown()).optional().describe("Input data to pass to the widget tool."),description:E.string().optional().describe("Instruction for rendering the requested widget."),interactive:E.boolean().optional().describe("Whether the widget requires user interaction before continuing."),sessionId:E.string().optional().describe("Session identifier to pass on future continue and reset calls."),error:E.string().optional().describe("Error message when status is error.")};function tt(e){let t=["","## FLOW EXECUTION PROTOCOL","","This tool implements a multi-step conversational flow. Follow this protocol exactly:","",'1. Call with `action: "start"` to begin and include `intent`.'," `intent` must be a brief summary of the user's goal for this flow."," Do NOT invent missing intent."," Optionally include `context` \u2014 the situation or environment that led the user to start"," this flow (e.g. what page they are on, what they were doing, or what triggered the request)."," Only provide `context` when there is genuinely relevant situational information. Do NOT invent missing context."," If the user's message already contains answers to likely questions,"," extract them into `stateUpdates` as `{ field: value }` pairs (see the `stateUpdates` schema"," for the list of writable fields). The engine will auto-skip steps whose fields are already filled."," Only extract values the user explicitly stated \u2014 do NOT guess or invent values."];return e.omitIntentPII&&t.push(" Do NOT include PII in `intent` or `context` \u2014 no names, emails, phones, addresses, IDs, ages, or birthdates.",' Summarize the goal abstractly (e.g. "user wants a quote", not "Jane Doe wants a quote").'),t.push(" For grouped fields (z.object state), use dot-notation keys in `stateUpdates`:",' e.g. `{ "driver.name": "John", "driver.license": "ABC123" }`.',"2. The response JSON `status` field tells you what to do next:",' - `"interrupt"`: Pause and ask the user. Two forms:'," a. Single question: `{ question, field, fieldSchema?, context? }` \u2014 ask `question`, store answer in `field`."," b. Multi-question: `{ questions: [{question, field, fieldSchema?}, ...], context? }` \u2014 ask ALL questions"," in one conversational message, collect all answers."," `fieldSchema` (when present) describes the expected value: `{ type, values?, description?, optional? }`.",' Use it to validate before sending \u2014 match enum `values` exactly, coerce strings to numbers where `type: "number"`.'," `context` (if present) is hidden AI instructions \u2014 use to shape your response, do NOT show verbatim."," Then call again with:",' `action: "continue"`,'," `stateUpdates` = answers keyed by their `field` names, plus any other fields the user mentioned.",' - `"widget"`: The flow wants to show a UI widget. Call the tool named in the `tool`'," field, passing the `data` object as the tool's input."," Check the `interactive` field in the response:"," \u2022 `interactive: true` \u2014 The widget requires user interaction. After calling the display tool,"," STOP and WAIT for the user to interact with the widget. Do NOT call this flow tool again"," until the user has responded. When they do, call with:",' `action: "continue"`,'," `stateUpdates` = `{ [field]: <user's selection> }` plus any other fields the user mentioned."," \u2022 `interactive: false` \u2014 The widget is display-only. You MUST STILL call the display tool"," FIRST to render it for the user \u2014 this is a required, user-visible step. Do NOT skip it",' and do NOT jump straight to `action: "continue"`. ONLY AFTER you have called the display',' tool, call THIS flow tool again with `action: "continue"`. Do NOT wait for user interaction.',' - `"complete"`: The flow is done. Present the result to the user.',' - `"error"`: Something went wrong. Show the `error` message.',"","3. Do NOT invent state values. Only use `stateUpdates` for information the user explicitly provided.","4. Include only the fields the user actually answered in `stateUpdates` \u2014 do NOT guess missing ones."," If the user did not answer all pending questions, the engine will re-prompt for the remaining ones."," If the user mentioned values for other known fields, include those too \u2014"," they will be applied immediately and those steps will be auto-skipped.","5. CORRECTION: If the user wants to CHANGE a previously-answered field",' (e.g. "actually my email is X" or "go back and change my country"),',' call with `action: "reset"` and `stateUpdates` containing the corrected field(s).'," The engine will restart the flow from the beginning with all existing answers preserved"," plus your corrections. Steps with filled answers will be auto-skipped."," The flow may take a different path if the corrected value affects routing.",' Do NOT use "reset" for the CURRENT question \u2014 use "continue" for that.',"6. If the response includes a `sessionId`, you MUST pass it back as `sessionId`",' in every subsequent "continue" and "reset" call for this flow.'),t.join(`
|
|
4
|
-
`)}function
|
|
5
|
-
${s}`,c=e.store??
|
|
6
|
-
`)}var $=class{nodes=new Map;edges=new Map;nodeOptions=new Map;config;constructor(t){this.config=t}addNode(t,n,r){let o=typeof t=="string"?t:t.id,i=typeof t=="string"?n:t.run,s=typeof t=="string"?r?.label:t.label,a=typeof t=="string"?r?.hideFromFunnel:t.hideFromFunnel;if(o===_||o===N)throw new Error(`"${o}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(o))throw new Error(`Node "${o}" already exists`);return this.nodes.set(o,i),(s!==void 0||a!==void 0)&&this.nodeOptions.set(o,{label:s??o,hideFromFunnel:a}),this}addEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge. Use addConditionalEdge for branching.`);return this.edges.set(t,{type:"direct",to:n}),this}addConditionalEdge(t,n,r){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge.`);if(n.length===0)throw new Error(`Conditional edge from "${t}" must declare at least one target node in \`to\`.`);return this.edges.set(t,{type:"conditional",condition:r,targets:[...n]}),this}graph(){return st(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return it({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>st(n,r),nodeOptions:new Map(this.nodeOptions)})}validate(){if(!this.edges.has(_))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(_);if(t?.type==="direct"&&t.to!==N&&!this.nodes.has(t.to))throw new Error(`START edge references non-existent node: "${t.to}"`);for(let[n,r]of this.edges){if(n!==_&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(r.type==="direct"&&r.to!==N&&!this.nodes.has(r.to))throw new Error(`Edge from "${n}" references non-existent node: "${r.to}"`);if(r.type==="conditional"&&r.targets){for(let o of r.targets)if(o!==N&&!this.nodes.has(o))throw new Error(`Conditional edge from "${n}" declares non-existent target: "${o}"`)}}for(let[n]of this.nodes)if(!this.edges.has(n))throw new Error(`Node "${n}" has no outgoing edge. Add one with .addEdge("${n}", ...) or .addConditionalEdge("${n}", ...)`)}};function at(e){return new $(e)}function ve(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function dt(e,t){let n=t?.stateStore,r=[],o=`test-session-${Math.random().toString(36).slice(2,10)}`,i={registerTool:(...d)=>{r.push(d)}};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 c(d){return{...d,decodedState:n?await n.get(o):null}}return{async start(d,l,u){let p=await s({action:"start",intent:d,...u?{context:u}:{},...l?{stateUpdates:l}:{}},a);return c(ve(p))},async continueWith(d){let l=await s({action:"continue",...d?{stateUpdates:d}:{}},a);return c(ve(l))},async resetWith(d){let l=await s({action:"reset",stateUpdates:d},a);return c(ve(l))},async lastState(){return n?n.get(o):null}}}var ie=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};import{AsyncLocalStorage as tn}from"async_hooks";var ct=globalThis,se=ct.__waniwaniKbRetrievalStore;se||(se=new tn,ct.__waniwaniKbRetrievalStore=se);var Ee=se;function lt(e){try{Ee.getStore()?.searches.push(e)}catch{}}var nn="@waniwani/sdk";function ut(e){let{apiUrl:t,apiKey:n}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function o(i,s,a){let c=r(),d=`${t.replace(/\/$/,"")}${s}`,l={Authorization:`Bearer ${c}`,"X-WaniWani-SDK":nn},u={method:i,headers:l};a!==void 0&&(l["Content-Type"]="application/json",u.body=JSON.stringify(a));let p=await fetch(d,u);if(!p.ok){let g=await p.text().catch(()=>"");throw new ie(g||`KB API error: HTTP ${p.status}`,p.status)}return(await p.json()).data}return{async ingest(i){return o("POST","/api/mcp/kb/ingest",{files:i})},async search(i,s){let a=await o("POST","/api/mcp/kb/search",{query:i,...s});return lt({query:i,resultCount:a.length,results:a.map(c=>({source:c.source,heading:c.heading,score:c.score}))}),a},async sources(){return o("GET","/api/mcp/kb/sources")}}}import{existsSync as rn,readFileSync as on}from"fs";import{resolve as sn}from"path";var an="waniwani.json",V;function pt(){if(V!==void 0)return V;try{let e=sn(process.cwd(),an);if(!rn(e))return V=null,null;let t=on(e,"utf-8");return V=JSON.parse(t),V}catch{return V=null,null}}var dn="__waniwani_config__";function ft(){return globalThis[dn]}var cn="@waniwani/sdk";function de(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??gt,o=pn(e),i=ae(e.meta),s=ae(e.metadata),a=fn(e,i),c=P(e.eventId)??r(),d=gn(e.timestamp,n),l=P(e.source)??W(i)??t.source??cn,u=xe(e)?{...e}:void 0,p={...s};return Object.keys(i).length>0&&(p.meta=i),u&&(p.rawLegacy=u),{id:c,type:"mcp.event",name:o,source:l,timestamp:d,correlation:a,properties:ln(e,o),metadata:p,rawLegacy:u}}function gt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function ln(e,t){if(!xe(e))return ae(e.properties);let n=un(e,t),r=ae(e.properties);return{...n,...r}}function un(e,t){switch(t){case"tool.called":{let n={};return P(e.toolName)&&(n.name=e.toolName),P(e.toolType)&&(n.type=e.toolType),n}case"link.clicked":{let n={};return P(e.linkUrl)&&(n.url=e.linkUrl),n}default:return{}}}function pn(e){return xe(e)?e.eventType:e.event}function fn(e,t){let n=P(e.requestId)??De(t),r=P(e.sessionId)??F(t),o=P(e.traceId)??je(t),i=P(e.externalUserId)??X(t),s=P(e.visitorId)??ee(t),a=P(e.correlationId)??Le(t)??n,c={};return r&&(c.sessionId=r),o&&(c.traceId=o),n&&(c.requestId=n),a&&(c.correlationId=a),i&&(c.externalUserId=i),s&&(c.visitorId=s),c}function gn(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 ae(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function P(e){if(typeof e=="string"&&e.trim().length!==0)return e}function xe(e){return"eventType"in e}var hn="/api/mcp/events/v2/batch";var ht="@waniwani/sdk";var wn=new Set([401,403]),mn=new Set([408,425,429,500,502,503,504]),yn=(e,t)=>globalThis.fetch(e,t);function wt(e){return new Re(e)}var Re=class{endpointUrl;flushIntervalMs;maxBatchSize;maxBufferSize;maxRetries;retryBaseDelayMs;retryMaxDelayMs;shutdownTimeoutMs;sdkVersion;fetchFn;logger;now;sleep;apiKey;buffer=[];flushTimer;flushScheduled=!1;flushScheduledTimer;flushInFlight;inFlightCount=0;isStopped=!1;isShuttingDown=!1;constructor(t){this.endpointUrl=kn(t.apiUrl,t.endpointPath??hn),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??yn,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(r=>setTimeout(r,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs)),this.registerBrowserTeardown()}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[Waniwani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[Waniwani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,r=this.flush();if(!Number.isFinite(n)||n<=0)return await r,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let o=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(n).then(()=>o)])===o?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}registerBrowserTeardown(){if(typeof document>"u"||typeof window>"u")return;let t=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush()};document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",()=>this.keepaliveFlush())}keepaliveFlush(){if(this.isStopped||this.buffer.length===0)return;let t=this.buffer.splice(0,this.buffer.length);this.sendKeepaliveChunk(t)}sendKeepaliveChunk(t){let n=JSON.stringify(this.makeBatchRequest(t));if(n.length>6e4&&t.length>1){let r=Math.ceil(t.length/2);this.sendKeepaliveChunk(t.slice(0,r)),this.sendKeepaliveChunk(t.slice(r));return}try{this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:n,keepalive:!0}).catch(()=>{})}catch{}}requestHeaders(){let t={"Content-Type":"application/json","X-WaniWani-SDK":ht};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,r=t;for(;r.length>0&&!this.isStopped;){this.inFlightCount=r.length;let o=await this.sendBatchOnce(r);switch(this.inFlightCount=0,o.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(o.status,r.length);return;case"permanent":this.logger.error("[Waniwani] Dropping %d event(s) after permanent failure: %s",r.length,o.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d event(s) after retry exhaustion: %s",r.length,o.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(o.permanent.length>0&&this.logger.error("[Waniwani] Dropping %d event(s) rejected as permanent",o.permanent.length),o.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d retryable event(s) after retry exhaustion",o.retryable.length);return}r=o.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:vn(i)}}if(wn.has(n.status))return{kind:"auth",status:n.status};if(mn.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:ht,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(Tn(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 Tn(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 kn(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function vn(e){return e instanceof Error?e.message:String(e)}function mt(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?wt({apiUrl:t,apiKey:n,endpointPath:r.endpointPath,flushIntervalMs:r.flushIntervalMs,maxBatchSize:r.maxBatchSize,maxBufferSize:r.maxBufferSize,maxRetries:r.maxRetries,retryBaseDelayMs:r.retryBaseDelayMs,retryMaxDelayMs:r.retryMaxDelayMs,shutdownTimeoutMs:r.shutdownTimeoutMs}):void 0;function s(l){o();let u=de(l);return!u.correlation.sessionId&&!u.correlation.externalUserId&&!u.correlation.visitorId&&console.warn(`[waniwani] event "${u.name}" has no sessionId, externalUserId, or visitorId; the ingest API requires one and will reject it.`),i?.enqueue(u),{eventId:u.id}}let a=async l=>s(l),c=Object.assign(a,J(a)),d={async identify(l,u,p){o();let I=de({event:"user.identified",externalUserId:l,properties:u,meta:p});return i?.enqueue(I),{eventId:I.id}},track:c,async flush(){o(),await i?.flush()},async shutdown(l){return o(),await i?.shutdown({timeoutMs:l?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&En(d,r.shutdownTimeoutMs),d}function En(e,t){if(typeof process>"u"||typeof process.once!="function"||typeof process.on!="function")return;let n=()=>{e.shutdown({timeoutMs:t})};process.once("beforeExit",n),process.once("SIGINT",n),process.once("SIGTERM",n)}function ce(e){let n=e??pt()??ft(),r=n?.apiUrl??process.env.WANIWANI_API_URL??"https://app.waniwani.ai",o=n?.apiKey??process.env.WANIWANI_API_KEY,i={endpointPath:n?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:n?.tracking?.flushIntervalMs??1e3,maxBatchSize:n?.tracking?.maxBatchSize??20,maxBufferSize:n?.tracking?.maxBufferSize??1e3,maxRetries:n?.tracking?.maxRetries??3,retryBaseDelayMs:n?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:n?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:n?.tracking?.shutdownTimeoutMs??2e3},s={apiUrl:r,apiKey:o,tracking:i},a=mt(s),c=ut(s);return{...a,kb:c,_config:s}}function xn(e){return{event:e.name??"widget_render",properties:e.properties,metadata:e.metadata,sessionId:e.correlation?.sessionId,traceId:e.correlation?.traceId,requestId:e.correlation?.requestId,correlationId:e.correlation?.correlationId,externalUserId:e.correlation?.externalUserId,visitorId:e.correlation?.visitorId,eventId:e.id,timestamp:e.timestamp,source:e.source}}function Rn(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=ce(t)),n}return async function(i){let s;try{s=await i.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!Array.isArray(s.events)||s.events.length===0)return new Response(JSON.stringify({error:"Missing or empty events array"}),{status:400,headers:{"Content-Type":"application/json"}});try{let a=r(),c=[];for(let d of s.events){let l=await a.track(xn(d));c.push(l.eventId)}return await a.flush(),new Response(JSON.stringify({ok:!0,accepted:c.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(a){let c=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({error:c}),{status:500,headers:{"Content-Type":"application/json"}})}}}var Ie=B("widget-token"),In=120*1e3,le=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-In?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=bn(this.config.apiUrl,"/api/mcp/widget-tokens");Ie("minting token from",r);let o={};t&&(o.sessionId=t),n&&(o.traceId=n);try{let i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)});if(Ie("mint response:",i.status),!i.ok)return null;let s=await i.json(),a=s.data&&typeof s.data=="object"?s.data:s,c=new Date(a.expiresAt).getTime();return!a.token||Number.isNaN(c)?null:(this.cached={token:a.token,expiresAt:c},a.token)}catch(i){return Ie("mint failed:",i),null}}};function bn(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function yt(e){if(typeof globalThis.crypto?.subtle?.digest=="function"){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return`simple-${Math.abs(t).toString(36)}`}function Cn(e){return yt(JSON.stringify({nodes:e.nodes,edges:e.edges}))}async function Tt(e){if(e.length===0)return null;let t=[...e].sort((o,i)=>o.flowId.localeCompare(i.flowId)),n=await yt(JSON.stringify(t.map(o=>({flowId:o.flowId,nodes:o.nodes,edges:o.edges})))),r=await Promise.all(e.map(async o=>({flowId:o.flowId,title:o.title,configHash:await Cn(o),nodes:o.nodes,edges:o.edges})));return{compositeHash:n,flows:r}}var St="waniwani/sessionId",ue="waniwani/geoLocation",pe="waniwani/userLocation",_n="openai/userLocation",Fn=[_n,ue,pe];function kt(e,t){if(t.length===0)return e;let n;for(let r of Fn){let o=e[r];if(!k(o))continue;let i;for(let s of t)s in o&&(i||(i={...o}),delete i[s]);i&&(n||(n={...e}),n[r]=i)}return n??e}function k(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Y(e){if(!k(e))return;let t=e._meta;return k(t)?t:void 0}function be(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 Pn(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function Ce(e,t,n,r,o,i,s){let a=Pn(e,n.toolType),c=n.stripLocationFields,d=c&&c.length>0,l=Y(t),u=l&&d?kt(l,c):l,p=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,I=d&&k(i?.output)&&k(i.output._meta)?{...i.output,_meta:kt(i.output._meta,c)}:i?.output,S=(k(i?.output)&&k(i.output._meta)?i.output._meta:void 0)?.[L],m=S&&u?{...u,[L]:S}:S?{[L]:S}:u,R=k(i?.input)&&typeof i.input.sessionId=="string"&&i.input.sessionId.length>0?i.input.sessionId:void 0,y=R&&!F(m??void 0)?{...m??{},"waniwani/sessionId":R}:m;return{event:"tool.called",properties:{name:e,type:a,...r??{},...p!==void 0&&{input:p},...I!==void 0&&{output:I},...s&&s.length>0&&{kbSearch:s}},meta:y,source:W(y??u,o),metadata:{...n.metadata??{},...o&&{clientInfo:o},...n.funnelSync&&{funnelSync:n.funnelSync}}}}async function _e(e,t,n){try{await e.track(t)}catch(r){n?.(Pe(r))}}async function Fe(e,t){try{await e.flush()}catch(n){t?.(Pe(n))}}async function Et(e,t,n,r,o,i){if(!k(e))return;k(e._meta)||(e._meta={});let s=e._meta,a=k(s[Q])?s[Q]:void 0,c={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let p=await t.getToken();p&&(c.token=p)}catch(p){o?.(Pe(p))}let d=F(s);d&&(c.sessionId||(c.sessionId=d));let l=It(s);l!==void 0&&(c.geoLocation||(c.geoLocation=l));let u=W(Y(r),i);u&&!c.source&&(c.source=u),s[Q]=c}var vt=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function xt(e,t){if(!t||!k(e))return;let n=!1;for(let o of vt)if(o in t){n=!0;break}if(!n)return;k(e._meta)||(e._meta={});let r=e._meta;for(let o of vt)o in t&&(o in r||(r[o]=t[o]))}function Rt(e,t){let n=Y(t);if(!n||!k(e))return;k(e._meta)||(e._meta={});let r=e._meta,o=F(n);o&&!r[St]&&(r[St]=o);let i=It(n);i&&(r[ue]||(r[ue]=i),r[pe]||(r[pe]=i))}function It(e){if(!e)return;let t=e[ue]??e[pe];if(k(t)||typeof t=="string")return t}function Pe(e){return e instanceof Error?e:new Error(String(e))}function bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ct(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(bt(e.requestInfo)){let t=e.requestInfo.headers;if(bt(t)){let n={};for(let i of Object.keys(t))n[i.toLowerCase()]=t[i];let r=n["mcp-session-id"];if(typeof r=="string"&&r)return r;let o=n["x-waniwani-session-id"];if(typeof o=="string"&&o)return o}}}var Ft=Symbol.for("waniwani.wrappedHandler"),fe=B("mcp"),Pt="https://app.waniwani.ai",Nn="REDACTED";function An(e){if(!e)return;let t=e[oe];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]=Nn,i=!0);return i?{...r,stateUpdates:s}:r}}function _t(e,t,n,r){let{server:o,tracker:i,opts:s,tokenCache:a,injectToken:c}=n,d=s.applyFieldRedactions===!0?An(r):void 0,l=async(u,p)=>{let I=d?{...s,redactInput:d,funnelSync:n.funnelSync}:{...s,funnelSync:n.funnelSync},g=Y(p)??{},S=o.server?.getClientVersion?.();if(!F(g)&&k(p)){let f=Ct(p);f&&(g["waniwani/sessionId"]=f,p._meta=g)}if(!W(g)&&k(p)){let f=p.requestInfo?.headers,T=W(g,S)??Be(f);T&&(g["waniwani/source"]=T,p._meta=g)}let R=qe(i,g,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});k(p)&&(p[te]=R);let y={searches:[]},v=performance.now();try{let f=await Ee.run(y,()=>t(u,p)),T=Math.round(performance.now()-v);fe(`tool "${e}" handler returned in ${T}ms, running post-processing...`);let x=k(f)&&f.isError===!0;if(x){let b=be(f);console.error(`[waniwani] Tool "${e}" returned error${b?`: ${b}`:""}`)}return await _e(i,Ce(e,p,I,{durationMs:T,status:x?"error":"ok",...x&&{errorMessage:be(f)??"Unknown tool error"}},S,{input:u,output:f},y.searches),s.onError),fe(`tool "${e}" tracking done`),s.flushAfterToolCall&&await Fe(i,s.onError),Rt(f,p),xt(f,r),c&&(await Et(f,a,i._config.apiUrl??Pt,p,s.onError,S),fe(`tool "${e}" widget config injected`)),fe(`tool "${e}" post-processing complete, returning result`),f}catch(f){let T=Math.round(performance.now()-v);throw await _e(i,Ce(e,p,I,{durationMs:T,status:"error",errorMessage:f instanceof Error?f.message:String(f),cause:O({error:f})},S,{input:u},y.searches),s.onError),s.flushAfterToolCall&&await Fe(i,s.onError),f}};return l[Ft]=!0,l}async function Wn(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??ce(),i=r.injectWidgetToken!==!1,s=o._config.apiKey?new le({apiUrl:o._config.apiUrl??Pt,apiKey:o._config.apiKey}):null,a={server:e,tracker:o,opts:r,tokenCache:s,injectToken:i,funnelSync:null},c=e.registerTool.bind(e);n.registerTool=((...l)=>{let[u,p,I]=l;if(typeof I!="function")return c(...l);let g=typeof u=="string"&&u.trim().length>0?u:"unknown",S=k(p)&&k(p._meta)?p._meta:void 0,m=_t(g,I,a,S);return c(u,p,m)});let d=e._registeredTools;if(k(d))for(let[l,u]of Object.entries(d)){if(!k(u))continue;let p=u.handler;if(typeof p!="function"||p[Ft])continue;let I=k(u._meta)?u._meta:void 0;u.handler=_t(l,p,a,I)}if(o._config.apiKey){let l=e._registeredTools,u=[];if(l&&typeof l=="object"){for(let p of Object.values(l))if(p&&typeof p=="object"){let I=p._meta,g=I&&typeof I=="object"?I._flowGraph:void 0;g?.nodes?.length&&u.push(g)}}u.length>0&&(a.funnelSync=await Tt(u))}return n}export{N as END,re as MemoryKvStore,te as SCOPED_CLIENT_KEY,_ as START,$ as StateGraph,q as WaniwaniKvStore,at as createFlow,dt as createFlowTestHarness,Rn as createTrackingRoute,he as extractScopedClient,nt as redacted,Wn as withWaniwani};
|
|
3
|
+
${_.context}`:`ERROR: ${S}`}:_),P=ft(C,w.context,d,l,c);if(P)return{...P,nodesVisited:u};break}}let R=r.get(d);if(!R)return F({waniwani:s,code:"agent_failed",cause:"flow_dead_end",properties:{node:d}}),{content:{status:"error",error:`No outgoing edge from node "${d}"`},nodesVisited:u};d=await B(R,l);continue}if(Xe(w)){let y=w.field;if(y&&Ee(Z(l,y))){let T=r.get(d);if(!T)return F({waniwani:s,code:"agent_failed",cause:"flow_dead_end",properties:{node:d}}),{content:{status:"error",error:`No outgoing edge from node "${d}"`},nodesVisited:u};d=await B(T,l);continue}let R=y?Ie(c,y):void 0,f=w.interactive!==!1;return{content:{status:"widget",tool:w.tool,...w.data!==void 0?{data:w.data}:{},description:f?`IMPORTANT: You MUST now call the ${w.tool} tool to display the widget. Do NOT skip this step`:`IMPORTANT \u2014 two ordered steps. STEP 1: call the ${w.tool} tool RIGHT NOW to display this widget to the user. This renders UI the user must see \u2014 do NOT skip it and do NOT jump straight to action:"continue". STEP 2: ONLY AFTER ${w.tool} has been called, call this flow again with action:"continue".`,interactive:f,...y?{field:y}:{},...R?{fieldSchema:R}:{}},flowTokenContent:{step:d,state:l,field:y,widgetId:w.tool},nodesVisited:u}}l=j(l,w);let x=r.get(d);if(!x)return F({waniwani:s,code:"agent_failed",cause:"flow_dead_end",properties:{node:d}}),{content:{status:"error",error:`No outgoing edge from node "${d}"`},nodesVisited:u};d=await B(x,l)}catch(h){let w=h instanceof Error?h.message:String(h);return F({waniwani:s,code:"agent_failed",cause:K({error:h}),properties:{node:d}}),{content:{status:"error",error:w},flowTokenContent:{step:d,state:l},nodesVisited:u}}}return F({waniwani:s,code:"agent_failed",cause:"flow_loop",properties:{node:d}}),{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"},nodesVisited:u}}function Re(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var mt=new Map;async function wt(e){let t=mt.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 mt.set(e,r),r}async function ht(e,t){let n=await wt(t),r=globalThis.crypto.getRandomValues(new Uint8Array(12)),o=new TextEncoder().encode(JSON.stringify(e)),i=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:r},n,o);return{__ww_enc:1,ct:Buffer.from(i).toString("base64"),iv:Buffer.from(r).toString("base64")}}async function yt(e,t){let n=await wt(t),r=Buffer.from(e.ct,"base64"),o=Buffer.from(e.iv,"base64"),i;try{i=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:o},n,r)}catch{throw new Error("[Waniwani KV] Decryption failed. The encryption key may be incorrect or the data may be corrupted.")}return JSON.parse(new TextDecoder().decode(i))}var Hn={debug:0,warn:1,error:2,none:3};function zn(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in Hn?e:process.env.WANIWANI_DEBUG?"debug":"none"}function H(e,t){return t??zn()==="debug"?(...r)=>console.log(`[waniwani:${e}]`,...r):()=>{}}var Yn="@waniwani/sdk",Gn="https://app.waniwani.ai",Zn=H("kv"),z=class{get baseUrl(){return(process.env.WANIWANI_API_URL??Gn).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(Re(n)){if(!this.encryptionKey)throw new Error("[Waniwani KV] Encrypted data found but WANIWANI_ENCRYPTION_KEY is not set.");return yt(n,this.encryptionKey)}return n}async set(t,n,r){if(!this.apiKey)throw new Error("[Waniwani KV] No API key configured. Set WANIWANI_API_KEY env var.");let o=this.encryptionKey;Zn(`set "${t}" \u2014 encryption ${o?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let i=o?await ht(n,o):n;await this.request("/api/mcp/redis/set",{key:t,value:i,ttlSeconds:r?.ttlSeconds})}async delete(t){if(this.apiKey)try{await this.request("/api/mcp/redis/delete",{key:t})}catch(n){console.error("[Waniwani KV] delete failed for key:",t,n)}}async request(t,n){let r=`${this.baseUrl}${t}`,o=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","X-WaniWani-SDK":Yn},body:JSON.stringify(n)});if(!o.ok){let s=await o.text().catch(()=>"");throw new Error(s||`KV store API error: HTTP ${o.status}`)}return(await o.json()).data}};var de=class{map=new Map;async get(t){return this.map.get(t)??null}async set(t,n,r){this.map.set(t,n)}async delete(t){this.map.delete(t)}};var J=class{store=new z;get(t){return this.store.get(t)}set(t,n,r){return this.store.set(t,n,r)}delete(t){return this.store.delete(t)}};function Jn(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function Tt(e,t,n,r){let o=[];for(let[s,a]of t){let c=r.get(s);o.push({id:s,type:Jn(a),label:c?.label??s,...c?.hideFromFunnel?{hideFromFunnel:!0}:{}})}let i=[];for(let[s,a]of n)a.type==="direct"?i.push({from:s,to:a.to,type:"direct"}):i.push({from:s,to:a.targets,type:"conditional"});return{flowId:e.id,title:e.title,nodes:o,edges:i}}function St(e,t){if(e===void 0)return;if(typeof e=="string"){let o=e.trim();if(!o)throw new Error(`[waniwani] createFlow "${t}": \`intro\` is an empty string. Pass the text to deliver word for word, or drop the option.`);return{verbatim:o}}if(typeof e!="object"||e===null)throw new Error(`[waniwani] createFlow "${t}": \`intro\` must be a string (delivered verbatim) or an object with \`verbatim\` and/or \`instructions\`.`);let n=typeof e.verbatim=="string"?e.verbatim.trim():void 0,r=typeof e.instructions=="string"?e.instructions.trim():void 0;if(!n&&!r)throw new Error(`[waniwani] createFlow "${t}": \`intro\` needs \`verbatim\` (text delivered word for word), \`instructions\` (guidance the assistant writes from), or both.`);return{...n?{verbatim:n}:{},...r?{instructions:r}:{}}}var Xn={intro:e=>St(e.intro,e.id)};function kt(e){let t=Object.entries(Xn).map(([n,r])=>[n,r(e)]).filter(([,n])=>n!==void 0);return Object.fromEntries(t)}async function vt(e){let{store:t,sessionId:n,sessionIsPreexisting:r,seed:o}=e;if(Object.keys(o).length===0)return{};if(!n||!r)return o;try{let i=await t.get(n);return i?i.internal??{}:o}catch{return o}}function xt(e,t){let{[t]:n,...r}=e??{};return{value:n,internal:r}}function It(e,t){return Object.keys(t).length===0?e:{...e,internal:t}}import{z as k}from"zod";var Et=k.object({type:k.enum(["enum","string","number","boolean","object","array","unknown"]),values:k.array(k.string()).optional(),description:k.string().optional(),optional:k.boolean().optional()}).describe("JIT schema fragment for a state field \u2014 type, allowed values, and description."),Qn=k.object({verbatim:k.string().optional().describe("Text to reproduce word for word, before anything else in the reply."),instructions:k.string().optional().describe("How to write the introduction in your own words.")}).describe("Opening message for the session's first flow response. Delivered once per conversation."),er=k.object({question:k.string(),field:k.string(),suggestions:k.array(k.string()).optional(),context:k.string().optional(),fieldSchema:Et.optional()}).describe("One question within a multi-question interrupt."),be={intro:Qn.optional().describe("Present only on the session's first flow response. Deliver it at the very start of your next message, then never again."),status:k.enum(["interrupt","widget","complete","error"]).describe("Current flow status and the next action the assistant should take."),question:k.string().optional().describe("Single question to ask the user when status is interrupt."),field:k.string().optional().describe("State field to fill with the user's answer on the next continue call."),fieldSchema:Et.optional().describe("JIT schema fragment for the single-question shorthand."),suggestions:k.array(k.string()).optional().describe("Suggested answers for the single-question shorthand."),questions:k.array(er).optional().describe("Multiple questions to ask the user when status is interrupt."),context:k.string().optional().describe("Private instruction context for the assistant."),tool:k.string().optional().describe("Widget tool to call when status is widget."),data:k.record(k.string(),k.unknown()).optional().describe("Input data to pass to the widget tool."),description:k.string().optional().describe("Instruction for rendering the requested widget."),interactive:k.boolean().optional().describe("Whether the widget requires user interaction before continuing."),sessionId:k.string().optional().describe("Session identifier to pass on future continue and reset calls."),error:k.string().optional().describe("Error message when status is error.")};function Rt(e){let t=["","## FLOW EXECUTION PROTOCOL","","This tool implements a multi-step conversational flow. Follow this protocol exactly:","",'1. Call with `action: "start"` to begin and include `intent`.'," `intent` must be a brief summary of the user's goal for this flow."," Do NOT invent missing intent."," Optionally include `context` \u2014 the situation or environment that led the user to start"," this flow (e.g. what page they are on, what they were doing, or what triggered the request)."," Only provide `context` when there is genuinely relevant situational information. Do NOT invent missing context."," If the user's message already contains answers to likely questions,"," extract them into `stateUpdates` as `{ field: value }` pairs (see the `stateUpdates` schema"," for the list of writable fields). The engine will auto-skip steps whose fields are already filled."," Only extract values the user explicitly stated \u2014 do NOT guess or invent values."];return e.omitIntentPII&&t.push(" Do NOT include PII in `intent` or `context` \u2014 no names, emails, phones, addresses, IDs, ages, or birthdates.",' Summarize the goal abstractly (e.g. "user wants a quote", not "Jane Doe wants a quote").'),t.push(" For grouped fields (z.object state), use dot-notation keys in `stateUpdates`:",' e.g. `{ "driver.name": "John", "driver.license": "ABC123" }`.',"2. The response JSON `status` field tells you what to do next:",' - `"interrupt"`: Pause and ask the user. Two forms:'," a. Single question: `{ question, field, fieldSchema?, context? }` \u2014 ask `question`, store answer in `field`."," b. Multi-question: `{ questions: [{question, field, fieldSchema?}, ...], context? }` \u2014 ask ALL questions"," in one conversational message, collect all answers."," `fieldSchema` (when present) describes the expected value: `{ type, values?, description?, optional? }`.",' Use it to validate before sending \u2014 match enum `values` exactly, coerce strings to numbers where `type: "number"`.'," `context` (if present) is hidden AI instructions \u2014 use to shape your response, do NOT show verbatim."," Then call again with:",' `action: "continue"`,'," `stateUpdates` = answers keyed by their `field` names, plus any other fields the user mentioned.",' - `"widget"`: The flow wants to show a UI widget. Call the tool named in the `tool`'," field, passing the `data` object as the tool's input."," Check the `interactive` field in the response:"," \u2022 `interactive: true` \u2014 The widget requires user interaction. After calling the display tool,"," STOP and WAIT for the user to interact with the widget. Do NOT call this flow tool again"," until the user has responded. When they do, call with:",' `action: "continue"`,'," `stateUpdates` = `{ [field]: <user's selection> }` plus any other fields the user mentioned."," \u2022 `interactive: false` \u2014 The widget is display-only. You MUST STILL call the display tool"," FIRST to render it for the user \u2014 this is a required, user-visible step. Do NOT skip it",' and do NOT jump straight to `action: "continue"`. ONLY AFTER you have called the display',' tool, call THIS flow tool again with `action: "continue"`. Do NOT wait for user interaction.',' - `"complete"`: The flow is done. Present the result to the user.',' - `"error"`: Something went wrong. Show the `error` message.',"","3. Do NOT invent state values. Only use `stateUpdates` for information the user explicitly provided.","4. Include only the fields the user actually answered in `stateUpdates` \u2014 do NOT guess missing ones."," If the user did not answer all pending questions, the engine will re-prompt for the remaining ones."," If the user mentioned values for other known fields, include those too \u2014"," they will be applied immediately and those steps will be auto-skipped.","5. CORRECTION: If the user wants to CHANGE a previously-answered field",' (e.g. "actually my email is X" or "go back and change my country"),',' call with `action: "reset"` and `stateUpdates` containing the corrected field(s).'," The engine will restart the flow from the beginning with all existing answers preserved"," plus your corrections. Steps with filled answers will be auto-skipped."," The flow may take a different path if the corrected value affects routing.",' Do NOT use "reset" for the CURRENT question \u2014 use "continue" for that.',"6. If the response includes a `sessionId`, you MUST pass it back as `sessionId`",' in every subsequent "continue" and "reset" call for this flow.'),e.intro&&t.push("7. OPENING MESSAGE: if the response contains an `intro` object, deliver it at the very"," start of your next message to the user \u2014 before the question, before calling a widget"," tool, before presenting the result."," - `intro.verbatim` (when present) MUST be reproduced word for word, exactly as written."," Do NOT paraphrase, translate, shorten, expand, reformat, or fold it into another sentence."," - `intro.instructions` (when present) tells you how to write the introduction in your own words."," - When both are present, follow `instructions` for the prose around the notice and leave the"," `verbatim` text untouched."," `intro` appears at most once per conversation. Later responses omit it, and you must not"," repeat it or reuse it from earlier in the conversation."),t.join(`
|
|
4
|
+
`)}function Ce(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function bt(e){let t=Ct(e),n=Ce(t.waniwani)?t.waniwani:{};return e.meta({...t,waniwani:{...n,redacted:!0}})}function tr(e){let n=Ct(e).waniwani;return Ce(n)&&n.redacted===!0}function Ct(e){let t=e.meta;if(typeof t!="function")return{};let n=t.call(e);return Ce(n)?n:{}}function _t(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))tr(r)&&t.push(n);return t}var le="waniwani/redactedStateUpdateFields";function nr(e){let t=e.omitIntentPII?" Do not include PII (names, emails, phones, addresses, IDs, ages, birthdates) \u2014 summarize abstractly.":"",r=e.state&&Object.keys(e.state).length>0?L.object(e.state).partial().passthrough():L.record(L.string(),L.unknown());return{action:L.enum(["start","continue","reset"]).describe('"start" to begin the flow, "continue" to resume after a pause (interrupt or widget), "reset" to restart from the beginning with a correction to a previously-collected field'),intent:L.string().optional().describe(`Required when action is "start". Provide a brief summary of the user's goal for this flow. Do not invent missing intent.${t}`),context:L.string().optional().describe(`Optional when action is "start". Describe the situation or environment that led the user to start this flow \u2014 e.g. what page they are on, what they were doing, or what triggered the request. Do not invent missing context.${t}`),stateUpdates:r.optional().describe(`State field values to set before processing the next node. Pass the user's answer (keyed by the field name from the response) and any other values the user mentioned. For nested state fields, use dot-paths like "driver.name".`),sessionId:L.string().optional().describe('Session identifier. If the response includes a `sessionId`, pass it back on every subsequent "continue" and "reset" call for this flow.')}}function rr(e){if(process.env.WANIWANI_API_KEY)return new J;throw new Error(`[waniwani] createFlow "${e}": no flow store configured. Pass { store } to .compile() \u2014 use MemoryKvStore from "@waniwani/sdk/mcp" for local development, or plug in a Redis/Upstash/Cloudflare KV adapter for production. Alternatively, set WANIWANI_API_KEY to use hosted flow state on app.waniwani.ai.`)}function Ft(e){let{config:t,nodes:n,edges:r}=e,o=nr(t),i=Tt(t,n,r,e.nodeOptions),s=Rt(t),a=`${t.description}
|
|
5
|
+
${s}`,c=e.store??rr(t.id),d=kt(t),l=new Map;async function u(h,w,x,y,R){let f=(T,b,S)=>gt(T,b,n,r,l,y,R,e.nodeOptions,t.state).then(C=>({...C,internal:S}));if(h.action==="start"){let T=typeof h.intent=="string"?h.intent.trim():void 0;if(h.intent=T||void 0,typeof h.context=="string"){let _=h.context.trim();h.context=_||void 0}let b=r.get(A);if(!b)return F({waniwani:R,code:"agent_failed",cause:"flow_dead_end",properties:{node:A}}),{content:{status:"error",error:"No start edge"}};let S=await vt({store:c,sessionId:w,sessionIsPreexisting:x,seed:d}),C=ce(h.stateUpdates??{}),P=await B(b,C);return f(P,C,S)}if(h.action==="continue"){if(!w)return{content:{status:"error",error:"No session ID available for continue action."}};let T;try{T=await c.get(w)}catch(_){let N=_ instanceof Error?_.message:String(_);return F({waniwani:R,code:"upstream_failed",cause:K({error:_})}),{content:{status:"error",error:`Failed to load flow state (session "${w}"): ${N}`}}}if(!T)return{content:{status:"error",error:`Flow state not found for session "${w}". The flow may have expired.`}};let b=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 C=j(b,ce(h.stateUpdates??{})),P=T.internal??{};if(T.widgetId){let _=r.get(S);if(!_)return F({waniwani:R,code:"agent_failed",cause:"flow_dead_end",properties:{node:S}}),{content:{status:"error",error:`No edge from step "${S}"`}};let N=await B(_,C);return f(N,C,P)}return f(S,C,P)}if(h.action==="reset"){if(!w)return{content:{status:"error",error:"No session ID available for reset action."}};let T;try{T=await c.get(w)}catch(N){let Te=N instanceof Error?N.message:String(N);return F({waniwani:R,code:"upstream_failed",cause:K({error:N})}),{content:{status:"error",error:`Failed to load flow state (session "${w}"): ${Te}`}}}if(!T)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(!T.step)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};if(!h.stateUpdates||Object.keys(h.stateUpdates).length===0)return{content:{status:"error",error:'Missing "stateUpdates" for action "reset". Include the corrected field(s).'}};let b=r.get(A);if(!b)return F({waniwani:R,code:"agent_failed",cause:"flow_dead_end",properties:{node:A}}),{content:{status:"error",error:"No start edge"}};let S=T.state,C=j(S,ce(h.stateUpdates)),P=T.internal??{},_=await B(b,C);return f(_,C,P)}return{content:{status:"error",error:`Unknown action: "${h.action}"`}}}let p=_t(t.state),I={title:t.title,description:a,inputSchema:o,outputSchema:be,annotations:t.annotations,...p.length>0&&{_meta:{[le]:p}}},E=(async(h,w)=>{let x=w,y=x._meta??{},R=W(y),f=R??h.sessionId,T=!!f;!f&&h.action==="start"&&(f=crypto.randomUUID()),f&&!R&&(y["waniwani/sessionId"]=f);let b=ve(x),S=await u(h,f,T,y,b),C=!R&&f?{...S.content,sessionId:f}:S.content,{value:P,internal:_}=C.status==="error"?{value:void 0,internal:S.internal??{}}:xt(S.internal,"intro"),N=P?{intro:P,...C}:C;if(y[ke]={suggestions:C.status==="interrupt"?C.suggestions??[]:[]},f&&S.flowTokenContent){let rn=It(S.flowTokenContent,_);try{await c.set(f,rn)}catch(Q){let on=Q instanceof Error?Q.message:String(Q);return F({waniwani:b,code:"upstream_failed",cause:K({error:Q}),properties:{node:S.flowTokenContent.step}}),{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${f}"): ${on}`},null,2)}],_meta:y,isError:!0}}}let Te=[{type:"text",text:JSON.stringify(N,null,2)}];return S.nodesVisited?.length&&(y[V]={flowId:t.id,nodesVisited:S.nodesVisited}),{content:Te,structuredContent:N,_meta:y,...S.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:I,handler:E,async register(h){let w={...I,_meta:{...I._meta,_flowGraph:i}};h.registerTool(t.id,w,E)},graph:e.graph,flowGraph:i}}function At(e,t){let n=["flowchart TD"];n.push(` ${A}((Start))`);for(let[r]of e)n.push(` ${r}[${r}]`);n.push(` ${O}((End))`);for(let[r,o]of t)if(o.type==="direct")n.push(` ${r} --> ${o.to}`);else for(let i of o.targets)n.push(` ${r} -.-> ${i}`);return n.join(`
|
|
6
|
+
`)}var Y=class{nodes=new Map;edges=new Map;nodeOptions=new Map;config;constructor(t){this.config=t}addNode(t,n,r){let o=typeof t=="string"?t:t.id,i=typeof t=="string"?n:t.run,s=typeof t=="string"?r?.label:t.label,a=typeof t=="string"?r?.hideFromFunnel:t.hideFromFunnel;if(o===A||o===O)throw new Error(`"${o}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(o))throw new Error(`Node "${o}" already exists`);return this.nodes.set(o,i),(s!==void 0||a!==void 0)&&this.nodeOptions.set(o,{label:s??o,hideFromFunnel:a}),this}addEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge. Use addConditionalEdge for branching.`);return this.edges.set(t,{type:"direct",to:n}),this}addConditionalEdge(t,n,r){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge.`);if(n.length===0)throw new Error(`Conditional edge from "${t}" must declare at least one target node in \`to\`.`);return this.edges.set(t,{type:"conditional",condition:r,targets:[...n]}),this}graph(){return At(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return Ft({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>At(n,r),nodeOptions:new Map(this.nodeOptions)})}validate(){if(!this.edges.has(A))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(A);if(t?.type==="direct"&&t.to!==O&&!this.nodes.has(t.to))throw new Error(`START edge references non-existent node: "${t.to}"`);for(let[n,r]of this.edges){if(n!==A&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(r.type==="direct"&&r.to!==O&&!this.nodes.has(r.to))throw new Error(`Edge from "${n}" references non-existent node: "${r.to}"`);if(r.type==="conditional"&&r.targets){for(let o of r.targets)if(o!==O&&!this.nodes.has(o))throw new Error(`Conditional edge from "${n}" declares non-existent target: "${o}"`)}}for(let[n]of this.nodes)if(!this.edges.has(n))throw new Error(`Node "${n}" has no outgoing edge. Add one with .addEdge("${n}", ...) or .addConditionalEdge("${n}", ...)`)}};function Pt(e){return new Y(e)}function _e(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function Wt(e,t){let n=t?.stateStore,r=[],o=`test-session-${Math.random().toString(36).slice(2,10)}`,i={registerTool:(...d)=>{r.push(d)}};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 c(d){return{...d,decodedState:n?await n.get(o):null}}return{async start(d,l,u){let p=await s({action:"start",intent:d,...u?{context:u}:{},...l?{stateUpdates:l}:{}},a);return c(_e(p))},async continueWith(d){let l=await s({action:"continue",...d?{stateUpdates:d}:{}},a);return c(_e(l))},async resetWith(d){let l=await s({action:"reset",stateUpdates:d},a);return c(_e(l))},async lastState(){return n?n.get(o):null}}}import{AsyncLocalStorage as or}from"async_hooks";var Nt=globalThis,ue=Nt.__waniwaniKbRetrievalStore;ue||(ue=new or,Nt.__waniwaniKbRetrievalStore=ue);var Fe=ue;function Mt(e){try{Fe.getStore()?.searches.push(e)}catch{}}var ir="@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 c=r(),d=`${t.replace(/\/$/,"")}${s}`,l={Authorization:`Bearer ${c}`,"X-WaniWani-SDK":ir},u={method:i,headers:l};a!==void 0&&(l["Content-Type"]="application/json",u.body=JSON.stringify(a));let p=await fetch(d,u);if(!p.ok){let E=await p.text().catch(()=>"");throw new $(E||`KB API error: HTTP ${p.status}`,p.status)}return(await p.json()).data}return{async ingest(i){return o("POST","/api/mcp/kb/ingest",{files:i})},async search(i,s){let a=await o("POST","/api/mcp/kb/search",{query:i,...s});return Mt({query:i,resultCount:a.length,results:a.map(c=>({source:c.source,heading:c.heading,score:c.score}))}),a},async sources(){return o("GET","/api/mcp/kb/sources")}}}import{existsSync as sr,readFileSync as ar}from"fs";import{resolve as cr}from"path";var dr="waniwani.json",G;function Ut(){if(G!==void 0)return G;try{let e=cr(process.cwd(),dr);if(!sr(e))return G=null,null;let t=ar(e,"utf-8");return G=JSON.parse(t),G}catch{return G=null,null}}var lr="__waniwani_config__";function Dt(){return globalThis[lr]}var ur="@waniwani/sdk";function fe(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??Kt,o=gr(e),i=pe(e.meta),s=pe(e.metadata),a=mr(e,i),c=M(e.eventId)??r(),d=wr(e.timestamp,n),l=M(e.source)??D(i)??t.source??ur,u=Ae(e)?{...e}:void 0,p={...s};return Object.keys(i).length>0&&(p.meta=i),u&&(p.rawLegacy=u),{id:c,type:"mcp.event",name:o,source:l,timestamp:d,correlation:a,properties:pr(e,o),metadata:p,rawLegacy:u}}function Kt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function pr(e,t){if(!Ae(e))return pe(e.properties);let n=fr(e,t),r=pe(e.properties);return{...n,...r}}function fr(e,t){switch(t){case"tool.called":{let n={};return M(e.toolName)&&(n.name=e.toolName),M(e.toolType)&&(n.type=e.toolType),n}case"link.clicked":{let n={};return M(e.linkUrl)&&(n.url=e.linkUrl),n}default:return{}}}function gr(e){return Ae(e)?e.eventType:e.event}function mr(e,t){let n=M(e.requestId)??nt(t),r=M(e.sessionId)??W(t),o=M(e.traceId)??rt(t),i=M(e.externalUserId)??oe(t),s=M(e.visitorId)??ie(t),a=M(e.correlationId)??se(t)??n,c={};return r&&(c.sessionId=r),o&&(c.traceId=o),n&&(c.requestId=n),a&&(c.correlationId=a),i&&(c.externalUserId=i),s&&(c.visitorId=s),c}function wr(e,t){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){let n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return t().toISOString()}function pe(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function M(e){if(typeof e=="string"&&e.trim().length!==0)return e}function Ae(e){return"eventType"in e}var hr="/api/mcp/events/v2/batch";var jt="@waniwani/sdk";var yr=new Set([401,403]),Tr=new Set([408,425,429,500,502,503,504]),Sr=(e,t)=>globalThis.fetch(e,t);function Lt(e){return new Pe(e)}var Pe=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=xr(t.apiUrl,t.endpointPath??hr),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??Sr,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(r=>setTimeout(r,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs)),this.registerBrowserTeardown()}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[Waniwani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[Waniwani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,r=this.flush();if(!Number.isFinite(n)||n<=0)return await r,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let o=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(n).then(()=>o)])===o?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}registerBrowserTeardown(){if(typeof document>"u"||typeof window>"u")return;let t=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush()};document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",()=>this.keepaliveFlush())}keepaliveFlush(){if(this.isStopped||this.buffer.length===0)return;let t=this.buffer.splice(0,this.buffer.length);this.sendKeepaliveChunk(t)}sendKeepaliveChunk(t){let n=JSON.stringify(this.makeBatchRequest(t));if(n.length>6e4&&t.length>1){let r=Math.ceil(t.length/2);this.sendKeepaliveChunk(t.slice(0,r)),this.sendKeepaliveChunk(t.slice(r));return}try{this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:n,keepalive:!0}).catch(()=>{})}catch{}}requestHeaders(){let t={"Content-Type":"application/json","X-WaniWani-SDK":jt};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,r=t;for(;r.length>0&&!this.isStopped;){this.inFlightCount=r.length;let o=await this.sendBatchOnce(r);switch(this.inFlightCount=0,o.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(o.status,r.length);return;case"permanent":this.logger.error("[Waniwani] Dropping %d event(s) after permanent failure: %s",r.length,o.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d event(s) after retry exhaustion: %s",r.length,o.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(o.permanent.length>0&&this.logger.error("[Waniwani] Dropping %d event(s) rejected as permanent",o.permanent.length),o.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d retryable event(s) after retry exhaustion",o.retryable.length);return}r=o.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:Ir(i)}}if(yr.has(n.status))return{kind:"auth",status:n.status};if(Tr.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await vr(n);if(!r?.rejected||r.rejected.length===0)return{kind:"success"};let o=this.classifyRejectedEvents(t,r.rejected);return o.retryable.length===0&&o.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:o.retryable,permanent:o.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:jt,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(s=>[s.id,s])),o=[],i=[];for(let s of n){let a=r.get(s.eventId);if(a){if(kr(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 kr(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 vr(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function xr(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function Ir(e){return e instanceof Error?e.message:String(e)}function Bt(e){let{apiUrl:t,apiKey:n,tracking:r}=e;function o(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}let i=n?Lt({apiUrl:t,apiKey:n,endpointPath:r.endpointPath,flushIntervalMs:r.flushIntervalMs,maxBatchSize:r.maxBatchSize,maxBufferSize:r.maxBufferSize,maxRetries:r.maxRetries,retryBaseDelayMs:r.retryBaseDelayMs,retryMaxDelayMs:r.retryMaxDelayMs,shutdownTimeoutMs:r.shutdownTimeoutMs}):void 0;function s(l){o();let u=fe(l);return!u.correlation.sessionId&&!u.correlation.externalUserId&&!u.correlation.visitorId&&console.warn(`[waniwani] event "${u.name}" has no sessionId, externalUserId, or visitorId; the ingest API requires one and will reject it.`),i?.enqueue(u),{eventId:u.id}}let a=async l=>s(l),c=Object.assign(a,te(a)),d={async identify(l,u,p){o();let I=fe({event:"user.identified",externalUserId:l,properties:u,meta:p});return i?.enqueue(I),{eventId:I.id}},track:c,async flush(){o(),await i?.flush()},async shutdown(l){return o(),await i?.shutdown({timeoutMs:l?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&Er(d,r.shutdownTimeoutMs),d}function Er(e,t){if(typeof process>"u"||typeof process.once!="function"||typeof process.on!="function")return;let n=()=>{e.shutdown({timeoutMs:t})};process.once("beforeExit",n),process.once("SIGINT",n),process.once("SIGTERM",n)}function ge(e){let n=e??Ut()??Dt(),r=n?.apiUrl??process.env.WANIWANI_API_URL??ne,o=n?.apiKey??process.env.WANIWANI_API_KEY,i={endpointPath:n?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:n?.tracking?.flushIntervalMs??1e3,maxBatchSize:n?.tracking?.maxBatchSize??20,maxBufferSize:n?.tracking?.maxBufferSize??1e3,maxRetries:n?.tracking?.maxRetries??3,retryBaseDelayMs:n?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:n?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:n?.tracking?.shutdownTimeoutMs??2e3},s={apiUrl:r,apiKey:o,tracking:i},a=Bt(s),c=Ot(s),d=ee(s);return{...a,kb:c,documents:d,_config:s}}function Rr(e){return{event:e.name??"widget_render",properties:e.properties,metadata:e.metadata,sessionId:e.correlation?.sessionId,traceId:e.correlation?.traceId,requestId:e.correlation?.requestId,correlationId:e.correlation?.correlationId,externalUserId:e.correlation?.externalUserId,visitorId:e.correlation?.visitorId,eventId:e.id,timestamp:e.timestamp,source:e.source}}function br(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=ge(t)),n}return async function(i){let s;try{s=await i.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!Array.isArray(s.events)||s.events.length===0)return new Response(JSON.stringify({error:"Missing or empty events array"}),{status:400,headers:{"Content-Type":"application/json"}});try{let a=r(),c=[];for(let d of s.events){let l=await a.track(Rr(d));c.push(l.eventId)}return await a.flush(),new Response(JSON.stringify({ok:!0,accepted:c.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(a){let c=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({error:c}),{status:500,headers:{"Content-Type":"application/json"}})}}}var We=H("widget-token"),Cr=120*1e3,me=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-Cr?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=_r(this.config.apiUrl,"/api/mcp/widget-tokens");We("minting token from",r);let o={};t&&(o.sessionId=t),n&&(o.traceId=n);try{let i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)});if(We("mint response:",i.status),!i.ok)return null;let s=await i.json(),a=s.data&&typeof s.data=="object"?s.data:s,c=new Date(a.expiresAt).getTime();return!a.token||Number.isNaN(c)?null:(this.cached={token:a.token,expiresAt:c},a.token)}catch(i){return We("mint failed:",i),null}}};function _r(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function $t(e){if(typeof globalThis.crypto?.subtle?.digest=="function"){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return`simple-${Math.abs(t).toString(36)}`}function Fr(e){return $t(JSON.stringify({nodes:e.nodes,edges:e.edges}))}async function qt(e){if(e.length===0)return null;let t=[...e].sort((o,i)=>o.flowId.localeCompare(i.flowId)),n=await $t(JSON.stringify(t.map(o=>({flowId:o.flowId,nodes:o.nodes,edges:o.edges})))),r=await Promise.all(e.map(async o=>({flowId:o.flowId,title:o.title,configHash:await Fr(o),nodes:o.nodes,edges:o.edges})));return{compositeHash:n,flows:r}}var Vt="waniwani/sessionId",we="waniwani/geoLocation",he="waniwani/userLocation",Ar="openai/userLocation",Pr=[Ar,we,he];function Ht(e,t){if(t.length===0)return e;let n;for(let r of Pr){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 X(e){if(!v(e))return;let t=e._meta;return v(t)?t:void 0}function Ne(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 Wr(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function Me(e,t,n,r,o,i,s){let a=Wr(e,n.toolType),c=n.stripLocationFields,d=c&&c.length>0,l=X(t),u=l&&d?Ht(l,c):l,p=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,I=d&&v(i?.output)&&v(i.output._meta)?{...i.output,_meta:Ht(i.output._meta,c)}:i?.output,h=(v(i?.output)&&v(i.output._meta)?i.output._meta:void 0)?.[V],w=h&&u?{...u,[V]:h}:h?{[V]:h}:u,x=v(i?.input)&&typeof i.input.sessionId=="string"&&i.input.sessionId.length>0?i.input.sessionId:void 0,y=x&&!W(w??void 0)?{...w??{},"waniwani/sessionId":x}:w;return{event:"tool.called",properties:{name:e,type:a,...r??{},...p!==void 0&&{input:p},...I!==void 0&&{output:I},...s&&s.length>0&&{kbSearch:s}},meta:y,source:D(y??u,o),metadata:{...n.metadata??{},...o&&{clientInfo:o},...n.funnelSync&&{funnelSync:n.funnelSync}}}}async function Oe(e,t,n){try{await e.track(t)}catch(r){n?.(De(r))}}async function Ue(e,t){try{await e.flush()}catch(n){t?.(De(n))}}async function Yt(e,t,n,r,o,i){if(!v(e))return;v(e._meta)||(e._meta={});let s=e._meta,a=v(s[re])?s[re]:void 0,c={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let p=await t.getToken();p&&(c.token=p)}catch(p){o?.(De(p))}let d=W(s);d&&(c.sessionId||(c.sessionId=d));let l=Jt(s);l!==void 0&&(c.geoLocation||(c.geoLocation=l));let u=D(X(r),i);u&&!c.source&&(c.source=u),s[re]=c}var zt=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function Gt(e,t){if(!t||!v(e))return;let n=!1;for(let o of zt)if(o in t){n=!0;break}if(!n)return;v(e._meta)||(e._meta={});let r=e._meta;for(let o of zt)o in t&&(o in r||(r[o]=t[o]))}function Zt(e,t){let n=X(t);if(!n||!v(e))return;v(e._meta)||(e._meta={});let r=e._meta,o=W(n);o&&!r[Vt]&&(r[Vt]=o);let i=Jt(n);i&&(r[we]||(r[we]=i),r[he]||(r[he]=i))}function Jt(e){if(!e)return;let t=e[we]??e[he];if(v(t)||typeof t=="string")return t}function De(e){return e instanceof Error?e:new Error(String(e))}function Xt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qt(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(Xt(e.requestInfo)){let t=e.requestInfo.headers;if(Xt(t)){let n={};for(let i of Object.keys(t))n[i.toLowerCase()]=t[i];let r=n["mcp-session-id"];if(typeof r=="string"&&r)return r;let o=n["x-waniwani-session-id"];if(typeof o=="string"&&o)return o}}}var tn=Symbol.for("waniwani.wrappedHandler"),ye=H("mcp"),nn="https://app.waniwani.ai",Nr="REDACTED";function Mr(e){if(!e)return;let t=e[le];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]=Nr,i=!0);return i?{...r,stateUpdates:s}:r}}function en(e,t,n,r){let{server:o,tracker:i,opts:s,tokenCache:a,injectToken:c}=n,d=s.applyFieldRedactions===!0?Mr(r):void 0,l=async(u,p)=>{let I=d?{...s,redactInput:d,funnelSync:n.funnelSync}:{...s,funnelSync:n.funnelSync},E=X(p)??{},h=o.server?.getClientVersion?.();if(!W(E)&&v(p)){let f=Qt(p);f&&(E["waniwani/sessionId"]=f,p._meta=E)}if(!D(E)&&v(p)){let f=p.requestInfo?.headers,T=D(E,h)??at(f);T&&(E["waniwani/source"]=T,p._meta=E)}let x=ct(i,E,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});v(p)&&(p[ae]=x);let y={searches:[]},R=performance.now();try{let f=await Fe.run(y,()=>t(u,p)),T=Math.round(performance.now()-R);ye(`tool "${e}" handler returned in ${T}ms, running post-processing...`);let b=v(f)&&f.isError===!0;if(b){let S=Ne(f);console.error(`[waniwani] Tool "${e}" returned error${S?`: ${S}`:""}`)}return await Oe(i,Me(e,p,I,{durationMs:T,status:b?"error":"ok",...b&&{errorMessage:Ne(f)??"Unknown tool error"}},h,{input:u,output:f},y.searches),s.onError),ye(`tool "${e}" tracking done`),s.flushAfterToolCall&&await Ue(i,s.onError),Zt(f,p),Gt(f,r),c&&(await Yt(f,a,i._config.apiUrl??nn,p,s.onError,h),ye(`tool "${e}" widget config injected`)),ye(`tool "${e}" post-processing complete, returning result`),f}catch(f){let T=Math.round(performance.now()-R);throw await Oe(i,Me(e,p,I,{durationMs:T,status:"error",errorMessage:f instanceof Error?f.message:String(f),cause:K({error:f})},h,{input:u},y.searches),s.onError),s.flushAfterToolCall&&await Ue(i,s.onError),f}};return l[tn]=!0,l}async function Or(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??ge(),i=r.injectWidgetToken!==!1,s=o._config.apiKey?new me({apiUrl:o._config.apiUrl??nn,apiKey:o._config.apiKey}):null,a={server:e,tracker:o,opts:r,tokenCache:s,injectToken:i,funnelSync:null},c=e.registerTool.bind(e);n.registerTool=((...l)=>{let[u,p,I]=l;if(typeof I!="function")return c(...l);let E=typeof u=="string"&&u.trim().length>0?u:"unknown",h=v(p)&&v(p._meta)?p._meta:void 0,w=en(E,I,a,h);return c(u,p,w)});let d=e._registeredTools;if(v(d))for(let[l,u]of Object.entries(d)){if(!v(u))continue;let p=u.handler;if(typeof p!="function"||p[tn])continue;let I=v(u._meta)?u._meta:void 0;u.handler=en(l,p,a,I)}if(o._config.apiKey){let l=e._registeredTools,u=[];if(l&&typeof l=="object"){for(let p of Object.values(l))if(p&&typeof p=="object"){let I=p._meta,E=I&&typeof I=="object"?I._flowGraph:void 0;E?.nodes?.length&&u.push(E)}}u.length>0&&(a.funnelSync=await qt(u))}return n}export{O as END,de as MemoryKvStore,ae as SCOPED_CLIENT_KEY,A as START,Y as StateGraph,z as WaniwaniKvStore,an as autoHeightFromMeta,Pt as createFlow,Wt as createFlowTestHarness,br as createTrackingRoute,qe as createWebMcpBridge,ve as extractScopedClient,cn as isDisplayTool,Ve as readWidgetStep,bt as redacted,je as resourceUriFromMeta,He as rewriteForAgent,$e as supportsWebMcp,Le as viewUriFor,Or as withWaniwani};
|
|
7
7
|
//# sourceMappingURL=index.js.map
|