Agent SDK · Running agents

Run.

Run a prompt to completion and get the final output.

runner.run(agent, input, options?)

Runs an agent turn and returns the complete result. Internally streams and collects all events.

TypeScript
import { Runner } from '@maincode-ai/matilda-agent-sdk';

const runner = new Runner();

const result = await runner.run(
  { name: 'helper', instructions: 'Be concise.' },
  'What is the capital of Australia?',
  {
    conversationId: 'conv-123',
    responseMode: 'instant',
    callbacks: {
      onToken: (delta) => process.stdout.write(delta),
      onDone: () => console.log('\n[done]'),
    },
  },
);

console.log(result.finalOutput);
console.log(result.usage);

AgentRunOptions

Extends RequestOptions. All fields optional.

Fieldtypedescription
signalAbortSignalAbort the run.
conversationIdstringAssociates this turn with a conversation thread. Auto-generated when omitted.
fileIdsstring[]File IDs to attach (from files.upload()).
clientToolsClientTool[]Client tools to advertise for this turn.
contextstringOverride the agent's context.
responseModeChatResponseModeOverride the response mode.
responseSchemastringRaw JSON Schema (as a string) to grammar-constrain the response to. Prefer runner.runObject / runner.streamObject, which convert a zod schema for you.
stallTimeoutMsnumberSSE stall watchdog timeout in ms. Defaults to 45_000. Pass 0 to disable.
metadataRecord<string, unknown>Custom data available to dynamic instructions.
toolHandlersToolHandlersHandlers for client tools.
maxToolRoundtripsnumberMaximum tool roundtrip cycles before stopping. Defaults to 25.
maxRetriesnumberMaximum retries on retryable errors (5xx, 429, 408, network). Defaults to 0.
throwOnStreamErrorbooleanThrow MatildaAgentStreamError if the stream emits an error event. Defaults to true.
callbacksAgentCallbacksCallback hooks for events (see below).
coreMatildaCoreOverride the runner's core for this run.
fingerprintstringDevice fingerprint for rate limiting.
accessTokenstringOverride the core-level access token for this request.
Note

Prefer runner.runObject / runner.streamObject over responseSchema — they convert a zod schema for you; see Structured output. Client tool handlers are wired up in Client tools.

AgentCallbacks

Simple callback hooks that fire as events arrive. An alternative to manually iterating stream().

TypeScript
const result = await runner.run(agent, input, {
  callbacks: {
    onToken: (delta) => process.stdout.write(delta),
    onToolCall: (name, args) => console.log(`Tool: ${name}`),
    onToolResult: (name, result, isError) => console.log(`Result: ${result}`),
    onUsage: (usage) => console.log(`Tokens: ${usage.output_tokens}`),
    onError: (code, message) => console.error(`Error: ${code}`),
    onRetry: (attempt, error, delayMs) => console.log(`Retry ${attempt} in ${delayMs}ms`),
    onDone: () => console.log('Done'),
  },
});
Fieldtypedescription
onEvent(event: AgentRunEvent) => voidEvery event — catch-all, fires before the typed hooks below. Useful for telemetry, UI plumbing, or event logging.
onToken(delta: string) => voidA text chunk arrives.
onToolCall(name: string, args: Record<string, unknown>) => voidThe agent calls a client tool.
onToolResult(name: string, result: string, isError: boolean) => voidA client tool handler returns.
onUsage(usage: UsageEvent) => voidToken usage data arrives.
onError(code: ChatErrorCode, message: string) => voidA stream error occurs.
onRetry(attempt: number, error: { code: string; message: string }, delayMs: number) => voidA retryable error triggers a retry.
onDone() => voidThe stream finishes. Fires per-turn in multi-turn tool loops.

AgentRunResult

Fieldtypedescription
agentNamestringThe agent's name.
finalOutputstringThe full assistant response text. Accumulated from message.delta events.
eventsAgentRunEvent[]Every event emitted during the run.
streamIdstring | undefinedDurable stream ID (from stream.started event).
lastEventIdstring | undefinedLast stream event ID (for resume).
usageUsageEvent | undefinedToken usage. Accumulated across multi-roundtrip runs.
errorsArray<{ code: ChatErrorCode; message: string }>Any errors emitted during the run.
truncatedReasonstring | undefinedWhy the response was truncated (e.g. 'max_tokens', 'max_tool_roundtrips').
safetyReplace{ message: string; categories: string[] } | undefinedSet when the backend replaced the answer for safety. finalOutput holds the replacement text.

throwOnStreamError: false

By default, run() throws MatildaAgentStreamError if the stream emits an error event. Pass throwOnStreamError: false to suppress the throw and inspect errors on the returned result instead:

TypeScript
const result = await runner.run(agent, input, { throwOnStreamError: false });

if (result.errors.length > 0) {
  for (const err of result.errors) {
    console.log(`${err.code}: ${err.message}`);
  }
}
console.log('Partial output:', result.finalOutput || '(none)');