> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/ComposioHQ/agent-orchestrator/llms.txt
> Use this file to discover all available pages before exploring further.

# Sessions

> Understanding session lifecycle, states, and management in Agent Orchestrator

A **session** represents a single agent working on a specific task. Each session gets its own isolated environment: a git worktree, a runtime (tmux session or container), and a running AI agent.

## What is a Session?

A session encapsulates everything needed for an agent to work independently:

* **Unique identifier** — e.g., `app-1`, `backend-12`
* **Isolated workspace** — Git worktree or clone with its own branch
* **Runtime environment** — Tmux session, Docker container, or process
* **Running agent** — Claude Code, Codex, Aider, or other AI coding tool
* **Task context** — Issue ID, branch name, PR information
* **Metadata** — State, timestamps, agent info, custom fields

### Session Naming

Sessions use a two-tier naming system:

**User-facing names** (clean and simple):

```
{sessionPrefix}-{num}

app-1, app-2        (my-app project)
be-1, be-2          (backend project)
int-1, int-2        (integrator project)
```

**Tmux session names** (globally unique):

```
{hash}-{sessionPrefix}-{num}

a3b4c5d6e7f8-app-1  (from config at ~/orchestrator)
f1e2d3c4b5a6-app-1  (from config at ~/orchestrator-v2)
```

<Note>
  The hash is derived from the config file location using SHA-256, ensuring multiple orchestrator instances never collide.
</Note>

## Session Lifecycle States

Sessions progress through a well-defined state machine:

### Active States

<Accordion title="spawning">
  Session is being created. The orchestrator is:

  * Creating the workspace (git worktree)
  * Setting up the runtime environment
  * Launching the agent

  Transitions to `working` once agent is running.
</Accordion>

<Accordion title="working">
  Agent is actively working on the task:

  * Reading code and documentation
  * Writing and testing code
  * Making commits

  Transitions to `pr_open` when agent creates a pull request.
</Accordion>

<Accordion title="pr_open">
  Pull request has been created and is awaiting CI or review.

  Transitions to:

  * `ci_failed` — CI checks failed
  * `review_pending` — CI passed, awaiting review
  * `merged` — PR was merged
</Accordion>

<Accordion title="ci_failed">
  CI checks failed on the PR. If reactions are enabled, the orchestrator automatically:

  1. Fetches CI logs
  2. Sends logs to agent
  3. Agent fixes the issue
  4. Pushes new commit

  Transitions back to `pr_open` after fix is pushed.
</Accordion>

<Accordion title="review_pending">
  PR passed CI and is awaiting human review.

  Transitions to:

  * `approved` — Reviewer approved
  * `changes_requested` — Reviewer requested changes
</Accordion>

<Accordion title="changes_requested">
  Reviewer requested changes. With auto-reactions:

  1. Review comments are fetched
  2. Comments sent to agent
  3. Agent addresses feedback
  4. New commits pushed

  Transitions back to `pr_open` after updates.
</Accordion>

<Accordion title="approved">
  PR has been approved but not yet mergeable (might have minor CI pending).

  Transitions to `mergeable` when ready to merge.
</Accordion>

<Accordion title="mergeable">
  PR is approved with passing CI and no conflicts — ready to merge.

  With `approved-and-green` reaction:

  * `auto: false` — Human gets notification to merge
  * `auto: true` — Automatic merge

  Transitions to `merged` after merge.
</Accordion>

### Terminal States

<Accordion title="merged">
  PR was successfully merged. Session work is complete.

  **This state cannot be restored** — the work is done.
</Accordion>

<Accordion title="killed">
  Session was terminated (either by user or because runtime died).

  Can be restored with `ao session restore <session-id>`.
</Accordion>

<Accordion title="done">
  Session completed successfully without PR (e.g., exploration task).
</Accordion>

<Accordion title="terminated">
  Session was force-stopped by user.
</Accordion>

<Accordion title="cleanup">
  Session is being cleaned up (workspace deletion, etc.).
</Accordion>

<Accordion title="errored">
  Session encountered a fatal error and cannot continue.
</Accordion>

### Intervention States

<Accordion title="needs_input">
  Agent is waiting for user input (e.g., permission prompt, question).

  Send a message to the agent:

  ```bash theme={null}
  ao send session-1 "Yes, proceed with the changes"
  ```

  Transitions back to `working` after input is provided.
</Accordion>

<Accordion title="stuck">
  Agent has been inactive for longer than the configured threshold (default: 5 minutes).

  With auto-reactions, the orchestrator can:

  * Send a nudge message
  * Notify human for intervention
  * Auto-restart the agent

  Use `ao send` to provide guidance.
</Accordion>

## Activity Detection

In addition to lifecycle states, each session has an **activity state** that reflects what the agent is currently doing:

| Activity State | Description |
| - | - |
| `active` | Agent is processing (thinking, writing code) |
| `ready` | Agent finished its turn, waiting for next input |
| `idle` | Agent inactive beyond threshold (becomes `stuck` in lifecycle) |
| `waiting_input` | Agent asking a question or waiting for permission |
| `blocked` | Agent hit an error or is stuck on a problem |
| `exited` | Agent process is no longer running |

<Info>
  Activity detection is handled by the Agent plugin, which reads agent-native telemetry (JSONL files, SQLite, etc.) rather than parsing terminal output.
</Info>

### Activity Detection Methods

Agent plugins use two methods:

**Preferred: `getActivityState()`**

* Reads agent's native session files (JSONL, SQLite, etc.)
* Runtime-agnostic (works even if tmux session is dead)
* More reliable and accurate
* Used by claude-code, codex plugins

**Fallback: `detectActivity()`**

* Parses terminal output from runtime
* Less reliable (depends on output patterns)
* Used when native detection unavailable

## Session Management Operations

### Spawn a Session

Create a new session for an issue:

```bash theme={null}
ao spawn my-project 123
```

**What happens:**

<Steps>
  ### Fetch Issue

  Tracker plugin fetches issue details from GitHub/Linear.

  ### Create Workspace

  Workspace plugin creates git worktree with feature branch.

  ### Generate Prompt

  Tracker plugin generates prompt from issue description.

  ### Launch Agent

  Agent plugin constructs launch command with prompt.

  ### Create Runtime

  Runtime plugin creates tmux session or container.

  ### Start Agent

  Agent process starts inside runtime.

  ### Write Metadata

  Session metadata written to `~/.agent-orchestrator/{hash}-{project}/sessions/{session-id}`.
</Steps>

### List Sessions

View all sessions or filter by project:

```bash theme={null}
ao session ls                    # All sessions
ao session ls my-project         # Project-specific
```

Output includes:

* Session ID
* Status
* Activity state
* Branch name
* Issue ID
* PR URL (if created)
* Summary (agent-generated)

### Attach to Session

Connect to a running session:

```bash theme={null}
ao attach session-1
```

Uses Terminal plugin to open the session in:

* iTerm2 tab (macOS)
* Web terminal (browser)
* Direct tmux attach

### Send Message

Send instructions to a running agent:

```bash theme={null}
ao send session-1 "Please add more test coverage"
```

The Runtime plugin delivers the message to the agent's stdin.

### Kill Session

Terminate a running session:

```bash theme={null}
ao session kill session-1
```

**What happens:**

1. Agent process is terminated
2. Runtime environment is destroyed
3. Session status set to `killed`
4. Workspace preserved (can be restored)

### Restore Session

Revive a killed or crashed session:

```bash theme={null}
ao session restore session-1
```

**Prerequisites:**

* Session must be in a terminal state (`killed`, `done`, etc.)
* Session must NOT be `merged` (cannot restore completed work)
* Workspace must still exist (or be restorable)

**What happens:**

1. Checks if workspace exists
2. If missing, attempts to recreate workspace (for worktree plugin)
3. Determines if agent can resume previous session
4. If yes, uses `getRestoreCommand()` to resume
5. If no, launches fresh agent with original prompt
6. Updates `restoredAt` timestamp in metadata

<Warning>
  Sessions in `merged` state cannot be restored — the work is complete and the branch is likely deleted.
</Warning>

### Cleanup Sessions

Remove completed or stale sessions:

```bash theme={null}
ao cleanup                       # Dry run (shows what would be cleaned)
ao cleanup --confirm             # Actually clean
ao cleanup my-project --confirm  # Project-specific
```

**Cleanup criteria:**

* Status is `merged`, `done`, or `killed`
* Issue is closed (if Tracker plugin supports it)
* PR is merged or closed

**What gets cleaned:**

1. Runtime terminated
2. Workspace deleted
3. Metadata moved to `archive/` with timestamp

## Session Metadata

Metadata is stored as flat key=value files for backwards compatibility:

```
project=my-app
issue=INT-100
branch=feat/INT-100
status=working
tmuxName=a3b4c5d6e7f8-app-1
worktree=/home/user/.agent-orchestrator/a3b4c5d6e7f8-my-app/worktrees/app-1
createdAt=2026-02-17T10:30:00Z
runtimeHandle={"id":"a3b4c5d6e7f8-app-1","runtimeName":"tmux","data":{}}
pr=https://github.com/owner/my-app/pull/123
summary=Implementing user authentication with JWT
agent=claude-code
```

### Key Fields

| Field | Description |
| - | - |
| `project` | Project ID (config key) |
| `issue` | Issue identifier (GitHub #, Linear ID, etc.) |
| `branch` | Git branch name |
| `status` | Current lifecycle status |
| `tmuxName` | Globally unique tmux session name |
| `worktree` | Absolute path to workspace |
| `createdAt` | ISO 8601 timestamp |
| `restoredAt` | When session was last restored (if applicable) |
| `runtimeHandle` | JSON-encoded runtime handle |
| `pr` | Pull request URL |
| `summary` | Agent-generated task summary |
| `agent` | Agent plugin name used for this session |

<Info>
  Metadata files are located at `~/.agent-orchestrator/{hash}-{project}/sessions/{session-id}`.
</Info>

## Session Restoration

When a session crashes or is killed, you can restore it:

### Restorable States

* `killed` — Session terminated
* `done` — Completed without PR
* `terminated` — Force-stopped
* `cleanup` — Being cleaned up
* `errored` — Error occurred

### Non-Restorable States

* `merged` — Work complete, cannot continue

### Restoration Process

<Steps>
  ### Validate Session

  Check if session is in restorable state and not merged.

  ### Check Workspace

  Verify workspace exists on disk. If missing and using worktree plugin, attempt to recreate.

  ### Determine Resume Method

  Agent plugin checks if it can resume the previous agent session.

  **Claude Code:** Looks for `.claude/sessions/<hash>` directory.
  **Other agents:** May not support resume, will start fresh.

  ### Generate Command

  * **With resume:** `getRestoreCommand()` returns launch command with session ID.
  * **Without resume:** Falls back to original `getLaunchCommand()` with prompt.

  ### Recreate Runtime

  Runtime plugin creates new tmux session or container.

  ### Launch Agent

  Agent starts with resume or fresh session.

  ### Update Metadata

  Set `restoredAt` timestamp and clear terminal status flags.
</Steps>

<Note>
  **Agent Resume Support:**

  * **claude-code:** Full session resume (preserves conversation history)
  * **codex, aider, opencode:** Fresh start with original prompt
</Note>

## Best Practices

### Session Naming

* Use descriptive session prefixes in project config
* Keep prefixes short (2-4 characters): `app`, `api`, `web`
* Avoid prefixes that conflict with common commands

### Activity Monitoring

* Set appropriate `readyThresholdMs` in config (default: 5 minutes)
* Monitor `stuck` sessions — they may need human guidance
* Use `ao send` to nudge idle agents back into action

### Cleanup Strategy

* Run cleanup periodically to free disk space
* Archive metadata is preserved for audit trail
* Completed sessions (`merged`, `done`) can be cleaned immediately
* Keep `killed` sessions until you verify work wasn't lost

### Session Restoration

* Restore sessions after system crashes or accidental kills
* Check workspace before restoring — missing worktrees can often be recreated
* Use agent resume when available (preserves context)
* For failed restores, check logs: `ao session restore session-1 --verbose`

## Next Steps

<Card title="Architecture" icon="sitemap" href="/concepts/architecture">
  Understand the plugin architecture and component interactions
</Card>

<Card title="Plugins" icon="puzzle" href="/concepts/plugins">
  Learn about the 8 plugin slots and how to use them
</Card>

<Card title="Workflows" icon="workflow" href="/concepts/workflows">
  See how sessions progress through typical workflows
</Card>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.