> ## 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.

# Managing Sessions

> List active sessions, attach to terminals, send messages to agents, and clean up completed work

Sessions are isolated workspaces where agents work on issues. Each session has its own git worktree, tmux session, and metadata.

## Listing Sessions

View all active sessions:

```bash theme={null}
ao session ls
```

**Output:**

```
Frontend:
  fe-1  (2m ago)  feat/add-login  [working]  https://github.com/org/app/pull/42
  fe-2  (5m ago)  feat/dashboard  [pr_open]

Backend:
  api-1  (1h ago)  fix/auth-bug  [review_pending]  https://github.com/org/api/pull/15
  (no active sessions)
```

Each session shows:

* **Session ID** (`fe-1`)
* **Last activity** (`2m ago`)
* **Branch name** (`feat/add-login`)
* **Status** (`working`, `pr_open`, `review_pending`)
* **PR URL** (if created)

### Filter by Project

List sessions for a specific project:

```bash theme={null}
ao session ls -p frontend
```

### Session Status Codes

| Status              | Meaning                             |
| ------------------- | ----------------------------------- |
| `spawning`          | Session is being created            |
| `working`           | Agent is actively coding            |
| `pr_open`           | PR created, waiting for CI/review   |
| `ci_failed`         | CI checks failed                    |
| `review_pending`    | Waiting for code review             |
| `changes_requested` | Reviewers requested changes         |
| `approved`          | PR approved by reviewers            |
| `mergeable`         | Approved + CI green, ready to merge |
| `merged`            | PR merged, session complete         |
| `needs_input`       | Agent is waiting for human input    |
| `stuck`             | Agent inactive for too long         |
| `errored`           | Agent encountered an error          |
| `killed`            | Session manually terminated         |

## Comprehensive Status View

Get detailed status with PR, CI, and review info:

```bash theme={null}
ao status
```

**Output:**

```
AGENT ORCHESTRATOR STATUS

Frontend:
  Session        Branch                  PR    CI     Rev   Thr  Activity  Age
  ─────────────────────────────────────────────────────────────────────────────
  fe-1           feat/add-login          #42   ✓      ✓     0    active    2m
                 Implementing OAuth login flow with session management
  fe-2           feat/dashboard          #43   ⋯      ⋯     2    ready     5m
                 Dashboard UI components with charts

Backend:
  Session        Branch                  PR    CI     Rev   Thr  Activity  Age
  ─────────────────────────────────────────────────────────────────────────────
  api-1          fix/auth-bug            #15   ✗      △     0    active    1h
                 Fixing JWT token validation

  3 active sessions across 2 projects
```

**Columns:**

* **PR**: PR number or `-` if not created
* **CI**: `✓` passing, `✗` failing, `⋯` pending, `-` no checks
* **Rev**: `✓` approved, `✗` changes requested, `△` pending
* **Thr**: Number of unresolved comment threads
* **Activity**: `active`, `ready`, `idle`, `waiting_input`, `blocked`, `exited`
* **Age**: Time since last activity

### Activity States

| State           | Meaning                           |
| --------------- | --------------------------------- |
| `active`        | Agent is thinking/writing code    |
| `ready`         | Agent finished, waiting for input |
| `idle`          | No activity for >5 minutes        |
| `waiting_input` | Agent is asking a question        |
| `blocked`       | Agent hit an error                |
| `exited`        | Agent process terminated          |

### JSON Output

Get machine-readable output for scripting:

```bash theme={null}
ao status --json
```

```json theme={null}
[
  {
    "name": "fe-1",
    "branch": "feat/add-login",
    "status": "working",
    "prNumber": 42,
    "ciStatus": "success",
    "reviewDecision": "approved",
    "pendingThreads": 0,
    "activity": "active",
    "lastActivity": "2m ago"
  }
]
```

## Attaching to Sessions

Attach to a session's terminal to watch the agent work:

```bash theme={null}
tmux attach -t fe-1
```

Or use the `open` command:

```bash theme={null}
ao open fe-1
```

**Detach without killing:**
Press `Ctrl+B`, then `D`

### Open Multiple Sessions

Open all sessions for a project:

```bash theme={null}
ao open frontend
```

Open all sessions across all projects:

```bash theme={null}
ao open all
```

### Open in New Window

```bash theme={null}
ao open fe-1 --new-window
```

This uses the Terminal plugin (default: `iterm2`) to create terminal tabs/windows.

## Sending Messages

Send instructions to a running agent:

```bash theme={null}
ao send fe-1 "Please address the review comments on your PR"
```

### How It Works

<Steps>
  <Step title="Wait for idle">
    The command waits for the agent to become idle before sending (default: 600s timeout)
  </Step>

  <Step title="Clear partial input">
    Sends `Ctrl+U` to clear any partial command
  </Step>

  <Step title="Send message">
    Injects the message into the tmux session
  </Step>

  <Step title="Press Enter">
    Automatically submits the message
  </Step>

  <Step title="Verify delivery">
    Checks that the agent received and is processing the message
  </Step>
</Steps>

### Send Without Waiting

Skip the idle wait:

```bash theme={null}
ao send fe-1 "Your message" --no-wait
```

<Warning>
  Sending while the agent is active may interrupt its current task. Use `--no-wait` only when necessary.
</Warning>

### Send from File

Send long instructions from a file:

```bash theme={null}
ao send fe-1 --file instructions.txt
```

**Example `instructions.txt`:**

```
The CI is failing with this error:

TypeError: Cannot read property 'id' of undefined
  at validateUser (auth.ts:42)

Please:
1. Add null checks for the user object
2. Add tests for the error case
3. Update the error message to be more descriptive
```

### Custom Timeout

Change the idle wait timeout:

```bash theme={null}
ao send fe-1 "Your message" --timeout 300  # 5 minutes
```

### Delivery Confirmation

The command verifies delivery:

```bash theme={null}
✓ Message sent and processing
```

Or:

```bash theme={null}
✓ Message queued (session finishing previous task)
```

If delivery can't be confirmed:

```bash theme={null}
⚠ Message sent — could not confirm it was received
```

## Killing Sessions

Terminate a session and remove its worktree:

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

This:

1. Kills the tmux session
2. Removes the git worktree
3. Updates session status to `killed`
4. Preserves metadata for audit trail

<Warning>
  Killing a session does NOT close or delete the PR. The PR remains open on GitHub/GitLab.
</Warning>

### When to Kill Sessions

✅ **Good reasons to kill:**

* PR merged, work is complete
* Agent is stuck and unrecoverable
* Duplicate session for the same issue
* Issue was closed/canceled

❌ **Don't kill if:**

* Agent is just slow (give it time)
* CI is failing (let auto-reactions handle it)
* You just want to pause (detach instead)

## Automatic Cleanup

Remove completed sessions automatically:

```bash theme={null}
ao session cleanup
```

This kills sessions where:

* PR is merged
* Issue is closed (in tracker)
* Runtime is no longer alive

**Dry run to preview:**

```bash theme={null}
ao session cleanup --dry-run
```

**Output:**

```
Checking for completed sessions...

  Would kill fe-2
  Would kill api-5

Dry run complete. 2 sessions would be cleaned.
```

**Cleanup specific project:**

```bash theme={null}
ao session cleanup -p frontend
```

### Cleanup Criteria

A session is cleaned if:

<Tabs>
  <Tab title="PR Merged">
    The PR associated with the session has been merged to the default branch.

    Detected via SCM plugin:

    ```typescript theme={null}
    const pr = await scm.detectPR(session, project);
    const merged = pr && pr.state === "merged";
    ```
  </Tab>

  <Tab title="Issue Closed">
    The issue in the tracker (GitHub Issues, Linear) is closed or done.

    Detected via Tracker plugin:

    ```typescript theme={null}
    const issue = await tracker.getIssue(session.issueId);
    const closed = issue && issue.status === "closed";
    ```
  </Tab>

  <Tab title="Runtime Dead">
    The tmux session or container is no longer running.

    Detected via Runtime plugin:

    ```typescript theme={null}
    const alive = await runtime.isAlive(session.runtimeHandle);
    ```
  </Tab>
</Tabs>

## Restoring Sessions

Restore a crashed or terminated session in-place:

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

This:

1. Verifies the worktree still exists
2. Checks that the session is restorable (not merged)
3. Creates a new tmux session
4. Relaunches the agent in the same workspace
5. Updates metadata with restore timestamp

**When to restore:**

* tmux session crashed but worktree is intact
* Agent exited unexpectedly
* You manually killed tmux but want to resume

<Warning>
  **Cannot restore if:**

  * Session status is `merged` (work is complete)
  * Worktree was deleted
  * Branch was deleted from the repo
</Warning>

**Restore output:**

```
✓ Session fe-1 restored.
  Worktree: /Users/you/.worktrees/fe-1
  Branch:   feat/add-login
  Attach:   tmux attach -t fe-1
```

## Session Metadata

Each session stores metadata in flat files:

```
~/.agent-orchestrator/sessions/my-app/
  fe-1/
    id=fe-1
    projectId=frontend
    status=working
    branch=feat/add-login
    issueId=123
    pr=https://github.com/org/app/pull/42
    createdAt=2024-03-04T10:30:00Z
    lastActivityAt=2024-03-04T10:32:00Z
```

Metadata is:

* **Flat key=value format** (backwards compatible)
* **Human-readable** (edit with any text editor)
* **Tracked in event log** (full audit trail)

## Scripting Examples

### Kill all merged sessions

```bash theme={null}
ao session cleanup --dry-run | grep "Would kill" | awk '{print $3}' | xargs -I {} ao session kill {}
```

### Send message to all sessions

```bash theme={null}
for session in $(ao session ls --json | jq -r '.[].name'); do
  ao send $session "Please check if your PR is ready for review"
done
```

### Monitor session status

```bash theme={null}
watch -n 30 'ao status'
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Auto-Reactions" icon="robot" href="/guides/auto-reactions">
    Automate CI failure handling and review responses
  </Card>

  <Card title="Multi-Project Setup" icon="folder-tree" href="/guides/multi-project">
    Manage multiple repositories simultaneously
  </Card>
</CardGroup>
