Agent SDK Sessions, Subagents, and Context
Resume state when continuity helps. Fork context when inherited assumptions become risk. Separate durable task state from conversational context. Choose new, resumed, forked, and compacted sessions from failure risk. Use subagents to isolate context and tools. Place hooks around deterministic lifecycle events. Design recovery that does not replay stale assumptions or duplicate side effects. A repository migration agent runs for several hours. Its context contains the original plan, tool outputs, failed experiments, partial patches, test logs, and several summaries. After a dependency changes, the team resumes the same session and says, "Continue from where you stopped." The agent follows an obsolete plan. It repeats a write action that had already succeeded before a timeout. Compaction preserved the broad story but dropped a critical test failure. A reviewer subagent receives the entire parent history and assumes the old dependency behavior is still true. The system confused three things: durable external state. current conversational context. execution history. They are related, but they should not be treated as one store. The model context should contain the information needed for the next decisions. It is not the authoritative database for completed work, approvals, files, checkpoints, or tool side effects. Store durable facts outside context: current task manifest and statuses. completed artifacts and versions. idempotency keys and external action IDs. approvals and expiration. last verified…
Agent SDK Sessions, Subagents, and Context: Resume state when continuity helps. Fork context when inherited assumptions become risk.
This free lesson is part of the AI Engineering from Scratch curriculum. Read the full explanation, run the lesson code, and verify the result in the interactive reader or from the repository source.
Browse the complete course catalog or open this lesson on GitHub.