marona 0.3.10 → 0.4.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 +40 -0
- package/README.md +37 -12
- package/dist/index.d.ts +23 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +319 -339
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
export const packageVersion = "0.
|
|
1
|
+
export const packageVersion = "0.4.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
|
+
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 = [];
|
|
@@ -390,6 +392,116 @@ export class HubClient {
|
|
|
390
392
|
}
|
|
391
393
|
}
|
|
392
394
|
}
|
|
395
|
+
export class SkillStep {
|
|
396
|
+
definition;
|
|
397
|
+
constructor(definition) {
|
|
398
|
+
this.definition = definition;
|
|
399
|
+
}
|
|
400
|
+
get id() {
|
|
401
|
+
return String(this.definition.id);
|
|
402
|
+
}
|
|
403
|
+
output(name) {
|
|
404
|
+
const outputs = asRecord(this.definition.outputs) ?? {};
|
|
405
|
+
if (!(name in outputs)) {
|
|
406
|
+
throw new EdgeRuntimeError(`Step '${this.id}' does not declare output '${name}'.`);
|
|
407
|
+
}
|
|
408
|
+
return `{{ steps.${this.id}.${name} }}`;
|
|
409
|
+
}
|
|
410
|
+
toJSON() {
|
|
411
|
+
return { ...this.definition };
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
export function step(input) {
|
|
415
|
+
const id = input.id.trim();
|
|
416
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) {
|
|
417
|
+
throw new EdgeRuntimeError("Skill step ids must use lowercase kebab-case.");
|
|
418
|
+
}
|
|
419
|
+
if (!["reasoning", "approval", "app"].includes(input.type)) {
|
|
420
|
+
throw new EdgeRuntimeError("Skill step type must be 'reasoning', 'approval', or 'app'.");
|
|
421
|
+
}
|
|
422
|
+
const supportedOutputTypes = new Set(["string", "number", "integer", "boolean", "object", "array"]);
|
|
423
|
+
const outputs = {};
|
|
424
|
+
for (const [rawName, rawType] of Object.entries(input.outputs ?? {})) {
|
|
425
|
+
const name = rawName.trim();
|
|
426
|
+
const outputType = String(rawType).trim().toLowerCase();
|
|
427
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
|
|
428
|
+
throw new EdgeRuntimeError(`Step '${id}' has invalid output '${name}'.`);
|
|
429
|
+
}
|
|
430
|
+
if (!supportedOutputTypes.has(outputType)) {
|
|
431
|
+
throw new EdgeRuntimeError(`Step '${id}' output '${name}' has unsupported type '${rawType}'.`);
|
|
432
|
+
}
|
|
433
|
+
outputs[name] = outputType;
|
|
434
|
+
}
|
|
435
|
+
const condition = typeof input.condition === "string" && input.condition.includes("{{ steps.")
|
|
436
|
+
? { operator: "equals", left: input.condition, right: true }
|
|
437
|
+
: input.condition;
|
|
438
|
+
const definition = omitEmpty({
|
|
439
|
+
id,
|
|
440
|
+
type: input.type,
|
|
441
|
+
outputs,
|
|
442
|
+
condition,
|
|
443
|
+
});
|
|
444
|
+
if (input.type === "reasoning") {
|
|
445
|
+
if (input.message !== undefined || input.app !== undefined || input.capability !== undefined) {
|
|
446
|
+
throw new EdgeRuntimeError("Reasoning steps accept instruction, inputs, outputs, and condition only.");
|
|
447
|
+
}
|
|
448
|
+
const instruction = input.instruction?.trim() ?? "";
|
|
449
|
+
if (!instruction)
|
|
450
|
+
throw new EdgeRuntimeError("Reasoning instruction is required.");
|
|
451
|
+
Object.assign(definition, { instruction, inputs: input.inputs ?? {} });
|
|
452
|
+
}
|
|
453
|
+
else if (input.type === "approval") {
|
|
454
|
+
if (input.instruction !== undefined ||
|
|
455
|
+
input.app !== undefined ||
|
|
456
|
+
input.capability !== undefined ||
|
|
457
|
+
Object.keys(input.inputs ?? {}).length) {
|
|
458
|
+
throw new EdgeRuntimeError("Approval steps accept message, outputs, and condition only.");
|
|
459
|
+
}
|
|
460
|
+
const message = input.message?.trim() ?? "";
|
|
461
|
+
if (!message)
|
|
462
|
+
throw new EdgeRuntimeError("Approval message is required.");
|
|
463
|
+
const approvalOutputs = outputs;
|
|
464
|
+
if (Object.keys(approvalOutputs).length !== 1 || approvalOutputs.approved !== "boolean") {
|
|
465
|
+
throw new EdgeRuntimeError("Approval step outputs must be { approved: 'boolean' }.");
|
|
466
|
+
}
|
|
467
|
+
Object.assign(definition, { message, outputs: approvalOutputs });
|
|
468
|
+
}
|
|
469
|
+
else {
|
|
470
|
+
if (input.message !== undefined) {
|
|
471
|
+
throw new EdgeRuntimeError("App steps accept app, capability, instruction, inputs, outputs, and condition only.");
|
|
472
|
+
}
|
|
473
|
+
const app = input.app?.trim().toLowerCase() ?? "";
|
|
474
|
+
const capability = input.capability?.trim() ?? "";
|
|
475
|
+
const instruction = input.instruction?.trim() ?? "";
|
|
476
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(app)) {
|
|
477
|
+
throw new EdgeRuntimeError("Skill App names must use lowercase kebab-case.");
|
|
478
|
+
}
|
|
479
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*\.[A-Za-z0-9_-]+$/.test(capability)) {
|
|
480
|
+
throw new EdgeRuntimeError("Skill capabilities must use '<app-slug>.<tool-name>'.");
|
|
481
|
+
}
|
|
482
|
+
if (capability.split(".")[0] !== app) {
|
|
483
|
+
throw new EdgeRuntimeError("Skill App step capability must belong to its declared App.");
|
|
484
|
+
}
|
|
485
|
+
if (!instruction)
|
|
486
|
+
throw new EdgeRuntimeError("App instruction is required.");
|
|
487
|
+
Object.assign(definition, { app, capability, instruction, inputs: input.inputs ?? {} });
|
|
488
|
+
}
|
|
489
|
+
return new SkillStep(definition);
|
|
490
|
+
}
|
|
491
|
+
function skillReferences(value) {
|
|
492
|
+
if (Array.isArray(value))
|
|
493
|
+
return value.flatMap(skillReferences);
|
|
494
|
+
if (value && typeof value === "object") {
|
|
495
|
+
return Object.values(value).flatMap(skillReferences);
|
|
496
|
+
}
|
|
497
|
+
if (typeof value !== "string")
|
|
498
|
+
return [];
|
|
499
|
+
const pattern = /\{\{\s*steps\.([a-zA-Z0-9_-]+)(?:\.([a-zA-Z0-9_.-]+))?\s*\}\}/g;
|
|
500
|
+
return [...value.matchAll(pattern)].map((match) => ({
|
|
501
|
+
stepId: match[1],
|
|
502
|
+
...(match[2] ? { path: match[2] } : {}),
|
|
503
|
+
}));
|
|
504
|
+
}
|
|
393
505
|
export class SkillDefinition {
|
|
394
506
|
definition;
|
|
395
507
|
constructor(definition) {
|
|
@@ -406,19 +518,42 @@ export class SkillDefinition {
|
|
|
406
518
|
if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) {
|
|
407
519
|
throw new EdgeRuntimeError('Skill version must use semantic versioning.');
|
|
408
520
|
}
|
|
521
|
+
const steps = this.definition.steps.map((value) => value.toJSON());
|
|
409
522
|
const ids = new Set();
|
|
410
|
-
|
|
523
|
+
const availableOutputs = new Map();
|
|
524
|
+
for (const step of steps) {
|
|
411
525
|
const id = stringValue(step.id);
|
|
412
526
|
if (!id || ids.has(id)) {
|
|
413
527
|
throw new EdgeRuntimeError(`Skill step ids must be present and unique: '${id ?? ''}'.`);
|
|
414
528
|
}
|
|
415
529
|
ids.add(id);
|
|
530
|
+
for (const reference of skillReferences(step)) {
|
|
531
|
+
const declared = availableOutputs.get(reference.stepId);
|
|
532
|
+
if (!declared) {
|
|
533
|
+
throw new EdgeRuntimeError(`Step '${id}' references missing or later step '${reference.stepId}'.`);
|
|
534
|
+
}
|
|
535
|
+
const root = reference.path?.split(".")[0] ?? "";
|
|
536
|
+
if (root && !declared.has(root)) {
|
|
537
|
+
throw new EdgeRuntimeError(`Step '${id}' references undeclared output '${reference.stepId}.${root}'.`);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
availableOutputs.set(id, new Set(Object.keys(asRecord(step.outputs) ?? {})));
|
|
541
|
+
}
|
|
542
|
+
for (const reference of skillReferences(this.definition.result)) {
|
|
543
|
+
const declared = availableOutputs.get(reference.stepId);
|
|
544
|
+
if (!declared) {
|
|
545
|
+
throw new EdgeRuntimeError(`Skill result references unknown step '${reference.stepId}'.`);
|
|
546
|
+
}
|
|
547
|
+
const root = reference.path?.split(".")[0] ?? "";
|
|
548
|
+
if (root && !declared.has(root)) {
|
|
549
|
+
throw new EdgeRuntimeError(`Skill result references undeclared output '${reference.stepId}.${root}'.`);
|
|
550
|
+
}
|
|
416
551
|
}
|
|
417
|
-
const requiredApps = [...new Set(
|
|
552
|
+
const requiredApps = [...new Set(steps
|
|
418
553
|
.filter((step) => step.type === 'app')
|
|
419
554
|
.map((step) => stringValue(step.app))
|
|
420
555
|
.filter((value) => Boolean(value)))].sort();
|
|
421
|
-
const exactCapabilities = [...new Set(
|
|
556
|
+
const exactCapabilities = [...new Set(steps
|
|
422
557
|
.filter((step) => step.type === 'app')
|
|
423
558
|
.map((step) => stringValue(step.capability))
|
|
424
559
|
.filter((value) => Boolean(value)))].sort();
|
|
@@ -434,7 +569,7 @@ export class SkillDefinition {
|
|
|
434
569
|
name,
|
|
435
570
|
description: this.definition.description.trim(),
|
|
436
571
|
version,
|
|
437
|
-
steps
|
|
572
|
+
steps,
|
|
438
573
|
result: this.definition.result,
|
|
439
574
|
required_apps: requiredApps,
|
|
440
575
|
exact_capabilities: exactCapabilities,
|
|
@@ -462,14 +597,12 @@ class MaronaHubClient extends HubClient {
|
|
|
462
597
|
super(baseUrl, options);
|
|
463
598
|
this.mode = options.mode;
|
|
464
599
|
this.cache = options.cache;
|
|
465
|
-
this.localGatewayUrl = cleanUrl(options.localGatewayUrl ?? options.local_gateway_url);
|
|
466
600
|
}
|
|
467
601
|
mode;
|
|
468
602
|
cache;
|
|
469
|
-
localGatewayUrl;
|
|
470
603
|
async connectResult(apps, options = {}) {
|
|
471
604
|
const adapter = options.adapter ?? "tools";
|
|
472
|
-
const cached = connectFromCache(this.cache, apps, adapter, this.mode
|
|
605
|
+
const cached = connectFromCache(this.cache, apps, adapter, this.mode);
|
|
473
606
|
if (cached.connections.length > 0 && (this.mode === "offline" || this.mode === "hybrid")) {
|
|
474
607
|
return cached;
|
|
475
608
|
}
|
|
@@ -1083,7 +1216,6 @@ export class Marona extends RuntimeTransport {
|
|
|
1083
1216
|
mode;
|
|
1084
1217
|
modelFetchImpl;
|
|
1085
1218
|
developerInstructions;
|
|
1086
|
-
localGatewayUrl;
|
|
1087
1219
|
constructor(options = {}) {
|
|
1088
1220
|
const mode = options.mode ?? "online";
|
|
1089
1221
|
if (!["online", "offline", "hybrid"].includes(mode)) {
|
|
@@ -1093,8 +1225,6 @@ export class Marona extends RuntimeTransport {
|
|
|
1093
1225
|
this.mode = mode;
|
|
1094
1226
|
this.cache = options.cache ?? new MaronaCache();
|
|
1095
1227
|
this.developerInstructions = cleanString(options.developerInstructions ?? options.developer_instructions);
|
|
1096
|
-
this.localGatewayUrl =
|
|
1097
|
-
cleanUrl(options.localGatewayUrl ?? options.local_gateway_url) ?? defaultLocalGatewayUrl(this.baseUrl);
|
|
1098
1228
|
this.modelFetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
1099
1229
|
this.models = new ModelManager(this.cache, this.modelFetchImpl);
|
|
1100
1230
|
this.hub = new MaronaHubClient(options.hubUrl ?? "https://hub.marona.ai", {
|
|
@@ -1104,7 +1234,6 @@ export class Marona extends RuntimeTransport {
|
|
|
1104
1234
|
fetchImpl: options.hubFetchImpl ?? options.fetchImpl,
|
|
1105
1235
|
mode,
|
|
1106
1236
|
cache: this.cache,
|
|
1107
|
-
localGatewayUrl: this.localGatewayUrl,
|
|
1108
1237
|
});
|
|
1109
1238
|
this.skills = new SkillsClient(options.hubUrl ?? 'https://hub.marona.ai', {
|
|
1110
1239
|
apiKey: options.apiKey,
|
|
@@ -1141,7 +1270,7 @@ export class Marona extends RuntimeTransport {
|
|
|
1141
1270
|
]);
|
|
1142
1271
|
const messageOptions = { ...options, developerInstructions };
|
|
1143
1272
|
if (this.mode === "online" && model?.location === "remote") {
|
|
1144
|
-
const response = await this.
|
|
1273
|
+
const response = await this.modelMessage(model, text, messageOptions);
|
|
1145
1274
|
this.cacheTurn(text, response, messageOptions);
|
|
1146
1275
|
return response;
|
|
1147
1276
|
}
|
|
@@ -1155,7 +1284,7 @@ export class Marona extends RuntimeTransport {
|
|
|
1155
1284
|
}
|
|
1156
1285
|
if (model && (model.location === "local" || this.mode === "hybrid")) {
|
|
1157
1286
|
try {
|
|
1158
|
-
const response = await this.
|
|
1287
|
+
const response = await this.modelMessage(model, text, {
|
|
1159
1288
|
...messageOptions,
|
|
1160
1289
|
tools: options.tools ?? [],
|
|
1161
1290
|
});
|
|
@@ -1189,11 +1318,11 @@ export class Marona extends RuntimeTransport {
|
|
|
1189
1318
|
attachments: [...normalized.attachments, ...(attachments ?? [])],
|
|
1190
1319
|
});
|
|
1191
1320
|
}
|
|
1192
|
-
async
|
|
1321
|
+
async modelMessage(model, text, options) {
|
|
1193
1322
|
const messages = [
|
|
1194
1323
|
{
|
|
1195
1324
|
role: "system",
|
|
1196
|
-
content: "Marona
|
|
1325
|
+
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
1326
|
},
|
|
1198
1327
|
...(options.developerInstructions || options.developer_instructions
|
|
1199
1328
|
? [
|
|
@@ -1219,18 +1348,21 @@ export class Marona extends RuntimeTransport {
|
|
|
1219
1348
|
}
|
|
1220
1349
|
messages.push({
|
|
1221
1350
|
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.',
|
|
1351
|
+
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
1352
|
});
|
|
1224
1353
|
messages.push({ role: "user", content: text });
|
|
1225
|
-
|
|
1226
|
-
return this.localMessageWithPromptPlanning(model, messages, text, options);
|
|
1227
|
-
}
|
|
1228
|
-
const availableTools = options.tools?.length
|
|
1354
|
+
let availableTools = options.tools?.length
|
|
1229
1355
|
? [...options.tools]
|
|
1230
1356
|
: [capabilityDiscoveryTool(this.localCapabilityCatalog())];
|
|
1231
1357
|
let payload = {};
|
|
1232
1358
|
let reply = "";
|
|
1233
1359
|
const toolResults = [];
|
|
1360
|
+
const modelResponses = [];
|
|
1361
|
+
const runtimeSteps = [];
|
|
1362
|
+
const executedCapabilityCalls = new Map();
|
|
1363
|
+
let toolChoice = "required";
|
|
1364
|
+
let emptyDiscoveries = 0;
|
|
1365
|
+
let hasExecutedCapability = false;
|
|
1234
1366
|
let contextTier = model.contextWindow !== undefined && model.contextWindow <= 2048
|
|
1235
1367
|
? 2
|
|
1236
1368
|
: model.contextWindow !== undefined && model.contextWindow <= 4096
|
|
@@ -1239,7 +1371,7 @@ export class Marona extends RuntimeTransport {
|
|
|
1239
1371
|
for (let turn = 0; turn < 8; turn += 1) {
|
|
1240
1372
|
while (true) {
|
|
1241
1373
|
try {
|
|
1242
|
-
payload = await callChatModel(model, compactMessagesForContext(messages, contextTier), compactToolsForContext(availableTools, contextTier), this.modelFetchImpl);
|
|
1374
|
+
payload = await callChatModel(model, compactMessagesForContext(messages, contextTier), compactToolsForContext(availableTools, contextTier), this.modelFetchImpl, toolChoice);
|
|
1243
1375
|
break;
|
|
1244
1376
|
}
|
|
1245
1377
|
catch (error) {
|
|
@@ -1248,6 +1380,7 @@ export class Marona extends RuntimeTransport {
|
|
|
1248
1380
|
contextTier += 1;
|
|
1249
1381
|
}
|
|
1250
1382
|
}
|
|
1383
|
+
modelResponses.push(payload);
|
|
1251
1384
|
reply = modelText(payload);
|
|
1252
1385
|
const toolCalls = modelToolCalls(payload);
|
|
1253
1386
|
if (!toolCalls.length || !availableTools.length)
|
|
@@ -1256,19 +1389,62 @@ export class Marona extends RuntimeTransport {
|
|
|
1256
1389
|
for (const call of toolCalls) {
|
|
1257
1390
|
if (toolCallName(call) === 'marona__discover_capabilities') {
|
|
1258
1391
|
const discovery = this.discoverLocalCapabilities(call);
|
|
1259
|
-
|
|
1392
|
+
availableTools = [capabilityDiscoveryTool(this.localCapabilityCatalog()), ...discovery.tools];
|
|
1393
|
+
if (discovery.tools.length) {
|
|
1394
|
+
toolChoice = "required";
|
|
1395
|
+
}
|
|
1396
|
+
else {
|
|
1397
|
+
emptyDiscoveries += 1;
|
|
1398
|
+
toolChoice = hasExecutedCapability || emptyDiscoveries >= 2 ? "auto" : "required";
|
|
1399
|
+
}
|
|
1400
|
+
runtimeSteps.push(discovery.result);
|
|
1260
1401
|
roundResults.push(discovery.result);
|
|
1261
1402
|
continue;
|
|
1262
1403
|
}
|
|
1404
|
+
const callName = toolCallName(call);
|
|
1405
|
+
const callArguments = toolCallArguments(call);
|
|
1406
|
+
const callKey = `${callName}:${JSON.stringify(callArguments)}`;
|
|
1407
|
+
const previousResult = executedCapabilityCalls.get(callKey);
|
|
1408
|
+
if (previousResult) {
|
|
1409
|
+
const repeatedResult = {
|
|
1410
|
+
status: "completed",
|
|
1411
|
+
success: true,
|
|
1412
|
+
tool_name: callName,
|
|
1413
|
+
arguments: callArguments,
|
|
1414
|
+
result: {
|
|
1415
|
+
status: "already_executed",
|
|
1416
|
+
message: "This exact capability call already ran in the current request. Use its existing result to answer the user.",
|
|
1417
|
+
previous_result: toolResultForModel(previousResult),
|
|
1418
|
+
},
|
|
1419
|
+
};
|
|
1420
|
+
runtimeSteps.push(repeatedResult);
|
|
1421
|
+
roundResults.push(repeatedResult);
|
|
1422
|
+
availableTools = [];
|
|
1423
|
+
toolChoice = "auto";
|
|
1424
|
+
continue;
|
|
1425
|
+
}
|
|
1263
1426
|
const result = await executeToolCall(call, availableTools, {
|
|
1264
1427
|
offline: this.mode === "offline",
|
|
1265
1428
|
fetchImpl: this.modelFetchImpl,
|
|
1266
1429
|
identityHeaders: localIdentityHeaders(options.identityToken ?? options.identity_token, options.interfaceName ?? options.interface ?? "api", options.conversationId ?? options.conversation_id),
|
|
1267
1430
|
});
|
|
1431
|
+
executedCapabilityCalls.set(callKey, result);
|
|
1268
1432
|
toolResults.push(result);
|
|
1433
|
+
runtimeSteps.push(result);
|
|
1434
|
+
availableTools = [capabilityDiscoveryTool(this.localCapabilityCatalog())];
|
|
1435
|
+
toolChoice = "auto";
|
|
1436
|
+
emptyDiscoveries = 0;
|
|
1437
|
+
hasExecutedCapability = true;
|
|
1269
1438
|
roundResults.push(result);
|
|
1270
1439
|
}
|
|
1271
|
-
messages.push(
|
|
1440
|
+
messages.push({
|
|
1441
|
+
role: "system",
|
|
1442
|
+
content: `Marona Runtime results from the previous model-selected calls:\n${JSON.stringify(roundResults.map(toolResultForModel))}\n` +
|
|
1443
|
+
"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.",
|
|
1444
|
+
});
|
|
1445
|
+
}
|
|
1446
|
+
if (toolResults.length && !reply) {
|
|
1447
|
+
reply = toolResultDisplayText(toolResults.at(-1));
|
|
1272
1448
|
}
|
|
1273
1449
|
return {
|
|
1274
1450
|
status: "completed",
|
|
@@ -1289,148 +1465,11 @@ export class Marona extends RuntimeTransport {
|
|
|
1289
1465
|
.map((tool) => stringValue(asRecord(tool.function)?.name))
|
|
1290
1466
|
.filter(Boolean),
|
|
1291
1467
|
model_response: payload,
|
|
1468
|
+
model_responses: modelResponses,
|
|
1469
|
+
...(runtimeSteps.length ? { runtime_steps: runtimeSteps } : {}),
|
|
1292
1470
|
},
|
|
1293
1471
|
};
|
|
1294
1472
|
}
|
|
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
1473
|
localCapabilityCatalog() {
|
|
1435
1474
|
const payload = this.cache.loadSyncPayload() ?? {};
|
|
1436
1475
|
const apps = Array.isArray(payload.available_agent_apps)
|
|
@@ -1441,26 +1480,41 @@ export class Marona extends RuntimeTransport {
|
|
|
1441
1480
|
? payload.items
|
|
1442
1481
|
: [];
|
|
1443
1482
|
const skills = Array.isArray(payload.available_skills) ? payload.available_skills : [];
|
|
1483
|
+
const managedCapabilities = new Set(skills.flatMap((raw) => {
|
|
1484
|
+
const skill = asRecord(raw);
|
|
1485
|
+
return skill ? skillManagedCapabilities(skill) : [];
|
|
1486
|
+
}));
|
|
1444
1487
|
const supportedApps = apps
|
|
1445
1488
|
.map(asRecord)
|
|
1446
1489
|
.filter((app) => {
|
|
1447
1490
|
if (!app || !appSupportsMode(app, this.mode))
|
|
1448
1491
|
return false;
|
|
1449
|
-
const target = selectExecutionTarget(app, this.mode
|
|
1492
|
+
const target = selectExecutionTarget(app, this.mode);
|
|
1450
1493
|
return Boolean(target && !target.installRequired);
|
|
1451
1494
|
});
|
|
1452
1495
|
const supportedSlugs = new Set(supportedApps.map((app) => stringValue(app.slug)).filter((slug) => Boolean(slug)));
|
|
1453
1496
|
return {
|
|
1454
|
-
apps: supportedApps.
|
|
1455
|
-
slug
|
|
1456
|
-
|
|
1457
|
-
|
|
1497
|
+
apps: supportedApps.flatMap((app) => {
|
|
1498
|
+
const slug = stringValue(app.slug);
|
|
1499
|
+
const capabilityCount = listOfRecords(app.tools).filter((tool) => {
|
|
1500
|
+
const name = stringValue(tool.name);
|
|
1501
|
+
return Boolean(slug && name && !managedCapabilities.has(`${slug}.${name}`));
|
|
1502
|
+
}).length;
|
|
1503
|
+
return capabilityCount ? [{
|
|
1504
|
+
slug: app.slug,
|
|
1505
|
+
description: shortCatalogText(app.description ?? app.tagline),
|
|
1506
|
+
capability_count: capabilityCount,
|
|
1507
|
+
}] : [];
|
|
1508
|
+
}),
|
|
1458
1509
|
skills: skills
|
|
1459
1510
|
.map(asRecord)
|
|
1460
1511
|
.filter((skill) => Boolean(skill) && skillSupportedBy(skill, supportedSlugs))
|
|
1461
1512
|
.map((skill) => ({
|
|
1462
1513
|
name: skill.name,
|
|
1463
1514
|
description: shortCatalogText(skill.description),
|
|
1515
|
+
required_apps: skillRequiredApps(skill),
|
|
1516
|
+
managed_capabilities: skillManagedCapabilities(skill),
|
|
1517
|
+
workflow_purpose: shortCatalogText(skillManifest(skill).description),
|
|
1464
1518
|
})),
|
|
1465
1519
|
};
|
|
1466
1520
|
}
|
|
@@ -1468,6 +1522,11 @@ export class Marona extends RuntimeTransport {
|
|
|
1468
1522
|
const args = toolCallArguments(call);
|
|
1469
1523
|
const requestedApps = new Set(stringList(args.app_slugs));
|
|
1470
1524
|
const requestedSkills = new Set(stringList(args.skill_names));
|
|
1525
|
+
const requestedCapabilities = new Set(stringList(args.capability_names));
|
|
1526
|
+
for (const capability of requestedCapabilities) {
|
|
1527
|
+
if (capability.includes('.'))
|
|
1528
|
+
requestedApps.add(capability.split('.')[0]);
|
|
1529
|
+
}
|
|
1471
1530
|
const payload = this.cache.loadSyncPayload() ?? {};
|
|
1472
1531
|
if (!requestedApps.size && !requestedSkills.size) {
|
|
1473
1532
|
return {
|
|
@@ -1488,9 +1547,19 @@ export class Marona extends RuntimeTransport {
|
|
|
1488
1547
|
return Boolean(name && requestedSkills.has(name));
|
|
1489
1548
|
});
|
|
1490
1549
|
for (const rawSkill of selectedSkills) {
|
|
1491
|
-
|
|
1550
|
+
const skill = asRecord(rawSkill);
|
|
1551
|
+
if (skill)
|
|
1552
|
+
skillRequiredApps(skill).forEach((slug) => requestedApps.add(slug));
|
|
1492
1553
|
}
|
|
1493
|
-
const exactCapabilities = new Set(selectedSkills.flatMap((
|
|
1554
|
+
const exactCapabilities = new Set(selectedSkills.flatMap((raw) => {
|
|
1555
|
+
const skill = asRecord(raw);
|
|
1556
|
+
return skill ? skillExactCapabilities(skill) : [];
|
|
1557
|
+
}));
|
|
1558
|
+
requestedCapabilities.forEach((capability) => exactCapabilities.add(capability));
|
|
1559
|
+
const managedCapabilities = new Set(rawSkills.flatMap((raw) => {
|
|
1560
|
+
const skill = asRecord(raw);
|
|
1561
|
+
return skill ? skillManagedCapabilities(skill) : [];
|
|
1562
|
+
}));
|
|
1494
1563
|
const rawApps = Array.isArray(payload.available_agent_apps)
|
|
1495
1564
|
? payload.available_agent_apps
|
|
1496
1565
|
: Array.isArray(payload.apps)
|
|
@@ -1500,12 +1569,13 @@ export class Marona extends RuntimeTransport {
|
|
|
1500
1569
|
: [];
|
|
1501
1570
|
const tools = [];
|
|
1502
1571
|
const apps = [];
|
|
1572
|
+
const capabilityOptions = [];
|
|
1503
1573
|
for (const rawApp of rawApps) {
|
|
1504
1574
|
const app = asRecord(rawApp);
|
|
1505
1575
|
const slug = stringValue(app?.slug);
|
|
1506
1576
|
if (!app || !slug || !requestedApps.has(slug) || !appSupportsMode(app, this.mode))
|
|
1507
1577
|
continue;
|
|
1508
|
-
const target = selectExecutionTarget(app, this.mode
|
|
1578
|
+
const target = selectExecutionTarget(app, this.mode);
|
|
1509
1579
|
if (!target || target.installRequired)
|
|
1510
1580
|
continue;
|
|
1511
1581
|
let appTools = toolsFromApp(app, stringValue(target.url), {
|
|
@@ -1518,6 +1588,18 @@ export class Marona extends RuntimeTransport {
|
|
|
1518
1588
|
return Boolean(name && exactCapabilities.has(`${slug}.${name}`));
|
|
1519
1589
|
});
|
|
1520
1590
|
}
|
|
1591
|
+
else {
|
|
1592
|
+
capabilityOptions.push(...appTools.flatMap((tool) => {
|
|
1593
|
+
const name = toolFunctionName(tool)?.split('__').at(-1);
|
|
1594
|
+
if (!name || managedCapabilities.has(`${slug}.${name}`))
|
|
1595
|
+
return [];
|
|
1596
|
+
return [{
|
|
1597
|
+
name: `${slug}.${name}`,
|
|
1598
|
+
description: shortCatalogText(asRecord(tool.function)?.description),
|
|
1599
|
+
}];
|
|
1600
|
+
}));
|
|
1601
|
+
appTools = [];
|
|
1602
|
+
}
|
|
1521
1603
|
tools.push(...appTools);
|
|
1522
1604
|
apps.push({
|
|
1523
1605
|
slug,
|
|
@@ -1525,6 +1607,19 @@ export class Marona extends RuntimeTransport {
|
|
|
1525
1607
|
installed: !target.installRequired,
|
|
1526
1608
|
});
|
|
1527
1609
|
}
|
|
1610
|
+
if (!tools.length && capabilityOptions.length) {
|
|
1611
|
+
return {
|
|
1612
|
+
tools: [],
|
|
1613
|
+
result: {
|
|
1614
|
+
tool_call_id: call.id,
|
|
1615
|
+
result: {
|
|
1616
|
+
status: 'capability_selection_required',
|
|
1617
|
+
capabilities: capabilityOptions,
|
|
1618
|
+
instruction: 'Select only the exact capability identifiers needed for the current request, then call marona__discover_capabilities again with capability_names.',
|
|
1619
|
+
},
|
|
1620
|
+
},
|
|
1621
|
+
};
|
|
1622
|
+
}
|
|
1528
1623
|
const skills = compactLocalSkills(selectedSkills);
|
|
1529
1624
|
return {
|
|
1530
1625
|
tools,
|
|
@@ -1656,7 +1751,7 @@ function redactModel(model) {
|
|
|
1656
1751
|
const { apiKey: _apiKey, ...safe } = model;
|
|
1657
1752
|
return safe;
|
|
1658
1753
|
}
|
|
1659
|
-
async function callChatModel(model, messages, tools, fetchImpl) {
|
|
1754
|
+
async function callChatModel(model, messages, tools, fetchImpl, toolChoice = "auto") {
|
|
1660
1755
|
if (model.protocol && !["chat_completions", "custom_http"].includes(model.protocol)) {
|
|
1661
1756
|
throw new MaronaModelError(`Model '${model.name}' does not support chat messages yet.`);
|
|
1662
1757
|
}
|
|
@@ -1670,7 +1765,7 @@ async function callChatModel(model, messages, tools, fetchImpl) {
|
|
|
1670
1765
|
...(tools.length
|
|
1671
1766
|
? {
|
|
1672
1767
|
tools: tools.map((tool) => asRecord(tool.function) ? { type: "function", function: tool.function } : tool),
|
|
1673
|
-
tool_choice:
|
|
1768
|
+
tool_choice: toolChoice,
|
|
1674
1769
|
}
|
|
1675
1770
|
: {}),
|
|
1676
1771
|
}),
|
|
@@ -1703,64 +1798,6 @@ function modelText(payload) {
|
|
|
1703
1798
|
const message = asRecord(first?.message);
|
|
1704
1799
|
return stringValue(message?.content) ?? "";
|
|
1705
1800
|
}
|
|
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
1801
|
function modelToolCalls(payload) {
|
|
1765
1802
|
const choices = Array.isArray(payload.choices) ? payload.choices : [];
|
|
1766
1803
|
const first = asRecord(choices[0]);
|
|
@@ -1768,19 +1805,6 @@ function modelToolCalls(payload) {
|
|
|
1768
1805
|
const calls = Array.isArray(message?.tool_calls) ? message.tool_calls : [];
|
|
1769
1806
|
return calls.map(asRecord).filter(Boolean);
|
|
1770
1807
|
}
|
|
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
1808
|
function toolResultForModel(result) {
|
|
1785
1809
|
if (Object.prototype.hasOwnProperty.call(result, "result")) {
|
|
1786
1810
|
return compactToolValue(result.result);
|
|
@@ -1790,38 +1814,17 @@ function toolResultForModel(result) {
|
|
|
1790
1814
|
function toolResultDisplayText(result) {
|
|
1791
1815
|
const value = asRecord(result.result) ?? result;
|
|
1792
1816
|
const structured = asRecord(value.structuredContent) ?? asRecord(value.structured_content);
|
|
1793
|
-
|
|
1817
|
+
for (const record of [structured, value]) {
|
|
1818
|
+
if (!record)
|
|
1819
|
+
continue;
|
|
1794
1820
|
for (const key of ['content', 'message', 'summary']) {
|
|
1795
|
-
const text = stringValue(
|
|
1821
|
+
const text = stringValue(record[key]);
|
|
1796
1822
|
if (text)
|
|
1797
1823
|
return text;
|
|
1798
1824
|
}
|
|
1799
1825
|
}
|
|
1800
1826
|
return contentBlocksText(value.content);
|
|
1801
1827
|
}
|
|
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
1828
|
function compactToolValue(value, depth = 0) {
|
|
1826
1829
|
if (value == null || typeof value === "number" || typeof value === "boolean")
|
|
1827
1830
|
return value;
|
|
@@ -2099,7 +2102,8 @@ function compactLocalSkills(value) {
|
|
|
2099
2102
|
name: skill.name,
|
|
2100
2103
|
description: skill.description,
|
|
2101
2104
|
version: skill.version,
|
|
2102
|
-
required_apps:
|
|
2105
|
+
required_apps: skillRequiredApps(skill),
|
|
2106
|
+
managed_capabilities: skillManagedCapabilities(skill),
|
|
2103
2107
|
steps: Array.isArray(manifest.steps) ? manifest.steps : [],
|
|
2104
2108
|
},
|
|
2105
2109
|
];
|
|
@@ -2130,6 +2134,12 @@ function capabilityDiscoveryTool(catalog = { apps: [], skills: [] }) {
|
|
|
2130
2134
|
maxItems: 3,
|
|
2131
2135
|
description: 'Exact Skill identifiers selected from the installed catalog.',
|
|
2132
2136
|
},
|
|
2137
|
+
capability_names: {
|
|
2138
|
+
type: 'array',
|
|
2139
|
+
items: { type: 'string' },
|
|
2140
|
+
maxItems: 5,
|
|
2141
|
+
description: 'Exact capability identifiers returned by a previous discovery call.',
|
|
2142
|
+
},
|
|
2133
2143
|
},
|
|
2134
2144
|
required: ['query'],
|
|
2135
2145
|
additionalProperties: false,
|
|
@@ -2156,8 +2166,29 @@ function toolCallArguments(call) {
|
|
|
2156
2166
|
function stringList(value) {
|
|
2157
2167
|
return Array.isArray(value) ? value.map(String).map((item) => item.trim()).filter(Boolean) : [];
|
|
2158
2168
|
}
|
|
2169
|
+
function skillManifest(skill) {
|
|
2170
|
+
return asRecord(skill.manifest) ?? {};
|
|
2171
|
+
}
|
|
2172
|
+
function skillRequiredApps(skill) {
|
|
2173
|
+
return stringList(skill.required_apps ?? skillManifest(skill).required_apps);
|
|
2174
|
+
}
|
|
2175
|
+
function skillExactCapabilities(skill) {
|
|
2176
|
+
const manifest = skillManifest(skill);
|
|
2177
|
+
const exact = stringList(skill.exact_capabilities ?? manifest.exact_capabilities);
|
|
2178
|
+
if (exact.length)
|
|
2179
|
+
return exact;
|
|
2180
|
+
return listOfRecords(manifest.steps)
|
|
2181
|
+
.filter((step) => step.type === 'app')
|
|
2182
|
+
.map((step) => stringValue(step.capability))
|
|
2183
|
+
.filter((value) => Boolean(value));
|
|
2184
|
+
}
|
|
2185
|
+
function skillManagedCapabilities(skill) {
|
|
2186
|
+
const manifest = skillManifest(skill);
|
|
2187
|
+
const managed = stringList(skill.managed_capabilities ?? manifest.managed_capabilities);
|
|
2188
|
+
return managed.length ? managed : skillExactCapabilities(skill);
|
|
2189
|
+
}
|
|
2159
2190
|
function skillSupportedBy(skill, appSlugs) {
|
|
2160
|
-
const required =
|
|
2191
|
+
const required = skillRequiredApps(skill);
|
|
2161
2192
|
return !required.length || required.every((slug) => appSlugs.has(slug));
|
|
2162
2193
|
}
|
|
2163
2194
|
function shortCatalogText(value) {
|
|
@@ -2169,16 +2200,6 @@ function shortCatalogText(value) {
|
|
|
2169
2200
|
function toolFunctionName(tool) {
|
|
2170
2201
|
return stringValue(asRecord(tool.function)?.name);
|
|
2171
2202
|
}
|
|
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
2203
|
function sanitizeContextValue(value) {
|
|
2183
2204
|
if (Array.isArray(value))
|
|
2184
2205
|
return value.map(sanitizeContextValue);
|
|
@@ -2267,7 +2288,7 @@ function firstItems(value, count) {
|
|
|
2267
2288
|
function lastItems(value, count) {
|
|
2268
2289
|
return Array.isArray(value) ? value.slice(-count) : [];
|
|
2269
2290
|
}
|
|
2270
|
-
function connectFromCache(cache, apps, adapter, mode
|
|
2291
|
+
function connectFromCache(cache, apps, adapter, mode) {
|
|
2271
2292
|
const connections = [];
|
|
2272
2293
|
const resolvedApps = [];
|
|
2273
2294
|
const missingApps = [];
|
|
@@ -2278,7 +2299,7 @@ function connectFromCache(cache, apps, adapter, mode, localGatewayUrl) {
|
|
|
2278
2299
|
continue;
|
|
2279
2300
|
}
|
|
2280
2301
|
resolvedApps.push(app);
|
|
2281
|
-
const target = selectExecutionTarget(app, mode
|
|
2302
|
+
const target = selectExecutionTarget(app, mode);
|
|
2282
2303
|
if (!target) {
|
|
2283
2304
|
missingApps.push(slug);
|
|
2284
2305
|
continue;
|
|
@@ -2352,30 +2373,29 @@ function executionTargets(app) {
|
|
|
2352
2373
|
type: String(target?.type ?? target?.kind ?? "").trim().toLowerCase(),
|
|
2353
2374
|
}));
|
|
2354
2375
|
}
|
|
2355
|
-
function selectExecutionTarget(app, mode
|
|
2376
|
+
function selectExecutionTarget(app, mode) {
|
|
2356
2377
|
const targets = executionTargets(app);
|
|
2357
2378
|
if (!targets.length)
|
|
2358
2379
|
return undefined;
|
|
2359
|
-
const slug = stringValue(app.slug) ?? stringValue(app.name) ?? "app";
|
|
2360
2380
|
let candidates;
|
|
2361
2381
|
if (mode === "offline") {
|
|
2362
|
-
candidates = targets.filter((target) => ["offline", "hybrid"].includes(String(target.mode)) && target.type
|
|
2382
|
+
candidates = targets.filter((target) => ["offline", "hybrid"].includes(String(target.mode)) && localExecutionTargetTypes.has(String(target.type)));
|
|
2363
2383
|
}
|
|
2364
2384
|
else if (mode === "hybrid") {
|
|
2365
2385
|
candidates = [
|
|
2366
|
-
...targets.filter((target) => ["offline", "hybrid"].includes(String(target.mode)) && target.type
|
|
2367
|
-
...targets.filter((target) => ["online", "hybrid"].includes(String(target.mode)) &&
|
|
2386
|
+
...targets.filter((target) => ["offline", "hybrid"].includes(String(target.mode)) && localExecutionTargetTypes.has(String(target.type))),
|
|
2387
|
+
...targets.filter((target) => ["online", "hybrid"].includes(String(target.mode)) && remoteExecutionTargetTypes.has(String(target.type))),
|
|
2368
2388
|
];
|
|
2369
2389
|
}
|
|
2370
2390
|
else {
|
|
2371
|
-
candidates = targets.filter((target) => ["online", "hybrid"].includes(String(target.mode)) &&
|
|
2391
|
+
candidates = targets.filter((target) => ["online", "hybrid"].includes(String(target.mode)) && remoteExecutionTargetTypes.has(String(target.type)));
|
|
2372
2392
|
}
|
|
2373
2393
|
let unavailableLocal;
|
|
2374
2394
|
for (const target of candidates) {
|
|
2375
|
-
const url = targetRuntimeUrl(target, mode
|
|
2395
|
+
const url = targetRuntimeUrl(target, mode);
|
|
2376
2396
|
if (url)
|
|
2377
2397
|
return { target, url, installRequired: false };
|
|
2378
|
-
if (
|
|
2398
|
+
if (localExecutionTargetTypes.has(String(target.type))) {
|
|
2379
2399
|
unavailableLocal = { target, installRequired: true };
|
|
2380
2400
|
if (mode === "offline")
|
|
2381
2401
|
return unavailableLocal;
|
|
@@ -2383,62 +2403,22 @@ function selectExecutionTarget(app, mode, localGatewayUrl) {
|
|
|
2383
2403
|
}
|
|
2384
2404
|
return unavailableLocal;
|
|
2385
2405
|
}
|
|
2386
|
-
function targetRuntimeUrl(target, mode
|
|
2406
|
+
function targetRuntimeUrl(target, mode) {
|
|
2387
2407
|
const type = stringValue(target.type);
|
|
2388
|
-
if (type
|
|
2408
|
+
if (remoteExecutionTargetTypes.has(type ?? "")) {
|
|
2389
2409
|
if (mode === "offline")
|
|
2390
2410
|
return undefined;
|
|
2391
2411
|
return stringValue(target.url)?.replace(/\/+$/, "");
|
|
2392
2412
|
}
|
|
2393
|
-
|
|
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)
|
|
2413
|
+
if (!localExecutionTargetTypes.has(type ?? ""))
|
|
2419
2414
|
return undefined;
|
|
2420
|
-
|
|
2421
|
-
if (!Number.isInteger(port) || port <= 0 || port > 65535)
|
|
2422
|
-
return undefined;
|
|
2423
|
-
return port;
|
|
2424
|
-
}
|
|
2425
|
-
function cleanUrl(value) {
|
|
2426
|
-
if (typeof value !== "string")
|
|
2415
|
+
if (target.installed !== true)
|
|
2427
2416
|
return undefined;
|
|
2428
|
-
|
|
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 {
|
|
2417
|
+
if (asRecord(target.state_sync) && target.state_ready !== true)
|
|
2440
2418
|
return undefined;
|
|
2441
|
-
|
|
2419
|
+
const value = stringValue(target.resolved_url);
|
|
2420
|
+
if (value && inferLocation(value) === "local")
|
|
2421
|
+
return value.replace(/\/+$/, "");
|
|
2442
2422
|
return undefined;
|
|
2443
2423
|
}
|
|
2444
2424
|
function toolsFromApp(app, url, options = {}) {
|