@fenixforce/kernel 0.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.
Files changed (213) hide show
  1. package/dist/agent/execution-result.d.ts +27 -0
  2. package/dist/agent-loop.d.ts +55 -0
  3. package/dist/api/dashboard.d.ts +260 -0
  4. package/dist/api/index.d.ts +9 -0
  5. package/dist/api/middleware.d.ts +46 -0
  6. package/dist/api/openai-compat.d.ts +163 -0
  7. package/dist/api/server.d.ts +44 -0
  8. package/dist/api/streaming.d.ts +15 -0
  9. package/dist/api/webhook-triggers.d.ts +139 -0
  10. package/dist/billing/cost-meter.d.ts +123 -0
  11. package/dist/billing/index.d.ts +2 -0
  12. package/dist/boot.d.ts +109 -0
  13. package/dist/channels/discord.d.ts +99 -0
  14. package/dist/channels/email.d.ts +88 -0
  15. package/dist/channels/http-api.d.ts +155 -0
  16. package/dist/channels/index.d.ts +20 -0
  17. package/dist/channels/mcp-channel.d.ts +75 -0
  18. package/dist/channels/mobile-hil.d.ts +88 -0
  19. package/dist/channels/openai-compat.d.ts +42 -0
  20. package/dist/channels/registry.d.ts +80 -0
  21. package/dist/channels/signal.d.ts +75 -0
  22. package/dist/channels/slack.d.ts +115 -0
  23. package/dist/channels/teams.d.ts +106 -0
  24. package/dist/channels/telegram.d.ts +164 -0
  25. package/dist/channels/types.d.ts +71 -0
  26. package/dist/channels/whatsapp.d.ts +83 -0
  27. package/dist/checkpoint.d.ts +77 -0
  28. package/dist/config/canary.d.ts +74 -0
  29. package/dist/config/constitution.d.ts +57 -0
  30. package/dist/config/defaults.d.ts +17 -0
  31. package/dist/config/index.d.ts +8 -0
  32. package/dist/config/loader.d.ts +11 -0
  33. package/dist/config/provider-config.d.ts +29 -0
  34. package/dist/config/schema.d.ts +118 -0
  35. package/dist/config/steering-rules.d.ts +28 -0
  36. package/dist/content/chunker.d.ts +42 -0
  37. package/dist/content/entity-extractor.d.ts +58 -0
  38. package/dist/content/index.d.ts +8 -0
  39. package/dist/content/ocr.d.ts +79 -0
  40. package/dist/content/pipeline.d.ts +153 -0
  41. package/dist/context-overflow.d.ts +19 -0
  42. package/dist/editions/mobile.d.ts +12 -0
  43. package/dist/editions/pro.d.ts +12 -0
  44. package/dist/editions/voices.d.ts +14 -0
  45. package/dist/events/block-manager.d.ts +37 -0
  46. package/dist/events/bus.d.ts +39 -0
  47. package/dist/events/index.d.ts +8 -0
  48. package/dist/events/session-manager.d.ts +59 -0
  49. package/dist/events/stream-adapter.d.ts +24 -0
  50. package/dist/events/types.d.ts +465 -0
  51. package/dist/events/websocket.d.ts +34 -0
  52. package/dist/extensions/defaults/05-session-repair.d.ts +6 -0
  53. package/dist/extensions/defaults/10-logging.d.ts +6 -0
  54. package/dist/extensions/defaults/15-loop-guard.d.ts +6 -0
  55. package/dist/extensions/defaults/20-cost-tracking.d.ts +7 -0
  56. package/dist/extensions/defaults/25-ssrf-protection.d.ts +6 -0
  57. package/dist/extensions/defaults/30-rate-limiting.d.ts +6 -0
  58. package/dist/extensions/defaults/35-shell-bleed.d.ts +6 -0
  59. package/dist/extensions/defaults/40-observation-capture.d.ts +7 -0
  60. package/dist/extensions/defaults/45-context-survival.d.ts +6 -0
  61. package/dist/extensions/defaults/50-context-budget.d.ts +6 -0
  62. package/dist/extensions/defaults/55-steering-rules.d.ts +7 -0
  63. package/dist/extensions/defaults/60-quality-gates.d.ts +7 -0
  64. package/dist/extensions/defaults/65-job-dispatch.d.ts +24 -0
  65. package/dist/extensions/defaults/70-skill-loader.d.ts +18 -0
  66. package/dist/extensions/hooks.d.ts +74 -0
  67. package/dist/extensions/index.d.ts +21 -0
  68. package/dist/extensions/intervention.d.ts +59 -0
  69. package/dist/extensions/manager.d.ts +63 -0
  70. package/dist/extensions/runner.d.ts +63 -0
  71. package/dist/hooks/hook-manager.d.ts +39 -0
  72. package/dist/hooks/hook-types.d.ts +60 -0
  73. package/dist/identity/assembler.d.ts +45 -0
  74. package/dist/identity/ccc-adapter.d.ts +33 -0
  75. package/dist/identity/index.d.ts +6 -0
  76. package/dist/identity/persona-parser.d.ts +24 -0
  77. package/dist/identity/soul-parser.d.ts +23 -0
  78. package/dist/identity/user-populator.d.ts +20 -0
  79. package/dist/index.d.ts +227 -0
  80. package/dist/index.js +579 -0
  81. package/dist/interrupt.d.ts +84 -0
  82. package/dist/job-queue.d.ts +69 -0
  83. package/dist/jobs/index.d.ts +12 -0
  84. package/dist/jobs/memory-queue.d.ts +23 -0
  85. package/dist/jobs/planned-tasks.d.ts +121 -0
  86. package/dist/jobs/queue.d.ts +79 -0
  87. package/dist/jobs/router.d.ts +23 -0
  88. package/dist/jobs/synthesize-memories.d.ts +26 -0
  89. package/dist/jobs/types.d.ts +47 -0
  90. package/dist/jobs/worker-pool.d.ts +25 -0
  91. package/dist/jobs/worker.d.ts +40 -0
  92. package/dist/loop/autonomous-controller.d.ts +91 -0
  93. package/dist/loop/backpressure.d.ts +64 -0
  94. package/dist/loop/fresh-context.d.ts +48 -0
  95. package/dist/loop/prd-importer.d.ts +134 -0
  96. package/dist/loop/stop-controller.d.ts +31 -0
  97. package/dist/loop-guard.d.ts +32 -0
  98. package/dist/mcp/tool-executor.d.ts +57 -0
  99. package/dist/memory/brain-artifacts.d.ts +25 -0
  100. package/dist/memory/dual-search.d.ts +67 -0
  101. package/dist/memory/episodic.d.ts +45 -0
  102. package/dist/memory/index.d.ts +27 -0
  103. package/dist/memory/knowledge-graph.d.ts +89 -0
  104. package/dist/memory/markdown-store.d.ts +64 -0
  105. package/dist/memory/metadata-filter.d.ts +29 -0
  106. package/dist/memory/mid-conversation-saves.d.ts +17 -0
  107. package/dist/memory/note-parser.d.ts +34 -0
  108. package/dist/memory/observation-store.d.ts +36 -0
  109. package/dist/memory/observation-thresholds.d.ts +26 -0
  110. package/dist/memory/progressive-search.d.ts +25 -0
  111. package/dist/memory/synthesis.d.ts +36 -0
  112. package/dist/memory/tree-index.d.ts +104 -0
  113. package/dist/memory/write-gate.d.ts +63 -0
  114. package/dist/mission-control.d.ts +34 -0
  115. package/dist/pre-classifier-widgets.d.ts +40 -0
  116. package/dist/pre-classifier.d.ts +19 -0
  117. package/dist/prompt/context-budget.d.ts +68 -0
  118. package/dist/prompt/index.d.ts +3 -0
  119. package/dist/prompt/system-prompt.d.ts +32 -0
  120. package/dist/prompt/templates.d.ts +11 -0
  121. package/dist/providers/anthropic.d.ts +24 -0
  122. package/dist/providers/auto-detect.d.ts +16 -0
  123. package/dist/providers/auto-discover.d.ts +28 -0
  124. package/dist/providers/bedrock.d.ts +38 -0
  125. package/dist/providers/cache-strategy.d.ts +58 -0
  126. package/dist/providers/circuit-breaker.d.ts +33 -0
  127. package/dist/providers/cost-meter.d.ts +74 -0
  128. package/dist/providers/cost-tracking.d.ts +36 -0
  129. package/dist/providers/google.d.ts +35 -0
  130. package/dist/providers/index.d.ts +32 -0
  131. package/dist/providers/interface.d.ts +98 -0
  132. package/dist/providers/json-repair.d.ts +10 -0
  133. package/dist/providers/key-rotation.d.ts +36 -0
  134. package/dist/providers/manager.d.ts +64 -0
  135. package/dist/providers/model-registry.d.ts +50 -0
  136. package/dist/providers/openai-compatible.d.ts +26 -0
  137. package/dist/providers/optimization-modes.d.ts +38 -0
  138. package/dist/providers/provider-manager.d.ts +71 -0
  139. package/dist/providers/runtime-crud.d.ts +68 -0
  140. package/dist/providers/sidecar-lifecycle.d.ts +40 -0
  141. package/dist/providers/stream-wrapper.d.ts +21 -0
  142. package/dist/providers/structured-verify.d.ts +31 -0
  143. package/dist/providers/versioning.d.ts +18 -0
  144. package/dist/quality-gates.d.ts +10 -0
  145. package/dist/scheduler/engine.d.ts +95 -0
  146. package/dist/scheduler/index.d.ts +4 -0
  147. package/dist/scheduler/webhook-handler.d.ts +37 -0
  148. package/dist/sdk/agent.d.ts +22 -0
  149. package/dist/sdk/cli.d.ts +2 -0
  150. package/dist/sdk/client.d.ts +19 -0
  151. package/dist/sdk/index.d.ts +24 -0
  152. package/dist/sdk/jobs.d.ts +25 -0
  153. package/dist/sdk/memory.d.ts +18 -0
  154. package/dist/sdk/types.d.ts +69 -0
  155. package/dist/security/approval-gates.d.ts +166 -0
  156. package/dist/security/content-wrapper.d.ts +38 -0
  157. package/dist/security/guard-rails.d.ts +6 -0
  158. package/dist/security/index.d.ts +21 -0
  159. package/dist/security/instruction-hierarchy.d.ts +109 -0
  160. package/dist/security/pii-tokenizer.d.ts +30 -0
  161. package/dist/security/reputation.d.ts +53 -0
  162. package/dist/security/secret-store.d.ts +41 -0
  163. package/dist/security/security-engine.d.ts +53 -0
  164. package/dist/security/shell-bleed.d.ts +15 -0
  165. package/dist/security/ssrf.d.ts +12 -0
  166. package/dist/security/taint-tracker.d.ts +63 -0
  167. package/dist/security/tool-access-control.d.ts +114 -0
  168. package/dist/session-compaction.d.ts +20 -0
  169. package/dist/session-orient.d.ts +22 -0
  170. package/dist/session-repair.d.ts +6 -0
  171. package/dist/storage/index.d.ts +24 -0
  172. package/dist/storage/interface.d.ts +245 -0
  173. package/dist/storage/postgres.d.ts +6 -0
  174. package/dist/storage/sqlite.d.ts +2 -0
  175. package/dist/streaming/reasoning.d.ts +67 -0
  176. package/dist/task-tracker.d.ts +26 -0
  177. package/dist/testing/action-cache.d.ts +39 -0
  178. package/dist/testing/incident-eval.d.ts +49 -0
  179. package/dist/testing/workflow-evals.d.ts +73 -0
  180. package/dist/tools/access-control.d.ts +60 -0
  181. package/dist/tools/browser-engine.d.ts +73 -0
  182. package/dist/tools/builtins/jobs-router.d.ts +7 -0
  183. package/dist/tools/builtins/tasks-router.d.ts +25 -0
  184. package/dist/tools/index.d.ts +20 -0
  185. package/dist/tools/map-reduce.d.ts +64 -0
  186. package/dist/tools/registry.d.ts +39 -0
  187. package/dist/tools/router.d.ts +30 -0
  188. package/dist/tools/routers/browser-router.d.ts +12 -0
  189. package/dist/tools/routers/code-router.d.ts +34 -0
  190. package/dist/tools/routers/file-router.d.ts +35 -0
  191. package/dist/tools/routers/memory-router.d.ts +21 -0
  192. package/dist/tools/routers/schedule-router.d.ts +31 -0
  193. package/dist/tools/routers/search-backends.d.ts +47 -0
  194. package/dist/tools/routers/task-router.d.ts +32 -0
  195. package/dist/tools/routers/web-router.d.ts +36 -0
  196. package/dist/tools/skill-discovery.d.ts +32 -0
  197. package/dist/tools/skill-loader.d.ts +76 -0
  198. package/dist/tools/skill-types.d.ts +21 -0
  199. package/dist/voice/audio-intelligence.d.ts +42 -0
  200. package/dist/voice/barge-in.d.ts +51 -0
  201. package/dist/voice/index.d.ts +22 -0
  202. package/dist/voice/marker-parser.d.ts +31 -0
  203. package/dist/voice/sidecar-manager.d.ts +68 -0
  204. package/dist/voice/speaker-focus.d.ts +41 -0
  205. package/dist/voice/speaker-voiceprint.d.ts +47 -0
  206. package/dist/voice/speech-intent.d.ts +51 -0
  207. package/dist/voice/speechmatics-stt.d.ts +77 -0
  208. package/dist/voice/speechmatics-tts.d.ts +39 -0
  209. package/dist/voice/stt-provider.d.ts +40 -0
  210. package/dist/voice/transcript.d.ts +19 -0
  211. package/dist/voice/turn-detection.d.ts +53 -0
  212. package/dist/wrapup.d.ts +15 -0
  213. package/package.json +39 -0
@@ -0,0 +1,24 @@
1
+ import type { LLMProvider, CompletionParams, CompletionResult, ProviderCapabilities } from "./interface.js";
2
+ import type { ChatCompletionChunk } from "./stream-wrapper.js";
3
+ export interface AnthropicConfig {
4
+ id?: string;
5
+ apiKey: string;
6
+ model: string;
7
+ baseUrl?: string;
8
+ maxTokens?: number;
9
+ }
10
+ export declare class AnthropicProvider implements LLMProvider {
11
+ readonly id: string;
12
+ private readonly apiKey;
13
+ private readonly model;
14
+ private readonly baseUrl;
15
+ private readonly maxTokens;
16
+ constructor(config: AnthropicConfig);
17
+ capabilities(): ProviderCapabilities;
18
+ complete(params: CompletionParams): Promise<CompletionResult>;
19
+ stream(params: CompletionParams): AsyncIterable<ChatCompletionChunk>;
20
+ private headers;
21
+ private buildRequestBody;
22
+ private convertContent;
23
+ private mapStopReason;
24
+ }
@@ -0,0 +1,16 @@
1
+ import type { ProviderSlot } from "./interface.js";
2
+ export interface DetectedProvider {
3
+ id: string;
4
+ slot: ProviderSlot;
5
+ apiKeyEnv?: string;
6
+ baseUrl?: string;
7
+ }
8
+ export interface AutoDetectResult {
9
+ chat: DetectedProvider | null;
10
+ tts: DetectedProvider | null;
11
+ stt: DetectedProvider | null;
12
+ reusedKeys: string[];
13
+ }
14
+ export declare function autoDetectProviders(): Promise<AutoDetectResult>;
15
+ /** List all supported provider IDs for documentation/diagnostics. */
16
+ export declare function listSupportedProviders(): string[];
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Model Auto-Discovery — at startup, probe configured providers for
3
+ * available models and populate the ModelRegistry.
4
+ *
5
+ * - Ollama: GET /api/tags
6
+ * - OpenRouter: known model list (no probe needed)
7
+ * - Custom/OpenAI-compatible endpoints: GET /v1/models
8
+ *
9
+ * ~60 lines of logic.
10
+ */
11
+ import type { ModelRegistry } from "./model-registry.js";
12
+ export interface DiscoveryTarget {
13
+ /** Provider identifier. */
14
+ provider: string;
15
+ /** Base URL of the provider API. */
16
+ baseUrl: string;
17
+ /** API key for authenticated endpoints. */
18
+ apiKey?: string;
19
+ /** Provider type hint for choosing the right probe strategy. */
20
+ type?: "ollama" | "openrouter" | "openai-compatible";
21
+ }
22
+ export interface DiscoveryResult {
23
+ provider: string;
24
+ models: string[];
25
+ registered: number;
26
+ error?: string;
27
+ }
28
+ export declare function discoverModels(targets: DiscoveryTarget[], registry: ModelRegistry): Promise<DiscoveryResult[]>;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Bedrock Provider — AWS Bedrock Converse API adapter.
3
+ *
4
+ * Features:
5
+ * - SigV4 request signing (AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY)
6
+ * - Region-based endpoints (https://bedrock-runtime.{region}.amazonaws.com)
7
+ * - Model IDs prefixed with provider (anthropic.claude-*, meta.llama-*)
8
+ * - Streaming via event stream encoding
9
+ * - Multi-region support with region variants in model registry
10
+ */
11
+ import type { LLMProvider, CompletionParams, CompletionResult, ProviderCapabilities } from "./interface.js";
12
+ import type { ChatCompletionChunk } from "./stream-wrapper.js";
13
+ export interface BedrockConfig {
14
+ id?: string;
15
+ model: string;
16
+ region?: string;
17
+ accessKeyId?: string;
18
+ secretAccessKey?: string;
19
+ sessionToken?: string;
20
+ maxTokens?: number;
21
+ }
22
+ export declare class BedrockProvider implements LLMProvider {
23
+ readonly id: string;
24
+ private readonly model;
25
+ private readonly region;
26
+ private readonly accessKeyId;
27
+ private readonly secretAccessKey;
28
+ private readonly sessionToken?;
29
+ private readonly maxTokens;
30
+ constructor(config: BedrockConfig);
31
+ capabilities(): ProviderCapabilities;
32
+ complete(params: CompletionParams): Promise<CompletionResult>;
33
+ stream(params: CompletionParams): AsyncIterable<ChatCompletionChunk>;
34
+ private buildRequest;
35
+ private convertContent;
36
+ private parseResponse;
37
+ private mapStopReason;
38
+ }
@@ -0,0 +1,58 @@
1
+ export interface CacheableMessage {
2
+ role: string;
3
+ content: string;
4
+ name?: string;
5
+ /** Provider-specific cache control annotation */
6
+ cacheControl?: {
7
+ type: "ephemeral";
8
+ };
9
+ }
10
+ export interface ToolDefinitionEntry {
11
+ name: string;
12
+ description: string;
13
+ parameters: Record<string, unknown>;
14
+ }
15
+ export interface CacheStrategyConfig {
16
+ /** System identity + steering rules — computed once at session start */
17
+ systemMessage: string;
18
+ /** Tool definitions — sorted by name for deterministic ordering */
19
+ toolDefinitions: ToolDefinitionEntry[];
20
+ /** Workspace steering rules — loaded at session start */
21
+ developerInstructions: string;
22
+ }
23
+ export interface OrderedRequest {
24
+ messages: CacheableMessage[];
25
+ /** Index of the last static message (cache breakpoint) */
26
+ cacheBreakpointIndex: number;
27
+ /** SHA-256 hash of the static prefix */
28
+ prefixHash: string;
29
+ }
30
+ export interface CacheMetrics {
31
+ sessionId: string;
32
+ totalCalls: number;
33
+ cacheHits: number;
34
+ estimatedTokensSaved: number;
35
+ hitRate: number;
36
+ }
37
+ export type CacheEventEmitter = (event: string, payload: Record<string, unknown>) => void;
38
+ export declare class CacheStrategy {
39
+ private config;
40
+ private prefixHash;
41
+ private metrics;
42
+ private emitEvent;
43
+ constructor(config: CacheStrategyConfig, emitEvent?: CacheEventEmitter);
44
+ /**
45
+ * Build an ordered request with cache-optimized message ordering.
46
+ * Pipeline: system → tool defs → dev instructions → history → current message.
47
+ */
48
+ buildOrderedRequest(sessionId: string, history: CacheableMessage[], currentMessage: CacheableMessage): OrderedRequest;
49
+ /**
50
+ * Record cache hit/miss from provider response metadata.
51
+ */
52
+ recordCacheResult(sessionId: string, cachedTokens: number, totalInputTokens: number): void;
53
+ /** Get cache metrics for a session. */
54
+ getMetrics(sessionId: string): CacheMetrics | null;
55
+ /** Update static config (triggers cache-bust on next call). */
56
+ updateConfig(partial: Partial<CacheStrategyConfig>): void;
57
+ private computePrefixHash;
58
+ }
@@ -0,0 +1,33 @@
1
+ export type CircuitState = "closed" | "open" | "half-open";
2
+ export interface CircuitBreakerConfig {
3
+ /** Failures before opening the circuit (default: 5) */
4
+ failureThreshold?: number;
5
+ /** Base reset timeout in ms (default: 60_000 = 60s) */
6
+ resetTimeoutMs?: number;
7
+ /** Max reset timeout after backoff in ms (default: 3_600_000 = 1hr) */
8
+ maxResetTimeoutMs?: number;
9
+ /** Base timeout for billing/quota errors in ms (default: 18_000_000 = 5hr) */
10
+ billingResetTimeoutMs?: number;
11
+ /** Max timeout for billing/quota errors in ms (default: 86_400_000 = 24hr) */
12
+ billingMaxResetTimeoutMs?: number;
13
+ }
14
+ export declare function isBillingError(error: unknown): boolean;
15
+ export declare class ProviderCircuitBreaker {
16
+ private state;
17
+ private failureCount;
18
+ private consecutiveResets;
19
+ private lastFailureTime;
20
+ private isBillingFailure;
21
+ private readonly config;
22
+ private keyBreakers;
23
+ constructor(config?: CircuitBreakerConfig);
24
+ getState(): CircuitState;
25
+ canAttempt(): boolean;
26
+ recordSuccess(): void;
27
+ recordFailure(error?: unknown): void;
28
+ /** Get or create a per-key sub-breaker (G14 multi-key support) */
29
+ getKeyBreaker(key: string): ProviderCircuitBreaker;
30
+ /** Find a healthy key from the list, or null if all are tripped */
31
+ getHealthyKey(keys: string[]): string | null;
32
+ private currentTimeout;
33
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * CostMeter — budget enforcement layer that checks spending limits
3
+ * before LLM calls, persists cost logs, and computes usage summaries.
4
+ *
5
+ * Yields quota:warning at 80% and quota:exceeded at budget limit.
6
+ */
7
+ import type { StorageAdapter } from "../storage/interface.js";
8
+ import type { BudgetsConfig } from "../config/schema.js";
9
+ import type { AgentEvent } from "../events/types.js";
10
+ export interface ModelPricing {
11
+ inputCostPer1k: number;
12
+ outputCostPer1k: number;
13
+ }
14
+ export type BudgetPeriod = "hourly" | "daily" | "monthly";
15
+ /** Input to track() — what happened during an LLM call */
16
+ export interface CostEntry {
17
+ provider: string;
18
+ model: string;
19
+ inputTokens: number;
20
+ outputTokens: number;
21
+ }
22
+ export interface UsageSummary {
23
+ period: BudgetPeriod;
24
+ costUsd: number;
25
+ totalTokens: number;
26
+ entries: number;
27
+ }
28
+ export interface BudgetStatus {
29
+ allowed: boolean;
30
+ reason?: string;
31
+ usage: {
32
+ hourly: UsageSummary;
33
+ daily: UsageSummary;
34
+ monthly: UsageSummary;
35
+ };
36
+ }
37
+ export declare function calculateCost(model: string, inputTokens: number, outputTokens: number, pricingTable?: Record<string, ModelPricing>): number;
38
+ export interface CostMeterOptions {
39
+ userId: string;
40
+ storage: StorageAdapter;
41
+ budgets: BudgetsConfig;
42
+ pricingTable?: Record<string, ModelPricing>;
43
+ }
44
+ export declare class CostMeter {
45
+ private userId;
46
+ private storage;
47
+ private budgets;
48
+ private pricingTable;
49
+ constructor(options: CostMeterOptions);
50
+ /**
51
+ * Record token usage after an LLM call. Persists to cost_logs table.
52
+ */
53
+ track(entry: CostEntry): Promise<void>;
54
+ /**
55
+ * Track usage and yield quota events if thresholds are crossed.
56
+ * Call this as an async generator to receive quota:warning / quota:exceeded.
57
+ */
58
+ trackWithEvents(entry: CostEntry, sessionId?: string): AsyncGenerator<AgentEvent, void>;
59
+ /**
60
+ * Check whether the user is within budget across all configured periods.
61
+ */
62
+ checkBudget(userId?: string): Promise<BudgetStatus>;
63
+ /**
64
+ * Get usage summary for a specific period.
65
+ */
66
+ getUsage(userId?: string, period?: BudgetPeriod, now?: Date): Promise<UsageSummary>;
67
+ /**
68
+ * Compute the usage percentage for the tightest configured budget.
69
+ * Returns null if no budgets are configured.
70
+ */
71
+ usagePercent(userId?: string): Promise<number | null>;
72
+ /** Get the tightest (smallest) configured budget limit in USD. */
73
+ private tightestLimit;
74
+ }
@@ -0,0 +1,36 @@
1
+ import type { LLMProvider, CompletionParams, CompletionResult, EmbeddingResult, ProviderCapabilities, GenerateObjectParams, StreamObjectChunk } from "./interface.js";
2
+ import type { ChatCompletionChunk } from "./stream-wrapper.js";
3
+ export interface CostRecord {
4
+ provider: string;
5
+ model: string;
6
+ inputTokens: number;
7
+ outputTokens: number;
8
+ estimatedCost: number;
9
+ timestamp: number;
10
+ }
11
+ export interface CostSummary {
12
+ totalInputTokens: number;
13
+ totalOutputTokens: number;
14
+ totalEstimatedCost: number;
15
+ recordCount: number;
16
+ }
17
+ export declare class CostTrackingProvider implements LLMProvider {
18
+ private readonly inner;
19
+ private readonly inputCostPerM;
20
+ private readonly outputCostPerM;
21
+ readonly id: string;
22
+ private readonly records;
23
+ private model;
24
+ stream?: (params: CompletionParams) => AsyncIterable<ChatCompletionChunk>;
25
+ generateObject?: <T = unknown>(params: GenerateObjectParams) => Promise<T>;
26
+ streamObject?: <T = unknown>(params: GenerateObjectParams) => AsyncIterable<StreamObjectChunk<T>>;
27
+ constructor(inner: LLMProvider, inputCostPerM?: number, outputCostPerM?: number);
28
+ capabilities(): ProviderCapabilities;
29
+ complete(params: CompletionParams): Promise<CompletionResult>;
30
+ embed(input: string | string[]): Promise<EmbeddingResult>;
31
+ getRecords(): readonly CostRecord[];
32
+ getSummary(): CostSummary;
33
+ private record;
34
+ private wrapStream;
35
+ private wrapObjectStream;
36
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Google Provider — Google Generative AI (Gemini) API adapter.
3
+ *
4
+ * Supports the generateContent endpoint with:
5
+ * - contents array with "model"/"user" roles (not "assistant")
6
+ * - Inline tool declarations (Google format, not OpenAI)
7
+ * - Streaming via SSE
8
+ * - Vertex AI support via baseUrl override + service account auth
9
+ * - GOOGLE_API_KEY env var
10
+ */
11
+ import type { LLMProvider, CompletionParams, CompletionResult, ProviderCapabilities } from "./interface.js";
12
+ import type { ChatCompletionChunk } from "./stream-wrapper.js";
13
+ export interface GoogleProviderConfig {
14
+ id?: string;
15
+ apiKey: string;
16
+ model: string;
17
+ /** Override for Vertex AI: e.g. https://{region}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/publishers/google */
18
+ baseUrl?: string;
19
+ maxOutputTokens?: number;
20
+ }
21
+ export declare class GoogleProvider implements LLMProvider {
22
+ readonly id: string;
23
+ private readonly apiKey;
24
+ private readonly model;
25
+ private readonly baseUrl;
26
+ private readonly maxOutputTokens;
27
+ constructor(config: GoogleProviderConfig);
28
+ capabilities(): ProviderCapabilities;
29
+ complete(params: CompletionParams): Promise<CompletionResult>;
30
+ stream(params: CompletionParams): AsyncIterable<ChatCompletionChunk>;
31
+ private buildRequest;
32
+ private convertContent;
33
+ private parseResponse;
34
+ private mapFinishReason;
35
+ }
@@ -0,0 +1,32 @@
1
+ export * from "./interface.js";
2
+ export * from "./circuit-breaker.js";
3
+ export * from "./cost-tracking.js";
4
+ export * from "./manager.js";
5
+ export * from "./cost-meter.js";
6
+ export { AnthropicProvider } from "./anthropic.js";
7
+ export { GoogleProvider } from "./google.js";
8
+ export { BedrockProvider } from "./bedrock.js";
9
+ export { ModelRegistry, loadDefaultRegistry, createRegistry } from "./model-registry.js";
10
+ export { discoverModels } from "./auto-discover.js";
11
+ export type { DiscoveryTarget, DiscoveryResult } from "./auto-discover.js";
12
+ export { rankModels, pickBestModel, resolveMode, createOptimizationConfig } from "./optimization-modes.js";
13
+ export type { OptimizationMode, OptimizationConfig, RankedModel } from "./optimization-modes.js";
14
+ export { checkCompatibility } from "./versioning.js";
15
+ export type { VersionCompat, VersionCheckResult } from "./versioning.js";
16
+ export { OpenAICompatibleProvider } from "./openai-compatible.js";
17
+ export type { OpenAICompatibleConfig } from "./openai-compatible.js";
18
+ export { repairJson, parsePartialJson } from "./json-repair.js";
19
+ export { verifiedGenerateObject, StructuredOutputError } from "./structured-verify.js";
20
+ export type { VerifyOptions, VerifyResult } from "./structured-verify.js";
21
+ export { SidecarLifecycle } from "./sidecar-lifecycle.js";
22
+ export type { SidecarConfig as SidecarLifecycleConfig, SidecarState as SidecarLifecycleState, StartFn as SidecarStartFn, HealthCheckFn as SidecarHealthCheckFn, } from "./sidecar-lifecycle.js";
23
+ export { createOpenAICompatibleStream } from "./stream-wrapper.js";
24
+ export type { ChatCompletionChunk, TokenUsage } from "./stream-wrapper.js";
25
+ export { createKeyRotator } from "./key-rotation.js";
26
+ export type { KeyRotationConfig, KeyRotator } from "./key-rotation.js";
27
+ export { createRuntimeProviderCRUD, _resetProviderIds } from "./runtime-crud.js";
28
+ export type { ProviderEntry, CreateProviderInput, UpdateProviderInput, TestResult, ProviderFactory, RuntimeProviderCRUDConfig, RuntimeProviderCRUD, } from "./runtime-crud.js";
29
+ export { autoDetectProviders, listSupportedProviders } from "./auto-detect.js";
30
+ export type { DetectedProvider, AutoDetectResult } from "./auto-detect.js";
31
+ export { CacheStrategy } from "./cache-strategy.js";
32
+ export type { CacheableMessage, ToolDefinitionEntry, CacheStrategyConfig, OrderedRequest, CacheMetrics, CacheEventEmitter, } from "./cache-strategy.js";
@@ -0,0 +1,98 @@
1
+ import type { ChatCompletionChunk } from "./stream-wrapper.js";
2
+ export type ProviderSlot = "chat" | "utility" | "embedding" | "vision" | "stt" | "tts";
3
+ export interface ProviderCapabilities {
4
+ nativeToolCalling: boolean;
5
+ vision: boolean;
6
+ streaming: boolean;
7
+ structuredOutput: boolean;
8
+ maxContextTokens: number;
9
+ }
10
+ export interface ToolCall {
11
+ id: string;
12
+ type: "function";
13
+ function: {
14
+ name: string;
15
+ arguments: string;
16
+ };
17
+ }
18
+ export interface ContentPart {
19
+ type: "text" | "image_url";
20
+ text?: string;
21
+ image_url?: {
22
+ url: string;
23
+ detail?: "low" | "high" | "auto";
24
+ };
25
+ }
26
+ export interface Message {
27
+ role: "system" | "user" | "assistant" | "tool";
28
+ content: string | ContentPart[] | null;
29
+ tool_call_id?: string;
30
+ tool_calls?: ToolCall[];
31
+ }
32
+ export interface ToolDefinition {
33
+ type: "function";
34
+ function: {
35
+ name: string;
36
+ description?: string;
37
+ parameters?: Record<string, unknown>;
38
+ };
39
+ }
40
+ export interface CompletionParams {
41
+ model?: string;
42
+ messages: Message[];
43
+ temperature?: number;
44
+ maxTokens?: number;
45
+ tools?: ToolDefinition[];
46
+ stop?: string | string[];
47
+ }
48
+ export interface CompletionResult {
49
+ content: string;
50
+ toolCalls?: ToolCall[];
51
+ finishReason: "stop" | "tool_calls" | "length" | "content_filter" | null;
52
+ usage?: {
53
+ inputTokens: number;
54
+ outputTokens: number;
55
+ };
56
+ }
57
+ export interface EmbeddingResult {
58
+ embeddings: number[][];
59
+ usage?: {
60
+ totalTokens: number;
61
+ };
62
+ }
63
+ export interface JsonSchema {
64
+ type: string;
65
+ properties?: Record<string, JsonSchema>;
66
+ items?: JsonSchema;
67
+ required?: string[];
68
+ description?: string;
69
+ enum?: unknown[];
70
+ additionalProperties?: boolean;
71
+ [key: string]: unknown;
72
+ }
73
+ export interface GenerateObjectParams {
74
+ model?: string;
75
+ messages: Message[];
76
+ schema: JsonSchema;
77
+ schemaName?: string;
78
+ schemaDescription?: string;
79
+ temperature?: number;
80
+ maxTokens?: number;
81
+ }
82
+ export interface StreamObjectChunk<T = unknown> {
83
+ partial: Partial<T>;
84
+ done: boolean;
85
+ usage?: {
86
+ inputTokens: number;
87
+ outputTokens: number;
88
+ };
89
+ }
90
+ export interface LLMProvider {
91
+ readonly id: string;
92
+ complete(params: CompletionParams): Promise<CompletionResult>;
93
+ stream?(params: CompletionParams): AsyncIterable<ChatCompletionChunk>;
94
+ embed?(input: string | string[]): Promise<EmbeddingResult>;
95
+ generateObject?<T = unknown>(params: GenerateObjectParams): Promise<T>;
96
+ streamObject?<T = unknown>(params: GenerateObjectParams): AsyncIterable<StreamObjectChunk<T>>;
97
+ capabilities(): ProviderCapabilities;
98
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Attempt to parse JSON, repairing common LLM output issues.
3
+ * Returns the parsed value, or throws if repair is impossible.
4
+ */
5
+ export declare function repairJson<T = unknown>(input: string): T;
6
+ /**
7
+ * Parse partial/streaming JSON, returning the best partial result.
8
+ * Unlike repairJson, this never throws — it returns undefined on failure.
9
+ */
10
+ export declare function parsePartialJson<T = unknown>(input: string): Partial<T> | undefined;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Key Rotation — round-robin between multiple API keys for a provider.
3
+ * Ties into ProviderCircuitBreaker per-key mode (G14): each key gets
4
+ * its own sub-breaker. When a key hits rate limits, the breaker opens
5
+ * and rotation skips to the next healthy key.
6
+ *
7
+ * ~50 lines of logic.
8
+ */
9
+ import { ProviderCircuitBreaker } from "./circuit-breaker.js";
10
+ export interface KeyRotationConfig {
11
+ /** Provider name (for identification). */
12
+ provider: string;
13
+ /** API keys to rotate between. */
14
+ keys: string[];
15
+ /** Circuit breaker config passed to per-key sub-breakers. */
16
+ breakerConfig?: ConstructorParameters<typeof ProviderCircuitBreaker>[0];
17
+ }
18
+ export interface KeyRotator {
19
+ /** Get the next healthy key via round-robin. Returns null if all tripped. */
20
+ next(): string | null;
21
+ /** Record success for the last-selected key's breaker. */
22
+ recordSuccess(): void;
23
+ /** Record failure for the last-selected key's breaker (opens after threshold). */
24
+ recordFailure(error?: unknown): void;
25
+ /** Snapshot of each key's circuit state. */
26
+ health(): Array<{
27
+ key: string;
28
+ state: string;
29
+ canAttempt: boolean;
30
+ }>;
31
+ /** Number of keys that can currently be used. */
32
+ healthyCount(): number;
33
+ /** The underlying per-key circuit breaker. */
34
+ readonly breaker: ProviderCircuitBreaker;
35
+ }
36
+ export declare function createKeyRotator(config: KeyRotationConfig): KeyRotator;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * ProviderManager — holds providers by slot, wraps with circuit breakers
3
+ * and cost tracking, and provides capability-based dispatch.
4
+ */
5
+ import type { LLMProvider, ProviderCapabilities, ProviderSlot } from "./interface.js";
6
+ import { ProviderCircuitBreaker } from "./circuit-breaker.js";
7
+ import { type AutoDetectResult } from "./auto-detect.js";
8
+ export interface ManagedProvider {
9
+ provider: LLMProvider;
10
+ breaker: ProviderCircuitBreaker;
11
+ slot: ProviderSlot;
12
+ }
13
+ export interface ProviderManagerOptions {
14
+ /** Wrap providers with CostTrackingProvider. */
15
+ enableCostTracking?: boolean;
16
+ sessionId?: string;
17
+ }
18
+ export declare class ProviderManager {
19
+ private slots;
20
+ private enableCostTracking;
21
+ constructor(options?: ProviderManagerOptions);
22
+ /**
23
+ * Register a provider for a slot. Wraps in CostTrackingProvider if
24
+ * cost tracking is enabled, and creates a circuit breaker.
25
+ */
26
+ register(slot: ProviderSlot, provider: LLMProvider): void;
27
+ /**
28
+ * Get a healthy (closed or half-open) provider for a given slot.
29
+ * Returns null if no healthy provider is available.
30
+ */
31
+ getHealthy(slot: ProviderSlot): LLMProvider | null;
32
+ /**
33
+ * Get the circuit breaker for a slot, for recording success/failure.
34
+ */
35
+ getBreaker(slot: ProviderSlot): ProviderCircuitBreaker | null;
36
+ /**
37
+ * Capability-based dispatch: returns a healthy provider that satisfies
38
+ * the requested capability. Falls back across slots in order:
39
+ * - For vision: try vision slot, then chat slot
40
+ * - For other capabilities: try the requested slot, then chat, then utility
41
+ */
42
+ getByCapability(capability: keyof ProviderCapabilities, preferredSlot?: ProviderSlot): LLMProvider | null;
43
+ /**
44
+ * List all registered slots.
45
+ */
46
+ listSlots(): ProviderSlot[];
47
+ /**
48
+ * Get the managed entry (provider + breaker) for a slot.
49
+ */
50
+ get(slot: ProviderSlot): ManagedProvider | undefined;
51
+ /**
52
+ * Check whether any provider slots are configured.
53
+ */
54
+ hasSlots(): boolean;
55
+ /**
56
+ * Auto-detect and populate provider slots from environment when
57
+ * no explicit configuration exists. Uses the G15 cascade:
58
+ * LLM → TTS → STT, with multi-modal key reuse.
59
+ *
60
+ * Callers must create LLMProvider instances from the detection
61
+ * result and register them via register().
62
+ */
63
+ static autoDetect(): Promise<AutoDetectResult>;
64
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Model Registry — central catalog of known LLM models with capabilities,
3
+ * pricing, and alias resolution. Loaded at startup from data/models.json,
4
+ * extensible at runtime via register().
5
+ */
6
+ export interface ModelCapabilities {
7
+ nativeToolCalling: boolean;
8
+ vision: boolean;
9
+ streaming: boolean;
10
+ reasoning: boolean;
11
+ maxContextTokens: number;
12
+ maxOutputTokens: number;
13
+ }
14
+ export interface ModelPricing {
15
+ inputPer1MTokens: number;
16
+ outputPer1MTokens: number;
17
+ cachedInputPer1MTokens: number;
18
+ }
19
+ export interface ModelEntry {
20
+ id: string;
21
+ provider: string;
22
+ model: string;
23
+ displayName: string;
24
+ capabilities: ModelCapabilities;
25
+ pricing: ModelPricing;
26
+ aliases: string[];
27
+ }
28
+ export declare class ModelRegistry {
29
+ private readonly models;
30
+ private readonly aliasIndex;
31
+ constructor(entries?: ModelEntry[]);
32
+ /** Register a model entry, indexing by ID and all aliases. */
33
+ register(entry: ModelEntry): void;
34
+ /** Look up a model by full ID or any alias. Returns undefined if not found. */
35
+ lookup(idOrAlias: string): ModelEntry | undefined;
36
+ /** List all models for a given provider name. */
37
+ listByProvider(provider: string): ModelEntry[];
38
+ /** Filter models by a capability key (e.g. "vision", "reasoning"). */
39
+ listByCapability(cap: keyof ModelCapabilities): ModelEntry[];
40
+ /** Estimate cost in USD for a given model and token counts. */
41
+ estimateCost(modelIdOrAlias: string, inputTokens: number, outputTokens: number, cachedInputTokens?: number): number;
42
+ /** Return all registered entries. */
43
+ listAll(): ModelEntry[];
44
+ /** Number of registered models. */
45
+ get size(): number;
46
+ }
47
+ /** Load the default registry from data/models.json. */
48
+ export declare function loadDefaultRegistry(): ModelRegistry;
49
+ /** Create a fresh registry (useful for testing). */
50
+ export declare function createRegistry(entries?: ModelEntry[]): ModelRegistry;
@@ -0,0 +1,26 @@
1
+ import type { LLMProvider, CompletionParams, CompletionResult, EmbeddingResult, ProviderCapabilities, GenerateObjectParams, StreamObjectChunk } from "./interface.js";
2
+ import type { ChatCompletionChunk } from "./stream-wrapper.js";
3
+ export interface OpenAICompatibleConfig {
4
+ id?: string;
5
+ baseUrl: string;
6
+ apiKey: string;
7
+ model: string;
8
+ capabilities?: Partial<ProviderCapabilities>;
9
+ }
10
+ export declare class OpenAICompatibleProvider implements LLMProvider {
11
+ readonly id: string;
12
+ private readonly baseUrl;
13
+ private readonly apiKey;
14
+ private readonly model;
15
+ private readonly caps;
16
+ constructor(config: OpenAICompatibleConfig);
17
+ capabilities(): ProviderCapabilities;
18
+ complete(params: CompletionParams): Promise<CompletionResult>;
19
+ stream(params: CompletionParams): AsyncIterable<ChatCompletionChunk>;
20
+ embed(input: string | string[]): Promise<EmbeddingResult>;
21
+ generateObject<T = unknown>(params: GenerateObjectParams): Promise<T>;
22
+ streamObject<T = unknown>(params: GenerateObjectParams): AsyncIterable<StreamObjectChunk<T>>;
23
+ private headers;
24
+ private buildRequestBody;
25
+ private mapFinishReason;
26
+ }