marona 0.8.7 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const packageVersion = "0.8.7";
1
+ export const packageVersion = "0.9.0";
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,50 +461,116 @@ 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
+ return runtime.createRealtimeSession({
561
+ model: agent.model,
495
562
  userId,
496
- sessionId,
497
- };
563
+ conversationId,
564
+ mode: inputs.has("image") || inputs.has("video") ? "voice_vision" : "voice",
565
+ voice: cleanString(agent.voice?.output_voice),
566
+ instructions: agent.instructions || undefined,
567
+ outputModalities: agent.outputModalities ?? ["audio"],
568
+ metadata: {
569
+ voice: agent.voice ?? {},
570
+ routing: agent.routing ?? {},
571
+ required_transport: "realtime",
572
+ },
573
+ });
498
574
  }
499
575
  }
500
576
  function developerIdForAgent(tools) {
@@ -506,6 +582,57 @@ function developerIdForAgent(tools) {
506
582
  }
507
583
  return developerId;
508
584
  }
585
+ function validateModalities(name, values) {
586
+ if (!values)
587
+ return;
588
+ const invalid = values.filter((value) => !supportedModalities.has(value));
589
+ if (invalid.length)
590
+ throw new EdgeRuntimeError(`${name} contains unsupported values: ${invalid.join(", ")}`);
591
+ }
592
+ function inputModalities(input) {
593
+ if (typeof input === "string")
594
+ return new Set(["text"]);
595
+ const result = new Set();
596
+ const messages = Array.isArray(input) ? input : [input];
597
+ for (const message of messages) {
598
+ if (!isPlainObject(message))
599
+ continue;
600
+ if (typeof message.content === "string") {
601
+ result.add("text");
602
+ continue;
603
+ }
604
+ if (!Array.isArray(message.content))
605
+ continue;
606
+ for (const block of message.content) {
607
+ if (!isPlainObject(block))
608
+ continue;
609
+ const type = stringValue(block.type);
610
+ if (type?.startsWith("input_"))
611
+ result.add(type.slice(6));
612
+ }
613
+ }
614
+ return result;
615
+ }
616
+ function normalizeAgentOutputRequest(agent, output) {
617
+ const modalities = output?.modalities ?? ["text"];
618
+ validateModalities("output.modalities", modalities);
619
+ const allowed = new Set(agent.outputModalities ?? [...supportedModalities]);
620
+ const unsupported = modalities.filter((value) => !allowed.has(value));
621
+ if (unsupported.length)
622
+ throw new EdgeRuntimeError(`Agent output does not allow: ${unsupported.join(", ")}`);
623
+ return { ...(output ?? {}), modalities: [...new Set(modalities)] };
624
+ }
625
+ function raiseAgentInterruption(response) {
626
+ if (response.needsServiceConnection) {
627
+ throw new MaronaServiceConnectionRequired(response.reply, { payload: response.serviceConnection?.rawJson ?? response.rawJson });
628
+ }
629
+ if (response.needsPermission) {
630
+ throw new MaronaPermissionRequired(response.reply, { payload: response.permissionRequest });
631
+ }
632
+ if (response.status === "planned") {
633
+ throw new MaronaApprovalRequired(response.reply, { payload: response.toolCall ?? response.rawJson });
634
+ }
635
+ }
509
636
  class HubClient {
510
637
  baseUrl;
511
638
  defaultHeaders;
@@ -910,6 +1037,12 @@ function runtimeMessageFromInput(input) {
910
1037
  if (attachment)
911
1038
  attachments.push(attachment);
912
1039
  }
1040
+ else if (blockType === "input_audio") {
1041
+ attachments.push(attachmentFromMediaBlock(block, index + 1, "audio"));
1042
+ }
1043
+ else if (blockType === "input_video") {
1044
+ attachments.push(attachmentFromMediaBlock(block, index + 1, "video"));
1045
+ }
913
1046
  });
914
1047
  }
915
1048
  const text = textParts.join("\n").trim();
@@ -982,6 +1115,34 @@ function attachmentFromFileBlock(block, index) {
982
1115
  metadata: inputBlockMetadata(block),
983
1116
  });
984
1117
  }
1118
+ function attachmentFromMediaBlock(block, index, kind) {
1119
+ const candidates = [
1120
+ [`${kind}_url`, cleanString(block[`${kind}_url`])],
1121
+ [`${kind}_data`, cleanString(block[`${kind}_data`])],
1122
+ ["file_id", cleanString(block.file_id)],
1123
+ ["path", cleanString(block.path)],
1124
+ ];
1125
+ const supplied = candidates.filter((entry) => Boolean(entry[1]));
1126
+ if (supplied.length !== 1) {
1127
+ throw new EdgeRuntimeError(`input_${kind} requires exactly one source: ${kind}_url, ${kind}_data, file_id, path`);
1128
+ }
1129
+ const [source, value] = supplied[0];
1130
+ const data = dataUriParts(value);
1131
+ const url = source.endsWith("_url") ? value : undefined;
1132
+ const filename = cleanString(block.filename) ?? filenameFromUrl(url) ?? `${kind}-${index}`;
1133
+ return new RuntimeAttachment({
1134
+ filename,
1135
+ mimeType: data.mimeType ?? cleanString(block.mime_type) ?? guessInputMimeType(filename, `${kind}/*`),
1136
+ kind,
1137
+ dataBase64: source.endsWith("_data") ? data.dataBase64 ?? value : undefined,
1138
+ url,
1139
+ metadata: {
1140
+ ...inputBlockMetadata(block),
1141
+ ...(source === "file_id" ? { file_id: value } : {}),
1142
+ ...(source === "path" ? { path: value } : {}),
1143
+ },
1144
+ });
1145
+ }
985
1146
  function inputBlockMetadata(block) {
986
1147
  const detail = cleanString(block.detail);
987
1148
  return detail ? { detail } : {};
@@ -1067,6 +1228,7 @@ class RuntimeMessageRequest {
1067
1228
  clientCapabilities;
1068
1229
  metadata;
1069
1230
  routing;
1231
+ output;
1070
1232
  constructor(text, options = {}) {
1071
1233
  this.text = text;
1072
1234
  this.model = cleanString(options.model);
@@ -1079,6 +1241,7 @@ class RuntimeMessageRequest {
1079
1241
  this.clientCapabilities = options.clientCapabilities ?? options.client_capabilities;
1080
1242
  this.metadata = options.metadata ?? {};
1081
1243
  this.routing = options.routing;
1244
+ this.output = options.output;
1082
1245
  }
1083
1246
  toJSON() {
1084
1247
  return this.toJson();
@@ -1096,6 +1259,7 @@ class RuntimeMessageRequest {
1096
1259
  client_capabilities: normalizeCapabilities(this.clientCapabilities),
1097
1260
  metadata: this.metadata,
1098
1261
  routing: normalizeRouting(this.routing),
1262
+ output: this.output,
1099
1263
  });
1100
1264
  }
1101
1265
  }
@@ -1730,7 +1894,7 @@ class RuntimeEngine extends RuntimeTransport {
1730
1894
  result: {
1731
1895
  status: "already_executed",
1732
1896
  message: "This exact capability call already ran in the current request. Use its existing result to answer the user.",
1733
- previous_result: toolResultForModel(previousResult),
1897
+ previous_result: toolResultForModel(previousResult, contextTier),
1734
1898
  },
1735
1899
  };
1736
1900
  runtimeSteps.push(repeatedResult);
@@ -1763,7 +1927,7 @@ class RuntimeEngine extends RuntimeTransport {
1763
1927
  }
1764
1928
  messages.push({
1765
1929
  role: "system",
1766
- content: `Marona Runtime results from the previous model-selected calls:\n${JSON.stringify(roundResults.map(toolResultForModel))}\n` +
1930
+ content: `Marona Runtime results from the previous model-selected calls:\n${JSON.stringify(roundResults.map((result) => toolResultForModel(result, contextTier)))}\n` +
1767
1931
  "Use these results to continue the current request. Preserve factual values, counts, currencies, and units exactly as returned. Call one of the currently available functions when more app data or action is required; otherwise answer the user directly.",
1768
1932
  });
1769
1933
  }
@@ -1776,7 +1940,6 @@ class RuntimeEngine extends RuntimeTransport {
1776
1940
  reply: reply || "Done.",
1777
1941
  text: reply || "Done.",
1778
1942
  output: runtimeOutput(reply || "Done.", artifacts),
1779
- outputText: reply || "Done.",
1780
1943
  interfaceName: options.interfaceName ?? options.interface ?? "api",
1781
1944
  conversationId: options.conversationId ?? options.conversation_id,
1782
1945
  artifacts,
@@ -2015,6 +2178,7 @@ export class Marona {
2015
2178
  this.responses = new ResponsesClient(this.runtime);
2016
2179
  this.models = new Models(this.runtime.models);
2017
2180
  this.skills = this.runtime.skills;
2181
+ activeRuntime = this.runtime;
2018
2182
  }
2019
2183
  }
2020
2184
  function parseRuntimeMessageResponse(payload) {
@@ -2031,7 +2195,6 @@ function parseRuntimeMessageResponse(payload) {
2031
2195
  reply,
2032
2196
  text: reply,
2033
2197
  output: runtimeOutput(reply, artifacts, payload.output),
2034
- outputText: reply,
2035
2198
  interfaceName: stringValue(payload.interface) || "api",
2036
2199
  conversationId: stringValue(payload.conversation_id),
2037
2200
  ui: ui ? parseRuntimeUI(ui) : undefined,
@@ -2126,14 +2289,30 @@ function titleCase(value) {
2126
2289
  return value.replace(/\b\w/g, (letter) => letter.toUpperCase());
2127
2290
  }
2128
2291
  function runtimeOutput(reply, artifacts, supplied) {
2129
- const provided = listOfRecords(supplied);
2130
- if (Array.isArray(supplied))
2131
- return provided;
2292
+ if (Array.isArray(supplied)) {
2293
+ return listOfRecords(supplied).map(normalizeOutputPart).filter(Boolean);
2294
+ }
2295
+ if (!artifacts.length)
2296
+ return reply;
2132
2297
  return [
2133
- ...(reply ? [{ type: "text", text: reply }] : []),
2134
- ...artifacts.map((artifact) => ({ ...artifact })),
2298
+ ...(reply ? [{ type: "output_text", text: reply }] : []),
2299
+ ...artifacts.map(normalizeOutputPart).filter(Boolean),
2135
2300
  ];
2136
2301
  }
2302
+ function normalizeOutputPart(value) {
2303
+ const type = stringValue(value.type ?? value.kind)?.toLowerCase();
2304
+ if (["text", "output_text"].includes(type ?? ""))
2305
+ return { ...value, type: "output_text" };
2306
+ if (["image", "output_image"].includes(type ?? ""))
2307
+ return { ...value, type: "output_image", image_url: value.image_url ?? value.url };
2308
+ if (["audio", "output_audio"].includes(type ?? ""))
2309
+ return { ...value, type: "output_audio", audio_url: value.audio_url ?? value.url };
2310
+ if (["video", "output_video"].includes(type ?? ""))
2311
+ return { ...value, type: "output_video", video_url: value.video_url ?? value.url };
2312
+ if (["file", "document", "pdf", "download", "output_file"].includes(type ?? ""))
2313
+ return { ...value, type: "output_file", file_url: value.file_url ?? value.url };
2314
+ return undefined;
2315
+ }
2137
2316
  function conversationKey(conversationId) {
2138
2317
  const cleaned = conversationId?.trim();
2139
2318
  return cleaned || "default";
@@ -2465,11 +2644,34 @@ function modelToolCalls(payload) {
2465
2644
  const calls = Array.isArray(message?.tool_calls) ? message.tool_calls : [];
2466
2645
  return calls.map(asRecord).filter(Boolean);
2467
2646
  }
2468
- function toolResultForModel(result) {
2469
- if (Object.prototype.hasOwnProperty.call(result, "result")) {
2470
- return compactToolValue(result.result);
2647
+ function toolResultForModel(result, contextTier = 0) {
2648
+ const value = Object.prototype.hasOwnProperty.call(result, "result")
2649
+ ? result.result
2650
+ : { error: result.error ?? "" };
2651
+ const compact = compactToolValue(value);
2652
+ if (contextTier < 2)
2653
+ return compact;
2654
+ return limitContextToolValue(compact, 3, contextTier >= 3 ? 1_000 : 2_000);
2655
+ }
2656
+ function limitContextToolValue(value, maxItems, maxChars) {
2657
+ if (typeof value === "string") {
2658
+ return value.length <= maxChars
2659
+ ? value
2660
+ : `${value.slice(0, maxChars)}\n...[truncated]`;
2471
2661
  }
2472
- return { error: compactToolValue(result.error ?? "") };
2662
+ if (Array.isArray(value)) {
2663
+ return value
2664
+ .slice(0, maxItems)
2665
+ .map((item) => limitContextToolValue(item, maxItems, maxChars));
2666
+ }
2667
+ const record = asRecord(value);
2668
+ if (record) {
2669
+ return Object.fromEntries(Object.entries(record).map(([key, item]) => [
2670
+ key,
2671
+ limitContextToolValue(item, maxItems, maxChars),
2672
+ ]));
2673
+ }
2674
+ return value;
2473
2675
  }
2474
2676
  function toolResultDisplayText(result) {
2475
2677
  const value = asRecord(result.result) ?? result;