refactor(session): centralize state ownership in SQLite (#5943)

* fix(session): move persistence off event loop

* refactor(session): isolate async persistence boundary

* refactor(session): keep a single session manager

* refactor(session): use stateless async adapters

* fix(session): serialize local persistence without file-lock contention

* refactor(session): own async persistence and snapshot commits

* refactor(session): narrow persistence changes to async adapters

* refactor(session): remove redundant async forwarding helpers

* fix(command): offload compact session persistence

* fix(session): adapt idle compaction to current main

* fix(webui): offload session metadata persistence

* refactor(session): centralize state ownership in SQLite

* fix(session): skip storage for non-recoverable followups

* test(webui): honor the full gateway event deadline

* perf(session): persist incremental changes and reuse owner snapshots

* test(agent): allow durable worker shutdown in burst test

* fix(gateway): drain session storage on Windows console shutdown

* fix(session): enforce bounded ownership and lifecycle-safe persistence

* fix: reject unresolved home paths and stabilize platform tests

* fix(session): preserve request context compatibility and owner-backed tests

* docs: focus configuration guide on user-facing behavior

* fix(session): adapt goal admission to async ownership after rebase

* fix(session): integrate current gateway and subagent contracts

* fix(session): align rebased workspace admission and async tests

* fix(session): support compatible SQLite schema evolution

* test(agent): use session owner in workspace context regressions

* test: stabilize Windows lifecycle and browser checks

* refactor(session): remove premature JSONL file export

* ci: bound Windows full-suite worker concurrency

* chore: remove session state refactor notes

* fix(session): queue writes and retain worker connections

* perf(webui): read detached metadata for session and task lists

* perf(agent): bound prompt preparation and local token counting

* docs: remove internal session storage guide

* perf(session): skip archived transcripts during idle scans

* fix(session): coordinate turns and isolate legacy session data

Bind WebUI input generations to the execution session and serialize idle
and SDK compaction with turns. Keep turn drafts through preparation so the
latest channel route persists.

Move imported workspace JSONL and checkpoints to durable private backups
before gateway admission, resuming cleanup after interruptions. Remove
committed child sessions when task creation is cancelled.

Validation: focused Python and frontend regressions, Ruff, BasedPyright,
import boundaries, WebUI build, and isolated gateway/browser flows.

* fix(agent): keep cancellation hooks independent of prompt preparation

* fix(session): preserve admission, delivery, and migration contracts

* fix(agent): preserve cancellation settlement after rebase

* fix(session): preserve request attribution through async ownership
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-16 17:28:47 +08:00
1 parent 33ff520d12
commit 8f6a5594fb
144 files changed
+8293 -4912

No files matched your search

+2 -2
View File
@@ -148,7 +148,7 @@ Defaults:
|---|---|
| Config | `~/.nanobot/config.json` |
| Workspace | `~/.nanobot/workspace/` |
| Sessions | `<config-dir>/sessions/<workspace-id>/*.jsonl` (default: `~/.nanobot/sessions/...`) |
| Sessions | `<config-dir>/sessions/<workspace-id>/sessions.sqlite3` (default: `~/.nanobot/sessions/...`) |
| Memory | `<workspace>/memory/` |
| Cron store | `<workspace>/cron/jobs.json` |
| WebUI/media/log runtime data | config directory subdirectories such as `webui/`, `media/`, and `logs/` |
@@ -175,7 +175,7 @@ Session history is the near-term conversation replay. Memory is the longer-term
| Store | File area |
|---|---|
| Session JSONL files | `<config-dir>/sessions/<workspace-id>/` |
| SQLite conversation state | `<config-dir>/sessions/<workspace-id>/sessions.sqlite3` |
| Long-term memory | `<workspace>/memory/MEMORY.md` |
| Consolidation source history | `<workspace>/memory/history.jsonl` |
| Bootstrap identity files | `<workspace>/SOUL.md`, `<workspace>/USER.md`, templates under `nanobot/templates/` |
+4 -8
View File
@@ -111,17 +111,13 @@ Status does not send a model request. On success, run the printed `nanobot agent
Inside the native TUI, `/sessions` switches saved conversations, `/new-chat` starts another saved conversation, and `/context` explains the compacted summary and raw session suffix available to the next agent turn. `/branch` forks a saved conversation from a completed reply, and `/diff` opens the latest turn's file changes as a full-screen unified diff. `PageUp` loads older transcript pages when you reach the top. By default, each launch starts a new session using the launch directory as its workspace. `--session` selects a specific existing session, and `--workspace` overrides the launch directory. When the TUI exits, it prints a ready-to-run `nanobot agent --session ...` command for the current session.
## Session Storage and Rollback
## Session Storage
Session JSONL files live under `<config-dir>/sessions/<workspace-id>/`, outside the agent-readable workspace. On the first upgraded start, nanobot safely migrates existing `<workspace>/sessions/*.jsonl` files after verifying an atomic copy. Stop every old nanobot process that uses the workspace before upgrading; old and new binaries must not write the same session concurrently.
Session state lives in `<config-dir>/sessions/<workspace-id>/sessions.sqlite3`, outside the agent-readable workspace. Existing JSONL conversations are imported on the first startup. JSONL migration is available from 0.3.6 through 0.4.x and is removed in **0.5.0**; installations with only JSONL data must upgrade through that window before using 0.5.0.
To prepare a downgrade, stop nanobot and copy the current sessions back to the path understood by older releases:
After a successful import, JSONL files and their checkpoints from `<workspace>/sessions/` move to `<config-dir>/sessions/<workspace-id>/jsonl-backup/`, preserving their contents outside the agent-readable workspace. JSONL files already in the private session directory remain there. An interrupted migration resumes on startup before nanobot serves conversations; failed imports leave their source files unchanged.
```bash
nanobot sessions restore-workspace --config ./bot-a/config.json --workspace ./bot-a/workspace
```
The command never deletes the external store and refuses to overwrite a different existing workspace file. Back up both the config directory and workspace before changing versions.
Before changing versions, stop nanobot gracefully and back up both the config directory and workspace. To downgrade, restore a backup compatible with the older release. Copying only `sessions.sqlite3` while nanobot is running can miss recent messages still held in its WAL file.
Interactive mode uses nanobot's native TypeScript terminal UI. It talks to the same local gateway as the WebUI, so streaming, tool progress, and WebSocket sessions share one protocol instead of maintaining a second agent loop. If no gateway is running, either client starts it on demand. The TUI paints immediately while the local gateway starts, then obtains fresh bootstrap credentials and connects in the background. Exiting one TUI or WebUI launcher releases only that client; the last interactive launcher stops the on-demand gateway. A small gateway watchdog also reclaims an on-demand process if its last client crashes. `/detach` promotes the shared gateway to persistent background mode before closing the TUI, so active agent work continues without a connected client. An explicit `nanobot gateway --background` starts or promotes the gateway the same way before opening a client. `nanobot gateway restart` restarts a detached gateway without changing that lifetime; restart an attached foreground gateway in its owning terminal. `nanobot gateway stop` ends either mode.
+1 -1
View File
@@ -129,7 +129,7 @@ nanobot uses two related stores:
| Store | Location | Purpose |
|---|---|---|
| Sessions | `<config-dir>/sessions/<workspace-id>/*.jsonl` | Recent conversation turns replayed into context |
| Sessions | `<config-dir>/sessions/<workspace-id>/sessions.sqlite3` | Recent conversation turns replayed into context |
| Memory | `<workspace>/memory/MEMORY.md` and `<workspace>/memory/history.jsonl` | Long-term facts and consolidated history |
Dream is a periodic consolidation job. It reads accumulated history and updates workspace memory so useful context can survive beyond short session replay.
+23 -34
View File
@@ -131,7 +131,7 @@ If a referenced variable is unset, nanobot fails fast and reports the exact conf
### Loading variables at startup
Pick whatever fits your deployment — nanobot only reads `os.environ` at startup, so any mechanism that populates the process environment works.
Set the variables in the environment that starts nanobot. Choose the method that fits your deployment:
**systemd** — use `EnvironmentFile=` in the service unit to load variables from a file that only the deploying user can read:
@@ -212,7 +212,7 @@ Internal variables such as `NANOBOT_RESTART_*` and `NANOBOT_PATH_*` are set by n
## Langfuse Observability
nanobot can trace OpenAI-compatible provider calls through Langfuse's OpenAI SDK wrapper, and Codex OAuth provider calls through Langfuse's native Python SDK. This is configured with environment variables, not `config.json`.
Use Langfuse to trace OpenAI-compatible model calls and Codex OAuth calls. Configure it with environment variables, not `config.json`.
Install the optional package in the same Python environment that runs nanobot:
@@ -236,11 +236,11 @@ $env:LANGFUSE_PUBLIC_KEY = "pk-lf-..."
$env:LANGFUSE_BASE_URL = "https://cloud.langfuse.com"
```
When `LANGFUSE_SECRET_KEY` is set and the `langfuse` package is installed, nanobot uses `langfuse.openai.AsyncOpenAI` for OpenAI-compatible providers so model requests are sent to Langfuse in the background. If the secret key is set but `langfuse` is missing, nanobot logs a warning and falls back to the regular OpenAI client. The Codex OAuth provider (`openai_codex`) uses the same `LANGFUSE_SECRET_KEY` check but logs each request through Langfuse's native SDK directly, since Codex does not use the OpenAI Python SDK client.
When `LANGFUSE_SECRET_KEY` is set and the `langfuse` package is installed, tracing is enabled for OpenAI-compatible providers and the Codex OAuth provider (`openai_codex`). If the package is missing, nanobot logs a warning and model calls continue without tracing.
Use the Langfuse region or self-hosted URL that matches your project. The [Langfuse OpenAI SDK docs](https://langfuse.com/integrations/model-providers/openai-py) use `LANGFUSE_BASE_URL` for cloud regions and self-hosted instances.
Tracing covers the providers that go through nanobot's OpenAI-compatible client path, plus the Codex OAuth provider (`openai_codex`) via Langfuse's native SDK. Other native providers that do not use either path may not produce Langfuse traces.
Other native provider integrations are not covered by this tracing setup.
## Providers
@@ -417,7 +417,7 @@ The `azure_openai` provider talks to your Azure OpenAI resource via the OpenAI *
**Mode 2: Microsoft Entra ID (Azure AD) via `DefaultAzureCredential`**
Omit `apiKey` (or leave it empty / unset). The provider falls back to [`DefaultAzureCredential`](https://learn.microsoft.com/azure/developer/python/sdk/authentication/credential-chains#defaultazurecredential-overview) and acquires a bearer token scoped to `https://cognitiveservices.azure.com/.default` for every request. The Azure SDK's own MSAL-backed cache returns valid tokens without a network round-trip.
Omit `apiKey` (or leave it empty) to use your Azure identity through [`DefaultAzureCredential`](https://learn.microsoft.com/azure/developer/python/sdk/authentication/credential-chains#defaultazurecredential-overview).
```json
{
@@ -526,7 +526,7 @@ Use the normal AWS credential chain (`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KE
}
```
You can also set `providers.bedrock.apiKey` to a Bedrock API key; nanobot exports it as `AWS_BEARER_TOKEN_BEDROCK` for the AWS SDK.
You can also supply a Bedrock API key through `providers.bedrock.apiKey` or the `AWS_BEARER_TOKEN_BEDROCK` environment variable.
Credential options:
@@ -643,7 +643,7 @@ Anthropic models on Bedrock can also require Anthropic use-case registration and
**4. Model IDs**
Use Bedrock model IDs or inference profile IDs with a `bedrock/` prefix in nanobot config. nanobot removes the prefix before calling AWS.
Use Bedrock model IDs or inference profile IDs with a `bedrock/` prefix in nanobot config.
Examples:
@@ -680,7 +680,7 @@ Model-specific fields can be supplied with `extraBody`; nanobot merges it into C
Use `apiBase` only for a custom Bedrock Runtime endpoint URL, such as a VPC endpoint or proxy. It is not needed for normal AWS regions.
Current scope: nanobot passes `messages`, `system`, `inferenceConfig`, `toolConfig`, and `additionalModelRequestFields`. Bedrock Prompt Management, Guardrails, `serviceTier`, and other top-level Converse options are not first-class config fields yet.
Bedrock Prompt Management, Guardrails, `serviceTier`, and other top-level Converse options are not available as dedicated configuration fields.
**6. Quick checks**
@@ -1724,9 +1724,7 @@ Telegram `richMessages` defaults to `false`. Enable it only to opt in to Bot API
### Retry Behavior
Retry is intentionally simple.
When a channel `send()` raises, nanobot retries at the channel-manager layer. By default, `channels.sendMaxRetries` is `3`, and that count includes the initial send.
When message delivery fails, nanobot retries. `channels.sendMaxRetries` defaults to `3`, including the initial attempt.
- **Attempt 1**: Send immediately
- **Attempt 2**: Retry after `1s`
@@ -1736,9 +1734,7 @@ When a channel `send()` raises, nanobot retries at the channel-manager layer. By
- **Permanent failures**: Invalid tokens, revoked access, or banned channels will exhaust the retry budget and fail cleanly
> [!NOTE]
> This design is deliberate: channel implementations should raise on delivery failure, and the channel manager owns the shared retry policy.
>
> Some channels may still apply small API-specific retries internally. For example, Telegram separately retries timeout and flood-control errors before surfacing a final failure to the manager.
> Some channels make additional retries for specific errors, so the total number of delivery attempts can exceed `channels.sendMaxRetries`. Telegram, for example, also retries timeouts and flood-control errors.
>
> If a channel is completely unreachable, nanobot cannot notify the user through that same channel. Watch logs for `Failed to send to {channel} after N attempts` to spot persistent delivery failures.
@@ -2277,8 +2273,8 @@ For API keys, tokens, and other secrets, see [Environment Variables for Secrets]
| `tools.exec.timeout` | alias | Legacy name for `maxRuntime`, not an inactivity timeout. Existing explicit values, including `0`, keep their hard-runtime meaning. Do not set both names. |
| `tools.exec.pathPrepend` | `""` | Extra directories to prepend to `PATH` when running shell commands. Use this when configured tools should win executable lookup precedence, such as a Python virtual environment's `bin` or `Scripts` directory. |
| `tools.exec.pathAppend` | `""` | Extra directories to append to `PATH` when running shell commands (e.g. `/usr/sbin` for `ufw`). |
| `tools.exec.sandboxRoBinds` | `[]` | Extra absolute paths to expose read-only inside the exec sandbox (`--ro-bind-try` for `"bwrap"`, an SBPL `file-read*` rule for `"seatbelt"`), such as `/home/user/.local/bin` or `/home/user/.cargo/bin` when those paths are also in `pathPrepend`/`pathAppend`. These roots are also accepted by the shell absolute-path guard only while a sandbox is active. Bind only directories whose contents are safe for agent commands to read; paths equal to or containing the active workspace are ignored so they cannot uncover its masked parent directory. |
| `tools.exec.sandboxRwBinds` | `[]` | Extra absolute paths to expose read-write inside the exec sandbox (`--bind-try` for `"bwrap"`, an SBPL `file-read* file-write*` rule for `"seatbelt"`), for trusted tool caches or scratch directories. Use sparingly: paths listed here are intentionally writable by shell commands inside the sandbox. Paths equal to or containing the active workspace are ignored. |
| `tools.exec.sandboxRoBinds` | `[]` | Extra absolute paths to expose read-only inside the exec sandbox, such as `/home/user/.local/bin` or `/home/user/.cargo/bin` when those paths are also in `pathPrepend`/`pathAppend`. These roots are also accepted by the shell absolute-path guard only while a sandbox is active. Bind only directories whose contents are safe for agent commands to read; paths equal to or containing the active workspace are ignored so they cannot uncover its masked parent directory. |
| `tools.exec.sandboxRwBinds` | `[]` | Extra absolute paths to expose read-write inside the exec sandbox, for trusted tool caches or scratch directories. Use sparingly: paths listed here are intentionally writable by shell commands inside the sandbox. Paths equal to or containing the active workspace are ignored. |
| `tools.webuiAllowRemotePackageInstall` | `false` | When `false`, the WebUI can install missing optional packages only from a browser opened on the same machine as nanobot. Set to `true` only when a trusted remote admin is allowed to install Python packages into this nanobot environment. |
| `tools.ssrfWhitelist` | `[]` | CIDR ranges exempted from the shared SSRF guard used by web fetches and HTTP/SSE MCP connections. Prefer exact host CIDRs such as `192.168.1.50/32`; broad ranges increase SSRF exposure. |
| `channels.*.allowFrom` | omitted | For channels using the common sender allowlist, omit to require pairing, set `["*"]` to allow everyone, or list specific user IDs. Slack and Mattermost instead use `dm.policy` / `dm.allowFrom` for DMs and default to open DMs; review their group policy separately. See [Pairing](#pairing). |
@@ -2432,9 +2428,9 @@ The gateway can run a protected heartbeat cron job that periodically checks `HEA
If `HEARTBEAT.md` has tasks under `## Active Tasks`, the agent executes them and sends only useful/actionable results to the most recently active chat target. If the file has no active tasks, or the result is routine with nothing useful to report, the heartbeat is skipped silently.
This is intentionally different from user-created cron jobs. A cron job created with the `cron` tool runs as a scheduled turn in its origin chat/session and normally delivers the result back to that channel. Use `HEARTBEAT.md` for recurring background checks that should not notify the user on every run.
Use `HEARTBEAT.md` for recurring background checks that should not notify you on every run. For a scheduled task that normally sends its result back to the chat where it was created, use the `cron` tool.
The heartbeat job is backed by the same cron service as user-created reminders. It is stored under the active workspace (`<workspace>/cron/jobs.json`) and shows up in `cron(action="list")` as `heartbeat`, but it is system-managed and cannot be removed with the `cron` tool. Disable it through config and restart the gateway if you do not want periodic heartbeat checks.
The heartbeat appears as `heartbeat` when you list cron jobs, but cannot be removed with the `cron` tool. To disable periodic checks, set `gateway.heartbeat.enabled` to `false` and restart the gateway.
| Option | Default | Description |
|--------|---------|-------------|
@@ -2444,7 +2440,7 @@ The heartbeat job is backed by the same cron service as user-created reminders.
### Custom heartbeat evaluator prompt
The notification gate runs on a built-in system prompt. Advanced users can override it, but you rarely need to — it's strongly advised to first read the evaluator code and the default `evaluator.md`. To override, drop your prompt at `<workspace>/prompts/evaluator.md`. It must still instruct the model to call the `evaluate_notification` tool; otherwise the gate fails closed and stays silent.
To customize which heartbeat results trigger a notification, place your prompt at `<workspace>/prompts/evaluator.md`. Start from the bundled `evaluator.md` prompt and keep its instruction to call `evaluate_notification`; without that call, no notification is sent.
## Subagent Concurrency
@@ -2494,19 +2490,12 @@ When a session is idle for longer than a configured threshold, nanobot summarize
| Option | Default | Description |
|--------|---------|-------------|
| `agents.defaults.idleCompactAfterMinutes` | `15` | Minutes of idle time before auto-compaction starts. Set to `0` to disable. The default is close to a typical LLM KV cache expiry window, so stale sessions get compacted before the user returns. |
| `agents.defaults.idleCompactAfterMinutes` | `15` | Minutes of idle time before auto-compaction starts. Set to `0` to disable. |
| `agents.defaults.idleCompactCheckIntervalSeconds` | `60` | Minimum number of seconds between scans for idle sessions. Set to `0` to scan on every idle tick (~1 s). |
`sessionTtlMinutes` remains accepted as a legacy alias for backward compatibility, but `idleCompactAfterMinutes` is the preferred config key going forward.
How it works:
1. **Idle detection**: On each idle tick (~1 s), checks whether an idle-session scan is due. By default, the full scan runs at most once per minute.
2. **Background compaction**: The conversation so far is summarized for the next turn.
3. **Session preservation**: The complete session history remains stored for later inspection and reuse.
4. **Restart-safe resume**: The compacted context remains available after a process restart.
> [!NOTE]
> Auto compact shortens the context sent to the model without deleting the session's structured message history.
The compacted context remains available after restarting nanobot.
Use `/compact` in chat to compact the current session without waiting for the idle threshold.
@@ -2567,13 +2556,13 @@ When enabled, all incoming messages — regardless of which channel they arrive
| Behavior | `false` (default) | `true` |
|----------|-------------------|--------|
| Session key | `channel:chat_id` | `unified:default` |
| Conversation scope | Separate for each channel and chat | Shared across channels and chats |
| Cross-channel continuity | No | Yes |
| `/new` clears | Current channel session | Shared session |
| `/stop` finds tasks | By channel session | By shared session |
| Existing `session_key_override` (e.g. Telegram thread) | Respected | Still respected — not overwritten |
| Separate conversations explicitly assigned by a channel (e.g. Telegram threads) | Kept separate | Still kept separate |
> This is designed for single-user, multi-device setups. It is **off by default** — existing users see zero behavior change.
> Use this only for single-user, multi-device setups: messages from different chats can share conversation context. It is **off by default**.
## Disabled Skills
@@ -2604,13 +2593,13 @@ Disabled skills are excluded from the main agent's skill summary, from always-on
### Agent Plugins v1
nanobot discovers [Agent Plugins](https://agent-plugins.org/) under `<workspace>/plugins/`; a v1 package has `plugin.json` and may add `mcp.json`, `skills/<name>/SKILL.md`, or both. Agent Plugins are the common package and activation boundary for installable capabilities; they do not replace native providers, channels, tools, standalone workspace skills, or directly configured MCP servers.
Install [Agent Plugins](https://agent-plugins.org/) under `<workspace>/plugins/`, then review and enable them in **Apps**. Copying a package into that directory does not activate it. Plugins can add skills and MCP servers; existing provider, channel, tool, skill, and MCP settings remain available.
Directory presence means installed; activation is explicit in **Apps**. Skills use progressive loading and `$skill-name` invocation, with workspace > plugin > built-in precedence. Enabled `stdio` servers receive contained `PLUGIN_ROOT` and isolated `PLUGIN_DATA` paths; explicit `tools.mcpServers` entries win collisions. Invalid or escaping components are ignored. An enabled package is treated as immutable: changing any packaged file disables it until the user reviews and enables it again. Runtime state belongs under `PLUGIN_DATA`, not the package root.
Enabled plugins run as the nanobot user; permissions are descriptive, not an OS sandbox. The optional `extensions.dev.nanobot.logo` accepts a contained PNG, JPEG, or WebP up to 256 KiB.
Changing any packaged file disables the plugin until you review and enable it again.
CLI Apps use the same skills-only package layout while their installer manages executables, updates, and removal. Future catalogs can place packages before using this activation path.
Enabled plugins run with the same operating-system permissions as nanobot. Their declared permissions are descriptive, **not an OS sandbox**. Install and enable only plugins you trust.
## Tool Hint Max Length
+11 -10
View File
@@ -559,14 +559,15 @@ async with Nanobot.from_config() as bot:
| Method | Description |
|--------|-------------|
| `await ingest(session_key, messages, metadata=None, source=None, save=True)` | Import existing transcript messages without running the model. |
| `get(session_key)` | Return a `SessionSnapshot`, or `None` if missing. |
| `list()` | Return compact `SessionInfo` rows. |
| `export(session_key)` | Return a trusted full `SessionSnapshot`, including model-only runtime context, suitable for JSON serialization. |
| `await restore(snapshot, session_key=None, save=True)` | Restore a trusted exported snapshot into an empty session; the returned snapshot is display-safe. |
| `clear(session_key)` | Clear and persist one session. |
| `delete(session_key)` | Delete one session from disk and cache. |
| `flush()` | Flush cached sessions to durable storage. |
| `await ingest(session_key, messages, metadata=None, source=None)` | Import existing transcript messages without running the model. |
| `await get(session_key)` | Return a `SessionSnapshot`, or `None` if missing. |
| `await list()` | Return compact `SessionInfo` rows. |
| `await export(session_key)` | Return a trusted full `SessionSnapshot`, including model-only runtime context, suitable for JSON serialization. |
| `await restore(snapshot, session_key=None)` | Restore a trusted exported snapshot into an empty session; the returned snapshot is display-safe. |
| `await clear(session_key)` | Clear and persist one session. |
| `await delete(session_key)` | Delete one session from disk and cache. |
Session writes commit before returning. Returned snapshots are detached; changing a snapshot does not save it. See [Session storage](cli-reference.md#session-storage) for upgrade and backup instructions.
Ingested messages must include `role` and `content`. Roles may be `user`, `assistant`, `tool`, or `system`. Other fields, such as `timestamp`, `source_session_id`, or `source_date`, are persisted as message metadata.
@@ -598,7 +599,7 @@ Both compaction methods serialize with turns for the same session key. Call them
Host applications can attach external context without copying or modifying the nanobot agent loop. A context provider receives a `RequestContext` before each model turn and may return one or more `RuntimeContextBlock` values. Use `attributes` for caller-owned routing data; nanobot keeps it separate from trusted channel metadata and does not persist it in session messages.
`on_session_turn_persisted()` invokes its callback after a non-ephemeral turn has been saved. The callback receives `SessionTurnPersisted` and may read the completed transcript through `bot.sessions`. Callbacks run in registration order, and async callbacks are awaited before the run continues. They are observational: callback exceptions are logged and suppressed so the completed local turn remains successful. Durable external synchronization must catch failures and persist retry work before the callback returns. During SDK runs, callbacks execute while the session is still serialized and must not await `bot.run()`, `bot.runtime.compact_session()`, or `bot.runtime.compact_idle_session()` for the same session.
`on_session_turn_persisted()` invokes its callback after a non-ephemeral turn has been saved. The callback receives `SessionTurnPersisted` and may read the completed transcript through `bot.sessions`. Callbacks run in registration order, and async callbacks are awaited before the run continues. They are observational: callback exceptions are logged and suppressed so the completed local turn remains successful. Durable external synchronization must catch failures and persist retry work before the callback returns. During SDK runs, callbacks execute while the session is still serialized. Schedule `bot.run()`, `bot.runtime.compact_session()`, or `bot.runtime.compact_idle_session()` for the same session after the callback returns.
```python
import json
@@ -639,7 +640,7 @@ async def run_with_external_memory(external_memory, enqueue_retry) -> None:
return external_context_block(text)
async def sync_saved_turn(event: SessionTurnPersisted):
snapshot = bot.sessions.get(event.context.session_key)
snapshot = await bot.sessions.get(event.context.session_key)
if snapshot is not None:
try:
await external_memory.sync(