marona 1.1.4 → 2.0.1

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.1";
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,30 +744,49 @@ 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 {
721
779
  }
722
780
  export class MaronaOutputValidationError extends EdgeRuntimeError {
781
+ agentName;
782
+ validationErrors;
783
+ constructor(message, agentName, rawOutput, validationErrors = []) {
784
+ super(message);
785
+ this.agentName = agentName;
786
+ // Keep model content out of normal logging and JSON serialization of errors.
787
+ Object.defineProperty(this, "rawOutput", { value: rawOutput, enumerable: false });
788
+ this.validationErrors = Object.freeze([...validationErrors]);
789
+ }
723
790
  }
724
791
  export class MaronaGuardrailError extends EdgeRuntimeError {
725
792
  }
@@ -764,11 +831,20 @@ export class FunctionTool {
764
831
  if (this.approval === "always" && !context.approvedTools.has(this.name)) {
765
832
  throw new EdgeRuntimeError(`Function tool '${this.name}' requires application approval.`);
766
833
  }
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));
834
+ let timer;
835
+ try {
836
+ const timeout = new Promise((_, reject) => {
837
+ timer = setTimeout(() => reject(new EdgeRuntimeError(`Function tool '${this.name}' timed out after ${this.timeoutMs} ms.`)), this.timeoutMs);
838
+ });
839
+ const result = await Promise.race([Promise.resolve().then(() => this.executor(argumentsValue, context)), timeout]);
840
+ if (this.outputSchema)
841
+ validateJsonSchema(result, this.outputSchema, "output");
842
+ return JSON.parse(JSON.stringify(result));
843
+ }
844
+ finally {
845
+ if (timer !== undefined)
846
+ clearTimeout(timer);
847
+ }
772
848
  }
773
849
  }
774
850
  export function functionTool(options) {
@@ -802,18 +878,20 @@ export class Handoff {
802
878
  history;
803
879
  voiceTransition;
804
880
  inputSchema;
805
- constructor(targetAgent, name, description, history = "full", voiceTransition = "preserve", inputSchema) {
881
+ inputFilter;
882
+ constructor(targetAgent, name, description, history = "full", voiceTransition = "preserve", inputSchema, inputFilter) {
806
883
  this.targetAgent = targetAgent;
807
884
  this.name = name;
808
885
  this.description = description;
809
886
  this.history = history;
810
887
  this.voiceTransition = voiceTransition;
811
888
  this.inputSchema = inputSchema;
889
+ this.inputFilter = inputFilter;
812
890
  validateAgentToolName(name);
813
891
  }
814
892
  }
815
893
  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);
894
+ 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
895
  }
818
896
  let activeRuntime;
819
897
  const supportedModalities = new Set(["text", "image", "audio", "video", "file"]);
@@ -824,6 +902,7 @@ export class Agent {
824
902
  instructions;
825
903
  inputSchema;
826
904
  outputSchema;
905
+ outputSchemaStrict;
827
906
  tools;
828
907
  handoffs;
829
908
  peers;
@@ -849,6 +928,7 @@ export class Agent {
849
928
  this.inputSchema = options.inputSchema;
850
929
  this.outputSchema = options.outputSchema;
851
930
  this.tools = options.tools;
931
+ this.outputSchemaStrict = options.outputSchemaStrict ?? false;
852
932
  this.handoffs = options.handoffs ?? [];
853
933
  this.peers = options.peers ?? [];
854
934
  this.inputGuardrails = options.inputGuardrails ?? [];
@@ -909,6 +989,7 @@ export class Runner {
909
989
  if (unsupportedInputs.length) {
910
990
  throw new EdgeRuntimeError(`Agent input does not allow: ${unsupportedInputs.join(", ")}`);
911
991
  }
992
+ const a2aEvents = [];
912
993
  try {
913
994
  const response = await new ResponsesClient(runtime).create({
914
995
  model: agent.model,
@@ -916,7 +997,8 @@ export class Runner {
916
997
  userId,
917
998
  conversationId,
918
999
  developerInstructions: resolveAgentInstructions(agent, context) || undefined,
919
- tools: agentRuntimeTools(agent),
1000
+ tools: agentRuntimeTools(agent, a2aEvents),
1001
+ toolChoice: agent.toolChoice,
920
1002
  routing: agent.routing,
921
1003
  output,
922
1004
  metadata: {
@@ -952,6 +1034,7 @@ export class Runner {
952
1034
  usage: asRecord(response.rawJson.usage) ?? {},
953
1035
  routing: response.routing,
954
1036
  traceId: cleanString(metadata.trace_id),
1037
+ a2aEvents,
955
1038
  };
956
1039
  for (const run of result.agentRuns.slice(1)) {
957
1040
  if (run.relationship === "delegation")
@@ -994,6 +1077,8 @@ export class Runner {
994
1077
  yield { type: "run.started" };
995
1078
  yield { type: "agent.started", data: { agent_name: agent.name } };
996
1079
  let response;
1080
+ const a2aEvents = [];
1081
+ let deliveredA2A = 0;
997
1082
  try {
998
1083
  for await (const event of new ResponsesClient(runtime).stream({
999
1084
  model: agent.model,
@@ -1001,7 +1086,7 @@ export class Runner {
1001
1086
  userId,
1002
1087
  conversationId,
1003
1088
  developerInstructions: resolveAgentInstructions(agent, context) || undefined,
1004
- tools: agentRuntimeTools(agent),
1089
+ tools: agentRuntimeTools(agent, a2aEvents),
1005
1090
  routing: agent.routing,
1006
1091
  output,
1007
1092
  toolChoice: agent.toolChoice,
@@ -1022,6 +1107,10 @@ export class Runner {
1022
1107
  },
1023
1108
  },
1024
1109
  })) {
1110
+ while (deliveredA2A < a2aEvents.length) {
1111
+ const peerEvent = a2aEvents[deliveredA2A++];
1112
+ yield { type: peerEvent.type, output: peerEvent.output, data: { peer_name: peerEvent.peerName, task_id: peerEvent.taskId, state: peerEvent.state, ...peerEvent.data } };
1113
+ }
1025
1114
  if (event.type === "run.started")
1026
1115
  continue;
1027
1116
  if (event.type === "run.failed") {
@@ -1062,6 +1151,7 @@ export class Runner {
1062
1151
  usage: asRecord(response.rawJson.usage) ?? {},
1063
1152
  routing: response.routing,
1064
1153
  traceId: cleanString(metadata.trace_id),
1154
+ a2aEvents,
1065
1155
  };
1066
1156
  for (const run of result.agentRuns.slice(1)) {
1067
1157
  if (run.relationship === "delegation")
@@ -1091,6 +1181,7 @@ export class RealtimeSession {
1091
1181
  initialTools;
1092
1182
  continueAfterSessionUpdate;
1093
1183
  closed = false;
1184
+ eventChain = Promise.resolve();
1094
1185
  constructor(descriptor, socket, agent, options) {
1095
1186
  this.descriptor = descriptor;
1096
1187
  this.socket = socket;
@@ -1104,7 +1195,13 @@ export class RealtimeSession {
1104
1195
  ? descriptor.capabilities.selector_tools.map(asRecord).filter(Boolean)
1105
1196
  : [];
1106
1197
  socket.addEventListener("message", (event) => {
1107
- void this.handleProviderEvent(JSON.parse(String(event.data)));
1198
+ this.eventChain = this.eventChain.then(() => this.handleProviderEvent(JSON.parse(String(event.data)))).catch(async (error) => {
1199
+ try {
1200
+ await this.agent.hooks?.onError?.(agentContext(this.agent, this.userId, this.sessionId), error);
1201
+ }
1202
+ catch { /* Keep the original event error observable. */ }
1203
+ this.enqueue({ type: 'error', data: { message: 'Realtime Agent event failed validation or execution.' } });
1204
+ });
1108
1205
  });
1109
1206
  socket.addEventListener("close", () => this.finish());
1110
1207
  socket.addEventListener("error", () => {
@@ -1121,6 +1218,9 @@ export class RealtimeSession {
1121
1218
  await runGuardrails(this.agent, "input", context, input);
1122
1219
  await this.agent.hooks?.onStart?.(context, input);
1123
1220
  const runtimeInput = this.agent.inputSchema ? JSON.stringify(input) : input;
1221
+ for (const modality of inputModalities(runtimeInput))
1222
+ if (this.agent.modalities && !this.agent.modalities.includes(modality))
1223
+ throw new EdgeRuntimeError('Agent input modality is not allowed.');
1124
1224
  for (const item of realtimeMessageItems(runtimeInput)) {
1125
1225
  this.send({ type: "conversation.item.create", item });
1126
1226
  }
@@ -1128,6 +1228,8 @@ export class RealtimeSession {
1128
1228
  }
1129
1229
  async sendAudio(audio) {
1130
1230
  this.ensureOpen();
1231
+ if (this.agent.modalities && !this.agent.modalities.includes('audio'))
1232
+ throw new EdgeRuntimeError('Agent input does not allow audio.');
1131
1233
  let binary = "";
1132
1234
  for (const value of audio)
1133
1235
  binary += String.fromCharCode(value);
@@ -1162,15 +1264,20 @@ export class RealtimeSession {
1162
1264
  for (const call of calls) {
1163
1265
  let output;
1164
1266
  try {
1267
+ if (this.agent.toolChoice === 'none')
1268
+ throw new EdgeRuntimeError('Agent tools are disabled.');
1269
+ await this.agent.hooks?.onToolCall?.(agentContext(this.agent, this.userId, this.sessionId), { runId: call.callId, agentName: this.agent.name, relationship: 'tool' });
1165
1270
  const selector = asRecord(this.selectorMap[call.name]);
1166
1271
  const delegated = agentToolByName(this.agent, call.name);
1167
1272
  const transfer = handoffByName(this.agent, call.name);
1168
1273
  if (delegated) {
1274
+ validateAgentSchema(delegated.inputSchema, call.arguments, 'input', delegated.targetAgent.name);
1169
1275
  this.enqueue({
1170
1276
  type: "agent.delegation.started",
1171
1277
  data: { source_agent: this.agent.name, target_agent: delegated.targetAgent.name },
1172
1278
  });
1173
1279
  const result = await Runner.run(delegated.targetAgent, delegated.inputSchema ? call.arguments : delegatedInput(call.arguments), { userId: this.userId, sessionId: this.sessionId, timeoutMs: delegated.timeoutMs });
1280
+ validateAgentSchema(delegated.outputSchema, result.output, 'output', delegated.targetAgent.name);
1174
1281
  output = { status: "completed", agent: delegated.targetAgent.name, output: result.output };
1175
1282
  this.enqueue({
1176
1283
  type: "agent.delegation.completed",
@@ -1181,6 +1288,8 @@ export class RealtimeSession {
1181
1288
  else if (transfer) {
1182
1289
  const source = this.agent;
1183
1290
  validateAgentSchema(transfer.inputSchema, call.arguments, "input", transfer.targetAgent.name);
1291
+ const handoffInput = transfer.inputFilter ? transfer.inputFilter(call.arguments) : call.arguments;
1292
+ await source.hooks?.onHandoff?.(agentContext(source, this.userId, this.sessionId), { runId: call.callId, agentName: transfer.targetAgent.name, relationship: 'handoff' });
1184
1293
  this.agent = transfer.targetAgent;
1185
1294
  this.send({
1186
1295
  type: "session.update",
@@ -1189,10 +1298,11 @@ export class RealtimeSession {
1189
1298
  instructions: resolveAgentInstructions(this.agent, agentContext(this.agent, this.userId, this.sessionId)),
1190
1299
  tools: realtimeAgentToolDefinitions(this.agent),
1191
1300
  tool_choice: agentHasTools(this.agent) ? this.agent.toolChoice : "none",
1301
+ ...(transfer.voiceTransition === 'target' && this.agent.voice?.output_voice ? { audio: { output: { voice: this.agent.voice.output_voice } } } : {}),
1192
1302
  },
1193
1303
  });
1194
1304
  agentUpdated = true;
1195
- output = { status: "completed", active_agent: this.agent.name, handoff_input: call.arguments };
1305
+ output = { status: "completed", active_agent: this.agent.name, handoff_input: handoffInput };
1196
1306
  this.enqueue({
1197
1307
  type: "agent.handoff.completed",
1198
1308
  data: { source_agent: source.name, target_agent: this.agent.name },
@@ -1200,6 +1310,9 @@ export class RealtimeSession {
1200
1310
  }
1201
1311
  else {
1202
1312
  const localTool = functionToolByName(this.agent, call.name);
1313
+ const peer = agentPeers(this.agent).find(value => value.toolName === call.name);
1314
+ if (peer)
1315
+ this.enqueue({ type: 'a2a.task.started', data: { peer_name: peer.name } });
1203
1316
  if (!localTool && !selector)
1204
1317
  usedHubTool = true;
1205
1318
  output = localTool
@@ -1209,6 +1322,10 @@ export class RealtimeSession {
1209
1322
  result: await localTool.invoke(call.arguments, toolContext(this.agent, this.userId, this.sessionId)),
1210
1323
  }
1211
1324
  : await executeRealtimeGateway(this.agent, call.name, call.arguments, { userId: this.userId, sessionId: this.sessionId }, selector);
1325
+ if (peer) {
1326
+ const task = output.result;
1327
+ 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 } });
1328
+ }
1212
1329
  const discovered = Array.isArray(output._marona_tools)
1213
1330
  ? output._marona_tools.map(asRecord).filter(Boolean)
1214
1331
  : [];
@@ -1248,6 +1365,7 @@ export class RealtimeSession {
1248
1365
  const context = agentContext(this.agent, this.userId, this.sessionId);
1249
1366
  const output = parseTypedOutput(this.agent, openAIRealtimeOutput(event));
1250
1367
  await runGuardrails(this.agent, "output", context, output);
1368
+ await this.agent.hooks?.onComplete?.(context, output);
1251
1369
  this.enqueue({ type: "response.completed", output, data: {} });
1252
1370
  return;
1253
1371
  }
@@ -1631,35 +1749,12 @@ function toolContext(agent, userId, sessionId) {
1631
1749
  };
1632
1750
  }
1633
1751
  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
- }
1752
+ try {
1753
+ if (matchesSchema(schema, value))
1754
+ return;
1662
1755
  }
1756
+ catch { /* Do not leak instance data. */ }
1757
+ throw new EdgeRuntimeError(`${path} does not match its JSON Schema.`);
1663
1758
  }
1664
1759
  function validateAgentToolName(value) {
1665
1760
  if (!/^[A-Za-z0-9_-]{1,64}$/.test(value)) {
@@ -1720,6 +1815,8 @@ function normalizeA2ATask(raw) {
1720
1815
  };
1721
1816
  }
1722
1817
  function redactA2AFields(value, denied) {
1818
+ if (value instanceof Uint8Array)
1819
+ return value.slice();
1723
1820
  if (Array.isArray(value))
1724
1821
  return value.map((item) => redactA2AFields(item, denied));
1725
1822
  const record = asRecord(value);
@@ -1825,7 +1922,7 @@ function agentConnection(agent) {
1825
1922
  visit(agent);
1826
1923
  return found;
1827
1924
  }
1828
- function agentRuntimeTools(agent) {
1925
+ function agentRuntimeTools(agent, events) {
1829
1926
  const values = [];
1830
1927
  const connection = agentConnection(agent);
1831
1928
  if (connection)
@@ -1841,8 +1938,19 @@ function agentRuntimeTools(agent) {
1841
1938
  else if (value instanceof AgentTool)
1842
1939
  visit(value.targetAgent);
1843
1940
  }
1844
- for (const peer of agentPeers(current))
1845
- values.push(peer.functionTool());
1941
+ for (const peer of agentPeers(current)) {
1942
+ const tool = peer.functionTool();
1943
+ values.push(events ? functionTool({
1944
+ name: tool.name, description: tool.description, inputSchema: tool.inputSchema,
1945
+ timeoutMs: tool.timeoutMs, permissions: tool.permissions,
1946
+ execute: async (args, context) => {
1947
+ events.push({ type: 'a2a.task.started', peerName: peer.name, data: {} });
1948
+ const task = await tool.invoke(args, context);
1949
+ 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 } });
1950
+ return task;
1951
+ },
1952
+ }) : tool);
1953
+ }
1846
1954
  for (const value of agentHandoffs(current))
1847
1955
  visit(value.targetAgent);
1848
1956
  };
@@ -1974,6 +2082,7 @@ function agentGraph(agent, context, options = {}) {
1974
2082
  max_turns: current.maxTurns ?? 20,
1975
2083
  input_schema: current.inputSchema,
1976
2084
  output_schema: current.outputSchema,
2085
+ output_schema_strict: current.outputSchemaStrict,
1977
2086
  hub_tools: agentTools(current).some((value) => value instanceof MCPConnection),
1978
2087
  function_tools: [...functionTools, ...peerTools],
1979
2088
  peers: agentPeers(current).map((peer) => ({
@@ -2040,44 +2149,24 @@ function parseTypedOutput(agent, value) {
2040
2149
  }
2041
2150
  catch { /* validation below reports the contract failure */ }
2042
2151
  }
2043
- validateAgentSchema(agent.outputSchema, parsed, "output", agent.name);
2152
+ validateAgentSchema(agent.outputSchema, parsed, "output", agent.name, value);
2044
2153
  return parsed;
2045
2154
  }
2046
- function validateAgentSchema(schema, value, stage, agentName) {
2155
+ function validateAgentSchema(schema, value, stage, agentName, rawOutput = value) {
2047
2156
  if (!schema)
2048
2157
  return;
2049
2158
  const fail = (message) => {
2050
- const ErrorType = stage === "input" ? MaronaInputValidationError : MaronaOutputValidationError;
2051
- throw new ErrorType(`${stage} validation failed for Agent '${agentName}': ${message}`);
2159
+ const summary = `${stage} validation failed for Agent '${agentName}': ${message}`;
2160
+ if (stage === "input")
2161
+ throw new MaronaInputValidationError(summary);
2162
+ throw new MaronaOutputValidationError(summary, agentName, rawOutput, [message]);
2052
2163
  };
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, "$");
2164
+ try {
2165
+ if (matchesSchema(schema, value))
2166
+ return;
2167
+ }
2168
+ catch { /* Safe contract error below. */ }
2169
+ fail("value does not match its JSON Schema.");
2081
2170
  }
2082
2171
  function inputModalities(input) {
2083
2172
  if (typeof input === "string")
@@ -2114,7 +2203,7 @@ function normalizeAgentOutputRequest(agent, output) {
2114
2203
  ...(output ?? {}),
2115
2204
  modalities: [...new Set(modalities)],
2116
2205
  ...(agent.outputSchema ? {
2117
- format: { type: "json_schema", name: `${agentSlug(agent.name)}_output`, schema: agent.outputSchema },
2206
+ format: { type: "json_schema", name: `${agentSlug(agent.name)}_output`, schema: agent.outputSchema, strict: agent.outputSchemaStrict },
2118
2207
  } : {}),
2119
2208
  };
2120
2209
  }
@@ -2642,29 +2731,23 @@ function combineText(parts) {
2642
2731
  return cleaned.length ? cleaned.join("\n\n") : undefined;
2643
2732
  }
2644
2733
  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;
2734
+ const data = attachmentSource(block, "image");
2735
+ const url = data.url;
2650
2736
  const filename = cleanString(block.filename) ?? filenameFromUrl(url) ?? `image-${index}`;
2651
2737
  return new RuntimeAttachment({
2652
2738
  filename,
2653
- mimeType: data.mimeType ?? guessInputMimeType(filename, "image/*"),
2739
+ mimeType: data.mimeType ?? cleanString(block.mime_type) ?? guessInputMimeType(filename, "image/*"),
2654
2740
  kind: "image",
2655
2741
  dataBase64: data.dataBase64,
2656
2742
  url,
2657
- metadata: inputBlockMetadata(block),
2743
+ metadata: data.metadata,
2658
2744
  });
2659
2745
  }
2660
2746
  function attachmentFromFileBlock(block, index) {
2661
- const value = cleanString(block.file_data ?? block.file_url ?? block.url);
2662
2747
  const text = cleanString(block.text);
2663
- if (!value && !text)
2664
- return undefined;
2665
2748
  const filename = cleanString(block.filename) ?? `file-${index}`;
2666
- const data = dataUriParts(value ?? "");
2667
- const url = data.dataBase64 ? undefined : value;
2749
+ const data = attachmentSource(block, "file", true);
2750
+ const url = data.url;
2668
2751
  const mimeType = data.mimeType ?? cleanString(block.mime_type) ?? guessInputMimeType(filename);
2669
2752
  return new RuntimeAttachment({
2670
2753
  filename,
@@ -2673,35 +2756,20 @@ function attachmentFromFileBlock(block, index) {
2673
2756
  dataBase64: data.dataBase64,
2674
2757
  url,
2675
2758
  text,
2676
- metadata: inputBlockMetadata(block),
2759
+ metadata: data.metadata,
2677
2760
  });
2678
2761
  }
2679
2762
  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;
2763
+ const data = attachmentSource(block, kind);
2764
+ const url = data.url;
2693
2765
  const filename = cleanString(block.filename) ?? filenameFromUrl(url) ?? `${kind}-${index}`;
2694
2766
  return new RuntimeAttachment({
2695
2767
  filename,
2696
2768
  mimeType: data.mimeType ?? cleanString(block.mime_type) ?? guessInputMimeType(filename, `${kind}/*`),
2697
2769
  kind,
2698
- dataBase64: source.endsWith("_data") ? data.dataBase64 ?? value : undefined,
2770
+ dataBase64: data.dataBase64,
2699
2771
  url,
2700
- metadata: {
2701
- ...inputBlockMetadata(block),
2702
- ...(source === "file_id" ? { file_id: value } : {}),
2703
- ...(source === "path" ? { path: value } : {}),
2704
- },
2772
+ metadata: data.metadata,
2705
2773
  });
2706
2774
  }
2707
2775
  function inputBlockMetadata(block) {
@@ -2713,13 +2781,71 @@ function dataUriParts(value) {
2713
2781
  return {};
2714
2782
  const comma = value.indexOf(",");
2715
2783
  if (comma < 0)
2716
- return {};
2784
+ throw new EdgeRuntimeError("Malformed attachment data URL");
2717
2785
  const header = value.slice(0, comma);
2718
2786
  const payload = value.slice(comma + 1);
2719
2787
  const mimeType = header.slice(5).split(";")[0] || undefined;
2788
+ const bytes = percentBytes(payload);
2720
2789
  if (header.includes(";base64"))
2721
- return { mimeType, dataBase64: payload };
2722
- return { mimeType, dataBase64: utf8Base64(payload) };
2790
+ return { mimeType, dataBase64: validatedBase64(new TextDecoder().decode(bytes)) };
2791
+ return { mimeType, dataBase64: base64Encode(bytes) };
2792
+ }
2793
+ function validatedBase64(value) {
2794
+ try {
2795
+ if (!value || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value) || btoa(atob(value)) !== value)
2796
+ throw new Error();
2797
+ return value;
2798
+ }
2799
+ catch {
2800
+ throw new EdgeRuntimeError("Attachment data must contain valid standard Base64");
2801
+ }
2802
+ }
2803
+ function percentBytes(value) {
2804
+ const bytes = [];
2805
+ for (let index = 0; index < value.length;) {
2806
+ if (value[index] === "%") {
2807
+ const hex = value.slice(index + 1, index + 3);
2808
+ if (!/^[0-9a-f]{2}$/i.test(hex))
2809
+ throw new EdgeRuntimeError("Malformed attachment data URL");
2810
+ bytes.push(Number.parseInt(hex, 16));
2811
+ index += 3;
2812
+ }
2813
+ else {
2814
+ let next = value.indexOf("%", index);
2815
+ if (next < 0)
2816
+ next = value.length;
2817
+ for (const byte of new TextEncoder().encode(value.slice(index, next)))
2818
+ bytes.push(byte);
2819
+ index = next;
2820
+ }
2821
+ }
2822
+ return new Uint8Array(bytes);
2823
+ }
2824
+ function attachmentSource(block, kind, allowText = false) {
2825
+ const keys = [`${kind}_data`, `${kind}_url`, "url", "file_id", "path", ...(kind === "image" ? ["file_data"] : [])];
2826
+ const supplied = keys.filter(key => cleanString(block[key]));
2827
+ const metadata = inputBlockMetadata(block);
2828
+ if (!supplied.length && allowText && cleanString(block.text))
2829
+ return { metadata };
2830
+ if (supplied.length !== 1)
2831
+ throw new EdgeRuntimeError(`input_${kind} requires exactly one document source`);
2832
+ const key = supplied[0];
2833
+ const value = cleanString(block[key]);
2834
+ if (["file_id", "path"].includes(key))
2835
+ return { metadata: { ...metadata, [key]: value } };
2836
+ if (value.startsWith("data:"))
2837
+ return { ...dataUriParts(value), metadata };
2838
+ if (key.endsWith("_data"))
2839
+ return { dataBase64: validatedBase64(value), metadata };
2840
+ try {
2841
+ const url = new URL(value);
2842
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password)
2843
+ throw new Error();
2844
+ }
2845
+ catch {
2846
+ throw new EdgeRuntimeError("Attachment URL must be credential-free HTTP(S)");
2847
+ }
2848
+ return { url: value, metadata };
2723
2849
  }
2724
2850
  function filenameFromUrl(url) {
2725
2851
  if (!url)
@@ -3575,16 +3701,31 @@ export class Hub {
3575
3701
  return this.hub.importMcpRegistry(input);
3576
3702
  }
3577
3703
  }
3704
+ export class Apps {
3705
+ runtime;
3706
+ constructor(runtime) {
3707
+ this.runtime = runtime;
3708
+ }
3709
+ list(options = {}) {
3710
+ return this.runtime.getApps(options);
3711
+ }
3712
+ connect(slug, options = {}) {
3713
+ return this.runtime.connectService(slug, options);
3714
+ }
3715
+ disconnect(slug) { return this.runtime.disconnectService(slug); }
3716
+ }
3578
3717
  export class Marona {
3579
3718
  hub;
3580
3719
  responses;
3581
3720
  skills;
3721
+ apps;
3582
3722
  runtime;
3583
3723
  constructor(options = {}) {
3584
3724
  this.runtime = new RuntimeEngine(options);
3585
3725
  this.hub = new Hub(this.runtime.hub);
3586
3726
  this.responses = new ResponsesClient(this.runtime);
3587
3727
  this.skills = this.runtime.skills;
3728
+ this.apps = new Apps(this.runtime);
3588
3729
  activeRuntime = this.runtime;
3589
3730
  }
3590
3731
  }
@@ -3670,6 +3811,7 @@ function normalizeRouting(value) {
3670
3811
  target_latency_ms: value.targetLatencyMs ?? value.target_latency_ms,
3671
3812
  timeout_ms: value.timeoutMs ?? value.timeout_ms,
3672
3813
  allowed_models: value.allowedModels ?? value.allowed_models,
3814
+ allowed_providers: value.allowedProviders ?? value.allowed_providers,
3673
3815
  fallback: value.fallback,
3674
3816
  });
3675
3817
  }
@@ -4520,6 +4662,8 @@ function skillToolFromSync(skill) {
4520
4662
  }
4521
4663
  function normalizeConnectedTools(tools) {
4522
4664
  return tools.flatMap((tool) => {
4665
+ if (!asRecord(tool))
4666
+ return [];
4523
4667
  if (asRecord(tool.function))
4524
4668
  return [tool];
4525
4669
  const name = stringValue(tool.name);