@qozara/ai-client 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ type GenAiProviderPreference = 'auto' | 'cloud' | 'byok' | 'local-browser' | 'local' | 'disabled';
2
+ type LegacyAiProviderPreference = 'qozara-intelligence' | 'ollama' | 'window.ai';
1
3
  interface AgentChatMessage {
2
4
  role: string;
3
5
  content: string;
@@ -27,12 +29,13 @@ interface AiProvider {
27
29
  getSetupMessage(): string | null;
28
30
  }
29
31
  interface AiFactoryConfig {
30
- providerPreference: 'auto' | 'byok' | 'local' | 'local-browser' | 'cloud' | 'disabled';
32
+ providerPreference: GenAiProviderPreference | LegacyAiProviderPreference;
31
33
  encryptedApiKey?: string;
32
34
  baseUrl?: string;
33
35
  proxyUrl?: string;
34
36
  ollamaModel?: string;
35
37
  byokProvider?: string;
38
+ enableLocalAi?: boolean;
36
39
  }
37
40
  type AuthTokenGetter = () => string | null | undefined | Promise<string | null | undefined>;
38
41
 
@@ -77,7 +80,7 @@ declare class DisabledAiProvider implements AiProvider {
77
80
  error: string;
78
81
  }>;
79
82
  checkAvailability(): Promise<boolean>;
80
- getSetupMessage(): null;
83
+ getSetupMessage(): string;
81
84
  }
82
85
  declare class AiProviderFactory {
83
86
  static createProvider(config: AiFactoryConfig, getAuthToken?: AuthTokenGetter): Promise<AiProvider>;
@@ -104,4 +107,118 @@ declare class AgentClient {
104
107
  chat(request: AgentClientChatOptions): Promise<AgentChatResponse>;
105
108
  }
106
109
 
107
- export { type AgentChatMessage, type AgentChatRequest, type AgentChatResponse, type AgentChatTool, AgentClient, type AgentClientChatOptions, type AiFactoryConfig, type AiProvider, AiProviderFactory, type AuthTokenGetter, DisabledAiProvider, LocalOllamaProvider, ProxyAiProvider, WindowAiProvider };
110
+ declare class LruMemoryCache<K, V> {
111
+ readonly capacity: number;
112
+ private readonly map;
113
+ constructor(capacity?: number);
114
+ get(key: K): V | undefined;
115
+ set(key: K, value: V): void;
116
+ has(key: K): boolean;
117
+ clear(): void;
118
+ get size(): number;
119
+ }
120
+
121
+ type AiErrorCode = 'RATE_LIMIT_EXCEEDED' | 'AI_DISABLED' | 'NO_ITEMS_PARSED' | 'NETWORK_ERROR' | 'AUTHENTICATION_REQUIRED' | 'PARSE_FAILED';
122
+ declare class AiError extends Error {
123
+ readonly code: AiErrorCode;
124
+ readonly cause?: unknown;
125
+ constructor(code: AiErrorCode, message: string, cause?: unknown);
126
+ }
127
+
128
+ declare function classifyAiError(err: unknown): AiError;
129
+
130
+ interface UserAiSettings {
131
+ providerPreference: GenAiProviderPreference;
132
+ enableLocalAi?: boolean;
133
+ encryptedApiKey?: string;
134
+ byokProvider?: string;
135
+ ollamaBaseUrl?: string;
136
+ ollamaModel?: string;
137
+ }
138
+ declare const DEFAULT_USER_AI_SETTINGS: UserAiSettings;
139
+ declare function normalizeProviderPreference(provider?: string | null, enabled?: boolean): GenAiProviderPreference;
140
+ declare function isGenAiEnabled(settings?: {
141
+ providerPreference?: string | null;
142
+ provider?: string | null;
143
+ enabled?: boolean;
144
+ } | null): boolean;
145
+
146
+ declare class AiKeyEncryptionService {
147
+ /**
148
+ * Encrypts a user's personal provider API key using the edge KMS proxy.
149
+ * Returns a secure ciphertext string to store safely in local or cloud storage.
150
+ */
151
+ static encryptApiKey(rawApiKey: string, proxyUrl: string, getAuthToken?: AuthTokenGetter): Promise<string>;
152
+ }
153
+ interface ValidateAndPrepareAiSettingsOptions {
154
+ providerPreference: GenAiProviderPreference | LegacyAiProviderPreference | string;
155
+ enableLocalAi?: boolean;
156
+ rawApiKey?: string;
157
+ existingEncryptedApiKey?: string;
158
+ byokProvider?: string;
159
+ ollamaBaseUrl?: string;
160
+ ollamaModel?: string;
161
+ proxyUrl?: string;
162
+ getAuthToken?: AuthTokenGetter;
163
+ probeAvailability?: boolean;
164
+ }
165
+ interface PreparedAiSettingsResult {
166
+ settings: UserAiSettings;
167
+ isReachable: boolean;
168
+ setupMessage: string | null;
169
+ }
170
+ declare function validateAndPrepareAiSettings(options: ValidateAndPrepareAiSettingsOptions): Promise<PreparedAiSettingsResult>;
171
+
172
+ interface ExtractedToolCall<TArgs = Record<string, any>> {
173
+ toolName?: string;
174
+ args: TArgs;
175
+ }
176
+ declare function extractToolCallData<TArgs = Record<string, any>>(response: unknown): ExtractedToolCall<TArgs> | null;
177
+
178
+ interface GenAiToolResolverConfig<TInput, TOutput, TArgs = Record<string, any>> {
179
+ factoryConfig: AiFactoryConfig | ((input: TInput) => AiFactoryConfig | Promise<AiFactoryConfig>);
180
+ getAuthToken?: AuthTokenGetter;
181
+ cache?: LruMemoryCache<string, TOutput> | null;
182
+ cacheCapacity?: number;
183
+ getCacheKey?: (input: TInput) => string | null;
184
+ buildRequest: (input: TInput) => AgentChatRequest | Promise<AgentChatRequest>;
185
+ parseResponse: (extracted: ExtractedToolCall<TArgs> | null, rawResponse: AgentChatResponse, input: TInput) => TOutput | null | Promise<TOutput | null>;
186
+ }
187
+ declare class GenAiToolResolver<TInput, TOutput, TArgs = Record<string, any>> {
188
+ private readonly config;
189
+ readonly kind: "genai";
190
+ private readonly cache;
191
+ constructor(config: GenAiToolResolverConfig<TInput, TOutput, TArgs>);
192
+ clearCache(): void;
193
+ resolve(input: TInput): Promise<TOutput | null>;
194
+ }
195
+ declare function createGenAiToolResolver<TInput, TOutput, TArgs = Record<string, any>>(config: GenAiToolResolverConfig<TInput, TOutput, TArgs>): GenAiToolResolver<TInput, TOutput, TArgs>;
196
+
197
+ type AiResolutionSource = 'symbolic' | 'composite' | 'symbolic-fallback';
198
+ interface AiResolutionResult<TOutput> {
199
+ output: TOutput;
200
+ source: AiResolutionSource;
201
+ }
202
+ interface IAiResolver<TInput, TOutput, TContext = void> {
203
+ readonly id: string;
204
+ readonly kind: 'symbolic' | 'genai' | 'composite';
205
+ resolve(input: TInput, context: TContext): Promise<TOutput>;
206
+ }
207
+ interface CompositeAiResolverConfig<TInput, TOutput, TContext = void> {
208
+ id?: string;
209
+ symbolicResolve: (input: TInput, context: TContext) => TOutput | Promise<TOutput>;
210
+ shouldEscalate: (symbolicOutput: TOutput, input: TInput, context: TContext) => boolean;
211
+ genAiResolve?: (input: TInput, symbolicOutput: TOutput, context: TContext) => Promise<TOutput | null>;
212
+ onGenAiError?: (err: unknown, symbolicOutput: TOutput, input: TInput, context: TContext) => TOutput;
213
+ }
214
+ declare class CompositeAiResolver<TInput, TOutput, TContext = void> implements IAiResolver<TInput, TOutput, TContext> {
215
+ private readonly config;
216
+ readonly id: string;
217
+ readonly kind: "composite";
218
+ constructor(config: CompositeAiResolverConfig<TInput, TOutput, TContext>);
219
+ resolveWithMetadata(input: TInput, context: TContext): Promise<AiResolutionResult<TOutput>>;
220
+ resolve(input: TInput, context: TContext): Promise<TOutput>;
221
+ }
222
+ declare function createCompositeAiResolver<TInput, TOutput, TContext = void>(config: CompositeAiResolverConfig<TInput, TOutput, TContext>): CompositeAiResolver<TInput, TOutput, TContext>;
223
+
224
+ export { type AgentChatMessage, type AgentChatRequest, type AgentChatResponse, type AgentChatTool, AgentClient, type AgentClientChatOptions, AiError as AiCommandError, AiError, type AiErrorCode, type AiFactoryConfig, AiKeyEncryptionService, AiError as AiMealError, type AiProvider, AiProviderFactory, type AiResolutionResult, type AiResolutionSource, type AuthTokenGetter, CompositeAiResolver, type CompositeAiResolverConfig, DEFAULT_USER_AI_SETTINGS, DisabledAiProvider, type ExtractedToolCall, type GenAiProviderPreference, GenAiToolResolver, type GenAiToolResolverConfig, type IAiResolver, type LegacyAiProviderPreference, LocalOllamaProvider, LruMemoryCache, type PreparedAiSettingsResult, ProxyAiProvider, type UserAiSettings, type ValidateAndPrepareAiSettingsOptions, WindowAiProvider, classifyAiError, createCompositeAiResolver, createGenAiToolResolver, extractToolCallData, isGenAiEnabled, normalizeProviderPreference, validateAndPrepareAiSettings };
package/dist/index.js CHANGED
@@ -240,39 +240,84 @@ var LocalOllamaProvider = class {
240
240
  }
241
241
  };
242
242
 
243
+ // src/settings/normalize.ts
244
+ var DEFAULT_USER_AI_SETTINGS = {
245
+ providerPreference: "auto",
246
+ enableLocalAi: false,
247
+ byokProvider: "google",
248
+ ollamaBaseUrl: "http://localhost:11434/api"
249
+ };
250
+ function normalizeProviderPreference(provider, enabled) {
251
+ if (enabled === false) {
252
+ return "disabled";
253
+ }
254
+ switch ((provider || "").trim()) {
255
+ case "disabled":
256
+ return "disabled";
257
+ case "byok":
258
+ return "byok";
259
+ case "local":
260
+ case "ollama":
261
+ return "local";
262
+ case "local-browser":
263
+ case "window.ai":
264
+ return "local-browser";
265
+ case "cloud":
266
+ case "qozara-intelligence":
267
+ return "cloud";
268
+ case "auto":
269
+ default:
270
+ return "auto";
271
+ }
272
+ }
273
+ function isGenAiEnabled(settings) {
274
+ if (!settings) {
275
+ return true;
276
+ }
277
+ return normalizeProviderPreference(
278
+ settings.providerPreference ?? settings.provider,
279
+ settings.enabled
280
+ ) !== "disabled";
281
+ }
282
+
243
283
  // src/providers/AiProviderFactory.ts
244
284
  var DisabledAiProvider = class {
245
285
  id = "disabled";
246
286
  mode = "disabled";
247
287
  async chat() {
248
- return { type: "text", error: "AI is disabled" };
288
+ return { type: "text", error: "GenAI is disabled" };
249
289
  }
250
290
  async checkAvailability() {
251
291
  return false;
252
292
  }
253
293
  getSetupMessage() {
254
- return null;
294
+ return "Generative AI is disabled. Natural language parsing runs 100% offline using built-in deterministic AI.";
255
295
  }
256
296
  };
257
297
  var AiProviderFactory = class {
258
298
  static async createProvider(config, getAuthToken) {
259
- const { providerPreference, encryptedApiKey, baseUrl, proxyUrl, byokProvider } = config;
260
- if (providerPreference === "disabled") {
299
+ const { providerPreference, encryptedApiKey, baseUrl, proxyUrl, byokProvider, enableLocalAi } = config;
300
+ const normalizedPreference = normalizeProviderPreference(providerPreference);
301
+ const isLocalAiOptedIn = Boolean(enableLocalAi);
302
+ if (normalizedPreference === "disabled") {
261
303
  return new DisabledAiProvider();
262
304
  }
263
- if (providerPreference === "byok" && encryptedApiKey && proxyUrl) {
305
+ if (normalizedPreference === "byok" && encryptedApiKey && proxyUrl) {
264
306
  return new ProxyAiProvider(proxyUrl, getAuthToken, encryptedApiKey, byokProvider);
265
307
  }
266
- if (providerPreference === "local") {
267
- return new LocalOllamaProvider(baseUrl, config.ollamaModel);
308
+ if (normalizedPreference === "local") {
309
+ if (isLocalAiOptedIn) {
310
+ return new LocalOllamaProvider(baseUrl, config.ollamaModel);
311
+ }
312
+ return new DisabledAiProvider();
268
313
  }
269
- if (providerPreference === "local-browser") {
314
+ if (normalizedPreference === "local-browser") {
270
315
  return new WindowAiProvider();
271
316
  }
272
- if (providerPreference === "cloud" && proxyUrl) {
317
+ if (normalizedPreference === "cloud" && proxyUrl) {
273
318
  return new ProxyAiProvider(proxyUrl, getAuthToken, encryptedApiKey, byokProvider);
274
319
  }
275
- if (providerPreference === "auto") {
320
+ if (normalizedPreference === "auto") {
276
321
  if (encryptedApiKey && proxyUrl) {
277
322
  return new ProxyAiProvider(proxyUrl, getAuthToken, encryptedApiKey, byokProvider);
278
323
  }
@@ -280,9 +325,11 @@ var AiProviderFactory = class {
280
325
  if (await windowProvider.checkAvailability()) {
281
326
  return windowProvider;
282
327
  }
283
- const localProvider = new LocalOllamaProvider(baseUrl, config.ollamaModel);
284
- if (await localProvider.checkAvailability()) {
285
- return localProvider;
328
+ if (isLocalAiOptedIn) {
329
+ const localProvider = new LocalOllamaProvider(baseUrl, config.ollamaModel);
330
+ if (await localProvider.checkAvailability()) {
331
+ return localProvider;
332
+ }
286
333
  }
287
334
  if (proxyUrl) {
288
335
  return new ProxyAiProvider(proxyUrl, getAuthToken, void 0, byokProvider);
@@ -291,17 +338,22 @@ var AiProviderFactory = class {
291
338
  return new DisabledAiProvider();
292
339
  }
293
340
  static getSetupMessage(providerId, config) {
294
- switch (providerId) {
341
+ switch ((providerId || "").trim()) {
295
342
  case "local":
296
343
  case "local-ollama":
344
+ case "ollama":
297
345
  return new LocalOllamaProvider(config?.baseUrl, config?.ollamaModel).getSetupMessage();
298
346
  case "local-browser":
299
347
  case "window-ai":
348
+ case "window.ai":
300
349
  return new WindowAiProvider().getSetupMessage();
301
350
  case "byok":
302
351
  return "Enter your Gemini API key below. It will be encrypted and stored solely in your personal storage.";
303
352
  case "cloud":
304
- return "Using Qozara Intelligence (Rate-limited).";
353
+ case "qozara-intelligence":
354
+ return "Using Qozara Intelligence (Requires registered Qozara Google account).";
355
+ case "disabled":
356
+ return "Generative AI is disabled. Natural language parsing runs 100% offline using built-in deterministic AI.";
305
357
  default:
306
358
  return null;
307
359
  }
@@ -371,11 +423,358 @@ var AgentClient = class {
371
423
  return await response.json();
372
424
  }
373
425
  };
426
+
427
+ // src/cache/LruMemoryCache.ts
428
+ var LruMemoryCache = class {
429
+ constructor(capacity = 50) {
430
+ this.capacity = capacity;
431
+ if (capacity <= 0) {
432
+ throw new Error("LruMemoryCache capacity must be greater than 0");
433
+ }
434
+ }
435
+ capacity;
436
+ map = /* @__PURE__ */ new Map();
437
+ get(key) {
438
+ if (!this.map.has(key)) {
439
+ return void 0;
440
+ }
441
+ const val = this.map.get(key);
442
+ this.map.delete(key);
443
+ this.map.set(key, val);
444
+ return val;
445
+ }
446
+ set(key, value) {
447
+ if (this.map.has(key)) {
448
+ this.map.delete(key);
449
+ } else if (this.map.size >= this.capacity) {
450
+ const oldestKey = this.map.keys().next().value;
451
+ if (oldestKey !== void 0) {
452
+ this.map.delete(oldestKey);
453
+ }
454
+ }
455
+ this.map.set(key, value);
456
+ }
457
+ has(key) {
458
+ return this.map.has(key);
459
+ }
460
+ clear() {
461
+ this.map.clear();
462
+ }
463
+ get size() {
464
+ return this.map.size;
465
+ }
466
+ };
467
+
468
+ // src/errors/AiError.ts
469
+ var AiError = class extends Error {
470
+ constructor(code, message, cause) {
471
+ super(message);
472
+ this.code = code;
473
+ this.cause = cause;
474
+ this.name = "AiError";
475
+ Object.setPrototypeOf(this, new.target.prototype);
476
+ }
477
+ code;
478
+ cause;
479
+ };
480
+ function classifyAiError(err) {
481
+ if (err instanceof AiError) {
482
+ return err;
483
+ }
484
+ const msg = err instanceof Error ? err.message : String(err);
485
+ if (/RATE_LIMIT|quota|Too Many Requests|429/i.test(msg)) {
486
+ return new AiError("RATE_LIMIT_EXCEEDED", msg, err);
487
+ }
488
+ if (/AI is disabled|GenAI is disabled/i.test(msg)) {
489
+ return new AiError("AI_DISABLED", msg, err);
490
+ }
491
+ if (/no food items|Could not extract/i.test(msg)) {
492
+ return new AiError("NO_ITEMS_PARSED", msg, err);
493
+ }
494
+ if (/Failed to fetch|Network error|ECONNREFUSED|ENOTFOUND|timeout|unreachable/i.test(msg)) {
495
+ return new AiError("NETWORK_ERROR", msg, err);
496
+ }
497
+ if (/Unauthorized|401|403|Forbidden|expired Google token/i.test(msg) || /invalid/i.test(msg) && /token/i.test(msg)) {
498
+ return new AiError("AUTHENTICATION_REQUIRED", msg, err);
499
+ }
500
+ return new AiError("PARSE_FAILED", msg, err);
501
+ }
502
+
503
+ // src/settings/index.ts
504
+ var AiKeyEncryptionService = class {
505
+ /**
506
+ * Encrypts a user's personal provider API key using the edge KMS proxy.
507
+ * Returns a secure ciphertext string to store safely in local or cloud storage.
508
+ */
509
+ static async encryptApiKey(rawApiKey, proxyUrl, getAuthToken) {
510
+ const trimmedKey = (rawApiKey || "").trim();
511
+ if (!trimmedKey) {
512
+ throw new Error("API key cannot be empty");
513
+ }
514
+ const cleanUrl = (proxyUrl || "").trim().replace(/\/+$/, "");
515
+ if (!cleanUrl) {
516
+ throw new Error("AI proxy URL is required to encrypt API key");
517
+ }
518
+ const client = new AgentClient(cleanUrl, getAuthToken);
519
+ return await client.encryptApiKey(trimmedKey);
520
+ }
521
+ };
522
+ async function validateAndPrepareAiSettings(options) {
523
+ const pref = normalizeProviderPreference(options.providerPreference);
524
+ let encryptedApiKey = options.existingEncryptedApiKey;
525
+ if (pref === "byok" && options.rawApiKey && options.rawApiKey.trim()) {
526
+ encryptedApiKey = await AiKeyEncryptionService.encryptApiKey(
527
+ options.rawApiKey,
528
+ options.proxyUrl || "",
529
+ options.getAuthToken
530
+ );
531
+ }
532
+ const enableLocalAi = Boolean(options.enableLocalAi);
533
+ const trimmedOllamaUrl = options.ollamaBaseUrl?.trim() || void 0;
534
+ const trimmedOllamaModel = options.ollamaModel?.trim() || void 0;
535
+ const byokProvider = options.byokProvider?.trim() || "google";
536
+ const settings = {
537
+ providerPreference: pref,
538
+ enableLocalAi,
539
+ ...encryptedApiKey ? { encryptedApiKey } : {},
540
+ byokProvider,
541
+ ...trimmedOllamaUrl ? { ollamaBaseUrl: trimmedOllamaUrl } : {},
542
+ ...trimmedOllamaModel ? { ollamaModel: trimmedOllamaModel } : {}
543
+ };
544
+ const setupMessage = AiProviderFactory.getSetupMessage(pref, {
545
+ baseUrl: trimmedOllamaUrl,
546
+ ollamaModel: trimmedOllamaModel
547
+ });
548
+ let isReachable = true;
549
+ if (pref !== "disabled" && options.probeAvailability !== false) {
550
+ const provider = await AiProviderFactory.createProvider(
551
+ {
552
+ providerPreference: pref,
553
+ enableLocalAi,
554
+ encryptedApiKey,
555
+ byokProvider,
556
+ baseUrl: enableLocalAi ? trimmedOllamaUrl : void 0,
557
+ ollamaModel: trimmedOllamaModel,
558
+ proxyUrl: options.proxyUrl
559
+ },
560
+ options.getAuthToken
561
+ );
562
+ isReachable = await provider.checkAvailability();
563
+ }
564
+ return {
565
+ settings,
566
+ isReachable,
567
+ setupMessage
568
+ };
569
+ }
570
+
571
+ // src/resolvers/extractToolCallData.ts
572
+ function parseJsonPayload(raw) {
573
+ if (raw === null || raw === void 0) return null;
574
+ if (typeof raw === "object") return raw;
575
+ if (typeof raw !== "string") return null;
576
+ const trimmed = raw.trim();
577
+ if (!trimmed) return null;
578
+ try {
579
+ return JSON.parse(trimmed);
580
+ } catch {
581
+ const fenceMatch = trimmed.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
582
+ if (fenceMatch && fenceMatch[1]) {
583
+ try {
584
+ return JSON.parse(fenceMatch[1].trim());
585
+ } catch {
586
+ }
587
+ }
588
+ const firstBrace = trimmed.indexOf("{");
589
+ const lastBrace = trimmed.lastIndexOf("}");
590
+ if (firstBrace !== -1 && lastBrace > firstBrace) {
591
+ try {
592
+ return JSON.parse(trimmed.slice(firstBrace, lastBrace + 1));
593
+ } catch {
594
+ return null;
595
+ }
596
+ }
597
+ return null;
598
+ }
599
+ }
600
+ function extractToolCallData(response) {
601
+ if (!response || typeof response !== "object") {
602
+ return null;
603
+ }
604
+ const res = response;
605
+ if (res.arguments !== void 0 && res.arguments !== null) {
606
+ const parsed = parseJsonPayload(res.arguments);
607
+ if (parsed && typeof parsed === "object") {
608
+ return {
609
+ toolName: typeof res.tool === "string" ? res.tool : void 0,
610
+ args: parsed
611
+ };
612
+ }
613
+ }
614
+ if (Array.isArray(res.tool_calls) && res.tool_calls.length > 0) {
615
+ const call = res.tool_calls[0];
616
+ const rawArgs = call?.function?.arguments ?? call?.arguments ?? call;
617
+ const parsed = parseJsonPayload(rawArgs);
618
+ if (parsed && typeof parsed === "object") {
619
+ return {
620
+ toolName: call?.function?.name || call?.name || (typeof res.tool === "string" ? res.tool : void 0),
621
+ args: parsed
622
+ };
623
+ }
624
+ }
625
+ const choiceMsg = res.choices?.[0]?.message;
626
+ if (choiceMsg && typeof choiceMsg === "object") {
627
+ if (Array.isArray(choiceMsg.tool_calls) && choiceMsg.tool_calls.length > 0) {
628
+ const call = choiceMsg.tool_calls[0];
629
+ const rawArgs = call?.function?.arguments ?? call?.arguments;
630
+ const parsed = parseJsonPayload(rawArgs);
631
+ if (parsed && typeof parsed === "object") {
632
+ return {
633
+ toolName: call?.function?.name || call?.name,
634
+ args: parsed
635
+ };
636
+ }
637
+ }
638
+ if (choiceMsg.content) {
639
+ const parsed = parseJsonPayload(choiceMsg.content);
640
+ if (parsed && typeof parsed === "object") {
641
+ if (typeof parsed.tool === "string" && parsed.arguments && typeof parsed.arguments === "object") {
642
+ return { toolName: parsed.tool, args: parsed.arguments };
643
+ }
644
+ return { args: parsed };
645
+ }
646
+ }
647
+ }
648
+ if (res.content) {
649
+ const parsed = parseJsonPayload(res.content);
650
+ if (parsed && typeof parsed === "object") {
651
+ if (typeof parsed.tool === "string" && parsed.arguments && typeof parsed.arguments === "object") {
652
+ return { toolName: parsed.tool, args: parsed.arguments };
653
+ }
654
+ return {
655
+ toolName: typeof res.tool === "string" ? res.tool : void 0,
656
+ args: parsed
657
+ };
658
+ }
659
+ }
660
+ return null;
661
+ }
662
+
663
+ // src/resolvers/GenAiToolResolver.ts
664
+ var GenAiToolResolver = class {
665
+ constructor(config) {
666
+ this.config = config;
667
+ if (config.cache === null) {
668
+ this.cache = null;
669
+ } else if (config.cache) {
670
+ this.cache = config.cache;
671
+ } else if (config.getCacheKey) {
672
+ this.cache = new LruMemoryCache(config.cacheCapacity ?? 50);
673
+ } else {
674
+ this.cache = null;
675
+ }
676
+ }
677
+ config;
678
+ kind = "genai";
679
+ cache;
680
+ clearCache() {
681
+ this.cache?.clear();
682
+ }
683
+ async resolve(input) {
684
+ const cacheKey = this.config.getCacheKey ? this.config.getCacheKey(input) : null;
685
+ if (this.cache && cacheKey) {
686
+ const cached = this.cache.get(cacheKey);
687
+ if (cached !== void 0 && cached !== null) {
688
+ return cached;
689
+ }
690
+ }
691
+ try {
692
+ const resolvedFactoryConfig = typeof this.config.factoryConfig === "function" ? await this.config.factoryConfig(input) : this.config.factoryConfig;
693
+ const provider = await AiProviderFactory.createProvider(
694
+ resolvedFactoryConfig,
695
+ this.config.getAuthToken
696
+ );
697
+ const request = await this.config.buildRequest(input);
698
+ const response = await provider.chat(request);
699
+ if (!response) {
700
+ return null;
701
+ }
702
+ if (response.error) {
703
+ throw classifyAiError(new Error(response.error));
704
+ }
705
+ const extracted = extractToolCallData(response);
706
+ const result = await this.config.parseResponse(extracted, response, input);
707
+ if (result !== null && result !== void 0 && this.cache && cacheKey) {
708
+ this.cache.set(cacheKey, result);
709
+ }
710
+ return result ?? null;
711
+ } catch (err) {
712
+ throw classifyAiError(err);
713
+ }
714
+ }
715
+ };
716
+ function createGenAiToolResolver(config) {
717
+ return new GenAiToolResolver(config);
718
+ }
719
+
720
+ // src/resolvers/CompositeAiResolver.ts
721
+ var CompositeAiResolver = class {
722
+ constructor(config) {
723
+ this.config = config;
724
+ this.id = config.id || "composite-ai-resolver";
725
+ }
726
+ config;
727
+ id;
728
+ kind = "composite";
729
+ async resolveWithMetadata(input, context) {
730
+ const symbolicOutput = await this.config.symbolicResolve(input, context);
731
+ if (!this.config.genAiResolve || !this.config.shouldEscalate(symbolicOutput, input, context)) {
732
+ return { output: symbolicOutput, source: "symbolic" };
733
+ }
734
+ try {
735
+ const genAiOutput = await this.config.genAiResolve(input, symbolicOutput, context);
736
+ if (genAiOutput !== null && genAiOutput !== void 0) {
737
+ return { output: genAiOutput, source: "composite" };
738
+ }
739
+ return { output: symbolicOutput, source: "symbolic-fallback" };
740
+ } catch (err) {
741
+ if (this.config.onGenAiError) {
742
+ return {
743
+ output: this.config.onGenAiError(err, symbolicOutput, input, context),
744
+ source: "symbolic-fallback"
745
+ };
746
+ }
747
+ throw err;
748
+ }
749
+ }
750
+ async resolve(input, context) {
751
+ const { output } = await this.resolveWithMetadata(input, context);
752
+ return output;
753
+ }
754
+ };
755
+ function createCompositeAiResolver(config) {
756
+ return new CompositeAiResolver(config);
757
+ }
374
758
  export {
375
759
  AgentClient,
760
+ AiError as AiCommandError,
761
+ AiError,
762
+ AiKeyEncryptionService,
763
+ AiError as AiMealError,
376
764
  AiProviderFactory,
765
+ CompositeAiResolver,
766
+ DEFAULT_USER_AI_SETTINGS,
377
767
  DisabledAiProvider,
768
+ GenAiToolResolver,
378
769
  LocalOllamaProvider,
770
+ LruMemoryCache,
379
771
  ProxyAiProvider,
380
- WindowAiProvider
772
+ WindowAiProvider,
773
+ classifyAiError,
774
+ createCompositeAiResolver,
775
+ createGenAiToolResolver,
776
+ extractToolCallData,
777
+ isGenAiEnabled,
778
+ normalizeProviderPreference,
779
+ validateAndPrepareAiSettings
381
780
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qozara/ai-client",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Isomorphic AI client SDK for Qozara ecosystem with polymorphic fallback and KMS envelope encryption support",
5
5
  "files": [
6
6
  "dist"
@@ -1,21 +0,0 @@
1
- import { AgentChatRequest, AgentChatResponse, AuthTokenGetter } from './providers/types.js';
2
- export interface AgentClientChatOptions extends AgentChatRequest {
3
- ciphertext?: string;
4
- byokProvider?: string;
5
- }
6
- export declare class AgentClient {
7
- private getAuthToken?;
8
- private base;
9
- constructor(baseUrl?: string, getAuthToken?: AuthTokenGetter | undefined);
10
- /**
11
- * Encrypts a personal API key using the edge proxy's KMS_SECRET.
12
- * Works completely unauthenticated (zero login required).
13
- */
14
- encryptApiKey(apiKey: string): Promise<string>;
15
- /**
16
- * Sends a chat request to the edge proxy.
17
- * Auth token is optional (unauthenticated clients can use BYOK or anonymous tier).
18
- */
19
- chat(request: AgentClientChatOptions): Promise<AgentChatResponse>;
20
- }
21
- //# sourceMappingURL=AgentClient.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"AgentClient.d.ts","sourceRoot":"","sources":["../src/AgentClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAE5F,MAAM,WAAW,sBAAuB,SAAQ,gBAAgB;IAC5D,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,qBAAa,WAAW;IAKhB,OAAO,CAAC,YAAY,CAAC;IAJzB,OAAO,CAAC,IAAI,CAAS;gBAGjB,OAAO,GAAE,MAAW,EACZ,YAAY,CAAC,EAAE,eAAe,YAAA;IAK1C;;;OAGG;IACG,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IA2BpD;;;OAGG;IACG,IAAI,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,iBAAiB,CAAC;CA4B1E"}
@@ -1,63 +0,0 @@
1
- export class AgentClient {
2
- getAuthToken;
3
- base;
4
- constructor(baseUrl = '', getAuthToken) {
5
- this.getAuthToken = getAuthToken;
6
- this.base = (baseUrl || '').replace(/\/$/, '');
7
- }
8
- /**
9
- * Encrypts a personal API key using the edge proxy's KMS_SECRET.
10
- * Works completely unauthenticated (zero login required).
11
- */
12
- async encryptApiKey(apiKey) {
13
- const headers = {
14
- 'Content-Type': 'application/json',
15
- };
16
- if (this.getAuthToken) {
17
- const token = await this.getAuthToken();
18
- if (token) {
19
- headers['Authorization'] = `Bearer ${token}`;
20
- }
21
- }
22
- const response = await fetch(`${this.base}/api/v1/agent/encrypt`, {
23
- method: 'POST',
24
- headers,
25
- body: JSON.stringify({ apiKey }),
26
- });
27
- if (!response.ok) {
28
- const error = await response.json().catch(() => ({}));
29
- throw new Error(error.message || error.error || `Encryption failed (${response.status})`);
30
- }
31
- const result = await response.json();
32
- return result.ciphertext;
33
- }
34
- /**
35
- * Sends a chat request to the edge proxy.
36
- * Auth token is optional (unauthenticated clients can use BYOK or anonymous tier).
37
- */
38
- async chat(request) {
39
- const headers = {
40
- 'Content-Type': 'application/json',
41
- };
42
- if (this.getAuthToken) {
43
- const token = await this.getAuthToken();
44
- if (token) {
45
- headers['Authorization'] = `Bearer ${token}`;
46
- }
47
- }
48
- const response = await fetch(`${this.base}/api/v1/agent/chat`, {
49
- method: 'POST',
50
- headers,
51
- body: JSON.stringify(request),
52
- });
53
- if (!response.ok) {
54
- const error = await response.json().catch(() => ({}));
55
- return {
56
- type: 'text',
57
- error: error.code || error.message || error.error || `AI proxy request failed (${response.status})`,
58
- };
59
- }
60
- return await response.json();
61
- }
62
- }
63
- //# sourceMappingURL=AgentClient.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"AgentClient.js","sourceRoot":"","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;OAGG;IACH,KAAK,CAAC,IAAI,CAAC,OAA+B;QACtC,MAAM,OAAO,GAA2B;YACpC,cAAc,EAAE,kBAAkB;SACrC,CAAC;QAEF,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;YACxC,IAAI,KAAK,EAAE,CAAC;gBACR,OAAO,CAAC,eAAe,CAAC,GAAG,UAAU,KAAK,EAAE,CAAC;YACjD,CAAC;QACL,CAAC;QAED,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,IAAI,CAAC,IAAI,oBAAoB,EAAE;YAC3D,MAAM,EAAE,MAAM;YACd,OAAO;YACP,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;SAChC,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACf,MAAM,KAAK,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,CAAQ,CAAC;YAC7D,OAAO;gBACH,IAAI,EAAE,MAAM;gBACZ,KAAK,EAAE,KAAK,CAAC,IAAI,IAAI,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,KAAK,IAAI,4BAA4B,QAAQ,CAAC,MAAM,GAAG;aACtG,CAAC;QACN,CAAC;QAED,OAAO,MAAM,QAAQ,CAAC,IAAI,EAAuB,CAAC;IACtD,CAAC;CACJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,iCAAiC,CAAC;AAChD,cAAc,oCAAoC,CAAC;AACnD,cAAc,kCAAkC,CAAC;AACjD,cAAc,kBAAkB,CAAC"}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,iCAAiC,CAAC;AAChD,cAAc,oCAAoC,CAAC;AACnD,cAAc,kCAAkC,CAAC;AACjD,cAAc,kBAAkB,CAAC"}
@@ -1,16 +0,0 @@
1
- import { AiFactoryConfig, AiProvider, AuthTokenGetter } from './types.js';
2
- export declare class DisabledAiProvider implements AiProvider {
3
- readonly id = "disabled";
4
- readonly mode = "disabled";
5
- chat(): Promise<{
6
- type: "text";
7
- error: string;
8
- }>;
9
- checkAvailability(): Promise<boolean>;
10
- getSetupMessage(): null;
11
- }
12
- export declare class AiProviderFactory {
13
- static createProvider(config: AiFactoryConfig, getAuthToken?: AuthTokenGetter): Promise<AiProvider>;
14
- static getSetupMessage(providerId: string, config?: Partial<AiFactoryConfig>): string | null;
15
- }
16
- //# sourceMappingURL=AiProviderFactory.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"AiProviderFactory.d.ts","sourceRoot":"","sources":["../../src/providers/AiProviderFactory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAK1E,qBAAa,kBAAmB,YAAW,UAAU;IACjD,QAAQ,CAAC,EAAE,cAAc;IACzB,QAAQ,CAAC,IAAI,cAAc;IACrB,IAAI;;;;IAGJ,iBAAiB;IAGvB,eAAe;CAGlB;AAED,qBAAa,iBAAiB;WACb,cAAc,CAAC,MAAM,EAAE,eAAe,EAAE,YAAY,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,UAAU,CAAC;IAyDzG,MAAM,CAAC,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,eAAe,CAAC,GAAG,MAAM,GAAG,IAAI;CAgB/F"}
@@ -1,81 +0,0 @@
1
- import { ProxyAiProvider } from './ProxyAiProvider.js';
2
- import { WindowAiProvider } from './WindowAiProvider.js';
3
- import { LocalOllamaProvider } from './LocalOllamaProvider.js';
4
- export class DisabledAiProvider {
5
- id = 'disabled';
6
- mode = 'disabled';
7
- async chat() {
8
- return { type: 'text', error: 'AI is disabled' };
9
- }
10
- async checkAvailability() {
11
- return false;
12
- }
13
- getSetupMessage() {
14
- return null;
15
- }
16
- }
17
- export class AiProviderFactory {
18
- static async createProvider(config, getAuthToken) {
19
- const { providerPreference, encryptedApiKey, baseUrl, proxyUrl, byokProvider } = config;
20
- // Forced Disable
21
- if (providerPreference === 'disabled') {
22
- return new DisabledAiProvider();
23
- }
24
- // 1. Explicit Selection: BYOK Cloud
25
- if (providerPreference === 'byok' && encryptedApiKey && proxyUrl) {
26
- return new ProxyAiProvider(proxyUrl, getAuthToken, encryptedApiKey, byokProvider);
27
- }
28
- // 2. Explicit Selection: Local Ollama
29
- if (providerPreference === 'local') {
30
- return new LocalOllamaProvider(baseUrl, config.ollamaModel);
31
- }
32
- // 3. Explicit Selection: Local Browser AI
33
- if (providerPreference === 'local-browser') {
34
- return new WindowAiProvider();
35
- }
36
- // 4. Explicit Selection: Cloud (Qozara Intelligence / BYOK based on config)
37
- if (providerPreference === 'cloud' && proxyUrl) {
38
- return new ProxyAiProvider(proxyUrl, getAuthToken, encryptedApiKey, byokProvider);
39
- }
40
- // 5. "Auto" Mode Polymorphic Fallback Waterfall:
41
- // BYOK -> window.ai -> Local Ollama -> Qozara Intelligence Cloud Proxy
42
- if (providerPreference === 'auto') {
43
- // a) If BYOK ciphertext exists and proxy is set, prioritize user's own key
44
- if (encryptedApiKey && proxyUrl) {
45
- return new ProxyAiProvider(proxyUrl, getAuthToken, encryptedApiKey, byokProvider);
46
- }
47
- // b) If Window AI (Gemini Nano on-device) is available
48
- const windowProvider = new WindowAiProvider();
49
- if (await windowProvider.checkAvailability()) {
50
- return windowProvider;
51
- }
52
- // c) If Local Ollama daemon is active
53
- const localProvider = new LocalOllamaProvider(baseUrl, config.ollamaModel);
54
- if (await localProvider.checkAvailability()) {
55
- return localProvider;
56
- }
57
- // d) Last resort: Qozara Intelligence edge proxy
58
- if (proxyUrl) {
59
- return new ProxyAiProvider(proxyUrl, getAuthToken, undefined, byokProvider);
60
- }
61
- }
62
- return new DisabledAiProvider();
63
- }
64
- static getSetupMessage(providerId, config) {
65
- switch (providerId) {
66
- case 'local':
67
- case 'local-ollama':
68
- return new LocalOllamaProvider(config?.baseUrl, config?.ollamaModel).getSetupMessage();
69
- case 'local-browser':
70
- case 'window-ai':
71
- return new WindowAiProvider().getSetupMessage();
72
- case 'byok':
73
- return 'Enter your Gemini API key below. It will be encrypted and stored solely in your personal storage.';
74
- case 'cloud':
75
- return 'Using Qozara Intelligence (Rate-limited).';
76
- default:
77
- return null;
78
- }
79
- }
80
- }
81
- //# sourceMappingURL=AiProviderFactory.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"AiProviderFactory.js","sourceRoot":"","sources":["../../src/providers/AiProviderFactory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAE/D,MAAM,OAAO,kBAAkB;IAClB,EAAE,GAAG,UAAU,CAAC;IAChB,IAAI,GAAG,UAAU,CAAC;IAC3B,KAAK,CAAC,IAAI;QACN,OAAO,EAAE,IAAI,EAAE,MAAe,EAAE,KAAK,EAAE,gBAAgB,EAAE,CAAC;IAC9D,CAAC;IACD,KAAK,CAAC,iBAAiB;QACnB,OAAO,KAAK,CAAC;IACjB,CAAC;IACD,eAAe;QACX,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ;AAED,MAAM,OAAO,iBAAiB;IAC1B,MAAM,CAAC,KAAK,CAAC,cAAc,CAAC,MAAuB,EAAE,YAA8B;QAC/E,MAAM,EAAE,kBAAkB,EAAE,eAAe,EAAE,OAAO,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,CAAC,WAAW,CAAC,CAAC;YAC3E,IAAI,MAAM,aAAa,CAAC,iBAAiB,EAAE,EAAE,CAAC;gBAC1C,OAAO,aAAa,CAAC;YACzB,CAAC;YAED,iDAAiD;YACjD,IAAI,QAAQ,EAAE,CAAC;gBACX,OAAO,IAAI,eAAe,CAAC,QAAQ,EAAE,YAAY,EAAE,SAAS,EAAE,YAAY,CAAC,CAAC;YAChF,CAAC;QACL,CAAC;QAED,OAAO,IAAI,kBAAkB,EAAE,CAAC;IACpC,CAAC;IAED,MAAM,CAAC,eAAe,CAAC,UAAkB,EAAE,MAAiC;QACxE,QAAQ,UAAU,EAAE,CAAC;YACjB,KAAK,OAAO,CAAC;YACb,KAAK,cAAc;gBACf,OAAO,IAAI,mBAAmB,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC,eAAe,EAAE,CAAC;YAC3F,KAAK,eAAe,CAAC;YACrB,KAAK,WAAW;gBACZ,OAAO,IAAI,gBAAgB,EAAE,CAAC,eAAe,EAAE,CAAC;YACpD,KAAK,MAAM;gBACP,OAAO,mGAAmG,CAAC;YAC/G,KAAK,OAAO;gBACR,OAAO,2CAA2C,CAAC;YACvD;gBACI,OAAO,IAAI,CAAC;QACpB,CAAC;IACL,CAAC;CACJ"}
@@ -1,12 +0,0 @@
1
- import { AiProvider, AgentChatRequest, AgentChatResponse } from './types.js';
2
- export declare class LocalOllamaProvider implements AiProvider {
3
- readonly id = "local-ollama";
4
- readonly mode = "local-ollama";
5
- private model;
6
- private base;
7
- constructor(baseUrl?: string, model?: string);
8
- chat(request: AgentChatRequest): Promise<AgentChatResponse>;
9
- checkAvailability(): Promise<boolean>;
10
- getSetupMessage(): string | null;
11
- }
12
- //# sourceMappingURL=LocalOllamaProvider.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"LocalOllamaProvider.d.ts","sourceRoot":"","sources":["../../src/providers/LocalOllamaProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE7E,qBAAa,mBAAoB,YAAW,UAAU;IAClD,QAAQ,CAAC,EAAE,kBAAkB;IAC7B,QAAQ,CAAC,IAAI,kBAAkB;IAC/B,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,IAAI,CAAS;gBAGjB,OAAO,GAAE,MAAqC,EAC9C,KAAK,GAAE,MAAuB;IAM5B,IAAI,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAqG3D,iBAAiB,IAAI,OAAO,CAAC,OAAO,CAAC;IAa3C,eAAe,IAAI,MAAM,GAAG,IAAI;CAGnC"}
@@ -1,121 +0,0 @@
1
- export class LocalOllamaProvider {
2
- id = 'local-ollama';
3
- mode = 'local-ollama';
4
- model;
5
- base;
6
- constructor(baseUrl = 'http://localhost:11434/api', model = 'qwen2.5:0.5b') {
7
- this.base = (baseUrl || 'http://localhost:11434/api').replace(/\/$/, '');
8
- this.model = model;
9
- }
10
- async chat(request) {
11
- try {
12
- const bodyPayload = {
13
- model: this.model,
14
- messages: [
15
- { role: 'system', content: request.systemPrompt },
16
- ...request.messages
17
- ],
18
- stream: false
19
- };
20
- if (request.tools && request.tools.length > 0) {
21
- bodyPayload.tools = request.tools.map((t) => ({
22
- type: 'function',
23
- function: {
24
- name: t.name,
25
- description: t.description,
26
- parameters: t.parameters
27
- }
28
- }));
29
- }
30
- else {
31
- bodyPayload.format = 'json';
32
- }
33
- const chatUrl = this.base.endsWith('/api') ? `${this.base}/chat` : `${this.base}/api/chat`;
34
- const response = await fetch(chatUrl, {
35
- method: 'POST',
36
- headers: {
37
- 'Content-Type': 'application/json',
38
- },
39
- body: JSON.stringify(bodyPayload)
40
- });
41
- if (!response.ok) {
42
- let errorMsg = `Ollama failed (${response.status})`;
43
- try {
44
- const errBody = await response.json();
45
- if (errBody.error)
46
- errorMsg += `: ${errBody.error}`;
47
- }
48
- catch {
49
- // Ignore JSON parse error in error handler
50
- }
51
- return { type: 'text', error: errorMsg };
52
- }
53
- const data = await response.json();
54
- // Native Ollama tool calling format
55
- if (data.message?.tool_calls && data.message.tool_calls.length > 0) {
56
- const call = data.message.tool_calls[0].function;
57
- return {
58
- type: 'tool_call',
59
- tool: call.name,
60
- arguments: call.arguments
61
- };
62
- }
63
- const content = data.message?.content || '';
64
- try {
65
- const parsed = JSON.parse(content);
66
- // Pattern 1 & 2: { tool: "name", arguments: { ... } } or { action/type/tool_used: "name", ...args }
67
- const toolName = parsed.tool || parsed.action || parsed.type || parsed.tool_used;
68
- if (toolName) {
69
- const args = parsed.arguments || { ...parsed };
70
- if (args === parsed) {
71
- delete args.tool;
72
- delete args.action;
73
- delete args.type;
74
- delete args.tool_used;
75
- }
76
- return {
77
- type: 'tool_call',
78
- tool: toolName,
79
- arguments: args
80
- };
81
- }
82
- // Dynamic Pattern 3: Match root key against any registered tool from request
83
- const requestedTools = (request.tools || []).map((t) => t.name);
84
- for (const tool of requestedTools) {
85
- const key = Object.keys(parsed).find(k => k.toLowerCase() === tool.toLowerCase());
86
- if (key) {
87
- return {
88
- type: 'tool_call',
89
- tool: tool,
90
- arguments: parsed[key]
91
- };
92
- }
93
- }
94
- return { type: 'text', content };
95
- }
96
- catch {
97
- return { type: 'text', content };
98
- }
99
- }
100
- catch (error) {
101
- return { type: 'text', error: error.message || 'Local Ollama error' };
102
- }
103
- }
104
- async checkAvailability() {
105
- try {
106
- const controller = new AbortController();
107
- const id = setTimeout(() => controller.abort(), 2000);
108
- const tagsUrl = this.base.endsWith('/api') ? `${this.base}/tags` : `${this.base}/api/tags`;
109
- const response = await fetch(tagsUrl, { signal: controller.signal });
110
- clearTimeout(id);
111
- return response.ok;
112
- }
113
- catch {
114
- return false;
115
- }
116
- }
117
- getSetupMessage() {
118
- return `Note: Start Ollama with OLLAMA_ORIGINS="*" ollama serve to allow browser connections. Make sure you have pulled the model '${this.model}'.`;
119
- }
120
- }
121
- //# sourceMappingURL=LocalOllamaProvider.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"LocalOllamaProvider.js","sourceRoot":"","sources":["../../src/providers/LocalOllamaProvider.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,mBAAmB;IACnB,EAAE,GAAG,cAAc,CAAC;IACpB,IAAI,GAAG,cAAc,CAAC;IACvB,KAAK,CAAS;IACd,IAAI,CAAS;IAErB,YACI,UAAkB,4BAA4B,EAC9C,QAAgB,cAAc;QAE9B,IAAI,CAAC,IAAI,GAAG,CAAC,OAAO,IAAI,4BAA4B,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACzE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,OAAyB;QAChC,IAAI,CAAC;YACD,MAAM,WAAW,GAAQ;gBACrB,KAAK,EAAE,IAAI,CAAC,KAAK;gBACjB,QAAQ,EAAE;oBACN,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,CAAC,YAAY,EAAE;oBACjD,GAAG,OAAO,CAAC,QAAQ;iBACtB;gBACD,MAAM,EAAE,KAAK;aAChB,CAAC;YAEF,IAAI,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAC5C,WAAW,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC;oBAC/C,IAAI,EAAE,UAAU;oBAChB,QAAQ,EAAE;wBACN,IAAI,EAAE,CAAC,CAAC,IAAI;wBACZ,WAAW,EAAE,CAAC,CAAC,WAAW;wBAC1B,UAAU,EAAE,CAAC,CAAC,UAAU;qBAC3B;iBACJ,CAAC,CAAC,CAAC;YACR,CAAC;iBAAM,CAAC;gBACJ,WAAW,CAAC,MAAM,GAAG,MAAM,CAAC;YAChC,CAAC;YAED,MAAM,OAAO,G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yBACzB,CAAC;oBACN,CAAC;gBACL,CAAC;gBAED,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;YACrC,CAAC;YAAC,MAAM,CAAC;gBACL,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;YACrC,CAAC;QACL,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YAClB,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,CAAC,OAAO,IAAI,oBAAoB,EAAE,CAAC;QAC1E,CAAC;IACL,CAAC;IAED,KAAK,CAAC,iBAAiB;QACnB,IAAI,CAAC;YACD,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;YACzC,MAAM,EAAE,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,CAAC;YACtD,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,WAAW,CAAC;YAC3F,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,OAAO,EAAE,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC,CAAC;YACrE,YAAY,CAAC,EAAE,CAAC,CAAC;YACjB,OAAO,QAAQ,CAAC,EAAE,CAAC;QACvB,CAAC;QAAC,MAAM,CAAC;YACL,OAAO,KAAK,CAAC;QACjB,CAAC;IACL,CAAC;IAED,eAAe;QACX,OAAO,8HAA8H,IAAI,CAAC,KAAK,IAAI,CAAC;IACxJ,CAAC;CACJ"}
@@ -1,14 +0,0 @@
1
- import { AiProvider, AgentChatRequest, AgentChatResponse, AuthTokenGetter } from './types.js';
2
- export declare class ProxyAiProvider implements AiProvider {
3
- private getAuthToken?;
4
- private encryptedApiKey?;
5
- private byokProvider?;
6
- readonly id = "cloud-proxy";
7
- private base;
8
- get mode(): 'byok' | 'cloud';
9
- constructor(proxyUrl?: string, getAuthToken?: AuthTokenGetter | undefined, encryptedApiKey?: string | undefined, byokProvider?: string | undefined);
10
- chat(request: AgentChatRequest): Promise<AgentChatResponse>;
11
- checkAvailability(): Promise<boolean>;
12
- getSetupMessage(): string | null;
13
- }
14
- //# sourceMappingURL=ProxyAiProvider.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ProxyAiProvider.d.ts","sourceRoot":"","sources":["../../src/providers/ProxyAiProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE9F,qBAAa,eAAgB,YAAW,UAAU;IAU1C,OAAO,CAAC,YAAY,CAAC;IACrB,OAAO,CAAC,eAAe,CAAC;IACxB,OAAO,CAAC,YAAY,CAAC;IAXzB,QAAQ,CAAC,EAAE,iBAAiB;IAC5B,OAAO,CAAC,IAAI,CAAS;IAErB,IAAI,IAAI,IAAI,MAAM,GAAG,OAAO,CAE3B;gBAGG,QAAQ,GAAE,MAAW,EACb,YAAY,CAAC,EAAE,eAAe,YAAA,EAC9B,eAAe,CAAC,EAAE,MAAM,YAAA,EACxB,YAAY,CAAC,EAAE,MAAM,YAAA;IAK3B,IAAI,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAuC3D,iBAAiB,IAAI,OAAO,CAAC,OAAO,CAAC;IAa3C,eAAe,IAAI,MAAM,GAAG,IAAI;CAGnC"}
@@ -1,69 +0,0 @@
1
- export class ProxyAiProvider {
2
- getAuthToken;
3
- encryptedApiKey;
4
- byokProvider;
5
- id = 'cloud-proxy';
6
- base;
7
- get mode() {
8
- return this.encryptedApiKey ? 'byok' : 'cloud';
9
- }
10
- constructor(proxyUrl = '', getAuthToken, encryptedApiKey, byokProvider) {
11
- this.getAuthToken = getAuthToken;
12
- this.encryptedApiKey = encryptedApiKey;
13
- this.byokProvider = byokProvider;
14
- this.base = (proxyUrl || '').replace(/\/$/, '');
15
- }
16
- async chat(request) {
17
- try {
18
- const headers = {
19
- 'Content-Type': 'application/json',
20
- };
21
- if (this.getAuthToken) {
22
- const token = await this.getAuthToken();
23
- if (token) {
24
- headers['Authorization'] = `Bearer ${token}`;
25
- }
26
- }
27
- const response = await fetch(`${this.base}/api/v1/agent/chat`, {
28
- method: 'POST',
29
- headers,
30
- body: JSON.stringify({
31
- messages: request.messages,
32
- systemPrompt: request.systemPrompt,
33
- tools: request.tools,
34
- ciphertext: this.encryptedApiKey,
35
- byokProvider: this.byokProvider,
36
- }),
37
- });
38
- if (!response.ok) {
39
- const error = await response.json().catch(() => ({}));
40
- return {
41
- type: 'text',
42
- error: error.code || error.message || error.error || `Proxy request failed (${response.status})`,
43
- };
44
- }
45
- return await response.json();
46
- }
47
- catch (error) {
48
- return { type: 'text', error: error.message || 'Network error communicating with AI proxy' };
49
- }
50
- }
51
- async checkAvailability() {
52
- if (!this.base)
53
- return false;
54
- try {
55
- const controller = new AbortController();
56
- const id = setTimeout(() => controller.abort(), 3000);
57
- const response = await fetch(`${this.base}/health`, { signal: controller.signal });
58
- clearTimeout(id);
59
- return response.ok;
60
- }
61
- catch {
62
- return false;
63
- }
64
- }
65
- getSetupMessage() {
66
- return null;
67
- }
68
- }
69
- //# sourceMappingURL=ProxyAiProvider.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ProxyAiProvider.js","sourceRoot":"","sources":["../../src/providers/ProxyAiProvider.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,eAAe;IAUZ;IACA;IACA;IAXH,EAAE,GAAG,aAAa,CAAC;IACpB,IAAI,CAAS;IAErB,IAAI,IAAI;QACJ,OAAO,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;IACnD,CAAC;IAED,YACI,WAAmB,EAAE,EACb,YAA8B,EAC9B,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,IAAI,KAAK,CAAC,KAAK,IAAI,yBAAyB,QAAQ,CAAC,MAAM,GAAG;iBACnG,CAAC;YACN,CAAC;YAED,OAAO,MAAM,QAAQ,CAAC,IAAI,EAAuB,CAAC;QACtD,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YAClB,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,CAAC,OAAO,IAAI,2CAA2C,EAAE,CAAC;QACjG,CAAC;IACL,CAAC;IAED,KAAK,CAAC,iBAAiB;QACnB,IAAI,CAAC,IAAI,CAAC,IAAI;YAAE,OAAO,KAAK,CAAC;QAC7B,IAAI,CAAC;YACD,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;YACzC,MAAM,EAAE,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,CAAC;YACtD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,IAAI,CAAC,IAAI,SAAS,EAAE,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC,CAAC;YACnF,YAAY,CAAC,EAAE,CAAC,CAAC;YACjB,OAAO,QAAQ,CAAC,EAAE,CAAC;QACvB,CAAC;QAAC,MAAM,CAAC;YACL,OAAO,KAAK,CAAC;QACjB,CAAC;IACL,CAAC;IAED,eAAe;QACX,OAAO,IAAI,CAAC;IAChB,CAAC;CACJ"}
@@ -1,10 +0,0 @@
1
- import { AiProvider, AgentChatRequest, AgentChatResponse } from './types.js';
2
- export declare class WindowAiProvider implements AiProvider {
3
- readonly id = "window-ai";
4
- readonly mode = "local-browser";
5
- chat(request: AgentChatRequest): Promise<AgentChatResponse>;
6
- checkAvailability(): Promise<boolean>;
7
- getSetupMessage(): string | null;
8
- private isSupported;
9
- }
10
- //# sourceMappingURL=WindowAiProvider.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"WindowAiProvider.d.ts","sourceRoot":"","sources":["../../src/providers/WindowAiProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE7E,qBAAa,gBAAiB,YAAW,UAAU;IAC/C,QAAQ,CAAC,EAAE,eAAe;IAC1B,QAAQ,CAAC,IAAI,mBAAmB;IAE1B,IAAI,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAgD3D,iBAAiB,IAAI,OAAO,CAAC,OAAO,CAAC;IAU3C,eAAe,IAAI,MAAM,GAAG,IAAI;IAKhC,OAAO,CAAC,WAAW;CAGtB"}
@@ -1,68 +0,0 @@
1
- export class WindowAiProvider {
2
- id = 'window-ai';
3
- mode = 'local-browser';
4
- async chat(request) {
5
- try {
6
- if (!this.isSupported()) {
7
- return { type: 'text', error: 'window.ai not supported' };
8
- }
9
- const capabilities = await globalThis.window?.ai.languageModel.capabilities();
10
- if (capabilities.available !== 'readily') {
11
- return { type: 'text', error: 'window.ai model not ready' };
12
- }
13
- const session = await globalThis.window?.ai.languageModel.create({
14
- systemPrompt: request.systemPrompt
15
- });
16
- const prompt = request.messages.map(m => `${m.role === 'user' ? 'User' : 'Assistant'}: ${m.content}`).join('\n') + '\nAssistant:';
17
- const response = await session.prompt(prompt);
18
- session.destroy();
19
- let cleanResponse = response.trim();
20
- if (cleanResponse.includes('```json')) {
21
- cleanResponse = cleanResponse.split('```json')[1].split('```')[0].trim();
22
- }
23
- else if (cleanResponse.includes('```')) {
24
- cleanResponse = cleanResponse.split('```')[1].split('```')[0].trim();
25
- }
26
- try {
27
- const parsed = JSON.parse(cleanResponse);
28
- if (parsed.tool && parsed.arguments) {
29
- return {
30
- type: 'tool_call',
31
- tool: parsed.tool,
32
- arguments: parsed.arguments
33
- };
34
- }
35
- if (parsed.type === 'tool_call') {
36
- return parsed;
37
- }
38
- return { type: 'text', content: response };
39
- }
40
- catch {
41
- return { type: 'text', content: response };
42
- }
43
- }
44
- catch (error) {
45
- return { type: 'text', error: error.message || 'Window AI error' };
46
- }
47
- }
48
- async checkAvailability() {
49
- if (!this.isSupported())
50
- return false;
51
- try {
52
- const capabilities = await globalThis.window?.ai.languageModel.capabilities();
53
- return capabilities.available === 'readily';
54
- }
55
- catch {
56
- return false;
57
- }
58
- }
59
- getSetupMessage() {
60
- if (this.isSupported())
61
- return null;
62
- return "To enable Local Browser AI: 1. Use Chrome Dev/Canary. 2. Enable 'Prompt API for Gemini Nano' in chrome://flags. 3. Enable 'Enables optimization guide on device' in chrome://flags. 4. Relaunch and wait for model download in chrome://components.";
63
- }
64
- isSupported() {
65
- return typeof globalThis !== 'undefined' && !!globalThis.window?.ai?.languageModel;
66
- }
67
- }
68
- //# sourceMappingURL=WindowAiProvider.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"WindowAiProvider.js","sourceRoot":"","sources":["../../src/providers/WindowAiProvider.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,gBAAgB;IAChB,EAAE,GAAG,WAAW,CAAC;IACjB,IAAI,GAAG,eAAe,CAAC;IAEhC,KAAK,CAAC,IAAI,CAAC,OAAyB;QAChC,IAAI,CAAC;YACD,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC;gBACtB,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,yBAAyB,EAAE,CAAC;YAC9D,CAAC;YAED,MAAM,YAAY,GAAG,MAAO,UAAkB,CAAC,MAAM,EAAE,EAAE,CAAC,aAAa,CAAC,YAAY,EAAE,CAAC;YACvF,IAAI,YAAY,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;gBACvC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,2BAA2B,EAAE,CAAC;YAChE,CAAC;YAED,MAAM,OAAO,GAAG,MAAO,UAAkB,CAAC,MAAM,EAAE,EAAE,CAAC,aAAa,CAAC,MAAM,CAAC;gBACtE,YAAY,EAAE,OAAO,CAAC,YAAY;aACr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MAA2B,CAAC;gBACvC,CAAC;gBACD,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;YAC/C,CAAC;YAAC,MAAM,CAAC;gBACL,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;YAC/C,CAAC;QACL,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YAClB,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,CAAC,OAAO,IAAI,iBAAiB,EAAE,CAAC;QACvE,CAAC;IACL,CAAC;IAED,KAAK,CAAC,iBAAiB;QACnB,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE;YAAE,OAAO,KAAK,CAAC;QACtC,IAAI,CAAC;YACD,MAAM,YAAY,GAAG,MAAO,UAAkB,CAAC,MAAM,EAAE,EAAE,CAAC,aAAa,CAAC,YAAY,EAAE,CAAC;YACvF,OAAO,YAAY,CAAC,SAAS,KAAK,SAAS,CAAC;QAChD,CAAC;QAAC,MAAM,CAAC;YACL,OAAO,KAAK,CAAC;QACjB,CAAC;IACL,CAAC;IAED,eAAe;QACX,IAAI,IAAI,CAAC,WAAW,EAAE;YAAE,OAAO,IAAI,CAAC;QACpC,OAAO,qPAAqP,CAAC;IACjQ,CAAC;IAEO,WAAW;QACf,OAAO,OAAO,UAAU,KAAK,WAAW,IAAI,CAAC,CAAE,UAAkB,CAAC,MAAM,EAAE,EAAE,EAAE,aAAa,CAAC;IAChG,CAAC;CACJ"}
@@ -1,38 +0,0 @@
1
- export interface AgentChatMessage {
2
- role: string;
3
- content: string;
4
- }
5
- export interface AgentChatTool {
6
- name: string;
7
- description: string;
8
- parameters: any;
9
- }
10
- export interface AgentChatRequest {
11
- messages: AgentChatMessage[];
12
- systemPrompt?: string;
13
- tools?: AgentChatTool[] | any[];
14
- }
15
- export interface AgentChatResponse {
16
- type: 'text' | 'tool_call';
17
- content?: string;
18
- tool?: string;
19
- arguments?: any;
20
- error?: string;
21
- }
22
- export interface AiProvider {
23
- readonly id: string;
24
- readonly mode: 'byok' | 'cloud' | 'local-browser' | 'local-ollama' | 'disabled';
25
- chat(request: AgentChatRequest): Promise<AgentChatResponse>;
26
- checkAvailability(): Promise<boolean>;
27
- getSetupMessage(): string | null;
28
- }
29
- export interface AiFactoryConfig {
30
- providerPreference: 'auto' | 'byok' | 'local' | 'local-browser' | 'cloud' | 'disabled';
31
- encryptedApiKey?: string;
32
- baseUrl?: string;
33
- proxyUrl?: string;
34
- ollamaModel?: string;
35
- byokProvider?: string;
36
- }
37
- export type AuthTokenGetter = () => string | null | undefined | Promise<string | null | undefined>;
38
- //# sourceMappingURL=types.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/providers/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,gBAAgB;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,aAAa;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,GAAG,CAAC;CACnB;AAED,MAAM,WAAW,gBAAgB;IAC7B,QAAQ,EAAE,gBAAgB,EAAE,CAAC;IAC7B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,EAAE,aAAa,EAAE,GAAG,GAAG,EAAE,CAAC;CACnC;AAED,MAAM,WAAW,iBAAiB;IAC9B,IAAI,EAAE,MAAM,GAAG,WAAW,CAAC;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,GAAG,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,UAAU;IACvB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,GAAG,eAAe,GAAG,cAAc,GAAG,UAAU,CAAC;IAChF,IAAI,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;IAC5D,iBAAiB,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IACtC,eAAe,IAAI,MAAM,GAAG,IAAI,CAAC;CACpC;AAED,MAAM,WAAW,eAAe;IAC5B,kBAAkB,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,eAAe,GAAG,OAAO,GAAG,UAAU,CAAC;IACvF,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,MAAM,eAAe,GAAG,MAAM,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/providers/types.ts"],"names":[],"mappings":""}