marona 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const packageVersion = "0.11.0";
1
+ export const packageVersion = "0.12.0";
2
2
  const standardInterfaces = ["api", "web", "mobile_app", "desktop", "whatsapp"];
3
3
  const interfaceNamePattern = "^[a-z][a-z0-9_-]{0,63}$";
4
4
  const standardExecutionModes = ["online", "hybrid", "offline"];
@@ -461,6 +461,192 @@ export class MCPConnection {
461
461
  return runtime.client(options);
462
462
  }
463
463
  }
464
+ export class A2APeer {
465
+ name;
466
+ url;
467
+ description;
468
+ authentication;
469
+ timeoutMs;
470
+ maxRetries;
471
+ permissions;
472
+ policy;
473
+ metadata;
474
+ card;
475
+ tool;
476
+ constructor(options) {
477
+ this.name = options.name.trim();
478
+ if (!this.name)
479
+ throw new EdgeRuntimeError("A2A peer name cannot be empty.");
480
+ this.url = validateA2AUrl(options.url, options.policy);
481
+ this.description = cleanString(options.description);
482
+ this.authentication = options.authentication;
483
+ this.timeoutMs = options.timeoutMs ?? 60_000;
484
+ this.maxRetries = options.maxRetries ?? 2;
485
+ this.permissions = [...new Set(options.permissions ?? [])];
486
+ this.policy = {
487
+ allowPrivateNetwork: options.policy?.allowPrivateNetwork ?? false,
488
+ requireHttps: options.policy?.requireHttps ?? true,
489
+ maxRequestBytes: options.policy?.maxRequestBytes ?? 1_000_000,
490
+ maxResponseBytes: options.policy?.maxResponseBytes ?? 10_000_000,
491
+ allowedSkills: options.policy?.allowedSkills ?? [],
492
+ deniedFields: options.policy?.deniedFields ?? [],
493
+ };
494
+ this.metadata = options.metadata ?? {};
495
+ if (this.timeoutMs <= 0 || this.maxRetries < 0) {
496
+ throw new EdgeRuntimeError("A2A timeout must be positive and retries non-negative.");
497
+ }
498
+ }
499
+ get toolName() {
500
+ const suffix = this.name.replace(/[^A-Za-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "peer";
501
+ return `a2a__${suffix}`.slice(0, 64);
502
+ }
503
+ async discover(force = false) {
504
+ if (this.card && !force)
505
+ return this.card;
506
+ const target = this.url.endsWith(".json")
507
+ ? this.url
508
+ : `${this.url.replace(/\/+$/, "")}/.well-known/agent-card.json`;
509
+ const response = await fetch(target, {
510
+ headers: this.headers(true),
511
+ redirect: "error",
512
+ signal: AbortSignal.timeout(Math.min(this.timeoutMs, 15_000)),
513
+ });
514
+ if (!response.ok)
515
+ throw new EdgeRuntimeError(`A2A Agent Card discovery failed with HTTP ${response.status}.`);
516
+ const card = asRecord(await response.json());
517
+ if (!card || !cleanString(card.name) || !Array.isArray(card.skills ?? [])) {
518
+ throw new EdgeRuntimeError("A2A Agent Card is invalid.");
519
+ }
520
+ this.card = card;
521
+ this.tool = undefined;
522
+ return card;
523
+ }
524
+ async run(input, options = {}) {
525
+ const card = await this.discover();
526
+ const published = new Set((Array.isArray(card.skills) ? card.skills : [])
527
+ .map(asRecord)
528
+ .map((value) => cleanString(value?.id))
529
+ .filter(Boolean));
530
+ if (options.skill && published.size && !published.has(options.skill)) {
531
+ throw new EdgeRuntimeError(`A2A peer does not publish skill '${options.skill}'.`);
532
+ }
533
+ if (options.skill && this.policy.allowedSkills.length && !this.policy.allowedSkills.includes(options.skill)) {
534
+ throw new EdgeRuntimeError(`A2A skill '${options.skill}' is not allowed by local policy.`);
535
+ }
536
+ const message = {
537
+ messageId: crypto.randomUUID(),
538
+ role: "ROLE_USER",
539
+ parts: typeof input === "string"
540
+ ? [{ text: input, mediaType: "text/plain" }]
541
+ : [{ data: redactA2AFields(input, new Set(this.policy.deniedFields)), mediaType: "application/json" }],
542
+ metadata: {
543
+ requested_skill: options.skill,
544
+ marona: {
545
+ user_id: options.context?.userId,
546
+ session_id: options.context?.sessionId ?? "default",
547
+ developer_id: options.context?.developerId,
548
+ permissions: this.permissions,
549
+ },
550
+ },
551
+ };
552
+ if (options.taskId)
553
+ message.taskId = options.taskId;
554
+ if (options.contextId)
555
+ message.contextId = options.contextId;
556
+ const endpoint = a2aInterface(card, this.url);
557
+ const url = endpoint.binding === "JSONRPC"
558
+ ? endpoint.url
559
+ : `${endpoint.url.replace(/\/+$/, "")}/message:send`;
560
+ const request = {
561
+ message,
562
+ configuration: { returnImmediately: false },
563
+ metadata: { peer: this.name },
564
+ };
565
+ const body = endpoint.binding === "JSONRPC"
566
+ ? { jsonrpc: "2.0", id: crypto.randomUUID(), method: "SendMessage", params: request }
567
+ : request;
568
+ const response = await fetch(url, {
569
+ method: "POST",
570
+ headers: this.headers(),
571
+ body: JSON.stringify(body),
572
+ redirect: "error",
573
+ signal: AbortSignal.timeout(this.timeoutMs),
574
+ });
575
+ if (!response.ok)
576
+ throw new EdgeRuntimeError(`A2A request failed with HTTP ${response.status}.`);
577
+ const payload = asRecord(await response.json()) ?? {};
578
+ const result = asRecord(payload.result) ?? payload;
579
+ const raw = asRecord(result.task) ?? result;
580
+ const task = normalizeA2ATask(raw);
581
+ if (["TASK_STATE_FAILED", "TASK_STATE_REJECTED", "TASK_STATE_CANCELED"].includes(task.state)) {
582
+ throw new EdgeRuntimeError(`A2A peer '${this.name}' returned ${task.state}.`);
583
+ }
584
+ return task;
585
+ }
586
+ functionTool() {
587
+ if (this.tool)
588
+ return this.tool;
589
+ const skills = (Array.isArray(this.card?.skills) ? this.card?.skills : [])
590
+ .map(asRecord)
591
+ .filter(Boolean);
592
+ const published = skills
593
+ .map((value) => `${cleanString(value.id)}: ${cleanString(value.description) ?? cleanString(value.name) ?? ""}`)
594
+ .filter((value) => !value.startsWith("undefined:"))
595
+ .join("; ");
596
+ const description = [
597
+ this.description ?? cleanString(this.card?.description) ?? `Collaborate with the independent A2A peer ${this.name}.`,
598
+ published ? `Available skills: ${published}` : "",
599
+ ].filter(Boolean).join(" ");
600
+ this.tool = functionTool({
601
+ name: this.toolName,
602
+ description,
603
+ inputSchema: {
604
+ type: "object",
605
+ properties: {
606
+ input: { description: "The minimum structured request the peer needs." },
607
+ skill: { type: ["string", "null"] },
608
+ task_id: { type: ["string", "null"] },
609
+ context_id: { type: ["string", "null"] },
610
+ },
611
+ required: ["input"],
612
+ additionalProperties: false,
613
+ },
614
+ outputSchema: { type: "object" },
615
+ timeoutMs: this.timeoutMs,
616
+ permissions: this.permissions,
617
+ metadata: { type: "a2a_peer", peer_name: this.name },
618
+ execute: async (argumentsValue, context) => {
619
+ const task = await this.run(argumentsValue.input, {
620
+ skill: cleanString(argumentsValue.skill),
621
+ taskId: cleanString(argumentsValue.task_id),
622
+ contextId: cleanString(argumentsValue.context_id),
623
+ context,
624
+ });
625
+ return task;
626
+ },
627
+ });
628
+ return this.tool;
629
+ }
630
+ headers(publicCard = false) {
631
+ const headers = {
632
+ "A2A-Version": "1.0",
633
+ "Content-Type": "application/json",
634
+ };
635
+ if (publicCard || !this.authentication || this.authentication.type === "none")
636
+ return headers;
637
+ if (this.authentication.type === "bearer") {
638
+ if (!this.authentication.token)
639
+ throw new EdgeRuntimeError(`A2A peer '${this.name}' requires a bearer token.`);
640
+ headers.Authorization = `Bearer ${this.authentication.token}`;
641
+ }
642
+ else {
643
+ if (!this.authentication.key)
644
+ throw new EdgeRuntimeError(`A2A peer '${this.name}' requires an API key.`);
645
+ headers[this.authentication.header ?? "X-API-Key"] = this.authentication.key;
646
+ }
647
+ return headers;
648
+ }
649
+ }
464
650
  export class MaronaAgentLoopError extends EdgeRuntimeError {
465
651
  }
466
652
  export class MaronaInputValidationError extends EdgeRuntimeError {
@@ -572,6 +758,7 @@ export class Agent {
572
758
  outputSchema;
573
759
  tools;
574
760
  handoffs;
761
+ peers;
575
762
  inputGuardrails;
576
763
  outputGuardrails;
577
764
  voice;
@@ -595,6 +782,7 @@ export class Agent {
595
782
  this.outputSchema = options.outputSchema;
596
783
  this.tools = options.tools;
597
784
  this.handoffs = options.handoffs ?? [];
785
+ this.peers = options.peers ?? [];
598
786
  this.inputGuardrails = options.inputGuardrails ?? [];
599
787
  this.outputGuardrails = options.outputGuardrails ?? [];
600
788
  this.voice = options.voice;
@@ -613,6 +801,7 @@ export class Agent {
613
801
  throw new EdgeRuntimeError("Agent model cannot be empty.");
614
802
  agentTools(this);
615
803
  agentHandoffs(this);
804
+ agentPeers(this);
616
805
  if (this.toolChoice === "required" && !agentHasTools(this)) {
617
806
  throw new EdgeRuntimeError("Agent toolChoice='required' needs a Hub connection or Agent tool.");
618
807
  }
@@ -633,6 +822,7 @@ export class Runner {
633
822
  const context = agentContext(agent, userId, sessionId);
634
823
  await runGuardrails(agent, "input", context, input);
635
824
  await agent.hooks?.onStart?.(context, input);
825
+ await resolveAgentPeers(agent);
636
826
  const graph = agentGraph(agent, context, options);
637
827
  const connection = agentConnection(agent);
638
828
  const runtime = connection?.agentRuntime() ?? agent.runtime ?? activeRuntime;
@@ -935,6 +1125,7 @@ export class RealtimeRunner {
935
1125
  return new RealtimeSession(descriptor, socket, agent, options);
936
1126
  }
937
1127
  static async createSessionDescriptor(agent, options = {}) {
1128
+ await resolveAgentPeers(agent);
938
1129
  const connection = agentConnection(agent);
939
1130
  const runtime = connection?.agentRuntime() ?? agent.runtime ?? activeRuntime;
940
1131
  if (!runtime)
@@ -1016,7 +1207,10 @@ function agentToolByName(agent, name) {
1016
1207
  return agentTools(agent).find((value) => value instanceof AgentTool && value.name === name);
1017
1208
  }
1018
1209
  function functionToolByName(agent, name) {
1019
- return agentTools(agent).find((value) => value instanceof FunctionTool && value.name === name);
1210
+ const tool = agentTools(agent).find((value) => value instanceof FunctionTool && value.name === name);
1211
+ if (tool)
1212
+ return tool;
1213
+ return agentPeers(agent).find((peer) => peer.toolName === name)?.functionTool();
1020
1214
  }
1021
1215
  function handoffByName(agent, name) {
1022
1216
  return agentHandoffs(agent).find((value) => value.name === name);
@@ -1065,6 +1259,15 @@ function realtimeAgentToolDefinitions(agent) {
1065
1259
  values.push(realtimeAgentFunction(value.name, value.description, value.inputSchema));
1066
1260
  }
1067
1261
  }
1262
+ for (const peer of agentPeers(agent)) {
1263
+ const tool = peer.functionTool();
1264
+ values.push({
1265
+ type: "function",
1266
+ name: tool.name,
1267
+ description: tool.description,
1268
+ parameters: tool.inputSchema,
1269
+ });
1270
+ }
1068
1271
  for (const value of agentHandoffs(agent)) {
1069
1272
  values.push(realtimeAgentFunction(value.name, value.description, value.inputSchema));
1070
1273
  }
@@ -1241,6 +1444,66 @@ function validateAgentToolName(value) {
1241
1444
  function agentSlug(value) {
1242
1445
  return value.trim().replace(/[^A-Za-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase().slice(0, 64) || "agent";
1243
1446
  }
1447
+ function validateA2AUrl(value, policy) {
1448
+ let url;
1449
+ try {
1450
+ url = new URL(value);
1451
+ }
1452
+ catch {
1453
+ throw new EdgeRuntimeError("A2A peer URL must be an absolute HTTP(S) URL.");
1454
+ }
1455
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash) {
1456
+ throw new EdgeRuntimeError("A2A peer URL must be a credential-free HTTP(S) URL.");
1457
+ }
1458
+ const local = ["localhost", "127.0.0.1", "::1", "[::1]"].includes(url.hostname);
1459
+ if ((policy?.requireHttps ?? true) && url.protocol !== "https:" && !local) {
1460
+ throw new EdgeRuntimeError("A2A peer URLs must use HTTPS outside localhost.");
1461
+ }
1462
+ return url.toString().replace(/\/$/, "");
1463
+ }
1464
+ function a2aInterface(card, fallbackUrl) {
1465
+ const interfaces = Array.isArray(card.supportedInterfaces) ? card.supportedInterfaces : [];
1466
+ for (const preferred of ["HTTP+JSON", "JSONRPC"]) {
1467
+ for (const raw of interfaces) {
1468
+ const value = asRecord(raw);
1469
+ if (cleanString(value?.protocolBinding)?.toUpperCase() === preferred) {
1470
+ return { url: cleanString(value?.url) ?? fallbackUrl, binding: preferred };
1471
+ }
1472
+ }
1473
+ }
1474
+ return { url: cleanString(card.url) ?? fallbackUrl, binding: "HTTP+JSON" };
1475
+ }
1476
+ function normalizeA2ATask(raw) {
1477
+ const status = asRecord(raw.status) ?? {};
1478
+ const state = cleanString(status.state) ?? cleanString(raw.state) ?? "TASK_STATE_UNSPECIFIED";
1479
+ const artifacts = (Array.isArray(raw.artifacts) ? raw.artifacts : [])
1480
+ .map(asRecord)
1481
+ .filter(Boolean);
1482
+ const outputs = artifacts.flatMap((artifact) => (Array.isArray(artifact.parts) ? artifact.parts : [])
1483
+ .map(asRecord)
1484
+ .filter(Boolean)
1485
+ .map((part) => part?.data ?? part?.text ?? part?.url ?? part?.raw)
1486
+ .filter((value) => value !== undefined));
1487
+ return {
1488
+ id: cleanString(raw.id ?? raw.taskId) ?? "",
1489
+ contextId: cleanString(raw.contextId ?? raw.context_id) ?? cleanString(raw.id) ?? "",
1490
+ state,
1491
+ output: outputs.length === 1 ? outputs[0] : outputs.length ? outputs : undefined,
1492
+ artifacts,
1493
+ inputRequired: ["TASK_STATE_INPUT_REQUIRED", "TASK_STATE_AUTH_REQUIRED"].includes(state),
1494
+ raw,
1495
+ };
1496
+ }
1497
+ function redactA2AFields(value, denied) {
1498
+ if (Array.isArray(value))
1499
+ return value.map((item) => redactA2AFields(item, denied));
1500
+ const record = asRecord(value);
1501
+ if (!record)
1502
+ return value;
1503
+ return Object.fromEntries(Object.entries(record)
1504
+ .filter(([key]) => !denied.has(key))
1505
+ .map(([key, item]) => [key, redactA2AFields(item, denied)]));
1506
+ }
1244
1507
  function agentTools(agent) {
1245
1508
  if (!agent.tools)
1246
1509
  return [];
@@ -1273,8 +1536,46 @@ function agentHandoffs(agent) {
1273
1536
  }
1274
1537
  return values;
1275
1538
  }
1539
+ function agentPeers(agent) {
1540
+ if (!Array.isArray(agent.peers))
1541
+ throw new EdgeRuntimeError("Agent peers must be an array.");
1542
+ const names = new Set();
1543
+ const toolNames = new Set(agentTools(agent)
1544
+ .filter((value) => value instanceof AgentTool || value instanceof FunctionTool)
1545
+ .map((value) => value.name));
1546
+ for (const peer of agent.peers) {
1547
+ if (!(peer instanceof A2APeer))
1548
+ throw new EdgeRuntimeError("Agent peers may contain only A2APeer values.");
1549
+ if (names.has(peer.name))
1550
+ throw new EdgeRuntimeError(`Duplicate A2A peer name '${peer.name}'.`);
1551
+ if (toolNames.has(peer.toolName))
1552
+ throw new EdgeRuntimeError(`A2A peer name conflicts with Agent tool '${peer.toolName}'.`);
1553
+ names.add(peer.name);
1554
+ toolNames.add(peer.toolName);
1555
+ }
1556
+ return agent.peers;
1557
+ }
1558
+ async function resolveAgentPeers(agent) {
1559
+ const visited = new Set();
1560
+ const peers = new Set();
1561
+ const visit = (current) => {
1562
+ if (visited.has(current))
1563
+ return;
1564
+ visited.add(current);
1565
+ for (const peer of agentPeers(current))
1566
+ peers.add(peer);
1567
+ for (const value of agentTools(current)) {
1568
+ if (value instanceof AgentTool)
1569
+ visit(value.targetAgent);
1570
+ }
1571
+ for (const value of agentHandoffs(current))
1572
+ visit(value.targetAgent);
1573
+ };
1574
+ visit(agent);
1575
+ await Promise.all([...peers].map((peer) => peer.discover()));
1576
+ }
1276
1577
  function agentHasTools(agent) {
1277
- return agentTools(agent).length > 0 || agentHandoffs(agent).length > 0;
1578
+ return agentTools(agent).length > 0 || agentHandoffs(agent).length > 0 || agentPeers(agent).length > 0;
1278
1579
  }
1279
1580
  function agentConnection(agent) {
1280
1581
  let found;
@@ -1315,6 +1616,8 @@ function agentRuntimeTools(agent) {
1315
1616
  else if (value instanceof AgentTool)
1316
1617
  visit(value.targetAgent);
1317
1618
  }
1619
+ for (const peer of agentPeers(current))
1620
+ values.push(peer.functionTool());
1318
1621
  for (const value of agentHandoffs(current))
1319
1622
  visit(value.targetAgent);
1320
1623
  };
@@ -1385,6 +1688,15 @@ function agentGraph(agent, context, options = {}) {
1385
1688
  input_schema: value.inputSchema,
1386
1689
  output_schema: value.outputSchema,
1387
1690
  }));
1691
+ const peerTools = agentPeers(current).map((peer) => {
1692
+ const tool = peer.functionTool();
1693
+ return {
1694
+ name: tool.name,
1695
+ description: tool.description,
1696
+ input_schema: tool.inputSchema,
1697
+ output_schema: tool.outputSchema,
1698
+ };
1699
+ });
1388
1700
  const transfers = agentHandoffs(current).map((value) => ({
1389
1701
  name: value.name,
1390
1702
  description: value.description,
@@ -1405,7 +1717,13 @@ function agentGraph(agent, context, options = {}) {
1405
1717
  input_schema: current.inputSchema,
1406
1718
  output_schema: current.outputSchema,
1407
1719
  hub_tools: agentTools(current).some((value) => value instanceof MCPConnection),
1408
- function_tools: functionTools,
1720
+ function_tools: [...functionTools, ...peerTools],
1721
+ peers: agentPeers(current).map((peer) => ({
1722
+ name: peer.name,
1723
+ tool_name: peer.toolName,
1724
+ description: peer.description,
1725
+ permissions: peer.permissions,
1726
+ })),
1409
1727
  delegations,
1410
1728
  handoffs: transfers,
1411
1729
  metadata: safeAgentMetadata(current.metadata),
@@ -2571,21 +2889,28 @@ class ResponsesClient {
2571
2889
  : [];
2572
2890
  if (!calls.length)
2573
2891
  return response;
2574
- const contextValues = asRecord(metadata.marona_tool_context) ?? {};
2575
- const context = {
2576
- userId: options.userId,
2577
- sessionId: cleanString(contextValues.session_id) ?? options.conversationId ?? "default",
2578
- developerId: cleanString(contextValues.developer_id),
2579
- permissions: new Set(Array.isArray(contextValues.permissions) ? contextValues.permissions.map(String) : []),
2580
- approvedTools: new Set(Array.isArray(contextValues.approved_tools) ? contextValues.approved_tools.map(String) : []),
2581
- metadata: {},
2582
- };
2583
2892
  for (const raw of calls) {
2584
2893
  const call = asRecord(raw);
2585
2894
  const name = cleanString(call?.name);
2586
2895
  const tool = name ? functions.get(name) : undefined;
2587
2896
  if (!call || !name || !tool)
2588
2897
  throw new EdgeRuntimeError(`Function tool '${name ?? ""}' is not available in this SDK process.`);
2898
+ const baseContext = asRecord(metadata.marona_tool_context) ?? {};
2899
+ const graph = asRecord(metadata.marona_multi_agent);
2900
+ const agents = asRecord(graph?.agents);
2901
+ const definition = asRecord(agents?.[cleanString(call.agent_id) ?? ""]);
2902
+ const contextValues = {
2903
+ ...baseContext,
2904
+ ...(asRecord(definition?.metadata) ?? {}),
2905
+ };
2906
+ const context = {
2907
+ userId: options.userId,
2908
+ sessionId: cleanString(contextValues.session_id) ?? options.conversationId ?? "default",
2909
+ developerId: cleanString(contextValues.developer_id),
2910
+ permissions: new Set(Array.isArray(contextValues.permissions) ? contextValues.permissions.map(String) : []),
2911
+ approvedTools: new Set(Array.isArray(contextValues.approved_tools) ? contextValues.approved_tools.map(String) : []),
2912
+ metadata: {},
2913
+ };
2589
2914
  const argumentsValue = asRecord(call.arguments) ?? {};
2590
2915
  results.push({
2591
2916
  call_id: cleanString(call.call_id) ?? "",