@waniwani/sdk 0.8.7-alpha.1 → 0.8.7-alpha.2
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.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function A(t,e){return e?(...n)=>console.log(`[waniwani:${t}]`,...n):()=>{}}function I(t){if(t===!0)return{};if(!(t===!1||t===void 0))return t}function W(t){let e=new Set(t.map(n=>n.replace(/\/$/,"").toLowerCase()));return function(r,i){let s=i?.headers.get("origin"),g=s?.toLowerCase();return g!=null&&(e.has(g)||g.endsWith(".mcp.waniwani.run"))&&(r.headers.set("Access-Control-Allow-Origin",s),r.headers.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),r.headers.set("Access-Control-Allow-Headers","Content-Type, Authorization, X-Session-Id, X-Client-User-Agent"),r.headers.set("Access-Control-Expose-Headers","X-Session-Id"),r.headers.set("Vary","Origin")),r}}function N(t){return function(n,r,i){return t(new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"},status:r}),i)}}var
|
|
1
|
+
function A(t,e){return e?(...n)=>console.log(`[waniwani:${t}]`,...n):()=>{}}function I(t){if(t===!0)return{};if(!(t===!1||t===void 0))return t}function V(t){try{let e=new URL(t);return e.hostname==="localhost"||e.hostname==="127.0.0.1"}catch{return!1}}function W(t){let e=new Set(t.map(n=>n.replace(/\/$/,"").toLowerCase()));return function(r,i){let s=i?.headers.get("origin"),g=s?.toLowerCase();return g!=null&&(e.has(g)||g.endsWith(".mcp.waniwani.run")||V(g))&&(r.headers.set("Access-Control-Allow-Origin",s),r.headers.set("Access-Control-Allow-Methods","GET, POST, OPTIONS"),r.headers.set("Access-Control-Allow-Headers","Content-Type, Authorization, X-Session-Id, X-Client-User-Agent"),r.headers.set("Access-Control-Expose-Headers","X-Session-Id"),r.headers.set("Vary","Origin")),r}}function N(t){return function(n,r,i){return t(new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"},status:r}),i)}}var v=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};function L(t){let e=t.headers,n=e.get("x-vercel-ip-city")??e.get("cf-ipcity")??void 0,r=n?z(n):void 0,i=e.get("x-vercel-ip-country")??e.get("cf-ipcountry")??void 0,s=e.get("x-vercel-ip-country-region")??void 0,g=e.get("x-vercel-ip-latitude")??e.get("cf-iplatitude")??void 0,c=e.get("x-vercel-ip-longitude")??e.get("cf-iplongitude")??void 0,f=e.get("x-vercel-ip-timezone")??e.get("cf-iptimezone")??void 0,d=e.get("x-real-ip")??e.get("x-forwarded-for")?.split(",")[0]?.trim()??e.get("cf-connecting-ip")??void 0;return{city:r,country:i,countryRegion:s,latitude:g,longitude:c,timezone:f,ip:d}}function z(t){try{return decodeURIComponent(t)}catch{return t}}function E(t){if(!t)return!1;let e=Array.isArray(t.content)&&t.content.length>0,n=typeof t.structuredContent=="object"&&t.structuredContent!==null&&Object.keys(t.structuredContent).length>0;return e||n}function q(t){if(!E(t))return"";let e=["## Widget Model Context","This hidden context was supplied by an MCP App via `ui/update-model-context`.","Use it for the next assistant turn only. If it includes flow continuation or tool-call instructions, follow them exactly."];if(t.content?.length){let n=t.content.map(r=>r.type==="text"&&typeof r.text=="string"?r.text.trim():JSON.stringify(r,null,2)).filter(Boolean).join(`
|
|
2
2
|
|
|
3
3
|
`);n&&e.push(`Content blocks:
|
|
4
4
|
${n}`)}return t.structuredContent&&Object.keys(t.structuredContent).length>0&&e.push(`Structured content JSON:
|
|
@@ -6,5 +6,5 @@ ${JSON.stringify(t.structuredContent,null,2)}`),e.join(`
|
|
|
6
6
|
|
|
7
7
|
`)}function B(t,e){if(!E(e))return t;let n=q(e);return n?[t,n].filter(Boolean).join(`
|
|
8
8
|
|
|
9
|
-
`):t}function J(t){let{apiKey:e,apiUrl:n,source:r,systemPrompt:i,maxSteps:s,beforeRequest:g,mcpServerUrl:c,resolveConfig:f,debug:d,webSearch:b}=t,o=A("chat",d);return async function(a){o("\u2192 POST",a.url);try{let p=await a.json(),S=p.messages??[],y=p.sessionId,x=p.modelContext,R=i,k=p.visitorContext??null,H=L(a),j={geo:H,client:k};if(o("body parsed \u2014 messages:",S.length,"sessionId:",y??"(none)","geo:",JSON.stringify(H)),g){o("running beforeRequest hook");try{let u=await g({messages:S,sessionId:y,modelContext:x,request:a,visitor:j});u&&(u.messages&&(S=u.messages),u.systemPrompt!==void 0&&(R=u.systemPrompt),u.sessionId!==void 0&&(y=u.sessionId),u.modelContext!==void 0&&(x=u.modelContext)),o("beforeRequest hook done \u2014 messages:",S.length,"sessionId:",y??"(none)")}catch(u){console.error("[waniwani:chat] beforeRequest hook error:",u);let O=u instanceof
|
|
9
|
+
`):t}function J(t){let{apiKey:e,apiUrl:n,source:r,systemPrompt:i,maxSteps:s,beforeRequest:g,mcpServerUrl:c,resolveConfig:f,debug:d,webSearch:b}=t,o=A("chat",d);return async function(a){o("\u2192 POST",a.url);try{let p=await a.json(),S=p.messages??[],y=p.sessionId,x=p.modelContext,R=i,k=p.visitorContext??null,H=L(a),j={geo:H,client:k};if(o("body parsed \u2014 messages:",S.length,"sessionId:",y??"(none)","geo:",JSON.stringify(H)),g){o("running beforeRequest hook");try{let u=await g({messages:S,sessionId:y,modelContext:x,request:a,visitor:j});u&&(u.messages&&(S=u.messages),u.systemPrompt!==void 0&&(R=u.systemPrompt),u.sessionId!==void 0&&(y=u.sessionId),u.modelContext!==void 0&&(x=u.modelContext)),o("beforeRequest hook done \u2014 messages:",S.length,"sessionId:",y??"(none)")}catch(u){console.error("[waniwani:chat] beforeRequest hook error:",u);let O=u instanceof v?u.status:400,F=u instanceof Error?u.message:"Request rejected";return o("\u2190 returning",O,"from hook error"),Response.json({error:F},{status:O})}}let l=c??(await f()).mcpServerUrl;o("mcpServerUrl:",l),R=B(R,x);let h=`${n}/api/mcp/chat`;o("forwarding to",h);let M=a.headers.get("user-agent"),m=await fetch(h,{method:"POST",headers:{"Content-Type":"application/json",...e?{Authorization:`Bearer ${e}`}:{},...M?{"X-Client-User-Agent":M}:{}},body:JSON.stringify({messages:S,mcpServerUrl:l,sessionId:y,source:r,systemPrompt:R,maxSteps:s,visitor:j,webSearch:b}),signal:a.signal});if(o("upstream response status:",m.status),!m.ok){let u=await m.text().catch(()=>"");return o("\u2190 returning",m.status,"upstream error:",u),new Response(u,{status:m.status,headers:{"Content-Type":m.headers.get("Content-Type")??"application/json"}})}let T=new Headers({"Content-Type":m.headers.get("Content-Type")??"text/event-stream"}),w=m.headers.get("x-session-id");return w&&T.set("x-session-id",w),o("\u2190 streaming response",m.status,"body null?",m.body===null),new Response(m.body,{status:m.status,headers:T})}catch(p){console.error("[waniwani:chat] handler error:",p);let S=p instanceof Error?p.message:"Unknown error occurred",y=p instanceof v?p.status:500;return o("\u2190 returning",y,"from caught error"),Response.json({error:S},{status:y})}}}function G(t){let{mcpServerUrl:e,resolveConfig:n,debug:r}=t,i=A("resource",r);return async function(g){i("\u2192 GET",g.toString());try{let c=g.searchParams.get("uri");if(i("uri:",c??"(missing)"),!c)return i("\u2190 400 missing uri"),Response.json({error:"Missing uri query parameter"},{status:400});let f=e??(await n()).mcpServerUrl;i("mcpServerUrl:",f);let d,b;try{[{createMCPClient:d},{StreamableHTTPClientTransport:b}]=await Promise.all([import("@ai-sdk/mcp"),import("@modelcontextprotocol/sdk/client/streamableHttp.js")]),i("MCP deps loaded")}catch(C){return console.error("[waniwani:resource] MCP deps import failed:",C),Response.json({error:"MCP resource handler requires @ai-sdk/mcp and @modelcontextprotocol/sdk. Install them to enable resource serving."},{status:501})}i("creating MCP client for",f);let o=await d({transport:new b(new URL(f))});try{i("reading resource:",c);let C=await o.readResource({uri:c});i("resource contents count:",C.contents.length);let a=C.contents[0];if(!a)return i("\u2190 404 resource not found"),Response.json({error:"Resource not found"},{status:404});let p;return"text"in a&&typeof a.text=="string"?p=a.text:"blob"in a&&typeof a.blob=="string"&&(p=atob(a.blob)),p?(i("\u2190 200 HTML length:",p.length),new Response(p,{headers:{"Content-Type":"text/html","Cache-Control":"private, max-age=300"}})):(i("\u2190 404 resource has no content, keys:",Object.keys(a)),Response.json({error:"Resource has no content"},{status:404}))}finally{await o.close(),i("MCP client closed")}}catch(c){console.error("[waniwani:resource] handler error:",c);let f=c instanceof Error?c.message:"Unknown error occurred",d=c instanceof v?c.status:500;return i("\u2190 returning",d,"from caught error"),Response.json({error:f},{status:d})}}}function $(t){let{mcpServerUrl:e,resolveConfig:n,debug:r,source:i}=t,s=A("tool",r);return async function(c){s("\u2192 POST",c.url);try{let f=await c.json(),{name:d,arguments:b}=f,o=c.headers.get("x-session-id")?.trim();if(!d||typeof d!="string")return s("\u2190 400 missing tool name"),Response.json({error:"Missing tool name"},{status:400});s("tool:",d,"args:",JSON.stringify(b),"sessionId:",o||"(none)");let C=e??(await n()).mcpServerUrl;s("mcpServerUrl:",C);let a,p;try{[{Client:a},{StreamableHTTPClientTransport:p}]=await Promise.all([import("@modelcontextprotocol/sdk/client/index.js"),import("@modelcontextprotocol/sdk/client/streamableHttp.js")]),s("MCP deps loaded")}catch(x){return console.error("[waniwani:tool] MCP deps import failed:",x),Response.json({error:"MCP tool handler requires @modelcontextprotocol/sdk. Install it to enable tool calls."},{status:501})}s("creating MCP client for",C);let S=new p(new URL(C)),y=new a({name:"waniwani-tool-caller",version:"1.0.0"});await y.connect(S);try{s("calling tool:",d);let x={};o&&(x["waniwani/sessionId"]=o),i&&(x["waniwani/source"]=i);let R=await y.callTool({name:d,arguments:b??{},...Object.keys(x).length>0?{_meta:x}:{}});return s("tool result received"),Response.json({content:R.content,structuredContent:R.structuredContent,_meta:R._meta,isError:R.isError})}finally{await y.close(),s("MCP client closed")}}catch(f){console.error("[waniwani:tool] handler error:",f);let d=f instanceof Error?f.message:"Unknown error occurred",b=f instanceof v?f.status:500;return s("\u2190 returning",b,"from caught error"),Response.json({error:d},{status:b})}}}var K=300*1e3;function D(t,e){let n=null,r=null;return async function(){if(n&&Date.now()<n.expiresAt)return n.config;if(r)return r;r=(async()=>{if(!e)throw new v("WANIWANI_API_KEY is required for createChatHandler",401);let s=await fetch(`${t}/api/mcp/environments/config`,{method:"GET",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!s.ok){let c=await s.text().catch(()=>"");throw new v(`Failed to resolve MCP environment config: ${s.status} ${c}`,s.status)}let g=await s.json();return n={config:g,expiresAt:Date.now()+K},g})();try{return await r}finally{r=null}}}var X="https://app.waniwani.ai";function _(t={}){let{apiKey:e=process.env.WANIWANI_API_KEY,apiUrl:n=X,source:r,systemPrompt:i,maxSteps:s=5,beforeRequest:g,mcpServerUrl:c,allowedOrigins:f,debug:d=!1,webSearch:b}=t,o=A("router",d),C=W([n,...f??[]]),a=N(C),p=D(n,e),S=J({apiKey:e,apiUrl:n,source:r,systemPrompt:i,maxSteps:s,beforeRequest:g,mcpServerUrl:c,resolveConfig:p,debug:d,webSearch:I(b)}),y=G({mcpServerUrl:c,resolveConfig:p,debug:d}),x=$({mcpServerUrl:c,resolveConfig:p,debug:d,source:r}),R=process.env.WANIWANI_EVAL==="1";async function k(l){o("\u2192 GET",l.url);try{let h=new URL(l.url),m=h.pathname.replace(/\/$/,"").split("/").filter(Boolean).at(-1);if(o("pathname:",h.pathname,"subRoute:",m),R&&m==="scenarios"){o("dispatching to scenarios handler (proxy to app API)");try{let w=await(await fetch(`${n}/api/mcp/scenarios`,{headers:{...e?{Authorization:`Bearer ${e}`}:{}}})).json();return a(w.data??w,200,l)}catch{return a([],200,l)}}if(m==="resource"){o("dispatching to resource handler");let T=await y(h);return o("\u2190 resource handler returned",T.status),C(T,l)}return m==="config"?(o("dispatching to config handler"),a({debug:d,eval:R},200,l)):(o("\u2190 404 no matching sub-route for",m),a({error:"Not found"},404,l))}catch(h){console.error("[waniwani:router] GET handler error:",h);let M=h instanceof Error?h.message:"Unknown error occurred";return o("\u2190 500 from caught error"),a({error:M},500,l)}}async function H(l){o("\u2192 POST",l.url);try{let h=new URL(l.url),m=h.pathname.replace(/\/$/,"").split("/").filter(Boolean).at(-1);if(o("pathname:",h.pathname,"subRoute:",m),R&&m==="scenarios"){o("dispatching to save-scenario handler (proxy to app API)");try{let w=await l.json(),u=await fetch(`${n}/api/mcp/scenarios`,{method:"POST",headers:{"Content-Type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(w)}),O=await u.json();return u.ok?a({ok:!0,scenario:O.data},200,l):a({error:O.message??"Failed to save scenario"},u.status,l)}catch(w){let u=w instanceof Error?w.message:"Failed to save scenario";return a({error:u},400,l)}}if(m==="tool"){o("dispatching to tool handler");let w=await x(l);return o("\u2190 tool handler returned",w.status),C(w,l)}o("dispatching to chat handler");let T=await S(l);return C(T,l)}catch(h){console.error("[waniwani:router] POST handler error:",h);let M=h instanceof Error?h.message:"Unknown error occurred";return o("\u2190 500 from caught error"),a({error:M},500,l)}}function j(l){return C(new Response(null,{status:204}),l)}return{handleChat:S,handleResource:y,handleTool:x,routeGet:k,routePost:H,handleOptions:j}}function qe(t,e){let{apiKey:n,apiUrl:r}=t._config,i=e?.debug??process.env.WANIWANI_DEBUG==="1",s=_({...e?.chat,apiKey:n,apiUrl:r,source:e?.source,allowedOrigins:e?.allowedOrigins,debug:i});return{POST:s.routePost,GET:s.routeGet,OPTIONS:g=>s.handleOptions(g)}}export{qe as toNextJsHandler};
|
|
10
10
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/logger.ts","../../../src/chat/server/@types.ts","../../../src/chat/server/@utils.ts","../../../src/error.ts","../../../src/chat/server/geo.ts","../../../src/shared/model-context.ts","../../../src/chat/server/model-context.ts","../../../src/chat/server/handle-chat.ts","../../../src/chat/server/handle-resource.ts","../../../src/chat/server/handle-tool.ts","../../../src/chat/server/mcp-config-resolver.ts","../../../src/chat/server/api-handler.ts","../../../src/chat/server/next-js/index.ts"],"sourcesContent":["/**\n * Creates a namespaced logger that writes to console.log when enabled,\n * or is a no-op when disabled.\n *\n * @example\n * const log = createLogger(\"chat\", debug);\n * log(\"→ POST\", request.url); // [waniwani:chat] → POST ...\n */\nexport function createLogger(\n\tnamespace: string,\n\tenabled: boolean,\n): (...args: unknown[]) => void {\n\treturn enabled\n\t\t? (...args: unknown[]) => console.log(`[waniwani:${namespace}]`, ...args)\n\t\t: () => {};\n}\n","// WaniWani SDK - Chat Server Types\n\nimport type { UIMessage } from \"ai\";\nimport type { ModelContextUpdate } from \"../../shared/model-context\";\nimport type { GeoLocation } from \"./geo\";\n\n// ============================================================================\n// Visitor Context\n// ============================================================================\n\n/** Client-side visitor context sent in the request body */\nexport interface ClientVisitorContext {\n\ttimezone: string;\n\tlanguage: string;\n\tlanguages: string[];\n\tdeviceType: \"mobile\" | \"tablet\" | \"desktop\";\n\treferrer: string;\n\tvisitorId: string;\n}\n\n/** Combined visitor context: server geo + client context */\nexport interface VisitorMeta {\n\tgeo: GeoLocation;\n\tclient: ClientVisitorContext | null;\n}\n\n// ============================================================================\n// Before Request Hook\n// ============================================================================\n\nexport interface BeforeRequestContext {\n\t/** The conversation messages from the client */\n\tmessages: UIMessage[];\n\t/** Session identifier for conversation continuity */\n\tsessionId?: string;\n\t/** Hidden widget-provided model context for the next assistant turn */\n\tmodelContext?: ModelContextUpdate;\n\t/** The original HTTP Request object */\n\trequest: Request;\n\t/** Server-extracted geo location + client-provided visitor context */\n\tvisitor: VisitorMeta;\n}\n\nexport type BeforeRequestResult = {\n\t/** Override messages (e.g., filtered, augmented) */\n\tmessages?: UIMessage[];\n\t/** Override the system prompt for this request */\n\tsystemPrompt?: string;\n\t/** Override sessionId */\n\tsessionId?: string;\n\t/** Override hidden widget-provided model context */\n\tmodelContext?: ModelContextUpdate;\n};\n\n// ============================================================================\n// Web Search\n// ============================================================================\n\nexport interface WebSearchConfig {\n\t/** Restrict web search results to these domains */\n\tincludeDomains?: string[];\n\t/** Exclude these domains from web search results */\n\texcludeDomains?: string[];\n}\n\n// ============================================================================\n// API Handler Options\n// ============================================================================\n\nexport interface ApiHandlerOptions {\n\t/**\n\t * Identifies this chatbar instance in analytics.\n\t * Forwarded as `waniwani/source` in MCP request metadata.\n\t */\n\tsource?: string;\n\n\t/**\n\t * Your WaniWani API key.\n\t * Defaults to process.env.WANIWANI_API_KEY.\n\t */\n\tapiKey?: string;\n\n\t/**\n\t * The base URL of the WaniWani API.\n\t * Defaults to https://app.waniwani.ai.\n\t */\n\tapiUrl?: string;\n\n\t/**\n\t * System prompt for the assistant.\n\t * Can be overridden per-request via `beforeRequest`.\n\t */\n\tsystemPrompt?: string;\n\n\t/**\n\t * Maximum number of tool call steps. Defaults to 5.\n\t */\n\tmaxSteps?: number;\n\n\t/**\n\t * Hook called before each request is forwarded to the WaniWani API.\n\t * - Return void to use defaults.\n\t * - Return an object to override messages, systemPrompt, or sessionId.\n\t * - Throw to reject the request (the error message is returned as JSON).\n\t */\n\tbeforeRequest?: (\n\t\tcontext: BeforeRequestContext,\n\t) =>\n\t\t| Promise<BeforeRequestResult | undefined>\n\t\t| BeforeRequestResult\n\t\t| undefined;\n\n\t/**\n\t * Override the MCP server URL directly, bypassing config resolution.\n\t * Useful for development/testing when pointing to a local MCP server.\n\t */\n\tmcpServerUrl?: string;\n\n\t/**\n\t * Enable verbose debug logging for all handler steps.\n\t * Logs request details, response codes, resolved URLs, and caught errors.\n\t */\n\tdebug?: boolean;\n\n\t/**\n\t * Additional origins allowed for cross-origin requests.\n\t * The WaniWani platform URL (apiUrl) is always included.\n\t */\n\tallowedOrigins?: string[];\n\n\t/**\n\t * Enable web search as an additional tool alongside MCP tools.\n\t * Pass `true` to enable with defaults, or a config object to restrict domains.\n\t */\n\twebSearch?: boolean | WebSearchConfig;\n}\n\n// ============================================================================\n// API Handler Result\n// ============================================================================\n\nexport interface ApiHandler {\n\t/** Proxies chat messages to the WaniWani API */\n\thandleChat: (request: Request) => Promise<Response>;\n\t/** Serves MCP resource content (HTML widgets) */\n\thandleResource: (url: URL) => Promise<Response>;\n\t/** Calls an MCP server tool and returns JSON */\n\thandleTool: (request: Request) => Promise<Response>;\n\t/** Routes GET sub-paths (e.g. /resource) */\n\trouteGet: (request: Request) => Promise<Response>;\n\t/** Routes POST sub-paths (e.g. /tool), defaults to chat */\n\troutePost: (request: Request) => Promise<Response>;\n\t/** Handles CORS preflight requests */\n\thandleOptions: (request?: Request) => Response;\n}\n\n// ============================================================================\n// Internal Dependencies (shared across sub-handlers)\n// ============================================================================\n\ninterface McpEnvironmentConfig {\n\tmcpServerUrl: string;\n}\n\ntype ConfigResolver = () => Promise<McpEnvironmentConfig>;\n\nexport interface ApiHandlerDeps {\n\tapiKey: string | undefined;\n\tapiUrl: string;\n\tsource: string | undefined;\n\tsystemPrompt: string | undefined;\n\tmaxSteps: number;\n\tbeforeRequest: ApiHandlerOptions[\"beforeRequest\"];\n\tmcpServerUrl: string | undefined;\n\tresolveConfig: ConfigResolver;\n\tdebug: boolean;\n\twebSearch?: WebSearchConfig;\n}\n\n/** Normalize `true` to `{}` so the upstream API always receives an object or undefined */\nexport function resolveWebSearchConfig(\n\tvalue: boolean | WebSearchConfig | undefined,\n): WebSearchConfig | undefined {\n\tif (value === true) {\n\t\treturn {};\n\t}\n\tif (value === false || value === undefined) {\n\t\treturn undefined;\n\t}\n\treturn value;\n}\n\nexport interface ResourceHandlerDeps {\n\tmcpServerUrl: string | undefined;\n\tresolveConfig: ConfigResolver;\n\tdebug: boolean;\n\tsource?: string;\n}\n","// Shared helpers for chat server handlers\n\nexport type CorsFunction = (response: Response, request?: Request) => Response;\n\nexport function createCors(allowedOrigins: string[]): CorsFunction {\n\tconst originSet = new Set(\n\t\tallowedOrigins.map((o) => o.replace(/\\/$/, \"\").toLowerCase()),\n\t);\n\n\treturn function applyCors(response: Response, request?: Request): Response {\n\t\tconst requestOrigin = request?.headers.get(\"origin\");\n\t\tconst origin = requestOrigin?.toLowerCase();\n\t\t// Auto-allow all *.mcp.waniwani.run subdomains (deployed chat widgets)\n\t\tconst isAllowed =\n\t\t\torigin != null &&\n\t\t\t(originSet.has(origin) || origin.endsWith(\".mcp.waniwani.run\"));\n\n\t\tif (!isAllowed) {\n\t\t\treturn response;\n\t\t}\n\n\t\tresponse.headers.set(\n\t\t\t\"Access-Control-Allow-Origin\",\n\t\t\trequestOrigin as string,\n\t\t);\n\t\tresponse.headers.set(\"Access-Control-Allow-Methods\", \"GET, POST, OPTIONS\");\n\t\tresponse.headers.set(\n\t\t\t\"Access-Control-Allow-Headers\",\n\t\t\t\"Content-Type, Authorization, X-Session-Id, X-Client-User-Agent\",\n\t\t);\n\t\tresponse.headers.set(\"Access-Control-Expose-Headers\", \"X-Session-Id\");\n\t\tresponse.headers.set(\"Vary\", \"Origin\");\n\t\treturn response;\n\t};\n}\n\nexport function createJsonResponse(cors: CorsFunction) {\n\treturn function json(\n\t\tdata: object,\n\t\tstatus: number,\n\t\trequest?: Request,\n\t): Response {\n\t\treturn cors(\n\t\t\tnew Response(JSON.stringify(data), {\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\tstatus,\n\t\t\t}),\n\t\t\trequest,\n\t\t);\n\t};\n}\n","// WaniWani SDK - Errors\n\nexport class WaniWaniError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic status: number,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"WaniWaniError\";\n\t}\n}\n","// Geo — Extract location metadata from platform request headers\n\n/**\n * Server-side geolocation extracted from platform headers (Vercel, Cloudflare).\n * All fields are optional — in local dev, no headers are present.\n */\nexport interface GeoLocation {\n\tcity?: string;\n\tcountry?: string;\n\tcountryRegion?: string;\n\tlatitude?: string;\n\tlongitude?: string;\n\ttimezone?: string;\n\tip?: string;\n}\n\n/**\n * Extracts geolocation from server-side request headers.\n *\n * Supports Vercel (`x-vercel-ip-*`), Cloudflare (`cf-ip*`, `cf-connecting-ip`),\n * and generic IP headers (`x-real-ip`, `x-forwarded-for`).\n *\n * Returns a `GeoLocation` with all fields optional (empty object in local dev).\n */\nexport function extractGeoFromHeaders(request: Request): GeoLocation {\n\tconst h = request.headers;\n\n\t// Vercel URL-encodes city names (e.g. \"S%C3%A3o%20Paulo\")\n\tconst rawCity = h.get(\"x-vercel-ip-city\") ?? h.get(\"cf-ipcity\") ?? undefined;\n\tconst city = rawCity ? safeDecodeURI(rawCity) : undefined;\n\n\tconst country =\n\t\th.get(\"x-vercel-ip-country\") ?? h.get(\"cf-ipcountry\") ?? undefined;\n\tconst countryRegion = h.get(\"x-vercel-ip-country-region\") ?? undefined;\n\tconst latitude =\n\t\th.get(\"x-vercel-ip-latitude\") ?? h.get(\"cf-iplatitude\") ?? undefined;\n\tconst longitude =\n\t\th.get(\"x-vercel-ip-longitude\") ?? h.get(\"cf-iplongitude\") ?? undefined;\n\tconst timezone =\n\t\th.get(\"x-vercel-ip-timezone\") ?? h.get(\"cf-iptimezone\") ?? undefined;\n\tconst ip =\n\t\th.get(\"x-real-ip\") ??\n\t\th.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ??\n\t\th.get(\"cf-connecting-ip\") ??\n\t\tundefined;\n\n\treturn { city, country, countryRegion, latitude, longitude, timezone, ip };\n}\n\nfunction safeDecodeURI(value: string): string {\n\ttry {\n\t\treturn decodeURIComponent(value);\n\t} catch {\n\t\treturn value;\n\t}\n}\n","import type { ContentBlock } from \"@modelcontextprotocol/sdk/types.js\";\n\nexport type ModelContextContentBlock = ContentBlock;\n\nexport type ModelContextUpdate = {\n\tcontent?: ModelContextContentBlock[];\n\tstructuredContent?: Record<string, unknown>;\n};\n\nexport function hasModelContext(\n\tvalue: ModelContextUpdate | null | undefined,\n): value is ModelContextUpdate {\n\tif (!value) {\n\t\treturn false;\n\t}\n\tconst hasContent = Array.isArray(value.content) && value.content.length > 0;\n\tconst hasStructuredContent =\n\t\ttypeof value.structuredContent === \"object\" &&\n\t\tvalue.structuredContent !== null &&\n\t\tObject.keys(value.structuredContent).length > 0;\n\treturn hasContent || hasStructuredContent;\n}\n\nexport function mergeModelContext(\n\tcurrent: ModelContextUpdate | null | undefined,\n\tnext: ModelContextUpdate | null | undefined,\n): ModelContextUpdate | null {\n\tif (!hasModelContext(current) && !hasModelContext(next)) {\n\t\treturn null;\n\t}\n\tif (!hasModelContext(current)) {\n\t\treturn {\n\t\t\t...(next?.content ? { content: [...next.content] } : {}),\n\t\t\t...(next?.structuredContent\n\t\t\t\t? { structuredContent: { ...next.structuredContent } }\n\t\t\t\t: {}),\n\t\t};\n\t}\n\tif (!hasModelContext(next)) {\n\t\treturn {\n\t\t\t...(current.content ? { content: [...current.content] } : {}),\n\t\t\t...(current.structuredContent\n\t\t\t\t? { structuredContent: { ...current.structuredContent } }\n\t\t\t\t: {}),\n\t\t};\n\t}\n\n\treturn {\n\t\t...(current.content || next.content\n\t\t\t? { content: [...(current.content ?? []), ...(next.content ?? [])] }\n\t\t\t: {}),\n\t\t...(current.structuredContent || next.structuredContent\n\t\t\t? {\n\t\t\t\t\tstructuredContent: {\n\t\t\t\t\t\t...(current.structuredContent ?? {}),\n\t\t\t\t\t\t...(next.structuredContent ?? {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\nexport function formatModelContextForPrompt(\n\tvalue: ModelContextUpdate | null | undefined,\n): string {\n\tif (!hasModelContext(value)) {\n\t\treturn \"\";\n\t}\n\n\tconst sections: string[] = [\n\t\t\"## Widget Model Context\",\n\t\t\"This hidden context was supplied by an MCP App via `ui/update-model-context`.\",\n\t\t\"Use it for the next assistant turn only. If it includes flow continuation or tool-call instructions, follow them exactly.\",\n\t];\n\n\tif (value.content?.length) {\n\t\tconst renderedBlocks = value.content\n\t\t\t.map((block) => {\n\t\t\t\tif (block.type === \"text\" && typeof block.text === \"string\") {\n\t\t\t\t\treturn block.text.trim();\n\t\t\t\t}\n\t\t\t\treturn JSON.stringify(block, null, 2);\n\t\t\t})\n\t\t\t.filter(Boolean)\n\t\t\t.join(\"\\n\\n\");\n\t\tif (renderedBlocks) {\n\t\t\tsections.push(`Content blocks:\\n${renderedBlocks}`);\n\t\t}\n\t}\n\n\tif (\n\t\tvalue.structuredContent &&\n\t\tObject.keys(value.structuredContent).length > 0\n\t) {\n\t\tsections.push(\n\t\t\t`Structured content JSON:\\n${JSON.stringify(value.structuredContent, null, 2)}`,\n\t\t);\n\t}\n\n\treturn sections.join(\"\\n\\n\");\n}\n","import {\n\tformatModelContextForPrompt,\n\thasModelContext,\n\ttype ModelContextUpdate,\n} from \"../../shared/model-context\";\n\nexport function applyModelContextToSystemPrompt(\n\tsystemPrompt: string | undefined,\n\tmodelContext: ModelContextUpdate | undefined,\n): string | undefined {\n\tif (!hasModelContext(modelContext)) {\n\t\treturn systemPrompt;\n\t}\n\n\tconst widgetContext = formatModelContextForPrompt(modelContext);\n\tif (!widgetContext) {\n\t\treturn systemPrompt;\n\t}\n\n\treturn [systemPrompt, widgetContext].filter(Boolean).join(\"\\n\\n\");\n}\n","// Handle Chat - Proxies chat requests to the WaniWani API\n\nimport { WaniWaniError } from \"../../error\";\nimport { createLogger } from \"../../utils/logger.js\";\nimport type {\n\tApiHandlerDeps,\n\tClientVisitorContext,\n\tVisitorMeta,\n} from \"./@types\";\nimport { extractGeoFromHeaders } from \"./geo\";\nimport { applyModelContextToSystemPrompt } from \"./model-context\";\n\nexport function createChatRequestHandler(deps: ApiHandlerDeps) {\n\tconst {\n\t\tapiKey,\n\t\tapiUrl,\n\t\tsource,\n\t\tsystemPrompt,\n\t\tmaxSteps,\n\t\tbeforeRequest,\n\t\tmcpServerUrl: mcpServerUrlOverride,\n\t\tresolveConfig,\n\t\tdebug,\n\t\twebSearch,\n\t} = deps;\n\n\tconst log = createLogger(\"chat\", debug);\n\n\treturn async function handleChat(request: Request): Promise<Response> {\n\t\tlog(\"→ POST\", request.url);\n\t\ttry {\n\t\t\t// 1. Parse request body\n\t\t\tconst body = await request.json();\n\t\t\tlet messages = body.messages ?? [];\n\t\t\tlet sessionId: string | undefined = body.sessionId;\n\t\t\tlet modelContext = body.modelContext;\n\t\t\tlet effectiveSystemPrompt = systemPrompt;\n\n\t\t\t// Extract visitor context (client-side + server-side geo)\n\t\t\tconst clientVisitorContext: ClientVisitorContext | null =\n\t\t\t\tbody.visitorContext ?? null;\n\t\t\tconst geo = extractGeoFromHeaders(request);\n\t\t\tconst visitor: VisitorMeta = { geo, client: clientVisitorContext };\n\n\t\t\tlog(\n\t\t\t\t\"body parsed — messages:\",\n\t\t\t\tmessages.length,\n\t\t\t\t\"sessionId:\",\n\t\t\t\tsessionId ?? \"(none)\",\n\t\t\t\t\"geo:\",\n\t\t\t\tJSON.stringify(geo),\n\t\t\t);\n\n\t\t\t// 2. Run beforeRequest hook\n\t\t\tif (beforeRequest) {\n\t\t\t\tlog(\"running beforeRequest hook\");\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await beforeRequest({\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tmodelContext,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\tvisitor,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (result) {\n\t\t\t\t\t\tif (result.messages) {\n\t\t\t\t\t\t\tmessages = result.messages;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.systemPrompt !== undefined) {\n\t\t\t\t\t\t\teffectiveSystemPrompt = result.systemPrompt;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.sessionId !== undefined) {\n\t\t\t\t\t\t\tsessionId = result.sessionId;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.modelContext !== undefined) {\n\t\t\t\t\t\t\tmodelContext = result.modelContext;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlog(\n\t\t\t\t\t\t\"beforeRequest hook done — messages:\",\n\t\t\t\t\t\tmessages.length,\n\t\t\t\t\t\t\"sessionId:\",\n\t\t\t\t\t\tsessionId ?? \"(none)\",\n\t\t\t\t\t);\n\t\t\t\t} catch (hookError) {\n\t\t\t\t\tconsole.error(\"[waniwani:chat] beforeRequest hook error:\", hookError);\n\t\t\t\t\tconst status =\n\t\t\t\t\t\thookError instanceof WaniWaniError ? hookError.status : 400;\n\t\t\t\t\tconst message =\n\t\t\t\t\t\thookError instanceof Error ? hookError.message : \"Request rejected\";\n\t\t\t\t\tlog(\"← returning\", status, \"from hook error\");\n\t\t\t\t\treturn Response.json({ error: message }, { status });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// 3. Resolve MCP server URL\n\t\t\tconst mcpServerUrl =\n\t\t\t\tmcpServerUrlOverride ?? (await resolveConfig()).mcpServerUrl;\n\t\t\tlog(\"mcpServerUrl:\", mcpServerUrl);\n\t\t\teffectiveSystemPrompt = applyModelContextToSystemPrompt(\n\t\t\t\teffectiveSystemPrompt,\n\t\t\t\tmodelContext,\n\t\t\t);\n\n\t\t\t// 4. Forward to WaniWani API\n\t\t\tconst upstreamUrl = `${apiUrl}/api/mcp/chat`;\n\t\t\tlog(\"forwarding to\", upstreamUrl);\n\t\t\tconst clientUserAgent = request.headers.get(\"user-agent\");\n\n\t\t\tconst response = await fetch(upstreamUrl, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n\t\t\t\t\t...(clientUserAgent\n\t\t\t\t\t\t? { \"X-Client-User-Agent\": clientUserAgent }\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmessages,\n\t\t\t\t\tmcpServerUrl,\n\t\t\t\t\tsessionId,\n\t\t\t\t\tsource,\n\t\t\t\t\tsystemPrompt: effectiveSystemPrompt,\n\t\t\t\t\tmaxSteps,\n\t\t\t\t\tvisitor,\n\t\t\t\t\twebSearch,\n\t\t\t\t}),\n\t\t\t\tsignal: request.signal,\n\t\t\t});\n\n\t\t\tlog(\"upstream response status:\", response.status);\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst errorBody = await response.text().catch(() => \"\");\n\t\t\t\tlog(\"← returning\", response.status, \"upstream error:\", errorBody);\n\t\t\t\treturn new Response(errorBody, {\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\":\n\t\t\t\t\t\t\tresponse.headers.get(\"Content-Type\") ?? \"application/json\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// 5. Stream the response back\n\t\t\tconst headers = new Headers({\n\t\t\t\t\"Content-Type\":\n\t\t\t\t\tresponse.headers.get(\"Content-Type\") ?? \"text/event-stream\",\n\t\t\t});\n\t\t\tconst upstreamSessionId = response.headers.get(\"x-session-id\");\n\t\t\tif (upstreamSessionId) {\n\t\t\t\theaders.set(\"x-session-id\", upstreamSessionId);\n\t\t\t}\n\n\t\t\tlog(\n\t\t\t\t\"← streaming response\",\n\t\t\t\tresponse.status,\n\t\t\t\t\"body null?\",\n\t\t\t\tresponse.body === null,\n\t\t\t);\n\t\t\treturn new Response(response.body, {\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:chat] handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tconst status = error instanceof WaniWaniError ? error.status : 500;\n\t\t\tlog(\"← returning\", status, \"from caught error\");\n\t\t\treturn Response.json({ error: message }, { status });\n\t\t}\n\t};\n}\n","// Handle Resource - Serves MCP resource content (HTML widgets)\n\nimport { WaniWaniError } from \"../../error\";\nimport { createLogger } from \"../../utils/logger.js\";\nimport type { ResourceHandlerDeps } from \"./@types\";\n\nexport function createResourceHandler(deps: ResourceHandlerDeps) {\n\tconst { mcpServerUrl: mcpServerUrlOverride, resolveConfig, debug } = deps;\n\n\tconst log = createLogger(\"resource\", debug);\n\n\treturn async function handleResource(url: URL): Promise<Response> {\n\t\tlog(\"→ GET\", url.toString());\n\t\ttry {\n\t\t\tconst uri = url.searchParams.get(\"uri\");\n\t\t\tlog(\"uri:\", uri ?? \"(missing)\");\n\n\t\t\tif (!uri) {\n\t\t\t\tlog(\"← 400 missing uri\");\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{ error: \"Missing uri query parameter\" },\n\t\t\t\t\t{ status: 400 },\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst mcpServerUrl =\n\t\t\t\tmcpServerUrlOverride ?? (await resolveConfig()).mcpServerUrl;\n\t\t\tlog(\"mcpServerUrl:\", mcpServerUrl);\n\n\t\t\t// Dynamic imports — these are optional peer dependencies\n\t\t\tlet createMCPClient: typeof import(\"@ai-sdk/mcp\")[\"createMCPClient\"];\n\t\t\tlet StreamableHTTPClientTransport: typeof import(\"@modelcontextprotocol/sdk/client/streamableHttp.js\")[\"StreamableHTTPClientTransport\"];\n\n\t\t\ttry {\n\t\t\t\t[{ createMCPClient }, { StreamableHTTPClientTransport }] =\n\t\t\t\t\tawait Promise.all([\n\t\t\t\t\t\timport(\"@ai-sdk/mcp\"),\n\t\t\t\t\t\timport(\"@modelcontextprotocol/sdk/client/streamableHttp.js\"),\n\t\t\t\t\t]);\n\t\t\t\tlog(\"MCP deps loaded\");\n\t\t\t} catch (importError) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t\"[waniwani:resource] MCP deps import failed:\",\n\t\t\t\t\timportError,\n\t\t\t\t);\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\t\"MCP resource handler requires @ai-sdk/mcp and @modelcontextprotocol/sdk. Install them to enable resource serving.\",\n\t\t\t\t\t},\n\t\t\t\t\t{ status: 501 },\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlog(\"creating MCP client for\", mcpServerUrl);\n\t\t\tconst mcp = await createMCPClient({\n\t\t\t\ttransport: new StreamableHTTPClientTransport(new URL(mcpServerUrl)),\n\t\t\t});\n\n\t\t\ttry {\n\t\t\t\tlog(\"reading resource:\", uri);\n\t\t\t\tconst result = await mcp.readResource({ uri });\n\t\t\t\tlog(\"resource contents count:\", result.contents.length);\n\n\t\t\t\tconst content = result.contents[0];\n\t\t\t\tif (!content) {\n\t\t\t\t\tlog(\"← 404 resource not found\");\n\t\t\t\t\treturn Response.json(\n\t\t\t\t\t\t{ error: \"Resource not found\" },\n\t\t\t\t\t\t{ status: 404 },\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tlet html: string | undefined;\n\t\t\t\tif (\"text\" in content && typeof content.text === \"string\") {\n\t\t\t\t\thtml = content.text;\n\t\t\t\t} else if (\"blob\" in content && typeof content.blob === \"string\") {\n\t\t\t\t\thtml = atob(content.blob);\n\t\t\t\t}\n\n\t\t\t\tif (!html) {\n\t\t\t\t\tlog(\"← 404 resource has no content, keys:\", Object.keys(content));\n\t\t\t\t\treturn Response.json(\n\t\t\t\t\t\t{ error: \"Resource has no content\" },\n\t\t\t\t\t\t{ status: 404 },\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tlog(\"← 200 HTML length:\", html.length);\n\t\t\t\treturn new Response(html, {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": \"text/html\",\n\t\t\t\t\t\t\"Cache-Control\": \"private, max-age=300\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tawait mcp.close();\n\t\t\t\tlog(\"MCP client closed\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:resource] handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tconst status = error instanceof WaniWaniError ? error.status : 500;\n\t\t\tlog(\"← returning\", status, \"from caught error\");\n\t\t\treturn Response.json({ error: message }, { status });\n\t\t}\n\t};\n}\n","// Handle Tool - Calls MCP server tools directly and returns JSON results\n\nimport { WaniWaniError } from \"../../error\";\nimport { createLogger } from \"../../utils/logger.js\";\nimport type { ResourceHandlerDeps } from \"./@types\";\n\nexport function createToolHandler(deps: ResourceHandlerDeps) {\n\tconst {\n\t\tmcpServerUrl: mcpServerUrlOverride,\n\t\tresolveConfig,\n\t\tdebug,\n\t\tsource,\n\t} = deps;\n\n\tconst log = createLogger(\"tool\", debug);\n\n\treturn async function handleTool(request: Request): Promise<Response> {\n\t\tlog(\"→ POST\", request.url);\n\t\ttry {\n\t\t\tconst body = await request.json();\n\t\t\tconst { name, arguments: args } = body as {\n\t\t\t\tname: string;\n\t\t\t\targuments: Record<string, unknown>;\n\t\t\t};\n\t\t\tconst requestSessionId = request.headers.get(\"x-session-id\")?.trim();\n\n\t\t\tif (!name || typeof name !== \"string\") {\n\t\t\t\tlog(\"← 400 missing tool name\");\n\t\t\t\treturn Response.json({ error: \"Missing tool name\" }, { status: 400 });\n\t\t\t}\n\n\t\t\tlog(\n\t\t\t\t\"tool:\",\n\t\t\t\tname,\n\t\t\t\t\"args:\",\n\t\t\t\tJSON.stringify(args),\n\t\t\t\t\"sessionId:\",\n\t\t\t\trequestSessionId || \"(none)\",\n\t\t\t);\n\n\t\t\tconst mcpServerUrl =\n\t\t\t\tmcpServerUrlOverride ?? (await resolveConfig()).mcpServerUrl;\n\t\t\tlog(\"mcpServerUrl:\", mcpServerUrl);\n\n\t\t\t// Dynamic imports — these are optional peer dependencies\n\t\t\tlet Client: typeof import(\"@modelcontextprotocol/sdk/client/index.js\")[\"Client\"];\n\t\t\tlet StreamableHTTPClientTransport: typeof import(\"@modelcontextprotocol/sdk/client/streamableHttp.js\")[\"StreamableHTTPClientTransport\"];\n\n\t\t\ttry {\n\t\t\t\t[{ Client }, { StreamableHTTPClientTransport }] = await Promise.all([\n\t\t\t\t\timport(\"@modelcontextprotocol/sdk/client/index.js\"),\n\t\t\t\t\timport(\"@modelcontextprotocol/sdk/client/streamableHttp.js\"),\n\t\t\t\t]);\n\t\t\t\tlog(\"MCP deps loaded\");\n\t\t\t} catch (importError) {\n\t\t\t\tconsole.error(\"[waniwani:tool] MCP deps import failed:\", importError);\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\t\"MCP tool handler requires @modelcontextprotocol/sdk. Install it to enable tool calls.\",\n\t\t\t\t\t},\n\t\t\t\t\t{ status: 501 },\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlog(\"creating MCP client for\", mcpServerUrl);\n\t\t\tconst transport = new StreamableHTTPClientTransport(\n\t\t\t\tnew URL(mcpServerUrl),\n\t\t\t);\n\t\t\tconst client = new Client({\n\t\t\t\tname: \"waniwani-tool-caller\",\n\t\t\t\tversion: \"1.0.0\",\n\t\t\t});\n\t\t\tawait client.connect(transport);\n\n\t\t\ttry {\n\t\t\t\tlog(\"calling tool:\", name);\n\t\t\t\tconst _meta: Record<string, unknown> = {};\n\t\t\t\tif (requestSessionId) {\n\t\t\t\t\t_meta[\"waniwani/sessionId\"] = requestSessionId;\n\t\t\t\t}\n\t\t\t\tif (source) {\n\t\t\t\t\t_meta[\"waniwani/source\"] = source;\n\t\t\t\t}\n\t\t\t\tconst result = await client.callTool({\n\t\t\t\t\tname,\n\t\t\t\t\targuments: args ?? {},\n\t\t\t\t\t...(Object.keys(_meta).length > 0 ? { _meta } : {}),\n\t\t\t\t} as {\n\t\t\t\t\tname: string;\n\t\t\t\t\targuments: Record<string, unknown>;\n\t\t\t\t\t_meta?: Record<string, unknown>;\n\t\t\t\t});\n\t\t\t\tlog(\"tool result received\");\n\n\t\t\t\treturn Response.json({\n\t\t\t\t\tcontent: result.content,\n\t\t\t\t\tstructuredContent: result.structuredContent,\n\t\t\t\t\t_meta: result._meta,\n\t\t\t\t\tisError: result.isError,\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tawait client.close();\n\t\t\t\tlog(\"MCP client closed\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:tool] handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tconst status = error instanceof WaniWaniError ? error.status : 500;\n\t\t\tlog(\"← returning\", status, \"from caught error\");\n\t\t\treturn Response.json({ error: message }, { status });\n\t\t}\n\t};\n}\n","// MCP Config Resolver - Lazy-loads and caches MCP environment config\n\nimport { WaniWaniError } from \"../../error\";\n\ninterface McpEnvironmentConfig {\n\tmcpServerUrl: string;\n}\n\nconst TTL_MS = 5 * 60 * 1000; // 5 minutes\n\nexport function createMcpConfigResolver(\n\tapiUrl: string,\n\tapiKey: string | undefined,\n) {\n\tlet cached: { config: McpEnvironmentConfig; expiresAt: number } | null = null;\n\tlet inflight: Promise<McpEnvironmentConfig> | null = null;\n\n\treturn async function resolve(): Promise<McpEnvironmentConfig> {\n\t\tif (cached && Date.now() < cached.expiresAt) {\n\t\t\treturn cached.config;\n\t\t}\n\n\t\t// Deduplicate concurrent requests (cold start scenario)\n\t\tif (inflight) {\n\t\t\treturn inflight;\n\t\t}\n\n\t\tinflight = (async () => {\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new WaniWaniError(\n\t\t\t\t\t\"WANIWANI_API_KEY is required for createChatHandler\",\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst response = await fetch(`${apiUrl}/api/mcp/environments/config`, {\n\t\t\t\tmethod: \"GET\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst body = await response.text().catch(() => \"\");\n\t\t\t\tthrow new WaniWaniError(\n\t\t\t\t\t`Failed to resolve MCP environment config: ${response.status} ${body}`,\n\t\t\t\t\tresponse.status,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst data = (await response.json()) as McpEnvironmentConfig;\n\t\t\tcached = { config: data, expiresAt: Date.now() + TTL_MS };\n\t\t\treturn data;\n\t\t})();\n\n\t\ttry {\n\t\t\treturn await inflight;\n\t\t} finally {\n\t\t\tinflight = null;\n\t\t}\n\t};\n}\n","// API Handler - Composes chat and resource handlers into a unified API handler\n\nimport { createLogger } from \"../../utils/logger.js\";\nimport {\n\ttype ApiHandler,\n\ttype ApiHandlerOptions,\n\tresolveWebSearchConfig,\n} from \"./@types\";\nimport { createCors, createJsonResponse } from \"./@utils\";\nimport { createChatRequestHandler } from \"./handle-chat\";\nimport { createResourceHandler } from \"./handle-resource\";\nimport { createToolHandler } from \"./handle-tool\";\nimport { createMcpConfigResolver } from \"./mcp-config-resolver\";\n\nconst DEFAULT_API_URL = \"https://app.waniwani.ai\";\n\nexport function createApiHandler(options: ApiHandlerOptions = {}): ApiHandler {\n\tconst {\n\t\tapiKey = process.env.WANIWANI_API_KEY,\n\t\tapiUrl = DEFAULT_API_URL,\n\t\tsource,\n\t\tsystemPrompt,\n\t\tmaxSteps = 5,\n\t\tbeforeRequest,\n\t\tmcpServerUrl,\n\t\tallowedOrigins: extraOrigins,\n\t\tdebug = false,\n\t\twebSearch,\n\t} = options;\n\n\tconst log = createLogger(\"router\", debug);\n\tconst cors = createCors([apiUrl, ...(extraOrigins ?? [])]);\n\tconst json = createJsonResponse(cors);\n\n\tconst resolveConfig = createMcpConfigResolver(apiUrl, apiKey);\n\n\tconst handleChat = createChatRequestHandler({\n\t\tapiKey,\n\t\tapiUrl,\n\t\tsource,\n\t\tsystemPrompt,\n\t\tmaxSteps,\n\t\tbeforeRequest,\n\t\tmcpServerUrl,\n\t\tresolveConfig,\n\t\tdebug,\n\t\twebSearch: resolveWebSearchConfig(webSearch),\n\t});\n\n\tconst handleResource = createResourceHandler({\n\t\tmcpServerUrl,\n\t\tresolveConfig,\n\t\tdebug,\n\t});\n\n\tconst handleTool = createToolHandler({\n\t\tmcpServerUrl,\n\t\tresolveConfig,\n\t\tdebug,\n\t\tsource,\n\t});\n\n\tconst evalEnabled = process.env.WANIWANI_EVAL === \"1\";\n\n\tasync function routeGet(request: Request): Promise<Response> {\n\t\tlog(\"→ GET\", request.url);\n\t\ttry {\n\t\t\tconst url = new URL(request.url);\n\t\t\tconst segments = url.pathname\n\t\t\t\t.replace(/\\/$/, \"\")\n\t\t\t\t.split(\"/\")\n\t\t\t\t.filter(Boolean);\n\t\t\tconst subRoute = segments.at(-1);\n\t\t\tlog(\"pathname:\", url.pathname, \"subRoute:\", subRoute);\n\n\t\t\tif (evalEnabled && subRoute === \"scenarios\") {\n\t\t\t\tlog(\"dispatching to scenarios handler (proxy to app API)\");\n\t\t\t\ttry {\n\t\t\t\t\tconst res = await fetch(`${apiUrl}/api/mcp/scenarios`, {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tconst data = await res.json();\n\t\t\t\t\treturn json(data.data ?? data, 200, request);\n\t\t\t\t} catch {\n\t\t\t\t\treturn json([], 200, request);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (subRoute === \"resource\") {\n\t\t\t\tlog(\"dispatching to resource handler\");\n\t\t\t\tconst response = await handleResource(url);\n\t\t\t\tlog(\"← resource handler returned\", response.status);\n\t\t\t\treturn cors(response, request);\n\t\t\t}\n\n\t\t\tif (subRoute === \"config\") {\n\t\t\t\tlog(\"dispatching to config handler\");\n\t\t\t\treturn json({ debug, eval: evalEnabled }, 200, request);\n\t\t\t}\n\n\t\t\tlog(\"← 404 no matching sub-route for\", subRoute);\n\t\t\treturn json({ error: \"Not found\" }, 404, request);\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:router] GET handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tlog(\"← 500 from caught error\");\n\t\t\treturn json({ error: message }, 500, request);\n\t\t}\n\t}\n\n\tasync function routePost(request: Request): Promise<Response> {\n\t\tlog(\"→ POST\", request.url);\n\t\ttry {\n\t\t\tconst url = new URL(request.url);\n\t\t\tconst segments = url.pathname\n\t\t\t\t.replace(/\\/$/, \"\")\n\t\t\t\t.split(\"/\")\n\t\t\t\t.filter(Boolean);\n\t\t\tconst subRoute = segments.at(-1);\n\t\t\tlog(\"pathname:\", url.pathname, \"subRoute:\", subRoute);\n\n\t\t\tif (evalEnabled && subRoute === \"scenarios\") {\n\t\t\t\tlog(\"dispatching to save-scenario handler (proxy to app API)\");\n\t\t\t\ttry {\n\t\t\t\t\tconst body = await request.json();\n\t\t\t\t\tconst res = await fetch(`${apiUrl}/api/mcp/scenarios`, {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t\t...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\t\t});\n\t\t\t\t\tconst data = await res.json();\n\t\t\t\t\tif (!res.ok) {\n\t\t\t\t\t\treturn json(\n\t\t\t\t\t\t\t{ error: data.message ?? \"Failed to save scenario\" },\n\t\t\t\t\t\t\tres.status,\n\t\t\t\t\t\t\trequest,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn json({ ok: true, scenario: data.data }, 200, request);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconst msg =\n\t\t\t\t\t\te instanceof Error ? e.message : \"Failed to save scenario\";\n\t\t\t\t\treturn json({ error: msg }, 400, request);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (subRoute === \"tool\") {\n\t\t\t\tlog(\"dispatching to tool handler\");\n\t\t\t\tconst response = await handleTool(request);\n\t\t\t\tlog(\"← tool handler returned\", response.status);\n\t\t\t\treturn cors(response, request);\n\t\t\t}\n\n\t\t\t// Default: treat as chat request\n\t\t\tlog(\"dispatching to chat handler\");\n\t\t\tconst chatResponse = await handleChat(request);\n\t\t\treturn cors(chatResponse, request);\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:router] POST handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tlog(\"← 500 from caught error\");\n\t\t\treturn json({ error: message }, 500, request);\n\t\t}\n\t}\n\n\tfunction handleOptions(request?: Request): Response {\n\t\treturn cors(new Response(null, { status: 204 }), request);\n\t}\n\n\treturn {\n\t\thandleChat,\n\t\thandleResource,\n\t\thandleTool,\n\t\trouteGet,\n\t\troutePost,\n\t\thandleOptions,\n\t};\n}\n","// WaniWani SDK - Next.js Adapter\n\nimport type { WaniWaniClient } from \"../../../types.js\";\nimport { createApiHandler } from \"../api-handler.js\";\nimport type { NextJsHandlerOptions, NextJsHandlerResult } from \"./@types.js\";\n\nexport type { NextJsHandlerOptions, NextJsHandlerResult } from \"./@types.js\";\n\n/**\n * Create Next.js route handlers from a WaniWani client.\n *\n * Returns `{ GET, POST }` for use with catch-all routes.\n * Mount at `app/api/waniwani/[[...path]]/route.ts`:\n *\n * - `POST /api/waniwani` → chat (proxied to WaniWani API)\n * - `GET /api/waniwani/resource?uri=…` → MCP resource content\n *\n * @example\n * ```typescript\n * // app/api/waniwani/[[...path]]/route.ts\n * import { waniwani } from \"@waniwani/sdk\";\n * import { toNextJsHandler } from \"@waniwani/sdk/next-js\";\n *\n * const wani = waniwani();\n *\n * export const { GET, POST } = toNextJsHandler(wani, {\n * chat: {\n * systemPrompt: \"You are a helpful assistant.\",\n * mcpServerUrl: process.env.MCP_SERVER_URL!,\n * },\n * });\n * ```\n */\nexport function toNextJsHandler(\n\tclient: WaniWaniClient,\n\toptions: NextJsHandlerOptions,\n): NextJsHandlerResult {\n\tconst { apiKey, apiUrl } = client._config;\n\n\tconst debugEnabled = options?.debug ?? process.env.WANIWANI_DEBUG === \"1\";\n\n\tconst handler = createApiHandler({\n\t\t...options?.chat,\n\t\tapiKey,\n\t\tapiUrl,\n\t\tsource: options?.source,\n\t\tallowedOrigins: options?.allowedOrigins,\n\t\tdebug: debugEnabled,\n\t});\n\n\treturn {\n\t\tPOST: handler.routePost,\n\t\tGET: handler.routeGet,\n\t\tOPTION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AAO,CACf,QAAQ,MAAM,wCAAyCA,CAAK,EAC5D,IAAMC,EACLD,aAAiB,MAAQA,EAAM,QAAU,yBAC1C,OAAAtB,EAAI,8BAAyB,EACtBI,EAAK,CAAE,MAAOmB,CAAQ,EAAG,IAAKN,CAAO,CAC7C,CACD,CAEA,SAASa,EAAcb,EAA6B,CACnD,OAAOf,EAAK,IAAI,SAAS,KAAM,CAAE,OAAQ,GAAI,CAAC,EAAGe,CAAO,CACzD,CAEA,MAAO,CACN,WAAAT,EACA,eAAAG,EACA,WAAAE,EACA,SAAAG,EACA,UAAAQ,EACA,cAAAM,CACD,CACD,CCvJO,SAASC,GACfC,EACAC,EACsB,CACtB,GAAM,CAAE,OAAAC,EAAQ,OAAAC,CAAO,EAAIH,EAAO,QAE5BI,EAAeH,GAAS,OAAS,QAAQ,IAAI,iBAAmB,IAEhEI,EAAUC,EAAiB,CAChC,GAAGL,GAAS,KACZ,OAAAC,EACA,OAAAC,EACA,OAAQF,GAAS,OACjB,eAAgBA,GAAS,eACzB,MAAOG,CACR,CAAC,EAED,MAAO,CACN,KAAMC,EAAQ,UACd,IAAKA,EAAQ,SACb,QAAUE,GAAqBF,EAAQ,cAAcE,CAAO,CAC7D,CACD","names":["createLogger","namespace","enabled","args","resolveWebSearchConfig","value","createCors","allowedOrigins","originSet","o","response","request","requestOrigin","origin","createJsonResponse","cors","data","status","WaniWaniError","message","status","extractGeoFromHeaders","request","h","rawCity","city","safeDecodeURI","country","countryRegion","latitude","longitude","timezone","ip","value","hasModelContext","value","hasContent","hasStructuredContent","formatModelContextForPrompt","value","hasModelContext","sections","renderedBlocks","block","applyModelContextToSystemPrompt","systemPrompt","modelContext","hasModelContext","widgetContext","formatModelContextForPrompt","createChatRequestHandler","deps","apiKey","apiUrl","source","systemPrompt","maxSteps","beforeRequest","mcpServerUrlOverride","resolveConfig","debug","webSearch","log","createLogger","request","body","messages","sessionId","modelContext","effectiveSystemPrompt","clientVisitorContext","geo","extractGeoFromHeaders","visitor","result","hookError","status","WaniWaniError","message","mcpServerUrl","applyModelContextToSystemPrompt","upstreamUrl","clientUserAgent","response","errorBody","headers","upstreamSessionId","error","createResourceHandler","deps","mcpServerUrlOverride","resolveConfig","debug","log","createLogger","url","uri","mcpServerUrl","createMCPClient","StreamableHTTPClientTransport","importError","mcp","result","content","html","error","message","status","WaniWaniError","createToolHandler","deps","mcpServerUrlOverride","resolveConfig","debug","source","log","createLogger","request","body","name","args","requestSessionId","mcpServerUrl","Client","StreamableHTTPClientTransport","importError","transport","client","_meta","result","error","message","status","WaniWaniError","TTL_MS","createMcpConfigResolver","apiUrl","apiKey","cached","inflight","WaniWaniError","response","body","data","DEFAULT_API_URL","createApiHandler","options","apiKey","apiUrl","source","systemPrompt","maxSteps","beforeRequest","mcpServerUrl","extraOrigins","debug","webSearch","log","createLogger","cors","createCors","json","createJsonResponse","resolveConfig","createMcpConfigResolver","handleChat","createChatRequestHandler","resolveWebSearchConfig","handleResource","createResourceHandler","handleTool","createToolHandler","evalEnabled","routeGet","request","url","subRoute","data","response","error","message","routePost","body","res","e","msg","chatResponse","handleOptions","toNextJsHandler","client","options","apiKey","apiUrl","debugEnabled","handler","createApiHandler","request"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/logger.ts","../../../src/chat/server/@types.ts","../../../src/chat/server/@utils.ts","../../../src/error.ts","../../../src/chat/server/geo.ts","../../../src/shared/model-context.ts","../../../src/chat/server/model-context.ts","../../../src/chat/server/handle-chat.ts","../../../src/chat/server/handle-resource.ts","../../../src/chat/server/handle-tool.ts","../../../src/chat/server/mcp-config-resolver.ts","../../../src/chat/server/api-handler.ts","../../../src/chat/server/next-js/index.ts"],"sourcesContent":["/**\n * Creates a namespaced logger that writes to console.log when enabled,\n * or is a no-op when disabled.\n *\n * @example\n * const log = createLogger(\"chat\", debug);\n * log(\"→ POST\", request.url); // [waniwani:chat] → POST ...\n */\nexport function createLogger(\n\tnamespace: string,\n\tenabled: boolean,\n): (...args: unknown[]) => void {\n\treturn enabled\n\t\t? (...args: unknown[]) => console.log(`[waniwani:${namespace}]`, ...args)\n\t\t: () => {};\n}\n","// WaniWani SDK - Chat Server Types\n\nimport type { UIMessage } from \"ai\";\nimport type { ModelContextUpdate } from \"../../shared/model-context\";\nimport type { GeoLocation } from \"./geo\";\n\n// ============================================================================\n// Visitor Context\n// ============================================================================\n\n/** Client-side visitor context sent in the request body */\nexport interface ClientVisitorContext {\n\ttimezone: string;\n\tlanguage: string;\n\tlanguages: string[];\n\tdeviceType: \"mobile\" | \"tablet\" | \"desktop\";\n\treferrer: string;\n\tvisitorId: string;\n}\n\n/** Combined visitor context: server geo + client context */\nexport interface VisitorMeta {\n\tgeo: GeoLocation;\n\tclient: ClientVisitorContext | null;\n}\n\n// ============================================================================\n// Before Request Hook\n// ============================================================================\n\nexport interface BeforeRequestContext {\n\t/** The conversation messages from the client */\n\tmessages: UIMessage[];\n\t/** Session identifier for conversation continuity */\n\tsessionId?: string;\n\t/** Hidden widget-provided model context for the next assistant turn */\n\tmodelContext?: ModelContextUpdate;\n\t/** The original HTTP Request object */\n\trequest: Request;\n\t/** Server-extracted geo location + client-provided visitor context */\n\tvisitor: VisitorMeta;\n}\n\nexport type BeforeRequestResult = {\n\t/** Override messages (e.g., filtered, augmented) */\n\tmessages?: UIMessage[];\n\t/** Override the system prompt for this request */\n\tsystemPrompt?: string;\n\t/** Override sessionId */\n\tsessionId?: string;\n\t/** Override hidden widget-provided model context */\n\tmodelContext?: ModelContextUpdate;\n};\n\n// ============================================================================\n// Web Search\n// ============================================================================\n\nexport interface WebSearchConfig {\n\t/** Restrict web search results to these domains */\n\tincludeDomains?: string[];\n\t/** Exclude these domains from web search results */\n\texcludeDomains?: string[];\n}\n\n// ============================================================================\n// API Handler Options\n// ============================================================================\n\nexport interface ApiHandlerOptions {\n\t/**\n\t * Identifies this chatbar instance in analytics.\n\t * Forwarded as `waniwani/source` in MCP request metadata.\n\t */\n\tsource?: string;\n\n\t/**\n\t * Your WaniWani API key.\n\t * Defaults to process.env.WANIWANI_API_KEY.\n\t */\n\tapiKey?: string;\n\n\t/**\n\t * The base URL of the WaniWani API.\n\t * Defaults to https://app.waniwani.ai.\n\t */\n\tapiUrl?: string;\n\n\t/**\n\t * System prompt for the assistant.\n\t * Can be overridden per-request via `beforeRequest`.\n\t */\n\tsystemPrompt?: string;\n\n\t/**\n\t * Maximum number of tool call steps. Defaults to 5.\n\t */\n\tmaxSteps?: number;\n\n\t/**\n\t * Hook called before each request is forwarded to the WaniWani API.\n\t * - Return void to use defaults.\n\t * - Return an object to override messages, systemPrompt, or sessionId.\n\t * - Throw to reject the request (the error message is returned as JSON).\n\t */\n\tbeforeRequest?: (\n\t\tcontext: BeforeRequestContext,\n\t) =>\n\t\t| Promise<BeforeRequestResult | undefined>\n\t\t| BeforeRequestResult\n\t\t| undefined;\n\n\t/**\n\t * Override the MCP server URL directly, bypassing config resolution.\n\t * Useful for development/testing when pointing to a local MCP server.\n\t */\n\tmcpServerUrl?: string;\n\n\t/**\n\t * Enable verbose debug logging for all handler steps.\n\t * Logs request details, response codes, resolved URLs, and caught errors.\n\t */\n\tdebug?: boolean;\n\n\t/**\n\t * Additional origins allowed for cross-origin requests.\n\t * The WaniWani platform URL (apiUrl) is always included.\n\t */\n\tallowedOrigins?: string[];\n\n\t/**\n\t * Enable web search as an additional tool alongside MCP tools.\n\t * Pass `true` to enable with defaults, or a config object to restrict domains.\n\t */\n\twebSearch?: boolean | WebSearchConfig;\n}\n\n// ============================================================================\n// API Handler Result\n// ============================================================================\n\nexport interface ApiHandler {\n\t/** Proxies chat messages to the WaniWani API */\n\thandleChat: (request: Request) => Promise<Response>;\n\t/** Serves MCP resource content (HTML widgets) */\n\thandleResource: (url: URL) => Promise<Response>;\n\t/** Calls an MCP server tool and returns JSON */\n\thandleTool: (request: Request) => Promise<Response>;\n\t/** Routes GET sub-paths (e.g. /resource) */\n\trouteGet: (request: Request) => Promise<Response>;\n\t/** Routes POST sub-paths (e.g. /tool), defaults to chat */\n\troutePost: (request: Request) => Promise<Response>;\n\t/** Handles CORS preflight requests */\n\thandleOptions: (request?: Request) => Response;\n}\n\n// ============================================================================\n// Internal Dependencies (shared across sub-handlers)\n// ============================================================================\n\ninterface McpEnvironmentConfig {\n\tmcpServerUrl: string;\n}\n\ntype ConfigResolver = () => Promise<McpEnvironmentConfig>;\n\nexport interface ApiHandlerDeps {\n\tapiKey: string | undefined;\n\tapiUrl: string;\n\tsource: string | undefined;\n\tsystemPrompt: string | undefined;\n\tmaxSteps: number;\n\tbeforeRequest: ApiHandlerOptions[\"beforeRequest\"];\n\tmcpServerUrl: string | undefined;\n\tresolveConfig: ConfigResolver;\n\tdebug: boolean;\n\twebSearch?: WebSearchConfig;\n}\n\n/** Normalize `true` to `{}` so the upstream API always receives an object or undefined */\nexport function resolveWebSearchConfig(\n\tvalue: boolean | WebSearchConfig | undefined,\n): WebSearchConfig | undefined {\n\tif (value === true) {\n\t\treturn {};\n\t}\n\tif (value === false || value === undefined) {\n\t\treturn undefined;\n\t}\n\treturn value;\n}\n\nexport interface ResourceHandlerDeps {\n\tmcpServerUrl: string | undefined;\n\tresolveConfig: ConfigResolver;\n\tdebug: boolean;\n\tsource?: string;\n}\n","// Shared helpers for chat server handlers\n\nexport type CorsFunction = (response: Response, request?: Request) => Response;\n\nfunction isLocalhostOrigin(origin: string): boolean {\n\ttry {\n\t\tconst url = new URL(origin);\n\t\treturn url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function createCors(allowedOrigins: string[]): CorsFunction {\n\tconst originSet = new Set(\n\t\tallowedOrigins.map((o) => o.replace(/\\/$/, \"\").toLowerCase()),\n\t);\n\n\treturn function applyCors(response: Response, request?: Request): Response {\n\t\tconst requestOrigin = request?.headers.get(\"origin\");\n\t\tconst origin = requestOrigin?.toLowerCase();\n\t\tconst isAllowed =\n\t\t\torigin != null &&\n\t\t\t(originSet.has(origin) ||\n\t\t\t\torigin.endsWith(\".mcp.waniwani.run\") ||\n\t\t\t\tisLocalhostOrigin(origin));\n\n\t\tif (!isAllowed) {\n\t\t\treturn response;\n\t\t}\n\n\t\tresponse.headers.set(\n\t\t\t\"Access-Control-Allow-Origin\",\n\t\t\trequestOrigin as string,\n\t\t);\n\t\tresponse.headers.set(\"Access-Control-Allow-Methods\", \"GET, POST, OPTIONS\");\n\t\tresponse.headers.set(\n\t\t\t\"Access-Control-Allow-Headers\",\n\t\t\t\"Content-Type, Authorization, X-Session-Id, X-Client-User-Agent\",\n\t\t);\n\t\tresponse.headers.set(\"Access-Control-Expose-Headers\", \"X-Session-Id\");\n\t\tresponse.headers.set(\"Vary\", \"Origin\");\n\t\treturn response;\n\t};\n}\n\nexport function createJsonResponse(cors: CorsFunction) {\n\treturn function json(\n\t\tdata: object,\n\t\tstatus: number,\n\t\trequest?: Request,\n\t): Response {\n\t\treturn cors(\n\t\t\tnew Response(JSON.stringify(data), {\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\tstatus,\n\t\t\t}),\n\t\t\trequest,\n\t\t);\n\t};\n}\n","// WaniWani SDK - Errors\n\nexport class WaniWaniError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic status: number,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"WaniWaniError\";\n\t}\n}\n","// Geo — Extract location metadata from platform request headers\n\n/**\n * Server-side geolocation extracted from platform headers (Vercel, Cloudflare).\n * All fields are optional — in local dev, no headers are present.\n */\nexport interface GeoLocation {\n\tcity?: string;\n\tcountry?: string;\n\tcountryRegion?: string;\n\tlatitude?: string;\n\tlongitude?: string;\n\ttimezone?: string;\n\tip?: string;\n}\n\n/**\n * Extracts geolocation from server-side request headers.\n *\n * Supports Vercel (`x-vercel-ip-*`), Cloudflare (`cf-ip*`, `cf-connecting-ip`),\n * and generic IP headers (`x-real-ip`, `x-forwarded-for`).\n *\n * Returns a `GeoLocation` with all fields optional (empty object in local dev).\n */\nexport function extractGeoFromHeaders(request: Request): GeoLocation {\n\tconst h = request.headers;\n\n\t// Vercel URL-encodes city names (e.g. \"S%C3%A3o%20Paulo\")\n\tconst rawCity = h.get(\"x-vercel-ip-city\") ?? h.get(\"cf-ipcity\") ?? undefined;\n\tconst city = rawCity ? safeDecodeURI(rawCity) : undefined;\n\n\tconst country =\n\t\th.get(\"x-vercel-ip-country\") ?? h.get(\"cf-ipcountry\") ?? undefined;\n\tconst countryRegion = h.get(\"x-vercel-ip-country-region\") ?? undefined;\n\tconst latitude =\n\t\th.get(\"x-vercel-ip-latitude\") ?? h.get(\"cf-iplatitude\") ?? undefined;\n\tconst longitude =\n\t\th.get(\"x-vercel-ip-longitude\") ?? h.get(\"cf-iplongitude\") ?? undefined;\n\tconst timezone =\n\t\th.get(\"x-vercel-ip-timezone\") ?? h.get(\"cf-iptimezone\") ?? undefined;\n\tconst ip =\n\t\th.get(\"x-real-ip\") ??\n\t\th.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ??\n\t\th.get(\"cf-connecting-ip\") ??\n\t\tundefined;\n\n\treturn { city, country, countryRegion, latitude, longitude, timezone, ip };\n}\n\nfunction safeDecodeURI(value: string): string {\n\ttry {\n\t\treturn decodeURIComponent(value);\n\t} catch {\n\t\treturn value;\n\t}\n}\n","import type { ContentBlock } from \"@modelcontextprotocol/sdk/types.js\";\n\nexport type ModelContextContentBlock = ContentBlock;\n\nexport type ModelContextUpdate = {\n\tcontent?: ModelContextContentBlock[];\n\tstructuredContent?: Record<string, unknown>;\n};\n\nexport function hasModelContext(\n\tvalue: ModelContextUpdate | null | undefined,\n): value is ModelContextUpdate {\n\tif (!value) {\n\t\treturn false;\n\t}\n\tconst hasContent = Array.isArray(value.content) && value.content.length > 0;\n\tconst hasStructuredContent =\n\t\ttypeof value.structuredContent === \"object\" &&\n\t\tvalue.structuredContent !== null &&\n\t\tObject.keys(value.structuredContent).length > 0;\n\treturn hasContent || hasStructuredContent;\n}\n\nexport function mergeModelContext(\n\tcurrent: ModelContextUpdate | null | undefined,\n\tnext: ModelContextUpdate | null | undefined,\n): ModelContextUpdate | null {\n\tif (!hasModelContext(current) && !hasModelContext(next)) {\n\t\treturn null;\n\t}\n\tif (!hasModelContext(current)) {\n\t\treturn {\n\t\t\t...(next?.content ? { content: [...next.content] } : {}),\n\t\t\t...(next?.structuredContent\n\t\t\t\t? { structuredContent: { ...next.structuredContent } }\n\t\t\t\t: {}),\n\t\t};\n\t}\n\tif (!hasModelContext(next)) {\n\t\treturn {\n\t\t\t...(current.content ? { content: [...current.content] } : {}),\n\t\t\t...(current.structuredContent\n\t\t\t\t? { structuredContent: { ...current.structuredContent } }\n\t\t\t\t: {}),\n\t\t};\n\t}\n\n\treturn {\n\t\t...(current.content || next.content\n\t\t\t? { content: [...(current.content ?? []), ...(next.content ?? [])] }\n\t\t\t: {}),\n\t\t...(current.structuredContent || next.structuredContent\n\t\t\t? {\n\t\t\t\t\tstructuredContent: {\n\t\t\t\t\t\t...(current.structuredContent ?? {}),\n\t\t\t\t\t\t...(next.structuredContent ?? {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\nexport function formatModelContextForPrompt(\n\tvalue: ModelContextUpdate | null | undefined,\n): string {\n\tif (!hasModelContext(value)) {\n\t\treturn \"\";\n\t}\n\n\tconst sections: string[] = [\n\t\t\"## Widget Model Context\",\n\t\t\"This hidden context was supplied by an MCP App via `ui/update-model-context`.\",\n\t\t\"Use it for the next assistant turn only. If it includes flow continuation or tool-call instructions, follow them exactly.\",\n\t];\n\n\tif (value.content?.length) {\n\t\tconst renderedBlocks = value.content\n\t\t\t.map((block) => {\n\t\t\t\tif (block.type === \"text\" && typeof block.text === \"string\") {\n\t\t\t\t\treturn block.text.trim();\n\t\t\t\t}\n\t\t\t\treturn JSON.stringify(block, null, 2);\n\t\t\t})\n\t\t\t.filter(Boolean)\n\t\t\t.join(\"\\n\\n\");\n\t\tif (renderedBlocks) {\n\t\t\tsections.push(`Content blocks:\\n${renderedBlocks}`);\n\t\t}\n\t}\n\n\tif (\n\t\tvalue.structuredContent &&\n\t\tObject.keys(value.structuredContent).length > 0\n\t) {\n\t\tsections.push(\n\t\t\t`Structured content JSON:\\n${JSON.stringify(value.structuredContent, null, 2)}`,\n\t\t);\n\t}\n\n\treturn sections.join(\"\\n\\n\");\n}\n","import {\n\tformatModelContextForPrompt,\n\thasModelContext,\n\ttype ModelContextUpdate,\n} from \"../../shared/model-context\";\n\nexport function applyModelContextToSystemPrompt(\n\tsystemPrompt: string | undefined,\n\tmodelContext: ModelContextUpdate | undefined,\n): string | undefined {\n\tif (!hasModelContext(modelContext)) {\n\t\treturn systemPrompt;\n\t}\n\n\tconst widgetContext = formatModelContextForPrompt(modelContext);\n\tif (!widgetContext) {\n\t\treturn systemPrompt;\n\t}\n\n\treturn [systemPrompt, widgetContext].filter(Boolean).join(\"\\n\\n\");\n}\n","// Handle Chat - Proxies chat requests to the WaniWani API\n\nimport { WaniWaniError } from \"../../error\";\nimport { createLogger } from \"../../utils/logger.js\";\nimport type {\n\tApiHandlerDeps,\n\tClientVisitorContext,\n\tVisitorMeta,\n} from \"./@types\";\nimport { extractGeoFromHeaders } from \"./geo\";\nimport { applyModelContextToSystemPrompt } from \"./model-context\";\n\nexport function createChatRequestHandler(deps: ApiHandlerDeps) {\n\tconst {\n\t\tapiKey,\n\t\tapiUrl,\n\t\tsource,\n\t\tsystemPrompt,\n\t\tmaxSteps,\n\t\tbeforeRequest,\n\t\tmcpServerUrl: mcpServerUrlOverride,\n\t\tresolveConfig,\n\t\tdebug,\n\t\twebSearch,\n\t} = deps;\n\n\tconst log = createLogger(\"chat\", debug);\n\n\treturn async function handleChat(request: Request): Promise<Response> {\n\t\tlog(\"→ POST\", request.url);\n\t\ttry {\n\t\t\t// 1. Parse request body\n\t\t\tconst body = await request.json();\n\t\t\tlet messages = body.messages ?? [];\n\t\t\tlet sessionId: string | undefined = body.sessionId;\n\t\t\tlet modelContext = body.modelContext;\n\t\t\tlet effectiveSystemPrompt = systemPrompt;\n\n\t\t\t// Extract visitor context (client-side + server-side geo)\n\t\t\tconst clientVisitorContext: ClientVisitorContext | null =\n\t\t\t\tbody.visitorContext ?? null;\n\t\t\tconst geo = extractGeoFromHeaders(request);\n\t\t\tconst visitor: VisitorMeta = { geo, client: clientVisitorContext };\n\n\t\t\tlog(\n\t\t\t\t\"body parsed — messages:\",\n\t\t\t\tmessages.length,\n\t\t\t\t\"sessionId:\",\n\t\t\t\tsessionId ?? \"(none)\",\n\t\t\t\t\"geo:\",\n\t\t\t\tJSON.stringify(geo),\n\t\t\t);\n\n\t\t\t// 2. Run beforeRequest hook\n\t\t\tif (beforeRequest) {\n\t\t\t\tlog(\"running beforeRequest hook\");\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await beforeRequest({\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tmodelContext,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\tvisitor,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (result) {\n\t\t\t\t\t\tif (result.messages) {\n\t\t\t\t\t\t\tmessages = result.messages;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.systemPrompt !== undefined) {\n\t\t\t\t\t\t\teffectiveSystemPrompt = result.systemPrompt;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.sessionId !== undefined) {\n\t\t\t\t\t\t\tsessionId = result.sessionId;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.modelContext !== undefined) {\n\t\t\t\t\t\t\tmodelContext = result.modelContext;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlog(\n\t\t\t\t\t\t\"beforeRequest hook done — messages:\",\n\t\t\t\t\t\tmessages.length,\n\t\t\t\t\t\t\"sessionId:\",\n\t\t\t\t\t\tsessionId ?? \"(none)\",\n\t\t\t\t\t);\n\t\t\t\t} catch (hookError) {\n\t\t\t\t\tconsole.error(\"[waniwani:chat] beforeRequest hook error:\", hookError);\n\t\t\t\t\tconst status =\n\t\t\t\t\t\thookError instanceof WaniWaniError ? hookError.status : 400;\n\t\t\t\t\tconst message =\n\t\t\t\t\t\thookError instanceof Error ? hookError.message : \"Request rejected\";\n\t\t\t\t\tlog(\"← returning\", status, \"from hook error\");\n\t\t\t\t\treturn Response.json({ error: message }, { status });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// 3. Resolve MCP server URL\n\t\t\tconst mcpServerUrl =\n\t\t\t\tmcpServerUrlOverride ?? (await resolveConfig()).mcpServerUrl;\n\t\t\tlog(\"mcpServerUrl:\", mcpServerUrl);\n\t\t\teffectiveSystemPrompt = applyModelContextToSystemPrompt(\n\t\t\t\teffectiveSystemPrompt,\n\t\t\t\tmodelContext,\n\t\t\t);\n\n\t\t\t// 4. Forward to WaniWani API\n\t\t\tconst upstreamUrl = `${apiUrl}/api/mcp/chat`;\n\t\t\tlog(\"forwarding to\", upstreamUrl);\n\t\t\tconst clientUserAgent = request.headers.get(\"user-agent\");\n\n\t\t\tconst response = await fetch(upstreamUrl, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n\t\t\t\t\t...(clientUserAgent\n\t\t\t\t\t\t? { \"X-Client-User-Agent\": clientUserAgent }\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmessages,\n\t\t\t\t\tmcpServerUrl,\n\t\t\t\t\tsessionId,\n\t\t\t\t\tsource,\n\t\t\t\t\tsystemPrompt: effectiveSystemPrompt,\n\t\t\t\t\tmaxSteps,\n\t\t\t\t\tvisitor,\n\t\t\t\t\twebSearch,\n\t\t\t\t}),\n\t\t\t\tsignal: request.signal,\n\t\t\t});\n\n\t\t\tlog(\"upstream response status:\", response.status);\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst errorBody = await response.text().catch(() => \"\");\n\t\t\t\tlog(\"← returning\", response.status, \"upstream error:\", errorBody);\n\t\t\t\treturn new Response(errorBody, {\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\":\n\t\t\t\t\t\t\tresponse.headers.get(\"Content-Type\") ?? \"application/json\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// 5. Stream the response back\n\t\t\tconst headers = new Headers({\n\t\t\t\t\"Content-Type\":\n\t\t\t\t\tresponse.headers.get(\"Content-Type\") ?? \"text/event-stream\",\n\t\t\t});\n\t\t\tconst upstreamSessionId = response.headers.get(\"x-session-id\");\n\t\t\tif (upstreamSessionId) {\n\t\t\t\theaders.set(\"x-session-id\", upstreamSessionId);\n\t\t\t}\n\n\t\t\tlog(\n\t\t\t\t\"← streaming response\",\n\t\t\t\tresponse.status,\n\t\t\t\t\"body null?\",\n\t\t\t\tresponse.body === null,\n\t\t\t);\n\t\t\treturn new Response(response.body, {\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:chat] handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tconst status = error instanceof WaniWaniError ? error.status : 500;\n\t\t\tlog(\"← returning\", status, \"from caught error\");\n\t\t\treturn Response.json({ error: message }, { status });\n\t\t}\n\t};\n}\n","// Handle Resource - Serves MCP resource content (HTML widgets)\n\nimport { WaniWaniError } from \"../../error\";\nimport { createLogger } from \"../../utils/logger.js\";\nimport type { ResourceHandlerDeps } from \"./@types\";\n\nexport function createResourceHandler(deps: ResourceHandlerDeps) {\n\tconst { mcpServerUrl: mcpServerUrlOverride, resolveConfig, debug } = deps;\n\n\tconst log = createLogger(\"resource\", debug);\n\n\treturn async function handleResource(url: URL): Promise<Response> {\n\t\tlog(\"→ GET\", url.toString());\n\t\ttry {\n\t\t\tconst uri = url.searchParams.get(\"uri\");\n\t\t\tlog(\"uri:\", uri ?? \"(missing)\");\n\n\t\t\tif (!uri) {\n\t\t\t\tlog(\"← 400 missing uri\");\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{ error: \"Missing uri query parameter\" },\n\t\t\t\t\t{ status: 400 },\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst mcpServerUrl =\n\t\t\t\tmcpServerUrlOverride ?? (await resolveConfig()).mcpServerUrl;\n\t\t\tlog(\"mcpServerUrl:\", mcpServerUrl);\n\n\t\t\t// Dynamic imports — these are optional peer dependencies\n\t\t\tlet createMCPClient: typeof import(\"@ai-sdk/mcp\")[\"createMCPClient\"];\n\t\t\tlet StreamableHTTPClientTransport: typeof import(\"@modelcontextprotocol/sdk/client/streamableHttp.js\")[\"StreamableHTTPClientTransport\"];\n\n\t\t\ttry {\n\t\t\t\t[{ createMCPClient }, { StreamableHTTPClientTransport }] =\n\t\t\t\t\tawait Promise.all([\n\t\t\t\t\t\timport(\"@ai-sdk/mcp\"),\n\t\t\t\t\t\timport(\"@modelcontextprotocol/sdk/client/streamableHttp.js\"),\n\t\t\t\t\t]);\n\t\t\t\tlog(\"MCP deps loaded\");\n\t\t\t} catch (importError) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t\"[waniwani:resource] MCP deps import failed:\",\n\t\t\t\t\timportError,\n\t\t\t\t);\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\t\"MCP resource handler requires @ai-sdk/mcp and @modelcontextprotocol/sdk. Install them to enable resource serving.\",\n\t\t\t\t\t},\n\t\t\t\t\t{ status: 501 },\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlog(\"creating MCP client for\", mcpServerUrl);\n\t\t\tconst mcp = await createMCPClient({\n\t\t\t\ttransport: new StreamableHTTPClientTransport(new URL(mcpServerUrl)),\n\t\t\t});\n\n\t\t\ttry {\n\t\t\t\tlog(\"reading resource:\", uri);\n\t\t\t\tconst result = await mcp.readResource({ uri });\n\t\t\t\tlog(\"resource contents count:\", result.contents.length);\n\n\t\t\t\tconst content = result.contents[0];\n\t\t\t\tif (!content) {\n\t\t\t\t\tlog(\"← 404 resource not found\");\n\t\t\t\t\treturn Response.json(\n\t\t\t\t\t\t{ error: \"Resource not found\" },\n\t\t\t\t\t\t{ status: 404 },\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tlet html: string | undefined;\n\t\t\t\tif (\"text\" in content && typeof content.text === \"string\") {\n\t\t\t\t\thtml = content.text;\n\t\t\t\t} else if (\"blob\" in content && typeof content.blob === \"string\") {\n\t\t\t\t\thtml = atob(content.blob);\n\t\t\t\t}\n\n\t\t\t\tif (!html) {\n\t\t\t\t\tlog(\"← 404 resource has no content, keys:\", Object.keys(content));\n\t\t\t\t\treturn Response.json(\n\t\t\t\t\t\t{ error: \"Resource has no content\" },\n\t\t\t\t\t\t{ status: 404 },\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tlog(\"← 200 HTML length:\", html.length);\n\t\t\t\treturn new Response(html, {\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": \"text/html\",\n\t\t\t\t\t\t\"Cache-Control\": \"private, max-age=300\",\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tawait mcp.close();\n\t\t\t\tlog(\"MCP client closed\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:resource] handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tconst status = error instanceof WaniWaniError ? error.status : 500;\n\t\t\tlog(\"← returning\", status, \"from caught error\");\n\t\t\treturn Response.json({ error: message }, { status });\n\t\t}\n\t};\n}\n","// Handle Tool - Calls MCP server tools directly and returns JSON results\n\nimport { WaniWaniError } from \"../../error\";\nimport { createLogger } from \"../../utils/logger.js\";\nimport type { ResourceHandlerDeps } from \"./@types\";\n\nexport function createToolHandler(deps: ResourceHandlerDeps) {\n\tconst {\n\t\tmcpServerUrl: mcpServerUrlOverride,\n\t\tresolveConfig,\n\t\tdebug,\n\t\tsource,\n\t} = deps;\n\n\tconst log = createLogger(\"tool\", debug);\n\n\treturn async function handleTool(request: Request): Promise<Response> {\n\t\tlog(\"→ POST\", request.url);\n\t\ttry {\n\t\t\tconst body = await request.json();\n\t\t\tconst { name, arguments: args } = body as {\n\t\t\t\tname: string;\n\t\t\t\targuments: Record<string, unknown>;\n\t\t\t};\n\t\t\tconst requestSessionId = request.headers.get(\"x-session-id\")?.trim();\n\n\t\t\tif (!name || typeof name !== \"string\") {\n\t\t\t\tlog(\"← 400 missing tool name\");\n\t\t\t\treturn Response.json({ error: \"Missing tool name\" }, { status: 400 });\n\t\t\t}\n\n\t\t\tlog(\n\t\t\t\t\"tool:\",\n\t\t\t\tname,\n\t\t\t\t\"args:\",\n\t\t\t\tJSON.stringify(args),\n\t\t\t\t\"sessionId:\",\n\t\t\t\trequestSessionId || \"(none)\",\n\t\t\t);\n\n\t\t\tconst mcpServerUrl =\n\t\t\t\tmcpServerUrlOverride ?? (await resolveConfig()).mcpServerUrl;\n\t\t\tlog(\"mcpServerUrl:\", mcpServerUrl);\n\n\t\t\t// Dynamic imports — these are optional peer dependencies\n\t\t\tlet Client: typeof import(\"@modelcontextprotocol/sdk/client/index.js\")[\"Client\"];\n\t\t\tlet StreamableHTTPClientTransport: typeof import(\"@modelcontextprotocol/sdk/client/streamableHttp.js\")[\"StreamableHTTPClientTransport\"];\n\n\t\t\ttry {\n\t\t\t\t[{ Client }, { StreamableHTTPClientTransport }] = await Promise.all([\n\t\t\t\t\timport(\"@modelcontextprotocol/sdk/client/index.js\"),\n\t\t\t\t\timport(\"@modelcontextprotocol/sdk/client/streamableHttp.js\"),\n\t\t\t\t]);\n\t\t\t\tlog(\"MCP deps loaded\");\n\t\t\t} catch (importError) {\n\t\t\t\tconsole.error(\"[waniwani:tool] MCP deps import failed:\", importError);\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\t\"MCP tool handler requires @modelcontextprotocol/sdk. Install it to enable tool calls.\",\n\t\t\t\t\t},\n\t\t\t\t\t{ status: 501 },\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlog(\"creating MCP client for\", mcpServerUrl);\n\t\t\tconst transport = new StreamableHTTPClientTransport(\n\t\t\t\tnew URL(mcpServerUrl),\n\t\t\t);\n\t\t\tconst client = new Client({\n\t\t\t\tname: \"waniwani-tool-caller\",\n\t\t\t\tversion: \"1.0.0\",\n\t\t\t});\n\t\t\tawait client.connect(transport);\n\n\t\t\ttry {\n\t\t\t\tlog(\"calling tool:\", name);\n\t\t\t\tconst _meta: Record<string, unknown> = {};\n\t\t\t\tif (requestSessionId) {\n\t\t\t\t\t_meta[\"waniwani/sessionId\"] = requestSessionId;\n\t\t\t\t}\n\t\t\t\tif (source) {\n\t\t\t\t\t_meta[\"waniwani/source\"] = source;\n\t\t\t\t}\n\t\t\t\tconst result = await client.callTool({\n\t\t\t\t\tname,\n\t\t\t\t\targuments: args ?? {},\n\t\t\t\t\t...(Object.keys(_meta).length > 0 ? { _meta } : {}),\n\t\t\t\t} as {\n\t\t\t\t\tname: string;\n\t\t\t\t\targuments: Record<string, unknown>;\n\t\t\t\t\t_meta?: Record<string, unknown>;\n\t\t\t\t});\n\t\t\t\tlog(\"tool result received\");\n\n\t\t\t\treturn Response.json({\n\t\t\t\t\tcontent: result.content,\n\t\t\t\t\tstructuredContent: result.structuredContent,\n\t\t\t\t\t_meta: result._meta,\n\t\t\t\t\tisError: result.isError,\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tawait client.close();\n\t\t\t\tlog(\"MCP client closed\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:tool] handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tconst status = error instanceof WaniWaniError ? error.status : 500;\n\t\t\tlog(\"← returning\", status, \"from caught error\");\n\t\t\treturn Response.json({ error: message }, { status });\n\t\t}\n\t};\n}\n","// MCP Config Resolver - Lazy-loads and caches MCP environment config\n\nimport { WaniWaniError } from \"../../error\";\n\ninterface McpEnvironmentConfig {\n\tmcpServerUrl: string;\n}\n\nconst TTL_MS = 5 * 60 * 1000; // 5 minutes\n\nexport function createMcpConfigResolver(\n\tapiUrl: string,\n\tapiKey: string | undefined,\n) {\n\tlet cached: { config: McpEnvironmentConfig; expiresAt: number } | null = null;\n\tlet inflight: Promise<McpEnvironmentConfig> | null = null;\n\n\treturn async function resolve(): Promise<McpEnvironmentConfig> {\n\t\tif (cached && Date.now() < cached.expiresAt) {\n\t\t\treturn cached.config;\n\t\t}\n\n\t\t// Deduplicate concurrent requests (cold start scenario)\n\t\tif (inflight) {\n\t\t\treturn inflight;\n\t\t}\n\n\t\tinflight = (async () => {\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new WaniWaniError(\n\t\t\t\t\t\"WANIWANI_API_KEY is required for createChatHandler\",\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst response = await fetch(`${apiUrl}/api/mcp/environments/config`, {\n\t\t\t\tmethod: \"GET\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${apiKey}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst body = await response.text().catch(() => \"\");\n\t\t\t\tthrow new WaniWaniError(\n\t\t\t\t\t`Failed to resolve MCP environment config: ${response.status} ${body}`,\n\t\t\t\t\tresponse.status,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst data = (await response.json()) as McpEnvironmentConfig;\n\t\t\tcached = { config: data, expiresAt: Date.now() + TTL_MS };\n\t\t\treturn data;\n\t\t})();\n\n\t\ttry {\n\t\t\treturn await inflight;\n\t\t} finally {\n\t\t\tinflight = null;\n\t\t}\n\t};\n}\n","// API Handler - Composes chat and resource handlers into a unified API handler\n\nimport { createLogger } from \"../../utils/logger.js\";\nimport {\n\ttype ApiHandler,\n\ttype ApiHandlerOptions,\n\tresolveWebSearchConfig,\n} from \"./@types\";\nimport { createCors, createJsonResponse } from \"./@utils\";\nimport { createChatRequestHandler } from \"./handle-chat\";\nimport { createResourceHandler } from \"./handle-resource\";\nimport { createToolHandler } from \"./handle-tool\";\nimport { createMcpConfigResolver } from \"./mcp-config-resolver\";\n\nconst DEFAULT_API_URL = \"https://app.waniwani.ai\";\n\nexport function createApiHandler(options: ApiHandlerOptions = {}): ApiHandler {\n\tconst {\n\t\tapiKey = process.env.WANIWANI_API_KEY,\n\t\tapiUrl = DEFAULT_API_URL,\n\t\tsource,\n\t\tsystemPrompt,\n\t\tmaxSteps = 5,\n\t\tbeforeRequest,\n\t\tmcpServerUrl,\n\t\tallowedOrigins: extraOrigins,\n\t\tdebug = false,\n\t\twebSearch,\n\t} = options;\n\n\tconst log = createLogger(\"router\", debug);\n\tconst cors = createCors([apiUrl, ...(extraOrigins ?? [])]);\n\tconst json = createJsonResponse(cors);\n\n\tconst resolveConfig = createMcpConfigResolver(apiUrl, apiKey);\n\n\tconst handleChat = createChatRequestHandler({\n\t\tapiKey,\n\t\tapiUrl,\n\t\tsource,\n\t\tsystemPrompt,\n\t\tmaxSteps,\n\t\tbeforeRequest,\n\t\tmcpServerUrl,\n\t\tresolveConfig,\n\t\tdebug,\n\t\twebSearch: resolveWebSearchConfig(webSearch),\n\t});\n\n\tconst handleResource = createResourceHandler({\n\t\tmcpServerUrl,\n\t\tresolveConfig,\n\t\tdebug,\n\t});\n\n\tconst handleTool = createToolHandler({\n\t\tmcpServerUrl,\n\t\tresolveConfig,\n\t\tdebug,\n\t\tsource,\n\t});\n\n\tconst evalEnabled = process.env.WANIWANI_EVAL === \"1\";\n\n\tasync function routeGet(request: Request): Promise<Response> {\n\t\tlog(\"→ GET\", request.url);\n\t\ttry {\n\t\t\tconst url = new URL(request.url);\n\t\t\tconst segments = url.pathname\n\t\t\t\t.replace(/\\/$/, \"\")\n\t\t\t\t.split(\"/\")\n\t\t\t\t.filter(Boolean);\n\t\t\tconst subRoute = segments.at(-1);\n\t\t\tlog(\"pathname:\", url.pathname, \"subRoute:\", subRoute);\n\n\t\t\tif (evalEnabled && subRoute === \"scenarios\") {\n\t\t\t\tlog(\"dispatching to scenarios handler (proxy to app API)\");\n\t\t\t\ttry {\n\t\t\t\t\tconst res = await fetch(`${apiUrl}/api/mcp/scenarios`, {\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tconst data = await res.json();\n\t\t\t\t\treturn json(data.data ?? data, 200, request);\n\t\t\t\t} catch {\n\t\t\t\t\treturn json([], 200, request);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (subRoute === \"resource\") {\n\t\t\t\tlog(\"dispatching to resource handler\");\n\t\t\t\tconst response = await handleResource(url);\n\t\t\t\tlog(\"← resource handler returned\", response.status);\n\t\t\t\treturn cors(response, request);\n\t\t\t}\n\n\t\t\tif (subRoute === \"config\") {\n\t\t\t\tlog(\"dispatching to config handler\");\n\t\t\t\treturn json({ debug, eval: evalEnabled }, 200, request);\n\t\t\t}\n\n\t\t\tlog(\"← 404 no matching sub-route for\", subRoute);\n\t\t\treturn json({ error: \"Not found\" }, 404, request);\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:router] GET handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tlog(\"← 500 from caught error\");\n\t\t\treturn json({ error: message }, 500, request);\n\t\t}\n\t}\n\n\tasync function routePost(request: Request): Promise<Response> {\n\t\tlog(\"→ POST\", request.url);\n\t\ttry {\n\t\t\tconst url = new URL(request.url);\n\t\t\tconst segments = url.pathname\n\t\t\t\t.replace(/\\/$/, \"\")\n\t\t\t\t.split(\"/\")\n\t\t\t\t.filter(Boolean);\n\t\t\tconst subRoute = segments.at(-1);\n\t\t\tlog(\"pathname:\", url.pathname, \"subRoute:\", subRoute);\n\n\t\t\tif (evalEnabled && subRoute === \"scenarios\") {\n\t\t\t\tlog(\"dispatching to save-scenario handler (proxy to app API)\");\n\t\t\t\ttry {\n\t\t\t\t\tconst body = await request.json();\n\t\t\t\t\tconst res = await fetch(`${apiUrl}/api/mcp/scenarios`, {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: {\n\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t\t...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\t\t});\n\t\t\t\t\tconst data = await res.json();\n\t\t\t\t\tif (!res.ok) {\n\t\t\t\t\t\treturn json(\n\t\t\t\t\t\t\t{ error: data.message ?? \"Failed to save scenario\" },\n\t\t\t\t\t\t\tres.status,\n\t\t\t\t\t\t\trequest,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn json({ ok: true, scenario: data.data }, 200, request);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconst msg =\n\t\t\t\t\t\te instanceof Error ? e.message : \"Failed to save scenario\";\n\t\t\t\t\treturn json({ error: msg }, 400, request);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (subRoute === \"tool\") {\n\t\t\t\tlog(\"dispatching to tool handler\");\n\t\t\t\tconst response = await handleTool(request);\n\t\t\t\tlog(\"← tool handler returned\", response.status);\n\t\t\t\treturn cors(response, request);\n\t\t\t}\n\n\t\t\t// Default: treat as chat request\n\t\t\tlog(\"dispatching to chat handler\");\n\t\t\tconst chatResponse = await handleChat(request);\n\t\t\treturn cors(chatResponse, request);\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[waniwani:router] POST handler error:\", error);\n\t\t\tconst message =\n\t\t\t\terror instanceof Error ? error.message : \"Unknown error occurred\";\n\t\t\tlog(\"← 500 from caught error\");\n\t\t\treturn json({ error: message }, 500, request);\n\t\t}\n\t}\n\n\tfunction handleOptions(request?: Request): Response {\n\t\treturn cors(new Response(null, { status: 204 }), request);\n\t}\n\n\treturn {\n\t\thandleChat,\n\t\thandleResource,\n\t\thandleTool,\n\t\trouteGet,\n\t\troutePost,\n\t\thandleOptions,\n\t};\n}\n","// WaniWani SDK - Next.js Adapter\n\nimport type { WaniWaniClient } from \"../../../types.js\";\nimport { createApiHandler } from \"../api-handler.js\";\nimport type { NextJsHandlerOptions, NextJsHandlerResult } from \"./@types.js\";\n\nexport type { NextJsHandlerOptions, NextJsHandlerResult } from \"./@types.js\";\n\n/**\n * Create Next.js route handlers from a WaniWani client.\n *\n * Returns `{ GET, POST }` for use with catch-all routes.\n * Mount at `app/api/waniwani/[[...path]]/route.ts`:\n *\n * - `POST /api/waniwani` → chat (proxied to WaniWani API)\n * - `GET /api/waniwani/resource?uri=…` → MCP resource content\n *\n * @example\n * ```typescript\n * // app/api/waniwani/[[...path]]/route.ts\n * import { waniwani } from \"@waniwani/sdk\";\n * import { toNextJsHandler } from \"@waniwani/sdk/next-js\";\n *\n * const wani = waniwani();\n *\n * export const { GET, POST } = toNextJsHandler(wani, {\n * chat: {\n * systemPrompt: \"You are a helpful assistant.\",\n * mcpServerUrl: process.env.MCP_SERVER_URL!,\n * },\n * });\n * ```\n */\nexport function toNextJsHandler(\n\tclient: WaniWaniClient,\n\toptions: NextJsHandlerOptions,\n): NextJsHandlerResult {\n\tconst { apiKey, apiUrl } = client._config;\n\n\tconst debugEnabled = options?.debug ?? process.env.WANIWANI_DEBUG === \"1\";\n\n\tconst handler = createApiHandler({\n\t\t...options?.chat,\n\t\tapiKey,\n\t\tapiUrl,\n\t\tsource: options?.source,\n\t\tallowedOrigins: options?.allowedOrigins,\n\t\tdebug: debugEnabled,\n\t});\n\n\treturn {\n\t\tPOST: hand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W,MAAMR,EAAWI,CAAO,EACzC,OAAAjB,EAAI,+BAA2BqB,EAAS,MAAM,EACvCnB,EAAKmB,EAAUJ,CAAO,CAC9B,CAGAjB,EAAI,6BAA6B,EACjC,IAAM6B,EAAe,MAAMrB,EAAWS,CAAO,EAC7C,OAAOf,EAAK2B,EAAcZ,CAAO,CAClC,OAASK,EAAO,CACf,QAAQ,MAAM,wCAAyCA,CAAK,EAC5D,IAAMC,EACLD,aAAiB,MAAQA,EAAM,QAAU,yBAC1C,OAAAtB,EAAI,8BAAyB,EACtBI,EAAK,CAAE,MAAOmB,CAAQ,EAAG,IAAKN,CAAO,CAC7C,CACD,CAEA,SAASa,EAAcb,EAA6B,CACnD,OAAOf,EAAK,IAAI,SAAS,KAAM,CAAE,OAAQ,GAAI,CAAC,EAAGe,CAAO,CACzD,CAEA,MAAO,CACN,WAAAT,EACA,eAAAG,EACA,WAAAE,EACA,SAAAG,EACA,UAAAQ,EACA,cAAAM,CACD,CACD,CCvJO,SAASC,GACfC,EACAC,EACsB,CACtB,GAAM,CAAE,OAAAC,EAAQ,OAAAC,CAAO,EAAIH,EAAO,QAE5BI,EAAeH,GAAS,OAAS,QAAQ,IAAI,iBAAmB,IAEhEI,EAAUC,EAAiB,CAChC,GAAGL,GAAS,KACZ,OAAAC,EACA,OAAAC,EACA,OAAQF,GAAS,OACjB,eAAgBA,GAAS,eACzB,MAAOG,CACR,CAAC,EAED,MAAO,CACN,KAAMC,EAAQ,UACd,IAAKA,EAAQ,SACb,QAAUE,GAAqBF,EAAQ,cAAcE,CAAO,CAC7D,CACD","names":["createLogger","namespace","enabled","args","resolveWebSearchConfig","value","isLocalhostOrigin","origin","url","createCors","allowedOrigins","originSet","o","response","request","requestOrigin","createJsonResponse","cors","data","status","WaniWaniError","message","status","extractGeoFromHeaders","request","h","rawCity","city","safeDecodeURI","country","countryRegion","latitude","longitude","timezone","ip","value","hasModelContext","value","hasContent","hasStructuredContent","formatModelContextForPrompt","value","hasModelContext","sections","renderedBlocks","block","applyModelContextToSystemPrompt","systemPrompt","modelContext","hasModelContext","widgetContext","formatModelContextForPrompt","createChatRequestHandler","deps","apiKey","apiUrl","source","systemPrompt","maxSteps","beforeRequest","mcpServerUrlOverride","resolveConfig","debug","webSearch","log","createLogger","request","body","messages","sessionId","modelContext","effectiveSystemPrompt","clientVisitorContext","geo","extractGeoFromHeaders","visitor","result","hookError","status","WaniWaniError","message","mcpServerUrl","applyModelContextToSystemPrompt","upstreamUrl","clientUserAgent","response","errorBody","headers","upstreamSessionId","error","createResourceHandler","deps","mcpServerUrlOverride","resolveConfig","debug","log","createLogger","url","uri","mcpServerUrl","createMCPClient","StreamableHTTPClientTransport","importError","mcp","result","content","html","error","message","status","WaniWaniError","createToolHandler","deps","mcpServerUrlOverride","resolveConfig","debug","source","log","createLogger","request","body","name","args","requestSessionId","mcpServerUrl","Client","StreamableHTTPClientTransport","importError","transport","client","_meta","result","error","message","status","WaniWaniError","TTL_MS","createMcpConfigResolver","apiUrl","apiKey","cached","inflight","WaniWaniError","response","body","data","DEFAULT_API_URL","createApiHandler","options","apiKey","apiUrl","source","systemPrompt","maxSteps","beforeRequest","mcpServerUrl","extraOrigins","debug","webSearch","log","createLogger","cors","createCors","json","createJsonResponse","resolveConfig","createMcpConfigResolver","handleChat","createChatRequestHandler","resolveWebSearchConfig","handleResource","createResourceHandler","handleTool","createToolHandler","evalEnabled","routeGet","request","url","subRoute","data","response","error","message","routePost","body","res","e","msg","chatResponse","handleOptions","toNextJsHandler","client","options","apiKey","apiUrl","debugEnabled","handler","createApiHandler","request"]}
|
package/dist/mcp/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
function
|
|
1
|
+
function ne(){return typeof window<"u"&&"openai"in window?"openai":"mcp-apps"}function it(){return ne()==="openai"}function st(){return ne()==="mcp-apps"}var C="__start__",b="__end__",Se=Symbol.for("waniwani.flow.interrupt"),ve=Symbol.for("waniwani.flow.widget");function Re(e,t){let n=t?.context,r=[];for(let[o,i]of Object.entries(e))if(typeof i=="object"&&i!==null&&"question"in i){let a=i;r.push({question:a.question,field:o,suggestions:a.suggestions,context:a.context,validate:a.validate})}return{__type:Se,questions:r,context:n}}function xe(e,t){return{__type:ve,tool:e,...t}}function Ee(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===Se}function Ie(e){return typeof e=="object"&&e!==null&&"__type"in e&&e.__type===ve}import{z as O}from"zod";var re="waniwani/client";function H(e){if(typeof e=="object"&&e!==null)return e[re]}function Ce(e,t,n){return{track(r){return e.track({...r,meta:{...t,...r.meta}})},identify(r,o){return e.identify(r,o,t)},kb:e.kb,_config:n}}function N(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}var at=["waniwani/sessionId","openai/sessionId","openai/session","sessionId","conversationId","anthropic/sessionId"],ct=["waniwani/requestId","openai/requestId","requestId","mcp/requestId"],dt=["waniwani/traceId","openai/traceId","traceId","mcp/traceId","openai/requestId","requestId"],ut=["waniwani/userId","openai/userId","externalUserId","userId","actorId"],lt=["correlationId","openai/requestId"];function P(e){return e?N(e,at):void 0}function be(e){return e?N(e,ct):void 0}function _e(e){return e?N(e,dt):void 0}function Pe(e){return e?N(e,ut):void 0}function We(e){return e?N(e,lt):void 0}var pt=[{key:"waniwani/sessionId",source:"chatbar"},{key:"openai/sessionId",source:"chatgpt"},{key:"openai/session",source:"chatgpt"},{key:"anthropic/sessionId",source:"claude"}];function U(e){if(!e)return;let t=e["waniwani/source"];if(typeof t=="string"&&t.length>0)return t;for(let{key:n,source:r}of pt){let o=e[n];if(typeof o=="string"&&o.length>0)return r}}function Me(e){let t=e._zod?.def;return t?.type==="object"&&t.shape?t.shape:null}function D(e,t){let n=t.split("."),r=e;for(let o of n){if(r==null||typeof r!="object")return;r=r[o]}return r}function ft(e,t,n){let r=t.split("."),o=r.pop();if(!o)return;let i=e;for(let a of r)(i[a]==null||typeof i[a]!="object"||Array.isArray(i[a]))&&(i[a]={}),i=i[a];i[o]=n}function Fe(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 oe(e){let t={};for(let[n,r]of Object.entries(e))n.includes(".")?ft(t,n,r):t[n]=r;return t}function W(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]=W(n[r],o):n[r]=o;return n}function ie(e){return e!=null&&e!==""}async function M(e,t){return e.type==="direct"?e.to:e.condition(t)}function Ae(e,t,n,r){if(e.every(c=>ie(D(r,c.field))))return null;let o=e.filter(c=>!ie(D(r,c.field))),i=o.length===1,a=o[0];return{content:i&&a?{status:"interrupt",question:a.question,field:a.field,...a.suggestions?{suggestions:a.suggestions}:{},...a.context||t?{context:a.context??t}:{}}:{status:"interrupt",questions:o,...t?{context:t}:{}},flowTokenContent:{step:n,state:r,...i&&a?{field:a.field}:{}}}}async function L(e,t,n,r,o,i,a){let s=e,c={...t},u=50,l=0;for(;l++<u;){if(s===b)return{content:{status:"complete"},flowTokenContent:{state:c}};let d=n.get(s);if(!d)return{content:{status:"error",error:`Unknown node: "${s}"`}};try{let p=await d({state:c,meta:i,interrupt:Re,showWidget:xe,waniwani:a});if(Ee(p)){for(let T of p.questions)T.validate&&o.set(`${s}:${T.field}`,T.validate);let y=Ae(p.questions,p.context,s,c);if(y)return y;for(let T of p.questions){let R=o.get(`${s}:${T.field}`);if(R)try{let v=D(c,T.field),S=await R(v);S&&typeof S=="object"&&(c=W(c,S))}catch(v){let S=v instanceof Error?v.message:String(v);Fe(c,T.field);let E=p.questions.map(_=>_.field===T.field?{..._,context:_.context?`ERROR: ${S}
|
|
2
2
|
|
|
3
|
-
${
|
|
4
|
-
`)}var
|
|
5
|
-
${o}`,a=e.store??new
|
|
6
|
-
`)}var A=class{nodes=new Map;edges=new Map;config;constructor(t){this.config=t}addNode(t,n){if(t===C||t===b)throw new Error(`"${t}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(t))throw new Error(`Node "${t}" already exists`);return this.nodes.set(t,n),this}addEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge. Use addConditionalEdge for branching.`);return this.edges.set(t,{type:"direct",to:n}),this}addConditionalEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge.`);return this.edges.set(t,{type:"conditional",condition:n}),this}graph(){return Me(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return We({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>Me(n,r)})}validate(){if(!this.edges.has(C))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(C);if(t?.type==="direct"&&t.to!==b&&!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!==C&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(r.type==="direct"&&r.to!==b&&!this.nodes.has(r.to))throw new Error(`Edge from "${n}" references non-existent node: "${r.to}"`)}for(let[n]of this.nodes)if(!this.edges.has(n))throw new Error(`Node "${n}" has no outgoing edge. Add one with .addEdge("${n}", ...) or .addConditionalEdge("${n}", ...)`)}};function Fe(e){return new A(e)}function Ae(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function Ne(e,t){let n=t?.stateStore,r=[],o=`test-session-${Math.random().toString(36).slice(2,10)}`,s={registerTool:(...d)=>{r.push(d)}};await e.register(s);let a=r[0]?.[2];if(!a)throw new Error(`Flow "${e.name}" did not register a handler`);let i={_meta:{sessionId:o}};async function c(d){return{...d,decodedState:n?await n.get(o):null}}return{async start(d,p){let u=await a({action:"start",intent:d,...p?{stateUpdates:p}:{}},i);return c(Ae(u))},async continueWith(d){let p=await a({action:"continue",...d?{stateUpdates:d}:{}},i);return c(Ae(p))},async lastState(){return n?n.get(o):null}}}var q="text/html+skybridge",L="text/html;profile=mcp-app",Ue=async(e,t)=>{let n=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${n}${t}`)).text()};function De(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function Oe(e){let t=e.widgetCSP?{connectDomains:e.widgetCSP.connect_domains,resourceDomains:e.widgetCSP.resource_domains,frameDomains:e.widgetCSP.frame_domains,redirectDomains:e.widgetCSP.redirect_domains}:void 0;return{ui:{...t&&{csp:t},...e.widgetDomain&&{domain:e.widgetDomain},...e.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function re(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.httpUrl&&{httpUrl:e.httpUrl}}},...e.mcpTemplateUri&&{"ui/resourceUri":e.mcpTemplateUri}}}function je(e){let{id:t,title:n,description:r,baseUrl:o,htmlPath:s,widgetDomain:a,prefersBorder:i=!0,autoHeight:c=!0}=e,d=e.widgetCSP??{connect_domains:[o],resource_domains:[o]};if(process.env.NODE_ENV==="development")try{let{hostname:S}=new URL(o);(S==="localhost"||S==="127.0.0.1")&&(d={...d,connect_domains:[...d.connect_domains||[],`ws://${S}:*`,`wss://${S}:*`],resource_domains:[...d.resource_domains||[],`http://${S}:*`]})}catch{}let p=`ui://widgets/apps-sdk/${t}.html`,u=`ui://widgets/ext-apps/${t}.html`,m=`${o.endsWith("/")?o.slice(0,-1):o}${s}`,T=null,y=()=>(T||(T=Ue(o,s)),T),l=r;async function f(S){let k=await y();S.registerResource(`${t}-openai-widget`,p,{title:n,description:l,mimeType:q,_meta:{"openai/widgetDescription":l,"openai/widgetPrefersBorder":i}},async v=>({contents:[{uri:v.href,mimeType:q,text:k,_meta:De({description:l,prefersBorder:i,widgetDomain:a,widgetCSP:d})}]})),S.registerResource(`${t}-mcp-widget`,u,{title:n,description:l,mimeType:L,_meta:{ui:{prefersBorder:i}}},async v=>({contents:[{uri:v.href,mimeType:L,text:k,_meta:Oe({description:l,prefersBorder:i,widgetDomain:a,widgetCSP:d})}]}))}return{id:t,title:n,description:r,openaiUri:p,mcpUri:u,autoHeight:c,httpUrl:m,register:f}}function dt(e,t){let{resource:n,description:r,inputSchema:o,annotations:s,autoInjectResultText:a=!0}=e,i=e.id??n?.id,c=e.title??n?.title;if(!i)throw new Error("createTool: `id` is required when no resource is provided");if(!c)throw new Error("createTool: `title` is required when no resource is provided");let d=n?re({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight,httpUrl:n.httpUrl}):void 0;return{id:i,title:c,description:r,async register(p){p.registerTool(i,{title:c,description:r,inputSchema:o,annotations:s,...d&&{_meta:d}},(async(u,g)=>{let m=g,T=m._meta??{},y=$(m),l=await t(u,{extra:{_meta:T},waniwani:y});return n&&l.data?{content:[{type:"text",text:l.text}],structuredContent:l.data,_meta:{...d,...T,...a===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:l.text}],...l.data?{structuredContent:l.data}:{},...a===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function ut(e,t){await Promise.all(t.map(n=>n.register?.(e)))}var H=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var pt="@waniwani/sdk";function Ke(e){let{apiUrl:t,apiKey:n}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function o(s,a,i){let c=r(),d=`${t.replace(/\/$/,"")}${a}`,p={Authorization:`Bearer ${c}`,"X-WaniWani-SDK":pt},u={method:s,headers:p};i!==void 0&&(p["Content-Type"]="application/json",u.body=JSON.stringify(i));let g=await fetch(d,u);if(!g.ok){let T=await g.text().catch(()=>"");throw new H(T||`KB API error: HTTP ${g.status}`,g.status)}return(await g.json()).data}return{async ingest(s){return o("POST","/api/mcp/kb/ingest",{files:s})},async search(s,a){return o("POST","/api/mcp/kb/search",{query:s,...a})},async sources(){return o("GET","/api/mcp/kb/sources")}}}var lt="@waniwani/sdk";function z(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??$e,o=mt(e),s=V(e.meta),a=V(e.metadata),i=wt(e,s),c=E(e.eventId)??r(),d=ht(e.timestamp,n),p=E(e.source)??P(s)??t.source??lt,u=oe(e)?{...e}:void 0,g={...a};return Object.keys(s).length>0&&(g.meta=s),u&&(g.rawLegacy=u),{id:c,type:"mcp.event",name:o,source:p,timestamp:d,correlation:i,properties:ft(e,o),metadata:g,rawLegacy:u}}function $e(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function ft(e,t){if(!oe(e))return V(e.properties);let n=gt(e,t),r=V(e.properties);return{...n,...r}}function gt(e,t){switch(t){case"tool.called":{let n={};return E(e.toolName)&&(n.name=e.toolName),E(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),E(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return E(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),E(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function mt(e){return oe(e)?e.eventType:e.event}function wt(e,t){let n=E(e.requestId)??ve(t),r=E(e.sessionId)??_(t),o=E(e.traceId)??xe(t),s=E(e.externalUserId)??Re(t),a=E(e.correlationId)??Ee(t)??n,i={};return r&&(i.sessionId=r),o&&(i.traceId=o),n&&(i.requestId=n),a&&(i.correlationId=a),s&&(i.externalUserId=s),i}function ht(e,t){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){let n=new Date(e);if(!Number.isNaN(n.getTime()))return n.toISOString()}return t().toISOString()}function V(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function E(e){if(typeof e=="string"&&e.trim().length!==0)return e}function oe(e){return"eventType"in e}var yt="/api/mcp/events/v2/batch";var Be="@waniwani/sdk",Tt=new Set([401,403]),kt=new Set([408,425,429,500,502,503,504]);function qe(e){return new ie(e)}var ie=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=xt(t.apiUrl,t.endpointPath??yt),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??fetch,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(r=>setTimeout(r,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs))}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[WaniWani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[WaniWani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,r=this.flush();if(!Number.isFinite(n)||n<=0)return await r,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let o=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(n).then(()=>o)])===o?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,r=t;for(;r.length>0&&!this.isStopped;){this.inFlightCount=r.length;let o=await this.sendBatchOnce(r);switch(this.inFlightCount=0,o.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(o.status,r.length);return;case"permanent":this.logger.error("[WaniWani] Dropping %d event(s) after permanent failure: %s",r.length,o.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d event(s) after retry exhaustion: %s",r.length,o.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(o.permanent.length>0&&this.logger.error("[WaniWani] Dropping %d event(s) rejected as permanent",o.permanent.length),o.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d retryable event(s) after retry exhaustion",o.retryable.length);return}r=o.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-WaniWani-SDK":Be},body:JSON.stringify(this.makeBatchRequest(t))})}catch(s){return{kind:"retryable",reason:Rt(s)}}if(Tt.has(n.status))return{kind:"auth",status:n.status};if(kt.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await vt(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:Be,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(a=>[a.id,a])),o=[],s=[];for(let a of n){let i=r.get(a.eventId);if(i){if(St(a)){o.push(i);continue}s.push(i)}}return{retryable:o,permanent:s}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let r=this.buffer.length;this.buffer.splice(0,r),this.logger.error("[WaniWani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+r)}};function St(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 vt(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function xt(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function Rt(e){return e instanceof Error?e.message:String(e)}function Le(e){let{apiUrl:t,apiKey:n,tracking:r}=e;function o(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}let s=n?qe({apiUrl:t,apiKey:n,endpointPath:r.endpointPath,flushIntervalMs:r.flushIntervalMs,maxBatchSize:r.maxBatchSize,maxBufferSize:r.maxBufferSize,maxRetries:r.maxRetries,retryBaseDelayMs:r.retryBaseDelayMs,retryMaxDelayMs:r.retryMaxDelayMs,shutdownTimeoutMs:r.shutdownTimeoutMs}):void 0,a={async identify(i,c,d){o();let p=z({event:"user.identified",externalUserId:i,properties:c,meta:d});return s?.enqueue(p),{eventId:p.id}},async track(i){o();let c=z(i);return s?.enqueue(c),{eventId:c.id}},async flush(){o(),await s?.flush()},async shutdown(i){return o(),await s?.shutdown({timeoutMs:i?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return s&&Et(a,r.shutdownTimeoutMs),a}function Et(e,t){if(typeof process>"u"||typeof process.once!="function"||typeof process.on!="function")return;let n=()=>{e.shutdown({timeoutMs:t})};process.once("beforeExit",n),process.once("SIGINT",n),process.once("SIGTERM",n)}function Y(e){let t=e,n=t?.apiUrl??"https://app.waniwani.ai",r=t?.apiKey??process.env.WANIWANI_API_KEY,o={endpointPath:t?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:t?.tracking?.flushIntervalMs??1e3,maxBatchSize:t?.tracking?.maxBatchSize??20,maxBufferSize:t?.tracking?.maxBufferSize??1e3,maxRetries:t?.tracking?.maxRetries??3,retryBaseDelayMs:t?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:t?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:t?.tracking?.shutdownTimeoutMs??2e3},s={apiUrl:n,apiKey:r,tracking:o},a=Le(s),i=Ke(s);return{...a,kb:i,_config:s}}function It(e){let t=e.event_type??"widget_click",r=t.startsWith("widget_")?t:`widget_${t}`,o={...e.metadata??{}};return e.event_name&&(o.event_name=e.event_name),{event:r,properties:o,sessionId:e.session_id,traceId:e.trace_id,externalUserId:e.user_id,eventId:e.event_id,timestamp:e.timestamp,source:e.source??"widget"}}function Ct(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=Y(t)),n}return async function(s){let a;try{a=await s.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!Array.isArray(a.events)||a.events.length===0)return new Response(JSON.stringify({error:"Missing or empty events array"}),{status:400,headers:{"Content-Type":"application/json"}});try{let i=r(),c=[];for(let d of a.events){let p=It(d),u=await i.track(p);c.push(u.eventId)}return await i.flush(),new Response(JSON.stringify({ok:!0,accepted:c.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(i){let c=i instanceof Error?i.message:"Unknown error";return new Response(JSON.stringify({error:c}),{status:500,headers:{"Content-Type":"application/json"}})}}}function G(e,t){return t?(...n)=>console.log(`[waniwani:${e}]`,...n):()=>{}}var se=G("widget-token",!!process.env.WANIWANI_DEBUG),bt=120*1e3,J=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-bt?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=_t(this.config.apiUrl,"/api/mcp/widget-tokens");se("minting token from",r);let o={};t&&(o.sessionId=t),n&&(o.traceId=n);try{let s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)});if(se("mint response:",s.status),!s.ok)return null;let a=await s.json(),i=a.data&&typeof a.data=="object"?a.data:a,c=new Date(i.expiresAt).getTime();return!i.token||Number.isNaN(c)?null:(this.cached={token:i.token,expiresAt:c},i.token)}catch(s){return se("mint failed:",s),null}}};function _t(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}var He="waniwani/sessionId",ae="waniwani/geoLocation",ce="waniwani/userLocation";function x(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function K(e){if(!x(e))return;let t=e._meta;return x(t)?t:void 0}function de(e){if(!x(e))return;let t=e.content;return Array.isArray(t)?t.find(r=>x(r)&&r.type==="text"&&typeof r.text=="string")?.text:void 0}function Pt(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function ue(e,t,n,r,o,s){let a=Pt(e,n.toolType),i=K(t);return console.log("[waniwani:debug] buildTrackInput meta:",JSON.stringify(i),"-> source:",P(i)),{event:"tool.called",properties:{name:e,type:a,...r??{},...s?.input!==void 0&&{input:s.input},...s?.output!==void 0&&{output:s.output}},meta:i,source:P(i),metadata:{...n.metadata??{},...o&&{clientInfo:o}}}}async function pe(e,t,n){try{await e.track(t)}catch(r){n?.(fe(r))}}async function le(e,t){try{await e.flush()}catch(n){t?.(fe(n))}}async function Ve(e,t,n,r,o){if(!x(e))return;x(e._meta)||(e._meta={});let s=e._meta,a=x(s.waniwani)?s.waniwani:void 0,i={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let u=await t.getToken();u&&(i.token=u)}catch(u){o?.(fe(u))}let c=_(s);c&&(i.sessionId||(i.sessionId=c));let d=Ye(s);d!==void 0&&(i.geoLocation||(i.geoLocation=d));let p=P(K(r));p&&!i.source&&(i.source=p),s.waniwani=i}function ze(e,t){let n=K(t);if(!n||!x(e))return;x(e._meta)||(e._meta={});let r=e._meta,o=_(n);o&&!r[He]&&(r[He]=o);let s=Ye(n);s&&(r[ae]||(r[ae]=s),r[ce]||(r[ce]=s))}function Ye(e){if(!e)return;let t=e[ae]??e[ce];if(x(t)||typeof t=="string")return t}function Ge(e,t){if(!t||!x(e))return;x(e._meta)||(e._meta={});let n=e._meta;for(let[r,o]of Object.entries(t))r in n||(n[r]=o)}function fe(e){return e instanceof Error?e:new Error(String(e))}var Z=G("mcp",!!process.env.WANIWANI_DEBUG),Je="https://app.waniwani.ai";function Wt(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??Y(),s=r.injectWidgetToken!==!1,a=o._config.apiKey?new J({apiUrl:o._config.apiUrl??Je,apiKey:o._config.apiKey}):null,i=e.registerTool.bind(e);return n.registerTool=((...c)=>{let[d,p,u]=c,g=typeof d=="string"&&d.trim().length>0?d:"unknown";if(typeof u!="function")return i(...c);let m=x(p)&&x(p._meta)?p._meta:void 0,T=u,y=async(l,f)=>{let S=K(f)??{},k=Se(o,S,{apiUrl:o._config.apiUrl,apiKey:o._config.apiKey});x(f)&&(f[ee]=k);let v=performance.now(),N=e.server?.getClientVersion?.();try{let R=await T(l,f),I=Math.round(performance.now()-v);Z(`tool "${g}" handler returned in ${I}ms, running post-processing...`);let X=x(R)&&R.isError===!0;if(X){let ge=de(R);console.error(`[waniwani] Tool "${g}" returned error${ge?`: ${ge}`:""}`)}return await pe(o,ue(g,f,r,{durationMs:I,status:X?"error":"ok",...X&&{errorMessage:de(R)??"Unknown tool error"}},N,{input:l,output:R}),r.onError),Z(`tool "${g}" tracking done`),r.flushAfterToolCall&&await le(o,r.onError),Ge(R,m),ze(R,f),s&&(await Ve(R,a,o._config.apiUrl??Je,f,r.onError),Z(`tool "${g}" widget config injected`)),Z(`tool "${g}" post-processing complete, returning result`),R}catch(R){let I=Math.round(performance.now()-v);throw await pe(o,ue(g,f,r,{durationMs:I,status:"error",errorMessage:R instanceof Error?R.message:String(R)},N,{input:l}),r.onError),r.flushAfterToolCall&&await le(o,r.onError),R}};if(x(p)&&x(p._meta)){let l=p._meta;l["openai/outputTemplate"]&&!l["openai/resultCanProduceWidget"]&&(l["openai/resultCanProduceWidget"]=!0,l["openai/widgetAccessible"]=!0)}return i(d,p,y)}),n}export{b as END,C as START,A as StateGraph,F as WaniwaniKvStore,Fe as createFlow,Ne as createFlowTestHarness,je as createResource,dt as createTool,Ct as createTrackingRoute,Q as detectPlatform,Xe as isMCPApps,Ze as isOpenAI,ut as registerTools,Wt as withWaniwani};
|
|
3
|
+
${_.context}`:`ERROR: ${S}`}:_),q=Ae(E,p.context,s,c);if(q)return q;break}}let g=r.get(s);if(!g)return{content:{status:"error",error:`No outgoing edge from node "${s}"`}};s=await M(g,c);continue}if(Ie(p)){let y=p.field;if(y&&ie(D(c,y))){let g=r.get(s);if(!g)return{content:{status:"error",error:`No outgoing edge from node "${s}"`}};s=await M(g,c);continue}return{content:{status:"widget",tool:p.tool.id,data:p.data,description:p.description,interactive:p.interactive!==!1},flowTokenContent:{step:s,state:c,field:y,widgetId:p.tool.id}}}c=W(c,p);let m=r.get(s);if(!m)return{content:{status:"error",error:`No outgoing edge from node "${s}"`}};s=await M(m,c)}catch(f){return{content:{status:"error",error:f instanceof Error?f.message:String(f)},flowTokenContent:{step:s,state:c}}}}return{content:{status:"error",error:"Flow exceeded maximum iterations (possible infinite loop)"}}}var gt="@waniwani/sdk",mt="https://app.waniwani.ai",F=class{get baseUrl(){return(process.env.WANIWANI_API_URL??mt).replace(/\/$/,"")}get apiKey(){return process.env.WANIWANI_API_KEY}async get(t){if(!this.apiKey)throw new Error("[WaniWani KV] No API key configured. Set WANIWANI_API_KEY env var.");return await this.request("/api/mcp/redis/get",{key:t})??null}async set(t,n){if(!this.apiKey)throw new Error("[WaniWani KV] No API key configured. Set WANIWANI_API_KEY env var.");await this.request("/api/mcp/redis/set",{key:t,value:n})}async delete(t){if(this.apiKey)try{await this.request("/api/mcp/redis/delete",{key:t})}catch(n){console.error("[WaniWani KV] delete failed for key:",t,n)}}async request(t,n){let r=`${this.baseUrl}${t}`,o=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","X-WaniWani-SDK":gt},body:JSON.stringify(n)});if(!o.ok){let a=await o.text().catch(()=>"");throw new Error(a||`KV store API error: HTTP ${o.status}`)}return(await o.json()).data}};var j=class{store=new F;get(t){return this.store.get(t)}set(t,n){return this.store.set(t,n)}delete(t){return this.store.delete(t)}};function Ne(e){let t=e.description??"",n=e._zod?.def;if(n?.type==="enum"&&n.entries){let r=Object.keys(n.entries).map(o=>`"${o}"`).join(" | ");return t?`${r} \u2014 ${t}`:r}return t}function Ue(e){let t=["","## FLOW EXECUTION PROTOCOL","","This tool implements a multi-step conversational flow. Follow this protocol exactly:","",'1. Call with `action: "start"` to begin and include `intent`.'," `intent` must be a brief summary of the user's goal for this flow,"," including relevant prior context that led to triggering it, if available."," Do NOT invent missing context."," If the user's message already contains answers to likely questions,"," extract them into `stateUpdates` as `{ field: value }` pairs."," The engine will auto-skip steps whose fields are already filled."," Only extract values the user explicitly stated \u2014 do NOT guess or invent values."];if(e.state){let n=[];for(let[r,o]of Object.entries(e.state)){let i=Me(o);if(i){let a=o.description??"",s=Object.entries(i).map(([c,u])=>{let l=Ne(u);return l?`\`${r}.${c}\` (${l})`:`\`${r}.${c}\``}).join(", ");n.push(a?`\`${r}\` (${a}): ${s}`:`\`${r}\`: ${s}`)}else{let a=Ne(o);n.push(a?`\`${r}\` (${a})`:`\`${r}\``)}}t.push(` Known fields: ${n.join(", ")}.`)}return t.push(" For grouped fields (shown as `group.subfield`), use dot-notation keys in `stateUpdates`:",' e.g. `{ "driver.name": "John", "driver.license": "ABC123" }`.',"2. The response JSON `status` field tells you what to do next:",' - `"interrupt"`: Pause and ask the user. Two forms:'," a. Single question: `{ question, field, context? }` \u2014 ask `question`, store answer in `field`."," b. Multi-question: `{ questions: [{question, field}, ...], context? }` \u2014 ask ALL questions"," in one conversational message, collect all answers."," `context` (if present) is hidden AI instructions \u2014 use to shape your response, do NOT show verbatim."," Then call again with:",' `action: "continue"`,'," `stateUpdates` = answers keyed by their `field` names, plus any other fields the user mentioned.",' - `"widget"`: The flow wants to show a UI widget. Call the tool named in the `tool`'," field, passing the `data` object as the tool's input."," Check the `interactive` field in the response:"," \u2022 `interactive: true` \u2014 The widget requires user interaction. After calling the display tool,"," STOP and WAIT for the user to interact with the widget. Do NOT call this flow tool again"," until the user has responded. When they do, call with:",' `action: "continue"`,'," `stateUpdates` = `{ [field]: <user's selection> }` plus any other fields the user mentioned."," \u2022 `interactive: false` \u2014 The widget is display-only. Call the display tool, then immediately",' call THIS flow tool again with `action: "continue"`. Do NOT wait for user interaction.',' - `"complete"`: The flow is done. Present the result to the user.',' - `"error"`: Something went wrong. Show the `error` message.',"","3. Do NOT invent state values. Only use `stateUpdates` for information the user explicitly provided.","4. Include only the fields the user actually answered in `stateUpdates` \u2014 do NOT guess missing ones."," If the user did not answer all pending questions, the engine will re-prompt for the remaining ones."," If the user mentioned values for other known fields, include those too \u2014"," they will be applied immediately and those steps will be auto-skipped."),t.join(`
|
|
4
|
+
`)}var wt={action:O.enum(["start","continue"]).describe('"start" to begin the flow, "continue" to resume after a pause (interrupt or widget)'),intent:O.string().optional().describe(`Required when action is "start". Provide a brief summary of the user's goal for this flow, including relevant prior context that led to triggering it, if available. Do not invent missing context.`),stateUpdates:O.record(O.string(),O.unknown()).optional().describe("State field values to set before processing the next node. Use this to pass the user's answer (keyed by the field name from the response) and any other values the user mentioned.")};function De(e){let{config:t,nodes:n,edges:r}=e,o=Ue(t),i=`${t.description}
|
|
5
|
+
${o}`,a=e.store??new j,s=new Map;async function c(d,f,p,m){if(d.action==="start"){let y=typeof d.intent=="string"?d.intent.trim():void 0;if(!y)return{content:{status:"error",error:`Missing required "intent" for action "start". Include a brief summary of the user's goal for this flow and any relevant prior context that led to triggering it, if available.`}};d.intent=y;let g=r.get(C);if(!g)return{content:{status:"error",error:"No start edge"}};let T=oe(d.stateUpdates??{}),R=await M(g,T);return L(R,T,n,r,s,p,m)}if(d.action==="continue"){if(!f)return{content:{status:"error",error:"No session ID available for continue action."}};let y;try{y=await a.get(f)}catch(v){let S=v instanceof Error?v.message:String(v);return{content:{status:"error",error:`Failed to load flow state (session "${f}"): ${S}`}}}if(!y)return{content:{status:"error",error:`Flow state not found for session "${f}". The flow may have expired.`}};let g=y.state,T=y.step;if(!T)return{content:{status:"error",error:'This flow has already completed. Use action "start" to begin a new flow.'}};let R=W(g,oe(d.stateUpdates??{}));if(y.widgetId){let v=r.get(T);if(!v)return{content:{status:"error",error:`No edge from step "${T}"`}};let S=await M(v,R);return L(S,R,n,r,s,p,m)}return L(T,R,n,r,s,p,m)}return{content:{status:"error",error:`Unknown action: "${d.action}"`}}}let u={title:t.title,description:i,inputSchema:wt,annotations:t.annotations},l=(async(d,f)=>{let p=f,m=p._meta??{},y=P(m),g=H(p),T=await c(d,y,m,g);if(y)if(T.flowTokenContent&&T.content.status!=="complete")try{await a.set(y,T.flowTokenContent)}catch(v){let S=v instanceof Error?v.message:String(v);return{content:[{type:"text",text:JSON.stringify({status:"error",error:`Flow state failed to persist (session "${y}"): ${S}`},null,2)}],_meta:m,isError:!0}}else T.content.status==="complete"&&await a.delete(y);return{content:[{type:"text",text:JSON.stringify(T.content,null,2)}],_meta:m,...T.content.status==="error"?{isError:!0}:{}}});return{name:t.id,config:u,handler:l,async register(d){d.registerTool(t.id,u,l)},graph:e.graph}}function je(e,t){let n=["flowchart TD"];n.push(` ${C}((Start))`);for(let[r]of e)n.push(` ${r}[${r}]`);n.push(` ${b}((End))`);for(let[r,o]of t)o.type==="direct"?n.push(` ${r} --> ${o.to}`):n.push(` ${r} -.-> ${r}_branch([?])`);return n.join(`
|
|
6
|
+
`)}var A=class{nodes=new Map;edges=new Map;config;constructor(t){this.config=t}addNode(t,n){if(t===C||t===b)throw new Error(`"${t}" is a reserved name and cannot be used as a node name`);if(this.nodes.has(t))throw new Error(`Node "${t}" already exists`);return this.nodes.set(t,n),this}addEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge. Use addConditionalEdge for branching.`);return this.edges.set(t,{type:"direct",to:n}),this}addConditionalEdge(t,n){if(this.edges.has(t))throw new Error(`Node "${t}" already has an outgoing edge.`);return this.edges.set(t,{type:"conditional",condition:n}),this}graph(){return je(this.nodes,this.edges)}compile(t){this.validate();let n=new Map(this.nodes),r=new Map(this.edges);return De({config:this.config,nodes:n,edges:r,store:t?.store,graph:()=>je(n,r)})}validate(){if(!this.edges.has(C))throw new Error('Flow must have an entry point. Add an edge from START: .addEdge(START, "first_node")');let t=this.edges.get(C);if(t?.type==="direct"&&t.to!==b&&!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!==C&&!this.nodes.has(n))throw new Error(`Edge from non-existent node: "${n}"`);if(r.type==="direct"&&r.to!==b&&!this.nodes.has(r.to))throw new Error(`Edge from "${n}" references non-existent node: "${r.to}"`)}for(let[n]of this.nodes)if(!this.edges.has(n))throw new Error(`Node "${n}" has no outgoing edge. Add one with .addEdge("${n}", ...) or .addConditionalEdge("${n}", ...)`)}};function Oe(e){return new A(e)}function $e(e){let t=e.content;return JSON.parse(t[0]?.text??"")}async function Ke(e,t){let n=t?.stateStore,r=[],o=`test-session-${Math.random().toString(36).slice(2,10)}`,i={registerTool:(...u)=>{r.push(u)}};await e.register(i);let a=r[0]?.[2];if(!a)throw new Error(`Flow "${e.name}" did not register a handler`);let s={_meta:{sessionId:o}};async function c(u){return{...u,decodedState:n?await n.get(o):null}}return{async start(u,l){let d=await a({action:"start",intent:u,...l?{stateUpdates:l}:{}},s);return c($e(d))},async continueWith(u){let l=await a({action:"continue",...u?{stateUpdates:u}:{}},s);return c($e(l))},async lastState(){return n?n.get(o):null}}}var V="text/html+skybridge",z="text/html;profile=mcp-app",qe=async(e,t)=>{let n=e.endsWith("/")?e.slice(0,-1):e;return await(await fetch(`${n}${t}`)).text()};function Be(e){return{"openai/widgetDescription":e.description,"openai/widgetPrefersBorder":e.prefersBorder,"openai/widgetDomain":e.widgetDomain,...e.widgetCSP&&{"openai/widgetCSP":e.widgetCSP}}}function He(e){let t=e.widgetCSP?{connectDomains:e.widgetCSP.connect_domains,resourceDomains:e.widgetCSP.resource_domains,frameDomains:e.widgetCSP.frame_domains,redirectDomains:e.widgetCSP.redirect_domains}:void 0;return{ui:{...t&&{csp:t},...e.widgetDomain&&{domain:e.widgetDomain},...e.prefersBorder!==void 0&&{prefersBorder:e.prefersBorder}}}}function se(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.httpUrl&&{httpUrl:e.httpUrl}}},...e.mcpTemplateUri&&{"ui/resourceUri":e.mcpTemplateUri}}}function Le(e){let{id:t,title:n,description:r,baseUrl:o,htmlPath:i,widgetDomain:a,prefersBorder:s=!0,autoHeight:c=!0}=e,u=e.widgetCSP??{connect_domains:[o],resource_domains:[o]};if(process.env.NODE_ENV==="development")try{let{hostname:R}=new URL(o);(R==="localhost"||R==="127.0.0.1")&&(u={...u,connect_domains:[...u.connect_domains||[],`ws://${R}:*`,`wss://${R}:*`],resource_domains:[...u.resource_domains||[],`http://${R}:*`]})}catch{}let l=`ui://widgets/apps-sdk/${t}.html`,d=`ui://widgets/ext-apps/${t}.html`,p=`${o.endsWith("/")?o.slice(0,-1):o}${i}`,m=null,y=()=>(m||(m=qe(o,i)),m),g=r;async function T(R){let v=await y();R.registerResource(`${t}-openai-widget`,l,{title:n,description:g,mimeType:V,_meta:{"openai/widgetDescription":g,"openai/widgetPrefersBorder":s}},async S=>({contents:[{uri:S.href,mimeType:V,text:v,_meta:Be({description:g,prefersBorder:s,widgetDomain:a,widgetCSP:u})}]})),R.registerResource(`${t}-mcp-widget`,d,{title:n,description:g,mimeType:z,_meta:{ui:{prefersBorder:s}}},async S=>({contents:[{uri:S.href,mimeType:z,text:v,_meta:He({description:g,prefersBorder:s,widgetDomain:a,widgetCSP:u})}]}))}return{id:t,title:n,description:r,openaiUri:l,mcpUri:d,autoHeight:c,httpUrl:p,register:T}}function ht(e,t){let{resource:n,description:r,inputSchema:o,annotations:i,autoInjectResultText:a=!0}=e,s=e.id??n?.id,c=e.title??n?.title;if(!s)throw new Error("createTool: `id` is required when no resource is provided");if(!c)throw new Error("createTool: `title` is required when no resource is provided");let u=n?se({openaiTemplateUri:n.openaiUri,mcpTemplateUri:n.mcpUri,invoking:e.invoking??"Loading...",invoked:e.invoked??"Loaded",autoHeight:n.autoHeight,httpUrl:n.httpUrl}):void 0;return{id:s,title:c,description:r,async register(l){l.registerTool(s,{title:c,description:r,inputSchema:o,annotations:i,...u&&{_meta:u}},(async(d,f)=>{let p=f,m=p._meta??{},y=H(p),g=await t(d,{extra:{_meta:m},waniwani:y});return n&&g.data?{content:[{type:"text",text:g.text}],structuredContent:g.data,_meta:{...u,...m,...a===!1?{"waniwani/autoInjectResultText":!1}:{}}}:{content:[{type:"text",text:g.text}],...g.data?{structuredContent:g.data}:{},...a===!1?{_meta:{"waniwani/autoInjectResultText":!1}}:{}}}))}}}async function yt(e,t){await Promise.all(t.map(n=>n.register?.(e)))}var Y=class extends Error{constructor(n,r){super(n);this.status=r;this.name="WaniWaniError"}};var Tt="@waniwani/sdk";function Ve(e){let{apiUrl:t,apiKey:n}=e;function r(){if(!n)throw new Error("WANIWANI_API_KEY is not set");return n}async function o(i,a,s){let c=r(),u=`${t.replace(/\/$/,"")}${a}`,l={Authorization:`Bearer ${c}`,"X-WaniWani-SDK":Tt},d={method:i,headers:l};s!==void 0&&(l["Content-Type"]="application/json",d.body=JSON.stringify(s));let f=await fetch(u,d);if(!f.ok){let m=await f.text().catch(()=>"");throw new Y(m||`KB API error: HTTP ${f.status}`,f.status)}return(await f.json()).data}return{async ingest(i){return o("POST","/api/mcp/kb/ingest",{files:i})},async search(i,a){return o("POST","/api/mcp/kb/search",{query:i,...a})},async sources(){return o("GET","/api/mcp/kb/sources")}}}var kt="@waniwani/sdk";function Z(e,t={}){let n=t.now??(()=>new Date),r=t.generateId??ze,o=Rt(e),i=G(e.meta),a=G(e.metadata),s=xt(e,i),c=I(e.eventId)??r(),u=Et(e.timestamp,n),l=I(e.source)??U(i)??t.source??kt,d=ae(e)?{...e}:void 0,f={...a};return Object.keys(i).length>0&&(f.meta=i),d&&(f.rawLegacy=d),{id:c,type:"mcp.event",name:o,source:l,timestamp:u,correlation:s,properties:St(e,o),metadata:f,rawLegacy:d}}function ze(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`evt_${crypto.randomUUID()}`:`evt_${Math.random().toString(36).slice(2,10)}_${Date.now().toString(36)}`}function St(e,t){if(!ae(e))return G(e.properties);let n=vt(e,t),r=G(e.properties);return{...n,...r}}function vt(e,t){switch(t){case"tool.called":{let n={};return I(e.toolName)&&(n.name=e.toolName),I(e.toolType)&&(n.type=e.toolType),n}case"quote.succeeded":{let n={};return typeof e.quoteAmount=="number"&&(n.amount=e.quoteAmount),I(e.quoteCurrency)&&(n.currency=e.quoteCurrency),n}case"link.clicked":{let n={};return I(e.linkUrl)&&(n.url=e.linkUrl),n}case"purchase.completed":{let n={};return typeof e.purchaseAmount=="number"&&(n.amount=e.purchaseAmount),I(e.purchaseCurrency)&&(n.currency=e.purchaseCurrency),n}default:return{}}}function Rt(e){return ae(e)?e.eventType:e.event}function xt(e,t){let n=I(e.requestId)??be(t),r=I(e.sessionId)??P(t),o=I(e.traceId)??_e(t),i=I(e.externalUserId)??Pe(t),a=I(e.correlationId)??We(t)??n,s={};return r&&(s.sessionId=r),o&&(s.traceId=o),n&&(s.requestId=n),a&&(s.correlationId=a),i&&(s.externalUserId=i),s}function Et(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 G(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function I(e){if(typeof e=="string"&&e.trim().length!==0)return e}function ae(e){return"eventType"in e}var It="/api/mcp/events/v2/batch";var Ye="@waniwani/sdk",Ct=new Set([401,403]),bt=new Set([408,425,429,500,502,503,504]);function Ge(e){return new ce(e)}var ce=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=Wt(t.apiUrl,t.endpointPath??It),this.flushIntervalMs=t.flushIntervalMs??1e3,this.maxBatchSize=t.maxBatchSize??20,this.maxBufferSize=t.maxBufferSize??1e3,this.maxRetries=t.maxRetries??3,this.retryBaseDelayMs=t.retryBaseDelayMs??200,this.retryMaxDelayMs=t.retryMaxDelayMs??2e3,this.shutdownTimeoutMs=t.shutdownTimeoutMs??2e3,this.fetchFn=t.fetchFn??fetch,this.logger=t.logger??console,this.now=t.now??(()=>new Date),this.sleep=t.sleep??(n=>new Promise(r=>setTimeout(r,n))),this.apiKey=t.apiKey,this.sdkVersion=t.sdkVersion,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>{this.flush()},this.flushIntervalMs))}enqueue(t){if(this.isStopped||this.isShuttingDown){this.logger.warn("[WaniWani] Tracking transport is stopped, dropping event %s",t.id);return}if(this.buffer.length>=this.maxBufferSize){let n=this.buffer.length-this.maxBufferSize+1;this.buffer.splice(0,n),this.logger.warn("[WaniWani] Tracking buffer overflow, dropped %d oldest event(s)",n)}if(this.buffer.push(t),this.buffer.length>=this.maxBatchSize){this.flush();return}this.scheduleMicroFlush()}pendingEvents(){return this.buffer.length+this.inFlightCount}async flush(){return this.flushInFlight?this.flushInFlight:(this.flushInFlight=this.flushLoop().finally(()=>{this.flushInFlight=void 0}),this.flushInFlight)}async shutdown(t){this.isShuttingDown=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flushScheduledTimer&&(clearTimeout(this.flushScheduledTimer),this.flushScheduledTimer=void 0,this.flushScheduled=!1);let n=t?.timeoutMs??this.shutdownTimeoutMs,r=this.flush();if(!Number.isFinite(n)||n<=0)return await r,this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()};let o=Symbol("shutdown-timeout");return await Promise.race([r.then(()=>"flushed"),this.sleep(n).then(()=>o)])===o?(this.isStopped=!0,{timedOut:!0,pendingEvents:this.pendingEvents()}):(this.isStopped=!0,{timedOut:!1,pendingEvents:this.pendingEvents()})}scheduleMicroFlush(){this.flushScheduled||(this.flushScheduled=!0,this.flushScheduledTimer=setTimeout(()=>{this.flushScheduledTimer=void 0,this.flushScheduled=!1,this.flush()},0))}async flushLoop(){for(;this.buffer.length>0&&!this.isStopped;){let t=this.buffer.splice(0,this.maxBatchSize);await this.sendBatchWithRetry(t)}}async sendBatchWithRetry(t){let n=0,r=t;for(;r.length>0&&!this.isStopped;){this.inFlightCount=r.length;let o=await this.sendBatchOnce(r);switch(this.inFlightCount=0,o.kind){case"success":return;case"auth":this.stopTransportForAuthFailure(o.status,r.length);return;case"permanent":this.logger.error("[WaniWani] Dropping %d event(s) after permanent failure: %s",r.length,o.reason);return;case"retryable":if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d event(s) after retry exhaustion: %s",r.length,o.reason);return}await this.sleep(this.backoffDelayMs(n)),n+=1;continue;case"partial":if(o.permanent.length>0&&this.logger.error("[WaniWani] Dropping %d event(s) rejected as permanent",o.permanent.length),o.retryable.length===0)return;if(n>=this.maxRetries){this.logger.error("[WaniWani] Dropping %d retryable event(s) after retry exhaustion",o.retryable.length);return}r=o.retryable,await this.sleep(this.backoffDelayMs(n)),n+=1;continue}}}async sendBatchOnce(t){let n;try{n=await this.fetchFn(this.endpointUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-WaniWani-SDK":Ye},body:JSON.stringify(this.makeBatchRequest(t))})}catch(i){return{kind:"retryable",reason:Mt(i)}}if(Ct.has(n.status))return{kind:"auth",status:n.status};if(bt.has(n.status))return{kind:"retryable",reason:`HTTP ${n.status}`};if(!n.ok)return{kind:"permanent",reason:`HTTP ${n.status}`};let r=await Pt(n);if(!r?.rejected||r.rejected.length===0)return{kind:"success"};let o=this.classifyRejectedEvents(t,r.rejected);return o.retryable.length===0&&o.permanent.length===0?{kind:"success"}:{kind:"partial",retryable:o.retryable,permanent:o.permanent}}makeBatchRequest(t){return{sentAt:this.now().toISOString(),source:{sdk:Ye,version:this.sdkVersion??"0.0.0"},events:t}}classifyRejectedEvents(t,n){let r=new Map(t.map(a=>[a.id,a])),o=[],i=[];for(let a of n){let s=r.get(a.eventId);if(s){if(_t(a)){o.push(s);continue}i.push(s)}}return{retryable:o,permanent:i}}backoffDelayMs(t){let n=this.retryBaseDelayMs*2**t;return Math.min(n,this.retryMaxDelayMs)}stopTransportForAuthFailure(t,n){this.isStopped=!0;let r=this.buffer.length;this.buffer.splice(0,r),this.logger.error("[WaniWani] Auth failure (HTTP %d). Stopping tracking transport and dropping %d queued event(s)",t,n+r)}};function _t(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 Pt(e){let t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function Wt(e,t){let n=e.endsWith("/")?e:`${e}/`,r=t.startsWith("/")?t.slice(1):t;return`${n}${r}`}function Mt(e){return e instanceof Error?e.message:String(e)}function Ze(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?Ge({apiUrl:t,apiKey:n,endpointPath:r.endpointPath,flushIntervalMs:r.flushIntervalMs,maxBatchSize:r.maxBatchSize,maxBufferSize:r.maxBufferSize,maxRetries:r.maxRetries,retryBaseDelayMs:r.retryBaseDelayMs,retryMaxDelayMs:r.retryMaxDelayMs,shutdownTimeoutMs:r.shutdownTimeoutMs}):void 0,a={async identify(s,c,u){o();let l=Z({event:"user.identified",externalUserId:s,properties:c,meta:u});return i?.enqueue(l),{eventId:l.id}},async track(s){o();let c=Z(s);return i?.enqueue(c),{eventId:c.id}},async flush(){o(),await i?.flush()},async shutdown(s){return o(),await i?.shutdown({timeoutMs:s?.timeoutMs??r.shutdownTimeoutMs})??{timedOut:!1,pendingEvents:0}}};return i&&Ft(a,r.shutdownTimeoutMs),a}function Ft(e,t){if(typeof process>"u"||typeof process.once!="function"||typeof process.on!="function")return;let n=()=>{e.shutdown({timeoutMs:t})};process.once("beforeExit",n),process.once("SIGINT",n),process.once("SIGTERM",n)}function J(e){let t=e,n=t?.apiUrl??"https://app.waniwani.ai",r=t?.apiKey??process.env.WANIWANI_API_KEY,o={endpointPath:t?.tracking?.endpointPath??"/api/mcp/events/v2/batch",flushIntervalMs:t?.tracking?.flushIntervalMs??1e3,maxBatchSize:t?.tracking?.maxBatchSize??20,maxBufferSize:t?.tracking?.maxBufferSize??1e3,maxRetries:t?.tracking?.maxRetries??3,retryBaseDelayMs:t?.tracking?.retryBaseDelayMs??200,retryMaxDelayMs:t?.tracking?.retryMaxDelayMs??2e3,shutdownTimeoutMs:t?.tracking?.shutdownTimeoutMs??2e3},i={apiUrl:n,apiKey:r,tracking:o},a=Ze(i),s=Ve(i);return{...a,kb:s,_config:i}}function At(e){let t=e.event_type??"widget_click",r=t.startsWith("widget_")?t:`widget_${t}`,o={...e.metadata??{}};return e.event_name&&(o.event_name=e.event_name),{event:r,properties:o,sessionId:e.session_id,traceId:e.trace_id,externalUserId:e.user_id,eventId:e.event_id,timestamp:e.timestamp,source:e.source??"widget"}}function Nt(e){let t={apiKey:e?.apiKey,apiUrl:e?.apiUrl},n;function r(){return n||(n=J(t)),n}return async function(i){let a;try{a=await i.json()}catch{return new Response(JSON.stringify({error:"Invalid JSON"}),{status:400,headers:{"Content-Type":"application/json"}})}if(!Array.isArray(a.events)||a.events.length===0)return new Response(JSON.stringify({error:"Missing or empty events array"}),{status:400,headers:{"Content-Type":"application/json"}});try{let s=r(),c=[];for(let u of a.events){let l=At(u),d=await s.track(l);c.push(d.eventId)}return await s.flush(),new Response(JSON.stringify({ok:!0,accepted:c.length}),{status:200,headers:{"Content-Type":"application/json"}})}catch(s){let c=s instanceof Error?s.message:"Unknown error";return new Response(JSON.stringify({error:c}),{status:500,headers:{"Content-Type":"application/json"}})}}}function X(e,t){return t?(...n)=>console.log(`[waniwani:${e}]`,...n):()=>{}}var de=X("widget-token",!!process.env.WANIWANI_DEBUG),Ut=120*1e3,Q=class{cached=null;pending=null;config;constructor(t){this.config=t}async getToken(t,n){return this.cached&&Date.now()<this.cached.expiresAt-Ut?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=Dt(this.config.apiUrl,"/api/mcp/widget-tokens");de("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(de("mint response:",i.status),!i.ok)return null;let a=await i.json(),s=a.data&&typeof a.data=="object"?a.data:a,c=new Date(s.expiresAt).getTime();return!s.token||Number.isNaN(c)?null:(this.cached={token:s.token,expiresAt:c},s.token)}catch(i){return de("mint failed:",i),null}}};function Dt(e,t){return`${e.endsWith("/")?e.slice(0,-1):e}${t}`}var Je="waniwani/sessionId",le="waniwani/geoLocation",pe="waniwani/userLocation";function k(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function $(e){if(!k(e))return;let t=e._meta;return k(t)?t:void 0}function fe(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 jt(e,t){return typeof t=="function"?t(e)??"other":t??"other"}function ge(e,t,n,r,o,i){let a=jt(e,n.toolType),s=$(t);return{event:"tool.called",properties:{name:e,type:a,...r??{},...i?.input!==void 0&&{input:i.input},...i?.output!==void 0&&{output:i.output}},meta:s,source:U(s),metadata:{...n.metadata??{},...o&&{clientInfo:o}}}}async function me(e,t,n){try{await e.track(t)}catch(r){n?.(he(r))}}async function we(e,t){try{await e.flush()}catch(n){t?.(he(n))}}async function Xe(e,t,n,r,o){if(!k(e))return;k(e._meta)||(e._meta={});let i=e._meta,a=k(i.waniwani)?i.waniwani:void 0,s={...a??{},endpoint:a?.endpoint??`${n.replace(/\/$/,"")}/api/mcp/events/v2/batch`};if(t)try{let d=await t.getToken();d&&(s.token=d)}catch(d){o?.(he(d))}let c=P(i);c&&(s.sessionId||(s.sessionId=c));let u=et(i);u!==void 0&&(s.geoLocation||(s.geoLocation=u));let l=U($(r));l&&!s.source&&(s.source=l),i.waniwani=s}function Qe(e,t){let n=$(t);if(!n||!k(e))return;k(e._meta)||(e._meta={});let r=e._meta,o=P(n);o&&!r[Je]&&(r[Je]=o);let i=et(n);i&&(r[le]||(r[le]=i),r[pe]||(r[pe]=i))}function et(e){if(!e)return;let t=e[le]??e[pe];if(k(t)||typeof t=="string")return t}function tt(e,t){if(!t||!k(e))return;k(e._meta)||(e._meta={});let n=e._meta;for(let[r,o]of Object.entries(t))r in n||(n[r]=o)}function he(e){return e instanceof Error?e:new Error(String(e))}var ee="/__waniwani/resource";function ue(e,t){let n=e[t];if(typeof n=="string")return n;if(Array.isArray(n)&&typeof n[0]=="string")return n[0]}function Ot(e){if(!k(e))return;let t=e.requestInfo;if(!k(t))return;let n=t.url;if(k(n)&&typeof n.origin=="string"&&n.origin!=="null")return n.origin;let r=t.headers;if(!k(r))return;let o=ue(r,"x-forwarded-host");if(o)return`${ue(r,"x-forwarded-proto")??"https"}://${o}`;let i=ue(r,"host");if(i)return`${i.startsWith("127.0.0.1:")||i.startsWith("localhost:")?"http":"https"}://${i}`}function nt(e,t,n){if(!k(e)||!k(e._meta))return;let o=e._meta.ui;if(!k(o))return;let i=o.resourceUri;if(typeof i!="string"||typeof o.httpUrl=="string"||!n.has(i))return;let a=Ot(t);a&&(o.httpUrl=`${a}${ee}?uri=${encodeURIComponent(i)}`)}function rt(e){return(t,n,r)=>{let o=t,i=n,a=typeof r=="function"?r:void 0;if(o.method!=="GET"){a?.();return}let s=null;if(o.query&&typeof o.query.uri=="string")s=o.query.uri;else if(o.url)try{s=new URL(o.url,"http://localhost").searchParams.get("uri")}catch{}if(!s){i.status(400).json({error:"Missing uri query parameter"});return}let c=e.get(s);if(!c){i.status(404).json({error:"Resource not found"});return}let u=k(o.headers)?o.headers:{};Promise.resolve(c(new URL(s),{requestInfo:{headers:u}})).then(l=>{let d=l?.contents?.[0];if(!d){i.status(404).json({error:"Resource has no content"});return}let f;if(typeof d.text=="string"?f=d.text:typeof d.blob=="string"&&(f=atob(d.blob)),!f){i.status(404).json({error:"Resource has no content"});return}i.setHeader("Content-Type","text/html"),i.setHeader("Cache-Control","private, max-age=300"),i.status(200).send(f)}).catch(l=>{let d=l instanceof Error?l.message:"Unknown error";i.status(500).json({error:d})})}}var K=X("mcp",!!process.env.WANIWANI_DEBUG),ot="https://app.waniwani.ai";function $t(e,t){let n=e;if(n.__waniwaniWrapped)return n;n.__waniwaniWrapped=!0;let r=t??{},o=r.client??J(),i=r.injectWidgetToken!==!1,a=o._config.apiKey?new Q({apiUrl:o._config.apiUrl??ot,apiKey:o._config.apiKey}):null,s=new Map,c=e.registerResource.bind(e);n.registerResource=((...f)=>{let[,p,,m]=f;return typeof p=="string"&&typeof m=="function"&&s.set(p,m),c(...f)});let u=!1,l=e;typeof l.use=="function"&&(l.use(ee,rt(s)),u=!0,K("registered HTTP resource endpoint at",ee));let d=e.registerTool.bind(e);return n.registerTool=((...f)=>{let[p,m,y]=f,g=typeof p=="string"&&p.trim().length>0?p:"unknown";if(typeof y!="function")return d(...f);let T=k(m)&&k(m._meta)?m._meta:void 0,R=y,v=async(S,E)=>{let q=$(E)??{},_=Ce(o,q,{apiUrl:o._config.apiUrl,apiKey:o._config.apiKey});k(E)&&(E[re]=_);let ye=performance.now(),Te=e.server?.getClientVersion?.();try{let x=await R(S,E),B=Math.round(performance.now()-ye);K(`tool "${g}" handler returned in ${B}ms, running post-processing...`);let te=k(x)&&x.isError===!0;if(te){let ke=fe(x);console.error(`[waniwani] Tool "${g}" returned error${ke?`: ${ke}`:""}`)}return await me(o,ge(g,E,r,{durationMs:B,status:te?"error":"ok",...te&&{errorMessage:fe(x)??"Unknown tool error"}},Te,{input:S,output:x}),r.onError),K(`tool "${g}" tracking done`),r.flushAfterToolCall&&await we(o,r.onError),tt(x,T),u&&nt(x,E,s),Qe(x,E),i&&(await Xe(x,a,o._config.apiUrl??ot,E,r.onError),K(`tool "${g}" widget config injected`)),K(`tool "${g}" post-processing complete, returning result`),x}catch(x){let B=Math.round(performance.now()-ye);throw await me(o,ge(g,E,r,{durationMs:B,status:"error",errorMessage:x instanceof Error?x.message:String(x)},Te,{input:S}),r.onError),r.flushAfterToolCall&&await we(o,r.onError),x}};if(k(m)&&k(m._meta)){let S=m._meta;S["openai/outputTemplate"]&&!S["openai/resultCanProduceWidget"]&&(S["openai/resultCanProduceWidget"]=!0,S["openai/widgetAccessible"]=!0)}return d(p,m,v)}),n}export{b as END,C as START,A as StateGraph,F as WaniwaniKvStore,Oe as createFlow,Ke as createFlowTestHarness,Le as createResource,ht as createTool,Nt as createTrackingRoute,ne as detectPlatform,st as isMCPApps,it as isOpenAI,yt as registerTools,$t as withWaniwani};
|
|
7
7
|
//# sourceMappingURL=index.js.map
|