# Kollabor Engine - Sessions API Specification

## Overview

Sessions represent isolated conversation contexts in the Kollabor Engine. Each session
has its own conversation history, LLM profile, approval mode, workspace context,
and MCP server connections. Multiple sessions can run concurrently.

Base URL: http://127.0.0.1:7433
Auth: Bearer token from ~/.kollabor-cli/engine.token


## Session Schema

Returned by GET /sessions, GET /sessions/{id}, POST /sessions:

```json
{
  "session_id": "sess_abc123def456",
  "profile": "default",
  "workspace": "/Users/dev/myproject",
  "approval_mode": "confirm_all",
  "created_at": "2026-02-17T12:00:00Z",
  "total_turns": 5,
  "total_input_tokens": 1240,
  "total_output_tokens": 3840,
  "history_length": 11,
  "active": false
}
```

Fields:
- session_id: unique session identifier (sess_ + 12 hex chars)
- profile: LLM profile name (must exist in ProfileManager)
- workspace: optional working directory path
- approval_mode: permission approval mode
- created_at: ISO 8601 timestamp of session creation
- total_turns: number of user messages processed
- total_input_tokens: cumulative input tokens across all turns
- total_output_tokens: cumulative output tokens across all turns
- history_length: number of messages in conversation history
- active: true if a turn is currently in progress


## History Schema

Returned by GET /sessions/{id}/history:

```json
{
  "session_id": "sess_abc123",
  "history": [
    {
      "role": "system",
      "content": "You are Claude..."
    },
    {
      "role": "user",
      "content": "Refactor this function",
      "ts": 1234567890
    },
    {
      "role": "assistant",
      "content": "Here is the refactored code...",
      "ts": 1234567891,
      "tool_calls": [...],
      "token_usage": {"input": 100, "output": 200}
    }
  ]
}
```

History item fields:
- role: "system" | "user" | "assistant"
- content: message text
- ts: optional timestamp (user/assistant messages)
- tool_calls: optional array of tool call details (assistant messages)
- token_usage: optional {input, output} token counts (assistant messages)


## Endpoints

### POST /sessions

Create a new session.

IMPLEMENTATION STATUS: IMPLEMENTED (routes/sessions.py:create_session)

Request:
```json
{
  "profile": "default",
  "system_prompt": "You are a helpful assistant...",
  "workspace": "/path/to/project",
  "approval_mode": "confirm_all",
  "mcp_servers": ["memory", "filesystem"],
  "metadata": {},
  "credentials": null
}
```

Request fields:
- profile: LLM profile name (must exist). Required if credentials not provided.
- system_prompt: optional override prompt. If set, injected as first history item.
- workspace: optional working directory for file operations
- approval_mode: "confirm_all" | "default" | "auto_approve_edits" | "trust_all"
- mcp_servers: list of MCP server names to connect
- metadata: arbitrary client data (not used by engine, returned in session info)
- credentials: optional inline LLM credentials (bypasses profile lookup)

Credentials object (when caller manages its own LLM):
```json
{
  "provider": "anthropic",
  "api_key": "sk-ant-...",
  "model": "claude-sonnet-4-6",
  "base_url": "",
  "max_tokens": null
}
```

Response (201):
```json
{
  "session_id": "sess_abc123def456",
  "profile": "default",
  "workspace": "/path/to/project",
  "approval_mode": "confirm_all",
  "created_at": "2026-02-17T12:00:00Z",
  "total_turns": 0,
  "total_input_tokens": 0,
  "total_output_tokens": 0,
  "history_length": 1,
  "active": false
}
```

Errors:
- 404: Profile not found (when using profile-based auth)
- 500: Initialization failed

Example:
```bash
curl -X POST http://127.0.0.1:7433/sessions \
  -H "Authorization: Bearer $(cat ~/.kollabor-cli/engine.token)" \
  -H "Content-Type: application/json" \
  -d '{
    "profile": "default",
    "workspace": "/Users/dev/myproject",
    "approval_mode": "confirm_all"
  }'
```

With inline credentials:
```bash
curl -X POST http://127.0.0.1:7433/sessions \
  -H "Authorization: Bearer $(cat ~/.kollabor-cli/engine.token)" \
  -H "Content-Type: application/json" \
  -d '{
    "credentials": {
      "provider": "anthropic",
      "api_key": "sk-ant-...",
      "model": "claude-sonnet-4-6"
    }
  }'
```


### GET /sessions

List all active sessions.

IMPLEMENTATION STATUS: IMPLEMENTED (routes/sessions.py:list_sessions)

Response (200):
```json
{
  "sessions": [
    {
      "session_id": "sess_abc123",
      "profile": "default",
      "workspace": "/Users/dev/myproject",
      "approval_mode": "confirm_all",
      "created_at": "2026-02-17T12:00:00Z",
      "total_turns": 5,
      "total_input_tokens": 1240,
      "total_output_tokens": 3840,
      "history_length": 11,
      "active": false
    }
  ]
}
```

Example:
```bash
curl http://127.0.0.1:7433/sessions \
  -H "Authorization: Bearer $(cat ~/.kollabor-cli/engine.token)"
```


### GET /sessions/{session_id}

Get detailed info for a single session.

IMPLEMENTATION STATUS: IMPLEMENTED (routes/sessions.py:get_session)

Response (200):
```json
{
  "session_id": "sess_abc123",
  "profile": "default",
  "workspace": "/Users/dev/myproject",
  "approval_mode": "confirm_all",
  "created_at": "2026-02-17T12:00:00Z",
  "total_turns": 5,
  "total_input_tokens": 1240,
  "total_output_tokens": 3840,
  "history_length": 11,
  "active": false
}
```

Errors:
- 404: Session not found

Example:
```bash
curl http://127.0.0.1:7433/sessions/sess_abc123 \
  -H "Authorization: Bearer $(cat ~/.kollabor-cli/engine.token)"
```


### DELETE /sessions/{session_id}

End a session and clean up resources. Shuts down MCP connections, cancels
active turns, and removes session from registry.

IMPLEMENTATION STATUS: IMPLEMENTED (routes/sessions.py:delete_session)

Response (200):
```json
{
  "ok": true,
  "session_id": "sess_abc123"
}
```

Errors:
- 404: Session not found

Example:
```bash
curl -X DELETE http://127.0.0.1:7433/sessions/sess_abc123 \
  -H "Authorization: Bearer $(cat ~/.kollabor-cli/engine.token)"
```


### GET /sessions/{session_id}/history

Get conversation history. Optional ?limit=N parameter returns last N messages.

IMPLEMENTATION STATUS: IMPLEMENTED (routes/sessions.py:get_history)

Query parameters:
- limit: optional integer, return last N messages

Response (200):
```json
{
  "session_id": "sess_abc123",
  "history": [
    {
      "role": "system",
      "content": "You are a helpful assistant..."
    },
    {
      "role": "user",
      "content": "Refactor this function",
      "ts": 1739798400
    },
    {
      "role": "assistant",
      "content": "Here is the refactored code...",
      "ts": 1739798401,
      "tool_calls": [
        {
          "id": "call_123",
          "name": "str_replace_editor",
          "input": {"path": "src/main.rs", ...}
        }
      ],
      "token_usage": {"input": 100, "output": 200}
    }
  ]
}
```

Errors:
- 404: Session not found

Examples:
```bash
# Full history
curl http://127.0.0.1:7433/sessions/sess_abc123/history \
  -H "Authorization: Bearer $(cat ~/.kollabor-cli/engine.token)"

# Last 10 messages
curl "http://127.0.0.1:7433/sessions/sess_abc123/history?limit=10" \
  -H "Authorization: Bearer $(cat ~/.kollabor-cli/engine.token)"
```


### DELETE /sessions/{session_id}/history

Clear conversation history. Preserves system prompt if present (it remains
as history[0]).

IMPLEMENTATION STATUS: IMPLEMENTED (routes/sessions.py:clear_history)

Response (200):
```json
{
  "ok": true,
  "session_id": "sess_abc123"
}
```

Errors:
- 404: Session not found

Example:
```bash
curl -X DELETE http://127.0.0.1:7433/sessions/sess_abc123/history \
  -H "Authorization: Bearer $(cat ~/.kollabor-cli/engine.token)"
```


### GET /sessions/{session_id}/system-prompt

Get the current system prompt for a session.

IMPLEMENTATION STATUS: NOT IMPLEMENTED

Returns session.system_prompt if set, otherwise extracts from history[0]
if role=="system", otherwise empty.

Response (200):
```json
{
  "session_id": "sess_abc123",
  "system_prompt": "You are Claude..."
}
```

Errors:
- 404: Session not found

Example:
```bash
curl http://127.0.0.1:7433/sessions/sess_abc123/system-prompt \
  -H "Authorization: Bearer $(cat ~/.kollabor-cli/engine.token)"
```


### POST /sessions/{session_id}/system-prompt/rebuild

Rebuild system prompt by re-rendering <trender> tags.

IMPLEMENTATION STATUS: NOT IMPLEMENTED

Response (200):
```json
{
  "session_id": "sess_abc123",
  "system_prompt": "You are Claude...\n\n## Project Structure\n\nsrc/"
}
```

Errors:
- 404: Session not found
- 500: Rebuild failed

Example:
```bash
curl -X POST http://127.0.0.1:7433/sessions/sess_abc123/system-prompt/rebuild \
  -H "Authorization: Bearer $(cat ~/.kollabor-cli/engine.token)"
```


## System Prompt Details

### Storage

- Raw prompt stored in session.system_prompt (EngineSession property)
- On init, injected into session.history[0] with role="system"
- Re-rendering processes <trender> tags via kollabor_ai.prompt_renderer

### Trender Tags

<trender>command</trender> - executes shell command
<trender type="include" path="file.md" /> - includes file content


## Approval Modes

Value mappings in EngineSession._APPROVAL_MODE_MAP:

| String | Enum | Behavior |
|--------|------|----------|
| confirm_all | CONFIRM_ALL | Ask for every tool |
| default | DEFAULT | Ask for high-risk tools only |
| auto_approve_edits | AUTO_APPROVE_EDITS | Auto-approve file edits |
| trust_all | TRUST_ALL | Never ask |


## MCP Servers

Sessions can optionally connect to MCP servers for tool augmentation.

At session creation (POST /sessions):
```json
{
  "mcp_servers": ["memory", "filesystem"]
}
```

The session initializes these servers during EngineSession.initialize().
Tools from MCP servers are merged with native tools and returned by
session.get_tools().


## Testing Considerations

- Large conversations (1000+ messages)
- History pagination with ?limit
- System prompt preservation after clear_history
- Concurrent sessions with different profiles
- Active turn cancellation on delete


## Error Codes

| Code | Description |
|------|-------------|
| 404 | Session not found |
| 404 | Profile not found |
| 500 | Init/rebuild failed |
