@waniwani/sdk 0.9.9 → 0.9.10
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/LICENSE +661 -21
- package/README.md +39 -32
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/mcp/index.js +5 -5
- package/dist/mcp/index.js.map +1 -1
- package/package.json +2 -2
package/dist/mcp/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
function J(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function
|
|
1
|
+
function J(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function et(){return J()==="openai"}function tt(){return J()==="mcp-apps"}var E="__start__",I="__end__",fe=Symbol.for("waniwani.flow.interrupt"),ge=Symbol.for("waniwani.flow.widget");function me(e,t){let n=t?.context,r=[];for(let[o,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&"question"in i){let a=i;r.push({question:a.question,field:o,suggestions:a.suggestions,context:a.context,validate:a.validate})}return{__type:fe,questions:r,context:n}}function we(e,t){return{__type:ge,tool:typeof e=="string"?e:e.id,...t}}function he(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===fe}function ye(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===ge}import{z as D}from"zod";var Z="waniwani/client";function j(e){if(typeof e=="object"&&e!==null)return e[Z]}function Te(e,t,n){return{track(r){return e.track({...r,meta:{...t,...r.meta}})},identify(r,o){return e.identify(r,o,t)},kb:e.kb,_config:n}}function A(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"],rt=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],ot=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],it=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],st=["correlationId","openai/requestId"];function C(e){return e?A(e,nt):void 0}function ke(e){return e?A(e,rt):void 0}function Se(e){return e?A(e,ot):void 0}function ve(e){return e?A(e,it):void 0}function xe(e){return e?A(e,st):void 0}var at=[{key:"waniwani/sessionId",source:"chatbar"},{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}];function b(e){if(!e)return;let t=e["waniwani/source"];if(typeof t=="string"&&t.length>0)return t;for(let{key:n,source:r}of at){let o=e[n];if(typeof o=="string"&&o.length>0)return r}}function Re(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function N(e,t){let n=t.split("."),r=e;for(let o of n){if(r==null||typeof r!="object")return;r=r[o]}return r}function ct(e,t,n){let r=t.split("."),o=r.pop();if(!o)return;let i=e;for(let a of r)(i[a]==null||typeof i[a]!="object"||Array.isArray(i[a]))&&(i[a]={}),i=i[a];i[o]=n}function Ee(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 X(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?ct(t,n,r):t[n]=r;return t}function _(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]=_(n[r],o):n[r]=o;return n}function Q(e){return e!=null&&e!==""}async function P(e,t){return e.type==="direct"?e.to:e.condition(t)}function Ie(e,t,n,r){if(e.every(c=>Q(N(r,c.field))))return null;let o=e.filter(c=>!Q(N(r,c.field))),i=o.length===1,a=o[0];return{content:i&&a?{status:"interrupt",question:a.question,field:a.field,...a.suggestions?{suggestions:a.suggestions}:{},...a.context||t?{context:a.context??t}:{}}:{status:"interrupt",questions:o,...t?{context:t}:{}},flowTokenContent:{step:n,state:r,...i&&a?{field:a.field}:{}}}}async function K(e,t,n,r,o,i,a){let s=e,c={...t},p=50,f=0;for(;f++<p;){if(s===I)return{content:{status:"complete"},flowTokenContent:{state:c}};let d=n.get(s);if(!d)return{content:{status:"error",error:`Unknown node: "${s}"`}};try{let g=await d({state:c,meta:i,interrupt:me,showWidget:we,waniwani:a});if(he(g)){for(let m of g.questions)m.validate&&o.set(`${s}:${m.field}`,m.validate);let y=Ie(g.questions,g.context,s,c);if(y)return y;for(let m of g.questions){let v=o.get(`${s}:${m.field}`);if(v)try{let S=N(c,m.field),x=await v(S);x&&typeof x=="object"&&(c=_(c,x))}catch(S){let x=S instanceof Error?S.message:String(S);Ee(c,m.field);let pe=g.questions.map(F=>F.field===m.field?{...F,context:F.context?`ERROR: ${x}
|
|
2
2
|
|
|
3
|
-
${F.context}`:`ERROR: ${x}`}:F),le=Ie(pe,g.context,s,c);if(le)return le;break}}let u=r.get(s);if(!u)return{content:{status:"error",error:`No outgoing edge from node "${s}"`}};s=await P(u,c);continue}if(ye(g)){let
|
|
4
|
-
`)}var
|
|
5
|
-
${o}`,a=e.store??new
|
|
6
|
-
`)}var M=class{nodes=new Map;edges=new Map;config;constructor(t){this.config=t}addNode(t,n){if(t===E||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}graph(){return Pe(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return _e({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>Pe(n,r)})}validate(){if(!this.edges.has(E))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(E);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!==E&&!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 We(e){return new M(e)}function Me(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function Fe(e,t){let n=t?.stateStore,r=[],o=`test-session-${Math.random().toString(36).slice(2,10)}`,i={registerTool:(...p)=>{r.push(p)}};await e.register(i);let a=r[0]?.[2];if(!a)throw new Error(`Flow "${e.name}" did not register a handler`);let s={_meta:{sessionId:o}};async function c(p){return{...p,decodedState:n?await n.get(o):null}}return{async start(p,l){let d=await a({action:"start",intent:p,...l?{stateUpdates:l}:{}},s);return c(Me(d))},async continueWith(p){let l=await a({action:"continue",...p?{stateUpdates:p}:{}},s);return c(Me(l))},async lastState(){return n?n.get(o):null}}}var $="text/html+skybridge",B="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 Ne(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 ee(e){return{...e.openaiTemplateUri&&{"openai/outputTemplate":e.openaiTemplateUri},"openai/toolInvocation/invoking":e.invoking,"openai/toolInvocation/invoked":e.invoked,"openai/widgetAccessible":!0,"openai/resultCanProduceWidget":!0,...e.mcpTemplateUri&&{ui:{resourceUri:e.mcpTemplateUri,...e.autoHeight&&{autoHeight:!0}}},...e.mcpTemplateUri&&{"ui/resourceUri":e.mcpTemplateUri}}}function Ue(e){let{id:t,title:n,description:r,baseUrl:o,htmlPath:i,widgetDomain:a,prefersBorder:s=!0,autoHeight:c=!0}=e,p=e.widgetCSP??{connect_domains:[o],resource_domains:[o]};if(process.env.NODE_ENV==="development")try{let{hostname:u}=new URL(o);(u==="localhost"||u==="127.0.0.1")&&(p={...p,connect_domains:[...p.connect_domains||[],`ws://${u}:*`,`wss://${u}:*`],resource_domains:[...p.resource_domains||[],`http://${u}:*`]})}catch{}let l=`ui://widgets/apps-sdk/${t}.html`,d=`ui://widgets/ext-apps/${t}.html`,f=null,g=()=>(f||(f=Ae(o,i)),f),T=r;async function w(u){let m=await g();u.registerResource(`${t}-openai-widget`,l,{title:n,description:T,mimeType:$,_meta:{"openai/widgetDescription":T,"openai/widgetPrefersBorder":s}},async v=>({contents:[{uri:v.href,mimeType:$,text:m,_meta:Ne({description:T,prefersBorder:s,widgetDomain:a,widgetCSP:p})}]})),u.registerResource(`${t}-mcp-widget`,d,{title:n,description:T,mimeType:B,_meta:{ui:{prefersBorder:s}}},async v=>({contents:[{uri:v.href,mimeType:B,text:m,_meta:De({description:T,prefersBorder:s,widgetDomain:a,widgetCSP:p})}]}))}return{id:t,title:n,description:r,openaiUri:l,mcpUri:d,autoHeight:c,register:w}}function ut(e,t){let{resource:n,description:r,inputSchema:o,annotations:i,autoInjectResultText:a=!0}=e,s=e.id??n?.id,c=e.title??n?.title;if(!s)throw new Error("createTool: `id` is required when no resource is provided");if(!c)throw new Error("createTool: `title` is required when no resource is provided");let p=n?ee({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:s,title:c,description:r,async register(l){l.registerTool(s,{title:c,description:r,inputSchema:o,annotations:i,...p&&{_meta:p}},(async(d,f)=>{let g=f,T=g._meta??{},w=j(g),u=await t(d,{extra:{_meta:T},waniwani:w});return n&&u.data?{content:[{type:"text",text:u.text}],structuredContent:u.data,_meta:{...p,...T,...a===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:u.text}],...u.data?{structuredContent:u.data}:{},...a===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function pt(e,t){await Promise.all(t.map(n=>n.register(e)))}var q=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var lt="@waniwani/sdk";function Oe(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,a,s){let c=r(),p=`${t.replace(/\/$/,"")}${a}`,l={Authorization:`Bearer ${c}`,"X-WaniWani-SDK":lt},d={method:i,headers:l};s!==void 0&&(l["Content-Type"]="application/json",d.body=JSON.stringify(s));let f=await fetch(p,d);if(!f.ok){let T=await f.text().catch(()=>"");throw new q(T||`KB API error: HTTP ${f.status}`,f.status)}return(await f.json()).data}return{async ingest(i){return o("POST","/api/mcp/kb/ingest",{files:i})},async search(i,a){return o("POST","/api/mcp/kb/search",{query:i,...a})},async sources(){return o("GET","/api/mcp/kb/sources")}}}var ft="@waniwani/sdk";function L(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??je,o=wt(e),i=H(e.meta),a=H(e.metadata),s=ht(e,i),c=R(e.eventId)??r(),p=yt(e.timestamp,n),l=R(e.source)??b(i)??t.source??ft,d=te(e)?{...e}:void 0,f={...a};return Object.keys(i).length>0&&(f.meta=i),d&&(f.rawLegacy=d),{id:c,type:"mcp.event",name:o,source:l,timestamp:p,correlation:s,properties:gt(e,o),metadata:f,rawLegacy:d}}function je(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function gt(e,t){if(!te(e))return H(e.properties);let n=mt(e,t),r=H(e.properties);return{...n,...r}}function mt(e,t){switch(t){case"tool.called":{let n={};return R(e.toolName)&&(n.name=e.toolName),R(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),R(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return R(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),R(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function wt(e){return te(e)?e.eventType:e.event}function ht(e,t){let n=R(e.requestId)??ke(t),r=R(e.sessionId)??C(t),o=R(e.traceId)??Se(t),i=R(e.externalUserId)??ve(t),a=R(e.correlationId)??xe(t)??n,s={};return r&&(s.sessionId=r),o&&(s.traceId=o),n&&(s.requestId=n),a&&(s.correlationId=a),i&&(s.externalUserId=i),s}function yt(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 H(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function R(e){if(typeof e=="string"&&e.trim().length!==0)return e}function te(e){return"eventType"in e}var Tt="/api/mcp/events/v2/batch";var Ke="@waniwani/sdk",kt=new Set([401,403]),St=new Set([408,425,429,500,502,503,504]);function $e(e){return new ne(e)}var ne=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=Rt(t.apiUrl,t.endpointPath??Tt),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":Ke},body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:Et(i)}}if(kt.has(n.status))return{kind:"auth",status:n.status};if(St.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await xt(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:Ke,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(a=>[a.id,a])),o=[],i=[];for(let a of n){let s=r.get(a.eventId);if(s){if(vt(a)){o.push(s);continue}i.push(s)}}return{retryable:o,permanent:i}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let r=this.buffer.length;this.buffer.splice(0,r),this.logger.error("[WaniWani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+r)}};function vt(e){if(e.retryable===!0)return!0;let t=e.code.toLowerCase();return t.includes("timeout")||t.includes("temporary")||t.includes("unavailable")||t.includes("rate_limit")||t.includes("transient")||t.includes("server")}async function xt(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function Rt(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function Et(e){return e instanceof Error?e.message:String(e)}function Be(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?$e({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,a={async identify(s,c,p){o();let l=L({event:"user.identified",externalUserId:s,properties:c,meta:p});return i?.enqueue(l),{eventId:l.id}},async track(s){o();let c=L(s);return i?.enqueue(c),{eventId:c.id}},async flush(){o(),await i?.flush()},async shutdown(s){return o(),await i?.shutdown({timeoutMs:s?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&It(a,r.shutdownTimeoutMs),a}function It(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 V(e){let t=e,n=t?.apiUrl??"https://app.waniwani.ai",r=t?.apiKey??process.env.WANIWANI_API_KEY,o={endpointPath:t?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:t?.tracking?.flushIntervalMs??1e3,maxBatchSize:t?.tracking?.maxBatchSize??20,maxBufferSize:t?.tracking?.maxBufferSize??1e3,maxRetries:t?.tracking?.maxRetries??3,retryBaseDelayMs:t?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:t?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:t?.tracking?.shutdownTimeoutMs??2e3},i={apiUrl:n,apiKey:r,tracking:o},a=Be(i),s=Oe(i);return{...a,kb:s,_config:i}}function Ct(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 bt(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=V(t)),n}return async function(i){let a;try{a=await i.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!Array.isArray(a.events)||a.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(),c=[];for(let p of a.events){let l=Ct(p),d=await s.track(l);c.push(d.eventId)}return await s.flush(),new Response(JSON.stringify({ok:!0,accepted:c.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(s){let c=s instanceof Error?s.message:"Unknown error";return new Response(JSON.stringify({error:c}),{status:500,headers:{"Content-Type":"application/json"}})}}}function z(e,t){return t?(...n)=>console.log(`[waniwani:${e}]`,...n):()=>{}}var re=z("widget-token",!!process.env.WANIWANI_DEBUG),_t=120*1e3,Y=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-_t?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=Pt(this.config.apiUrl,"/api/mcp/widget-tokens");re("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(re("mint response:",i.status),!i.ok)return null;let a=await i.json(),s=a.data&&typeof a.data=="object"?a.data:a,c=new Date(s.expiresAt).getTime();return!s.token||Number.isNaN(c)?null:(this.cached={token:s.token,expiresAt:c},s.token)}catch(i){return re("mint failed:",i),null}}};function Pt(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}var qe="waniwani/sessionId",oe="waniwani/geoLocation",ie="waniwani/userLocation";function k(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function O(e){if(!k(e))return;let t=e._meta;return k(t)?t:void 0}function se(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 Wt(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function ae(e,t,n,r,o,i){let a=Wt(e,n.toolType),s=O(t);return console.log("[waniwani:debug] buildTrackInput meta:",JSON.stringify(s),"-> source:",b(s)),{event:"tool.called",properties:{name:e,type:a,...r??{},...i?.input!==void 0&&{input:i.input},...i?.output!==void 0&&{output:i.output}},meta:s,source:b(s),metadata:{...n.metadata??{},...o&&{clientInfo:o}}}}async function ce(e,t,n){try{await e.track(t)}catch(r){n?.(ue(r))}}async function de(e,t){try{await e.flush()}catch(n){t?.(ue(n))}}async function Le(e,t,n,r,o){if(!k(e))return;k(e._meta)||(e._meta={});let i=e._meta,a=k(i.waniwani)?i.waniwani:void 0,s={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let d=await t.getToken();d&&(s.token=d)}catch(d){o?.(ue(d))}let c=C(i);c&&(s.sessionId||(s.sessionId=c));let p=Ye(i);p!==void 0&&(s.geoLocation||(s.geoLocation=p));let l=b(O(r));l&&!s.source&&(s.source=l),i.waniwani=s}var He=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function Ve(e,t){if(!t||!k(e))return;let n=!1;for(let o of He)if(o in t){n=!0;break}if(!n)return;k(e._meta)||(e._meta={});let r=e._meta;for(let o of He)o in t&&(o in r||(r[o]=t[o]))}function ze(e,t){let n=O(t);if(!n||!k(e))return;k(e._meta)||(e._meta={});let r=e._meta,o=C(n);o&&!r[qe]&&(r[qe]=o);let i=Ye(n);i&&(r[oe]||(r[oe]=i),r[ie]||(r[ie]=i))}function Ye(e){if(!e)return;let t=e[oe]??e[ie];if(k(t)||typeof t=="string")return t}function ue(e){return e instanceof Error?e:new Error(String(e))}var Je=Symbol.for("waniwani.wrappedHandler"),G=z("mcp",!!process.env.WANIWANI_DEBUG),Ze="https://app.waniwani.ai";function Ge(e,t,n,r){let{server:o,tracker:i,opts:a,tokenCache:s,injectToken:c}=n,p=async(l,d)=>{let f=O(d)??{},g=Te(i,f,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});k(d)&&(d[Z]=g);let T=performance.now(),w=o.server?.getClientVersion?.();try{let u=await t(l,d),m=Math.round(performance.now()-T);G(`tool "${e}" handler returned in ${m}ms, running post-processing...`);let v=k(u)&&u.isError===!0;if(v){let S=se(u);console.error(`[waniwani] Tool "${e}" returned error${S?`: ${S}`:""}`)}return await ce(i,ae(e,d,a,{durationMs:m,status:v?"error":"ok",...v&&{errorMessage:se(u)??"Unknown tool error"}},w,{input:l,output:u}),a.onError),G(`tool "${e}" tracking done`),a.flushAfterToolCall&&await de(i,a.onError),ze(u,d),Ve(u,r),c&&(await Le(u,s,i._config.apiUrl??Ze,d,a.onError),G(`tool "${e}" widget config injected`)),G(`tool "${e}" post-processing complete, returning result`),u}catch(u){let m=Math.round(performance.now()-T);throw await ce(i,ae(e,d,a,{durationMs:m,status:"error",errorMessage:u instanceof Error?u.message:String(u)},w,{input:l}),a.onError),a.flushAfterToolCall&&await de(i,a.onError),u}};return p[Je]=!0,p}function Mt(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??V(),i=r.injectWidgetToken!==!1,a=o._config.apiKey?new Y({apiUrl:o._config.apiUrl??Ze,apiKey:o._config.apiKey}):null,s={server:e,tracker:o,opts:r,tokenCache:a,injectToken:i},c=e.registerTool.bind(e);n.registerTool=((...l)=>{let[d,f,g]=l;if(typeof g!="function")return c(...l);let T=typeof d=="string"&&d.trim().length>0?d:"unknown",w=k(f)&&k(f._meta)?f._meta:void 0,u=Ge(T,g,s,w);return c(d,f,u)});let p=e._registeredTools;if(k(p))for(let[l,d]of Object.entries(p)){if(!k(d))continue;let f=d.handler;if(typeof f!="function"||f[Je])continue;let g=k(d._meta)?d._meta:void 0;d.handler=Ge(l,f,s,g)}return n}export{I as END,E as START,M as StateGraph,W as WaniwaniKvStore,We as createFlow,Fe as createFlowTestHarness,Ue as createResource,ut as createTool,bt as createTrackingRoute,J as detectPlatform,Qe as isMCPApps,Xe as isOpenAI,pt as registerTools,Mt as withWaniwani};
|
|
3
|
+
${F.context}`:`ERROR: ${x}`}:F),le=Ie(pe,g.context,s,c);if(le)return le;break}}let u=r.get(s);if(!u)return{content:{status:"error",error:`No outgoing edge from node "${s}"`}};s=await P(u,c);continue}if(ye(g)){let y=g.field;if(y&&Q(N(c,y))){let u=r.get(s);if(!u)return{content:{status:"error",error:`No outgoing edge from node "${s}"`}};s=await P(u,c);continue}return{content:{status:"widget",tool:g.tool,data:g.data,description:g.description,interactive:g.interactive!==!1},flowTokenContent:{step:s,state:c,field:y,widgetId:g.tool}}}c=_(c,g);let T=r.get(s);if(!T)return{content:{status:"error",error:`No outgoing edge from node "${s}"`}};s=await P(T,c)}catch(l){return{content:{status:"error",error:l instanceof Error?l.message:String(l)},flowTokenContent:{step:s,state:c}}}}return{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"}}}var dt="@waniwani/sdk",ut="https://app.waniwani.ai",W=class{get baseUrl(){return(process.env.WANIWANI_API_URL??ut).replace(/\/$/,"")}get apiKey(){return process.env.WANIWANI_API_KEY}async get(t){if(!this.apiKey)throw new Error("[WaniWani KV] No API key configured. Set WANIWANI_API_KEY env var.");return await this.request("/api/mcp/redis/get",{key:t})??null}async set(t,n){if(!this.apiKey)throw new Error("[WaniWani KV] No API key configured. Set WANIWANI_API_KEY env var.");await this.request("/api/mcp/redis/set",{key:t,value:n})}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":dt},body:JSON.stringify(n)});if(!o.ok){let a=await o.text().catch(()=>"");throw new Error(a||`KV store API error: HTTP ${o.status}`)}return(await o.json()).data}};var U=class{store=new W;get(t){return this.store.get(t)}set(t,n){return this.store.set(t,n)}delete(t){return this.store.delete(t)}};function Ce(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 be(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,"," including relevant prior context that led to triggering it, if available."," Do NOT invent missing context."," If the user's message already contains answers to likely questions,"," extract them into `stateUpdates` as `{ field: value }` pairs."," The engine will auto-skip steps whose fields are already filled."," Only extract values the user explicitly stated \u2014 do NOT guess or invent values."];if(e.state){let n=[];for(let[r,o]of Object.entries(e.state)){let i=Re(o);if(i){let a=o.description??"",s=Object.entries(i).map(([c,p])=>{let f=Ce(p);return f?`\`${r}.${c}\` (${f})`:`\`${r}.${c}\``}).join(", ");n.push(a?`\`${r}\` (${a}): ${s}`:`\`${r}\`: ${s}`)}else{let a=Ce(o);n.push(a?`\`${r}\` (${a})`:`\`${r}\``)}}t.push(` Known fields: ${n.join(", ")}.`)}return t.push(" For grouped fields (shown as `group.subfield`), use dot-notation keys in `stateUpdates`:",' e.g. `{ "driver.name": "John", "driver.license": "ABC123" }`.',"2. The response JSON `status` field tells you what to do next:",' - `"interrupt"`: Pause and ask the user. Two forms:'," a. Single question: `{ question, field, context? }` \u2014 ask `question`, store answer in `field`."," b. Multi-question: `{ questions: [{question, field}, ...], context? }` \u2014 ask ALL questions"," in one conversational message, collect all answers."," `context` (if present) is hidden AI instructions \u2014 use to shape your response, do NOT show verbatim."," Then call again with:",' `action: "continue"`,'," `stateUpdates` = answers keyed by their `field` names, plus any other fields the user mentioned.",' - `"widget"`: The flow wants to show a UI widget. Call the tool named in the `tool`'," field, passing the `data` object as the tool's input."," Check the `interactive` field in the response:"," \u2022 `interactive: true` \u2014 The widget requires user interaction. After calling the display tool,"," STOP and WAIT for the user to interact with the widget. Do NOT call this flow tool again"," until the user has responded. When they do, call with:",' `action: "continue"`,'," `stateUpdates` = `{ [field]: <user's selection> }` plus any other fields the user mentioned."," \u2022 `interactive: false` \u2014 The widget is display-only. Call the display tool, then immediately",' call THIS flow tool again with `action: "continue"`. Do NOT wait for user interaction.',' - `"complete"`: The flow is done. Present the result to the user.',' - `"error"`: Something went wrong. Show the `error` message.',"","3. Do NOT invent state values. Only use `stateUpdates` for information the user explicitly provided.","4. Include only the fields the user actually answered in `stateUpdates` \u2014 do NOT guess missing ones."," If the user did not answer all pending questions, the engine will re-prompt for the remaining ones."," If the user mentioned values for other known fields, include those too \u2014"," they will be applied immediately and those steps will be auto-skipped."),t.join(`
|
|
4
|
+
`)}var pt={action:D.enum(["start","continue"]).describe('"start" to begin the flow, "continue" to resume after a pause (interrupt or widget)'),intent:D.string().optional().describe(`Required when action is "start". Provide a brief summary of the user's goal for this flow, including relevant prior context that led to triggering it, if available. Do not invent missing context.`),stateUpdates:D.record(D.string(),D.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 _e(e){let{config:t,nodes:n,edges:r}=e,o=be(t),i=`${t.description}
|
|
5
|
+
${o}`,a=e.store??new U,s=new Map;async function c(d,l,g,T){if(d.action==="start"){let y=typeof d.intent=="string"?d.intent.trim():void 0;if(!y)return{content:{status:"error",error:`Missing required "intent" for action "start". Include a brief summary of the user's goal for this flow and any relevant prior context that led to triggering it, if available.`}};d.intent=y;let u=r.get(E);if(!u)return{content:{status:"error",error:"No start edge"}};let m=X(d.stateUpdates??{}),v=await P(u,m);return K(v,m,n,r,s,g,T)}if(d.action==="continue"){if(!l)return{content:{status:"error",error:"No session ID available for continue action."}};let y;try{y=await a.get(l)}catch(S){let x=S instanceof Error?S.message:String(S);return{content:{status:"error",error:`Failed to load flow state (session "${l}"): ${x}`}}}if(!y)return{content:{status:"error",error:`Flow state not found for session "${l}". The flow may have expired.`}};let u=y.state,m=y.step;if(!m)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let v=_(u,X(d.stateUpdates??{}));if(y.widgetId){let S=r.get(m);if(!S)return{content:{status:"error",error:`No edge from step "${m}"`}};let x=await P(S,v);return K(x,v,n,r,s,g,T)}return K(m,v,n,r,s,g,T)}return{content:{status:"error",error:`Unknown action: "${d.action}"`}}}let p={title:t.title,description:i,inputSchema:pt,annotations:t.annotations},f=(async(d,l)=>{let g=l,T=g._meta??{},y=C(T),u=j(g),m=await c(d,y,T,u);if(y)if(m.flowTokenContent&&m.content.status!=="complete")try{await a.set(y,m.flowTokenContent)}catch(S){let x=S instanceof Error?S.message:String(S);return{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${y}"): ${x}`},null,2)}],_meta:T,isError:!0}}else m.content.status==="complete"&&await a.delete(y);return{content:[{type:"text",text:JSON.stringify(m.content,null,2)}],_meta:T,...m.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:p,handler:f,async register(d){d.registerTool(t.id,p,f)},graph:e.graph}}function Pe(e,t){let n=["flowchart TD"];n.push(` ${E}((Start))`);for(let[r]of e)n.push(` ${r}[${r}]`);n.push(` ${I}((End))`);for(let[r,o]of t)o.type==="direct"?n.push(` ${r} --> ${o.to}`):n.push(` ${r} -.-> ${r}_branch([?])`);return n.join(`
|
|
6
|
+
`)}var M=class{nodes=new Map;edges=new Map;config;constructor(t){this.config=t}addNode(t,n){if(t===E||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}graph(){return Pe(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return _e({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>Pe(n,r)})}validate(){if(!this.edges.has(E))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(E);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!==E&&!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 We(e){return new M(e)}function Me(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function Fe(e,t){let n=t?.stateStore,r=[],o=`test-session-${Math.random().toString(36).slice(2,10)}`,i={registerTool:(...p)=>{r.push(p)}};await e.register(i);let a=r[0]?.[2];if(!a)throw new Error(`Flow "${e.name}" did not register a handler`);let s={_meta:{sessionId:o}};async function c(p){return{...p,decodedState:n?await n.get(o):null}}return{async start(p,f){let d=await a({action:"start",intent:p,...f?{stateUpdates:f}:{}},s);return c(Me(d))},async continueWith(p){let f=await a({action:"continue",...p?{stateUpdates:p}:{}},s);return c(Me(f))},async lastState(){return n?n.get(o):null}}}var $="text/html+skybridge",B="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 Ne(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function Ue(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 ee(e){return{...e.openaiTemplateUri&&{"openai/outputTemplate":e.openaiTemplateUri},"openai/toolInvocation/invoking":e.invoking,"openai/toolInvocation/invoked":e.invoked,"openai/widgetAccessible":!0,"openai/resultCanProduceWidget":!0,...e.mcpTemplateUri&&{ui:{resourceUri:e.mcpTemplateUri,...e.autoHeight&&{autoHeight:!0}}},...e.mcpTemplateUri&&{"ui/resourceUri":e.mcpTemplateUri}}}function De(e){let{id:t,title:n,description:r,baseUrl:o,htmlPath:i,widgetDomain:a,prefersBorder:s=!0,autoHeight:c=!0}=e,p=e.widgetCSP??{connect_domains:[o],resource_domains:[o]};if(process.env.NODE_ENV==="development")try{let{hostname:u}=new URL(o);(u==="localhost"||u==="127.0.0.1")&&(p={...p,connect_domains:[...p.connect_domains||[],`ws://${u}:*`,`wss://${u}:*`],resource_domains:[...p.resource_domains||[],`http://${u}:*`]})}catch{}let f=`ui://widgets/apps-sdk/${t}.html`,d=`ui://widgets/ext-apps/${t}.html`,l=null,g=()=>(l||(l=Ae(o,i)),l),T=r;async function y(u){let m=await g();u.registerResource(`${t}-openai-widget`,f,{title:n,description:T,mimeType:$,_meta:{"openai/widgetDescription":T,"openai/widgetPrefersBorder":s}},async v=>({contents:[{uri:v.href,mimeType:$,text:m,_meta:Ne({description:T,prefersBorder:s,widgetDomain:a,widgetCSP:p})}]})),u.registerResource(`${t}-mcp-widget`,d,{title:n,description:T,mimeType:B,_meta:{ui:{prefersBorder:s}}},async v=>({contents:[{uri:v.href,mimeType:B,text:m,_meta:Ue({description:T,prefersBorder:s,widgetDomain:a,widgetCSP:p})}]}))}return{id:t,title:n,description:r,openaiUri:f,mcpUri:d,autoHeight:c,register:y}}function lt(e,t){let{resource:n,description:r,inputSchema:o,annotations:i,autoInjectResultText:a=!0}=e,s=e.id??n?.id,c=e.title??n?.title;if(!s)throw new Error("createTool: `id` is required when no resource is provided");if(!c)throw new Error("createTool: `title` is required when no resource is provided");let p=n?ee({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:s,title:c,description:r,async register(f){f.registerTool(s,{title:c,description:r,inputSchema:o,annotations:i,...p&&{_meta:p}},(async(d,l)=>{let g=l,T=g._meta??{},y=j(g),u=await t(d,{extra:{_meta:T},waniwani:y});return n&&u.data?{content:[{type:"text",text:u.text}],structuredContent:u.data,_meta:{...p,...T,...a===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:u.text}],...u.data?{structuredContent:u.data}:{},...a===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function ft(e,t){await Promise.all(t.map(n=>n.register(e)))}var q=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var gt="@waniwani/sdk";function Oe(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,a,s){let c=r(),p=`${t.replace(/\/$/,"")}${a}`,f={Authorization:`Bearer ${c}`,"X-WaniWani-SDK":gt},d={method:i,headers:f};s!==void 0&&(f["Content-Type"]="application/json",d.body=JSON.stringify(s));let l=await fetch(p,d);if(!l.ok){let T=await l.text().catch(()=>"");throw new q(T||`KB API error: HTTP ${l.status}`,l.status)}return(await l.json()).data}return{async ingest(i){return o("POST","/api/mcp/kb/ingest",{files:i})},async search(i,a){return o("POST","/api/mcp/kb/search",{query:i,...a})},async sources(){return o("GET","/api/mcp/kb/sources")}}}var mt="@waniwani/sdk";function L(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??je,o=yt(e),i=H(e.meta),a=H(e.metadata),s=Tt(e,i),c=R(e.eventId)??r(),p=kt(e.timestamp,n),f=R(e.source)??b(i)??t.source??mt,d=te(e)?{...e}:void 0,l={...a};return Object.keys(i).length>0&&(l.meta=i),d&&(l.rawLegacy=d),{id:c,type:"mcp.event",name:o,source:f,timestamp:p,correlation:s,properties:wt(e,o),metadata:l,rawLegacy:d}}function je(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function wt(e,t){if(!te(e))return H(e.properties);let n=ht(e,t),r=H(e.properties);return{...n,...r}}function ht(e,t){switch(t){case"tool.called":{let n={};return R(e.toolName)&&(n.name=e.toolName),R(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),R(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return R(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),R(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function yt(e){return te(e)?e.eventType:e.event}function Tt(e,t){let n=R(e.requestId)??ke(t),r=R(e.sessionId)??C(t),o=R(e.traceId)??Se(t),i=R(e.externalUserId)??ve(t),a=R(e.correlationId)??xe(t)??n,s={};return r&&(s.sessionId=r),o&&(s.traceId=o),n&&(s.requestId=n),a&&(s.correlationId=a),i&&(s.externalUserId=i),s}function kt(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 H(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function R(e){if(typeof e=="string"&&e.trim().length!==0)return e}function te(e){return"eventType"in e}var St="/api/mcp/events/v2/batch";var Ke="@waniwani/sdk",vt=new Set([401,403]),xt=new Set([408,425,429,500,502,503,504]);function $e(e){return new ne(e)}var ne=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=It(t.apiUrl,t.endpointPath??St),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":Ke},body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:Ct(i)}}if(vt.has(n.status))return{kind:"auth",status:n.status};if(xt.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await Et(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:Ke,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(a=>[a.id,a])),o=[],i=[];for(let a of n){let s=r.get(a.eventId);if(s){if(Rt(a)){o.push(s);continue}i.push(s)}}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 Rt(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 Et(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function It(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function Ct(e){return e instanceof Error?e.message:String(e)}function Be(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?$e({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,a={async identify(s,c,p){o();let f=L({event:"user.identified",externalUserId:s,properties:c,meta:p});return i?.enqueue(f),{eventId:f.id}},async track(s){o();let c=L(s);return i?.enqueue(c),{eventId:c.id}},async flush(){o(),await i?.flush()},async shutdown(s){return o(),await i?.shutdown({timeoutMs:s?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&bt(a,r.shutdownTimeoutMs),a}function bt(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 V(e){let t=e,n=t?.apiUrl??"https://app.waniwani.ai",r=t?.apiKey??process.env.WANIWANI_API_KEY,o={endpointPath:t?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:t?.tracking?.flushIntervalMs??1e3,maxBatchSize:t?.tracking?.maxBatchSize??20,maxBufferSize:t?.tracking?.maxBufferSize??1e3,maxRetries:t?.tracking?.maxRetries??3,retryBaseDelayMs:t?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:t?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:t?.tracking?.shutdownTimeoutMs??2e3},i={apiUrl:n,apiKey:r,tracking:o},a=Be(i),s=Oe(i);return{...a,kb:s,_config:i}}function _t(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 Pt(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=V(t)),n}return async function(i){let a;try{a=await i.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!Array.isArray(a.events)||a.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(),c=[];for(let p of a.events){let f=_t(p),d=await s.track(f);c.push(d.eventId)}return await s.flush(),new Response(JSON.stringify({ok:!0,accepted:c.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(s){let c=s instanceof Error?s.message:"Unknown error";return new Response(JSON.stringify({error:c}),{status:500,headers:{"Content-Type":"application/json"}})}}}function z(e,t){return t?(...n)=>console.log(`[waniwani:${e}]`,...n):()=>{}}var re=z("widget-token",!!process.env.WANIWANI_DEBUG),Wt=120*1e3,Y=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-Wt?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=Mt(this.config.apiUrl,"/api/mcp/widget-tokens");re("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(re("mint response:",i.status),!i.ok)return null;let a=await i.json(),s=a.data&&typeof a.data=="object"?a.data:a,c=new Date(s.expiresAt).getTime();return!s.token||Number.isNaN(c)?null:(this.cached={token:s.token,expiresAt:c},s.token)}catch(i){return re("mint failed:",i),null}}};function Mt(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}var qe="waniwani/sessionId",oe="waniwani/geoLocation",ie="waniwani/userLocation";function k(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function O(e){if(!k(e))return;let t=e._meta;return k(t)?t:void 0}function se(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 Ft(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function ae(e,t,n,r,o,i){let a=Ft(e,n.toolType),s=O(t);return console.log("[waniwani:debug] buildTrackInput meta:",JSON.stringify(s),"-> source:",b(s)),{event:"tool.called",properties:{name:e,type:a,...r??{},...i?.input!==void 0&&{input:i.input},...i?.output!==void 0&&{output:i.output}},meta:s,source:b(s),metadata:{...n.metadata??{},...o&&{clientInfo:o}}}}async function ce(e,t,n){try{await e.track(t)}catch(r){n?.(ue(r))}}async function de(e,t){try{await e.flush()}catch(n){t?.(ue(n))}}async function Le(e,t,n,r,o){if(!k(e))return;k(e._meta)||(e._meta={});let i=e._meta,a=k(i.waniwani)?i.waniwani:void 0,s={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let d=await t.getToken();d&&(s.token=d)}catch(d){o?.(ue(d))}let c=C(i);c&&(s.sessionId||(s.sessionId=c));let p=Ye(i);p!==void 0&&(s.geoLocation||(s.geoLocation=p));let f=b(O(r));f&&!s.source&&(s.source=f),i.waniwani=s}var He=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function Ve(e,t){if(!t||!k(e))return;let n=!1;for(let o of He)if(o in t){n=!0;break}if(!n)return;k(e._meta)||(e._meta={});let r=e._meta;for(let o of He)o in t&&(o in r||(r[o]=t[o]))}function ze(e,t){let n=O(t);if(!n||!k(e))return;k(e._meta)||(e._meta={});let r=e._meta,o=C(n);o&&!r[qe]&&(r[qe]=o);let i=Ye(n);i&&(r[oe]||(r[oe]=i),r[ie]||(r[ie]=i))}function Ye(e){if(!e)return;let t=e[oe]??e[ie];if(k(t)||typeof t=="string")return t}function ue(e){return e instanceof Error?e:new Error(String(e))}function Ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Je(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(Ge(e.requestInfo)){let t=e.requestInfo.headers;if(Ge(t)){let n=t["mcp-session-id"];if(typeof n=="string"&&n)return n}}}var Xe=Symbol.for("waniwani.wrappedHandler"),G=z("mcp",!!process.env.WANIWANI_DEBUG),Qe="https://app.waniwani.ai";function Ze(e,t,n,r){let{server:o,tracker:i,opts:a,tokenCache:s,injectToken:c}=n,p=async(f,d)=>{let l=O(d)??{};if(!C(l)&&k(d)){let u=Je(d);u&&(l["waniwani/sessionId"]=u,d._meta=l)}let g=Te(i,l,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});k(d)&&(d[Z]=g);let T=performance.now(),y=o.server?.getClientVersion?.();try{let u=await t(f,d),m=Math.round(performance.now()-T);G(`tool "${e}" handler returned in ${m}ms, running post-processing...`);let v=k(u)&&u.isError===!0;if(v){let S=se(u);console.error(`[waniwani] Tool "${e}" returned error${S?`: ${S}`:""}`)}return await ce(i,ae(e,d,a,{durationMs:m,status:v?"error":"ok",...v&&{errorMessage:se(u)??"Unknown tool error"}},y,{input:f,output:u}),a.onError),G(`tool "${e}" tracking done`),a.flushAfterToolCall&&await de(i,a.onError),ze(u,d),Ve(u,r),c&&(await Le(u,s,i._config.apiUrl??Qe,d,a.onError),G(`tool "${e}" widget config injected`)),G(`tool "${e}" post-processing complete, returning result`),u}catch(u){let m=Math.round(performance.now()-T);throw await ce(i,ae(e,d,a,{durationMs:m,status:"error",errorMessage:u instanceof Error?u.message:String(u)},y,{input:f}),a.onError),a.flushAfterToolCall&&await de(i,a.onError),u}};return p[Xe]=!0,p}function At(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??V(),i=r.injectWidgetToken!==!1,a=o._config.apiKey?new Y({apiUrl:o._config.apiUrl??Qe,apiKey:o._config.apiKey}):null,s={server:e,tracker:o,opts:r,tokenCache:a,injectToken:i},c=e.registerTool.bind(e);n.registerTool=((...f)=>{let[d,l,g]=f;if(typeof g!="function")return c(...f);let T=typeof d=="string"&&d.trim().length>0?d:"unknown",y=k(l)&&k(l._meta)?l._meta:void 0,u=Ze(T,g,s,y);return c(d,l,u)});let p=e._registeredTools;if(k(p))for(let[f,d]of Object.entries(p)){if(!k(d))continue;let l=d.handler;if(typeof l!="function"||l[Xe])continue;let g=k(d._meta)?d._meta:void 0;d.handler=Ze(f,l,s,g)}return n}export{I as END,E as START,M as StateGraph,W as WaniwaniKvStore,We as createFlow,Fe as createFlowTestHarness,De as createResource,lt as createTool,Pt as createTrackingRoute,J as detectPlatform,tt as isMCPApps,et as isOpenAI,ft as registerTools,At as withWaniwani};
|
|
7
7
|
//# sourceMappingURL=index.js.map
|