@waniwani/sdk 0.4.3-beta.2 → 0.4.3-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat/index.js +1 -1
- package/dist/chat/next-js/index.js +3 -3
- package/dist/chat/next-js/index.js.map +1 -1
- package/dist/{chunk-5JBHQYU5.js → chunk-HVAT4SNH.js} +2 -2
- package/dist/chunk-HVAT4SNH.js.map +1 -0
- package/dist/{code-block-37QAKDTI-IIYKFI5S.js → code-block-37QAKDTI-M2QCKVTI.js} +2 -2
- package/dist/mcp/index.d.ts +1 -0
- package/dist/mcp/index.js +4 -4
- package/dist/mcp/index.js.map +1 -1
- package/dist/mermaid-4DMBBIKO-NR6M3PLG.js +3 -0
- package/package.json +1 -1
- package/dist/chunk-5JBHQYU5.js.map +0 -1
- package/dist/mermaid-4DMBBIKO-PAA57QRQ.js +0 -3
- /package/dist/{code-block-37QAKDTI-IIYKFI5S.js.map → code-block-37QAKDTI-M2QCKVTI.js.map} +0 -0
- /package/dist/{mermaid-4DMBBIKO-PAA57QRQ.js.map → mermaid-4DMBBIKO-NR6M3PLG.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use client";import{q as g,r as u,s as b,t as h}from"./chunk-
|
|
2
|
+
"use client";import{q as g,r as u,s as b,t as h}from"./chunk-HVAT4SNH.js";import"./chunk-V3ZDECK5.js";import{memo as x,useMemo as f,useContext as N,useState as v,useEffect as y}from"react";import{jsx as r,jsxs as k}from"react/jsx-runtime";var w=g("block","before:content-[counter(line)]","before:inline-block","before:[counter-increment:line]","before:w-6","before:mr-4","before:text-[13px]","before:text-right","before:text-muted-foreground/50","before:font-mono","before:select-none"),C=x(({children:a,result:e,language:o,className:s,...m})=>{let i=f(()=>({backgroundColor:e.bg,color:e.fg}),[e.bg,e.fg]);return r("pre",{className:g(s,"p-4 text-sm dark:bg-(--shiki-dark-bg)!"),"data-language":o,"data-streamdown":"code-block-body",style:i,...m,children:r("code",{className:"[counter-increment:line_0] [counter-reset:line]",children:e.tokens.map((c,l)=>r("span",{className:w,children:c.map((t,n)=>r("span",{className:"dark:bg-(--shiki-dark-bg)! dark:text-(--shiki-dark)!",style:{color:t.color,backgroundColor:t.bgColor,...t.htmlStyle},...t.htmlAttrs,children:t.content},n))},l))})})},(a,e)=>a.result===e.result&&a.language===e.language&&a.className===e.className),S=({className:a,language:e,style:o,...s})=>r("div",{className:g("my-4 w-full overflow-hidden rounded-xl border border-border",a),"data-language":e,"data-streamdown":"code-block",style:{contentVisibility:"auto",containIntrinsicSize:"auto 200px",...o},...s}),j=({language:a,children:e})=>k("div",{className:"flex items-center justify-between bg-muted/80 p-3 text-muted-foreground text-xs","data-language":a,"data-streamdown":"code-block-header",children:[r("span",{className:"ml-1 font-mono lowercase",children:a}),r("div",{className:"flex items-center gap-2",children:e})]}),E=({code:a,language:e,className:o,children:s,...m})=>{let{shikiTheme:i}=N(h),c=b(),l=f(()=>({bg:"transparent",fg:"inherit",tokens:a.split(`
|
|
3
3
|
`).map(d=>[{content:d,color:"inherit",bgColor:"transparent",htmlStyle:{},offset:0}])}),[a]),[t,n]=v(l);return y(()=>{if(!c){n(l);return}let d=c.highlight({code:a,language:e,themes:i},p=>{n(p)});if(d){n(d);return}n(l)},[a,e,i,c,l]),r(u.Provider,{value:{code:a},children:k(S,{language:e,children:[r(j,{language:e,children:s}),r(C,{className:o,language:e,result:t,...m})]})})};export{E as CodeBlock};
|
|
4
|
-
//# sourceMappingURL=code-block-37QAKDTI-
|
|
4
|
+
//# sourceMappingURL=code-block-37QAKDTI-M2QCKVTI.js.map
|
package/dist/mcp/index.d.ts
CHANGED
package/dist/mcp/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
function
|
|
1
|
+
function q(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function Ee(){return q()==="openai"}function Ie(){return q()==="mcp-apps"}var R="__start__",I="__end__",Q=Symbol.for("waniwani.flow.interrupt"),ee=Symbol.for("waniwani.flow.widget");function te(e,t){let n=t?.context,r=[];for(let[o,a]of Object.entries(e))if(typeof a=="object"&&a!==null&&"question"in a){let i=a;r.push({question:i.question,field:o,suggestions:i.suggestions,context:i.context,validate:i.validate})}return{__type:Q,questions:r,context:n}}function ne(e,t){return{__type:ee,tool:e,...t}}function re(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Q}function oe(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===ee}import{z as A}from"zod";var Ce=["waniwani/sessionId","openai/sessionId","sessionId","conversationId","anthropic/sessionId"];function ie(e){if(e)for(let t of Ce){let n=e[t];if(typeof n=="string"&&n.length>0)return n}}function L(e){return e!=null&&e!==""}async function b(e,t){return e.type==="direct"?e.to:e.condition(t)}function se(e,t,n,r){if(e.every(u=>L(r[u.field])))return null;let o=e.filter(u=>!L(r[u.field])),a=o.length===1,i=o[0];return{content:a&&i?{status:"interrupt",question:i.question,field:i.field,...i.suggestions?{suggestions:i.suggestions}:{},...i.context||t?{context:i.context??t}:{}}:{status:"interrupt",questions:o,...t?{context:t}:{}},flowTokenContent:{step:n,state:r,...a&&i?{field:i.field}:{}}}}async function W(e,t,n,r,o,a){let i=e,s={...t},u=50,d=0;for(;d++<u;){if(i===I)return{content:{status:"complete"},flowTokenContent:{state:s}};let g=n.get(i);if(!g)return{content:{status:"error",error:`Unknown node: "${i}"`}};try{let c=await g({state:s,meta:a,interrupt:te,showWidget:ne});if(re(c)){for(let f of c.questions)f.validate&&o.set(`${i}:${f.field}`,f.validate);let l=se(c.questions,c.context,i,s);if(l)return l;for(let f of c.questions){let v=o.get(`${i}:${f.field}`);if(v)try{let k=s[f.field],y=await v(k);y&&typeof y=="object"&&(s={...s,...y})}catch(k){let y=k instanceof Error?k.message:String(k);delete s[f.field];let M=c.questions.map(E=>E.field===f.field?{...E,context:E.context?`ERROR: ${y}
|
|
2
2
|
|
|
3
|
-
${
|
|
4
|
-
`)}var
|
|
5
|
-
${o}`,i=e.store??new _,s=new Map;async function u(c,g,p){if(c.action==="start"){let d=r.get(x);if(!d)return{content:{status:"error",error:"No start edge"}};let T={...c.stateUpdates??{}},l=await R(d,T);return F(l,T,n,r,s,p)}if(c.action==="continue"){if(!g)return{content:{status:"error",error:"No session ID available for continue action."}};let d=await i.get(g);if(!d)return{content:{status:"error",error:"Flow state not found. The flow may have expired."}};let T=d.state,l=d.step;if(!l)return{content:{status:"error",error:"Flow state is missing the current step. The flow may have expired."}};let h={...T,...c.stateUpdates??{}};if(d.widgetId){let f=r.get(l);if(!f)return{content:{status:"error",error:`No edge from step "${l}"`}};let S=await R(f,h);return F(S,h,n,r,s,p)}return F(l,h,n,r,s,p)}return{content:{status:"error",error:`Unknown action: "${c.action}"`}}}return{id:t.id,title:t.title,description:a,async register(c){c.registerTool(t.id,{title:t.title,description:a,inputSchema:be,annotations:t.annotations},(async(g,p)=>{let T=p._meta??{},l=ee(T),h=await u(g,l,T);return h.flowTokenContent&&l&&await i.set(l,h.flowTokenContent),{content:[{type:"text",text:JSON.stringify(h.content,null,2)}],_meta:T,...h.content.status==="error"?{isError:!0}:{}}}))}}}var I=class{nodes=new Map;edges=new Map;config;constructor(t){this.config=t}addNode(t,n){if(t===x||t===E)throw new Error(`"${t}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(t))throw new Error(`Node "${t}" already exists`);return this.nodes.set(t,n),this}addEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge. Use addConditionalEdge for branching.`);return this.edges.set(t,{type:"direct",to:n}),this}addConditionalEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge.`);return this.edges.set(t,{type:"conditional",condition:n}),this}compile(t){return this.validate(),re({config:this.config,nodes:new Map(this.nodes),edges:new Map(this.edges),store:t?.store})}validate(){if(!this.edges.has(x))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(x);if(t?.type==="direct"&&t.to!==E&&!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!==x&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(r.type==="direct"&&r.to!==E&&!this.nodes.has(r.to))throw new Error(`Edge from "${n}" references non-existent node: "${r.to}"`)}for(let[n]of this.nodes)if(!this.edges.has(n))throw new Error(`Node "${n}" has no outgoing edge. Add one with .addEdge("${n}", ...) or .addConditionalEdge("${n}", ...)`)}};function oe(e){return new I(e)}function ie(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function se(e,t){let n=t?.stateStore,r=[],o=`test-session-${Math.random().toString(36).slice(2,10)}`,a={registerTool:(...c)=>{r.push(c)}};await e.register(a);let i=r[0]?.[2];if(!i)throw new Error(`Flow "${e.id}" did not register a handler`);let s={_meta:{sessionId:o}};async function u(c){return{...c,decodedState:n?await n.get(o):null}}return{async start(c){let g=await i({action:"start",...c?{stateUpdates:c}:{}},s);return u(ie(g))},async continueWith(c){let g=await i({action:"continue",...c?{stateUpdates:c}:{}},s);return u(ie(g))},async lastState(){return n?n.get(o):null}}}var W="text/html+skybridge",A="text/html;profile=mcp-app",ae=async(e,t)=>{let n=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${n}${t}`)).text()};function ce(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function de(e){let t=e.widgetCSP?{connectDomains:e.widgetCSP.connect_domains,resourceDomains:e.widgetCSP.resource_domains,frameDomains:e.widgetCSP.frame_domains,redirectDomains:e.widgetCSP.redirect_domains}:void 0;return{ui:{...t&&{csp:t},...e.widgetDomain&&{domain:e.widgetDomain},...e.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function $(e){return{...e.openaiTemplateUri&&{"openai/outputTemplate":e.openaiTemplateUri},"openai/toolInvocation/invoking":e.invoking,"openai/toolInvocation/invoked":e.invoked,"openai/widgetAccessible":!0,"openai/resultCanProduceWidget":!0,...e.mcpTemplateUri&&{ui:{resourceUri:e.mcpTemplateUri,...e.autoHeight&&{autoHeight:!0}}}}}function ue(e){let{id:t,title:n,description:r,baseUrl:o,htmlPath:a,widgetDomain:i,prefersBorder:s=!0,autoHeight:u=!0}=e,c=e.widgetCSP??{connect_domains:[o],resource_domains:[o]};if(process.env.NODE_ENV==="development")try{let{hostname:f}=new URL(o);(f==="localhost"||f==="127.0.0.1")&&(c={...c,connect_domains:[...c.connect_domains||[],`ws://${f}:*`,`wss://${f}:*`],resource_domains:[...c.resource_domains||[],`http://${f}:*`]})}catch{}let g=`ui://widgets/apps-sdk/${t}.html`,p=`ui://widgets/ext-apps/${t}.html`,d=null,T=()=>(d||(d=ae(o,a)),d),l=r;async function h(f){let S=await T();f.registerResource(`${t}-openai-widget`,g,{title:n,description:l,mimeType:W,_meta:{"openai/widgetDescription":l,"openai/widgetPrefersBorder":s}},async y=>({contents:[{uri:y.href,mimeType:W,text:S,_meta:ce({description:l,prefersBorder:s,widgetDomain:i,widgetCSP:c})}]})),f.registerResource(`${t}-mcp-widget`,p,{title:n,description:l,mimeType:A,_meta:{ui:{prefersBorder:s}}},async y=>({contents:[{uri:y.href,mimeType:A,text:S,_meta:de({description:l,prefersBorder:s,widgetCSP:c})}]}))}return{id:t,title:n,description:r,openaiUri:g,mcpUri:p,autoHeight:u,register:h}}function _e(e,t){let{resource:n,description:r,inputSchema:o,annotations:a,autoInjectResultText:i=!0}=e,s=e.id??n?.id,u=e.title??n?.title;if(!s)throw new Error("createTool: `id` is required when no resource is provided");if(!u)throw new Error("createTool: `title` is required when no resource is provided");let c=n?$({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:s,title:u,description:r,async register(g){g.registerTool(s,{title:u,description:r,inputSchema:o,annotations:a,...c&&{_meta:c}},(async(p,d)=>{let l=d._meta??{},h=await t(p,{extra:{_meta:l}});return n&&h.data?{content:[{type:"text",text:h.text}],structuredContent:h.data,_meta:{...c,...l,...i===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:h.text}],...h.data?{structuredContent:h.data}:{},...i===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function Me(e,t){await Promise.all(t.map(n=>n.register(e)))}var D=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var Fe="@waniwani/sdk";function le(e){let{baseUrl:t,apiKey:n}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function o(a,i,s){let u=r(),c=`${t.replace(/\/$/,"")}${i}`,g={Authorization:`Bearer ${u}`,"X-WaniWani-SDK":Fe},p={method:a,headers:g};s!==void 0&&(g["Content-Type"]="application/json",p.body=JSON.stringify(s));let d=await fetch(c,p);if(!d.ok){let l=await d.text().catch(()=>"");throw new D(l||`KB API error: HTTP ${d.status}`,d.status)}return(await d.json()).data}return{async ingest(a){return o("POST","/api/mcp/kb/ingest",{files:a})},async search(a,i){return o("POST","/api/mcp/kb/search",{query:a,...i})},async sources(){return o("GET","/api/mcp/kb/sources")}}}var Pe="@waniwani/sdk";function N(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??pe,o=De(e),a=U(e.meta),i=U(e.metadata),s=Ue(e,a),u=k(e.eventId)??r(),c=Ne(e.timestamp,n),g=k(e.source)??t.source??Pe,p=L(e)?{...e}:void 0,d={...i};return Object.keys(a).length>0&&(d.meta=a),p&&(d.rawLegacy=p),{id:u,type:"mcp.event",name:o,source:g,timestamp:c,correlation:s,properties:We(e,o),metadata:d,rawLegacy:p}}function pe(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function We(e,t){if(!L(e))return U(e.properties);let n=Ae(e,t),r=U(e.properties);return{...n,...r}}function Ae(e,t){switch(t){case"tool.called":{let n={};return k(e.toolName)&&(n.name=e.toolName),k(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),k(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return k(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),k(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function De(e){return L(e)?e.eventType:e.event}function Ue(e,t){let n=k(e.requestId)??M(t,["openai/requestId","requestId","mcp/requestId"]),r=k(e.sessionId)??M(t,["openai/sessionId","sessionId","conversationId","anthropic/sessionId"]),o=k(e.traceId)??M(t,["openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"]),a=k(e.externalUserId)??M(t,["openai/userId","externalUserId","userId","actorId"]),i=k(e.correlationId)??M(t,["correlationId","openai/requestId"])??n,s={};return r&&(s.sessionId=r),o&&(s.traceId=o),n&&(s.requestId=n),i&&(s.correlationId=i),a&&(s.externalUserId=a),s}function Ne(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 M(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim().length>0)return r}}function U(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function k(e){if(typeof e=="string"&&e.trim().length!==0)return e}function L(e){return"eventType"in e}var Oe="/api/mcp/events/v2/batch";var fe="@waniwani/sdk",Be=new Set([401,403]),je=new Set([408,425,429,500,502,503,504]);function ge(e){return new H(e)}var H=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=Le(t.baseUrl,t.endpointPath??Oe),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??fetch,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(r=>setTimeout(r,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs))}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[WaniWani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[WaniWani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,r=this.flush();if(!Number.isFinite(n)||n<=0)return await r,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let o=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(n).then(()=>o)])===o?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,r=t;for(;r.length>0&&!this.isStopped;){this.inFlightCount=r.length;let o=await this.sendBatchOnce(r);switch(this.inFlightCount=0,o.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(o.status,r.length);return;case"permanent":this.logger.error("[WaniWani] Dropping %d event(s) after permanent failure: %s",r.length,o.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d event(s) after retry exhaustion: %s",r.length,o.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(o.permanent.length>0&&this.logger.error("[WaniWani] Dropping %d event(s) rejected as permanent",o.permanent.length),o.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d retryable event(s) after retry exhaustion",o.retryable.length);return}r=o.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-WaniWani-SDK":fe},body:JSON.stringify(this.makeBatchRequest(t))})}catch(a){return{kind:"retryable",reason:He(a)}}if(Be.has(n.status))return{kind:"auth",status:n.status};if(je.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await $e(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:fe,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(i=>[i.id,i])),o=[],a=[];for(let i of n){let s=r.get(i.eventId);if(s){if(qe(i)){o.push(s);continue}a.push(s)}}return{retryable:o,permanent:a}}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 qe(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 $e(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function Le(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function He(e){return e instanceof Error?e.message:String(e)}function he(e){let{baseUrl:t,apiKey:n,tracking:r}=e;function o(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}let a=n?ge({baseUrl: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,i={async identify(s,u){o();let c=N({event:"user.identified",externalUserId:s,properties:u});return a?.enqueue(c),{eventId:c.id}},async track(s){o();let u=N(s);return a?.enqueue(u),{eventId:u.id}},async flush(){o(),await a?.flush()},async shutdown(s){return o(),await a?.shutdown({timeoutMs:s?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return a&&Ke(i,r.shutdownTimeoutMs),i}function Ke(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 O(e){let t=e?.baseUrl??"https://app.waniwani.ai",n=e?.apiKey??process.env.WANIWANI_API_KEY,r={endpointPath:e?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:e?.tracking?.flushIntervalMs??1e3,maxBatchSize:e?.tracking?.maxBatchSize??20,maxBufferSize:e?.tracking?.maxBufferSize??1e3,maxRetries:e?.tracking?.maxRetries??3,retryBaseDelayMs:e?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:e?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:e?.tracking?.shutdownTimeoutMs??2e3},o={baseUrl:t,apiKey:n,tracking:r},a=he(o),i=le(o);return{...a,kb:i,_config:o}}function Ve(e){let t=e.event_type??"widget_click",r=t.startsWith("widget_")?t:`widget_${t}`,o={...e.metadata??{}};return e.event_name&&(o.event_name=e.event_name),{event:r,properties:o,sessionId:e.session_id,traceId:e.trace_id,externalUserId:e.user_id,eventId:e.event_id,timestamp:e.timestamp,source:e.source??"widget"}}function ze(e){let t={apiKey:e?.apiKey,baseUrl:e?.baseUrl},n;function r(){return n||(n=O(t)),n}return async function(a){let i;try{i=await a.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!Array.isArray(i.events)||i.events.length===0)return new Response(JSON.stringify({error:"Missing or empty events array"}),{status:400,headers:{"Content-Type":"application/json"}});try{let s=r(),u=[];for(let c of i.events){let g=Ve(c),p=await s.track(g);u.push(p.eventId)}return await s.flush(),new Response(JSON.stringify({ok:!0,accepted:u.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(s){let u=s instanceof Error?s.message:"Unknown error";return new Response(JSON.stringify({error:u}),{status:500,headers:{"Content-Type":"application/json"}})}}}var B=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-12e4?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=Ye(this.config.baseUrl,"/api/mcp/widget-tokens"),o={};t&&(o.sessionId=t),n&&(o.traceId=n);try{let a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o)});if(!a.ok)return null;let i=await a.json(),s=i.data&&typeof i.data=="object"?i.data:i,u=new Date(s.expiresAt).getTime();return!s.token||Number.isNaN(u)?null:(this.cached={token:s.token,expiresAt:u},s.token)}catch{return null}}};function Ye(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}var me="https://app.waniwani.ai";function Xe(e,t={}){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t.client??O(t.config),o=t.injectWidgetToken!==!1,a=null;function i(){if(a)return a;let u=r._config.apiKey;return u?(a=new B({baseUrl:r._config.baseUrl??me,apiKey:u}),a):null}let s=e.registerTool.bind(e);return n.registerTool=((...u)=>{let[c,g,p]=u,d=typeof c=="string"&&c.trim().length>0?c:"unknown";if(typeof p!="function")return s(...u);let T=p;return s(c,g,async(h,f)=>{let S=performance.now();try{let y=await T(h,f),v=Math.round(performance.now()-S);return await ye(r,we(d,f,t,{durationMs:v,status:"ok"}),t.onError),t.flushAfterToolCall&&await Te(r,t.onError),o&&await Je(y,i(),r._config.baseUrl??me,t.onError),Ge(y,f),y}catch(y){let v=Math.round(performance.now()-S);throw await ye(r,we(d,f,t,{durationMs:v,status:"error",errorMessage:y instanceof Error?y.message:String(y)}),t.onError),t.flushAfterToolCall&&await Te(r,t.onError),y}})}),n}async function Je(e,t,n,r){if(!C(e))return;C(e._meta)||(e._meta={});let o=e._meta,a={endpoint:`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let i=await t.getToken();i&&(a.token=i)}catch(i){r?.(V(i))}o.waniwani=a}function we(e,t,n,r){let o=Ze(e,n.toolType),a=ke(t);return{event:"tool.called",properties:{name:e,type:o,...r??{}},meta:a,metadata:{source:"withWaniwani",...n.metadata??{}}}}function Ze(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function ke(e){if(!C(e))return;let t=e._meta;if(C(t))return t}function C(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}async function ye(e,t,n){try{await e.track(t)}catch(r){n?.(V(r))}}async function Te(e,t){try{await e.flush()}catch(n){t?.(V(n))}}function V(e){return e instanceof Error?e:new Error(String(e))}var K="waniwani/userLocation";function Ge(e,t){let n=ke(t);if(!n)return;let r=n[K];if(!r||!C(e))return;C(e._meta)||(e._meta={});let o=e._meta;o[K]||(o[K]=r)}export{E as END,x as START,I as StateGraph,oe as createFlow,se as createFlowTestHarness,ue as createResource,_e as createTool,ze as createTrackingRoute,j as detectPlatform,xe as isMCPApps,ve as isOpenAI,Me as registerTools,Xe as withWaniwani};
|
|
3
|
+
${E.context}`:`ERROR: ${y}`}:E),C=se(M,c.context,i,s);if(C)return C;break}}let m=r.get(i);if(!m)return{content:{status:"error",error:`No outgoing edge from node "${i}"`}};i=await b(m,s);continue}if(oe(c)){let l=c.field;if(l&&L(s[l])){let m=r.get(i);if(!m)return{content:{status:"error",error:`No outgoing edge from node "${i}"`}};i=await b(m,s);continue}return{content:{status:"widget",tool:c.tool.id,data:c.data,description:c.description,...c.interactive===!1?{interactive:!1}:{}},flowTokenContent:{step:i,state:s,field:l,widgetId:c.tool.id}}}s={...s,...c};let T=r.get(i);if(!T)return{content:{status:"error",error:`No outgoing edge from node "${i}"`}};i=await b(T,s)}catch(p){return{content:{status:"error",error:p instanceof Error?p.message:String(p)},flowTokenContent:{step:i,state:s}}}}return{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"}}}var be="@waniwani/sdk",_e="https://app.waniwani.ai",F=class{baseUrl;apiKey;constructor(t){this.baseUrl=(t?.baseUrl??process.env.WANIWANI_BASE_URL??_e).replace(/\/$/,""),this.apiKey=t?.apiKey??process.env.WANIWANI_API_KEY}async get(t){if(!this.apiKey)return null;try{return await this.request("/api/mcp/redis/get",{key:t})??null}catch{return null}}async set(t,n){if(this.apiKey)try{await this.request("/api/mcp/redis/set",{key:t,value:n})}catch{}}async delete(t){if(this.apiKey)try{await this.request("/api/mcp/redis/delete",{key:t})}catch{}}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":be},body:JSON.stringify(n)});if(!o.ok){let i=await o.text().catch(()=>"");throw new Error(i||`Flow state API error: HTTP ${o.status}`)}return(await o.json()).data}};function Me(e){let t=e.description??"",n=e._zod?.def;if(n?.type==="enum"&&n.entries){let r=Object.keys(n.entries).map(o=>`"${o}"`).join(" | ");return t?`${r} \u2014 ${t}`:r}return t}function ae(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. If the user\'s message already'," contains answers to likely questions, extract them into `stateUpdates`"," as `{ field: value }` pairs. The engine will auto-skip steps whose"," fields are already filled."," Only extract values the user explicitly stated \u2014 do NOT guess or invent values."];if(e.state){let n=Object.entries(e.state).map(([r,o])=>{let a=Me(o);return a?`\`${r}\` (${a})`:`\`${r}\``}).join(", ");t.push(` Known fields: ${n}.`)}return t.push("2. The response JSON `status` field tells you what to do next:",' - `"interrupt"`: Pause and ask the user. Two forms:'," a. Single question: `{ question, field, context? }` \u2014 ask `question`, store answer in `field`."," b. Multi-question: `{ questions: [{question, field}, ...], context? }` \u2014 ask ALL questions"," in one conversational message, collect all answers."," `context` (if present) is hidden AI instructions \u2014 use to shape your response, do NOT show verbatim."," Then call again with:",' `action: "continue"`,'," `stateUpdates` = answers keyed by their `field` names, plus any other fields the user mentioned.",' - `"widget"`: The flow wants to show a UI widget. Call the tool named in the `tool`'," field, passing the `data` object as the tool's input."," If the response includes `interactive: false`, the widget is display-only:"," call the display tool, show the widget, then immediately call THIS flow tool again with",' `action: "continue"`. In that case, do NOT wait for the user'," to click or use the widget, and do NOT ask them to interact with it unless the"," description explicitly says otherwise."," Otherwise, present the widget result to the user. When the user makes a choice or interacts"," with the widget, call THIS flow tool again with:",' `action: "continue"`,'," `stateUpdates` = `{ [field]: <user's selection> }` plus any other fields the user mentioned.",' - `"complete"`: The flow is done. Present the result to the user.',' - `"error"`: Something went wrong. Show the `error` message.',"","3. Do NOT invent state values. Only use `stateUpdates` for information the user explicitly provided.","4. Include only the fields the user actually answered in `stateUpdates` \u2014 do NOT guess missing ones."," If the user did not answer all pending questions, the engine will re-prompt for the remaining ones."," If the user mentioned values for other known fields, include those too \u2014"," they will be applied immediately and those steps will be auto-skipped."),t.join(`
|
|
4
|
+
`)}var Fe={action:A.enum(["start","continue"]).describe('"start" to begin the flow, "continue" to resume after a pause (interrupt or widget)'),stateUpdates:A.record(A.string(),A.unknown()).optional().describe("State field values to set before processing the next node. Use this to pass the user's answer (keyed by the field name from the response) and any other values the user mentioned.")};function ce(e){let{config:t,nodes:n,edges:r}=e,o=ae(t),a=`${t.description}
|
|
5
|
+
${o}`,i=e.store??new F,s=new Map;async function u(d,g,p){if(d.action==="start"){let c=r.get(R);if(!c)return{content:{status:"error",error:"No start edge"}};let T={...d.stateUpdates??{}},l=await b(c,T);return W(l,T,n,r,s,p)}if(d.action==="continue"){if(!g)return{content:{status:"error",error:"No session ID available for continue action."}};let c=await i.get(g);if(!c)return{content:{status:"error",error:"Flow state not found. The flow may have expired."}};let T=c.state,l=c.step;if(!l)return{content:{status:"error",error:"Flow state is missing the current step. The flow may have expired."}};let m={...T,...d.stateUpdates??{}};if(c.widgetId){let f=r.get(l);if(!f)return{content:{status:"error",error:`No edge from step "${l}"`}};let v=await b(f,m);return W(v,m,n,r,s,p)}return W(l,m,n,r,s,p)}return{content:{status:"error",error:`Unknown action: "${d.action}"`}}}return{id:t.id,title:t.title,description:a,async register(d){d.registerTool(t.id,{title:t.title,description:a,inputSchema:Fe,annotations:t.annotations},(async(g,p)=>{let T=p._meta??{},l=ie(T),m=await u(g,l,T);return m.flowTokenContent&&l&&await i.set(l,m.flowTokenContent),{content:[{type:"text",text:JSON.stringify(m.content,null,2)}],_meta:T,...m.content.status==="error"?{isError:!0}:{}}}))}}}var _=class{nodes=new Map;edges=new Map;config;constructor(t){this.config=t}addNode(t,n){if(t===R||t===I)throw new Error(`"${t}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(t))throw new Error(`Node "${t}" already exists`);return this.nodes.set(t,n),this}addEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge. Use addConditionalEdge for branching.`);return this.edges.set(t,{type:"direct",to:n}),this}addConditionalEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge.`);return this.edges.set(t,{type:"conditional",condition:n}),this}compile(t){return this.validate(),ce({config:this.config,nodes:new Map(this.nodes),edges:new Map(this.edges),store:t?.store})}validate(){if(!this.edges.has(R))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(R);if(t?.type==="direct"&&t.to!==I&&!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!==R&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(r.type==="direct"&&r.to!==I&&!this.nodes.has(r.to))throw new Error(`Edge from "${n}" references non-existent node: "${r.to}"`)}for(let[n]of this.nodes)if(!this.edges.has(n))throw new Error(`Node "${n}" has no outgoing edge. Add one with .addEdge("${n}", ...) or .addConditionalEdge("${n}", ...)`)}};function de(e){return new _(e)}function ue(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function le(e,t){let n=t?.stateStore,r=[],o=`test-session-${Math.random().toString(36).slice(2,10)}`,a={registerTool:(...d)=>{r.push(d)}};await e.register(a);let i=r[0]?.[2];if(!i)throw new Error(`Flow "${e.id}" did not register a handler`);let s={_meta:{sessionId:o}};async function u(d){return{...d,decodedState:n?await n.get(o):null}}return{async start(d){let g=await i({action:"start",...d?{stateUpdates:d}:{}},s);return u(ue(g))},async continueWith(d){let g=await i({action:"continue",...d?{stateUpdates:d}:{}},s);return u(ue(g))},async lastState(){return n?n.get(o):null}}}var U="text/html+skybridge",D="text/html;profile=mcp-app",pe=async(e,t)=>{let n=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${n}${t}`)).text()};function fe(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function ge(e){let t=e.widgetCSP?{connectDomains:e.widgetCSP.connect_domains,resourceDomains:e.widgetCSP.resource_domains,frameDomains:e.widgetCSP.frame_domains,redirectDomains:e.widgetCSP.redirect_domains}:void 0;return{ui:{...t&&{csp:t},...e.widgetDomain&&{domain:e.widgetDomain},...e.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function H(e){return{...e.openaiTemplateUri&&{"openai/outputTemplate":e.openaiTemplateUri},"openai/toolInvocation/invoking":e.invoking,"openai/toolInvocation/invoked":e.invoked,"openai/widgetAccessible":!0,"openai/resultCanProduceWidget":!0,...e.mcpTemplateUri&&{ui:{resourceUri:e.mcpTemplateUri,...e.autoHeight&&{autoHeight:!0}}}}}function me(e){let{id:t,title:n,description:r,baseUrl:o,htmlPath:a,widgetDomain:i,prefersBorder:s=!0,autoHeight:u=!0}=e,d=e.widgetCSP??{connect_domains:[o],resource_domains:[o]};if(process.env.NODE_ENV==="development")try{let{hostname:f}=new URL(o);(f==="localhost"||f==="127.0.0.1")&&(d={...d,connect_domains:[...d.connect_domains||[],`ws://${f}:*`,`wss://${f}:*`],resource_domains:[...d.resource_domains||[],`http://${f}:*`]})}catch{}let g=`ui://widgets/apps-sdk/${t}.html`,p=`ui://widgets/ext-apps/${t}.html`,c=null,T=()=>(c||(c=pe(o,a)),c),l=r;async function m(f){let v=await T();f.registerResource(`${t}-openai-widget`,g,{title:n,description:l,mimeType:U,_meta:{"openai/widgetDescription":l,"openai/widgetPrefersBorder":s}},async k=>({contents:[{uri:k.href,mimeType:U,text:v,_meta:fe({description:l,prefersBorder:s,widgetDomain:i,widgetCSP:d})}]})),f.registerResource(`${t}-mcp-widget`,p,{title:n,description:l,mimeType:D,_meta:{ui:{prefersBorder:s}}},async k=>({contents:[{uri:k.href,mimeType:D,text:v,_meta:ge({description:l,prefersBorder:s,widgetCSP:d})}]}))}return{id:t,title:n,description:r,openaiUri:g,mcpUri:p,autoHeight:u,register:m}}function Pe(e,t){let{resource:n,description:r,inputSchema:o,annotations:a,autoInjectResultText:i=!0}=e,s=e.id??n?.id,u=e.title??n?.title;if(!s)throw new Error("createTool: `id` is required when no resource is provided");if(!u)throw new Error("createTool: `title` is required when no resource is provided");let d=n?H({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:s,title:u,description:r,async register(g){g.registerTool(s,{title:u,description:r,inputSchema:o,annotations:a,...d&&{_meta:d}},(async(p,c)=>{let l=c._meta??{},m=await t(p,{extra:{_meta:l}});return n&&m.data?{content:[{type:"text",text:m.text}],structuredContent:m.data,_meta:{...d,...l,...i===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:m.text}],...m.data?{structuredContent:m.data}:{},...i===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function We(e,t){await Promise.all(t.map(n=>n.register(e)))}var N=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var Ae="@waniwani/sdk";function he(e){let{baseUrl:t,apiKey:n}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function o(a,i,s){let u=r(),d=`${t.replace(/\/$/,"")}${i}`,g={Authorization:`Bearer ${u}`,"X-WaniWani-SDK":Ae},p={method:a,headers:g};s!==void 0&&(g["Content-Type"]="application/json",p.body=JSON.stringify(s));let c=await fetch(d,p);if(!c.ok){let l=await c.text().catch(()=>"");throw new N(l||`KB API error: HTTP ${c.status}`,c.status)}return(await c.json()).data}return{async ingest(a){return o("POST","/api/mcp/kb/ingest",{files:a})},async search(a,i){return o("POST","/api/mcp/kb/search",{query:a,...i})},async sources(){return o("GET","/api/mcp/kb/sources")}}}var Ue="@waniwani/sdk";function B(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??we,o=Oe(e),a=O(e.meta),i=O(e.metadata),s=Be(e,a),u=S(e.eventId)??r(),d=je(e.timestamp,n),g=S(e.source)??t.source??Ue,p=K(e)?{...e}:void 0,c={...i};return Object.keys(a).length>0&&(c.meta=a),p&&(c.rawLegacy=p),{id:u,type:"mcp.event",name:o,source:g,timestamp:d,correlation:s,properties:De(e,o),metadata:c,rawLegacy:p}}function we(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function De(e,t){if(!K(e))return O(e.properties);let n=Ne(e,t),r=O(e.properties);return{...n,...r}}function Ne(e,t){switch(t){case"tool.called":{let n={};return S(e.toolName)&&(n.name=e.toolName),S(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),S(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return S(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),S(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function Oe(e){return K(e)?e.eventType:e.event}function Be(e,t){let n=S(e.requestId)??P(t,["openai/requestId","requestId","mcp/requestId"]),r=S(e.sessionId)??P(t,["openai/sessionId","sessionId","conversationId","anthropic/sessionId"]),o=S(e.traceId)??P(t,["openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"]),a=S(e.externalUserId)??P(t,["openai/userId","externalUserId","userId","actorId"]),i=S(e.correlationId)??P(t,["correlationId","openai/requestId"])??n,s={};return r&&(s.sessionId=r),o&&(s.traceId=o),n&&(s.requestId=n),i&&(s.correlationId=i),a&&(s.externalUserId=a),s}function je(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 P(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim().length>0)return r}}function O(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function S(e){if(typeof e=="string"&&e.trim().length!==0)return e}function K(e){return"eventType"in e}var $e="/api/mcp/events/v2/batch";var ye="@waniwani/sdk",qe=new Set([401,403]),Le=new Set([408,425,429,500,502,503,504]);function Te(e){return new V(e)}var V=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=Ve(t.baseUrl,t.endpointPath??$e),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??fetch,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(r=>setTimeout(r,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs))}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[WaniWani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[WaniWani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,r=this.flush();if(!Number.isFinite(n)||n<=0)return await r,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let o=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(n).then(()=>o)])===o?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,r=t;for(;r.length>0&&!this.isStopped;){this.inFlightCount=r.length;let o=await this.sendBatchOnce(r);switch(this.inFlightCount=0,o.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(o.status,r.length);return;case"permanent":this.logger.error("[WaniWani] Dropping %d event(s) after permanent failure: %s",r.length,o.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d event(s) after retry exhaustion: %s",r.length,o.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(o.permanent.length>0&&this.logger.error("[WaniWani] Dropping %d event(s) rejected as permanent",o.permanent.length),o.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d retryable event(s) after retry exhaustion",o.retryable.length);return}r=o.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-WaniWani-SDK":ye},body:JSON.stringify(this.makeBatchRequest(t))})}catch(a){return{kind:"retryable",reason:ze(a)}}if(qe.has(n.status))return{kind:"auth",status:n.status};if(Le.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await Ke(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:ye,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(i=>[i.id,i])),o=[],a=[];for(let i of n){let s=r.get(i.eventId);if(s){if(He(i)){o.push(s);continue}a.push(s)}}return{retryable:o,permanent:a}}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 He(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 Ke(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function Ve(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function ze(e){return e instanceof Error?e.message:String(e)}function ke(e){let{baseUrl:t,apiKey:n,tracking:r}=e;function o(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}let a=n?Te({baseUrl: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,i={async identify(s,u){o();let d=B({event:"user.identified",externalUserId:s,properties:u});return a?.enqueue(d),{eventId:d.id}},async track(s){o();let u=B(s);return a?.enqueue(u),{eventId:u.id}},async flush(){o(),await a?.flush()},async shutdown(s){return o(),await a?.shutdown({timeoutMs:s?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return a&&Ye(i,r.shutdownTimeoutMs),i}function Ye(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 j(e){let t=e?.baseUrl??"https://app.waniwani.ai",n=e?.apiKey??process.env.WANIWANI_API_KEY,r={endpointPath:e?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:e?.tracking?.flushIntervalMs??1e3,maxBatchSize:e?.tracking?.maxBatchSize??20,maxBufferSize:e?.tracking?.maxBufferSize??1e3,maxRetries:e?.tracking?.maxRetries??3,retryBaseDelayMs:e?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:e?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:e?.tracking?.shutdownTimeoutMs??2e3},o={baseUrl:t,apiKey:n,tracking:r},a=ke(o),i=he(o);return{...a,kb:i,_config:o}}function Xe(e){let t=e.event_type??"widget_click",r=t.startsWith("widget_")?t:`widget_${t}`,o={...e.metadata??{}};return e.event_name&&(o.event_name=e.event_name),{event:r,properties:o,sessionId:e.session_id,traceId:e.trace_id,externalUserId:e.user_id,eventId:e.event_id,timestamp:e.timestamp,source:e.source??"widget"}}function Je(e){let t={apiKey:e?.apiKey,baseUrl:e?.baseUrl},n;function r(){return n||(n=j(t)),n}return async function(a){let i;try{i=await a.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!Array.isArray(i.events)||i.events.length===0)return new Response(JSON.stringify({error:"Missing or empty events array"}),{status:400,headers:{"Content-Type":"application/json"}});try{let s=r(),u=[];for(let d of i.events){let g=Xe(d),p=await s.track(g);u.push(p.eventId)}return await s.flush(),new Response(JSON.stringify({ok:!0,accepted:u.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(s){let u=s instanceof Error?s.message:"Unknown error";return new Response(JSON.stringify({error:u}),{status:500,headers:{"Content-Type":"application/json"}})}}}var $=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-12e4?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=Ze(this.config.baseUrl,"/api/mcp/widget-tokens"),o={};t&&(o.sessionId=t),n&&(o.traceId=n);try{let a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o)});if(!a.ok)return null;let i=await a.json(),s=i.data&&typeof i.data=="object"?i.data:i,u=new Date(s.expiresAt).getTime();return!s.token||Number.isNaN(u)?null:(this.cached={token:s.token,expiresAt:u},s.token)}catch{return null}}};function Ze(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}var z="waniwani/userLocation";function x(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Se(e){if(!x(e))return;let t=e._meta;return x(t)?t:void 0}function Y(e){if(!x(e))return;let t=e.content;return Array.isArray(t)?t.find(r=>x(r)&&r.type==="text"&&typeof r.text=="string")?.text:void 0}function Ge(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function X(e,t,n,r,o){let a=Ge(e,n.toolType),i=Se(t);return{event:"tool.called",properties:{name:e,type:a,...r??{}},meta:i,metadata:{source:"withWaniwani",...n.metadata??{},...o&&{clientInfo:o}}}}async function J(e,t,n){try{await e.track(t)}catch(r){n?.(G(r))}}async function Z(e,t){try{await e.flush()}catch(n){t?.(G(n))}}async function ve(e,t,n,r){if(!x(e))return;x(e._meta)||(e._meta={});let o=e._meta,a={endpoint:`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let i=await t.getToken();i&&(a.token=i)}catch(i){r?.(G(i))}o.waniwani=a}function xe(e,t){let n=Se(t);if(!n)return;let r=n[z];if(!r||!x(e))return;x(e._meta)||(e._meta={});let o=e._meta;o[z]||(o[z]=r)}function G(e){return e instanceof Error?e:new Error(String(e))}var Re="https://app.waniwani.ai";function Qe(e,t={}){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t.client??j(t.config),o=t.injectWidgetToken!==!1,a=null;function i(){if(a)return a;let u=r._config.apiKey;return u?(a=new $({baseUrl:r._config.baseUrl??Re,apiKey:u}),a):null}let s=e.registerTool.bind(e);return n.registerTool=((...u)=>{let[d,g,p]=u,c=typeof d=="string"&&d.trim().length>0?d:"unknown";if(typeof p!="function")return s(...u);let T=p;return s(d,g,async(m,f)=>{let v=performance.now(),k=e.server?.getClientVersion?.();try{let y=await T(m,f),M=Math.round(performance.now()-v),C=x(y)&&y.isError===!0;if(C){let E=Y(y);console.error(`[waniwani] Tool "${c}" returned error${E?`: ${E}`:""}`)}return await J(r,X(c,f,t,{durationMs:M,status:C?"error":"ok",...C&&{errorMessage:Y(y)??"Unknown tool error"}},k),t.onError),t.flushAfterToolCall&&await Z(r,t.onError),o&&await ve(y,i(),r._config.baseUrl??Re,t.onError),xe(y,f),y}catch(y){let M=Math.round(performance.now()-v);throw await J(r,X(c,f,t,{durationMs:M,status:"error",errorMessage:y instanceof Error?y.message:String(y)},k),t.onError),t.flushAfterToolCall&&await Z(r,t.onError),y}})}),n}export{I as END,R as START,_ as StateGraph,de as createFlow,le as createFlowTestHarness,me as createResource,Pe as createTool,Je as createTrackingRoute,q as detectPlatform,Ie as isMCPApps,Ee as isOpenAI,We as registerTools,Qe as withWaniwani};
|
|
6
6
|
//# sourceMappingURL=index.js.map
|