marona 0.9.1 → 0.9.3

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.1";
1
+ export const packageVersion = "0.9.3";
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"];
@@ -472,6 +472,7 @@ export class Agent {
472
472
  modalities;
473
473
  outputModalities;
474
474
  routing;
475
+ toolChoice;
475
476
  /** @internal */ runtime;
476
477
  constructor(options) {
477
478
  this.name = options.name.trim();
@@ -482,6 +483,7 @@ export class Agent {
482
483
  this.modalities = options.modalities;
483
484
  this.outputModalities = options.outputModalities ?? options.output_modalities;
484
485
  this.routing = options.routing;
486
+ this.toolChoice = normalizeToolChoice(options.toolChoice ?? options.tool_choice);
485
487
  this.runtime = activeRuntime;
486
488
  if (!this.name)
487
489
  throw new EdgeRuntimeError("Agent name cannot be empty.");
@@ -490,6 +492,9 @@ export class Agent {
490
492
  if (this.tools !== undefined && !(this.tools instanceof MCPConnection)) {
491
493
  throw new EdgeRuntimeError("Agent tools must be a Marona Hub connection.");
492
494
  }
495
+ if (this.toolChoice === "required" && !this.tools) {
496
+ throw new EdgeRuntimeError("Agent toolChoice='required' needs a Hub connection.");
497
+ }
493
498
  validateModalities("modalities", this.modalities);
494
499
  validateModalities("outputModalities", this.outputModalities);
495
500
  }
@@ -526,7 +531,8 @@ export class Runner {
526
531
  input_modalities: [...inputs],
527
532
  allowed_output_modalities: agent.outputModalities ?? [...supportedModalities],
528
533
  output_modalities: output.modalities,
529
- tools_enabled: Boolean(agent.tools),
534
+ tools_enabled: Boolean(agent.tools) && agent.toolChoice !== "none",
535
+ tool_choice: agent.toolChoice,
530
536
  voice: agent.voice ?? {},
531
537
  },
532
538
  },
@@ -543,11 +549,168 @@ export class Runner {
543
549
  yield { type: "run.completed", output: result.output };
544
550
  }
545
551
  }
552
+ export class RealtimeSession {
553
+ provider;
554
+ model;
555
+ conversationId;
556
+ descriptor;
557
+ agent;
558
+ userId;
559
+ sessionId;
560
+ socket;
561
+ events = [];
562
+ waiters = [];
563
+ closed = false;
564
+ constructor(descriptor, socket, agent, options) {
565
+ this.descriptor = descriptor;
566
+ this.socket = socket;
567
+ this.agent = agent;
568
+ this.userId = cleanString(options.userId);
569
+ this.sessionId = cleanString(options.sessionId) ?? "default";
570
+ this.provider = descriptor.provider;
571
+ this.model = descriptor.model;
572
+ this.conversationId = descriptor.conversationId;
573
+ socket.addEventListener("message", (event) => {
574
+ void this.handleProviderEvent(JSON.parse(String(event.data)));
575
+ });
576
+ socket.addEventListener("close", () => this.finish());
577
+ socket.addEventListener("error", () => {
578
+ this.enqueue({ type: "error", data: { message: "Realtime connection failed." } });
579
+ });
580
+ }
581
+ get status() {
582
+ return this.closed ? "closed" : "connected";
583
+ }
584
+ async sendMessage(input) {
585
+ this.ensureOpen();
586
+ for (const item of realtimeMessageItems(input)) {
587
+ this.send({ type: "conversation.item.create", item });
588
+ }
589
+ this.send({ type: "response.create" });
590
+ }
591
+ async sendAudio(audio) {
592
+ this.ensureOpen();
593
+ let binary = "";
594
+ for (const value of audio)
595
+ binary += String.fromCharCode(value);
596
+ this.send({ type: "input_audio_buffer.append", audio: btoa(binary) });
597
+ }
598
+ async close() {
599
+ if (this.closed)
600
+ return;
601
+ this.closed = true;
602
+ this.socket.close();
603
+ this.finish();
604
+ }
605
+ async *[Symbol.asyncIterator]() {
606
+ while (!this.closed || this.events.length) {
607
+ const event = await this.nextEvent();
608
+ if (!event)
609
+ return;
610
+ yield event;
611
+ }
612
+ }
613
+ async handleProviderEvent(event) {
614
+ const eventType = cleanString(event.type) ?? "";
615
+ if (eventType === "input_audio_buffer.committed" && this.agent.tools) {
616
+ this.send({ type: "response.create" });
617
+ }
618
+ if (eventType === "response.done") {
619
+ const calls = openAIRealtimeToolCalls(event);
620
+ if (calls.length) {
621
+ let forceTool = false;
622
+ for (const call of calls) {
623
+ let output;
624
+ try {
625
+ output = await executeRealtimeGateway(this.agent, call.name, call.arguments, { userId: this.userId, sessionId: this.sessionId });
626
+ }
627
+ catch (error) {
628
+ output = { status: "failed", error: String(error) };
629
+ }
630
+ this.send({
631
+ type: "conversation.item.create",
632
+ item: {
633
+ type: "function_call_output",
634
+ call_id: call.callId,
635
+ output: JSON.stringify(output),
636
+ },
637
+ });
638
+ forceTool ||= call.name === "marona__discover_capabilities";
639
+ }
640
+ this.send({
641
+ type: "response.create",
642
+ response: {
643
+ instructions: forceTool
644
+ ? "Call marona__call_capability with one exact discovered capability and arguments matching its schema."
645
+ : "Answer naturally using the completed capability result.",
646
+ tool_choice: forceTool ? "required" : "auto",
647
+ },
648
+ });
649
+ return;
650
+ }
651
+ this.enqueue({ type: "response.completed", output: openAIRealtimeOutput(event), data: {} });
652
+ return;
653
+ }
654
+ const mapped = {
655
+ "session.created": "session.connected",
656
+ "session.updated": "session.updated",
657
+ "input_audio_buffer.speech_started": "input_audio.started",
658
+ "input_audio_buffer.speech_stopped": "input_audio.stopped",
659
+ "input_audio_buffer.committed": "input_audio.committed",
660
+ "response.output_audio.delta": "output_audio.delta",
661
+ "response.output_audio_transcript.delta": "transcript.delta",
662
+ "response.output_text.delta": "output_text.delta",
663
+ error: "error",
664
+ };
665
+ const type = mapped[eventType];
666
+ if (!type)
667
+ return;
668
+ this.enqueue({
669
+ type,
670
+ delta: cleanString(event.delta),
671
+ data: type === "error" ? asRecord(event.error) ?? {} : {},
672
+ });
673
+ }
674
+ send(event) {
675
+ this.ensureOpen();
676
+ this.socket.send(JSON.stringify(event));
677
+ }
678
+ ensureOpen() {
679
+ if (this.closed || this.socket.readyState !== 1) {
680
+ throw new EdgeRuntimeError("Realtime session is closed.");
681
+ }
682
+ }
683
+ enqueue(event) {
684
+ const waiter = this.waiters.shift();
685
+ if (waiter)
686
+ waiter(event);
687
+ else
688
+ this.events.push(event);
689
+ }
690
+ nextEvent() {
691
+ const event = this.events.shift();
692
+ if (event)
693
+ return Promise.resolve(event);
694
+ if (this.closed)
695
+ return Promise.resolve(undefined);
696
+ return new Promise((resolve) => this.waiters.push(resolve));
697
+ }
698
+ finish() {
699
+ this.closed = true;
700
+ for (const waiter of this.waiters.splice(0))
701
+ waiter(undefined);
702
+ }
703
+ }
546
704
  export class RealtimeRunner {
547
705
  static async connect(agent, options = {}) {
548
- return RealtimeRunner.createClientSession(agent, options);
706
+ const descriptor = await RealtimeRunner.createSessionDescriptor(agent, {
707
+ ...options,
708
+ transport: "websocket",
709
+ });
710
+ const socket = await openRealtimeSocket(descriptor);
711
+ return new RealtimeSession(descriptor, socket, agent, options);
549
712
  }
550
- static async createClientSession(agent, options = {}) {
713
+ static async createSessionDescriptor(agent, options = {}) {
551
714
  const runtime = agent.tools?.agentRuntime() ?? agent.runtime ?? activeRuntime;
552
715
  if (!runtime)
553
716
  throw new EdgeRuntimeError("Create Marona before creating a realtime session.");
@@ -570,6 +733,7 @@ export class RealtimeRunner {
570
733
  voice: cleanString(agent.voice?.output_voice),
571
734
  instructions: agent.instructions || undefined,
572
735
  outputModalities,
736
+ transport: options.transport ?? "webrtc",
573
737
  metadata: {
574
738
  voice: agent.voice ?? {},
575
739
  routing: agent.routing ?? {},
@@ -577,53 +741,102 @@ export class RealtimeRunner {
577
741
  marona_agent: {
578
742
  input_modalities: [...inputs],
579
743
  output_modalities: outputModalities,
580
- tools_enabled: Boolean(agent.tools),
744
+ tools_enabled: Boolean(agent.tools) && agent.toolChoice !== "none",
745
+ tool_choice: agent.toolChoice,
581
746
  },
582
747
  },
583
748
  });
584
749
  }
585
- static async handleToolCall(agent, name, argumentsValue = {}, options = {}) {
586
- if (!agent.tools)
587
- throw new EdgeRuntimeError("The realtime Agent has no Marona Hub tools connected.");
588
- const userId = cleanString(options.userId);
589
- const sessionId = cleanString(options.sessionId) ?? "default";
590
- const developerId = developerIdForAgent(agent.tools);
591
- const conversationId = [developerId, userId ?? "anonymous", sessionId]
592
- .map((value) => encodeURIComponent(value)).join(":");
593
- if (name === "marona__discover_capabilities") {
594
- const query = cleanString(argumentsValue.request) ?? cleanString(argumentsValue.query);
595
- if (!query)
596
- throw new EdgeRuntimeError("Realtime capability discovery requires a request.");
597
- return {
598
- status: "completed",
599
- capabilities: realtimeCapabilities(agent.tools.listTools(), query),
600
- instruction: "Choose the exact capability name and call marona__call_capability with arguments matching its inputSchema.",
601
- };
602
- }
603
- if (name === "marona__call_capability") {
604
- const capability = cleanString(argumentsValue.name);
605
- if (!capability)
606
- throw new EdgeRuntimeError("Realtime capability execution requires a name.");
607
- const toolArguments = asRecord(argumentsValue.arguments) ?? {};
608
- const result = await agent.tools.callTool(capability, toolArguments, {
609
- userId,
610
- conversationId,
611
- });
612
- return { status: "completed", capability, result };
613
- }
614
- throw new EdgeRuntimeError(`Unsupported realtime gateway call '${name}'.`);
750
+ }
751
+ async function openRealtimeSocket(descriptor) {
752
+ if (!descriptor.clientSecret) {
753
+ throw new EdgeRuntimeError("Realtime provider did not return a client secret.");
615
754
  }
616
- static async handleEvent(agent, event, options = {}) {
617
- if (event.type !== "tool_call") {
618
- throw new EdgeRuntimeError("RealtimeRunner supports neutral tool_call events.");
755
+ const Socket = globalThis.WebSocket ?? (await import("ws")).default;
756
+ const socket = new Socket(descriptor.endpoint, [
757
+ "realtime",
758
+ `openai-insecure-api-key.${descriptor.clientSecret}`,
759
+ ]);
760
+ await new Promise((resolve, reject) => {
761
+ socket.addEventListener("open", () => resolve());
762
+ socket.addEventListener("error", () => reject(new EdgeRuntimeError("Realtime connection failed.")));
763
+ });
764
+ return socket;
765
+ }
766
+ async function executeRealtimeGateway(agent, name, argumentsValue, options) {
767
+ if (!agent.tools)
768
+ throw new EdgeRuntimeError("The realtime Agent has no Marona Hub tools connected.");
769
+ const userId = cleanString(options.userId);
770
+ const sessionId = cleanString(options.sessionId) ?? "default";
771
+ const conversationId = [developerIdForAgent(agent.tools), userId ?? "anonymous", sessionId]
772
+ .map((value) => encodeURIComponent(value)).join(":");
773
+ if (name === "marona__discover_capabilities") {
774
+ const query = cleanString(argumentsValue.request) ?? cleanString(argumentsValue.query);
775
+ if (!query)
776
+ throw new EdgeRuntimeError("Realtime capability discovery requires a request.");
777
+ return { status: "completed", capabilities: realtimeCapabilities(agent.tools.listTools(), query) };
778
+ }
779
+ if (name === "marona__call_capability") {
780
+ const capability = cleanString(argumentsValue.name);
781
+ if (!capability)
782
+ throw new EdgeRuntimeError("Realtime capability execution requires a name.");
783
+ const result = await agent.tools.callTool(capability, asRecord(argumentsValue.arguments) ?? {}, { userId, conversationId });
784
+ return { status: "completed", capability, result };
785
+ }
786
+ throw new EdgeRuntimeError(`Unsupported realtime gateway call '${name}'.`);
787
+ }
788
+ function realtimeMessageItems(input) {
789
+ if (typeof input === "string") {
790
+ return [{ type: "message", role: "user", content: [{ type: "input_text", text: input }] }];
791
+ }
792
+ const messages = Array.isArray(input) ? input : [input];
793
+ return messages.map((message) => {
794
+ if (typeof message === "string") {
795
+ return { type: "message", role: "user", content: [{ type: "input_text", text: message }] };
619
796
  }
620
- const output = await RealtimeRunner.handleToolCall(agent, cleanString(event.name) ?? "", asRecord(event.arguments) ?? {}, options);
621
797
  return {
622
- type: "tool_result",
623
- call_id: cleanString(event.call_id) ?? "",
624
- output,
798
+ type: "message",
799
+ role: message.role ?? "user",
800
+ content: Array.isArray(message.content)
801
+ ? message.content
802
+ : [{ type: "input_text", text: String(message.content ?? "") }],
625
803
  };
804
+ });
805
+ }
806
+ function openAIRealtimeToolCalls(event) {
807
+ const response = asRecord(event.response) ?? {};
808
+ const output = Array.isArray(response.output) ? response.output : [];
809
+ return output.flatMap((value) => {
810
+ const item = asRecord(value);
811
+ if (!item || item.type !== "function_call")
812
+ return [];
813
+ let argumentsValue = {};
814
+ try {
815
+ argumentsValue = asRecord(JSON.parse(String(item.arguments ?? "{}"))) ?? {};
816
+ }
817
+ catch { }
818
+ return [{
819
+ callId: cleanString(item.call_id) ?? "",
820
+ name: cleanString(item.name) ?? "",
821
+ arguments: argumentsValue,
822
+ }];
823
+ });
824
+ }
825
+ function openAIRealtimeOutput(event) {
826
+ const response = asRecord(event.response) ?? {};
827
+ const output = Array.isArray(response.output) ? response.output : [];
828
+ const parts = [];
829
+ for (const value of output) {
830
+ const item = asRecord(value);
831
+ const content = item && Array.isArray(item.content) ? item.content : [];
832
+ for (const contentValue of content) {
833
+ const part = asRecord(contentValue);
834
+ const text = cleanString(part?.text) ?? cleanString(part?.transcript);
835
+ if (text)
836
+ parts.push({ type: "output_text", text });
837
+ }
626
838
  }
839
+ return parts.length === 1 ? String(parts[0].text) : parts;
627
840
  }
628
841
  function realtimeCapabilities(tools, query, limit = 12) {
629
842
  const terms = new Set(query.toLowerCase().replaceAll("-", " ").split(/\s+/)
@@ -663,6 +876,13 @@ function validateModalities(name, values) {
663
876
  if (invalid.length)
664
877
  throw new EdgeRuntimeError(`${name} contains unsupported values: ${invalid.join(", ")}`);
665
878
  }
879
+ function normalizeToolChoice(value) {
880
+ const choice = String(value ?? "auto").trim().toLowerCase();
881
+ if (choice !== "auto" && choice !== "required" && choice !== "none") {
882
+ throw new EdgeRuntimeError("toolChoice must be one of: auto, required, none");
883
+ }
884
+ return choice;
885
+ }
666
886
  function inputModalities(input) {
667
887
  if (typeof input === "string")
668
888
  return new Set(["text"]);
@@ -1346,6 +1566,7 @@ class RealtimeSessionRequest {
1346
1566
  voice;
1347
1567
  instructions;
1348
1568
  outputModalities;
1569
+ transport;
1349
1570
  clientCapabilities;
1350
1571
  metadata;
1351
1572
  constructor(input = {}) {
@@ -1357,6 +1578,7 @@ class RealtimeSessionRequest {
1357
1578
  this.voice = cleanString(input.voice);
1358
1579
  this.instructions = cleanString(input.instructions);
1359
1580
  this.outputModalities = input.outputModalities ?? input.output_modalities ?? ["audio"];
1581
+ this.transport = input.transport ?? "websocket";
1360
1582
  this.clientCapabilities = input.clientCapabilities ?? input.client_capabilities;
1361
1583
  this.metadata = input.metadata ?? {};
1362
1584
  }
@@ -1373,6 +1595,7 @@ class RealtimeSessionRequest {
1373
1595
  voice: this.voice,
1374
1596
  instructions: this.instructions,
1375
1597
  output_modalities: this.outputModalities,
1598
+ transport: this.transport,
1376
1599
  client_capabilities: normalizeCapabilities(this.clientCapabilities),
1377
1600
  metadata: this.metadata,
1378
1601
  });
@@ -1669,13 +1892,26 @@ class ResponsesClient {
1669
1892
  this.runtime = runtime;
1670
1893
  }
1671
1894
  async create(options) {
1895
+ const toolChoice = normalizeToolChoice(options.toolChoice);
1896
+ if (toolChoice === "required" && !options.tools) {
1897
+ throw new EdgeRuntimeError("toolChoice='required' needs a Hub connection.");
1898
+ }
1672
1899
  const tools = options.tools
1673
1900
  ? normalizeConnectedTools(options.tools.descriptors())
1674
1901
  : [];
1902
+ const metadata = {
1903
+ ...(options.metadata ?? {}),
1904
+ marona_agent: {
1905
+ ...(asRecord(options.metadata?.marona_agent) ?? {}),
1906
+ tool_choice: toolChoice,
1907
+ tools_enabled: Boolean(options.tools) && toolChoice !== "none",
1908
+ },
1909
+ };
1675
1910
  return this.runtime.client({
1676
1911
  ...options,
1677
1912
  model: options.model ?? "marona/gpt-5.6",
1678
- tools,
1913
+ metadata,
1914
+ tools: toolChoice === "none" ? [] : tools,
1679
1915
  });
1680
1916
  }
1681
1917
  }
@@ -1906,16 +2142,19 @@ class RuntimeEngine extends RuntimeTransport {
1906
2142
  });
1907
2143
  messages.push({ role: "user", content: modelUserContent(text, options.attachments ?? []) });
1908
2144
  const capabilityCatalog = this.localCapabilityCatalog();
2145
+ const requestedToolChoice = normalizeToolChoice(asRecord(options.metadata?.marona_agent)?.tool_choice);
1909
2146
  let availableTools = options.tools?.length
1910
2147
  ? normalizeConnectedTools(options.tools)
1911
2148
  : capabilitySelectorTools(capabilityCatalog);
2149
+ if (requestedToolChoice === "none")
2150
+ availableTools = [];
1912
2151
  let payload = {};
1913
2152
  let reply = "";
1914
2153
  const toolResults = [];
1915
2154
  const modelResponses = [];
1916
2155
  const runtimeSteps = [];
1917
2156
  const executedCapabilityCalls = new Map();
1918
- let toolChoice = "auto";
2157
+ let toolChoice = availableTools.length ? requestedToolChoice : "none";
1919
2158
  let contextTier = model.contextWindow !== undefined && model.contextWindow <= 2048
1920
2159
  ? 2
1921
2160
  : model.contextWindow !== undefined && model.contextWindow <= 4096