marona 0.15.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -464
- package/README.md +62 -787
- package/dist/index.d.ts +113 -88
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +276 -1005
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export const packageVersion = "
|
|
1
|
+
export const packageVersion = "1.1.0";
|
|
2
2
|
const maronaApiKeyRequired = "Marona Developer Key is required.\n\n" +
|
|
3
3
|
"Provide it through the SDK configuration or set the MARONA_API_KEY environment variable.\n\n" +
|
|
4
4
|
"Create/manage developer keys from the Marona Developer Portal.";
|
|
@@ -9,28 +9,6 @@ const interfaceNamePattern = "^[a-z][a-z0-9_-]{0,63}$";
|
|
|
9
9
|
const standardExecutionModes = ["online", "hybrid", "offline"];
|
|
10
10
|
const localExecutionTargetTypes = new Set(["python_package", "wasm", "static_cache", "builtin"]);
|
|
11
11
|
const remoteExecutionTargetTypes = new Set(["remote_mcp", "marona_hosted"]);
|
|
12
|
-
const providerDefaultEndpoints = {
|
|
13
|
-
openai: "https://api.openai.com/v1",
|
|
14
|
-
openrouter: "https://openrouter.ai/api/v1",
|
|
15
|
-
anthropic: "https://api.anthropic.com/v1",
|
|
16
|
-
gemini: "https://generativelanguage.googleapis.com/v1beta",
|
|
17
|
-
ollama: "http://127.0.0.1:11434/v1",
|
|
18
|
-
};
|
|
19
|
-
const providerKeyEnvironment = {
|
|
20
|
-
openai: "OPENAI_API_KEY",
|
|
21
|
-
openrouter: "OPENROUTER_API_KEY",
|
|
22
|
-
anthropic: "ANTHROPIC_API_KEY",
|
|
23
|
-
gemini: "GEMINI_API_KEY",
|
|
24
|
-
litellm: "LITELLM_API_KEY",
|
|
25
|
-
};
|
|
26
|
-
const providerEndpointEnvironment = {
|
|
27
|
-
openai: "OPENAI_API_BASE",
|
|
28
|
-
openrouter: "OPENROUTER_API_BASE",
|
|
29
|
-
anthropic: "ANTHROPIC_API_BASE",
|
|
30
|
-
gemini: "GEMINI_API_BASE",
|
|
31
|
-
ollama: "OLLAMA_API_BASE",
|
|
32
|
-
litellm: "LITELLM_API_BASE",
|
|
33
|
-
};
|
|
34
12
|
function normalizeExecutionModes(value) {
|
|
35
13
|
const rawModes = Array.isArray(value) ? value : ["online"];
|
|
36
14
|
const modes = [];
|
|
@@ -81,6 +59,95 @@ export class EdgeRuntimeError extends Error {
|
|
|
81
59
|
this.payload = options.payload;
|
|
82
60
|
}
|
|
83
61
|
}
|
|
62
|
+
export class MaronaError extends EdgeRuntimeError {
|
|
63
|
+
code;
|
|
64
|
+
requestId;
|
|
65
|
+
retryable;
|
|
66
|
+
requiredAction;
|
|
67
|
+
retryAfterMs;
|
|
68
|
+
details;
|
|
69
|
+
constructor(message, options) {
|
|
70
|
+
super(message, options);
|
|
71
|
+
this.name = "MaronaError";
|
|
72
|
+
this.code = options.code;
|
|
73
|
+
this.requestId = options.requestId;
|
|
74
|
+
this.retryable = options.retryable ?? false;
|
|
75
|
+
this.requiredAction = options.requiredAction;
|
|
76
|
+
this.retryAfterMs = options.retryAfterMs;
|
|
77
|
+
this.details = options.details;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
export class MaronaApiKeyRequiredError extends MaronaError {
|
|
81
|
+
}
|
|
82
|
+
export class MaronaAuthenticationError extends MaronaError {
|
|
83
|
+
}
|
|
84
|
+
export class InvalidModelNamespaceError extends MaronaError {
|
|
85
|
+
}
|
|
86
|
+
export class ModelNotFoundError extends MaronaError {
|
|
87
|
+
}
|
|
88
|
+
export class ModelAccessDeniedError extends MaronaError {
|
|
89
|
+
}
|
|
90
|
+
export class ModelConfigurationError extends MaronaError {
|
|
91
|
+
}
|
|
92
|
+
export class InsufficientCreditsError extends MaronaError {
|
|
93
|
+
}
|
|
94
|
+
export class ProviderAuthenticationError extends MaronaError {
|
|
95
|
+
}
|
|
96
|
+
export class ProviderRateLimitedError extends MaronaError {
|
|
97
|
+
}
|
|
98
|
+
export class ProviderUnavailableError extends MaronaError {
|
|
99
|
+
}
|
|
100
|
+
export class CustomModelAuthenticationError extends MaronaError {
|
|
101
|
+
}
|
|
102
|
+
export class CustomModelTimeoutError extends MaronaError {
|
|
103
|
+
}
|
|
104
|
+
export class CustomModelUnavailableError extends MaronaError {
|
|
105
|
+
}
|
|
106
|
+
export class MaronaServiceUnavailableError extends MaronaError {
|
|
107
|
+
}
|
|
108
|
+
export class RateLimitExceededError extends MaronaError {
|
|
109
|
+
}
|
|
110
|
+
export class RequestTimeoutError extends MaronaError {
|
|
111
|
+
}
|
|
112
|
+
export class BillingError extends MaronaError {
|
|
113
|
+
}
|
|
114
|
+
export class InternalError extends MaronaError {
|
|
115
|
+
}
|
|
116
|
+
function maronaError(payload, statusCode, fallback) {
|
|
117
|
+
const error = asRecord(asRecord(payload)?.error) ?? {};
|
|
118
|
+
const code = stringValue(error.code) ?? "INTERNAL_ERROR";
|
|
119
|
+
const options = {
|
|
120
|
+
code,
|
|
121
|
+
statusCode,
|
|
122
|
+
requestId: stringValue(error.request_id),
|
|
123
|
+
retryable: error.retryable === true,
|
|
124
|
+
requiredAction: stringValue(error.required_action),
|
|
125
|
+
retryAfterMs: numberValue(error.retry_after_ms),
|
|
126
|
+
details: error.details,
|
|
127
|
+
payload,
|
|
128
|
+
};
|
|
129
|
+
const message = stringValue(error.message) ?? fallback;
|
|
130
|
+
const ErrorType = code === "MARONA_API_KEY_REQUIRED" ? MaronaApiKeyRequiredError
|
|
131
|
+
: ["INVALID_MARONA_API_KEY", "MARONA_API_KEY_REVOKED", "MARONA_API_KEY_EXPIRED"].includes(code) ? MaronaAuthenticationError
|
|
132
|
+
: code === "INVALID_MODEL_NAMESPACE" ? InvalidModelNamespaceError
|
|
133
|
+
: code === "MODEL_NOT_FOUND" ? ModelNotFoundError
|
|
134
|
+
: code === "MODEL_ACCESS_DENIED" ? ModelAccessDeniedError
|
|
135
|
+
: code === "MODEL_CONFIGURATION_ERROR" ? ModelConfigurationError
|
|
136
|
+
: code === "INSUFFICIENT_CREDITS" ? InsufficientCreditsError
|
|
137
|
+
: code === "PROVIDER_AUTHENTICATION_FAILED" ? ProviderAuthenticationError
|
|
138
|
+
: code === "PROVIDER_RATE_LIMITED" ? ProviderRateLimitedError
|
|
139
|
+
: ["PROVIDER_UNAVAILABLE", "PROVIDER_REQUEST_FAILED"].includes(code) ? ProviderUnavailableError
|
|
140
|
+
: code === "CUSTOM_MODEL_AUTHENTICATION_FAILED" ? CustomModelAuthenticationError
|
|
141
|
+
: code === "CUSTOM_MODEL_TIMEOUT" ? CustomModelTimeoutError
|
|
142
|
+
: code === "CUSTOM_MODEL_UNAVAILABLE" ? CustomModelUnavailableError
|
|
143
|
+
: code === "MARONA_SERVICE_UNAVAILABLE" ? MaronaServiceUnavailableError
|
|
144
|
+
: code === "RATE_LIMIT_EXCEEDED" ? RateLimitExceededError
|
|
145
|
+
: code === "REQUEST_TIMEOUT" ? RequestTimeoutError
|
|
146
|
+
: code === "BILLING_ERROR" ? BillingError
|
|
147
|
+
: code === "INTERNAL_ERROR" ? InternalError
|
|
148
|
+
: MaronaError;
|
|
149
|
+
return new ErrorType(message, options);
|
|
150
|
+
}
|
|
84
151
|
export class MaronaOfflineError extends EdgeRuntimeError {
|
|
85
152
|
constructor(message, options = {}) {
|
|
86
153
|
super(message, options);
|
|
@@ -103,9 +170,7 @@ class MaronaCache {
|
|
|
103
170
|
syncPayload;
|
|
104
171
|
privateContext;
|
|
105
172
|
apps = new Map();
|
|
106
|
-
models = new Map();
|
|
107
173
|
conversationContexts = new Map();
|
|
108
|
-
defaultModelName;
|
|
109
174
|
loadSyncPayload() {
|
|
110
175
|
return this.syncPayload ? { ...this.syncPayload } : undefined;
|
|
111
176
|
}
|
|
@@ -143,15 +208,6 @@ class MaronaCache {
|
|
|
143
208
|
if (record && slug)
|
|
144
209
|
this.apps.set(slug, record);
|
|
145
210
|
}
|
|
146
|
-
const models = Array.isArray(payload.models) ? payload.models : [];
|
|
147
|
-
for (const model of models) {
|
|
148
|
-
const record = asRecord(model);
|
|
149
|
-
if (record)
|
|
150
|
-
this.saveModel(modelFromJson(record));
|
|
151
|
-
}
|
|
152
|
-
const defaultModel = stringValue(payload.default_model);
|
|
153
|
-
if (defaultModel && this.models.has(defaultModel))
|
|
154
|
-
this.defaultModelName = defaultModel;
|
|
155
211
|
const contexts = asRecord(payload.conversation_contexts);
|
|
156
212
|
if (contexts) {
|
|
157
213
|
for (const [key, value] of Object.entries(contexts)) {
|
|
@@ -168,8 +224,6 @@ class MaronaCache {
|
|
|
168
224
|
sync_payload: this.syncPayload,
|
|
169
225
|
private_context: this.privateContext,
|
|
170
226
|
apps: [...this.apps.values()].map((app) => ({ ...app })),
|
|
171
|
-
models: [...this.models.values()].map(redactModel),
|
|
172
|
-
default_model: this.defaultModelName,
|
|
173
227
|
conversation_contexts: Object.fromEntries(this.conversationContexts.entries()),
|
|
174
228
|
});
|
|
175
229
|
}
|
|
@@ -179,11 +233,6 @@ class MaronaCache {
|
|
|
179
233
|
loadPrivateContext() {
|
|
180
234
|
return this.privateContext ? { ...this.privateContext } : undefined;
|
|
181
235
|
}
|
|
182
|
-
saveModel(model, options = {}) {
|
|
183
|
-
this.models.set(model.name, { ...model, features: [...model.features], metadata: { ...model.metadata } });
|
|
184
|
-
if (options.makeDefault || !this.defaultModelName)
|
|
185
|
-
this.defaultModelName = model.name;
|
|
186
|
-
}
|
|
187
236
|
loadConversationContext(conversationId) {
|
|
188
237
|
return { ...(this.conversationContexts.get(conversationKey(conversationId)) ?? {}) };
|
|
189
238
|
}
|
|
@@ -236,145 +285,11 @@ class MaronaCache {
|
|
|
236
285
|
}
|
|
237
286
|
return output;
|
|
238
287
|
}
|
|
239
|
-
getModel(name) {
|
|
240
|
-
const model = this.models.get(name);
|
|
241
|
-
return model ? { ...model, features: [...model.features], metadata: { ...model.metadata } } : undefined;
|
|
242
|
-
}
|
|
243
|
-
listModels() {
|
|
244
|
-
return [...this.models.values()].map((model) => ({
|
|
245
|
-
...model,
|
|
246
|
-
features: [...model.features],
|
|
247
|
-
metadata: { ...model.metadata },
|
|
248
|
-
}));
|
|
249
|
-
}
|
|
250
|
-
removeModel(name) {
|
|
251
|
-
this.models.delete(name);
|
|
252
|
-
if (this.defaultModelName === name)
|
|
253
|
-
this.defaultModelName = undefined;
|
|
254
|
-
}
|
|
255
|
-
useModel(name) {
|
|
256
|
-
const model = this.getModel(name);
|
|
257
|
-
if (!model)
|
|
258
|
-
throw new MaronaModelError(`Model '${name}' is not registered.`);
|
|
259
|
-
this.defaultModelName = name;
|
|
260
|
-
return model;
|
|
261
|
-
}
|
|
262
|
-
defaultModel() {
|
|
263
|
-
if (this.defaultModelName)
|
|
264
|
-
return this.getModel(this.defaultModelName);
|
|
265
|
-
const first = this.models.values().next();
|
|
266
|
-
return first.done ? undefined : this.getModel(first.value.name);
|
|
267
|
-
}
|
|
268
288
|
clear() {
|
|
269
289
|
this.syncPayload = undefined;
|
|
270
290
|
this.privateContext = undefined;
|
|
271
291
|
this.apps.clear();
|
|
272
|
-
this.models.clear();
|
|
273
292
|
this.conversationContexts.clear();
|
|
274
|
-
this.defaultModelName = undefined;
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
class ModelManager {
|
|
278
|
-
cache;
|
|
279
|
-
fetchImpl;
|
|
280
|
-
executors = new Map();
|
|
281
|
-
adapters = new Map();
|
|
282
|
-
constructor(cache, fetchImpl) {
|
|
283
|
-
this.cache = cache;
|
|
284
|
-
this.fetchImpl = fetchImpl;
|
|
285
|
-
}
|
|
286
|
-
async register(input) {
|
|
287
|
-
if (!input.name.trim())
|
|
288
|
-
throw new MaronaModelError("Model name is required.");
|
|
289
|
-
const name = input.name.trim();
|
|
290
|
-
const endpoint = input.executor
|
|
291
|
-
? `local://${name}`
|
|
292
|
-
: input.adapter
|
|
293
|
-
? (input.endpoint ?? `adapter://${name}`).replace(/\/+$/, "")
|
|
294
|
-
: (input.endpoint ?? "").replace(/\/+$/, "");
|
|
295
|
-
if (!endpoint)
|
|
296
|
-
throw new MaronaModelError("Model endpoint or executor is required.");
|
|
297
|
-
const record = {
|
|
298
|
-
name,
|
|
299
|
-
endpoint,
|
|
300
|
-
provider: cleanString(input.provider)?.toLowerCase(),
|
|
301
|
-
model: input.model,
|
|
302
|
-
protocol: input.executor ? "local_executor" : input.adapter ? "custom_adapter" : input.protocol,
|
|
303
|
-
features: input.executor || input.adapter
|
|
304
|
-
? [...new Set([...(input.features ?? []), "text", "tool_calling", "streaming"])]
|
|
305
|
-
: input.features ?? [],
|
|
306
|
-
location: input.executor ? "local" : inferLocation(endpoint),
|
|
307
|
-
status: input.executor || input.adapter ? "available" : "registered",
|
|
308
|
-
apiKey: input.apiKey,
|
|
309
|
-
metadata: input.metadata ?? {},
|
|
310
|
-
lastCheckedAt: input.executor || input.adapter ? new Date().toISOString() : undefined,
|
|
311
|
-
contextWindow: input.contextWindow,
|
|
312
|
-
maxOutputTokens: input.maxOutputTokens,
|
|
313
|
-
};
|
|
314
|
-
if (input.executor)
|
|
315
|
-
this.executors.set(name, input.executor);
|
|
316
|
-
if (input.adapter)
|
|
317
|
-
this.adapters.set(name, input.adapter);
|
|
318
|
-
const detected = input.executor || input.adapter ? record : await this.detect(record);
|
|
319
|
-
this.cache.saveModel(detected, { makeDefault: input.makeDefault ?? false });
|
|
320
|
-
return detected;
|
|
321
|
-
}
|
|
322
|
-
get(name) {
|
|
323
|
-
return this.cache.getModel(name);
|
|
324
|
-
}
|
|
325
|
-
executor(name) {
|
|
326
|
-
return this.executors.get(name);
|
|
327
|
-
}
|
|
328
|
-
adapter(name) {
|
|
329
|
-
return this.adapters.get(name);
|
|
330
|
-
}
|
|
331
|
-
list() {
|
|
332
|
-
return this.cache.listModels();
|
|
333
|
-
}
|
|
334
|
-
remove(name) {
|
|
335
|
-
this.cache.removeModel(name);
|
|
336
|
-
}
|
|
337
|
-
async inspect(name) {
|
|
338
|
-
const model = this.cache.getModel(name);
|
|
339
|
-
if (!model)
|
|
340
|
-
throw new MaronaModelError(`Model '${name}' is not registered.`);
|
|
341
|
-
const detected = await this.detect(model);
|
|
342
|
-
this.cache.saveModel(detected);
|
|
343
|
-
return detected;
|
|
344
|
-
}
|
|
345
|
-
default() {
|
|
346
|
-
return this.cache.defaultModel();
|
|
347
|
-
}
|
|
348
|
-
async detect(record) {
|
|
349
|
-
for (const base of candidateModelBases(record.endpoint)) {
|
|
350
|
-
try {
|
|
351
|
-
const response = await this.fetchImpl(`${base}/models`, {
|
|
352
|
-
headers: modelHeaders(record),
|
|
353
|
-
});
|
|
354
|
-
if (response.ok) {
|
|
355
|
-
const payload = await response.json();
|
|
356
|
-
const modelId = selectModelId(payload, record.model);
|
|
357
|
-
return {
|
|
358
|
-
...record,
|
|
359
|
-
endpoint: base,
|
|
360
|
-
model: modelId,
|
|
361
|
-
protocol: record.protocol ?? "chat_completions",
|
|
362
|
-
features: [...new Set([...(record.features ?? []), "text", "streaming"])],
|
|
363
|
-
status: "available",
|
|
364
|
-
lastCheckedAt: new Date().toISOString(),
|
|
365
|
-
};
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
catch {
|
|
369
|
-
continue;
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
return {
|
|
373
|
-
...record,
|
|
374
|
-
protocol: record.protocol ?? "custom_http",
|
|
375
|
-
status: "unverified",
|
|
376
|
-
lastCheckedAt: new Date().toISOString(),
|
|
377
|
-
};
|
|
378
293
|
}
|
|
379
294
|
}
|
|
380
295
|
function neutralGatewayTools() {
|
|
@@ -927,7 +842,7 @@ export class Agent {
|
|
|
927
842
|
constructor(options) {
|
|
928
843
|
this.name = options.name.trim();
|
|
929
844
|
this.description = cleanString(options.description);
|
|
930
|
-
this.model = (options.model
|
|
845
|
+
this.model = validateModelNamespace(options.model);
|
|
931
846
|
this.instructions = typeof options.instructions === "function"
|
|
932
847
|
? options.instructions
|
|
933
848
|
: (options.instructions ?? "").trim();
|
|
@@ -1163,7 +1078,6 @@ export class Runner {
|
|
|
1163
1078
|
}
|
|
1164
1079
|
}
|
|
1165
1080
|
export class RealtimeSession {
|
|
1166
|
-
provider;
|
|
1167
1081
|
model;
|
|
1168
1082
|
conversationId;
|
|
1169
1083
|
descriptor;
|
|
@@ -1183,7 +1097,6 @@ export class RealtimeSession {
|
|
|
1183
1097
|
this.agent = agent;
|
|
1184
1098
|
this.userId = cleanString(options.userId);
|
|
1185
1099
|
this.sessionId = cleanString(options.sessionId) ?? "default";
|
|
1186
|
-
this.provider = descriptor.provider;
|
|
1187
1100
|
this.model = descriptor.model;
|
|
1188
1101
|
this.conversationId = descriptor.conversationId;
|
|
1189
1102
|
this.selectorMap = asRecord(descriptor.capabilities.selector_map) ?? {};
|
|
@@ -1466,7 +1379,7 @@ export class RealtimeRunner {
|
|
|
1466
1379
|
}
|
|
1467
1380
|
async function openRealtimeSocket(descriptor) {
|
|
1468
1381
|
if (!descriptor.clientSecret) {
|
|
1469
|
-
throw new EdgeRuntimeError("
|
|
1382
|
+
throw new EdgeRuntimeError("Marona Runtime did not return a realtime session token.");
|
|
1470
1383
|
}
|
|
1471
1384
|
let lastError;
|
|
1472
1385
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
@@ -1486,7 +1399,7 @@ async function openRealtimeSocketAttempt(descriptor) {
|
|
|
1486
1399
|
const Socket = globalThis.WebSocket ?? (await import("ws")).default;
|
|
1487
1400
|
const socket = new Socket(descriptor.endpoint, [
|
|
1488
1401
|
"realtime",
|
|
1489
|
-
`
|
|
1402
|
+
`marona-bearer.${descriptor.clientSecret}`,
|
|
1490
1403
|
]);
|
|
1491
1404
|
await new Promise((resolve, reject) => {
|
|
1492
1405
|
const timer = setTimeout(() => {
|
|
@@ -1962,7 +1875,7 @@ function responsesContext(options, metadata) {
|
|
|
1962
1875
|
metadata: {
|
|
1963
1876
|
...metadata,
|
|
1964
1877
|
_marona: {
|
|
1965
|
-
model: options.model ?? "marona/
|
|
1878
|
+
model: options.model ?? "marona/auto",
|
|
1966
1879
|
framework: "marona",
|
|
1967
1880
|
runtime: "responses",
|
|
1968
1881
|
},
|
|
@@ -2222,7 +2135,7 @@ class HubClient {
|
|
|
2222
2135
|
timeoutMs;
|
|
2223
2136
|
fetchImpl;
|
|
2224
2137
|
toolExecutor;
|
|
2225
|
-
constructor(baseUrl = "https://
|
|
2138
|
+
constructor(baseUrl = "https://platform.marona.ai/api", options = {}) {
|
|
2226
2139
|
this.baseUrl = baseUrl.replace(/\/+$/, "");
|
|
2227
2140
|
this.timeoutMs = options.timeoutMs ?? 60_000;
|
|
2228
2141
|
this.defaultHeaders = { ...(options.headers ?? {}) };
|
|
@@ -2258,12 +2171,79 @@ class HubClient {
|
|
|
2258
2171
|
const payload = await this.requestJson("GET", "/hub/billing/summary");
|
|
2259
2172
|
return asRecord(payload) ?? {};
|
|
2260
2173
|
}
|
|
2174
|
+
async registerMcpServer(input) {
|
|
2175
|
+
return this.mcpRecord(await this.requestJson("POST", "/hub/mcp/servers", { body: {
|
|
2176
|
+
name: input.name, slug: input.slug, server_url: input.serverUrl,
|
|
2177
|
+
description: input.description ?? "", visibility: input.visibility ?? "private",
|
|
2178
|
+
transport: "streamable_http", auth_mode: input.authMode ?? "none",
|
|
2179
|
+
} }));
|
|
2180
|
+
}
|
|
2181
|
+
async listMcpServers() {
|
|
2182
|
+
return this.mcpRecord(await this.requestJson("GET", "/hub/mcp/servers"));
|
|
2183
|
+
}
|
|
2184
|
+
async getMcpServer(serverId) {
|
|
2185
|
+
return this.mcpRecord(await this.requestJson("GET", this.mcpPath(serverId)));
|
|
2186
|
+
}
|
|
2187
|
+
async verifyMcpServer(serverId) {
|
|
2188
|
+
return this.mcpRecord(await this.requestJson("POST", `${this.mcpPath(serverId)}/verify`, { body: {} }));
|
|
2189
|
+
}
|
|
2190
|
+
async activateMcpServer(serverId, allowedTools = []) {
|
|
2191
|
+
return this.mcpRecord(await this.requestJson("POST", `${this.mcpPath(serverId)}/activate`, { body: { allowed_tools: allowedTools } }));
|
|
2192
|
+
}
|
|
2193
|
+
async disableMcpServer(serverId) {
|
|
2194
|
+
return this.mcpRecord(await this.requestJson("POST", `${this.mcpPath(serverId)}/disable`, { body: {} }));
|
|
2195
|
+
}
|
|
2196
|
+
async setMcpApiKey(serverId, input) {
|
|
2197
|
+
return this.mcpRecord(await this.requestJson("POST", `${this.mcpPath(serverId)}/credentials/api-key`, { body: {
|
|
2198
|
+
value: input.value, header: input.header ?? "x-api-key", user_subject: input.userSubject,
|
|
2199
|
+
} }));
|
|
2200
|
+
}
|
|
2201
|
+
async configureMcpOauthClient(serverId, input) {
|
|
2202
|
+
return this.mcpRecord(await this.requestJson("POST", `${this.mcpPath(serverId)}/credentials/oauth-client`, { body: {
|
|
2203
|
+
client_id: input.clientId, client_secret: input.clientSecret,
|
|
2204
|
+
} }));
|
|
2205
|
+
}
|
|
2206
|
+
async startMcpOauth(serverId, input = {}) {
|
|
2207
|
+
return this.mcpRecord(await this.requestJson("POST", `${this.mcpPath(serverId)}/oauth/start`, { body: {
|
|
2208
|
+
scopes: input.scopes ?? [], user_subject: input.userSubject,
|
|
2209
|
+
} }));
|
|
2210
|
+
}
|
|
2211
|
+
async executeMcpTool(serverId, input) {
|
|
2212
|
+
return this.mcpRecord(await this.requestJson("POST", `${this.mcpPath(serverId)}/execute`, { body: {
|
|
2213
|
+
tool: input.tool, arguments: input.arguments ?? {}, user_subject: input.userSubject,
|
|
2214
|
+
approved: input.approved ?? false, request_id: input.requestId,
|
|
2215
|
+
} }));
|
|
2216
|
+
}
|
|
2217
|
+
async listMcpInvocations(limit = 50) {
|
|
2218
|
+
return this.mcpRecord(await this.requestJson("GET", `/hub/mcp/invocations?limit=${Math.trunc(limit)}`));
|
|
2219
|
+
}
|
|
2220
|
+
async listMcpRegistry(limit = 50, cursor) {
|
|
2221
|
+
const query = new URLSearchParams({ limit: String(Math.trunc(limit)) });
|
|
2222
|
+
if (cursor)
|
|
2223
|
+
query.set("cursor", cursor);
|
|
2224
|
+
return this.mcpRecord(await this.requestJson("GET", `/hub/mcp/registry?${query}`));
|
|
2225
|
+
}
|
|
2226
|
+
async importMcpRegistry(input) {
|
|
2227
|
+
return this.mcpRecord(await this.requestJson("POST", "/hub/mcp/registry/import", { body: {
|
|
2228
|
+
registry_name: input.registryName, version: input.version ?? "latest", slug: input.slug,
|
|
2229
|
+
visibility: input.visibility ?? "private", auth_mode: input.authMode ?? "none",
|
|
2230
|
+
} }));
|
|
2231
|
+
}
|
|
2232
|
+
mcpPath(serverId) {
|
|
2233
|
+
return `/hub/mcp/servers/${encodeURIComponent(serverId)}`;
|
|
2234
|
+
}
|
|
2235
|
+
mcpRecord(payload) {
|
|
2236
|
+
const record = asRecord(payload);
|
|
2237
|
+
if (!record)
|
|
2238
|
+
throw new EdgeRuntimeError("Marona Hub returned an invalid MCP response.", { payload });
|
|
2239
|
+
return record;
|
|
2240
|
+
}
|
|
2261
2241
|
async requestJson(method, path, options = {}) {
|
|
2262
2242
|
requireMaronaApiKey(this.defaultHeaders);
|
|
2263
2243
|
const controller = new AbortController();
|
|
2264
2244
|
const timeout = this.timeoutMs > 0 ? setTimeout(() => controller.abort(), this.timeoutMs) : undefined;
|
|
2265
2245
|
try {
|
|
2266
|
-
const url = new URL(path, `${this.baseUrl}/`);
|
|
2246
|
+
const url = new URL(path.replace(/^\/+/, ""), `${this.baseUrl}/`);
|
|
2267
2247
|
const response = await this.fetchImpl(url.toString(), {
|
|
2268
2248
|
method,
|
|
2269
2249
|
headers: {
|
|
@@ -2277,10 +2257,7 @@ class HubClient {
|
|
|
2277
2257
|
const text = await response.text();
|
|
2278
2258
|
const payload = parseMaybeJson(text);
|
|
2279
2259
|
if (!response.ok) {
|
|
2280
|
-
throw
|
|
2281
|
-
statusCode: response.status,
|
|
2282
|
-
payload,
|
|
2283
|
-
});
|
|
2260
|
+
throw maronaError(payload, response.status, "Marona Hub could not complete the request.");
|
|
2284
2261
|
}
|
|
2285
2262
|
return payload;
|
|
2286
2263
|
}
|
|
@@ -2969,7 +2946,7 @@ class RuntimeTransport {
|
|
|
2969
2946
|
signal: AbortSignal.timeout(this.timeoutMs),
|
|
2970
2947
|
});
|
|
2971
2948
|
if (!response.ok) {
|
|
2972
|
-
throw
|
|
2949
|
+
throw maronaError(parseMaybeJson(await response.text()), response.status, "Marona Runtime could not start the stream.");
|
|
2973
2950
|
}
|
|
2974
2951
|
if (!response.body) {
|
|
2975
2952
|
throw new EdgeRuntimeError("Edge runtime returned an empty event stream.");
|
|
@@ -2987,6 +2964,8 @@ class RuntimeTransport {
|
|
|
2987
2964
|
if (!line.startsWith("data:"))
|
|
2988
2965
|
continue;
|
|
2989
2966
|
const event = asRecord(parseMaybeJson(line.slice(5).trim()));
|
|
2967
|
+
if (event?.error)
|
|
2968
|
+
throw maronaError(event, undefined, "Marona Runtime stream failed.");
|
|
2990
2969
|
if (event)
|
|
2991
2970
|
yield event;
|
|
2992
2971
|
}
|
|
@@ -2995,6 +2974,8 @@ class RuntimeTransport {
|
|
|
2995
2974
|
}
|
|
2996
2975
|
if (buffer.startsWith("data:")) {
|
|
2997
2976
|
const event = asRecord(parseMaybeJson(buffer.slice(5).trim()));
|
|
2977
|
+
if (event?.error)
|
|
2978
|
+
throw maronaError(event, undefined, "Marona Runtime stream failed.");
|
|
2998
2979
|
if (event)
|
|
2999
2980
|
yield event;
|
|
3000
2981
|
}
|
|
@@ -3116,10 +3097,7 @@ class RuntimeTransport {
|
|
|
3116
3097
|
});
|
|
3117
3098
|
const text = await response.text();
|
|
3118
3099
|
if (!response.ok) {
|
|
3119
|
-
throw
|
|
3120
|
-
statusCode: response.status,
|
|
3121
|
-
payload: parseMaybeJson(text),
|
|
3122
|
-
});
|
|
3100
|
+
throw maronaError(parseMaybeJson(text), response.status, "Marona Runtime could not complete the request.");
|
|
3123
3101
|
}
|
|
3124
3102
|
return text;
|
|
3125
3103
|
}
|
|
@@ -3276,7 +3254,7 @@ class ResponsesClient {
|
|
|
3276
3254
|
for (let round = 0; round < 8; round += 1) {
|
|
3277
3255
|
const response = await this.runtime.client({
|
|
3278
3256
|
...runtimeOptions,
|
|
3279
|
-
model: options.model ?? "marona/
|
|
3257
|
+
model: options.model ?? "marona/auto",
|
|
3280
3258
|
metadata: {
|
|
3281
3259
|
...metadata,
|
|
3282
3260
|
...(results.length ? { marona_function_tool_results: results } : {}),
|
|
@@ -3372,7 +3350,7 @@ class ResponsesClient {
|
|
|
3372
3350
|
let response;
|
|
3373
3351
|
for await (const event of this.runtime.clientStream({
|
|
3374
3352
|
...options,
|
|
3375
|
-
model: options.model ?? "marona/
|
|
3353
|
+
model: options.model ?? "marona/auto",
|
|
3376
3354
|
metadata: {
|
|
3377
3355
|
...metadata,
|
|
3378
3356
|
...(results.length ? { marona_function_tool_results: results } : {}),
|
|
@@ -3431,17 +3409,11 @@ class ResponsesClient {
|
|
|
3431
3409
|
class RuntimeEngine extends RuntimeTransport {
|
|
3432
3410
|
hub;
|
|
3433
3411
|
cache;
|
|
3434
|
-
models;
|
|
3435
3412
|
skills;
|
|
3436
3413
|
tools;
|
|
3437
3414
|
responses;
|
|
3438
3415
|
mode;
|
|
3439
|
-
modelFetchImpl;
|
|
3440
3416
|
developerInstructions;
|
|
3441
|
-
defaultModelRoute;
|
|
3442
|
-
providerCredentials;
|
|
3443
|
-
providerEndpoints;
|
|
3444
|
-
maronaAccessVerified = false;
|
|
3445
3417
|
constructor(options = {}) {
|
|
3446
3418
|
const developerKey = resolveMaronaApiKey(options.apiKey);
|
|
3447
3419
|
const authenticatedHeaders = maronaHeaders(options.headers, developerKey);
|
|
@@ -3458,12 +3430,7 @@ class RuntimeEngine extends RuntimeTransport {
|
|
|
3458
3430
|
this.mode = mode;
|
|
3459
3431
|
this.cache = options.cache ?? new MaronaCache();
|
|
3460
3432
|
this.developerInstructions = undefined;
|
|
3461
|
-
this.
|
|
3462
|
-
this.providerCredentials = Object.fromEntries(Object.entries(options.providerCredentials ?? {}).map(([key, value]) => [key.toLowerCase(), value]));
|
|
3463
|
-
this.providerEndpoints = Object.fromEntries(Object.entries(options.providerEndpoints ?? {}).map(([key, value]) => [key.toLowerCase(), value.replace(/\/+$/, "")]));
|
|
3464
|
-
this.modelFetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
3465
|
-
this.models = new ModelManager(this.cache, this.modelFetchImpl);
|
|
3466
|
-
this.tools = new ToolExecutor(this.baseUrl, this.defaultHeaders, this.modelFetchImpl);
|
|
3433
|
+
this.tools = new ToolExecutor(this.baseUrl, this.defaultHeaders, options.fetchImpl ?? globalThis.fetch);
|
|
3467
3434
|
this.tools.runtime = this;
|
|
3468
3435
|
this.hub = new MaronaHubClient(options.hubUrl ?? "https://hub.marona.ai", {
|
|
3469
3436
|
apiKey: developerKey,
|
|
@@ -3503,116 +3470,20 @@ class RuntimeEngine extends RuntimeTransport {
|
|
|
3503
3470
|
return payload;
|
|
3504
3471
|
}
|
|
3505
3472
|
async message(text, options = {}) {
|
|
3506
|
-
const
|
|
3507
|
-
const
|
|
3508
|
-
|
|
3509
|
-
|
|
3510
|
-
|
|
3511
|
-
|
|
3512
|
-
|
|
3513
|
-
|
|
3514
|
-
const messageOptions = { ...options, model: modelRoute, developerInstructions };
|
|
3515
|
-
if (this.mode === "offline" && model?.location !== "local") {
|
|
3516
|
-
throw new MaronaOfflineError(`Offline mode cannot use remote model '${modelRoute}'.`);
|
|
3517
|
-
}
|
|
3518
|
-
if (model && (this.mode === "online" || model.location === "local" || this.mode === "hybrid")) {
|
|
3519
|
-
try {
|
|
3520
|
-
await this.ensureMaronaAccess();
|
|
3521
|
-
const response = await this.modelMessage(model, text, messageOptions);
|
|
3522
|
-
this.cacheTurn(text, response, messageOptions);
|
|
3523
|
-
return response;
|
|
3524
|
-
}
|
|
3525
|
-
catch (error) {
|
|
3526
|
-
if (this.mode !== "hybrid")
|
|
3527
|
-
throw error;
|
|
3528
|
-
messageOptions.model = "marona/gpt-5.6";
|
|
3529
|
-
}
|
|
3530
|
-
}
|
|
3531
|
-
if (this.mode === "online") {
|
|
3532
|
-
const response = await super.message(text, {
|
|
3533
|
-
...messageOptions,
|
|
3534
|
-
metadata: { ...(options.metadata ?? {}), ...(options.tools ? { tools: options.tools } : {}) },
|
|
3535
|
-
});
|
|
3536
|
-
this.cacheTurn(text, response, messageOptions);
|
|
3537
|
-
return response;
|
|
3538
|
-
}
|
|
3539
|
-
if (this.mode === "offline") {
|
|
3540
|
-
throw new MaronaOfflineError("Offline mode requires a registered local model before calling message().");
|
|
3541
|
-
}
|
|
3542
|
-
const response = await super.message(text, {
|
|
3543
|
-
...messageOptions,
|
|
3473
|
+
const model = validateModelNamespace(options.model);
|
|
3474
|
+
const messageOptions = {
|
|
3475
|
+
...options,
|
|
3476
|
+
model,
|
|
3477
|
+
developerInstructions: combineText([
|
|
3478
|
+
this.developerInstructions,
|
|
3479
|
+
options.developerInstructions ?? options.developer_instructions,
|
|
3480
|
+
]),
|
|
3544
3481
|
metadata: { ...(options.metadata ?? {}), ...(options.tools ? { tools: options.tools } : {}) },
|
|
3545
|
-
}
|
|
3482
|
+
};
|
|
3483
|
+
const response = await super.message(text, messageOptions);
|
|
3546
3484
|
this.cacheTurn(text, response, messageOptions);
|
|
3547
3485
|
return response;
|
|
3548
3486
|
}
|
|
3549
|
-
async ensureMaronaAccess() {
|
|
3550
|
-
if (this.maronaAccessVerified)
|
|
3551
|
-
return;
|
|
3552
|
-
requireMaronaApiKey(this.defaultHeaders);
|
|
3553
|
-
await this.hub.billingSummary();
|
|
3554
|
-
this.maronaAccessVerified = true;
|
|
3555
|
-
}
|
|
3556
|
-
resolveModel(reference) {
|
|
3557
|
-
if (reference.startsWith("marona/"))
|
|
3558
|
-
return undefined;
|
|
3559
|
-
const registered = this.models.get(reference);
|
|
3560
|
-
if (registered)
|
|
3561
|
-
return registered;
|
|
3562
|
-
const slash = reference.indexOf("/");
|
|
3563
|
-
if (slash <= 0 || slash === reference.length - 1) {
|
|
3564
|
-
throw new MaronaModelError("Model names must use an explicit namespace such as 'marona/gpt-5.6' or 'openai/gpt-5.6'.");
|
|
3565
|
-
}
|
|
3566
|
-
const routeProvider = reference.slice(0, slash).toLowerCase();
|
|
3567
|
-
const provider = routeProvider === "google" ? "gemini" : routeProvider;
|
|
3568
|
-
const providerModel = reference.slice(slash + 1);
|
|
3569
|
-
if (provider === "marona")
|
|
3570
|
-
return undefined;
|
|
3571
|
-
if (provider === "local") {
|
|
3572
|
-
throw new MaronaModelError(`Local model '${reference}' must be registered with an executor.`);
|
|
3573
|
-
}
|
|
3574
|
-
if (!["openai", "openrouter", "anthropic", "gemini", "ollama", "litellm"].includes(provider)) {
|
|
3575
|
-
throw new MaronaModelError(`Custom model route '${reference}' must be registered first.`);
|
|
3576
|
-
}
|
|
3577
|
-
const endpoint = this.providerEndpoint(provider);
|
|
3578
|
-
const apiKey = this.providerKey(provider);
|
|
3579
|
-
if (["openai", "openrouter", "anthropic", "gemini"].includes(provider) && !apiKey) {
|
|
3580
|
-
throw new MaronaModelError(`${providerKeyEnvironment[provider]} is required for '${reference}'.`);
|
|
3581
|
-
}
|
|
3582
|
-
if (provider === "litellm" && !endpoint) {
|
|
3583
|
-
throw new MaronaModelError("LITELLM_API_BASE or a configured endpoint is required.");
|
|
3584
|
-
}
|
|
3585
|
-
return {
|
|
3586
|
-
name: reference,
|
|
3587
|
-
endpoint: endpoint ?? "",
|
|
3588
|
-
provider,
|
|
3589
|
-
model: providerModel,
|
|
3590
|
-
protocol: provider === "anthropic" ? "anthropic" : provider === "gemini" ? "gemini" : "chat_completions",
|
|
3591
|
-
features: ["text", "streaming", "native_tool_calling"],
|
|
3592
|
-
location: provider === "ollama" ? "local" : "remote",
|
|
3593
|
-
status: "available",
|
|
3594
|
-
apiKey,
|
|
3595
|
-
metadata: { route: reference },
|
|
3596
|
-
lastCheckedAt: new Date().toISOString(),
|
|
3597
|
-
};
|
|
3598
|
-
}
|
|
3599
|
-
providerKey(provider) {
|
|
3600
|
-
const configured = this.providerCredentials[provider];
|
|
3601
|
-
const value = typeof configured === "string" ? configured : configured?.apiKey;
|
|
3602
|
-
return cleanString(value) ?? environmentValue(providerKeyEnvironment[provider]);
|
|
3603
|
-
}
|
|
3604
|
-
providerEndpoint(provider) {
|
|
3605
|
-
const configured = this.providerCredentials[provider];
|
|
3606
|
-
let endpoint = this.providerEndpoints[provider]
|
|
3607
|
-
?? (typeof configured === "object" ? configured.endpoint ?? configured.baseUrl : undefined)
|
|
3608
|
-
?? environmentValue(providerEndpointEnvironment[provider])
|
|
3609
|
-
?? providerDefaultEndpoints[provider];
|
|
3610
|
-
endpoint = cleanString(endpoint)?.replace(/\/+$/, "");
|
|
3611
|
-
if (endpoint && ["openai", "openrouter", "ollama", "litellm"].includes(provider) && !endpoint.endsWith("/v1")) {
|
|
3612
|
-
endpoint = `${endpoint}/v1`;
|
|
3613
|
-
}
|
|
3614
|
-
return endpoint;
|
|
3615
|
-
}
|
|
3616
3487
|
async client(options) {
|
|
3617
3488
|
const { input, attachments, ...messageOptions } = options;
|
|
3618
3489
|
const normalized = runtimeMessageFromInput(input);
|
|
@@ -3628,17 +3499,7 @@ class RuntimeEngine extends RuntimeTransport {
|
|
|
3628
3499
|
async *clientStream(options) {
|
|
3629
3500
|
const { input, attachments, ...messageOptions } = options;
|
|
3630
3501
|
const normalized = runtimeMessageFromInput(input);
|
|
3631
|
-
const
|
|
3632
|
-
?? "marona/gpt-5.6";
|
|
3633
|
-
const model = this.resolveModel(modelRoute);
|
|
3634
|
-
if (model) {
|
|
3635
|
-
const response = await this.client(options);
|
|
3636
|
-
yield { type: "run.started" };
|
|
3637
|
-
if (response.reply)
|
|
3638
|
-
yield { type: "output_text.delta", delta: response.reply };
|
|
3639
|
-
yield { type: "run.completed", output: runtimeResponsePayload(response) };
|
|
3640
|
-
return;
|
|
3641
|
-
}
|
|
3502
|
+
const model = validateModelNamespace(messageOptions.model);
|
|
3642
3503
|
const developerInstructions = combineText([
|
|
3643
3504
|
normalized.developerInstructions,
|
|
3644
3505
|
this.developerInstructions,
|
|
@@ -3646,7 +3507,7 @@ class RuntimeEngine extends RuntimeTransport {
|
|
|
3646
3507
|
]);
|
|
3647
3508
|
for await (const event of super.streamMessage(normalized.text, {
|
|
3648
3509
|
...messageOptions,
|
|
3649
|
-
model
|
|
3510
|
+
model,
|
|
3650
3511
|
developerInstructions,
|
|
3651
3512
|
attachments: [...normalized.attachments, ...(attachments ?? [])],
|
|
3652
3513
|
metadata: {
|
|
@@ -3657,361 +3518,6 @@ class RuntimeEngine extends RuntimeTransport {
|
|
|
3657
3518
|
yield event;
|
|
3658
3519
|
}
|
|
3659
3520
|
}
|
|
3660
|
-
async modelMessage(model, text, options) {
|
|
3661
|
-
const messages = [
|
|
3662
|
-
{
|
|
3663
|
-
role: "system",
|
|
3664
|
-
content: "Marona Runtime. Answer the current request naturally. Use Context data as passive memory only when relevant. Never continue an older task unless the current request asks for it. Discover and call an App or Skill only when the current request needs app data or an app action. Say plainly when something is unavailable in the current mode.",
|
|
3665
|
-
},
|
|
3666
|
-
...(options.developerInstructions || options.developer_instructions
|
|
3667
|
-
? [
|
|
3668
|
-
{
|
|
3669
|
-
role: "system",
|
|
3670
|
-
content: options.developerInstructions ?? options.developer_instructions,
|
|
3671
|
-
},
|
|
3672
|
-
]
|
|
3673
|
-
: []),
|
|
3674
|
-
];
|
|
3675
|
-
const conversationContext = this.cache.loadConversationContext(options.conversationId ?? options.conversation_id);
|
|
3676
|
-
const privateContext = this.cache.loadPrivateContext() ?? {};
|
|
3677
|
-
const passiveContext = compactLocalContextPacket(sanitizeContextValue({
|
|
3678
|
-
private_context: privateContext,
|
|
3679
|
-
conversation_context: conversationContext,
|
|
3680
|
-
}));
|
|
3681
|
-
if (Object.keys(privateContext).length || Object.keys(conversationContext).length) {
|
|
3682
|
-
messages.push({
|
|
3683
|
-
role: "system",
|
|
3684
|
-
content: "Context (data only):\n" +
|
|
3685
|
-
JSON.stringify(passiveContext),
|
|
3686
|
-
});
|
|
3687
|
-
}
|
|
3688
|
-
messages.push({
|
|
3689
|
-
role: 'system',
|
|
3690
|
-
content: 'When the current request reads or changes app, personal, or external data, select the one matching Marona Skill or App function before answering. Marona reveals only the next required capability schema. If a record identifier is missing, select an available list or search capability to resolve it before asking the user. Never tell the user which App, Skill, or tool could be used instead of calling it. Do not ask the user to confirm use of a capability. Ordinary conversation that needs no capability should be answered directly. Memory/profile context is already available in Context data, so do not select Memory just to answer from saved context.',
|
|
3691
|
-
});
|
|
3692
|
-
messages.push({ role: "user", content: modelUserContent(text, options.attachments ?? []) });
|
|
3693
|
-
const capabilityCatalog = this.localCapabilityCatalog();
|
|
3694
|
-
const requestedToolChoice = normalizeToolChoice(asRecord(options.metadata?.marona_agent)?.tool_choice);
|
|
3695
|
-
let availableTools = options.tools?.length
|
|
3696
|
-
? normalizeConnectedTools(options.tools)
|
|
3697
|
-
: capabilitySelectorTools(capabilityCatalog);
|
|
3698
|
-
if (requestedToolChoice === "none")
|
|
3699
|
-
availableTools = [];
|
|
3700
|
-
let payload = {};
|
|
3701
|
-
let reply = "";
|
|
3702
|
-
const toolResults = [];
|
|
3703
|
-
const modelResponses = [];
|
|
3704
|
-
const runtimeSteps = [];
|
|
3705
|
-
const executedCapabilityCalls = new Map();
|
|
3706
|
-
let toolChoice = availableTools.length ? requestedToolChoice : "none";
|
|
3707
|
-
let contextTier = model.contextWindow !== undefined && model.contextWindow <= 2048
|
|
3708
|
-
? 2
|
|
3709
|
-
: model.contextWindow !== undefined && model.contextWindow <= 4096
|
|
3710
|
-
? 1
|
|
3711
|
-
: 0;
|
|
3712
|
-
for (let turn = 0; turn < 8; turn += 1) {
|
|
3713
|
-
while (true) {
|
|
3714
|
-
try {
|
|
3715
|
-
payload = await callChatModel(model, compactMessagesForContext(messages, contextTier), compactToolsForContext(availableTools, contextTier), this.modelFetchImpl, toolChoice, this.models.executor(model.name), this.models.adapter(model.name));
|
|
3716
|
-
break;
|
|
3717
|
-
}
|
|
3718
|
-
catch (error) {
|
|
3719
|
-
if (!(error instanceof MaronaModelError) || contextTier >= 3 || !isContextLimitError(error))
|
|
3720
|
-
throw error;
|
|
3721
|
-
contextTier += 1;
|
|
3722
|
-
}
|
|
3723
|
-
}
|
|
3724
|
-
modelResponses.push(payload);
|
|
3725
|
-
reply = modelText(payload);
|
|
3726
|
-
const toolCalls = modelToolCalls(payload);
|
|
3727
|
-
if (!toolCalls.length || !availableTools.length)
|
|
3728
|
-
break;
|
|
3729
|
-
const roundResults = [];
|
|
3730
|
-
for (const call of toolCalls) {
|
|
3731
|
-
const selector = selectorForCall(call, availableTools);
|
|
3732
|
-
if (selector) {
|
|
3733
|
-
const selectorType = stringValue(selector.selector_type);
|
|
3734
|
-
const identifier = stringValue(selector.identifier);
|
|
3735
|
-
if (!selectorType || !identifier)
|
|
3736
|
-
continue;
|
|
3737
|
-
const discovery = this.discoverLocalCapabilities(discoveryCallForSelector(call, text, selectorType, identifier));
|
|
3738
|
-
availableTools = discovery.tools.length
|
|
3739
|
-
? discovery.tools
|
|
3740
|
-
: capabilityChoiceTools(discovery.result);
|
|
3741
|
-
toolChoice = availableTools.length ? "required" : "auto";
|
|
3742
|
-
runtimeSteps.push(discovery.result);
|
|
3743
|
-
roundResults.push(discovery.result);
|
|
3744
|
-
continue;
|
|
3745
|
-
}
|
|
3746
|
-
const callName = toolCallName(call);
|
|
3747
|
-
const callArguments = toolCallArguments(call);
|
|
3748
|
-
const callKey = `${callName}:${JSON.stringify(callArguments)}`;
|
|
3749
|
-
const previousResult = executedCapabilityCalls.get(callKey);
|
|
3750
|
-
if (previousResult) {
|
|
3751
|
-
const repeatedResult = {
|
|
3752
|
-
status: "completed",
|
|
3753
|
-
success: true,
|
|
3754
|
-
tool_name: callName,
|
|
3755
|
-
arguments: callArguments,
|
|
3756
|
-
result: {
|
|
3757
|
-
status: "already_executed",
|
|
3758
|
-
message: "This exact capability call already ran in the current request. Use its existing result to answer the user.",
|
|
3759
|
-
previous_result: toolResultForModel(previousResult, contextTier),
|
|
3760
|
-
},
|
|
3761
|
-
};
|
|
3762
|
-
runtimeSteps.push(repeatedResult);
|
|
3763
|
-
roundResults.push(repeatedResult);
|
|
3764
|
-
availableTools = [];
|
|
3765
|
-
toolChoice = "auto";
|
|
3766
|
-
continue;
|
|
3767
|
-
}
|
|
3768
|
-
const selectedTool = availableTools.find((tool) => stringValue(asRecord(tool.function)?.name) === callName);
|
|
3769
|
-
const localFunction = options.localFunctionTools?.find((value) => value.name === callName);
|
|
3770
|
-
const result = localFunction
|
|
3771
|
-
? {
|
|
3772
|
-
tool_call_id: call.id,
|
|
3773
|
-
tool_name: callName,
|
|
3774
|
-
arguments: callArguments,
|
|
3775
|
-
result: await localFunction.invoke(callArguments, {
|
|
3776
|
-
userId: options.userId ?? options.user_id,
|
|
3777
|
-
sessionId: options.conversationId ?? options.conversation_id ?? "default",
|
|
3778
|
-
permissions: new Set(Array.isArray(asRecord(options.metadata?.marona_tool_context)?.permissions)
|
|
3779
|
-
? (asRecord(options.metadata?.marona_tool_context)?.permissions).map(String)
|
|
3780
|
-
: []),
|
|
3781
|
-
approvedTools: new Set(Array.isArray(asRecord(options.metadata?.marona_tool_context)?.approved_tools)
|
|
3782
|
-
? (asRecord(options.metadata?.marona_tool_context)?.approved_tools).map(String)
|
|
3783
|
-
: []),
|
|
3784
|
-
metadata: {},
|
|
3785
|
-
}),
|
|
3786
|
-
}
|
|
3787
|
-
: selectedTool
|
|
3788
|
-
? {
|
|
3789
|
-
tool_call_id: call.id,
|
|
3790
|
-
app_slug: asRecord(selectedTool.marona)?.app_slug,
|
|
3791
|
-
tool_name: asRecord(selectedTool.marona)?.tool_name ?? callName,
|
|
3792
|
-
arguments: callArguments,
|
|
3793
|
-
result: await this.tools.execute(selectedTool, callArguments, {
|
|
3794
|
-
interfaceName: options.interfaceName ?? options.interface ?? "api",
|
|
3795
|
-
userId: options.userId ?? options.user_id,
|
|
3796
|
-
conversationId: options.conversationId ?? options.conversation_id,
|
|
3797
|
-
model: model.name,
|
|
3798
|
-
}),
|
|
3799
|
-
}
|
|
3800
|
-
: { tool_call_id: call.id, error: `Tool '${callName}' is not connected.` };
|
|
3801
|
-
executedCapabilityCalls.set(callKey, result);
|
|
3802
|
-
toolResults.push(result);
|
|
3803
|
-
runtimeSteps.push(result);
|
|
3804
|
-
availableTools = capabilitySelectorTools(capabilityCatalog);
|
|
3805
|
-
toolChoice = "auto";
|
|
3806
|
-
roundResults.push(result);
|
|
3807
|
-
}
|
|
3808
|
-
messages.push({
|
|
3809
|
-
role: "system",
|
|
3810
|
-
content: `Marona Runtime results from the previous model-selected calls:\n${JSON.stringify(roundResults.map((result) => toolResultForModel(result, contextTier)))}\n` +
|
|
3811
|
-
"Use these results to continue the current request. Preserve factual values, counts, currencies, and units exactly as returned. Call one of the currently available functions when more app data or action is required; otherwise answer the user directly.",
|
|
3812
|
-
});
|
|
3813
|
-
}
|
|
3814
|
-
if (toolResults.length && !reply) {
|
|
3815
|
-
reply = toolResultDisplayText(toolResults.at(-1));
|
|
3816
|
-
}
|
|
3817
|
-
const artifacts = toolResultArtifacts(toolResults);
|
|
3818
|
-
return {
|
|
3819
|
-
status: "completed",
|
|
3820
|
-
reply: reply || "Done.",
|
|
3821
|
-
text: reply || "Done.",
|
|
3822
|
-
output: runtimeOutput(reply || "Done.", artifacts),
|
|
3823
|
-
interfaceName: options.interfaceName ?? options.interface ?? "api",
|
|
3824
|
-
conversationId: options.conversationId ?? options.conversation_id,
|
|
3825
|
-
artifacts,
|
|
3826
|
-
needsPermission: false,
|
|
3827
|
-
needsServiceConnection: false,
|
|
3828
|
-
model: model.name,
|
|
3829
|
-
routing: {},
|
|
3830
|
-
agent: {},
|
|
3831
|
-
toolCall: toolResults.length ? { results: toolResults } : undefined,
|
|
3832
|
-
rawJson: {
|
|
3833
|
-
mode: this.mode,
|
|
3834
|
-
model: redactModel(model),
|
|
3835
|
-
metadata: options.metadata ?? {},
|
|
3836
|
-
available_tools: availableTools
|
|
3837
|
-
.filter((tool) => !asRecord(tool.marona)?.internal)
|
|
3838
|
-
.map((tool) => stringValue(asRecord(tool.function)?.name))
|
|
3839
|
-
.filter(Boolean),
|
|
3840
|
-
model_response: payload,
|
|
3841
|
-
model_responses: modelResponses,
|
|
3842
|
-
...(runtimeSteps.length ? { runtime_steps: runtimeSteps } : {}),
|
|
3843
|
-
},
|
|
3844
|
-
};
|
|
3845
|
-
}
|
|
3846
|
-
localCapabilityCatalog() {
|
|
3847
|
-
const payload = this.cache.loadSyncPayload() ?? {};
|
|
3848
|
-
const apps = Array.isArray(payload.available_agent_apps)
|
|
3849
|
-
? payload.available_agent_apps
|
|
3850
|
-
: Array.isArray(payload.apps)
|
|
3851
|
-
? payload.apps
|
|
3852
|
-
: Array.isArray(payload.items)
|
|
3853
|
-
? payload.items
|
|
3854
|
-
: [];
|
|
3855
|
-
const skills = Array.isArray(payload.available_skills) ? payload.available_skills : [];
|
|
3856
|
-
const managedCapabilities = new Set(skills.flatMap((raw) => {
|
|
3857
|
-
const skill = asRecord(raw);
|
|
3858
|
-
return skill ? skillManagedCapabilities(skill) : [];
|
|
3859
|
-
}));
|
|
3860
|
-
const supportedApps = apps
|
|
3861
|
-
.map(asRecord)
|
|
3862
|
-
.filter((app) => {
|
|
3863
|
-
if (!app || !appSupportsMode(app, this.mode))
|
|
3864
|
-
return false;
|
|
3865
|
-
const target = selectExecutionTarget(app, this.mode);
|
|
3866
|
-
return Boolean(target && !target.installRequired);
|
|
3867
|
-
});
|
|
3868
|
-
const supportedSlugs = new Set(supportedApps.map((app) => stringValue(app.slug)).filter((slug) => Boolean(slug)));
|
|
3869
|
-
return {
|
|
3870
|
-
apps: supportedApps.flatMap((app) => {
|
|
3871
|
-
const slug = stringValue(app.slug);
|
|
3872
|
-
const capabilityCount = listOfRecords(app.tools).filter((tool) => {
|
|
3873
|
-
const name = stringValue(tool.name);
|
|
3874
|
-
return Boolean(slug && name && !managedCapabilities.has(`${slug}.${name}`));
|
|
3875
|
-
}).length;
|
|
3876
|
-
return capabilityCount ? [{
|
|
3877
|
-
slug: app.slug,
|
|
3878
|
-
description: shortCatalogText(app.description ?? app.tagline),
|
|
3879
|
-
capability_count: capabilityCount,
|
|
3880
|
-
}] : [];
|
|
3881
|
-
}),
|
|
3882
|
-
skills: skills
|
|
3883
|
-
.map(asRecord)
|
|
3884
|
-
.filter((skill) => Boolean(skill) && skillSupportedBy(skill, supportedSlugs))
|
|
3885
|
-
.map((skill) => ({
|
|
3886
|
-
name: skill.name,
|
|
3887
|
-
description: shortCatalogText(skill.description),
|
|
3888
|
-
required_apps: skillRequiredApps(skill),
|
|
3889
|
-
})),
|
|
3890
|
-
};
|
|
3891
|
-
}
|
|
3892
|
-
discoverLocalCapabilities(call) {
|
|
3893
|
-
const args = toolCallArguments(call);
|
|
3894
|
-
const requestedApps = new Set(stringList(args.app_slugs));
|
|
3895
|
-
const requestedSkills = new Set(stringList(args.skill_names));
|
|
3896
|
-
const requestedCapabilities = new Set(stringList(args.capability_names));
|
|
3897
|
-
for (const capability of requestedCapabilities) {
|
|
3898
|
-
if (capability.includes('.'))
|
|
3899
|
-
requestedApps.add(capability.split('.')[0]);
|
|
3900
|
-
}
|
|
3901
|
-
const payload = this.cache.loadSyncPayload() ?? {};
|
|
3902
|
-
if (!requestedApps.size && !requestedSkills.size) {
|
|
3903
|
-
return {
|
|
3904
|
-
tools: [],
|
|
3905
|
-
result: {
|
|
3906
|
-
tool_call_id: call.id,
|
|
3907
|
-
result: {
|
|
3908
|
-
status: 'selection_required',
|
|
3909
|
-
catalog: this.localCapabilityCatalog(),
|
|
3910
|
-
instruction: 'Select the exact matching App and/or Skill identifiers from this catalog, then call marona__discover_capabilities again with them.',
|
|
3911
|
-
},
|
|
3912
|
-
},
|
|
3913
|
-
};
|
|
3914
|
-
}
|
|
3915
|
-
const rawSkills = Array.isArray(payload.available_skills) ? payload.available_skills : [];
|
|
3916
|
-
const selectedSkills = rawSkills.filter((rawSkill) => {
|
|
3917
|
-
const name = stringValue(asRecord(rawSkill)?.name);
|
|
3918
|
-
return Boolean(name && requestedSkills.has(name));
|
|
3919
|
-
});
|
|
3920
|
-
for (const rawSkill of selectedSkills) {
|
|
3921
|
-
const skill = asRecord(rawSkill);
|
|
3922
|
-
if (skill)
|
|
3923
|
-
skillRequiredApps(skill).forEach((slug) => requestedApps.add(slug));
|
|
3924
|
-
}
|
|
3925
|
-
const exactCapabilities = new Set(selectedSkills.flatMap((raw) => {
|
|
3926
|
-
const skill = asRecord(raw);
|
|
3927
|
-
return skill ? skillExactCapabilities(skill) : [];
|
|
3928
|
-
}));
|
|
3929
|
-
requestedCapabilities.forEach((capability) => exactCapabilities.add(capability));
|
|
3930
|
-
const managedCapabilities = new Set(rawSkills.flatMap((raw) => {
|
|
3931
|
-
const skill = asRecord(raw);
|
|
3932
|
-
return skill ? skillManagedCapabilities(skill) : [];
|
|
3933
|
-
}));
|
|
3934
|
-
const rawApps = Array.isArray(payload.available_agent_apps)
|
|
3935
|
-
? payload.available_agent_apps
|
|
3936
|
-
: Array.isArray(payload.apps)
|
|
3937
|
-
? payload.apps
|
|
3938
|
-
: Array.isArray(payload.items)
|
|
3939
|
-
? payload.items
|
|
3940
|
-
: [];
|
|
3941
|
-
const tools = [];
|
|
3942
|
-
const apps = [];
|
|
3943
|
-
const capabilityOptions = [];
|
|
3944
|
-
for (const rawApp of rawApps) {
|
|
3945
|
-
const app = asRecord(rawApp);
|
|
3946
|
-
const slug = stringValue(app?.slug);
|
|
3947
|
-
if (!app || !slug || !requestedApps.has(slug) || !appSupportsMode(app, this.mode))
|
|
3948
|
-
continue;
|
|
3949
|
-
const target = selectExecutionTarget(app, this.mode);
|
|
3950
|
-
if (!target || target.installRequired)
|
|
3951
|
-
continue;
|
|
3952
|
-
let appTools = toolsFromApp(app, stringValue(target.url), {
|
|
3953
|
-
executionMode: this.mode,
|
|
3954
|
-
executionTarget: asRecord(target.target),
|
|
3955
|
-
});
|
|
3956
|
-
if (exactCapabilities.size) {
|
|
3957
|
-
appTools = appTools.filter((tool) => {
|
|
3958
|
-
const name = toolFunctionName(tool)?.split('__').at(-1);
|
|
3959
|
-
return Boolean(name && exactCapabilities.has(`${slug}.${name}`));
|
|
3960
|
-
});
|
|
3961
|
-
}
|
|
3962
|
-
else {
|
|
3963
|
-
capabilityOptions.push(...appTools.flatMap((tool) => {
|
|
3964
|
-
const name = toolFunctionName(tool)?.split('__').at(-1);
|
|
3965
|
-
if (!name || managedCapabilities.has(`${slug}.${name}`))
|
|
3966
|
-
return [];
|
|
3967
|
-
return [{
|
|
3968
|
-
name: `${slug}.${name}`,
|
|
3969
|
-
description: shortCatalogText(asRecord(tool.function)?.description),
|
|
3970
|
-
}];
|
|
3971
|
-
}));
|
|
3972
|
-
appTools = [];
|
|
3973
|
-
}
|
|
3974
|
-
tools.push(...appTools);
|
|
3975
|
-
apps.push({
|
|
3976
|
-
slug,
|
|
3977
|
-
tools: appTools.map(toolFunctionName).filter(Boolean),
|
|
3978
|
-
installed: !target.installRequired,
|
|
3979
|
-
});
|
|
3980
|
-
}
|
|
3981
|
-
if (!tools.length && capabilityOptions.length) {
|
|
3982
|
-
return {
|
|
3983
|
-
tools: [],
|
|
3984
|
-
result: {
|
|
3985
|
-
tool_call_id: call.id,
|
|
3986
|
-
result: {
|
|
3987
|
-
status: 'capability_selection_required',
|
|
3988
|
-
capabilities: capabilityOptions,
|
|
3989
|
-
instruction: 'Select only the exact capability identifiers needed for the current request, then call marona__discover_capabilities again with capability_names.',
|
|
3990
|
-
},
|
|
3991
|
-
},
|
|
3992
|
-
};
|
|
3993
|
-
}
|
|
3994
|
-
const skills = compactLocalSkills(selectedSkills);
|
|
3995
|
-
return {
|
|
3996
|
-
tools,
|
|
3997
|
-
result: {
|
|
3998
|
-
tool_call_id: call.id,
|
|
3999
|
-
result: {
|
|
4000
|
-
status: 'completed',
|
|
4001
|
-
apps,
|
|
4002
|
-
skills,
|
|
4003
|
-
...(skills.length
|
|
4004
|
-
? {
|
|
4005
|
-
instruction: 'Skills are workflows, not callable tool names. Follow the selected workflow using the exact App tools returned by this discovery result.',
|
|
4006
|
-
}
|
|
4007
|
-
: {}),
|
|
4008
|
-
...(!apps.length && !skills.length
|
|
4009
|
-
? { message: 'No requested capability identifiers are available in this mode.' }
|
|
4010
|
-
: {}),
|
|
4011
|
-
},
|
|
4012
|
-
},
|
|
4013
|
-
};
|
|
4014
|
-
}
|
|
4015
3521
|
cacheTurn(text, response, options) {
|
|
4016
3522
|
this.cache.saveTurn({
|
|
4017
3523
|
conversationId: options.conversationId ?? options.conversation_id ?? response.conversationId,
|
|
@@ -4037,27 +3543,45 @@ export class Hub {
|
|
|
4037
3543
|
connect(options = {}) {
|
|
4038
3544
|
return this.hub.connect(options);
|
|
4039
3545
|
}
|
|
4040
|
-
|
|
4041
|
-
|
|
4042
|
-
models;
|
|
4043
|
-
constructor(models) {
|
|
4044
|
-
this.models = models;
|
|
3546
|
+
registerMcpServer(input) {
|
|
3547
|
+
return this.hub.registerMcpServer(input);
|
|
4045
3548
|
}
|
|
4046
|
-
|
|
4047
|
-
|
|
3549
|
+
listMcpServers() { return this.hub.listMcpServers(); }
|
|
3550
|
+
getMcpServer(serverId) { return this.hub.getMcpServer(serverId); }
|
|
3551
|
+
verifyMcpServer(serverId) { return this.hub.verifyMcpServer(serverId); }
|
|
3552
|
+
activateMcpServer(serverId, allowedTools = []) {
|
|
3553
|
+
return this.hub.activateMcpServer(serverId, allowedTools);
|
|
3554
|
+
}
|
|
3555
|
+
disableMcpServer(serverId) { return this.hub.disableMcpServer(serverId); }
|
|
3556
|
+
setMcpApiKey(serverId, input) {
|
|
3557
|
+
return this.hub.setMcpApiKey(serverId, input);
|
|
3558
|
+
}
|
|
3559
|
+
configureMcpOauthClient(serverId, input) {
|
|
3560
|
+
return this.hub.configureMcpOauthClient(serverId, input);
|
|
3561
|
+
}
|
|
3562
|
+
startMcpOauth(serverId, input = {}) {
|
|
3563
|
+
return this.hub.startMcpOauth(serverId, input);
|
|
3564
|
+
}
|
|
3565
|
+
executeMcpTool(serverId, input) {
|
|
3566
|
+
return this.hub.executeMcpTool(serverId, input);
|
|
3567
|
+
}
|
|
3568
|
+
listMcpInvocations(limit = 50) { return this.hub.listMcpInvocations(limit); }
|
|
3569
|
+
listMcpRegistry(limit = 50, cursor) {
|
|
3570
|
+
return this.hub.listMcpRegistry(limit, cursor);
|
|
3571
|
+
}
|
|
3572
|
+
importMcpRegistry(input) {
|
|
3573
|
+
return this.hub.importMcpRegistry(input);
|
|
4048
3574
|
}
|
|
4049
3575
|
}
|
|
4050
3576
|
export class Marona {
|
|
4051
3577
|
hub;
|
|
4052
3578
|
responses;
|
|
4053
|
-
models;
|
|
4054
3579
|
skills;
|
|
4055
3580
|
runtime;
|
|
4056
3581
|
constructor(options = {}) {
|
|
4057
3582
|
this.runtime = new RuntimeEngine(options);
|
|
4058
3583
|
this.hub = new Hub(this.runtime.hub);
|
|
4059
3584
|
this.responses = new ResponsesClient(this.runtime);
|
|
4060
|
-
this.models = new Models(this.runtime.models);
|
|
4061
3585
|
this.skills = this.runtime.skills;
|
|
4062
3586
|
activeRuntime = this.runtime;
|
|
4063
3587
|
}
|
|
@@ -4071,6 +3595,33 @@ function parseRuntimeMessageResponse(payload) {
|
|
|
4071
3595
|
if (serviceConnection && authorizationUrl && !artifacts.some((artifact) => artifact.url === authorizationUrl)) {
|
|
4072
3596
|
artifacts.push(serviceConnectionArtifact(serviceConnection));
|
|
4073
3597
|
}
|
|
3598
|
+
const rawRouting = asRecord(payload.routing) ?? {};
|
|
3599
|
+
const routing = omitEmpty({
|
|
3600
|
+
requested_model: rawRouting.requested_model,
|
|
3601
|
+
selected_model: rawRouting.selected_model,
|
|
3602
|
+
strategy: rawRouting.strategy,
|
|
3603
|
+
fallback_used: rawRouting.fallback_used,
|
|
3604
|
+
});
|
|
3605
|
+
const rawJson = omitEmpty({
|
|
3606
|
+
status: payload.status,
|
|
3607
|
+
reply: payload.reply,
|
|
3608
|
+
output: payload.output,
|
|
3609
|
+
interface: payload.interface,
|
|
3610
|
+
conversation_id: payload.conversation_id,
|
|
3611
|
+
ui: payload.ui,
|
|
3612
|
+
artifacts: payload.artifacts,
|
|
3613
|
+
selected_app: payload.selected_app,
|
|
3614
|
+
selected_tool: payload.selected_tool,
|
|
3615
|
+
needs_permission: payload.needs_permission,
|
|
3616
|
+
needs_service_connection: payload.needs_service_connection,
|
|
3617
|
+
permission_request: payload.permission_request,
|
|
3618
|
+
service_connection: payload.service_connection,
|
|
3619
|
+
tool_call: payload.tool_call,
|
|
3620
|
+
model: payload.model,
|
|
3621
|
+
routing,
|
|
3622
|
+
agent: payload.agent,
|
|
3623
|
+
usage: payload.usage,
|
|
3624
|
+
});
|
|
4074
3625
|
return {
|
|
4075
3626
|
status: stringValue(payload.status) || "unknown",
|
|
4076
3627
|
reply,
|
|
@@ -4089,9 +3640,9 @@ function parseRuntimeMessageResponse(payload) {
|
|
|
4089
3640
|
? parseServiceConnectionAction(serviceConnection)
|
|
4090
3641
|
: undefined,
|
|
4091
3642
|
toolCall: asRecord(payload.tool_call),
|
|
4092
|
-
rawJson
|
|
3643
|
+
rawJson,
|
|
4093
3644
|
model: stringValue(payload.model),
|
|
4094
|
-
routing
|
|
3645
|
+
routing,
|
|
4095
3646
|
agent: asRecord(payload.agent) ?? {},
|
|
4096
3647
|
};
|
|
4097
3648
|
}
|
|
@@ -4117,7 +3668,6 @@ function normalizeRouting(value) {
|
|
|
4117
3668
|
target_latency_ms: value.targetLatencyMs ?? value.target_latency_ms,
|
|
4118
3669
|
timeout_ms: value.timeoutMs ?? value.timeout_ms,
|
|
4119
3670
|
allowed_models: value.allowedModels ?? value.allowed_models,
|
|
4120
|
-
allowed_providers: value.allowedProviders ?? value.allowed_providers,
|
|
4121
3671
|
fallback: value.fallback,
|
|
4122
3672
|
});
|
|
4123
3673
|
}
|
|
@@ -4230,315 +3780,6 @@ function inferLocation(endpoint) {
|
|
|
4230
3780
|
}
|
|
4231
3781
|
return "remote";
|
|
4232
3782
|
}
|
|
4233
|
-
function candidateModelBases(endpoint) {
|
|
4234
|
-
const base = endpoint.replace(/\/+$/, "");
|
|
4235
|
-
return base.endsWith("/v1") ? [base] : [base, `${base}/v1`];
|
|
4236
|
-
}
|
|
4237
|
-
function modelHeaders(model) {
|
|
4238
|
-
return {
|
|
4239
|
-
"Content-Type": "application/json",
|
|
4240
|
-
...(model.apiKey ? { Authorization: `Bearer ${model.apiKey}` } : {}),
|
|
4241
|
-
};
|
|
4242
|
-
}
|
|
4243
|
-
function firstModelId(payload) {
|
|
4244
|
-
return modelIds(payload)[0];
|
|
4245
|
-
}
|
|
4246
|
-
function selectModelId(payload, requested) {
|
|
4247
|
-
const ids = modelIds(payload);
|
|
4248
|
-
const cleanRequested = requested?.trim();
|
|
4249
|
-
if (cleanRequested && (!ids.length || ids.includes(cleanRequested)))
|
|
4250
|
-
return cleanRequested;
|
|
4251
|
-
return ids[0] ?? cleanRequested;
|
|
4252
|
-
}
|
|
4253
|
-
function modelIds(payload) {
|
|
4254
|
-
const record = asRecord(payload);
|
|
4255
|
-
const data = Array.isArray(record?.data) ? record?.data : [];
|
|
4256
|
-
return data
|
|
4257
|
-
.map((item) => stringValue(asRecord(item)?.id)?.trim())
|
|
4258
|
-
.filter((item) => Boolean(item))
|
|
4259
|
-
.sort((a, b) => Number(a.includes(",")) - Number(b.includes(",")) || a.localeCompare(b));
|
|
4260
|
-
}
|
|
4261
|
-
function modelFromJson(payload) {
|
|
4262
|
-
return {
|
|
4263
|
-
name: stringValue(payload.name) ?? "",
|
|
4264
|
-
endpoint: stringValue(payload.endpoint) ?? "",
|
|
4265
|
-
provider: stringValue(payload.provider),
|
|
4266
|
-
model: stringValue(payload.model),
|
|
4267
|
-
protocol: stringValue(payload.protocol),
|
|
4268
|
-
features: Array.isArray(payload.features) ? payload.features.map(String) : [],
|
|
4269
|
-
location: (stringValue(payload.location) ?? inferLocation(stringValue(payload.endpoint) ?? "")),
|
|
4270
|
-
status: (stringValue(payload.status) ?? "unknown"),
|
|
4271
|
-
apiKey: stringValue(payload.api_key) ?? stringValue(payload.apiKey),
|
|
4272
|
-
metadata: asRecord(payload.metadata) ?? {},
|
|
4273
|
-
lastCheckedAt: stringValue(payload.last_checked_at) ?? stringValue(payload.lastCheckedAt),
|
|
4274
|
-
contextWindow: numberValue(payload.context_window) ?? numberValue(payload.contextWindow),
|
|
4275
|
-
maxOutputTokens: numberValue(payload.max_output_tokens) ?? numberValue(payload.maxOutputTokens),
|
|
4276
|
-
};
|
|
4277
|
-
}
|
|
4278
|
-
function redactModel(model) {
|
|
4279
|
-
const { apiKey: _apiKey, ...safe } = model;
|
|
4280
|
-
return safe;
|
|
4281
|
-
}
|
|
4282
|
-
function modelUserContent(text, attachments) {
|
|
4283
|
-
if (!attachments.length)
|
|
4284
|
-
return text;
|
|
4285
|
-
const content = [{ type: "text", text }];
|
|
4286
|
-
for (const input of attachments) {
|
|
4287
|
-
const attachment = input instanceof RuntimeAttachment ? input : new RuntimeAttachment(input);
|
|
4288
|
-
const source = attachment.dataBase64
|
|
4289
|
-
? `data:${attachment.mimeType};base64,${attachment.dataBase64}`
|
|
4290
|
-
: attachment.url;
|
|
4291
|
-
if (attachment.kind === "image" && source) {
|
|
4292
|
-
content.push({ type: "image_url", image_url: { url: source }, mime_type: attachment.mimeType });
|
|
4293
|
-
}
|
|
4294
|
-
else if (attachment.text) {
|
|
4295
|
-
content.push({ type: "text", text: `File ${attachment.filename}:\n${attachment.text}` });
|
|
4296
|
-
}
|
|
4297
|
-
else {
|
|
4298
|
-
content.push({
|
|
4299
|
-
type: "file",
|
|
4300
|
-
filename: attachment.filename,
|
|
4301
|
-
mime_type: attachment.mimeType,
|
|
4302
|
-
data: attachment.dataBase64,
|
|
4303
|
-
url: attachment.url,
|
|
4304
|
-
});
|
|
4305
|
-
}
|
|
4306
|
-
}
|
|
4307
|
-
return content;
|
|
4308
|
-
}
|
|
4309
|
-
async function callChatModel(model, messages, tools, fetchImpl, toolChoice = "auto", executor, adapter) {
|
|
4310
|
-
const request = {
|
|
4311
|
-
model: model.model ?? model.name,
|
|
4312
|
-
messages,
|
|
4313
|
-
...(modelOutputLimit(model) ? { max_tokens: modelOutputLimit(model) } : {}),
|
|
4314
|
-
...(tools.length
|
|
4315
|
-
? {
|
|
4316
|
-
tools: tools.map((tool) => asRecord(tool.function) ? { type: "function", function: tool.function } : tool),
|
|
4317
|
-
tool_choice: toolChoice,
|
|
4318
|
-
}
|
|
4319
|
-
: {}),
|
|
4320
|
-
};
|
|
4321
|
-
const handler = model.protocol === "local_executor" ? executor : model.protocol === "custom_adapter" ? adapter : undefined;
|
|
4322
|
-
if (handler) {
|
|
4323
|
-
const payload = await handler(request);
|
|
4324
|
-
const record = asRecord(payload);
|
|
4325
|
-
if (!record)
|
|
4326
|
-
throw new MaronaModelError(`Local model '${model.name}' returned a non-JSON response.`, { payload });
|
|
4327
|
-
return record;
|
|
4328
|
-
}
|
|
4329
|
-
if (model.protocol === "local_executor" || model.protocol === "custom_adapter") {
|
|
4330
|
-
throw new MaronaModelError(`Model '${model.name}' has no registered adapter.`);
|
|
4331
|
-
}
|
|
4332
|
-
if (model.protocol === "anthropic" || model.provider === "anthropic") {
|
|
4333
|
-
return callAnthropicModel(model, messages, tools, fetchImpl, toolChoice);
|
|
4334
|
-
}
|
|
4335
|
-
if (model.protocol === "gemini" || model.provider === "gemini") {
|
|
4336
|
-
return callGeminiModel(model, messages, tools, fetchImpl, toolChoice);
|
|
4337
|
-
}
|
|
4338
|
-
if (model.protocol && !["chat_completions", "custom_http"].includes(model.protocol)) {
|
|
4339
|
-
throw new MaronaModelError(`Model '${model.name}' does not support chat messages yet.`);
|
|
4340
|
-
}
|
|
4341
|
-
const response = await fetchImpl(`${model.endpoint.replace(/\/+$/, "")}/chat/completions`, {
|
|
4342
|
-
method: "POST",
|
|
4343
|
-
headers: modelHeaders(model),
|
|
4344
|
-
body: JSON.stringify(request),
|
|
4345
|
-
});
|
|
4346
|
-
const text = await response.text();
|
|
4347
|
-
const payload = parseMaybeJson(text);
|
|
4348
|
-
if (!response.ok) {
|
|
4349
|
-
throw new MaronaModelError(`Local model request failed with HTTP ${response.status}.`, {
|
|
4350
|
-
statusCode: response.status,
|
|
4351
|
-
payload,
|
|
4352
|
-
});
|
|
4353
|
-
}
|
|
4354
|
-
const record = asRecord(payload);
|
|
4355
|
-
if (!record)
|
|
4356
|
-
throw new MaronaModelError("Local model returned a non-JSON response.", { payload });
|
|
4357
|
-
return record;
|
|
4358
|
-
}
|
|
4359
|
-
async function callAnthropicModel(model, messages, tools, fetchImpl, toolChoice) {
|
|
4360
|
-
const system = messages
|
|
4361
|
-
.filter((message) => message.role === "system")
|
|
4362
|
-
.map((message) => contentText(message.content))
|
|
4363
|
-
.filter(Boolean)
|
|
4364
|
-
.join("\n\n");
|
|
4365
|
-
const anthropicMessages = messages
|
|
4366
|
-
.filter((message) => message.role !== "system" && (message.role === "user" || message.role === "assistant"))
|
|
4367
|
-
.map((message) => ({ role: message.role, content: anthropicContent(message.content) }));
|
|
4368
|
-
const response = await fetchImpl(`${model.endpoint.replace(/\/+$/, "")}/messages`, {
|
|
4369
|
-
method: "POST",
|
|
4370
|
-
headers: {
|
|
4371
|
-
"Content-Type": "application/json",
|
|
4372
|
-
"anthropic-version": "2023-06-01",
|
|
4373
|
-
...(model.apiKey ? { "x-api-key": model.apiKey } : {}),
|
|
4374
|
-
},
|
|
4375
|
-
body: JSON.stringify({
|
|
4376
|
-
model: model.model ?? model.name,
|
|
4377
|
-
system: system || undefined,
|
|
4378
|
-
messages: anthropicMessages,
|
|
4379
|
-
max_tokens: modelOutputLimit(model) ?? 1024,
|
|
4380
|
-
...(tools.length
|
|
4381
|
-
? {
|
|
4382
|
-
tools: tools.map((tool) => {
|
|
4383
|
-
const fn = asRecord(tool.function) ?? tool;
|
|
4384
|
-
return {
|
|
4385
|
-
name: fn.name,
|
|
4386
|
-
description: fn.description,
|
|
4387
|
-
input_schema: fn.parameters ?? { type: "object", properties: {} },
|
|
4388
|
-
};
|
|
4389
|
-
}),
|
|
4390
|
-
tool_choice: toolChoice === "required" ? { type: "any" } : { type: "auto" },
|
|
4391
|
-
}
|
|
4392
|
-
: {}),
|
|
4393
|
-
}),
|
|
4394
|
-
});
|
|
4395
|
-
const payload = parseMaybeJson(await response.text());
|
|
4396
|
-
if (!response.ok) {
|
|
4397
|
-
throw new MaronaModelError(`Anthropic model request failed with HTTP ${response.status}.`, {
|
|
4398
|
-
statusCode: response.status,
|
|
4399
|
-
payload,
|
|
4400
|
-
});
|
|
4401
|
-
}
|
|
4402
|
-
const record = asRecord(payload);
|
|
4403
|
-
if (!record)
|
|
4404
|
-
throw new MaronaModelError("Anthropic returned a non-JSON response.", { payload });
|
|
4405
|
-
const blocks = Array.isArray(record.content) ? record.content.map(asRecord).filter(Boolean) : [];
|
|
4406
|
-
const text = blocks.filter((block) => block.type === "text").map((block) => stringValue(block.text)).filter(Boolean).join("\n");
|
|
4407
|
-
const toolCalls = blocks.filter((block) => block.type === "tool_use").map((block) => ({
|
|
4408
|
-
id: block.id,
|
|
4409
|
-
type: "function",
|
|
4410
|
-
function: { name: block.name, arguments: JSON.stringify(asRecord(block.input) ?? {}) },
|
|
4411
|
-
}));
|
|
4412
|
-
return { choices: [{ message: { role: "assistant", content: text, ...(toolCalls.length ? { tool_calls: toolCalls } : {}) } }], raw_provider_response: record };
|
|
4413
|
-
}
|
|
4414
|
-
async function callGeminiModel(model, messages, tools, fetchImpl, toolChoice) {
|
|
4415
|
-
const system = messages
|
|
4416
|
-
.filter((message) => message.role === "system")
|
|
4417
|
-
.map((message) => contentText(message.content))
|
|
4418
|
-
.filter(Boolean)
|
|
4419
|
-
.join("\n\n");
|
|
4420
|
-
const contents = messages
|
|
4421
|
-
.filter((message) => message.role !== "system" && (message.role === "user" || message.role === "assistant"))
|
|
4422
|
-
.map((message) => ({ role: message.role === "assistant" ? "model" : "user", parts: geminiParts(message.content) }));
|
|
4423
|
-
const endpoint = `${model.endpoint.replace(/\/+$/, "")}/models/${encodeURIComponent(model.model ?? model.name)}:generateContent`;
|
|
4424
|
-
const url = new URL(endpoint);
|
|
4425
|
-
if (model.apiKey)
|
|
4426
|
-
url.searchParams.set("key", model.apiKey);
|
|
4427
|
-
const response = await fetchImpl(url.toString(), {
|
|
4428
|
-
method: "POST",
|
|
4429
|
-
headers: { "Content-Type": "application/json" },
|
|
4430
|
-
body: JSON.stringify({
|
|
4431
|
-
...(system ? { systemInstruction: { parts: [{ text: system }] } } : {}),
|
|
4432
|
-
contents,
|
|
4433
|
-
...(tools.length
|
|
4434
|
-
? {
|
|
4435
|
-
tools: [{ functionDeclarations: tools.map((tool) => {
|
|
4436
|
-
const fn = asRecord(tool.function) ?? tool;
|
|
4437
|
-
return { name: fn.name, description: fn.description, parameters: fn.parameters ?? { type: "object", properties: {} } };
|
|
4438
|
-
}) }],
|
|
4439
|
-
toolConfig: { functionCallingConfig: { mode: toolChoice === "required" ? "ANY" : "AUTO" } },
|
|
4440
|
-
}
|
|
4441
|
-
: {}),
|
|
4442
|
-
...(modelOutputLimit(model) ? { generationConfig: { maxOutputTokens: modelOutputLimit(model) } } : {}),
|
|
4443
|
-
}),
|
|
4444
|
-
});
|
|
4445
|
-
const payload = parseMaybeJson(await response.text());
|
|
4446
|
-
if (!response.ok) {
|
|
4447
|
-
throw new MaronaModelError(`Gemini model request failed with HTTP ${response.status}.`, {
|
|
4448
|
-
statusCode: response.status,
|
|
4449
|
-
payload,
|
|
4450
|
-
});
|
|
4451
|
-
}
|
|
4452
|
-
const record = asRecord(payload);
|
|
4453
|
-
if (!record)
|
|
4454
|
-
throw new MaronaModelError("Gemini returned a non-JSON response.", { payload });
|
|
4455
|
-
const candidates = Array.isArray(record.candidates) ? record.candidates : [];
|
|
4456
|
-
const content = asRecord(asRecord(candidates[0])?.content);
|
|
4457
|
-
const parts = Array.isArray(content?.parts) ? content.parts.map(asRecord).filter(Boolean) : [];
|
|
4458
|
-
const text = parts.map((part) => stringValue(part.text)).filter(Boolean).join("\n");
|
|
4459
|
-
const toolCalls = parts.map((part, index) => asRecord(part.functionCall) ? ({
|
|
4460
|
-
id: `gemini-call-${index}`,
|
|
4461
|
-
type: "function",
|
|
4462
|
-
function: {
|
|
4463
|
-
name: asRecord(part.functionCall)?.name,
|
|
4464
|
-
arguments: JSON.stringify(asRecord(asRecord(part.functionCall)?.args) ?? {}),
|
|
4465
|
-
},
|
|
4466
|
-
}) : undefined).filter(Boolean);
|
|
4467
|
-
return { choices: [{ message: { role: "assistant", content: text, ...(toolCalls.length ? { tool_calls: toolCalls } : {}) } }], raw_provider_response: record };
|
|
4468
|
-
}
|
|
4469
|
-
function anthropicContent(content) {
|
|
4470
|
-
if (typeof content === "string")
|
|
4471
|
-
return content;
|
|
4472
|
-
if (!Array.isArray(content))
|
|
4473
|
-
return String(content ?? "");
|
|
4474
|
-
return content.map((raw) => {
|
|
4475
|
-
const block = asRecord(raw);
|
|
4476
|
-
if (!block)
|
|
4477
|
-
return { type: "text", text: String(raw) };
|
|
4478
|
-
if (block.type === "image_url") {
|
|
4479
|
-
const image = asRecord(block.image_url);
|
|
4480
|
-
const data = dataUriParts(stringValue(image?.url) ?? "");
|
|
4481
|
-
if (data.dataBase64)
|
|
4482
|
-
return { type: "image", source: { type: "base64", media_type: data.mimeType, data: data.dataBase64 } };
|
|
4483
|
-
}
|
|
4484
|
-
if (block.type === "file") {
|
|
4485
|
-
const data = stringValue(block.data);
|
|
4486
|
-
if (data)
|
|
4487
|
-
return { type: "document", source: { type: "base64", media_type: block.mime_type, data }, title: block.filename };
|
|
4488
|
-
}
|
|
4489
|
-
return { type: "text", text: stringValue(block.text) ?? JSON.stringify(block) };
|
|
4490
|
-
});
|
|
4491
|
-
}
|
|
4492
|
-
function geminiParts(content) {
|
|
4493
|
-
if (typeof content === "string")
|
|
4494
|
-
return [{ text: content }];
|
|
4495
|
-
if (!Array.isArray(content))
|
|
4496
|
-
return [{ text: String(content ?? "") }];
|
|
4497
|
-
return content.map((raw) => {
|
|
4498
|
-
const block = asRecord(raw);
|
|
4499
|
-
if (!block)
|
|
4500
|
-
return { text: String(raw) };
|
|
4501
|
-
if (block.type === "image_url") {
|
|
4502
|
-
const url = stringValue(asRecord(block.image_url)?.url);
|
|
4503
|
-
const data = dataUriParts(url ?? "");
|
|
4504
|
-
if (data.dataBase64)
|
|
4505
|
-
return { inlineData: { mimeType: data.mimeType, data: data.dataBase64 } };
|
|
4506
|
-
if (url)
|
|
4507
|
-
return { fileData: { mimeType: block.mime_type ?? "image/*", fileUri: url } };
|
|
4508
|
-
}
|
|
4509
|
-
if (block.type === "file") {
|
|
4510
|
-
const data = stringValue(block.data);
|
|
4511
|
-
if (data)
|
|
4512
|
-
return { inlineData: { mimeType: block.mime_type, data } };
|
|
4513
|
-
const url = stringValue(block.url);
|
|
4514
|
-
if (url)
|
|
4515
|
-
return { fileData: { mimeType: block.mime_type, fileUri: url } };
|
|
4516
|
-
}
|
|
4517
|
-
return { text: stringValue(block.text) ?? JSON.stringify(block) };
|
|
4518
|
-
});
|
|
4519
|
-
}
|
|
4520
|
-
function modelOutputLimit(model) {
|
|
4521
|
-
if (model.contextWindow && model.contextWindow <= 2048) {
|
|
4522
|
-
return Math.min(model.maxOutputTokens ?? 192, 192);
|
|
4523
|
-
}
|
|
4524
|
-
if (model.contextWindow && model.contextWindow <= 4096) {
|
|
4525
|
-
return Math.min(model.maxOutputTokens ?? 384, 384);
|
|
4526
|
-
}
|
|
4527
|
-
return model.maxOutputTokens;
|
|
4528
|
-
}
|
|
4529
|
-
function modelText(payload) {
|
|
4530
|
-
const choices = Array.isArray(payload.choices) ? payload.choices : [];
|
|
4531
|
-
const first = asRecord(choices[0]);
|
|
4532
|
-
const message = asRecord(first?.message);
|
|
4533
|
-
return stringValue(message?.content) ?? "";
|
|
4534
|
-
}
|
|
4535
|
-
function modelToolCalls(payload) {
|
|
4536
|
-
const choices = Array.isArray(payload.choices) ? payload.choices : [];
|
|
4537
|
-
const first = asRecord(choices[0]);
|
|
4538
|
-
const message = asRecord(first?.message);
|
|
4539
|
-
const calls = Array.isArray(message?.tool_calls) ? message.tool_calls : [];
|
|
4540
|
-
return calls.map(asRecord).filter(Boolean);
|
|
4541
|
-
}
|
|
4542
3783
|
function toolResultForModel(result, contextTier = 0) {
|
|
4543
3784
|
const value = Object.prototype.hasOwnProperty.call(result, "result")
|
|
4544
3785
|
? result.result
|
|
@@ -5326,7 +4567,6 @@ function parseRuntimeAppsPage(payload) {
|
|
|
5326
4567
|
function parseRealtimeSessionCreated(payload) {
|
|
5327
4568
|
return {
|
|
5328
4569
|
status: stringValue(payload.status) || "",
|
|
5329
|
-
provider: stringValue(payload.provider) || "",
|
|
5330
4570
|
model: stringValue(payload.model) || "",
|
|
5331
4571
|
voice: stringValue(payload.voice) || "",
|
|
5332
4572
|
mode: stringValue(payload.mode) || "",
|
|
@@ -5336,7 +4576,15 @@ function parseRealtimeSessionCreated(payload) {
|
|
|
5336
4576
|
expiresAt: numberValue(payload.expires_at),
|
|
5337
4577
|
session: asRecord(payload.session) ?? {},
|
|
5338
4578
|
capabilities: asRecord(payload.capabilities) ?? {},
|
|
5339
|
-
rawJson: {
|
|
4579
|
+
rawJson: omitEmpty({
|
|
4580
|
+
status: payload.status,
|
|
4581
|
+
model: payload.model,
|
|
4582
|
+
voice: payload.voice,
|
|
4583
|
+
mode: payload.mode,
|
|
4584
|
+
conversation_id: payload.conversation_id,
|
|
4585
|
+
expires_at: payload.expires_at,
|
|
4586
|
+
capabilities: payload.capabilities,
|
|
4587
|
+
}),
|
|
5340
4588
|
};
|
|
5341
4589
|
}
|
|
5342
4590
|
function parseServiceConnectionAction(payload) {
|
|
@@ -5459,12 +4707,31 @@ function resolveMaronaApiKey(explicit) {
|
|
|
5459
4707
|
if (explicit !== undefined) {
|
|
5460
4708
|
const value = cleanString(explicit);
|
|
5461
4709
|
if (!value)
|
|
5462
|
-
throw new
|
|
4710
|
+
throw new MaronaApiKeyRequiredError(maronaApiKeyRequired, {
|
|
4711
|
+
code: "MARONA_API_KEY_REQUIRED",
|
|
4712
|
+
statusCode: 401,
|
|
4713
|
+
requiredAction: "CONFIGURE_MARONA_API_KEY",
|
|
4714
|
+
});
|
|
5463
4715
|
return value;
|
|
5464
4716
|
}
|
|
5465
4717
|
const value = environmentValue("MARONA_API_KEY");
|
|
5466
4718
|
if (!value)
|
|
5467
|
-
throw new
|
|
4719
|
+
throw new MaronaApiKeyRequiredError(maronaApiKeyRequired, {
|
|
4720
|
+
code: "MARONA_API_KEY_REQUIRED",
|
|
4721
|
+
statusCode: 401,
|
|
4722
|
+
requiredAction: "CONFIGURE_MARONA_API_KEY",
|
|
4723
|
+
});
|
|
4724
|
+
return value;
|
|
4725
|
+
}
|
|
4726
|
+
function validateModelNamespace(model) {
|
|
4727
|
+
const value = cleanString(model) ?? "marona/auto";
|
|
4728
|
+
if (!value.startsWith("marona/") || value === "marona/") {
|
|
4729
|
+
throw new InvalidModelNamespaceError("Models executed through Marona must use the marona/* namespace.", {
|
|
4730
|
+
code: "INVALID_MODEL_NAMESPACE",
|
|
4731
|
+
statusCode: 400,
|
|
4732
|
+
requiredAction: "USE_OR_REGISTER_A_MARONA_MODEL",
|
|
4733
|
+
});
|
|
4734
|
+
}
|
|
5468
4735
|
return value;
|
|
5469
4736
|
}
|
|
5470
4737
|
function maronaHeaders(headers, apiKey) {
|
|
@@ -5495,7 +4762,11 @@ function hasMaronaApiKey(headers) {
|
|
|
5495
4762
|
}
|
|
5496
4763
|
function requireMaronaApiKey(headers) {
|
|
5497
4764
|
if (!hasMaronaApiKey(headers)) {
|
|
5498
|
-
throw new
|
|
4765
|
+
throw new MaronaApiKeyRequiredError(maronaApiKeyRequired, {
|
|
4766
|
+
code: "MARONA_API_KEY_REQUIRED",
|
|
4767
|
+
statusCode: 401,
|
|
4768
|
+
requiredAction: "CONFIGURE_MARONA_API_KEY",
|
|
4769
|
+
});
|
|
5499
4770
|
}
|
|
5500
4771
|
}
|
|
5501
4772
|
function isPlainObject(value) {
|