@qozara/ai-client 1.0.1 → 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 +119 -3
- package/dist/index.js +406 -12
- package/package.json +1 -1
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,7 +29,7 @@ interface AiProvider {
|
|
|
27
29
|
getSetupMessage(): string | null;
|
|
28
30
|
}
|
|
29
31
|
interface AiFactoryConfig {
|
|
30
|
-
providerPreference:
|
|
32
|
+
providerPreference: GenAiProviderPreference | LegacyAiProviderPreference;
|
|
31
33
|
encryptedApiKey?: string;
|
|
32
34
|
baseUrl?: string;
|
|
33
35
|
proxyUrl?: string;
|
|
@@ -78,7 +80,7 @@ declare class DisabledAiProvider implements AiProvider {
|
|
|
78
80
|
error: string;
|
|
79
81
|
}>;
|
|
80
82
|
checkAvailability(): Promise<boolean>;
|
|
81
|
-
getSetupMessage():
|
|
83
|
+
getSetupMessage(): string;
|
|
82
84
|
}
|
|
83
85
|
declare class AiProviderFactory {
|
|
84
86
|
static createProvider(config: AiFactoryConfig, getAuthToken?: AuthTokenGetter): Promise<AiProvider>;
|
|
@@ -105,4 +107,118 @@ declare class AgentClient {
|
|
|
105
107
|
chat(request: AgentClientChatOptions): Promise<AgentChatResponse>;
|
|
106
108
|
}
|
|
107
109
|
|
|
108
|
-
|
|
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,42 +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: "
|
|
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
|
|
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
299
|
const { providerPreference, encryptedApiKey, baseUrl, proxyUrl, byokProvider, enableLocalAi } = config;
|
|
260
|
-
|
|
300
|
+
const normalizedPreference = normalizeProviderPreference(providerPreference);
|
|
301
|
+
const isLocalAiOptedIn = Boolean(enableLocalAi);
|
|
302
|
+
if (normalizedPreference === "disabled") {
|
|
261
303
|
return new DisabledAiProvider();
|
|
262
304
|
}
|
|
263
|
-
if (
|
|
305
|
+
if (normalizedPreference === "byok" && encryptedApiKey && proxyUrl) {
|
|
264
306
|
return new ProxyAiProvider(proxyUrl, getAuthToken, encryptedApiKey, byokProvider);
|
|
265
307
|
}
|
|
266
|
-
if (
|
|
267
|
-
if (
|
|
308
|
+
if (normalizedPreference === "local") {
|
|
309
|
+
if (isLocalAiOptedIn) {
|
|
268
310
|
return new LocalOllamaProvider(baseUrl, config.ollamaModel);
|
|
269
311
|
}
|
|
270
312
|
return new DisabledAiProvider();
|
|
271
313
|
}
|
|
272
|
-
if (
|
|
314
|
+
if (normalizedPreference === "local-browser") {
|
|
273
315
|
return new WindowAiProvider();
|
|
274
316
|
}
|
|
275
|
-
if (
|
|
317
|
+
if (normalizedPreference === "cloud" && proxyUrl) {
|
|
276
318
|
return new ProxyAiProvider(proxyUrl, getAuthToken, encryptedApiKey, byokProvider);
|
|
277
319
|
}
|
|
278
|
-
if (
|
|
320
|
+
if (normalizedPreference === "auto") {
|
|
279
321
|
if (encryptedApiKey && proxyUrl) {
|
|
280
322
|
return new ProxyAiProvider(proxyUrl, getAuthToken, encryptedApiKey, byokProvider);
|
|
281
323
|
}
|
|
@@ -283,7 +325,7 @@ var AiProviderFactory = class {
|
|
|
283
325
|
if (await windowProvider.checkAvailability()) {
|
|
284
326
|
return windowProvider;
|
|
285
327
|
}
|
|
286
|
-
if (
|
|
328
|
+
if (isLocalAiOptedIn) {
|
|
287
329
|
const localProvider = new LocalOllamaProvider(baseUrl, config.ollamaModel);
|
|
288
330
|
if (await localProvider.checkAvailability()) {
|
|
289
331
|
return localProvider;
|
|
@@ -296,17 +338,22 @@ var AiProviderFactory = class {
|
|
|
296
338
|
return new DisabledAiProvider();
|
|
297
339
|
}
|
|
298
340
|
static getSetupMessage(providerId, config) {
|
|
299
|
-
switch (providerId) {
|
|
341
|
+
switch ((providerId || "").trim()) {
|
|
300
342
|
case "local":
|
|
301
343
|
case "local-ollama":
|
|
344
|
+
case "ollama":
|
|
302
345
|
return new LocalOllamaProvider(config?.baseUrl, config?.ollamaModel).getSetupMessage();
|
|
303
346
|
case "local-browser":
|
|
304
347
|
case "window-ai":
|
|
348
|
+
case "window.ai":
|
|
305
349
|
return new WindowAiProvider().getSetupMessage();
|
|
306
350
|
case "byok":
|
|
307
351
|
return "Enter your Gemini API key below. It will be encrypted and stored solely in your personal storage.";
|
|
308
352
|
case "cloud":
|
|
353
|
+
case "qozara-intelligence":
|
|
309
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.";
|
|
310
357
|
default:
|
|
311
358
|
return null;
|
|
312
359
|
}
|
|
@@ -376,11 +423,358 @@ var AgentClient = class {
|
|
|
376
423
|
return await response.json();
|
|
377
424
|
}
|
|
378
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
|
+
}
|
|
379
758
|
export {
|
|
380
759
|
AgentClient,
|
|
760
|
+
AiError as AiCommandError,
|
|
761
|
+
AiError,
|
|
762
|
+
AiKeyEncryptionService,
|
|
763
|
+
AiError as AiMealError,
|
|
381
764
|
AiProviderFactory,
|
|
765
|
+
CompositeAiResolver,
|
|
766
|
+
DEFAULT_USER_AI_SETTINGS,
|
|
382
767
|
DisabledAiProvider,
|
|
768
|
+
GenAiToolResolver,
|
|
383
769
|
LocalOllamaProvider,
|
|
770
|
+
LruMemoryCache,
|
|
384
771
|
ProxyAiProvider,
|
|
385
|
-
WindowAiProvider
|
|
772
|
+
WindowAiProvider,
|
|
773
|
+
classifyAiError,
|
|
774
|
+
createCompositeAiResolver,
|
|
775
|
+
createGenAiToolResolver,
|
|
776
|
+
extractToolCallData,
|
|
777
|
+
isGenAiEnabled,
|
|
778
|
+
normalizeProviderPreference,
|
|
779
|
+
validateAndPrepareAiSettings
|
|
386
780
|
};
|