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 os: windows-latest
python-version: "3.14" python-version: "3.14"
coverage: false coverage: false
# Real PowerShell/process-tree tests run serially in a separate # Real PowerShell, browser-handoff, and process-tree tests run
# job. Keep them out of xdist so workers never share a console. # serially so xdist workers do not compete for native processes.
pytest_args: "-n auto --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/tools/test_exec_platform.py" # 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: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
@@ -274,6 +275,7 @@ jobs:
run: >- run: >-
uv run --no-sync python -m pytest uv run --no-sync python -m pytest
tests/tools/test_exec_platform.py tests/tools/test_exec_platform.py
tests/cli/test_wsl_browser.py
--durations=25 --durations-min=1.0 --durations=25 --durations-min=1.0
webui: 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. 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)** **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 data_root = tmp_path.parent / "session-data" / uuid4().hex
runtime_root = data_root / "runtime" runtime_root = data_root / "runtime"
legacy_root = data_root / "legacy-sessions"
def runtime_subdir(name: str) -> Path: def runtime_subdir(name: str) -> Path:
path = runtime_root / name path = runtime_root / name
@@ -49,13 +48,9 @@ def _isolate_sessions_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> I
return path return path
monkeypatch.setattr( monkeypatch.setattr(
"nanobot.session.manager.get_runtime_subdir", "nanobot.session.location.get_runtime_subdir",
runtime_subdir, runtime_subdir,
) )
monkeypatch.setattr(
"nanobot.session.manager.get_legacy_sessions_dir",
lambda: legacy_root,
)
yield yield
@@ -136,3 +131,17 @@ def _use_windows_system_ca_for_default_http_clients() -> Iterator[None]:
yield yield
finally: finally:
ssl.create_default_context = original 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` | | Config | `~/.nanobot/config.json` |
| Workspace | `~/.nanobot/workspace/` | | 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/` | | Memory | `<workspace>/memory/` |
| Cron store | `<workspace>/cron/jobs.json` | | Cron store | `<workspace>/cron/jobs.json` |
| WebUI/media/log runtime data | config directory subdirectories such as `webui/`, `media/`, and `logs/` | | 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 | | 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` | | Long-term memory | `<workspace>/memory/MEMORY.md` |
| Consolidation source history | `<workspace>/memory/history.jsonl` | | Consolidation source history | `<workspace>/memory/history.jsonl` |
| Bootstrap identity files | `<workspace>/SOUL.md`, `<workspace>/USER.md`, templates under `nanobot/templates/` | | 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. 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 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.
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.
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. 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 | | 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 | | 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. 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 ### 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: **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 ## 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: 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" $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. 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 ## 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`** **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 ```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: Credential options:
@@ -643,7 +643,7 @@ Anthropic models on Bedrock can also require Anthropic use-case registration and
**4. Model IDs** **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: 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. 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** **6. Quick checks**
@@ -1724,9 +1724,7 @@ Telegram `richMessages` defaults to `false`. Enable it only to opt in to Bot API
### Retry Behavior ### Retry Behavior
Retry is intentionally simple. When message delivery fails, nanobot retries. `channels.sendMaxRetries` defaults to `3`, including the initial attempt.
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.
- **Attempt 1**: Send immediately - **Attempt 1**: Send immediately
- **Attempt 2**: Retry after `1s` - **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 - **Permanent failures**: Invalid tokens, revoked access, or banned channels will exhaust the retry budget and fail cleanly
> [!NOTE] > [!NOTE]
> This design is deliberate: channel implementations should raise on delivery failure, and the channel manager owns the shared retry policy. > 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.
>
> 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.
> >
> 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. > 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.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.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.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.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 (`--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.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.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. | | `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). | | `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. 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 | | 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 ### 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 ## Subagent Concurrency
@@ -2494,19 +2490,12 @@ When a session is idle for longer than a configured threshold, nanobot summarize
| Option | Default | Description | | 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). | | `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. `sessionTtlMinutes` remains accepted as a legacy alias for backward compatibility, but `idleCompactAfterMinutes` is the preferred config key going forward.
How it works: The compacted context remains available after restarting nanobot.
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.
Use `/compact` in chat to compact the current session without waiting for the idle threshold. 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` | | 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 | | Cross-channel continuity | No | Yes |
| `/new` clears | Current channel session | Shared session | | `/new` clears | Current channel session | Shared session |
| `/stop` finds tasks | By channel session | By 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 ## Disabled Skills
@@ -2604,13 +2593,13 @@ Disabled skills are excluded from the main agent's skill summary, from always-on
### Agent Plugins v1 ### 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. 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 ## Tool Hint Max Length
+11 -10
View File
@@ -559,14 +559,15 @@ async with Nanobot.from_config() as bot:
| Method | Description | | Method | Description |
|--------|-------------| |--------|-------------|
| `await ingest(session_key, messages, metadata=None, source=None, save=True)` | Import existing transcript messages without running the model. | | `await ingest(session_key, messages, metadata=None, source=None)` | Import existing transcript messages without running the model. |
| `get(session_key)` | Return a `SessionSnapshot`, or `None` if missing. | | `await get(session_key)` | Return a `SessionSnapshot`, or `None` if missing. |
| `list()` | Return compact `SessionInfo` rows. | | `await list()` | Return compact `SessionInfo` rows. |
| `export(session_key)` | Return a trusted full `SessionSnapshot`, including model-only runtime context, suitable for JSON serialization. | | `await 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. | | `await restore(snapshot, session_key=None)` | Restore a trusted exported snapshot into an empty session; the returned snapshot is display-safe. |
| `clear(session_key)` | Clear and persist one session. | | `await clear(session_key)` | Clear and persist one session. |
| `delete(session_key)` | Delete one session from disk and cache. | | `await delete(session_key)` | Delete one session from disk and cache. |
| `flush()` | Flush cached sessions to durable storage. |
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. 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. 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 ```python
import json import json
@@ -639,7 +640,7 @@ async def run_with_external_memory(external_memory, enqueue_retry) -> None:
return external_context_block(text) return external_context_block(text)
async def sync_saved_turn(event: SessionTurnPersisted): 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: if snapshot is not None:
try: try:
await external_memory.sync( await external_memory.sync(
+33 -34
View File
@@ -3,7 +3,7 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
from collections.abc import Collection from collections.abc import Awaitable, Collection
from datetime import datetime from datetime import datetime
from typing import TYPE_CHECKING, Any, Callable, Coroutine 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.manager import Session, SessionManager
from nanobot.session.summary import ( from nanobot.session.summary import (
SessionSummary, SessionSummary,
is_summary_checkpoint,
session_summary_from_metadata, session_summary_from_metadata,
) )
@@ -26,10 +25,15 @@ SessionEventFactory = Callable[[str], EventSink]
class AutoCompact: class AutoCompact:
def __init__(self, sessions: SessionManager, consolidator: Consolidator, def __init__(
session_ttl_minutes: int = 0, self,
bind_events: SessionEventFactory | None = None, sessions: SessionManager,
*, session_lock: Callable[[str], asyncio.Lock]): consolidator: Consolidator,
session_ttl_minutes: int = 0,
bind_events: SessionEventFactory | None = None,
*,
session_lock: Callable[[str], asyncio.Lock],
):
self.sessions = sessions self.sessions = sessions
self.consolidator = consolidator self.consolidator = consolidator
self._ttl = session_ttl_minutes self._ttl = session_ttl_minutes
@@ -56,38 +60,30 @@ class AutoCompact:
return False return False
return idle_seconds >= self._ttl * 60 return idle_seconds >= self._ttl * 60
def _has_unarchived_messages(self, key: str) -> bool: async def check_expired(
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(
self, self,
schedule_background: Callable[[Coroutine[Any, Any, None]], None], schedule_background: Callable[[Coroutine[Any, Any, None]], None],
resolve_runtime: Callable[[Session], LLMRuntime], resolve_runtime: Callable[[Session], Awaitable[LLMRuntime]],
active_session_keys: Collection[str] = (), active_session_keys: Collection[str] = (),
) -> None: ) -> None:
"""Schedule archival for idle sessions, skipping those with in-flight agent tasks.""" """Schedule idle archival without blocking the event loop."""
now = datetime.now() 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", "") 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: if not key or is_dream_session(key) or key in self._archiving:
continue continue
if key in active_session_keys: if key in active_keys or not self._is_expired(info.get("updated_at"), now):
continue continue
updated_at = info.get("updated_at") if not await self.sessions.state.has_unarchived_messages(key):
if self._is_expired(updated_at, now) and self._has_unarchived_messages(key): continue
session = self.sessions.get_or_create(key) session = await self.sessions.state.get(key)
try: try:
runtime = resolve_runtime(session) runtime = await resolve_runtime(session)
except (KeyError, ValueError): except (KeyError, ValueError):
# Invalid session selections remain recoverable through /model. continue
continue self._archiving.add(key)
self._archiving.add(key) schedule_background(self._archive(key, runtime=runtime))
schedule_background(self._archive(key, runtime=runtime))
async def _archive(self, key: str, *, runtime: LLMRuntime) -> None: async def _archive(self, key: str, *, runtime: LLMRuntime) -> None:
if is_dream_session(key): if is_dream_session(key):
@@ -95,13 +91,14 @@ class AutoCompact:
return return
try: try:
async with self._session_lock(key): async with self._session_lock(key):
# Idle compaction and turns share one transcript boundary.
summary = await self.consolidator.compact_idle_session( summary = await self.consolidator.compact_idle_session(
key, key,
runtime=runtime, runtime=runtime,
events=self._bind_events(key) if self._bind_events else NO_EVENTS, events=self._bind_events(key) if self._bind_events else NO_EVENTS,
) )
if summary: if summary:
session = self.sessions.get_or_create(key) session = await self.sessions.state.get(key)
stored = session_summary_from_metadata( stored = session_summary_from_metadata(
session.metadata, session.metadata,
fallback_last_active=session.updated_at, fallback_last_active=session.updated_at,
@@ -113,14 +110,16 @@ class AutoCompact:
finally: finally:
self._archiving.discard(key) 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): if is_dream_session(key):
self._archiving.discard(key) self._archiving.discard(key)
self._summaries.pop(key, None) self._summaries.pop(key, None)
return session, 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). # Hot path: summary from in-memory dict (process hasn't restarted).
entry = self._summaries.pop(key, None) entry = self._summaries.pop(key, None)
if entry: if entry:
+3 -3
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import asyncio import asyncio
import dataclasses import dataclasses
from collections.abc import Callable, Iterable from collections.abc import Awaitable, Callable, Iterable
from nanobot.bus.events import InboundMessage, OutboundMessage from nanobot.bus.events import InboundMessage, OutboundMessage
@@ -19,7 +19,7 @@ class AutomationTurnCoordinator:
def __init__( def __init__(
self, self,
*, *,
enqueue: Callable[[InboundMessage], None], enqueue: Callable[[InboundMessage], Awaitable[None]],
turn_id: Callable[[InboundMessage], str | None], turn_id: Callable[[InboundMessage], str | None],
pending_id: Callable[[InboundMessage], str | None], pending_id: Callable[[InboundMessage], str | None],
should_defer_turn: Callable[[InboundMessage, str, Iterable[str]], bool], should_defer_turn: Callable[[InboundMessage, str, Iterable[str]], bool],
@@ -54,7 +54,7 @@ class AutomationTurnCoordinator:
self._waiters[turn_id] = future self._waiters[turn_id] = future
self._pending_messages_by_turn_id[turn_id] = msg self._pending_messages_by_turn_id[turn_id] = msg
try: try:
self._enqueue(msg) await self._enqueue(msg)
try: try:
return await future return await future
except asyncio.CancelledError: except asyncio.CancelledError:
-12
View File
@@ -71,7 +71,6 @@ BACKFILL_CONTENT = "[Tool result unavailable — call was interrupted or lost]"
PLACEHOLDER_TEXTS = frozenset({ PLACEHOLDER_TEXTS = frozenset({
"[Previous assistant message omitted.]", "[Previous assistant message omitted.]",
}) })
_PreparationArgs = ParamSpec("_PreparationArgs") _PreparationArgs = ParamSpec("_PreparationArgs")
_PreparationResult = TypeVar("_PreparationResult") _PreparationResult = TypeVar("_PreparationResult")
@@ -234,17 +233,6 @@ class ContextCompactionState:
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
return deepcopy(request_messages[len(self.accepted_messages):]) 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) @dataclass(slots=True)
class ModelRequestState: class ModelRequestState:
"""Context state shared by every provider request in one runner turn.""" """Context state shared by every provider request in one runner turn."""
+2 -2
View File
@@ -2,7 +2,7 @@
from __future__ import annotations 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.agent.automation_turns import AutomationTurnCoordinator
from nanobot.bus.events import InboundMessage from nanobot.bus.events import InboundMessage
@@ -19,7 +19,7 @@ class CronTurnCoordinator(AutomationTurnCoordinator):
def __init__( def __init__(
self, self,
*, *,
enqueue: Callable[[InboundMessage], None], enqueue: Callable[[InboundMessage], Awaitable[None]],
deferred_queues: dict[str, list[InboundMessage]] | None = None, deferred_queues: dict[str, list[InboundMessage]] | None = None,
) -> None: ) -> None:
super().__init__( super().__init__(
+210 -137
View File
@@ -97,11 +97,12 @@ from nanobot.session.recovery import (
RequestOrigin, RequestOrigin,
acknowledge_pending_followups, acknowledge_pending_followups,
pending_followups, pending_followups,
record_pending_followup,
request_origin_from_metadata, request_origin_from_metadata,
restore_pending_interruption, restore_pending_interruption,
restore_runtime_checkpoint, restore_runtime_checkpoint,
) )
from nanobot.session.sqlite_store import SessionConflictError
from nanobot.session.state import SessionOperationQueueFullError
from nanobot.session.summary import ( from nanobot.session.summary import (
SessionSummary, SessionSummary,
SessionSummaryCheckpoint, SessionSummaryCheckpoint,
@@ -181,6 +182,8 @@ class TurnContext:
provider_compaction_applied: bool = False provider_compaction_applied: bool = False
ephemeral: 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 run_extra_hooks_for_ephemeral: bool = False
hooks: list[AgentHook] = field(default_factory=list) hooks: list[AgentHook] = field(default_factory=list)
hook_factories: list[AgentTurnHookFactory] = field(default_factory=list) hook_factories: list[AgentTurnHookFactory] = field(default_factory=list)
@@ -543,13 +546,13 @@ class AgentLoop:
self._publish_runtime_selection(runtime) self._publish_runtime_selection(runtime)
return runtime return runtime
def runtime_for_session( def _resolve_session_runtime(
self, self,
session: Session, session: Session,
*, *,
recover_removed: bool = True, recover_removed: bool,
) -> LLMRuntime: ) -> LLMRuntime | None:
"""Resolve the immutable runtime selected by one session.""" """Return the selected runtime, or clear a removed preset for persistence."""
name = model_preset_from_metadata(session.metadata) name = model_preset_from_metadata(session.metadata)
if name is None: if name is None:
return self.llm_runtime() return self.llm_runtime()
@@ -564,19 +567,38 @@ class AgentLoop:
name, name,
) )
session.metadata.pop(SESSION_MODEL_PRESET_METADATA_KEY, None) session.metadata.pop(SESSION_MODEL_PRESET_METADATA_KEY, None)
self.sessions.save(session) return None
return self.llm_runtime()
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, self,
session_key: str, session_key: str,
name: str, name: str,
) -> LLMRuntime: ) -> 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) runtime = self.runtime_resolver.resolve_preset(name)
session = self.sessions.get_or_create(session_key) await self.sessions.state.update_metadata(
session.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = runtime.model_preset session_key,
self.sessions.save(session) {SESSION_MODEL_PRESET_METADATA_KEY: runtime.model_preset},
create_if_missing=True,
)
return runtime return runtime
def _publish_runtime_selection( def _publish_runtime_selection(
@@ -675,17 +697,14 @@ class AgentLoop:
def pending_local_trigger_ids_for_session(self, session_key: str) -> set[str]: 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) return self._local_trigger_turns.pending_trigger_ids_for_session(session_key)
def _persist_user_message_early( async def _persist_user_message_early(
self, self,
msg: InboundMessage, msg: InboundMessage,
session: Session, session: Session,
runtime_context_blocks: list[RuntimeContextBlock] | None = None, runtime_context_blocks: list[RuntimeContextBlock] | None = None,
**kwargs: Any, **kwargs: Any,
) -> bool: ) -> bool:
"""Persist the triggering user message before the turn starts. """Persist the triggering user message and recovery markers before running the turn."""
Returns True if the message was persisted.
"""
if not turn_continuation.should_persist_user_message(msg.metadata): if not turn_continuation.should_persist_user_message(msg.metadata):
return False return False
media_paths = [ media_paths = [
@@ -716,7 +735,7 @@ class AgentLoop:
followup_id = msg.metadata.get(PENDING_FOLLOWUP_ID_KEY) followup_id = msg.metadata.get(PENDING_FOLLOWUP_ID_KEY)
if isinstance(followup_id, str) and followup_id: if isinstance(followup_id, str) and followup_id:
acknowledge_pending_followups(session, [followup_id]) acknowledge_pending_followups(session, [followup_id])
self.sessions.save(session) await self.sessions.state.prepare_input(session)
return True return True
return False return False
@@ -743,7 +762,11 @@ class AgentLoop:
ctx.session.metadata[REQUEST_ORIGIN_METADATA_KEY] = origin ctx.session.metadata[REQUEST_ORIGIN_METADATA_KEY] = origin
if ctx.original_user_text is None: if ctx.original_user_text is None:
# No new user row will persist this turn's owner before execution. # 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( scope = await self.runner.prepare_prompt(
self.workspace_scopes.for_turn, self.workspace_scopes.for_turn,
channel=ctx.delivery.route.channel, channel=ctx.delivery.route.channel,
@@ -755,6 +778,7 @@ class AgentLoop:
chat_id=ctx.delivery.route.chat_id, chat_id=ctx.delivery.route.chat_id,
message_id=origin["message_id"], message_id=origin["message_id"],
session_key=ctx.session_key, session_key=ctx.session_key,
session_generation=ctx.session.generation,
original_user_text=ctx.original_user_text, original_user_text=ctx.original_user_text,
runtime=ctx.runtime, runtime=ctx.runtime,
metadata=dict(ctx.msg.metadata or {}), metadata=dict(ctx.msg.metadata or {}),
@@ -789,9 +813,10 @@ class AgentLoop:
] ]
blocks = runtime_context_blocks_from_metadata(request.metadata) blocks = runtime_context_blocks_from_metadata(request.metadata)
blocks.extend(await resolve_runtime_context(providers, request)) blocks.extend(await resolve_runtime_context(providers, request))
skill_context = await self.runner.prepare_prompt( text = request.original_user_text or ""
self.context.skills.build_explicit_skill_runtime_context, skill_context = (
request.original_user_text or "", 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: if skill_context is not None and skill_context not in blocks:
blocks.append(skill_context) blocks.append(skill_context)
@@ -806,7 +831,7 @@ class AgentLoop:
) -> None: ) -> None:
"""Dispatch a command directly from the run() loop and publish the result.""" """Dispatch a command directly from the run() loop and publish the result."""
if self.commands.requires_session_queue(raw): if self.commands.requires_session_queue(raw):
self._enqueue_session_message(msg) await self._enqueue_session_message(msg)
return return
async def dispatch_and_publish() -> None: async def dispatch_and_publish() -> None:
@@ -821,7 +846,7 @@ class AgentLoop:
) )
result = await dispatch_fn(ctx) result = await dispatch_fn(ctx)
if isinstance(result, InboundMessage): if isinstance(result, InboundMessage):
self._enqueue_session_message(result) await self._enqueue_session_message(result)
elif result is not None: elif result is not None:
await self.bus.publish_outbound(result) await self.bus.publish_outbound(result)
@@ -839,7 +864,7 @@ class AgentLoop:
if tool is None: if tool is None:
content = "Shell execution is disabled in this nanobot configuration." content = "Shell execution is disabled in this nanobot configuration."
else: 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( scope = self.workspace_scopes.for_turn(
channel=ctx.msg.channel, channel=ctx.msg.channel,
message_metadata=metadata, message_metadata=metadata,
@@ -850,6 +875,7 @@ class AgentLoop:
chat_id=ctx.msg.chat_id, chat_id=ctx.msg.chat_id,
message_id=metadata.get("message_id"), message_id=metadata.get("message_id"),
session_key=ctx.key, session_key=ctx.key,
session_generation=session.generation,
original_user_text=f"!{ctx.args.strip()}", original_user_text=f"!{ctx.args.strip()}",
runtime=ctx.runtime, runtime=ctx.runtime,
metadata=metadata, metadata=metadata,
@@ -900,7 +926,7 @@ class AgentLoop:
Returns the total number of cancelled tasks, subagents, and exec sessions. 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 = ( journaled_followup_ids = (
tuple( tuple(
followup_id followup_id
@@ -928,9 +954,7 @@ class AgentLoop:
# Explicit session cancellation owns the follow-ups accepted before # Explicit session cancellation owns the follow-ups accepted before
# it began. Gateway shutdown uses aclose() directly and keeps this # it began. Gateway shutdown uses aclose() directly and keeps this
# journal intact for startup recovery. # journal intact for startup recovery.
current_session = self.sessions.get_cached(key) or journal_session await self.sessions.state.acknowledge_followups(key, journaled_followup_ids)
acknowledge_pending_followups(current_session, journaled_followup_ids)
self.sessions.save(current_session)
sub_cancelled = await self.subagents.cancel_by_session(key) sub_cancelled = await self.subagents.cancel_by_session(key)
exec_cancelled = await self._exec_session_manager.terminate_by_owner(key) exec_cancelled = await self._exec_session_manager.terminate_by_owner(key)
return cancelled + sub_cancelled + exec_cancelled return cancelled + sub_cancelled + exec_cancelled
@@ -939,7 +963,7 @@ class AgentLoop:
"""Stop active work for *key* and forget its cached session.""" """Stop active work for *key* and forget its cached session."""
self._discarding_sessions.add(key) self._discarding_sessions.add(key)
try: try:
self.sessions.invalidate(key) await self.sessions.state.discard(key)
await self._cancel_active_tasks(key) await self._cancel_active_tasks(key)
finally: finally:
self.discard_session_file_state(key) self.discard_session_file_state(key)
@@ -970,7 +994,9 @@ class AgentLoop:
session_key: str, session_key: str,
) -> EventSink: ) -> EventSink:
"""Bind one idle compaction to its current user-facing destination.""" """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( return self.turn_delivery_factory.session_events(
session_key, session.metadata, session_key, session.metadata,
) )
@@ -1042,7 +1068,7 @@ class AgentLoop:
public_payload[self._PROVIDER_STATE_CHECKPOINT_VERSION_KEY] = ( public_payload[self._PROVIDER_STATE_CHECKPOINT_VERSION_KEY] = (
self._PROVIDER_STATE_CHECKPOINT_VERSION self._PROVIDER_STATE_CHECKPOINT_VERSION
) )
self._set_runtime_checkpoint(session, public_payload) await self._set_runtime_checkpoint(session, public_payload)
async def _drain_pending( async def _drain_pending(
*, *,
@@ -1099,6 +1125,7 @@ class AgentLoop:
chat_id=pending_msg.chat_id, chat_id=pending_msg.chat_id,
message_id=metadata.get("message_id"), message_id=metadata.get("message_id"),
session_key=active_session_key, session_key=active_session_key,
session_generation=session.generation if session is not None else None,
original_user_text=pending_msg.content, original_user_text=pending_msg.content,
runtime=runtime, runtime=runtime,
metadata=dict(metadata), metadata=dict(metadata),
@@ -1222,6 +1249,9 @@ class AgentLoop:
request_ctx = dataclasses.replace( request_ctx = dataclasses.replace(
request_ctx, request_ctx,
workspace_scope=effective_scope, workspace_scope=effective_scope,
session_generation=(
session.generation if session is not None else request_ctx.session_generation
),
log_content=( log_content=(
request_ctx.log_content and not ephemeral request_ctx.log_content and not ephemeral
and (session is None or session.policy.log_content) and (session is None or session.policy.log_content)
@@ -1237,8 +1267,9 @@ class AgentLoop:
workspace_token = bind_workspace_scope(effective_scope) workspace_token = bind_workspace_scope(effective_scope)
turn_scope_stack = ExitStack() turn_scope_stack = ExitStack()
# Compute lazily because create_goal may create goal metadata during this run. # Compute lazily because create_goal may create goal metadata during this run.
def _goal_continue() -> str | None: async def _goal_continue() -> str | None:
_goal_lines = goal_state_runtime_lines(session.metadata if session is not None else 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: if not _goal_lines:
return None return None
return ( return (
@@ -1350,17 +1381,20 @@ class AgentLoop:
) )
return result return result
def _check_expired_sessions_if_due(self) -> None: async def _check_expired_sessions_if_due(self) -> None:
"""Scan idle sessions no more often than the configured interval.""" """Scan idle sessions without blocking the event loop."""
now = time.monotonic() now = time.monotonic()
if now < self._next_idle_compact_check_at: if now < self._next_idle_compact_check_at:
return return
self._next_idle_compact_check_at = now + self._idle_compact_check_interval_s self._next_idle_compact_check_at = now + self._idle_compact_check_interval_s
self.auto_compact.check_expired( try:
self.schedule_background, await self.auto_compact.check_expired(
self.runtime_for_session, self.schedule_background,
active_session_keys=self._pending_queues.keys(), 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: async def run(self) -> None:
"""Run the agent loop, dispatching messages as tasks to stay responsive to /stop.""" """Run the agent loop, dispatching messages as tasks to stay responsive to /stop."""
@@ -1372,7 +1406,7 @@ class AgentLoop:
try: try:
msg = await asyncio.wait_for(self.bus.consume_inbound(), timeout=1.0) msg = await asyncio.wait_for(self.bus.consume_inbound(), timeout=1.0)
except asyncio.TimeoutError: except asyncio.TimeoutError:
self._check_expired_sessions_if_due() await self._check_expired_sessions_if_due()
continue continue
except asyncio.CancelledError: except asyncio.CancelledError:
# Preserve real task cancellation so shutdown can complete cleanly. # Preserve real task cancellation so shutdown can complete cleanly.
@@ -1387,55 +1421,66 @@ class AgentLoop:
logger.warning("Error consuming inbound message: {}, continuing...", e) logger.warning("Error consuming inbound message: {}, continuing...", e)
continue continue
raw = command_text(msg) try:
effective_key = self._effective_session_key(msg) await self._dispatch_inbound(msg)
if msg.metadata.get(INBOUND_META_RUNTIME_CONTROL) == RUNTIME_CONTROL_SESSION_DISCARD: except (SessionOperationQueueFullError, SessionConflictError) as exc:
await self.discard_session(msg.session_key) key = self._effective_session_key(msg)
continue logger.warning("Session input rejected for {}: {}", key, exc)
if ( if msg.is_user_input:
msg.require_existing_session delivery = self.turn_delivery_factory.unrouted(msg, key)
and self.sessions.get_existing(effective_key) is None await delivery.fail(publish_completion=key not in self._pending_queues)
):
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)
finally: finally:
await self.aclose() 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: def preserve_inflight_turns_on_shutdown(self) -> None:
"""Keep durable checkpoints when the owning gateway exits. """Keep durable checkpoints when the owning gateway exits.
@@ -1446,7 +1491,7 @@ class AgentLoop:
""" """
self._preserve_inflight_turns_on_shutdown = True self._preserve_inflight_turns_on_shutdown = True
def _journal_pending_message( async def _journal_pending_message(
self, self,
session_key: str, session_key: str,
msg: InboundMessage, msg: InboundMessage,
@@ -1454,8 +1499,7 @@ class AgentLoop:
"""Persist a recoverable WebUI follow-up before adding it to the inbox.""" """Persist a recoverable WebUI follow-up before adding it to the inbox."""
if not self._can_inject_message(msg): if not self._can_inject_message(msg):
return msg return msg
session = self.sessions.get_or_create(session_key) followup_id = await self.sessions.state.queue_followup(session_key, msg)
followup_id = record_pending_followup(session, msg)
if followup_id is None: if followup_id is None:
return msg return msg
pending_msg = dataclasses.replace( pending_msg = dataclasses.replace(
@@ -1465,10 +1509,9 @@ class AgentLoop:
PENDING_FOLLOWUP_ID_KEY: followup_id, PENDING_FOLLOWUP_ID_KEY: followup_id,
}, },
) )
self.sessions.save(session)
return pending_msg 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.""" """Admit session work without waiting for its execution or result."""
session_key = self._effective_session_key(msg) session_key = self._effective_session_key(msg)
if not self.subagents.accepts_result(msg, session_key): if not self.subagents.accepts_result(msg, session_key):
@@ -1484,9 +1527,11 @@ class AgentLoop:
): ):
return return
if session_key in self._pending_queues:
msg = await self._journal_pending_message(session_key, msg)
pending = self._pending_queues.get(session_key) pending = self._pending_queues.get(session_key)
if pending is not None: if pending is not None:
pending.put_nowait(self._journal_pending_message(session_key, msg)) pending.put_nowait(msg)
return return
new_pending: asyncio.Queue[InboundMessage] = asyncio.Queue() new_pending: asyncio.Queue[InboundMessage] = asyncio.Queue()
@@ -1514,7 +1559,7 @@ class AgentLoop:
msg = deferred.pop(0) msg = deferred.pop(0)
if not deferred: if not deferred:
self._deferred_automation_turns.pop(session_key) 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 ( log_content = session is None or (
session.policy.persist and session.policy.log_content session.policy.persist and session.policy.log_content
) )
@@ -1566,7 +1611,7 @@ class AgentLoop:
session_key = self._effective_session_key(msg) session_key = self._effective_session_key(msg)
# The request context is reset before errors reach this boundary, and # The request context is reset before errors reach this boundary, and
# discard may evict the session while a turn is still unwinding. # 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 ( log_content = session is None or (
session.policy.persist and session.policy.log_content 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 # A preceding user turn may have completed or blocked the goal
# while its older continuation was still waiting in the inbox. # while its older continuation was still waiting in the inbox.
if turn_continuation.sustained_goal_continuation_inbound(msg.metadata) and not ( 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 return
try: try:
await self.sessions.state.read(session_key)
delivery = self.turn_delivery_factory.create( delivery = self.turn_delivery_factory.create(
msg, msg,
session_key, session_key,
@@ -1637,10 +1683,10 @@ class AgentLoop:
raise raise
try: try:
key = self._effective_session_key(msg) 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): if restore_runtime_checkpoint(session):
self._clear_pending_user_turn(session) self._clear_pending_user_turn(session)
self.sessions.save(session) await self.sessions.state.restore_interruption(session)
logger.info( logger.info(
"Restored partial context for cancelled session {}", "Restored partial context for cancelled session {}",
key, key,
@@ -1727,6 +1773,7 @@ class AgentLoop:
self.subagents.close, self.subagents.close,
self._exec_session_manager.close_all, self._exec_session_manager.close_all,
self.runtime_resolver.aclose, self.runtime_resolver.aclose,
self.sessions.state.aclose,
) )
for cleanup in cleanup_steps: for cleanup in cleanup_steps:
try: try:
@@ -1790,6 +1837,17 @@ class AgentLoop:
key = session_key or msg.session_key key = session_key or msg.session_key
if not self.subagents.accepts_result(msg, key): if not self.subagents.accepts_result(msg, key):
return None 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: if delivery is None:
delivery = self.turn_delivery_factory.create(msg, key) delivery = self.turn_delivery_factory.create(msg, key)
elif delivery.session_key != key: elif delivery.session_key != key:
@@ -1823,6 +1881,7 @@ class AgentLoop:
on_runtime_admitted=on_runtime_admitted, on_runtime_admitted=on_runtime_admitted,
pending_queue=pending_queue, pending_queue=pending_queue,
ephemeral=ephemeral, ephemeral=ephemeral,
commit_session=commit_session,
run_extra_hooks_for_ephemeral=run_extra_hooks_for_ephemeral, run_extra_hooks_for_ephemeral=run_extra_hooks_for_ephemeral,
hooks=list(hooks or []), hooks=list(hooks or []),
hook_factories=list(hook_factories or []), hook_factories=list(hook_factories or []),
@@ -1980,13 +2039,19 @@ class AgentLoop:
msg = ctx.msg msg = ctx.msg
if ctx.session is None: if ctx.session is None:
if msg.require_existing_session: if msg.require_existing_session or msg.session_generation is not None:
ctx.session = self.sessions.get_existing(ctx.session_key) ctx.session = await self.sessions.state.read(ctx.session_key)
if ctx.session is None: if ctx.session is None:
raise RuntimeError("required session is not active") 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: else:
ctx.session = self.sessions.get_or_create(ctx.session_key) ctx.session = await self.sessions.state.get(ctx.session_key)
session = ctx.session session = ctx.session
ctx.delivery.bind_session_generation(session.generation)
ctx.ephemeral = ctx.ephemeral or not session.policy.persist ctx.ephemeral = ctx.ephemeral or not session.policy.persist
tools = ctx.tools if ctx.tools is not None else self.tools tools = ctx.tools if ctx.tools is not None else self.tools
if session.policy.disabled_tools: if session.policy.disabled_tools:
@@ -2016,17 +2081,20 @@ class AgentLoop:
if ctx.kind is TurnKind.USER: if ctx.kind is TurnKind.USER:
self.workspace_scopes.persist_message_scope(session, msg) self.workspace_scopes.persist_message_scope(session, msg)
if restore_runtime_checkpoint(session): if restore_runtime_checkpoint(session) and ctx.commit_session:
self.sessions.save(session) await self.sessions.state.restore_interruption(session)
if ( if (
RECOVERY_INBOUND_METADATA_KEY not in msg.metadata RECOVERY_INBOUND_METADATA_KEY not in msg.metadata
and restore_pending_interruption(session) 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: async def _compact_session(self, ctx: TurnContext) -> None:
if not ctx.commit_session:
return
session = ctx.require_session() session = ctx.require_session()
ctx.session, pending = self.auto_compact.prepare_session( ctx.session, pending = await self.auto_compact.prepare_session(
session, session,
ctx.session_key, ctx.session_key,
) )
@@ -2068,15 +2136,15 @@ class AgentLoop:
# message. Mark messages with _command so get_history can filter # message. Mark messages with _command so get_history can filter
# them out of LLM context. /new is excluded because it # them out of LLM context. /new is excluded because it
# intentionally clears the session. # intentionally clears the session.
if cmd_ctx.raw.lower() != "/new": if cmd_ctx.raw.lower() != "/new" and ctx.commit_session:
ctx.input_persisted_early = self._persist_user_message_early( ctx.input_persisted_early = await self._persist_user_message_early(
ctx.msg, session, _command=True ctx.msg, session, _command=True
) )
session.add_message( session.add_message(
"assistant", result.content, _command=True "assistant", result.content, _command=True
) )
self._clear_pending_user_turn(session) self._clear_pending_user_turn(session)
self.sessions.save(session) await self.sessions.state.prepare_input(session)
if not ctx.ephemeral: if not ctx.ephemeral:
await self.runtime_event_publisher.session_turn_persisted( await self.runtime_event_publisher.session_turn_persisted(
ctx.msg, ctx.msg,
@@ -2091,7 +2159,7 @@ class AgentLoop:
session = ctx.require_session() session = ctx.require_session()
runtime = ctx.runtime runtime = ctx.runtime
if runtime is None: if runtime is None:
runtime = self.runtime_for_session(session) runtime = await self.runtime_for_session(session)
ctx.runtime = runtime ctx.runtime = runtime
if ctx.session_key.startswith("dream:"): if ctx.session_key.startswith("dream:"):
logger.info( logger.info(
@@ -2101,22 +2169,10 @@ class AgentLoop:
) )
if ctx.on_runtime_admitted is not None: if ctx.on_runtime_admitted is not None:
await ctx.on_runtime_admitted(runtime) 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" 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( 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 stored_state = session.provider_state
subagent_followup_persisted = False subagent_followup_persisted = False
@@ -2136,7 +2192,7 @@ class AgentLoop:
# provider compatibility or prompt assembly work. A compatible # provider compatibility or prompt assembly work. A compatible
# staged state replaces this in a second atomic save below. # staged state replaces this in a second atomic save below.
session.provider_state = None session.provider_state = None
self.sessions.save(session) await self.sessions.state.prepare_input(session)
ctx.input_persisted_early = True ctx.input_persisted_early = True
await ctx.delivery.runtime_admitted(runtime) await ctx.delivery.runtime_admitted(runtime)
@@ -2189,8 +2245,8 @@ class AgentLoop:
staged_provider_state = True staged_provider_state = True
elif stored_state is not None: elif stored_state is not None:
session.provider_state = None session.provider_state = None
if ctx.kind is TurnKind.USER: if ctx.kind is TurnKind.USER and ctx.commit_session:
ctx.input_persisted_early = self._persist_user_message_early( ctx.input_persisted_early = await self._persist_user_message_early(
ctx.msg, ctx.msg,
session, session,
runtime_context_blocks=ctx.runtime_context_blocks, runtime_context_blocks=ctx.runtime_context_blocks,
@@ -2200,7 +2256,9 @@ class AgentLoop:
elif subagent_followup_persisted and staged_provider_state: elif subagent_followup_persisted and staged_provider_state:
# Upgrade the replay-safe baseline to the resumable state before # Upgrade the replay-safe baseline to the resumable state before
# prompt assembly and the first model checkpoint. # 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) ctx.transcript_input = self._build_transcript_input(ctx)
@@ -2242,7 +2300,10 @@ class AgentLoop:
ctx.usage = result.usage ctx.usage = result.usage
ctx.delivery.record_usage(result.round_usages) ctx.delivery.record_usage(result.round_usages)
if ctx.kind is TurnKind.USER: 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: async def _persist_turn(self, ctx: TurnContext) -> None:
session = ctx.require_session() session = ctx.require_session()
@@ -2284,7 +2345,8 @@ class AgentLoop:
session.provider_state = None session.provider_state = None
self._clear_pending_user_turn(session) self._clear_pending_user_turn(session)
self._clear_runtime_checkpoint(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: if not ctx.ephemeral:
await self.runtime_event_publisher.session_turn_persisted( await self.runtime_event_publisher.session_turn_persisted(
ctx.msg, ctx.msg,
@@ -2532,10 +2594,14 @@ class AgentLoop:
) )
return True return True
def _set_runtime_checkpoint(self, session: Session, payload: dict[str, Any]) -> None: async def _set_runtime_checkpoint(
"""Persist the latest in-flight turn state into session metadata.""" 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 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: def _mark_pending_user_turn(self, session: Session) -> None:
session.metadata[self._PENDING_USER_TURN_KEY] = True 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. # Share the dispatch lock so direct calls serialize with bus turns.
lock = self._get_session_lock(session_key) lock = self._get_session_lock(session_key)
temporary_parent = False
try: try:
async with lock: async with lock:
kwargs: dict[str, Any] = { kwargs: dict[str, Any] = {
@@ -2597,7 +2664,10 @@ class AgentLoop:
if _session_policy is not None: if _session_policy is not None:
# Isolate per-run state before any early save or checkpoint; # Isolate per-run state before any early save or checkpoint;
# the cached conversation must survive a temporary SDK turn. # 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( session.policy = SessionPolicy(
persist=session.policy.persist and _session_policy.persist, persist=session.policy.persist and _session_policy.persist,
log_content=session.policy.log_content and _session_policy.log_content, log_content=session.policy.log_content and _session_policy.log_content,
@@ -2618,10 +2688,13 @@ class AgentLoop:
kwargs["on_runtime_admitted"] = on_runtime_admitted kwargs["on_runtime_admitted"] = on_runtime_admitted
if attributes is not None: if attributes is not None:
kwargs["attributes"] = dict(attributes) kwargs["attributes"] = dict(attributes)
return await self._process_message( try:
msg, return await self._process_message(msg, **kwargs)
**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: finally:
await self.runtime_event_publisher.run_status_changed(msg, session_key, "idle") await self.runtime_event_publisher.run_status_changed(msg, session_key, "idle")
self.runtime_event_publisher.clear_turn(session_key) 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.base import LLMResponse, ProviderConversationState
from nanobot.providers.conversation_state import ProviderConversationStateController from nanobot.providers.conversation_state import ProviderConversationStateController
from nanobot.runtime_context import public_history_messages 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.manager import Session, SessionManager
from nanobot.session.summary import is_summary_checkpoint, session_summary_from_metadata from nanobot.session.summary import is_summary_checkpoint, session_summary_from_metadata
from nanobot.utils.gitstore import GitStore from nanobot.utils.gitstore import GitStore
@@ -722,28 +721,6 @@ class MemoryStore:
return prefix return prefix
return f"{prefix}\n\n{diff_body}" 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 # Memory ingestion and context-pressure coordination
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -1253,8 +1230,8 @@ class Consolidator:
""" """
lock = self.get_lock(session_key) lock = self.get_lock(session_key)
async with lock: async with lock:
self.sessions.invalidate(session_key) await self.sessions.state.discard(session_key)
session = self.sessions.get_or_create(session_key) session = await self.sessions.state.get(session_key)
archive_start = session.last_archived archive_start = session.last_archived
messages_to_archive = list(session.messages[archive_start:]) messages_to_archive = list(session.messages[archive_start:])
@@ -1269,20 +1246,15 @@ class Consolidator:
await events.emit( await events.emit(
ContextCompactionEvent(compaction_id=compaction_id, phase="started", notify=notify), ContextCompactionEvent(compaction_id=compaction_id, phase="started", notify=notify),
) )
last_active = session.updated_at
archive_end = archive_start + len(messages_to_archive) archive_end = archive_start + len(messages_to_archive)
try: try:
summary = await self.archive_session( summary = await self.archive_session(
session, archive_end=archive_end, runtime=runtime, session, archive_end=archive_end, runtime=runtime,
) )
if summary: if summary:
# Concurrent appends remain after the captured boundary. await self.sessions.state.commit_summary(
session.commit_summary_checkpoint( session, summary, archive_end=archive_end,
summary, insert_at=archive_end, last_active=last_active,
) )
# 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: except (Exception, asyncio.CancelledError) as exc:
await events.emit( await events.emit(
ContextCompactionEvent( ContextCompactionEvent(
+14 -28
View File
@@ -68,7 +68,7 @@ def _raise_if_cancelling() -> None:
raise asyncio.CancelledError raise asyncio.CancelledError
ContinuationCallback = Callable[[], str | None] ContinuationCallback = Callable[[], Awaitable[str | None]]
CheckpointCallback = Callable[[dict[str, Any]], Awaitable[None]] CheckpointCallback = Callable[[dict[str, Any]], Awaitable[None]]
InjectionCallback = Callable[[], Awaitable[Iterable[Any] | None]] InjectionCallback = Callable[[], Awaitable[Iterable[Any] | None]]
@@ -158,29 +158,15 @@ class AgentRunner:
self, operation: Callable[_PromptArgs, _PromptResult], self, operation: Callable[_PromptArgs, _PromptResult],
*args: _PromptArgs.args, **kwargs: _PromptArgs.kwargs, *args: _PromptArgs.args, **kwargs: _PromptArgs.kwargs,
) -> _PromptResult: ) -> _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) 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( async def _run_context_snapshot(
self, messages: list[dict[str, Any]], self, hook: AgentHook, messages: list[dict[str, Any]],
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
if not messages: if not messages or not hook.has_run_hooks():
return [] return []
task = asyncio.current_task() return await asyncio.to_thread(deepcopy, messages)
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)
@staticmethod @staticmethod
def _append_injected_messages( def _append_injected_messages(
@@ -208,7 +194,7 @@ class AgentRunner:
injections = await self._drain_injections(spec) if drain_callback else [] injections = await self._drain_injections(spec) if drain_callback else []
real_injection = bool(injections) real_injection = bool(injections)
if not injections and allow_continuation and assistant_message is not None: 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: if continuation is not None:
injections = [continuation] injections = [continuation]
if ( if (
@@ -260,12 +246,12 @@ class AgentRunner:
return True, injection_cycles return True, injection_cycles
@staticmethod @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 callback = spec.continuation_callback
if callback is None: if callback is None:
return None return None
try: try:
content = callback() content = await callback()
except Exception: except Exception:
logger.opt(exception=tool_log_content_allowed()).error("continuation_callback failed") logger.opt(exception=tool_log_content_allowed()).error("continuation_callback failed")
return None return None
@@ -332,18 +318,18 @@ class AgentRunner:
try: try:
try: try:
messages, compaction = await self.prepare_prompt(self._initial_transcript_and_compaction, spec) 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) await hook.before_run(context)
result = await self._run_core(spec, hook, messages, compaction) result = await self._run_core(spec, hook, messages, compaction)
except Exception as exc: 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.stop_reason = "error"
context.error = f"Error: {type(exc).__name__}: {exc}" context.error = f"Error: {type(exc).__name__}: {exc}"
context.exception = exc context.exception = exc
await hook.on_error(context) await hook.on_error(context)
raise raise
else: 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.final_content = result.final_content
context.tools_used = list(result.tools_used) context.tools_used = list(result.tools_used)
context.usage = result.usage context.usage = result.usage
@@ -365,14 +351,14 @@ class AgentRunner:
if has_run_hooks: if has_run_hooks:
try: try:
if isinstance(context.exception, asyncio.CancelledError): 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: else:
context.messages = await self._run_context_snapshot(messages) context.messages = await self._run_context_snapshot(hook, messages)
except asyncio.CancelledError as exc: except asyncio.CancelledError as exc:
context.stop_reason = "cancelled" context.stop_reason = "cancelled"
context.error = None context.error = None
context.exception = exc context.exception = exc
context.messages = await self.copy_messages_on_loop(messages) context.messages = await self._run_context_snapshot(hook, messages)
raise raise
finally: finally:
try: try:
+101 -41
View File
@@ -7,7 +7,7 @@ import json
import time import time
import uuid import uuid
import warnings import warnings
from collections.abc import Callable, Mapping from collections.abc import Awaitable, Callable, Mapping
from copy import deepcopy from copy import deepcopy
from dataclasses import dataclass, field, replace from dataclasses import dataclass, field, replace
from functools import partial from functools import partial
@@ -49,6 +49,7 @@ from nanobot.security.workspace_access import (
workspace_sandbox_status, workspace_sandbox_status,
) )
from nanobot.session.manager import Session, SessionManager, SessionPolicy 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.llm_runtime import LLMRuntime
from nanobot.utils.prompt_templates import render_template from nanobot.utils.prompt_templates import render_template
@@ -158,7 +159,7 @@ class _SubagentHook(AgentHook):
def __init__(self, status: SubagentStatus | None = None, def __init__(self, status: SubagentStatus | None = None,
*, check_active: Callable[[], None] | None = None, *, check_active: Callable[[], None] | None = None,
max_result_chars: int = 16000, max_result_chars: int = 16000,
on_status: Callable[[SubagentStatus], None] | None = None) -> None: on_status: Callable[[SubagentStatus], Awaitable[None]] | None = None) -> None:
super().__init__() super().__init__()
self._status = status self._status = status
self._check_active = check_active self._check_active = check_active
@@ -180,7 +181,7 @@ class _SubagentHook(AgentHook):
{"name": call.name, "status": "running"} for call in context.tool_calls {"name": call.name, "status": "running"} for call in context.tool_calls
] ]
if self._status is not None and self._on_status is not None: 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( async def before_execute_tool(
self, context: AgentHookContext, tool_call: ToolCallRequest, self, context: AgentHookContext, tool_call: ToolCallRequest,
@@ -199,7 +200,7 @@ class _SubagentHook(AgentHook):
if context.error: if context.error:
self._status.error = str(context.error) self._status.error = str(context.error)
if self._on_status is not None: if self._on_status is not None:
self._on_status(self._status) await self._on_status(self._status)
class SubagentManager: class SubagentManager:
@@ -273,6 +274,7 @@ class SubagentManager:
self._terminal_statuses: dict[str, SubagentStatus] = {} self._terminal_statuses: dict[str, SubagentStatus] = {}
self._closed = False self._closed = False
self._close_task: asyncio.Task[int] | None = None self._close_task: asyncio.Task[int] | None = None
self._admitting = 0
self.sessions = SubagentSessions(session_manager) if session_manager is not None else None self.sessions = SubagentSessions(session_manager) if session_manager is not None else None
MAX_ACTIVE = 128 MAX_ACTIVE = 128
@@ -283,11 +285,11 @@ class SubagentManager:
CANCEL_WAIT_SECONDS = 5.0 CANCEL_WAIT_SECONDS = 5.0
def _save_status( async def _save_status(
self, status: SubagentStatus, *, fsync: bool = False, self, status: SubagentStatus,
) -> None: ) -> None:
status.revision += 1 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 return
self._publish_status(status) self._publish_status(status)
@@ -300,10 +302,10 @@ class SubagentManager:
task_id=status.task_id, 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.""" """Recover observations only after the host has claimed execution ownership."""
if self.sessions is not None: 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]: def _start_cleanup(self, record: _SubagentTask, *, retry: bool = False) -> asyncio.Task[int]:
cleanup = record.cleanup_task cleanup = record.cleanup_task
@@ -326,10 +328,11 @@ class SubagentManager:
and not cleanup.cancelled() and cleanup.exception() is None): and not cleanup.cancelled() and cleanup.exception() is None):
self._tasks.pop(record.status.task_id, 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: cleanup_error: str | None = None) -> _SubagentOutcome:
outcome = record.finish(self.max_tool_result_chars, cleanup_error) 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() self._terminal_statuses[record.status.task_id] = record.snapshot()
while len(self._terminal_statuses) > self.MAX_TERMINAL: while len(self._terminal_statuses) > self.MAX_TERMINAL:
del self._terminal_statuses[next(iter(self._terminal_statuses))] del self._terminal_statuses[next(iter(self._terminal_statuses))]
@@ -341,7 +344,7 @@ class SubagentManager:
for message_id, _ in snapshot: for message_id, _ in snapshot:
record.status.receipts[message_id] = "delivered" record.status.receipts[message_id] = "delivered"
if snapshot: if snapshot:
self._save_status(record.status) await self._save_status(record.status)
return [{"role": "user", "content": content} for _, content in snapshot] return [{"role": "user", "content": content} for _, content in snapshot]
def _owned_status(self, task_id: str, owner: str | None) -> SubagentStatus: def _owned_status(self, task_id: str, owner: str | None) -> SubagentStatus:
@@ -377,7 +380,7 @@ class SubagentManager:
raise SubagentControlError("task unavailable") raise SubagentControlError("task unavailable")
return status, child 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: message: str | None) -> SubagentMessageReceipt:
"""Accept a bounded follow-up only while execution is open.""" """Accept a bounded follow-up only while execution is open."""
status = self._owned_status(task_id, owner) status = self._owned_status(task_id, owner)
@@ -391,7 +394,7 @@ class SubagentManager:
message_id = str(uuid.uuid4()) message_id = str(uuid.uuid4())
record.inbox.append((message_id, message)) record.inbox.append((message_id, message))
status.receipts[message_id] = "accepted" status.receipts[message_id] = "accepted"
self._save_status(status) await self._save_status(status)
return {"task_id": task_id, "message_id": message_id, return {"task_id": task_id, "message_id": message_id,
"receipt": "accepted", "delivered": False} "receipt": "accepted", "delivered": False}
@@ -410,7 +413,7 @@ class SubagentManager:
task_id = record.status.task_id task_id = record.status.task_id
task = self._running_tasks.get(task_id) task = self._running_tasks.get(task_id)
if record.decide(_SubagentOutcome("cancelled", "Task cancelled.", "cancelled")): 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(): if task is not None and record.begun and not task.done():
task.cancel() task.cancel()
if record.status.finished_at is None: if record.status.finished_at is None:
@@ -428,21 +431,44 @@ class SubagentManager:
**deepcopy(self._terminal_statuses), **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( def statuses_for_session(
self, session_key: str | None, *, include_history: bool = True, self, session_key: str | None, *, include_history: bool = True,
) -> Mapping[str, SubagentStatus]: ) -> Mapping[str, SubagentStatus]:
"""Return only tasks owned by the given session, never a global fallback.""" """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 {}
return { return self._merge_session_statuses(
**(self.sessions.load(session_key) if include_history and self.sessions is not None else {}), session_key, self._runtime_statuses_for_session(session_key), include_history=include_history,
**{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))}, async def read_statuses_for_session(self, session_key: str) -> Mapping[str, SubagentStatus]:
**{tid: deepcopy(status) for tid, status in self._terminal_statuses.items() """Capture runtime observations on the owner loop; read stored metadata on a worker."""
if status.owner == session_key runtime = self._runtime_statuses_for_session(session_key)
and (self.sessions is None or self.sessions.contains(tid, 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: def set_provider(self, provider: LLMProvider, model: str) -> None:
"""Update the deprecated runtime source used by legacy ``spawn`` calls.""" """Update the deprecated runtime source used by legacy ``spawn`` calls."""
@@ -511,7 +537,7 @@ class SubagentManager:
ToolLoader().load(ctx, registry, scope="subagent") ToolLoader().load(ctx, registry, scope="subagent")
return registry return registry
def _create_task( async def _create_task(
self, task: str, label: str | None, origin_channel: str, origin_chat_id: str, self, task: str, label: str | None, origin_channel: str, origin_chat_id: str,
session_key: str | None, origin_message_id: str | None, session_key: str | None, origin_message_id: str | None,
temperature: float | None, workspace_scope: WorkspaceScope | None, temperature: float | None, workspace_scope: WorkspaceScope | None,
@@ -523,7 +549,7 @@ class SubagentManager:
if temperature is not None: if temperature is not None:
runtime = runtime.with_generation_overrides(temperature=temperature) runtime = runtime.with_generation_overrides(temperature=temperature)
# A failed cleanup owns admission even after its status has been evicted. # 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") raise SubagentControlError("subagent manager is closed or at task capacity")
owner = session_key or f"{origin_channel}:{origin_chat_id}" owner = session_key or f"{origin_channel}:{origin_chat_id}"
task_id = str(uuid.uuid4()) task_id = str(uuid.uuid4())
@@ -537,11 +563,28 @@ class SubagentManager:
origin_message_id=origin_message_id, origin_message_id=origin_message_id,
origin_turn_id=origin_turn_id, origin_turn_id=origin_turn_id,
) )
if self.sessions is not None: self._admitting += 1
child = self.sessions.create(status, policy=session_policy) try:
else: if self.sessions is not None:
child = Session(key=SubagentSessions.key(task_id), policy=session_policy or SessionPolicy()) admission = asyncio.create_task(self.sessions.create(status, policy=session_policy))
child.add_message("user", task) 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( record = _SubagentTask(
status=status, status=status,
session=child, session=child,
@@ -580,7 +623,7 @@ class SubagentManager:
) -> str: ) -> str:
"""Start background work and route its terminal result to the parent.""" """Start background work and route its terminal result to the parent."""
try: try:
record = self._create_task( record = await self._create_task(
task, label, origin_channel, origin_chat_id, session_key, task, label, origin_channel, origin_chat_id, session_key,
origin_message_id, temperature, workspace_scope, runtime, announce=True, origin_turn_id=origin_turn_id, origin_message_id, temperature, workspace_scope, runtime, announce=True, origin_turn_id=origin_turn_id,
session_policy=session_policy, session_policy=session_policy,
@@ -607,7 +650,7 @@ class SubagentManager:
) -> str: ) -> str:
"""Wait for the same task lifecycle without a background notice.""" """Wait for the same task lifecycle without a background notice."""
try: try:
record = self._create_task( record = await self._create_task(
task, label, origin_channel, origin_chat_id, session_key, task, label, origin_channel, origin_chat_id, session_key,
origin_message_id, temperature, workspace_scope, runtime, announce=False, origin_turn_id=origin_turn_id, origin_message_id, temperature, workspace_scope, runtime, announce=False, origin_turn_id=origin_turn_id,
session_policy=session_policy, session_policy=session_policy,
@@ -647,9 +690,25 @@ class SubagentManager:
else _SubagentOutcome("cancelled", "Task cancelled.", "cancelled") else _SubagentOutcome("cancelled", "Task cancelled.", "cancelled")
) )
self._start_cleanup(record) 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) 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: async def _run_subagent(self, record: _SubagentTask) -> str:
"""Execute once, seal the outcome, then clean up and publish once.""" """Execute once, seal the outcome, then clean up and publish once."""
status = record.status status = record.status
@@ -661,7 +720,7 @@ class SubagentManager:
record.raise_if_stopping() record.raise_if_stopping()
status.state = "running" status.state = "running"
status.phase = "initializing" status.phase = "initializing"
self._save_status(status) await self._save_status(status)
outcome = await self._run_admitted_subagent(record) outcome = await self._run_admitted_subagent(record)
record.decide(outcome) record.decide(outcome)
except asyncio.CancelledError: except asyncio.CancelledError:
@@ -677,7 +736,7 @@ class SubagentManager:
"Subagent [{}] exec cleanup failed", status.task_id, "Subagent [{}] exec cleanup failed", status.task_id,
) )
cleanup_error = f"Error cleaning up task processes: {exc}" 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: if record.announce and not record.suppress_notice and not self._closed:
await self._announce_result( await self._announce_result(
status.task_id, label, task_text, outcome.result, record.origin, status.task_id, label, task_text, outcome.result, record.origin,
@@ -703,7 +762,7 @@ class SubagentManager:
iteration = payload.get("iteration", status.iteration) iteration = payload.get("iteration", status.iteration)
if (phase, iteration) != (status.phase, status.iteration): if (phase, iteration) != (status.phase, status.iteration):
status.phase, status.iteration = phase, 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 root = workspace_scope.project_path if workspace_scope is not None else self.workspace
cfg = None cfg = None
@@ -719,13 +778,14 @@ class SubagentManager:
] ]
activity = SessionActivity() activity = SessionActivity()
def save_observation(status: SubagentStatus) -> None: async def save_observation(status: SubagentStatus) -> None:
record.session.messages = activity.transcript() 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: async def publish_activity(event: AgentEvent) -> None:
if activity.remember(event): if activity.remember(event):
save_observation(status) await save_observation(status)
events = EventSink(publish_activity) events = EventSink(publish_activity)
hook = build_agent_turn_hook(AgentTurnHookSpec( hook = build_agent_turn_hook(AgentTurnHookSpec(
+39 -49
View File
@@ -4,7 +4,6 @@ from __future__ import annotations
import math import math
import time import time
from copy import deepcopy
from typing import Any, cast from typing import Any, cast
from loguru import logger 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 SubagentSessionError as SubagentSessionError
from nanobot.agent.subagent_status import SubagentStatus from nanobot.agent.subagent_status import SubagentStatus
from nanobot.session.manager import Session, SessionManager, SessionPolicy 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 from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY, SessionType
SUBAGENT = SessionType("subagent", needs_handle=False, public_history=False) SUBAGENT = SessionType("subagent", needs_handle=False, public_history=False)
@@ -33,21 +33,23 @@ class SubagentSessions:
return f"subagent:{task_id}" return f"subagent:{task_id}"
def exists(self, owner: str) -> bool: 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: def contains(self, task_id: str, owner: str) -> bool:
key = self.key(task_id) key = self.key(task_id)
child = self.sessions.get_cached(key) metadata = self.sessions.get_cached_metadata(key)
metadata = child.metadata if child is not None else (self.sessions.read_session_metadata(key) or {}).get("metadata", {}) 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 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: def snapshot(self, task_id: str, owner: str) -> Session | None:
"""Read a detached child only while its parent still owns it.""" """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):
if not self.exists(owner) or not self.contains(task_id, owner): return None
return None return self.sessions.get_existing(self.key(task_id))
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))
@staticmethod @staticmethod
def _payload(status: SubagentStatus) -> dict[str, Any]: def _payload(status: SubagentStatus) -> dict[str, Any]:
@@ -56,49 +58,36 @@ class SubagentSessions:
"elapsed_seconds": status.as_dict()["elapsed_seconds"], "elapsed_seconds": status.as_dict()["elapsed_seconds"],
} }
def create(self, status: SubagentStatus, *, policy: SessionPolicy | None = None) -> Session: async def create(self, status: SubagentStatus, *, policy: SessionPolicy | None = None) -> Session:
with self.sessions.locked_session_files(): return await self.sessions.state.create_child(
parent = self.sessions.get_existing(status.owner) status.owner, self.key(status.task_id),
if parent is None: metadata={SESSION_TYPE_KEY: SUBAGENT.name, TASK_METADATA_KEY: self._payload(status)},
parent = self.sessions.get_or_create(status.owner) content=status.task_description, policy=policy or SessionPolicy(),
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
def save(self, status: SubagentStatus, *, fsync: bool = False) -> bool: async def save(self, status: SubagentStatus) -> bool:
with self.sessions.locked_session_files(): try:
if not self.exists(status.owner): await self.sessions.state.update_metadata(
return False self.key(status.task_id), {TASK_METADATA_KEY: self._payload(status)},
child = self.sessions.get_existing(self.key(status.task_id)) )
if child is None or not self.contains(status.task_id, status.owner): except SessionConflictError:
return False return False
child.metadata[TASK_METADATA_KEY] = self._payload(status) return True
# Only create() establishes identity. Progress and late completion
# cannot recreate a child removed with its parent.
self.sessions.save(child, fsync=fsync)
return True
def status(self, task_id: str, owner: str) -> SubagentStatus | None: def status(self, task_id: str, owner: str) -> SubagentStatus | None:
payload = self.sessions.read_session_metadata(self.key(task_id)) 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: if payload is None:
return None return None
metadata = payload.get("metadata", {}) 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: if metadata.get(SESSION_TYPE_KEY) != SUBAGENT.name or metadata.get(PARENT_SESSION_KEY) != owner:
return None return None
raw: object = metadata.get(TASK_METADATA_KEY) raw: object = metadata.get(TASK_METADATA_KEY)
@@ -123,16 +112,17 @@ class SubagentSessions:
def load(self, owner: str) -> dict[str, SubagentStatus]: def load(self, owner: str) -> dict[str, SubagentStatus]:
result: 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:") task_id = key.removeprefix("subagent:")
if key != self.key(task_id): if key != self.key(task_id):
continue continue
status = self.status(task_id, owner) status = self._status_from_metadata(task_id, owner, row["metadata"])
if status is not None: if status is not None:
result[task_id] = status result[task_id] = status
return result return result
def interrupt_pending(self) -> None: async def interrupt_pending(self) -> None:
"""Seal abandoned work after the gateway acquires execution ownership.""" """Seal abandoned work after the gateway acquires execution ownership."""
for row in self.sessions.list_sessions(): for row in self.sessions.list_sessions():
key = row["key"] key = row["key"]
@@ -156,6 +146,6 @@ class SubagentSessions:
status.tool_events = [] status.tool_events = []
status.receipts = {key: "undelivered" if receipt == "accepted" else receipt status.receipts = {key: "undelivered" if receipt == "accepted" else receipt
for key, receipt in status.receipts.items()} for key, receipt in status.receipts.items()}
self.save(status, fsync=True) await self.save(status)
except (OSError, SubagentSessionError): except (OSError, SubagentSessionError):
logger.exception("Could not recover subagent session {}", key) logger.exception("Could not recover subagent session {}", key)
+1
View File
@@ -33,6 +33,7 @@ class RequestContext:
chat_id: str chat_id: str
message_id: str | None = None message_id: str | None = None
session_key: str | None = None session_key: str | None = None
session_generation: str | None = field(default=None, kw_only=True)
original_user_text: str | None = None original_user_text: str | None = None
runtime: LLMRuntime | None = None runtime: LLMRuntime | None = None
metadata: dict[str, Any] = field(default_factory=dict) 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, sustained_goal_active,
) )
from nanobot.session.turn_continuation import reset_goal_continuation_rounds 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 from nanobot.utils.prompt_templates import render_template
if TYPE_CHECKING: if TYPE_CHECKING:
from nanobot.session.manager import SessionManager from nanobot.session.manager import Session, SessionManager
_GOAL_ACTIONS = ("complete", "cancel", "block", "replace") _GOAL_ACTIONS = ("complete", "cancel", "block", "replace")
@@ -61,36 +62,47 @@ class _GoalToolsMixin:
self._sessions = sessions self._sessions = sessions
self._bus = bus self._bus = bus
def _session(self): async def _session(self) -> Session | None:
request_ctx = current_request_context() request_ctx = current_request_context()
if request_ctx is None: if request_ctx is None:
return None return None
key = request_ctx.session_key key = request_ctx.session_key
if not key: if not key:
return None return None
return self._sessions.get_or_create(key) return await self._sessions.state.get_header(key)
def _goal_mutation_allowed(self) -> bool: def _goal_mutation_allowed(self) -> bool:
return current_request_context() is not None and goal_mutation_allowed() return current_request_context() is not None and goal_mutation_allowed()
def _save_goal_state( async def _save_goal_state(
self, self,
sess: Any, sess: Session,
blob: dict[str, Any], blob: dict[str, Any],
*, *,
reset_continuation: bool = False, reset_continuation: bool = False,
revoke_permission: bool = False,
) -> None: ) -> None:
previous_metadata = deepcopy(sess.metadata) saved = False
sess.metadata[GOAL_STATE_KEY] = blob
discard_legacy_goal_state_key(sess.metadata) async def save_and_publish() -> None:
if reset_continuation: nonlocal saved
reset_goal_continuation_rounds(sess.metadata) 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: try:
self._sessions.save(sess) await shield_and_drain(save_and_publish())
except BaseException: finally:
sess.metadata.clear() # This ContextVar belongs to the caller task, not the settlement task.
sess.metadata.update(previous_metadata) if revoke_permission and saved:
raise revoke_goal_mutation_permission()
async def _publish_goal_state_changed(self, metadata: dict[str, Any]) -> None: async def _publish_goal_state_changed(self, metadata: dict[str, Any]) -> None:
bus = self._bus bus = self._bus
@@ -171,11 +183,14 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
self, self,
request: RequestContext, request: RequestContext,
) -> RuntimeContextBlock | None: ) -> RuntimeContextBlock | None:
if not request.session_key: if not request.session_key or not request.persist_session:
return None 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_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: if not goal_start_requested and not goal_active:
return None return None
@@ -185,7 +200,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
goal_start_requested=goal_start_requested, goal_start_requested=goal_start_requested,
goal_active=goal_active, 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) content = "\n\n".join(part for part in (guidance, state) if part)
return RuntimeContextBlock(source="goal", content=content) return RuntimeContextBlock(source="goal", content=content)
@@ -195,7 +210,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
ui_summary: str | None = None, ui_summary: str | None = None,
**kwargs: Any, **kwargs: Any,
) -> str: ) -> str:
sess = self._session() sess = await self._session()
if sess is None: if sess is None:
return ToolResult.error( return ToolResult.error(
"Error: create_goal requires an active chat session (missing routing context)." "Error: create_goal requires an active chat session (missing routing context)."
@@ -223,8 +238,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
"ui_summary": summary, "ui_summary": summary,
"started_at": _iso_now(), "started_at": _iso_now(),
} }
self._save_goal_state(sess, blob, reset_continuation=True) await self._save_goal_state(sess, blob, reset_continuation=True)
await self._publish_goal_state_changed(sess.metadata)
extra = f"\nSummary line: {summary}" if summary else "" extra = f"\nSummary line: {summary}" if summary else ""
return ( return (
"Goal recorded. Keep working toward the objective using ordinary tools. " "Goal recorded. Keep working toward the objective using ordinary tools. "
@@ -303,7 +317,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
ui_summary: str | None = None, ui_summary: str | None = None,
**kwargs: Any, **kwargs: Any,
) -> str: ) -> str:
sess = self._session() sess = await self._session()
if sess is None: if sess is None:
return ToolResult.error("Error: update_goal requires an active chat session.") return ToolResult.error("Error: update_goal requires an active chat session.")
prior = parse_goal_state(goal_state_raw(sess.metadata)) prior = parse_goal_state(goal_state_raw(sess.metadata))
@@ -338,8 +352,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
"previous_objective": str(prior.get("objective") or ""), "previous_objective": str(prior.get("objective") or ""),
"recap": (recap or "").strip(), "recap": (recap or "").strip(),
} }
self._save_goal_state(sess, blob, reset_continuation=True) await self._save_goal_state(sess, blob, reset_continuation=True)
await self._publish_goal_state_changed(sess.metadata)
extra = f"\nSummary line: {summary}" if summary else "" extra = f"\nSummary line: {summary}" if summary else ""
return "Goal replaced. Continue toward the new objective using ordinary tools." + extra return "Goal replaced. Continue toward the new objective using ordinary tools." + extra
@@ -357,9 +370,7 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
} }
if normalized == "complete": if normalized == "complete":
blob["completed_at"] = ended blob["completed_at"] = ended
self._save_goal_state(sess, blob) await self._save_goal_state(sess, blob, revoke_permission=True)
revoke_goal_mutation_permission()
await self._publish_goal_state_changed(sess.metadata)
tail = (recap or "").strip() tail = (recap or "").strip()
label = { label = {
+3
View File
@@ -225,6 +225,9 @@ class MessageTool(Tool):
metadata["message_id"] = message_id metadata["message_id"] = message_id
if media: if media:
metadata["_record_channel_delivery"] = True 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( msg = OutboundMessage(
channel=channel, channel=channel,
+8 -4
View File
@@ -100,7 +100,7 @@ class RuntimeControl(Protocol):
def set_model(self, model: str) -> LLMRuntime: ... def set_model(self, model: str) -> LLMRuntime: ...
def set_model_preset( async def set_model_preset(
self, self,
name: str, name: str,
*, *,
@@ -156,7 +156,11 @@ class _RuntimeControlTarget(Protocol):
def set_model_preset(self, name: str | None) -> LLMRuntime: ... 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: class AgentRuntimeControl:
@@ -227,14 +231,14 @@ class AgentRuntimeControl:
def set_model(self, model: str) -> LLMRuntime: def set_model(self, model: str) -> LLMRuntime:
return self.__target.set_runtime_model(model) return self.__target.set_runtime_model(model)
def set_model_preset( async def set_model_preset(
self, self,
name: str, name: str,
*, *,
session_key: str | None, session_key: str | None,
) -> LLMRuntime: ) -> LLMRuntime:
if session_key is not None: 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) return self.__target.set_model_preset(name)
def set_max_iterations(self, value: int) -> None: def set_max_iterations(self, value: int) -> None:
+5 -5
View File
@@ -252,7 +252,7 @@ class MyTool(Tool):
if not self._modify_allowed: if not self._modify_allowed:
return ToolResult.error("Error: set is disabled (tools.my.allow_set is false)") return ToolResult.error("Error: set is disabled (tools.my.allow_set is false)")
if action in ("modify", "set"): if action in ("modify", "set"):
return self._modify(key, value) return await self._modify(key, value)
return f"Unknown action: {action}" return f"Unknown action: {action}"
# -- inspect -- # -- inspect --
@@ -335,7 +335,7 @@ class MyTool(Tool):
# -- modify -- # -- 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): if err := self._validate_key(key):
return err return err
key = cast(str, key) key = cast(str, key)
@@ -361,7 +361,7 @@ class MyTool(Tool):
self._audit("modify", f"READ_ONLY {key}") self._audit("modify", f"READ_ONLY {key}")
return ToolResult.error(f"Error: '{key}' is read-only and cannot be modified") return ToolResult.error(f"Error: '{key}' is read-only and cannot be modified")
if key == "model_preset": if key == "model_preset":
return self._modify_model_preset(value) return await self._modify_model_preset(value)
if key in self.RESTRICTED: if key in self.RESTRICTED:
return self._modify_restricted(key, value) return self._modify_restricted(key, value)
if key in RUNTIME_COMMAND_KEYS: 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 ToolResult.error(f"Error: '{key}' is read-only and cannot be modified")
return self._modify_scratchpad(key, value) 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(): if not isinstance(value, str) or not value.strip():
return ToolResult.error("Error: 'model_preset' must be a non-empty string") return ToolResult.error("Error: 'model_preset' must be a non-empty string")
name = value.strip() name = value.strip()
session_key = current_request_session_key() session_key = current_request_session_key()
old = self._runtime_control.snapshot().model_preset old = self._runtime_control.snapshot().model_preset
try: try:
runtime = self._runtime_control.set_model_preset( runtime = await self._runtime_control.set_model_preset(
name, name,
session_key=session_key, session_key=session_key,
) )
+3 -6
View File
@@ -88,7 +88,7 @@ class ListSessionsTool(Tool):
request = current_request_context() request = current_request_context()
if request is None or not request.session_key: if request is None or not request.session_key:
return ToolResult.error("Error: session context is unavailable") 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( return json.dumps(
[ [
f"@{handle.name}" f"@{handle.name}"
@@ -219,14 +219,11 @@ class SendSessionMessageTool(Tool):
target_name = normalize_session_handle(target_handle) target_name = normalize_session_handle(target_handle)
except ValueError as exc: except ValueError as exc:
raise SessionMessageError(str(exc)) from 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: if target is None:
raise SessionMessageError(f"session @{target_name} was not found") raise SessionMessageError(f"session @{target_name} was not found")
source = await asyncio.to_thread( source = await self._handles.ahandle_for_session(source_session_key)
self._handles.handle_for_session,
source_session_key,
)
if source is None: if source is None:
raise SessionMessageError("source session was not found") raise SessionMessageError("source session was not found")
envelope: SessionMessageEnvelope = { envelope: SessionMessageEnvelope = {
+1 -4
View File
@@ -186,10 +186,7 @@ class ReadSessionTool(_SessionTool):
handle_name = normalize_session_handle(session_key) handle_name = normalize_session_handle(session_key)
except ValueError as exc: except ValueError as exc:
return ToolResult.error(f"Error: {exc}") return ToolResult.error(f"Error: {exc}")
handle = await asyncio.to_thread( handle = await self._handles.aresolve(handle_name)
self._handles.resolve,
handle_name,
)
if handle is None: if handle is None:
return ToolResult.error(f"Error: session @{handle_name} was not found") return ToolResult.error(f"Error: session @{handle_name} was not found")
session_handle = f"@{handle_name}" session_handle = f"@{handle_name}"
+1 -1
View File
@@ -109,7 +109,7 @@ class SubagentTool(Tool):
if not task_id: if not task_id:
return ToolResult.error(f"Error: {action} requires task_id") return ToolResult.error(f"Error: {action} requires task_id")
if action == "send": 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) status = await self._manager.cancel(task_id, owner)
return json.dumps(status.as_dict(), ensure_ascii=False) return json.dumps(status.as_dict(), ensure_ascii=False)
return ToolResult.error("Error: unknown subagent action") return ToolResult.error("Error: unknown subagent action")
+5
View File
@@ -231,6 +231,11 @@ class TurnDelivery:
def streaming(self) -> bool: def streaming(self) -> bool:
return self._stream_base_id is not None 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: def remember_session_route(self, session_metadata: dict[str, Any]) -> None:
"""Keep only routing fields needed to deliver a later idle notification.""" """Keep only routing fields needed to deliver a later idle notification."""
if is_internal_session(self.session_key): 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 session_key_override: str | None = None # Optional override for thread-scoped sessions
require_existing_session: bool = False require_existing_session: bool = False
input_role: Literal["user", "system"] | None = None input_role: Literal["user", "system"] | None = None
session_generation: str | None = None # Trusted identity assigned at session admission
@property @property
def session_key(self) -> str: def session_key(self) -> str:
+8
View File
@@ -23,6 +23,7 @@ class RuntimeEventContext:
session_key: str session_key: str
metadata: dict[str, Any] = field(default_factory=dict) metadata: dict[str, Any] = field(default_factory=dict)
attributes: dict[str, Any] = field(default_factory=dict) attributes: dict[str, Any] = field(default_factory=dict)
session_generation: str | None = None
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -128,11 +129,13 @@ class RuntimeEventPublisher:
session_key: str, session_key: str,
metadata: dict[str, Any] | None, metadata: dict[str, Any] | None,
attributes: dict[str, Any] | None = None, attributes: dict[str, Any] | None = None,
session_generation: str | None = None,
) -> RuntimeEventContext: ) -> RuntimeEventContext:
return RuntimeEventContext( return RuntimeEventContext(
channel=channel, channel=channel,
chat_id=chat_id, chat_id=chat_id,
session_key=session_key, session_key=session_key,
session_generation=session_generation,
metadata=dict(metadata or {}), metadata=dict(metadata or {}),
attributes=dict(attributes or {}), attributes=dict(attributes or {}),
) )
@@ -180,6 +183,7 @@ class RuntimeEventPublisher:
chat_id=msg.chat_id, chat_id=msg.chat_id,
session_key=session_key, session_key=session_key,
metadata=msg.metadata, metadata=msg.metadata,
session_generation=msg.session_generation,
), ),
content=msg.content, content=msg.content,
) )
@@ -197,6 +201,7 @@ class RuntimeEventPublisher:
chat_id=msg.chat_id, chat_id=msg.chat_id,
session_key=session_key, session_key=session_key,
metadata=msg.metadata, metadata=msg.metadata,
session_generation=msg.session_generation,
), ),
) )
) )
@@ -216,6 +221,7 @@ class RuntimeEventPublisher:
chat_id=msg.chat_id, chat_id=msg.chat_id,
session_key=session_key, session_key=session_key,
metadata=msg.metadata, metadata=msg.metadata,
session_generation=msg.session_generation,
), ),
runtime=runtime, runtime=runtime,
) )
@@ -236,6 +242,7 @@ class RuntimeEventPublisher:
chat_id=msg.chat_id, chat_id=msg.chat_id,
session_key=session_key, session_key=session_key,
metadata=msg.metadata, metadata=msg.metadata,
session_generation=msg.session_generation,
), ),
status=status, status=status,
started_at=started_at, started_at=started_at,
@@ -257,6 +264,7 @@ class RuntimeEventPublisher:
chat_id=msg.chat_id, chat_id=msg.chat_id,
session_key=session_key, session_key=session_key,
metadata=msg.metadata, metadata=msg.metadata,
session_generation=msg.session_generation,
attributes=attributes, attributes=attributes,
), ),
turn_id=turn_id, turn_id=turn_id,
+2
View File
@@ -265,6 +265,7 @@ class BaseChannel(ABC):
is_dm: bool = False, is_dm: bool = False,
authorization_id: str | None = None, authorization_id: str | None = None,
require_existing_session: bool = False, require_existing_session: bool = False,
session_generation: str | None = None,
) -> None: ) -> None:
"""Handle a message after checking its authorization subject. """Handle a message after checking its authorization subject.
@@ -323,6 +324,7 @@ class BaseChannel(ABC):
media=media or [], media=media or [],
metadata=meta, metadata=meta,
session_key_override=session_key, session_key_override=session_key,
session_generation=session_generation,
require_existing_session=require_existing_session, require_existing_session=require_existing_session,
) )
+1
View File
@@ -202,6 +202,7 @@ class ChannelManager:
static_dist_path=static_path, static_dist_path=static_path,
workspace_path=workspace, workspace_path=workspace,
default_restrict_to_workspace=self.config.tools.restrict_to_workspace, default_restrict_to_workspace=self.config.tools.restrict_to_workspace,
unified_session=self.config.agents.defaults.unified_session,
config_path=self._config_path, config_path=self._config_path,
disabled_skills=set(self.config.agents.defaults.disabled_skills), disabled_skills=set(self.config.agents.defaults.disabled_skills),
runtime_model_name=self._webui_runtime_model_name, runtime_model_name=self._webui_runtime_model_name,
+2
View File
@@ -432,6 +432,7 @@ class SignalChannel(BaseChannel):
is_dm: bool = False, is_dm: bool = False,
authorization_id: str | None = None, authorization_id: str | None = None,
require_existing_session: bool = False, require_existing_session: bool = False,
session_generation: str | None = None,
) -> None: ) -> None:
"""Handle an inbound message whose policy has already been checked. """Handle an inbound message whose policy has already been checked.
@@ -454,6 +455,7 @@ class SignalChannel(BaseChannel):
media=media or [], media=media or [],
metadata=meta, metadata=meta,
session_key_override=session_key, session_key_override=session_key,
session_generation=session_generation,
require_existing_session=require_existing_session, require_existing_session=require_existing_session,
) )
) )
+2
View File
@@ -459,6 +459,7 @@ class WebSocketChannel(BaseChannel):
is_dm: bool, is_dm: bool,
session_key: str | None, session_key: str | None,
require_existing_session: bool, require_existing_session: bool,
session_generation: str | None,
) -> None: ) -> None:
await self._handle_message( await self._handle_message(
sender_id=sender_id, sender_id=sender_id,
@@ -469,6 +470,7 @@ class WebSocketChannel(BaseChannel):
is_dm=is_dm, is_dm=is_dm,
session_key=session_key, session_key=session_key,
require_existing_session=require_existing_session, require_existing_session=require_existing_session,
session_generation=session_generation,
) )
def _attach(self, connection: ServerConnection, chat_id: str) -> None: def _attach(self, connection: ServerConnection, chat_id: str) -> None:
@@ -2,6 +2,7 @@
import asyncio import asyncio
import json import json
import threading
import time import time
import uuid import uuid
from pathlib import Path 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.runtime_context import RUNTIME_CONTEXT_INPUT_META, WEBUI_QUOTE_SOURCE
from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY
from nanobot.session import webui_turns as wth 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.model_selection import SESSION_MODEL_PRESET_METADATA_KEY
from nanobot.session.session_handles import session_handle_for_name from nanobot.session.session_handles import session_handle_for_name
from nanobot.webui.gateway_services import GatewayServices, build_gateway_services 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", "chat-running",
channel.gateway.workspaces.scope_for_session_key("websocket: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 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 @pytest.mark.asyncio
async def test_stream_transcript_writes_once_per_completed_segment(monkeypatch) -> None: async def test_stream_transcript_writes_once_per_completed_segment(monkeypatch) -> None:
bus = MagicMock() 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: async def test_hydrate_skips_when_no_goal_on_disk() -> None:
bus = MagicMock() bus = MagicMock()
sm = MagicMock() sm = MagicMock()
sm.read_session_metadata.return_value = None sm.state.read_metadata = AsyncMock()
sm.state.read_metadata.return_value = None
channel = WebSocketChannel( channel = WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]}, {"enabled": True, "allowFrom": ["*"]},
bus, 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: async def test_hydrate_notifies_when_goal_active_on_disk() -> None:
bus = MagicMock() bus = MagicMock()
sm = MagicMock() sm = MagicMock()
sm.read_session_metadata.return_value = { sm.state.read_metadata = AsyncMock()
sm.state.read_metadata.return_value = {
"metadata": { "metadata": {
"goal_state": { "goal_state": {
"status": "active", "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: async def test_hydrate_restores_blocked_attention_on_disk() -> None:
bus = MagicMock() bus = MagicMock()
sm = MagicMock() sm = MagicMock()
sm.read_session_metadata.return_value = { sm.state.read_metadata = AsyncMock()
sm.state.read_metadata.return_value = {
"metadata": { "metadata": {
"goal_state": { "goal_state": {
"status": "blocked", "status": "blocked",
@@ -5692,13 +5746,17 @@ def test_sessions_list_includes_active_run_started_at(monkeypatch) -> None:
"updated_at": "2026-05-19T10:01:00Z", "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") handle = session_handle_for_name("websocket:chat-1", "luma")
monkeypatch.setattr( monkeypatch.setattr(
ws_http_module, ws_http_module,
"SessionHandleResolver", "SessionHandleResolver",
lambda _session_manager: SimpleNamespace( 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( 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( assert channel.gateway.workspaces.scope_for_session_key(
"websocket:handshake-scope" "websocket:handshake-scope"
).access_mode == mode ).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() channel._handle_message.assert_awaited_once()
metadata = channel._handle_message.call_args.kwargs["metadata"] 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 handle is not None
assert metadata["session_mentions"] == [{ assert metadata["session_mentions"] == [{
**handle.public_payload(), **handle.public_payload(),
@@ -313,7 +313,7 @@ async def test_sessions_list_and_thread_restore_transcript_without_canonical_fil
key, key,
{"event": "message", "chat_id": "restored-history", "text": "original answer"}, {"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() port = _free_port()
channel = _ch(bus, session_manager=sm, port=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 question",
"original answer", "original answer",
] ]
assert not sm._get_session_path(key).exists() assert sm.read_session_snapshot(key) is None
finally: finally:
await channel.stop() await channel.stop()
await server_task 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} rows = {row["key"]: row for row in sessions}
handles = { handles = {
handle.session_key: handle 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[ assert rows["websocket:alpha"]["handle"] == handles[
"websocket:alpha" "websocket:alpha"
@@ -2385,8 +2385,8 @@ async def test_session_delete_removes_file(
channel = _ch(bus, session_manager=sm, port=29903) channel = _ch(bus, session_manager=sm, port=29903)
server_task = asyncio.create_task(channel.start()) server_task = asyncio.create_task(channel.start())
try: try:
path = sm._get_session_path("websocket:doomed") session_key = "websocket:doomed"
assert path.exists() assert sm.read_session_snapshot(session_key) is not None
webui_path = tmp_path / "webui" / f"{SessionManager.safe_key('websocket:doomed')}.jsonl" webui_path = tmp_path / "webui" / f"{SessionManager.safe_key('websocket:doomed')}.jsonl"
assert webui_path.is_file() assert webui_path.is_file()
resp = await _webui_mutate( resp = await _webui_mutate(
@@ -2396,7 +2396,7 @@ async def test_session_delete_removes_file(
) )
assert resp.status_code == 200 assert resp.status_code == 200
assert resp.json()["deleted"] is True assert resp.json()["deleted"] is True
assert not path.exists() assert sm.read_session_snapshot(session_key) is None
assert not webui_path.exists() assert not webui_path.exists()
finally: finally:
await channel.stop() await channel.stop()
@@ -2416,7 +2416,7 @@ async def test_session_delete_removes_transcript_without_canonical_file(
key, key,
{"event": "user", "chat_id": "transcript-only", "text": "recover me"}, {"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" webui_path = tmp_path / "webui" / f"{SessionManager.safe_key(key)}.jsonl"
assert webui_path.is_file() 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) channel = _ch(bus, session_manager=sm, cron_service=cron, port=29915)
server_task = asyncio.create_task(channel.start()) server_task = asyncio.create_task(channel.start())
try: try:
path = sm._get_session_path("websocket:doomed") session_key = "websocket:doomed"
resp = await _webui_mutate( resp = await _webui_mutate(
channel, channel,
"session.delete", "session.delete",
@@ -3010,7 +3010,7 @@ async def test_session_delete_blocks_when_bound_automation_exists(
assert body["deleted"] is False assert body["deleted"] is False
assert body["blocked_by_automations"] is True assert body["blocked_by_automations"] is True
assert [job["name"] for job in body["automations"]] == ["Daily check"] 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") assert cron.list_bound_cron_jobs_for_session("websocket:doomed")
finally: finally:
await channel.stop() 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) channel = _ch(bus, session_manager=sm, cron_service=cron, port=29916)
server_task = asyncio.create_task(channel.start()) server_task = asyncio.create_task(channel.start())
try: try:
path = sm._get_session_path("websocket:doomed") session_key = "websocket:doomed"
resp = await _webui_mutate( resp = await _webui_mutate(
channel, channel,
"session.delete", "session.delete",
@@ -3095,7 +3095,7 @@ async def test_session_delete_can_cascade_bound_automations(
assert resp.status_code == 200 assert resp.status_code == 200
assert resp.json()["deleted"] is True 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_bound_cron_jobs_for_session("websocket:doomed") == []
assert cron.list_jobs(include_disabled=True) == [] assert cron.list_jobs(include_disabled=True) == []
finally: finally:
@@ -3126,7 +3126,7 @@ async def test_session_delete_blocks_origin_automation_when_unified_enabled(
) )
server_task = asyncio.create_task(channel.start()) server_task = asyncio.create_task(channel.start())
try: try:
path = sm._get_session_path("websocket:doomed") session_key = "websocket:doomed"
resp = await _webui_mutate( resp = await _webui_mutate(
channel, channel,
"session.delete", "session.delete",
@@ -3138,7 +3138,7 @@ async def test_session_delete_blocks_origin_automation_when_unified_enabled(
assert body["deleted"] is False assert body["deleted"] is False
assert body["blocked_by_automations"] is True assert body["blocked_by_automations"] is True
assert [job["name"] for job in body["automations"]] == ["Chat daily check"] 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")] == [ assert [job.name for job in cron.list_bound_cron_jobs_for_session("websocket:doomed")] == [
"Chat daily check" "Chat daily check"
] ]
@@ -3155,8 +3155,8 @@ async def test_session_delete_action_accepts_websocket_keys(
channel = _ch(bus, session_manager=sm, port=29910) channel = _ch(bus, session_manager=sm, port=29910)
server_task = asyncio.create_task(channel.start()) server_task = asyncio.create_task(channel.start())
try: try:
path = sm._get_session_path("websocket:encoded-key") session_key = "websocket:encoded-key"
assert path.exists() assert sm.read_session_snapshot(session_key) is not None
deleted = await _webui_mutate( deleted = await _webui_mutate(
channel, channel,
"session.delete", "session.delete",
@@ -3164,7 +3164,7 @@ async def test_session_delete_action_accepts_websocket_keys(
) )
assert deleted.status_code == 200 assert deleted.status_code == 200
assert deleted.json()["deleted"] is True assert deleted.json()["deleted"] is True
assert not path.exists() assert sm.read_session_snapshot(session_key) is None
finally: finally:
await channel.stop() await channel.stop()
await server_task await server_task
@@ -3511,8 +3511,8 @@ async def test_session_delete_rejects_non_websocket_keys(
token = channel.gateway.tokens.issue_api_token(300) token = channel.gateway.tokens.issue_api_token(300)
auth = {"Authorization": f"Bearer {token}"} auth = {"Authorization": f"Bearer {token}"}
doomed = sm._get_session_path("slack:C123") session_key = "slack:C123"
assert doomed.exists() assert sm.read_session_snapshot(session_key) is not None
get_delete = await _http_get( get_delete = await _http_get(
"http://127.0.0.1:29909/api/sessions/slack:C123/delete", "http://127.0.0.1:29909/api/sessions/slack:C123/delete",
headers=auth, headers=auth,
@@ -3525,7 +3525,7 @@ async def test_session_delete_rejects_non_websocket_keys(
{"key": "slack:C123"}, {"key": "slack:C123"},
) )
assert deny_delete.status_code == 404 assert deny_delete.status_code == 404
assert doomed.exists() assert sm.read_session_snapshot(session_key) is not None
finally: finally:
await channel.stop() await channel.stop()
await server_task 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) response = await _webui_mutate(channel, "workspace.favorite", {"path": str(project), "pinned": False}, connection=connection)
assert response.status_code == 200 assert response.status_code == 200
assert response.json() == {"favorite_projects": []} 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.""" """Test websocket subscribe hydration only replays known active turns."""
from unittest.mock import MagicMock, patch from unittest.mock import AsyncMock, MagicMock, patch
import pytest import pytest
@@ -15,7 +15,7 @@ async def test_hydrate_after_subscribe_is_quiet_when_no_turn_active():
channel = WebSocketChannel.__new__(WebSocketChannel) channel = WebSocketChannel.__new__(WebSocketChannel)
channel.gateway = MagicMock() channel.gateway = MagicMock()
channel.gateway.session_manager = 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._session_projection = WebUISessionProjection(channel.gateway.session_manager)
channel._outbound = WebUIOutboundProjector(channel, channel._session_projection) channel._outbound = WebUIOutboundProjector(channel, channel._session_projection)
channel._turn_models = {} channel._turn_models = {}
@@ -43,7 +43,7 @@ async def test_hydrate_after_subscribe_pushes_running_when_turn_active():
channel = WebSocketChannel.__new__(WebSocketChannel) channel = WebSocketChannel.__new__(WebSocketChannel)
channel.gateway = MagicMock() channel.gateway = MagicMock()
channel.gateway.session_manager = 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._session_projection = WebUISessionProjection(channel.gateway.session_manager)
channel._outbound = WebUIOutboundProjector(channel, channel._session_projection) channel._outbound = WebUIOutboundProjector(channel, channel._session_projection)
channel._turn_models = {} 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) 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 # Channel Commands
# ============================================================================ # ============================================================================
+70 -50
View File
@@ -4,6 +4,8 @@ import asyncio
import signal import signal
from collections.abc import Awaitable, Callable, Coroutine, Iterable from collections.abc import Awaitable, Callable, Coroutine, Iterable
from contextlib import suppress from contextlib import suppress
from dataclasses import replace
from functools import partial
from pathlib import Path from pathlib import Path
from typing import Any, cast 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.mcp import MCPProvider
from nanobot.agent.tools.registry import ToolRegistry 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 import terminal as cli_terminal
from nanobot.cli.runtime_config import _migrate_cron_store from nanobot.cli.runtime_config import _migrate_cron_store
from nanobot.cli.webui_support import ( from nanobot.cli.webui_support import (
@@ -44,7 +48,9 @@ from nanobot.session.keys import (
HEARTBEAT_SESSION_KEY, HEARTBEAT_SESSION_KEY,
UNIFIED_SESSION_KEY, UNIFIED_SESSION_KEY,
last_channel_from_metadata, 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.evaluator import evaluate_response, resolve_evaluator_prompt
from nanobot.utils.helpers import sync_workspace_templates from nanobot.utils.helpers import sync_workspace_templates
from nanobot.utils.token_encoding import warmup_token_encoding from nanobot.utils.token_encoding import warmup_token_encoding
@@ -57,6 +63,48 @@ __all__ = ["_run_gateway"]
console = Console() 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): class _MCPReadinessHook(AgentHook):
"""Retry application-owned MCP connections before the runner reads tools.""" """Retry application-owned MCP connections before the runner reads tools."""
@@ -519,9 +567,6 @@ def _run_gateway(
schedule_background=_schedule_webui_background, schedule_background=_schedule_webui_background,
recovery=recovery, 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: def _channel_session_key(channel: str, chat_id: str) -> str:
return session_key_for_channel( return session_key_for_channel(
channel, channel,
@@ -529,41 +574,16 @@ def _run_gateway(
unified_session=config.agents.defaults.unified_session, unified_session=config.agents.defaults.unified_session,
) )
async def _deliver_to_channel( deliver_to_channel = partial(
msg: OutboundMessage, *, record: bool = False, session_key: str | None = None, _deliver_to_channel,
) -> None: bus=bus,
"""Publish a user-visible message and mirror it into that channel's session.""" session_manager=session_manager,
metadata = dict(msg.metadata or {}) unified_session=config.agents.defaults.unified_session,
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)
message_tool = agent.tools.get("message") message_tool = agent.tools.get("message")
if isinstance(message_tool, MessageTool): 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) # Set cron callback (needs agent)
async def on_cron_job(job: CronJob) -> str | CronRunResult | None: async def on_cron_job(job: CronJob) -> str | CronRunResult | None:
@@ -576,7 +596,6 @@ def _run_gateway(
from nanobot.agent.memory import MemoryStore from nanobot.agent.memory import MemoryStore
dream_session_key = MemoryStore.dream_session_key dream_session_key = MemoryStore.dream_session_key
prune_dream_sessions = MemoryStore.prune_dream_sessions
store = agent.context.memory store = agent.context.memory
resp = None resp = None
@@ -628,7 +647,7 @@ def _run_gateway(
if sha: if sha:
logger.info("Dream commit: {}", sha) logger.info("Dream commit: {}", sha)
store.compact_history() store.compact_history()
prune_dream_sessions(agent.sessions) await agent.sessions.state.prune_dream_sessions()
return None return None
# Heartbeat is a system job that checks HEARTBEAT.md for active tasks. # 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") logger.debug("Heartbeat: HEARTBEAT.md has no active tasks")
return None return None
channel, chat_id = _pick_heartbeat_target() channel, chat_id = await _pick_heartbeat_target()
if channel == "cli": if channel == "cli":
return None 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 = ( prompt = (
_HEARTBEAT_PREAMBLE _HEARTBEAT_PREAMBLE
@@ -690,9 +714,11 @@ def _run_gateway(
if should_notify: if should_notify:
logger.info("Heartbeat: completed, delivering response") logger.info("Heartbeat: completed, delivering response")
await _deliver_to_channel( await deliver_to_channel(
OutboundMessage(channel=channel, chat_id=chat_id, content=response), OutboundMessage(channel=channel, chat_id=chat_id, content=response),
record=True, record=True,
session_key=delivery_key,
session_generation=delivery_generation,
) )
else: else:
logger.info("Heartbeat: silenced by post-run evaluation") logger.info("Heartbeat: silenced by post-run evaluation")
@@ -755,17 +781,17 @@ def _run_gateway(
config_path=Path(config_path), 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.""" """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 unified_metadata = None
if config.agents.defaults.unified_session: 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): if isinstance(record, dict) and isinstance(record.get("metadata"), dict):
unified_metadata = record["metadata"] unified_metadata = record["metadata"]
return _pick_heartbeat_target_from_sessions( return _pick_heartbeat_target_from_sessions(
enabled_channels=channels.enabled_channels, enabled_channels=channels.enabled_channels,
sessions=session_manager.list_sessions(), sessions=await session_manager.state.list_sessions(),
archived_keys=sidebar_state.get("archived_keys", []), archived_keys=sidebar_state.get("archived_keys", []),
unified_session_metadata=unified_metadata, unified_session_metadata=unified_metadata,
) )
@@ -930,6 +956,7 @@ def _run_gateway(
console.print, console.print,
) )
try: try:
await agent.subagents.recover_interrupted()
await cron.start() await cron.start()
# Re-read once on first admission to close the watcher subscription window. # Re-read once on first admission to close the watcher subscription window.
agent.runtime_resolver.invalidate() agent.runtime_resolver.invalidate()
@@ -1039,12 +1066,6 @@ def _run_gateway(
runtime_tasks, runtime_tasks,
) )
await bus.drain() 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: finally:
restore_shutdown_handlers() restore_shutdown_handlers()
@@ -1052,7 +1073,6 @@ def _run_gateway(
gateway_runtime.foreground_instance(gateway_start_options), gateway_runtime.foreground_instance(gateway_start_options),
webui_turn_coordinator.connected(), webui_turn_coordinator.connected(),
): ):
agent.subagents.recover_interrupted()
if health_server_enabled: if health_server_enabled:
gateway_runtime.publish_health_host(config.gateway.host) gateway_runtime.publish_health_host(config.gateway.host)
asyncio.run(run()) 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.command.router import CommandContext, CommandRouter, normalize_command_text
from nanobot.providers.base import LLMUsage from nanobot.providers.base import LLMUsage
from nanobot.session.history_visibility import HIDDEN_HISTORY_META 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.helpers import build_status_content
from nanobot.utils.restart import set_restart_notice_to_env from nanobot.utils.restart import set_restart_notice_to_env
from nanobot.utils.workspace_prompts import initialize_workspace_prompt 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: async def cmd_status(ctx: CommandContext) -> OutboundMessage:
"""Build an outbound status message for a session.""" """Build an outbound status message for a session."""
loop = ctx.loop loop = ctx.loop
session = ctx.session or loop.sessions.get_or_create(ctx.key) session = ctx.session or await loop.sessions.state.get(ctx.key)
runtime = ctx.runtime or loop.runtime_for_session(session) runtime = ctx.runtime or await loop.runtime_for_session(session)
ctx_est = 0 ctx_est = 0
with suppress(Exception): with suppress(Exception):
ctx_est, _ = loop.consolidator.estimate_session_prompt_tokens( ctx_est, _ = loop.consolidator.estimate_session_prompt_tokens(
@@ -316,29 +317,30 @@ async def cmd_new(ctx: CommandContext) -> OutboundMessage:
loop = ctx.loop loop = ctx.loop
await loop._cancel_active_tasks(ctx.key) # pyright: ignore[reportPrivateUsage] await loop._cancel_active_tasks(ctx.key) # pyright: ignore[reportPrivateUsage]
loop.discard_session_file_state(ctx.key) 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) snapshot = list(session.messages)
archive_snapshot = None archive_snapshot = None
runtime = None runtime = None
if session.last_archived < len(snapshot): 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( archive_snapshot = replace(
session, session,
messages=snapshot, messages=snapshot,
metadata=dict(session.metadata), metadata=dict(session.metadata),
provider_state=None, provider_state=None,
) )
session.clear() async def reset_and_schedule_archive() -> None:
loop.sessions.save(session) await loop.sessions.state.reset(session.key)
loop.sessions.invalidate(session.key) if archive_snapshot is not None and runtime is not None:
if archive_snapshot is not None and runtime is not None: loop.schedule_background(
loop.schedule_background( loop.consolidator.archive_session( # pyright: ignore[reportUnknownMemberType]
loop.consolidator.archive_session( # pyright: ignore[reportUnknownMemberType] archive_snapshot,
archive_snapshot, archive_end=len(snapshot),
archive_end=len(snapshot), runtime=runtime,
runtime=runtime, )
) )
)
await shield_and_drain(reset_and_schedule_archive())
return OutboundMessage( return OutboundMessage(
channel=ctx.msg.channel, chat_id=ctx.msg.chat_id, channel=ctx.msg.channel, chat_id=ctx.msg.chat_id,
content="New session started.", content="New session started.",
@@ -349,12 +351,12 @@ async def cmd_new(ctx: CommandContext) -> OutboundMessage:
async def cmd_compact(ctx: CommandContext) -> None: async def cmd_compact(ctx: CommandContext) -> None:
"""Compact the current session without resetting the conversation.""" """Compact the current session without resetting the conversation."""
loop = ctx.loop loop = ctx.loop
session = ctx.session or loop.sessions.get_or_create(ctx.key) session = ctx.session or await loop.sessions.state.get(ctx.key)
runtime = ctx.runtime or loop.runtime_for_session(session) runtime = ctx.runtime or await loop.runtime_for_session(session)
delivery = loop.turn_delivery_factory.create(ctx.msg, ctx.key) delivery = loop.turn_delivery_factory.create(ctx.msg, ctx.key)
try: try:
summary = await loop.consolidator.compact_idle_session( await loop.consolidator.compact_idle_session(
ctx.key, ctx.key,
runtime=runtime, runtime=runtime,
events=delivery.events, events=delivery.events,
@@ -364,10 +366,6 @@ async def cmd_compact(ctx: CommandContext) -> None:
logger.exception("Manual context compaction failed for {}", ctx.key) logger.exception("Manual context compaction failed for {}", ctx.key)
return 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: 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) 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) names = _model_preset_names(loop)
try: 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: except (KeyError, ValueError) as exc:
return "\n".join([ return "\n".join([
"## Model", "## Model",
@@ -411,17 +409,17 @@ async def cmd_model(ctx: CommandContext) -> OutboundMessage:
metadata = {**dict(ctx.msg.metadata or {}), "render_as": "text"} metadata = {**dict(ctx.msg.metadata or {}), "render_as": "text"}
if not args: 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( return OutboundMessage(
channel=ctx.msg.channel, channel=ctx.msg.channel,
chat_id=ctx.msg.chat_id, chat_id=ctx.msg.chat_id,
content=_model_command_status(loop, session), content=await _model_command_status(loop, session),
metadata=metadata, metadata=metadata,
) )
name = args name = args
try: 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: except (KeyError, ValueError) as exc:
names = _model_preset_names(loop) names = _model_preset_names(loop)
return OutboundMessage( return OutboundMessage(
@@ -465,7 +463,6 @@ async def cmd_dream(ctx: CommandContext) -> OutboundMessage:
dream_session_key = MemoryStore.dream_session_key dream_session_key = MemoryStore.dream_session_key
build_dream_commit_message = MemoryStore.build_dream_commit_message build_dream_commit_message = MemoryStore.build_dream_commit_message
prune_dream_sessions = MemoryStore.prune_dream_sessions
store = loop.context.memory store = loop.context.memory
content = "" content = ""
@@ -519,7 +516,7 @@ async def cmd_dream(ctx: CommandContext) -> OutboundMessage:
if sha: if sha:
content += f" (commit {sha})" content += f" (commit {sha})"
store.compact_history() store.compact_history()
prune_dream_sessions(loop.sessions) await loop.sessions.state.prune_dream_sessions()
await loop.bus.publish_outbound(OutboundMessage( await loop.bus.publish_outbound(OutboundMessage(
channel=msg.channel, chat_id=msg.chat_id, content=content, 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 {}), 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) history = session.get_history(max_messages=0, include_runtime_context=False)
visible = [_format_history_message(m) for m in history] visible = [_format_history_message(m) for m in history]
visible = [m for m in visible if m is not None] 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"}, 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)) 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( return replace(
ctx.msg, ctx.msg,
content=goal, 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 ( from nanobot.sdk.types import (
SessionInfo, SessionInfo,
SessionSnapshot, SessionSnapshot,
snapshot_from_payload,
snapshot_from_session, snapshot_from_session,
) )
@@ -21,138 +20,76 @@ if TYPE_CHECKING:
class SessionClient: class SessionClient:
"""Session management helpers exposed through ``bot.sessions``.""" """Asynchronous operations over committed session state."""
_RESERVED_MESSAGE_KEYS = {"role", "content", RUNTIME_CONTEXT_HISTORY_META}
_VALID_ROLES = {"user", "assistant", "tool", "system"}
def __init__(self, loop: AgentLoop) -> None: def __init__(self, loop: AgentLoop) -> None:
self._loop = loop self._loop = loop
self._state = loop.sessions.state
async def ingest( async def ingest(
self, self, session_key: str, messages: Iterable[Mapping[str, Any]], *,
session_key: str, metadata: Mapping[str, Any] | None = None, source: str | None = None,
messages: Iterable[Mapping[str, Any]],
*,
metadata: Mapping[str, Any] | None = None,
source: str | None = None,
save: bool = True,
) -> SessionSnapshot: ) -> SessionSnapshot:
"""Import an existing transcript without running the model.""" """Validate and durably import a transcript as one operation."""
prepared_metadata = deepcopy(dict(metadata)) if metadata else {} prepared: list[dict[str, Any]] = []
prepared: list[tuple[str, Any, dict[str, Any]]] = []
for raw in messages: for raw in messages:
if "role" not in raw: if "role" not in raw or "content" not in raw:
raise ValueError("ingested messages must include a role") raise ValueError("ingested messages must include role and content")
if "content" not in raw: message = {
raise ValueError("ingested messages must include content") key: deepcopy(value) for key, value in raw.items()
role = str(raw["role"]).strip() if key != RUNTIME_CONTEXT_HISTORY_META
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 source is not None and "source" not in extra: message["role"] = str(raw["role"]).strip()
extra["source"] = source if source is not None:
prepared.append((role, deepcopy(raw["content"]), extra)) message.setdefault("source", source)
prepared.append(message)
session = self._loop.sessions.get_or_create(session_key) session = await self._state.import_messages(session_key, prepared, metadata=metadata)
session.metadata.update(prepared_metadata)
for role, content, extra in prepared:
session.add_message(role, content, **extra)
if save:
self._loop.sessions.save(session)
return snapshot_from_session(session) return snapshot_from_session(session)
def get(self, session_key: str) -> SessionSnapshot | None: async def get(self, session_key: str) -> SessionSnapshot | None:
"""Return a display-safe snapshot without creating a new session on disk.""" """Return a detached display-safe view of committed state."""
cached = self._loop.sessions.get_cached(session_key) session = await self._state.read(session_key)
if cached is not None: return snapshot_from_session(session) if session is not None else 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)
def list(self) -> list[SessionInfo]: async def list(self) -> list[SessionInfo]:
"""List persisted sessions."""
return [ return [
SessionInfo( SessionInfo(
key=str(row.get("key") or ""), key=str(row.get("key") or ""),
created_at=row.get("created_at"), created_at=row.get("created_at"), updated_at=row.get("updated_at"),
updated_at=row.get("updated_at"), title=str(row.get("title") or ""), preview=str(row.get("preview") or ""),
title=str(row.get("title") or ""),
preview=str(row.get("preview") or ""),
path=row.get("path"), 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: async def export(self, session_key: str) -> SessionSnapshot | None:
"""Return a trusted full snapshot, including model-only runtime context.""" """Return a trusted detached snapshot including model-only context."""
cached = self._loop.sessions.get_cached(session_key) session = await self._state.read(session_key)
if cached is not None: return (
return snapshot_from_session(cached, include_runtime_context=True) snapshot_from_session(session, include_runtime_context=True)
payload = self._loop.sessions.read_session_file(session_key) if session is not None else None
if payload is None: )
return None
return snapshot_from_payload(payload, include_runtime_context=True)
async def restore( async def restore(
self, self, snapshot: SessionSnapshot, *, session_key: str | None = None,
snapshot: SessionSnapshot,
*,
session_key: str | None = None,
save: bool = True,
) -> SessionSnapshot: ) -> SessionSnapshot:
"""Restore a trusted snapshot into an empty session.""" """Atomically restore a trusted snapshot into an empty session."""
key = session_key or snapshot.key key = session_key or snapshot.key
if not key: if not key:
raise ValueError("restored snapshots must include a session key") raise ValueError("restored snapshots must include a session key")
session = self._loop.sessions.get_or_create(key) session = await self._state.import_messages(
if session.messages: key, snapshot.messages, metadata=snapshot.metadata, require_empty=True,
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)
return snapshot_from_session(session) return snapshot_from_session(session)
def clear(self, session_key: str) -> SessionSnapshot: async def clear(self, session_key: str) -> SessionSnapshot:
"""Clear one session and persist the empty session.""" """Reset state and invalidate results from an older execution."""
await self._state.reset(session_key)
self._loop.discard_session_file_state(session_key) self._loop.discard_session_file_state(session_key)
session = self._loop.sessions.get_or_create(session_key) return snapshot_from_session(await self._state.get(session_key))
session.clear()
self._loop.sessions.save(session)
return snapshot_from_session(session)
def delete(self, session_key: str) -> bool: async def delete(self, session_key: str) -> bool:
"""Delete one session from disk and cache.""" return await self._state.delete(session_key)
return self._loop.sessions.delete_session(session_key)
def flush(self) -> int:
"""Flush cached sessions to durable storage."""
return self._loop.sessions.flush_all()
class MemoryClient: class MemoryClient:
@@ -214,19 +151,21 @@ class RuntimeClient:
async def compact_session(self, session_key: str) -> SessionSnapshot: async def compact_session(self, session_key: str) -> SessionSnapshot:
"""Summarize one session and exclude its archived messages from replay.""" """Summarize one session and exclude its archived messages from replay."""
async with self._loop._get_session_lock(session_key): # pyright: ignore[reportPrivateUsage] async with self._loop._get_session_lock(session_key): # pyright: ignore[reportPrivateUsage]
session = self._loop.sessions.get_or_create(session_key) session = await self._loop.sessions.state.get(session_key)
runtime = self._loop.runtime_for_session(session) runtime = await self._loop.runtime_for_session(session)
await self._loop.consolidator.compact_idle_session( await self._loop.consolidator.compact_idle_session(
session_key, session_key,
runtime=runtime, 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: 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.""" """Return a replacement summary; legacy ``max_suffix`` no longer retains history."""
async with self._loop._get_session_lock(session_key): # pyright: ignore[reportPrivateUsage] async with self._loop._get_session_lock(session_key): # pyright: ignore[reportPrivateUsage]
session = self._loop.sessions.get_or_create(session_key) session = await self._loop.sessions.state.get(session_key)
runtime = self._loop.runtime_for_session(session) runtime = await self._loop.runtime_for_session(session)
return await self._loop.consolidator.compact_idle_session( return await self._loop.consolidator.compact_idle_session(
session_key, session_key,
runtime=runtime, runtime=runtime,
+13 -2
View File
@@ -163,6 +163,17 @@ def workspace_sandbox_status(
"""Return how workspace restriction is enforced in the current host.""" """Return how workspace restriction is enforced in the current host."""
workspace_root = str(Path(workspace).expanduser().resolve(strict=False)) 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) provider = _env_system_provider(environ)
if not restrict_to_workspace: if not restrict_to_workspace:
return WorkspaceSandboxStatus( return WorkspaceSandboxStatus(
@@ -215,9 +226,9 @@ def build_workspace_scope(
project_path=root, project_path=root,
access_mode=mode, access_mode=mode,
restrict_to_workspace=restrict, restrict_to_workspace=restrict,
sandbox_status=workspace_sandbox_status( sandbox_status=_workspace_sandbox_status(
restrict_to_workspace=restrict, restrict_to_workspace=restrict,
workspace=root, workspace_root=str(root),
), ),
source_channel=source_channel, 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 typing import Any, TypedDict, cast
from nanobot.session.manager import SessionManager from nanobot.session.manager import SessionManager
from nanobot.session.types import SessionTypes
SESSION_HANDLE_METADATA_KEY = "session_handle" SESSION_HANDLE_METADATA_KEY = "session_handle"
@@ -128,7 +129,7 @@ def _candidate_indexes(syllable_count: int):
yield (start + offset * step) % size 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 syllable_count in _SYLLABLE_COUNTS:
for index in _candidate_indexes(syllable_count): for index in _candidate_indexes(syllable_count):
parts = _name_parts_at(syllable_count, index) parts = _name_parts_at(syllable_count, index)
@@ -143,6 +144,51 @@ def _allocate_name(used: set[str]) -> str:
return name 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: class SessionHandleResolver:
"""Allocate and resolve handles stored in canonical session metadata.""" """Allocate and resolve handles stored in canonical session metadata."""
@@ -150,71 +196,65 @@ class SessionHandleResolver:
self._sessions = sessions self._sessions = sessions
def _ensure_all(self) -> dict[str, SessionHandle]: def _ensure_all(self) -> dict[str, SessionHandle]:
with self._sessions.locked_session_files(): names = self._sessions.ensure_session_handles_offline()
rows = sorted( return {
self._sessions.list_sessions(), key: session_handle_for_name(key, name)
key=lambda row: ( for key, name in names.items()
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)
for key in pending: async def _ensure_all_async(self) -> dict[str, SessionHandle]:
name = _allocate_name(used) names = await self._sessions.state.ensure_session_handles()
if not self._sessions.update_session_metadata( return {
key, key: session_handle_for_name(key, name)
{SESSION_HANDLE_METADATA_KEY: name}, for key, name in names.items()
fsync=True, }
):
continue
names[key] = name
used.add(name)
return { def handles_from_metadata(
key: session_handle_for_name(key, name) self, rows: list[dict[str, Any]],
for key, name in names.items() ) -> 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: def handle_for_session(self, session_key: str) -> SessionHandle | None:
"""Offline compatibility API; runtime callers must use ahandle_for_session()."""
try: try:
key = _clean_session_key(session_key) key = _clean_session_key(session_key)
except ValueError: except ValueError:
return None return None
return self._ensure_all().get(key) 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]: 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) 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]: def list_all_by_key(self) -> dict[str, SessionHandle]:
"""Offline compatibility API; runtime callers must use alist_all_by_key()."""
return self._ensure_all() 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: def resolve(self, name: str) -> SessionHandle | None:
"""Offline compatibility API; runtime callers must use aresolve()."""
try: try:
normalized = normalize_session_handle(name) normalized = normalize_session_handle(name)
except ValueError: except ValueError:
@@ -227,3 +267,17 @@ class SessionHandleResolver:
), ),
None, 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.""" """Queue an internal continuation for *ctx* when policy allows it."""
if ctx.session is None or ctx.pending_queue is None: if ctx.session is None or ctx.pending_queue is None:
return False return False
if not _continuation_available( if not _continuation_available(
stop_reason=ctx.stop_reason, stop_reason=ctx.stop_reason,
pending_queue_available=True, pending_queue_available=True,
session_metadata=ctx.session.metadata, session_metadata=session_metadata,
message_metadata=ctx.msg.metadata, message_metadata=ctx.msg.metadata,
): ):
return False return False
@@ -136,7 +138,7 @@ async def maybe_continue_turn(ctx: TurnContext) -> bool:
"message_id": request.message_id, "message_id": request.message_id,
"turn_id": request.turn_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) messages = _strip_terminal_assistant(ctx.all_messages, ctx.final_content)
_increment_goal_continuation_round(ctx.session.metadata) _increment_goal_continuation_round(ctx.session.metadata)
+40 -16
View File
@@ -49,6 +49,7 @@ from nanobot.session.session_messages import (
SessionMessageEnvelope, SessionMessageEnvelope,
session_message_envelope, session_message_envelope,
) )
from nanobot.session.sqlite_store import SessionConflictError
from nanobot.utils.helpers import strip_think, truncate_text from nanobot.utils.helpers import strip_think, truncate_text
from nanobot.utils.llm_runtime import LLMRuntime from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.webui.metadata import ( 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 so pass ``target_session_key`` to project the title onto that per-chat
session instead of storing it on the shared one. 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 target_is_routed = target_session_key is None or target_session_key == session_key
if target_is_routed or target_session_key is None: if target_is_routed or target_session_key is None:
target_session = routed_session target_session = routed_session
else: else:
target_session = sessions.get_or_create(target_session_key) target_session = await sessions.state.get(target_session_key)
if ( if (
routed_session.metadata.get(WEBUI_SESSION_METADATA_KEY) is not True routed_session.metadata.get(WEBUI_SESSION_METADATA_KEY) is not True
and target_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) cleaned_current_title = clean_generated_title(current_title)
if cleaned_current_title: if cleaned_current_title:
if cleaned_current_title != current_title: if cleaned_current_title != current_title:
target_session.metadata[WEBUI_TITLE_METADATA_KEY] = cleaned_current_title def clean_title(metadata: dict[str, Any]) -> None:
sessions.save(target_session) 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 return False
target_session.metadata.pop(WEBUI_TITLE_METADATA_KEY, None) target_session.metadata.pop(WEBUI_TITLE_METADATA_KEY, None)
@@ -292,9 +300,20 @@ async def maybe_generate_webui_title(
response.finish_reason, response.finish_reason,
) )
return False return False
target_session.metadata[WEBUI_TITLE_METADATA_KEY] = title def set_title(metadata: dict[str, Any]) -> bool:
sessions.save(target_session) if metadata.get(WEBUI_TITLE_USER_EDITED_METADATA_KEY) is True:
return 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( async def maybe_generate_webui_title_after_turn(
@@ -473,8 +492,8 @@ class WebuiTurnRoutePolicy:
) )
and route.channel == "websocket" and route.channel == "websocket"
): ):
session = self.sessions.get_or_create(session_key) metadata_snapshot = self.sessions.state.peek_metadata(session_key)
if session.metadata.get(WEBUI_SESSION_METADATA_KEY) is True: if metadata_snapshot is not None and metadata_snapshot.get(WEBUI_SESSION_METADATA_KEY) is True:
metadata = dict(route.metadata) metadata = dict(route.metadata)
turn_prefix = "session-input" if internal_user_input else "subagent" turn_prefix = "session-input" if internal_user_input else "subagent"
metadata.update({ metadata.update({
@@ -552,6 +571,7 @@ class WebuiTurnCoordinator:
sessions: SessionManager sessions: SessionManager
schedule_background: Callable[[Awaitable[None]], None] schedule_background: Callable[[Awaitable[None]], None]
recovery: RecoveryCoordinator | None = None recovery: RecoveryCoordinator | None = None
def subscribe(self) -> Callable[[], None]: def subscribe(self) -> Callable[[], None]:
"""Subscribe this coordinator to runtime events.""" """Subscribe this coordinator to runtime events."""
unsubscribe = [ unsubscribe = [
@@ -626,7 +646,7 @@ class WebuiTurnCoordinator:
or not is_webui_session_key(session_key) or not is_webui_session_key(session_key)
): ):
return 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_value: object = persisted.get("metadata") if persisted is not None else None
metadata = ( metadata = (
cast(dict[str, Any], metadata_value) cast(dict[str, Any], metadata_value)
@@ -658,11 +678,15 @@ class WebuiTurnCoordinator:
), ),
)) ))
def _handle_session_turn_started(self, event: SessionTurnStarted) -> None: async def _handle_session_turn_started(self, event: SessionTurnStarted) -> None:
if not self._is_websocket_event(event.context): if (self._is_websocket_event(event.context)
return and event.context.metadata.get(WEBUI_SESSION_METADATA_KEY) is True):
session = self.sessions.get_or_create(event.context.session_key) await self.sessions.state.update_metadata(
mark_webui_session(session, event.context.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: async def _handle_run_status_changed(self, event: TurnRunStatusChanged) -> None:
if not self._is_websocket_event(event.context): if not self._is_websocket_event(event.context):
@@ -771,7 +795,7 @@ class WebuiTurnCoordinator:
if msg.channel != "websocket": if msg.channel != "websocket":
return return
session = self.sessions.get_or_create(session_key) session = await self.sessions.state.get(session_key)
await self.bus.publish_outbound( await self.bus.publish_outbound(
outbound_message_for_event( outbound_message_for_event(
channel=msg.channel, channel=msg.channel,
+2 -2
View File
@@ -2,7 +2,7 @@
from __future__ import annotations 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.agent.automation_turns import AutomationTurnCoordinator
from nanobot.bus.events import InboundMessage from nanobot.bus.events import InboundMessage
@@ -15,7 +15,7 @@ class LocalTriggerTurnCoordinator(AutomationTurnCoordinator):
def __init__( def __init__(
self, self,
*, *,
enqueue: Callable[[InboundMessage], None], enqueue: Callable[[InboundMessage], Awaitable[None]],
deferred_queues: dict[str, list[InboundMessage]] | None = None, deferred_queues: dict[str, list[InboundMessage]] | None = None,
) -> None: ) -> None:
super().__init__( super().__init__(
+4 -4
View File
@@ -9,7 +9,7 @@ from nanobot.cron.binding import CronBinding
from nanobot.cron.types import CronJob from nanobot.cron.types import CronJob
from nanobot.session.manager import ( from nanobot.session.manager import (
SessionManager, SessionManager,
_metadata_title, # pyright: ignore[reportPrivateUsage] metadata_title,
) )
from nanobot.session.session_handles import SessionHandleResolver from nanobot.session.session_handles import SessionHandleResolver
from nanobot.utils.helpers import truncate_text from nanobot.utils.helpers import truncate_text
@@ -30,7 +30,7 @@ class AutomationChat:
**({"unavailable": True} if not self.available else {})} **({"unavailable": True} if not self.available else {})}
def automation_chats( async def automation_chats(
job: CronJob, sessions: SessionManager, workspaces: WebUIWorkspaceController, job: CronJob, sessions: SessionManager, workspaces: WebUIWorkspaceController,
channel_status: dict[str, Any], channel_status: dict[str, Any],
) -> list[AutomationChat]: ) -> list[AutomationChat]:
@@ -50,7 +50,7 @@ def automation_chats(
) )
result: list[AutomationChat] = [] result: list[AutomationChat] = []
previews = {row["key"]: row.get("preview", "") for row in sessions.list_sessions()} 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 key = handle.session_key
data = sessions.read_session_metadata(key) data = sessions.read_session_metadata(key)
metadata: dict[str, Any] = data.get("metadata", {}) if data else {} metadata: dict[str, Any] = data.get("metadata", {}) if data else {}
@@ -76,7 +76,7 @@ def automation_chats(
continue continue
result.append(AutomationChat( result.append(AutomationChat(
id=handle.id, id=handle.id,
title=(_metadata_title(metadata) title=(metadata_title(metadata)
or truncate_text(" ".join(previews.get(key, "").split()), 60) or truncate_text(" ".join(previews.get(key, "").split()), 60)
or f"@{handle.name}"), or f"@{handle.name}"),
binding=CronBinding(key, channel, chat_id, route_metadata), binding=CronBinding(key, channel, chat_id, route_metadata),
+16 -19
View File
@@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
import asyncio
import uuid import uuid
from collections.abc import Mapping from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, Protocol from typing import TYPE_CHECKING, Any, Protocol
@@ -9,7 +10,7 @@ from typing import TYPE_CHECKING, Any, Protocol
from loguru import logger from loguru import logger
from nanobot.session.manager import SessionManager 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.session_identity import is_valid_webui_chat_id, webui_session_key
from nanobot.webui.transcript import ( from nanobot.webui.transcript import (
append_fork_marker, append_fork_marker,
@@ -42,7 +43,7 @@ class WebUIForkHost(Protocol):
) -> None: ... ) -> None: ...
def create_webui_chat_fork( async def create_webui_chat_fork(
session_manager: SessionManager, session_manager: SessionManager,
*, *,
source_chat_id: str, source_chat_id: str,
@@ -54,30 +55,26 @@ def create_webui_chat_fork(
source_key = webui_session_key(source_chat_id) source_key = webui_session_key(source_chat_id)
target_key = webui_session_key(new_id) target_key = webui_session_key(new_id)
try: try:
forked = session_manager.fork_session_before_user_index( forked = await session_manager.state.fork(
source_key, source_key,
target_key, target_key,
before_user_index, before_user_index,
title=clean_generated_title(title),
) )
if forked is None: if forked is None:
return None return None
transcript_ok = fork_transcript_before_user_index( def write_transcript() -> None:
source_key, transcript_ok = fork_transcript_before_user_index(
target_key, source_key, target_key, before_user_index,
before_user_index, )
) if not transcript_ok:
if not transcript_ok: write_session_messages_as_transcript(target_key, forked.messages)
write_session_messages_as_transcript(target_key, forked.messages) append_fork_marker(target_key)
append_fork_marker(target_key) await asyncio.to_thread(write_transcript)
fork_title = clean_generated_title(title)
if fork_title:
forked.metadata[WEBUI_TITLE_METADATA_KEY] = fork_title
session_manager.save(forked, fsync=True)
except Exception: except Exception:
delete_webui_transcript(target_key) await asyncio.to_thread(delete_webui_transcript, target_key)
session_manager.delete_session(target_key) await session_manager.state.delete(target_key)
raise raise
return new_id, target_key return new_id, target_key
@@ -108,7 +105,7 @@ async def handle_webui_fork_chat(
return return
try: try:
forked = create_webui_chat_fork( forked = await create_webui_chat_fork(
session_manager, session_manager,
source_chat_id=source_chat_id, source_chat_id=source_chat_id,
before_user_index=raw_index, before_user_index=raw_index,
+3
View File
@@ -53,6 +53,7 @@ class GatewayServices:
local_trigger_store: LocalTriggerStore | None local_trigger_store: LocalTriggerStore | None
cron_pending_job_ids: Callable[[str], set[str]] | None cron_pending_job_ids: Callable[[str], set[str]] | None
local_trigger_pending_ids: Callable[[str], set[str]] | None local_trigger_pending_ids: Callable[[str], set[str]] | None
unified_session: bool = False
def build_gateway_services( def build_gateway_services(
@@ -63,6 +64,7 @@ def build_gateway_services(
static_dist_path: Path | None, static_dist_path: Path | None,
workspace_path: Path, workspace_path: Path,
default_restrict_to_workspace: bool, default_restrict_to_workspace: bool,
unified_session: bool = False,
config_path: Path | None = None, config_path: Path | None = None,
runtime_model_name: Callable[[], str | None] | None, runtime_model_name: Callable[[], str | None] | None,
refresh_runtime_config: Callable[[], None] | None = None, refresh_runtime_config: Callable[[], None] | None = None,
@@ -171,4 +173,5 @@ def build_gateway_services(
local_trigger_store=local_trigger_store, local_trigger_store=local_trigger_store,
cron_pending_job_ids=cron_pending_job_ids, cron_pending_job_ids=cron_pending_job_ids,
local_trigger_pending_ids=local_trigger_pending_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 re
import time import time
import uuid import uuid
from collections.abc import Callable from collections.abc import Awaitable, Callable
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any, Protocol, cast from typing import Any, Protocol, cast
@@ -28,6 +28,7 @@ from nanobot.security.workspace_access import (
WORKSPACE_SCOPE_METADATA_KEY, WORKSPACE_SCOPE_METADATA_KEY,
WorkspaceScopeError, WorkspaceScopeError,
) )
from nanobot.session.keys import session_key_for_channel
from nanobot.session.webui_turns import ( from nanobot.session.webui_turns import (
clear_websocket_turn_if_current, clear_websocket_turn_if_current,
clear_websocket_turns, clear_websocket_turns,
@@ -126,6 +127,7 @@ class WebUICommandTransport(Protocol):
is_dm: bool, is_dm: bool,
session_key: str | None, session_key: str | None,
require_existing_session: bool, require_existing_session: bool,
session_generation: str | None,
) -> None: ... ) -> None: ...
async def send_session_updated( async def send_session_updated(
@@ -182,13 +184,13 @@ class WebUICommandRouter:
fork_id: str, fork_id: str,
fork_key: str, fork_key: str,
) -> None: ) -> 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) self._transport.webui_attach(connection, fork_id)
await self._transport.webui_send_event( await self._transport.webui_send_event(
connection, connection,
"attached", "attached",
chat_id=fork_id, 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( await self._transport.webui_send_event(
connection, connection,
@@ -275,13 +277,13 @@ class WebUICommandRouter:
async def workspace_scope_or_error( async def workspace_scope_or_error(
self, self,
connection: ServerConnection, connection: ServerConnection,
resolver: Callable[[], Any], resolver: Callable[[], Awaitable[Any]],
*, *,
chat_id: str | None = None, chat_id: str | None = None,
turn_id: str | None = None, turn_id: str | None = None,
) -> Any | None: ) -> Any | None:
try: try:
return resolver() return await resolver()
except WorkspaceScopeError as exc: except WorkspaceScopeError as exc:
await self._transport.webui_send_event( await self._transport.webui_send_event(
connection, connection,
@@ -315,13 +317,13 @@ class WebUICommandRouter:
) )
if scope is None: if scope is None:
return return
self._workspaces.stage_scope(new_id, scope) await self._workspaces.stage_scope(new_id, scope)
self._transport.webui_attach(connection, new_id) self._transport.webui_attach(connection, new_id)
await self._transport.webui_send_event( await self._transport.webui_send_event(
connection, connection,
"attached", "attached",
chat_id=new_id, 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( await self._transport.webui_send_event(
connection, connection,
@@ -334,7 +336,7 @@ class WebUICommandRouter:
return return
if command_type == "new_temporary_chat": if command_type == "new_temporary_chat":
try: try:
new_id = self._temporary_chats.create( new_id = await self._temporary_chats.create(
connection, connection,
trusted_webui=connection in self._webui_connections, trusted_webui=connection in self._webui_connections,
) )
@@ -395,7 +397,7 @@ class WebUICommandRouter:
connection, connection,
"attached", "attached",
chat_id=chat_id, 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) await self._transport.webui_hydrate(chat_id)
return return
@@ -456,7 +458,7 @@ class WebUICommandRouter:
) )
if scope is None: if scope is None:
return 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.send_session_updated(chat_id, scope="metadata")
await self._transport.webui_send_event( await self._transport.webui_send_event(
connection, connection,
@@ -619,20 +621,18 @@ class WebUICommandRouter:
if temporary_policy is None or temporary_policy.hydrate_transcript: if temporary_policy is None or temporary_policy.hydrate_transcript:
await self._transport.webui_hydrate(chat_id) await self._transport.webui_hydrate(chat_id)
scope = await self.workspace_scope_or_error( scope = temporary_policy.workspace_scope if temporary_policy is not None else (
connection, await self.workspace_scope_or_error(
lambda: ( connection,
temporary_policy.workspace_scope lambda: self._workspaces.scope_for_message(
if temporary_policy is not None
else self._workspaces.scope_for_message(
envelope, envelope,
chat_id=chat_id, chat_id=chat_id,
chat_running=websocket_turn_wall_started_at(chat_id) is not None, chat_running=websocket_turn_wall_started_at(chat_id) is not None,
can_change_project=self.workspace_project_selection_available(connection), can_change_project=self.workspace_project_selection_available(connection),
) ),
), chat_id=chat_id,
chat_id=chat_id, turn_id=turn_id,
turn_id=turn_id, )
) )
if scope is None: if scope is None:
return return
@@ -685,8 +685,7 @@ class WebUICommandRouter:
metadata["mcp_presets"] = mcp_presets metadata["mcp_presets"] = mcp_presets
session_mentions: list[SessionMention] = [] session_mentions: list[SessionMention] = []
if trusted_webui and self._session_access is not None: if trusted_webui and self._session_access is not None:
session_mentions = await asyncio.to_thread( session_mentions = await self._session_access.normalize_mentions(
self._session_access.normalize_mentions,
envelope.get("session_mentions"), envelope.get("session_mentions"),
exclude_session_key=webui_session_key(chat_id), exclude_session_key=webui_session_key(chat_id),
) )
@@ -715,7 +714,44 @@ class WebUICommandRouter:
metadata[WEBSOCKET_TURN_OWNER_METADATA_KEY] = queued_owner metadata[WEBSOCKET_TURN_OWNER_METADATA_KEY] = queued_owner
accepted = False 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: 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 ( if is_webui and not restart_control and (
temporary_policy is None or temporary_policy.persist_transcript temporary_policy is None or temporary_policy.persist_transcript
): ):
@@ -753,21 +789,35 @@ class WebUICommandRouter:
metadata=metadata, metadata=metadata,
is_dm=False, is_dm=False,
session_key=( 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=( require_existing_session=(
temporary_policy.require_existing_session temporary_policy.require_existing_session
if temporary_policy is not None if temporary_policy is not None
else False else False
), ),
session_generation=execution_generation,
) )
if not restart_control:
self._workspaces.persist_scope(chat_id, scope)
accepted = True accepted = True
if turn_id: if turn_id:
self._accepted_messages[(chat_id, turn_id)] = time.monotonic() + 600 self._accepted_messages[(chat_id, turn_id)] = time.monotonic() + 600
if len(self._accepted_messages) > 1024: if len(self._accepted_messages) > 1024:
del self._accepted_messages[next(iter(self._accepted_messages))] 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: finally:
if not accepted and queued_owner is not None: if not accepted and queued_owner is not None:
clear_websocket_turn_if_current(chat_id, queued_owner) 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: async def hydrate(self, chat_id: str) -> None:
"""Replay reconnect state through the existing stable wire operations.""" """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), webui_session_key(chat_id),
chat_id, chat_id,
): ):
+23 -23
View File
@@ -86,8 +86,8 @@ class RecoveryCoordinator:
async def scan(self) -> None: async def scan(self) -> None:
"""Recover every interrupted WebUI session once at gateway startup.""" """Recover every interrupted WebUI session once at gateway startup."""
for key in self._recovery_candidates(): for key in await self._recovery_candidates():
metadata_payload = self.sessions.read_session_metadata(key) metadata_payload = await self.sessions.state.read_metadata(key)
raw_metadata = metadata_payload.get("metadata") if metadata_payload else None raw_metadata = metadata_payload.get("metadata") if metadata_payload else None
metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {} metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
route = self._websocket_route_for(key, metadata) route = self._websocket_route_for(key, metadata)
@@ -96,7 +96,7 @@ class RecoveryCoordinator:
unfinished = self._has_unfinished_webui_transcript(key) unfinished = self._has_unfinished_webui_transcript(key)
if not self._needs_recovery(metadata) and not unfinished: if not self._needs_recovery(metadata) and not unfinished:
continue continue
session = self.sessions.get_or_create(key) session = await self.sessions.state.get(key)
try: try:
await self._recover_session(session, route[1]) await self._recover_session(session, route[1])
await self._requeue_pending_followups(session) await self._requeue_pending_followups(session)
@@ -111,14 +111,14 @@ class RecoveryCoordinator:
reason="recovery_failed", reason="recovery_failed",
can_continue=False, can_continue=False,
) )
self.sessions.save(session) await self.sessions.state.restore_interruption(session)
await self._publish(route[1], failed) 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.""" """Discover canonical and transcript-only WebUI sessions cheaply."""
candidates = dict.fromkeys( candidates = dict.fromkeys(
key key
for item in self.sessions.list_sessions() for item in await self.sessions.state.list_sessions()
if isinstance((key := item.get("key")), str) if isinstance((key := item.get("key")), str)
) )
try: try:
@@ -127,7 +127,7 @@ class RecoveryCoordinator:
# duplicating its filename and migration rules here would drift. # duplicating its filename and migration rules here would drift.
from nanobot.webui.session_list_index import list_webui_sessions 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") key = item.get("key")
if isinstance(key, str): if isinstance(key, str):
candidates.setdefault(key, None) candidates.setdefault(key, None)
@@ -153,7 +153,7 @@ class RecoveryCoordinator:
"""Reject stale queued recoveries and let new user input supersede them.""" """Reject stale queued recoveries and let new user input supersede them."""
recovery_id = message.metadata.get(RECOVERY_INBOUND_METADATA_KEY) recovery_id = message.metadata.get(RECOVERY_INBOUND_METADATA_KEY)
if isinstance(recovery_id, str): 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) state = recovery_state_from_metadata(session.metadata)
return bool( return bool(
state state
@@ -162,7 +162,7 @@ class RecoveryCoordinator:
) )
if message.channel != "websocket": if message.channel != "websocket":
return True 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) state = recovery_state_from_metadata(session.metadata)
if state and state["status"] in {"resuming", "awaiting_user", "failed"}: if state and state["status"] in {"resuming", "awaiting_user", "failed"}:
await self._cancel_active_recovery(message.session_key) await self._cancel_active_recovery(message.session_key)
@@ -176,13 +176,13 @@ class RecoveryCoordinator:
attempts=cast(int, state.get("attempts", 0)), attempts=cast(int, state.get("attempts", 0)),
reason="superseded", reason="superseded",
) )
self.sessions.save(session) await self.sessions.state.restore_interruption(session)
await self._publish(message.chat_id, recovered) await self._publish(message.chat_id, recovered)
return True return True
async def turn_completed(self, session_key: str) -> None: async def turn_completed(self, session_key: str) -> None:
"""Resolve a resuming state after the recovered turn commits.""" """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) state = recovery_state_from_metadata(session.metadata)
if not state or state["status"] != "resuming": if not state or state["status"] != "resuming":
return return
@@ -196,7 +196,7 @@ class RecoveryCoordinator:
attempts=cast(int, state.get("attempts", 0)), attempts=cast(int, state.get("attempts", 0)),
reason="continued", reason="continued",
) )
self.sessions.save(session) await self.sessions.state.restore_interruption(session)
await self._publish(route[1], recovered) await self._publish(route[1], recovered)
async def handle_action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]: 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") raise RecoveryActionError("missing chat_id")
if not isinstance(recovery_id, str) or not recovery_id: if not isinstance(recovery_id, str) or not recovery_id:
raise RecoveryActionError("missing 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) state = recovery_state_from_metadata(session.metadata)
if not state or state["recovery_id"] != recovery_id: if not state or state["recovery_id"] != recovery_id:
raise RecoveryActionError("recovery state is stale", status=409) raise RecoveryActionError("recovery state is stale", status=409)
@@ -222,7 +222,7 @@ class RecoveryCoordinator:
attempts=cast(int, state.get("attempts", 0)), attempts=cast(int, state.get("attempts", 0)),
reason="dismissed", reason="dismissed",
) )
self.sessions.save(session) await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, next_state) await self._publish(chat_id, next_state)
return next_state return next_state
if action != "continue": if action != "continue":
@@ -239,7 +239,7 @@ class RecoveryCoordinator:
reason="user_confirmed", reason="user_confirmed",
resume_message_count=len(session.messages), 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._publish(chat_id, next_state)
await self._queue_continuation(session, chat_id, next_state) await self._queue_continuation(session, chat_id, next_state)
return next_state return next_state
@@ -272,7 +272,7 @@ class RecoveryCoordinator:
attempts=cast(int, state.get("attempts", 1)), attempts=cast(int, state.get("attempts", 1)),
reason="loop_guard", reason="loop_guard",
) )
self.sessions.save(session) await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, next_state) await self._publish(chat_id, next_state)
elif self._has_unfinished_webui_transcript(session.key): elif self._has_unfinished_webui_transcript(session.key):
# A normal last-client shutdown can materialize the checkpoint # A normal last-client shutdown can materialize the checkpoint
@@ -294,7 +294,7 @@ class RecoveryCoordinator:
), ),
can_continue=can_continue, can_continue=can_continue,
) )
self.sessions.save(session) await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, waiting) await self._publish(chat_id, waiting)
return return
if state and state["status"] in {"awaiting_user", "failed"}: if state and state["status"] in {"awaiting_user", "failed"}:
@@ -310,7 +310,7 @@ class RecoveryCoordinator:
attempts=cast(int, state.get("attempts", 1)), attempts=cast(int, state.get("attempts", 1)),
reason="loop_guard", reason="loop_guard",
) )
self.sessions.save(session) await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, waiting) await self._publish(chat_id, waiting)
return return
@@ -328,7 +328,7 @@ class RecoveryCoordinator:
reason="checkpoint_unknown", reason="checkpoint_unknown",
can_continue=False, can_continue=False,
) )
self.sessions.save(session) await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, waiting) await self._publish(chat_id, waiting)
return return
if checkpoint is not None and not runtime_checkpoint_is_well_formed(checkpoint): if checkpoint is not None and not runtime_checkpoint_is_well_formed(checkpoint):
@@ -342,7 +342,7 @@ class RecoveryCoordinator:
reason="checkpoint_invalid", reason="checkpoint_invalid",
can_continue=False, can_continue=False,
) )
self.sessions.save(session) await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, waiting) await self._publish(chat_id, waiting)
return return
if phase == "final_response": if phase == "final_response":
@@ -354,7 +354,7 @@ class RecoveryCoordinator:
attempts=0, attempts=0,
reason="answer_restored", reason="answer_restored",
) )
self.sessions.save(session) await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, recovered) await self._publish(chat_id, recovered)
return return
if phase in UNCERTAIN_TOOL_PHASES or pending_calls: if phase in UNCERTAIN_TOOL_PHASES or pending_calls:
@@ -366,7 +366,7 @@ class RecoveryCoordinator:
attempts=0, attempts=0,
reason="tool_state_unknown", reason="tool_state_unknown",
) )
self.sessions.save(session) await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, waiting) await self._publish(chat_id, waiting)
return return
# A gateway restart is a lifecycle boundary. Never enqueue model work # A gateway restart is a lifecycle boundary. Never enqueue model work
@@ -381,7 +381,7 @@ class RecoveryCoordinator:
attempts=0, attempts=0,
reason="restart_requires_confirmation", reason="restart_requires_confirmation",
) )
self.sessions.save(session) await self.sessions.state.restore_interruption(session)
await self._publish(chat_id, waiting) await self._publish(chat_id, waiting)
async def _queue_continuation( async def _queue_continuation(
+12 -4
View File
@@ -51,22 +51,30 @@ class WebuiSessionAccess:
return None return None
return payload return payload
def normalize_mentions( async def normalize_mentions(
self, self,
raw: object, raw: object,
*, *,
exclude_session_key: str | None = None, exclude_session_key: str | None = None,
) -> list[SessionMention]: ) -> list[SessionMention]:
mentions = normalize_session_mentions_metadata(raw)
if not mentions:
return []
normalized: list[SessionMention] = [] normalized: list[SessionMention] = []
seen_keys: set[str] = set() seen_keys: set[str] = set()
seen_names: 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 mention = raw_mention
key = mention["session_key"] 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: if payload is None or key in seen_keys:
continue continue
handle = self._handles.handle_for_session(key) handle = handles.get(key)
if handle is None: if handle is None:
continue continue
folded_name = handle.name.casefold() 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.cron.types import CronJob
from nanobot.session.history_visibility import is_hidden_history_message from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import ( from nanobot.session.manager import (
_message_preview_text, # pyright: ignore[reportPrivateUsage] message_preview_text, # pyright: ignore[reportPrivateUsage]
_metadata_title, # pyright: ignore[reportPrivateUsage] metadata_title, # pyright: ignore[reportPrivateUsage]
) )
from nanobot.triggers.local_types import LocalTrigger from nanobot.triggers.local_types import LocalTrigger
from nanobot.webui.session_identity import is_webui_session_key from nanobot.webui.session_identity import is_webui_session_key
@@ -322,7 +322,7 @@ def _websocket_origin_payload(
if session_manager is not None: if session_manager is not None:
data = session_manager.read_session_file(session_key) data = session_manager.read_session_file(session_key)
if isinstance(data, dict): if isinstance(data, dict):
title = _metadata_title(data.get("metadata")) title = metadata_title(data.get("metadata"))
preview = _session_preview(data.get("messages")) preview = _session_preview(data.get("messages"))
return { return {
@@ -344,7 +344,7 @@ def _session_preview(messages: Any) -> str:
message = cast(dict[str, Any], message_value) message = cast(dict[str, Any], message_value)
if is_hidden_history_message(message): if is_hidden_history_message(message):
continue continue
text = _message_preview_text(message) text = message_preview_text(message)
if not text: if not text:
continue continue
if message.get("role") == "user": 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 The core ``SessionManager`` owns model context while the WebUI transcript owns
durable display history. The sidebar discovers both without reconstructing one durable display history. The sidebar discovers both without reconstructing one
@@ -11,6 +11,8 @@ import json
import os import os
import re import re
import secrets import secrets
import stat
from dataclasses import dataclass, field
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
from typing import Any, cast from typing import Any, cast
@@ -19,17 +21,12 @@ from loguru import logger
from nanobot.config.paths import get_webui_dir from nanobot.config.paths import get_webui_dir
from nanobot.security.workspace_access import WORKSPACE_SCOPE_METADATA_KEY 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 ( from nanobot.session.manager import (
_PROVIDER_STATE_RECORD_TYPE, # pyright: ignore[reportPrivateUsage]
_SESSION_LIST_PREVIEW_MAX_CHARS, # pyright: ignore[reportPrivateUsage] _SESSION_LIST_PREVIEW_MAX_CHARS, # pyright: ignore[reportPrivateUsage]
_SESSION_LIST_PREVIEW_MAX_RECORDS, # pyright: ignore[reportPrivateUsage] _SESSION_LIST_PREVIEW_MAX_RECORDS, # pyright: ignore[reportPrivateUsage]
Session,
SessionManager, SessionManager,
_is_provider_state_record_line, # pyright: ignore[reportPrivateUsage] message_preview_text, # pyright: ignore[reportPrivateUsage]
_message_preview_text, # pyright: ignore[reportPrivateUsage] )
_metadata_title, # pyright: ignore[reportPrivateUsage]
)
from nanobot.session.model_selection import model_preset_from_metadata from nanobot.session.model_selection import model_preset_from_metadata
from nanobot.session.recovery import recovery_state_from_metadata from nanobot.session.recovery import recovery_state_from_metadata
from nanobot.webui.session_identity import ( from nanobot.webui.session_identity import (
@@ -62,28 +59,73 @@ _TRANSCRIPT_SEGMENTS_SUFFIX = ".segments"
_TRANSCRIPT_NON_ANSWER_KINDS = {"progress", "reasoning", "tool_hint"} _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.""" """Return session rows for the WebUI sidebar, backed by a rebuildable cache."""
with session_manager.locked_session_files(): webui_dir = get_webui_dir()
rows, changed = _reconcile_index(session_manager) rows, changed = _reconcile_index(session_manager, stored_sessions, webui_dir)
if changed: if changed:
try: try:
_write_index_rows(session_manager.sessions_dir, rows) _write_index_rows(session_manager.sessions_dir, [row for row in rows if row.get(_ROW_SOURCE_FIELD) == _TRANSCRIPT_SOURCE])
except Exception as e: except Exception as e:
logger.debug("Failed to write WebUI session list index: {}", e) logger.debug("Failed to write WebUI transcript list cache: {}", e)
sessions = [ sessions = [_public_row(session_manager.sessions_dir, webui_dir, row) for row in rows]
_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", {})
)
]
return sorted(sessions, key=lambda row: row.get("updated_at", ""), reverse=True) 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_rows = _read_index_rows(session_manager.sessions_dir)
existing_by_source = { existing_by_source = {
(row.get(_ROW_SOURCE_FIELD), row.get("file")): row (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) if isinstance(row.get(_ROW_SOURCE_FIELD), str)
and isinstance(row.get("file"), 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 changed = existing_rows is None
expected_sources: set[tuple[str, str]] = set() expected_sources: set[tuple[str, str]] = set()
for stem, files in transcripts:
for key, path in sorted(session_paths.items()): files.signature = activity_by_stem[os.path.normcase(stem)]
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
identity = (_TRANSCRIPT_SOURCE, stem) identity = (_TRANSCRIPT_SOURCE, stem)
row = existing_by_source.get(identity) row = existing_by_source.get(identity)
cached_key = row.get("key") if row is not None else None 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( if key is not None and row is not None and _indexed_transcript_row_matches(
row, row,
key, key,
webui_dir, files.signature,
): ):
rows.append(row) rows.append(row)
expected_sources.add(identity) expected_sources.add(identity)
continue continue
changed = True 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 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) rows.append(scanned)
expected_sources.add(identity) expected_sources.add(identity)
if set(existing_by_source) != expected_sources: if set(existing_by_source) != expected_sources:
changed = True 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 changed = True
return rows, changed 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) 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( def _indexed_transcript_row_matches(
row: dict[str, Any], row: dict[str, Any],
session_key: str, session_key: str,
webui_dir: Path, signature: dict[str, int],
) -> bool: ) -> bool:
if not all(isinstance(row.get(key), str) for key in ("key", "created_at", "updated_at")): if not all(isinstance(row.get(key), str) for key in ("key", "created_at", "updated_at")):
return False return False
@@ -236,7 +223,6 @@ def _indexed_transcript_row_matches(
return False return False
if not isinstance(row.get(_WORKSPACE_SCOPE_PRESENT_FIELD), bool): if not isinstance(row.get(_WORKSPACE_SCOPE_PRESENT_FIELD), bool):
return False return False
signature = _webui_activity_signature(session_key, webui_dir)
return ( return (
row.get(_WEBUI_ACTIVITY_MTIME_NS) == signature[_WEBUI_ACTIVITY_MTIME_NS] row.get(_WEBUI_ACTIVITY_MTIME_NS) == signature[_WEBUI_ACTIVITY_MTIME_NS]
and row.get(_WEBUI_ACTIVITY_SIZE) == signature[_WEBUI_ACTIVITY_SIZE] 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, ...]: def add_file(stem: str, entry: os.DirEntry[str]) -> None:
paths: list[Path] = []
segments_dir = webui_dir / f"{stem}{_TRANSCRIPT_SEGMENTS_SUFFIX}"
if segments_dir.is_dir() and not segments_dir.is_symlink():
try: try:
paths.extend( info = entry.stat(follow_symlinks=False)
sorted(
path
for path in segments_dir.glob("*.jsonl")
if path.is_file() and not path.is_symlink()
)
)
except OSError: except OSError:
pass return
active = webui_dir / f"{stem}.jsonl" if not stat.S_ISREG(info.st_mode):
if active.is_file() and not active.is_symlink(): return
paths.append(active) files = files_by_stem.setdefault(stem, _WebuiFiles())
return tuple(paths) 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: 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: except OSError:
return {} pass
for path in entries: return files_by_stem
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))
}
def _transcript_record(line: str) -> dict[str, Any] | None: 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 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: def _webui_activity_updated_at(signature: dict[str, int]) -> str | None:
mtime_ns = signature.get(_WEBUI_ACTIVITY_MTIME_NS, 0) mtime_ns = signature.get(_WEBUI_ACTIVITY_MTIME_NS, 0)
if 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 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( def _visible_activity_updated_at(
stored: str | None, stored: str | None,
@@ -482,37 +380,12 @@ def _visible_activity_updated_at(
return _latest_updated_at(visible_message_at, webui_activity) or stored 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]: def _transcript_preview(record: dict[str, Any]) -> tuple[str, str]:
text = record.get("text") text = record.get("text")
if not isinstance(text, str) or not text.strip(): if not isinstance(text, str) or not text.strip():
return "", "" return "", ""
preview = _message_preview_text({"content": text}) preview = message_preview_text({"content": text})
if not preview: if not preview:
return "", "" return "", ""
event = record.get("event") event = record.get("event")
@@ -543,13 +416,10 @@ def _transcript_created_at(record: dict[str, Any]) -> str | None:
def _scan_transcript_row( def _scan_transcript_row(
session_key: str | None, session_key: str | None,
stem: str, stem: str,
paths: tuple[Path, ...], files: _WebuiFiles,
webui_dir: Path, webui_dir: Path,
) -> dict[str, Any] | None: ) -> dict[str, Any] | None:
path_key = session_key or webui_session_key( signature = files.signature
stem.removeprefix(_WEBUI_SESSION_STEM_PREFIX)
)
signature = _webui_activity_signature(path_key, webui_dir)
activity_updated_at = _webui_activity_updated_at(signature) activity_updated_at = _webui_activity_updated_at(signature)
if activity_updated_at is None: if activity_updated_at is None:
return None return None
@@ -560,6 +430,7 @@ def _scan_transcript_row(
saw_record = False saw_record = False
scanned_records = 0 scanned_records = 0
scanned_chars = 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: for path in paths:
try: try:
with open(path, encoding="utf-8") as handle: with open(path, encoding="utf-8") as handle:
@@ -606,7 +477,7 @@ def _scan_transcript_row(
if created_at is None: if created_at is None:
try: 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() created_at = datetime.fromtimestamp(earliest_mtime).isoformat()
except (OSError, OverflowError, ValueError): except (OSError, OverflowError, ValueError):
created_at = activity_updated_at created_at = activity_updated_at
@@ -625,95 +496,3 @@ def _scan_transcript_row(
"size": signature[_WEBUI_ACTIVITY_SIZE], "size": signature[_WEBUI_ACTIVITY_SIZE],
**signature, **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.goal_state import goal_state_ws_blob
from nanobot.session.model_selection import model_preset_from_metadata from nanobot.session.model_selection import model_preset_from_metadata
from nanobot.session.recovery import recovery_state_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 from nanobot.session.webui_turns import websocket_turn_id, websocket_turn_wall_started_at
if TYPE_CHECKING: if TYPE_CHECKING:
@@ -20,7 +21,8 @@ if TYPE_CHECKING:
class SessionMetadataReader(Protocol): class SessionMetadataReader(Protocol):
"""Narrow persisted-session dependency used by WebUI projections.""" """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: class WebUISessionProjection:
@@ -46,11 +48,11 @@ class WebUISessionProjection:
except SubagentControlError: except SubagentControlError:
return None 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.""" """Return the session runtime facts sent with an attach handshake."""
if self._sessions is None: if self._sessions is None:
return {} 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 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 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() fields["usage"] = usage.to_turn_dict()
return fields 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.""" """Return reconnect events for durable and same-process session state."""
events: list[dict[str, Any]] = [] 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: if goal_state is not None:
events.append( events.append(
{ {
@@ -97,11 +99,11 @@ class WebUISessionProjection:
events.append(event) events.append(event)
return tuple(events) 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.""" """Return an actionable persisted goal state for reconnect hydration."""
if self._sessions is None: if self._sessions is None:
return 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 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 {} metadata = cast(dict[str, Any], raw_metadata) if isinstance(raw_metadata, dict) else {}
goal_state = goal_state_ws_blob(metadata) goal_state = goal_state_ws_blob(metadata)
+14 -4
View File
@@ -1822,7 +1822,11 @@ class ModelSettingsHandler:
) -> SettingsRouteResult: ) -> SettingsRouteResult:
try: try:
if action == "agent-update": 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() self._refresh_runtime_config()
return SettingsRouteResult.success( return SettingsRouteResult.success(
payload, payload,
@@ -1831,7 +1835,8 @@ class ModelSettingsHandler:
) )
if action == "model-update": if action == "model-update":
payload = self.settings.mutate( payload = await asyncio.to_thread(
self.settings.mutate,
operations.update_model, operations.update_model,
request.query, request.query,
rename_model_preset=self.settings.rename_model_preset, rename_model_preset=self.settings.rename_model_preset,
@@ -1847,12 +1852,17 @@ class ModelSettingsHandler:
"provider-create": operations.create_provider, "provider-create": operations.create_provider,
}.get(action) }.get(action)
if mutation is not None: 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() self._refresh_runtime_config()
return SettingsRouteResult.success(payload, decorate_restart=True) return SettingsRouteResult.success(payload, decorate_restart=True)
if action == "provider-update": if action == "provider-update":
payload = self.settings.mutate( payload = await asyncio.to_thread(
self.settings.mutate,
operations.update_provider, operations.update_provider,
request.query, 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.builtin import register_builtin_commands
from nanobot.command.router import CommandRouter from nanobot.command.router import CommandRouter
from nanobot.security.workspace_access import WorkspaceScope 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 from nanobot.webui.workspaces import WebUIWorkspaceController
_TEMPORARY_CHAT_DISABLED_TOOLS = frozenset({ _TEMPORARY_CHAT_DISABLED_TOOLS = frozenset({
@@ -41,6 +41,7 @@ class TemporaryChatMessagePolicy:
"""Server-owned message rules for one active Temporary Chat.""" """Server-owned message rules for one active Temporary Chat."""
session_key: str session_key: str
session_generation: str
workspace_scope: WorkspaceScope workspace_scope: WorkspaceScope
require_existing_session: bool = True require_existing_session: bool = True
hydrate_transcript: bool = False hydrate_transcript: bool = False
@@ -68,9 +69,6 @@ class WebUITemporaryChats:
register_builtin_commands(self._commands) register_builtin_commands(self._commands)
self._owners: dict[str, object] = {} self._owners: dict[str, object] = {}
self._owner_chat_ids: dict[object, set[str]] = {} 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 # Retain policy-derived tombstones until shutdown so late outbound
# events cannot create a durable transcript after a chat is discarded. # events cannot create a durable transcript after a chat is discarded.
self._known_transient_chat_ids: set[str] = set() self._known_transient_chat_ids: set[str] = set()
@@ -82,10 +80,10 @@ class WebUITemporaryChats:
def _cached_session_is_transient(self, chat_id: str) -> bool: def _cached_session_is_transient(self, chat_id: str) -> bool:
if self._sessions is None: if self._sessions is None:
return False return False
session = self._sessions.get_cached(self._session_key(chat_id)) identity = self._sessions.state.peek_identity(self._session_key(chat_id))
return session is not None and not session.policy.persist 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.""" """Create a server-identified chat owned by one authenticated WebUI connection."""
if not trusted_webui: if not trusted_webui:
raise TemporaryChatError("access_denied") raise TemporaryChatError("access_denied")
@@ -93,7 +91,7 @@ class WebUITemporaryChats:
raise TemporaryChatError("temporary_chat_unavailable") raise TemporaryChatError("temporary_chat_unavailable")
chat_id = str(uuid.uuid4()) chat_id = str(uuid.uuid4())
session = self._sessions.get_or_create_transient( session = await self._sessions.state.register_transient(
self._session_key(chat_id), self._session_key(chat_id),
disabled_tools=_TEMPORARY_CHAT_DISABLED_TOOLS, disabled_tools=_TEMPORARY_CHAT_DISABLED_TOOLS,
) )
@@ -101,7 +99,6 @@ class WebUITemporaryChats:
raise RuntimeError("Temporary Chat must use a non-persistent session policy") raise RuntimeError("Temporary Chat must use a non-persistent session policy")
self._owners[chat_id] = owner self._owners[chat_id] = owner
self._owner_chat_ids.setdefault(owner, set()).add(chat_id) self._owner_chat_ids.setdefault(owner, set()).add(chat_id)
self._active_sessions[chat_id] = session
self._known_transient_chat_ids.add(chat_id) self._known_transient_chat_ids.add(chat_id)
return 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: if self._owners.get(chat_id) is not owner or self._sessions is None:
raise TemporaryChatError("temporary_chat_unavailable") raise TemporaryChatError("temporary_chat_unavailable")
session = self._sessions.get_cached(self._session_key(chat_id)) identity = self._sessions.state.peek_identity(self._session_key(chat_id))
if session is None: if identity is None:
raise TemporaryChatError("temporary_chat_unavailable") raise TemporaryChatError("temporary_chat_unavailable")
command = self._commands.command_name(content) command = self._commands.command_name(content)
@@ -129,6 +126,7 @@ class WebUITemporaryChats:
return TemporaryChatMessagePolicy( return TemporaryChatMessagePolicy(
session_key=self._session_key(chat_id), session_key=self._session_key(chat_id),
session_generation=identity.generation,
workspace_scope=self._workspaces.restricted_default_scope(), workspace_scope=self._workspaces.restricted_default_scope(),
) )
@@ -193,10 +191,9 @@ class WebUITemporaryChats:
session_key = self._session_key(chat_id) session_key = self._session_key(chat_id)
self._forget_owner(owner, chat_id) self._forget_owner(owner, chat_id)
self._active_sessions.pop(chat_id, None)
self._discard_media(chat_id) self._discard_media(chat_id)
if self._sessions is not None: if self._sessions is not None:
self._sessions.invalidate(session_key) await self._sessions.state.discard(session_key)
await self._bus.publish_inbound( await self._bus.publish_inbound(
InboundMessage( InboundMessage(
channel=self._channel_name, channel=self._channel_name,
@@ -215,8 +212,7 @@ class WebUITemporaryChats:
for chat_id in tuple(self._owners): for chat_id in tuple(self._owners):
self._discard_media(chat_id) self._discard_media(chat_id)
if self._sessions is not None: 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._owners.clear()
self._owner_chat_ids.clear() self._owner_chat_ids.clear()
self._active_sessions.clear()
self._known_transient_chat_ids.clear() self._known_transient_chat_ids.clear()
+62 -18
View File
@@ -286,6 +286,19 @@ class WebUIWorkspaceController:
if self._sessions is None: if self._sessions is None:
return self.default_scope() return self.default_scope()
data = self._sessions.read_session_metadata(session_key) 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): if not isinstance(data, dict):
return self.default_scope() return self.default_scope()
metadata = data.get("metadata", {}) metadata = data.get("metadata", {})
@@ -348,14 +361,18 @@ class WebUIWorkspaceController:
write_webui_workspace_state(state) write_webui_workspace_state(state)
return [{"name": Path(item).name or item, "path": item} for item in favorites] return [{"name": Path(item).name or item, "path": item} for item in favorites]
def scope_from_envelope( async def scope_from_envelope(
self, self,
envelope: dict[str, Any], envelope: dict[str, Any],
*, *,
session_key: str | None, session_key: str | None,
can_change_project: bool, can_change_project: bool,
) -> WorkspaceScope: ) -> 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) raw = envelope.get(WORKSPACE_SCOPE_METADATA_KEY)
if raw is None: if raw is None:
scope = current scope = current
@@ -373,19 +390,19 @@ class WebUIWorkspaceController:
) )
return scope return scope
def scope_for_new_chat( async def scope_for_new_chat(
self, self,
envelope: dict[str, Any], envelope: dict[str, Any],
*, *,
can_change_project: bool, can_change_project: bool,
) -> WorkspaceScope: ) -> WorkspaceScope:
return self.scope_from_envelope( return await self.scope_from_envelope(
envelope, envelope,
session_key=None, session_key=None,
can_change_project=can_change_project, can_change_project=can_change_project,
) )
def scope_for_set_request( async def scope_for_set_request(
self, self,
envelope: dict[str, Any], envelope: dict[str, Any],
*, *,
@@ -395,13 +412,13 @@ class WebUIWorkspaceController:
) -> WorkspaceScope: ) -> WorkspaceScope:
if chat_running: if chat_running:
raise WorkspaceScopeError("chat_running", status=409) raise WorkspaceScopeError("chat_running", status=409)
return self.scope_from_envelope( return await self.scope_from_envelope(
envelope, envelope,
session_key=webui_session_key(chat_id), session_key=webui_session_key(chat_id),
can_change_project=can_change_project, can_change_project=can_change_project,
) )
def scope_for_message( async def scope_for_message(
self, self,
envelope: dict[str, Any], envelope: dict[str, Any],
*, *,
@@ -409,7 +426,7 @@ class WebUIWorkspaceController:
chat_running: bool, chat_running: bool,
can_change_project: bool, can_change_project: bool,
) -> WorkspaceScope: ) -> WorkspaceScope:
scope = self.scope_from_envelope( scope = await self.scope_from_envelope(
envelope, envelope,
session_key=webui_session_key(chat_id), session_key=webui_session_key(chat_id),
can_change_project=can_change_project, can_change_project=can_change_project,
@@ -417,29 +434,56 @@ class WebUIWorkspaceController:
if ( if (
WORKSPACE_SCOPE_METADATA_KEY in envelope WORKSPACE_SCOPE_METADATA_KEY in envelope
and chat_running 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) raise WorkspaceScopeError("chat_running", status=409)
return scope return scope
def persist_scope(self, chat_id: str, scope: WorkspaceScope) -> None: async def persist_scope(
session_key = webui_session_key(chat_id) 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: if self._sessions is not None:
session = self._sessions.get_or_create(session_key) generation, created = await self._sessions.state.open_with_metadata(
session.metadata["webui"] = True session_key,
session.metadata[WORKSPACE_SCOPE_METADATA_KEY] = scope.metadata() {"webui": True, WORKSPACE_SCOPE_METADATA_KEY: scope.metadata()},
self._sessions.save(session) expected_generation=generation,
)
self._draft_scopes.pop(session_key, None) self._draft_scopes.pop(session_key, None)
remember_webui_project(scope.project_path) 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.""" """Keep a new chat's scope transient until its first accepted message."""
session_key = webui_session_key(chat_id) session_key = webui_session_key(chat_id)
if ( if (
self._sessions is not None 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 return
remember_webui_project(scope.project_path) remember_webui_project(scope.project_path)
self._draft_scopes[session_key] = scope 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.security.workspace_access import WorkspaceScope, WorkspaceScopeError
from nanobot.session.manager import SessionManager from nanobot.session.manager import SessionManager
from nanobot.session.session_handles import ( from nanobot.session.session_handles import (
SessionHandle,
SessionHandleResolver, SessionHandleResolver,
) )
from nanobot.triggers.local_types import LocalTrigger from nanobot.triggers.local_types import LocalTrigger
@@ -837,7 +838,7 @@ class GatewayHTTPHandler:
m = re.fullmatch(r"/api/sessions/([^/]+)/subagents", got) m = re.fullmatch(r"/api/sessions/([^/]+)/subagents", got)
if m: 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) m = re.match(r"^/api/sessions/([^/]+)/delete$", got)
if m: if m:
@@ -866,7 +867,7 @@ class GatewayHTTPHandler:
return _http_error(exc.status, str(exc)) return _http_error(exc.status, str(exc))
return _http_json_response(result) 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): if not self.check_api_token(request):
return _http_error(401, "Unauthorized") return _http_error(401, "Unauthorized")
session_key = _decode_api_key(key) session_key = _decode_api_key(key)
@@ -877,7 +878,7 @@ class GatewayHTTPHandler:
if self.subagent_manager is None: if self.subagent_manager is None:
return _http_error(503, "subagent manager unavailable") return _http_error(503, "subagent manager unavailable")
try: try:
statuses = self.subagent_manager.statuses_for_session(session_key) statuses = await self.subagent_manager.read_statuses_for_session(session_key)
except (OSError, SubagentSessionError): except (OSError, SubagentSessionError):
return _http_error(503, "task history unavailable") return _http_error(503, "task history unavailable")
return _http_json_response({ return _http_json_response({
@@ -958,20 +959,47 @@ class GatewayHTTPHandler:
return _http_error(401, "Unauthorized") return _http_error(401, "Unauthorized")
if self.session_manager is None: if self.session_manager is None:
return _http_error(503, "session manager unavailable") return _http_error(503, "session manager unavailable")
payload = await asyncio.to_thread(self._sessions_list_payload) accept_encoding = _combined_list_header(request.headers, "Accept-Encoding")
return _http_json_response(
payload,
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 assert self.session_manager is not None
from nanobot.session.webui_turns import websocket_turn_wall_started_at from nanobot.session.webui_turns import websocket_turn_wall_started_at
sessions = list_webui_sessions(self.session_manager) sessions = list_webui_sessions(self.session_manager, stored_sessions)
handles = SessionHandleResolver(self.session_manager).list_all_by_key()
cleaned: list[dict[str, Any]] = [] cleaned: list[dict[str, Any]] = []
default_scope: WorkspaceScope | None = None default_scope: WorkspaceScope | None = None
scopes: dict[str, WorkspaceScope] = {}
for s in sessions: for s in sessions:
key = s.get("key") key = s.get("key")
if not (isinstance(key, str) and is_webui_session_key(key)): if not (isinstance(key, str) and is_webui_session_key(key)):
@@ -992,11 +1020,16 @@ class GatewayHTTPHandler:
if default_scope is None: if default_scope is None:
default_scope = self.workspaces.default_scope() default_scope = self.workspaces.default_scope()
scope_present, raw_scope = indexed_workspace_scope(s) scope_present, raw_scope = indexed_workspace_scope(s)
scope = self.workspaces.scope_for_indexed_metadata( if scope_present:
raw_scope, scope_key = json.dumps(raw_scope, ensure_ascii=False, sort_keys=True)
scope_present=scope_present, scope = scopes.get(scope_key)
default_scope=default_scope, 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() row["workspace_scope"] = scope.payload()
handle = handles.get(key) handle = handles.get(key)
if handle is not None: if handle is not None:
@@ -1307,7 +1340,7 @@ class GatewayHTTPHandler:
for job in automation_jobs: for job in automation_jobs:
if isinstance(job, LocalTrigger): if isinstance(job, LocalTrigger):
if self.local_trigger_store is not None: 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: elif self.cron_service is not None:
self.cron_service.remove_job(job.id) self.cron_service.remove_job(job.id)
draft_deleted = self.workspaces.discard_draft_scope(decoded_key) draft_deleted = self.workspaces.discard_draft_scope(decoded_key)
@@ -1315,8 +1348,8 @@ class GatewayHTTPHandler:
await self.discard_session(decoded_key) await self.discard_session(decoded_key)
elif self.subagent_manager is not None: elif self.subagent_manager is not None:
await self.subagent_manager.cancel_by_session(decoded_key) await self.subagent_manager.cancel_by_session(decoded_key)
session_deleted = self.session_manager.delete_session(decoded_key) session_deleted = await self.session_manager.state.delete(decoded_key)
transcript_deleted = delete_webui_thread(decoded_key) transcript_deleted = await asyncio.to_thread(delete_webui_thread, decoded_key)
return _http_json_response( return _http_json_response(
{"deleted": bool(draft_deleted or session_deleted or transcript_deleted)} {"deleted": bool(draft_deleted or session_deleted or transcript_deleted)}
) )
@@ -1333,7 +1366,7 @@ class GatewayHTTPHandler:
if got == "/api/webui/automations/result": if got == "/api/webui/automations/result":
return await self._handle_webui_automation_result(request) return await self._handle_webui_automation_result(request)
if got == "/api/webui/automations/chats": 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) m = re.match(r"^/api/webui/automations/(enable|disable|delete|run|update|change-chat)$", got)
if m: if m:
return await self._handle_webui_automation_action(request, m.group(1)) 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: if self.session_manager is None:
return [] return []
return automation_chats( return await automation_chats(
job, self.session_manager, self.workspaces, job, self.session_manager, self.workspaces,
self.channel_runtime_status() if self.channel_runtime_status else {}, 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): if not self.check_api_token(request):
return _http_error(401, "Unauthorized") return _http_error(401, "Unauthorized")
job_id = _query_first(_request_query(request), "id") or "" job_id = _query_first(_request_query(request), "id") or ""
job = self.cron_service.get_job(job_id) if self.cron_service else None 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): if job is None or not is_bound_cron_job(job):
return _http_error(404, "automation has no movable chat") 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 current = next((chat for chat in chats
if chat.binding.session_key == job.payload.session_key), None) if chat.binding.session_key == job.payload.session_key), None)
return _http_json_response({ return _http_json_response({
@@ -1504,7 +1537,7 @@ class GatewayHTTPHandler:
return _http_error(400, "invalid automation chat payload") return _http_error(400, "invalid automation chat payload")
if job.id in self._pending_cron_job_ids_for_all(): if job.id in self._pending_cron_job_ids_for_all():
return _http_error(409, "automation_chat_busy") 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 chat.id == values["target_id"]), None)
if target is None or not target.available: if target is None or not target.available:
return _http_error(409, "automation_chat_unavailable") 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: if patch_deps:
with patch("nanobot.agent.loop.ContextBuilder"), \ with patch("nanobot.agent.loop.ContextBuilder"), \
patch("nanobot.agent.loop.SessionManager"), \
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr: 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.cancel_by_session = AsyncMock(return_value=0)
return AgentLoop(**kwargs) return AgentLoop(**kwargs)
+21 -3
View File
@@ -21,11 +21,11 @@ def visible_message(message: dict) -> dict:
return public_history_message(message) 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.""" """Persist the child that owns a synthetic completion notification."""
assert loop.subagents.sessions is not None assert loop.subagents.sessions is not None
now = time.monotonic() 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", task_id=task_id, label=task_id, task_description="Background work",
owner=owner, started_at=now, finished_at=now, completed_at=time.time(), owner=owner, started_at=now, finished_at=now, completed_at=time.time(),
state="done", phase="done", 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: async def run_session(loop: AgentLoop, msg: InboundMessage) -> None:
"""Submit input and wait for its session worker to finish.""" """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)]) 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.""" """Tests for auto compact (idle TTL) feature."""
import asyncio import asyncio
import time
from datetime import datetime, timedelta from datetime import datetime, timedelta
from pathlib import Path from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock from unittest.mock import AsyncMock, MagicMock
import pytest import pytest
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.context import current_request_context
from nanobot.agent.tools.registry import ToolRegistry from nanobot.agent.tools.registry import ToolRegistry
from nanobot.bus.events import InboundMessage from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus 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.events import NO_EVENTS
from nanobot.providers.base import LLMResponse from nanobot.providers.base import LLMResponse
from nanobot.runtime_context import public_history_message 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( def _make_loop(
tmp_path: Path, tmp_path: Path,
session_ttl_minutes: int = 15, session_ttl_minutes: int = 15,
unified_session: bool = False,
) -> AgentLoop: ) -> AgentLoop:
"""Create a minimal AgentLoop for testing.""" """Create a minimal AgentLoop for testing."""
bus = MessageBus() bus = MessageBus()
@@ -37,6 +42,7 @@ def _make_loop(
model="test-model", model="test-model",
context_window_tokens=128_000, context_window_tokens=128_000,
session_ttl_minutes=session_ttl_minutes, session_ttl_minutes=session_ttl_minutes,
unified_session=unified_session,
) )
loop.tools.get_definitions = MagicMock(return_value=[]) loop.tools.get_definitions = MagicMock(return_value=[])
return loop return loop
@@ -94,16 +100,14 @@ def _make_fake_compact(
events=NO_EVENTS, events=NO_EVENTS,
) -> str: ) -> str:
state["count"] += 1 state["count"] += 1
session = loop.sessions.get_or_create(key) session = await loop.sessions.state.get(key)
tail = list(session.messages[session.last_archived:]) tail = list(session.messages[session.last_archived:])
if not tail: if not tail:
loop.sessions.save(session)
return "" return ""
archive_end = session.last_archived + len(tail) archive_end = session.last_archived + len(tail)
archive_msgs = tail archive_msgs = tail
last_active = session.updated_at
s = summary s = summary
if on_archive: if on_archive:
result = on_archive(archive_msgs) result = on_archive(archive_msgs)
@@ -111,14 +115,7 @@ def _make_fake_compact(
if track_archived is not None: if track_archived is not None:
track_archived.extend(archive_msgs) track_archived.extend(archive_msgs)
if s and s != "(nothing)": await loop.sessions.state.commit_summary(session, s, archive_end=archive_end)
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)
return s return s
# Attach state for count access # 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.sessions.save(session)
loop.consolidator.archive_session = AsyncMock(return_value="Heartbeat summary.") 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) await _drain_background_tasks(loop)
loop.consolidator.archive_session.assert_awaited_once() 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() 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: class TestSessionTTLConfig:
"""Test session TTL configuration.""" """Test session TTL configuration."""
@@ -202,10 +293,10 @@ class TestSessionTTLConfig:
class TestIdleScanThrottling: class TestIdleScanThrottling:
"""Test scheduling of full idle-session scans.""" """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.""" """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)) 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({ config = Config.model_validate({
"agents": { "agents": {
"defaults": { "defaults": {
@@ -221,24 +312,24 @@ class TestIdleScanThrottling:
tool_registry=ToolRegistry(), tool_registry=ToolRegistry(),
provider=provider, 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.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.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 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.""" """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 = _make_loop(tmp_path)
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._check_expired_sessions_if_due() await loop._check_expired_sessions_if_due()
assert loop.auto_compact.check_expired.call_count == 2 assert loop.auto_compact.check_expired.call_count == 2
@@ -274,7 +365,7 @@ class TestAutoCompact:
loop.sessions.save(s2) loop.sessions.save(s2)
loop.consolidator.compact_idle_session = _make_fake_compact(loop) 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) await _drain_background_tasks(loop)
active_after = loop.sessions.get_or_create("cli:active") active_after = loop.sessions.get_or_create("cli:active")
@@ -742,7 +833,7 @@ class TestProactiveAutoCompact:
@staticmethod @staticmethod
async def _run_check_expired(loop, active_session_keys=()): async def _run_check_expired(loop, active_session_keys=()):
"""Helper: run check_expired via callback and wait for background tasks.""" """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.schedule_background,
loop.runtime_for_session, loop.runtime_for_session,
active_session_keys=active_session_keys, active_session_keys=active_session_keys,
@@ -763,15 +854,12 @@ class TestProactiveAutoCompact:
healthy.add_message("user", "keep me") healthy.add_message("user", "keep me")
loop.sessions.save(healthy) loop.sessions.save(healthy)
removed_path = loop.sessions._get_session_path(removed.key) original_list = loop.sessions.list_sessions
original_open = open def delete_after_listing():
rows = original_list()
def remove_before_open(path, *args, **kwargs): loop.sessions.delete_session(removed.key)
if Path(path) == removed_path: return rows
removed_path.unlink() monkeypatch.setattr(loop.sessions.state, "list_sessions", AsyncMock(side_effect=delete_after_listing))
return original_open(path, *args, **kwargs)
monkeypatch.setattr("builtins.open", remove_before_open)
async def idle_once(): async def idle_once():
loop._running = False loop._running = False
@@ -881,12 +969,12 @@ class TestProactiveAutoCompact:
loop.consolidator.compact_idle_session = _slow_compact loop.consolidator.compact_idle_session = _slow_compact
# First call starts archiving via callback # 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() await started.wait()
assert archive_count == 1 assert archive_count == 1
# Second call should skip (key is in _archiving) # 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 assert archive_count == 1
# Clean up # Clean up
@@ -1008,8 +1096,9 @@ class TestProactiveAutoCompact:
await loop.aclose() await loop.aclose()
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_no_reschedule_after_successful_archive(self, tmp_path): @pytest.mark.parametrize("command_tail", [False, True])
"""Already-archived session should NOT be re-scheduled on subsequent ticks.""" 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) loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test") session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 5, prefix="old") _add_turns(session, 5, prefix="old")
@@ -1019,14 +1108,33 @@ class TestProactiveAutoCompact:
_fake_compact = _make_fake_compact(loop) _fake_compact = _make_fake_compact(loop)
loop.consolidator.compact_idle_session = _fake_compact loop.consolidator.compact_idle_session = _fake_compact
# First tick: archives the session try:
await self._run_check_expired(loop) await self._run_check_expired(loop)
assert _fake_compact.state["count"] == 1 assert _fake_compact.state["count"] == 1
# Second tick: should NOT re-schedule because the session has no removable tail. if command_tail:
await self._run_check_expired(loop) session = await loop.sessions.state.get(session.key)
assert _fake_compact.state["count"] == 1 # Still 1, not re-scheduled session.add_message("user", "/status", _command=True)
await loop.aclose() 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 @pytest.mark.asyncio
async def test_empty_session_does_not_schedule_idle_compact(self, tmp_path): 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") msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="second topic")
await loop._process_message(msg) await loop._process_message(msg)
# Simulate idle again # Explicit archival does not require another TTL scan.
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)
# Second compact cycle should succeed # Second compact cycle should succeed
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime()) await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
assert _fake_compact.state["count"] == 2 assert _fake_compact.state["count"] == 2
@@ -1131,7 +1234,7 @@ class TestSummaryPersistence:
reloaded = loop.sessions.get_or_create("cli:test") reloaded = loop.sessions.get_or_create("cli:test")
assert len(reloaded.messages) == 13 assert len(reloaded.messages) == 13
assert reloaded.get_history(max_messages=12) == [] 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 is not None
assert summary["text"] == "User said hello." assert summary["text"] == "User said hello."
@@ -1158,9 +1261,9 @@ class TestSummaryPersistence:
reloaded = loop.sessions.get_or_create("cli:test") reloaded = loop.sessions.get_or_create("cli:test")
# Every call returns the persisted summary. # 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 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 is not None
assert summary2["text"] == "Summary." assert summary2["text"] == "Summary."
# _last_summary persists in metadata for restart survival. # _last_summary persists in metadata for restart survival.
@@ -1187,7 +1290,7 @@ class TestSummaryPersistence:
assert "_last_summary" in reloaded.metadata assert "_last_summary" in reloaded.metadata
# In-memory path is taken (no restart) # 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 assert summary is not None
# _last_summary persists in metadata for restart survival. # _last_summary persists in metadata for restart survival.
assert "_last_summary" in reloaded.metadata assert "_last_summary" in reloaded.metadata
@@ -1208,17 +1311,17 @@ class TestSummaryPersistence:
await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime()) await loop.auto_compact._archive("cli:test", runtime=loop.llm_runtime())
# Consume the first summary via hot path # 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" loop.sessions.get_or_create("cli:test"), "cli:test"
) )
assert summary1 is not None assert summary1 is not None
assert summary1["text"] == "First summary." assert summary1["text"] == "First summary."
assert "cli:test" not in loop.auto_compact._summaries # popped by hot path 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") _add_turns(session, 4, prefix="world")
session.updated_at = datetime.now() - timedelta(minutes=20) await loop.sessions.state.finish_turn(session)
loop.sessions.save(session)
loop.consolidator.compact_idle_session = _make_fake_compact( loop.consolidator.compact_idle_session = _make_fake_compact(
loop, summary="Second summary.", loop, summary="Second summary.",
@@ -1230,7 +1333,7 @@ class TestSummaryPersistence:
# prepare_session must return the new summary # prepare_session must return the new summary
reloaded = loop.sessions.get_or_create("cli:test") 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 is not None
assert summary2["text"] == "Second summary." assert summary2["text"] == "Second summary."
await loop.aclose() await loop.aclose()
@@ -1254,9 +1357,7 @@ class TestSummaryPersistence:
assert "_last_summary" in reloaded.metadata assert "_last_summary" in reloaded.metadata
# Simulate /new command # Simulate /new command
reloaded.clear() await loop.sessions.state.reset(reloaded.key)
loop.sessions.save(reloaded)
loop.sessions.invalidate(reloaded.key)
# After /new, metadata should no longer contain _last_summary # After /new, metadata should no longer contain _last_summary
fresh = loop.sessions.get_or_create("cli:test") 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.""" """Direct unit tests for AutoCompact class methods in isolation."""
import asyncio import asyncio
from collections import defaultdict
from datetime import datetime, timedelta from datetime import datetime, timedelta
from unittest.mock import AsyncMock, MagicMock 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 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): def _runtime(_session: Session | None = None):
return MagicMock(name="runtime") return MagicMock(name="runtime")
async def _resolve_runtime(session: Session):
return _runtime(session)
def _make_session( def _make_session(
key: str = "cli:test", key: str = "cli:test",
messages: list | None = None, messages: list | None = None,
@@ -41,7 +54,10 @@ def _make_autocompact(
) -> AutoCompact: ) -> AutoCompact:
"""Create an AutoCompact with mock dependencies.""" """Create an AutoCompact with mock dependencies."""
if sessions is None: 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: if consolidator is None:
consolidator = MagicMock() consolidator = MagicMock()
consolidator.compact_idle_session = AsyncMock(return_value="Summary.") consolidator.compact_idle_session = AsyncMock(return_value="Summary.")
@@ -49,7 +65,7 @@ def _make_autocompact(
sessions=sessions, sessions=sessions,
consolidator=consolidator, consolidator=consolidator,
session_ttl_minutes=ttl, 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}") session.add_message("assistant", f"{prefix} assistant {i}")
def test_default_ttl_disables_idle_compaction(): async def test_default_ttl_disables_idle_compaction():
sessions = MagicMock(spec=SessionManager) sessions = _mock_sessions()
sessions.list_sessions.return_value = [ sessions.list_sessions.return_value = [
{"key": "cli:idle", "updated_at": datetime.now() - timedelta(days=365)}, {"key": "cli:idle", "updated_at": datetime.now() - timedelta(days=365)},
] ]
sessions.get_or_create.return_value = _make_session( sessions.get_or_create.return_value = _make_session(
key="cli:idle", messages=[{"role": "user", "content": "pending"}], key="cli:idle", messages=[{"role": "user", "content": "pending"}],
) )
ac = AutoCompact(sessions=sessions, consolidator=MagicMock(), ac = AutoCompact(
session_lock=lambda _key: asyncio.Lock()) sessions=sessions, consolidator=MagicMock(),
session_lock=defaultdict(asyncio.Lock).__getitem__,
)
schedule = MagicMock(side_effect=lambda pending: pending.close()) 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 assert schedule.call_count == 0
@@ -162,20 +180,20 @@ class TestIsExpired:
class TestCheckExpired: class TestCheckExpired:
"""Test AutoCompact.check_expired scheduling logic.""" """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.""" """No sessions → schedule_background should never be called."""
ac = _make_autocompact(ttl=15) ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager) mock_sm = _mock_sessions()
mock_sm.list_sessions.return_value = [] mock_sm.list_sessions.return_value = []
ac.sessions = mock_sm ac.sessions = mock_sm
scheduler = MagicMock() scheduler = MagicMock()
ac.check_expired(scheduler, _runtime) await ac.check_expired(scheduler, _resolve_runtime)
scheduler.assert_not_called() 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.""" """Expired session should trigger schedule_background."""
ac = _make_autocompact(ttl=15) ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager) mock_sm = _mock_sessions()
old_dt = datetime.now() - timedelta(minutes=20) old_dt = datetime.now() - timedelta(minutes=20)
session = _make_session("cli:old", updated_at=old_dt) session = _make_session("cli:old", updated_at=old_dt)
_add_turns(session, 5) _add_turns(session, 5)
@@ -189,11 +207,11 @@ class TestCheckExpired:
scheduled.append(coro) scheduled.append(coro)
coro.close() coro.close()
ac.check_expired(scheduler, _runtime) await ac.check_expired(scheduler, _resolve_runtime)
assert len(scheduled) == 1 assert len(scheduled) == 1
assert "cli:old" in ac._archiving 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. """A malformed timestamp is skipped without hiding later sessions.
The idle scan runs from the agent loop's inbound-timeout branch, so a The idle scan runs from the agent loop's inbound-timeout branch, so a
@@ -202,7 +220,7 @@ class TestCheckExpired:
does when loading. does when loading.
""" """
ac = _make_autocompact(ttl=15) ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager) mock_sm = _mock_sessions()
old_dt = datetime.now() - timedelta(minutes=20) old_dt = datetime.now() - timedelta(minutes=20)
session = _make_session("cli:old", updated_at=old_dt) session = _make_session("cli:old", updated_at=old_dt)
_add_turns(session, 5) _add_turns(session, 5)
@@ -218,7 +236,7 @@ class TestCheckExpired:
scheduled.append(coro) scheduled.append(coro)
coro.close() coro.close()
ac.check_expired(scheduler, _runtime) await ac.check_expired(scheduler, _resolve_runtime)
assert len(scheduled) == 1 assert len(scheduled) == 1
assert ac._archiving == {"cli:old"} assert ac._archiving == {"cli:old"}
@@ -235,10 +253,10 @@ class TestCheckExpired:
ac.sessions.get_or_create.return_value = session ac.sessions.get_or_create.return_value = session
admitted = _runtime() admitted = _runtime()
replacement = _runtime() replacement = _runtime()
resolve_runtime = MagicMock(return_value=admitted) resolve_runtime = AsyncMock(return_value=admitted)
scheduled = [] scheduled = []
ac.check_expired(scheduled.append, resolve_runtime) await ac.check_expired(scheduled.append, resolve_runtime)
resolve_runtime.return_value = replacement resolve_runtime.return_value = replacement
await scheduled[0] await scheduled[0]
@@ -250,7 +268,7 @@ class TestCheckExpired:
) )
@pytest.mark.parametrize("resolution_error", [KeyError, ValueError]) @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) ac = _make_autocompact(ttl=15)
old_dt = datetime.now() - timedelta(minutes=20) old_dt = datetime.now() - timedelta(minutes=20)
sessions = { sessions = {
@@ -266,7 +284,7 @@ class TestCheckExpired:
ac.sessions.get_or_create.side_effect = sessions.__getitem__ ac.sessions.get_or_create.side_effect = sessions.__getitem__
healthy_runtime = _runtime() healthy_runtime = _runtime()
def resolve_runtime(session: Session): async def resolve_runtime(session: Session):
if session.key == "cli:removed": if session.key == "cli:removed":
raise resolution_error("model preset cannot be resolved") raise resolution_error("model preset cannot be resolved")
return healthy_runtime return healthy_runtime
@@ -277,12 +295,12 @@ class TestCheckExpired:
scheduled.append(coro) scheduled.append(coro)
coro.close() coro.close()
ac.check_expired(scheduler, resolve_runtime) await ac.check_expired(scheduler, resolve_runtime)
assert len(scheduled) == 1 assert len(scheduled) == 1
assert ac._archiving == {"cli:healthy"} 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) ac = _make_autocompact(ttl=15)
old_dt = datetime.now() - timedelta(minutes=20) old_dt = datetime.now() - timedelta(minutes=20)
session = _make_session("cli:old", updated_at=old_dt) session = _make_session("cli:old", updated_at=old_dt)
@@ -292,59 +310,59 @@ class TestCheckExpired:
] ]
ac.sessions.get_or_create.return_value = session ac.sessions.get_or_create.return_value = session
def fail(_session: Session): async def fail(_session: Session):
raise RuntimeError("unexpected resolver failure") raise RuntimeError("unexpected resolver failure")
with pytest.raises(RuntimeError, match="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.""" """Session in active_session_keys should be skipped."""
ac = _make_autocompact(ttl=15) ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager) mock_sm = _mock_sessions()
old_ts = (datetime.now() - timedelta(minutes=20)).isoformat() old_ts = (datetime.now() - timedelta(minutes=20)).isoformat()
mock_sm.list_sessions.return_value = [{"key": "cli:busy", "updated_at": old_ts}] mock_sm.list_sessions.return_value = [{"key": "cli:busy", "updated_at": old_ts}]
ac.sessions = mock_sm ac.sessions = mock_sm
scheduler = MagicMock() 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() 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.""" """Session already in _archiving set should be skipped."""
ac = _make_autocompact(ttl=15) ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager) mock_sm = _mock_sessions()
old_ts = (datetime.now() - timedelta(minutes=20)).isoformat() old_ts = (datetime.now() - timedelta(minutes=20)).isoformat()
mock_sm.list_sessions.return_value = [{"key": "cli:dup", "updated_at": old_ts}] mock_sm.list_sessions.return_value = [{"key": "cli:dup", "updated_at": old_ts}]
ac.sessions = mock_sm ac.sessions = mock_sm
ac._archiving.add("cli:dup") ac._archiving.add("cli:dup")
scheduler = MagicMock() scheduler = MagicMock()
ac.check_expired(scheduler, _runtime) await ac.check_expired(scheduler, _resolve_runtime)
scheduler.assert_not_called() 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.""" """Session info with empty/missing key should be skipped."""
ac = _make_autocompact(ttl=15) ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager) mock_sm = _mock_sessions()
mock_sm.list_sessions.return_value = [{"key": "", "updated_at": "old"}] mock_sm.list_sessions.return_value = [{"key": "", "updated_at": "old"}]
ac.sessions = mock_sm ac.sessions = mock_sm
scheduler = MagicMock() scheduler = MagicMock()
ac.check_expired(scheduler, _runtime) await ac.check_expired(scheduler, _resolve_runtime)
scheduler.assert_not_called() 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.""" """Session info dict without 'key' field should be skipped."""
ac = _make_autocompact(ttl=15) ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager) mock_sm = _mock_sessions()
mock_sm.list_sessions.return_value = [{"updated_at": "old"}] mock_sm.list_sessions.return_value = [{"updated_at": "old"}]
ac.sessions = mock_sm ac.sessions = mock_sm
scheduler = MagicMock() scheduler = MagicMock()
ac.check_expired(scheduler, _runtime) await ac.check_expired(scheduler, _resolve_runtime)
scheduler.assert_not_called() 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.""" """Internal Dream sessions should not be scheduled for idle compact."""
ac = _make_autocompact(ttl=15) ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager) mock_sm = _mock_sessions()
old_ts = (datetime.now() - timedelta(minutes=20)).isoformat() old_ts = (datetime.now() - timedelta(minutes=20)).isoformat()
mock_sm.list_sessions.return_value = [ mock_sm.list_sessions.return_value = [
{"key": "dream:20260602-155256", "updated_at": old_ts}, {"key": "dream:20260602-155256", "updated_at": old_ts},
@@ -352,15 +370,15 @@ class TestCheckExpired:
ac.sessions = mock_sm ac.sessions = mock_sm
scheduler = MagicMock() scheduler = MagicMock()
ac.check_expired(scheduler, _runtime) await ac.check_expired(scheduler, _resolve_runtime)
scheduler.assert_not_called() scheduler.assert_not_called()
assert "dream:20260602-155256" not in ac._archiving 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.""" """A short idle session still needs an archive entry for Dream."""
ac = _make_autocompact(ttl=15) ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager) mock_sm = _mock_sessions()
last_active = datetime(2026, 1, 1, 10, 0, 0) last_active = datetime(2026, 1, 1, 10, 0, 0)
session = _make_session("cli:short", updated_at=last_active) session = _make_session("cli:short", updated_at=last_active)
_add_turns(session, 2) _add_turns(session, 2)
@@ -376,14 +394,14 @@ class TestCheckExpired:
scheduled.append(coro) scheduled.append(coro)
coro.close() coro.close()
ac.check_expired(scheduler, _runtime) await ac.check_expired(scheduler, _resolve_runtime)
assert len(scheduled) == 1 assert len(scheduled) == 1
assert ac._archiving == {"cli:short"} 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) ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager) mock_sm = _mock_sessions()
last_active = datetime(2026, 1, 1, 10, 0, 0) last_active = datetime(2026, 1, 1, 10, 0, 0)
session = _make_session("cli:done", updated_at=last_active) session = _make_session("cli:done", updated_at=last_active)
_add_turns(session, 2) _add_turns(session, 2)
@@ -392,12 +410,14 @@ class TestCheckExpired:
{"key": "cli:done", "updated_at": last_active.isoformat()}, {"key": "cli:done", "updated_at": last_active.isoformat()},
] ]
mock_sm.get_or_create.return_value = session mock_sm.get_or_create.return_value = session
mock_sm.state.has_unarchived_messages.return_value = False
ac.sessions = mock_sm ac.sessions = mock_sm
scheduler = MagicMock() scheduler = MagicMock()
ac.check_expired(scheduler, _runtime) await ac.check_expired(scheduler, _resolve_runtime)
scheduler.assert_not_called() scheduler.assert_not_called()
mock_sm.state.get.assert_not_awaited()
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -411,7 +431,8 @@ class TestArchiveDelegates:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_calls_compact_idle_session(self): async def test_calls_compact_idle_session(self):
ac = _make_autocompact() 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.sessions = mock_sm
ac.consolidator.compact_idle_session = AsyncMock(return_value="Summary.") ac.consolidator.compact_idle_session = AsyncMock(return_value="Summary.")
@@ -426,7 +447,8 @@ class TestArchiveDelegates:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_forwards_timeout_compaction_events_with_session_key(self): 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() consolidator = MagicMock()
observed: list[tuple[str, ContextCompactionEvent]] = [] observed: list[tuple[str, ContextCompactionEvent]] = []
@@ -446,7 +468,7 @@ class TestArchiveDelegates:
consolidator=consolidator, consolidator=consolidator,
session_ttl_minutes=15, session_ttl_minutes=15,
bind_events=bind, bind_events=bind,
session_lock=lambda _key: asyncio.Lock(), session_lock=defaultdict(asyncio.Lock).__getitem__,
) )
await ac._archive("cli:test", runtime=_runtime()) await ac._archive("cli:test", runtime=_runtime())
@@ -469,7 +491,7 @@ class TestArchiveDelegates:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_populates_summaries_from_metadata(self): async def test_populates_summaries_from_metadata(self):
ac = _make_autocompact() ac = _make_autocompact()
mock_sm = MagicMock(spec=SessionManager) mock_sm = _mock_sessions()
session = _make_session( session = _make_session(
metadata={"_last_summary": {"text": "Hello.", "last_active": "2026-05-13T10:00:00"}} metadata={"_last_summary": {"text": "Hello.", "last_active": "2026-05-13T10:00:00"}}
) )
@@ -486,7 +508,7 @@ class TestArchiveDelegates:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_no_summary_when_compact_returns_empty(self): async def test_no_summary_when_compact_returns_empty(self):
ac = _make_autocompact() ac = _make_autocompact()
mock_sm = MagicMock(spec=SessionManager) mock_sm = _mock_sessions()
ac.sessions = mock_sm ac.sessions = mock_sm
ac.consolidator.compact_idle_session = AsyncMock(return_value="") ac.consolidator.compact_idle_session = AsyncMock(return_value="")
@@ -497,7 +519,7 @@ class TestArchiveDelegates:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_no_summary_when_compact_returns_nothing(self): async def test_no_summary_when_compact_returns_nothing(self):
ac = _make_autocompact() ac = _make_autocompact()
mock_sm = MagicMock(spec=SessionManager) mock_sm = _mock_sessions()
ac.sessions = mock_sm ac.sessions = mock_sm
ac.consolidator.compact_idle_session = AsyncMock(return_value="(nothing)") ac.consolidator.compact_idle_session = AsyncMock(return_value="(nothing)")
@@ -508,7 +530,7 @@ class TestArchiveDelegates:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_exception_still_removes_from_archiving(self): async def test_exception_still_removes_from_archiving(self):
ac = _make_autocompact() ac = _make_autocompact()
mock_sm = MagicMock(spec=SessionManager) mock_sm = _mock_sessions()
ac.sessions = mock_sm ac.sessions = mock_sm
ac.consolidator.compact_idle_session = AsyncMock(side_effect=RuntimeError("fail")) ac.consolidator.compact_idle_session = AsyncMock(side_effect=RuntimeError("fail"))
@@ -526,36 +548,21 @@ class TestArchiveDelegates:
class TestPrepareSession: class TestPrepareSession:
"""Test AutoCompact.prepare_session logic.""" """Test AutoCompact.prepare_session logic."""
def test_key_in_archiving_reloads_session(self): @pytest.mark.parametrize("archiving", [False, True])
"""If key is in _archiving, session should be reloaded via get_or_create.""" async def test_preparing_idle_session_preserves_turn_metadata(self, archiving):
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."""
ac = _make_autocompact(ttl=15) ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager) session = _make_session(
reloaded = _make_session(key="cli:test", updated_at=datetime.now()) updated_at=datetime.now() - timedelta(minutes=20),
mock_sm.get_or_create.return_value = reloaded metadata={"last_channel": "discord:new"},
ac.sessions = mock_sm )
if archiving:
ac._archiving.add(session.key)
old_session = _make_session(updated_at=datetime.now() - timedelta(minutes=20)) prepared, _ = await ac.prepare_session(session, session.key)
result_session, summary = ac.prepare_session(old_session, "cli:test")
mock_sm.get_or_create.assert_called_once_with("cli:test") assert prepared.metadata["last_channel"] == "discord:new"
assert result_session is reloaded
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).""" """Summary from _summaries dict should be returned (hot path)."""
ac = _make_autocompact() ac = _make_autocompact()
session = _make_session() session = _make_session()
@@ -565,7 +572,7 @@ class TestPrepareSession:
"last_active": last_active.isoformat(), "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 result_session is session
assert summary is not None assert summary is not None
@@ -574,7 +581,7 @@ class TestPrepareSession:
"last_active": last_active.isoformat(), "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).""" """Hot path should pop the summary (one-shot; second call returns None)."""
ac = _make_autocompact() ac = _make_autocompact()
session = _make_session() session = _make_session()
@@ -584,13 +591,13 @@ class TestPrepareSession:
"last_active": last_active.isoformat(), "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 assert summary1 is not None
# Second call: hot path entry was popped # 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 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).""" """When _summaries is empty, summary should come from metadata (cold path)."""
ac = _make_autocompact() ac = _make_autocompact()
last_active = datetime(2026, 5, 13, 14, 0, 0) 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 result_session is session
assert summary is not None assert summary is not None
assert summary["text"] == "Cold summary." 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. """A malformed persisted last_active must not raise on the turn path.
prepare_session runs from _compact_session on every turn. Persisted prepare_session runs from _compact_session on every turn. Persisted
@@ -624,7 +631,7 @@ class TestPrepareSession:
updated_at=fallback, 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 result_session is session
assert summary is not None assert summary is not None
@@ -633,7 +640,7 @@ class TestPrepareSession:
"last_active": fallback.isoformat(), "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.""" """A _last_summary dict without last_active must not raise."""
ac = _make_autocompact(ttl=0) ac = _make_autocompact(ttl=0)
fallback = datetime(2026, 1, 2, 3, 4, 5) fallback = datetime(2026, 1, 2, 3, 4, 5)
@@ -642,7 +649,7 @@ class TestPrepareSession:
updated_at=fallback, 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 result_session is session
assert summary is not None assert summary is not None
@@ -651,32 +658,32 @@ class TestPrepareSession:
"last_active": fallback.isoformat(), "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.""" """A _last_summary without a non-empty string text yields no summary."""
ac = _make_autocompact() ac = _make_autocompact()
session = _make_session(metadata={ session = _make_session(metadata={
"_last_summary": {"last_active": datetime(2026, 1, 1).isoformat()}, "_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 result_session is session
assert summary is None 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).""" """When no summary is available, should return (session, None)."""
ac = _make_autocompact() ac = _make_autocompact()
session = _make_session() 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 result_session is session
assert summary is None 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.""" """Internal Dream sessions should not reload or receive compact summaries."""
ac = _make_autocompact(ttl=15) ac = _make_autocompact(ttl=15)
mock_sm = MagicMock(spec=SessionManager) mock_sm = _mock_sessions()
ac.sessions = mock_sm ac.sessions = mock_sm
key = "dream:20260602-155256" key = "dream:20260602-155256"
ac._archiving.add(key) 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() mock_sm.get_or_create.assert_not_called()
assert result_session is session assert result_session is session
@@ -703,17 +710,17 @@ class TestPrepareSession:
assert key not in ac._archiving assert key not in ac._archiving
assert key not in ac._summaries 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.""" """If metadata _last_summary is not a dict, should return None summary."""
ac = _make_autocompact() ac = _make_autocompact()
session = _make_session(metadata={"_last_summary": "not a dict"}) 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 result_session is session
assert summary is None 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.""" """Hot path (_summaries) should take priority over metadata."""
ac = _make_autocompact() ac = _make_autocompact()
session = _make_session(metadata={ session = _make_session(metadata={
@@ -728,7 +735,7 @@ class TestPrepareSession:
"last_active": last_active.isoformat(), "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 is not None
assert summary["text"] == "Hot summary." assert summary["text"] == "Hot summary."
# After hot path pops, cold path would kick in on next call # After hot path pops, cold path would kick in on next call
+13 -12
View File
@@ -2,6 +2,7 @@
import asyncio import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
from unittest.mock import patch
import pytest import pytest
@@ -56,18 +57,18 @@ async def seed_history(bot, key):
]) ])
def schedule_idle_archive(bot, key): async def schedule_idle_archive(bot):
session = bot._loop.sessions.get_or_create(key)
session.updated_at = datetime.now() - timedelta(minutes=30)
bot._loop.sessions.save(session)
scheduled = [] 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 assert len(scheduled) == 1
return scheduled[0] return scheduled[0]
def assert_reply_and_summary(bot, key): async def assert_reply_and_summary(bot, key):
snapshot = bot.sessions.export(key) snapshot = await bot.sessions.export(key)
assert snapshot is not None assert snapshot is not None
assert ("assistant", "new reply") in [ assert ("assistant", "new reply") in [
(message["role"], message["content"]) for message in snapshot.messages (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 bot, provider = bot
key = "sdk:shared" key = "sdk:shared"
await seed_history(bot, key) 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() compact_attempted = asyncio.Event()
async def compact(): async def compact():
@@ -112,7 +113,7 @@ async def test_compaction_waits_for_active_sdk_turn_and_preserves_reply(
provider.release_summary.set() provider.release_summary.set()
compacted = await asyncio.wait_for(compaction, timeout=5) 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 summary_started_during_turn is False
assert {"role": "assistant", "content": "new reply"} in provider.summary_messages assert {"role": "assistant", "content": "new reply"} in provider.summary_messages
if trigger == "compact_session": if trigger == "compact_session":
@@ -123,7 +124,7 @@ async def test_compaction_waits_for_active_sdk_turn_and_preserves_reply(
await bot.aclose() await bot.aclose()
async with Nanobot(loop_factory(provider=ControlledProvider())) as restarted: async with Nanobot(loop_factory(provider=ControlledProvider())) as restarted:
assert_reply_and_summary(restarted, key) await assert_reply_and_summary(restarted, key)
finally: finally:
provider.release_turn.set() provider.release_turn.set()
provider.release_summary.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 bot, provider = bot
key = "sdk:shared" key = "sdk:shared"
await seed_history(bot, key) 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() turn_attempted = asyncio.Event()
async def run(): 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() provider.release_turn.set()
result = await asyncio.wait_for(turn, timeout=5) result = await asyncio.wait_for(turn, timeout=5)
assert result.content == "new reply" assert result.content == "new reply"
assert_reply_and_summary(bot, key) await assert_reply_and_summary(bot, key)
finally: finally:
provider.release_turn.set() provider.release_turn.set()
provider.release_summary.set() provider.release_summary.set()
+8 -7
View File
@@ -880,10 +880,10 @@ class TestCompactIdleSession:
"cli:incremental", "cli:incremental",
runtime=runtime, 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("user", "second user")
current.add_message("assistant", "second assistant") current.add_message("assistant", "second assistant")
sessions.save(current) await sessions.state.finish_turn(current)
second = await real_consolidator.compact_idle_session( second = await real_consolidator.compact_idle_session(
"cli:incremental", "cli:incremental",
runtime=runtime, runtime=runtime,
@@ -928,10 +928,10 @@ class TestCompactIdleSession:
"cli:cumulative-fallback", "cli:cumulative-fallback",
runtime=runtime, 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("user", "second user")
current.add_message("assistant", "newest working state") current.add_message("assistant", "newest working state")
sessions.save(current) await sessions.state.finish_turn(current)
fallback = await real_consolidator.compact_idle_session( fallback = await real_consolidator.compact_idle_session(
"cli:cumulative-fallback", "cli:cumulative-fallback",
@@ -971,10 +971,10 @@ class TestCompactIdleSession:
runtime=runtime, 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("user", "thanks")
current.add_message("assistant", "you're welcome") current.add_message("assistant", "you're welcome")
sessions.save(current) await sessions.state.finish_turn(current)
result = await real_consolidator.compact_idle_session( result = await real_consolidator.compact_idle_session(
"cli:nothing-after-summary", "cli:nothing-after-summary",
runtime=runtime, runtime=runtime,
@@ -999,9 +999,10 @@ class TestCompactIdleSession:
sessions.save(session) sessions.save(session)
async def append_during_archive(**_kwargs): 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("user", "late user")
current.add_message("assistant", "late assistant") current.add_message("assistant", "late assistant")
await sessions.state.finish_turn(current)
return LLMResponse(content="Summary.", finish_reason="stop") return LLMResponse(content="Summary.", finish_reason="stop")
mock_provider.chat_stream_with_retry.side_effect = append_during_archive mock_provider.chat_stream_with_retry.side_effect = append_during_archive
+4 -7
View File
@@ -402,9 +402,7 @@ class TestEphemeralDirect:
) )
with ( with (
patch("nanobot.agent.loop.SessionManager"),
patch("nanobot.agent.loop.SubagentManager") as mock_sub, patch("nanobot.agent.loop.SubagentManager") as mock_sub,
patch("nanobot.agent.loop.Consolidator"),
): ):
mock_sub.return_value.cancel_by_session = AsyncMock(return_value=0) mock_sub.return_value.cancel_by_session = AsyncMock(return_value=0)
loop = AgentLoop( loop = AgentLoop(
@@ -695,7 +693,7 @@ class TestEphemeralDirect:
for marker in [*markers.values(), "DREAM_AGENTS_MARKER"]: for marker in [*markers.values(), "DREAM_AGENTS_MARKER"]:
assert marker in system_prompt assert marker in system_prompt
assert request_text.count(marker) == 1 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: class TestEphemeralHooks:
@@ -725,13 +723,12 @@ class TestEphemeralHooks:
spy = MagicMock(spec=AgentHook) spy = MagicMock(spec=AgentHook)
spy.wants_streaming.return_value = False spy.wants_streaming.return_value = False
spy.before_iteration = AsyncMock() spy.finalize_content.side_effect = lambda context, content: content
spy.after_iteration = AsyncMock() spy.before_iteration = AsyncMock(return_value=None)
spy.after_iteration = AsyncMock(return_value=None)
with ( with (
patch("nanobot.agent.loop.SessionManager"),
patch("nanobot.agent.loop.SubagentManager") as mock_sub, patch("nanobot.agent.loop.SubagentManager") as mock_sub,
patch("nanobot.agent.loop.Consolidator"),
): ):
mock_sub.return_value.cancel_by_session = AsyncMock(return_value=0) mock_sub.return_value.cancel_by_session = AsyncMock(return_value=0)
loop = AgentLoop( loop = AgentLoop(
+30 -82
View File
@@ -25,91 +25,39 @@ class TestDreamSessionKey:
class TestPruneDreamSessions: class TestPruneDreamSessions:
def test_keeps_n_most_recent(self, tmp_path): async def test_keeps_n_most_recent(self, tmp_path):
import os manager = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "runtime")
import time 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( assert await manager.state.prune_dream_sessions(keep=10) == 5
tmp_path / "workspace", await manager.state.aclose()
sessions_root=tmp_path / "runtime",
)
sessions_dir = manager.sessions_dir
base_time = time.time() - 100 assert [manager.read_session_snapshot(key) is not None for key in keys] == [False] * 5 + [True] * 10
dream_paths = [] assert manager.read_session_snapshot("telegram:normal") is not None
for i in range(15): async def test_leaves_legacy_backup_untouched(self, tmp_path):
key = f"dream:20260528-{100000 + i:06d}" manager = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "runtime")
path = sessions_dir / f"{SessionManager._storage_key(key)}.jsonl" path = manager.sessions_dir / "dream_20260713-095959.jsonl"
path.write_text( path.write_text('legacy backup', encoding="utf-8")
f'{{"_type": "metadata", "key": "{key}", ' await manager.state.prune_dream_sessions(keep=0)
f'"created_at": "2026-05-28T10:00:{i:02d}", ' await manager.state.aclose()
f'"updated_at": "2026-05-28T10:00:{i:02d}"}}\n', assert path.read_text(encoding="utf-8") == 'legacy backup'
encoding="utf-8",
)
os.utime(path, (base_time + i, base_time + i))
dream_paths.append(path)
normal_path = sessions_dir / "telegram_123.jsonl" async def test_noop_when_under_limit(self, tmp_path):
normal_path.write_text('{"_type": "metadata"}\n', encoding="utf-8") manager = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "runtime")
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
for i in range(3): for i in range(3):
key = f"dream:20260528-{100000 + i:06d}" manager.save(manager.get_or_create(f"dream:20260528-{100000 + i:06d}"))
path = sessions_dir / f"{SessionManager._storage_key(key)}.jsonl" assert await manager.state.prune_dream_sessions(keep=10) == 0
path.write_text("{}", encoding="utf-8") await manager.state.aclose()
assert len(manager.list_sessions()) == 3
MemoryStore.prune_dream_sessions(manager, keep=10) async def test_empty_store_noop(self, tmp_path):
assert len(list(sessions_dir.glob("*.jsonl"))) == 3 manager = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "runtime")
assert await manager.state.prune_dream_sessions(keep=10) == 0
def test_empty_dir_noop(self, tmp_path): await manager.state.aclose()
manager = SessionManager( assert manager.list_sessions() == []
tmp_path / "workspace",
sessions_root=tmp_path / "runtime",
)
MemoryStore.prune_dream_sessions(manager, keep=10)
assert list(manager.sessions_dir.glob("*.jsonl")) == []
+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=[]) loop.tools.get_definitions = MagicMock(return_value=[])
session = loop.sessions.get_or_create("cli:test") session = await loop.sessions.state.import_messages("cli:test", _populated_session(30).messages)
session.messages = _populated_session(30).messages
expected_history = session.get_history() expected_history = session.get_history()
loop.provider.aclose = AsyncMock() loop.provider.aclose = AsyncMock()
result = await loop.process_direct("hello", session_key="cli:test") 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 import pytest
from agent.session_helpers import mock_session_manager
from nanobot.agent.context import TranscriptInput from nanobot.agent.context import TranscriptInput
from nanobot.agent.hook import ( from nanobot.agent.hook import (
AgentHook, AgentHook,
@@ -438,7 +439,7 @@ def _make_loop(tmp_path, hooks=None, hook_factories=None):
provider.generation.max_tokens = 4096 provider.generation.max_tokens = 4096
with patch("nanobot.agent.loop.ContextBuilder"), \ 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.SubagentManager") as mock_sub_mgr, \
patch("nanobot.agent.loop.Consolidator"): patch("nanobot.agent.loop.Consolidator"):
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0) mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
+3 -3
View File
@@ -596,10 +596,10 @@ class TestToolEventProgress:
calls += 1 calls += 1
if calls == 1: if calls == 1:
await on_content_delta("old partial") 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", channel="websocket", sender_id="u", chat_id="test", content="new question",
metadata={"_wants_stream": True}, metadata={"_wants_stream": True},
)) )))
return LLMResponse(content="old partial", finish_reason="length") return LLMResponse(content="old partial", finish_reason="length")
has_followup = any( has_followup = any(
"new question" in str(message.get("content", "")) "new question" in str(message.get("content", ""))
@@ -869,7 +869,7 @@ class TestToolEventProgress:
session.add_message("user", "Run this in the background") session.add_message("user", "Run this in the background")
session.metadata.update({"webui": True, "title": "Existing title"}) session.metadata.update({"webui": True, "title": "Existing title"})
loop.sessions.save(session) 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( dispatch = asyncio.create_task(run_session(loop, InboundMessage(
channel="system", channel="system",
sender_id="subagent", 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", channel="websocket", sender_id="user", chat_id="chat", content="Inspect configuration",
metadata={"webui": True, "webui_turn_id": "user-request", "message_id": "user-message"}, 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(): with coordinator.connected():
if late_result: if late_result:
provider.chat_stream_with_retry = AsyncMock(side_effect=[ 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", channel="websocket", sender_id="user", chat_id="chat", content="New request B",
metadata={"webui": True, "webui_turn_id": "request-b", "message_id": "message-b"}, metadata={"webui": True, "webui_turn_id": "request-b", "message_id": "message-b"},
), asyncio.Queue()) ), asyncio.Queue())
save_completed_subagent(loop, "task-a", request.session_key) await save_completed_subagent(loop, "task-a", request.session_key)
request = InboundMessage( request = InboundMessage(
channel="system", sender_id="subagent", chat_id=request.session_key, channel="system", sender_id="subagent", chat_id=request.session_key,
content="Background check for the original request completed", 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 import pytest
from agent.session_helpers import mock_session_manager
from nanobot.agent.context import TranscriptInput from nanobot.agent.context import TranscriptInput
from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission from nanobot.agent.goal_permission import goal_mutation_allowed, goal_mutation_permission
from nanobot.agent.tools.context import RequestContext from nanobot.agent.tools.context import RequestContext
@@ -46,7 +47,7 @@ def _make_loop(tmp_path):
provider.generation = GenerationSettings() provider.generation = GenerationSettings()
with patch("nanobot.agent.loop.ContextBuilder"), \ 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.SubagentManager") as mock_sub_mgr:
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0) mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path) 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 = loop.sessions.get_or_create("cli:direct")
session.add_message("user", "Let's agree on the migration implementation.") session.add_message("user", "Let's agree on the migration implementation.")
session.add_message("assistant", "Use the staged migration plan and run integration tests.") session.add_message("assistant", "Use the staged migration plan and run integration tests.")
loop.sessions.save(session)
result = await loop._process_message( result = await loop._process_message(
InboundMessage( 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 is not None
assert result.content == "done" assert result.content == "done"
assert goal_mutation_allowed() is False assert goal_mutation_allowed() is False
session = await loop.sessions.state.get(session.key)
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed" assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
first_request = provider.chat_stream_with_retry.await_args_list[0].kwargs["messages"] first_request = provider.chat_stream_with_retry.await_args_list[0].kwargs["messages"]
assert "staged migration plan" in str(first_request) 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 second_wire[3]["content"].startswith("second turn")
assert len(provider_calls) == 2 assert len(provider_calls) == 2
session = await loop.sessions.state.get(session.key)
persisted_first_user = session.messages[0] persisted_first_user = session.messages[0]
assert persisted_first_user["content"] == first_wire[1]["content"] assert persisted_first_user["content"] == first_wire[1]["content"]
assert public_history_message(persisted_first_user)["content"] == "first turn $review" 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"] request = provider.chat_stream_with_retry.await_args.kwargs["messages"]
assert "What does this mean?" in str(request) assert "What does this mean?" in str(request)
assert "the selected answer excerpt" 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 "the selected answer excerpt" in str(session.messages[0]["content"])
assert public_history_message(session.messages[0])["content"] == "What does this mean?" 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" 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) 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"} 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( InboundMessage(
channel="websocket", channel="websocket",
sender_id="cron", 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 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) 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] = [ session.metadata[PENDING_FOLLOWUPS_KEY] = [
{ {
"id": "followup-1", "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( InboundMessage(
channel="websocket", channel="websocket",
sender_id="user", 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 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) 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( InboundMessage(
channel="websocket", channel="websocket",
sender_id="trigger", 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 assert generated is True
session = await loop.sessions.state.get(session.key)
assert session.metadata[WEBUI_TITLE_METADATA_KEY] == "优化 WebUI 侧边栏" assert session.metadata[WEBUI_TITLE_METADATA_KEY] == "优化 WebUI 侧边栏"
loop.provider.chat_stream_with_retry.assert_awaited_once() 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 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 列表。") unified.add_message("assistant", "以下是临期 IP 列表。")
chat = loop.sessions.get_or_create("websocket:chat-existing") chat = loop.sessions.get_or_create("websocket:chat-existing")
chat.metadata[WEBUI_TITLE_METADATA_KEY] = "Existing title" chat.metadata[WEBUI_TITLE_METADATA_KEY] = "Existing title"
loop.sessions.save(chat)
loop.sessions.save(unified) loop.sessions.save(unified)
generated = await maybe_generate_webui_title_after_turn( 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( loop.provider.chat_stream_with_retry = AsyncMock(
return_value=LLMResponse(content="done", provider_state=state) 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( await loop._run_agent_loop(
TranscriptInput( 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) public_payload = loop.sessions.read_session_file(session.key)
assert public_payload is not None assert public_payload is not None
assert "private-checkpoint-blob" not in json.dumps(public_payload) assert "private-checkpoint-blob" not in json.dumps(public_payload)
raw = loop.sessions._get_session_path(session.key).read_text(encoding="utf-8") stored = loop.sessions.read_session_snapshot(session.key)
assert "private-checkpoint-blob" in raw assert stored is not None and stored.provider_state is not None
assert stored.provider_state.payload == state.payload
@pytest.mark.asyncio @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 = loop.sessions.get_or_create("cli:subagent-crash")
session.provider_state = _provider_state() session.provider_state = _provider_state()
loop.sessions.save(session) loop.sessions.save(session)
save_completed_subagent(loop, "sub-1", session.key) await save_completed_subagent(loop, "sub-1", session.key)
msg = InboundMessage( msg = InboundMessage(
channel="system", 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 = loop.sessions.get_or_create("cli:subagent-prompt-crash")
session.provider_state = _provider_state() session.provider_state = _provider_state()
loop.sessions.save(session) loop.sessions.save(session)
save_completed_subagent(loop, "sub-1", session.key) await save_completed_subagent(loop, "sub-1", session.key)
msg = InboundMessage( msg = InboundMessage(
channel="system", 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 = loop.sessions.get_or_create("cli:subagent-redelivery")
session.provider_state = _provider_state() session.provider_state = _provider_state()
loop.sessions.save(session) loop.sessions.save(session)
save_completed_subagent(loop, "sub-1", session.key) await save_completed_subagent(loop, "sub-1", session.key)
msg = InboundMessage( msg = InboundMessage(
channel="system", channel="system",
sender_id="subagent", 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 = loop.sessions.get_or_create("cli:subagent-compat-crash")
session.provider_state = _provider_state() session.provider_state = _provider_state()
loop.sessions.save(session) loop.sessions.save(session)
save_completed_subagent(loop, "sub-1", session.key) await save_completed_subagent(loop, "sub-1", session.key)
msg = InboundMessage( msg = InboundMessage(
channel="system", channel="system",
@@ -1712,7 +1715,8 @@ async def test_process_message_uses_explicit_session_for_goal_context(
assert result is not None assert result is not None
assert result.content == "ok" assert result.content == "ok"
kwargs = loop._run_agent_loop.call_args.kwargs 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 kwargs["request_context"].session_key == "system"
assert GOAL_STATE_KEY not in kwargs["session"].metadata 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 from nanobot.agent.runner import AgentRunResult
loop = _make_full_loop(tmp_path) 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] = {} seen: dict[str, str | None] = {}
async def fake_run(spec): async def fake_run(spec):
assert callable(spec.continuation_callback) assert callable(spec.continuation_callback)
session.metadata[GOAL_STATE_KEY] = { await loop.sessions.state.update_metadata(session.key, {GOAL_STATE_KEY: {
"status": "active", "status": "active",
"objective": "Goal created during this runner call.", "objective": "Goal created during this runner call.",
} }})
seen["goal_continue"] = spec.continuation_callback() seen["goal_continue"] = await spec.continuation_callback()
return AgentRunResult( return AgentRunResult(
final_content="ok", final_content="ok",
messages=[{"role": "assistant", "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): async def interrupted_run_agent_loop(_transcript_input, *, session=None, **_kwargs):
assert session is not None assert session is not None
loop._set_runtime_checkpoint( await loop._set_runtime_checkpoint(
session, session,
{ {
"assistant_message": { "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") first_msg = InboundMessage(channel="feishu", sender_id="u1", chat_id="c4", content="keep progress")
task = asyncio.create_task(loop._process_message(first_msg)) task = asyncio.create_task(loop._process_message(first_msg))
loop._active_tasks[first_msg.session_key] = {task} 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_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) 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("user", "question")
session.add_message("assistant", "working") session.add_message("assistant", "working")
loop.sessions.save(session) 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() runtime = loop.llm_runtime()
seen: dict[str, object] = {} 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 @pytest.mark.asyncio
async def test_system_subagent_followup_does_not_log_content(tmp_path: Path) -> None: async def test_system_subagent_followup_does_not_log_content(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path) 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): async def fake_run_agent_loop(transcript_input, **_kwargs):
initial_messages = _assembled_messages(loop.context, transcript_input) 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 @pytest.mark.asyncio
async def test_system_subagent_followup_uses_common_turn_lifecycle(tmp_path: Path) -> None: async def test_system_subagent_followup_uses_common_turn_lifecycle(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path) 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] = [] visited: list[str] = []
for name in ( 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] loop._run_agent_loop = fake_run_agent_loop # type: ignore[method-assign]
for idx in range(3): 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( await loop._process_message(
InboundMessage( InboundMessage(
channel="system", 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 = loop.sessions.get_or_create("slack:C123:1700.42")
thread_session.add_message("user", "thread question") thread_session.add_message("user", "thread question")
loop.sessions.save(thread_session) 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] = {} 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, 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, "first question"))
await loop._process_message(_message(key, "second 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": if selection == "explicit_empty":
kwargs["tools"] = ToolRegistry() kwargs["tools"] = ToolRegistry()
elif selection == "disable_all": elif selection == "disable_all":
session = loop.sessions.get_or_create(key) await loop.sessions.state.get(key)
session.policy = SessionPolicy(disabled_tools=frozenset(loop.tools.tool_names)) await loop.sessions.state.set_policy(key, SessionPolicy(disabled_tools=frozenset(loop.tools.tool_names)))
try: try:
response = await loop.process_direct("Handle this request", session_key=key, **kwargs) 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 loop.max_tool_result_chars = 2048
key = "websocket:privacy-regression" key = "websocket:privacy-regression"
if privacy == "temporary": if privacy == "temporary":
loop.sessions.get_or_create_transient(key) await loop.sessions.state.register_transient(key)
else: else:
session = loop.sessions.get_or_create(key) await loop.sessions.state.get(key)
session.policy = SessionPolicy(log_content=privacy != "quiet") await loop.sessions.state.set_policy(key, SessionPolicy(log_content=privacy != "quiet"))
secret = "synthetic-private-query-测试" secret = "synthetic-private-query-测试"
text = "synthetic-private-result-" * 1000 text = "synthetic-private-result-" * 1000
image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,c3ludGhldGlj"}} 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: async def test_direct_transient_run_never_spills_before_cancellation(tmp_path) -> None:
loop = _loop(tmp_path, []) 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.max_tool_result_chars = 100
loop.tools.prepare_call = MagicMock(return_value=(None, {}, None)) loop.tools.prepare_call = MagicMock(return_value=(None, {}, None))
loop.tools.execute = AsyncMock(return_value="synthetic large result" * 1000) 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, []) loop = _loop(tmp_path, [])
key = "websocket:synthetic-worker-error" key = "websocket:synthetic-worker-error"
if private: if private:
loop.sessions.get_or_create_transient(key) await loop.sessions.state.register_transient(key)
else: else:
loop.sessions.get_or_create(key) await loop.sessions.state.get(key)
secret = "synthetic-private-worker-content" secret = "synthetic-private-worker-content"
if failure == "runner": if failure == "runner":
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=ValueError(secret)) 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") durable.add_message("user", "durable question")
loop.sessions.save(durable) loop.sessions.save(durable)
key = "websocket:transient-unified" 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")) 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] == [ assert [public_history_message(message)["content"] for message in transient.messages] == [
"private question", "private question",
"private answer", "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: async def test_missing_required_session_cannot_fall_back_to_disk(tmp_path) -> None:
loop = _loop(tmp_path, []) loop = _loop(tmp_path, [])
key = "websocket:transient-stale" key = "websocket:transient-stale"
loop.sessions.get_or_create_transient(key) await loop.sessions.state.register_transient(key)
loop.sessions.invalidate(key) loop.sessions.invalidate(key)
with pytest.raises(RuntimeError, match="required session is not active"): 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) task_id, = loop.subagents.statuses_for_session(key)
notice = await asyncio.wait_for(loop.bus.consume_inbound(), timeout=2) notice = await asyncio.wait_for(loop.bus.consume_inbound(), timeout=2)
assert notice.require_existing_session 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 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) == {} 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 key not in loop._pending_queues
assert await loop._process_message(notice) is None assert await loop._process_message(notice) is None
loop.provider.chat_stream_with_retry.assert_not_awaited() 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" key = "websocket:transient-cancelled"
previous_file_state = loop._file_state_store.for_session(key) previous_file_state = loop._file_state_store.for_session(key)
loop.sessions.get_or_create_transient( await loop.sessions.state.register_transient(
key, key,
disabled_tools={"create_goal", "update_goal", "subagent", "cron"}, 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, channel="cli", sender_id="user", chat_id="test", content=command,
)) ))
async with asyncio.timeout(3): 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) await asyncio.sleep(0)
assert len(calls) == 1 assert len(calls) == 1
release.set() release.set()
await asyncio.wait_for(asyncio.gather(*loop._active_tasks["cli:test"]), 5) 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 process.await_count == 1
assert permissions[:3] == [False, True, True] assert permissions[:3] == [False, True, True]
assert "Discuss the migration" in calls[1] 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 "only be started by a user" in response.content
assert loop._pending_queues == {} assert loop._pending_queues == {}
assert goal_mutation_allowed() is False 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: finally:
await loop.aclose() 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": if boundary == "empty":
return LLMResponse(content="") return LLMResponse(content="")
return LLMResponse(content="The migration plan is ready.") 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 assert goal_mutation_allowed() is True
return LLMResponse(content=None, tool_calls=[ToolCallRequest( return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id="create", name="create_goal", 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( await run_session(loop, InboundMessage(
channel="cli", sender_id="user", chat_id="test", content="Discuss the migration.", 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" assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
goal_calls = [call for call in calls if "Goal Runtime Guidance" in call] goal_calls = [call for call in calls if "Goal Runtime Guidance" in call]
assert goal_calls 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): async def test_generated_goal_input_survives_pending_followup_recovery(tmp_path):
from nanobot.command.router import CommandContext 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 = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "test-model" 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, raw=message.content, loop=loop, is_user_turn=True,
)) ))
assert isinstance(generated, InboundMessage) assert isinstance(generated, InboundMessage)
session = loop.sessions.get_or_create(message.session_key) assert await loop.sessions.state.queue_followup(message.session_key, generated)
assert record_pending_followup(session, generated)
loop.sessions.save(session)
finally: finally:
await loop.aclose() await loop.aclose()
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model") 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) recovered, = pending_followups(session)
responses = iter([ responses = iter([
LLMResponse(content=None, tool_calls=[ToolCallRequest( 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): async with asyncio.timeout(5):
while (await loop.bus.consume_outbound()).content != "done": while (await loop.bus.consume_outbound()).content != "done":
pass pass
session = await loop.sessions.state.get(message.session_key)
assert session.metadata[GOAL_STATE_KEY]["status"] == "completed" assert session.metadata[GOAL_STATE_KEY]["status"] == "completed"
assert pending_followups(session) == [] assert pending_followups(session) == []
assert sum(row.get("content") == message.content for row in session.messages) == 1 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): with goal_mutation_permission(True):
await loop._process_message(message, session_key="cli:test") await loop._process_message(message, session_key="cli:test")
assert goal_mutation_allowed() is True 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"] final_request = provider.chat_stream_with_retry.await_args.kwargs["messages"]
assert "create_goal is unavailable for this turn" in str(final_request) assert "create_goal is unavailable for this turn" in str(final_request)
assert goal_mutation_allowed() is False assert goal_mutation_allowed() is False
+192 -4
View File
@@ -3,10 +3,12 @@
import asyncio import asyncio
import threading import threading
from copy import deepcopy from copy import deepcopy
from unittest.mock import AsyncMock
import pytest import pytest
from nanobot.agent.hook import AgentHook from nanobot.agent.hook import AgentHook
from nanobot.agent.runner import AgentRunner
from nanobot.agent.tools.context import current_request_context from nanobot.agent.tools.context import current_request_context
from nanobot.providers.base import LLMProvider, LLMResponse, LLMUsage from nanobot.providers.base import LLMProvider, LLMResponse, LLMUsage
from nanobot.runtime_context import public_history_message 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) loop.sessions.save(session)
runtime_loop = asyncio.get_running_loop() runtime_loop = asyncio.get_running_loop()
entered = asyncio.Event() entered = asyncio.Event()
hook_returned = asyncio.Event() snapshot_entered = asyncio.Event()
worker_finished = asyncio.Event() worker_finished = asyncio.Event()
release = threading.Event() release = threading.Event()
events = [] events = []
@@ -223,7 +225,6 @@ async def test_cancellation_during_run_cleanup_delivers_finally_once(
loop.process_direct("Blocked", session_key="cli:blocker"), loop.process_direct("Blocked", session_key="cli:blocker"),
)) ))
await asyncio.wait_for(entered.wait(), 5) await asyncio.wait_for(entered.wait(), 5)
hook_returned.set()
async def before_run(self, context): async def before_run(self, context):
events.append("before_run") events.append("before_run")
@@ -262,10 +263,22 @@ async def test_cancellation_during_run_cleanup_delivers_finally_once(
return original_read(path, *args, **kwargs) return original_read(path, *args, **kwargs)
monkeypatch.setattr(type(prompt_file), "read_text", read_text) 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()])) first = asyncio.create_task(loop.process_direct("First", session_key="cli:first", hooks=[Lifecycle()]))
try: try:
await asyncio.wait_for(hook_returned.wait(), 5) await asyncio.wait_for(snapshot_entered.wait(), 5)
await asyncio.sleep(0)
first.cancel() first.cancel()
with pytest.raises(asyncio.CancelledError): with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(first, 0.5) 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(): if entered.is_set():
await asyncio.wait_for(worker_finished.wait(), 5) await asyncio.wait_for(worker_finished.wait(), 5)
await loop.aclose() 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", model="test-model",
max_iterations=3, max_iterations=3,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS, 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, 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): async def test_runner_completes_without_a_continuation_request(run_spec, callback):
run_spec.continuation_callback = 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." continuation = "Continue working toward the active sustained goal."
run_spec.max_iterations = max_iterations run_spec.max_iterations = max_iterations
run_spec.finalize_on_max_iterations = finalize 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) 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( run_spec.runtime.provider.chat_stream_with_retry.return_value = LLMResponse(
content=None, finish_reason="error", content=None, finish_reason="error",
) )
callback = MagicMock(return_value="Continue working.") callback = AsyncMock(return_value="Continue working.")
run_spec.continuation_callback = callback run_spec.continuation_callback = callback
result = await AgentRunner().run(run_spec) 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.") return LLMResponse(content="The draft is complete.")
run_spec.runtime.provider.chat_stream_with_retry.side_effect = respond 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) result = await AgentRunner().run(run_spec)
+2 -1
View File
@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest import pytest
from agent.runner_helpers import make_run_spec 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 import TranscriptInput
from nanobot.agent.context_governance import ( from nanobot.agent.context_governance import (
BACKFILL_CONTENT, BACKFILL_CONTENT,
@@ -80,7 +81,7 @@ def _make_loop(tmp_path):
provider.get_default_model.return_value = "test-model" provider.get_default_model.return_value = "test-model"
with patch("nanobot.agent.loop.ContextBuilder"), \ 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.SubagentManager") as mock_sub_mgr:
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0) mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path) 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" provider.get_default_model.return_value = "test-model"
with patch("nanobot.agent.loop.ContextBuilder"), \ with patch("nanobot.agent.loop.ContextBuilder"), \
patch("nanobot.agent.loop.SessionManager"), \
patch("nanobot.agent.loop.SubagentManager") as mock_sub_mgr: 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.cancel_by_session = AsyncMock(return_value=0)
mock_sub_mgr.return_value.close = AsyncMock() mock_sub_mgr.return_value.close = AsyncMock()
@@ -393,7 +392,7 @@ async def test_goal_continuation_precedes_terminal_wait():
continuation_checks = 0 continuation_checks = 0
terminal_waits = 0 terminal_waits = 0
def continue_goal() -> str | None: async def continue_goal() -> str | None:
nonlocal continuation_checks nonlocal continuation_checks
continuation_checks += 1 continuation_checks += 1
return "Continue the active goal." if continuation_checks == 1 else None 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) 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() pending_queue = asyncio.Queue()
await pending_queue.put(InboundMessage( await pending_queue.put(InboundMessage(
channel="telegram", channel="telegram",
@@ -1444,9 +1443,9 @@ async def test_persistent_conversion_error_does_not_drop_later_session_inputs(tm
calls += 1 calls += 1
if calls == 1: if calls == 1:
for content in ["before", "bad", "after"]: 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, channel="cli", sender_id="u", chat_id="c", content=content,
)) )))
return LLMResponse(content="answer", finish_reason="stop") return LLMResponse(content="answer", finish_reason="stop")
async def context_provider(request): 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 @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.""" """A preloaded burst has one FIFO path before the worker can be scheduled."""
from nanobot.bus.events import InboundMessage, OutboundMessage from nanobot.bus.events import InboundMessage, OutboundMessage
loop = _make_loop(tmp_path) loop = _make_loop(tmp_path)
first_started = asyncio.Event() first_started = asyncio.Event()
all_enqueued = asyncio.Event()
release_first = asyncio.Event() release_first = asyncio.Event()
all_processed = asyncio.Event() all_processed = asyncio.Event()
processed: list[str] = [] processed: list[str] = []
followups = [f"follow-up-{index}" for index in range(40)] 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): async def _process_message(msg, **_kwargs):
processed.append(msg.content) 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()) 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" 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 len(loop._active_tasks[session_key]) == 1
assert loop._pending_queues[session_key].qsize() == len(followups) 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", model="test-model",
) )
loop.tools.get_definitions = MagicMock(return_value=[]) 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)] followups = [f"follow-up-{index:02}" for index in range(12)]
run_task = asyncio.create_task(loop.run()) 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 break
await asyncio.sleep(0.01) await asyncio.sleep(0.01)
loop.stop() 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 assert len(captured_messages) == 2
second_request = "\n".join( second_request = "\n".join(
+2 -2
View File
@@ -20,7 +20,7 @@ from nanobot.runtime_context import (
webui_quote_runtime_context, webui_quote_runtime_context,
) )
from nanobot.sdk.types import snapshot_from_session 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.session.webui_turns import _title_inputs
from nanobot.webui.transcript import _session_user_event 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]) 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", "") assert _title_inputs(session) == ("visible user text", "")
event = _session_user_event("websocket:chat", persisted) event = _session_user_event("websocket:chat", persisted)
assert event is not None 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)] 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") provider = _provider("shared-model")
shared_signature = ("shared-model", "auto", "same-settings") shared_signature = ("shared-model", "auto", "same-settings")
snapshots = { 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") session = loop.sessions.get_or_create("sdk:new-after-refresh")
assert runtime.model_preset == "deep" 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 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") catalog["fast"] = ModelPresetConfig(model="model-b")
loop.invalidate_runtime_config() loop.invalidate_runtime_config()
runtime = loop.runtime_for_session(session) runtime = (await loop.runtime_for_session(session))
await asyncio.sleep(0) await asyncio.sleep(0)
assert published == [] assert published == []
+18 -18
View File
@@ -1,5 +1,5 @@
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import MagicMock from unittest.mock import AsyncMock, MagicMock
import pytest import pytest
@@ -242,19 +242,19 @@ def test_self_tool_inspect_shows_model_preset(tmp_path) -> None:
assert "model_preset: 'fast'" in output 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 = { presets = {
"fast": ModelPresetConfig(model="openai/gpt-4.1"), "fast": ModelPresetConfig(model="openai/gpt-4.1"),
} }
loop = _make_loop(tmp_path, presets=presets) loop = _make_loop(tmp_path, presets=presets)
tool = _my_tool(loop) tool = _my_tool(loop)
result = tool._modify("model_preset", "fast") result = await tool._modify("model_preset", "fast")
assert "Error" not in result assert "Error" not in result
assert loop.model_preset == "fast" assert loop.model_preset == "fast"
assert loop.model == "openai/gpt-4.1" 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 = { presets = {
"default": ModelPresetConfig(model="base-model", context_window_tokens=1000), "default": ModelPresetConfig(model="base-model", context_window_tokens=1000),
"fast": ModelPresetConfig(model="openai/gpt-4.1", context_window_tokens=32_768), "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") loop = _make_loop(tmp_path, presets=presets, active_preset="fast")
tool = _my_tool(loop) tool = _my_tool(loop)
result = tool._modify("model_preset", "default") result = await tool._modify("model_preset", "default")
assert "Error" not in result assert "Error" not in result
assert "model is now 'base-model'" 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 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 = { presets = {
"default": ModelPresetConfig(model="base-model"), "default": ModelPresetConfig(model="base-model"),
"fast": ModelPresetConfig(model="openai/gpt-4.1"), "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) loop = _make_loop(tmp_path, presets=presets)
tool = _my_tool(loop) 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 result == "Error: model_preset 'missing' not found. Available: default, fast."
assert loop.model_preset is None assert loop.model_preset is None
assert loop.model == "base-model" 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 = { presets = {
"default": ModelPresetConfig(model="base-model"), "default": ModelPresetConfig(model="base-model"),
"fast": ModelPresetConfig(model="openai/gpt-4.1"), "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", session_key="cli:one",
metadata={"source": "self-tool"}, 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 "for the next turn" in result
assert model_preset_from_metadata( 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" 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 = _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'.") side_effect=ValueError("No API key configured for provider 'openai'.")
) )
tool = _my_tool(loop) tool = _my_tool(loop)
@@ -322,7 +322,7 @@ def test_self_tool_reports_session_preset_provider_configuration_error(tmp_path)
chat_id="one", chat_id="one",
session_key="cli: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'." 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), ("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, tmp_path,
key: str, key: str,
value: object, value: object,
@@ -347,24 +347,24 @@ def test_self_tool_rejects_instance_runtime_changes_in_session(
channel="cli", channel="cli",
chat_id="one", chat_id="one",
session_key=session.key, 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 "instance-wide and disabled" in result
assert "model_preset" in result assert "model_preset" in result
assert other_runtime.model == "base-model" assert other_runtime.model == "base-model"
assert other_runtime.context_window_tokens == 1000 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 = { presets = {
"fast": ModelPresetConfig(model="openai/gpt-4.1"), "fast": ModelPresetConfig(model="openai/gpt-4.1"),
} }
loop = _make_loop(tmp_path, presets=presets, active_preset="fast") loop = _make_loop(tmp_path, presets=presets, active_preset="fast")
tool = _my_tool(loop) 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 "Error" not in result
assert loop.model_preset is None assert loop.model_preset is None
assert loop.model == "anthropic/claude-opus-4-5" 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 import json
from datetime import datetime
from pathlib import Path from pathlib import Path
import pytest
from filelock import Timeout
from nanobot.providers.base import ProviderConversationState from nanobot.providers.base import ProviderConversationState
from nanobot.session.manager import Session, SessionManager from nanobot.session.manager import Session, SessionManager
class TestAtomicSave: def test_provider_state_round_trips_in_private_record_only(tmp_path: Path):
def test_save_creates_valid_jsonl(self, tmp_path: Path): mgr = SessionManager(tmp_path)
mgr = SessionManager(tmp_path) secret = "encrypted-reasoning-blob"
session = Session(key="test:1") session = Session(
session.add_message("user", "hello") key="test:provider-state",
session.add_message("assistant", "hi") provider_state=ProviderConversationState(
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(
kind="openai_responses", kind="openai_responses",
provider="openai:test", provider="openai:https://api.openai.com/v1",
model="gpt-5.6", model="gpt-5.6",
version=1, version=1,
payload={"items": []}, payload={
) "items": [
source = Session(key="test:state-source", provider_state=state) {
source.add_message("user", "hello") "type": "reasoning",
mgr.save(source) "encrypted_content": secret,
}
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"}),
] ]
) },
+ "\n", pending_messages=[{"role": "user", "content": "continue"}],
encoding="utf-8", ),
) )
session.add_message("user", "hello")
mgr.save(session)
loaded = mgr._load("test:bad-provider-state") mgr.invalidate(session.key)
assert loaded is not None loaded = mgr.get_or_create(session.key)
assert loaded.provider_state is None assert loaded.provider_state is not None
assert loaded.messages == [{"role": "user", "content": "safe"}] 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 test_provider_state_does_not_consume_list_preview_budget(
def _write_corrupt_jsonl(self, path: Path, lines: list[str]) -> None: tmp_path: Path,
path.parent.mkdir(parents=True, exist_ok=True) monkeypatch,
path.write_text("\n".join(lines) + "\n", encoding="utf-8") ):
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): assert mgr.list_sessions()[0]["preview"] == "visible preview"
mgr = SessionManager(tmp_path)
path = mgr._get_session_path("test:trunc")
valid_meta = json.dumps({ def test_clear_and_fork_discard_provider_state(tmp_path: Path):
"_type": "metadata", mgr = SessionManager(tmp_path)
"key": "test:trunc", state = ProviderConversationState(
"created_at": datetime.now().isoformat(), kind="openai_responses",
"updated_at": datetime.now().isoformat(), provider="openai:test",
"metadata": {}, model="gpt-5.6",
"last_consolidated": 0, version=1,
}) payload={"items": []},
valid_msg = json.dumps({"role": "user", "content": "hello"}) )
source = Session(key="test:state-source", provider_state=state)
source.add_message("user", "hello")
mgr.save(source)
self._write_corrupt_jsonl(path, [ fork = mgr.fork_session_before_user_index(
valid_meta, source.key,
valid_msg, "test:state-fork",
'{"role": "assistant", "content": "partial...', 1,
]) )
assert fork is not None
assert fork.provider_state is None
session = mgr._load("test:trunc") source.clear()
assert session is not None assert source.provider_state is 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"
+14 -140
View File
@@ -1,144 +1,18 @@
"""Regression tests for collision-resistant session filenames.""" """Session keys remain distinct even when their display filenames collide."""
import json
from datetime import datetime
from pathlib import Path
from nanobot.session.manager import Session, SessionManager from nanobot.session.manager import Session, SessionManager
from nanobot.utils.helpers import safe_filename
def _manager(tmp_path: Path, monkeypatch) -> SessionManager: def test_colliding_display_names_roundtrip_independently(tmp_path):
monkeypatch.setattr( manager = SessionManager(tmp_path)
"nanobot.session.manager.get_legacy_sessions_dir", keys = ("telegram:a_b", "telegram:a:b", "telegram:a/b", "telegram:你好")
lambda: tmp_path / "legacy_sessions", for key in keys:
) session = Session(key=key)
return SessionManager(tmp_path / "workspace") session.add_message("user", key)
manager.save(session)
assert manager.safe_key(keys[0]) == manager.safe_key(keys[1])
def _write_session_file(path: Path, key: str, content: str) -> None: assert len(manager.list_sessions()) == len(keys)
path.parent.mkdir(parents=True, exist_ok=True) for key in keys:
metadata = { assert manager.read_session_file(key)["messages"][0]["content"] == key
"_type": "metadata", manager.delete_session(keys[0])
"key": key, assert manager.read_session_snapshot(keys[1]) is not None
"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"
+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: def test_delete_session_removes_file_and_invalidates_cache(tmp_path: Path) -> None:
sm = _seed(tmp_path, "telegram:abc") sm = _seed(tmp_path, "telegram:abc")
file_path = sm._get_session_path("telegram:abc") assert sm.read_session_snapshot("telegram:abc") is not None
assert file_path.exists()
# Populate cache as a real consumer would. # Populate cache as a real consumer would.
cached = sm.get_or_create("telegram:abc") cached = sm.get_or_create("telegram:abc")
assert cached.messages assert cached.messages
assert sm.delete_session("telegram:abc") is True 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). # Subsequent get_or_create returns a fresh, empty Session (no stale cache).
fresh = sm.get_or_create("telegram:abc") fresh = sm.get_or_create("telegram:abc")
assert fresh.messages == [] 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: def test_read_session_file_does_not_populate_cache(tmp_path: Path) -> None:
sm = _seed(tmp_path, "telegram:abc") sm = _seed(tmp_path, "telegram:abc")
sm.invalidate("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") 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: def test_read_session_file_missing(tmp_path: Path) -> None:
sm = SessionManager(tmp_path) sm = SessionManager(tmp_path)
assert sm.read_session_file("nope:none") is None 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.""" """Independent turns and internal controls retain their session inbox semantics."""
import asyncio import asyncio
import threading
from unittest.mock import AsyncMock, MagicMock from unittest.mock import AsyncMock, MagicMock
import pytest import pytest
@@ -23,7 +24,6 @@ from nanobot.session.recovery import (
PENDING_FOLLOWUPS_KEY, PENDING_FOLLOWUPS_KEY,
REQUEST_ORIGIN_METADATA_KEY, REQUEST_ORIGIN_METADATA_KEY,
pending_followups, pending_followups,
record_pending_followup,
) )
from nanobot.triggers.local_session_turns import LOCAL_TRIGGER_META from nanobot.triggers.local_session_turns import LOCAL_TRIGGER_META
from nanobot.webui.recovery import RecoveryCoordinator from nanobot.webui.recovery import RecoveryCoordinator
@@ -46,6 +46,95 @@ async def loop(tmp_path):
await agent.aclose() 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: def _automation_message(kind: str, name: str) -> InboundMessage:
metadata = ( metadata = (
{ {
@@ -83,9 +172,6 @@ async def test_automation_turn_is_deferred_while_session_active(loop, kind):
async with asyncio.timeout(3): async with asyncio.timeout(3):
while not coordinator.deferred_queues.get(key): while not coordinator.deferred_queues.get(key):
await asyncio.sleep(0) await asyncio.sleep(0)
loop.stop()
await asyncio.wait_for(run_task, timeout=3)
assert pending.empty() assert pending.empty()
assert loop._active_tasks == {} assert loop._active_tasks == {}
assert coordinator.deferred_queues[key] == [msg] 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"]) @pytest.mark.parametrize("kind", ["cron", "local_trigger"])
async def test_submitted_automation_reports_pending_until_completed(loop, kind): async def test_submitted_automation_reports_pending_until_completed(loop, kind):
coordinator = loop._cron_turns if kind == "cron" else loop._local_trigger_turns 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 submit = loop.submit_cron_turn if kind == "cron" else loop.submit_local_trigger_turn
pending_ids = ( pending_ids = (
loop.pending_cron_job_ids_for_session 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 loop.provider.chat_stream_with_retry = chat
key = "websocket:test" key = "websocket:test"
loop._enqueue_session_message(InboundMessage( (await loop._enqueue_session_message(InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content="first", channel="websocket", sender_id="u", chat_id="test", content="first",
metadata={"webui": True}, metadata={"webui": True},
)) )))
await asyncio.wait_for(started.wait(), timeout=3) 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", channel="websocket", sender_id="u", chat_id="test", content="cancel me",
metadata={"webui": True}, metadata={"webui": True},
)) )))
if not followup_still_queued: if not followup_still_queued:
consumed = loop._pending_queues[key].get_nowait() 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): async def test_cancel_preserves_followups_accepted_after_cancellation_started(loop):
key = "websocket:test" key = "websocket:test"
session = loop.sessions.get_or_create(key) session = await loop.sessions.state.get(key)
def journal(content): async def journal(content):
record_pending_followup(session, InboundMessage( await loop.sessions.state.queue_followup(key, InboundMessage(
channel="websocket", sender_id="u", chat_id="test", content=content, 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() started = asyncio.Event()
cancelling = asyncio.Event() cancelling = asyncio.Event()
release = 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)) stop = asyncio.create_task(loop._cancel_active_tasks(key))
try: try:
await asyncio.wait_for(cancelling.wait(), timeout=3) await asyncio.wait_for(cancelling.wait(), timeout=3)
journal("new followup") await journal("new followup")
finally: finally:
release.set() release.set()
await stop await stop
@@ -422,7 +507,7 @@ async def test_ingress_sources_share_one_session_worker(loop, bus_running):
if bus_running: if bus_running:
await loop.bus.publish_inbound(first) await loop.bus.publish_inbound(first)
else: else:
loop._enqueue_session_message(first) (await loop._enqueue_session_message(first))
await asyncio.wait_for(started.wait(), timeout=3) await asyncio.wait_for(started.wait(), timeout=3)
cron = asyncio.create_task(loop.submit_cron_turn(_automation_message("cron", "cron"))) cron = asyncio.create_task(loop.submit_cron_turn(_automation_message("cron", "cron")))
trigger = asyncio.create_task(loop.submit_local_trigger_turn( 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(): while loop._pending_queues[key].empty():
await asyncio.sleep(0) await asyncio.sleep(0)
else: else:
loop._enqueue_session_message(second) (await loop._enqueue_session_message(second))
compact = InboundMessage(channel="websocket", sender_id="u", chat_id="test", content="/compact") compact = InboundMessage(channel="websocket", sender_id="u", chat_id="test", content="/compact")
await loop._dispatch_command_inline(compact, key, compact.content, loop.commands.dispatch) await loop._dispatch_command_inline(compact, key, compact.content, loop.commands.dispatch)
assert len(loop._active_tasks[key]) == 1 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(): while loop._pending_queues["cli:test"].empty():
await asyncio.sleep(0) await asyncio.sleep(0)
elif complete_on_followup or len(requests) == 3: 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="done")
return LLMResponse( return LLMResponse(
content="working", finish_reason="tool_calls", 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 = SessionManager(loop.workspace).get_or_create(key)
persisted_origin = persisted.metadata[REQUEST_ORIGIN_METADATA_KEY] persisted_origin = persisted.metadata[REQUEST_ORIGIN_METADATA_KEY]
await loop.tools.get("message").execute(content="Continuation reply") 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="done")
return LLMResponse(content="working", finish_reason="tool_calls", tool_calls=[ return LLMResponse(content="working", finish_reason="tool_calls", tool_calls=[
ToolCallRequest(id=f"call-{len(requests)}", name="noop", arguments={}), 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) manager = SessionManager(tmp_path)
session = manager.get_or_create("websocket:chat-title") session = manager.get_or_create("websocket:chat-title")
session.metadata["title"] = "自动生成标题" session.metadata["title"] = "自动生成标题"
+31 -5
View File
@@ -4,6 +4,7 @@ import pytest
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import RuntimeModelChanged
from nanobot.config.schema import ModelPresetConfig from nanobot.config.schema import ModelPresetConfig
from nanobot.nanobot import Nanobot from nanobot.nanobot import Nanobot
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse 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, preset_snapshot_loader=load_preset,
) )
loop.schedule_background = lambda coro: coro.close() # type: ignore[method-assign] loop.schedule_background = lambda coro: coro.close() # type: ignore[method-assign]
loop.set_session_model_preset("sdk:fast", "fast") (await loop.set_session_model_preset("sdk:fast", "fast"))
loop.set_session_model_preset("sdk:deep", "deep") (await loop.set_session_model_preset("sdk:deep", "deep"))
fast_reply, deep_reply = await asyncio.gather( fast_reply, deep_reply = await asyncio.gather(
loop.process_direct("hello", session_key="sdk:fast"), 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 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 @pytest.mark.asyncio
async def test_streamed_sdk_resolves_session_runtime_after_lock_admission(tmp_path) -> None: async def test_streamed_sdk_resolves_session_runtime_after_lock_admission(tmp_path) -> None:
base = RecordingProvider("base-model") 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] loop.schedule_background = lambda coro: coro.close() # type: ignore[method-assign]
session_key = "sdk:queued" 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()) lock = loop._session_locks.setdefault(session_key, asyncio.Lock())
await lock.acquire() await lock.acquire()
try: try:
run = await Nanobot(loop).run_streamed("hello", session_key=session_key) 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: finally:
lock.release() lock.release()
@@ -210,7 +236,7 @@ async def test_sdk_custom_model_preset_metadata_does_not_select_runtime(
metadata={"model_preset": custom_value}, metadata={"model_preset": custom_value},
) )
ingested_result = await bot.run("hello", session_key="sdk:custom-metadata") 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( restored = await bot.sessions.restore(
SessionSnapshot( SessionSnapshot(
key="sdk:restored-metadata", key="sdk:restored-metadata",
+4 -4
View File
@@ -16,7 +16,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest 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.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.session.recovery import RUNTIME_CHECKPOINT_KEY from nanobot.session.recovery import RUNTIME_CHECKPOINT_KEY
@@ -37,7 +37,7 @@ def _make_loop(tmp_path: Path) -> AgentLoop:
bus = MessageBus() bus = MessageBus()
provider = _make_provider() provider = _make_provider()
with patch("nanobot.agent.loop.ContextBuilder"), \ 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: patch("nanobot.agent.loop.SubagentManager") as mock_subagent_manager:
mock_subagent_manager.return_value.cancel_by_session = AsyncMock(return_value=0) mock_subagent_manager.return_value.cancel_by_session = AsyncMock(return_value=0)
return AgentLoop(bus=bus, provider=provider, workspace=tmp_path) 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()) workspace.__truediv__ = MagicMock(return_value=MagicMock())
with patch("nanobot.agent.loop.ContextBuilder"), \ 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: patch("nanobot.agent.loop.SubagentManager") as mock_subagent_manager:
mock_subagent_manager.return_value.cancel_by_session = AsyncMock(return_value=0) mock_subagent_manager.return_value.cancel_by_session = AsyncMock(return_value=0)
loop = AgentLoop(bus=bus, provider=provider, workspace=workspace) 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, \ assert checkpoint_key not in session.metadata, \
"Checkpoint metadata should be cleared after restore" "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" "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.config import Config
from nanobot.nanobot import Nanobot from nanobot.nanobot import Nanobot
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest 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.session.webui_turns import WebuiTurnRoutePolicy
from nanobot.utils.llm_runtime import LLMRuntime 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: if existing_parent:
parent.add_message("user", "Earlier durable question") parent.add_message("user", "Earlier durable question")
loop.sessions.save(parent) 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" secret = "private-delegation-marker"
source = loop.workspace / f"{secret}.txt" source = loop.workspace / f"{secret}.txt"
source.write_text(secret * 1000, encoding="utf-8") 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 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 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 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 list(loop.sessions.sessions_dir.glob("*.checkpoint.json"))
assert not (loop.workspace / ".nanobot" / "tool-results").exists() assert not (loop.workspace / ".nanobot" / "tool-results").exists()
assert loop.bus.inbound_size == 0 assert loop.bus.inbound_size == 0
loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Durable answer")) loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="Durable answer"))
await bot.run("Durable follow-up", session_key=key) await bot.run("Durable follow-up", session_key=key)
bot.sessions.flush() saved = json.dumps(loop.sessions.read_session_file(key))
saved = "\n".join(path.read_text() for path in loop.sessions.sessions_dir.glob("*.jsonl"))
assert "Durable answer" in saved assert "Durable answer" in saved
assert ("Earlier durable question" in saved) is existing_parent assert ("Earlier durable question" in saved) is existing_parent
assert secret not in saved 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: finally:
loop.stop() loop.stop()
await asyncio.wait_for(consumer, timeout=2) 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 @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) monkeypatch.setattr("nanobot.agent.loop._SUBAGENT_TERMINAL_WAIT_SECONDS", 0.01)
child_started, release_child, parent_idle = (asyncio.Event() for _ in range(3)) 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) saved = SessionManager(workspace, sessions_root=sessions_root).get_existing(session_key)
assert saved is not None assert saved is not None
saved_route = saved.metadata["_compaction_route"] 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() release_child.set()
late_reply = await next_reply("Late follow-up") 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, _, ctx = setup(tmp_path)
manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="private")) manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="private"))
task_id = await spawn(manager, ctx) 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 = manager.statuses_for_session("owner")[task_id]
snapshot.state = "cancelled" snapshot.state = "cancelled"
snapshot.owner = "other" snapshot.owner = "other"
+3 -3
View File
@@ -8,7 +8,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest 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.agent.memory import Consolidator
from nanobot.bus.outbound_events import StreamDeltaEvent, StreamEndEvent from nanobot.bus.outbound_events import StreamDeltaEvent, StreamEndEvent
from nanobot.config.schema import AgentDefaults from nanobot.config.schema import AgentDefaults
@@ -37,7 +37,7 @@ def _make_loop(*, tools_config=None):
workspace.__truediv__ = MagicMock(return_value=MagicMock()) workspace.__truediv__ = MagicMock(return_value=MagicMock())
with patch("nanobot.agent.loop.ContextBuilder"), \ 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.SubagentManager") as mock_sub_mgr:
mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0) mock_sub_mgr.return_value.cancel_by_session = AsyncMock(return_value=0)
loop = AgentLoop(bus=bus, provider=provider, workspace=workspace, tools_config=tools_config) 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): async def test_run_logs_and_continues_after_leaked_cancelled_error(self, monkeypatch):
loop, bus = _make_loop() loop, bus = _make_loop()
loop.aclose = AsyncMock() loop.aclose = AsyncMock()
loop.auto_compact.check_expired = MagicMock() loop.auto_compact.check_expired = AsyncMock()
warnings: list[str] = [] warnings: list[str] = []
calls = 0 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) 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 from nanobot.session import webui_turns as wth
sessions = SessionManager(tmp_path / "sessions") sessions = SessionManager(tmp_path / "sessions")
target = sessions.get_or_create("websocket:target") target = sessions.get_or_create("websocket:target")
target.metadata["webui"] = True target.metadata["webui"] = True
sessions.save(target) sessions.save(target)
await sessions.state.read(target.key)
factory = TurnDeliveryFactory( factory = TurnDeliveryFactory(
MessageBus(), MessageBus(),
route_policy=WebuiTurnRoutePolicy(sessions), 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) 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) sessions = SessionManager(tmp_path)
factory = TurnDeliveryFactory( factory = TurnDeliveryFactory(
MessageBus(), 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 = sessions.get_or_create(session_key)
session.metadata["webui"] = True session.metadata["webui"] = True
sessions.save(session)
await sessions.state.read(session_key)
first_visible_route = factory.create(msg, session_key).route first_visible_route = factory.create(msg, session_key).route
second_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