marona 0.3.9 → 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,92 +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 decisionPayload = await callChatModel(model, [
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"]}. Select only identifiers from this installed catalog: ' +
1302
- JSON.stringify(catalog),
1303
- },
1304
- ...messages.slice(-1),
1305
- ], [], this.modelFetchImpl);
1306
- const decision = modelJsonObject(decisionPayload);
1307
- if (decision.action !== 'discover') {
1308
- const reply = stringValue(decision.response) ?? (modelText(decisionPayload) || 'Done.');
1309
- return localRuntimeResponse(model, options, reply, decisionPayload);
1310
- }
1311
- const discovery = this.discoverLocalCapabilities({
1312
- id: 'discover_1',
1313
- type: 'function',
1314
- function: {
1315
- name: 'marona__discover_capabilities',
1316
- arguments: JSON.stringify({
1317
- query: text,
1318
- app_slugs: stringList(decision.app_slugs),
1319
- skill_names: stringList(decision.skill_names),
1320
- }),
1321
- },
1322
- });
1323
- if (!discovery.tools.length) {
1324
- return localRuntimeResponse(model, options, 'That capability is not available offline on this device.', decisionPayload);
1325
- }
1326
- const agentMessages = [
1327
- ...messages,
1328
- {
1329
- role: 'system',
1330
- content: `Selected capability workflow:\n${JSON.stringify(asRecord(discovery.result.result) ?? {})}`,
1331
- },
1332
- ];
1333
- const toolResults = [];
1334
- let finalPayload = decisionPayload;
1335
- let reply = '';
1336
- for (let turn = 0; turn < 8; turn += 1) {
1337
- finalPayload = await callChatModel(model, [
1338
- ...agentMessages,
1339
- {
1340
- role: 'system',
1341
- 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: ' +
1342
- JSON.stringify(discovery.tools.map((tool) => asRecord(tool.function) ? { type: 'function', function: tool.function } : tool)),
1343
- },
1344
- ], [], this.modelFetchImpl);
1345
- const toolDecision = modelJsonObject(finalPayload);
1346
- if (toolDecision.action !== 'tool') {
1347
- reply = stringValue(toolDecision.response) ?? modelText(finalPayload);
1348
- break;
1349
- }
1350
- const name = stringValue(toolDecision.tool_name) ?? '';
1351
- if (!discovery.tools.some((tool) => toolFunctionName(tool) === name)) {
1352
- agentMessages.push({
1353
- role: 'system',
1354
- content: `Rejected unknown function '${name}'. Select an exact available name.`,
1355
- });
1356
- continue;
1357
- }
1358
- const result = await executeToolCall({
1359
- id: `local_call_${turn + 1}`,
1360
- type: 'function',
1361
- function: {
1362
- name,
1363
- arguments: JSON.stringify(asRecord(toolDecision.arguments) ?? {}),
1364
- },
1365
- }, discovery.tools, {
1366
- offline: this.mode === 'offline',
1367
- fetchImpl: this.modelFetchImpl,
1368
- identityHeaders: localIdentityHeaders(options.identityToken ?? options.identity_token, options.interfaceName ?? options.interface ?? 'api', options.conversationId ?? options.conversation_id),
1369
- });
1370
- toolResults.push(result);
1371
- agentMessages.push({
1372
- role: 'system',
1373
- content: `Function result:\n${JSON.stringify(toolResultForModel(result))}`,
1374
- });
1375
- }
1376
- return localRuntimeResponse(model, options, reply || 'Done.', finalPayload, discovery.tools, toolResults);
1377
- }
1378
1340
  localCapabilityCatalog() {
1379
1341
  const payload = this.cache.loadSyncPayload() ?? {};
1380
1342
  const apps = Array.isArray(payload.available_agent_apps)
@@ -1385,26 +1347,41 @@ export class Marona extends RuntimeTransport {
1385
1347
  ? payload.items
1386
1348
  : [];
1387
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
+ }));
1388
1354
  const supportedApps = apps
1389
1355
  .map(asRecord)
1390
1356
  .filter((app) => {
1391
1357
  if (!app || !appSupportsMode(app, this.mode))
1392
1358
  return false;
1393
- const target = selectExecutionTarget(app, this.mode, this.localGatewayUrl);
1359
+ const target = selectExecutionTarget(app, this.mode);
1394
1360
  return Boolean(target && !target.installRequired);
1395
1361
  });
1396
1362
  const supportedSlugs = new Set(supportedApps.map((app) => stringValue(app.slug)).filter((slug) => Boolean(slug)));
1397
1363
  return {
1398
- apps: supportedApps.map((app) => ({
1399
- slug: app.slug,
1400
- description: shortCatalogText(app.description ?? app.tagline),
1401
- })),
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
+ }),
1402
1376
  skills: skills
1403
1377
  .map(asRecord)
1404
1378
  .filter((skill) => Boolean(skill) && skillSupportedBy(skill, supportedSlugs))
1405
1379
  .map((skill) => ({
1406
1380
  name: skill.name,
1407
1381
  description: shortCatalogText(skill.description),
1382
+ required_apps: skillRequiredApps(skill),
1383
+ managed_capabilities: skillManagedCapabilities(skill),
1384
+ workflow_purpose: shortCatalogText(skillManifest(skill).description),
1408
1385
  })),
1409
1386
  };
1410
1387
  }
@@ -1412,6 +1389,11 @@ export class Marona extends RuntimeTransport {
1412
1389
  const args = toolCallArguments(call);
1413
1390
  const requestedApps = new Set(stringList(args.app_slugs));
1414
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
+ }
1415
1397
  const payload = this.cache.loadSyncPayload() ?? {};
1416
1398
  if (!requestedApps.size && !requestedSkills.size) {
1417
1399
  return {
@@ -1432,9 +1414,19 @@ export class Marona extends RuntimeTransport {
1432
1414
  return Boolean(name && requestedSkills.has(name));
1433
1415
  });
1434
1416
  for (const rawSkill of selectedSkills) {
1435
- 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));
1436
1420
  }
1437
- 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
+ }));
1438
1430
  const rawApps = Array.isArray(payload.available_agent_apps)
1439
1431
  ? payload.available_agent_apps
1440
1432
  : Array.isArray(payload.apps)
@@ -1444,12 +1436,13 @@ export class Marona extends RuntimeTransport {
1444
1436
  : [];
1445
1437
  const tools = [];
1446
1438
  const apps = [];
1439
+ const capabilityOptions = [];
1447
1440
  for (const rawApp of rawApps) {
1448
1441
  const app = asRecord(rawApp);
1449
1442
  const slug = stringValue(app?.slug);
1450
1443
  if (!app || !slug || !requestedApps.has(slug) || !appSupportsMode(app, this.mode))
1451
1444
  continue;
1452
- const target = selectExecutionTarget(app, this.mode, this.localGatewayUrl);
1445
+ const target = selectExecutionTarget(app, this.mode);
1453
1446
  if (!target || target.installRequired)
1454
1447
  continue;
1455
1448
  let appTools = toolsFromApp(app, stringValue(target.url), {
@@ -1462,6 +1455,18 @@ export class Marona extends RuntimeTransport {
1462
1455
  return Boolean(name && exactCapabilities.has(`${slug}.${name}`));
1463
1456
  });
1464
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
+ }
1465
1470
  tools.push(...appTools);
1466
1471
  apps.push({
1467
1472
  slug,
@@ -1469,6 +1474,19 @@ export class Marona extends RuntimeTransport {
1469
1474
  installed: !target.installRequired,
1470
1475
  });
1471
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
+ }
1472
1490
  const skills = compactLocalSkills(selectedSkills);
1473
1491
  return {
1474
1492
  tools,
@@ -1600,7 +1618,7 @@ function redactModel(model) {
1600
1618
  const { apiKey: _apiKey, ...safe } = model;
1601
1619
  return safe;
1602
1620
  }
1603
- async function callChatModel(model, messages, tools, fetchImpl) {
1621
+ async function callChatModel(model, messages, tools, fetchImpl, toolChoice = "auto") {
1604
1622
  if (model.protocol && !["chat_completions", "custom_http"].includes(model.protocol)) {
1605
1623
  throw new MaronaModelError(`Model '${model.name}' does not support chat messages yet.`);
1606
1624
  }
@@ -1610,10 +1628,11 @@ async function callChatModel(model, messages, tools, fetchImpl) {
1610
1628
  body: JSON.stringify({
1611
1629
  model: model.model ?? model.name,
1612
1630
  messages,
1631
+ ...(modelOutputLimit(model) ? { max_tokens: modelOutputLimit(model) } : {}),
1613
1632
  ...(tools.length
1614
1633
  ? {
1615
1634
  tools: tools.map((tool) => asRecord(tool.function) ? { type: "function", function: tool.function } : tool),
1616
- tool_choice: "auto",
1635
+ tool_choice: toolChoice,
1617
1636
  }
1618
1637
  : {}),
1619
1638
  }),
@@ -1631,36 +1650,21 @@ async function callChatModel(model, messages, tools, fetchImpl) {
1631
1650
  throw new MaronaModelError("Local model returned a non-JSON response.", { payload });
1632
1651
  return record;
1633
1652
  }
1653
+ function modelOutputLimit(model) {
1654
+ if (model.contextWindow && model.contextWindow <= 2048) {
1655
+ return Math.min(model.maxOutputTokens ?? 192, 192);
1656
+ }
1657
+ if (model.contextWindow && model.contextWindow <= 4096) {
1658
+ return Math.min(model.maxOutputTokens ?? 384, 384);
1659
+ }
1660
+ return model.maxOutputTokens;
1661
+ }
1634
1662
  function modelText(payload) {
1635
1663
  const choices = Array.isArray(payload.choices) ? payload.choices : [];
1636
1664
  const first = asRecord(choices[0]);
1637
1665
  const message = asRecord(first?.message);
1638
1666
  return stringValue(message?.content) ?? "";
1639
1667
  }
1640
- function modelJsonObject(payload) {
1641
- const text = modelText(payload).trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
1642
- return asRecord(parseMaybeJson(text)) ?? {};
1643
- }
1644
- function localRuntimeResponse(model, options, reply, payload, availableTools = [], toolResults = []) {
1645
- return {
1646
- status: 'completed',
1647
- reply,
1648
- text: reply,
1649
- interfaceName: options.interfaceName ?? options.interface ?? 'api',
1650
- conversationId: options.conversationId ?? options.conversation_id,
1651
- artifacts: [],
1652
- needsPermission: false,
1653
- needsServiceConnection: false,
1654
- toolCall: toolResults.length ? { results: toolResults } : undefined,
1655
- rawJson: {
1656
- mode: 'local',
1657
- model: redactModel(model),
1658
- metadata: options.metadata ?? {},
1659
- available_tools: availableTools.map(toolFunctionName).filter(Boolean),
1660
- model_response: payload,
1661
- },
1662
- };
1663
- }
1664
1668
  function modelToolCalls(payload) {
1665
1669
  const choices = Array.isArray(payload.choices) ? payload.choices : [];
1666
1670
  const first = asRecord(choices[0]);
@@ -1668,25 +1672,26 @@ function modelToolCalls(payload) {
1668
1672
  const calls = Array.isArray(message?.tool_calls) ? message.tool_calls : [];
1669
1673
  return calls.map(asRecord).filter(Boolean);
1670
1674
  }
1671
- function assistantToolMessage(payload) {
1672
- const choices = Array.isArray(payload.choices) ? payload.choices : [];
1673
- const first = asRecord(choices[0]);
1674
- const message = asRecord(first?.message);
1675
- return message ?? { role: "assistant", content: "" };
1676
- }
1677
- function toolResultMessage(result) {
1678
- return {
1679
- role: "tool",
1680
- tool_call_id: stringValue(result.tool_call_id) ?? stringValue(result.id) ?? "tool",
1681
- content: JSON.stringify(toolResultForModel(result)),
1682
- };
1683
- }
1684
1675
  function toolResultForModel(result) {
1685
1676
  if (Object.prototype.hasOwnProperty.call(result, "result")) {
1686
1677
  return compactToolValue(result.result);
1687
1678
  }
1688
1679
  return { error: compactToolValue(result.error ?? "") };
1689
1680
  }
1681
+ function toolResultDisplayText(result) {
1682
+ const value = asRecord(result.result) ?? result;
1683
+ const structured = asRecord(value.structuredContent) ?? asRecord(value.structured_content);
1684
+ for (const record of [structured, value]) {
1685
+ if (!record)
1686
+ continue;
1687
+ for (const key of ['content', 'message', 'summary']) {
1688
+ const text = stringValue(record[key]);
1689
+ if (text)
1690
+ return text;
1691
+ }
1692
+ }
1693
+ return contentBlocksText(value.content);
1694
+ }
1690
1695
  function compactToolValue(value, depth = 0) {
1691
1696
  if (value == null || typeof value === "number" || typeof value === "boolean")
1692
1697
  return value;
@@ -1964,7 +1969,8 @@ function compactLocalSkills(value) {
1964
1969
  name: skill.name,
1965
1970
  description: skill.description,
1966
1971
  version: skill.version,
1967
- required_apps: Array.isArray(skill.required_apps) ? skill.required_apps : [],
1972
+ required_apps: skillRequiredApps(skill),
1973
+ managed_capabilities: skillManagedCapabilities(skill),
1968
1974
  steps: Array.isArray(manifest.steps) ? manifest.steps : [],
1969
1975
  },
1970
1976
  ];
@@ -1995,6 +2001,12 @@ function capabilityDiscoveryTool(catalog = { apps: [], skills: [] }) {
1995
2001
  maxItems: 3,
1996
2002
  description: 'Exact Skill identifiers selected from the installed catalog.',
1997
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
+ },
1998
2010
  },
1999
2011
  required: ['query'],
2000
2012
  additionalProperties: false,
@@ -2021,8 +2033,29 @@ function toolCallArguments(call) {
2021
2033
  function stringList(value) {
2022
2034
  return Array.isArray(value) ? value.map(String).map((item) => item.trim()).filter(Boolean) : [];
2023
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
+ }
2024
2057
  function skillSupportedBy(skill, appSlugs) {
2025
- const required = stringList(skill.required_apps);
2058
+ const required = skillRequiredApps(skill);
2026
2059
  return !required.length || required.every((slug) => appSlugs.has(slug));
2027
2060
  }
2028
2061
  function shortCatalogText(value) {
@@ -2034,16 +2067,6 @@ function shortCatalogText(value) {
2034
2067
  function toolFunctionName(tool) {
2035
2068
  return stringValue(asRecord(tool.function)?.name);
2036
2069
  }
2037
- function mergeTools(destination, incoming) {
2038
- const names = new Set(destination.map(toolFunctionName));
2039
- for (const tool of incoming) {
2040
- const name = toolFunctionName(tool);
2041
- if (name && !names.has(name)) {
2042
- names.add(name);
2043
- destination.push(tool);
2044
- }
2045
- }
2046
- }
2047
2070
  function sanitizeContextValue(value) {
2048
2071
  if (Array.isArray(value))
2049
2072
  return value.map(sanitizeContextValue);
@@ -2132,7 +2155,7 @@ function firstItems(value, count) {
2132
2155
  function lastItems(value, count) {
2133
2156
  return Array.isArray(value) ? value.slice(-count) : [];
2134
2157
  }
2135
- function connectFromCache(cache, apps, adapter, mode, localGatewayUrl) {
2158
+ function connectFromCache(cache, apps, adapter, mode) {
2136
2159
  const connections = [];
2137
2160
  const resolvedApps = [];
2138
2161
  const missingApps = [];
@@ -2143,7 +2166,7 @@ function connectFromCache(cache, apps, adapter, mode, localGatewayUrl) {
2143
2166
  continue;
2144
2167
  }
2145
2168
  resolvedApps.push(app);
2146
- const target = selectExecutionTarget(app, mode, localGatewayUrl);
2169
+ const target = selectExecutionTarget(app, mode);
2147
2170
  if (!target) {
2148
2171
  missingApps.push(slug);
2149
2172
  continue;
@@ -2217,30 +2240,29 @@ function executionTargets(app) {
2217
2240
  type: String(target?.type ?? target?.kind ?? "").trim().toLowerCase(),
2218
2241
  }));
2219
2242
  }
2220
- function selectExecutionTarget(app, mode, localGatewayUrl) {
2243
+ function selectExecutionTarget(app, mode) {
2221
2244
  const targets = executionTargets(app);
2222
2245
  if (!targets.length)
2223
2246
  return undefined;
2224
- const slug = stringValue(app.slug) ?? stringValue(app.name) ?? "app";
2225
2247
  let candidates;
2226
2248
  if (mode === "offline") {
2227
- 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)));
2228
2250
  }
2229
2251
  else if (mode === "hybrid") {
2230
2252
  candidates = [
2231
- ...targets.filter((target) => ["offline", "hybrid"].includes(String(target.mode)) && target.type !== "remote_mcp"),
2232
- ...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))),
2233
2255
  ];
2234
2256
  }
2235
2257
  else {
2236
- 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)));
2237
2259
  }
2238
2260
  let unavailableLocal;
2239
2261
  for (const target of candidates) {
2240
- const url = targetRuntimeUrl(target, mode, slug, localGatewayUrl);
2262
+ const url = targetRuntimeUrl(target, mode);
2241
2263
  if (url)
2242
2264
  return { target, url, installRequired: false };
2243
- if (!["remote_mcp", "marona_hosted"].includes(String(target.type))) {
2265
+ if (localExecutionTargetTypes.has(String(target.type))) {
2244
2266
  unavailableLocal = { target, installRequired: true };
2245
2267
  if (mode === "offline")
2246
2268
  return unavailableLocal;
@@ -2248,62 +2270,22 @@ function selectExecutionTarget(app, mode, localGatewayUrl) {
2248
2270
  }
2249
2271
  return unavailableLocal;
2250
2272
  }
2251
- function targetRuntimeUrl(target, mode, slug, localGatewayUrl) {
2273
+ function targetRuntimeUrl(target, mode) {
2252
2274
  const type = stringValue(target.type);
2253
- if (type === "remote_mcp" || type === "marona_hosted") {
2275
+ if (remoteExecutionTargetTypes.has(type ?? "")) {
2254
2276
  if (mode === "offline")
2255
2277
  return undefined;
2256
2278
  return stringValue(target.url)?.replace(/\/+$/, "");
2257
2279
  }
2258
- const value = stringValue(target.runtime_url) ?? stringValue(target.resolved_url);
2259
- if (value && inferLocation(value) === "local")
2260
- return value.replace(/\/+$/, "");
2261
- return localTargetUrl(target, slug, localGatewayUrl);
2262
- }
2263
- function localTargetUrl(target, slug, localGatewayUrl) {
2264
- const port = targetPort(target);
2265
- if (!port)
2280
+ if (!localExecutionTargetTypes.has(type ?? ""))
2266
2281
  return undefined;
2267
- const endpoint = targetEndpoint(target);
2268
- const gateway = cleanUrl(localGatewayUrl);
2269
- if (gateway) {
2270
- return `${gateway}/local-mcp/${encodeURIComponent(slug)}/${port}${endpoint}`;
2271
- }
2272
- return `http://127.0.0.1:${port}${endpoint}`;
2273
- }
2274
- function targetEndpoint(target) {
2275
- let endpoint = stringValue(target.endpoint) ?? "/mcp";
2276
- if (!endpoint.startsWith("/"))
2277
- endpoint = `/${endpoint}`;
2278
- return endpoint === "/mcp" ? "/mcp/" : endpoint;
2279
- }
2280
- function targetPort(target) {
2281
- const runtimeConfig = asRecord(target.runtime_config);
2282
- const raw = target.port ?? runtimeConfig?.port;
2283
- if (raw === undefined || raw === null)
2282
+ if (target.installed !== true)
2284
2283
  return undefined;
2285
- const port = Number.parseInt(String(raw), 10);
2286
- if (!Number.isInteger(port) || port <= 0 || port > 65535)
2284
+ if (asRecord(target.state_sync) && target.state_ready !== true)
2287
2285
  return undefined;
2288
- return port;
2289
- }
2290
- function cleanUrl(value) {
2291
- if (typeof value !== "string")
2292
- return undefined;
2293
- const cleaned = value.trim().replace(/\/+$/, "");
2294
- return cleaned || undefined;
2295
- }
2296
- function defaultLocalGatewayUrl(baseUrl) {
2297
- try {
2298
- const url = new URL(baseUrl);
2299
- const host = url.hostname.toLowerCase();
2300
- if (host === "localhost" || host === "127.0.0.1" || host === "::1" || host.startsWith("10.") || host.startsWith("192.168.") || host.startsWith("172.")) {
2301
- return cleanUrl(baseUrl);
2302
- }
2303
- }
2304
- catch {
2305
- return undefined;
2306
- }
2286
+ const value = stringValue(target.resolved_url);
2287
+ if (value && inferLocation(value) === "local")
2288
+ return value.replace(/\/+$/, "");
2307
2289
  return undefined;
2308
2290
  }
2309
2291
  function toolsFromApp(app, url, options = {}) {