@ultrst-armada/kloks 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.
Files changed (33) hide show
  1. package/.krusbl-release-attestation.json +3 -3
  2. package/package.json +1 -1
  3. package/packages/backend/dist/ai-inference/index.d.ts +1 -1
  4. package/packages/backend/dist/ai-keys/index.d.ts +17 -47
  5. package/packages/backend/dist/ai-keys/index.js +1 -1
  6. package/packages/backend/dist/ai-models/index.d.ts +15 -34
  7. package/packages/backend/dist/ai-models/index.js +6 -8
  8. package/packages/backend/dist/ai-provider/index.d.ts +2 -2
  9. package/packages/backend/dist/ai-routing/index.d.ts +15 -1
  10. package/packages/backend/dist/ai-routing/index.js +3 -2
  11. package/packages/backend/dist/ai-tools/index.d.ts +2 -0
  12. package/packages/backend/dist/ai-tools/index.js +1 -1
  13. package/packages/backend/dist/{chunk-MSCOKLAO.js → chunk-AQT3GIXB.js} +30 -1
  14. package/packages/backend/dist/{chunk-XGPL43T3.js → chunk-EWQYKBSN.js} +13 -6
  15. package/packages/backend/dist/{chunk-MFM2QIY5.js → chunk-F4J4YPUR.js} +122 -2
  16. package/packages/backend/dist/{chunk-4GWYTYDQ.js → chunk-HXFTSHCP.js} +87 -24
  17. package/packages/backend/dist/{chunk-NSKVYL74.js → chunk-U4HUGPRH.js} +20 -0
  18. package/packages/backend/dist/chunk-UU6M3L3O.js +0 -0
  19. package/packages/backend/dist/index.d.ts +5 -3
  20. package/packages/backend/dist/index.js +48 -51
  21. package/packages/backend/dist/krnl-ai-services.d.ts +18 -0
  22. package/packages/backend/dist/krnl-ai-services.js +5 -6
  23. package/packages/backend/dist/krnl-services.js +3 -3
  24. package/packages/backend/dist/services/index.js +1 -1
  25. package/packages/backend/dist/types-B0aSwTAt.d.ts +47 -0
  26. package/packages/backend/dist/{types-2p2AhboE.d.ts → types-Di4ZAQYA.d.ts} +1 -1
  27. package/packages/backend/dist/types-fYUdf9oB.d.ts +36 -0
  28. package/packages/backend/dist/workspace/index.js +2 -2
  29. package/packages/state-graph/dist/index.js +9 -9
  30. package/packages/backend/dist/chunk-2WT7OUHW.js +0 -51
  31. package/packages/backend/dist/chunk-Z3LXEA6P.js +0 -45
  32. package/packages/backend/dist/{chunk-EIYYESEU.js → chunk-BTMIK44G.js} +3 -3
  33. package/packages/backend/dist/{chunk-D6ZGQFWQ.js → chunk-T26VJ22Y.js} +4 -4
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "schema": 1,
3
3
  "packageName": "@ultrst-armada/kloks",
4
- "version": "1.14.0",
5
- "sourceCommit": "f78e0968c6172b3d594f9af45c17e5478df2290b",
4
+ "version": "1.16.0",
5
+ "sourceCommit": "eb260f0bb24e9dc18bfca085e3389e2477a4258f",
6
6
  "releaseWorkflow": "npm Release",
7
- "workflowRunId": "40835042415"
7
+ "workflowRunId": "40836920132"
8
8
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultrst-armada/kloks",
3
- "version": "1.14.0",
3
+ "version": "1.16.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -1,4 +1,4 @@
1
- import { a as ProviderId } from '../types-2p2AhboE.js';
1
+ import { P as ProviderId } from '../types-Di4ZAQYA.js';
2
2
  import { b as AITransportClient } from '../AITransportClient-dToGr8nj.js';
3
3
 
4
4
  /**
@@ -1,48 +1,5 @@
1
- import { a as ProviderId } from '../types-2p2AhboE.js';
2
-
3
- /**
4
- * @file types.ts
5
- * @description Canonical AI Key Management contracts and types for @ultrst-armada/kloks/backend
6
- */
7
-
8
- type RotationStrategy = 'lowest-latency' | 'round-robin' | 'weighted-random' | 'failover-priority';
9
- interface ApiKeyEntry {
10
- id: string;
11
- providerId: ProviderId;
12
- label: string;
13
- key: string;
14
- keyValue?: string;
15
- status: 'active' | 'valid' | 'invalid' | 'rate-limited' | 'checking';
16
- isActive: boolean;
17
- createdAt: string;
18
- weight: number;
19
- remainingCreditsUsd: number | null;
20
- totalCalls: number;
21
- successfulCalls: number;
22
- failedCalls: number;
23
- lastLatencyMs: number;
24
- errorCount: number;
25
- lifespanSeconds?: number | null;
26
- expiresAt?: string | null;
27
- lastUsedAt?: string | null;
28
- validationError?: string | null;
29
- failedModels?: string[];
30
- }
31
- interface KeyValidationResult {
32
- valid: boolean;
33
- status: 'valid' | 'invalid' | 'rate-limited';
34
- error?: string;
35
- latencyMs: number;
36
- }
37
- interface KeyModelUsageStats {
38
- keyId: string;
39
- modelId: string;
40
- totalCalls: number;
41
- successfulCalls: number;
42
- failedCalls: number;
43
- lastUsedAt?: string;
44
- avgLatencyMs?: number;
45
- }
1
+ import { a as KeyValidationResult, A as ApiKeyEntry, R as RotationStrategy, K as KeyModelUsageStats } from '../types-B0aSwTAt.js';
2
+ import { P as ProviderId } from '../types-Di4ZAQYA.js';
46
3
 
47
4
  /**
48
5
  * @file keyValidator.ts
@@ -74,13 +31,26 @@ declare const keysStorage: KeysStorage;
74
31
  declare class KeyStoreService {
75
32
  private strategy;
76
33
  private roundRobinIndices;
34
+ private forcedNextKeys;
35
+ private permanentKeys;
77
36
  getKeys(providerId?: ProviderId): ApiKeyEntry[];
78
37
  getKey(id: string): ApiKeyEntry | undefined;
79
38
  getActiveKey(providerId: ProviderId): ApiKeyEntry | undefined;
80
39
  setStrategy(strategy: RotationStrategy): void;
81
40
  getStrategy(): RotationStrategy;
82
- addKey(entry: Omit<ApiKeyEntry, 'id' | 'createdAt' | 'totalCalls' | 'successfulCalls' | 'failedCalls' | 'lastLatencyMs' | 'errorCount'>): ApiKeyEntry;
41
+ addKey(entry: Partial<ApiKeyEntry> & Pick<ApiKeyEntry, 'providerId' | 'label' | 'key'>): ApiKeyEntry;
42
+ getPermanentKey(providerId: ProviderId): string | null;
43
+ getPermanentKeysMap(): Record<string, string>;
44
+ setPermanentKey(providerId: ProviderId, keyId: string | null): void;
45
+ setForcedNextKey(providerId: ProviderId, keyId: string): void;
46
+ peekNextKey(providerId: ProviderId, _modelId?: string): ApiKeyEntry | null;
47
+ getNextKey(providerId: ProviderId, modelId?: string): ApiKeyEntry | null;
83
48
  selectNextKey(providerId: ProviderId, _modelId?: string): ApiKeyEntry | undefined;
49
+ updateKeyLabel(id: string, label: string): ApiKeyEntry | undefined;
50
+ deleteKey(id: string): boolean;
51
+ resetKeyProbabilities(id: string): ApiKeyEntry | undefined;
52
+ resetAllFailures(): void;
53
+ getUsageStats(_keyId?: string, _modelId?: string): KeyModelUsageStats[];
84
54
  updateKeyStatus(id: string, status: ApiKeyEntry['status']): void;
85
55
  recordUsage(keyId: string, successOrLatency: boolean | number, latencyOrSuccess: boolean | number, _costUsd?: number, _modelId?: string, error?: string): void;
86
56
  exportKeysStructured(): {
@@ -96,4 +66,4 @@ declare class KeyStoreService {
96
66
  }
97
67
  declare const keyStore: KeyStoreService;
98
68
 
99
- export { type ApiKeyEntry, type KeyModelUsageStats, KeyStoreService, type KeyValidationResult, KeysStorage, type RotationStrategy, keyStore, keysStorage, validateApiKey };
69
+ export { ApiKeyEntry, KeyModelUsageStats, KeyStoreService, KeyValidationResult, KeysStorage, RotationStrategy, keyStore, keysStorage, validateApiKey };
@@ -5,7 +5,7 @@ import {
5
5
  keyStore,
6
6
  keysStorage,
7
7
  validateApiKey
8
- } from "../chunk-4GWYTYDQ.js";
8
+ } from "../chunk-HXFTSHCP.js";
9
9
  import "../chunk-JSQZAFBU.js";
10
10
  export {
11
11
  KeyStoreService,
@@ -1,38 +1,7 @@
1
- import { a as ProviderId } from '../types-2p2AhboE.js';
1
+ import { M as ModelCatalogEntry, a as ModelHealthStatus } from '../types-fYUdf9oB.js';
2
+ import { P as ProviderId } from '../types-Di4ZAQYA.js';
2
3
  import { b as AITransportClient } from '../AITransportClient-dToGr8nj.js';
3
4
 
4
- /**
5
- * @file types.ts
6
- * @description Canonical Model Catalog and Discovery types for @ultrst-armada/kloks/backend
7
- */
8
-
9
- interface ModelCatalogEntry {
10
- id: string;
11
- name: string;
12
- providerId: ProviderId;
13
- contextWindow?: number;
14
- inputCostPer1k?: number;
15
- outputCostPer1k?: number;
16
- supportsTools?: boolean;
17
- supportsVision?: boolean;
18
- supportsJson?: boolean;
19
- isFree?: boolean;
20
- latencyRatingMs?: number;
21
- qualityRating?: number;
22
- maxOutputTokens?: number;
23
- status?: 'active' | 'deprecated' | 'offline';
24
- description?: string;
25
- }
26
- interface ModelHealthStatus {
27
- modelId: string;
28
- providerId: ProviderId;
29
- isHealthy: boolean;
30
- latencyMs: number;
31
- consecutiveFailures: number;
32
- lastCheckedAt: string;
33
- lastError?: string;
34
- }
35
-
36
5
  /**
37
6
  * @file catalogData.ts
38
7
  * @description Builtin static AI Model Catalog data across major providers
@@ -73,7 +42,19 @@ declare const modelHealthService: ModelHealthService;
73
42
  */
74
43
 
75
44
  declare class ModelCatalogService {
45
+ private providerStatuses;
76
46
  private customModels;
47
+ getCatalog(providerId?: ProviderId): ModelCatalogEntry[];
48
+ getProviderStatuses(): Array<{
49
+ providerId: ProviderId;
50
+ status: string;
51
+ modelsCount: number;
52
+ error?: string;
53
+ }>;
54
+ refreshCatalogFromEndpoints(): Promise<{
55
+ updated: number;
56
+ errors: string[];
57
+ }>;
77
58
  getAllModels(): ModelCatalogEntry[];
78
59
  getModelsByProvider(providerId: ProviderId): ModelCatalogEntry[];
79
60
  getModelById(id: string): ModelCatalogEntry | undefined;
@@ -88,4 +69,4 @@ declare class ModelCatalogService {
88
69
  }
89
70
  declare const modelCatalog: ModelCatalogService;
90
71
 
91
- export { EndpointRefresher, type ModelCatalogEntry, ModelCatalogService, ModelHealthService, type ModelHealthStatus, STATIC_MODELS_CATALOG, endpointRefresher, modelCatalog, modelHealthService };
72
+ export { EndpointRefresher, ModelCatalogEntry, ModelCatalogService, ModelHealthService, ModelHealthStatus, STATIC_MODELS_CATALOG, endpointRefresher, modelCatalog, modelHealthService };
@@ -1,16 +1,14 @@
1
+ import "../chunk-UU6M3L3O.js";
1
2
  import {
2
3
  EndpointRefresher,
3
- endpointRefresher
4
- } from "../chunk-2WT7OUHW.js";
5
- import {
6
4
  ModelCatalogService,
7
- STATIC_MODELS_CATALOG,
8
- modelCatalog
9
- } from "../chunk-MFM2QIY5.js";
10
- import {
11
5
  ModelHealthService,
6
+ STATIC_MODELS_CATALOG,
7
+ endpointRefresher,
8
+ modelCatalog,
12
9
  modelHealthService
13
- } from "../chunk-Z3LXEA6P.js";
10
+ } from "../chunk-F4J4YPUR.js";
11
+ import "../chunk-HXFTSHCP.js";
14
12
  import "../chunk-MAMK4GDH.js";
15
13
  import "../chunk-JSQZAFBU.js";
16
14
  export {
@@ -1,5 +1,5 @@
1
- import { b as ProviderMeta, a as ProviderId, A as AIProviderStatus } from '../types-2p2AhboE.js';
2
- export { P as ProviderCapabilities } from '../types-2p2AhboE.js';
1
+ import { b as ProviderMeta, P as ProviderId, A as AIProviderStatus } from '../types-Di4ZAQYA.js';
2
+ export { a as ProviderCapabilities } from '../types-Di4ZAQYA.js';
3
3
  import { b as AITransportClient } from '../AITransportClient-dToGr8nj.js';
4
4
  export { A as AIHttpRequest, a as AIHttpResponse } from '../AITransportClient-dToGr8nj.js';
5
5
 
@@ -1,4 +1,4 @@
1
- import { a as ProviderId } from '../types-2p2AhboE.js';
1
+ import { P as ProviderId } from '../types-Di4ZAQYA.js';
2
2
 
3
3
  /**
4
4
  * @file types.ts
@@ -69,6 +69,13 @@ declare class MetricsLogger {
69
69
  toolCalls?: unknown;
70
70
  toolsProvided?: unknown;
71
71
  }): void;
72
+ getLogs(limit?: number): AIMetricRecord[];
73
+ getMetricsSummary(): {
74
+ totalRequests: number;
75
+ successRatePercent: number;
76
+ averageLatencyMs: number;
77
+ totalFailovers: number;
78
+ };
72
79
  log(record: Omit<AIMetricRecord, 'id' | 'timestamp'>): void;
73
80
  getRecent(limit?: number): AIMetricRecord[];
74
81
  getAverageLatency(providerId: ProviderId, modelId?: string): number;
@@ -82,6 +89,13 @@ declare const metricsLogger: MetricsLogger;
82
89
  */
83
90
 
84
91
  declare class HealthCheckService {
92
+ runRoutineCheck(): Promise<{
93
+ timestamp: string;
94
+ keysTotal: number;
95
+ keysValid: number;
96
+ modelsCatalogTotal: number;
97
+ status: 'healthy';
98
+ }>;
85
99
  checkProvider(providerId: ProviderId, apiKey?: string): Promise<boolean>;
86
100
  isRouteAvailable(providerId: ProviderId, modelId: string): boolean;
87
101
  recordRouteFailure(providerId: ProviderId, modelId: string, error: string): void;
@@ -6,8 +6,9 @@ import {
6
6
  failoverExecutionEngine,
7
7
  healthCheckService,
8
8
  metricsLogger
9
- } from "../chunk-MSCOKLAO.js";
10
- import "../chunk-Z3LXEA6P.js";
9
+ } from "../chunk-AQT3GIXB.js";
10
+ import "../chunk-F4J4YPUR.js";
11
+ import "../chunk-HXFTSHCP.js";
11
12
  import "../chunk-SLR6SIEU.js";
12
13
  import "../chunk-MAMK4GDH.js";
13
14
  import "../chunk-JSQZAFBU.js";
@@ -45,6 +45,8 @@ declare class MCPEngine {
45
45
  private servers;
46
46
  private registeredTools;
47
47
  private toolHandlers;
48
+ getSystemTools(): MCPTool[];
49
+ handleJsonRpc(payload: any): Promise<any>;
48
50
  registerServer(config: MCPServerConfig): void;
49
51
  getServer(id: string): MCPServerConfig | undefined;
50
52
  listServers(): MCPServerConfig[];
@@ -6,7 +6,7 @@ import {
6
6
  ToolManagerService,
7
7
  mcpEngine,
8
8
  toolManagerService
9
- } from "../chunk-NSKVYL74.js";
9
+ } from "../chunk-U4HUGPRH.js";
10
10
  export {
11
11
  MCPEngine,
12
12
  ToolManagerService,
@@ -1,6 +1,10 @@
1
1
  import {
2
+ modelCatalog,
2
3
  modelHealthService
3
- } from "./chunk-Z3LXEA6P.js";
4
+ } from "./chunk-F4J4YPUR.js";
5
+ import {
6
+ keyStore
7
+ } from "./chunk-HXFTSHCP.js";
4
8
  import {
5
9
  aiProviderService
6
10
  } from "./chunk-SLR6SIEU.js";
@@ -17,6 +21,20 @@ var MetricsLogger = class {
17
21
  success: record.status !== "failure"
18
22
  });
19
23
  }
24
+ getLogs(limit = 50) {
25
+ return this.records.slice(-limit);
26
+ }
27
+ getMetricsSummary() {
28
+ const totalRequests = this.records.length;
29
+ const successes = this.records.filter((record) => record.success).length;
30
+ const averageLatencyMs = totalRequests ? Math.round(this.records.reduce((sum, record) => sum + record.durationMs, 0) / totalRequests) : 0;
31
+ return {
32
+ totalRequests,
33
+ successRatePercent: totalRequests ? Math.round(successes / totalRequests * 100) : 100,
34
+ averageLatencyMs,
35
+ totalFailovers: 0
36
+ };
37
+ }
20
38
  log(record) {
21
39
  const full = {
22
40
  id: `met_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
@@ -50,6 +68,17 @@ var metricsLogger = new MetricsLogger();
50
68
 
51
69
  // src/ai-routing/healthCheckService.ts
52
70
  var HealthCheckService = class {
71
+ async runRoutineCheck() {
72
+ const keys = keyStore.getKeys();
73
+ const catalog = modelCatalog.getAllModels();
74
+ return {
75
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
76
+ keysTotal: keys.length,
77
+ keysValid: keys.filter((key) => key.status === "active" || key.status === "valid").length,
78
+ modelsCatalogTotal: catalog.length,
79
+ status: "healthy"
80
+ };
81
+ }
53
82
  async checkProvider(providerId, apiKey) {
54
83
  const status = await aiProviderService.checkHealth(providerId, apiKey);
55
84
  return status.isOnline;
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  toolManagerService
3
- } from "./chunk-NSKVYL74.js";
3
+ } from "./chunk-U4HUGPRH.js";
4
4
  import {
5
5
  createService,
6
6
  createServiceDefinition
@@ -9,14 +9,14 @@ import {
9
9
  inferenceExecutor
10
10
  } from "./chunk-GCTQY24J.js";
11
11
  import {
12
- keyStore
13
- } from "./chunk-4GWYTYDQ.js";
12
+ failoverExecutionEngine
13
+ } from "./chunk-AQT3GIXB.js";
14
14
  import {
15
15
  modelCatalog
16
- } from "./chunk-MFM2QIY5.js";
16
+ } from "./chunk-F4J4YPUR.js";
17
17
  import {
18
- failoverExecutionEngine
19
- } from "./chunk-MSCOKLAO.js";
18
+ keyStore
19
+ } from "./chunk-HXFTSHCP.js";
20
20
  import {
21
21
  aiProviderService
22
22
  } from "./chunk-SLR6SIEU.js";
@@ -108,6 +108,9 @@ var AIModelCatalogServiceFacade = {
108
108
  version: AIModelCatalogServiceDefinition.version,
109
109
  runtime: "server",
110
110
  deployment: "local",
111
+ getCatalog: (providerId) => modelCatalog.getCatalog(providerId),
112
+ getProviderStatuses: () => modelCatalog.getProviderStatuses(),
113
+ refreshCatalogFromEndpoints: () => modelCatalog.refreshCatalogFromEndpoints(),
111
114
  definition: AIModelCatalogServiceDefinition,
112
115
  createInstance: () => createService(AIModelCatalogServiceDefinition),
113
116
  execute: async (op, input) => {
@@ -170,6 +173,10 @@ var AIKeyServiceFacade = {
170
173
  version: AIKeyServiceDefinition.version,
171
174
  runtime: "server",
172
175
  deployment: "local",
176
+ getKeys: (providerId) => keyStore.getKeys(providerId),
177
+ getStrategy: () => keyStore.getStrategy(),
178
+ getUsageStats: (keyId, modelId) => keyStore.getUsageStats(keyId, modelId),
179
+ addKey: (input) => keyStore.addKey(input),
173
180
  definition: AIKeyServiceDefinition,
174
181
  createInstance: () => createService(AIKeyServiceDefinition),
175
182
  execute: async (op, input) => {
@@ -1,6 +1,12 @@
1
1
  import {
2
- modelHealthService
3
- } from "./chunk-Z3LXEA6P.js";
2
+ keyStore
3
+ } from "./chunk-HXFTSHCP.js";
4
+ import {
5
+ AITransportClient
6
+ } from "./chunk-MAMK4GDH.js";
7
+ import {
8
+ getProviderMeta
9
+ } from "./chunk-JSQZAFBU.js";
4
10
 
5
11
  // src/ai-models/catalogData.ts
6
12
  var STATIC_MODELS_CATALOG = [
@@ -126,9 +132,119 @@ var STATIC_MODELS_CATALOG = [
126
132
  }
127
133
  ];
128
134
 
135
+ // src/ai-models/endpointRefresher.ts
136
+ var EndpointRefresher = class {
137
+ client;
138
+ constructor(client) {
139
+ this.client = client ?? new AITransportClient();
140
+ }
141
+ async fetchRemoteModels(providerId, apiKey) {
142
+ const meta = getProviderMeta(providerId);
143
+ if (!meta) throw new Error(`Unknown provider ${providerId}`);
144
+ const url = `${meta.baseUrl}${meta.modelsEndpoint}`;
145
+ const headers = {};
146
+ if (meta.defaultHeaderKey === "Authorization") {
147
+ headers["Authorization"] = `Bearer ${apiKey.trim()}`;
148
+ } else {
149
+ headers[meta.defaultHeaderKey] = apiKey.trim();
150
+ }
151
+ const res = await this.client.request({
152
+ url,
153
+ method: "GET",
154
+ headers,
155
+ timeoutMs: 12e3
156
+ });
157
+ if (!res.ok) {
158
+ throw new Error(`Failed to fetch models from ${providerId}: HTTP ${res.status}`);
159
+ }
160
+ const rawList = res.data.data || res.data.models || [];
161
+ return rawList.map((item) => ({
162
+ id: item.id || item.name || "",
163
+ name: item.display_name || item.name || item.id || "",
164
+ providerId,
165
+ contextWindow: item.context_window || item.input_token_limit || 131072,
166
+ supportsTools: true,
167
+ supportsVision: Boolean(item.architecture?.modality?.includes("image")),
168
+ supportsJson: true,
169
+ status: "active"
170
+ }));
171
+ }
172
+ };
173
+ var endpointRefresher = new EndpointRefresher();
174
+
175
+ // src/ai-models/modelHealthService.ts
176
+ var ModelHealthService = class {
177
+ healthMap = /* @__PURE__ */ new Map();
178
+ recordSuccess(providerId, modelId, latencyMs) {
179
+ const key = `${providerId}:${modelId}`;
180
+ this.healthMap.set(key, {
181
+ modelId,
182
+ providerId,
183
+ isHealthy: true,
184
+ latencyMs,
185
+ consecutiveFailures: 0,
186
+ lastCheckedAt: (/* @__PURE__ */ new Date()).toISOString()
187
+ });
188
+ }
189
+ recordFailure(providerId, modelId, error) {
190
+ const key = `${providerId}:${modelId}`;
191
+ const existing = this.healthMap.get(key);
192
+ const consecutive = (existing?.consecutiveFailures ?? 0) + 1;
193
+ this.healthMap.set(key, {
194
+ modelId,
195
+ providerId,
196
+ isHealthy: consecutive < 3,
197
+ latencyMs: existing?.latencyMs ?? 0,
198
+ consecutiveFailures: consecutive,
199
+ lastCheckedAt: (/* @__PURE__ */ new Date()).toISOString(),
200
+ lastError: error
201
+ });
202
+ }
203
+ isModelAvailable(providerId, modelId) {
204
+ const status = this.healthMap.get(`${providerId}:${modelId}`);
205
+ return status ? status.isHealthy : true;
206
+ }
207
+ getHealth(providerId, modelId) {
208
+ return this.healthMap.get(`${providerId}:${modelId}`);
209
+ }
210
+ getAllHealth() {
211
+ return Array.from(this.healthMap.values());
212
+ }
213
+ };
214
+ var modelHealthService = new ModelHealthService();
215
+
129
216
  // src/ai-models/modelCatalog.ts
130
217
  var ModelCatalogService = class {
218
+ providerStatuses = {};
131
219
  customModels = /* @__PURE__ */ new Map();
220
+ getCatalog(providerId) {
221
+ return providerId ? this.getAllModels().filter((model) => model.providerId === providerId) : this.getAllModels();
222
+ }
223
+ getProviderStatuses() {
224
+ const providers = new Set(this.getAllModels().map((model) => model.providerId));
225
+ for (const providerId of providers) {
226
+ const modelsCount = this.getModelsByProvider(providerId).length;
227
+ this.providerStatuses[providerId] ??= { providerId, status: "online", modelsCount };
228
+ this.providerStatuses[providerId].modelsCount = modelsCount;
229
+ }
230
+ return Object.values(this.providerStatuses);
231
+ }
232
+ async refreshCatalogFromEndpoints() {
233
+ const errors = [];
234
+ let updated = 0;
235
+ for (const providerId of Array.from(new Set(this.getAllModels().map((model) => model.providerId)))) {
236
+ const key = keyStore.getActiveKey(providerId);
237
+ if (!key) continue;
238
+ try {
239
+ const models = await endpointRefresher.fetchRemoteModels(providerId, key.key);
240
+ for (const model of models) this.registerModel(model);
241
+ updated += models.length;
242
+ } catch (error) {
243
+ errors.push(error instanceof Error ? error.message : String(error));
244
+ }
245
+ }
246
+ return { updated, errors };
247
+ }
132
248
  getAllModels() {
133
249
  const list = [...STATIC_MODELS_CATALOG, ...Array.from(this.customModels.values())];
134
250
  return list;
@@ -168,6 +284,10 @@ var modelCatalog = new ModelCatalogService();
168
284
 
169
285
  export {
170
286
  STATIC_MODELS_CATALOG,
287
+ EndpointRefresher,
288
+ endpointRefresher,
289
+ ModelHealthService,
290
+ modelHealthService,
171
291
  ModelCatalogService,
172
292
  modelCatalog
173
293
  };
@@ -2,6 +2,29 @@ import {
2
2
  getProviderMeta
3
3
  } from "./chunk-JSQZAFBU.js";
4
4
 
5
+ // src/ai-keys/keysStorage.ts
6
+ var KeysStorage = class {
7
+ inMemoryKeys = /* @__PURE__ */ new Map();
8
+ loadKeys() {
9
+ return Array.from(this.inMemoryKeys.values());
10
+ }
11
+ saveKey(entry) {
12
+ this.inMemoryKeys.set(entry.id, entry);
13
+ }
14
+ saveKeys(entries) {
15
+ for (const e of entries) {
16
+ this.inMemoryKeys.set(e.id, e);
17
+ }
18
+ }
19
+ deleteKey(id) {
20
+ this.inMemoryKeys.delete(id);
21
+ }
22
+ clear() {
23
+ this.inMemoryKeys.clear();
24
+ }
25
+ };
26
+ var keysStorage = new KeysStorage();
27
+
5
28
  // src/ai-keys/keyValidator.ts
6
29
  async function validateApiKey(providerId, apiKey) {
7
30
  const meta = getProviderMeta(providerId);
@@ -68,33 +91,12 @@ async function validateApiKey(providerId, apiKey) {
68
91
  }
69
92
  }
70
93
 
71
- // src/ai-keys/keysStorage.ts
72
- var KeysStorage = class {
73
- inMemoryKeys = /* @__PURE__ */ new Map();
74
- loadKeys() {
75
- return Array.from(this.inMemoryKeys.values());
76
- }
77
- saveKey(entry) {
78
- this.inMemoryKeys.set(entry.id, entry);
79
- }
80
- saveKeys(entries) {
81
- for (const e of entries) {
82
- this.inMemoryKeys.set(e.id, e);
83
- }
84
- }
85
- deleteKey(id) {
86
- this.inMemoryKeys.delete(id);
87
- }
88
- clear() {
89
- this.inMemoryKeys.clear();
90
- }
91
- };
92
- var keysStorage = new KeysStorage();
93
-
94
94
  // src/ai-keys/keyStore.ts
95
95
  var KeyStoreService = class {
96
96
  strategy = "lowest-latency";
97
97
  roundRobinIndices = /* @__PURE__ */ new Map();
98
+ forcedNextKeys = /* @__PURE__ */ new Map();
99
+ permanentKeys = /* @__PURE__ */ new Map();
98
100
  getKeys(providerId) {
99
101
  const all = keysStorage.loadKeys();
100
102
  if (!providerId) return all;
@@ -137,14 +139,75 @@ var KeyStoreService = class {
137
139
  failedCalls: 0,
138
140
  lastLatencyMs: 0,
139
141
  errorCount: 0,
142
+ status: "active",
143
+ isActive: true,
144
+ remainingCreditsUsd: null,
145
+ weight: 5,
140
146
  ...entry
141
147
  };
142
148
  keysStorage.saveKey(full);
143
149
  return full;
144
150
  }
151
+ getPermanentKey(providerId) {
152
+ return this.permanentKeys.get(providerId) ?? null;
153
+ }
154
+ getPermanentKeysMap() {
155
+ return Object.fromEntries(this.permanentKeys.entries());
156
+ }
157
+ setPermanentKey(providerId, keyId) {
158
+ if (keyId) this.permanentKeys.set(providerId, keyId);
159
+ else this.permanentKeys.delete(providerId);
160
+ }
161
+ setForcedNextKey(providerId, keyId) {
162
+ this.forcedNextKeys.set(providerId, keyId);
163
+ }
164
+ peekNextKey(providerId, _modelId) {
165
+ const keys = this.getKeys(providerId).filter((key) => key.status !== "invalid" && key.isActive);
166
+ const forced = this.forcedNextKeys.get(providerId);
167
+ const permanent = this.permanentKeys.get(providerId);
168
+ return forced && this.getKey(forced) || permanent && this.getKey(permanent) || keys[0] || null;
169
+ }
170
+ getNextKey(providerId, modelId) {
171
+ const key = this.peekNextKey(providerId, modelId);
172
+ this.forcedNextKeys.delete(providerId);
173
+ return key;
174
+ }
145
175
  selectNextKey(providerId, _modelId) {
146
176
  return this.getActiveKey(providerId);
147
177
  }
178
+ updateKeyLabel(id, label) {
179
+ const key = this.getKey(id);
180
+ if (!key) return void 0;
181
+ key.label = label;
182
+ keysStorage.saveKey(key);
183
+ return key;
184
+ }
185
+ deleteKey(id) {
186
+ const existed = Boolean(this.getKey(id));
187
+ keysStorage.deleteKey(id);
188
+ return existed;
189
+ }
190
+ resetKeyProbabilities(id) {
191
+ const key = this.getKey(id);
192
+ if (!key) return void 0;
193
+ key.weight = 5;
194
+ key.errorCount = 0;
195
+ key.status = "active";
196
+ key.isActive = true;
197
+ keysStorage.saveKey(key);
198
+ return key;
199
+ }
200
+ resetAllFailures() {
201
+ for (const key of this.getKeys()) {
202
+ key.errorCount = 0;
203
+ key.status = "active";
204
+ key.isActive = true;
205
+ keysStorage.saveKey(key);
206
+ }
207
+ }
208
+ getUsageStats(_keyId, _modelId) {
209
+ return [];
210
+ }
148
211
  updateKeyStatus(id, status) {
149
212
  const key = this.getKey(id);
150
213
  if (!key) return;
@@ -193,9 +256,9 @@ var KeyStoreService = class {
193
256
  var keyStore = new KeyStoreService();
194
257
 
195
258
  export {
196
- validateApiKey,
197
259
  KeysStorage,
198
260
  keysStorage,
261
+ validateApiKey,
199
262
  KeyStoreService,
200
263
  keyStore
201
264
  };
@@ -3,6 +3,26 @@ var MCPEngine = class {
3
3
  servers = /* @__PURE__ */ new Map();
4
4
  registeredTools = /* @__PURE__ */ new Map();
5
5
  toolHandlers = /* @__PURE__ */ new Map();
6
+ getSystemTools() {
7
+ return this.listTools();
8
+ }
9
+ async handleJsonRpc(payload) {
10
+ const { id, method, params } = payload ?? {};
11
+ if (method === "tools/list") {
12
+ return { jsonrpc: "2.0", id, result: { tools: this.listTools() } };
13
+ }
14
+ if (method === "tools/call") {
15
+ const toolName = params?.name;
16
+ if (!toolName) return { jsonrpc: "2.0", id, error: { code: -32602, message: "Tool name is required." } };
17
+ const result = await this.executeTool(toolName, params?.arguments ?? {});
18
+ return {
19
+ jsonrpc: "2.0",
20
+ id,
21
+ result: result.success ? { content: [{ type: "text", text: JSON.stringify(result.output ?? "") }] } : { content: [{ type: "text", text: result.error ?? "Tool execution failed" }], isError: true }
22
+ };
23
+ }
24
+ return { jsonrpc: "2.0", id, error: { code: -32601, message: `Method "${method}" not found.` } };
25
+ }
6
26
  registerServer(config) {
7
27
  this.servers.set(config.id, config);
8
28
  }
File without changes
@@ -14,13 +14,15 @@ export { CompositeBackend, EndpointGenerator, GeneratedEndpointSummary, LOCAL_ST
14
14
  import { AssetDataType as AssetDataType$1, AssetChannelType as AssetChannelType$1, GraphFolderInfo as GraphFolderInfo$1, GraphAssetItem as GraphAssetItem$1, SpaceNode, NodeConnection, DawProject } from '@ultrst-armada/kloks/state-graph';
15
15
  export { AuthServiceDefinition, AuthServiceFacade, ControlPlaneServiceDefinition, ControlPlaneServiceFacade, DatabaseServiceDefinition, DatabaseServiceFacade, GeminiServiceDefinition, GeminiServiceFacade, SrklServiceDefinition, SrklServiceFacade, StorageServiceDefinition, StorageServiceFacade, WorkspaceGraphServiceDefinition, WorkspaceGraphServiceFacade, WorkspaceServiceDefinition, WorkspaceServiceFacade, krnlAuthServiceDefinition, krnlAuthServiceFacade, krnlControlPlaneServiceDefinition, krnlControlPlaneServiceFacade, krnlDatabaseServiceDefinition, krnlDatabaseServiceFacade, krnlGeminiServiceDefinition, krnlGeminiServiceFacade, krnlSrklServiceDefinition, krnlSrklServiceFacade, krnlStorageServiceDefinition, krnlStorageServiceFacade, krnlWorkspaceGraphServiceDefinition, krnlWorkspaceGraphServiceFacade, krnlWorkspaceServiceDefinition, krnlWorkspaceServiceFacade } from './krnl-services.js';
16
16
  export { AgentHarnessProvider, AgentHarnessProviderInfo, AgentHarnessResult, AgentHarnessRunInput, AgentHarnessRuntime, AgentHarnessServiceContract, AgentHarnessServiceDefinition, AgentHarnessServiceFacade, CodeDiagnosticsInput, CodeDiagnosticsResult, CodeDiagnosticsService, CodeValidationInput, CodeValidationResult, CodeValidationRuntime, CodeValidationServiceDefinition, CodeValidationServiceFacade, DevelopmentProvider, DevelopmentRequest, DevelopmentResult, DevelopmentRuntime, DevelopmentServiceContract, DevelopmentServiceDefinition, DevelopmentServiceFacade, DevelopmentTask, GitHubActionsClient, GitHubActionsConfig, GitHubActionsServiceDefinition, GitHubActionsServiceFacade, TYPESCRIPT_LANGUAGE_SERVER_PACKAGE, TYPESCRIPT_LANGUAGE_SERVER_VERSION, TypeScriptLanguageServerNotificationInput, TypeScriptLanguageServerRequestInput, TypeScriptLanguageServerResponse, TypeScriptLanguageServerServiceDefinition, TypeScriptLanguageServerServiceFacade, TypeScriptLanguageServerStartInput, TypeScriptLanguageServerStatus, ValidationDiagnostic, ValidationLayer, WebContainerCommand, WebContainerRunCommandInput, WebContainerRuntime, WebContainerServiceDefinition, WebContainerServiceFacade, WorkflowRun, codeDiagnosticsService, resolveDevelopmentCommand } from './development/index.js';
17
- export { A as AIProviderStatus, P as ProviderCapabilities, a as ProviderId, b as ProviderMeta } from './types-2p2AhboE.js';
17
+ export { A as AIProviderStatus, a as ProviderCapabilities, P as ProviderId, b as ProviderMeta } from './types-Di4ZAQYA.js';
18
18
  export { AIProviderService, PROVIDERS_META, PROVIDER_COLORS, aiProviderService, getProviderMeta, listProviders } from './ai-provider/index.js';
19
19
  export { A as AIHttpRequest, a as AIHttpResponse, b as AITransportClient } from './AITransportClient-dToGr8nj.js';
20
20
  export { DeterministicEndpointExecutor, EndpointExecutionParams, EndpointExecutionResult, ErrorClassification, InferenceExecutorService, InferenceOptions, InferenceResult, ParsedProviderError, ToolCall, classifyAndFormatError, deterministicEndpointExecutor, inferenceExecutor, parseErrorJson, performInference } from './ai-inference/index.js';
21
- export { EndpointRefresher, ModelCatalogEntry, ModelCatalogService, ModelHealthService, ModelHealthStatus, STATIC_MODELS_CATALOG, endpointRefresher, modelCatalog, modelHealthService } from './ai-models/index.js';
21
+ export { M as ModelCatalogEntry, a as ModelHealthStatus } from './types-fYUdf9oB.js';
22
+ export { EndpointRefresher, ModelCatalogService, ModelHealthService, STATIC_MODELS_CATALOG, endpointRefresher, modelCatalog, modelHealthService } from './ai-models/index.js';
22
23
  export { AIMetricRecord, AIRoutingStrategy, FailoverExecutionEngine, HealthCheckService, MetricsLogger, RetryPolicy, RouteCandidate, RouteExecutionResult, failoverExecutionEngine, healthCheckService, metricsLogger } from './ai-routing/index.js';
23
- export { ApiKeyEntry, KeyModelUsageStats, KeyStoreService, KeyValidationResult, KeysStorage, RotationStrategy, keyStore, keysStorage, validateApiKey } from './ai-keys/index.js';
24
+ export { A as ApiKeyEntry, K as KeyModelUsageStats, a as KeyValidationResult, R as RotationStrategy } from './types-B0aSwTAt.js';
25
+ export { KeyStoreService, KeysStorage, keyStore, keysStorage, validateApiKey } from './ai-keys/index.js';
24
26
  export { MCPEngine, MCPServerConfig, MCPTool, MCPToolParameter, ToolExecutionResult, ToolInputValidationResult, ToolManagerService, mcpEngine, toolManagerService, validateToolInput } from './ai-tools/index.js';
25
27
  export { AIInferenceServiceDefinition, AIInferenceServiceFacade, AIKeyServiceDefinition, AIKeyServiceFacade, AIModelCatalogServiceDefinition, AIModelCatalogServiceFacade, AIProviderServiceDefinition, AIProviderServiceFacade, AIRoutingServiceDefinition, AIRoutingServiceFacade, AIToolServiceDefinition, AIToolServiceFacade } from './krnl-ai-services.js';
26
28
  export { EndpointDescriptor, IService, ProtocolAdapter, ServiceDefinition } from '@ultrst-armada/krnl';
@@ -1,22 +1,3 @@
1
- import {
2
- S3Adapter
3
- } from "./chunk-RBQ4CW3T.js";
4
- import {
5
- RemoteWorkspaceService,
6
- SyncEngine,
7
- WorkingWorkspaceService,
8
- WorkspaceCloneSyncEngine,
9
- WorkspaceFS,
10
- findWorkspaceRecord,
11
- getDefaultWorkingWorkspaceDir,
12
- getWorkingWorkspaceConfig,
13
- getWorkingWorkspaceDir,
14
- getWorkspaceFolderKey,
15
- remoteWorkspaceService,
16
- setWorkingWorkspaceConfig,
17
- syncWorkspace,
18
- workingWorkspaceService
19
- } from "./chunk-EIYYESEU.js";
20
1
  import {
21
2
  CANONICAL_SRKL_URL,
22
3
  SrklClient,
@@ -35,6 +16,25 @@ import {
35
16
  syncSrklAccounts,
36
17
  useSrklServices
37
18
  } from "./chunk-3IUA66RS.js";
19
+ import {
20
+ S3Adapter
21
+ } from "./chunk-RBQ4CW3T.js";
22
+ import {
23
+ RemoteWorkspaceService,
24
+ SyncEngine,
25
+ WorkingWorkspaceService,
26
+ WorkspaceCloneSyncEngine,
27
+ WorkspaceFS,
28
+ findWorkspaceRecord,
29
+ getDefaultWorkingWorkspaceDir,
30
+ getWorkingWorkspaceConfig,
31
+ getWorkingWorkspaceDir,
32
+ getWorkspaceFolderKey,
33
+ remoteWorkspaceService,
34
+ setWorkingWorkspaceConfig,
35
+ syncWorkspace,
36
+ workingWorkspaceService
37
+ } from "./chunk-BTMIK44G.js";
38
38
  import {
39
39
  validateToolInput
40
40
  } from "./chunk-6GQNYRD6.js";
@@ -138,13 +138,13 @@ import {
138
138
  AIRoutingServiceFacade,
139
139
  AIToolServiceDefinition,
140
140
  AIToolServiceFacade
141
- } from "./chunk-XGPL43T3.js";
141
+ } from "./chunk-EWQYKBSN.js";
142
142
  import {
143
143
  MCPEngine,
144
144
  ToolManagerService,
145
145
  mcpEngine,
146
146
  toolManagerService
147
- } from "./chunk-NSKVYL74.js";
147
+ } from "./chunk-U4HUGPRH.js";
148
148
  import {
149
149
  AuthServiceDefinition,
150
150
  AuthServiceFacade,
@@ -178,11 +178,7 @@ import {
178
178
  krnlWorkspaceGraphServiceFacade,
179
179
  krnlWorkspaceServiceDefinition,
180
180
  krnlWorkspaceServiceFacade
181
- } from "./chunk-D6ZGQFWQ.js";
182
- import {
183
- formatCanonicalWorkspaceFolderName,
184
- sanitizeWorkspaceName
185
- } from "./chunk-FZKBTF34.js";
181
+ } from "./chunk-T26VJ22Y.js";
186
182
  import {
187
183
  getPrimarySrklDeploymentUrl,
188
184
  getSrklAccounts,
@@ -195,6 +191,10 @@ import {
195
191
  b2ListFileNames,
196
192
  b2UploadFile
197
193
  } from "./chunk-4QEMALXF.js";
194
+ import {
195
+ formatCanonicalWorkspaceFolderName,
196
+ sanitizeWorkspaceName
197
+ } from "./chunk-FZKBTF34.js";
198
198
  import {
199
199
  CanonicalAuthClient,
200
200
  RateLimiter,
@@ -241,13 +241,6 @@ import {
241
241
  updateWorkspace,
242
242
  writeWorkspaceFile
243
243
  } from "./chunk-6K75XXFD.js";
244
- import {
245
- BaseStorageAdapter,
246
- GoogleDriveAdapter,
247
- createGoogleDriveAuthorizationUrl,
248
- exchangeGoogleDriveCode,
249
- refreshGoogleDriveAccessToken
250
- } from "./chunk-KKRWZDMN.js";
251
244
  import {
252
245
  b2DeleteFileVersion,
253
246
  b2DeleteFolder,
@@ -256,6 +249,13 @@ import {
256
249
  getUnifiedDbUrl,
257
250
  queryUnifiedDb
258
251
  } from "./chunk-VAFCR2MS.js";
252
+ import {
253
+ BaseStorageAdapter,
254
+ GoogleDriveAdapter,
255
+ createGoogleDriveAuthorizationUrl,
256
+ exchangeGoogleDriveCode,
257
+ refreshGoogleDriveAccessToken
258
+ } from "./chunk-KKRWZDMN.js";
259
259
  import "./chunk-TY32TUNI.js";
260
260
  import {
261
261
  DeterministicEndpointExecutor,
@@ -269,22 +269,7 @@ import {
269
269
  performInference
270
270
  } from "./chunk-GCTQY24J.js";
271
271
  import "./chunk-IN3WRHXE.js";
272
- import {
273
- KeyStoreService,
274
- KeysStorage,
275
- keyStore,
276
- keysStorage,
277
- validateApiKey
278
- } from "./chunk-4GWYTYDQ.js";
279
- import {
280
- EndpointRefresher,
281
- endpointRefresher
282
- } from "./chunk-2WT7OUHW.js";
283
- import {
284
- ModelCatalogService,
285
- STATIC_MODELS_CATALOG,
286
- modelCatalog
287
- } from "./chunk-MFM2QIY5.js";
272
+ import "./chunk-UU6M3L3O.js";
288
273
  import "./chunk-LV55WKZR.js";
289
274
  import "./chunk-WVDSMTW3.js";
290
275
  import {
@@ -294,11 +279,23 @@ import {
294
279
  failoverExecutionEngine,
295
280
  healthCheckService,
296
281
  metricsLogger
297
- } from "./chunk-MSCOKLAO.js";
282
+ } from "./chunk-AQT3GIXB.js";
298
283
  import {
284
+ EndpointRefresher,
285
+ ModelCatalogService,
299
286
  ModelHealthService,
287
+ STATIC_MODELS_CATALOG,
288
+ endpointRefresher,
289
+ modelCatalog,
300
290
  modelHealthService
301
- } from "./chunk-Z3LXEA6P.js";
291
+ } from "./chunk-F4J4YPUR.js";
292
+ import {
293
+ KeyStoreService,
294
+ KeysStorage,
295
+ keyStore,
296
+ keysStorage,
297
+ validateApiKey
298
+ } from "./chunk-HXFTSHCP.js";
302
299
  import {
303
300
  AIProviderService,
304
301
  aiProviderService
@@ -1,5 +1,8 @@
1
1
  import * as _ultrst_armada_krnl from '@ultrst-armada/krnl';
2
2
  import { ServiceDefinition } from '@ultrst-armada/krnl';
3
+ import { P as ProviderId } from './types-Di4ZAQYA.js';
4
+ import { M as ModelCatalogEntry } from './types-fYUdf9oB.js';
5
+ import { A as ApiKeyEntry, R as RotationStrategy, K as KeyModelUsageStats } from './types-B0aSwTAt.js';
3
6
 
4
7
  declare const AIProviderServiceDefinition: ServiceDefinition;
5
8
  declare const AIProviderServiceFacade: {
@@ -30,6 +33,17 @@ declare const AIModelCatalogServiceFacade: {
30
33
  version: string;
31
34
  runtime: "server";
32
35
  deployment: "local";
36
+ getCatalog: (providerId?: string) => ModelCatalogEntry[];
37
+ getProviderStatuses: () => {
38
+ providerId: ProviderId;
39
+ status: string;
40
+ modelsCount: number;
41
+ error?: string;
42
+ }[];
43
+ refreshCatalogFromEndpoints: () => Promise<{
44
+ updated: number;
45
+ errors: string[];
46
+ }>;
33
47
  definition: ServiceDefinition<Record<string, unknown>, Record<string, unknown>>;
34
48
  createInstance: () => _ultrst_armada_krnl.ServiceInstance<Record<string, unknown>, Record<string, unknown>>;
35
49
  execute: <TIn = unknown, TOut = unknown>(op: string, input?: TIn) => Promise<TOut>;
@@ -52,6 +66,10 @@ declare const AIKeyServiceFacade: {
52
66
  version: string;
53
67
  runtime: "server";
54
68
  deployment: "local";
69
+ getKeys: (providerId?: string) => ApiKeyEntry[];
70
+ getStrategy: () => RotationStrategy;
71
+ getUsageStats: (keyId?: string, modelId?: string) => KeyModelUsageStats[];
72
+ addKey: (input: any) => ApiKeyEntry;
55
73
  definition: ServiceDefinition<Record<string, unknown>, Record<string, unknown>>;
56
74
  createInstance: () => _ultrst_armada_krnl.ServiceInstance<Record<string, unknown>, Record<string, unknown>>;
57
75
  execute: <TIn = unknown, TOut = unknown>(op: string, input?: TIn) => Promise<TOut>;
@@ -11,14 +11,13 @@ import {
11
11
  AIRoutingServiceFacade,
12
12
  AIToolServiceDefinition,
13
13
  AIToolServiceFacade
14
- } from "./chunk-XGPL43T3.js";
15
- import "./chunk-NSKVYL74.js";
14
+ } from "./chunk-EWQYKBSN.js";
15
+ import "./chunk-U4HUGPRH.js";
16
16
  import "./chunk-TY32TUNI.js";
17
17
  import "./chunk-GCTQY24J.js";
18
- import "./chunk-4GWYTYDQ.js";
19
- import "./chunk-MFM2QIY5.js";
20
- import "./chunk-MSCOKLAO.js";
21
- import "./chunk-Z3LXEA6P.js";
18
+ import "./chunk-AQT3GIXB.js";
19
+ import "./chunk-F4J4YPUR.js";
20
+ import "./chunk-HXFTSHCP.js";
22
21
  import "./chunk-SLR6SIEU.js";
23
22
  import "./chunk-MAMK4GDH.js";
24
23
  import "./chunk-JSQZAFBU.js";
@@ -31,16 +31,16 @@ import {
31
31
  krnlWorkspaceGraphServiceFacade,
32
32
  krnlWorkspaceServiceDefinition,
33
33
  krnlWorkspaceServiceFacade
34
- } from "./chunk-D6ZGQFWQ.js";
35
- import "./chunk-FZKBTF34.js";
34
+ } from "./chunk-T26VJ22Y.js";
36
35
  import "./chunk-XHADDA75.js";
37
36
  import "./chunk-4QEMALXF.js";
37
+ import "./chunk-FZKBTF34.js";
38
38
  import "./chunk-WTBAG4AV.js";
39
39
  import "./chunk-VKSGYMAH.js";
40
40
  import "./chunk-SHZAQTIT.js";
41
41
  import "./chunk-6K75XXFD.js";
42
- import "./chunk-KKRWZDMN.js";
43
42
  import "./chunk-VAFCR2MS.js";
43
+ import "./chunk-KKRWZDMN.js";
44
44
  import "./chunk-TY32TUNI.js";
45
45
  export {
46
46
  AuthServiceDefinition,
@@ -17,8 +17,8 @@ import {
17
17
  } from "../chunk-VKSGYMAH.js";
18
18
  import "../chunk-SHZAQTIT.js";
19
19
  import "../chunk-6K75XXFD.js";
20
- import "../chunk-KKRWZDMN.js";
21
20
  import "../chunk-VAFCR2MS.js";
21
+ import "../chunk-KKRWZDMN.js";
22
22
  import "../chunk-TY32TUNI.js";
23
23
  export {
24
24
  CompositeBackend,
@@ -0,0 +1,47 @@
1
+ import { P as ProviderId } from './types-Di4ZAQYA.js';
2
+
3
+ /**
4
+ * @file types.ts
5
+ * @description Canonical AI Key Management contracts and types for @ultrst-armada/kloks/backend
6
+ */
7
+
8
+ type RotationStrategy = 'lowest-latency' | 'round-robin' | 'weighted-random' | 'failover-priority';
9
+ interface ApiKeyEntry {
10
+ id: string;
11
+ providerId: ProviderId;
12
+ label: string;
13
+ key: string;
14
+ keyValue?: string;
15
+ status: 'active' | 'valid' | 'invalid' | 'rate-limited' | 'checking';
16
+ isActive: boolean;
17
+ createdAt: string;
18
+ weight: number;
19
+ remainingCreditsUsd: number | null;
20
+ totalCalls: number;
21
+ successfulCalls: number;
22
+ failedCalls: number;
23
+ lastLatencyMs: number;
24
+ errorCount: number;
25
+ lifespanSeconds?: number | null;
26
+ expiresAt?: string | null;
27
+ lastUsedAt?: string | null;
28
+ validationError?: string | null;
29
+ failedModels?: string[];
30
+ }
31
+ interface KeyValidationResult {
32
+ valid: boolean;
33
+ status: 'valid' | 'invalid' | 'rate-limited';
34
+ error?: string;
35
+ latencyMs: number;
36
+ }
37
+ interface KeyModelUsageStats {
38
+ keyId: string;
39
+ modelId: string;
40
+ totalCalls: number;
41
+ successfulCalls: number;
42
+ failedCalls: number;
43
+ lastUsedAt?: string;
44
+ avgLatencyMs?: number;
45
+ }
46
+
47
+ export type { ApiKeyEntry as A, KeyModelUsageStats as K, RotationStrategy as R, KeyValidationResult as a };
@@ -30,4 +30,4 @@ interface AIProviderStatus {
30
30
  error?: string;
31
31
  }
32
32
 
33
- export type { AIProviderStatus as A, ProviderCapabilities as P, ProviderId as a, ProviderMeta as b };
33
+ export type { AIProviderStatus as A, ProviderId as P, ProviderCapabilities as a, ProviderMeta as b };
@@ -0,0 +1,36 @@
1
+ import { P as ProviderId } from './types-Di4ZAQYA.js';
2
+
3
+ /**
4
+ * @file types.ts
5
+ * @description Canonical Model Catalog and Discovery types for @ultrst-armada/kloks/backend
6
+ */
7
+
8
+ interface ModelCatalogEntry {
9
+ id: string;
10
+ name: string;
11
+ providerId: ProviderId;
12
+ contextWindow?: number;
13
+ inputCostPer1k?: number;
14
+ outputCostPer1k?: number;
15
+ supportsTools?: boolean;
16
+ supportsVision?: boolean;
17
+ supportsJson?: boolean;
18
+ isFree?: boolean;
19
+ latencyRatingMs?: number;
20
+ qualityRating?: number;
21
+ maxOutputTokens?: number;
22
+ status?: 'active' | 'deprecated' | 'offline' | 'online' | 'currently_unavailable';
23
+ runtimeStats?: Record<string, any>;
24
+ description?: string;
25
+ }
26
+ interface ModelHealthStatus {
27
+ modelId: string;
28
+ providerId: ProviderId;
29
+ isHealthy: boolean;
30
+ latencyMs: number;
31
+ consecutiveFailures: number;
32
+ lastCheckedAt: string;
33
+ lastError?: string;
34
+ }
35
+
36
+ export type { ModelCatalogEntry as M, ModelHealthStatus as a };
@@ -6,14 +6,14 @@ import {
6
6
  WorkspaceFS,
7
7
  remoteWorkspaceService,
8
8
  workingWorkspaceService
9
- } from "../chunk-EIYYESEU.js";
9
+ } from "../chunk-BTMIK44G.js";
10
10
  import {
11
11
  formatCanonicalWorkspaceFolderName,
12
12
  sanitizeWorkspaceName
13
13
  } from "../chunk-FZKBTF34.js";
14
14
  import "../chunk-6K75XXFD.js";
15
- import "../chunk-KKRWZDMN.js";
16
15
  import "../chunk-VAFCR2MS.js";
16
+ import "../chunk-KKRWZDMN.js";
17
17
  export {
18
18
  RemoteWorkspaceService,
19
19
  SyncEngine,
@@ -7,6 +7,15 @@ import {
7
7
  instantiateSubgraph
8
8
  } from "./chunk-S22PMERU.js";
9
9
  import "./chunk-RHRXPY2U.js";
10
+ import {
11
+ LifecycleCycleError,
12
+ LifecycleGraph,
13
+ SKIPO_STATE,
14
+ SkipoStateEngine,
15
+ useLifecycleScope,
16
+ useSkipoBind,
17
+ useSkipoState
18
+ } from "./chunk-EW4ACSZB.js";
10
19
  import {
11
20
  AttractionEngine,
12
21
  GhostInferenceEngine,
@@ -22,15 +31,6 @@ import {
22
31
  WireTypeRegistry,
23
32
  initializeDefaultGraphRules
24
33
  } from "./chunk-TZOL3RN7.js";
25
- import {
26
- LifecycleCycleError,
27
- LifecycleGraph,
28
- SKIPO_STATE,
29
- SkipoStateEngine,
30
- useLifecycleScope,
31
- useSkipoBind,
32
- useSkipoState
33
- } from "./chunk-EW4ACSZB.js";
34
34
  import {
35
35
  CommandApi,
36
36
  GhostStore,
@@ -1,51 +0,0 @@
1
- import {
2
- AITransportClient
3
- } from "./chunk-MAMK4GDH.js";
4
- import {
5
- getProviderMeta
6
- } from "./chunk-JSQZAFBU.js";
7
-
8
- // src/ai-models/endpointRefresher.ts
9
- var EndpointRefresher = class {
10
- client;
11
- constructor(client) {
12
- this.client = client ?? new AITransportClient();
13
- }
14
- async fetchRemoteModels(providerId, apiKey) {
15
- const meta = getProviderMeta(providerId);
16
- if (!meta) throw new Error(`Unknown provider ${providerId}`);
17
- const url = `${meta.baseUrl}${meta.modelsEndpoint}`;
18
- const headers = {};
19
- if (meta.defaultHeaderKey === "Authorization") {
20
- headers["Authorization"] = `Bearer ${apiKey.trim()}`;
21
- } else {
22
- headers[meta.defaultHeaderKey] = apiKey.trim();
23
- }
24
- const res = await this.client.request({
25
- url,
26
- method: "GET",
27
- headers,
28
- timeoutMs: 12e3
29
- });
30
- if (!res.ok) {
31
- throw new Error(`Failed to fetch models from ${providerId}: HTTP ${res.status}`);
32
- }
33
- const rawList = res.data.data || res.data.models || [];
34
- return rawList.map((item) => ({
35
- id: item.id || item.name || "",
36
- name: item.display_name || item.name || item.id || "",
37
- providerId,
38
- contextWindow: item.context_window || item.input_token_limit || 131072,
39
- supportsTools: true,
40
- supportsVision: Boolean(item.architecture?.modality?.includes("image")),
41
- supportsJson: true,
42
- status: "active"
43
- }));
44
- }
45
- };
46
- var endpointRefresher = new EndpointRefresher();
47
-
48
- export {
49
- EndpointRefresher,
50
- endpointRefresher
51
- };
@@ -1,45 +0,0 @@
1
- // src/ai-models/modelHealthService.ts
2
- var ModelHealthService = class {
3
- healthMap = /* @__PURE__ */ new Map();
4
- recordSuccess(providerId, modelId, latencyMs) {
5
- const key = `${providerId}:${modelId}`;
6
- this.healthMap.set(key, {
7
- modelId,
8
- providerId,
9
- isHealthy: true,
10
- latencyMs,
11
- consecutiveFailures: 0,
12
- lastCheckedAt: (/* @__PURE__ */ new Date()).toISOString()
13
- });
14
- }
15
- recordFailure(providerId, modelId, error) {
16
- const key = `${providerId}:${modelId}`;
17
- const existing = this.healthMap.get(key);
18
- const consecutive = (existing?.consecutiveFailures ?? 0) + 1;
19
- this.healthMap.set(key, {
20
- modelId,
21
- providerId,
22
- isHealthy: consecutive < 3,
23
- latencyMs: existing?.latencyMs ?? 0,
24
- consecutiveFailures: consecutive,
25
- lastCheckedAt: (/* @__PURE__ */ new Date()).toISOString(),
26
- lastError: error
27
- });
28
- }
29
- isModelAvailable(providerId, modelId) {
30
- const status = this.healthMap.get(`${providerId}:${modelId}`);
31
- return status ? status.isHealthy : true;
32
- }
33
- getHealth(providerId, modelId) {
34
- return this.healthMap.get(`${providerId}:${modelId}`);
35
- }
36
- getAllHealth() {
37
- return Array.from(this.healthMap.values());
38
- }
39
- };
40
- var modelHealthService = new ModelHealthService();
41
-
42
- export {
43
- ModelHealthService,
44
- modelHealthService
45
- };
@@ -5,15 +5,15 @@ import {
5
5
  getWorkspaces,
6
6
  updateWorkspace
7
7
  } from "./chunk-6K75XXFD.js";
8
- import {
9
- GoogleDriveAdapter
10
- } from "./chunk-KKRWZDMN.js";
11
8
  import {
12
9
  b2DownloadFile,
13
10
  b2ListFileNames,
14
11
  b2UploadFile,
15
12
  queryUnifiedDb
16
13
  } from "./chunk-VAFCR2MS.js";
14
+ import {
15
+ GoogleDriveAdapter
16
+ } from "./chunk-KKRWZDMN.js";
17
17
 
18
18
  // src/workspace/WorkspaceFS.ts
19
19
  import { SkipoBase } from "@ultrst-armada/kloks/functions";
@@ -1,7 +1,3 @@
1
- import {
2
- formatCanonicalWorkspaceFolderName,
3
- sanitizeWorkspaceName
4
- } from "./chunk-FZKBTF34.js";
5
1
  import {
6
2
  getSrklAccounts,
7
3
  srklListBackblazeBuckets
@@ -9,6 +5,10 @@ import {
9
5
  import {
10
6
  b2ListBuckets
11
7
  } from "./chunk-4QEMALXF.js";
8
+ import {
9
+ formatCanonicalWorkspaceFolderName,
10
+ sanitizeWorkspaceName
11
+ } from "./chunk-FZKBTF34.js";
12
12
  import {
13
13
  RateLimiter,
14
14
  SessionManager,