cencori 1.16.4 → 1.17.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.
@@ -305,6 +305,13 @@ interface RunOptions<Ctx = unknown> extends TransportOptions {
305
305
  user?: string;
306
306
  /** Extra metadata on the session (strings). */
307
307
  metadata?: Record<string, string>;
308
+ /**
309
+ * Called once for each finished tool call, before its result goes back to the model: your
310
+ * tools, MCP servers' tools and rejected calls alike. Calls the model made together run
311
+ * together, and this is then called for each in order. Not called for handoffs or for
312
+ * tools Cencori runs. Awaited; an error it throws stops the run.
313
+ */
314
+ onToolEnd?: (result: ToolResult, runContext: RunContext<Ctx>) => void | Promise<void>;
308
315
  }
309
316
  /** A tool call waiting for a human. Approve or reject it on result.state, then run again. */
310
317
  interface ToolApprovalItem {
@@ -347,6 +354,20 @@ interface Usage {
347
354
  outputTokens: number;
348
355
  totalTokens: number;
349
356
  }
357
+ /** One model call in a run: which model answered it and what it cost. */
358
+ interface RunStep {
359
+ agentName: string;
360
+ /** The model that answered. With model: 'auto', the one it was routed to. */
361
+ model: string | undefined;
362
+ provider: string | undefined;
363
+ /** True when the model you asked for failed and another answered. */
364
+ usedFallback: boolean;
365
+ usage: Usage;
366
+ /** What Cencori charged, in USD. 0 on your own provider key. */
367
+ costUsd: number;
368
+ /** What the provider's price list says the call cost, in USD. */
369
+ providerCostUsd: number;
370
+ }
350
371
  type RunStreamEvent = {
351
372
  type: 'agent_updated';
352
373
  agent: Agent<any>;
@@ -461,6 +482,8 @@ interface RunResult<Output = string> {
461
482
  /** Messages, tool calls and handoffs in this run, in order. */
462
483
  newItems: RunItem[];
463
484
  usage: Usage;
485
+ /** Each model call this run() made, in order. A run resumed from a RunState lists the calls made since. */
486
+ steps: RunStep[];
464
487
  /**
465
488
  * A person is handling this conversation (the agent handed it over with
466
489
  * humanHandoff, or someone stepped in): the message was kept for them and
@@ -509,8 +532,23 @@ interface OutputGuardrail<Ctx = unknown> {
509
532
  output: unknown;
510
533
  agent: Agent<Ctx, any>;
511
534
  runContext: RunContext<Ctx>;
535
+ /**
536
+ * What each tool returned in this run, in order (your tools and MCP servers'). Use it to
537
+ * tell the user's own data, which a tool fetched, from something the answer must not say.
538
+ */
539
+ toolResults: ToolResult[];
512
540
  }) => GuardrailResult | Promise<GuardrailResult>;
513
541
  }
542
+ /** One finished tool call: what the model asked for and what the tool gave back. */
543
+ interface ToolResult {
544
+ callId: string;
545
+ toolName: string;
546
+ /** The model's arguments, as JSON text. */
547
+ arguments: string;
548
+ /** What the model was given back. */
549
+ output: string;
550
+ agentName: string;
551
+ }
514
552
  interface GuardrailResult {
515
553
  /** true stops the run with a GuardrailTripwireTriggered error. */
516
554
  tripwireTriggered: boolean;
@@ -771,4 +809,4 @@ interface WebFetchToolOptions {
771
809
  }
772
810
  declare function webFetch<Ctx = unknown>(options?: WebFetchToolOptions): FunctionTool<Ctx>;
773
811
 
774
- export { Agent, type AgentChatHandlerOptions, type AgentInput, type AgentInputItem, type AgentOptions, AgentsError, CencoriRunError, DEFAULT_MODEL, type FunctionTool, type GuardrailResult, GuardrailTripwireTriggered, HUMAN_HANDOFF_TOOL, type HumanHandoffOptions, type HumanMessage, type HumanStatus, type InputContentPart, type InputGuardrail, type JsonSchema, type MCPCallResult, type MCPServer, type MCPServerOptions, MCPServerStdio, type MCPServerStdioOptions, MCPServerStreamableHttp, type MCPServerStreamableHttpOptions, type MCPTool, MaxTurnsExceededError, type ModelSettings, type NeedsApproval, type OutputGuardrail, type RunContext, type RunItem, type RunOptions, type RunResult, RunState, type RunStreamEvent, type SchemaLike, SchemaValidationError, type StandardSchemaV1, type StreamedRunResult, type ToolApprovalItem, type ToolOptions, type Usage, type WebFetchToolOptions, type WebSearchToolOptions, WidgetNode, createAgentChatHandler, file, humanHandoff, humanReply, humanStatus, image, inputText, releaseToAgent, run, toAgentChatStream, tool, webFetch, webSearch };
812
+ export { Agent, type AgentChatHandlerOptions, type AgentInput, type AgentInputItem, type AgentOptions, AgentsError, CencoriRunError, DEFAULT_MODEL, type FunctionTool, type GuardrailResult, GuardrailTripwireTriggered, HUMAN_HANDOFF_TOOL, type HumanHandoffOptions, type HumanMessage, type HumanStatus, type InputContentPart, type InputGuardrail, type JsonSchema, type MCPCallResult, type MCPServer, type MCPServerOptions, MCPServerStdio, type MCPServerStdioOptions, MCPServerStreamableHttp, type MCPServerStreamableHttpOptions, type MCPTool, MaxTurnsExceededError, type ModelSettings, type NeedsApproval, type OutputGuardrail, type RunContext, type RunItem, type RunOptions, type RunResult, RunState, type RunStep, type RunStreamEvent, type SchemaLike, SchemaValidationError, type StandardSchemaV1, type StreamedRunResult, type ToolApprovalItem, type ToolOptions, type ToolResult, type Usage, type WebFetchToolOptions, type WebSearchToolOptions, WidgetNode, createAgentChatHandler, file, humanHandoff, humanReply, humanStatus, image, inputText, releaseToAgent, run, toAgentChatStream, tool, webFetch, webSearch };
@@ -305,6 +305,13 @@ interface RunOptions<Ctx = unknown> extends TransportOptions {
305
305
  user?: string;
306
306
  /** Extra metadata on the session (strings). */
307
307
  metadata?: Record<string, string>;
308
+ /**
309
+ * Called once for each finished tool call, before its result goes back to the model: your
310
+ * tools, MCP servers' tools and rejected calls alike. Calls the model made together run
311
+ * together, and this is then called for each in order. Not called for handoffs or for
312
+ * tools Cencori runs. Awaited; an error it throws stops the run.
313
+ */
314
+ onToolEnd?: (result: ToolResult, runContext: RunContext<Ctx>) => void | Promise<void>;
308
315
  }
309
316
  /** A tool call waiting for a human. Approve or reject it on result.state, then run again. */
310
317
  interface ToolApprovalItem {
@@ -347,6 +354,20 @@ interface Usage {
347
354
  outputTokens: number;
348
355
  totalTokens: number;
349
356
  }
357
+ /** One model call in a run: which model answered it and what it cost. */
358
+ interface RunStep {
359
+ agentName: string;
360
+ /** The model that answered. With model: 'auto', the one it was routed to. */
361
+ model: string | undefined;
362
+ provider: string | undefined;
363
+ /** True when the model you asked for failed and another answered. */
364
+ usedFallback: boolean;
365
+ usage: Usage;
366
+ /** What Cencori charged, in USD. 0 on your own provider key. */
367
+ costUsd: number;
368
+ /** What the provider's price list says the call cost, in USD. */
369
+ providerCostUsd: number;
370
+ }
350
371
  type RunStreamEvent = {
351
372
  type: 'agent_updated';
352
373
  agent: Agent<any>;
@@ -461,6 +482,8 @@ interface RunResult<Output = string> {
461
482
  /** Messages, tool calls and handoffs in this run, in order. */
462
483
  newItems: RunItem[];
463
484
  usage: Usage;
485
+ /** Each model call this run() made, in order. A run resumed from a RunState lists the calls made since. */
486
+ steps: RunStep[];
464
487
  /**
465
488
  * A person is handling this conversation (the agent handed it over with
466
489
  * humanHandoff, or someone stepped in): the message was kept for them and
@@ -509,8 +532,23 @@ interface OutputGuardrail<Ctx = unknown> {
509
532
  output: unknown;
510
533
  agent: Agent<Ctx, any>;
511
534
  runContext: RunContext<Ctx>;
535
+ /**
536
+ * What each tool returned in this run, in order (your tools and MCP servers'). Use it to
537
+ * tell the user's own data, which a tool fetched, from something the answer must not say.
538
+ */
539
+ toolResults: ToolResult[];
512
540
  }) => GuardrailResult | Promise<GuardrailResult>;
513
541
  }
542
+ /** One finished tool call: what the model asked for and what the tool gave back. */
543
+ interface ToolResult {
544
+ callId: string;
545
+ toolName: string;
546
+ /** The model's arguments, as JSON text. */
547
+ arguments: string;
548
+ /** What the model was given back. */
549
+ output: string;
550
+ agentName: string;
551
+ }
514
552
  interface GuardrailResult {
515
553
  /** true stops the run with a GuardrailTripwireTriggered error. */
516
554
  tripwireTriggered: boolean;
@@ -771,4 +809,4 @@ interface WebFetchToolOptions {
771
809
  }
772
810
  declare function webFetch<Ctx = unknown>(options?: WebFetchToolOptions): FunctionTool<Ctx>;
773
811
 
774
- export { Agent, type AgentChatHandlerOptions, type AgentInput, type AgentInputItem, type AgentOptions, AgentsError, CencoriRunError, DEFAULT_MODEL, type FunctionTool, type GuardrailResult, GuardrailTripwireTriggered, HUMAN_HANDOFF_TOOL, type HumanHandoffOptions, type HumanMessage, type HumanStatus, type InputContentPart, type InputGuardrail, type JsonSchema, type MCPCallResult, type MCPServer, type MCPServerOptions, MCPServerStdio, type MCPServerStdioOptions, MCPServerStreamableHttp, type MCPServerStreamableHttpOptions, type MCPTool, MaxTurnsExceededError, type ModelSettings, type NeedsApproval, type OutputGuardrail, type RunContext, type RunItem, type RunOptions, type RunResult, RunState, type RunStreamEvent, type SchemaLike, SchemaValidationError, type StandardSchemaV1, type StreamedRunResult, type ToolApprovalItem, type ToolOptions, type Usage, type WebFetchToolOptions, type WebSearchToolOptions, WidgetNode, createAgentChatHandler, file, humanHandoff, humanReply, humanStatus, image, inputText, releaseToAgent, run, toAgentChatStream, tool, webFetch, webSearch };
812
+ export { Agent, type AgentChatHandlerOptions, type AgentInput, type AgentInputItem, type AgentOptions, AgentsError, CencoriRunError, DEFAULT_MODEL, type FunctionTool, type GuardrailResult, GuardrailTripwireTriggered, HUMAN_HANDOFF_TOOL, type HumanHandoffOptions, type HumanMessage, type HumanStatus, type InputContentPart, type InputGuardrail, type JsonSchema, type MCPCallResult, type MCPServer, type MCPServerOptions, MCPServerStdio, type MCPServerStdioOptions, MCPServerStreamableHttp, type MCPServerStreamableHttpOptions, type MCPTool, MaxTurnsExceededError, type ModelSettings, type NeedsApproval, type OutputGuardrail, type RunContext, type RunItem, type RunOptions, type RunResult, RunState, type RunStep, type RunStreamEvent, type SchemaLike, SchemaValidationError, type StandardSchemaV1, type StreamedRunResult, type ToolApprovalItem, type ToolOptions, type ToolResult, type Usage, type WebFetchToolOptions, type WebSearchToolOptions, WidgetNode, createAgentChatHandler, file, humanHandoff, humanReply, humanStatus, image, inputText, releaseToAgent, run, toAgentChatStream, tool, webFetch, webSearch };
@@ -1278,6 +1278,18 @@ function wireTools(agent, resolved = agent.tools) {
1278
1278
  }
1279
1279
  return tools;
1280
1280
  }
1281
+ function stepOf(agentName, usage, trace) {
1282
+ const t = trace ?? {};
1283
+ return {
1284
+ agentName,
1285
+ model: typeof t.model === "string" ? t.model : void 0,
1286
+ provider: typeof t.provider === "string" ? t.provider : void 0,
1287
+ usedFallback: t.used_fallback === true,
1288
+ usage: addUsage({ inputTokens: 0, outputTokens: 0, totalTokens: 0 }, usage),
1289
+ costUsd: Number(t.cost_usd) || 0,
1290
+ providerCostUsd: Number(t.provider_cost_usd) || 0
1291
+ };
1292
+ }
1281
1293
  function addUsage(total, usage) {
1282
1294
  const u = usage ?? {};
1283
1295
  return {
@@ -1340,10 +1352,10 @@ async function* consumeTurn(response, agentName, sessionId, items) {
1340
1352
  }
1341
1353
  case "turn.paused": {
1342
1354
  const actions = Array.isArray(data.actions) ? data.actions : [{ action_id: String(data.action_id), tool: String(data.tool), arguments: JSON.stringify(data.arguments?.[String(data.tool)] ?? {}) }];
1343
- return { kind: "paused", pause: { actionId: String(data.action_id), actions, text } };
1355
+ return { kind: "paused", pause: { actionId: String(data.action_id), actions, text }, usage: data.usage, trace: data.trace };
1344
1356
  }
1345
1357
  case "turn.completed":
1346
- return { kind: "completed", text: completedText(text, data), usage: data.usage };
1358
+ return { kind: "completed", text: completedText(text, data), usage: data.usage, trace: data.trace };
1347
1359
  case "owner.handling":
1348
1360
  return { kind: "with_human" };
1349
1361
  case "turn.failed": {
@@ -1365,6 +1377,8 @@ async function* runLoop(startAgent, input, options) {
1365
1377
  const agents = collectAgents(startAgent);
1366
1378
  const maxTurns = options.maxTurns ?? DEFAULT_MAX_TURNS;
1367
1379
  const items = [];
1380
+ const steps = [];
1381
+ const toolResults = [];
1368
1382
  const contextFor = (agent2, sessionId2) => {
1369
1383
  const ctx = {
1370
1384
  context: options.context,
@@ -1457,10 +1471,11 @@ async function* runLoop(startAgent, input, options) {
1457
1471
  response = void 0;
1458
1472
  if (outcome.kind === "with_human") {
1459
1473
  yield { type: "with_human" };
1460
- return { finalOutput: void 0, sessionId, lastAgent: agent, interruptions: [], state: void 0, newItems: items, usage, withHuman: true };
1474
+ return { finalOutput: void 0, sessionId, lastAgent: agent, interruptions: [], state: void 0, newItems: items, usage, steps, withHuman: true };
1461
1475
  }
1462
1476
  if (outcome.kind === "completed") {
1463
1477
  usage = addUsage(usage, outcome.usage);
1478
+ steps.push(stepOf(agent.name, outcome.usage, outcome.trace));
1464
1479
  let finalOutput = outcome.text;
1465
1480
  if (agent.outputType) {
1466
1481
  let parsed;
@@ -1474,11 +1489,13 @@ async function* runLoop(startAgent, input, options) {
1474
1489
  items.push({ type: "message", agentName: agent.name, text: outcome.text });
1475
1490
  const runContext2 = contextFor(agent, sessionId);
1476
1491
  for (const guardrail of agent.outputGuardrails) {
1477
- const verdict = await guardrail.execute({ output: finalOutput, agent, runContext: runContext2 });
1492
+ const verdict = await guardrail.execute({ output: finalOutput, agent, runContext: runContext2, toolResults });
1478
1493
  if (verdict.tripwireTriggered) throw new GuardrailTripwireTriggered("output", guardrail.name, verdict.outputInfo);
1479
1494
  }
1480
- return { finalOutput, sessionId, lastAgent: agent, interruptions: [], state: void 0, newItems: items, usage, withHuman: false };
1495
+ return { finalOutput, sessionId, lastAgent: agent, interruptions: [], state: void 0, newItems: items, usage, steps, withHuman: false };
1481
1496
  }
1497
+ usage = addUsage(usage, outcome.usage);
1498
+ steps.push(stepOf(agent.name, outcome.usage, outcome.trace));
1482
1499
  pending = outcome.pause;
1483
1500
  if (outcome.pause.text) items.push({ type: "message", agentName: agent.name, text: outcome.pause.text });
1484
1501
  for (const action of outcome.pause.actions) {
@@ -1515,7 +1532,7 @@ async function* runLoop(startAgent, input, options) {
1515
1532
  if (interruptions.length > 0) {
1516
1533
  const state = new RunState({ sessionId, agentName: agent.name, turnsUsed, usage, pending });
1517
1534
  yield { type: "interruption", interruptions };
1518
- return { finalOutput: void 0, sessionId, lastAgent: agent, interruptions, state, newItems: items, usage, withHuman: false };
1535
+ return { finalOutput: void 0, sessionId, lastAgent: agent, interruptions, state, newItems: items, usage, steps, withHuman: false };
1519
1536
  }
1520
1537
  if (turnsUsed >= maxTurns) throw new MaxTurnsExceededError(maxTurns, sessionId);
1521
1538
  let handoffTo;
@@ -1547,6 +1564,9 @@ async function* runLoop(startAgent, input, options) {
1547
1564
  yield { type: "widget", callId: action.action_id, widgetId: shown.widgetId, widget: shown.widget, agentName: agent.name };
1548
1565
  }
1549
1566
  const output = result.output;
1567
+ const finished = { callId: action.action_id, toolName: action.tool, arguments: action.arguments, output, agentName: agent.name };
1568
+ toolResults.push(finished);
1569
+ if (options.onToolEnd) await options.onToolEnd(finished, runContext);
1550
1570
  items.push({ type: "tool_output", agentName: agent.name, callId: action.action_id, toolName: action.tool, output });
1551
1571
  yield { type: "tool_output", callId: action.action_id, toolName: action.tool, output, agentName: agent.name };
1552
1572
  if (action.tool === HUMAN_HANDOFF_TOOL && !output.startsWith("Error")) {