@waniwani/sdk 0.2.5 → 0.2.6-beta.1

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.
Files changed (33) hide show
  1. package/dist/chat/index.d.ts +8 -0
  2. package/dist/chat/index.js +7 -5
  3. package/dist/chat/index.js.map +1 -1
  4. package/dist/chat/next-js/index.d.ts +11 -0
  5. package/dist/chat/next-js/index.js +9 -1
  6. package/dist/chat/next-js/index.js.map +1 -1
  7. package/dist/chat/server/index.d.ts +15 -0
  8. package/dist/{chunk-HVAT4SNH.js → chunk-5JBHQYU5.js} +2 -2
  9. package/dist/chunk-5JBHQYU5.js.map +1 -0
  10. package/dist/chunk-OMMDVQYW.js +9 -0
  11. package/dist/chunk-OMMDVQYW.js.map +1 -0
  12. package/dist/{code-block-37QAKDTI-M2QCKVTI.js → code-block-37QAKDTI-IIYKFI5S.js} +2 -2
  13. package/dist/mcp/index.d.ts +62 -6
  14. package/dist/mcp/index.js +3 -3
  15. package/dist/mcp/index.js.map +1 -1
  16. package/dist/mcp/react.d.ts +25 -4
  17. package/dist/mcp/react.js +6 -6
  18. package/dist/mcp/react.js.map +1 -1
  19. package/dist/{mcp-apps-client-6WEBHSGH.js → mcp-apps-client-AXOLX2YD.js} +2 -2
  20. package/dist/mcp-apps-client-AXOLX2YD.js.map +1 -0
  21. package/dist/mermaid-4DMBBIKO-PAA57QRQ.js +3 -0
  22. package/dist/openai-client-IAONK3N3.js +5 -0
  23. package/dist/openai-client-IAONK3N3.js.map +1 -0
  24. package/package.json +1 -1
  25. package/dist/chunk-HVAT4SNH.js.map +0 -1
  26. package/dist/chunk-ZUGQBRJF.js +0 -3
  27. package/dist/chunk-ZUGQBRJF.js.map +0 -1
  28. package/dist/mcp-apps-client-6WEBHSGH.js.map +0 -1
  29. package/dist/mermaid-4DMBBIKO-NR6M3PLG.js +0 -3
  30. package/dist/openai-client-HLQSYZJC.js +0 -3
  31. package/dist/openai-client-HLQSYZJC.js.map +0 -1
  32. /package/dist/{code-block-37QAKDTI-M2QCKVTI.js.map → code-block-37QAKDTI-IIYKFI5S.js.map} +0 -0
  33. /package/dist/{mermaid-4DMBBIKO-NR6M3PLG.js.map → mermaid-4DMBBIKO-PAA57QRQ.js.map} +0 -0
@@ -1,4 +1,5 @@
1
1
  import { UIMessage } from 'ai';
2
+ import { ContentBlock } from '@modelcontextprotocol/sdk/types.js';
2
3
 
3
4
  interface SearchResult {
4
5
  source: string;
@@ -200,11 +201,19 @@ interface InternalConfig {
200
201
  tracking: Required<TrackingConfig>;
201
202
  }
202
203
 
204
+ type ModelContextContentBlock = ContentBlock;
205
+ type ModelContextUpdate = {
206
+ content?: ModelContextContentBlock[];
207
+ structuredContent?: Record<string, unknown>;
208
+ };
209
+
203
210
  interface BeforeRequestContext {
204
211
  /** The conversation messages from the client */
205
212
  messages: UIMessage[];
206
213
  /** Session identifier for conversation continuity */
207
214
  sessionId?: string;
215
+ /** Hidden widget-provided model context for the next assistant turn */
216
+ modelContext?: ModelContextUpdate;
208
217
  /** The original HTTP Request object */
209
218
  request: Request;
210
219
  }
@@ -215,6 +224,8 @@ type BeforeRequestResult = {
215
224
  systemPrompt?: string;
216
225
  /** Override sessionId */
217
226
  sessionId?: string;
227
+ /** Override hidden widget-provided model context */
228
+ modelContext?: ModelContextUpdate;
218
229
  };
219
230
 
220
231
  interface ChatOptions {
@@ -1,2 +1,10 @@
1
- function C(l,n){return n?(...a)=>console.log(`[waniwani:${l}]`,...a):()=>{}}var y=class extends Error{constructor(a,m){super(a);this.status=m;this.name="WaniWaniError"}};function E(l){let{apiKey:n,baseUrl:a,systemPrompt:m,maxSteps:e,beforeRequest:d,mcpServerUrl:f,resolveConfig:t,debug:c}=l,r=C("chat",c);return async function(g){r("\u2192 POST",g.url);try{let u=await g.json(),o=u.messages??[],i=u.sessionId,h=m;if(r("body parsed \u2014 messages:",o.length,"sessionId:",i??"(none)"),d){r("running beforeRequest hook");try{let p=await d({messages:o,sessionId:i,request:g});p&&(p.messages&&(o=p.messages),p.systemPrompt!==void 0&&(h=p.systemPrompt),p.sessionId!==void 0&&(i=p.sessionId)),r("beforeRequest hook done \u2014 messages:",o.length,"sessionId:",i??"(none)")}catch(p){console.error("[waniwani:chat] beforeRequest hook error:",p);let T=p instanceof y?p.status:400,k=p instanceof Error?p.message:"Request rejected";return r("\u2190 returning",T,"from hook error"),Response.json({error:k},{status:T})}}let x=f??(await t()).mcpServerUrl;r("mcpServerUrl:",x);let w=`${a}/api/mcp/chat`;r("forwarding to",w);let s=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({messages:o,mcpServerUrl:x,sessionId:i,systemPrompt:h,maxSteps:e}),signal:g.signal});if(r("upstream response status:",s.status),!s.ok){let p=await s.text().catch(()=>"");return r("\u2190 returning",s.status,"upstream error:",p),new Response(p,{status:s.status,headers:{"Content-Type":s.headers.get("Content-Type")??"application/json"}})}let H=new Headers({"Content-Type":s.headers.get("Content-Type")??"text/event-stream"}),S=s.headers.get("x-session-id");return S&&H.set("x-session-id",S),r("\u2190 streaming response",s.status,"body null?",s.body===null),new Response(s.body,{status:s.status,headers:H})}catch(u){console.error("[waniwani:chat] handler error:",u);let o=u instanceof Error?u.message:"Unknown error occurred",i=u instanceof y?u.status:500;return r("\u2190 returning",i,"from caught error"),Response.json({error:o},{status:i})}}}function U(l){let{mcpServerUrl:n,resolveConfig:a,debug:m}=l,e=C("resource",m);return async function(f){e("\u2192 GET",f.toString());try{let t=f.searchParams.get("uri");if(e("uri:",t??"(missing)"),!t)return e("\u2190 400 missing uri"),Response.json({error:"Missing uri query parameter"},{status:400});let c=n??(await a()).mcpServerUrl;e("mcpServerUrl:",c);let r,v;try{[{createMCPClient:r},{StreamableHTTPClientTransport:v}]=await Promise.all([import("@ai-sdk/mcp"),import("@modelcontextprotocol/sdk/client/streamableHttp.js")]),e("MCP deps loaded")}catch(u){return console.error("[waniwani:resource] MCP deps import failed:",u),Response.json({error:"MCP resource handler requires @ai-sdk/mcp and @modelcontextprotocol/sdk. Install them to enable resource serving."},{status:501})}e("creating MCP client for",c);let g=await r({transport:new v(new URL(c))});try{e("reading resource:",t);let u=await g.readResource({uri:t});e("resource contents count:",u.contents.length);let o=u.contents[0];if(!o)return e("\u2190 404 resource not found"),Response.json({error:"Resource not found"},{status:404});let i;return"text"in o&&typeof o.text=="string"?i=o.text:"blob"in o&&typeof o.blob=="string"&&(i=atob(o.blob)),i?(e("\u2190 200 HTML length:",i.length),new Response(i,{headers:{"Content-Type":"text/html","Cache-Control":"private, max-age=300"}})):(e("\u2190 404 resource has no content, keys:",Object.keys(o)),Response.json({error:"Resource has no content"},{status:404}))}finally{await g.close(),e("MCP client closed")}}catch(t){console.error("[waniwani:resource] handler error:",t);let c=t instanceof Error?t.message:"Unknown error occurred",r=t instanceof y?t.status:500;return e("\u2190 returning",r,"from caught error"),Response.json({error:c},{status:r})}}}var M=300*1e3;function j(l,n){let a=null,m=null;return async function(){if(a&&Date.now()<a.expiresAt)return a.config;if(m)return m;m=(async()=>{if(!n)throw new y("WANIWANI_API_KEY is required for createChatHandler",401);let d=await fetch(`${l}/api/mcp/environments/config`,{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}});if(!d.ok){let t=await d.text().catch(()=>"");throw new y(`Failed to resolve MCP environment config: ${d.status} ${t}`,d.status)}let f=await d.json();return a={config:f,expiresAt:Date.now()+M},f})();try{return await m}finally{m=null}}}function P(l,n){return new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"},status:n})}function A(l={}){let{apiKey:n=process.env.WANIWANI_API_KEY,baseUrl:a="https://app.waniwani.ai",systemPrompt:m,maxSteps:e=5,beforeRequest:d,mcpServerUrl:f,debug:t=!1}=l,c=C("router",t),r=j(a,n),v=E({apiKey:n,baseUrl:a,systemPrompt:m,maxSteps:e,beforeRequest:d,mcpServerUrl:f,resolveConfig:r,debug:t}),g=U({mcpServerUrl:f,resolveConfig:r,debug:t});async function u(){return P({debug:t},200)}async function o(i){c("\u2192 GET",i.url);try{let h=new URL(i.url),w=h.pathname.replace(/\/$/,"").split("/").filter(Boolean).at(-1);if(c("pathname:",h.pathname,"subRoute:",w),w==="resource"){c("dispatching to resource handler");let s=await g(h);return c("\u2190 resource handler returned",s.status),s}if(w==="config"){c("dispatching to config handler");let s=await u();return c("\u2190 config handler returned",s.status),s}return c("\u2190 404 no matching sub-route for",w),P({error:"Not found"},404)}catch(h){console.error("[waniwani:router] GET handler error:",h);let x=h instanceof Error?h.message:"Unknown error occurred";return c("\u2190 500 from caught error"),P({error:x},500)}}return{handleChat:v,handleResource:g,routeGet:o}}function te(l,n){let{apiKey:a,baseUrl:m}=l._config,e=n?.debug??process.env.WANIWANI_DEBUG==="1",d=A({...n?.chat,apiKey:a,baseUrl:m,debug:e});return{POST:d.handleChat,GET:d.routeGet}}export{te as toNextJsHandler};
1
+ function S(e,n){return n?(...s)=>console.log(`[waniwani:${e}]`,...s):()=>{}}var w=class extends Error{constructor(s,i){super(s);this.status=i;this.name="WaniWaniError"}};function U(e){if(!e)return!1;let n=Array.isArray(e.content)&&e.content.length>0,s=typeof e.structuredContent=="object"&&e.structuredContent!==null&&Object.keys(e.structuredContent).length>0;return n||s}function H(e){if(!U(e))return"";let n=["## 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(e.content?.length){let s=e.content.map(i=>i.type==="text"&&typeof i.text=="string"?i.text.trim():JSON.stringify(i,null,2)).filter(Boolean).join(`
2
+
3
+ `);s&&n.push(`Content blocks:
4
+ ${s}`)}return e.structuredContent&&Object.keys(e.structuredContent).length>0&&n.push(`Structured content JSON:
5
+ ${JSON.stringify(e.structuredContent,null,2)}`),n.join(`
6
+
7
+ `)}function k(e,n){if(!U(n))return e;let s=H(n);return s?[e,s].filter(Boolean).join(`
8
+
9
+ `):e}function E(e){let{apiKey:n,baseUrl:s,systemPrompt:i,maxSteps:t,beforeRequest:f,mcpServerUrl:g,resolveConfig:o,debug:r}=e,a=S("chat",r);return async function(h){a("\u2192 POST",h.url);try{let c=await h.json(),l=c.messages??[],u=c.sessionId,C=c.modelContext,y=i;if(a("body parsed \u2014 messages:",l.length,"sessionId:",u??"(none)"),f){a("running beforeRequest hook");try{let d=await f({messages:l,sessionId:u,modelContext:C,request:h});d&&(d.messages&&(l=d.messages),d.systemPrompt!==void 0&&(y=d.systemPrompt),d.sessionId!==void 0&&(u=d.sessionId),d.modelContext!==void 0&&(C=d.modelContext)),a("beforeRequest hook done \u2014 messages:",l.length,"sessionId:",u??"(none)")}catch(d){console.error("[waniwani:chat] beforeRequest hook error:",d);let j=d instanceof w?d.status:400,I=d instanceof Error?d.message:"Request rejected";return a("\u2190 returning",j,"from hook error"),Response.json({error:I},{status:j})}}let m=g??(await o()).mcpServerUrl;a("mcpServerUrl:",m),y=k(y,C);let M=`${s}/api/mcp/chat`;a("forwarding to",M);let p=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:{}},body:JSON.stringify({messages:l,mcpServerUrl:m,sessionId:u,systemPrompt:y,maxSteps:t}),signal:h.signal});if(a("upstream response status:",p.status),!p.ok){let d=await p.text().catch(()=>"");return a("\u2190 returning",p.status,"upstream error:",d),new Response(d,{status:p.status,headers:{"Content-Type":p.headers.get("Content-Type")??"application/json"}})}let x=new Headers({"Content-Type":p.headers.get("Content-Type")??"text/event-stream"}),v=p.headers.get("x-session-id");return v&&x.set("x-session-id",v),a("\u2190 streaming response",p.status,"body null?",p.body===null),new Response(p.body,{status:p.status,headers:x})}catch(c){console.error("[waniwani:chat] handler error:",c);let l=c instanceof Error?c.message:"Unknown error occurred",u=c instanceof w?c.status:500;return a("\u2190 returning",u,"from caught error"),Response.json({error:l},{status:u})}}}function A(e){let{mcpServerUrl:n,resolveConfig:s,debug:i}=e,t=S("resource",i);return async function(g){t("\u2192 GET",g.toString());try{let o=g.searchParams.get("uri");if(t("uri:",o??"(missing)"),!o)return t("\u2190 400 missing uri"),Response.json({error:"Missing uri query parameter"},{status:400});let r=n??(await s()).mcpServerUrl;t("mcpServerUrl:",r);let a,R;try{[{createMCPClient:a},{StreamableHTTPClientTransport:R}]=await Promise.all([import("@ai-sdk/mcp"),import("@modelcontextprotocol/sdk/client/streamableHttp.js")]),t("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})}t("creating MCP client for",r);let h=await a({transport:new R(new URL(r))});try{t("reading resource:",o);let c=await h.readResource({uri:o});t("resource contents count:",c.contents.length);let l=c.contents[0];if(!l)return t("\u2190 404 resource not found"),Response.json({error:"Resource not found"},{status:404});let u;return"text"in l&&typeof l.text=="string"?u=l.text:"blob"in l&&typeof l.blob=="string"&&(u=atob(l.blob)),u?(t("\u2190 200 HTML length:",u.length),new Response(u,{headers:{"Content-Type":"text/html","Cache-Control":"private, max-age=300"}})):(t("\u2190 404 resource has no content, keys:",Object.keys(l)),Response.json({error:"Resource has no content"},{status:404}))}finally{await h.close(),t("MCP client closed")}}catch(o){console.error("[waniwani:resource] handler error:",o);let r=o instanceof Error?o.message:"Unknown error occurred",a=o instanceof w?o.status:500;return t("\u2190 returning",a,"from caught error"),Response.json({error:r},{status:a})}}}function O(e){let{mcpServerUrl:n,resolveConfig:s,debug:i}=e,t=S("tool",i);return async function(g){t("\u2192 POST",g.url);try{let o=await g.json(),{name:r,arguments:a}=o;if(!r||typeof r!="string")return t("\u2190 400 missing tool name"),Response.json({error:"Missing tool name"},{status:400});t("tool:",r,"args:",JSON.stringify(a));let R=n??(await s()).mcpServerUrl;t("mcpServerUrl:",R);let h,c;try{[{Client:h},{StreamableHTTPClientTransport:c}]=await Promise.all([import("@modelcontextprotocol/sdk/client/index.js"),import("@modelcontextprotocol/sdk/client/streamableHttp.js")]),t("MCP deps loaded")}catch(C){return console.error("[waniwani:tool] MCP deps import failed:",C),Response.json({error:"MCP tool handler requires @modelcontextprotocol/sdk. Install it to enable tool calls."},{status:501})}t("creating MCP client for",R);let l=new c(new URL(R)),u=new h({name:"waniwani-tool-caller",version:"1.0.0"});await u.connect(l);try{t("calling tool:",r);let C=await u.callTool({name:r,arguments:a??{}});return t("tool result received"),Response.json({content:C.content,structuredContent:C.structuredContent,_meta:C._meta,isError:C.isError})}finally{await u.close(),t("MCP client closed")}}catch(o){console.error("[waniwani:tool] handler error:",o);let r=o instanceof Error?o.message:"Unknown error occurred",a=o instanceof w?o.status:500;return t("\u2190 returning",a,"from caught error"),Response.json({error:r},{status:a})}}}var B=300*1e3;function N(e,n){let s=null,i=null;return async function(){if(s&&Date.now()<s.expiresAt)return s.config;if(i)return i;i=(async()=>{if(!n)throw new w("WANIWANI_API_KEY is required for createChatHandler",401);let f=await fetch(`${e}/api/mcp/environments/config`,{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}});if(!f.ok){let o=await f.text().catch(()=>"");throw new w(`Failed to resolve MCP environment config: ${f.status} ${o}`,f.status)}let g=await f.json();return s={config:g,expiresAt:Date.now()+B},g})();try{return await i}finally{i=null}}}function T(e,n){return new Response(JSON.stringify(e),{headers:{"Content-Type":"application/json"},status:n})}function W(e={}){let{apiKey:n=process.env.WANIWANI_API_KEY,baseUrl:s="https://app.waniwani.ai",systemPrompt:i,maxSteps:t=5,beforeRequest:f,mcpServerUrl:g,debug:o=!1}=e,r=S("router",o),a=N(s,n),R=E({apiKey:n,baseUrl:s,systemPrompt:i,maxSteps:t,beforeRequest:f,mcpServerUrl:g,resolveConfig:a,debug:o}),h=A({mcpServerUrl:g,resolveConfig:a,debug:o}),c=O({mcpServerUrl:g,resolveConfig:a,debug:o});async function l(){return T({debug:o},200)}async function u(y){r("\u2192 GET",y.url);try{let m=new URL(y.url),p=m.pathname.replace(/\/$/,"").split("/").filter(Boolean).at(-1);if(r("pathname:",m.pathname,"subRoute:",p),p==="resource"){r("dispatching to resource handler");let x=await h(m);return r("\u2190 resource handler returned",x.status),x}if(p==="config"){r("dispatching to config handler");let x=await l();return r("\u2190 config handler returned",x.status),x}return r("\u2190 404 no matching sub-route for",p),T({error:"Not found"},404)}catch(m){console.error("[waniwani:router] GET handler error:",m);let M=m instanceof Error?m.message:"Unknown error occurred";return r("\u2190 500 from caught error"),T({error:M},500)}}async function C(y){r("\u2192 POST",y.url);try{let m=new URL(y.url),p=m.pathname.replace(/\/$/,"").split("/").filter(Boolean).at(-1);if(r("pathname:",m.pathname,"subRoute:",p),p==="tool"){r("dispatching to tool handler");let x=await c(y);return r("\u2190 tool handler returned",x.status),x}return r("dispatching to chat handler"),R(y)}catch(m){console.error("[waniwani:router] POST handler error:",m);let M=m instanceof Error?m.message:"Unknown error occurred";return r("\u2190 500 from caught error"),T({error:M},500)}}return{handleChat:R,handleResource:h,handleTool:c,routeGet:u,routePost:C}}function ye(e,n){let{apiKey:s,baseUrl:i}=e._config,t=n?.debug??process.env.WANIWANI_DEBUG==="1",f=W({...n?.chat,apiKey:s,baseUrl:i,debug:t});return{POST:f.routePost,GET:f.routeGet}}export{ye as toNextJsHandler};
2
10
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/utils/logger.ts","../../../src/error.ts","../../../src/chat/server/handle-chat.ts","../../../src/chat/server/handle-resource.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 - 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","// Handle Chat - Proxies chat requests to the WaniWani API\n\nimport { WaniWaniError } from \"../../error\";\nimport { createLogger } from \"../../utils/logger.js\";\nimport type { ApiHandlerDeps } from \"./@types\";\n\nexport function createChatRequestHandler(deps: ApiHandlerDeps) {\n\tconst {\n\t\tapiKey,\n\t\tbaseUrl,\n\t\tsystemPrompt,\n\t\tmaxSteps,\n\t\tbeforeRequest,\n\t\tmcpServerUrl: mcpServerUrlOverride,\n\t\tresolveConfig,\n\t\tdebug,\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 effectiveSystemPrompt = systemPrompt;\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);\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\trequest,\n\t\t\t\t\t});\n\n\t\t\t\t\tif (result) {\n\t\t\t\t\t\tif (result.messages) messages = result.messages;\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\tif (result.sessionId !== undefined) sessionId = result.sessionId;\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\n\t\t\t// 4. Forward to WaniWani API\n\t\t\tconst upstreamUrl = `${baseUrl}/api/mcp/chat`;\n\t\t\tlog(\"forwarding to\", upstreamUrl);\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},\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\tsystemPrompt: effectiveSystemPrompt,\n\t\t\t\t\tmaxSteps,\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","// 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\tbaseUrl: 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(`${baseUrl}/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 type { ApiHandler, ApiHandlerOptions } from \"./@types\";\nimport { createChatRequestHandler } from \"./handle-chat\";\nimport { createResourceHandler } from \"./handle-resource\";\nimport { createMcpConfigResolver } from \"./mcp-config-resolver\";\n\n/**\n * Create a JSON response with the given data and status code.\n * @param data - The data to be serialized to JSON.\n * @param status - The HTTP status code to be returned.\n * @returns A Response object with the JSON data and the given status code.\n */\nfunction jsonResponse(data: object, status: number): Response {\n\treturn new Response(JSON.stringify(data), {\n\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\tstatus,\n\t});\n}\n\n/**\n * Create a framework-agnostic API handler for chat and MCP resources.\n *\n * Returns an object with handler methods that can be wired into\n * any framework (Next.js, Hono, Express, etc.):\n *\n * - `handleChat(request)` → proxies chat messages to WaniWani API\n * - `handleResource(url)` → serves MCP resource content (HTML widgets)\n * - `routeGet(request)` → routes GET sub-paths (e.g. /resource)\n *\n * @example\n * ```typescript\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, dynamic } = toNextJsHandler(wani, {\n * chat: { systemPrompt: \"You are a helpful assistant.\" },\n * });\n * ```\n */\nexport function createApiHandler(options: ApiHandlerOptions = {}): ApiHandler {\n\tconst {\n\t\tapiKey = process.env.WANIWANI_API_KEY,\n\t\tbaseUrl = \"https://app.waniwani.ai\",\n\t\tsystemPrompt,\n\t\tmaxSteps = 5,\n\t\tbeforeRequest,\n\t\tmcpServerUrl,\n\t\tdebug = false,\n\t} = options;\n\n\tconst log = createLogger(\"router\", debug);\n\n\tconst resolveConfig = createMcpConfigResolver(baseUrl, apiKey);\n\n\tconst handleChat = createChatRequestHandler({\n\t\tapiKey,\n\t\tbaseUrl,\n\t\tsystemPrompt,\n\t\tmaxSteps,\n\t\tbeforeRequest,\n\t\tmcpServerUrl,\n\t\tresolveConfig,\n\t\tdebug,\n\t});\n\n\tconst handleResource = createResourceHandler({\n\t\tmcpServerUrl,\n\t\tresolveConfig,\n\t\tdebug,\n\t});\n\n\tasync function handleConfig(): Promise<Response> {\n\t\treturn jsonResponse({ debug }, 200);\n\t}\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 (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 response;\n\t\t\t}\n\n\t\t\tif (subRoute === \"config\") {\n\t\t\t\tlog(\"dispatching to config handler\");\n\t\t\t\tconst response = await handleConfig();\n\t\t\t\tlog(\"← config handler returned\", response.status);\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\tlog(\"← 404 no matching sub-route for\", subRoute);\n\t\t\treturn jsonResponse({ error: \"Not found\" }, 404);\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 jsonResponse({ error: message }, 500);\n\t\t}\n\t}\n\n\treturn { handleChat, handleResource, routeGet };\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, baseUrl } = 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\tbaseUrl,\n\t\tdebug: debugEnabled,\n\t});\n\n\treturn {\n\t\tPOST: handler.handleChat,\n\t\tGET: handler.routeGet,\n\t};\n}\n"],"mappings":"AAQO,SAASA,EACfC,EACAC,EAC+B,CAC/B,OAAOA,EACJ,IAAIC,IAAoB,QAAQ,IAAI,aAAaF,CAAS,IAAK,GAAGE,CAAI,EACtE,IAAM,CAAC,CACX,CCbO,IAAMC,EAAN,cAA4B,KAAM,CACxC,YACCC,EACOC,EACN,CACD,MAAMD,CAAO,EAFN,YAAAC,EAGP,KAAK,KAAO,eACb,CACD,ECJO,SAASC,EAAyBC,EAAsB,CAC9D,GAAM,CACL,OAAAC,EACA,QAAAC,EACA,aAAAC,EACA,SAAAC,EACA,cAAAC,EACA,aAAcC,EACd,cAAAC,EACA,MAAAC,CACD,EAAIR,EAEES,EAAMC,EAAa,OAAQF,CAAK,EAEtC,OAAO,eAA0BG,EAAqC,CACrEF,EAAI,cAAUE,EAAQ,GAAG,EACzB,GAAI,CAEH,IAAMC,EAAO,MAAMD,EAAQ,KAAK,EAC5BE,EAAWD,EAAK,UAAY,CAAC,EAC7BE,EAAgCF,EAAK,UACrCG,EAAwBZ,EAU5B,GARAM,EACC,+BACAI,EAAS,OACT,aACAC,GAAa,QACd,EAGIT,EAAe,CAClBI,EAAI,4BAA4B,EAChC,GAAI,CACH,IAAMO,EAAS,MAAMX,EAAc,CAClC,SAAAQ,EACA,UAAAC,EACA,QAAAH,CACD,CAAC,EA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EhEI,EAAUC,EAAiB,CAChC,GAAGL,GAAS,KACZ,OAAAC,EACA,QAAAC,EACA,MAAOC,CACR,CAAC,EAED,MAAO,CACN,KAAMC,EAAQ,WACd,IAAKA,EAAQ,QACd,CACD","names":["createLogger","namespace","enabled","args","WaniWaniError","message","status","createChatRequestHandler","deps","apiKey","baseUrl","systemPrompt","maxSteps","beforeRequest","mcpServerUrlOverride","resolveConfig","debug","log","createLogger","request","body","messages","sessionId","effectiveSystemPrompt","result","hookError","status","WaniWaniError","message","mcpServerUrl","upstreamUrl","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","TTL_MS","createMcpConfigResolver","baseUrl","apiKey","cached","inflight","WaniWaniError","response","body","data","jsonResponse","data","status","createApiHandler","options","apiKey","baseUrl","systemPrompt","maxSteps","beforeRequest","mcpServerUrl","debug","log","createLogger","resolveConfig","createMcpConfigResolver","handleChat","createChatRequestHandler","handleResource","createResourceHandler","handleConfig","routeGet","request","url","subRoute","response","error","message","toNextJsHandler","client","options","apiKey","baseUrl","debugEnabled","handler","createApiHandler"]}
1
+ {"version":3,"sources":["../../../src/utils/logger.ts","../../../src/error.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 - Errors\n\nexport class WaniWaniError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic status: number,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"WaniWaniError\";\n\t}\n}\n","import type { 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) return false;\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)) return null;\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)) return \"\";\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 { ApiHandlerDeps } from \"./@types\";\nimport { applyModelContextToSystemPrompt } from \"./model-context\";\n\nexport function createChatRequestHandler(deps: ApiHandlerDeps) {\n\tconst {\n\t\tapiKey,\n\t\tbaseUrl,\n\t\tsystemPrompt,\n\t\tmaxSteps,\n\t\tbeforeRequest,\n\t\tmcpServerUrl: mcpServerUrlOverride,\n\t\tresolveConfig,\n\t\tdebug,\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\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);\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});\n\n\t\t\t\t\tif (result) {\n\t\t\t\t\t\tif (result.messages) messages = result.messages;\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\tif (result.sessionId !== undefined) sessionId = result.sessionId;\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}\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 = `${baseUrl}/api/mcp/chat`;\n\t\t\tlog(\"forwarding to\", upstreamUrl);\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},\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\tsystemPrompt: effectiveSystemPrompt,\n\t\t\t\t\tmaxSteps,\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 { mcpServerUrl: mcpServerUrlOverride, resolveConfig, debug } = 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\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(\"tool:\", name, \"args:\", JSON.stringify(args));\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 result = await client.callTool({\n\t\t\t\t\tname,\n\t\t\t\t\targuments: args ?? {},\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\tbaseUrl: 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(`${baseUrl}/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 type { ApiHandler, ApiHandlerOptions } from \"./@types\";\nimport { createChatRequestHandler } from \"./handle-chat\";\nimport { createResourceHandler } from \"./handle-resource\";\nimport { createToolHandler } from \"./handle-tool\";\nimport { createMcpConfigResolver } from \"./mcp-config-resolver\";\n\n/**\n * Create a JSON response with the given data and status code.\n * @param data - The data to be serialized to JSON.\n * @param status - The HTTP status code to be returned.\n * @returns A Response object with the JSON data and the given status code.\n */\nfunction jsonResponse(data: object, status: number): Response {\n\treturn new Response(JSON.stringify(data), {\n\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\tstatus,\n\t});\n}\n\n/**\n * Create a framework-agnostic API handler for chat and MCP resources.\n *\n * Returns an object with handler methods that can be wired into\n * any framework (Next.js, Hono, Express, etc.):\n *\n * - `handleChat(request)` → proxies chat messages to WaniWani API\n * - `handleResource(url)` → serves MCP resource content (HTML widgets)\n * - `routeGet(request)` → routes GET sub-paths (e.g. /resource)\n *\n * @example\n * ```typescript\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, dynamic } = toNextJsHandler(wani, {\n * chat: { systemPrompt: \"You are a helpful assistant.\" },\n * });\n * ```\n */\nexport function createApiHandler(options: ApiHandlerOptions = {}): ApiHandler {\n\tconst {\n\t\tapiKey = process.env.WANIWANI_API_KEY,\n\t\tbaseUrl = \"https://app.waniwani.ai\",\n\t\tsystemPrompt,\n\t\tmaxSteps = 5,\n\t\tbeforeRequest,\n\t\tmcpServerUrl,\n\t\tdebug = false,\n\t} = options;\n\n\tconst log = createLogger(\"router\", debug);\n\n\tconst resolveConfig = createMcpConfigResolver(baseUrl, apiKey);\n\n\tconst handleChat = createChatRequestHandler({\n\t\tapiKey,\n\t\tbaseUrl,\n\t\tsystemPrompt,\n\t\tmaxSteps,\n\t\tbeforeRequest,\n\t\tmcpServerUrl,\n\t\tresolveConfig,\n\t\tdebug,\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});\n\n\tasync function handleConfig(): Promise<Response> {\n\t\treturn jsonResponse({ debug }, 200);\n\t}\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 (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 response;\n\t\t\t}\n\n\t\t\tif (subRoute === \"config\") {\n\t\t\t\tlog(\"dispatching to config handler\");\n\t\t\t\tconst response = await handleConfig();\n\t\t\t\tlog(\"← config handler returned\", response.status);\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\tlog(\"← 404 no matching sub-route for\", subRoute);\n\t\t\treturn jsonResponse({ error: \"Not found\" }, 404);\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 jsonResponse({ error: message }, 500);\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 (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 response;\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\treturn handleChat(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 jsonResponse({ error: message }, 500);\n\t\t}\n\t}\n\n\treturn { handleChat, handleResource, handleTool, routeGet, routePost };\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, baseUrl } = 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\tbaseUrl,\n\t\tdebug: debugEnabled,\n\t});\n\n\treturn {\n\t\tPOST: handler.routePost,\n\t\tGET: handler.routeGet,\n\t};\n}\n"],"mappings":"AAQO,SAASA,EACfC,EACAC,EAC+B,CAC/B,OAAOA,EACJ,IAAIC,IAAoB,QAAQ,IAAI,aAAaF,CAAS,IAAK,GAAGE,CAAI,EACtE,IAAM,CAAC,CACX,CCbO,IAAMC,EAAN,cAA4B,KAAM,CACxC,YACCC,EACOC,EACN,CACD,MAAMD,CAAO,EAFN,YAAAC,EAGP,KAAK,KAAO,eACb,CACD,ECDO,SAASC,EACfC,EAC8B,CAC9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B,OAASI,EAAO,CACf,QAAQ,MAAM,wCAAyCA,CAAK,EAC5D,IAAMC,EACLD,aAAiB,MAAQA,EAAM,QAAU,yBAC1C,OAAAhB,EAAI,8BAAyB,EACtBZ,EAAa,CAAE,MAAO6B,CAAQ,EAAG,GAAG,CAC5C,CACD,CAEA,MAAO,CAAE,WAAAb,EAAY,eAAAE,EAAgB,WAAAE,EAAY,SAAAG,EAAU,UAAAO,CAAU,CACtE,CCxHO,SAASC,GACfC,EACAC,EACsB,CACtB,GAAM,CAAE,OAAAC,EAAQ,QAAAC,CAAQ,EAAIH,EAAO,QAE7BI,EAAeH,GAAS,OAAS,QAAQ,IAAI,iBAAmB,IAEhEI,EAAUC,EAAiB,CAChC,GAAGL,GAAS,KACZ,OAAAC,EACA,QAAAC,EACA,MAAOC,CACR,CAAC,EAED,MAAO,CACN,KAAMC,EAAQ,UACd,IAAKA,EAAQ,QACd,CACD","names":["createLogger","namespace","enabled","args","WaniWaniError","message","status","hasModelContext","value","hasContent","hasStructuredContent","formatModelContextForPrompt","value","hasModelContext","sections","renderedBlocks","block","applyModelContextToSystemPrompt","systemPrompt","modelContext","hasModelContext","widgetContext","formatModelContextForPrompt","createChatRequestHandler","deps","apiKey","baseUrl","systemPrompt","maxSteps","beforeRequest","mcpServerUrlOverride","resolveConfig","debug","log","createLogger","request","body","messages","sessionId","modelContext","effectiveSystemPrompt","result","hookError","status","WaniWaniError","message","mcpServerUrl","applyModelContextToSystemPrompt","upstreamUrl","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","log","createLogger","request","body","name","args","mcpServerUrl","Client","StreamableHTTPClientTransport","importError","transport","client","result","error","message","status","WaniWaniError","TTL_MS","createMcpConfigResolver","baseUrl","apiKey","cached","inflight","WaniWaniError","response","body","data","jsonResponse","data","status","createApiHandler","options","apiKey","baseUrl","systemPrompt","maxSteps","beforeRequest","mcpServerUrl","debug","log","createLogger","resolveConfig","createMcpConfigResolver","handleChat","createChatRequestHandler","handleResource","createResourceHandler","handleTool","createToolHandler","handleConfig","routeGet","request","url","subRoute","response","error","message","routePost","toNextJsHandler","client","options","apiKey","baseUrl","debugEnabled","handler","createApiHandler"]}
@@ -1,15 +1,24 @@
1
1
  import { UIMessage } from 'ai';
2
+ import { ContentBlock } from '@modelcontextprotocol/sdk/types.js';
2
3
 
3
4
  declare class WaniWaniError extends Error {
4
5
  status: number;
5
6
  constructor(message: string, status: number);
6
7
  }
7
8
 
9
+ type ModelContextContentBlock = ContentBlock;
10
+ type ModelContextUpdate = {
11
+ content?: ModelContextContentBlock[];
12
+ structuredContent?: Record<string, unknown>;
13
+ };
14
+
8
15
  interface BeforeRequestContext {
9
16
  /** The conversation messages from the client */
10
17
  messages: UIMessage[];
11
18
  /** Session identifier for conversation continuity */
12
19
  sessionId?: string;
20
+ /** Hidden widget-provided model context for the next assistant turn */
21
+ modelContext?: ModelContextUpdate;
13
22
  /** The original HTTP Request object */
14
23
  request: Request;
15
24
  }
@@ -20,6 +29,8 @@ type BeforeRequestResult = {
20
29
  systemPrompt?: string;
21
30
  /** Override sessionId */
22
31
  sessionId?: string;
32
+ /** Override hidden widget-provided model context */
33
+ modelContext?: ModelContextUpdate;
23
34
  };
24
35
  interface ApiHandlerOptions {
25
36
  /**
@@ -64,8 +75,12 @@ interface ApiHandler {
64
75
  handleChat: (request: Request) => Promise<Response>;
65
76
  /** Serves MCP resource content (HTML widgets) */
66
77
  handleResource: (url: URL) => Promise<Response>;
78
+ /** Calls an MCP server tool and returns JSON */
79
+ handleTool: (request: Request) => Promise<Response>;
67
80
  /** Routes GET sub-paths (e.g. /resource) */
68
81
  routeGet: (request: Request) => Promise<Response>;
82
+ /** Routes POST sub-paths (e.g. /tool), defaults to chat */
83
+ routePost: (request: Request) => Promise<Response>;
69
84
  }
70
85
 
71
86
  export { type ApiHandler, type ApiHandlerOptions, type BeforeRequestContext, type BeforeRequestResult, WaniWaniError };
@@ -110,7 +110,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let n="<p>An error
110
110
  `||d==="\r"){o=!0;break}if(!o)return u;let c=[];for(let d of u)d===" "?c.push("\\t"):d===`
111
111
  `?c.push("\\n"):d==="\r"?c.push("\\r"):c.push(d);return c.join("")},i=t.length>0?r.length+1:r.length,a=new Array(i),s=0;t.length>0&&(a[s]=t.map(n).join(" "),s+=1);for(let u of r)a[s]=u.map(n).join(" "),s+=1;return a.join(`
112
112
  `)},uo=e=>{let t=!1;for(let n of e)if(n==="\\"||n==="|"){t=!0;break}if(!t)return e;let r=[];for(let n of e)n==="\\"?r.push("\\\\"):n==="|"?r.push("\\|"):r.push(n);return r.join("")},kx=e=>{let{headers:t,rows:r}=e;if(t.length===0)return"";let n=new Array(r.length+2),i=0,a=t.map(u=>uo(u));n[i]=`| ${a.join(" | ")} |`,i+=1;let s=new Array(t.length);for(let u=0;u<t.length;u+=1)s[u]="---";n[i]=`| ${s.join(" | ")} |`,i+=1;for(let u of r)if(u.length<t.length){let o=new Array(t.length);for(let c=0;c<t.length;c+=1)o[c]=c<u.length?uo(u[c]):"";n[i]=`| ${o.join(" | ")} |`,i+=1}else{let o=u.map(c=>uo(c));n[i]=`| ${o.join(" | ")} |`,i+=1}return n.join(`
113
- `)},Ax=({children:e,className:t,onCopy:r,onError:n,timeout:i=2e3})=>{let[a,s]=ye(!1),[u,o]=ye(!1),c=bt(null),d=bt(0),{isAnimating:f}=Ze(Ke),h=async g=>{var k,I;if(typeof window>"u"||!((k=navigator?.clipboard)!=null&&k.write)){n?.(new Error("Clipboard API not available"));return}try{let y=(I=c.current)==null?void 0:I.closest('[data-streamdown="table-wrapper"]'),D=y?.querySelector("table");if(!D){n?.(new Error("Table not found"));return}let L=_f(D),B=g==="csv"?Cf(L):xx(L),z=new ClipboardItem({"text/plain":new Blob([B],{type:"text/plain"}),"text/html":new Blob([D.outerHTML],{type:"text/html"})});await navigator.clipboard.write([z]),o(!0),s(!1),r?.(g),d.current=window.setTimeout(()=>o(!1),i)}catch(y){n?.(y)}};Xe(()=>{let g=k=>{let I=k.composedPath();c.current&&!I.includes(c.current)&&s(!1)};return document.addEventListener("mousedown",g),()=>{document.removeEventListener("mousedown",g),window.clearTimeout(d.current)}},[]);let p=u?mo:go;return oe("div",{className:"relative",ref:c,children:[_("button",{className:K("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",t),disabled:f,onClick:()=>s(!a),title:"Copy table",type:"button",children:e??_(p,{size:14})}),a?oe("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[120px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[_("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>h("csv"),title:"Copy table as CSV",type:"button",children:"CSV"}),_("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>h("tsv"),title:"Copy table as TSV",type:"button",children:"TSV"})]}):null]})},yx=({children:e,className:t,onDownload:r,onError:n})=>{let[i,a]=ye(!1),s=bt(null),{isAnimating:u}=Ze(Ke),o=c=>{var d;try{let f=(d=s.current)==null?void 0:d.closest('[data-streamdown="table-wrapper"]'),h=f?.querySelector("table");if(!h){n?.(new Error("Table not found"));return}let p=_f(h),g=c==="csv"?Cf(p):kx(p);wr(`table.${c==="csv"?"csv":"md"}`,g,c==="csv"?"text/csv":"text/markdown"),a(!1),r?.(c)}catch(f){n?.(f)}};return Xe(()=>{let c=d=>{let f=d.composedPath();s.current&&!f.includes(s.current)&&a(!1)};return document.addEventListener("mousedown",c),()=>{document.removeEventListener("mousedown",c)}},[]),oe("div",{className:"relative",ref:s,children:[_("button",{className:K("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",t),disabled:u,onClick:()=>a(!i),title:"Download table",type:"button",children:e??_(Bi,{size:14})}),i?oe("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[120px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[_("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>o("csv"),title:"Download table as CSV",type:"button",children:"CSV"}),_("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>o("markdown"),title:"Download table as Markdown",type:"button",children:"Markdown"})]}):null]})},_x=({children:e,className:t,showControls:r,...n})=>oe("div",{className:"my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",children:[r?oe("div",{className:"flex items-center justify-end gap-1",children:[_(Ax,{}),_(yx,{})]}):null,_("div",{className:"overflow-x-auto",children:_("table",{className:K("w-full border-collapse border border-border",t),"data-streamdown":"table",...n,children:e})})]}),Cx=xf(()=>import("./code-block-37QAKDTI-M2QCKVTI.js").then(e=>({default:e.CodeBlock}))),Sx=xf(()=>import("./mermaid-4DMBBIKO-NR6M3PLG.js").then(e=>({default:e.Mermaid}))),Ix=/language-([^\s]+)/;function Fi(e,t){if(!(e!=null&&e.position||t!=null&&t.position))return!0;if(!(e!=null&&e.position&&t!=null&&t.position))return!1;let r=e.position.start,n=t.position.start,i=e.position.end,a=t.position.end;return r?.line===n?.line&&r?.column===n?.column&&i?.line===a?.line&&i?.column===a?.column}function Te(e,t){return e.className===t.className&&Fi(e.node,t.node)}var ho=(e,t)=>typeof e=="boolean"?e:e[t]!==!1,Mi=(e,t)=>{if(typeof e=="boolean")return e;let r=e.mermaid;return r===!1?!1:r===!0||r===void 0?!0:r[t]!==!1},Eo=he(({children:e,className:t,node:r,...n})=>_("ol",{className:K("list-inside list-decimal whitespace-normal [li_&]:pl-6",t),"data-streamdown":"ordered-list",...n,children:e}),(e,t)=>Te(e,t));Eo.displayName="MarkdownOl";var Sf=he(({children:e,className:t,node:r,...n})=>_("li",{className:K("py-1 [&>p]:inline",t),"data-streamdown":"list-item",...n,children:e}),(e,t)=>e.className===t.className&&Fi(e.node,t.node));Sf.displayName="MarkdownLi";var If=he(({children:e,className:t,node:r,...n})=>_("ul",{className:K("list-inside list-disc whitespace-normal [li_&]:pl-6",t),"data-streamdown":"unordered-list",...n,children:e}),(e,t)=>Te(e,t));If.displayName="MarkdownUl";var Nf=he(({className:e,node:t,...r})=>_("hr",{className:K("my-6 border-border",e),"data-streamdown":"horizontal-rule",...r}),(e,t)=>Te(e,t));Nf.displayName="MarkdownHr";var wf=he(({children:e,className:t,node:r,...n})=>_("span",{className:K("font-semibold",t),"data-streamdown":"strong",...n,children:e}),(e,t)=>Te(e,t));wf.displayName="MarkdownStrong";var Nx=({children:e,className:t,href:r,node:n,...i})=>{let{linkSafety:a}=Ze(Ke),[s,u]=ye(!1),o=r==="streamdown:incomplete-link",c=je(async p=>{if(!(!(a!=null&&a.enabled&&r)||o)){if(p.preventDefault(),a.onLinkCheck&&await a.onLinkCheck(r)){window.open(r,"_blank","noreferrer");return}u(!0)}},[a,r,o]),d=je(()=>{r&&window.open(r,"_blank","noreferrer")},[r]),f=je(()=>{u(!1)},[]),h={url:r??"",isOpen:s,onClose:f,onConfirm:d};return a!=null&&a.enabled&&r?oe(Vt,{children:[_("button",{className:K("wrap-anywhere appearance-none text-left font-medium text-primary underline",t),"data-incomplete":o,"data-streamdown":"link",onClick:c,type:"button",children:e}),a.renderModal?a.renderModal(h):_(px,{...h})]}):_("a",{className:K("wrap-anywhere font-medium text-primary underline",t),"data-incomplete":o,"data-streamdown":"link",href:r,rel:"noreferrer",target:"_blank",...i,children:e})},Lf=he(Nx,(e,t)=>Te(e,t)&&e.href===t.href);Lf.displayName="MarkdownA";var Rf=he(({children:e,className:t,node:r,...n})=>_("h1",{className:K("mt-6 mb-2 font-semibold text-3xl",t),"data-streamdown":"heading-1",...n,children:e}),(e,t)=>Te(e,t));Rf.displayName="MarkdownH1";var Df=he(({children:e,className:t,node:r,...n})=>_("h2",{className:K("mt-6 mb-2 font-semibold text-2xl",t),"data-streamdown":"heading-2",...n,children:e}),(e,t)=>Te(e,t));Df.displayName="MarkdownH2";var Of=he(({children:e,className:t,node:r,...n})=>_("h3",{className:K("mt-6 mb-2 font-semibold text-xl",t),"data-streamdown":"heading-3",...n,children:e}),(e,t)=>Te(e,t));Of.displayName="MarkdownH3";var Pf=he(({children:e,className:t,node:r,...n})=>_("h4",{className:K("mt-6 mb-2 font-semibold text-lg",t),"data-streamdown":"heading-4",...n,children:e}),(e,t)=>Te(e,t));Pf.displayName="MarkdownH4";var Mf=he(({children:e,className:t,node:r,...n})=>_("h5",{className:K("mt-6 mb-2 font-semibold text-base",t),"data-streamdown":"heading-5",...n,children:e}),(e,t)=>Te(e,t));Mf.displayName="MarkdownH5";var vf=he(({children:e,className:t,node:r,...n})=>_("h6",{className:K("mt-6 mb-2 font-semibold text-sm",t),"data-streamdown":"heading-6",...n,children:e}),(e,t)=>Te(e,t));vf.displayName="MarkdownH6";var Bf=he(({children:e,className:t,node:r,...n})=>{let{controls:i}=Ze(Ke),a=ho(i,"table");return _(_x,{className:t,showControls:a,...n,children:e})},(e,t)=>Te(e,t));Bf.displayName="MarkdownTable";var Ff=he(({children:e,className:t,node:r,...n})=>_("thead",{className:K("bg-muted/80",t),"data-streamdown":"table-header",...n,children:e}),(e,t)=>Te(e,t));Ff.displayName="MarkdownThead";var Hf=he(({children:e,className:t,node:r,...n})=>_("tbody",{className:K("divide-y divide-border bg-muted/40",t),"data-streamdown":"table-body",...n,children:e}),(e,t)=>Te(e,t));Hf.displayName="MarkdownTbody";var Uf=he(({children:e,className:t,node:r,...n})=>_("tr",{className:K("border-border border-b",t),"data-streamdown":"table-row",...n,children:e}),(e,t)=>Te(e,t));Uf.displayName="MarkdownTr";var zf=he(({children:e,className:t,node:r,...n})=>_("th",{className:K("whitespace-nowrap px-4 py-2 text-left font-semibold text-sm",t),"data-streamdown":"table-header-cell",...n,children:e}),(e,t)=>Te(e,t));zf.displayName="MarkdownTh";var qf=he(({children:e,className:t,node:r,...n})=>_("td",{className:K("px-4 py-2 text-sm",t),"data-streamdown":"table-cell",...n,children:e}),(e,t)=>Te(e,t));qf.displayName="MarkdownTd";var Vf=he(({children:e,className:t,node:r,...n})=>_("blockquote",{className:K("my-4 border-muted-foreground/30 border-l-4 pl-4 text-muted-foreground italic",t),"data-streamdown":"blockquote",...n,children:e}),(e,t)=>Te(e,t));Vf.displayName="MarkdownBlockquote";var Yf=he(({children:e,className:t,node:r,...n})=>_("sup",{className:K("text-sm",t),"data-streamdown":"superscript",...n,children:e}),(e,t)=>Te(e,t));Yf.displayName="MarkdownSup";var jf=he(({children:e,className:t,node:r,...n})=>_("sub",{className:K("text-sm",t),"data-streamdown":"subscript",...n,children:e}),(e,t)=>Te(e,t));jf.displayName="MarkdownSub";var Gf=he(({children:e,className:t,node:r,...n})=>{if("data-footnotes"in n){let i=s=>{var u,o;if(!Nr(s))return!1;let c=Array.isArray(s.props.children)?s.props.children:[s.props.children],d=!1,f=!1;for(let h of c)if(h){if(typeof h=="string")h.trim()!==""&&(d=!0);else if(Nr(h))if(((u=h.props)==null?void 0:u["data-footnote-backref"])!==void 0)f=!0;else{let p=Array.isArray(h.props.children)?h.props.children:[h.props.children];for(let g of p){if(typeof g=="string"&&g.trim()!==""){d=!0;break}if(Nr(g)&&((o=g.props)==null?void 0:o["data-footnote-backref"])===void 0){d=!0;break}}}}return f&&!d},a=Array.isArray(e)?e.map(s=>{if(!Nr(s))return s;if(s.type===Eo){let u=(Array.isArray(s.props.children)?s.props.children:[s.props.children]).filter(o=>!i(o));return u.length===0?null:{...s,props:{...s.props,children:u}}}return s}):e;return(Array.isArray(a)?a.some(s=>s!==null):a!==null)?_("section",{className:t,...n,children:a}):null}return _("section",{className:t,...n,children:e})},(e,t)=>Te(e,t));Gf.displayName="MarkdownSection";var wx=({node:e,className:t,children:r,...n})=>{var i,a,s;let u=((i=e?.position)==null?void 0:i.start.line)===((a=e?.position)==null?void 0:a.end.line),{mermaid:o,controls:c}=Ze(Ke),d=bo();if(u)return _("code",{className:K("rounded bg-muted px-1.5 py-0.5 font-mono text-sm",t),"data-streamdown":"inline-code",...n,children:r});let f=t?.match(Ix),h=(s=f?.at(1))!=null?s:"",p="";if(Nr(r)&&r.props&&typeof r.props=="object"&&"children"in r.props&&typeof r.props.children=="string"?p=r.props.children:typeof r=="string"&&(p=r),h==="mermaid"&&d){let k=ho(c,"mermaid"),I=Mi(c,"download"),y=Mi(c,"copy"),D=Mi(c,"fullscreen"),L=Mi(c,"panZoom"),B=k&&(I||y||D);return _(ff,{fallback:_(gf,{}),children:oe("div",{className:K("group relative my-4 h-auto rounded-xl border p-4",t),"data-streamdown":"mermaid-block",children:[B?oe("div",{className:"flex items-center justify-end gap-2",children:[I?_(gx,{chart:p,config:o?.config}):null,y?_(pf,{code:p}):null,D?_(Tx,{chart:p,config:o?.config}):null]}):null,_(Sx,{chart:p,config:o?.config,showControls:L})]})})}let g=ho(c,"code");return _(ff,{fallback:_(gf,{}),children:_(Cx,{className:K("overflow-x-auto border-border border-t",t),code:p,language:h,children:g?oe(Vt,{children:[_(lx,{code:p,language:h}),_(pf,{})]}):null})})},Wf=he(wx,(e,t)=>e.className===t.className&&Fi(e.node,t.node));Wf.displayName="MarkdownCode";var $f=he(dx,(e,t)=>e.className===t.className&&Fi(e.node,t.node));$f.displayName="MarkdownImg";var Qf=he(({children:e,className:t,node:r,...n})=>{var i,a;let s=(Array.isArray(e)?e:[e]).filter(u=>u!=null&&u!=="");if(s.length===1&&Nr(s[0])){let u=s[0].props.node,o=u?.tagName;if(o==="img")return _(Vt,{children:e});if(o==="code"&&((i=u?.position)==null?void 0:i.start.line)!==((a=u?.position)==null?void 0:a.end.line))return _(Vt,{children:e})}return _("p",{className:t,...n,children:e})},(e,t)=>Te(e,t));Qf.displayName="MarkdownParagraph";var Lx={ol:Eo,li:Sf,ul:If,hr:Nf,strong:wf,a:Lf,h1:Rf,h2:Df,h3:Of,h4:Pf,h5:Mf,h6:vf,table:Bf,thead:Ff,tbody:Hf,tr:Uf,th:zf,td:qf,blockquote:Vf,code:Wf,img:$f,pre:({children:e})=>e,sup:Yf,sub:jf,p:Qf,section:Gf},bf=[],Ef={allowDangerousHtml:!0},vi=new WeakMap,Rx=class{constructor(){this.cache=new Map,this.keyCache=new WeakMap,this.maxSize=100}generateCacheKey(e){let t=this.keyCache.get(e);if(t)return t;let r=e.rehypePlugins,n=e.remarkPlugins,i=e.remarkRehypeOptions;if(!(r||n||i)){let d="default";return this.keyCache.set(e,d),d}let a=d=>{if(!d||d.length===0)return"";let f="";for(let h=0;h<d.length;h+=1){let p=d[h];if(h>0&&(f+=","),Array.isArray(p)){let[g,k]=p;if(typeof g=="function"){let I=vi.get(g);I||(I=g.name,vi.set(g,I)),f+=I}else f+=String(g);f+=":",f+=JSON.stringify(k)}else if(typeof p=="function"){let g=vi.get(p);g||(g=p.name,vi.set(p,g)),f+=g}else f+=String(p)}return f},s=a(r),u=a(n),o=i?JSON.stringify(i):"",c=`${u}::${s}::${o}`;return this.keyCache.set(e,c),c}get(e){let t=this.generateCacheKey(e),r=this.cache.get(t);return r&&(this.cache.delete(t),this.cache.set(t,r)),r}set(e,t){let r=this.generateCacheKey(e);if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(r,t)}clear(){this.cache.clear()}},Tf=new Rx,Xf=e=>{let t=Dx(e),r=e.children||"";return Px(t.runSync(t.parse(r),r),e)},Dx=e=>{let t=Tf.get(e);if(t)return t;let r=Ox(e);return Tf.set(e,r),r},Ox=e=>{let t=e.rehypePlugins||bf,r=e.remarkPlugins||bf,n=e.remarkRehypeOptions?{...Ef,...e.remarkRehypeOptions}:Ef;return Qs().use(xi).use(r).use(_i,n).use(t)},Px=(e,t)=>Rs(e,{Fragment:Vt,components:t.components,ignoreInvalidStyle:!0,jsx:_,jsxs:oe,passKeys:!0,passNode:!0}),Mx=/\[\^[^\]\s]{1,200}\](?!:)/,vx=/\[\^[^\]\s]{1,200}\]:/,Bx=/<\/(\w+)>/,Fx=/<(\w+)[\s>]/,lo=e=>{let t=0;for(;t<e.length&&(e[t]===" "||e[t]===" "||e[t]===`
113
+ `)},Ax=({children:e,className:t,onCopy:r,onError:n,timeout:i=2e3})=>{let[a,s]=ye(!1),[u,o]=ye(!1),c=bt(null),d=bt(0),{isAnimating:f}=Ze(Ke),h=async g=>{var k,I;if(typeof window>"u"||!((k=navigator?.clipboard)!=null&&k.write)){n?.(new Error("Clipboard API not available"));return}try{let y=(I=c.current)==null?void 0:I.closest('[data-streamdown="table-wrapper"]'),D=y?.querySelector("table");if(!D){n?.(new Error("Table not found"));return}let L=_f(D),B=g==="csv"?Cf(L):xx(L),z=new ClipboardItem({"text/plain":new Blob([B],{type:"text/plain"}),"text/html":new Blob([D.outerHTML],{type:"text/html"})});await navigator.clipboard.write([z]),o(!0),s(!1),r?.(g),d.current=window.setTimeout(()=>o(!1),i)}catch(y){n?.(y)}};Xe(()=>{let g=k=>{let I=k.composedPath();c.current&&!I.includes(c.current)&&s(!1)};return document.addEventListener("mousedown",g),()=>{document.removeEventListener("mousedown",g),window.clearTimeout(d.current)}},[]);let p=u?mo:go;return oe("div",{className:"relative",ref:c,children:[_("button",{className:K("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",t),disabled:f,onClick:()=>s(!a),title:"Copy table",type:"button",children:e??_(p,{size:14})}),a?oe("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[120px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[_("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>h("csv"),title:"Copy table as CSV",type:"button",children:"CSV"}),_("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>h("tsv"),title:"Copy table as TSV",type:"button",children:"TSV"})]}):null]})},yx=({children:e,className:t,onDownload:r,onError:n})=>{let[i,a]=ye(!1),s=bt(null),{isAnimating:u}=Ze(Ke),o=c=>{var d;try{let f=(d=s.current)==null?void 0:d.closest('[data-streamdown="table-wrapper"]'),h=f?.querySelector("table");if(!h){n?.(new Error("Table not found"));return}let p=_f(h),g=c==="csv"?Cf(p):kx(p);wr(`table.${c==="csv"?"csv":"md"}`,g,c==="csv"?"text/csv":"text/markdown"),a(!1),r?.(c)}catch(f){n?.(f)}};return Xe(()=>{let c=d=>{let f=d.composedPath();s.current&&!f.includes(s.current)&&a(!1)};return document.addEventListener("mousedown",c),()=>{document.removeEventListener("mousedown",c)}},[]),oe("div",{className:"relative",ref:s,children:[_("button",{className:K("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",t),disabled:u,onClick:()=>a(!i),title:"Download table",type:"button",children:e??_(Bi,{size:14})}),i?oe("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[120px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[_("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>o("csv"),title:"Download table as CSV",type:"button",children:"CSV"}),_("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>o("markdown"),title:"Download table as Markdown",type:"button",children:"Markdown"})]}):null]})},_x=({children:e,className:t,showControls:r,...n})=>oe("div",{className:"my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",children:[r?oe("div",{className:"flex items-center justify-end gap-1",children:[_(Ax,{}),_(yx,{})]}):null,_("div",{className:"overflow-x-auto",children:_("table",{className:K("w-full border-collapse border border-border",t),"data-streamdown":"table",...n,children:e})})]}),Cx=xf(()=>import("./code-block-37QAKDTI-IIYKFI5S.js").then(e=>({default:e.CodeBlock}))),Sx=xf(()=>import("./mermaid-4DMBBIKO-PAA57QRQ.js").then(e=>({default:e.Mermaid}))),Ix=/language-([^\s]+)/;function Fi(e,t){if(!(e!=null&&e.position||t!=null&&t.position))return!0;if(!(e!=null&&e.position&&t!=null&&t.position))return!1;let r=e.position.start,n=t.position.start,i=e.position.end,a=t.position.end;return r?.line===n?.line&&r?.column===n?.column&&i?.line===a?.line&&i?.column===a?.column}function Te(e,t){return e.className===t.className&&Fi(e.node,t.node)}var ho=(e,t)=>typeof e=="boolean"?e:e[t]!==!1,Mi=(e,t)=>{if(typeof e=="boolean")return e;let r=e.mermaid;return r===!1?!1:r===!0||r===void 0?!0:r[t]!==!1},Eo=he(({children:e,className:t,node:r,...n})=>_("ol",{className:K("list-inside list-decimal whitespace-normal [li_&]:pl-6",t),"data-streamdown":"ordered-list",...n,children:e}),(e,t)=>Te(e,t));Eo.displayName="MarkdownOl";var Sf=he(({children:e,className:t,node:r,...n})=>_("li",{className:K("py-1 [&>p]:inline",t),"data-streamdown":"list-item",...n,children:e}),(e,t)=>e.className===t.className&&Fi(e.node,t.node));Sf.displayName="MarkdownLi";var If=he(({children:e,className:t,node:r,...n})=>_("ul",{className:K("list-inside list-disc whitespace-normal [li_&]:pl-6",t),"data-streamdown":"unordered-list",...n,children:e}),(e,t)=>Te(e,t));If.displayName="MarkdownUl";var Nf=he(({className:e,node:t,...r})=>_("hr",{className:K("my-6 border-border",e),"data-streamdown":"horizontal-rule",...r}),(e,t)=>Te(e,t));Nf.displayName="MarkdownHr";var wf=he(({children:e,className:t,node:r,...n})=>_("span",{className:K("font-semibold",t),"data-streamdown":"strong",...n,children:e}),(e,t)=>Te(e,t));wf.displayName="MarkdownStrong";var Nx=({children:e,className:t,href:r,node:n,...i})=>{let{linkSafety:a}=Ze(Ke),[s,u]=ye(!1),o=r==="streamdown:incomplete-link",c=je(async p=>{if(!(!(a!=null&&a.enabled&&r)||o)){if(p.preventDefault(),a.onLinkCheck&&await a.onLinkCheck(r)){window.open(r,"_blank","noreferrer");return}u(!0)}},[a,r,o]),d=je(()=>{r&&window.open(r,"_blank","noreferrer")},[r]),f=je(()=>{u(!1)},[]),h={url:r??"",isOpen:s,onClose:f,onConfirm:d};return a!=null&&a.enabled&&r?oe(Vt,{children:[_("button",{className:K("wrap-anywhere appearance-none text-left font-medium text-primary underline",t),"data-incomplete":o,"data-streamdown":"link",onClick:c,type:"button",children:e}),a.renderModal?a.renderModal(h):_(px,{...h})]}):_("a",{className:K("wrap-anywhere font-medium text-primary underline",t),"data-incomplete":o,"data-streamdown":"link",href:r,rel:"noreferrer",target:"_blank",...i,children:e})},Lf=he(Nx,(e,t)=>Te(e,t)&&e.href===t.href);Lf.displayName="MarkdownA";var Rf=he(({children:e,className:t,node:r,...n})=>_("h1",{className:K("mt-6 mb-2 font-semibold text-3xl",t),"data-streamdown":"heading-1",...n,children:e}),(e,t)=>Te(e,t));Rf.displayName="MarkdownH1";var Df=he(({children:e,className:t,node:r,...n})=>_("h2",{className:K("mt-6 mb-2 font-semibold text-2xl",t),"data-streamdown":"heading-2",...n,children:e}),(e,t)=>Te(e,t));Df.displayName="MarkdownH2";var Of=he(({children:e,className:t,node:r,...n})=>_("h3",{className:K("mt-6 mb-2 font-semibold text-xl",t),"data-streamdown":"heading-3",...n,children:e}),(e,t)=>Te(e,t));Of.displayName="MarkdownH3";var Pf=he(({children:e,className:t,node:r,...n})=>_("h4",{className:K("mt-6 mb-2 font-semibold text-lg",t),"data-streamdown":"heading-4",...n,children:e}),(e,t)=>Te(e,t));Pf.displayName="MarkdownH4";var Mf=he(({children:e,className:t,node:r,...n})=>_("h5",{className:K("mt-6 mb-2 font-semibold text-base",t),"data-streamdown":"heading-5",...n,children:e}),(e,t)=>Te(e,t));Mf.displayName="MarkdownH5";var vf=he(({children:e,className:t,node:r,...n})=>_("h6",{className:K("mt-6 mb-2 font-semibold text-sm",t),"data-streamdown":"heading-6",...n,children:e}),(e,t)=>Te(e,t));vf.displayName="MarkdownH6";var Bf=he(({children:e,className:t,node:r,...n})=>{let{controls:i}=Ze(Ke),a=ho(i,"table");return _(_x,{className:t,showControls:a,...n,children:e})},(e,t)=>Te(e,t));Bf.displayName="MarkdownTable";var Ff=he(({children:e,className:t,node:r,...n})=>_("thead",{className:K("bg-muted/80",t),"data-streamdown":"table-header",...n,children:e}),(e,t)=>Te(e,t));Ff.displayName="MarkdownThead";var Hf=he(({children:e,className:t,node:r,...n})=>_("tbody",{className:K("divide-y divide-border bg-muted/40",t),"data-streamdown":"table-body",...n,children:e}),(e,t)=>Te(e,t));Hf.displayName="MarkdownTbody";var Uf=he(({children:e,className:t,node:r,...n})=>_("tr",{className:K("border-border border-b",t),"data-streamdown":"table-row",...n,children:e}),(e,t)=>Te(e,t));Uf.displayName="MarkdownTr";var zf=he(({children:e,className:t,node:r,...n})=>_("th",{className:K("whitespace-nowrap px-4 py-2 text-left font-semibold text-sm",t),"data-streamdown":"table-header-cell",...n,children:e}),(e,t)=>Te(e,t));zf.displayName="MarkdownTh";var qf=he(({children:e,className:t,node:r,...n})=>_("td",{className:K("px-4 py-2 text-sm",t),"data-streamdown":"table-cell",...n,children:e}),(e,t)=>Te(e,t));qf.displayName="MarkdownTd";var Vf=he(({children:e,className:t,node:r,...n})=>_("blockquote",{className:K("my-4 border-muted-foreground/30 border-l-4 pl-4 text-muted-foreground italic",t),"data-streamdown":"blockquote",...n,children:e}),(e,t)=>Te(e,t));Vf.displayName="MarkdownBlockquote";var Yf=he(({children:e,className:t,node:r,...n})=>_("sup",{className:K("text-sm",t),"data-streamdown":"superscript",...n,children:e}),(e,t)=>Te(e,t));Yf.displayName="MarkdownSup";var jf=he(({children:e,className:t,node:r,...n})=>_("sub",{className:K("text-sm",t),"data-streamdown":"subscript",...n,children:e}),(e,t)=>Te(e,t));jf.displayName="MarkdownSub";var Gf=he(({children:e,className:t,node:r,...n})=>{if("data-footnotes"in n){let i=s=>{var u,o;if(!Nr(s))return!1;let c=Array.isArray(s.props.children)?s.props.children:[s.props.children],d=!1,f=!1;for(let h of c)if(h){if(typeof h=="string")h.trim()!==""&&(d=!0);else if(Nr(h))if(((u=h.props)==null?void 0:u["data-footnote-backref"])!==void 0)f=!0;else{let p=Array.isArray(h.props.children)?h.props.children:[h.props.children];for(let g of p){if(typeof g=="string"&&g.trim()!==""){d=!0;break}if(Nr(g)&&((o=g.props)==null?void 0:o["data-footnote-backref"])===void 0){d=!0;break}}}}return f&&!d},a=Array.isArray(e)?e.map(s=>{if(!Nr(s))return s;if(s.type===Eo){let u=(Array.isArray(s.props.children)?s.props.children:[s.props.children]).filter(o=>!i(o));return u.length===0?null:{...s,props:{...s.props,children:u}}}return s}):e;return(Array.isArray(a)?a.some(s=>s!==null):a!==null)?_("section",{className:t,...n,children:a}):null}return _("section",{className:t,...n,children:e})},(e,t)=>Te(e,t));Gf.displayName="MarkdownSection";var wx=({node:e,className:t,children:r,...n})=>{var i,a,s;let u=((i=e?.position)==null?void 0:i.start.line)===((a=e?.position)==null?void 0:a.end.line),{mermaid:o,controls:c}=Ze(Ke),d=bo();if(u)return _("code",{className:K("rounded bg-muted px-1.5 py-0.5 font-mono text-sm",t),"data-streamdown":"inline-code",...n,children:r});let f=t?.match(Ix),h=(s=f?.at(1))!=null?s:"",p="";if(Nr(r)&&r.props&&typeof r.props=="object"&&"children"in r.props&&typeof r.props.children=="string"?p=r.props.children:typeof r=="string"&&(p=r),h==="mermaid"&&d){let k=ho(c,"mermaid"),I=Mi(c,"download"),y=Mi(c,"copy"),D=Mi(c,"fullscreen"),L=Mi(c,"panZoom"),B=k&&(I||y||D);return _(ff,{fallback:_(gf,{}),children:oe("div",{className:K("group relative my-4 h-auto rounded-xl border p-4",t),"data-streamdown":"mermaid-block",children:[B?oe("div",{className:"flex items-center justify-end gap-2",children:[I?_(gx,{chart:p,config:o?.config}):null,y?_(pf,{code:p}):null,D?_(Tx,{chart:p,config:o?.config}):null]}):null,_(Sx,{chart:p,config:o?.config,showControls:L})]})})}let g=ho(c,"code");return _(ff,{fallback:_(gf,{}),children:_(Cx,{className:K("overflow-x-auto border-border border-t",t),code:p,language:h,children:g?oe(Vt,{children:[_(lx,{code:p,language:h}),_(pf,{})]}):null})})},Wf=he(wx,(e,t)=>e.className===t.className&&Fi(e.node,t.node));Wf.displayName="MarkdownCode";var $f=he(dx,(e,t)=>e.className===t.className&&Fi(e.node,t.node));$f.displayName="MarkdownImg";var Qf=he(({children:e,className:t,node:r,...n})=>{var i,a;let s=(Array.isArray(e)?e:[e]).filter(u=>u!=null&&u!=="");if(s.length===1&&Nr(s[0])){let u=s[0].props.node,o=u?.tagName;if(o==="img")return _(Vt,{children:e});if(o==="code"&&((i=u?.position)==null?void 0:i.start.line)!==((a=u?.position)==null?void 0:a.end.line))return _(Vt,{children:e})}return _("p",{className:t,...n,children:e})},(e,t)=>Te(e,t));Qf.displayName="MarkdownParagraph";var Lx={ol:Eo,li:Sf,ul:If,hr:Nf,strong:wf,a:Lf,h1:Rf,h2:Df,h3:Of,h4:Pf,h5:Mf,h6:vf,table:Bf,thead:Ff,tbody:Hf,tr:Uf,th:zf,td:qf,blockquote:Vf,code:Wf,img:$f,pre:({children:e})=>e,sup:Yf,sub:jf,p:Qf,section:Gf},bf=[],Ef={allowDangerousHtml:!0},vi=new WeakMap,Rx=class{constructor(){this.cache=new Map,this.keyCache=new WeakMap,this.maxSize=100}generateCacheKey(e){let t=this.keyCache.get(e);if(t)return t;let r=e.rehypePlugins,n=e.remarkPlugins,i=e.remarkRehypeOptions;if(!(r||n||i)){let d="default";return this.keyCache.set(e,d),d}let a=d=>{if(!d||d.length===0)return"";let f="";for(let h=0;h<d.length;h+=1){let p=d[h];if(h>0&&(f+=","),Array.isArray(p)){let[g,k]=p;if(typeof g=="function"){let I=vi.get(g);I||(I=g.name,vi.set(g,I)),f+=I}else f+=String(g);f+=":",f+=JSON.stringify(k)}else if(typeof p=="function"){let g=vi.get(p);g||(g=p.name,vi.set(p,g)),f+=g}else f+=String(p)}return f},s=a(r),u=a(n),o=i?JSON.stringify(i):"",c=`${u}::${s}::${o}`;return this.keyCache.set(e,c),c}get(e){let t=this.generateCacheKey(e),r=this.cache.get(t);return r&&(this.cache.delete(t),this.cache.set(t,r)),r}set(e,t){let r=this.generateCacheKey(e);if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(r,t)}clear(){this.cache.clear()}},Tf=new Rx,Xf=e=>{let t=Dx(e),r=e.children||"";return Px(t.runSync(t.parse(r),r),e)},Dx=e=>{let t=Tf.get(e);if(t)return t;let r=Ox(e);return Tf.set(e,r),r},Ox=e=>{let t=e.rehypePlugins||bf,r=e.remarkPlugins||bf,n=e.remarkRehypeOptions?{...Ef,...e.remarkRehypeOptions}:Ef;return Qs().use(xi).use(r).use(_i,n).use(t)},Px=(e,t)=>Rs(e,{Fragment:Vt,components:t.components,ignoreInvalidStyle:!0,jsx:_,jsxs:oe,passKeys:!0,passNode:!0}),Mx=/\[\^[^\]\s]{1,200}\](?!:)/,vx=/\[\^[^\]\s]{1,200}\]:/,Bx=/<\/(\w+)>/,Fx=/<(\w+)[\s>]/,lo=e=>{let t=0;for(;t<e.length&&(e[t]===" "||e[t]===" "||e[t]===`
114
114
  `||e[t]==="\r");)t+=1;return t+1<e.length&&e[t]==="$"&&e[t+1]==="$"},Hx=e=>{let t=e.length-1;for(;t>=0&&(e[t]===" "||e[t]===" "||e[t]===`
115
115
  `||e[t]==="\r");)t-=1;return t>=1&&e[t]==="$"&&e[t-1]==="$"},co=e=>{let t=0;for(let r=0;r<e.length-1;r+=1)e[r]==="$"&&e[r+1]==="$"&&(t+=1,r+=1);return t},Ux=e=>{let t=Mx.test(e),r=vx.test(e);if(t||r)return[e];let n=Ye.lex(e,{gfm:!0}),i=[],a=[];for(let s of n){let u=s.raw,o=i.length;if(a.length>0){if(i[o-1]+=u,s.type==="html"){let c=u.match(Bx);if(c){let d=c[1];a.at(-1)===d&&a.pop()}}continue}if(s.type==="html"&&s.block){let c=u.match(Fx);if(c){let d=c[1];u.includes(`</${d}>`)||a.push(d)}}if(u.trim()==="$$"&&o>0){let c=i[o-1],d=lo(c),f=co(c);if(d&&f%2===1){i[o-1]=c+u;continue}}if(o>0&&Hx(u)){let c=i[o-1],d=lo(c),f=co(c),h=co(u);if(d&&f%2===1&&!lo(u)&&h===1){i[o-1]=c+u;continue}}i.push(u)}return i},zx={raw:$n,sanitize:[Qn,{}],harden:[wo,{allowedImagePrefixes:["*"],allowedLinkPrefixes:["*"],allowedProtocols:["*"],defaultOrigin:void 0,allowDataImages:!0}]},qx={gfm:[di,{}]},Vx=Object.values(zx),Yx=Object.values(qx),jx={block:" \u258B",circle:" \u25CF"},Gx={shikiTheme:["github-light","github-dark"],controls:!0,isAnimating:!1,mode:"streaming",mermaid:void 0,linkSafety:{enabled:!0}},Ke=po(Gx),Kf=he(({content:e,shouldParseIncompleteMarkdown:t,index:r,...n})=>_(Xf,{...n,children:e}),(e,t)=>{if(e.content!==t.content||e.index!==t.index)return!1;if(e.components!==t.components){let r=Object.keys(e.components||{}),n=Object.keys(t.components||{});if(r.length!==n.length||r.some(i=>{var a,s;return((a=e.components)==null?void 0:a[i])!==((s=t.components)==null?void 0:s[i])}))return!1}return!(e.rehypePlugins!==t.rehypePlugins||e.remarkPlugins!==t.remarkPlugins)});Kf.displayName="Block";var Wx=["github-light","github-dark"],$x=he(({children:e,mode:t="streaming",parseIncompleteMarkdown:r=!0,components:n,rehypePlugins:i=Vx,remarkPlugins:a=Yx,className:s,shikiTheme:u=Wx,mermaid:o,controls:c=!0,isAnimating:d=!1,BlockComponent:f=Kf,parseMarkdownIntoBlocksFn:h=Ux,caret:p,plugins:g,remend:k,linkSafety:I={enabled:!0},...y})=>{let D=K2(),[L,B]=Z2(),z=lt(()=>typeof e!="string"?"":t==="streaming"&&r?rc(e,k):e,[e,t,r,k]),N=lt(()=>h(z),[z,h]),[Z,v]=ye(N);Xe(()=>{t==="streaming"?B(()=>{v(N)}):v(N)},[N,t]);let W=t==="streaming"?Z:N,C=lt(()=>W.map((X,ie)=>`${D}-${ie}`),[W.length,D]),ue=lt(()=>{var X,ie;return{shikiTheme:(ie=(X=g?.code)==null?void 0:X.getThemes())!=null?ie:u,controls:c,isAnimating:d,mode:t,mermaid:o,linkSafety:I}},[u,c,d,t,o,I,g?.code]),U=lt(()=>({...Lx,...n}),[n]),F=lt(()=>{let X=[];return g!=null&&g.cjk&&(X=[...X,...g.cjk.remarkPluginsBefore]),X=[...X,...a],g!=null&&g.cjk&&(X=[...X,...g.cjk.remarkPluginsAfter]),g!=null&&g.math&&(X=[...X,g.math.remarkPlugin]),X},[a,g?.math,g?.cjk]),$=lt(()=>g!=null&&g.math?[...i,g.math.rehypePlugin]:i,[i,g?.math]),Q=lt(()=>p&&d?{"--streamdown-caret":`"${jx[p]}"`}:void 0,[p,d]);return t==="static"?_(fo.Provider,{value:g??null,children:_(Ke.Provider,{value:ue,children:_("div",{className:K("space-y-4 whitespace-normal *:first:mt-0 *:last:mb-0",s),children:_(Xf,{components:U,rehypePlugins:$,remarkPlugins:F,...y,children:e})})})}):_(fo.Provider,{value:g??null,children:_(Ke.Provider,{value:ue,children:oe("div",{className:K("space-y-4 whitespace-normal *:first:mt-0 *:last:mb-0",p?"*:last:after:inline *:last:after:align-baseline *:last:after:content-(--streamdown-caret)":null,s),style:Q,children:[W.length===0&&p&&d&&_("span",{}),W.map((X,ie)=>_(f,{components:U,content:X,index:ie,rehypePlugins:$,remarkPlugins:F,shouldParseIncompleteMarkdown:r,...y},C[ie]))]})})})},(e,t)=>e.children===t.children&&e.shikiTheme===t.shikiTheme&&e.isAnimating===t.isAnimating&&e.mode===t.mode&&e.plugins===t.plugins&&e.className===t.className&&e.linkSafety===t.linkSafety);$x.displayName="Streamdown";var Qx=({children:e,className:t,minZoom:r=.5,maxZoom:n=3,zoomStep:i=.1,showControls:a=!0,initialZoom:s=1,fullscreen:u=!1})=>{let o=bt(null),c=bt(null),[d,f]=ye(s),[h,p]=ye({x:0,y:0}),[g,k]=ye(!1),[I,y]=ye({x:0,y:0}),[D,L]=ye({x:0,y:0}),B=je(U=>{f(F=>Math.max(r,Math.min(n,F+U)))},[r,n]),z=je(()=>{B(i)},[B,i]),N=je(()=>{B(-i)},[B,i]),Z=je(()=>{f(s),p({x:0,y:0})},[s]),v=je(U=>{U.preventDefault();let F=U.deltaY>0?-i:i;B(F)},[B,i]),W=je(U=>{if(U.button!==0||U.isPrimary===!1)return;k(!0),y({x:U.clientX,y:U.clientY}),L(h);let F=U.currentTarget;F instanceof HTMLElement&&F.setPointerCapture(U.pointerId)},[h]),C=je(U=>{if(!g)return;U.preventDefault();let F=U.clientX-I.x,$=U.clientY-I.y;p({x:D.x+F,y:D.y+$})},[g,I,D]),ue=je(U=>{k(!1);let F=U.currentTarget;F instanceof HTMLElement&&F.releasePointerCapture(U.pointerId)},[]);return Xe(()=>{let U=o.current;if(U)return U.addEventListener("wheel",v,{passive:!1}),()=>{U.removeEventListener("wheel",v)}},[v]),Xe(()=>{let U=c.current;if(U&&g)return document.body.style.userSelect="none",U.addEventListener("pointermove",C,{passive:!1}),U.addEventListener("pointerup",ue),U.addEventListener("pointercancel",ue),()=>{document.body.style.userSelect="",U.removeEventListener("pointermove",C),U.removeEventListener("pointerup",ue),U.removeEventListener("pointercancel",ue)}},[g,C,ue]),oe("div",{className:K("relative flex flex-col",u?"h-full w-full":"min-h-28 w-full",t),ref:o,style:{cursor:g?"grabbing":"grab"},children:[a?oe("div",{className:K("absolute z-10 flex flex-col gap-1 rounded-md border border-border bg-background/90 p-1 shadow-sm backdrop-blur-sm",u?"bottom-4 left-4":"bottom-2 left-2"),children:[_("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",disabled:d>=n,onClick:z,title:"Zoom in",type:"button",children:_(sx,{size:16})}),_("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",disabled:d<=r,onClick:N,title:"Zoom out",type:"button",children:_(ox,{size:16})}),_("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:Z,title:"Reset zoom and pan",type:"button",children:_(ax,{size:16})})]}):null,_("div",{className:K("flex-1 origin-center transition-transform duration-150 ease-out",u?"flex h-full w-full items-center justify-center":"flex w-full items-center justify-center"),onPointerDown:W,ref:c,role:"application",style:{transform:`translate(${h.x}px, ${h.y}px) scale(${d})`,transformOrigin:"center center",touchAction:"none",willChange:"transform"},children:e})]})},Xx=({chart:e,className:t,config:r,fullscreen:n=!1,showControls:i=!0})=>{let[a,s]=ye(null),[u,o]=ye(!1),[c,d]=ye(""),[f,h]=ye(""),[p,g]=ye(0),{mermaid:k}=Ze(Ke),I=bo(),y=k?.errorComponent,{shouldRender:D,containerRef:L}=rx({immediate:n});if(Xe(()=>{if(D){if(!I){s("Mermaid plugin not available. Please add the mermaid plugin to enable diagram rendering.");return}(async()=>{try{s(null),o(!0);let z=I.getMermaid(r),N=e.split("").reduce((W,C)=>(W<<5)-W+C.charCodeAt(0)|0,0),Z=`mermaid-${Math.abs(N)}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,{svg:v}=await z.render(Z,e);d(v),h(v)}catch(z){if(!(f||c)){let N=z instanceof Error?z.message:"Failed to render Mermaid chart";s(N)}}finally{o(!1)}})()}},[e,r,p,D,I]),!(D||c||f))return _("div",{className:K("my-4 min-h-[200px]",t),ref:L});if(u&&!c&&!f)return _("div",{className:K("my-4 flex justify-center p-4",t),ref:L,children:oe("div",{className:"flex items-center space-x-2 text-muted-foreground",children:[_("div",{className:"h-4 w-4 animate-spin rounded-full border-current border-b-2"}),_("span",{className:"text-sm",children:"Loading diagram..."})]})});if(a&&!c&&!f)return y?_("div",{ref:L,children:_(y,{chart:e,error:a,retry:()=>g(N=>N+1)})}):oe("div",{className:K("rounded-lg border border-red-200 bg-red-50 p-4",t),ref:L,children:[oe("p",{className:"font-mono text-red-700 text-sm",children:["Mermaid Error: ",a]}),oe("details",{className:"mt-2",children:[_("summary",{className:"cursor-pointer text-red-600 text-xs",children:"Show Code"}),_("pre",{className:"mt-2 overflow-x-auto rounded bg-red-100 p-2 text-red-800 text-xs",children:e})]})]});let B=c||f;return _("div",{className:K("size-full",t),"data-streamdown":"mermaid",ref:L,children:_(Qx,{className:K(n?"size-full overflow-hidden":"my-4 overflow-hidden",t),fullscreen:n,maxZoom:3,minZoom:.5,showControls:i,zoomStep:.1,children:_("div",{"aria-label":"Mermaid chart",className:K("flex justify-center",n?"size-full items-center":null),dangerouslySetInnerHTML:{__html:B},role:"img"})})})};export{ic as a,yN as b,re as c,xe as d,Me as e,Ft as f,rt as g,$o as h,yt as i,_t as j,$e as k,Nn as l,_a as m,Cn as n,Sn as o,Ss as p,K as q,ux as r,pR as s,Ke as t,$x as u,Xx as v};
116
- //# sourceMappingURL=chunk-HVAT4SNH.js.map
116
+ //# sourceMappingURL=chunk-5JBHQYU5.js.map