@digilogiclabs/platform-core 1.14.0 → 1.16.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.
@@ -0,0 +1,781 @@
1
+ // src/interfaces/ILogger.ts
2
+ var NoopLogger = class {
3
+ debug() {
4
+ }
5
+ info() {
6
+ }
7
+ warn() {
8
+ }
9
+ error() {
10
+ }
11
+ child() {
12
+ return this;
13
+ }
14
+ };
15
+
16
+ // src/agent/agent-loop.ts
17
+ var DEFAULT_AGENT_LOOP_OPTIONS = {
18
+ maxIterations: 10,
19
+ maxTokens: Infinity,
20
+ maxCostUsd: Infinity,
21
+ cacheTtlSeconds: 300,
22
+ cacheKeyPrefix: "agent:tool:"
23
+ };
24
+ function mapFinishReason(reason) {
25
+ switch (reason) {
26
+ case "stop":
27
+ return "stop";
28
+ case "length":
29
+ return "length";
30
+ case "content_filter":
31
+ return "content_filter";
32
+ case "tool_calls":
33
+ return "stop";
34
+ // shouldn't reach here in normal flow
35
+ case "error":
36
+ default:
37
+ return "error";
38
+ }
39
+ }
40
+ async function executeToolCall(toolCall, executorMap, cache, cacheKeyPrefix, cacheTtlSeconds) {
41
+ const start = Date.now();
42
+ const executor = executorMap.get(toolCall.function.name);
43
+ if (!executor) {
44
+ return {
45
+ toolCall,
46
+ result: `Error: Unknown tool "${toolCall.function.name}"`,
47
+ success: false,
48
+ error: `Unknown tool: ${toolCall.function.name}`,
49
+ durationMs: Date.now() - start,
50
+ cached: false
51
+ };
52
+ }
53
+ if (cache) {
54
+ const cacheKey = cacheKeyPrefix + toolCall.function.name + ":" + toolCall.function.arguments;
55
+ try {
56
+ const cached = await cache.get(cacheKey);
57
+ if (cached !== null) {
58
+ return {
59
+ toolCall,
60
+ result: cached,
61
+ success: true,
62
+ durationMs: Date.now() - start,
63
+ cached: true
64
+ };
65
+ }
66
+ } catch {
67
+ }
68
+ }
69
+ try {
70
+ const parsed = JSON.parse(toolCall.function.arguments);
71
+ const result = await executor.execute(parsed, toolCall);
72
+ if (cache) {
73
+ const cacheKey = cacheKeyPrefix + toolCall.function.name + ":" + toolCall.function.arguments;
74
+ await cache.set(cacheKey, result, cacheTtlSeconds).catch(() => {
75
+ });
76
+ }
77
+ return {
78
+ toolCall,
79
+ result,
80
+ success: true,
81
+ durationMs: Date.now() - start,
82
+ cached: false
83
+ };
84
+ } catch (err) {
85
+ const errorMsg = err instanceof Error ? err.message : String(err);
86
+ return {
87
+ toolCall,
88
+ result: `Error: ${errorMsg}`,
89
+ success: false,
90
+ error: errorMsg,
91
+ durationMs: Date.now() - start,
92
+ cached: false
93
+ };
94
+ }
95
+ }
96
+ async function runAgentLoop(options) {
97
+ const opts = { ...DEFAULT_AGENT_LOOP_OPTIONS, ...options };
98
+ const logger = opts.logger ?? new NoopLogger();
99
+ const toolDefs = opts.tools.map((t) => t.definition);
100
+ const executorMap = /* @__PURE__ */ new Map();
101
+ for (const tool of opts.tools) {
102
+ executorMap.set(tool.definition.function.name, tool);
103
+ }
104
+ const messages = [...opts.messages];
105
+ const iterations = [];
106
+ const cumulative = {
107
+ promptTokens: 0,
108
+ completionTokens: 0,
109
+ totalTokens: 0,
110
+ estimatedCostUsd: 0,
111
+ iterations: 0,
112
+ toolCallCount: 0
113
+ };
114
+ let lastResponse;
115
+ let stopReason = "stop";
116
+ for (let i = 1; i <= opts.maxIterations; i++) {
117
+ if (opts.signal?.aborted) {
118
+ stopReason = "aborted";
119
+ break;
120
+ }
121
+ if (cumulative.totalTokens >= opts.maxTokens) {
122
+ stopReason = "max_tokens";
123
+ break;
124
+ }
125
+ if (cumulative.estimatedCostUsd >= opts.maxCostUsd) {
126
+ stopReason = "max_cost";
127
+ break;
128
+ }
129
+ logger.debug("Agent loop iteration", { iteration: i });
130
+ const chatRequest = {
131
+ ...opts.chatRequestOverrides,
132
+ messages,
133
+ tools: toolDefs.length > 0 ? toolDefs : void 0
134
+ };
135
+ const response = await opts.ai.chat(chatRequest);
136
+ lastResponse = response;
137
+ cumulative.promptTokens += response.usage.promptTokens;
138
+ cumulative.completionTokens += response.usage.completionTokens;
139
+ cumulative.totalTokens += response.usage.totalTokens;
140
+ cumulative.estimatedCostUsd += response.usage.estimatedCostUsd;
141
+ cumulative.iterations = i;
142
+ const assistantMessage = response.choices[0]?.message;
143
+ if (!assistantMessage) {
144
+ stopReason = "error";
145
+ break;
146
+ }
147
+ messages.push(assistantMessage);
148
+ if (response.finishReason !== "tool_calls") {
149
+ stopReason = mapFinishReason(response.finishReason);
150
+ const event2 = {
151
+ iteration: i,
152
+ response,
153
+ toolCalls: [],
154
+ cumulativeUsage: { ...cumulative },
155
+ messages: [...messages]
156
+ };
157
+ iterations.push(event2);
158
+ await opts.onIteration?.(event2);
159
+ break;
160
+ }
161
+ const toolCalls = assistantMessage.toolCalls ?? [];
162
+ cumulative.toolCallCount += toolCalls.length;
163
+ const toolResults = await Promise.all(
164
+ toolCalls.map(
165
+ (tc) => executeToolCall(
166
+ tc,
167
+ executorMap,
168
+ opts.cache,
169
+ opts.cacheKeyPrefix,
170
+ opts.cacheTtlSeconds
171
+ )
172
+ )
173
+ );
174
+ for (const tr of toolResults) {
175
+ messages.push({
176
+ role: "tool",
177
+ content: tr.result,
178
+ toolCallId: tr.toolCall.id
179
+ });
180
+ }
181
+ const event = {
182
+ iteration: i,
183
+ response,
184
+ toolCalls: toolResults,
185
+ cumulativeUsage: { ...cumulative },
186
+ messages: [...messages]
187
+ };
188
+ iterations.push(event);
189
+ const callbackResult = await opts.onIteration?.(event);
190
+ if (callbackResult === false) {
191
+ stopReason = "callback_abort";
192
+ break;
193
+ }
194
+ if (i === opts.maxIterations) {
195
+ stopReason = "max_iterations";
196
+ }
197
+ }
198
+ return {
199
+ response: lastResponse,
200
+ messages,
201
+ stopReason,
202
+ iterations,
203
+ usage: cumulative
204
+ };
205
+ }
206
+
207
+ // src/agent/agent-tracer.ts
208
+ function createAgentTracer(options) {
209
+ const { tracing, agentId } = options;
210
+ return {
211
+ async traceLoop(fn) {
212
+ return tracing.withSpanAsync(
213
+ "agent.loop",
214
+ async (span) => {
215
+ span.setAttribute("agent.id", agentId);
216
+ return fn(span);
217
+ },
218
+ { kind: "internal" }
219
+ );
220
+ },
221
+ async traceIteration(iteration, fn) {
222
+ return tracing.withSpanAsync(
223
+ "agent.iteration",
224
+ async (span) => {
225
+ span.setAttributes({
226
+ "agent.id": agentId,
227
+ "agent.iteration": iteration
228
+ });
229
+ return fn(span);
230
+ },
231
+ { kind: "internal" }
232
+ );
233
+ },
234
+ async traceToolCall(toolName, fn) {
235
+ return tracing.withSpanAsync(
236
+ `agent.tool.${toolName}`,
237
+ async (span) => {
238
+ span.setAttributes({
239
+ "agent.id": agentId,
240
+ "agent.tool.name": toolName
241
+ });
242
+ const result = await fn(span);
243
+ span.setAttributes({
244
+ "agent.tool.duration_ms": result.durationMs,
245
+ "agent.tool.success": result.success,
246
+ "agent.tool.cached": result.cached
247
+ });
248
+ if (result.error) {
249
+ span.setAttribute("agent.tool.error", result.error);
250
+ }
251
+ return result;
252
+ },
253
+ { kind: "internal" }
254
+ );
255
+ },
256
+ traceDecision(span, attrs) {
257
+ span.setAttributes({
258
+ "agent.decision.finish_reason": attrs.finishReason,
259
+ "agent.decision.tool_count": attrs.toolCallCount,
260
+ "agent.decision.total_tokens": attrs.cumulativeUsage.totalTokens,
261
+ "agent.decision.cost_usd": attrs.cumulativeUsage.estimatedCostUsd,
262
+ "agent.decision.iterations": attrs.cumulativeUsage.iterations
263
+ });
264
+ span.addEvent("agent.decision", {
265
+ finish_reason: attrs.finishReason,
266
+ tool_count: attrs.toolCallCount
267
+ });
268
+ }
269
+ };
270
+ }
271
+
272
+ // src/agent/agent-usage.ts
273
+ function createAgentUsageTracker(options) {
274
+ const { usage, agentId, tenantId, userId } = options;
275
+ return {
276
+ async recordIteration(params) {
277
+ return usage.record({
278
+ tenantId,
279
+ userId,
280
+ category: params.category ?? "chat",
281
+ provider: params.provider,
282
+ model: params.model,
283
+ inputTokens: params.usage.promptTokens,
284
+ outputTokens: params.usage.completionTokens,
285
+ totalTokens: params.usage.totalTokens,
286
+ costUsd: params.usage.estimatedCostUsd,
287
+ latencyMs: params.latencyMs ?? 0,
288
+ success: params.success ?? true,
289
+ error: params.error,
290
+ metadata: { agentId }
291
+ });
292
+ },
293
+ createBudgetCallback(budget) {
294
+ return async (event) => {
295
+ const response = event.response;
296
+ await usage.record({
297
+ tenantId,
298
+ userId,
299
+ category: "chat",
300
+ provider: response.provider,
301
+ model: response.model,
302
+ inputTokens: response.usage.promptTokens,
303
+ outputTokens: response.usage.completionTokens,
304
+ totalTokens: response.usage.totalTokens,
305
+ costUsd: response.usage.estimatedCostUsd,
306
+ latencyMs: 0,
307
+ success: true,
308
+ metadata: { agentId, iteration: event.iteration }
309
+ });
310
+ if (budget) {
311
+ if (budget.maxCostUsd !== void 0 && event.cumulativeUsage.estimatedCostUsd >= budget.maxCostUsd) {
312
+ return false;
313
+ }
314
+ if (budget.maxTokens !== void 0 && event.cumulativeUsage.totalTokens >= budget.maxTokens) {
315
+ return false;
316
+ }
317
+ }
318
+ };
319
+ }
320
+ };
321
+ }
322
+
323
+ // src/agent/traced-ai.ts
324
+ function createTracedAI(options) {
325
+ const { ai, tracing } = options;
326
+ return {
327
+ async chat(request) {
328
+ return tracing.withSpanAsync(
329
+ "ai.chat",
330
+ async (span) => {
331
+ const start = Date.now();
332
+ if (request.model) {
333
+ span.setAttribute("ai.model", request.model);
334
+ }
335
+ try {
336
+ const response = await ai.chat(request);
337
+ span.setAttributes({
338
+ "ai.provider": response.provider,
339
+ "ai.model": response.model,
340
+ "ai.input_tokens": response.usage.promptTokens,
341
+ "ai.output_tokens": response.usage.completionTokens,
342
+ "ai.total_tokens": response.usage.totalTokens,
343
+ "ai.cost_usd": response.usage.estimatedCostUsd,
344
+ "ai.finish_reason": response.finishReason,
345
+ "ai.latency_ms": Date.now() - start
346
+ });
347
+ span.setStatus({ code: "ok" });
348
+ return response;
349
+ } catch (err) {
350
+ span.setAttributes({
351
+ "ai.latency_ms": Date.now() - start
352
+ });
353
+ if (err instanceof Error) {
354
+ span.recordException(err);
355
+ }
356
+ span.setStatus({
357
+ code: "error",
358
+ message: err instanceof Error ? err.message : String(err)
359
+ });
360
+ throw err;
361
+ }
362
+ },
363
+ { kind: "client" }
364
+ );
365
+ },
366
+ async *chatStream(request) {
367
+ yield* ai.chatStream(request);
368
+ },
369
+ async chatWithCallback(request, callback) {
370
+ return tracing.withSpanAsync(
371
+ "ai.chatWithCallback",
372
+ async (span) => {
373
+ const start = Date.now();
374
+ if (request.model) {
375
+ span.setAttribute("ai.model", request.model);
376
+ }
377
+ try {
378
+ const response = await ai.chatWithCallback(request, callback);
379
+ span.setAttributes({
380
+ "ai.provider": response.provider,
381
+ "ai.model": response.model,
382
+ "ai.input_tokens": response.usage.promptTokens,
383
+ "ai.output_tokens": response.usage.completionTokens,
384
+ "ai.total_tokens": response.usage.totalTokens,
385
+ "ai.cost_usd": response.usage.estimatedCostUsd,
386
+ "ai.finish_reason": response.finishReason,
387
+ "ai.latency_ms": Date.now() - start
388
+ });
389
+ span.setStatus({ code: "ok" });
390
+ return response;
391
+ } catch (err) {
392
+ span.setAttributes({
393
+ "ai.latency_ms": Date.now() - start
394
+ });
395
+ if (err instanceof Error) {
396
+ span.recordException(err);
397
+ }
398
+ span.setStatus({
399
+ code: "error",
400
+ message: err instanceof Error ? err.message : String(err)
401
+ });
402
+ throw err;
403
+ }
404
+ },
405
+ { kind: "client" }
406
+ );
407
+ },
408
+ // Pass-through methods (no tracing needed for non-chat operations in v1)
409
+ async complete(request) {
410
+ return ai.complete(request);
411
+ },
412
+ async *completeStream(request) {
413
+ yield* ai.completeStream(request);
414
+ },
415
+ async embed(request) {
416
+ return ai.embed(request);
417
+ },
418
+ async similarity(text1, text2, model) {
419
+ return ai.similarity(text1, text2, model);
420
+ },
421
+ async listModels() {
422
+ return ai.listModels();
423
+ },
424
+ async getModel(modelId) {
425
+ return ai.getModel(modelId);
426
+ },
427
+ async supportsCapability(modelId, capability) {
428
+ return ai.supportsCapability(modelId, capability);
429
+ },
430
+ async estimateTokens(text, model) {
431
+ return ai.estimateTokens(text, model);
432
+ },
433
+ async estimateCost(request) {
434
+ return ai.estimateCost(request);
435
+ },
436
+ async healthCheck() {
437
+ return ai.healthCheck();
438
+ }
439
+ };
440
+ }
441
+
442
+ // src/interfaces/IAI.ts
443
+ var AIErrorMessages = {
444
+ invalid_request: "The request was invalid or malformed",
445
+ authentication_error: "Authentication failed - check your API key",
446
+ rate_limit_exceeded: "Rate limit exceeded - try again later",
447
+ quota_exceeded: "Usage quota exceeded for this billing period",
448
+ model_not_found: "The specified model was not found",
449
+ context_length_exceeded: "Input exceeds the model context length",
450
+ content_filter: "Content was filtered due to policy violations",
451
+ server_error: "The AI provider encountered an internal error",
452
+ timeout: "The request timed out",
453
+ network_error: "Network error connecting to AI provider",
454
+ provider_unavailable: "The AI provider is currently unavailable",
455
+ unknown: "An unknown error occurred"
456
+ };
457
+ function createAIError(code, message, options) {
458
+ const error = new Error(message || AIErrorMessages[code]);
459
+ error.name = "AIError";
460
+ error.code = code;
461
+ error.provider = options?.provider;
462
+ error.model = options?.model;
463
+ error.statusCode = options?.statusCode;
464
+ error.retryable = options?.retryable ?? [
465
+ "rate_limit_exceeded",
466
+ "server_error",
467
+ "timeout",
468
+ "network_error"
469
+ ].includes(code);
470
+ error.retryAfterMs = options?.retryAfterMs;
471
+ if (options?.cause) {
472
+ error.cause = options.cause;
473
+ }
474
+ return error;
475
+ }
476
+
477
+ // src/adapters/ollama/OllamaAdapter.ts
478
+ var OllamaAdapter = class {
479
+ baseUrl;
480
+ defaultModel;
481
+ defaultEmbeddingModel;
482
+ timeoutMs;
483
+ constructor(config) {
484
+ this.baseUrl = (config?.baseUrl ?? "http://localhost:11434").replace(
485
+ /\/$/,
486
+ ""
487
+ );
488
+ this.defaultModel = config?.defaultModel ?? "qwen2.5:3b";
489
+ this.defaultEmbeddingModel = config?.defaultEmbeddingModel ?? "nomic-embed-text";
490
+ this.timeoutMs = config?.timeoutMs ?? 12e4;
491
+ }
492
+ async chat(request) {
493
+ const model = request.model ?? this.defaultModel;
494
+ const ollamaReq = {
495
+ model,
496
+ messages: request.messages.map((m) => ({
497
+ role: m.role === "tool" ? "assistant" : m.role,
498
+ content: m.content
499
+ })),
500
+ stream: false,
501
+ options: {
502
+ temperature: request.temperature,
503
+ num_predict: request.maxTokens,
504
+ top_p: request.topP,
505
+ stop: request.stop ? Array.isArray(request.stop) ? request.stop : [request.stop] : void 0
506
+ }
507
+ };
508
+ const response = await this.fetch(
509
+ "/api/chat",
510
+ ollamaReq
511
+ );
512
+ const usage = {
513
+ promptTokens: response.prompt_eval_count ?? 0,
514
+ completionTokens: response.eval_count ?? 0,
515
+ totalTokens: (response.prompt_eval_count ?? 0) + (response.eval_count ?? 0),
516
+ estimatedCostUsd: 0
517
+ // Local — zero cost
518
+ };
519
+ return {
520
+ id: `ollama-${Date.now()}`,
521
+ model: response.model ?? model,
522
+ provider: "custom",
523
+ choices: [
524
+ {
525
+ index: 0,
526
+ message: {
527
+ role: "assistant",
528
+ content: response.message.content
529
+ },
530
+ finishReason: "stop"
531
+ }
532
+ ],
533
+ usage,
534
+ created: /* @__PURE__ */ new Date(),
535
+ finishReason: "stop"
536
+ };
537
+ }
538
+ async *chatStream(request) {
539
+ const model = request.model ?? this.defaultModel;
540
+ const ollamaReq = {
541
+ model,
542
+ messages: request.messages.map((m) => ({
543
+ role: m.role === "tool" ? "assistant" : m.role,
544
+ content: m.content
545
+ })),
546
+ stream: true,
547
+ options: {
548
+ temperature: request.temperature,
549
+ num_predict: request.maxTokens,
550
+ top_p: request.topP
551
+ }
552
+ };
553
+ const controller = new AbortController();
554
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
555
+ try {
556
+ const res = await fetch(`${this.baseUrl}/api/chat`, {
557
+ method: "POST",
558
+ headers: { "Content-Type": "application/json" },
559
+ body: JSON.stringify(ollamaReq),
560
+ signal: controller.signal
561
+ });
562
+ if (!res.ok) {
563
+ throw createAIError("server_error", `Ollama error: ${res.status}`);
564
+ }
565
+ const reader = res.body?.getReader();
566
+ if (!reader) return;
567
+ const decoder = new TextDecoder();
568
+ let buffer = "";
569
+ while (true) {
570
+ const { done, value } = await reader.read();
571
+ if (done) break;
572
+ buffer += decoder.decode(value, { stream: true });
573
+ const lines = buffer.split("\n");
574
+ buffer = lines.pop() ?? "";
575
+ for (const line of lines) {
576
+ if (!line.trim()) continue;
577
+ const chunk = JSON.parse(line);
578
+ yield {
579
+ id: `ollama-stream-${Date.now()}`,
580
+ model,
581
+ provider: "custom",
582
+ delta: {
583
+ content: chunk.message?.content ?? ""
584
+ },
585
+ finishReason: chunk.done ? "stop" : void 0
586
+ };
587
+ }
588
+ }
589
+ } finally {
590
+ clearTimeout(timer);
591
+ }
592
+ }
593
+ async chatWithCallback(request, callback) {
594
+ let fullContent = "";
595
+ for await (const chunk of this.chatStream(request)) {
596
+ await callback(chunk);
597
+ if (chunk.delta.content) {
598
+ fullContent += chunk.delta.content;
599
+ }
600
+ }
601
+ const model = request.model ?? this.defaultModel;
602
+ return {
603
+ id: `ollama-${Date.now()}`,
604
+ model,
605
+ provider: "custom",
606
+ choices: [
607
+ {
608
+ index: 0,
609
+ message: { role: "assistant", content: fullContent },
610
+ finishReason: "stop"
611
+ }
612
+ ],
613
+ usage: {
614
+ promptTokens: 0,
615
+ completionTokens: 0,
616
+ totalTokens: 0,
617
+ estimatedCostUsd: 0
618
+ },
619
+ created: /* @__PURE__ */ new Date(),
620
+ finishReason: "stop"
621
+ };
622
+ }
623
+ async complete(request) {
624
+ const response = await this.chat({
625
+ messages: [{ role: "user", content: request.prompt }],
626
+ model: request.model,
627
+ temperature: request.temperature,
628
+ maxTokens: request.maxTokens
629
+ });
630
+ return {
631
+ id: response.id,
632
+ model: response.model,
633
+ provider: "custom",
634
+ text: response.choices[0]?.message.content ?? "",
635
+ usage: response.usage,
636
+ created: response.created,
637
+ finishReason: response.finishReason
638
+ };
639
+ }
640
+ async *completeStream(request) {
641
+ yield* this.chatStream({
642
+ messages: [{ role: "user", content: request.prompt }],
643
+ model: request.model,
644
+ temperature: request.temperature,
645
+ maxTokens: request.maxTokens
646
+ });
647
+ }
648
+ async embed(request) {
649
+ const model = request.model ?? this.defaultEmbeddingModel;
650
+ const response = await this.fetch("/api/embed", {
651
+ model,
652
+ input: request.input
653
+ });
654
+ return {
655
+ id: `ollama-emb-${Date.now()}`,
656
+ model,
657
+ provider: "custom",
658
+ embeddings: response.embeddings,
659
+ usage: {
660
+ promptTokens: 0,
661
+ completionTokens: 0,
662
+ totalTokens: 0,
663
+ estimatedCostUsd: 0
664
+ },
665
+ created: /* @__PURE__ */ new Date()
666
+ };
667
+ }
668
+ async similarity(text1, text2, model) {
669
+ const response = await this.embed({ input: [text1, text2], model });
670
+ const [a, b] = response.embeddings;
671
+ if (!a || !b) return 0;
672
+ let dot = 0, normA = 0, normB = 0;
673
+ for (let i = 0; i < a.length; i++) {
674
+ dot += a[i] * b[i];
675
+ normA += a[i] * a[i];
676
+ normB += b[i] * b[i];
677
+ }
678
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
679
+ }
680
+ async listModels() {
681
+ try {
682
+ const response = await this.fetch(
683
+ "/api/tags",
684
+ null,
685
+ "GET"
686
+ );
687
+ return response.models.map((m) => ({
688
+ modelId: m.name,
689
+ provider: "custom",
690
+ capabilities: ["chat", "completion"],
691
+ maxContextTokens: 4096,
692
+ maxOutputTokens: 2048,
693
+ inputCostPer1K: 0,
694
+ outputCostPer1K: 0,
695
+ supportsStreaming: true,
696
+ supportsTools: false,
697
+ supportsVision: false
698
+ }));
699
+ } catch {
700
+ return [];
701
+ }
702
+ }
703
+ async getModel(modelId) {
704
+ const models = await this.listModels();
705
+ return models.find((m) => m.modelId === modelId) ?? null;
706
+ }
707
+ async supportsCapability(modelId, capability) {
708
+ const model = await this.getModel(modelId);
709
+ return model?.capabilities.includes(capability) ?? false;
710
+ }
711
+ async estimateTokens(text, _model) {
712
+ return Math.ceil(text.length / 4);
713
+ }
714
+ async estimateCost() {
715
+ return 0;
716
+ }
717
+ async healthCheck() {
718
+ try {
719
+ const start = Date.now();
720
+ await this.fetch("/api/tags", null, "GET");
721
+ const latency = Date.now() - start;
722
+ return {
723
+ healthy: true,
724
+ providers: {
725
+ custom: { available: true, latencyMs: latency },
726
+ openai: { available: false, error: "Not configured" },
727
+ anthropic: { available: false, error: "Not configured" },
728
+ google: { available: false, error: "Not configured" },
729
+ azure: { available: false, error: "Not configured" },
730
+ bedrock: { available: false, error: "Not configured" }
731
+ }
732
+ };
733
+ } catch (err) {
734
+ return {
735
+ healthy: false,
736
+ providers: {
737
+ custom: {
738
+ available: false,
739
+ error: err instanceof Error ? err.message : "Ollama unavailable"
740
+ },
741
+ openai: { available: false, error: "Not configured" },
742
+ anthropic: { available: false, error: "Not configured" },
743
+ google: { available: false, error: "Not configured" },
744
+ azure: { available: false, error: "Not configured" },
745
+ bedrock: { available: false, error: "Not configured" }
746
+ }
747
+ };
748
+ }
749
+ }
750
+ async fetch(path, body, method = "POST") {
751
+ const controller = new AbortController();
752
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
753
+ try {
754
+ const res = await fetch(`${this.baseUrl}${path}`, {
755
+ method,
756
+ headers: body ? { "Content-Type": "application/json" } : void 0,
757
+ body: body ? JSON.stringify(body) : void 0,
758
+ signal: controller.signal
759
+ });
760
+ if (!res.ok) {
761
+ const text = await res.text().catch(() => "");
762
+ throw createAIError(
763
+ "server_error",
764
+ `Ollama ${method} ${path}: ${res.status} ${text}`
765
+ );
766
+ }
767
+ return await res.json();
768
+ } finally {
769
+ clearTimeout(timer);
770
+ }
771
+ }
772
+ };
773
+ export {
774
+ DEFAULT_AGENT_LOOP_OPTIONS,
775
+ OllamaAdapter,
776
+ createAgentTracer,
777
+ createAgentUsageTracker,
778
+ createTracedAI,
779
+ runAgentLoop
780
+ };
781
+ //# sourceMappingURL=agents.mjs.map