marona 0.12.2 → 0.13.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.12.2";
1
+ export const packageVersion = "0.13.1";
2
2
  const discoverCapabilitiesTool = "marona__discover_capabilities";
3
3
  const callCapabilityTool = "marona__call_capability";
4
4
  const standardInterfaces = ["api", "web", "mobile_app", "desktop", "whatsapp"];
@@ -493,10 +493,14 @@ export class MCPConnection {
493
493
  payload;
494
494
  executor;
495
495
  gatewayEnabled;
496
- constructor(payload, executor, gatewayEnabled = false) {
496
+ requestedApps;
497
+ requestedSkills;
498
+ constructor(payload, executor, gatewayEnabled = false, requestedApps, requestedSkills = []) {
497
499
  this.payload = payload;
498
500
  this.executor = executor;
499
501
  this.gatewayEnabled = gatewayEnabled;
502
+ this.requestedApps = requestedApps;
503
+ this.requestedSkills = requestedSkills;
500
504
  }
501
505
  /** @internal */
502
506
  agentRuntime() {
@@ -581,6 +585,14 @@ export class MCPConnection {
581
585
  server_urls: this.serverUrls,
582
586
  };
583
587
  }
588
+ /** @internal */
589
+ realtimeScope() {
590
+ return {
591
+ all_apps: this.gatewayEnabled,
592
+ apps: this.requestedApps ?? [],
593
+ skills: this.requestedSkills,
594
+ };
595
+ }
584
596
  descriptors() {
585
597
  return Array.isArray(this.payload.connections)
586
598
  ? this.payload.connections.map(asRecord).filter(Boolean)
@@ -1034,16 +1046,113 @@ export class Runner {
1034
1046
  }
1035
1047
  }
1036
1048
  static async *stream(agent, input, options = {}) {
1049
+ const userId = cleanString(options.userId);
1050
+ const sessionId = cleanString(options.sessionId) ?? "default";
1051
+ const context = agentContext(agent, userId, sessionId);
1052
+ await runGuardrails(agent, "input", context, input);
1053
+ await agent.hooks?.onStart?.(context, input);
1054
+ await resolveAgentPeers(agent);
1055
+ const graph = agentGraph(agent, context, options);
1056
+ const connection = agentConnection(agent);
1057
+ const runtime = connection?.agentRuntime() ?? agent.runtime ?? activeRuntime;
1058
+ if (!runtime)
1059
+ throw new EdgeRuntimeError("Create Marona before running an Agent without tools.");
1060
+ const developerId = connection ? developerIdForAgent(connection) : "authenticated";
1061
+ const conversationId = [developerId, userId ?? "anonymous", sessionId]
1062
+ .map((value) => encodeURIComponent(value))
1063
+ .join(":");
1064
+ const output = normalizeAgentOutputRequest(agent, options.output);
1065
+ const runtimeInput = agent.inputSchema ? JSON.stringify(input) : input;
1066
+ validateAgentSchema(agent.inputSchema, input, "input", agent.name);
1067
+ const inputs = inputModalities(runtimeInput);
1068
+ const unsupportedInputs = [...inputs].filter((value) => !new Set(agent.modalities ?? [...supportedModalities]).has(value));
1069
+ if (unsupportedInputs.length) {
1070
+ throw new EdgeRuntimeError(`Agent input does not allow: ${unsupportedInputs.join(", ")}`);
1071
+ }
1037
1072
  yield { type: "run.started" };
1038
- yield { type: "agent.started" };
1039
- const result = await Runner.run(agent, input, options);
1040
- for (const run of result.agentRuns.slice(1)) {
1041
- yield { type: `agent.${run.relationship}.completed`, output: undefined };
1073
+ yield { type: "agent.started", data: { agent_name: agent.name } };
1074
+ let response;
1075
+ try {
1076
+ for await (const event of new ResponsesClient(runtime).stream({
1077
+ model: agent.model,
1078
+ input: runtimeInput,
1079
+ userId,
1080
+ conversationId,
1081
+ developerInstructions: resolveAgentInstructions(agent, context) || undefined,
1082
+ tools: agentRuntimeTools(agent),
1083
+ routing: agent.routing,
1084
+ output,
1085
+ toolChoice: agent.toolChoice,
1086
+ metadata: {
1087
+ marona_agent: {
1088
+ input_modalities: [...inputs],
1089
+ allowed_output_modalities: agent.outputModalities ?? [...supportedModalities],
1090
+ output_modalities: output.modalities,
1091
+ tools_enabled: Boolean(agent.tools) && agent.toolChoice !== "none",
1092
+ voice: agent.voice ?? {},
1093
+ },
1094
+ marona_multi_agent: graph,
1095
+ marona_tool_context: {
1096
+ session_id: sessionId,
1097
+ developer_id: developerId,
1098
+ permissions: Array.isArray(agent.metadata.permissions) ? agent.metadata.permissions : [],
1099
+ approved_tools: Array.isArray(agent.metadata.approved_tools) ? agent.metadata.approved_tools : [],
1100
+ },
1101
+ },
1102
+ })) {
1103
+ if (event.type === "run.started")
1104
+ continue;
1105
+ if (event.type === "run.failed") {
1106
+ throw new EdgeRuntimeError(cleanString(asRecord(event.data)?.message) ?? "Agent stream failed.");
1107
+ }
1108
+ if (event.type === "run.completed") {
1109
+ const payload = asRecord(event.output);
1110
+ if (payload)
1111
+ response = parseRuntimeMessageResponse(payload);
1112
+ continue;
1113
+ }
1114
+ yield {
1115
+ type: String(event.type ?? "event"),
1116
+ delta: cleanString(event.delta),
1117
+ output: event.output,
1118
+ data: asRecord(event.data),
1119
+ };
1120
+ }
1121
+ if (!response)
1122
+ throw new EdgeRuntimeError("Agent stream completed without a final response.");
1123
+ raiseAgentInterruption(response);
1042
1124
  }
1043
- if (typeof result.output === "string") {
1044
- yield { type: "output_text.delta", delta: result.output };
1125
+ catch (error) {
1126
+ await agent.hooks?.onError?.(context, error);
1127
+ throw error;
1045
1128
  }
1046
- yield { type: "run.completed", output: result.output };
1129
+ const metadata = response.agent ?? asRecord(response.rawJson.agent) ?? {};
1130
+ const activeAgent = agentByName(agent, cleanString(metadata.active_agent) ?? agent.name);
1131
+ const lastAgent = agentByName(agent, cleanString(metadata.last_agent) ?? activeAgent.name);
1132
+ const parsedOutput = parseTypedOutput(activeAgent, response.output);
1133
+ const activeContext = agentContext(activeAgent, userId, sessionId);
1134
+ await runGuardrails(activeAgent, "output", activeContext, parsedOutput);
1135
+ const result = {
1136
+ output: parsedOutput,
1137
+ lastAgent,
1138
+ activeAgent,
1139
+ agentRuns: normalizeAgentRuns(metadata, agent),
1140
+ usage: asRecord(response.rawJson.usage) ?? {},
1141
+ routing: response.routing,
1142
+ traceId: cleanString(metadata.trace_id),
1143
+ };
1144
+ for (const run of result.agentRuns.slice(1)) {
1145
+ if (run.relationship === "delegation")
1146
+ await agent.hooks?.onToolCall?.(context, run);
1147
+ if (run.relationship === "handoff")
1148
+ await agent.hooks?.onHandoff?.(context, run);
1149
+ }
1150
+ await activeAgent.hooks?.onComplete?.(activeContext, result);
1151
+ yield {
1152
+ type: "run.completed",
1153
+ output: result.output,
1154
+ data: { usage: result.usage, routing: result.routing, trace_id: result.traceId },
1155
+ };
1047
1156
  }
1048
1157
  }
1049
1158
  export class RealtimeSession {
@@ -1057,6 +1166,8 @@ export class RealtimeSession {
1057
1166
  socket;
1058
1167
  events = [];
1059
1168
  waiters = [];
1169
+ selectorMap;
1170
+ initialTools;
1060
1171
  closed = false;
1061
1172
  constructor(descriptor, socket, agent, options) {
1062
1173
  this.descriptor = descriptor;
@@ -1067,6 +1178,10 @@ export class RealtimeSession {
1067
1178
  this.provider = descriptor.provider;
1068
1179
  this.model = descriptor.model;
1069
1180
  this.conversationId = descriptor.conversationId;
1181
+ this.selectorMap = asRecord(descriptor.capabilities.selector_map) ?? {};
1182
+ this.initialTools = Array.isArray(descriptor.capabilities.selector_tools)
1183
+ ? descriptor.capabilities.selector_tools.map(asRecord).filter(Boolean)
1184
+ : [];
1070
1185
  socket.addEventListener("message", (event) => {
1071
1186
  void this.handleProviderEvent(JSON.parse(String(event.data)));
1072
1187
  });
@@ -1120,10 +1235,12 @@ export class RealtimeSession {
1120
1235
  if (eventType === "response.done") {
1121
1236
  const calls = openAIRealtimeToolCalls(event);
1122
1237
  if (calls.length) {
1123
- let forceTool = false;
1238
+ const selectedTools = [];
1239
+ let usedHubTool = false;
1124
1240
  for (const call of calls) {
1125
1241
  let output;
1126
1242
  try {
1243
+ const selector = asRecord(this.selectorMap[call.name]);
1127
1244
  const delegated = agentToolByName(this.agent, call.name);
1128
1245
  const transfer = handoffByName(this.agent, call.name);
1129
1246
  if (delegated) {
@@ -1160,13 +1277,21 @@ export class RealtimeSession {
1160
1277
  }
1161
1278
  else {
1162
1279
  const localTool = functionToolByName(this.agent, call.name);
1280
+ if (!localTool && !selector)
1281
+ usedHubTool = true;
1163
1282
  output = localTool
1164
1283
  ? {
1165
1284
  status: "completed",
1166
1285
  tool_name: call.name,
1167
1286
  result: await localTool.invoke(call.arguments, toolContext(this.agent, this.userId, this.sessionId)),
1168
1287
  }
1169
- : await executeRealtimeGateway(this.agent, call.name, call.arguments, { userId: this.userId, sessionId: this.sessionId });
1288
+ : await executeRealtimeGateway(this.agent, call.name, call.arguments, { userId: this.userId, sessionId: this.sessionId }, selector);
1289
+ const discovered = Array.isArray(output._marona_tools)
1290
+ ? output._marona_tools.map(asRecord).filter(Boolean)
1291
+ : [];
1292
+ if (discovered.length)
1293
+ selectedTools.push(...discovered);
1294
+ delete output._marona_tools;
1170
1295
  }
1171
1296
  }
1172
1297
  catch (error) {
@@ -1180,15 +1305,17 @@ export class RealtimeSession {
1180
1305
  output: JSON.stringify(output),
1181
1306
  },
1182
1307
  });
1183
- forceTool ||= call.name === "marona__discover_capabilities";
1308
+ }
1309
+ if (selectedTools.length) {
1310
+ this.updateRuntimeTools(selectedTools, "required");
1311
+ }
1312
+ else if (usedHubTool && this.initialTools.length) {
1313
+ this.updateRuntimeTools(this.initialTools, "auto");
1184
1314
  }
1185
1315
  this.send({
1186
1316
  type: "response.create",
1187
1317
  response: {
1188
- instructions: forceTool
1189
- ? "Call marona__call_capability with one exact discovered capability and arguments matching its schema."
1190
- : "Answer naturally using the completed capability result.",
1191
- tool_choice: forceTool ? "required" : "auto",
1318
+ tool_choice: selectedTools.length ? "required" : "auto",
1192
1319
  },
1193
1320
  });
1194
1321
  return;
@@ -1223,6 +1350,16 @@ export class RealtimeSession {
1223
1350
  this.ensureOpen();
1224
1351
  this.socket.send(JSON.stringify(event));
1225
1352
  }
1353
+ updateRuntimeTools(tools, toolChoice) {
1354
+ this.send({
1355
+ type: "session.update",
1356
+ session: {
1357
+ type: "realtime",
1358
+ tools,
1359
+ tool_choice: tools.length ? toolChoice : "none",
1360
+ },
1361
+ });
1362
+ }
1226
1363
  ensureOpen() {
1227
1364
  if (this.closed || this.socket.readyState !== 1) {
1228
1365
  throw new EdgeRuntimeError("Realtime session is closed.");
@@ -1294,6 +1431,11 @@ export class RealtimeRunner {
1294
1431
  tools_enabled: agentHasTools(agent) && agent.toolChoice !== "none",
1295
1432
  tool_choice: agent.toolChoice,
1296
1433
  },
1434
+ marona_connection_scope: connection?.realtimeScope() ?? {
1435
+ all_apps: false,
1436
+ apps: [],
1437
+ skills: [],
1438
+ },
1297
1439
  marona_multi_agent: agentGraph(agent, agentContext(agent, userId, sessionId)),
1298
1440
  },
1299
1441
  });
@@ -1314,7 +1456,7 @@ async function openRealtimeSocket(descriptor) {
1314
1456
  });
1315
1457
  return socket;
1316
1458
  }
1317
- async function executeRealtimeGateway(agent, name, argumentsValue, options) {
1459
+ async function executeRealtimeGateway(agent, name, argumentsValue, options, selector) {
1318
1460
  const connection = agentConnection(agent);
1319
1461
  if (!connection)
1320
1462
  throw new EdgeRuntimeError("The realtime Agent has no Marona Hub tools connected.");
@@ -1322,20 +1464,55 @@ async function executeRealtimeGateway(agent, name, argumentsValue, options) {
1322
1464
  const sessionId = cleanString(options.sessionId) ?? "default";
1323
1465
  const conversationId = [developerIdForAgent(connection), userId ?? "anonymous", sessionId]
1324
1466
  .map((value) => encodeURIComponent(value)).join(":");
1325
- if (name === "marona__discover_capabilities") {
1326
- const query = cleanString(argumentsValue.request) ?? cleanString(argumentsValue.query);
1327
- if (!query)
1328
- throw new EdgeRuntimeError("Realtime capability discovery requires a request.");
1329
- return { status: "completed", capabilities: realtimeCapabilities(connection.listCapabilities(), query) };
1467
+ if (selector) {
1468
+ const selectorType = cleanString(selector.selector_type);
1469
+ const identifier = cleanString(selector.identifier);
1470
+ if (!identifier || (selectorType !== "app" && selectorType !== "skill")) {
1471
+ throw new EdgeRuntimeError("Realtime capability selector is invalid.");
1472
+ }
1473
+ const capabilities = connection.listCapabilities().filter((capability) => {
1474
+ const key = selectorType === "app" ? "app_slug" : "skill_name";
1475
+ return cleanString(capability.annotations?.[key]) === identifier;
1476
+ });
1477
+ return {
1478
+ status: "completed",
1479
+ selector_type: selectorType,
1480
+ identifier,
1481
+ capabilities,
1482
+ _marona_tools: capabilities.map(realtimeCapabilityTool),
1483
+ };
1330
1484
  }
1331
- if (name === "marona__call_capability") {
1332
- const capability = cleanString(argumentsValue.name);
1333
- if (!capability)
1334
- throw new EdgeRuntimeError("Realtime capability execution requires a name.");
1335
- const result = await connection.callTool(capability, asRecord(argumentsValue.arguments) ?? {}, { userId, conversationId });
1336
- return { status: "completed", capability, result };
1485
+ const result = await connection.callTool(name, argumentsValue, { userId, conversationId });
1486
+ return { status: "completed", capability: name, result };
1487
+ }
1488
+ function realtimeCapabilityTool(capability) {
1489
+ return {
1490
+ type: "function",
1491
+ name: capability.name,
1492
+ description: capability.description,
1493
+ parameters: realtimeProviderSchema(capability.inputSchema),
1494
+ };
1495
+ }
1496
+ function realtimeProviderSchema(value) {
1497
+ const schema = { ...(value ?? {}) };
1498
+ let properties = asRecord(schema.properties);
1499
+ if (!properties) {
1500
+ properties = {};
1501
+ for (const keyword of ["anyOf", "oneOf", "allOf"]) {
1502
+ const variants = Array.isArray(schema[keyword]) ? schema[keyword] : [];
1503
+ for (const variant of variants) {
1504
+ const nested = asRecord(asRecord(variant)?.properties);
1505
+ if (nested)
1506
+ Object.assign(properties, nested);
1507
+ }
1508
+ }
1337
1509
  }
1338
- throw new EdgeRuntimeError(`Unsupported realtime gateway call '${name}'.`);
1510
+ schema.type = "object";
1511
+ schema.properties = properties;
1512
+ for (const keyword of ["anyOf", "oneOf", "allOf", "enum", "const", "not"]) {
1513
+ delete schema[keyword];
1514
+ }
1515
+ return schema;
1339
1516
  }
1340
1517
  function agentToolByName(agent, name) {
1341
1518
  return agentTools(agent).find((value) => value instanceof AgentTool && value.name === name);
@@ -1359,32 +1536,6 @@ function delegatedInput(argumentsValue) {
1359
1536
  }
1360
1537
  function realtimeAgentToolDefinitions(agent) {
1361
1538
  const values = [];
1362
- if (agentTools(agent).some((value) => value instanceof MCPConnection)) {
1363
- values.push({
1364
- type: "function",
1365
- name: "marona__discover_capabilities",
1366
- description: "Discover relevant connected Marona capabilities.",
1367
- parameters: {
1368
- type: "object",
1369
- properties: { request: { type: "string" } },
1370
- required: ["request"],
1371
- additionalProperties: false,
1372
- },
1373
- }, {
1374
- type: "function",
1375
- name: "marona__call_capability",
1376
- description: "Execute one exact capability returned by discovery.",
1377
- parameters: {
1378
- type: "object",
1379
- properties: {
1380
- name: { type: "string" },
1381
- arguments: { type: "object", additionalProperties: true },
1382
- },
1383
- required: ["name", "arguments"],
1384
- additionalProperties: false,
1385
- },
1386
- });
1387
- }
1388
1539
  for (const value of agentTools(agent)) {
1389
1540
  if (value instanceof AgentTool) {
1390
1541
  values.push(realtimeAgentFunction(value.name, value.description, value.inputSchema));
@@ -1399,7 +1550,7 @@ function realtimeAgentToolDefinitions(agent) {
1399
1550
  type: "function",
1400
1551
  name: tool.name,
1401
1552
  description: tool.description,
1402
- parameters: tool.inputSchema,
1553
+ parameters: realtimeProviderSchema(tool.inputSchema),
1403
1554
  });
1404
1555
  }
1405
1556
  for (const value of agentHandoffs(agent)) {
@@ -1412,14 +1563,14 @@ function realtimeAgentFunction(name, description, schema) {
1412
1563
  type: "function",
1413
1564
  name,
1414
1565
  description,
1415
- parameters: schema ?? {
1566
+ parameters: realtimeProviderSchema(schema ?? {
1416
1567
  type: "object",
1417
1568
  properties: {
1418
1569
  input: { type: "string", description: "The bounded task or transfer context." },
1419
1570
  },
1420
1571
  required: ["input"],
1421
1572
  additionalProperties: false,
1422
- },
1573
+ }),
1423
1574
  };
1424
1575
  }
1425
1576
  function realtimeMessageItems(input) {
@@ -1475,28 +1626,6 @@ function openAIRealtimeOutput(event) {
1475
1626
  }
1476
1627
  return parts.length === 1 ? String(parts[0].text) : parts;
1477
1628
  }
1478
- function realtimeCapabilities(tools, query, limit = 12) {
1479
- const terms = new Set(query.toLowerCase().replaceAll("-", " ").split(/\s+/)
1480
- .map((part) => part.replace(/[^a-z0-9_]/g, ""))
1481
- .filter((part) => part.length > 1));
1482
- return tools.map((tool) => {
1483
- const name = tool.name ?? "";
1484
- const haystack = `${name.replaceAll("__", " ")} ${tool.description}`.toLowerCase();
1485
- let score = 0;
1486
- for (const term of terms) {
1487
- if (haystack.includes(term))
1488
- score += name.toLowerCase().includes(term) ? 3 : 1;
1489
- }
1490
- return { score, tool };
1491
- }).filter(({ score }) => score > 0)
1492
- .sort((left, right) => right.score - left.score || left.tool.name.localeCompare(right.tool.name))
1493
- .slice(0, limit)
1494
- .map(({ tool }) => ({
1495
- name: tool.name,
1496
- description: tool.description,
1497
- inputSchema: tool.inputSchema,
1498
- }));
1499
- }
1500
1629
  function developerIdForAgent(tools) {
1501
1630
  const developerContext = asRecord(tools.session.developer_context);
1502
1631
  const workspace = asRecord(developerContext?.workspace);
@@ -2026,7 +2155,7 @@ class HubClient {
2026
2155
  }
2027
2156
  async connect(options = {}) {
2028
2157
  const payload = await this.connectResult(options);
2029
- return new MCPConnection(payload, this.toolExecutor, options.apps === undefined && !(options.skills?.length));
2158
+ return new MCPConnection(payload, this.toolExecutor, options.apps === undefined && !(options.skills?.length), options.apps, options.skills ?? []);
2030
2159
  }
2031
2160
  async connectResult(options = {}) {
2032
2161
  const payload = await this.requestJson("POST", "/hub/connect", {
@@ -2744,6 +2873,52 @@ class RuntimeTransport {
2744
2873
  message(text, options = {}) {
2745
2874
  return this.postRuntimeMessage(new RuntimeMessageRequest(text, options));
2746
2875
  }
2876
+ async *streamMessage(text, options = {}) {
2877
+ const response = await this.fetchImpl(new URL("/runtime/message/stream", `${this.baseUrl}/`).toString(), {
2878
+ method: "POST",
2879
+ headers: {
2880
+ ...this.defaultHeaders,
2881
+ Accept: "text/event-stream",
2882
+ "Content-Type": "application/json",
2883
+ },
2884
+ body: JSON.stringify(new RuntimeMessageRequest(text, options).toJson()),
2885
+ signal: AbortSignal.timeout(this.timeoutMs),
2886
+ });
2887
+ if (!response.ok) {
2888
+ throw new EdgeRuntimeError(`Edge runtime request failed with HTTP ${response.status}.`, { statusCode: response.status, payload: parseMaybeJson(await response.text()) });
2889
+ }
2890
+ if (!response.body) {
2891
+ throw new EdgeRuntimeError("Edge runtime returned an empty event stream.");
2892
+ }
2893
+ const reader = response.body.getReader();
2894
+ const decoder = new TextDecoder();
2895
+ let buffer = "";
2896
+ try {
2897
+ while (true) {
2898
+ const { done, value } = await reader.read();
2899
+ buffer += decoder.decode(value, { stream: !done });
2900
+ const lines = buffer.split(/\r?\n/);
2901
+ buffer = lines.pop() ?? "";
2902
+ for (const line of lines) {
2903
+ if (!line.startsWith("data:"))
2904
+ continue;
2905
+ const event = asRecord(parseMaybeJson(line.slice(5).trim()));
2906
+ if (event)
2907
+ yield event;
2908
+ }
2909
+ if (done)
2910
+ break;
2911
+ }
2912
+ if (buffer.startsWith("data:")) {
2913
+ const event = asRecord(parseMaybeJson(buffer.slice(5).trim()));
2914
+ if (event)
2915
+ yield event;
2916
+ }
2917
+ }
2918
+ finally {
2919
+ reader.releaseLock();
2920
+ }
2921
+ }
2747
2922
  async createRealtimeSession(request) {
2748
2923
  const sessionRequest = request instanceof RealtimeSessionRequest ? request : new RealtimeSessionRequest(request);
2749
2924
  const payload = await this.requestJson("POST", "/runtime/realtime/session", {
@@ -3056,6 +3231,103 @@ class ResponsesClient {
3056
3231
  }
3057
3232
  throw new EdgeRuntimeError("Function tool execution exceeded 8 model rounds.");
3058
3233
  }
3234
+ async *stream(options) {
3235
+ const toolChoice = normalizeToolChoice(options.toolChoice);
3236
+ if (toolChoice === "required" && !options.tools) {
3237
+ throw new EdgeRuntimeError("toolChoice='required' needs a Hub connection.");
3238
+ }
3239
+ const values = options.tools === undefined
3240
+ ? []
3241
+ : Array.isArray(options.tools) ? options.tools : [options.tools];
3242
+ const functions = new Map();
3243
+ const descriptors = [];
3244
+ for (const value of values) {
3245
+ if (value instanceof MCPConnection)
3246
+ descriptors.push(...value.descriptors());
3247
+ else if (value instanceof FunctionTool) {
3248
+ if (functions.has(value.name))
3249
+ throw new EdgeRuntimeError(`Duplicate function tool name '${value.name}'.`);
3250
+ functions.set(value.name, value);
3251
+ descriptors.push(value.maronaDescriptor);
3252
+ }
3253
+ }
3254
+ const tools = normalizeConnectedTools(descriptors);
3255
+ const metadata = {
3256
+ ...(options.metadata ?? {}),
3257
+ marona_agent: {
3258
+ ...(asRecord(options.metadata?.marona_agent) ?? {}),
3259
+ tool_choice: toolChoice,
3260
+ tools_enabled: Boolean(options.tools) && toolChoice !== "none",
3261
+ },
3262
+ };
3263
+ if (functions.size) {
3264
+ metadata.marona_function_tools = [...functions.values()].map((tool) => ({
3265
+ name: tool.name,
3266
+ description: tool.description,
3267
+ input_schema: tool.inputSchema,
3268
+ output_schema: tool.outputSchema,
3269
+ }));
3270
+ }
3271
+ let results = [];
3272
+ for (let round = 0; round < 8; round += 1) {
3273
+ let response;
3274
+ for await (const event of this.runtime.clientStream({
3275
+ ...options,
3276
+ model: options.model ?? "marona/gpt-5.6",
3277
+ metadata: {
3278
+ ...metadata,
3279
+ ...(results.length ? { marona_function_tool_results: results } : {}),
3280
+ },
3281
+ tools: toolChoice === "none" ? [] : tools,
3282
+ localFunctionTools: [...functions.values()],
3283
+ })) {
3284
+ if (event.type === "run.completed") {
3285
+ const payload = asRecord(event.output);
3286
+ if (payload)
3287
+ response = parseRuntimeMessageResponse(payload);
3288
+ continue;
3289
+ }
3290
+ yield event;
3291
+ }
3292
+ if (!response)
3293
+ throw new EdgeRuntimeError("Streaming runtime returned no completed response.");
3294
+ const calls = Array.isArray(response.agent.function_tool_calls)
3295
+ ? response.agent.function_tool_calls
3296
+ : [];
3297
+ if (!calls.length) {
3298
+ yield { type: "run.completed", output: response.rawJson };
3299
+ return;
3300
+ }
3301
+ results = [];
3302
+ for (const raw of calls) {
3303
+ const call = asRecord(raw);
3304
+ const name = cleanString(call?.name);
3305
+ const tool = name ? functions.get(name) : undefined;
3306
+ if (!call || !name || !tool)
3307
+ throw new EdgeRuntimeError(`Function tool '${name ?? ""}' is not available in this SDK process.`);
3308
+ const callId = cleanString(call.call_id) ?? "";
3309
+ yield { type: "tool.started", data: { tool_name: name, call_id: callId } };
3310
+ const baseContext = asRecord(metadata.marona_tool_context) ?? {};
3311
+ const context = {
3312
+ userId: options.userId,
3313
+ sessionId: cleanString(baseContext.session_id) ?? options.conversationId ?? "default",
3314
+ developerId: cleanString(baseContext.developer_id),
3315
+ permissions: new Set(Array.isArray(baseContext.permissions) ? baseContext.permissions.map(String) : []),
3316
+ approvedTools: new Set(Array.isArray(baseContext.approved_tools) ? baseContext.approved_tools.map(String) : []),
3317
+ metadata: {},
3318
+ };
3319
+ const argumentsValue = asRecord(call.arguments) ?? {};
3320
+ results.push({
3321
+ call_id: callId,
3322
+ name,
3323
+ arguments: argumentsValue,
3324
+ output: await tool.invoke(argumentsValue, context),
3325
+ });
3326
+ yield { type: "tool.completed", data: { tool_name: name, call_id: callId } };
3327
+ }
3328
+ }
3329
+ throw new EdgeRuntimeError("Function tool execution exceeded 8 model rounds.");
3330
+ }
3059
3331
  }
3060
3332
  class RuntimeEngine extends RuntimeTransport {
3061
3333
  hub;
@@ -3250,6 +3522,38 @@ class RuntimeEngine extends RuntimeTransport {
3250
3522
  attachments: [...normalized.attachments, ...(attachments ?? [])],
3251
3523
  });
3252
3524
  }
3525
+ async *clientStream(options) {
3526
+ const { input, attachments, ...messageOptions } = options;
3527
+ const normalized = runtimeMessageFromInput(input);
3528
+ const modelRoute = cleanString(messageOptions.model ?? this.defaultModelRoute)
3529
+ ?? "marona/gpt-5.6";
3530
+ const model = this.resolveModel(modelRoute);
3531
+ if (model) {
3532
+ const response = await this.client(options);
3533
+ yield { type: "run.started" };
3534
+ if (response.reply)
3535
+ yield { type: "output_text.delta", delta: response.reply };
3536
+ yield { type: "run.completed", output: runtimeResponsePayload(response) };
3537
+ return;
3538
+ }
3539
+ const developerInstructions = combineText([
3540
+ normalized.developerInstructions,
3541
+ this.developerInstructions,
3542
+ messageOptions.developerInstructions ?? messageOptions.developer_instructions,
3543
+ ]);
3544
+ for await (const event of super.streamMessage(normalized.text, {
3545
+ ...messageOptions,
3546
+ model: modelRoute,
3547
+ developerInstructions,
3548
+ attachments: [...normalized.attachments, ...(attachments ?? [])],
3549
+ metadata: {
3550
+ ...(messageOptions.metadata ?? {}),
3551
+ ...(messageOptions.tools ? { tools: messageOptions.tools } : {}),
3552
+ },
3553
+ })) {
3554
+ yield event;
3555
+ }
3556
+ }
3253
3557
  async modelMessage(model, text, options) {
3254
3558
  const messages = [
3255
3559
  {
@@ -3688,6 +3992,19 @@ function parseRuntimeMessageResponse(payload) {
3688
3992
  agent: asRecord(payload.agent) ?? {},
3689
3993
  };
3690
3994
  }
3995
+ function runtimeResponsePayload(response) {
3996
+ return {
3997
+ ...response.rawJson,
3998
+ status: response.status,
3999
+ reply: response.reply,
4000
+ interface: response.interfaceName,
4001
+ conversation_id: response.conversationId,
4002
+ artifacts: response.artifacts,
4003
+ model: response.model,
4004
+ routing: response.routing,
4005
+ agent: response.agent,
4006
+ };
4007
+ }
3691
4008
  function normalizeRouting(value) {
3692
4009
  if (!value)
3693
4010
  return undefined;