marona 0.15.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/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const packageVersion = "0.15.0";
1
+ export const packageVersion = "1.0.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 ?? "marona/auto").trim();
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("Realtime provider did not return a client secret.");
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
- `openai-insecure-api-key.${descriptor.clientSecret}`,
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/gpt-5.6",
1878
+ model: options.model ?? "marona/auto",
1966
1879
  framework: "marona",
1967
1880
  runtime: "responses",
1968
1881
  },
@@ -2277,10 +2190,7 @@ class HubClient {
2277
2190
  const text = await response.text();
2278
2191
  const payload = parseMaybeJson(text);
2279
2192
  if (!response.ok) {
2280
- throw new EdgeRuntimeError(`Marona Hub request failed with HTTP ${response.status}.`, {
2281
- statusCode: response.status,
2282
- payload,
2283
- });
2193
+ throw maronaError(payload, response.status, "Marona Hub could not complete the request.");
2284
2194
  }
2285
2195
  return payload;
2286
2196
  }
@@ -2969,7 +2879,7 @@ class RuntimeTransport {
2969
2879
  signal: AbortSignal.timeout(this.timeoutMs),
2970
2880
  });
2971
2881
  if (!response.ok) {
2972
- throw new EdgeRuntimeError(`Edge runtime request failed with HTTP ${response.status}.`, { statusCode: response.status, payload: parseMaybeJson(await response.text()) });
2882
+ throw maronaError(parseMaybeJson(await response.text()), response.status, "Marona Runtime could not start the stream.");
2973
2883
  }
2974
2884
  if (!response.body) {
2975
2885
  throw new EdgeRuntimeError("Edge runtime returned an empty event stream.");
@@ -2987,6 +2897,8 @@ class RuntimeTransport {
2987
2897
  if (!line.startsWith("data:"))
2988
2898
  continue;
2989
2899
  const event = asRecord(parseMaybeJson(line.slice(5).trim()));
2900
+ if (event?.error)
2901
+ throw maronaError(event, undefined, "Marona Runtime stream failed.");
2990
2902
  if (event)
2991
2903
  yield event;
2992
2904
  }
@@ -2995,6 +2907,8 @@ class RuntimeTransport {
2995
2907
  }
2996
2908
  if (buffer.startsWith("data:")) {
2997
2909
  const event = asRecord(parseMaybeJson(buffer.slice(5).trim()));
2910
+ if (event?.error)
2911
+ throw maronaError(event, undefined, "Marona Runtime stream failed.");
2998
2912
  if (event)
2999
2913
  yield event;
3000
2914
  }
@@ -3116,10 +3030,7 @@ class RuntimeTransport {
3116
3030
  });
3117
3031
  const text = await response.text();
3118
3032
  if (!response.ok) {
3119
- throw new EdgeRuntimeError(`Edge runtime request failed with HTTP ${response.status}.`, {
3120
- statusCode: response.status,
3121
- payload: parseMaybeJson(text),
3122
- });
3033
+ throw maronaError(parseMaybeJson(text), response.status, "Marona Runtime could not complete the request.");
3123
3034
  }
3124
3035
  return text;
3125
3036
  }
@@ -3276,7 +3187,7 @@ class ResponsesClient {
3276
3187
  for (let round = 0; round < 8; round += 1) {
3277
3188
  const response = await this.runtime.client({
3278
3189
  ...runtimeOptions,
3279
- model: options.model ?? "marona/gpt-5.6",
3190
+ model: options.model ?? "marona/auto",
3280
3191
  metadata: {
3281
3192
  ...metadata,
3282
3193
  ...(results.length ? { marona_function_tool_results: results } : {}),
@@ -3372,7 +3283,7 @@ class ResponsesClient {
3372
3283
  let response;
3373
3284
  for await (const event of this.runtime.clientStream({
3374
3285
  ...options,
3375
- model: options.model ?? "marona/gpt-5.6",
3286
+ model: options.model ?? "marona/auto",
3376
3287
  metadata: {
3377
3288
  ...metadata,
3378
3289
  ...(results.length ? { marona_function_tool_results: results } : {}),
@@ -3431,17 +3342,11 @@ class ResponsesClient {
3431
3342
  class RuntimeEngine extends RuntimeTransport {
3432
3343
  hub;
3433
3344
  cache;
3434
- models;
3435
3345
  skills;
3436
3346
  tools;
3437
3347
  responses;
3438
3348
  mode;
3439
- modelFetchImpl;
3440
3349
  developerInstructions;
3441
- defaultModelRoute;
3442
- providerCredentials;
3443
- providerEndpoints;
3444
- maronaAccessVerified = false;
3445
3350
  constructor(options = {}) {
3446
3351
  const developerKey = resolveMaronaApiKey(options.apiKey);
3447
3352
  const authenticatedHeaders = maronaHeaders(options.headers, developerKey);
@@ -3458,12 +3363,7 @@ class RuntimeEngine extends RuntimeTransport {
3458
3363
  this.mode = mode;
3459
3364
  this.cache = options.cache ?? new MaronaCache();
3460
3365
  this.developerInstructions = undefined;
3461
- this.defaultModelRoute = undefined;
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);
3366
+ this.tools = new ToolExecutor(this.baseUrl, this.defaultHeaders, options.fetchImpl ?? globalThis.fetch);
3467
3367
  this.tools.runtime = this;
3468
3368
  this.hub = new MaronaHubClient(options.hubUrl ?? "https://hub.marona.ai", {
3469
3369
  apiKey: developerKey,
@@ -3503,116 +3403,20 @@ class RuntimeEngine extends RuntimeTransport {
3503
3403
  return payload;
3504
3404
  }
3505
3405
  async message(text, options = {}) {
3506
- const configuredRoute = cleanString(options.model ?? this.defaultModelRoute);
3507
- const legacyDefault = configuredRoute ? undefined : this.models.default();
3508
- const modelRoute = configuredRoute ?? legacyDefault?.name ?? "marona/gpt-5.6";
3509
- const model = configuredRoute ? this.resolveModel(modelRoute) : legacyDefault;
3510
- const developerInstructions = combineText([
3511
- this.developerInstructions,
3512
- options.developerInstructions ?? options.developer_instructions,
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,
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
+ ]),
3544
3414
  metadata: { ...(options.metadata ?? {}), ...(options.tools ? { tools: options.tools } : {}) },
3545
- });
3415
+ };
3416
+ const response = await super.message(text, messageOptions);
3546
3417
  this.cacheTurn(text, response, messageOptions);
3547
3418
  return response;
3548
3419
  }
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
3420
  async client(options) {
3617
3421
  const { input, attachments, ...messageOptions } = options;
3618
3422
  const normalized = runtimeMessageFromInput(input);
@@ -3628,17 +3432,7 @@ class RuntimeEngine extends RuntimeTransport {
3628
3432
  async *clientStream(options) {
3629
3433
  const { input, attachments, ...messageOptions } = options;
3630
3434
  const normalized = runtimeMessageFromInput(input);
3631
- const modelRoute = cleanString(messageOptions.model ?? this.defaultModelRoute)
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
- }
3435
+ const model = validateModelNamespace(messageOptions.model);
3642
3436
  const developerInstructions = combineText([
3643
3437
  normalized.developerInstructions,
3644
3438
  this.developerInstructions,
@@ -3646,7 +3440,7 @@ class RuntimeEngine extends RuntimeTransport {
3646
3440
  ]);
3647
3441
  for await (const event of super.streamMessage(normalized.text, {
3648
3442
  ...messageOptions,
3649
- model: modelRoute,
3443
+ model,
3650
3444
  developerInstructions,
3651
3445
  attachments: [...normalized.attachments, ...(attachments ?? [])],
3652
3446
  metadata: {
@@ -3657,361 +3451,6 @@ class RuntimeEngine extends RuntimeTransport {
3657
3451
  yield event;
3658
3452
  }
3659
3453
  }
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
3454
  cacheTurn(text, response, options) {
4016
3455
  this.cache.saveTurn({
4017
3456
  conversationId: options.conversationId ?? options.conversation_id ?? response.conversationId,
@@ -4038,26 +3477,15 @@ export class Hub {
4038
3477
  return this.hub.connect(options);
4039
3478
  }
4040
3479
  }
4041
- export class Models {
4042
- models;
4043
- constructor(models) {
4044
- this.models = models;
4045
- }
4046
- register(input) {
4047
- return this.models.register({ ...input, makeDefault: false });
4048
- }
4049
- }
4050
3480
  export class Marona {
4051
3481
  hub;
4052
3482
  responses;
4053
- models;
4054
3483
  skills;
4055
3484
  runtime;
4056
3485
  constructor(options = {}) {
4057
3486
  this.runtime = new RuntimeEngine(options);
4058
3487
  this.hub = new Hub(this.runtime.hub);
4059
3488
  this.responses = new ResponsesClient(this.runtime);
4060
- this.models = new Models(this.runtime.models);
4061
3489
  this.skills = this.runtime.skills;
4062
3490
  activeRuntime = this.runtime;
4063
3491
  }
@@ -4071,6 +3499,33 @@ function parseRuntimeMessageResponse(payload) {
4071
3499
  if (serviceConnection && authorizationUrl && !artifacts.some((artifact) => artifact.url === authorizationUrl)) {
4072
3500
  artifacts.push(serviceConnectionArtifact(serviceConnection));
4073
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
+ });
4074
3529
  return {
4075
3530
  status: stringValue(payload.status) || "unknown",
4076
3531
  reply,
@@ -4089,9 +3544,9 @@ function parseRuntimeMessageResponse(payload) {
4089
3544
  ? parseServiceConnectionAction(serviceConnection)
4090
3545
  : undefined,
4091
3546
  toolCall: asRecord(payload.tool_call),
4092
- rawJson: { ...payload },
3547
+ rawJson,
4093
3548
  model: stringValue(payload.model),
4094
- routing: asRecord(payload.routing) ?? {},
3549
+ routing,
4095
3550
  agent: asRecord(payload.agent) ?? {},
4096
3551
  };
4097
3552
  }
@@ -4117,7 +3572,6 @@ function normalizeRouting(value) {
4117
3572
  target_latency_ms: value.targetLatencyMs ?? value.target_latency_ms,
4118
3573
  timeout_ms: value.timeoutMs ?? value.timeout_ms,
4119
3574
  allowed_models: value.allowedModels ?? value.allowed_models,
4120
- allowed_providers: value.allowedProviders ?? value.allowed_providers,
4121
3575
  fallback: value.fallback,
4122
3576
  });
4123
3577
  }
@@ -4230,315 +3684,6 @@ function inferLocation(endpoint) {
4230
3684
  }
4231
3685
  return "remote";
4232
3686
  }
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
3687
  function toolResultForModel(result, contextTier = 0) {
4543
3688
  const value = Object.prototype.hasOwnProperty.call(result, "result")
4544
3689
  ? result.result
@@ -5326,7 +4471,6 @@ function parseRuntimeAppsPage(payload) {
5326
4471
  function parseRealtimeSessionCreated(payload) {
5327
4472
  return {
5328
4473
  status: stringValue(payload.status) || "",
5329
- provider: stringValue(payload.provider) || "",
5330
4474
  model: stringValue(payload.model) || "",
5331
4475
  voice: stringValue(payload.voice) || "",
5332
4476
  mode: stringValue(payload.mode) || "",
@@ -5336,7 +4480,15 @@ function parseRealtimeSessionCreated(payload) {
5336
4480
  expiresAt: numberValue(payload.expires_at),
5337
4481
  session: asRecord(payload.session) ?? {},
5338
4482
  capabilities: asRecord(payload.capabilities) ?? {},
5339
- rawJson: { ...payload },
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
+ }),
5340
4492
  };
5341
4493
  }
5342
4494
  function parseServiceConnectionAction(payload) {
@@ -5459,12 +4611,31 @@ function resolveMaronaApiKey(explicit) {
5459
4611
  if (explicit !== undefined) {
5460
4612
  const value = cleanString(explicit);
5461
4613
  if (!value)
5462
- throw new EdgeRuntimeError(maronaApiKeyRequired);
4614
+ throw new MaronaApiKeyRequiredError(maronaApiKeyRequired, {
4615
+ code: "MARONA_API_KEY_REQUIRED",
4616
+ statusCode: 401,
4617
+ requiredAction: "CONFIGURE_MARONA_API_KEY",
4618
+ });
5463
4619
  return value;
5464
4620
  }
5465
4621
  const value = environmentValue("MARONA_API_KEY");
5466
4622
  if (!value)
5467
- throw new EdgeRuntimeError(maronaApiKeyRequired);
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
+ }
5468
4639
  return value;
5469
4640
  }
5470
4641
  function maronaHeaders(headers, apiKey) {
@@ -5495,7 +4666,11 @@ function hasMaronaApiKey(headers) {
5495
4666
  }
5496
4667
  function requireMaronaApiKey(headers) {
5497
4668
  if (!hasMaronaApiKey(headers)) {
5498
- throw new EdgeRuntimeError(maronaApiKeyRequired);
4669
+ throw new MaronaApiKeyRequiredError(maronaApiKeyRequired, {
4670
+ code: "MARONA_API_KEY_REQUIRED",
4671
+ statusCode: 401,
4672
+ requiredAction: "CONFIGURE_MARONA_API_KEY",
4673
+ });
5499
4674
  }
5500
4675
  }
5501
4676
  function isPlainObject(value) {