@waniwani/sdk 0.5.2 → 0.5.3-beta.0

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/index.d.ts CHANGED
@@ -254,9 +254,10 @@ interface WaniWaniProjectConfig {
254
254
  /**
255
255
  * Define and register a WaniWani project configuration.
256
256
  *
257
- * Calling this stores the config in a module-level variable so that
257
+ * Calling this stores the config on `globalThis` so that
258
258
  * `waniwani()` and `withWaniwani()` can read from it automatically
259
- * when no explicit config is passed.
259
+ * when no explicit config is passed — even across different SDK
260
+ * entry points (`@waniwani/sdk`, `@waniwani/sdk/mcp`, etc.).
260
261
  *
261
262
  * The config is also returned for direct use.
262
263
  */
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var m=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var k;function U(e){return k=e,e}function S(){return k}var V="@waniwani/sdk";function w(e){let{apiUrl:t,apiKey:n}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function i(s,a,o){let d=r(),g=`${t.replace(/\/$/,"")}${a}`,f={Authorization:`Bearer ${d}`,"X-WaniWani-SDK":V},h={method:s,headers:f};o!==void 0&&(f["Content-Type"]="application/json",h.body=JSON.stringify(o));let u=await fetch(g,h);if(!u.ok){let W=await u.text().catch(()=>"");throw new m(W||`KB API error: HTTP ${u.status}`,u.status)}return(await u.json()).data}return{async ingest(s){return i("POST","/api/mcp/kb/ingest",{files:s})},async search(s,a){return i("POST","/api/mcp/kb/search",{query:s,...a})},async sources(){return i("GET","/api/mcp/kb/sources")}}}function y(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var F=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","anthropic/sessionId"],j=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],K=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],L=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],O=["correlationId","openai/requestId"];function b(e){return e?y(e,F):void 0}function R(e){return e?y(e,j):void 0}function x(e){return e?y(e,K):void 0}function M(e){return e?y(e,L):void 0}function _(e){return e?y(e,O):void 0}var q=[{key:"waniwani/sessionId",source:"chatbar"},{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"},{key:"anthropic/sessionId",source:"claude"}];function C(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 q){let i=e[n];if(typeof i=="string"&&i.length>0)return r}}var N="@waniwani/sdk";function T(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??D,i=$(e),s=v(e.meta),a=v(e.metadata),o=H(e,s),d=c(e.eventId)??r(),g=X(e.timestamp,n),f=c(e.source)??C(s)??t.source??N,h=E(e)?{...e}:void 0,u={...a};return Object.keys(s).length>0&&(u.meta=s),h&&(u.rawLegacy=h),{id:d,type:"mcp.event",name:i,source:f,timestamp:g,correlation:o,properties:z(e,i),metadata:u,rawLegacy:h}}function D(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function z(e,t){if(!E(e))return v(e.properties);let n=Y(e,t),r=v(e.properties);return{...n,...r}}function Y(e,t){switch(t){case"tool.called":{let n={};return c(e.toolName)&&(n.name=e.toolName),c(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),c(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return c(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),c(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function $(e){return E(e)?e.eventType:e.event}function H(e,t){let n=c(e.requestId)??R(t),r=c(e.sessionId)??b(t),i=c(e.traceId)??x(t),s=c(e.externalUserId)??M(t),a=c(e.correlationId)??_(t)??n,o={};return r&&(o.sessionId=r),i&&(o.traceId=i),n&&(o.requestId=n),a&&(o.correlationId=a),s&&(o.externalUserId=s),o}function X(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 v(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function c(e){if(typeof e=="string"&&e.trim().length!==0)return e}function E(e){return"eventType"in e}var G="/api/mcp/events/v2/batch";var A="@waniwani/sdk",J=new Set([401,403]),Z=new Set([408,425,429,500,502,503,504]);function B(e){return new I(e)}var I=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=te(t.apiUrl,t.endpointPath??G),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 i=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(n).then(()=>i)])===i?(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 i=await this.sendBatchOnce(r);switch(this.inFlightCount=0,i.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(i.status,r.length);return;case"permanent":this.logger.error("[WaniWani] Dropping %d event(s) after permanent failure: %s",r.length,i.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d event(s) after retry exhaustion: %s",r.length,i.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(i.permanent.length>0&&this.logger.error("[WaniWani] Dropping %d event(s) rejected as permanent",i.permanent.length),i.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d retryable event(s) after retry exhaustion",i.retryable.length);return}r=i.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":A},body:JSON.stringify(this.makeBatchRequest(t))})}catch(s){return{kind:"retryable",reason:ne(s)}}if(J.has(n.status))return{kind:"auth",status:n.status};if(Z.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await ee(n);if(!r?.rejected||r.rejected.length===0)return{kind:"success"};let i=this.classifyRejectedEvents(t,r.rejected);return i.retryable.length===0&&i.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:i.retryable,permanent:i.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:A,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(a=>[a.id,a])),i=[],s=[];for(let a of n){let o=r.get(a.eventId);if(o){if(Q(a)){i.push(o);continue}s.push(o)}}return{retryable:i,permanent:s}}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 Q(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 ee(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function te(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function ne(e){return e instanceof Error?e.message:String(e)}function P(e){let{apiUrl:t,apiKey:n,tracking:r}=e;function i(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}let s=n?B({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(o,d,g){i();let f=T({event:"user.identified",externalUserId:o,properties:d,meta:g});return s?.enqueue(f),{eventId:f.id}},async track(o){i();let d=T(o);return s?.enqueue(d),{eventId:d.id}},async flush(){i(),await s?.flush()},async shutdown(o){return i(),await s?.shutdown({timeoutMs:o?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return s&&re(a,r.shutdownTimeoutMs),a}function re(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 ie(e){let t=e??S(),n=t?.apiUrl??"https://app.waniwani.ai",r=t?.apiKey??process.env.WANIWANI_API_KEY,i={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},s={apiUrl:n,apiKey:r,tracking:i},a=P(s),o=w(s);return{...a,kb:o,_config:s}}export{m as WaniWaniError,U as defineConfig,ie as waniwani};
1
+ var m=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var k="__waniwani_config__";function U(e){return globalThis[k]=e,e}function S(){return globalThis[k]}var V="@waniwani/sdk";function w(e){let{apiUrl:t,apiKey:n}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function i(s,a,o){let d=r(),g=`${t.replace(/\/$/,"")}${a}`,f={Authorization:`Bearer ${d}`,"X-WaniWani-SDK":V},h={method:s,headers:f};o!==void 0&&(f["Content-Type"]="application/json",h.body=JSON.stringify(o));let u=await fetch(g,h);if(!u.ok){let W=await u.text().catch(()=>"");throw new m(W||`KB API error: HTTP ${u.status}`,u.status)}return(await u.json()).data}return{async ingest(s){return i("POST","/api/mcp/kb/ingest",{files:s})},async search(s,a){return i("POST","/api/mcp/kb/search",{query:s,...a})},async sources(){return i("GET","/api/mcp/kb/sources")}}}function y(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var F=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","anthropic/sessionId"],j=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],L=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],K=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],O=["correlationId","openai/requestId"];function b(e){return e?y(e,F):void 0}function R(e){return e?y(e,j):void 0}function x(e){return e?y(e,L):void 0}function _(e){return e?y(e,K):void 0}function M(e){return e?y(e,O):void 0}var q=[{key:"waniwani/sessionId",source:"chatbar"},{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"},{key:"anthropic/sessionId",source:"claude"}];function C(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 q){let i=e[n];if(typeof i=="string"&&i.length>0)return r}}var N="@waniwani/sdk";function T(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??D,i=$(e),s=v(e.meta),a=v(e.metadata),o=H(e,s),d=c(e.eventId)??r(),g=X(e.timestamp,n),f=c(e.source)??C(s)??t.source??N,h=E(e)?{...e}:void 0,u={...a};return Object.keys(s).length>0&&(u.meta=s),h&&(u.rawLegacy=h),{id:d,type:"mcp.event",name:i,source:f,timestamp:g,correlation:o,properties:z(e,i),metadata:u,rawLegacy:h}}function D(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function z(e,t){if(!E(e))return v(e.properties);let n=Y(e,t),r=v(e.properties);return{...n,...r}}function Y(e,t){switch(t){case"tool.called":{let n={};return c(e.toolName)&&(n.name=e.toolName),c(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),c(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return c(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),c(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function $(e){return E(e)?e.eventType:e.event}function H(e,t){let n=c(e.requestId)??R(t),r=c(e.sessionId)??b(t),i=c(e.traceId)??x(t),s=c(e.externalUserId)??_(t),a=c(e.correlationId)??M(t)??n,o={};return r&&(o.sessionId=r),i&&(o.traceId=i),n&&(o.requestId=n),a&&(o.correlationId=a),s&&(o.externalUserId=s),o}function X(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 v(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function c(e){if(typeof e=="string"&&e.trim().length!==0)return e}function E(e){return"eventType"in e}var G="/api/mcp/events/v2/batch";var A="@waniwani/sdk",J=new Set([401,403]),Z=new Set([408,425,429,500,502,503,504]);function B(e){return new I(e)}var I=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=te(t.apiUrl,t.endpointPath??G),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 i=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(n).then(()=>i)])===i?(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 i=await this.sendBatchOnce(r);switch(this.inFlightCount=0,i.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(i.status,r.length);return;case"permanent":this.logger.error("[WaniWani] Dropping %d event(s) after permanent failure: %s",r.length,i.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d event(s) after retry exhaustion: %s",r.length,i.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(i.permanent.length>0&&this.logger.error("[WaniWani] Dropping %d event(s) rejected as permanent",i.permanent.length),i.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d retryable event(s) after retry exhaustion",i.retryable.length);return}r=i.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":A},body:JSON.stringify(this.makeBatchRequest(t))})}catch(s){return{kind:"retryable",reason:ne(s)}}if(J.has(n.status))return{kind:"auth",status:n.status};if(Z.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await ee(n);if(!r?.rejected||r.rejected.length===0)return{kind:"success"};let i=this.classifyRejectedEvents(t,r.rejected);return i.retryable.length===0&&i.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:i.retryable,permanent:i.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:A,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(a=>[a.id,a])),i=[],s=[];for(let a of n){let o=r.get(a.eventId);if(o){if(Q(a)){i.push(o);continue}s.push(o)}}return{retryable:i,permanent:s}}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 Q(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 ee(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function te(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function ne(e){return e instanceof Error?e.message:String(e)}function P(e){let{apiUrl:t,apiKey:n,tracking:r}=e;function i(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}let s=n?B({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(o,d,g){i();let f=T({event:"user.identified",externalUserId:o,properties:d,meta:g});return s?.enqueue(f),{eventId:f.id}},async track(o){i();let d=T(o);return s?.enqueue(d),{eventId:d.id}},async flush(){i(),await s?.flush()},async shutdown(o){return i(),await s?.shutdown({timeoutMs:o?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return s&&re(a,r.shutdownTimeoutMs),a}function re(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 ie(e){let t=e??S(),n=t?.apiUrl??"https://app.waniwani.ai",r=t?.apiKey??process.env.WANIWANI_API_KEY,i={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},s={apiUrl:n,apiKey:r,tracking:i},a=P(s),o=w(s);return{...a,kb:o,_config:s}}export{m as WaniWaniError,U as defineConfig,ie as waniwani};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/error.ts","../src/project-config.ts","../src/kb/client.ts","../src/mcp/server/utils.ts","../src/tracking/mapper.ts","../src/tracking/transport.ts","../src/tracking/index.ts","../src/waniwani.ts"],"sourcesContent":["// WaniWani SDK - Errors\n\nexport class WaniWaniError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic status: number,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"WaniWaniError\";\n\t}\n}\n","import type { TrackingConfig } from \"./tracking/@types.js\";\n\n/**\n * Project-level configuration for WaniWani MCP projects.\n *\n * This is the single source of truth for both CLI tools (`waniwani eval`,\n * `waniwani embed`, etc.) and the runtime SDK client (`waniwani()`).\n *\n * Create a `waniwani.config.ts` at the project root:\n * ```ts\n * import { defineConfig } from \"@waniwani/sdk\";\n *\n * export default defineConfig({\n * apiKey: process.env.WANIWANI_API_KEY,\n * evals: {\n * mcpServerUrl: \"http://localhost:3001\",\n * },\n * });\n * ```\n *\n * Then import it as a side-effect to register the config globally:\n * ```ts\n * import \"./waniwani.config\";\n * import { waniwani } from \"@waniwani/sdk\";\n *\n * const wani = waniwani(); // picks up config from defineConfig\n * ```\n */\nexport interface WaniWaniProjectConfig {\n\t/**\n\t * Your MCP environment API key.\n\t * Defaults to `process.env.WANIWANI_API_KEY` if not provided.\n\t */\n\tapiKey?: string;\n\t/**\n\t * The base URL of the WaniWani API.\n\t * Defaults to `https://app.waniwani.ai`.\n\t */\n\tapiUrl?: string;\n\t/** Tracking transport behavior. */\n\ttracking?: TrackingConfig;\n\tevals?: {\n\t\t/** Path to the evals directory (relative to project root).\n\t\t *\n\t\t * @default ./evals */\n\t\tdir?: string;\n\t\t/** MCP server URL to test against. */\n\t\tmcpServerUrl: string;\n\t};\n\tknowledgeBase?: {\n\t\t/** Path to the knowledge base directory (relative to project root).\n\t\t *\n\t\t * @default ./knowledge-base\n\t\t */\n\t\tdir?: string;\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Global singleton\n// ---------------------------------------------------------------------------\n\nlet _globalConfig: WaniWaniProjectConfig | undefined;\n\n/**\n * Define and register a WaniWani project configuration.\n *\n * Calling this stores the config in a module-level variable so that\n * `waniwani()` and `withWaniwani()` can read from it automatically\n * when no explicit config is passed.\n *\n * The config is also returned for direct use.\n */\nexport function defineConfig(\n\tconfig: WaniWaniProjectConfig,\n): WaniWaniProjectConfig {\n\t_globalConfig = config;\n\treturn config;\n}\n\n/**\n * Retrieve the globally registered config (set by `defineConfig`).\n * Returns `undefined` if `defineConfig` has not been called.\n * @internal\n */\nexport function getGlobalConfig(): WaniWaniProjectConfig | undefined {\n\treturn _globalConfig;\n}\n","// KB Client — thin HTTP wrapper for knowledge base API\n\nimport { WaniWaniError } from \"../error.js\";\nimport type { InternalConfig } from \"../types.js\";\nimport type {\n\tKbClient,\n\tKbIngestFile,\n\tKbIngestResult,\n\tKbSearchOptions,\n\tKbSource,\n\tSearchResult,\n} from \"./types.js\";\n\nconst SDK_NAME = \"@waniwani/sdk\";\n\nexport function createKbClient(config: InternalConfig): KbClient {\n\tconst { apiUrl, apiKey } = config;\n\n\tfunction requireApiKey(): string {\n\t\tif (!apiKey) {\n\t\t\tthrow new Error(\"WANIWANI_API_KEY is not set\");\n\t\t}\n\t\treturn apiKey;\n\t}\n\n\tasync function request<T>(\n\t\tmethod: \"GET\" | \"POST\",\n\t\tpath: string,\n\t\tbody?: unknown,\n\t): Promise<T> {\n\t\tconst key = requireApiKey();\n\t\tconst url = `${apiUrl.replace(/\\/$/, \"\")}${path}`;\n\n\t\tconst headers: Record<string, string> = {\n\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\"X-WaniWani-SDK\": SDK_NAME,\n\t\t};\n\n\t\tconst init: RequestInit = { method, headers };\n\n\t\tif (body !== undefined) {\n\t\t\theaders[\"Content-Type\"] = \"application/json\";\n\t\t\tinit.body = JSON.stringify(body);\n\t\t}\n\n\t\tconst response = await fetch(url, init);\n\n\t\tif (!response.ok) {\n\t\t\tconst text = await response.text().catch(() => \"\");\n\t\t\tthrow new WaniWaniError(\n\t\t\t\ttext || `KB API error: HTTP ${response.status}`,\n\t\t\t\tresponse.status,\n\t\t\t);\n\t\t}\n\n\t\tconst json = (await response.json()) as { data: T };\n\t\treturn json.data;\n\t}\n\n\treturn {\n\t\tasync ingest(files: KbIngestFile[]): Promise<KbIngestResult> {\n\t\t\treturn request<KbIngestResult>(\"POST\", \"/api/mcp/kb/ingest\", {\n\t\t\t\tfiles,\n\t\t\t});\n\t\t},\n\n\t\tasync search(\n\t\t\tquery: string,\n\t\t\toptions?: KbSearchOptions,\n\t\t): Promise<SearchResult[]> {\n\t\t\treturn request<SearchResult[]>(\"POST\", \"/api/mcp/kb/search\", {\n\t\t\t\tquery,\n\t\t\t\t...options,\n\t\t\t});\n\t\t},\n\n\t\tasync sources(): Promise<KbSource[]> {\n\t\t\treturn request<KbSource[]>(\"GET\", \"/api/mcp/kb/sources\");\n\t\t},\n\t};\n}\n","// ============================================================================\n// Meta key extraction helpers\n// ============================================================================\n\n/** Pick the first non-empty string value from `meta` matching the given keys. */\nfunction pickFirst(\n\tmeta: Record<string, unknown>,\n\tkeys: readonly string[],\n): string | undefined {\n\tfor (const key of keys) {\n\t\tconst value = meta[key];\n\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\treturn value;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n// --- Key lists (ordered by priority) ---\n\nconst SESSION_ID_KEYS = [\n\t\"waniwani/sessionId\",\n\t\"openai/sessionId\",\n\t\"openai/session\",\n\t\"sessionId\",\n\t\"conversationId\",\n\t\"anthropic/sessionId\",\n] as const;\n\nconst REQUEST_ID_KEYS = [\n\t\"waniwani/requestId\",\n\t\"openai/requestId\",\n\t\"requestId\",\n\t\"mcp/requestId\",\n] as const;\n\nconst TRACE_ID_KEYS = [\n\t\"waniwani/traceId\",\n\t\"openai/traceId\",\n\t\"traceId\",\n\t\"mcp/traceId\",\n\t\"openai/requestId\",\n\t\"requestId\",\n] as const;\n\nconst EXTERNAL_USER_ID_KEYS = [\n\t\"waniwani/userId\",\n\t\"openai/userId\",\n\t\"externalUserId\",\n\t\"userId\",\n\t\"actorId\",\n] as const;\n\nconst CORRELATION_ID_KEYS = [\"correlationId\", \"openai/requestId\"] as const;\n\n// --- Extractors ---\n\nexport function extractSessionId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, SESSION_ID_KEYS) : undefined;\n}\n\nexport function extractRequestId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, REQUEST_ID_KEYS) : undefined;\n}\n\nexport function extractTraceId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, TRACE_ID_KEYS) : undefined;\n}\n\nexport function extractExternalUserId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, EXTERNAL_USER_ID_KEYS) : undefined;\n}\n\nexport function extractCorrelationId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, CORRELATION_ID_KEYS) : undefined;\n}\n\nconst SOURCE_SESSION_KEYS = [\n\t{ key: \"waniwani/sessionId\", source: \"chatbar\" },\n\t{ key: \"openai/sessionId\", source: \"chatgpt\" },\n\t{ key: \"openai/session\", source: \"chatgpt\" },\n\t{ key: \"anthropic/sessionId\", source: \"claude\" },\n] as const;\n\nexport function extractSource(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\tif (!meta) {\n\t\treturn undefined;\n\t}\n\t// Explicit source set by the caller (e.g. chatbar name)\n\tconst explicit = meta[\"waniwani/source\"];\n\tif (typeof explicit === \"string\" && explicit.length > 0) {\n\t\treturn explicit;\n\t}\n\t// Derive from session ID key\n\tfor (const { key, source } of SOURCE_SESSION_KEYS) {\n\t\tconst value = meta[key];\n\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\treturn source;\n\t\t}\n\t}\n\treturn undefined;\n}\n","import {\n\textractCorrelationId,\n\textractExternalUserId,\n\textractRequestId,\n\textractSessionId,\n\textractSource,\n\textractTraceId,\n} from \"../mcp/server/utils.js\";\nimport type { EventType, LegacyTrackEvent, TrackInput } from \"./@types.js\";\nimport type { V2CorrelationIds, V2EventEnvelope } from \"./v2-types.js\";\n\nconst DEFAULT_SOURCE = \"@waniwani/sdk\";\n\nexport interface MapTrackEventOptions {\n\tnow?: () => Date;\n\tgenerateId?: () => string;\n\tsource?: string;\n}\n\nexport function mapTrackEventToV2(\n\tinput: TrackInput,\n\toptions: MapTrackEventOptions = {},\n): V2EventEnvelope {\n\tconst now = options.now ?? (() => new Date());\n\tconst generateId = options.generateId ?? createEventId;\n\tconst eventName = resolveEventName(input);\n\tconst meta = toRecord(input.meta);\n\tconst metadata = toRecord(input.metadata);\n\tconst correlation = resolveCorrelationIds(input, meta);\n\tconst eventId = takeNonEmptyString(input.eventId) ?? generateId();\n\tconst timestamp = normalizeTimestamp(input.timestamp, now);\n\tconst source =\n\t\ttakeNonEmptyString(input.source) ??\n\t\textractSource(meta) ??\n\t\toptions.source ??\n\t\tDEFAULT_SOURCE;\n\tconst rawLegacy = isLegacyTrackEvent(input) ? { ...input } : undefined;\n\n\tconst mappedMetadata: Record<string, unknown> = {\n\t\t...metadata,\n\t};\n\tif (Object.keys(meta).length > 0) {\n\t\tmappedMetadata.meta = meta;\n\t}\n\tif (rawLegacy) {\n\t\tmappedMetadata.rawLegacy = rawLegacy;\n\t}\n\n\treturn {\n\t\tid: eventId,\n\t\ttype: \"mcp.event\",\n\t\tname: eventName,\n\t\tsource,\n\t\ttimestamp,\n\t\tcorrelation,\n\t\tproperties: mapProperties(input, eventName),\n\t\tmetadata: mappedMetadata,\n\t\trawLegacy,\n\t};\n}\n\nexport function createEventId(): string {\n\tif (\n\t\ttypeof crypto !== \"undefined\" &&\n\t\ttypeof crypto.randomUUID === \"function\"\n\t) {\n\t\treturn `evt_${crypto.randomUUID()}`;\n\t}\n\n\treturn `evt_${Math.random().toString(36).slice(2, 10)}_${Date.now().toString(36)}`;\n}\n\nfunction mapProperties(\n\tinput: TrackInput,\n\teventName: EventType,\n): Record<string, unknown> {\n\tif (!isLegacyTrackEvent(input)) {\n\t\treturn toRecord(input.properties);\n\t}\n\n\tconst legacyProperties = mapLegacyProperties(input, eventName);\n\tconst explicitProperties = toRecord(input.properties);\n\treturn {\n\t\t...legacyProperties,\n\t\t...explicitProperties,\n\t};\n}\n\nfunction mapLegacyProperties(\n\tinput: LegacyTrackEvent,\n\teventName: EventType,\n): Record<string, unknown> {\n\tswitch (eventName) {\n\t\tcase \"tool.called\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (takeNonEmptyString(input.toolName)) {\n\t\t\t\tproperties.name = input.toolName;\n\t\t\t}\n\t\t\tif (takeNonEmptyString(input.toolType)) {\n\t\t\t\tproperties.type = input.toolType;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tcase \"quote.succeeded\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (typeof input.quoteAmount === \"number\") {\n\t\t\t\tproperties.amount = input.quoteAmount;\n\t\t\t}\n\t\t\tif (takeNonEmptyString(input.quoteCurrency)) {\n\t\t\t\tproperties.currency = input.quoteCurrency;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tcase \"link.clicked\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (takeNonEmptyString(input.linkUrl)) {\n\t\t\t\tproperties.url = input.linkUrl;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tcase \"purchase.completed\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (typeof input.purchaseAmount === \"number\") {\n\t\t\t\tproperties.amount = input.purchaseAmount;\n\t\t\t}\n\t\t\tif (takeNonEmptyString(input.purchaseCurrency)) {\n\t\t\t\tproperties.currency = input.purchaseCurrency;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tdefault:\n\t\t\treturn {};\n\t}\n}\n\nfunction resolveEventName(input: TrackInput): EventType {\n\tif (isLegacyTrackEvent(input)) {\n\t\treturn input.eventType;\n\t}\n\treturn input.event;\n}\n\nfunction resolveCorrelationIds(\n\tinput: TrackInput,\n\tmeta: Record<string, unknown>,\n): V2CorrelationIds {\n\tconst requestId =\n\t\ttakeNonEmptyString(input.requestId) ?? extractRequestId(meta);\n\n\tconst sessionId =\n\t\ttakeNonEmptyString(input.sessionId) ?? extractSessionId(meta);\n\n\tconst traceId = takeNonEmptyString(input.traceId) ?? extractTraceId(meta);\n\n\tconst externalUserId =\n\t\ttakeNonEmptyString(input.externalUserId) ?? extractExternalUserId(meta);\n\n\tconst correlationId =\n\t\ttakeNonEmptyString(input.correlationId) ??\n\t\textractCorrelationId(meta) ??\n\t\trequestId;\n\n\tconst correlation: V2CorrelationIds = {};\n\tif (sessionId) {\n\t\tcorrelation.sessionId = sessionId;\n\t}\n\tif (traceId) {\n\t\tcorrelation.traceId = traceId;\n\t}\n\tif (requestId) {\n\t\tcorrelation.requestId = requestId;\n\t}\n\tif (correlationId) {\n\t\tcorrelation.correlationId = correlationId;\n\t}\n\tif (externalUserId) {\n\t\tcorrelation.externalUserId = externalUserId;\n\t}\n\treturn correlation;\n}\n\nfunction normalizeTimestamp(\n\tinput: string | Date | undefined,\n\tnow: () => Date,\n): string {\n\tif (input instanceof Date) {\n\t\treturn input.toISOString();\n\t}\n\tif (typeof input === \"string\") {\n\t\tconst date = new Date(input);\n\t\tif (!Number.isNaN(date.getTime())) {\n\t\t\treturn date.toISOString();\n\t\t}\n\t}\n\treturn now().toISOString();\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\treturn {};\n\t}\n\treturn value as Record<string, unknown>;\n}\n\nfunction takeNonEmptyString(value: unknown): string | undefined {\n\tif (typeof value !== \"string\") {\n\t\treturn undefined;\n\t}\n\tif (value.trim().length === 0) {\n\t\treturn undefined;\n\t}\n\treturn value;\n}\n\nfunction isLegacyTrackEvent(input: TrackInput): input is LegacyTrackEvent {\n\treturn \"eventType\" in input;\n}\n","import type {\n\tTrackingShutdownOptions,\n\tTrackingShutdownResult,\n} from \"./@types.js\";\nimport type {\n\tV2BatchRejectedEvent,\n\tV2BatchRequest,\n\tV2BatchResponse,\n\tV2EventEnvelope,\n} from \"./v2-types.js\";\n\nconst DEFAULT_ENDPOINT_PATH = \"/api/mcp/events/v2/batch\";\nconst DEFAULT_FLUSH_INTERVAL_MS = 1_000;\nconst DEFAULT_MAX_BATCH_SIZE = 20;\nconst DEFAULT_MAX_BUFFER_SIZE = 1_000;\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_RETRY_BASE_DELAY_MS = 200;\nconst DEFAULT_RETRY_MAX_DELAY_MS = 2_000;\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 2_000;\nconst SDK_NAME = \"@waniwani/sdk\";\n\nconst AUTH_FAILURE_STATUS = new Set([401, 403]);\nconst RETRYABLE_STATUS = new Set([408, 425, 429, 500, 502, 503, 504]);\n\ninterface Logger {\n\twarn: (message: string, ...args: unknown[]) => void;\n\terror: (message: string, ...args: unknown[]) => void;\n}\n\nexport interface V2TransportOptions {\n\tapiUrl: string;\n\tapiKey: string;\n\tendpointPath?: string;\n\tflushIntervalMs?: number;\n\tmaxBatchSize?: number;\n\tmaxBufferSize?: number;\n\tmaxRetries?: number;\n\tretryBaseDelayMs?: number;\n\tretryMaxDelayMs?: number;\n\tshutdownTimeoutMs?: number;\n\tsdkVersion?: string;\n\tfetchFn?: typeof fetch;\n\tlogger?: Logger;\n\tnow?: () => Date;\n\tsleep?: (delayMs: number) => Promise<void>;\n}\n\nexport interface V2BatchTransport {\n\tenqueue: (event: V2EventEnvelope) => void;\n\tflush: () => Promise<void>;\n\tshutdown: (\n\t\toptions?: TrackingShutdownOptions,\n\t) => Promise<TrackingShutdownResult>;\n\tpendingEvents: () => number;\n}\n\ntype SendBatchResult =\n\t| { kind: \"success\" }\n\t| { kind: \"retryable\"; reason: string }\n\t| { kind: \"permanent\"; reason: string }\n\t| { kind: \"auth\"; status: number }\n\t| {\n\t\t\tkind: \"partial\";\n\t\t\tretryable: V2EventEnvelope[];\n\t\t\tpermanent: V2EventEnvelope[];\n\t };\n\nexport function createV2BatchTransport(\n\toptions: V2TransportOptions,\n): V2BatchTransport {\n\treturn new BatchingV2Transport(options);\n}\n\nclass BatchingV2Transport implements V2BatchTransport {\n\tprivate readonly endpointUrl: string;\n\tprivate readonly flushIntervalMs: number;\n\tprivate readonly maxBatchSize: number;\n\tprivate readonly maxBufferSize: number;\n\tprivate readonly maxRetries: number;\n\tprivate readonly retryBaseDelayMs: number;\n\tprivate readonly retryMaxDelayMs: number;\n\tprivate readonly shutdownTimeoutMs: number;\n\tprivate readonly sdkVersion?: string;\n\tprivate readonly fetchFn: typeof fetch;\n\tprivate readonly logger: Logger;\n\tprivate readonly now: () => Date;\n\tprivate readonly sleep: (delayMs: number) => Promise<void>;\n\tprivate readonly apiKey: string;\n\n\tprivate readonly buffer: V2EventEnvelope[] = [];\n\tprivate flushTimer: ReturnType<typeof setInterval> | undefined;\n\tprivate flushScheduled = false;\n\tprivate flushScheduledTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate flushInFlight: Promise<void> | undefined;\n\tprivate inFlightCount = 0;\n\tprivate isStopped = false;\n\tprivate isShuttingDown = false;\n\n\tconstructor(options: V2TransportOptions) {\n\t\tthis.endpointUrl = joinUrl(\n\t\t\toptions.apiUrl,\n\t\t\toptions.endpointPath ?? DEFAULT_ENDPOINT_PATH,\n\t\t);\n\t\tthis.flushIntervalMs = options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;\n\t\tthis.maxBatchSize = options.maxBatchSize ?? DEFAULT_MAX_BATCH_SIZE;\n\t\tthis.maxBufferSize = options.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE;\n\t\tthis.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n\t\tthis.retryBaseDelayMs =\n\t\t\toptions.retryBaseDelayMs ?? DEFAULT_RETRY_BASE_DELAY_MS;\n\t\tthis.retryMaxDelayMs =\n\t\t\toptions.retryMaxDelayMs ?? DEFAULT_RETRY_MAX_DELAY_MS;\n\t\tthis.shutdownTimeoutMs =\n\t\t\toptions.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;\n\t\tthis.fetchFn = options.fetchFn ?? fetch;\n\t\tthis.logger = options.logger ?? console;\n\t\tthis.now = options.now ?? (() => new Date());\n\t\tthis.sleep =\n\t\t\toptions.sleep ??\n\t\t\t((delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)));\n\t\tthis.apiKey = options.apiKey;\n\t\tthis.sdkVersion = options.sdkVersion;\n\n\t\tif (this.flushIntervalMs > 0) {\n\t\t\tthis.flushTimer = setInterval(() => {\n\t\t\t\tvoid this.flush();\n\t\t\t}, this.flushIntervalMs);\n\t\t}\n\t}\n\n\tenqueue(event: V2EventEnvelope): void {\n\t\tif (this.isStopped || this.isShuttingDown) {\n\t\t\tthis.logger.warn(\n\t\t\t\t\"[WaniWani] Tracking transport is stopped, dropping event %s\",\n\t\t\t\tevent.id,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.buffer.length >= this.maxBufferSize) {\n\t\t\tconst dropCount = this.buffer.length - this.maxBufferSize + 1;\n\t\t\tthis.buffer.splice(0, dropCount);\n\t\t\tthis.logger.warn(\n\t\t\t\t\"[WaniWani] Tracking buffer overflow, dropped %d oldest event(s)\",\n\t\t\t\tdropCount,\n\t\t\t);\n\t\t}\n\n\t\tthis.buffer.push(event);\n\n\t\tif (this.buffer.length >= this.maxBatchSize) {\n\t\t\tvoid this.flush();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.scheduleMicroFlush();\n\t}\n\n\tpendingEvents(): number {\n\t\treturn this.buffer.length + this.inFlightCount;\n\t}\n\n\tasync flush(): Promise<void> {\n\t\tif (this.flushInFlight) {\n\t\t\treturn this.flushInFlight;\n\t\t}\n\t\tthis.flushInFlight = this.flushLoop().finally(() => {\n\t\t\tthis.flushInFlight = undefined;\n\t\t});\n\t\treturn this.flushInFlight;\n\t}\n\n\tasync shutdown(\n\t\toptions?: TrackingShutdownOptions,\n\t): Promise<TrackingShutdownResult> {\n\t\tthis.isShuttingDown = true;\n\t\tif (this.flushTimer) {\n\t\t\tclearInterval(this.flushTimer);\n\t\t\tthis.flushTimer = undefined;\n\t\t}\n\t\tif (this.flushScheduledTimer) {\n\t\t\tclearTimeout(this.flushScheduledTimer);\n\t\t\tthis.flushScheduledTimer = undefined;\n\t\t\tthis.flushScheduled = false;\n\t\t}\n\n\t\tconst timeoutMs = options?.timeoutMs ?? this.shutdownTimeoutMs;\n\t\tconst flushPromise = this.flush();\n\n\t\tif (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n\t\t\tawait flushPromise;\n\t\t\tthis.isStopped = true;\n\t\t\treturn { timedOut: false, pendingEvents: this.pendingEvents() };\n\t\t}\n\n\t\tconst timeoutSignal = Symbol(\"shutdown-timeout\");\n\t\tconst result = await Promise.race([\n\t\t\tflushPromise.then(() => \"flushed\" as const),\n\t\t\tthis.sleep(timeoutMs).then(() => timeoutSignal),\n\t\t]);\n\n\t\tif (result === timeoutSignal) {\n\t\t\tthis.isStopped = true;\n\t\t\treturn { timedOut: true, pendingEvents: this.pendingEvents() };\n\t\t}\n\n\t\tthis.isStopped = true;\n\t\treturn { timedOut: false, pendingEvents: this.pendingEvents() };\n\t}\n\n\tprivate scheduleMicroFlush(): void {\n\t\tif (this.flushScheduled) {\n\t\t\treturn;\n\t\t}\n\t\tthis.flushScheduled = true;\n\t\tthis.flushScheduledTimer = setTimeout(() => {\n\t\t\tthis.flushScheduledTimer = undefined;\n\t\t\tthis.flushScheduled = false;\n\t\t\tvoid this.flush();\n\t\t}, 0);\n\t}\n\n\tprivate async flushLoop(): Promise<void> {\n\t\twhile (this.buffer.length > 0 && !this.isStopped) {\n\t\t\tconst batch = this.buffer.splice(0, this.maxBatchSize);\n\t\t\tawait this.sendBatchWithRetry(batch);\n\t\t}\n\t}\n\n\tprivate async sendBatchWithRetry(batch: V2EventEnvelope[]): Promise<void> {\n\t\tlet attempt = 0;\n\t\tlet pendingBatch = batch;\n\n\t\twhile (pendingBatch.length > 0 && !this.isStopped) {\n\t\t\tthis.inFlightCount = pendingBatch.length;\n\t\t\tconst result = await this.sendBatchOnce(pendingBatch);\n\t\t\tthis.inFlightCount = 0;\n\n\t\t\tswitch (result.kind) {\n\t\t\t\tcase \"success\":\n\t\t\t\t\treturn;\n\t\t\t\tcase \"auth\":\n\t\t\t\t\tthis.stopTransportForAuthFailure(result.status, pendingBatch.length);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"permanent\":\n\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\"[WaniWani] Dropping %d event(s) after permanent failure: %s\",\n\t\t\t\t\t\tpendingBatch.length,\n\t\t\t\t\t\tresult.reason,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"retryable\":\n\t\t\t\t\tif (attempt >= this.maxRetries) {\n\t\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\t\"[WaniWani] Dropping %d event(s) after retry exhaustion: %s\",\n\t\t\t\t\t\t\tpendingBatch.length,\n\t\t\t\t\t\t\tresult.reason,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tawait this.sleep(this.backoffDelayMs(attempt));\n\t\t\t\t\tattempt += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\tcase \"partial\":\n\t\t\t\t\tif (result.permanent.length > 0) {\n\t\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\t\"[WaniWani] Dropping %d event(s) rejected as permanent\",\n\t\t\t\t\t\t\tresult.permanent.length,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (result.retryable.length === 0) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (attempt >= this.maxRetries) {\n\t\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\t\"[WaniWani] Dropping %d retryable event(s) after retry exhaustion\",\n\t\t\t\t\t\t\tresult.retryable.length,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tpendingBatch = result.retryable;\n\t\t\t\t\tawait this.sleep(this.backoffDelayMs(attempt));\n\t\t\t\t\tattempt += 1;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async sendBatchOnce(\n\t\tevents: V2EventEnvelope[],\n\t): Promise<SendBatchResult> {\n\t\tlet response: Response;\n\n\t\ttry {\n\t\t\tresponse = await this.fetchFn(this.endpointUrl, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tAuthorization: `Bearer ${this.apiKey}`,\n\t\t\t\t\t\"X-WaniWani-SDK\": SDK_NAME,\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(this.makeBatchRequest(events)),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tkind: \"retryable\",\n\t\t\t\treason: getErrorMessage(error),\n\t\t\t};\n\t\t}\n\n\t\tif (AUTH_FAILURE_STATUS.has(response.status)) {\n\t\t\treturn { kind: \"auth\", status: response.status };\n\t\t}\n\n\t\tif (RETRYABLE_STATUS.has(response.status)) {\n\t\t\treturn {\n\t\t\t\tkind: \"retryable\",\n\t\t\t\treason: `HTTP ${response.status}`,\n\t\t\t};\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\treturn {\n\t\t\t\tkind: \"permanent\",\n\t\t\t\treason: `HTTP ${response.status}`,\n\t\t\t};\n\t\t}\n\n\t\tconst data = await parseJsonResponse<V2BatchResponse>(response);\n\t\tif (!data?.rejected || data.rejected.length === 0) {\n\t\t\treturn { kind: \"success\" };\n\t\t}\n\n\t\tconst partial = this.classifyRejectedEvents(events, data.rejected);\n\t\tif (partial.retryable.length === 0 && partial.permanent.length === 0) {\n\t\t\treturn { kind: \"success\" };\n\t\t}\n\n\t\treturn {\n\t\t\tkind: \"partial\",\n\t\t\tretryable: partial.retryable,\n\t\t\tpermanent: partial.permanent,\n\t\t};\n\t}\n\n\tprivate makeBatchRequest(events: V2EventEnvelope[]): V2BatchRequest {\n\t\treturn {\n\t\t\tsentAt: this.now().toISOString(),\n\t\t\tsource: {\n\t\t\t\tsdk: SDK_NAME,\n\t\t\t\tversion: this.sdkVersion ?? \"0.0.0\",\n\t\t\t},\n\t\t\tevents,\n\t\t};\n\t}\n\n\tprivate classifyRejectedEvents(\n\t\tevents: V2EventEnvelope[],\n\t\trejected: V2BatchRejectedEvent[],\n\t): {\n\t\tretryable: V2EventEnvelope[];\n\t\tpermanent: V2EventEnvelope[];\n\t} {\n\t\tconst byId = new Map(events.map((event) => [event.id, event]));\n\t\tconst retryable: V2EventEnvelope[] = [];\n\t\tconst permanent: V2EventEnvelope[] = [];\n\n\t\tfor (const rejectedEvent of rejected) {\n\t\t\tconst event = byId.get(rejectedEvent.eventId);\n\t\t\tif (!event) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isRetryableRejectedEvent(rejectedEvent)) {\n\t\t\t\tretryable.push(event);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tpermanent.push(event);\n\t\t}\n\n\t\treturn { retryable, permanent };\n\t}\n\n\tprivate backoffDelayMs(attempt: number): number {\n\t\tconst rawDelay = this.retryBaseDelayMs * 2 ** attempt;\n\t\treturn Math.min(rawDelay, this.retryMaxDelayMs);\n\t}\n\n\tprivate stopTransportForAuthFailure(\n\t\tstatus: number,\n\t\trejectedCount: number,\n\t): void {\n\t\tthis.isStopped = true;\n\t\tconst buffered = this.buffer.length;\n\t\tthis.buffer.splice(0, buffered);\n\t\tthis.logger.error(\n\t\t\t\"[WaniWani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)\",\n\t\t\tstatus,\n\t\t\trejectedCount + buffered,\n\t\t);\n\t}\n}\n\nfunction isRetryableRejectedEvent(\n\trejectedEvent: V2BatchRejectedEvent,\n): boolean {\n\tif (rejectedEvent.retryable === true) {\n\t\treturn true;\n\t}\n\tconst code = rejectedEvent.code.toLowerCase();\n\treturn (\n\t\tcode.includes(\"timeout\") ||\n\t\tcode.includes(\"temporary\") ||\n\t\tcode.includes(\"unavailable\") ||\n\t\tcode.includes(\"rate_limit\") ||\n\t\tcode.includes(\"transient\") ||\n\t\tcode.includes(\"server\")\n\t);\n}\n\nasync function parseJsonResponse<T>(\n\tresponse: Response,\n): Promise<T | undefined> {\n\tconst body = await response.text();\n\tif (!body) {\n\t\treturn undefined;\n\t}\n\ttry {\n\t\treturn JSON.parse(body) as T;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction joinUrl(apiUrl: string, endpointPath: string): string {\n\tconst normalizedBase = apiUrl.endsWith(\"/\") ? apiUrl : `${apiUrl}/`;\n\tconst normalizedPath = endpointPath.startsWith(\"/\")\n\t\t? endpointPath.slice(1)\n\t\t: endpointPath;\n\treturn `${normalizedBase}${normalizedPath}`;\n}\n\nfunction getErrorMessage(error: unknown): string {\n\tif (error instanceof Error) {\n\t\treturn error.message;\n\t}\n\treturn String(error);\n}\n","// Tracking Module\n\nimport type { InternalConfig } from \"../types.js\";\nimport type {\n\tTrackInput,\n\tTrackingClient,\n\tTrackingShutdownOptions,\n} from \"./@types.js\";\nimport { mapTrackEventToV2 } from \"./mapper.js\";\nimport { createV2BatchTransport } from \"./transport.js\";\n\n// Re-export types\nexport type {\n\tEventType,\n\tLegacyTrackEvent,\n\tLinkClickedProperties,\n\tPurchaseCompletedProperties,\n\tQuoteSucceededProperties,\n\tToolCalledProperties,\n\tTrackEvent,\n\tTrackInput,\n\tTrackingClient,\n\tTrackingConfig,\n\tTrackingShutdownOptions,\n\tTrackingShutdownResult,\n} from \"./@types.js\";\nexport { createEventId, mapTrackEventToV2 } from \"./mapper.js\";\nexport type {\n\tV2BatchRejectedEvent,\n\tV2BatchRequest,\n\tV2BatchResponse,\n\tV2CorrelationIds,\n\tV2EnvelopeType,\n\tV2EventEnvelope,\n} from \"./v2-types.js\";\n\nexport function createTrackingClient(config: InternalConfig): TrackingClient {\n\tconst { apiUrl, apiKey, tracking } = config;\n\n\tfunction requireApiKey(): string {\n\t\tif (!apiKey) {\n\t\t\tthrow new Error(\"WANIWANI_API_KEY is not set\");\n\t\t}\n\t\treturn apiKey;\n\t}\n\n\tconst transport = apiKey\n\t\t? createV2BatchTransport({\n\t\t\t\tapiUrl,\n\t\t\t\tapiKey,\n\t\t\t\tendpointPath: tracking.endpointPath,\n\t\t\t\tflushIntervalMs: tracking.flushIntervalMs,\n\t\t\t\tmaxBatchSize: tracking.maxBatchSize,\n\t\t\t\tmaxBufferSize: tracking.maxBufferSize,\n\t\t\t\tmaxRetries: tracking.maxRetries,\n\t\t\t\tretryBaseDelayMs: tracking.retryBaseDelayMs,\n\t\t\t\tretryMaxDelayMs: tracking.retryMaxDelayMs,\n\t\t\t\tshutdownTimeoutMs: tracking.shutdownTimeoutMs,\n\t\t\t})\n\t\t: undefined;\n\n\tconst client: TrackingClient = {\n\t\tasync identify(\n\t\t\tuserId: string,\n\t\t\tproperties?: Record<string, unknown>,\n\t\t\tmeta?: Record<string, unknown>,\n\t\t): Promise<{ eventId: string }> {\n\t\t\trequireApiKey();\n\t\t\tconst mappedEvent = mapTrackEventToV2({\n\t\t\t\tevent: \"user.identified\",\n\t\t\t\texternalUserId: userId,\n\t\t\t\tproperties,\n\t\t\t\tmeta,\n\t\t\t});\n\t\t\ttransport?.enqueue(mappedEvent);\n\t\t\treturn { eventId: mappedEvent.id };\n\t\t},\n\t\tasync track(event: TrackInput): Promise<{ eventId: string }> {\n\t\t\trequireApiKey();\n\t\t\tconst mappedEvent = mapTrackEventToV2(event);\n\t\t\ttransport?.enqueue(mappedEvent);\n\t\t\treturn { eventId: mappedEvent.id };\n\t\t},\n\t\tasync flush(): Promise<void> {\n\t\t\trequireApiKey();\n\t\t\tawait transport?.flush();\n\t\t},\n\t\tasync shutdown(options?: TrackingShutdownOptions) {\n\t\t\trequireApiKey();\n\t\t\treturn (\n\t\t\t\t(await transport?.shutdown({\n\t\t\t\t\ttimeoutMs: options?.timeoutMs ?? tracking.shutdownTimeoutMs,\n\t\t\t\t})) ?? { timedOut: false, pendingEvents: 0 }\n\t\t\t);\n\t\t},\n\t};\n\n\tif (transport) {\n\t\tattachShutdownHooks(client, tracking.shutdownTimeoutMs);\n\t}\n\treturn client;\n}\n\nfunction attachShutdownHooks(\n\tclient: TrackingClient,\n\tdefaultTimeoutMs: number,\n): void {\n\tif (\n\t\ttypeof process === \"undefined\" ||\n\t\ttypeof process.once !== \"function\" ||\n\t\ttypeof process.on !== \"function\"\n\t) {\n\t\treturn;\n\t}\n\n\tconst shutdown = () => {\n\t\tvoid client.shutdown({ timeoutMs: defaultTimeoutMs });\n\t};\n\n\tprocess.once(\"beforeExit\", shutdown);\n\tprocess.once(\"SIGINT\", shutdown);\n\tprocess.once(\"SIGTERM\", shutdown);\n}\n","// WaniWani SDK - Main Entry\n\nimport { createKbClient } from \"./kb/client.js\";\nimport type { WaniWaniProjectConfig } from \"./project-config.js\";\nimport { getGlobalConfig } from \"./project-config.js\";\nimport { createTrackingClient } from \"./tracking/index.js\";\nimport type { WaniWaniClient, WaniWaniConfig } from \"./types.js\";\n\n/**\n * Create a WaniWani SDK client\n *\n * @param config - Configuration options. When omitted, reads from the global\n * config registered by `defineConfig()`, then falls back to env vars.\n * @returns A fully typed WaniWani client\n *\n * @example\n * ```typescript\n * import { waniwani } from \"@waniwani/sdk\";\n * import { toNextJsHandler } from \"@waniwani/sdk/next-js\";\n *\n * const wani = waniwani({ apiKey: \"...\" });\n *\n * // Next.js route handler\n * export const { GET, POST } = toNextJsHandler(wani, {\n * chat: { systemPrompt: \"You are a helpful assistant.\" },\n * });\n * ```\n */\nexport function waniwani(\n\tconfig?: WaniWaniConfig | WaniWaniProjectConfig,\n): WaniWaniClient {\n\tconst effective = config ?? getGlobalConfig();\n\n\tconst apiUrl = effective?.apiUrl ?? \"https://app.waniwani.ai\";\n\tconst apiKey = effective?.apiKey ?? process.env.WANIWANI_API_KEY;\n\tconst trackingConfig = {\n\t\tendpointPath:\n\t\t\teffective?.tracking?.endpointPath ?? \"/api/mcp/events/v2/batch\",\n\t\tflushIntervalMs: effective?.tracking?.flushIntervalMs ?? 1_000,\n\t\tmaxBatchSize: effective?.tracking?.maxBatchSize ?? 20,\n\t\tmaxBufferSize: effective?.tracking?.maxBufferSize ?? 1_000,\n\t\tmaxRetries: effective?.tracking?.maxRetries ?? 3,\n\t\tretryBaseDelayMs: effective?.tracking?.retryBaseDelayMs ?? 200,\n\t\tretryMaxDelayMs: effective?.tracking?.retryMaxDelayMs ?? 2_000,\n\t\tshutdownTimeoutMs: effective?.tracking?.shutdownTimeoutMs ?? 2_000,\n\t};\n\n\tconst internalConfig = { apiUrl, apiKey, tracking: trackingConfig };\n\n\t// Compose client from modules\n\tconst trackingClient = createTrackingClient(internalConfig);\n\tconst kbClient = createKbClient(internalConfig);\n\n\treturn {\n\t\t...trackingClient,\n\t\tkb: kbClient,\n\t\t_config: internalConfig,\n\t};\n}\n"],"mappings":"AAEO,IAAMA,EAAN,cAA4B,KAAM,CACxC,YACCC,EACOC,EACN,CACD,MAAMD,CAAO,EAFN,YAAAC,EAGP,KAAK,KAAO,eACb,CACD,ECoDA,IAAIC,EAWG,SAASC,EACfC,EACwB,CACxB,OAAAF,EAAgBE,EACTA,CACR,CAOO,SAASC,GAAqD,CACpE,OAAOH,CACR,CC1EA,IAAMI,EAAW,gBAEV,SAASC,EAAeC,EAAkC,CAChE,GAAM,CAAE,OAAAC,EAAQ,OAAAC,CAAO,EAAIF,EAE3B,SAASG,GAAwB,CAChC,GAAI,CAACD,EACJ,MAAM,IAAI,MAAM,6BAA6B,EAE9C,OAAOA,CACR,CAEA,eAAeE,EACdC,EACAC,EACAC,EACa,CACb,IAAMC,EAAML,EAAc,EACpBM,EAAM,GAAGR,EAAO,QAAQ,MAAO,EAAE,CAAC,GAAGK,CAAI,GAEzCI,EAAkC,CACvC,cAAe,UAAUF,CAAG,GAC5B,iBAAkBV,CACnB,EAEMa,EAAoB,CAAE,OAAAN,EAAQ,QAAAK,CAAQ,EAExCH,IAAS,SACZG,EAAQ,cAAc,EAAI,mBAC1BC,EAAK,KAAO,KAAK,UAAUJ,CAAI,GAGhC,IAAMK,EAAW,MAAM,MAAMH,EAAKE,CAAI,EAEtC,GAAI,CAACC,EAAS,GAAI,CACjB,IAAMC,EAAO,MAAMD,EAAS,KAAK,EAAE,MAAM,IAAM,EAAE,EACjD,MAAM,IAAIE,EACTD,GAAQ,sBAAsBD,EAAS,MAAM,GAC7CA,EAAS,MACV,CACD,CAGA,OADc,MAAMA,E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B,IAAMC,EAAYD,GAAUE,EAAgB,EAEtCC,EAASF,GAAW,QAAU,0BAC9BG,EAASH,GAAW,QAAU,QAAQ,IAAI,iBAC1CI,EAAiB,CACtB,aACCJ,GAAW,UAAU,cAAgB,2BACtC,gBAAiBA,GAAW,UAAU,iBAAmB,IACzD,aAAcA,GAAW,UAAU,cAAgB,GACnD,cAAeA,GAAW,UAAU,eAAiB,IACrD,WAAYA,GAAW,UAAU,YAAc,EAC/C,iBAAkBA,GAAW,UAAU,kBAAoB,IAC3D,gBAAiBA,GAAW,UAAU,iBAAmB,IACzD,kBAAmBA,GAAW,UAAU,mBAAqB,GAC9D,EAEMK,EAAiB,CAAE,OAAAH,EAAQ,OAAAC,EAAQ,SAAUC,CAAe,EAG5DE,EAAiBC,EAAqBF,CAAc,EACpDG,EAAWC,EAAeJ,CAAc,EAE9C,MAAO,CACN,GAAGC,EACH,GAAIE,EACJ,QAASH,CACV,CACD","names":["WaniWaniError","message","status","_globalConfig","defineConfig","config","getGlobalConfig","SDK_NAME","createKbClient","config","apiUrl","apiKey","requireApiKey","request","method","path","body","key","url","headers","init","response","text","WaniWaniError","files","query","options","pickFirst","meta","keys","key","value","SESSION_ID_KEYS","REQUEST_ID_KEYS","TRACE_ID_KEYS","EXTERNAL_USER_ID_KEYS","CORRELATION_ID_KEYS","extractSessionId","extractRequestId","extractTraceId","extractExternalUserId","extractCorrelationId","SOURCE_SESSION_KEYS","extractSource","explicit","source","DEFAULT_SOURCE","mapTrackEventToV2","input","options","now","generateId","createEventId","eventName","resolveEventName","meta","toRecord","metadata","correlation","resolveCorrelationIds","eventId","takeNonEmptyString","timestamp","normalizeTimestamp","source","extractSource","rawLegacy","isLegacyTrackEvent","mappedMetadata","mapProperties","legacyProperties","mapLegacyProperties","explicitProperties","properties","requestId","extractRequestId","sessionId","extractSessionId","traceId","extractTraceId","externalUserId","extractExternalUserId","correlationId","extractCorrelationId","date","value","DEFAULT_ENDPOINT_PATH","SDK_NAME","AUTH_FAILURE_STATUS","RETRYABLE_STATUS","createV2BatchTransport","options","BatchingV2Transport","joinUrl","DEFAULT_ENDPOINT_PATH","delayMs","resolve","event","dropCount","timeoutMs","flushPromise","timeoutSignal","batch","attempt","pendingBatch","result","events","response","error","getErrorMessage","data","parseJsonResponse","partial","rejected","byId","retryable","permanent","rejectedEvent","isRetryableRejectedEvent","rawDelay","status","rejectedCount","buffered","code","body","apiUrl","endpointPath","normalizedBase","normalizedPath","createTrackingClient","config","apiUrl","apiKey","tracking","requireApiKey","transport","createV2BatchTransport","client","userId","properties","meta","mappedEvent","mapTrackEventToV2","event","options","attachShutdownHooks","defaultTimeoutMs","shutdown","waniwani","config","effective","getGlobalConfig","apiUrl","apiKey","trackingConfig","internalConfig","trackingClient","createTrackingClient","kbClient","createKbClient"]}
1
+ {"version":3,"sources":["../src/error.ts","../src/project-config.ts","../src/kb/client.ts","../src/mcp/server/utils.ts","../src/tracking/mapper.ts","../src/tracking/transport.ts","../src/tracking/index.ts","../src/waniwani.ts"],"sourcesContent":["// WaniWani SDK - Errors\n\nexport class WaniWaniError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic status: number,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"WaniWaniError\";\n\t}\n}\n","import type { TrackingConfig } from \"./tracking/@types.js\";\n\n/**\n * Project-level configuration for WaniWani MCP projects.\n *\n * This is the single source of truth for both CLI tools (`waniwani eval`,\n * `waniwani embed`, etc.) and the runtime SDK client (`waniwani()`).\n *\n * Create a `waniwani.config.ts` at the project root:\n * ```ts\n * import { defineConfig } from \"@waniwani/sdk\";\n *\n * export default defineConfig({\n * apiKey: process.env.WANIWANI_API_KEY,\n * evals: {\n * mcpServerUrl: \"http://localhost:3001\",\n * },\n * });\n * ```\n *\n * Then import it as a side-effect to register the config globally:\n * ```ts\n * import \"./waniwani.config\";\n * import { waniwani } from \"@waniwani/sdk\";\n *\n * const wani = waniwani(); // picks up config from defineConfig\n * ```\n */\nexport interface WaniWaniProjectConfig {\n\t/**\n\t * Your MCP environment API key.\n\t * Defaults to `process.env.WANIWANI_API_KEY` if not provided.\n\t */\n\tapiKey?: string;\n\t/**\n\t * The base URL of the WaniWani API.\n\t * Defaults to `https://app.waniwani.ai`.\n\t */\n\tapiUrl?: string;\n\t/** Tracking transport behavior. */\n\ttracking?: TrackingConfig;\n\tevals?: {\n\t\t/** Path to the evals directory (relative to project root).\n\t\t *\n\t\t * @default ./evals */\n\t\tdir?: string;\n\t\t/** MCP server URL to test against. */\n\t\tmcpServerUrl: string;\n\t};\n\tknowledgeBase?: {\n\t\t/** Path to the knowledge base directory (relative to project root).\n\t\t *\n\t\t * @default ./knowledge-base\n\t\t */\n\t\tdir?: string;\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Global singleton — uses globalThis so the config is shared across all\n// SDK entry points (e.g. @waniwani/sdk and @waniwani/sdk/mcp) even when\n// they are bundled as separate chunks with their own module scopes.\n// ---------------------------------------------------------------------------\n\nconst GLOBAL_KEY = \"__waniwani_config__\" as const;\n\n/**\n * Define and register a WaniWani project configuration.\n *\n * Calling this stores the config on `globalThis` so that\n * `waniwani()` and `withWaniwani()` can read from it automatically\n * when no explicit config is passed — even across different SDK\n * entry points (`@waniwani/sdk`, `@waniwani/sdk/mcp`, etc.).\n *\n * The config is also returned for direct use.\n */\nexport function defineConfig(\n\tconfig: WaniWaniProjectConfig,\n): WaniWaniProjectConfig {\n\t(globalThis as Record<string, unknown>)[GLOBAL_KEY] = config;\n\treturn config;\n}\n\n/**\n * Retrieve the globally registered config (set by `defineConfig`).\n * Returns `undefined` if `defineConfig` has not been called.\n * @internal\n */\nexport function getGlobalConfig(): WaniWaniProjectConfig | undefined {\n\treturn (globalThis as Record<string, unknown>)[GLOBAL_KEY] as\n\t\t| WaniWaniProjectConfig\n\t\t| undefined;\n}\n","// KB Client — thin HTTP wrapper for knowledge base API\n\nimport { WaniWaniError } from \"../error.js\";\nimport type { InternalConfig } from \"../types.js\";\nimport type {\n\tKbClient,\n\tKbIngestFile,\n\tKbIngestResult,\n\tKbSearchOptions,\n\tKbSource,\n\tSearchResult,\n} from \"./types.js\";\n\nconst SDK_NAME = \"@waniwani/sdk\";\n\nexport function createKbClient(config: InternalConfig): KbClient {\n\tconst { apiUrl, apiKey } = config;\n\n\tfunction requireApiKey(): string {\n\t\tif (!apiKey) {\n\t\t\tthrow new Error(\"WANIWANI_API_KEY is not set\");\n\t\t}\n\t\treturn apiKey;\n\t}\n\n\tasync function request<T>(\n\t\tmethod: \"GET\" | \"POST\",\n\t\tpath: string,\n\t\tbody?: unknown,\n\t): Promise<T> {\n\t\tconst key = requireApiKey();\n\t\tconst url = `${apiUrl.replace(/\\/$/, \"\")}${path}`;\n\n\t\tconst headers: Record<string, string> = {\n\t\t\tAuthorization: `Bearer ${key}`,\n\t\t\t\"X-WaniWani-SDK\": SDK_NAME,\n\t\t};\n\n\t\tconst init: RequestInit = { method, headers };\n\n\t\tif (body !== undefined) {\n\t\t\theaders[\"Content-Type\"] = \"application/json\";\n\t\t\tinit.body = JSON.stringify(body);\n\t\t}\n\n\t\tconst response = await fetch(url, init);\n\n\t\tif (!response.ok) {\n\t\t\tconst text = await response.text().catch(() => \"\");\n\t\t\tthrow new WaniWaniError(\n\t\t\t\ttext || `KB API error: HTTP ${response.status}`,\n\t\t\t\tresponse.status,\n\t\t\t);\n\t\t}\n\n\t\tconst json = (await response.json()) as { data: T };\n\t\treturn json.data;\n\t}\n\n\treturn {\n\t\tasync ingest(files: KbIngestFile[]): Promise<KbIngestResult> {\n\t\t\treturn request<KbIngestResult>(\"POST\", \"/api/mcp/kb/ingest\", {\n\t\t\t\tfiles,\n\t\t\t});\n\t\t},\n\n\t\tasync search(\n\t\t\tquery: string,\n\t\t\toptions?: KbSearchOptions,\n\t\t): Promise<SearchResult[]> {\n\t\t\treturn request<SearchResult[]>(\"POST\", \"/api/mcp/kb/search\", {\n\t\t\t\tquery,\n\t\t\t\t...options,\n\t\t\t});\n\t\t},\n\n\t\tasync sources(): Promise<KbSource[]> {\n\t\t\treturn request<KbSource[]>(\"GET\", \"/api/mcp/kb/sources\");\n\t\t},\n\t};\n}\n","// ============================================================================\n// Meta key extraction helpers\n// ============================================================================\n\n/** Pick the first non-empty string value from `meta` matching the given keys. */\nfunction pickFirst(\n\tmeta: Record<string, unknown>,\n\tkeys: readonly string[],\n): string | undefined {\n\tfor (const key of keys) {\n\t\tconst value = meta[key];\n\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\treturn value;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n// --- Key lists (ordered by priority) ---\n\nconst SESSION_ID_KEYS = [\n\t\"waniwani/sessionId\",\n\t\"openai/sessionId\",\n\t\"openai/session\",\n\t\"sessionId\",\n\t\"conversationId\",\n\t\"anthropic/sessionId\",\n] as const;\n\nconst REQUEST_ID_KEYS = [\n\t\"waniwani/requestId\",\n\t\"openai/requestId\",\n\t\"requestId\",\n\t\"mcp/requestId\",\n] as const;\n\nconst TRACE_ID_KEYS = [\n\t\"waniwani/traceId\",\n\t\"openai/traceId\",\n\t\"traceId\",\n\t\"mcp/traceId\",\n\t\"openai/requestId\",\n\t\"requestId\",\n] as const;\n\nconst EXTERNAL_USER_ID_KEYS = [\n\t\"waniwani/userId\",\n\t\"openai/userId\",\n\t\"externalUserId\",\n\t\"userId\",\n\t\"actorId\",\n] as const;\n\nconst CORRELATION_ID_KEYS = [\"correlationId\", \"openai/requestId\"] as const;\n\n// --- Extractors ---\n\nexport function extractSessionId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, SESSION_ID_KEYS) : undefined;\n}\n\nexport function extractRequestId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, REQUEST_ID_KEYS) : undefined;\n}\n\nexport function extractTraceId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, TRACE_ID_KEYS) : undefined;\n}\n\nexport function extractExternalUserId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, EXTERNAL_USER_ID_KEYS) : undefined;\n}\n\nexport function extractCorrelationId(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\treturn meta ? pickFirst(meta, CORRELATION_ID_KEYS) : undefined;\n}\n\nconst SOURCE_SESSION_KEYS = [\n\t{ key: \"waniwani/sessionId\", source: \"chatbar\" },\n\t{ key: \"openai/sessionId\", source: \"chatgpt\" },\n\t{ key: \"openai/session\", source: \"chatgpt\" },\n\t{ key: \"anthropic/sessionId\", source: \"claude\" },\n] as const;\n\nexport function extractSource(\n\tmeta: Record<string, unknown> | undefined,\n): string | undefined {\n\tif (!meta) {\n\t\treturn undefined;\n\t}\n\t// Explicit source set by the caller (e.g. chatbar name)\n\tconst explicit = meta[\"waniwani/source\"];\n\tif (typeof explicit === \"string\" && explicit.length > 0) {\n\t\treturn explicit;\n\t}\n\t// Derive from session ID key\n\tfor (const { key, source } of SOURCE_SESSION_KEYS) {\n\t\tconst value = meta[key];\n\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\treturn source;\n\t\t}\n\t}\n\treturn undefined;\n}\n","import {\n\textractCorrelationId,\n\textractExternalUserId,\n\textractRequestId,\n\textractSessionId,\n\textractSource,\n\textractTraceId,\n} from \"../mcp/server/utils.js\";\nimport type { EventType, LegacyTrackEvent, TrackInput } from \"./@types.js\";\nimport type { V2CorrelationIds, V2EventEnvelope } from \"./v2-types.js\";\n\nconst DEFAULT_SOURCE = \"@waniwani/sdk\";\n\nexport interface MapTrackEventOptions {\n\tnow?: () => Date;\n\tgenerateId?: () => string;\n\tsource?: string;\n}\n\nexport function mapTrackEventToV2(\n\tinput: TrackInput,\n\toptions: MapTrackEventOptions = {},\n): V2EventEnvelope {\n\tconst now = options.now ?? (() => new Date());\n\tconst generateId = options.generateId ?? createEventId;\n\tconst eventName = resolveEventName(input);\n\tconst meta = toRecord(input.meta);\n\tconst metadata = toRecord(input.metadata);\n\tconst correlation = resolveCorrelationIds(input, meta);\n\tconst eventId = takeNonEmptyString(input.eventId) ?? generateId();\n\tconst timestamp = normalizeTimestamp(input.timestamp, now);\n\tconst source =\n\t\ttakeNonEmptyString(input.source) ??\n\t\textractSource(meta) ??\n\t\toptions.source ??\n\t\tDEFAULT_SOURCE;\n\tconst rawLegacy = isLegacyTrackEvent(input) ? { ...input } : undefined;\n\n\tconst mappedMetadata: Record<string, unknown> = {\n\t\t...metadata,\n\t};\n\tif (Object.keys(meta).length > 0) {\n\t\tmappedMetadata.meta = meta;\n\t}\n\tif (rawLegacy) {\n\t\tmappedMetadata.rawLegacy = rawLegacy;\n\t}\n\n\treturn {\n\t\tid: eventId,\n\t\ttype: \"mcp.event\",\n\t\tname: eventName,\n\t\tsource,\n\t\ttimestamp,\n\t\tcorrelation,\n\t\tproperties: mapProperties(input, eventName),\n\t\tmetadata: mappedMetadata,\n\t\trawLegacy,\n\t};\n}\n\nexport function createEventId(): string {\n\tif (\n\t\ttypeof crypto !== \"undefined\" &&\n\t\ttypeof crypto.randomUUID === \"function\"\n\t) {\n\t\treturn `evt_${crypto.randomUUID()}`;\n\t}\n\n\treturn `evt_${Math.random().toString(36).slice(2, 10)}_${Date.now().toString(36)}`;\n}\n\nfunction mapProperties(\n\tinput: TrackInput,\n\teventName: EventType,\n): Record<string, unknown> {\n\tif (!isLegacyTrackEvent(input)) {\n\t\treturn toRecord(input.properties);\n\t}\n\n\tconst legacyProperties = mapLegacyProperties(input, eventName);\n\tconst explicitProperties = toRecord(input.properties);\n\treturn {\n\t\t...legacyProperties,\n\t\t...explicitProperties,\n\t};\n}\n\nfunction mapLegacyProperties(\n\tinput: LegacyTrackEvent,\n\teventName: EventType,\n): Record<string, unknown> {\n\tswitch (eventName) {\n\t\tcase \"tool.called\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (takeNonEmptyString(input.toolName)) {\n\t\t\t\tproperties.name = input.toolName;\n\t\t\t}\n\t\t\tif (takeNonEmptyString(input.toolType)) {\n\t\t\t\tproperties.type = input.toolType;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tcase \"quote.succeeded\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (typeof input.quoteAmount === \"number\") {\n\t\t\t\tproperties.amount = input.quoteAmount;\n\t\t\t}\n\t\t\tif (takeNonEmptyString(input.quoteCurrency)) {\n\t\t\t\tproperties.currency = input.quoteCurrency;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tcase \"link.clicked\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (takeNonEmptyString(input.linkUrl)) {\n\t\t\t\tproperties.url = input.linkUrl;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tcase \"purchase.completed\": {\n\t\t\tconst properties: Record<string, unknown> = {};\n\t\t\tif (typeof input.purchaseAmount === \"number\") {\n\t\t\t\tproperties.amount = input.purchaseAmount;\n\t\t\t}\n\t\t\tif (takeNonEmptyString(input.purchaseCurrency)) {\n\t\t\t\tproperties.currency = input.purchaseCurrency;\n\t\t\t}\n\t\t\treturn properties;\n\t\t}\n\t\tdefault:\n\t\t\treturn {};\n\t}\n}\n\nfunction resolveEventName(input: TrackInput): EventType {\n\tif (isLegacyTrackEvent(input)) {\n\t\treturn input.eventType;\n\t}\n\treturn input.event;\n}\n\nfunction resolveCorrelationIds(\n\tinput: TrackInput,\n\tmeta: Record<string, unknown>,\n): V2CorrelationIds {\n\tconst requestId =\n\t\ttakeNonEmptyString(input.requestId) ?? extractRequestId(meta);\n\n\tconst sessionId =\n\t\ttakeNonEmptyString(input.sessionId) ?? extractSessionId(meta);\n\n\tconst traceId = takeNonEmptyString(input.traceId) ?? extractTraceId(meta);\n\n\tconst externalUserId =\n\t\ttakeNonEmptyString(input.externalUserId) ?? extractExternalUserId(meta);\n\n\tconst correlationId =\n\t\ttakeNonEmptyString(input.correlationId) ??\n\t\textractCorrelationId(meta) ??\n\t\trequestId;\n\n\tconst correlation: V2CorrelationIds = {};\n\tif (sessionId) {\n\t\tcorrelation.sessionId = sessionId;\n\t}\n\tif (traceId) {\n\t\tcorrelation.traceId = traceId;\n\t}\n\tif (requestId) {\n\t\tcorrelation.requestId = requestId;\n\t}\n\tif (correlationId) {\n\t\tcorrelation.correlationId = correlationId;\n\t}\n\tif (externalUserId) {\n\t\tcorrelation.externalUserId = externalUserId;\n\t}\n\treturn correlation;\n}\n\nfunction normalizeTimestamp(\n\tinput: string | Date | undefined,\n\tnow: () => Date,\n): string {\n\tif (input instanceof Date) {\n\t\treturn input.toISOString();\n\t}\n\tif (typeof input === \"string\") {\n\t\tconst date = new Date(input);\n\t\tif (!Number.isNaN(date.getTime())) {\n\t\t\treturn date.toISOString();\n\t\t}\n\t}\n\treturn now().toISOString();\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\treturn {};\n\t}\n\treturn value as Record<string, unknown>;\n}\n\nfunction takeNonEmptyString(value: unknown): string | undefined {\n\tif (typeof value !== \"string\") {\n\t\treturn undefined;\n\t}\n\tif (value.trim().length === 0) {\n\t\treturn undefined;\n\t}\n\treturn value;\n}\n\nfunction isLegacyTrackEvent(input: TrackInput): input is LegacyTrackEvent {\n\treturn \"eventType\" in input;\n}\n","import type {\n\tTrackingShutdownOptions,\n\tTrackingShutdownResult,\n} from \"./@types.js\";\nimport type {\n\tV2BatchRejectedEvent,\n\tV2BatchRequest,\n\tV2BatchResponse,\n\tV2EventEnvelope,\n} from \"./v2-types.js\";\n\nconst DEFAULT_ENDPOINT_PATH = \"/api/mcp/events/v2/batch\";\nconst DEFAULT_FLUSH_INTERVAL_MS = 1_000;\nconst DEFAULT_MAX_BATCH_SIZE = 20;\nconst DEFAULT_MAX_BUFFER_SIZE = 1_000;\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_RETRY_BASE_DELAY_MS = 200;\nconst DEFAULT_RETRY_MAX_DELAY_MS = 2_000;\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 2_000;\nconst SDK_NAME = \"@waniwani/sdk\";\n\nconst AUTH_FAILURE_STATUS = new Set([401, 403]);\nconst RETRYABLE_STATUS = new Set([408, 425, 429, 500, 502, 503, 504]);\n\ninterface Logger {\n\twarn: (message: string, ...args: unknown[]) => void;\n\terror: (message: string, ...args: unknown[]) => void;\n}\n\nexport interface V2TransportOptions {\n\tapiUrl: string;\n\tapiKey: string;\n\tendpointPath?: string;\n\tflushIntervalMs?: number;\n\tmaxBatchSize?: number;\n\tmaxBufferSize?: number;\n\tmaxRetries?: number;\n\tretryBaseDelayMs?: number;\n\tretryMaxDelayMs?: number;\n\tshutdownTimeoutMs?: number;\n\tsdkVersion?: string;\n\tfetchFn?: typeof fetch;\n\tlogger?: Logger;\n\tnow?: () => Date;\n\tsleep?: (delayMs: number) => Promise<void>;\n}\n\nexport interface V2BatchTransport {\n\tenqueue: (event: V2EventEnvelope) => void;\n\tflush: () => Promise<void>;\n\tshutdown: (\n\t\toptions?: TrackingShutdownOptions,\n\t) => Promise<TrackingShutdownResult>;\n\tpendingEvents: () => number;\n}\n\ntype SendBatchResult =\n\t| { kind: \"success\" }\n\t| { kind: \"retryable\"; reason: string }\n\t| { kind: \"permanent\"; reason: string }\n\t| { kind: \"auth\"; status: number }\n\t| {\n\t\t\tkind: \"partial\";\n\t\t\tretryable: V2EventEnvelope[];\n\t\t\tpermanent: V2EventEnvelope[];\n\t };\n\nexport function createV2BatchTransport(\n\toptions: V2TransportOptions,\n): V2BatchTransport {\n\treturn new BatchingV2Transport(options);\n}\n\nclass BatchingV2Transport implements V2BatchTransport {\n\tprivate readonly endpointUrl: string;\n\tprivate readonly flushIntervalMs: number;\n\tprivate readonly maxBatchSize: number;\n\tprivate readonly maxBufferSize: number;\n\tprivate readonly maxRetries: number;\n\tprivate readonly retryBaseDelayMs: number;\n\tprivate readonly retryMaxDelayMs: number;\n\tprivate readonly shutdownTimeoutMs: number;\n\tprivate readonly sdkVersion?: string;\n\tprivate readonly fetchFn: typeof fetch;\n\tprivate readonly logger: Logger;\n\tprivate readonly now: () => Date;\n\tprivate readonly sleep: (delayMs: number) => Promise<void>;\n\tprivate readonly apiKey: string;\n\n\tprivate readonly buffer: V2EventEnvelope[] = [];\n\tprivate flushTimer: ReturnType<typeof setInterval> | undefined;\n\tprivate flushScheduled = false;\n\tprivate flushScheduledTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate flushInFlight: Promise<void> | undefined;\n\tprivate inFlightCount = 0;\n\tprivate isStopped = false;\n\tprivate isShuttingDown = false;\n\n\tconstructor(options: V2TransportOptions) {\n\t\tthis.endpointUrl = joinUrl(\n\t\t\toptions.apiUrl,\n\t\t\toptions.endpointPath ?? DEFAULT_ENDPOINT_PATH,\n\t\t);\n\t\tthis.flushIntervalMs = options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;\n\t\tthis.maxBatchSize = options.maxBatchSize ?? DEFAULT_MAX_BATCH_SIZE;\n\t\tthis.maxBufferSize = options.maxBufferSize ?? DEFAULT_MAX_BUFFER_SIZE;\n\t\tthis.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n\t\tthis.retryBaseDelayMs =\n\t\t\toptions.retryBaseDelayMs ?? DEFAULT_RETRY_BASE_DELAY_MS;\n\t\tthis.retryMaxDelayMs =\n\t\t\toptions.retryMaxDelayMs ?? DEFAULT_RETRY_MAX_DELAY_MS;\n\t\tthis.shutdownTimeoutMs =\n\t\t\toptions.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;\n\t\tthis.fetchFn = options.fetchFn ?? fetch;\n\t\tthis.logger = options.logger ?? console;\n\t\tthis.now = options.now ?? (() => new Date());\n\t\tthis.sleep =\n\t\t\toptions.sleep ??\n\t\t\t((delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)));\n\t\tthis.apiKey = options.apiKey;\n\t\tthis.sdkVersion = options.sdkVersion;\n\n\t\tif (this.flushIntervalMs > 0) {\n\t\t\tthis.flushTimer = setInterval(() => {\n\t\t\t\tvoid this.flush();\n\t\t\t}, this.flushIntervalMs);\n\t\t}\n\t}\n\n\tenqueue(event: V2EventEnvelope): void {\n\t\tif (this.isStopped || this.isShuttingDown) {\n\t\t\tthis.logger.warn(\n\t\t\t\t\"[WaniWani] Tracking transport is stopped, dropping event %s\",\n\t\t\t\tevent.id,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.buffer.length >= this.maxBufferSize) {\n\t\t\tconst dropCount = this.buffer.length - this.maxBufferSize + 1;\n\t\t\tthis.buffer.splice(0, dropCount);\n\t\t\tthis.logger.warn(\n\t\t\t\t\"[WaniWani] Tracking buffer overflow, dropped %d oldest event(s)\",\n\t\t\t\tdropCount,\n\t\t\t);\n\t\t}\n\n\t\tthis.buffer.push(event);\n\n\t\tif (this.buffer.length >= this.maxBatchSize) {\n\t\t\tvoid this.flush();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.scheduleMicroFlush();\n\t}\n\n\tpendingEvents(): number {\n\t\treturn this.buffer.length + this.inFlightCount;\n\t}\n\n\tasync flush(): Promise<void> {\n\t\tif (this.flushInFlight) {\n\t\t\treturn this.flushInFlight;\n\t\t}\n\t\tthis.flushInFlight = this.flushLoop().finally(() => {\n\t\t\tthis.flushInFlight = undefined;\n\t\t});\n\t\treturn this.flushInFlight;\n\t}\n\n\tasync shutdown(\n\t\toptions?: TrackingShutdownOptions,\n\t): Promise<TrackingShutdownResult> {\n\t\tthis.isShuttingDown = true;\n\t\tif (this.flushTimer) {\n\t\t\tclearInterval(this.flushTimer);\n\t\t\tthis.flushTimer = undefined;\n\t\t}\n\t\tif (this.flushScheduledTimer) {\n\t\t\tclearTimeout(this.flushScheduledTimer);\n\t\t\tthis.flushScheduledTimer = undefined;\n\t\t\tthis.flushScheduled = false;\n\t\t}\n\n\t\tconst timeoutMs = options?.timeoutMs ?? this.shutdownTimeoutMs;\n\t\tconst flushPromise = this.flush();\n\n\t\tif (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n\t\t\tawait flushPromise;\n\t\t\tthis.isStopped = true;\n\t\t\treturn { timedOut: false, pendingEvents: this.pendingEvents() };\n\t\t}\n\n\t\tconst timeoutSignal = Symbol(\"shutdown-timeout\");\n\t\tconst result = await Promise.race([\n\t\t\tflushPromise.then(() => \"flushed\" as const),\n\t\t\tthis.sleep(timeoutMs).then(() => timeoutSignal),\n\t\t]);\n\n\t\tif (result === timeoutSignal) {\n\t\t\tthis.isStopped = true;\n\t\t\treturn { timedOut: true, pendingEvents: this.pendingEvents() };\n\t\t}\n\n\t\tthis.isStopped = true;\n\t\treturn { timedOut: false, pendingEvents: this.pendingEvents() };\n\t}\n\n\tprivate scheduleMicroFlush(): void {\n\t\tif (this.flushScheduled) {\n\t\t\treturn;\n\t\t}\n\t\tthis.flushScheduled = true;\n\t\tthis.flushScheduledTimer = setTimeout(() => {\n\t\t\tthis.flushScheduledTimer = undefined;\n\t\t\tthis.flushScheduled = false;\n\t\t\tvoid this.flush();\n\t\t}, 0);\n\t}\n\n\tprivate async flushLoop(): Promise<void> {\n\t\twhile (this.buffer.length > 0 && !this.isStopped) {\n\t\t\tconst batch = this.buffer.splice(0, this.maxBatchSize);\n\t\t\tawait this.sendBatchWithRetry(batch);\n\t\t}\n\t}\n\n\tprivate async sendBatchWithRetry(batch: V2EventEnvelope[]): Promise<void> {\n\t\tlet attempt = 0;\n\t\tlet pendingBatch = batch;\n\n\t\twhile (pendingBatch.length > 0 && !this.isStopped) {\n\t\t\tthis.inFlightCount = pendingBatch.length;\n\t\t\tconst result = await this.sendBatchOnce(pendingBatch);\n\t\t\tthis.inFlightCount = 0;\n\n\t\t\tswitch (result.kind) {\n\t\t\t\tcase \"success\":\n\t\t\t\t\treturn;\n\t\t\t\tcase \"auth\":\n\t\t\t\t\tthis.stopTransportForAuthFailure(result.status, pendingBatch.length);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"permanent\":\n\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\"[WaniWani] Dropping %d event(s) after permanent failure: %s\",\n\t\t\t\t\t\tpendingBatch.length,\n\t\t\t\t\t\tresult.reason,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"retryable\":\n\t\t\t\t\tif (attempt >= this.maxRetries) {\n\t\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\t\"[WaniWani] Dropping %d event(s) after retry exhaustion: %s\",\n\t\t\t\t\t\t\tpendingBatch.length,\n\t\t\t\t\t\t\tresult.reason,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tawait this.sleep(this.backoffDelayMs(attempt));\n\t\t\t\t\tattempt += 1;\n\t\t\t\t\tcontinue;\n\t\t\t\tcase \"partial\":\n\t\t\t\t\tif (result.permanent.length > 0) {\n\t\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\t\"[WaniWani] Dropping %d event(s) rejected as permanent\",\n\t\t\t\t\t\t\tresult.permanent.length,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (result.retryable.length === 0) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (attempt >= this.maxRetries) {\n\t\t\t\t\t\tthis.logger.error(\n\t\t\t\t\t\t\t\"[WaniWani] Dropping %d retryable event(s) after retry exhaustion\",\n\t\t\t\t\t\t\tresult.retryable.length,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tpendingBatch = result.retryable;\n\t\t\t\t\tawait this.sleep(this.backoffDelayMs(attempt));\n\t\t\t\t\tattempt += 1;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async sendBatchOnce(\n\t\tevents: V2EventEnvelope[],\n\t): Promise<SendBatchResult> {\n\t\tlet response: Response;\n\n\t\ttry {\n\t\t\tresponse = await this.fetchFn(this.endpointUrl, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tAuthorization: `Bearer ${this.apiKey}`,\n\t\t\t\t\t\"X-WaniWani-SDK\": SDK_NAME,\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(this.makeBatchRequest(events)),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tkind: \"retryable\",\n\t\t\t\treason: getErrorMessage(error),\n\t\t\t};\n\t\t}\n\n\t\tif (AUTH_FAILURE_STATUS.has(response.status)) {\n\t\t\treturn { kind: \"auth\", status: response.status };\n\t\t}\n\n\t\tif (RETRYABLE_STATUS.has(response.status)) {\n\t\t\treturn {\n\t\t\t\tkind: \"retryable\",\n\t\t\t\treason: `HTTP ${response.status}`,\n\t\t\t};\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\treturn {\n\t\t\t\tkind: \"permanent\",\n\t\t\t\treason: `HTTP ${response.status}`,\n\t\t\t};\n\t\t}\n\n\t\tconst data = await parseJsonResponse<V2BatchResponse>(response);\n\t\tif (!data?.rejected || data.rejected.length === 0) {\n\t\t\treturn { kind: \"success\" };\n\t\t}\n\n\t\tconst partial = this.classifyRejectedEvents(events, data.rejected);\n\t\tif (partial.retryable.length === 0 && partial.permanent.length === 0) {\n\t\t\treturn { kind: \"success\" };\n\t\t}\n\n\t\treturn {\n\t\t\tkind: \"partial\",\n\t\t\tretryable: partial.retryable,\n\t\t\tpermanent: partial.permanent,\n\t\t};\n\t}\n\n\tprivate makeBatchRequest(events: V2EventEnvelope[]): V2BatchRequest {\n\t\treturn {\n\t\t\tsentAt: this.now().toISOString(),\n\t\t\tsource: {\n\t\t\t\tsdk: SDK_NAME,\n\t\t\t\tversion: this.sdkVersion ?? \"0.0.0\",\n\t\t\t},\n\t\t\tevents,\n\t\t};\n\t}\n\n\tprivate classifyRejectedEvents(\n\t\tevents: V2EventEnvelope[],\n\t\trejected: V2BatchRejectedEvent[],\n\t): {\n\t\tretryable: V2EventEnvelope[];\n\t\tpermanent: V2EventEnvelope[];\n\t} {\n\t\tconst byId = new Map(events.map((event) => [event.id, event]));\n\t\tconst retryable: V2EventEnvelope[] = [];\n\t\tconst permanent: V2EventEnvelope[] = [];\n\n\t\tfor (const rejectedEvent of rejected) {\n\t\t\tconst event = byId.get(rejectedEvent.eventId);\n\t\t\tif (!event) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (isRetryableRejectedEvent(rejectedEvent)) {\n\t\t\t\tretryable.push(event);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tpermanent.push(event);\n\t\t}\n\n\t\treturn { retryable, permanent };\n\t}\n\n\tprivate backoffDelayMs(attempt: number): number {\n\t\tconst rawDelay = this.retryBaseDelayMs * 2 ** attempt;\n\t\treturn Math.min(rawDelay, this.retryMaxDelayMs);\n\t}\n\n\tprivate stopTransportForAuthFailure(\n\t\tstatus: number,\n\t\trejectedCount: number,\n\t): void {\n\t\tthis.isStopped = true;\n\t\tconst buffered = this.buffer.length;\n\t\tthis.buffer.splice(0, buffered);\n\t\tthis.logger.error(\n\t\t\t\"[WaniWani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)\",\n\t\t\tstatus,\n\t\t\trejectedCount + buffered,\n\t\t);\n\t}\n}\n\nfunction isRetryableRejectedEvent(\n\trejectedEvent: V2BatchRejectedEvent,\n): boolean {\n\tif (rejectedEvent.retryable === true) {\n\t\treturn true;\n\t}\n\tconst code = rejectedEvent.code.toLowerCase();\n\treturn (\n\t\tcode.includes(\"timeout\") ||\n\t\tcode.includes(\"temporary\") ||\n\t\tcode.includes(\"unavailable\") ||\n\t\tcode.includes(\"rate_limit\") ||\n\t\tcode.includes(\"transient\") ||\n\t\tcode.includes(\"server\")\n\t);\n}\n\nasync function parseJsonResponse<T>(\n\tresponse: Response,\n): Promise<T | undefined> {\n\tconst body = await response.text();\n\tif (!body) {\n\t\treturn undefined;\n\t}\n\ttry {\n\t\treturn JSON.parse(body) as T;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction joinUrl(apiUrl: string, endpointPath: string): string {\n\tconst normalizedBase = apiUrl.endsWith(\"/\") ? apiUrl : `${apiUrl}/`;\n\tconst normalizedPath = endpointPath.startsWith(\"/\")\n\t\t? endpointPath.slice(1)\n\t\t: endpointPath;\n\treturn `${normalizedBase}${normalizedPath}`;\n}\n\nfunction getErrorMessage(error: unknown): string {\n\tif (error instanceof Error) {\n\t\treturn error.message;\n\t}\n\treturn String(error);\n}\n","// Tracking Module\n\nimport type { InternalConfig } from \"../types.js\";\nimport type {\n\tTrackInput,\n\tTrackingClient,\n\tTrackingShutdownOptions,\n} from \"./@types.js\";\nimport { mapTrackEventToV2 } from \"./mapper.js\";\nimport { createV2BatchTransport } from \"./transport.js\";\n\n// Re-export types\nexport type {\n\tEventType,\n\tLegacyTrackEvent,\n\tLinkClickedProperties,\n\tPurchaseCompletedProperties,\n\tQuoteSucceededProperties,\n\tToolCalledProperties,\n\tTrackEvent,\n\tTrackInput,\n\tTrackingClient,\n\tTrackingConfig,\n\tTrackingShutdownOptions,\n\tTrackingShutdownResult,\n} from \"./@types.js\";\nexport { createEventId, mapTrackEventToV2 } from \"./mapper.js\";\nexport type {\n\tV2BatchRejectedEvent,\n\tV2BatchRequest,\n\tV2BatchResponse,\n\tV2CorrelationIds,\n\tV2EnvelopeType,\n\tV2EventEnvelope,\n} from \"./v2-types.js\";\n\nexport function createTrackingClient(config: InternalConfig): TrackingClient {\n\tconst { apiUrl, apiKey, tracking } = config;\n\n\tfunction requireApiKey(): string {\n\t\tif (!apiKey) {\n\t\t\tthrow new Error(\"WANIWANI_API_KEY is not set\");\n\t\t}\n\t\treturn apiKey;\n\t}\n\n\tconst transport = apiKey\n\t\t? createV2BatchTransport({\n\t\t\t\tapiUrl,\n\t\t\t\tapiKey,\n\t\t\t\tendpointPath: tracking.endpointPath,\n\t\t\t\tflushIntervalMs: tracking.flushIntervalMs,\n\t\t\t\tmaxBatchSize: tracking.maxBatchSize,\n\t\t\t\tmaxBufferSize: tracking.maxBufferSize,\n\t\t\t\tmaxRetries: tracking.maxRetries,\n\t\t\t\tretryBaseDelayMs: tracking.retryBaseDelayMs,\n\t\t\t\tretryMaxDelayMs: tracking.retryMaxDelayMs,\n\t\t\t\tshutdownTimeoutMs: tracking.shutdownTimeoutMs,\n\t\t\t})\n\t\t: undefined;\n\n\tconst client: TrackingClient = {\n\t\tasync identify(\n\t\t\tuserId: string,\n\t\t\tproperties?: Record<string, unknown>,\n\t\t\tmeta?: Record<string, unknown>,\n\t\t): Promise<{ eventId: string }> {\n\t\t\trequireApiKey();\n\t\t\tconst mappedEvent = mapTrackEventToV2({\n\t\t\t\tevent: \"user.identified\",\n\t\t\t\texternalUserId: userId,\n\t\t\t\tproperties,\n\t\t\t\tmeta,\n\t\t\t});\n\t\t\ttransport?.enqueue(mappedEvent);\n\t\t\treturn { eventId: mappedEvent.id };\n\t\t},\n\t\tasync track(event: TrackInput): Promise<{ eventId: string }> {\n\t\t\trequireApiKey();\n\t\t\tconst mappedEvent = mapTrackEventToV2(event);\n\t\t\ttransport?.enqueue(mappedEvent);\n\t\t\treturn { eventId: mappedEvent.id };\n\t\t},\n\t\tasync flush(): Promise<void> {\n\t\t\trequireApiKey();\n\t\t\tawait transport?.flush();\n\t\t},\n\t\tasync shutdown(options?: TrackingShutdownOptions) {\n\t\t\trequireApiKey();\n\t\t\treturn (\n\t\t\t\t(await transport?.shutdown({\n\t\t\t\t\ttimeoutMs: options?.timeoutMs ?? tracking.shutdownTimeoutMs,\n\t\t\t\t})) ?? { timedOut: false, pendingEvents: 0 }\n\t\t\t);\n\t\t},\n\t};\n\n\tif (transport) {\n\t\tattachShutdownHooks(client, tracking.shutdownTimeoutMs);\n\t}\n\treturn client;\n}\n\nfunction attachShutdownHooks(\n\tclient: TrackingClient,\n\tdefaultTimeoutMs: number,\n): void {\n\tif (\n\t\ttypeof process === \"undefined\" ||\n\t\ttypeof process.once !== \"function\" ||\n\t\ttypeof process.on !== \"function\"\n\t) {\n\t\treturn;\n\t}\n\n\tconst shutdown = () => {\n\t\tvoid client.shutdown({ timeoutMs: defaultTimeoutMs });\n\t};\n\n\tprocess.once(\"beforeExit\", shutdown);\n\tprocess.once(\"SIGINT\", shutdown);\n\tprocess.once(\"SIGTERM\", shutdown);\n}\n","// WaniWani SDK - Main Entry\n\nimport { createKbClient } from \"./kb/client.js\";\nimport type { WaniWaniProjectConfig } from \"./project-config.js\";\nimport { getGlobalConfig } from \"./project-config.js\";\nimport { createTrackingClient } from \"./tracking/index.js\";\nimport type { WaniWaniClient, WaniWaniConfig } from \"./types.js\";\n\n/**\n * Create a WaniWani SDK client\n *\n * @param config - Configuration options. When omitted, reads from the global\n * config registered by `defineConfig()`, then falls back to env vars.\n * @returns A fully typed WaniWani client\n *\n * @example\n * ```typescript\n * import { waniwani } from \"@waniwani/sdk\";\n * import { toNextJsHandler } from \"@waniwani/sdk/next-js\";\n *\n * const wani = waniwani({ apiKey: \"...\" });\n *\n * // Next.js route handler\n * export const { GET, POST } = toNextJsHandler(wani, {\n * chat: { systemPrompt: \"You are a helpful assistant.\" },\n * });\n * ```\n */\nexport function waniwani(\n\tconfig?: WaniWaniConfig | WaniWaniProjectConfig,\n): WaniWaniClient {\n\tconst effective = config ?? getGlobalConfig();\n\n\tconst apiUrl = effective?.apiUrl ?? \"https://app.waniwani.ai\";\n\tconst apiKey = effective?.apiKey ?? process.env.WANIWANI_API_KEY;\n\tconst trackingConfig = {\n\t\tendpointPath:\n\t\t\teffective?.tracking?.endpointPath ?? \"/api/mcp/events/v2/batch\",\n\t\tflushIntervalMs: effective?.tracking?.flushIntervalMs ?? 1_000,\n\t\tmaxBatchSize: effective?.tracking?.maxBatchSize ?? 20,\n\t\tmaxBufferSize: effective?.tracking?.maxBufferSize ?? 1_000,\n\t\tmaxRetries: effective?.tracking?.maxRetries ?? 3,\n\t\tretryBaseDelayMs: effective?.tracking?.retryBaseDelayMs ?? 200,\n\t\tretryMaxDelayMs: effective?.tracking?.retryMaxDelayMs ?? 2_000,\n\t\tshutdownTimeoutMs: effective?.tracking?.shutdownTimeoutMs ?? 2_000,\n\t};\n\n\tconst internalConfig = { apiUrl, apiKey, tracking: trackingConfig };\n\n\t// Compose client from modules\n\tconst trackingClient = createTrackingClient(internalConfig);\n\tconst kbClient = createKbClient(internalConfig);\n\n\treturn {\n\t\t...trackingClient,\n\t\tkb: kbClient,\n\t\t_config: internalConfig,\n\t};\n}\n"],"mappings":"AAEO,IAAMA,EAAN,cAA4B,KAAM,CACxC,YACCC,EACOC,EACN,CACD,MAAMD,CAAO,EAFN,YAAAC,EAGP,KAAK,KAAO,eACb,CACD,ECsDA,IAAMC,EAAa,sBAYZ,SAASC,EACfC,EACwB,CACxB,OAAC,WAAuCF,CAAU,EAAIE,EAC/CA,CACR,CAOO,SAASC,GAAqD,CACpE,OAAQ,WAAuCH,CAAU,CAG1D,CC/EA,IAAMI,EAAW,gBAEV,SAASC,EAAeC,EAAkC,CAChE,GAAM,CAAE,OAAAC,EAAQ,OAAAC,CAAO,EAAIF,EAE3B,SAASG,GAAwB,CAChC,GAAI,CAACD,EACJ,MAAM,IAAI,MAAM,6BAA6B,EAE9C,OAAOA,CACR,CAEA,eAAeE,EACdC,EACAC,EACAC,EACa,CACb,IAAMC,EAAML,EAAc,EACpBM,EAAM,GAAGR,EAAO,QAAQ,MAAO,EAAE,CAAC,GAAGK,CAAI,GAEzCI,EAAkC,CACvC,cAAe,UAAUF,CAAG,GAC5B,iBAAkBV,CACnB,EAEMa,EAAoB,CAAE,OAAAN,EAAQ,QAAAK,CAAQ,EAExCH,IAAS,SACZG,EAAQ,cAAc,EAAI,mBAC1BC,EAAK,KAAO,KAAK,UAAUJ,CAAI,GAGhC,IAAMK,EAAW,MAAM,MAAMH,EAAKE,CAAI,EAEtC,GAAI,CAACC,EAAS,GAAI,CACjB,IAAMC,EAAO,MAAMD,EAAS,KAAK,EAAE,MAAM,IAAM,EAAE,EACjD,MAAM,IAAIE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A,CAAQ,EAC/B,QAAQ,KAAK,UAAWA,CAAQ,CACjC,CC9FO,SAASC,GACfC,EACiB,CACjB,IAAMC,EAAYD,GAAUE,EAAgB,EAEtCC,EAASF,GAAW,QAAU,0BAC9BG,EAASH,GAAW,QAAU,QAAQ,IAAI,iBAC1CI,EAAiB,CACtB,aACCJ,GAAW,UAAU,cAAgB,2BACtC,gBAAiBA,GAAW,UAAU,iBAAmB,IACzD,aAAcA,GAAW,UAAU,cAAgB,GACnD,cAAeA,GAAW,UAAU,eAAiB,IACrD,WAAYA,GAAW,UAAU,YAAc,EAC/C,iBAAkBA,GAAW,UAAU,kBAAoB,IAC3D,gBAAiBA,GAAW,UAAU,iBAAmB,IACzD,kBAAmBA,GAAW,UAAU,mBAAqB,GAC9D,EAEMK,EAAiB,CAAE,OAAAH,EAAQ,OAAAC,EAAQ,SAAUC,CAAe,EAG5DE,EAAiBC,EAAqBF,CAAc,EACpDG,EAAWC,EAAeJ,CAAc,EAE9C,MAAO,CACN,GAAGC,EACH,GAAIE,EACJ,QAASH,CACV,CACD","names":["WaniWaniError","message","status","GLOBAL_KEY","defineConfig","config","getGlobalConfig","SDK_NAME","createKbClient","config","apiUrl","apiKey","requireApiKey","request","method","path","body","key","url","headers","init","response","text","WaniWaniError","files","query","options","pickFirst","meta","keys","key","value","SESSION_ID_KEYS","REQUEST_ID_KEYS","TRACE_ID_KEYS","EXTERNAL_USER_ID_KEYS","CORRELATION_ID_KEYS","extractSessionId","extractRequestId","extractTraceId","extractExternalUserId","extractCorrelationId","SOURCE_SESSION_KEYS","extractSource","explicit","source","DEFAULT_SOURCE","mapTrackEventToV2","input","options","now","generateId","createEventId","eventName","resolveEventName","meta","toRecord","metadata","correlation","resolveCorrelationIds","eventId","takeNonEmptyString","timestamp","normalizeTimestamp","source","extractSource","rawLegacy","isLegacyTrackEvent","mappedMetadata","mapProperties","legacyProperties","mapLegacyProperties","explicitProperties","properties","requestId","extractRequestId","sessionId","extractSessionId","traceId","extractTraceId","externalUserId","extractExternalUserId","correlationId","extractCorrelationId","date","value","DEFAULT_ENDPOINT_PATH","SDK_NAME","AUTH_FAILURE_STATUS","RETRYABLE_STATUS","createV2BatchTransport","options","BatchingV2Transport","joinUrl","DEFAULT_ENDPOINT_PATH","delayMs","resolve","event","dropCount","timeoutMs","flushPromise","timeoutSignal","batch","attempt","pendingBatch","result","events","response","error","getErrorMessage","data","parseJsonResponse","partial","rejected","byId","retryable","permanent","rejectedEvent","isRetryableRejectedEvent","rawDelay","status","rejectedCount","buffered","code","body","apiUrl","endpointPath","normalizedBase","normalizedPath","createTrackingClient","config","apiUrl","apiKey","tracking","requireApiKey","transport","createV2BatchTransport","client","userId","properties","meta","mappedEvent","mapTrackEventToV2","event","options","attachShutdownHooks","defaultTimeoutMs","shutdown","waniwani","config","effective","getGlobalConfig","apiUrl","apiKey","trackingConfig","internalConfig","trackingClient","createTrackingClient","kbClient","createKbClient"]}
package/dist/mcp/index.js CHANGED
@@ -1,7 +1,7 @@
1
- function X(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function Ye(){return X()==="openai"}function Ge(){return X()==="mcp-apps"}var R="__start__",C="__end__",le=Symbol.for("waniwani.flow.interrupt"),fe=Symbol.for("waniwani.flow.widget");function ge(e,t){let n=t?.context,r=[];for(let[o,s]of Object.entries(e))if(typeof s=="object"&&s!==null&&"question"in s){let a=s;r.push({question:a.question,field:o,suggestions:a.suggestions,context:a.context,validate:a.validate})}return{__type:le,questions:r,context:n}}function me(e,t){return{__type:fe,tool:e,...t}}function we(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===le}function he(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===fe}import{z as B}from"zod";var Z="waniwani/client";function K(e){if(typeof e=="object"&&e!==null)return e[Z]}function ye(e,t){return{track(n){return e.track({...n,meta:{...t,...n.meta}})},identify(n,r){return e.identify(n,r,t)},kb:e.kb}}function N(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var Je=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","anthropic/sessionId"],Xe=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Ze=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],Qe=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],et=["correlationId","openai/requestId"];function _(e){return e?N(e,Je):void 0}function Te(e){return e?N(e,Xe):void 0}function ke(e){return e?N(e,Ze):void 0}function Se(e){return e?N(e,Qe):void 0}function ve(e){return e?N(e,et):void 0}var tt=[{key:"waniwani/sessionId",source:"chatbar"},{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"},{key:"anthropic/sessionId",source:"claude"}];function P(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 tt){let o=e[n];if(typeof o=="string"&&o.length>0)return r}}function xe(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function D(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 nt(e,t,n){let r=t.split("."),o=r.pop();if(!o)return;let s=e;for(let a of r)(s[a]==null||typeof s[a]!="object"||Array.isArray(s[a]))&&(s[a]={}),s=s[a];s[o]=n}function Re(e,t){let n=t.split("."),r=n.pop();if(!r)return;let o=e;for(let s of n){if(o==null||typeof o!="object")return;o=o[s]}o!=null&&typeof o=="object"&&delete o[r]}function Q(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?nt(t,n,r):t[n]=r;return t}function M(e,t){let n={...e};for(let[r,o]of Object.entries(t))o!==null&&typeof o=="object"&&!Array.isArray(o)&&n[r]!==null&&typeof n[r]=="object"&&!Array.isArray(n[r])?n[r]=M(n[r],o):n[r]=o;return n}function ee(e){return e!=null&&e!==""}async function W(e,t){return e.type==="direct"?e.to:e.condition(t)}function Ee(e,t,n,r){if(e.every(c=>ee(D(r,c.field))))return null;let o=e.filter(c=>!ee(D(r,c.field))),s=o.length===1,a=o[0];return{content:s&&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,...s&&a?{field:a.field}:{}}}}async function $(e,t,n,r,o,s,a){let i=e,c={...t},d=50,p=0;for(;p++<d;){if(i===C)return{content:{status:"complete"},flowTokenContent:{state:c}};let w=n.get(i);if(!w)return{content:{status:"error",error:`Unknown node: "${i}"`}};try{let u=await w({state:c,meta:s,interrupt:ge,showWidget:me,waniwani:a});if(we(u)){for(let y of u.questions)y.validate&&o.set(`${i}:${y.field}`,y.validate);let T=Ee(u.questions,u.context,i,c);if(T)return T;for(let y of u.questions){let x=o.get(`${i}:${y.field}`);if(x)try{let b=D(c,y.field),E=await x(b);E&&typeof E=="object"&&(c=M(c,E))}catch(b){let E=b instanceof Error?b.message:String(b);Re(c,y.field);let j=u.questions.map(I=>I.field===y.field?{...I,context:I.context?`ERROR: ${E}
1
+ function Z(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function Ye(){return Z()==="openai"}function Ge(){return Z()==="mcp-apps"}var R="__start__",C="__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,s]of Object.entries(e))if(typeof s=="object"&&s!==null&&"question"in s){let a=s;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:e,...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 q}from"zod";var Q="waniwani/client";function j(e){if(typeof e=="object"&&e!==null)return e[Q]}function Te(e,t){return{track(n){return e.track({...n,meta:{...t,...n.meta}})},identify(n,r){return e.identify(n,r,t)},kb:e.kb}}function N(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var Je=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","anthropic/sessionId"],Xe=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Ze=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],Qe=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],et=["correlationId","openai/requestId"];function _(e){return e?N(e,Je):void 0}function ke(e){return e?N(e,Xe):void 0}function Se(e){return e?N(e,Ze):void 0}function ve(e){return e?N(e,Qe):void 0}function xe(e){return e?N(e,et):void 0}var tt=[{key:"waniwani/sessionId",source:"chatbar"},{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"},{key:"anthropic/sessionId",source:"claude"}];function P(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 tt){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 D(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 nt(e,t,n){let r=t.split("."),o=r.pop();if(!o)return;let s=e;for(let a of r)(s[a]==null||typeof s[a]!="object"||Array.isArray(s[a]))&&(s[a]={}),s=s[a];s[o]=n}function Ee(e,t){let n=t.split("."),r=n.pop();if(!r)return;let o=e;for(let s of n){if(o==null||typeof o!="object")return;o=o[s]}o!=null&&typeof o=="object"&&delete o[r]}function ee(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?nt(t,n,r):t[n]=r;return t}function M(e,t){let n={...e};for(let[r,o]of Object.entries(t))o!==null&&typeof o=="object"&&!Array.isArray(o)&&n[r]!==null&&typeof n[r]=="object"&&!Array.isArray(n[r])?n[r]=M(n[r],o):n[r]=o;return n}function te(e){return e!=null&&e!==""}async function W(e,t){return e.type==="direct"?e.to:e.condition(t)}function Ie(e,t,n,r){if(e.every(c=>te(D(r,c.field))))return null;let o=e.filter(c=>!te(D(r,c.field))),s=o.length===1,a=o[0];return{content:s&&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,...s&&a?{field:a.field}:{}}}}async function $(e,t,n,r,o,s,a){let i=e,c={...t},d=50,p=0;for(;p++<d;){if(i===C)return{content:{status:"complete"},flowTokenContent:{state:c}};let w=n.get(i);if(!w)return{content:{status:"error",error:`Unknown node: "${i}"`}};try{let u=await w({state:c,meta:s,interrupt:me,showWidget:we,waniwani:a});if(he(u)){for(let y of u.questions)y.validate&&o.set(`${i}:${y.field}`,y.validate);let T=Ie(u.questions,u.context,i,c);if(T)return T;for(let y of u.questions){let x=o.get(`${i}:${y.field}`);if(x)try{let b=D(c,y.field),E=await x(b);E&&typeof E=="object"&&(c=M(c,E))}catch(b){let E=b instanceof Error?b.message:String(b);Ee(c,y.field);let K=u.questions.map(I=>I.field===y.field?{...I,context:I.context?`ERROR: ${E}
2
2
 
3
- ${I.context}`:`ERROR: ${E}`}:I),k=Ee(j,u.context,i,c);if(k)return k;break}}let l=r.get(i);if(!l)return{content:{status:"error",error:`No outgoing edge from node "${i}"`}};i=await W(l,c);continue}if(he(u)){let T=u.field;if(T&&ee(D(c,T))){let l=r.get(i);if(!l)return{content:{status:"error",error:`No outgoing edge from node "${i}"`}};i=await W(l,c);continue}return{content:{status:"widget",tool:u.tool.id,data:u.data,description:u.description,interactive:u.interactive!==!1},flowTokenContent:{step:i,state:c,field:T,widgetId:u.tool.id}}}c=M(c,u);let h=r.get(i);if(!h)return{content:{status:"error",error:`No outgoing edge from node "${i}"`}};i=await W(h,c)}catch(f){return{content:{status:"error",error:f instanceof Error?f.message:String(f)},flowTokenContent:{step:i,state:c}}}}return{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"}}}var rt="@waniwani/sdk",ot="https://app.waniwani.ai",F=class{baseUrl;apiKey;constructor(t){this.baseUrl=(t?.baseUrl??process.env.WANIWANI_API_URL??ot).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":rt},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;constructor(t){this.store=new F(t)}get(t){return this.store.get(t)}set(t,n){return this.store.set(t,n)}delete(t){return this.store.delete(t)}};function Ie(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 Ce(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=[];for(let[r,o]of Object.entries(e.state)){let s=xe(o);if(s){let a=o.description??"",i=Object.entries(s).map(([c,d])=>{let p=Ie(d);return p?`\`${r}.${c}\` (${p})`:`\`${r}.${c}\``}).join(", ");n.push(a?`\`${r}\` (${a}): ${i}`:`\`${r}\`: ${i}`)}else{let a=Ie(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 it={action:B.enum(["start","continue"]).describe('"start" to begin the flow, "continue" to resume after a pause (interrupt or widget)'),stateUpdates:B.record(B.string(),B.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 be(e){let{config:t,nodes:n,edges:r}=e,o=Ce(t),s=`${t.description}
5
- ${o}`,a=e.store??new U,i=new Map;async function c(d,p,w,f){if(d.action==="start"){let u=r.get(R);if(!u)return{content:{status:"error",error:"No start edge"}};let h=Q(d.stateUpdates??{}),T=await W(u,h);return $(T,h,n,r,i,w,f)}if(d.action==="continue"){if(!p)return{content:{status:"error",error:"No session ID available for continue action."}};let u=await a.get(p);if(!u)return{content:{status:"error",error:"Flow state not found. The flow may have expired."}};let h=u.state,T=u.step;if(!T)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let l=M(h,Q(d.stateUpdates??{}));if(u.widgetId){let y=r.get(T);if(!y)return{content:{status:"error",error:`No edge from step "${T}"`}};let x=await W(y,l);return $(x,l,n,r,i,w,f)}return $(T,l,n,r,i,w,f)}return{content:{status:"error",error:`Unknown action: "${d.action}"`}}}return{id:t.id,title:t.title,description:s,graph:e.graph,async register(d){d.registerTool(t.id,{title:t.title,description:s,inputSchema:it,annotations:t.annotations},(async(p,w)=>{let f=w,u=f._meta??{},h=_(u),T=K(f),l=await c(p,h,u,T);return h&&(l.flowTokenContent&&l.content.status!=="complete"?await a.set(h,l.flowTokenContent):l.content.status==="complete"&&await a.delete(h)),{content:[{type:"text",text:JSON.stringify(l.content,null,2)}],_meta:u,...l.content.status==="error"?{isError:!0}:{}}}))}}}function _e(e,t){let n=["flowchart TD"];n.push(` ${R}((Start))`);for(let[r]of e)n.push(` ${r}[${r}]`);n.push(` ${C}((End))`);for(let[r,o]of t)o.type==="direct"?n.push(` ${r} --> ${o.to}`):n.push(` ${r} -.-> ${r}_branch([?])`);return n.join(`
6
- `)}var A=class{nodes=new Map;edges=new Map;config;constructor(t){this.config=t}addNode(t,n){if(t===R||t===C)throw new Error(`"${t}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(t))throw new Error(`Node "${t}" already exists`);return this.nodes.set(t,n),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 _e(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return be({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>_e(n,r)})}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!==C&&!this.nodes.has(t.to))throw new Error(`START edge references non-existent node: "${t.to}"`);for(let[n,r]of this.edges){if(n!==R&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(r.type==="direct"&&r.to!==C&&!this.nodes.has(r.to))throw new Error(`Edge from "${n}" references non-existent node: "${r.to}"`)}for(let[n]of this.nodes)if(!this.edges.has(n))throw new Error(`Node "${n}" has no outgoing edge. Add one with .addEdge("${n}", ...) or .addConditionalEdge("${n}", ...)`)}};function Pe(e){return new A(e)}function Me(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function We(e,t){let n=t?.stateStore,r=[],o=`test-session-${Math.random().toString(36).slice(2,10)}`,s={registerTool:(...d)=>{r.push(d)}};await e.register(s);let a=r[0]?.[2];if(!a)throw new Error(`Flow "${e.id}" did not register a handler`);let i={_meta:{sessionId:o}};async function c(d){return{...d,decodedState:n?await n.get(o):null}}return{async start(d){let p=await a({action:"start",...d?{stateUpdates:d}:{}},i);return c(Me(p))},async continueWith(d){let p=await a({action:"continue",...d?{stateUpdates:d}:{}},i);return c(Me(p))},async lastState(){return n?n.get(o):null}}}var q="text/html+skybridge",L="text/html;profile=mcp-app",Fe=async(e,t)=>{let n=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${n}${t}`)).text()};function Ae(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function Ne(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 te(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:s,widgetDomain:a,prefersBorder:i=!0,autoHeight:c=!0}=e,d=e.widgetCSP??{connect_domains:[o],resource_domains:[o]};if(process.env.NODE_ENV==="development")try{let{hostname:l}=new URL(o);(l==="localhost"||l==="127.0.0.1")&&(d={...d,connect_domains:[...d.connect_domains||[],`ws://${l}:*`,`wss://${l}:*`],resource_domains:[...d.resource_domains||[],`http://${l}:*`]})}catch{}let p=`ui://widgets/apps-sdk/${t}.html`,w=`ui://widgets/ext-apps/${t}.html`,f=null,u=()=>(f||(f=Fe(o,s)),f),h=r;async function T(l){let y=await u();l.registerResource(`${t}-openai-widget`,p,{title:n,description:h,mimeType:q,_meta:{"openai/widgetDescription":h,"openai/widgetPrefersBorder":i}},async x=>({contents:[{uri:x.href,mimeType:q,text:y,_meta:Ae({description:h,prefersBorder:i,widgetDomain:a,widgetCSP:d})}]})),l.registerResource(`${t}-mcp-widget`,w,{title:n,description:h,mimeType:L,_meta:{ui:{prefersBorder:i}}},async x=>({contents:[{uri:x.href,mimeType:L,text:y,_meta:Ne({description:h,prefersBorder:i,widgetDomain:a,widgetCSP:d})}]}))}return{id:t,title:n,description:r,openaiUri:p,mcpUri:w,autoHeight:c,register:T}}function st(e,t){let{resource:n,description:r,inputSchema:o,annotations:s,autoInjectResultText:a=!0}=e,i=e.id??n?.id,c=e.title??n?.title;if(!i)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 d=n?te({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:i,title:c,description:r,async register(p){p.registerTool(i,{title:c,description:r,inputSchema:o,annotations:s,...d&&{_meta:d}},(async(w,f)=>{let u=f,h=u._meta??{},T=K(u),l=await t(w,{extra:{_meta:h},waniwani:T});return n&&l.data?{content:[{type:"text",text:l.text}],structuredContent:l.data,_meta:{...d,...h,...a===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:l.text}],...l.data?{structuredContent:l.data}:{},...a===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function at(e,t){await Promise.all(t.map(n=>n.register(e)))}var V=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var ct="@waniwani/sdk";function Ue(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(s,a,i){let c=r(),d=`${t.replace(/\/$/,"")}${a}`,p={Authorization:`Bearer ${c}`,"X-WaniWani-SDK":ct},w={method:s,headers:p};i!==void 0&&(p["Content-Type"]="application/json",w.body=JSON.stringify(i));let f=await fetch(d,w);if(!f.ok){let h=await f.text().catch(()=>"");throw new V(h||`KB API error: HTTP ${f.status}`,f.status)}return(await f.json()).data}return{async ingest(s){return o("POST","/api/mcp/kb/ingest",{files:s})},async search(s,a){return o("POST","/api/mcp/kb/search",{query:s,...a})},async sources(){return o("GET","/api/mcp/kb/sources")}}}var dt;function Oe(){return dt}var ut="@waniwani/sdk";function H(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??je,o=ft(e),s=z(e.meta),a=z(e.metadata),i=gt(e,s),c=v(e.eventId)??r(),d=mt(e.timestamp,n),p=v(e.source)??P(s)??t.source??ut,w=ne(e)?{...e}:void 0,f={...a};return Object.keys(s).length>0&&(f.meta=s),w&&(f.rawLegacy=w),{id:c,type:"mcp.event",name:o,source:p,timestamp:d,correlation:i,properties:pt(e,o),metadata:f,rawLegacy:w}}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 pt(e,t){if(!ne(e))return z(e.properties);let n=lt(e,t),r=z(e.properties);return{...n,...r}}function lt(e,t){switch(t){case"tool.called":{let n={};return v(e.toolName)&&(n.name=e.toolName),v(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),v(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return v(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),v(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function ft(e){return ne(e)?e.eventType:e.event}function gt(e,t){let n=v(e.requestId)??Te(t),r=v(e.sessionId)??_(t),o=v(e.traceId)??ke(t),s=v(e.externalUserId)??Se(t),a=v(e.correlationId)??ve(t)??n,i={};return r&&(i.sessionId=r),o&&(i.traceId=o),n&&(i.requestId=n),a&&(i.correlationId=a),s&&(i.externalUserId=s),i}function mt(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 z(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function v(e){if(typeof e=="string"&&e.trim().length!==0)return e}function ne(e){return"eventType"in e}var wt="/api/mcp/events/v2/batch";var Ke="@waniwani/sdk",ht=new Set([401,403]),yt=new Set([408,425,429,500,502,503,504]);function $e(e){return new re(e)}var re=class{endpointUrl;flushIntervalMs;maxBatchSize;maxBufferSize;maxRetries;retryBaseDelayMs;retryMaxDelayMs;shutdownTimeoutMs;sdkVersion;fetchFn;logger;now;sleep;apiKey;buffer=[];flushTimer;flushScheduled=!1;flushScheduledTimer;flushInFlight;inFlightCount=0;isStopped=!1;isShuttingDown=!1;constructor(t){this.endpointUrl=St(t.apiUrl,t.endpointPath??wt),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(s){return{kind:"retryable",reason:vt(s)}}if(ht.has(n.status))return{kind:"auth",status:n.status};if(yt.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await kt(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=[],s=[];for(let a of n){let i=r.get(a.eventId);if(i){if(Tt(a)){o.push(i);continue}s.push(i)}}return{retryable:o,permanent:s}}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 Tt(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 kt(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function St(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function vt(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 s=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(i,c,d){o();let p=H({event:"user.identified",externalUserId:i,properties:c,meta:d});return s?.enqueue(p),{eventId:p.id}},async track(i){o();let c=H(i);return s?.enqueue(c),{eventId:c.id}},async flush(){o(),await s?.flush()},async shutdown(i){return o(),await s?.shutdown({timeoutMs:i?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return s&&xt(a,r.shutdownTimeoutMs),a}function xt(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 Y(e){let t=e??Oe(),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},s={apiUrl:n,apiKey:r,tracking:o},a=Be(s),i=Ue(s);return{...a,kb:i,_config:s}}function Rt(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 Et(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=Y(t)),n}return async function(s){let a;try{a=await s.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 i=r(),c=[];for(let d of a.events){let p=Rt(d),w=await i.track(p);c.push(w.eventId)}return await i.flush(),new Response(JSON.stringify({ok:!0,accepted:c.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(i){let c=i instanceof Error?i.message:"Unknown error";return new Response(JSON.stringify({error:c}),{status:500,headers:{"Content-Type":"application/json"}})}}}var G=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=It(this.config.apiUrl,"/api/mcp/widget-tokens"),o={};t&&(o.sessionId=t),n&&(o.traceId=n);try{let s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o)});if(!s.ok)return null;let a=await s.json(),i=a.data&&typeof a.data=="object"?a.data:a,c=new Date(i.expiresAt).getTime();return!i.token||Number.isNaN(c)?null:(this.cached={token:i.token,expiresAt:c},i.token)}catch{return null}}};function It(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}var qe="waniwani/sessionId",oe="waniwani/geoLocation",ie="waniwani/userLocation";function S(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function O(e){if(!S(e))return;let t=e._meta;return S(t)?t:void 0}function se(e){if(!S(e))return;let t=e.content;return Array.isArray(t)?t.find(r=>S(r)&&r.type==="text"&&typeof r.text=="string")?.text:void 0}function Ct(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function ae(e,t,n,r,o,s){let a=Ct(e,n.toolType),i=O(t);return console.log("[waniwani:debug] buildTrackInput meta:",JSON.stringify(i),"-> source:",P(i)),{event:"tool.called",properties:{name:e,type:a,...r??{},...s?.input!==void 0&&{input:s.input},...s?.output!==void 0&&{output:s.output}},meta:i,source:P(i),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(!S(e))return;S(e._meta)||(e._meta={});let s=e._meta,a=S(s.waniwani)?s.waniwani:void 0,i={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let w=await t.getToken();w&&(i.token=w)}catch(w){o?.(ue(w))}let c=_(s);c&&(i.sessionId||(i.sessionId=c));let d=ze(s);d!==void 0&&(i.geoLocation||(i.geoLocation=d));let p=P(O(r));p&&!i.source&&(i.source=p),s.waniwani=i}function Ve(e,t){let n=O(t);if(!n||!S(e))return;S(e._meta)||(e._meta={});let r=e._meta,o=_(n);o&&!r[qe]&&(r[qe]=o);let s=ze(n);s&&(r[oe]||(r[oe]=s),r[ie]||(r[ie]=s))}function ze(e){if(!e)return;let t=e[oe]??e[ie];if(S(t)||typeof t=="string")return t}function ue(e){return e instanceof Error?e:new Error(String(e))}var He="https://app.waniwani.ai";function bt(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??Y(),s=r.injectWidgetToken!==!1,a=null;function i(){if(a)return a;let d=o._config.apiKey;return d?(a=new G({apiUrl:o._config.apiUrl??He,apiKey:d}),a):null}let c=e.registerTool.bind(e);return n.registerTool=((...d)=>{let[p,w,f]=d,u=typeof p=="string"&&p.trim().length>0?p:"unknown";if(typeof f!="function")return c(...d);let h=f;return c(p,w,async(l,y)=>{let x=O(y)??{},b=ye(o,x);S(y)&&(y[Z]=b);let E=performance.now(),j=e.server?.getClientVersion?.();try{let k=await h(l,y),I=Math.round(performance.now()-E),J=S(k)&&k.isError===!0;if(J){let pe=se(k);console.error(`[waniwani] Tool "${u}" returned error${pe?`: ${pe}`:""}`)}return await ce(o,ae(u,y,r,{durationMs:I,status:J?"error":"ok",...J&&{errorMessage:se(k)??"Unknown tool error"}},j,{input:l,output:k}),r.onError),r.flushAfterToolCall&&await de(o,r.onError),Ve(k,y),s&&await Le(k,i(),o._config.apiUrl??He,y,r.onError),k}catch(k){let I=Math.round(performance.now()-E);throw await ce(o,ae(u,y,r,{durationMs:I,status:"error",errorMessage:k instanceof Error?k.message:String(k)},j,{input:l}),r.onError),r.flushAfterToolCall&&await de(o,r.onError),k}})}),n}export{C as END,R as START,A as StateGraph,F as WaniwaniKvStore,Pe as createFlow,We as createFlowTestHarness,De as createResource,st as createTool,Et as createTrackingRoute,X as detectPlatform,Ge as isMCPApps,Ye as isOpenAI,at as registerTools,bt as withWaniwani};
3
+ ${I.context}`:`ERROR: ${E}`}:I),k=Ie(K,u.context,i,c);if(k)return k;break}}let l=r.get(i);if(!l)return{content:{status:"error",error:`No outgoing edge from node "${i}"`}};i=await W(l,c);continue}if(ye(u)){let T=u.field;if(T&&te(D(c,T))){let l=r.get(i);if(!l)return{content:{status:"error",error:`No outgoing edge from node "${i}"`}};i=await W(l,c);continue}return{content:{status:"widget",tool:u.tool.id,data:u.data,description:u.description,interactive:u.interactive!==!1},flowTokenContent:{step:i,state:c,field:T,widgetId:u.tool.id}}}c=M(c,u);let h=r.get(i);if(!h)return{content:{status:"error",error:`No outgoing edge from node "${i}"`}};i=await W(h,c)}catch(f){return{content:{status:"error",error:f instanceof Error?f.message:String(f)},flowTokenContent:{step:i,state:c}}}}return{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"}}}var rt="__waniwani_config__";function B(){return globalThis[rt]}var ot="@waniwani/sdk",it="https://app.waniwani.ai",F=class{baseUrl;apiKey;constructor(t){let n=B();this.baseUrl=(t?.baseUrl??process.env.WANIWANI_API_URL??n?.apiUrl??it).replace(/\/$/,""),this.apiKey=t?.apiKey??process.env.WANIWANI_API_KEY??n?.apiKey}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":ot},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;constructor(t){this.store=new F(t)}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. 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 s=Re(o);if(s){let a=o.description??"",i=Object.entries(s).map(([c,d])=>{let p=Ce(d);return p?`\`${r}.${c}\` (${p})`:`\`${r}.${c}\``}).join(", ");n.push(a?`\`${r}\` (${a}): ${i}`:`\`${r}\`: ${i}`)}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 st={action:q.enum(["start","continue"]).describe('"start" to begin the flow, "continue" to resume after a pause (interrupt or widget)'),stateUpdates:q.record(q.string(),q.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),s=`${t.description}
5
+ ${o}`,a=e.store??new U,i=new Map;async function c(d,p,w,f){if(d.action==="start"){let u=r.get(R);if(!u)return{content:{status:"error",error:"No start edge"}};let h=ee(d.stateUpdates??{}),T=await W(u,h);return $(T,h,n,r,i,w,f)}if(d.action==="continue"){if(!p)return{content:{status:"error",error:"No session ID available for continue action."}};let u=await a.get(p);if(!u)return{content:{status:"error",error:"Flow state not found. The flow may have expired."}};let h=u.state,T=u.step;if(!T)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let l=M(h,ee(d.stateUpdates??{}));if(u.widgetId){let y=r.get(T);if(!y)return{content:{status:"error",error:`No edge from step "${T}"`}};let x=await W(y,l);return $(x,l,n,r,i,w,f)}return $(T,l,n,r,i,w,f)}return{content:{status:"error",error:`Unknown action: "${d.action}"`}}}return{id:t.id,title:t.title,description:s,graph:e.graph,async register(d){d.registerTool(t.id,{title:t.title,description:s,inputSchema:st,annotations:t.annotations},(async(p,w)=>{let f=w,u=f._meta??{},h=_(u),T=j(f),l=await c(p,h,u,T);return h&&(l.flowTokenContent&&l.content.status!=="complete"?await a.set(h,l.flowTokenContent):l.content.status==="complete"&&await a.delete(h)),{content:[{type:"text",text:JSON.stringify(l.content,null,2)}],_meta:u,...l.content.status==="error"?{isError:!0}:{}}}))}}}function Pe(e,t){let n=["flowchart TD"];n.push(` ${R}((Start))`);for(let[r]of e)n.push(` ${r}[${r}]`);n.push(` ${C}((End))`);for(let[r,o]of t)o.type==="direct"?n.push(` ${r} --> ${o.to}`):n.push(` ${r} -.-> ${r}_branch([?])`);return n.join(`
6
+ `)}var A=class{nodes=new Map;edges=new Map;config;constructor(t){this.config=t}addNode(t,n){if(t===R||t===C)throw new Error(`"${t}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(t))throw new Error(`Node "${t}" already exists`);return this.nodes.set(t,n),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(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!==C&&!this.nodes.has(t.to))throw new Error(`START edge references non-existent node: "${t.to}"`);for(let[n,r]of this.edges){if(n!==R&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(r.type==="direct"&&r.to!==C&&!this.nodes.has(r.to))throw new Error(`Edge from "${n}" references non-existent node: "${r.to}"`)}for(let[n]of this.nodes)if(!this.edges.has(n))throw new Error(`Node "${n}" has no outgoing edge. Add one with .addEdge("${n}", ...) or .addConditionalEdge("${n}", ...)`)}};function Me(e){return new A(e)}function We(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)}`,s={registerTool:(...d)=>{r.push(d)}};await e.register(s);let a=r[0]?.[2];if(!a)throw new Error(`Flow "${e.id}" did not register a handler`);let i={_meta:{sessionId:o}};async function c(d){return{...d,decodedState:n?await n.get(o):null}}return{async start(d){let p=await a({action:"start",...d?{stateUpdates:d}:{}},i);return c(We(p))},async continueWith(d){let p=await a({action:"continue",...d?{stateUpdates:d}:{}},i);return c(We(p))},async lastState(){return n?n.get(o):null}}}var L="text/html+skybridge",V="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 ne(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:s,widgetDomain:a,prefersBorder:i=!0,autoHeight:c=!0}=e,d=e.widgetCSP??{connect_domains:[o],resource_domains:[o]};if(process.env.NODE_ENV==="development")try{let{hostname:l}=new URL(o);(l==="localhost"||l==="127.0.0.1")&&(d={...d,connect_domains:[...d.connect_domains||[],`ws://${l}:*`,`wss://${l}:*`],resource_domains:[...d.resource_domains||[],`http://${l}:*`]})}catch{}let p=`ui://widgets/apps-sdk/${t}.html`,w=`ui://widgets/ext-apps/${t}.html`,f=null,u=()=>(f||(f=Ae(o,s)),f),h=r;async function T(l){let y=await u();l.registerResource(`${t}-openai-widget`,p,{title:n,description:h,mimeType:L,_meta:{"openai/widgetDescription":h,"openai/widgetPrefersBorder":i}},async x=>({contents:[{uri:x.href,mimeType:L,text:y,_meta:Ne({description:h,prefersBorder:i,widgetDomain:a,widgetCSP:d})}]})),l.registerResource(`${t}-mcp-widget`,w,{title:n,description:h,mimeType:V,_meta:{ui:{prefersBorder:i}}},async x=>({contents:[{uri:x.href,mimeType:V,text:y,_meta:De({description:h,prefersBorder:i,widgetDomain:a,widgetCSP:d})}]}))}return{id:t,title:n,description:r,openaiUri:p,mcpUri:w,autoHeight:c,register:T}}function at(e,t){let{resource:n,description:r,inputSchema:o,annotations:s,autoInjectResultText:a=!0}=e,i=e.id??n?.id,c=e.title??n?.title;if(!i)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 d=n?ne({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:i,title:c,description:r,async register(p){p.registerTool(i,{title:c,description:r,inputSchema:o,annotations:s,...d&&{_meta:d}},(async(w,f)=>{let u=f,h=u._meta??{},T=j(u),l=await t(w,{extra:{_meta:h},waniwani:T});return n&&l.data?{content:[{type:"text",text:l.text}],structuredContent:l.data,_meta:{...d,...h,...a===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:l.text}],...l.data?{structuredContent:l.data}:{},...a===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function ct(e,t){await Promise.all(t.map(n=>n.register(e)))}var z=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var dt="@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(s,a,i){let c=r(),d=`${t.replace(/\/$/,"")}${a}`,p={Authorization:`Bearer ${c}`,"X-WaniWani-SDK":dt},w={method:s,headers:p};i!==void 0&&(p["Content-Type"]="application/json",w.body=JSON.stringify(i));let f=await fetch(d,w);if(!f.ok){let h=await f.text().catch(()=>"");throw new z(h||`KB API error: HTTP ${f.status}`,f.status)}return(await f.json()).data}return{async ingest(s){return o("POST","/api/mcp/kb/ingest",{files:s})},async search(s,a){return o("POST","/api/mcp/kb/search",{query:s,...a})},async sources(){return o("GET","/api/mcp/kb/sources")}}}var ut="@waniwani/sdk";function Y(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??Ke,o=ft(e),s=H(e.meta),a=H(e.metadata),i=gt(e,s),c=v(e.eventId)??r(),d=mt(e.timestamp,n),p=v(e.source)??P(s)??t.source??ut,w=re(e)?{...e}:void 0,f={...a};return Object.keys(s).length>0&&(f.meta=s),w&&(f.rawLegacy=w),{id:c,type:"mcp.event",name:o,source:p,timestamp:d,correlation:i,properties:pt(e,o),metadata:f,rawLegacy:w}}function Ke(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function pt(e,t){if(!re(e))return H(e.properties);let n=lt(e,t),r=H(e.properties);return{...n,...r}}function lt(e,t){switch(t){case"tool.called":{let n={};return v(e.toolName)&&(n.name=e.toolName),v(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),v(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return v(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),v(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function ft(e){return re(e)?e.eventType:e.event}function gt(e,t){let n=v(e.requestId)??ke(t),r=v(e.sessionId)??_(t),o=v(e.traceId)??Se(t),s=v(e.externalUserId)??ve(t),a=v(e.correlationId)??xe(t)??n,i={};return r&&(i.sessionId=r),o&&(i.traceId=o),n&&(i.requestId=n),a&&(i.correlationId=a),s&&(i.externalUserId=s),i}function mt(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 v(e){if(typeof e=="string"&&e.trim().length!==0)return e}function re(e){return"eventType"in e}var wt="/api/mcp/events/v2/batch";var je="@waniwani/sdk",ht=new Set([401,403]),yt=new Set([408,425,429,500,502,503,504]);function $e(e){return new oe(e)}var oe=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=St(t.apiUrl,t.endpointPath??wt),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":je},body:JSON.stringify(this.makeBatchRequest(t))})}catch(s){return{kind:"retryable",reason:vt(s)}}if(ht.has(n.status))return{kind:"auth",status:n.status};if(yt.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await kt(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:je,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(a=>[a.id,a])),o=[],s=[];for(let a of n){let i=r.get(a.eventId);if(i){if(Tt(a)){o.push(i);continue}s.push(i)}}return{retryable:o,permanent:s}}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 Tt(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 kt(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function St(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function vt(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 s=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(i,c,d){o();let p=Y({event:"user.identified",externalUserId:i,properties:c,meta:d});return s?.enqueue(p),{eventId:p.id}},async track(i){o();let c=Y(i);return s?.enqueue(c),{eventId:c.id}},async flush(){o(),await s?.flush()},async shutdown(i){return o(),await s?.shutdown({timeoutMs:i?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return s&&xt(a,r.shutdownTimeoutMs),a}function xt(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 G(e){let t=e??B(),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},s={apiUrl:n,apiKey:r,tracking:o},a=Be(s),i=Oe(s);return{...a,kb:i,_config:s}}function Rt(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 Et(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=G(t)),n}return async function(s){let a;try{a=await s.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 i=r(),c=[];for(let d of a.events){let p=Rt(d),w=await i.track(p);c.push(w.eventId)}return await i.flush(),new Response(JSON.stringify({ok:!0,accepted:c.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(i){let c=i instanceof Error?i.message:"Unknown error";return new Response(JSON.stringify({error:c}),{status:500,headers:{"Content-Type":"application/json"}})}}}var J=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=It(this.config.apiUrl,"/api/mcp/widget-tokens"),o={};t&&(o.sessionId=t),n&&(o.traceId=n);try{let s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o)});if(!s.ok)return null;let a=await s.json(),i=a.data&&typeof a.data=="object"?a.data:a,c=new Date(i.expiresAt).getTime();return!i.token||Number.isNaN(c)?null:(this.cached={token:i.token,expiresAt:c},i.token)}catch{return null}}};function It(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}var qe="waniwani/sessionId",ie="waniwani/geoLocation",se="waniwani/userLocation";function S(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function O(e){if(!S(e))return;let t=e._meta;return S(t)?t:void 0}function ae(e){if(!S(e))return;let t=e.content;return Array.isArray(t)?t.find(r=>S(r)&&r.type==="text"&&typeof r.text=="string")?.text:void 0}function Ct(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function ce(e,t,n,r,o,s){let a=Ct(e,n.toolType),i=O(t);return console.log("[waniwani:debug] buildTrackInput meta:",JSON.stringify(i),"-> source:",P(i)),{event:"tool.called",properties:{name:e,type:a,...r??{},...s?.input!==void 0&&{input:s.input},...s?.output!==void 0&&{output:s.output}},meta:i,source:P(i),metadata:{...n.metadata??{},...o&&{clientInfo:o}}}}async function de(e,t,n){try{await e.track(t)}catch(r){n?.(pe(r))}}async function ue(e,t){try{await e.flush()}catch(n){t?.(pe(n))}}async function Le(e,t,n,r,o){if(!S(e))return;S(e._meta)||(e._meta={});let s=e._meta,a=S(s.waniwani)?s.waniwani:void 0,i={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let w=await t.getToken();w&&(i.token=w)}catch(w){o?.(pe(w))}let c=_(s);c&&(i.sessionId||(i.sessionId=c));let d=ze(s);d!==void 0&&(i.geoLocation||(i.geoLocation=d));let p=P(O(r));p&&!i.source&&(i.source=p),s.waniwani=i}function Ve(e,t){let n=O(t);if(!n||!S(e))return;S(e._meta)||(e._meta={});let r=e._meta,o=_(n);o&&!r[qe]&&(r[qe]=o);let s=ze(n);s&&(r[ie]||(r[ie]=s),r[se]||(r[se]=s))}function ze(e){if(!e)return;let t=e[ie]??e[se];if(S(t)||typeof t=="string")return t}function pe(e){return e instanceof Error?e:new Error(String(e))}var He="https://app.waniwani.ai";function bt(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??G(),s=r.injectWidgetToken!==!1,a=null;function i(){if(a)return a;let d=o._config.apiKey;return d?(a=new J({apiUrl:o._config.apiUrl??He,apiKey:d}),a):null}let c=e.registerTool.bind(e);return n.registerTool=((...d)=>{let[p,w,f]=d,u=typeof p=="string"&&p.trim().length>0?p:"unknown";if(typeof f!="function")return c(...d);let h=f;return c(p,w,async(l,y)=>{let x=O(y)??{},b=Te(o,x);S(y)&&(y[Q]=b);let E=performance.now(),K=e.server?.getClientVersion?.();try{let k=await h(l,y),I=Math.round(performance.now()-E),X=S(k)&&k.isError===!0;if(X){let le=ae(k);console.error(`[waniwani] Tool "${u}" returned error${le?`: ${le}`:""}`)}return await de(o,ce(u,y,r,{durationMs:I,status:X?"error":"ok",...X&&{errorMessage:ae(k)??"Unknown tool error"}},K,{input:l,output:k}),r.onError),r.flushAfterToolCall&&await ue(o,r.onError),Ve(k,y),s&&await Le(k,i(),o._config.apiUrl??He,y,r.onError),k}catch(k){let I=Math.round(performance.now()-E);throw await de(o,ce(u,y,r,{durationMs:I,status:"error",errorMessage:k instanceof Error?k.message:String(k)},K,{input:l}),r.onError),r.flushAfterToolCall&&await ue(o,r.onError),k}})}),n}export{C as END,R as START,A as StateGraph,F as WaniwaniKvStore,Me as createFlow,Fe as createFlowTestHarness,Ue as createResource,at as createTool,Et as createTrackingRoute,Z as detectPlatform,Ge as isMCPApps,Ye as isOpenAI,ct as registerTools,bt as withWaniwani};
7
7
  //# sourceMappingURL=index.js.map