marona 1.1.4 → 2.0.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,8 @@
1
- export const packageVersion = "1.1.4";
1
+ import { matchesSchema } from "./schema.js";
2
+ import { A2ATaskStore, AgentCardResolver, A2AProtocolError, A2ASecurityError, A2ATaskError, a2aParts, parseA2ATask, parseA2AEvent, readA2AResponse, readA2AStream, unwrapA2A, validateA2AHost } from "./a2a.js";
3
+ export { A2ATaskStore, AgentCardResolver, A2AError, A2ADiscoveryError, A2AProtocolError, A2ASecurityError, A2ATaskError } from "./a2a.js";
4
+ export { A2AServer } from "./a2a-server.js";
5
+ export const packageVersion = "2.0.0";
2
6
  const maronaApiKeyRequired = "Marona Developer Key is required.\n\n" +
3
7
  "Provide it through the SDK configuration or set the MARONA_API_KEY environment variable.\n\n" +
4
8
  "Create/manage developer keys from the Marona Developer Portal.";
@@ -535,6 +539,10 @@ export class A2APeer {
535
539
  permissions;
536
540
  policy;
537
541
  metadata;
542
+ taskStore;
543
+ client;
544
+ resolver;
545
+ fetchImpl;
538
546
  card;
539
547
  tool;
540
548
  constructor(options) {
@@ -556,97 +564,137 @@ export class A2APeer {
556
564
  deniedFields: options.policy?.deniedFields ?? [],
557
565
  };
558
566
  this.metadata = options.metadata ?? {};
559
- if (this.timeoutMs <= 0 || this.maxRetries < 0) {
560
- throw new EdgeRuntimeError("A2A timeout must be positive and retries non-negative.");
567
+ this.taskStore = options.taskStore ?? new A2ATaskStore();
568
+ this.fetchImpl = options.fetchImpl ?? ((...args) => fetch(...args));
569
+ if (this.timeoutMs <= 0 || !Number.isInteger(this.maxRetries) || this.maxRetries < 0
570
+ || this.policy.maxRequestBytes <= 0 || this.policy.maxResponseBytes <= 0 || (options.cardTtlMs ?? 0) < 0) {
571
+ throw new EdgeRuntimeError("A2A limits must be positive and retries/cache TTL non-negative.");
561
572
  }
573
+ this.resolver = new AgentCardResolver({ timeoutMs: Math.min(this.timeoutMs, 15_000), cacheTtlMs: options.cardTtlMs, policy: this.policy, fetchImpl: this.fetchImpl });
574
+ this.client = new A2AClient(this);
562
575
  }
563
576
  get toolName() {
564
577
  const suffix = this.name.replace(/[^A-Za-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "peer";
565
578
  return `a2a__${suffix}`.slice(0, 64);
566
579
  }
567
580
  async discover(force = false) {
568
- if (this.card && !force)
569
- return this.card;
570
- const target = this.url.endsWith(".json")
571
- ? this.url
572
- : `${this.url.replace(/\/+$/, "")}/.well-known/agent-card.json`;
573
- const response = await fetch(target, {
574
- headers: this.headers(true),
575
- redirect: "error",
576
- signal: AbortSignal.timeout(Math.min(this.timeoutMs, 15_000)),
577
- });
578
- if (!response.ok)
579
- throw new EdgeRuntimeError(`A2A Agent Card discovery failed with HTTP ${response.status}.`);
580
- const card = asRecord(await response.json());
581
- if (!card || !cleanString(card.name) || !Array.isArray(card.skills ?? [])) {
582
- throw new EdgeRuntimeError("A2A Agent Card is invalid.");
583
- }
584
- this.card = card;
581
+ this.card = await this.resolver.resolve(this.url, { force, headers: this.headers(true) });
585
582
  this.tool = undefined;
586
- return card;
583
+ return structuredClone(this.card);
587
584
  }
588
585
  async run(input, options = {}) {
589
586
  const card = await this.discover();
590
- const published = new Set((Array.isArray(card.skills) ? card.skills : [])
591
- .map(asRecord)
592
- .map((value) => cleanString(value?.id))
593
- .filter(Boolean));
594
- if (options.skill && published.size && !published.has(options.skill)) {
595
- throw new EdgeRuntimeError(`A2A peer does not publish skill '${options.skill}'.`);
596
- }
597
- if (options.skill && this.policy.allowedSkills.length && !this.policy.allowedSkills.includes(options.skill)) {
598
- throw new EdgeRuntimeError(`A2A skill '${options.skill}' is not allowed by local policy.`);
599
- }
600
- const message = {
601
- messageId: crypto.randomUUID(),
602
- role: "ROLE_USER",
603
- parts: typeof input === "string"
604
- ? [{ text: input, mediaType: "text/plain" }]
605
- : [{ data: redactA2AFields(input, new Set(this.policy.deniedFields)), mediaType: "application/json" }],
606
- metadata: {
607
- requested_skill: options.skill,
608
- marona: {
609
- user_id: options.context?.userId,
610
- session_id: options.context?.sessionId ?? "default",
611
- developer_id: options.context?.developerId,
612
- permissions: this.permissions,
613
- },
614
- },
615
- };
616
- if (options.taskId)
617
- message.taskId = options.taskId;
618
- if (options.contextId)
619
- message.contextId = options.contextId;
620
- const endpoint = a2aInterface(card, this.url);
621
- const url = endpoint.binding === "JSONRPC"
622
- ? endpoint.url
623
- : `${endpoint.url.replace(/\/+$/, "")}/message:send`;
624
- const request = {
625
- message,
626
- configuration: { returnImmediately: false },
627
- metadata: { peer: this.name },
628
- };
629
- const body = endpoint.binding === "JSONRPC"
630
- ? { jsonrpc: "2.0", id: crypto.randomUUID(), method: "SendMessage", params: request }
631
- : request;
632
- const response = await fetch(url, {
633
- method: "POST",
634
- headers: this.headers(),
635
- body: JSON.stringify(body),
636
- redirect: "error",
637
- signal: AbortSignal.timeout(this.timeoutMs),
638
- });
639
- if (!response.ok)
640
- throw new EdgeRuntimeError(`A2A request failed with HTTP ${response.status}.`);
641
- const payload = asRecord(await response.json()) ?? {};
642
- const result = asRecord(payload.result) ?? payload;
643
- const raw = asRecord(result.task) ?? result;
644
- const task = normalizeA2ATask(raw);
587
+ const task = parseA2ATask(await this.request(card, "SendMessage", this.message(card, input, options), "message:send"));
588
+ await this.taskStore.save(this.name, this.session(options.context), task);
645
589
  if (["TASK_STATE_FAILED", "TASK_STATE_REJECTED", "TASK_STATE_CANCELED"].includes(task.state)) {
646
- throw new EdgeRuntimeError(`A2A peer '${this.name}' returned ${task.state}.`);
590
+ throw new A2ATaskError(`A2A peer '${this.name}' returned ${task.state}.`);
647
591
  }
648
592
  return task;
649
593
  }
594
+ async continueTask(input, options = {}) {
595
+ const previous = await this.taskStore.latest(this.name, this.session(options.context));
596
+ const taskId = options.taskId ?? previous?.id;
597
+ if (!taskId)
598
+ throw new A2ATaskError("No previous A2A task exists for this session");
599
+ return this.run(input, { ...options, taskId, contextId: options.contextId ?? previous?.contextId });
600
+ }
601
+ async getTask(taskId) {
602
+ if (!taskId)
603
+ throw new A2AProtocolError("A2A task ID is required");
604
+ return parseA2ATask(await this.request(await this.discover(), "GetTask", { id: taskId, historyLength: 20 }, `tasks/${encodeURIComponent(taskId)}`, true));
605
+ }
606
+ async cancel(taskId) {
607
+ if (!taskId)
608
+ throw new A2AProtocolError("A2A task ID is required");
609
+ return parseA2ATask(await this.request(await this.discover(), "CancelTask", { id: taskId }, `tasks/${encodeURIComponent(taskId)}:cancel`));
610
+ }
611
+ async *stream(input, options = {}) {
612
+ const card = await this.discover();
613
+ const endpoint = a2aInterface(card, this.url);
614
+ await validateA2AHost(endpoint.url, this.policy);
615
+ const params = this.message(card, input, options);
616
+ const body = this.encoded(endpoint.binding === "JSONRPC"
617
+ ? { jsonrpc: "2.0", id: crypto.randomUUID(), method: "SendStreamingMessage", params } : params);
618
+ const response = await this.fetchImpl(endpoint.binding === "JSONRPC" ? endpoint.url : `${endpoint.url.replace(/\/+$/, "")}/message:stream`, {
619
+ method: "POST", headers: { ...this.headers(), Accept: "text/event-stream" }, body,
620
+ redirect: "error", signal: AbortSignal.timeout(this.timeoutMs),
621
+ });
622
+ if (!response.ok) {
623
+ await response.body?.cancel();
624
+ throw new A2AProtocolError(`A2A stream returned HTTP ${response.status}`);
625
+ }
626
+ let task;
627
+ for await (const value of readA2AStream(response, this.policy.maxResponseBytes)) {
628
+ if (value.task)
629
+ task = parseA2ATask(value);
630
+ if (task && value.artifactUpdate) {
631
+ const update = asRecord(value.artifactUpdate);
632
+ const artifacts = (task.raw.artifacts ?? []);
633
+ if (update?.artifact)
634
+ task.raw.artifacts = [...artifacts, update.artifact];
635
+ task = parseA2ATask(task.raw);
636
+ }
637
+ if (task && value.statusUpdate) {
638
+ task.raw.status = asRecord(value.statusUpdate)?.status;
639
+ task = parseA2ATask(task.raw);
640
+ }
641
+ if (task)
642
+ await this.taskStore.save(this.name, this.session(options.context), task);
643
+ const event = parseA2AEvent(this.name, value);
644
+ if (event)
645
+ yield event;
646
+ }
647
+ }
648
+ session(context) { return JSON.stringify([context?.developerId ?? null, context?.userId ?? null, context?.sessionId ?? "default"]); }
649
+ message(card, input, options) {
650
+ const missing = this.permissions.filter(permission => !options.context?.permissions.has(permission));
651
+ if (missing.length)
652
+ throw new A2ASecurityError("A2A execution requires additional permissions");
653
+ const published = new Set((Array.isArray(card.skills) ? card.skills : []).map(value => asRecord(value)?.id));
654
+ if (options.skill && published.size && !published.has(options.skill))
655
+ throw new A2AProtocolError("A2A peer does not publish requested skill");
656
+ if (options.skill && this.policy.allowedSkills.length && !this.policy.allowedSkills.includes(options.skill))
657
+ throw new A2ASecurityError("A2A skill denied by local policy");
658
+ return { message: {
659
+ messageId: crypto.randomUUID(), role: "ROLE_USER",
660
+ parts: a2aParts(redactA2AFields(input, new Set(this.policy.deniedFields))),
661
+ ...(options.taskId ? { taskId: options.taskId } : {}), ...(options.contextId ? { contextId: options.contextId } : {}),
662
+ metadata: { requested_skill: options.skill, marona: {
663
+ user_id: options.context?.userId, session_id: options.context?.sessionId ?? "default",
664
+ developer_id: options.context?.developerId, permissions: this.permissions,
665
+ } },
666
+ }, configuration: { returnImmediately: false }, metadata: { peer: this.name } };
667
+ }
668
+ encoded(body) {
669
+ const encoded = JSON.stringify(body);
670
+ if (new TextEncoder().encode(encoded).length > this.policy.maxRequestBytes)
671
+ throw new A2ASecurityError("A2A request exceeds byte limit");
672
+ return encoded;
673
+ }
674
+ async request(card, operation, params, path, get = false) {
675
+ const endpoint = a2aInterface(card, this.url);
676
+ await validateA2AHost(endpoint.url, this.policy);
677
+ const rpc = endpoint.binding === "JSONRPC";
678
+ const body = this.encoded(rpc ? { jsonrpc: "2.0", id: crypto.randomUUID(), method: operation, params } : params);
679
+ const url = rpc ? endpoint.url : `${endpoint.url.replace(/\/+$/, "")}/${path}`;
680
+ for (let attempt = 0;; attempt++) {
681
+ let response;
682
+ try {
683
+ response = await this.fetchImpl(url, { method: !rpc && get ? "GET" : "POST", headers: this.headers(), body: !rpc && get ? undefined : body, redirect: "error", signal: AbortSignal.timeout(this.timeoutMs) });
684
+ }
685
+ catch (error) {
686
+ if (attempt >= this.maxRetries)
687
+ throw new A2AProtocolError("A2A transport request failed", { cause: error });
688
+ await new Promise(resolve => setTimeout(resolve, Math.min(250 * 2 ** attempt, 2000)));
689
+ continue;
690
+ }
691
+ if (!response.ok) {
692
+ await response.body?.cancel();
693
+ throw new A2AProtocolError(`A2A peer returned HTTP ${response.status}`);
694
+ }
695
+ return unwrapA2A(await readA2AResponse(response, this.policy.maxResponseBytes));
696
+ }
697
+ }
650
698
  functionTool() {
651
699
  if (this.tool)
652
700
  return this.tool;
@@ -696,25 +744,35 @@ export class A2APeer {
696
744
  return this.tool;
697
745
  }
698
746
  headers(publicCard = false) {
699
- const headers = {
700
- "A2A-Version": "1.0",
701
- "Content-Type": "application/json",
702
- };
703
- if (publicCard || !this.authentication || this.authentication.type === "none")
747
+ const headers = { "A2A-Version": "1.0", "Content-Type": "application/a2a+json" };
748
+ if ((publicCard && !this.authentication?.sendWithCard) || !this.authentication || this.authentication.type === "none")
704
749
  return headers;
705
750
  if (this.authentication.type === "bearer") {
706
- if (!this.authentication.token)
707
- throw new EdgeRuntimeError(`A2A peer '${this.name}' requires a bearer token.`);
751
+ if (!this.authentication.token?.trim())
752
+ throw new A2ASecurityError("A2A bearer token is required");
708
753
  headers.Authorization = `Bearer ${this.authentication.token}`;
709
754
  }
710
- else {
711
- if (!this.authentication.key)
712
- throw new EdgeRuntimeError(`A2A peer '${this.name}' requires an API key.`);
755
+ else if (this.authentication.type === "api_key") {
756
+ if (!this.authentication.key?.trim())
757
+ throw new A2ASecurityError("A2A API key is required");
713
758
  headers[this.authentication.header ?? "X-API-Key"] = this.authentication.key;
714
759
  }
760
+ else
761
+ throw new A2ASecurityError("Unsupported A2A authentication type");
715
762
  return headers;
716
763
  }
717
764
  }
765
+ export class A2AClient {
766
+ peer;
767
+ constructor(peer) {
768
+ this.peer = peer;
769
+ }
770
+ agentCard(force = false) { return this.peer.discover(force); }
771
+ send(input, options = {}) { return this.peer.run(input, options); }
772
+ stream(input, options = {}) { return this.peer.stream(input, options); }
773
+ getTask(taskId) { return this.peer.getTask(taskId); }
774
+ cancel(taskId) { return this.peer.cancel(taskId); }
775
+ }
718
776
  export class MaronaAgentLoopError extends EdgeRuntimeError {
719
777
  }
720
778
  export class MaronaInputValidationError extends EdgeRuntimeError {
@@ -764,11 +822,20 @@ export class FunctionTool {
764
822
  if (this.approval === "always" && !context.approvedTools.has(this.name)) {
765
823
  throw new EdgeRuntimeError(`Function tool '${this.name}' requires application approval.`);
766
824
  }
767
- const timeout = new Promise((_, reject) => setTimeout(() => reject(new EdgeRuntimeError(`Function tool '${this.name}' timed out after ${this.timeoutMs} ms.`)), this.timeoutMs));
768
- const result = await Promise.race([Promise.resolve(this.executor(argumentsValue, context)), timeout]);
769
- if (this.outputSchema)
770
- validateJsonSchema(result, this.outputSchema, "output");
771
- return JSON.parse(JSON.stringify(result));
825
+ let timer;
826
+ try {
827
+ const timeout = new Promise((_, reject) => {
828
+ timer = setTimeout(() => reject(new EdgeRuntimeError(`Function tool '${this.name}' timed out after ${this.timeoutMs} ms.`)), this.timeoutMs);
829
+ });
830
+ const result = await Promise.race([Promise.resolve().then(() => this.executor(argumentsValue, context)), timeout]);
831
+ if (this.outputSchema)
832
+ validateJsonSchema(result, this.outputSchema, "output");
833
+ return JSON.parse(JSON.stringify(result));
834
+ }
835
+ finally {
836
+ if (timer !== undefined)
837
+ clearTimeout(timer);
838
+ }
772
839
  }
773
840
  }
774
841
  export function functionTool(options) {
@@ -802,18 +869,20 @@ export class Handoff {
802
869
  history;
803
870
  voiceTransition;
804
871
  inputSchema;
805
- constructor(targetAgent, name, description, history = "full", voiceTransition = "preserve", inputSchema) {
872
+ inputFilter;
873
+ constructor(targetAgent, name, description, history = "full", voiceTransition = "preserve", inputSchema, inputFilter) {
806
874
  this.targetAgent = targetAgent;
807
875
  this.name = name;
808
876
  this.description = description;
809
877
  this.history = history;
810
878
  this.voiceTransition = voiceTransition;
811
879
  this.inputSchema = inputSchema;
880
+ this.inputFilter = inputFilter;
812
881
  validateAgentToolName(name);
813
882
  }
814
883
  }
815
884
  export function handoff(targetAgent, options = {}) {
816
- return new Handoff(targetAgent, options.name ?? `transfer_to_${agentSlug(targetAgent.name)}`, options.description ?? targetAgent.description ?? `Transfer the conversation to ${targetAgent.name}.`, options.history ?? "full", options.voiceTransition ?? "preserve", options.inputSchema);
885
+ return new Handoff(targetAgent, options.name ?? `transfer_to_${agentSlug(targetAgent.name)}`, options.description ?? targetAgent.description ?? `Transfer the conversation to ${targetAgent.name}.`, options.history ?? "full", options.voiceTransition ?? "preserve", options.inputSchema, options.inputFilter);
817
886
  }
818
887
  let activeRuntime;
819
888
  const supportedModalities = new Set(["text", "image", "audio", "video", "file"]);
@@ -824,6 +893,7 @@ export class Agent {
824
893
  instructions;
825
894
  inputSchema;
826
895
  outputSchema;
896
+ outputSchemaStrict;
827
897
  tools;
828
898
  handoffs;
829
899
  peers;
@@ -849,6 +919,7 @@ export class Agent {
849
919
  this.inputSchema = options.inputSchema;
850
920
  this.outputSchema = options.outputSchema;
851
921
  this.tools = options.tools;
922
+ this.outputSchemaStrict = options.outputSchemaStrict ?? false;
852
923
  this.handoffs = options.handoffs ?? [];
853
924
  this.peers = options.peers ?? [];
854
925
  this.inputGuardrails = options.inputGuardrails ?? [];
@@ -909,6 +980,7 @@ export class Runner {
909
980
  if (unsupportedInputs.length) {
910
981
  throw new EdgeRuntimeError(`Agent input does not allow: ${unsupportedInputs.join(", ")}`);
911
982
  }
983
+ const a2aEvents = [];
912
984
  try {
913
985
  const response = await new ResponsesClient(runtime).create({
914
986
  model: agent.model,
@@ -916,7 +988,8 @@ export class Runner {
916
988
  userId,
917
989
  conversationId,
918
990
  developerInstructions: resolveAgentInstructions(agent, context) || undefined,
919
- tools: agentRuntimeTools(agent),
991
+ tools: agentRuntimeTools(agent, a2aEvents),
992
+ toolChoice: agent.toolChoice,
920
993
  routing: agent.routing,
921
994
  output,
922
995
  metadata: {
@@ -952,6 +1025,7 @@ export class Runner {
952
1025
  usage: asRecord(response.rawJson.usage) ?? {},
953
1026
  routing: response.routing,
954
1027
  traceId: cleanString(metadata.trace_id),
1028
+ a2aEvents,
955
1029
  };
956
1030
  for (const run of result.agentRuns.slice(1)) {
957
1031
  if (run.relationship === "delegation")
@@ -994,6 +1068,8 @@ export class Runner {
994
1068
  yield { type: "run.started" };
995
1069
  yield { type: "agent.started", data: { agent_name: agent.name } };
996
1070
  let response;
1071
+ const a2aEvents = [];
1072
+ let deliveredA2A = 0;
997
1073
  try {
998
1074
  for await (const event of new ResponsesClient(runtime).stream({
999
1075
  model: agent.model,
@@ -1001,7 +1077,7 @@ export class Runner {
1001
1077
  userId,
1002
1078
  conversationId,
1003
1079
  developerInstructions: resolveAgentInstructions(agent, context) || undefined,
1004
- tools: agentRuntimeTools(agent),
1080
+ tools: agentRuntimeTools(agent, a2aEvents),
1005
1081
  routing: agent.routing,
1006
1082
  output,
1007
1083
  toolChoice: agent.toolChoice,
@@ -1022,6 +1098,10 @@ export class Runner {
1022
1098
  },
1023
1099
  },
1024
1100
  })) {
1101
+ while (deliveredA2A < a2aEvents.length) {
1102
+ const peerEvent = a2aEvents[deliveredA2A++];
1103
+ yield { type: peerEvent.type, output: peerEvent.output, data: { peer_name: peerEvent.peerName, task_id: peerEvent.taskId, state: peerEvent.state, ...peerEvent.data } };
1104
+ }
1025
1105
  if (event.type === "run.started")
1026
1106
  continue;
1027
1107
  if (event.type === "run.failed") {
@@ -1062,6 +1142,7 @@ export class Runner {
1062
1142
  usage: asRecord(response.rawJson.usage) ?? {},
1063
1143
  routing: response.routing,
1064
1144
  traceId: cleanString(metadata.trace_id),
1145
+ a2aEvents,
1065
1146
  };
1066
1147
  for (const run of result.agentRuns.slice(1)) {
1067
1148
  if (run.relationship === "delegation")
@@ -1091,6 +1172,7 @@ export class RealtimeSession {
1091
1172
  initialTools;
1092
1173
  continueAfterSessionUpdate;
1093
1174
  closed = false;
1175
+ eventChain = Promise.resolve();
1094
1176
  constructor(descriptor, socket, agent, options) {
1095
1177
  this.descriptor = descriptor;
1096
1178
  this.socket = socket;
@@ -1104,7 +1186,13 @@ export class RealtimeSession {
1104
1186
  ? descriptor.capabilities.selector_tools.map(asRecord).filter(Boolean)
1105
1187
  : [];
1106
1188
  socket.addEventListener("message", (event) => {
1107
- void this.handleProviderEvent(JSON.parse(String(event.data)));
1189
+ this.eventChain = this.eventChain.then(() => this.handleProviderEvent(JSON.parse(String(event.data)))).catch(async (error) => {
1190
+ try {
1191
+ await this.agent.hooks?.onError?.(agentContext(this.agent, this.userId, this.sessionId), error);
1192
+ }
1193
+ catch { /* Keep the original event error observable. */ }
1194
+ this.enqueue({ type: 'error', data: { message: 'Realtime Agent event failed validation or execution.' } });
1195
+ });
1108
1196
  });
1109
1197
  socket.addEventListener("close", () => this.finish());
1110
1198
  socket.addEventListener("error", () => {
@@ -1121,6 +1209,9 @@ export class RealtimeSession {
1121
1209
  await runGuardrails(this.agent, "input", context, input);
1122
1210
  await this.agent.hooks?.onStart?.(context, input);
1123
1211
  const runtimeInput = this.agent.inputSchema ? JSON.stringify(input) : input;
1212
+ for (const modality of inputModalities(runtimeInput))
1213
+ if (this.agent.modalities && !this.agent.modalities.includes(modality))
1214
+ throw new EdgeRuntimeError('Agent input modality is not allowed.');
1124
1215
  for (const item of realtimeMessageItems(runtimeInput)) {
1125
1216
  this.send({ type: "conversation.item.create", item });
1126
1217
  }
@@ -1128,6 +1219,8 @@ export class RealtimeSession {
1128
1219
  }
1129
1220
  async sendAudio(audio) {
1130
1221
  this.ensureOpen();
1222
+ if (this.agent.modalities && !this.agent.modalities.includes('audio'))
1223
+ throw new EdgeRuntimeError('Agent input does not allow audio.');
1131
1224
  let binary = "";
1132
1225
  for (const value of audio)
1133
1226
  binary += String.fromCharCode(value);
@@ -1162,15 +1255,20 @@ export class RealtimeSession {
1162
1255
  for (const call of calls) {
1163
1256
  let output;
1164
1257
  try {
1258
+ if (this.agent.toolChoice === 'none')
1259
+ throw new EdgeRuntimeError('Agent tools are disabled.');
1260
+ await this.agent.hooks?.onToolCall?.(agentContext(this.agent, this.userId, this.sessionId), { runId: call.callId, agentName: this.agent.name, relationship: 'tool' });
1165
1261
  const selector = asRecord(this.selectorMap[call.name]);
1166
1262
  const delegated = agentToolByName(this.agent, call.name);
1167
1263
  const transfer = handoffByName(this.agent, call.name);
1168
1264
  if (delegated) {
1265
+ validateAgentSchema(delegated.inputSchema, call.arguments, 'input', delegated.targetAgent.name);
1169
1266
  this.enqueue({
1170
1267
  type: "agent.delegation.started",
1171
1268
  data: { source_agent: this.agent.name, target_agent: delegated.targetAgent.name },
1172
1269
  });
1173
1270
  const result = await Runner.run(delegated.targetAgent, delegated.inputSchema ? call.arguments : delegatedInput(call.arguments), { userId: this.userId, sessionId: this.sessionId, timeoutMs: delegated.timeoutMs });
1271
+ validateAgentSchema(delegated.outputSchema, result.output, 'output', delegated.targetAgent.name);
1174
1272
  output = { status: "completed", agent: delegated.targetAgent.name, output: result.output };
1175
1273
  this.enqueue({
1176
1274
  type: "agent.delegation.completed",
@@ -1181,6 +1279,8 @@ export class RealtimeSession {
1181
1279
  else if (transfer) {
1182
1280
  const source = this.agent;
1183
1281
  validateAgentSchema(transfer.inputSchema, call.arguments, "input", transfer.targetAgent.name);
1282
+ const handoffInput = transfer.inputFilter ? transfer.inputFilter(call.arguments) : call.arguments;
1283
+ await source.hooks?.onHandoff?.(agentContext(source, this.userId, this.sessionId), { runId: call.callId, agentName: transfer.targetAgent.name, relationship: 'handoff' });
1184
1284
  this.agent = transfer.targetAgent;
1185
1285
  this.send({
1186
1286
  type: "session.update",
@@ -1189,10 +1289,11 @@ export class RealtimeSession {
1189
1289
  instructions: resolveAgentInstructions(this.agent, agentContext(this.agent, this.userId, this.sessionId)),
1190
1290
  tools: realtimeAgentToolDefinitions(this.agent),
1191
1291
  tool_choice: agentHasTools(this.agent) ? this.agent.toolChoice : "none",
1292
+ ...(transfer.voiceTransition === 'target' && this.agent.voice?.output_voice ? { audio: { output: { voice: this.agent.voice.output_voice } } } : {}),
1192
1293
  },
1193
1294
  });
1194
1295
  agentUpdated = true;
1195
- output = { status: "completed", active_agent: this.agent.name, handoff_input: call.arguments };
1296
+ output = { status: "completed", active_agent: this.agent.name, handoff_input: handoffInput };
1196
1297
  this.enqueue({
1197
1298
  type: "agent.handoff.completed",
1198
1299
  data: { source_agent: source.name, target_agent: this.agent.name },
@@ -1200,6 +1301,9 @@ export class RealtimeSession {
1200
1301
  }
1201
1302
  else {
1202
1303
  const localTool = functionToolByName(this.agent, call.name);
1304
+ const peer = agentPeers(this.agent).find(value => value.toolName === call.name);
1305
+ if (peer)
1306
+ this.enqueue({ type: 'a2a.task.started', data: { peer_name: peer.name } });
1203
1307
  if (!localTool && !selector)
1204
1308
  usedHubTool = true;
1205
1309
  output = localTool
@@ -1209,6 +1313,10 @@ export class RealtimeSession {
1209
1313
  result: await localTool.invoke(call.arguments, toolContext(this.agent, this.userId, this.sessionId)),
1210
1314
  }
1211
1315
  : await executeRealtimeGateway(this.agent, call.name, call.arguments, { userId: this.userId, sessionId: this.sessionId }, selector);
1316
+ if (peer) {
1317
+ const task = output.result;
1318
+ this.enqueue({ type: task.inputRequired ? 'a2a.task.input_required' : 'a2a.task.completed', output: task.output, data: { peer_name: peer.name, task_id: task.id, state: task.state, task: task.raw } });
1319
+ }
1212
1320
  const discovered = Array.isArray(output._marona_tools)
1213
1321
  ? output._marona_tools.map(asRecord).filter(Boolean)
1214
1322
  : [];
@@ -1248,6 +1356,7 @@ export class RealtimeSession {
1248
1356
  const context = agentContext(this.agent, this.userId, this.sessionId);
1249
1357
  const output = parseTypedOutput(this.agent, openAIRealtimeOutput(event));
1250
1358
  await runGuardrails(this.agent, "output", context, output);
1359
+ await this.agent.hooks?.onComplete?.(context, output);
1251
1360
  this.enqueue({ type: "response.completed", output, data: {} });
1252
1361
  return;
1253
1362
  }
@@ -1631,35 +1740,12 @@ function toolContext(agent, userId, sessionId) {
1631
1740
  };
1632
1741
  }
1633
1742
  function validateJsonSchema(value, schema, path) {
1634
- const type = typeof schema.type === "string" ? schema.type : undefined;
1635
- const valid = type === undefined
1636
- || (type === "object" && value !== null && typeof value === "object" && !Array.isArray(value))
1637
- || (type === "array" && Array.isArray(value))
1638
- || (type === "string" && typeof value === "string")
1639
- || (type === "integer" && typeof value === "number" && Number.isInteger(value))
1640
- || (type === "number" && typeof value === "number")
1641
- || (type === "boolean" && typeof value === "boolean")
1642
- || (type === "null" && value === null);
1643
- if (!valid)
1644
- throw new EdgeRuntimeError(`${path} must be ${type}.`);
1645
- const record = asRecord(value);
1646
- if (type === "object" && record) {
1647
- const required = Array.isArray(schema.required) ? schema.required.map(String) : [];
1648
- const missing = required.filter((key) => !(key in record));
1649
- if (missing.length)
1650
- throw new EdgeRuntimeError(`${path} is missing required fields: ${missing.join(", ")}`);
1651
- const properties = asRecord(schema.properties) ?? {};
1652
- if (schema.additionalProperties === false) {
1653
- const extra = Object.keys(record).filter((key) => !(key in properties));
1654
- if (extra.length)
1655
- throw new EdgeRuntimeError(`${path} has unknown fields: ${extra.join(", ")}`);
1656
- }
1657
- for (const [key, child] of Object.entries(properties)) {
1658
- const childSchema = asRecord(child);
1659
- if (key in record && childSchema)
1660
- validateJsonSchema(record[key], childSchema, `${path}.${key}`);
1661
- }
1743
+ try {
1744
+ if (matchesSchema(schema, value))
1745
+ return;
1662
1746
  }
1747
+ catch { /* Do not leak instance data. */ }
1748
+ throw new EdgeRuntimeError(`${path} does not match its JSON Schema.`);
1663
1749
  }
1664
1750
  function validateAgentToolName(value) {
1665
1751
  if (!/^[A-Za-z0-9_-]{1,64}$/.test(value)) {
@@ -1720,6 +1806,8 @@ function normalizeA2ATask(raw) {
1720
1806
  };
1721
1807
  }
1722
1808
  function redactA2AFields(value, denied) {
1809
+ if (value instanceof Uint8Array)
1810
+ return value.slice();
1723
1811
  if (Array.isArray(value))
1724
1812
  return value.map((item) => redactA2AFields(item, denied));
1725
1813
  const record = asRecord(value);
@@ -1825,7 +1913,7 @@ function agentConnection(agent) {
1825
1913
  visit(agent);
1826
1914
  return found;
1827
1915
  }
1828
- function agentRuntimeTools(agent) {
1916
+ function agentRuntimeTools(agent, events) {
1829
1917
  const values = [];
1830
1918
  const connection = agentConnection(agent);
1831
1919
  if (connection)
@@ -1841,8 +1929,19 @@ function agentRuntimeTools(agent) {
1841
1929
  else if (value instanceof AgentTool)
1842
1930
  visit(value.targetAgent);
1843
1931
  }
1844
- for (const peer of agentPeers(current))
1845
- values.push(peer.functionTool());
1932
+ for (const peer of agentPeers(current)) {
1933
+ const tool = peer.functionTool();
1934
+ values.push(events ? functionTool({
1935
+ name: tool.name, description: tool.description, inputSchema: tool.inputSchema,
1936
+ timeoutMs: tool.timeoutMs, permissions: tool.permissions,
1937
+ execute: async (args, context) => {
1938
+ events.push({ type: 'a2a.task.started', peerName: peer.name, data: {} });
1939
+ const task = await tool.invoke(args, context);
1940
+ events.push({ type: task.inputRequired ? 'a2a.task.input_required' : 'a2a.task.completed', peerName: peer.name, taskId: task.id, state: task.state, output: task.output, data: { task: task.raw } });
1941
+ return task;
1942
+ },
1943
+ }) : tool);
1944
+ }
1846
1945
  for (const value of agentHandoffs(current))
1847
1946
  visit(value.targetAgent);
1848
1947
  };
@@ -1974,6 +2073,7 @@ function agentGraph(agent, context, options = {}) {
1974
2073
  max_turns: current.maxTurns ?? 20,
1975
2074
  input_schema: current.inputSchema,
1976
2075
  output_schema: current.outputSchema,
2076
+ output_schema_strict: current.outputSchemaStrict,
1977
2077
  hub_tools: agentTools(current).some((value) => value instanceof MCPConnection),
1978
2078
  function_tools: [...functionTools, ...peerTools],
1979
2079
  peers: agentPeers(current).map((peer) => ({
@@ -2050,34 +2150,12 @@ function validateAgentSchema(schema, value, stage, agentName) {
2050
2150
  const ErrorType = stage === "input" ? MaronaInputValidationError : MaronaOutputValidationError;
2051
2151
  throw new ErrorType(`${stage} validation failed for Agent '${agentName}': ${message}`);
2052
2152
  };
2053
- const visit = (current, candidate, path) => {
2054
- const type = cleanString(current.type);
2055
- if (type === "object") {
2056
- const record = asRecord(candidate);
2057
- if (!record)
2058
- return fail(`${path} must be an object.`);
2059
- for (const key of (Array.isArray(current.required) ? current.required : [])) {
2060
- if (!(String(key) in record))
2061
- fail(`${path}.${String(key)} is required.`);
2062
- }
2063
- const properties = asRecord(current.properties) ?? {};
2064
- for (const [key, child] of Object.entries(properties)) {
2065
- if (key in record && isPlainObject(child))
2066
- visit(child, record[key], `${path}.${key}`);
2067
- }
2068
- }
2069
- else if (type === "array" && !Array.isArray(candidate))
2070
- fail(`${path} must be an array.`);
2071
- else if (type === "string" && typeof candidate !== "string")
2072
- fail(`${path} must be a string.`);
2073
- else if (type === "number" && typeof candidate !== "number")
2074
- fail(`${path} must be a number.`);
2075
- else if (type === "integer" && (!Number.isInteger(candidate)))
2076
- fail(`${path} must be an integer.`);
2077
- else if (type === "boolean" && typeof candidate !== "boolean")
2078
- fail(`${path} must be a boolean.`);
2079
- };
2080
- visit(schema, value, "$");
2153
+ try {
2154
+ if (matchesSchema(schema, value))
2155
+ return;
2156
+ }
2157
+ catch { /* Safe contract error below. */ }
2158
+ fail("value does not match its JSON Schema.");
2081
2159
  }
2082
2160
  function inputModalities(input) {
2083
2161
  if (typeof input === "string")
@@ -2114,7 +2192,7 @@ function normalizeAgentOutputRequest(agent, output) {
2114
2192
  ...(output ?? {}),
2115
2193
  modalities: [...new Set(modalities)],
2116
2194
  ...(agent.outputSchema ? {
2117
- format: { type: "json_schema", name: `${agentSlug(agent.name)}_output`, schema: agent.outputSchema },
2195
+ format: { type: "json_schema", name: `${agentSlug(agent.name)}_output`, schema: agent.outputSchema, strict: agent.outputSchemaStrict },
2118
2196
  } : {}),
2119
2197
  };
2120
2198
  }
@@ -2642,29 +2720,23 @@ function combineText(parts) {
2642
2720
  return cleaned.length ? cleaned.join("\n\n") : undefined;
2643
2721
  }
2644
2722
  function attachmentFromImageBlock(block, index) {
2645
- const value = cleanString(block.image_url ?? block.url ?? block.file_data);
2646
- if (!value)
2647
- return undefined;
2648
- const data = dataUriParts(value);
2649
- const url = data.dataBase64 ? undefined : value;
2723
+ const data = attachmentSource(block, "image");
2724
+ const url = data.url;
2650
2725
  const filename = cleanString(block.filename) ?? filenameFromUrl(url) ?? `image-${index}`;
2651
2726
  return new RuntimeAttachment({
2652
2727
  filename,
2653
- mimeType: data.mimeType ?? guessInputMimeType(filename, "image/*"),
2728
+ mimeType: data.mimeType ?? cleanString(block.mime_type) ?? guessInputMimeType(filename, "image/*"),
2654
2729
  kind: "image",
2655
2730
  dataBase64: data.dataBase64,
2656
2731
  url,
2657
- metadata: inputBlockMetadata(block),
2732
+ metadata: data.metadata,
2658
2733
  });
2659
2734
  }
2660
2735
  function attachmentFromFileBlock(block, index) {
2661
- const value = cleanString(block.file_data ?? block.file_url ?? block.url);
2662
2736
  const text = cleanString(block.text);
2663
- if (!value && !text)
2664
- return undefined;
2665
2737
  const filename = cleanString(block.filename) ?? `file-${index}`;
2666
- const data = dataUriParts(value ?? "");
2667
- const url = data.dataBase64 ? undefined : value;
2738
+ const data = attachmentSource(block, "file", true);
2739
+ const url = data.url;
2668
2740
  const mimeType = data.mimeType ?? cleanString(block.mime_type) ?? guessInputMimeType(filename);
2669
2741
  return new RuntimeAttachment({
2670
2742
  filename,
@@ -2673,35 +2745,20 @@ function attachmentFromFileBlock(block, index) {
2673
2745
  dataBase64: data.dataBase64,
2674
2746
  url,
2675
2747
  text,
2676
- metadata: inputBlockMetadata(block),
2748
+ metadata: data.metadata,
2677
2749
  });
2678
2750
  }
2679
2751
  function attachmentFromMediaBlock(block, index, kind) {
2680
- const candidates = [
2681
- [`${kind}_url`, cleanString(block[`${kind}_url`])],
2682
- [`${kind}_data`, cleanString(block[`${kind}_data`])],
2683
- ["file_id", cleanString(block.file_id)],
2684
- ["path", cleanString(block.path)],
2685
- ];
2686
- const supplied = candidates.filter((entry) => Boolean(entry[1]));
2687
- if (supplied.length !== 1) {
2688
- throw new EdgeRuntimeError(`input_${kind} requires exactly one source: ${kind}_url, ${kind}_data, file_id, path`);
2689
- }
2690
- const [source, value] = supplied[0];
2691
- const data = dataUriParts(value);
2692
- const url = source.endsWith("_url") ? value : undefined;
2752
+ const data = attachmentSource(block, kind);
2753
+ const url = data.url;
2693
2754
  const filename = cleanString(block.filename) ?? filenameFromUrl(url) ?? `${kind}-${index}`;
2694
2755
  return new RuntimeAttachment({
2695
2756
  filename,
2696
2757
  mimeType: data.mimeType ?? cleanString(block.mime_type) ?? guessInputMimeType(filename, `${kind}/*`),
2697
2758
  kind,
2698
- dataBase64: source.endsWith("_data") ? data.dataBase64 ?? value : undefined,
2759
+ dataBase64: data.dataBase64,
2699
2760
  url,
2700
- metadata: {
2701
- ...inputBlockMetadata(block),
2702
- ...(source === "file_id" ? { file_id: value } : {}),
2703
- ...(source === "path" ? { path: value } : {}),
2704
- },
2761
+ metadata: data.metadata,
2705
2762
  });
2706
2763
  }
2707
2764
  function inputBlockMetadata(block) {
@@ -2713,13 +2770,71 @@ function dataUriParts(value) {
2713
2770
  return {};
2714
2771
  const comma = value.indexOf(",");
2715
2772
  if (comma < 0)
2716
- return {};
2773
+ throw new EdgeRuntimeError("Malformed attachment data URL");
2717
2774
  const header = value.slice(0, comma);
2718
2775
  const payload = value.slice(comma + 1);
2719
2776
  const mimeType = header.slice(5).split(";")[0] || undefined;
2777
+ const bytes = percentBytes(payload);
2720
2778
  if (header.includes(";base64"))
2721
- return { mimeType, dataBase64: payload };
2722
- return { mimeType, dataBase64: utf8Base64(payload) };
2779
+ return { mimeType, dataBase64: validatedBase64(new TextDecoder().decode(bytes)) };
2780
+ return { mimeType, dataBase64: base64Encode(bytes) };
2781
+ }
2782
+ function validatedBase64(value) {
2783
+ try {
2784
+ if (!value || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value) || btoa(atob(value)) !== value)
2785
+ throw new Error();
2786
+ return value;
2787
+ }
2788
+ catch {
2789
+ throw new EdgeRuntimeError("Attachment data must contain valid standard Base64");
2790
+ }
2791
+ }
2792
+ function percentBytes(value) {
2793
+ const bytes = [];
2794
+ for (let index = 0; index < value.length;) {
2795
+ if (value[index] === "%") {
2796
+ const hex = value.slice(index + 1, index + 3);
2797
+ if (!/^[0-9a-f]{2}$/i.test(hex))
2798
+ throw new EdgeRuntimeError("Malformed attachment data URL");
2799
+ bytes.push(Number.parseInt(hex, 16));
2800
+ index += 3;
2801
+ }
2802
+ else {
2803
+ let next = value.indexOf("%", index);
2804
+ if (next < 0)
2805
+ next = value.length;
2806
+ for (const byte of new TextEncoder().encode(value.slice(index, next)))
2807
+ bytes.push(byte);
2808
+ index = next;
2809
+ }
2810
+ }
2811
+ return new Uint8Array(bytes);
2812
+ }
2813
+ function attachmentSource(block, kind, allowText = false) {
2814
+ const keys = [`${kind}_data`, `${kind}_url`, "url", "file_id", "path", ...(kind === "image" ? ["file_data"] : [])];
2815
+ const supplied = keys.filter(key => cleanString(block[key]));
2816
+ const metadata = inputBlockMetadata(block);
2817
+ if (!supplied.length && allowText && cleanString(block.text))
2818
+ return { metadata };
2819
+ if (supplied.length !== 1)
2820
+ throw new EdgeRuntimeError(`input_${kind} requires exactly one document source`);
2821
+ const key = supplied[0];
2822
+ const value = cleanString(block[key]);
2823
+ if (["file_id", "path"].includes(key))
2824
+ return { metadata: { ...metadata, [key]: value } };
2825
+ if (value.startsWith("data:"))
2826
+ return { ...dataUriParts(value), metadata };
2827
+ if (key.endsWith("_data"))
2828
+ return { dataBase64: validatedBase64(value), metadata };
2829
+ try {
2830
+ const url = new URL(value);
2831
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password)
2832
+ throw new Error();
2833
+ }
2834
+ catch {
2835
+ throw new EdgeRuntimeError("Attachment URL must be credential-free HTTP(S)");
2836
+ }
2837
+ return { url: value, metadata };
2723
2838
  }
2724
2839
  function filenameFromUrl(url) {
2725
2840
  if (!url)
@@ -3575,16 +3690,31 @@ export class Hub {
3575
3690
  return this.hub.importMcpRegistry(input);
3576
3691
  }
3577
3692
  }
3693
+ export class Apps {
3694
+ runtime;
3695
+ constructor(runtime) {
3696
+ this.runtime = runtime;
3697
+ }
3698
+ list(options = {}) {
3699
+ return this.runtime.getApps(options);
3700
+ }
3701
+ connect(slug, options = {}) {
3702
+ return this.runtime.connectService(slug, options);
3703
+ }
3704
+ disconnect(slug) { return this.runtime.disconnectService(slug); }
3705
+ }
3578
3706
  export class Marona {
3579
3707
  hub;
3580
3708
  responses;
3581
3709
  skills;
3710
+ apps;
3582
3711
  runtime;
3583
3712
  constructor(options = {}) {
3584
3713
  this.runtime = new RuntimeEngine(options);
3585
3714
  this.hub = new Hub(this.runtime.hub);
3586
3715
  this.responses = new ResponsesClient(this.runtime);
3587
3716
  this.skills = this.runtime.skills;
3717
+ this.apps = new Apps(this.runtime);
3588
3718
  activeRuntime = this.runtime;
3589
3719
  }
3590
3720
  }
@@ -3670,6 +3800,7 @@ function normalizeRouting(value) {
3670
3800
  target_latency_ms: value.targetLatencyMs ?? value.target_latency_ms,
3671
3801
  timeout_ms: value.timeoutMs ?? value.timeout_ms,
3672
3802
  allowed_models: value.allowedModels ?? value.allowed_models,
3803
+ allowed_providers: value.allowedProviders ?? value.allowed_providers,
3673
3804
  fallback: value.fallback,
3674
3805
  });
3675
3806
  }