Skip to content

Stream events ​

A turn is a conversation with notifications. After turn/start is accepted, Codex streams what it is doing, and your app turns those events into whatever it shows.

The shape of a turn ​

turn/started
  item/started          item = agentMessage | commandExecution | fileChange | reasoning | ...
    item/agentMessage/delta   (repeated)
  item/completed
  turn/diff/updated     aggregated file changes so far
  thread/tokenUsage/updated
turn/completed          status = completed | interrupted | failed

Every event carries threadId, and most carry turnId. Route by those identifiers rather than by arrival order, especially when several threads share one client.

Subscribe ​

ts
const stop = client.onNotification('item/agentMessage/delta', ({ params }) => {
  render(params.threadId, params.itemId, params.delta);
});

onNotification(method, listener) narrows params to that method. onNotification(listener) receives every notification, which suits logging or a custom reducer. Each registration returns an unsubscribe function. A listener that throws never affects other listeners or in-flight requests; the error goes to onListenerError.

Items are the unit of work ​

Each piece of work appears as a ThreadItem, delivered by item/started and item/completed with its final state. Use deltas for live rendering and the completed item as the authoritative record.

Item typeMeaningLive updates
agentMessageText addressed to the useritem/agentMessage/delta
reasoningReasoning summary and contentitem/reasoning/summaryTextDelta, item/reasoning/textDelta
planA proposed planitem/plan/delta, turn/plan/updated
commandExecutionA shell command and its outputitem/commandExecution/outputDelta
fileChangeA patch applied to filesitem/fileChange/outputDelta, item/fileChange/patchUpdated
mcpToolCallA tool call to an MCP serveritem/mcpToolCall/progress

Narrow on item.type to reach each variant's fields. The full list of items and methods is in the protocol inventory.

Finish a turn ​

turn/start resolves when the turn is admitted, not when it finishes. Wait for turn/completed and inspect turn.status and turn.error; a completed notification can carry a failed or interrupted turn. Events may arrive before the turn/start response resolves, so record them by turnId instead of assuming the order.

ts
import type { CodexAppServerClient, v2 } from '@korus-dev/codex-sdk';

export type TurnResult = {
  status: v2.TurnStatus;
  error: v2.TurnError | null;
  text: string;
  diff: string | null;
};

type TurnState = { text: string; diff: string | null; completed: v2.Turn | null };

/**
 * Runs one turn and resolves with its outcome. Events are recorded per turn ID,
 * so notifications that arrive before the `turn/start` response are not lost
 * and a late event from an earlier turn cannot finish this one.
 */
export async function runTurn(
  client: CodexAppServerClient,
  threadId: string,
  prompt: string,
  onText: (delta: string) => void = () => undefined,
): Promise<TurnResult> {
  const turns = new Map<string, TurnState>();
  const stateFor = (turnId: string): TurnState => {
    let state = turns.get(turnId);
    if (!state) {
      state = { text: '', diff: null, completed: null };
      turns.set(turnId, state);
    }
    return state;
  };

  let activeTurnId: string | null = null;
  const { promise, resolve, reject } = Promise.withResolvers<TurnResult>();
  const settleIfDone = () => {
    const state = activeTurnId === null ? undefined : turns.get(activeTurnId);
    if (state?.completed) {
      resolve({
        status: state.completed.status,
        error: state.completed.error,
        text: state.text,
        diff: state.diff,
      });
    }
  };

  const subscriptions = [
    client.onNotification('item/agentMessage/delta', ({ params }) => {
      if (params.threadId !== threadId) return;
      stateFor(params.turnId).text += params.delta;
      if (params.turnId === activeTurnId) onText(params.delta);
    }),
    client.onNotification('turn/diff/updated', ({ params }) => {
      if (params.threadId === threadId) stateFor(params.turnId).diff = params.diff;
    }),
    client.onNotification('turn/completed', ({ params }) => {
      if (params.threadId !== threadId) return;
      stateFor(params.turn.id).completed = params.turn;
      settleIfDone();
    }),
    client.onDisconnect(reject),
  ];

  try {
    const { turn } = await client.request('turn/start', {
      threadId,
      input: [{ type: 'text', text: prompt, text_elements: [] }],
    });
    activeTurnId = turn.id;
    settleIfDone();
    return await promise;
  } finally {
    for (const unsubscribe of subscriptions) unsubscribe();
  }
}

The helper accumulates text and the final diff per turn, ignores events from earlier turns, and rejects if the connection drops. turn/interrupt ends a turn early; it still finishes with a turn/completed notification.

Useful signals beyond the turn ​

  • thread/tokenUsage/updated reports context use for a progress meter.
  • thread/status/changed tells you when a thread becomes active or idle.
  • serverRequest/resolved dismisses an approval already answered elsewhere.
  • warning, configWarning, and deprecationNotice surface server-side problems worth showing or logging.
  • account/updated and account/rateLimits/updated report account changes.

To reduce traffic, pass optOutNotificationMethods in the initialize capabilities. Exact method names listed there are suppressed for that connection.

Released under the Apache License 2.0.