Skip to content

Sessions

Sessions are complete, append-only conversation logs. Every turn (the user prompt, the agent's thinking, each tool call with its result, and the answer) is persisted as JSON under the project's .polyglav/sessions/ directory. Entries are never removed. Compaction only trims the provider context, never the log.

A paused turn is restored as open when the session loads, so /continue works after a restart. A loaded session warns when its recorded role or team no longer exists.

A JSONL session is materialized to .json on session switch and exit, so the JSON stays portable. JSONL remains the source when both files exist.

SQLite storage

Set session.storage = "sqlite" and enable polyglav-core-storage-sqlite to keep sessions in .polyglav/sessions/sessions.db. The plugin is off by default and uses only the standard library. A materialized JSON snapshot is still written on session switch and exit.

JSONL storage

Set session.storage = "jsonl" to write append-only .polyglav/sessions/<name>.jsonl files beside the JSON store. Each line is a meta or turn event, the last event per turn wins on load, and JSON stays the export and import format. The default remains json.

Where sessions live

Each session is one JSON file: .polyglav/sessions/<name>.json, next to the local .polyglav/config.json. The sessions directory is created 0700 and every session, tool-log, and error file is written 0600, so the logs stay readable only to the owner. Files written by an earlier version keep their old mode until they are rewritten, and chmod -R go-rwx .polyglav closes that gap in one step.

Names are explicit (/session new <name>, /session load <name>) or auto-generated as ses_<timestamp>_<id>, e.g. ses_20260817_120000_ab12cd. The <id> is a six-character base36 hash minted at creation and embedded in the name, so an auto session is fully named from the start (no prompt-slug rename).

Session files carry a kind prefix so the kinds stay distinguishable at a glance:

Prefix Kind Example
job_ Jobs: one fresh file per run job_20260826_110230_7f3k2a.json
ses_ Interactive/auto sessions ses_20260817_120000_ab12cd.json
sub_ Delegation sub-agents sub_20260817_120100_cd34ef.json

The trailing <id> is a six-character base36 hash minted at creation and embedded in the name, so a generated session is fully named from the start (no prompt-slug rename). The session_id is the stable run handle: each run mirrors it as Run.session_id, /status shows it, and the session name carries it. The ses_, job_, and sub_ kinds carry an id. Explicit names carry no id and are referenced by session:<name>. Files written before the session_name/session_id fields were introduced no longer load (the file is left on disk and stays listed).

Delegation writes each sub-agent's log as its own session: sub_<ts>_<id> (sub_20260817_120100_cd34ef), with the calling session recorded as parent_id rather than in the filename. Job runs use job_<ts>_<id>, with the job name still recorded in the job registry and each run's JobRun.session. A caller may resume a run or session explicitly with call/team resume=... and context=continue|compact|new, which appends to that run's own log instead of minting a new one. These live in the same .polyglav/sessions/ directory and are regular sessions, hidden from /sessions list and reachable through /history --tree, /print --tree, and --tree exports, so caller and sub-agent logs stay separate and complete.

Each session also records the agent role that owns it (the bound root role, the delegated role, the team-stage role, or the job role), stamped at creation. That makes a run reconstructable from its log even after the process exits. A plain root or a headless run with no --role leaves role empty.

Each session also records the Polyglav version that created it, so a log says which build wrote it. The version is stamped once at creation and never changes. Files written before the field load with an empty version (no backfill).

Session files written before the turn format (flat messages) and files written before the session_name/session_id rename do not load: read() returns nothing for them, the file is left untouched on disk, and /sessions still lists the name. The turn format is a full cutover, not a compatibility layer.

An unreadable or unwritable session file is recorded in .polyglav/sessions/errors.log, one tab-separated line per failure holding the timestamp, the read or save action, the session name, and the error. A legacy-format file that parses but does not load is not logged, since that is an expected skip rather than a failure. The log is best-effort, so a failure to write the log itself never interrupts a session.

Managing sessions

The active session is handled by /session (like /model for the model). The catalog of saved sessions lives under /sessions (like /models).

Command Purpose
/history [N\|N-O\|-O\|N-\|all] [session:<name> ...] [--thoughts [all]] [--tree] Numbered turn index of the active session (default last 10), with an optional dim thinking excerpt and a whole-tree view
/print [N\|N-O\|-O\|N-\|N.M] [session:<name> ...] [--full] [--tree] Reprint a turn in full, or only its m-th part, capped per part at 4000 characters. --tree renders the whole run tree
/session Show the active session (name, provider-context message count, context tokens and window)
/session new <name> Create and switch to a new session
/session load <name> Load a session (with compaction offer if it has a summary)
/session save Save the current session
/sessions List saved root sessions (sub-runs hidden)
/sessions preview <name> Structural preview (title, outcome, idle time, turn count, part kinds, tool names) without switching
/sessions delete <name> Delete a session
/sessions export <name> [out] [--json] [--tree] Export a session (or its run tree) to Markdown (or JSON)
/sessions import <file> [name] [--force] Import a session from a JSON export
/sessions prune --older-than <days> [--dry-run] Delete sessions not updated in that many days, with their tool logs and summaries. The current session is always kept

The current session auto-saves after every turn and command, so nothing is lost on exit.

Retention

Sessions are kept until you delete them. There is no background timer and no automatic expiry, because losing a log to a timer is worse than keeping it. /sessions delete <name> removes one session, and /sessions prune --older-than <days> removes every session whose updated_at is older than the threshold, together with its .tools.log sidecar and summary. The current session is always kept. The headless form is polyglav sessions prune --older-than <days> [--dry-run] [--yes], and it is a dry run unless --yes is passed. The removal reports the session count and the bytes freed.

This is the deletion half of a data-protection story. The other half is encryption at rest, which is a backlog idea: it would cost full-text search over the logs, so it follows retention rather than replacing it.

/history lists the active session's turns as a numbered index, one line per turn: #<index> [<status>] <duration> <tool count> <prompt>. The index is the turn's absolute index, so a turn can be named later regardless of the listing limit. /history 3 shows the last three turns, /history all every turn, and --thoughts adds a dim first-line excerpt of the turn's thinking (--thoughts all prints the full thinking text). /history session:<name> reads another saved session without changing the current session. --tree lists the root and every sub-run with its depth.

/print <n> reprints the turn with that absolute index: the full turn metadata block (#index, status, duration, tool count, started/ended, model, provider, mode, reasoning, with empty values shown as -, so even a command turn is self-describing), then each part: the user prompt, thinking (dim), every tool call with input JSON, output, is_error, and analysis, the answer, command records (a compaction summary included), and system notes. /print <n>.<m> prints only the m-th part of turn n. Each part's text is capped at 4000 characters with ... (N more chars, use --full) appended, and --full removes the cap. /print takes the same session:<name> selector as /history, so it can read another saved session without changing the current session. --tree renders the whole run tree.

Exporting to Markdown

/sessions export <name> renders any saved session as a Markdown transcript. It reads the persisted log directly (read(), not load()), so the current session is never switched and the source file is left untouched. --tree renders the root and every sub-run, separated by ---.

Default output is .polyglav/exports/<name>.md, next to the sessions/ directory. A second argument overrides the path (/sessions export <name> out.md). - prints the transcript to stdout instead of a file. The command tab-completes session names.

The export is the full, auditable log: user prompts, each thinking block, tool calls (arguments and result, with the optional analysis), plain assistant answers, command records, compaction summaries (with the trimmed-context boundary), system notes, and a final ## Errors section. Since it renders the persisted form, line-range tool refs resolve to their log sections as they appear in the file.

The header lists the session metadata every transcript starts with: created and updated timestamps, session id, role, mode, version, turn count, and the derived outcome (empty fields render as -).

The headless CLI polyglav export <name> [--out <file>] [--json] [--tree] reuses the same renderer for scripts and CI. --out - prints to stdout, and the default matches the slash command (.polyglav/exports/<name>.md). --tree includes sub-runs and defaults to <name>_tree.md (or _tree.json).

--json (and /sessions export <name> --json) emits a machine-readable document instead: {"info": {...}, "turns": [...], "errors": [...], "permissions": [...]}, where info holds the session header (name, id, role, mode, version, created and updated timestamps, parent and sub-session links, and the derived title, outcome, and idle time), turns is the full turn log, and errors and permissions are the session-level audit arrays. The document round-trips through the JSON import. The default output becomes .polyglav/exports/<name>.json. With --tree, the document is {"sessions": [<document>, ...]} in root-first order.

Importing from JSON

/sessions import <file> [name] [--force] and polyglav import <file> [--name] [--force] read an export document and write it into .polyglav/sessions/. The session keeps the original name when it is free, uses an explicit name when given, and otherwise gets a fresh ses_<ts>_<id> name. A collision with an explicit name is an error unless --force overwrites it. Import reads info, turns, errors, and permissions, ignores the derived header fields (title, outcome, idle_at), does not change the active session, and also accepts a raw session file (session_name plus turns).

File structure

{
  "created_at": "2026-08-17T12:00:00+00:00",
  "errors": [],
  "mode": "",
  "plan": "",
  "parent_id": "",
  "permissions": [],
  "role": "",
  "session_id": "ab12cd",
  "session_name": "ses_20260817_120000_ab12cd",
  "sub_sessions": [],
  "turns": [],
  "updated_at": "2026-08-17T12:05:15+00:00",
  "version": "0.35.0"
}
Key Type Description
created_at string ISO 8601 UTC timestamp of creation
errors array Turn-level errors (provider, network, agent loop)
mode string Session posture (read or write), empty means follow the config mode. Set by /mode
plan string Attached plan path, empty when no plan is attached. Set by plan_write or /plan use
parent_id string Name of the session this one was spawned from (sub-agent sessions set it, empty otherwise)
permissions array Audit log of tool permission decisions (see below)
role string Role that owns the session, stamped at creation (empty for a plain root or a headless run with no --role)
session_id string Six-character base36 session id, embedded in an auto name's trailing component (empty for explicit names)
session_name string Session name, matches the filename
sub_sessions array Names of sessions spawned from this one (calls, since the call sets the sub-agent's parent_id)
turns array The conversation log, append-only, one entry per turn
updated_at string ISO 8601 UTC timestamp, bumped on every appended part
version string Polyglav version that created the session, stamped at creation (empty for files written before the field)

/sessions preview prints the parent and sub-sessions links. /sessions list shows root sessions only. /history --tree and /print --tree reach the sub-runs.

A session's title, outcome, and idle_at are derived on read rather than stored, so the log stays the single source of truth and no index file is needed. title is the first user prompt collapsed to one line and clipped to 60 characters, outcome is error when any turn failed and ok otherwise, and idle_at is the last turn's ended_at (falling back to updated_at). /sessions preview shows all three.

Turn and part schema

A turn is one user prompt (or one slash command) and the agent's response to it. It holds the turn-level context and an ordered list of parts:

Turn field Description
index 1-based position in the log
started_at / ended_at ISO 8601 UTC timestamps (duration is the difference)
status running, ok, error, truncated, empty, or cancelled
model / provider Model and provider that served the turn
mode Agent mode in effect (read or write)
reasoning The reasoning config value in effect (false/"off" or an effort value)
usage Provider usage summed across every request in the turn (prompt_tokens, completion_tokens, reasoning_tokens, total_tokens, requests) plus the last request's context_tokens, when the provider reported it. Recorded on agent turns
context_tokens Context/input token count the turn ran with (prompt_tokens, else a chars/4 fallback). Recorded on agent turns
finish_reason The provider's raw stop reason (stop, length, tool_calls, ...) when the provider reported one. Recorded on agent turns
parts Ordered list of parts (below)

Every part has type and timestamp. Fields beyond those depend on the type:

Part type Fields Description
user text, origin A user prompt. origin records who sent it: absent or user for the person, a role name for a delegated prompt
text text Assistant answer text
thinking text Reasoning that preceded the answer or the tool call
tool name, input, output, is_error, analysis, call_id, duration, usage, result_tokens One tool call and its result, co-located. usage is the assistant round that issued the call, recorded once per round. input is the parsed argument object, is_error marks an Error result, analysis is reserved for a one-line insight, call_id is the provider's tool-call id, duration is the wall-clock seconds the call took, and result_tokens is the chars/4 estimate of the full result before truncation
command text A slash command. summary, compact_from, compact_from_part, compaction_index, auto, reason, usage, context_before, context_after, rounds_summarized, and tokens_summarized are set on a /compact record
system text An injected note

A tool call and its result never split into separate records: the tool part is created with name/input/call_id, the engine executes the call, and output/is_error/analysis/duration fill in on the same part. Thinking recorded before a tool round becomes a thinking part ahead of the tool parts.

Examples

A plain prompt and answer:

{
  "index": 1, "started_at": "2026-08-17T12:00:00+00:00",
  "ended_at": "2026-08-17T12:00:05+00:00", "status": "ok",
  "model": "llama3.2", "provider": "ollama", "mode": "read",
  "parts": [
    {"type": "user", "text": "What is OEE?", "timestamp": "2026-08-17T12:00:00+00:00"},
    {"type": "thinking", "text": "The user asks a definitional question, answer directly.", "timestamp": "2026-08-17T12:00:01+00:00"},
    {"type": "text", "text": "OEE is Overall Equipment Effectiveness...", "timestamp": "2026-08-17T12:00:05+00:00"}
  ]
}

A tool round and the final answer:

{
  "index": 2, "status": "ok",
  "parts": [
    {"type": "user", "text": "search for the latest Python release", "timestamp": "..."},
    {"type": "thinking", "text": "I need current data, search first.", "timestamp": "..."},
    {"type": "tool", "name": "web_search", "input": {"query": "latest Python release"},
     "output": "Web search results...", "is_error": false,
     "analysis": "Pages about recent Python releases, 3.13 being the latest.", "timestamp": "..."},
    {"type": "text", "text": "The latest release is 3.13...", "timestamp": "..."}
  ]
}

A command and a compaction record:

{"index": 3, "status": "ok", "parts": [
  {"type": "command", "text": "/model llama3.3", "timestamp": "..."}]}
{"index": 4, "status": "ok", "parts": [
  {"type": "command", "text": "/compact", "summary": "Summary of the earlier conversation...",
   "compact_from": 4, "compact_from_part": 7, "compaction_index": 1, "timestamp": "..."}]}

A command part with a summary is a compaction record: summary holds the text, compact_from the turn index, and compact_from_part the part index in that turn where the kept portion starts. A missing compact_from_part or 0 means the whole boundary turn is kept. compaction_index numbers the compaction within the engine process, auto and reason say whether the threshold or /compact triggered it, usage is the summarization request usage, context_before and context_after are the estimated context sizes, and rounds_summarized and tokens_summarized describe the summarized input. The configured system_prompt and mode instruction are injected at request time, never stored in the log.

Errors

Turn-level failures are appended to the errors array, separate from the turn log:

{"code": 401, "message": "Unauthorized", "timestamp": "2026-08-17T12:40:00+00:00"}

code is the HTTP status where one exists, otherwise 0. Errors include provider auth/network failures, stream EOF or empty completions, max_tokens truncation, and unexpected agent-loop exceptions.

Permissions

Every tool permission resolution is recorded to the permissions array, making the log an audit trail of what the agent was allowed to do:

{"tool": "run_command", "action": "ask", "decision": "granted", "path": "/home/me/proj", "timestamp": "2026-08-17T12:40:00+00:00"}
{"tool": "file_write", "action": "deny", "decision": "denied", "path": "/home/me/proj/a.md", "timestamp": "2026-08-17T12:41:00+00:00"}
Field Description
tool The tool name
action The resolved policy action: allow, ask, or deny
decision The outcome: granted (ran), declined (user refused an ask), or denied (blocked by policy)
path The tool's path_arg value when the tool has one (e.g. the file or command target)
timestamp ISO 8601 UTC timestamp

Per-invocation (resolver-based) actions are recorded the same way, for example delegate logs the action resolved from the target role, so which delegation was allowed, asked, or denied is auditable. Entries are append-only and never removed. Recording is always on, with no config switch, so the log stays a reliable audit record.

Append-only semantics

Turns and errors are only ever appended. Compaction stores the summary in a command part and leaves the earlier turns in place. Loading a session never rewrites history. The only transformations happen at serialization time (below), never to the in-memory log. A turn is written whenever it produced content or thinking, so a truncated mid-reasoning turn still persists its thinking, and a reasoning-only turn (thinking, no text) is recorded rather than lost. An empty turn (no content, no thinking) still records its status and any tool results.

Serialization-time transforms

Every tool result appends to one log beside the session, .polyglav/sessions/<session>.tools.log, when tool_output_log is true (the default). The tool part records a relative line-range ref such as .polyglav/sessions/<session>.tools.log#L120-L180, plus bytes, lines, and summary. The session keeps the summary as its inline output, while /print and Markdown export resolve the line range to the full section. Small results are logged too.

Disabling tool_output_log keeps the full inline output and accepts a larger session file. The log is deleted with its session, is never pruned partially, and a missing ref renders [tool log missing]. Old sessions with inline output load as-is.

Preparing the provider context

The provider payload is prepared from the turns by turns.provider_messages() (via Engine._provider_messages):

  • The latest command part with a summary becomes a system summary: Summary of earlier conversation:\n\n<summary>, turns before its compact_from index are skipped, and within the boundary turn only parts from compact_from_part are used while its user and system prelude stays.
  • command parts are dropped.
  • Within a turn, assistant text and the consecutive tool parts that follow become one assistant message with tool_calls (reusing each part's stored call_id, or a synthesized id for older logs), followed by the tool result messages, so a co-located tool round rebuilds to the OpenAI-compatible shape.
  • thinking is attached to the assistant message it preceded.
  • user and system parts pass through in order.

When a session has plan set, a bounded plan block is injected as a system message after the mode instruction. It holds the path, the next mode and role, the status, and the plan body (capped at 8000 chars). A todo block, when present, follows it as a compact current-work block. Both are read from their files at request time and are not part of the summarized turns, so compaction never removes them. The plan path is included in the Markdown header and the JSON info document, and the todo state is stored in .polyglav/todos/<session>.json.

For compaction, tool results fold back into the summarized context as [tool result] <output> user messages so the summary can carry forward what the tools found.

Compaction

/compact summarizes the earlier conversation and trims the provider context, controlled by compact_keep (default 1 round kept at the tail). A round is one assistant response with its tool calls and results, or one assistant answer. The current user prompt is always kept. The summary is stored in the summary of a command part with a compact_from turn index and a compact_from_part part index, so the full history stays in the log while only the summary plus the kept rounds are sent to the model going forward. Automatic compaction uses the same boundary when compact_auto is on. The record also carries the summarization usage and the context size before and after, so a run log shows what each compaction cost.

The same summary is also written to .polyglav/summaries/<name>.md as a standalone brief (session name, compact_from turn and part, version, then the summary text), so a person or another agent can attach it without reading the session log. That file is derived and best-effort, and the in-log command part stays the source of truth.