marona 0.4.2 → 0.5.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 +12 -0
- package/README.md +97 -172
- package/dist/index.d.ts +42 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +489 -49
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,9 +1,28 @@
|
|
|
1
|
-
export const packageVersion = "0.
|
|
1
|
+
export const packageVersion = "0.5.0";
|
|
2
2
|
export const standardInterfaces = ["api", "web", "mobile_app", "desktop", "whatsapp"];
|
|
3
3
|
export const interfaceNamePattern = "^[a-z][a-z0-9_-]{0,63}$";
|
|
4
4
|
export const standardExecutionModes = ["online", "hybrid", "offline"];
|
|
5
5
|
const localExecutionTargetTypes = new Set(["python_package", "wasm", "static_cache", "builtin"]);
|
|
6
6
|
const remoteExecutionTargetTypes = new Set(["remote_mcp", "marona_hosted"]);
|
|
7
|
+
const providerDefaultEndpoints = {
|
|
8
|
+
openai: "https://api.openai.com/v1",
|
|
9
|
+
anthropic: "https://api.anthropic.com/v1",
|
|
10
|
+
gemini: "https://generativelanguage.googleapis.com/v1beta",
|
|
11
|
+
ollama: "http://127.0.0.1:11434/v1",
|
|
12
|
+
};
|
|
13
|
+
const providerKeyEnvironment = {
|
|
14
|
+
openai: "OPENAI_API_KEY",
|
|
15
|
+
anthropic: "ANTHROPIC_API_KEY",
|
|
16
|
+
gemini: "GEMINI_API_KEY",
|
|
17
|
+
litellm: "LITELLM_API_KEY",
|
|
18
|
+
};
|
|
19
|
+
const providerEndpointEnvironment = {
|
|
20
|
+
openai: "OPENAI_API_BASE",
|
|
21
|
+
anthropic: "ANTHROPIC_API_BASE",
|
|
22
|
+
gemini: "GEMINI_API_BASE",
|
|
23
|
+
ollama: "OLLAMA_API_BASE",
|
|
24
|
+
litellm: "LITELLM_API_BASE",
|
|
25
|
+
};
|
|
7
26
|
export function normalizeExecutionModes(value) {
|
|
8
27
|
const rawModes = Array.isArray(value) ? value : ["online"];
|
|
9
28
|
const modes = [];
|
|
@@ -244,6 +263,8 @@ export class MaronaCache {
|
|
|
244
263
|
export class ModelManager {
|
|
245
264
|
cache;
|
|
246
265
|
fetchImpl;
|
|
266
|
+
executors = new Map();
|
|
267
|
+
adapters = new Map();
|
|
247
268
|
constructor(cache, fetchImpl) {
|
|
248
269
|
this.cache = cache;
|
|
249
270
|
this.fetchImpl = fetchImpl;
|
|
@@ -251,27 +272,52 @@ export class ModelManager {
|
|
|
251
272
|
async register(input) {
|
|
252
273
|
if (!input.name.trim())
|
|
253
274
|
throw new MaronaModelError("Model name is required.");
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
275
|
+
const name = input.name.trim();
|
|
276
|
+
const endpoint = input.executor
|
|
277
|
+
? `local://${name}`
|
|
278
|
+
: input.adapter
|
|
279
|
+
? (input.endpoint ?? `adapter://${name}`).replace(/\/+$/, "")
|
|
280
|
+
: (input.endpoint ?? "").replace(/\/+$/, "");
|
|
281
|
+
if (!endpoint)
|
|
282
|
+
throw new MaronaModelError("Model endpoint or executor is required.");
|
|
283
|
+
const record = {
|
|
284
|
+
name,
|
|
285
|
+
endpoint,
|
|
286
|
+
provider: cleanString(input.provider)?.toLowerCase(),
|
|
259
287
|
model: input.model,
|
|
260
|
-
protocol: input.protocol,
|
|
261
|
-
features: input.
|
|
262
|
-
|
|
263
|
-
|
|
288
|
+
protocol: input.executor ? "local_executor" : input.adapter ? "custom_adapter" : input.protocol,
|
|
289
|
+
features: input.executor || input.adapter
|
|
290
|
+
? [...new Set([...(input.features ?? []), "text", "tool_calling", "streaming"])]
|
|
291
|
+
: input.features ?? [],
|
|
292
|
+
location: input.executor ? "local" : inferLocation(endpoint),
|
|
293
|
+
status: input.executor || input.adapter ? "available" : "registered",
|
|
264
294
|
apiKey: input.apiKey,
|
|
265
295
|
metadata: input.metadata ?? {},
|
|
296
|
+
lastCheckedAt: input.executor || input.adapter ? new Date().toISOString() : undefined,
|
|
266
297
|
contextWindow: input.contextWindow,
|
|
267
298
|
maxOutputTokens: input.maxOutputTokens,
|
|
268
|
-
}
|
|
269
|
-
|
|
299
|
+
};
|
|
300
|
+
if (input.executor)
|
|
301
|
+
this.executors.set(name, input.executor);
|
|
302
|
+
if (input.adapter)
|
|
303
|
+
this.adapters.set(name, input.adapter);
|
|
304
|
+
const detected = input.executor || input.adapter ? record : await this.detect(record);
|
|
305
|
+
this.cache.saveModel(detected, { makeDefault: input.makeDefault ?? false });
|
|
270
306
|
return detected;
|
|
271
307
|
}
|
|
272
308
|
use(name) {
|
|
309
|
+
console.warn("models.use() is deprecated; pass model to client() or message().");
|
|
273
310
|
return this.cache.useModel(name);
|
|
274
311
|
}
|
|
312
|
+
get(name) {
|
|
313
|
+
return this.cache.getModel(name);
|
|
314
|
+
}
|
|
315
|
+
executor(name) {
|
|
316
|
+
return this.executors.get(name);
|
|
317
|
+
}
|
|
318
|
+
adapter(name) {
|
|
319
|
+
return this.adapters.get(name);
|
|
320
|
+
}
|
|
275
321
|
list() {
|
|
276
322
|
return this.cache.listModels();
|
|
277
323
|
}
|
|
@@ -347,6 +393,7 @@ export class HubClient {
|
|
|
347
393
|
const payload = await this.requestJson("POST", "/hub/connect", {
|
|
348
394
|
body: {
|
|
349
395
|
apps,
|
|
396
|
+
...(options.skills?.length ? { skills: options.skills } : {}),
|
|
350
397
|
adapter: options.adapter ?? "openai_mcp",
|
|
351
398
|
},
|
|
352
399
|
});
|
|
@@ -602,7 +649,7 @@ class MaronaHubClient extends HubClient {
|
|
|
602
649
|
cache;
|
|
603
650
|
async connectResult(apps, options = {}) {
|
|
604
651
|
const adapter = options.adapter ?? "tools";
|
|
605
|
-
const cached = connectFromCache(this.cache, apps, adapter, this.mode);
|
|
652
|
+
const cached = connectFromCache(this.cache, apps, options.skills ?? [], adapter, this.mode);
|
|
606
653
|
if (cached.connections.length > 0 && (this.mode === "offline" || this.mode === "hybrid")) {
|
|
607
654
|
return cached;
|
|
608
655
|
}
|
|
@@ -611,7 +658,7 @@ class MaronaHubClient extends HubClient {
|
|
|
611
658
|
payload: { missing_apps: apps },
|
|
612
659
|
});
|
|
613
660
|
}
|
|
614
|
-
return super.connectResult(apps, { adapter });
|
|
661
|
+
return super.connectResult(apps, { adapter, skills: options.skills });
|
|
615
662
|
}
|
|
616
663
|
}
|
|
617
664
|
export class RuntimeAttachment {
|
|
@@ -864,6 +911,7 @@ function isObject(value) {
|
|
|
864
911
|
}
|
|
865
912
|
export class RuntimeMessageRequest {
|
|
866
913
|
text;
|
|
914
|
+
model;
|
|
867
915
|
interfaceName;
|
|
868
916
|
userId;
|
|
869
917
|
identityToken;
|
|
@@ -875,6 +923,7 @@ export class RuntimeMessageRequest {
|
|
|
875
923
|
metadata;
|
|
876
924
|
constructor(text, options = {}) {
|
|
877
925
|
this.text = text;
|
|
926
|
+
this.model = cleanString(options.model);
|
|
878
927
|
this.interfaceName = options.interfaceName ?? options.interface ?? "api";
|
|
879
928
|
this.userId = cleanString(options.userId ?? options.user_id);
|
|
880
929
|
this.identityToken = cleanString(options.identityToken ?? options.identity_token);
|
|
@@ -895,6 +944,7 @@ export class RuntimeMessageRequest {
|
|
|
895
944
|
identity_token: this.identityToken,
|
|
896
945
|
conversation_id: this.conversationId,
|
|
897
946
|
text: this.text,
|
|
947
|
+
model: this.model,
|
|
898
948
|
developer_instructions: this.developerInstructions,
|
|
899
949
|
execute: this.execute,
|
|
900
950
|
attachments: this.attachments.map((attachment) => attachment.toJson()),
|
|
@@ -1208,14 +1258,76 @@ class RuntimeTransport {
|
|
|
1208
1258
|
return url.toString();
|
|
1209
1259
|
}
|
|
1210
1260
|
}
|
|
1261
|
+
export class ToolExecutor {
|
|
1262
|
+
baseUrl;
|
|
1263
|
+
headers;
|
|
1264
|
+
fetchImpl;
|
|
1265
|
+
constructor(baseUrl, headers, fetchImpl) {
|
|
1266
|
+
this.baseUrl = baseUrl;
|
|
1267
|
+
this.headers = headers;
|
|
1268
|
+
this.fetchImpl = fetchImpl;
|
|
1269
|
+
}
|
|
1270
|
+
async execute(tool, argumentsValue = {}, options = {}) {
|
|
1271
|
+
const normalized = normalizeConnectedTools([tool]);
|
|
1272
|
+
if (!normalized.length)
|
|
1273
|
+
throw new EdgeRuntimeError("Invalid connected tool descriptor.");
|
|
1274
|
+
const descriptor = normalized[0];
|
|
1275
|
+
const metadata = asRecord(descriptor.marona) ?? {};
|
|
1276
|
+
const fn = asRecord(descriptor.function) ?? {};
|
|
1277
|
+
if (metadata.type === "skill") {
|
|
1278
|
+
const request = stringValue(argumentsValue.request);
|
|
1279
|
+
if (!request)
|
|
1280
|
+
throw new EdgeRuntimeError("Skill execution requires a request string.");
|
|
1281
|
+
const response = await this.fetchImpl(new URL("/runtime/skills/execute", `${this.baseUrl}/`).toString(), {
|
|
1282
|
+
method: "POST",
|
|
1283
|
+
headers: { ...this.headers, "Content-Type": "application/json" },
|
|
1284
|
+
body: JSON.stringify(omitEmpty({
|
|
1285
|
+
skill_name: metadata.skill_name,
|
|
1286
|
+
request,
|
|
1287
|
+
context: {
|
|
1288
|
+
...(asRecord(argumentsValue.context) ?? {}),
|
|
1289
|
+
...(typeof argumentsValue.approved === "boolean" ? { approved: argumentsValue.approved } : {}),
|
|
1290
|
+
},
|
|
1291
|
+
interface: options.interfaceName ?? "api",
|
|
1292
|
+
identity_token: options.identityToken,
|
|
1293
|
+
conversation_id: options.conversationId,
|
|
1294
|
+
model: options.model,
|
|
1295
|
+
})),
|
|
1296
|
+
});
|
|
1297
|
+
const payload = parseMaybeJson(await response.text());
|
|
1298
|
+
if (!response.ok) {
|
|
1299
|
+
throw new EdgeRuntimeError(`Marona Skill execution failed with HTTP ${response.status}.`, {
|
|
1300
|
+
statusCode: response.status,
|
|
1301
|
+
payload,
|
|
1302
|
+
});
|
|
1303
|
+
}
|
|
1304
|
+
const record = asRecord(payload);
|
|
1305
|
+
if (!record)
|
|
1306
|
+
throw new EdgeRuntimeError("Marona Runtime returned an invalid Skill result.", { payload });
|
|
1307
|
+
return record;
|
|
1308
|
+
}
|
|
1309
|
+
return executeToolCall({
|
|
1310
|
+
id: "marona-external-tool",
|
|
1311
|
+
function: { name: fn.name, arguments: JSON.stringify(argumentsValue) },
|
|
1312
|
+
}, [descriptor], {
|
|
1313
|
+
offline: false,
|
|
1314
|
+
fetchImpl: this.fetchImpl,
|
|
1315
|
+
identityHeaders: localIdentityHeaders(options.identityToken, options.interfaceName ?? "api", options.conversationId),
|
|
1316
|
+
});
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1211
1319
|
export class Marona extends RuntimeTransport {
|
|
1212
1320
|
hub;
|
|
1213
1321
|
cache;
|
|
1214
1322
|
models;
|
|
1215
1323
|
skills;
|
|
1324
|
+
tools;
|
|
1216
1325
|
mode;
|
|
1217
1326
|
modelFetchImpl;
|
|
1218
1327
|
developerInstructions;
|
|
1328
|
+
defaultModelRoute;
|
|
1329
|
+
providerCredentials;
|
|
1330
|
+
providerEndpoints;
|
|
1219
1331
|
constructor(options = {}) {
|
|
1220
1332
|
const mode = options.mode ?? "online";
|
|
1221
1333
|
if (!["online", "offline", "hybrid"].includes(mode)) {
|
|
@@ -1225,6 +1337,9 @@ export class Marona extends RuntimeTransport {
|
|
|
1225
1337
|
this.mode = mode;
|
|
1226
1338
|
this.cache = options.cache ?? new MaronaCache();
|
|
1227
1339
|
this.developerInstructions = cleanString(options.developerInstructions ?? options.developer_instructions);
|
|
1340
|
+
this.defaultModelRoute = cleanString(options.model);
|
|
1341
|
+
this.providerCredentials = Object.fromEntries(Object.entries(options.providerCredentials ?? {}).map(([key, value]) => [key.toLowerCase(), value]));
|
|
1342
|
+
this.providerEndpoints = Object.fromEntries(Object.entries(options.providerEndpoints ?? {}).map(([key, value]) => [key.toLowerCase(), value.replace(/\/+$/, "")]));
|
|
1228
1343
|
this.modelFetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
1229
1344
|
this.models = new ModelManager(this.cache, this.modelFetchImpl);
|
|
1230
1345
|
this.hub = new MaronaHubClient(options.hubUrl ?? "https://hub.marona.ai", {
|
|
@@ -1241,6 +1356,7 @@ export class Marona extends RuntimeTransport {
|
|
|
1241
1356
|
headers: options.headers,
|
|
1242
1357
|
fetchImpl: options.hubFetchImpl ?? options.fetchImpl,
|
|
1243
1358
|
});
|
|
1359
|
+
this.tools = new ToolExecutor(this.baseUrl, this.defaultHeaders, this.modelFetchImpl);
|
|
1244
1360
|
}
|
|
1245
1361
|
setMode(mode) {
|
|
1246
1362
|
if (!['online', 'offline', 'hybrid'].includes(mode)) {
|
|
@@ -1263,39 +1379,38 @@ export class Marona extends RuntimeTransport {
|
|
|
1263
1379
|
return payload;
|
|
1264
1380
|
}
|
|
1265
1381
|
async message(text, options = {}) {
|
|
1266
|
-
const
|
|
1382
|
+
const configuredRoute = cleanString(options.model ?? this.defaultModelRoute);
|
|
1383
|
+
const legacyDefault = configuredRoute ? undefined : this.models.default();
|
|
1384
|
+
const modelRoute = configuredRoute ?? legacyDefault?.name ?? "marona/default";
|
|
1385
|
+
const model = configuredRoute ? this.resolveModel(modelRoute) : legacyDefault;
|
|
1267
1386
|
const developerInstructions = combineText([
|
|
1268
1387
|
this.developerInstructions,
|
|
1269
1388
|
options.developerInstructions ?? options.developer_instructions,
|
|
1270
1389
|
]);
|
|
1271
|
-
const messageOptions = { ...options, developerInstructions };
|
|
1272
|
-
if (this.mode === "
|
|
1273
|
-
|
|
1274
|
-
this.cacheTurn(text, response, messageOptions);
|
|
1275
|
-
return response;
|
|
1390
|
+
const messageOptions = { ...options, model: modelRoute, developerInstructions };
|
|
1391
|
+
if (this.mode === "offline" && model?.location !== "local") {
|
|
1392
|
+
throw new MaronaOfflineError(`Offline mode cannot use remote model '${modelRoute}'.`);
|
|
1276
1393
|
}
|
|
1277
|
-
if (this.mode === "online") {
|
|
1278
|
-
const response = await super.message(text, {
|
|
1279
|
-
...messageOptions,
|
|
1280
|
-
metadata: { ...(options.metadata ?? {}), ...(options.tools ? { tools: options.tools } : {}) },
|
|
1281
|
-
});
|
|
1282
|
-
this.cacheTurn(text, response, messageOptions);
|
|
1283
|
-
return response;
|
|
1284
|
-
}
|
|
1285
|
-
if (model && (model.location === "local" || this.mode === "hybrid")) {
|
|
1394
|
+
if (model && (this.mode === "online" || model.location === "local" || this.mode === "hybrid")) {
|
|
1286
1395
|
try {
|
|
1287
|
-
const response = await this.modelMessage(model, text,
|
|
1288
|
-
...messageOptions,
|
|
1289
|
-
tools: options.tools ?? [],
|
|
1290
|
-
});
|
|
1396
|
+
const response = await this.modelMessage(model, text, messageOptions);
|
|
1291
1397
|
this.cacheTurn(text, response, messageOptions);
|
|
1292
1398
|
return response;
|
|
1293
1399
|
}
|
|
1294
1400
|
catch (error) {
|
|
1295
1401
|
if (this.mode !== "hybrid")
|
|
1296
1402
|
throw error;
|
|
1403
|
+
messageOptions.model = "marona/default";
|
|
1297
1404
|
}
|
|
1298
1405
|
}
|
|
1406
|
+
if (this.mode === "online") {
|
|
1407
|
+
const response = await super.message(text, {
|
|
1408
|
+
...messageOptions,
|
|
1409
|
+
metadata: { ...(options.metadata ?? {}), ...(options.tools ? { tools: options.tools } : {}) },
|
|
1410
|
+
});
|
|
1411
|
+
this.cacheTurn(text, response, messageOptions);
|
|
1412
|
+
return response;
|
|
1413
|
+
}
|
|
1299
1414
|
if (this.mode === "offline") {
|
|
1300
1415
|
throw new MaronaOfflineError("Offline mode requires a registered local model before calling message().");
|
|
1301
1416
|
}
|
|
@@ -1306,6 +1421,63 @@ export class Marona extends RuntimeTransport {
|
|
|
1306
1421
|
this.cacheTurn(text, response, messageOptions);
|
|
1307
1422
|
return response;
|
|
1308
1423
|
}
|
|
1424
|
+
resolveModel(reference) {
|
|
1425
|
+
if (reference === "marona/default")
|
|
1426
|
+
return undefined;
|
|
1427
|
+
const registered = this.models.get(reference);
|
|
1428
|
+
if (registered)
|
|
1429
|
+
return registered;
|
|
1430
|
+
const slash = reference.indexOf("/");
|
|
1431
|
+
if (slash <= 0 || slash === reference.length - 1) {
|
|
1432
|
+
throw new MaronaModelError(`Unknown model route '${reference}'. Use provider/model or register it first.`);
|
|
1433
|
+
}
|
|
1434
|
+
const provider = reference.slice(0, slash).toLowerCase();
|
|
1435
|
+
const providerModel = reference.slice(slash + 1);
|
|
1436
|
+
if (provider === "local") {
|
|
1437
|
+
throw new MaronaModelError(`Local model '${reference}' must be registered with an executor.`);
|
|
1438
|
+
}
|
|
1439
|
+
if (!["openai", "anthropic", "gemini", "ollama", "litellm"].includes(provider)) {
|
|
1440
|
+
throw new MaronaModelError(`Custom model route '${reference}' must be registered first.`);
|
|
1441
|
+
}
|
|
1442
|
+
const endpoint = this.providerEndpoint(provider);
|
|
1443
|
+
const apiKey = this.providerKey(provider);
|
|
1444
|
+
if (["openai", "anthropic", "gemini"].includes(provider) && !apiKey) {
|
|
1445
|
+
throw new MaronaModelError(`${providerKeyEnvironment[provider]} is required for '${reference}'.`);
|
|
1446
|
+
}
|
|
1447
|
+
if (provider === "litellm" && !endpoint) {
|
|
1448
|
+
throw new MaronaModelError("LITELLM_API_BASE or a configured endpoint is required.");
|
|
1449
|
+
}
|
|
1450
|
+
return {
|
|
1451
|
+
name: reference,
|
|
1452
|
+
endpoint: endpoint ?? "",
|
|
1453
|
+
provider,
|
|
1454
|
+
model: providerModel,
|
|
1455
|
+
protocol: provider === "anthropic" ? "anthropic" : provider === "gemini" ? "gemini" : "chat_completions",
|
|
1456
|
+
features: ["text", "streaming", "native_tool_calling"],
|
|
1457
|
+
location: provider === "ollama" ? "local" : "remote",
|
|
1458
|
+
status: "available",
|
|
1459
|
+
apiKey,
|
|
1460
|
+
metadata: { route: reference },
|
|
1461
|
+
lastCheckedAt: new Date().toISOString(),
|
|
1462
|
+
};
|
|
1463
|
+
}
|
|
1464
|
+
providerKey(provider) {
|
|
1465
|
+
const configured = this.providerCredentials[provider];
|
|
1466
|
+
const value = typeof configured === "string" ? configured : configured?.apiKey;
|
|
1467
|
+
return cleanString(value) ?? environmentValue(providerKeyEnvironment[provider]);
|
|
1468
|
+
}
|
|
1469
|
+
providerEndpoint(provider) {
|
|
1470
|
+
const configured = this.providerCredentials[provider];
|
|
1471
|
+
let endpoint = this.providerEndpoints[provider]
|
|
1472
|
+
?? (typeof configured === "object" ? configured.endpoint ?? configured.baseUrl : undefined)
|
|
1473
|
+
?? environmentValue(providerEndpointEnvironment[provider])
|
|
1474
|
+
?? providerDefaultEndpoints[provider];
|
|
1475
|
+
endpoint = cleanString(endpoint)?.replace(/\/+$/, "");
|
|
1476
|
+
if (endpoint && ["openai", "ollama", "litellm"].includes(provider) && !endpoint.endsWith("/v1")) {
|
|
1477
|
+
endpoint = `${endpoint}/v1`;
|
|
1478
|
+
}
|
|
1479
|
+
return endpoint;
|
|
1480
|
+
}
|
|
1309
1481
|
async client(options) {
|
|
1310
1482
|
const { input, attachments, conversationId: _conversationId, conversation_id: _conversation_id, ...messageOptions } = options;
|
|
1311
1483
|
const normalized = runtimeMessageFromInput(input);
|
|
@@ -1350,9 +1522,9 @@ export class Marona extends RuntimeTransport {
|
|
|
1350
1522
|
role: 'system',
|
|
1351
1523
|
content: 'When the current request reads or changes app, personal, or external data, you must call marona__discover_capabilities before answering. Select exact identifiers from its installed catalog. If a record identifier is missing, discover first and use 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 discover Memory just to answer from saved context.',
|
|
1352
1524
|
});
|
|
1353
|
-
messages.push({ role: "user", content: text });
|
|
1525
|
+
messages.push({ role: "user", content: modelUserContent(text, options.attachments ?? []) });
|
|
1354
1526
|
let availableTools = options.tools?.length
|
|
1355
|
-
?
|
|
1527
|
+
? normalizeConnectedTools(options.tools)
|
|
1356
1528
|
: [capabilityDiscoveryTool(this.localCapabilityCatalog())];
|
|
1357
1529
|
let payload = {};
|
|
1358
1530
|
let reply = "";
|
|
@@ -1371,7 +1543,7 @@ export class Marona extends RuntimeTransport {
|
|
|
1371
1543
|
for (let turn = 0; turn < 8; turn += 1) {
|
|
1372
1544
|
while (true) {
|
|
1373
1545
|
try {
|
|
1374
|
-
payload = await callChatModel(model, compactMessagesForContext(messages, contextTier), compactToolsForContext(availableTools, contextTier), this.modelFetchImpl, toolChoice);
|
|
1546
|
+
payload = await callChatModel(model, compactMessagesForContext(messages, contextTier), compactToolsForContext(availableTools, contextTier), this.modelFetchImpl, toolChoice, this.models.executor(model.name), this.models.adapter(model.name));
|
|
1375
1547
|
break;
|
|
1376
1548
|
}
|
|
1377
1549
|
catch (error) {
|
|
@@ -1513,8 +1685,6 @@ export class Marona extends RuntimeTransport {
|
|
|
1513
1685
|
name: skill.name,
|
|
1514
1686
|
description: shortCatalogText(skill.description),
|
|
1515
1687
|
required_apps: skillRequiredApps(skill),
|
|
1516
|
-
managed_capabilities: skillManagedCapabilities(skill),
|
|
1517
|
-
workflow_purpose: shortCatalogText(skillManifest(skill).description),
|
|
1518
1688
|
})),
|
|
1519
1689
|
};
|
|
1520
1690
|
}
|
|
@@ -1735,6 +1905,7 @@ function modelFromJson(payload) {
|
|
|
1735
1905
|
return {
|
|
1736
1906
|
name: stringValue(payload.name) ?? "",
|
|
1737
1907
|
endpoint: stringValue(payload.endpoint) ?? "",
|
|
1908
|
+
provider: stringValue(payload.provider),
|
|
1738
1909
|
model: stringValue(payload.model),
|
|
1739
1910
|
protocol: stringValue(payload.protocol),
|
|
1740
1911
|
features: Array.isArray(payload.features) ? payload.features.map(String) : [],
|
|
@@ -1751,37 +1922,243 @@ function redactModel(model) {
|
|
|
1751
1922
|
const { apiKey: _apiKey, ...safe } = model;
|
|
1752
1923
|
return safe;
|
|
1753
1924
|
}
|
|
1754
|
-
|
|
1925
|
+
function modelUserContent(text, attachments) {
|
|
1926
|
+
if (!attachments.length)
|
|
1927
|
+
return text;
|
|
1928
|
+
const content = [{ type: "text", text }];
|
|
1929
|
+
for (const input of attachments) {
|
|
1930
|
+
const attachment = input instanceof RuntimeAttachment ? input : new RuntimeAttachment(input);
|
|
1931
|
+
const source = attachment.dataBase64
|
|
1932
|
+
? `data:${attachment.mimeType};base64,${attachment.dataBase64}`
|
|
1933
|
+
: attachment.url;
|
|
1934
|
+
if (attachment.kind === "image" && source) {
|
|
1935
|
+
content.push({ type: "image_url", image_url: { url: source }, mime_type: attachment.mimeType });
|
|
1936
|
+
}
|
|
1937
|
+
else if (attachment.text) {
|
|
1938
|
+
content.push({ type: "text", text: `File ${attachment.filename}:\n${attachment.text}` });
|
|
1939
|
+
}
|
|
1940
|
+
else {
|
|
1941
|
+
content.push({
|
|
1942
|
+
type: "file",
|
|
1943
|
+
filename: attachment.filename,
|
|
1944
|
+
mime_type: attachment.mimeType,
|
|
1945
|
+
data: attachment.dataBase64,
|
|
1946
|
+
url: attachment.url,
|
|
1947
|
+
});
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
return content;
|
|
1951
|
+
}
|
|
1952
|
+
async function callChatModel(model, messages, tools, fetchImpl, toolChoice = "auto", executor, adapter) {
|
|
1953
|
+
const request = {
|
|
1954
|
+
model: model.model ?? model.name,
|
|
1955
|
+
messages,
|
|
1956
|
+
...(modelOutputLimit(model) ? { max_tokens: modelOutputLimit(model) } : {}),
|
|
1957
|
+
...(tools.length
|
|
1958
|
+
? {
|
|
1959
|
+
tools: tools.map((tool) => asRecord(tool.function) ? { type: "function", function: tool.function } : tool),
|
|
1960
|
+
tool_choice: toolChoice,
|
|
1961
|
+
}
|
|
1962
|
+
: {}),
|
|
1963
|
+
};
|
|
1964
|
+
const handler = model.protocol === "local_executor" ? executor : model.protocol === "custom_adapter" ? adapter : undefined;
|
|
1965
|
+
if (handler) {
|
|
1966
|
+
const payload = await handler(request);
|
|
1967
|
+
const record = asRecord(payload);
|
|
1968
|
+
if (!record)
|
|
1969
|
+
throw new MaronaModelError(`Local model '${model.name}' returned a non-JSON response.`, { payload });
|
|
1970
|
+
return record;
|
|
1971
|
+
}
|
|
1972
|
+
if (model.protocol === "local_executor" || model.protocol === "custom_adapter") {
|
|
1973
|
+
throw new MaronaModelError(`Model '${model.name}' has no registered adapter.`);
|
|
1974
|
+
}
|
|
1975
|
+
if (model.protocol === "anthropic" || model.provider === "anthropic") {
|
|
1976
|
+
return callAnthropicModel(model, messages, tools, fetchImpl, toolChoice);
|
|
1977
|
+
}
|
|
1978
|
+
if (model.protocol === "gemini" || model.provider === "gemini") {
|
|
1979
|
+
return callGeminiModel(model, messages, tools, fetchImpl, toolChoice);
|
|
1980
|
+
}
|
|
1755
1981
|
if (model.protocol && !["chat_completions", "custom_http"].includes(model.protocol)) {
|
|
1756
1982
|
throw new MaronaModelError(`Model '${model.name}' does not support chat messages yet.`);
|
|
1757
1983
|
}
|
|
1758
1984
|
const response = await fetchImpl(`${model.endpoint.replace(/\/+$/, "")}/chat/completions`, {
|
|
1759
1985
|
method: "POST",
|
|
1760
1986
|
headers: modelHeaders(model),
|
|
1987
|
+
body: JSON.stringify(request),
|
|
1988
|
+
});
|
|
1989
|
+
const text = await response.text();
|
|
1990
|
+
const payload = parseMaybeJson(text);
|
|
1991
|
+
if (!response.ok) {
|
|
1992
|
+
throw new MaronaModelError(`Local model request failed with HTTP ${response.status}.`, {
|
|
1993
|
+
statusCode: response.status,
|
|
1994
|
+
payload,
|
|
1995
|
+
});
|
|
1996
|
+
}
|
|
1997
|
+
const record = asRecord(payload);
|
|
1998
|
+
if (!record)
|
|
1999
|
+
throw new MaronaModelError("Local model returned a non-JSON response.", { payload });
|
|
2000
|
+
return record;
|
|
2001
|
+
}
|
|
2002
|
+
async function callAnthropicModel(model, messages, tools, fetchImpl, toolChoice) {
|
|
2003
|
+
const system = messages
|
|
2004
|
+
.filter((message) => message.role === "system")
|
|
2005
|
+
.map((message) => contentText(message.content))
|
|
2006
|
+
.filter(Boolean)
|
|
2007
|
+
.join("\n\n");
|
|
2008
|
+
const anthropicMessages = messages
|
|
2009
|
+
.filter((message) => message.role !== "system" && (message.role === "user" || message.role === "assistant"))
|
|
2010
|
+
.map((message) => ({ role: message.role, content: anthropicContent(message.content) }));
|
|
2011
|
+
const response = await fetchImpl(`${model.endpoint.replace(/\/+$/, "")}/messages`, {
|
|
2012
|
+
method: "POST",
|
|
2013
|
+
headers: {
|
|
2014
|
+
"Content-Type": "application/json",
|
|
2015
|
+
"anthropic-version": "2023-06-01",
|
|
2016
|
+
...(model.apiKey ? { "x-api-key": model.apiKey } : {}),
|
|
2017
|
+
},
|
|
1761
2018
|
body: JSON.stringify({
|
|
1762
2019
|
model: model.model ?? model.name,
|
|
1763
|
-
|
|
1764
|
-
|
|
2020
|
+
system: system || undefined,
|
|
2021
|
+
messages: anthropicMessages,
|
|
2022
|
+
max_tokens: modelOutputLimit(model) ?? 1024,
|
|
1765
2023
|
...(tools.length
|
|
1766
2024
|
? {
|
|
1767
|
-
tools: tools.map((tool) =>
|
|
1768
|
-
|
|
2025
|
+
tools: tools.map((tool) => {
|
|
2026
|
+
const fn = asRecord(tool.function) ?? tool;
|
|
2027
|
+
return {
|
|
2028
|
+
name: fn.name,
|
|
2029
|
+
description: fn.description,
|
|
2030
|
+
input_schema: fn.parameters ?? { type: "object", properties: {} },
|
|
2031
|
+
};
|
|
2032
|
+
}),
|
|
2033
|
+
tool_choice: toolChoice === "required" ? { type: "any" } : { type: "auto" },
|
|
1769
2034
|
}
|
|
1770
2035
|
: {}),
|
|
1771
2036
|
}),
|
|
1772
2037
|
});
|
|
1773
|
-
const
|
|
1774
|
-
const payload = parseMaybeJson(text);
|
|
2038
|
+
const payload = parseMaybeJson(await response.text());
|
|
1775
2039
|
if (!response.ok) {
|
|
1776
|
-
throw new MaronaModelError(`
|
|
2040
|
+
throw new MaronaModelError(`Anthropic model request failed with HTTP ${response.status}.`, {
|
|
1777
2041
|
statusCode: response.status,
|
|
1778
2042
|
payload,
|
|
1779
2043
|
});
|
|
1780
2044
|
}
|
|
1781
2045
|
const record = asRecord(payload);
|
|
1782
2046
|
if (!record)
|
|
1783
|
-
throw new MaronaModelError("
|
|
1784
|
-
|
|
2047
|
+
throw new MaronaModelError("Anthropic returned a non-JSON response.", { payload });
|
|
2048
|
+
const blocks = Array.isArray(record.content) ? record.content.map(asRecord).filter(Boolean) : [];
|
|
2049
|
+
const text = blocks.filter((block) => block.type === "text").map((block) => stringValue(block.text)).filter(Boolean).join("\n");
|
|
2050
|
+
const toolCalls = blocks.filter((block) => block.type === "tool_use").map((block) => ({
|
|
2051
|
+
id: block.id,
|
|
2052
|
+
type: "function",
|
|
2053
|
+
function: { name: block.name, arguments: JSON.stringify(asRecord(block.input) ?? {}) },
|
|
2054
|
+
}));
|
|
2055
|
+
return { choices: [{ message: { role: "assistant", content: text, ...(toolCalls.length ? { tool_calls: toolCalls } : {}) } }], raw_provider_response: record };
|
|
2056
|
+
}
|
|
2057
|
+
async function callGeminiModel(model, messages, tools, fetchImpl, toolChoice) {
|
|
2058
|
+
const system = messages
|
|
2059
|
+
.filter((message) => message.role === "system")
|
|
2060
|
+
.map((message) => contentText(message.content))
|
|
2061
|
+
.filter(Boolean)
|
|
2062
|
+
.join("\n\n");
|
|
2063
|
+
const contents = messages
|
|
2064
|
+
.filter((message) => message.role !== "system" && (message.role === "user" || message.role === "assistant"))
|
|
2065
|
+
.map((message) => ({ role: message.role === "assistant" ? "model" : "user", parts: geminiParts(message.content) }));
|
|
2066
|
+
const endpoint = `${model.endpoint.replace(/\/+$/, "")}/models/${encodeURIComponent(model.model ?? model.name)}:generateContent`;
|
|
2067
|
+
const url = new URL(endpoint);
|
|
2068
|
+
if (model.apiKey)
|
|
2069
|
+
url.searchParams.set("key", model.apiKey);
|
|
2070
|
+
const response = await fetchImpl(url.toString(), {
|
|
2071
|
+
method: "POST",
|
|
2072
|
+
headers: { "Content-Type": "application/json" },
|
|
2073
|
+
body: JSON.stringify({
|
|
2074
|
+
...(system ? { systemInstruction: { parts: [{ text: system }] } } : {}),
|
|
2075
|
+
contents,
|
|
2076
|
+
...(tools.length
|
|
2077
|
+
? {
|
|
2078
|
+
tools: [{ functionDeclarations: tools.map((tool) => {
|
|
2079
|
+
const fn = asRecord(tool.function) ?? tool;
|
|
2080
|
+
return { name: fn.name, description: fn.description, parameters: fn.parameters ?? { type: "object", properties: {} } };
|
|
2081
|
+
}) }],
|
|
2082
|
+
toolConfig: { functionCallingConfig: { mode: toolChoice === "required" ? "ANY" : "AUTO" } },
|
|
2083
|
+
}
|
|
2084
|
+
: {}),
|
|
2085
|
+
...(modelOutputLimit(model) ? { generationConfig: { maxOutputTokens: modelOutputLimit(model) } } : {}),
|
|
2086
|
+
}),
|
|
2087
|
+
});
|
|
2088
|
+
const payload = parseMaybeJson(await response.text());
|
|
2089
|
+
if (!response.ok) {
|
|
2090
|
+
throw new MaronaModelError(`Gemini model request failed with HTTP ${response.status}.`, {
|
|
2091
|
+
statusCode: response.status,
|
|
2092
|
+
payload,
|
|
2093
|
+
});
|
|
2094
|
+
}
|
|
2095
|
+
const record = asRecord(payload);
|
|
2096
|
+
if (!record)
|
|
2097
|
+
throw new MaronaModelError("Gemini returned a non-JSON response.", { payload });
|
|
2098
|
+
const candidates = Array.isArray(record.candidates) ? record.candidates : [];
|
|
2099
|
+
const content = asRecord(asRecord(candidates[0])?.content);
|
|
2100
|
+
const parts = Array.isArray(content?.parts) ? content.parts.map(asRecord).filter(Boolean) : [];
|
|
2101
|
+
const text = parts.map((part) => stringValue(part.text)).filter(Boolean).join("\n");
|
|
2102
|
+
const toolCalls = parts.map((part, index) => asRecord(part.functionCall) ? ({
|
|
2103
|
+
id: `gemini-call-${index}`,
|
|
2104
|
+
type: "function",
|
|
2105
|
+
function: {
|
|
2106
|
+
name: asRecord(part.functionCall)?.name,
|
|
2107
|
+
arguments: JSON.stringify(asRecord(asRecord(part.functionCall)?.args) ?? {}),
|
|
2108
|
+
},
|
|
2109
|
+
}) : undefined).filter(Boolean);
|
|
2110
|
+
return { choices: [{ message: { role: "assistant", content: text, ...(toolCalls.length ? { tool_calls: toolCalls } : {}) } }], raw_provider_response: record };
|
|
2111
|
+
}
|
|
2112
|
+
function anthropicContent(content) {
|
|
2113
|
+
if (typeof content === "string")
|
|
2114
|
+
return content;
|
|
2115
|
+
if (!Array.isArray(content))
|
|
2116
|
+
return String(content ?? "");
|
|
2117
|
+
return content.map((raw) => {
|
|
2118
|
+
const block = asRecord(raw);
|
|
2119
|
+
if (!block)
|
|
2120
|
+
return { type: "text", text: String(raw) };
|
|
2121
|
+
if (block.type === "image_url") {
|
|
2122
|
+
const image = asRecord(block.image_url);
|
|
2123
|
+
const data = dataUriParts(stringValue(image?.url) ?? "");
|
|
2124
|
+
if (data.dataBase64)
|
|
2125
|
+
return { type: "image", source: { type: "base64", media_type: data.mimeType, data: data.dataBase64 } };
|
|
2126
|
+
}
|
|
2127
|
+
if (block.type === "file") {
|
|
2128
|
+
const data = stringValue(block.data);
|
|
2129
|
+
if (data)
|
|
2130
|
+
return { type: "document", source: { type: "base64", media_type: block.mime_type, data }, title: block.filename };
|
|
2131
|
+
}
|
|
2132
|
+
return { type: "text", text: stringValue(block.text) ?? JSON.stringify(block) };
|
|
2133
|
+
});
|
|
2134
|
+
}
|
|
2135
|
+
function geminiParts(content) {
|
|
2136
|
+
if (typeof content === "string")
|
|
2137
|
+
return [{ text: content }];
|
|
2138
|
+
if (!Array.isArray(content))
|
|
2139
|
+
return [{ text: String(content ?? "") }];
|
|
2140
|
+
return content.map((raw) => {
|
|
2141
|
+
const block = asRecord(raw);
|
|
2142
|
+
if (!block)
|
|
2143
|
+
return { text: String(raw) };
|
|
2144
|
+
if (block.type === "image_url") {
|
|
2145
|
+
const url = stringValue(asRecord(block.image_url)?.url);
|
|
2146
|
+
const data = dataUriParts(url ?? "");
|
|
2147
|
+
if (data.dataBase64)
|
|
2148
|
+
return { inlineData: { mimeType: data.mimeType, data: data.dataBase64 } };
|
|
2149
|
+
if (url)
|
|
2150
|
+
return { fileData: { mimeType: block.mime_type ?? "image/*", fileUri: url } };
|
|
2151
|
+
}
|
|
2152
|
+
if (block.type === "file") {
|
|
2153
|
+
const data = stringValue(block.data);
|
|
2154
|
+
if (data)
|
|
2155
|
+
return { inlineData: { mimeType: block.mime_type, data } };
|
|
2156
|
+
const url = stringValue(block.url);
|
|
2157
|
+
if (url)
|
|
2158
|
+
return { fileData: { mimeType: block.mime_type, fileUri: url } };
|
|
2159
|
+
}
|
|
2160
|
+
return { text: stringValue(block.text) ?? JSON.stringify(block) };
|
|
2161
|
+
});
|
|
1785
2162
|
}
|
|
1786
2163
|
function modelOutputLimit(model) {
|
|
1787
2164
|
if (model.contextWindow && model.contextWindow <= 2048) {
|
|
@@ -2288,7 +2665,7 @@ function firstItems(value, count) {
|
|
|
2288
2665
|
function lastItems(value, count) {
|
|
2289
2666
|
return Array.isArray(value) ? value.slice(-count) : [];
|
|
2290
2667
|
}
|
|
2291
|
-
function connectFromCache(cache, apps, adapter, mode) {
|
|
2668
|
+
function connectFromCache(cache, apps, skills, adapter, mode) {
|
|
2292
2669
|
const connections = [];
|
|
2293
2670
|
const resolvedApps = [];
|
|
2294
2671
|
const missingApps = [];
|
|
@@ -2318,13 +2695,25 @@ function connectFromCache(cache, apps, adapter, mode) {
|
|
|
2318
2695
|
});
|
|
2319
2696
|
}
|
|
2320
2697
|
}
|
|
2698
|
+
const sync = cache.loadSyncPayload() ?? {};
|
|
2699
|
+
const availableSkills = Array.isArray(sync.available_skills)
|
|
2700
|
+
? sync.available_skills.map(asRecord).filter(Boolean)
|
|
2701
|
+
: [];
|
|
2702
|
+
const resolvedSkills = availableSkills.filter((skill) => {
|
|
2703
|
+
const name = stringValue(skill.name) ?? stringValue(skill.slug);
|
|
2704
|
+
return Boolean(name && skills.includes(name));
|
|
2705
|
+
});
|
|
2706
|
+
connections.push(...resolvedSkills.map(skillToolFromSync));
|
|
2707
|
+
const missingSkills = skills.filter((slug) => !resolvedSkills.some((skill) => (stringValue(skill.name) ?? stringValue(skill.slug)) === slug));
|
|
2321
2708
|
return {
|
|
2322
2709
|
status: connections.length ? "connected" : "missing",
|
|
2323
2710
|
adapter,
|
|
2324
2711
|
execution: "cache",
|
|
2325
2712
|
connections,
|
|
2326
2713
|
apps: resolvedApps,
|
|
2714
|
+
skills: resolvedSkills,
|
|
2327
2715
|
missing_apps: missingApps,
|
|
2716
|
+
missing_skills: missingSkills,
|
|
2328
2717
|
billing: { uses_marona_runtime: false },
|
|
2329
2718
|
};
|
|
2330
2719
|
}
|
|
@@ -2449,6 +2838,51 @@ function toolsFromApp(app, url, options = {}) {
|
|
|
2449
2838
|
};
|
|
2450
2839
|
});
|
|
2451
2840
|
}
|
|
2841
|
+
function skillToolFromSync(skill) {
|
|
2842
|
+
const slug = stringValue(skill.name) ?? stringValue(skill.slug) ?? "skill";
|
|
2843
|
+
return {
|
|
2844
|
+
type: "function",
|
|
2845
|
+
function: {
|
|
2846
|
+
name: `skill__${slug}`.replaceAll("-", "_"),
|
|
2847
|
+
description: stringValue(skill.description) ?? slug,
|
|
2848
|
+
parameters: {
|
|
2849
|
+
type: "object",
|
|
2850
|
+
properties: {
|
|
2851
|
+
request: { type: "string" },
|
|
2852
|
+
context: { type: "object", additionalProperties: true },
|
|
2853
|
+
approved: { type: "boolean" },
|
|
2854
|
+
},
|
|
2855
|
+
required: ["request"],
|
|
2856
|
+
},
|
|
2857
|
+
},
|
|
2858
|
+
marona: {
|
|
2859
|
+
type: "skill",
|
|
2860
|
+
skill_name: slug,
|
|
2861
|
+
version: skill.version,
|
|
2862
|
+
required_apps: skillRequiredApps(skill),
|
|
2863
|
+
execution_modes: skill.execution_modes ?? ["online"],
|
|
2864
|
+
execution: "marona_runtime",
|
|
2865
|
+
},
|
|
2866
|
+
};
|
|
2867
|
+
}
|
|
2868
|
+
function normalizeConnectedTools(tools) {
|
|
2869
|
+
return tools.flatMap((tool) => {
|
|
2870
|
+
if (asRecord(tool.function))
|
|
2871
|
+
return [tool];
|
|
2872
|
+
const name = stringValue(tool.name);
|
|
2873
|
+
if (!name)
|
|
2874
|
+
return [];
|
|
2875
|
+
return [{
|
|
2876
|
+
type: "function",
|
|
2877
|
+
function: {
|
|
2878
|
+
name,
|
|
2879
|
+
description: stringValue(tool.description) ?? name,
|
|
2880
|
+
parameters: asRecord(tool.parameters) ?? { type: "object", properties: {} },
|
|
2881
|
+
},
|
|
2882
|
+
marona: asRecord(tool.x_marona) ?? {},
|
|
2883
|
+
}];
|
|
2884
|
+
});
|
|
2885
|
+
}
|
|
2452
2886
|
function parseRuntimeUI(payload) {
|
|
2453
2887
|
return {
|
|
2454
2888
|
version: stringValue(payload.version) || "1.0",
|
|
@@ -2646,6 +3080,12 @@ function listOfRecords(value) {
|
|
|
2646
3080
|
function cleanString(value) {
|
|
2647
3081
|
return typeof value === "string" && value.trim() ? value : undefined;
|
|
2648
3082
|
}
|
|
3083
|
+
function environmentValue(name) {
|
|
3084
|
+
if (!name)
|
|
3085
|
+
return undefined;
|
|
3086
|
+
const processValue = globalThis.process;
|
|
3087
|
+
return cleanString(processValue?.env?.[name]);
|
|
3088
|
+
}
|
|
2649
3089
|
function stringValue(value) {
|
|
2650
3090
|
if (value === undefined || value === null)
|
|
2651
3091
|
return undefined;
|