marona 0.8.8 → 0.9.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,4 @@
1
- export const packageVersion = "0.8.8";
1
+ export const packageVersion = "0.9.1";
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"];
@@ -88,6 +88,12 @@ export class MaronaModelError extends EdgeRuntimeError {
88
88
  this.name = "MaronaModelError";
89
89
  }
90
90
  }
91
+ export class MaronaApprovalRequired extends EdgeRuntimeError {
92
+ }
93
+ export class MaronaPermissionRequired extends EdgeRuntimeError {
94
+ }
95
+ export class MaronaServiceConnectionRequired extends EdgeRuntimeError {
96
+ }
91
97
  class MaronaCache {
92
98
  syncPayload;
93
99
  privateContext;
@@ -373,6 +379,10 @@ export class MCPConnection {
373
379
  this.payload = payload;
374
380
  this.executor = executor;
375
381
  }
382
+ /** @internal */
383
+ agentRuntime() {
384
+ return this.executor?.runtime;
385
+ }
376
386
  listTools() {
377
387
  return normalizeConnectedTools(this.descriptors()).map((descriptor) => {
378
388
  const fn = asRecord(descriptor.function) ?? {};
@@ -451,52 +461,192 @@ export class MCPConnection {
451
461
  return runtime.client(options);
452
462
  }
453
463
  }
464
+ let activeRuntime;
465
+ const supportedModalities = new Set(["text", "image", "audio", "video", "file"]);
454
466
  export class Agent {
455
467
  name;
456
468
  model;
457
469
  instructions;
458
470
  tools;
471
+ voice;
472
+ modalities;
473
+ outputModalities;
459
474
  routing;
475
+ /** @internal */ runtime;
460
476
  constructor(options) {
461
477
  this.name = options.name.trim();
462
- this.model = (options.model ?? "marona/gpt-5.6").trim();
478
+ this.model = (options.model ?? "marona/auto").trim();
463
479
  this.instructions = (options.instructions ?? "").trim();
464
480
  this.tools = options.tools;
481
+ this.voice = options.voice;
482
+ this.modalities = options.modalities;
483
+ this.outputModalities = options.outputModalities ?? options.output_modalities;
465
484
  this.routing = options.routing;
485
+ this.runtime = activeRuntime;
466
486
  if (!this.name)
467
487
  throw new EdgeRuntimeError("Agent name cannot be empty.");
468
488
  if (!this.model)
469
489
  throw new EdgeRuntimeError("Agent model cannot be empty.");
470
- if (!(this.tools instanceof MCPConnection)) {
490
+ if (this.tools !== undefined && !(this.tools instanceof MCPConnection)) {
471
491
  throw new EdgeRuntimeError("Agent tools must be a Marona Hub connection.");
472
492
  }
493
+ validateModalities("modalities", this.modalities);
494
+ validateModalities("outputModalities", this.outputModalities);
473
495
  }
474
496
  }
475
497
  export class Runner {
476
498
  static async run(agent, input, options = {}) {
477
- const developerId = developerIdForAgent(agent.tools);
499
+ const runtime = agent.tools?.agentRuntime() ?? agent.runtime ?? activeRuntime;
500
+ if (!runtime)
501
+ throw new EdgeRuntimeError("Create Marona before running an Agent without tools.");
502
+ const developerId = agent.tools ? developerIdForAgent(agent.tools) : "authenticated";
478
503
  const userId = cleanString(options.userId);
479
504
  const sessionId = cleanString(options.sessionId) ?? "default";
480
505
  const conversationId = [developerId, userId ?? "anonymous", sessionId]
481
506
  .map((value) => encodeURIComponent(value))
482
507
  .join(":");
483
- const response = await agent.tools.runAgent({
508
+ const output = normalizeAgentOutputRequest(agent, options.output);
509
+ const inputs = inputModalities(input);
510
+ const allowedInputs = new Set(agent.modalities ?? [...supportedModalities]);
511
+ const unsupportedInputs = [...inputs].filter((value) => !allowedInputs.has(value));
512
+ if (unsupportedInputs.length) {
513
+ throw new EdgeRuntimeError(`Agent input does not allow: ${unsupportedInputs.join(", ")}`);
514
+ }
515
+ const response = await runtime.client({
484
516
  model: agent.model,
485
517
  input,
486
518
  userId,
487
519
  conversationId,
488
520
  developerInstructions: agent.instructions || undefined,
489
- tools: agent.tools.descriptors(),
521
+ tools: agent.tools?.descriptors() ?? [],
490
522
  routing: agent.routing,
523
+ output,
524
+ metadata: {
525
+ marona_agent: {
526
+ input_modalities: [...inputs],
527
+ allowed_output_modalities: agent.outputModalities ?? [...supportedModalities],
528
+ output_modalities: output.modalities,
529
+ tools_enabled: Boolean(agent.tools),
530
+ voice: agent.voice ?? {},
531
+ },
532
+ },
491
533
  });
492
- return {
493
- finalOutput: response.outputText,
494
- response,
534
+ raiseAgentInterruption(response);
535
+ return { output: response.output };
536
+ }
537
+ static async *stream(agent, input, options = {}) {
538
+ yield { type: "run.started" };
539
+ const result = await Runner.run(agent, input, options);
540
+ if (typeof result.output === "string") {
541
+ yield { type: "output_text.delta", delta: result.output };
542
+ }
543
+ yield { type: "run.completed", output: result.output };
544
+ }
545
+ }
546
+ export class RealtimeRunner {
547
+ static async connect(agent, options = {}) {
548
+ return RealtimeRunner.createClientSession(agent, options);
549
+ }
550
+ static async createClientSession(agent, options = {}) {
551
+ const runtime = agent.tools?.agentRuntime() ?? agent.runtime ?? activeRuntime;
552
+ if (!runtime)
553
+ throw new EdgeRuntimeError("Create Marona before creating a realtime session.");
554
+ const developerId = agent.tools ? developerIdForAgent(agent.tools) : "authenticated";
555
+ const userId = cleanString(options.userId);
556
+ const sessionId = cleanString(options.sessionId) ?? "default";
557
+ const conversationId = [developerId, userId ?? "anonymous", sessionId]
558
+ .map((value) => encodeURIComponent(value)).join(":");
559
+ const inputs = new Set(agent.modalities ?? ["text", "audio"]);
560
+ const outputModalities = agent.outputModalities ?? ["audio"];
561
+ const unsupportedOutput = outputModalities.filter((value) => !["text", "audio"].includes(value));
562
+ if (unsupportedOutput.length) {
563
+ throw new EdgeRuntimeError(`Realtime output does not allow: ${unsupportedOutput.join(", ")}`);
564
+ }
565
+ return runtime.createRealtimeSession({
566
+ model: agent.model,
495
567
  userId,
496
- sessionId,
568
+ conversationId,
569
+ mode: inputs.has("image") || inputs.has("video") ? "voice_vision" : "voice",
570
+ voice: cleanString(agent.voice?.output_voice),
571
+ instructions: agent.instructions || undefined,
572
+ outputModalities,
573
+ metadata: {
574
+ voice: agent.voice ?? {},
575
+ routing: agent.routing ?? {},
576
+ required_transport: "realtime",
577
+ marona_agent: {
578
+ input_modalities: [...inputs],
579
+ output_modalities: outputModalities,
580
+ tools_enabled: Boolean(agent.tools),
581
+ },
582
+ },
583
+ });
584
+ }
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}'.`);
615
+ }
616
+ static async handleEvent(agent, event, options = {}) {
617
+ if (event.type !== "tool_call") {
618
+ throw new EdgeRuntimeError("RealtimeRunner supports neutral tool_call events.");
619
+ }
620
+ const output = await RealtimeRunner.handleToolCall(agent, cleanString(event.name) ?? "", asRecord(event.arguments) ?? {}, options);
621
+ return {
622
+ type: "tool_result",
623
+ call_id: cleanString(event.call_id) ?? "",
624
+ output,
497
625
  };
498
626
  }
499
627
  }
628
+ function realtimeCapabilities(tools, query, limit = 12) {
629
+ const terms = new Set(query.toLowerCase().replaceAll("-", " ").split(/\s+/)
630
+ .map((part) => part.replace(/[^a-z0-9_]/g, ""))
631
+ .filter((part) => part.length > 1));
632
+ return tools.map((tool) => {
633
+ const name = tool.name ?? "";
634
+ const haystack = `${name.replaceAll("__", " ")} ${tool.description}`.toLowerCase();
635
+ let score = 0;
636
+ for (const term of terms) {
637
+ if (haystack.includes(term))
638
+ score += name.toLowerCase().includes(term) ? 3 : 1;
639
+ }
640
+ return { score, tool };
641
+ }).filter(({ score }) => score > 0)
642
+ .sort((left, right) => right.score - left.score || left.tool.name.localeCompare(right.tool.name))
643
+ .slice(0, limit)
644
+ .map(({ tool }) => ({
645
+ name: tool.name,
646
+ description: tool.description,
647
+ inputSchema: tool.inputSchema,
648
+ }));
649
+ }
500
650
  function developerIdForAgent(tools) {
501
651
  const developerContext = asRecord(tools.session.developer_context);
502
652
  const workspace = asRecord(developerContext?.workspace);
@@ -506,6 +656,57 @@ function developerIdForAgent(tools) {
506
656
  }
507
657
  return developerId;
508
658
  }
659
+ function validateModalities(name, values) {
660
+ if (!values)
661
+ return;
662
+ const invalid = values.filter((value) => !supportedModalities.has(value));
663
+ if (invalid.length)
664
+ throw new EdgeRuntimeError(`${name} contains unsupported values: ${invalid.join(", ")}`);
665
+ }
666
+ function inputModalities(input) {
667
+ if (typeof input === "string")
668
+ return new Set(["text"]);
669
+ const result = new Set();
670
+ const messages = Array.isArray(input) ? input : [input];
671
+ for (const message of messages) {
672
+ if (!isPlainObject(message))
673
+ continue;
674
+ if (typeof message.content === "string") {
675
+ result.add("text");
676
+ continue;
677
+ }
678
+ if (!Array.isArray(message.content))
679
+ continue;
680
+ for (const block of message.content) {
681
+ if (!isPlainObject(block))
682
+ continue;
683
+ const type = stringValue(block.type);
684
+ if (type?.startsWith("input_"))
685
+ result.add(type.slice(6));
686
+ }
687
+ }
688
+ return result;
689
+ }
690
+ function normalizeAgentOutputRequest(agent, output) {
691
+ const modalities = output?.modalities ?? ["text"];
692
+ validateModalities("output.modalities", modalities);
693
+ const allowed = new Set(agent.outputModalities ?? [...supportedModalities]);
694
+ const unsupported = modalities.filter((value) => !allowed.has(value));
695
+ if (unsupported.length)
696
+ throw new EdgeRuntimeError(`Agent output does not allow: ${unsupported.join(", ")}`);
697
+ return { ...(output ?? {}), modalities: [...new Set(modalities)] };
698
+ }
699
+ function raiseAgentInterruption(response) {
700
+ if (response.needsServiceConnection) {
701
+ throw new MaronaServiceConnectionRequired(response.reply, { payload: response.serviceConnection?.rawJson ?? response.rawJson });
702
+ }
703
+ if (response.needsPermission) {
704
+ throw new MaronaPermissionRequired(response.reply, { payload: response.permissionRequest });
705
+ }
706
+ if (response.status === "planned") {
707
+ throw new MaronaApprovalRequired(response.reply, { payload: response.toolCall ?? response.rawJson });
708
+ }
709
+ }
509
710
  class HubClient {
510
711
  baseUrl;
511
712
  defaultHeaders;
@@ -910,6 +1111,12 @@ function runtimeMessageFromInput(input) {
910
1111
  if (attachment)
911
1112
  attachments.push(attachment);
912
1113
  }
1114
+ else if (blockType === "input_audio") {
1115
+ attachments.push(attachmentFromMediaBlock(block, index + 1, "audio"));
1116
+ }
1117
+ else if (blockType === "input_video") {
1118
+ attachments.push(attachmentFromMediaBlock(block, index + 1, "video"));
1119
+ }
913
1120
  });
914
1121
  }
915
1122
  const text = textParts.join("\n").trim();
@@ -982,6 +1189,34 @@ function attachmentFromFileBlock(block, index) {
982
1189
  metadata: inputBlockMetadata(block),
983
1190
  });
984
1191
  }
1192
+ function attachmentFromMediaBlock(block, index, kind) {
1193
+ const candidates = [
1194
+ [`${kind}_url`, cleanString(block[`${kind}_url`])],
1195
+ [`${kind}_data`, cleanString(block[`${kind}_data`])],
1196
+ ["file_id", cleanString(block.file_id)],
1197
+ ["path", cleanString(block.path)],
1198
+ ];
1199
+ const supplied = candidates.filter((entry) => Boolean(entry[1]));
1200
+ if (supplied.length !== 1) {
1201
+ throw new EdgeRuntimeError(`input_${kind} requires exactly one source: ${kind}_url, ${kind}_data, file_id, path`);
1202
+ }
1203
+ const [source, value] = supplied[0];
1204
+ const data = dataUriParts(value);
1205
+ const url = source.endsWith("_url") ? value : undefined;
1206
+ const filename = cleanString(block.filename) ?? filenameFromUrl(url) ?? `${kind}-${index}`;
1207
+ return new RuntimeAttachment({
1208
+ filename,
1209
+ mimeType: data.mimeType ?? cleanString(block.mime_type) ?? guessInputMimeType(filename, `${kind}/*`),
1210
+ kind,
1211
+ dataBase64: source.endsWith("_data") ? data.dataBase64 ?? value : undefined,
1212
+ url,
1213
+ metadata: {
1214
+ ...inputBlockMetadata(block),
1215
+ ...(source === "file_id" ? { file_id: value } : {}),
1216
+ ...(source === "path" ? { path: value } : {}),
1217
+ },
1218
+ });
1219
+ }
985
1220
  function inputBlockMetadata(block) {
986
1221
  const detail = cleanString(block.detail);
987
1222
  return detail ? { detail } : {};
@@ -1067,6 +1302,7 @@ class RuntimeMessageRequest {
1067
1302
  clientCapabilities;
1068
1303
  metadata;
1069
1304
  routing;
1305
+ output;
1070
1306
  constructor(text, options = {}) {
1071
1307
  this.text = text;
1072
1308
  this.model = cleanString(options.model);
@@ -1079,6 +1315,7 @@ class RuntimeMessageRequest {
1079
1315
  this.clientCapabilities = options.clientCapabilities ?? options.client_capabilities;
1080
1316
  this.metadata = options.metadata ?? {};
1081
1317
  this.routing = options.routing;
1318
+ this.output = options.output;
1082
1319
  }
1083
1320
  toJSON() {
1084
1321
  return this.toJson();
@@ -1096,6 +1333,7 @@ class RuntimeMessageRequest {
1096
1333
  client_capabilities: normalizeCapabilities(this.clientCapabilities),
1097
1334
  metadata: this.metadata,
1098
1335
  routing: normalizeRouting(this.routing),
1336
+ output: this.output,
1099
1337
  });
1100
1338
  }
1101
1339
  }
@@ -1776,7 +2014,6 @@ class RuntimeEngine extends RuntimeTransport {
1776
2014
  reply: reply || "Done.",
1777
2015
  text: reply || "Done.",
1778
2016
  output: runtimeOutput(reply || "Done.", artifacts),
1779
- outputText: reply || "Done.",
1780
2017
  interfaceName: options.interfaceName ?? options.interface ?? "api",
1781
2018
  conversationId: options.conversationId ?? options.conversation_id,
1782
2019
  artifacts,
@@ -2015,6 +2252,7 @@ export class Marona {
2015
2252
  this.responses = new ResponsesClient(this.runtime);
2016
2253
  this.models = new Models(this.runtime.models);
2017
2254
  this.skills = this.runtime.skills;
2255
+ activeRuntime = this.runtime;
2018
2256
  }
2019
2257
  }
2020
2258
  function parseRuntimeMessageResponse(payload) {
@@ -2031,7 +2269,6 @@ function parseRuntimeMessageResponse(payload) {
2031
2269
  reply,
2032
2270
  text: reply,
2033
2271
  output: runtimeOutput(reply, artifacts, payload.output),
2034
- outputText: reply,
2035
2272
  interfaceName: stringValue(payload.interface) || "api",
2036
2273
  conversationId: stringValue(payload.conversation_id),
2037
2274
  ui: ui ? parseRuntimeUI(ui) : undefined,
@@ -2126,14 +2363,30 @@ function titleCase(value) {
2126
2363
  return value.replace(/\b\w/g, (letter) => letter.toUpperCase());
2127
2364
  }
2128
2365
  function runtimeOutput(reply, artifacts, supplied) {
2129
- const provided = listOfRecords(supplied);
2130
- if (Array.isArray(supplied))
2131
- return provided;
2366
+ if (Array.isArray(supplied)) {
2367
+ return listOfRecords(supplied).map(normalizeOutputPart).filter(Boolean);
2368
+ }
2369
+ if (!artifacts.length)
2370
+ return reply;
2132
2371
  return [
2133
- ...(reply ? [{ type: "text", text: reply }] : []),
2134
- ...artifacts.map((artifact) => ({ ...artifact })),
2372
+ ...(reply ? [{ type: "output_text", text: reply }] : []),
2373
+ ...artifacts.map(normalizeOutputPart).filter(Boolean),
2135
2374
  ];
2136
2375
  }
2376
+ function normalizeOutputPart(value) {
2377
+ const type = stringValue(value.type ?? value.kind)?.toLowerCase();
2378
+ if (["text", "output_text"].includes(type ?? ""))
2379
+ return { ...value, type: "output_text" };
2380
+ if (["image", "output_image"].includes(type ?? ""))
2381
+ return { ...value, type: "output_image", image_url: value.image_url ?? value.url };
2382
+ if (["audio", "output_audio"].includes(type ?? ""))
2383
+ return { ...value, type: "output_audio", audio_url: value.audio_url ?? value.url };
2384
+ if (["video", "output_video"].includes(type ?? ""))
2385
+ return { ...value, type: "output_video", video_url: value.video_url ?? value.url };
2386
+ if (["file", "document", "pdf", "download", "output_file"].includes(type ?? ""))
2387
+ return { ...value, type: "output_file", file_url: value.file_url ?? value.url };
2388
+ return undefined;
2389
+ }
2137
2390
  function conversationKey(conversationId) {
2138
2391
  const cleaned = conversationId?.trim();
2139
2392
  return cleaned || "default";