marona 0.14.0 → 1.0.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 +10 -454
- package/README.md +47 -788
- package/dist/index.d.ts +56 -88
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +210 -1012
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
export const packageVersion = "0.
|
|
1
|
+
export const packageVersion = "1.0.0";
|
|
2
|
+
const maronaApiKeyRequired = "Marona Developer Key is required.\n\n" +
|
|
3
|
+
"Provide it through the SDK configuration or set the MARONA_API_KEY environment variable.\n\n" +
|
|
4
|
+
"Create/manage developer keys from the Marona Developer Portal.";
|
|
2
5
|
const discoverCapabilitiesTool = "marona__discover_capabilities";
|
|
3
6
|
const callCapabilityTool = "marona__call_capability";
|
|
4
7
|
const standardInterfaces = ["api", "web", "mobile_app", "desktop", "whatsapp"];
|
|
@@ -6,28 +9,6 @@ const interfaceNamePattern = "^[a-z][a-z0-9_-]{0,63}$";
|
|
|
6
9
|
const standardExecutionModes = ["online", "hybrid", "offline"];
|
|
7
10
|
const localExecutionTargetTypes = new Set(["python_package", "wasm", "static_cache", "builtin"]);
|
|
8
11
|
const remoteExecutionTargetTypes = new Set(["remote_mcp", "marona_hosted"]);
|
|
9
|
-
const providerDefaultEndpoints = {
|
|
10
|
-
openai: "https://api.openai.com/v1",
|
|
11
|
-
openrouter: "https://openrouter.ai/api/v1",
|
|
12
|
-
anthropic: "https://api.anthropic.com/v1",
|
|
13
|
-
gemini: "https://generativelanguage.googleapis.com/v1beta",
|
|
14
|
-
ollama: "http://127.0.0.1:11434/v1",
|
|
15
|
-
};
|
|
16
|
-
const providerKeyEnvironment = {
|
|
17
|
-
openai: "OPENAI_API_KEY",
|
|
18
|
-
openrouter: "OPENROUTER_API_KEY",
|
|
19
|
-
anthropic: "ANTHROPIC_API_KEY",
|
|
20
|
-
gemini: "GEMINI_API_KEY",
|
|
21
|
-
litellm: "LITELLM_API_KEY",
|
|
22
|
-
};
|
|
23
|
-
const providerEndpointEnvironment = {
|
|
24
|
-
openai: "OPENAI_API_BASE",
|
|
25
|
-
openrouter: "OPENROUTER_API_BASE",
|
|
26
|
-
anthropic: "ANTHROPIC_API_BASE",
|
|
27
|
-
gemini: "GEMINI_API_BASE",
|
|
28
|
-
ollama: "OLLAMA_API_BASE",
|
|
29
|
-
litellm: "LITELLM_API_BASE",
|
|
30
|
-
};
|
|
31
12
|
function normalizeExecutionModes(value) {
|
|
32
13
|
const rawModes = Array.isArray(value) ? value : ["online"];
|
|
33
14
|
const modes = [];
|
|
@@ -78,6 +59,95 @@ export class EdgeRuntimeError extends Error {
|
|
|
78
59
|
this.payload = options.payload;
|
|
79
60
|
}
|
|
80
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
|
+
}
|
|
81
151
|
export class MaronaOfflineError extends EdgeRuntimeError {
|
|
82
152
|
constructor(message, options = {}) {
|
|
83
153
|
super(message, options);
|
|
@@ -100,9 +170,7 @@ class MaronaCache {
|
|
|
100
170
|
syncPayload;
|
|
101
171
|
privateContext;
|
|
102
172
|
apps = new Map();
|
|
103
|
-
models = new Map();
|
|
104
173
|
conversationContexts = new Map();
|
|
105
|
-
defaultModelName;
|
|
106
174
|
loadSyncPayload() {
|
|
107
175
|
return this.syncPayload ? { ...this.syncPayload } : undefined;
|
|
108
176
|
}
|
|
@@ -140,15 +208,6 @@ class MaronaCache {
|
|
|
140
208
|
if (record && slug)
|
|
141
209
|
this.apps.set(slug, record);
|
|
142
210
|
}
|
|
143
|
-
const models = Array.isArray(payload.models) ? payload.models : [];
|
|
144
|
-
for (const model of models) {
|
|
145
|
-
const record = asRecord(model);
|
|
146
|
-
if (record)
|
|
147
|
-
this.saveModel(modelFromJson(record));
|
|
148
|
-
}
|
|
149
|
-
const defaultModel = stringValue(payload.default_model);
|
|
150
|
-
if (defaultModel && this.models.has(defaultModel))
|
|
151
|
-
this.defaultModelName = defaultModel;
|
|
152
211
|
const contexts = asRecord(payload.conversation_contexts);
|
|
153
212
|
if (contexts) {
|
|
154
213
|
for (const [key, value] of Object.entries(contexts)) {
|
|
@@ -165,8 +224,6 @@ class MaronaCache {
|
|
|
165
224
|
sync_payload: this.syncPayload,
|
|
166
225
|
private_context: this.privateContext,
|
|
167
226
|
apps: [...this.apps.values()].map((app) => ({ ...app })),
|
|
168
|
-
models: [...this.models.values()].map(redactModel),
|
|
169
|
-
default_model: this.defaultModelName,
|
|
170
227
|
conversation_contexts: Object.fromEntries(this.conversationContexts.entries()),
|
|
171
228
|
});
|
|
172
229
|
}
|
|
@@ -176,11 +233,6 @@ class MaronaCache {
|
|
|
176
233
|
loadPrivateContext() {
|
|
177
234
|
return this.privateContext ? { ...this.privateContext } : undefined;
|
|
178
235
|
}
|
|
179
|
-
saveModel(model, options = {}) {
|
|
180
|
-
this.models.set(model.name, { ...model, features: [...model.features], metadata: { ...model.metadata } });
|
|
181
|
-
if (options.makeDefault || !this.defaultModelName)
|
|
182
|
-
this.defaultModelName = model.name;
|
|
183
|
-
}
|
|
184
236
|
loadConversationContext(conversationId) {
|
|
185
237
|
return { ...(this.conversationContexts.get(conversationKey(conversationId)) ?? {}) };
|
|
186
238
|
}
|
|
@@ -233,145 +285,11 @@ class MaronaCache {
|
|
|
233
285
|
}
|
|
234
286
|
return output;
|
|
235
287
|
}
|
|
236
|
-
getModel(name) {
|
|
237
|
-
const model = this.models.get(name);
|
|
238
|
-
return model ? { ...model, features: [...model.features], metadata: { ...model.metadata } } : undefined;
|
|
239
|
-
}
|
|
240
|
-
listModels() {
|
|
241
|
-
return [...this.models.values()].map((model) => ({
|
|
242
|
-
...model,
|
|
243
|
-
features: [...model.features],
|
|
244
|
-
metadata: { ...model.metadata },
|
|
245
|
-
}));
|
|
246
|
-
}
|
|
247
|
-
removeModel(name) {
|
|
248
|
-
this.models.delete(name);
|
|
249
|
-
if (this.defaultModelName === name)
|
|
250
|
-
this.defaultModelName = undefined;
|
|
251
|
-
}
|
|
252
|
-
useModel(name) {
|
|
253
|
-
const model = this.getModel(name);
|
|
254
|
-
if (!model)
|
|
255
|
-
throw new MaronaModelError(`Model '${name}' is not registered.`);
|
|
256
|
-
this.defaultModelName = name;
|
|
257
|
-
return model;
|
|
258
|
-
}
|
|
259
|
-
defaultModel() {
|
|
260
|
-
if (this.defaultModelName)
|
|
261
|
-
return this.getModel(this.defaultModelName);
|
|
262
|
-
const first = this.models.values().next();
|
|
263
|
-
return first.done ? undefined : this.getModel(first.value.name);
|
|
264
|
-
}
|
|
265
288
|
clear() {
|
|
266
289
|
this.syncPayload = undefined;
|
|
267
290
|
this.privateContext = undefined;
|
|
268
291
|
this.apps.clear();
|
|
269
|
-
this.models.clear();
|
|
270
292
|
this.conversationContexts.clear();
|
|
271
|
-
this.defaultModelName = undefined;
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
class ModelManager {
|
|
275
|
-
cache;
|
|
276
|
-
fetchImpl;
|
|
277
|
-
executors = new Map();
|
|
278
|
-
adapters = new Map();
|
|
279
|
-
constructor(cache, fetchImpl) {
|
|
280
|
-
this.cache = cache;
|
|
281
|
-
this.fetchImpl = fetchImpl;
|
|
282
|
-
}
|
|
283
|
-
async register(input) {
|
|
284
|
-
if (!input.name.trim())
|
|
285
|
-
throw new MaronaModelError("Model name is required.");
|
|
286
|
-
const name = input.name.trim();
|
|
287
|
-
const endpoint = input.executor
|
|
288
|
-
? `local://${name}`
|
|
289
|
-
: input.adapter
|
|
290
|
-
? (input.endpoint ?? `adapter://${name}`).replace(/\/+$/, "")
|
|
291
|
-
: (input.endpoint ?? "").replace(/\/+$/, "");
|
|
292
|
-
if (!endpoint)
|
|
293
|
-
throw new MaronaModelError("Model endpoint or executor is required.");
|
|
294
|
-
const record = {
|
|
295
|
-
name,
|
|
296
|
-
endpoint,
|
|
297
|
-
provider: cleanString(input.provider)?.toLowerCase(),
|
|
298
|
-
model: input.model,
|
|
299
|
-
protocol: input.executor ? "local_executor" : input.adapter ? "custom_adapter" : input.protocol,
|
|
300
|
-
features: input.executor || input.adapter
|
|
301
|
-
? [...new Set([...(input.features ?? []), "text", "tool_calling", "streaming"])]
|
|
302
|
-
: input.features ?? [],
|
|
303
|
-
location: input.executor ? "local" : inferLocation(endpoint),
|
|
304
|
-
status: input.executor || input.adapter ? "available" : "registered",
|
|
305
|
-
apiKey: input.apiKey,
|
|
306
|
-
metadata: input.metadata ?? {},
|
|
307
|
-
lastCheckedAt: input.executor || input.adapter ? new Date().toISOString() : undefined,
|
|
308
|
-
contextWindow: input.contextWindow,
|
|
309
|
-
maxOutputTokens: input.maxOutputTokens,
|
|
310
|
-
};
|
|
311
|
-
if (input.executor)
|
|
312
|
-
this.executors.set(name, input.executor);
|
|
313
|
-
if (input.adapter)
|
|
314
|
-
this.adapters.set(name, input.adapter);
|
|
315
|
-
const detected = input.executor || input.adapter ? record : await this.detect(record);
|
|
316
|
-
this.cache.saveModel(detected, { makeDefault: input.makeDefault ?? false });
|
|
317
|
-
return detected;
|
|
318
|
-
}
|
|
319
|
-
get(name) {
|
|
320
|
-
return this.cache.getModel(name);
|
|
321
|
-
}
|
|
322
|
-
executor(name) {
|
|
323
|
-
return this.executors.get(name);
|
|
324
|
-
}
|
|
325
|
-
adapter(name) {
|
|
326
|
-
return this.adapters.get(name);
|
|
327
|
-
}
|
|
328
|
-
list() {
|
|
329
|
-
return this.cache.listModels();
|
|
330
|
-
}
|
|
331
|
-
remove(name) {
|
|
332
|
-
this.cache.removeModel(name);
|
|
333
|
-
}
|
|
334
|
-
async inspect(name) {
|
|
335
|
-
const model = this.cache.getModel(name);
|
|
336
|
-
if (!model)
|
|
337
|
-
throw new MaronaModelError(`Model '${name}' is not registered.`);
|
|
338
|
-
const detected = await this.detect(model);
|
|
339
|
-
this.cache.saveModel(detected);
|
|
340
|
-
return detected;
|
|
341
|
-
}
|
|
342
|
-
default() {
|
|
343
|
-
return this.cache.defaultModel();
|
|
344
|
-
}
|
|
345
|
-
async detect(record) {
|
|
346
|
-
for (const base of candidateModelBases(record.endpoint)) {
|
|
347
|
-
try {
|
|
348
|
-
const response = await this.fetchImpl(`${base}/models`, {
|
|
349
|
-
headers: modelHeaders(record),
|
|
350
|
-
});
|
|
351
|
-
if (response.ok) {
|
|
352
|
-
const payload = await response.json();
|
|
353
|
-
const modelId = selectModelId(payload, record.model);
|
|
354
|
-
return {
|
|
355
|
-
...record,
|
|
356
|
-
endpoint: base,
|
|
357
|
-
model: modelId,
|
|
358
|
-
protocol: record.protocol ?? "chat_completions",
|
|
359
|
-
features: [...new Set([...(record.features ?? []), "text", "streaming"])],
|
|
360
|
-
status: "available",
|
|
361
|
-
lastCheckedAt: new Date().toISOString(),
|
|
362
|
-
};
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
catch {
|
|
366
|
-
continue;
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
return {
|
|
370
|
-
...record,
|
|
371
|
-
protocol: record.protocol ?? "custom_http",
|
|
372
|
-
status: "unverified",
|
|
373
|
-
lastCheckedAt: new Date().toISOString(),
|
|
374
|
-
};
|
|
375
293
|
}
|
|
376
294
|
}
|
|
377
295
|
function neutralGatewayTools() {
|
|
@@ -924,7 +842,7 @@ export class Agent {
|
|
|
924
842
|
constructor(options) {
|
|
925
843
|
this.name = options.name.trim();
|
|
926
844
|
this.description = cleanString(options.description);
|
|
927
|
-
this.model = (options.model
|
|
845
|
+
this.model = validateModelNamespace(options.model);
|
|
928
846
|
this.instructions = typeof options.instructions === "function"
|
|
929
847
|
? options.instructions
|
|
930
848
|
: (options.instructions ?? "").trim();
|
|
@@ -1160,7 +1078,6 @@ export class Runner {
|
|
|
1160
1078
|
}
|
|
1161
1079
|
}
|
|
1162
1080
|
export class RealtimeSession {
|
|
1163
|
-
provider;
|
|
1164
1081
|
model;
|
|
1165
1082
|
conversationId;
|
|
1166
1083
|
descriptor;
|
|
@@ -1180,7 +1097,6 @@ export class RealtimeSession {
|
|
|
1180
1097
|
this.agent = agent;
|
|
1181
1098
|
this.userId = cleanString(options.userId);
|
|
1182
1099
|
this.sessionId = cleanString(options.sessionId) ?? "default";
|
|
1183
|
-
this.provider = descriptor.provider;
|
|
1184
1100
|
this.model = descriptor.model;
|
|
1185
1101
|
this.conversationId = descriptor.conversationId;
|
|
1186
1102
|
this.selectorMap = asRecord(descriptor.capabilities.selector_map) ?? {};
|
|
@@ -1463,7 +1379,7 @@ export class RealtimeRunner {
|
|
|
1463
1379
|
}
|
|
1464
1380
|
async function openRealtimeSocket(descriptor) {
|
|
1465
1381
|
if (!descriptor.clientSecret) {
|
|
1466
|
-
throw new EdgeRuntimeError("
|
|
1382
|
+
throw new EdgeRuntimeError("Marona Runtime did not return a realtime session token.");
|
|
1467
1383
|
}
|
|
1468
1384
|
let lastError;
|
|
1469
1385
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
@@ -1483,7 +1399,7 @@ async function openRealtimeSocketAttempt(descriptor) {
|
|
|
1483
1399
|
const Socket = globalThis.WebSocket ?? (await import("ws")).default;
|
|
1484
1400
|
const socket = new Socket(descriptor.endpoint, [
|
|
1485
1401
|
"realtime",
|
|
1486
|
-
`
|
|
1402
|
+
`marona-bearer.${descriptor.clientSecret}`,
|
|
1487
1403
|
]);
|
|
1488
1404
|
await new Promise((resolve, reject) => {
|
|
1489
1405
|
const timer = setTimeout(() => {
|
|
@@ -1959,7 +1875,7 @@ function responsesContext(options, metadata) {
|
|
|
1959
1875
|
metadata: {
|
|
1960
1876
|
...metadata,
|
|
1961
1877
|
_marona: {
|
|
1962
|
-
model: options.model ?? "marona/
|
|
1878
|
+
model: options.model ?? "marona/auto",
|
|
1963
1879
|
framework: "marona",
|
|
1964
1880
|
runtime: "responses",
|
|
1965
1881
|
},
|
|
@@ -2274,10 +2190,7 @@ class HubClient {
|
|
|
2274
2190
|
const text = await response.text();
|
|
2275
2191
|
const payload = parseMaybeJson(text);
|
|
2276
2192
|
if (!response.ok) {
|
|
2277
|
-
throw
|
|
2278
|
-
statusCode: response.status,
|
|
2279
|
-
payload,
|
|
2280
|
-
});
|
|
2193
|
+
throw maronaError(payload, response.status, "Marona Hub could not complete the request.");
|
|
2281
2194
|
}
|
|
2282
2195
|
return payload;
|
|
2283
2196
|
}
|
|
@@ -2966,7 +2879,7 @@ class RuntimeTransport {
|
|
|
2966
2879
|
signal: AbortSignal.timeout(this.timeoutMs),
|
|
2967
2880
|
});
|
|
2968
2881
|
if (!response.ok) {
|
|
2969
|
-
throw
|
|
2882
|
+
throw maronaError(parseMaybeJson(await response.text()), response.status, "Marona Runtime could not start the stream.");
|
|
2970
2883
|
}
|
|
2971
2884
|
if (!response.body) {
|
|
2972
2885
|
throw new EdgeRuntimeError("Edge runtime returned an empty event stream.");
|
|
@@ -2984,6 +2897,8 @@ class RuntimeTransport {
|
|
|
2984
2897
|
if (!line.startsWith("data:"))
|
|
2985
2898
|
continue;
|
|
2986
2899
|
const event = asRecord(parseMaybeJson(line.slice(5).trim()));
|
|
2900
|
+
if (event?.error)
|
|
2901
|
+
throw maronaError(event, undefined, "Marona Runtime stream failed.");
|
|
2987
2902
|
if (event)
|
|
2988
2903
|
yield event;
|
|
2989
2904
|
}
|
|
@@ -2992,6 +2907,8 @@ class RuntimeTransport {
|
|
|
2992
2907
|
}
|
|
2993
2908
|
if (buffer.startsWith("data:")) {
|
|
2994
2909
|
const event = asRecord(parseMaybeJson(buffer.slice(5).trim()));
|
|
2910
|
+
if (event?.error)
|
|
2911
|
+
throw maronaError(event, undefined, "Marona Runtime stream failed.");
|
|
2995
2912
|
if (event)
|
|
2996
2913
|
yield event;
|
|
2997
2914
|
}
|
|
@@ -3113,10 +3030,7 @@ class RuntimeTransport {
|
|
|
3113
3030
|
});
|
|
3114
3031
|
const text = await response.text();
|
|
3115
3032
|
if (!response.ok) {
|
|
3116
|
-
throw
|
|
3117
|
-
statusCode: response.status,
|
|
3118
|
-
payload: parseMaybeJson(text),
|
|
3119
|
-
});
|
|
3033
|
+
throw maronaError(parseMaybeJson(text), response.status, "Marona Runtime could not complete the request.");
|
|
3120
3034
|
}
|
|
3121
3035
|
return text;
|
|
3122
3036
|
}
|
|
@@ -3273,7 +3187,7 @@ class ResponsesClient {
|
|
|
3273
3187
|
for (let round = 0; round < 8; round += 1) {
|
|
3274
3188
|
const response = await this.runtime.client({
|
|
3275
3189
|
...runtimeOptions,
|
|
3276
|
-
model: options.model ?? "marona/
|
|
3190
|
+
model: options.model ?? "marona/auto",
|
|
3277
3191
|
metadata: {
|
|
3278
3192
|
...metadata,
|
|
3279
3193
|
...(results.length ? { marona_function_tool_results: results } : {}),
|
|
@@ -3369,7 +3283,7 @@ class ResponsesClient {
|
|
|
3369
3283
|
let response;
|
|
3370
3284
|
for await (const event of this.runtime.clientStream({
|
|
3371
3285
|
...options,
|
|
3372
|
-
model: options.model ?? "marona/
|
|
3286
|
+
model: options.model ?? "marona/auto",
|
|
3373
3287
|
metadata: {
|
|
3374
3288
|
...metadata,
|
|
3375
3289
|
...(results.length ? { marona_function_tool_results: results } : {}),
|
|
@@ -3428,46 +3342,42 @@ class ResponsesClient {
|
|
|
3428
3342
|
class RuntimeEngine extends RuntimeTransport {
|
|
3429
3343
|
hub;
|
|
3430
3344
|
cache;
|
|
3431
|
-
models;
|
|
3432
3345
|
skills;
|
|
3433
3346
|
tools;
|
|
3434
3347
|
responses;
|
|
3435
3348
|
mode;
|
|
3436
|
-
modelFetchImpl;
|
|
3437
3349
|
developerInstructions;
|
|
3438
|
-
defaultModelRoute;
|
|
3439
|
-
providerCredentials;
|
|
3440
|
-
providerEndpoints;
|
|
3441
|
-
maronaAccessVerified = false;
|
|
3442
3350
|
constructor(options = {}) {
|
|
3351
|
+
const developerKey = resolveMaronaApiKey(options.apiKey);
|
|
3352
|
+
const authenticatedHeaders = maronaHeaders(options.headers, developerKey);
|
|
3353
|
+
const authenticatedOptions = {
|
|
3354
|
+
...options,
|
|
3355
|
+
apiKey: developerKey,
|
|
3356
|
+
headers: authenticatedHeaders,
|
|
3357
|
+
};
|
|
3443
3358
|
const mode = options.mode ?? "online";
|
|
3444
3359
|
if (!["online", "offline", "hybrid"].includes(mode)) {
|
|
3445
3360
|
throw new EdgeRuntimeError("mode must be one of: online, offline, hybrid");
|
|
3446
3361
|
}
|
|
3447
|
-
super(options.baseUrl ?? "https://edge.marona.ai",
|
|
3362
|
+
super(options.baseUrl ?? "https://edge.marona.ai", authenticatedOptions);
|
|
3448
3363
|
this.mode = mode;
|
|
3449
3364
|
this.cache = options.cache ?? new MaronaCache();
|
|
3450
3365
|
this.developerInstructions = undefined;
|
|
3451
|
-
this.
|
|
3452
|
-
this.providerCredentials = Object.fromEntries(Object.entries(options.providerCredentials ?? {}).map(([key, value]) => [key.toLowerCase(), value]));
|
|
3453
|
-
this.providerEndpoints = Object.fromEntries(Object.entries(options.providerEndpoints ?? {}).map(([key, value]) => [key.toLowerCase(), value.replace(/\/+$/, "")]));
|
|
3454
|
-
this.modelFetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
3455
|
-
this.models = new ModelManager(this.cache, this.modelFetchImpl);
|
|
3456
|
-
this.tools = new ToolExecutor(this.baseUrl, this.defaultHeaders, this.modelFetchImpl);
|
|
3366
|
+
this.tools = new ToolExecutor(this.baseUrl, this.defaultHeaders, options.fetchImpl ?? globalThis.fetch);
|
|
3457
3367
|
this.tools.runtime = this;
|
|
3458
3368
|
this.hub = new MaronaHubClient(options.hubUrl ?? "https://hub.marona.ai", {
|
|
3459
|
-
apiKey:
|
|
3369
|
+
apiKey: developerKey,
|
|
3460
3370
|
timeoutMs: options.timeoutMs,
|
|
3461
|
-
headers:
|
|
3371
|
+
headers: authenticatedHeaders,
|
|
3462
3372
|
fetchImpl: options.hubFetchImpl ?? options.fetchImpl,
|
|
3463
3373
|
mode,
|
|
3464
3374
|
cache: this.cache,
|
|
3465
3375
|
toolExecutor: this.tools,
|
|
3466
3376
|
});
|
|
3467
3377
|
this.skills = new SkillsClient(options.hubUrl ?? 'https://hub.marona.ai', {
|
|
3468
|
-
apiKey:
|
|
3378
|
+
apiKey: developerKey,
|
|
3469
3379
|
timeoutMs: options.timeoutMs,
|
|
3470
|
-
headers:
|
|
3380
|
+
headers: authenticatedHeaders,
|
|
3471
3381
|
fetchImpl: options.hubFetchImpl ?? options.fetchImpl,
|
|
3472
3382
|
});
|
|
3473
3383
|
this.responses = new ResponsesClient(this);
|
|
@@ -3493,120 +3403,20 @@ class RuntimeEngine extends RuntimeTransport {
|
|
|
3493
3403
|
return payload;
|
|
3494
3404
|
}
|
|
3495
3405
|
async message(text, options = {}) {
|
|
3496
|
-
const
|
|
3497
|
-
const
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
|
|
3501
|
-
|
|
3502
|
-
|
|
3503
|
-
|
|
3504
|
-
const messageOptions = { ...options, model: modelRoute, developerInstructions };
|
|
3505
|
-
if (this.mode === "offline" && model?.location !== "local") {
|
|
3506
|
-
throw new MaronaOfflineError(`Offline mode cannot use remote model '${modelRoute}'.`);
|
|
3507
|
-
}
|
|
3508
|
-
if (model && (this.mode === "online" || model.location === "local" || this.mode === "hybrid")) {
|
|
3509
|
-
try {
|
|
3510
|
-
const explicitlyRegistered = this.models.get(modelRoute) !== undefined;
|
|
3511
|
-
if (this.mode !== "offline"
|
|
3512
|
-
&& !(explicitlyRegistered && !hasMaronaApiKey(this.defaultHeaders))) {
|
|
3513
|
-
await this.ensureMaronaAccess();
|
|
3514
|
-
}
|
|
3515
|
-
const response = await this.modelMessage(model, text, messageOptions);
|
|
3516
|
-
this.cacheTurn(text, response, messageOptions);
|
|
3517
|
-
return response;
|
|
3518
|
-
}
|
|
3519
|
-
catch (error) {
|
|
3520
|
-
if (this.mode !== "hybrid")
|
|
3521
|
-
throw error;
|
|
3522
|
-
messageOptions.model = "marona/gpt-5.6";
|
|
3523
|
-
}
|
|
3524
|
-
}
|
|
3525
|
-
if (this.mode === "online") {
|
|
3526
|
-
const response = await super.message(text, {
|
|
3527
|
-
...messageOptions,
|
|
3528
|
-
metadata: { ...(options.metadata ?? {}), ...(options.tools ? { tools: options.tools } : {}) },
|
|
3529
|
-
});
|
|
3530
|
-
this.cacheTurn(text, response, messageOptions);
|
|
3531
|
-
return response;
|
|
3532
|
-
}
|
|
3533
|
-
if (this.mode === "offline") {
|
|
3534
|
-
throw new MaronaOfflineError("Offline mode requires a registered local model before calling message().");
|
|
3535
|
-
}
|
|
3536
|
-
const response = await super.message(text, {
|
|
3537
|
-
...messageOptions,
|
|
3406
|
+
const model = validateModelNamespace(options.model);
|
|
3407
|
+
const messageOptions = {
|
|
3408
|
+
...options,
|
|
3409
|
+
model,
|
|
3410
|
+
developerInstructions: combineText([
|
|
3411
|
+
this.developerInstructions,
|
|
3412
|
+
options.developerInstructions ?? options.developer_instructions,
|
|
3413
|
+
]),
|
|
3538
3414
|
metadata: { ...(options.metadata ?? {}), ...(options.tools ? { tools: options.tools } : {}) },
|
|
3539
|
-
}
|
|
3415
|
+
};
|
|
3416
|
+
const response = await super.message(text, messageOptions);
|
|
3540
3417
|
this.cacheTurn(text, response, messageOptions);
|
|
3541
3418
|
return response;
|
|
3542
3419
|
}
|
|
3543
|
-
async ensureMaronaAccess() {
|
|
3544
|
-
if (this.maronaAccessVerified)
|
|
3545
|
-
return;
|
|
3546
|
-
requireMaronaApiKey(this.defaultHeaders);
|
|
3547
|
-
await this.hub.billingSummary();
|
|
3548
|
-
this.maronaAccessVerified = true;
|
|
3549
|
-
}
|
|
3550
|
-
resolveModel(reference) {
|
|
3551
|
-
if (reference.startsWith("marona/"))
|
|
3552
|
-
return undefined;
|
|
3553
|
-
const registered = this.models.get(reference);
|
|
3554
|
-
if (registered)
|
|
3555
|
-
return registered;
|
|
3556
|
-
const slash = reference.indexOf("/");
|
|
3557
|
-
if (slash <= 0 || slash === reference.length - 1) {
|
|
3558
|
-
throw new MaronaModelError("Model names must use an explicit namespace such as 'marona/gpt-5.6' or 'openai/gpt-5.6'.");
|
|
3559
|
-
}
|
|
3560
|
-
const routeProvider = reference.slice(0, slash).toLowerCase();
|
|
3561
|
-
const provider = routeProvider === "google" ? "gemini" : routeProvider;
|
|
3562
|
-
const providerModel = reference.slice(slash + 1);
|
|
3563
|
-
if (provider === "marona")
|
|
3564
|
-
return undefined;
|
|
3565
|
-
if (provider === "local") {
|
|
3566
|
-
throw new MaronaModelError(`Local model '${reference}' must be registered with an executor.`);
|
|
3567
|
-
}
|
|
3568
|
-
if (!["openai", "openrouter", "anthropic", "gemini", "ollama", "litellm"].includes(provider)) {
|
|
3569
|
-
throw new MaronaModelError(`Custom model route '${reference}' must be registered first.`);
|
|
3570
|
-
}
|
|
3571
|
-
const endpoint = this.providerEndpoint(provider);
|
|
3572
|
-
const apiKey = this.providerKey(provider);
|
|
3573
|
-
if (["openai", "openrouter", "anthropic", "gemini"].includes(provider) && !apiKey) {
|
|
3574
|
-
throw new MaronaModelError(`${providerKeyEnvironment[provider]} is required for '${reference}'.`);
|
|
3575
|
-
}
|
|
3576
|
-
if (provider === "litellm" && !endpoint) {
|
|
3577
|
-
throw new MaronaModelError("LITELLM_API_BASE or a configured endpoint is required.");
|
|
3578
|
-
}
|
|
3579
|
-
return {
|
|
3580
|
-
name: reference,
|
|
3581
|
-
endpoint: endpoint ?? "",
|
|
3582
|
-
provider,
|
|
3583
|
-
model: providerModel,
|
|
3584
|
-
protocol: provider === "anthropic" ? "anthropic" : provider === "gemini" ? "gemini" : "chat_completions",
|
|
3585
|
-
features: ["text", "streaming", "native_tool_calling"],
|
|
3586
|
-
location: provider === "ollama" ? "local" : "remote",
|
|
3587
|
-
status: "available",
|
|
3588
|
-
apiKey,
|
|
3589
|
-
metadata: { route: reference },
|
|
3590
|
-
lastCheckedAt: new Date().toISOString(),
|
|
3591
|
-
};
|
|
3592
|
-
}
|
|
3593
|
-
providerKey(provider) {
|
|
3594
|
-
const configured = this.providerCredentials[provider];
|
|
3595
|
-
const value = typeof configured === "string" ? configured : configured?.apiKey;
|
|
3596
|
-
return cleanString(value) ?? environmentValue(providerKeyEnvironment[provider]);
|
|
3597
|
-
}
|
|
3598
|
-
providerEndpoint(provider) {
|
|
3599
|
-
const configured = this.providerCredentials[provider];
|
|
3600
|
-
let endpoint = this.providerEndpoints[provider]
|
|
3601
|
-
?? (typeof configured === "object" ? configured.endpoint ?? configured.baseUrl : undefined)
|
|
3602
|
-
?? environmentValue(providerEndpointEnvironment[provider])
|
|
3603
|
-
?? providerDefaultEndpoints[provider];
|
|
3604
|
-
endpoint = cleanString(endpoint)?.replace(/\/+$/, "");
|
|
3605
|
-
if (endpoint && ["openai", "openrouter", "ollama", "litellm"].includes(provider) && !endpoint.endsWith("/v1")) {
|
|
3606
|
-
endpoint = `${endpoint}/v1`;
|
|
3607
|
-
}
|
|
3608
|
-
return endpoint;
|
|
3609
|
-
}
|
|
3610
3420
|
async client(options) {
|
|
3611
3421
|
const { input, attachments, ...messageOptions } = options;
|
|
3612
3422
|
const normalized = runtimeMessageFromInput(input);
|
|
@@ -3622,17 +3432,7 @@ class RuntimeEngine extends RuntimeTransport {
|
|
|
3622
3432
|
async *clientStream(options) {
|
|
3623
3433
|
const { input, attachments, ...messageOptions } = options;
|
|
3624
3434
|
const normalized = runtimeMessageFromInput(input);
|
|
3625
|
-
const
|
|
3626
|
-
?? "marona/gpt-5.6";
|
|
3627
|
-
const model = this.resolveModel(modelRoute);
|
|
3628
|
-
if (model) {
|
|
3629
|
-
const response = await this.client(options);
|
|
3630
|
-
yield { type: "run.started" };
|
|
3631
|
-
if (response.reply)
|
|
3632
|
-
yield { type: "output_text.delta", delta: response.reply };
|
|
3633
|
-
yield { type: "run.completed", output: runtimeResponsePayload(response) };
|
|
3634
|
-
return;
|
|
3635
|
-
}
|
|
3435
|
+
const model = validateModelNamespace(messageOptions.model);
|
|
3636
3436
|
const developerInstructions = combineText([
|
|
3637
3437
|
normalized.developerInstructions,
|
|
3638
3438
|
this.developerInstructions,
|
|
@@ -3640,7 +3440,7 @@ class RuntimeEngine extends RuntimeTransport {
|
|
|
3640
3440
|
]);
|
|
3641
3441
|
for await (const event of super.streamMessage(normalized.text, {
|
|
3642
3442
|
...messageOptions,
|
|
3643
|
-
model
|
|
3443
|
+
model,
|
|
3644
3444
|
developerInstructions,
|
|
3645
3445
|
attachments: [...normalized.attachments, ...(attachments ?? [])],
|
|
3646
3446
|
metadata: {
|
|
@@ -3651,361 +3451,6 @@ class RuntimeEngine extends RuntimeTransport {
|
|
|
3651
3451
|
yield event;
|
|
3652
3452
|
}
|
|
3653
3453
|
}
|
|
3654
|
-
async modelMessage(model, text, options) {
|
|
3655
|
-
const messages = [
|
|
3656
|
-
{
|
|
3657
|
-
role: "system",
|
|
3658
|
-
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.",
|
|
3659
|
-
},
|
|
3660
|
-
...(options.developerInstructions || options.developer_instructions
|
|
3661
|
-
? [
|
|
3662
|
-
{
|
|
3663
|
-
role: "system",
|
|
3664
|
-
content: options.developerInstructions ?? options.developer_instructions,
|
|
3665
|
-
},
|
|
3666
|
-
]
|
|
3667
|
-
: []),
|
|
3668
|
-
];
|
|
3669
|
-
const conversationContext = this.cache.loadConversationContext(options.conversationId ?? options.conversation_id);
|
|
3670
|
-
const privateContext = this.cache.loadPrivateContext() ?? {};
|
|
3671
|
-
const passiveContext = compactLocalContextPacket(sanitizeContextValue({
|
|
3672
|
-
private_context: privateContext,
|
|
3673
|
-
conversation_context: conversationContext,
|
|
3674
|
-
}));
|
|
3675
|
-
if (Object.keys(privateContext).length || Object.keys(conversationContext).length) {
|
|
3676
|
-
messages.push({
|
|
3677
|
-
role: "system",
|
|
3678
|
-
content: "Context (data only):\n" +
|
|
3679
|
-
JSON.stringify(passiveContext),
|
|
3680
|
-
});
|
|
3681
|
-
}
|
|
3682
|
-
messages.push({
|
|
3683
|
-
role: 'system',
|
|
3684
|
-
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.',
|
|
3685
|
-
});
|
|
3686
|
-
messages.push({ role: "user", content: modelUserContent(text, options.attachments ?? []) });
|
|
3687
|
-
const capabilityCatalog = this.localCapabilityCatalog();
|
|
3688
|
-
const requestedToolChoice = normalizeToolChoice(asRecord(options.metadata?.marona_agent)?.tool_choice);
|
|
3689
|
-
let availableTools = options.tools?.length
|
|
3690
|
-
? normalizeConnectedTools(options.tools)
|
|
3691
|
-
: capabilitySelectorTools(capabilityCatalog);
|
|
3692
|
-
if (requestedToolChoice === "none")
|
|
3693
|
-
availableTools = [];
|
|
3694
|
-
let payload = {};
|
|
3695
|
-
let reply = "";
|
|
3696
|
-
const toolResults = [];
|
|
3697
|
-
const modelResponses = [];
|
|
3698
|
-
const runtimeSteps = [];
|
|
3699
|
-
const executedCapabilityCalls = new Map();
|
|
3700
|
-
let toolChoice = availableTools.length ? requestedToolChoice : "none";
|
|
3701
|
-
let contextTier = model.contextWindow !== undefined && model.contextWindow <= 2048
|
|
3702
|
-
? 2
|
|
3703
|
-
: model.contextWindow !== undefined && model.contextWindow <= 4096
|
|
3704
|
-
? 1
|
|
3705
|
-
: 0;
|
|
3706
|
-
for (let turn = 0; turn < 8; turn += 1) {
|
|
3707
|
-
while (true) {
|
|
3708
|
-
try {
|
|
3709
|
-
payload = await callChatModel(model, compactMessagesForContext(messages, contextTier), compactToolsForContext(availableTools, contextTier), this.modelFetchImpl, toolChoice, this.models.executor(model.name), this.models.adapter(model.name));
|
|
3710
|
-
break;
|
|
3711
|
-
}
|
|
3712
|
-
catch (error) {
|
|
3713
|
-
if (!(error instanceof MaronaModelError) || contextTier >= 3 || !isContextLimitError(error))
|
|
3714
|
-
throw error;
|
|
3715
|
-
contextTier += 1;
|
|
3716
|
-
}
|
|
3717
|
-
}
|
|
3718
|
-
modelResponses.push(payload);
|
|
3719
|
-
reply = modelText(payload);
|
|
3720
|
-
const toolCalls = modelToolCalls(payload);
|
|
3721
|
-
if (!toolCalls.length || !availableTools.length)
|
|
3722
|
-
break;
|
|
3723
|
-
const roundResults = [];
|
|
3724
|
-
for (const call of toolCalls) {
|
|
3725
|
-
const selector = selectorForCall(call, availableTools);
|
|
3726
|
-
if (selector) {
|
|
3727
|
-
const selectorType = stringValue(selector.selector_type);
|
|
3728
|
-
const identifier = stringValue(selector.identifier);
|
|
3729
|
-
if (!selectorType || !identifier)
|
|
3730
|
-
continue;
|
|
3731
|
-
const discovery = this.discoverLocalCapabilities(discoveryCallForSelector(call, text, selectorType, identifier));
|
|
3732
|
-
availableTools = discovery.tools.length
|
|
3733
|
-
? discovery.tools
|
|
3734
|
-
: capabilityChoiceTools(discovery.result);
|
|
3735
|
-
toolChoice = availableTools.length ? "required" : "auto";
|
|
3736
|
-
runtimeSteps.push(discovery.result);
|
|
3737
|
-
roundResults.push(discovery.result);
|
|
3738
|
-
continue;
|
|
3739
|
-
}
|
|
3740
|
-
const callName = toolCallName(call);
|
|
3741
|
-
const callArguments = toolCallArguments(call);
|
|
3742
|
-
const callKey = `${callName}:${JSON.stringify(callArguments)}`;
|
|
3743
|
-
const previousResult = executedCapabilityCalls.get(callKey);
|
|
3744
|
-
if (previousResult) {
|
|
3745
|
-
const repeatedResult = {
|
|
3746
|
-
status: "completed",
|
|
3747
|
-
success: true,
|
|
3748
|
-
tool_name: callName,
|
|
3749
|
-
arguments: callArguments,
|
|
3750
|
-
result: {
|
|
3751
|
-
status: "already_executed",
|
|
3752
|
-
message: "This exact capability call already ran in the current request. Use its existing result to answer the user.",
|
|
3753
|
-
previous_result: toolResultForModel(previousResult, contextTier),
|
|
3754
|
-
},
|
|
3755
|
-
};
|
|
3756
|
-
runtimeSteps.push(repeatedResult);
|
|
3757
|
-
roundResults.push(repeatedResult);
|
|
3758
|
-
availableTools = [];
|
|
3759
|
-
toolChoice = "auto";
|
|
3760
|
-
continue;
|
|
3761
|
-
}
|
|
3762
|
-
const selectedTool = availableTools.find((tool) => stringValue(asRecord(tool.function)?.name) === callName);
|
|
3763
|
-
const localFunction = options.localFunctionTools?.find((value) => value.name === callName);
|
|
3764
|
-
const result = localFunction
|
|
3765
|
-
? {
|
|
3766
|
-
tool_call_id: call.id,
|
|
3767
|
-
tool_name: callName,
|
|
3768
|
-
arguments: callArguments,
|
|
3769
|
-
result: await localFunction.invoke(callArguments, {
|
|
3770
|
-
userId: options.userId ?? options.user_id,
|
|
3771
|
-
sessionId: options.conversationId ?? options.conversation_id ?? "default",
|
|
3772
|
-
permissions: new Set(Array.isArray(asRecord(options.metadata?.marona_tool_context)?.permissions)
|
|
3773
|
-
? (asRecord(options.metadata?.marona_tool_context)?.permissions).map(String)
|
|
3774
|
-
: []),
|
|
3775
|
-
approvedTools: new Set(Array.isArray(asRecord(options.metadata?.marona_tool_context)?.approved_tools)
|
|
3776
|
-
? (asRecord(options.metadata?.marona_tool_context)?.approved_tools).map(String)
|
|
3777
|
-
: []),
|
|
3778
|
-
metadata: {},
|
|
3779
|
-
}),
|
|
3780
|
-
}
|
|
3781
|
-
: selectedTool
|
|
3782
|
-
? {
|
|
3783
|
-
tool_call_id: call.id,
|
|
3784
|
-
app_slug: asRecord(selectedTool.marona)?.app_slug,
|
|
3785
|
-
tool_name: asRecord(selectedTool.marona)?.tool_name ?? callName,
|
|
3786
|
-
arguments: callArguments,
|
|
3787
|
-
result: await this.tools.execute(selectedTool, callArguments, {
|
|
3788
|
-
interfaceName: options.interfaceName ?? options.interface ?? "api",
|
|
3789
|
-
userId: options.userId ?? options.user_id,
|
|
3790
|
-
conversationId: options.conversationId ?? options.conversation_id,
|
|
3791
|
-
model: model.name,
|
|
3792
|
-
}),
|
|
3793
|
-
}
|
|
3794
|
-
: { tool_call_id: call.id, error: `Tool '${callName}' is not connected.` };
|
|
3795
|
-
executedCapabilityCalls.set(callKey, result);
|
|
3796
|
-
toolResults.push(result);
|
|
3797
|
-
runtimeSteps.push(result);
|
|
3798
|
-
availableTools = capabilitySelectorTools(capabilityCatalog);
|
|
3799
|
-
toolChoice = "auto";
|
|
3800
|
-
roundResults.push(result);
|
|
3801
|
-
}
|
|
3802
|
-
messages.push({
|
|
3803
|
-
role: "system",
|
|
3804
|
-
content: `Marona Runtime results from the previous model-selected calls:\n${JSON.stringify(roundResults.map((result) => toolResultForModel(result, contextTier)))}\n` +
|
|
3805
|
-
"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.",
|
|
3806
|
-
});
|
|
3807
|
-
}
|
|
3808
|
-
if (toolResults.length && !reply) {
|
|
3809
|
-
reply = toolResultDisplayText(toolResults.at(-1));
|
|
3810
|
-
}
|
|
3811
|
-
const artifacts = toolResultArtifacts(toolResults);
|
|
3812
|
-
return {
|
|
3813
|
-
status: "completed",
|
|
3814
|
-
reply: reply || "Done.",
|
|
3815
|
-
text: reply || "Done.",
|
|
3816
|
-
output: runtimeOutput(reply || "Done.", artifacts),
|
|
3817
|
-
interfaceName: options.interfaceName ?? options.interface ?? "api",
|
|
3818
|
-
conversationId: options.conversationId ?? options.conversation_id,
|
|
3819
|
-
artifacts,
|
|
3820
|
-
needsPermission: false,
|
|
3821
|
-
needsServiceConnection: false,
|
|
3822
|
-
model: model.name,
|
|
3823
|
-
routing: {},
|
|
3824
|
-
agent: {},
|
|
3825
|
-
toolCall: toolResults.length ? { results: toolResults } : undefined,
|
|
3826
|
-
rawJson: {
|
|
3827
|
-
mode: this.mode,
|
|
3828
|
-
model: redactModel(model),
|
|
3829
|
-
metadata: options.metadata ?? {},
|
|
3830
|
-
available_tools: availableTools
|
|
3831
|
-
.filter((tool) => !asRecord(tool.marona)?.internal)
|
|
3832
|
-
.map((tool) => stringValue(asRecord(tool.function)?.name))
|
|
3833
|
-
.filter(Boolean),
|
|
3834
|
-
model_response: payload,
|
|
3835
|
-
model_responses: modelResponses,
|
|
3836
|
-
...(runtimeSteps.length ? { runtime_steps: runtimeSteps } : {}),
|
|
3837
|
-
},
|
|
3838
|
-
};
|
|
3839
|
-
}
|
|
3840
|
-
localCapabilityCatalog() {
|
|
3841
|
-
const payload = this.cache.loadSyncPayload() ?? {};
|
|
3842
|
-
const apps = Array.isArray(payload.available_agent_apps)
|
|
3843
|
-
? payload.available_agent_apps
|
|
3844
|
-
: Array.isArray(payload.apps)
|
|
3845
|
-
? payload.apps
|
|
3846
|
-
: Array.isArray(payload.items)
|
|
3847
|
-
? payload.items
|
|
3848
|
-
: [];
|
|
3849
|
-
const skills = Array.isArray(payload.available_skills) ? payload.available_skills : [];
|
|
3850
|
-
const managedCapabilities = new Set(skills.flatMap((raw) => {
|
|
3851
|
-
const skill = asRecord(raw);
|
|
3852
|
-
return skill ? skillManagedCapabilities(skill) : [];
|
|
3853
|
-
}));
|
|
3854
|
-
const supportedApps = apps
|
|
3855
|
-
.map(asRecord)
|
|
3856
|
-
.filter((app) => {
|
|
3857
|
-
if (!app || !appSupportsMode(app, this.mode))
|
|
3858
|
-
return false;
|
|
3859
|
-
const target = selectExecutionTarget(app, this.mode);
|
|
3860
|
-
return Boolean(target && !target.installRequired);
|
|
3861
|
-
});
|
|
3862
|
-
const supportedSlugs = new Set(supportedApps.map((app) => stringValue(app.slug)).filter((slug) => Boolean(slug)));
|
|
3863
|
-
return {
|
|
3864
|
-
apps: supportedApps.flatMap((app) => {
|
|
3865
|
-
const slug = stringValue(app.slug);
|
|
3866
|
-
const capabilityCount = listOfRecords(app.tools).filter((tool) => {
|
|
3867
|
-
const name = stringValue(tool.name);
|
|
3868
|
-
return Boolean(slug && name && !managedCapabilities.has(`${slug}.${name}`));
|
|
3869
|
-
}).length;
|
|
3870
|
-
return capabilityCount ? [{
|
|
3871
|
-
slug: app.slug,
|
|
3872
|
-
description: shortCatalogText(app.description ?? app.tagline),
|
|
3873
|
-
capability_count: capabilityCount,
|
|
3874
|
-
}] : [];
|
|
3875
|
-
}),
|
|
3876
|
-
skills: skills
|
|
3877
|
-
.map(asRecord)
|
|
3878
|
-
.filter((skill) => Boolean(skill) && skillSupportedBy(skill, supportedSlugs))
|
|
3879
|
-
.map((skill) => ({
|
|
3880
|
-
name: skill.name,
|
|
3881
|
-
description: shortCatalogText(skill.description),
|
|
3882
|
-
required_apps: skillRequiredApps(skill),
|
|
3883
|
-
})),
|
|
3884
|
-
};
|
|
3885
|
-
}
|
|
3886
|
-
discoverLocalCapabilities(call) {
|
|
3887
|
-
const args = toolCallArguments(call);
|
|
3888
|
-
const requestedApps = new Set(stringList(args.app_slugs));
|
|
3889
|
-
const requestedSkills = new Set(stringList(args.skill_names));
|
|
3890
|
-
const requestedCapabilities = new Set(stringList(args.capability_names));
|
|
3891
|
-
for (const capability of requestedCapabilities) {
|
|
3892
|
-
if (capability.includes('.'))
|
|
3893
|
-
requestedApps.add(capability.split('.')[0]);
|
|
3894
|
-
}
|
|
3895
|
-
const payload = this.cache.loadSyncPayload() ?? {};
|
|
3896
|
-
if (!requestedApps.size && !requestedSkills.size) {
|
|
3897
|
-
return {
|
|
3898
|
-
tools: [],
|
|
3899
|
-
result: {
|
|
3900
|
-
tool_call_id: call.id,
|
|
3901
|
-
result: {
|
|
3902
|
-
status: 'selection_required',
|
|
3903
|
-
catalog: this.localCapabilityCatalog(),
|
|
3904
|
-
instruction: 'Select the exact matching App and/or Skill identifiers from this catalog, then call marona__discover_capabilities again with them.',
|
|
3905
|
-
},
|
|
3906
|
-
},
|
|
3907
|
-
};
|
|
3908
|
-
}
|
|
3909
|
-
const rawSkills = Array.isArray(payload.available_skills) ? payload.available_skills : [];
|
|
3910
|
-
const selectedSkills = rawSkills.filter((rawSkill) => {
|
|
3911
|
-
const name = stringValue(asRecord(rawSkill)?.name);
|
|
3912
|
-
return Boolean(name && requestedSkills.has(name));
|
|
3913
|
-
});
|
|
3914
|
-
for (const rawSkill of selectedSkills) {
|
|
3915
|
-
const skill = asRecord(rawSkill);
|
|
3916
|
-
if (skill)
|
|
3917
|
-
skillRequiredApps(skill).forEach((slug) => requestedApps.add(slug));
|
|
3918
|
-
}
|
|
3919
|
-
const exactCapabilities = new Set(selectedSkills.flatMap((raw) => {
|
|
3920
|
-
const skill = asRecord(raw);
|
|
3921
|
-
return skill ? skillExactCapabilities(skill) : [];
|
|
3922
|
-
}));
|
|
3923
|
-
requestedCapabilities.forEach((capability) => exactCapabilities.add(capability));
|
|
3924
|
-
const managedCapabilities = new Set(rawSkills.flatMap((raw) => {
|
|
3925
|
-
const skill = asRecord(raw);
|
|
3926
|
-
return skill ? skillManagedCapabilities(skill) : [];
|
|
3927
|
-
}));
|
|
3928
|
-
const rawApps = Array.isArray(payload.available_agent_apps)
|
|
3929
|
-
? payload.available_agent_apps
|
|
3930
|
-
: Array.isArray(payload.apps)
|
|
3931
|
-
? payload.apps
|
|
3932
|
-
: Array.isArray(payload.items)
|
|
3933
|
-
? payload.items
|
|
3934
|
-
: [];
|
|
3935
|
-
const tools = [];
|
|
3936
|
-
const apps = [];
|
|
3937
|
-
const capabilityOptions = [];
|
|
3938
|
-
for (const rawApp of rawApps) {
|
|
3939
|
-
const app = asRecord(rawApp);
|
|
3940
|
-
const slug = stringValue(app?.slug);
|
|
3941
|
-
if (!app || !slug || !requestedApps.has(slug) || !appSupportsMode(app, this.mode))
|
|
3942
|
-
continue;
|
|
3943
|
-
const target = selectExecutionTarget(app, this.mode);
|
|
3944
|
-
if (!target || target.installRequired)
|
|
3945
|
-
continue;
|
|
3946
|
-
let appTools = toolsFromApp(app, stringValue(target.url), {
|
|
3947
|
-
executionMode: this.mode,
|
|
3948
|
-
executionTarget: asRecord(target.target),
|
|
3949
|
-
});
|
|
3950
|
-
if (exactCapabilities.size) {
|
|
3951
|
-
appTools = appTools.filter((tool) => {
|
|
3952
|
-
const name = toolFunctionName(tool)?.split('__').at(-1);
|
|
3953
|
-
return Boolean(name && exactCapabilities.has(`${slug}.${name}`));
|
|
3954
|
-
});
|
|
3955
|
-
}
|
|
3956
|
-
else {
|
|
3957
|
-
capabilityOptions.push(...appTools.flatMap((tool) => {
|
|
3958
|
-
const name = toolFunctionName(tool)?.split('__').at(-1);
|
|
3959
|
-
if (!name || managedCapabilities.has(`${slug}.${name}`))
|
|
3960
|
-
return [];
|
|
3961
|
-
return [{
|
|
3962
|
-
name: `${slug}.${name}`,
|
|
3963
|
-
description: shortCatalogText(asRecord(tool.function)?.description),
|
|
3964
|
-
}];
|
|
3965
|
-
}));
|
|
3966
|
-
appTools = [];
|
|
3967
|
-
}
|
|
3968
|
-
tools.push(...appTools);
|
|
3969
|
-
apps.push({
|
|
3970
|
-
slug,
|
|
3971
|
-
tools: appTools.map(toolFunctionName).filter(Boolean),
|
|
3972
|
-
installed: !target.installRequired,
|
|
3973
|
-
});
|
|
3974
|
-
}
|
|
3975
|
-
if (!tools.length && capabilityOptions.length) {
|
|
3976
|
-
return {
|
|
3977
|
-
tools: [],
|
|
3978
|
-
result: {
|
|
3979
|
-
tool_call_id: call.id,
|
|
3980
|
-
result: {
|
|
3981
|
-
status: 'capability_selection_required',
|
|
3982
|
-
capabilities: capabilityOptions,
|
|
3983
|
-
instruction: 'Select only the exact capability identifiers needed for the current request, then call marona__discover_capabilities again with capability_names.',
|
|
3984
|
-
},
|
|
3985
|
-
},
|
|
3986
|
-
};
|
|
3987
|
-
}
|
|
3988
|
-
const skills = compactLocalSkills(selectedSkills);
|
|
3989
|
-
return {
|
|
3990
|
-
tools,
|
|
3991
|
-
result: {
|
|
3992
|
-
tool_call_id: call.id,
|
|
3993
|
-
result: {
|
|
3994
|
-
status: 'completed',
|
|
3995
|
-
apps,
|
|
3996
|
-
skills,
|
|
3997
|
-
...(skills.length
|
|
3998
|
-
? {
|
|
3999
|
-
instruction: 'Skills are workflows, not callable tool names. Follow the selected workflow using the exact App tools returned by this discovery result.',
|
|
4000
|
-
}
|
|
4001
|
-
: {}),
|
|
4002
|
-
...(!apps.length && !skills.length
|
|
4003
|
-
? { message: 'No requested capability identifiers are available in this mode.' }
|
|
4004
|
-
: {}),
|
|
4005
|
-
},
|
|
4006
|
-
},
|
|
4007
|
-
};
|
|
4008
|
-
}
|
|
4009
3454
|
cacheTurn(text, response, options) {
|
|
4010
3455
|
this.cache.saveTurn({
|
|
4011
3456
|
conversationId: options.conversationId ?? options.conversation_id ?? response.conversationId,
|
|
@@ -4032,26 +3477,15 @@ export class Hub {
|
|
|
4032
3477
|
return this.hub.connect(options);
|
|
4033
3478
|
}
|
|
4034
3479
|
}
|
|
4035
|
-
export class Models {
|
|
4036
|
-
models;
|
|
4037
|
-
constructor(models) {
|
|
4038
|
-
this.models = models;
|
|
4039
|
-
}
|
|
4040
|
-
register(input) {
|
|
4041
|
-
return this.models.register({ ...input, makeDefault: false });
|
|
4042
|
-
}
|
|
4043
|
-
}
|
|
4044
3480
|
export class Marona {
|
|
4045
3481
|
hub;
|
|
4046
3482
|
responses;
|
|
4047
|
-
models;
|
|
4048
3483
|
skills;
|
|
4049
3484
|
runtime;
|
|
4050
3485
|
constructor(options = {}) {
|
|
4051
3486
|
this.runtime = new RuntimeEngine(options);
|
|
4052
3487
|
this.hub = new Hub(this.runtime.hub);
|
|
4053
3488
|
this.responses = new ResponsesClient(this.runtime);
|
|
4054
|
-
this.models = new Models(this.runtime.models);
|
|
4055
3489
|
this.skills = this.runtime.skills;
|
|
4056
3490
|
activeRuntime = this.runtime;
|
|
4057
3491
|
}
|
|
@@ -4065,6 +3499,33 @@ function parseRuntimeMessageResponse(payload) {
|
|
|
4065
3499
|
if (serviceConnection && authorizationUrl && !artifacts.some((artifact) => artifact.url === authorizationUrl)) {
|
|
4066
3500
|
artifacts.push(serviceConnectionArtifact(serviceConnection));
|
|
4067
3501
|
}
|
|
3502
|
+
const rawRouting = asRecord(payload.routing) ?? {};
|
|
3503
|
+
const routing = omitEmpty({
|
|
3504
|
+
requested_model: rawRouting.requested_model,
|
|
3505
|
+
selected_model: rawRouting.selected_model,
|
|
3506
|
+
strategy: rawRouting.strategy,
|
|
3507
|
+
fallback_used: rawRouting.fallback_used,
|
|
3508
|
+
});
|
|
3509
|
+
const rawJson = omitEmpty({
|
|
3510
|
+
status: payload.status,
|
|
3511
|
+
reply: payload.reply,
|
|
3512
|
+
output: payload.output,
|
|
3513
|
+
interface: payload.interface,
|
|
3514
|
+
conversation_id: payload.conversation_id,
|
|
3515
|
+
ui: payload.ui,
|
|
3516
|
+
artifacts: payload.artifacts,
|
|
3517
|
+
selected_app: payload.selected_app,
|
|
3518
|
+
selected_tool: payload.selected_tool,
|
|
3519
|
+
needs_permission: payload.needs_permission,
|
|
3520
|
+
needs_service_connection: payload.needs_service_connection,
|
|
3521
|
+
permission_request: payload.permission_request,
|
|
3522
|
+
service_connection: payload.service_connection,
|
|
3523
|
+
tool_call: payload.tool_call,
|
|
3524
|
+
model: payload.model,
|
|
3525
|
+
routing,
|
|
3526
|
+
agent: payload.agent,
|
|
3527
|
+
usage: payload.usage,
|
|
3528
|
+
});
|
|
4068
3529
|
return {
|
|
4069
3530
|
status: stringValue(payload.status) || "unknown",
|
|
4070
3531
|
reply,
|
|
@@ -4083,9 +3544,9 @@ function parseRuntimeMessageResponse(payload) {
|
|
|
4083
3544
|
? parseServiceConnectionAction(serviceConnection)
|
|
4084
3545
|
: undefined,
|
|
4085
3546
|
toolCall: asRecord(payload.tool_call),
|
|
4086
|
-
rawJson
|
|
3547
|
+
rawJson,
|
|
4087
3548
|
model: stringValue(payload.model),
|
|
4088
|
-
routing
|
|
3549
|
+
routing,
|
|
4089
3550
|
agent: asRecord(payload.agent) ?? {},
|
|
4090
3551
|
};
|
|
4091
3552
|
}
|
|
@@ -4111,7 +3572,6 @@ function normalizeRouting(value) {
|
|
|
4111
3572
|
target_latency_ms: value.targetLatencyMs ?? value.target_latency_ms,
|
|
4112
3573
|
timeout_ms: value.timeoutMs ?? value.timeout_ms,
|
|
4113
3574
|
allowed_models: value.allowedModels ?? value.allowed_models,
|
|
4114
|
-
allowed_providers: value.allowedProviders ?? value.allowed_providers,
|
|
4115
3575
|
fallback: value.fallback,
|
|
4116
3576
|
});
|
|
4117
3577
|
}
|
|
@@ -4224,315 +3684,6 @@ function inferLocation(endpoint) {
|
|
|
4224
3684
|
}
|
|
4225
3685
|
return "remote";
|
|
4226
3686
|
}
|
|
4227
|
-
function candidateModelBases(endpoint) {
|
|
4228
|
-
const base = endpoint.replace(/\/+$/, "");
|
|
4229
|
-
return base.endsWith("/v1") ? [base] : [base, `${base}/v1`];
|
|
4230
|
-
}
|
|
4231
|
-
function modelHeaders(model) {
|
|
4232
|
-
return {
|
|
4233
|
-
"Content-Type": "application/json",
|
|
4234
|
-
...(model.apiKey ? { Authorization: `Bearer ${model.apiKey}` } : {}),
|
|
4235
|
-
};
|
|
4236
|
-
}
|
|
4237
|
-
function firstModelId(payload) {
|
|
4238
|
-
return modelIds(payload)[0];
|
|
4239
|
-
}
|
|
4240
|
-
function selectModelId(payload, requested) {
|
|
4241
|
-
const ids = modelIds(payload);
|
|
4242
|
-
const cleanRequested = requested?.trim();
|
|
4243
|
-
if (cleanRequested && (!ids.length || ids.includes(cleanRequested)))
|
|
4244
|
-
return cleanRequested;
|
|
4245
|
-
return ids[0] ?? cleanRequested;
|
|
4246
|
-
}
|
|
4247
|
-
function modelIds(payload) {
|
|
4248
|
-
const record = asRecord(payload);
|
|
4249
|
-
const data = Array.isArray(record?.data) ? record?.data : [];
|
|
4250
|
-
return data
|
|
4251
|
-
.map((item) => stringValue(asRecord(item)?.id)?.trim())
|
|
4252
|
-
.filter((item) => Boolean(item))
|
|
4253
|
-
.sort((a, b) => Number(a.includes(",")) - Number(b.includes(",")) || a.localeCompare(b));
|
|
4254
|
-
}
|
|
4255
|
-
function modelFromJson(payload) {
|
|
4256
|
-
return {
|
|
4257
|
-
name: stringValue(payload.name) ?? "",
|
|
4258
|
-
endpoint: stringValue(payload.endpoint) ?? "",
|
|
4259
|
-
provider: stringValue(payload.provider),
|
|
4260
|
-
model: stringValue(payload.model),
|
|
4261
|
-
protocol: stringValue(payload.protocol),
|
|
4262
|
-
features: Array.isArray(payload.features) ? payload.features.map(String) : [],
|
|
4263
|
-
location: (stringValue(payload.location) ?? inferLocation(stringValue(payload.endpoint) ?? "")),
|
|
4264
|
-
status: (stringValue(payload.status) ?? "unknown"),
|
|
4265
|
-
apiKey: stringValue(payload.api_key) ?? stringValue(payload.apiKey),
|
|
4266
|
-
metadata: asRecord(payload.metadata) ?? {},
|
|
4267
|
-
lastCheckedAt: stringValue(payload.last_checked_at) ?? stringValue(payload.lastCheckedAt),
|
|
4268
|
-
contextWindow: numberValue(payload.context_window) ?? numberValue(payload.contextWindow),
|
|
4269
|
-
maxOutputTokens: numberValue(payload.max_output_tokens) ?? numberValue(payload.maxOutputTokens),
|
|
4270
|
-
};
|
|
4271
|
-
}
|
|
4272
|
-
function redactModel(model) {
|
|
4273
|
-
const { apiKey: _apiKey, ...safe } = model;
|
|
4274
|
-
return safe;
|
|
4275
|
-
}
|
|
4276
|
-
function modelUserContent(text, attachments) {
|
|
4277
|
-
if (!attachments.length)
|
|
4278
|
-
return text;
|
|
4279
|
-
const content = [{ type: "text", text }];
|
|
4280
|
-
for (const input of attachments) {
|
|
4281
|
-
const attachment = input instanceof RuntimeAttachment ? input : new RuntimeAttachment(input);
|
|
4282
|
-
const source = attachment.dataBase64
|
|
4283
|
-
? `data:${attachment.mimeType};base64,${attachment.dataBase64}`
|
|
4284
|
-
: attachment.url;
|
|
4285
|
-
if (attachment.kind === "image" && source) {
|
|
4286
|
-
content.push({ type: "image_url", image_url: { url: source }, mime_type: attachment.mimeType });
|
|
4287
|
-
}
|
|
4288
|
-
else if (attachment.text) {
|
|
4289
|
-
content.push({ type: "text", text: `File ${attachment.filename}:\n${attachment.text}` });
|
|
4290
|
-
}
|
|
4291
|
-
else {
|
|
4292
|
-
content.push({
|
|
4293
|
-
type: "file",
|
|
4294
|
-
filename: attachment.filename,
|
|
4295
|
-
mime_type: attachment.mimeType,
|
|
4296
|
-
data: attachment.dataBase64,
|
|
4297
|
-
url: attachment.url,
|
|
4298
|
-
});
|
|
4299
|
-
}
|
|
4300
|
-
}
|
|
4301
|
-
return content;
|
|
4302
|
-
}
|
|
4303
|
-
async function callChatModel(model, messages, tools, fetchImpl, toolChoice = "auto", executor, adapter) {
|
|
4304
|
-
const request = {
|
|
4305
|
-
model: model.model ?? model.name,
|
|
4306
|
-
messages,
|
|
4307
|
-
...(modelOutputLimit(model) ? { max_tokens: modelOutputLimit(model) } : {}),
|
|
4308
|
-
...(tools.length
|
|
4309
|
-
? {
|
|
4310
|
-
tools: tools.map((tool) => asRecord(tool.function) ? { type: "function", function: tool.function } : tool),
|
|
4311
|
-
tool_choice: toolChoice,
|
|
4312
|
-
}
|
|
4313
|
-
: {}),
|
|
4314
|
-
};
|
|
4315
|
-
const handler = model.protocol === "local_executor" ? executor : model.protocol === "custom_adapter" ? adapter : undefined;
|
|
4316
|
-
if (handler) {
|
|
4317
|
-
const payload = await handler(request);
|
|
4318
|
-
const record = asRecord(payload);
|
|
4319
|
-
if (!record)
|
|
4320
|
-
throw new MaronaModelError(`Local model '${model.name}' returned a non-JSON response.`, { payload });
|
|
4321
|
-
return record;
|
|
4322
|
-
}
|
|
4323
|
-
if (model.protocol === "local_executor" || model.protocol === "custom_adapter") {
|
|
4324
|
-
throw new MaronaModelError(`Model '${model.name}' has no registered adapter.`);
|
|
4325
|
-
}
|
|
4326
|
-
if (model.protocol === "anthropic" || model.provider === "anthropic") {
|
|
4327
|
-
return callAnthropicModel(model, messages, tools, fetchImpl, toolChoice);
|
|
4328
|
-
}
|
|
4329
|
-
if (model.protocol === "gemini" || model.provider === "gemini") {
|
|
4330
|
-
return callGeminiModel(model, messages, tools, fetchImpl, toolChoice);
|
|
4331
|
-
}
|
|
4332
|
-
if (model.protocol && !["chat_completions", "custom_http"].includes(model.protocol)) {
|
|
4333
|
-
throw new MaronaModelError(`Model '${model.name}' does not support chat messages yet.`);
|
|
4334
|
-
}
|
|
4335
|
-
const response = await fetchImpl(`${model.endpoint.replace(/\/+$/, "")}/chat/completions`, {
|
|
4336
|
-
method: "POST",
|
|
4337
|
-
headers: modelHeaders(model),
|
|
4338
|
-
body: JSON.stringify(request),
|
|
4339
|
-
});
|
|
4340
|
-
const text = await response.text();
|
|
4341
|
-
const payload = parseMaybeJson(text);
|
|
4342
|
-
if (!response.ok) {
|
|
4343
|
-
throw new MaronaModelError(`Local model request failed with HTTP ${response.status}.`, {
|
|
4344
|
-
statusCode: response.status,
|
|
4345
|
-
payload,
|
|
4346
|
-
});
|
|
4347
|
-
}
|
|
4348
|
-
const record = asRecord(payload);
|
|
4349
|
-
if (!record)
|
|
4350
|
-
throw new MaronaModelError("Local model returned a non-JSON response.", { payload });
|
|
4351
|
-
return record;
|
|
4352
|
-
}
|
|
4353
|
-
async function callAnthropicModel(model, messages, tools, fetchImpl, toolChoice) {
|
|
4354
|
-
const system = messages
|
|
4355
|
-
.filter((message) => message.role === "system")
|
|
4356
|
-
.map((message) => contentText(message.content))
|
|
4357
|
-
.filter(Boolean)
|
|
4358
|
-
.join("\n\n");
|
|
4359
|
-
const anthropicMessages = messages
|
|
4360
|
-
.filter((message) => message.role !== "system" && (message.role === "user" || message.role === "assistant"))
|
|
4361
|
-
.map((message) => ({ role: message.role, content: anthropicContent(message.content) }));
|
|
4362
|
-
const response = await fetchImpl(`${model.endpoint.replace(/\/+$/, "")}/messages`, {
|
|
4363
|
-
method: "POST",
|
|
4364
|
-
headers: {
|
|
4365
|
-
"Content-Type": "application/json",
|
|
4366
|
-
"anthropic-version": "2023-06-01",
|
|
4367
|
-
...(model.apiKey ? { "x-api-key": model.apiKey } : {}),
|
|
4368
|
-
},
|
|
4369
|
-
body: JSON.stringify({
|
|
4370
|
-
model: model.model ?? model.name,
|
|
4371
|
-
system: system || undefined,
|
|
4372
|
-
messages: anthropicMessages,
|
|
4373
|
-
max_tokens: modelOutputLimit(model) ?? 1024,
|
|
4374
|
-
...(tools.length
|
|
4375
|
-
? {
|
|
4376
|
-
tools: tools.map((tool) => {
|
|
4377
|
-
const fn = asRecord(tool.function) ?? tool;
|
|
4378
|
-
return {
|
|
4379
|
-
name: fn.name,
|
|
4380
|
-
description: fn.description,
|
|
4381
|
-
input_schema: fn.parameters ?? { type: "object", properties: {} },
|
|
4382
|
-
};
|
|
4383
|
-
}),
|
|
4384
|
-
tool_choice: toolChoice === "required" ? { type: "any" } : { type: "auto" },
|
|
4385
|
-
}
|
|
4386
|
-
: {}),
|
|
4387
|
-
}),
|
|
4388
|
-
});
|
|
4389
|
-
const payload = parseMaybeJson(await response.text());
|
|
4390
|
-
if (!response.ok) {
|
|
4391
|
-
throw new MaronaModelError(`Anthropic model request failed with HTTP ${response.status}.`, {
|
|
4392
|
-
statusCode: response.status,
|
|
4393
|
-
payload,
|
|
4394
|
-
});
|
|
4395
|
-
}
|
|
4396
|
-
const record = asRecord(payload);
|
|
4397
|
-
if (!record)
|
|
4398
|
-
throw new MaronaModelError("Anthropic returned a non-JSON response.", { payload });
|
|
4399
|
-
const blocks = Array.isArray(record.content) ? record.content.map(asRecord).filter(Boolean) : [];
|
|
4400
|
-
const text = blocks.filter((block) => block.type === "text").map((block) => stringValue(block.text)).filter(Boolean).join("\n");
|
|
4401
|
-
const toolCalls = blocks.filter((block) => block.type === "tool_use").map((block) => ({
|
|
4402
|
-
id: block.id,
|
|
4403
|
-
type: "function",
|
|
4404
|
-
function: { name: block.name, arguments: JSON.stringify(asRecord(block.input) ?? {}) },
|
|
4405
|
-
}));
|
|
4406
|
-
return { choices: [{ message: { role: "assistant", content: text, ...(toolCalls.length ? { tool_calls: toolCalls } : {}) } }], raw_provider_response: record };
|
|
4407
|
-
}
|
|
4408
|
-
async function callGeminiModel(model, messages, tools, fetchImpl, toolChoice) {
|
|
4409
|
-
const system = messages
|
|
4410
|
-
.filter((message) => message.role === "system")
|
|
4411
|
-
.map((message) => contentText(message.content))
|
|
4412
|
-
.filter(Boolean)
|
|
4413
|
-
.join("\n\n");
|
|
4414
|
-
const contents = messages
|
|
4415
|
-
.filter((message) => message.role !== "system" && (message.role === "user" || message.role === "assistant"))
|
|
4416
|
-
.map((message) => ({ role: message.role === "assistant" ? "model" : "user", parts: geminiParts(message.content) }));
|
|
4417
|
-
const endpoint = `${model.endpoint.replace(/\/+$/, "")}/models/${encodeURIComponent(model.model ?? model.name)}:generateContent`;
|
|
4418
|
-
const url = new URL(endpoint);
|
|
4419
|
-
if (model.apiKey)
|
|
4420
|
-
url.searchParams.set("key", model.apiKey);
|
|
4421
|
-
const response = await fetchImpl(url.toString(), {
|
|
4422
|
-
method: "POST",
|
|
4423
|
-
headers: { "Content-Type": "application/json" },
|
|
4424
|
-
body: JSON.stringify({
|
|
4425
|
-
...(system ? { systemInstruction: { parts: [{ text: system }] } } : {}),
|
|
4426
|
-
contents,
|
|
4427
|
-
...(tools.length
|
|
4428
|
-
? {
|
|
4429
|
-
tools: [{ functionDeclarations: tools.map((tool) => {
|
|
4430
|
-
const fn = asRecord(tool.function) ?? tool;
|
|
4431
|
-
return { name: fn.name, description: fn.description, parameters: fn.parameters ?? { type: "object", properties: {} } };
|
|
4432
|
-
}) }],
|
|
4433
|
-
toolConfig: { functionCallingConfig: { mode: toolChoice === "required" ? "ANY" : "AUTO" } },
|
|
4434
|
-
}
|
|
4435
|
-
: {}),
|
|
4436
|
-
...(modelOutputLimit(model) ? { generationConfig: { maxOutputTokens: modelOutputLimit(model) } } : {}),
|
|
4437
|
-
}),
|
|
4438
|
-
});
|
|
4439
|
-
const payload = parseMaybeJson(await response.text());
|
|
4440
|
-
if (!response.ok) {
|
|
4441
|
-
throw new MaronaModelError(`Gemini model request failed with HTTP ${response.status}.`, {
|
|
4442
|
-
statusCode: response.status,
|
|
4443
|
-
payload,
|
|
4444
|
-
});
|
|
4445
|
-
}
|
|
4446
|
-
const record = asRecord(payload);
|
|
4447
|
-
if (!record)
|
|
4448
|
-
throw new MaronaModelError("Gemini returned a non-JSON response.", { payload });
|
|
4449
|
-
const candidates = Array.isArray(record.candidates) ? record.candidates : [];
|
|
4450
|
-
const content = asRecord(asRecord(candidates[0])?.content);
|
|
4451
|
-
const parts = Array.isArray(content?.parts) ? content.parts.map(asRecord).filter(Boolean) : [];
|
|
4452
|
-
const text = parts.map((part) => stringValue(part.text)).filter(Boolean).join("\n");
|
|
4453
|
-
const toolCalls = parts.map((part, index) => asRecord(part.functionCall) ? ({
|
|
4454
|
-
id: `gemini-call-${index}`,
|
|
4455
|
-
type: "function",
|
|
4456
|
-
function: {
|
|
4457
|
-
name: asRecord(part.functionCall)?.name,
|
|
4458
|
-
arguments: JSON.stringify(asRecord(asRecord(part.functionCall)?.args) ?? {}),
|
|
4459
|
-
},
|
|
4460
|
-
}) : undefined).filter(Boolean);
|
|
4461
|
-
return { choices: [{ message: { role: "assistant", content: text, ...(toolCalls.length ? { tool_calls: toolCalls } : {}) } }], raw_provider_response: record };
|
|
4462
|
-
}
|
|
4463
|
-
function anthropicContent(content) {
|
|
4464
|
-
if (typeof content === "string")
|
|
4465
|
-
return content;
|
|
4466
|
-
if (!Array.isArray(content))
|
|
4467
|
-
return String(content ?? "");
|
|
4468
|
-
return content.map((raw) => {
|
|
4469
|
-
const block = asRecord(raw);
|
|
4470
|
-
if (!block)
|
|
4471
|
-
return { type: "text", text: String(raw) };
|
|
4472
|
-
if (block.type === "image_url") {
|
|
4473
|
-
const image = asRecord(block.image_url);
|
|
4474
|
-
const data = dataUriParts(stringValue(image?.url) ?? "");
|
|
4475
|
-
if (data.dataBase64)
|
|
4476
|
-
return { type: "image", source: { type: "base64", media_type: data.mimeType, data: data.dataBase64 } };
|
|
4477
|
-
}
|
|
4478
|
-
if (block.type === "file") {
|
|
4479
|
-
const data = stringValue(block.data);
|
|
4480
|
-
if (data)
|
|
4481
|
-
return { type: "document", source: { type: "base64", media_type: block.mime_type, data }, title: block.filename };
|
|
4482
|
-
}
|
|
4483
|
-
return { type: "text", text: stringValue(block.text) ?? JSON.stringify(block) };
|
|
4484
|
-
});
|
|
4485
|
-
}
|
|
4486
|
-
function geminiParts(content) {
|
|
4487
|
-
if (typeof content === "string")
|
|
4488
|
-
return [{ text: content }];
|
|
4489
|
-
if (!Array.isArray(content))
|
|
4490
|
-
return [{ text: String(content ?? "") }];
|
|
4491
|
-
return content.map((raw) => {
|
|
4492
|
-
const block = asRecord(raw);
|
|
4493
|
-
if (!block)
|
|
4494
|
-
return { text: String(raw) };
|
|
4495
|
-
if (block.type === "image_url") {
|
|
4496
|
-
const url = stringValue(asRecord(block.image_url)?.url);
|
|
4497
|
-
const data = dataUriParts(url ?? "");
|
|
4498
|
-
if (data.dataBase64)
|
|
4499
|
-
return { inlineData: { mimeType: data.mimeType, data: data.dataBase64 } };
|
|
4500
|
-
if (url)
|
|
4501
|
-
return { fileData: { mimeType: block.mime_type ?? "image/*", fileUri: url } };
|
|
4502
|
-
}
|
|
4503
|
-
if (block.type === "file") {
|
|
4504
|
-
const data = stringValue(block.data);
|
|
4505
|
-
if (data)
|
|
4506
|
-
return { inlineData: { mimeType: block.mime_type, data } };
|
|
4507
|
-
const url = stringValue(block.url);
|
|
4508
|
-
if (url)
|
|
4509
|
-
return { fileData: { mimeType: block.mime_type, fileUri: url } };
|
|
4510
|
-
}
|
|
4511
|
-
return { text: stringValue(block.text) ?? JSON.stringify(block) };
|
|
4512
|
-
});
|
|
4513
|
-
}
|
|
4514
|
-
function modelOutputLimit(model) {
|
|
4515
|
-
if (model.contextWindow && model.contextWindow <= 2048) {
|
|
4516
|
-
return Math.min(model.maxOutputTokens ?? 192, 192);
|
|
4517
|
-
}
|
|
4518
|
-
if (model.contextWindow && model.contextWindow <= 4096) {
|
|
4519
|
-
return Math.min(model.maxOutputTokens ?? 384, 384);
|
|
4520
|
-
}
|
|
4521
|
-
return model.maxOutputTokens;
|
|
4522
|
-
}
|
|
4523
|
-
function modelText(payload) {
|
|
4524
|
-
const choices = Array.isArray(payload.choices) ? payload.choices : [];
|
|
4525
|
-
const first = asRecord(choices[0]);
|
|
4526
|
-
const message = asRecord(first?.message);
|
|
4527
|
-
return stringValue(message?.content) ?? "";
|
|
4528
|
-
}
|
|
4529
|
-
function modelToolCalls(payload) {
|
|
4530
|
-
const choices = Array.isArray(payload.choices) ? payload.choices : [];
|
|
4531
|
-
const first = asRecord(choices[0]);
|
|
4532
|
-
const message = asRecord(first?.message);
|
|
4533
|
-
const calls = Array.isArray(message?.tool_calls) ? message.tool_calls : [];
|
|
4534
|
-
return calls.map(asRecord).filter(Boolean);
|
|
4535
|
-
}
|
|
4536
3687
|
function toolResultForModel(result, contextTier = 0) {
|
|
4537
3688
|
const value = Object.prototype.hasOwnProperty.call(result, "result")
|
|
4538
3689
|
? result.result
|
|
@@ -5320,7 +4471,6 @@ function parseRuntimeAppsPage(payload) {
|
|
|
5320
4471
|
function parseRealtimeSessionCreated(payload) {
|
|
5321
4472
|
return {
|
|
5322
4473
|
status: stringValue(payload.status) || "",
|
|
5323
|
-
provider: stringValue(payload.provider) || "",
|
|
5324
4474
|
model: stringValue(payload.model) || "",
|
|
5325
4475
|
voice: stringValue(payload.voice) || "",
|
|
5326
4476
|
mode: stringValue(payload.mode) || "",
|
|
@@ -5330,7 +4480,15 @@ function parseRealtimeSessionCreated(payload) {
|
|
|
5330
4480
|
expiresAt: numberValue(payload.expires_at),
|
|
5331
4481
|
session: asRecord(payload.session) ?? {},
|
|
5332
4482
|
capabilities: asRecord(payload.capabilities) ?? {},
|
|
5333
|
-
rawJson: {
|
|
4483
|
+
rawJson: omitEmpty({
|
|
4484
|
+
status: payload.status,
|
|
4485
|
+
model: payload.model,
|
|
4486
|
+
voice: payload.voice,
|
|
4487
|
+
mode: payload.mode,
|
|
4488
|
+
conversation_id: payload.conversation_id,
|
|
4489
|
+
expires_at: payload.expires_at,
|
|
4490
|
+
capabilities: payload.capabilities,
|
|
4491
|
+
}),
|
|
5334
4492
|
};
|
|
5335
4493
|
}
|
|
5336
4494
|
function parseServiceConnectionAction(payload) {
|
|
@@ -5449,6 +4607,42 @@ function environmentValue(name) {
|
|
|
5449
4607
|
const processValue = globalThis.process;
|
|
5450
4608
|
return cleanString(processValue?.env?.[name]);
|
|
5451
4609
|
}
|
|
4610
|
+
function resolveMaronaApiKey(explicit) {
|
|
4611
|
+
if (explicit !== undefined) {
|
|
4612
|
+
const value = cleanString(explicit);
|
|
4613
|
+
if (!value)
|
|
4614
|
+
throw new MaronaApiKeyRequiredError(maronaApiKeyRequired, {
|
|
4615
|
+
code: "MARONA_API_KEY_REQUIRED",
|
|
4616
|
+
statusCode: 401,
|
|
4617
|
+
requiredAction: "CONFIGURE_MARONA_API_KEY",
|
|
4618
|
+
});
|
|
4619
|
+
return value;
|
|
4620
|
+
}
|
|
4621
|
+
const value = environmentValue("MARONA_API_KEY");
|
|
4622
|
+
if (!value)
|
|
4623
|
+
throw new MaronaApiKeyRequiredError(maronaApiKeyRequired, {
|
|
4624
|
+
code: "MARONA_API_KEY_REQUIRED",
|
|
4625
|
+
statusCode: 401,
|
|
4626
|
+
requiredAction: "CONFIGURE_MARONA_API_KEY",
|
|
4627
|
+
});
|
|
4628
|
+
return value;
|
|
4629
|
+
}
|
|
4630
|
+
function validateModelNamespace(model) {
|
|
4631
|
+
const value = cleanString(model) ?? "marona/auto";
|
|
4632
|
+
if (!value.startsWith("marona/") || value === "marona/") {
|
|
4633
|
+
throw new InvalidModelNamespaceError("Models executed through Marona must use the marona/* namespace.", {
|
|
4634
|
+
code: "INVALID_MODEL_NAMESPACE",
|
|
4635
|
+
statusCode: 400,
|
|
4636
|
+
requiredAction: "USE_OR_REGISTER_A_MARONA_MODEL",
|
|
4637
|
+
});
|
|
4638
|
+
}
|
|
4639
|
+
return value;
|
|
4640
|
+
}
|
|
4641
|
+
function maronaHeaders(headers, apiKey) {
|
|
4642
|
+
const result = Object.fromEntries(Object.entries(headers ?? {}).filter(([name]) => name.toLowerCase() !== "authorization"));
|
|
4643
|
+
result.Authorization = `Bearer ${apiKey}`;
|
|
4644
|
+
return result;
|
|
4645
|
+
}
|
|
5452
4646
|
function stringValue(value) {
|
|
5453
4647
|
if (value === undefined || value === null)
|
|
5454
4648
|
return undefined;
|
|
@@ -5472,7 +4666,11 @@ function hasMaronaApiKey(headers) {
|
|
|
5472
4666
|
}
|
|
5473
4667
|
function requireMaronaApiKey(headers) {
|
|
5474
4668
|
if (!hasMaronaApiKey(headers)) {
|
|
5475
|
-
throw new
|
|
4669
|
+
throw new MaronaApiKeyRequiredError(maronaApiKeyRequired, {
|
|
4670
|
+
code: "MARONA_API_KEY_REQUIRED",
|
|
4671
|
+
statusCode: 401,
|
|
4672
|
+
requiredAction: "CONFIGURE_MARONA_API_KEY",
|
|
4673
|
+
});
|
|
5476
4674
|
}
|
|
5477
4675
|
}
|
|
5478
4676
|
function isPlainObject(value) {
|