The pickaxe.agent method creates a new instance of an agent in Pickaxe.

Quick Reference

Usage Example

import { pickaxe } from "@hatchet-dev/pickaxe";
import z from "zod";
// TODO: Import your tools here
// Example: import { myTool } from "@/tools/my-tool";

const MyAgentInput = z.object({
  message: z.string(),
});

const MyAgentOutput = z.object({
  message: z.string(),
});

export const myToolbox = pickaxe.toolbox({
  // See pickaxe.toolbox documentation
  tools: [
    // TODO: Add your tools here
    // Example: myTool,
  ],
});

export const myAgent = pickaxe.agent({
  name: "my-agent",
  executionTimeout: "15m",
  inputSchema: MyAgentInput,
  outputSchema: MyAgentOutput,
  description: "Description of what this agent does",
  fn: async (input, ctx) => {
    const result = await myToolbox.pickAndRun({
      prompt: input.message,
    });

    switch (result.name) {
      // TODO: Handle your tool results here
      // Example:
      // case "myTool":
      //   return {
      //     message: `Result: ${result.output}`,
      //   };
      default:
        return myToolbox.assertExhaustive(result);
    }
  },
});

Parameters

ParameterTypeRequiredDescription
namestringYesA unique identifier for the agent. Used for workflow registration and execution.
descriptionstringYesA human-readable description of what the agent does and its purpose.
inputSchemaZodTypeYesZod schema that defines and validates the input structure for the agent.
outputSchemaZodTypeYesZod schema that defines and validates the output structure returned by the agent.
fn(input: z.infer<InputSchema>, ctx: DurableContext<z.infer<InputSchema>>) => Promise<z.infer<OutputSchema>>YesThe main agent function that processes input and returns output. Receives validated input and DurableContext.
executionTimeoutstringNoExecution timeout duration for the agent after it starts running. Go duration format (e.g., “1s”, “5m”, “1h”). Default: ”60s”
scheduleTimeoutstringNoSchedule timeout for the agent (max duration to allow the agent to wait in the queue). Go duration format. Default: “5m”
retriesnumberNoNumber of retries for the agent. Default: 0
concurrencyConcurrency | Concurrency[]NoConcurrency configuration for the agent. Controls how many concurrent executions are allowed.
defaultPriorityPriorityNoThe priority for the agent. Values: Priority.LOW (1), Priority.MEDIUM (2), Priority.HIGH (3)
onCronsstring[]NoCron config for the agent.
onEventsstring[]NoEvent config for the agent.

Concurrency Type

PropertyTypeRequiredDescription
expressionstringYesThe CEL expression to use for concurrency (e.g., “input.key”)
maxRunsnumberNoThe maximum number of concurrent workflow runs. Default: 1
limitStrategyConcurrencyLimitStrategyNoThe strategy to use when the concurrency limit is reached. Default: CANCEL_IN_PROGRESS

Returns

The pickaxe.agent method returns an AgentDeclaration<InputSchema, OutputSchema> object with the following properties and methods:

Properties

PropertyTypeDescription
inputSchemaInputSchemaThe Zod schema used for input validation
outputSchemaOutputSchemaThe Zod schema used for output validation
descriptionstringThe description of the agent
namestringThe unique name identifier for the agent
clientIHatchetClient | undefinedThe Hatchet client instance used to execute the workflow
definitionWorkflowDefinitionThe internal workflow definition

Methods

run(input, options?)

Executes the agent with the given input and waits for completion.

Parameters:

  • input: z.infer<InputSchema> - The input data for the agent
  • options?: RunOpts - Optional configuration for this agent run

Returns: Promise<z.infer<OutputSchema>> - A promise that resolves with the agent result

Throws: Error if the agent is not bound to a Hatchet client

runAndWait(input, options?)

Alias for run(). Triggers an agent run and waits for the result.

Parameters:

  • input: z.infer<InputSchema> - The input data for the agent
  • options?: RunOpts - Optional configuration for this agent run

Returns: Promise<z.infer<OutputSchema>> - A promise that resolves with the agent result

runNoWait(input, options?)

Triggers the agent execution without waiting for completion.

Parameters:

  • input: z.infer<InputSchema> - The input data for the agent
  • options?: RunOpts - Optional configuration for this agent run

Returns: Promise<WorkflowRunRef<z.infer<OutputSchema>>> - A WorkflowRunRef containing the run ID and methods to get results and interact with the run

Throws: Error if the agent is not bound to a Hatchet client

schedule(enqueueAt, input, options?)

Schedules the agent to run at a specific date and time in the future.

Parameters:

  • enqueueAt: Date - The date when the agent should be triggered
  • input: z.infer<InputSchema> - The input data for the agent
  • options?: RunOpts - Optional configuration for this agent run

Returns: Promise<ScheduledWorkflows> - A promise that resolves with the scheduled workflow details

Throws: Error if the agent is not bound to a Hatchet client

delay(duration, input, options?)

Schedules the agent to run after a specified delay.

Parameters:

  • duration: number - The delay in seconds before the agent should run
  • input: z.infer<InputSchema> - The input data for the agent
  • options?: RunOpts - Optional configuration for this agent run

Returns: Promise<ScheduledWorkflows> - A promise that resolves with the scheduled workflow details

Throws: Error if the agent is not bound to a Hatchet client

cron(name, expression, input, options?)

Creates a cron schedule for recurring agent execution.

Parameters:

  • name: string - The name of the cron schedule
  • expression: string - The cron expression defining the schedule
  • input: z.infer<InputSchema> - The input data for the agent
  • options?: RunOpts - Optional configuration for this agent run

Returns: Promise<CronWorkflows> - A promise that resolves with the cron workflow details

Throws: Error if the agent is not bound to a Hatchet client

RunOpts Type

PropertyTypeRequiredDescription
additionalMetadataRecord<string, string>NoAdditional metadata to attach to the workflow run
priorityPriorityNoThe priority for the workflow run. Values: Priority.LOW (1), Priority.MEDIUM (2), Priority.HIGH (3)

DurableContext

The ctx parameter in the agent function provides a DurableContext object that extends the standard workflow context with durable execution capabilities. This context persists across worker restarts and transient failures, making it essential for long-running agent workflows.

Core Properties

PropertyTypeDescription
inputTThe original input data for the agent
workflowRunId()() => stringGets the ID of the current workflow run
workflowName()() => stringGets the name of the current workflow
taskName()() => stringGets the name of the current running task
taskRunId()() => stringGets the ID of the current task run
workflowId()() => string | undefinedGets the workflow ID
workflowVersionId()() => string | undefinedGets the workflow version ID
cancelledbooleanGets cancellation status
controllerAbortControllerThe abort controller for the current task
loggerLoggerStructured logging methods (info, debug, warn, error)

Durable Execution Methods

MethodParametersReturnsDescription
sleepFor()duration: Duration, readableDataKey?: stringPromise<Record<string, any>>Pauses execution for a specified duration that persists across restarts
waitFor()conditions: [Conditions](#conditions-type) | [Conditions[]](#conditions-type)Promise<Record<string, any>>Waits for specific conditions to be met, persisting across failures

Execution Control

MethodParametersReturnsDescription
cancel()NonePromise<void>Cancels the current task
refreshTimeout()incrementBy: DurationPromise<void>Refreshes the timeout for the current task
retryCount()NonenumberGets the number of times the current task has been retried

Logging & Data Methods

MethodParametersReturnsDescription
putStream()data: string | Uint8ArrayPromise<void>Streams data from the current task run
additionalMetadata()NoneRecord<string, string>Retrieves additional metadata
errors()NoneRecord<string, string>Returns errors from any task runs in the workflow
triggers()NoneTriggerDataGets the dag conditional triggers for the current workflow run
filterPayload()NoneRecord<string, any>Gets the payload from the filter that matched when triggering the event
triggeredByEvent()NonebooleanDetermines if the workflow was triggered by an event
priority()NonePriority | undefinedGets the priority of the workflow

Conditions Type

The Conditions type defines criteria that the agent can wait for during durable execution:

Condition TypeDescription
SleepSleep for a specified duration
UserEventWait for a specific user event to be triggered
ParentWait for parent task completion

Conditions can be combined using Or() for complex conditional logic.

Duration Format

Durations use a subset of Go duration string format with single suffixes only:

FormatDescription
"1s"1 second
"5m"5 minutes
"1h"1 hour