mirror of
https://github.com/openclaw/openclaw.git
synced 2026-07-15 12:16:06 +00:00
* refactor(sessions): migrate runtime storage to sqlite * test(sessions): fix sqlite CI regressions * test(sessions): align remaining sqlite fixtures * fix(codex): require sqlite trajectory recorder * test(sessions): align orphan recovery sqlite fixture * test(sessions): align sqlite rebase fixtures * fix(sessions): finish current-main integration of the sqlite flip Resolve the whole-store SDK removal across its owner boundary: drop the loadSessionStore re-export and the registry whole-store wrappers, wire hasTrackedActiveSessionRun into gateway chat, complete the preserveLockedHarnessIds cleanup contract, flip the codex thread-history import to storePath targets, and port remaining main-side tests from file-store helpers to session accessor reads. * chore: drop committed pebbles log, revert plugin-inspector bump, refresh generated docs Remove the 1.8k-line .pebbles/events.jsonl work log from the branch, restore the plugin-inspector advisory lane to main's pinned 0.3.10 so the supply-chain bump gets its own review, and regenerate docs_map, the plugin SDK API baseline, and the export-surface ratchet for the merged tree. * feat(sessions): keep archived transcripts by default with zstd cold storage Codex-style retention: deleting or resetting a session archives its transcript as a zstd-compressed JSONL artifact (plain when the runtime lacks node:zlib zstd) and keeps it until the disk budget evicts oldest first. resetArchiveRetention now governs both deleted and reset archives and defaults to keep; maxDiskBytes defaults to 2gb so retention stays bounded, with archives evicted before live sessions. The cron reaper follows the same knob instead of deleting archives on its own timer. * fix(state): converge agent DB migration lineages and bound database growth Merge coherence: run both structure-gated legacy memory-schema repairs (flip-lineage drop, main-lineage identity rebuild) before the flip migration so pre-flip v1/v2 and pre-merge flip v1/v4 databases all converge, and hoist foreign_keys=OFF outside the schema transaction where the pragma was silently ignored and the v1 sessions rebuild cascade-deleted session_entries. Growth guards: fresh agent DBs enable auto_vacuum=INCREMENTAL, WAL maintenance releases freed pages in bounded passes (never a blocking full VACUUM), and doctor reports state/agent DB bloat from freelist stats. * fix(codex): resolve the store path for thread-history import via the SDK The supervision catalog passed the legacy sessionFile locator to the storePath-targeted transcript mirror; resolve the agent store path with the session-store SDK helper instead of a runtime-object seam so test fakes and headless callers need no extra surface. Drop the obsolete missing-session-id preprocessing case: sessions rows are NOT NULL on session_id and upsert repairs id-less patches at write time. * fix(sessions): fail safe on malformed disk-budget config and doctor stat errors A malformed explicit maxDiskBytes disables the budget instead of falling back to the destructive 2gb default the user never chose, and the doctor bloat check skips databases whose paths stat-fail instead of aborting doctor. * fix(sessions): complete sqlite conflict translations * test(sqlite): align hardening checks with maintenance * test(sessions): inspect compressed transcript archives * fix(tests): await session seeds and drop unused helpers flagged by CI lint The five unawaited writeSessionStoreSeed calls raced their SQLite seeds against the assertions, failing compact shards; the bloat probe drops a useless initializer and the merged tests drop now-unused helpers. * test(sessions): type legacy proof events directly * test(sessions): align hardening contracts * perf(sessions): read usage transcript sizes from SQL aggregates Usage/cost scans walked every session and materialized every transcript event just to re-stringify it for a byte estimate — the #86718 stall class reborn on the DB. readTranscriptStatsSync sums stored JSON bytes in SQLite without loading a single row. * fix(sessions): re-root foreign-root transcript paths onto the current sessions dir Restored backups, moved OPENCLAW_STATE_DIR, and rehearsal copies carry absolute sessionFile paths from the old root; the containment fallback kept those foreign paths, so migration read (and would archive) files in the original root and reported local copies missing. Re-root the canonical agents/<id>/sessions suffix onto the current dir when the file exists there; genuine cross-root layouts still fall through unchanged. * test(agents): seed harness admission through sqlite * fix(sqlite): close agent db on pragma setup failure * fix(doctor): compact and retrofit incremental auto-vacuum after session import The migration is the sanctioned offline window: post-import compact reclaims import churn and applies auto_vacuum=INCREMENTAL to databases created before the fresh-DB pragma existed, so runtime maintenance can release pages in bounded passes on every install. --------- Co-authored-by: Peter Steinberger <steipete@gmail.com>
141 lines
12 KiB
Markdown
141 lines
12 KiB
Markdown
---
|
||
summary: "Agent tools for cross-session status, recall, messaging, and sub-agent orchestration"
|
||
read_when:
|
||
- You want to understand what session tools the agent has
|
||
- You want to configure cross-session access or sub-agent spawning
|
||
- You want to inspect spawned sub-agent status
|
||
title: "Session tools"
|
||
---
|
||
|
||
OpenClaw gives agents tools to work across sessions, inspect status, and orchestrate sub-agents.
|
||
|
||
## Available tools
|
||
|
||
| Tool | What it does |
|
||
| ------------------ | --------------------------------------------------------------------------- |
|
||
| `sessions_list` | List sessions with optional filters (kind, label, agent, archive, preview) |
|
||
| `sessions_history` | Read the transcript of a specific session |
|
||
| `sessions_send` | Send a message to another session and optionally wait |
|
||
| `sessions_spawn` | Spawn an isolated sub-agent session for background work |
|
||
| `sessions_yield` | End the current turn and wait for follow-up sub-agent results |
|
||
| `subagents` | List spawned sub-agent status for this session |
|
||
| `session_status` | Show a `/status`-style card and optionally set a per-session model override |
|
||
|
||
These tools are still subject to the active tool profile and allow/deny policy. `tools.profile: "coding"` includes the full session orchestration set, including `sessions_spawn`, `sessions_yield`, and `subagents`. `tools.profile: "messaging"` includes cross-session messaging tools (`sessions_list`, `sessions_history`, `sessions_send`, `session_status`) but does not include sub-agent spawning. To keep a messaging profile and still allow native delegation, add:
|
||
|
||
```json5
|
||
{
|
||
tools: {
|
||
profile: "messaging",
|
||
alsoAllow: ["sessions_spawn", "sessions_yield", "subagents"],
|
||
},
|
||
}
|
||
```
|
||
|
||
Group, provider, sandbox, and per-agent policies can still remove those tools after the profile stage. Use `/tools` from the affected session to inspect the effective tool list.
|
||
|
||
## Listing and reading sessions
|
||
|
||
`sessions_list` returns sessions with their key, agentId, kind, channel, model, token counts, and timestamps. Filter by `kinds` (array; accepted values: `main`, `group`, `cron`, `hook`, `node`, `other`), exact `label`, exact `agentId`, `search` text, or recency (`activeMinutes`). Active sessions are returned by default; pass `archived: true` to inspect archived sessions instead. Rows include `pinned` and `archived` state. Set `includeDerivedTitles`, `includeLastMessage`, or `messageLimit` (capped at 20) when you need mailbox-style triage: a visibility-scoped derived title, a last-message preview snippet, or bounded recent messages on each row. Derived titles and previews are produced only for sessions the caller can already see under the configured session tool visibility policy, so unrelated sessions stay hidden. When visibility is restricted, `sessions_list` returns optional `visibility` metadata showing the effective mode and a warning that results may be scope-limited.
|
||
|
||
`sessions_history` fetches the conversation transcript for a specific session. By default, tool results are excluded; pass `includeTools: true` to see them. Use `limit` for the newest bounded tail. Pass `offset: 0` when you need pagination metadata, then pass returned `nextOffset` values to page backward through older OpenClaw transcript windows without reading raw transcript files. Explicit offset pages do not merge external CLI fallback imports; use the default newest-tail view (no `offset`) when you need that merged display history.
|
||
|
||
The returned view is intentionally bounded and safety-filtered:
|
||
|
||
- assistant text is normalized before recall:
|
||
- thinking tags are stripped
|
||
- `<relevant-memories>` / `<relevant_memories>` scaffolding blocks are stripped
|
||
- plain-text tool-call XML payload blocks such as `<tool_call>...</tool_call>`, `<function_call>...</function_call>`, `<tool_calls>...</tool_calls>`, and `<function_calls>...</function_calls>` are stripped, including truncated payloads that never close cleanly
|
||
- downgraded tool-call/result scaffolding such as `[Tool Call: ...]`, `[Tool Result ...]`, and `[Historical context ...]` is stripped
|
||
- leaked model control tokens such as `<|assistant|>`, other ASCII `<|...|>` tokens, and full-width `<|...|>` variants are stripped
|
||
- malformed MiniMax tool-call XML such as `<invoke ...>` / `</minimax:tool_call>` is stripped
|
||
- credential/token-like text is redacted before it is returned
|
||
- long text blocks are truncated
|
||
- very large histories can drop older rows or replace an oversized row with `[sessions_history omitted: message too large]`
|
||
- the tool reports summary flags such as `truncated`, `droppedMessages`, `contentTruncated`, `contentRedacted`, `bytes`, and pagination metadata
|
||
|
||
Both tools accept either a **session key** (like `"main"`) or a **session ID** from a previous list call.
|
||
|
||
If you need the exact raw transcript, inspect the scoped SQLite transcript rows instead of treating `sessions_history` as an unfiltered dump.
|
||
|
||
## Sending cross-session messages
|
||
|
||
`sessions_send` delivers a message to another session and optionally waits for the response:
|
||
|
||
- **Fire-and-forget:** set `timeoutSeconds: 0` to enqueue and return immediately.
|
||
- **Wait for reply:** set a timeout and get the response inline.
|
||
|
||
Thread-scoped chat sessions, such as keys ending in `:thread:<id>`, are not valid `sessions_send` targets. Use the parent channel session key for inter-agent coordination so tool-routed messages do not appear inside an active human-facing thread.
|
||
|
||
Messages and A2A follow-up replies are marked as inter-session data in the receiving prompt (`[Inter-session message ... isUser=false]`) and in transcript provenance. The receiving agent should treat them as tool-routed data, not as a direct end-user-authored instruction.
|
||
|
||
After the target responds, OpenClaw can run a **reply-back loop** where the agents alternate messages (up to `session.agentToAgent.maxPingPongTurns`, range 0-20, default 5). The target agent can reply `REPLY_SKIP` to stop early.
|
||
|
||
## Status and orchestration helpers
|
||
|
||
`session_status` is the lightweight `/status`-equivalent tool for the current or another visible session. It reports usage, time, model/runtime state, and linked background-task context when present. Like `/status`, it can backfill sparse token/cache counters from the latest transcript usage entry, and `model=default` clears a per-session override. Use `sessionKey="current"` for the caller's current session; visible client labels such as `openclaw-tui` are not session keys.
|
||
|
||
When route metadata is available, `session_status` also includes a visible `Route context` JSON block and matching structured `details` fields. These fields disambiguate the session key from the route that is currently handling the live run:
|
||
|
||
- `origin` is where the session was created, or the provider inferred from a deliverable session-key prefix when older state lacks stored origin metadata.
|
||
- `active` is the current live-run route. It is only reported for the live or current session being handled now.
|
||
- `deliveryContext` is the persisted delivery route stored on the session, which OpenClaw can reuse for later delivery even when the active surface differs.
|
||
|
||
## Session state changes
|
||
|
||
OpenClaw keeps a best-effort signal log for selected session state changes: direct human messages to child sessions, child-run completion or failure, child creation, goal changes, and compaction. Cancelled and timed-out child runs are recorded as failures, with the specific outcome (`cancelled`, `timeout`, or `error`) preserved in the event payload. The log contains metadata and one-line summaries, never message content. Its `stateVersion` is the session's signal-log head, not a transactional change-data-capture version; the session-store mutation and signal append use separate storage, so a failed append is logged without failing the originating turn.
|
||
|
||
`sessions_list` includes `stateVersion` on rows with logged changes. `session_status` always returns `stateVersion` in structured details. Pass `changesSince: <previousStateVersion>` to retrieve up to 200 retained events after that version; this read does not acknowledge or advance parent notification cursors. A `historyGap: true` result means the requested version predates retained history, so refresh the whole session state instead of treating the response as an exact delta.
|
||
|
||
When another actor sends a direct human turn to a watched child or changes its goal, the parent receives a system notice telling it to call `session_status` with its last-seen version. Main-session parents are proactively woken. Nested sub-agent parents receive the notice on their next turn because heartbeat routing cannot target their queue directly. Completion announcements remain the owner for ordinary child-run completion delivery.
|
||
|
||
History is bounded to 30 days and 50,000 rows, while per-session heads remain monotonic after pruning. Notice delivery uses the gateway's in-memory system-event queue and assumes one gateway process owns delivery for the shared state database. Multiple gateways still share the durable log and `changesSince` reconciliation surface, but v1 does not push notices across processes. Parent notices require an agent-qualified parent session key; under `session.scope="global"` the shared `global` key is ambiguous across agents, so those parents get the durable log and `changesSince` but no proactive notices in v1.
|
||
|
||
`sessions_yield` intentionally ends the current turn so the next message can be the follow-up event you are waiting for. Use it after spawning sub-agents when you want completion results to arrive as the next message instead of building poll loops.
|
||
|
||
`subagents` is the visibility helper for already spawned OpenClaw sub-agents. It supports `action: "list"` to inspect active/recent runs.
|
||
|
||
## Spawning sub-agents
|
||
|
||
`sessions_spawn` creates an isolated session for a background task by default. It is always non-blocking; it returns immediately with a `runId` and `childSessionKey`. Native sub-agent runs receive the delegated task in the child session's first visible `[Subagent Task]` message, while the system prompt carries only sub-agent runtime rules and routing context.
|
||
|
||
Key options:
|
||
|
||
- `runtime: "subagent"` (default) or `"acp"` for external harness agents.
|
||
- `model` and `thinking` overrides for the child session.
|
||
- `thread: true` to bind the spawn to a chat thread (Discord, Slack, etc.).
|
||
- `sandbox: "require"` to enforce sandboxing on the child.
|
||
- `context: "fork"` for native sub-agents when the child needs the current requester transcript; omit it or use `context: "isolated"` for a clean child. `context: "fork"` is only valid with `runtime: "subagent"`. Thread-bound native sub-agents default to `context: "fork"` unless `threadBindings.defaultSpawnContext` says otherwise.
|
||
|
||
Default leaf sub-agents do not get session tools. When `maxSpawnDepth >= 2`, depth-1 orchestrator sub-agents additionally receive `sessions_spawn`, `subagents`, `sessions_list`, and `sessions_history` so they can manage their own children. Leaf runs still do not get recursive orchestration tools.
|
||
|
||
After completion, an announce step posts the result to the requester's channel. Completion delivery preserves bound thread/topic routing when available, and if the completion origin only identifies a channel, OpenClaw can still reuse the requester session's stored route (`lastChannel` / `lastTo`) for direct delivery.
|
||
|
||
For ACP-specific behavior, see [ACP Agents](/tools/acp-agents).
|
||
|
||
## Visibility
|
||
|
||
Session tools are scoped to limit what the agent can see:
|
||
|
||
| Level | Scope |
|
||
| ------- | ---------------------------------------- |
|
||
| `self` | Only the current session |
|
||
| `tree` | Current session + spawned sub-agents |
|
||
| `agent` | All sessions for this agent |
|
||
| `all` | All sessions (cross-agent if configured) |
|
||
|
||
Default is `tree`. Sandboxed sessions are clamped to `tree` regardless of config.
|
||
|
||
## Further reading
|
||
|
||
- [Session Management](/concepts/session): routing, lifecycle, maintenance
|
||
- [Sub-agents](/tools/subagents): child-session lifecycle and delivery
|
||
- [ACP Agents](/tools/acp-agents): external harness spawning
|
||
- [Multi-agent](/concepts/multi-agent): multi-agent architecture
|
||
- [Gateway Configuration](/gateway/configuration): session tool config knobs
|
||
|
||
## Related
|
||
|
||
- [Session management](/concepts/session)
|
||
- [Session pruning](/concepts/session-pruning)
|