# What should an agent report when a tool is still running at the end of a turn?

URL: https://www.getpleach.com/blog/what-an-agent-should-report-when-a-tool-is-still-running-at-turn-end
Published: 2026-11-29

> A tool call that is still open when its turn ends has no known outcome. Pleach closes it on the record as outcome unknown rather than as a failure, labels a call that never started as not-started, and lets a later real result replace the closure. Here is each case, the reader code that honours it, and what core does not do yet.

_Drafted by an AI agent, from the Pleach docs and package source; reviewed by a maintainer before publishing._

_No @pleach/* package is on npm yet. Each name holds a 0.0.1 placeholder until its first release, so the code here describes the source, not an install that works today. [Package status](https://www.getpleach.com/docs/packages)._

**A tool call that is still running when its turn ends has no known outcome, so the record should say exactly that: the call was closed because the turn ended, not because the tool was seen to fail.** Pleach now does this. When the system cuts a turn short, each open call gets a synthetic `tool.failed` with `outcomeKnown: false`. A call that never started gets its own `not-started` failure label. A real result that arrives after the closure supersedes it.

Before this, the event log could hold a `tool.started` with nothing after it. Every reader that pairs a start with a terminal saw a call that ran forever. The turn's answer couldn't say why it was empty, so the user got the generic "please rephrase" fallback for a request that had nothing wrong with it.

This post covers the three outcomes a tool call can have at turn end, what the runtime emits for each, the reader code that keeps them apart, and what core doesn't do yet. For how a stopped turn is recorded, see [Aborting a turn](/docs/session-runtime#aborting-a-turn). For the row fields, see [What a tool row holds](/docs/event-log#what-a-tool-row-holds).

## Three outcomes, not two

A tool call has one of three outcomes when its turn ends. Most agent loops record only two of them.

| What happened | What the runtime knows | What Pleach records |
|---|---|---|
| The tool ran and returned | Its result or its error | `tool.completed`, or `tool.failed` with `failure_class` `fault` (or `guard-refusal` for a refusal) |
| The tool was never dispatched | That it didn't run | `tool.failed` with `failure_class: "not-started"` |
| The tool was dispatched and the turn ended first | Nothing about the result | Flat `tool.failed` with `outcomeKnown: false`, error code `TOOL_TIMEOUT` or `ABORTED` |

A two-outcome model files the second and third rows under "failed", and the two mistakes cost different things.

Calling a never-started tool a "fault" sends someone looking for a bug in the tool when the real cause was a backend that wasn't up yet. Excluding it from error totals is wrong too, because then a backend outage vanishes from your dashboards. The `not-started` label keeps the cause honest and the outage visible: `detectAnomalies` counts it as an error, and only `guard-refusal` is left out.

Calling an open call "failed" is worse, because it may not have failed at all. The work may have finished a second after the deadline, or it may still be running on a backend that will finish it. A retry built on "it failed" can run a side-effecting tool twice.

## Why a call is left open

A turn ends while a tool is in flight for a few ordinary reasons:

- The turn reaches its deadline (abort reason `"timeout"`).
- The host shuts the runtime down (`"shutdown"`).
- The turn errors, which is also how an unclassified signal abort or a client disconnect with no stop intent is latched (`"error"`).
- Every model in the turn's provider family has been tried (`"provider-exhausted"`).

In each case the runtime unwinds between supersteps, and the tool's own completion never reaches the stream. The event log keeps the `tool.started` row and gets no terminal row for it.

## What the runtime emits at turn end

The runtime follows every `tool.started` and every terminal on the turn's own stream, in both the nested `{ toolCall: { id, name } }` shape and the flat `{ toolCallId, toolName }` shape. A real terminal that arrives removes its call from the open set. When a turn ends for a system reason, every call still open gets one terminal:

```json
{
  "type": "tool.failed",
  "toolCallId": "call_7f3a",
  "toolName": "fetch_structure",
  "hasError": true,
  "error": "TIMED_OUT: tool \"fetch_structure\" returned no result before the turn's deadline (open 41200 ms)",
  "error_code": "TOOL_TIMEOUT",
  "outcomeKnown": false,
  "turnAbortReason": "timeout",
  "msOpen": 41200,
  "ledgerOnly": true
}
```

The code depends on why the turn ended:

- **Deadline (`"timeout"`)**: `TOOL_TIMEOUT`, with the error text starting `TIMED_OUT:`. Only this case changes the answer's wording, covered below.
- **Any other system reason**: `ABORTED`, with the error text starting `ABORTED:`. The call is still closed so the ledger never shows it running forever, but nothing claims it timed out.
- **User Stop**: no closure. Only an explicit user abort means Stop, and a stopped turn's calls end the way their own path ends them.

The closure is idempotent. A call is closed at most once, and a call whose real terminal arrived first is never closed. It uses the same flat, ledger-only shape the runtime already emits for a call it resolved without dispatching, so a frame writer or client reducer that handles that shape settles this one without a new branch.

## The async job exception

One kind of open call is deliberately left open: a call that is waiting on an async job that is still running.

An async tool reports its own terminal when it submits the job: the dispatcher emits `tool.completed` with the receipt. So when a call is still open at turn end and it names a pending job, it is a wait or status read on that job. The job's own "still running" message is the true account of where things stand, and a synthetic failure would contradict it.

The runtime decides a call is waiting only when one of its arguments names a pending job. That means a `job:<id>` ref anywhere in the arguments, or a plain string under a `job_id`, `jobId`, `job_ids` or `jobIds` key, up to one array level deep. It never matches by tool name, because a call to the same tool as some unrelated pending job has nothing to do with it, and leaving that call open would recreate the original defect. The pending set is the host's `getPendingJobs` provider combined with the async receipts the turn's own stream carried, so a host that never configured a job provider is covered too.

## What the user sees

Closing the record is half the fix. The other half is what the user reads when the turn produced no answer.

When the deadline cut the turn short, no answer was produced, and one or more calls not waiting on a pending job were still open, the final message names the cause instead of asking for a rephrase. The default is brand-free:

> I wasn't able to produce a response because a tool didn't return a result before this turn ended, so there is nothing to show yet. Nothing is wrong with your request; please try again in a moment.

A host replaces it with `toolTimeoutTerminalMessage` on the [`SessionRuntimeConfig`](/docs/session-runtime#sessionruntimeconfig-fields):

```typescript
const runtime = new SessionRuntime({
  // ...
  toolTimeoutTerminalMessage:
    "A lookup took longer than this turn allows, so there's no answer yet. Try again in a minute.",
});
```

It is a fixed string, not a template. The runtime's canned-stub recognisers match by exact value, and the runtime adds the string to the session's stub roster, so later code can still tell it apart from a model-written answer. Keep its opening phrase recognisable to any stub-marker list your host keeps.

Only a deadline changes this copy. A shutdown or a provider exhaustion closes the open calls on the record and leaves the answer to the path that already handles that case.

## Reading the closure correctly

Emitting `outcomeKnown: false` only helps if every reader honours it. A reader that pairs calls with terminals needs two rules:

1. **An unknown-outcome terminal isn't a failure and isn't an executed call.** Don't count it in failure rates, and don't count it as a step completed.
2. **A later real terminal for the same call id replaces it.** The runtime passes a late real result through unchanged, so the reader has to let it win.

`@pleach/core/runtime` exports the two helpers that make this short. `isUnknownOutcomeTerminal(event)` is a type guard that matches only the synthetic closure. `toolEventCallIdentity(event)` reads the call id and name from either event shape.

```typescript
import { isUnknownOutcomeTerminal, toolEventCallIdentity } from "@pleach/core/runtime";

type CallOutcome = "known" | "unknown";
const outcomes = new Map<string, { outcome: CallOutcome; event: unknown }>();

for await (const event of runtime.executeMessage(sessionId, prompt, { abortSignal })) {
  if (event.type !== "tool.completed" && event.type !== "tool.failed") continue;
  const { id } = toolEventCallIdentity(event);
  if (id === null) continue;

  if (isUnknownOutcomeTerminal(event)) {
    // Never let the synthetic closure overwrite a real terminal.
    if (!outcomes.has(id)) outcomes.set(id, { outcome: "unknown", event });
    continue;
  }
  // A real terminal always wins, including one that arrives after the closure.
  outcomes.set(id, { outcome: "known", event });
}
```

Classify the "known" entries the way you already do. A `tool.completed` can itself report a failure status, so keep using your existing success and failure rule for those. Show the "unknown" entries as their own state, such as "outcome unknown", rather than as an error.

If you store these rows, write the closure as one row per call and don't let it take the call's terminal slot. Otherwise a real result that arrives later has nowhere to land, and the record keeps the guess.

## Which core readers honour it

Core's own readers follow both rules, from the change merged on 2026-11-30. On earlier builds they settle on the first terminal and count the closure as a failure.

- **The stream reducer** behind `useHarness` (`applyStreamEvent`) marks the part `outcomeKnown: false` and lets a later real terminal replace it. See [Tool parts](/docs/react#tool-parts).
- **The AI SDK adapter** (`toUIMessageChunks`, `toUIMessageStreamResponse`) settles the closure as a `tool-output-error` with fixed "outcome unknown" text, which `unknownOutcomeErrorText` replaces and `onError` never masks, then still emits a later real result so `useChat` replaces the part. See [the AI SDK options](/docs/providers).
- **The query aggregates** read the stored row's `outcome_known: false`: `detectAnomalies` reports it in `unknownOutcomes` instead of `errors`, and `getToolEffectiveness` doesn't count it as an invocation. See [Cross-session analytics](/docs/query#cross-session-analytics).

## What core does not do yet

- **A result that arrives after the answer ends doesn't reach the AI SDK client.** The adapter stops at `finish`, and the closure is emitted just before the answer completes. A later result, such as one delivered by a job callback, reaches the user only through your own store.
- **Closing a call on the record doesn't stop the work behind it.** A backend that has already accepted the work may still finish it. Treat an unknown outcome as "check before retrying", above all for a tool with side effects.
- **`not-started` is only as good as its producer.** Core adds the label and counts it, but a producer has to stamp it, and only when it positively knows the call was never dispatched. Core never infers it from missing evidence that the tool ran, and your producer shouldn't either.

## Worked example: a structure lookup that outlives its turn

A turn has a 40-second deadline. The model calls `fetch_structure`, whose backend is slow today.

1. At 0 s the runtime emits `tool.started` for `call_7f3a`.
2. At 40 s the deadline fires. The call names no pending job, so the runtime emits the flat `tool.failed` above with `outcomeKnown: false` and `TOOL_TIMEOUT`.
3. The turn has no answer, and the open call is the only reason. The user reads the tool-timeout message, not "please rephrase".
4. At 41 s the backend returns. The real `tool.completed` for `call_7f3a` passes through unchanged. A reader using the loop above, or core's reducer, replaces "unknown" with the real result if it is still reading the stream. A reader that settles on the first terminal keeps the closure.

Change step 1 so that the backend is still starting and the call is never dispatched. The producer stamps `not-started`, and the turn records a known outcome (the tool didn't run) that counts toward error totals. A retry is safe here because nothing ran.

## Key takeaways

- A tool call at turn end has three outcomes: it ran, it never started, or nobody knows. Record all three.
- When the system ends a turn, Pleach closes each open call with `outcomeKnown: false`: `TOOL_TIMEOUT` for a deadline, `ABORTED` otherwise. A user Stop never closes calls.
- A call waiting on a pending async job is left open, matched by the job its arguments name, never by tool name.
- A deadline with no answer gets a message naming the tool timeout, which `toolTimeoutTerminalMessage` can replace.
- Readers must treat the closure as neither a failure nor an executed call, and must let a later real result replace it. `isUnknownOutcomeTerminal` and `toolEventCallIdentity` from `@pleach/core/runtime` do the pairing.
- Core's AI SDK adapter and query aggregates don't honour the flag yet, so filter on `outcomeKnown` yourself where the split matters.

## Frequently asked

### What does Pleach record for a tool that is still running when a turn ends?

When the system ends the turn (its deadline, a shutdown, an error or provider exhaustion), the runtime emits one flat tool.failed event for each call still open, with outcomeKnown set to false. The error code is TOOL_TIMEOUT when the turn hit its deadline and ABORTED for any other system reason. The event closes the call on the record. It doesn't claim the tool failed.

### Does a user pressing Stop close open tool calls the same way?

No. A user Stop never triggers the closure. A stopped turn's calls keep whatever ending their own path gives them, because only an explicit user abort means Stop and that case already has its own handling.

### What happens if the real tool result arrives after the turn ended?

The runtime passes it through unchanged. The synthetic closure is marked outcomeKnown false so that any real terminal for the same call id supersedes it. A reader that pairs each call with its terminal should prefer the real one, and isUnknownOutcomeTerminal from @pleach/core/runtime tells the two apart.

### How is a tool that never started different from one whose outcome is unknown?

A tool.failed row whose failure_class is not-started means the producer positively knows the call was never dispatched, for example because the backend it needs was still starting. That is a known outcome. The tool didn't run, and detectAnomalies counts it as an error. An unknown outcome means the call was dispatched and no one observed how it ended, so detectAnomalies reports it in unknownOutcomes, not in errors.

### Will the answer still ask the user to rephrase when a tool timed out?

No. When the deadline cut the turn short, no answer was produced, and an open tool call is the only explanation, the turn's final message says a tool didn't return a result in time and to try again. The host can replace that text with toolTimeoutTerminalMessage on the session runtime config.
