---
title: "Pause and Resume Agents with stopWhen Code Agent SDK"
source: https://docs.autohand.ai/agent-sdk/io/step-control
---

# Pause and resume agents with `stopWhen`

Use a stop condition to pause a TypeScript SDK run after a completed tool step. You can inspect the ordered step record, apply application policy, and continue with the same Agent and conversation state.

**Availability:** Per-step `stopWhen` control is currently a TypeScript SDK feature. Omitting `stopWhen` preserves the normal run-to-completion behavior.

## Quick start

Stop after the first completed tool step, inspect what happened, then continue the same session:

``` typescript
import { Agent, isStepCount } from '@autohandai/agent-sdk';

const agent = await Agent.create({ cwd: '.' });

try {
  const inspected = await agent.run(
    'Read package.json, then explain the package.',
    { stopWhen: isStepCount(1) },
  );

  if (inspected.status === 'stopped') {
    console.log(inspected.steps);

    const completed = await agent.run(
      'Continue from the completed tool result.',
    );
    console.log(completed.text);
  }
} finally {
  await agent.close();
}
```

Continuation is another call to `agent.run()` on the same agent. The CLI persists the tool result before the SDK evaluates the condition, so the next prompt sees the completed step.

## Built-in stop conditions

| Helper | Stops when | Validation |
|---|---|---|
| isStepCount(count) | The accumulated completed-step count reaches count. | count must be a positive integer. |
| hasToolCall(toolName) | The latest completed step called the named tool. | toolName must be a non-empty string. |

``` typescript
import {
  hasToolCall,
  isStepCount,
} from '@autohandai/agent-sdk';

const result = await agent.run('Inspect the repository safely.', {
  stopWhen: [
    isStepCount(3),
    hasToolCall('write_file'),
  ],
});
```

When you provide an array, all conditions are evaluated and the run stops when any condition returns `true`.

## Write a custom condition

A `StopCondition` receives the ordered completed steps and may return a boolean synchronously or asynchronously.

``` typescript
import type { StopCondition } from '@autohandai/agent-sdk';

const stopAfterSuccessfulWrite: StopCondition = async ({ steps }) => {
  const latest = steps.at(-1);

  return latest?.toolResults.some(
    (result) =>
      result.tool === 'write_file' &&
      result.success,
  ) ?? false;
};
```

If a predicate throws, the SDK first completes the CLI stop handshake at that step boundary and then surfaces the predicate error. This prevents the subprocess from waiting indefinitely for a decision.

## Result and step contract

`agent.run()` returns a `RunResult` with `status` set to `completed`, `aborted`, or `stopped`. Every result includes its buffered events and completed steps.

``` typescript
interface RunResult {
  id: string;
  status: 'completed' | 'aborted' | 'stopped';
  text: string;
  events: SDKEvent[];
  steps: AgentStep[];
}

interface AgentStep {
  stepNumber: number;
  thought?: string;
  toolCalls: AgentStepToolCall[];
  toolResults: AgentStepToolResult[];
}
```

Tool calls expose their tool name and validated arguments. Tool results expose the tool name, success state, and available output or error.

## Observe step boundaries

A controlled run includes a typed `step_end` event after each completed tool step. The terminal `turn_end` event reports `reason: 'stop_condition'`, and `agent_end` completes with a stopped reason.

``` typescript
const run = await agent.send('Inspect the package.', {
  stopWhen: isStepCount(1),
});

for await (const event of run.stream()) {
  if (event.type === 'step_end') {
    console.log(event.step.stepNumber);
    console.log(event.step.toolResults);
  }
}

const result = await run.wait();
```

## Execution semantics

-   Conditions run only after every tool call in the current step finishes and its results are stored in conversation history.
-   A text-only terminal response has no tool-step boundary and completes normally.
-   Completed steps accumulate for the current run and are passed to every condition in order.
-   Stopping pauses the result; it does not close the `Agent` or discard session history.
-   Use `finally` to close the agent when the application is finished.

## When to use step control

-   **Human review:** pause after the agent inspects files but before another step begins.
-   **Write gates:** stop when a write-capable tool appears and require application approval.
-   **Budgets:** cap the number of tool steps performed by one run.
-   **Workflow composition:** divide a long agent task into explicit, inspectable application stages.