drizzle-cube 0.4.19 → 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 +73 -69
  5. package/dist/adapters/fastify/index.cjs +6 -6
  6. package/dist/adapters/fastify/index.js +133 -129
  7. package/dist/adapters/google-BAK9pnQf.cjs +2 -0
  8. package/dist/adapters/google-DficVAsJ.js +146 -0
  9. package/dist/adapters/{handler-BV4JuWNW.js → handler-9Rdn7zM2.js} +537 -457
  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 -195
  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 +215 -211
  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 +51 -45
  37. package/dist/server/index.d.ts +49 -10
  38. package/dist/server/index.js +1978 -1898
  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-D4MVKkVy.cjs +0 -33
@@ -1,35 +1,35 @@
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 u, 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
8
  extractSecurityContext: y,
9
9
  engineType: L,
10
10
  cors: q,
11
11
  basePath: p = "/cubejs-api/v1",
12
- bodyLimit: m = 10485760,
12
+ bodyLimit: g = 10485760,
13
13
  // 10MB
14
- cache: H,
15
- mcp: f = { enabled: !0 },
16
- agent: v
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
31
  }), i.post(`${p}/load`, {
32
- bodyLimit: m,
32
+ bodyLimit: g,
33
33
  schema: {
34
34
  body: {
35
35
  type: "object",
@@ -38,16 +38,16 @@ 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 y(t), s = c.validateQuery(a);
42
- if (!s.isValid)
43
- return r.status(400).send(u(
44
- `Query validation failed: ${s.errors.join(", ")}`,
41
+ const e = t.body, a = e.query || e, n = await y(t), o = c.validateQuery(a);
42
+ if (!o.isValid)
43
+ return r.status(400).send(d(
44
+ `Query validation failed: ${o.errors.join(", ")}`,
45
45
  400
46
46
  ));
47
- const o = t.headers["x-cache-control"] === "no-cache", l = await c.executeMultiCubeQuery(a, n, { skipCache: o });
48
- return A(a, l, c);
47
+ const s = t.headers["x-cache-control"] === "no-cache", u = await c.executeMultiCubeQuery(a, n, { skipCache: s });
48
+ return A(a, u, c);
49
49
  } catch (e) {
50
- return t.log.error(e, "Query execution error"), r.status(500).send(u(
50
+ return t.log.error(e, "Query execution error"), r.status(500).send(d(
51
51
  e instanceof Error ? e.message : "Query execution failed",
52
52
  500
53
53
  ));
@@ -69,27 +69,27 @@ const N = function(i, k, R) {
69
69
  try {
70
70
  a = JSON.parse(e);
71
71
  } catch {
72
- return r.status(400).send(u(
72
+ return r.status(400).send(d(
73
73
  "Invalid JSON in query parameter",
74
74
  400
75
75
  ));
76
76
  }
77
- const n = await y(t), s = c.validateQuery(a);
78
- if (!s.isValid)
79
- return r.status(400).send(u(
80
- `Query validation failed: ${s.errors.join(", ")}`,
77
+ const n = await y(t), o = c.validateQuery(a);
78
+ if (!o.isValid)
79
+ return r.status(400).send(d(
80
+ `Query validation failed: ${o.errors.join(", ")}`,
81
81
  400
82
82
  ));
83
- const o = t.headers["x-cache-control"] === "no-cache", l = await c.executeMultiCubeQuery(a, n, { skipCache: o });
84
- return A(a, l, c);
83
+ const s = t.headers["x-cache-control"] === "no-cache", u = await c.executeMultiCubeQuery(a, n, { skipCache: s });
84
+ return A(a, u, c);
85
85
  } catch (e) {
86
- return t.log.error(e, "Query execution error"), r.status(500).send(u(
86
+ return t.log.error(e, "Query execution error"), r.status(500).send(d(
87
87
  e instanceof Error ? e.message : "Query execution failed",
88
88
  500
89
89
  ));
90
90
  }
91
91
  }), i.post(`${p}/batch`, {
92
- bodyLimit: m,
92
+ bodyLimit: g,
93
93
  schema: {
94
94
  body: {
95
95
  type: "object",
@@ -106,19 +106,19 @@ const N = function(i, k, R) {
106
106
  try {
107
107
  const { queries: e } = t.body;
108
108
  if (!e || !Array.isArray(e))
109
- return r.status(400).send(u(
109
+ return r.status(400).send(d(
110
110
  'Request body must contain a "queries" array',
111
111
  400
112
112
  ));
113
113
  if (e.length === 0)
114
- return r.status(400).send(u(
114
+ return r.status(400).send(d(
115
115
  "Queries array cannot be empty",
116
116
  400
117
117
  ));
118
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
- return t.log.error(e, "Batch execution error"), r.status(500).send(u(
121
+ return t.log.error(e, "Batch execution error"), r.status(500).send(d(
122
122
  e instanceof Error ? e.message : "Batch execution failed",
123
123
  500
124
124
  ));
@@ -128,13 +128,13 @@ const N = function(i, k, R) {
128
128
  const e = c.getMetadata();
129
129
  return G(e);
130
130
  } catch (e) {
131
- return t.log.error(e, "Metadata error"), r.status(500).send(u(
131
+ return t.log.error(e, "Metadata error"), r.status(500).send(d(
132
132
  e instanceof Error ? e.message : "Failed to fetch metadata",
133
133
  500
134
134
  ));
135
135
  }
136
136
  }), i.post(`${p}/sql`, {
137
- bodyLimit: m,
137
+ bodyLimit: g,
138
138
  schema: {
139
139
  body: {
140
140
  type: "object",
@@ -145,20 +145,20 @@ const N = function(i, k, R) {
145
145
  try {
146
146
  const e = t.body, a = await y(t), n = c.validateQuery(e);
147
147
  if (!n.isValid)
148
- return r.status(400).send(u(
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)
154
- return r.status(400).send(u(
152
+ const o = e.measures?.[0] || e.dimensions?.[0];
153
+ if (!o)
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], l = await c.generateSQL(o, e, a);
159
- return I(e, l);
158
+ const s = o.split(".")[0], u = await c.generateSQL(s, e, a);
159
+ return I(e, u);
160
160
  } catch (e) {
161
- return t.log.error(e, "SQL generation error"), r.status(500).send(u(
161
+ return t.log.error(e, "SQL generation error"), r.status(500).send(d(
162
162
  e instanceof Error ? e.message : "SQL generation failed",
163
163
  500
164
164
  ));
@@ -175,28 +175,28 @@ 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 y(t), s = c.validateQuery(a);
179
- if (!s.isValid)
180
- return r.status(400).send(u(
181
- `Query validation failed: ${s.errors.join(", ")}`,
178
+ const { query: e } = t.query, a = JSON.parse(e), n = await y(t), o = c.validateQuery(a);
179
+ if (!o.isValid)
180
+ return r.status(400).send(d(
181
+ `Query validation failed: ${o.errors.join(", ")}`,
182
182
  400
183
183
  ));
184
- const o = a.measures?.[0] || a.dimensions?.[0];
185
- if (!o)
186
- return r.status(400).send(u(
184
+ const s = a.measures?.[0] || a.dimensions?.[0];
185
+ if (!s)
186
+ return r.status(400).send(d(
187
187
  "No measures or dimensions specified",
188
188
  400
189
189
  ));
190
- const l = o.split(".")[0], g = await c.generateSQL(l, a, n);
191
- return I(a, g);
190
+ const u = s.split(".")[0], w = await c.generateSQL(u, a, n);
191
+ return I(a, w);
192
192
  } catch (e) {
193
- return t.log.error(e, "SQL generation error"), r.status(500).send(u(
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
198
  }), i.post(`${p}/dry-run`, {
199
- bodyLimit: m,
199
+ bodyLimit: g,
200
200
  schema: {
201
201
  body: {
202
202
  type: "object",
@@ -206,7 +206,7 @@ const N = function(i, k, R) {
206
206
  }, async (t, r) => {
207
207
  try {
208
208
  const e = t.body, a = e.query || e, n = await y(t);
209
- return await M(a, n, c);
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",
@@ -226,7 +226,7 @@ const N = function(i, k, R) {
226
226
  }, async (t, r) => {
227
227
  try {
228
228
  const { query: e } = t.query, a = JSON.parse(e), n = await y(t);
229
- return await M(a, n, c);
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",
@@ -234,7 +234,7 @@ const N = function(i, k, R) {
234
234
  });
235
235
  }
236
236
  }), i.post(`${p}/explain`, {
237
- bodyLimit: m,
237
+ bodyLimit: g,
238
238
  schema: {
239
239
  body: {
240
240
  type: "object",
@@ -243,17 +243,17 @@ 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 y(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
- }), v && i.post(`${p}/agent/chat`, {
256
- bodyLimit: m,
255
+ }), h && i.post(`${p}/agent/chat`, {
256
+ bodyLimit: g,
257
257
  schema: {
258
258
  body: {
259
259
  type: "object",
@@ -262,44 +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-BV4JuWNW.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 l = (v.apiKey || "").trim();
269
- if (v.allowClientApiKey) {
270
- const d = t.headers["x-agent-api-key"];
271
- d && (l = d.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
- if (!l)
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 g = await y(t);
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 d = 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
- securityContext: g,
290
- agentConfig: v,
291
- apiKey: l
289
+ securityContext: b,
290
+ agentConfig: h,
291
+ apiKey: u,
292
+ systemContext: f,
293
+ providerOverride: w,
294
+ modelOverride: l,
295
+ baseURLOverride: v
292
296
  });
293
- for await (const h of d)
294
- r.raw.write(`data: ${JSON.stringify(h)}
297
+ for await (const C of m)
298
+ r.raw.write(`data: ${JSON.stringify(C)}
295
299
 
296
300
  `);
297
- } catch (d) {
298
- const h = {
301
+ } catch (m) {
302
+ const C = {
299
303
  type: "error",
300
- data: { message: d instanceof Error ? d.message : "Stream failed" }
304
+ data: { message: m instanceof Error ? m.message : "Stream failed" }
301
305
  };
302
- r.raw.write(`data: ${JSON.stringify(h)}
306
+ r.raw.write(`data: ${JSON.stringify(C)}
303
307
 
304
308
  `);
305
309
  } finally {
@@ -311,10 +315,10 @@ const N = function(i, k, R) {
311
315
  error: e instanceof Error ? e.message : "Agent chat failed"
312
316
  });
313
317
  }
314
- }), f.enabled !== !1) {
315
- const t = f.basePath ?? "/mcp";
318
+ }), S.enabled !== !1) {
319
+ const t = S.basePath ?? "/mcp";
316
320
  i.post(`${t}`, {
317
- bodyLimit: m,
321
+ bodyLimit: g,
318
322
  schema: {
319
323
  body: {
320
324
  type: "object",
@@ -322,71 +326,71 @@ const N = function(i, k, R) {
322
326
  }
323
327
  }
324
328
  }, async (r, e) => {
325
- const a = K(
329
+ const a = D(
326
330
  r.headers.origin,
327
- f.allowedOrigins ? { allowedOrigins: f.allowedOrigins } : {}
331
+ S.allowedOrigins ? { allowedOrigins: S.allowedOrigins } : {}
328
332
  );
329
333
  if (!a.valid)
330
- return e.status(403).send(x(null, -32600, a.reason));
334
+ return e.status(403).send(E(null, -32600, a.reason));
331
335
  const n = r.headers.accept;
332
336
  if (!T(n))
333
- return e.status(400).send(x(null, -32600, "Accept header must include both application/json and text/event-stream"));
334
- const s = V(r.headers);
335
- 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)
336
340
  return e.status(426).send({
337
341
  error: "Unsupported MCP protocol version",
338
- supported: s.supported
342
+ supported: o.supported
339
343
  });
340
- const o = z(r.body);
341
- if (!o)
342
- return e.status(400).send(x(null, -32600, "Invalid JSON-RPC 2.0 request"));
343
- const l = _(n), g = 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";
344
348
  try {
345
- const d = await B(
346
- o.method,
347
- o.params,
349
+ const l = await B(
350
+ s.method,
351
+ s.params,
348
352
  {
349
353
  semanticLayer: c,
350
354
  extractSecurityContext: y,
351
355
  rawRequest: r,
352
356
  rawResponse: e,
353
- negotiatedProtocol: s.negotiated
357
+ negotiatedProtocol: o.negotiated
354
358
  }
355
359
  );
356
- if (j(o))
360
+ if (j(s))
357
361
  return e.status(202).send();
358
- const h = g && d && typeof d == "object" && "sessionId" in d ? d.sessionId : void 0;
359
- h && e.header(F, h);
360
- const C = U(o.id ?? null, d);
361
- if (l) {
362
- const w = E();
363
- e.header("Content-Type", "text/event-stream").header("Cache-Control", "no-cache").header("Connection", "keep-alive").send(`id: ${w}
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);
365
+ if (u) {
366
+ const f = P();
367
+ e.header("Content-Type", "text/event-stream").header("Cache-Control", "no-cache").header("Connection", "keep-alive").send(`id: ${f}
364
368
 
365
- ${P(C, w)}`);
369
+ ${Q(b, f)}`);
366
370
  return;
367
371
  }
368
- return e.send(C);
369
- } catch (d) {
370
- if (j(o))
371
- return r.log.error(d, "MCP notification processing error"), e.status(202).send();
372
- r.log.error(d, "MCP RPC error");
373
- const h = d?.code ?? -32603, C = d?.data, w = d.message || "MCP request failed", Q = x(o.id ?? null, h, w, C);
374
- if (l) {
375
- const $ = E();
376
- e.header("Content-Type", "text/event-stream").header("Cache-Control", "no-cache").header("Connection", "keep-alive").send(`id: ${$}
372
+ return e.send(b);
373
+ } catch (l) {
374
+ if (j(s))
375
+ return r.log.error(l, "MCP notification processing error"), e.status(202).send();
376
+ r.log.error(l, "MCP RPC error");
377
+ const v = l?.code ?? -32603, b = l?.data, f = l.message || "MCP request failed", m = E(s.id ?? null, v, f, b);
378
+ if (u) {
379
+ const C = P();
380
+ e.header("Content-Type", "text/event-stream").header("Cache-Control", "no-cache").header("Connection", "keep-alive").send(`id: ${C}
377
381
 
378
- ${P(Q, $)}`);
382
+ ${Q(m, C)}`);
379
383
  return;
380
384
  }
381
- return e.send(Q);
385
+ return e.send(m);
382
386
  }
383
387
  }), i.get(`${t}`, async (r, e) => {
384
- const a = E();
388
+ const a = P();
385
389
  e.raw.writeHead(200, {
386
390
  "Content-Type": "text/event-stream",
387
391
  "Cache-Control": "no-cache",
388
392
  Connection: "keep-alive"
389
- }), e.raw.write(P({
393
+ }), e.raw.write(Q({
390
394
  jsonrpc: "2.0",
391
395
  method: "mcp/ready",
392
396
  params: { protocol: "streamable-http" }
@@ -404,20 +408,20 @@ ${P(Q, $)}`);
404
408
  i.setErrorHandler(async (t, r, e) => {
405
409
  r.log.error(t, "Fastify cube adapter error"), e.statusCode < 400 && e.status(500);
406
410
  const a = t instanceof Error ? t : String(t);
407
- return u(a, e.statusCode);
408
- }), R();
411
+ return d(a, e.statusCode);
412
+ }), $();
409
413
  };
410
- async function Z(b, i) {
411
- await b.register(N, i);
414
+ async function Z(x, i) {
415
+ await x.register(M, i);
412
416
  }
413
- function ee(b) {
417
+ function ee(x) {
414
418
  const i = require("fastify")({
415
419
  logger: !0
416
420
  });
417
- return i.register(N, b), i;
421
+ return i.register(M, x), i;
418
422
  }
419
423
  export {
420
424
  ee as createCubeApp,
421
- N as cubePlugin,
425
+ M as cubePlugin,
422
426
  Z as registerCubeRoutes
423
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;
@@ -0,0 +1,146 @@
1
+ function l(u) {
2
+ const t = {};
3
+ for (const [e, s] of Object.entries(u))
4
+ if (e === "type" && typeof s == "string")
5
+ t[e] = s.toUpperCase();
6
+ else if (e === "properties" && typeof s == "object" && s !== null) {
7
+ const n = {};
8
+ for (const [a, o] of Object.entries(s))
9
+ typeof o == "object" && o !== null ? n[a] = l(o) : n[a] = o;
10
+ t[e] = n;
11
+ } else e === "items" && typeof s == "object" && s !== null ? t[e] = l(s) : t[e] = s;
12
+ return t;
13
+ }
14
+ class p {
15
+ apiKey;
16
+ sdk;
17
+ initialized = !1;
18
+ constructor(t) {
19
+ this.apiKey = t;
20
+ }
21
+ async ensureSDK() {
22
+ if (!this.initialized) {
23
+ try {
24
+ this.sdk = await import(
25
+ /* webpackIgnore: true */
26
+ "./index-C45_meK_.js"
27
+ );
28
+ } catch {
29
+ throw new Error("@google/generative-ai is required for the Google provider. Install it with: npm install @google/generative-ai");
30
+ }
31
+ this.initialized = !0;
32
+ }
33
+ }
34
+ async createStream(t) {
35
+ await this.ensureSDK();
36
+ const { GoogleGenerativeAI: e } = this.sdk, n = new e(this.apiKey).getGenerativeModel({
37
+ model: t.model,
38
+ systemInstruction: t.system,
39
+ generationConfig: {
40
+ maxOutputTokens: t.maxTokens
41
+ }
42
+ }), { messages: a } = this.formatMessages(t.messages, t.system), o = this.formatTools(t.tools);
43
+ return (await n.generateContentStream({
44
+ contents: a,
45
+ tools: o.length > 0 ? [{ functionDeclarations: o }] : void 0
46
+ })).stream;
47
+ }
48
+ async *parseStreamEvents(t) {
49
+ let e = "stop", s = !1;
50
+ for await (const n of t) {
51
+ const a = n;
52
+ a.usageMetadata && (yield {
53
+ type: "message_meta",
54
+ inputTokens: a.usageMetadata.promptTokenCount,
55
+ outputTokens: a.usageMetadata.candidatesTokenCount,
56
+ stopReason: ""
57
+ });
58
+ const o = a.candidates?.[0];
59
+ if (!o) continue;
60
+ o.finishReason && (o.finishReason === "STOP" ? e = "stop" : o.finishReason === "MAX_TOKENS" ? e = "max_tokens" : e = o.finishReason);
61
+ const i = o.content?.parts;
62
+ if (i) {
63
+ for (const r of i)
64
+ if (r.text && !r.thought && (yield { type: "text_delta", text: r.text }), r.functionCall) {
65
+ s = !0;
66
+ const f = `gemini-tc-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`, c = r.thoughtSignature ? { thoughtSignature: r.thoughtSignature } : void 0;
67
+ 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" };
68
+ }
69
+ }
70
+ }
71
+ yield {
72
+ type: "message_meta",
73
+ stopReason: s ? "tool_use" : e
74
+ };
75
+ }
76
+ formatTools(t) {
77
+ return t.map((e) => ({
78
+ name: e.name,
79
+ description: e.description,
80
+ parameters: l(e.parameters)
81
+ }));
82
+ }
83
+ formatMessages(t, e) {
84
+ const s = [];
85
+ for (const n of t)
86
+ if (n.role === "tool_result") {
87
+ const a = n._toolResults;
88
+ if (a && a.length > 0)
89
+ s.push({
90
+ role: "user",
91
+ parts: a.map((o) => ({
92
+ functionResponse: {
93
+ name: o.toolName || o.toolUseId,
94
+ response: { content: o.content, isError: o.isError || !1 }
95
+ }
96
+ }))
97
+ });
98
+ else {
99
+ const o = typeof n.content == "string" ? n.content : JSON.stringify(n.content);
100
+ o && s.push({ role: "user", parts: [{ text: o }] });
101
+ }
102
+ } else if (n.role === "user") {
103
+ const a = typeof n.content == "string" ? n.content : JSON.stringify(n.content);
104
+ s.push({ role: "user", parts: [{ text: a }] });
105
+ } else if (n.role === "assistant")
106
+ if (typeof n.content == "string")
107
+ s.push({ role: "model", parts: [{ text: n.content }] });
108
+ else {
109
+ const a = n.content, o = [];
110
+ for (const i of a)
111
+ if (i.type === "text" && i.text)
112
+ o.push({ text: i.text });
113
+ else if (i.type === "tool_use") {
114
+ const r = {
115
+ functionCall: {
116
+ name: i.name,
117
+ args: i.input || {}
118
+ }
119
+ };
120
+ i.metadata?.thoughtSignature && (r.thoughtSignature = i.metadata.thoughtSignature), o.push(r);
121
+ }
122
+ o.length > 0 && s.push({ role: "model", parts: o });
123
+ }
124
+ return { messages: s };
125
+ }
126
+ formatToolResults(t) {
127
+ return {
128
+ role: "tool_result",
129
+ content: t.map((e) => `${e.toolName || e.toolUseId}: ${e.content}`).join(`
130
+ `),
131
+ _toolResults: t
132
+ };
133
+ }
134
+ shouldContinue(t) {
135
+ return t === "tool_use";
136
+ }
137
+ formatError(t) {
138
+ if (!t || !(t instanceof Error))
139
+ return "Something went wrong. Please try again.";
140
+ const e = t.message || "", s = t;
141
+ 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." : e.includes("SAFETY") ? "The request was blocked by safety filters. Please rephrase your request." : e.includes("RECITATION") ? "The response was blocked due to recitation concerns. Please try a different query." : e.startsWith("{") || e.startsWith("[") ? "The AI service encountered an error. Please try again." : e;
142
+ }
143
+ }
144
+ export {
145
+ p as GoogleProvider
146
+ };