marona 0.10.3 → 0.11.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.10.3";
1
+ export const packageVersion = "0.11.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"];
@@ -469,6 +469,57 @@ export class MaronaOutputValidationError extends EdgeRuntimeError {
469
469
  }
470
470
  export class MaronaGuardrailError extends EdgeRuntimeError {
471
471
  }
472
+ export class FunctionTool {
473
+ name;
474
+ description;
475
+ inputSchema;
476
+ outputSchema;
477
+ timeoutMs;
478
+ permissions;
479
+ approval;
480
+ metadata;
481
+ executor;
482
+ constructor(options) {
483
+ validateAgentToolName(options.name);
484
+ if (!options.description.trim())
485
+ throw new EdgeRuntimeError("Function tool description cannot be empty.");
486
+ this.name = options.name;
487
+ this.description = options.description.trim();
488
+ this.inputSchema = options.inputSchema;
489
+ this.outputSchema = options.outputSchema;
490
+ this.timeoutMs = options.timeoutMs ?? 30_000;
491
+ if (this.timeoutMs <= 0)
492
+ throw new EdgeRuntimeError("Function tool timeoutMs must be greater than zero.");
493
+ this.permissions = [...new Set(options.permissions ?? [])];
494
+ this.approval = options.approval ?? "never";
495
+ this.metadata = options.metadata ?? {};
496
+ this.executor = options.execute;
497
+ }
498
+ get maronaDescriptor() {
499
+ return {
500
+ type: "function",
501
+ function: { name: this.name, description: this.description, parameters: this.inputSchema },
502
+ marona: { type: "function", execution: "client" },
503
+ };
504
+ }
505
+ async invoke(argumentsValue = {}, context = defaultToolContext()) {
506
+ validateJsonSchema(argumentsValue, this.inputSchema, "arguments");
507
+ const missing = this.permissions.filter((value) => !context.permissions.has(value));
508
+ if (missing.length)
509
+ throw new EdgeRuntimeError(`Function tool requires permission: ${missing.join(", ")}`);
510
+ if (this.approval === "always" && !context.approvedTools.has(this.name)) {
511
+ throw new EdgeRuntimeError(`Function tool '${this.name}' requires application approval.`);
512
+ }
513
+ const timeout = new Promise((_, reject) => setTimeout(() => reject(new EdgeRuntimeError(`Function tool '${this.name}' timed out after ${this.timeoutMs} ms.`)), this.timeoutMs));
514
+ const result = await Promise.race([Promise.resolve(this.executor(argumentsValue, context)), timeout]);
515
+ if (this.outputSchema)
516
+ validateJsonSchema(result, this.outputSchema, "output");
517
+ return JSON.parse(JSON.stringify(result));
518
+ }
519
+ }
520
+ export function functionTool(options) {
521
+ return new FunctionTool(options);
522
+ }
472
523
  export class AgentTool {
473
524
  targetAgent;
474
525
  name;
@@ -601,13 +652,13 @@ export class Runner {
601
652
  throw new EdgeRuntimeError(`Agent input does not allow: ${unsupportedInputs.join(", ")}`);
602
653
  }
603
654
  try {
604
- const response = await runtime.client({
655
+ const response = await new ResponsesClient(runtime).create({
605
656
  model: agent.model,
606
657
  input: runtimeInput,
607
658
  userId,
608
659
  conversationId,
609
660
  developerInstructions: resolveAgentInstructions(agent, context) || undefined,
610
- tools: connection?.descriptors() ?? [],
661
+ tools: agentRuntimeTools(agent),
611
662
  routing: agent.routing,
612
663
  output,
613
664
  metadata: {
@@ -620,6 +671,12 @@ export class Runner {
620
671
  voice: agent.voice ?? {},
621
672
  },
622
673
  marona_multi_agent: graph,
674
+ marona_tool_context: {
675
+ session_id: sessionId,
676
+ developer_id: developerId,
677
+ permissions: Array.isArray(agent.metadata.permissions) ? agent.metadata.permissions : [],
678
+ approved_tools: Array.isArray(agent.metadata.approved_tools) ? agent.metadata.approved_tools : [],
679
+ },
623
680
  },
624
681
  });
625
682
  raiseAgentInterruption(response);
@@ -778,7 +835,14 @@ export class RealtimeSession {
778
835
  });
779
836
  }
780
837
  else {
781
- output = await executeRealtimeGateway(this.agent, call.name, call.arguments, { userId: this.userId, sessionId: this.sessionId });
838
+ const localTool = functionToolByName(this.agent, call.name);
839
+ output = localTool
840
+ ? {
841
+ status: "completed",
842
+ tool_name: call.name,
843
+ result: await localTool.invoke(call.arguments, toolContext(this.agent, this.userId, this.sessionId)),
844
+ }
845
+ : await executeRealtimeGateway(this.agent, call.name, call.arguments, { userId: this.userId, sessionId: this.sessionId });
782
846
  }
783
847
  }
784
848
  catch (error) {
@@ -951,6 +1015,9 @@ async function executeRealtimeGateway(agent, name, argumentsValue, options) {
951
1015
  function agentToolByName(agent, name) {
952
1016
  return agentTools(agent).find((value) => value instanceof AgentTool && value.name === name);
953
1017
  }
1018
+ function functionToolByName(agent, name) {
1019
+ return agentTools(agent).find((value) => value instanceof FunctionTool && value.name === name);
1020
+ }
954
1021
  function handoffByName(agent, name) {
955
1022
  return agentHandoffs(agent).find((value) => value.name === name);
956
1023
  }
@@ -994,6 +1061,9 @@ function realtimeAgentToolDefinitions(agent) {
994
1061
  if (value instanceof AgentTool) {
995
1062
  values.push(realtimeAgentFunction(value.name, value.description, value.inputSchema));
996
1063
  }
1064
+ else if (value instanceof FunctionTool) {
1065
+ values.push(realtimeAgentFunction(value.name, value.description, value.inputSchema));
1066
+ }
997
1067
  }
998
1068
  for (const value of agentHandoffs(agent)) {
999
1069
  values.push(realtimeAgentFunction(value.name, value.description, value.inputSchema));
@@ -1113,6 +1183,56 @@ function normalizeToolChoice(value) {
1113
1183
  }
1114
1184
  return choice;
1115
1185
  }
1186
+ function defaultToolContext() {
1187
+ return {
1188
+ sessionId: "default",
1189
+ permissions: new Set(),
1190
+ approvedTools: new Set(),
1191
+ metadata: {},
1192
+ };
1193
+ }
1194
+ function toolContext(agent, userId, sessionId) {
1195
+ const permissions = Array.isArray(agent.metadata.permissions) ? agent.metadata.permissions : [];
1196
+ const approved = Array.isArray(agent.metadata.approved_tools) ? agent.metadata.approved_tools : [];
1197
+ return {
1198
+ userId,
1199
+ sessionId,
1200
+ permissions: new Set(permissions.map(String)),
1201
+ approvedTools: new Set(approved.map(String)),
1202
+ metadata: safeAgentMetadata(agent.metadata),
1203
+ };
1204
+ }
1205
+ function validateJsonSchema(value, schema, path) {
1206
+ const type = typeof schema.type === "string" ? schema.type : undefined;
1207
+ const valid = type === undefined
1208
+ || (type === "object" && value !== null && typeof value === "object" && !Array.isArray(value))
1209
+ || (type === "array" && Array.isArray(value))
1210
+ || (type === "string" && typeof value === "string")
1211
+ || (type === "integer" && typeof value === "number" && Number.isInteger(value))
1212
+ || (type === "number" && typeof value === "number")
1213
+ || (type === "boolean" && typeof value === "boolean")
1214
+ || (type === "null" && value === null);
1215
+ if (!valid)
1216
+ throw new EdgeRuntimeError(`${path} must be ${type}.`);
1217
+ const record = asRecord(value);
1218
+ if (type === "object" && record) {
1219
+ const required = Array.isArray(schema.required) ? schema.required.map(String) : [];
1220
+ const missing = required.filter((key) => !(key in record));
1221
+ if (missing.length)
1222
+ throw new EdgeRuntimeError(`${path} is missing required fields: ${missing.join(", ")}`);
1223
+ const properties = asRecord(schema.properties) ?? {};
1224
+ if (schema.additionalProperties === false) {
1225
+ const extra = Object.keys(record).filter((key) => !(key in properties));
1226
+ if (extra.length)
1227
+ throw new EdgeRuntimeError(`${path} has unknown fields: ${extra.join(", ")}`);
1228
+ }
1229
+ for (const [key, child] of Object.entries(properties)) {
1230
+ const childSchema = asRecord(child);
1231
+ if (key in record && childSchema)
1232
+ validateJsonSchema(record[key], childSchema, `${path}.${key}`);
1233
+ }
1234
+ }
1235
+ }
1116
1236
  function validateAgentToolName(value) {
1117
1237
  if (!/^[A-Za-z0-9_-]{1,64}$/.test(value)) {
1118
1238
  throw new EdgeRuntimeError("Agent tool and handoff names must use 1-64 letters, numbers, underscores, or hyphens.");
@@ -1127,10 +1247,10 @@ function agentTools(agent) {
1127
1247
  const values = Array.isArray(agent.tools) ? agent.tools : [agent.tools];
1128
1248
  const names = new Set();
1129
1249
  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.");
1250
+ if (!(value instanceof MCPConnection) && !(value instanceof AgentTool) && !(value instanceof FunctionTool)) {
1251
+ throw new EdgeRuntimeError("Agent tools may contain only FunctionTool, Hub connections, and Agent.asTool() values.");
1132
1252
  }
1133
- if (value instanceof AgentTool) {
1253
+ if (value instanceof AgentTool || value instanceof FunctionTool) {
1134
1254
  if (names.has(value.name))
1135
1255
  throw new EdgeRuntimeError(`Duplicate Agent tool name '${value.name}'.`);
1136
1256
  names.add(value.name);
@@ -1170,7 +1290,7 @@ function agentConnection(agent) {
1170
1290
  }
1171
1291
  found = value;
1172
1292
  }
1173
- else
1293
+ else if (value instanceof AgentTool)
1174
1294
  visit(value.targetAgent);
1175
1295
  }
1176
1296
  for (const value of agentHandoffs(current))
@@ -1179,6 +1299,29 @@ function agentConnection(agent) {
1179
1299
  visit(agent);
1180
1300
  return found;
1181
1301
  }
1302
+ function agentRuntimeTools(agent) {
1303
+ const values = [];
1304
+ const connection = agentConnection(agent);
1305
+ if (connection)
1306
+ values.push(connection);
1307
+ const visited = new Set();
1308
+ const visit = (current) => {
1309
+ if (visited.has(current))
1310
+ return;
1311
+ visited.add(current);
1312
+ for (const value of agentTools(current)) {
1313
+ if (value instanceof FunctionTool)
1314
+ values.push(value);
1315
+ else if (value instanceof AgentTool)
1316
+ visit(value.targetAgent);
1317
+ }
1318
+ for (const value of agentHandoffs(current))
1319
+ visit(value.targetAgent);
1320
+ };
1321
+ visit(agent);
1322
+ const unique = values.filter((value, index) => values.indexOf(value) === index);
1323
+ return unique.length === 0 ? undefined : unique.length === 1 ? unique[0] : unique;
1324
+ }
1182
1325
  function agentContext(agent, userId, sessionId) {
1183
1326
  return { userId, sessionId, agentName: agent.name, metadata: safeAgentMetadata(agent.metadata) };
1184
1327
  }
@@ -1236,6 +1379,12 @@ function agentGraph(agent, context, options = {}) {
1236
1379
  input_schema: value.inputSchema,
1237
1380
  output_schema: value.outputSchema,
1238
1381
  }));
1382
+ const functionTools = agentTools(current).filter((value) => value instanceof FunctionTool).map((value) => ({
1383
+ name: value.name,
1384
+ description: value.description,
1385
+ input_schema: value.inputSchema,
1386
+ output_schema: value.outputSchema,
1387
+ }));
1239
1388
  const transfers = agentHandoffs(current).map((value) => ({
1240
1389
  name: value.name,
1241
1390
  description: value.description,
@@ -1256,6 +1405,7 @@ function agentGraph(agent, context, options = {}) {
1256
1405
  input_schema: current.inputSchema,
1257
1406
  output_schema: current.outputSchema,
1258
1407
  hub_tools: agentTools(current).some((value) => value instanceof MCPConnection),
1408
+ function_tools: functionTools,
1259
1409
  delegations,
1260
1410
  handoffs: transfers,
1261
1411
  metadata: safeAgentMetadata(current.metadata),
@@ -2372,9 +2522,22 @@ class ResponsesClient {
2372
2522
  if (toolChoice === "required" && !options.tools) {
2373
2523
  throw new EdgeRuntimeError("toolChoice='required' needs a Hub connection.");
2374
2524
  }
2375
- const tools = options.tools
2376
- ? normalizeConnectedTools(options.tools.descriptors())
2377
- : [];
2525
+ const values = options.tools === undefined
2526
+ ? []
2527
+ : Array.isArray(options.tools) ? options.tools : [options.tools];
2528
+ const functions = new Map();
2529
+ const descriptors = [];
2530
+ for (const value of values) {
2531
+ if (value instanceof MCPConnection)
2532
+ descriptors.push(...value.descriptors());
2533
+ else if (value instanceof FunctionTool) {
2534
+ if (functions.has(value.name))
2535
+ throw new EdgeRuntimeError(`Duplicate function tool name '${value.name}'.`);
2536
+ functions.set(value.name, value);
2537
+ descriptors.push(value.maronaDescriptor);
2538
+ }
2539
+ }
2540
+ const tools = normalizeConnectedTools(descriptors);
2378
2541
  const metadata = {
2379
2542
  ...(options.metadata ?? {}),
2380
2543
  marona_agent: {
@@ -2383,12 +2546,63 @@ class ResponsesClient {
2383
2546
  tools_enabled: Boolean(options.tools) && toolChoice !== "none",
2384
2547
  },
2385
2548
  };
2386
- return this.runtime.client({
2387
- ...options,
2388
- model: options.model ?? "marona/gpt-5.6",
2389
- metadata,
2390
- tools: toolChoice === "none" ? [] : tools,
2391
- });
2549
+ if (functions.size) {
2550
+ metadata.marona_function_tools = [...functions.values()].map((tool) => ({
2551
+ name: tool.name,
2552
+ description: tool.description,
2553
+ input_schema: tool.inputSchema,
2554
+ output_schema: tool.outputSchema,
2555
+ }));
2556
+ }
2557
+ const results = [];
2558
+ for (let round = 0; round < 8; round += 1) {
2559
+ const response = await this.runtime.client({
2560
+ ...options,
2561
+ model: options.model ?? "marona/gpt-5.6",
2562
+ metadata: {
2563
+ ...metadata,
2564
+ ...(results.length ? { marona_function_tool_results: results } : {}),
2565
+ },
2566
+ tools: toolChoice === "none" ? [] : tools,
2567
+ localFunctionTools: [...functions.values()],
2568
+ });
2569
+ const calls = Array.isArray(response.agent.function_tool_calls)
2570
+ ? response.agent.function_tool_calls
2571
+ : [];
2572
+ if (!calls.length)
2573
+ return response;
2574
+ for (const raw of calls) {
2575
+ const call = asRecord(raw);
2576
+ const name = cleanString(call?.name);
2577
+ const tool = name ? functions.get(name) : undefined;
2578
+ if (!call || !name || !tool)
2579
+ throw new EdgeRuntimeError(`Function tool '${name ?? ""}' is not available in this SDK process.`);
2580
+ const baseContext = asRecord(metadata.marona_tool_context) ?? {};
2581
+ const graph = asRecord(metadata.marona_multi_agent);
2582
+ const agents = asRecord(graph?.agents);
2583
+ const definition = asRecord(agents?.[cleanString(call.agent_id) ?? ""]);
2584
+ const contextValues = {
2585
+ ...baseContext,
2586
+ ...(asRecord(definition?.metadata) ?? {}),
2587
+ };
2588
+ const context = {
2589
+ userId: options.userId,
2590
+ sessionId: cleanString(contextValues.session_id) ?? options.conversationId ?? "default",
2591
+ developerId: cleanString(contextValues.developer_id),
2592
+ permissions: new Set(Array.isArray(contextValues.permissions) ? contextValues.permissions.map(String) : []),
2593
+ approvedTools: new Set(Array.isArray(contextValues.approved_tools) ? contextValues.approved_tools.map(String) : []),
2594
+ metadata: {},
2595
+ };
2596
+ const argumentsValue = asRecord(call.arguments) ?? {};
2597
+ results.push({
2598
+ call_id: cleanString(call.call_id) ?? "",
2599
+ name,
2600
+ arguments: argumentsValue,
2601
+ output: await tool.invoke(argumentsValue, context),
2602
+ });
2603
+ }
2604
+ }
2605
+ throw new EdgeRuntimeError("Function tool execution exceeded 8 model rounds.");
2392
2606
  }
2393
2607
  }
2394
2608
  class RuntimeEngine extends RuntimeTransport {
@@ -2693,20 +2907,38 @@ class RuntimeEngine extends RuntimeTransport {
2693
2907
  continue;
2694
2908
  }
2695
2909
  const selectedTool = availableTools.find((tool) => stringValue(asRecord(tool.function)?.name) === callName);
2696
- const result = selectedTool
2910
+ const localFunction = options.localFunctionTools?.find((value) => value.name === callName);
2911
+ const result = localFunction
2697
2912
  ? {
2698
2913
  tool_call_id: call.id,
2699
- app_slug: asRecord(selectedTool.marona)?.app_slug,
2700
- tool_name: asRecord(selectedTool.marona)?.tool_name ?? callName,
2914
+ tool_name: callName,
2701
2915
  arguments: callArguments,
2702
- result: await this.tools.execute(selectedTool, callArguments, {
2703
- interfaceName: options.interfaceName ?? options.interface ?? "api",
2916
+ result: await localFunction.invoke(callArguments, {
2704
2917
  userId: options.userId ?? options.user_id,
2705
- conversationId: options.conversationId ?? options.conversation_id,
2706
- model: model.name,
2918
+ sessionId: options.conversationId ?? options.conversation_id ?? "default",
2919
+ permissions: new Set(Array.isArray(asRecord(options.metadata?.marona_tool_context)?.permissions)
2920
+ ? (asRecord(options.metadata?.marona_tool_context)?.permissions).map(String)
2921
+ : []),
2922
+ approvedTools: new Set(Array.isArray(asRecord(options.metadata?.marona_tool_context)?.approved_tools)
2923
+ ? (asRecord(options.metadata?.marona_tool_context)?.approved_tools).map(String)
2924
+ : []),
2925
+ metadata: {},
2707
2926
  }),
2708
2927
  }
2709
- : { tool_call_id: call.id, error: `Tool '${callName}' is not connected.` };
2928
+ : selectedTool
2929
+ ? {
2930
+ tool_call_id: call.id,
2931
+ app_slug: asRecord(selectedTool.marona)?.app_slug,
2932
+ tool_name: asRecord(selectedTool.marona)?.tool_name ?? callName,
2933
+ arguments: callArguments,
2934
+ result: await this.tools.execute(selectedTool, callArguments, {
2935
+ interfaceName: options.interfaceName ?? options.interface ?? "api",
2936
+ userId: options.userId ?? options.user_id,
2937
+ conversationId: options.conversationId ?? options.conversation_id,
2938
+ model: model.name,
2939
+ }),
2940
+ }
2941
+ : { tool_call_id: call.id, error: `Tool '${callName}' is not connected.` };
2710
2942
  executedCapabilityCalls.set(callKey, result);
2711
2943
  toolResults.push(result);
2712
2944
  runtimeSteps.push(result);