@waniwani/sdk 0.12.14-beta.5 → 0.12.15

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.
@@ -337,6 +337,56 @@ type FieldSchemaInfo = {
337
337
  optional?: boolean;
338
338
  };
339
339
 
340
+ /**
341
+ * Generic key-value store backed by the WaniWani API.
342
+ *
343
+ * Values are stored as JSON objects (`Record<string, unknown>`) in the
344
+ * `/api/mcp/redis/*` endpoints. Tenant isolation is handled by the API key.
345
+ *
346
+ * Config is read from env vars:
347
+ * - `WANIWANI_API_KEY` (required)
348
+ * - `WANIWANI_API_URL` (optional, defaults to https://app.waniwani.ai)
349
+ * - `WANIWANI_ENCRYPTION_KEY` (optional, base64-encoded 32-byte key for AES-256-GCM encryption)
350
+ */
351
+ interface KvStoreSetOptions {
352
+ /**
353
+ * Time-to-live in seconds, mirroring Redis `SET ... EX`. When omitted the
354
+ * server applies its default retention window. The value is kept until it
355
+ * expires, however far in the future.
356
+ */
357
+ ttlSeconds?: number;
358
+ }
359
+ interface KvStore<T = Record<string, unknown>> {
360
+ get(key: string): Promise<T | null>;
361
+ set(key: string, value: T, options?: KvStoreSetOptions): Promise<void>;
362
+ delete(key: string): Promise<void>;
363
+ }
364
+ declare class WaniwaniKvStore<T = Record<string, unknown>> implements KvStore<T> {
365
+ private get baseUrl();
366
+ private get apiKey();
367
+ private get encryptionKey();
368
+ get(key: string): Promise<T | null>;
369
+ set(key: string, value: T, options?: KvStoreSetOptions): Promise<void>;
370
+ delete(key: string): Promise<void>;
371
+ private request;
372
+ }
373
+
374
+ /**
375
+ * In-memory KvStore implementation.
376
+ *
377
+ * State lives in a `Map` for the lifetime of the process — nothing is
378
+ * persisted, nothing is shared across instances. Use for local development
379
+ * and tests. For production, plug in a Redis/Upstash/CF-KV adapter or set
380
+ * `WANIWANI_API_KEY` to use the hosted store.
381
+ */
382
+
383
+ declare class MemoryKvStore<T = Record<string, unknown>> implements KvStore<T> {
384
+ private readonly map;
385
+ get(key: string): Promise<T | null>;
386
+ set(key: string, value: T, _options?: KvStoreSetOptions): Promise<void>;
387
+ delete(key: string): Promise<void>;
388
+ }
389
+
340
390
  /**
341
391
  * Server-side flow state store.
342
392
  *
@@ -346,7 +396,7 @@ type FieldSchemaInfo = {
346
396
 
347
397
  interface FlowStore {
348
398
  get(key: string): Promise<FlowTokenContent | null>;
349
- set(key: string, value: FlowTokenContent): Promise<void>;
399
+ set(key: string, value: FlowTokenContent, options?: KvStoreSetOptions): Promise<void>;
350
400
  delete(key: string): Promise<void>;
351
401
  }
352
402
 
@@ -932,48 +982,6 @@ declare function createFlowTestHarness(flow: RegisteredFlow, options?: {
932
982
  lastState(): Promise<FlowTokenContent | null>;
933
983
  }>;
934
984
 
935
- /**
936
- * Generic key-value store backed by the WaniWani API.
937
- *
938
- * Values are stored as JSON objects (`Record<string, unknown>`) in the
939
- * `/api/mcp/redis/*` endpoints. Tenant isolation is handled by the API key.
940
- *
941
- * Config is read from env vars:
942
- * - `WANIWANI_API_KEY` (required)
943
- * - `WANIWANI_API_URL` (optional, defaults to https://app.waniwani.ai)
944
- * - `WANIWANI_ENCRYPTION_KEY` (optional, base64-encoded 32-byte key for AES-256-GCM encryption)
945
- */
946
- interface KvStore<T = Record<string, unknown>> {
947
- get(key: string): Promise<T | null>;
948
- set(key: string, value: T): Promise<void>;
949
- delete(key: string): Promise<void>;
950
- }
951
- declare class WaniwaniKvStore<T = Record<string, unknown>> implements KvStore<T> {
952
- private get baseUrl();
953
- private get apiKey();
954
- private get encryptionKey();
955
- get(key: string): Promise<T | null>;
956
- set(key: string, value: T): Promise<void>;
957
- delete(key: string): Promise<void>;
958
- private request;
959
- }
960
-
961
- /**
962
- * In-memory KvStore implementation.
963
- *
964
- * State lives in a `Map` for the lifetime of the process — nothing is
965
- * persisted, nothing is shared across instances. Use for local development
966
- * and tests. For production, plug in a Redis/Upstash/CF-KV adapter or set
967
- * `WANIWANI_API_KEY` to use the hosted store.
968
- */
969
-
970
- declare class MemoryKvStore<T = Record<string, unknown>> implements KvStore<T> {
971
- private readonly map;
972
- get(key: string): Promise<T | null>;
973
- set(key: string, value: T): Promise<void>;
974
- delete(key: string): Promise<void>;
975
- }
976
-
977
985
  /**
978
986
  * Server-side API route handler for widget tracking events.
979
987
  *
@@ -1451,4 +1459,4 @@ declare function createTool<TInput extends z.ZodRawShape>(config: ToolConfig<TIn
1451
1459
  */
1452
1460
  declare function registerTools(server: McpServer, tools: RegisteredTool[]): Promise<void>;
1453
1461
 
1454
- export { type AddNodeConfig, type ConditionFn, END, type FlowConfig, type FlowTestResult, type HostContext, type InferFlowState, type InterruptSignal, type KvStore, MemoryKvStore, type NodeContext, type NodeHandler, type RegisteredFlow, type RegisteredResource, type RegisteredTool, type ResourceConfig, START, type ScopedWaniWaniClient, StateGraph, type ToolCallResult, type ToolConfig, type ToolHandler, type ToolHandlerContext, type ToolResult, type ToolToolCallback, type TrackingRouteOptions, type TypedInterrupt, type TypedShowWidget, type UnifiedWidgetClient, WaniwaniKvStore, type WidgetCSP, type WidgetPlatform, type WidgetSignal, type WithWaniwaniOptions, createFlow, createFlowTestHarness, createResource, createTool, createTrackingRoute, detectPlatform, isMCPApps, isOpenAI, redacted, registerTools, withWaniwani };
1462
+ export { type AddNodeConfig, type ConditionFn, END, type FlowConfig, type FlowTestResult, type HostContext, type InferFlowState, type InterruptSignal, type KvStore, type KvStoreSetOptions, MemoryKvStore, type NodeContext, type NodeHandler, type RegisteredFlow, type RegisteredResource, type RegisteredTool, type ResourceConfig, START, type ScopedWaniWaniClient, StateGraph, type ToolCallResult, type ToolConfig, type ToolHandler, type ToolHandlerContext, type ToolResult, type ToolToolCallback, type TrackingRouteOptions, type TypedInterrupt, type TypedShowWidget, type UnifiedWidgetClient, WaniwaniKvStore, type WidgetCSP, type WidgetPlatform, type WidgetSignal, type WithWaniwaniOptions, createFlow, createFlowTestHarness, createResource, createTool, createTrackingRoute, detectPlatform, isMCPApps, isOpenAI, redacted, registerTools, withWaniwani };
package/dist/mcp/index.js CHANGED
@@ -1,7 +1,7 @@
1
- var _="__start__",F="__end__",Ie=Symbol.for("waniwani.flow.interrupt"),be=Symbol.for("waniwani.flow.widget");function Ce(e,t){let n=t?.context,o=[];for(let[r,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&"question"in i){let s=i;o.push({question:s.question,field:r,suggestions:s.suggestions,context:s.context,validate:s.validate})}return{__type:Ie,questions:o,context:n}}function _e(e,t){let n=typeof e=="object"&&e!==null&&"tool"in e,o=n?e.tool:e,r=n?e:t??{};if(r.description!==void 0){let c=typeof o=="string"?o:o.id;throw new Error(`showWidget("${c}", { description }) is no longer supported. The engine now emits a standardized instruction telling the AI to call the widget tool. Return any per-widget description from the "${c}" tool's own response instead.`)}let{data:i,interactive:s,field:a}=r;return{__type:be,tool:typeof o=="string"?o:o.id,...i!==void 0?{data:i}:{},...s!==void 0?{interactive:s}:{},...a!==void 0?{field:a}:{}}}function Fe(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Ie}function Pe(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===be}import{z as A}from"zod";var ce="waniwani/client";function G(e){if(typeof e=="object"&&e!==null)return e[ce]}function We(e,t,n){return{track(o){return e.track({...o,meta:{...t,...o.meta}})},identify(o,r){return e.identify(o,r,t)},kb:e.kb,_config:n}}function q(e,t){for(let n of t){let o=e[n];if(typeof o=="string"&&o.length>0)return o}}var _t=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],Ft=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Pt=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],Wt=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],Nt=["correlationId","openai/requestId"];var O="waniwani/flow";function P(e){return e?q(e,_t):void 0}function Ae(e){return e?q(e,Ft):void 0}function Me(e){return e?q(e,Pt):void 0}function Ue(e){return e?q(e,Wt):void 0}function De(e){return e?q(e,Nt):void 0}var At=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],Mt=[{needle:"claude",source:"claude"}];function W(e,t){if(e){let o=e["waniwani/source"];if(typeof o=="string"&&o.length>0)return o;for(let{key:r,source:i}of At){let s=e[r];if(typeof s=="string"&&s.length>0)return i}}let n=t?.name;if(typeof n=="string"&&n.length>0){let o=n.toLowerCase();for(let{needle:r,source:i}of Mt)if(o.includes(r))return i}}function Ne(e,t){let n=t.toLowerCase(),o=e[t]??e[n];if(o===void 0){for(let i of Object.keys(e))if(i.toLowerCase()===n){o=e[i];break}}let r=Array.isArray(o)?o[0]:o;return typeof r=="string"&&r.length>0?r:void 0}function Oe(e){if(!e)return;let t=Ne(e,"user-agent"),n=Ne(e,"x-anthropic-client");if(t&&/claude/i.test(t)||n&&/claude|anthropic/i.test(n))return"claude"}function je(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function H(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null||typeof o!="object")return;o=o[r]}return o}function Ut(e,t,n){let o=t.split("."),r=o.pop();if(!r)return;let i=e;for(let s of o)(i[s]==null||typeof i[s]!="object"||Array.isArray(i[s]))&&(i[s]={}),i=i[s];i[r]=n}function Ke(e,t){let n=t.split("."),o=n.pop();if(!o)return;let r=e;for(let i of n){if(r==null||typeof r!="object")return;r=r[i]}r!=null&&typeof r=="object"&&delete r[o]}function Z(e){let t={};for(let[n,o]of Object.entries(e))n.includes(".")?Ut(t,n,o):o!==null&&typeof o=="object"&&!Array.isArray(o)?t=N(t,{[n]:o}):t[n]=o;return t}function N(e,t){let n={...e};for(let[o,r]of Object.entries(t))r!==null&&typeof r=="object"&&!Array.isArray(r)&&n[o]!==null&&typeof n[o]=="object"&&!Array.isArray(n[o])?n[o]=N(n[o],r):n[o]=r;return n}function $e(e){return e._zod?.def}function Dt(e){let t=e,n=!1;for(let o=0;o<8;o++){let r=$e(t);if(!r?.innerType)break;if(r.type==="optional"||r.type==="nullable"||r.type==="default"){n=!0,t=r.innerType;continue}break}return{inner:t,optional:n}}function Le(e){let{inner:t,optional:n}=Dt(e),o=t.description??e.description??void 0,r=$e(t),i=r?.type,s={type:"unknown",...o?{description:o}:{},...n?{optional:!0}:{}};return i==="enum"&&r?.entries?{...s,type:"enum",values:Object.keys(r.entries)}:i==="string"||i==="number"||i==="boolean"||i==="object"||i==="array"?{...s,type:i}:s}function ue(e,t){if(!e||!t)return;if(t.includes(".")){let o=t.indexOf("."),r=t.slice(0,o),i=t.slice(o+1),s=e[r];if(!s)return;let c=je(s)?.[i];return c?Le(c):void 0}let n=e[t];if(n)return Le(n)}function le(e){return e!=null&&e!==""}async function U(e,t){return e.type==="direct"?e.to:e.condition(t)}function qe(e,t,n,o,r){if(e.every(d=>le(H(o,d.field))))return null;let i=e.filter(d=>!le(H(o,d.field))).map(d=>{let u=ue(r,d.field);return u?{...d,fieldSchema:u}:d}),s=i.length===1,a=i[0];return{content:s&&a?{status:"interrupt",question:a.question,field:a.field,...a.suggestions?{suggestions:a.suggestions}:{},...a.fieldSchema?{fieldSchema:a.fieldSchema}:{},...a.context||t?{context:a.context??t}:{}}:{status:"interrupt",questions:i,...t?{context:t}:{}},flowTokenContent:{step:n,state:o,...s&&a?{field:a.field}:{}}}}async function B(e,t,n,o,r,i,s,a,c){let d=e,u={...t},p=[],l=50,x=0;for(;x++<l;){if(d===F)return{content:{status:"complete"},flowTokenContent:{state:u},nodesVisited:p};let f=n.get(d);if(!f)return{content:{status:"error",error:`Unknown node: "${d}"`},nodesVisited:p};a?.get(d)?.hideFromFunnel||p.push(d);try{let g=await f({state:u,meta:i,interrupt:Ce,showWidget:_e,waniwani:s});if(Fe(g)){for(let S of g.questions)S.validate&&r.set(`${d}:${S.field}`,S.validate);let y=qe(g.questions,g.context,d,u,c);if(y)return{...y,nodesVisited:p};for(let S of g.questions){let R=r.get(`${d}:${S.field}`);if(R)try{let I=H(u,S.field),b=await R(I);b&&typeof b=="object"&&(u=N(u,b))}catch(I){let b=I instanceof Error?I.message:String(I);Ke(u,S.field);let M=g.questions.map(D=>D.field===S.field?{...D,context:D.context?`ERROR: ${b}
1
+ var _="__start__",F="__end__",Ie=Symbol.for("waniwani.flow.interrupt"),be=Symbol.for("waniwani.flow.widget");function Ce(e,t){let n=t?.context,o=[];for(let[r,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&"question"in i){let s=i;o.push({question:s.question,field:r,suggestions:s.suggestions,context:s.context,validate:s.validate})}return{__type:Ie,questions:o,context:n}}function _e(e,t){let n=typeof e=="object"&&e!==null&&"tool"in e,o=n?e.tool:e,r=n?e:t??{};if(r.description!==void 0){let c=typeof o=="string"?o:o.id;throw new Error(`showWidget("${c}", { description }) is no longer supported. The engine now emits a standardized instruction telling the AI to call the widget tool. Return any per-widget description from the "${c}" tool's own response instead.`)}let{data:i,interactive:s,field:a}=r;return{__type:be,tool:typeof o=="string"?o:o.id,...i!==void 0?{data:i}:{},...s!==void 0?{interactive:s}:{},...a!==void 0?{field:a}:{}}}function Fe(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Ie}function Pe(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===be}import{z as A}from"zod";var ce="waniwani/client";function G(e){if(typeof e=="object"&&e!==null)return e[ce]}function We(e,t,n){return{track(o){return e.track({...o,meta:{...t,...o.meta}})},identify(o,r){return e.identify(o,r,t)},kb:e.kb,_config:n}}function q(e,t){for(let n of t){let o=e[n];if(typeof o=="string"&&o.length>0)return o}}var _t=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],Ft=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Pt=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],Wt=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],Nt=["correlationId","openai/requestId"];var D="waniwani/flow";function P(e){return e?q(e,_t):void 0}function Ae(e){return e?q(e,Ft):void 0}function Me(e){return e?q(e,Pt):void 0}function Ue(e){return e?q(e,Wt):void 0}function Oe(e){return e?q(e,Nt):void 0}var At=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],Mt=[{needle:"claude",source:"claude"}];function W(e,t){if(e){let o=e["waniwani/source"];if(typeof o=="string"&&o.length>0)return o;for(let{key:r,source:i}of At){let s=e[r];if(typeof s=="string"&&s.length>0)return i}}let n=t?.name;if(typeof n=="string"&&n.length>0){let o=n.toLowerCase();for(let{needle:r,source:i}of Mt)if(o.includes(r))return i}}function Ne(e,t){let n=t.toLowerCase(),o=e[t]??e[n];if(o===void 0){for(let i of Object.keys(e))if(i.toLowerCase()===n){o=e[i];break}}let r=Array.isArray(o)?o[0]:o;return typeof r=="string"&&r.length>0?r:void 0}function De(e){if(!e)return;let t=Ne(e,"user-agent"),n=Ne(e,"x-anthropic-client");if(t&&/claude/i.test(t)||n&&/claude|anthropic/i.test(n))return"claude"}function Ke(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function H(e,t){let n=t.split("."),o=e;for(let r of n){if(o==null||typeof o!="object")return;o=o[r]}return o}function Ut(e,t,n){let o=t.split("."),r=o.pop();if(!r)return;let i=e;for(let s of o)(i[s]==null||typeof i[s]!="object"||Array.isArray(i[s]))&&(i[s]={}),i=i[s];i[r]=n}function je(e,t){let n=t.split("."),o=n.pop();if(!o)return;let r=e;for(let i of n){if(r==null||typeof r!="object")return;r=r[i]}r!=null&&typeof r=="object"&&delete r[o]}function Z(e){let t={};for(let[n,o]of Object.entries(e))n.includes(".")?Ut(t,n,o):o!==null&&typeof o=="object"&&!Array.isArray(o)?t=N(t,{[n]:o}):t[n]=o;return t}function N(e,t){let n={...e};for(let[o,r]of Object.entries(t))r!==null&&typeof r=="object"&&!Array.isArray(r)&&n[o]!==null&&typeof n[o]=="object"&&!Array.isArray(n[o])?n[o]=N(n[o],r):n[o]=r;return n}function $e(e){return e._zod?.def}function Ot(e){let t=e,n=!1;for(let o=0;o<8;o++){let r=$e(t);if(!r?.innerType)break;if(r.type==="optional"||r.type==="nullable"||r.type==="default"){n=!0,t=r.innerType;continue}break}return{inner:t,optional:n}}function Le(e){let{inner:t,optional:n}=Ot(e),o=t.description??e.description??void 0,r=$e(t),i=r?.type,s={type:"unknown",...o?{description:o}:{},...n?{optional:!0}:{}};return i==="enum"&&r?.entries?{...s,type:"enum",values:Object.keys(r.entries)}:i==="string"||i==="number"||i==="boolean"||i==="object"||i==="array"?{...s,type:i}:s}function ue(e,t){if(!e||!t)return;if(t.includes(".")){let o=t.indexOf("."),r=t.slice(0,o),i=t.slice(o+1),s=e[r];if(!s)return;let c=Ke(s)?.[i];return c?Le(c):void 0}let n=e[t];if(n)return Le(n)}function le(e){return e!=null&&e!==""}async function U(e,t){return e.type==="direct"?e.to:e.condition(t)}function qe(e,t,n,o,r){if(e.every(d=>le(H(o,d.field))))return null;let i=e.filter(d=>!le(H(o,d.field))).map(d=>{let u=ue(r,d.field);return u?{...d,fieldSchema:u}:d}),s=i.length===1,a=i[0];return{content:s&&a?{status:"interrupt",question:a.question,field:a.field,...a.suggestions?{suggestions:a.suggestions}:{},...a.fieldSchema?{fieldSchema:a.fieldSchema}:{},...a.context||t?{context:a.context??t}:{}}:{status:"interrupt",questions:i,...t?{context:t}:{}},flowTokenContent:{step:n,state:o,...s&&a?{field:a.field}:{}}}}async function B(e,t,n,o,r,i,s,a,c){let d=e,u={...t},p=[],l=50,x=0;for(;x++<l;){if(d===F)return{content:{status:"complete"},flowTokenContent:{state:u},nodesVisited:p};let f=n.get(d);if(!f)return{content:{status:"error",error:`Unknown node: "${d}"`},nodesVisited:p};a?.get(d)?.hideFromFunnel||p.push(d);try{let g=await f({state:u,meta:i,interrupt:Ce,showWidget:_e,waniwani:s});if(Fe(g)){for(let S of g.questions)S.validate&&r.set(`${d}:${S.field}`,S.validate);let y=qe(g.questions,g.context,d,u,c);if(y)return{...y,nodesVisited:p};for(let S of g.questions){let R=r.get(`${d}:${S.field}`);if(R)try{let I=H(u,S.field),b=await R(I);b&&typeof b=="object"&&(u=N(u,b))}catch(I){let b=I instanceof Error?I.message:String(I);je(u,S.field);let M=g.questions.map(O=>O.field===S.field?{...O,context:O.context?`ERROR: ${b}
2
2
 
3
- ${D.context}`:`ERROR: ${b}`}:D),Y=qe(M,g.context,d,u,c);if(Y)return{...Y,nodesVisited:p};break}}let w=o.get(d);if(!w)return{content:{status:"error",error:`No outgoing edge from node "${d}"`},nodesVisited:p};d=await U(w,u);continue}if(Pe(g)){let y=g.field;if(y&&le(H(u,y))){let R=o.get(d);if(!R)return{content:{status:"error",error:`No outgoing edge from node "${d}"`},nodesVisited:p};d=await U(R,u);continue}let w=y?ue(c,y):void 0,S=g.interactive!==!1;return{content:{status:"widget",tool:g.tool,...g.data!==void 0?{data:g.data}:{},description:S?`IMPORTANT: You MUST now call the ${g.tool} tool to display the widget. Do NOT skip this step`:`IMPORTANT \u2014 two ordered steps. STEP 1: call the ${g.tool} tool RIGHT NOW to display this widget to the user. This renders UI the user must see \u2014 do NOT skip it and do NOT jump straight to action:"continue". STEP 2: ONLY AFTER ${g.tool} has been called, call this flow again with action:"continue".`,interactive:S,...y?{field:y}:{},...w?{fieldSchema:w}:{}},flowTokenContent:{step:d,state:u,field:y,widgetId:g.tool},nodesVisited:p}}u=N(u,g);let E=o.get(d);if(!E)return{content:{status:"error",error:`No outgoing edge from node "${d}"`},nodesVisited:p};d=await U(E,u)}catch(T){return{content:{status:"error",error:T instanceof Error?T.message:String(T)},flowTokenContent:{step:d,state:u},nodesVisited:p}}}return{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"},nodesVisited:p}}function pe(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var He=new Map;async function Be(e){let t=He.get(e);if(t)return t;let n=Buffer.from(e,"base64");if(n.length!==32)throw new Error("[WaniWani KV] WANIWANI_ENCRYPTION_KEY must be a base64-encoded 32-byte (256-bit) key.");let o=await globalThis.crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"]);return He.set(e,o),o}async function Ve(e,t){let n=await Be(t),o=globalThis.crypto.getRandomValues(new Uint8Array(12)),r=new TextEncoder().encode(JSON.stringify(e)),i=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:o},n,r);return{__ww_enc:1,ct:Buffer.from(i).toString("base64"),iv:Buffer.from(o).toString("base64")}}async function ze(e,t){let n=await Be(t),o=Buffer.from(e.ct,"base64"),r=Buffer.from(e.iv,"base64"),i;try{i=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:r},n,o)}catch{throw new Error("[WaniWani KV] Decryption failed. The encryption key may be incorrect or the data may be corrupted.")}return JSON.parse(new TextDecoder().decode(i))}var Ot={debug:0,warn:1,error:2,none:3};function jt(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in Ot?e:process.env.WANIWANI_DEBUG?"debug":"none"}function j(e,t){return t??jt()==="debug"?(...o)=>console.log(`[waniwani:${e}]`,...o):()=>{}}var Kt="@waniwani/sdk",Lt="https://app.waniwani.ai",$t=j("kv"),K=class{get baseUrl(){return(process.env.WANIWANI_API_URL??Lt).replace(/\/$/,"")}get apiKey(){return process.env.WANIWANI_API_KEY}get encryptionKey(){return process.env.WANIWANI_ENCRYPTION_KEY}async get(t){if(!this.apiKey)throw new Error("[WaniWani KV] No API key configured. Set WANIWANI_API_KEY env var.");let n=await this.request("/api/mcp/redis/get",{key:t});if(n==null)return null;if(pe(n)){if(!this.encryptionKey)throw new Error("[WaniWani KV] Encrypted data found but WANIWANI_ENCRYPTION_KEY is not set.");return ze(n,this.encryptionKey)}return n}async set(t,n){if(!this.apiKey)throw new Error("[WaniWani KV] No API key configured. Set WANIWANI_API_KEY env var.");let o=this.encryptionKey;$t(`set "${t}" \u2014 encryption ${o?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let r=o?await Ve(n,o):n;await this.request("/api/mcp/redis/set",{key:t,value:r})}async delete(t){if(this.apiKey)try{await this.request("/api/mcp/redis/delete",{key:t})}catch(n){console.error("[WaniWani KV] delete failed for key:",t,n)}}async request(t,n){let o=`${this.baseUrl}${t}`,r=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","X-WaniWani-SDK":Kt},body:JSON.stringify(n)});if(!r.ok){let s=await r.text().catch(()=>"");throw new Error(s||`KV store API error: HTTP ${r.status}`)}return(await r.json()).data}};var J=class{map=new Map;async get(t){return this.map.get(t)??null}async set(t,n){this.map.set(t,n)}async delete(t){this.map.delete(t)}};var V=class{store=new K;get(t){return this.store.get(t)}set(t,n){return this.store.set(t,n)}delete(t){return this.store.delete(t)}};function qt(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function Ht(e,t){let n=e.toString(),o=[];for(let r of t){let i=`"${r}"`,s=`'${r}'`,a=`\`${r}\``;(n.includes(i)||n.includes(s)||n.includes(a))&&o.push(r)}return o}function Ye(e,t,n,o){let r=new Set([...t.keys(),F]),i=[];for(let[a,c]of t){let d=o.get(a);i.push({id:a,type:qt(c),label:d?.label??a,...d?.hideFromFunnel?{hideFromFunnel:!0}:{}})}let s=[];for(let[a,c]of n)if(c.type==="direct")s.push({from:a,to:c.to,type:"direct"});else{let d=Ht(c.condition,r);s.push({from:a,to:d,type:"conditional"})}return{flowId:e.id,title:e.title,nodes:i,edges:s}}import{z as v}from"zod";var Ge=v.object({type:v.enum(["enum","string","number","boolean","object","array","unknown"]),values:v.array(v.string()).optional(),description:v.string().optional(),optional:v.boolean().optional()}).describe("JIT schema fragment for a state field \u2014 type, allowed values, and description."),Bt=v.object({question:v.string(),field:v.string(),suggestions:v.array(v.string()).optional(),context:v.string().optional(),fieldSchema:Ge.optional()}).describe("One question within a multi-question interrupt."),fe={status:v.enum(["interrupt","widget","complete","error"]).describe("Current flow status and the next action the assistant should take."),question:v.string().optional().describe("Single question to ask the user when status is interrupt."),field:v.string().optional().describe("State field to fill with the user's answer on the next continue call."),fieldSchema:Ge.optional().describe("JIT schema fragment for the single-question shorthand."),suggestions:v.array(v.string()).optional().describe("Suggested answers for the single-question shorthand."),questions:v.array(Bt).optional().describe("Multiple questions to ask the user when status is interrupt."),context:v.string().optional().describe("Private instruction context for the assistant."),tool:v.string().optional().describe("Widget tool to call when status is widget."),data:v.record(v.string(),v.unknown()).optional().describe("Input data to pass to the widget tool."),description:v.string().optional().describe("Instruction for rendering the requested widget."),interactive:v.boolean().optional().describe("Whether the widget requires user interaction before continuing."),sessionId:v.string().optional().describe("Session identifier to pass on future continue and reset calls."),error:v.string().optional().describe("Error message when status is error.")};function Ze(e){let t=["","## FLOW EXECUTION PROTOCOL","","This tool implements a multi-step conversational flow. Follow this protocol exactly:","",'1. Call with `action: "start"` to begin and include `intent`.'," `intent` must be a brief summary of the user's goal for this flow."," Do NOT invent missing intent."," Optionally include `context` \u2014 the situation or environment that led the user to start"," this flow (e.g. what page they are on, what they were doing, or what triggered the request)."," Only provide `context` when there is genuinely relevant situational information. Do NOT invent missing context."," If the user's message already contains answers to likely questions,"," extract them into `stateUpdates` as `{ field: value }` pairs (see the `stateUpdates` schema"," for the list of writable fields). The engine will auto-skip steps whose fields are already filled."," Only extract values the user explicitly stated \u2014 do NOT guess or invent values."];return e.omitIntentPII&&t.push(" Do NOT include PII in `intent` or `context` \u2014 no names, emails, phones, addresses, IDs, ages, or birthdates.",' Summarize the goal abstractly (e.g. "user wants a quote", not "Jane Doe wants a quote").'),t.push(" For grouped fields (z.object state), use dot-notation keys in `stateUpdates`:",' e.g. `{ "driver.name": "John", "driver.license": "ABC123" }`.',"2. The response JSON `status` field tells you what to do next:",' - `"interrupt"`: Pause and ask the user. Two forms:'," a. Single question: `{ question, field, fieldSchema?, context? }` \u2014 ask `question`, store answer in `field`."," b. Multi-question: `{ questions: [{question, field, fieldSchema?}, ...], context? }` \u2014 ask ALL questions"," in one conversational message, collect all answers."," `fieldSchema` (when present) describes the expected value: `{ type, values?, description?, optional? }`.",' Use it to validate before sending \u2014 match enum `values` exactly, coerce strings to numbers where `type: "number"`.'," `context` (if present) is hidden AI instructions \u2014 use to shape your response, do NOT show verbatim."," Then call again with:",' `action: "continue"`,'," `stateUpdates` = answers keyed by their `field` names, plus any other fields the user mentioned.",' - `"widget"`: The flow wants to show a UI widget. Call the tool named in the `tool`'," field, passing the `data` object as the tool's input."," Check the `interactive` field in the response:"," \u2022 `interactive: true` \u2014 The widget requires user interaction. After calling the display tool,"," STOP and WAIT for the user to interact with the widget. Do NOT call this flow tool again"," until the user has responded. When they do, call with:",' `action: "continue"`,'," `stateUpdates` = `{ [field]: <user's selection> }` plus any other fields the user mentioned."," \u2022 `interactive: false` \u2014 The widget is display-only. You MUST STILL call the display tool"," FIRST to render it for the user \u2014 this is a required, user-visible step. Do NOT skip it",' and do NOT jump straight to `action: "continue"`. ONLY AFTER you have called the display',' tool, call THIS flow tool again with `action: "continue"`. Do NOT wait for user interaction.',' - `"complete"`: The flow is done. Present the result to the user.',' - `"error"`: Something went wrong. Show the `error` message.',"","3. Do NOT invent state values. Only use `stateUpdates` for information the user explicitly provided.","4. Include only the fields the user actually answered in `stateUpdates` \u2014 do NOT guess missing ones."," If the user did not answer all pending questions, the engine will re-prompt for the remaining ones."," If the user mentioned values for other known fields, include those too \u2014"," they will be applied immediately and those steps will be auto-skipped.","5. CORRECTION: If the user wants to CHANGE a previously-answered field",' (e.g. "actually my email is X" or "go back and change my country"),',' call with `action: "reset"` and `stateUpdates` containing the corrected field(s).'," The engine will restart the flow from the beginning with all existing answers preserved"," plus your corrections. Steps with filled answers will be auto-skipped."," The flow may take a different path if the corrected value affects routing.",' Do NOT use "reset" for the CURRENT question \u2014 use "continue" for that.',"6. If the response includes a `sessionId`, you MUST pass it back as `sessionId`",' in every subsequent "continue" and "reset" call for this flow.'),t.join(`
3
+ ${O.context}`:`ERROR: ${b}`}:O),Y=qe(M,g.context,d,u,c);if(Y)return{...Y,nodesVisited:p};break}}let w=o.get(d);if(!w)return{content:{status:"error",error:`No outgoing edge from node "${d}"`},nodesVisited:p};d=await U(w,u);continue}if(Pe(g)){let y=g.field;if(y&&le(H(u,y))){let R=o.get(d);if(!R)return{content:{status:"error",error:`No outgoing edge from node "${d}"`},nodesVisited:p};d=await U(R,u);continue}let w=y?ue(c,y):void 0,S=g.interactive!==!1;return{content:{status:"widget",tool:g.tool,...g.data!==void 0?{data:g.data}:{},description:S?`IMPORTANT: You MUST now call the ${g.tool} tool to display the widget. Do NOT skip this step`:`IMPORTANT \u2014 two ordered steps. STEP 1: call the ${g.tool} tool RIGHT NOW to display this widget to the user. This renders UI the user must see \u2014 do NOT skip it and do NOT jump straight to action:"continue". STEP 2: ONLY AFTER ${g.tool} has been called, call this flow again with action:"continue".`,interactive:S,...y?{field:y}:{},...w?{fieldSchema:w}:{}},flowTokenContent:{step:d,state:u,field:y,widgetId:g.tool},nodesVisited:p}}u=N(u,g);let E=o.get(d);if(!E)return{content:{status:"error",error:`No outgoing edge from node "${d}"`},nodesVisited:p};d=await U(E,u)}catch(T){return{content:{status:"error",error:T instanceof Error?T.message:String(T)},flowTokenContent:{step:d,state:u},nodesVisited:p}}}return{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"},nodesVisited:p}}function pe(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var He=new Map;async function Be(e){let t=He.get(e);if(t)return t;let n=Buffer.from(e,"base64");if(n.length!==32)throw new Error("[WaniWani KV] WANIWANI_ENCRYPTION_KEY must be a base64-encoded 32-byte (256-bit) key.");let o=await globalThis.crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"]);return He.set(e,o),o}async function Ve(e,t){let n=await Be(t),o=globalThis.crypto.getRandomValues(new Uint8Array(12)),r=new TextEncoder().encode(JSON.stringify(e)),i=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:o},n,r);return{__ww_enc:1,ct:Buffer.from(i).toString("base64"),iv:Buffer.from(o).toString("base64")}}async function ze(e,t){let n=await Be(t),o=Buffer.from(e.ct,"base64"),r=Buffer.from(e.iv,"base64"),i;try{i=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:r},n,o)}catch{throw new Error("[WaniWani KV] Decryption failed. The encryption key may be incorrect or the data may be corrupted.")}return JSON.parse(new TextDecoder().decode(i))}var Dt={debug:0,warn:1,error:2,none:3};function Kt(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in Dt?e:process.env.WANIWANI_DEBUG?"debug":"none"}function K(e,t){return t??Kt()==="debug"?(...o)=>console.log(`[waniwani:${e}]`,...o):()=>{}}var jt="@waniwani/sdk",Lt="https://app.waniwani.ai",$t=K("kv"),j=class{get baseUrl(){return(process.env.WANIWANI_API_URL??Lt).replace(/\/$/,"")}get apiKey(){return process.env.WANIWANI_API_KEY}get encryptionKey(){return process.env.WANIWANI_ENCRYPTION_KEY}async get(t){if(!this.apiKey)throw new Error("[WaniWani KV] No API key configured. Set WANIWANI_API_KEY env var.");let n=await this.request("/api/mcp/redis/get",{key:t});if(n==null)return null;if(pe(n)){if(!this.encryptionKey)throw new Error("[WaniWani KV] Encrypted data found but WANIWANI_ENCRYPTION_KEY is not set.");return ze(n,this.encryptionKey)}return n}async set(t,n,o){if(!this.apiKey)throw new Error("[WaniWani KV] No API key configured. Set WANIWANI_API_KEY env var.");let r=this.encryptionKey;$t(`set "${t}" \u2014 encryption ${r?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let i=r?await Ve(n,r):n;await this.request("/api/mcp/redis/set",{key:t,value:i,ttlSeconds:o?.ttlSeconds})}async delete(t){if(this.apiKey)try{await this.request("/api/mcp/redis/delete",{key:t})}catch(n){console.error("[WaniWani KV] delete failed for key:",t,n)}}async request(t,n){let o=`${this.baseUrl}${t}`,r=await fetch(o,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","X-WaniWani-SDK":jt},body:JSON.stringify(n)});if(!r.ok){let s=await r.text().catch(()=>"");throw new Error(s||`KV store API error: HTTP ${r.status}`)}return(await r.json()).data}};var J=class{map=new Map;async get(t){return this.map.get(t)??null}async set(t,n,o){this.map.set(t,n)}async delete(t){this.map.delete(t)}};var V=class{store=new j;get(t){return this.store.get(t)}set(t,n,o){return this.store.set(t,n,o)}delete(t){return this.store.delete(t)}};function qt(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function Ht(e,t){let n=e.toString(),o=[];for(let r of t){let i=`"${r}"`,s=`'${r}'`,a=`\`${r}\``;(n.includes(i)||n.includes(s)||n.includes(a))&&o.push(r)}return o}function Ye(e,t,n,o){let r=new Set([...t.keys(),F]),i=[];for(let[a,c]of t){let d=o.get(a);i.push({id:a,type:qt(c),label:d?.label??a,...d?.hideFromFunnel?{hideFromFunnel:!0}:{}})}let s=[];for(let[a,c]of n)if(c.type==="direct")s.push({from:a,to:c.to,type:"direct"});else{let d=Ht(c.condition,r);s.push({from:a,to:d,type:"conditional"})}return{flowId:e.id,title:e.title,nodes:i,edges:s}}import{z as v}from"zod";var Ge=v.object({type:v.enum(["enum","string","number","boolean","object","array","unknown"]),values:v.array(v.string()).optional(),description:v.string().optional(),optional:v.boolean().optional()}).describe("JIT schema fragment for a state field \u2014 type, allowed values, and description."),Bt=v.object({question:v.string(),field:v.string(),suggestions:v.array(v.string()).optional(),context:v.string().optional(),fieldSchema:Ge.optional()}).describe("One question within a multi-question interrupt."),fe={status:v.enum(["interrupt","widget","complete","error"]).describe("Current flow status and the next action the assistant should take."),question:v.string().optional().describe("Single question to ask the user when status is interrupt."),field:v.string().optional().describe("State field to fill with the user's answer on the next continue call."),fieldSchema:Ge.optional().describe("JIT schema fragment for the single-question shorthand."),suggestions:v.array(v.string()).optional().describe("Suggested answers for the single-question shorthand."),questions:v.array(Bt).optional().describe("Multiple questions to ask the user when status is interrupt."),context:v.string().optional().describe("Private instruction context for the assistant."),tool:v.string().optional().describe("Widget tool to call when status is widget."),data:v.record(v.string(),v.unknown()).optional().describe("Input data to pass to the widget tool."),description:v.string().optional().describe("Instruction for rendering the requested widget."),interactive:v.boolean().optional().describe("Whether the widget requires user interaction before continuing."),sessionId:v.string().optional().describe("Session identifier to pass on future continue and reset calls."),error:v.string().optional().describe("Error message when status is error.")};function Ze(e){let t=["","## FLOW EXECUTION PROTOCOL","","This tool implements a multi-step conversational flow. Follow this protocol exactly:","",'1. Call with `action: "start"` to begin and include `intent`.'," `intent` must be a brief summary of the user's goal for this flow."," Do NOT invent missing intent."," Optionally include `context` \u2014 the situation or environment that led the user to start"," this flow (e.g. what page they are on, what they were doing, or what triggered the request)."," Only provide `context` when there is genuinely relevant situational information. Do NOT invent missing context."," If the user's message already contains answers to likely questions,"," extract them into `stateUpdates` as `{ field: value }` pairs (see the `stateUpdates` schema"," for the list of writable fields). The engine will auto-skip steps whose fields are already filled."," Only extract values the user explicitly stated \u2014 do NOT guess or invent values."];return e.omitIntentPII&&t.push(" Do NOT include PII in `intent` or `context` \u2014 no names, emails, phones, addresses, IDs, ages, or birthdates.",' Summarize the goal abstractly (e.g. "user wants a quote", not "Jane Doe wants a quote").'),t.push(" For grouped fields (z.object state), use dot-notation keys in `stateUpdates`:",' e.g. `{ "driver.name": "John", "driver.license": "ABC123" }`.',"2. The response JSON `status` field tells you what to do next:",' - `"interrupt"`: Pause and ask the user. Two forms:'," a. Single question: `{ question, field, fieldSchema?, context? }` \u2014 ask `question`, store answer in `field`."," b. Multi-question: `{ questions: [{question, field, fieldSchema?}, ...], context? }` \u2014 ask ALL questions"," in one conversational message, collect all answers."," `fieldSchema` (when present) describes the expected value: `{ type, values?, description?, optional? }`.",' Use it to validate before sending \u2014 match enum `values` exactly, coerce strings to numbers where `type: "number"`.'," `context` (if present) is hidden AI instructions \u2014 use to shape your response, do NOT show verbatim."," Then call again with:",' `action: "continue"`,'," `stateUpdates` = answers keyed by their `field` names, plus any other fields the user mentioned.",' - `"widget"`: The flow wants to show a UI widget. Call the tool named in the `tool`'," field, passing the `data` object as the tool's input."," Check the `interactive` field in the response:"," \u2022 `interactive: true` \u2014 The widget requires user interaction. After calling the display tool,"," STOP and WAIT for the user to interact with the widget. Do NOT call this flow tool again"," until the user has responded. When they do, call with:",' `action: "continue"`,'," `stateUpdates` = `{ [field]: <user's selection> }` plus any other fields the user mentioned."," \u2022 `interactive: false` \u2014 The widget is display-only. You MUST STILL call the display tool"," FIRST to render it for the user \u2014 this is a required, user-visible step. Do NOT skip it",' and do NOT jump straight to `action: "continue"`. ONLY AFTER you have called the display',' tool, call THIS flow tool again with `action: "continue"`. Do NOT wait for user interaction.',' - `"complete"`: The flow is done. Present the result to the user.',' - `"error"`: Something went wrong. Show the `error` message.',"","3. Do NOT invent state values. Only use `stateUpdates` for information the user explicitly provided.","4. Include only the fields the user actually answered in `stateUpdates` \u2014 do NOT guess missing ones."," If the user did not answer all pending questions, the engine will re-prompt for the remaining ones."," If the user mentioned values for other known fields, include those too \u2014"," they will be applied immediately and those steps will be auto-skipped.","5. CORRECTION: If the user wants to CHANGE a previously-answered field",' (e.g. "actually my email is X" or "go back and change my country"),',' call with `action: "reset"` and `stateUpdates` containing the corrected field(s).'," The engine will restart the flow from the beginning with all existing answers preserved"," plus your corrections. Steps with filled answers will be auto-skipped."," The flow may take a different path if the corrected value affects routing.",' Do NOT use "reset" for the CURRENT question \u2014 use "continue" for that.',"6. If the response includes a `sessionId`, you MUST pass it back as `sessionId`",' in every subsequent "continue" and "reset" call for this flow.'),t.join(`
4
4
  `)}function ge(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Je(e){let t=Xe(e),n=ge(t.waniwani)?t.waniwani:{};return e.meta({...t,waniwani:{...n,redacted:!0}})}function Vt(e){let n=Xe(e).waniwani;return ge(n)&&n.redacted===!0}function Xe(e){let t=e.meta;if(typeof t!="function")return{};let n=t.call(e);return ge(n)?n:{}}function Qe(e){if(!e)return[];let t=[];for(let[n,o]of Object.entries(e))Vt(o)&&t.push(n);return t}var X="waniwani/redactedStateUpdateFields";function zt(e){let t=e.omitIntentPII?" Do not include PII (names, emails, phones, addresses, IDs, ages, birthdates) \u2014 summarize abstractly.":"",o=e.state&&Object.keys(e.state).length>0?A.object(e.state).partial().passthrough():A.record(A.string(),A.unknown());return{action:A.enum(["start","continue","reset"]).describe('"start" to begin the flow, "continue" to resume after a pause (interrupt or widget), "reset" to restart from the beginning with a correction to a previously-collected field'),intent:A.string().optional().describe(`Required when action is "start". Provide a brief summary of the user's goal for this flow. Do not invent missing intent.${t}`),context:A.string().optional().describe(`Optional when action is "start". Describe the situation or environment that led the user to start this flow \u2014 e.g. what page they are on, what they were doing, or what triggered the request. Do not invent missing context.${t}`),stateUpdates:o.optional().describe(`State field values to set before processing the next node. Pass the user's answer (keyed by the field name from the response) and any other values the user mentioned. For nested state fields, use dot-paths like "driver.name".`),sessionId:A.string().optional().describe('Session identifier. If the response includes a `sessionId`, pass it back on every subsequent "continue" and "reset" call for this flow.')}}function Yt(e){if(process.env.WANIWANI_API_KEY)return new V;throw new Error(`[waniwani] createFlow "${e}": no flow store configured. Pass { store } to .compile() \u2014 use MemoryKvStore from "@waniwani/sdk/mcp" for local development, or plug in a Redis/Upstash/Cloudflare KV adapter for production. Alternatively, set WANIWANI_API_KEY to use hosted flow state on app.waniwani.ai.`)}function et(e){let{config:t,nodes:n,edges:o}=e,r=zt(t),i=Ye(t,n,o,e.nodeOptions),s=Ze(t),a=`${t.description}
5
- ${s}`,c=e.store??Yt(t.id),d=new Map;async function u(f,T,g,E){if(f.action==="start"){let y=typeof f.intent=="string"?f.intent.trim():void 0;if(!y)return{content:{status:"error",error:`Missing required "intent" for action "start". Include a brief summary of the user's goal for this flow and any relevant prior context that led to triggering it, if available.`}};if(f.intent=y,typeof f.context=="string"){let I=f.context.trim();f.context=I||void 0}let w=o.get(_);if(!w)return{content:{status:"error",error:"No start edge"}};let S=Z(f.stateUpdates??{}),R=await U(w,S);return B(R,S,n,o,d,g,E,e.nodeOptions,t.state)}if(f.action==="continue"){if(!T)return{content:{status:"error",error:"No session ID available for continue action."}};let y;try{y=await c.get(T)}catch(I){let b=I instanceof Error?I.message:String(I);return{content:{status:"error",error:`Failed to load flow state (session "${T}"): ${b}`}}}if(!y)return{content:{status:"error",error:`Flow state not found for session "${T}". The flow may have expired.`}};let w=y.state,S=y.step;if(!S)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let R=N(w,Z(f.stateUpdates??{}));if(y.widgetId){let I=o.get(S);if(!I)return{content:{status:"error",error:`No edge from step "${S}"`}};let b=await U(I,R);return B(b,R,n,o,d,g,E,e.nodeOptions,t.state)}return B(S,R,n,o,d,g,E,e.nodeOptions,t.state)}if(f.action==="reset"){if(!T)return{content:{status:"error",error:"No session ID available for reset action."}};let y;try{y=await c.get(T)}catch(b){let M=b instanceof Error?b.message:String(b);return{content:{status:"error",error:`Failed to load flow state (session "${T}"): ${M}`}}}if(!y)return{content:{status:"error",error:`Flow state not found for session "${T}". The flow may have completed or expired. Use action "start" to begin a new flow.`}};if(!y.step)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};if(!f.stateUpdates||Object.keys(f.stateUpdates).length===0)return{content:{status:"error",error:'Missing "stateUpdates" for action "reset". Include the corrected field(s).'}};let w=o.get(_);if(!w)return{content:{status:"error",error:"No start edge"}};let S=y.state,R=N(S,Z(f.stateUpdates)),I=await U(w,R);return B(I,R,n,o,d,g,E,e.nodeOptions,t.state)}return{content:{status:"error",error:`Unknown action: "${f.action}"`}}}let p=Qe(t.state),l={title:t.title,description:a,inputSchema:r,outputSchema:fe,annotations:t.annotations,...p.length>0&&{_meta:{[X]:p}}},x=(async(f,T)=>{let g=T,E=g._meta??{},y=P(E),w=y??f.sessionId;!w&&f.action==="start"&&(w=crypto.randomUUID()),w&&!y&&(E["waniwani/sessionId"]=w);let S=G(g),R=await u(f,w,E,S);if(w&&R.flowTokenContent)try{await c.set(w,R.flowTokenContent)}catch(M){let Y=M instanceof Error?M.message:String(M);return{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${w}"): ${Y}`},null,2)}],_meta:E,isError:!0}}let I=!y&&w?{...R.content,sessionId:w}:R.content,b=[{type:"text",text:JSON.stringify(I,null,2)}];return R.nodesVisited?.length&&(E[O]={flowId:t.id,nodesVisited:R.nodesVisited}),{content:b,structuredContent:I,_meta:E,...R.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:l,handler:x,async register(f){let T={...l,_meta:{...l._meta,_flowGraph:i}};f.registerTool(t.id,T,x)},graph:e.graph,flowGraph:i}}function tt(e,t){let n=["flowchart TD"];n.push(` ${_}((Start))`);for(let[o]of e)n.push(` ${o}[${o}]`);n.push(` ${F}((End))`);for(let[o,r]of t)r.type==="direct"?n.push(` ${o} --> ${r.to}`):n.push(` ${o} -.-> ${o}_branch([?])`);return n.join(`
6
- `)}var L=class{nodes=new Map;edges=new Map;nodeOptions=new Map;config;constructor(t){this.config=t}addNode(t,n,o){let r=typeof t=="string"?t:t.id,i=typeof t=="string"?n:t.run,s=typeof t=="string"?o?.label:t.label,a=typeof t=="string"?o?.hideFromFunnel:t.hideFromFunnel;if(r===_||r===F)throw new Error(`"${r}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(r))throw new Error(`Node "${r}" already exists`);return this.nodes.set(r,i),(s!==void 0||a!==void 0)&&this.nodeOptions.set(r,{label:s??r,hideFromFunnel:a}),this}addEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge. Use addConditionalEdge for branching.`);return this.edges.set(t,{type:"direct",to:n}),this}addConditionalEdge(t,n){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 tt(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),o=new Map(this.edges);return et({config:this.config,nodes:n,edges:o,store:t?.store,graph:()=>tt(n,o),nodeOptions:new Map(this.nodeOptions)})}validate(){if(!this.edges.has(_))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(_);if(t?.type==="direct"&&t.to!==F&&!this.nodes.has(t.to))throw new Error(`START edge references non-existent node: "${t.to}"`);for(let[n,o]of this.edges){if(n!==_&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(o.type==="direct"&&o.to!==F&&!this.nodes.has(o.to))throw new Error(`Edge from "${n}" references non-existent node: "${o.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 nt(e){return new L(e)}function we(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function ot(e,t){let n=t?.stateStore,o=[],r=`test-session-${Math.random().toString(36).slice(2,10)}`,i={registerTool:(...d)=>{o.push(d)}};await e.register(i);let s=o[0]?.[2];if(!s)throw new Error(`Flow "${e.name}" did not register a handler`);let a={_meta:{sessionId:r}};async function c(d){return{...d,decodedState:n?await n.get(r):null}}return{async start(d,u,p){let l=await s({action:"start",intent:d,...p?{context:p}:{},...u?{stateUpdates:u}:{}},a);return c(we(l))},async continueWith(d){let u=await s({action:"continue",...d?{stateUpdates:d}:{}},a);return c(we(u))},async resetWith(d){let u=await s({action:"reset",stateUpdates:d},a);return c(we(u))},async lastState(){return n?n.get(r):null}}}var Q=class extends Error{constructor(n,o){super(n);this.status=o;this.name="WaniWaniError"}};var Gt="@waniwani/sdk";function rt(e){let{apiUrl:t,apiKey:n}=e;function o(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function r(i,s,a){let c=o(),d=`${t.replace(/\/$/,"")}${s}`,u={Authorization:`Bearer ${c}`,"X-WaniWani-SDK":Gt},p={method:i,headers:u};a!==void 0&&(u["Content-Type"]="application/json",p.body=JSON.stringify(a));let l=await fetch(d,p);if(!l.ok){let f=await l.text().catch(()=>"");throw new Q(f||`KB API error: HTTP ${l.status}`,l.status)}return(await l.json()).data}return{async ingest(i){return r("POST","/api/mcp/kb/ingest",{files:i})},async search(i,s){return r("POST","/api/mcp/kb/search",{query:i,...s})},async sources(){return r("GET","/api/mcp/kb/sources")}}}import{existsSync as Zt,readFileSync as Jt}from"fs";import{resolve as Xt}from"path";var Qt="waniwani.json",$;function it(){if($!==void 0)return $;try{let e=Xt(process.cwd(),Qt);if(!Zt(e))return $=null,null;let t=Jt(e,"utf-8");return $=JSON.parse(t),$}catch{return $=null,null}}var en="__waniwani_config__";function st(){return globalThis[en]}var tn="@waniwani/sdk";function te(e,t={}){let n=t.now??(()=>new Date),o=t.generateId??at,r=rn(e),i=ee(e.meta),s=ee(e.metadata),a=sn(e,i),c=C(e.eventId)??o(),d=an(e.timestamp,n),u=C(e.source)??W(i)??t.source??tn,p=me(e)?{...e}:void 0,l={...s};return Object.keys(i).length>0&&(l.meta=i),p&&(l.rawLegacy=p),{id:c,type:"mcp.event",name:r,source:u,timestamp:d,correlation:a,properties:nn(e,r),metadata:l,rawLegacy:p}}function at(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function nn(e,t){if(!me(e))return ee(e.properties);let n=on(e,t),o=ee(e.properties);return{...n,...o}}function on(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 rn(e){return me(e)?e.eventType:e.event}function sn(e,t){let n=C(e.requestId)??Ae(t),o=C(e.sessionId)??P(t),r=C(e.traceId)??Me(t),i=C(e.externalUserId)??Ue(t),s=C(e.correlationId)??De(t)??n,a={};return o&&(a.sessionId=o),r&&(a.traceId=r),n&&(a.requestId=n),s&&(a.correlationId=s),i&&(a.externalUserId=i),a}function an(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 ee(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function C(e){if(typeof e=="string"&&e.trim().length!==0)return e}function me(e){return"eventType"in e}var dn="/api/mcp/events/v2/batch";var dt="@waniwani/sdk",cn=new Set([401,403]),un=new Set([408,425,429,500,502,503,504]);function ct(e){return new he(e)}var he=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=fn(t.apiUrl,t.endpointPath??dn),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(o=>setTimeout(o,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,o=this.flush();if(!Number.isFinite(n)||n<=0)return await o,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let r=Symbol("shutdown-timeout");return await Promise.race([o.then(()=>"flushed"),this.sleep(n).then(()=>r)])===r?(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,o=t;for(;o.length>0&&!this.isStopped;){this.inFlightCount=o.length;let r=await this.sendBatchOnce(o);switch(this.inFlightCount=0,r.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(r.status,o.length);return;case"permanent":this.logger.error("[WaniWani] Dropping %d event(s) after permanent failure: %s",o.length,r.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d event(s) after retry exhaustion: %s",o.length,r.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(r.permanent.length>0&&this.logger.error("[WaniWani] Dropping %d event(s) rejected as permanent",r.permanent.length),r.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d retryable event(s) after retry exhaustion",r.retryable.length);return}o=r.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":dt},body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:gn(i)}}if(cn.has(n.status))return{kind:"auth",status:n.status};if(un.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let o=await pn(n);if(!o?.rejected||o.rejected.length===0)return{kind:"success"};let r=this.classifyRejectedEvents(t,o.rejected);return r.retryable.length===0&&r.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:r.retryable,permanent:r.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:dt,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let o=new Map(t.map(s=>[s.id,s])),r=[],i=[];for(let s of n){let a=o.get(s.eventId);if(a){if(ln(s)){r.push(a);continue}i.push(a)}}return{retryable:r,permanent:i}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let o=this.buffer.length;this.buffer.splice(0,o),this.logger.error("[WaniWani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+o)}};function ln(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 pn(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function fn(e,t){let n=e.endsWith("/")?e:`${e}/`,o=t.startsWith("/")?t.slice(1):t;return`${n}${o}`}function gn(e){return e instanceof Error?e.message:String(e)}function ut(e){let{apiUrl:t,apiKey:n,tracking:o}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}let i=n?ct({apiUrl:t,apiKey:n,endpointPath:o.endpointPath,flushIntervalMs:o.flushIntervalMs,maxBatchSize:o.maxBatchSize,maxBufferSize:o.maxBufferSize,maxRetries:o.maxRetries,retryBaseDelayMs:o.retryBaseDelayMs,retryMaxDelayMs:o.retryMaxDelayMs,shutdownTimeoutMs:o.shutdownTimeoutMs}):void 0,s={async identify(a,c,d){r();let u=te({event:"user.identified",externalUserId:a,properties:c,meta:d});return i?.enqueue(u),{eventId:u.id}},async track(a){r();let c=te(a);return i?.enqueue(c),{eventId:c.id}},async flush(){r(),await i?.flush()},async shutdown(a){return r(),await i?.shutdown({timeoutMs:a?.timeoutMs??o.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&wn(s,o.shutdownTimeoutMs),s}function wn(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 ne(e){let n=e??it()??st(),o=n?.apiUrl??"https://app.waniwani.ai",r=n?.apiKey??process.env.WANIWANI_API_KEY,i={endpointPath:n?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:n?.tracking?.flushIntervalMs??1e3,maxBatchSize:n?.tracking?.maxBatchSize??20,maxBufferSize:n?.tracking?.maxBufferSize??1e3,maxRetries:n?.tracking?.maxRetries??3,retryBaseDelayMs:n?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:n?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:n?.tracking?.shutdownTimeoutMs??2e3},s={apiUrl:o,apiKey:r,tracking:i},a=ut(s),c=rt(s);return{...a,kb:c,_config:s}}function mn(e){let t=e.event_type??"widget_click",o=t.startsWith("widget_")?t:`widget_${t}`,r={...e.metadata??{}};return e.event_name&&(r.event_name=e.event_name),{event:o,properties:r,sessionId:e.session_id,traceId:e.trace_id,externalUserId:e.user_id,eventId:e.event_id,timestamp:e.timestamp,source:e.source??"widget"}}function hn(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function o(){return n||(n=ne(t)),n}return async function(i){let s;try{s=await i.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!Array.isArray(s.events)||s.events.length===0)return new Response(JSON.stringify({error:"Missing or empty events array"}),{status:400,headers:{"Content-Type":"application/json"}});try{let a=o(),c=[];for(let d of s.events){let u=mn(d),p=await a.track(u);c.push(p.eventId)}return await a.flush(),new Response(JSON.stringify({ok:!0,accepted:c.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(a){let c=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({error:c}),{status:500,headers:{"Content-Type":"application/json"}})}}}var ye=j("widget-token"),yn=120*1e3,oe=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-yn?this.cached.token:this.pending?this.pending:(this.pending=this.mint(t,n).finally(()=>{this.pending=null}),this.pending)}async mint(t,n){let o=Tn(this.config.apiUrl,"/api/mcp/widget-tokens");ye("minting token from",o);let r={};t&&(r.sessionId=t),n&&(r.traceId=n);try{let i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(r),signal:AbortSignal.timeout(5e3)});if(ye("mint response:",i.status),!i.ok)return null;let s=await i.json(),a=s.data&&typeof s.data=="object"?s.data:s,c=new Date(a.expiresAt).getTime();return!a.token||Number.isNaN(c)?null:(this.cached={token:a.token,expiresAt:c},a.token)}catch(i){return ye("mint failed:",i),null}}};function Tn(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function lt(e){if(typeof globalThis.crypto?.subtle?.digest=="function"){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return`simple-${Math.abs(t).toString(36)}`}function Sn(e){return lt(JSON.stringify({nodes:e.nodes,edges:e.edges}))}async function pt(e){if(e.length===0)return null;let t=[...e].sort((r,i)=>r.flowId.localeCompare(i.flowId)),n=await lt(JSON.stringify(t.map(r=>({flowId:r.flowId,nodes:r.nodes,edges:r.edges})))),o=await Promise.all(e.map(async r=>({flowId:r.flowId,title:r.title,configHash:await Sn(r),nodes:r.nodes,edges:r.edges})));return{compositeHash:n,flows:o}}var ft="waniwani/sessionId",re="waniwani/geoLocation",ie="waniwani/userLocation",kn="openai/userLocation",vn=[kn,re,ie];function gt(e,t){if(t.length===0)return e;let n;for(let o of vn){let r=e[o];if(!k(r))continue;let i;for(let s of t)s in r&&(i||(i={...r}),delete i[s]);i&&(n||(n={...e}),n[o]=i)}return n??e}function k(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function z(e){if(!k(e))return;let t=e._meta;return k(t)?t:void 0}function Te(e){if(!k(e))return;let t=e.content;return Array.isArray(t)?t.find(o=>k(o)&&o.type==="text"&&typeof o.text=="string")?.text:void 0}function Rn(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function Se(e,t,n,o,r,i){let s=Rn(e,n.toolType),a=n.stripLocationFields,c=a&&a.length>0,d=z(t),u=d&&c?gt(d,a):d,p=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,l=c&&k(i?.output)&&k(i.output._meta)?{...i.output,_meta:gt(i.output._meta,a)}:i?.output,f=(k(i?.output)&&k(i.output._meta)?i.output._meta:void 0)?.[O],T=f&&u?{...u,[O]:f}:f?{[O]:f}:u,g=k(i?.input)&&typeof i.input.sessionId=="string"&&i.input.sessionId.length>0?i.input.sessionId:void 0,E=g&&!P(T??void 0)?{...T??{},"waniwani/sessionId":g}:T;return{event:"tool.called",properties:{name:e,type:s,...o??{},...p!==void 0&&{input:p},...l!==void 0&&{output:l}},meta:E,source:W(E??u,r),metadata:{...n.metadata??{},...r&&{clientInfo:r},...n.funnelSync&&{funnelSync:n.funnelSync}}}}async function ke(e,t,n){try{await e.track(t)}catch(o){n?.(Re(o))}}async function ve(e,t){try{await e.flush()}catch(n){t?.(Re(n))}}async function mt(e,t,n,o,r,i){if(!k(e))return;k(e._meta)||(e._meta={});let s=e._meta,a=k(s.waniwani)?s.waniwani:void 0,c={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let l=await t.getToken();l&&(c.token=l)}catch(l){r?.(Re(l))}let d=P(s);d&&(c.sessionId||(c.sessionId=d));let u=Tt(s);u!==void 0&&(c.geoLocation||(c.geoLocation=u));let p=W(z(o),i);p&&!c.source&&(c.source=p),s.waniwani=c}var wt=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function ht(e,t){if(!t||!k(e))return;let n=!1;for(let r of wt)if(r in t){n=!0;break}if(!n)return;k(e._meta)||(e._meta={});let o=e._meta;for(let r of wt)r in t&&(r in o||(o[r]=t[r]))}function yt(e,t){let n=z(t);if(!n||!k(e))return;k(e._meta)||(e._meta={});let o=e._meta,r=P(n);r&&!o[ft]&&(o[ft]=r);let i=Tt(n);i&&(o[re]||(o[re]=i),o[ie]||(o[ie]=i))}function Tt(e){if(!e)return;let t=e[re]??e[ie];if(k(t)||typeof t=="string")return t}function Re(e){return e instanceof Error?e:new Error(String(e))}function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kt(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(St(e.requestInfo)){let t=e.requestInfo.headers;if(St(t)){let n={};for(let i of Object.keys(t))n[i.toLowerCase()]=t[i];let o=n["mcp-session-id"];if(typeof o=="string"&&o)return o;let r=n["x-waniwani-session-id"];if(typeof r=="string"&&r)return r}}}var Rt=Symbol.for("waniwani.wrappedHandler"),se=j("mcp"),xt="https://app.waniwani.ai",xn="REDACTED";function En(e){if(!e)return;let t=e[X];if(!Array.isArray(t)||t.length===0)return;let n=new Set(t.filter(o=>typeof o=="string"));if(n.size!==0)return o=>{if(!k(o))return o;let r=o.stateUpdates;if(!k(r))return o;let i=!1,s={...r};for(let a of n)a in s&&(s[a]=xn,i=!0);return i?{...o,stateUpdates:s}:o}}function vt(e,t,n,o){let{server:r,tracker:i,opts:s,tokenCache:a,injectToken:c}=n,d=s.applyFieldRedactions===!0?En(o):void 0,u=async(p,l)=>{let x=d?{...s,redactInput:d,funnelSync:n.funnelSync}:{...s,funnelSync:n.funnelSync},f=z(l)??{},T=r.server?.getClientVersion?.();if(!P(f)&&k(l)){let w=kt(l);w&&(f["waniwani/sessionId"]=w,l._meta=f)}if(!W(f)&&k(l)){let w=l.requestInfo?.headers,S=W(f,T)??Oe(w);S&&(f["waniwani/source"]=S,l._meta=f)}let E=We(i,f,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});k(l)&&(l[ce]=E);let y=performance.now();try{let w=await t(p,l),S=Math.round(performance.now()-y);se(`tool "${e}" handler returned in ${S}ms, running post-processing...`);let R=k(w)&&w.isError===!0;if(R){let I=Te(w);console.error(`[waniwani] Tool "${e}" returned error${I?`: ${I}`:""}`)}return await ke(i,Se(e,l,x,{durationMs:S,status:R?"error":"ok",...R&&{errorMessage:Te(w)??"Unknown tool error"}},T,{input:p,output:w}),s.onError),se(`tool "${e}" tracking done`),s.flushAfterToolCall&&await ve(i,s.onError),yt(w,l),ht(w,o),c&&(await mt(w,a,i._config.apiUrl??xt,l,s.onError,T),se(`tool "${e}" widget config injected`)),se(`tool "${e}" post-processing complete, returning result`),w}catch(w){let S=Math.round(performance.now()-y);throw await ke(i,Se(e,l,x,{durationMs:S,status:"error",errorMessage:w instanceof Error?w.message:String(w)},T,{input:p}),s.onError),s.flushAfterToolCall&&await ve(i,s.onError),w}};return u[Rt]=!0,u}async function In(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let o=t??{},r=o.client??ne(),i=o.injectWidgetToken!==!1,s=r._config.apiKey?new oe({apiUrl:r._config.apiUrl??xt,apiKey:r._config.apiKey}):null,a={server:e,tracker:r,opts:o,tokenCache:s,injectToken:i,funnelSync:null},c=e.registerTool.bind(e);n.registerTool=((...u)=>{let[p,l,x]=u;if(typeof x!="function")return c(...u);let f=typeof p=="string"&&p.trim().length>0?p:"unknown",T=k(l)&&k(l._meta)?l._meta:void 0,g=vt(f,x,a,T);return c(p,l,g)});let d=e._registeredTools;if(k(d))for(let[u,p]of Object.entries(d)){if(!k(p))continue;let l=p.handler;if(typeof l!="function"||l[Rt])continue;let x=k(p._meta)?p._meta:void 0;p.handler=vt(u,l,a,x)}if(r._config.apiKey){let u=e._registeredTools,p=[];if(u&&typeof u=="object"){for(let l of Object.values(u))if(l&&typeof l=="object"){let x=l._meta,f=x&&typeof x=="object"?x._flowGraph:void 0;f?.nodes?.length&&p.push(f)}}p.length>0&&(a.funnelSync=await pt(p))}return n}function xe(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function bn(){return xe()==="openai"}function Cn(){return xe()==="mcp-apps"}var ae="text/html+skybridge",de="text/html;profile=mcp-app",Et=async(e,t)=>{let n=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${n}${t}`)).text()};function It(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function bt(e){let t=e.widgetCSP?{connectDomains:e.widgetCSP.connect_domains,resourceDomains:e.widgetCSP.resource_domains,frameDomains:e.widgetCSP.frame_domains,redirectDomains:e.widgetCSP.redirect_domains}:void 0;return{ui:{...t&&{csp:t},...e.widgetDomain&&{domain:e.widgetDomain},...e.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function Ee(e){return{...e.openaiTemplateUri&&{"openai/outputTemplate":e.openaiTemplateUri},"openai/toolInvocation/invoking":e.invoking,"openai/toolInvocation/invoked":e.invoked,"openai/widgetAccessible":!0,"openai/resultCanProduceWidget":!0,...e.mcpTemplateUri&&{ui:{resourceUri:e.mcpTemplateUri,...e.autoHeight&&{autoHeight:!0}}},...e.mcpTemplateUri&&{"ui/resourceUri":e.mcpTemplateUri}}}function Ct(e){let{id:t,title:n,description:o,baseUrl:r,htmlPath:i,widgetDomain:s,prefersBorder:a=!0,autoHeight:c=!0}=e,d=e.widgetCSP??{connect_domains:[r],resource_domains:[r]};if(process.env.NODE_ENV==="development")try{let{hostname:g}=new URL(r);(g==="localhost"||g==="127.0.0.1")&&(d={...d,connect_domains:[...d.connect_domains||[],`ws://${g}:*`,`wss://${g}:*`],resource_domains:[...d.resource_domains||[],`http://${g}:*`]})}catch{}let u=`ui://widgets/apps-sdk/${t}.html`,p=`ui://widgets/ext-apps/${t}.html`,l=null,x=()=>(l||(l=Et(r,i)),l),f=o;async function T(g){let E=await x();g.registerResource(`${t}-openai-widget`,u,{title:n,description:f,mimeType:ae,_meta:{"openai/widgetDescription":f,"openai/widgetPrefersBorder":a}},async y=>({contents:[{uri:y.href,mimeType:ae,text:E,_meta:It({description:f,prefersBorder:a,widgetDomain:s,widgetCSP:d})}]})),g.registerResource(`${t}-mcp-widget`,p,{title:n,description:f,mimeType:de,_meta:{ui:{prefersBorder:a}}},async y=>({contents:[{uri:y.href,mimeType:de,text:E,_meta:bt({description:f,prefersBorder:a,widgetDomain:s,widgetCSP:d})}]}))}return{id:t,title:n,description:o,openaiUri:u,mcpUri:p,autoHeight:c,register:T}}function _n(e,t){let{resource:n,description:o,inputSchema:r,annotations:i,autoInjectResultText:s=!0}=e,a=e.id??n?.id,c=e.title??n?.title;if(!a)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?Ee({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:a,title:c,description:o,async register(u){u.registerTool(a,{title:c,description:o,inputSchema:r,annotations:i,...d&&{_meta:d}},(async(p,l)=>{let x=l,f=x._meta??{},T=G(x),g=await t(p,{extra:{_meta:f},waniwani:T});return n&&g.data?{content:[{type:"text",text:g.text}],structuredContent:g.data,_meta:{...d,...f,...s===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:g.text}],...g.data?{structuredContent:g.data}:{},...s===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function Fn(e,t){await Promise.all(t.map(n=>n.register(e)))}export{F as END,J as MemoryKvStore,_ as START,L as StateGraph,K as WaniwaniKvStore,nt as createFlow,ot as createFlowTestHarness,Ct as createResource,_n as createTool,hn as createTrackingRoute,xe as detectPlatform,Cn as isMCPApps,bn as isOpenAI,Je as redacted,Fn as registerTools,In as withWaniwani};
5
+ ${s}`,c=e.store??Yt(t.id),d=new Map;async function u(f,T,g,E){if(f.action==="start"){let y=typeof f.intent=="string"?f.intent.trim():void 0;if(!y)return{content:{status:"error",error:`Missing required "intent" for action "start". Include a brief summary of the user's goal for this flow and any relevant prior context that led to triggering it, if available.`}};if(f.intent=y,typeof f.context=="string"){let I=f.context.trim();f.context=I||void 0}let w=o.get(_);if(!w)return{content:{status:"error",error:"No start edge"}};let S=Z(f.stateUpdates??{}),R=await U(w,S);return B(R,S,n,o,d,g,E,e.nodeOptions,t.state)}if(f.action==="continue"){if(!T)return{content:{status:"error",error:"No session ID available for continue action."}};let y;try{y=await c.get(T)}catch(I){let b=I instanceof Error?I.message:String(I);return{content:{status:"error",error:`Failed to load flow state (session "${T}"): ${b}`}}}if(!y)return{content:{status:"error",error:`Flow state not found for session "${T}". The flow may have expired.`}};let w=y.state,S=y.step;if(!S)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let R=N(w,Z(f.stateUpdates??{}));if(y.widgetId){let I=o.get(S);if(!I)return{content:{status:"error",error:`No edge from step "${S}"`}};let b=await U(I,R);return B(b,R,n,o,d,g,E,e.nodeOptions,t.state)}return B(S,R,n,o,d,g,E,e.nodeOptions,t.state)}if(f.action==="reset"){if(!T)return{content:{status:"error",error:"No session ID available for reset action."}};let y;try{y=await c.get(T)}catch(b){let M=b instanceof Error?b.message:String(b);return{content:{status:"error",error:`Failed to load flow state (session "${T}"): ${M}`}}}if(!y)return{content:{status:"error",error:`Flow state not found for session "${T}". The flow may have completed or expired. Use action "start" to begin a new flow.`}};if(!y.step)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};if(!f.stateUpdates||Object.keys(f.stateUpdates).length===0)return{content:{status:"error",error:'Missing "stateUpdates" for action "reset". Include the corrected field(s).'}};let w=o.get(_);if(!w)return{content:{status:"error",error:"No start edge"}};let S=y.state,R=N(S,Z(f.stateUpdates)),I=await U(w,R);return B(I,R,n,o,d,g,E,e.nodeOptions,t.state)}return{content:{status:"error",error:`Unknown action: "${f.action}"`}}}let p=Qe(t.state),l={title:t.title,description:a,inputSchema:r,outputSchema:fe,annotations:t.annotations,...p.length>0&&{_meta:{[X]:p}}},x=(async(f,T)=>{let g=T,E=g._meta??{},y=P(E),w=y??f.sessionId;!w&&f.action==="start"&&(w=crypto.randomUUID()),w&&!y&&(E["waniwani/sessionId"]=w);let S=G(g),R=await u(f,w,E,S);if(w&&R.flowTokenContent)try{await c.set(w,R.flowTokenContent)}catch(M){let Y=M instanceof Error?M.message:String(M);return{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${w}"): ${Y}`},null,2)}],_meta:E,isError:!0}}let I=!y&&w?{...R.content,sessionId:w}:R.content,b=[{type:"text",text:JSON.stringify(I,null,2)}];return R.nodesVisited?.length&&(E[D]={flowId:t.id,nodesVisited:R.nodesVisited}),{content:b,structuredContent:I,_meta:E,...R.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:l,handler:x,async register(f){let T={...l,_meta:{...l._meta,_flowGraph:i}};f.registerTool(t.id,T,x)},graph:e.graph,flowGraph:i}}function tt(e,t){let n=["flowchart TD"];n.push(` ${_}((Start))`);for(let[o]of e)n.push(` ${o}[${o}]`);n.push(` ${F}((End))`);for(let[o,r]of t)r.type==="direct"?n.push(` ${o} --> ${r.to}`):n.push(` ${o} -.-> ${o}_branch([?])`);return n.join(`
6
+ `)}var L=class{nodes=new Map;edges=new Map;nodeOptions=new Map;config;constructor(t){this.config=t}addNode(t,n,o){let r=typeof t=="string"?t:t.id,i=typeof t=="string"?n:t.run,s=typeof t=="string"?o?.label:t.label,a=typeof t=="string"?o?.hideFromFunnel:t.hideFromFunnel;if(r===_||r===F)throw new Error(`"${r}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(r))throw new Error(`Node "${r}" already exists`);return this.nodes.set(r,i),(s!==void 0||a!==void 0)&&this.nodeOptions.set(r,{label:s??r,hideFromFunnel:a}),this}addEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge. Use addConditionalEdge for branching.`);return this.edges.set(t,{type:"direct",to:n}),this}addConditionalEdge(t,n){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 tt(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),o=new Map(this.edges);return et({config:this.config,nodes:n,edges:o,store:t?.store,graph:()=>tt(n,o),nodeOptions:new Map(this.nodeOptions)})}validate(){if(!this.edges.has(_))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(_);if(t?.type==="direct"&&t.to!==F&&!this.nodes.has(t.to))throw new Error(`START edge references non-existent node: "${t.to}"`);for(let[n,o]of this.edges){if(n!==_&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(o.type==="direct"&&o.to!==F&&!this.nodes.has(o.to))throw new Error(`Edge from "${n}" references non-existent node: "${o.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 nt(e){return new L(e)}function we(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function ot(e,t){let n=t?.stateStore,o=[],r=`test-session-${Math.random().toString(36).slice(2,10)}`,i={registerTool:(...d)=>{o.push(d)}};await e.register(i);let s=o[0]?.[2];if(!s)throw new Error(`Flow "${e.name}" did not register a handler`);let a={_meta:{sessionId:r}};async function c(d){return{...d,decodedState:n?await n.get(r):null}}return{async start(d,u,p){let l=await s({action:"start",intent:d,...p?{context:p}:{},...u?{stateUpdates:u}:{}},a);return c(we(l))},async continueWith(d){let u=await s({action:"continue",...d?{stateUpdates:d}:{}},a);return c(we(u))},async resetWith(d){let u=await s({action:"reset",stateUpdates:d},a);return c(we(u))},async lastState(){return n?n.get(r):null}}}var Q=class extends Error{constructor(n,o){super(n);this.status=o;this.name="WaniWaniError"}};var Gt="@waniwani/sdk";function rt(e){let{apiUrl:t,apiKey:n}=e;function o(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function r(i,s,a){let c=o(),d=`${t.replace(/\/$/,"")}${s}`,u={Authorization:`Bearer ${c}`,"X-WaniWani-SDK":Gt},p={method:i,headers:u};a!==void 0&&(u["Content-Type"]="application/json",p.body=JSON.stringify(a));let l=await fetch(d,p);if(!l.ok){let f=await l.text().catch(()=>"");throw new Q(f||`KB API error: HTTP ${l.status}`,l.status)}return(await l.json()).data}return{async ingest(i){return r("POST","/api/mcp/kb/ingest",{files:i})},async search(i,s){return r("POST","/api/mcp/kb/search",{query:i,...s})},async sources(){return r("GET","/api/mcp/kb/sources")}}}import{existsSync as Zt,readFileSync as Jt}from"fs";import{resolve as Xt}from"path";var Qt="waniwani.json",$;function it(){if($!==void 0)return $;try{let e=Xt(process.cwd(),Qt);if(!Zt(e))return $=null,null;let t=Jt(e,"utf-8");return $=JSON.parse(t),$}catch{return $=null,null}}var en="__waniwani_config__";function st(){return globalThis[en]}var tn="@waniwani/sdk";function te(e,t={}){let n=t.now??(()=>new Date),o=t.generateId??at,r=rn(e),i=ee(e.meta),s=ee(e.metadata),a=sn(e,i),c=C(e.eventId)??o(),d=an(e.timestamp,n),u=C(e.source)??W(i)??t.source??tn,p=me(e)?{...e}:void 0,l={...s};return Object.keys(i).length>0&&(l.meta=i),p&&(l.rawLegacy=p),{id:c,type:"mcp.event",name:r,source:u,timestamp:d,correlation:a,properties:nn(e,r),metadata:l,rawLegacy:p}}function at(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function nn(e,t){if(!me(e))return ee(e.properties);let n=on(e,t),o=ee(e.properties);return{...n,...o}}function on(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 rn(e){return me(e)?e.eventType:e.event}function sn(e,t){let n=C(e.requestId)??Ae(t),o=C(e.sessionId)??P(t),r=C(e.traceId)??Me(t),i=C(e.externalUserId)??Ue(t),s=C(e.correlationId)??Oe(t)??n,a={};return o&&(a.sessionId=o),r&&(a.traceId=r),n&&(a.requestId=n),s&&(a.correlationId=s),i&&(a.externalUserId=i),a}function an(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 ee(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function C(e){if(typeof e=="string"&&e.trim().length!==0)return e}function me(e){return"eventType"in e}var dn="/api/mcp/events/v2/batch";var dt="@waniwani/sdk",cn=new Set([401,403]),un=new Set([408,425,429,500,502,503,504]);function ct(e){return new he(e)}var he=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=fn(t.apiUrl,t.endpointPath??dn),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(o=>setTimeout(o,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,o=this.flush();if(!Number.isFinite(n)||n<=0)return await o,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let r=Symbol("shutdown-timeout");return await Promise.race([o.then(()=>"flushed"),this.sleep(n).then(()=>r)])===r?(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,o=t;for(;o.length>0&&!this.isStopped;){this.inFlightCount=o.length;let r=await this.sendBatchOnce(o);switch(this.inFlightCount=0,r.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(r.status,o.length);return;case"permanent":this.logger.error("[WaniWani] Dropping %d event(s) after permanent failure: %s",o.length,r.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d event(s) after retry exhaustion: %s",o.length,r.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(r.permanent.length>0&&this.logger.error("[WaniWani] Dropping %d event(s) rejected as permanent",r.permanent.length),r.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d retryable event(s) after retry exhaustion",r.retryable.length);return}o=r.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":dt},body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:gn(i)}}if(cn.has(n.status))return{kind:"auth",status:n.status};if(un.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let o=await pn(n);if(!o?.rejected||o.rejected.length===0)return{kind:"success"};let r=this.classifyRejectedEvents(t,o.rejected);return r.retryable.length===0&&r.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:r.retryable,permanent:r.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:dt,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let o=new Map(t.map(s=>[s.id,s])),r=[],i=[];for(let s of n){let a=o.get(s.eventId);if(a){if(ln(s)){r.push(a);continue}i.push(a)}}return{retryable:r,permanent:i}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let o=this.buffer.length;this.buffer.splice(0,o),this.logger.error("[WaniWani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+o)}};function ln(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 pn(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function fn(e,t){let n=e.endsWith("/")?e:`${e}/`,o=t.startsWith("/")?t.slice(1):t;return`${n}${o}`}function gn(e){return e instanceof Error?e.message:String(e)}function ut(e){let{apiUrl:t,apiKey:n,tracking:o}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}let i=n?ct({apiUrl:t,apiKey:n,endpointPath:o.endpointPath,flushIntervalMs:o.flushIntervalMs,maxBatchSize:o.maxBatchSize,maxBufferSize:o.maxBufferSize,maxRetries:o.maxRetries,retryBaseDelayMs:o.retryBaseDelayMs,retryMaxDelayMs:o.retryMaxDelayMs,shutdownTimeoutMs:o.shutdownTimeoutMs}):void 0,s={async identify(a,c,d){r();let u=te({event:"user.identified",externalUserId:a,properties:c,meta:d});return i?.enqueue(u),{eventId:u.id}},async track(a){r();let c=te(a);return i?.enqueue(c),{eventId:c.id}},async flush(){r(),await i?.flush()},async shutdown(a){return r(),await i?.shutdown({timeoutMs:a?.timeoutMs??o.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&wn(s,o.shutdownTimeoutMs),s}function wn(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 ne(e){let n=e??it()??st(),o=n?.apiUrl??"https://app.waniwani.ai",r=n?.apiKey??process.env.WANIWANI_API_KEY,i={endpointPath:n?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:n?.tracking?.flushIntervalMs??1e3,maxBatchSize:n?.tracking?.maxBatchSize??20,maxBufferSize:n?.tracking?.maxBufferSize??1e3,maxRetries:n?.tracking?.maxRetries??3,retryBaseDelayMs:n?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:n?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:n?.tracking?.shutdownTimeoutMs??2e3},s={apiUrl:o,apiKey:r,tracking:i},a=ut(s),c=rt(s);return{...a,kb:c,_config:s}}function mn(e){let t=e.event_type??"widget_click",o=t.startsWith("widget_")?t:`widget_${t}`,r={...e.metadata??{}};return e.event_name&&(r.event_name=e.event_name),{event:o,properties:r,sessionId:e.session_id,traceId:e.trace_id,externalUserId:e.user_id,eventId:e.event_id,timestamp:e.timestamp,source:e.source??"widget"}}function hn(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function o(){return n||(n=ne(t)),n}return async function(i){let s;try{s=await i.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!Array.isArray(s.events)||s.events.length===0)return new Response(JSON.stringify({error:"Missing or empty events array"}),{status:400,headers:{"Content-Type":"application/json"}});try{let a=o(),c=[];for(let d of s.events){let u=mn(d),p=await a.track(u);c.push(p.eventId)}return await a.flush(),new Response(JSON.stringify({ok:!0,accepted:c.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(a){let c=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({error:c}),{status:500,headers:{"Content-Type":"application/json"}})}}}var ye=K("widget-token"),yn=120*1e3,oe=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-yn?this.cached.token:this.pending?this.pending:(this.pending=this.mint(t,n).finally(()=>{this.pending=null}),this.pending)}async mint(t,n){let o=Tn(this.config.apiUrl,"/api/mcp/widget-tokens");ye("minting token from",o);let r={};t&&(r.sessionId=t),n&&(r.traceId=n);try{let i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(r),signal:AbortSignal.timeout(5e3)});if(ye("mint response:",i.status),!i.ok)return null;let s=await i.json(),a=s.data&&typeof s.data=="object"?s.data:s,c=new Date(a.expiresAt).getTime();return!a.token||Number.isNaN(c)?null:(this.cached={token:a.token,expiresAt:c},a.token)}catch(i){return ye("mint failed:",i),null}}};function Tn(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function lt(e){if(typeof globalThis.crypto?.subtle?.digest=="function"){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return`simple-${Math.abs(t).toString(36)}`}function Sn(e){return lt(JSON.stringify({nodes:e.nodes,edges:e.edges}))}async function pt(e){if(e.length===0)return null;let t=[...e].sort((r,i)=>r.flowId.localeCompare(i.flowId)),n=await lt(JSON.stringify(t.map(r=>({flowId:r.flowId,nodes:r.nodes,edges:r.edges})))),o=await Promise.all(e.map(async r=>({flowId:r.flowId,title:r.title,configHash:await Sn(r),nodes:r.nodes,edges:r.edges})));return{compositeHash:n,flows:o}}var ft="waniwani/sessionId",re="waniwani/geoLocation",ie="waniwani/userLocation",kn="openai/userLocation",vn=[kn,re,ie];function gt(e,t){if(t.length===0)return e;let n;for(let o of vn){let r=e[o];if(!k(r))continue;let i;for(let s of t)s in r&&(i||(i={...r}),delete i[s]);i&&(n||(n={...e}),n[o]=i)}return n??e}function k(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function z(e){if(!k(e))return;let t=e._meta;return k(t)?t:void 0}function Te(e){if(!k(e))return;let t=e.content;return Array.isArray(t)?t.find(o=>k(o)&&o.type==="text"&&typeof o.text=="string")?.text:void 0}function Rn(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function Se(e,t,n,o,r,i){let s=Rn(e,n.toolType),a=n.stripLocationFields,c=a&&a.length>0,d=z(t),u=d&&c?gt(d,a):d,p=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,l=c&&k(i?.output)&&k(i.output._meta)?{...i.output,_meta:gt(i.output._meta,a)}:i?.output,f=(k(i?.output)&&k(i.output._meta)?i.output._meta:void 0)?.[D],T=f&&u?{...u,[D]:f}:f?{[D]:f}:u,g=k(i?.input)&&typeof i.input.sessionId=="string"&&i.input.sessionId.length>0?i.input.sessionId:void 0,E=g&&!P(T??void 0)?{...T??{},"waniwani/sessionId":g}:T;return{event:"tool.called",properties:{name:e,type:s,...o??{},...p!==void 0&&{input:p},...l!==void 0&&{output:l}},meta:E,source:W(E??u,r),metadata:{...n.metadata??{},...r&&{clientInfo:r},...n.funnelSync&&{funnelSync:n.funnelSync}}}}async function ke(e,t,n){try{await e.track(t)}catch(o){n?.(Re(o))}}async function ve(e,t){try{await e.flush()}catch(n){t?.(Re(n))}}async function mt(e,t,n,o,r,i){if(!k(e))return;k(e._meta)||(e._meta={});let s=e._meta,a=k(s.waniwani)?s.waniwani:void 0,c={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let l=await t.getToken();l&&(c.token=l)}catch(l){r?.(Re(l))}let d=P(s);d&&(c.sessionId||(c.sessionId=d));let u=Tt(s);u!==void 0&&(c.geoLocation||(c.geoLocation=u));let p=W(z(o),i);p&&!c.source&&(c.source=p),s.waniwani=c}var wt=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function ht(e,t){if(!t||!k(e))return;let n=!1;for(let r of wt)if(r in t){n=!0;break}if(!n)return;k(e._meta)||(e._meta={});let o=e._meta;for(let r of wt)r in t&&(r in o||(o[r]=t[r]))}function yt(e,t){let n=z(t);if(!n||!k(e))return;k(e._meta)||(e._meta={});let o=e._meta,r=P(n);r&&!o[ft]&&(o[ft]=r);let i=Tt(n);i&&(o[re]||(o[re]=i),o[ie]||(o[ie]=i))}function Tt(e){if(!e)return;let t=e[re]??e[ie];if(k(t)||typeof t=="string")return t}function Re(e){return e instanceof Error?e:new Error(String(e))}function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kt(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(St(e.requestInfo)){let t=e.requestInfo.headers;if(St(t)){let n={};for(let i of Object.keys(t))n[i.toLowerCase()]=t[i];let o=n["mcp-session-id"];if(typeof o=="string"&&o)return o;let r=n["x-waniwani-session-id"];if(typeof r=="string"&&r)return r}}}var Rt=Symbol.for("waniwani.wrappedHandler"),se=K("mcp"),xt="https://app.waniwani.ai",xn="REDACTED";function En(e){if(!e)return;let t=e[X];if(!Array.isArray(t)||t.length===0)return;let n=new Set(t.filter(o=>typeof o=="string"));if(n.size!==0)return o=>{if(!k(o))return o;let r=o.stateUpdates;if(!k(r))return o;let i=!1,s={...r};for(let a of n)a in s&&(s[a]=xn,i=!0);return i?{...o,stateUpdates:s}:o}}function vt(e,t,n,o){let{server:r,tracker:i,opts:s,tokenCache:a,injectToken:c}=n,d=s.applyFieldRedactions===!0?En(o):void 0,u=async(p,l)=>{let x=d?{...s,redactInput:d,funnelSync:n.funnelSync}:{...s,funnelSync:n.funnelSync},f=z(l)??{},T=r.server?.getClientVersion?.();if(!P(f)&&k(l)){let w=kt(l);w&&(f["waniwani/sessionId"]=w,l._meta=f)}if(!W(f)&&k(l)){let w=l.requestInfo?.headers,S=W(f,T)??De(w);S&&(f["waniwani/source"]=S,l._meta=f)}let E=We(i,f,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});k(l)&&(l[ce]=E);let y=performance.now();try{let w=await t(p,l),S=Math.round(performance.now()-y);se(`tool "${e}" handler returned in ${S}ms, running post-processing...`);let R=k(w)&&w.isError===!0;if(R){let I=Te(w);console.error(`[waniwani] Tool "${e}" returned error${I?`: ${I}`:""}`)}return await ke(i,Se(e,l,x,{durationMs:S,status:R?"error":"ok",...R&&{errorMessage:Te(w)??"Unknown tool error"}},T,{input:p,output:w}),s.onError),se(`tool "${e}" tracking done`),s.flushAfterToolCall&&await ve(i,s.onError),yt(w,l),ht(w,o),c&&(await mt(w,a,i._config.apiUrl??xt,l,s.onError,T),se(`tool "${e}" widget config injected`)),se(`tool "${e}" post-processing complete, returning result`),w}catch(w){let S=Math.round(performance.now()-y);throw await ke(i,Se(e,l,x,{durationMs:S,status:"error",errorMessage:w instanceof Error?w.message:String(w)},T,{input:p}),s.onError),s.flushAfterToolCall&&await ve(i,s.onError),w}};return u[Rt]=!0,u}async function In(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let o=t??{},r=o.client??ne(),i=o.injectWidgetToken!==!1,s=r._config.apiKey?new oe({apiUrl:r._config.apiUrl??xt,apiKey:r._config.apiKey}):null,a={server:e,tracker:r,opts:o,tokenCache:s,injectToken:i,funnelSync:null},c=e.registerTool.bind(e);n.registerTool=((...u)=>{let[p,l,x]=u;if(typeof x!="function")return c(...u);let f=typeof p=="string"&&p.trim().length>0?p:"unknown",T=k(l)&&k(l._meta)?l._meta:void 0,g=vt(f,x,a,T);return c(p,l,g)});let d=e._registeredTools;if(k(d))for(let[u,p]of Object.entries(d)){if(!k(p))continue;let l=p.handler;if(typeof l!="function"||l[Rt])continue;let x=k(p._meta)?p._meta:void 0;p.handler=vt(u,l,a,x)}if(r._config.apiKey){let u=e._registeredTools,p=[];if(u&&typeof u=="object"){for(let l of Object.values(u))if(l&&typeof l=="object"){let x=l._meta,f=x&&typeof x=="object"?x._flowGraph:void 0;f?.nodes?.length&&p.push(f)}}p.length>0&&(a.funnelSync=await pt(p))}return n}function xe(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function bn(){return xe()==="openai"}function Cn(){return xe()==="mcp-apps"}var ae="text/html+skybridge",de="text/html;profile=mcp-app",Et=async(e,t)=>{let n=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${n}${t}`)).text()};function It(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function bt(e){let t=e.widgetCSP?{connectDomains:e.widgetCSP.connect_domains,resourceDomains:e.widgetCSP.resource_domains,frameDomains:e.widgetCSP.frame_domains,redirectDomains:e.widgetCSP.redirect_domains}:void 0;return{ui:{...t&&{csp:t},...e.widgetDomain&&{domain:e.widgetDomain},...e.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function Ee(e){return{...e.openaiTemplateUri&&{"openai/outputTemplate":e.openaiTemplateUri},"openai/toolInvocation/invoking":e.invoking,"openai/toolInvocation/invoked":e.invoked,"openai/widgetAccessible":!0,"openai/resultCanProduceWidget":!0,...e.mcpTemplateUri&&{ui:{resourceUri:e.mcpTemplateUri,...e.autoHeight&&{autoHeight:!0}}},...e.mcpTemplateUri&&{"ui/resourceUri":e.mcpTemplateUri}}}function Ct(e){let{id:t,title:n,description:o,baseUrl:r,htmlPath:i,widgetDomain:s,prefersBorder:a=!0,autoHeight:c=!0}=e,d=e.widgetCSP??{connect_domains:[r],resource_domains:[r]};if(process.env.NODE_ENV==="development")try{let{hostname:g}=new URL(r);(g==="localhost"||g==="127.0.0.1")&&(d={...d,connect_domains:[...d.connect_domains||[],`ws://${g}:*`,`wss://${g}:*`],resource_domains:[...d.resource_domains||[],`http://${g}:*`]})}catch{}let u=`ui://widgets/apps-sdk/${t}.html`,p=`ui://widgets/ext-apps/${t}.html`,l=null,x=()=>(l||(l=Et(r,i)),l),f=o;async function T(g){let E=await x();g.registerResource(`${t}-openai-widget`,u,{title:n,description:f,mimeType:ae,_meta:{"openai/widgetDescription":f,"openai/widgetPrefersBorder":a}},async y=>({contents:[{uri:y.href,mimeType:ae,text:E,_meta:It({description:f,prefersBorder:a,widgetDomain:s,widgetCSP:d})}]})),g.registerResource(`${t}-mcp-widget`,p,{title:n,description:f,mimeType:de,_meta:{ui:{prefersBorder:a}}},async y=>({contents:[{uri:y.href,mimeType:de,text:E,_meta:bt({description:f,prefersBorder:a,widgetDomain:s,widgetCSP:d})}]}))}return{id:t,title:n,description:o,openaiUri:u,mcpUri:p,autoHeight:c,register:T}}function _n(e,t){let{resource:n,description:o,inputSchema:r,annotations:i,autoInjectResultText:s=!0}=e,a=e.id??n?.id,c=e.title??n?.title;if(!a)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?Ee({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:a,title:c,description:o,async register(u){u.registerTool(a,{title:c,description:o,inputSchema:r,annotations:i,...d&&{_meta:d}},(async(p,l)=>{let x=l,f=x._meta??{},T=G(x),g=await t(p,{extra:{_meta:f},waniwani:T});return n&&g.data?{content:[{type:"text",text:g.text}],structuredContent:g.data,_meta:{...d,...f,...s===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:g.text}],...g.data?{structuredContent:g.data}:{},...s===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function Fn(e,t){await Promise.all(t.map(n=>n.register(e)))}export{F as END,J as MemoryKvStore,_ as START,L as StateGraph,j as WaniwaniKvStore,nt as createFlow,ot as createFlowTestHarness,Ct as createResource,_n as createTool,hn as createTrackingRoute,xe as detectPlatform,Cn as isMCPApps,bn as isOpenAI,Je as redacted,Fn as registerTools,In as withWaniwani};
7
7
  //# sourceMappingURL=index.js.map