@waniwani/sdk 0.15.2 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat/embed.js +68 -68
- package/dist/chat/embed.js.map +1 -1
- package/dist/chat/express-js/index.d.ts +17 -8
- package/dist/chat/index.d.ts +305 -0
- package/dist/chat/index.js +7 -7
- package/dist/chat/index.js.map +1 -1
- package/dist/chat/next-js/index.d.ts +17 -8
- package/dist/chat/styles.css +1 -1
- package/dist/index.d.ts +88 -9
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/legacy/chat/express-js/index.d.ts +17 -8
- package/dist/legacy/chat/next-js/index.d.ts +17 -8
- package/dist/legacy/index.d.ts +83 -8
- package/dist/legacy/index.js +13 -13
- package/dist/legacy/index.js.map +1 -1
- package/dist/legacy/mcp/react.js.map +1 -1
- package/dist/mcp/index.d.ts +43 -14
- package/dist/mcp/index.js +5 -5
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/react/skybridge.d.ts +355 -0
- package/dist/mcp/react/skybridge.js +3 -0
- package/dist/mcp/react/skybridge.js.map +1 -0
- package/dist/mcp/react.d.ts +297 -52
- package/dist/mcp/react.js +6 -6
- package/dist/mcp/react.js.map +1 -1
- package/package.json +11 -2
package/dist/mcp/index.d.ts
CHANGED
|
@@ -67,7 +67,14 @@ interface KbClient {
|
|
|
67
67
|
sources(): Promise<KbSource[]>;
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
-
|
|
70
|
+
/**
|
|
71
|
+
* Every event name in the typed taxonomy, as a runtime list. Single source of
|
|
72
|
+
* truth for {@link EventType} and for surfaces that need to recognize
|
|
73
|
+
* first-class names at runtime (the widget transport passes these through
|
|
74
|
+
* verbatim instead of namespacing them as custom widget events).
|
|
75
|
+
*/
|
|
76
|
+
declare const EVENT_TYPES: readonly ["session.started", "page.viewed", "tool.called", "quote.requested", "quote.succeeded", "quote.failed", "link.clicked", "purchase.completed", "widget_render", "user.identified", "price_shown", "prices_compared", "option_selected", "lead_qualified", "converted"];
|
|
77
|
+
type EventType = (typeof EVENT_TYPES)[number];
|
|
71
78
|
/**
|
|
72
79
|
* Properties for `page.viewed` — emitted once when the chat widget initializes
|
|
73
80
|
* on a host page (the top of the funnel). Attributed to the anonymous
|
|
@@ -165,6 +172,13 @@ interface TrackingContext {
|
|
|
165
172
|
requestId?: string;
|
|
166
173
|
correlationId?: string;
|
|
167
174
|
externalUserId?: string;
|
|
175
|
+
/**
|
|
176
|
+
* Anonymous visitor id (the analytics "device id"). Counts as identity on
|
|
177
|
+
* its own: the ingest API accepts `sessionId`, `externalUserId`, or
|
|
178
|
+
* `visitorId`. The chat widget uses it for pre-session events like
|
|
179
|
+
* `page.viewed`.
|
|
180
|
+
*/
|
|
181
|
+
visitorId?: string;
|
|
168
182
|
/** Optional explicit envelope fields. */
|
|
169
183
|
eventId?: string;
|
|
170
184
|
timestamp?: string | Date;
|
|
@@ -200,6 +214,8 @@ type TrackEvent = ({
|
|
|
200
214
|
properties?: PurchaseCompletedProperties;
|
|
201
215
|
} & BaseTrackEvent) | ({
|
|
202
216
|
event: "user.identified";
|
|
217
|
+
} & BaseTrackEvent) | ({
|
|
218
|
+
event: "widget_render";
|
|
203
219
|
} & BaseTrackEvent) | ({
|
|
204
220
|
event: "price_shown";
|
|
205
221
|
properties?: PriceShownProperties;
|
|
@@ -267,13 +283,6 @@ interface RevenueTrackingApi {
|
|
|
267
283
|
leadQualified: (input?: RevenueLeadQualifiedInput) => Promise<{
|
|
268
284
|
eventId: string;
|
|
269
285
|
}>;
|
|
270
|
-
/**
|
|
271
|
-
* @deprecated Renamed in 0.15.0. Use `track.leadQualified()` instead; this
|
|
272
|
-
* alias emits a `lead_qualified` event and will be removed in 0.16.0.
|
|
273
|
-
*/
|
|
274
|
-
lead: (input?: RevenueLeadQualifiedInput) => Promise<{
|
|
275
|
-
eventId: string;
|
|
276
|
-
}>;
|
|
277
286
|
converted: (input: RevenueConvertedInput) => Promise<{
|
|
278
287
|
eventId: string;
|
|
279
288
|
}>;
|
|
@@ -350,6 +359,11 @@ interface TrackingClient {
|
|
|
350
359
|
shutdown: (options?: TrackingShutdownOptions) => Promise<TrackingShutdownResult>;
|
|
351
360
|
}
|
|
352
361
|
|
|
362
|
+
/**
|
|
363
|
+
* Well-known key used to attach the scoped client to the MCP `extra` object.
|
|
364
|
+
* Read by `createTool` and flow compilation to surface it in handler contexts.
|
|
365
|
+
*/
|
|
366
|
+
declare const SCOPED_CLIENT_KEY = "waniwani/client";
|
|
353
367
|
/**
|
|
354
368
|
* A request-scoped Waniwani client with meta pre-attached.
|
|
355
369
|
*
|
|
@@ -357,6 +371,13 @@ interface TrackingClient {
|
|
|
357
371
|
* when the server is wrapped with `withWaniwani()`.
|
|
358
372
|
*/
|
|
359
373
|
interface ScopedWaniWaniClient {
|
|
374
|
+
/**
|
|
375
|
+
* The session id this request's events correlate to, resolved from the
|
|
376
|
+
* request meta. Read it to link the session to your own records (store it
|
|
377
|
+
* on a lead, then send an off-platform `converted` with the same
|
|
378
|
+
* `sessionId` later). `undefined` when the host provided no session id.
|
|
379
|
+
*/
|
|
380
|
+
readonly sessionId?: string;
|
|
360
381
|
/**
|
|
361
382
|
* Track an event — request meta is automatically merged. Also exposes the
|
|
362
383
|
* revenue helpers flat (`track.priceShown()`, `track.converted()`, …), which
|
|
@@ -375,6 +396,11 @@ interface ScopedWaniWaniClient {
|
|
|
375
396
|
apiKey?: string;
|
|
376
397
|
};
|
|
377
398
|
}
|
|
399
|
+
/**
|
|
400
|
+
* Extract the scoped client from the MCP `extra` object.
|
|
401
|
+
* Returns undefined if `withWaniwani()` is not wrapping the server.
|
|
402
|
+
*/
|
|
403
|
+
declare function extractScopedClient(extra: unknown): ScopedWaniWaniClient | undefined;
|
|
378
404
|
|
|
379
405
|
type WidgetCSP = {
|
|
380
406
|
/** Domains permitted for fetch/XHR network requests */
|
|
@@ -1148,10 +1174,13 @@ declare function createFlowTestHarness(flow: RegisteredFlow, options?: {
|
|
|
1148
1174
|
}>;
|
|
1149
1175
|
|
|
1150
1176
|
/**
|
|
1151
|
-
* Server-side API route handler for
|
|
1177
|
+
* Server-side API route handler for frontend tracking events.
|
|
1152
1178
|
*
|
|
1153
|
-
* Receives
|
|
1154
|
-
*
|
|
1179
|
+
* Receives V2 batch payloads from the SDK's frontend tracking client
|
|
1180
|
+
* (`createFrontendClient`, `useWaniwani`, `chat.track`) configured with your
|
|
1181
|
+
* own endpoint, and forwards them to the Waniwani backend with the secret
|
|
1182
|
+
* API key. Use this proxy when you do not want any Waniwani credential in
|
|
1183
|
+
* the browser; the direct path (public token or widget JWT) needs no route.
|
|
1155
1184
|
*
|
|
1156
1185
|
* @example Next.js App Router
|
|
1157
1186
|
* ```typescript
|
|
@@ -1173,8 +1202,8 @@ interface TrackingRouteOptions {
|
|
|
1173
1202
|
apiUrl?: string;
|
|
1174
1203
|
}
|
|
1175
1204
|
/**
|
|
1176
|
-
* Creates a POST handler that receives tracking
|
|
1177
|
-
*
|
|
1205
|
+
* Creates a POST handler that receives frontend tracking batches and
|
|
1206
|
+
* forwards them to the Waniwani backend.
|
|
1178
1207
|
*/
|
|
1179
1208
|
declare function createTrackingRoute(options?: TrackingRouteOptions): (request: Request) => Promise<Response>;
|
|
1180
1209
|
|
|
@@ -1629,4 +1658,4 @@ declare function createTool<TInput extends z.ZodRawShape>(config: ToolConfig<TIn
|
|
|
1629
1658
|
*/
|
|
1630
1659
|
declare function registerTools(server: McpServer, tools: RegisteredTool[]): Promise<void>;
|
|
1631
1660
|
|
|
1632
|
-
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 };
|
|
1661
|
+
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, SCOPED_CLIENT_KEY, 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, extractScopedClient, isMCPApps, isOpenAI, redacted, registerTools, withWaniwani };
|
package/dist/mcp/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
1
|
+
var P="__start__",F="__end__",Pe=Symbol.for("waniwani.flow.interrupt"),Fe=Symbol.for("waniwani.flow.widget");function Ae(e,t){let n=t?.context,r=[];for(let[o,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&"question"in i){let s=i;r.push({question:s.question,field:o,suggestions:s.suggestions,context:s.context,validate:s.validate})}return{__type:Pe,questions:r,context:n}}function Ne(e,t){let n=typeof e=="object"&&e!==null&&"tool"in e,r=n?e.tool:e,o=n?e:t??{};if(o.description!==void 0){let d=typeof r=="string"?r:r.id;throw new Error(`showWidget("${d}", { 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 "${d}" tool's own response instead.`)}let{data:i,interactive:s,field:a}=o;return{__type:Fe,tool:typeof r=="string"?r:r.id,...i!==void 0?{data:i}:{},...s!==void 0?{interactive:s}:{},...a!==void 0?{field:a}:{}}}function We(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Pe}function Me(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Fe}import{z as W}from"zod";function Z(e){return{priceShown:({amount:t,currency:n,itemId:r,label:o,...i})=>e({event:"price_shown",properties:{amount:t,currency:n,itemId:r,label:o},...i}),pricesCompared:({options:t,...n})=>e({event:"prices_compared",properties:{options:t},...n}),optionSelected:({id:t,amount:n,currency:r,...o})=>e({event:"option_selected",properties:{id:t,amount:n,currency:r},...o}),leadQualified:t=>{let{externalId:n,email:r,name:o,...i}=t??{};return e({event:"lead_qualified",properties:{externalId:n,email:r,name:o},...i})},converted:({amount:t,currency:n,occurredAt:r,...o})=>e({event:"converted",properties:{amount:t,currency:n,occurredAt:r},...o})}}function D(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var Ot=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","mcp-session-id"],Ut=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],Dt=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],Kt=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],jt=["waniwani/visitorId","visitorId"],Lt=["correlationId","openai/requestId"];var K="waniwani/flow",J="waniwani/widget";function _(e){return e?D(e,Ot):void 0}function Ue(e){return e?D(e,Ut):void 0}function De(e){return e?D(e,Dt):void 0}function Ke(e){return e?D(e,Kt):void 0}function je(e){return e?D(e,jt):void 0}function Le(e){return e?D(e,Lt):void 0}var qt=[{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"}],Bt=[{needle:"claude",source:"claude"},{needle:"chatgpt",source:"chatgpt"},{needle:"openai",source:"chatgpt"},{needle:"gemini",source:"gemini"}];function A(e,t){if(e){let r=e["waniwani/source"];if(typeof r=="string"&&r.length>0)return r;for(let{key:o,source:i}of qt){let s=e[o];if(typeof s=="string"&&s.length>0)return i}}let n=t?.name;if(typeof n=="string"&&n.length>0){let r=n.toLowerCase();for(let{needle:o,source:i}of Bt)if(r.includes(o))return i}}function Oe(e,t){let n=t.toLowerCase(),r=e[t]??e[n];if(r===void 0){for(let i of Object.keys(e))if(i.toLowerCase()===n){r=e[i];break}}let o=Array.isArray(r)?r[0]:r;return typeof o=="string"&&o.length>0?o:void 0}function qe(e){if(!e)return;let t=Oe(e,"user-agent"),n=Oe(e,"x-anthropic-client");if(t&&/claude/i.test(t)||n&&/claude|anthropic/i.test(n))return"claude";if(t&&/chatgpt|openai/i.test(t))return"chatgpt"}var Q="waniwani/client";function $(e){if(typeof e=="object"&&e!==null)return e[Q]}function Be(e,t,n){let r=o=>e.track({...o,meta:{...t,...o.meta}});return{sessionId:_(t),track:Object.assign(r,Z(r)),identify(o,i){return e.identify(o,i,t)},kb:e.kb,_config:n}}function $e(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function V(e,t){let n=t.split("."),r=e;for(let o of n){if(r==null||typeof r!="object")return;r=r[o]}return r}function $t(e,t,n){let r=t.split("."),o=r.pop();if(!o)return;let i=e;for(let s of r)(i[s]==null||typeof i[s]!="object"||Array.isArray(i[s]))&&(i[s]={}),i=i[s];i[o]=n}function Ve(e,t){let n=t.split("."),r=n.pop();if(!r)return;let o=e;for(let i of n){if(o==null||typeof o!="object")return;o=o[i]}o!=null&&typeof o=="object"&&delete o[r]}function X(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?$t(t,n,r):r!==null&&typeof r=="object"&&!Array.isArray(r)?t=N(t,{[n]:r}):t[n]=r;return t}function N(e,t){let n={...e};for(let[r,o]of Object.entries(t))o!==null&&typeof o=="object"&&!Array.isArray(o)&&n[r]!==null&&typeof n[r]=="object"&&!Array.isArray(n[r])?n[r]=N(n[r],o):n[r]=o;return n}function ze(e){return e._zod?.def}function Vt(e){let t=e,n=!1;for(let r=0;r<8;r++){let o=ze(t);if(!o?.innerType)break;if(o.type==="optional"||o.type==="nullable"||o.type==="default"){n=!0,t=o.innerType;continue}break}return{inner:t,optional:n}}function He(e){let{inner:t,optional:n}=Vt(e),r=t.description??e.description??void 0,o=ze(t),i=o?.type,s={type:"unknown",...r?{description:r}:{},...n?{optional:!0}:{}};return i==="enum"&&o?.entries?{...s,type:"enum",values:Object.keys(o.entries)}:i==="string"||i==="number"||i==="boolean"||i==="object"||i==="array"?{...s,type:i}:s}function fe(e,t){if(!e||!t)return;if(t.includes(".")){let r=t.indexOf("."),o=t.slice(0,r),i=t.slice(r+1),s=e[o];if(!s)return;let d=$e(s)?.[i];return d?He(d):void 0}let n=e[t];if(n)return He(n)}function ge(e){return e!=null&&e!==""}async function O(e,t){return e.type==="direct"?e.to:e.condition(t)}function Ye(e,t,n,r,o){if(e.every(c=>ge(V(r,c.field))))return null;let i=e.filter(c=>!ge(V(r,c.field))).map(c=>{let p=fe(o,c.field);return p?{...c,fieldSchema:p}:c}),s=i.length===1,a=i[0];return{content:s&&a?{status:"interrupt",question:a.question,field:a.field,...a.suggestions?{suggestions:a.suggestions}:{},...a.fieldSchema?{fieldSchema:a.fieldSchema}:{},...a.context||t?{context:a.context??t}:{}}:{status:"interrupt",questions:i,...t?{context:t}:{}},flowTokenContent:{step:n,state:r,...s&&a?{field:a.field}:{}}}}async function H(e,t,n,r,o,i,s,a,d){let c=e,p={...t},u=[],l=50,v=0;for(;v++<l;){if(c===F)return{content:{status:"complete"},flowTokenContent:{state:p},nodesVisited:u};let f=n.get(c);if(!f)return{content:{status:"error",error:`Unknown node: "${c}"`},nodesVisited:u};a?.get(c)?.hideFromFunnel||u.push({id:c,at:new Date().toISOString()});try{let g=await f({state:p,meta:i,interrupt:Ae,showWidget:Ne,waniwani:s});if(We(g)){for(let m of g.questions)m.validate&&o.set(`${c}:${m.field}`,m.validate);let y=Ye(g.questions,g.context,c,p,d);if(y)return{...y,nodesVisited:u};for(let m of g.questions){let S=o.get(`${c}:${m.field}`);if(S)try{let I=V(p,m.field),b=await S(I);b&&typeof b=="object"&&(p=N(p,b))}catch(I){let b=I instanceof Error?I.message:String(I);Ve(p,m.field);let M=g.questions.map(U=>U.field===m.field?{...U,context:U.context?`ERROR: ${b}
|
|
2
2
|
|
|
3
|
-
${O.context}`:`ERROR: ${b}`}:O),Y=He(M,g.context,c,d,l);if(Y)return{...Y,nodesVisited:u};break}}let R=o.get(c);if(!R)return{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:u};c=await U(R,d);continue}if(We(g)){let y=g.field;if(y&&fe(B(d,y))){let S=o.get(c);if(!S)return{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:u};c=await U(S,d);continue}let R=y?pe(l,y):void 0,w=g.interactive!==!1;return{content:{status:"widget",tool:g.tool,...g.data!==void 0?{data:g.data}:{},description:w?`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:w,...y?{field:y}:{},...R?{fieldSchema:R}:{}},flowTokenContent:{step:c,state:d,field:y,widgetId:g.tool},nodesVisited:u}}d=N(d,g);let E=o.get(c);if(!E)return{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:u};c=await U(E,d)}catch(T){return{content:{status:"error",error:T instanceof Error?T.message:String(T)},flowTokenContent:{step:c,state:d},nodesVisited:u}}}return{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"},nodesVisited:u}}function ge(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var ze=new Map;async function Ye(e){let t=ze.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 ze.set(e,o),o}async function Ge(e,t){let n=await Ye(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 Ye(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 qt={debug:0,warn:1,error:2,none:3};function Bt(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in qt?e:process.env.WANIWANI_DEBUG?"debug":"none"}function K(e,t){return t??Bt()==="debug"?(...o)=>console.log(`[waniwani:${e}]`,...o):()=>{}}var Vt="@waniwani/sdk",Ht="https://app.waniwani.ai",zt=K("kv"),j=class{get baseUrl(){return(process.env.WANIWANI_API_URL??Ht).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(ge(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;zt(`set "${t}" \u2014 encryption ${r?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let i=r?await Ge(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":Vt},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 X=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 H=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 Yt(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function Je(e,t,n,o){let r=[];for(let[s,a]of t){let l=o.get(s);r.push({id:s,type:Yt(a),label:l?.label??s,...l?.hideFromFunnel?{hideFromFunnel:!0}:{}})}let i=[];for(let[s,a]of n)a.type==="direct"?i.push({from:s,to:a.to,type:"direct"}):i.push({from:s,to:a.targets,type:"conditional"});return{flowId:e.id,title:e.title,nodes:r,edges:i}}import{z as x}from"zod";var Xe=x.object({type:x.enum(["enum","string","number","boolean","object","array","unknown"]),values:x.array(x.string()).optional(),description:x.string().optional(),optional:x.boolean().optional()}).describe("JIT schema fragment for a state field \u2014 type, allowed values, and description."),Gt=x.object({question:x.string(),field:x.string(),suggestions:x.array(x.string()).optional(),context:x.string().optional(),fieldSchema:Xe.optional()}).describe("One question within a multi-question interrupt."),we={status:x.enum(["interrupt","widget","complete","error"]).describe("Current flow status and the next action the assistant should take."),question:x.string().optional().describe("Single question to ask the user when status is interrupt."),field:x.string().optional().describe("State field to fill with the user's answer on the next continue call."),fieldSchema:Xe.optional().describe("JIT schema fragment for the single-question shorthand."),suggestions:x.array(x.string()).optional().describe("Suggested answers for the single-question shorthand."),questions:x.array(Gt).optional().describe("Multiple questions to ask the user when status is interrupt."),context:x.string().optional().describe("Private instruction context for the assistant."),tool:x.string().optional().describe("Widget tool to call when status is widget."),data:x.record(x.string(),x.unknown()).optional().describe("Input data to pass to the widget tool."),description:x.string().optional().describe("Instruction for rendering the requested widget."),interactive:x.boolean().optional().describe("Whether the widget requires user interaction before continuing."),sessionId:x.string().optional().describe("Session identifier to pass on future continue and reset calls."),error:x.string().optional().describe("Error message when status is error.")};function Qe(e){let t=["","## FLOW EXECUTION PROTOCOL","","This tool implements a multi-step conversational flow. Follow this protocol exactly:","",'1. Call with `action: "start"` to begin and include `intent`.'," `intent` must be a brief summary of the user's goal for this flow."," Do NOT invent missing intent."," Optionally include `context` \u2014 the situation or environment that led the user to start"," this flow (e.g. what page they are on, what they were doing, or what triggered the request)."," Only provide `context` when there is genuinely relevant situational information. Do NOT invent missing context."," If the user's message already contains answers to likely questions,"," extract them into `stateUpdates` as `{ field: value }` pairs (see the `stateUpdates` schema"," for the list of writable fields). The engine will auto-skip steps whose fields are already filled."," Only extract values the user explicitly stated \u2014 do NOT guess or invent values."];return e.omitIntentPII&&t.push(" Do NOT include PII in `intent` or `context` \u2014 no names, emails, phones, addresses, IDs, ages, or birthdates.",' Summarize the goal abstractly (e.g. "user wants a quote", not "Jane Doe wants a quote").'),t.push(" For grouped fields (z.object state), use dot-notation keys in `stateUpdates`:",' e.g. `{ "driver.name": "John", "driver.license": "ABC123" }`.',"2. The response JSON `status` field tells you what to do next:",' - `"interrupt"`: Pause and ask the user. Two forms:'," a. Single question: `{ question, field, fieldSchema?, context? }` \u2014 ask `question`, store answer in `field`."," b. Multi-question: `{ questions: [{question, field, fieldSchema?}, ...], context? }` \u2014 ask ALL questions"," in one conversational message, collect all answers."," `fieldSchema` (when present) describes the expected value: `{ type, values?, description?, optional? }`.",' Use it to validate before sending \u2014 match enum `values` exactly, coerce strings to numbers where `type: "number"`.'," `context` (if present) is hidden AI instructions \u2014 use to shape your response, do NOT show verbatim."," Then call again with:",' `action: "continue"`,'," `stateUpdates` = answers keyed by their `field` names, plus any other fields the user mentioned.",' - `"widget"`: The flow wants to show a UI widget. Call the tool named in the `tool`'," field, passing the `data` object as the tool's input."," Check the `interactive` field in the response:"," \u2022 `interactive: true` \u2014 The widget requires user interaction. After calling the display tool,"," STOP and WAIT for the user to interact with the widget. Do NOT call this flow tool again"," until the user has responded. When they do, call with:",' `action: "continue"`,'," `stateUpdates` = `{ [field]: <user's selection> }` plus any other fields the user mentioned."," \u2022 `interactive: false` \u2014 The widget is display-only. You MUST STILL call the display tool"," FIRST to render it for the user \u2014 this is a required, user-visible step. Do NOT skip it",' and do NOT jump straight to `action: "continue"`. ONLY AFTER you have called the display',' tool, call THIS flow tool again with `action: "continue"`. Do NOT wait for user interaction.',' - `"complete"`: The flow is done. Present the result to the user.',' - `"error"`: Something went wrong. Show the `error` message.',"","3. Do NOT invent state values. Only use `stateUpdates` for information the user explicitly provided.","4. Include only the fields the user actually answered in `stateUpdates` \u2014 do NOT guess missing ones."," If the user did not answer all pending questions, the engine will re-prompt for the remaining ones."," If the user mentioned values for other known fields, include those too \u2014"," they will be applied immediately and those steps will be auto-skipped.","5. CORRECTION: If the user wants to CHANGE a previously-answered field",' (e.g. "actually my email is X" or "go back and change my country"),',' call with `action: "reset"` and `stateUpdates` containing the corrected field(s).'," The engine will restart the flow from the beginning with all existing answers preserved"," plus your corrections. Steps with filled answers will be auto-skipped."," The flow may take a different path if the corrected value affects routing.",' Do NOT use "reset" for the CURRENT question \u2014 use "continue" for that.',"6. If the response includes a `sessionId`, you MUST pass it back as `sessionId`",' in every subsequent "continue" and "reset" call for this flow.'),t.join(`
|
|
4
|
-
`)}function
|
|
5
|
-
${s}`,
|
|
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,o){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge.`);if(n.length===0)throw new Error(`Conditional edge from "${t}" must declare at least one target node in \`to\`.`);return this.edges.set(t,{type:"conditional",condition:o,targets:[...n]}),this}graph(){return rt(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),o=new Map(this.edges);return ot({config:this.config,nodes:n,edges:o,store:t?.store,graph:()=>rt(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}"`);if(o.type==="conditional"&&o.targets){for(let r of o.targets)if(r!==F&&!this.nodes.has(r))throw new Error(`Conditional edge from "${n}" declares non-existent target: "${r}"`)}}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 it(e){return new L(e)}function he(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function st(e,t){let n=t?.stateStore,o=[],r=`test-session-${Math.random().toString(36).slice(2,10)}`,i={registerTool:(...c)=>{o.push(c)}};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 l(c){return{...c,decodedState:n?await n.get(r):null}}return{async start(c,d,u){let p=await s({action:"start",intent:c,...u?{context:u}:{},...d?{stateUpdates:d}:{}},a);return l(he(p))},async continueWith(c){let d=await s({action:"continue",...c?{stateUpdates:c}:{}},a);return l(he(d))},async resetWith(c){let d=await s({action:"reset",stateUpdates:c},a);return l(he(d))},async lastState(){return n?n.get(r):null}}}var ee=class extends Error{constructor(n,o){super(n);this.status=o;this.name="WaniWaniError"}};import{AsyncLocalStorage as Qt}from"async_hooks";var at=globalThis,te=at.__waniwaniKbRetrievalStore;te||(te=new Qt,at.__waniwaniKbRetrievalStore=te);var ye=te;function ct(e){try{ye.getStore()?.searches.push(e)}catch{}}var en="@waniwani/sdk";function dt(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 l=o(),c=`${t.replace(/\/$/,"")}${s}`,d={Authorization:`Bearer ${l}`,"X-WaniWani-SDK":en},u={method:i,headers:d};a!==void 0&&(d["Content-Type"]="application/json",u.body=JSON.stringify(a));let p=await fetch(c,u);if(!p.ok){let f=await p.text().catch(()=>"");throw new ee(f||`KB API error: HTTP ${p.status}`,p.status)}return(await p.json()).data}return{async ingest(i){return r("POST","/api/mcp/kb/ingest",{files:i})},async search(i,s){let a=await r("POST","/api/mcp/kb/search",{query:i,...s});return ct({query:i,resultCount:a.length,results:a.map(l=>({source:l.source,heading:l.heading,score:l.score}))}),a},async sources(){return r("GET","/api/mcp/kb/sources")}}}import{existsSync as tn,readFileSync as nn}from"fs";import{resolve as on}from"path";var rn="waniwani.json",$;function lt(){if($!==void 0)return $;try{let e=on(process.cwd(),rn);if(!tn(e))return $=null,null;let t=nn(e,"utf-8");return $=JSON.parse(t),$}catch{return $=null,null}}var sn="__waniwani_config__";function ut(){return globalThis[sn]}var an="@waniwani/sdk";function oe(e,t={}){let n=t.now??(()=>new Date),o=t.generateId??pt,r=ln(e),i=ne(e.meta),s=ne(e.metadata),a=un(e,i),l=C(e.eventId)??o(),c=pn(e.timestamp,n),d=C(e.source)??A(i)??t.source??an,u=Te(e)?{...e}:void 0,p={...s};return Object.keys(i).length>0&&(p.meta=i),u&&(p.rawLegacy=u),{id:l,type:"mcp.event",name:r,source:d,timestamp:c,correlation:a,properties:cn(e,r),metadata:p,rawLegacy:u}}function pt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function cn(e,t){if(!Te(e))return ne(e.properties);let n=dn(e,t),o=ne(e.properties);return{...n,...o}}function dn(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 ln(e){let t=Te(e)?e.eventType:e.event;return t==="lead"?"lead_qualified":t}function un(e,t){let n=C(e.requestId)??Oe(t),o=C(e.sessionId)??P(t),r=C(e.traceId)??De(t),i=C(e.externalUserId)??Ke(t),s=C(e.correlationId)??je(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 pn(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 ne(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function C(e){if(typeof e=="string"&&e.trim().length!==0)return e}function Te(e){return"eventType"in e}var fn="/api/mcp/events/v2/batch";var ft="@waniwani/sdk",gn=new Set([401,403]),wn=new Set([408,425,429,500,502,503,504]);function gt(e){return new Se(e)}var Se=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=yn(t.apiUrl,t.endpointPath??fn),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":ft},body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:Tn(i)}}if(gn.has(n.status))return{kind:"auth",status:n.status};if(wn.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let o=await hn(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:ft,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(mn(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 mn(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 hn(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function yn(e,t){let n=e.endsWith("/")?e:`${e}/`,o=t.startsWith("/")?t.slice(1):t;return`${n}${o}`}function Tn(e){return e instanceof Error?e.message:String(e)}function wt(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?gt({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;function s(d){r();let u=oe(d);return!u.correlation.sessionId&&!u.correlation.externalUserId&&console.warn(`[waniwani] event "${u.name}" has no sessionId or externalUserId; the ingest API requires one and will reject it.`),i?.enqueue(u),{eventId:u.id}}let a=async d=>s(d),l=Object.assign(a,G(a)),c={async identify(d,u,p){r();let v=oe({event:"user.identified",externalUserId:d,properties:u,meta:p});return i?.enqueue(v),{eventId:v.id}},track:l,async flush(){r(),await i?.flush()},async shutdown(d){return r(),await i?.shutdown({timeoutMs:d?.timeoutMs??o.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&Sn(c,o.shutdownTimeoutMs),c}function Sn(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 re(e){let n=e??lt()??ut(),o=n?.apiUrl??process.env.WANIWANI_API_URL??"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=wt(s),l=dt(s);return{...a,kb:l,_config:s}}function kn(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 vn(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function o(){return n||(n=re(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(),l=[];for(let c of s.events){let d=kn(c),u=await a.track(d);l.push(u.eventId)}return await a.flush(),new Response(JSON.stringify({ok:!0,accepted:l.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(a){let l=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({error:l}),{status:500,headers:{"Content-Type":"application/json"}})}}}var ke=K("widget-token"),Rn=120*1e3,ie=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-Rn?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=xn(this.config.apiUrl,"/api/mcp/widget-tokens");ke("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(ke("mint response:",i.status),!i.ok)return null;let s=await i.json(),a=s.data&&typeof s.data=="object"?s.data:s,l=new Date(a.expiresAt).getTime();return!a.token||Number.isNaN(l)?null:(this.cached={token:a.token,expiresAt:l},a.token)}catch(i){return ke("mint failed:",i),null}}};function xn(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function mt(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 In(e){return mt(JSON.stringify({nodes:e.nodes,edges:e.edges}))}async function ht(e){if(e.length===0)return null;let t=[...e].sort((r,i)=>r.flowId.localeCompare(i.flowId)),n=await mt(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 In(r),nodes:r.nodes,edges:r.edges})));return{compositeHash:n,flows:o}}var yt="waniwani/sessionId",se="waniwani/geoLocation",ae="waniwani/userLocation",En="openai/userLocation",bn=[En,se,ae];function Tt(e,t){if(t.length===0)return e;let n;for(let o of bn){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 ve(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 Cn(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function Re(e,t,n,o,r,i,s){let a=Cn(e,n.toolType),l=n.stripLocationFields,c=l&&l.length>0,d=z(t),u=d&&c?Tt(d,l):d,p=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,v=c&&k(i?.output)&&k(i.output._meta)?{...i.output,_meta:Tt(i.output._meta,l)}:i?.output,T=(k(i?.output)&&k(i.output._meta)?i.output._meta:void 0)?.[D],g=T&&u?{...u,[D]:T}:T?{[D]:T}:u,E=k(i?.input)&&typeof i.input.sessionId=="string"&&i.input.sessionId.length>0?i.input.sessionId:void 0,y=E&&!P(g??void 0)?{...g??{},"waniwani/sessionId":E}:g;return{event:"tool.called",properties:{name:e,type:a,...o??{},...p!==void 0&&{input:p},...v!==void 0&&{output:v},...s&&s.length>0&&{kbSearch:s}},meta:y,source:A(y??u,r),metadata:{...n.metadata??{},...r&&{clientInfo:r},...n.funnelSync&&{funnelSync:n.funnelSync}}}}async function xe(e,t,n){try{await e.track(t)}catch(o){n?.(Ee(o))}}async function Ie(e,t){try{await e.flush()}catch(n){t?.(Ee(n))}}async function kt(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,l={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let p=await t.getToken();p&&(l.token=p)}catch(p){r?.(Ee(p))}let c=P(s);c&&(l.sessionId||(l.sessionId=c));let d=xt(s);d!==void 0&&(l.geoLocation||(l.geoLocation=d));let u=A(z(o),i);u&&!l.source&&(l.source=u),s.waniwani=l}var St=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function vt(e,t){if(!t||!k(e))return;let n=!1;for(let r of St)if(r in t){n=!0;break}if(!n)return;k(e._meta)||(e._meta={});let o=e._meta;for(let r of St)r in t&&(r in o||(o[r]=t[r]))}function Rt(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[yt]&&(o[yt]=r);let i=xt(n);i&&(o[se]||(o[se]=i),o[ae]||(o[ae]=i))}function xt(e){if(!e)return;let t=e[se]??e[ae];if(k(t)||typeof t=="string")return t}function Ee(e){return e instanceof Error?e:new Error(String(e))}function It(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Et(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(It(e.requestInfo)){let t=e.requestInfo.headers;if(It(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 Ct=Symbol.for("waniwani.wrappedHandler"),ce=K("mcp"),_t="https://app.waniwani.ai",_n="REDACTED";function Fn(e){if(!e)return;let t=e[Q];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]=_n,i=!0);return i?{...o,stateUpdates:s}:o}}function bt(e,t,n,o){let{server:r,tracker:i,opts:s,tokenCache:a,injectToken:l}=n,c=s.applyFieldRedactions===!0?Fn(o):void 0,d=async(u,p)=>{let v=c?{...s,redactInput:c,funnelSync:n.funnelSync}:{...s,funnelSync:n.funnelSync},f=z(p)??{},T=r.server?.getClientVersion?.();if(!P(f)&&k(p)){let w=Et(p);w&&(f["waniwani/sessionId"]=w,p._meta=f)}if(!A(f)&&k(p)){let w=p.requestInfo?.headers,S=A(f,T)??Le(w);S&&(f["waniwani/source"]=S,p._meta=f)}let E=Me(i,f,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});k(p)&&(p[ue]=E);let y={searches:[]},R=performance.now();try{let w=await ye.run(y,()=>t(u,p)),S=Math.round(performance.now()-R);ce(`tool "${e}" handler returned in ${S}ms, running post-processing...`);let I=k(w)&&w.isError===!0;if(I){let b=ve(w);console.error(`[waniwani] Tool "${e}" returned error${b?`: ${b}`:""}`)}return await xe(i,Re(e,p,v,{durationMs:S,status:I?"error":"ok",...I&&{errorMessage:ve(w)??"Unknown tool error"}},T,{input:u,output:w},y.searches),s.onError),ce(`tool "${e}" tracking done`),s.flushAfterToolCall&&await Ie(i,s.onError),Rt(w,p),vt(w,o),l&&(await kt(w,a,i._config.apiUrl??_t,p,s.onError,T),ce(`tool "${e}" widget config injected`)),ce(`tool "${e}" post-processing complete, returning result`),w}catch(w){let S=Math.round(performance.now()-R);throw await xe(i,Re(e,p,v,{durationMs:S,status:"error",errorMessage:w instanceof Error?w.message:String(w)},T,{input:u},y.searches),s.onError),s.flushAfterToolCall&&await Ie(i,s.onError),w}};return d[Ct]=!0,d}async function Pn(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let o=t??{},r=o.client??re(),i=o.injectWidgetToken!==!1,s=r._config.apiKey?new ie({apiUrl:r._config.apiUrl??_t,apiKey:r._config.apiKey}):null,a={server:e,tracker:r,opts:o,tokenCache:s,injectToken:i,funnelSync:null},l=e.registerTool.bind(e);n.registerTool=((...d)=>{let[u,p,v]=d;if(typeof v!="function")return l(...d);let f=typeof u=="string"&&u.trim().length>0?u:"unknown",T=k(p)&&k(p._meta)?p._meta:void 0,g=bt(f,v,a,T);return l(u,p,g)});let c=e._registeredTools;if(k(c))for(let[d,u]of Object.entries(c)){if(!k(u))continue;let p=u.handler;if(typeof p!="function"||p[Ct])continue;let v=k(u._meta)?u._meta:void 0;u.handler=bt(d,p,a,v)}if(r._config.apiKey){let d=e._registeredTools,u=[];if(d&&typeof d=="object"){for(let p of Object.values(d))if(p&&typeof p=="object"){let v=p._meta,f=v&&typeof v=="object"?v._flowGraph:void 0;f?.nodes?.length&&u.push(f)}}u.length>0&&(a.funnelSync=await ht(u))}return n}function be(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function An(){return be()==="openai"}function Nn(){return be()==="mcp-apps"}var de="text/html+skybridge",le="text/html;profile=mcp-app",Ft=async(e,t)=>{let n=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${n}${t}`)).text()};function Pt(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function At(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.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function Ce(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 Nt(e){let{id:t,title:n,description:o,baseUrl:r,htmlPath:i,widgetDomain:s,prefersBorder:a=!0,autoHeight:l=!0}=e,c=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")&&(c={...c,connect_domains:[...c.connect_domains||[],`ws://${g}:*`,`wss://${g}:*`],resource_domains:[...c.resource_domains||[],`http://${g}:*`]})}catch{}let d=`ui://widgets/apps-sdk/${t}.html`,u=`ui://widgets/ext-apps/${t}.html`,p=null,v=()=>(p||(p=Ft(r,i)),p),f=o;async function T(g){let E=await v();g.registerResource(`${t}-openai-widget`,d,{title:n,description:f,mimeType:de,_meta:{"openai/widgetDescription":f,"openai/widgetPrefersBorder":a}},async y=>({contents:[{uri:y.href,mimeType:de,text:E,_meta:Pt({description:f,prefersBorder:a,widgetDomain:s,widgetCSP:c})}]})),g.registerResource(`${t}-mcp-widget`,u,{title:n,description:f,mimeType:le,_meta:{ui:{prefersBorder:a}}},async y=>({contents:[{uri:y.href,mimeType:le,text:E,_meta:At({description:f,prefersBorder:a,widgetCSP:c})}]}))}return{id:t,title:n,description:o,openaiUri:d,mcpUri:u,autoHeight:l,register:T}}function Wn(e,t){let{resource:n,description:o,inputSchema:r,annotations:i,autoInjectResultText:s=!0}=e,a=e.id??n?.id,l=e.title??n?.title;if(!a)throw new Error("createTool: `id` is required when no resource is provided");if(!l)throw new Error("createTool: `title` is required when no resource is provided");let c=n?Ce({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:a,title:l,description:o,async register(d){d.registerTool(a,{title:l,description:o,inputSchema:r,annotations:i,...c&&{_meta:c}},(async(u,p)=>{let v=p,f=v._meta??{},T=Z(v),g=await t(u,{extra:{_meta:f},waniwani:T});return n&&g.data?{content:[{type:"text",text:g.text}],structuredContent:g.data,_meta:{...c,...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 Mn(e,t){await Promise.all(t.map(n=>n.register(e)))}export{F as END,X as MemoryKvStore,_ as START,L as StateGraph,j as WaniwaniKvStore,it as createFlow,st as createFlowTestHarness,Nt as createResource,Wn as createTool,vn as createTrackingRoute,be as detectPlatform,Nn as isMCPApps,An as isOpenAI,et as redacted,Mn as registerTools,Pn as withWaniwani};
|
|
3
|
+
${U.context}`:`ERROR: ${b}`}:U),G=Ye(M,g.context,c,p,d);if(G)return{...G,nodesVisited:u};break}}let x=r.get(c);if(!x)return{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:u};c=await O(x,p);continue}if(Me(g)){let y=g.field;if(y&&ge(V(p,y))){let S=r.get(c);if(!S)return{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:u};c=await O(S,p);continue}let x=y?fe(d,y):void 0,m=g.interactive!==!1;return{content:{status:"widget",tool:g.tool,...g.data!==void 0?{data:g.data}:{},description:m?`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:m,...y?{field:y}:{},...x?{fieldSchema:x}:{}},flowTokenContent:{step:c,state:p,field:y,widgetId:g.tool},nodesVisited:u}}p=N(p,g);let E=r.get(c);if(!E)return{content:{status:"error",error:`No outgoing edge from node "${c}"`},nodesVisited:u};c=await O(E,p)}catch(T){return{content:{status:"error",error:T instanceof Error?T.message:String(T)},flowTokenContent:{step:c,state:p},nodesVisited:u}}}return{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"},nodesVisited:u}}function me(e){return typeof e=="object"&&e!==null&&e.__ww_enc===1&&typeof e.ct=="string"&&typeof e.iv=="string"}var Ge=new Map;async function Ze(e){let t=Ge.get(e);if(t)return t;let n=Buffer.from(e,"base64");if(n.length!==32)throw new Error("[Waniwani KV] WANIWANI_ENCRYPTION_KEY must be a base64-encoded 32-byte (256-bit) key.");let r=await globalThis.crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"]);return Ge.set(e,r),r}async function Je(e,t){let n=await Ze(t),r=globalThis.crypto.getRandomValues(new Uint8Array(12)),o=new TextEncoder().encode(JSON.stringify(e)),i=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:r},n,o);return{__ww_enc:1,ct:Buffer.from(i).toString("base64"),iv:Buffer.from(r).toString("base64")}}async function Qe(e,t){let n=await Ze(t),r=Buffer.from(e.ct,"base64"),o=Buffer.from(e.iv,"base64"),i;try{i=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:o},n,r)}catch{throw new Error("[Waniwani KV] Decryption failed. The encryption key may be incorrect or the data may be corrupted.")}return JSON.parse(new TextDecoder().decode(i))}var Ht={debug:0,warn:1,error:2,none:3};function zt(){let e=process.env.WANIWANI_LOG_LEVEL;return e&&e in Ht?e:process.env.WANIWANI_DEBUG?"debug":"none"}function j(e,t){return t??zt()==="debug"?(...r)=>console.log(`[waniwani:${e}]`,...r):()=>{}}var Yt="@waniwani/sdk",Gt="https://app.waniwani.ai",Zt=j("kv"),L=class{get baseUrl(){return(process.env.WANIWANI_API_URL??Gt).replace(/\/$/,"")}get apiKey(){return process.env.WANIWANI_API_KEY}get encryptionKey(){return process.env.WANIWANI_ENCRYPTION_KEY}async get(t){if(!this.apiKey)throw new Error("[Waniwani KV] No API key configured. Set WANIWANI_API_KEY env var.");let n=await this.request("/api/mcp/redis/get",{key:t});if(n==null)return null;if(me(n)){if(!this.encryptionKey)throw new Error("[Waniwani KV] Encrypted data found but WANIWANI_ENCRYPTION_KEY is not set.");return Qe(n,this.encryptionKey)}return n}async set(t,n,r){if(!this.apiKey)throw new Error("[Waniwani KV] No API key configured. Set WANIWANI_API_KEY env var.");let o=this.encryptionKey;Zt(`set "${t}" \u2014 encryption ${o?"enabled":"disabled (no WANIWANI_ENCRYPTION_KEY)"}`);let i=o?await Je(n,o):n;await this.request("/api/mcp/redis/set",{key:t,value:i,ttlSeconds:r?.ttlSeconds})}async delete(t){if(this.apiKey)try{await this.request("/api/mcp/redis/delete",{key:t})}catch(n){console.error("[Waniwani KV] delete failed for key:",t,n)}}async request(t,n){let r=`${this.baseUrl}${t}`,o=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","X-WaniWani-SDK":Yt},body:JSON.stringify(n)});if(!o.ok){let s=await o.text().catch(()=>"");throw new Error(s||`KV store API error: HTTP ${o.status}`)}return(await o.json()).data}};var ee=class{map=new Map;async get(t){return this.map.get(t)??null}async set(t,n,r){this.map.set(t,n)}async delete(t){this.map.delete(t)}};var z=class{store=new L;get(t){return this.store.get(t)}set(t,n,r){return this.store.set(t,n,r)}delete(t){return this.store.delete(t)}};function Jt(e){let t=e.toString();return t.includes("showWidget")?"widget":t.includes("interrupt")?"interrupt":"action"}function Xe(e,t,n,r){let o=[];for(let[s,a]of t){let d=r.get(s);o.push({id:s,type:Jt(a),label:d?.label??s,...d?.hideFromFunnel?{hideFromFunnel:!0}:{}})}let i=[];for(let[s,a]of n)a.type==="direct"?i.push({from:s,to:a.to,type:"direct"}):i.push({from:s,to:a.targets,type:"conditional"});return{flowId:e.id,title:e.title,nodes:o,edges:i}}import{z as R}from"zod";var et=R.object({type:R.enum(["enum","string","number","boolean","object","array","unknown"]),values:R.array(R.string()).optional(),description:R.string().optional(),optional:R.boolean().optional()}).describe("JIT schema fragment for a state field \u2014 type, allowed values, and description."),Qt=R.object({question:R.string(),field:R.string(),suggestions:R.array(R.string()).optional(),context:R.string().optional(),fieldSchema:et.optional()}).describe("One question within a multi-question interrupt."),we={status:R.enum(["interrupt","widget","complete","error"]).describe("Current flow status and the next action the assistant should take."),question:R.string().optional().describe("Single question to ask the user when status is interrupt."),field:R.string().optional().describe("State field to fill with the user's answer on the next continue call."),fieldSchema:et.optional().describe("JIT schema fragment for the single-question shorthand."),suggestions:R.array(R.string()).optional().describe("Suggested answers for the single-question shorthand."),questions:R.array(Qt).optional().describe("Multiple questions to ask the user when status is interrupt."),context:R.string().optional().describe("Private instruction context for the assistant."),tool:R.string().optional().describe("Widget tool to call when status is widget."),data:R.record(R.string(),R.unknown()).optional().describe("Input data to pass to the widget tool."),description:R.string().optional().describe("Instruction for rendering the requested widget."),interactive:R.boolean().optional().describe("Whether the widget requires user interaction before continuing."),sessionId:R.string().optional().describe("Session identifier to pass on future continue and reset calls."),error:R.string().optional().describe("Error message when status is error.")};function tt(e){let t=["","## FLOW EXECUTION PROTOCOL","","This tool implements a multi-step conversational flow. Follow this protocol exactly:","",'1. Call with `action: "start"` to begin and include `intent`.'," `intent` must be a brief summary of the user's goal for this flow."," Do NOT invent missing intent."," Optionally include `context` \u2014 the situation or environment that led the user to start"," this flow (e.g. what page they are on, what they were doing, or what triggered the request)."," Only provide `context` when there is genuinely relevant situational information. Do NOT invent missing context."," If the user's message already contains answers to likely questions,"," extract them into `stateUpdates` as `{ field: value }` pairs (see the `stateUpdates` schema"," for the list of writable fields). The engine will auto-skip steps whose fields are already filled."," Only extract values the user explicitly stated \u2014 do NOT guess or invent values."];return e.omitIntentPII&&t.push(" Do NOT include PII in `intent` or `context` \u2014 no names, emails, phones, addresses, IDs, ages, or birthdates.",' Summarize the goal abstractly (e.g. "user wants a quote", not "Jane Doe wants a quote").'),t.push(" For grouped fields (z.object state), use dot-notation keys in `stateUpdates`:",' e.g. `{ "driver.name": "John", "driver.license": "ABC123" }`.',"2. The response JSON `status` field tells you what to do next:",' - `"interrupt"`: Pause and ask the user. Two forms:'," a. Single question: `{ question, field, fieldSchema?, context? }` \u2014 ask `question`, store answer in `field`."," b. Multi-question: `{ questions: [{question, field, fieldSchema?}, ...], context? }` \u2014 ask ALL questions"," in one conversational message, collect all answers."," `fieldSchema` (when present) describes the expected value: `{ type, values?, description?, optional? }`.",' Use it to validate before sending \u2014 match enum `values` exactly, coerce strings to numbers where `type: "number"`.'," `context` (if present) is hidden AI instructions \u2014 use to shape your response, do NOT show verbatim."," Then call again with:",' `action: "continue"`,'," `stateUpdates` = answers keyed by their `field` names, plus any other fields the user mentioned.",' - `"widget"`: The flow wants to show a UI widget. Call the tool named in the `tool`'," field, passing the `data` object as the tool's input."," Check the `interactive` field in the response:"," \u2022 `interactive: true` \u2014 The widget requires user interaction. After calling the display tool,"," STOP and WAIT for the user to interact with the widget. Do NOT call this flow tool again"," until the user has responded. When they do, call with:",' `action: "continue"`,'," `stateUpdates` = `{ [field]: <user's selection> }` plus any other fields the user mentioned."," \u2022 `interactive: false` \u2014 The widget is display-only. You MUST STILL call the display tool"," FIRST to render it for the user \u2014 this is a required, user-visible step. Do NOT skip it",' and do NOT jump straight to `action: "continue"`. ONLY AFTER you have called the display',' tool, call THIS flow tool again with `action: "continue"`. Do NOT wait for user interaction.',' - `"complete"`: The flow is done. Present the result to the user.',' - `"error"`: Something went wrong. Show the `error` message.',"","3. Do NOT invent state values. Only use `stateUpdates` for information the user explicitly provided.","4. Include only the fields the user actually answered in `stateUpdates` \u2014 do NOT guess missing ones."," If the user did not answer all pending questions, the engine will re-prompt for the remaining ones."," If the user mentioned values for other known fields, include those too \u2014"," they will be applied immediately and those steps will be auto-skipped.","5. CORRECTION: If the user wants to CHANGE a previously-answered field",' (e.g. "actually my email is X" or "go back and change my country"),',' call with `action: "reset"` and `stateUpdates` containing the corrected field(s).'," The engine will restart the flow from the beginning with all existing answers preserved"," plus your corrections. Steps with filled answers will be auto-skipped."," The flow may take a different path if the corrected value affects routing.",' Do NOT use "reset" for the CURRENT question \u2014 use "continue" for that.',"6. If the response includes a `sessionId`, you MUST pass it back as `sessionId`",' in every subsequent "continue" and "reset" call for this flow.'),t.join(`
|
|
4
|
+
`)}function he(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function nt(e){let t=rt(e),n=he(t.waniwani)?t.waniwani:{};return e.meta({...t,waniwani:{...n,redacted:!0}})}function Xt(e){let n=rt(e).waniwani;return he(n)&&n.redacted===!0}function rt(e){let t=e.meta;if(typeof t!="function")return{};let n=t.call(e);return he(n)?n:{}}function ot(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))Xt(r)&&t.push(n);return t}var te="waniwani/redactedStateUpdateFields";function en(e){let t=e.omitIntentPII?" Do not include PII (names, emails, phones, addresses, IDs, ages, birthdates) \u2014 summarize abstractly.":"",r=e.state&&Object.keys(e.state).length>0?W.object(e.state).partial().passthrough():W.record(W.string(),W.unknown());return{action:W.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:W.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:W.string().optional().describe(`Optional when action is "start". Describe the situation or environment that led the user to start this flow \u2014 e.g. what page they are on, what they were doing, or what triggered the request. Do not invent missing context.${t}`),stateUpdates:r.optional().describe(`State field values to set before processing the next node. Pass the user's answer (keyed by the field name from the response) and any other values the user mentioned. For nested state fields, use dot-paths like "driver.name".`),sessionId:W.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 tn(e){if(process.env.WANIWANI_API_KEY)return new z;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 it(e){let{config:t,nodes:n,edges:r}=e,o=en(t),i=Xe(t,n,r,e.nodeOptions),s=tt(t),a=`${t.description}
|
|
5
|
+
${s}`,d=e.store??tn(t.id),c=new Map;async function p(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 x=r.get(P);if(!x)return{content:{status:"error",error:"No start edge"}};let m=X(f.stateUpdates??{}),S=await O(x,m);return H(S,m,n,r,c,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 d.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 x=y.state,m=y.step;if(!m)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let S=N(x,X(f.stateUpdates??{}));if(y.widgetId){let I=r.get(m);if(!I)return{content:{status:"error",error:`No edge from step "${m}"`}};let b=await O(I,S);return H(b,S,n,r,c,g,E,e.nodeOptions,t.state)}return H(m,S,n,r,c,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 d.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 x=r.get(P);if(!x)return{content:{status:"error",error:"No start edge"}};let m=y.state,S=N(m,X(f.stateUpdates)),I=await O(x,S);return H(I,S,n,r,c,g,E,e.nodeOptions,t.state)}return{content:{status:"error",error:`Unknown action: "${f.action}"`}}}let u=ot(t.state),l={title:t.title,description:a,inputSchema:o,outputSchema:we,annotations:t.annotations,...u.length>0&&{_meta:{[te]:u}}},v=(async(f,T)=>{let g=T,E=g._meta??{},y=_(E),x=y??f.sessionId;!x&&f.action==="start"&&(x=crypto.randomUUID()),x&&!y&&(E["waniwani/sessionId"]=x);let m=$(g),S=await p(f,x,E,m);if(x&&S.flowTokenContent)try{await d.set(x,S.flowTokenContent)}catch(M){let G=M instanceof Error?M.message:String(M);return{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${x}"): ${G}`},null,2)}],_meta:E,isError:!0}}let I=!y&&x?{...S.content,sessionId:x}:S.content,b=[{type:"text",text:JSON.stringify(I,null,2)}];return S.nodesVisited?.length&&(E[K]={flowId:t.id,nodesVisited:S.nodesVisited}),{content:b,structuredContent:I,_meta:E,...S.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:l,handler:v,async register(f){let T={...l,_meta:{...l._meta,_flowGraph:i}};f.registerTool(t.id,T,v)},graph:e.graph,flowGraph:i}}function st(e,t){let n=["flowchart TD"];n.push(` ${P}((Start))`);for(let[r]of e)n.push(` ${r}[${r}]`);n.push(` ${F}((End))`);for(let[r,o]of t)if(o.type==="direct")n.push(` ${r} --> ${o.to}`);else for(let i of o.targets)n.push(` ${r} -.-> ${i}`);return n.join(`
|
|
6
|
+
`)}var q=class{nodes=new Map;edges=new Map;nodeOptions=new Map;config;constructor(t){this.config=t}addNode(t,n,r){let o=typeof t=="string"?t:t.id,i=typeof t=="string"?n:t.run,s=typeof t=="string"?r?.label:t.label,a=typeof t=="string"?r?.hideFromFunnel:t.hideFromFunnel;if(o===P||o===F)throw new Error(`"${o}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(o))throw new Error(`Node "${o}" already exists`);return this.nodes.set(o,i),(s!==void 0||a!==void 0)&&this.nodeOptions.set(o,{label:s??o,hideFromFunnel:a}),this}addEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge. Use addConditionalEdge for branching.`);return this.edges.set(t,{type:"direct",to:n}),this}addConditionalEdge(t,n,r){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge.`);if(n.length===0)throw new Error(`Conditional edge from "${t}" must declare at least one target node in \`to\`.`);return this.edges.set(t,{type:"conditional",condition:r,targets:[...n]}),this}graph(){return st(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return it({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>st(n,r),nodeOptions:new Map(this.nodeOptions)})}validate(){if(!this.edges.has(P))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(P);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,r]of this.edges){if(n!==P&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(r.type==="direct"&&r.to!==F&&!this.nodes.has(r.to))throw new Error(`Edge from "${n}" references non-existent node: "${r.to}"`);if(r.type==="conditional"&&r.targets){for(let o of r.targets)if(o!==F&&!this.nodes.has(o))throw new Error(`Conditional edge from "${n}" declares non-existent target: "${o}"`)}}for(let[n]of this.nodes)if(!this.edges.has(n))throw new Error(`Node "${n}" has no outgoing edge. Add one with .addEdge("${n}", ...) or .addConditionalEdge("${n}", ...)`)}};function at(e){return new q(e)}function ye(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function ct(e,t){let n=t?.stateStore,r=[],o=`test-session-${Math.random().toString(36).slice(2,10)}`,i={registerTool:(...c)=>{r.push(c)}};await e.register(i);let s=r[0]?.[2];if(!s)throw new Error(`Flow "${e.name}" did not register a handler`);let a={_meta:{sessionId:o}};async function d(c){return{...c,decodedState:n?await n.get(o):null}}return{async start(c,p,u){let l=await s({action:"start",intent:c,...u?{context:u}:{},...p?{stateUpdates:p}:{}},a);return d(ye(l))},async continueWith(c){let p=await s({action:"continue",...c?{stateUpdates:c}:{}},a);return d(ye(p))},async resetWith(c){let p=await s({action:"reset",stateUpdates:c},a);return d(ye(p))},async lastState(){return n?n.get(o):null}}}var ne=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};import{AsyncLocalStorage as nn}from"async_hooks";var dt=globalThis,re=dt.__waniwaniKbRetrievalStore;re||(re=new nn,dt.__waniwaniKbRetrievalStore=re);var Te=re;function pt(e){try{Te.getStore()?.searches.push(e)}catch{}}var rn="@waniwani/sdk";function ut(e){let{apiUrl:t,apiKey:n}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function o(i,s,a){let d=r(),c=`${t.replace(/\/$/,"")}${s}`,p={Authorization:`Bearer ${d}`,"X-WaniWani-SDK":rn},u={method:i,headers:p};a!==void 0&&(p["Content-Type"]="application/json",u.body=JSON.stringify(a));let l=await fetch(c,u);if(!l.ok){let f=await l.text().catch(()=>"");throw new ne(f||`KB API error: HTTP ${l.status}`,l.status)}return(await l.json()).data}return{async ingest(i){return o("POST","/api/mcp/kb/ingest",{files:i})},async search(i,s){let a=await o("POST","/api/mcp/kb/search",{query:i,...s});return pt({query:i,resultCount:a.length,results:a.map(d=>({source:d.source,heading:d.heading,score:d.score}))}),a},async sources(){return o("GET","/api/mcp/kb/sources")}}}import{existsSync as on,readFileSync as sn}from"fs";import{resolve as an}from"path";var cn="waniwani.json",B;function lt(){if(B!==void 0)return B;try{let e=an(process.cwd(),cn);if(!on(e))return B=null,null;let t=sn(e,"utf-8");return B=JSON.parse(t),B}catch{return B=null,null}}var dn="__waniwani_config__";function ft(){return globalThis[dn]}var pn="@waniwani/sdk";function ie(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??gt,o=fn(e),i=oe(e.meta),s=oe(e.metadata),a=gn(e,i),d=C(e.eventId)??r(),c=mn(e.timestamp,n),p=C(e.source)??A(i)??t.source??pn,u=Se(e)?{...e}:void 0,l={...s};return Object.keys(i).length>0&&(l.meta=i),u&&(l.rawLegacy=u),{id:d,type:"mcp.event",name:o,source:p,timestamp:c,correlation:a,properties:un(e,o),metadata:l,rawLegacy:u}}function gt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function un(e,t){if(!Se(e))return oe(e.properties);let n=ln(e,t),r=oe(e.properties);return{...n,...r}}function ln(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 fn(e){return Se(e)?e.eventType:e.event}function gn(e,t){let n=C(e.requestId)??Ue(t),r=C(e.sessionId)??_(t),o=C(e.traceId)??De(t),i=C(e.externalUserId)??Ke(t),s=C(e.visitorId)??je(t),a=C(e.correlationId)??Le(t)??n,d={};return r&&(d.sessionId=r),o&&(d.traceId=o),n&&(d.requestId=n),a&&(d.correlationId=a),i&&(d.externalUserId=i),s&&(d.visitorId=s),d}function mn(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 oe(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function C(e){if(typeof e=="string"&&e.trim().length!==0)return e}function Se(e){return"eventType"in e}var wn="/api/mcp/events/v2/batch";var mt="@waniwani/sdk";var hn=new Set([401,403]),yn=new Set([408,425,429,500,502,503,504]);function wt(e){return new ke(e)}var ke=class{endpointUrl;flushIntervalMs;maxBatchSize;maxBufferSize;maxRetries;retryBaseDelayMs;retryMaxDelayMs;shutdownTimeoutMs;sdkVersion;fetchFn;logger;now;sleep;apiKey;buffer=[];flushTimer;flushScheduled=!1;flushScheduledTimer;flushInFlight;inFlightCount=0;isStopped=!1;isShuttingDown=!1;constructor(t){this.endpointUrl=kn(t.apiUrl,t.endpointPath??wn),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??fetch,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(r=>setTimeout(r,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs)),this.registerBrowserTeardown()}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[Waniwani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[Waniwani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,r=this.flush();if(!Number.isFinite(n)||n<=0)return await r,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let o=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(n).then(()=>o)])===o?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}registerBrowserTeardown(){if(typeof document>"u"||typeof window>"u")return;let t=()=>{document.visibilityState==="hidden"&&this.keepaliveFlush()};document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",()=>this.keepaliveFlush())}keepaliveFlush(){if(this.isStopped||this.buffer.length===0)return;let t=this.buffer.splice(0,this.buffer.length);this.sendKeepaliveChunk(t)}sendKeepaliveChunk(t){let n=JSON.stringify(this.makeBatchRequest(t));if(n.length>6e4&&t.length>1){let r=Math.ceil(t.length/2);this.sendKeepaliveChunk(t.slice(0,r)),this.sendKeepaliveChunk(t.slice(r));return}try{this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:n,keepalive:!0}).catch(()=>{})}catch{}}requestHeaders(){let t={"Content-Type":"application/json","X-WaniWani-SDK":mt};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,r=t;for(;r.length>0&&!this.isStopped;){this.inFlightCount=r.length;let o=await this.sendBatchOnce(r);switch(this.inFlightCount=0,o.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(o.status,r.length);return;case"permanent":this.logger.error("[Waniwani] Dropping %d event(s) after permanent failure: %s",r.length,o.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d event(s) after retry exhaustion: %s",r.length,o.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(o.permanent.length>0&&this.logger.error("[Waniwani] Dropping %d event(s) rejected as permanent",o.permanent.length),o.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[Waniwani] Dropping %d retryable event(s) after retry exhaustion",o.retryable.length);return}r=o.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:this.requestHeaders(),body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:vn(i)}}if(hn.has(n.status))return{kind:"auth",status:n.status};if(yn.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await Sn(n);if(!r?.rejected||r.rejected.length===0)return{kind:"success"};let o=this.classifyRejectedEvents(t,r.rejected);return o.retryable.length===0&&o.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:o.retryable,permanent:o.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:mt,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(s=>[s.id,s])),o=[],i=[];for(let s of n){let a=r.get(s.eventId);if(a){if(Tn(s)){o.push(a);continue}i.push(a)}}return{retryable:o,permanent:i}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let r=this.buffer.length;this.buffer.splice(0,r),this.logger.error("[Waniwani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+r)}};function Tn(e){if(e.retryable===!0)return!0;let t=e.code.toLowerCase();return t.includes("timeout")||t.includes("temporary")||t.includes("unavailable")||t.includes("rate_limit")||t.includes("transient")||t.includes("server")}async function Sn(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function kn(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function vn(e){return e instanceof Error?e.message:String(e)}function ht(e){let{apiUrl:t,apiKey:n,tracking:r}=e;function o(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}let i=n?wt({apiUrl:t,apiKey:n,endpointPath:r.endpointPath,flushIntervalMs:r.flushIntervalMs,maxBatchSize:r.maxBatchSize,maxBufferSize:r.maxBufferSize,maxRetries:r.maxRetries,retryBaseDelayMs:r.retryBaseDelayMs,retryMaxDelayMs:r.retryMaxDelayMs,shutdownTimeoutMs:r.shutdownTimeoutMs}):void 0;function s(p){o();let u=ie(p);return!u.correlation.sessionId&&!u.correlation.externalUserId&&!u.correlation.visitorId&&console.warn(`[waniwani] event "${u.name}" has no sessionId, externalUserId, or visitorId; the ingest API requires one and will reject it.`),i?.enqueue(u),{eventId:u.id}}let a=async p=>s(p),d=Object.assign(a,Z(a)),c={async identify(p,u,l){o();let v=ie({event:"user.identified",externalUserId:p,properties:u,meta:l});return i?.enqueue(v),{eventId:v.id}},track:d,async flush(){o(),await i?.flush()},async shutdown(p){return o(),await i?.shutdown({timeoutMs:p?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&xn(c,r.shutdownTimeoutMs),c}function xn(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 se(e){let n=e??lt()??ft(),r=n?.apiUrl??process.env.WANIWANI_API_URL??"https://app.waniwani.ai",o=n?.apiKey??process.env.WANIWANI_API_KEY,i={endpointPath:n?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:n?.tracking?.flushIntervalMs??1e3,maxBatchSize:n?.tracking?.maxBatchSize??20,maxBufferSize:n?.tracking?.maxBufferSize??1e3,maxRetries:n?.tracking?.maxRetries??3,retryBaseDelayMs:n?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:n?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:n?.tracking?.shutdownTimeoutMs??2e3},s={apiUrl:r,apiKey:o,tracking:i},a=ht(s),d=ut(s);return{...a,kb:d,_config:s}}function Rn(e){return{event:e.name??"widget_render",properties:e.properties,metadata:e.metadata,sessionId:e.correlation?.sessionId,traceId:e.correlation?.traceId,requestId:e.correlation?.requestId,correlationId:e.correlation?.correlationId,externalUserId:e.correlation?.externalUserId,visitorId:e.correlation?.visitorId,eventId:e.id,timestamp:e.timestamp,source:e.source}}function In(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=se(t)),n}return async function(i){let s;try{s=await i.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!Array.isArray(s.events)||s.events.length===0)return new Response(JSON.stringify({error:"Missing or empty events array"}),{status:400,headers:{"Content-Type":"application/json"}});try{let a=r(),d=[];for(let c of s.events){let p=await a.track(Rn(c));d.push(p.eventId)}return await a.flush(),new Response(JSON.stringify({ok:!0,accepted:d.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(a){let d=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({error:d}),{status:500,headers:{"Content-Type":"application/json"}})}}}var ve=j("widget-token"),En=120*1e3,ae=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-En?this.cached.token:this.pending?this.pending:(this.pending=this.mint(t,n).finally(()=>{this.pending=null}),this.pending)}async mint(t,n){let r=bn(this.config.apiUrl,"/api/mcp/widget-tokens");ve("minting token from",r);let o={};t&&(o.sessionId=t),n&&(o.traceId=n);try{let i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)});if(ve("mint response:",i.status),!i.ok)return null;let s=await i.json(),a=s.data&&typeof s.data=="object"?s.data:s,d=new Date(a.expiresAt).getTime();return!a.token||Number.isNaN(d)?null:(this.cached={token:a.token,expiresAt:d},a.token)}catch(i){return ve("mint failed:",i),null}}};function bn(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}async function yt(e){if(typeof globalThis.crypto?.subtle?.digest=="function"){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return`simple-${Math.abs(t).toString(36)}`}function Cn(e){return yt(JSON.stringify({nodes:e.nodes,edges:e.edges}))}async function Tt(e){if(e.length===0)return null;let t=[...e].sort((o,i)=>o.flowId.localeCompare(i.flowId)),n=await yt(JSON.stringify(t.map(o=>({flowId:o.flowId,nodes:o.nodes,edges:o.edges})))),r=await Promise.all(e.map(async o=>({flowId:o.flowId,title:o.title,configHash:await Cn(o),nodes:o.nodes,edges:o.edges})));return{compositeHash:n,flows:r}}var St="waniwani/sessionId",ce="waniwani/geoLocation",de="waniwani/userLocation",_n="openai/userLocation",Pn=[_n,ce,de];function kt(e,t){if(t.length===0)return e;let n;for(let r of Pn){let o=e[r];if(!k(o))continue;let i;for(let s of t)s in o&&(i||(i={...o}),delete i[s]);i&&(n||(n={...e}),n[r]=i)}return n??e}function k(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Y(e){if(!k(e))return;let t=e._meta;return k(t)?t:void 0}function xe(e){if(!k(e))return;let t=e.content;return Array.isArray(t)?t.find(r=>k(r)&&r.type==="text"&&typeof r.text=="string")?.text:void 0}function Fn(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function Re(e,t,n,r,o,i,s){let a=Fn(e,n.toolType),d=n.stripLocationFields,c=d&&d.length>0,p=Y(t),u=p&&c?kt(p,d):p,l=i?.input!==void 0&&n.redactInput?n.redactInput(i.input):i?.input,v=c&&k(i?.output)&&k(i.output._meta)?{...i.output,_meta:kt(i.output._meta,d)}:i?.output,T=(k(i?.output)&&k(i.output._meta)?i.output._meta:void 0)?.[K],g=T&&u?{...u,[K]:T}:T?{[K]:T}:u,E=k(i?.input)&&typeof i.input.sessionId=="string"&&i.input.sessionId.length>0?i.input.sessionId:void 0,y=E&&!_(g??void 0)?{...g??{},"waniwani/sessionId":E}:g;return{event:"tool.called",properties:{name:e,type:a,...r??{},...l!==void 0&&{input:l},...v!==void 0&&{output:v},...s&&s.length>0&&{kbSearch:s}},meta:y,source:A(y??u,o),metadata:{...n.metadata??{},...o&&{clientInfo:o},...n.funnelSync&&{funnelSync:n.funnelSync}}}}async function Ie(e,t,n){try{await e.track(t)}catch(r){n?.(be(r))}}async function Ee(e,t){try{await e.flush()}catch(n){t?.(be(n))}}async function xt(e,t,n,r,o,i){if(!k(e))return;k(e._meta)||(e._meta={});let s=e._meta,a=k(s[J])?s[J]:void 0,d={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let l=await t.getToken();l&&(d.token=l)}catch(l){o?.(be(l))}let c=_(s);c&&(d.sessionId||(d.sessionId=c));let p=Et(s);p!==void 0&&(d.geoLocation||(d.geoLocation=p));let u=A(Y(r),i);u&&!d.source&&(d.source=u),s[J]=d}var vt=["openai/outputTemplate","openai/widgetAccessible","openai/resultCanProduceWidget","openai/toolInvocation/invoking","openai/toolInvocation/invoked","ui/resourceUri","ui"];function Rt(e,t){if(!t||!k(e))return;let n=!1;for(let o of vt)if(o in t){n=!0;break}if(!n)return;k(e._meta)||(e._meta={});let r=e._meta;for(let o of vt)o in t&&(o in r||(r[o]=t[o]))}function It(e,t){let n=Y(t);if(!n||!k(e))return;k(e._meta)||(e._meta={});let r=e._meta,o=_(n);o&&!r[St]&&(r[St]=o);let i=Et(n);i&&(r[ce]||(r[ce]=i),r[de]||(r[de]=i))}function Et(e){if(!e)return;let t=e[ce]??e[de];if(k(t)||typeof t=="string")return t}function be(e){return e instanceof Error?e:new Error(String(e))}function bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ct(e){if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(bt(e.requestInfo)){let t=e.requestInfo.headers;if(bt(t)){let n={};for(let i of Object.keys(t))n[i.toLowerCase()]=t[i];let r=n["mcp-session-id"];if(typeof r=="string"&&r)return r;let o=n["x-waniwani-session-id"];if(typeof o=="string"&&o)return o}}}var Pt=Symbol.for("waniwani.wrappedHandler"),pe=j("mcp"),Ft="https://app.waniwani.ai",An="REDACTED";function Nn(e){if(!e)return;let t=e[te];if(!Array.isArray(t)||t.length===0)return;let n=new Set(t.filter(r=>typeof r=="string"));if(n.size!==0)return r=>{if(!k(r))return r;let o=r.stateUpdates;if(!k(o))return r;let i=!1,s={...o};for(let a of n)a in s&&(s[a]=An,i=!0);return i?{...r,stateUpdates:s}:r}}function _t(e,t,n,r){let{server:o,tracker:i,opts:s,tokenCache:a,injectToken:d}=n,c=s.applyFieldRedactions===!0?Nn(r):void 0,p=async(u,l)=>{let v=c?{...s,redactInput:c,funnelSync:n.funnelSync}:{...s,funnelSync:n.funnelSync},f=Y(l)??{},T=o.server?.getClientVersion?.();if(!_(f)&&k(l)){let m=Ct(l);m&&(f["waniwani/sessionId"]=m,l._meta=f)}if(!A(f)&&k(l)){let m=l.requestInfo?.headers,S=A(f,T)??qe(m);S&&(f["waniwani/source"]=S,l._meta=f)}let E=Be(i,f,{apiUrl:i._config.apiUrl,apiKey:i._config.apiKey});k(l)&&(l[Q]=E);let y={searches:[]},x=performance.now();try{let m=await Te.run(y,()=>t(u,l)),S=Math.round(performance.now()-x);pe(`tool "${e}" handler returned in ${S}ms, running post-processing...`);let I=k(m)&&m.isError===!0;if(I){let b=xe(m);console.error(`[waniwani] Tool "${e}" returned error${b?`: ${b}`:""}`)}return await Ie(i,Re(e,l,v,{durationMs:S,status:I?"error":"ok",...I&&{errorMessage:xe(m)??"Unknown tool error"}},T,{input:u,output:m},y.searches),s.onError),pe(`tool "${e}" tracking done`),s.flushAfterToolCall&&await Ee(i,s.onError),It(m,l),Rt(m,r),d&&(await xt(m,a,i._config.apiUrl??Ft,l,s.onError,T),pe(`tool "${e}" widget config injected`)),pe(`tool "${e}" post-processing complete, returning result`),m}catch(m){let S=Math.round(performance.now()-x);throw await Ie(i,Re(e,l,v,{durationMs:S,status:"error",errorMessage:m instanceof Error?m.message:String(m)},T,{input:u},y.searches),s.onError),s.flushAfterToolCall&&await Ee(i,s.onError),m}};return p[Pt]=!0,p}async function Wn(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??se(),i=r.injectWidgetToken!==!1,s=o._config.apiKey?new ae({apiUrl:o._config.apiUrl??Ft,apiKey:o._config.apiKey}):null,a={server:e,tracker:o,opts:r,tokenCache:s,injectToken:i,funnelSync:null},d=e.registerTool.bind(e);n.registerTool=((...p)=>{let[u,l,v]=p;if(typeof v!="function")return d(...p);let f=typeof u=="string"&&u.trim().length>0?u:"unknown",T=k(l)&&k(l._meta)?l._meta:void 0,g=_t(f,v,a,T);return d(u,l,g)});let c=e._registeredTools;if(k(c))for(let[p,u]of Object.entries(c)){if(!k(u))continue;let l=u.handler;if(typeof l!="function"||l[Pt])continue;let v=k(u._meta)?u._meta:void 0;u.handler=_t(p,l,a,v)}if(o._config.apiKey){let p=e._registeredTools,u=[];if(p&&typeof p=="object"){for(let l of Object.values(p))if(l&&typeof l=="object"){let v=l._meta,f=v&&typeof v=="object"?v._flowGraph:void 0;f?.nodes?.length&&u.push(f)}}u.length>0&&(a.funnelSync=await Tt(u))}return n}function Ce(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function Mn(){return Ce()==="openai"}function On(){return Ce()==="mcp-apps"}var ue="text/html+skybridge",le="text/html;profile=mcp-app",At=async(e,t)=>{let n=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${n}${t}`)).text()};function Nt(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function Wt(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.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function _e(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 Mt(e){let{id:t,title:n,description:r,baseUrl:o,htmlPath:i,widgetDomain:s,prefersBorder:a=!0,autoHeight:d=!0}=e,c=e.widgetCSP??{connect_domains:[o],resource_domains:[o]};if(process.env.NODE_ENV==="development")try{let{hostname:g}=new URL(o);(g==="localhost"||g==="127.0.0.1")&&(c={...c,connect_domains:[...c.connect_domains||[],`ws://${g}:*`,`wss://${g}:*`],resource_domains:[...c.resource_domains||[],`http://${g}:*`]})}catch{}let p=`ui://widgets/apps-sdk/${t}.html`,u=`ui://widgets/ext-apps/${t}.html`,l=null,v=()=>(l||(l=At(o,i)),l),f=r;async function T(g){let E=await v();g.registerResource(`${t}-openai-widget`,p,{title:n,description:f,mimeType:ue,_meta:{"openai/widgetDescription":f,"openai/widgetPrefersBorder":a}},async y=>({contents:[{uri:y.href,mimeType:ue,text:E,_meta:Nt({description:f,prefersBorder:a,widgetDomain:s,widgetCSP:c})}]})),g.registerResource(`${t}-mcp-widget`,u,{title:n,description:f,mimeType:le,_meta:{ui:{prefersBorder:a}}},async y=>({contents:[{uri:y.href,mimeType:le,text:E,_meta:Wt({description:f,prefersBorder:a,widgetCSP:c})}]}))}return{id:t,title:n,description:r,openaiUri:p,mcpUri:u,autoHeight:d,register:T}}function Un(e,t){let{resource:n,description:r,inputSchema:o,annotations:i,autoInjectResultText:s=!0}=e,a=e.id??n?.id,d=e.title??n?.title;if(!a)throw new Error("createTool: `id` is required when no resource is provided");if(!d)throw new Error("createTool: `title` is required when no resource is provided");let c=n?_e({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight}):void 0;return{id:a,title:d,description:r,async register(p){p.registerTool(a,{title:d,description:r,inputSchema:o,annotations:i,...c&&{_meta:c}},(async(u,l)=>{let v=l,f=v._meta??{},T=$(v),g=await t(u,{extra:{_meta:f},waniwani:T});return n&&g.data?{content:[{type:"text",text:g.text}],structuredContent:g.data,_meta:{...c,...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 Dn(e,t){await Promise.all(t.map(n=>n.register(e)))}export{F as END,ee as MemoryKvStore,Q as SCOPED_CLIENT_KEY,P as START,q as StateGraph,L as WaniwaniKvStore,at as createFlow,ct as createFlowTestHarness,Mt as createResource,Un as createTool,In as createTrackingRoute,Ce as detectPlatform,$ as extractScopedClient,On as isMCPApps,Mn as isOpenAI,nt as redacted,Dn as registerTools,Wn as withWaniwani};
|
|
7
7
|
//# sourceMappingURL=index.js.map
|