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

+5 -3
View File
@@ -164,9 +164,10 @@ jobs:
os: windows-latest
python-version: "3.14"
coverage: false
# Real PowerShell/process-tree tests run serially in a separate
# job. Keep them out of xdist so workers never share a console.
pytest_args: "-n auto --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/tools/test_exec_platform.py"
# Real PowerShell, browser-handoff, and process-tree tests run
# serially so xdist workers do not compete for native processes.
# Bound concurrent threaded storage work on the Windows runner.
pytest_args: "-n 2 --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/tools/test_exec_platform.py --ignore=tests/cli/test_wsl_browser.py"
steps:
- uses: actions/checkout@v4
@@ -274,6 +275,7 @@ jobs:
run: >-
uv run --no-sync python -m pytest
tests/tools/test_exec_platform.py
tests/cli/test_wsl_browser.py
--durations=25 --durations-min=1.0
webui:
+1 -1
View File
@@ -77,7 +77,7 @@ You need **Python 3.11 or newer** and access to a [supported model provider or l
Choose the **stable release** for everyday use or **current source** for development and the latest features. This README describes current source; [published documentation](https://nanobot.wiki/docs/latest/getting-started/nanobot-overview) covers the released version.
New to terminals or model credentials? Follow [Start Without Technical Background](./docs/start-without-technical-background.md). Updating an existing instance? Back up its config directory and workspace, stop every old nanobot process using that workspace, then update and restart through the original launcher or service. See [session storage and version changes](./docs/cli-reference.md#session-storage-and-rollback).
New to terminals or model credentials? Follow [Start Without Technical Background](./docs/start-without-technical-background.md). Updating an existing instance? Stop every old nanobot process using that workspace, back up its config directory and workspace, then update and restart through the original launcher or service. See [session storage and version changes](./docs/cli-reference.md#session-storage).
**Stable release: automatic setup (recommended)**
+15 -6
View File
@@ -41,7 +41,6 @@ def _isolate_sessions_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> I
"""
data_root = tmp_path.parent / "session-data" / uuid4().hex
runtime_root = data_root / "runtime"
legacy_root = data_root / "legacy-sessions"
def runtime_subdir(name: str) -> Path:
path = runtime_root / name
@@ -49,13 +48,9 @@ def _isolate_sessions_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> I
return path
monkeypatch.setattr(
"nanobot.session.manager.get_runtime_subdir",
"nanobot.session.location.get_runtime_subdir",
runtime_subdir,
)
monkeypatch.setattr(
"nanobot.session.manager.get_legacy_sessions_dir",
lambda: legacy_root,
)
yield
@@ -136,3 +131,17 @@ def _use_windows_system_ca_for_default_http_clients() -> Iterator[None]:
yield
finally:
ssl.create_default_context = original
@pytest.fixture
def create_symlink():
"""Create real symlinks, skipping only Windows' missing-privilege error."""
def create(link: Path, target: Path, *, target_is_directory: bool = False) -> None:
try:
link.symlink_to(target, target_is_directory=target_is_directory)
except OSError as exc:
if sys.platform == "win32" and getattr(exc, "winerror", None) == 1314:
pytest.skip("Windows symlink creation requires Developer Mode or privilege")
raise
return create
+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(
+33 -34
View File
@@ -3,7 +3,7 @@
from __future__ import annotations
import asyncio
from collections.abc import Collection
from collections.abc import Awaitable, Collection
from datetime import datetime
from typing import TYPE_CHECKING, Any, Callable, Coroutine
@@ -14,7 +14,6 @@ from nanobot.session.keys import is_dream_session
from nanobot.session.manager import Session, SessionManager
from nanobot.session.summary import (
SessionSummary,
is_summary_checkpoint,
session_summary_from_metadata,
)
@@ -26,10 +25,15 @@ SessionEventFactory = Callable[[str], EventSink]
class AutoCompact:
def __init__(self, sessions: SessionManager, consolidator: Consolidator,
session_ttl_minutes: int = 0,
bind_events: SessionEventFactory | None = None,
*, session_lock: Callable[[str], asyncio.Lock]):
def __init__(
self,
sessions: SessionManager,
consolidator: Consolidator,
session_ttl_minutes: int = 0,
bind_events: SessionEventFactory | None = None,
*,
session_lock: Callable[[str], asyncio.Lock],
):
self.sessions = sessions
self.consolidator = consolidator
self._ttl = session_ttl_minutes
@@ -56,38 +60,30 @@ class AutoCompact:
return False
return idle_seconds >= self._ttl * 60
def _has_unarchived_messages(self, key: str) -> bool:
session = self.sessions.get_or_create(key)
return any(
not message.get("_command") and not is_summary_checkpoint(message)
for message in session.messages[session.last_archived:]
)
def check_expired(
async def check_expired(
self,
schedule_background: Callable[[Coroutine[Any, Any, None]], None],
resolve_runtime: Callable[[Session], LLMRuntime],
resolve_runtime: Callable[[Session], Awaitable[LLMRuntime]],
active_session_keys: Collection[str] = (),
) -> None:
"""Schedule archival for idle sessions, skipping those with in-flight agent tasks."""
"""Schedule idle archival without blocking the event loop."""
now = datetime.now()
for info in self.sessions.list_sessions():
active_keys = set(active_session_keys)
for info in await self.sessions.state.list_sessions():
key = info.get("key", "")
# Dream sessions are per-run; persistent maintenance sessions still compact.
if not key or is_dream_session(key) or key in self._archiving:
continue
if key in active_session_keys:
if key in active_keys or not self._is_expired(info.get("updated_at"), now):
continue
updated_at = info.get("updated_at")
if self._is_expired(updated_at, now) and self._has_unarchived_messages(key):
session = self.sessions.get_or_create(key)
try:
runtime = resolve_runtime(session)
except (KeyError, ValueError):
# Invalid session selections remain recoverable through /model.
continue
self._archiving.add(key)
schedule_background(self._archive(key, runtime=runtime))
if not await self.sessions.state.has_unarchived_messages(key):
continue
session = await self.sessions.state.get(key)
try:
runtime = await resolve_runtime(session)
except (KeyError, ValueError):
continue
self._archiving.add(key)
schedule_background(self._archive(key, runtime=runtime))
async def _archive(self, key: str, *, runtime: LLMRuntime) -> None:
if is_dream_session(key):
@@ -95,13 +91,14 @@ class AutoCompact:
return
try:
async with self._session_lock(key):
# Idle compaction and turns share one transcript boundary.
summary = await self.consolidator.compact_idle_session(
key,
runtime=runtime,
events=self._bind_events(key) if self._bind_events else NO_EVENTS,
)
if summary:
session = self.sessions.get_or_create(key)
session = await self.sessions.state.get(key)
stored = session_summary_from_metadata(
session.metadata,
fallback_last_active=session.updated_at,
@@ -113,14 +110,16 @@ class AutoCompact:
finally:
self._archiving.discard(key)
def prepare_session(self, session: Session, key: str) -> tuple[Session, SessionSummary | None]:
async def prepare_session(
self,
session: Session,
key: str,
) -> tuple[Session, SessionSummary | None]:
"""Resolve a summary while preserving the turn's owner-issued draft."""
if is_dream_session(key):
self._archiving.discard(key)
self._summaries.pop(key, None)
return session, None
if key in self._archiving or self._is_expired(session.updated_at):
logger.info("Auto-compact: reloading session {} (archiving={})", key, key in self._archiving)
session = self.sessions.get_or_create(key)
# Hot path: summary from in-memory dict (process hasn't restarted).
entry = self._summaries.pop(key, None)
if entry:
+3 -3
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import asyncio
import dataclasses
from collections.abc import Callable, Iterable
from collections.abc import Awaitable, Callable, Iterable
from nanobot.bus.events import InboundMessage, OutboundMessage
@@ -19,7 +19,7 @@ class AutomationTurnCoordinator:
def __init__(
self,
*,
enqueue: Callable[[InboundMessage], None],
enqueue: Callable[[InboundMessage], Awaitable[None]],
turn_id: Callable[[InboundMessage], str | None],
pending_id: Callable[[InboundMessage], str | None],
should_defer_turn: Callable[[InboundMessage, str, Iterable[str]], bool],
@@ -54,7 +54,7 @@ class AutomationTurnCoordinator:
self._waiters[turn_id] = future
self._pending_messages_by_turn_id[turn_id] = msg
try:
self._enqueue(msg)
await self._enqueue(msg)
try:
return await future
except asyncio.CancelledError:
-12
View File
@@ -71,7 +71,6 @@ BACKFILL_CONTENT = "[Tool result unavailable — call was interrupted or lost]"
PLACEHOLDER_TEXTS = frozenset({
"[Previous assistant message omitted.]",
})
_PreparationArgs = ParamSpec("_PreparationArgs")
_PreparationResult = TypeVar("_PreparationResult")
@@ -234,17 +233,6 @@ class ContextCompactionState:
) -> list[dict[str, Any]]:
return deepcopy(request_messages[len(self.accepted_messages):])
def accept_request(
self,
model_messages: list[dict[str, Any]],
*,
raw_boundary: int,
) -> None:
"""Advance H after the provider has received one request."""
self.accepted_messages = deepcopy(model_messages)
self.raw_accepted_boundary = raw_boundary
@dataclass(slots=True)
class ModelRequestState:
"""Context state shared by every provider request in one runner turn."""
+2 -2
View File
@@ -2,7 +2,7 @@
from __future__ import annotations
from collections.abc import Callable, Iterable
from collections.abc import Awaitable, Callable, Iterable
from nanobot.agent.automation_turns import AutomationTurnCoordinator
from nanobot.bus.events import InboundMessage
@@ -19,7 +19,7 @@ class CronTurnCoordinator(AutomationTurnCoordinator):
def __init__(
self,
*,
enqueue: Callable[[InboundMessage], None],
enqueue: Callable[[InboundMessage], Awaitable[None]],
deferred_queues: dict[str, list[InboundMessage]] | None = None,
) -> None:
super().__init__(
+210 -137
View File
@@ -97,11 +97,12 @@ from nanobot.session.recovery import (
RequestOrigin,
acknowledge_pending_followups,
pending_followups,
record_pending_followup,
request_origin_from_metadata,
restore_pending_interruption,
restore_runtime_checkpoint,
)
from nanobot.session.sqlite_store import SessionConflictError
from nanobot.session.state import SessionOperationQueueFullError
from nanobot.session.summary import (
SessionSummary,
SessionSummaryCheckpoint,
@@ -181,6 +182,8 @@ class TurnContext:
provider_compaction_applied: bool = False
ephemeral: bool = False
# SDK temporary turns use an isolated draft; gateway temporary chats retain owner state.
commit_session: bool = True
run_extra_hooks_for_ephemeral: bool = False
hooks: list[AgentHook] = field(default_factory=list)
hook_factories: list[AgentTurnHookFactory] = field(default_factory=list)
@@ -543,13 +546,13 @@ class AgentLoop:
self._publish_runtime_selection(runtime)
return runtime
def runtime_for_session(
def _resolve_session_runtime(
self,
session: Session,
*,
recover_removed: bool = True,
) -> LLMRuntime:
"""Resolve the immutable runtime selected by one session."""
recover_removed: bool,
) -> LLMRuntime | None:
"""Return the selected runtime, or clear a removed preset for persistence."""
name = model_preset_from_metadata(session.metadata)
if name is None:
return self.llm_runtime()
@@ -564,19 +567,38 @@ class AgentLoop:
name,
)
session.metadata.pop(SESSION_MODEL_PRESET_METADATA_KEY, None)
self.sessions.save(session)
return self.llm_runtime()
return None
def set_session_model_preset(
async def runtime_for_session(
self,
session: Session,
*,
recover_removed: bool = True,
) -> LLMRuntime:
"""Resolve a session runtime without blocking on recovery persistence."""
runtime = self._resolve_session_runtime(session, recover_removed=recover_removed)
if runtime is not None:
return runtime
await self.sessions.state.update_metadata(
session.key,
{},
remove=(SESSION_MODEL_PRESET_METADATA_KEY,),
expected_generation=session.generation,
)
return self.llm_runtime()
async def set_session_model_preset(
self,
session_key: str,
name: str,
) -> LLMRuntime:
"""Validate and persist one session's preset selection."""
"""Validate and persist one session's preset selection without blocking."""
runtime = self.runtime_resolver.resolve_preset(name)
session = self.sessions.get_or_create(session_key)
session.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = runtime.model_preset
self.sessions.save(session)
await self.sessions.state.update_metadata(
session_key,
{SESSION_MODEL_PRESET_METADATA_KEY: runtime.model_preset},
create_if_missing=True,
)
return runtime
def _publish_runtime_selection(
@@ -675,17 +697,14 @@ class AgentLoop:
def pending_local_trigger_ids_for_session(self, session_key: str) -> set[str]:
return self._local_trigger_turns.pending_trigger_ids_for_session(session_key)
def _persist_user_message_early(
async def _persist_user_message_early(
self,
msg: InboundMessage,
session: Session,
runtime_context_blocks: list[RuntimeContextBlock] | None = None,
**kwargs: Any,
) -> bool:
"""Persist the triggering user message before the turn starts.
Returns True if the message was persisted.
"""
"""Persist the triggering user message and recovery markers before running the turn."""
if not turn_continuation.should_persist_user_message(msg.metadata):
return False
media_paths = [
@@ -716,7 +735,7 @@ class AgentLoop:
followup_id = msg.metadata.get(PENDING_FOLLOWUP_ID_KEY)
if isinstance(followup_id, str) and followup_id:
acknowledge_pending_followups(session, [followup_id])
self.sessions.save(session)
await self.sessions.state.prepare_input(session)
return True
return False
@@ -743,7 +762,11 @@ class AgentLoop:
ctx.session.metadata[REQUEST_ORIGIN_METADATA_KEY] = origin
if ctx.original_user_text is None:
# No new user row will persist this turn's owner before execution.
self.sessions.save(ctx.session)
await self.sessions.state.update_metadata(
ctx.session.key,
{REQUEST_ORIGIN_METADATA_KEY: origin},
expected_generation=ctx.session.generation,
)
scope = await self.runner.prepare_prompt(
self.workspace_scopes.for_turn,
channel=ctx.delivery.route.channel,
@@ -755,6 +778,7 @@ class AgentLoop:
chat_id=ctx.delivery.route.chat_id,
message_id=origin["message_id"],
session_key=ctx.session_key,
session_generation=ctx.session.generation,
original_user_text=ctx.original_user_text,
runtime=ctx.runtime,
metadata=dict(ctx.msg.metadata or {}),
@@ -789,9 +813,10 @@ class AgentLoop:
]
blocks = runtime_context_blocks_from_metadata(request.metadata)
blocks.extend(await resolve_runtime_context(providers, request))
skill_context = await self.runner.prepare_prompt(
self.context.skills.build_explicit_skill_runtime_context,
request.original_user_text or "",
text = request.original_user_text or ""
skill_context = (
await self.runner.prepare_prompt(self.context.skills.build_explicit_skill_runtime_context, text)
if "$" in text else None
)
if skill_context is not None and skill_context not in blocks:
blocks.append(skill_context)
@@ -806,7 +831,7 @@ class AgentLoop:
) -> None:
"""Dispatch a command directly from the run() loop and publish the result."""
if self.commands.requires_session_queue(raw):
self._enqueue_session_message(msg)
await self._enqueue_session_message(msg)
return
async def dispatch_and_publish() -> None:
@@ -821,7 +846,7 @@ class AgentLoop:
)
result = await dispatch_fn(ctx)
if isinstance(result, InboundMessage):
self._enqueue_session_message(result)
await self._enqueue_session_message(result)
elif result is not None:
await self.bus.publish_outbound(result)
@@ -839,7 +864,7 @@ class AgentLoop:
if tool is None:
content = "Shell execution is disabled in this nanobot configuration."
else:
session = ctx.session or self.sessions.get_or_create(ctx.key)
session = ctx.session or await self.sessions.state.get(ctx.key)
scope = self.workspace_scopes.for_turn(
channel=ctx.msg.channel,
message_metadata=metadata,
@@ -850,6 +875,7 @@ class AgentLoop:
chat_id=ctx.msg.chat_id,
message_id=metadata.get("message_id"),
session_key=ctx.key,
session_generation=session.generation,
original_user_text=f"!{ctx.args.strip()}",
runtime=ctx.runtime,
metadata=metadata,
@@ -900,7 +926,7 @@ class AgentLoop:
Returns the total number of cancelled tasks, subagents, and exec sessions.
"""
journal_session = self.sessions.get_cached(key) or self.sessions.read_session_snapshot(key)
journal_session = await self.sessions.state.read(key)
journaled_followup_ids = (
tuple(
followup_id
@@ -928,9 +954,7 @@ class AgentLoop:
# Explicit session cancellation owns the follow-ups accepted before
# it began. Gateway shutdown uses aclose() directly and keeps this
# journal intact for startup recovery.
current_session = self.sessions.get_cached(key) or journal_session
acknowledge_pending_followups(current_session, journaled_followup_ids)
self.sessions.save(current_session)
await self.sessions.state.acknowledge_followups(key, journaled_followup_ids)
sub_cancelled = await self.subagents.cancel_by_session(key)
exec_cancelled = await self._exec_session_manager.terminate_by_owner(key)
return cancelled + sub_cancelled + exec_cancelled
@@ -939,7 +963,7 @@ class AgentLoop:
"""Stop active work for *key* and forget its cached session."""
self._discarding_sessions.add(key)
try:
self.sessions.invalidate(key)
await self.sessions.state.discard(key)
await self._cancel_active_tasks(key)
finally:
self.discard_session_file_state(key)
@@ -970,7 +994,9 @@ class AgentLoop:
session_key: str,
) -> EventSink:
"""Bind one idle compaction to its current user-facing destination."""
session = self.sessions.get_or_create(session_key)
session = self.sessions.state.peek_header(session_key)
if session is None:
return NO_EVENTS
return self.turn_delivery_factory.session_events(
session_key, session.metadata,
)
@@ -1042,7 +1068,7 @@ class AgentLoop:
public_payload[self._PROVIDER_STATE_CHECKPOINT_VERSION_KEY] = (
self._PROVIDER_STATE_CHECKPOINT_VERSION
)
self._set_runtime_checkpoint(session, public_payload)
await self._set_runtime_checkpoint(session, public_payload)
async def _drain_pending(
*,
@@ -1099,6 +1125,7 @@ class AgentLoop:
chat_id=pending_msg.chat_id,
message_id=metadata.get("message_id"),
session_key=active_session_key,
session_generation=session.generation if session is not None else None,
original_user_text=pending_msg.content,
runtime=runtime,
metadata=dict(metadata),
@@ -1222,6 +1249,9 @@ class AgentLoop:
request_ctx = dataclasses.replace(
request_ctx,
workspace_scope=effective_scope,
session_generation=(
session.generation if session is not None else request_ctx.session_generation
),
log_content=(
request_ctx.log_content and not ephemeral
and (session is None or session.policy.log_content)
@@ -1237,8 +1267,9 @@ class AgentLoop:
workspace_token = bind_workspace_scope(effective_scope)
turn_scope_stack = ExitStack()
# Compute lazily because create_goal may create goal metadata during this run.
def _goal_continue() -> str | None:
_goal_lines = goal_state_runtime_lines(session.metadata if session is not None else None)
async def _goal_continue() -> str | None:
current = await self.sessions.state.read_metadata(session.key) if session else None
_goal_lines = goal_state_runtime_lines(current["metadata"] if current else None)
if not _goal_lines:
return None
return (
@@ -1350,17 +1381,20 @@ class AgentLoop:
)
return result
def _check_expired_sessions_if_due(self) -> None:
"""Scan idle sessions no more often than the configured interval."""
async def _check_expired_sessions_if_due(self) -> None:
"""Scan idle sessions without blocking the event loop."""
now = time.monotonic()
if now < self._next_idle_compact_check_at:
return
self._next_idle_compact_check_at = now + self._idle_compact_check_interval_s
self.auto_compact.check_expired(
self.schedule_background,
self.runtime_for_session,
active_session_keys=self._pending_queues.keys(),
)
try:
await self.auto_compact.check_expired(
self.schedule_background,
self.runtime_for_session,
active_session_keys=self._pending_queues.keys(),
)
except SessionOperationQueueFullError:
logger.debug("Skipping idle archival while session storage is busy")
async def run(self) -> None:
"""Run the agent loop, dispatching messages as tasks to stay responsive to /stop."""
@@ -1372,7 +1406,7 @@ class AgentLoop:
try:
msg = await asyncio.wait_for(self.bus.consume_inbound(), timeout=1.0)
except asyncio.TimeoutError:
self._check_expired_sessions_if_due()
await self._check_expired_sessions_if_due()
continue
except asyncio.CancelledError:
# Preserve real task cancellation so shutdown can complete cleanly.
@@ -1387,55 +1421,66 @@ class AgentLoop:
logger.warning("Error consuming inbound message: {}, continuing...", e)
continue
raw = command_text(msg)
effective_key = self._effective_session_key(msg)
if msg.metadata.get(INBOUND_META_RUNTIME_CONTROL) == RUNTIME_CONTROL_SESSION_DISCARD:
await self.discard_session(msg.session_key)
continue
if (
msg.require_existing_session
and self.sessions.get_existing(effective_key) is None
):
continue
if msg.is_user_input:
await self.runtime_event_publisher.user_input_accepted(msg, effective_key)
if msg.channel != "system" and self.commands.is_priority(raw):
await self._dispatch_command_inline(
msg, effective_key, raw,
self.commands.dispatch_priority,
)
continue
routed_msg = msg
if effective_key != msg.session_key:
routed_msg = dataclasses.replace(
msg,
session_key_override=effective_key,
)
# A newer WebUI message must supersede an explicit recovery
# before it is injected into that recovery's pending queue.
# Without this admission point, a recovered turn could finish
# first and only then observe the user's newer request.
if (
effective_key in self._pending_queues
and msg.channel == "websocket"
and self._recovery_admission is not None
and not await self._recovery_admission.admit(routed_msg)
):
continue
# If this session already has an active pending queue (i.e. a task
# is processing this session), route the message there for mid-turn
# injection instead of creating a competing task.
if effective_key in self._pending_queues:
if msg.channel != "system" and self.commands.is_dispatchable_command(raw):
await self._dispatch_command_inline(
msg, effective_key, raw,
self.commands.dispatch,
)
continue
self._enqueue_session_message(routed_msg)
try:
await self._dispatch_inbound(msg)
except (SessionOperationQueueFullError, SessionConflictError) as exc:
key = self._effective_session_key(msg)
logger.warning("Session input rejected for {}: {}", key, exc)
if msg.is_user_input:
delivery = self.turn_delivery_factory.unrouted(msg, key)
await delivery.fail(publish_completion=key not in self._pending_queues)
finally:
await self.aclose()
async def _dispatch_inbound(self, msg: InboundMessage) -> None:
"""Route one input through command and session admission."""
raw = command_text(msg)
effective_key = self._effective_session_key(msg)
if msg.metadata.get(INBOUND_META_RUNTIME_CONTROL) == RUNTIME_CONTROL_SESSION_DISCARD:
await self.discard_session(msg.session_key)
return
if (
msg.require_existing_session
and await self.sessions.state.read_metadata(effective_key) is None
):
return
if msg.is_user_input:
await self.runtime_event_publisher.user_input_accepted(msg, effective_key)
if msg.channel != "system" and self.commands.is_priority(raw):
await self._dispatch_command_inline(
msg, effective_key, raw,
self.commands.dispatch_priority,
)
return
routed_msg = msg
if effective_key != msg.session_key:
routed_msg = dataclasses.replace(
msg,
session_key_override=effective_key,
)
# A newer WebUI message must supersede an explicit recovery
# before it is injected into that recovery's pending queue.
# Without this admission point, a recovered turn could finish
# first and only then observe the user's newer request.
if (
effective_key in self._pending_queues
and msg.channel == "websocket"
and self._recovery_admission is not None
and not await self._recovery_admission.admit(routed_msg)
):
return
# If this session already has an active pending queue (i.e. a task
# is processing this session), route the message there for mid-turn
# injection instead of creating a competing task.
if effective_key in self._pending_queues:
if msg.channel != "system" and self.commands.is_dispatchable_command(raw):
await self._dispatch_command_inline(
msg, effective_key, raw,
self.commands.dispatch,
)
return
await self._enqueue_session_message(routed_msg)
def preserve_inflight_turns_on_shutdown(self) -> None:
"""Keep durable checkpoints when the owning gateway exits.
@@ -1446,7 +1491,7 @@ class AgentLoop:
"""
self._preserve_inflight_turns_on_shutdown = True
def _journal_pending_message(
async def _journal_pending_message(
self,
session_key: str,
msg: InboundMessage,
@@ -1454,8 +1499,7 @@ class AgentLoop:
"""Persist a recoverable WebUI follow-up before adding it to the inbox."""
if not self._can_inject_message(msg):
return msg
session = self.sessions.get_or_create(session_key)
followup_id = record_pending_followup(session, msg)
followup_id = await self.sessions.state.queue_followup(session_key, msg)
if followup_id is None:
return msg
pending_msg = dataclasses.replace(
@@ -1465,10 +1509,9 @@ class AgentLoop:
PENDING_FOLLOWUP_ID_KEY: followup_id,
},
)
self.sessions.save(session)
return pending_msg
def _enqueue_session_message(self, msg: InboundMessage) -> None:
async def _enqueue_session_message(self, msg: InboundMessage) -> None:
"""Admit session work without waiting for its execution or result."""
session_key = self._effective_session_key(msg)
if not self.subagents.accepts_result(msg, session_key):
@@ -1484,9 +1527,11 @@ class AgentLoop:
):
return
if session_key in self._pending_queues:
msg = await self._journal_pending_message(session_key, msg)
pending = self._pending_queues.get(session_key)
if pending is not None:
pending.put_nowait(self._journal_pending_message(session_key, msg))
pending.put_nowait(msg)
return
new_pending: asyncio.Queue[InboundMessage] = asyncio.Queue()
@@ -1514,7 +1559,7 @@ class AgentLoop:
msg = deferred.pop(0)
if not deferred:
self._deferred_automation_turns.pop(session_key)
session = self.sessions.get_cached(session_key)
session = self.sessions.state.peek_header(session_key)
log_content = session is None or (
session.policy.persist and session.policy.log_content
)
@@ -1566,7 +1611,7 @@ class AgentLoop:
session_key = self._effective_session_key(msg)
# The request context is reset before errors reach this boundary, and
# discard may evict the session while a turn is still unwinding.
session = self.sessions.get_cached(session_key)
session = self.sessions.state.peek_header(session_key)
log_content = session is None or (
session.policy.persist and session.policy.log_content
)
@@ -1595,10 +1640,11 @@ class AgentLoop:
# A preceding user turn may have completed or blocked the goal
# while its older continuation was still waiting in the inbox.
if turn_continuation.sustained_goal_continuation_inbound(msg.metadata) and not (
sustained_goal_active(self.sessions.get_or_create(session_key).metadata)
sustained_goal_active((await self.sessions.state.get(session_key)).metadata)
):
return
try:
await self.sessions.state.read(session_key)
delivery = self.turn_delivery_factory.create(
msg,
session_key,
@@ -1637,10 +1683,10 @@ class AgentLoop:
raise
try:
key = self._effective_session_key(msg)
session = self.sessions.get_or_create(key)
session = await self.sessions.state.get(key)
if restore_runtime_checkpoint(session):
self._clear_pending_user_turn(session)
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
logger.info(
"Restored partial context for cancelled session {}",
key,
@@ -1727,6 +1773,7 @@ class AgentLoop:
self.subagents.close,
self._exec_session_manager.close_all,
self.runtime_resolver.aclose,
self.sessions.state.aclose,
)
for cleanup in cleanup_steps:
try:
@@ -1790,6 +1837,17 @@ class AgentLoop:
key = session_key or msg.session_key
if not self.subagents.accepts_result(msg, key):
return None
commit_session = session is None or session.policy.persist
if session is None:
session = (await self.sessions.state.read(key)
if msg.require_existing_session or msg.session_generation is not None
else await self.sessions.state.get(key))
if msg.require_existing_session and session is None:
raise RuntimeError("required session is not active")
if msg.session_generation is not None and (
session is None or session.generation != msg.session_generation
):
raise RuntimeError("required session generation was replaced")
if delivery is None:
delivery = self.turn_delivery_factory.create(msg, key)
elif delivery.session_key != key:
@@ -1823,6 +1881,7 @@ class AgentLoop:
on_runtime_admitted=on_runtime_admitted,
pending_queue=pending_queue,
ephemeral=ephemeral,
commit_session=commit_session,
run_extra_hooks_for_ephemeral=run_extra_hooks_for_ephemeral,
hooks=list(hooks or []),
hook_factories=list(hook_factories or []),
@@ -1980,13 +2039,19 @@ class AgentLoop:
msg = ctx.msg
if ctx.session is None:
if msg.require_existing_session:
ctx.session = self.sessions.get_existing(ctx.session_key)
if msg.require_existing_session or msg.session_generation is not None:
ctx.session = await self.sessions.state.read(ctx.session_key)
if ctx.session is None:
raise RuntimeError("required session is not active")
if (
msg.session_generation is not None
and ctx.session.generation != msg.session_generation
):
raise RuntimeError("required session generation was replaced")
else:
ctx.session = self.sessions.get_or_create(ctx.session_key)
ctx.session = await self.sessions.state.get(ctx.session_key)
session = ctx.session
ctx.delivery.bind_session_generation(session.generation)
ctx.ephemeral = ctx.ephemeral or not session.policy.persist
tools = ctx.tools if ctx.tools is not None else self.tools
if session.policy.disabled_tools:
@@ -2016,17 +2081,20 @@ class AgentLoop:
if ctx.kind is TurnKind.USER:
self.workspace_scopes.persist_message_scope(session, msg)
if restore_runtime_checkpoint(session):
self.sessions.save(session)
if restore_runtime_checkpoint(session) and ctx.commit_session:
await self.sessions.state.restore_interruption(session)
if (
RECOVERY_INBOUND_METADATA_KEY not in msg.metadata
and restore_pending_interruption(session)
and ctx.commit_session
):
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
async def _compact_session(self, ctx: TurnContext) -> None:
if not ctx.commit_session:
return
session = ctx.require_session()
ctx.session, pending = self.auto_compact.prepare_session(
ctx.session, pending = await self.auto_compact.prepare_session(
session,
ctx.session_key,
)
@@ -2068,15 +2136,15 @@ class AgentLoop:
# message. Mark messages with _command so get_history can filter
# them out of LLM context. /new is excluded because it
# intentionally clears the session.
if cmd_ctx.raw.lower() != "/new":
ctx.input_persisted_early = self._persist_user_message_early(
if cmd_ctx.raw.lower() != "/new" and ctx.commit_session:
ctx.input_persisted_early = await self._persist_user_message_early(
ctx.msg, session, _command=True
)
session.add_message(
"assistant", result.content, _command=True
)
self._clear_pending_user_turn(session)
self.sessions.save(session)
await self.sessions.state.prepare_input(session)
if not ctx.ephemeral:
await self.runtime_event_publisher.session_turn_persisted(
ctx.msg,
@@ -2091,7 +2159,7 @@ class AgentLoop:
session = ctx.require_session()
runtime = ctx.runtime
if runtime is None:
runtime = self.runtime_for_session(session)
runtime = await self.runtime_for_session(session)
ctx.runtime = runtime
if ctx.session_key.startswith("dream:"):
logger.info(
@@ -2101,22 +2169,10 @@ class AgentLoop:
)
if ctx.on_runtime_admitted is not None:
await ctx.on_runtime_admitted(runtime)
if not ctx.ephemeral:
ctx.session, ctx.pending_summary = self.auto_compact.prepare_session(
session,
ctx.session_key,
)
session = ctx.require_session()
is_subagent = ctx.kind is TurnKind.SYSTEM and ctx.msg.sender_id == "subagent"
# Capture replay inputs on the loop; the worker never sees the live Session/cache.
history_records = session.messages[session.last_archived:]
history_snapshot = Session(
key=session.key,
messages=await self.runner.copy_messages_on_loop(history_records),
)
ctx.history = await self.runner.prepare_prompt(
history_snapshot.get_history, extend_to_user=is_subagent,
session.get_history, extend_to_user=is_subagent,
)
stored_state = session.provider_state
subagent_followup_persisted = False
@@ -2136,7 +2192,7 @@ class AgentLoop:
# provider compatibility or prompt assembly work. A compatible
# staged state replaces this in a second atomic save below.
session.provider_state = None
self.sessions.save(session)
await self.sessions.state.prepare_input(session)
ctx.input_persisted_early = True
await ctx.delivery.runtime_admitted(runtime)
@@ -2189,8 +2245,8 @@ class AgentLoop:
staged_provider_state = True
elif stored_state is not None:
session.provider_state = None
if ctx.kind is TurnKind.USER:
ctx.input_persisted_early = self._persist_user_message_early(
if ctx.kind is TurnKind.USER and ctx.commit_session:
ctx.input_persisted_early = await self._persist_user_message_early(
ctx.msg,
session,
runtime_context_blocks=ctx.runtime_context_blocks,
@@ -2200,7 +2256,9 @@ class AgentLoop:
elif subagent_followup_persisted and staged_provider_state:
# Upgrade the replay-safe baseline to the resumable state before
# prompt assembly and the first model checkpoint.
self.sessions.save(session)
await self.sessions.state.prepare_input(session)
if not session.persisted and ctx.commit_session:
await self.sessions.state.prepare_input(session)
ctx.transcript_input = self._build_transcript_input(ctx)
@@ -2242,7 +2300,10 @@ class AgentLoop:
ctx.usage = result.usage
ctx.delivery.record_usage(result.round_usages)
if ctx.kind is TurnKind.USER:
await turn_continuation.maybe_continue_turn(ctx)
current = await self.sessions.state.read_metadata(ctx.session_key)
await turn_continuation.maybe_continue_turn(
ctx, session_metadata=current["metadata"] if current else {},
)
async def _persist_turn(self, ctx: TurnContext) -> None:
session = ctx.require_session()
@@ -2284,7 +2345,8 @@ class AgentLoop:
session.provider_state = None
self._clear_pending_user_turn(session)
self._clear_runtime_checkpoint(session)
self.sessions.save(session)
if ctx.commit_session:
await self.sessions.state.finish_turn(session)
if not ctx.ephemeral:
await self.runtime_event_publisher.session_turn_persisted(
ctx.msg,
@@ -2532,10 +2594,14 @@ class AgentLoop:
)
return True
def _set_runtime_checkpoint(self, session: Session, payload: dict[str, Any]) -> None:
"""Persist the latest in-flight turn state into session metadata."""
async def _set_runtime_checkpoint(
self,
session: Session,
payload: dict[str, Any],
) -> None:
"""Persist the latest in-flight turn state without blocking the event loop."""
session.metadata[self._RUNTIME_CHECKPOINT_KEY] = payload
self.sessions.save_runtime_checkpoint(session)
await self.sessions.state.checkpoint_view(session, payload)
def _mark_pending_user_turn(self, session: Session) -> None:
session.metadata[self._PENDING_USER_TURN_KEY] = True
@@ -2585,6 +2651,7 @@ class AgentLoop:
)
# Share the dispatch lock so direct calls serialize with bus turns.
lock = self._get_session_lock(session_key)
temporary_parent = False
try:
async with lock:
kwargs: dict[str, Any] = {
@@ -2597,7 +2664,10 @@ class AgentLoop:
if _session_policy is not None:
# Isolate per-run state before any early save or checkpoint;
# the cached conversation must survive a temporary SDK turn.
session = deepcopy(self.sessions.get_or_create(session_key))
session = (await self.sessions.state.read(session_key) or Session(key=session_key)
if not _session_policy.persist
else await self.sessions.state.get(session_key))
temporary_parent = not _session_policy.persist and not session.persisted
session.policy = SessionPolicy(
persist=session.policy.persist and _session_policy.persist,
log_content=session.policy.log_content and _session_policy.log_content,
@@ -2618,10 +2688,13 @@ class AgentLoop:
kwargs["on_runtime_admitted"] = on_runtime_admitted
if attributes is not None:
kwargs["attributes"] = dict(attributes)
return await self._process_message(
msg,
**kwargs,
)
try:
return await self._process_message(msg, **kwargs)
finally:
if temporary_parent:
parent = self.sessions.state.peek_header(session_key)
if parent is not None and not parent.policy.persist:
await self.sessions.state.delete(session_key, expected_generation=parent.generation)
finally:
await self.runtime_event_publisher.run_status_changed(msg, session_key, "idle")
self.runtime_event_publisher.clear_turn(session_key)
+4 -32
View File
@@ -25,7 +25,6 @@ from nanobot.llm_usage.context import llm_usage_source
from nanobot.providers.base import LLMResponse, ProviderConversationState
from nanobot.providers.conversation_state import ProviderConversationStateController
from nanobot.runtime_context import public_history_messages
from nanobot.session.keys import is_dream_session
from nanobot.session.manager import Session, SessionManager
from nanobot.session.summary import is_summary_checkpoint, session_summary_from_metadata
from nanobot.utils.gitstore import GitStore
@@ -722,28 +721,6 @@ class MemoryStore:
return prefix
return f"{prefix}\n\n{diff_body}"
@staticmethod
def prune_dream_sessions(sessions: SessionManager, *, keep: int = 10) -> None:
"""Remove the oldest Dream session files, keeping only the N most recent.
Only current base64url-encoded Dream session keys are considered.
Non-dream session files are never touched.
"""
with sessions.locked_session_files() as sessions_dir:
dream_files: list[tuple[Path, str]] = []
for path in sessions_dir.glob("*.jsonl"):
decoded_key = SessionManager.decode_storage_key(path.stem)
if decoded_key is not None and is_dream_session(decoded_key):
dream_files.append((path, decoded_key))
dream_files.sort(key=lambda item: item[0].stat().st_mtime)
for path, key in dream_files[: max(0, len(dream_files) - keep)]:
if sessions.delete_session(key):
logger.debug("Pruned old dream session: {}", path.stem)
else:
logger.warning("Failed to prune dream session {}", path)
# ---------------------------------------------------------------------------
# Memory ingestion and context-pressure coordination
# ---------------------------------------------------------------------------
@@ -1253,8 +1230,8 @@ class Consolidator:
"""
lock = self.get_lock(session_key)
async with lock:
self.sessions.invalidate(session_key)
session = self.sessions.get_or_create(session_key)
await self.sessions.state.discard(session_key)
session = await self.sessions.state.get(session_key)
archive_start = session.last_archived
messages_to_archive = list(session.messages[archive_start:])
@@ -1269,20 +1246,15 @@ class Consolidator:
await events.emit(
ContextCompactionEvent(compaction_id=compaction_id, phase="started", notify=notify),
)
last_active = session.updated_at
archive_end = archive_start + len(messages_to_archive)
try:
summary = await self.archive_session(
session, archive_end=archive_end, runtime=runtime,
)
if summary:
# Concurrent appends remain after the captured boundary.
session.commit_summary_checkpoint(
summary, insert_at=archive_end, last_active=last_active,
await self.sessions.state.commit_summary(
session, summary, archive_end=archive_end,
)
# Resume from the summary and retained transcript, not the old provider history.
session.provider_state = None
self.sessions.save(session)
except (Exception, asyncio.CancelledError) as exc:
await events.emit(
ContextCompactionEvent(
+14 -28
View File
@@ -68,7 +68,7 @@ def _raise_if_cancelling() -> None:
raise asyncio.CancelledError
ContinuationCallback = Callable[[], str | None]
ContinuationCallback = Callable[[], Awaitable[str | None]]
CheckpointCallback = Callable[[dict[str, Any]], Awaitable[None]]
InjectionCallback = Callable[[], Awaitable[Iterable[Any] | None]]
@@ -158,29 +158,15 @@ class AgentRunner:
self, operation: Callable[_PromptArgs, _PromptResult],
*args: _PromptArgs.args, **kwargs: _PromptArgs.kwargs,
) -> _PromptResult:
"""Share the bounded worker for read-only prompt preparation."""
"""Share the bounded context worker for prompt filesystem preparation."""
return await self.context_governor.prepare_in_background(operation, *args, **kwargs)
@staticmethod
async def copy_messages_on_loop(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Detach loop-owned records while yielding between bounded batches."""
copied: list[dict[str, Any]] = []
memo: dict[int, Any] = {id(messages): copied}
for start in range(0, len(messages), 64):
copied.extend(deepcopy(message, memo) for message in messages[start:start + 64])
await asyncio.sleep(0)
return copied
async def _run_context_snapshot(
self, messages: list[dict[str, Any]],
self, hook: AgentHook, messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
if not messages:
if not messages or not hook.has_run_hooks():
return []
task = asyncio.current_task()
if task is not None and task.cancelling():
# Cancellation cleanup must not queue behind its own unfinished worker.
return await self.copy_messages_on_loop(messages)
return await self.prepare_prompt(deepcopy, messages)
return await asyncio.to_thread(deepcopy, messages)
@staticmethod
def _append_injected_messages(
@@ -208,7 +194,7 @@ class AgentRunner:
injections = await self._drain_injections(spec) if drain_callback else []
real_injection = bool(injections)
if not injections and allow_continuation and assistant_message is not None:
continuation = self._build_continuation_message(spec)
continuation = await self._build_continuation_message(spec)
if continuation is not None:
injections = [continuation]
if (
@@ -260,12 +246,12 @@ class AgentRunner:
return True, injection_cycles
@staticmethod
def _build_continuation_message(spec: AgentRunSpec) -> dict[str, str] | None:
async def _build_continuation_message(spec: AgentRunSpec) -> dict[str, str] | None:
callback = spec.continuation_callback
if callback is None:
return None
try:
content = callback()
content = await callback()
except Exception:
logger.opt(exception=tool_log_content_allowed()).error("continuation_callback failed")
return None
@@ -332,18 +318,18 @@ class AgentRunner:
try:
try:
messages, compaction = await self.prepare_prompt(self._initial_transcript_and_compaction, spec)
context.messages = await self._run_context_snapshot(messages) if has_run_hooks else []
context.messages = await self._run_context_snapshot(hook, messages) if has_run_hooks else []
await hook.before_run(context)
result = await self._run_core(spec, hook, messages, compaction)
except Exception as exc:
context.messages = await self._run_context_snapshot(messages) if has_run_hooks else []
context.messages = await self._run_context_snapshot(hook, messages) if has_run_hooks else []
context.stop_reason = "error"
context.error = f"Error: {type(exc).__name__}: {exc}"
context.exception = exc
await hook.on_error(context)
raise
else:
context.messages = await self._run_context_snapshot(result.messages) if has_run_hooks else []
context.messages = await self._run_context_snapshot(hook, result.messages) if has_run_hooks else []
context.final_content = result.final_content
context.tools_used = list(result.tools_used)
context.usage = result.usage
@@ -365,14 +351,14 @@ class AgentRunner:
if has_run_hooks:
try:
if isinstance(context.exception, asyncio.CancelledError):
context.messages = await self.copy_messages_on_loop(messages)
context.messages = await self._run_context_snapshot(hook, messages)
else:
context.messages = await self._run_context_snapshot(messages)
context.messages = await self._run_context_snapshot(hook, messages)
except asyncio.CancelledError as exc:
context.stop_reason = "cancelled"
context.error = None
context.exception = exc
context.messages = await self.copy_messages_on_loop(messages)
context.messages = await self._run_context_snapshot(hook, messages)
raise
finally:
try:
+101 -41
View File
@@ -7,7 +7,7 @@ import json
import time
import uuid
import warnings
from collections.abc import Callable, Mapping
from collections.abc import Awaitable, Callable, Mapping
from copy import deepcopy
from dataclasses import dataclass, field, replace
from functools import partial
@@ -49,6 +49,7 @@ from nanobot.security.workspace_access import (
workspace_sandbox_status,
)
from nanobot.session.manager import Session, SessionManager, SessionPolicy
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.utils.prompt_templates import render_template
@@ -158,7 +159,7 @@ class _SubagentHook(AgentHook):
def __init__(self, status: SubagentStatus | None = None,
*, check_active: Callable[[], None] | None = None,
max_result_chars: int = 16000,
on_status: Callable[[SubagentStatus], None] | None = None) -> None:
on_status: Callable[[SubagentStatus], Awaitable[None]] | None = None) -> None:
super().__init__()
self._status = status
self._check_active = check_active
@@ -180,7 +181,7 @@ class _SubagentHook(AgentHook):
{"name": call.name, "status": "running"} for call in context.tool_calls
]
if self._status is not None and self._on_status is not None:
self._on_status(self._status)
await self._on_status(self._status)
async def before_execute_tool(
self, context: AgentHookContext, tool_call: ToolCallRequest,
@@ -199,7 +200,7 @@ class _SubagentHook(AgentHook):
if context.error:
self._status.error = str(context.error)
if self._on_status is not None:
self._on_status(self._status)
await self._on_status(self._status)
class SubagentManager:
@@ -273,6 +274,7 @@ class SubagentManager:
self._terminal_statuses: dict[str, SubagentStatus] = {}
self._closed = False
self._close_task: asyncio.Task[int] | None = None
self._admitting = 0
self.sessions = SubagentSessions(session_manager) if session_manager is not None else None
MAX_ACTIVE = 128
@@ -283,11 +285,11 @@ class SubagentManager:
CANCEL_WAIT_SECONDS = 5.0
def _save_status(
self, status: SubagentStatus, *, fsync: bool = False,
async def _save_status(
self, status: SubagentStatus,
) -> None:
status.revision += 1
if self.sessions is not None and not self.sessions.save(status, fsync=fsync):
if self.sessions is not None and not await self.sessions.save(status):
return
self._publish_status(status)
@@ -300,10 +302,10 @@ class SubagentManager:
task_id=status.task_id,
))
def recover_interrupted(self) -> None:
async def recover_interrupted(self) -> None:
"""Recover observations only after the host has claimed execution ownership."""
if self.sessions is not None:
self.sessions.interrupt_pending()
await self.sessions.interrupt_pending()
def _start_cleanup(self, record: _SubagentTask, *, retry: bool = False) -> asyncio.Task[int]:
cleanup = record.cleanup_task
@@ -326,10 +328,11 @@ class SubagentManager:
and not cleanup.cancelled() and cleanup.exception() is None):
self._tasks.pop(record.status.task_id, None)
def _finish(self, record: _SubagentTask,
async def _finish(self, record: _SubagentTask,
cleanup_error: str | None = None) -> _SubagentOutcome:
outcome = record.finish(self.max_tool_result_chars, cleanup_error)
self._save_status(record.status, fsync=True)
await self._save_transcript(record)
await self._save_status(record.status)
self._terminal_statuses[record.status.task_id] = record.snapshot()
while len(self._terminal_statuses) > self.MAX_TERMINAL:
del self._terminal_statuses[next(iter(self._terminal_statuses))]
@@ -341,7 +344,7 @@ class SubagentManager:
for message_id, _ in snapshot:
record.status.receipts[message_id] = "delivered"
if snapshot:
self._save_status(record.status)
await self._save_status(record.status)
return [{"role": "user", "content": content} for _, content in snapshot]
def _owned_status(self, task_id: str, owner: str | None) -> SubagentStatus:
@@ -377,7 +380,7 @@ class SubagentManager:
raise SubagentControlError("task unavailable")
return status, child
def send(self, task_id: str, owner: str | None,
async def send(self, task_id: str, owner: str | None,
message: str | None) -> SubagentMessageReceipt:
"""Accept a bounded follow-up only while execution is open."""
status = self._owned_status(task_id, owner)
@@ -391,7 +394,7 @@ class SubagentManager:
message_id = str(uuid.uuid4())
record.inbox.append((message_id, message))
status.receipts[message_id] = "accepted"
self._save_status(status)
await self._save_status(status)
return {"task_id": task_id, "message_id": message_id,
"receipt": "accepted", "delivered": False}
@@ -410,7 +413,7 @@ class SubagentManager:
task_id = record.status.task_id
task = self._running_tasks.get(task_id)
if record.decide(_SubagentOutcome("cancelled", "Task cancelled.", "cancelled")):
self._save_status(record.status, fsync=True)
await self._save_status(record.status)
if task is not None and record.begun and not task.done():
task.cancel()
if record.status.finished_at is None:
@@ -428,21 +431,44 @@ class SubagentManager:
**deepcopy(self._terminal_statuses),
}
def _runtime_statuses_for_session(self, session_key: str) -> dict[str, SubagentStatus]:
return {
**{tid: record.snapshot() for tid, record in self._tasks.items()
if record.status.owner == session_key and record.status.finished_at is None},
**{tid: deepcopy(status) for tid, status in self._terminal_statuses.items()
if status.owner == session_key},
}
def _merge_session_statuses(
self, session_key: str, runtime: Mapping[str, SubagentStatus], *, include_history: bool,
) -> Mapping[str, SubagentStatus]:
if self.sessions is not None and not self.sessions.exists(session_key):
return {}
statuses = self.sessions.load(session_key) if include_history and self.sessions is not None else {}
for task_id, status in runtime.items():
if self.sessions is not None and not self.sessions.contains(task_id, session_key):
continue
persisted = statuses.get(task_id)
if persisted is None or status.revision >= persisted.revision:
statuses[task_id] = status
return statuses
def statuses_for_session(
self, session_key: str | None, *, include_history: bool = True,
) -> Mapping[str, SubagentStatus]:
"""Return only tasks owned by the given session, never a global fallback."""
if not session_key or (self.sessions is not None and not self.sessions.exists(session_key)):
if not session_key:
return {}
return {
**(self.sessions.load(session_key) if include_history and self.sessions is not None else {}),
**{tid: record.snapshot() for tid, record in self._tasks.items()
if record.status.owner == session_key and record.status.finished_at is None
and (self.sessions is None or self.sessions.contains(tid, session_key))},
**{tid: deepcopy(status) for tid, status in self._terminal_statuses.items()
if status.owner == session_key
and (self.sessions is None or self.sessions.contains(tid, session_key))},
}
return self._merge_session_statuses(
session_key, self._runtime_statuses_for_session(session_key), include_history=include_history,
)
async def read_statuses_for_session(self, session_key: str) -> Mapping[str, SubagentStatus]:
"""Capture runtime observations on the owner loop; read stored metadata on a worker."""
runtime = self._runtime_statuses_for_session(session_key)
return await asyncio.to_thread(
self._merge_session_statuses, session_key, runtime, include_history=True,
)
def set_provider(self, provider: LLMProvider, model: str) -> None:
"""Update the deprecated runtime source used by legacy ``spawn`` calls."""
@@ -511,7 +537,7 @@ class SubagentManager:
ToolLoader().load(ctx, registry, scope="subagent")
return registry
def _create_task(
async def _create_task(
self, task: str, label: str | None, origin_channel: str, origin_chat_id: str,
session_key: str | None, origin_message_id: str | None,
temperature: float | None, workspace_scope: WorkspaceScope | None,
@@ -523,7 +549,7 @@ class SubagentManager:
if temperature is not None:
runtime = runtime.with_generation_overrides(temperature=temperature)
# A failed cleanup owns admission even after its status has been evicted.
if self._closed or len(self._tasks) >= self.MAX_ACTIVE:
if self._closed or len(self._tasks) + self._admitting >= self.MAX_ACTIVE:
raise SubagentControlError("subagent manager is closed or at task capacity")
owner = session_key or f"{origin_channel}:{origin_chat_id}"
task_id = str(uuid.uuid4())
@@ -537,11 +563,28 @@ class SubagentManager:
origin_message_id=origin_message_id,
origin_turn_id=origin_turn_id,
)
if self.sessions is not None:
child = self.sessions.create(status, policy=session_policy)
else:
child = Session(key=SubagentSessions.key(task_id), policy=session_policy or SessionPolicy())
child.add_message("user", task)
self._admitting += 1
try:
if self.sessions is not None:
admission = asyncio.create_task(self.sessions.create(status, policy=session_policy))
try:
child = await shield_and_drain(admission)
except asyncio.CancelledError:
if not admission.cancelled() and admission.exception() is None:
child = admission.result()
await shield_and_drain(self.sessions.sessions.state.delete(
child.key, expected_generation=child.generation,
))
raise
else:
child = Session(key=SubagentSessions.key(task_id), policy=session_policy or SessionPolicy())
child.add_message("user", task)
finally:
self._admitting -= 1
if self._closed:
if self.sessions is not None:
await self.sessions.sessions.state.delete(child.key, expected_generation=child.generation)
raise SubagentControlError("subagent manager is closed")
record = _SubagentTask(
status=status,
session=child,
@@ -580,7 +623,7 @@ class SubagentManager:
) -> str:
"""Start background work and route its terminal result to the parent."""
try:
record = self._create_task(
record = await self._create_task(
task, label, origin_channel, origin_chat_id, session_key,
origin_message_id, temperature, workspace_scope, runtime, announce=True, origin_turn_id=origin_turn_id,
session_policy=session_policy,
@@ -607,7 +650,7 @@ class SubagentManager:
) -> str:
"""Wait for the same task lifecycle without a background notice."""
try:
record = self._create_task(
record = await self._create_task(
task, label, origin_channel, origin_chat_id, session_key,
origin_message_id, temperature, workspace_scope, runtime, announce=False, origin_turn_id=origin_turn_id,
session_policy=session_policy,
@@ -647,9 +690,25 @@ class SubagentManager:
else _SubagentOutcome("cancelled", "Task cancelled.", "cancelled")
)
self._start_cleanup(record)
self._finish(record)
settlement = asyncio.create_task(self._settle_unfinished_task(record))
self._running_tasks[record.status.task_id] = settlement
settlement.add_done_callback(partial(self._task_done, record))
self._release_task(record)
async def _save_transcript(self, record: _SubagentTask) -> None:
if self.sessions is not None:
from nanobot.session.sqlite_store import SessionConflictError
try:
await self.sessions.sessions.state.finish_turn(record.session)
except SessionConflictError:
# A removed child must not be recreated by a late observation.
return
async def _settle_unfinished_task(self, record: _SubagentTask) -> str:
outcome = await self._finish(record)
return outcome.result
async def _run_subagent(self, record: _SubagentTask) -> str:
"""Execute once, seal the outcome, then clean up and publish once."""
status = record.status
@@ -661,7 +720,7 @@ class SubagentManager:
record.raise_if_stopping()
status.state = "running"
status.phase = "initializing"
self._save_status(status)
await self._save_status(status)
outcome = await self._run_admitted_subagent(record)
record.decide(outcome)
except asyncio.CancelledError:
@@ -677,7 +736,7 @@ class SubagentManager:
"Subagent [{}] exec cleanup failed", status.task_id,
)
cleanup_error = f"Error cleaning up task processes: {exc}"
outcome = self._finish(record, cleanup_error)
outcome = await self._finish(record, cleanup_error)
if record.announce and not record.suppress_notice and not self._closed:
await self._announce_result(
status.task_id, label, task_text, outcome.result, record.origin,
@@ -703,7 +762,7 @@ class SubagentManager:
iteration = payload.get("iteration", status.iteration)
if (phase, iteration) != (status.phase, status.iteration):
status.phase, status.iteration = phase, iteration
self._save_status(status)
await self._save_status(status)
root = workspace_scope.project_path if workspace_scope is not None else self.workspace
cfg = None
@@ -719,13 +778,14 @@ class SubagentManager:
]
activity = SessionActivity()
def save_observation(status: SubagentStatus) -> None:
async def save_observation(status: SubagentStatus) -> None:
record.session.messages = activity.transcript()
self._save_status(status)
await self._save_transcript(record)
await self._save_status(status)
async def publish_activity(event: AgentEvent) -> None:
if activity.remember(event):
save_observation(status)
await save_observation(status)
events = EventSink(publish_activity)
hook = build_agent_turn_hook(AgentTurnHookSpec(
+39 -49
View File
@@ -4,7 +4,6 @@ from __future__ import annotations
import math
import time
from copy import deepcopy
from typing import Any, cast
from loguru import logger
@@ -13,6 +12,7 @@ from pydantic import TypeAdapter, ValidationError
from nanobot.agent.subagent_status import SubagentSessionError as SubagentSessionError
from nanobot.agent.subagent_status import SubagentStatus
from nanobot.session.manager import Session, SessionManager, SessionPolicy
from nanobot.session.sqlite_store import SessionConflictError
from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY, SessionType
SUBAGENT = SessionType("subagent", needs_handle=False, public_history=False)
@@ -33,21 +33,23 @@ class SubagentSessions:
return f"subagent:{task_id}"
def exists(self, owner: str) -> bool:
return self.sessions.get_cached(owner) is not None or self.sessions.read_session_metadata(owner) is not None
return (
self.sessions.get_cached_metadata(owner) is not None
or self.sessions.read_session_metadata(owner) is not None
)
def contains(self, task_id: str, owner: str) -> bool:
key = self.key(task_id)
child = self.sessions.get_cached(key)
metadata = child.metadata if child is not None else (self.sessions.read_session_metadata(key) or {}).get("metadata", {})
metadata = self.sessions.get_cached_metadata(key)
if metadata is None:
metadata = (self.sessions.read_session_metadata(key) or {}).get("metadata", {})
return metadata.get(SESSION_TYPE_KEY) == SUBAGENT.name and metadata.get(PARENT_SESSION_KEY) == owner
def snapshot(self, task_id: str, owner: str) -> Session | None:
"""Read a detached child only while its parent still owns it."""
with self.sessions.locked_session_files():
if not self.exists(owner) or not self.contains(task_id, owner):
return None
child = self.sessions.get_cached(self.key(task_id))
return deepcopy(child) if child is not None else self.sessions.read_session_snapshot(self.key(task_id))
if not self.exists(owner) or not self.contains(task_id, owner):
return None
return self.sessions.get_existing(self.key(task_id))
@staticmethod
def _payload(status: SubagentStatus) -> dict[str, Any]:
@@ -56,49 +58,36 @@ class SubagentSessions:
"elapsed_seconds": status.as_dict()["elapsed_seconds"],
}
def create(self, status: SubagentStatus, *, policy: SessionPolicy | None = None) -> Session:
with self.sessions.locked_session_files():
parent = self.sessions.get_existing(status.owner)
if parent is None:
parent = self.sessions.get_or_create(status.owner)
requested = policy or SessionPolicy()
effective = SessionPolicy(
persist=parent.policy.persist and requested.persist,
log_content=parent.policy.log_content and requested.log_content,
)
if effective.persist and self.sessions.read_session_metadata(parent.key) is None:
self.sessions.save(parent, fsync=True)
key = self.key(status.task_id)
child = (self.sessions.get_or_create(key) if effective.persist
else self.sessions.get_or_create_transient(key))
child.policy = effective
child.metadata.update({
SESSION_TYPE_KEY: SUBAGENT.name,
PARENT_SESSION_KEY: status.owner,
TASK_METADATA_KEY: self._payload(status),
})
child.add_message("user", status.task_description)
self.sessions.save(child, fsync=True)
return child
async def create(self, status: SubagentStatus, *, policy: SessionPolicy | None = None) -> Session:
return await self.sessions.state.create_child(
status.owner, self.key(status.task_id),
metadata={SESSION_TYPE_KEY: SUBAGENT.name, TASK_METADATA_KEY: self._payload(status)},
content=status.task_description, policy=policy or SessionPolicy(),
)
def save(self, status: SubagentStatus, *, fsync: bool = False) -> bool:
with self.sessions.locked_session_files():
if not self.exists(status.owner):
return False
child = self.sessions.get_existing(self.key(status.task_id))
if child is None or not self.contains(status.task_id, status.owner):
return False
child.metadata[TASK_METADATA_KEY] = self._payload(status)
# Only create() establishes identity. Progress and late completion
# cannot recreate a child removed with its parent.
self.sessions.save(child, fsync=fsync)
return True
async def save(self, status: SubagentStatus) -> bool:
try:
await self.sessions.state.update_metadata(
self.key(status.task_id), {TASK_METADATA_KEY: self._payload(status)},
)
except SessionConflictError:
return False
return True
def status(self, task_id: str, owner: str) -> SubagentStatus | None:
payload = self.sessions.read_session_metadata(self.key(task_id))
if payload is None:
metadata = self.sessions.get_cached_metadata(self.key(task_id))
payload = {"metadata": metadata} if metadata is not None else None
if payload is None:
return None
metadata = payload.get("metadata", {})
return self._status_from_metadata(task_id, owner, metadata)
@staticmethod
def _status_from_metadata(
task_id: str, owner: str, metadata: dict[str, Any],
) -> SubagentStatus | None:
if metadata.get(SESSION_TYPE_KEY) != SUBAGENT.name or metadata.get(PARENT_SESSION_KEY) != owner:
return None
raw: object = metadata.get(TASK_METADATA_KEY)
@@ -123,16 +112,17 @@ class SubagentSessions:
def load(self, owner: str) -> dict[str, SubagentStatus]:
result: dict[str, SubagentStatus] = {}
for key in self.sessions.child_session_keys(owner):
for row in self.sessions.list_child_session_metadata(owner):
key = row["key"]
task_id = key.removeprefix("subagent:")
if key != self.key(task_id):
continue
status = self.status(task_id, owner)
status = self._status_from_metadata(task_id, owner, row["metadata"])
if status is not None:
result[task_id] = status
return result
def interrupt_pending(self) -> None:
async def interrupt_pending(self) -> None:
"""Seal abandoned work after the gateway acquires execution ownership."""
for row in self.sessions.list_sessions():
key = row["key"]
@@ -156,6 +146,6 @@ class SubagentSessions:
status.tool_events = []
status.receipts = {key: "undelivered" if receipt == "accepted" else receipt
for key, receipt in status.receipts.items()}
self.save(status, fsync=True)
await self.save(status)
except (OSError, SubagentSessionError):
logger.exception("Could not recover subagent session {}", key)
+1
View File
@@ -33,6 +33,7 @@ class RequestContext:
chat_id: str
message_id: str | None = None
session_key: str | None = None
session_generation: str | None = field(default=None, kw_only=True)
original_user_text: str | None = None
runtime: LLMRuntime | None = None
metadata: dict[str, Any] = field(default_factory=dict)
+39 -28
View File
@@ -29,10 +29,11 @@ from nanobot.session.goal_state import (
sustained_goal_active,
)
from nanobot.session.turn_continuation import reset_goal_continuation_rounds
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.prompt_templates import render_template
if TYPE_CHECKING:
from nanobot.session.manager import SessionManager
from nanobot.session.manager import Session, SessionManager
_GOAL_ACTIONS = ("complete", "cancel", "block", "replace")
@@ -61,36 +62,47 @@ class _GoalToolsMixin:
self._sessions = sessions
self._bus = bus
def _session(self):
async def _session(self) -> Session | None:
request_ctx = current_request_context()
if request_ctx is None:
return None
key = request_ctx.session_key
if not key:
return None
return self._sessions.get_or_create(key)
return await self._sessions.state.get_header(key)
def _goal_mutation_allowed(self) -> bool:
return current_request_context() is not None and goal_mutation_allowed()
def _save_goal_state(
async def _save_goal_state(
self,
sess: Any,
sess: Session,
blob: dict[str, Any],
*,
reset_continuation: bool = False,
revoke_permission: bool = False,
) -> None:
previous_metadata = deepcopy(sess.metadata)
sess.metadata[GOAL_STATE_KEY] = blob
discard_legacy_goal_state_key(sess.metadata)
if reset_continuation:
reset_goal_continuation_rounds(sess.metadata)
saved = False
async def save_and_publish() -> None:
nonlocal saved
def change(metadata: dict[str, Any]) -> None:
metadata[GOAL_STATE_KEY] = deepcopy(blob)
discard_legacy_goal_state_key(metadata)
if reset_continuation:
reset_goal_continuation_rounds(metadata)
_, sess.metadata = await self._sessions.state.mutate_metadata(
sess.key, change, expected_generation=sess.generation,
)
saved = True
await self._publish_goal_state_changed(sess.metadata)
try:
self._sessions.save(sess)
except BaseException:
sess.metadata.clear()
sess.metadata.update(previous_metadata)
raise
await shield_and_drain(save_and_publish())
finally:
# This ContextVar belongs to the caller task, not the settlement task.
if revoke_permission and saved:
revoke_goal_mutation_permission()
async def _publish_goal_state_changed(self, metadata: dict[str, Any]) -> None:
bus = self._bus
@@ -171,11 +183,14 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
self,
request: RequestContext,
) -> RuntimeContextBlock | None:
if not request.session_key:
if not request.session_key or not request.persist_session:
return None
session = self._sessions.get_or_create(request.session_key)
payload = await self._sessions.state.read_metadata(request.session_key)
if payload is None:
return None
metadata = payload["metadata"]
goal_start_requested = explicit_goal_requested(request.metadata)
goal_active = sustained_goal_active(session.metadata)
goal_active = sustained_goal_active(metadata)
if not goal_start_requested and not goal_active:
return None
@@ -185,7 +200,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
goal_start_requested=goal_start_requested,
goal_active=goal_active,
)
state = wrap_runtime_context_lines(goal_state_runtime_lines(session.metadata))
state = wrap_runtime_context_lines(goal_state_runtime_lines(metadata))
content = "\n\n".join(part for part in (guidance, state) if part)
return RuntimeContextBlock(source="goal", content=content)
@@ -195,7 +210,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
ui_summary: str | None = None,
**kwargs: Any,
) -> str:
sess = self._session()
sess = await self._session()
if sess is None:
return ToolResult.error(
"Error: create_goal requires an active chat session (missing routing context)."
@@ -223,8 +238,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
"ui_summary": summary,
"started_at": _iso_now(),
}
self._save_goal_state(sess, blob, reset_continuation=True)
await self._publish_goal_state_changed(sess.metadata)
await self._save_goal_state(sess, blob, reset_continuation=True)
extra = f"\nSummary line: {summary}" if summary else ""
return (
"Goal recorded. Keep working toward the objective using ordinary tools. "
@@ -303,7 +317,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
ui_summary: str | None = None,
**kwargs: Any,
) -> str:
sess = self._session()
sess = await self._session()
if sess is None:
return ToolResult.error("Error: update_goal requires an active chat session.")
prior = parse_goal_state(goal_state_raw(sess.metadata))
@@ -338,8 +352,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
"previous_objective": str(prior.get("objective") or ""),
"recap": (recap or "").strip(),
}
self._save_goal_state(sess, blob, reset_continuation=True)
await self._publish_goal_state_changed(sess.metadata)
await self._save_goal_state(sess, blob, reset_continuation=True)
extra = f"\nSummary line: {summary}" if summary else ""
return "Goal replaced. Continue toward the new objective using ordinary tools." + extra
@@ -357,9 +370,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
}
if normalized == "complete":
blob["completed_at"] = ended
self._save_goal_state(sess, blob)
revoke_goal_mutation_permission()
await self._publish_goal_state_changed(sess.metadata)
await self._save_goal_state(sess, blob, revoke_permission=True)
tail = (recap or "").strip()
label = {
+3
View File
@@ -225,6 +225,9 @@ class MessageTool(Tool):
metadata["message_id"] = message_id
if media:
metadata["_record_channel_delivery"] = True
if same_target and request_ctx is not None and request_ctx.session_generation is not None:
metadata["_session_key"] = request_ctx.session_key
metadata["_session_generation"] = request_ctx.session_generation
msg = OutboundMessage(
channel=channel,
+8 -4
View File
@@ -100,7 +100,7 @@ class RuntimeControl(Protocol):
def set_model(self, model: str) -> LLMRuntime: ...
def set_model_preset(
async def set_model_preset(
self,
name: str,
*,
@@ -156,7 +156,11 @@ class _RuntimeControlTarget(Protocol):
def set_model_preset(self, name: str | None) -> LLMRuntime: ...
def set_session_model_preset(self, session_key: str, name: str) -> LLMRuntime: ...
async def set_session_model_preset(
self,
session_key: str,
name: str,
) -> LLMRuntime: ...
class AgentRuntimeControl:
@@ -227,14 +231,14 @@ class AgentRuntimeControl:
def set_model(self, model: str) -> LLMRuntime:
return self.__target.set_runtime_model(model)
def set_model_preset(
async def set_model_preset(
self,
name: str,
*,
session_key: str | None,
) -> LLMRuntime:
if session_key is not None:
return self.__target.set_session_model_preset(session_key, name)
return await self.__target.set_session_model_preset(session_key, name)
return self.__target.set_model_preset(name)
def set_max_iterations(self, value: int) -> None:
+5 -5
View File
@@ -252,7 +252,7 @@ class MyTool(Tool):
if not self._modify_allowed:
return ToolResult.error("Error: set is disabled (tools.my.allow_set is false)")
if action in ("modify", "set"):
return self._modify(key, value)
return await self._modify(key, value)
return f"Unknown action: {action}"
# -- inspect --
@@ -335,7 +335,7 @@ class MyTool(Tool):
# -- modify --
def _modify(self, key: str | None, value: Any) -> str:
async def _modify(self, key: str | None, value: Any) -> str:
if err := self._validate_key(key):
return err
key = cast(str, key)
@@ -361,7 +361,7 @@ class MyTool(Tool):
self._audit("modify", f"READ_ONLY {key}")
return ToolResult.error(f"Error: '{key}' is read-only and cannot be modified")
if key == "model_preset":
return self._modify_model_preset(value)
return await self._modify_model_preset(value)
if key in self.RESTRICTED:
return self._modify_restricted(key, value)
if key in RUNTIME_COMMAND_KEYS:
@@ -371,14 +371,14 @@ class MyTool(Tool):
return ToolResult.error(f"Error: '{key}' is read-only and cannot be modified")
return self._modify_scratchpad(key, value)
def _modify_model_preset(self, value: Any) -> str:
async def _modify_model_preset(self, value: Any) -> str:
if not isinstance(value, str) or not value.strip():
return ToolResult.error("Error: 'model_preset' must be a non-empty string")
name = value.strip()
session_key = current_request_session_key()
old = self._runtime_control.snapshot().model_preset
try:
runtime = self._runtime_control.set_model_preset(
runtime = await self._runtime_control.set_model_preset(
name,
session_key=session_key,
)
+3 -6
View File
@@ -88,7 +88,7 @@ class ListSessionsTool(Tool):
request = current_request_context()
if request is None or not request.session_key:
return ToolResult.error("Error: session context is unavailable")
handles = await asyncio.to_thread(self._handles.list_all)
handles = await self._handles.alist_all()
return json.dumps(
[
f"@{handle.name}"
@@ -219,14 +219,11 @@ class SendSessionMessageTool(Tool):
target_name = normalize_session_handle(target_handle)
except ValueError as exc:
raise SessionMessageError(str(exc)) from exc
target = await asyncio.to_thread(self._handles.resolve, target_name)
target = await self._handles.aresolve(target_name)
if target is None:
raise SessionMessageError(f"session @{target_name} was not found")
source = await asyncio.to_thread(
self._handles.handle_for_session,
source_session_key,
)
source = await self._handles.ahandle_for_session(source_session_key)
if source is None:
raise SessionMessageError("source session was not found")
envelope: SessionMessageEnvelope = {
+1 -4
View File
@@ -186,10 +186,7 @@ class ReadSessionTool(_SessionTool):
handle_name = normalize_session_handle(session_key)
except ValueError as exc:
return ToolResult.error(f"Error: {exc}")
handle = await asyncio.to_thread(
self._handles.resolve,
handle_name,
)
handle = await self._handles.aresolve(handle_name)
if handle is None:
return ToolResult.error(f"Error: session @{handle_name} was not found")
session_handle = f"@{handle_name}"
+1 -1
View File
@@ -109,7 +109,7 @@ class SubagentTool(Tool):
if not task_id:
return ToolResult.error(f"Error: {action} requires task_id")
if action == "send":
return json.dumps(self._manager.send(task_id, owner, message))
return json.dumps(await self._manager.send(task_id, owner, message))
status = await self._manager.cancel(task_id, owner)
return json.dumps(status.as_dict(), ensure_ascii=False)
return ToolResult.error("Error: unknown subagent action")
+5
View File
@@ -231,6 +231,11 @@ class TurnDelivery:
def streaming(self) -> bool:
return self._stream_base_id is not None
def bind_session_generation(self, generation: str) -> None:
"""Attach the admitted session identity to all later lifecycle events."""
self.delivery_message.session_generation = generation
self.lifecycle_message.session_generation = generation
def remember_session_route(self, session_metadata: dict[str, Any]) -> None:
"""Keep only routing fields needed to deliver a later idle notification."""
if is_internal_session(self.session_key):
+1
View File
@@ -36,6 +36,7 @@ class InboundMessage:
session_key_override: str | None = None # Optional override for thread-scoped sessions
require_existing_session: bool = False
input_role: Literal["user", "system"] | None = None
session_generation: str | None = None # Trusted identity assigned at session admission
@property
def session_key(self) -> str:
+8
View File
@@ -23,6 +23,7 @@ class RuntimeEventContext:
session_key: str
metadata: dict[str, Any] = field(default_factory=dict)
attributes: dict[str, Any] = field(default_factory=dict)
session_generation: str | None = None
@dataclass(frozen=True)
@@ -128,11 +129,13 @@ class RuntimeEventPublisher:
session_key: str,
metadata: dict[str, Any] | None,
attributes: dict[str, Any] | None = None,
session_generation: str | None = None,
) -> RuntimeEventContext:
return RuntimeEventContext(
channel=channel,
chat_id=chat_id,
session_key=session_key,
session_generation=session_generation,
metadata=dict(metadata or {}),
attributes=dict(attributes or {}),
)
@@ -180,6 +183,7 @@ class RuntimeEventPublisher:
chat_id=msg.chat_id,
session_key=session_key,
metadata=msg.metadata,
session_generation=msg.session_generation,
),
content=msg.content,
)
@@ -197,6 +201,7 @@ class RuntimeEventPublisher:
chat_id=msg.chat_id,
session_key=session_key,
metadata=msg.metadata,
session_generation=msg.session_generation,
),
)
)
@@ -216,6 +221,7 @@ class RuntimeEventPublisher:
chat_id=msg.chat_id,
session_key=session_key,
metadata=msg.metadata,
session_generation=msg.session_generation,
),
runtime=runtime,
)
@@ -236,6 +242,7 @@ class RuntimeEventPublisher:
chat_id=msg.chat_id,
session_key=session_key,
metadata=msg.metadata,
session_generation=msg.session_generation,
),
status=status,
started_at=started_at,
@@ -257,6 +264,7 @@ class RuntimeEventPublisher:
chat_id=msg.chat_id,
session_key=session_key,
metadata=msg.metadata,
session_generation=msg.session_generation,
attributes=attributes,
),
turn_id=turn_id,
+2
View File
@@ -265,6 +265,7 @@ class BaseChannel(ABC):
is_dm: bool = False,
authorization_id: str | None = None,
require_existing_session: bool = False,
session_generation: str | None = None,
) -> None:
"""Handle a message after checking its authorization subject.
@@ -323,6 +324,7 @@ class BaseChannel(ABC):
media=media or [],
metadata=meta,
session_key_override=session_key,
session_generation=session_generation,
require_existing_session=require_existing_session,
)
+1
View File
@@ -202,6 +202,7 @@ class ChannelManager:
static_dist_path=static_path,
workspace_path=workspace,
default_restrict_to_workspace=self.config.tools.restrict_to_workspace,
unified_session=self.config.agents.defaults.unified_session,
config_path=self._config_path,
disabled_skills=set(self.config.agents.defaults.disabled_skills),
runtime_model_name=self._webui_runtime_model_name,
+2
View File
@@ -432,6 +432,7 @@ class SignalChannel(BaseChannel):
is_dm: bool = False,
authorization_id: str | None = None,
require_existing_session: bool = False,
session_generation: str | None = None,
) -> None:
"""Handle an inbound message whose policy has already been checked.
@@ -454,6 +455,7 @@ class SignalChannel(BaseChannel):
media=media or [],
metadata=meta,
session_key_override=session_key,
session_generation=session_generation,
require_existing_session=require_existing_session,
)
)
+2
View File
@@ -459,6 +459,7 @@ class WebSocketChannel(BaseChannel):
is_dm: bool,
session_key: str | None,
require_existing_session: bool,
session_generation: str | None,
) -> None:
await self._handle_message(
sender_id=sender_id,
@@ -469,6 +470,7 @@ class WebSocketChannel(BaseChannel):
is_dm=is_dm,
session_key=session_key,
require_existing_session=require_existing_session,
session_generation=session_generation,
)
def _attach(self, connection: ServerConnection, chat_id: str) -> None:
@@ -2,6 +2,7 @@
import asyncio
import json
import threading
import time
import uuid
from pathlib import Path
@@ -52,7 +53,7 @@ from nanobot.providers.base import LLMUsage
from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META, WEBUI_QUOTE_SOURCE
from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY
from nanobot.session import webui_turns as wth
from nanobot.session.manager import SessionManager
from nanobot.session.manager import Session, SessionManager
from nanobot.session.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
from nanobot.session.session_handles import session_handle_for_name
from nanobot.webui.gateway_services import GatewayServices, build_gateway_services
@@ -2034,7 +2035,7 @@ async def test_webui_set_workspace_scope_rejects_running_chat(bus: MagicMock, tm
},
},
)
channel.gateway.workspaces.persist_scope(
await channel.gateway.workspaces.persist_scope(
"chat-running",
channel.gateway.workspaces.scope_for_session_key("websocket:chat-running"),
)
@@ -2974,6 +2975,56 @@ async def test_stream_transcript_persists_without_subscribers() -> None:
assert _thread_conversation_events(body)[-1]["latencyMs"] == 42
@pytest.mark.asyncio
@pytest.mark.parametrize("temporary", [False, True])
async def test_stream_policy_does_not_copy_history_on_runtime_loop(
bus, tmp_path, monkeypatch, temporary,
) -> None:
import nanobot.session.state as session_state
sessions = SessionManager(tmp_path)
channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]}, bus,
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
)
owner = object()
chat_id = (
await channel.gateway.temporary_chats.create(owner, trusted_webui=True)
if temporary else "history-copy"
)
history = [
{"role": "user", "content": f"history {i}"} for i in range(1000)
]
draft = await sessions.state.import_messages(f"websocket:{chat_id}", history)
await sessions.state.checkpoint_view(draft, {"messages": history})
runtime_thread = threading.get_ident()
original_copy = session_state.deepcopy
def copy_off_loop(value, *args, **kwargs):
if (
isinstance(value, Session) and value.messages
or isinstance(value, dict) and "runtime_checkpoint" in value
):
assert threading.get_ident() != runtime_thread, "history copied on runtime loop"
return original_copy(value, *args, **kwargs)
monkeypatch.setattr(session_state, "deepcopy", copy_off_loop)
append = MagicMock()
monkeypatch.setattr("nanobot.webui.transcript.append_transcript_object", append)
try:
policy = channel.gateway.temporary_chats.message_policy(owner, chat_id, "hello")
assert (policy is not None) is temporary
await channel.send_delta(chat_id, "one", stream_id="s1")
await channel.send_delta(chat_id, " two", stream_id="s1")
await channel.send_delta(chat_id, "", stream_id="s1", stream_end=True)
await channel.send_reasoning_delta(chat_id, "plan", stream_id="r1")
await channel.send_reasoning_end(chat_id, stream_id="r1")
assert append.call_count == (0 if temporary else 2)
finally:
channel.gateway.temporary_chats.close()
await sessions.state.aclose()
@pytest.mark.asyncio
async def test_stream_transcript_writes_once_per_completed_segment(monkeypatch) -> None:
bus = MagicMock()
@@ -3913,7 +3964,8 @@ async def test_hydrate_noop_without_session_manager() -> None:
async def test_hydrate_skips_when_no_goal_on_disk() -> None:
bus = MagicMock()
sm = MagicMock()
sm.read_session_metadata.return_value = None
sm.state.read_metadata = AsyncMock()
sm.state.read_metadata.return_value = None
channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]},
bus,
@@ -3929,7 +3981,8 @@ async def test_hydrate_skips_when_no_goal_on_disk() -> None:
async def test_hydrate_notifies_when_goal_active_on_disk() -> None:
bus = MagicMock()
sm = MagicMock()
sm.read_session_metadata.return_value = {
sm.state.read_metadata = AsyncMock()
sm.state.read_metadata.return_value = {
"metadata": {
"goal_state": {
"status": "active",
@@ -3960,7 +4013,8 @@ async def test_hydrate_notifies_when_goal_active_on_disk() -> None:
async def test_hydrate_restores_blocked_attention_on_disk() -> None:
bus = MagicMock()
sm = MagicMock()
sm.read_session_metadata.return_value = {
sm.state.read_metadata = AsyncMock()
sm.state.read_metadata.return_value = {
"metadata": {
"goal_state": {
"status": "blocked",
@@ -5692,13 +5746,17 @@ def test_sessions_list_includes_active_run_started_at(monkeypatch) -> None:
"updated_at": "2026-05-19T10:01:00Z",
},
]
monkeypatch.setattr(ws_http_module, "list_webui_sessions", lambda _session_manager: sessions)
session_manager.state.query_metadata = AsyncMock(side_effect=lambda project: project([]))
monkeypatch.setattr(ws_http_module, "list_webui_sessions", lambda _session_manager, _stored: sessions)
handle = session_handle_for_name("websocket:chat-1", "luma")
monkeypatch.setattr(
ws_http_module,
"SessionHandleResolver",
lambda _session_manager: SimpleNamespace(
list_all_by_key=lambda: {handle.session_key: handle}
handles_from_metadata=MagicMock(return_value={handle.session_key: handle}),
alist_all_by_key=AsyncMock(
return_value={handle.session_key: handle}
)
),
)
channel = WebSocketChannel(
@@ -6673,3 +6731,48 @@ async def test_webui_access_mode_can_toggle_back_to_full(bus, tmp_path, headers)
assert channel.gateway.workspaces.scope_for_session_key(
"websocket:handshake-scope"
).access_mode == mode
@pytest.mark.parametrize("command_type", ["new_chat", "attach", "set_workspace_scope", "message"])
async def test_webui_commands_keep_session_io_off_event_loop(
bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, command_type: str,
) -> None:
import threading
sessions = SessionManager(tmp_path / "sessions")
sessions.save(sessions.get_or_create("websocket:io-chat"))
channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"], "host": "127.0.0.1"},
bus,
gateway=_basic_handler(bus, session_manager=sessions, workspace_path=tmp_path),
)
conn = AsyncMock()
conn.remote_address = ("127.0.0.1", 50123)
loop_thread = threading.get_ident()
calls: list[str] = []
def require_worker(name):
operation = getattr(sessions._store, name)
def checked(*args, **kwargs):
assert threading.get_ident() != loop_thread, name
calls.append(name)
return operation(*args, **kwargs)
return checked
for name in ("read_metadata", "load", "save", "replace_metadata"):
monkeypatch.setattr(sessions._store, name, require_worker(name))
await channel._dispatch_envelope(
conn,
"webui-client",
{"type": command_type, "chat_id": "io-chat", "content": "/help", "webui": True},
)
assert "read_metadata" in calls
if command_type in {"set_workspace_scope", "message"}:
assert "load" in calls
assert "save" in calls or "replace_metadata" in calls
assert all(json.loads(call.args[0])["event"] != "error" for call in conn.send.await_args_list)
await channel._cleanup_connection(conn)
@@ -194,7 +194,7 @@ async def test_webui_message_forwards_verified_session_mentions(tmp_path) -> Non
channel._handle_message.assert_awaited_once()
metadata = channel._handle_message.call_args.kwargs["metadata"]
handle = SessionHandleResolver(manager).handle_for_session("websocket:pricing")
handle = await SessionHandleResolver(manager).ahandle_for_session("websocket:pricing")
assert handle is not None
assert metadata["session_mentions"] == [{
**handle.public_payload(),
@@ -313,7 +313,7 @@ async def test_sessions_list_and_thread_restore_transcript_without_canonical_fil
key,
{"event": "message", "chat_id": "restored-history", "text": "original answer"},
)
assert not sm._get_session_path(key).exists()
assert sm.read_session_snapshot(key) is None
port = _free_port()
channel = _ch(bus, session_manager=sm, port=port)
@@ -344,7 +344,7 @@ async def test_sessions_list_and_thread_restore_transcript_without_canonical_fil
"original question",
"original answer",
]
assert not sm._get_session_path(key).exists()
assert sm.read_session_snapshot(key) is None
finally:
await channel.stop()
await server_task
@@ -2306,7 +2306,7 @@ async def test_sessions_list_only_returns_websocket_sessions_by_default(
rows = {row["key"]: row for row in sessions}
handles = {
handle.session_key: handle
for handle in SessionHandleResolver(sm).list_all()
for handle in await SessionHandleResolver(sm).alist_all()
}
assert rows["websocket:alpha"]["handle"] == handles[
"websocket:alpha"
@@ -2385,8 +2385,8 @@ async def test_session_delete_removes_file(
channel = _ch(bus, session_manager=sm, port=29903)
server_task = asyncio.create_task(channel.start())
try:
path = sm._get_session_path("websocket:doomed")
assert path.exists()
session_key = "websocket:doomed"
assert sm.read_session_snapshot(session_key) is not None
webui_path = tmp_path / "webui" / f"{SessionManager.safe_key('websocket:doomed')}.jsonl"
assert webui_path.is_file()
resp = await _webui_mutate(
@@ -2396,7 +2396,7 @@ async def test_session_delete_removes_file(
)
assert resp.status_code == 200
assert resp.json()["deleted"] is True
assert not path.exists()
assert sm.read_session_snapshot(session_key) is None
assert not webui_path.exists()
finally:
await channel.stop()
@@ -2416,7 +2416,7 @@ async def test_session_delete_removes_transcript_without_canonical_file(
key,
{"event": "user", "chat_id": "transcript-only", "text": "recover me"},
)
assert not sm._get_session_path(key).exists()
assert sm.read_session_snapshot(key) is None
webui_path = tmp_path / "webui" / f"{SessionManager.safe_key(key)}.jsonl"
assert webui_path.is_file()
@@ -2998,7 +2998,7 @@ async def test_session_delete_blocks_when_bound_automation_exists(
channel = _ch(bus, session_manager=sm, cron_service=cron, port=29915)
server_task = asyncio.create_task(channel.start())
try:
path = sm._get_session_path("websocket:doomed")
session_key = "websocket:doomed"
resp = await _webui_mutate(
channel,
"session.delete",
@@ -3010,7 +3010,7 @@ async def test_session_delete_blocks_when_bound_automation_exists(
assert body["deleted"] is False
assert body["blocked_by_automations"] is True
assert [job["name"] for job in body["automations"]] == ["Daily check"]
assert path.exists()
assert sm.read_session_snapshot(session_key) is not None
assert cron.list_bound_cron_jobs_for_session("websocket:doomed")
finally:
await channel.stop()
@@ -3086,7 +3086,7 @@ async def test_session_delete_can_cascade_bound_automations(
channel = _ch(bus, session_manager=sm, cron_service=cron, port=29916)
server_task = asyncio.create_task(channel.start())
try:
path = sm._get_session_path("websocket:doomed")
session_key = "websocket:doomed"
resp = await _webui_mutate(
channel,
"session.delete",
@@ -3095,7 +3095,7 @@ async def test_session_delete_can_cascade_bound_automations(
assert resp.status_code == 200
assert resp.json()["deleted"] is True
assert not path.exists()
assert sm.read_session_snapshot(session_key) is None
assert cron.list_bound_cron_jobs_for_session("websocket:doomed") == []
assert cron.list_jobs(include_disabled=True) == []
finally:
@@ -3126,7 +3126,7 @@ async def test_session_delete_blocks_origin_automation_when_unified_enabled(
)
server_task = asyncio.create_task(channel.start())
try:
path = sm._get_session_path("websocket:doomed")
session_key = "websocket:doomed"
resp = await _webui_mutate(
channel,
"session.delete",
@@ -3138,7 +3138,7 @@ async def test_session_delete_blocks_origin_automation_when_unified_enabled(
assert body["deleted"] is False
assert body["blocked_by_automations"] is True
assert [job["name"] for job in body["automations"]] == ["Chat daily check"]
assert path.exists()
assert sm.read_session_snapshot(session_key) is not None
assert [job.name for job in cron.list_bound_cron_jobs_for_session("websocket:doomed")] == [
"Chat daily check"
]
@@ -3155,8 +3155,8 @@ async def test_session_delete_action_accepts_websocket_keys(
channel = _ch(bus, session_manager=sm, port=29910)
server_task = asyncio.create_task(channel.start())
try:
path = sm._get_session_path("websocket:encoded-key")
assert path.exists()
session_key = "websocket:encoded-key"
assert sm.read_session_snapshot(session_key) is not None
deleted = await _webui_mutate(
channel,
"session.delete",
@@ -3164,7 +3164,7 @@ async def test_session_delete_action_accepts_websocket_keys(
)
assert deleted.status_code == 200
assert deleted.json()["deleted"] is True
assert not path.exists()
assert sm.read_session_snapshot(session_key) is None
finally:
await channel.stop()
await server_task
@@ -3511,8 +3511,8 @@ async def test_session_delete_rejects_non_websocket_keys(
token = channel.gateway.tokens.issue_api_token(300)
auth = {"Authorization": f"Bearer {token}"}
doomed = sm._get_session_path("slack:C123")
assert doomed.exists()
session_key = "slack:C123"
assert sm.read_session_snapshot(session_key) is not None
get_delete = await _http_get(
"http://127.0.0.1:29909/api/sessions/slack:C123/delete",
headers=auth,
@@ -3525,7 +3525,7 @@ async def test_session_delete_rejects_non_websocket_keys(
{"key": "slack:C123"},
)
assert deny_delete.status_code == 404
assert doomed.exists()
assert sm.read_session_snapshot(session_key) is not None
finally:
await channel.stop()
await server_task
@@ -4254,3 +4254,42 @@ async def test_project_favorites_mutation_persists_without_selecting_project(
response = await _webui_mutate(channel, "workspace.favorite", {"path": str(project), "pinned": False}, connection=connection)
assert response.status_code == 200
assert response.json() == {"favorite_projects": []}
@pytest.mark.asyncio
async def test_session_delete_waiting_on_sqlite_does_not_block_event_loop(
bus: MagicMock,
tmp_path: Path,
) -> None:
import sqlite3
sm = _seed_session(tmp_path, key="websocket:locked-delete")
channel = _ch(bus, session_manager=sm, port=_free_port())
blocker = sqlite3.connect(sm._store.path, isolation_level=None)
blocker.execute("BEGIN IMMEDIATE")
try:
deletion = asyncio.create_task(
_webui_mutate(
channel,
"session.delete",
{"key": "websocket:locked-delete"},
)
)
ticked = False
async def tick() -> None:
nonlocal ticked
await asyncio.sleep(0.05)
ticked = True
await asyncio.wait_for(tick(), timeout=0.25)
assert ticked
assert not deletion.done()
blocker.rollback()
response = await asyncio.wait_for(deletion, timeout=2)
assert response.status_code == 200
assert sm.read_session_snapshot("websocket:locked-delete") is None
finally:
if blocker.in_transaction:
blocker.rollback()
blocker.close()
@@ -1,6 +1,6 @@
"""Test websocket subscribe hydration only replays known active turns."""
from unittest.mock import MagicMock, patch
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -15,7 +15,7 @@ async def test_hydrate_after_subscribe_is_quiet_when_no_turn_active():
channel = WebSocketChannel.__new__(WebSocketChannel)
channel.gateway = MagicMock()
channel.gateway.session_manager = MagicMock()
channel.gateway.session_manager.read_session_metadata = MagicMock(return_value={})
channel.gateway.session_manager.state.read_metadata = AsyncMock(return_value={})
channel._session_projection = WebUISessionProjection(channel.gateway.session_manager)
channel._outbound = WebUIOutboundProjector(channel, channel._session_projection)
channel._turn_models = {}
@@ -43,7 +43,7 @@ async def test_hydrate_after_subscribe_pushes_running_when_turn_active():
channel = WebSocketChannel.__new__(WebSocketChannel)
channel.gateway = MagicMock()
channel.gateway.session_manager = MagicMock()
channel.gateway.session_manager.read_session_metadata = MagicMock(return_value={})
channel.gateway.session_manager.state.read_metadata = AsyncMock(return_value={})
channel._session_projection = WebUISessionProjection(channel.gateway.session_manager)
channel._outbound = WebUIOutboundProjector(channel, channel._session_projection)
channel._turn_models = {}
@@ -0,0 +1,177 @@
"""WebUI admission binds the generation of the session that executes the turn."""
from __future__ import annotations
import asyncio
import json
from collections.abc import AsyncIterator
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import pytest
from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.manager import ChannelManager
from nanobot.channels.websocket.runtime import WebSocketChannel
from nanobot.config.schema import Config
from nanobot.providers.base import LLMProvider, LLMResponse
from nanobot.runtime_context import public_history_message
from nanobot.session.keys import UNIFIED_SESSION_KEY, session_key_for_channel
from nanobot.session.manager import SessionManager
from nanobot.session.webui_turns import clear_websocket_turns
from nanobot.webui.transcript import read_transcript_lines
class _Provider(LLMProvider):
def __init__(self) -> None:
super().__init__(provider_name="test")
self.calls = 0
def get_default_model(self) -> str:
return "test-model"
async def chat(self, messages: list[dict[str, Any]], **kwargs: Any) -> LLMResponse:
self.calls += 1
return LLMResponse(content="hello back", finish_reason="stop")
class _Connection:
remote_address = None
def __init__(self) -> None:
self.sent: list[dict[str, Any]] = []
async def send(self, raw: str) -> None:
self.sent.append(json.loads(raw))
@dataclass
class _Runtime:
bus: MessageBus
sessions: SessionManager
loop: AgentLoop
channel: WebSocketChannel
connection: _Connection
provider: _Provider
async def message(self, chat_id: str, text: str = "hello") -> InboundMessage:
await self.channel._dispatch_envelope(
self.connection,
"webui-client",
{"type": "message", "chat_id": chat_id, "content": text, "webui": True},
)
return await self.bus.consume_inbound()
async def execute(self, message: InboundMessage) -> None:
await self.loop._enqueue_session_message(message)
tasks = self.loop._active_tasks[self.loop._effective_session_key(message)]
await asyncio.gather(*tuple(tasks))
@pytest.fixture(params=[False, True], ids=["separate", "shared"])
async def runtime(request: pytest.FixtureRequest, tmp_path: Path) -> AsyncIterator[_Runtime]:
unified = request.param
workspace = tmp_path / "workspace"
workspace.mkdir()
config = Config.model_validate({"agents": {"defaults": {
"workspace": str(workspace), "unifiedSession": unified,
}}})
bus = MessageBus()
sessions = SessionManager(workspace)
provider = _Provider()
loop = AgentLoop(
bus=bus, provider=provider, workspace=workspace,
session_manager=sessions, unified_session=unified,
)
manager = ChannelManager(
config, bus, session_manager=sessions, webui_static_dist=False,
config_path=tmp_path / "config.json",
)
channel = manager.channels["websocket"]
assert isinstance(channel, WebSocketChannel)
connection = _Connection()
channel._webui_connections.add(connection)
try:
yield _Runtime(bus, sessions, loop, channel, connection, provider)
finally:
chat_ids = tuple(channel._subs)
await channel._cleanup_connection(connection)
channel.gateway.temporary_chats.close()
for chat_id in chat_ids:
clear_websocket_turns(chat_id)
await loop.aclose()
async def test_webui_admission_executes_with_the_routed_session(runtime: _Runtime) -> None:
for chat_id in ("chat-a", "chat-b"):
message = await runtime.message(chat_id)
await runtime.execute(message)
key = session_key_for_channel(
"websocket", chat_id, unified_session=runtime.channel.gateway.unified_session,
)
session = await runtime.sessions.state.read(key)
assert session is not None
assert [public_history_message(record)["content"] for record in session.messages
if record["role"] == "user"] == (
["hello", "hello"] if key == UNIFIED_SESSION_KEY and chat_id == "chat-b"
else ["hello"]
)
display = await runtime.sessions.state.read_metadata(f"websocket:{chat_id}")
assert display is not None and display["metadata"]["webui"] is True
assert runtime.provider.calls == 2
@pytest.mark.parametrize("operation", ["reset", "delete"])
async def test_replaced_execution_session_rejects_accepted_input(
runtime: _Runtime, operation: str,
) -> None:
message = await runtime.message("chat-stale")
key = runtime.loop._effective_session_key(message)
if operation == "reset":
await runtime.sessions.state.reset(key)
else:
await runtime.sessions.state.delete(key)
await runtime.execute(message)
assert runtime.provider.calls == 0
remaining = await runtime.sessions.state.read(key)
assert remaining is None or remaining.messages == []
async def test_failed_transport_admission_removes_new_sessions(
runtime: _Runtime, monkeypatch: pytest.MonkeyPatch,
) -> None:
async def reject(message: InboundMessage) -> None:
raise RuntimeError("queue unavailable")
monkeypatch.setattr(runtime.bus, "publish_inbound", reject)
with pytest.raises(RuntimeError, match="queue unavailable"):
await runtime.message("chat-rejected")
assert await runtime.sessions.state.list_sessions() == []
async def test_temporary_chat_retains_its_own_generation(runtime: _Runtime) -> None:
await runtime.channel._dispatch_envelope(
runtime.connection, "webui-client", {"type": "new_temporary_chat"},
)
chat_id = next(event["chat_id"] for event in runtime.connection.sent
if event["event"] == "attached")
first = await runtime.message(chat_id)
await runtime.execute(first)
assert runtime.provider.calls == 1
assert runtime.loop._effective_session_key(first) == f"websocket:{chat_id}"
assert await runtime.sessions.state.list_sessions() == []
assert read_transcript_lines(f"websocket:{chat_id}") == []
queued = await runtime.message(chat_id, "discarded input")
await runtime.channel.gateway.temporary_chats.discard(runtime.connection, chat_id)
await runtime.execute(queued)
assert runtime.provider.calls == 1
assert await runtime.sessions.state.read(first.session_key) is None
assert await runtime.sessions.state.list_sessions() == []
-38
View File
@@ -477,44 +477,6 @@ app.add_typer(
app.command(name="agent")(agent)
# ============================================================================
# Session Commands
# ============================================================================
sessions_app = typer.Typer(help="Manage persisted session history")
app.add_typer(sessions_app, name="sessions")
@sessions_app.command("restore-workspace")
def sessions_restore_workspace(
config: str | None = typer.Option(None, "--config", "-c", help="Path to config file"),
workspace: str | None = typer.Option(None, "--workspace", "-w", help="Workspace directory"),
) -> None:
"""Copy sessions back into the workspace before downgrading nanobot."""
from nanobot.session.manager import SessionManager
runtime_config = _load_runtime_config(config, workspace)
data_dir = runtime_config.runtime_data_dir
manager = SessionManager(
runtime_config.workspace_path,
sessions_root=data_dir / "sessions" if data_dir is not None else None,
)
result = manager.restore_sessions_to_workspace()
console.print(
f"Restored {result.restored} session file(s) to "
f"{escape(str(runtime_config.workspace_path / 'sessions'))}; "
f"{result.unchanged} already matched."
)
if result.conflicts:
console.print(
"[red]Rollback is incomplete: existing or invalid files require manual review.[/red]"
)
for path in result.conflicts:
console.print(Text(f"- {path}", style="red"))
raise typer.Exit(1)
# ============================================================================
# Channel Commands
# ============================================================================
+70 -50
View File
@@ -4,6 +4,8 @@ import asyncio
import signal
from collections.abc import Awaitable, Callable, Coroutine, Iterable
from contextlib import suppress
from dataclasses import replace
from functools import partial
from pathlib import Path
from typing import Any, cast
@@ -21,6 +23,8 @@ from nanobot.agent.tools.image_generation import (
)
from nanobot.agent.tools.mcp import MCPProvider
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.cli import terminal as cli_terminal
from nanobot.cli.runtime_config import _migrate_cron_store
from nanobot.cli.webui_support import (
@@ -44,7 +48,9 @@ from nanobot.session.keys import (
HEARTBEAT_SESSION_KEY,
UNIFIED_SESSION_KEY,
last_channel_from_metadata,
session_key_for_channel,
)
from nanobot.session.manager import SessionManager
from nanobot.utils.evaluator import evaluate_response, resolve_evaluator_prompt
from nanobot.utils.helpers import sync_workspace_templates
from nanobot.utils.token_encoding import warmup_token_encoding
@@ -57,6 +63,48 @@ __all__ = ["_run_gateway"]
console = Console()
async def _deliver_to_channel(
msg: OutboundMessage,
*,
bus: MessageBus,
session_manager: SessionManager,
unified_session: bool = False,
record: bool = False,
session_key: str | None = None,
session_generation: str | None = None,
) -> None:
"""Publish a user-visible message and mirror it into its admitted session."""
metadata = dict(msg.metadata or {})
record = record or bool(metadata.pop("_record_channel_delivery", False))
raw_key = metadata.pop("_session_key", None)
raw_generation = metadata.pop("_session_generation", None)
expected_generation = (
session_generation
if session_generation is not None
else raw_generation if isinstance(raw_generation, str) else None
)
if metadata != (msg.metadata or {}):
msg = replace(msg, metadata=metadata)
if record and msg.channel != "cli" and msg.content.strip():
key = session_key or (raw_key if isinstance(raw_key, str) else None)
if key is None:
key = session_key_for_channel(
msg.channel, msg.chat_id, unified_session=unified_session,
)
if expected_generation is None:
# Cross-target sends admit their target before recording; subsequent
# deletion or reset must still revoke this delivery's generation.
target = await session_manager.state.get_header(key)
expected_generation = target.generation
extra: dict[str, Any] = {"_channel_delivery": True}
if msg.media:
extra["media"] = list(msg.media)
await session_manager.state.record_delivery(
key, msg.content, extra, expected_generation=expected_generation,
)
await bus.publish_outbound(msg)
class _MCPReadinessHook(AgentHook):
"""Retry application-owned MCP connections before the runner reads tools."""
@@ -519,9 +567,6 @@ def _run_gateway(
schedule_background=_schedule_webui_background,
recovery=recovery,
)
from nanobot.bus.events import OutboundMessage
from nanobot.session.keys import session_key_for_channel
def _channel_session_key(channel: str, chat_id: str) -> str:
return session_key_for_channel(
channel,
@@ -529,41 +574,16 @@ def _run_gateway(
unified_session=config.agents.defaults.unified_session,
)
async def _deliver_to_channel(
msg: OutboundMessage, *, record: bool = False, session_key: str | None = None,
) -> None:
"""Publish a user-visible message and mirror it into that channel's session."""
metadata = dict(msg.metadata or {})
record = record or bool(metadata.pop("_record_channel_delivery", False))
if metadata != (msg.metadata or {}):
msg = OutboundMessage(
channel=msg.channel,
chat_id=msg.chat_id,
content=msg.content,
reply_to=msg.reply_to,
media=msg.media,
metadata=metadata,
buttons=msg.buttons,
)
if (
record
and msg.channel != "cli"
and msg.content.strip()
and hasattr(session_manager, "get_or_create")
and hasattr(session_manager, "save")
):
key = session_key or _channel_session_key(msg.channel, msg.chat_id)
session = session_manager.get_or_create(key)
extra: dict[str, Any] = {"_channel_delivery": True}
if msg.media:
extra["media"] = list(msg.media)
session.add_message("assistant", msg.content, **extra)
session_manager.save(session)
await bus.publish_outbound(msg)
deliver_to_channel = partial(
_deliver_to_channel,
bus=bus,
session_manager=session_manager,
unified_session=config.agents.defaults.unified_session,
)
message_tool = agent.tools.get("message")
if isinstance(message_tool, MessageTool):
message_tool.set_send_callback(_deliver_to_channel)
message_tool.set_send_callback(deliver_to_channel)
# Set cron callback (needs agent)
async def on_cron_job(job: CronJob) -> str | CronRunResult | None:
@@ -576,7 +596,6 @@ def _run_gateway(
from nanobot.agent.memory import MemoryStore
dream_session_key = MemoryStore.dream_session_key
prune_dream_sessions = MemoryStore.prune_dream_sessions
store = agent.context.memory
resp = None
@@ -628,7 +647,7 @@ def _run_gateway(
if sha:
logger.info("Dream commit: {}", sha)
store.compact_history()
prune_dream_sessions(agent.sessions)
await agent.sessions.state.prune_dream_sessions()
return None
# Heartbeat is a system job that checks HEARTBEAT.md for active tasks.
@@ -643,9 +662,14 @@ def _run_gateway(
logger.debug("Heartbeat: HEARTBEAT.md has no active tasks")
return None
channel, chat_id = _pick_heartbeat_target()
channel, chat_id = await _pick_heartbeat_target()
if channel == "cli":
return None
delivery_key = _channel_session_key(channel, chat_id)
delivery_session = await session_manager.state.read(delivery_key)
if delivery_session is None:
return None
delivery_generation = delivery_session.generation
prompt = (
_HEARTBEAT_PREAMBLE
@@ -690,9 +714,11 @@ def _run_gateway(
if should_notify:
logger.info("Heartbeat: completed, delivering response")
await _deliver_to_channel(
await deliver_to_channel(
OutboundMessage(channel=channel, chat_id=chat_id, content=response),
record=True,
session_key=delivery_key,
session_generation=delivery_generation,
)
else:
logger.info("Heartbeat: silenced by post-run evaluation")
@@ -755,17 +781,17 @@ def _run_gateway(
config_path=Path(config_path),
)
def _pick_heartbeat_target() -> tuple[str, str]:
async def _pick_heartbeat_target() -> tuple[str, str]:
"""Pick a routable channel/chat target for heartbeat-triggered messages."""
sidebar_state = read_webui_sidebar_state()
sidebar_state = await asyncio.to_thread(read_webui_sidebar_state)
unified_metadata = None
if config.agents.defaults.unified_session:
record = session_manager.read_session_metadata(UNIFIED_SESSION_KEY)
record = await session_manager.state.read_metadata(UNIFIED_SESSION_KEY)
if isinstance(record, dict) and isinstance(record.get("metadata"), dict):
unified_metadata = record["metadata"]
return _pick_heartbeat_target_from_sessions(
enabled_channels=channels.enabled_channels,
sessions=session_manager.list_sessions(),
sessions=await session_manager.state.list_sessions(),
archived_keys=sidebar_state.get("archived_keys", []),
unified_session_metadata=unified_metadata,
)
@@ -930,6 +956,7 @@ def _run_gateway(
console.print,
)
try:
await agent.subagents.recover_interrupted()
await cron.start()
# Re-read once on first admission to close the watcher subscription window.
agent.runtime_resolver.invalidate()
@@ -1039,12 +1066,6 @@ def _run_gateway(
runtime_tasks,
)
await bus.drain()
# Flush all cached sessions to durable storage before exit.
# This prevents data loss on filesystems with write-back
# caching (rclone VFS, NFS, FUSE mounts, etc.).
flushed = agent.sessions.flush_all()
if flushed:
logger.info("Shutdown: flushed {} session(s) to disk", flushed)
finally:
restore_shutdown_handlers()
@@ -1052,7 +1073,6 @@ def _run_gateway(
gateway_runtime.foreground_instance(gateway_start_options),
webui_turn_coordinator.connected(),
):
agent.subagents.recover_interrupted()
if health_server_enabled:
gateway_runtime.publish_health_host(config.gateway.host)
asyncio.run(run())
+28 -31
View File
@@ -18,6 +18,7 @@ from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage, Outbound
from nanobot.command.router import CommandContext, CommandRouter, normalize_command_text
from nanobot.providers.base import LLMUsage
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
from nanobot.utils.cancellation import shield_and_drain
from nanobot.utils.helpers import build_status_content
from nanobot.utils.restart import set_restart_notice_to_env
from nanobot.utils.workspace_prompts import initialize_workspace_prompt
@@ -267,8 +268,8 @@ async def cmd_restart(ctx: CommandContext) -> OutboundMessage:
async def cmd_status(ctx: CommandContext) -> OutboundMessage:
"""Build an outbound status message for a session."""
loop = ctx.loop
session = ctx.session or loop.sessions.get_or_create(ctx.key)
runtime = ctx.runtime or loop.runtime_for_session(session)
session = ctx.session or await loop.sessions.state.get(ctx.key)
runtime = ctx.runtime or await loop.runtime_for_session(session)
ctx_est = 0
with suppress(Exception):
ctx_est, _ = loop.consolidator.estimate_session_prompt_tokens(
@@ -316,29 +317,30 @@ async def cmd_new(ctx: CommandContext) -> OutboundMessage:
loop = ctx.loop
await loop._cancel_active_tasks(ctx.key) # pyright: ignore[reportPrivateUsage]
loop.discard_session_file_state(ctx.key)
session = ctx.session or loop.sessions.get_or_create(ctx.key)
session = ctx.session or await loop.sessions.state.get(ctx.key)
snapshot = list(session.messages)
archive_snapshot = None
runtime = None
if session.last_archived < len(snapshot):
runtime = ctx.runtime or loop.runtime_for_session(session)
runtime = ctx.runtime or await loop.runtime_for_session(session)
archive_snapshot = replace(
session,
messages=snapshot,
metadata=dict(session.metadata),
provider_state=None,
)
session.clear()
loop.sessions.save(session)
loop.sessions.invalidate(session.key)
if archive_snapshot is not None and runtime is not None:
loop.schedule_background(
loop.consolidator.archive_session( # pyright: ignore[reportUnknownMemberType]
archive_snapshot,
archive_end=len(snapshot),
runtime=runtime,
async def reset_and_schedule_archive() -> None:
await loop.sessions.state.reset(session.key)
if archive_snapshot is not None and runtime is not None:
loop.schedule_background(
loop.consolidator.archive_session( # pyright: ignore[reportUnknownMemberType]
archive_snapshot,
archive_end=len(snapshot),
runtime=runtime,
)
)
)
await shield_and_drain(reset_and_schedule_archive())
return OutboundMessage(
channel=ctx.msg.channel, chat_id=ctx.msg.chat_id,
content="New session started.",
@@ -349,12 +351,12 @@ async def cmd_new(ctx: CommandContext) -> OutboundMessage:
async def cmd_compact(ctx: CommandContext) -> None:
"""Compact the current session without resetting the conversation."""
loop = ctx.loop
session = ctx.session or loop.sessions.get_or_create(ctx.key)
runtime = ctx.runtime or loop.runtime_for_session(session)
session = ctx.session or await loop.sessions.state.get(ctx.key)
runtime = ctx.runtime or await loop.runtime_for_session(session)
delivery = loop.turn_delivery_factory.create(ctx.msg, ctx.key)
try:
summary = await loop.consolidator.compact_idle_session(
await loop.consolidator.compact_idle_session(
ctx.key,
runtime=runtime,
events=delivery.events,
@@ -364,10 +366,6 @@ async def cmd_compact(ctx: CommandContext) -> None:
logger.exception("Manual context compaction failed for {}", ctx.key)
return
if summary:
refreshed = loop.sessions.get_or_create(ctx.key)
refreshed.provider_state = None
loop.sessions.save(refreshed)
def _format_preset_names(names: list[str]) -> str:
@@ -384,10 +382,10 @@ def _command_error_message(exc: Exception) -> str:
return str(exc.args[0]) if isinstance(exc, KeyError) and exc.args else str(exc)
def _model_command_status(loop: AgentLoop, session: Session) -> str:
async def _model_command_status(loop: AgentLoop, session: Session) -> str:
names = _model_preset_names(loop)
try:
runtime = loop.runtime_for_session(session, recover_removed=False)
runtime = await loop.runtime_for_session(session, recover_removed=False)
except (KeyError, ValueError) as exc:
return "\n".join([
"## Model",
@@ -411,17 +409,17 @@ async def cmd_model(ctx: CommandContext) -> OutboundMessage:
metadata = {**dict(ctx.msg.metadata or {}), "render_as": "text"}
if not args:
session = ctx.session or loop.sessions.get_or_create(ctx.key)
session = ctx.session or await loop.sessions.state.get(ctx.key)
return OutboundMessage(
channel=ctx.msg.channel,
chat_id=ctx.msg.chat_id,
content=_model_command_status(loop, session),
content=await _model_command_status(loop, session),
metadata=metadata,
)
name = args
try:
runtime = loop.set_session_model_preset(ctx.key, name)
runtime = await loop.set_session_model_preset(ctx.key, name)
except (KeyError, ValueError) as exc:
names = _model_preset_names(loop)
return OutboundMessage(
@@ -465,7 +463,6 @@ async def cmd_dream(ctx: CommandContext) -> OutboundMessage:
dream_session_key = MemoryStore.dream_session_key
build_dream_commit_message = MemoryStore.build_dream_commit_message
prune_dream_sessions = MemoryStore.prune_dream_sessions
store = loop.context.memory
content = ""
@@ -519,7 +516,7 @@ async def cmd_dream(ctx: CommandContext) -> OutboundMessage:
if sha:
content += f" (commit {sha})"
store.compact_history()
prune_dream_sessions(loop.sessions)
await loop.sessions.state.prune_dream_sessions()
await loop.bus.publish_outbound(OutboundMessage(
channel=msg.channel, chat_id=msg.chat_id, content=content,
))
@@ -882,7 +879,7 @@ async def cmd_history(ctx: CommandContext) -> OutboundMessage:
metadata=dict(ctx.msg.metadata or {}),
)
session = ctx.session or ctx.loop.sessions.get_or_create(ctx.key)
session = ctx.session or await ctx.loop.sessions.state.get(ctx.key)
history = session.get_history(max_messages=0, include_runtime_context=False)
visible = [_format_history_message(m) for m in history]
visible = [m for m in visible if m is not None]
@@ -921,9 +918,9 @@ async def cmd_goal(ctx: CommandContext) -> InboundMessage | OutboundMessage:
metadata={**dict(ctx.msg.metadata or {}), "render_as": "text"},
)
session = ctx.session or ctx.loop.sessions.get_or_create(ctx.key)
session = ctx.session or await ctx.loop.sessions.state.get(ctx.key)
session.add_message("user", ctx.msg.content, _command=True, media=list(ctx.msg.media))
ctx.loop.sessions.save(session)
await ctx.loop.sessions.state.prepare_input(session)
return replace(
ctx.msg,
content=goal,
+49 -110
View File
@@ -12,7 +12,6 @@ from nanobot.runtime_context import RUNTIME_CONTEXT_HISTORY_META, RuntimeContext
from nanobot.sdk.types import (
SessionInfo,
SessionSnapshot,
snapshot_from_payload,
snapshot_from_session,
)
@@ -21,138 +20,76 @@ if TYPE_CHECKING:
class SessionClient:
"""Session management helpers exposed through ``bot.sessions``."""
_RESERVED_MESSAGE_KEYS = {"role", "content", RUNTIME_CONTEXT_HISTORY_META}
_VALID_ROLES = {"user", "assistant", "tool", "system"}
"""Asynchronous operations over committed session state."""
def __init__(self, loop: AgentLoop) -> None:
self._loop = loop
self._state = loop.sessions.state
async def ingest(
self,
session_key: str,
messages: Iterable[Mapping[str, Any]],
*,
metadata: Mapping[str, Any] | None = None,
source: str | None = None,
save: bool = True,
self, session_key: str, messages: Iterable[Mapping[str, Any]], *,
metadata: Mapping[str, Any] | None = None, source: str | None = None,
) -> SessionSnapshot:
"""Import an existing transcript without running the model."""
prepared_metadata = deepcopy(dict(metadata)) if metadata else {}
prepared: list[tuple[str, Any, dict[str, Any]]] = []
"""Validate and durably import a transcript as one operation."""
prepared: list[dict[str, Any]] = []
for raw in messages:
if "role" not in raw:
raise ValueError("ingested messages must include a role")
if "content" not in raw:
raise ValueError("ingested messages must include content")
role = str(raw["role"]).strip()
if role not in self._VALID_ROLES:
raise ValueError(f"unsupported message role: {role!r}")
extra = {
key: deepcopy(value)
for key, value in raw.items()
if key not in self._RESERVED_MESSAGE_KEYS
if "role" not in raw or "content" not in raw:
raise ValueError("ingested messages must include role and content")
message = {
key: deepcopy(value) for key, value in raw.items()
if key != RUNTIME_CONTEXT_HISTORY_META
}
if source is not None and "source" not in extra:
extra["source"] = source
prepared.append((role, deepcopy(raw["content"]), extra))
session = self._loop.sessions.get_or_create(session_key)
session.metadata.update(prepared_metadata)
for role, content, extra in prepared:
session.add_message(role, content, **extra)
if save:
self._loop.sessions.save(session)
message["role"] = str(raw["role"]).strip()
if source is not None:
message.setdefault("source", source)
prepared.append(message)
session = await self._state.import_messages(session_key, prepared, metadata=metadata)
return snapshot_from_session(session)
def get(self, session_key: str) -> SessionSnapshot | None:
"""Return a display-safe snapshot without creating a new session on disk."""
cached = self._loop.sessions.get_cached(session_key)
if cached is not None:
return snapshot_from_session(cached)
payload = self._loop.sessions.read_session_file(session_key)
if payload is None:
return None
return snapshot_from_payload(payload)
async def get(self, session_key: str) -> SessionSnapshot | None:
"""Return a detached display-safe view of committed state."""
session = await self._state.read(session_key)
return snapshot_from_session(session) if session is not None else None
def list(self) -> list[SessionInfo]:
"""List persisted sessions."""
async def list(self) -> list[SessionInfo]:
return [
SessionInfo(
key=str(row.get("key") or ""),
created_at=row.get("created_at"),
updated_at=row.get("updated_at"),
title=str(row.get("title") or ""),
preview=str(row.get("preview") or ""),
created_at=row.get("created_at"), updated_at=row.get("updated_at"),
title=str(row.get("title") or ""), preview=str(row.get("preview") or ""),
path=row.get("path"),
)
for row in self._loop.sessions.list_sessions()
for row in await self._state.list_sessions()
]
def export(self, session_key: str) -> SessionSnapshot | None:
"""Return a trusted full snapshot, including model-only runtime context."""
cached = self._loop.sessions.get_cached(session_key)
if cached is not None:
return snapshot_from_session(cached, include_runtime_context=True)
payload = self._loop.sessions.read_session_file(session_key)
if payload is None:
return None
return snapshot_from_payload(payload, include_runtime_context=True)
async def export(self, session_key: str) -> SessionSnapshot | None:
"""Return a trusted detached snapshot including model-only context."""
session = await self._state.read(session_key)
return (
snapshot_from_session(session, include_runtime_context=True)
if session is not None else None
)
async def restore(
self,
snapshot: SessionSnapshot,
*,
session_key: str | None = None,
save: bool = True,
self, snapshot: SessionSnapshot, *, session_key: str | None = None,
) -> SessionSnapshot:
"""Restore a trusted snapshot into an empty session."""
"""Atomically restore a trusted snapshot into an empty session."""
key = session_key or snapshot.key
if not key:
raise ValueError("restored snapshots must include a session key")
session = self._loop.sessions.get_or_create(key)
if session.messages:
raise ValueError(f"restore target session is not empty: {key}")
prepared: list[tuple[str, Any, dict[str, Any]]] = []
for raw in snapshot.messages:
if "role" not in raw or "content" not in raw:
raise ValueError("restored messages must include role and content")
role = str(raw["role"]).strip()
if role not in self._VALID_ROLES:
raise ValueError(f"unsupported message role: {role!r}")
extra = {
field: deepcopy(value)
for field, value in raw.items()
if field not in {"role", "content"}
}
prepared.append((role, deepcopy(raw["content"]), extra))
session.metadata.update(deepcopy(snapshot.metadata))
for role, content, extra in prepared:
session.add_message(role, content, **extra)
if save:
self._loop.sessions.save(session)
session = await self._state.import_messages(
key, snapshot.messages, metadata=snapshot.metadata, require_empty=True,
)
return snapshot_from_session(session)
def clear(self, session_key: str) -> SessionSnapshot:
"""Clear one session and persist the empty session."""
async def clear(self, session_key: str) -> SessionSnapshot:
"""Reset state and invalidate results from an older execution."""
await self._state.reset(session_key)
self._loop.discard_session_file_state(session_key)
session = self._loop.sessions.get_or_create(session_key)
session.clear()
self._loop.sessions.save(session)
return snapshot_from_session(session)
return snapshot_from_session(await self._state.get(session_key))
def delete(self, session_key: str) -> bool:
"""Delete one session from disk and cache."""
return self._loop.sessions.delete_session(session_key)
def flush(self) -> int:
"""Flush cached sessions to durable storage."""
return self._loop.sessions.flush_all()
async def delete(self, session_key: str) -> bool:
return await self._state.delete(session_key)
class MemoryClient:
@@ -214,19 +151,21 @@ class RuntimeClient:
async def compact_session(self, session_key: str) -> SessionSnapshot:
"""Summarize one session and exclude its archived messages from replay."""
async with self._loop._get_session_lock(session_key): # pyright: ignore[reportPrivateUsage]
session = self._loop.sessions.get_or_create(session_key)
runtime = self._loop.runtime_for_session(session)
session = await self._loop.sessions.state.get(session_key)
runtime = await self._loop.runtime_for_session(session)
await self._loop.consolidator.compact_idle_session(
session_key,
runtime=runtime,
)
return snapshot_from_session(self._loop.sessions.get_or_create(session_key))
return snapshot_from_session(
await self._loop.sessions.state.get(session_key)
)
async def compact_idle_session(self, session_key: str, *, max_suffix: int = 0) -> str | None:
"""Return a replacement summary; legacy ``max_suffix`` no longer retains history."""
async with self._loop._get_session_lock(session_key): # pyright: ignore[reportPrivateUsage]
session = self._loop.sessions.get_or_create(session_key)
runtime = self._loop.runtime_for_session(session)
session = await self._loop.sessions.state.get(session_key)
runtime = await self._loop.runtime_for_session(session)
return await self._loop.consolidator.compact_idle_session(
session_key,
runtime=runtime,
+13 -2
View File
@@ -163,6 +163,17 @@ def workspace_sandbox_status(
"""Return how workspace restriction is enforced in the current host."""
workspace_root = str(Path(workspace).expanduser().resolve(strict=False))
return _workspace_sandbox_status(
restrict_to_workspace=restrict_to_workspace,
workspace_root=workspace_root,
environ=environ,
)
def _workspace_sandbox_status(
*, restrict_to_workspace: bool, workspace_root: str,
environ: dict[str, str] | None = None,
) -> WorkspaceSandboxStatus:
provider = _env_system_provider(environ)
if not restrict_to_workspace:
return WorkspaceSandboxStatus(
@@ -215,9 +226,9 @@ def build_workspace_scope(
project_path=root,
access_mode=mode,
restrict_to_workspace=restrict,
sandbox_status=workspace_sandbox_status(
sandbox_status=_workspace_sandbox_status(
restrict_to_workspace=restrict,
workspace=root,
workspace_root=str(root),
),
source_channel=source_channel,
)
+290
View File
@@ -0,0 +1,290 @@
"""One-time JSONL import, introduced in 0.3.6 and removed in 0.5.0.
0.4.x is the final migration release line. Older installations must pass through
that line before upgrading to 0.5.0. Workspace sources move to private backups
after the import commits; failed imports leave their source files unchanged.
"""
from __future__ import annotations
import hashlib
import json
import os
import secrets
import stat
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any, TypedDict, cast
from loguru import logger
from nanobot.providers.base import ProviderConversationState
from nanobot.session.location import SessionLocation
from nanobot.session.manager import Session
if TYPE_CHECKING:
from nanobot.session.sqlite_store import SqliteSessionStore
INTRODUCED_VERSION = "0.3.6"
LAST_SUPPORTED_RELEASE_LINE = "0.4.x"
SUNSET_VERSION = "0.5.0"
WORKSPACE_BACKUP_DIR = "jsonl-backup"
_WORKSPACE_SOURCES_KEY = "jsonl_workspace_sources"
class _WorkspaceSource(TypedDict):
name: str
digest: str
def _file_identity(value: os.stat_result) -> tuple[int, int, int, int]:
return value.st_dev, value.st_ino, value.st_size, value.st_mtime_ns
@dataclass(frozen=True)
class _LegacyFile:
path: Path
content: bytes
stat: os.stat_result
@property
def digest(self) -> str:
return hashlib.sha256(self.content).hexdigest()
def _read_file(path: Path) -> _LegacyFile:
if not stat.S_ISREG(path.lstat().st_mode):
raise ValueError(f"JSONL migration requires a regular file: {path}")
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
with os.fdopen(os.open(path, flags), "rb") as handle:
before = os.fstat(handle.fileno())
if not stat.S_ISREG(before.st_mode):
raise ValueError(f"JSONL migration requires a regular file: {path}")
content = handle.read()
after = os.fstat(handle.fileno())
if _file_identity(before) != _file_identity(after):
raise ValueError(f"JSONL migration source changed while reading: {path}")
return _LegacyFile(path, content, after)
def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
value: dict[str, Any] = {}
for key, item in pairs:
if key in value:
raise ValueError(f"duplicate JSON key: {key!r}")
value[key] = item
return value
def _record(line: str) -> dict[str, Any]:
value: object = json.loads(line, object_pairs_hook=_unique_object)
if not isinstance(value, dict):
raise ValueError("JSONL records must be objects")
return cast(dict[str, Any], value)
def read_jsonl(path: Path) -> tuple[Session, list[_LegacyFile]]:
"""Read a complete legacy session, failing without modifying malformed input."""
source = _read_file(path)
files = [source]
header: dict[str, Any] | None = None
messages: list[dict[str, Any]] = []
provider: ProviderConversationState | None = None
provider_seen = False
for line in source.content.decode("utf-8").splitlines():
if not line.strip():
continue
item = _record(line)
if item.get("_type") == "metadata":
if header is not None:
raise ValueError(f"multiple session headers: {path}")
header = item
elif item.get("_type") == "provider_state":
if provider_seen:
raise ValueError(f"multiple provider state records: {path}")
provider_seen = True
provider = ProviderConversationState.from_private_record(item.get("state"))
if provider is None:
raise ValueError(f"invalid private provider state: {path}")
else:
if not isinstance(item.get("role"), str):
raise ValueError(f"invalid session message: {path}")
messages.append(item)
if header is None:
raise ValueError(f"missing session header: {path}")
key = header.get("key") or SessionLocation.session_key_from_path(path)
if not isinstance(key, str) or not key:
raise ValueError(f"cannot determine session key: {path}")
metadata: object = header.get("metadata")
if metadata is None:
metadata = {}
if not isinstance(metadata, dict):
raise ValueError(f"invalid session metadata: {path}")
fallback = datetime.fromtimestamp(source.stat.st_mtime).isoformat()
session = Session(
key=key, messages=messages, metadata=cast(dict[str, Any], metadata),
created_at=datetime.fromisoformat(header.get("created_at") or fallback),
updated_at=datetime.fromisoformat(header.get("updated_at") or fallback),
last_consolidated=header.get("last_archived", header.get("last_consolidated", 0)),
provider_state=provider,
)
checkpoint_path = path.with_suffix(".checkpoint.json")
if checkpoint_path.exists() or checkpoint_path.is_symlink():
checkpoint_source = _read_file(checkpoint_path)
files.append(checkpoint_source)
checkpoint = _record(checkpoint_source.content.decode("utf-8"))
if (
checkpoint_source.stat.st_mtime_ns >= source.stat.st_mtime_ns
and checkpoint.get("version") == 1
and checkpoint.get("session_key") == key
and checkpoint.get("base_updated_at") == session.updated_at.isoformat()
and checkpoint.get("base_message_count") == len(messages)
):
if not isinstance(checkpoint.get("checkpoint"), dict):
raise ValueError(f"invalid checkpoint: {checkpoint_path}")
session.metadata["runtime_checkpoint"] = checkpoint["checkpoint"]
raw_provider = checkpoint.get("provider_state")
session.provider_state = ProviderConversationState.from_private_record(raw_provider)
if raw_provider is not None and session.provider_state is None:
raise ValueError(f"invalid checkpoint provider state: {checkpoint_path}")
return session, files
def migrate_jsonl(store: SqliteSessionStore, workspace: Path) -> int:
"""Import atomically, then let the caller commit the durable completion marker.
A malformed or conflicting source aborts the whole import. The committed
workspace-source manifest lets startup finish isolation after a crash.
"""
imported: dict[str, tuple[Path, tuple[str, ...]]] = {}
workspace_sources: list[_WorkspaceSource] = []
workspace_directory = workspace / "sessions"
for directory in (store.path.parent, workspace_directory):
if directory.is_symlink():
raise ValueError(f"migration source must not be a symlink: {directory}")
for path in sorted(directory.glob("*.jsonl")):
try:
session, files = read_jsonl(path)
digests = tuple(source.digest for source in files)
prior = imported.get(session.key)
if prior is not None:
prior_path, prior_digests = prior
if prior_digests != digests or store.load(session.key) != session:
raise ValueError(f"duplicate JSONL session key: {prior_path} and {path}")
else:
if store.load(session.key) is not None:
raise ValueError(f"session already exists in SQLite: {session.key}")
store.save(session)
imported[session.key] = path, digests
if directory == workspace_directory:
workspace_sources.extend(
{"name": source.path.name, "digest": source.digest} for source in files
)
except Exception as exc:
raise RuntimeError(
f"JSONL migration failed for {path}; source files are unchanged. "
"Resolve the invalid or conflicting file and restart."
) from exc
if workspace_sources:
with store.transaction() as db:
db.execute("INSERT INTO storage_meta (key, value) VALUES (?, ?)", (
_WORKSPACE_SOURCES_KEY, json.dumps(workspace_sources),
))
if imported:
logger.info("Imported {} JSONL sessions into {}", len(imported), store.path)
return len(imported)
def _workspace_sources(raw: str) -> list[_WorkspaceSource]:
value: object = json.loads(raw)
if not isinstance(value, list):
raise ValueError("workspace migration manifest must be a list")
sources: list[_WorkspaceSource] = []
for item in cast(list[object], value):
if not isinstance(item, dict):
raise ValueError("workspace migration source must be an object")
record = cast(dict[str, object], item)
name, digest = record.get("name"), record.get("digest")
if (
not isinstance(name, str) or Path(name).name != name
or not name.endswith((".jsonl", ".checkpoint.json"))
or not isinstance(digest, str) or len(digest) != 64
or any(char not in "0123456789abcdef" for char in digest)
):
raise ValueError("invalid workspace migration source")
sources.append({"name": name, "digest": digest})
return sources
def _write_backup(path: Path, source: _LegacyFile) -> None:
temporary = path.with_name(f".{path.name}.{secrets.token_hex(8)}.tmp")
try:
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
with os.fdopen(os.open(temporary, flags, 0o600), "wb") as handle:
handle.write(source.content)
handle.flush()
os.utime(temporary, ns=(source.stat.st_atime_ns, source.stat.st_mtime_ns))
os.fsync(handle.fileno())
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
def finish_workspace_migration(store: SqliteSessionStore, workspace: Path) -> None:
"""Durably back up every workspace source before removing any of them.
The import and its manifest commit together. Cleanup holds the startup write
lock and clears the manifest only after both backup and removal are durable.
"""
source_directory = workspace / "sessions"
backup_directory = store.path.parent / WORKSPACE_BACKUP_DIR
with store.transaction() as db:
pending = db.execute(
"SELECT value FROM storage_meta WHERE key=?", (_WORKSPACE_SOURCES_KEY,),
).fetchone()
if pending is None:
return
try:
sources = _workspace_sources(pending[0])
if source_directory.is_symlink() or backup_directory.is_symlink():
raise ValueError("workspace migration directories must not be symlinks")
backup_directory.mkdir(mode=0o700, exist_ok=True)
SessionLocation.fsync_directory(backup_directory.parent)
prepared: list[tuple[Path, os.stat_result]] = []
for record in sources:
source_path = source_directory / record["name"]
backup_path = backup_directory / record["name"]
source: _LegacyFile | None = None
try:
source = _read_file(source_path)
except FileNotFoundError:
pass
if source is not None:
if source.digest != record["digest"]:
raise ValueError(f"workspace migration source changed: {source_path}")
prepared.append((source_path, source.stat))
try:
backup = _read_file(backup_path)
except FileNotFoundError:
if source is None:
raise ValueError(f"workspace migration source and backup are missing: {source_path}") from None
_write_backup(backup_path, source)
else:
if backup.digest != record["digest"]:
raise ValueError(f"workspace migration backup differs from its source: {backup_path}")
SessionLocation.fsync_directory(backup_directory)
for path, expected in prepared:
actual = path.lstat()
if not stat.S_ISREG(actual.st_mode) or _file_identity(actual) != _file_identity(expected):
raise ValueError(f"workspace migration source changed: {path}")
for path, _expected in prepared:
path.unlink()
if source_directory.exists():
SessionLocation.fsync_directory(source_directory)
db.execute("DELETE FROM storage_meta WHERE key=?", (_WORKSPACE_SOURCES_KEY,))
except Exception as exc:
raise RuntimeError(
f"Could not move legacy sessions out of {source_directory}; "
f"backups are in {backup_directory}. Resolve the file error and restart."
) from exc
+252
View File
@@ -0,0 +1,252 @@
"""Stable workspace identity and private session storage locations."""
from __future__ import annotations
import base64
import errno
import os
import re
import secrets
from contextlib import suppress
from pathlib import Path
from filelock import FileLock
from nanobot.config.paths import get_runtime_subdir
from nanobot.utils.helpers import (
ensure_dir,
safe_filename,
)
_WORKSPACE_STATE_DIR = ".nanobot"
_WORKSPACE_ID_FILE = "workspace-id"
_WORKSPACE_ID_RE = re.compile(r"^[0-9a-f]{32}$")
_SESSION_MIGRATION_LOCK_TIMEOUT_SECONDS = 30
class SessionLocation:
def __init__(self, workspace: Path, *, sessions_root: Path | None = None):
canonical_workspace = Path(workspace).expanduser().resolve(strict=False)
ensure_dir(canonical_workspace)
root = (
Path(sessions_root).expanduser().resolve(strict=False)
if sessions_root is not None
else get_runtime_subdir("sessions").resolve(strict=False)
)
if root == canonical_workspace or root.is_relative_to(canonical_workspace):
raise RuntimeError(
"session storage must be outside the agent workspace; "
"move --config outside --workspace or choose a nested workspace directory"
)
ensure_dir(root)
with suppress(OSError):
os.chmod(root, 0o700)
self.workspace = canonical_workspace
self._migration_lock = FileLock(
str(root / ".workspace-migration.lock"),
timeout=_SESSION_MIGRATION_LOCK_TIMEOUT_SECONDS,
)
with self._migration_lock:
workspace_id = self._load_or_create_workspace_id(canonical_workspace, root)
workspace_id = self._claim_workspace_namespace(
root,
canonical_workspace,
workspace_id,
)
self.sessions_dir = ensure_dir(root / workspace_id)
@staticmethod
def fsync_directory(path: Path) -> None:
"""Persist storage directory entries where directory fsync is supported."""
with suppress(PermissionError, NotImplementedError):
fd = os.open(path, os.O_RDONLY)
try:
os.fsync(fd)
except OSError as exc:
if exc.errno != errno.EINVAL:
raise
finally:
os.close(fd)
@classmethod
def _write_text_atomic(cls, path: Path, content: str, *, mode: int = 0o600) -> None:
tmp = path.with_name(f".{path.name}.{secrets.token_hex(8)}.tmp")
try:
with open(tmp, "x", encoding="utf-8") as handle:
os.chmod(tmp, mode)
handle.write(content)
handle.flush()
os.fsync(handle.fileno())
os.replace(tmp, path)
cls.fsync_directory(path.parent)
finally:
tmp.unlink(missing_ok=True)
@classmethod
def _read_workspace_id(cls, marker: Path) -> str:
if marker.is_symlink():
raise RuntimeError(f"workspace identity marker must not be a symlink: {marker}")
value = marker.read_text(encoding="utf-8").strip()
if not _WORKSPACE_ID_RE.fullmatch(value):
raise RuntimeError(
f"workspace identity marker is invalid: {marker}; "
"restore its original 32-character identifier before starting nanobot"
)
return value
@staticmethod
def _workspace_id_path(workspace: Path) -> Path:
state_dir = workspace / _WORKSPACE_STATE_DIR
if state_dir.is_symlink():
raise RuntimeError(f"workspace state directory must not be a symlink: {state_dir}")
ensure_dir(state_dir)
return state_dir / _WORKSPACE_ID_FILE
@classmethod
def _find_workspace_namespace(cls, workspace: Path, root: Path) -> str | None:
"""Recover an identity marker removed by cleanup at the same workspace path."""
matches: list[str] = []
for sessions_dir in root.iterdir():
if (
not _WORKSPACE_ID_RE.fullmatch(sessions_dir.name)
or sessions_dir.is_symlink()
or not sessions_dir.is_dir()
):
continue
marker = sessions_dir / ".workspace"
if marker.is_symlink() or not marker.is_file():
continue
try:
recorded = Path(marker.read_text(encoding="utf-8").strip()).expanduser()
recorded = recorded.resolve(strict=False)
same_workspace = recorded == workspace or (
recorded.exists() and recorded.samefile(workspace)
)
except (OSError, UnicodeError, ValueError):
continue
if same_workspace:
matches.append(sessions_dir.name)
if len(matches) > 1:
raise RuntimeError(
f"multiple session namespaces claim workspace {workspace}; "
"remove the stale namespace marker before starting nanobot"
)
return matches[0] if matches else None
@classmethod
def _load_or_create_workspace_id(cls, workspace: Path, root: Path) -> str:
marker = cls._workspace_id_path(workspace)
if marker.exists() or marker.is_symlink():
return cls._read_workspace_id(marker)
recovered = cls._find_workspace_namespace(workspace, root)
if recovered is not None:
cls._write_text_atomic(marker, f"{recovered}\n")
return recovered
workspace_id = secrets.token_hex(16)
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
flags |= getattr(os, "O_NOFOLLOW", 0)
try:
fd = os.open(marker, flags, 0o600)
except FileExistsError:
return cls._read_workspace_id(marker)
try:
payload = f"{workspace_id}\n".encode("ascii")
view = memoryview(payload)
while view:
written = os.write(fd, view)
view = view[written:]
os.fsync(fd)
except BaseException:
with suppress(OSError):
marker.unlink()
raise
finally:
os.close(fd)
cls.fsync_directory(marker.parent)
return workspace_id
@classmethod
def _replace_workspace_id(cls, workspace: Path, workspace_id: str) -> None:
cls._write_text_atomic(cls._workspace_id_path(workspace), f"{workspace_id}\n")
@classmethod
def _write_workspace_marker(cls, sessions_dir: Path, workspace: Path) -> None:
cls._write_text_atomic(sessions_dir / ".workspace", f"{workspace}\n")
@classmethod
def _claim_workspace_namespace(
cls,
root: Path,
workspace: Path,
workspace_id: str,
) -> str:
"""Bind a stable workspace ID, rotating copied live workspaces apart."""
for _attempt in range(3):
sessions_dir = root / workspace_id
marker = sessions_dir / ".workspace"
if sessions_dir.is_symlink():
raise RuntimeError(f"session namespace must not be a symlink: {sessions_dir}")
if not sessions_dir.exists():
ensure_dir(sessions_dir)
cls._write_workspace_marker(sessions_dir, workspace)
return workspace_id
if marker.is_symlink():
raise RuntimeError(f"session workspace marker must not be a symlink: {marker}")
if not marker.exists():
if any(sessions_dir.iterdir()):
raise RuntimeError(
f"session namespace has data but no workspace marker: {sessions_dir}"
)
cls._write_workspace_marker(sessions_dir, workspace)
return workspace_id
recorded_text = marker.read_text(encoding="utf-8").strip()
if not recorded_text:
raise RuntimeError(f"session workspace marker is empty: {marker}")
recorded = Path(recorded_text).expanduser().resolve(strict=False)
if recorded == workspace:
return workspace_id
try:
same_workspace = recorded.exists() and recorded.samefile(workspace)
except OSError:
same_workspace = False
if same_workspace:
cls._write_workspace_marker(sessions_dir, workspace)
return workspace_id
if not recorded.exists():
# The identity marker travelled with a renamed or moved workspace.
cls._write_workspace_marker(sessions_dir, workspace)
return workspace_id
# Both paths exist and are different: this is a copy, not a move.
workspace_id = secrets.token_hex(16)
cls._replace_workspace_id(workspace, workspace_id)
raise RuntimeError(f"could not allocate an isolated session namespace for {workspace}")
@staticmethod
def safe_key(key: str) -> str:
return safe_filename(key.replace(":", "_"))
@staticmethod
def storage_key(key: str) -> str:
return base64.urlsafe_b64encode(key.encode()).decode().rstrip("=")
@staticmethod
def decode_storage_key(stem: str) -> str | None:
try:
padding = 4 - len(stem) % 4
if padding != 4:
stem += "=" * padding
return base64.urlsafe_b64decode(stem).decode("utf-8")
except (ValueError, TypeError, AttributeError, KeyError):
return None
@classmethod
def session_key_from_path(cls, path: Path) -> str | None:
key = cls.decode_storage_key(path.stem)
if key is None or cls.storage_key(key) != path.stem:
return None
return key
+180 -1431
View File
File diff suppressed because it is too large. Load diff
+103 -49
View File
@@ -10,6 +10,7 @@ from dataclasses import dataclass
from typing import Any, TypedDict, cast
from nanobot.session.manager import SessionManager
from nanobot.session.types import SessionTypes
SESSION_HANDLE_METADATA_KEY = "session_handle"
@@ -128,7 +129,7 @@ def _candidate_indexes(syllable_count: int):
yield (start + offset * step) % size
def _allocate_name(used: set[str]) -> str:
def allocate_session_handle_name(used: set[str]) -> str:
for syllable_count in _SYLLABLE_COUNTS:
for index in _candidate_indexes(syllable_count):
parts = _name_parts_at(syllable_count, index)
@@ -143,6 +144,51 @@ def _allocate_name(used: set[str]) -> str:
return name
# Backward-compatible alias for callers that used the original private helper.
_allocate_name = allocate_session_handle_name
def allocate_session_handles(
rows: list[dict[str, Any]], types: SessionTypes,
) -> tuple[dict[str, str], dict[str, str]]:
"""Return valid existing names and metadata updates for missing handles."""
used: set[str] = set()
names: dict[str, str] = {}
pending: list[str] = []
for row in sorted(
rows,
key=lambda item: (
str(item.get("created_at", "")),
str(item.get("key", "")),
),
):
raw_key = row.get("key")
if not isinstance(raw_key, str):
continue
raw_metadata = row.get("metadata")
metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
if not types.needs_handle(metadata):
continue
raw_name = metadata.get(SESSION_HANDLE_METADATA_KEY)
try:
name = normalize_session_handle(raw_name) if isinstance(raw_name, str) else ""
except ValueError:
name = ""
if not name or name in used:
pending.append(raw_key)
continue
names[raw_key] = name
used.add(name)
updates: dict[str, str] = {}
for key in pending:
name = allocate_session_handle_name(used)
names[key] = name
updates[key] = name
used.add(name)
return names, updates
class SessionHandleResolver:
"""Allocate and resolve handles stored in canonical session metadata."""
@@ -150,71 +196,65 @@ class SessionHandleResolver:
self._sessions = sessions
def _ensure_all(self) -> dict[str, SessionHandle]:
with self._sessions.locked_session_files():
rows = sorted(
self._sessions.list_sessions(),
key=lambda row: (
str(row.get("created_at", "")),
str(row.get("key", "")),
),
)
used: set[str] = set()
names: dict[str, str] = {}
pending: list[str] = []
for row in rows:
raw_key: Any = row.get("key")
if not isinstance(raw_key, str):
continue
payload = self._sessions.read_session_metadata(raw_key)
raw_metadata = payload.get("metadata") if payload is not None else None
metadata = (
cast(dict[str, Any], raw_metadata)
if isinstance(raw_metadata, dict)
else {}
)
if not self._sessions.types.needs_handle(metadata):
continue
raw_name = metadata.get(SESSION_HANDLE_METADATA_KEY)
try:
name = normalize_session_handle(raw_name) if isinstance(raw_name, str) else ""
except ValueError:
name = ""
if not name or name in used:
pending.append(raw_key)
continue
names[raw_key] = name
used.add(name)
names = self._sessions.ensure_session_handles_offline()
return {
key: session_handle_for_name(key, name)
for key, name in names.items()
}
for key in pending:
name = _allocate_name(used)
if not self._sessions.update_session_metadata(
key,
{SESSION_HANDLE_METADATA_KEY: name},
fsync=True,
):
continue
names[key] = name
used.add(name)
async def _ensure_all_async(self) -> dict[str, SessionHandle]:
names = await self._sessions.state.ensure_session_handles()
return {
key: session_handle_for_name(key, name)
for key, name in names.items()
}
return {
key: session_handle_for_name(key, name)
for key, name in names.items()
}
def handles_from_metadata(
self, rows: list[dict[str, Any]],
) -> dict[str, SessionHandle] | None:
"""Resolve a detached snapshot, or request allocation through the owner."""
names, updates = allocate_session_handles(rows, self._sessions.types)
if updates:
return None
return {
key: session_handle_for_name(key, name)
for key, name in names.items()
}
def handle_for_session(self, session_key: str) -> SessionHandle | None:
"""Offline compatibility API; runtime callers must use ahandle_for_session()."""
try:
key = _clean_session_key(session_key)
except ValueError:
return None
return self._ensure_all().get(key)
async def ahandle_for_session(self, session_key: str) -> SessionHandle | None:
try:
key = _clean_session_key(session_key)
except ValueError:
return None
return (await self._ensure_all_async()).get(key)
def list_all(self) -> list[SessionHandle]:
"""Offline compatibility API; runtime callers must use alist_all()."""
return sorted(self._ensure_all().values(), key=lambda handle: handle.name)
async def alist_all(self) -> list[SessionHandle]:
return sorted(
(await self._ensure_all_async()).values(),
key=lambda handle: handle.name,
)
def list_all_by_key(self) -> dict[str, SessionHandle]:
"""Offline compatibility API; runtime callers must use alist_all_by_key()."""
return self._ensure_all()
async def alist_all_by_key(self) -> dict[str, SessionHandle]:
return await self._ensure_all_async()
def resolve(self, name: str) -> SessionHandle | None:
"""Offline compatibility API; runtime callers must use aresolve()."""
try:
normalized = normalize_session_handle(name)
except ValueError:
@@ -227,3 +267,17 @@ class SessionHandleResolver:
),
None,
)
async def aresolve(self, name: str) -> SessionHandle | None:
try:
normalized = normalize_session_handle(name)
except ValueError:
return None
return next(
(
handle
for handle in (await self._ensure_all_async()).values()
if handle.name == normalized
),
None,
)
+441
View File
@@ -0,0 +1,441 @@
"""Transactional SQLite storage for private conversation state."""
from __future__ import annotations
import json
import os
import sqlite3
import threading
from collections.abc import Callable, Generator
from contextlib import contextmanager, suppress
from datetime import datetime
from pathlib import Path
from typing import Any, TypeVar, cast
from nanobot.providers.base import ProviderConversationState
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import (
Session,
SessionInfo,
SessionMetadataPayload,
SessionPayload,
message_preview_text,
metadata_title,
)
from nanobot.session.summary import is_summary_checkpoint
from nanobot.session.types import PARENT_SESSION_KEY
_CHECKPOINT = "runtime_checkpoint"
_INPUTS = ("pending_user_followups",)
_T = TypeVar("_T")
def _encode(value: object) -> str:
return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
def _object(value: str) -> dict[str, Any]:
parsed: object = json.loads(value)
if not isinstance(parsed, dict):
raise ValueError("stored session record must be an object")
return cast(dict[str, Any], parsed)
def _create_schema_v1(db: sqlite3.Connection) -> None:
for statement in (
"CREATE TABLE IF NOT EXISTS storage_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)",
"""CREATE TABLE IF NOT EXISTS sessions (
key TEXT PRIMARY KEY, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
metadata TEXT NOT NULL, provider_state TEXT, last_archived INTEGER NOT NULL,
revision INTEGER NOT NULL, generation TEXT NOT NULL,
title TEXT NOT NULL, preview TEXT NOT NULL, visible_updated_at TEXT
)""",
"""CREATE TABLE IF NOT EXISTS messages (
session_key TEXT NOT NULL REFERENCES sessions(key) ON DELETE CASCADE,
position INTEGER NOT NULL, record TEXT NOT NULL,
PRIMARY KEY (session_key, position)
)""",
"""CREATE TABLE IF NOT EXISTS checkpoints (
session_key TEXT PRIMARY KEY REFERENCES sessions(key) ON DELETE CASCADE,
record TEXT NOT NULL
)""",
"""CREATE TABLE IF NOT EXISTS pending_inputs (
session_key TEXT NOT NULL REFERENCES sessions(key) ON DELETE CASCADE,
kind TEXT NOT NULL, position INTEGER NOT NULL, record TEXT NOT NULL,
PRIMARY KEY (session_key, kind, position)
)""",
"CREATE INDEX IF NOT EXISTS sessions_updated ON sessions(updated_at DESC)",
):
db.execute(statement)
# Entries upgrade version N to N+1. Preserve released entries and append upgrades.
_SCHEMA_MIGRATIONS: tuple[Callable[[sqlite3.Connection], None], ...] = (_create_schema_v1,)
def _schema_version(db: sqlite3.Connection) -> int:
version = int(db.execute("PRAGMA user_version").fetchone()[0])
if not 0 <= version <= len(_SCHEMA_MIGRATIONS):
raise RuntimeError(f"unsupported session database schema: {version}")
return version
class SessionConflictError(RuntimeError):
"""A command refers to a replaced session or obsolete history."""
class SqliteSessionStore:
"""Synchronous repository; runtime callers use the session state's worker.
Nested repository operations share a transaction. Runtime worker threads
retain their own connections until their state owner drains and closes;
administrative calls close each connection after their transaction.
"""
def __init__(self, sessions_dir: Path) -> None:
self.path = sessions_dir / "sessions.sqlite3"
self._local = threading.local()
def run_write(self, operation: Callable[[], _T]) -> _T:
"""Run one repository command inside a write transaction."""
with self.transaction():
return operation()
def run_read(self, operation: Callable[[], _T]) -> _T:
"""Run one repository command against a consistent read snapshot."""
with self.transaction(write=False):
return operation()
def _open_connection(self, *, worker: bool = False) -> sqlite3.Connection:
if self.path.is_symlink():
raise RuntimeError("session database must not be a symlink")
connection = sqlite3.connect(
self.path, timeout=5, isolation_level=None, check_same_thread=not worker,
)
connection.row_factory = sqlite3.Row
try:
connection.execute("PRAGMA foreign_keys = ON")
connection.execute("PRAGMA synchronous = FULL")
except BaseException:
connection.close()
raise
return connection
def worker_connection(self) -> sqlite3.Connection:
"""Retain this worker's connection; its owner closes it after the worker exits."""
connection: sqlite3.Connection | None = getattr(self._local, "worker_connection", None)
if connection is None:
connection = self._open_connection(worker=True)
self._local.worker_connection = connection
return connection
@contextmanager
def transaction(self, *, write: bool = True) -> Generator[sqlite3.Connection, None, None]:
current: sqlite3.Connection | None = getattr(self._local, "connection", None)
if current is not None:
yield current
return
if self.path.is_symlink():
raise RuntimeError("session database must not be a symlink")
connection: sqlite3.Connection | None = getattr(self._local, "worker_connection", None)
owned = connection is None
if connection is None:
connection = self._open_connection()
self._local.connection = connection
try:
connection.execute("BEGIN IMMEDIATE" if write else "BEGIN")
yield connection
connection.commit()
except BaseException:
connection.rollback()
raise
finally:
self._local.connection = None
if owned:
connection.close()
def initialize(self, workspace: Path) -> None:
"""Upgrade the schema and import legacy sessions in one atomic transaction."""
workspace = workspace.expanduser().resolve(strict=False)
# WAL is persistent and must be enabled outside a transaction.
if self.path.is_symlink():
raise RuntimeError("session database must not be a symlink")
connection = sqlite3.connect(self.path, timeout=30, isolation_level=None)
try:
# Reject newer databases before changing their persistent settings.
_schema_version(connection)
try:
connection.execute("SELECT json_extract('{}', '$'), json_type('{}')")
except sqlite3.OperationalError as exc:
raise RuntimeError(
"session storage requires SQLite JSON support; use a Python build "
"linked to SQLite with JSON enabled"
) from exc
connection.execute("PRAGMA journal_mode = WAL")
finally:
connection.close()
with suppress(OSError):
os.chmod(self.path, 0o600)
with self.transaction() as db:
# Recheck under the write lock in case another startup upgraded first.
version = _schema_version(db)
for target, migrate in enumerate(_SCHEMA_MIGRATIONS[version:], start=version + 1):
migrate(db)
db.execute(f"PRAGMA user_version = {target}")
marker = db.execute(
"SELECT value FROM storage_meta WHERE key='jsonl_import'"
).fetchone()
if marker is None:
from nanobot.session.jsonl_migration import migrate_jsonl
migrate_jsonl(self, workspace)
db.execute("INSERT INTO storage_meta (key, value) VALUES ('jsonl_import', 'complete')")
elif marker[0] != "complete":
raise RuntimeError(
f"invalid JSONL migration marker in {self.path}: {marker[0]!r}; "
"restore a valid database backup or repair the marker explicitly"
)
from nanobot.session.jsonl_migration import finish_workspace_migration
finish_workspace_migration(self, workspace)
def _metadata(self, db: sqlite3.Connection, key: str, raw: str) -> dict[str, Any]:
metadata = _object(raw)
row = db.execute("SELECT record FROM checkpoints WHERE session_key=?", (key,)).fetchone()
if row is not None:
metadata[_CHECKPOINT] = _object(row[0])
for kind in _INPUTS:
values = [
_object(row[0]) for row in db.execute(
"SELECT record FROM pending_inputs WHERE session_key=? AND kind=? ORDER BY position",
(key, kind),
)
]
if values:
metadata[kind] = values
return metadata
def load(self, key: str, *, history: bool = True) -> Session | None:
with self.transaction(write=False) as db:
row = db.execute("SELECT * FROM sessions WHERE key=?", (key,)).fetchone()
if row is None:
return None
session = Session(
key=key,
messages=[_object(item[0]) for item in db.execute(
"SELECT record FROM messages WHERE session_key=? ORDER BY position", (key,),
)] if history else [],
created_at=datetime.fromisoformat(row["created_at"]),
updated_at=datetime.fromisoformat(row["updated_at"]),
metadata=self._metadata(db, key, row["metadata"]),
last_consolidated=row["last_archived"],
provider_state=ProviderConversationState.from_private_record(
_object(row["provider_state"])
) if row["provider_state"] is not None else None,
revision=row["revision"], generation=row["generation"], persisted=True,
)
if not history:
# A header carries the real offset even though history was not requested.
session.last_archived = row["last_archived"]
return session
def has_unarchived_messages(self, key: str) -> bool:
"""Check the indexed suffix without loading the archived transcript."""
with self.transaction(write=False) as db:
for row in db.execute(
"""SELECT record FROM messages
WHERE session_key=? AND position >= (
SELECT last_archived FROM sessions WHERE key=?
) ORDER BY position""",
(key, key),
):
message = _object(row[0])
if not message.get("_command") and not is_summary_checkpoint(message):
return True
return False
@staticmethod
def _write_metadata(db: sqlite3.Connection, key: str, values: dict[str, Any], *, bump_revision: bool = True) -> None:
metadata = dict(values)
checkpoint = metadata.pop(_CHECKPOINT, None)
if checkpoint is None:
db.execute("DELETE FROM checkpoints WHERE session_key=?", (key,))
else:
db.execute(
"INSERT INTO checkpoints (session_key, record) VALUES (?, ?) ON CONFLICT(session_key) DO UPDATE SET record=excluded.record",
(key, _encode(checkpoint)),
)
for kind in _INPUTS:
inputs = metadata.pop(kind, [])
if not isinstance(inputs, list):
raise ValueError(f"{kind} must be a list")
db.execute("DELETE FROM pending_inputs WHERE session_key=? AND kind=?", (key, kind))
db.executemany("INSERT INTO pending_inputs (session_key, kind, position, record) VALUES (?, ?, ?, ?)", [
(key, kind, position, _encode(record))
for position, record in enumerate(cast(list[object], inputs))
])
db.execute("UPDATE sessions SET metadata=?, title=?, revision=revision+? WHERE key=?", (
_encode(metadata), metadata_title(metadata), int(bump_revision), key,
))
def save(self, session: Session, *, message_start: int = 0) -> None:
"""Commit history, optionally skipping a prefix verified at this revision."""
if not 0 <= message_start <= len(session.messages):
raise ValueError("invalid message suffix boundary")
records = [_encode(message) for message in session.messages[message_start:]]
provider = _encode(session.provider_state.to_private_record()) if session.provider_state else None
preview = ""
fallback = ""
scanned_chars = 0
for message in session.messages[:200]:
scanned_chars += len(_encode(message)) + 1
if scanned_chars > 1_000_000:
break
if is_hidden_history_message(message):
continue
text = message_preview_text(message)
if message.get("role") == "user" and text:
preview = text
break
if message.get("role") == "assistant" and not fallback:
fallback = text
preview = preview or fallback
last_visible = next((m["timestamp"] for m in reversed(session.messages)
if m.get("timestamp") and not is_hidden_history_message(m)
and m.get("role") in {"user", "assistant"}), None)
with self.transaction() as db:
row = db.execute("SELECT revision, generation FROM sessions WHERE key=?", (session.key,)).fetchone()
if row is None:
if session.persisted:
raise SessionConflictError("session was deleted")
if message_start:
raise ValueError("a new session must include its full history")
db.execute("""INSERT INTO sessions (
key, created_at, updated_at, metadata, provider_state, last_archived,
revision, generation, title, preview, visible_updated_at
) VALUES (?, ?, ?, '{}', NULL, 0, 0, ?, '', '', NULL)""", (
session.key, session.created_at.isoformat(), session.updated_at.isoformat(), session.generation,
))
elif row[0] != session.revision or row[1] != session.generation:
raise SessionConflictError("session history changed")
db.execute("UPDATE sessions SET updated_at=?, provider_state=?, last_archived=?, revision=revision+1, preview=?, visible_updated_at=? WHERE key=?", (
session.updated_at.isoformat(), provider, session.last_archived,
preview, last_visible, session.key,
))
# Unchanged message rows do not generate writes. Appends only write the suffix.
db.executemany("""INSERT INTO messages (session_key, position, record) VALUES (?, ?, ?)
ON CONFLICT(session_key, position) DO UPDATE SET record=excluded.record
WHERE messages.record != excluded.record""", [
(session.key, position, record)
for position, record in enumerate(records, message_start)
])
db.execute("DELETE FROM messages WHERE session_key=? AND position>=?", (session.key, len(session.messages)))
self._write_metadata(db, session.key, session.metadata, bump_revision=False)
session.revision += 1
session.persisted = True
def save_runtime_checkpoint(self, session: Session) -> None:
with self.transaction() as db:
row = db.execute("SELECT generation FROM sessions WHERE key=?", (session.key,)).fetchone()
if row is None or row[0] != session.generation:
raise SessionConflictError("checkpoint belongs to a replaced session")
metadata = self.read_metadata(session.key)
assert metadata is not None
values = metadata["metadata"]
if _CHECKPOINT in session.metadata:
values[_CHECKPOINT] = session.metadata[_CHECKPOINT]
else:
values.pop(_CHECKPOINT, None)
self._write_metadata(db, session.key, values)
session.revision += 1
db.execute("UPDATE sessions SET provider_state=? WHERE key=?", (
_encode(session.provider_state.to_private_record()) if session.provider_state else None,
session.key,
))
def update_metadata(self, key: str, updates: dict[str, Any]) -> bool:
with self.transaction() as db:
payload = self.read_metadata(key)
if payload is None:
return False
self._write_metadata(db, key, {**payload["metadata"], **updates})
return True
def replace_metadata(
self, key: str, metadata: dict[str, Any], *, updated_at: datetime | None = None,
) -> None:
with self.transaction() as db:
self._write_metadata(db, key, metadata)
if updated_at is not None:
db.execute("UPDATE sessions SET updated_at=? WHERE key=?", (updated_at.isoformat(), key))
def read_metadata(self, key: str) -> SessionMetadataPayload | None:
with self.transaction(write=False) as db:
row = db.execute("SELECT created_at, updated_at, metadata FROM sessions WHERE key=?", (key,)).fetchone()
if row is None:
return None
return {"key": key, "created_at": row[0], "updated_at": row[1],
"metadata": self._metadata(db, key, row[2])}
def read(self, key: str) -> SessionPayload | None:
session = self.load(key)
if session is None:
return None
return {"key": key, "created_at": session.created_at.isoformat(),
"updated_at": session.updated_at.isoformat(),
"metadata": session.metadata, "messages": session.messages}
def delete(self, key: str) -> bool:
with self.transaction() as db:
return db.execute("DELETE FROM sessions WHERE key=?", (key,)).rowcount > 0
def list_sessions(self) -> list[SessionInfo]:
with self.transaction(write=False) as db:
return [SessionInfo(key=row[0], created_at=row[1], updated_at=row[2],
title=row[3], preview=row[4], path=str(self.path))
for row in db.execute("SELECT key, created_at, updated_at, title, preview FROM sessions ORDER BY updated_at DESC")]
def child_session_keys(self, parent_key: str) -> list[str]:
"""Find all persisted child kinds without decoding unrelated metadata."""
with self.transaction(write=False) as db:
return [row[0] for row in db.execute(
f"""SELECT key FROM sessions
WHERE json_extract(metadata, '$.{PARENT_SESSION_KEY}')=?
AND json_type(metadata, '$.{PARENT_SESSION_KEY}')='text'
ORDER BY updated_at DESC""",
(parent_key,),
)]
def list_child_session_metadata(self, parent_key: str) -> list[SessionMetadataPayload]:
"""Read child headers from one snapshot, excluding checkpoints and pending inputs."""
with self.transaction(write=False) as db:
return [{"key": row[0], "created_at": row[1], "updated_at": row[2],
"metadata": _object(row[3])}
for row in db.execute(
f"""SELECT key, created_at, updated_at, metadata FROM sessions
WHERE json_extract(metadata, '$.{PARENT_SESSION_KEY}')=?
AND json_type(metadata, '$.{PARENT_SESSION_KEY}')='text'
ORDER BY updated_at DESC""",
(parent_key,),
)]
def list_metadata(self) -> list[dict[str, Any]]:
with self.transaction(write=False) as db:
# Fetch one value so a large list does not cross the Python/SQLite
# iterator boundary for every session while other workers are busy.
encoded = db.execute("""
SELECT json_group_array(json_object(
'key', key, 'created_at', created_at, 'updated_at', updated_at,
'title', title, 'preview', preview, 'visible_updated_at', visible_updated_at,
'metadata', metadata
)) FROM (
SELECT key, created_at, updated_at, title, preview, visible_updated_at, metadata
FROM sessions ORDER BY updated_at DESC
)
""").fetchone()[0]
# The SQL projection constructs this list and its dictionary fields.
rows = cast(list[dict[str, Any]], json.loads(encoded))
for row in rows:
row["path"] = str(self.path)
row["metadata"] = _object(row["metadata"])
return rows
File diff suppressed because it is too large. Load diff
+5 -3
View File
@@ -114,14 +114,16 @@ def should_finalize_on_max_iterations(
)
async def maybe_continue_turn(ctx: TurnContext) -> bool:
async def maybe_continue_turn(
ctx: TurnContext, *, session_metadata: Mapping[str, Any],
) -> bool:
"""Queue an internal continuation for *ctx* when policy allows it."""
if ctx.session is None or ctx.pending_queue is None:
return False
if not _continuation_available(
stop_reason=ctx.stop_reason,
pending_queue_available=True,
session_metadata=ctx.session.metadata,
session_metadata=session_metadata,
message_metadata=ctx.msg.metadata,
):
return False
@@ -136,7 +138,7 @@ async def maybe_continue_turn(ctx: TurnContext) -> bool:
"message_id": request.message_id,
"turn_id": request.turn_id,
}
content = _goal_continuation_prompt(ctx.session.metadata)
content = _goal_continuation_prompt(session_metadata)
messages = _strip_terminal_assistant(ctx.all_messages, ctx.final_content)
_increment_goal_continuation_round(ctx.session.metadata)
+40 -16
View File
@@ -49,6 +49,7 @@ from nanobot.session.session_messages import (
SessionMessageEnvelope,
session_message_envelope,
)
from nanobot.session.sqlite_store import SessionConflictError
from nanobot.utils.helpers import strip_think, truncate_text
from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.webui.metadata import (
@@ -210,12 +211,14 @@ async def maybe_generate_webui_title(
so pass ``target_session_key`` to project the title onto that per-chat
session instead of storing it on the shared one.
"""
routed_session = sessions.get_or_create(session_key)
routed_session = await sessions.state.read(session_key)
if routed_session is None:
return False
target_is_routed = target_session_key is None or target_session_key == session_key
if target_is_routed or target_session_key is None:
target_session = routed_session
else:
target_session = sessions.get_or_create(target_session_key)
target_session = await sessions.state.get(target_session_key)
if (
routed_session.metadata.get(WEBUI_SESSION_METADATA_KEY) is not True
and target_session.metadata.get(WEBUI_SESSION_METADATA_KEY) is not True
@@ -228,8 +231,13 @@ async def maybe_generate_webui_title(
cleaned_current_title = clean_generated_title(current_title)
if cleaned_current_title:
if cleaned_current_title != current_title:
target_session.metadata[WEBUI_TITLE_METADATA_KEY] = cleaned_current_title
sessions.save(target_session)
def clean_title(metadata: dict[str, Any]) -> None:
if (metadata.get(WEBUI_TITLE_METADATA_KEY) == current_title
and metadata.get(WEBUI_TITLE_USER_EDITED_METADATA_KEY) is not True):
metadata[WEBUI_TITLE_METADATA_KEY] = cleaned_current_title
await sessions.state.mutate_metadata(
target_session.key, clean_title, expected_generation=target_session.generation,
)
return False
target_session.metadata.pop(WEBUI_TITLE_METADATA_KEY, None)
@@ -292,9 +300,20 @@ async def maybe_generate_webui_title(
response.finish_reason,
)
return False
target_session.metadata[WEBUI_TITLE_METADATA_KEY] = title
sessions.save(target_session)
return True
def set_title(metadata: dict[str, Any]) -> bool:
if metadata.get(WEBUI_TITLE_USER_EDITED_METADATA_KEY) is True:
return False
if metadata.get(WEBUI_TITLE_METADATA_KEY) != current_title:
return False
metadata[WEBUI_TITLE_METADATA_KEY] = title
return True
try:
changed, _ = await sessions.state.mutate_metadata(
target_session.key, set_title, expected_generation=target_session.generation,
)
except SessionConflictError:
return False
return changed
async def maybe_generate_webui_title_after_turn(
@@ -473,8 +492,8 @@ class WebuiTurnRoutePolicy:
)
and route.channel == "websocket"
):
session = self.sessions.get_or_create(session_key)
if session.metadata.get(WEBUI_SESSION_METADATA_KEY) is True:
metadata_snapshot = self.sessions.state.peek_metadata(session_key)
if metadata_snapshot is not None and metadata_snapshot.get(WEBUI_SESSION_METADATA_KEY) is True:
metadata = dict(route.metadata)
turn_prefix = "session-input" if internal_user_input else "subagent"
metadata.update({
@@ -552,6 +571,7 @@ class WebuiTurnCoordinator:
sessions: SessionManager
schedule_background: Callable[[Awaitable[None]], None]
recovery: RecoveryCoordinator | None = None
def subscribe(self) -> Callable[[], None]:
"""Subscribe this coordinator to runtime events."""
unsubscribe = [
@@ -626,7 +646,7 @@ class WebuiTurnCoordinator:
or not is_webui_session_key(session_key)
):
return
persisted = self.sessions.read_session_metadata(session_key)
persisted = await self.sessions.state.read_metadata(session_key)
metadata_value: object = persisted.get("metadata") if persisted is not None else None
metadata = (
cast(dict[str, Any], metadata_value)
@@ -658,11 +678,15 @@ class WebuiTurnCoordinator:
),
))
def _handle_session_turn_started(self, event: SessionTurnStarted) -> None:
if not self._is_websocket_event(event.context):
return
session = self.sessions.get_or_create(event.context.session_key)
mark_webui_session(session, event.context.metadata)
async def _handle_session_turn_started(self, event: SessionTurnStarted) -> None:
if (self._is_websocket_event(event.context)
and event.context.metadata.get(WEBUI_SESSION_METADATA_KEY) is True):
await self.sessions.state.update_metadata(
event.context.session_key,
{WEBUI_SESSION_METADATA_KEY: True},
expected_generation=event.context.session_generation,
create_if_missing=False,
)
async def _handle_run_status_changed(self, event: TurnRunStatusChanged) -> None:
if not self._is_websocket_event(event.context):
@@ -771,7 +795,7 @@ class WebuiTurnCoordinator:
if msg.channel != "websocket":
return
session = self.sessions.get_or_create(session_key)
session = await self.sessions.state.get(session_key)
await self.bus.publish_outbound(
outbound_message_for_event(
channel=msg.channel,
+2 -2
View File
@@ -2,7 +2,7 @@
from __future__ import annotations
from collections.abc import Callable, Iterable
from collections.abc import Awaitable, Callable, Iterable
from nanobot.agent.automation_turns import AutomationTurnCoordinator
from nanobot.bus.events import InboundMessage
@@ -15,7 +15,7 @@ class LocalTriggerTurnCoordinator(AutomationTurnCoordinator):
def __init__(
self,
*,
enqueue: Callable[[InboundMessage], None],
enqueue: Callable[[InboundMessage], Awaitable[None]],
deferred_queues: dict[str, list[InboundMessage]] | None = None,
) -> None:
super().__init__(
+4 -4
View File
@@ -9,7 +9,7 @@ from nanobot.cron.binding import CronBinding
from nanobot.cron.types import CronJob
from nanobot.session.manager import (
SessionManager,
_metadata_title, # pyright: ignore[reportPrivateUsage]
metadata_title,
)
from nanobot.session.session_handles import SessionHandleResolver
from nanobot.utils.helpers import truncate_text
@@ -30,7 +30,7 @@ class AutomationChat:
**({"unavailable": True} if not self.available else {})}
def automation_chats(
async def automation_chats(
job: CronJob, sessions: SessionManager, workspaces: WebUIWorkspaceController,
channel_status: dict[str, Any],
) -> list[AutomationChat]:
@@ -50,7 +50,7 @@ def automation_chats(
)
result: list[AutomationChat] = []
previews = {row["key"]: row.get("preview", "") for row in sessions.list_sessions()}
for handle in SessionHandleResolver(sessions).list_all():
for handle in await SessionHandleResolver(sessions).alist_all():
key = handle.session_key
data = sessions.read_session_metadata(key)
metadata: dict[str, Any] = data.get("metadata", {}) if data else {}
@@ -76,7 +76,7 @@ def automation_chats(
continue
result.append(AutomationChat(
id=handle.id,
title=(_metadata_title(metadata)
title=(metadata_title(metadata)
or truncate_text(" ".join(previews.get(key, "").split()), 60)
or f"@{handle.name}"),
binding=CronBinding(key, channel, chat_id, route_metadata),
+16 -19
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import asyncio
import uuid
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, Protocol
@@ -9,7 +10,7 @@ from typing import TYPE_CHECKING, Any, Protocol
from loguru import logger
from nanobot.session.manager import SessionManager
from nanobot.session.webui_turns import WEBUI_TITLE_METADATA_KEY, clean_generated_title
from nanobot.session.webui_turns import clean_generated_title
from nanobot.webui.session_identity import is_valid_webui_chat_id, webui_session_key
from nanobot.webui.transcript import (
append_fork_marker,
@@ -42,7 +43,7 @@ class WebUIForkHost(Protocol):
) -> None: ...
def create_webui_chat_fork(
async def create_webui_chat_fork(
session_manager: SessionManager,
*,
source_chat_id: str,
@@ -54,30 +55,26 @@ def create_webui_chat_fork(
source_key = webui_session_key(source_chat_id)
target_key = webui_session_key(new_id)
try:
forked = session_manager.fork_session_before_user_index(
forked = await session_manager.state.fork(
source_key,
target_key,
before_user_index,
title=clean_generated_title(title),
)
if forked is None:
return None
transcript_ok = fork_transcript_before_user_index(
source_key,
target_key,
before_user_index,
)
if not transcript_ok:
write_session_messages_as_transcript(target_key, forked.messages)
append_fork_marker(target_key)
fork_title = clean_generated_title(title)
if fork_title:
forked.metadata[WEBUI_TITLE_METADATA_KEY] = fork_title
session_manager.save(forked, fsync=True)
def write_transcript() -> None:
transcript_ok = fork_transcript_before_user_index(
source_key, target_key, before_user_index,
)
if not transcript_ok:
write_session_messages_as_transcript(target_key, forked.messages)
append_fork_marker(target_key)
await asyncio.to_thread(write_transcript)
except Exception:
delete_webui_transcript(target_key)
session_manager.delete_session(target_key)
await asyncio.to_thread(delete_webui_transcript, target_key)
await session_manager.state.delete(target_key)
raise
return new_id, target_key
@@ -108,7 +105,7 @@ async def handle_webui_fork_chat(
return
try:
forked = create_webui_chat_fork(
forked = await create_webui_chat_fork(
session_manager,
source_chat_id=source_chat_id,
before_user_index=raw_index,
+3
View File
@@ -53,6 +53,7 @@ class GatewayServices:
local_trigger_store: LocalTriggerStore | None
cron_pending_job_ids: Callable[[str], set[str]] | None
local_trigger_pending_ids: Callable[[str], set[str]] | None
unified_session: bool = False
def build_gateway_services(
@@ -63,6 +64,7 @@ def build_gateway_services(
static_dist_path: Path | None,
workspace_path: Path,
default_restrict_to_workspace: bool,
unified_session: bool = False,
config_path: Path | None = None,
runtime_model_name: Callable[[], str | None] | None,
refresh_runtime_config: Callable[[], None] | None = None,
@@ -171,4 +173,5 @@ def build_gateway_services(
local_trigger_store=local_trigger_store,
cron_pending_job_ids=cron_pending_job_ids,
local_trigger_pending_ids=local_trigger_pending_ids,
unified_session=unified_session,
)
+75 -25
View File
@@ -8,7 +8,7 @@ import json
import re
import time
import uuid
from collections.abc import Callable
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any, Protocol, cast
@@ -28,6 +28,7 @@ from nanobot.security.workspace_access import (
WORKSPACE_SCOPE_METADATA_KEY,
WorkspaceScopeError,
)
from nanobot.session.keys import session_key_for_channel
from nanobot.session.webui_turns import (
clear_websocket_turn_if_current,
clear_websocket_turns,
@@ -126,6 +127,7 @@ class WebUICommandTransport(Protocol):
is_dm: bool,
session_key: str | None,
require_existing_session: bool,
session_generation: str | None,
) -> None: ...
async def send_session_updated(
@@ -182,13 +184,13 @@ class WebUICommandRouter:
fork_id: str,
fork_key: str,
) -> None:
scope = self._workspaces.scope_for_session_key(fork_key)
scope = await self._workspaces.async_scope_for_session_key(fork_key)
self._transport.webui_attach(connection, fork_id)
await self._transport.webui_send_event(
connection,
"attached",
chat_id=fork_id,
**self._session_projection.attach_fields(fork_key),
**(await self._session_projection.attach_fields(fork_key)),
)
await self._transport.webui_send_event(
connection,
@@ -275,13 +277,13 @@ class WebUICommandRouter:
async def workspace_scope_or_error(
self,
connection: ServerConnection,
resolver: Callable[[], Any],
resolver: Callable[[], Awaitable[Any]],
*,
chat_id: str | None = None,
turn_id: str | None = None,
) -> Any | None:
try:
return resolver()
return await resolver()
except WorkspaceScopeError as exc:
await self._transport.webui_send_event(
connection,
@@ -315,13 +317,13 @@ class WebUICommandRouter:
)
if scope is None:
return
self._workspaces.stage_scope(new_id, scope)
await self._workspaces.stage_scope(new_id, scope)
self._transport.webui_attach(connection, new_id)
await self._transport.webui_send_event(
connection,
"attached",
chat_id=new_id,
**self._session_projection.attach_fields(webui_session_key(new_id)),
**(await self._session_projection.attach_fields(webui_session_key(new_id))),
)
await self._transport.webui_send_event(
connection,
@@ -334,7 +336,7 @@ class WebUICommandRouter:
return
if command_type == "new_temporary_chat":
try:
new_id = self._temporary_chats.create(
new_id = await self._temporary_chats.create(
connection,
trusted_webui=connection in self._webui_connections,
)
@@ -395,7 +397,7 @@ class WebUICommandRouter:
connection,
"attached",
chat_id=chat_id,
**self._session_projection.attach_fields(webui_session_key(chat_id)),
**(await self._session_projection.attach_fields(webui_session_key(chat_id))),
)
await self._transport.webui_hydrate(chat_id)
return
@@ -456,7 +458,7 @@ class WebUICommandRouter:
)
if scope is None:
return
self._workspaces.stage_scope(chat_id, scope)
await self._workspaces.stage_scope(chat_id, scope)
await self._transport.send_session_updated(chat_id, scope="metadata")
await self._transport.webui_send_event(
connection,
@@ -619,20 +621,18 @@ class WebUICommandRouter:
if temporary_policy is None or temporary_policy.hydrate_transcript:
await self._transport.webui_hydrate(chat_id)
scope = await self.workspace_scope_or_error(
connection,
lambda: (
temporary_policy.workspace_scope
if temporary_policy is not None
else self._workspaces.scope_for_message(
scope = temporary_policy.workspace_scope if temporary_policy is not None else (
await self.workspace_scope_or_error(
connection,
lambda: self._workspaces.scope_for_message(
envelope,
chat_id=chat_id,
chat_running=websocket_turn_wall_started_at(chat_id) is not None,
can_change_project=self.workspace_project_selection_available(connection),
)
),
chat_id=chat_id,
turn_id=turn_id,
),
chat_id=chat_id,
turn_id=turn_id,
)
)
if scope is None:
return
@@ -685,8 +685,7 @@ class WebUICommandRouter:
metadata["mcp_presets"] = mcp_presets
session_mentions: list[SessionMention] = []
if trusted_webui and self._session_access is not None:
session_mentions = await asyncio.to_thread(
self._session_access.normalize_mentions,
session_mentions = await self._session_access.normalize_mentions(
envelope.get("session_mentions"),
exclude_session_key=webui_session_key(chat_id),
)
@@ -715,7 +714,44 @@ class WebUICommandRouter:
metadata[WEBSOCKET_TURN_OWNER_METADATA_KEY] = queued_owner
accepted = False
admission_session_key = (
temporary_policy.session_key
if temporary_policy is not None
else webui_session_key(chat_id)
)
execution_session_key = (
temporary_policy.session_key
if temporary_policy is not None
else session_key_for_channel(
"websocket", chat_id, unified_session=self.gateway.unified_session,
)
)
session_generation: str | None = None
session_created = False
execution_generation: str | None = None
execution_created = False
try:
if not restart_control:
session_generation, session_created = await self._workspaces.persist_scope(
chat_id,
scope,
session_key=admission_session_key,
expected_generation=(
temporary_policy.session_generation
if temporary_policy is not None
else None
),
)
execution_generation = session_generation
if (
execution_session_key != admission_session_key
and self.gateway.session_manager is not None
):
execution_generation, execution_created = (
await self.gateway.session_manager.state.open_with_metadata(
execution_session_key, {},
)
)
if is_webui and not restart_control and (
temporary_policy is None or temporary_policy.persist_transcript
):
@@ -753,21 +789,35 @@ class WebUICommandRouter:
metadata=metadata,
is_dm=False,
session_key=(
temporary_policy.session_key if temporary_policy is not None else None
execution_session_key
if temporary_policy is not None
or execution_session_key != admission_session_key
else None
),
require_existing_session=(
temporary_policy.require_existing_session
if temporary_policy is not None
else False
),
session_generation=execution_generation,
)
if not restart_control:
self._workspaces.persist_scope(chat_id, scope)
accepted = True
if turn_id:
self._accepted_messages[(chat_id, turn_id)] = time.monotonic() + 600
if len(self._accepted_messages) > 1024:
del self._accepted_messages[next(iter(self._accepted_messages))]
except BaseException:
await self._workspaces.rollback_scope_admission(
execution_session_key,
execution_generation,
created=execution_created,
)
await self._workspaces.rollback_scope_admission(
admission_session_key,
session_generation,
created=session_created,
)
raise
finally:
if not accepted and queued_owner is not None:
clear_websocket_turn_if_current(chat_id, queued_owner)
+1 -1
View File
@@ -122,7 +122,7 @@ class WebUIOutboundProjector:
async def hydrate(self, chat_id: str) -> None:
"""Replay reconnect state through the existing stable wire operations."""
for event in self._session_projection.hydration_events(
for event in await self._session_projection.hydration_events(
webui_session_key(chat_id),
chat_id,
):
+23 -23
View File
@@ -86,8 +86,8 @@ class RecoveryCoordinator:
async def scan(self) -> None:
"""Recover every interrupted WebUI session once at gateway startup."""
for key in self._recovery_candidates():
metadata_payload = self.sessions.read_session_metadata(key)
for key in await self._recovery_candidates():
metadata_payload = await self.sessions.state.read_metadata(key)
raw_metadata = metadata_payload.get("metadata") if metadata_payload else None
metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
route = self._websocket_route_for(key, metadata)
@@ -96,7 +96,7 @@ class RecoveryCoordinator:
unfinished = self._has_unfinished_webui_transcript(key)
if not self._needs_recovery(metadata) and not unfinished:
continue
session = self.sessions.get_or_create(key)
session = await self.sessions.state.get(key)
try:
await self._recover_session(session, route[1])
await self._requeue_pending_followups(session)
@@ -111,14 +111,14 @@ class RecoveryCoordinator:
reason="recovery_failed",
can_continue=False,
)
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
await self._publish(route[1], failed)
def _recovery_candidates(self) -> list[str]:
async def _recovery_candidates(self) -> list[str]:
"""Discover canonical and transcript-only WebUI sessions cheaply."""
candidates = dict.fromkeys(
key
for item in self.sessions.list_sessions()
for item in await self.sessions.state.list_sessions()
if isinstance((key := item.get("key")), str)
)
try:
@@ -127,7 +127,7 @@ class RecoveryCoordinator:
# duplicating its filename and migration rules here would drift.
from nanobot.webui.session_list_index import list_webui_sessions
for item in list_webui_sessions(self.sessions):
for item in await asyncio.to_thread(list_webui_sessions, self.sessions):
key = item.get("key")
if isinstance(key, str):
candidates.setdefault(key, None)
@@ -153,7 +153,7 @@ class RecoveryCoordinator:
"""Reject stale queued recoveries and let new user input supersede them."""
recovery_id = message.metadata.get(RECOVERY_INBOUND_METADATA_KEY)
if isinstance(recovery_id, str):
session = self.sessions.get_or_create(message.session_key)
session = await self.sessions.state.get(message.session_key)
state = recovery_state_from_metadata(session.metadata)
return bool(
state
@@ -162,7 +162,7 @@ class RecoveryCoordinator:
)
if message.channel != "websocket":
return True
session = self.sessions.get_or_create(message.session_key)
session = await self.sessions.state.get(message.session_key)
state = recovery_state_from_metadata(session.metadata)
if state and state["status"] in {"resuming", "awaiting_user", "failed"}:
await self._cancel_active_recovery(message.session_key)
@@ -176,13 +176,13 @@ class RecoveryCoordinator:
attempts=cast(int, state.get("attempts", 0)),
reason="superseded",
)
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
await self._publish(message.chat_id, recovered)
return True
async def turn_completed(self, session_key: str) -> None:
"""Resolve a resuming state after the recovered turn commits."""
session = self.sessions.get_or_create(session_key)
session = await self.sessions.state.get(session_key)
state = recovery_state_from_metadata(session.metadata)
if not state or state["status"] != "resuming":
return
@@ -196,7 +196,7 @@ class RecoveryCoordinator:
attempts=cast(int, state.get("attempts", 0)),
reason="continued",
)
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
await self._publish(route[1], recovered)
async def handle_action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]:
@@ -207,7 +207,7 @@ class RecoveryCoordinator:
raise RecoveryActionError("missing chat_id")
if not isinstance(recovery_id, str) or not recovery_id:
raise RecoveryActionError("missing recovery_id")
session = self.sessions.get_or_create(self._session_key(chat_id))
session = await self.sessions.state.get(self._session_key(chat_id))
state = recovery_state_from_metadata(session.metadata)
if not state or state["recovery_id"] != recovery_id:
raise RecoveryActionError("recovery state is stale", status=409)
@@ -222,7 +222,7 @@ class RecoveryCoordinator:
attempts=cast(int, state.get("attempts", 0)),
reason="dismissed",
)
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, next_state)
return next_state
if action != "continue":
@@ -239,7 +239,7 @@ class RecoveryCoordinator:
reason="user_confirmed",
resume_message_count=len(session.messages),
)
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, next_state)
await self._queue_continuation(session, chat_id, next_state)
return next_state
@@ -272,7 +272,7 @@ class RecoveryCoordinator:
attempts=cast(int, state.get("attempts", 1)),
reason="loop_guard",
)
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, next_state)
elif self._has_unfinished_webui_transcript(session.key):
# A normal last-client shutdown can materialize the checkpoint
@@ -294,7 +294,7 @@ class RecoveryCoordinator:
),
can_continue=can_continue,
)
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, waiting)
return
if state and state["status"] in {"awaiting_user", "failed"}:
@@ -310,7 +310,7 @@ class RecoveryCoordinator:
attempts=cast(int, state.get("attempts", 1)),
reason="loop_guard",
)
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, waiting)
return
@@ -328,7 +328,7 @@ class RecoveryCoordinator:
reason="checkpoint_unknown",
can_continue=False,
)
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, waiting)
return
if checkpoint is not None and not runtime_checkpoint_is_well_formed(checkpoint):
@@ -342,7 +342,7 @@ class RecoveryCoordinator:
reason="checkpoint_invalid",
can_continue=False,
)
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, waiting)
return
if phase == "final_response":
@@ -354,7 +354,7 @@ class RecoveryCoordinator:
attempts=0,
reason="answer_restored",
)
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, recovered)
return
if phase in UNCERTAIN_TOOL_PHASES or pending_calls:
@@ -366,7 +366,7 @@ class RecoveryCoordinator:
attempts=0,
reason="tool_state_unknown",
)
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, waiting)
return
# A gateway restart is a lifecycle boundary. Never enqueue model work
@@ -381,7 +381,7 @@ class RecoveryCoordinator:
attempts=0,
reason="restart_requires_confirmation",
)
self.sessions.save(session)
await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, waiting)
async def _queue_continuation(
+12 -4
View File
@@ -51,22 +51,30 @@ class WebuiSessionAccess:
return None
return payload
def normalize_mentions(
async def normalize_mentions(
self,
raw: object,
*,
exclude_session_key: str | None = None,
) -> list[SessionMention]:
mentions = normalize_session_mentions_metadata(raw)
if not mentions:
return []
normalized: list[SessionMention] = []
seen_keys: set[str] = set()
seen_names: set[str] = set()
for raw_mention in normalize_session_mentions_metadata(raw):
handles = await self._handles.alist_all_by_key()
for raw_mention in mentions:
mention = raw_mention
key = mention["session_key"]
payload = self._metadata(key, exclude_session_key=exclude_session_key)
payload = (
None
if key == exclude_session_key
else await self._sessions.state.read_metadata(key)
)
if payload is None or key in seen_keys:
continue
handle = self._handles.handle_for_session(key)
handle = handles.get(key)
if handle is None:
continue
folded_name = handle.name.casefold()
+4 -4
View File
@@ -10,8 +10,8 @@ from nanobot.cron.session_turns import is_bound_cron_job
from nanobot.cron.types import CronJob
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import (
_message_preview_text, # pyright: ignore[reportPrivateUsage]
_metadata_title, # pyright: ignore[reportPrivateUsage]
message_preview_text, # pyright: ignore[reportPrivateUsage]
metadata_title, # pyright: ignore[reportPrivateUsage]
)
from nanobot.triggers.local_types import LocalTrigger
from nanobot.webui.session_identity import is_webui_session_key
@@ -322,7 +322,7 @@ def _websocket_origin_payload(
if session_manager is not None:
data = session_manager.read_session_file(session_key)
if isinstance(data, dict):
title = _metadata_title(data.get("metadata"))
title = metadata_title(data.get("metadata"))
preview = _session_preview(data.get("messages"))
return {
@@ -344,7 +344,7 @@ def _session_preview(messages: Any) -> str:
message = cast(dict[str, Any], message_value)
if is_hidden_history_message(message):
continue
text = _message_preview_text(message)
text = message_preview_text(message)
if not text:
continue
if message.get("role") == "user":
+111 -332
View File
@@ -1,4 +1,4 @@
"""Cache-only WebUI session list index.
"""SQLite sidebar queries and a rebuildable display-transcript cache.
The core ``SessionManager`` owns model context while the WebUI transcript owns
durable display history. The sidebar discovers both without reconstructing one
@@ -11,6 +11,8 @@ import json
import os
import re
import secrets
import stat
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any, cast
@@ -19,17 +21,12 @@ from loguru import logger
from nanobot.config.paths import get_webui_dir
from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import (
_PROVIDER_STATE_RECORD_TYPE, # pyright: ignore[reportPrivateUsage]
_SESSION_LIST_PREVIEW_MAX_CHARS, # pyright: ignore[reportPrivateUsage]
_SESSION_LIST_PREVIEW_MAX_RECORDS, # pyright: ignore[reportPrivateUsage]
Session,
SessionManager,
_is_provider_state_record_line, # pyright: ignore[reportPrivateUsage]
_message_preview_text, # pyright: ignore[reportPrivateUsage]
_metadata_title, # pyright: ignore[reportPrivateUsage]
)
message_preview_text, # pyright: ignore[reportPrivateUsage]
)
from nanobot.session.model_selection import model_preset_from_metadata
from nanobot.session.recovery import recovery_state_from_metadata
from nanobot.webui.session_identity import (
@@ -62,28 +59,73 @@ _TRANSCRIPT_SEGMENTS_SUFFIX = ".segments"
_TRANSCRIPT_NON_ANSWER_KINDS = {"progress", "reasoning", "tool_hint"}
def list_webui_sessions(session_manager: SessionManager) -> list[dict[str, Any]]:
@dataclass
class _WebuiFiles:
signature: dict[str, int] = field(default_factory=lambda: {
_WEBUI_ACTIVITY_MTIME_NS: 0, _WEBUI_ACTIVITY_SIZE: 0, _WEBUI_ACTIVITY_FILES: 0,
})
records: list[tuple[Path, float]] = field(default_factory=list)
def list_webui_sessions(
session_manager: SessionManager,
stored_sessions: list[dict[str, Any]] | None = None,
) -> list[dict[str, Any]]:
"""Return session rows for the WebUI sidebar, backed by a rebuildable cache."""
with session_manager.locked_session_files():
rows, changed = _reconcile_index(session_manager)
if changed:
try:
_write_index_rows(session_manager.sessions_dir, rows)
except Exception as e:
logger.debug("Failed to write WebUI session list index: {}", e)
sessions = [
_public_row(session_manager.sessions_dir, get_webui_dir(), row)
for row in rows
]
sessions = [
row for row in sessions if session_manager.types.public_history(
(session_manager.read_session_metadata(row["key"]) or {}).get("metadata", {})
)
]
webui_dir = get_webui_dir()
rows, changed = _reconcile_index(session_manager, stored_sessions, webui_dir)
if changed:
try:
_write_index_rows(session_manager.sessions_dir, [row for row in rows if row.get(_ROW_SOURCE_FIELD) == _TRANSCRIPT_SOURCE])
except Exception as e:
logger.debug("Failed to write WebUI transcript list cache: {}", e)
sessions = [_public_row(session_manager.sessions_dir, webui_dir, row) for row in rows]
return sorted(sessions, key=lambda row: row.get("updated_at", ""), reverse=True)
def _reconcile_index(session_manager: SessionManager) -> tuple[list[dict[str, Any]], bool]:
def _reconcile_index(
session_manager: SessionManager,
stored_sessions: list[dict[str, Any]] | None,
webui_dir: Path,
) -> tuple[list[dict[str, Any]], bool]:
files_by_stem = _read_webui_files(webui_dir)
activity_by_stem: dict[str, dict[str, int]] = {}
for stem, files in files_by_stem.items():
identity = os.path.normcase(stem)
previous = activity_by_stem.get(identity)
activity_by_stem[identity] = files.signature if previous is None else {
_WEBUI_ACTIVITY_MTIME_NS: max(previous[_WEBUI_ACTIVITY_MTIME_NS], files.signature[_WEBUI_ACTIVITY_MTIME_NS]),
_WEBUI_ACTIVITY_SIZE: previous[_WEBUI_ACTIVITY_SIZE] + files.signature[_WEBUI_ACTIVITY_SIZE],
_WEBUI_ACTIVITY_FILES: previous[_WEBUI_ACTIVITY_FILES] + files.signature[_WEBUI_ACTIVITY_FILES],
}
stored = session_manager.list_session_metadata() if stored_sessions is None else stored_sessions
session_keys = {row["key"] for row in stored}
session_stems = {os.path.normcase(SessionManager.safe_key(key)) for key in session_keys if is_webui_session_key(key)}
rows: list[dict[str, Any]] = []
for row in stored:
metadata = row["metadata"]
if not session_manager.types.public_history(metadata):
continue
signature = activity_by_stem.get(os.path.normcase(SessionManager.safe_key(row["key"])))
activity = _webui_activity_updated_at(signature) if signature is not None else None
rows.append({
"key": row["key"], "created_at": row["created_at"],
"updated_at": _visible_activity_updated_at(row["updated_at"], row["visible_updated_at"], activity),
"title": row["title"], "preview": row["preview"],
_MODEL_PRESET_FIELD: model_preset_from_metadata(metadata),
"recovery_state": recovery_state_from_metadata(metadata),
**_indexed_workspace_scope_fields(metadata),
_ROW_SOURCE_FIELD: _SESSION_SOURCE, "file": "sessions.sqlite3",
})
transcripts = [
(stem, files) for stem, files in sorted(files_by_stem.items())
if stem.startswith(_WEBUI_SESSION_STEM_PREFIX) and files.records
and os.path.normcase(stem) not in session_stems
]
if not transcripts:
return rows, False
# Only transcript-only sessions use the file cache; SQLite rows are fresh.
existing_rows = _read_index_rows(session_manager.sessions_dir)
existing_by_source = {
(row.get(_ROW_SOURCE_FIELD), row.get("file")): row
@@ -91,39 +133,10 @@ def _reconcile_index(session_manager: SessionManager) -> tuple[list[dict[str, An
if isinstance(row.get(_ROW_SOURCE_FIELD), str)
and isinstance(row.get("file"), str)
}
webui_dir = get_webui_dir()
session_paths: dict[str, Path] = {}
for path in sorted(session_manager.sessions_dir.glob("*.jsonl")):
key = SessionManager._session_key_from_path(path) # pyright: ignore[reportPrivateUsage]
if key is not None:
session_paths[key] = path
session_keys_by_stem = {
SessionManager.safe_key(key): key
for key in session_paths
if is_webui_session_key(key)
}
rows: list[dict[str, Any]] = []
changed = existing_rows is None
expected_sources: set[tuple[str, str]] = set()
for key, path in sorted(session_paths.items()):
identity = (_SESSION_SOURCE, path.name)
row = existing_by_source.get(identity)
if row is not None and _indexed_row_matches_file(row, path, webui_dir):
rows.append(row)
expected_sources.add(identity)
continue
changed = True
scanned = _scan_session_row(session_manager, path, webui_dir)
if scanned is not None:
rows.append(scanned)
expected_sources.add(identity)
for stem, paths in _webui_transcript_sources(webui_dir).items():
if stem in session_keys_by_stem:
continue
for stem, files in transcripts:
files.signature = activity_by_stem[os.path.normcase(stem)]
identity = (_TRANSCRIPT_SOURCE, stem)
row = existing_by_source.get(identity)
cached_key = row.get("key") if row is not None else None
@@ -135,22 +148,23 @@ def _reconcile_index(session_manager: SessionManager) -> tuple[list[dict[str, An
if key is not None and row is not None and _indexed_transcript_row_matches(
row,
key,
webui_dir,
files.signature,
):
rows.append(row)
expected_sources.add(identity)
continue
changed = True
scanned = _scan_transcript_row(key, stem, paths, webui_dir)
scanned = _scan_transcript_row(key, stem, files, webui_dir)
scanned_key = scanned.get("key") if scanned is not None else None
if scanned is not None and scanned_key not in session_paths:
if scanned is not None and scanned_key not in session_keys:
rows.append(scanned)
expected_sources.add(identity)
if set(existing_by_source) != expected_sources:
changed = True
if existing_rows is not None and rows != existing_rows:
transcript_rows = [row for row in rows if row.get(_ROW_SOURCE_FIELD) == _TRANSCRIPT_SOURCE]
if existing_rows is not None and transcript_rows != existing_rows:
changed = True
return rows, changed
@@ -193,38 +207,11 @@ def _write_index_rows(sessions_dir: Path, rows: list[dict[str, Any]]) -> None:
tmp_path.unlink(missing_ok=True)
def _file_signature(path: Path) -> dict[str, int]:
stat = path.stat()
return {"mtime_ns": stat.st_mtime_ns, "size": stat.st_size}
def _indexed_row_matches_file(row: dict[str, Any], path: Path, webui_dir: Path) -> bool:
if not all(isinstance(row.get(key), str) for key in ("key", "created_at", "updated_at")):
return False
if not isinstance(row.get("title", ""), str) or not isinstance(row.get("preview", ""), str):
return False
if not isinstance(row.get(_WORKSPACE_SCOPE_PRESENT_FIELD), bool):
return False
if row.get(_ROW_SOURCE_FIELD) != _SESSION_SOURCE or row.get("file") != path.name:
return False
try:
signature = _file_signature(path)
except OSError:
return False
activity_signature = _webui_activity_signature(str(row.get("key")), webui_dir)
return (
row.get("mtime_ns") == signature["mtime_ns"]
and row.get("size") == signature["size"]
and row.get(_WEBUI_ACTIVITY_MTIME_NS) == activity_signature[_WEBUI_ACTIVITY_MTIME_NS]
and row.get(_WEBUI_ACTIVITY_SIZE) == activity_signature[_WEBUI_ACTIVITY_SIZE]
and row.get(_WEBUI_ACTIVITY_FILES) == activity_signature[_WEBUI_ACTIVITY_FILES]
)
def _indexed_transcript_row_matches(
row: dict[str, Any],
session_key: str,
webui_dir: Path,
signature: dict[str, int],
) -> bool:
if not all(isinstance(row.get(key), str) for key in ("key", "created_at", "updated_at")):
return False
@@ -236,7 +223,6 @@ def _indexed_transcript_row_matches(
return False
if not isinstance(row.get(_WORKSPACE_SCOPE_PRESENT_FIELD), bool):
return False
signature = _webui_activity_signature(session_key, webui_dir)
return (
row.get(_WEBUI_ACTIVITY_MTIME_NS) == signature[_WEBUI_ACTIVITY_MTIME_NS]
and row.get(_WEBUI_ACTIVITY_SIZE) == signature[_WEBUI_ACTIVITY_SIZE]
@@ -309,72 +295,43 @@ def _indexed_workspace_scope_fields(metadata: object) -> dict[str, object]:
}
def _preview_from_messages(messages: list[dict[str, Any]]) -> str:
fallback_preview = ""
scanned_records = 0
scanned_chars = 0
for item in messages:
scanned_records += 1
scanned_chars += len(json.dumps(item, ensure_ascii=False)) + 1
if (
scanned_records > _SESSION_LIST_PREVIEW_MAX_RECORDS
or scanned_chars > _SESSION_LIST_PREVIEW_MAX_CHARS
):
break
if is_hidden_history_message(item):
continue
text = _message_preview_text(item)
if not text:
continue
if item.get("role") == "user":
return text
if not fallback_preview and item.get("role") == "assistant":
fallback_preview = text
return fallback_preview
def _read_webui_files(webui_dir: Path) -> dict[str, _WebuiFiles]:
"""Discover present display files once per request, including all segment activity."""
files_by_stem: dict[str, _WebuiFiles] = {}
def _webui_transcript_record_paths(stem: str, webui_dir: Path) -> tuple[Path, ...]:
paths: list[Path] = []
segments_dir = webui_dir / f"{stem}{_TRANSCRIPT_SEGMENTS_SUFFIX}"
if segments_dir.is_dir() and not segments_dir.is_symlink():
def add_file(stem: str, entry: os.DirEntry[str]) -> None:
try:
paths.extend(
sorted(
path
for path in segments_dir.glob("*.jsonl")
if path.is_file() and not path.is_symlink()
)
)
info = entry.stat(follow_symlinks=False)
except OSError:
pass
active = webui_dir / f"{stem}.jsonl"
if active.is_file() and not active.is_symlink():
paths.append(active)
return tuple(paths)
return
if not stat.S_ISREG(info.st_mode):
return
files = files_by_stem.setdefault(stem, _WebuiFiles())
signature = files.signature
signature[_WEBUI_ACTIVITY_MTIME_NS] = max(signature[_WEBUI_ACTIVITY_MTIME_NS], info.st_mtime_ns)
signature[_WEBUI_ACTIVITY_SIZE] += info.st_size
signature[_WEBUI_ACTIVITY_FILES] += 1
if os.path.normcase(entry.name).endswith(".jsonl"):
files.records.append((Path(entry.path), info.st_mtime))
def _webui_transcript_sources(webui_dir: Path) -> dict[str, tuple[Path, ...]]:
stems: set[str] = set()
try:
entries = tuple(webui_dir.iterdir())
with os.scandir(webui_dir) as entries:
for entry in entries:
name = os.path.normcase(entry.name)
if name.endswith(_TRANSCRIPT_SEGMENTS_SUFFIX) and entry.is_dir(follow_symlinks=False):
stem = entry.name[:-len(_TRANSCRIPT_SEGMENTS_SUFFIX)]
try:
with os.scandir(entry.path) as segments:
for segment in segments:
add_file(stem, segment)
except OSError:
pass
elif name.endswith((".jsonl", ".json")):
add_file(entry.name.rsplit(".", 1)[0], entry)
except OSError:
return {}
for path in entries:
if path.is_symlink():
continue
if path.is_file() and path.suffix == ".jsonl":
stem = path.stem
elif path.is_dir() and path.name.endswith(_TRANSCRIPT_SEGMENTS_SUFFIX):
stem = path.name.removesuffix(_TRANSCRIPT_SEGMENTS_SUFFIX)
else:
continue
if stem.startswith(_WEBUI_SESSION_STEM_PREFIX):
stems.add(stem)
return {
stem: paths
for stem in sorted(stems)
if (paths := _webui_transcript_record_paths(stem, webui_dir))
}
pass
return files_by_stem
def _transcript_record(line: str) -> dict[str, Any] | None:
@@ -392,48 +349,6 @@ def _valid_transcript_session_key(key: str, stem: str) -> bool:
return _WEBUI_CHAT_ID_RE.fullmatch(chat_id) is not None and SessionManager.safe_key(key) == stem
def _webui_activity_paths(session_key: str, webui_dir: Path) -> list[Path]:
stem = SessionManager.safe_key(session_key)
paths = [
webui_dir / f"{stem}.jsonl",
webui_dir / f"{stem}.json",
]
segments_dir = webui_dir / f"{stem}{_TRANSCRIPT_SEGMENTS_SUFFIX}"
if segments_dir.is_dir() and not segments_dir.is_symlink():
try:
paths.extend(
sorted(
path
for path in segments_dir.iterdir()
if path.is_file() and not path.is_symlink()
)
)
except OSError:
pass
return paths
def _webui_activity_signature(session_key: str, webui_dir: Path) -> dict[str, int]:
latest_mtime_ns = 0
total_size = 0
file_count = 0
for path in _webui_activity_paths(session_key, webui_dir):
try:
stat = path.stat()
except OSError:
continue
if not path.is_file():
continue
file_count += 1
latest_mtime_ns = max(latest_mtime_ns, stat.st_mtime_ns)
total_size += stat.st_size
return {
_WEBUI_ACTIVITY_MTIME_NS: latest_mtime_ns,
_WEBUI_ACTIVITY_SIZE: total_size,
_WEBUI_ACTIVITY_FILES: file_count,
}
def _webui_activity_updated_at(signature: dict[str, int]) -> str | None:
mtime_ns = signature.get(_WEBUI_ACTIVITY_MTIME_NS, 0)
if mtime_ns <= 0:
@@ -456,23 +371,6 @@ def _latest_updated_at(stored: str | None, activity: str | None) -> str | None:
return stored
def _visible_message_timestamp(item: dict[str, Any]) -> str | None:
if item.get("role") not in _VISIBLE_TRANSCRIPT_ROLES:
return None
if is_hidden_history_message(item):
return None
timestamp = item.get("timestamp")
return timestamp if isinstance(timestamp, str) else None
def _last_visible_message_at(messages: list[dict[str, Any]]) -> str | None:
latest: str | None = None
for item in messages:
timestamp = _visible_message_timestamp(item)
if timestamp is not None:
latest = _latest_updated_at(latest, timestamp)
return latest
def _visible_activity_updated_at(
stored: str | None,
@@ -482,37 +380,12 @@ def _visible_activity_updated_at(
return _latest_updated_at(visible_message_at, webui_activity) or stored
def _indexed_row_for_session(session: Session, path: Path, webui_dir: Path) -> dict[str, Any]:
signature = _file_signature(path)
activity_signature = _webui_activity_signature(session.key, webui_dir)
activity_updated_at = _webui_activity_updated_at(activity_signature)
visible_message_at = _last_visible_message_at(session.messages)
return {
"key": session.key,
"created_at": session.created_at.isoformat(),
"updated_at": _visible_activity_updated_at(
session.updated_at.isoformat(),
visible_message_at,
activity_updated_at,
),
"title": _metadata_title(session.metadata),
"preview": _preview_from_messages(session.messages),
_MODEL_PRESET_FIELD: model_preset_from_metadata(session.metadata),
"recovery_state": recovery_state_from_metadata(session.metadata),
**_indexed_workspace_scope_fields(session.metadata),
_ROW_SOURCE_FIELD: _SESSION_SOURCE,
"file": path.name,
"mtime_ns": signature["mtime_ns"],
"size": signature["size"],
**activity_signature,
}
def _transcript_preview(record: dict[str, Any]) -> tuple[str, str]:
text = record.get("text")
if not isinstance(text, str) or not text.strip():
return "", ""
preview = _message_preview_text({"content": text})
preview = message_preview_text({"content": text})
if not preview:
return "", ""
event = record.get("event")
@@ -543,13 +416,10 @@ def _transcript_created_at(record: dict[str, Any]) -> str | None:
def _scan_transcript_row(
session_key: str | None,
stem: str,
paths: tuple[Path, ...],
files: _WebuiFiles,
webui_dir: Path,
) -> dict[str, Any] | None:
path_key = session_key or webui_session_key(
stem.removeprefix(_WEBUI_SESSION_STEM_PREFIX)
)
signature = _webui_activity_signature(path_key, webui_dir)
signature = files.signature
activity_updated_at = _webui_activity_updated_at(signature)
if activity_updated_at is None:
return None
@@ -560,6 +430,7 @@ def _scan_transcript_row(
saw_record = False
scanned_records = 0
scanned_chars = 0
paths = [path for path, _ in sorted(files.records, key=lambda item: (item[0].parent == webui_dir, item[0]))]
for path in paths:
try:
with open(path, encoding="utf-8") as handle:
@@ -606,7 +477,7 @@ def _scan_transcript_row(
if created_at is None:
try:
earliest_mtime = min(path.stat().st_mtime for path in paths)
earliest_mtime = min(mtime for _, mtime in files.records)
created_at = datetime.fromtimestamp(earliest_mtime).isoformat()
except (OSError, OverflowError, ValueError):
created_at = activity_updated_at
@@ -625,95 +496,3 @@ def _scan_transcript_row(
"size": signature[_WEBUI_ACTIVITY_SIZE],
**signature,
}
def _scan_session_row(
session_manager: SessionManager,
path: Path,
webui_dir: Path,
) -> dict[str, Any] | None:
storage_key = SessionManager._session_key_from_path(path) # pyright: ignore[reportPrivateUsage]
if storage_key is None:
return None
try:
signature = _file_signature(path)
with open(path, encoding="utf-8") as f:
first_line = f.readline().strip()
if not first_line:
return None
data = json.loads(first_line)
if data.get("_type") != "metadata":
return None
preview = ""
fallback_preview = ""
visible_message_at = None
preview_done = False
scanned_records = 0
scanned_chars = 0
for line in f:
if not line.strip():
continue
if _is_provider_state_record_line(line):
continue
item = json.loads(line)
if item.get("_type") == _PROVIDER_STATE_RECORD_TYPE:
continue
timestamp = _visible_message_timestamp(item)
if timestamp is not None:
visible_message_at = _latest_updated_at(visible_message_at, timestamp)
if not preview_done:
scanned_records += 1
scanned_chars += len(line)
if (
scanned_records > _SESSION_LIST_PREVIEW_MAX_RECORDS
or scanned_chars > _SESSION_LIST_PREVIEW_MAX_CHARS
):
preview_done = True
continue
if item.get("_type") == "metadata":
continue
if is_hidden_history_message(item):
continue
text = _message_preview_text(item)
if not text:
continue
if item.get("role") == "user":
preview = text
preview_done = True
continue
if not fallback_preview and item.get("role") == "assistant":
fallback_preview = text
created_at_s = data.get("created_at")
updated_at_s = data.get("updated_at")
if not created_at_s or not updated_at_s:
fallback_time = datetime.fromtimestamp(signature["mtime_ns"] / 1e9).isoformat()
created_at_s = created_at_s or fallback_time
updated_at_s = updated_at_s or fallback_time
key = data.get("key") or storage_key
metadata = data.get("metadata", {})
activity_signature = _webui_activity_signature(key, webui_dir)
activity_updated_at = _webui_activity_updated_at(activity_signature)
return {
"key": key,
"created_at": created_at_s,
"updated_at": _visible_activity_updated_at(
updated_at_s,
visible_message_at,
activity_updated_at,
),
"title": _metadata_title(metadata),
"preview": preview or fallback_preview,
_MODEL_PRESET_FIELD: model_preset_from_metadata(metadata),
"recovery_state": recovery_state_from_metadata(metadata),
**_indexed_workspace_scope_fields(metadata),
_ROW_SOURCE_FIELD: _SESSION_SOURCE,
"file": path.name,
"mtime_ns": signature["mtime_ns"],
"size": signature["size"],
**activity_signature,
}
except Exception:
repaired = session_manager._repair(storage_key) # pyright: ignore[reportPrivateUsage]
if repaired is None:
return None
return _indexed_row_for_session(repaired, path, webui_dir)
+9 -7
View File
@@ -11,6 +11,7 @@ from nanobot.providers.base import LLMUsage
from nanobot.session.goal_state import goal_state_ws_blob
from nanobot.session.model_selection import model_preset_from_metadata
from nanobot.session.recovery import recovery_state_from_metadata
from nanobot.session.state import SessionState
from nanobot.session.webui_turns import websocket_turn_id, websocket_turn_wall_started_at
if TYPE_CHECKING:
@@ -20,7 +21,8 @@ if TYPE_CHECKING:
class SessionMetadataReader(Protocol):
"""Narrow persisted-session dependency used by WebUI projections."""
def read_session_metadata(self, key: str) -> dict[str, Any] | None: ...
@property
def state(self) -> SessionState: ...
class WebUISessionProjection:
@@ -46,11 +48,11 @@ class WebUISessionProjection:
except SubagentControlError:
return None
def attach_fields(self, session_key: str) -> dict[str, Any]:
async def attach_fields(self, session_key: str) -> dict[str, Any]:
"""Return the session runtime facts sent with an attach handshake."""
if self._sessions is None:
return {}
snapshot = self._sessions.read_session_metadata(session_key)
snapshot = await self._sessions.state.read_metadata(session_key)
raw_metadata = snapshot.get("metadata") if snapshot is not None else None
metadata = cast(dict[str, object], raw_metadata) if isinstance(raw_metadata, dict) else None
@@ -71,10 +73,10 @@ class WebUISessionProjection:
fields["usage"] = usage.to_turn_dict()
return fields
def hydration_events(self, session_key: str, chat_id: str) -> tuple[dict[str, Any], ...]:
async def hydration_events(self, session_key: str, chat_id: str) -> tuple[dict[str, Any], ...]:
"""Return reconnect events for durable and same-process session state."""
events: list[dict[str, Any]] = []
goal_state = self.persisted_goal_state(session_key)
goal_state = await self.persisted_goal_state(session_key)
if goal_state is not None:
events.append(
{
@@ -97,11 +99,11 @@ class WebUISessionProjection:
events.append(event)
return tuple(events)
def persisted_goal_state(self, session_key: str) -> dict[str, Any] | None:
async def persisted_goal_state(self, session_key: str) -> dict[str, Any] | None:
"""Return an actionable persisted goal state for reconnect hydration."""
if self._sessions is None:
return None
snapshot = self._sessions.read_session_metadata(session_key)
snapshot = await self._sessions.state.read_metadata(session_key)
raw_metadata = snapshot.get("metadata") if snapshot is not None else None
metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
goal_state = goal_state_ws_blob(metadata)
+14 -4
View File
@@ -1822,7 +1822,11 @@ class ModelSettingsHandler:
) -> SettingsRouteResult:
try:
if action == "agent-update":
payload = self.settings.mutate(operations.update_agent, request.query)
payload = await asyncio.to_thread(
self.settings.mutate,
operations.update_agent,
request.query,
)
self._refresh_runtime_config()
return SettingsRouteResult.success(
payload,
@@ -1831,7 +1835,8 @@ class ModelSettingsHandler:
)
if action == "model-update":
payload = self.settings.mutate(
payload = await asyncio.to_thread(
self.settings.mutate,
operations.update_model,
request.query,
rename_model_preset=self.settings.rename_model_preset,
@@ -1847,12 +1852,17 @@ class ModelSettingsHandler:
"provider-create": operations.create_provider,
}.get(action)
if mutation is not None:
payload = self.settings.mutate(mutation, request.query)
payload = await asyncio.to_thread(
self.settings.mutate,
mutation,
request.query,
)
self._refresh_runtime_config()
return SettingsRouteResult.success(payload, decorate_restart=True)
if action == "provider-update":
payload = self.settings.mutate(
payload = await asyncio.to_thread(
self.settings.mutate,
operations.update_provider,
request.query,
)
+11 -15
View File
@@ -16,7 +16,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.command.builtin import register_builtin_commands
from nanobot.command.router import CommandRouter
from nanobot.security.workspace_access import WorkspaceScope
from nanobot.session.manager import Session, SessionManager
from nanobot.session.manager import SessionManager
from nanobot.webui.workspaces import WebUIWorkspaceController
_TEMPORARY_CHAT_DISABLED_TOOLS = frozenset({
@@ -41,6 +41,7 @@ class TemporaryChatMessagePolicy:
"""Server-owned message rules for one active Temporary Chat."""
session_key: str
session_generation: str
workspace_scope: WorkspaceScope
require_existing_session: bool = True
hydrate_transcript: bool = False
@@ -68,9 +69,6 @@ class WebUITemporaryChats:
register_builtin_commands(self._commands)
self._owners: dict[str, object] = {}
self._owner_chat_ids: dict[object, set[str]] = {}
# Keep active sessions alive if the bounded manager cache evicts them
# between WebUI turns. SessionPolicy remains the authority below.
self._active_sessions: dict[str, Session] = {}
# Retain policy-derived tombstones until shutdown so late outbound
# events cannot create a durable transcript after a chat is discarded.
self._known_transient_chat_ids: set[str] = set()
@@ -82,10 +80,10 @@ class WebUITemporaryChats:
def _cached_session_is_transient(self, chat_id: str) -> bool:
if self._sessions is None:
return False
session = self._sessions.get_cached(self._session_key(chat_id))
return session is not None and not session.policy.persist
identity = self._sessions.state.peek_identity(self._session_key(chat_id))
return identity is not None and not identity.policy.persist
def create(self, owner: object, *, trusted_webui: bool) -> str:
async def create(self, owner: object, *, trusted_webui: bool) -> str:
"""Create a server-identified chat owned by one authenticated WebUI connection."""
if not trusted_webui:
raise TemporaryChatError("access_denied")
@@ -93,7 +91,7 @@ class WebUITemporaryChats:
raise TemporaryChatError("temporary_chat_unavailable")
chat_id = str(uuid.uuid4())
session = self._sessions.get_or_create_transient(
session = await self._sessions.state.register_transient(
self._session_key(chat_id),
disabled_tools=_TEMPORARY_CHAT_DISABLED_TOOLS,
)
@@ -101,7 +99,6 @@ class WebUITemporaryChats:
raise RuntimeError("Temporary Chat must use a non-persistent session policy")
self._owners[chat_id] = owner
self._owner_chat_ids.setdefault(owner, set()).add(chat_id)
self._active_sessions[chat_id] = session
self._known_transient_chat_ids.add(chat_id)
return chat_id
@@ -119,8 +116,8 @@ class WebUITemporaryChats:
if self._owners.get(chat_id) is not owner or self._sessions is None:
raise TemporaryChatError("temporary_chat_unavailable")
session = self._sessions.get_cached(self._session_key(chat_id))
if session is None:
identity = self._sessions.state.peek_identity(self._session_key(chat_id))
if identity is None:
raise TemporaryChatError("temporary_chat_unavailable")
command = self._commands.command_name(content)
@@ -129,6 +126,7 @@ class WebUITemporaryChats:
return TemporaryChatMessagePolicy(
session_key=self._session_key(chat_id),
session_generation=identity.generation,
workspace_scope=self._workspaces.restricted_default_scope(),
)
@@ -193,10 +191,9 @@ class WebUITemporaryChats:
session_key = self._session_key(chat_id)
self._forget_owner(owner, chat_id)
self._active_sessions.pop(chat_id, None)
self._discard_media(chat_id)
if self._sessions is not None:
self._sessions.invalidate(session_key)
await self._sessions.state.discard(session_key)
await self._bus.publish_inbound(
InboundMessage(
channel=self._channel_name,
@@ -215,8 +212,7 @@ class WebUITemporaryChats:
for chat_id in tuple(self._owners):
self._discard_media(chat_id)
if self._sessions is not None:
self._sessions.invalidate(self._session_key(chat_id))
self._sessions.state.forget_transient(self._session_key(chat_id))
self._owners.clear()
self._owner_chat_ids.clear()
self._active_sessions.clear()
self._known_transient_chat_ids.clear()
+62 -18
View File
@@ -286,6 +286,19 @@ class WebUIWorkspaceController:
if self._sessions is None:
return self.default_scope()
data = self._sessions.read_session_metadata(session_key)
return self._scope_from_snapshot(data)
async def async_scope_for_session_key(self, session_key: str) -> WorkspaceScope:
draft = self._draft_scopes.get(session_key)
if draft is not None:
self._draft_scopes.move_to_end(session_key)
return draft
if self._sessions is None:
return self.default_scope()
data = await self._sessions.state.read_metadata(session_key)
return self._scope_from_snapshot(data)
def _scope_from_snapshot(self, data: dict[str, Any] | None) -> WorkspaceScope:
if not isinstance(data, dict):
return self.default_scope()
metadata = data.get("metadata", {})
@@ -348,14 +361,18 @@ class WebUIWorkspaceController:
write_webui_workspace_state(state)
return [{"name": Path(item).name or item, "path": item} for item in favorites]
def scope_from_envelope(
async def scope_from_envelope(
self,
envelope: dict[str, Any],
*,
session_key: str | None,
can_change_project: bool,
) -> WorkspaceScope:
current = self.scope_for_session_key(session_key) if session_key else self.default_scope()
current = (
await self.async_scope_for_session_key(session_key)
if session_key
else self.default_scope()
)
raw = envelope.get(WORKSPACE_SCOPE_METADATA_KEY)
if raw is None:
scope = current
@@ -373,19 +390,19 @@ class WebUIWorkspaceController:
)
return scope
def scope_for_new_chat(
async def scope_for_new_chat(
self,
envelope: dict[str, Any],
*,
can_change_project: bool,
) -> WorkspaceScope:
return self.scope_from_envelope(
return await self.scope_from_envelope(
envelope,
session_key=None,
can_change_project=can_change_project,
)
def scope_for_set_request(
async def scope_for_set_request(
self,
envelope: dict[str, Any],
*,
@@ -395,13 +412,13 @@ class WebUIWorkspaceController:
) -> WorkspaceScope:
if chat_running:
raise WorkspaceScopeError("chat_running", status=409)
return self.scope_from_envelope(
return await self.scope_from_envelope(
envelope,
session_key=webui_session_key(chat_id),
can_change_project=can_change_project,
)
def scope_for_message(
async def scope_for_message(
self,
envelope: dict[str, Any],
*,
@@ -409,7 +426,7 @@ class WebUIWorkspaceController:
chat_running: bool,
can_change_project: bool,
) -> WorkspaceScope:
scope = self.scope_from_envelope(
scope = await self.scope_from_envelope(
envelope,
session_key=webui_session_key(chat_id),
can_change_project=can_change_project,
@@ -417,29 +434,56 @@ class WebUIWorkspaceController:
if (
WORKSPACE_SCOPE_METADATA_KEY in envelope
and chat_running
and scope.metadata() != self.scope_for_session_key(webui_session_key(chat_id)).metadata()
and scope.metadata()
!= (await self.async_scope_for_session_key(webui_session_key(chat_id))).metadata()
):
raise WorkspaceScopeError("chat_running", status=409)
return scope
def persist_scope(self, chat_id: str, scope: WorkspaceScope) -> None:
session_key = webui_session_key(chat_id)
async def persist_scope(
self,
chat_id: str,
scope: WorkspaceScope,
*,
session_key: str | None = None,
expected_generation: str | None = None,
) -> tuple[str | None, bool]:
session_key = session_key or webui_session_key(chat_id)
generation = expected_generation
created = False
if self._sessions is not None:
session = self._sessions.get_or_create(session_key)
session.metadata["webui"] = True
session.metadata[WORKSPACE_SCOPE_METADATA_KEY] = scope.metadata()
self._sessions.save(session)
generation, created = await self._sessions.state.open_with_metadata(
session_key,
{"webui": True, WORKSPACE_SCOPE_METADATA_KEY: scope.metadata()},
expected_generation=generation,
)
self._draft_scopes.pop(session_key, None)
remember_webui_project(scope.project_path)
return generation, created
def stage_scope(self, chat_id: str, scope: WorkspaceScope) -> None:
async def rollback_scope_admission(
self,
session_key: str,
generation: str | None,
*,
created: bool,
) -> None:
"""Remove a newly opened session when transport admission fails."""
if not created or generation is None or self._sessions is None:
return
await self._sessions.state.delete(
session_key,
expected_generation=generation,
)
async def stage_scope(self, chat_id: str, scope: WorkspaceScope) -> None:
"""Keep a new chat's scope transient until its first accepted message."""
session_key = webui_session_key(chat_id)
if (
self._sessions is not None
and self._sessions.read_session_metadata(session_key) is not None
and await self._sessions.state.read_metadata(session_key) is not None
):
self.persist_scope(chat_id, scope)
await self.persist_scope(chat_id, scope)
return
remember_webui_project(scope.project_path)
self._draft_scopes[session_key] = scope
+58 -25
View File
@@ -35,6 +35,7 @@ from nanobot.cron.types import CronJob, CronSchedule
from nanobot.security.workspace_access import WorkspaceScope, WorkspaceScopeError
from nanobot.session.manager import SessionManager
from nanobot.session.session_handles import (
SessionHandle,
SessionHandleResolver,
)
from nanobot.triggers.local_types import LocalTrigger
@@ -837,7 +838,7 @@ class GatewayHTTPHandler:
m = re.fullmatch(r"/api/sessions/([^/]+)/subagents", got)
if m:
return self._handle_subagents_get(request, m.group(1))
return await self._handle_subagents_get(request, m.group(1))
m = re.match(r"^/api/sessions/([^/]+)/delete$", got)
if m:
@@ -866,7 +867,7 @@ class GatewayHTTPHandler:
return _http_error(exc.status, str(exc))
return _http_json_response(result)
def _handle_subagents_get(self, request: WsRequest, key: str) -> Response:
async def _handle_subagents_get(self, request: WsRequest, key: str) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
session_key = _decode_api_key(key)
@@ -877,7 +878,7 @@ class GatewayHTTPHandler:
if self.subagent_manager is None:
return _http_error(503, "subagent manager unavailable")
try:
statuses = self.subagent_manager.statuses_for_session(session_key)
statuses = await self.subagent_manager.read_statuses_for_session(session_key)
except (OSError, SubagentSessionError):
return _http_error(503, "task history unavailable")
return _http_json_response({
@@ -958,20 +959,47 @@ class GatewayHTTPHandler:
return _http_error(401, "Unauthorized")
if self.session_manager is None:
return _http_error(503, "session manager unavailable")
payload = await asyncio.to_thread(self._sessions_list_payload)
return _http_json_response(
payload,
accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"),
)
accept_encoding = _combined_list_header(request.headers, "Accept-Encoding")
def _sessions_list_payload(self) -> dict[str, Any]:
def render(stored: list[dict[str, Any]]) -> Response | None:
payload = self._sessions_list_from_snapshot(stored)
if payload is None:
return None
return _http_json_response(payload, accept_encoding=accept_encoding)
response = await self.session_manager.state.query_metadata(render)
if response is None:
handles = await SessionHandleResolver(self.session_manager).alist_all_by_key()
def render_allocated(stored: list[dict[str, Any]]) -> Response:
return _http_json_response(
self._sessions_list_payload(handles, stored), accept_encoding=accept_encoding,
)
response = await self.session_manager.state.query_metadata(render_allocated)
return response
def _sessions_list_from_snapshot(
self, stored_sessions: list[dict[str, Any]],
) -> dict[str, Any] | None:
assert self.session_manager is not None
handles = SessionHandleResolver(self.session_manager).handles_from_metadata(stored_sessions)
if handles is None:
return None
return self._sessions_list_payload(handles, stored_sessions)
def _sessions_list_payload(
self,
handles: dict[str, SessionHandle],
stored_sessions: list[dict[str, Any]],
) -> dict[str, Any]:
assert self.session_manager is not None
from nanobot.session.webui_turns import websocket_turn_wall_started_at
sessions = list_webui_sessions(self.session_manager)
handles = SessionHandleResolver(self.session_manager).list_all_by_key()
sessions = list_webui_sessions(self.session_manager, stored_sessions)
cleaned: list[dict[str, Any]] = []
default_scope: WorkspaceScope | None = None
scopes: dict[str, WorkspaceScope] = {}
for s in sessions:
key = s.get("key")
if not (isinstance(key, str) and is_webui_session_key(key)):
@@ -992,11 +1020,16 @@ class GatewayHTTPHandler:
if default_scope is None:
default_scope = self.workspaces.default_scope()
scope_present, raw_scope = indexed_workspace_scope(s)
scope = self.workspaces.scope_for_indexed_metadata(
raw_scope,
scope_present=scope_present,
default_scope=default_scope,
)
if scope_present:
scope_key = json.dumps(raw_scope, ensure_ascii=False, sort_keys=True)
scope = scopes.get(scope_key)
if scope is None:
scope = self.workspaces.scope_for_indexed_metadata(
raw_scope, scope_present=True, default_scope=default_scope,
)
scopes[scope_key] = scope
else:
scope = default_scope
row["workspace_scope"] = scope.payload()
handle = handles.get(key)
if handle is not None:
@@ -1307,7 +1340,7 @@ class GatewayHTTPHandler:
for job in automation_jobs:
if isinstance(job, LocalTrigger):
if self.local_trigger_store is not None:
self.local_trigger_store.delete(job.id)
await asyncio.to_thread(self.local_trigger_store.delete, job.id)
elif self.cron_service is not None:
self.cron_service.remove_job(job.id)
draft_deleted = self.workspaces.discard_draft_scope(decoded_key)
@@ -1315,8 +1348,8 @@ class GatewayHTTPHandler:
await self.discard_session(decoded_key)
elif self.subagent_manager is not None:
await self.subagent_manager.cancel_by_session(decoded_key)
session_deleted = self.session_manager.delete_session(decoded_key)
transcript_deleted = delete_webui_thread(decoded_key)
session_deleted = await self.session_manager.state.delete(decoded_key)
transcript_deleted = await asyncio.to_thread(delete_webui_thread, decoded_key)
return _http_json_response(
{"deleted": bool(draft_deleted or session_deleted or transcript_deleted)}
)
@@ -1333,7 +1366,7 @@ class GatewayHTTPHandler:
if got == "/api/webui/automations/result":
return await self._handle_webui_automation_result(request)
if got == "/api/webui/automations/chats":
return self._handle_webui_automation_chats(request)
return await self._handle_webui_automation_chats(request)
m = re.match(r"^/api/webui/automations/(enable|disable|delete|run|update|change-chat)$", got)
if m:
return await self._handle_webui_automation_action(request, m.group(1))
@@ -1385,22 +1418,22 @@ class GatewayHTTPHandler:
)
)
def _automation_chats(self, job: CronJob) -> list[AutomationChat]:
async def _automation_chats(self, job: CronJob) -> list[AutomationChat]:
if self.session_manager is None:
return []
return automation_chats(
return await automation_chats(
job, self.session_manager, self.workspaces,
self.channel_runtime_status() if self.channel_runtime_status else {},
)
def _handle_webui_automation_chats(self, request: WsRequest) -> Response:
async def _handle_webui_automation_chats(self, request: WsRequest) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
job_id = _query_first(_request_query(request), "id") or ""
job = self.cron_service.get_job(job_id) if self.cron_service else None
if job is None or not is_bound_cron_job(job):
return _http_error(404, "automation has no movable chat")
chats = self._automation_chats(job)
chats = await self._automation_chats(job)
current = next((chat for chat in chats
if chat.binding.session_key == job.payload.session_key), None)
return _http_json_response({
@@ -1504,7 +1537,7 @@ class GatewayHTTPHandler:
return _http_error(400, "invalid automation chat payload")
if job.id in self._pending_cron_job_ids_for_all():
return _http_error(409, "automation_chat_busy")
target = next((chat for chat in self._automation_chats(job)
target = next((chat for chat in await self._automation_chats(job)
if chat.id == values["target_id"]), None)
if target is None or not target.available:
return _http_error(409, "automation_chat_unavailable")
+454
View File
@@ -0,0 +1,454 @@
"""Reproducible, synthetic JSONL/SQLite storage and ownership comparison."""
from __future__ import annotations
import argparse
import asyncio
import errno
import gc
import hashlib
import json
import math
import os
import platform
import shutil
import sqlite3
import statistics
import subprocess
import sys
import tempfile
import time
from datetime import UTC, datetime
from importlib.metadata import distributions
from pathlib import Path
try:
import resource
except ModuleNotFoundError: # Windows
resource = None # type: ignore[assignment]
def stats(samples):
values = sorted(samples)
return {
"count": len(values), "p50_ms": statistics.median(values),
"p95_ms": values[max(0, math.ceil(len(values) * .95) - 1)],
"max_ms": max(values), "mean_ms": statistics.mean(values),
}
def sync_file(path):
with path.open("rb") as handle:
os.fsync(handle.fileno())
try:
fd = os.open(path.parent, os.O_RDONLY)
except PermissionError:
return
try:
try:
os.fsync(fd)
except OSError as exc:
if exc.errno != errno.EINVAL:
raise
finally:
os.close(fd)
def _sha256(path):
return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None
def _git(repo, *args):
return subprocess.run(
["git", *args],
cwd=repo,
check=True,
capture_output=True,
text=True,
encoding="utf-8",
).stdout.strip()
def git_identity(repo):
status = _git(repo, "status", "--porcelain=v1", "--untracked-files=all")
diff = _git(repo, "diff", "--binary", "HEAD")
return {
"commit": _git(repo, "rev-parse", "HEAD"),
"branch": _git(repo, "rev-parse", "--abbrev-ref", "HEAD"),
"dirty": bool(status),
"status_sha256": hashlib.sha256(status.encode()).hexdigest(),
"tracked_diff_sha256": hashlib.sha256(diff.encode()).hexdigest(),
}
def dependency_identity(repo):
installed = sorted(
f"{(dist.metadata.get('Name') or '').casefold()}=={dist.version}"
for dist in distributions()
if dist.metadata.get("Name")
)
encoded = "\n".join(installed).encode()
return {
"installed_count": len(installed),
"installed_sha256": hashlib.sha256(encoded).hexdigest(),
"uv_lock_sha256": _sha256(repo / "uv.lock"),
}
def filesystem_identity(path):
resolved = path.resolve()
usage = shutil.disk_usage(resolved)
filesystem_type = None
mount_point = resolved.anchor
collector = "platform-fallback"
if os.name == "nt":
import ctypes
fs_name = ctypes.create_unicode_buffer(256)
root = resolved.anchor or str(resolved)
ok = ctypes.windll.kernel32.GetVolumeInformationW(
root, None, 0, None, None, None, fs_name, len(fs_name)
)
filesystem_type = fs_name.value if ok else None
collector = "GetVolumeInformationW"
else:
try:
best = ("", None)
for line in Path("/proc/self/mountinfo").read_text(encoding="utf-8").splitlines():
left, right = line.split(" - ", 1)
fields = left.split()
candidate = fields[4].replace("\\040", " ")
if str(resolved).startswith(candidate.rstrip("/") + "/") or str(resolved) == candidate:
if len(candidate) > len(best[0]):
best = (candidate, right.split()[0])
if best[0]:
mount_point, filesystem_type = best
collector = "/proc/self/mountinfo"
except (OSError, ValueError, IndexError):
pass
return {
"path": str(resolved),
"device": os.stat(resolved).st_dev,
"mount_point": mount_point,
"filesystem_type": filesystem_type,
"collector": collector,
"total_bytes": usage.total,
"free_bytes": usage.free,
}
def peak_rss_bytes():
if resource is not None:
value = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
return value if sys.platform == "darwin" else value * 1024
if os.name == "nt":
import ctypes
from ctypes import wintypes
class ProcessMemoryCounters(ctypes.Structure):
_fields_ = [
("cb", wintypes.DWORD),
("PageFaultCount", wintypes.DWORD),
("PeakWorkingSetSize", ctypes.c_size_t),
("WorkingSetSize", ctypes.c_size_t),
("QuotaPeakPagedPoolUsage", ctypes.c_size_t),
("QuotaPagedPoolUsage", ctypes.c_size_t),
("QuotaPeakNonPagedPoolUsage", ctypes.c_size_t),
("QuotaNonPagedPoolUsage", ctypes.c_size_t),
("PagefileUsage", ctypes.c_size_t),
("PeakPagefileUsage", ctypes.c_size_t),
]
counters = ProcessMemoryCounters()
counters.cb = ctypes.sizeof(counters)
process = ctypes.windll.kernel32.GetCurrentProcess()
if ctypes.windll.psapi.GetProcessMemoryInfo(
process, ctypes.byref(counters), counters.cb
):
return counters.PeakWorkingSetSize
return None
def allocated_bytes(path):
blocks = getattr(path.stat(), "st_blocks", None)
return blocks * 512 if isinstance(blocks, int) else None
async def main(args):
started_at_utc = datetime.now(UTC).isoformat()
sys.path.insert(0, str(args.repo.resolve()))
import nanobot.session.manager as session_module
from nanobot.config.loader import set_config_path
from nanobot.session.manager import Session, SessionManager
assert Path(session_module.__file__).is_relative_to(args.repo.resolve())
sqlite = args.variant == "sqlite"
durable = args.variant != "jsonl-default"
if not sqlite:
from nanobot.session.io import call
records = []
managers = []
stamp = datetime(2026, 1, 1)
content = ("benchmark message: evidence and deterministic data. " * 12)[:512]
def message(index, role=None):
return {
"role": role or ("user" if index % 2 == 0 else "assistant"),
"content": f"{index:06d} {content}",
"timestamp": stamp.isoformat(),
}
def new_manager(root, name):
manager = SessionManager(root / name / "workspace", sessions_root=root / name / "storage")
managers.append(manager)
return manager
def save(manager, session, *, seed=False):
if sqlite:
manager.save(session)
else:
manager.save(session, fsync=seed or durable)
def seed(manager, key, count):
session = Session(
key=key, messages=[message(i) for i in range(count)],
metadata={"title": f"Conversation {key}", "webui": True},
created_at=stamp, updated_at=stamp,
)
save(manager, session, seed=True)
return session
def add_result(name, size, samples, **extra):
result = {"operation": name, "history_messages": size, **stats(samples),
"samples_ms": samples, **extra}
records.append(result)
print(f"{args.variant} trial={args.trial} {name} n={size}: "
f"p50={result['p50_ms']:.3f}ms p95={result['p95_ms']:.3f}ms", flush=True)
def measure_sync(name, size, operation, *, iterations=None):
for i in range(3):
operation(i)
gc.collect()
samples = []
for i in range(iterations or args.iterations):
started = time.perf_counter()
operation(i + 3)
samples.append((time.perf_counter() - started) * 1000)
add_result(name, size, samples)
async def measure_async(name, size, operation):
for i in range(3):
await operation(i)
gc.collect()
samples = []
for i in range(args.iterations):
started = time.perf_counter()
await operation(i + 3)
samples.append((time.perf_counter() - started) * 1000)
add_result(name, size, samples)
async def get(manager, key):
return await manager.state.get(key) if sqlite else await call(manager.get_or_create, key)
async def turn(manager, key, index):
session = await get(manager, key)
session.add_message("user", f"turn-{index}: {content}")
session.metadata["pending_user_turn"] = True
if sqlite:
await manager.state.prepare_input(session)
else:
await call(save, manager, session)
session.add_message("assistant", f"answer-{index}: {content}")
session.metadata.pop("pending_user_turn", None)
if sqlite:
await manager.state.finish_turn(session)
else:
await call(save, manager, session)
def checkpoint_jsonl(manager, session, payload):
session.metadata["runtime_checkpoint"] = payload
manager.save_runtime_checkpoint(session)
if durable:
sync_file(manager._jsonl_store.get_runtime_checkpoint_path(session.key))
args.output.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix=f"{args.variant}-{args.trial}-", dir=args.output.parent) as raw:
root = Path(raw)
set_config_path(root / "config.json")
if not sqlite:
session_module.get_legacy_sessions_dir = lambda: root / "isolated-legacy"
for size in args.sizes:
manager = new_manager(root, f"history-{size}")
sessions = {name: seed(manager, f"websocket:{name}", size) for name in (
"append", "read", "metadata", "turn", "checkpoint", "runtime-metadata",
)}
append_session = sessions["append"]
def append(index):
append_session.add_message("user", f"append-{index}: {content}")
append_session.add_message("assistant", f"reply-{index}: {content}")
save(manager, append_session)
measure_sync("repository_append", size, append)
assert len(manager.read_session_snapshot(append_session.key).messages) == size + 2 * (args.iterations + 3)
def read(_):
loaded = manager.read_session_snapshot(sessions["read"].key)
assert len(loaded.messages) == size
measure_sync("repository_read", size, read)
def metadata(index):
updates = {"title": f"title-{index}"}
if sqlite:
assert manager.update_session_metadata(sessions["metadata"].key, updates)
else:
assert manager.update_session_metadata(sessions["metadata"].key, updates, fsync=durable)
measure_sync("repository_metadata", size, metadata)
assert manager.read_session_metadata(sessions["metadata"].key)["metadata"]["title"] == f"title-{args.iterations + 2}"
await measure_async("runtime_turn", size, lambda i: turn(manager, sessions["turn"].key, i))
assert len(manager.read_session_snapshot(sessions["turn"].key).messages) == size + 2 * (args.iterations + 3)
draft = await get(manager, sessions["checkpoint"].key)
async def checkpoint(index):
payload = {"phase": "tool-finished", "sequence": index,
"messages": [{"role": "assistant", "content": "c" * 8192}]}
if sqlite:
await manager.state.checkpoint_view(draft, payload)
else:
await call(checkpoint_jsonl, manager, draft, payload)
await measure_async("runtime_checkpoint", size, checkpoint)
assert manager.read_session_snapshot(draft.key).metadata["runtime_checkpoint"]["sequence"] == args.iterations + 2
async def runtime_metadata(index):
updates = {"title": f"runtime-title-{index}"}
key = sessions["runtime-metadata"].key
if sqlite:
await manager.state.update_metadata(key, updates)
else:
assert await call(manager.update_session_metadata, key, updates, fsync=durable)
await measure_async("runtime_metadata", size, runtime_metadata)
assert manager.read_session_metadata(sessions["runtime-metadata"].key)["metadata"]["title"] == f"runtime-title-{args.iterations + 2}"
listing = new_manager(root, "listing")
for index in range(args.list_count):
seed(listing, f"websocket:list-{index:05d}", 100)
def list_sessions(_):
rows = listing.list_sessions()
assert len(rows) == args.list_count
assert len({row["key"] for row in rows}) == args.list_count
measure_sync("list_sessions", 100, list_sessions, iterations=args.iterations)
paths = [p for p in listing.sessions_dir.rglob("*") if p.is_file()]
allocated = [allocated_bytes(path) for path in paths]
disk = {"sessions": args.list_count, "messages_per_session": 100,
"files": len(paths), "logical_bytes": sum(p.stat().st_size for p in paths),
"allocated_bytes": (
sum(value for value in allocated if value is not None)
if all(value is not None for value in allocated) else None
),
"allocated_bytes_collector": "st_blocks" if allocated and allocated[0] is not None else None}
concurrent = new_manager(root, "concurrent")
keys = [f"websocket:producer-{i}" for i in range(args.concurrency)]
for key in keys:
seed(concurrent, key, 1000)
for key in keys:
await get(concurrent, key)
running = True
lag_samples = []
latency_samples = []
event_loop = asyncio.get_running_loop()
async def heartbeat():
while running:
expected = event_loop.time() + .002
await asyncio.sleep(.002)
lag_samples.append(max(0, event_loop.time() - expected) * 1000)
async def producer(key):
for index in range(args.turns):
started = time.perf_counter()
await turn(concurrent, key, index)
latency_samples.append((time.perf_counter() - started) * 1000)
pulse = asyncio.create_task(heartbeat())
await asyncio.sleep(0)
started = time.perf_counter()
await asyncio.gather(*(producer(key) for key in keys))
elapsed = time.perf_counter() - started
running = False
await pulse
for key in keys:
loaded = concurrent.read_session_snapshot(key)
assert len(loaded.messages) == 1000 + args.turns * 2
suffix = loaded.messages[1000:]
assert [row["content"] for row in suffix[::2]] == [f"turn-{i}: {content}" for i in range(args.turns)]
assert "pending_user_turn" not in loaded.metadata
add_result("concurrent_turn", 1000, latency_samples,
concurrency=args.concurrency, turns=len(latency_samples),
duration_s=elapsed, throughput_per_s=len(latency_samples) / elapsed,
heartbeat=stats(lag_samples), heartbeat_samples_ms=lag_samples)
if sqlite:
for manager in managers:
await manager.state.aclose()
harness = Path(__file__).resolve()
result = {
"schema_version": 1,
"started_at_utc": started_at_utc,
"variant": args.variant,
"trial": args.trial,
"repo": str(args.repo.resolve()),
"target_module": str(Path(session_module.__file__).resolve()),
"git": git_identity(args.repo.resolve()),
"dependencies": dependency_identity(args.repo.resolve()),
"python": {
"executable": sys.executable,
"implementation": platform.python_implementation(),
"version": sys.version,
},
"platform": platform.platform(),
"pid": os.getpid(),
"load_average": list(os.getloadavg()) if hasattr(os, "getloadavg") else None,
"logical_cpus": os.cpu_count(),
"peak_rss_bytes": peak_rss_bytes(),
"sqlite_version": sqlite3.sqlite_version,
"parameters": {
"iterations": args.iterations,
"sizes": args.sizes,
"list_count": args.list_count,
"concurrency": args.concurrency,
"turns": args.turns,
"content_bytes": len(content.encode()),
},
"data_filesystem": filesystem_identity(args.output.parent),
"disk": disk,
"correctness": "PASS",
"harness": {"path": str(harness), "sha256": _sha256(harness)},
"operations": records,
}
args.output.write_text(json.dumps(result, indent=2) + "\n")
print(f"RESULT {args.output}", flush=True)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--repo", type=Path, required=True)
parser.add_argument("--variant", choices=["jsonl-durable", "jsonl-default", "sqlite"], required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--trial", type=int, default=0)
parser.add_argument("--iterations", type=int, default=30)
parser.add_argument("--sizes", type=int, nargs="+", default=[100, 1000, 10000])
parser.add_argument("--list-count", type=int, default=1000)
parser.add_argument("--concurrency", type=int, default=8)
parser.add_argument("--turns", type=int, default=25)
asyncio.run(main(parser.parse_args()))
-1
View File
@@ -80,7 +80,6 @@ def make_loop(
if patch_deps:
with patch("nanobot.agent.loop.ContextBuilder"), \
patch("nanobot.agent.loop.SessionManager"), \
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
return AgentLoop(**kwargs)
+21 -3
View File
@@ -21,11 +21,11 @@ def visible_message(message: dict) -> dict:
return public_history_message(message)
def save_completed_subagent(loop: AgentLoop, task_id: str, owner: str) -> None:
async def save_completed_subagent(loop: AgentLoop, task_id: str, owner: str) -> None:
"""Persist the child that owns a synthetic completion notification."""
assert loop.subagents.sessions is not None
now = time.monotonic()
loop.subagents.sessions.create(SubagentStatus(
await loop.subagents.sessions.create(SubagentStatus(
task_id=task_id, label=task_id, task_description="Background work",
owner=owner, started_at=now, finished_at=now, completed_at=time.time(),
state="done", phase="done",
@@ -34,5 +34,23 @@ def save_completed_subagent(loop: AgentLoop, task_id: str, owner: str) -> None:
async def run_session(loop: AgentLoop, msg: InboundMessage) -> None:
"""Submit input and wait for its session worker to finish."""
loop._enqueue_session_message(msg)
(await loop._enqueue_session_message(msg))
await asyncio.gather(*loop._active_tasks[loop._effective_session_key(msg)])
def mock_session_manager(*_args, **_kwargs):
"""Model the asynchronous state boundary in scheduler-only unit tests."""
from unittest.mock import AsyncMock, MagicMock
from nanobot.session.manager import Session, SessionManager
from nanobot.session.state import SessionState
manager = MagicMock(spec=SessionManager)
manager.get_or_create.side_effect = lambda key: Session(key=key)
manager.state = MagicMock(spec=SessionState)
manager.state.get = AsyncMock(side_effect=lambda key: manager.get_or_create(key))
manager.state.read = AsyncMock(return_value=None)
manager.state.read_metadata = AsyncMock(return_value=None)
manager.state.list_sessions = AsyncMock(return_value=[])
manager.state.peek.return_value = None
return manager
+165 -64
View File
@@ -1,13 +1,16 @@
"""Tests for auto compact (idle TTL) feature."""
import asyncio
import time
from datetime import datetime, timedelta
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.context import current_request_context
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
@@ -16,12 +19,14 @@ from nanobot.config.schema import AgentDefaults, Config
from nanobot.events import NO_EVENTS
from nanobot.providers.base import LLMResponse
from nanobot.runtime_context import public_history_message
from nanobot.session.keys import HEARTBEAT_SESSION_KEY
from nanobot.sdk.clients import RuntimeClient
from nanobot.session.keys import HEARTBEAT_SESSION_KEY, UNIFIED_SESSION_KEY
def _make_loop(
tmp_path: Path,
session_ttl_minutes: int = 15,
unified_session: bool = False,
) -> AgentLoop:
"""Create a minimal AgentLoop for testing."""
bus = MessageBus()
@@ -37,6 +42,7 @@ def _make_loop(
model="test-model",
context_window_tokens=128_000,
session_ttl_minutes=session_ttl_minutes,
unified_session=unified_session,
)
loop.tools.get_definitions = MagicMock(return_value=[])
return loop
@@ -94,16 +100,14 @@ def _make_fake_compact(
events=NO_EVENTS,
) -> str:
state["count"] += 1
session = loop.sessions.get_or_create(key)
session = await loop.sessions.state.get(key)
tail = list(session.messages[session.last_archived:])
if not tail:
loop.sessions.save(session)
return ""
archive_end = session.last_archived + len(tail)
archive_msgs = tail
last_active = session.updated_at
s = summary
if on_archive:
result = on_archive(archive_msgs)
@@ -111,14 +115,7 @@ def _make_fake_compact(
if track_archived is not None:
track_archived.extend(archive_msgs)
if s and s != "(nothing)":
session.metadata["_last_summary"] = {
"text": s,
"last_active": last_active.isoformat(),
}
session.commit_summary_checkpoint(s, insert_at=archive_end, last_active=last_active)
loop.sessions.save(session)
await loop.sessions.state.commit_summary(session, s, archive_end=archive_end)
return s
# Attach state for count access
@@ -142,7 +139,7 @@ async def test_heartbeat_idle_compaction_persists_summary_without_channel_notice
loop.sessions.save(session)
loop.consolidator.archive_session = AsyncMock(return_value="Heartbeat summary.")
loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
await loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
await _drain_background_tasks(loop)
loop.consolidator.archive_session.assert_awaited_once()
@@ -152,6 +149,100 @@ async def test_heartbeat_idle_compaction_persists_summary_without_channel_notice
assert loop.bus.outbound.empty()
async def test_expired_unified_turn_keeps_latest_delivery_route(tmp_path, monkeypatch):
monkeypatch.setattr("nanobot.config.home._home_path", tmp_path / "home")
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
loop = _make_loop(tmp_path / "workspace", unified_session=True)
session = loop.sessions.get_or_create(UNIFIED_SESSION_KEY)
session.metadata["last_channel"] = "telegram:old"
session.metadata["_compaction_route"] = {
"channel": "telegram", "chat_id": "old", "metadata": {},
}
session.updated_at = datetime.now() - timedelta(minutes=20)
loop.sessions.save(session)
try:
response = await loop.process_direct(
"hello", session_key=UNIFIED_SESSION_KEY, channel="discord", chat_id="new",
)
assert response is not None and response.content == "ok"
saved = await loop.sessions.state.get(UNIFIED_SESSION_KEY)
assert saved.generation == session.generation
assert saved.metadata["last_channel"] == "discord:new"
assert saved.metadata["_compaction_route"] == {
"channel": "discord", "chat_id": "new", "metadata": {},
}
finally:
await loop.aclose()
@pytest.mark.parametrize("compaction", ["idle", "compact_session", "compact_idle_session"])
async def test_turn_resuming_during_archive_commits_reply(tmp_path, monkeypatch, compaction):
monkeypatch.setattr("nanobot.config.home._home_path", tmp_path / "home")
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
loop = _make_loop(tmp_path / "workspace")
session = loop.sessions.get_or_create("cli:idle")
_add_turns(session, 1, prefix="old")
session.updated_at = datetime.now() - timedelta(minutes=20)
loop.sessions.save(session)
entered, release = asyncio.Event(), asyncio.Event()
archive_committed = asyncio.Event()
async def archive(_session, **_kwargs):
entered.set()
await release.wait()
return "Old session summary."
loop.consolidator.archive_session = archive
async def respond(**_kwargs):
request = current_request_context()
if request is not None and request.session_key == session.key:
await archive_committed.wait()
return LLMResponse(content="new reply")
loop.provider.chat_stream_with_retry.side_effect = respond
turn = None
compact_task = None
try:
if compaction == "idle":
await loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
else:
compact_task = asyncio.create_task(getattr(RuntimeClient(loop), compaction)(session.key))
await asyncio.wait_for(entered.wait(), 5)
turn = asyncio.create_task(loop.process_direct("new input", session_key=session.key))
# The pending archive only holds its own conversation's execution slot.
other = await asyncio.wait_for(
loop.process_direct("other input", session_key="cli:other"), 5,
)
assert other is not None and other.content == "new reply"
release.set()
if compact_task is not None:
await compact_task
else:
await _drain_background_tasks(loop)
archive_committed.set()
response = await asyncio.wait_for(turn, 5)
assert response is not None and response.content == "new reply"
saved = await loop.sessions.state.get(session.key)
assert saved.generation == session.generation
assert saved.metadata["_last_summary"]["text"] == "Old session summary."
assert saved.messages[-1]["content"] == "new reply"
assert saved.messages[-2]["content"].startswith("new input")
assert "pending_user_turn" not in saved.metadata
assert "runtime_checkpoint" not in saved.metadata
finally:
release.set()
archive_committed.set()
if turn is not None:
await asyncio.gather(turn, return_exceptions=True)
if compact_task is not None:
await compact_task
await loop.aclose()
class TestSessionTTLConfig:
"""Test session TTL configuration."""
@@ -202,10 +293,10 @@ class TestSessionTTLConfig:
class TestIdleScanThrottling:
"""Test scheduling of full idle-session scans."""
def test_configured_idle_scan_interval_throttles_checks(self, tmp_path, monkeypatch):
async def test_configured_idle_scan_interval_throttles_checks(self, tmp_path, monkeypatch):
"""The configured interval should reach the loop and gate session scans."""
ticks = iter((1_000.0, 1_000.0, 1_009.999, 1_010.0))
monkeypatch.setattr("nanobot.agent.loop.time.monotonic", lambda: next(ticks))
monkeypatch.setattr("nanobot.agent.loop.time", SimpleNamespace(time=time.time, monotonic=lambda: next(ticks)))
config = Config.model_validate({
"agents": {
"defaults": {
@@ -221,24 +312,24 @@ class TestIdleScanThrottling:
tool_registry=ToolRegistry(),
provider=provider,
)
loop.auto_compact.check_expired = MagicMock()
loop.auto_compact.check_expired = AsyncMock()
loop._check_expired_sessions_if_due()
await loop._check_expired_sessions_if_due()
loop.auto_compact.check_expired.assert_called_once()
loop._check_expired_sessions_if_due()
await loop._check_expired_sessions_if_due()
loop.auto_compact.check_expired.assert_called_once()
loop._check_expired_sessions_if_due()
await loop._check_expired_sessions_if_due()
assert loop.auto_compact.check_expired.call_count == 2
def test_zero_idle_scan_interval_checks_every_tick(self, tmp_path, monkeypatch):
async def test_zero_idle_scan_interval_checks_every_tick(self, tmp_path, monkeypatch):
"""An explicit zero should leave each idle tick eligible to scan."""
monkeypatch.setattr("nanobot.agent.loop.time.monotonic", lambda: 1_000.0)
monkeypatch.setattr("nanobot.agent.loop.time", SimpleNamespace(time=time.time, monotonic=lambda: 1_000.0))
loop = _make_loop(tmp_path)
loop.auto_compact.check_expired = MagicMock()
loop.auto_compact.check_expired = AsyncMock()
loop._check_expired_sessions_if_due()
loop._check_expired_sessions_if_due()
await loop._check_expired_sessions_if_due()
await loop._check_expired_sessions_if_due()
assert loop.auto_compact.check_expired.call_count == 2
@@ -274,7 +365,7 @@ class TestAutoCompact:
loop.sessions.save(s2)
loop.consolidator.compact_idle_session = _make_fake_compact(loop)
loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
await loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
await _drain_background_tasks(loop)
active_after = loop.sessions.get_or_create("cli:active")
@@ -742,7 +833,7 @@ class TestProactiveAutoCompact:
@staticmethod
async def _run_check_expired(loop, active_session_keys=()):
"""Helper: run check_expired via callback and wait for background tasks."""
loop.auto_compact.check_expired(
await loop.auto_compact.check_expired(
loop.schedule_background,
loop.runtime_for_session,
active_session_keys=active_session_keys,
@@ -763,15 +854,12 @@ class TestProactiveAutoCompact:
healthy.add_message("user", "keep me")
loop.sessions.save(healthy)
removed_path = loop.sessions._get_session_path(removed.key)
original_open = open
def remove_before_open(path, *args, **kwargs):
if Path(path) == removed_path:
removed_path.unlink()
return original_open(path, *args, **kwargs)
monkeypatch.setattr("builtins.open", remove_before_open)
original_list = loop.sessions.list_sessions
def delete_after_listing():
rows = original_list()
loop.sessions.delete_session(removed.key)
return rows
monkeypatch.setattr(loop.sessions.state, "list_sessions", AsyncMock(side_effect=delete_after_listing))
async def idle_once():
loop._running = False
@@ -881,12 +969,12 @@ class TestProactiveAutoCompact:
loop.consolidator.compact_idle_session = _slow_compact
# First call starts archiving via callback
loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
await loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
await started.wait()
assert archive_count == 1
# Second call should skip (key is in _archiving)
loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
await loop.auto_compact.check_expired(loop.schedule_background, loop.runtime_for_session)
assert archive_count == 1
# Clean up
@@ -1008,8 +1096,9 @@ class TestProactiveAutoCompact:
await loop.aclose()
@pytest.mark.asyncio
async def test_no_reschedule_after_successful_archive(self, tmp_path):
"""Already-archived session should NOT be re-scheduled on subsequent ticks."""
@pytest.mark.parametrize("command_tail", [False, True])
async def test_no_reschedule_after_successful_archive(self, tmp_path, monkeypatch, command_tail):
"""Idle scans skip archived history until another ordinary message arrives."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 5, prefix="old")
@@ -1019,14 +1108,33 @@ class TestProactiveAutoCompact:
_fake_compact = _make_fake_compact(loop)
loop.consolidator.compact_idle_session = _fake_compact
# First tick: archives the session
await self._run_check_expired(loop)
assert _fake_compact.state["count"] == 1
try:
await self._run_check_expired(loop)
assert _fake_compact.state["count"] == 1
# Second tick: should NOT re-schedule because the session has no removable tail.
await self._run_check_expired(loop)
assert _fake_compact.state["count"] == 1 # Still 1, not re-scheduled
await loop.aclose()
if command_tail:
session = await loop.sessions.state.get(session.key)
session.add_message("user", "/status", _command=True)
session.add_message("assistant", "Ready.", _command=True)
session.updated_at = datetime.now() - timedelta(minutes=20)
await loop.sessions.state.finish_turn(session)
await loop.sessions.state.discard(session.key)
with monkeypatch.context() as patch:
patch.setattr(loop.sessions.state, "get", AsyncMock(side_effect=AssertionError(
"an idle scan must not load an already-archived transcript",
)))
await self._run_check_expired(loop)
assert _fake_compact.state["count"] == 1
session = await loop.sessions.state.get(session.key)
session.add_message("user", "Another topic.")
session.updated_at = datetime.now() - timedelta(minutes=20)
await loop.sessions.state.finish_turn(session)
await self._run_check_expired(loop)
assert _fake_compact.state["count"] == 2
finally:
await loop.aclose()
@pytest.mark.asyncio
async def test_empty_session_does_not_schedule_idle_compact(self, tmp_path):
@@ -1068,12 +1176,7 @@ class TestProactiveAutoCompact:
msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="second topic")
await loop._process_message(msg)
# Simulate idle again
loop.sessions.invalidate("cli:test")
session2 = loop.sessions.get_or_create("cli:test")
session2.updated_at = datetime.now() - timedelta(minutes=20)
loop.sessions.save(session2)
# Explicit archival does not require another TTL scan.
# Second compact cycle should succeed
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
assert _fake_compact.state["count"] == 2
@@ -1131,7 +1234,7 @@ class TestSummaryPersistence:
reloaded = loop.sessions.get_or_create("cli:test")
assert len(reloaded.messages) == 13
assert reloaded.get_history(max_messages=12) == []
_, summary = loop.auto_compact.prepare_session(reloaded, "cli:test")
_, summary = await loop.auto_compact.prepare_session(reloaded, "cli:test")
assert summary is not None
assert summary["text"] == "User said hello."
@@ -1158,9 +1261,9 @@ class TestSummaryPersistence:
reloaded = loop.sessions.get_or_create("cli:test")
# Every call returns the persisted summary.
_, summary = loop.auto_compact.prepare_session(reloaded, "cli:test")
_, summary = await loop.auto_compact.prepare_session(reloaded, "cli:test")
assert summary is not None
_, summary2 = loop.auto_compact.prepare_session(reloaded, "cli:test")
_, summary2 = await loop.auto_compact.prepare_session(reloaded, "cli:test")
assert summary2 is not None
assert summary2["text"] == "Summary."
# _last_summary persists in metadata for restart survival.
@@ -1187,7 +1290,7 @@ class TestSummaryPersistence:
assert "_last_summary" in reloaded.metadata
# In-memory path is taken (no restart)
_, summary = loop.auto_compact.prepare_session(reloaded, "cli:test")
_, summary = await loop.auto_compact.prepare_session(reloaded, "cli:test")
assert summary is not None
# _last_summary persists in metadata for restart survival.
assert "_last_summary" in reloaded.metadata
@@ -1208,17 +1311,17 @@ class TestSummaryPersistence:
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
# Consume the first summary via hot path
_, summary1 = loop.auto_compact.prepare_session(
_, summary1 = await loop.auto_compact.prepare_session(
loop.sessions.get_or_create("cli:test"), "cli:test"
)
assert summary1 is not None
assert summary1["text"] == "First summary."
assert "cli:test" not in loop.auto_compact._summaries # popped by hot path
# Add new messages and archive again (simulating a later turn)
# Read the committed snapshot before starting the next edit.
session = await loop.sessions.state.get("cli:test")
_add_turns(session, 4, prefix="world")
session.updated_at = datetime.now() - timedelta(minutes=20)
loop.sessions.save(session)
await loop.sessions.state.finish_turn(session)
loop.consolidator.compact_idle_session = _make_fake_compact(
loop, summary="Second summary.",
@@ -1230,7 +1333,7 @@ class TestSummaryPersistence:
# prepare_session must return the new summary
reloaded = loop.sessions.get_or_create("cli:test")
_, summary2 = loop.auto_compact.prepare_session(reloaded, "cli:test")
_, summary2 = await loop.auto_compact.prepare_session(reloaded, "cli:test")
assert summary2 is not None
assert summary2["text"] == "Second summary."
await loop.aclose()
@@ -1254,9 +1357,7 @@ class TestSummaryPersistence:
assert "_last_summary" in reloaded.metadata
# Simulate /new command
reloaded.clear()
loop.sessions.save(reloaded)
loop.sessions.invalidate(reloaded.key)
await loop.sessions.state.reset(reloaded.key)
# After /new, metadata should no longer contain _last_summary
fresh = loop.sessions.get_or_create("cli:test")
+106 -99
View File
@@ -1,6 +1,7 @@
"""Direct unit tests for AutoCompact class methods in isolation."""
import asyncio
from collections import defaultdict
from datetime import datetime, timedelta
from unittest.mock import AsyncMock, MagicMock
@@ -11,10 +12,22 @@ from nanobot.events import NO_EVENTS, ContextCompactionEvent, EventSink
from nanobot.session.manager import Session, SessionManager
def _mock_sessions():
sessions = MagicMock(spec=SessionManager)
sessions.state.get = AsyncMock(side_effect=lambda key: sessions.get_or_create(key))
sessions.state.list_sessions = AsyncMock(side_effect=lambda: sessions.list_sessions())
sessions.state.has_unarchived_messages = AsyncMock(return_value=True)
return sessions
def _runtime(_session: Session | None = None):
return MagicMock(name="runtime")
async def _resolve_runtime(session: Session):
return _runtime(session)
def _make_session(
key: str = "cli:test",
messages: list | None = None,
@@ -41,7 +54,10 @@ def _make_autocompact(
) -> AutoCompact:
"""Create an AutoCompact with mock dependencies."""
if sessions is None:
sessions = MagicMock(spec=SessionManager)
sessions = _mock_sessions()
sessions.get_or_create.return_value = Session(key="cli:test")
if isinstance(sessions, MagicMock):
sessions.state.get = AsyncMock(side_effect=lambda key: sessions.get_or_create(key))
if consolidator is None:
consolidator = MagicMock()
consolidator.compact_idle_session = AsyncMock(return_value="Summary.")
@@ -49,7 +65,7 @@ def _make_autocompact(
sessions=sessions,
consolidator=consolidator,
session_ttl_minutes=ttl,
session_lock=lambda _key: asyncio.Lock(),
session_lock=defaultdict(asyncio.Lock).__getitem__,
)
@@ -60,19 +76,21 @@ def _add_turns(session: Session, turns: int, *, prefix: str = "msg") -> None:
session.add_message("assistant", f"{prefix} assistant {i}")
def test_default_ttl_disables_idle_compaction():
sessions = MagicMock(spec=SessionManager)
async def test_default_ttl_disables_idle_compaction():
sessions = _mock_sessions()
sessions.list_sessions.return_value = [
{"key": "cli:idle", "updated_at": datetime.now() - timedelta(days=365)},
]
sessions.get_or_create.return_value = _make_session(
key="cli:idle", messages=[{"role": "user", "content": "pending"}],
)
ac = AutoCompact(sessions=sessions, consolidator=MagicMock(),
session_lock=lambda _key: asyncio.Lock())
ac = AutoCompact(
sessions=sessions, consolidator=MagicMock(),
session_lock=defaultdict(asyncio.Lock).__getitem__,
)
schedule = MagicMock(side_effect=lambda pending: pending.close())
ac.check_expired(schedule, _runtime)
await ac.check_expired(schedule, _resolve_runtime)
assert schedule.call_count == 0
@@ -162,20 +180,20 @@ class TestIsExpired:
class TestCheckExpired:
"""Test AutoCompact.check_expired scheduling logic."""
def test_empty_sessions_list(self):
async def test_empty_sessions_list(self):
"""No sessions → schedule_background should never be called."""
ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
mock_sm.list_sessions.return_value = []
ac.sessions = mock_sm
scheduler = MagicMock()
ac.check_expired(scheduler, _runtime)
await ac.check_expired(scheduler, _resolve_runtime)
scheduler.assert_not_called()
def test_expired_session_schedules_background(self):
async def test_expired_session_schedules_background(self):
"""Expired session should trigger schedule_background."""
ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
old_dt = datetime.now() - timedelta(minutes=20)
session = _make_session("cli:old", updated_at=old_dt)
_add_turns(session, 5)
@@ -189,11 +207,11 @@ class TestCheckExpired:
scheduled.append(coro)
coro.close()
ac.check_expired(scheduler, _runtime)
await ac.check_expired(scheduler, _resolve_runtime)
assert len(scheduled) == 1
assert "cli:old" in ac._archiving
def test_unparseable_updated_at_does_not_stop_scan(self):
async def test_unparseable_updated_at_does_not_stop_scan(self):
"""A malformed timestamp is skipped without hiding later sessions.
The idle scan runs from the agent loop's inbound-timeout branch, so a
@@ -202,7 +220,7 @@ class TestCheckExpired:
does when loading.
"""
ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
old_dt = datetime.now() - timedelta(minutes=20)
session = _make_session("cli:old", updated_at=old_dt)
_add_turns(session, 5)
@@ -218,7 +236,7 @@ class TestCheckExpired:
scheduled.append(coro)
coro.close()
ac.check_expired(scheduler, _runtime)
await ac.check_expired(scheduler, _resolve_runtime)
assert len(scheduled) == 1
assert ac._archiving == {"cli:old"}
@@ -235,10 +253,10 @@ class TestCheckExpired:
ac.sessions.get_or_create.return_value = session
admitted = _runtime()
replacement = _runtime()
resolve_runtime = MagicMock(return_value=admitted)
resolve_runtime = AsyncMock(return_value=admitted)
scheduled = []
ac.check_expired(scheduled.append, resolve_runtime)
await ac.check_expired(scheduled.append, resolve_runtime)
resolve_runtime.return_value = replacement
await scheduled[0]
@@ -250,7 +268,7 @@ class TestCheckExpired:
)
@pytest.mark.parametrize("resolution_error", [KeyError, ValueError])
def test_invalid_preset_is_isolated_to_one_session(self, resolution_error):
async def test_invalid_preset_is_isolated_to_one_session(self, resolution_error):
ac = _make_autocompact(ttl=15)
old_dt = datetime.now() - timedelta(minutes=20)
sessions = {
@@ -266,7 +284,7 @@ class TestCheckExpired:
ac.sessions.get_or_create.side_effect = sessions.__getitem__
healthy_runtime = _runtime()
def resolve_runtime(session: Session):
async def resolve_runtime(session: Session):
if session.key == "cli:removed":
raise resolution_error("model preset cannot be resolved")
return healthy_runtime
@@ -277,12 +295,12 @@ class TestCheckExpired:
scheduled.append(coro)
coro.close()
ac.check_expired(scheduler, resolve_runtime)
await ac.check_expired(scheduler, resolve_runtime)
assert len(scheduled) == 1
assert ac._archiving == {"cli:healthy"}
def test_unexpected_runtime_resolution_failure_propagates(self):
async def test_unexpected_runtime_resolution_failure_propagates(self):
ac = _make_autocompact(ttl=15)
old_dt = datetime.now() - timedelta(minutes=20)
session = _make_session("cli:old", updated_at=old_dt)
@@ -292,59 +310,59 @@ class TestCheckExpired:
]
ac.sessions.get_or_create.return_value = session
def fail(_session: Session):
async def fail(_session: Session):
raise RuntimeError("unexpected resolver failure")
with pytest.raises(RuntimeError, match="unexpected resolver failure"):
ac.check_expired(MagicMock(), fail)
await ac.check_expired(MagicMock(), fail)
def test_active_session_key_skips(self):
async def test_active_session_key_skips(self):
"""Session in active_session_keys should be skipped."""
ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
old_ts = (datetime.now() - timedelta(minutes=20)).isoformat()
mock_sm.list_sessions.return_value = [{"key": "cli:busy", "updated_at": old_ts}]
ac.sessions = mock_sm
scheduler = MagicMock()
ac.check_expired(scheduler, _runtime, active_session_keys={"cli:busy"})
await ac.check_expired(scheduler, _resolve_runtime, active_session_keys={"cli:busy"})
scheduler.assert_not_called()
def test_session_already_in_archiving_skips(self):
async def test_session_already_in_archiving_skips(self):
"""Session already in _archiving set should be skipped."""
ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
old_ts = (datetime.now() - timedelta(minutes=20)).isoformat()
mock_sm.list_sessions.return_value = [{"key": "cli:dup", "updated_at": old_ts}]
ac.sessions = mock_sm
ac._archiving.add("cli:dup")
scheduler = MagicMock()
ac.check_expired(scheduler, _runtime)
await ac.check_expired(scheduler, _resolve_runtime)
scheduler.assert_not_called()
def test_session_with_no_key_skips(self):
async def test_session_with_no_key_skips(self):
"""Session info with empty/missing key should be skipped."""
ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
mock_sm.list_sessions.return_value = [{"key": "", "updated_at": "old"}]
ac.sessions = mock_sm
scheduler = MagicMock()
ac.check_expired(scheduler, _runtime)
await ac.check_expired(scheduler, _resolve_runtime)
scheduler.assert_not_called()
def test_session_with_missing_key_field_skips(self):
async def test_session_with_missing_key_field_skips(self):
"""Session info dict without 'key' field should be skipped."""
ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
mock_sm.list_sessions.return_value = [{"updated_at": "old"}]
ac.sessions = mock_sm
scheduler = MagicMock()
ac.check_expired(scheduler, _runtime)
await ac.check_expired(scheduler, _resolve_runtime)
scheduler.assert_not_called()
def test_dream_session_skips(self):
async def test_dream_session_skips(self):
"""Internal Dream sessions should not be scheduled for idle compact."""
ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
old_ts = (datetime.now() - timedelta(minutes=20)).isoformat()
mock_sm.list_sessions.return_value = [
{"key": "dream:20260602-155256", "updated_at": old_ts},
@@ -352,15 +370,15 @@ class TestCheckExpired:
ac.sessions = mock_sm
scheduler = MagicMock()
ac.check_expired(scheduler, _runtime)
await ac.check_expired(scheduler, _resolve_runtime)
scheduler.assert_not_called()
assert "dream:20260602-155256" not in ac._archiving
def test_short_unarchived_session_schedules(self):
async def test_short_unarchived_session_schedules(self):
"""A short idle session still needs an archive entry for Dream."""
ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
last_active = datetime(2026, 1, 1, 10, 0, 0)
session = _make_session("cli:short", updated_at=last_active)
_add_turns(session, 2)
@@ -376,14 +394,14 @@ class TestCheckExpired:
scheduled.append(coro)
coro.close()
ac.check_expired(scheduler, _runtime)
await ac.check_expired(scheduler, _resolve_runtime)
assert len(scheduled) == 1
assert ac._archiving == {"cli:short"}
def test_fully_archived_session_skips(self):
async def test_fully_archived_session_skips(self):
ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
last_active = datetime(2026, 1, 1, 10, 0, 0)
session = _make_session("cli:done", updated_at=last_active)
_add_turns(session, 2)
@@ -392,12 +410,14 @@ class TestCheckExpired:
{"key": "cli:done", "updated_at": last_active.isoformat()},
]
mock_sm.get_or_create.return_value = session
mock_sm.state.has_unarchived_messages.return_value = False
ac.sessions = mock_sm
scheduler = MagicMock()
ac.check_expired(scheduler, _runtime)
await ac.check_expired(scheduler, _resolve_runtime)
scheduler.assert_not_called()
mock_sm.state.get.assert_not_awaited()
# ---------------------------------------------------------------------------
@@ -411,7 +431,8 @@ class TestArchiveDelegates:
@pytest.mark.asyncio
async def test_calls_compact_idle_session(self):
ac = _make_autocompact()
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
mock_sm.get_or_create.return_value = Session(key="cli:test")
ac.sessions = mock_sm
ac.consolidator.compact_idle_session = AsyncMock(return_value="Summary.")
@@ -426,7 +447,8 @@ class TestArchiveDelegates:
@pytest.mark.asyncio
async def test_forwards_timeout_compaction_events_with_session_key(self):
sessions = MagicMock(spec=SessionManager)
sessions = _mock_sessions()
sessions.get_or_create.return_value = Session(key="cli:test")
consolidator = MagicMock()
observed: list[tuple[str, ContextCompactionEvent]] = []
@@ -446,7 +468,7 @@ class TestArchiveDelegates:
consolidator=consolidator,
session_ttl_minutes=15,
bind_events=bind,
session_lock=lambda _key: asyncio.Lock(),
session_lock=defaultdict(asyncio.Lock).__getitem__,
)
await ac._archive("cli:test", runtime=_runtime())
@@ -469,7 +491,7 @@ class TestArchiveDelegates:
@pytest.mark.asyncio
async def test_populates_summaries_from_metadata(self):
ac = _make_autocompact()
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
session = _make_session(
metadata={"_last_summary": {"text": "Hello.", "last_active": "2026-05-13T10:00:00"}}
)
@@ -486,7 +508,7 @@ class TestArchiveDelegates:
@pytest.mark.asyncio
async def test_no_summary_when_compact_returns_empty(self):
ac = _make_autocompact()
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
ac.sessions = mock_sm
ac.consolidator.compact_idle_session = AsyncMock(return_value="")
@@ -497,7 +519,7 @@ class TestArchiveDelegates:
@pytest.mark.asyncio
async def test_no_summary_when_compact_returns_nothing(self):
ac = _make_autocompact()
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
ac.sessions = mock_sm
ac.consolidator.compact_idle_session = AsyncMock(return_value="(nothing)")
@@ -508,7 +530,7 @@ class TestArchiveDelegates:
@pytest.mark.asyncio
async def test_exception_still_removes_from_archiving(self):
ac = _make_autocompact()
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
ac.sessions = mock_sm
ac.consolidator.compact_idle_session = AsyncMock(side_effect=RuntimeError("fail"))
@@ -526,36 +548,21 @@ class TestArchiveDelegates:
class TestPrepareSession:
"""Test AutoCompact.prepare_session logic."""
def test_key_in_archiving_reloads_session(self):
"""If key is in _archiving, session should be reloaded via get_or_create."""
ac = _make_autocompact()
mock_sm = MagicMock(spec=SessionManager)
reloaded = _make_session(key="cli:test")
mock_sm.get_or_create.return_value = reloaded
ac.sessions = mock_sm
ac._archiving.add("cli:test")
original_session = _make_session()
result_session, summary = ac.prepare_session(original_session, "cli:test")
mock_sm.get_or_create.assert_called_once_with("cli:test")
assert result_session is reloaded
def test_expired_session_reloads(self):
"""If session is expired, it should be reloaded via get_or_create."""
@pytest.mark.parametrize("archiving", [False, True])
async def test_preparing_idle_session_preserves_turn_metadata(self, archiving):
ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager)
reloaded = _make_session(key="cli:test", updated_at=datetime.now())
mock_sm.get_or_create.return_value = reloaded
ac.sessions = mock_sm
session = _make_session(
updated_at=datetime.now() - timedelta(minutes=20),
metadata={"last_channel": "discord:new"},
)
if archiving:
ac._archiving.add(session.key)
old_session = _make_session(updated_at=datetime.now() - timedelta(minutes=20))
result_session, summary = ac.prepare_session(old_session, "cli:test")
prepared, _ = await ac.prepare_session(session, session.key)
mock_sm.get_or_create.assert_called_once_with("cli:test")
assert result_session is reloaded
assert prepared.metadata["last_channel"] == "discord:new"
def test_hot_path_summary_from_summaries(self):
async def test_hot_path_summary_from_summaries(self):
"""Summary from _summaries dict should be returned (hot path)."""
ac = _make_autocompact()
session = _make_session()
@@ -565,7 +572,7 @@ class TestPrepareSession:
"last_active": last_active.isoformat(),
}
result_session, summary = ac.prepare_session(session, "cli:test")
result_session, summary = await ac.prepare_session(session, "cli:test")
assert result_session is session
assert summary is not None
@@ -574,7 +581,7 @@ class TestPrepareSession:
"last_active": last_active.isoformat(),
}
def test_hot_path_pops_summary_one_shot(self):
async def test_hot_path_pops_summary_one_shot(self):
"""Hot path should pop the summary (one-shot; second call returns None)."""
ac = _make_autocompact()
session = _make_session()
@@ -584,13 +591,13 @@ class TestPrepareSession:
"last_active": last_active.isoformat(),
}
_, summary1 = ac.prepare_session(session, "cli:test")
_, summary1 = await ac.prepare_session(session, "cli:test")
assert summary1 is not None
# Second call: hot path entry was popped
_, summary2 = ac.prepare_session(session, "cli:test")
_, summary2 = await ac.prepare_session(session, "cli:test")
assert summary2 is None
def test_cold_path_summary_from_metadata(self):
async def test_cold_path_summary_from_metadata(self):
"""When _summaries is empty, summary should come from metadata (cold path)."""
ac = _make_autocompact()
last_active = datetime(2026, 5, 13, 14, 0, 0)
@@ -601,13 +608,13 @@ class TestPrepareSession:
},
})
result_session, summary = ac.prepare_session(session, "cli:test")
result_session, summary = await ac.prepare_session(session, "cli:test")
assert result_session is session
assert summary is not None
assert summary["text"] == "Cold summary."
def test_cold_path_tolerates_malformed_last_active(self):
async def test_cold_path_tolerates_malformed_last_active(self):
"""A malformed persisted last_active must not raise on the turn path.
prepare_session runs from _compact_session on every turn. Persisted
@@ -624,7 +631,7 @@ class TestPrepareSession:
updated_at=fallback,
)
result_session, summary = ac.prepare_session(session, "cli:test")
result_session, summary = await ac.prepare_session(session, "cli:test")
assert result_session is session
assert summary is not None
@@ -633,7 +640,7 @@ class TestPrepareSession:
"last_active": fallback.isoformat(),
}
def test_cold_path_tolerates_missing_last_active(self):
async def test_cold_path_tolerates_missing_last_active(self):
"""A _last_summary dict without last_active must not raise."""
ac = _make_autocompact(ttl=0)
fallback = datetime(2026, 1, 2, 3, 4, 5)
@@ -642,7 +649,7 @@ class TestPrepareSession:
updated_at=fallback,
)
result_session, summary = ac.prepare_session(session, "cli:test")
result_session, summary = await ac.prepare_session(session, "cli:test")
assert result_session is session
assert summary is not None
@@ -651,32 +658,32 @@ class TestPrepareSession:
"last_active": fallback.isoformat(),
}
def test_cold_path_missing_text_returns_none(self):
async def test_cold_path_missing_text_returns_none(self):
"""A _last_summary without a non-empty string text yields no summary."""
ac = _make_autocompact()
session = _make_session(metadata={
"_last_summary": {"last_active": datetime(2026, 1, 1).isoformat()},
})
result_session, summary = ac.prepare_session(session, "cli:test")
result_session, summary = await ac.prepare_session(session, "cli:test")
assert result_session is session
assert summary is None
def test_no_summary_available_returns_none(self):
async def test_no_summary_available_returns_none(self):
"""When no summary is available, should return (session, None)."""
ac = _make_autocompact()
session = _make_session()
result_session, summary = ac.prepare_session(session, "cli:test")
result_session, summary = await ac.prepare_session(session, "cli:test")
assert result_session is session
assert summary is None
def test_dream_session_skips_reload_and_summaries(self):
async def test_dream_session_skips_reload_and_summaries(self):
"""Internal Dream sessions should not reload or receive compact summaries."""
ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager)
mock_sm = _mock_sessions()
ac.sessions = mock_sm
key = "dream:20260602-155256"
ac._archiving.add(key)
@@ -695,7 +702,7 @@ class TestPrepareSession:
},
)
result_session, summary = ac.prepare_session(session, key)
result_session, summary = await ac.prepare_session(session, key)
mock_sm.get_or_create.assert_not_called()
assert result_session is session
@@ -703,17 +710,17 @@ class TestPrepareSession:
assert key not in ac._archiving
assert key not in ac._summaries
def test_cold_path_metadata_not_dict_returns_none(self):
async def test_cold_path_metadata_not_dict_returns_none(self):
"""If metadata _last_summary is not a dict, should return None summary."""
ac = _make_autocompact()
session = _make_session(metadata={"_last_summary": "not a dict"})
result_session, summary = ac.prepare_session(session, "cli:test")
result_session, summary = await ac.prepare_session(session, "cli:test")
assert result_session is session
assert summary is None
def test_hot_path_takes_priority_over_metadata(self):
async def test_hot_path_takes_priority_over_metadata(self):
"""Hot path (_summaries) should take priority over metadata."""
ac = _make_autocompact()
session = _make_session(metadata={
@@ -728,7 +735,7 @@ class TestPrepareSession:
"last_active": last_active.isoformat(),
}
_, summary = ac.prepare_session(session, "cli:test")
_, summary = await ac.prepare_session(session, "cli:test")
assert summary is not None
assert summary["text"] == "Hot summary."
# After hot path pops, cold path would kick in on next call
+13 -12
View File
@@ -2,6 +2,7 @@
import asyncio
from datetime import datetime, timedelta
from unittest.mock import patch
import pytest
@@ -56,18 +57,18 @@ async def seed_history(bot, key):
])
def schedule_idle_archive(bot, key):
session = bot._loop.sessions.get_or_create(key)
session.updated_at = datetime.now() - timedelta(minutes=30)
bot._loop.sessions.save(session)
async def schedule_idle_archive(bot):
scheduled = []
bot._loop.auto_compact.check_expired(scheduled.append, bot._loop.runtime_for_session)
with patch("nanobot.agent.autocompact.datetime") as clock:
clock.now.return_value = datetime.now() + timedelta(minutes=30)
clock.fromisoformat.side_effect = datetime.fromisoformat
await bot._loop.auto_compact.check_expired(scheduled.append, bot._loop.runtime_for_session)
assert len(scheduled) == 1
return scheduled[0]
def assert_reply_and_summary(bot, key):
snapshot = bot.sessions.export(key)
async def assert_reply_and_summary(bot, key):
snapshot = await bot.sessions.export(key)
assert snapshot is not None
assert ("assistant", "new reply") in [
(message["role"], message["content"]) for message in snapshot.messages
@@ -82,7 +83,7 @@ async def test_compaction_waits_for_active_sdk_turn_and_preserves_reply(
bot, provider = bot
key = "sdk:shared"
await seed_history(bot, key)
idle_archive = schedule_idle_archive(bot, key) if trigger == "scheduled_idle" else None
idle_archive = await schedule_idle_archive(bot) if trigger == "scheduled_idle" else None
compact_attempted = asyncio.Event()
async def compact():
@@ -112,7 +113,7 @@ async def test_compaction_waits_for_active_sdk_turn_and_preserves_reply(
provider.release_summary.set()
compacted = await asyncio.wait_for(compaction, timeout=5)
assert_reply_and_summary(bot, key)
await assert_reply_and_summary(bot, key)
assert summary_started_during_turn is False
assert {"role": "assistant", "content": "new reply"} in provider.summary_messages
if trigger == "compact_session":
@@ -123,7 +124,7 @@ async def test_compaction_waits_for_active_sdk_turn_and_preserves_reply(
await bot.aclose()
async with Nanobot(loop_factory(provider=ControlledProvider())) as restarted:
assert_reply_and_summary(restarted, key)
await assert_reply_and_summary(restarted, key)
finally:
provider.release_turn.set()
provider.release_summary.set()
@@ -136,7 +137,7 @@ async def test_sdk_turn_waits_for_running_idle_archive_and_uses_its_summary(bot)
bot, provider = bot
key = "sdk:shared"
await seed_history(bot, key)
archive = asyncio.create_task(schedule_idle_archive(bot, key))
archive = asyncio.create_task(await schedule_idle_archive(bot))
turn_attempted = asyncio.Event()
async def run():
@@ -160,7 +161,7 @@ async def test_sdk_turn_waits_for_running_idle_archive_and_uses_its_summary(bot)
provider.release_turn.set()
result = await asyncio.wait_for(turn, timeout=5)
assert result.content == "new reply"
assert_reply_and_summary(bot, key)
await assert_reply_and_summary(bot, key)
finally:
provider.release_turn.set()
provider.release_summary.set()
+8 -7
View File
@@ -880,10 +880,10 @@ class TestCompactIdleSession:
"cli:incremental",
runtime=runtime,
)
current = sessions.get_or_create("cli:incremental")
current = await sessions.state.get("cli:incremental")
current.add_message("user", "second user")
current.add_message("assistant", "second assistant")
sessions.save(current)
await sessions.state.finish_turn(current)
second = await real_consolidator.compact_idle_session(
"cli:incremental",
runtime=runtime,
@@ -928,10 +928,10 @@ class TestCompactIdleSession:
"cli:cumulative-fallback",
runtime=runtime,
)
current = sessions.get_or_create("cli:cumulative-fallback")
current = await sessions.state.get("cli:cumulative-fallback")
current.add_message("user", "second user")
current.add_message("assistant", "newest working state")
sessions.save(current)
await sessions.state.finish_turn(current)
fallback = await real_consolidator.compact_idle_session(
"cli:cumulative-fallback",
@@ -971,10 +971,10 @@ class TestCompactIdleSession:
runtime=runtime,
)
current = sessions.get_or_create("cli:nothing-after-summary")
current = await sessions.state.get("cli:nothing-after-summary")
current.add_message("user", "thanks")
current.add_message("assistant", "you're welcome")
sessions.save(current)
await sessions.state.finish_turn(current)
result = await real_consolidator.compact_idle_session(
"cli:nothing-after-summary",
runtime=runtime,
@@ -999,9 +999,10 @@ class TestCompactIdleSession:
sessions.save(session)
async def append_during_archive(**_kwargs):
current = sessions.get_or_create("cli:concurrent")
current = await sessions.state.get("cli:concurrent")
current.add_message("user", "late user")
current.add_message("assistant", "late assistant")
await sessions.state.finish_turn(current)
return LLMResponse(content="Summary.", finish_reason="stop")
mock_provider.chat_stream_with_retry.side_effect = append_during_archive
+4 -7
View File
@@ -402,9 +402,7 @@ class TestEphemeralDirect:
)
with (
patch("nanobot.agent.loop.SessionManager"),
patch("nanobot.agent.loop.SubagentManager") as mock_sub,
patch("nanobot.agent.loop.Consolidator"),
):
mock_sub.return_value.cancel_by_session = AsyncMock(return_value=0)
loop = AgentLoop(
@@ -695,7 +693,7 @@ class TestEphemeralDirect:
for marker in [*markers.values(), "DREAM_AGENTS_MARKER"]:
assert marker in system_prompt
assert request_text.count(marker) == 1
assert loop.sessions._get_session_path(session_key).exists()
assert loop.sessions.read_session_snapshot(session_key) is not None
class TestEphemeralHooks:
@@ -725,13 +723,12 @@ class TestEphemeralHooks:
spy = MagicMock(spec=AgentHook)
spy.wants_streaming.return_value = False
spy.before_iteration = AsyncMock()
spy.after_iteration = AsyncMock()
spy.finalize_content.side_effect = lambda context, content: content
spy.before_iteration = AsyncMock(return_value=None)
spy.after_iteration = AsyncMock(return_value=None)
with (
patch("nanobot.agent.loop.SessionManager"),
patch("nanobot.agent.loop.SubagentManager") as mock_sub,
patch("nanobot.agent.loop.Consolidator"),
):
mock_sub.return_value.cancel_by_session = AsyncMock(return_value=0)
loop = AgentLoop(
+30 -82
View File
@@ -25,91 +25,39 @@ class TestDreamSessionKey:
class TestPruneDreamSessions:
def test_keeps_n_most_recent(self, tmp_path):
import os
import time
async def test_keeps_n_most_recent(self, tmp_path):
manager = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "runtime")
keys = [f"dream:20260528-{100000 + i:06d}" for i in range(15)]
for i, key in enumerate(keys):
session = manager.get_or_create(key)
session.updated_at = datetime(2026, 5, 28, 10, 0, i)
manager.save(session)
manager.save(manager.get_or_create("telegram:normal"))
manager = SessionManager(
tmp_path / "workspace",
sessions_root=tmp_path / "runtime",
)
sessions_dir = manager.sessions_dir
assert await manager.state.prune_dream_sessions(keep=10) == 5
await manager.state.aclose()
base_time = time.time() - 100
dream_paths = []
assert [manager.read_session_snapshot(key) is not None for key in keys] == [False] * 5 + [True] * 10
assert manager.read_session_snapshot("telegram:normal") is not None
for i in range(15):
key = f"dream:20260528-{100000 + i:06d}"
path = sessions_dir / f"{SessionManager._storage_key(key)}.jsonl"
path.write_text(
f'{{"_type": "metadata", "key": "{key}", '
f'"created_at": "2026-05-28T10:00:{i:02d}", '
f'"updated_at": "2026-05-28T10:00:{i:02d}"}}\n',
encoding="utf-8",
)
os.utime(path, (base_time + i, base_time + i))
dream_paths.append(path)
async def test_leaves_legacy_backup_untouched(self, tmp_path):
manager = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "runtime")
path = manager.sessions_dir / "dream_20260713-095959.jsonl"
path.write_text('legacy backup', encoding="utf-8")
await manager.state.prune_dream_sessions(keep=0)
await manager.state.aclose()
assert path.read_text(encoding="utf-8") == 'legacy backup'
normal_path = sessions_dir / "telegram_123.jsonl"
normal_path.write_text('{"_type": "metadata"}\n', encoding="utf-8")
MemoryStore.prune_dream_sessions(manager, keep=10)
assert [path.exists() for path in dream_paths] == [False] * 5 + [True] * 10
assert normal_path.exists()
def test_ignores_legacy_dream_filenames(self, tmp_path):
import os
import time
manager = SessionManager(
tmp_path / "workspace",
sessions_root=tmp_path / "runtime",
)
sessions_dir = manager.sessions_dir
base_time = time.time() - 100
current_paths = []
for i in range(2):
key = f"dream:20260713-{100000 + i:06d}"
path = sessions_dir / f"{SessionManager._storage_key(key)}.jsonl"
path.write_text(
f'{{"_type": "metadata", "key": "{key}"}}\n',
encoding="utf-8",
)
os.utime(path, (base_time + i, base_time + i))
current_paths.append(path)
legacy_path = sessions_dir / "dream_20260713-095959.jsonl"
legacy_path.write_text(
'{"_type": "metadata", "key": "dream:20260713-095959"}\n',
encoding="utf-8",
)
os.utime(legacy_path, (base_time - 1, base_time - 1))
MemoryStore.prune_dream_sessions(manager, keep=1)
assert [path.exists() for path in current_paths] == [False, True]
assert legacy_path.exists()
def test_noop_when_under_limit(self, tmp_path):
manager = SessionManager(
tmp_path / "workspace",
sessions_root=tmp_path / "runtime",
)
sessions_dir = manager.sessions_dir
async def test_noop_when_under_limit(self, tmp_path):
manager = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "runtime")
for i in range(3):
key = f"dream:20260528-{100000 + i:06d}"
path = sessions_dir / f"{SessionManager._storage_key(key)}.jsonl"
path.write_text("{}", encoding="utf-8")
manager.save(manager.get_or_create(f"dream:20260528-{100000 + i:06d}"))
assert await manager.state.prune_dream_sessions(keep=10) == 0
await manager.state.aclose()
assert len(manager.list_sessions()) == 3
MemoryStore.prune_dream_sessions(manager, keep=10)
assert len(list(sessions_dir.glob("*.jsonl"))) == 3
def test_empty_dir_noop(self, tmp_path):
manager = SessionManager(
tmp_path / "workspace",
sessions_root=tmp_path / "runtime",
)
MemoryStore.prune_dream_sessions(manager, keep=10)
assert list(manager.sessions_dir.glob("*.jsonl")) == []
async def test_empty_store_noop(self, tmp_path):
manager = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "runtime")
assert await manager.state.prune_dream_sessions(keep=10) == 0
await manager.state.aclose()
assert manager.list_sessions() == []
+1 -2
View File
@@ -73,8 +73,7 @@ async def test_process_message_hands_complete_replay_to_runner(tmp_path: Path) -
)
loop.tools.get_definitions = MagicMock(return_value=[])
session = loop.sessions.get_or_create("cli:test")
session.messages = _populated_session(30).messages
session = await loop.sessions.state.import_messages("cli:test", _populated_session(30).messages)
expected_history = session.get_history()
loop.provider.aclose = AsyncMock()
result = await loop.process_direct("hello", session_key="cli:test")
+2 -1
View File
@@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from agent.session_helpers import mock_session_manager
from nanobot.agent.context import TranscriptInput
from nanobot.agent.hook import (
AgentHook,
@@ -438,7 +439,7 @@ def _make_loop(tmp_path, hooks=None, hook_factories=None):
provider.generation.max_tokens = 4096
with patch("nanobot.agent.loop.ContextBuilder"), \
patch("nanobot.agent.loop.SessionManager"), \
patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr, \
patch("nanobot.agent.loop.Consolidator"):
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
+3 -3
View File
@@ -596,10 +596,10 @@ class TestToolEventProgress:
calls += 1
if calls == 1:
await on_content_delta("old partial")
loop._enqueue_session_message(InboundMessage(
(await loop._enqueue_session_message(InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content="new question",
metadata={"_wants_stream": True},
))
)))
return LLMResponse(content="old partial", finish_reason="length")
has_followup = any(
"new question" in str(message.get("content", ""))
@@ -869,7 +869,7 @@ class TestToolEventProgress:
session.add_message("user", "Run this in the background")
session.metadata.update({"webui": True, "title": "Existing title"})
loop.sessions.save(session)
save_completed_subagent(loop, "sub-1", session_key)
await save_completed_subagent(loop, "sub-1", session_key)
dispatch = asyncio.create_task(run_session(loop, InboundMessage(
channel="system",
sender_id="subagent",
+3 -2
View File
@@ -108,7 +108,8 @@ async def test_recovery_preserves_turn_origin_until_the_next_user_turn(
channel="websocket", sender_id="user", chat_id="chat", content="Inspect configuration",
metadata={"webui": True, "webui_turn_id": "user-request", "message_id": "user-message"},
)
loop.sessions.get_or_create(request.session_key).metadata["title"] = "Configuration"
await loop.sessions.state.get(request.session_key)
await loop.sessions.state.update_metadata(request.session_key, {"title": "Configuration"})
with coordinator.connected():
if late_result:
provider.chat_stream_with_retry = AsyncMock(side_effect=[
@@ -119,7 +120,7 @@ async def test_recovery_preserves_turn_origin_until_the_next_user_turn(
channel="websocket", sender_id="user", chat_id="chat", content="New request B",
metadata={"webui": True, "webui_turn_id": "request-b", "message_id": "message-b"},
), asyncio.Queue())
save_completed_subagent(loop, "task-a", request.session_key)
await save_completed_subagent(loop, "task-a", request.session_key)
request = InboundMessage(
channel="system", sender_id="subagent", chat_id=request.session_key,
content="Background check for the original request completed",
+6 -1
View File
@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from agent.session_helpers import mock_session_manager
from nanobot.agent.context import TranscriptInput
from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission
from nanobot.agent.tools.context import RequestContext
@@ -46,7 +47,7 @@ def _make_loop(tmp_path):
provider.generation = GenerationSettings()
with patch("nanobot.agent.loop.ContextBuilder"), \
patch("nanobot.agent.loop.SessionManager"), \
patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path)
@@ -159,6 +160,7 @@ async def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path):
session = loop.sessions.get_or_create("cli:direct")
session.add_message("user", "Let's agree on the migration implementation.")
session.add_message("assistant", "Use the staged migration plan and run integration tests.")
loop.sessions.save(session)
result = await loop._process_message(
InboundMessage(
@@ -172,6 +174,7 @@ async def test_goal_command_can_implement_plan_from_prior_discussion(tmp_path):
assert result is not None
assert result.content == "done"
assert goal_mutation_allowed() is False
session = await loop.sessions.state.get(session.key)
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
first_request = provider.chat_stream_with_retry.await_args_list[0].kwargs["messages"]
assert "staged migration plan" in str(first_request)
@@ -243,6 +246,7 @@ async def test_runtime_context_is_persisted_as_next_turn_prompt_prefix(tmp_path)
assert second_wire[3]["content"].startswith("second turn")
assert len(provider_calls) == 2
session = await loop.sessions.state.get(session.key)
persisted_first_user = session.messages[0]
assert persisted_first_user["content"] == first_wire[1]["content"]
assert public_history_message(persisted_first_user)["content"] == "first turn $review"
@@ -276,6 +280,7 @@ async def test_webui_quote_reaches_model_without_leaking_into_public_history(tmp
request = provider.chat_stream_with_retry.await_args.kwargs["messages"]
assert "What does this mean?" in str(request)
assert "the selected answer excerpt" in str(request)
session = await loop.sessions.state.get(session.key)
assert "the selected answer excerpt" in str(session.messages[0]["content"])
assert public_history_message(session.messages[0])["content"] == "What does this mean?"
+46 -28
View File
@@ -161,12 +161,12 @@ def test_agent_loop_llm_runtime_reflects_current_provider_and_model(tmp_path: Pa
assert runtime.model == "next-model"
def test_persist_cron_turn_uses_distinct_history_marker(tmp_path: Path) -> None:
async def test_persist_cron_turn_uses_distinct_history_marker(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path)
session = loop.sessions.get_or_create("websocket:auto")
session = await loop.sessions.state.get("websocket:auto")
prompt_ref = {"id": "cron.agent_turn.reminder", "version": 1, "sha256": "abc"}
persisted = loop._persist_user_message_early(
persisted = await loop._persist_user_message_early(
InboundMessage(
channel="websocket",
sender_id="cron",
@@ -203,9 +203,9 @@ def test_persist_cron_turn_uses_distinct_history_marker(tmp_path: Path) -> None:
assert message["cron_prompt_ref"] == prompt_ref
def test_persist_user_message_acknowledges_durable_followup(tmp_path: Path) -> None:
async def test_persist_user_message_acknowledges_durable_followup(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path)
session = loop.sessions.get_or_create("websocket:chat")
session = await loop.sessions.state.get("websocket:chat")
session.metadata[PENDING_FOLLOWUPS_KEY] = [
{
"id": "followup-1",
@@ -217,7 +217,7 @@ def test_persist_user_message_acknowledges_durable_followup(tmp_path: Path) -> N
}
]
persisted = loop._persist_user_message_early(
persisted = await loop._persist_user_message_early(
InboundMessage(
channel="websocket",
sender_id="user",
@@ -232,11 +232,11 @@ def test_persist_user_message_acknowledges_durable_followup(tmp_path: Path) -> N
assert PENDING_FOLLOWUPS_KEY not in session.metadata
def test_persist_local_trigger_turn_uses_hidden_automation_marker(tmp_path: Path) -> None:
async def test_persist_local_trigger_turn_uses_hidden_automation_marker(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path)
session = loop.sessions.get_or_create("websocket:auto")
session = await loop.sessions.state.get("websocket:auto")
persisted = loop._persist_user_message_early(
persisted = await loop._persist_user_message_early(
InboundMessage(
channel="websocket",
sender_id="trigger",
@@ -384,6 +384,7 @@ async def test_generate_webui_title_only_for_marked_webui_sessions(tmp_path: Pat
)
assert generated is True
session = await loop.sessions.state.get(session.key)
assert session.metadata[WEBUI_TITLE_METADATA_KEY] == "优化 WebUI 侧边栏"
loop.provider.chat_stream_with_retry.assert_awaited_once()
assert loop.provider.chat_stream_with_retry.await_args.kwargs["max_tokens"] == TITLE_GENERATION_MAX_TOKENS
@@ -510,6 +511,7 @@ async def test_projected_title_generation_skips_existing_chat_title(tmp_path: Pa
unified.add_message("assistant", "以下是临期 IP 列表。")
chat = loop.sessions.get_or_create("websocket:chat-existing")
chat.metadata[WEBUI_TITLE_METADATA_KEY] = "Existing title"
loop.sessions.save(chat)
loop.sessions.save(unified)
generated = await maybe_generate_webui_title_after_turn(
@@ -1064,7 +1066,7 @@ async def test_runtime_checkpoint_keeps_provider_state_out_of_public_metadata(
loop.provider.chat_stream_with_retry = AsyncMock(
return_value=LLMResponse(content="done", provider_state=state)
)
session = loop.sessions.get_or_create("cli:private-checkpoint")
session = await loop.sessions.state.get("cli:private-checkpoint")
await loop._run_agent_loop(
TranscriptInput(
@@ -1089,8 +1091,9 @@ async def test_runtime_checkpoint_keeps_provider_state_out_of_public_metadata(
public_payload = loop.sessions.read_session_file(session.key)
assert public_payload is not None
assert "private-checkpoint-blob" not in json.dumps(public_payload)
raw = loop.sessions._get_session_path(session.key).read_text(encoding="utf-8")
assert "private-checkpoint-blob" in raw
stored = loop.sessions.read_session_snapshot(session.key)
assert stored is not None and stored.provider_state is not None
assert stored.provider_state.payload == state.payload
@pytest.mark.asyncio
@@ -1120,7 +1123,7 @@ async def test_subagent_followup_stages_provider_state_before_turn_runs(
session = loop.sessions.get_or_create("cli:subagent-crash")
session.provider_state = _provider_state()
loop.sessions.save(session)
save_completed_subagent(loop, "sub-1", session.key)
await save_completed_subagent(loop, "sub-1", session.key)
msg = InboundMessage(
channel="system",
@@ -1152,7 +1155,7 @@ async def test_subagent_followup_state_is_durable_before_prompt_assembly(
session = loop.sessions.get_or_create("cli:subagent-prompt-crash")
session.provider_state = _provider_state()
loop.sessions.save(session)
save_completed_subagent(loop, "sub-1", session.key)
await save_completed_subagent(loop, "sub-1", session.key)
msg = InboundMessage(
channel="system",
@@ -1186,7 +1189,7 @@ async def test_subagent_redelivery_does_not_duplicate_staged_provider_input(
session = loop.sessions.get_or_create("cli:subagent-redelivery")
session.provider_state = _provider_state()
loop.sessions.save(session)
save_completed_subagent(loop, "sub-1", session.key)
await save_completed_subagent(loop, "sub-1", session.key)
msg = InboundMessage(
channel="system",
sender_id="subagent",
@@ -1236,7 +1239,7 @@ async def test_subagent_followup_clears_state_before_compatibility_failure(
session = loop.sessions.get_or_create("cli:subagent-compat-crash")
session.provider_state = _provider_state()
loop.sessions.save(session)
save_completed_subagent(loop, "sub-1", session.key)
await save_completed_subagent(loop, "sub-1", session.key)
msg = InboundMessage(
channel="system",
@@ -1712,7 +1715,8 @@ async def test_process_message_uses_explicit_session_for_goal_context(
assert result is not None
assert result.content == "ok"
kwargs = loop._run_agent_loop.call_args.kwargs
assert kwargs["session"] is system_session
assert kwargs["session"].key == system_session.key
assert kwargs["session"] is not system_session
assert kwargs["request_context"].session_key == "system"
assert GOAL_STATE_KEY not in kwargs["session"].metadata
@@ -1724,16 +1728,16 @@ async def test_run_agent_loop_continuation_reads_latest_goal_metadata(
from nanobot.agent.runner import AgentRunResult
loop = _make_full_loop(tmp_path)
session = loop.sessions.get_or_create("websocket:late-goal")
session = await loop.sessions.state.get("websocket:late-goal")
seen: dict[str, str | None] = {}
async def fake_run(spec):
assert callable(spec.continuation_callback)
session.metadata[GOAL_STATE_KEY] = {
await loop.sessions.state.update_metadata(session.key, {GOAL_STATE_KEY: {
"status": "active",
"objective": "Goal created during this runner call.",
}
seen["goal_continue"] = spec.continuation_callback()
}})
seen["goal_continue"] = await spec.continuation_callback()
return AgentRunResult(
final_content="ok",
messages=[{"role": "assistant", "content": "ok"}],
@@ -1873,7 +1877,7 @@ async def test_stop_preserves_runtime_checkpoint_for_next_turn(tmp_path: Path) -
async def interrupted_run_agent_loop(_transcript_input, *, session=None, **_kwargs):
assert session is not None
loop._set_runtime_checkpoint(
await loop._set_runtime_checkpoint(
session,
{
"assistant_message": {
@@ -1917,7 +1921,21 @@ async def test_stop_preserves_runtime_checkpoint_for_next_turn(tmp_path: Path) -
first_msg = InboundMessage(channel="feishu", sender_id="u1", chat_id="c4", content="keep progress")
task = asyncio.create_task(loop._process_message(first_msg))
loop._active_tasks[first_msg.session_key] = {task}
await asyncio.wait_for(checkpoint_saved.wait(), timeout=1.0)
checkpoint_wait = asyncio.create_task(checkpoint_saved.wait())
try:
done, _ = await asyncio.wait(
(checkpoint_wait, task), timeout=5, return_when=asyncio.FIRST_COMPLETED,
)
if task in done:
await task
assert checkpoint_wait in done, "the turn did not reach its durable checkpoint"
except BaseException:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
raise
finally:
checkpoint_wait.cancel()
await asyncio.gather(checkpoint_wait, return_exceptions=True)
stop_msg = InboundMessage(channel="feishu", sender_id="u1", chat_id="c4", content="/stop")
stop_ctx = CommandContext(msg=stop_msg, session=None, key=stop_msg.session_key, raw="/stop", loop=loop)
@@ -1976,7 +1994,7 @@ async def test_system_subagent_followup_is_persisted_before_prompt_assembly(tmp_
session.add_message("user", "question")
session.add_message("assistant", "working")
loop.sessions.save(session)
save_completed_subagent(loop, "sub-1", session.key)
await save_completed_subagent(loop, "sub-1", session.key)
runtime = loop.llm_runtime()
seen: dict[str, object] = {}
@@ -2077,7 +2095,7 @@ async def test_turn_usage_is_persisted_with_the_saved_session(tmp_path: Path) ->
@pytest.mark.asyncio
async def test_system_subagent_followup_does_not_log_content(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path)
save_completed_subagent(loop, "sub-logs", "cli:logs")
await save_completed_subagent(loop, "sub-logs", "cli:logs")
async def fake_run_agent_loop(transcript_input, **_kwargs):
initial_messages = _assembled_messages(loop.context, transcript_input)
@@ -2114,7 +2132,7 @@ async def test_system_subagent_followup_does_not_log_content(tmp_path: Path) ->
@pytest.mark.asyncio
async def test_system_subagent_followup_uses_common_turn_lifecycle(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path)
save_completed_subagent(loop, "sub-1", "cli:test")
await save_completed_subagent(loop, "sub-1", "cli:test")
visited: list[str] = []
for name in (
@@ -2243,7 +2261,7 @@ async def test_multiple_subagent_followups_all_persist_as_standalone_history(tmp
loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
for idx in range(3):
save_completed_subagent(loop, f"sub-{idx}", "cli:multi")
await save_completed_subagent(loop, f"sub-{idx}", "cli:multi")
await loop._process_message(
InboundMessage(
channel="system",
@@ -2361,7 +2379,7 @@ async def test_system_subagent_followup_uses_thread_session_and_slack_metadata(t
thread_session = loop.sessions.get_or_create("slack:C123:1700.42")
thread_session.add_message("user", "thread question")
loop.sessions.save(thread_session)
save_completed_subagent(loop, "sub-1", thread_session.key)
await save_completed_subagent(loop, "sub-1", thread_session.key)
seen: dict[str, object] = {}
+16 -15
View File
@@ -64,7 +64,7 @@ async def test_transient_session_keeps_history_without_persisting_or_durable_too
default_restrict_to_workspace=True,
),
)
key = f"websocket:{temporary_chats.create(object(), trusted_webui=True)}"
key = f"websocket:{await temporary_chats.create(object(), trusted_webui=True)}"
await loop._process_message(_message(key, "first question"))
await loop._process_message(_message(key, "second question"))
@@ -111,8 +111,8 @@ async def test_turn_tool_selection_preserves_empty_registries(tmp_path, monkeypa
if selection == "explicit_empty":
kwargs["tools"] = ToolRegistry()
elif selection == "disable_all":
session = loop.sessions.get_or_create(key)
session.policy = SessionPolicy(disabled_tools=frozenset(loop.tools.tool_names))
await loop.sessions.state.get(key)
await loop.sessions.state.set_policy(key, SessionPolicy(disabled_tools=frozenset(loop.tools.tool_names)))
try:
response = await loop.process_direct("Handle this request", session_key=key, **kwargs)
@@ -152,10 +152,10 @@ async def test_session_policy_controls_tool_logs_and_result_offload(
loop.max_tool_result_chars = 2048
key = "websocket:privacy-regression"
if privacy == "temporary":
loop.sessions.get_or_create_transient(key)
await loop.sessions.state.register_transient(key)
else:
session = loop.sessions.get_or_create(key)
session.policy = SessionPolicy(log_content=privacy != "quiet")
await loop.sessions.state.get(key)
await loop.sessions.state.set_policy(key, SessionPolicy(log_content=privacy != "quiet"))
secret = "synthetic-private-query-测试"
text = "synthetic-private-result-" * 1000
image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,c3ludGhldGlj"}}
@@ -198,7 +198,7 @@ async def test_session_policy_controls_tool_logs_and_result_offload(
async def test_direct_transient_run_never_spills_before_cancellation(tmp_path) -> None:
loop = _loop(tmp_path, [])
session = loop.sessions.get_or_create_transient("websocket:cancel-private")
session = await loop.sessions.state.register_transient("websocket:cancel-private")
loop.max_tool_result_chars = 100
loop.tools.prepare_call = MagicMock(return_value=(None, {}, None))
loop.tools.execute = AsyncMock(return_value="synthetic large result" * 1000)
@@ -244,9 +244,9 @@ async def test_session_worker_errors_keep_private_content_out_of_logs(
loop = _loop(tmp_path, [])
key = "websocket:synthetic-worker-error"
if private:
loop.sessions.get_or_create_transient(key)
await loop.sessions.state.register_transient(key)
else:
loop.sessions.get_or_create(key)
await loop.sessions.state.get(key)
secret = "synthetic-private-worker-content"
if failure == "runner":
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=ValueError(secret))
@@ -278,10 +278,11 @@ async def test_transient_session_stays_outside_unified_session(tmp_path) -> None
durable.add_message("user", "durable question")
loop.sessions.save(durable)
key = "websocket:transient-unified"
transient = loop.sessions.get_or_create_transient(key)
await loop.sessions.state.register_transient(key)
await run_session(loop, _message(key, "private question"))
transient = await loop.sessions.state.get(key)
assert [public_history_message(message)["content"] for message in transient.messages] == [
"private question",
"private answer",
@@ -294,7 +295,7 @@ async def test_transient_session_stays_outside_unified_session(tmp_path) -> None
async def test_missing_required_session_cannot_fall_back_to_disk(tmp_path) -> None:
loop = _loop(tmp_path, [])
key = "websocket:transient-stale"
loop.sessions.get_or_create_transient(key)
await loop.sessions.state.register_transient(key)
loop.sessions.invalidate(key)
with pytest.raises(RuntimeError, match="required session is not active"):
@@ -331,12 +332,12 @@ async def test_deleted_child_cannot_notify_a_recreated_parent(tmp_path) -> None:
task_id, = loop.subagents.statuses_for_session(key)
notice = await asyncio.wait_for(loop.bus.consume_inbound(), timeout=2)
assert notice.require_existing_session
assert loop.sessions.delete_session(key)
assert await loop.sessions.state.delete(key)
assert loop.sessions.read_session_file(SubagentSessions.key(task_id)) is None
loop.sessions.save(loop.sessions.get_or_create(key))
await loop.sessions.state.get(key)
assert loop.subagents.statuses_for_session(key) == {}
loop._enqueue_session_message(notice)
await loop._enqueue_session_message(notice)
assert key not in loop._pending_queues
assert await loop._process_message(notice) is None
loop.provider.chat_stream_with_retry.assert_not_awaited()
@@ -370,7 +371,7 @@ async def test_session_discard_control_cancels_active_turn(tmp_path, monkeypatch
)
key = "websocket:transient-cancelled"
previous_file_state = loop._file_state_store.for_session(key)
loop.sessions.get_or_create_transient(
await loop.sessions.state.register_transient(
key,
disabled_tools={"create_goal", "update_goal", "subagent", "cron"},
)
+10 -11
View File
@@ -65,12 +65,12 @@ async def test_goal_input_enters_running_turn_with_scoped_permission(tmp_path, c
channel="cli", sender_id="user", chat_id="test", content=command,
))
async with asyncio.timeout(3):
while loop._pending_queues["cli:test"].empty():
while "cli:test" not in loop._pending_queues or loop._pending_queues["cli:test"].empty():
await asyncio.sleep(0)
assert len(calls) == 1
release.set()
await asyncio.wait_for(asyncio.gather(*loop._active_tasks["cli:test"]), 5)
session = loop.sessions.get_or_create("cli:test")
session = (await loop.sessions.state.get("cli:test"))
assert process.await_count == 1
assert permissions[:3] == [False, True, True]
assert "Discuss the migration" in calls[1]
@@ -105,7 +105,7 @@ async def test_scheduled_goal_command_cannot_generate_internal_input(tmp_path):
assert "only be started by a user" in response.content
assert loop._pending_queues == {}
assert goal_mutation_allowed() is False
assert loop.sessions.get_or_create(msg.session_key).messages == []
assert (await loop.sessions.state.get(msg.session_key)).messages == []
finally:
await loop.aclose()
@@ -142,7 +142,7 @@ async def test_goal_at_iteration_limit_stays_queued_for_a_tool_capable_turn(tmp_
if boundary == "empty":
return LLMResponse(content="")
return LLMResponse(content="The migration plan is ready.")
if kwargs.get("tools") and GOAL_STATE_KEY not in loop.sessions.get_or_create("cli:test").metadata:
if kwargs.get("tools") and GOAL_STATE_KEY not in (await loop.sessions.state.get("cli:test")).metadata:
assert goal_mutation_allowed() is True
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="create", name="create_goal",
@@ -160,7 +160,7 @@ async def test_goal_at_iteration_limit_stays_queued_for_a_tool_capable_turn(tmp_
await run_session(loop, InboundMessage(
channel="cli", sender_id="user", chat_id="test", content="Discuss the migration.",
))
session = loop.sessions.get_or_create("cli:test")
session = (await loop.sessions.state.get("cli:test"))
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
goal_calls = [call for call in calls if "Goal Runtime Guidance" in call]
assert goal_calls
@@ -173,7 +173,7 @@ async def test_goal_at_iteration_limit_stays_queued_for_a_tool_capable_turn(tmp_
async def test_generated_goal_input_survives_pending_followup_recovery(tmp_path):
from nanobot.command.router import CommandContext
from nanobot.session.recovery import pending_followups, record_pending_followup
from nanobot.session.recovery import pending_followups
provider = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "test-model"
@@ -189,14 +189,12 @@ async def test_generated_goal_input_survives_pending_followup_recovery(tmp_path)
raw=message.content, loop=loop, is_user_turn=True,
))
assert isinstance(generated, InboundMessage)
session = loop.sessions.get_or_create(message.session_key)
assert record_pending_followup(session, generated)
loop.sessions.save(session)
assert await loop.sessions.state.queue_followup(message.session_key, generated)
finally:
await loop.aclose()
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model")
session = loop.sessions.get_or_create(message.session_key)
session = (await loop.sessions.state.get(message.session_key))
recovered, = pending_followups(session)
responses = iter([
LLMResponse(content=None, tool_calls=[ToolCallRequest(
@@ -225,6 +223,7 @@ async def test_generated_goal_input_survives_pending_followup_recovery(tmp_path)
async with asyncio.timeout(5):
while (await loop.bus.consume_outbound()).content != "done":
pass
session = await loop.sessions.state.get(message.session_key)
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
assert pending_followups(session) == []
assert sum(row.get("content") == message.content for row in session.messages) == 1
@@ -255,7 +254,7 @@ async def test_internal_continuation_cannot_inherit_goal_permission(tmp_path):
with goal_mutation_permission(True):
await loop._process_message(message, session_key="cli:test")
assert goal_mutation_allowed() is True
assert GOAL_STATE_KEY not in loop.sessions.get_or_create("cli:test").metadata
assert GOAL_STATE_KEY not in (await loop.sessions.state.get("cli:test")).metadata
final_request = provider.chat_stream_with_retry.await_args.kwargs["messages"]
assert "create_goal is unavailable for this turn" in str(final_request)
assert goal_mutation_allowed() is False
+192 -4
View File
@@ -3,10 +3,12 @@
import asyncio
import threading
from copy import deepcopy
from unittest.mock import AsyncMock
import pytest
from nanobot.agent.hook import AgentHook
from nanobot.agent.runner import AgentRunner
from nanobot.agent.tools.context import current_request_context
from nanobot.providers.base import LLMProvider, LLMResponse, LLMUsage
from nanobot.runtime_context import public_history_message
@@ -209,7 +211,7 @@ async def test_cancellation_during_run_cleanup_delivers_finally_once(
loop.sessions.save(session)
runtime_loop = asyncio.get_running_loop()
entered = asyncio.Event()
hook_returned = asyncio.Event()
snapshot_entered = asyncio.Event()
worker_finished = asyncio.Event()
release = threading.Event()
events = []
@@ -223,7 +225,6 @@ async def test_cancellation_during_run_cleanup_delivers_finally_once(
loop.process_direct("Blocked", session_key="cli:blocker"),
))
await asyncio.wait_for(entered.wait(), 5)
hook_returned.set()
async def before_run(self, context):
events.append("before_run")
@@ -262,10 +263,22 @@ async def test_cancellation_during_run_cleanup_delivers_finally_once(
return original_read(path, *args, **kwargs)
monkeypatch.setattr(type(prompt_file), "read_text", read_text)
original_snapshot = loop.runner._run_context_snapshot
snapshot_paused = False
async def snapshot(hook, messages):
nonlocal snapshot_paused
boundary = "after_iteration" if phase == "success_snapshot" else "after_run"
if events and events[-1] == boundary and not snapshot_paused:
snapshot_paused = True
snapshot_entered.set()
await asyncio.Event().wait()
return await original_snapshot(hook, messages)
monkeypatch.setattr(loop.runner, "_run_context_snapshot", snapshot)
first = asyncio.create_task(loop.process_direct("First", session_key="cli:first", hooks=[Lifecycle()]))
try:
await asyncio.wait_for(hook_returned.wait(), 5)
await asyncio.sleep(0)
await asyncio.wait_for(snapshot_entered.wait(), 5)
first.cancel()
with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(first, 0.5)
@@ -294,3 +307,178 @@ async def test_cancellation_during_run_cleanup_delivers_finally_once(
if entered.is_set():
await asyncio.wait_for(worker_finished.wait(), 5)
await loop.aclose()
@pytest.mark.asyncio
@pytest.mark.parametrize("cancel", [False, True])
async def test_prompt_preparation_preserves_context_and_allows_cancellation(
tmp_path, monkeypatch, loop_factory, cancel,
) -> None:
loop = loop_factory()
loop.provider.provider_name = "prompt-test"
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Done"))
runtime_loop = asyncio.get_running_loop()
entered = asyncio.Event()
completed = asyncio.Event()
release = threading.Event()
original = loop.context.build_system_prompt
captured = []
finalized = []
class Lifecycle(AgentHook):
async def on_finally(self, context):
finalized.append((context.stop_reason, current_request_context(), asyncio.get_running_loop()))
loop._extra_hooks.append(Lifecycle())
def build(**kwargs):
captured.append(current_request_context())
runtime_loop.call_soon_threadsafe(entered.set)
try:
assert release.wait(5), "test did not release prompt filesystem work"
return original(**kwargs)
finally:
runtime_loop.call_soon_threadsafe(completed.set)
monkeypatch.setattr(loop.context, "build_system_prompt", build)
task = asyncio.create_task(loop.process_direct("Hello", session_key="cli:prompt-work"))
try:
await asyncio.wait_for(entered.wait(), timeout=5)
assert captured[0] is not None
assert captured[0].session_key == "cli:prompt-work"
assert captured[0].workspace_scope.project_path == tmp_path.resolve()
assert current_request_context() is None
loop.provider.chat_stream_with_retry.assert_not_awaited()
if cancel:
task.cancel()
with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(task, timeout=5)
loop.provider.chat_stream_with_retry.assert_not_awaited()
assert len(finalized) == 1
reason, request, final_loop = finalized[0]
assert reason == "cancelled"
assert request is not None and request.session_key == "cli:prompt-work"
assert final_loop is runtime_loop
release.set()
await asyncio.wait_for(completed.wait(), timeout=5)
if not cancel:
result = await asyncio.wait_for(task, timeout=5)
assert result is not None and result.content == "Done"
saved = loop.sessions.read_session_snapshot("cli:prompt-work")
assert [public_history_message(message)["content"] for message in saved.messages] == ["Hello", "Done"]
assert current_request_context() is None
finally:
release.set()
if not task.done():
task.cancel()
await asyncio.gather(task, return_exceptions=True)
if captured:
await asyncio.wait_for(completed.wait(), timeout=5)
await loop.aclose()
@pytest.mark.asyncio
async def test_cancelled_prompt_keeps_its_worker_slot_until_read_finishes() -> None:
runner = AgentRunner()
runtime_loop = asyncio.get_running_loop()
entered = {name: asyncio.Event() for name in ("first", "second")}
released = {name: threading.Event() for name in entered}
def read(name):
runtime_loop.call_soon_threadsafe(entered[name].set)
assert released[name].wait(5), "test did not release prompt read"
return name
first = asyncio.create_task(runner.prepare_prompt(read, "first"))
tasks = [first]
try:
await asyncio.wait_for(entered["first"].wait(), timeout=5)
first.cancel()
with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(first, timeout=5)
second = asyncio.create_task(runner.prepare_prompt(read, "second"))
tasks.append(second)
await asyncio.sleep(0)
# The cancelled caller's read keeps its slot until the worker exits.
assert not entered["second"].is_set()
released["first"].set()
await asyncio.wait_for(entered["second"].wait(), timeout=5)
released["second"].set()
assert await asyncio.wait_for(second, timeout=5) == "second"
finally:
for release in released.values():
release.set()
for task in tasks:
if not task.done():
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
await asyncio.gather(*tuple(runner.context_governor._preparation_jobs), return_exceptions=True)
@pytest.mark.asyncio
@pytest.mark.parametrize("phase", ["request", "usage"])
@pytest.mark.parametrize("cancel", [False, True])
async def test_local_token_estimation_leaves_loop_available(
tmp_path, monkeypatch, loop_factory, phase, cancel,
) -> None:
loop = loop_factory()
loop.provider.provider_name = "token-test"
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Done"))
runtime_loop = asyncio.get_running_loop()
entered = asyncio.Event()
completed = asyncio.Event()
release = threading.Event()
captured = []
finalized = []
class Lifecycle(AgentHook):
async def on_finally(self, context):
finalized.append((context.stop_reason, current_request_context(), asyncio.get_running_loop()))
loop._extra_hooks.append(Lifecycle())
def count(*_args, **_kwargs):
captured.append(current_request_context())
runtime_loop.call_soon_threadsafe(entered.set)
try:
assert release.wait(5), "test did not release local token estimation"
return 10, "test-counter"
finally:
runtime_loop.call_soon_threadsafe(completed.set)
module = "context_governance" if phase == "request" else "runner"
monkeypatch.setattr(f"nanobot.agent.{module}.estimate_prompt_tokens_chain", count)
task = asyncio.create_task(loop.process_direct("Hello", session_key="cli:token-work"))
try:
await asyncio.wait_for(entered.wait(), timeout=5)
assert captured[0] is not None
assert captured[0].session_key == "cli:token-work"
assert captured[0].workspace_scope.project_path == tmp_path.resolve()
assert current_request_context() is None
if phase == "request":
loop.provider.chat_stream_with_retry.assert_not_awaited()
else:
loop.provider.chat_stream_with_retry.assert_awaited_once()
if cancel:
task.cancel()
with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(asyncio.shield(task), timeout=1)
assert len(finalized) == 1
reason, request, final_loop = finalized[0]
assert reason == "cancelled"
assert request is not None and request.session_key == "cli:token-work"
assert final_loop is runtime_loop
else:
release.set()
result = await asyncio.wait_for(task, timeout=5)
assert result is not None and result.content == "Done"
saved = loop.sessions.read_session_snapshot("cli:token-work")
assert [public_history_message(message)["content"] for message in saved.messages] == ["Hello", "Done"]
finally:
release.set()
if not task.done():
task.cancel()
await asyncio.gather(task, return_exceptions=True)
if captured:
await asyncio.wait_for(completed.wait(), timeout=5)
await loop.aclose()
+1 -1
View File
@@ -811,7 +811,7 @@ async def test_runner_does_not_auto_continue_goal_after_policy_terminal(
model="test-model",
max_iterations=3,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
continuation_callback=lambda: "Continue working.",
continuation_callback=AsyncMock(return_value="Continue working."),
terminal_injection_callback=terminal_injection_callback,
))
+4 -4
View File
@@ -26,7 +26,7 @@ def run_spec():
)
@pytest.mark.parametrize("callback", [None, lambda: None], ids=["absent", "no-request"])
@pytest.mark.parametrize("callback", [None, AsyncMock(return_value=None)], ids=["absent", "no-request"])
async def test_runner_completes_without_a_continuation_request(run_spec, callback):
run_spec.continuation_callback = callback
@@ -42,7 +42,7 @@ async def test_continuation_injects_text_without_exceeding_budget(run_spec, max_
continuation = "Continue working toward the active sustained goal."
run_spec.max_iterations = max_iterations
run_spec.finalize_on_max_iterations = finalize
run_spec.continuation_callback = lambda: continuation
run_spec.continuation_callback = AsyncMock(side_effect=lambda: continuation)
result = await AgentRunner().run(run_spec)
@@ -60,7 +60,7 @@ async def test_runner_does_not_request_continuation_on_error(run_spec):
run_spec.runtime.provider.chat_stream_with_retry.return_value = LLMResponse(
content=None, finish_reason="error",
)
callback = MagicMock(return_value="Continue working.")
callback = AsyncMock(return_value="Continue working.")
run_spec.continuation_callback = callback
result = await AgentRunner().run(run_spec)
@@ -85,7 +85,7 @@ async def test_runner_reads_continuation_state_after_each_response(run_spec):
return LLMResponse(content="The draft is complete.")
run_spec.runtime.provider.chat_stream_with_retry.side_effect = respond
run_spec.continuation_callback = lambda: continuation
run_spec.continuation_callback = AsyncMock(side_effect=lambda: continuation)
result = await AgentRunner().run(run_spec)
+2 -1
View File
@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from agent.runner_helpers import make_run_spec
from agent.session_helpers import mock_session_manager
from nanobot.agent.context import TranscriptInput
from nanobot.agent.context_governance import (
BACKFILL_CONTENT,
@@ -80,7 +81,7 @@ def _make_loop(tmp_path):
provider.get_default_model.return_value = "test-model"
with patch("nanobot.agent.loop.ContextBuilder"), \
patch("nanobot.agent.loop.SessionManager"), \
patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path)
+21 -14
View File
@@ -37,7 +37,6 @@ def _make_loop(tmp_path, *, recovery_admission=None):
provider.get_default_model.return_value = "test-model"
with patch("nanobot.agent.loop.ContextBuilder"), \
patch("nanobot.agent.loop.SessionManager"), \
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
mock_sub_mgr.return_value.close = AsyncMock()
@@ -393,7 +392,7 @@ async def test_goal_continuation_precedes_terminal_wait():
continuation_checks = 0
terminal_waits = 0
def continue_goal() -> str | None:
async def continue_goal() -> str | None:
nonlocal continuation_checks
continuation_checks += 1
return "Continue the active goal." if continuation_checks == 1 else None
@@ -749,7 +748,7 @@ async def test_pending_injection_resolves_its_own_runtime_context(tmp_path):
)
loop.register_runtime_context_provider(provide_identity)
session = loop.sessions.get_or_create("telegram:group-1")
session = await loop.sessions.state.get("telegram:group-1")
pending_queue = asyncio.Queue()
await pending_queue.put(InboundMessage(
channel="telegram",
@@ -1444,9 +1443,9 @@ async def test_persistent_conversion_error_does_not_drop_later_session_inputs(tm
calls += 1
if calls == 1:
for content in ["before", "bad", "after"]:
loop._enqueue_session_message(InboundMessage(
(await loop._enqueue_session_message(InboundMessage(
channel="cli", sender_id="u", chat_id="c", content=content,
))
)))
return LLMResponse(content="answer", finish_reason="stop")
async def context_provider(request):
@@ -1472,16 +1471,25 @@ async def test_persistent_conversion_error_does_not_drop_later_session_inputs(tm
@pytest.mark.asyncio
async def test_session_inbox_is_installed_before_worker_start(tmp_path):
async def test_session_inbox_is_installed_before_worker_start(tmp_path, monkeypatch):
"""A preloaded burst has one FIFO path before the worker can be scheduled."""
from nanobot.bus.events import InboundMessage, OutboundMessage
loop = _make_loop(tmp_path)
first_started = asyncio.Event()
all_enqueued = asyncio.Event()
release_first = asyncio.Event()
all_processed = asyncio.Event()
processed: list[str] = []
followups = [f"follow-up-{index}" for index in range(40)]
enqueue = loop._enqueue_session_message
async def capture_enqueue(msg):
await enqueue(msg)
if msg.content == followups[-1]:
all_enqueued.set()
monkeypatch.setattr(loop, "_enqueue_session_message", capture_enqueue)
async def _process_message(msg, **_kwargs):
processed.append(msg.content)
@@ -1502,14 +1510,11 @@ async def test_session_inbox_is_installed_before_worker_start(tmp_path):
)
run_task = asyncio.create_task(loop.run())
await asyncio.wait_for(first_started.wait(), timeout=2)
await asyncio.wait_for(
asyncio.gather(first_started.wait(), all_enqueued.wait()), timeout=30,
)
session_key = "cli:c"
for _ in range(200):
pending = loop._pending_queues.get(session_key)
if pending is not None and pending.qsize() == len(followups):
break
await asyncio.sleep(0.01)
assert len(loop._active_tasks[session_key]) == 1
assert loop._pending_queues[session_key].qsize() == len(followups)
@@ -1562,7 +1567,8 @@ async def test_busy_session_burst_reaches_next_model_call_as_one_ordered_batch(
model="test-model",
)
loop.tools.get_definitions = MagicMock(return_value=[])
loop.sessions.get_or_create("cli:c").policy = SessionPolicy(log_content=log_content)
await loop.sessions.state.get("cli:c")
await loop.sessions.state.set_policy("cli:c", SessionPolicy(log_content=log_content))
followups = [f"follow-up-{index:02}" for index in range(12)]
run_task = asyncio.create_task(loop.run())
@@ -1594,7 +1600,8 @@ async def test_busy_session_burst_reaches_next_model_call_as_one_ordered_batch(
break
await asyncio.sleep(0.01)
loop.stop()
await asyncio.wait_for(run_task, timeout=2)
# Shutdown drains accepted writes and closes the worker's WAL connection.
await asyncio.wait_for(run_task, timeout=30)
assert len(captured_messages) == 2
second_request = "\n".join(
+2 -2
View File
@@ -20,7 +20,7 @@ from nanobot.runtime_context import (
webui_quote_runtime_context,
)
from nanobot.sdk.types import snapshot_from_session
from nanobot.session.manager import Session, _message_preview_text
from nanobot.session.manager import Session, message_preview_text
from nanobot.session.webui_turns import _title_inputs
from nanobot.webui.transcript import _session_user_event
@@ -163,7 +163,7 @@ def test_webui_preview_title_and_backfill_hide_runtime_context() -> None:
}
session = Session(key="websocket:chat", messages=[persisted])
assert _message_preview_text(persisted) == "visible user text"
assert message_preview_text(persisted) == "visible user text"
assert _title_inputs(session) == ("visible user text", "")
event = _session_user_event("websocket:chat", persisted)
assert event is not None
+3 -3
View File
@@ -148,7 +148,7 @@ def test_same_snapshot_default_clears_preset_and_publishes_update(tmp_path: Path
assert published == [("fast-model", None)]
def test_named_default_refresh_is_used_by_sessions_without_override(tmp_path: Path) -> None:
async def test_named_default_refresh_is_used_by_sessions_without_override(tmp_path: Path) -> None:
provider = _provider("shared-model")
shared_signature = ("shared-model", "auto", "same-settings")
snapshots = {
@@ -189,7 +189,7 @@ def test_named_default_refresh_is_used_by_sessions_without_override(tmp_path: Pa
session = loop.sessions.get_or_create("sdk:new-after-refresh")
assert runtime.model_preset == "deep"
assert loop.runtime_for_session(session).model_preset == "deep"
assert (await loop.runtime_for_session(session)).model_preset == "deep"
assert model_preset_from_metadata(session.metadata) is None
@@ -231,7 +231,7 @@ async def test_config_invalidation_defers_canonical_notification_until_default_r
catalog["fast"] = ModelPresetConfig(model="model-b")
loop.invalidate_runtime_config()
runtime = loop.runtime_for_session(session)
runtime = (await loop.runtime_for_session(session))
await asyncio.sleep(0)
assert published == []
+18 -18
View File
@@ -1,5 +1,5 @@
from types import SimpleNamespace
from unittest.mock import MagicMock
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -242,19 +242,19 @@ def test_self_tool_inspect_shows_model_preset(tmp_path) -> None:
assert "model_preset: 'fast'" in output
def test_self_tool_set_model_preset_via_modify(tmp_path) -> None:
async def test_self_tool_set_model_preset_via_modify(tmp_path) -> None:
presets = {
"fast": ModelPresetConfig(model="openai/gpt-4.1"),
}
loop = _make_loop(tmp_path, presets=presets)
tool = _my_tool(loop)
result = tool._modify("model_preset", "fast")
result = await tool._modify("model_preset", "fast")
assert "Error" not in result
assert loop.model_preset == "fast"
assert loop.model == "openai/gpt-4.1"
def test_self_tool_set_model_preset_switches_back_to_default(tmp_path) -> None:
async def test_self_tool_set_model_preset_switches_back_to_default(tmp_path) -> None:
presets = {
"default": ModelPresetConfig(model="base-model", context_window_tokens=1000),
"fast": ModelPresetConfig(model="openai/gpt-4.1", context_window_tokens=32_768),
@@ -262,7 +262,7 @@ def test_self_tool_set_model_preset_switches_back_to_default(tmp_path) -> None:
loop = _make_loop(tmp_path, presets=presets, active_preset="fast")
tool = _my_tool(loop)
result = tool._modify("model_preset", "default")
result = await tool._modify("model_preset", "default")
assert "Error" not in result
assert "model is now 'base-model'" in result
@@ -271,7 +271,7 @@ def test_self_tool_set_model_preset_switches_back_to_default(tmp_path) -> None:
assert loop.context_window_tokens == 1000
def test_self_tool_set_model_preset_unknown_lists_available(tmp_path) -> None:
async def test_self_tool_set_model_preset_unknown_lists_available(tmp_path) -> None:
presets = {
"default": ModelPresetConfig(model="base-model"),
"fast": ModelPresetConfig(model="openai/gpt-4.1"),
@@ -279,14 +279,14 @@ def test_self_tool_set_model_preset_unknown_lists_available(tmp_path) -> None:
loop = _make_loop(tmp_path, presets=presets)
tool = _my_tool(loop)
result = tool._modify("model_preset", "missing")
result = await tool._modify("model_preset", "missing")
assert result == "Error: model_preset 'missing' not found. Available: default, fast."
assert loop.model_preset is None
assert loop.model == "base-model"
def test_self_tool_sets_model_preset_for_current_session(tmp_path) -> None:
async def test_self_tool_sets_model_preset_for_current_session(tmp_path) -> None:
presets = {
"default": ModelPresetConfig(model="base-model"),
"fast": ModelPresetConfig(model="openai/gpt-4.1"),
@@ -300,7 +300,7 @@ def test_self_tool_sets_model_preset_for_current_session(tmp_path) -> None:
session_key="cli:one",
metadata={"source": "self-tool"},
)):
result = tool._modify("model_preset", "fast")
result = await tool._modify("model_preset", "fast")
assert "for the next turn" in result
assert model_preset_from_metadata(
@@ -310,9 +310,9 @@ def test_self_tool_sets_model_preset_for_current_session(tmp_path) -> None:
assert loop.model == "base-model"
def test_self_tool_reports_session_preset_provider_configuration_error(tmp_path) -> None:
async def test_self_tool_reports_session_preset_provider_configuration_error(tmp_path) -> None:
loop = _make_loop(tmp_path)
loop.set_session_model_preset = MagicMock(
loop.set_session_model_preset = AsyncMock(
side_effect=ValueError("No API key configured for provider 'openai'.")
)
tool = _my_tool(loop)
@@ -322,7 +322,7 @@ def test_self_tool_reports_session_preset_provider_configuration_error(tmp_path)
chat_id="one",
session_key="cli:one",
)):
result = tool._modify("model_preset", "broken")
result = await tool._modify("model_preset", "broken")
assert result == "Error: No API key configured for provider 'openai'."
@@ -334,7 +334,7 @@ def test_self_tool_reports_session_preset_provider_configuration_error(tmp_path)
("context_window_tokens", 8_192),
],
)
def test_self_tool_rejects_instance_runtime_changes_in_session(
async def test_self_tool_rejects_instance_runtime_changes_in_session(
tmp_path,
key: str,
value: object,
@@ -347,24 +347,24 @@ def test_self_tool_rejects_instance_runtime_changes_in_session(
channel="cli",
chat_id="one",
session_key=session.key,
runtime=loop.runtime_for_session(session),
runtime=(await loop.runtime_for_session(session)),
)):
result = tool._modify(key, value)
result = await tool._modify(key, value)
other_runtime = loop.runtime_for_session(loop.sessions.get_or_create("cli:two"))
other_runtime = (await loop.runtime_for_session(loop.sessions.get_or_create("cli:two")))
assert "instance-wide and disabled" in result
assert "model_preset" in result
assert other_runtime.model == "base-model"
assert other_runtime.context_window_tokens == 1000
def test_self_tool_set_model_clears_active_preset(tmp_path) -> None:
async def test_self_tool_set_model_clears_active_preset(tmp_path) -> None:
presets = {
"fast": ModelPresetConfig(model="openai/gpt-4.1"),
}
loop = _make_loop(tmp_path, presets=presets, active_preset="fast")
tool = _my_tool(loop)
result = tool._modify("model", "anthropic/claude-opus-4-5")
result = await tool._modify("model", "anthropic/claude-opus-4-5")
assert "Error" not in result
assert loop.model_preset is None
assert loop.model == "anthropic/claude-opus-4-5"
+68 -404
View File
@@ -1,423 +1,87 @@
"""Tests for atomic session save and corrupt-file repair."""
"""Private continuation state stays outside public conversation history."""
import json
from datetime import datetime
from pathlib import Path
import pytest
from filelock import Timeout
from nanobot.providers.base import ProviderConversationState
from nanobot.session.manager import Session, SessionManager
class TestAtomicSave:
def test_save_creates_valid_jsonl(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
session = Session(key="test:1")
session.add_message("user", "hello")
session.add_message("assistant", "hi")
mgr.save(session)
path = mgr._get_session_path("test:1")
lines = path.read_text(encoding="utf-8").strip().split("\n")
assert len(lines) == 3
meta = json.loads(lines[0])
assert meta["_type"] == "metadata"
assert meta["key"] == "test:1"
msg1 = json.loads(lines[1])
assert msg1["role"] == "user"
assert msg1["content"] == "hello"
def test_no_tmp_file_left_after_successful_save(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
session = Session(key="test:clean")
mgr.save(session)
tmp_files = list(mgr.sessions_dir.glob("*.tmp"))
assert tmp_files == []
def test_unique_tmp_file_cleaned_up_on_write_failure(
self,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
):
mgr = SessionManager(tmp_path)
session = Session(key="test:fail")
path = mgr._get_session_path("test:fail")
stale_shared_tmp = path.with_suffix(".jsonl.tmp")
unique_tmp = path.with_name(f".{path.name}.save-failure.tmp")
path.parent.mkdir(parents=True, exist_ok=True)
stale_shared_tmp.write_text("stale", encoding="utf-8")
monkeypatch.setattr(
"nanobot.session.manager.secrets.token_hex",
lambda _length: "save-failure",
)
original_dumps = json.dumps
def failing_dumps(obj, **kwargs):
if isinstance(obj, dict) and obj.get("role") == "assistant":
raise OSError("simulated disk full")
return original_dumps(obj, **kwargs)
session = Session(key="test:fail")
session.messages = [
{"role": "user", "content": "ok"},
{"role": "assistant", "content": "will fail"},
]
import unittest.mock
with (
unittest.mock.patch(
"nanobot.session.manager.json.dumps",
side_effect=failing_dumps,
),
pytest.raises(OSError, match="simulated disk full"),
):
mgr.save(session)
assert not unique_tmp.exists()
assert stale_shared_tmp.read_text(encoding="utf-8") == "stale"
def test_overwrite_preserves_latest_data(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
session = Session(key="test:overwrite")
session.add_message("user", "first")
mgr.save(session)
session.add_message("user", "second")
mgr.save(session)
mgr.invalidate("test:overwrite")
loaded = mgr.get_or_create("test:overwrite")
assert len(loaded.messages) == 2
assert loaded.messages[0]["content"] == "first"
assert loaded.messages[1]["content"] == "second"
def test_consecutive_saves_are_consistent(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
session = Session(key="test:consistency")
for i in range(5):
session.add_message("user", f"msg{i}")
mgr.save(session)
mgr.invalidate("test:consistency")
loaded = mgr.get_or_create("test:consistency")
assert len(loaded.messages) == 5
for i in range(5):
assert loaded.messages[i]["content"] == f"msg{i}"
def test_managers_for_same_directory_coordinate_saves(self, tmp_path: Path):
workspace = tmp_path / "workspace"
sessions_root = tmp_path / "runtime"
owner = SessionManager(workspace, sessions_root=sessions_root)
peer = SessionManager(workspace, sessions_root=sessions_root)
assert owner.sessions_dir == peer.sessions_dir
session = Session(key="test:peer-manager")
peer._jsonl_store._session_files_lock.timeout = 0
with owner.locked_session_files(), pytest.raises(Timeout):
peer.save(session)
peer.save(session)
assert peer._get_session_path(session.key).is_file()
def test_provider_state_round_trips_in_private_record_only(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
secret = "encrypted-reasoning-blob"
session = Session(
key="test:provider-state",
provider_state=ProviderConversationState(
kind="openai_responses",
provider="openai:https://api.openai.com/v1",
model="gpt-5.6",
version=1,
payload={
"items": [
{
"type": "reasoning",
"encrypted_content": secret,
}
]
},
pending_messages=[{"role": "user", "content": "continue"}],
),
)
session.add_message("user", "hello")
mgr.save(session)
records = [
json.loads(line)
for line in mgr._get_session_path(session.key)
.read_text(encoding="utf-8")
.splitlines()
]
assert [record.get("_type") for record in records] == [
"metadata",
"provider_state",
None,
]
assert secret in records[1]["state"]["payload"]["items"][0]["encrypted_content"]
mgr.invalidate(session.key)
loaded = mgr.get_or_create(session.key)
assert loaded.provider_state is not None
assert loaded.provider_state.to_private_record() == session.provider_state.to_private_record()
public_payload = mgr.read_session_file(session.key)
assert public_payload is not None
assert public_payload["messages"] == [session.messages[0]]
assert secret not in json.dumps(public_payload)
assert secret not in json.dumps(mgr.list_sessions())
def test_provider_state_does_not_consume_list_preview_budget(
self,
tmp_path: Path,
monkeypatch,
):
import nanobot.session.manager as session_manager
monkeypatch.setattr(session_manager, "_SESSION_LIST_PREVIEW_MAX_CHARS", 100)
mgr = SessionManager(tmp_path)
session = Session(
key="test:provider-state-preview",
provider_state=ProviderConversationState(
kind="openai_responses",
provider="openai:test",
model="test-model",
version=1,
payload={"items": [{"encrypted_content": "x" * 200}]},
),
)
session.add_message("user", "visible preview")
mgr.save(session)
assert mgr.list_sessions()[0]["preview"] == "visible preview"
def test_clear_and_fork_discard_provider_state(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
state = ProviderConversationState(
def test_provider_state_round_trips_in_private_record_only(tmp_path: Path):
mgr = SessionManager(tmp_path)
secret = "encrypted-reasoning-blob"
session = Session(
key="test:provider-state",
provider_state=ProviderConversationState(
kind="openai_responses",
provider="openai:test",
provider="openai:https://api.openai.com/v1",
model="gpt-5.6",
version=1,
payload={"items": []},
)
source = Session(key="test:state-source", provider_state=state)
source.add_message("user", "hello")
mgr.save(source)
fork = mgr.fork_session_before_user_index(
source.key,
"test:state-fork",
1,
)
assert fork is not None
assert fork.provider_state is None
source.clear()
assert source.provider_state is None
def test_invalid_provider_state_record_is_not_public_history(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
path = mgr._get_session_path("test:bad-provider-state")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
"\n".join(
[
json.dumps(
{
"_type": "metadata",
"key": "test:bad-provider-state",
"created_at": datetime.now().isoformat(),
"updated_at": datetime.now().isoformat(),
"metadata": {},
"last_consolidated": 0,
}
),
json.dumps(
{
"_type": "provider_state",
"state": {"kind": "openai_responses"},
}
),
json.dumps({"role": "user", "content": "safe"}),
payload={
"items": [
{
"type": "reasoning",
"encrypted_content": secret,
}
]
)
+ "\n",
encoding="utf-8",
)
},
pending_messages=[{"role": "user", "content": "continue"}],
),
)
session.add_message("user", "hello")
mgr.save(session)
loaded = mgr._load("test:bad-provider-state")
assert loaded is not None
assert loaded.provider_state is None
assert loaded.messages == [{"role": "user", "content": "safe"}]
mgr.invalidate(session.key)
loaded = mgr.get_or_create(session.key)
assert loaded.provider_state is not None
assert loaded.provider_state.to_private_record() == session.provider_state.to_private_record()
public_payload = mgr.read_session_file(session.key)
assert public_payload is not None
assert public_payload["messages"] == [session.messages[0]]
assert secret not in json.dumps(public_payload)
assert secret not in json.dumps(mgr.list_sessions())
class TestRepairCorruptFile:
def _write_corrupt_jsonl(self, path: Path, lines: list[str]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
def test_provider_state_does_not_consume_list_preview_budget(
tmp_path: Path,
monkeypatch,
):
mgr = SessionManager(tmp_path)
session = Session(
key="test:provider-state-preview",
provider_state=ProviderConversationState(
kind="openai_responses",
provider="openai:test",
model="test-model",
version=1,
payload={"items": [{"encrypted_content": "x" * 200}]},
),
)
session.add_message("user", "visible preview")
mgr.save(session)
def test_truncated_last_line_recovered(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
path = mgr._get_session_path("test:trunc")
assert mgr.list_sessions()[0]["preview"] == "visible preview"
valid_meta = json.dumps({
"_type": "metadata",
"key": "test:trunc",
"created_at": datetime.now().isoformat(),
"updated_at": datetime.now().isoformat(),
"metadata": {},
"last_consolidated": 0,
})
valid_msg = json.dumps({"role": "user", "content": "hello"})
def test_clear_and_fork_discard_provider_state(tmp_path: Path):
mgr = SessionManager(tmp_path)
state = ProviderConversationState(
kind="openai_responses",
provider="openai:test",
model="gpt-5.6",
version=1,
payload={"items": []},
)
source = Session(key="test:state-source", provider_state=state)
source.add_message("user", "hello")
mgr.save(source)
self._write_corrupt_jsonl(path, [
valid_meta,
valid_msg,
'{"role": "assistant", "content": "partial...',
])
fork = mgr.fork_session_before_user_index(
source.key,
"test:state-fork",
1,
)
assert fork is not None
assert fork.provider_state is None
session = mgr._load("test:trunc")
assert session is not None
assert len(session.messages) == 1
assert session.messages[0]["content"] == "hello"
def test_corrupt_metadata_line_skipped(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
path = mgr._get_session_path("test:badmeta")
self._write_corrupt_jsonl(path, [
"NOT VALID JSON!!!",
'{"role": "user", "content": "survived"}',
])
session = mgr._load("test:badmeta")
assert session is not None
assert len(session.messages) == 1
assert session.messages[0]["content"] == "survived"
def test_all_corrupt_lines_returns_none(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
path = mgr._get_session_path("test:allbad")
self._write_corrupt_jsonl(path, [
"garbage line 1",
"garbage line 2",
"{{invalid json",
])
session = mgr._load("test:allbad")
assert session is None
def test_empty_file_returns_empty_session(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
path = mgr._get_session_path("test:empty")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("", encoding="utf-8")
session = mgr._load("test:empty")
assert session is not None
assert session.messages == []
assert session.key == "test:empty"
def test_repair_preserves_valid_messages_amid_corruption(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
path = mgr._get_session_path("test:mixed")
self._write_corrupt_jsonl(path, [
json.dumps({"_type": "metadata", "key": "test:mixed",
"created_at": datetime.now().isoformat(),
"updated_at": datetime.now().isoformat(),
"metadata": {}, "last_consolidated": 0}),
"BROKEN",
json.dumps({"role": "user", "content": "msg1"}),
'{"role": "assistant", "content": "broken',
json.dumps({"role": "user", "content": "msg2"}),
])
session = mgr._load("test:mixed")
assert session is not None
assert len(session.messages) == 2
assert session.messages[0]["content"] == "msg1"
assert session.messages[1]["content"] == "msg2"
def test_repair_with_bad_timestamp_uses_fallback(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
path = mgr._get_session_path("test:badts")
self._write_corrupt_jsonl(path, [
json.dumps({"_type": "metadata", "key": "test:badts",
"created_at": "not-a-date",
"updated_at": "also-bad",
"metadata": {}, "last_consolidated": 5}),
json.dumps({"role": "user", "content": "hi"}),
])
session = mgr._load("test:badts")
assert session is not None
# offset 5 exceeds the single loaded message; reset to avoid hiding history (#4066)
assert session.last_consolidated == 0
assert isinstance(session.created_at, datetime)
def test_read_session_file_repairs_corrupt_jsonl(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
path = mgr._get_session_path("test:read-repair")
self._write_corrupt_jsonl(path, [
json.dumps({
"_type": "metadata",
"key": "test:read-repair",
"created_at": datetime.now().isoformat(),
"updated_at": datetime.now().isoformat(),
"metadata": {"source": "repair"},
"last_consolidated": 0,
}),
json.dumps({"role": "user", "content": "survived"}),
'{"role": "assistant", "content": "partial...',
])
payload = mgr.read_session_file("test:read-repair")
assert payload is not None
assert payload["key"] == "test:read-repair"
assert payload["metadata"] == {"source": "repair"}
assert payload["messages"] == [{"role": "user", "content": "survived"}]
def test_list_sessions_keeps_repaired_corrupt_file(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
path = mgr._get_session_path("test:list-repair")
self._write_corrupt_jsonl(path, [
"NOT VALID JSON",
json.dumps({
"_type": "metadata",
"key": "test:list-repair",
"created_at": datetime.now().isoformat(),
"updated_at": datetime.now().isoformat(),
"metadata": {},
"last_consolidated": 0,
}),
json.dumps({"role": "user", "content": "hello"}),
])
sessions = mgr.list_sessions()
assert any(s["key"] == "test:list-repair" for s in sessions)
def test_get_or_create_returns_new_session_for_corrupt_file(self, tmp_path: Path):
mgr = SessionManager(tmp_path)
path = mgr._get_session_path("test:fallback")
self._write_corrupt_jsonl(path, ["{{{{"])
session = mgr.get_or_create("test:fallback")
assert session is not None
assert session.messages == []
assert session.key == "test:fallback"
source.clear()
assert source.provider_state is None
+14 -140
View File
@@ -1,144 +1,18 @@
"""Regression tests for collision-resistant session filenames."""
import json
from datetime import datetime
from pathlib import Path
"""Session keys remain distinct even when their display filenames collide."""
from nanobot.session.manager import Session, SessionManager
from nanobot.utils.helpers import safe_filename
def _manager(tmp_path: Path, monkeypatch) -> SessionManager:
monkeypatch.setattr(
"nanobot.session.manager.get_legacy_sessions_dir",
lambda: tmp_path / "legacy_sessions",
)
return SessionManager(tmp_path / "workspace")
def _write_session_file(path: Path, key: str, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
metadata = {
"_type": "metadata",
"key": key,
"created_at": datetime(2025, 1, 1).isoformat(),
"updated_at": datetime(2025, 1, 1).isoformat(),
"metadata": {"source": "test"},
"last_consolidated": 0,
}
message = {"role": "user", "content": content}
path.write_text(
json.dumps(metadata) + "\n" + json.dumps(message) + "\n",
encoding="utf-8",
)
def test_distinct_keys_have_distinct_filenames(tmp_path: Path, monkeypatch) -> None:
sm = _manager(tmp_path, monkeypatch)
first = sm._get_session_path("telegram:a_b")
second = sm._get_session_path("telegram:a:b")
assert first.name != second.name
assert sm.safe_key("telegram:a_b") == sm.safe_key("telegram:a:b")
assert sm._storage_key("telegram:a_b") != sm._storage_key("telegram:a:b")
def test_save_uses_new_path_not_lossy(tmp_path: Path, monkeypatch) -> None:
sm = _manager(tmp_path, monkeypatch)
key = "telegram:a:b"
session = Session(key=key)
session.add_message("user", "first")
sm.save(session)
new_path = sm._get_session_path(key)
lossy_path = sm._get_legacy_lossy_path(key)
_write_session_file(lossy_path, key, "stale lossy content")
stale_lossy = lossy_path.read_text(encoding="utf-8")
session.add_message("assistant", "latest content")
sm.save(session)
assert new_path.exists()
assert lossy_path.exists()
assert "latest content" in new_path.read_text(encoding="utf-8")
assert lossy_path.read_text(encoding="utf-8") == stale_lossy
def test_load_ignores_legacy_lossy_path(tmp_path: Path, monkeypatch) -> None:
sm = _manager(tmp_path, monkeypatch)
key = "telegram:legacy:lossy"
lossy_path = sm._get_legacy_lossy_path(key)
_write_session_file(lossy_path, key, "loaded from lossy")
session = sm._load(key)
assert session is None
assert lossy_path.exists()
assert not sm._get_session_path(key).exists()
def test_load_ignores_legacy_global_path(tmp_path: Path, monkeypatch) -> None:
sm = _manager(tmp_path, monkeypatch)
key = "telegram:legacy:global"
new_path = sm._get_session_path(key)
legacy_path = sm._get_legacy_session_path(key)
_write_session_file(legacy_path, key, "loaded from global")
session = sm._load(key)
assert session is None
assert legacy_path.exists()
assert not new_path.exists()
def test_safe_key_is_lossy() -> None:
assert SessionManager.safe_key("telegram:a_b") == SessionManager.safe_key("telegram:a:b")
def test_storage_key_is_collision_resistant() -> None:
encoded = {
SessionManager._storage_key("a:b"),
SessionManager._storage_key("a_b"),
SessionManager._storage_key("a:b:c"),
}
assert len(encoded) == 3
assert SessionManager._storage_key("telegram:a_b") != SessionManager._storage_key("telegram:a:b")
def test_lossy_path_helper_returns_expected_path(tmp_path: Path, monkeypatch) -> None:
sm = _manager(tmp_path, monkeypatch)
key = "telegram:a:b"
expected = sm.sessions_dir / f"{safe_filename(key.replace(':', '_'))}.jsonl"
assert sm._get_legacy_lossy_path(key) == expected
def test_storage_paths_are_distinct_when_keys_collide_under_safe_key(
tmp_path: Path,
monkeypatch,
) -> None:
sm = _manager(tmp_path, monkeypatch)
first = Session(key="telegram:a_b")
first.add_message("user", "underscore history")
second = Session(key="telegram:a:b")
second.add_message("user", "colon history")
sm.save(first)
sm.save(second)
assert sm.safe_key(first.key) == sm.safe_key(second.key)
assert sm._get_session_path(first.key).exists()
assert sm._get_session_path(second.key).exists()
assert sm._get_session_path(first.key) != sm._get_session_path(second.key)
sm.invalidate(first.key)
sm.invalidate(second.key)
loaded_first = sm._load(first.key)
loaded_second = sm._load(second.key)
assert loaded_first is not None
assert loaded_second is not None
assert loaded_first.messages[0]["content"] == "underscore history"
assert loaded_second.messages[0]["content"] == "colon history"
def test_colliding_display_names_roundtrip_independently(tmp_path):
manager = SessionManager(tmp_path)
keys = ("telegram:a_b", "telegram:a:b", "telegram:a/b", "telegram:你好")
for key in keys:
session = Session(key=key)
session.add_message("user", key)
manager.save(session)
assert manager.safe_key(keys[0]) == manager.safe_key(keys[1])
assert len(manager.list_sessions()) == len(keys)
for key in keys:
assert manager.read_session_file(key)["messages"][0]["content"] == key
manager.delete_session(keys[0])
assert manager.read_session_snapshot(keys[1]) is not None
+4 -92
View File
@@ -16,14 +16,13 @@ def _seed(workspace: Path, key: str = "telegram:abc") -> SessionManager:
def test_delete_session_removes_file_and_invalidates_cache(tmp_path: Path) -> None:
sm = _seed(tmp_path, "telegram:abc")
file_path = sm._get_session_path("telegram:abc")
assert file_path.exists()
assert sm.read_session_snapshot("telegram:abc") is not None
# Populate cache as a real consumer would.
cached = sm.get_or_create("telegram:abc")
assert cached.messages
assert sm.delete_session("telegram:abc") is True
assert not file_path.exists()
assert sm.read_session_snapshot("telegram:abc") is None
# Subsequent get_or_create returns a fresh, empty Session (no stale cache).
fresh = sm.get_or_create("telegram:abc")
assert fresh.messages == []
@@ -59,98 +58,11 @@ def test_read_session_file_returns_metadata_and_messages(tmp_path: Path) -> None
def test_read_session_file_does_not_populate_cache(tmp_path: Path) -> None:
sm = _seed(tmp_path, "telegram:abc")
sm.invalidate("telegram:abc")
assert "telegram:abc" not in sm._cache
assert sm.get_cached("telegram:abc") is None
sm.read_session_file("telegram:abc")
assert "telegram:abc" not in sm._cache
assert sm.get_cached("telegram:abc") is None
def test_read_session_file_missing(tmp_path: Path) -> None:
sm = SessionManager(tmp_path)
assert sm.read_session_file("nope:none") is None
def test_storage_key_matches_internal_path(tmp_path: Path) -> None:
sm = SessionManager(tmp_path)
key = "telegram:abc/def"
expected = sm._get_session_path(key).name
assert SessionManager._storage_key(key) + ".jsonl" == expected
def _write_legacy_session(legacy_dir: Path, key: str, roles: list[str]) -> Path:
legacy_dir.mkdir(parents=True, exist_ok=True)
safe = SessionManager.safe_key(key)
path = legacy_dir / f"{safe}.jsonl"
metadata_line = (
'{"_type":"metadata","key":"' + key + '",'
'"created_at":"2025-01-01T00:00:00",'
'"updated_at":"2025-01-01T00:00:00",'
'"metadata":{}}'
)
lines = [metadata_line]
for role in roles:
lines.append('{"role":"' + role + '","content":"msg"}')
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
return path
def test_delete_session_cleans_legacy_file(tmp_path: Path, monkeypatch) -> None:
"""A session that only exists at the legacy location must also be deleted."""
legacy = tmp_path / "legacy_sessions"
monkeypatch.setattr(
"nanobot.session.manager.get_legacy_sessions_dir",
lambda: legacy,
)
key = "telegram:only-legacy"
legacy_path = _write_legacy_session(legacy, key, ["user", "assistant"])
assert legacy_path.exists()
sm = SessionManager(tmp_path / "workspace")
new_path = sm._get_session_path(key)
assert not new_path.exists()
assert sm.delete_session(key) is True
assert not legacy_path.exists(), "legacy session file should have been removed"
def test_delete_session_cleans_both_locations(tmp_path: Path, monkeypatch) -> None:
"""When files exist at both the new and legacy paths, both must be removed."""
legacy = tmp_path / "legacy_sessions"
monkeypatch.setattr(
"nanobot.session.manager.get_legacy_sessions_dir",
lambda: legacy,
)
workspace = tmp_path / "workspace"
key = "telegram:both-paths"
_write_legacy_session(legacy, key, ["user", "assistant"])
sm = SessionManager(workspace)
session = Session(key=key)
session.add_message("user", "recent")
sm.save(session)
assert sm._get_session_path(key).exists()
assert (legacy / f"{SessionManager.safe_key(key)}.jsonl").exists()
assert sm.delete_session(key) is True
assert not sm._get_session_path(key).exists()
assert not (legacy / f"{SessionManager.safe_key(key)}.jsonl").exists()
def test_delete_session_prevents_legacy_revival(tmp_path: Path, monkeypatch) -> None:
"""After delete_session, a subsequent get_or_create must not resurrect history."""
legacy = tmp_path / "legacy_sessions"
monkeypatch.setattr(
"nanobot.session.manager.get_legacy_sessions_dir",
lambda: legacy,
)
workspace = tmp_path / "workspace"
key = "telegram:no-revival"
_write_legacy_session(legacy, key, ["user", "assistant"])
sm = SessionManager(workspace)
assert sm.delete_session(key) is True
assert not (legacy / f"{SessionManager.safe_key(key)}.jsonl").exists()
fresh = sm.get_or_create(key)
assert fresh.messages == []
+109 -20
View File
@@ -1,6 +1,7 @@
"""Independent turns and internal controls retain their session inbox semantics."""
import asyncio
import threading
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -23,7 +24,6 @@ from nanobot.session.recovery import (
PENDING_FOLLOWUPS_KEY,
REQUEST_ORIGIN_METADATA_KEY,
pending_followups,
record_pending_followup,
)
from nanobot.triggers.local_session_turns import LOCAL_TRIGGER_META
from nanobot.webui.recovery import RecoveryCoordinator
@@ -46,6 +46,95 @@ async def loop(tmp_path):
await agent.aclose()
@pytest.mark.parametrize("rejection", ["stop", "followup", "replaced-followup", "idle"])
async def test_rejected_input_does_not_stop_other_sessions(loop, monkeypatch, rejection):
state = loop.sessions.state
session = await state.get("websocket:busy")
model_started, release_model = asyncio.Event(), asyncio.Event()
readers_started, release_readers = threading.Event(), threading.Event()
idle_checked = asyncio.Event()
active_turn = rejection in {"followup", "replaced-followup"}
readers = []
async def chat(**kwargs):
if active_turn and not model_started.is_set():
model_started.set()
await release_model.wait()
return LLMResponse(content="still responsive")
async def reply(chat_id):
async with asyncio.timeout(5):
while True:
message = await loop.bus.consume_outbound()
if message.chat_id == chat_id and message.event is None:
return message
original_list = loop.sessions._store.list_metadata
def blocked_list():
readers_started.set()
assert release_readers.wait(5)
return original_list()
loop.provider.chat_stream_with_retry = chat
if rejection == "idle":
original_check = loop.auto_compact.check_expired
async def observed_check(*args, **kwargs):
try:
await original_check(*args, **kwargs)
finally:
idle_checked.set()
monkeypatch.setattr(loop.auto_compact, "check_expired", observed_check)
loop._next_idle_compact_check_at = 0
run_task = asyncio.create_task(loop.run())
try:
if active_turn:
await loop.bus.publish_inbound(InboundMessage(
channel="websocket", sender_id="u", chat_id="busy", content="first",
metadata={"webui": True}, session_generation=session.generation,
))
await asyncio.wait_for(model_started.wait(), timeout=3)
if rejection == "replaced-followup":
await state.reset(session.key)
else:
monkeypatch.setattr(loop.sessions._store, "list_metadata", blocked_list)
readers = [asyncio.create_task(state.list_metadata()) for _ in range(64)]
assert await asyncio.to_thread(readers_started.wait, 2)
if rejection == "idle":
await asyncio.wait_for(idle_checked.wait(), timeout=3)
else:
rejected = InboundMessage(
channel="telegram" if rejection == "stop" else "websocket",
sender_id="u", chat_id="busy",
content="/stop" if rejection == "stop" else "rejected follow-up",
metadata={"webui": True}, session_generation=session.generation,
)
await loop.bus.publish_inbound(rejected)
assert (await reply("busy")).content == "Sorry, I encountered an error."
assert not run_task.done()
release_readers.set()
await asyncio.gather(*readers)
await loop.bus.publish_inbound(InboundMessage(
channel="telegram", sender_id="u", chat_id="other", content="hello",
))
assert (await reply("other")).content == "still responsive"
if active_turn:
assert not release_model.is_set()
assert loop._pending_queues[session.key].empty()
saved = await state.read(session.key)
assert pending_followups(saved) == []
finally:
release_readers.set()
await asyncio.gather(*readers, return_exceptions=True)
loop.stop()
run_task.cancel()
await asyncio.gather(run_task, return_exceptions=True)
def _automation_message(kind: str, name: str) -> InboundMessage:
metadata = (
{
@@ -83,9 +172,6 @@ async def test_automation_turn_is_deferred_while_session_active(loop, kind):
async with asyncio.timeout(3):
while not coordinator.deferred_queues.get(key):
await asyncio.sleep(0)
loop.stop()
await asyncio.wait_for(run_task, timeout=3)
assert pending.empty()
assert loop._active_tasks == {}
assert coordinator.deferred_queues[key] == [msg]
@@ -106,7 +192,7 @@ async def test_automation_turn_is_deferred_while_session_active(loop, kind):
@pytest.mark.parametrize("kind", ["cron", "local_trigger"])
async def test_submitted_automation_reports_pending_until_completed(loop, kind):
coordinator = loop._cron_turns if kind == "cron" else loop._local_trigger_turns
coordinator._enqueue = MagicMock()
coordinator._enqueue = AsyncMock()
submit = loop.submit_cron_turn if kind == "cron" else loop.submit_local_trigger_turn
pending_ids = (
loop.pending_cron_job_ids_for_session
@@ -256,15 +342,15 @@ async def test_stopped_followups_are_not_recovered_but_shutdown_preserves_them(
loop.provider.chat_stream_with_retry = chat
key = "websocket:test"
loop._enqueue_session_message(InboundMessage(
(await loop._enqueue_session_message(InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content="first",
metadata={"webui": True},
))
)))
await asyncio.wait_for(started.wait(), timeout=3)
loop._enqueue_session_message(InboundMessage(
(await loop._enqueue_session_message(InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content="cancel me",
metadata={"webui": True},
))
)))
if not followup_still_queued:
consumed = loop._pending_queues[key].get_nowait()
@@ -300,16 +386,15 @@ async def test_stopped_followups_are_not_recovered_but_shutdown_preserves_them(
async def test_cancel_preserves_followups_accepted_after_cancellation_started(loop):
key = "websocket:test"
session = loop.sessions.get_or_create(key)
session = await loop.sessions.state.get(key)
def journal(content):
record_pending_followup(session, InboundMessage(
async def journal(content):
await loop.sessions.state.queue_followup(key, InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content=content,
metadata={"webui": True},
metadata={"webui": True}, session_generation=session.generation,
))
loop.sessions.save(session)
journal("old followup")
await journal("old followup")
started = asyncio.Event()
cancelling = asyncio.Event()
release = asyncio.Event()
@@ -328,7 +413,7 @@ async def test_cancel_preserves_followups_accepted_after_cancellation_started(lo
stop = asyncio.create_task(loop._cancel_active_tasks(key))
try:
await asyncio.wait_for(cancelling.wait(), timeout=3)
journal("new followup")
await journal("new followup")
finally:
release.set()
await stop
@@ -422,7 +507,7 @@ async def test_ingress_sources_share_one_session_worker(loop, bus_running):
if bus_running:
await loop.bus.publish_inbound(first)
else:
loop._enqueue_session_message(first)
(await loop._enqueue_session_message(first))
await asyncio.wait_for(started.wait(), timeout=3)
cron = asyncio.create_task(loop.submit_cron_turn(_automation_message("cron", "cron")))
trigger = asyncio.create_task(loop.submit_local_trigger_turn(
@@ -437,7 +522,7 @@ async def test_ingress_sources_share_one_session_worker(loop, bus_running):
while loop._pending_queues[key].empty():
await asyncio.sleep(0)
else:
loop._enqueue_session_message(second)
(await loop._enqueue_session_message(second))
compact = InboundMessage(channel="websocket", sender_id="u", chat_id="test", content="/compact")
await loop._dispatch_command_inline(compact, key, compact.content, loop.commands.dispatch)
assert len(loop._active_tasks[key]) == 1
@@ -528,7 +613,9 @@ async def test_goal_continuation_after_followup_keeps_control_identity(loop, com
while loop._pending_queues["cli:test"].empty():
await asyncio.sleep(0)
elif complete_on_followup or len(requests) == 3:
session.metadata[GOAL_STATE_KEY]["status"] = "complete"
await loop.sessions.state.update_metadata(session.key, {
GOAL_STATE_KEY: {"status": "complete", "objective": "Finish the long goal"},
})
return LLMResponse(content="done")
return LLMResponse(
content="working", finish_reason="tool_calls",
@@ -587,7 +674,9 @@ async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loop
persisted = SessionManager(loop.workspace).get_or_create(key)
persisted_origin = persisted.metadata[REQUEST_ORIGIN_METADATA_KEY]
await loop.tools.get("message").execute(content="Continuation reply")
session.metadata[GOAL_STATE_KEY]["status"] = "complete"
await loop.sessions.state.mutate_metadata(
key, lambda metadata: metadata[GOAL_STATE_KEY].update(status="complete"),
)
return LLMResponse(content="done")
return LLMResponse(content="working", finish_reason="tool_calls", tool_calls=[
ToolCallRequest(id=f"call-{len(requests)}", name="noop", arguments={}),
+1 -1
View File
@@ -38,7 +38,7 @@ def _tool_turn(prefix: str, idx: int) -> list[dict]:
]
def test_list_sessions_includes_metadata_title(tmp_path):
def test_list_sessions_includesmetadata_title(tmp_path):
manager = SessionManager(tmp_path)
session = manager.get_or_create("websocket:chat-title")
session.metadata["title"] = "自动生成标题"
+31 -5
View File
@@ -4,6 +4,7 @@ import pytest
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import RuntimeModelChanged
from nanobot.config.schema import ModelPresetConfig
from nanobot.nanobot import Nanobot
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse
@@ -69,8 +70,8 @@ async def test_sessions_run_concurrently_with_isolated_model_presets(tmp_path) -
preset_snapshot_loader=load_preset,
)
loop.schedule_background = lambda coro: coro.close() # type: ignore[method-assign]
loop.set_session_model_preset("sdk:fast", "fast")
loop.set_session_model_preset("sdk:deep", "deep")
(await loop.set_session_model_preset("sdk:fast", "fast"))
(await loop.set_session_model_preset("sdk:deep", "deep"))
fast_reply, deep_reply = await asyncio.gather(
loop.process_direct("hello", session_key="sdk:fast"),
@@ -135,6 +136,31 @@ async def test_removed_session_model_preset_falls_back_and_clears_metadata(tmp_p
assert model_preset_from_metadata(restored.metadata) is None
async def test_async_runtime_resolution_publishes_model_refresh_on_event_loop(
tmp_path,
monkeypatch,
) -> None:
provider = RecordingProvider("base-model")
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="base-model")
session = loop.sessions.get_or_create("sdk:runtime-refresh")
refreshed = LLMRuntime.capture(provider, "updated-model", context_window_tokens=16_000)
monkeypatch.setattr(loop.runtime_resolver, "admit", lambda: refreshed)
published = asyncio.Event()
events: list[RuntimeModelChanged] = []
def on_changed(event: RuntimeModelChanged) -> None:
events.append(event)
published.set()
unsubscribe = loop.bus.subscribe(on_changed, RuntimeModelChanged)
try:
assert await loop.runtime_for_session(session) is refreshed
await asyncio.wait_for(published.wait(), timeout=1)
finally:
unsubscribe()
assert events[0].model == "updated-model"
@pytest.mark.asyncio
async def test_streamed_sdk_resolves_session_runtime_after_lock_admission(tmp_path) -> None:
base = RecordingProvider("base-model")
@@ -166,13 +192,13 @@ async def test_streamed_sdk_resolves_session_runtime_after_lock_admission(tmp_pa
)
loop.schedule_background = lambda coro: coro.close() # type: ignore[method-assign]
session_key = "sdk:queued"
loop.set_session_model_preset(session_key, "fast")
(await loop.set_session_model_preset(session_key, "fast"))
lock = loop._session_locks.setdefault(session_key, asyncio.Lock())
await lock.acquire()
try:
run = await Nanobot(loop).run_streamed("hello", session_key=session_key)
loop.set_session_model_preset(session_key, "deep")
(await loop.set_session_model_preset(session_key, "deep"))
finally:
lock.release()
@@ -210,7 +236,7 @@ async def test_sdk_custom_model_preset_metadata_does_not_select_runtime(
metadata={"model_preset": custom_value},
)
ingested_result = await bot.run("hello", session_key="sdk:custom-metadata")
exported = bot.sessions.export("sdk:custom-metadata")
exported = (await bot.sessions.export("sdk:custom-metadata"))
restored = await bot.sessions.restore(
SessionSnapshot(
key="sdk:restored-metadata",
+4 -4
View File
@@ -16,7 +16,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from agent.session_helpers import run_session
from agent.session_helpers import mock_session_manager, run_session
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
from nanobot.session.recovery import RUNTIME_CHECKPOINT_KEY
@@ -37,7 +37,7 @@ def _make_loop(tmp_path: Path) -> AgentLoop:
bus = MessageBus()
provider = _make_provider()
with patch("nanobot.agent.loop.ContextBuilder"), \
patch("nanobot.agent.loop.SessionManager"), \
patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
patch("nanobot.agent.loop.SubagentManager") as mock_subagent_manager:
mock_subagent_manager.return_value.cancel_by_session = AsyncMock(return_value=0)
return AgentLoop(bus=bus, provider=provider, workspace=tmp_path)
@@ -60,7 +60,7 @@ async def test_dispatch_cancellation_restores_checkpoint():
workspace.__truediv__ = MagicMock(return_value=MagicMock())
with patch("nanobot.agent.loop.ContextBuilder"), \
patch("nanobot.agent.loop.SessionManager"), \
patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
patch("nanobot.agent.loop.SubagentManager") as mock_subagent_manager:
mock_subagent_manager.return_value.cancel_by_session = AsyncMock(return_value=0)
loop = AgentLoop(bus=bus, provider=provider, workspace=workspace)
@@ -112,7 +112,7 @@ async def test_dispatch_cancellation_restores_checkpoint():
)
assert checkpoint_key not in session.metadata, \
"Checkpoint metadata should be cleared after restore"
assert loop.sessions.save.called, \
assert loop.sessions.state.restore_interruption.await_count == 1, \
"Session should be persisted so the restored state survives process restart"
+15 -8
View File
@@ -28,7 +28,7 @@ from nanobot.bus.runtime_events import TurnRunStatusChanged
from nanobot.config import Config
from nanobot.nanobot import Nanobot
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
from nanobot.session.manager import SessionManager
from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, SessionManager
from nanobot.session.webui_turns import WebuiTurnRoutePolicy
from nanobot.utils.llm_runtime import LLMRuntime
@@ -101,7 +101,7 @@ async def test_sdk_ephemeral_delegation_never_persists_on_later_flush(
if existing_parent:
parent.add_message("user", "Earlier durable question")
loop.sessions.save(parent)
before = {path.name: path.read_bytes() for path in loop.sessions.sessions_dir.glob("*.jsonl")}
before = loop.sessions.read_session_file(key)
secret = "private-delegation-marker"
source = loop.workspace / f"{secret}.txt"
source.write_text(secret * 1000, encoding="utf-8")
@@ -138,19 +138,18 @@ async def test_sdk_ephemeral_delegation_never_persists_on_later_flush(
assert result.content == f"Parent conclusion: {secret}"
assert all(ctx is not None and not ctx.log_content and not ctx.persist_session for ctx in requests)
assert secret not in "\n".join(logs)
assert {path.name: path.read_bytes() for path in loop.sessions.sessions_dir.glob("*.jsonl")} == before
assert loop.sessions.read_session_file(key) == before
assert not list(loop.sessions.sessions_dir.glob("*.checkpoint.json"))
assert not (loop.workspace / ".nanobot" / "tool-results").exists()
assert loop.bus.inbound_size == 0
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Durable answer"))
await bot.run("Durable follow-up", session_key=key)
bot.sessions.flush()
saved = "\n".join(path.read_text() for path in loop.sessions.sessions_dir.glob("*.jsonl"))
saved = json.dumps(loop.sessions.read_session_file(key))
assert "Durable answer" in saved
assert ("Earlier durable question" in saved) is existing_parent
assert secret not in saved
assert len(list(loop.sessions.sessions_dir.glob("*.jsonl"))) == 1
assert [row["key"] for row in loop.sessions.list_sessions()] == [key]
finally:
loop.stop()
await asyncio.wait_for(consumer, timeout=2)
@@ -181,7 +180,10 @@ async def test_child_origin_uses_the_channel_turn_identity(loop_factory):
@pytest.mark.asyncio
async def test_default_loop_keeps_slack_thread_for_late_subagent_result(tmp_path, monkeypatch):
@pytest.mark.parametrize("cache_invalidation", ["handles", "eviction"])
async def test_default_loop_keeps_slack_thread_for_late_subagent_result(
tmp_path, monkeypatch, cache_invalidation,
):
monkeypatch.setattr("nanobot.agent.loop._SUBAGENT_TERMINAL_WAIT_SECONDS", 0.01)
child_started, release_child, parent_idle = (asyncio.Event() for _ in range(3))
@@ -245,6 +247,11 @@ async def test_default_loop_keeps_slack_thread_for_late_subagent_result(tmp_path
saved = SessionManager(workspace, sessions_root=sessions_root).get_existing(session_key)
assert saved is not None
saved_route = saved.metadata["_compaction_route"]
if cache_invalidation == "handles":
await sessions.state.ensure_session_handles()
else:
for i in range(SESSION_CACHE_MAX_SIZE + 1):
await sessions.state.get_header(f"telegram:other-{i}")
release_child.set()
late_reply = await next_reply("Late follow-up")
@@ -265,7 +272,7 @@ async def test_owner_canonical_fallback_and_absent_context(tmp_path):
manager, _, ctx = setup(tmp_path)
manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="private"))
task_id = await spawn(manager, ctx)
receipt = manager.send(task_id, "owner", "follow-up")
receipt = await manager.send(task_id, "owner", "follow-up")
snapshot = manager.statuses_for_session("owner")[task_id]
snapshot.state = "cancelled"
snapshot.owner = "other"
+3 -3
View File
@@ -8,7 +8,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from agent.session_helpers import run_session
from agent.session_helpers import mock_session_manager, run_session
from nanobot.agent.memory import Consolidator
from nanobot.bus.outbound_events import StreamDeltaEvent, StreamEndEvent
from nanobot.config.schema import AgentDefaults
@@ -37,7 +37,7 @@ def _make_loop(*, tools_config=None):
workspace.__truediv__ = MagicMock(return_value=MagicMock())
with patch("nanobot.agent.loop.ContextBuilder"), \
patch("nanobot.agent.loop.SessionManager"), \
patch("nanobot.agent.loop.SessionManager", side_effect=mock_session_manager), \
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr:
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
loop = AgentLoop(bus=bus, provider=provider, workspace=workspace, tools_config=tools_config)
@@ -340,7 +340,7 @@ class TestDispatch:
async def test_run_logs_and_continues_after_leaked_cancelled_error(self, monkeypatch):
loop, bus = _make_loop()
loop.aclose = AsyncMock()
loop.auto_compact.check_expired = MagicMock()
loop.auto_compact.check_expired = AsyncMock()
warnings: list[str] = []
calls = 0
+5 -2
View File
@@ -325,13 +325,14 @@ def test_websocket_lifecycle_reuses_registered_ingress_owner(tmp_path: Path) ->
wth.clear_websocket_turn_if_current("chat-queued", owner)
def test_internal_user_input_uses_the_persisted_webui_route(tmp_path: Path) -> None:
async def test_internal_user_input_uses_the_persisted_webui_route(tmp_path: Path) -> None:
from nanobot.session import webui_turns as wth
sessions = SessionManager(tmp_path / "sessions")
target = sessions.get_or_create("websocket:target")
target.metadata["webui"] = True
sessions.save(target)
await sessions.state.read(target.key)
factory = TurnDeliveryFactory(
MessageBus(),
route_policy=WebuiTurnRoutePolicy(sessions),
@@ -418,7 +419,7 @@ async def test_same_chat_different_sessions_restore_previous_active_projection(
wth._WEBSOCKET_TURN_OWNERS.pop("shared-chat", None)
def test_late_subagent_route_requires_webui_owned_session(tmp_path: Path) -> None:
async def test_late_subagent_route_requires_webui_owned_session(tmp_path: Path) -> None:
sessions = SessionManager(tmp_path)
factory = TurnDeliveryFactory(
MessageBus(),
@@ -446,6 +447,8 @@ def test_late_subagent_route_requires_webui_owned_session(tmp_path: Path) -> Non
session = sessions.get_or_create(session_key)
session.metadata["webui"] = True
sessions.save(session)
await sessions.state.read(session_key)
first_visible_route = factory.create(msg, session_key).route
second_visible_route = factory.create(msg, session_key).route
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff. Show more