@mastra/core
Version:
203 lines (202 loc) • 8.25 kB
JavaScript
import { i as createObservabilityContext } from "../../observability-Cz-X7NF_.js";
import { a as AgentStreamEventTypes, i as AGENT_STREAM_TOPIC, o as DurableAgentDefaults, s as DurableStepIds } from "../../agent-Dj30gJa3.js";
import { A as emitFinishEvent, B as serializeDurableState, C as baseIterationStateSchema, D as createDurableAgentStream, E as modelListEntrySchema, F as RunRegistry, H as serializeToolsMetadata, I as globalRunRegistry, L as prepareForDurableExecution, M as emitStepStartEvent, N as emitSuspendedEvent, O as emitChunkEvent, P as ExtendedRunRegistry, R as createWorkflowInput, S as baseDurableAgenticInputSchema, T as modelConfigSchema, U as runDurableStreamUntilIdle, V as serializeModelConfig, W as runResumeDurableStreamUntilIdle, _ as resolveDurableToolCallConcurrency, a as DurableAgent, b as createBaseIterationStateUpdate, c as createDurableToolCallStep, d as resolveInternalState, f as resolveModel, g as createDurableBackgroundTaskCheckStep, h as toolRequiresApproval, i as isLocalDurableAgent, j as emitStepFinishEvent, k as emitErrorEvent, l as createDurableLLMExecutionStep, m as resolveTool, o as createDurableAgenticWorkflow, p as resolveRuntimeDependencies, r as isDurableAgent, s as createDurableLLMMappingStep, t as createDurableAgent, u as rebuildRunToolsFromMastra, v as buildStepRecord, w as durableAgenticOutputSchema, x as accumulatedUsageSchema, y as calculateAccumulatedUsage, z as serializeDurableOptions } from "../../create-durable-agent-CmEJXplU.js";
//#region src/agent/durable/workflows/shared/execute-tool-calls.ts
/**
* Execute tool calls durably with optional hooks for observability and streaming.
*
* This is the shared implementation used by:
* - Core DurableAgent workflow
* - Inngest durable agent workflow (with observability hooks)
* - Evented durable agent workflow
*
* @param ctx - Tool execution context with tool calls, resolved tools, and optional hooks
* @returns Array of tool call outputs with results or errors
*/
async function executeDurableToolCalls(ctx) {
const toolResults = [];
for (const toolCall of ctx.toolCalls) {
if (toolCall.providerExecuted && toolCall.output !== void 0) {
toolResults.push({
...toolCall,
result: toolCall.output
});
continue;
}
const tool = ctx.tools[toolCall.toolName];
if (!tool) {
const error = {
name: "ToolNotFoundError",
message: `Tool ${toolCall.toolName} not found`
};
await ctx.onToolError?.(toolCall, error);
toolResults.push({
...toolCall,
error
});
continue;
}
await ctx.onToolStart?.(toolCall);
try {
if (tool.execute) {
const result = await tool.execute(toolCall.args, {
toolCallId: toolCall.toolCallId,
messages: [],
workspace: ctx.workspace,
requestContext: ctx.requestContext
});
await ctx.onToolResult?.(toolCall, result);
toolResults.push({
...toolCall,
result
});
} else {
await ctx.onToolResult?.(toolCall, void 0);
toolResults.push({
...toolCall,
result: void 0
});
}
} catch (error) {
const toolError = {
name: "ToolExecutionError",
message: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : void 0
};
await ctx.onToolError?.(toolCall, toolError);
toolResults.push({
...toolCall,
error: toolError
});
}
}
return toolResults;
}
//#endregion
//#region src/agent/durable/evented-agent.ts
/**
* EventedAgent - A durable agent that uses fire-and-forget execution.
*
* EventedAgent extends DurableAgent and overrides the execution strategy to use
* fire-and-forget execution via the workflow engine's startAsync() method.
*
* Unlike DurableAgent which runs the workflow synchronously, EventedAgent:
* 1. Uses startAsync() for non-blocking execution
* 2. Fire-and-forget pattern - execution starts and returns immediately
* 3. Events are streamed via pubsub as the workflow executes
*/
/**
* EventedAgent extends DurableAgent to use fire-and-forget execution.
*
* This agent type uses the built-in evented workflow engine, which is useful when:
* - You don't need an external execution engine (like Inngest)
* - You want fire-and-forget execution with pubsub streaming
* - You need resumable streams with event caching
*
* The key difference from DurableAgent is the execution strategy:
* - DurableAgent: Runs the workflow synchronously via createRun + start
* - EventedAgent: Uses run.startAsync() for fire-and-forget execution
*
* @example
* ```typescript
* import { Agent } from '@mastra/core/agent';
* import { EventedAgent } from '@mastra/core/agent/durable';
*
* const agent = new Agent({
* id: 'my-agent',
* instructions: 'You are a helpful assistant',
* model: openai('gpt-4'),
* });
*
* const eventedAgent = new EventedAgent({ agent });
*
* const { output, runId, cleanup } = await eventedAgent.stream('Hello!');
* const text = await output.text;
* cleanup();
* ```
*/
var EventedAgent = class extends DurableAgent {
/**
* Create a new EventedAgent that wraps an existing Agent
*/
constructor(config) {
super(config);
}
/**
* Execute the durable workflow using fire-and-forget pattern.
*
* Unlike DurableAgent which runs the workflow synchronously, EventedAgent uses
* the workflow's startAsync() method for non-blocking execution.
*
* @param runId - The unique run ID
* @param workflowInput - The serialized workflow input
* @internal
*/
async executeWorkflow(runId, workflowInput) {
try {
const run = await this.getWorkflow().createRun({
runId,
pubsub: this.pubsubInternal
});
const entry = globalRunRegistry.get(runId);
await run.startAsync({
inputData: workflowInput,
requestContext: entry?.requestContext,
actor: workflowInput.options?.actor,
...createObservabilityContext({ currentSpan: entry?.agentSpan })
});
} catch (error) {
await this.emitError(runId, error instanceof Error ? error : new Error(String(error)));
}
}
};
/**
* Check if an object is an EventedAgent class instance
*/
function isEventedAgentClass(obj) {
return obj instanceof EventedAgent;
}
//#endregion
//#region src/agent/durable/create-evented-agent.ts
/**
* Create an EventedAgent that wraps an existing Agent.
*
* This factory function creates an EventedAgent instance with fire-and-forget
* execution via the built-in workflow engine.
*
* @param options - Configuration options
* @returns An EventedAgent instance
*
* @example
* ```typescript
* const agent = new Agent({
* id: 'my-agent',
* instructions: 'You are helpful',
* model: openai('gpt-4'),
* });
*
* const eventedAgent = createEventedAgent({ agent });
*
* const mastra = new Mastra({
* agents: { myAgent: eventedAgent },
* });
* ```
*/
function createEventedAgent(options) {
const { agent, pubsub, cache, maxSteps } = options;
return new EventedAgent({
agent,
pubsub,
cache,
maxSteps
});
}
/**
* Check if an object is an EventedAgent
*/
function isEventedAgent(obj) {
return obj instanceof EventedAgent;
}
//#endregion
export { AGENT_STREAM_TOPIC, AgentStreamEventTypes, DurableAgent, DurableAgentDefaults, DurableStepIds, EventedAgent, ExtendedRunRegistry, RunRegistry, accumulatedUsageSchema, baseDurableAgenticInputSchema, baseIterationStateSchema, buildStepRecord, calculateAccumulatedUsage, createBaseIterationStateUpdate, createDurableAgent, createDurableAgentStream, createDurableAgenticWorkflow, createDurableBackgroundTaskCheckStep, createDurableLLMExecutionStep, createDurableLLMMappingStep, createDurableToolCallStep, createEventedAgent, createWorkflowInput, durableAgenticOutputSchema, emitChunkEvent, emitErrorEvent, emitFinishEvent, emitStepFinishEvent, emitStepStartEvent, emitSuspendedEvent, executeDurableToolCalls, globalRunRegistry, isDurableAgent, isEventedAgent, isEventedAgentClass, isLocalDurableAgent, modelConfigSchema, modelListEntrySchema, prepareForDurableExecution, rebuildRunToolsFromMastra, resolveDurableToolCallConcurrency, resolveInternalState, resolveModel, resolveRuntimeDependencies, resolveTool, runDurableStreamUntilIdle, runResumeDurableStreamUntilIdle, serializeDurableOptions, serializeDurableState, serializeModelConfig, serializeToolsMetadata, toolRequiresApproval };
//# sourceMappingURL=index.js.map