marona 0.3.10 → 0.3.18

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,7 +1,9 @@
1
- export const packageVersion = "0.3.1";
1
+ export const packageVersion = "0.3.18";
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
+ const localExecutionTargetTypes = new Set(["python_package", "wasm", "static_cache", "builtin"]);
6
+ const remoteExecutionTargetTypes = new Set(["remote_mcp", "marona_hosted"]);
5
7
  export function normalizeExecutionModes(value) {
6
8
  const rawModes = Array.isArray(value) ? value : ["online"];
7
9
  const modes = [];
@@ -462,14 +464,12 @@ class MaronaHubClient extends HubClient {
462
464
  super(baseUrl, options);
463
465
  this.mode = options.mode;
464
466
  this.cache = options.cache;
465
- this.localGatewayUrl = cleanUrl(options.localGatewayUrl ?? options.local_gateway_url);
466
467
  }
467
468
  mode;
468
469
  cache;
469
- localGatewayUrl;
470
470
  async connectResult(apps, options = {}) {
471
471
  const adapter = options.adapter ?? "tools";
472
- const cached = connectFromCache(this.cache, apps, adapter, this.mode, this.localGatewayUrl);
472
+ const cached = connectFromCache(this.cache, apps, adapter, this.mode);
473
473
  if (cached.connections.length > 0 && (this.mode === "offline" || this.mode === "hybrid")) {
474
474
  return cached;
475
475
  }
@@ -1083,7 +1083,6 @@ export class Marona extends RuntimeTransport {
1083
1083
  mode;
1084
1084
  modelFetchImpl;
1085
1085
  developerInstructions;
1086
- localGatewayUrl;
1087
1086
  constructor(options = {}) {
1088
1087
  const mode = options.mode ?? "online";
1089
1088
  if (!["online", "offline", "hybrid"].includes(mode)) {
@@ -1093,8 +1092,6 @@ export class Marona extends RuntimeTransport {
1093
1092
  this.mode = mode;
1094
1093
  this.cache = options.cache ?? new MaronaCache();
1095
1094
  this.developerInstructions = cleanString(options.developerInstructions ?? options.developer_instructions);
1096
- this.localGatewayUrl =
1097
- cleanUrl(options.localGatewayUrl ?? options.local_gateway_url) ?? defaultLocalGatewayUrl(this.baseUrl);
1098
1095
  this.modelFetchImpl = options.fetchImpl ?? globalThis.fetch;
1099
1096
  this.models = new ModelManager(this.cache, this.modelFetchImpl);
1100
1097
  this.hub = new MaronaHubClient(options.hubUrl ?? "https://hub.marona.ai", {
@@ -1104,7 +1101,6 @@ export class Marona extends RuntimeTransport {
1104
1101
  fetchImpl: options.hubFetchImpl ?? options.fetchImpl,
1105
1102
  mode,
1106
1103
  cache: this.cache,
1107
- localGatewayUrl: this.localGatewayUrl,
1108
1104
  });
1109
1105
  this.skills = new SkillsClient(options.hubUrl ?? 'https://hub.marona.ai', {
1110
1106
  apiKey: options.apiKey,
@@ -1141,7 +1137,7 @@ export class Marona extends RuntimeTransport {
1141
1137
  ]);
1142
1138
  const messageOptions = { ...options, developerInstructions };
1143
1139
  if (this.mode === "online" && model?.location === "remote") {
1144
- const response = await this.localMessage(model, text, messageOptions);
1140
+ const response = await this.modelMessage(model, text, messageOptions);
1145
1141
  this.cacheTurn(text, response, messageOptions);
1146
1142
  return response;
1147
1143
  }
@@ -1155,7 +1151,7 @@ export class Marona extends RuntimeTransport {
1155
1151
  }
1156
1152
  if (model && (model.location === "local" || this.mode === "hybrid")) {
1157
1153
  try {
1158
- const response = await this.localMessage(model, text, {
1154
+ const response = await this.modelMessage(model, text, {
1159
1155
  ...messageOptions,
1160
1156
  tools: options.tools ?? [],
1161
1157
  });
@@ -1189,11 +1185,11 @@ export class Marona extends RuntimeTransport {
1189
1185
  attachments: [...normalized.attachments, ...(attachments ?? [])],
1190
1186
  });
1191
1187
  }
1192
- async localMessage(model, text, options) {
1188
+ async modelMessage(model, text, options) {
1193
1189
  const messages = [
1194
1190
  {
1195
1191
  role: "system",
1196
- content: "Marona local runtime. Answer the current request naturally. Use context only when relevant and never continue an old task. Discover and call an App or Skill when needed. Say when something is unavailable offline.",
1192
+ 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.",
1197
1193
  },
1198
1194
  ...(options.developerInstructions || options.developer_instructions
1199
1195
  ? [
@@ -1219,18 +1215,21 @@ export class Marona extends RuntimeTransport {
1219
1215
  }
1220
1216
  messages.push({
1221
1217
  role: 'system',
1222
- 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. Do not ask the user to confirm use of a capability. Ordinary conversation that needs no capability should be answered directly.',
1218
+ 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.',
1223
1219
  });
1224
1220
  messages.push({ role: "user", content: text });
1225
- if (!options.tools?.length && !model.features.includes('native_tool_calling')) {
1226
- return this.localMessageWithPromptPlanning(model, messages, text, options);
1227
- }
1228
- const availableTools = options.tools?.length
1221
+ let availableTools = options.tools?.length
1229
1222
  ? [...options.tools]
1230
1223
  : [capabilityDiscoveryTool(this.localCapabilityCatalog())];
1231
1224
  let payload = {};
1232
1225
  let reply = "";
1233
1226
  const toolResults = [];
1227
+ const modelResponses = [];
1228
+ const runtimeSteps = [];
1229
+ const executedCapabilityCalls = new Map();
1230
+ let toolChoice = "required";
1231
+ let emptyDiscoveries = 0;
1232
+ let hasExecutedCapability = false;
1234
1233
  let contextTier = model.contextWindow !== undefined && model.contextWindow <= 2048
1235
1234
  ? 2
1236
1235
  : model.contextWindow !== undefined && model.contextWindow <= 4096
@@ -1239,7 +1238,7 @@ export class Marona extends RuntimeTransport {
1239
1238
  for (let turn = 0; turn < 8; turn += 1) {
1240
1239
  while (true) {
1241
1240
  try {
1242
- payload = await callChatModel(model, compactMessagesForContext(messages, contextTier), compactToolsForContext(availableTools, contextTier), this.modelFetchImpl);
1241
+ payload = await callChatModel(model, compactMessagesForContext(messages, contextTier), compactToolsForContext(availableTools, contextTier), this.modelFetchImpl, toolChoice);
1243
1242
  break;
1244
1243
  }
1245
1244
  catch (error) {
@@ -1248,6 +1247,7 @@ export class Marona extends RuntimeTransport {
1248
1247
  contextTier += 1;
1249
1248
  }
1250
1249
  }
1250
+ modelResponses.push(payload);
1251
1251
  reply = modelText(payload);
1252
1252
  const toolCalls = modelToolCalls(payload);
1253
1253
  if (!toolCalls.length || !availableTools.length)
@@ -1256,19 +1256,62 @@ export class Marona extends RuntimeTransport {
1256
1256
  for (const call of toolCalls) {
1257
1257
  if (toolCallName(call) === 'marona__discover_capabilities') {
1258
1258
  const discovery = this.discoverLocalCapabilities(call);
1259
- mergeTools(availableTools, discovery.tools);
1259
+ availableTools = [capabilityDiscoveryTool(this.localCapabilityCatalog()), ...discovery.tools];
1260
+ if (discovery.tools.length) {
1261
+ toolChoice = "required";
1262
+ }
1263
+ else {
1264
+ emptyDiscoveries += 1;
1265
+ toolChoice = hasExecutedCapability || emptyDiscoveries >= 2 ? "auto" : "required";
1266
+ }
1267
+ runtimeSteps.push(discovery.result);
1260
1268
  roundResults.push(discovery.result);
1261
1269
  continue;
1262
1270
  }
1271
+ const callName = toolCallName(call);
1272
+ const callArguments = toolCallArguments(call);
1273
+ const callKey = `${callName}:${JSON.stringify(callArguments)}`;
1274
+ const previousResult = executedCapabilityCalls.get(callKey);
1275
+ if (previousResult) {
1276
+ const repeatedResult = {
1277
+ status: "completed",
1278
+ success: true,
1279
+ tool_name: callName,
1280
+ arguments: callArguments,
1281
+ result: {
1282
+ status: "already_executed",
1283
+ message: "This exact capability call already ran in the current request. Use its existing result to answer the user.",
1284
+ previous_result: toolResultForModel(previousResult),
1285
+ },
1286
+ };
1287
+ runtimeSteps.push(repeatedResult);
1288
+ roundResults.push(repeatedResult);
1289
+ availableTools = [];
1290
+ toolChoice = "auto";
1291
+ continue;
1292
+ }
1263
1293
  const result = await executeToolCall(call, availableTools, {
1264
1294
  offline: this.mode === "offline",
1265
1295
  fetchImpl: this.modelFetchImpl,
1266
1296
  identityHeaders: localIdentityHeaders(options.identityToken ?? options.identity_token, options.interfaceName ?? options.interface ?? "api", options.conversationId ?? options.conversation_id),
1267
1297
  });
1298
+ executedCapabilityCalls.set(callKey, result);
1268
1299
  toolResults.push(result);
1300
+ runtimeSteps.push(result);
1301
+ availableTools = [capabilityDiscoveryTool(this.localCapabilityCatalog())];
1302
+ toolChoice = "auto";
1303
+ emptyDiscoveries = 0;
1304
+ hasExecutedCapability = true;
1269
1305
  roundResults.push(result);
1270
1306
  }
1271
- messages.push(assistantToolMessage(payload), ...roundResults.map(toolResultMessage));
1307
+ messages.push({
1308
+ role: "system",
1309
+ content: `Marona Runtime results from the previous model-selected calls:\n${JSON.stringify(roundResults.map(toolResultForModel))}\n` +
1310
+ "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.",
1311
+ });
1312
+ }
1313
+ if (toolResults.length && !reply) {
1314
+ reply = toolResultDisplayText(toolResults.at(-1));
1272
1315
  }
1273
1316
  return {
1274
1317
  status: "completed",
@@ -1289,148 +1332,11 @@ export class Marona extends RuntimeTransport {
1289
1332
  .map((tool) => stringValue(asRecord(tool.function)?.name))
1290
1333
  .filter(Boolean),
1291
1334
  model_response: payload,
1335
+ model_responses: modelResponses,
1336
+ ...(runtimeSteps.length ? { runtime_steps: runtimeSteps } : {}),
1292
1337
  },
1293
1338
  };
1294
1339
  }
1295
- async localMessageWithPromptPlanning(model, messages, text, options) {
1296
- const catalog = this.localCapabilityCatalog();
1297
- const planningMessages = [
1298
- ...messages.slice(0, -1),
1299
- {
1300
- role: 'system',
1301
- content: 'Decide how to handle only the current user request. Return only JSON. For ordinary conversation return {"action":"respond","response":"natural answer"}. When app data or an app action is needed return {"action":"discover","app_slugs":["exact-id"],"skill_names":["exact-id"]}. Prefer the most specific dedicated capability over a general-purpose capability. Select only identifiers from this installed catalog: ' +
1302
- JSON.stringify(catalog),
1303
- },
1304
- ...messages.slice(-1),
1305
- ];
1306
- let decisionPayload = {};
1307
- let decision = {};
1308
- for (let attempt = 0; attempt < 3; attempt += 1) {
1309
- decisionPayload = await callChatModel(model, planningMessages, [], this.modelFetchImpl);
1310
- decision = modelJsonObject(decisionPayload);
1311
- if (decision.action === 'respond' || decision.action === 'discover')
1312
- break;
1313
- if (!('action' in decision))
1314
- break;
1315
- if (attempt < 2) {
1316
- planningMessages.push({ role: 'assistant', content: modelText(decisionPayload) }, {
1317
- role: 'system',
1318
- content: "Invalid decision. The action must be exactly 'respond' or 'discover'. Return only a corrected JSON object and select the capability that directly satisfies the request.",
1319
- });
1320
- }
1321
- }
1322
- const appIds = new Set((Array.isArray(catalog.apps) ? catalog.apps : [])
1323
- .map(asRecord)
1324
- .filter((item) => item !== undefined)
1325
- .map((item) => stringValue(item.slug))
1326
- .filter((item) => Boolean(item)));
1327
- const skillIds = new Set((Array.isArray(catalog.skills) ? catalog.skills : [])
1328
- .map(asRecord)
1329
- .filter((item) => item !== undefined)
1330
- .map((item) => stringValue(item.name))
1331
- .filter((item) => Boolean(item)));
1332
- const selectedAction = stringValue(decision.action);
1333
- if (selectedAction && appIds.has(selectedAction)) {
1334
- decision = { ...decision, action: 'discover', app_slugs: [selectedAction] };
1335
- }
1336
- else if (selectedAction && skillIds.has(selectedAction)) {
1337
- decision = { ...decision, action: 'discover', skill_names: [selectedAction] };
1338
- }
1339
- if (decision.action !== 'discover') {
1340
- const reply = stringValue(decision.response) ?? (modelText(decisionPayload) || 'Done.');
1341
- return localRuntimeResponse(model, options, reply, decisionPayload);
1342
- }
1343
- const discovery = this.discoverLocalCapabilities({
1344
- id: 'discover_1',
1345
- type: 'function',
1346
- function: {
1347
- name: 'marona__discover_capabilities',
1348
- arguments: JSON.stringify({
1349
- query: text,
1350
- app_slugs: stringList(decision.app_slugs),
1351
- skill_names: stringList(decision.skill_names),
1352
- }),
1353
- },
1354
- });
1355
- if (!discovery.tools.length) {
1356
- return localRuntimeResponse(model, options, 'That capability is not available offline on this device.', decisionPayload);
1357
- }
1358
- const agentMessages = [
1359
- ...messages,
1360
- {
1361
- role: 'system',
1362
- content: `Selected capability workflow:\n${JSON.stringify(asRecord(discovery.result.result) ?? {})}`,
1363
- },
1364
- ];
1365
- const toolResults = [];
1366
- const executedCalls = new Set();
1367
- let finalPayload = decisionPayload;
1368
- let reply = '';
1369
- for (let turn = 0; turn < 8; turn += 1) {
1370
- finalPayload = await callChatModel(model, [
1371
- ...agentMessages,
1372
- {
1373
- role: 'system',
1374
- content: 'Continue the current task. Return only JSON. To execute one function return {"action":"tool","tool_name":"exact_name","arguments":{}}. When no further function is needed return {"action":"respond","response":"natural answer"}. Never invent a function. Available functions: ' +
1375
- JSON.stringify(discovery.tools.map((tool) => asRecord(tool.function) ? { type: 'function', function: tool.function } : tool)),
1376
- },
1377
- ], [], this.modelFetchImpl);
1378
- let toolDecision = modelJsonObject(finalPayload);
1379
- const toolNames = new Set(discovery.tools.map(toolFunctionName));
1380
- const selectedAction = stringValue(toolDecision.action);
1381
- if (selectedAction && toolNames.has(selectedAction)) {
1382
- toolDecision = { ...toolDecision, action: 'tool', tool_name: selectedAction };
1383
- }
1384
- if (toolDecision.action !== 'tool') {
1385
- reply = stringValue(toolDecision.response) ?? '';
1386
- if (toolResults.length && toolResultRequiresExactDisplay(toolResults.at(-1))) {
1387
- reply = toolResultDisplayText(toolResults.at(-1));
1388
- }
1389
- else if (!reply && toolResults.length)
1390
- reply = toolResultDisplayText(toolResults.at(-1));
1391
- if (!reply)
1392
- reply = modelText(finalPayload);
1393
- break;
1394
- }
1395
- const name = stringValue(toolDecision.tool_name) ?? '';
1396
- if (!toolNames.has(name)) {
1397
- agentMessages.push({
1398
- role: 'system',
1399
- content: `Rejected unknown function '${name}'. Select an exact available name.`,
1400
- });
1401
- continue;
1402
- }
1403
- const args = asRecord(toolDecision.arguments) ?? {};
1404
- const signature = `${name}:${JSON.stringify(args)}`;
1405
- if (executedCalls.has(signature)) {
1406
- reply = toolResults.length ? toolResultDisplayText(toolResults.at(-1)) : 'Done.';
1407
- break;
1408
- }
1409
- executedCalls.add(signature);
1410
- const result = await executeToolCall({
1411
- id: `local_call_${turn + 1}`,
1412
- type: 'function',
1413
- function: {
1414
- name,
1415
- arguments: JSON.stringify(args),
1416
- },
1417
- }, discovery.tools, {
1418
- offline: this.mode === 'offline',
1419
- fetchImpl: this.modelFetchImpl,
1420
- identityHeaders: localIdentityHeaders(options.identityToken ?? options.identity_token, options.interfaceName ?? options.interface ?? 'api', options.conversationId ?? options.conversation_id),
1421
- });
1422
- toolResults.push(result);
1423
- agentMessages.push({
1424
- role: 'system',
1425
- content: `Function result:\n${JSON.stringify(toolResultForContext(result, model.contextWindow && model.contextWindow <= 2048
1426
- ? 2
1427
- : model.contextWindow && model.contextWindow <= 4096
1428
- ? 1
1429
- : 0))}`,
1430
- });
1431
- }
1432
- return localRuntimeResponse(model, options, reply || (toolResults.length ? toolResultDisplayText(toolResults.at(-1)) : 'Done.'), finalPayload, discovery.tools, toolResults);
1433
- }
1434
1340
  localCapabilityCatalog() {
1435
1341
  const payload = this.cache.loadSyncPayload() ?? {};
1436
1342
  const apps = Array.isArray(payload.available_agent_apps)
@@ -1441,26 +1347,41 @@ export class Marona extends RuntimeTransport {
1441
1347
  ? payload.items
1442
1348
  : [];
1443
1349
  const skills = Array.isArray(payload.available_skills) ? payload.available_skills : [];
1350
+ const managedCapabilities = new Set(skills.flatMap((raw) => {
1351
+ const skill = asRecord(raw);
1352
+ return skill ? skillManagedCapabilities(skill) : [];
1353
+ }));
1444
1354
  const supportedApps = apps
1445
1355
  .map(asRecord)
1446
1356
  .filter((app) => {
1447
1357
  if (!app || !appSupportsMode(app, this.mode))
1448
1358
  return false;
1449
- const target = selectExecutionTarget(app, this.mode, this.localGatewayUrl);
1359
+ const target = selectExecutionTarget(app, this.mode);
1450
1360
  return Boolean(target && !target.installRequired);
1451
1361
  });
1452
1362
  const supportedSlugs = new Set(supportedApps.map((app) => stringValue(app.slug)).filter((slug) => Boolean(slug)));
1453
1363
  return {
1454
- apps: supportedApps.map((app) => ({
1455
- slug: app.slug,
1456
- description: shortCatalogText(app.description ?? app.tagline),
1457
- })),
1364
+ apps: supportedApps.flatMap((app) => {
1365
+ const slug = stringValue(app.slug);
1366
+ const capabilityCount = listOfRecords(app.tools).filter((tool) => {
1367
+ const name = stringValue(tool.name);
1368
+ return Boolean(slug && name && !managedCapabilities.has(`${slug}.${name}`));
1369
+ }).length;
1370
+ return capabilityCount ? [{
1371
+ slug: app.slug,
1372
+ description: shortCatalogText(app.description ?? app.tagline),
1373
+ capability_count: capabilityCount,
1374
+ }] : [];
1375
+ }),
1458
1376
  skills: skills
1459
1377
  .map(asRecord)
1460
1378
  .filter((skill) => Boolean(skill) && skillSupportedBy(skill, supportedSlugs))
1461
1379
  .map((skill) => ({
1462
1380
  name: skill.name,
1463
1381
  description: shortCatalogText(skill.description),
1382
+ required_apps: skillRequiredApps(skill),
1383
+ managed_capabilities: skillManagedCapabilities(skill),
1384
+ workflow_purpose: shortCatalogText(skillManifest(skill).description),
1464
1385
  })),
1465
1386
  };
1466
1387
  }
@@ -1468,6 +1389,11 @@ export class Marona extends RuntimeTransport {
1468
1389
  const args = toolCallArguments(call);
1469
1390
  const requestedApps = new Set(stringList(args.app_slugs));
1470
1391
  const requestedSkills = new Set(stringList(args.skill_names));
1392
+ const requestedCapabilities = new Set(stringList(args.capability_names));
1393
+ for (const capability of requestedCapabilities) {
1394
+ if (capability.includes('.'))
1395
+ requestedApps.add(capability.split('.')[0]);
1396
+ }
1471
1397
  const payload = this.cache.loadSyncPayload() ?? {};
1472
1398
  if (!requestedApps.size && !requestedSkills.size) {
1473
1399
  return {
@@ -1488,9 +1414,19 @@ export class Marona extends RuntimeTransport {
1488
1414
  return Boolean(name && requestedSkills.has(name));
1489
1415
  });
1490
1416
  for (const rawSkill of selectedSkills) {
1491
- stringList(asRecord(rawSkill)?.required_apps).forEach((slug) => requestedApps.add(slug));
1417
+ const skill = asRecord(rawSkill);
1418
+ if (skill)
1419
+ skillRequiredApps(skill).forEach((slug) => requestedApps.add(slug));
1492
1420
  }
1493
- const exactCapabilities = new Set(selectedSkills.flatMap((skill) => stringList(asRecord(skill)?.exact_capabilities)));
1421
+ const exactCapabilities = new Set(selectedSkills.flatMap((raw) => {
1422
+ const skill = asRecord(raw);
1423
+ return skill ? skillExactCapabilities(skill) : [];
1424
+ }));
1425
+ requestedCapabilities.forEach((capability) => exactCapabilities.add(capability));
1426
+ const managedCapabilities = new Set(rawSkills.flatMap((raw) => {
1427
+ const skill = asRecord(raw);
1428
+ return skill ? skillManagedCapabilities(skill) : [];
1429
+ }));
1494
1430
  const rawApps = Array.isArray(payload.available_agent_apps)
1495
1431
  ? payload.available_agent_apps
1496
1432
  : Array.isArray(payload.apps)
@@ -1500,12 +1436,13 @@ export class Marona extends RuntimeTransport {
1500
1436
  : [];
1501
1437
  const tools = [];
1502
1438
  const apps = [];
1439
+ const capabilityOptions = [];
1503
1440
  for (const rawApp of rawApps) {
1504
1441
  const app = asRecord(rawApp);
1505
1442
  const slug = stringValue(app?.slug);
1506
1443
  if (!app || !slug || !requestedApps.has(slug) || !appSupportsMode(app, this.mode))
1507
1444
  continue;
1508
- const target = selectExecutionTarget(app, this.mode, this.localGatewayUrl);
1445
+ const target = selectExecutionTarget(app, this.mode);
1509
1446
  if (!target || target.installRequired)
1510
1447
  continue;
1511
1448
  let appTools = toolsFromApp(app, stringValue(target.url), {
@@ -1518,6 +1455,18 @@ export class Marona extends RuntimeTransport {
1518
1455
  return Boolean(name && exactCapabilities.has(`${slug}.${name}`));
1519
1456
  });
1520
1457
  }
1458
+ else {
1459
+ capabilityOptions.push(...appTools.flatMap((tool) => {
1460
+ const name = toolFunctionName(tool)?.split('__').at(-1);
1461
+ if (!name || managedCapabilities.has(`${slug}.${name}`))
1462
+ return [];
1463
+ return [{
1464
+ name: `${slug}.${name}`,
1465
+ description: shortCatalogText(asRecord(tool.function)?.description),
1466
+ }];
1467
+ }));
1468
+ appTools = [];
1469
+ }
1521
1470
  tools.push(...appTools);
1522
1471
  apps.push({
1523
1472
  slug,
@@ -1525,6 +1474,19 @@ export class Marona extends RuntimeTransport {
1525
1474
  installed: !target.installRequired,
1526
1475
  });
1527
1476
  }
1477
+ if (!tools.length && capabilityOptions.length) {
1478
+ return {
1479
+ tools: [],
1480
+ result: {
1481
+ tool_call_id: call.id,
1482
+ result: {
1483
+ status: 'capability_selection_required',
1484
+ capabilities: capabilityOptions,
1485
+ instruction: 'Select only the exact capability identifiers needed for the current request, then call marona__discover_capabilities again with capability_names.',
1486
+ },
1487
+ },
1488
+ };
1489
+ }
1528
1490
  const skills = compactLocalSkills(selectedSkills);
1529
1491
  return {
1530
1492
  tools,
@@ -1656,7 +1618,7 @@ function redactModel(model) {
1656
1618
  const { apiKey: _apiKey, ...safe } = model;
1657
1619
  return safe;
1658
1620
  }
1659
- async function callChatModel(model, messages, tools, fetchImpl) {
1621
+ async function callChatModel(model, messages, tools, fetchImpl, toolChoice = "auto") {
1660
1622
  if (model.protocol && !["chat_completions", "custom_http"].includes(model.protocol)) {
1661
1623
  throw new MaronaModelError(`Model '${model.name}' does not support chat messages yet.`);
1662
1624
  }
@@ -1670,7 +1632,7 @@ async function callChatModel(model, messages, tools, fetchImpl) {
1670
1632
  ...(tools.length
1671
1633
  ? {
1672
1634
  tools: tools.map((tool) => asRecord(tool.function) ? { type: "function", function: tool.function } : tool),
1673
- tool_choice: "auto",
1635
+ tool_choice: toolChoice,
1674
1636
  }
1675
1637
  : {}),
1676
1638
  }),
@@ -1703,64 +1665,6 @@ function modelText(payload) {
1703
1665
  const message = asRecord(first?.message);
1704
1666
  return stringValue(message?.content) ?? "";
1705
1667
  }
1706
- function modelJsonObject(payload) {
1707
- const text = modelText(payload).trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
1708
- const parsed = asRecord(parseMaybeJson(text));
1709
- if (parsed)
1710
- return parsed;
1711
- const first = firstJsonObject(text);
1712
- return first ? asRecord(parseMaybeJson(first)) ?? {} : {};
1713
- }
1714
- function firstJsonObject(text) {
1715
- const start = text.indexOf('{');
1716
- if (start < 0)
1717
- return undefined;
1718
- let depth = 0;
1719
- let inString = false;
1720
- let escaped = false;
1721
- for (let index = start; index < text.length; index += 1) {
1722
- const character = text[index];
1723
- if (inString) {
1724
- if (escaped)
1725
- escaped = false;
1726
- else if (character === '\\')
1727
- escaped = true;
1728
- else if (character === '"')
1729
- inString = false;
1730
- continue;
1731
- }
1732
- if (character === '"')
1733
- inString = true;
1734
- else if (character === '{')
1735
- depth += 1;
1736
- else if (character === '}') {
1737
- depth -= 1;
1738
- if (depth === 0)
1739
- return text.slice(start, index + 1);
1740
- }
1741
- }
1742
- return undefined;
1743
- }
1744
- function localRuntimeResponse(model, options, reply, payload, availableTools = [], toolResults = []) {
1745
- return {
1746
- status: 'completed',
1747
- reply,
1748
- text: reply,
1749
- interfaceName: options.interfaceName ?? options.interface ?? 'api',
1750
- conversationId: options.conversationId ?? options.conversation_id,
1751
- artifacts: [],
1752
- needsPermission: false,
1753
- needsServiceConnection: false,
1754
- toolCall: toolResults.length ? { results: toolResults } : undefined,
1755
- rawJson: {
1756
- mode: 'local',
1757
- model: redactModel(model),
1758
- metadata: options.metadata ?? {},
1759
- available_tools: availableTools.map(toolFunctionName).filter(Boolean),
1760
- model_response: payload,
1761
- },
1762
- };
1763
- }
1764
1668
  function modelToolCalls(payload) {
1765
1669
  const choices = Array.isArray(payload.choices) ? payload.choices : [];
1766
1670
  const first = asRecord(choices[0]);
@@ -1768,19 +1672,6 @@ function modelToolCalls(payload) {
1768
1672
  const calls = Array.isArray(message?.tool_calls) ? message.tool_calls : [];
1769
1673
  return calls.map(asRecord).filter(Boolean);
1770
1674
  }
1771
- function assistantToolMessage(payload) {
1772
- const choices = Array.isArray(payload.choices) ? payload.choices : [];
1773
- const first = asRecord(choices[0]);
1774
- const message = asRecord(first?.message);
1775
- return message ?? { role: "assistant", content: "" };
1776
- }
1777
- function toolResultMessage(result) {
1778
- return {
1779
- role: "tool",
1780
- tool_call_id: stringValue(result.tool_call_id) ?? stringValue(result.id) ?? "tool",
1781
- content: JSON.stringify(toolResultForModel(result)),
1782
- };
1783
- }
1784
1675
  function toolResultForModel(result) {
1785
1676
  if (Object.prototype.hasOwnProperty.call(result, "result")) {
1786
1677
  return compactToolValue(result.result);
@@ -1790,38 +1681,17 @@ function toolResultForModel(result) {
1790
1681
  function toolResultDisplayText(result) {
1791
1682
  const value = asRecord(result.result) ?? result;
1792
1683
  const structured = asRecord(value.structuredContent) ?? asRecord(value.structured_content);
1793
- if (structured) {
1684
+ for (const record of [structured, value]) {
1685
+ if (!record)
1686
+ continue;
1794
1687
  for (const key of ['content', 'message', 'summary']) {
1795
- const text = stringValue(structured[key]);
1688
+ const text = stringValue(record[key]);
1796
1689
  if (text)
1797
1690
  return text;
1798
1691
  }
1799
1692
  }
1800
1693
  return contentBlocksText(value.content);
1801
1694
  }
1802
- function toolResultRequiresExactDisplay(result) {
1803
- const value = asRecord(result.result) ?? result;
1804
- const structured = asRecord(value.structuredContent) ?? asRecord(value.structured_content);
1805
- return structured?.presentation_hint === 'display_as_provided';
1806
- }
1807
- function toolResultForContext(result, tier) {
1808
- const value = toolResultForModel(result);
1809
- const record = asRecord(value);
1810
- if (tier < 2 || !record)
1811
- return value;
1812
- const compact = {};
1813
- for (const key of ['status', 'success', 'message', 'count', 'summary']) {
1814
- if (Object.prototype.hasOwnProperty.call(record, key))
1815
- compact[key] = record[key];
1816
- }
1817
- const content = stringValue(record.content);
1818
- if (content)
1819
- compact.content = content.slice(0, tier === 2 ? 1200 : 600);
1820
- if (Array.isArray(record.items)) {
1821
- compact.items = record.items.slice(0, 2).map((item) => compactToolValue(item));
1822
- }
1823
- return Object.keys(compact).length ? compact : compactToolValue(record);
1824
- }
1825
1695
  function compactToolValue(value, depth = 0) {
1826
1696
  if (value == null || typeof value === "number" || typeof value === "boolean")
1827
1697
  return value;
@@ -2099,7 +1969,8 @@ function compactLocalSkills(value) {
2099
1969
  name: skill.name,
2100
1970
  description: skill.description,
2101
1971
  version: skill.version,
2102
- required_apps: Array.isArray(skill.required_apps) ? skill.required_apps : [],
1972
+ required_apps: skillRequiredApps(skill),
1973
+ managed_capabilities: skillManagedCapabilities(skill),
2103
1974
  steps: Array.isArray(manifest.steps) ? manifest.steps : [],
2104
1975
  },
2105
1976
  ];
@@ -2130,6 +2001,12 @@ function capabilityDiscoveryTool(catalog = { apps: [], skills: [] }) {
2130
2001
  maxItems: 3,
2131
2002
  description: 'Exact Skill identifiers selected from the installed catalog.',
2132
2003
  },
2004
+ capability_names: {
2005
+ type: 'array',
2006
+ items: { type: 'string' },
2007
+ maxItems: 5,
2008
+ description: 'Exact capability identifiers returned by a previous discovery call.',
2009
+ },
2133
2010
  },
2134
2011
  required: ['query'],
2135
2012
  additionalProperties: false,
@@ -2156,8 +2033,29 @@ function toolCallArguments(call) {
2156
2033
  function stringList(value) {
2157
2034
  return Array.isArray(value) ? value.map(String).map((item) => item.trim()).filter(Boolean) : [];
2158
2035
  }
2036
+ function skillManifest(skill) {
2037
+ return asRecord(skill.manifest) ?? {};
2038
+ }
2039
+ function skillRequiredApps(skill) {
2040
+ return stringList(skill.required_apps ?? skillManifest(skill).required_apps);
2041
+ }
2042
+ function skillExactCapabilities(skill) {
2043
+ const manifest = skillManifest(skill);
2044
+ const exact = stringList(skill.exact_capabilities ?? manifest.exact_capabilities);
2045
+ if (exact.length)
2046
+ return exact;
2047
+ return listOfRecords(manifest.steps)
2048
+ .filter((step) => step.type === 'app')
2049
+ .map((step) => stringValue(step.capability))
2050
+ .filter((value) => Boolean(value));
2051
+ }
2052
+ function skillManagedCapabilities(skill) {
2053
+ const manifest = skillManifest(skill);
2054
+ const managed = stringList(skill.managed_capabilities ?? manifest.managed_capabilities);
2055
+ return managed.length ? managed : skillExactCapabilities(skill);
2056
+ }
2159
2057
  function skillSupportedBy(skill, appSlugs) {
2160
- const required = stringList(skill.required_apps);
2058
+ const required = skillRequiredApps(skill);
2161
2059
  return !required.length || required.every((slug) => appSlugs.has(slug));
2162
2060
  }
2163
2061
  function shortCatalogText(value) {
@@ -2169,16 +2067,6 @@ function shortCatalogText(value) {
2169
2067
  function toolFunctionName(tool) {
2170
2068
  return stringValue(asRecord(tool.function)?.name);
2171
2069
  }
2172
- function mergeTools(destination, incoming) {
2173
- const names = new Set(destination.map(toolFunctionName));
2174
- for (const tool of incoming) {
2175
- const name = toolFunctionName(tool);
2176
- if (name && !names.has(name)) {
2177
- names.add(name);
2178
- destination.push(tool);
2179
- }
2180
- }
2181
- }
2182
2070
  function sanitizeContextValue(value) {
2183
2071
  if (Array.isArray(value))
2184
2072
  return value.map(sanitizeContextValue);
@@ -2267,7 +2155,7 @@ function firstItems(value, count) {
2267
2155
  function lastItems(value, count) {
2268
2156
  return Array.isArray(value) ? value.slice(-count) : [];
2269
2157
  }
2270
- function connectFromCache(cache, apps, adapter, mode, localGatewayUrl) {
2158
+ function connectFromCache(cache, apps, adapter, mode) {
2271
2159
  const connections = [];
2272
2160
  const resolvedApps = [];
2273
2161
  const missingApps = [];
@@ -2278,7 +2166,7 @@ function connectFromCache(cache, apps, adapter, mode, localGatewayUrl) {
2278
2166
  continue;
2279
2167
  }
2280
2168
  resolvedApps.push(app);
2281
- const target = selectExecutionTarget(app, mode, localGatewayUrl);
2169
+ const target = selectExecutionTarget(app, mode);
2282
2170
  if (!target) {
2283
2171
  missingApps.push(slug);
2284
2172
  continue;
@@ -2352,30 +2240,29 @@ function executionTargets(app) {
2352
2240
  type: String(target?.type ?? target?.kind ?? "").trim().toLowerCase(),
2353
2241
  }));
2354
2242
  }
2355
- function selectExecutionTarget(app, mode, localGatewayUrl) {
2243
+ function selectExecutionTarget(app, mode) {
2356
2244
  const targets = executionTargets(app);
2357
2245
  if (!targets.length)
2358
2246
  return undefined;
2359
- const slug = stringValue(app.slug) ?? stringValue(app.name) ?? "app";
2360
2247
  let candidates;
2361
2248
  if (mode === "offline") {
2362
- candidates = targets.filter((target) => ["offline", "hybrid"].includes(String(target.mode)) && target.type !== "remote_mcp");
2249
+ candidates = targets.filter((target) => ["offline", "hybrid"].includes(String(target.mode)) && localExecutionTargetTypes.has(String(target.type)));
2363
2250
  }
2364
2251
  else if (mode === "hybrid") {
2365
2252
  candidates = [
2366
- ...targets.filter((target) => ["offline", "hybrid"].includes(String(target.mode)) && target.type !== "remote_mcp"),
2367
- ...targets.filter((target) => ["online", "hybrid"].includes(String(target.mode)) && ["remote_mcp", "marona_hosted"].includes(String(target.type))),
2253
+ ...targets.filter((target) => ["offline", "hybrid"].includes(String(target.mode)) && localExecutionTargetTypes.has(String(target.type))),
2254
+ ...targets.filter((target) => ["online", "hybrid"].includes(String(target.mode)) && remoteExecutionTargetTypes.has(String(target.type))),
2368
2255
  ];
2369
2256
  }
2370
2257
  else {
2371
- candidates = targets.filter((target) => ["online", "hybrid"].includes(String(target.mode)) && ["remote_mcp", "marona_hosted"].includes(String(target.type)));
2258
+ candidates = targets.filter((target) => ["online", "hybrid"].includes(String(target.mode)) && remoteExecutionTargetTypes.has(String(target.type)));
2372
2259
  }
2373
2260
  let unavailableLocal;
2374
2261
  for (const target of candidates) {
2375
- const url = targetRuntimeUrl(target, mode, slug, localGatewayUrl);
2262
+ const url = targetRuntimeUrl(target, mode);
2376
2263
  if (url)
2377
2264
  return { target, url, installRequired: false };
2378
- if (!["remote_mcp", "marona_hosted"].includes(String(target.type))) {
2265
+ if (localExecutionTargetTypes.has(String(target.type))) {
2379
2266
  unavailableLocal = { target, installRequired: true };
2380
2267
  if (mode === "offline")
2381
2268
  return unavailableLocal;
@@ -2383,62 +2270,22 @@ function selectExecutionTarget(app, mode, localGatewayUrl) {
2383
2270
  }
2384
2271
  return unavailableLocal;
2385
2272
  }
2386
- function targetRuntimeUrl(target, mode, slug, localGatewayUrl) {
2273
+ function targetRuntimeUrl(target, mode) {
2387
2274
  const type = stringValue(target.type);
2388
- if (type === "remote_mcp" || type === "marona_hosted") {
2275
+ if (remoteExecutionTargetTypes.has(type ?? "")) {
2389
2276
  if (mode === "offline")
2390
2277
  return undefined;
2391
2278
  return stringValue(target.url)?.replace(/\/+$/, "");
2392
2279
  }
2393
- const value = stringValue(target.runtime_url) ?? stringValue(target.resolved_url);
2394
- if (value && inferLocation(value) === "local")
2395
- return value.replace(/\/+$/, "");
2396
- return localTargetUrl(target, slug, localGatewayUrl);
2397
- }
2398
- function localTargetUrl(target, slug, localGatewayUrl) {
2399
- const port = targetPort(target);
2400
- if (!port)
2401
- return undefined;
2402
- const endpoint = targetEndpoint(target);
2403
- const gateway = cleanUrl(localGatewayUrl);
2404
- if (gateway) {
2405
- return `${gateway}/local-mcp/${encodeURIComponent(slug)}/${port}${endpoint}`;
2406
- }
2407
- return `http://127.0.0.1:${port}${endpoint}`;
2408
- }
2409
- function targetEndpoint(target) {
2410
- let endpoint = stringValue(target.endpoint) ?? "/mcp";
2411
- if (!endpoint.startsWith("/"))
2412
- endpoint = `/${endpoint}`;
2413
- return endpoint === "/mcp" ? "/mcp/" : endpoint;
2414
- }
2415
- function targetPort(target) {
2416
- const runtimeConfig = asRecord(target.runtime_config);
2417
- const raw = target.port ?? runtimeConfig?.port;
2418
- if (raw === undefined || raw === null)
2280
+ if (!localExecutionTargetTypes.has(type ?? ""))
2419
2281
  return undefined;
2420
- const port = Number.parseInt(String(raw), 10);
2421
- if (!Number.isInteger(port) || port <= 0 || port > 65535)
2282
+ if (target.installed !== true)
2422
2283
  return undefined;
2423
- return port;
2424
- }
2425
- function cleanUrl(value) {
2426
- if (typeof value !== "string")
2427
- return undefined;
2428
- const cleaned = value.trim().replace(/\/+$/, "");
2429
- return cleaned || undefined;
2430
- }
2431
- function defaultLocalGatewayUrl(baseUrl) {
2432
- try {
2433
- const url = new URL(baseUrl);
2434
- const host = url.hostname.toLowerCase();
2435
- if (host === "localhost" || host === "127.0.0.1" || host === "::1" || host.startsWith("10.") || host.startsWith("192.168.") || host.startsWith("172.")) {
2436
- return cleanUrl(baseUrl);
2437
- }
2438
- }
2439
- catch {
2284
+ if (asRecord(target.state_sync) && target.state_ready !== true)
2440
2285
  return undefined;
2441
- }
2286
+ const value = stringValue(target.resolved_url);
2287
+ if (value && inferLocation(value) === "local")
2288
+ return value.replace(/\/+$/, "");
2442
2289
  return undefined;
2443
2290
  }
2444
2291
  function toolsFromApp(app, url, options = {}) {