marona 0.9.3 → 0.10.2

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.9.3";
1
+ export const packageVersion = "0.10.2";
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,88 +461,204 @@ export class MCPConnection {
461
461
  return runtime.client(options);
462
462
  }
463
463
  }
464
+ export class MaronaAgentLoopError extends EdgeRuntimeError {
465
+ }
466
+ export class MaronaInputValidationError extends EdgeRuntimeError {
467
+ }
468
+ export class MaronaOutputValidationError extends EdgeRuntimeError {
469
+ }
470
+ export class MaronaGuardrailError extends EdgeRuntimeError {
471
+ }
472
+ export class AgentTool {
473
+ targetAgent;
474
+ name;
475
+ description;
476
+ history;
477
+ timeoutMs;
478
+ inputSchema;
479
+ outputSchema;
480
+ constructor(targetAgent, name, description, history = "summary", timeoutMs = 30_000, inputSchema, outputSchema) {
481
+ this.targetAgent = targetAgent;
482
+ this.name = name;
483
+ this.description = description;
484
+ this.history = history;
485
+ this.timeoutMs = timeoutMs;
486
+ this.inputSchema = inputSchema;
487
+ this.outputSchema = outputSchema;
488
+ validateAgentToolName(name);
489
+ if (timeoutMs <= 0)
490
+ throw new EdgeRuntimeError("Agent tool timeoutMs must be greater than zero.");
491
+ }
492
+ }
493
+ export class Handoff {
494
+ targetAgent;
495
+ name;
496
+ description;
497
+ history;
498
+ voiceTransition;
499
+ inputSchema;
500
+ constructor(targetAgent, name, description, history = "full", voiceTransition = "preserve", inputSchema) {
501
+ this.targetAgent = targetAgent;
502
+ this.name = name;
503
+ this.description = description;
504
+ this.history = history;
505
+ this.voiceTransition = voiceTransition;
506
+ this.inputSchema = inputSchema;
507
+ validateAgentToolName(name);
508
+ }
509
+ }
510
+ export function handoff(targetAgent, options = {}) {
511
+ 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);
512
+ }
464
513
  let activeRuntime;
465
514
  const supportedModalities = new Set(["text", "image", "audio", "video", "file"]);
466
515
  export class Agent {
467
516
  name;
517
+ description;
468
518
  model;
469
519
  instructions;
520
+ inputSchema;
521
+ outputSchema;
470
522
  tools;
523
+ handoffs;
524
+ inputGuardrails;
525
+ outputGuardrails;
471
526
  voice;
472
527
  modalities;
473
528
  outputModalities;
529
+ modelSettings;
474
530
  routing;
475
531
  toolChoice;
532
+ maxTurns;
533
+ hooks;
534
+ metadata;
476
535
  /** @internal */ runtime;
477
536
  constructor(options) {
478
537
  this.name = options.name.trim();
538
+ this.description = cleanString(options.description);
479
539
  this.model = (options.model ?? "marona/auto").trim();
480
- this.instructions = (options.instructions ?? "").trim();
540
+ this.instructions = typeof options.instructions === "function"
541
+ ? options.instructions
542
+ : (options.instructions ?? "").trim();
543
+ this.inputSchema = options.inputSchema;
544
+ this.outputSchema = options.outputSchema;
481
545
  this.tools = options.tools;
546
+ this.handoffs = options.handoffs ?? [];
547
+ this.inputGuardrails = options.inputGuardrails ?? [];
548
+ this.outputGuardrails = options.outputGuardrails ?? [];
482
549
  this.voice = options.voice;
483
550
  this.modalities = options.modalities;
484
551
  this.outputModalities = options.outputModalities ?? options.output_modalities;
552
+ this.modelSettings = options.modelSettings;
485
553
  this.routing = options.routing;
486
554
  this.toolChoice = normalizeToolChoice(options.toolChoice ?? options.tool_choice);
555
+ this.maxTurns = options.maxTurns;
556
+ this.hooks = options.hooks;
557
+ this.metadata = options.metadata ?? {};
487
558
  this.runtime = activeRuntime;
488
559
  if (!this.name)
489
560
  throw new EdgeRuntimeError("Agent name cannot be empty.");
490
561
  if (!this.model)
491
562
  throw new EdgeRuntimeError("Agent model cannot be empty.");
492
- if (this.tools !== undefined && !(this.tools instanceof MCPConnection)) {
493
- throw new EdgeRuntimeError("Agent tools must be a Marona Hub connection.");
563
+ agentTools(this);
564
+ agentHandoffs(this);
565
+ if (this.toolChoice === "required" && !agentHasTools(this)) {
566
+ throw new EdgeRuntimeError("Agent toolChoice='required' needs a Hub connection or Agent tool.");
494
567
  }
495
- if (this.toolChoice === "required" && !this.tools) {
496
- throw new EdgeRuntimeError("Agent toolChoice='required' needs a Hub connection.");
568
+ if (this.maxTurns !== undefined && this.maxTurns <= 0) {
569
+ throw new EdgeRuntimeError("Agent maxTurns must be greater than zero.");
497
570
  }
498
571
  validateModalities("modalities", this.modalities);
499
572
  validateModalities("outputModalities", this.outputModalities);
500
573
  }
574
+ asTool(options = {}) {
575
+ return new AgentTool(this, options.name ?? agentSlug(this.name), options.description ?? this.description ?? `Delegate a bounded task to ${this.name}.`, options.history ?? "summary", options.timeoutMs ?? 30_000, options.inputSchema ?? this.inputSchema, options.outputSchema ?? this.outputSchema);
576
+ }
501
577
  }
502
578
  export class Runner {
503
579
  static async run(agent, input, options = {}) {
504
- const runtime = agent.tools?.agentRuntime() ?? agent.runtime ?? activeRuntime;
505
- if (!runtime)
506
- throw new EdgeRuntimeError("Create Marona before running an Agent without tools.");
507
- const developerId = agent.tools ? developerIdForAgent(agent.tools) : "authenticated";
508
580
  const userId = cleanString(options.userId);
509
581
  const sessionId = cleanString(options.sessionId) ?? "default";
582
+ const context = agentContext(agent, userId, sessionId);
583
+ await runGuardrails(agent, "input", context, input);
584
+ await agent.hooks?.onStart?.(context, input);
585
+ const graph = agentGraph(agent, context, options);
586
+ const connection = agentConnection(agent);
587
+ const runtime = connection?.agentRuntime() ?? agent.runtime ?? activeRuntime;
588
+ if (!runtime)
589
+ throw new EdgeRuntimeError("Create Marona before running an Agent without tools.");
590
+ const developerId = connection ? developerIdForAgent(connection) : "authenticated";
510
591
  const conversationId = [developerId, userId ?? "anonymous", sessionId]
511
592
  .map((value) => encodeURIComponent(value))
512
593
  .join(":");
513
594
  const output = normalizeAgentOutputRequest(agent, options.output);
514
- const inputs = inputModalities(input);
595
+ const runtimeInput = agent.inputSchema ? JSON.stringify(input) : input;
596
+ validateAgentSchema(agent.inputSchema, input, "input", agent.name);
597
+ const inputs = inputModalities(runtimeInput);
515
598
  const allowedInputs = new Set(agent.modalities ?? [...supportedModalities]);
516
599
  const unsupportedInputs = [...inputs].filter((value) => !allowedInputs.has(value));
517
600
  if (unsupportedInputs.length) {
518
601
  throw new EdgeRuntimeError(`Agent input does not allow: ${unsupportedInputs.join(", ")}`);
519
602
  }
520
- const response = await runtime.client({
521
- model: agent.model,
522
- input,
523
- userId,
524
- conversationId,
525
- developerInstructions: agent.instructions || undefined,
526
- tools: agent.tools?.descriptors() ?? [],
527
- routing: agent.routing,
528
- output,
529
- metadata: {
530
- marona_agent: {
531
- input_modalities: [...inputs],
532
- allowed_output_modalities: agent.outputModalities ?? [...supportedModalities],
533
- output_modalities: output.modalities,
534
- tools_enabled: Boolean(agent.tools) && agent.toolChoice !== "none",
535
- tool_choice: agent.toolChoice,
536
- voice: agent.voice ?? {},
603
+ try {
604
+ const response = await runtime.client({
605
+ model: agent.model,
606
+ input: runtimeInput,
607
+ userId,
608
+ conversationId,
609
+ developerInstructions: resolveAgentInstructions(agent, context) || undefined,
610
+ tools: connection?.descriptors() ?? [],
611
+ routing: agent.routing,
612
+ output,
613
+ metadata: {
614
+ marona_agent: {
615
+ input_modalities: [...inputs],
616
+ allowed_output_modalities: agent.outputModalities ?? [...supportedModalities],
617
+ output_modalities: output.modalities,
618
+ tools_enabled: Boolean(agent.tools) && agent.toolChoice !== "none",
619
+ tool_choice: agent.toolChoice,
620
+ voice: agent.voice ?? {},
621
+ },
622
+ marona_multi_agent: graph,
537
623
  },
538
- },
539
- });
540
- raiseAgentInterruption(response);
541
- return { output: response.output };
624
+ });
625
+ raiseAgentInterruption(response);
626
+ const metadata = response.agent ?? asRecord(response.rawJson.agent) ?? {};
627
+ const activeAgent = agentByName(agent, cleanString(metadata.active_agent) ?? agent.name);
628
+ const lastAgent = agentByName(agent, cleanString(metadata.last_agent) ?? activeAgent.name);
629
+ const parsedOutput = parseTypedOutput(activeAgent, response.output);
630
+ const activeContext = agentContext(activeAgent, userId, sessionId);
631
+ await runGuardrails(activeAgent, "output", activeContext, parsedOutput);
632
+ const result = {
633
+ output: parsedOutput,
634
+ lastAgent,
635
+ activeAgent,
636
+ agentRuns: normalizeAgentRuns(metadata, agent),
637
+ usage: asRecord(response.rawJson.usage) ?? {},
638
+ routing: response.routing,
639
+ traceId: cleanString(metadata.trace_id),
640
+ };
641
+ for (const run of result.agentRuns.slice(1)) {
642
+ if (run.relationship === "delegation")
643
+ await agent.hooks?.onToolCall?.(context, run);
644
+ if (run.relationship === "handoff")
645
+ await agent.hooks?.onHandoff?.(context, run);
646
+ }
647
+ await activeAgent.hooks?.onComplete?.(activeContext, result);
648
+ return result;
649
+ }
650
+ catch (error) {
651
+ await agent.hooks?.onError?.(context, error);
652
+ throw error;
653
+ }
542
654
  }
543
655
  static async *stream(agent, input, options = {}) {
544
656
  yield { type: "run.started" };
657
+ yield { type: "agent.started" };
545
658
  const result = await Runner.run(agent, input, options);
659
+ for (const run of result.agentRuns.slice(1)) {
660
+ yield { type: `agent.${run.relationship}.completed`, output: undefined };
661
+ }
546
662
  if (typeof result.output === "string") {
547
663
  yield { type: "output_text.delta", delta: result.output };
548
664
  }
@@ -583,7 +699,12 @@ export class RealtimeSession {
583
699
  }
584
700
  async sendMessage(input) {
585
701
  this.ensureOpen();
586
- for (const item of realtimeMessageItems(input)) {
702
+ const context = agentContext(this.agent, this.userId, this.sessionId);
703
+ validateAgentSchema(this.agent.inputSchema, input, "input", this.agent.name);
704
+ await runGuardrails(this.agent, "input", context, input);
705
+ await this.agent.hooks?.onStart?.(context, input);
706
+ const runtimeInput = this.agent.inputSchema ? JSON.stringify(input) : input;
707
+ for (const item of realtimeMessageItems(runtimeInput)) {
587
708
  this.send({ type: "conversation.item.create", item });
588
709
  }
589
710
  this.send({ type: "response.create" });
@@ -612,7 +733,7 @@ export class RealtimeSession {
612
733
  }
613
734
  async handleProviderEvent(event) {
614
735
  const eventType = cleanString(event.type) ?? "";
615
- if (eventType === "input_audio_buffer.committed" && this.agent.tools) {
736
+ if (eventType === "input_audio_buffer.committed" && agentHasTools(this.agent)) {
616
737
  this.send({ type: "response.create" });
617
738
  }
618
739
  if (eventType === "response.done") {
@@ -622,7 +743,43 @@ export class RealtimeSession {
622
743
  for (const call of calls) {
623
744
  let output;
624
745
  try {
625
- output = await executeRealtimeGateway(this.agent, call.name, call.arguments, { userId: this.userId, sessionId: this.sessionId });
746
+ const delegated = agentToolByName(this.agent, call.name);
747
+ const transfer = handoffByName(this.agent, call.name);
748
+ if (delegated) {
749
+ this.enqueue({
750
+ type: "agent.delegation.started",
751
+ data: { source_agent: this.agent.name, target_agent: delegated.targetAgent.name },
752
+ });
753
+ const result = await Runner.run(delegated.targetAgent, delegated.inputSchema ? call.arguments : delegatedInput(call.arguments), { userId: this.userId, sessionId: this.sessionId, timeoutMs: delegated.timeoutMs });
754
+ output = { status: "completed", agent: delegated.targetAgent.name, output: result.output };
755
+ this.enqueue({
756
+ type: "agent.delegation.completed",
757
+ output: result.output,
758
+ data: { source_agent: this.agent.name, target_agent: delegated.targetAgent.name },
759
+ });
760
+ }
761
+ else if (transfer) {
762
+ const source = this.agent;
763
+ validateAgentSchema(transfer.inputSchema, call.arguments, "input", transfer.targetAgent.name);
764
+ this.agent = transfer.targetAgent;
765
+ this.send({
766
+ type: "session.update",
767
+ session: {
768
+ type: "realtime",
769
+ instructions: resolveAgentInstructions(this.agent, agentContext(this.agent, this.userId, this.sessionId)),
770
+ tools: realtimeAgentToolDefinitions(this.agent),
771
+ tool_choice: agentHasTools(this.agent) ? this.agent.toolChoice : "none",
772
+ },
773
+ });
774
+ output = { status: "completed", active_agent: this.agent.name, handoff_input: call.arguments };
775
+ this.enqueue({
776
+ type: "agent.handoff.completed",
777
+ data: { source_agent: source.name, target_agent: this.agent.name },
778
+ });
779
+ }
780
+ else {
781
+ output = await executeRealtimeGateway(this.agent, call.name, call.arguments, { userId: this.userId, sessionId: this.sessionId });
782
+ }
626
783
  }
627
784
  catch (error) {
628
785
  output = { status: "failed", error: String(error) };
@@ -648,7 +805,10 @@ export class RealtimeSession {
648
805
  });
649
806
  return;
650
807
  }
651
- this.enqueue({ type: "response.completed", output: openAIRealtimeOutput(event), data: {} });
808
+ const context = agentContext(this.agent, this.userId, this.sessionId);
809
+ const output = parseTypedOutput(this.agent, openAIRealtimeOutput(event));
810
+ await runGuardrails(this.agent, "output", context, output);
811
+ this.enqueue({ type: "response.completed", output, data: {} });
652
812
  return;
653
813
  }
654
814
  const mapped = {
@@ -711,10 +871,11 @@ export class RealtimeRunner {
711
871
  return new RealtimeSession(descriptor, socket, agent, options);
712
872
  }
713
873
  static async createSessionDescriptor(agent, options = {}) {
714
- const runtime = agent.tools?.agentRuntime() ?? agent.runtime ?? activeRuntime;
874
+ const connection = agentConnection(agent);
875
+ const runtime = connection?.agentRuntime() ?? agent.runtime ?? activeRuntime;
715
876
  if (!runtime)
716
877
  throw new EdgeRuntimeError("Create Marona before creating a realtime session.");
717
- const developerId = agent.tools ? developerIdForAgent(agent.tools) : "authenticated";
878
+ const developerId = connection ? developerIdForAgent(connection) : "authenticated";
718
879
  const userId = cleanString(options.userId);
719
880
  const sessionId = cleanString(options.sessionId) ?? "default";
720
881
  const conversationId = [developerId, userId ?? "anonymous", sessionId]
@@ -731,7 +892,7 @@ export class RealtimeRunner {
731
892
  conversationId,
732
893
  mode: inputs.has("image") || inputs.has("video") ? "voice_vision" : "voice",
733
894
  voice: cleanString(agent.voice?.output_voice),
734
- instructions: agent.instructions || undefined,
895
+ instructions: resolveAgentInstructions(agent, agentContext(agent, userId, sessionId)) || undefined,
735
896
  outputModalities,
736
897
  transport: options.transport ?? "webrtc",
737
898
  metadata: {
@@ -741,9 +902,10 @@ export class RealtimeRunner {
741
902
  marona_agent: {
742
903
  input_modalities: [...inputs],
743
904
  output_modalities: outputModalities,
744
- tools_enabled: Boolean(agent.tools) && agent.toolChoice !== "none",
905
+ tools_enabled: agentHasTools(agent) && agent.toolChoice !== "none",
745
906
  tool_choice: agent.toolChoice,
746
907
  },
908
+ marona_multi_agent: agentGraph(agent, agentContext(agent, userId, sessionId)),
747
909
  },
748
910
  });
749
911
  }
@@ -764,27 +926,95 @@ async function openRealtimeSocket(descriptor) {
764
926
  return socket;
765
927
  }
766
928
  async function executeRealtimeGateway(agent, name, argumentsValue, options) {
767
- if (!agent.tools)
929
+ const connection = agentConnection(agent);
930
+ if (!connection)
768
931
  throw new EdgeRuntimeError("The realtime Agent has no Marona Hub tools connected.");
769
932
  const userId = cleanString(options.userId);
770
933
  const sessionId = cleanString(options.sessionId) ?? "default";
771
- const conversationId = [developerIdForAgent(agent.tools), userId ?? "anonymous", sessionId]
934
+ const conversationId = [developerIdForAgent(connection), userId ?? "anonymous", sessionId]
772
935
  .map((value) => encodeURIComponent(value)).join(":");
773
936
  if (name === "marona__discover_capabilities") {
774
937
  const query = cleanString(argumentsValue.request) ?? cleanString(argumentsValue.query);
775
938
  if (!query)
776
939
  throw new EdgeRuntimeError("Realtime capability discovery requires a request.");
777
- return { status: "completed", capabilities: realtimeCapabilities(agent.tools.listTools(), query) };
940
+ return { status: "completed", capabilities: realtimeCapabilities(connection.listTools(), query) };
778
941
  }
779
942
  if (name === "marona__call_capability") {
780
943
  const capability = cleanString(argumentsValue.name);
781
944
  if (!capability)
782
945
  throw new EdgeRuntimeError("Realtime capability execution requires a name.");
783
- const result = await agent.tools.callTool(capability, asRecord(argumentsValue.arguments) ?? {}, { userId, conversationId });
946
+ const result = await connection.callTool(capability, asRecord(argumentsValue.arguments) ?? {}, { userId, conversationId });
784
947
  return { status: "completed", capability, result };
785
948
  }
786
949
  throw new EdgeRuntimeError(`Unsupported realtime gateway call '${name}'.`);
787
950
  }
951
+ function agentToolByName(agent, name) {
952
+ return agentTools(agent).find((value) => value instanceof AgentTool && value.name === name);
953
+ }
954
+ function handoffByName(agent, name) {
955
+ return agentHandoffs(agent).find((value) => value.name === name);
956
+ }
957
+ function delegatedInput(argumentsValue) {
958
+ for (const key of ["input", "request", "task", "message"]) {
959
+ const value = cleanString(argumentsValue[key]);
960
+ if (value)
961
+ return value;
962
+ }
963
+ return JSON.stringify(argumentsValue);
964
+ }
965
+ function realtimeAgentToolDefinitions(agent) {
966
+ const values = [];
967
+ if (agentTools(agent).some((value) => value instanceof MCPConnection)) {
968
+ values.push({
969
+ type: "function",
970
+ name: "marona__discover_capabilities",
971
+ description: "Discover relevant connected Marona capabilities.",
972
+ parameters: {
973
+ type: "object",
974
+ properties: { request: { type: "string" } },
975
+ required: ["request"],
976
+ additionalProperties: false,
977
+ },
978
+ }, {
979
+ type: "function",
980
+ name: "marona__call_capability",
981
+ description: "Execute one exact capability returned by discovery.",
982
+ parameters: {
983
+ type: "object",
984
+ properties: {
985
+ name: { type: "string" },
986
+ arguments: { type: "object", additionalProperties: true },
987
+ },
988
+ required: ["name", "arguments"],
989
+ additionalProperties: false,
990
+ },
991
+ });
992
+ }
993
+ for (const value of agentTools(agent)) {
994
+ if (value instanceof AgentTool) {
995
+ values.push(realtimeAgentFunction(value.name, value.description, value.inputSchema));
996
+ }
997
+ }
998
+ for (const value of agentHandoffs(agent)) {
999
+ values.push(realtimeAgentFunction(value.name, value.description, value.inputSchema));
1000
+ }
1001
+ return values;
1002
+ }
1003
+ function realtimeAgentFunction(name, description, schema) {
1004
+ return {
1005
+ type: "function",
1006
+ name,
1007
+ description,
1008
+ parameters: schema ?? {
1009
+ type: "object",
1010
+ properties: {
1011
+ input: { type: "string", description: "The bounded task or transfer context." },
1012
+ },
1013
+ required: ["input"],
1014
+ additionalProperties: false,
1015
+ },
1016
+ };
1017
+ }
788
1018
  function realtimeMessageItems(input) {
789
1019
  if (typeof input === "string") {
790
1020
  return [{ type: "message", role: "user", content: [{ type: "input_text", text: input }] }];
@@ -883,6 +1113,246 @@ function normalizeToolChoice(value) {
883
1113
  }
884
1114
  return choice;
885
1115
  }
1116
+ function validateAgentToolName(value) {
1117
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(value)) {
1118
+ throw new EdgeRuntimeError("Agent tool and handoff names must use 1-64 letters, numbers, underscores, or hyphens.");
1119
+ }
1120
+ }
1121
+ function agentSlug(value) {
1122
+ return value.trim().replace(/[^A-Za-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase().slice(0, 64) || "agent";
1123
+ }
1124
+ function agentTools(agent) {
1125
+ if (!agent.tools)
1126
+ return [];
1127
+ const values = Array.isArray(agent.tools) ? agent.tools : [agent.tools];
1128
+ const names = new Set();
1129
+ for (const value of values) {
1130
+ if (!(value instanceof MCPConnection) && !(value instanceof AgentTool)) {
1131
+ throw new EdgeRuntimeError("Agent tools may contain only Hub connections and Agent.asTool() values.");
1132
+ }
1133
+ if (value instanceof AgentTool) {
1134
+ if (names.has(value.name))
1135
+ throw new EdgeRuntimeError(`Duplicate Agent tool name '${value.name}'.`);
1136
+ names.add(value.name);
1137
+ }
1138
+ }
1139
+ return values;
1140
+ }
1141
+ function agentHandoffs(agent) {
1142
+ const values = agent.handoffs.map((value) => value instanceof Handoff ? value : handoff(value));
1143
+ const names = new Set();
1144
+ for (const value of values) {
1145
+ if (names.has(value.name))
1146
+ throw new EdgeRuntimeError(`Duplicate handoff name '${value.name}'.`);
1147
+ names.add(value.name);
1148
+ }
1149
+ for (const value of agentTools(agent)) {
1150
+ if (value instanceof AgentTool && names.has(value.name)) {
1151
+ throw new EdgeRuntimeError(`Agent tool and handoff names must be unique: ${value.name}`);
1152
+ }
1153
+ }
1154
+ return values;
1155
+ }
1156
+ function agentHasTools(agent) {
1157
+ return agentTools(agent).length > 0 || agentHandoffs(agent).length > 0;
1158
+ }
1159
+ function agentConnection(agent) {
1160
+ let found;
1161
+ const visited = new Set();
1162
+ const visit = (current) => {
1163
+ if (visited.has(current))
1164
+ return;
1165
+ visited.add(current);
1166
+ for (const value of agentTools(current)) {
1167
+ if (value instanceof MCPConnection) {
1168
+ if (found && found.agentRuntime() !== value.agentRuntime()) {
1169
+ throw new EdgeRuntimeError("All Hub connections in one Agent graph must belong to the same Marona client.");
1170
+ }
1171
+ found = value;
1172
+ }
1173
+ else
1174
+ visit(value.targetAgent);
1175
+ }
1176
+ for (const value of agentHandoffs(current))
1177
+ visit(value.targetAgent);
1178
+ };
1179
+ visit(agent);
1180
+ return found;
1181
+ }
1182
+ function agentContext(agent, userId, sessionId) {
1183
+ return { userId, sessionId, agentName: agent.name, metadata: safeAgentMetadata(agent.metadata) };
1184
+ }
1185
+ function resolveAgentInstructions(agent, context) {
1186
+ const value = typeof agent.instructions === "function" ? agent.instructions(context) : agent.instructions;
1187
+ if (typeof value !== "string")
1188
+ throw new EdgeRuntimeError("Agent instructions callback must return a string.");
1189
+ return value;
1190
+ }
1191
+ async function runGuardrails(agent, stage, context, value) {
1192
+ const guardrails = stage === "input" ? agent.inputGuardrails : agent.outputGuardrails;
1193
+ for (const guardrail of guardrails) {
1194
+ const result = await guardrail(context, value);
1195
+ if (result === false || (typeof result === "string" && result.trim())) {
1196
+ throw new MaronaGuardrailError(typeof result === "string" ? result : `${stage} guardrail blocked Agent execution.`);
1197
+ }
1198
+ }
1199
+ }
1200
+ function agentGraph(agent, context, options = {}) {
1201
+ const maxDepth = options.maxDepth ?? 4;
1202
+ if (maxDepth <= 0 || maxDepth > 8)
1203
+ throw new EdgeRuntimeError("Multi-agent maxDepth must be between 1 and 8.");
1204
+ const limits = {
1205
+ max_agent_calls: options.maxAgentCalls ?? 10,
1206
+ max_handoffs: options.maxHandoffs ?? 5,
1207
+ max_depth: maxDepth,
1208
+ timeout_ms: options.timeoutMs ?? 60_000,
1209
+ max_turns: options.maxTurns ?? agent.maxTurns ?? 20,
1210
+ };
1211
+ if (Object.values(limits).some((value) => value <= 0)) {
1212
+ throw new EdgeRuntimeError("Multi-agent execution limits must be greater than zero.");
1213
+ }
1214
+ const ids = new Map();
1215
+ const visiting = new Set();
1216
+ const definitions = {};
1217
+ const visit = (current, depth) => {
1218
+ if (visiting.has(current))
1219
+ throw new MaronaAgentLoopError(`Agent graph cycle detected at '${current.name}'.`);
1220
+ const existing = ids.get(current);
1221
+ if (existing)
1222
+ return existing;
1223
+ if (depth > maxDepth)
1224
+ throw new EdgeRuntimeError(`Agent graph exceeds maxDepth=${maxDepth}.`);
1225
+ if (ids.size >= 64)
1226
+ throw new EdgeRuntimeError("Agent graph cannot contain more than 64 agents.");
1227
+ const id = `agent_${ids.size}`;
1228
+ ids.set(current, id);
1229
+ visiting.add(current);
1230
+ const delegations = agentTools(current).filter((value) => value instanceof AgentTool).map((value) => ({
1231
+ name: value.name,
1232
+ description: value.description,
1233
+ target: visit(value.targetAgent, depth + 1),
1234
+ history: value.history,
1235
+ timeout_ms: value.timeoutMs,
1236
+ input_schema: value.inputSchema,
1237
+ output_schema: value.outputSchema,
1238
+ }));
1239
+ const transfers = agentHandoffs(current).map((value) => ({
1240
+ name: value.name,
1241
+ description: value.description,
1242
+ target: visit(value.targetAgent, depth + 1),
1243
+ history: value.history,
1244
+ voice_transition: value.voiceTransition,
1245
+ input_schema: value.inputSchema,
1246
+ }));
1247
+ definitions[id] = {
1248
+ name: current.name,
1249
+ description: current.description,
1250
+ instructions: resolveAgentInstructions(current, { ...context, agentName: current.name, metadata: safeAgentMetadata(current.metadata) }),
1251
+ model: current.model,
1252
+ model_settings: current.modelSettings ?? {},
1253
+ routing: current.routing ?? {},
1254
+ tool_choice: current.toolChoice,
1255
+ max_turns: current.maxTurns ?? 20,
1256
+ input_schema: current.inputSchema,
1257
+ output_schema: current.outputSchema,
1258
+ hub_tools: agentTools(current).some((value) => value instanceof MCPConnection),
1259
+ delegations,
1260
+ handoffs: transfers,
1261
+ metadata: safeAgentMetadata(current.metadata),
1262
+ voice: current.voice ?? {},
1263
+ modalities: current.modalities ?? [],
1264
+ output_modalities: current.outputModalities ?? [],
1265
+ };
1266
+ visiting.delete(current);
1267
+ return id;
1268
+ };
1269
+ const root = visit(agent, 0);
1270
+ return { version: 1, root, agents: definitions, limits };
1271
+ }
1272
+ function safeAgentMetadata(value) {
1273
+ const blocked = ["api_key", "authorization", "credential", "password", "secret", "token"];
1274
+ return Object.fromEntries(Object.entries(value).filter(([key]) => !blocked.some((part) => key.toLowerCase().includes(part))));
1275
+ }
1276
+ function agentByName(root, name) {
1277
+ const visited = new Set();
1278
+ const find = (current) => {
1279
+ if (visited.has(current))
1280
+ return undefined;
1281
+ visited.add(current);
1282
+ if (current.name === name)
1283
+ return current;
1284
+ const targets = [
1285
+ ...agentTools(current).filter((value) => value instanceof AgentTool).map((value) => value.targetAgent),
1286
+ ...agentHandoffs(current).map((value) => value.targetAgent),
1287
+ ];
1288
+ for (const target of targets) {
1289
+ const match = find(target);
1290
+ if (match)
1291
+ return match;
1292
+ }
1293
+ return undefined;
1294
+ };
1295
+ return find(root) ?? root;
1296
+ }
1297
+ function normalizeAgentRuns(metadata, root) {
1298
+ const values = Array.isArray(metadata.runs) ? metadata.runs : [];
1299
+ const runs = values.map(asRecord).filter(Boolean).map((value, index) => ({
1300
+ runId: cleanString(value.run_id) ?? `run_${index}`,
1301
+ agentName: cleanString(value.agent_name) ?? root.name,
1302
+ parentRunId: cleanString(value.parent_run_id),
1303
+ relationship: cleanString(value.relationship) ?? "root",
1304
+ }));
1305
+ return runs.length ? runs : [{ runId: "run_root", agentName: root.name, relationship: "root" }];
1306
+ }
1307
+ function parseTypedOutput(agent, value) {
1308
+ if (!agent.outputSchema)
1309
+ return value;
1310
+ let parsed = value;
1311
+ if (typeof value === "string") {
1312
+ try {
1313
+ parsed = JSON.parse(value);
1314
+ }
1315
+ catch { /* validation below reports the contract failure */ }
1316
+ }
1317
+ validateAgentSchema(agent.outputSchema, parsed, "output", agent.name);
1318
+ return parsed;
1319
+ }
1320
+ function validateAgentSchema(schema, value, stage, agentName) {
1321
+ if (!schema)
1322
+ return;
1323
+ const fail = (message) => {
1324
+ const ErrorType = stage === "input" ? MaronaInputValidationError : MaronaOutputValidationError;
1325
+ throw new ErrorType(`${stage} validation failed for Agent '${agentName}': ${message}`);
1326
+ };
1327
+ const visit = (current, candidate, path) => {
1328
+ const type = cleanString(current.type);
1329
+ if (type === "object") {
1330
+ const record = asRecord(candidate);
1331
+ if (!record)
1332
+ return fail(`${path} must be an object.`);
1333
+ for (const key of (Array.isArray(current.required) ? current.required : [])) {
1334
+ if (!(String(key) in record))
1335
+ fail(`${path}.${String(key)} is required.`);
1336
+ }
1337
+ const properties = asRecord(current.properties) ?? {};
1338
+ for (const [key, child] of Object.entries(properties)) {
1339
+ if (key in record && isPlainObject(child))
1340
+ visit(child, record[key], `${path}.${key}`);
1341
+ }
1342
+ }
1343
+ else if (type === "array" && !Array.isArray(candidate))
1344
+ fail(`${path} must be an array.`);
1345
+ else if (type === "string" && typeof candidate !== "string")
1346
+ fail(`${path} must be a string.`);
1347
+ else if (type === "number" && typeof candidate !== "number")
1348
+ fail(`${path} must be a number.`);
1349
+ else if (type === "integer" && (!Number.isInteger(candidate)))
1350
+ fail(`${path} must be an integer.`);
1351
+ else if (type === "boolean" && typeof candidate !== "boolean")
1352
+ fail(`${path} must be a boolean.`);
1353
+ };
1354
+ visit(schema, value, "$");
1355
+ }
886
1356
  function inputModalities(input) {
887
1357
  if (typeof input === "string")
888
1358
  return new Set(["text"]);
@@ -914,7 +1384,13 @@ function normalizeAgentOutputRequest(agent, output) {
914
1384
  const unsupported = modalities.filter((value) => !allowed.has(value));
915
1385
  if (unsupported.length)
916
1386
  throw new EdgeRuntimeError(`Agent output does not allow: ${unsupported.join(", ")}`);
917
- return { ...(output ?? {}), modalities: [...new Set(modalities)] };
1387
+ return {
1388
+ ...(output ?? {}),
1389
+ modalities: [...new Set(modalities)],
1390
+ ...(agent.outputSchema ? {
1391
+ format: { type: "json_schema", name: `${agentSlug(agent.name)}_output`, schema: agent.outputSchema },
1392
+ } : {}),
1393
+ };
918
1394
  }
919
1395
  function raiseAgentInterruption(response) {
920
1396
  if (response.needsServiceConnection) {
@@ -2260,6 +2736,7 @@ class RuntimeEngine extends RuntimeTransport {
2260
2736
  needsServiceConnection: false,
2261
2737
  model: model.name,
2262
2738
  routing: {},
2739
+ agent: {},
2263
2740
  toolCall: toolResults.length ? { results: toolResults } : undefined,
2264
2741
  rawJson: {
2265
2742
  mode: this.mode,
@@ -2524,6 +3001,7 @@ function parseRuntimeMessageResponse(payload) {
2524
3001
  rawJson: { ...payload },
2525
3002
  model: stringValue(payload.model),
2526
3003
  routing: asRecord(payload.routing) ?? {},
3004
+ agent: asRecord(payload.agent) ?? {},
2527
3005
  };
2528
3006
  }
2529
3007
  function normalizeRouting(value) {