drizzle-cube 0.4.20 → 0.4.21

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 (42) hide show
  1. package/dist/adapters/anthropic-BTkjgFpT.cjs +1 -0
  2. package/dist/adapters/anthropic-CTu9E801.js +126 -0
  3. package/dist/adapters/express/index.cjs +6 -6
  4. package/dist/adapters/express/index.js +119 -116
  5. package/dist/adapters/fastify/index.cjs +6 -6
  6. package/dist/adapters/fastify/index.js +113 -110
  7. package/dist/adapters/google-BAK9pnQf.cjs +2 -0
  8. package/dist/adapters/google-DficVAsJ.js +146 -0
  9. package/dist/adapters/{handler-CbDMdSY5.js → handler-9Rdn7zM2.js} +534 -461
  10. package/dist/adapters/handler-B-tEntiU.cjs +39 -0
  11. package/dist/adapters/hono/index.cjs +6 -6
  12. package/dist/adapters/hono/index.js +199 -196
  13. package/dist/adapters/index-BIMhF5KZ.cjs +23 -0
  14. package/dist/adapters/index-BgCeQBuN.cjs +2 -0
  15. package/dist/adapters/index-C45_meK_.js +719 -0
  16. package/dist/adapters/index-CFEJ62GJ.js +5337 -0
  17. package/dist/adapters/nextjs/index.cjs +5 -5
  18. package/dist/adapters/nextjs/index.js +245 -242
  19. package/dist/adapters/openai-CUSRuKTk.js +131 -0
  20. package/dist/adapters/openai-mLo2MCat.cjs +1 -0
  21. package/dist/client/components/AgenticNotebook/AgentChatPanel.d.ts +3 -0
  22. package/dist/client/components/AgenticNotebook/index.d.ts +6 -0
  23. package/dist/client/hooks/useAgentChat.d.ts +6 -0
  24. package/dist/client/index.js +730 -697
  25. package/dist/client/index.js.map +1 -1
  26. package/dist/client/styles.css +1 -1
  27. package/dist/client-bundle-stats.html +1 -1
  28. package/dist/server/anthropic-BTkjgFpT.cjs +1 -0
  29. package/dist/server/anthropic-CTu9E801.js +126 -0
  30. package/dist/server/google-BAK9pnQf.cjs +2 -0
  31. package/dist/server/google-DficVAsJ.js +146 -0
  32. package/dist/server/index-BIMhF5KZ.cjs +23 -0
  33. package/dist/server/index-BgCeQBuN.cjs +2 -0
  34. package/dist/server/index-C45_meK_.js +719 -0
  35. package/dist/server/index-CFEJ62GJ.js +5337 -0
  36. package/dist/server/index.cjs +48 -46
  37. package/dist/server/index.d.ts +37 -10
  38. package/dist/server/index.js +1974 -1901
  39. package/dist/server/openai-CUSRuKTk.js +131 -0
  40. package/dist/server/openai-mLo2MCat.cjs +1 -0
  41. package/package.json +12 -2
  42. package/dist/adapters/handler-DtdjM1Vx.cjs +0 -37
@@ -1,11 +1,11 @@
1
- "use strict";var O=Object.create;var j=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty;var H=(l,n,v,R)=>{if(n&&typeof n=="object"||typeof n=="function")for(let f of J(n))!D.call(l,f)&&f!==v&&j(l,f,{get:()=>n[f],enumerable:!(R=k(n,f))||R.enumerable});return l};var T=(l,n,v)=>(v=l!=null?O(L(l)):{},H(n||!l||!l.__esModule?j(v,"default",{value:l,enumerable:!0}):v,l));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("../mcp-transport-8u9G5oNa.cjs"),a=require("../utils.cjs"),q=function(n,v,R){const{cubes:f,drizzle:I,schema:A,extractSecurityContext:g,engineType:M,cors:P,basePath:h="/cubejs-api/v1",bodyLimit:C=10485760,cache:N,mcp:x={enabled:!0},agent:w}=v;if(!f||f.length===0)return R(new Error("At least one cube must be provided in the cubes array"));P&&n.register(import("@fastify/cors"),P),n.addHook("onRequest",async(r,t)=>{r.method==="POST"&&(r.body=void 0)});const d=new u.SemanticLayerCompiler({drizzle:I,schema:A,engineType:M,cache:N});if(f.forEach(r=>{d.registerCube(r)}),n.post(`${h}/load`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(r,t)=>{try{const e=r.body,o=e.query||e,s=await g(r),i=d.validateQuery(o);if(!i.isValid)return t.status(400).send(a.formatErrorResponse(`Query validation failed: ${i.errors.join(", ")}`,400));const c=r.headers["x-cache-control"]==="no-cache",p=await d.executeMultiCubeQuery(o,s,{skipCache:c});return a.formatCubeResponse(o,p,d)}catch(e){return r.log.error(e,"Query execution error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"Query execution failed",500))}}),n.get(`${h}/load`,{schema:{querystring:{type:"object",properties:{query:{type:"string"}},required:["query"]}}},async(r,t)=>{try{const{query:e}=r.query;let o;try{o=JSON.parse(e)}catch{return t.status(400).send(a.formatErrorResponse("Invalid JSON in query parameter",400))}const s=await g(r),i=d.validateQuery(o);if(!i.isValid)return t.status(400).send(a.formatErrorResponse(`Query validation failed: ${i.errors.join(", ")}`,400));const c=r.headers["x-cache-control"]==="no-cache",p=await d.executeMultiCubeQuery(o,s,{skipCache:c});return a.formatCubeResponse(o,p,d)}catch(e){return r.log.error(e,"Query execution error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"Query execution failed",500))}}),n.post(`${h}/batch`,{bodyLimit:C,schema:{body:{type:"object",required:["queries"],properties:{queries:{type:"array",items:{type:"object"}}}}}},async(r,t)=>{try{const{queries:e}=r.body;if(!e||!Array.isArray(e))return t.status(400).send(a.formatErrorResponse('Request body must contain a "queries" array',400));if(e.length===0)return t.status(400).send(a.formatErrorResponse("Queries array cannot be empty",400));const o=await g(r),s=r.headers["x-cache-control"]==="no-cache";return await a.handleBatchRequest(e,o,d,{skipCache:s})}catch(e){return r.log.error(e,"Batch execution error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"Batch execution failed",500))}}),n.get(`${h}/meta`,async(r,t)=>{try{const e=d.getMetadata();return a.formatMetaResponse(e)}catch(e){return r.log.error(e,"Metadata error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"Failed to fetch metadata",500))}}),n.post(`${h}/sql`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(r,t)=>{try{const e=r.body,o=await g(r),s=d.validateQuery(e);if(!s.isValid)return t.status(400).send(a.formatErrorResponse(`Query validation failed: ${s.errors.join(", ")}`,400));const i=e.measures?.[0]||e.dimensions?.[0];if(!i)return t.status(400).send(a.formatErrorResponse("No measures or dimensions specified",400));const c=i.split(".")[0],p=await d.generateSQL(c,e,o);return a.formatSqlResponse(e,p)}catch(e){return r.log.error(e,"SQL generation error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"SQL generation failed",500))}}),n.get(`${h}/sql`,{schema:{querystring:{type:"object",properties:{query:{type:"string"}},required:["query"]}}},async(r,t)=>{try{const{query:e}=r.query,o=JSON.parse(e),s=await g(r),i=d.validateQuery(o);if(!i.isValid)return t.status(400).send(a.formatErrorResponse(`Query validation failed: ${i.errors.join(", ")}`,400));const c=o.measures?.[0]||o.dimensions?.[0];if(!c)return t.status(400).send(a.formatErrorResponse("No measures or dimensions specified",400));const p=c.split(".")[0],E=await d.generateSQL(p,o,s);return a.formatSqlResponse(o,E)}catch(e){return r.log.error(e,"SQL generation error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"SQL generation failed",500))}}),n.post(`${h}/dry-run`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(r,t)=>{try{const e=r.body,o=e.query||e,s=await g(r);return await a.handleDryRun(o,s,d)}catch(e){return r.log.error(e,"Dry-run error"),t.status(400).send({error:e instanceof Error?e.message:"Dry-run validation failed",valid:!1})}}),n.get(`${h}/dry-run`,{schema:{querystring:{type:"object",properties:{query:{type:"string"}},required:["query"]}}},async(r,t)=>{try{const{query:e}=r.query,o=JSON.parse(e),s=await g(r);return await a.handleDryRun(o,s,d)}catch(e){return r.log.error(e,"Dry-run error"),t.status(400).send({error:e instanceof Error?e.message:"Dry-run validation failed",valid:!1})}}),n.post(`${h}/explain`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(r,t)=>{try{const e=r.body,o=e.query||e,s=e.options||{},i=await g(r),c=d.validateQuery(o);return c.isValid?await d.explainQuery(o,i,s):t.status(400).send({error:`Query validation failed: ${c.errors.join(", ")}`})}catch(e){return r.log.error(e,"Explain error"),t.status(500).send({error:e instanceof Error?e.message:"Explain query failed"})}}),w&&n.post(`${h}/agent/chat`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(r,t)=>{try{const{handleAgentChat:e}=await Promise.resolve().then(()=>require("../handler-DtdjM1Vx.cjs")),o=r.body,{message:s,sessionId:i,history:c}=o;if(!s||typeof s!="string")return t.status(400).send({error:"message is required and must be a string"});let p=(w.apiKey||"").trim();if(w.allowClientApiKey){const m=r.headers["x-agent-api-key"];m&&(p=m.trim())}if(!p)return t.status(401).send({error:"No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header."});const E=await g(r),y=w.buildSystemContext?.(E);t.raw.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});try{const m=e({message:s,sessionId:i,history:c,semanticLayer:d,securityContext:E,agentConfig:w,apiKey:p,systemContext:y});for await(const b of m)t.raw.write(`data: ${JSON.stringify(b)}
1
+ "use strict";var N=Object.create;var j=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty;var D=(l,n,v,S)=>{if(n&&typeof n=="object"||typeof n=="function")for(let f of J(n))!K.call(l,f)&&f!==v&&j(l,f,{get:()=>n[f],enumerable:!(S=k(n,f))||S.enumerable});return l};var H=(l,n,v)=>(v=l!=null?N(L(l)):{},D(n||!l||!l.__esModule?j(v,"default",{value:l,enumerable:!0}):v,l));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("../mcp-transport-8u9G5oNa.cjs"),a=require("../utils.cjs"),Q=function(n,v,S){const{cubes:f,drizzle:A,schema:I,extractSecurityContext:m,engineType:O,cors:$,basePath:g="/cubejs-api/v1",bodyLimit:C=10485760,cache:M,mcp:q={enabled:!0},agent:b}=v;if(!f||f.length===0)return S(new Error("At least one cube must be provided in the cubes array"));$&&n.register(import("@fastify/cors"),$),n.addHook("onRequest",async(r,t)=>{r.method==="POST"&&(r.body=void 0)});const u=new d.SemanticLayerCompiler({drizzle:A,schema:I,engineType:O,cache:M});if(f.forEach(r=>{u.registerCube(r)}),n.post(`${g}/load`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(r,t)=>{try{const e=r.body,o=e.query||e,s=await m(r),i=u.validateQuery(o);if(!i.isValid)return t.status(400).send(a.formatErrorResponse(`Query validation failed: ${i.errors.join(", ")}`,400));const c=r.headers["x-cache-control"]==="no-cache",p=await u.executeMultiCubeQuery(o,s,{skipCache:c});return a.formatCubeResponse(o,p,u)}catch(e){return r.log.error(e,"Query execution error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"Query execution failed",500))}}),n.get(`${g}/load`,{schema:{querystring:{type:"object",properties:{query:{type:"string"}},required:["query"]}}},async(r,t)=>{try{const{query:e}=r.query;let o;try{o=JSON.parse(e)}catch{return t.status(400).send(a.formatErrorResponse("Invalid JSON in query parameter",400))}const s=await m(r),i=u.validateQuery(o);if(!i.isValid)return t.status(400).send(a.formatErrorResponse(`Query validation failed: ${i.errors.join(", ")}`,400));const c=r.headers["x-cache-control"]==="no-cache",p=await u.executeMultiCubeQuery(o,s,{skipCache:c});return a.formatCubeResponse(o,p,u)}catch(e){return r.log.error(e,"Query execution error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"Query execution failed",500))}}),n.post(`${g}/batch`,{bodyLimit:C,schema:{body:{type:"object",required:["queries"],properties:{queries:{type:"array",items:{type:"object"}}}}}},async(r,t)=>{try{const{queries:e}=r.body;if(!e||!Array.isArray(e))return t.status(400).send(a.formatErrorResponse('Request body must contain a "queries" array',400));if(e.length===0)return t.status(400).send(a.formatErrorResponse("Queries array cannot be empty",400));const o=await m(r),s=r.headers["x-cache-control"]==="no-cache";return await a.handleBatchRequest(e,o,u,{skipCache:s})}catch(e){return r.log.error(e,"Batch execution error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"Batch execution failed",500))}}),n.get(`${g}/meta`,async(r,t)=>{try{const e=u.getMetadata();return a.formatMetaResponse(e)}catch(e){return r.log.error(e,"Metadata error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"Failed to fetch metadata",500))}}),n.post(`${g}/sql`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(r,t)=>{try{const e=r.body,o=await m(r),s=u.validateQuery(e);if(!s.isValid)return t.status(400).send(a.formatErrorResponse(`Query validation failed: ${s.errors.join(", ")}`,400));const i=e.measures?.[0]||e.dimensions?.[0];if(!i)return t.status(400).send(a.formatErrorResponse("No measures or dimensions specified",400));const c=i.split(".")[0],p=await u.generateSQL(c,e,o);return a.formatSqlResponse(e,p)}catch(e){return r.log.error(e,"SQL generation error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"SQL generation failed",500))}}),n.get(`${g}/sql`,{schema:{querystring:{type:"object",properties:{query:{type:"string"}},required:["query"]}}},async(r,t)=>{try{const{query:e}=r.query,o=JSON.parse(e),s=await m(r),i=u.validateQuery(o);if(!i.isValid)return t.status(400).send(a.formatErrorResponse(`Query validation failed: ${i.errors.join(", ")}`,400));const c=o.measures?.[0]||o.dimensions?.[0];if(!c)return t.status(400).send(a.formatErrorResponse("No measures or dimensions specified",400));const p=c.split(".")[0],P=await u.generateSQL(p,o,s);return a.formatSqlResponse(o,P)}catch(e){return r.log.error(e,"SQL generation error"),t.status(500).send(a.formatErrorResponse(e instanceof Error?e.message:"SQL generation failed",500))}}),n.post(`${g}/dry-run`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(r,t)=>{try{const e=r.body,o=e.query||e,s=await m(r);return await a.handleDryRun(o,s,u)}catch(e){return r.log.error(e,"Dry-run error"),t.status(400).send({error:e instanceof Error?e.message:"Dry-run validation failed",valid:!1})}}),n.get(`${g}/dry-run`,{schema:{querystring:{type:"object",properties:{query:{type:"string"}},required:["query"]}}},async(r,t)=>{try{const{query:e}=r.query,o=JSON.parse(e),s=await m(r);return await a.handleDryRun(o,s,u)}catch(e){return r.log.error(e,"Dry-run error"),t.status(400).send({error:e instanceof Error?e.message:"Dry-run validation failed",valid:!1})}}),n.post(`${g}/explain`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(r,t)=>{try{const e=r.body,o=e.query||e,s=e.options||{},i=await m(r),c=u.validateQuery(o);return c.isValid?await u.explainQuery(o,i,s):t.status(400).send({error:`Query validation failed: ${c.errors.join(", ")}`})}catch(e){return r.log.error(e,"Explain error"),t.status(500).send({error:e instanceof Error?e.message:"Explain query failed"})}}),b&&n.post(`${g}/agent/chat`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(r,t)=>{try{const{handleAgentChat:e}=await Promise.resolve().then(()=>require("../handler-B-tEntiU.cjs")),o=r.body,{message:s,sessionId:i,history:c}=o;if(!s||typeof s!="string")return t.status(400).send({error:"message is required and must be a string"});let p=(b.apiKey||"").trim();if(b.allowClientApiKey){const h=r.headers["x-agent-api-key"];h&&(p=h.trim())}if(!p)return t.status(401).send({error:"No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header."});const P=b.allowClientApiKey?r.headers["x-agent-provider"]:void 0,y=b.allowClientApiKey?r.headers["x-agent-model"]:void 0,E=b.allowClientApiKey?r.headers["x-agent-provider-endpoint"]:void 0,w=await m(r),R=b.buildSystemContext?.(w);t.raw.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});try{const h=e({message:s,sessionId:i,history:c,semanticLayer:u,securityContext:w,agentConfig:b,apiKey:p,systemContext:R,providerOverride:P,modelOverride:y,baseURLOverride:E});for await(const x of h)t.raw.write(`data: ${JSON.stringify(x)}
2
2
 
3
- `)}catch(m){const b={type:"error",data:{message:m instanceof Error?m.message:"Stream failed"}};t.raw.write(`data: ${JSON.stringify(b)}
3
+ `)}catch(h){const x={type:"error",data:{message:h instanceof Error?h.message:"Stream failed"}};t.raw.write(`data: ${JSON.stringify(x)}
4
4
 
5
- `)}finally{t.raw.end()}}catch(e){if(r.log.error(e,"Agent chat error"),!t.raw.headersSent)return t.status(500).send({error:e instanceof Error?e.message:"Agent chat failed"})}}),x.enabled!==!1){const r=x.basePath??"/mcp";n.post(`${r}`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(t,e)=>{const o=u.validateOriginHeader(t.headers.origin,x.allowedOrigins?{allowedOrigins:x.allowedOrigins}:{});if(!o.valid)return e.status(403).send(u.buildJsonRpcError(null,-32600,o.reason));const s=t.headers.accept;if(!u.validateAcceptHeader(s))return e.status(400).send(u.buildJsonRpcError(null,-32600,"Accept header must include both application/json and text/event-stream"));const i=u.negotiateProtocol(t.headers);if(!i.ok)return e.status(426).send({error:"Unsupported MCP protocol version",supported:i.supported});const c=u.parseJsonRpc(t.body);if(!c)return e.status(400).send(u.buildJsonRpcError(null,-32600,"Invalid JSON-RPC 2.0 request"));const p=u.wantsEventStream(s),E=c.method==="initialize";try{const y=await u.dispatchMcpMethod(c.method,c.params,{semanticLayer:d,extractSecurityContext:g,rawRequest:t,rawResponse:e,negotiatedProtocol:i.negotiated});if(u.isNotification(c))return e.status(202).send();const m=E&&y&&typeof y=="object"&&"sessionId"in y?y.sessionId:void 0;m&&e.header(u.MCP_SESSION_ID_HEADER,m);const b=u.buildJsonRpcResult(c.id??null,y);if(p){const S=u.primeEventId();e.header("Content-Type","text/event-stream").header("Cache-Control","no-cache").header("Connection","keep-alive").send(`id: ${S}
5
+ `)}finally{t.raw.end()}}catch(e){if(r.log.error(e,"Agent chat error"),!t.raw.headersSent)return t.status(500).send({error:e instanceof Error?e.message:"Agent chat failed"})}}),q.enabled!==!1){const r=q.basePath??"/mcp";n.post(`${r}`,{bodyLimit:C,schema:{body:{type:"object",additionalProperties:!0}}},async(t,e)=>{const o=d.validateOriginHeader(t.headers.origin,q.allowedOrigins?{allowedOrigins:q.allowedOrigins}:{});if(!o.valid)return e.status(403).send(d.buildJsonRpcError(null,-32600,o.reason));const s=t.headers.accept;if(!d.validateAcceptHeader(s))return e.status(400).send(d.buildJsonRpcError(null,-32600,"Accept header must include both application/json and text/event-stream"));const i=d.negotiateProtocol(t.headers);if(!i.ok)return e.status(426).send({error:"Unsupported MCP protocol version",supported:i.supported});const c=d.parseJsonRpc(t.body);if(!c)return e.status(400).send(d.buildJsonRpcError(null,-32600,"Invalid JSON-RPC 2.0 request"));const p=d.wantsEventStream(s),P=c.method==="initialize";try{const y=await d.dispatchMcpMethod(c.method,c.params,{semanticLayer:u,extractSecurityContext:m,rawRequest:t,rawResponse:e,negotiatedProtocol:i.negotiated});if(d.isNotification(c))return e.status(202).send();const E=P&&y&&typeof y=="object"&&"sessionId"in y?y.sessionId:void 0;E&&e.header(d.MCP_SESSION_ID_HEADER,E);const w=d.buildJsonRpcResult(c.id??null,y);if(p){const R=d.primeEventId();e.header("Content-Type","text/event-stream").header("Cache-Control","no-cache").header("Connection","keep-alive").send(`id: ${R}
6
6
 
7
- ${u.serializeSseEvent(b,S)}`);return}return e.send(b)}catch(y){if(u.isNotification(c))return t.log.error(y,"MCP notification processing error"),e.status(202).send();t.log.error(y,"MCP RPC error");const m=y?.code??-32603,b=y?.data,S=y.message||"MCP request failed",Q=u.buildJsonRpcError(c.id??null,m,S,b);if(p){const $=u.primeEventId();e.header("Content-Type","text/event-stream").header("Cache-Control","no-cache").header("Connection","keep-alive").send(`id: ${$}
7
+ ${d.serializeSseEvent(w,R)}`);return}return e.send(w)}catch(y){if(d.isNotification(c))return t.log.error(y,"MCP notification processing error"),e.status(202).send();t.log.error(y,"MCP RPC error");const E=y?.code??-32603,w=y?.data,R=y.message||"MCP request failed",h=d.buildJsonRpcError(c.id??null,E,R,w);if(p){const x=d.primeEventId();e.header("Content-Type","text/event-stream").header("Cache-Control","no-cache").header("Connection","keep-alive").send(`id: ${x}
8
8
 
9
- ${u.serializeSseEvent(Q,$)}`);return}return e.send(Q)}}),n.get(`${r}`,async(t,e)=>{const o=u.primeEventId();e.raw.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),e.raw.write(u.serializeSseEvent({jsonrpc:"2.0",method:"mcp/ready",params:{protocol:"streamable-http"}},o,15e3));const s=setInterval(()=>{e.raw.write(`: keep-alive
9
+ ${d.serializeSseEvent(h,x)}`);return}return e.send(h)}}),n.get(`${r}`,async(t,e)=>{const o=d.primeEventId();e.raw.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),e.raw.write(d.serializeSseEvent({jsonrpc:"2.0",method:"mcp/ready",params:{protocol:"streamable-http"}},o,15e3));const s=setInterval(()=>{e.raw.write(`: keep-alive
10
10
 
11
- `)},15e3);t.raw.on("close",()=>{clearInterval(s)})}),n.delete(`${r}`,async(t,e)=>e.status(405).send({error:"Session termination not supported"}))}n.setErrorHandler(async(r,t,e)=>{t.log.error(r,"Fastify cube adapter error"),e.statusCode<400&&e.status(500);const o=r instanceof Error?r:String(r);return a.formatErrorResponse(o,e.statusCode)}),R()};async function z(l,n){await l.register(q,n)}function K(l){const n=require("fastify")({logger:!0});return n.register(q,l),n}exports.createCubeApp=K;exports.cubePlugin=q;exports.registerCubeRoutes=z;
11
+ `)},15e3);t.raw.on("close",()=>{clearInterval(s)})}),n.delete(`${r}`,async(t,e)=>e.status(405).send({error:"Session termination not supported"}))}n.setErrorHandler(async(r,t,e)=>{t.log.error(r,"Fastify cube adapter error"),e.statusCode<400&&e.status(500);const o=r instanceof Error?r:String(r);return a.formatErrorResponse(o,e.statusCode)}),S()};async function T(l,n){await l.register(Q,n)}function z(l){const n=require("fastify")({logger:!0});return n.register(Q,l),n}exports.createCubeApp=z;exports.cubePlugin=Q;exports.registerCubeRoutes=T;
@@ -1,34 +1,34 @@
1
- import { S as D, v as K, b as x, a as T, n as V, p as z, w as _, d as B, i as j, M as F, c as U, e as E, s as P } from "../mcp-transport-m1X1GtwG.js";
2
- import { formatErrorResponse as d, formatCubeResponse as A, handleBatchRequest as X, formatMetaResponse as G, formatSqlResponse as I, handleDryRun as M } from "../utils.js";
3
- const N = function(i, k, R) {
1
+ import { S as H, v as D, b as E, a as T, n as V, p as z, w as _, d as B, i as j, M as F, c as U, e as P, s as Q } from "../mcp-transport-m1X1GtwG.js";
2
+ import { formatErrorResponse as d, formatCubeResponse as A, handleBatchRequest as X, formatMetaResponse as G, formatSqlResponse as I, handleDryRun as O } from "../utils.js";
3
+ const M = function(i, N, $) {
4
4
  const {
5
- cubes: S,
6
- drizzle: O,
5
+ cubes: R,
6
+ drizzle: k,
7
7
  schema: J,
8
- extractSecurityContext: p,
8
+ extractSecurityContext: y,
9
9
  engineType: L,
10
10
  cors: q,
11
- basePath: m = "/cubejs-api/v1",
11
+ basePath: p = "/cubejs-api/v1",
12
12
  bodyLimit: g = 10485760,
13
13
  // 10MB
14
- cache: H,
15
- mcp: C = { enabled: !0 },
16
- agent: f
17
- } = k;
18
- if (!S || S.length === 0)
19
- return R(new Error("At least one cube must be provided in the cubes array"));
14
+ cache: K,
15
+ mcp: S = { enabled: !0 },
16
+ agent: h
17
+ } = N;
18
+ if (!R || R.length === 0)
19
+ return $(new Error("At least one cube must be provided in the cubes array"));
20
20
  q && i.register(import("@fastify/cors"), q), i.addHook("onRequest", async (t, r) => {
21
21
  t.method === "POST" && (t.body = void 0);
22
22
  });
23
- const c = new D({
24
- drizzle: O,
23
+ const c = new H({
24
+ drizzle: k,
25
25
  schema: J,
26
26
  engineType: L,
27
- cache: H
27
+ cache: K
28
28
  });
29
- if (S.forEach((t) => {
29
+ if (R.forEach((t) => {
30
30
  c.registerCube(t);
31
- }), i.post(`${m}/load`, {
31
+ }), i.post(`${p}/load`, {
32
32
  bodyLimit: g,
33
33
  schema: {
34
34
  body: {
@@ -38,13 +38,13 @@ const N = function(i, k, R) {
38
38
  }
39
39
  }, async (t, r) => {
40
40
  try {
41
- const e = t.body, a = e.query || e, n = await p(t), s = c.validateQuery(a);
42
- if (!s.isValid)
41
+ const e = t.body, a = e.query || e, n = await y(t), o = c.validateQuery(a);
42
+ if (!o.isValid)
43
43
  return r.status(400).send(d(
44
- `Query validation failed: ${s.errors.join(", ")}`,
44
+ `Query validation failed: ${o.errors.join(", ")}`,
45
45
  400
46
46
  ));
47
- const o = t.headers["x-cache-control"] === "no-cache", u = await c.executeMultiCubeQuery(a, n, { skipCache: o });
47
+ const s = t.headers["x-cache-control"] === "no-cache", u = await c.executeMultiCubeQuery(a, n, { skipCache: s });
48
48
  return A(a, u, c);
49
49
  } catch (e) {
50
50
  return t.log.error(e, "Query execution error"), r.status(500).send(d(
@@ -52,7 +52,7 @@ const N = function(i, k, R) {
52
52
  500
53
53
  ));
54
54
  }
55
- }), i.get(`${m}/load`, {
55
+ }), i.get(`${p}/load`, {
56
56
  schema: {
57
57
  querystring: {
58
58
  type: "object",
@@ -74,13 +74,13 @@ const N = function(i, k, R) {
74
74
  400
75
75
  ));
76
76
  }
77
- const n = await p(t), s = c.validateQuery(a);
78
- if (!s.isValid)
77
+ const n = await y(t), o = c.validateQuery(a);
78
+ if (!o.isValid)
79
79
  return r.status(400).send(d(
80
- `Query validation failed: ${s.errors.join(", ")}`,
80
+ `Query validation failed: ${o.errors.join(", ")}`,
81
81
  400
82
82
  ));
83
- const o = t.headers["x-cache-control"] === "no-cache", u = await c.executeMultiCubeQuery(a, n, { skipCache: o });
83
+ const s = t.headers["x-cache-control"] === "no-cache", u = await c.executeMultiCubeQuery(a, n, { skipCache: s });
84
84
  return A(a, u, c);
85
85
  } catch (e) {
86
86
  return t.log.error(e, "Query execution error"), r.status(500).send(d(
@@ -88,7 +88,7 @@ const N = function(i, k, R) {
88
88
  500
89
89
  ));
90
90
  }
91
- }), i.post(`${m}/batch`, {
91
+ }), i.post(`${p}/batch`, {
92
92
  bodyLimit: g,
93
93
  schema: {
94
94
  body: {
@@ -115,7 +115,7 @@ const N = function(i, k, R) {
115
115
  "Queries array cannot be empty",
116
116
  400
117
117
  ));
118
- const a = await p(t), n = t.headers["x-cache-control"] === "no-cache";
118
+ const a = await y(t), n = t.headers["x-cache-control"] === "no-cache";
119
119
  return await X(e, a, c, { skipCache: n });
120
120
  } catch (e) {
121
121
  return t.log.error(e, "Batch execution error"), r.status(500).send(d(
@@ -123,7 +123,7 @@ const N = function(i, k, R) {
123
123
  500
124
124
  ));
125
125
  }
126
- }), i.get(`${m}/meta`, async (t, r) => {
126
+ }), i.get(`${p}/meta`, async (t, r) => {
127
127
  try {
128
128
  const e = c.getMetadata();
129
129
  return G(e);
@@ -133,7 +133,7 @@ const N = function(i, k, R) {
133
133
  500
134
134
  ));
135
135
  }
136
- }), i.post(`${m}/sql`, {
136
+ }), i.post(`${p}/sql`, {
137
137
  bodyLimit: g,
138
138
  schema: {
139
139
  body: {
@@ -143,19 +143,19 @@ const N = function(i, k, R) {
143
143
  }
144
144
  }, async (t, r) => {
145
145
  try {
146
- const e = t.body, a = await p(t), n = c.validateQuery(e);
146
+ const e = t.body, a = await y(t), n = c.validateQuery(e);
147
147
  if (!n.isValid)
148
148
  return r.status(400).send(d(
149
149
  `Query validation failed: ${n.errors.join(", ")}`,
150
150
  400
151
151
  ));
152
- const s = e.measures?.[0] || e.dimensions?.[0];
153
- if (!s)
152
+ const o = e.measures?.[0] || e.dimensions?.[0];
153
+ if (!o)
154
154
  return r.status(400).send(d(
155
155
  "No measures or dimensions specified",
156
156
  400
157
157
  ));
158
- const o = s.split(".")[0], u = await c.generateSQL(o, e, a);
158
+ const s = o.split(".")[0], u = await c.generateSQL(s, e, a);
159
159
  return I(e, u);
160
160
  } catch (e) {
161
161
  return t.log.error(e, "SQL generation error"), r.status(500).send(d(
@@ -163,7 +163,7 @@ const N = function(i, k, R) {
163
163
  500
164
164
  ));
165
165
  }
166
- }), i.get(`${m}/sql`, {
166
+ }), i.get(`${p}/sql`, {
167
167
  schema: {
168
168
  querystring: {
169
169
  type: "object",
@@ -175,27 +175,27 @@ const N = function(i, k, R) {
175
175
  }
176
176
  }, async (t, r) => {
177
177
  try {
178
- const { query: e } = t.query, a = JSON.parse(e), n = await p(t), s = c.validateQuery(a);
179
- if (!s.isValid)
178
+ const { query: e } = t.query, a = JSON.parse(e), n = await y(t), o = c.validateQuery(a);
179
+ if (!o.isValid)
180
180
  return r.status(400).send(d(
181
- `Query validation failed: ${s.errors.join(", ")}`,
181
+ `Query validation failed: ${o.errors.join(", ")}`,
182
182
  400
183
183
  ));
184
- const o = a.measures?.[0] || a.dimensions?.[0];
185
- if (!o)
184
+ const s = a.measures?.[0] || a.dimensions?.[0];
185
+ if (!s)
186
186
  return r.status(400).send(d(
187
187
  "No measures or dimensions specified",
188
188
  400
189
189
  ));
190
- const u = o.split(".")[0], b = await c.generateSQL(u, a, n);
191
- return I(a, b);
190
+ const u = s.split(".")[0], w = await c.generateSQL(u, a, n);
191
+ return I(a, w);
192
192
  } catch (e) {
193
193
  return t.log.error(e, "SQL generation error"), r.status(500).send(d(
194
194
  e instanceof Error ? e.message : "SQL generation failed",
195
195
  500
196
196
  ));
197
197
  }
198
- }), i.post(`${m}/dry-run`, {
198
+ }), i.post(`${p}/dry-run`, {
199
199
  bodyLimit: g,
200
200
  schema: {
201
201
  body: {
@@ -205,15 +205,15 @@ const N = function(i, k, R) {
205
205
  }
206
206
  }, async (t, r) => {
207
207
  try {
208
- const e = t.body, a = e.query || e, n = await p(t);
209
- return await M(a, n, c);
208
+ const e = t.body, a = e.query || e, n = await y(t);
209
+ return await O(a, n, c);
210
210
  } catch (e) {
211
211
  return t.log.error(e, "Dry-run error"), r.status(400).send({
212
212
  error: e instanceof Error ? e.message : "Dry-run validation failed",
213
213
  valid: !1
214
214
  });
215
215
  }
216
- }), i.get(`${m}/dry-run`, {
216
+ }), i.get(`${p}/dry-run`, {
217
217
  schema: {
218
218
  querystring: {
219
219
  type: "object",
@@ -225,15 +225,15 @@ const N = function(i, k, R) {
225
225
  }
226
226
  }, async (t, r) => {
227
227
  try {
228
- const { query: e } = t.query, a = JSON.parse(e), n = await p(t);
229
- return await M(a, n, c);
228
+ const { query: e } = t.query, a = JSON.parse(e), n = await y(t);
229
+ return await O(a, n, c);
230
230
  } catch (e) {
231
231
  return t.log.error(e, "Dry-run error"), r.status(400).send({
232
232
  error: e instanceof Error ? e.message : "Dry-run validation failed",
233
233
  valid: !1
234
234
  });
235
235
  }
236
- }), i.post(`${m}/explain`, {
236
+ }), i.post(`${p}/explain`, {
237
237
  bodyLimit: g,
238
238
  schema: {
239
239
  body: {
@@ -243,16 +243,16 @@ const N = function(i, k, R) {
243
243
  }
244
244
  }, async (t, r) => {
245
245
  try {
246
- const e = t.body, a = e.query || e, n = e.options || {}, s = await p(t), o = c.validateQuery(a);
247
- return o.isValid ? await c.explainQuery(a, s, n) : r.status(400).send({
248
- error: `Query validation failed: ${o.errors.join(", ")}`
246
+ const e = t.body, a = e.query || e, n = e.options || {}, o = await y(t), s = c.validateQuery(a);
247
+ return s.isValid ? await c.explainQuery(a, o, n) : r.status(400).send({
248
+ error: `Query validation failed: ${s.errors.join(", ")}`
249
249
  });
250
250
  } catch (e) {
251
251
  return t.log.error(e, "Explain error"), r.status(500).send({
252
252
  error: e instanceof Error ? e.message : "Explain query failed"
253
253
  });
254
254
  }
255
- }), f && i.post(`${m}/agent/chat`, {
255
+ }), h && i.post(`${p}/agent/chat`, {
256
256
  bodyLimit: g,
257
257
  schema: {
258
258
  body: {
@@ -262,45 +262,48 @@ const N = function(i, k, R) {
262
262
  }
263
263
  }, async (t, r) => {
264
264
  try {
265
- const { handleAgentChat: e } = await import("../handler-CbDMdSY5.js"), a = t.body, { message: n, sessionId: s, history: o } = a;
265
+ const { handleAgentChat: e } = await import("../handler-9Rdn7zM2.js"), a = t.body, { message: n, sessionId: o, history: s } = a;
266
266
  if (!n || typeof n != "string")
267
267
  return r.status(400).send({ error: "message is required and must be a string" });
268
- let u = (f.apiKey || "").trim();
269
- if (f.allowClientApiKey) {
270
- const y = t.headers["x-agent-api-key"];
271
- y && (u = y.trim());
268
+ let u = (h.apiKey || "").trim();
269
+ if (h.allowClientApiKey) {
270
+ const m = t.headers["x-agent-api-key"];
271
+ m && (u = m.trim());
272
272
  }
273
273
  if (!u)
274
274
  return r.status(401).send({
275
275
  error: "No API key configured. Set agent.apiKey in server config or send X-Agent-Api-Key header."
276
276
  });
277
- const b = await p(t), l = f.buildSystemContext?.(b);
277
+ const w = h.allowClientApiKey ? t.headers["x-agent-provider"] : void 0, l = h.allowClientApiKey ? t.headers["x-agent-model"] : void 0, v = h.allowClientApiKey ? t.headers["x-agent-provider-endpoint"] : void 0, b = await y(t), f = h.buildSystemContext?.(b);
278
278
  r.raw.writeHead(200, {
279
279
  "Content-Type": "text/event-stream",
280
280
  "Cache-Control": "no-cache",
281
281
  Connection: "keep-alive"
282
282
  });
283
283
  try {
284
- const y = e({
284
+ const m = e({
285
285
  message: n,
286
- sessionId: s,
287
- history: o,
286
+ sessionId: o,
287
+ history: s,
288
288
  semanticLayer: c,
289
289
  securityContext: b,
290
- agentConfig: f,
290
+ agentConfig: h,
291
291
  apiKey: u,
292
- systemContext: l
292
+ systemContext: f,
293
+ providerOverride: w,
294
+ modelOverride: l,
295
+ baseURLOverride: v
293
296
  });
294
- for await (const h of y)
295
- r.raw.write(`data: ${JSON.stringify(h)}
297
+ for await (const C of m)
298
+ r.raw.write(`data: ${JSON.stringify(C)}
296
299
 
297
300
  `);
298
- } catch (y) {
299
- const h = {
301
+ } catch (m) {
302
+ const C = {
300
303
  type: "error",
301
- data: { message: y instanceof Error ? y.message : "Stream failed" }
304
+ data: { message: m instanceof Error ? m.message : "Stream failed" }
302
305
  };
303
- r.raw.write(`data: ${JSON.stringify(h)}
306
+ r.raw.write(`data: ${JSON.stringify(C)}
304
307
 
305
308
  `);
306
309
  } finally {
@@ -312,8 +315,8 @@ const N = function(i, k, R) {
312
315
  error: e instanceof Error ? e.message : "Agent chat failed"
313
316
  });
314
317
  }
315
- }), C.enabled !== !1) {
316
- const t = C.basePath ?? "/mcp";
318
+ }), S.enabled !== !1) {
319
+ const t = S.basePath ?? "/mcp";
317
320
  i.post(`${t}`, {
318
321
  bodyLimit: g,
319
322
  schema: {
@@ -323,71 +326,71 @@ const N = function(i, k, R) {
323
326
  }
324
327
  }
325
328
  }, async (r, e) => {
326
- const a = K(
329
+ const a = D(
327
330
  r.headers.origin,
328
- C.allowedOrigins ? { allowedOrigins: C.allowedOrigins } : {}
331
+ S.allowedOrigins ? { allowedOrigins: S.allowedOrigins } : {}
329
332
  );
330
333
  if (!a.valid)
331
- return e.status(403).send(x(null, -32600, a.reason));
334
+ return e.status(403).send(E(null, -32600, a.reason));
332
335
  const n = r.headers.accept;
333
336
  if (!T(n))
334
- return e.status(400).send(x(null, -32600, "Accept header must include both application/json and text/event-stream"));
335
- const s = V(r.headers);
336
- if (!s.ok)
337
+ return e.status(400).send(E(null, -32600, "Accept header must include both application/json and text/event-stream"));
338
+ const o = V(r.headers);
339
+ if (!o.ok)
337
340
  return e.status(426).send({
338
341
  error: "Unsupported MCP protocol version",
339
- supported: s.supported
342
+ supported: o.supported
340
343
  });
341
- const o = z(r.body);
342
- if (!o)
343
- return e.status(400).send(x(null, -32600, "Invalid JSON-RPC 2.0 request"));
344
- const u = _(n), b = o.method === "initialize";
344
+ const s = z(r.body);
345
+ if (!s)
346
+ return e.status(400).send(E(null, -32600, "Invalid JSON-RPC 2.0 request"));
347
+ const u = _(n), w = s.method === "initialize";
345
348
  try {
346
349
  const l = await B(
347
- o.method,
348
- o.params,
350
+ s.method,
351
+ s.params,
349
352
  {
350
353
  semanticLayer: c,
351
- extractSecurityContext: p,
354
+ extractSecurityContext: y,
352
355
  rawRequest: r,
353
356
  rawResponse: e,
354
- negotiatedProtocol: s.negotiated
357
+ negotiatedProtocol: o.negotiated
355
358
  }
356
359
  );
357
- if (j(o))
360
+ if (j(s))
358
361
  return e.status(202).send();
359
- const y = b && l && typeof l == "object" && "sessionId" in l ? l.sessionId : void 0;
360
- y && e.header(F, y);
361
- const h = U(o.id ?? null, l);
362
+ const v = w && l && typeof l == "object" && "sessionId" in l ? l.sessionId : void 0;
363
+ v && e.header(F, v);
364
+ const b = U(s.id ?? null, l);
362
365
  if (u) {
363
- const w = E();
364
- e.header("Content-Type", "text/event-stream").header("Cache-Control", "no-cache").header("Connection", "keep-alive").send(`id: ${w}
366
+ const f = P();
367
+ e.header("Content-Type", "text/event-stream").header("Cache-Control", "no-cache").header("Connection", "keep-alive").send(`id: ${f}
365
368
 
366
- ${P(h, w)}`);
369
+ ${Q(b, f)}`);
367
370
  return;
368
371
  }
369
- return e.send(h);
372
+ return e.send(b);
370
373
  } catch (l) {
371
- if (j(o))
374
+ if (j(s))
372
375
  return r.log.error(l, "MCP notification processing error"), e.status(202).send();
373
376
  r.log.error(l, "MCP RPC error");
374
- const y = l?.code ?? -32603, h = l?.data, w = l.message || "MCP request failed", Q = x(o.id ?? null, y, w, h);
377
+ const v = l?.code ?? -32603, b = l?.data, f = l.message || "MCP request failed", m = E(s.id ?? null, v, f, b);
375
378
  if (u) {
376
- const $ = E();
377
- e.header("Content-Type", "text/event-stream").header("Cache-Control", "no-cache").header("Connection", "keep-alive").send(`id: ${$}
379
+ const C = P();
380
+ e.header("Content-Type", "text/event-stream").header("Cache-Control", "no-cache").header("Connection", "keep-alive").send(`id: ${C}
378
381
 
379
- ${P(Q, $)}`);
382
+ ${Q(m, C)}`);
380
383
  return;
381
384
  }
382
- return e.send(Q);
385
+ return e.send(m);
383
386
  }
384
387
  }), i.get(`${t}`, async (r, e) => {
385
- const a = E();
388
+ const a = P();
386
389
  e.raw.writeHead(200, {
387
390
  "Content-Type": "text/event-stream",
388
391
  "Cache-Control": "no-cache",
389
392
  Connection: "keep-alive"
390
- }), e.raw.write(P({
393
+ }), e.raw.write(Q({
391
394
  jsonrpc: "2.0",
392
395
  method: "mcp/ready",
393
396
  params: { protocol: "streamable-http" }
@@ -406,19 +409,19 @@ ${P(Q, $)}`);
406
409
  r.log.error(t, "Fastify cube adapter error"), e.statusCode < 400 && e.status(500);
407
410
  const a = t instanceof Error ? t : String(t);
408
411
  return d(a, e.statusCode);
409
- }), R();
412
+ }), $();
410
413
  };
411
- async function Z(v, i) {
412
- await v.register(N, i);
414
+ async function Z(x, i) {
415
+ await x.register(M, i);
413
416
  }
414
- function ee(v) {
417
+ function ee(x) {
415
418
  const i = require("fastify")({
416
419
  logger: !0
417
420
  });
418
- return i.register(N, v), i;
421
+ return i.register(M, x), i;
419
422
  }
420
423
  export {
421
424
  ee as createCubeApp,
422
- N as cubePlugin,
425
+ M as cubePlugin,
423
426
  Z as registerCubeRoutes
424
427
  };
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function l(u){const e={};for(const[t,s]of Object.entries(u))if(t==="type"&&typeof s=="string")e[t]=s.toUpperCase();else if(t==="properties"&&typeof s=="object"&&s!==null){const n={};for(const[a,o]of Object.entries(s))typeof o=="object"&&o!==null?n[a]=l(o):n[a]=o;e[t]=n}else t==="items"&&typeof s=="object"&&s!==null?e[t]=l(s):e[t]=s;return e}class p{apiKey;sdk;initialized=!1;constructor(e){this.apiKey=e}async ensureSDK(){if(!this.initialized){try{this.sdk=await Promise.resolve().then(()=>require("./index-BgCeQBuN.cjs"))}catch{throw new Error("@google/generative-ai is required for the Google provider. Install it with: npm install @google/generative-ai")}this.initialized=!0}}async createStream(e){await this.ensureSDK();const{GoogleGenerativeAI:t}=this.sdk,n=new t(this.apiKey).getGenerativeModel({model:e.model,systemInstruction:e.system,generationConfig:{maxOutputTokens:e.maxTokens}}),{messages:a}=this.formatMessages(e.messages,e.system),o=this.formatTools(e.tools);return(await n.generateContentStream({contents:a,tools:o.length>0?[{functionDeclarations:o}]:void 0})).stream}async*parseStreamEvents(e){let t="stop",s=!1;for await(const n of e){const a=n;a.usageMetadata&&(yield{type:"message_meta",inputTokens:a.usageMetadata.promptTokenCount,outputTokens:a.usageMetadata.candidatesTokenCount,stopReason:""});const o=a.candidates?.[0];if(!o)continue;o.finishReason&&(o.finishReason==="STOP"?t="stop":o.finishReason==="MAX_TOKENS"?t="max_tokens":t=o.finishReason);const i=o.content?.parts;if(i){for(const r of i)if(r.text&&!r.thought&&(yield{type:"text_delta",text:r.text}),r.functionCall){s=!0;const f=`gemini-tc-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,c=r.thoughtSignature?{thoughtSignature:r.thoughtSignature}:void 0;yield{type:"tool_use_start",id:f,name:r.functionCall.name,...c?{metadata:c}:{}},yield{type:"tool_input_delta",json:JSON.stringify(r.functionCall.args||{})},yield{type:"tool_use_end"}}}}yield{type:"message_meta",stopReason:s?"tool_use":t}}formatTools(e){return e.map(t=>({name:t.name,description:t.description,parameters:l(t.parameters)}))}formatMessages(e,t){const s=[];for(const n of e)if(n.role==="tool_result"){const a=n._toolResults;if(a&&a.length>0)s.push({role:"user",parts:a.map(o=>({functionResponse:{name:o.toolName||o.toolUseId,response:{content:o.content,isError:o.isError||!1}}}))});else{const o=typeof n.content=="string"?n.content:JSON.stringify(n.content);o&&s.push({role:"user",parts:[{text:o}]})}}else if(n.role==="user"){const a=typeof n.content=="string"?n.content:JSON.stringify(n.content);s.push({role:"user",parts:[{text:a}]})}else if(n.role==="assistant")if(typeof n.content=="string")s.push({role:"model",parts:[{text:n.content}]});else{const a=n.content,o=[];for(const i of a)if(i.type==="text"&&i.text)o.push({text:i.text});else if(i.type==="tool_use"){const r={functionCall:{name:i.name,args:i.input||{}}};i.metadata?.thoughtSignature&&(r.thoughtSignature=i.metadata.thoughtSignature),o.push(r)}o.length>0&&s.push({role:"model",parts:o})}return{messages:s}}formatToolResults(e){return{role:"tool_result",content:e.map(t=>`${t.toolName||t.toolUseId}: ${t.content}`).join(`
2
+ `),_toolResults:e}}shouldContinue(e){return e==="tool_use"}formatError(e){if(!e||!(e instanceof Error))return"Something went wrong. Please try again.";const t=e.message||"",s=e;return s.status===429?"Too many requests. Please wait a moment and try again.":s.status===403||s.status===401?"Authentication failed. Please check your API key configuration.":s.status===503||s.status===500?"The AI service is temporarily unavailable. Please try again in a moment.":t.includes("SAFETY")?"The request was blocked by safety filters. Please rephrase your request.":t.includes("RECITATION")?"The response was blocked due to recitation concerns. Please try a different query.":t.startsWith("{")||t.startsWith("[")?"The AI service encountered an error. Please try again.":t}}exports.GoogleProvider=p;