The Agent Loop and the Event Model

Lesson 2: The Agent Loop and the Event Model

In production you will never see the agent's reasoning directly. You will see a stream of typed events. Getting fluent with that stream is what separates "it worked in the demo" from "I can debug a 40-turn run at 2am". This lesson covers the loop that generates the events, the events themselves, and the two completion signals that trip almost everyone up.

A turn is exactly one LLM API call

The CLI's loop is mechanical: send the full conversation history to the model; if the model asked for tools, execute them and feed the results back as the next turn's input; repeat until the model answers without requesting a tool. Each iteration is one turn.

session.send LLM call = 1 turn tools? Execute tools collect results Final text no tools results fed back as next turn input session.idle

Two facts follow directly from this, and both matter operationally:

  1. The model sees the full accumulated context on every call โ€” system prompt, user messages, every prior tool call and result.
  2. There are no hidden calls. The number of assistant.turn_start / assistant.turn_end pairs in the event log equals the number of LLM API calls made. No separate planning call, no evaluation call, no completion-check call.
Why "no hidden calls" is worth memorising: it is the foundation of cost attribution. If a session cost more than expected, the turn count tells you it was more model round-trips, not a mystery surcharge. You can count turns straight off the event log:
grep -c "assistant.turn_start" ~/.copilot/session-state/<sessionId>/events.jsonl

The model is the decision-maker for when to stop. The CLI is purely mechanical: "model asked for tools โ†’ execute โ†’ call model again."

The two completion signals โ€” and why this distinction bites people

This is the most consequential API distinction in the whole SDK.

session.idlesession.task_complete
EmittedAlways โ€” when the loop endsOptionally โ€” requires the model to signal it
Persisted?No โ€” ephemeral, not replayed on resumeYes โ€” saved to the session event log
Means"Stopped processing, ready for the next message""I consider the overall task fulfilled"
Carriesโ€”Optional summary field
Use it forYour reliable "done" signal, timeouts, error handlingBest-effort task-done detection

sendAndWait() waits for session.idle:

// Blocks until session.idle fires, then returns the final assistant message
const response = await session.sendAndWait({ prompt: "Fix the bug" });

// Or drive it yourself and treat task_complete as advisory
session.on("session.task_complete", (event) => {
  console.log("Task done:", event.data.summary);
});

Why does task_complete go missing in normal chat? Because in interactive mode the CLI does not nudge for it. If you ask a conversational question, there is no discrete "task" to complete, so the model just answers and stops. session.idle still fires, because it is a mechanical signal (the loop ended), not a semantic one (the model thinks it is done).

Never gate a production workflow on task_complete alone. If you wait for it and it never arrives, your job hangs forever while the agent has already finished. Gate on session.idle, and optionally record task_complete for richer reporting.

Autopilot nudges โ€” a two-level completion mechanism

In autopilot mode (headless, autonomous work), the CLI actively tracks whether the model called task_complete. If the loop ends without it, the CLI injects a synthetic user message that restarts the loop โ€” roughly:

"You have not yet marked the task as complete using the task_complete tool. If you were planning, stop planning and start implementing."

The nudge also instructs the model not to claim completion if it has open questions, hit an error, or left steps undone. The practical effect: in autopilot, "the agent stopped" is not the same as "the agent gave up". This is why autonomous runs behave differently from chat runs, and why you must budget for the extra turns a nudge loop can generate.

The event envelope

Every event, whatever its type, carries the same envelope. Learn these six fields once and every event becomes parseable:

FieldTypeMeaning
idstring (UUID v4)Unique event identifier
timestampstring (ISO 8601)When the event was created
parentIdstring | nullPrevious event in the chain โ€” a linkable list. null for the first.
agentIdstring?Sub-agent instance ID. Absent for the root agent and for session-level events.
ephemeralboolean?true = streamed live but not persisted, not replayed on resume
type + datastring + objectDiscriminator plus type-specific payload
agentId is your free multiplexer. Sub-agent events share the parent session's stream and are tagged with agentId. Root-agent and session-level events omit it. So a main-chat renderer is one if (!event.agentId) away from never leaking a sub-agent's chatter into the user's view.

Subscribing

// Every event โ€” good for traces, bad for rendering
session.on((event) => {
  console.log(event.type, event.data);
});

// One type โ€” data is narrowed automatically, no casts
session.on("assistant.message_delta", (event) => {
  process.stdout.write(event.data.deltaContent);
});

// Render only the parent agent's response (ignore sub-agents)
export function subscribeParentResponse(session: CopilotSession): void {
  session.on("assistant.message_delta", (event) => {
    if (!event.agentId) {
      process.stdout.write(event.data.deltaContent);
    }
  });
}

You can also subscribe before a session exists โ€” useful when a session is created by another part of your app โ€” and unsubscribe by keeping the return value of session.on(...).

The event taxonomy

There are 40+ event types. You do not need to memorise them, but you do need to know the families, because "which event do I hook?" is a daily question. Here is the map:

FamilyEventsWhat you do with them
Assistant assistant.turn_start, assistant.intent, assistant.reasoning, assistant.reasoning_delta, assistant.message, assistant.message_delta, assistant.turn_end, assistant.usage, assistant.streaming_delta Render text, show reasoning, count turns, capture token usage per call
Tool execution tool.execution_start, tool.execution_partial_result, tool.execution_progress, tool.execution_complete, tool.shell_output, tool.user_requested Progress UI, live shell output, per-tool latency, audit trails
Session lifecycle session.idle, session.error, session.compaction_start, session.compaction_complete, session.title_changed, session.context_changed, session.usage_info, session.usage_checkpoint, session.session_limits_changed, session.task_complete, session.shutdown Completion detection, error alerting, context-window monitoring, cost dashboards
Permissions & input permission.requested, permission.completed, user_input.requested, user_input.completed, elicitation.requested, elicitation.completed Human-in-the-loop approval UI, structured form dialogs
Sub-agents & skills subagent.started, subagent.completed, subagent.failed, subagent.selected, subagent.deselected, skill.invoked Multi-agent progress UI, skill-usage analytics
Transport & plan abort, user.message, system.message, external_tool.requested, external_tool.completed, exit_plan_mode.requested, exit_plan_mode.completed, command.queued, command.completed Audit, plan-mode approvals, slash-command tracking

Streaming: deltas vs finals

With streaming: true you get both delta events (chunks, ephemeral) and final events (complete content, persisted). The rule is simple: accumulate deltas for liveness, read the final event for truth. A dropped delta should never change your recorded answer.

const session = await client.createSession({ streaming: true, onPermissionRequest: approveAll });

let buffer = "";

session.on("assistant.message_delta", (e) => {
  if (e.agentId) return;          // skip sub-agent streams
  buffer += e.data.deltaContent;
  process.stdout.write(e.data.deltaContent);
});

session.on("assistant.message", (e) => {
  if (e.agentId) return;
  buffer = e.data.content;        // authoritative โ€” replaces the accumulation
});

Reasoning models stream a parallel channel: assistant.reasoning_delta chunks up into assistant.reasoning. Deltas are not produced when streaming is disabled, including after a resume โ€” so if your UI depends on them, verify the flag survived the resume.

Token angle: assistant.usage is emitted after each model call, which makes it the natural place to build per-turn cost attribution rather than per-session totals. It also exposes apiEndpoint (AssistantUsageApiEndpoint) telling you whether that turn went through Chat Completions, Responses, or Anthropic Messages โ€” the single most useful field when you are trying to explain an unexpected bill. session.compaction_start / session.compaction_complete bracket every context compaction, so you can alert on "this session is compacting constantly", which almost always means your tool results are too large.

Error handling in the stream

Two different failure surfaces, and conflating them is a common bug:

  • session.error is an event โ€” the loop hit a problem but the session survives. Log it, alert, decide whether to re-prompt.
  • A thrown exception from sendAndWait or createSession is a rejected promise โ€” transport or creation failure. await plus try/catch handles that path.

You can also intercept errors inside the loop and choose a strategy โ€” covered in Lesson 5's onErrorOccurred hook, which returns "retry", "skip", or "abort".

๐Ÿง  Knowledge Check

1. A single user prompt produces four assistant.turn_start / assistant.turn_end pairs. How many LLM API calls happened?

2. Your headless job awaits session.task_complete and hangs, though the agent visibly finished. What is the correct fix?

3. Which envelope field lets a single renderer distinguish the main agent's output from a sub-agent's, and what is its value for the root agent?

Further Reading