Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

docs(gateway): dedicated Gateway docs section, rewritten for readers, with Studio deep links (#6287)

t0saki59fff75e88a8
diff --git a/docs/.vitepress/theme/docs-sections.ts b/docs/.vitepress/theme/docs-sections.ts
index 5ea57b1aa..7ad06386a 100644
--- a/docs/.vitepress/theme/docs-sections.ts
+++ b/docs/.vitepress/theme/docs-sections.ts
@@ -33,7 +33,8 @@ export const sections: DocSection[] = [
p('agent-integrations/01-overview'),
p('workflows/01-overview'),
p('context-compilation/01-overview'),
- p('guides/17-vikingbot')
+ p('guides/17-vikingbot'),
+ p('guides/15-gateway')
]),
g('Learn, deploy and troubleshoot', '深入与排障', [
p('concepts/00-overview'),
@@ -110,14 +111,61 @@ export const sections: DocSection[] = [
p('agent-integrations/18-plugin-development'),
p('guides/working-memory-default-off')
]),
- g('OpenViking Gateway', 'OpenViking 网关', [
- p('guides/15-gateway'),
- p('guides/22-gateway-operations')
- ]),
g('VikingBot', 'VikingBot', [
p('guides/17-vikingbot'),
p('guides/12-vikingbot-metrics-validation')
])
+ ],
+ nextSteps: [
+ g('Clients without a plugin', '没有插件的客户端', [
+ p('guides/15-gateway')
+ ])
+ ]
+ },
+ // The entry page and the deployment page keep their guides/ paths so released Studio builds,
+ // the Helm README and openviking_gateway/config.py keep linking to them; every other gateway
+ // page lives in gateway/. Ownership does not depend on file location (see the top of this file).
+ {
+ id: 'gateway', en: 'Gateway', zh: '网关',
+ enNote: 'Give any API-key client memory through one proxy, then manage and run it.', zhNote: '用一个代理为 API Key 客户端接入记忆,并管理与运维。',
+ entry: 'guides/15-gateway', aliases: [],
+ groups: [
+ g('Understand the gateway', '了解网关', [
+ p('guides/15-gateway'),
+ p('gateway/01-how-it-works')
+ ]),
+ g('Get started', '上手与接入', [
+ p('gateway/02-quickstart'),
+ p('gateway/03-connect-clients')
+ ]),
+ g('Memory and tools', '记忆与工具', [
+ p('gateway/04-openviking-tools'),
+ p('gateway/05-long-conversations')
+ ]),
+ g('Manage in Studio', '在 Studio 中管理', [
+ p('gateway/06-manage-in-studio'),
+ p('gateway/07-upstreams'),
+ p('gateway/08-context-profiles'),
+ p('gateway/09-gateway-keys'),
+ p('gateway/10-overview-and-requests')
+ ]),
+ g('Deploy and operate', '部署与运维', [
+ p('guides/22-gateway-operations'),
+ p('gateway/11-security-and-data')
+ ]),
+ g('Troubleshoot and look up', '排障与参考', [
+ p('gateway/12-troubleshooting'),
+ p('gateway/13-configuration')
+ ])
+ ],
+ nextSteps: [
+ g('Related docs', '相关文档', [
+ p('api/25-gateway'),
+ p('guides/04-authentication'),
+ p('guides/12-public-access'),
+ p('guides/06-mcp-integration'),
+ p('agent-integrations/01-overview')
+ ])
]
},
{
diff --git a/docs/en/agent-integrations/01-overview.md b/docs/en/agent-integrations/01-overview.md
index 7b6260c99..52d5c3e6a 100644
--- a/docs/en/agent-integrations/01-overview.md
+++ b/docs/en/agent-integrations/01-overview.md
@@ -22,6 +22,8 @@ OpenViking can act as the long-term memory and context backend for many agent ru
| **Chat clients / SDK and API apps / other clients without a plugin** | [OpenViking Gateway](../guides/15-gateway.md) — point any client that takes a base URL and an API key at the gateway; it recalls memory and saves conversations with nothing to install in the client |
| **ZCode / AstrBot / …** | [Community Plugins](./08-community-plugins.md) — community-maintained integrations for various runtimes |
+Some agents, such as Claude Code, Codex, OpenCode, pi and DSH, can use either their plugin or OpenViking Gateway. To decide between them, see [Gateway or plugin?](../guides/15-gateway.md#gateway-or-plugin).
+
## Compare integrations side by side
For the concrete differences between integrations — tool surface, automatic recall, session and commit behaviour, compaction takeover, degradation and fault tolerance — see the [Capability Reference](./16-capability-reference.md), a cross-integration comparison matrix.
diff --git a/docs/en/api/25-gateway.md b/docs/en/api/25-gateway.md
index de8a4a490..da8df10e8 100644
--- a/docs/en/api/25-gateway.md
+++ b/docs/en/api/25-gateway.md
@@ -2,9 +2,9 @@
The management API lets you check permissions, configure upstreams and context profiles, issue gateway keys, and read usage and logs. All paths start with `/gateway/admin/` and are served by the gateway itself: when the gateway runs inside OpenViking Server, use the server's port (1933 by default); when it runs standalone, use the gateway's own port (1935 by default). The examples set `SERVER_URL` to that address without any path, such as `http://127.0.0.1:1933`.
-Model clients do not call these endpoints. They use a gateway key on `/gateway/v1/*`, `/gateway/api/v3/*` or `/gateway/api/compatible/v1/*`; see [OpenViking Gateway](../guides/15-gateway.md#connect-clients).
+Model clients do not call these endpoints. They use a gateway key on `/gateway/v1/*`, `/gateway/api/v3/*` or `/gateway/api/compatible/v1/*`; see [OpenViking Gateway](../gateway/03-connect-clients.md#connect-clients).
-## Credentials and account scope
+## Credentials and account scope {#credentials-and-account-scope}
Every management request carries an OpenViking API key in `X-API-Key` or `Authorization: Bearer`. The gateway asks OpenViking which account, user and role the key belongs to, and caches the answer for up to 30 seconds. Local dev mode needs no key; the caller is always the root identity `default/default`. The gateway does not support trusted authentication.
@@ -26,13 +26,13 @@ The management key works on its own, without an OpenViking API key, which suits
Read-only views of upstreams leave out the API key, header values and header names; they keep only `has_api_key` and `auth_mode`.
-## Access and discovery
+## Access and discovery {#access-and-discovery}
| Method | Path | Returns |
| --- | --- | --- |
| GET | `/gateway/admin/access` | The caller's permissions: `managed`, `can_write_objects`, `can_import_vlm`, `can_issue_for_others`, `role`, `account_id`, `user_id`, `warnings` |
| GET | `/gateway/admin/overview` | A summary of the latest 10,000 log records the caller can see: usage, cache hits, recall, saving problems, OpenViking status and log retention |
-| GET | `/gateway/admin/logs` | The newest log records the caller can see; `limit` defaults to 200, range 1–1000 |
+| GET | `/gateway/admin/logs` | A JSON array of the newest log records the caller can see, newest first; `limit` defaults to 200, range 1–1000. See [Log records](#log-records). |
| GET | `/gateway/admin/guides` | The client address `base_url`, plus `public_url_configured`; `base_url` is `public_url` followed by `/gateway`, or the request's origin followed by `/gateway` when `public_url` is empty |
| GET | `/gateway/admin/tools` | The OpenViking tools available to the caller, with names, descriptions and annotations, read with the caller's own OpenViking key (root: with the OpenViking key of a gateway key issued in this account, or the last catalog read, since OpenViking refuses root on `/mcp`) |
@@ -58,7 +58,35 @@ curl "$SERVER_URL/gateway/admin/access" \
If OpenViking rejects the API key, the response is 401 `openviking_http_401`.
-## Upstreams and context profiles
+### Log records {#log-records}
+
+The log holds metadata only, never message content. A record is written when a request to a model provider finishes, and when a conversation's saving status changes (`kind` is `capture`). Requests the gateway rejects before reaching a provider are not logged. Every field except `time` is optional and is left out when it does not apply.
+
+| Field | Meaning |
+| --- | --- |
+| `time` | When the record was written, in epoch seconds |
+| `request_id` | The gateway's ID for the request |
+| `kind` | `user`, `continuation`, `auxiliary`, `subagent`, `count`, `passthrough` or `capture`; see [Requests](../gateway/10-overview-and-requests.md#requests) |
+| `model` | The model name the client sent |
+| `status` | The provider's HTTP status |
+| `upstream_id`, `credential_id` | The upstream that served the request, and the gateway key that sent it |
+| `session`, `protocol` | The conversation and its protocol; use them to [reset saving](#gateway-keys) |
+| `degradation` | Issue code; see [Issues on degraded requests](../gateway/12-troubleshooting.md#issues-on-degraded-requests) |
+| `recall_reason`, `recall_count`, `recall_ms` | Memory search result code, entries added and search time; see [No memory is added](../gateway/12-troubleshooting.md#no-memory-is-added) |
+| `replay_hits` | Earlier messages whose memory was replayed unchanged |
+| `capture_status`, `capture_reason`, `capture_retry_at` | Saving status (`active`, `disabled`, `retrying` or `paused`), its reason, and the next retry in epoch seconds; see [Saving status](../gateway/10-overview-and-requests.md#saving-status) |
+| `tool_skip_reason` | Why the request got no OpenViking tools; see [When tools are not offered](../gateway/04-openviking-tools.md#when-tools-are-not-offered) |
+| `tool_stop_reason` | `token_budget` when the tool token budget refused further calls; see [Limits](../gateway/04-openviking-tools.md#limits) |
+| `compaction_failed` | Why compaction failed (with `still_over_threshold` the summary was kept); see [Long conversations hit the context limit](../gateway/12-troubleshooting.md#long-conversations-hit-the-context-limit) |
+| `context_tokens`, `context_window` | Estimated context size, and the window it was compared with |
+| `input_tokens`, `output_tokens`, `cached_tokens`, `cache_write_tokens` | Token usage summed over every provider call of the request, OpenViking tool rounds included. `input_tokens` includes cached and cache-write tokens. |
+| `duration_ms` | Time from sending the request to the provider until the reply finished |
+
+Fields that start with `first_upstream_` and `hidden_upstream_` split the token usage between the first provider call and the OpenViking tool rounds; the first-call cache hit rate uses the first group.
+
+`/overview` aggregates these records. Besides usage and cache figures, it returns `degradations` (issue code → count), `capture_issues` (conversations retrying or paused), `cache_alerts`, `openviking` (OpenViking's `status`, plus `reason` when degraded) and `log_retention_days`.
+
+## Upstreams and context profiles {#upstreams-and-context-profiles}
| Method | Path | Description |
| --- | --- | --- |
@@ -73,7 +101,7 @@ If OpenViking rejects the API key, the response is 401 `openviking_http_401`.
| PUT | `/gateway/admin/policies/{identifier}` | Create or replace a context profile |
| DELETE | `/gateway/admin/policies/{identifier}` | Delete a context profile no key uses |
-The caller chooses the IDs. `PUT` takes the complete object, and unknown fields fail validation. The meaning, default and range of every field are in the [Configuration reference](../guides/22-gateway-operations.md#configuration-reference).
+The caller chooses the IDs. `PUT` takes the complete object, and unknown fields fail validation. The meaning, default and range of every field are in the [Configuration reference](../gateway/13-configuration.md#configuration-reference).
An upstream's `api_key` and `headers` are write-only:
@@ -90,29 +118,36 @@ curl -X PUT "$SERVER_URL/gateway/admin/upstreams/openai?account_id=team" \
Deleting an object that gateway keys still use returns 409 `in_use` with `key_count`. Revoke those keys first. If you only want requests to stop reaching an upstream right away, turn it off instead of deleting it.
-### Upstream tests
+### Upstream tests {#upstream-tests}
`POST /gateway/admin/upstreams/{identifier}/test` supports two modes. An empty `{}` body checks the connection with `GET /v1/models`. A `{"model":"<model-name>"}` body sends one small, non-streaming generation request with the stored credentials and headers. The model name is resolved through the upstream's aliases. Model requests use the configured Chat Completions, Responses or Anthropic Messages endpoint, including an exact endpoint URL when path appending is off. When gateway tools are allowed, they include the account's OpenViking tools filtered by the default context profile; a temporary tool-catalog failure falls back to a request without tools. The model test does not set a reasoning effort, so the model uses its default.
The response includes `{ok, kind, status, reason, url}`, where `kind` is `connection` or `model`. Failed tests also include the upstream HTTP response in `response`, with `http_version`, `status`, `reason`, `headers`, `body` and an optional `truncated` flag. The body is limited to 16 KiB; `status` is left out when no response arrived. The timeout is the smaller of the configured upstream timeout and 60 seconds. Running either test requires write access; model tests make a real provider request and may incur a small charge.
-Anthropic tests send the key in both `x-api-key` and `Authorization: Bearer` and default `anthropic-version` to `2023-06-01` when the upstream headers do not set it. Chat Completions and Responses tests send only Bearer authentication. A `key_header` other than `authorization`, or `{api_key}` in `base_url`, changes this as described in [Credentials](../guides/22-gateway-operations.md#credentials); `url` keeps the `{api_key}` placeholder.
+Anthropic tests send the key in both `x-api-key` and `Authorization: Bearer` and default `anthropic-version` to `2023-06-01` when the upstream headers do not set it. Chat Completions and Responses tests send only Bearer authentication. A `key_header` other than `authorization`, or `{api_key}` in `base_url`, changes this as described in [Credentials](../gateway/07-upstreams.md#credentials); `url` keeps the `{api_key}` placeholder.
-| Provider response | `reason` | `ok` |
-| --- | --- | --- |
-| The Coding Plan upstream has not been approved for gateway use. No request is sent. | `coding_plan_blocked` | `false` |
-| A connection test of an exact endpoint (`append_endpoint_path` is `false`), which has no model list. No request is sent; run a model test instead. | `exact_endpoint_untestable` | `false` |
-| No API key to use: none is stored, or the upstream expects each client to send its own. No request is sent. | `upstream_key_missing` | `false` |
-| 2xx with a response matching the configured model protocol | `passed` | `true` |
-| 2xx with invalid JSON or a response that does not match the configured protocol | `invalid_response` | `false` |
-| 401 or 403 | `upstream_key_rejected` | `false` |
-| 400, 404, 405 or 422 | `model_request_rejected` | `false` |
-| 429 | `rate_limited` | `false` |
-| Network error, timeout, redirect or 5xx | `upstream_unavailable` | `false` |
+The two tests read the provider's response differently:
+
+| Test | Provider response | `reason` | `ok` |
+| --- | --- | --- | --- |
+| Connection | The upstream is an exact endpoint (`append_endpoint_path` is `false`), which has no model list. No request is sent; run a model test instead. | `exact_endpoint_untestable` | `false` |
+| Model | The Coding Plan upstream has not been approved for gateway use. No request is sent. | `coding_plan_blocked` | `false` |
+| Both | No API key to use: none is stored, or the upstream expects each client to send its own. No request is sent. | `upstream_key_missing` | `false` |
+| Connection | 2xx with a JSON object that holds a `data` list | `passed` | `true` |
+| Connection | Any other 2xx: invalid JSON, a body over 16 KiB, no `data` list, or an `error` field | `upstream_key_rejected` | `false` |
+| Connection | 404 or 405: the provider has no model list, so the key is not verified | `models_unavailable` | `true` |
+| Connection | 429: the address answered, but the key is not verified | `rate_limited` | `true` |
+| Model | 2xx with a response matching the configured model protocol | `passed` | `true` |
+| Model | Any other 2xx: invalid JSON, a body over 16 KiB, or a response that does not match the protocol | `invalid_response` | `false` |
+| Model | 429 | `rate_limited` | `false` |
+| Model | 404 or 405 | `model_request_rejected` | `false` |
+| Both | 400 or 422 | `model_request_rejected` | `false` |
+| Both | 401 or 403 | `upstream_key_rejected` | `false` |
+| Both | Network error, timeout, redirect, 5xx or any other status | `upstream_unavailable` | `false` |
-A passed connection test confirms reachability and, when `/v1/models` is available, the stored credentials. A 404 or 405 still allows a model test because some providers do not expose that endpoint. A passed model test confirms that the selected model completed this request. It does not verify other models or authorize Coding Plan use.
+A connection test that returns `passed` confirms reachability and the stored credentials. `models_unavailable` and `rate_limited` confirm only that the address is reachable; Studio shows them as **Connected** with a neutral badge. Run a model test to check the key. Coding Plan approval applies only to model tests, so a connection test of an unapproved Coding Plan upstream is still sent. A passed model test confirms that the selected model completed this request. It does not verify other models or authorize Coding Plan use.
-### Import VLM settings
+### Import VLM settings {#import-vlm-settings}
`POST /gateway/admin/upstreams/import-vlm` turns OpenViking Server's VLM credentials into upstreams in the selected account. It is available only in embedded deployments; a standalone gateway returns 404 `vlm_import_unavailable`.
@@ -133,7 +168,7 @@ Each imported upstream gets the fixed ID `vlm-<credential id>`, so importing aga
| `litellm_unsupported_route` | The LiteLLM route does not use the OpenAI Chat Completions API, such as `gemini/`, `bedrock/` or `vertex_ai/`. Add that provider as an upstream by hand. |
| `invalid_configuration` | The credential does not make a valid upstream, for example because the base URL is invalid. |
-## Gateway keys
+## Gateway keys {#gateway-keys}
| Method | Path | Description |
| --- | --- | --- |
@@ -186,13 +221,13 @@ curl -X POST "$SERVER_URL/gateway/admin/keys?account_id=team" \
Save the `key` from the response right away; the gateway keeps only its hash. `GET` returns the same fields without `key`. Gateway keys cannot be changed and have no `PUT`. To change the context profile, upstreams, models or user, issue a new key and revoke the old one.
-When the user's OpenViking API key is regenerated or the user is deleted, the gateway keys bound to it stop working and are deleted; the user's data stays. See [Gateway keys](../guides/22-gateway-operations.md#gateway-keys).
+When the user's OpenViking API key is regenerated or the user is deleted, the gateway keys bound to it stop working and are deleted; the user's data stays. See [Gateway keys](../gateway/09-gateway-keys.md#gateway-keys).
**Resetting saving.** The body is `{"session":"<session header value or the session from the log>","protocol":"chat"}`, where `protocol` is `chat`, `anthropic` or `responses`. On success the response is `{"status":"ready","message":"…"}`, and on the conversation's next request the gateway writes the full history to a new OpenViking session. If the conversation is not found, the response is 404 `not_found`.
-**Deleting data.** Both delete endpoints remove conversation content the gateway has not yet saved, and logs. Sessions and memories already stored in OpenViking are not affected. Retention and the other ways data is deleted are described in [Security and data](../guides/22-gateway-operations.md#security-and-data).
+**Deleting data.** Both delete endpoints remove conversation content the gateway has not yet saved, and logs. Sessions and memories already stored in OpenViking are not affected. Retention and the other ways data is deleted are described in [Security and data](../gateway/11-security-and-data.md).
-## Errors
+## Errors {#errors}
Error responses from the management API carry a stable top-level `reason` and a short English `detail`. Some carry extra fields, for example:
@@ -225,4 +260,4 @@ Check `reason`, not the text of `detail`. When the server does not have the gate
Other HTTP errors from OpenViking are reported as `openviking_http_<status>`. The gateway's own generic HTTP errors are reported as `gateway_http_<status>`, for example 405 `gateway_http_405` for an unsupported method.
-A 401 that a model client receives is not a management API error. It means the gateway key is missing, wrong or revoked, or the OpenViking key bound to it is no longer valid; see [Clients get an error from the gateway](../guides/22-gateway-operations.md#clients-get-an-error-from-the-gateway).
+A 401 that a model client receives is not a management API error. It means the gateway key is missing, wrong or revoked, or the OpenViking key bound to it is no longer valid; see [Clients get an error from the gateway](../gateway/12-troubleshooting.md#clients-get-an-error-from-the-gateway).
diff --git a/docs/en/configuration/01-server.md b/docs/en/configuration/01-server.md
index 246b12400..a002e200d 100644
--- a/docs/en/configuration/01-server.md
+++ b/docs/en/configuration/01-server.md
@@ -73,7 +73,7 @@ Optional sections use their defaults when omitted. Unknown fields in `ov.conf` a
| `log` | object | console | Log level, format, and file output |
| `telemetry` | object | disabled | OpenTelemetry tracing |
| `oauth` | object | disabled | MCP OAuth 2.1 |
-| `gateway` | object | disabled | OpenViking Gateway, the model API gateway that adds OpenViking memory to API-key clients. Unknown keys in this section are errors. See the [configuration reference](../guides/22-gateway-operations.md#configuration-reference) |
+| `gateway` | object | disabled | OpenViking Gateway, the model API gateway that adds OpenViking memory to API-key clients. Unknown keys in this section are errors. See the [configuration reference](../gateway/13-configuration.md#configuration-reference) |
| `prompts` | object | built-in templates | Custom prompt template directory |
| `ingest` | object | built-in defaults | Conversation-log ingestion |
| `output_language_override` | string | `""` | Force summary/memory language; empty means auto-detect |
diff --git a/docs/en/gateway/01-how-it-works.md b/docs/en/gateway/01-how-it-works.md
new file mode 100644
index 000000000..8027532cf
--- /dev/null
+++ b/docs/en/gateway/01-how-it-works.md
@@ -0,0 +1,142 @@
+---
+description: How OpenViking Gateway handles one turn, from recall and the opening context to replay and saving, and why it works this way.
+---
+
+# How OpenViking Gateway works
+
+Model APIs are stateless: the client resends the whole conversation with every request, and OpenViking Gateway works inside that loop. It adds memory to each new user message, records exactly what it added and puts it back on later requests, and saves finished turns to OpenViking. This page follows one turn through those steps for readers who want the mechanics before trusting the gateway with their requests; the terms it uses are defined in [Key terms](../guides/15-gateway.md#key-terms).
+
+## What happens in one turn {#what-happens-once-you-connect}
+
+![What happens in one turn: the gateway recognizes the conversation and the request type, puts earlier memory back exactly as it was, recalls only for the new message, forwards the request to the upstream in the same API and queues the turn for saving; below, how replay keeps the prompt cache hitting, and how saving and compaction work across turns](../../images/gateway/one-turn.en.svg)
+
+The gateway handles every request in the same order. Only a new user message triggers [recall](#what-the-model-sees); tool steps and housekeeping requests such as title generation reuse what was already added.
+
+| Step | What the gateway does | Details |
+| --- | --- | --- |
+| Recognize | Matches the request to its conversation on its own, and tells a new user message apart from tool steps, housekeeping and other request types. | [How conversations are recognized](03-connect-clients.md#how-conversations-are-recognized), [Request types](10-overview-and-requests.md#request-types) |
+| Replay | Puts every memory block it added earlier back on its message, exactly as it was. | [Replay and prompt caching](#replay) |
+| Recall | For a new user message only, searches OpenViking and appends what it finds. A new conversation also gets the opening context. | [What the model sees](#what-the-model-sees), [The opening context](#the-opening-context) |
+| Forward | Sends the request to the upstream in the same API it arrived in. | [Routing](07-upstreams.md#routing) |
+| Save | Queues the turn, and saves it once the next user message shows that the client kept it. | [When conversations are saved](#when-conversations-are-saved) |
+
+When a conversation nears the model's context window, the gateway also compacts it (see [Long conversations](#long-conversations)). The budgets, timings and switches on this page all come from the key's [context profile](08-context-profiles.md#context-profiles), where an admin can change or turn off each one.
+
+## What the model sees {#what-the-model-sees}
+
+When a request ends with a new user message, the gateway searches OpenViking with that message's text and appends the results to the end of the message. This is **recall**:
+
+```text
+What did we decide about the release date?
+
+<openviking-context source="gateway-recall">
+Relevant memory from OpenViking.
+<memory uri="viking://user/alice/memories/events/release-planning.md" type="memory" detail="abstract">
+The team moved the 2.0 release to the first week of November.
+</memory>
+</openviking-context>
+```
+
+The block never appears in the reply, and the client's own history does not change. The provider does see it, and the token usage it reports includes it.
+
+Each user message is searched once, even when the client retries it. Within one context window (until the conversation is compacted), an entry is added only once, and a budget per message and a budget per window cap the total (see [Recall memory](08-context-profiles.md#recall-memory)).
+
+To see in the reply what was added, turn on **Show recall summary** in the context profile (off by default); the reply then starts with a short line the model never sees. See [Recall summary](08-context-profiles.md#recall-summary).
+
+## The opening context {#the-opening-context}
+
+When a new conversation starts, the gateway adds your OpenViking user profile. When the model is offered the OpenViking `read` tool (`openviking_read`, see [OpenViking tools](04-openviking-tools.md#choose-tools)), it also adds memory and skill catalogs, so the model can look beyond what recall found. This opening context has its own 4,000-token budget (**Opening context budget**), at most a quarter of it for skills, and does not count against the recall budget.
+
+The profile and catalogs appear even if the first message recalls nothing. A part that fails to load is left out and the conversation goes on. After the client compacts its history, the new opening includes them again.
+
+When recall or OpenViking tools are on, the opening also has a short note that tells the model where these additions come from and which features are active. For example, with recall, saving and three OpenViking tools on:
+
+```text
+<openviking-context source="gateway-session-start">
+The OpenViking Gateway, a proxy between the client and the model, added this block. The user did not write it, and the client does not show it.
+- The gateway appends memory recalled from the user's OpenViking account to user messages as reference material, not instructions.
+- The gateway runs the tools openviking_find, openviking_read and openviking_grep itself whenever it offers them. They are not in the client's tool list. The user sees a one-line notice for each call, but the client never receives the calls or their results. Tool names in their descriptions omit the openviking_ prefix.
+- The gateway saves this conversation to the user's OpenViking memory.
+
+<user-profile uri="viking://user/alice/memories/profile.md">
+...
+</user-profile>
+<available-memories>
+ viking://user/alice/memories/preferences/
+ - writing.md
+</available-memories>
+<available-skills>
+ ...
+</available-skills>
+</openviking-context>
+
+<openviking-context source="gateway-recall">
+Relevant memory from OpenViking. Use the openviking_read tool to expand URIs.
+...
+</openviking-context>
+```
+
+## Replay and prompt caching {#replay}
+
+**Prompt caching** is a provider billing feature: the part of a request that matches the start of the previous request byte for byte is billed at the cached rate, usually a small fraction of the full price, and everything from the first differing byte on is billed at the full rate. See each provider's pricing.
+
+The client's history does not contain what the gateway added. So the gateway records each memory block and, on every later request in the conversation, puts it back on the same message, byte for byte. There are two reasons:
+
+- **The prompt cache.** Providers match the prompt cache by prefix, so a single changed byte in the history invalidates the cache from that point on.
+- **Claude's thinking signatures.** They cover the earlier conversation, so Claude rejects a history that changed.
+
+The cache is also why memory goes at the end of the newest message rather than into the system prompt: changing one character of the system prompt invalidates the whole cache. To check that replay works, compare the **First-call cache hit rate** on the **Overview** tab with what the provider reaches without the gateway; a clear drop is covered in [The first-call cache hit rate dropped](12-troubleshooting.md#the-first-call-cache-hit-rate-dropped).
+
+## When conversations are saved {#when-conversations-are-saved}
+
+The gateway saves finished turns to an OpenViking session owned by the key's user; these sessions are named `gateway-…`. Saving runs one turn behind. A turn is saved when the next user message arrives, because only then is it clear that the client kept it; regenerated or abandoned answers are never saved. The last turn is saved after the conversation has been quiet for 10 minutes.
+
+After saving, the gateway **commits** the session: OpenViking archives the older saved turns, keeping the newest messages in the session, and extracts memories from them in the background. A saved turn becomes memory only after a commit. A commit happens when the conversation has been quiet for 10 minutes, or when 20,000 tokens are waiting to be committed.
+
+What is left out:
+
+- What the gateway added, and client noise such as `<system-reminder>` blocks, are stripped before saving.
+- Sub-agent, housekeeping and token-count requests are never saved.
+
+The timings are set under [Save conversations](08-context-profiles.md#save-conversations), and the **Requests** tab shows each conversation's [saving status](10-overview-and-requests.md#saving-status).
+
+## Long conversations {#long-conversations}
+
+When a conversation reaches 90% of the model's context window (the default **Compact at**), the gateway compacts it: the same model writes a summary of the conversation so far, with a length cap, and from then on the summary replaces everything before the cut. The history shown in the client does not change. Each compaction costs one extra model request and one provider cache miss.
+
+When it compacts, which context window to set and what the summary contains are in [Long conversations in the gateway](05-long-conversations.md#long-conversations).
+
+## OpenViking tools {#openviking-tools}
+
+With OpenViking tools on, the model can search, read and, if an admin allows it, write OpenViking memory itself while it answers; new context profiles turn them on with only the read-only tools selected. The gateway runs the calls and replays the rounds on later turns, so the client never declares or runs these tools and sees only a one-line notice per call. See [OpenViking tools in the gateway](04-openviking-tools.md#agentic-memory-for-any-client).
+
+## Behaviors to expect {#what-to-expect}
+
+- **Recall waits up to 2 seconds.** The first model call of each new message waits for the OpenViking search, at most the profile's **Time limit** (2 seconds by default). If OpenViking times out or is down, the message goes to the model without memory and never gets it later.
+- **Settings apply to new conversations.** A conversation keeps the context profile and upstream it started with, so long-running clients such as Claude Code and Codex pick up a profile change only when they start a new conversation. See [When changes take effect](06-manage-in-studio.md#when-changes-take-effect).
+- **Changed history is saved again.** If the client edits or deletes earlier messages, regenerates an answer after it was saved, or compacts the conversation itself, the gateway saves the current full history to a new OpenViking session. Turns already saved stay in the old session.
+- **Very long sessions can hit the request size limit.** After the gateway compacts a conversation, the client still sends its full history, and request bodies over 32 MiB are rejected by default. See [Side effects](05-long-conversations.md#side-effects).
+- **One key means one memory owner.** Everyone who shares a key shares the memory of the OpenViking user behind it, so issue one key per person. See [One key per person](09-gateway-keys.md#one-key-per-person).
+- **Clients cannot sign in with a subscription.** Requests with a Claude subscription token are rejected. Configure the upstream with a provider API key, or put a subscription proxy behind the gateway as a [custom upstream](07-upstreams.md#custom-upstreams). Codex can use a ChatGPT subscription this way through CLIProxyAPI; see [Use a ChatGPT subscription](03-connect-clients.md#codex-chatgpt-subscription). For other subscription services, check their terms yourself.
+- **Responses needs the full history.** Responses requests that rely on state stored at the provider are forwarded without memory; see [Client requirements](04-openviking-tools.md#client-requirements).
+- **Other endpoints pass through.** Endpoints other than the three model APIs and the model list, such as embeddings, are forwarded without memory to the highest-priority upstream bound to the key that serves the requested model.
+
+## Why it works this way {#design-trade-offs}
+
+The table explains why the gateway's main design choices were made and what they cost, so you can judge whether it fits your setup:
+
+| Design | Choice and reason | Cost |
+| --- | --- | --- |
+| Where it plugs in | On the model call path instead of a plugin in every agent: clients that cannot install plugins can use it, and provider keys are managed in one place. | It cannot see the working directory; keeping projects' memory apart means a different OpenViking user per project. |
+| Who runs the tools | The gateway runs OpenViking tools during the reply, stores the rounds and replays them unchanged on the next turn: even clients with no tools and no MCP support get a model that uses memory on its own. | No per-call approval; clients must send the full history every turn; admins need to narrow the tool list and limits. |
+| Where memory goes | At the end of the newest user message, not in the system prompt: one changed character in the system prompt invalidates the whole cache, while appending at the end and replaying unchanged keeps the prefix stable. | The gateway must reliably record the exact text of every addition; a lost record costs one cache miss. |
+| When turns are saved | One turn behind: only when the next message brings the previous turn back is it clear the user kept it. | The last turn is saved only after **Save the latest reply after** (10 minutes by default). |
+| Long conversations | The gateway has the same model write the summary: only the gateway knows what the model actually received, and the summary request mostly hits the cache. | The turn that triggers compaction costs one extra, billed model call; text before the cut is no longer sent to the model. |
+| Local state | SQLite on one host, with no Postgres or Redis dependency, which suits self-hosting. | The gateway cannot fail over between machines and is a single point on the model call path. |
+| Client identity | The gateway issues its own keys instead of using OpenViking keys directly: they can be revoked on their own, and one person's clients can use different context profiles. | The gateway has to store users' OpenViking keys, so turn on encryption; a leaked gateway key exposes that user's memory. |
+
+## Next steps {#next-steps}
+
+- [Get started with OpenViking Gateway](02-quickstart.md): send a test request and watch recall and saving happen.
+- [OpenViking tools in the gateway](04-openviking-tools.md): choose which tools the model may run, and what users see.
+- [Long conversations in the gateway](05-long-conversations.md): set the model's context window and understand what compaction keeps.
diff --git a/docs/en/gateway/02-quickstart.md b/docs/en/gateway/02-quickstart.md
new file mode 100644
index 000000000..f121e6c12
--- /dev/null
+++ b/docs/en/gateway/02-quickstart.md
@@ -0,0 +1,98 @@
+---
+description: Turn on OpenViking Gateway, issue a gateway key, send a test request and confirm that memory works.
+---
+
+# Get started with OpenViking Gateway
+
+This page takes you from a working OpenViking server to a [gateway key](../guides/15-gateway.md#key-terms), a test request through the gateway and proof that memory works. You need an OpenViking installation whose `ov.conf` has embedding and VLM models set up (see [Quick Start](../getting-started/02-quickstart.md)). The gateway is part of the core package, so there is nothing extra to install.
+
+Pick the path that matches your server:
+
+| Your server | Follow |
+| --- | --- |
+| Bound to `127.0.0.1` in local dev mode (no `root_api_key`) | [Local server](#local-server-no-api-key) |
+| Reached over the network with `api_key` authentication | [Remote server](#remote-server-api-keys) |
+| An existing OpenViking service whose configuration you do not want to change | [Standalone deployment](../guides/22-gateway-operations.md#standalone-deployment), then come back to [Send a test request](#send-a-test-request) |
+
+## Local server (no API key) {#local-server-no-api-key}
+
+A local server in dev mode needs no OpenViking API key: Studio opens without one, and the gateway key you issue reads and writes memory as the local `default` user.
+
+1. **Turn the gateway on.** Run `openviking-server init` and answer yes to **Enable OpenViking Gateway on the same port?**. With an existing configuration, choose **Update gateway** from the menu. You can also merge `{"gateway": {"enabled": true}}` into `ov.conf` by hand.
+2. **Start or restart `openviking-server`.** The gateway now answers on the same port as OpenViking, at `http://127.0.0.1:1933/gateway`.
+3. **Open the gateway in Studio.** Open <http://127.0.0.1:1933/studio/> and choose **OpenViking Gateway** in the sidebar. If the default account has no [upstreams](../guides/15-gateway.md#key-terms) yet, the gateway imports the server's VLM settings as upstreams at startup and creates a context profile. You should see the **Get started** checklist on the Overview tab with its first two steps already done (see [Get started checklist and Quick mode](06-manage-in-studio.md#get-started-checklist)). An imported Coding Plan upstream needs your confirmation before use; see [Import OpenViking model settings](07-upstreams.md#import-openviking-model-settings). If nothing could be imported, add an upstream as described in [Upstreams](07-upstreams.md#upstreams).
+4. **Issue a gateway key.** On the Overview tab, choose **Get a key** in the **Quick mode** card. Or issue one by hand: on the Keys tab, choose **Issue key**, enter a name, pick the context profile and an upstream, and issue it. You should see the **Copy your gateway key** dialog with the full `ovgw_…` key. It is shown only once, so copy it before you close the dialog.
+
+Your gateway address is `http://127.0.0.1:1933/gateway`. Continue with [Send a test request](#send-a-test-request).
+
+## Remote server (API keys) {#remote-server-api-keys}
+
+A remote server is one that people reach over the network with `api_key` authentication. Each person signs in to Studio with their own OpenViking API key.
+
+If you'd rather not run init on the server host, root can sign in to Studio and choose **Enable gateway** on the OpenViking Gateway page instead of steps 1-3. The confirmation dialog can also generate the gateway management key. See [Enable it in the server](../guides/22-gateway-operations.md#enable-it-in-the-server).
+
+1. **Turn the gateway on.** On the server host, run `openviking-server init`, choose **Remote (0.0.0.0)** for the bind address, and answer yes to **Enable OpenViking Gateway on the same port?**.
+2. **Choose who may change upstreams.** The next question, **Allow users to configure their own gateway upstreams?**, decides who may change upstreams and context profiles. Answer yes to let every signed-in user configure their account's upstreams and context profiles. Answer no to protect them with a [gateway management key](../guides/22-gateway-operations.md#gateway-management-key): init generates a key starting with `ovgm_`, prints it and saves it to `gateway.management_key` in `ov.conf`, and only requests that carry this key can change upstreams and context profiles. Keep the printed key; you need it in step 6.
+3. **Restart the server.** The gateway now answers on the same port as OpenViking, at `https://ov.example.com/gateway`.
+4. **Get an OpenViking API key.** Use your own user API key, or use the root API key to create an account and user as described in [Authentication](../guides/04-authentication.md).
+5. **Sign in to Studio.** Open `https://ov.example.com/studio/`, enter your API key under **Connection Settings**, and choose **OpenViking Gateway** in the sidebar. You should see the Overview tab.
+6. **Add an upstream.** On the Upstreams tab, choose **Add upstream**, pick the provider and the protocol your client uses (the test request below uses Chat Completions), paste the provider's API key and save. Then choose **Test** in the upstream list. You should see **Connected** or **Model works**, which means the gateway reaches the provider. If the tab is read-only, a gateway management key is set: choose **Enter gateway management key** to unlock editing (see [Unlock editing](06-manage-in-studio.md#unlock-editing)), or ask whoever deployed the gateway.
+7. **Create a context profile.** On the Profiles tab, choose **Create with recommended settings**. You should see the new context profile among the cards.
+8. **Issue a gateway key** for yourself, as in step 4 of the local path. You should see the **Copy your gateway key** dialog; copy the key now, because it is shown only once. To issue keys for other users, see [Issue a key](09-gateway-keys.md#issue-a-key).
+
+Your gateway address is `https://ov.example.com/gateway`, with your server's address in place of `ov.example.com`.
+
+## Send a test request {#send-a-test-request}
+
+> **Tip**: step 3 of [Confirm that memory works](#confirm-that-memory-works) waits 10 quiet minutes before memories are extracted. To try it faster, first create a context profile with a shorter **Save the latest reply after** (for example 30 s), issue a key with it, and use that key as `GATEWAY_KEY` below. A context profile change reaches only conversations that start afterwards ([when changes take effect](06-manage-in-studio.md#when-changes-take-effect)).
+
+Send two requests with curl: one lists the models the key can use, the other asks a model a question through the gateway. Set `GATEWAY_URL` to your gateway address (`http://127.0.0.1:1933/gateway` for a local server) and replace `<model>` with a model the upstream serves:
+
+```bash
+export GATEWAY_URL=https://ov.example.com/gateway
+export GATEWAY_KEY='ovgw_...'
+
+curl -s "$GATEWAY_URL/v1/models" -H "Authorization: Bearer $GATEWAY_KEY"
+
+curl -s "$GATEWAY_URL/v1/chat/completions" \
+ -H "Authorization: Bearer $GATEWAY_KEY" \
+ -H "Content-Type: application/json" \
+ -H "X-OpenViking-Session: quickstart-1" \
+ -d '{"model": "<model>", "messages": [{"role": "user", "content": "Remember that I prefer short answers."}]}'
+```
+
+| Command | What you should see |
+| --- | --- |
+| `GET /v1/models` | The model names and aliases of the enabled upstreams bound to the key, limited to the key's allowed models if it has any |
+| `POST /v1/chat/completions` | A normal reply from your provider |
+
+The model list can be incomplete or even empty while requests still work: an upstream with an empty model list accepts any model name but adds nothing to this list. The `X-OpenViking-Session` header names the conversation, so the next request with the same value continues it; see [How conversations are recognized](03-connect-clients.md#how-conversations-are-recognized).
+
+## Confirm that memory works {#confirm-that-memory-works}
+
+Check three things in order: the request went through the gateway, the conversation was saved, and memories come back in a new conversation.
+
+1. **The request went through the gateway.** Open the Requests tab. You should see your request as a **New message** with status 200. Once OpenViking has something relevant, the **Memory** column shows how many entries were added, for example `+3`; on a brand-new account it stays empty.
+2. **The conversation is saved.** Send a second request with the same `X-OpenViking-Session` value. Its `messages` must hold the whole conversation: your first message, the reply you got back and a new message. Chat clients do this for you; with curl you add them yourself:
+
+ ```bash
+ curl -s "$GATEWAY_URL/v1/chat/completions" \
+ -H "Authorization: Bearer $GATEWAY_KEY" \
+ -H "Content-Type: application/json" \
+ -H "X-OpenViking-Session: quickstart-1" \
+ -d '{"model": "<model>", "messages": [
+ {"role": "user", "content": "Remember that I prefer short answers."},
+ {"role": "assistant", "content": "<the reply you got>"},
+ {"role": "user", "content": "Thanks."}]}'
+ ```
+
+ The first turn is saved as soon as this request arrives ([why saving runs one turn behind](01-how-it-works.md#when-conversations-are-saved)). Open the **Sessions** page in Studio, and you should see a `gateway-…` session. Sessions belong to the key's user: if the key was issued for someone else, sign in under **Connection Settings** with that user's OpenViking API key to see it.
+3. **Memories are extracted.** After **Save the latest reply after** (10 minutes by default) passes with no new message, the gateway commits the session, and OpenViking extracts memories in the background, which takes a moment. Then start a new conversation with another session value and ask something that depends on the memory, such as "How long should your answers be?". The **Memory** column should show recalled entries, and the reply should use them.
+
+If the **Memory** column stays empty or no session appears, see [No memory is added](12-troubleshooting.md#no-memory-is-added) and [Conversations do not appear in OpenViking](12-troubleshooting.md#conversations-do-not-appear-in-openviking).
+
+## Next steps {#next-steps}
+
+- [Connect clients](03-connect-clients.md#connect-clients): point Claude Code, Codex CLI or a chat app at the gateway.
+- [Issue a key](09-gateway-keys.md#issue-a-key): give other users their own gateway keys.
+- [Deployment and operations](../guides/22-gateway-operations.md): run the gateway for a team with Docker Compose, Helm or a standalone deployment.
diff --git a/docs/en/gateway/03-connect-clients.md b/docs/en/gateway/03-connect-clients.md
new file mode 100644
index 000000000..8b2064030
--- /dev/null
+++ b/docs/en/gateway/03-connect-clients.md
@@ -0,0 +1,315 @@
+---
+description: Point Claude Code, Codex, chat apps, SDKs and other clients at OpenViking Gateway, and check the connection.
+---
+
+# Connect clients to OpenViking Gateway
+
+This page gives the exact settings for each client and a way to check that they work. Every client needs three things: the gateway address, a gateway key, and an enabled upstream bound to that key that speaks the client's protocol and serves the model it requests. No gateway key yet? Start with [Get started](02-quickstart.md).
+
+Two limits apply to every client:
+
+- A client cannot sign in to the gateway with a subscription login. The upstream needs a provider API key, or a subscription proxy: Codex can use a ChatGPT subscription through a CLIProxyAPI upstream (see [Use a ChatGPT subscription](#codex-chatgpt-subscription)). For other subscription services, check their terms yourself (see also [Behaviors to expect](01-how-it-works.md#what-to-expect)).
+- Responses clients must send the full conversation history with every request (see [Client requirements](04-openviking-tools.md#client-requirements)).
+
+## Client settings at a glance {#connect-clients}
+
+The gateway address is the server's address followed by `/gateway`. In Studio, it appears at the top of the OpenViking Gateway page and on the **Connect** tab. The examples use `https://ov.example.com/gateway`; replace it with your own. Anthropic clients use the gateway address as it is, OpenAI-compatible clients add `/v1`, and Ark SDKs add `/api/v3`.
+
+| Client | Upstream protocol | Base URL | How its conversations are recognized |
+| --- | --- | --- | --- |
+| [Claude Code](#claude-code) | Anthropic Messages | `https://ov.example.com/gateway` | Claude Code's session header |
+| [Codex CLI](#codex-cli) | Responses | `https://ov.example.com/gateway/v1` | Codex's session header |
+| [Chat clients and SDKs](#chat-clients-and-sdks) | Chat Completions (or the API your SDK uses) | `https://ov.example.com/gateway/v1` | `X-OpenViking-Session`, which you send yourself |
+| [Open WebUI](#open-webui) | Chat Completions | `https://ov.example.com/gateway/v1` | An `X-OpenViking-Session` header set on the connection |
+| [OpenCode](#opencode) | Chat Completions, Anthropic Messages or Responses | `https://ov.example.com/gateway/v1` | OpenCode's session header |
+| [pi](#pi) | Chat Completions, Anthropic Messages or Responses | `https://ov.example.com/gateway/v1` (Anthropic Messages: `https://ov.example.com/gateway`) | Usually matched from the conversation history |
+| [DSH](#dsh) | Chat Completions, Anthropic Messages or Responses | `https://ov.example.com/gateway/v1` (Anthropic Messages: `https://ov.example.com/gateway`) | Usually matched from the conversation history |
+| [Volcano Engine Ark and BytePlus ModelArk SDKs](#volcano-engine-ark-and-byteplus-modelark-sdks) | Any of the three | `https://ov.example.com/gateway/api/v3` or `https://ov.example.com/gateway/api/compatible` | Depends on the headers the client sends |
+
+The last column is explained in [How conversations are recognized](#how-conversations-are-recognized).
+
+## When each client sends its own provider key {#bring-your-own-provider-key}
+
+By default the gateway holds the provider API key, and clients send only the gateway key. An [upstream](07-upstreams.md#upstreams) can instead have **Who provides the API key** set to **Each client sends its own key** (see [Credentials](07-upstreams.md#credentials)). Then the client keeps the gateway key in its usual API key setting and also sends its own provider API key in an `X-OpenViking-Upstream-Key` header on every request. In Studio, the **Bring your own provider key** card on the **Connect** tab lists which of your upstreams need it.
+
+Without the header, every request fails with 401 `Upstream API key is missing`. To add it:
+
+| Client | How to send `X-OpenViking-Upstream-Key` |
+| --- | --- |
+| Claude Code | `export ANTHROPIC_CUSTOM_HEADERS='X-OpenViking-Upstream-Key: <provider-key>'` |
+| Codex CLI | `env_http_headers` in the provider block, for example `env_http_headers = { "X-OpenViking-Upstream-Key" = "PROVIDER_API_KEY" }`, with the key exported as `PROVIDER_API_KEY` |
+| OpenAI and Anthropic SDKs | `default_headers` on the client, or `extra_headers` on each request |
+| Open WebUI | Add it to the connection's custom headers, next to the session headers |
+
+## Claude Code {#claude-code}
+
+Claude Code uses Anthropic Messages with the base URL `https://ov.example.com/gateway`. Set three environment variables before you start it:
+
+```bash
+export ANTHROPIC_BASE_URL=https://ov.example.com/gateway
+export ANTHROPIC_AUTH_TOKEN='<gateway-key>'
+export CLAUDE_CODE_GATEWAY_HINT_HEADERS=1
+```
+
+- Leave `/v1` off the address; Claude Code adds the path itself.
+- `CLAUDE_CODE_GATEWAY_HINT_HEADERS=1` makes Claude Code label sub-agent, compaction and background requests, so the gateway does not recall memory for them or save them as conversation turns.
+- Claude Code sends its own session ID, which the gateway uses to recognize the conversation, including after `--resume`.
+- The upstream must accept the model names Claude Code requests: leave its model list empty, list those names, or map them to the provider's model with model aliases (see [Models](07-upstreams.md#models)).
+- A Claude subscription login does not work through the gateway; requests with a subscription token are rejected. Configure the upstream with a provider API key.
+- If the OpenViking plugin is also installed, the gateway steps aside for those conversations (see [When both are in use](../guides/15-gateway.md#when-both-are-in-use)). With only the OpenViking MCP server, the gateway still adds memory and leaves the OpenViking tools to the MCP server.
+
+Next, [check the connection](#check-the-connection).
+
+## Codex CLI {#codex-cli}
+
+Codex uses the Responses API with the base URL `https://ov.example.com/gateway/v1`. It sends the full history with every request, which is what the gateway needs. Add a provider to `~/.codex/config.toml`. The two top-level settings must come before any `[section]`:
+
+```toml
+model_provider = "openviking"
+model = "<model>"
+
+[model_providers.openviking]
+name = "OpenViking Gateway"
+base_url = "https://ov.example.com/gateway/v1"
+wire_api = "responses"
+env_key = "OPENVIKING_GATEWAY_KEY"
+```
+
+Then set the gateway key in the environment Codex runs in:
+
+```bash
+export OPENVIKING_GATEWAY_KEY='<gateway-key>'
+```
+
+- The upstream bound to the key must use Responses and serve `<model>`.
+- Codex first tries a WebSocket connection. The gateway declines it, and Codex falls back to HTTP.
+- Codex sends its own session ID, which the gateway uses to recognize the conversation, including after `codex resume`.
+- Codex may warn that it has no metadata for an unfamiliar model name. The warning does not affect requests.
+- To use a ChatGPT subscription instead of an API key, see the next section.
+
+### Use a ChatGPT subscription {#codex-chatgpt-subscription}
+
+Codex can use your ChatGPT subscription through the gateway. Codex does not send its ChatGPT login to the gateway; instead, [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) (CPA) sits behind the gateway as an upstream, signs in with your ChatGPT account and serves it as a Responses API. OpenAI accepts this setup: Tibo, who leads Codex at OpenAI, has [publicly walked through](https://x.com/thsottiaux/status/2076119366647894371) connecting a Codex subscription through CLIProxyAPI.
+
+1. Run CPA and sign it in with your ChatGPT account, following its README.
+2. In Studio, add CPA as an upstream: provider *Generic*, protocol Responses, CPA's address as the **Base URL**, and one of CPA's API keys. See [Custom upstreams](07-upstreams.md#custom-upstreams).
+3. Issue a gateway key bound to that upstream and configure Codex as above. Codex keeps talking to the gateway with the gateway key; the subscription stays in CPA.
+
+Next, [check the connection](#check-the-connection).
+
+## Chat clients and SDKs {#chat-clients-and-sdks}
+
+Any client or SDK that supports the OpenAI Chat Completions API can connect, with the base URL `https://ov.example.com/gateway/v1`. Enter these settings wherever the client asks for an OpenAI-compatible provider:
+
+```text
+Base URL: https://ov.example.com/gateway/v1
+API key: <gateway-key>
+Model: <model>
+X-OpenViking-Session: <conversation-id>
+```
+
+The `X-OpenViking-Session` header is optional but recommended. It tells the gateway which conversation a request belongs to. Use a value that stays the same within a conversation and differs between conversations, such as your app's chat ID. Without it, the gateway matches conversations by their history; see [How conversations are recognized](#how-conversations-are-recognized).
+
+With the OpenAI Python SDK:
+
+```python
+from openai import OpenAI
+
+client = OpenAI(base_url="https://ov.example.com/gateway/v1", api_key="<gateway-key>")
+
+reply = client.chat.completions.create(
+ model="<model>",
+ messages=[{"role": "user", "content": "What did we decide about the release date?"}],
+ extra_headers={"X-OpenViking-Session": "chat-42"},
+)
+print(reply.choices[0].message.content)
+```
+
+When you stream Chat Completions, also ask for usage (`"stream_options": {"include_usage": true}`). Otherwise the provider reports no token counts for streamed replies, Studio cannot show usage, and the gateway has to estimate how full the context window is.
+
+SDKs for the other two APIs work the same way, as long as the upstream uses the same API as the SDK:
+
+- Point the Anthropic SDK at `https://ov.example.com/gateway`.
+- For the Responses API, use `https://ov.example.com/gateway/v1`, send the full history in every request and set `store: false`. Other Responses requests are forwarded without memory.
+
+Next, [check the connection](#check-the-connection).
+
+## Open WebUI {#open-webui}
+
+Open WebUI connects over Chat Completions with the base URL `https://ov.example.com/gateway/v1`. Set it up in three steps:
+
+1. In Open WebUI, open Admin Panel → Settings → Connections and add an OpenAI-compatible connection with the base URL `https://ov.example.com/gateway/v1` and the gateway key.
+2. Add these custom headers to the connection, so that each chat is its own conversation and the gateway recognizes Open WebUI's background tasks:
+
+ ```json
+ {
+ "X-OpenViking-Session": "{{CHAT_ID}}",
+ "X-OpenViking-Task": "{{TASK}}"
+ }
+ ```
+
+3. Set `RAG_SYSTEM_CONTEXT=true` in Open WebUI's environment. Open WebUI then puts content retrieved from attachments into the system message instead of rewriting your message for one turn, which keeps the conversation history stable between requests.
+
+Two things to know:
+
+- **One connection key means one memory owner.** Every Open WebUI user who chats through this connection reads and writes the memory of the OpenViking user behind the key. Give the connection to one person, or accept that its users share memory (see [One key per person](09-gateway-keys.md#one-key-per-person)).
+- Open WebUI also sends background requests (titles, tags, follow-up suggestions) through the same connection. The gateway recognizes title and summary requests. If the request log shows other background tasks as **New message**, point Open WebUI's task model at a connection that does not go through the gateway.
+
+Next, [check the connection](#check-the-connection).
+
+## OpenCode {#opencode}
+
+OpenCode can use Chat Completions, Anthropic Messages or Responses, always with the base URL `https://ov.example.com/gateway/v1`. Add a provider to `~/.config/opencode/opencode.json`, merged with your existing settings:
+
+```json
+{
+ "provider": {
+ "openviking": {
+ "npm": "@ai-sdk/openai-compatible",
+ "name": "OpenViking",
+ "options": {
+ "baseURL": "https://ov.example.com/gateway/v1",
+ "apiKey": "{env:OPENVIKING_GATEWAY_KEY}"
+ },
+ "models": {
+ "<model>": {}
+ }
+ }
+ }
+}
+```
+
+The example uses Chat Completions. For another protocol, change `npm`; `baseURL` stays the same. The upstream bound to the key must speak the protocol you pick, and the **Connect** tab in Studio fills in the matching package:
+
+| Upstream protocol | `npm` |
+| --- | --- |
+| Chat Completions | `@ai-sdk/openai-compatible` |
+| Responses | `@ai-sdk/openai` |
+| Anthropic Messages | `@ai-sdk/anthropic` |
+
+Export the gateway key as `OPENVIKING_GATEWAY_KEY`, then select `openviking/<model>` in OpenCode. If the OpenViking plugin for OpenCode is also installed, the gateway steps aside for those conversations.
+
+Next, [check the connection](#check-the-connection).
+
+## pi {#pi}
+
+pi can use Chat Completions, Anthropic Messages or Responses, with the base URL `https://ov.example.com/gateway/v1` (`https://ov.example.com/gateway` for Anthropic Messages). Add a provider to pi's model configuration, `~/.pi/agent/models.json`:
+
+```json
+{
+ "providers": {
+ "openviking": {
+ "baseUrl": "https://ov.example.com/gateway/v1",
+ "apiKey": "$OPENVIKING_GATEWAY_KEY",
+ "api": "openai-completions",
+ "models": [
+ {
+ "id": "<model>"
+ }
+ ]
+ }
+ }
+}
+```
+
+The example uses Chat Completions. For another protocol, set `api` and `baseUrl` as below; the upstream bound to the key must speak that protocol. With Anthropic Messages, leave `/v1` off, because the Anthropic SDK adds it:
+
+| Upstream protocol | `api` | `baseUrl` |
+| --- | --- | --- |
+| Chat Completions | `openai-completions` | `https://ov.example.com/gateway/v1` |
+| Responses | `openai-responses` | `https://ov.example.com/gateway/v1` |
+| Anthropic Messages | `anthropic-messages` | `https://ov.example.com/gateway` |
+
+- `apiKey` reads the gateway key from the `OPENVIKING_GATEWAY_KEY` environment variable; export it before you start pi. Keep the leading `$`, or pi sends the string itself as the key.
+- pi usually sends no session header, so the gateway matches its conversations by their history (see [How conversations are recognized](#how-conversations-are-recognized)).
+- If pi's own OpenViking extension is active, the gateway steps aside for those conversations. Use one or the other.
+
+Next, [check the connection](#check-the-connection).
+
+## DSH {#dsh}
+
+[DeepSeek Harness](https://www.npmjs.com/package/@deepseek-ai/dsh) (`dsh`) builds on pi's model layer and takes the same `api` and base URL values: `https://ov.example.com/gateway/v1`, or `https://ov.example.com/gateway` for Anthropic Messages. Add a provider to the profile configuration. `dsh web` uses the `web` profile, so the file is `~/.dsh/profiles/web/cordis.patch.yml`:
+
+```yaml
+- id: llm-pi-ai
+ config:
+ providers:
+ openviking:
+ api: openai-completions
+ baseURL: "https://ov.example.com/gateway/v1"
+ apiKeyEnv: OPENVIKING_GATEWAY_KEY
+ models:
+ - id: "<model>"
+```
+
+If the file already has an `llm-pi-ai` entry, add `openviking` under its `providers` instead of writing a second entry. For Responses or Anthropic Messages, set `api` and `baseURL` as in the [pi table](#pi).
+
+Export the gateway key as `OPENVIKING_GATEWAY_KEY`, the variable `apiKeyEnv` names, then start `dsh web` and pick `<model>` under the `openviking` provider in the model picker.
+
+- You can also add the provider in the Web UI under Settings → Models → Add model provider → Custom model API, which writes the same file.
+- A DSH provider speaks one protocol. To use the gateway over several, declare one provider per protocol.
+- Unless DSH sends one of the session headers, the gateway matches its conversations by their history (see [How conversations are recognized](#how-conversations-are-recognized)).
+- If the [OpenViking plugin for DSH](../agent-integrations/17-dsh.md) is installed in the same profile, the gateway steps aside for those conversations. Use one or the other.
+
+Next, [check the connection](#check-the-connection).
+
+## Volcano Engine Ark and BytePlus ModelArk SDKs {#volcano-engine-ark-and-byteplus-modelark-sdks}
+
+Clients and SDKs already set up for Volcano Engine Ark, or BytePlus ModelArk (its international edition), can use any of the three APIs and only need the address replaced, usually with `https://ov.example.com/gateway/api/v3`. Under `/gateway`, the gateway accepts Ark's own paths (`/api/v3/chat/completions`, `/api/v3/responses`, `/api/v3/models` and `/api/compatible/v1/messages`) as well as the standard `/v1` paths:
+
+| Original address | Gateway address |
+| --- | --- |
+| `https://ark.cn-beijing.volces.com/api/v3` | `https://ov.example.com/gateway/api/v3` |
+| `https://ark.ap-southeast.bytepluses.com/api/v3` | `https://ov.example.com/gateway/api/v3` |
+| `https://ark.cn-beijing.volces.com/api/compatible` (Anthropic-compatible) | `https://ov.example.com/gateway/api/compatible` |
+
+Use the gateway key in place of the Ark API key. With the Volcano Engine Ark Python SDK:
+
+```python
+from volcenginesdkarkruntime import Ark
+
+client = Ark(base_url="https://ov.example.com/gateway/api/v3", api_key="<gateway-key>")
+```
+
+The path a client uses only decides which API it speaks. The request still goes to an upstream bound to the key that uses that API and serves the model, usually one whose provider is Volcano Engine Ark or BytePlus ModelArk (see [Upstreams](07-upstreams.md#upstreams)). As with other chat clients, send `X-OpenViking-Session` with one value per conversation.
+
+Next, [check the connection](#check-the-connection).
+
+## Check the connection {#check-the-connection}
+
+Check every new client setup once, with a short conversation. This matters most for Open WebUI, OpenCode, pi and DSH: their setups follow each client's documented provider settings, so treat them as a starting point.
+
+1. In the client, send two messages in one conversation (one chat, or one agent session). You should get normal replies.
+2. In Studio, open the **Requests** tab. Both requests should appear as **New message** with status 200.
+3. Expand both requests. They should show the same **Conversation**, and **Saving** should read **On**, which means saving is enabled and healthy. The first turn is saved once the second message arrives; to see it, look for a `gateway-…` session on Studio's **Sessions** page, signed in as the key's user (see [Confirm that memory works](02-quickstart.md#confirm-that-memory-works)).
+
+If something is off:
+
+- **No requests appear.** Only requests that reach a model provider are logged; the client received the gateway's error directly. See [Clients get an error from the gateway](12-troubleshooting.md#clients-get-an-error-from-the-gateway).
+- **The two requests have different conversations.** The client sends no session header and the history did not match; see [How conversations are recognized](#how-conversations-are-recognized).
+- **Memory stays empty.** That is expected on a brand-new account. To prove that memory works end to end, follow [Confirm that memory works](02-quickstart.md#confirm-that-memory-works).
+
+Every column and label of the log is explained in [Requests](10-overview-and-requests.md#requests).
+
+## How conversations are recognized {#how-conversations-are-recognized}
+
+A conversation is the series of requests the gateway treats as one chat: it keeps one context profile and one upstream, and is saved to an OpenViking session, or to a new one in some cases, for example when the client rewrites its history (see [Saving status](10-overview-and-requests.md#saving-status)). To decide which conversation a request belongs to, the gateway takes the first of these request headers that is present:
+
+1. `X-OpenViking-Session`
+2. `thread-id`
+3. `x-claude-code-session-id` (Claude Code)
+4. `x-opencode-session-id` (OpenCode)
+5. `x-session-id`
+6. `session-id` (Codex CLI)
+
+If none is present, the gateway looks at the latest assistant reply in the history. If exactly one earlier conversation produced that reply, the request joins it; otherwise it starts a new conversation. Two conversations that only share an opening message are never merged. This handles ordinary back-and-forth chat, but retries, regenerated answers and identical conversations are ambiguous and may start a new conversation. So send `X-OpenViking-Session` whenever your client lets you set headers.
+
+Conversations belong to the OpenViking user behind the key, separately for each API. Two gateway keys of the same user that send the same session value share one conversation; the same session value on a different API is a different conversation. The gateway removes all `X-OpenViking-*` headers before forwarding, so providers never see them.
+
+A request that does not join an existing conversation still gets memory: new messages are recalled for, and memory added earlier is replayed, because the gateway finds it by the messages themselves. The difference is that the request starts a new conversation. Its turns are saved to a new OpenViking session, its memory budget starts from zero, and it uses the key's current context profile.
+
+## Next steps {#next-steps}
+
+- [Behaviors to expect](01-how-it-works.md#what-to-expect): what changes for your client once it goes through the gateway.
+- [Context profiles](08-context-profiles.md): tune how much memory is recalled and whether conversations are saved.
+- [Troubleshoot OpenViking Gateway](12-troubleshooting.md): fix errors, missing memory or unsaved conversations.
diff --git a/docs/en/gateway/04-openviking-tools.md b/docs/en/gateway/04-openviking-tools.md
new file mode 100644
index 000000000..59f7e8d49
--- /dev/null
+++ b/docs/en/gateway/04-openviking-tools.md
@@ -0,0 +1,215 @@
+---
+description: Let the model search, read and write OpenViking memory through tools that OpenViking Gateway runs for any client.
+---
+
+# OpenViking tools in the gateway
+
+With OpenViking tools on, the model searches, reads and writes OpenViking memory by itself while it answers, and the gateway runs those tool calls for the client. The feature is meant for chat apps and API apps that cannot connect to the OpenViking MCP server; clients that support MCP or have a plugin, such as Claude Code and Codex, are better served by those, because they show each tool call and its result and ask for approval first. In Studio: **Profiles** → **OpenViking tools**, together with **Allow OpenViking tools** on each upstream.
+
+## Agentic memory for any client {#agentic-memory-for-any-client}
+
+With automatic recall, the gateway guesses what the model needs. With OpenViking tools on, the model decides for itself what to search, read and remember. The gateway runs the tools, so this works even when the client's request has no tools at all.
+
+![One reply with OpenViking tools: the gateway adds recalled memory and the OpenViking tool definitions to the client's request; when the model calls an OpenViking tool, the gateway runs it with the user's OpenViking key, feeds the result back and asks the model again until it gives a final answer; the client receives one continuous reply with notice lines, and the tool rounds are replayed unchanged in the next turn](../../images/gateway/tool-loop.en.svg)
+
+- **Several steps in one reply**: the gateway intercepts the model's OpenViking tool calls, runs them with the user's OpenViking key, feeds the results back and asks the model again, until the model stops calling them. The client receives one continuous reply, streaming or not.
+- **The client's own tools still work**: in the same reply, the model can call both OpenViking tools and client tools such as Bash. Client tool calls go to the client unchanged and pass through its permission prompts as usual.
+- **The next turn remembers**: tool calls and results are not in the client's history, so the gateway stores these rounds and replays them unchanged on the next turn. The model remembers what it found, and the [prompt cache](01-how-it-works.md#replay) keeps working.
+
+## What each kind of client gets {#what-each-kind-of-client-gets}
+
+| Client | Without the gateway | Through the gateway, with OpenViking tools on |
+| --- | --- | --- |
+| Chat apps, such as Cherry Studio and Open WebUI | To use memory you set up MCP or write tools yourself; a plain chat only exchanges text. | The model searches memory and reads the original text by URI. With `remember` checked, it notes down what the user asks it to remember; with `add_resource` checked, it imports files the user attaches. This works even in a plain chat mode with no tools. |
+| SDK scripts and low-code platforms | One question, one answer; multi-step work needs a loop you write. | One request covers "search → read → grep for exact matches → answer", with no code changes. |
+| Coding agents such as Claude Code and Codex (without the OpenViking plugin or MCP server) | Their own tools, but no OpenViking. | OpenViking tools and client tools such as Bash mix in the same reply. If you want to approve each tool call, the plugin or MCP server is still the better choice. |
+
+## Which tools the model can use {#which-tools-the-model-can-use}
+
+The tool list comes straight from the MCP tools your OpenViking server provides, each with an `openviking_` prefix, so tools that OpenViking adds later become available on their own. The model works within the user's own OpenViking permissions. The common groups:
+
+| Purpose | Tools | What the model uses them for |
+| --- | --- | --- |
+| Search | `find`, `search`, `grep`, `glob` | Semantic search over memory and resources; exact lookups by regular expression or file name. |
+| Browse and read | `list`, `tree`, `read` | Expanding a recalled entry to its original text by URI; browsing memory and skill directories. |
+| Write | `remember`, `write`, `edit` | Storing a long-term memory; writing or editing memory files. |
+| Import | `add_resource`, `add_skill` | Importing a web page or repository by URL, importing a chat attachment, creating a skill from text, all without a shell on the client. |
+| Delete and permissions | `forget`, `set_acl` and others | Deleting memory permanently; changing access to shared resources. |
+
+Which of these a new profile selects is under [Choose tools](#choose-tools). An experimental profile setting, **Agent-managed context windows**, gives the model two more tools for starting a fresh context window; see [Experimental: agent-managed context windows](05-long-conversations.md#experimental-agent-managed-context-windows).
+
+## What users see {#what-users-see}
+
+The model's text streams as usual. With **Show tool calls** on (the default, in the [context profile](08-context-profiles.md#context-profiles)'s **OpenViking tools** section), each OpenViking tool call leaves a one-line notice at the point in the reply where the call happened:
+
+```text
+> OpenViking find: "the release date we agreed on" — done
+> OpenViking read: viking://user/alice/memories/release.md — done
+```
+
+- **What a notice names**: the tool and, when the gateway can tell, what the call works on: the search query, the URI read, listed or written, or the file or skill being imported. Users never see the full arguments or the results.
+- **When it appears**: in a streaming reply, the notice appears as soon as the call starts, so users can see the gateway working during slow calls such as imports. A non-streaming reply carries the same notices in the final message.
+- **Where it goes**: each notice is its own paragraph. In Chat Completions the notices are part of the reply text; in Anthropic Messages the notices for one round of calls share a text block; in Responses they share an assistant message.
+- **Only for users**: the model never sees the notices; it gets the real calls and results. The gateway does not save notices to OpenViking.
+- **Token usage**: the usage the client receives is the sum of every model call in the reply, including the extra calls made while the model used tools.
+
+### Tool call notices {#tool-call-notices}
+
+When a call ends, the gateway adds its outcome to the notice:
+
+| Outcome | Meaning |
+| --- | --- |
+| `done` | The call finished. |
+| `failed` | The call returned an error. |
+| `skipped` | The gateway refused the call without running it, for example because the round limit or token budget was used up. |
+
+To hide the notices, turn off **Show tool calls**. Like other profile changes, this reaches only new conversations (see [When changes take effect](06-manage-in-studio.md#when-changes-take-effect)).
+
+## Risks and controls {#risks-and-controls}
+
+> **Warning**: Selected tools run without the client's permission prompts, including tools that write or delete data; a tool-call notice reports a call after it ran and is not an approval step. If users need to approve each call, connect the OpenViking plugin or MCP server instead (see [Gateway or plugin?](../guides/15-gateway.md#gateway-or-plugin)). The model can never do more than the user's own OpenViking permissions allow.
+
+Before you check a tool that changes data, make sure that is acceptable. For profiles used by chat apps, leave at least `forget` and `set_acl` unchecked.
+
+What admins control:
+
+| Control | Where in Studio | What it does |
+| --- | --- | --- |
+| **OpenViking tools** switch | **Profiles** → **OpenViking tools** | Turns gateway tools on or off for conversations that use the profile. |
+| **Tools** checkboxes | **Profiles** → **OpenViking tools** | Picks which tools the model gets; see [Choose tools](#choose-tools). |
+| **Allow OpenViking tools** | **Upstreams** → **Routing** | Lets profiles offer tools through this upstream. Turning it off also stops them in ongoing conversations. |
+| Rounds, total time and token budget | **Profiles** → **OpenViking tools** → **Advanced settings** | Caps how long the model can keep using tools; see [Limits](#limits). |
+
+## Choose tools {#choose-tools}
+
+The **Tools** list in a [context profile](08-context-profiles.md#context-profiles)'s **OpenViking tools** section decides which OpenViking tools the model gets. New context profiles have **OpenViking tools** on, including those made with **Create with recommended settings**, and every tool is selected except the ones the gateway knows change data:
+
+| Default | Tools |
+| --- | --- |
+| Selected | `find`, `search`, `grep`, `glob`, `list`, `tree`, `read`, `download`, `list_watches`, `get_acl`, `list_users`, `list_groups`, `health` |
+| Not selected (they change data) | `remember`, `write`, `edit`, `add_resource`, `add_skill`, `forget`, `set_acl`, `cancel_watch` |
+
+Check `remember` to let the model save memories, and `add_resource` to let it import web pages or attachments. Read the warning in [Risks and controls](#risks-and-controls) before checking any tool that changes data.
+
+**Allow OpenViking tools** is on by default for every [upstream](07-upstreams.md#upstreams). With both switches on, new conversations get the selected tools with an `openviking_` prefix, such as `openviking_find` and `openviking_read`. Tool definitions go with every request in the conversation, and the full set adds about 3,500 input tokens, so unchecking tools nobody needs also saves tokens.
+
+Things to know about the list:
+
+- **Where it comes from**: the **Tools** list comes from your OpenViking service, and Studio describes what each tool does. When OpenViking annotates a tool, Studio also shows a **Read only** or **Modifies data** badge next to it. OpenViking marks `search` as **Modifies data**, but the gateway still selects it by default.
+- **Tools added later**: tools that OpenViking adds later are available by default; ongoing conversations keep the tool list they started with. Existing context profiles keep their selection.
+- **The list is empty for root**: OpenViking does not accept root API keys for its tools, so for root the gateway reads the list with the OpenViking key behind a [gateway key](09-gateway-keys.md#gateway-keys) issued in the current account. Until the account has a gateway key, the list can be empty and Studio shows **Issue a gateway key to load the tool list.** Issue a key first, or edit the profile signed in as a user or account admin. A profile saved before then keeps the default selection.
+- **`download` needs a shell**: `download` returns a one-time `curl` command, so the client needs a shell tool, and the link must be reachable from the client. See [With a client shell tool](#import-with-a-shell-tool) for which names count and where the link points.
+
+## Client requirements {#client-requirements}
+
+OpenViking tools work with all three model APIs, streaming and non-streaming, as long as the client sends the full conversation every turn:
+
+| Protocol | What the client must do |
+| --- | --- |
+| Chat Completions | Send the full `messages` history. |
+| Responses | Use `store: false` and the full `input` history, and on the next turn send back the whole returned `output`, including reasoning and client tool calls. `item_reference` cannot rebuild the full history. |
+| Anthropic Messages | Send the full `messages` history with thinking and signature blocks intact. Token-count requests carry the same tool definitions but run no tools. |
+
+When the model calls OpenViking tools and client tools in the same reply, the gateway handles the OpenViking calls, and the client runs its own tools and returns their results as usual. Responses supports client function and custom tools; Anthropic Messages supports client tool_use calls.
+
+Responses requests that rely on state stored at the provider (`previous_response_id`, `conversation`, `background`), or that do not set `store: false`, are forwarded as they are: they get neither recalled memory nor OpenViking tools. Later lookups of those responses still go to the upstream that created them.
+
+## When tools are not offered {#when-tools-are-not-offered}
+
+A request can reach the model without OpenViking tools even though its [context profile](08-context-profiles.md#context-profiles) has them on. Its detail in the **Requests** tab then shows **Not offered:** followed by the reason. Studio shows the label; the code in parentheses is the value in the management API (`tool_skip_reason`):
+
+| Reason | Meaning |
+| --- | --- |
+| **Responses requests must send the full conversation and set store: false** (`tools_require_full_history`) | A Responses request needs `store: false` and the full input history, without `item_reference`. |
+| **OpenViking tools are turned off for this upstream** (`upstream_tools_disabled`) | The upstream has **Allow OpenViking tools** off. |
+| **The request asked for several choices (n > 1)** (`tools_multiple_choices`) | The request asks for several choices (`n` above 1). |
+| **The request asked for structured output** (`tools_structured_output`) | The request asks for structured output (`response_format`, `text.format` or `output_config.format`). |
+| **The client sent tools that are not functions** (`tools_non_function`) | A Chat Completions client sent a tool that is not a function. |
+| **The client required a specific tool** (`tools_forced_choice`) | `tool_choice` is anything other than `auto` or `none`: for example `required`, Anthropic `any` or `tool`, a named function, or a Responses object such as `allowed_tools`. |
+| **DeepSeek thinking is on and earlier reasoning cannot be sent back** (`deepseek_reasoning_history_required`) | The upstream is DeepSeek, thinking is on (standard Responses requests have no `thinking` field and count as on), and earlier replies would reach DeepSeek without their reasoning. Turn on **Restore reasoning the client drops** in the upstream's **Routing** section ([details and cases it cannot cover](07-upstreams.md#restore-reasoning)), or send `"thinking": {"type": "disabled"}`. |
+| **The client already has OpenViking tools** (`tool_name_collision`) | The gateway stops offering its own tools for the rest of the conversation (requests that resend history in which the model already called gateway tools keep them). See [When the client has its own OpenViking tools](#client-has-openviking-tools). |
+| **OpenViking's tool list couldn't be loaded when this conversation first needed it** (`tools_unavailable`) | The tool list could not be loaded from OpenViking, and no earlier list was available. Start a new conversation once the connection is back. |
+| **This conversation has no OpenViking tools** (`tools_not_selected_at_session_start`) | The profile has tools on, but this conversation's tool list is empty: either the profile selects no tools, or the conversation started before a gateway upgrade. Start a new conversation. |
+
+### When the decision is made {#when-the-decision-is-made}
+
+Whether a conversation gets tools is decided at its first request that could use them (housekeeping requests such as title generation do not count) and then stays fixed, so profile changes only reach new conversations. The one exception switches tools off: the client turns out to have OpenViking tools of its own before the model has called a gateway tool, for example because an MCP server connected after the first turn.
+
+Housekeeping requests, sub-agent requests and conversations where an OpenViking plugin was detected never get OpenViking tools. If such a request sends back history in which the model used these tools, the gateway still attaches the tool definitions so the history stays valid, but refuses new OpenViking calls. The client's own tools stay available in every request.
+
+### When the client has its own OpenViking tools {#client-has-openviking-tools}
+
+The gateway decides that the client already has OpenViking tools (`tool_name_collision`) when any of these holds:
+
+- An MCP server name (`server_label`, `mcp_server_name`, `mcp_servers[].name`) contains the word `openviking`.
+- A tool whose name ends in an OpenViking tool name also contains that word, such as `mcp__claude_ai_OpenViking__search`. A connector's `authenticate` tool does not count. Deferred tools listed by name on a line of their own count too.
+- A prefixed tool whose name ends in an OpenViking tool name, such as `mcp__ov__read`, mentions `viking://` in its definition.
+- In any request, a client tool has the same name as a gateway tool, because upstreams reject duplicate tool names.
+
+A false match also lasts for the whole conversation; start a new one.
+
+## Import files and skills {#import-files-and-skills}
+
+The model can import material when your OpenViking service provides the import tools (`add_resource`, `add_skill`) and the profile has them checked. Importing by URL needs nothing more. Importing a local file needs either a client shell tool or an attachment on the user message. Uploads are limited by `max_body_bytes`, the gateway's request size limit (32 MiB by default; see [Side effects](05-long-conversations.md#side-effects)).
+
+### With a client shell tool {#import-with-a-shell-tool}
+
+A shell tool is a client tool named like bash, shell, exec_command, terminal or run_command. The import tool returns a one-time upload link, and the model uploads the file with the client's shell tool, which goes through the client's permission prompt. Skill directories are zipped first.
+
+Upload links, and the download links that `download` returns, point to `public_url` plus `/gateway/uploads` or `/gateway/downloads`. So `public_url` must be an address the client can reach (see [Public address](../guides/22-gateway-operations.md#public-address)), and any proxy in front must forward those paths like the others. Without `public_url`, imports fail with "Set gateway.public_url for client uploads and downloads". With `mcp_file_links` set to `direct`, the gateway passes OpenViking's own links through unchanged. They then point at OpenViking Server, whose `OPENVIKING_PUBLIC_BASE_URL` (or `server.public_base_url`) must be an address the client can reach.
+
+### From an attachment {#import-from-an-attachment}
+
+Without a shell tool, the model can import a file attached to a user message, sent either as base64 data or as attachment text. This covers embedded `base64` and `text` data in Chat Completions `file` parts (`file.file_data`, as raw base64 or a `data:` URL), Responses `input_file` and Anthropic `document.source`. Open WebUI usually sends only the extracted text, which is imported as a text file.
+
+Attachment URLs and provider file IDs are not fetched; to import a remote resource, use the import tool's URL parameter.
+
+## Limits {#limits}
+
+Rounds, total time and the token budget have no limit by default: as in an agent's own tool loop, the model keeps using OpenViking tools until it is done. In Studio, the limits are under **Profiles** → **OpenViking tools** → **Advanced settings**, and an empty field means no limit:
+
+| Setting | Default | At the limit |
+| --- | --- | --- |
+| **Rounds per request** | No limit | Further OpenViking calls are refused; the model continues with the results it has and the client's own tools. |
+| **Time limit per call** | 30 s | The call returns an error to the model. |
+| **Result size** | 65,536 bytes | The result is truncated. |
+| **Total time** | No limit | The request fails with "Hidden tool request timed out"; see [Failure handling](#failure-handling). |
+| **Token budget** | No limit | Further OpenViking calls are refused; the model continues with the results it has and the client's own tools. This is not a billing cap; the final answer can go past it. |
+
+API names and allowed ranges are in [Context profile settings](13-configuration.md#context-profile-settings).
+
+> **Note**: A non-streaming request keeps running after the client disconnects, so set **Total time** if your clients send non-streaming requests. In a streaming request, the user can stop the reply at any time, and the gateway stops when the client disconnects.
+
+The token budget counts only what using OpenViking tools adds: the extra calls, their results and the model output that follows. The client's existing conversation, tool definitions and images do not count. The gateway keeps the client's limit on answer length (`max_tokens`, `max_completion_tokens` or `max_output_tokens`).
+
+To see what one request used, expand it in the **Requests** tab: the **OpenViking tools** item shows the rounds, the extra model calls and the tokens added, plus **Tool token budget reached** when the budget refused further calls.
+
+Profiles saved before these defaults became "no limit" keep their old values (5 rounds, 120 seconds, 100,000 tokens); clear the fields to remove the limits.
+
+## Failure handling {#failure-handling}
+
+When a single OpenViking call fails, the model receives an error result and can carry on with its answer. The whole answer fails only in these cases:
+
+- The provider rejects a follow-up model request.
+- The model calls an OpenViking tool that is not available in this conversation, or keeps calling OpenViking tools after they were refused.
+- **Hidden tool request timed out**: the OpenViking tool rounds took longer than the profile's tool **Total time**; or, with no total time set, one model request during the rounds took longer than `upstream_timeout_seconds`.
+
+The client then receives an error, and the request log shows **OpenViking tools failed** (`hidden_tool_loop_failed`). What the error looks like depends on the request:
+
+| Request | What the client receives |
+| --- | --- |
+| Streaming | An error event at the end of the stream: `response.failed` in Responses, and an `error` of type `gateway_tool_error` in Chat Completions and Anthropic Messages. The HTTP status is already 200 by then. |
+| Non-streaming, the provider rejected a follow-up request | The provider's own error body and status. |
+| Non-streaming, timed out | 504 (`gateway_http_504`). |
+| Non-streaming, any other failure | 502 with body `{"reason": "gateway_http_502", "detail": "..."}`. |
+
+Two more cases:
+
+- **One upstream keeps failing**: turn off its **Allow OpenViking tools**. Claude conversations that already used the tools may then show **Tool history unavailable** (`hidden_tool_history_unavailable`): the earlier thinking can no longer be used, and the gateway removed it. Restore the setting named in the request detail's skip reason, or start a new conversation.
+- **Retries**: a retried tool call reuses the first call's result, and an interrupted write is never repeated automatically.
+
+## Next steps {#next-steps}
+
+- [Context profiles](08-context-profiles.md#context-profiles): set up recall, saving and tools together for each kind of client.
+- [File imports or downloads fail](12-troubleshooting.md#file-imports-or-downloads-fail): fix upload and download links.
+- [Context profile settings](13-configuration.md#context-profile-settings): the API names and ranges of every tool setting.
diff --git a/docs/en/gateway/05-long-conversations.md b/docs/en/gateway/05-long-conversations.md
new file mode 100644
index 000000000..caf3216b4
--- /dev/null
+++ b/docs/en/gateway/05-long-conversations.md
@@ -0,0 +1,166 @@
+---
+description: How OpenViking Gateway compacts long conversations, which context window to set, and what compaction costs.
+---
+
+# Long conversations in the gateway
+
+This page is for admins who set up context profiles and upstreams, and for users whose long conversation was cut short or rejected as too long. It explains when and how the gateway summarizes a long conversation, what the model receives afterwards, and what that costs. The setting to check first is the model's [context window](#context-window): if it is not set, the gateway assumes 1,000,000 tokens.
+
+## What compaction does {#long-conversations}
+
+[Compaction](../guides/15-gateway.md#key-terms) keeps a conversation inside the model's context window, the most tokens one request can hold, and it is on by default. When a conversation nears the window, the same model writes a summary of the conversation so far, and from then on the summary replaces everything before the cut. The history shown in the client does not change. When saving is on and the model has the OpenViking `grep` and `read` tools, the summary ends with directions for [finding what was cut](#finding-what-was-cut).
+
+In Studio: **Profiles** → **Long conversations**.
+
+| Setting | Default | What it does |
+| --- | --- | --- |
+| **Compaction** | On | Replace the earlier part of a conversation with a summary when it nears the context window. |
+| **Compact at** | 0.9 of the window | How full the window must be before the gateway compacts. |
+| **Summary length** | 8,000 tokens | The most tokens the model may write for one summary. |
+| **Default context window** | Not set (1,000,000 tokens assumed) | The window for models the upstream does not list; see [Set the model's context window](#context-window). |
+| **Agent-managed context windows** | Off | Experimental: the model starts fresh windows itself; see [below](#experimental-agent-managed-context-windows). |
+
+A conversation keeps the context profile it started with, so profile changes reach only new conversations (see [When changes take effect](06-manage-in-studio.md#when-changes-take-effect)). Ranges and API names are in the [configuration reference](13-configuration.md#context-profile-settings).
+
+## When it compacts {#when-it-compacts}
+
+On every new user message and every tool step (a request in which the client sends back results from its own tools; the **Tool step** [request type](10-overview-and-requests.md#request-types)), the gateway estimates how full the context window is: the token usage the provider reported for this conversation's previous reply, plus an estimate for the messages added since. When the estimate reaches **Compact at** (0.9 of the window by default), the gateway compacts before it forwards the request.
+
+Exceptions:
+
+- **No usage from the provider.** Without the reported usage (for example, streamed Chat Completions without `stream_options.include_usage`), the gateway estimates the whole request.
+- **Requests that never trigger it.** Housekeeping, sub-agent and token-count requests never trigger compaction.
+- **OpenViking tool rounds are not checked.** The gateway checks the window only when a request arrives, so the OpenViking tool rounds it runs inside one request are never compacted. Rounds and the token budget have no limit by default; to keep one request inside the window, set **Rounds per request** or **Token budget** (see [Limits](04-openviking-tools.md#limits)).
+
+## Set the model's context window {#context-window}
+
+The gateway has to know each model's context window to compact in time. It takes the window from the first of these that is set:
+
+1. The upstream's **Context windows** entry for the model, matched by the model name sent to the upstream (after aliases).
+2. The context profile's **Default context window**.
+3. Otherwise, 1,000,000 tokens.
+
+For a model whose window is smaller than 1,000,000 tokens, set one of the first two. Otherwise the gateway compacts too late, and the provider rejects the conversation as too long before compaction ever starts. If you cannot change upstreams or context profiles, ask whoever manages the gateway (see [Who can change what](06-manage-in-studio.md#who-can-change-what)).
+
+To set and check a model's window:
+
+1. In Studio, open **Upstreams**, edit the upstream, and under **Models** → **Context windows** add the model name with its window in tokens (at least 1,024). Saved upstream settings apply at once. To cover every model the upstream does not list instead, set **Default context window** under **Profiles** → **Long conversations**; that reaches new conversations only.
+2. Send a message, then expand the request on the **Requests** tab. The **Context window** line should read "About … of *N* tokens", where *N* is the window you entered.
+
+## How the summary is written {#how-the-summary-is-written}
+
+The gateway sends one extra, non-streaming request to the same upstream and model. The client's system prompt, tools and thinking settings stay the same, so most of the request hits the provider's [prompt cache](01-how-it-works.md#replay). Settings that a plain-text summary cannot follow are removed: a forced tool choice becomes "no tool call", and structured output formats and stop sequences are dropped.
+
+The request contains the conversation up to the cut, plus an instruction for the model to summarize it for itself. An earlier summary is folded into the new one. The summary covers:
+
+- the user's goals and the latest request, word for word;
+- key decisions and current progress;
+- files, paths and identifiers;
+- errors and how they were fixed;
+- open items;
+- key facts from the latest tool results.
+
+The summary is plain text of at most **Summary length** (8,000) tokens. Thinking counts against the output cap, and some models (such as DeepSeek V4.1) think by default even when the request has no thinking settings, so the gateway always allows 16,000 tokens of output on top of the summary length; when the client sets an explicit thinking budget, it adds that budget instead. The provider bills this request like any other.
+
+## What the model receives afterwards {#what-the-model-receives-afterwards}
+
+Where the cut falls depends on the request:
+
+| Request | Where the cut falls | What the model receives |
+| --- | --- | --- |
+| New user message | Right before that message | The system and developer messages, the summary as one user message, and the new message |
+| Tool step | After the latest tool result | The system and developer messages and the summary, from which it continues the task |
+
+The summary message starts by saying that the gateway replaced the earlier part of the conversation and that the user did not write it. It ends with the conversation's opening gateway note and user profile, so these survive compaction.
+
+Every later request that resends this history, including housekeeping and token-count requests, gets the same replacement; sub-agents usually send their own separate history and are not affected. Each compaction costs one provider cache miss at the cut, and caching works normally after that.
+
+**Nothing before the cut is kept word for word**, not even the latest turns. The model's earlier replies and their thinking depend on the history being replaced, and keeping only part of it would break Claude's thinking signatures. Everything generated after the cut is sent as usual, thinking included.
+
+### Finding what was cut {#finding-what-was-cut}
+
+The conversation itself is still saved in OpenViking. When **Save conversations** is on and the conversation has the `openviking_grep` and `openviking_read` tools, the summary ends with directions:
+
+- the conversation's OpenViking session (`viking://user/<user_id>/sessions/<session_id>/`) and where its messages are stored;
+- how to search them: grep the session for a specific pattern to get line numbers, then read the lines around a match.
+
+When a cut falls in the middle of a turn, the part before it is saved to OpenViking right away, so the model can search it within the same turn.
+
+## See compaction in the request log {#see-compaction-in-the-request-log}
+
+Expand a request on the **Requests** tab (see [Requests](10-overview-and-requests.md#requests)). Its **Context window** line shows:
+
+| Line | Meaning |
+| --- | --- |
+| About *X* of *Y* tokens (*P*%) | How full the window was estimated to be, and the window size *Y* the gateway used |
+| Sent with the earlier history replaced | The request carried a summary in place of the history before the cut |
+| Summary of about *N* tokens written in *T* | This request triggered compaction, and the summary took *T* to write |
+| Compaction failed (*reason*), so the full history was sent | See [When compaction fails](#when-compaction-fails) |
+| Summary kept, but usage is still at or above Compact at (`still_over_threshold`) | The summary was written and used, but the conversation still fills the window; see [When compaction fails](#when-compaction-fails) |
+
+## When compaction fails {#when-compaction-fails}
+
+If the summary request fails, or the reply calls a tool, is empty or is cut off at the length limit, the gateway sends the full history instead. The request detail shows **Compaction failed** with the reason, and the gateway does not try to compact this conversation again for 60 seconds.
+
+One case keeps the summary: if usage is still at or above **Compact at** after the summary is written (for example because the system prompt and tools alone fill most of the window), the gateway uses the summary, records the failure, and also waits 60 seconds before trying again.
+
+Each reason and its fix are listed under [Long conversations hit the context limit](12-troubleshooting.md#long-conversations-hit-the-context-limit).
+
+## Side effects {#side-effects}
+
+**No Working Memory summaries.** The summary comes from the conversation's own model, not from OpenViking's session summaries. New OpenViking sessions that the gateway creates have Working Memory turned off: commits still archive messages and extract memories, but no session summary is written.
+
+**The memory budget starts over.** **Budget per context window** (see [Recall memory](08-context-profiles.md#recall-memory)) resets after each compaction, so memory added before the cut may be added again.
+
+**The client still sends the full history.** After the gateway compacts, the client keeps sending its full history, and the gateway replaces the part before the cut on every request. The client sees small usage numbers, so clients that compact by usage rarely compact on their own.
+
+**Very long sessions can hit the request size limit.** Because the client's history keeps growing, a very long session can eventually exceed the request size limit: request bodies over 32 MiB are rejected with HTTP 413 (see [Clients get an error from the gateway](12-troubleshooting.md#clients-get-an-error-from-the-gateway)). Operators can change the limit with `max_body_bytes` (see [Gateway fields](13-configuration.md#gateway-fields)); a reverse proxy in front of the gateway must allow bodies at least as large (see [Reverse proxy and HTTPS](../guides/22-gateway-operations.md#reverse-proxy-and-https)).
+
+**A client's own compaction starts a new session.** When the client compacts or edits its history, the gateway saves the new history to a new OpenViking session. If the search tools are available, the opening gateway note of the new history tells the model where the earlier sessions are.
+
+## Experimental: agent-managed context windows {#experimental-agent-managed-context-windows}
+
+With **Agent-managed context windows** on (off by default), the model decides when to start a fresh context window and writes its own hand-off notes, instead of waiting for the gateway's summary. The gateway gives it two tools and reminds it as the window fills up. The setting only works in conversations that get [OpenViking tools](04-openviking-tools.md#agentic-memory-for-any-client); other conversations are [compacted](#long-conversations) as usual, and when compaction is on, it remains the fallback if the model never starts a new window.
+
+In Studio: **Profiles** → **Long conversations** → **Agent-managed context windows** (marked **Experimental**), with **Soft reminder at** (0.7) and **Hard reminder at** (0.85). How well this works depends on the model, and the behavior may change in later releases.
+
+### What the model gets {#what-the-model-gets}
+
+Two extra tools. They are not in the profile's **Tools** list; only this setting controls them.
+
+| Tool | What it does |
+| --- | --- |
+| `openviking_new_context(reason, notes, next_steps)` | Starts a new window; `next_steps` is optional. |
+| `openviking_context_remaining()` | Returns the window number, estimated tokens used and left, the user turns in this window, the time since the user's previous message, and a one-line recommendation. |
+
+`openviking_new_context` must be the only tool call in its round. Called together with other tools, every call in the round returns an error and the window is not reset. It also returns an error if the gateway already replaced the context at the same point in this request (for example, it just compacted).
+
+The model also sees:
+
+- **One more line in the opening gateway note**, telling the model that it manages its own context windows with these two tools.
+- **A status line**: after each new user message, the memory block ends with `[context-status] window wN · ~X/Y tokens (P%) · T since your previous message`.
+- **A soft reminder**: when the window reaches **Soft reminder at** (0.7), the gateway reminds the model once to start a new window after the current step, with notes that keep the exact paths, line numbers and values it will need.
+- **A hard reminder**: at **Hard reminder at** (0.85), it tells the model to start a new window now, and repeats on every step until the model does or compaction takes over.
+
+Reminders are attached to the new user message, or to the client's tool result in a tool step. They are not added between the gateway's own OpenViking tool rounds.
+
+### When the model starts a new window {#when-the-model-starts-a-new-window}
+
+When the model calls `openviking_new_context`, the gateway replaces the conversation so far with a window header, and the model carries on in the same reply. The header contains, in order:
+
+1. that this is window N, started by the model, and that the user did not write it;
+2. the reason, notes and next steps;
+3. the user's latest message, word for word;
+4. how to search earlier windows (under the same conditions as for [compaction](#finding-what-was-cut));
+5. the conversation's opening gateway note.
+
+Later requests rebuild the same window from the client's history. The content before the reset is saved to OpenViking right away and stays searchable; the reason and notes appear only in the header and are not saved to OpenViking. Each reset costs one provider cache miss but needs no summary request.
+
+In the request log, the **Context window** line of each request shows the window number ("Window *N*, managed by the model"), "The model started a new window" when it did, and which reminder the model received ("Reminded the model to start a new window soon" or "Told the model to start a new window now").
+
+## Next steps {#next-steps}
+
+- [Long conversations hit the context limit](12-troubleshooting.md#long-conversations-hit-the-context-limit): what each compaction failure reason means and how to fix it.
+- [Models](07-upstreams.md#models): where an upstream's **Context windows** sit among the other model settings.
+- [Context profiles](08-context-profiles.md#context-profiles): the other sections of a profile and their defaults.
+- [OpenViking tools in the gateway](04-openviking-tools.md#limits): limit the rounds and tokens of one request.
diff --git a/docs/en/gateway/06-manage-in-studio.md b/docs/en/gateway/06-manage-in-studio.md
new file mode 100644
index 000000000..4a35f796f
--- /dev/null
+++ b/docs/en/gateway/06-manage-in-studio.md
@@ -0,0 +1,95 @@
+---
+description: Find your way around the OpenViking Gateway pages in Studio, see who can change what, unlock editing and learn when changes apply.
+---
+
+# Manage OpenViking Gateway in Studio
+
+This page is for anyone who uses the gateway pages in Studio: what each tab is for, who can change what, and when saved changes take effect. Open Studio with your OpenViking API key (a server in [local dev mode](02-quickstart.md#local-server-no-api-key) needs none) and choose **OpenViking Gateway** in the sidebar; a standalone gateway serves its own Studio at `/studio/`. Upstreams and context profiles are shared by everyone in an OpenViking account, while gateway keys and request logs belong to each user.
+
+## Studio tabs {#studio-tabs}
+
+The gateway pages have six tabs. Each row links the page that explains the tab in detail.
+
+| Tab | What it is for | Whose data | Explained in |
+| --- | --- | --- | --- |
+| **Overview** | Health at a glance: request count, cache hit rates, recalled memory, OpenViking status and degraded requests. Before the first request, it shows the **Get started** checklist. | Your requests; account admins and root see the whole account | [Overview](10-overview-and-requests.md#overview), [Get started checklist](#get-started-checklist) |
+| **Upstreams** | Add, edit, test and import the model endpoints the gateway forwards requests to. | Shared by the account | [Upstreams](07-upstreams.md#upstreams) |
+| **Profiles** | Create and edit context profiles: recall, saving, long conversations and OpenViking tools. | Shared by the account | [Context profiles](08-context-profiles.md#context-profiles) |
+| **Keys** | Issue and revoke gateway keys; account admins and root can also delete a user's gateway data. | Your keys; account admins and root manage the whole account | [Gateway keys](09-gateway-keys.md#gateway-keys) |
+| **Requests** | The request log: each model request with its memory, tokens, issues and saving status. | Your requests; account admins and root see the whole account | [Requests](10-overview-and-requests.md#requests) |
+| **Connect** | The gateway address and copy-ready settings for each client. | Same for everyone | [Connect clients](03-connect-clients.md#connect-clients) |
+
+## Who can change what {#who-can-change-what}
+
+Whether you can edit [upstreams and context profiles](../guides/15-gateway.md#key-terms) depends on one deployment setting: the [gateway management key](../guides/22-gateway-operations.md#gateway-management-key). It is not set by default, and whoever deploys the gateway decides whether to set it.
+
+| Action in Studio | No management key set | Management key set |
+| --- | --- | --- |
+| View upstreams and context profiles, and pick them when issuing a key | Every signed-in user in the account | Every signed-in user; read-only views leave out upstream API keys and headers |
+| Add, change or delete upstreams and context profiles | Every signed-in user in the account | Only after you [unlock editing](#unlock-editing), account admins and root included |
+| Test an upstream (connection test or model test) | Every signed-in user in the account | Only after unlocking; while Studio is read-only, the **Test** button is hidden |
+| Import OpenViking model settings (embedded deployments only) | Root only, including local dev mode | Only after unlocking |
+| Issue gateway keys | Users for themselves; account admins for users in their account; root first switches account in the sidebar | Same; the management key adds no rights |
+
+Testing needs write access because a test uses the stored credentials, and a model test is billed by the provider. Key issuing is covered in [Gateway keys](09-gateway-keys.md#gateway-keys), and the full rules, including the management API, are in the [access matrix](../api/25-gateway.md#credentials-and-account-scope).
+
+If no usable upstream or context profile exists yet and you cannot change them, the **Get started** checklist says it is waiting for your gateway admin. Ask whoever deployed the gateway.
+
+## Unlock editing {#unlock-editing}
+
+When a [gateway management key](../guides/22-gateway-operations.md#gateway-management-key) is set, the Upstreams and Profiles tabs are read-only until you unlock them in your browser tab. An account admin's or root's API key does not unlock them, and neither does a gateway key (`ovgw_…`).
+
+1. On the Upstreams or Profiles tab, choose **Enter gateway management key** in the read-only notice.
+2. Paste the management key and choose **Unlock**. Keys generated by `openviking-server init`, `openviking-gateway init` or Studio's **Enable gateway** start with `ovgm_`; **Where can I find it?** in the dialog lists where it is stored.
+3. You should see **Unlocked. You can now edit upstreams and profiles.**, and the page header shows **Editing upstreams and profiles** with a **Lock** button.
+
+Editing stays unlocked only in that browser tab, until you choose **Lock** or close the tab. If the management key is changed on the server, Studio locks again on its own and shows **The gateway management key is no longer valid. Upstreams and profiles are read-only again.** If nobody has the key, see [Lost the management key](../guides/22-gateway-operations.md#lost-the-management-key).
+
+## Get started checklist and Quick mode {#get-started-checklist}
+
+The **Get started** checklist sits on the Overview tab until the first request arrives. It lists four steps in order: **Add an upstream**, **Create a context profile**, **Issue a gateway key** and **Connect a client**. Once a client sends its first request, the checklist goes away.
+
+Until the first [gateway key](../guides/15-gateway.md#key-terms) exists, the checklist also shows a **Quick mode** card. **Get a key** does the first three steps in one click:
+
+| Step | What Quick mode does |
+| --- | --- |
+| Upstream | Uses the usable upstreams you already have. If there is none, it [imports OpenViking's own model settings](07-upstreams.md#import-openviking-model-settings) (the VLM models in `ov.conf`) as upstreams. |
+| Context profile | Uses an existing context profile. If there is none, it creates one named "Default" with the recommended settings. |
+| Key | Issues a key named "Quick mode" for the current user, bound to every usable upstream. Outside local dev mode, root picks the key's user in the issue dialog instead. |
+
+An upstream counts as usable when all of these hold:
+
+- it is enabled;
+- the gateway stores its API key (it is not set to **Each client sends its own key**) and a key is saved;
+- it lists at least one model or alias (an empty **Models** list does not count, so Quick mode still imports model settings even if you already have such an upstream);
+- it is not a [Coding Plan upstream](07-upstreams.md#coding-plan-keys) that is still [blocked](07-upstreams.md#blocked-upstreams).
+
+Exceptions:
+
+- If the imported settings still give no model the gateway can relay directly, the card says so, and you add an upstream yourself in step 1 (**Add an upstream**).
+- When a management key is configured and Quick mode needs to create a context profile or import models, the card first asks you to unlock with the management key.
+- Only some users can import model settings: root (or anyone in local dev mode) when no management key is set, and whoever unlocks with the management key when one is set. A standalone gateway cannot import them at all. If you can't import, the card appears only once a usable upstream exists.
+
+## When changes take effect {#when-changes-take-effect}
+
+Saved changes to an upstream or a context profile apply to every gateway key that uses it, so you never need to reissue keys for them. What differs is whether a [conversation](../guides/15-gateway.md#key-terms) that is already under way sees the change:
+
+| What you change | When it applies |
+| --- | --- |
+| Any upstream setting except priority, such as the API key, models or **Enabled** | At once, in ongoing conversations too. For what turning an upstream off does to its conversations, see [Routing](07-upstreams.md#routing). |
+| Upstream priority | Only in conversations that start afterwards. An ongoing conversation stays on its upstream as long as that upstream can still serve it. |
+| Any context profile setting | Only in conversations that start afterwards. |
+| A gateway key | Keys cannot be edited. To change a key's context profile, upstreams, allowed models or user, issue a new key and revoke the old one; see [After issuing](09-gateway-keys.md#after-issuing). |
+
+A conversation records its context profile at its first request and keeps it, because changing what the model sees mid-conversation would break the provider's [prompt cache](01-how-it-works.md#replay). How soon a client picks up a profile change therefore depends on how often it starts a new conversation:
+
+- Clients that open a new conversation for every chat pick up changes quickly.
+- Claude Code, Codex and clients that send a fixed session header can continue one conversation for days. They keep the old settings until they start a new conversation, or until the conversation has been idle for 30 days (`session_ttl_days`), when the gateway deletes its state.
+
+How the gateway tells conversations apart is explained in [How conversations are recognized](03-connect-clients.md#how-conversations-are-recognized).
+
+## Next steps {#next-steps}
+
+- [Get started with OpenViking Gateway](02-quickstart.md): go from an empty gateway to a working key and a test request.
+- [Gateway management key](../guides/22-gateway-operations.md#gateway-management-key): set, change or reset the key that protects upstreams and context profiles.
+- [Studio shows a setup card](12-troubleshooting.md#studio-shows-a-setup-card): what to do when Studio shows a setup card instead of the gateway tabs.
diff --git a/docs/en/gateway/07-upstreams.md b/docs/en/gateway/07-upstreams.md
new file mode 100644
index 000000000..99e1302e3
--- /dev/null
+++ b/docs/en/gateway/07-upstreams.md
@@ -0,0 +1,230 @@
+---
+description: Add and configure the model endpoints that OpenViking Gateway forwards requests to.
+---
+
+# Manage gateway upstreams
+
+This page is for whoever adds or fixes the model endpoints that OpenViking Gateway forwards requests to: add an upstream that works the first time, then look up each editor field in the order Studio shows it. In Studio: **Upstreams** tab. Adding, changing and testing upstreams needs write access; see [Who can change what](06-manage-in-studio.md#who-can-change-what).
+
+## What an upstream is {#upstreams}
+
+An upstream is one endpoint of a model service that the gateway forwards requests to, and it uses exactly one API. The gateway does not convert between APIs, so add one upstream for each API your clients use, even when they come from the same provider:
+
+| Protocol | Used by |
+| --- | --- |
+| Anthropic Messages | Claude Code and Anthropic SDKs |
+| Chat Completions | Most chat apps and SDKs |
+| Responses | Codex CLI, when every request carries the full history (see [Client requirements](04-openviking-tools.md#client-requirements)) |
+
+Upstreams are shared by the whole account, but a [gateway key](09-gateway-keys.md#gateway-keys) reaches only the upstreams selected when it was issued.
+
+When you choose a provider in the editor, its default Base URL is filled in:
+
+| Provider | Protocols | Default Base URL |
+| --- | --- | --- |
+| Generic | All three | None; enter it yourself |
+| Anthropic | Anthropic Messages | `https://api.anthropic.com` |
+| OpenAI | Chat Completions, Responses | `https://api.openai.com/v1` |
+| DeepSeek | All three | `https://api.deepseek.com`; `https://api.deepseek.com/anthropic` for Anthropic Messages |
+| Volcano Engine Ark | All three | `https://ark.cn-beijing.volces.com/api/v3` for Chat Completions and Responses; `https://ark.cn-beijing.volces.com/api/compatible` for Anthropic Messages |
+| BytePlus ModelArk | All three | `https://ark.ap-southeast.bytepluses.com/api/v3` for Chat Completions and Responses; `https://ark.ap-southeast.bytepluses.com/api/compatible` for Anthropic Messages |
+
+## Add an upstream {#add-an-upstream}
+
+1. On the **Upstreams** tab, choose **Add upstream**. The **New upstream** editor opens with four sections: **Endpoint**, **Credentials**, **Models** and **Routing**.
+2. Under **Endpoint**, enter a **Name**, then choose the **Provider** and the **Protocol** your clients use. Below **Base URL**, **Requests go to** should show the full address of the provider's endpoint, for example `https://api.openai.com/v1/chat/completions`.
+3. Under **Credentials**, keep **The gateway holds the API key** and paste the provider's **API key**.
+4. Under **Models**, list the model names clients will request, or leave it empty to accept any name. Add a **Context windows** entry for any model with a window smaller than the default; see [Set the model's context window](05-long-conversations.md#context-window).
+5. Choose **Add upstream**. You should see **Added “&lt;name&gt;”** and the new upstream in the list. If the editor footer shows **Still to fill in or fix** instead, correct the fields it names.
+6. Choose **Test** on the new upstream's row, then choose a model and **Run test**. You should see **Connected**, then **Model works**; see [Test and delete](#test-and-delete) if not.
+7. [Issue a gateway key](09-gateway-keys.md#issue-a-key) that selects the upstream. Existing keys keep the upstreams they were issued with.
+
+## Endpoint {#endpoint}
+
+The **Endpoint** section sets where the gateway sends requests and which API the [upstream](#upstreams) speaks. A new upstream starts as provider *Generic* with protocol *Chat Completions*.
+
+| Field | What it decides |
+| --- | --- |
+| **Name** | The label shown in Studio and when you issue gateway keys. |
+| **Provider** | Which protocols you can pick, and how the gateway handles that provider's differences (below). |
+| **Protocol** | Which API the upstream accepts. Anthropic upstreams send both `x-api-key` and `Authorization: Bearer`; Chat Completions and Responses upstreams send only Bearer. |
+| **Base URL** | The provider address the gateway appends the endpoint to (see [How the Base URL is joined](#base-url)). |
+| **Append protocol endpoint path** | On by default. Turn it off only when the Base URL is already the complete request endpoint (see [Send to an exact endpoint](#exact-endpoint)). |
+
+### What each provider changes {#provider-differences}
+
+Choose *Generic* for a provider not in the list, for a compatible proxy such as LiteLLM or new-api, and for a reverse proxy such as [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) that exposes subscription accounts as an API; see [Custom upstreams](#custom-upstreams).
+
+- *Generic*, *Anthropic* and *OpenAI* forward requests the same way.
+- *DeepSeek*: when a request has tools, DeepSeek requires every earlier reply in the history to carry its reasoning, and many chat apps do not send it back. DeepSeek upstreams have [**Restore reasoning the client drops**](#restore-reasoning) on by default, so requests can keep thinking on and still get OpenViking tools. With that setting off, OpenViking tools are offered only when a request turns thinking off (`"thinking": {"type": "disabled"}`). Standard Responses requests have no `thinking` field, so they then get no tools. Memory is added as usual.
+- *Volcano Engine Ark* and *BytePlus ModelArk* behave the same: each Chat Completions and Responses conversation gets a fixed `prompt_cache_key`, so Ark's prefix cache follows the conversation. If a request's model, thinking mode, sampling parameters, system prompt or tools differ from the conversation's first request, Ark rebuilds its cache, and the request is flagged **Cache parameters changed** (see [Issues on degraded requests](12-troubleshooting.md#issues-on-degraded-requests)).
+
+### How the Base URL is joined {#base-url}
+
+Copy the Base URL from the provider's SDK documentation. The gateway appends the protocol's endpoint to it:
+
+| Protocol | Appended path | Note |
+| --- | --- | --- |
+| Chat Completions | `/chat/completions` | A bare domain does not get `/v1` added, so OpenAI needs `https://api.openai.com/v1`. |
+| Responses | `/responses` | Same as Chat Completions. |
+| Anthropic Messages | `/v1/messages` | The Base URL must not end in `/v1`; saving such a URL is rejected. |
+
+- A trailing slash is removed. Addresses with a version path, such as `/api/paas/v4`, work as is.
+- The Base URL may carry a query, such as `?api-version=…`. The client's query parameters follow it, and on a name clash the Base URL's value wins.
+- Requests that clients send to the Ark paths (`/gateway/api/v3/`, `/gateway/api/compatible/v1/`) follow the same rules.
+- An upstream has one Base URL. If a provider uses different addresses for different protocols, create separate upstreams.
+
+The editor previews the final request URL as you type. If an OpenAI or Ark address is missing its path, or an Anthropic address ends in `/v1`, it warns you and offers a one-click fix.
+
+Base URLs for some providers without a preset, all following the rules above:
+
+| Service | Protocol | Base URL |
+| --- | --- | --- |
+| Azure OpenAI (v1 API) | Chat Completions or Responses | `https://RES.openai.azure.com/openai/v1` |
+| Claude in Microsoft Foundry | Anthropic Messages | `https://RES.services.ai.azure.com/anthropic` |
+| Gemini (OpenAI-compatible API) | Chat Completions | `https://generativelanguage.googleapis.com/v1beta/openai` |
+| Zhipu | Chat Completions | `https://open.bigmodel.cn/api/paas/v4` |
+| Zhipu | Responses | `https://open.bigmodel.cn/api/v1` |
+| Ark Coding Plan | Chat Completions, Responses | `…/api/coding/v3` |
+| Ark Coding Plan | Anthropic Messages | `…/api/coding` |
+
+### Send to an exact endpoint {#exact-endpoint}
+
+Turn off **Append protocol endpoint path** when the Base URL is already the complete request endpoint. For example, an Azure OpenAI deployment uses:
+
+- **Protocol** *Chat Completions* and **Provider** *Generic*
+- **Base URL** `https://RES.openai.azure.com/openai/deployments/DEPLOYMENT/chat/completions?api-version=2024-10-21`
+- **Append protocol endpoint path** off
+- **Send the key as** *api-key header*
+
+The gateway then sends the protocol's requests to that exact URL without adding a protocol path. Sub-paths continue after it: Anthropic token counting goes to `…/count_tokens`. Other APIs, such as embeddings and the model list, are not routed to such an upstream, and the connection test skips it.
+
+## Credentials {#credentials}
+
+The **Credentials** section sets how the gateway signs in to the provider. By default the gateway holds the provider API key, and clients need only their [gateway key](09-gateway-keys.md#gateway-keys).
+
+- **Who provides the API key**:
+ - **The gateway holds the API key** (the default): the gateway sends the upstream's API key.
+ - **Each client sends its own key**: besides the gateway key, every request carries the client's own provider API key in the `X-OpenViking-Upstream-Key` header. Without it the request fails with 401 "Upstream API key is missing". The gateway passes the key on as set in **Send the key as**, or fills it into the URL when the Base URL contains `{api_key}`; `X-OpenViking-*` headers themselves are never forwarded. How each client adds the header is in [When each client sends its own provider key](03-connect-clients.md#bring-your-own-provider-key).
+- **Send the key as** (provider *Generic* only): `Authorization: Bearer` (the default), the `api-key` header (Azure OpenAI) or the `x-api-key` header.
+- **Key in the URL**: for a provider that expects the key in the address, write `{api_key}` in the Base URL's path or query, for example `?key={api_key}`. The gateway fills in the URL-encoded key when sending and then sends no auth header. Don't write the key itself into the address: the Base URL is visible to everyone who can view upstreams.
+- **API key**: stored encrypted and never shown again. Leave it blank to keep the stored key.
+- **Extra headers** are added to every request to this upstream, such as a provider's version or organization header, and replace any client header with the same name. Their values are write-only like the API key: leave a value blank to keep it, or remove the row to delete the header. `Host`, `Content-Length`, `Transfer-Encoding` and `Connection` cannot be set.
+
+> **Changing the Base URL clears the stored API key and header values.** Enter them again whenever you change the address. A stored key is never sent to a new address.
+
+### Coding Plan and subscription keys {#coding-plan-keys}
+
+Providers usually allow subscription keys such as Coding Plan keys only in their own coding tools, and using one through a shared gateway can get the subscription suspended. The gateway cannot tell from the key itself whether it is a subscription key, so you have to mark it: check **This key is a Coding Plan or subscription key**.
+
+Once marked, every request to the upstream is rejected with 403 "Coding Plan upstreams are disabled; configure a model API key", unless you also check **Allow this plan through the gateway**. Check that only after confirming that your plan permits use outside the provider's tools.
+
+Claude subscription tokens (`sk-ant-oat…`) are always rejected, whichever box you check; see [Behaviors to expect](01-how-it-works.md#what-to-expect).
+
+## Models {#models}
+
+The **Models** section sets which model names an [upstream](#upstreams) serves and what they are called at the provider. By default the list is empty and the upstream accepts any model name.
+
+| Field | What it does |
+| --- | --- |
+| **Models** | The model names this upstream serves. Only listed names and aliases appear in the model list (`/gateway/v1/models`). |
+| **Model aliases** | Map a name that clients use to the model sent to the upstream, for example the Claude model names Claude Code requests to a model your provider serves. Aliases appear in the model list, and the request log shows the name the client used. |
+| **Context windows** | Each model's window size in tokens (at least 1,024), keyed by the model name actually sent to the upstream, after aliases. |
+
+Long conversations are compacted at a share of the context window, so list every model whose window is smaller than the default; see [Set the model's context window](05-long-conversations.md#context-window).
+
+## Routing {#routing}
+
+The **Routing** section sets how the gateway chooses between upstreams. For each request, the gateway looks at the enabled [upstreams](#upstreams) bound to the key that use the request's API and serve the requested model, and picks the one with the highest **Priority**. Once a conversation starts, it stays on its upstream as long as that upstream can still serve it.
+
+| Field | Default | What it does |
+| --- | --- | --- |
+| **Priority** | 0 | Higher wins. A change affects only new conversations; see [When changes take effect](06-manage-in-studio.md#when-changes-take-effect). |
+| **Enabled** | On | A turned-off upstream receives no requests and disappears from the model list. |
+| **Allow OpenViking tools** | On | Whether [OpenViking tools](04-openviking-tools.md#choose-tools) can be offered through this upstream. Turning it off takes effect at once, also in conversations that already have the tools. |
+| **Restore reasoning the client drops** | Depends on the provider | Puts dropped reasoning back into later requests (below). |
+| **Minimum cacheable prompt** | 1,024 tokens | Ark and ModelArk only: the shortest prompt the model can cache. It only affects how the request log reports cache eligibility. |
+
+Turning an upstream off moves the conversations that were using it to the next candidate. That costs one provider cache miss and drops earlier Claude thinking blocks, and those requests are flagged **Upstream switched** (see [Issues on degraded requests](12-troubleshooting.md#issues-on-degraded-requests)). Turn an upstream off instead of deleting it if you may want it back.
+
+The gateway does not fail over: when the chosen upstream returns an error, the client receives it, and an unreachable provider returns 502 "Model upstream is unavailable".
+
+### Restore reasoning the client drops {#restore-reasoning}
+
+When clients send the history back, they often leave out the reasoning of the model's earlier replies. **Restore reasoning the client drops** is on by default for DeepSeek, Volcano Engine Ark and BytePlus ModelArk, and off for other providers.
+
+With it on, the gateway records the reasoning of every reply it relays and puts it back in later requests:
+
+- Chat Completions: `reasoning_content`.
+- Anthropic Messages: thinking blocks.
+- Responses: reasoning items with plain-text content, before their item.
+
+The restored content is byte-identical every time, so the provider's prompt cache keeps hitting, but it counts as input tokens. Replies whose reasoning the client sent back itself are left alone.
+
+Some requests cannot get their reasoning back even with this on: the conversation moved to another upstream (**Upstream switched**), a Claude conversation lost its memory record (**Memory record missing**), or the client sent thinking back as plain text. On a DeepSeek upstream, such requests also get no OpenViking tools.
+
+### Upstreams that fail every request {#blocked-upstreams}
+
+The upstream list flags two states in which every request to an upstream fails:
+
+| Label | Cause | Clients receive |
+| --- | --- | --- |
+| **Key missing** | The gateway holds the key but has none stored, for example after the Base URL changed. | 401 "Upstream API key is missing" |
+| **Requests blocked** | A [Coding Plan upstream](#coding-plan-keys) not allowed through the gateway. | 403 |
+
+Such an upstream still takes part in routing. If it has the highest priority among the matching upstreams, requests fail instead of moving to a lower-priority one. Fix it, or turn it off.
+
+## Test and delete {#test-and-delete}
+
+**Test** checks that an [upstream](#upstreams)'s saved endpoint, key, model and protocol work together. It always uses the saved settings, so save your changes first.
+
+1. Choose **Test** in the upstream list or in the upstream editor's header. The gateway checks the saved connection; you should see **Connected**. An exact endpoint has no model list to check, so this step is skipped.
+2. Select or enter a model name and choose **Run test**. The gateway sends one small generation request with the stored credentials; you should see **Model works**. The provider may charge for this request.
+
+The model test includes OpenViking tools when the upstream allows them and leaves reasoning effort at the model default. Each result is explained in [Upstream tests](../api/25-gateway.md#upstream-tests).
+
+**Test** is unavailable:
+
+- without write access, where it is hidden;
+- for upstreams set to **Each client sends its own key**, because there is no stored key to test with;
+- for upstreams that have no stored API key yet.
+
+Coding Plan upstreams stay blocked from model tests until **Allow this plan through the gateway** is checked.
+
+**Delete** removes the upstream together with its stored API key and headers. An upstream that keys still use cannot be deleted: the delete dialog offers **Disable** instead, or you can revoke those keys first.
+
+## Import OpenViking model settings {#import-openviking-model-settings}
+
+Importing turns the OpenViking server's VLM credentials into upstreams in the current account, so you need not retype them. It is available only in an embedded deployment. Choose **Import from OpenViking** in the Upstreams tab header; while the list is still empty, the button is called **Use OpenViking's model settings**. Without a management key, only root (including local dev) can import; with one, [unlock editing](06-manage-in-studio.md#unlock-editing) first.
+
+The result shows three groups: imported, needs confirmation and not imported.
+
+- **Needs confirmation**: upstreams whose Base URL has a path segment named `coding` or `plan` (for example `/api/coding/v3`) are marked as [Coding Plan](#coding-plan-keys). Once you have confirmed that the provider's terms allow it, check **Allow this plan through the gateway** to use one.
+- **Azure OpenAI** credentials (provider `azure`, or LiteLLM `azure/<deployment>`) become exact-endpoint upstreams that send the key in the `api-key` header, with the configured `api_version`.
+- **Not imported**: Codex OAuth credentials, LiteLLM credentials without `api_base`, and LiteLLM routes that do not use the OpenAI Chat Completions API. The reasons are listed in [Import VLM settings](../api/25-gateway.md#import-vlm-settings).
+
+Importing again does not create duplicates:
+
+| Refreshed from the server | Kept as you changed it in the gateway |
+| --- | --- |
+| Address, API key, headers, protocol, provider, the Coding Plan mark, **Append protocol endpoint path**, **Send the key as** | Name, enabled state, priority, models, aliases, context windows, **Allow this plan through the gateway** |
+
+If you uncheck the Coding Plan mark on an imported upstream, the next import marks it again, and the upstream is blocked until you check **Allow this plan through the gateway**.
+
+## Custom upstreams: proxies and subscription quota {#custom-upstreams}
+
+Any service that speaks one of the three APIs can be an upstream, not only a model provider. Two common uses:
+
+- **Billing, quotas and load balancing.** The gateway does none of these. If you need them, put a service such as LiteLLM or new-api behind the gateway and add it as an upstream.
+- **Subscription quota.** Clients cannot sign in to the gateway with a subscription, but you can add a reverse proxy such as [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) as an upstream. It exposes subscription accounts such as ChatGPT (Codex) and Claude as an API, so Codex, for example, can use a ChatGPT subscription through the gateway. OpenAI accepts this for Codex: Tibo, who leads Codex at OpenAI, has [publicly walked through](https://x.com/thsottiaux/status/2076119366647894371) connecting a Codex subscription this way, and the steps are in [Use a ChatGPT subscription](03-connect-clients.md#codex-chatgpt-subscription). **For any other subscription service, check its terms yourself before using it this way.**
+
+To add one, choose *Generic* as the provider and follow [Add an upstream](#add-an-upstream).
+
+API names, defaults and allowed values for every field are in [Upstream settings](13-configuration.md#upstream-settings).
+
+## Next steps {#next-steps}
+
+- [Issue a gateway key](09-gateway-keys.md#issue-a-key) that selects your upstreams.
+- [Connect a client](03-connect-clients.md#connect-clients) to the gateway.
+- [Set up a context profile](08-context-profiles.md#context-profiles) for recall and saving.
+- [The upstream returned an error](12-troubleshooting.md#the-upstream-returned-an-error) if requests fail.
diff --git a/docs/en/gateway/08-context-profiles.md b/docs/en/gateway/08-context-profiles.md
new file mode 100644
index 000000000..d8a49ae3b
--- /dev/null
+++ b/docs/en/gateway/08-context-profiles.md
@@ -0,0 +1,109 @@
+---
+description: Create context profiles that decide how OpenViking Gateway recalls and saves memory for each gateway key.
+---
+
+# Manage gateway context profiles
+
+In Studio: **Profiles** tab. A context profile decides how OpenViking Gateway recalls memory, saves conversations, handles long conversations and offers OpenViking tools for every gateway key that uses it. This page walks through each section of the profile editor and its defaults; changing profiles needs write access, see [Who can change what](06-manage-in-studio.md#who-can-change-what).
+
+## What a context profile is {#context-profiles}
+
+A [context profile](../guides/15-gateway.md#key-terms) is a named set of memory settings. Each [gateway key](09-gateway-keys.md#gateway-keys) uses one profile, chosen when the key is issued, and one profile can serve many keys. For example, a "Coding" profile might recall memories, resources and skills, while a "Chat" profile recalls only memories, with a smaller budget.
+
+A profile has four sections. The defaults below are also the recommended settings:
+
+| Section | What it does | Main settings and defaults |
+| --- | --- | --- |
+| Recall memory | Searches OpenViking with each new user message and appends what is relevant to that message. | Sources: memories, resources, skills · Budget per message: 1,600 tokens · Budget per context window: 30,000 tokens · Relevance threshold: 0.35 · Time limit: 2 s |
+| Save conversations | Writes finished turns to an OpenViking session and commits it, so OpenViking can extract memories. | Save the latest reply after: 600 s · Commit after: 20,000 tokens · Keep recent messages: 10 |
+| Long conversations | When a conversation nears the context window, has the same model write a summary that replaces the earlier messages. | Compaction: on · Compact at: 0.9 of the window · Summary length: 8,000 tokens · Agent-managed context windows: off |
+| OpenViking tools | Lets the model use OpenViking's tools while it answers. | On · read-only tools selected; see [OpenViking tools](04-openviking-tools.md) |
+
+Each section has its own switch, and Long conversations has one each for compaction and agent-managed context windows. Recall and saving are independent: a profile can recall without saving, or save without recalling.
+
+Saved changes reach only conversations that start afterwards; see [When changes take effect](06-manage-in-studio.md#when-changes-take-effect).
+
+### Create, duplicate or delete a profile {#manage-profiles}
+
+1. Open the **Profiles** tab. While it is empty, choose **Create with recommended settings** to create a profile named "Default" in one click, or **Customize** to open the editor first. Once a profile exists, use **New profile** instead.
+2. In the editor, enter a **Name**; it is shown when someone chooses a profile for a gateway key. Change the sections described on this page as needed.
+3. Choose **Create profile**, or **Save** when you edit an existing one. You should see a card for the profile that summarizes each section and counts the keys that use it (**Not used by any key** at first).
+
+Other actions:
+
+- **Duplicate**, on a card or in the editor's **More actions** (⋯) menu, opens a copy named "Copy of …". It is the quickest way to make a variant.
+- **Reset to recommended**, in the same menu, restores the recommended settings; save to apply them.
+- A profile that keys use cannot be deleted. Revoke those keys first, or, if they are still needed, issue replacements that use another profile.
+- While Studio is read-only, cards show **View** instead of **Edit**, and creating, duplicating and deleting are unavailable; see [Unlock editing](06-manage-in-studio.md#unlock-editing).
+
+## Recall memory {#recall-memory}
+
+The **Recall memory** section (on by default) controls [recall](../guides/15-gateway.md#key-terms): for each new user message, the gateway searches OpenViking and appends what is relevant to that message. What the model then receives is shown in [What the model sees](01-how-it-works.md#what-the-model-sees). The settings, in the order the editor shows them:
+
+| Setting | Default | What it controls |
+| --- | --- | --- |
+| **User profile at conversation start** | On | Gives the model your OpenViking user profile when a conversation starts. |
+| **Opening context budget** | 4,000 tokens | The most the profile and the memory and skill catalogs may use at the start. |
+| **Show recall summary** | Off | Starts the reply with a one-line summary; see [Recall summary](#recall-summary). |
+| **Sources** | Memories, resources, skills | What recall searches. |
+| **Budget per message** | 1,600 tokens | The most memory added to one message. |
+| **Budget per context window** | 30,000 tokens | The most memory added within one context window. |
+| **Relevance threshold** | 0.35 | Only results scoring at least this much, from 0 to 1, are added. Higher means fewer but closer matches. |
+| **Time limit** | 2 s | How long the search may take. |
+| **Query length** (under **Advanced settings**) | 8,000 characters | How much of the message is used as the search query. |
+| **Limit by category** (under **Advanced settings**) | Off | The most entries each category may add. |
+
+How the settings work together:
+
+- **Opening context.** **User profile at conversation start** works independently of recall. When the OpenViking `read` tool (`openviking_read`) is offered, memory and skill catalogs are added at the start as well. Skills get at most a quarter of the **Opening context budget**, and 0 leaves all of it out. This budget does not count against the recall budget; see [The opening context](01-how-it-works.md#the-opening-context).
+- **What is added.** OpenViking selects and formats the recalled content within the budget. It may also return just a URI for the model to read later.
+- **Search query.** The query is the user message with client noise removed, cut to **Query length** characters. Messages shorter than 3 characters are not searched.
+- **Budgets.** Each message gets at most the smaller of **Budget per message** and what is left of **Budget per context window**. With less than 64 tokens left, the search is skipped. The budget per context window starts over whenever the conversation is compacted, by the gateway or by the client. These token counts are conservative estimates, not the provider's billing counts.
+- **Turning recall off.** Setting **Budget per context window** to 0 turns recall off; **Budget per message** is at least 64.
+- **Time limit.** If OpenViking does not answer within the **Time limit**, the message goes to the model without memory and does not get it later, even if the client retries.
+- **Limit by category.** It sets a maximum number of entries for each of six categories: events, entities, preferences, experiences, resources and skills. Only categories above 0 are searched. When it is off, all sources are ranked together.
+
+### Recall summary {#recall-summary}
+
+The recall summary is a short note at the start of the reply that names what OpenViking added to a new user message, or says why recall failed. It is off by default; turn on **Show recall summary** in the **Recall memory** section of the [context profile](#context-profiles). The model never sees it. For example:
+
+```text
+> OpenViking context: user profile, memory index, skill list, earlier sessions
+> OpenViking recall: 4 items (3 memories, 1 resource) — booking_duplicate_handling, user_lang_pref, +2 more
+```
+
+- The `context` line appears only in the first reply of a conversation. It lists what the opening actually contained: the user profile, the memory catalog, the skill catalog, and where earlier parts of the conversation are stored in OpenViking.
+- The `recall` line counts the recalled entries by kind and names up to three. If the search fails, it gives the reason instead, for example `> OpenViking recall failed: OpenViking unavailable`. It is left out when nothing was found, recall is off or the budget is used up, so after the first reply such messages get no summary.
+- Tool steps and other follow-up requests show no summary. When the client retries the same message, the summary is the same as the first time.
+- In Anthropic Messages the summary is its own text block, in Responses its own assistant message, and in Chat Completions the start of the reply text. Requests that ask for structured output, and Chat Completions requests with `n` above 1, get no summary.
+- When the client sends the reply back with the next message, the gateway removes the summary before forwarding, and it is not saved to OpenViking.
+
+## Save conversations {#save-conversations}
+
+The **Save conversations** section (on by default) controls [saving](../guides/15-gateway.md#key-terms): the gateway writes finished turns to an OpenViking session and commits it, so OpenViking can extract memories. How the gateway decides that a turn is finished is explained in [When conversations are saved](01-how-it-works.md#when-conversations-are-saved).
+
+| Setting | Default | What it controls |
+| --- | --- | --- |
+| **Save the latest reply after** | 600 s | How long the latest turn waits for a follow-up before the gateway saves it and commits the session. |
+| **Commit after** | 20,000 tokens | How many tokens may wait in the session before it is committed. |
+| **Keep recent messages** | 10 | How many messages stay in the session after a commit. |
+
+- A turn is saved when the next user message arrives. **Save the latest reply after** covers the last turn, so short conversations get committed too.
+- The session is committed whenever **Commit after** tokens are waiting. After each commit, OpenViking extracts memories in the background.
+- After a commit, the session keeps the newest whole turns, at least **Keep recent messages** messages.
+
+## Long conversations and OpenViking tools {#long-conversations-and-tools}
+
+The last two sections of the editor each have their own page:
+
+- **Long conversations** holds **Compaction** with **Compact at** and **Summary length**, the experimental **Agent-managed context windows** with **Soft reminder at** and **Hard reminder at**, and **Default context window** under **Advanced settings**. See [Long conversations in the gateway](05-long-conversations.md#long-conversations); for models with a smaller window, set the window as described in [Set the model's context window](05-long-conversations.md#context-window).
+- **OpenViking tools** holds the **Tools** list and **Show tool calls**, with **Rounds per request**, **Time limit per call**, **Result size**, **Total time** and **Token budget** under **Advanced settings**. See [Choose tools](04-openviking-tools.md#choose-tools) and [Limits](04-openviking-tools.md#limits). The gateway runs the selected tools without the client's permission prompts; read [Risks and controls](04-openviking-tools.md#risks-and-controls) before checking tools that change data.
+
+The API name and range of every setting are in the [Configuration reference](13-configuration.md#context-profile-settings).
+
+## Next steps {#next-steps}
+
+- [Issue a gateway key](09-gateway-keys.md#issue-a-key) that uses the profile.
+- Check recall and saving per request in the [request log](10-overview-and-requests.md#requests).
+- If memory never shows up, see [No memory is added](12-troubleshooting.md#no-memory-is-added).
+- Follow one turn end to end in [How OpenViking Gateway works](01-how-it-works.md#what-happens-once-you-connect).
diff --git a/docs/en/gateway/09-gateway-keys.md b/docs/en/gateway/09-gateway-keys.md
new file mode 100644
index 000000000..efde9cffe
--- /dev/null
+++ b/docs/en/gateway/09-gateway-keys.md
@@ -0,0 +1,84 @@
+---
+description: Issue gateway keys that connect clients to OpenViking Gateway, and manage them over time.
+---
+
+# Manage gateway keys
+
+This page is for anyone issuing gateway keys: users issuing one for themselves, and account admins issuing keys for others or cleaning up after a user. You will issue a key, copy it into a client, and know what happens to it when it is revoked or its user's OpenViking API key changes. You need at least one [upstream](07-upstreams.md#upstreams) and one [context profile](08-context-profiles.md#context-profiles) first.
+
+## What a gateway key is {#gateway-keys}
+
+In Studio: **OpenViking Gateway** → **Keys**. A gateway key (`ovgw_…`) is what a client uses in place of a provider API key. Each key binds:
+
+- **One OpenViking user.** The gateway recalls and saves memory as that user, with that user's own [OpenViking API key](../guides/22-gateway-operations.md#keys-and-credentials), so a key can never do more than its user; see [Isolation by user](11-security-and-data.md#isolation-by-user).
+- **One context profile**, which decides how its conversations recall and save memory.
+- **A set of upstreams**, optionally narrowed to a list of allowed models.
+
+The **Keys** tab lists your own keys. Account admins and root see every key in the account, with an **OpenViking user** column. The **Key** column shows only the first characters of each key.
+
+## Issue a key {#issue-a-key}
+
+If the **Keys** tab asks you to add an upstream or create a context profile first, do that, or ask whoever deployed the gateway if you cannot. On a new gateway, **Get a key** in the Overview tab's **Quick mode** card does all of this in one click; see [Get started checklist and Quick mode](06-manage-in-studio.md#get-started-checklist).
+
+1. On the **Keys** tab, choose **Issue key**. The **Issue a gateway key** dialog opens.
+2. Enter a **Name** that tells keys apart; the person and the client make a good name, for example "Alice · Claude Code".
+3. Under **Who is this for?**, choose the OpenViking user whose memory the key reads and writes; see [Who the key is for](#who-the-key-is-for).
+4. Choose a **Context profile** and at least one of the **Upstreams**. The key can reach only the upstreams you select; for each request the gateway picks one of them that speaks the client's protocol and serves the requested model ([Routing](07-upstreams.md#routing)).
+5. Optionally fill in **Allowed models**; see [Limit the models a key can use](#allowed-models).
+6. Choose **Issue key**. The gateway first checks the user's OpenViking API key with OpenViking. You should see the **Copy your gateway key** dialog. If the dialog shows **Couldn't issue the key** instead, see [Issuing a key fails](12-troubleshooting.md#issuing-a-key-fails).
+7. Choose **Copy gateway key**, and copy the setup for Claude Code, Codex CLI or a chat client, which already contains the real key and gateway address. If a client tab says the key has no enabled upstream for its protocol, that client cannot use this key. Choose **I've copied it** when you are done.
+
+The key works as soon as it is issued. The **Copy your gateway key** dialog is the only time you see the full key: the gateway keeps only a hash and the first few characters. If a key is lost, issue a new one. For other clients, see [Connect clients](03-connect-clients.md#connect-clients).
+
+### Who the key is for {#who-the-key-is-for}
+
+The gateway recalls and saves memory as the user you choose under **Who is this for?**. Who you can choose depends on who you are:
+
+| You are | Who you can issue keys for |
+| --- | --- |
+| A user | Only yourself. Studio shows "Read and write memory as you (&lt;user&gt;)", and you never need to paste a key. |
+| An account admin | Any user or admin in your account. |
+| Root | Switch account in the sidebar first, then choose a user in that account. A root API key cannot be bound to a gateway key. |
+| Anyone, in local dev mode | Keys read and write memory as the `default` user. |
+
+Issuing a key for yourself never needs a pasted key, unless you are root. To issue a key for someone else, the gateway reads that user's API key from OpenViking. If OpenViking stores only key hashes, it cannot: the user is marked "The server can't read this user's API key; paste it instead", and a **Paste &lt;user&gt;'s user API key** field appears for that user's current key. You can also choose **Paste a user API key** to enter a key directly. If the user list cannot be loaded, Studio asks for an **OpenViking API key** instead.
+
+A gateway key lets its holder use the user's memory, so the right to issue keys for others amounts to reading every user's memory in the account; see [Access control](11-security-and-data.md#access-control).
+
+### Limit the models a key can use {#allowed-models}
+
+**Allowed models** is empty by default, which allows every model the key's [upstreams](07-upstreams.md#upstreams) serve. To restrict a key, enter the model names clients send, including aliases. The key's model list then shows only those names, and requests for any other model are rejected before they reach a provider. A key with allowed models also needs every request to name its model; for the exact errors, see [Clients get an error from the gateway](12-troubleshooting.md#clients-get-an-error-from-the-gateway).
+
+## After issuing {#after-issuing}
+
+A [gateway key](#gateway-keys) is fixed once issued, but the conversations it started belong to its user.
+
+- **Keys cannot be edited.** To change a key's context profile, upstreams, allowed models or user, issue a new key and revoke the old one.
+- **Conversations belong to the user, not the key.** If the client sends the same session ID, a new key for the same user continues the existing [conversation](03-connect-clients.md#how-conversations-are-recognized), so replacing a key does not interrupt it.
+- **Revoking** a key (**Revoke** on the **Keys** tab, then **Revoke key**) stops it working at once. The user's conversation state and logs stay until they are explicitly deleted or expire. Turns not yet saved to OpenViking, such as the latest reply, are saved only if the conversation continues with a new key.
+
+### One key per person {#one-key-per-person}
+
+Memory belongs to the OpenViking user behind a [gateway key](#gateway-keys), so everyone who shares a key shares that user's memory. Issue one key per person. Also issue separate keys per client if you want different context profiles, or want to revoke each client on its own.
+
+### When the user's OpenViking API key changes {#when-the-openviking-key-changes}
+
+Each gateway key depends on its user's current [OpenViking API key](../guides/22-gateway-operations.md#keys-and-credentials). After that key is regenerated or the user is deleted, OpenViking rejects the old key the gateway stored. The gateway notices on a later request (up to about 30 seconds later) and deletes the gateway keys bound to it; conversation state and logs stay. Issue a new key with the current OpenViking API key.
+
+If OpenViking is only unreachable or returns an error, the gateway keeps the key, and requests still reach the model, just without memory.
+
+## Delete a user's gateway data {#delete-a-users-gateway-data}
+
+Revoking keys does not delete what the gateway keeps for a user. To delete it, an account admin or root opens the **…** menu on one of the user's keys on the **Keys** tab, chooses **Delete this user's gateway data…** and confirms with **Delete gateway data**. This:
+
+- revokes all of the user's gateway keys, so their clients lose access at once;
+- deletes the conversation state the gateway keeps for them, including content not yet saved to OpenViking;
+- deletes their request logs.
+
+Memories already in OpenViking are not affected. For the API call, account-wide deletion and when to use it, see [Deleting data](11-security-and-data.md#deleting-data).
+
+## Next steps {#next-steps}
+
+- [Connect clients](03-connect-clients.md#connect-clients): put the key into Claude Code, Codex or another client.
+- [Check the connection](03-connect-clients.md#check-the-connection): confirm requests and memory arrive.
+- [OpenViking Gateway security and data](11-security-and-data.md): what the gateway stores for each user and how long.
diff --git a/docs/en/gateway/10-overview-and-requests.md b/docs/en/gateway/10-overview-and-requests.md
new file mode 100644
index 000000000..73e4a8460
--- /dev/null
+++ b/docs/en/gateway/10-overview-and-requests.md
@@ -0,0 +1,149 @@
+---
+description: Read the cards, columns, request types and saving status on OpenViking Gateway's Overview and Requests tabs in Studio.
+---
+
+# Gateway overview and request log
+
+This page explains every card, column, label and saving status on the gateway's **Overview** and **Requests** tabs, and which values mean the gateway is healthy. In Studio, open **OpenViking Gateway** and choose the **Overview** or **Requests** tab. Both tabs stay empty until a client sends its first request through the gateway; see [Connect clients](03-connect-clients.md#connect-clients).
+
+## Who sees which requests {#requests-and-overview}
+
+Both tabs read the gateway's request log: one record per model request that went through the gateway. Users see only their own requests; account admins and root see the whole account's. The Overview figures are computed from the same records, so they cover the same requests.
+
+The log holds metadata only, never prompts, replies or memory text; see [What request logs record](11-security-and-data.md#what-request-logs-record). Records are kept for 30 days by default; see [Retention](11-security-and-data.md#retention).
+
+## Overview {#overview}
+
+The **Overview** tab summarizes the latest 10,000 requests in the request log. Until the first request arrives, it also shows the **Get started** checklist; see [Get started checklist and Quick mode](06-manage-in-studio.md#get-started-checklist).
+
+| Card | What it shows | Healthy value | If it looks wrong |
+| --- | --- | --- | --- |
+| **Requests** | The number of model requests (background saving events, shown as **Memory sync** in the log, are not counted), when the last one arrived, and their output tokens | Grows as clients send requests | [Check the connection](03-connect-clients.md#check-the-connection) |
+| **First-call cache hit rate** | The share of input tokens the provider served from its [prompt cache](01-how-it-works.md#replay) on the first model call of each new user message | Close to what the provider reaches without the gateway. This is the most important sign of a healthy gateway. | [The first-call cache hit rate dropped](12-troubleshooting.md#the-first-call-cache-hit-rate-dropped) |
+| **Within-turn cache hit rate** | The same share for later calls in a turn, such as tool steps and OpenViking tool rounds | Usually high | — |
+| **Memory entries recalled** | Memory entries added to new messages, and how long an OpenViking search took on average (counting only messages that searched) | Grows once the user has memories in OpenViking; 0 is expected on a brand-new account | [No memory is added](12-troubleshooting.md#no-memory-is-added) |
+| **OpenViking** | **Connected**, **Degraded** or **Starting**, the OpenViking version, and the reason when degraded. Its **Saving conversations** part counts conversations that are retrying or have paused saving. | **Connected**, and no saving problems in recent requests | [OpenViking is degraded](12-troubleshooting.md#openviking-is-degraded), [Conversations do not appear in OpenViking](12-troubleshooting.md#conversations-do-not-appear-in-openviking) |
+| **Degraded requests** | How often each issue occurred, with an explanation and a suggested action | **No degraded requests** | [Issues on degraded requests](12-troubleshooting.md#issues-on-degraded-requests) |
+| **Recent requests** | The latest requests, with a link to the **Requests** tab | — | [Requests](#requests) |
+
+A clear drop in the first-call rate usually means the history the gateway sends no longer matches the previous request. While OpenViking is unreachable, requests still reach the model, just without memory, and saving is retried until OpenViking is back. When the **Saving conversations** part or the **Degraded requests** card reports a problem, **Show in Requests** opens the **Requests** tab filtered to **Issues**.
+
+### Long conversations missing the cache {#long-conversations-missing-the-cache}
+
+A warning such as "2 long conversations keep missing the prompt cache" appears below the four number cards at the top (**Requests**, **First-call cache hit rate**, **Within-turn cache hit rate** and **Memory entries recalled**) when a conversation's last 3 model calls each sent at least 32,000 input tokens, less than 5 minutes apart, and the provider reported 0 cached tokens every time. It lists the model, upstream and streak of each conversation. When they are all Anthropic conversations whose upstream never wrote the cache either, the warning suggests checking that the client sets `cache_control`.
+
+The cache cannot hit across these changes, so a streak starts over at each of them:
+
+- a [compaction](05-long-conversations.md#long-conversations), or the model starting a new context window
+- a switch to another model or upstream
+- gateway tools appearing in or disappearing from the requests
+
+When an upstream has not reported any cache hit lately, you see a note instead: long conversations through that upstream keep showing a 0% cache hit rate. For causes and fixes, see [The first-call cache hit rate dropped](12-troubleshooting.md#the-first-call-cache-hit-rate-dropped).
+
+## Requests {#requests}
+
+The **Requests** tab lists the latest 1,000 records of the request log, newest first, and refreshes every 30 seconds while you are on the first page. Filters and search cover those 1,000 records.
+
+Only requests that reached a model provider are logged. Requests the gateway rejects first are not, such as an invalid key, a model the key does not allow, no matching upstream or a body over the size limit; the client receives the error directly. See [Clients get an error from the gateway](12-troubleshooting.md#clients-get-an-error-from-the-gateway).
+
+### Filter and search {#filter-and-search}
+
+| Filter | Shows |
+| --- | --- |
+| **All** | Every record |
+| **New messages** | Requests that start a turn with a new user message |
+| **Tool steps** | Requests that continue a turn, for example with tool results |
+| **Issues** | Degraded requests, requests whose conversation saving is **Retrying** or **Paused**, and requests where the provider returned HTTP 400 or above (see [The upstream returned an error](12-troubleshooting.md#the-upstream-returned-an-error)) |
+| **Request type** | One of the [request types](#request-types) |
+
+Search matches the model, conversation ID, request ID, key name or prefix, and upstream name. The log stores only a hash of the conversation ID, so Studio hashes a pasted conversation ID in the browser before matching. This works only when Studio is opened over HTTPS or on localhost; over plain HTTP, searching by conversation ID finds nothing.
+
+### Columns {#columns}
+
+| Column | Shows |
+| --- | --- |
+| **Time** | When the request arrived |
+| **Type** | The [request type](#request-types) |
+| **Model** | The model name the client sent |
+| **Status** | The HTTP status the provider returned |
+| **Tokens** | Input tokens, the cached share and output tokens |
+| **Memory** | What [recall](../guides/15-gateway.md#key-terms) did in this request (see below) |
+| **Saving** | The conversation's [saving status](#saving-status); hover for the reason |
+| **Issue** | The issue, for a degraded request |
+
+The **Memory** column uses this notation:
+
+| Shown | Meaning |
+| --- | --- |
+| `+3` | This request's search added 3 memory entries; the search time is shown next to it. |
+| `↺ 4` | Memory added to 4 earlier messages was replayed unchanged. |
+| **Recall failed** | This request's memory search did not finish, for example because OpenViking was unreachable, rejected the key, or did not answer within the context profile's **Time limit**. Hover for the reason, and see [No memory is added](12-troubleshooting.md#no-memory-is-added). |
+
+### Request details {#request-details}
+
+Expand a row to see:
+
+- the conversation ID, upstream, gateway key and duration
+- the token breakdown
+- the memory search result
+- context window use, and whether the history was compacted or the model started a new window
+- the saving status, with the next retry time
+- OpenViking tool details, including why tools were not offered
+
+For a request with an issue, the expanded row also explains what happened and what to do.
+
+### Request types {#request-types}
+
+Every record has one type. The type decides whether the request searches memory and whether its turn is saved.
+
+| Type | Meaning | Memory |
+| --- | --- | --- |
+| New message | A request whose last message is a new user message | Searched once, earlier memory replayed; the turn is saved |
+| Tool step | The same turn continuing, for example with tool results | Earlier memory replayed; saved with its turn |
+| Housekeeping | Title, summary, compaction, suggestion and permission-check requests | Earlier memory replayed; never saved |
+| Sub-agent | Requests from a client's sub-agents | Earlier memory replayed; never saved |
+| Token count | Token-counting requests (`/gateway/v1/messages/count_tokens`) | Earlier memory replayed, so the count matches what is actually sent |
+| Forwarded | Requests passed through unchanged, without memory: other endpoints, Responses requests that rely on provider-side state, compressed or unreadable bodies | None |
+| Memory sync | Background saving events, not model requests | — |
+
+## Saving status {#saving-status}
+
+The **Saving** column shows whether the gateway is [saving](../guides/15-gateway.md#key-terms) a conversation's finished turns to OpenViking. Normally it shows **On**.
+
+| Status | Meaning | What the gateway does |
+| --- | --- | --- |
+| **On** | Saving works normally. | — |
+| **Off** | The conversation's [context profile](08-context-profiles.md#save-conversations) does not save. | Nothing is saved. |
+| **Retrying** | OpenViking rejected a save or could not be reached. | Retries after 10, 20, 40 and 80 seconds. |
+| **Paused** | Five attempts in a row failed. | Retries every 5 minutes until it succeeds. Unsaved turns are kept until they are saved or the conversation expires. |
+| **Paused** with the reason `gateway_key_revoked` | The conversation's gateway key was revoked or deleted. | Stops retrying. Saving resumes when the user next sends a request in this conversation with a valid key. |
+
+The expanded row and the **Saving** badge's tooltip show the reason for the latest change:
+
+| Reason shown | Code | Meaning |
+| --- | --- | --- |
+| OpenViking rejected the key. It may be wrong or revoked. | `openviking_http_401` | The user's OpenViking key is no longer valid. |
+| OpenViking is unreachable or didn't answer in time | `openviking_unavailable` | OpenViking is down, unreachable or too slow. |
+| Saving to OpenViking failed | `delivery_failed` | A save failed for another reason; the gateway retries as above. |
+| Saving works again | `delivery_recovered` | A save succeeded after failures. |
+| The conversation history changed, so saving continues in a new OpenViking session | `history_changed` | Normal: the client edited, regenerated or compacted the conversation, and the gateway continues saving the current history in a new OpenViking session. |
+| The history changed while saving, so saving continues in a new OpenViking session | `history_changed_during_delivery` | Normal: the same, while a save was in progress. |
+| A saved turn continued after a pause, so saving continues in a new OpenViking session | `continued_after_idle` | Normal: a turn already saved after **Save the latest reply after** continued. |
+| Resynced by an administrator | `manual_reset` | Someone used **Resync conversation…** (see below). |
+
+Earlier turns stay in the older OpenViking session. If saving stays at **Retrying** or **Paused**, see [Conversations do not appear in OpenViking](12-troubleshooting.md#conversations-do-not-appear-in-openviking).
+
+### Resync a conversation {#resync-a-conversation}
+
+Resync starts a new OpenViking session for a conversation, and the gateway writes the full history to it with the user's next message. Use it when a conversation stays paused after you fixed the cause, or when you want a clean copy of a conversation. What was already saved stays in the old session, so OpenViking may extract some memories twice.
+
+1. On the **Requests** tab, expand a record of the conversation. Resync needs the key shown on the record; if that key has been revoked, pick a newer record of the same conversation.
+2. Choose **Resync conversation…**, then **Resync**. You should see "The conversation will be saved again with its next message."
+3. Wait for the user's next message in that conversation. Nothing happens until it arrives; then the gateway saves the full history to the new session, and the conversation's records show the reason "Resynced by an administrator".
+
+## Next steps {#next-steps}
+
+- [Troubleshoot OpenViking Gateway](12-troubleshooting.md#common-symptoms): match a card, label or status to its cause and fix.
+- [Replay and prompt caching](01-how-it-works.md#replay): why the first-call cache hit rate matters.
+- [Monitoring](../guides/22-gateway-operations.md#monitoring): check the gateway's state outside Studio.
+- [Security and data](11-security-and-data.md#what-request-logs-record): what the log records and how long it is kept.
diff --git a/docs/en/gateway/11-security-and-data.md b/docs/en/gateway/11-security-and-data.md
new file mode 100644
index 000000000..66bdbd01d
--- /dev/null
+++ b/docs/en/gateway/11-security-and-data.md
@@ -0,0 +1,120 @@
+---
+description: What OpenViking Gateway stores, who can reach it, what providers see, and how data is kept, deleted and backed up.
+---
+
+# OpenViking Gateway security and data
+
+This page is for operators and security reviewers approving a gateway deployment, and for users who want to know what the gateway keeps about them. Sessions and memories always live in OpenViking under its own rules; the gateway keeps only its settings, the state it needs to continue conversations, and metadata-only request logs, in two SQLite files under `storage_path`. Each section below answers one review question and can be linked on its own.
+
+## Isolation by user {#isolation-by-user}
+
+Each [gateway key](../guides/15-gateway.md#key-terms) is bound to one OpenViking user. The gateway searches memory, saves conversations and calls tools with that user's own OpenViking key, so it can never do more than the user can. Each user's conversation state is kept separate from every other user's.
+
+## What the gateway stores {#what-the-gateway-stores}
+
+Everything the gateway keeps is in two SQLite databases in `storage_path` (default `~/.openviking/gateway`):
+
+| File | What it holds |
+| --- | --- |
+| `management.sqlite3` | Upstreams, context profiles, gateway keys, request logs, and which upstream created each Responses response |
+| `kernel.sqlite3` | The state of each conversation: the memory text added to messages, OpenViking tool rounds and their results, summaries, conversation text waiting to be saved, and the reasoning of model replies when **Restore reasoning the client drops** is on |
+
+Some of this is sensitive:
+
+- `management.sqlite3` holds upstream API keys, header values and the OpenViking keys bound to gateway keys. Gateway keys themselves are stored only as a hash and a short prefix.
+- `kernel.sqlite3` holds memory text word for word, because the gateway needs it to [replay](01-how-it-works.md#replay) what it added in earlier turns.
+
+Only the system user that runs the gateway can read the files. With [encryption](../guides/22-gateway-operations.md#encryption) on, every stored value is encrypted as well; with it off, the credentials above are in plain text, protected only by file permissions.
+
+## What request logs record {#what-request-logs-record}
+
+Request logs hold metadata only, never content:
+
+| Recorded | Never recorded |
+| --- | --- |
+| Request type, model, status, upstream | Message text |
+| A hash of the conversation ID | Recalled memory |
+| Token counts, memory counts and timing | Tool arguments or results |
+| Saving status and issues | Any key |
+
+The gateway writes no HTTP access log, and its error messages never repeat submitted values. To read the logs in Studio, see [Requests](10-overview-and-requests.md#requests).
+
+## What providers see {#what-providers-see}
+
+Every [upstream](../guides/15-gateway.md#key-terms) receives the full model input, including memory the gateway added and OpenViking tool results. Only add providers you trust with that data.
+
+Some things never leave the gateway: `X-OpenViking-*` headers, client credentials and cookies are never forwarded to upstreams. When an upstream takes each client's own provider key, that key reaches the provider only as the upstream's credential.
+
+## Access control {#access-control}
+
+Four things grant access through the gateway, and each has a limit worth knowing:
+
+| Credential | What it allows | What to watch |
+| --- | --- | --- |
+| [Gateway key](09-gateway-keys.md#gateway-keys), sent in `Authorization: Bearer` or `x-api-key` | Model requests as the bound user: recall memory, save conversations, call OpenViking tools | Can be revoked at any time on the **Keys** tab |
+| [Gateway management key](../guides/22-gateway-operations.md#gateway-management-key) | Only changes to upstreams and context profiles | Grants no access to memory or logs and no right to issue keys |
+| An account admin's right to issue keys | Issuing gateway keys for any user in the account | Amounts to reading the memory of every user in the account |
+| One-time token in an upload or download link | Calls to `/gateway/uploads` and `/gateway/downloads`, which need no gateway key | The token travels in the query string |
+
+Two of these need care:
+
+- **Issuing keys.** A gateway key lets its holder recall memory and call tools as that user, so give the right to issue keys only to admins you trust. When OpenViking stores only key hashes, the user has to supply their own OpenViking key.
+- **Upload and download links.** Each link is authorized by a one-time token signed by OpenViking, and the gateway only forwards it to OpenViking's upload or download endpoint. Keep their query strings out of proxy logs.
+
+The full rules, including the management API, are in the [access matrix](../api/25-gateway.md#credentials-and-account-scope). What each role can do in Studio is in [Who can change what](06-manage-in-studio.md#who-can-change-what).
+
+## Retention {#retention}
+
+Gateway data expires on its own. A cleanup job runs every hour:
+
+| Data | Kept for | Setting |
+| --- | --- | --- |
+| Conversation state | 30 days after last use | `session_ttl_days` |
+| Request logs | 30 days | `log_retention_days` |
+| Which upstream created each Responses response | 30 days | `response_ttl_seconds` |
+| Sessions and memories in OpenViking | OpenViking's own rules | — |
+
+Minimums and where to set these are in [Gateway fields](13-configuration.md#gateway-fields).
+
+## Deleting data {#deleting-data}
+
+Revoking a gateway key, or the bound OpenViking key becoming invalid, does not delete user data. There are three ways to delete it:
+
+| Who | How | What is deleted |
+| --- | --- | --- |
+| Account admin or root | **Delete this user's gateway data…** in Studio ([steps](09-gateway-keys.md#delete-a-users-gateway-data)), or `DELETE /gateway/admin/users/{user_id}/data` | One user: revokes their gateway keys and deletes their conversation state and logs, including content not yet saved |
+| Root | `DELETE /gateway/admin/account/data?account_id=<account>` | All gateway data of an account |
+| Embedded deployment, automatically | Deleting a user or account in OpenViking | The matching gateway data |
+
+A standalone deployment has no automatic step; its data stays until it is explicitly deleted or [expires](#retention).
+
+None of this touches memories and sessions already stored in OpenViking. The reverse also holds: after you delete a memory in OpenViking, the copy the gateway saved for an ongoing conversation is still replayed until that conversation expires. To clear it now, delete the user's gateway data.
+
+## Backups and recovery {#backups}
+
+Back up these, together:
+
+- The whole `storage_path` directory: both databases and their `-wal` and `-shm` files.
+- With encryption on, OpenViking's encryption root key (not the root API key), as the [Encryption guide](../guides/08-encryption.md) describes.
+
+For a consistent copy, stop the gateway first, or use SQLite's online backup while it runs:
+
+```bash
+sqlite3 kernel.sqlite3 ".backup kernel.backup.sqlite3"
+sqlite3 management.sqlite3 ".backup management.backup.sqlite3"
+```
+
+What losing each piece means:
+
+| Lost | What happens | What to do |
+| --- | --- | --- |
+| `kernel.sqlite3` | Memory added earlier cannot be replayed. Each ongoing conversation takes one provider cache miss, Claude conversations lose their earlier thinking once ([**Memory record missing**](12-troubleshooting.md#issues-on-degraded-requests)), and turns not yet saved are lost. | None; ongoing conversations recover after one miss |
+| `management.sqlite3` | Upstreams, context profiles, keys and request logs are gone. | Set them up again and issue new keys |
+| Encryption root key (encryption on) | The encrypted values in both databases cannot be read. | Start again with an empty `storage_path` |
+
+## Next steps {#next-steps}
+
+- [Encryption](../guides/22-gateway-operations.md#encryption): turn on encryption for stored credentials and conversation state.
+- [Delete a user's gateway data](09-gateway-keys.md#delete-a-users-gateway-data): the Studio steps for removing one user.
+- [Routine checks](../guides/22-gateway-operations.md#day-to-day-operations): what to check regularly, including backups.
+- [Access matrix](../api/25-gateway.md#credentials-and-account-scope): every operation and the credential it needs.
diff --git a/docs/en/gateway/12-troubleshooting.md b/docs/en/gateway/12-troubleshooting.md
new file mode 100644
index 000000000..f369043af
--- /dev/null
+++ b/docs/en/gateway/12-troubleshooting.md
@@ -0,0 +1,218 @@
+---
+description: Match an OpenViking Gateway symptom, Studio label or error code to its cause and fix.
+---
+
+# Troubleshoot OpenViking Gateway
+
+Use this page when a client gets an error, memory or saving is missing, or Studio flags a problem. Look in three places first: the **OpenViking** card on the **Overview** tab, the **Requests** tab filtered to **Issues**, and the server log (`docker compose logs openviking` with Docker Compose, or the standalone gateway's own output). Then find your symptom in the table below; each section reads on its own and links to the setting involved.
+
+## Common symptoms {#common-symptoms}
+
+| Symptom | Likely cause | What to do |
+| --- | --- | --- |
+| The server stops right after you enable the gateway | The embedded gateway failed its startup checks. | [The gateway does not start](#the-gateway-does-not-start) |
+| Studio shows a card instead of the gateway tabs | The gateway is off, your OpenViking API key is missing or invalid, or the gateway cannot reach OpenViking. | [Studio shows a setup card](#studio-shows-a-setup-card) |
+| The Upstreams and Profiles tabs are read-only | The deployer set a gateway management key. | [Unlock editing](06-manage-in-studio.md#unlock-editing); if nobody has the key, [Lost the management key](../guides/22-gateway-operations.md#lost-the-management-key) |
+| **Couldn't issue the key** | The OpenViking API key behind the new gateway key did not pass the check. | [Issuing a key fails](#issuing-a-key-fails) |
+| A client gets an error and the request is not in the log | The gateway rejected the request before it reached a provider. | [Clients get an error from the gateway](#clients-get-an-error-from-the-gateway) |
+| A request in the log shows HTTP 400 or above | The provider rejected or failed the call. | [The upstream returned an error](#the-upstream-returned-an-error) |
+| A conversation gets no recall and is not saved | An OpenViking plugin was detected, and the gateway left recall, saving and tools to the plugin. | Expected: it keeps content from being added or saved twice. See [When both are in use](../guides/15-gateway.md#when-both-are-in-use). |
+| Requests go without memory | OpenViking unreachable or too slow, budget used up, nothing relevant, and so on. | [No memory is added](#no-memory-is-added) |
+| Saving shows **Retrying**, then **Paused** | OpenViking rejected the save or could not be reached, or the conversation's gateway key was revoked (`gateway_key_revoked`), for example after the user's OpenViking key was regenerated. | Saving resumes on its own once OpenViking is back. After a revocation, issue a new gateway key; the user's next request resumes saving. See [Conversations do not appear in OpenViking](#conversations-do-not-appear-in-openviking). |
+| The profile has tools on, but the conversation has none | No request that could use tools has arrived yet, loading the tool list failed on the first one, the client does not send the full history, or the client has its own OpenViking tools. | Check the reason in the request log; see [When tools are not offered](04-openviking-tools.md#when-tools-are-not-offered). **The client already has OpenViking tools** (`tool_name_collision`) is expected when the client has the OpenViking MCP server; for other reasons, fix the cause and start a new conversation. |
+| The **First-call cache hit rate** dropped, or Overview warns about cache misses | Memory could not be replayed, the conversation switched upstreams, or the client or relay changes the request prefix. | [The first-call cache hit rate dropped](#the-first-call-cache-hit-rate-dropped) |
+| The provider rejects a long conversation as too long | The gateway does not know the model's real window and compacts too late. | [Long conversations hit the context limit](#long-conversations-hit-the-context-limit) |
+| A file import or download link fails | `public_url` is missing or wrong, or the proxy does not forward the file paths. | [File imports or downloads fail](#file-imports-or-downloads-fail) |
+| A request is flagged with an issue label | The gateway could not fully handle that request. | [Issues on degraded requests](#issues-on-degraded-requests) |
+
+## The gateway does not start {#the-gateway-does-not-start}
+
+When an embedded gateway cannot start, the whole OpenViking Server stops. Read the startup error in the server log (`docker compose logs openviking` with Compose) and match it below.
+
+| Problem (log text) | Cause and fix |
+| --- | --- |
+| v0.5 data without the old key (`holds data encrypted by OpenViking Gateway 0.5`) | The storage directory holds data encrypted by the v0.5 gateway, but there is neither `OPENVIKING_GATEWAY_ENCRYPTION_KEY` nor `encryption.key` in `storage_path`. Provide the original key; see step 5 of [Migration](../guides/22-gateway-operations.md#migration). |
+| Removed flags or fields (`unrecognized argument --…`, `Extra inputs are not permitted`) | A standalone gateway was started with a removed `openviking-gateway` flag, or its `gateway.conf` still has a field it does not accept, such as `enabled`. Move the settings into `gateway.conf` or environment variables; see step 2 of [Migration](../guides/22-gateway-operations.md#migration). Leftover fields in the `gateway` section of `ov.conf` only log `Ignoring removed gateway settings` and do not stop startup. |
+| Management key too short (`management_key must resolve to at least 32 characters`) | The [gateway management key](../guides/22-gateway-operations.md#gateway-management-key) needs at least 32 characters. An unset environment variable referenced with `$VAR` causes the same error. |
+| Encryption settings (`Gateway data is encrypted; configure the encryption settings it was written with`, or an encryption config error) | The server's `encryption` section (embedded) or the `encryption` block in `gateway.conf` (standalone) is missing, invalid, or its encryption root key cannot be loaded. See the [Encryption guide](../guides/08-encryption.md). |
+| Incompatible storage (`Unsupported gateway schema`) | The storage directory was written by an incompatible gateway version (an older one, or a newer one if you downgraded). Use a fresh, empty `storage_path`. |
+| Standalone without an OpenViking URL (`OpenViking Gateway needs an OpenViking server URL`) | Run `openviking-gateway init`, or set `OPENVIKING_GATEWAY_OPENVIKING_URL`. |
+| Standalone config file not found (`Gateway config file not found`) | The file named by `--config` or `OPENVIKING_GATEWAY_CONFIG_FILE` does not exist. Fix the path, or create the file with `openviking-gateway init --config <path>`. |
+| Standalone on a non-loopback address (`A publicly bound OpenViking Gateway requires a successful synchronous probe`) | The startup check must reach OpenViking and confirm `api_key` authentication, or the gateway exits. Start OpenViking first (in containers, wait until it is ready), or bind to `127.0.0.1`. |
+| OpenViking in trusted mode (`OpenViking Gateway does not support trusted authentication`) | Standalone only: the startup check refuses OpenViking's trusted mode on any bind address. Switch OpenViking Server to `api_key` authentication (`server.auth_mode`); see [Startup checks](../guides/22-gateway-operations.md#startup-checks). |
+
+## Studio shows a setup card {#studio-shows-a-setup-card}
+
+Studio shows a setup card in place of the gateway tabs when it cannot load the gateway for you. The card title names the problem:
+
+| Card | What to do |
+| --- | --- |
+| **The gateway is not enabled on this OpenViking server** (404) | Run `openviking-server init` → **Update gateway**, or set `gateway.enabled: true` in `ov.conf` and restart; see [Enable it in the server](../guides/22-gateway-operations.md#enable-it-in-the-server). On a server that uses API keys, root can choose **Enable gateway** on the card instead. Account admins and regular users see a card that only asks them to contact whoever deployed the server. |
+| **Connect to OpenViking first**, or **Your OpenViking API key is invalid** (401) | Choose **Open connection settings** and enter your current OpenViking API key. |
+| **The gateway does not support Trusted mode** (`trusted_mode_unsupported`) | Switch the server to `api_key` authentication. |
+| **The gateway cannot reach OpenViking** (`openviking_unreachable`) | Standalone gateways only: check `openviking_url` (in `gateway.conf` or `OPENVIKING_GATEWAY_OPENVIKING_URL`) and the network. |
+| **Couldn't load the OpenViking Gateway** | Any other failure. The card shows the gateway's message; choose **Retry**, and match the message against the sections on this page. |
+
+Read-only **Upstreams** and **Profiles** tabs are not a setup card: the deployer set a [gateway management key](../guides/22-gateway-operations.md#gateway-management-key) (`management_key_required`), and an OpenViking root or admin API key does not unlock editing. Choose **Enter gateway management key**; see [Unlock editing](06-manage-in-studio.md#unlock-editing). After the key is changed on the server (`management_key_invalid`), Studio locks again, and if nobody has the key, see [Lost the management key](../guides/22-gateway-operations.md#lost-the-management-key).
+
+## Issuing a key fails {#issuing-a-key-fails}
+
+Before it issues a [gateway key](09-gateway-keys.md#issue-a-key), the gateway checks the bound OpenViking API key with OpenViking. When that check fails, the **Issue a gateway key** dialog shows why; the code in parentheses is the `reason` the management API returned.
+
+| Message in Studio | Cause and fix |
+| --- | --- |
+| The server only stores a hash of this user's API key and cannot read it. Paste their user API key instead. (`user_key_unreadable`) | OpenViking Server stores only key hashes (`encryption.api_key_hashing.enabled`). Choose **Paste a user API key** and enter that user's own key. |
+| This is a root API key. Use the user API key of a user in this account. (`root_key_not_allowed`) | A root API key cannot be bound to a gateway key. Use the API key of a user or account admin instead. Local dev mode's `default/default` is exempt. |
+| A root API key has no user of its own. Choose the user this key is for. (`user_required`) | You are signed in to Studio as root and chose neither a user nor a pasted key. Choose the user, or paste their key. |
+| This OpenViking API key belongs to another account. (`other_account`) | The key belongs to a different account from the one you are managing in Studio. |
+| OpenViking rejected this key. (`openviking_http_401`, `openviking_http_403`) | The key is incomplete or was regenerated, or the user was deleted. Use the user's current key. |
+| OpenViking couldn't tell which user this key belongs to (`openviking_identity_missing`) | OpenViking returned no user for this key. Use the key of a user in this account. |
+| The gateway couldn't reach OpenViking to check this key. (`openviking_unavailable`) | The gateway cannot reach OpenViking; for a standalone gateway, check `openviking_url`. |
+| OpenViking is older than the gateway requires. (`openviking_version_mismatch`) | Standalone gateways only: OpenViking Server is older than `min_server_version` (0.4.16). Upgrade it. A server installed from source without version tags may report a development version such as `0.1.dev123`; install a release, or set `min_server_version` to match. |
+| You don't have permission to do this. (`forbidden`) | The pasted OpenViking API key belongs to a different user than the one selected in the dialog, for example an admin pasted their own key instead of the chosen user's. Paste the selected user's own key, or select the user the key belongs to. A regular user gets the same error when the pasted key is not their own. |
+| This user is no longer in this account. Choose another user. (`unknown_user`) | The selected user was removed from the account while the dialog was open. `unknown_policy` and `unknown_upstream` mean the same for the selected context profile or upstream. Refresh and choose again. |
+
+## Clients get an error from the gateway {#clients-get-an-error-from-the-gateway}
+
+The gateway checks each client request before forwarding it: the gateway key, the model and a matching upstream. These rejections happen before the request reaches a provider, so they do not appear in the request log. For an error the provider itself returned, see [The upstream returned an error](#the-upstream-returned-an-error).
+
+| Status and message | Cause and fix |
+| --- | --- |
+| 401 "Invalid gateway key. It may have been revoked, or removed because its OpenViking API key was regenerated…" | The client sent no gateway key, a revoked key or its provider API key, or the gateway deleted the key after the user's OpenViking API key was regenerated. Check which key the client actually sends, and [issue a new one](09-gateway-keys.md#issue-a-key) if needed. |
+| 403 "Claude subscription OAuth credentials are not supported" | The client sent a Claude subscription token, for example Claude Code signed in with a subscription and no `ANTHROPIC_AUTH_TOKEN` set; or the upstream stores a subscription token. Use an API key. |
+| 403 "Model is not allowed by this key" | The model is not in the key's [allowed models](09-gateway-keys.md#allowed-models). Issue a key that allows it. |
+| 400 "Request model is missing", 415 "Compressed request bodies are not supported" | Only for keys that allow specific models: the request body must name a model and must not be content-encoded. |
+| 404 "This upstream is an exact endpoint for … only" | **Append protocol endpoint path** is off on the key's upstream ([Send to an exact endpoint](07-upstreams.md#exact-endpoint)), so it accepts only that protocol's endpoint, and the client called another path, such as `/v1/models`. |
+| 404 "No allowed upstream matches this protocol and model" | No enabled upstream bound to the key uses the API the client called and serves the requested model. Check the upstreams' protocol, models and aliases, whether they are enabled, and which upstreams the key is bound to. |
+| 401 "Upstream API key is missing" | The upstream expects each client to send its own key in `X-OpenViking-Upstream-Key`, or an upstream where the gateway holds the key has none stored. See [Credentials](07-upstreams.md#credentials). |
+| 403 "Coding Plan upstreams are disabled; configure a model API key" | The upstream is marked as a [Coding Plan key](07-upstreams.md#coding-plan-keys). Use a model API key, or deliberately check **Allow this plan through the gateway**. |
+| 403 "Context policy is unavailable" | The key's context profile no longer exists. Issue a new key with an existing context profile. |
+| 404 "Unknown response for this key", 403 "Response upstream is no longer allowed" | The Responses response being looked up was not created with this key, or the upstream that created it is now turned off or no longer bound to the key. |
+| 413 "Request exceeds configured body limit" | The request body is larger than `max_body_bytes` (see [the request size limit](05-long-conversations.md#side-effects)), or than your proxy's own limit. |
+| 426 | A WebSocket connection to the Responses API. Expected: Codex falls back to HTTP. |
+| 502 "Model upstream is unavailable" | The gateway could not reach the provider, or the call took longer than `upstream_timeout_seconds`. Choose **Test** on the upstream ([Test and delete](07-upstreams.md#test-and-delete)). |
+
+"Hidden tool request timed out" (504) happens after the provider call and is logged; see [Failure handling](04-openviking-tools.md#failure-handling).
+
+## The upstream returned an error {#the-upstream-returned-an-error}
+
+An upstream error is one the provider itself returned. Its row on the **Requests** tab has an HTTP status of 400 or above and no gateway issue, and the details read **The upstream answered with HTTP …, and the client received this error.** The gateway passed the provider's error to the client unchanged.
+
+Common causes are a wrong or expired API key, a model name the provider does not know, a rate limit or quota, a conversation longer than the model's context window, or a provider outage. Choose **Test** on the [upstream](07-upstreams.md#test-and-delete) and compare with the error the client received. For context-length errors, see [Long conversations hit the context limit](#long-conversations-hit-the-context-limit).
+
+## OpenViking is degraded {#openviking-is-degraded}
+
+The **OpenViking** card on the Overview tab shows the gateway's latest OpenViking health check. **Connected** is healthy; the other states are:
+
+- **Starting**: the gateway has not finished its first check yet. An embedded gateway checks every second until OpenViking is up. Refresh in a minute.
+- **Degraded**: the last check failed. The card names the reason:
+
+| Reason | What to do |
+| --- | --- |
+| OpenViking is unreachable or didn't answer in time (`openviking_unavailable`) | OpenViking is not running or cannot be reached. For a standalone gateway, check `openviking_url` and the network. |
+| OpenViking returned HTTP … (`openviking_http_<status>`) or OpenViking reported error … (`openviking_<CODE>`) | OpenViking answered with an error. Check the OpenViking server log. |
+| `trusted_mode_unsupported` | OpenViking runs in trusted mode. Switch it to `api_key` authentication. |
+
+While OpenViking is degraded, requests still reach the model without memory, and saving is retried until it is back. The gateway checks again at growing intervals, up to `health_interval_seconds` (60 by default).
+
+## No memory is added {#no-memory-is-added}
+
+[Recall](08-context-profiles.md#recall-memory) searches OpenViking on each new user message and adds what it finds; when it adds nothing, the request log says why. First find the request on the **Requests** tab. If it is not there, the client did not go through the gateway, or the gateway rejected the request (see [Clients get an error from the gateway](#clients-get-an-error-from-the-gateway)). If it is there, expand it and read **Recall** in the details:
+
+| Recall result | Meaning | What to do |
+| --- | --- | --- |
+| **Nothing relevant found** (`empty`) | Normal for a new user. Memories exist only after a conversation is committed and OpenViking has extracted them. | Keep using it; see [Conversations do not appear in OpenViking](#conversations-do-not-appear-in-openviking) if memories never appear. |
+| **Recall is off or the budget is used up** (`disabled`) | The context profile has recall off, the context window has less than 64 tokens of recall budget left, or the message is shorter than 3 characters. | Turn recall on in the context profile if it is off. |
+| **Too little budget left to add memory** (`budget`) | After the memory wrapper, this message's recall budget left fewer than 64 tokens for results, so no search ran. The conversation has nearly used up its **Budget per context window** (it starts over in the next context window, for example after compaction), or **Budget per message** is set close to its 64-token minimum. | Raise **Budget per message** if it is near the minimum. |
+| **OpenViking is unreachable or didn't answer in time** (`openviking_unavailable`), **Recall timed out** (`recall_timeout`) | The search did not finish. | Check the OpenViking card (see [OpenViking is degraded](#openviking-is-degraded)). If OpenViking is running but slow, raise the **Time limit**. |
+| **OpenViking rejected the key** (`openviking_http_401`) | The user's OpenViking key is no longer valid. | Issue a new gateway key with the current key; see [When the user's OpenViking API key changes](09-gateway-keys.md#when-the-openviking-key-changes). |
+| **OpenViking returned HTTP …** (`openviking_http_<status>`) or **OpenViking reported error …** (`openviking_<CODE>`) | The search failed inside OpenViking. An OpenViking Server older than `min_server_version` can also fail this way. | Check the OpenViking server log. |
+| **OpenViking plugin in use** (`plugin_present`) | The gateway detected an OpenViking plugin and stepped aside for this conversation. | Expected; see [When both are in use](../guides/15-gateway.md#when-both-are-in-use). |
+| The **Type** is not **New message** | Tool steps, housekeeping and sub-agent requests never search; they replay the memory earlier messages received. | Nothing to do; see [Request types](10-overview-and-requests.md#request-types). |
+
+A message whose search failed never gets memory later; the next message searches again.
+
+## Conversations do not appear in OpenViking {#conversations-do-not-appear-in-openviking}
+
+[Saving](08-context-profiles.md#save-conversations) writes each finished turn to an OpenViking session named `gateway-…`, owned by the OpenViking user behind the gateway key. When a turn you expect is missing, match what you see:
+
+| What you see | Why | What to do |
+| --- | --- | --- |
+| The latest turn is missing | Saving runs one turn behind: a turn appears when the next message arrives, and the last turn waits for **Save the latest reply after** (10 minutes by default). | Wait, or send the next message. |
+| The **Saving** column shows **Off** | The context profile does not save conversations. | Turn saving on in the context profile; it reaches only new conversations ([When changes take effect](06-manage-in-studio.md#when-changes-take-effect)). |
+| **Retrying** or **Paused** | Saving failed; the expanded row shows the reason. | Fix the cause (for example, make OpenViking reachable again); the gateway retries within 5 minutes. With `gateway_key_revoked`, issue a new gateway key; the next request resumes saving. If the conversation stays paused, use **Resync conversation…** ([Resync a conversation](10-overview-and-requests.md#resync-a-conversation)). |
+| **OpenViking plugin in use** (`plugin_present`) | The gateway saves nothing for a conversation in which it detected an OpenViking plugin. | Expected; use either the plugin or the gateway for a given client. |
+| Only part of the conversation is in the session | The gateway writes the current history to a new `gateway-…` session when the client edits, regenerates or compacts it (`history_changed`, `history_changed_during_delivery`), when a turn already saved after **Save the latest reply after** continues (`continued_after_idle`), or after **Resync conversation…** (`manual_reset`). Earlier turns stay in the older session. | Look in the older session too; see [Saving status](10-overview-and-requests.md#saving-status). |
+| No `gateway-…` sessions at all | You are looking as a different OpenViking user from the one behind the gateway key. | Sign in as that user. |
+| Sessions appear, but memories do not yet | OpenViking extracts memories in the background, only after a commit. | Wait for extraction to finish. |
+
+## The first-call cache hit rate dropped {#the-first-call-cache-hit-rate-dropped}
+
+The **First-call cache hit rate** on the Overview tab is the share of input tokens the provider served from its [prompt cache](01-how-it-works.md#replay) on the first model call of each new user message. Healthy is close to what the provider reaches without the gateway, so compare with that first. Then look at the issues flagged on recent requests and at the Overview notes:
+
+| What you see | Cause | What to do |
+| --- | --- | --- |
+| **Memory record missing** (`missing_injection_record`) | The gateway's storage was lost or restored from an old backup, or the record expired, so memory added earlier could not be replayed. | Nothing; ongoing conversations recover after one miss. |
+| **Upstream switched** (`upstream_changed`) | The conversation's upstream was turned off, is not bound to the key the client now uses, or no longer serves the model, so the conversation moved to another upstream. | Turn the upstream back on or give the client a key that includes it; see [Routing](07-upstreams.md#routing). |
+| **Cache parameters changed** (`ark_cache_parameters_changed`) | On Ark or ModelArk, the client changed the model, thinking mode, sampling parameters, system prompt or tools within a conversation. | Keep them the same within a conversation. |
+| No issue flagged | The client itself may change earlier messages or its system prompt every turn, for example by inserting the current time, which the gateway cannot fix. Each compaction, and each new context window the model starts, also costs one miss; that is expected. | Check the client's system prompt for content that changes every request. |
+| **… long conversations keep missing the prompt cache**, or a hit rate that stays at 0%, and the provider's or relay's cache records show hits | The upstream isn't passing cache usage back to the gateway, for example a relay that drops the cache fields when it converts protocols. The gateway reads the common fields, such as `cache_read_input_tokens`, `prompt_tokens_details.cached_tokens`, `input_tokens_details.cached_tokens` and `prompt_cache_hit_tokens`. | Make the relay pass cache usage through. |
+| The same, or **… hasn't reported any cache hits lately**, and the provider's records show no hits either | Caching is not happening at all. | Check that the provider supports prompt caching, that an Anthropic client sets `cache_control`, and that the relay isn't rotating between accounts or channels. |
+
+## Long conversations hit the context limit {#long-conversations-hit-the-context-limit}
+
+[Compaction](05-long-conversations.md#long-conversations) replaces the earlier history of a long conversation with a summary before it fills the model's context window. When the provider still rejects a long conversation as too long, it is usually one of three causes:
+
+| Cause | Fix |
+| --- | --- |
+| The gateway does not know the model's window: the upstream's **Context windows** has no entry for the model and the profile has no **Default context window**, so the gateway falls back to its 1,000,000-token default and compacts too late for a smaller model. | Add the model's window; see [Set the model's context window](05-long-conversations.md#context-window). |
+| The conversation's context profile has compaction off. | Turn it on; profile changes reach only new conversations ([When changes take effect](06-manage-in-studio.md#when-changes-take-effect)). |
+| Compaction failed. The request details show **Compaction failed** with one of the reasons below. | See the reason table. |
+
+| Reason | Cause and fix |
+| --- | --- |
+| `summary_incomplete` | The summary reply did not finish normally, usually because it hit the length limit. Raise **Summary length**. |
+| `summary_http_<status>` | The summary request was rejected, by the upstream or by the gateway before sending (no upstream key, or a blocked Coding Plan). Check the upstream's key, the model and the Coding Plan setting. A 400 has already been retried once without the extra output headroom. |
+| `summary_unavailable` | The upstream could not be reached, timed out (`upstream_timeout_seconds`) or returned something other than JSON. |
+| `summary_tool_call`, `summary_empty` | The model called a tool, or returned no text, instead of writing a summary. |
+| `cut_not_found` | The client's latest messages did not line up with the stored history, so the gateway could not choose a cut point. Usually transient. |
+| `summary_failed` | An unexpected internal error. Check the gateway log for "OpenViking Gateway summary failed". |
+| `still_over_threshold` | The summary was written and kept, but usage is still at or above **Compact at**: the system prompt, tools and summary alone fill most of the window. Lower **Summary length**, or check the model's context window setting. |
+
+For every reason except `still_over_threshold`, the request was sent with the full history. For every reason, the gateway waits 60 seconds before trying to compact that conversation again.
+
+## File imports or downloads fail {#file-imports-or-downloads-fail}
+
+[Importing files](04-openviking-tools.md#import-files-and-skills) gives the client upload and download links on the gateway's [public address](../guides/22-gateway-operations.md#public-address). Match the error you see:
+
+| Error | Fix |
+| --- | --- |
+| "Set gateway.public_url for client uploads and downloads" | Set `public_url` to an address the client can reach, or set `mcp_file_links` to `direct`. |
+| The upload or download link is unreachable or returns 404 | Make sure `public_url` is not an old `:1935` address, does not already end in `/gateway`, and that your proxy forwards `/gateway/uploads` and `/gateway/downloads` like the other paths. With `mcp_file_links` set to `direct`, check the server's `OPENVIKING_PUBLIC_BASE_URL` instead. |
+| 413 "Upload exceeds configured body limit" | The file is larger than `max_body_bytes` or the proxy's limit. |
+| 502 "OpenViking upload is unavailable" or "OpenViking download is unavailable" | The gateway cannot reach OpenViking Server. |
+| The model has no import tool | The OpenViking service does not provide it, the profile has it unchecked, or this request cannot use gateway tools. Check the tool list and the request details. |
+
+## Issues on degraded requests {#issues-on-degraded-requests}
+
+A degraded request is one the gateway could not fully handle; the Requests and Overview tabs flag it. Studio shows the issue label; the code in parentheses is the matching value in the management API:
+
+| Issue | What happened | What to do |
+| --- | --- | --- |
+| Memory unavailable (`memory_store_failure`) | The gateway could not read or write its storage, or the user's gateway data was just deleted. The request went to the model without memory; in Claude conversations, earlier thinking was removed. | Check disk space, permissions and the gateway log. Expected right after [deleting a user's gateway data](09-gateway-keys.md#delete-a-users-gateway-data). |
+| Forwarded unchanged (`unsafe_json`) | The request had numbers that cannot be re-encoded exactly, or duplicate keys, so the gateway forwarded it byte for byte without memory. | Usually specific to one client; nothing to change in the gateway. |
+| Upstream switched (`upstream_changed`) | The conversation's upstream could no longer serve it, so it moved to another one, with one cache miss and earlier Claude thinking removed. | Turn the upstream back on, or give the client a key that includes it; or accept the switch. |
+| Memory record missing (`missing_injection_record`) | In a Claude conversation, memory added earlier is no longer on record, so earlier thinking was removed once. | Expected after storage loss or in very old conversations. If it keeps happening, start a new conversation. |
+| OpenViking plugin in use (`plugin_present`) | An OpenViking plugin was detected, and this conversation no longer uses gateway memory. | Expected when a plugin is in use. Use either the plugin or the gateway for a given client. |
+| Cache parameters changed (`ark_cache_parameters_changed`) | On Ark or ModelArk, parameters that affect caching differ from the conversation's first request, so the prompt cache probably missed. | Keep the model, thinking mode, sampling parameters, system prompt and tools the same within a conversation. |
+| Tool history unavailable (`hidden_tool_history_unavailable`) | A Claude conversation used OpenViking tools, but this request cannot use them, so earlier thinking was removed. | Check the tool skip reason in the request details, restore the original settings, or start a new conversation. |
+| OpenViking tools failed (`hidden_tool_loop_failed`) | The model could not finish its answer while using OpenViking tools, and the client received an error. | See [Failure handling](04-openviking-tools.md#failure-handling). |
+| No usable model reply (`hidden_reply_without_anchor`) | The model used OpenViking tools during this request but returned no content to continue the conversation from. The client still got the reply, but the next request cannot reuse those tool results. | Retry the question or start a new conversation. |
+| Reply not saved (`capture_parse_failure`) | A streamed reply could not be parsed, so it was not saved. The client was not affected. | Nothing to do; it is for information only. |
+| Key not verified (`revocation_check_unavailable`) | OpenViking could not confirm the gateway key, so the request was served without checking whether the key was revoked. | Check that OpenViking is reachable and healthy. |
+
+## Next steps {#next-steps}
+
+- [Gateway overview and request log](10-overview-and-requests.md#requests): read every column, label and saving state in the request log.
+- [Monitoring](../guides/22-gateway-operations.md#monitoring): check liveness with `/health` and read the gateway's state through the management API before users notice a problem.
+- [Configuration reference](13-configuration.md#gateway-fields): look up `max_body_bytes`, `public_url`, `min_server_version` and the other fields named on this page.
diff --git a/docs/en/gateway/13-configuration.md b/docs/en/gateway/13-configuration.md
new file mode 100644
index 000000000..f8ac395ce
--- /dev/null
+++ b/docs/en/gateway/13-configuration.md
@@ -0,0 +1,183 @@
+---
+description: Look up every OpenViking Gateway configuration field, environment variable, context profile setting and upstream setting.
+---
+
+# OpenViking Gateway configuration reference
+
+This page is for operators editing `ov.conf`, `gateway.conf` or environment variables, and for anyone mapping a Studio label to its management API name. Every table gives the name, default and accepted values; what a setting does and when to change it are on the feature page linked from each section.
+
+## Where the settings live {#configuration-reference}
+
+An embedded and a standalone gateway share most fields; they differ in which file holds them and how you create it. The **Form** column under [Gateway fields](#gateway-fields) marks the fields that only one form uses.
+
+| | Embedded | Standalone |
+| --- | --- | --- |
+| File | The `gateway` section of `ov.conf` | The root of `gateway.conf`, with no `gateway` wrapper |
+| Created by | `openviking-server init` | `openviking-gateway init` |
+| Which file is read | The server's own `ov.conf` | `--config` or `OPENVIKING_GATEWAY_CONFIG_FILE`, which must point to an existing file; otherwise the first of `~/.openviking/gateway.conf` and `/etc/openviking/gateway.conf` that exists |
+| Host, port and workers | Come from the server | The `host`, `port` and `workers` fields |
+
+`OPENVIKING_CONFIG_FILE` only selects the server's configuration; it never points a standalone gateway at a file.
+
+## Gateway fields {#gateway-fields}
+
+| Field | Form | Default | Accepted values | Meaning |
+| --- | --- | --- | --- | --- |
+| `enabled` | Embedded | `false` | | Turns the gateway on inside the server |
+| `openviking_url` | Standalone | — (required) | HTTP(S) URL | Address of the OpenViking Server |
+| `host` | Standalone | `127.0.0.1` | | Listen address |
+| `port` | Standalone | `1935` | 1–65,535 | Listen port |
+| `workers` | Standalone | `1` | 1–64 | Worker processes |
+| `public_url` | Both | empty | HTTP(S) URL, without `/gateway` | The external address clients use; the gateway appends `/gateway` itself. When empty, an embedded gateway uses the server's public address; with neither, setup guides use the request's origin, and MCP file uploads and downloads do not work unless `mcp_file_links` is `direct`. See [Public address](../guides/22-gateway-operations.md#public-address) |
+| `mcp_file_links` | Both | `proxy` | `proxy`, `direct` | How links from the MCP upload and download tools reach the client. `proxy` rewrites them to `public_url` plus `/gateway/uploads` or `/gateway/downloads` and needs `public_url`. `direct` passes OpenViking's links through unchanged and needs the server's `OPENVIKING_PUBLIC_BASE_URL` (or `server.public_base_url`) to be reachable by the client |
+| `storage_path` | Both | `~/.openviking/gateway` | | Local storage directory |
+| `encryption` | Standalone | not set (plain text) | Same fields as the `encryption` section of `ov.conf` | Encrypts stored data; see [Encryption](../guides/22-gateway-operations.md#encryption). Embedded gateways use the server's section |
+| `management_key` | Both | empty | At least 32 characters | Optional [gateway management key](../guides/22-gateway-operations.md#gateway-management-key) |
+| `min_server_version` | Both | `0.4.16` | Version string | Lowest OpenViking Server version a standalone gateway accepts |
+| `session_ttl_days` | Both | `30` | 1 or more | Days of inactivity before a conversation expires |
+| `response_ttl_seconds` | Both | `2592000` (30 days) | 60 or more | Seconds to remember which upstream created a Responses response |
+| `log_retention_days` | Both | `30` | 1 or more | Days to keep request logs |
+| `max_body_bytes` | Both | `33554432` (32 MiB) | 1,024 or more | Size limit for requests and uploads, in bytes |
+| `upstream_timeout_seconds` | Both | `600` | More than 0 | Timeout for provider requests |
+| `health_interval_seconds` | Both | `60` | 1 or more | Seconds between OpenViking status checks |
+
+## Environment variables {#environment-variables}
+
+Every gateway field can be set as an environment variable named `OPENVIKING_GATEWAY_` plus the field name in upper case, in both forms:
+
+```bash
+OPENVIKING_GATEWAY_PUBLIC_URL=https://ov.example.com
+OPENVIKING_GATEWAY_MANAGEMENT_KEY='<management-key>'
+```
+
+- **Environment variables override the file.** A non-empty variable wins over the value in the file; an empty variable counts as unset.
+- Values that start with `tcp://` or `udp://` are ignored, so the variables Kubernetes sets for a Service named `openviking-gateway` (such as `OPENVIKING_GATEWAY_PORT=tcp://…`) do not override the file.
+- A value in the file can also be a `"$VAR"` reference, resolved from the environment.
+- The `encryption` block can only be set in the file.
+- Containers usually need no file: set the fields they need as variables.
+
+## Validation {#validation}
+
+| What | Rule |
+| --- | --- |
+| `openviking_url` and `public_url` | HTTP(S), with no credentials, query or fragment |
+| Upstream `base_url` | Its own rules; see [Endpoint](07-upstreams.md#endpoint) |
+| `management_key` | At least 32 characters once `$VAR` references are resolved; an unresolved `$VAR` fails |
+| Unknown fields | Fail validation |
+| Removed fields | Ignored, with a startup warning: `encryption_key_env`, and in `ov.conf` also the v0.5 fields listed in [Migration](../guides/22-gateway-operations.md#migration) |
+
+## Context profile settings {#context-profile-settings}
+
+In Studio: **Profiles** → a profile. The tables follow the editor's sections, with the Studio label first and then the name in the management API, which calls context profiles `policies`. **Name** (`name`, default `Default`) is the profile's display name; what each section does is explained in [Context profiles](08-context-profiles.md#context-profiles).
+
+### Recall memory {#profile-recall}
+
+Explained in [Recall memory](08-context-profiles.md#recall-memory).
+
+| Studio label | API name | Default | Range | Meaning |
+| --- | --- | --- | --- | --- |
+| Recall memory | `recall` | `true` | | Search memory for each new user message. |
+| User profile at conversation start | `profile` | `true` | | Provide the user profile when a conversation starts, independently of recall. |
+| Opening context budget | `profile_max_tokens` | `4000` | 0–32,000 | Separate budget for the profile and catalogs; 0 leaves them out. Catalogs need the OpenViking `read` tool (`openviking_read`). |
+| Show recall summary | `show_recall` | `false` | | Start the reply with a summary of what OpenViking added, or why recall failed. The model never sees it. |
+| Sources | `context_types` | `memory`, `resource`, `skill` | At least one while recall is on (checked by Studio only) | What to search: memories, resources, skills. |
+| Budget per message | `max_tokens` | `1600` | 64–32,000 | Most tokens added to one message. |
+| Budget per context window | `session_max_tokens` | `30000` | 0 or more | Most tokens added within one context window; resets after each compaction. 0 turns recall off. |
+| Relevance threshold | `score_threshold` | `0.35` | 0–1 | Lowest relevance score accepted. |
+| Time limit | `recall_timeout` | `2` (seconds) | More than 0, up to 30 | How long a search may take before the message goes on without memory. |
+| Query length | `query_max_chars` | `8000` | 3–32,000 | Characters of the message used as the search query. |
+| Limit by category | `quotas` | `{}` (off) | Keys: `events`, `entities`, `preferences`, `experiences`, `resources`, `skills`; when set, at least one above 0 (checked by Studio only) | Most entries per category; only categories above 0 are searched. |
+
+The management API saves `context_types` and `quotas` without checking them. An unknown `quotas` key makes every recall fail, because OpenViking rejects it.
+
+### Save conversations {#profile-saving}
+
+Explained in [Save conversations](08-context-profiles.md#save-conversations).
+
+| Studio label | API name | Default | Range | Meaning |
+| --- | --- | --- | --- | --- |
+| Save conversations | `capture` | `true` | | Save finished turns to OpenViking. |
+| Save the latest reply after | `idle_seconds` | `600` (seconds) | 1 or more | Quiet time before the last turn is saved and the session committed. |
+| Commit after | `commit_tokens` | `20000` | 1 or more | Tokens waiting in the session that trigger a commit. |
+| Keep recent messages | `keep_recent_messages` | `10` | 0–1,000 | Messages left in the session after a commit. |
+
+### Long conversations {#profile-long-conversations}
+
+Explained in [Long conversations in the gateway](05-long-conversations.md#long-conversations).
+
+| Studio label | API name | Default | Range | Meaning |
+| --- | --- | --- | --- | --- |
+| Compaction | `compaction` | `true` | | Replace the earlier part of a conversation with a summary near the context window. |
+| Compact at | `compaction_threshold` | `0.9` | 0.5–0.98 | Share of the context window that triggers compaction. |
+| Summary length | `summary_max_tokens` | `8000` | 1,000–32,000 | Most tokens in one summary. |
+| Default context window | `context_window` | Not set (1,000,000 assumed) | 1,024 or more | Window used when the upstream does not list the model; see [Set the model's context window](05-long-conversations.md#context-window). |
+| Agent-managed context windows | `agent_windows` | `false` | | Experimental. Let the model start new context windows itself; needs OpenViking tools. |
+| Soft reminder at | `window_soft_ratio` | `0.7` | 0.3–0.95, below `window_hard_ratio` | Share of the window at which the model is reminded to start a new window soon. |
+| Hard reminder at | `window_hard_ratio` | `0.85` | 0.4–0.97 | Share of the window at which the model is told to start a new window now. |
+
+### OpenViking tools {#profile-tools}
+
+Explained in [Choose tools](04-openviking-tools.md#choose-tools) and [Limits](04-openviking-tools.md#limits).
+
+| Studio label | API name | Default | Range | Meaning |
+| --- | --- | --- | --- | --- |
+| OpenViking tools | `gateway_tools` | `true` | | Offer OpenViking tools for Chat Completions, full-history Responses and Anthropic Messages. |
+| Tools (unchecked boxes) | `disabled_tools` | The 8 tools that change data | OpenViking tool names, without `openviking_` | Tools new conversations do not get; every other available tool is offered, including ones added later. |
+| Show tool calls | `show_tool_calls` | `true` | | Add a one-line notice to the reply for each OpenViking tool call. |
+| Rounds per request | `tool_max_rounds` | `null` (no limit) | 1 or more | Tool rounds after which further OpenViking calls are refused. |
+| Time limit per call | `tool_timeout_seconds` | `30` (seconds) | More than 0, up to 120 | A slower call returns an error to the model. |
+| Result size | `tool_result_bytes` | `65536` (bytes) | 1,024–1,048,576 | Longer results are cut off before the model sees them. |
+| Total time | `tool_total_seconds` | `null` (no limit) | More than 0 | Seconds after which a request still using tools fails. |
+| Token budget | `tool_total_tokens` | `null` (no limit) | 1,024 or more | Estimated tokens tool calls and results may add to one request before further OpenViking calls are refused. |
+
+API requests that omit `disabled_tools` get the default list; an empty list with `gateway_tools` on offers every available tool.
+
+## Upstream settings {#upstream-settings}
+
+In Studio: **Upstreams** → an upstream. The tables follow the editor's four sections; what each field does is explained in [Upstreams](07-upstreams.md#upstreams).
+
+### Endpoint {#upstream-endpoint}
+
+| Studio label | API name | Default | Accepted values | Meaning |
+| --- | --- | --- | --- | --- |
+| Name | `name` | — (required) | | Display name. |
+| Provider | `vendor` | `generic` | `generic`, `anthropic`, `openai`, `deepseek`, `ark` (Volcano Engine Ark), `byteplus` (BytePlus ModelArk) | Studio offers only the protocols a provider supports; the API accepts any pair. |
+| Protocol | `protocol` | — (required) | `anthropic` (Anthropic Messages), `chat` (Chat Completions), `responses` (Responses) | The API this upstream speaks. |
+| Base URL | `base_url` | — (required) | HTTP(S) URL | Provider address; defaults are in [What an upstream is](07-upstreams.md#upstreams) and path rules in [Endpoint](07-upstreams.md#endpoint). |
+| Append protocol endpoint path | `append_endpoint_path` | `true` | | Appends the selected protocol's path; when false, uses `base_url` as the complete request URL. |
+
+### Credentials {#upstream-credentials}
+
+| Studio label | API name | Default | Accepted values | Meaning |
+| --- | --- | --- | --- | --- |
+| Who provides the API key | `auth_mode` | `managed` | `managed` (the gateway holds the API key), `passthrough` (each client sends its own key) | See [Credentials](07-upstreams.md#credentials). |
+| Send the key as | `key_header` | `authorization` | `authorization` (Bearer), `api-key`, `x-api-key` | Ignored when `base_url` contains `{api_key}`. |
+| API key | `api_key` | empty | | Write-only; see [Credentials](07-upstreams.md#credentials). |
+| Extra headers | `headers` | `{}` | Header name → value | Write-only; see [Credentials](07-upstreams.md#credentials). |
+| This key is a Coding Plan or subscription key | `coding_plan` | `false` | | Rejects requests to this upstream unless allowed. |
+| Allow this plan through the gateway | `allow_coding_plan` | `false` | | Allows use of a key marked as Coding Plan. |
+
+### Models {#upstream-models}
+
+| Studio label | API name | Default | Accepted values | Meaning |
+| --- | --- | --- | --- | --- |
+| Models | `models` | `[]` | Model names | Model names served; empty accepts any name. |
+| Model aliases | `aliases` | `{}` | Name clients use → model sent to the upstream | |
+| Context windows | `context_windows` | `{}` | Model → tokens, each at least 1,024 | Each model's context window; see [Set the model's context window](05-long-conversations.md#context-window). |
+
+### Routing {#upstream-routing}
+
+| Studio label | API name | Default | Accepted values | Meaning |
+| --- | --- | --- | --- | --- |
+| Priority | `priority` | `0` | Integer | Higher values win for new conversations. |
+| Enabled | `enabled` | `true` | | A turned-off upstream receives no requests. |
+| Allow OpenViking tools | `allow_gateway_tools` | `true` | | Whether OpenViking tools can be offered through this upstream. |
+| Restore reasoning the client drops | `replay_reasoning` | `null` (follows the provider) | `null`, `true`, `false` | Puts reasoning the client dropped back on earlier replies. `null` means on for `deepseek`, `ark` and `byteplus` and off for other providers; `true` or `false` overrides that. Studio saves `null` while the switch matches the provider default. |
+| Minimum cacheable prompt | `cache_min_tokens` | `1024` | 0 or more | Ark and ModelArk only; affects how cache eligibility is reported. |
+
+## Next steps {#next-steps}
+
+- [Standalone deployment](../guides/22-gateway-operations.md#standalone-deployment): create `gateway.conf` and run the gateway on its own.
+- [Enable it in the server](../guides/22-gateway-operations.md#enable-it-in-the-server): turn on the embedded gateway in `ov.conf`.
+- [Context profiles](08-context-profiles.md) and [Upstreams](07-upstreams.md): what these settings do, in Studio terms.
+- [Management API](../api/25-gateway.md): gateway key fields, every management operation, the access rules and the error reasons.
diff --git a/docs/en/guides/15-gateway.md b/docs/en/guides/15-gateway.md
index 00d05be63..c27ada462 100644
--- a/docs/en/guides/15-gateway.md
+++ b/docs/en/guides/15-gateway.md
@@ -4,9 +4,7 @@ description: Give any API-key model client OpenViking memory by pointing it at O
# OpenViking Gateway
-OpenViking Gateway is a model API proxy. Any client that lets you change its base URL can use it to get OpenViking memory. You change two settings: the base URL becomes the gateway address, and the provider's API key becomes a gateway key. There is no plugin to install and no code or prompt to change.
-
-For an animated walkthrough of how the gateway works, see [openviking.ai/gateway](https://openviking.ai/gateway).
+OpenViking Gateway is a model API proxy that gives OpenViking memory to any client that lets you change its base URL. You change two settings: the base URL becomes the gateway address, and the provider's API key becomes a gateway key. There is no plugin to install and no code or prompt to change.
While it forwards a request, the gateway does three things:
@@ -16,461 +14,155 @@ While it forwards a request, the gateway does three things:
| Model-driven memory | The model can call OpenViking tools to search, read, write and import material. The gateway runs the tools, so the client does not declare or implement any of them. |
| Saving and compaction | The gateway saves conversations to OpenViking, which extracts new memories from them. When a conversation nears the model's context window, the gateway has the same model write a summary that replaces the earlier part. |
-**Who it is for**: clients that cannot install a plugin or MCP server, such as chat apps, SDK scripts and low-code platforms, and teams that want to manage providers, keys and memory settings in one place. **Not for**: clients signed in directly with a subscription (use a [subscription proxy upstream](#custom-upstreams) instead), and clients such as Cursor and Trae whose model calls leave from the vendor's servers.
-
-The gateway supports three model APIs: Anthropic Messages, OpenAI Chat Completions and OpenAI Responses (when every request carries the full history). It forwards each request to a model endpoint you configure, called an **upstream** in these docs. A request goes out in the same API it came in; the gateway never converts between APIs.
+For an animated walkthrough of how the gateway works, see [openviking.ai/gateway](https://openviking.ai/gateway). To connect a client right away, go to [Connect clients](../gateway/03-connect-clients.md); to find the page for any other task or Studio tab, see [Where to go next](#next-steps).
-OpenViking Gateway is in beta. This page covers how it works and how to connect clients. For deployment, managing it in Studio and troubleshooting, see [OpenViking Gateway deployment and operations](22-gateway-operations.md).
+> **Note**: OpenViking Gateway is in beta. It is a different component from VikingBot Gateway (`vikingbot gateway`), which handles remote access and chat platforms.
-> **Note**: OpenViking Gateway and VikingBot Gateway (`vikingbot gateway`) are different components. VikingBot Gateway handles remote access and chat platforms.
+## Who it is for {#who-it-is-for}
-## Custom upstreams
+- **For**: clients that cannot install a plugin or MCP server, such as chat apps, SDK scripts and low-code platforms, and teams that want to manage providers, keys and memory settings in one place.
+- **Not for**: clients signed in directly with a subscription (use a [subscription proxy upstream](../gateway/07-upstreams.md#custom-upstreams) instead; Codex can use a ChatGPT subscription this way, see [Use a ChatGPT subscription](../gateway/03-connect-clients.md#codex-chatgpt-subscription)), and clients such as Cursor and Trae whose model calls leave from the vendor's servers.
-Any service that speaks one of the three APIs can be an upstream, not only a model provider. Two common uses:
+The gateway supports three model APIs: Anthropic Messages, OpenAI Chat Completions and OpenAI Responses (when every request carries the full history; see [Client requirements](../gateway/04-openviking-tools.md#client-requirements)). It forwards each request to a model endpoint you configure, called an **upstream**. A request goes out in the same API it came in; the gateway never converts between APIs.
-- **Billing, quotas and load balancing.** The gateway does none of these. If you need them, put a service such as LiteLLM or new-api behind the gateway and add it as an upstream.
-- **Subscription quota.** Clients cannot sign in to the gateway with a subscription, but you can add a reverse proxy such as [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) as an upstream. It exposes subscription accounts such as ChatGPT (Codex) and Claude as an API, so Codex, for example, can use a ChatGPT subscription through the gateway. Tibo, who leads Codex at OpenAI, has [publicly walked through](https://x.com/thsottiaux/status/2076119366647894371) connecting a Codex subscription this way. **Check that this complies with your provider's terms.**
+## Key terms {#key-terms}
-To add one, choose *Generic* as the provider; see [Upstreams](22-gateway-operations.md#upstreams).
+Every gateway page uses these terms in exactly this sense. Users in an OpenViking account share its upstreams and context profiles; gateway keys and request logs belong to individual users.
-## Architecture at a glance
+| Term | What it means | Explained in |
+| --- | --- | --- |
+| Upstream | A model endpoint the gateway forwards requests to, with its API key; each upstream speaks exactly one of the three APIs. | [Upstreams](../gateway/07-upstreams.md#upstreams) |
+| Context profile | A named set of memory settings, such as the recall budget, whether conversations are saved and whether OpenViking tools are offered; each gateway key uses one. | [Context profiles](../gateway/08-context-profiles.md#context-profiles) |
+| Gateway key | The key (`ovgw_…`) a client uses in place of the provider API key; it binds one OpenViking user, one context profile and a set of upstreams. | [Gateway keys](../gateway/09-gateway-keys.md#gateway-keys) |
+| OpenViking API key | Your OpenViking user key: it signs you in to Studio and decides which account and user memory is read and written as. | [Keys and credentials](22-gateway-operations.md#keys-and-credentials) |
+| Gateway management key | An optional key (`ovgm_…`); once set, only requests that carry it can change upstreams and context profiles. Who may change what is in the [access matrix](../api/25-gateway.md#credentials-and-account-scope). | [Gateway management key](22-gateway-operations.md#gateway-management-key) |
+| Conversation | The requests the gateway treats as one chat; a conversation keeps the context profile and upstream it started with. Its turns are saved to an OpenViking session, and to a new one in some cases, for example when the client rewrites the history (see [Saving status](../gateway/10-overview-and-requests.md#saving-status)). | [How conversations are recognized](../gateway/03-connect-clients.md#how-conversations-are-recognized) |
+| Recall | Searching OpenViking for memory related to the current message and appending it to that message. | [What the model sees](../gateway/01-how-it-works.md#what-the-model-sees) |
+| Saving | Writing finished turns to an OpenViking session, one turn behind, so a later commit can turn them into memories. | [When conversations are saved](../gateway/01-how-it-works.md#when-conversations-are-saved) |
+| Commit | Telling OpenViking that the saved turns in a session are ready: it archives the older turns, keeping the newest messages in the session, and extracts memories from them in the background. A saved turn becomes memory only after a commit. | [When conversations are saved](../gateway/01-how-it-works.md#when-conversations-are-saved) |
+| Compaction | When a conversation nears the model's context window, the same model writes a summary that replaces everything before the cut. | [Long conversations in the gateway](../gateway/05-long-conversations.md#long-conversations) |
+| Prompt caching | A provider billing feature: the part of a request that matches the start of the previous request is billed at the cached rate, usually a small fraction of the full rate, and everything from the first differing byte on at the full rate. | [Replay and prompt caching](../gateway/01-how-it-works.md#replay) |
+| Local dev mode | An OpenViking server running in dev mode: bound to `127.0.0.1` with no `root_api_key`, so Studio needs no API key and everything runs as the `default` user. | [Local server](../gateway/02-quickstart.md#local-server-no-api-key) |
+| OpenViking tools | The tools your OpenViking server provides (named `openviking_…`), which the gateway offers to the model and runs itself while the model answers. | [OpenViking tools](../gateway/04-openviking-tools.md#agentic-memory-for-any-client) |
+
+## Architecture at a glance {#architecture-at-a-glance}
![OpenViking Gateway in its two forms. Embedded: clients call the OpenViking Server port, which passes everything under /gateway (model APIs, uploads and gateway management) to the gateway in the same process; the gateway searches and saves memory over loopback HTTP with the user's own OpenViking key. Standalone: openviking-gateway on its own port serves the same /gateway paths and a gateway-only Studio, and calls an existing OpenViking service over HTTP(S). Either way the gateway forwards each request to the upstream model provider in the same API, sessions and memories live in OpenViking, and the gateway keeps only two SQLite files (encrypted when OpenViking encryption is on)](../../images/gateway/architecture.en.svg)
-- **Where it runs**: once enabled, inside OpenViking Server on the server's port. You can also run `openviking-gateway` on its own against an existing OpenViking service, open source or OpenViking Cloud. Either way, every gateway URL is under `/gateway`, such as `/gateway/v1`, so clients use the same paths. See [Deployment options](22-gateway-operations.md#deployment-options).
+- **Where it runs**: once enabled, inside OpenViking Server on the server's port. You can also run `openviking-gateway` on its own against an existing OpenViking service, open source or OpenViking Cloud. Either way, every gateway URL is under `/gateway`, such as `/gateway/v1`, so clients use the same paths. See [Choose a deployment form](22-gateway-operations.md#deployment-options).
- **How it relates to OpenViking**: the gateway only calls OpenViking's public APIs. Embedding and memory extraction happen in OpenViking.
-- **Where the data lives**: sessions and memories live in OpenViking. The gateway host keeps only two SQLite files, encrypted when OpenViking encryption is on, one for upstreams, keys and settings and one for conversation state. See [Security and data](22-gateway-operations.md#security-and-data).
+- **Where the data lives**: sessions and memories live in OpenViking. The gateway host keeps only two SQLite files, encrypted when OpenViking encryption is on, one for upstreams, keys and settings and one for conversation state. See [Security and data](../gateway/11-security-and-data.md).
- **When something fails**: if OpenViking is down, conversations go on without memory and saving retries on its own. If the gateway is down, every model call that goes through it fails.
-- **What you manage**: users in an account share its **upstreams** (model endpoints and their API keys) and **context profiles** (memory settings such as the recall budget, whether conversations are saved and whether OpenViking tools are offered). Each gateway key binds one OpenViking user, one context profile and a set of upstreams. Who may change what is in the [access matrix](../api/25-gateway.md#credentials-and-account-scope).
-
-## What happens once you connect
-
-Two terms first. **Recall** means searching OpenViking for memory related to the current message and appending it to that message. **Prompt caching** is a provider billing feature: the part of a request that matches the start of the previous request is billed at the cached rate, and everything from the first differing byte on is billed at the full rate. The cached rate is usually a small fraction of the full rate; see each provider's pricing.
-
-What you get: relevant memory on every new message, your user profile at the start of a new conversation, conversations saved to OpenViking and turned into new memories, and automatic compaction of long conversations. With OpenViking tools on, the model can also search, read and write memory itself (see the [next section](#agentic-memory-for-any-client)).
-
-What it costs: the first model call of each new message can wait up to 2 extra seconds; added memory is billed as input tokens, mostly at the cached rate on later requests; and the turn that triggers compaction makes one extra model call.
-
-![What happens in one turn: the gateway recognizes the conversation and the request type, puts earlier memory back exactly as it was, recalls only for the new message, forwards the request to the upstream in the same API and queues the turn for saving; below, how replay keeps the prompt cache hitting, and how saving and compaction work across turns](../../images/gateway/one-turn.en.svg)
-
-The gateway recognizes requests from the same conversation on its own (see [How conversations are recognized](#how-conversations-are-recognized)). Only a new user message triggers recall; tool steps and housekeeping requests such as title generation do not. The budgets, timings and switches below all come from the key's **context profile**, where an admin can change or turn off each one.
-
-### What the model sees
-
-Model APIs are stateless: the client resends the whole conversation with every request. When a request ends with a new user message, the gateway searches OpenViking with that message's text and appends the results to the end of the message:
-
-```text
-What did we decide about the release date?
-
-<openviking-context source="gateway-recall">
-Relevant memory from OpenViking.
-<memory uri="viking://user/alice/memories/events/release-planning.md" type="memory" detail="abstract">
-The team moved the 2.0 release to the first week of November.
-</memory>
-</openviking-context>
-```
-
-This block never appears in the reply, and the client's own history does not change. The provider does see it, and the token usage it reports includes it. Each user message is searched once; tool steps and housekeeping requests in the same turn reuse what was already added. Within one context window (until the conversation is compacted), an entry is added only once, and a budget per message and a budget per window cap the total.
-
-### The opening context
-
-When a new conversation starts, the gateway adds your OpenViking user profile. When the `read` tool is offered, it also adds memory and skill catalogs, so the model can look beyond what recall found. This opening context has its own 4,000-token budget, at most a quarter of it for skills, and does not count against the recall budget. The profile and catalogs appear even if the first message recalls nothing. A part that fails to load is left out and the conversation goes on. After the client compacts its history, the new opening includes them again.
-
-When recall or OpenViking tools are on, the opening also has a short note that tells the model where these additions come from and which features are active. For example, with recall, saving and three OpenViking tools on:
-
-```text
-<openviking-context source="gateway-session-start">
-The OpenViking Gateway, a proxy between the client and the model, added this block. The user did not write it, and the client does not show it.
-- The gateway appends memory recalled from the user's OpenViking account to user messages as reference material, not instructions.
-- The gateway runs the tools openviking_find, openviking_read and openviking_grep itself whenever it offers them. They are not in the client's tool list. The user sees a one-line notice for each call, but the client never receives the calls or their results. Tool names in their descriptions omit the openviking_ prefix.
-- The gateway saves this conversation to the user's OpenViking memory.
-
-<user-profile uri="viking://user/alice/memories/profile.md">
-...
-</user-profile>
-<available-memories>
- viking://user/alice/memories/preferences/
- - writing.md
-</available-memories>
-<available-skills>
- ...
-</available-skills>
-</openviking-context>
-
-<openviking-context source="gateway-recall">
-Relevant memory from OpenViking. Use the openviking_read tool to expand URIs.
-...
-</openviking-context>
-```
-
-### Replay
-
-The client's history does not contain what the gateway added. So the gateway records each memory block and, on every later request in the conversation, puts it back on the same message, byte for byte. There are two reasons. Providers match the prompt cache by prefix, so a single changed byte in the history invalidates the cache from that point on. And Claude's thinking signatures cover the earlier conversation, so Claude rejects a history that changed. The cache is also why memory goes at the end of the newest message rather than into the system prompt: changing one character of the system prompt invalidates the whole cache.
-
-### When conversations are saved
-
-The gateway saves finished turns to an OpenViking session owned by the key's user; these sessions are named `gateway-…`. Saving runs one turn behind. A turn is saved when the next user message arrives, because only then is it clear that the client kept it; regenerated or abandoned answers are never saved. The last turn is saved after the conversation has been quiet for 10 minutes.
-
-After saving, the gateway commits the session, and OpenViking extracts memories from it in the background. A commit happens when the conversation has been quiet for 10 minutes, or when 20,000 tokens are waiting to be committed. Before saving, the gateway strips what it added and client noise such as `<system-reminder>` blocks. Sub-agent, housekeeping and token-count requests are never saved.
-### Long conversations
+## What you get and what it costs {#what-you-get-and-what-it-costs}
-When a conversation reaches 90% of the model's context window, the gateway compacts it: the same model writes a summary of the conversation so far, with a length cap, and from then on the summary replaces everything before the cut. The history shown in the client does not change. When saving is on and the model has the OpenViking `grep` and `read` tools, the summary ends with directions for finding details in the saved conversation. Each compaction costs one extra model request and one provider cache miss.
+What you get:
-The gateway needs to know the model's context window. If neither the upstream nor the context profile sets it, the gateway assumes 1,000,000 tokens. For a model with a smaller window, ask an admin to set the real one; otherwise the provider rejects long conversations as too long before compaction starts. Details are in [Long conversations](22-gateway-operations.md#long-conversations).
+- relevant memory on every new message;
+- your user profile at the start of a new conversation;
+- conversations saved to OpenViking and turned into new memories;
+- automatic compaction of long conversations;
+- with OpenViking tools on, a model that searches, reads and writes memory itself (see [Agentic memory for any client](../gateway/04-openviking-tools.md#agentic-memory-for-any-client)).
-## Agentic memory for any client
+What it costs:
-With automatic recall, the gateway guesses what the model needs. With OpenViking tools on, the model decides for itself what to search, read and remember. The gateway runs the tools, so this works even when the client's request has no tools at all.
+- the first model call of each new message can wait up to 2 extra seconds;
+- added memory is billed as input tokens, mostly at the cached rate on later requests;
+- the turn that triggers compaction makes one extra model call.
-![One reply with OpenViking tools: the gateway adds recalled memory and the OpenViking tool definitions to the client's request; when the model calls an OpenViking tool, the gateway runs it with the user's OpenViking key, feeds the result back and asks the model again until it gives a final answer; the client receives one continuous reply with notice lines, and the tool rounds are replayed unchanged in the next turn](../../images/gateway/tool-loop.en.svg)
+For how each of these works, turn by turn, see [How OpenViking Gateway works](../gateway/01-how-it-works.md).
-- **Several steps in one reply**: the gateway intercepts the model's OpenViking tool calls, runs them with the user's OpenViking key, feeds the results back and asks the model again, until the model stops calling them. The client receives one continuous reply, streaming or not.
-- **The client's own tools still work**: in the same reply, the model can call both OpenViking tools and client tools such as Bash. Client tool calls go to the client unchanged and pass through its permission prompts as usual.
-- **The next turn remembers**: tool calls and results are not in the client's history, so the gateway stores these rounds and replays them unchanged on the next turn. The model remembers what it found, and the prompt cache keeps working.
+## Gateway or plugin? {#gateway-or-plugin}
-### What each kind of client gets
+OpenViking also connects to agents through plugins, such as those for Claude Code, Codex, Cursor, TRAE, OpenCode, pi, DSH, OpenClaw and Hermes (see [Choose an integration](../agent-integrations/01-overview.md)). Both read and write the same OpenViking memory. What separates them is where they run: the gateway sits on the model call path and changes the request the model receives, while a plugin runs inside one agent and works through that agent's events. Neither is better in general; most differences below follow from that one fact, and some vary from plugin to plugin.
-| Client | Without the gateway | Through the gateway, with OpenViking tools on |
-| --- | --- | --- |
-| Chat apps, such as Cherry Studio and Open WebUI | To use memory you set up MCP or write tools yourself; a plain chat only exchanges text. | The model searches memory and reads the original text by URI. With `remember` checked, it notes down what the user asks it to remember; with `add_resource` checked, it imports files the user attaches. This works even in a plain chat mode with no tools. |
-| SDK scripts and low-code platforms | One question, one answer; multi-step work needs a loop you write. | One request covers "search → read → grep for exact matches → answer", with no code changes. |
-| Coding agents such as Claude Code and Codex (without the OpenViking plugin or MCP server) | Their own tools, but no OpenViking. | OpenViking tools and client tools such as Bash mix in the same reply. If you want to approve each tool call, the plugin or MCP server is still the better choice. |
-
-### Which tools the model can use
-
-The tool list comes straight from the MCP tools your OpenViking server provides, each with an `openviking_` prefix. Tools that OpenViking adds later become available on their own. The common groups:
-
-| Purpose | Tools | What the model uses them for |
-| --- | --- | --- |
-| Search | `find`, `search`, `grep`, `glob` | Semantic search over memory and resources; exact lookups by regular expression or file name. |
-| Browse and read | `list`, `tree`, `read` | Expanding a recalled entry to its original text by URI; browsing memory and skill directories. |
-| Write | `remember`, `write`, `edit` | Storing a long-term memory; writing or editing memory files. |
-| Import | `add_resource`, `add_skill` | Importing a web page or repository by URL, importing a chat attachment, creating a skill from text, all without a shell on the client. |
-| Delete and permissions | `forget`, `set_acl` and others | Deleting memory permanently; changing access to shared resources. |
-
-### Defaults
-
-New context profiles have OpenViking tools on, but only the read-only tools for searching, browsing and reading are selected. Tools that change data, such as `remember`, `add_resource` and `forget`, stay off until an admin checks them. Rounds, total time and the token budget are unlimited by default, so the model keeps using tools until it is done.
-
-The client must send the full history every turn; with Responses it must also set `store: false`. The gateway does not offer its tools when the client forces a specific tool, asks for structured output, or already has OpenViking tools of its own. For the full default tool list, the limits, file imports and every reason tools are left out, see [OpenViking tools](22-gateway-operations.md#openviking-tools).
-
-### What users see
-
-The model's text streams as usual. Each OpenViking tool call leaves a one-line notice in the reply. It appears when the call starts, and `done`, `failed` or `skipped` is added when the call ends:
-
-```text
-> OpenViking find: "the release date we agreed on" — done
-> OpenViking read: viking://user/alice/memories/release.md — done
-```
-
-A notice shows only the tool name and what it works on, such as the query or URI. Users never see the full arguments or the results. The model does not see the notices, and the gateway does not save them to OpenViking; an admin can turn them off in the context profile. The token usage the client receives is the sum of every model call in the reply.
-
-### Risks and controls
-
-> **Note**: Selected tools run without the client's permission prompts, including tools that write or delete data. A notice reports what already happened; it does not ask for approval. The model can never do more than the user's own OpenViking permissions allow.
-
-- **What admins control**: the tools switch and the per-tool checkboxes in the context profile, the **Allow OpenViking tools** switch on each upstream, and the limits on tool rounds, total time and tokens. For profiles used by chat apps, uncheck at least `forget` and `set_acl`.
-- **Gateway tools or a plugin/MCP server**: plugins and MCP servers show each call and its result in the client and ask for approval first, which makes them more transparent for Claude Code and Codex. Gateway tools are mainly for clients that cannot use a plugin or MCP server.
-
-**Experimental**: a context profile can also let the model manage its own context window. The model gets two more tools, one that reports how full the window is and one that starts a fresh window after it writes hand-off notes, and the gateway reminds it as the window fills up. This is off by default; see [Experimental: agent-managed context windows](22-gateway-operations.md#experimental-agent-managed-context-windows).
-
-## Gateway or plugin?
-
-OpenViking also connects to Claude Code, Codex, OpenCode, pi, OpenClaw, Hermes and other agents through plugins (see [Agent Integrations](../agent-integrations/01-overview.md)). The two approaches complement each other, and their differences all follow from where each one runs:
+### Side by side {#gateway-and-plugin-compared}
| | OpenViking Gateway | Agent plugin |
| --- | --- | --- |
-| Where it runs | Between the client and the model provider. It sees only the requests sent to the model. | Inside the agent. It sees the agent's sessions, events and local workspace. |
-| Clients it covers | Anything that lets you set a base URL and API key: chat apps, SDK and API apps, low-code platforms, coding agents. | Agents that have an OpenViking plugin. |
-| Clients it cannot cover | Clients signed in directly with a subscription (a Claude login in Claude Code, a ChatGPT login in Codex; use a [subscription proxy upstream](#custom-upstreams) instead) and clients whose model calls leave from the vendor's servers, such as Cursor and Trae. | Clients without an extension API. |
-| Per-project memory | It cannot see the working directory or repository. Memory belongs to an OpenViking user, so to keep projects apart, give each project a gateway key bound to a different OpenViking user. | Detects the workspace and repository automatically. |
-| Visibility | Added memory is invisible in the client. OpenViking tool calls show a one-line notice in the reply by default, without results. Studio's request log records recall counts and tool rounds, not content. Tool calls skip the client's permission prompts. | Tool calls appear in the transcript and go through the agent's permission prompts. |
-| When conversations are saved | One turn behind: a turn is saved when the next message arrives, the last turn after a quiet period. | On the agent's own events, such as the end of each turn. |
-| Setup and upgrades | One service for everyone, nothing to install on each machine. Upstreams, keys and memory settings are managed in one place. | Installed and upgraded on each machine. |
-| Keys, data and failures | Holds provider API keys and unsaved conversation text centrally (encrypted when OpenViking encryption is on), and adds one hop to every model call. If the gateway is down, model calls through it fail. | Provider keys stay with each agent, and only saved conversations reach OpenViking. No extra service to run. |
-
-Keep the plugin for Claude Code, Codex and pi when you need per-project memory or want to see and approve every tool call. Use the gateway for clients without a plugin, and when you want to manage providers, keys and memory settings centrally.
-
-**When both are in use, the gateway steps aside.** If a request shows signs of an OpenViking plugin, the gateway stops adding memory, saving turns and offering OpenViking tools for that conversation, and only forwards it. That keeps the same content from being added or saved twice. It looks for two signs:
-
-- memory blocks that plugins insert: `<openviking-context>`, `<relevant-memories>`, `<relevant-memory>` or `<memory-context>`;
-- an `X-OpenViking-Plugin` request header, which plugin and app authors can send to opt out explicitly.
-
-The decision holds for the rest of that conversation and does not affect others. To use gateway memory again, start a new conversation without the plugin. Studio's request log flags these requests **OpenViking plugin in use**.
-
-OpenViking MCP tools alone, without a plugin, do not count. The gateway still adds memory and saves turns; it only stops offering its own OpenViking tools, so the model does not see two sets with the same names (the request log shows `tool_name_collision`).
-
-## Quick start
+| Where it runs | One shared service between clients and the model provider. It sees only model requests. | Inside each agent, through its hooks or extension API. It sees the agent's sessions, events and workspace. |
+| Clients | Any client whose base URL and API key you can set, in Anthropic Messages, Chat Completions or Responses: chat apps, SDK scripts, low-code platforms and coding agents. Not Cursor or TRAE, whose model calls leave from the vendor's servers. | Only agents that have an OpenViking plugin. Other MCP clients can add the OpenViking tools, without automatic recall or saving. |
+| Model sign-in | Needs a provider API key, held by the gateway or [sent by each client](../gateway/03-connect-clients.md#bring-your-own-provider-key). Clients cannot sign in with a subscription; use a [subscription proxy upstream](../gateway/07-upstreams.md#custom-upstreams) instead. Codex can use a ChatGPT subscription through [CLIProxyAPI](../gateway/03-connect-clients.md#codex-chatgpt-subscription); for other subscription services, check their terms yourself. | Does not touch model calls, so the agent keeps its own sign-in, subscriptions included. |
+| Recall | For each new user message, appended to that message; the search waits at most 2 seconds by default. Searches memories, resources and skills by default. | On the agent's prompt event. Most plugins send the session ID so the server can expand the query from the conversation, and leave resources out of automatic recall. |
+| Saving | Finished turns, with the client's own tool calls and results, one turn behind. Sub-agent and housekeeping requests are not saved. | On the agent's events, usually at the end of each turn. Sub-agents differ: Claude Code, OpenCode and DSH save them as separate sessions, Codex folds them into the main session, Hermes skips them. |
+| OpenViking tools | The gateway runs them during the reply, so clients without tool or MCP support get them too. Read-only tools by default. Calls [skip the client's permission prompts](../gateway/04-openviking-tools.md#risks-and-controls) and show a one-line notice. | The agent runs them as its own tools, so calls and results appear in the transcript and follow the agent's tool permissions. |
+| Prompt caching | Puts each memory block back byte for byte on later requests, so the cached prefix holds. The **Overview** tab shows the cache hit rate. | Depends on the plugin. Hook-based plugins hand the block to the agent, which keeps it in its history; pi and OpenCode v2 also keep earlier recall stable; OpenClaw rebuilds recall in the system prompt every turn. |
+| Long conversations | Compacts near the model's context window for any client, including apps that never compact. The [experimental agent-managed context windows](../gateway/05-long-conversations.md#experimental-agent-managed-context-windows) let the model start fresh windows itself. | The agent compacts; most plugins commit what they captured first. pi and OpenClaw can replace the agent's summary with OpenViking's. |
+| Per-project memory | Cannot see the working directory. To keep projects apart, give each one a gateway key bound to a different OpenViking user. | Plugins built on the shared plugin code tag memories with the current repository automatically. |
+| Visibility | Added memory is invisible unless the profile turns on the [recall summary](../gateway/08-context-profiles.md#recall-summary). Studio's request log shows counts and saving status, not content. | Claude Code's status line and `/openviking-memory:ov` command show recall counts and where added context came from; pi's status line shows the connection. Other plugins have no indicator of their own. |
+| Setup and operation | One service, embedded in OpenViking Server or standalone. Users change only a base URL and a key; upstreams, profiles and keys are managed in Studio. | Installed and upgraded on each machine, each with its own OpenViking credentials. |
+| Teams | An admin issues one gateway key per person and can revoke each one. Users never see the provider key when the gateway holds it. | Each person installs the plugin with their own OpenViking API key. Behavior settings can be shared per repository in `.openviking/config.json`. |
+| When something fails | Without OpenViking, requests go on without memory and saving retries. If the gateway is down (for the embedded form, the OpenViking Server), every model call through it fails. It holds provider keys and unsaved text centrally, and adds one network hop to every model call. | Without OpenViking, the agent goes on without memory after the plugin's recall timeout (15 seconds for most, 4 for Hermes); most plugins queue failed writes on disk. Model calls never depend on OpenViking. |
-Start with a working OpenViking installation whose `ov.conf` has embedding and VLM models set up (see [Quick Start](../getting-started/02-quickstart.md)). The gateway is part of the core package; there is nothing extra to install. Pick the path that matches your server. To run the gateway against an existing OpenViking service without changing its configuration, see [Standalone deployment](22-gateway-operations.md#standalone-deployment).
+The [capability reference](../agent-integrations/16-capability-reference.md) has the per-plugin details; [How OpenViking Gateway works](../gateway/01-how-it-works.md) has the gateway's.
-### Local server (no API key)
+### Which to choose {#which-to-choose}
-For a server bound to `127.0.0.1` with the default local authentication.
+Choose the gateway when:
-1. **Turn the gateway on.** Run `openviking-server init` and answer yes to **Enable OpenViking Gateway on the same port?**. With an existing configuration, choose **Update gateway** from the menu. You can also merge `{"gateway": {"enabled": true}}` into `ov.conf`.
-2. **Start or restart** `openviking-server`.
-3. **Open the gateway in Studio.** Open <http://127.0.0.1:1933/studio/> and choose **OpenViking Gateway** in the sidebar. No key is needed. If the default account has no upstreams yet, the gateway imports the server's VLM settings as upstreams at startup and creates a context profile, so the first two steps of the **Get started** checklist on the Overview tab are already done. An imported Coding Plan upstream needs your confirmation before use; see [Import OpenViking model settings](22-gateway-operations.md#import-openviking-model-settings). If nothing could be imported, add an upstream as described in [Upstreams](22-gateway-operations.md#upstreams).
-4. **Issue a gateway key.** On the Overview tab, choose **Get a key** in the **Quick mode** card, or issue one by hand: on the Keys tab, choose **Issue key**, enter a name, pick the context profile and an upstream, and issue it. The key reads and writes memory as the local `default` user. The **Copy your gateway key** dialog shows the full `ovgw_…` key only once, so copy it before you close the dialog.
+- the client has no OpenViking plugin: chat apps, SDK scripts, low-code platforms, or your own app that calls a model API;
+- several people or clients should share one setup, with providers, memory settings and per-person keys managed in Studio and nothing installed on users' machines;
+- the client lacks memory tools or compaction of its own, since the gateway adds both;
+- your clients already use provider API keys, or you route model traffic through a central proxy anyway.
-Then [send a test request](#send-a-test-request) to `http://127.0.0.1:1933/gateway`.
+Choose a plugin when:
-### Remote server (API keys)
+- you sign in to Claude Code with a Claude subscription;
+- you use Cursor or TRAE, which only a plugin can reach;
+- you want each repository's memory tagged without setup, or every OpenViking tool call shown and approved in the agent;
+- you want saving to follow the agent's events, such as sub-agent sessions, a save before the agent compacts and a commit at exit;
+- you do not want another service on the model call path.
-For a server that people reach over the network, with `api_key` authentication.
+Codex with a ChatGPT subscription works either way: with its plugin, or through the gateway with a [CLIProxyAPI upstream](../gateway/03-connect-clients.md#codex-chatgpt-subscription).
-1. **Turn the gateway on.** On the server host, run `openviking-server init`, choose **Remote (0.0.0.0)** for the bind address, and answer yes to **Enable OpenViking Gateway on the same port?**. The next question, **Allow users to configure their own gateway upstreams?**, decides who may change upstreams and context profiles:
- - Yes: every signed-in user can configure their account's upstreams and context profiles.
- - No: init generates a gateway management key starting with `ovgm_`, prints it and saves it to `gateway.management_key` in `ov.conf`. Only requests that carry this key can change upstreams and context profiles; see [Gateway management key](22-gateway-operations.md#gateway-management-key).
+You can mix them: give your coding agents their plugins and send everything else through the gateway. For one client with both, see the next section.
- Then restart the server. Alternatively, sign in to Studio with the root key and choose **Enable gateway** on the OpenViking Gateway page: Studio writes `ov.conf` and restarts the server (single-worker server only).
-2. **Get an OpenViking API key.** Use your own user API key, or use the root key to create an account and user as described in [Authentication](04-authentication.md).
-3. **Sign in to Studio.** Open `https://ov.example.com/studio/`, enter your API key under **Connection Settings**, and choose **OpenViking Gateway** in the sidebar.
-4. **Add an upstream.** On the Upstreams tab, choose **Add upstream**, pick the provider and the protocol your client uses (the test request below uses Chat Completions), paste the provider's API key and save. Choose **Test** in the upstream list to check that the gateway reaches the provider. If the tab is read-only, the deployer set a gateway management key; see [Manage the gateway in Studio](22-gateway-operations.md#manage-the-gateway-in-studio).
-5. **Create a context profile.** On the Profiles tab, choose **Create with recommended settings**.
-6. **Issue a gateway key** for yourself, as in step 4 of the local path. To issue keys for other users, see [Gateway keys](22-gateway-operations.md#gateway-keys).
+> **Try new features early**: the gateway controls the whole model request, which allows features that a plugin cannot add through an agent's extension API. [Agent-managed context windows](../gateway/05-long-conversations.md#experimental-agent-managed-context-windows), where the model decides when to start a fresh context window, is the first of these, and more are planned for the gateway. If you want to try them early, connect a client through the gateway.
-### Send a test request
+### When both are in use {#when-both-are-in-use}
-For a local server, use `http://127.0.0.1:1933/gateway` as the address. Replace `<model>` with a model the upstream serves:
+When a request shows signs of an OpenViking plugin, the gateway steps aside: for that [conversation](#key-terms) it stops adding memory, saving turns and offering OpenViking tools, and only forwards requests. That keeps the same content from being added or saved twice. It looks for two signs:
-```bash
-export GATEWAY_URL=https://ov.example.com/gateway
-export GATEWAY_KEY='ovgw_...'
-
-curl -s "$GATEWAY_URL/v1/models" -H "Authorization: Bearer $GATEWAY_KEY"
-
-curl -s "$GATEWAY_URL/v1/chat/completions" \
- -H "Authorization: Bearer $GATEWAY_KEY" \
- -H "Content-Type: application/json" \
- -H "X-OpenViking-Session: quickstart-1" \
- -d '{"model": "<model>", "messages": [{"role": "user", "content": "Remember that I prefer short answers."}]}'
-```
-
-The first command lists the models and aliases configured on the upstream; the list is empty if the upstream accepts any model name. The second should return a normal reply from your provider.
-
-### Confirm that memory works
-
-1. **The request went through the gateway.** Open the Requests tab. Your request shows as a **New message** with status 200. Once OpenViking has something relevant, the **Memory** column shows how many entries were added (for example `+3`); on a brand-new account it stays empty.
-2. **The conversation is saved.** Send a second message with the same `X-OpenViking-Session` value; the first turn is saved right away. Connect Studio as the key's user, and a `gateway-…` session appears on the **Sessions** page.
-3. **Memories are extracted.** After 10 quiet minutes the gateway commits the session, and OpenViking extracts memories in the background, which takes a moment. Then start a new conversation with another session value and ask something that depends on the memory, such as "How long should your answers be?". The **Memory** column should show recalled entries, and the reply should use them.
-
-To see results sooner while you try things out, create a second context profile with a shorter **Save the latest reply after** time, issue a key with it, and start a new conversation with that key. Profile changes only reach conversations that start afterwards.
-
-## Connect clients
-
-Every client needs the gateway address and a gateway key. The gateway address is the server's address followed by `/gateway`. The examples use `https://ov.example.com/gateway`; replace it with your gateway address, which Studio shows at the top of the OpenViking Gateway page and on the Connect tab. Anthropic clients use the gateway address as it is, OpenAI-compatible clients add `/v1`, and Ark SDKs add `/api/v3`. The client's key must also be bound to an enabled upstream that speaks the client's protocol and serves the model it requests.
-
-| Client | Upstream protocol | Base URL | How its conversations are recognized |
-| --- | --- | --- | --- |
-| [Claude Code](#claude-code) | Anthropic Messages | `https://ov.example.com/gateway` | Claude Code's session header |
-| [Codex CLI](#codex-cli) | Responses | `https://ov.example.com/gateway/v1` | Codex's session header |
-| [Chat clients and SDKs](#chat-clients-and-sdks) | Chat Completions (or the API your SDK uses) | `https://ov.example.com/gateway/v1` | `X-OpenViking-Session`, which you send yourself |
-| [Open WebUI](#open-webui) | Chat Completions | `https://ov.example.com/gateway/v1` | An `X-OpenViking-Session` header set on the connection |
-| [OpenCode](#opencode) | Chat Completions | `https://ov.example.com/gateway/v1` | OpenCode's session header |
-| [pi](#pi) | Chat Completions | `https://ov.example.com/gateway/v1` | Usually matched from the conversation history |
-| [Volcano Engine Ark and BytePlus ModelArk SDKs](#volcano-engine-ark-and-byteplus-modelark-sdks) | Any of the three | `https://ov.example.com/gateway/api/v3` or `https://ov.example.com/gateway/api/compatible` | Depends on the headers the client sends |
-
-The Open WebUI, OpenCode and pi setups follow each client's documented provider settings. Treat them as a starting point and check the result: send two messages in one conversation, then expand both requests on the Requests tab. They should belong to the same conversation, and the first turn should be saved once the second message arrives.
-
-### Claude Code
-
-Claude Code uses Anthropic Messages. Set three environment variables before you start it:
-
-```bash
-export ANTHROPIC_BASE_URL=https://ov.example.com/gateway
-export ANTHROPIC_AUTH_TOKEN='<gateway-key>'
-export CLAUDE_CODE_GATEWAY_HINT_HEADERS=1
-```
-
-- Leave `/v1` off the address; Claude Code adds the path itself.
-- `CLAUDE_CODE_GATEWAY_HINT_HEADERS=1` makes Claude Code label sub-agent, compaction and background requests, so the gateway does not recall memory for them or save them as conversation turns.
-- Claude Code sends its own session ID, which the gateway uses to recognize the conversation, including after `--resume`.
-- The upstream must accept the model names Claude Code requests: leave its model list empty, list those names, or map them to the provider's model with model aliases.
-- A Claude subscription login does not work through the gateway; requests with a subscription token are rejected. Configure the upstream with a provider API key.
-- If the OpenViking plugin is also installed, the gateway steps aside for those conversations (see [Gateway or plugin?](#gateway-or-plugin)). With only the OpenViking MCP server, the gateway still adds memory and leaves the OpenViking tools to the MCP server.
-
-### Codex CLI
-
-Codex uses the Responses API and sends the full history with every request, which is what the gateway needs. Add a provider to `~/.codex/config.toml`. The two top-level settings must come before any `[section]`:
-
-```toml
-model_provider = "openviking"
-model = "<model>"
-
-[model_providers.openviking]
-name = "OpenViking Gateway"
-base_url = "https://ov.example.com/gateway/v1"
-wire_api = "responses"
-env_key = "OPENVIKING_GATEWAY_KEY"
-```
-
-Then set the gateway key in the environment Codex runs in:
-
-```bash
-export OPENVIKING_GATEWAY_KEY='<gateway-key>'
-```
-
-- The upstream bound to the key must use Responses and serve `<model>`.
-- Codex first tries a WebSocket connection. The gateway declines it, and Codex falls back to HTTP.
-- Codex sends its own session ID, which the gateway uses to recognize the conversation, including after `codex resume`.
-- Codex may warn that it has no metadata for an unfamiliar model name. The warning does not affect requests.
-- A ChatGPT login does not work through the gateway. Configure the upstream with a provider API key.
-
-### Chat clients and SDKs
-
-Any client or SDK that supports the OpenAI Chat Completions API can connect. Enter these settings wherever the client asks for an OpenAI-compatible provider:
-
-```text
-Base URL: https://ov.example.com/gateway/v1
-API key: <gateway-key>
-Model: <model>
-X-OpenViking-Session: <conversation-id>
-```
-
-The `X-OpenViking-Session` header is optional but recommended. It tells the gateway which conversation a request belongs to. Use a value that stays the same within a conversation and differs between conversations, such as your app's chat ID. Without it, the gateway matches conversations by their history; see [How conversations are recognized](#how-conversations-are-recognized).
-
-With the OpenAI Python SDK:
-
-```python
-from openai import OpenAI
-
-client = OpenAI(base_url="https://ov.example.com/gateway/v1", api_key="<gateway-key>")
-
-reply = client.chat.completions.create(
- model="<model>",
- messages=[{"role": "user", "content": "What did we decide about the release date?"}],
- extra_headers={"X-OpenViking-Session": "chat-42"},
-)
-print(reply.choices[0].message.content)
-```
-
-SDKs for the other two APIs work the same way, as long as the upstream uses the same API as the SDK:
-
-- Point the Anthropic SDK at `https://ov.example.com/gateway`.
-- For the Responses API, use `https://ov.example.com/gateway/v1`, send the full history in every request and set `store: false`. Other Responses requests are forwarded without memory.
-
-When you stream Chat Completions, also ask for usage (`"stream_options": {"include_usage": true}`). Otherwise the provider reports no token counts for streamed replies, Studio cannot show usage, and the gateway has to estimate how full the context window is.
-
-### Open WebUI
-
-In Open WebUI, add an OpenAI-compatible connection (Admin Panel → Settings → Connections) with the base URL `https://ov.example.com/gateway/v1` and the gateway key. Add these custom headers to the connection, so that each chat is its own conversation and the gateway recognizes Open WebUI's background tasks:
-
-```json
-{
- "X-OpenViking-Session": "{{CHAT_ID}}",
- "X-OpenViking-Task": "{{TASK}}"
-}
-```
-
-Also set `RAG_SYSTEM_CONTEXT=true` in Open WebUI's environment. Open WebUI then puts content retrieved from attachments into the system message instead of rewriting your message for one turn, which keeps the conversation history stable between requests.
-
-- **One connection key means one memory owner.** Every Open WebUI user who chats through this connection reads and writes the memory of the OpenViking user behind the key. Give the connection to one person, or accept that its users share memory.
-- Open WebUI also sends background requests (titles, tags, follow-up suggestions) through the same connection. The gateway recognizes title and summary requests. If the request log shows other background tasks as **New message**, point Open WebUI's task model at a connection that does not go through the gateway.
-
-### OpenCode
-
-Add a provider to `~/.config/opencode/opencode.json`, merged with your existing settings:
-
-```json
-{
- "provider": {
- "openviking": {
- "npm": "@ai-sdk/openai-compatible",
- "name": "OpenViking",
- "options": {
- "baseURL": "https://ov.example.com/gateway/v1",
- "apiKey": "{env:OPENVIKING_GATEWAY_KEY}"
- },
- "models": {
- "<model>": {}
- }
- }
- }
-}
-```
+- memory blocks that plugins insert: `<openviking-context>` (the plugins built on the shared plugin code, such as Claude Code, Codex, OpenCode, pi and DSH), `<relevant-memories>` (OpenClaw), `<memory-context>` (Hermes) or `<relevant-memory>`;
+- an `X-OpenViking-Plugin` request header, which plugin and app authors can send to opt out explicitly.
-Export the gateway key as `OPENVIKING_GATEWAY_KEY`, then select `openviking/<model>` in OpenCode. The upstream must use Chat Completions. If the OpenViking plugin for OpenCode is also installed, the gateway steps aside for those conversations.
+The decision holds for the rest of that conversation and does not affect others. To use gateway memory again, start a new conversation without the plugin. Studio's request log flags these requests **OpenViking plugin in use**. In effect the plugin handles memory and the gateway only forwards, while the client still needs a gateway key and an upstream with a provider API key.
-### pi
+OpenViking MCP tools alone, without a plugin, do not count. The gateway still adds memory and saves turns; it only stops offering its own OpenViking tools, so the model does not see two sets with the same names. In the request details on the **Requests** tab, **OpenViking tools** then reads **Not offered: The client already has OpenViking tools**; see [When tools are not offered](../gateway/04-openviking-tools.md#when-tools-are-not-offered).
-Add a provider to pi's model configuration, `~/.pi/agent/models.json`:
-
-```json
-{
- "providers": {
- "openviking": {
- "baseUrl": "https://ov.example.com/gateway/v1",
- "apiKey": "$OPENVIKING_GATEWAY_KEY",
- "api": "openai-completions",
- "models": [
- {
- "id": "<model>"
- }
- ]
- }
- }
-}
-```
+## Where to go next {#next-steps}
-- `apiKey` reads the gateway key from the `OPENVIKING_GATEWAY_KEY` environment variable; export it before you start pi. Keep the leading `$`, or pi sends the string itself as the key.
-- The upstream must use Chat Completions.
-- pi usually sends no session header, so the gateway matches its conversations by their history (see [How conversations are recognized](#how-conversations-are-recognized)).
-- If pi's own OpenViking extension is active, the gateway steps aside for those conversations. Use one or the other.
+### By task {#by-task}
-### Volcano Engine Ark and BytePlus ModelArk SDKs
-
-Clients and SDKs already set up for Volcano Engine Ark, or BytePlus ModelArk (its international edition), only need the address replaced. Under `/gateway`, the gateway accepts Ark's own paths (`/api/v3/chat/completions`, `/api/v3/responses`, `/api/v3/models` and `/api/compatible/v1/messages`) as well as the standard `/v1` paths:
-
-| Original address | Gateway address |
+| I want to… | Go to |
| --- | --- |
-| `https://ark.cn-beijing.volces.com/api/v3` | `https://ov.example.com/gateway/api/v3` |
-| `https://ark.ap-southeast.bytepluses.com/api/v3` | `https://ov.example.com/gateway/api/v3` |
-| `https://ark.cn-beijing.volces.com/api/compatible` (Anthropic-compatible) | `https://ov.example.com/gateway/api/compatible` |
-
-Use the gateway key in place of the Ark API key. With the Volcano Engine Ark Python SDK:
-
-```python
-from volcenginesdkarkruntime import Ark
-
-client = Ark(base_url="https://ov.example.com/gateway/api/v3", api_key="<gateway-key>")
-```
+| Understand what happens in a turn, what the model sees and why it works this way | [How OpenViking Gateway works](../gateway/01-how-it-works.md) |
+| Try it end to end, from a gateway key to proof that memory works | [Get started](../gateway/02-quickstart.md) |
+| Connect Claude Code, Codex, a chat app or an SDK | [Connect clients](../gateway/03-connect-clients.md) |
+| Let the model use memory tools, or handle long conversations | [OpenViking tools](../gateway/04-openviking-tools.md) and [Long conversations in the gateway](../gateway/05-long-conversations.md) |
+| Deploy, expose, upgrade and monitor the gateway | [Deployment and operations](22-gateway-operations.md) |
+| Review what is stored, who can see it and how to delete it | [Security and data](../gateway/11-security-and-data.md) |
+| Fix an error, a warning or missing memory | [Troubleshooting](../gateway/12-troubleshooting.md) |
+| Look up a setting's name, default or range | [Configuration reference](../gateway/13-configuration.md) |
+| Manage the gateway over HTTP | [Management API](../api/25-gateway.md) |
-The path a client uses only decides which API it speaks. The request still goes to an upstream bound to the key that uses that API and serves the model, usually one whose provider is Volcano Engine Ark or BytePlus ModelArk (see [Upstreams](22-gateway-operations.md#upstreams)).
+### By Studio tab {#by-studio-tab}
-## How conversations are recognized
+In Studio, open **OpenViking Gateway** in the sidebar. Each tab has its own page:
-The gateway needs to know which conversation a request belongs to. A conversation keeps one context profile and one upstream, and is saved to one OpenViking session. The gateway takes the first of these request headers that is present:
-
-1. `X-OpenViking-Session`
-2. `thread-id`
-3. `x-claude-code-session-id` (Claude Code)
-4. `x-opencode-session-id` (OpenCode)
-5. `x-session-id`
-6. `session-id` (Codex CLI)
-
-If none is present, the gateway looks at the latest assistant reply in the history. If an earlier conversation produced that reply, the request joins it; otherwise it starts a new conversation. Two conversations that only share an opening message are never merged. This handles ordinary back-and-forth chat, but retries, regenerated answers and identical conversations are ambiguous and may start a new conversation. So send `X-OpenViking-Session` whenever your client lets you set headers.
-
-Conversations belong to the OpenViking user behind the key, separately for each API. Two gateway keys of the same user that send the same session value share one conversation; the same session value on a different API is a different conversation. The gateway removes all `X-OpenViking-*` headers before forwarding, so providers never see them.
-
-A request that does not join an existing conversation still gets memory: new messages are recalled for, and memory added earlier is replayed, because the gateway finds it by the messages themselves. The difference is that the request starts a new conversation. Its turns are saved to a new OpenViking session, its memory budget starts from zero, and it uses the key's current context profile.
-
-## What to expect
+| Tab | What it is for | Page |
+| --- | --- | --- |
+| **Overview** | Requests, prompt caching, memory and the health of OpenViking at a glance | [Overview](../gateway/10-overview-and-requests.md#overview) |
+| **Upstreams** | The model endpoints the gateway forwards requests to | [Upstreams](../gateway/07-upstreams.md) |
+| **Profiles** | Context profiles: how conversations use memory and tools | [Context profiles](../gateway/08-context-profiles.md) |
+| **Keys** | Issuing and revoking gateway keys | [Gateway keys](../gateway/09-gateway-keys.md) |
+| **Requests** | Each model request and what happened to memory in it | [Request log](../gateway/10-overview-and-requests.md#requests) |
+| **Connect** | The gateway address and exact settings for each client | [Connect clients](../gateway/03-connect-clients.md) |
-- **Recall waits up to 2 seconds.** The first model call of each new message waits for the OpenViking search, at most the profile's **Time limit** (2 seconds by default). If OpenViking times out or is down, the message goes to the model without memory and never gets it later.
-- **Settings apply to new conversations.** A conversation keeps the context profile and upstream it started with. Long-running clients such as Claude Code and Codex can continue one conversation for days, so a profile change reaches them only when they start a new one. The gateway deletes a conversation's state after 30 days without use.
-- **Changed history is saved again.** If the client edits or deletes earlier messages, regenerates an answer after it was saved, or compacts the conversation itself, the gateway saves the current full history to a new OpenViking session. Turns already saved stay in the old session.
-- **Very long sessions can hit the request size limit.** After the gateway compacts a conversation, the client still sends the full history but sees small usage numbers, so clients that compact by usage rarely compact on their own. Request bodies over 32 MiB are rejected; operators can change the limit (see [Long conversations](22-gateway-operations.md#long-conversations)).
-- **One key means one memory owner.** Everyone who shares a key shares the memory of the OpenViking user behind it. Issue one key per person, and separate keys per client if you want different context profiles.
-- **Subscription logins are not supported.** Requests with a Claude subscription token are rejected. Configure the upstream with a provider API key.
-- **Responses needs the full history.** Responses requests that rely on state stored at the provider (`previous_response_id`, `conversation`, `background`), or that do not set `store: false`, are forwarded without memory. Later lookups of those responses still go to the upstream that created them.
-- **Other endpoints pass through.** Endpoints other than the three model APIs and the model list, such as embeddings, are forwarded without memory to the highest-priority upstream bound to the key that serves the requested model.
+If **Upstreams** or **Profiles** is read-only, or Studio asks you to **Enter gateway management key**, see [Who can change what](../gateway/06-manage-in-studio.md#who-can-change-what).
-## Next steps
+### Related docs {#related-docs}
-- [OpenViking Gateway deployment and operations](22-gateway-operations.md): deploy with Docker Compose, Helm or a standalone process; manage upstreams, context profiles and keys; troubleshoot.
-- [OpenViking Gateway Management API](../api/25-gateway.md): the access matrix and management endpoints.
- [Authentication](04-authentication.md): create accounts, users and their keys.
- [Public Access & Reverse Proxy](12-public-access.md): put OpenViking behind HTTPS.
- [Agent Integrations](../agent-integrations/01-overview.md): plugins for agents that support them.
diff --git a/docs/en/guides/22-gateway-operations.md b/docs/en/guides/22-gateway-operations.md
index c02299303..64d84feff 100644
--- a/docs/en/guides/22-gateway-operations.md
+++ b/docs/en/guides/22-gateway-operations.md
@@ -1,95 +1,50 @@
---
-description: Deploy OpenViking Gateway with Docker Compose, Helm or as a standalone process, manage it in Studio, and troubleshoot it.
+description: Deploy OpenViking Gateway inside the server, with Docker Compose or Helm, or as a standalone process, then expose it, protect it and keep it running through upgrades.
---
# OpenViking Gateway deployment and operations
-This page is for the people who run OpenViking Gateway: how to deploy it, how to manage upstreams, context profiles and keys in Studio, where data is stored and how to back it up, and how to track down problems. For what the gateway does and how to connect clients, see [OpenViking Gateway](15-gateway.md); for the overall design, see [Architecture at a glance](15-gateway.md#architecture-at-a-glance).
+This page is for the people who run OpenViking Gateway as a service: deploy it in the form that suits you, put it behind a proxy, control who can change it, and keep it healthy through upgrades and migrations. You need an OpenViking Server that uses API-key authentication or local dev mode; the full list is under [Requirements](#requirements). If you are new to the gateway, read [OpenViking Gateway](15-gateway.md) first.
-The gateway is in beta. Settings and APIs may change between releases, so read the release notes before you upgrade.
+> **Note**: The gateway is in beta. Settings and APIs may change between releases, so read the release notes before you upgrade.
-## Requirements
+**Looking for something else?** This page covers running the gateway. For everything else:
-- **OpenViking authentication**: `api_key` or local dev mode. The gateway does not support trusted authentication.
-- **OpenViking version**: an embedded gateway ships with the server, so there is nothing to check. A standalone gateway needs OpenViking Server 0.4.16 or later.
-- **Installation**: the gateway is part of the OpenViking core package. The optional `gateway-fast` extra (`pip install "openviking[gateway-fast]"`) adds a faster event loop and HTTP parser.
-- **Sign-in**: remote deployments need an OpenViking API key. Users, account admins and root can all sign in to the gateway pages in Studio. Local dev mode needs no key and always uses the `default/default` identity.
-- **Storage**: a local disk. The gateway's SQLite databases serve one host only; network filesystems and storage shared between hosts are not supported.
+- Studio tabs and settings: [Manage OpenViking Gateway in Studio](../gateway/06-manage-in-studio.md), then [Upstreams](../gateway/07-upstreams.md), [Context profiles](../gateway/08-context-profiles.md), [Gateway keys](../gateway/09-gateway-keys.md) and [Gateway overview and request log](../gateway/10-overview-and-requests.md).
+- An error, a warning or a Studio setup card: [Troubleshoot OpenViking Gateway](../gateway/12-troubleshooting.md).
+- A configuration field or environment variable: [Configuration reference](../gateway/13-configuration.md).
+- What is stored, who can see it, retention and backups: [Security and data](../gateway/11-security-and-data.md).
+- OpenViking tools or long conversations: [OpenViking tools in the gateway](../gateway/04-openviking-tools.md) and [Long conversations in the gateway](../gateway/05-long-conversations.md).
+- Settings for one client: [Connect clients](../gateway/03-connect-clients.md).
-## Keys and credentials
+## Requirements {#requirements}
-The gateway involves four keys, each with one job:
-
-| Key | Purpose | Where it is used |
-| --- | --- | --- |
-| OpenViking API key | Signs in to Studio; decides which account and user memory is read and written as | `X-API-Key` or `Authorization: Bearer` on management requests |
-| Gateway key (`ovgw_…`) | Connects a client; each one binds a user, a context profile and a set of upstreams | The client's API key field |
-| Gateway management key (optional) | Restricts who can change upstreams and context profiles | `gateway.management_key`; the `X-OpenViking-Gateway-Management-Key` request header |
-| Upstream API key | Calls the model provider | The upstream editor |
-
-The gateway has no encryption key of its own: it encrypts its local storage with OpenViking's encryption settings; see [Encryption](#encryption).
-
-### Gateway management key
-
-Without a management key, every signed-in user in an account can add and change that account's upstreams and context profiles. With one, only requests that carry it can change them, including requests from OpenViking admins and root. Everyone else can view and test them, and pick them when issuing keys. The management key does not limit who can sign in, or whether users can issue gateway keys for themselves. The full rules are in the [access matrix](../api/25-gateway.md#credentials-and-account-scope).
-
-To set one:
-
-- **`openviking-server init`** (embedded): for a remote deployment, answer no to **Allow users to configure their own gateway upstreams?**. Init generates a value starting with `ovgm_`, prints it and saves it to `gateway.management_key` in `ov.conf`.
-- **`openviking-gateway init`** (standalone): answer yes to **Require a management key to change upstreams and profiles?**. Init generates an `ovgm_` value, prints it once and saves it to `management_key` in `gateway.conf`.
-- **By hand**: use at least 32 characters, for example from `openssl rand -base64 32`. Put it in `management_key`, or set the `OPENVIKING_GATEWAY_MANAGEMENT_KEY` environment variable, which overrides the file in both forms; see [Configuration reference](#configuration-reference).
-- **Compose and Helm**: Compose passes `OPENVIKING_GATEWAY_MANAGEMENT_KEY` into the container; Helm reads it from the `management-key` entry of the Secret named in `gateway.existingSecret`. See [Docker Compose](#docker-compose) and [Helm](#helm).
-
-There is no command-line flag for the management key, because flags show up in process lists and shell history. Setting, changing or removing it takes a restart. It does not revoke issued gateway keys or change existing upstreams and context profiles.
-
-#### Lost the management key
-
-Look where the gateway reads it from:
-
-- The `OPENVIKING_GATEWAY_MANAGEMENT_KEY` environment variable wins over the files. Compose usually sets it in the `.env` file next to `docker-compose.yml`; Helm reads it from the `management-key` entry of the Secret named in `gateway.existingSecret`.
-- Otherwise it is `gateway.management_key` in `ov.conf` (embedded) or `management_key` in `gateway.conf` (standalone). A value written as `$VAR` lives in that environment variable.
-- On an embedded gateway, root can also open `ov.conf` in Studio under **Settings** → **Server configuration** → **File editor**. Keys generated by `openviking-server init` and by Studio's **Enable gateway** are stored there in plain text.
-
-If you can't recover it, put a new value of at least 32 characters in the same place (for example from `openssl rand -base64 32`) and restart. Issued gateway keys, upstreams and context profiles are unaffected. An empty environment variable does not clear the value in the file; unset the variable instead.
-
-### Encryption
-
-The gateway encrypts stored credentials and conversation state with OpenViking's own encryption (see the [Encryption guide](08-encryption.md)):
-
-- **Embedded**: the gateway follows the server's `encryption` section in `ov.conf`. There is nothing to set for the gateway itself.
-- **Standalone**: add an `encryption` block to `gateway.conf`. It has exactly the same fields as the `encryption` section of `ov.conf`, for example:
-
- ```json
- {
- "openviking_url": "https://ov.example.com",
- "encryption": {
- "enabled": true,
- "provider": "local",
- "local": { "key_file": "~/.openviking/master.key" }
- }
- }
- ```
-
-When encryption is off or the block is missing, the gateway stores everything in plain text, protected only by file permissions. Turning encryption on later is safe: values written before stay readable, and new writes are encrypted. Turning it off, or switching to a different root key, makes the encrypted values unreadable, so keep the settings the data was written with. Back up the root key as the Encryption guide describes; without it, the gateway's databases cannot be read.
+| Requirement | Details |
+| --- | --- |
+| OpenViking authentication | `api_key` or local dev mode. The gateway does not support trusted authentication. |
+| OpenViking version | An embedded gateway ships with the server, so there is nothing to check. A standalone gateway needs OpenViking Server 0.4.16 or later. |
+| Installation | The gateway is part of the OpenViking core package. The optional `gateway-fast` extra (`pip install "openviking[gateway-fast]"`) adds a faster event loop and HTTP parser. |
+| Sign-in | Remote deployments need an OpenViking API key; users, account admins and root can all sign in to the gateway pages in Studio. Local dev mode needs no key and always uses the `default/default` identity. |
+| Storage | A local disk. The gateway's SQLite databases serve one host only; network filesystems and storage shared between hosts are not supported. |
-Data written by the v0.5 gateway, which used its own key, is converted on the first start; see [Migration](#migration).
+## Choose a deployment form {#deployment-options}
-## Deploy
+The gateway runs either inside the OpenViking Server (embedded) or as its own process (standalone). Both serve the same model and management paths under `/gateway`.
-### Deployment options
+| Form | Choose it when | How to enable it | Client address |
+| --- | --- | --- | --- |
+| Embedded in the server (including Compose and Helm) | You run the OpenViking Server yourself. There is no second process and no path-based reverse proxy. | Turn on `gateway.enabled` in `ov.conf` | The server address plus `/gateway`, `http://127.0.0.1:1933/gateway` by default |
+| Standalone | You want to leave the OpenViking service's configuration untouched, for example an OpenViking Cloud service. | `openviking-gateway init`, then `openviking-gateway` | The gateway's own address plus `/gateway`, `http://127.0.0.1:1935/gateway` by default |
-| Form | How to enable it | Client address |
-| --- | --- | --- |
-| Embedded in the server (including Compose and Helm) | Turn on `gateway.enabled` in `ov.conf` | The server address plus `/gateway`, `http://127.0.0.1:1933/gateway` by default |
-| Standalone | `openviking-gateway init`, then `openviking-gateway` | The gateway's own address plus `/gateway`, `http://127.0.0.1:1935/gateway` by default |
+Then follow the section for your setup: [Enable it in the server](#enable-it-in-the-server), [Docker Compose](#docker-compose), [Helm](#helm) or [Standalone deployment](#standalone-deployment).
-Both forms serve the same model and management paths under `/gateway`. An embedded gateway needs no second process and no path-based reverse proxy. A standalone gateway leaves the existing OpenViking service's configuration untouched.
+## Enable it in the server {#enable-it-in-the-server}
-### Enable it in the server
+The embedded gateway runs inside the OpenViking Server on the same port, and it is off by default (`gateway.enabled` is `false`). Until you turn it on, Studio's **OpenViking Gateway** page shows **The gateway is not enabled on this OpenViking server**. Turn it on in one of three ways.
-Run `openviking-server init`, answer yes to **Enable OpenViking Gateway on the same port?**, then start or restart the server. With an existing configuration, choose **Update gateway** from the menu. For a remote deployment, init also asks whether users may configure upstreams themselves; see [Gateway management key](#gateway-management-key).
+**With `openviking-server init`.** Answer yes to **Enable OpenViking Gateway on the same port?**, then start or restart the server. With an existing configuration, choose **Update gateway** from the menu. For a remote deployment, init also asks whether users may configure upstreams themselves; see [Gateway management key](#gateway-management-key).
-You can also merge this into `ov.conf` and restart:
+**In `ov.conf`.** Merge this into `ov.conf` and restart the server:
```json
{
@@ -99,44 +54,25 @@ You can also merge this into `ov.conf` and restart:
}
```
-On a server that uses API keys, root can also choose **Enable gateway** on Studio's OpenViking Gateway page, which writes `gateway.enabled: true` to `ov.conf` and restarts the server (the restart from Studio needs a single-worker server; otherwise Studio only saves the file and you restart the server yourself).
+**From Studio.** On a server that uses API keys, root can choose **Enable gateway** on Studio's OpenViking Gateway page. Studio writes `gateway.enabled: true` to `ov.conf` and restarts the server. The confirmation dialog can also generate a gateway management key; see [Gateway management key](#gateway-management-key). Exceptions:
-Open `/studio/` on the server and choose **OpenViking Gateway** in the sidebar. In dev mode, if the default account has no upstreams, the gateway imports the server's usable VLM credentials as upstreams at startup and creates a `default` context profile. Imported Coding Plan upstreams need confirmation before use. If nothing can be imported, add an upstream by hand.
+- Restarting from Studio needs a single-worker server. Otherwise Studio only saves the file, and you restart the server yourself.
+- When `OPENVIKING_GATEWAY_ENABLED` is set, it overrides `gateway.enabled` in `ov.conf`, so a false value keeps the gateway off after the restart.
+- If `ov.conf` is read-only, for example mounted from a Helm ConfigMap, Studio cannot change it. Set `gateway.enabled: true` in the Helm values or `OPENVIKING_GATEWAY_ENABLED=true`, then restart the server.
-**Letting an agent change the configuration.** An agent that holds the root API key can edit `ov.conf` and restart the server through the [runtime configuration API](../api/08-admin.md#runtime-configuration). A standalone gateway does not offer this API.
-
-### Routes
-
-Every gateway URL is under `/gateway`, in both forms. An embedded server hands the whole `/gateway` prefix to the gateway and keeps every other path for itself:
+**Check that it is on.** Open `/studio/` on the server and choose **OpenViking Gateway** in the sidebar: you should see the gateway tabs instead of the not-enabled card. In local dev mode, if the default account has no upstreams, the gateway imports the server's usable VLM credentials as upstreams at startup and creates a `default` context profile. Imported Coding Plan upstreams need confirmation before use; if nothing can be imported, add an upstream by hand ([Upstreams](../gateway/07-upstreams.md#add-an-upstream)).
-| Path prefix | Purpose |
-| --- | --- |
-| `/gateway/v1/` | Model APIs and the model list |
-| `/gateway/api/v3/` | Ark-compatible clients |
-| `/gateway/api/compatible/v1/` | Ark Anthropic-compatible clients |
-| `/gateway/uploads` | Tool uploads |
-| `/gateway/admin/` | Management API (authenticated) |
-
-Clients therefore use these base URLs, with `http://127.0.0.1:1933` replaced by your server's address:
-
-| Client | Base URL |
-| --- | --- |
-| Claude Code and Anthropic SDKs | `http://127.0.0.1:1933/gateway` |
-| OpenAI-compatible clients and SDKs, including Codex, OpenCode, pi and Open WebUI | `http://127.0.0.1:1933/gateway/v1` |
-| Volcano Engine Ark and BytePlus ModelArk SDKs | `http://127.0.0.1:1933/gateway/api/v3` |
-
-`/health` stays the server's own health check; an embedded gateway has no separate `/health`.
-
-A standalone gateway serves the same `/gateway` paths on its own port, plus these at the root:
+**Letting an agent change the configuration.** An agent that holds the root API key can edit `ov.conf` and restart the server through the [runtime configuration API](../api/08-admin.md#runtime-configuration). A standalone gateway does not offer this API.
-- `/` redirects to `/studio/`, where Studio has only the gateway and connection pages.
-- `/health` returns `service: "openviking-gateway"`, `auth_mode` and `openviking_url`, and also the caller's identity when the request carries a valid OpenViking credential.
+## Docker Compose {#docker-compose}
-**Public address.** For a shared deployment, set `public_url` to the address clients use to reach the server (or the standalone gateway), without `/gateway`; the gateway appends `/gateway` itself. When it is empty, an embedded gateway uses the server's public address (`OPENVIKING_PUBLIC_BASE_URL` or `server.public_base_url`). Studio's setup guides build client settings from it: Anthropic clients use `<public_url>/gateway`, and OpenAI-style clients `<public_url>/gateway/v1`. Without it, the guides use the address the browser used to open Studio, but upload and download links only work with `public_url` set; see [Import files and skills](#import-files-and-skills).
+With Docker Compose, the gateway runs inside the `openviking` service; there is no separate service or profile.
-### Docker Compose
+1. Set `OPENVIKING_GATEWAY_ENABLED=true` in `.env`, or turn on `gateway.enabled` in the mounted `ov.conf`. When the variable is set, it wins over `ov.conf`.
+2. Make sure the mounted `ov.conf` uses API-key authentication: the server listens on `0.0.0.0` inside the container.
+3. Run `docker compose up -d`, open `/studio/` on port 1933 and choose **OpenViking Gateway**. You should see the gateway tabs; if the server does not come up, read the startup errors with `docker compose logs openviking`.
-Set `OPENVIKING_GATEWAY_ENABLED=true` in `.env`, then run `docker compose up -d`; or turn on `gateway.enabled` in the mounted `ov.conf`. The gateway runs inside the `openviking` service; there is no separate service or profile. Without Compose, add `-e OPENVIKING_GATEWAY_ENABLED=true` to `docker run`:
+Without Compose, add `-e OPENVIKING_GATEWAY_ENABLED=true` to `docker run`:
```bash
docker run -d -p 1933:1933 -v ~/.openviking:/app/.openviking \
@@ -144,17 +80,15 @@ docker run -d -p 1933:1933 -v ~/.openviking:/app/.openviking \
ghcr.io/volcengine/openviking:latest
```
-The server listens on `0.0.0.0` inside the container, so `ov.conf` must use API-key authentication.
-
- **Management key**: set `OPENVIKING_GATEWAY_MANAGEMENT_KEY` in `.env`, and the bundled Compose file passes it into the container; or put it in `gateway.management_key` in the mounted `ov.conf`. The Compose file also passes `OPENVIKING_GATEWAY_ENCRYPTION_KEY`, which is only read once to migrate v0.5 data; see [Migration](#migration).
-- **Public address**: set `OPENVIKING_PUBLIC_BASE_URL` (the bundled Compose file passes it); the gateway uses it when it has no `public_url` of its own.
-- **After a configuration change**: run `docker compose restart openviking`; read startup errors with `docker compose logs openviking`.
+- **Public address**: set `OPENVIKING_PUBLIC_BASE_URL` (the bundled Compose file passes it); the gateway uses it when it has no `public_url` of its own. See [Public address](#public-address).
+- **After a configuration change**: after editing the mounted `ov.conf`, run `docker compose restart openviking`. After editing `.env`, run `docker compose up -d`: `restart` reuses the existing container and does not pick up new `.env` values.
The bundled Caddy forwards all paths to `openviking:1933`. Clients can keep using the compatibility port 1934, or go straight to the server on 1933. For HTTPS, a single `reverse_proxy openviking:1933` carries Studio, the management API and model traffic; see [Public access](12-public-access.md).
-### Helm
+## Helm {#helm}
-Set `gateway.enabled: true` in the chart values. The gateway runs inside the server container, keeps its data in `<persistence.mountPath>/gateway`, and uses the server port for both the Service and the Ingress. Keep `replicaCount: 1`.
+With the Helm chart, set `gateway.enabled: true` in the chart values. The gateway runs inside the server container, keeps its data in `<persistence.mountPath>/gateway`, and uses the server port for both the Service and the Ingress. Keep `replicaCount: 1`.
```yaml
gateway:
@@ -167,745 +101,252 @@ config:
- The gateway encrypts its data with the chart's `config.encryption` settings, the same as the server.
- With a `management-key` entry in the `existingSecret` Secret, changing upstreams and context profiles requires that management key.
-- Model requests stream: the Ingress must turn off response buffering and allow request bodies of at least 32 MiB and timeouts of 600 seconds.
+- Model requests stream: the Ingress must turn off response buffering and allow request bodies of at least 32 MiB and timeouts of 600 seconds (see [Reverse proxy and HTTPS](#reverse-proxy-and-https)).
The NGINX annotations, the commands to create the Secrets and the notes on upgrading from the sidecar chart are in the [chart README](https://github.com/volcengine/OpenViking/blob/main/deploy/helm/README.md#openviking-gateway).
-### Standalone deployment
+## Standalone deployment {#standalone-deployment}
-A standalone gateway does not read `ov.conf`. It only needs the OpenViking address, so an existing open-source or OpenViking Cloud service needs no configuration change:
+A standalone gateway does not read `ov.conf`. It only needs the OpenViking address, so an existing open-source or OpenViking Cloud service needs no configuration change.
-```bash
-openviking-gateway init # writes ~/.openviking/gateway.conf
-openviking-gateway
-```
-
-`openviking-gateway init` asks for the OpenViking address and checks it (showing the server's authentication mode and version), the listen address (`127.0.0.1:1935` by default), and whether to require a [management key](#gateway-management-key). It writes `~/.openviking/gateway.conf`, or the file named by `--config`, readable only by you. Run it again to change the settings: it offers the current values as defaults and keeps existing secrets unless you change them. The resulting file looks like this:
-
-```json
-{
- "openviking_url": "https://ov.example.com",
- "host": "127.0.0.1",
- "port": 1935
-}
-```
-
-Open the gateway's `/studio/` and sign in with the API key of an OpenViking user, account admin or root. The connection page shows which OpenViking address the gateway uses. A standalone gateway cannot read the remote server's VLM settings, so it cannot import model settings; add upstreams by hand.
-
-**Where the settings come from.** The only flag is `--config`. When `--config` or `OPENVIKING_GATEWAY_CONFIG_FILE` is set, it must point to an existing file; otherwise the gateway reads the first of `~/.openviking/gateway.conf` and `/etc/openviking/gateway.conf` that exists. Environment variables override any field in it. A container needs no file at all: set `OPENVIKING_GATEWAY_OPENVIKING_URL`, plus for example `OPENVIKING_GATEWAY_HOST=0.0.0.0`. Without an OpenViking address from either source, the gateway exits and asks you to run `openviking-gateway init` or set `OPENVIKING_GATEWAY_OPENVIKING_URL`. Every field and the override rule are in the [Configuration reference](#configuration-reference).
-
-**Startup checks.** Before it starts, a standalone gateway contacts OpenViking once:
-
-- If OpenViking uses trusted authentication, the gateway refuses to start.
-- When the gateway binds to a non-loopback address, it starts only after confirming that OpenViking uses `api_key` authentication. If OpenViking is unreachable or runs in dev mode, the gateway exits. Start OpenViking first, or bind to `127.0.0.1`.
-- When OpenViking runs on another host, connect over TLS or a private network.
-
-**Connecting to the public OpenViking service.** When the gateway connects to `https://api.vikingdb.cn-beijing.volces.com/openviking` without a management key, the startup log and Studio show the `public_openviking_without_management_key` warning: anyone with an API key for that service can sign in to this gateway and change the upstreams in their account. If the gateway is only for you or your team, set `OPENVIKING_GATEWAY_MANAGEMENT_KEY` and restart to restrict changes. This does not limit who can sign in or whether they can issue gateway keys for themselves.
-
-### Reverse proxy and HTTPS
-
-Forward the whole site to the server (embedded) or to the gateway (standalone); no path-based routing is needed. With Caddy:
-
-```caddyfile
-ov.example.com {
- reverse_proxy 127.0.0.1:1933 {
- flush_interval -1
- }
-}
-```
-
-Whatever proxy you use, it needs three things: response buffering off, so streamed output arrives in real time; request bodies of at least 32 MiB; and read timeouts of at least 600 seconds. Also keep the query strings of `/gateway/uploads` out of proxy logs, because they carry one-time upload tokens. Set up authentication before you expose the service; see [Public access](12-public-access.md).
-
-### Scaling
-
-One storage directory serves one deployment on one host, and an embedded and a standalone gateway must not share a directory. An embedded gateway follows the server's worker setting; a standalone gateway takes `workers`, from 1 to 64. For load balancing, failover or rate limiting across providers, add a service such as LiteLLM as an upstream.
-
-## Manage the gateway in Studio
-
-Connect Studio with an OpenViking API key and open **OpenViking Gateway** in the sidebar. Upstreams and context profiles are shared by the whole account; gateway keys and request logs belong to individual users.
-
-- **No management key set**: every signed-in user can add and change the account's upstreams and context profiles.
-- **Management key set**: the Upstreams and Profiles tabs are read-only, for OpenViking admins and root too. Read-only users can still view upstreams (without their API keys and headers) and pick them when issuing keys for themselves, but model tests require write access because they make billable provider requests. Choose **Enter gateway management key** to unlock editing and testing; the header then shows **Editing upstreams and profiles**. Editing stays unlocked until you choose **Lock** or close the browser tab. If the management key is changed, Studio locks again on its own.
-- **Gateway keys**: everyone can issue keys for themselves; account admins can issue keys for users in their account; root first switches account in the sidebar. See [Gateway keys](#gateway-keys).
-
-Saved upstreams and context profiles take effect at once for the keys that use them (a context profile only affects conversations that start afterwards). If no usable upstream or context profile exists yet and you cannot change them, ask whoever deployed the gateway.
-
-### Upstreams
-
-An upstream is one endpoint of a model service and uses exactly one API: Anthropic Messages, Chat Completions or Responses. The gateway does not convert between APIs, so add one upstream for each API your clients use, even when they come from the same provider. Claude Code uses Anthropic Messages, Codex CLI uses Responses, and most chat apps and SDKs use Chat Completions.
-
-When you choose a provider in the editor, its default Base URL is filled in:
-
-| Provider | Protocols | Default Base URL |
-| --- | --- | --- |
-| Generic | All three | None; enter it yourself |
-| Anthropic | Anthropic Messages | `https://api.anthropic.com` |
-| OpenAI | Chat Completions, Responses | `https://api.openai.com/v1` |
-| DeepSeek | All three | `https://api.deepseek.com`; `https://api.deepseek.com/anthropic` for Anthropic Messages |
-| Volcano Engine Ark | All three | `https://ark.cn-beijing.volces.com/api/v3` for Chat Completions and Responses; `https://ark.cn-beijing.volces.com/api/compatible` for Anthropic Messages |
-| BytePlus ModelArk | All three | `https://ark.ap-southeast.bytepluses.com/api/v3` for Chat Completions and Responses; `https://ark.ap-southeast.bytepluses.com/api/compatible` for Anthropic Messages |
-
-#### Endpoint
-
-- **Provider** decides which protocols you can pick and lets the gateway handle each provider's differences. Choose *Generic* for a provider not in the list, for a compatible proxy such as LiteLLM or new-api, and for a reverse proxy such as [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) that exposes subscription accounts as an API (see [Custom upstreams](15-gateway.md#custom-upstreams); check yourself whether using subscription quota this way is allowed).
- - *Generic*, *Anthropic* and *OpenAI* forward requests the same way.
- - *DeepSeek*: when a request has tools, DeepSeek requires every earlier reply in the history to carry its reasoning, and many chat apps do not send it back. DeepSeek upstreams have **Restore reasoning the client drops** on by default (see [Routing](#routing)), so requests can keep thinking on and still get OpenViking tools. With that setting off, OpenViking tools are offered only when a request turns thinking off (`"thinking": {"type": "disabled"}`). Standard Responses requests have no `thinking` field, so they then get no tools. Memory is added as usual.
- - *Volcano Engine Ark* and *BytePlus ModelArk* behave the same: each Chat Completions and Responses conversation gets a fixed `prompt_cache_key`, so Ark's prefix cache follows the conversation. If a request's model, thinking mode, sampling parameters, system prompt or tools differ from the conversation's first request, Ark rebuilds its cache, and the request is flagged **Cache parameters changed** (`ark_cache_parameters_changed`).
-- **Protocol** decides which API the upstream accepts. Anthropic upstreams send both `x-api-key` and `Authorization: Bearer`; Chat Completions and Responses upstreams send only Bearer.
-- **Base URL**: copy it from the provider's SDK documentation. The gateway appends the endpoint to it:
- - Chat Completions and Responses append `/chat/completions` or `/responses`. A bare domain does not get `/v1` added, so OpenAI needs `https://api.openai.com/v1`.
- - Anthropic Messages appends `/v1/messages`, so the Base URL must not end in `/v1`; saving such a URL is rejected.
- - A trailing slash is removed. Addresses with a version path, such as `/api/paas/v4`, work as is.
- - The Base URL may carry a query, such as `?api-version=…`. The client's query parameters follow it, and on a name clash the Base URL's value wins.
- - Requests that clients send to the Ark paths (`/gateway/api/v3/`, `/gateway/api/compatible/v1/`) follow the same rules.
- - Azure OpenAI's v1 API uses `https://RES.openai.azure.com/openai/v1`, Claude in Microsoft Foundry uses the Anthropic Messages protocol with `https://RES.services.ai.azure.com/anthropic`, and Gemini's OpenAI-compatible API uses `https://generativelanguage.googleapis.com/v1beta/openai`; all of them follow these joining rules.
- - An upstream has one Base URL. If a provider uses different addresses for different protocols, create separate upstreams. For example, Zhipu uses `https://open.bigmodel.cn/api/paas/v4` for Chat Completions and `https://open.bigmodel.cn/api/v1` for Responses. Ark Coding Plan uses `…/api/coding/v3` for Chat Completions and Responses and `…/api/coding` for Anthropic Messages.
-- **Append protocol endpoint path** is on by default. Turn it off when Base URL is already the complete request endpoint; the gateway then sends the protocol's requests to that exact URL without adding a protocol path. Sub-paths continue after it: Anthropic token counting goes to `…/count_tokens`. Other APIs, such as embeddings and the model list, are not routed to such an upstream, and the connection test skips it. For example, an Azure OpenAI deployment uses protocol *Chat Completions*, provider *Generic*, Base URL `https://RES.openai.azure.com/openai/deployments/DEPLOYMENT/chat/completions?api-version=2024-10-21`, this setting off, and **Send the key as** *api-key header*.
-
- The editor previews the final request URL as you type. If an OpenAI or Ark address is missing its path, or an Anthropic address ends in `/v1`, it warns you and offers a one-click fix.
-
-#### Credentials
-
-- **Who provides the API key**:
- - **The gateway holds the API key** (the default): the gateway sends the upstream's API key, and clients need only their gateway key.
- - **Each client sends its own key**: besides the gateway key, every request carries the client's own provider API key in the `X-OpenViking-Upstream-Key` header. Without it the request fails with 401 "Upstream API key is missing". The gateway passes the key on as set in **Send the key as** (or fills it into the URL when the Base URL contains `{api_key}`); `X-OpenViking-*` headers themselves are never forwarded.
-- **Send the key as** (provider *Generic* only): `Authorization: Bearer` (the default), the `api-key` header (Azure OpenAI) or the `x-api-key` header.
-- **Key in the URL**: for a provider that expects the key in the address, write `{api_key}` in the Base URL's path or query, for example `?key={api_key}`. The gateway fills in the URL-encoded key when sending and then sends no auth header. Don't write the key itself into the address: the Base URL is visible to everyone who can view upstreams.
-- **API key and extra headers are write-only.** Leave a field blank to keep the stored value; remove a header row to delete that header. **Changing the Base URL clears the stored API key and header values**, so enter them again whenever you change the address. A stored key is never sent to a new address.
-- **Extra headers** are added to every request to this upstream, such as a provider's version or organization header, and replace any client header with the same name. `Host`, `Content-Length`, `Transfer-Encoding` and `Connection` cannot be set.
-- **This key is a Coding Plan or subscription key**: providers usually allow subscription keys such as Coding Plan keys only in their own coding tools, and using one through a shared gateway can get the subscription suspended. When you check this, every request to the upstream is rejected with 403 "Coding Plan upstreams are disabled; configure a model API key", unless you also check **Allow this plan through the gateway**. The gateway cannot tell from the key itself whether it is a subscription key, so you have to mark it. Claude subscription tokens (`sk-ant-oat…`) are always rejected.
-
-#### Models
-
-- **Models** lists the model names this upstream serves. Leave it empty to accept any name. Only listed names and aliases appear in the model list (`/gateway/v1/models`).
-- **Model aliases** map a name that clients use to the model sent to the upstream, for example the Claude model names Claude Code requests to a model your provider serves. Aliases appear in the model list, and the request log shows the name the client used.
-- **Context windows** records each model's window size in tokens (at least 1,024), keyed by the model name actually sent to the upstream, after aliases. Long conversations are compacted at a share of this window, so list every model whose window is smaller than 1,000,000 tokens; see [Long conversations](#long-conversations).
-
-#### Routing
-
-- **Priority**: for each request, the gateway looks at the enabled upstreams bound to the key that use the request's API and serve the requested model, and picks the one with the highest priority. Once a conversation starts, it stays on its upstream as long as that upstream can still serve it, so priority changes only affect new conversations.
-- **Enabled**: a turned-off upstream receives no requests and disappears from the model list. Conversations that were using it move to the next candidate, which costs one provider cache miss and drops earlier Claude thinking blocks; these requests are flagged **Upstream switched** (`upstream_changed`). Turn an upstream off instead of deleting it if you may want it back.
-- **Allow OpenViking tools**: decides whether OpenViking tools can be offered through this upstream. Turning it off takes effect at once, also in conversations that already have the tools.
-- **Restore reasoning the client drops**: when clients send the history back, they often leave out the reasoning of the model's earlier replies. With this on, the gateway records the reasoning of every reply it relays and puts it back in later requests: `reasoning_content` for Chat Completions, thinking blocks for Anthropic Messages, and reasoning items with plain-text content before their item for Responses. The restored content is byte-identical every time, so the provider's prompt cache keeps hitting, but it counts as input tokens. Replies whose reasoning the client sent back itself are left alone. It is on by default for DeepSeek, Volcano Engine Ark and BytePlus ModelArk, and off for other providers. Some requests cannot get their reasoning back even with this on: the conversation moved to another upstream (`upstream_changed`), a Claude conversation lost its memory record (`missing_injection_record`), or the client sent thinking back as plain text. On a DeepSeek upstream, such requests also get no OpenViking tools.
-- **Minimum cacheable prompt** (Ark and ModelArk only): the shortest prompt the model can cache. It only affects how the request log reports cache eligibility.
-
-All upstream settings except priority take effect at once, in ongoing conversations too. The gateway does not fail over: when the chosen upstream returns an error, the client receives it, and an unreachable provider returns 502 "Model upstream is unavailable".
-
-#### Test and delete
-
-With write access, choose **Test** in the upstream list. The gateway checks the saved connection first. Once that succeeds, select or enter a model name and run the model test. The gateway sends one small generation request with the stored credentials and reports whether the endpoint, key, model and protocol worked together. It includes OpenViking tools when the upstream allows them and leaves reasoning effort at the model default. The provider may charge for the model request. Coding Plan upstreams stay blocked from model tests until gateway use is approved. Each result is explained in [Upstream tests](../api/25-gateway.md#upstream-tests).
-
-An upstream that keys still use cannot be deleted. Revoke those keys first, or turn the upstream off instead.
-
-### Import OpenViking model settings
-
-In an embedded deployment, **Use OpenViking's model settings** (**Import from OpenViking** in the Upstreams tab header) turns the server's VLM credentials into upstreams in the current account. Without a management key, only root (including local dev) can import; with one, unlock editing first.
-
-- The result shows three groups: imported, needs confirmation and not imported. Upstreams whose path contains `coding` or `plan` are marked as Coding Plan. Once you have confirmed that the provider's terms allow it, check **Allow this plan through the gateway** to use one.
-- Importing again does not create duplicates. It refreshes the address, API key, headers, protocol and provider from the server, and keeps what you changed in the gateway: name, enabled state, priority, models, aliases, context windows and the Coding Plan confirmation.
-- Azure OpenAI credentials (provider `azure`, or LiteLLM `azure/<deployment>`) become exact-endpoint upstreams that send the key in the `api-key` header, with the configured `api_version`.
-- Codex OAuth credentials, LiteLLM credentials without `api_base`, and LiteLLM routes that do not use the OpenAI Chat Completions API are skipped. The reasons are listed in [Import VLM settings](../api/25-gateway.md#import-vlm-settings).
-
-### Context profiles
-
-A context profile is a named set of memory settings. Each gateway key uses one profile, and one profile can serve many keys. For example, a "Coding" profile might recall memories, resources and skills, while a "Chat" profile recalls only memories, with a smaller budget.
-
-The Profiles tab shows one card per profile, summarizing each section and counting the keys that use it. While the tab is empty, **Create with recommended settings** creates a profile named "Default" in one click and **Customize** opens the editor; after that, use **New profile**. A profile that keys use cannot be deleted. To make a variant, **Duplicate** is the quickest way.
-
-> **Note**: Saved changes apply only to conversations that start afterwards. A conversation records its profile at its first request and keeps it, because changing what the model sees mid-conversation would break the provider cache. Clients that open a new conversation for every chat pick up changes quickly. Claude Code, Codex and clients that send a fixed session header keep the old settings until they start a new conversation, or until the conversation has been idle for 30 days (`session_ttl_days`).
-
-| Section | What it does | Main settings and defaults |
-| --- | --- | --- |
-| Recall memory | Searches OpenViking with each new user message and appends what is relevant to that message. | Sources: memories, resources, skills · Budget per message: 1,600 tokens · Budget per context window: 30,000 tokens · Relevance threshold: 0.35 · Time limit: 2 s |
-| Save conversations | Writes finished turns to an OpenViking session and commits it, so OpenViking can extract memories. | Save the latest reply after: 600 s · Commit after: 20,000 tokens · Keep recent messages: 10 |
-| Long conversations | When a conversation nears the context window, has the same model write a summary that replaces the earlier messages. | Compaction: on · Compact at: 0.9 of the window · Summary length: 8,000 tokens · Agent-managed context windows: off |
-| OpenViking tools | Lets the model use OpenViking's tools while it answers. | On · read-only tools selected; see [OpenViking tools](#openviking-tools) |
-
-Each section has its own switch, and Long conversations has one each for compaction and agent-managed context windows. Recall and saving are independent: a profile can recall without saving, or save without recalling.
-
-**Recall details:**
-
-- **User profile at conversation start** works independently of recall. When the `read` tool is offered, memory and skill catalogs are added at the start as well. **Opening context budget** is 4,000 tokens by default, with at most a quarter for skills; 0 leaves all of it out. It does not count against the recall budget.
-- OpenViking selects and formats the recalled content within the budget. It may also return just a URI for the model to read later.
-- The search query is the user message with client noise removed, cut to **Query length** (8,000) characters. Messages shorter than 3 characters are not searched.
-- Each message gets at most the smaller of **Budget per message** and what is left of **Budget per context window**. With less than 64 tokens left, the search is skipped. The budget per context window starts over whenever the conversation is compacted, by the gateway or by the client. A budget of 0 turns recall off. These token counts are conservative estimates, not the provider's billing counts.
-- If OpenViking does not answer within the **Time limit**, the message goes to the model without memory and does not get it later, even if the client retries.
-- **Limit by category** (under **Advanced settings**) sets a maximum number of entries for each of six categories: events, entities, preferences, experiences, resources and skills. Only categories above 0 are searched. When it is off, all sources are ranked together.
-
-**Recall summary.** With **Show recall summary** on (off by default), the reply to each new user message starts with a short summary of what the gateway added:
-
-```text
-> OpenViking context: user profile, memory index, skill list, earlier sessions
-> OpenViking recall: 4 items (3 memories, 1 resource) — booking_duplicate_handling, user_lang_pref, +2 more
-```
+1. Run `openviking-gateway init`. It asks for the OpenViking address and checks it (showing the server's authentication mode and version), the listen address (`127.0.0.1:1935` by default), and whether to require a [management key](#gateway-management-key). It writes `~/.openviking/gateway.conf`, or the file named by `--config`, readable only by you:
-- The `context` line appears only in the first reply of a conversation. It lists what the opening actually contained: the user profile, the memory catalog, the skill catalog, and where earlier parts of the conversation are stored in OpenViking.
-- The `recall` line counts the recalled entries by kind and names up to three. If the search fails, it gives the reason instead, for example `> OpenViking recall failed: OpenViking unavailable`. It is left out when nothing was found, recall is off or the budget is used up, so after the first reply such messages get no summary.
-- Tool steps and other follow-up requests show no summary. When the client retries the same message, the summary is the same as the first time.
-- In Anthropic Messages the summary is its own text block, in Responses its own assistant message, and in Chat Completions the start of the reply text. Requests that ask for structured output, and Chat Completions requests with `n` above 1, get no summary.
-- The model never sees the summary: when the client sends the reply back with the next message, the gateway removes it before forwarding, and it is not saved to OpenViking.
+ ```json
+ {
+ "openviking_url": "https://ov.example.com",
+ "host": "127.0.0.1",
+ "port": 1935
+ }
+ ```
-**Saving details:**
+2. Run `openviking-gateway`. It runs the [startup checks](#startup-checks) and then listens on the address you chose.
+3. Open the gateway's `/studio/` and sign in with the API key of an OpenViking user, account admin or root. You should see the gateway pages and a connection page that shows which OpenViking address the gateway uses.
+4. Add upstreams by hand. A standalone gateway cannot read the remote server's VLM settings, so it cannot import model settings.
-- A turn is saved when the next user message arrives. **Save the latest reply after** sets how long the gateway waits before it saves the last turn and commits the session, so short conversations get committed too.
-- **Commit after**: the session is committed whenever this many tokens are waiting. After each commit, OpenViking extracts memories in the background.
-- **Keep recent messages**: after a commit, the session keeps the newest whole turns, at least this many messages.
+To change the settings later, run `openviking-gateway init` again: it offers the current values as defaults and keeps existing secrets unless you change them.
-The API name and range of every setting are in the [Configuration reference](#configuration-reference).
+### Where the settings come from {#standalone-config-sources}
-### Gateway keys
+The only command-line flag is `--config`. When `--config` or `OPENVIKING_GATEWAY_CONFIG_FILE` is set, it must point to an existing file; otherwise the gateway reads the first of `~/.openviking/gateway.conf` and `/etc/openviking/gateway.conf` that exists. Environment variables override any field in it, so a container needs no file at all: set `OPENVIKING_GATEWAY_OPENVIKING_URL`, plus for example `OPENVIKING_GATEWAY_HOST=0.0.0.0`.
-A gateway key (`ovgw_…`) is what a client uses in place of a provider API key. Each key belongs to one OpenViking user and uses one context profile and a set of upstreams.
+Without an OpenViking address from either source, the gateway exits and asks you to run `openviking-gateway init` or set `OPENVIKING_GATEWAY_OPENVIKING_URL`. Every field and the override rule are in the [Configuration reference](../gateway/13-configuration.md#configuration-reference).
-On the Keys tab, choose **Issue key** and fill in:
+### Startup checks {#startup-checks}
-- **Name**: something to recognize the key by, for example "alice · Claude Code".
-- **Who is this for?**: users issue keys only for themselves; account admins can choose a user in their account; root switches account in the sidebar first. The gateway reads the chosen user's API key from OpenViking. If OpenViking stores only key hashes, it cannot, and Studio shows **Paste a user API key** so you can enter that user's current key. A root API key cannot be bound to a gateway key. In local dev mode, keys read and write memory as the `default` user.
-- **Context profile**.
-- **Upstreams**: at least one. The key can reach only the upstreams you select.
-- **Allowed models** (optional): leave empty to allow every model these upstreams serve. Enter the names clients send, including aliases. Requests for other models fail with 403 "Model is not allowed by this key", and the model list shows only allowed names.
+Before it starts, a standalone gateway contacts OpenViking once:
-Before issuing, the gateway checks the user's key with OpenViking. If you paste a root key, a key from another account or an invalid key, or OpenViking is unreachable, issuing fails; see [Issuing a key fails](#issuing-a-key-fails).
-
-After issuing, the **Copy your gateway key** dialog shows the full key. This is the only time you see it: the gateway keeps only a hash and the first few characters. The dialog also has setups for Claude Code, Codex CLI and chat clients, with the real key and gateway address filled in, ready to paste. If a key is lost, issue a new one.
-
-- **Keys cannot be edited.** To change a key's context profile, upstreams, allowed models or user, issue a new key and revoke the old one.
-- **Conversations belong to the user, not the key.** If the client sends the same session ID, a new key for the same user continues the existing conversation, so replacing a key does not interrupt it.
-- **Revoking** a key stops it working at once. The user's conversation state and logs stay until they are explicitly deleted or expire.
-- **When the OpenViking key changes**: after the user's OpenViking API key is regenerated or the user is deleted, OpenViking rejects the old key the gateway stored. The gateway notices on a later request (up to about 30 seconds later) and deletes the gateway keys bound to it; conversation state and logs stay. Issue a new key with the current OpenViking key. If OpenViking is only unreachable or returns an error, the gateway keeps the key, and requests still reach the model, just without memory.
-- **One key per person.** Everyone who shares a key shares the memory of its OpenViking user. Issue one key per person, and separate keys per client if you want different context profiles.
-
-Account admins and root can use **Delete this user's gateway data…** on the Keys tab. It revokes all of the user's gateway keys and deletes the conversation state the gateway keeps for them (including content not yet saved to OpenViking) and their request logs. Memories already in OpenViking are not affected; see [Security and data](#security-and-data).
-
-### Requests and overview
-
-Users see only their own requests; account admins and root see the whole account's.
-
-The **Overview** tab summarizes the latest 10,000 requests within the log retention period (30 days by default):
-
-- Until the first request arrives, a **Get started** checklist, in the order upstream → context profile → key → client. Until the first key exists, its **Quick mode** card does the first three steps in one click: it imports OpenViking's VLM settings when no upstream is usable, creates a context profile with the recommended settings when there is none, and issues a key for the current user. Outside local dev mode, root picks the key's user in the issue dialog instead.
-- **Requests**: the number of model requests, when the last one arrived, and their output tokens.
-- **First-call cache hit rate**: the share of input tokens served from the provider's prompt cache on the first model call of each new user message. This is the most important sign of a healthy gateway. It should stay close to what the provider reaches without the gateway. A clear drop usually means the history the gateway sends no longer matches the previous request; see [The first-call cache hit rate dropped](#the-first-call-cache-hit-rate-dropped).
-- **Within-turn cache hit rate**: the same for later calls in a turn, such as tool steps and OpenViking tool rounds. It is usually high.
-- **Memory entries recalled**: entries added to new messages, and how long an OpenViking search took on average (counting only messages that searched).
-- **Long conversations missing the cache**: a warning when a conversation's last 3 model calls each sent at least 32,000 input tokens, less than 5 minutes apart, and the provider reported 0 cached tokens every time. It lists the model, upstream and streak; when they are all Anthropic conversations that never wrote the cache either, the suggestion is to check that the client sets `cache_control`. Compaction, new context windows, a switched model or upstream, and requests where gateway tools come and go do not count. When an upstream has not reported any cache hit lately, a note says long conversations through it keep showing a 0% cache hit rate instead. See [The first-call cache hit rate dropped](#the-first-call-cache-hit-rate-dropped).
-- **OpenViking**: Connected, Degraded or Starting, with the version, and the reason when degraded. While OpenViking is unreachable, requests still reach the model without memory. The card's **Saving conversations** part counts conversations that are retrying or have paused saving.
-- **Degraded requests**: how often each issue occurred, with an explanation; see [Issues on degraded requests](#issues-on-degraded-requests).
-- **Recent requests**, with a link to the Requests tab.
-
-The **Requests** tab lists the latest 1,000 records, newest first, and refreshes every 30 seconds while you are on the first page. Filter by **All**, **New messages**, **Tool steps** or **Issues**, or by **Request type**, or search by model, conversation or key.
-
-The columns are type, model (the name the client sent), the provider's HTTP status, tokens (input, cached share, output), **Memory**, **Saving** status and **Issue**. In the **Memory** column, `+3` means this request's search added 3 entries, shown with the search time, and `↺ 4` means memory added to 4 earlier messages was replayed unchanged. Expand a row for the conversation ID, upstream, key, duration, token breakdown, memory search result, context window use (and whether it was compacted or the model started a new window), saving status with the next retry time, and OpenViking tool details. For a request with an issue, the row also explains what happened and what to do.
-
-Only requests that reached a model provider are logged. Requests the gateway rejects first are not, such as an invalid key, a model the key does not allow, no matching upstream or a body over the size limit; the client receives the error directly.
-
-| Type | Meaning | Memory |
-| --- | --- | --- |
-| New message | A request whose last message is a new user message | Searched once, earlier memory replayed; the turn is saved |
-| Tool step | The same turn continuing, for example with tool results | Earlier memory replayed; saved with its turn |
-| Housekeeping | Title, summary, compaction, suggestion and permission-check requests | Earlier memory replayed; never saved |
-| Sub-agent | Requests from a client's sub-agents | Earlier memory replayed; never saved |
-| Token count | Token-counting requests (`/gateway/v1/messages/count_tokens`) | Earlier memory replayed, so the count matches what is actually sent |
-| Forwarded | Requests passed through unchanged, without memory: other endpoints, Responses requests that rely on provider-side state, compressed or unreadable bodies | None |
-| Memory sync | Background saving events, not model requests | — |
-
-The **Saving** column shows each conversation's saving status:
-
-- **On**: saving works normally.
-- **Off**: the conversation's context profile does not save.
-- **Retrying**: OpenViking rejected a save or could not be reached. The gateway retries after 10, 20, 40 and 80 seconds.
-- **Paused**: five attempts in a row failed. The gateway then retries every 5 minutes until it succeeds. Unsaved turns are kept until they are saved or the conversation expires.
-- **Paused** with the reason `gateway_key_revoked`: the conversation's gateway key was revoked or deleted, and the gateway stops retrying. Saving resumes when the user next sends a request in this conversation with a valid key.
-
-The expanded row shows the reason, for example that OpenViking rejected the key (`openviking_http_401`, meaning the user's OpenViking key is no longer valid) or that OpenViking is unreachable (`openviking_unavailable`). A history change (`history_changed`) is normal: the client edited, regenerated or compacted the conversation, and the gateway continues saving the current history in a new OpenViking session.
-
-**Resync conversation…** in an expanded row starts a new OpenViking session for the conversation. The next time the user sends a message, the gateway writes the full history to it. What was already saved stays in the old session, so some memories may be extracted twice. Use it when a conversation stays paused after you fixed the cause, or when you want a clean copy of a conversation. Nothing happens until the next message arrives. Resync needs the key shown on the record; if that key has been revoked, pick a newer record of the same conversation.
+- If OpenViking uses trusted authentication, the gateway refuses to start.
+- When the gateway binds to a non-loopback address, it starts only after confirming that OpenViking uses `api_key` authentication. If OpenViking is unreachable or runs in local dev mode, the gateway exits. Start OpenViking first, or bind to `127.0.0.1`.
+- When OpenViking runs on another host, connect over TLS or a private network.
-## OpenViking tools
+### Connecting to the public OpenViking service {#public-openviking-service}
-With OpenViking tools on, the model can use the tools your OpenViking service provides while it answers, within the user's own OpenViking permissions. The gateway runs the calls, the client keeps receiving the answer until the reply ends, and the token usage it sees includes every model call made along the way. For what this means for each kind of client and what users see in the reply, see [Agentic memory for any client](15-gateway.md#agentic-memory-for-any-client). This section covers client requirements, settings and limits.
+A standalone gateway that connects to the public OpenViking service, `https://api.vikingdb.cn-beijing.volces.com/openviking`, without a management key is open to that service's users. The startup log shows the `public_openviking_without_management_key` warning, and Studio shows **This gateway is open to every OpenViking Cloud user**: anyone with an API key for that service can sign in to this gateway and change the upstreams in their account.
-The feature is meant for chat apps and API apps that cannot connect to the OpenViking MCP server. Clients that support MCP or have a plugin, such as Claude Code and Codex, are better served by those, because they show each tool call and its result and ask for approval first.
+If the gateway is only for you or your team, set `OPENVIKING_GATEWAY_MANAGEMENT_KEY` and restart to restrict changes. This does not limit who can sign in or whether they can issue gateway keys for themselves.
-### Client requirements
+## Routes {#routes}
-All three protocols support streaming and non-streaming requests:
+Every gateway URL is under `/gateway`, in both forms. An embedded server hands the whole `/gateway` prefix to the gateway and keeps every other path for itself:
-| Protocol | What the client must do |
+| Path prefix | Purpose |
| --- | --- |
-| Chat Completions | Send the full `messages` history. |
-| Responses | Use `store: false` and the full `input` history, and on the next turn send back the whole returned `output`, including reasoning and client tool calls. Requests with `previous_response_id`, `conversation` or `background` are forwarded as usual but get no gateway tools; `item_reference` cannot rebuild the full history. |
-| Anthropic Messages | Send the full `messages` history with thinking and signature blocks intact. Token-count requests carry the same tool definitions but run no tools. |
-
-When the model calls OpenViking tools and client tools in the same reply, the gateway handles the OpenViking calls, and the client runs its own tools and returns their results as usual. Responses supports client function and custom tools; Anthropic Messages supports client tool_use calls.
-
-### Choose tools
-
-New context profiles have **OpenViking tools** on, including those made with **Create with recommended settings**. The **Tools** list comes from your OpenViking service, and only read-only tools are selected by default:
-
-- **Selected by default**: `find`, `search`, `grep`, `glob`, `list`, `tree`, `read`, `download`, `list_watches`, `get_acl`, `list_users`, `list_groups` and `health`.
-- **Not selected by default** (they change data): `remember`, `write`, `edit`, `add_resource`, `add_skill`, `forget`, `set_acl` and `cancel_watch`. Check `remember` to let the model save memories, and `add_resource` to let it import web pages or attachments.
-
-`download` returns a one-time `curl` command, so it needs a client shell tool (see [Import files and skills](#import-files-and-skills) for which names count). Like upload links, the download link goes through the gateway at `public_url` plus `/gateway/downloads` by default. Set `mcp_file_links` to `direct` to pass OpenViking's own upload and download links through unchanged; they then point at the server, whose `OPENVIKING_PUBLIC_BASE_URL` (or `server.public_base_url`) must be an address the client can reach.
-
-Tools that OpenViking adds later are available by default; ongoing conversations keep the tool list they started with. Existing context profiles keep their selection.
-
-**Allow OpenViking tools** is on by default for every upstream. With both switches on, new conversations get the selected tools with an `openviking_` prefix, such as `openviking_find` and `openviking_read`. Studio describes what each tool does, and shows a read-only label only when OpenViking provides that information. Tool definitions go with every request in the conversation, and the full set adds about 3,500 input tokens, so unchecking tools nobody needs also saves tokens.
-
-> **Note**: Selected tools run without the client's permission prompts, including tools that write or delete data. Before you check a tool that changes data, make sure that is acceptable. For profiles used by chat apps, leave `forget` and `set_acl` unchecked. A tool-call notice only reports what already happened; it is not an approval step.
-
-### Tool call notices
-
-With **Show tool calls** on (the default), each OpenViking tool call the gateway runs adds a one-line notice to the reply, at the point where the call happened:
-
-```text
-> OpenViking find: "release date" — done
-```
-
-- The notice names the tool and, when it can tell, what the call works on: the search query, the URI read, listed or written, or the file or skill being imported.
-- In a streaming reply, the notice appears as soon as the call starts, so users can see the gateway working during slow calls such as imports. A non-streaming reply carries the same notices in the final message.
-- When the call ends, the outcome is added: `done` when it finished, `failed` when it returned an error, and `skipped` when the gateway refused the call without running it, for example because the round limit or token budget was used up.
-- Each notice is its own paragraph. In Chat Completions the notices are part of the reply text; in Anthropic Messages the notices for one round of calls share a text block; in Responses they share an assistant message.
-- The model never sees the notices; it gets the real calls and results. The gateway does not save notices to OpenViking.
-
-To hide the notices, turn off **Show tool calls** in the profile's **OpenViking tools** section. Like the other tool settings, the change applies to new conversations.
-
-### When tools are not offered
-
-Whether a conversation gets tools is decided at its first request that could use them (housekeeping requests such as title generation do not count) and then stays fixed, so profile changes only reach new conversations. The one exception switches tools off: the client turns out to have OpenViking tools of its own before the model has called a gateway tool, for example because an MCP server connected after the first turn.
-
-Housekeeping requests, sub-agent requests and conversations where an OpenViking plugin was detected never get OpenViking tools. If such a request sends back history in which the model used these tools, the gateway still attaches the tool definitions so the history stays valid, but refuses new OpenViking calls. The client's own tools stay available in every request.
+| `/gateway/v1/` | Model APIs and the model list |
+| `/gateway/api/v3/` | Ark-compatible clients |
+| `/gateway/api/compatible/v1/` | Ark Anthropic-compatible clients |
+| `/gateway/uploads` | Tool uploads |
+| `/gateway/downloads` | Tool downloads |
+| `/gateway/admin/` | Management API (authenticated) |
-When a request goes without tools, its detail in the request log gives the reason:
+Clients therefore use these base URLs, with `http://127.0.0.1:1933` replaced by your server's address. Per-client settings are in [Connect clients](../gateway/03-connect-clients.md#connect-clients).
-| Reason | Meaning |
+| Client | Base URL |
| --- | --- |
-| `tools_require_full_history` | A Responses request needs `store: false` and the full input history, without `item_reference`. |
-| `upstream_tools_disabled` | The upstream has **Allow OpenViking tools** off. |
-| `tools_multiple_choices` | The request asks for several choices (`n` above 1). |
-| `tools_structured_output` | The request asks for structured output (`response_format`, `text.format` or `output_config.format`). |
-| `tools_non_function` | A Chat Completions client sent a tool that is not a function. |
-| `tools_forced_choice` | `tool_choice` is `required` or names a specific tool. |
-| `deepseek_reasoning_history_required` | The upstream is DeepSeek, the request does not turn thinking off (`"thinking": {"type": "disabled"}`), and earlier replies would reach the upstream without their reasoning: either **Restore reasoning the client drops** is off, or this request cannot restore it (the conversation changed upstream, lost its memory record, or had thinking sent back as text). Standard Responses requests have no `thinking` field and count as thinking on. |
-| `tool_name_collision` | The client already has OpenViking tools, so the gateway stops offering its own for the rest of the conversation (except on a branch where the model already called them). The conditions are listed below. |
-| `tools_unavailable` | The tool list could not be loaded from OpenViking, and no earlier list was available. Start a new conversation once the connection is back. |
-| `tools_not_selected_at_session_start` | The profile has tools on, but this conversation's tool list is empty: either the profile selects no tools, or the conversation started before a gateway upgrade. Start a new conversation. |
-
-The gateway decides that the client already has OpenViking tools (`tool_name_collision`) when any of these holds:
-
-- An MCP server name (`server_label`, `mcp_server_name`, `mcp_servers[].name`) contains the word `openviking`.
-- A tool whose name ends in an OpenViking tool name also contains that word, such as `mcp__claude_ai_OpenViking__search`. A connector's `authenticate` tool does not count. Deferred tools listed by name on a line of their own count too.
-- A prefixed tool whose name ends in an OpenViking tool name, such as `mcp__ov__read`, mentions `viking://` in its definition.
-- In any request, a client tool has the same name as a gateway tool, because upstreams reject duplicate tool names.
-
-A false match also lasts for the whole conversation; start a new one.
-
-### Import files and skills
-
-The model can import material when your OpenViking service provides the import tools and the profile has them checked. Importing by URL needs nothing more. Importing a local file needs one of these:
-
-- **A client shell tool** (named like bash, shell, exec_command, terminal or run_command): the import tool returns a one-time upload link, and the model uploads the file with the client's shell tool, which goes through the client's permission prompt. Skill directories are zipped first. The link points to `public_url` plus `/gateway/uploads`, so `public_url` must be an address the client can reach, and any proxy in front must forward that path like the others. Without `public_url`, imports fail with "Set gateway.public_url for client uploads and downloads". With `mcp_file_links` set to `direct`, the link points at OpenViking Server instead.
-- **An attachment on the user message**: without a shell tool, the model can import a file attached to a user message, sent either as base64 data or as attachment text. This covers embedded `base64` and `text` data in Responses `input_file` and Anthropic `document.source`. Open WebUI usually sends only the extracted text, which is imported as a text file. Attachment URLs and provider file IDs are not fetched; to import a remote resource, use the import tool's URL parameter.
-
-Uploads are limited by `max_body_bytes` (32 MiB by default).
-
-### Limits
-
-These limits are under **Advanced settings** in the profile's **OpenViking tools** section:
-
-| Setting | API name | Default | Range | At the limit |
-| --- | --- | --- | --- | --- |
-| Rounds per request | `tool_max_rounds` | No limit | 1 or more | Further OpenViking calls are refused; the model continues with the results it has and the client's own tools. |
-| Time limit per call | `tool_timeout_seconds` | 30 s | Up to 120 s | The call returns an error to the model. |
-| Result size | `tool_result_bytes` | 65,536 bytes | 1,024–1,048,576 | The result is truncated. |
-| Total time | `tool_total_seconds` | No limit | More than 0 s | The request fails with 504 "Hidden tool request timed out". |
-| Token budget | `tool_total_tokens` | No limit | 1,024 or more | Further OpenViking calls are refused; the model continues with the results it has and the client's own tools. This is not a billing cap; the final answer can go past it. |
+| Claude Code and Anthropic SDKs | `http://127.0.0.1:1933/gateway` |
+| OpenAI-compatible clients and SDKs, including Codex, OpenCode, pi and Open WebUI | `http://127.0.0.1:1933/gateway/v1` |
+| Volcano Engine Ark and BytePlus ModelArk SDKs | `http://127.0.0.1:1933/gateway/api/v3` |
-Rounds, total time and the token budget are unlimited by default. As in an agent's own tool loop, the model keeps using OpenViking tools until it is done. In a streaming request, the user can stop the reply at any time, and the gateway stops when the client disconnects. **A non-streaming request keeps running after the client disconnects, so set Total time if your clients send non-streaming requests.** An empty field means no limit. Profiles saved before these defaults became "no limit" keep their old values (5 rounds, 120 seconds, 100,000 tokens); clear the fields to remove the limits.
+`/health` stays the server's own health check; an embedded gateway has no separate `/health`. A standalone gateway serves the same `/gateway` paths on its own port, plus two at the root:
-The token budget counts only what using OpenViking tools adds: the extra calls, their results and the model output that follows. The client's existing conversation, tool definitions and images do not count. The gateway keeps the client's limit on answer length (`max_tokens`, `max_completion_tokens` or `max_output_tokens`).
+- `/` redirects to `/studio/`, where Studio has only the gateway and connection pages.
+- `/health` returns `service: "openviking-gateway"`, `auth_mode` and `openviking_url`, and also the caller's identity when the request carries a valid OpenViking credential.
-### Failure handling
+### Public address {#public-address}
-- **A single call fails**: the model receives an error result and can carry on with its answer.
-- **The whole answer fails**: for example, the provider rejects a follow-up model request, or the model keeps calling OpenViking tools after they were refused. The client receives an error, and the request log shows **OpenViking tools failed** (`hidden_tool_loop_failed`). Streaming Responses requests end with a `response.failed` event; Chat Completions and Anthropic Messages return a `gateway_tool_error` error.
-- **One upstream keeps failing**: turn off its **Allow OpenViking tools**. Claude conversations that already used the tools may then show **Tool history unavailable** (`hidden_tool_history_unavailable`): the earlier thinking can no longer be used, and the gateway removed it. Restore the setting named in the request detail's skip reason, or start a new conversation.
-- **Retries**: a retried tool call reuses the first call's result, and an interrupted write is never repeated automatically.
+The public address, `public_url`, is the address clients use to reach the server (or the standalone gateway), written without `/gateway`; the gateway appends `/gateway` itself. It is empty by default, and then an embedded gateway uses the server's public address (`OPENVIKING_PUBLIC_BASE_URL` or `server.public_base_url`). Set it for every shared deployment, and always when a reverse proxy is in front:
-## Long conversations
+- **Embedded**: set `gateway.public_url` in `ov.conf`, then restart the server.
+- **Standalone**: set `public_url` in `gateway.conf`, or `OPENVIKING_GATEWAY_PUBLIC_URL`, then restart the gateway.
-A model's context window limits how long a conversation can get. With **Compaction** on (the default), the gateway replaces the earlier part of a conversation with a summary before the window fills up.
+Two things are built from it:
-**When it compacts.** On every new user message and every tool step, the gateway estimates how full the window is: the token usage the provider reported for this conversation's previous reply, plus an estimate for the messages added since. Without that usage (for example, streamed Chat Completions without `stream_options.include_usage`), it estimates the whole request. When the estimate reaches **Compact at** (0.9 of the window), the gateway compacts. Housekeeping, sub-agent and token-count requests never trigger compaction.
+- **Studio's setup guides**: Anthropic clients use `<public_url>/gateway`, and OpenAI-style clients `<public_url>/gateway/v1`.
+- **Upload and download links** for OpenViking tools, unless `mcp_file_links` is `direct`; see [Import files and skills](../gateway/04-openviking-tools.md#import-files-and-skills).
-**Where the window size comes from.** The gateway first looks for the model in the upstream's **Context windows** (by the model name sent to the upstream), then uses the profile's **Default context window**, and without either assumes 1,000,000 tokens. For a model with a smaller window, set one of the two; otherwise the provider rejects the conversation as too long before compaction ever starts.
+With no public address at all, the guides use the scheme and host the request reached the server with. Behind a reverse proxy this can be an internal or `http://` address, and the **Connect** tab warns **Clients may not be able to reach this address**; for a loopback address such as `127.0.0.1`, it warns **Only the gateway's own machine can use this address**.
-**How the summary is written.** The gateway sends one extra, non-streaming request to the same upstream and model. The client's system prompt, tools and thinking settings stay the same, so most of the request hits the provider's prompt cache. Settings that a plain-text summary cannot follow are removed: a forced tool choice becomes "no tool call", and structured output formats and stop sequences are dropped. The request contains the conversation up to the cut, plus an instruction for the model to summarize it for itself. The summary covers:
+## Reverse proxy and HTTPS {#reverse-proxy-and-https}
-- the user's goals and the latest request, word for word;
-- key decisions and current progress;
-- files, paths and identifiers;
-- errors and how they were fixed;
-- open items;
-- key facts from the latest tool results.
+Forward the whole site to the server (embedded) or to the gateway (standalone); no path-based routing is needed. With Caddy:
-An earlier summary is folded into the new one. The summary is plain text of at most **Summary length** (8,000) tokens. Thinking counts against the output cap, and some models (such as DeepSeek V4.1) think by default even when the request has no thinking settings, so the gateway always allows 16,000 tokens of output on top of the summary length; when the client sets an explicit thinking budget, it adds that budget instead. The provider bills this request like any other.
+```caddyfile
+ov.example.com {
+ reverse_proxy 127.0.0.1:1933 {
+ flush_interval -1
+ }
+}
+```
-**What the model receives afterwards.** Where the cut falls depends on the request:
+Whatever proxy you use, it needs these settings:
-- On a new user message, the cut falls right before that message. The model receives the system and developer messages, the summary as one user message, and the new message.
-- On a tool step, the cut falls after the latest tool result, and the model continues the task from the summary.
+| Setting | Value | Why |
+| --- | --- | --- |
+| Response buffering | Off | Streamed output arrives in real time |
+| Request body size | At least 32 MiB | The gateway's own default limit for requests and uploads; long conversations send their full history ([Side effects](../gateway/05-long-conversations.md#side-effects)) |
+| Read timeout | At least 600 seconds | The gateway waits up to 600 seconds for a provider by default |
+| Logging of `/gateway/uploads` and `/gateway/downloads` | Leave out the query strings | They carry one-time tokens |
-The summary message starts by saying that the gateway replaced the earlier part of the conversation and that the user did not write it. It ends with the conversation's opening gateway note and user profile, so these survive compaction. Every later request that resends this history, including housekeeping and token-count requests, gets the same replacement; sub-agents usually send their own separate history and are not affected. Each compaction costs one provider cache miss at the cut, and caching works normally after that.
+Set up authentication and the [public address](#public-address) before you expose the service; see [Public access](12-public-access.md).
-**Nothing before the cut is kept word for word**, not even the latest turns. The model's earlier replies and their thinking depend on the history being replaced, and keeping only part of it would break Claude's thinking signatures. Everything generated after the cut is sent as usual, thinking included.
+## Keys and credentials {#keys-and-credentials}
-**Finding what was cut.** The conversation itself is still saved in OpenViking. When **Save conversations** is on and the conversation has the `openviking_grep` and `openviking_read` tools, the summary ends with directions: the conversation's OpenViking session (`viking://user/<user_id>/sessions/<session_id>/`), where its messages are stored, and how to search them (grep the session for a specific pattern to get line numbers, then read the lines around a match). When a cut falls in the middle of a turn, the part before it is saved to OpenViking right away, so the model can search it within the same turn.
+The gateway involves four keys, each with one job:
-**When compaction fails.** If the summary request fails, or the reply calls a tool, is empty or is cut off at the length limit, the gateway sends the full history instead and does not try to compact this conversation again for 60 seconds. The request detail shows **Compaction failed** with the reason. If usage is still at or above **Compact at** after the summary (for example because the system prompt and tools alone fill most of the window), the gateway keeps the summary and also waits 60 seconds before trying again, with the reason `still_over_threshold`.
+| Key | Purpose | Where it is used |
+| --- | --- | --- |
+| OpenViking API key | Signs in to Studio; decides which account and user memory is read and written as | `X-API-Key` or `Authorization: Bearer` on management requests |
+| Gateway key (`ovgw_…`) | Connects a client; each one binds a user, a context profile and a set of upstreams ([Gateway keys](../gateway/09-gateway-keys.md#gateway-keys)) | The client's API key field |
+| Gateway management key (optional) | Restricts who can change upstreams and context profiles | `gateway.management_key`; the `X-OpenViking-Gateway-Management-Key` request header |
+| Upstream API key | Calls the model provider ([Credentials](../gateway/07-upstreams.md#credentials)) | The upstream editor |
-**No Working Memory summaries.** The summary comes from the conversation's own model, not from OpenViking's session summaries. New OpenViking sessions that the gateway creates have Working Memory turned off: commits still archive messages and extract memories, but no session summary is written.
+The gateway has no encryption key of its own: it encrypts its local storage with OpenViking's encryption settings; see [Encryption](#encryption).
-**The memory budget starts over.** **Budget per context window** resets after each compaction, so memory added before the cut may be added again.
+### Gateway management key {#gateway-management-key}
-**The client still sends the full history.** After the gateway compacts, the client keeps sending its full history, and the gateway replaces the part before the cut on every request. The client sees small usage numbers, so clients that compact by usage rarely compact on their own, and a very long session can eventually exceed `max_body_bytes`. When the client compacts or edits its history, the gateway saves the new history to a new OpenViking session; if the search tools are available, the opening gateway note of the new history tells the model where the earlier sessions are.
+The gateway management key is an optional deployment secret that restricts who can change [upstreams and context profiles](15-gateway.md#key-terms). It is not set by default, so every signed-in user in an account can add and change that account's upstreams and context profiles. Once it is set, only requests that carry it can change them, OpenViking admins and root included. It does not limit who can sign in, or whether users can issue gateway keys for themselves.
-Each request's detail in the request log shows how full the context window was, whether earlier history was replaced, and the size and time of a newly written summary.
+What read-only users can still see and do in Studio is in [Who can change what](../gateway/06-manage-in-studio.md#who-can-change-what); the full rules, including the management API, are in the [access matrix](../api/25-gateway.md#credentials-and-account-scope).
-### Experimental: agent-managed context windows
+**Treat it as a deployment secret.** The management key also works on its own, without an OpenViking API key: with `account_id` it can read, create, change and delete upstreams and context profiles in any account, including pointing an upstream at a different provider address. It cannot read memory or logs, or issue gateway keys. Share it only with the people who maintain upstreams.
-With **Agent-managed context windows** on (off by default), the model decides when to start a fresh context window and writes its own hand-off notes, instead of waiting for the gateway's summary. The setting only works in conversations that get [OpenViking tools](#openviking-tools); other conversations are compacted as usual. When compaction is on, it remains the fallback if the model never starts a new window.
+To set one:
-The model sees:
+- **`openviking-server init`** (embedded): for a remote deployment, answer no to **Allow users to configure their own gateway upstreams?**. Init generates a value starting with `ovgm_`, prints it and saves it to `gateway.management_key` in `ov.conf`.
+- **`openviking-gateway init`** (standalone): answer yes to **Require a management key to change upstreams and profiles?**. Init generates an `ovgm_` value, prints it once and saves it to `management_key` in `gateway.conf`.
+- **Studio** (embedded, root): the confirmation dialog of **Enable gateway** has a checkbox, **Only people with the gateway management key can change upstreams and context profiles**, which is off by default. If you check it, Studio generates an `ovgm_` value, saves it to `gateway.management_key` in `ov.conf` along with `gateway.enabled: true`, and shows it once.
+- **By hand**: use at least 32 characters, for example from `openssl rand -base64 32`. Put it in `management_key`, or set the `OPENVIKING_GATEWAY_MANAGEMENT_KEY` environment variable, which overrides the file in both forms; see [Configuration reference](../gateway/13-configuration.md#configuration-reference).
+- **Compose and Helm**: Compose passes `OPENVIKING_GATEWAY_MANAGEMENT_KEY` into the container; Helm reads it from the `management-key` entry of the Secret named in `gateway.existingSecret`. See [Docker Compose](#docker-compose) and [Helm](#helm).
-- **Two extra tools.** They are not in the profile's **Tools** list; only this setting controls them.
- - `openviking_new_context(reason, notes, next_steps)` starts a new window; `next_steps` is optional. It must be the only tool call in its round. Called together with other tools, every call in the round returns an error and the window is not reset. It also returns an error if the gateway already replaced the context at the same point in this request (for example, it just compacted).
- - `openviking_context_remaining()` returns the window number, estimated tokens used and left, the user turns in this window, the time since the user's previous message, and a one-line recommendation.
-- **One more line in the opening gateway note**, telling the model that it manages its own context windows with these two tools.
-- **A status line**: after each new user message, the memory block ends with `[context-status] window wN · ~X/Y tokens (P%) · T since your previous message`.
-- **Two reminders**: when the window reaches **Soft reminder at** (0.7), the gateway reminds the model once to start a new window after the current step, with notes that keep the exact paths, line numbers and values it will need. At **Hard reminder at** (0.85), it tells the model to start a new window now, and repeats on every step until the model does or compaction takes over. Reminders are attached to the new user message, or to the tool result during a tool step.
+There is no command-line flag for the management key, because flags show up in process lists and shell history. Setting, changing or removing it takes a restart. It does not revoke issued gateway keys or change existing upstreams and context profiles.
-When the model calls `openviking_new_context`, the gateway replaces the conversation so far with a window header, and the model carries on in the same reply. The header contains, in order: that this is window N started by the model and that the user did not write it; the reason, notes and next steps; the user's latest message word for word; how to search earlier windows (under the same conditions as for compaction); and the conversation's opening gateway note. Later requests rebuild the same window from the client's history. The content before the reset is saved to OpenViking right away and stays searchable. The reason and notes appear only in the header and are not saved to OpenViking. Each reset costs one provider cache miss but needs no summary request.
+#### Lost the management key {#lost-the-management-key}
-Each request's detail in the request log shows the window number, whether the model started a new window, and which reminder it received. How well this works depends on the model, and the behavior may change in later releases.
+If nobody has the [gateway management key](#gateway-management-key), look where the gateway reads it from, in this order:
-## Security and data
+1. The `OPENVIKING_GATEWAY_MANAGEMENT_KEY` environment variable, which wins over the files. Compose usually sets it in the `.env` file next to `docker-compose.yml`; Helm reads it from the `management-key` entry of the Secret named in `gateway.existingSecret`.
+2. Otherwise, `gateway.management_key` in `ov.conf` (embedded) or `management_key` in `gateway.conf` (standalone). A value written as `$VAR` lives in that environment variable.
-**Isolation by user.** Each gateway key is bound to one OpenViking user. The gateway searches memory, saves conversations and calls tools with that user's own OpenViking key, so it can never do more than the user can, and each user's conversation state is kept separate. Sessions and memories always live in OpenViking; the gateway keeps only the state it needs to continue conversations.
+On an embedded gateway, root can also open `ov.conf` in Studio under **Settings** → **Server configuration** → **File editor**. Keys generated by `openviking-server init` and by Studio's **Enable gateway** are stored there in plain text.
-**What the gateway stores.** `storage_path` holds two SQLite databases. Only the system user that runs the gateway can read the files, and with [encryption](#encryption) on, every stored value is encrypted as well:
+If you can't recover it, replace it:
-- `management.sqlite3`: upstreams, context profiles, gateway keys, request logs, and which upstream created each Responses response. This includes upstream API keys, header values and the OpenViking keys bound to gateway keys, which are in plain text when encryption is off; gateway keys themselves are stored only as a hash and a short prefix.
-- `kernel.sqlite3`: the state of each conversation, including the memory text added to messages (needed for replay), OpenViking tool rounds, summaries and conversation text waiting to be saved.
+1. Generate a new value of at least 32 characters, for example with `openssl rand -base64 32`.
+2. Put it in the same place. An empty environment variable does not clear the value in the file; unset the variable instead.
+3. Restart. With Compose, a change in `.env` takes effect only after `docker compose up -d`, not `docker compose restart`.
+4. In Studio, choose **Enter gateway management key** and paste the new value. Issued gateway keys, upstreams and context profiles are unaffected.
-**What request logs record.** Metadata only: request type, model, status, upstream, a hash of the conversation ID, token counts, memory counts and timing, saving status and issues. Never message text, recalled memory, tool arguments or results, or any key. The gateway writes no HTTP access log, and its error messages never repeat submitted values.
+## Encryption {#encryption}
-**What providers see.** Every upstream receives the full model input, including memory the gateway added and OpenViking tool results. Only add providers you trust with that data.
+The gateway encrypts stored credentials and conversation state with OpenViking's own encryption (see the [Encryption guide](08-encryption.md)). When encryption is off or not configured, the gateway stores everything in plain text, protected only by file permissions.
-**Retention.** A cleanup job runs every hour:
+- **Embedded**: the gateway follows the server's `encryption` section in `ov.conf`. There is nothing to set for the gateway itself.
+- **Standalone**: add an `encryption` block to `gateway.conf`. It has exactly the same fields as the `encryption` section of `ov.conf`, for example:
-| Data | Kept for | Setting |
-| --- | --- | --- |
-| Conversation state | 30 days after last use | `session_ttl_days` |
-| Request logs | 30 days | `log_retention_days` |
-| Which upstream created each Responses response | 30 days | `response_ttl_seconds` |
-| Sessions and memories in OpenViking | OpenViking's own rules | — |
+ ```json
+ {
+ "openviking_url": "https://ov.example.com",
+ "encryption": {
+ "enabled": true,
+ "provider": "local",
+ "local": { "key_file": "~/.openviking/master.key" }
+ }
+ }
+ ```
-**Deleting data.** Revoking a gateway key, or the bound OpenViking key becoming invalid, does not delete user data. There are three ways to delete it:
+Changing the setting later:
-- An account admin or root uses **Delete this user's gateway data…** in Studio, or calls `DELETE /gateway/admin/users/{user_id}/data`. This revokes the user's gateway keys and deletes their conversation state and logs, including content not yet saved.
-- Root calls `DELETE /gateway/admin/account/data?account_id=<account>` to delete all gateway data of an account.
-- In an embedded deployment, deleting a user or account in OpenViking also deletes the matching gateway data. A standalone deployment has no such step; its data stays until it is explicitly deleted or expires.
+- **Turning encryption on** is safe: values written before stay readable, and new writes are encrypted.
+- **Turning it off, or switching to a different encryption root key**, makes the encrypted values unreadable, so keep the settings the data was written with.
+- **Losing the encryption root key** makes the gateway's databases unreadable. Back it up as the Encryption guide describes.
-None of this touches memories and sessions already stored in OpenViking. The reverse also holds: after you delete a memory in OpenViking, the copy the gateway saved for an ongoing conversation is still replayed until that conversation expires. To clear it now, delete the user's gateway data.
+Data written by the v0.5 gateway, which used its own key, is converted on the first start; see [Migration](#migration).
-**Access control.**
+## Scaling {#scaling}
-- Clients authenticate with gateway keys, sent in `Authorization: Bearer` or `x-api-key`. Keys can be revoked at any time.
-- The management key only controls changes to upstreams and context profiles. It grants no access to memory or logs and no right to issue keys; see the [access matrix](../api/25-gateway.md#credentials-and-account-scope).
-- Account admins can issue gateway keys for any user in their account (when OpenViking stores only key hashes, the user has to supply their key). A gateway key lets its holder recall memory and call tools as that user, so the right to issue keys amounts to reading the memory of every user in the account. Give it only to admins you trust.
-- `/gateway/uploads` needs no gateway key. Each upload is authorized by a one-time token signed by OpenViking, and the gateway only forwards it to OpenViking's upload endpoint. Keep its query string out of proxy logs.
-- `X-OpenViking-*` headers, client credentials and cookies are never forwarded to upstreams.
+One storage directory serves one deployment on one host, and an embedded and a standalone gateway must not share a directory. An embedded gateway follows the server's worker setting; a standalone gateway takes `workers`, from 1 to 64. For load balancing, failover or rate limiting across providers, add a service such as LiteLLM as an upstream.
-**Backups.** Back up `storage_path`, including both databases and their `-wal` and `-shm` files; with encryption on, also keep a backup of OpenViking's root key. For a consistent copy, stop the gateway first, or use SQLite's online backup (`sqlite3 kernel.sqlite3 ".backup kernel.backup.sqlite3"`, and the same for `management.sqlite3`). What losing each file means:
+## Monitoring and routine checks {#monitoring}
-- **`kernel.sqlite3` lost**: memory added earlier cannot be replayed. Each ongoing conversation takes one provider cache miss, Claude conversations lose their earlier thinking once (**Memory record missing**, `missing_injection_record`), and turns not yet saved are lost.
-- **`management.sqlite3` lost**: upstreams, context profiles, keys and request logs are gone. Set them up again and issue new keys.
-- **Root key lost** (encryption on): the encrypted values in both databases cannot be read. Start again with an empty `storage_path`.
+The gateway exports no metrics such as Prometheus and writes no HTTP access log. Check its state on Studio's [Overview and Requests](../gateway/10-overview-and-requests.md#overview) tabs, or through the management API's `/gateway/admin/overview` and `/gateway/admin/logs`.
-## Day-to-day operations
+### Routine checks {#day-to-day-operations}
-- **Watch the first-call cache hit rate.** It reflects prompt caching across turns and should stay close to what the provider reaches without the gateway. The **Within-turn cache hit rate** covers tool steps and is normally high. If the first-call rate drops noticeably, see [The first-call cache hit rate dropped](#the-first-call-cache-hit-rate-dropped).
-- **Use the request log to look into a single request.** Filter by new messages, tool steps or issues, then expand a row to see the recall result, saving status and why OpenViking tools were left out; see [Requests and overview](#requests-and-overview).
-- **Set the public address.** Set `public_url` to the address clients use, without `/gateway`, so client settings and upload links stay correct behind a reverse proxy.
-- **Back up regularly.** Back up the gateway's storage directory and, with encryption on, OpenViking's root key; see **Backups** under [Security and data](#security-and-data).
+- **Liveness:** `/health`, which is the server's health check in an embedded deployment and the gateway's own in a standalone one.
+- **Gateway health:** the **First-call cache hit rate** on the Overview tab ([what it means](../gateway/10-overview-and-requests.md#overview)). If it drops noticeably, see [The first-call cache hit rate dropped](../gateway/12-troubleshooting.md#the-first-call-cache-hit-rate-dropped).
+- **A single request:** expand its row on the Requests tab; see [Requests](../gateway/10-overview-and-requests.md#requests).
+- **Public address:** `public_url` still matches the address clients use; see [Public address](#public-address).
+- **Backups:** the storage directory and, with encryption on, the encryption root key; see [Backups and recovery](../gateway/11-security-and-data.md#backups).
-### Upgrades
+## Upgrades {#upgrades}
-- Read the release notes before you upgrade. If a new gateway version cannot read the old storage format, it stops at startup with `Unsupported gateway schema`; see [The gateway does not start](#the-gateway-does-not-start).
-- A standalone gateway needs OpenViking Server `min_server_version` (0.4.16) or later. With an older server, memory search and saving stop and no keys can be issued. When you upgrade the two separately, upgrade OpenViking first, then the gateway. An embedded gateway ships with its server and skips this check.
+- Read the release notes before you upgrade. If a new gateway version cannot read the old storage format, it stops at startup with `Unsupported gateway schema`; see [The gateway does not start](../gateway/12-troubleshooting.md#the-gateway-does-not-start).
+- A standalone gateway needs OpenViking Server `min_server_version` (0.4.16) or later. With an older server, no keys can be issued and saving retries fail with `openviking_version_mismatch`; memory search may also fail, shown as `openviking_http_<status>`. When you upgrade the two separately, upgrade OpenViking first, then the gateway. An embedded gateway ships with its server and skips this check.
- To move from the sidecar or an older standalone gateway, see [Migration](#migration).
-### Monitoring
-
-The gateway exports no metrics such as Prometheus and writes no HTTP access log. Check its state on Studio's Overview and Requests tabs, or through the management API's `/gateway/admin/overview` and `/gateway/admin/logs`. Use `/health` for liveness: the server's health check in an embedded deployment, and the gateway's own in a standalone one.
-
-## Design trade-offs
-
-The table explains why the gateway's main design choices were made and what they cost, so you can judge whether it fits your setup:
-
-| Design | Choice and reason | Cost |
-| --- | --- | --- |
-| Where it plugs in | On the model call path instead of a plugin in every agent: clients that cannot install plugins can use it, and provider keys are managed in one place. | It cannot see the working directory; keeping projects' memory apart means a different OpenViking user per project. |
-| Who runs the tools | The gateway runs OpenViking tools during the reply, stores the rounds and replays them unchanged on the next turn: even clients with no tools and no MCP support get a model that uses memory on its own. | No per-call approval; clients must send the full history every turn; admins need to narrow the tool list and limits. |
-| Where memory goes | At the end of the newest user message, not in the system prompt: one changed character in the system prompt invalidates the whole cache, while appending at the end and replaying unchanged keeps the prefix stable. | The gateway must reliably record the exact text of every addition; a lost record costs one cache miss. |
-| When turns are saved | One turn behind: only when the next message brings the previous turn back is it clear the user kept it. | The last turn is saved only after **Save the latest reply after** (10 minutes by default). |
-| Long conversations | The gateway has the same model write the summary: only the gateway knows what the model actually received, and the summary request mostly hits the cache. | The turn that triggers compaction costs one extra, billed model call; text before the cut is no longer sent to the model. |
-| Local state | SQLite on one host, with no Postgres or Redis dependency, which suits self-hosting. | The gateway cannot fail over between machines and is a single point on the model call path. |
-| Client identity | The gateway issues its own keys instead of using OpenViking keys directly: they can be revoked on their own, and one person's clients can use different context profiles. | The gateway has to store users' OpenViking keys, so turn on encryption; a leaked gateway key exposes that user's memory. |
-
-## Configuration reference
-
-Both forms use the same fields; they differ only in where the file lives and how you create it:
+## Migration from earlier releases {#migration}
-- **Embedded**: the `gateway` section of `ov.conf`, written by `openviking-server init`. Host, port and workers come from the server.
-- **Standalone**: the root of `gateway.conf`, with no `gateway` wrapper, written by `openviking-gateway init`. When `--config` or `OPENVIKING_GATEWAY_CONFIG_FILE` is set, it must point to an existing file; otherwise the gateway reads the first of `~/.openviking/gateway.conf` and `/etc/openviking/gateway.conf` that exists. `OPENVIKING_CONFIG_FILE` only selects the server's configuration.
-
-| Field | Form | Default | Meaning |
-| --- | --- | --- | --- |
-| `enabled` | Embedded | `false` | Turns the gateway on inside the server |
-| `openviking_url` | Standalone | — (required) | Address of the OpenViking Server |
-| `host` | Standalone | `127.0.0.1` | Listen address |
-| `port` | Standalone | `1935` | Listen port |
-| `workers` | Standalone | `1` | Worker processes, 1–64 |
-| `encryption` | Standalone | not set (plain text) | Same fields as the `encryption` section of `ov.conf`; see [Encryption](#encryption). Embedded gateways use the server's section |
-| `public_url` | Both | empty | The external address clients use, without `/gateway` (the gateway appends it); when empty, an embedded gateway uses the server's public address; with neither, setup guides use the request's origin, and MCP file uploads and downloads do not work unless `mcp_file_links` is `direct` |
-| `mcp_file_links` | Both | `proxy` | How links from the MCP upload and download tools reach the client: `proxy` rewrites them to `public_url` plus `/gateway/uploads` or `/gateway/downloads` and needs `public_url`; `direct` passes OpenViking's links through unchanged and needs the server's `OPENVIKING_PUBLIC_BASE_URL` (or `server.public_base_url`) to be reachable by the client |
-| `storage_path` | Both | `~/.openviking/gateway` | Local storage directory |
-| `management_key` | Both | empty | Optional gateway management key, at least 32 characters |
-| `min_server_version` | Both | `0.4.16` | Lowest OpenViking Server version a standalone gateway accepts |
-| `session_ttl_days` | Both | `30` | Days of inactivity before a conversation expires; minimum 1 |
-| `response_ttl_seconds` | Both | `2592000` | Seconds to remember which upstream created a Responses response; minimum 60 |
-| `log_retention_days` | Both | `30` | Days to keep request logs; minimum 1 |
-| `max_body_bytes` | Both | `33554432` | Size limit for requests and uploads; minimum 1,024 bytes |
-| `upstream_timeout_seconds` | Both | `600` | Timeout for provider requests; must be above 0 |
-| `health_interval_seconds` | Both | `60` | Seconds between OpenViking status checks; minimum 1 |
-
-**Environment variables override the file.** The rule is the same in both forms: a non-empty `OPENVIKING_GATEWAY_<FIELD NAME IN UPPER CASE>` variable, such as `OPENVIKING_GATEWAY_PUBLIC_URL` or `OPENVIKING_GATEWAY_MANAGEMENT_KEY`, wins over the value in the file; an empty variable counts as unset. A value in the file can also be a `"$VAR"` reference. The `encryption` block can only be set in the file. Containers usually need no file: set the fields they need as variables.
-
-URLs must be HTTP(S) and contain no credentials, query or fragment. Unknown fields fail validation, except removed ones, which are ignored with a startup warning: `encryption_key_env`, and in `ov.conf` also the v0.5 fields listed in [Migration](#migration).
-
-**Context profile settings.** Studio label first, then the name in the management API (which calls context profiles `policies`):
-
-| Studio label | API name | Default | Range | Meaning |
-| --- | --- | --- | --- | --- |
-| Name | `name` | `Default` | | Display name. |
-| Recall memory | `recall` | `true` | | Search memory for each new user message. |
-| User profile at conversation start | `profile` | `true` | | Provide the user profile when a conversation starts, independently of recall. |
-| Opening context budget | `profile_max_tokens` | `4000` | 0–32,000 | Separate budget for the profile and catalogs; 0 leaves them out. Catalogs need the `read` tool. |
-| Show recall summary | `show_recall` | `false` | | Start the reply with a summary of what OpenViking added, or why recall failed. The model never sees it. |
-| Sources | `context_types` | `memory`, `resource`, `skill` | At least one | What to search: memories, resources, skills. |
-| Budget per message | `max_tokens` | `1600` | 64–32,000 | Most tokens added to one message. |
-| Budget per context window | `session_max_tokens` | `30000` | ≥ 0 | Most tokens added within one context window; resets after each compaction. 0 turns recall off. |
-| Relevance threshold | `score_threshold` | `0.35` | 0–1 | Lowest relevance score accepted. |
-| Time limit | `recall_timeout` | `2` (seconds) | Up to 30 | How long a search may take before the message goes on without memory. |
-| Query length | `query_max_chars` | `8000` | 3–32,000 | Characters of the message used as the search query. |
-| Limit by category | `quotas` | `{}` (off) | Keys: `events`, `entities`, `preferences`, `experiences`, `resources`, `skills` | Most entries per category; only categories above 0 are searched. |
-| Save conversations | `capture` | `true` | | Save finished turns to OpenViking. |
-| Save the latest reply after | `idle_seconds` | `600` (seconds) | ≥ 1 | Quiet time before the last turn is saved and the session committed. |
-| Commit after | `commit_tokens` | `20000` | ≥ 1 | Tokens waiting in the session that trigger a commit. |
-| Keep recent messages | `keep_recent_messages` | `10` | 0–1,000 | Messages left in the session after a commit. |
-| Compaction | `compaction` | `true` | | Replace the earlier part of a conversation with a summary near the context window. |
-| Compact at | `compaction_threshold` | `0.9` | 0.5–0.98 | Share of the context window that triggers compaction. |
-| Summary length | `summary_max_tokens` | `8000` | 1,000–32,000 | Most tokens in one summary. |
-| Default context window | `context_window` | Not set (1,000,000 assumed) | ≥ 1,024 | Window used when the upstream does not list the model. |
-| Agent-managed context windows | `agent_windows` | `false` | | Experimental. Let the model start new context windows itself; needs OpenViking tools. |
-| Soft reminder at | `window_soft_ratio` | `0.7` | 0.3–0.95, below `window_hard_ratio` | Share of the window at which the model is reminded to start a new window soon. |
-| Hard reminder at | `window_hard_ratio` | `0.85` | 0.4–0.97 | Share of the window at which the model is told to start a new window now. |
-| OpenViking tools | `gateway_tools` | `true` | | Offer OpenViking tools for Chat Completions, full-history Responses and Anthropic Messages. |
-| Unchecked tools | `disabled_tools` | The 8 tools that change data; see [Choose tools](#choose-tools) | OpenViking tool names, without `openviking_` | Tools new conversations do not get; every other available tool is offered, including ones added later. API requests that omit the field get the default list; an empty list with the main switch on offers every available tool. |
-| Show tool calls | `show_tool_calls` | `true` | | Add a one-line notice to the reply for each OpenViking tool call. |
-| Rounds per request | `tool_max_rounds` | `null` (no limit) | 1 or more | See [Limits](#limits). |
-| Time limit per call | `tool_timeout_seconds` | `30` | Up to 120 | |
-| Result size | `tool_result_bytes` | `65536` | 1,024–1,048,576 | |
-| Total time | `tool_total_seconds` | `null` (no limit) | More than 0 | |
-| Token budget | `tool_total_tokens` | `null` (no limit) | 1,024 or more | |
-
-**Upstream settings:**
-
-| Studio label | API name | Default | Meaning |
-| --- | --- | --- | --- |
-| Name | `name` | | Display name. |
-| Protocol | `protocol` | | `anthropic` (Anthropic Messages), `chat` (Chat Completions) or `responses` (Responses). |
-| Provider | `vendor` | `generic` | `generic`, `anthropic`, `openai`, `deepseek`, `ark` (Volcano Engine Ark) or `byteplus` (BytePlus ModelArk). Studio offers only the protocols a provider supports; the API accepts any pair. |
-| Base URL | `base_url` | | Provider address; defaults and path rules are in [Upstreams](#upstreams). |
-| Append protocol endpoint path | `append_endpoint_path` | `true` | Appends the selected protocol's path; when false, uses `base_url` as the complete request URL. |
-| Send the key as | `key_header` | `authorization` | `authorization` (Bearer), `api-key` or `x-api-key`. Ignored when `base_url` contains `{api_key}`. |
-| Who provides the API key | `auth_mode` | `managed` | `managed` (the gateway holds the API key) or `passthrough` (each client sends its own key). |
-| API key | `api_key` | | Write-only; see [Credentials](#credentials). |
-| Extra headers | `headers` | `{}` | Write-only; see [Credentials](#credentials). |
-| Models | `models` | `[]` | Model names served; empty accepts any name. |
-| Model aliases | `aliases` | `{}` | Name clients use → model sent to the upstream. |
-| Context windows | `context_windows` | `{}` | Model → tokens, each at least 1,024. |
-| Priority | `priority` | `0` | Higher values win for new conversations. |
-| Enabled | `enabled` | `true` | A turned-off upstream receives no requests. |
-| Allow OpenViking tools | `allow_gateway_tools` | `true` | Whether OpenViking tools can be offered through this upstream. |
-| Restore reasoning the client drops | `replay_reasoning` | `null` (follows the provider) | Puts reasoning the client dropped back on earlier replies. `null` means on for `deepseek`, `ark` and `byteplus` and off for other providers; `true` or `false` overrides that. Studio saves `null` while the switch matches the provider default. |
-| This key is a Coding Plan or subscription key | `coding_plan` | `false` | Rejects requests to this upstream unless allowed. |
-| Allow this plan through the gateway | `allow_coding_plan` | `false` | Allows use of a key marked as Coding Plan. |
-| Minimum cacheable prompt | `cache_min_tokens` | `1024` | Ark and ModelArk only; affects how cache eligibility is reported. |
-
-Gateway key fields, every management operation, the access rules and the error reasons are in the [Management API](../api/25-gateway.md).
-
-## Migration
-
-These steps apply when you move from the sidecar or standalone gateway of earlier releases to the embedded gateway.
+These steps apply when you move from the sidecar or standalone gateway of earlier releases to the embedded gateway. Steps 4 and 7 are detailed in the tables after the list.
1. **Back up first.** Back up `storage_path` (both databases and `encryption.key`, if it is there). Stop the old gateway process or sidecar before you enable the embedded gateway.
-2. **Remove old fields.** Delete `host`, `port`, `workers`, `url`, `openviking_url`, `admin_token_env` and `encryption_key_env` from the `gateway` section of `ov.conf`. The server ignores them and logs a warning at startup, so an old `ov.conf` still starts, but clean them up. `openviking-server init` → **Update gateway** removes them for you. To keep running the gateway on its own instead, run `openviking-gateway init`, or move its settings to a separate `gateway.conf`, without the `gateway` wrapper and `enabled`. The standalone command no longer takes `--openviking-url`, `--host`, `--port`, `--workers` or `--storage-path`; set them in `gateway.conf` or as environment variables.
+2. **Remove old fields.** Delete `host`, `port`, `workers`, `url`, `openviking_url`, `admin_token_env` and `encryption_key_env` from the `gateway` section of `ov.conf`. The server ignores them and logs a warning at startup, so an old `ov.conf` still starts, but clean them up; `openviking-server init` → **Update gateway** removes them for you.
+
+ To keep running the gateway on its own instead, run `openviking-gateway init`, or move its settings to a separate `gateway.conf`, without the `gateway` wrapper and `enabled`. The standalone command no longer takes `--openviking-url`, `--host`, `--port`, `--workers` or `--storage-path`; set them in `gateway.conf` or as environment variables.
3. **Fix the public address.** Point `public_url` at the server's public address, without `/gateway`, or remove it. The old quick start set it to `http://127.0.0.1:1935`, which the embedded gateway no longer listens on, so setup guides and upload links would point at nothing. When `public_url` points at another port, `openviking-server init` → **Update gateway** offers to clear it.
-4. **Update client addresses and deployment config.** Every gateway URL now lives under `/gateway`, so clients change both the port and the path: `http://host:1935/v1` becomes `http://host:1933/gateway/v1`, a Claude Code `ANTHROPIC_BASE_URL` of `http://host:1935` becomes `http://host:1933/gateway`, and Ark SDKs move to `http://host:1933/gateway/api/v3`. The old paths are not served any more. Scripts that call the management API move from `/api/v1/admin/gateway/...` to `/gateway/admin/...`. Remove the old 1935 Service and Ingress routes, the Compose `gateway` service and profile, and the Helm sidecar settings `gateway.workers`, `gateway.port` and `gateway.resources`. 1935 is still the standalone default port, and a standalone gateway uses the same `/gateway` paths.
-5. **Let the first start convert stored data.** The v0.5 gateway encrypted its data with its own key. On the first start, the new gateway (embedded or standalone) decrypts it with that key and rewrites it under the current [encryption](#encryption) settings, or in plain text when encryption is off, so turn on OpenViking encryption before this start if you want the data to stay encrypted. The old key is read from the `OPENVIKING_GATEWAY_ENCRYPTION_KEY` environment variable, or from `encryption.key` in `storage_path`. `encryption_key_env` is ignored: if you used it to point at another variable, export the key as `OPENVIKING_GATEWAY_ENCRYPTION_KEY` for this start. If old encrypted data exists and neither source has the key, the gateway refuses to start and the error names both places. With Helm, keep the `encryption-key` entry in the `existingSecret` Secret for the upgrade release only. After a successful start the old key is never read again, so you can remove the variable, the Secret entry and `encryption.key`.
-6. **Remove the shared admin token.** `OPENVIKING_GATEWAY_ADMIN_TOKEN` is **not** used as a management key. To restrict who can change upstreams and context profiles, set `management_key` explicitly.
-7. **Check upstream addresses.** On first start, the gateway rewrites stored Base URLs once, so each upstream keeps calling the same address as before the upgrade:
- - Ark and ModelArk Chat Completions and Responses upstreams with only a domain get `/api/v3` added.
- - Other Chat Completions and Responses upstreams whose path does not end in a version segment such as `/v1` or `/v4` get `/v1` added. This covers bare domains (`https://api.deepseek.com` → `https://api.deepseek.com/v1`) and addresses with a path prefix (`https://openrouter.ai/api` → `https://openrouter.ai/api/v1`, or a self-hosted proxy under `/litellm`).
- - Ark and ModelArk Anthropic upstreams with only a domain get `/api/compatible` added.
- - Anthropic Base URLs ending in `/v1` lose the `/v1`.
-
- Addresses that already end in another version segment are left alone, such as Zhipu's `https://open.bigmodel.cn/api/paas/v4`. Before the upgrade it became `…/v4/v1` and failed; now it works as entered. New and edited upstreams follow the rules in [Upstreams](#upstreams), and an Anthropic Base URL ending in `/v1` is rejected.
+4. **Update client addresses and deployment config.** Every gateway URL now lives under `/gateway`, so clients change both the port and the path, and the old paths are not served any more; see [New addresses](#new-addresses). Remove the old 1935 Service and Ingress routes, the Compose `gateway` service and profile, and the Helm sidecar settings `gateway.workers`, `gateway.port` and `gateway.resources`.
+5. **Let the first start convert stored data.** The v0.5 gateway encrypted its data with its own key. On the first start, the new gateway (embedded or standalone) decrypts it with that key and rewrites it under the current [encryption](#encryption) settings, or in plain text when encryption is off, so turn on OpenViking encryption before this start if you want the data to stay encrypted.
+
+ The old key is read from the `OPENVIKING_GATEWAY_ENCRYPTION_KEY` environment variable, or from `encryption.key` in `storage_path`. `encryption_key_env` is ignored: if you used it to point at another variable, export the key as `OPENVIKING_GATEWAY_ENCRYPTION_KEY` for this start. If old encrypted data exists and neither source has the key, the gateway refuses to start and the error names both places. With Helm, keep the `encryption-key` entry in the `existingSecret` Secret for the upgrade release only. After a successful start the old key is never read again, so you can remove the variable, the Secret entry and `encryption.key`.
+6. **Remove the shared admin token.** `OPENVIKING_GATEWAY_ADMIN_TOKEN` is **not** used as a management key. To restrict who can change upstreams and context profiles, set `management_key` explicitly; see [Gateway management key](#gateway-management-key).
+7. **Check upstream addresses.** On the first start, the gateway rewrites stored Base URLs once, so each upstream keeps calling the same address as before the upgrade; see [How stored upstream addresses change](#upstream-address-rewrite). Use **Test** on the Upstreams tab to confirm each one still answers.
8. **Note the changes to logs and revocation.** Request logs gain a user column; older records have no user and appear only in account admin and root views. Revoking a key no longer deletes the user's data; explicit deletion and retention still apply.
-## Troubleshooting
+### New addresses {#new-addresses}
-### Common symptoms
+Replace `host` with your server's address:
-| Symptom | Cause | What to do |
+| What | Before | After |
| --- | --- | --- |
-| A conversation gets no recall and is not saved | An OpenViking plugin was detected, and the gateway left recall, saving and tools to the plugin. | Expected: it keeps content from being added or saved twice. See [Gateway or plugin?](15-gateway.md#gateway-or-plugin). |
-| Saving shows **Retrying**, then **Paused** | OpenViking rejected the save or could not be reached, or the conversation's gateway key was revoked (`gateway_key_revoked`), for example after the user's OpenViking key was regenerated. | Saving resumes on its own once OpenViking is back. After a revocation, issue a new gateway key; the user's next request resumes saving. See [Conversations do not appear in OpenViking](#conversations-do-not-appear-in-openviking). |
-| The profile has tools on, but the conversation has none | No request that could use tools has arrived yet, loading the tool list failed on the first one, the client does not send the full history, or the client has its own OpenViking tools. | Check the reason in the request log (see [When tools are not offered](#when-tools-are-not-offered)). `tool_name_collision` is expected when the client has the OpenViking MCP server; for other reasons, fix the cause and start a new conversation. |
-| Requests go without memory | OpenViking unreachable or too slow, budget used up, nothing relevant, and so on. | See [No memory is added](#no-memory-is-added). |
-| The provider rejects a long conversation as too long | The gateway does not know the model's real window and compacts too late. | See [Long conversations hit the context limit](#long-conversations-hit-the-context-limit). |
+| OpenAI-compatible clients | `http://host:1935/v1` | `http://host:1933/gateway/v1` |
+| Claude Code `ANTHROPIC_BASE_URL` | `http://host:1935` | `http://host:1933/gateway` |
+| Volcano Engine Ark and BytePlus ModelArk SDKs | The old gateway address | `http://host:1933/gateway/api/v3` |
+| Scripts that call the management API | `/api/v1/admin/gateway/...` | `/gateway/admin/...` |
-### The gateway does not start
+1935 is still the standalone default port, and a standalone gateway uses the same `/gateway` paths.
-When an embedded gateway cannot start, the whole OpenViking Server stops. Read the startup error in the server log (`docker compose logs openviking` with Compose).
-
-- **v0.5 data without the old key**: the storage directory holds data encrypted by the v0.5 gateway, but there is neither `OPENVIKING_GATEWAY_ENCRYPTION_KEY` nor `encryption.key` in `storage_path`. Provide the original key; see step 5 of [Migration](#migration).
-- **Old fields**: remove the fields listed in step 2 of [Migration](#migration).
-- **Management key too short**: it needs at least 32 characters. An unset environment variable referenced with `$VAR` causes the same error.
-- **Encryption settings**: the server's `encryption` section (embedded) or the `encryption` block in `gateway.conf` (standalone) is invalid, or its root key cannot be loaded. See the [Encryption guide](08-encryption.md).
-- **Unsupported storage format** (`Unsupported gateway schema`): the storage directory was written by an incompatible gateway version (an older one, or a newer one if you downgraded). Use a fresh, empty `storage_path`.
-- **Standalone without an OpenViking URL**: run `openviking-gateway init`, or set `OPENVIKING_GATEWAY_OPENVIKING_URL`.
-- **Standalone config file not found**: the file named by `--config` or `OPENVIKING_GATEWAY_CONFIG_FILE` does not exist. Fix the path, or create the file with `openviking-gateway init --config <path>`.
-- **Standalone on a non-loopback address**: the startup check must reach OpenViking and confirm `api_key` authentication, or the gateway exits. Start OpenViking first (in containers, wait until it is ready), or bind to `127.0.0.1`.
-
-### Studio shows a setup card
-
-| Card | What to do |
-| --- | --- |
-| The gateway is not enabled on this OpenViking server (404) | Run `openviking-server init` → **Update gateway**, or set `gateway.enabled: true` in `ov.conf` and restart. On a server that uses API keys, root can choose **Enable gateway** on that page instead. Account admins and regular users see a card that only asks them to contact whoever deployed the server. |
-| Connect to OpenViking first, or Your OpenViking API key is invalid (401) | Open connection settings and enter your current OpenViking API key. |
-| The gateway does not support Trusted mode (`trusted_mode_unsupported`) | Switch the server to `api_key` authentication. |
-| The gateway cannot reach OpenViking (`openviking_unreachable`) | Standalone gateways only: check `openviking_url` (in `gateway.conf` or `OPENVIKING_GATEWAY_OPENVIKING_URL`) and the network. |
+### How stored upstream addresses change {#upstream-address-rewrite}
-If the Upstreams and Profiles tabs are read-only, the deployer set a gateway management key: choose **Enter gateway management key** to unlock them. An OpenViking root or admin API key does not unlock editing. After the management key is changed (`management_key_invalid`), Studio locks again. If nobody has the key, see [Lost the management key](#lost-the-management-key).
-
-### Issuing a key fails
-
-The **Issue a gateway key** dialog shows why issuing failed; the code in parentheses is the `reason` the management API returned.
-
-| Message in Studio | Cause and fix |
-| --- | --- |
-| The server only stores a hash of this user's API key and cannot read it. Paste their user API key instead. (`user_key_unreadable`) | OpenViking Server stores only key hashes (`encryption.api_key_hashing.enabled`). Choose **Paste a user API key** and enter that user's own key. |
-| This is a root API key. Use the user API key of a user in this account. (`root_key_not_allowed`) | A root API key cannot be bound to a gateway key. Use the API key of a user or account admin instead. Local dev mode's `default/default` is exempt. |
-| This OpenViking API key belongs to another account. (`other_account`) | The key belongs to a different account from the one you are managing in Studio. |
-| OpenViking rejected this key. (`openviking_http_401`) | The key is incomplete or was regenerated, or the user was deleted. Use the user's current key. |
-| OpenViking couldn't tell which user this key belongs to (`openviking_identity_missing`) | OpenViking returned no user for this key. Use the key of a user in this account. |
-| The gateway couldn't reach OpenViking to check this key. (`openviking_unavailable`) | The gateway cannot reach OpenViking; for a standalone gateway, check `openviking_url`. |
-| OpenViking is older than the gateway requires. (`openviking_version_mismatch`) | Standalone gateways only: OpenViking Server is older than `min_server_version` (0.4.16). Upgrade it. A server installed from source without version tags may report a development version such as `0.1.dev123`; install a release, or set `min_server_version` to match. |
-
-### Clients get an error from the gateway
-
-These rejections happen before the request reaches a provider, so they do not appear in the request log.
-
-| Status and message | Cause and fix |
-| --- | --- |
-| 401 "Invalid gateway key. It may have been revoked, or removed because its OpenViking API key was regenerated…" | The client sent no gateway key, a revoked key or its provider API key, or the gateway deleted the key after the user's OpenViking API key was regenerated. Check which key the client actually sends, and issue a new one if needed. |
-| 403 "Claude subscription OAuth credentials are not supported" | The client sent a Claude subscription token, for example Claude Code signed in with a subscription and no `ANTHROPIC_AUTH_TOKEN` set; or the upstream stores a subscription token. Use an API key. |
-| 403 "Model is not allowed by this key" | The model is not in the key's allowed models. Issue a key that allows it. |
-| 404 "No allowed upstream matches this protocol and model" | No enabled upstream bound to the key uses the API the client called and serves the requested model. Check the upstreams' protocol, models and aliases, whether they are enabled, and which upstreams the key is bound to. |
-| 401 "Upstream API key is missing" | The upstream expects each client to send its own key in `X-OpenViking-Upstream-Key`, or an upstream where the gateway holds the key has none stored. |
-| 403 "Coding Plan upstreams are disabled; configure a model API key" | The upstream is marked as a Coding Plan key. Use a model API key, or deliberately check **Allow this plan through the gateway**. |
-| 404 "Unknown response for this key", 403 "Response upstream is no longer allowed" | The Responses response being looked up was not created with this key, or the upstream that created it is now turned off or no longer bound to the key. |
-| 413 | The request body is larger than `max_body_bytes`, or than your proxy's own limit. |
-| 426 | A WebSocket connection to the Responses API. Expected: Codex falls back to HTTP. |
-| 502 "Model upstream is unavailable" | The gateway could not reach the provider, or the call took longer than `upstream_timeout_seconds`. Choose **Test** on the upstream. |
-| 504 "Hidden tool request timed out" | The OpenViking tool rounds took longer than the profile's tool **Total time**; or, with no total time set, one model request during the tool rounds took longer than `upstream_timeout_seconds`. |
-
-### No memory is added
-
-First find the request in the request log. If it is not there, the client did not go through the gateway, or the gateway rejected the request (see the previous section). If it is there, expand it and check the memory search result:
-
-- **Nothing relevant found** (`empty`): normal for a new user. Memories exist only after a conversation is committed and OpenViking has extracted them.
-- **Recall is off or the budget is used up** (`disabled`): the profile has recall off, the conversation used up its budget, or the message is shorter than 3 characters.
-- **OpenViking is unreachable or didn't answer in time** (`openviking_unavailable`): check the OpenViking card on the Overview tab. If OpenViking is running but slow, raise the **Time limit**.
-- **OpenViking rejected the key** (`openviking_http_401`): the user's OpenViking key is no longer valid. Issue a new gateway key with the current key.
-- **OpenViking is older than the gateway requires** (`openviking_version_mismatch`): see [Issuing a key fails](#issuing-a-key-fails).
-- **OpenViking plugin in use** (`plugin_present`): the gateway detected an OpenViking plugin and stepped aside for this conversation.
-- **The type is not New message**: tool steps, housekeeping and sub-agent requests never search; they replay the memory earlier messages received.
-
-A message whose search failed never gets memory later; the next message searches again.
-
-### Conversations do not appear in OpenViking
-
-- **Saving runs one turn behind.** A turn appears when the next message arrives; the last turn waits for **Save the latest reply after** (10 minutes by default).
-- **The profile does not save.** The **Saving** column shows Off.
-- **Saving is retrying or paused.** The expanded row shows the reason. Once the cause is fixed (for example, OpenViking is reachable again), the gateway retries within 5 minutes. With `gateway_key_revoked`, issue a new gateway key; the next request resumes saving. If the conversation stays paused, use **Resync conversation…**.
-- **An OpenViking plugin was detected** (`plugin_present`): the gateway saves nothing for that conversation.
-- **You are looking as a different user.** Sessions belong to the OpenViking user behind the gateway key and are named `gateway-…`.
-- **Memories show up later than sessions.** OpenViking extracts memories in the background, only after a commit.
-
-### The first-call cache hit rate dropped
-
-Compare it with what the provider reaches without the gateway, then look at the issues flagged on recent requests:
-
-- **Memory record missing** (`missing_injection_record`): the gateway's storage was lost or restored from an old backup, or the record expired, so memory added earlier could not be replayed. Ongoing conversations recover after one miss.
-- **Upstream switched** (`upstream_changed`): the conversation's upstream was turned off, is not bound to the key the client now uses, or no longer serves the model, so the conversation moved to another upstream.
-- **Cache parameters changed** (`ark_cache_parameters_changed`): on Ark or ModelArk, the client changed the model, thinking mode, sampling parameters, system prompt or tools within a conversation.
-- **No issue flagged**: the client itself may change earlier messages or its system prompt every turn, for example by inserting the current time, which the gateway cannot fix. Each compaction, and each new context window the model starts, also costs one miss; that is expected.
-- **Always 0%**: first compare with the cache records of your provider or relay. Hits there mean the upstream isn't passing cache usage back to the gateway, for example a relay that drops the cache fields when it converts protocols; the gateway reads the common fields, such as `cache_read_input_tokens`, `prompt_tokens_details.cached_tokens`, `input_tokens_details.cached_tokens` and `prompt_cache_hit_tokens`. No hits there: check that the provider supports prompt caching, that an Anthropic client sets `cache_control`, and that the relay isn't rotating between accounts or channels.
-
-### Long conversations hit the context limit
-
-When the provider rejects a long conversation as too long, it is usually one of three causes:
-
-- **The gateway does not know the model's window.** The upstream's **Context windows** has no entry for the model and the profile has no **Default context window**, so the gateway assumes 1,000,000 tokens and compacts too late for a smaller model. Add the model's window.
-- **The conversation's profile has compaction off.** Profile changes only reach new conversations.
-- **Compaction failed.** The request detail shows the reason, and the gateway tries again after 60 seconds. If summaries keep getting cut off at the length limit, raise **Summary length**. `still_over_threshold` means the system prompt, tools and summary alone fill most of the window: lower **Summary length**, or check the model's context window setting.
-
-### File imports or downloads fail
-
-- "Set gateway.public_url for client uploads and downloads": set `public_url` to an address the client can reach, or set `mcp_file_links` to `direct`.
-- The upload or download link is unreachable or returns 404: make sure `public_url` is not an old `:1935` address, does not already end in `/gateway`, and that your proxy forwards `/gateway/uploads` and `/gateway/downloads` like the other paths. With `mcp_file_links` set to `direct`, check the server's `OPENVIKING_PUBLIC_BASE_URL` instead.
-- 413: the file is larger than `max_body_bytes` or the proxy's limit.
-- 502 "OpenViking upload is unavailable" or "OpenViking download is unavailable": the gateway cannot reach OpenViking Server.
-- The model has no import tool: the OpenViking service does not provide it, the profile has it unchecked, or this request cannot use gateway tools. Check the tool list and the request detail.
+| Upstream | Stored Base URL | After the first start |
+| --- | --- | --- |
+| Ark and ModelArk, Chat Completions or Responses | Only a domain | `/api/v3` added |
+| Other Chat Completions or Responses | A path that does not end in a version segment such as `/v1` or `/v4`, including a bare domain or a path prefix | `/v1` added: `https://api.deepseek.com` → `https://api.deepseek.com/v1`, `https://openrouter.ai/api` → `https://openrouter.ai/api/v1`, or a self-hosted proxy under `/litellm` |
+| Ark and ModelArk, Anthropic | Only a domain | `/api/compatible` added |
+| Anthropic | Ends in `/v1` | `/v1` removed |
+| Any | Already ends in another version segment, such as Zhipu's `https://open.bigmodel.cn/api/paas/v4` | Unchanged. Before the upgrade it became `…/v4/v1` and failed; now it works as entered. |
-### Issues on degraded requests
+New and edited upstreams follow the rules in [How the Base URL is joined](../gateway/07-upstreams.md#base-url), and an Anthropic Base URL ending in `/v1` is rejected.
-The Requests and Overview tabs flag requests the gateway could not fully handle. Studio shows the issue label; the code in parentheses is the matching value in the management API:
+## Next steps {#next-steps}
-| Issue | What happened | What to do |
-| --- | --- | --- |
-| Memory unavailable (`memory_store_failure`) | The gateway could not read or write its storage, or the user's gateway data was just deleted. The request went to the model without memory; in Claude conversations, earlier thinking was removed. | Check disk space, permissions and the gateway log. Expected right after deleting a user's gateway data. |
-| Forwarded unchanged (`unsafe_json`) | The request had numbers that cannot be re-encoded exactly, or duplicate keys, so the gateway forwarded it byte for byte without memory. | Usually specific to one client; nothing to change in the gateway. |
-| Upstream switched (`upstream_changed`) | The conversation's upstream could no longer serve it, so it moved to another one, with one cache miss and earlier Claude thinking removed. | Turn the upstream back on, or give the client a key that includes it; or accept the switch. |
-| Memory record missing (`missing_injection_record`) | In a Claude conversation, memory added earlier is no longer on record, so earlier thinking was removed once. | Expected after storage loss or in very old conversations. If it keeps happening, start a new conversation. |
-| OpenViking plugin in use (`plugin_present`) | An OpenViking plugin was detected, and this conversation no longer uses gateway memory. | Expected when a plugin is in use. Use either the plugin or the gateway for a given client. |
-| Cache parameters changed (`ark_cache_parameters_changed`) | On Ark or ModelArk, parameters that affect caching differ from the conversation's first request, so the prompt cache probably missed. | Keep the model, thinking mode, sampling parameters, system prompt and tools the same within a conversation. |
-| Tool history unavailable (`hidden_tool_history_unavailable`) | A Claude conversation used OpenViking tools, but this request cannot use them, so earlier thinking was removed. | Check the tool skip reason in the request detail, restore the original settings, or start a new conversation. |
-| OpenViking tools failed (`hidden_tool_loop_failed`) | The model could not finish its answer while using OpenViking tools, and the client received an error. | See [Failure handling](#failure-handling). |
-| Reply not saved (`capture_parse_failure`) | A streamed reply could not be parsed, so it was not saved. The client was not affected. | Nothing to do; it is for information only. |
-| Key not verified (`revocation_check_unavailable`) | OpenViking could not confirm the gateway key, so the request was served without checking whether the key was revoked. | Check that OpenViking is reachable and healthy. |
+- [Manage OpenViking Gateway in Studio](../gateway/06-manage-in-studio.md): add upstreams, create context profiles and issue the first gateway keys.
+- [Security and data](../gateway/11-security-and-data.md): review what the gateway stores, who can reach it, and how to back it up and delete data.
+- [Troubleshoot OpenViking Gateway](../gateway/12-troubleshooting.md): match a startup error, setup card or failed request to its fix.
diff --git a/docs/zh/agent-integrations/01-overview.md b/docs/zh/agent-integrations/01-overview.md
index 1006c47aa..75d4e78bc 100644
--- a/docs/zh/agent-integrations/01-overview.md
+++ b/docs/zh/agent-integrations/01-overview.md
@@ -22,6 +22,8 @@ OpenViking 可以作为多种 Agent 运行时的长期记忆与上下文后端
| **聊天客户端 / SDK 与 API 应用 / 其他没有插件的客户端** | [OpenViking 网关](../guides/15-gateway.md) — 能填 Base URL 和 API Key 的客户端都能接入网关,由网关召回记忆、保存对话,客户端里不用装任何东西 |
| **ZCode / AstrBot / …** | [社区插件](./08-community-plugins.md) — 社区维护的各运行时集成 |
+Claude Code、Codex、OpenCode、pi、DSH 等 Agent 既能用自己的插件,也能接入 OpenViking 网关。两者怎么选,见[网关还是插件](../guides/15-gateway.md#gateway-or-plugin)。
+
## 横向对比各集成能力
想知道各个集成在工具面、自动召回、会话与 commit、压缩接管、降级容错上的具体差异,见 [集成能力参考](./16-capability-reference.md)——一份覆盖全部集成的横向对照矩阵。
diff --git a/docs/zh/api/25-gateway.md b/docs/zh/api/25-gateway.md
index 25999c64d..4716b6927 100644
--- a/docs/zh/api/25-gateway.md
+++ b/docs/zh/api/25-gateway.md
@@ -2,15 +2,15 @@
管理 API 用来查看权限、配置上游和上下文配置、签发网关密钥、读取用量和日志。所有路径都以 `/gateway/admin/` 开头,由网关直接提供:网关在 OpenViking Server 内运行时,访问 Server 的端口(默认 1933);独立运行时,访问网关自己的端口(默认 1935)。示例中的 `SERVER_URL` 指这个地址本身,不带路径,例如 `http://127.0.0.1:1933`。
-模型客户端不调用这组接口。它们用网关密钥访问 `/gateway/v1/*`、`/gateway/api/v3/*` 或 `/gateway/api/compatible/v1/*`,见[OpenViking 网关](../guides/15-gateway.md#接入客户端)。
+模型客户端不调用这组接口。它们用网关密钥访问 `/gateway/v1/*`、`/gateway/api/v3/*` 或 `/gateway/api/compatible/v1/*`,见[OpenViking 网关](../gateway/03-connect-clients.md#connect-clients)。
-## 凭证和账号范围
+## 凭证和账号范围 {#credentials-and-account-scope}
每个管理请求都要带 OpenViking API 密钥,放在 `X-API-Key` 或 `Authorization: Bearer` 中。网关向 OpenViking 确认这把密钥属于哪个账号、哪个用户、什么角色,确认结果最多缓存 30 秒。本地 dev 模式不需要密钥,调用方固定为 root 身份 `default/default`。网关不支持 trusted 认证。
上游和上下文配置(API 中叫 `policies`)属于账号,同一账号的用户共用。请求默认作用于调用方所在的账号;root 可以用 query 参数 `account_id` 指定其他账号,admin 和 user 只能访问自己的账号。
-部署者可以另外设置网关管理密钥(配置方法见[网关管理密钥](../guides/22-gateway-operations.md#网关管理密钥))。设置之后,修改上游和上下文配置的请求必须在 `X-OpenViking-Gateway-Management-Key` 中带上它,OpenViking 的 admin 和 root 也不例外。请求带了管理密钥但值不对时,网关直接返回 401 `management_key_invalid`,不会降级成只读请求。
+部署者可以另外设置网关管理密钥(配置方法见[网关管理密钥](../guides/22-gateway-operations.md#gateway-management-key))。设置之后,修改上游和上下文配置的请求必须在 `X-OpenViking-Gateway-Management-Key` 中带上它,OpenViking 的 admin 和 root 也不例外。请求带了管理密钥但值不对时,网关直接返回 401 `management_key_invalid`,不会降级成只读请求。
| 操作 | 未设置管理密钥 | 已设置管理密钥 |
| --- | --- | --- |
@@ -26,13 +26,13 @@
只读视图不返回上游的 API Key、请求头的值和请求头名称,只保留 `has_api_key` 和 `auth_mode`。
-## 权限与发现
+## 权限与发现 {#access-and-discovery}
| 方法 | 路径 | 返回 |
| --- | --- | --- |
| GET | `/gateway/admin/access` | 调用方的权限:`managed`、`can_write_objects`、`can_import_vlm`、`can_issue_for_others`、`role`、`account_id`、`user_id`、`warnings` |
| GET | `/gateway/admin/overview` | 调用方可见的最近 10,000 条日志汇总:用量、缓存命中、召回、保存异常、OpenViking 状态和日志保留期 |
-| GET | `/gateway/admin/logs` | 调用方可见的最新日志;`limit` 默认 200,取值 1–1000 |
+| GET | `/gateway/admin/logs` | 调用方可见的最新日志,以 JSON 数组返回,最新的在前;`limit` 默认 200,取值 1–1000。字段见[日志记录](#log-records)。 |
| GET | `/gateway/admin/guides` | 客户端接入地址 `base_url`,以及 `public_url_configured`;`base_url` 是 `public_url` 加 `/gateway`,未设置 `public_url` 时取请求的来源地址加 `/gateway` |
| GET | `/gateway/admin/tools` | 调用方能用的 OpenViking 工具:名称、描述和 annotations,用调用方自己的 OpenViking 密钥读取(OpenViking 拒绝 root 访问 `/mcp`,所以 root 改用本账号已签发网关密钥对应的 OpenViking 密钥,没有时返回上次读到的目录) |
@@ -58,7 +58,35 @@ curl "$SERVER_URL/gateway/admin/access" \
OpenViking 拒绝 API 密钥时,返回 401 `openviking_http_401`。
-## 上游和上下文配置
+### 日志记录 {#log-records}
+
+日志只记元数据,不含消息内容。发往模型服务商的请求结束时写一条记录;对话的保存状态变化时也写一条(`kind` 为 `capture`)。网关在请求到达服务商之前就拒绝的,不记日志。除 `time` 外,字段都是可选的,不适用时省略。
+
+| 字段 | 含义 |
+| --- | --- |
+| `time` | 记录写入时间,Unix 时间戳(秒) |
+| `request_id` | 网关为请求分配的 ID |
+| `kind` | `user`、`continuation`、`auxiliary`、`subagent`、`count`、`passthrough` 或 `capture`,见[请求日志](../gateway/10-overview-and-requests.md#requests) |
+| `model` | 客户端发送的模型名 |
+| `status` | 服务商返回的 HTTP 状态码 |
+| `upstream_id`、`credential_id` | 处理请求的上游,以及发出请求的网关密钥 |
+| `session`、`protocol` | 对话及其协议,[重置保存](#gateway-keys)时要用 |
+| `degradation` | 异常代码,见[降级请求的异常](../gateway/12-troubleshooting.md#issues-on-degraded-requests) |
+| `recall_reason`、`recall_count`、`recall_ms` | 记忆检索的结果代码、补充的条数和检索耗时,见[没有补充记忆](../gateway/12-troubleshooting.md#no-memory-is-added) |
+| `replay_hits` | 原样放回记忆的历史消息数 |
+| `capture_status`、`capture_reason`、`capture_retry_at` | 保存状态(`active`、`disabled`、`retrying` 或 `paused`)、原因,以及下次重试时间(Unix 时间戳,秒),见[保存状态](../gateway/10-overview-and-requests.md#saving-status) |
+| `tool_skip_reason` | 请求没有拿到 OpenViking 工具的原因,见[什么时候不提供工具](../gateway/04-openviking-tools.md#when-tools-are-not-offered) |
+| `tool_stop_reason` | 工具 Token 预算用完、后续调用被拒绝时为 `token_budget`,见[上限](../gateway/04-openviking-tools.md#limits) |
+| `compaction_failed` | 压缩失败的原因(`still_over_threshold` 时摘要已保留),见[长对话超出上下文长度](../gateway/12-troubleshooting.md#long-conversations-hit-the-context-limit) |
+| `context_tokens`、`context_window` | 估算的上下文大小,以及用来比较的上下文窗口 |
+| `input_tokens`、`output_tokens`、`cached_tokens`、`cache_write_tokens` | 本次请求所有服务商调用(含 OpenViking 工具轮次)的 token 用量合计。`input_tokens` 已包含缓存命中和缓存写入的 token。 |
+| `duration_ms` | 从把请求发给服务商到回复结束的耗时 |
+
+以 `first_upstream_` 和 `hidden_upstream_` 开头的字段把 token 用量拆成首次服务商调用和 OpenViking 工具轮次两部分,首次调用缓存命中率按前者计算。
+
+`/overview` 由这些记录汇总而来。除用量和缓存数据外,还返回 `degradations`(异常代码 → 次数)、`capture_issues`(正在重试或已暂停保存的对话数)、`cache_alerts`、`openviking`(OpenViking 的 `status`,降级时另有 `reason`)和 `log_retention_days`。
+
+## 上游和上下文配置 {#upstreams-and-context-profiles}
| 方法 | 路径 | 说明 |
| --- | --- | --- |
@@ -73,7 +101,7 @@ OpenViking 拒绝 API 密钥时,返回 401 `openviking_http_401`。
| PUT | `/gateway/admin/policies/{identifier}` | 创建或替换上下文配置 |
| DELETE | `/gateway/admin/policies/{identifier}` | 删除没有密钥在用的上下文配置 |
-ID 由调用方指定。`PUT` 提交完整对象,未知字段会导致校验失败。各字段的含义、默认值和取值范围见[配置参考](../guides/22-gateway-operations.md#配置参考)。
+ID 由调用方指定。`PUT` 提交完整对象,未知字段会导致校验失败。各字段的含义、默认值和取值范围见[配置参考](../gateway/13-configuration.md#configuration-reference)。
上游的 `api_key` 和 `headers` 只写不读:
@@ -90,29 +118,36 @@ curl -X PUT "$SERVER_URL/gateway/admin/upstreams/openai?account_id=team" \
删除仍有网关密钥在用的对象,返回 409 `in_use` 和 `key_count`。先吊销这些密钥;只是想让请求立即停止发往某个上游,可以停用它而不删除。
-### 上游测试
+### 上游测试 {#upstream-tests}
-`POST /gateway/admin/upstreams/{identifier}/test` 支持两种模式:空请求体 `{}` 通过 `GET /v1/models` 检查连接;`{"model":"<模型名>"}` 使用已存的凭证和请求头发送一次很小的非流式生成请求。模型名会先经过上游的别名映射。模型请求使用已配置的 Chat Completions、Responses 或 Anthropic Messages 接口;关闭路径拼接时,也会遵循配置的完整接口 URL。上游允许 Gateway 工具时,请求会带上当前账户的 OpenViking 工具,并按默认上下文配置筛选;工具目录暂时不可用时,降级为不带工具继续测试。模型测试不设置 reasoning effort,由模型使用默认值。
+`POST /gateway/admin/upstreams/{identifier}/test` 支持两种模式:空请求体 `{}` 通过 `GET /v1/models` 检查连接;`{"model":"<模型名>"}` 使用已存的凭证和请求头发送一次很小的非流式生成请求。模型名会先经过上游的别名映射。模型请求使用已配置的 Chat Completions、Responses 或 Anthropic Messages 接口;关闭路径拼接时,也会遵循配置的完整接口 URL。上游允许 OpenViking 工具时,请求会带上当前账号的 OpenViking 工具,并按默认上下文配置筛选;工具目录暂时不可用时,降级为不带工具继续测试。模型测试不设置 reasoning effort,由模型使用默认值。
响应包含 `{ok, kind, status, reason, url}`,其中 `kind` 为 `connection` 或 `model`。测试失败时还会在 `response` 中返回完整的上游 HTTP 响应,包括 `http_version`、`status`、`reason`、`headers`、`body` 和可选的 `truncated` 标记。响应体最多 16 KiB;没有收到响应时不含 `status`。超时时间取已配置上游超时与 60 秒中的较小值。两种测试都需要写权限;模型测试会真实请求服务商并可能产生少量费用。
-Anthropic 测试同时在 `x-api-key` 和 `Authorization: Bearer` 中发送密钥;上游请求头未设置 `anthropic-version` 时,默认使用 `2023-06-01`。Chat Completions 和 Responses 测试只发送 Bearer 鉴权。`key_header` 不是 `authorization`,或者 `base_url` 含 `{api_key}` 时,按[凭证](../guides/22-gateway-operations.md#凭证)中的规则发送;返回的 `url` 保留 `{api_key}` 占位符。
+Anthropic 测试同时在 `x-api-key` 和 `Authorization: Bearer` 中发送密钥;上游请求头未设置 `anthropic-version` 时,默认使用 `2023-06-01`。Chat Completions 和 Responses 测试只发送 Bearer 鉴权。`key_header` 不是 `authorization`,或者 `base_url` 含 `{api_key}` 时,按[凭证](../gateway/07-upstreams.md#credentials)中的规则发送;返回的 `url` 保留 `{api_key}` 占位符。
-| 服务商的响应 | `reason` | `ok` |
-| --- | --- | --- |
-| Coding Plan 上游尚未授权网关使用。网关不发请求。 | `coding_plan_blocked` | `false` |
-| 对完整请求地址(`append_endpoint_path` 为 `false`)做连接测试:这种上游没有模型列表,网关不发请求,请改用模型测试。 | `exact_endpoint_untestable` | `false` |
-| 没有可用的 API Key:没有保存,或者上游要求每个客户端自带。网关不发请求。 | `upstream_key_missing` | `false` |
-| 2xx,响应符合已配置的模型协议 | `passed` | `true` |
-| 2xx,但响应不是合法 JSON 或不符合已配置的协议 | `invalid_response` | `false` |
-| 401 或 403 | `upstream_key_rejected` | `false` |
-| 400、404、405 或 422 | `model_request_rejected` | `false` |
-| 429 | `rate_limited` | `false` |
-| 网络错误、超时、重定向或 5xx | `upstream_unavailable` | `false` |
+两种测试对服务商响应的判断不同:
+
+| 测试 | 服务商的响应 | `reason` | `ok` |
+| --- | --- | --- | --- |
+| 连接 | 上游是完整请求地址(`append_endpoint_path` 为 `false`),没有模型列表。网关不发请求,请改用模型测试。 | `exact_endpoint_untestable` | `false` |
+| 模型 | Coding Plan 上游尚未授权网关使用。网关不发请求。 | `coding_plan_blocked` | `false` |
+| 两者 | 没有可用的 API Key:没有保存,或者上游要求每个客户端自带。网关不发请求。 | `upstream_key_missing` | `false` |
+| 连接 | 2xx,响应是带 `data` 列表的 JSON 对象 | `passed` | `true` |
+| 连接 | 其他 2xx:不是合法 JSON、响应体超过 16 KiB、没有 `data` 列表,或带 `error` 字段 | `upstream_key_rejected` | `false` |
+| 连接 | 404 或 405:服务商不提供模型列表,API Key 未经验证 | `models_unavailable` | `true` |
+| 连接 | 429:地址有响应,但 API Key 未经验证 | `rate_limited` | `true` |
+| 模型 | 2xx,响应符合已配置的模型协议 | `passed` | `true` |
+| 模型 | 其他 2xx:不是合法 JSON、响应体超过 16 KiB,或不符合已配置的协议 | `invalid_response` | `false` |
+| 模型 | 429 | `rate_limited` | `false` |
+| 模型 | 404 或 405 | `model_request_rejected` | `false` |
+| 两者 | 400 或 422 | `model_request_rejected` | `false` |
+| 两者 | 401 或 403 | `upstream_key_rejected` | `false` |
+| 两者 | 网络错误、超时、重定向、5xx 或其他状态码 | `upstream_unavailable` | `false` |
-连接测试通过说明地址可达;服务商提供 `/v1/models` 时也会验证已存凭证。部分服务商不提供该接口,返回 404 或 405 后仍可继续测试模型。模型测试通过说明所选模型完成了本次请求,不代表其他模型也可用,也不会授权使用 Coding Plan。
+连接测试返回 `passed`,说明地址可达,已存凭证也有效。`models_unavailable` 和 `rate_limited` 只能说明地址可达,Studio 显示为中性色的 **连接可用**;要验证 API Key,请再做一次模型测试。Coding Plan 授权只拦截模型测试,未授权的 Coding Plan 上游照样可以做连接测试。模型测试通过说明所选模型完成了本次请求,不代表其他模型也可用,也不会授权使用 Coding Plan。
-### 导入 VLM 配置
+### 导入 VLM 配置 {#import-vlm-settings}
`POST /gateway/admin/upstreams/import-vlm` 把 OpenViking Server 的 VLM 凭证导入为所选账号的上游,只在嵌入部署中可用;独立网关返回 404 `vlm_import_unavailable`。
@@ -133,7 +168,7 @@ Anthropic 测试同时在 `x-api-key` 和 `Authorization: Bearer` 中发送密
| `litellm_unsupported_route` | LiteLLM 路由不使用 OpenAI Chat Completions API,例如 `gemini/`、`bedrock/` 或 `vertex_ai/`。请手动把这个服务商添加为上游。 |
| `invalid_configuration` | 凭证构不成有效的上游,例如 base URL 无效。 |
-## 网关密钥
+## 网关密钥 {#gateway-keys}
| 方法 | 路径 | 说明 |
| --- | --- | --- |
@@ -186,13 +221,13 @@ curl -X POST "$SERVER_URL/gateway/admin/keys?account_id=team" \
立即保存响应中的 `key`,网关只保留它的哈希。`GET` 返回同样的字段,但没有 `key`。网关密钥不能修改,没有对应的 `PUT`;要换上下文配置、上游、模型或用户,就签发新密钥,再吊销旧的。
-用户的 OpenViking API 密钥重新生成或用户被删除后,绑定它的网关密钥会失效并被删除,用户数据保留,见[网关密钥](../guides/22-gateway-operations.md#网关密钥)。
+用户的 OpenViking API 密钥重新生成或用户被删除后,绑定它的网关密钥会失效并被删除,用户数据保留,见[网关密钥](../gateway/09-gateway-keys.md#gateway-keys)。
**重置保存。** 请求体为 `{"session":"<会话请求头的值或日志中的 session>","protocol":"chat"}`,`protocol` 取 `chat`、`anthropic` 或 `responses`。成功返回 `{"status":"ready","message":"…"}`,网关会在这段对话的下一个请求里,把完整历史写入一个新的 OpenViking 会话。找不到这段对话时返回 404 `not_found`。
-**删除数据。** 两个删除接口会清掉网关里尚未保存的对话内容和日志,不影响已经存入 OpenViking 的会话和记忆。保留期和其他删除途径见[安全与数据](../guides/22-gateway-operations.md#安全与数据)。
+**删除数据。** 两个删除接口会清掉网关里尚未保存的对话内容和日志,不影响已经存入 OpenViking 的会话和记忆。保留期和其他删除途径见[安全与数据](../gateway/11-security-and-data.md)。
-## 错误
+## 错误 {#errors}
管理接口的错误响应带稳定的顶层 `reason`,以及一句简短的英文说明 `detail`;部分错误另有附加字段,例如:
@@ -204,7 +239,7 @@ curl -X POST "$SERVER_URL/gateway/admin/keys?account_id=team" \
| HTTP | `reason` | 含义和处理 |
| --- | --- | --- |
-| 401 | `management_key_invalid` | 管理密钥不正确。向部署者确认当前的管理密钥,或者见[忘记网关管理密钥](../guides/22-gateway-operations.md#忘记网关管理密钥)。 |
+| 401 | `management_key_invalid` | 管理密钥不正确。向部署者确认当前的管理密钥,或者见[忘记网关管理密钥](../guides/22-gateway-operations.md#lost-the-management-key)。 |
| 403 | `management_key_required` | 已设置管理密钥,修改上游或上下文配置时必须带上它。 |
| 401 | `openviking_http_401` | OpenViking 拒绝了 API 密钥。换用当前有效的密钥。 |
| 401 | `openviking_identity_missing` | OpenViking 没有返回这把密钥对应的用户。 |
@@ -225,4 +260,4 @@ curl -X POST "$SERVER_URL/gateway/admin/keys?account_id=team" \
OpenViking 返回的其他 HTTP 错误记为 `openviking_http_<status>`;网关自身的通用 HTTP 错误记为 `gateway_http_<status>`,例如对不支持的方法返回 405 `gateway_http_405`。
-模型客户端收到的 401 不属于管理 API。原因可能是网关密钥缺失、错误或已吊销,也可能是它绑定的 OpenViking 密钥已经失效,排查方法见[客户端收到网关返回的错误](../guides/22-gateway-operations.md#客户端收到网关返回的错误)。
+模型客户端收到的 401 不属于管理 API。原因可能是网关密钥缺失、错误或已吊销,也可能是它绑定的 OpenViking 密钥已经失效,排查方法见[客户端收到网关返回的错误](../gateway/12-troubleshooting.md#clients-get-an-error-from-the-gateway)。
diff --git a/docs/zh/configuration/01-server.md b/docs/zh/configuration/01-server.md
index a77202c92..c4b5bf611 100644
--- a/docs/zh/configuration/01-server.md
+++ b/docs/zh/configuration/01-server.md
@@ -73,7 +73,7 @@ openviking-server --config /path/to/ov.conf
| `log` | object | 控制台日志 | 日志级别、格式和文件输出 |
| `telemetry` | object | disabled | OpenTelemetry trace 上报 |
| `oauth` | object | disabled | MCP OAuth 2.1 配置 |
-| `gateway` | object | disabled | OpenViking 网关配置,网关为使用 API Key 的模型客户端补充 OpenViking 记忆。这一部分的未知字段会直接报错,见[配置参考](../guides/22-gateway-operations.md#配置参考) |
+| `gateway` | object | disabled | OpenViking 网关配置,网关为使用 API Key 的模型客户端补充 OpenViking 记忆。这一部分的未知字段会直接报错,见[配置参考](../gateway/13-configuration.md#configuration-reference) |
| `prompts` | object | 内置模板 | 自定义 Prompt 模板目录 |
| `ingest` | object | 内置默认值 | 会话日志导入配置 |
| `output_language_override` | string | `""` | 强制摘要和记忆输出语言;空值表示自动识别 |
diff --git a/docs/zh/gateway/01-how-it-works.md b/docs/zh/gateway/01-how-it-works.md
new file mode 100644
index 000000000..746364bcb
--- /dev/null
+++ b/docs/zh/gateway/01-how-it-works.md
@@ -0,0 +1,142 @@
+---
+description: OpenViking 网关如何处理一轮对话:召回、对话开头的内容、原样放回、保存,以及背后的设计取舍。
+---
+
+# OpenViking 网关的工作原理
+
+模型 API 是无状态的:客户端每次请求都把整段对话重新发一遍,OpenViking 网关就在这个循环里工作。它为每条新的用户消息补充记忆,记下补充的原文并在之后的请求里原样放回,再把完成的轮次保存到 OpenViking。本页沿着一轮对话讲清这几步,适合想先弄懂机制、再把请求交给网关的读者;文中术语的定义见[关键术语](../guides/15-gateway.md#key-terms)。
+
+## 一轮对话里发生什么 {#what-happens-once-you-connect}
+
+![一轮对话里发生了什么:网关识别对话和请求类型,把之前补充的记忆原样放回,只为新消息召回,再用同一种 API 转发给上游,并把这一轮放进待保存队列;下方说明原样放回如何让提示词缓存持续命中,以及跨轮的保存和长对话压缩](../../images/gateway/one-turn.zh.svg)
+
+每个请求都按同样的顺序处理。只有用户的新消息触发[召回](#what-the-model-sees),工具步骤和生成标题这类辅助请求沿用已经补充的内容。
+
+| 步骤 | 网关做什么 | 详见 |
+| --- | --- | --- |
+| 识别 | 自动认出请求属于哪段对话,并区分用户新消息、工具步骤、辅助请求等请求类型。 | [网关如何识别对话](03-connect-clients.md#how-conversations-are-recognized)、[请求类型](10-overview-and-requests.md#request-types) |
+| 原样放回 | 把之前补充过的每个记忆块放回原来的消息上,一字不差。 | [记忆原样放回与提示词缓存](#replay) |
+| 召回 | 只为用户新消息检索 OpenViking,把结果附加上去;新对话还会附上开头内容。 | [模型看到什么](#what-the-model-sees)、[对话开头的内容](#the-opening-context) |
+| 转发 | 用请求进来时的同一种 API 转发给上游。 | [路由](07-upstreams.md#routing) |
+| 保存 | 把这一轮放进待保存队列,等下一条用户消息表明客户端保留了它,再保存。 | [对话什么时候保存](#when-conversations-are-saved) |
+
+对话接近模型的上下文窗口时,网关还会压缩它(见[长对话](#long-conversations))。本页提到的预算、时长和开关都来自密钥使用的[上下文配置](08-context-profiles.md#context-profiles),管理员可以逐项调整或关闭。
+
+## 模型看到什么 {#what-the-model-sees}
+
+请求以一条新的用户消息结尾时,网关用这条消息的文本检索 OpenViking,把结果附加到消息末尾,这就是**召回**:
+
+```text
+发布日期最后定在哪天?
+
+<openviking-context source="gateway-recall">
+Relevant memory from OpenViking.
+<memory uri="viking://user/alice/memories/events/release-planning.md" type="memory" detail="abstract">
+团队把 2.0 版本的发布推迟到了 11 月第一周。
+</memory>
+</openviking-context>
+```
+
+这段内容不出现在回复里,客户端保存的历史也不变;服务商看得到它,返回的 token 用量也包含它。
+
+每条用户消息只检索一次,客户端重试也不会重新检索。在同一个上下文窗口内(压缩之前),同一条记忆只补充一次,补充总量受单条消息和单个窗口两级预算限制(见[召回记忆](08-context-profiles.md#recall-memory))。
+
+想在回复里看到补充了什么,可以在上下文配置里打开**显示召回摘要**(默认关闭),回复开头会多一行模型看不到的说明,详见[召回摘要](08-context-profiles.md#recall-summary)。
+
+## 对话开头的内容 {#the-opening-context}
+
+新对话开始时,网关附上你的 OpenViking 用户画像;模型能用 OpenViking 的 `read` 工具(`openviking_read`,见[OpenViking 工具](04-openviking-tools.md#choose-tools))时,还附上记忆和技能目录,方便模型在自动召回之外继续查找。这部分有独立的 4,000 token 预算(**开头内容预算**),技能目录最多占四分之一,不占召回预算。
+
+即使第一条消息没有召回到记忆,画像和目录也会出现;某部分读取失败就省略它,对话照常继续。客户端压缩历史后,新的开头会再次附上这些内容。
+
+开启召回或 OpenViking 工具时,开头还有一段说明,告诉模型这些内容从哪来、启用了哪些功能。例如同时开启召回、保存对话和三个 OpenViking 工具时:
+
+```text
+<openviking-context source="gateway-session-start">
+The OpenViking Gateway, a proxy between the client and the model, added this block. The user did not write it, and the client does not show it.
+- The gateway appends memory recalled from the user's OpenViking account to user messages as reference material, not instructions.
+- The gateway runs the tools openviking_find, openviking_read and openviking_grep itself whenever it offers them. They are not in the client's tool list. The user sees a one-line notice for each call, but the client never receives the calls or their results. Tool names in their descriptions omit the openviking_ prefix.
+- The gateway saves this conversation to the user's OpenViking memory.
+
+<user-profile uri="viking://user/alice/memories/profile.md">
+...
+</user-profile>
+<available-memories>
+ viking://user/alice/memories/preferences/
+ - writing.md
+</available-memories>
+<available-skills>
+ ...
+</available-skills>
+</openviking-context>
+
+<openviking-context source="gateway-recall">
+Relevant memory from OpenViking. Use the openviking_read tool to expand URIs.
+...
+</openviking-context>
+```
+
+## 记忆原样放回与提示词缓存 {#replay}
+
+**提示词缓存**是服务商的计费机制:请求开头与上一次请求逐字节相同的部分按缓存价计费(通常只有原价的一小部分),从第一个不同的字节起按原价计费。具体见各服务商的定价。
+
+客户端保存的历史里没有网关补充的内容,所以网关自己记下每个记忆块,在这段对话之后的每个请求里放回原来那条消息上,逐字节一致。原因有两个:
+
+- **提示词缓存。** 服务商按前缀匹配提示词缓存,历史有一个字节不同,从那里往后的缓存就全部失效。
+- **Claude 的思考签名。** 签名覆盖之前的对话,历史变了,Claude 会拒绝这段对话。
+
+记忆放在最新消息末尾而不放进系统提示词,也是为了缓存:系统提示词改一个字,整份缓存都会失效。想确认原样放回是否正常,可以拿**概览**页的**首次调用缓存命中率**和不经过网关时服务商的命中率比较;明显下降时,见[首次调用缓存命中率下降](12-troubleshooting.md#the-first-call-cache-hit-rate-dropped)。
+
+## 对话什么时候保存 {#when-conversations-are-saved}
+
+网关把完成的轮次保存到密钥所属用户的 OpenViking 会话里,会话名形如 `gateway-…`。保存晚一轮:下一条用户消息到达时,网关才保存上一轮,因为这时才能确认客户端保留了它,被重新生成或放弃的回答不会保存。最后一轮在对话停顿 10 分钟后保存。
+
+保存之后,网关会**提交**会话:OpenViking 归档较早的已保存轮次(会话中只留最新的消息),并在后台从中提取记忆。已保存的轮次要等提交之后才会变成记忆。提交发生在两种时候:对话停顿 10 分钟,或者待提交内容累计到 20,000 token。
+
+以下内容不保存:
+
+- 网关自己添加的内容,以及 `<system-reminder>` 这类客户端噪声,保存前会去掉。
+- 子 Agent 请求、辅助请求和 token 计数请求从不保存。
+
+这些时长在[保存对话](08-context-profiles.md#save-conversations)里设置;每段对话的[保存状态](10-overview-and-requests.md#saving-status)显示在**请求日志**页。
+
+## 长对话 {#long-conversations}
+
+对话用到模型上下文窗口的 90%(**压缩时机**的默认值)时,网关压缩它:让同一个模型为目前为止的对话写一份有长度上限的摘要,此后用摘要代替截断点之前的全部内容。客户端界面里的历史不变。每次压缩多一次模型请求,服务商缓存也失效一次。
+
+什么时候触发压缩、上下文窗口该怎么设、摘要里有什么,见[网关中的长对话](05-long-conversations.md#long-conversations)。
+
+## OpenViking 工具 {#openviking-tools}
+
+开启 OpenViking 工具后,模型在回答过程中可以自己检索、读取 OpenViking 记忆,管理员允许时还能写入;新建的上下文配置默认开启工具,但只勾选只读工具。工具调用由网关执行,往返记录会在之后的轮次里原样放回,所以客户端不用声明或执行这些工具,每次调用只看到一行提示。详见[网关中的 OpenViking 工具](04-openviking-tools.md#agentic-memory-for-any-client)。
+
+## 使用须知 {#what-to-expect}
+
+- **召回最多等 2 秒。** 每条新消息的第一次模型调用要等 OpenViking 检索完成,最多等上下文配置里的**超时时间**(默认 2 秒)。OpenViking 超时或不可用时,这条消息不带记忆直接发给模型,之后也不会补上。
+- **设置只对新对话生效。** 一段对话始终沿用开始时的上下文配置和上游,所以 Claude Code、Codex 这类长期运行的客户端,要开始新对话才会用上修改后的配置。详见[修改何时生效](06-manage-in-studio.md#when-changes-take-effect)。
+- **改动过的历史会重新保存。** 客户端编辑或删除了之前的消息、在回答保存后重新生成,或者自己压缩了对话时,网关把当前的完整历史保存到一个新的 OpenViking 会话,已经保存的轮次留在旧会话里。
+- **特别长的会话可能碰到请求大小上限。** 网关压缩对话后,客户端仍然发送完整历史,而超过 32 MiB 的请求体默认会被拒绝。详见[副作用](05-long-conversations.md#side-effects)。
+- **一个密钥只对应一位记忆归属者。** 共用一个密钥的人共享它背后那位 OpenViking 用户的记忆,所以应该一人一个密钥。详见[每人一把密钥](09-gateway-keys.md#one-key-per-person)。
+- **客户端不能用订阅账号登录。** 带 Claude 订阅令牌的请求会被拒绝。请为上游配置服务商的 API Key,或者把订阅代理作为[自定义上游](07-upstreams.md#custom-upstreams)接在网关后面。Codex 就可以这样通过 CLIProxyAPI 使用 ChatGPT 订阅,见[使用 ChatGPT 订阅](03-connect-clients.md#codex-chatgpt-subscription)。其他订阅服务请自行确认其使用条款。
+- **Responses 需要完整历史。** 依赖服务商端已存状态的 Responses 请求不补充记忆,直接转发,详见[客户端要求](04-openviking-tools.md#client-requirements)。
+- **其他接口直接转发。** 三种模型 API 和模型列表之外的接口(例如 embeddings)不补充记忆,直接转发给密钥绑定的、提供所请求模型且优先级最高的上游。
+
+## 为什么这样设计 {#design-trade-offs}
+
+下表说明网关几项关键设计的原因和代价,帮你判断它是否适合自己的场景:
+
+| 设计 | 选择及原因 | 代价 |
+| --- | --- | --- |
+| 接入位置 | 接在模型调用路径上,而不是给每个 Agent 装插件:装不了插件的客户端也能用,服务商密钥集中管理。 | 看不到工作目录,按项目隔离记忆要给每个项目用不同的 OpenViking 用户。 |
+| 工具由谁执行 | 网关在回复过程中代为执行 OpenViking 工具,存下往返并在下一轮原样放回:没有工具、不支持 MCP 的客户端也能让模型主动使用记忆。 | 没有逐次确认;客户端必须每轮回传完整历史;需要管理员收紧工具清单和上限。 |
+| 记忆放在哪 | 附加在最新用户消息末尾,而不是系统提示词里:系统提示词改一个字整份缓存就失效;附加在末尾并在之后原样放回,前缀始终不变。 | 网关必须可靠地记下每处补充的原文,记录丢失时缓存失效一次。 |
+| 保存时机 | 晚一轮保存:下一条消息带回上一轮,才能确认用户保留了它。 | 最后一轮要等**最新回复等待时长**(默认 10 分钟)之后才保存。 |
+| 长对话 | 由网关让同一个模型写摘要:只有网关知道模型实际收到了什么,摘要请求也大部分命中缓存。 | 触发压缩的那一轮多一次模型调用和计费;截断点之前的原文不再发给模型。 |
+| 本地状态 | 单台主机上的 SQLite,不引入 Postgres、Redis 这类依赖,适合自部署。 | 网关不能多机互备,是模型调用路径上的单点。 |
+| 客户端身份 | 网关签发自己的密钥,而不是直接用 OpenViking 密钥:可以单独吊销,同一个人的不同客户端可以绑定不同的上下文配置。 | 网关要保存用户的 OpenViking 密钥,因此应开启加密;网关密钥泄露,等于该用户的记忆泄露。 |
+
+## 下一步 {#next-steps}
+
+- [OpenViking 网关快速上手](02-quickstart.md):发一个测试请求,亲眼看到召回和保存。
+- [网关中的 OpenViking 工具](04-openviking-tools.md):选择允许模型执行哪些工具,了解用户会看到什么。
+- [网关中的长对话](05-long-conversations.md):设置模型的上下文窗口,弄清压缩会保留什么。
diff --git a/docs/zh/gateway/02-quickstart.md b/docs/zh/gateway/02-quickstart.md
new file mode 100644
index 000000000..7a8c035e8
--- /dev/null
+++ b/docs/zh/gateway/02-quickstart.md
@@ -0,0 +1,98 @@
+---
+description: 开启 OpenViking 网关,签发网关密钥,发送测试请求并确认记忆生效。
+---
+
+# OpenViking 网关快速上手
+
+跟着本页走完,你会从一套能正常工作的 OpenViking 服务出发,拿到一个[网关密钥](../guides/15-gateway.md#key-terms),经网关发出一次测试请求,并亲眼确认记忆生效。开始前,`ov.conf` 中需要已经配好 embedding 和 VLM 模型(见[快速开始](../getting-started/02-quickstart.md))。网关包含在核心包中,不需要另外安装。
+
+先按服务端的情况选一条路径:
+
+| 你的服务端 | 跟着做 |
+| --- | --- |
+| 绑定在 `127.0.0.1`,本地 dev 模式(未配置 `root_api_key`) | [本地服务](#local-server-no-api-key) |
+| 通过网络访问,使用 `api_key` 认证 | [远程服务](#remote-server-api-keys) |
+| 已有 OpenViking 服务,不想改它的配置 | 先按[独立部署](../guides/22-gateway-operations.md#standalone-deployment)运行网关,再回到[发送测试请求](#send-a-test-request) |
+
+## 本地服务(不需要 API 密钥) {#local-server-no-api-key}
+
+本地 dev 模式的服务不需要 OpenViking API 密钥:打开 Studio 不用填密钥,签发的网关密钥以本地 `default` 用户的身份读写记忆。
+
+1. **开启网关。** 运行 `openviking-server init`,在 **Enable OpenViking Gateway on the same port?** 处回答 yes;已有配置时,在菜单中选择 **Update gateway**。也可以手动把 `{"gateway": {"enabled": true}}` 合并进 `ov.conf`。
+2. **启动或重启 `openviking-server`。** 网关和 OpenViking 共用同一个端口,地址是 `http://127.0.0.1:1933/gateway`。
+3. **在 Studio 中打开网关。** 打开 <http://127.0.0.1:1933/studio/>,在侧边栏选择 **OpenViking 网关**。默认账号还没有[上游](../guides/15-gateway.md#key-terms)时,网关启动时会把服务端的 VLM 配置导入为上游,并创建一份上下文配置。此时“概览”标签页的**快速开始**清单应该已经完成了前两步(见[快速开始清单和快速模式](06-manage-in-studio.md#get-started-checklist))。导入的 Coding Plan 上游需要你确认后才能使用,见[导入 OpenViking 模型配置](07-upstreams.md#import-openviking-model-settings);没有可导入的配置时,按[上游](07-upstreams.md#upstreams)手动添加。
+4. **签发网关密钥。** 在“概览”标签页的**快速模式**卡片中点**一键生成密钥**;也可以手动签发:在“密钥”标签页点**签发密钥**,填写名称,选择上下文配置和上游,然后签发。随后会弹出**复制网关密钥**对话框,显示完整的 `ovgw_…` 密钥。密钥只显示这一次,关闭对话框前务必复制。
+
+网关地址是 `http://127.0.0.1:1933/gateway`。接下来[发送测试请求](#send-a-test-request)。
+
+## 远程服务(使用 API 密钥) {#remote-server-api-keys}
+
+远程服务指通过网络访问、使用 `api_key` 认证的服务。每个人用自己的 OpenViking API 密钥登录 Studio。
+
+不想在服务端主机上运行 init 的话,可以用 root API 密钥登录 Studio,在 OpenViking 网关页面点**开启网关**,代替第 1-3 步;确认对话框里也能生成网关管理密钥。见[在 Server 中启用](../guides/22-gateway-operations.md#enable-it-in-the-server)。
+
+1. **开启网关。** 在服务端主机上运行 `openviking-server init`,绑定地址选择 **Remote (0.0.0.0)**,在 **Enable OpenViking Gateway on the same port?** 处回答 yes。
+2. **决定谁能修改上游。** 接下来的 **Allow users to configure their own gateway upstreams?** 决定谁能修改上游和上下文配置。回答 yes,每个登录的用户都能配置本账号的上游和上下文配置。回答 no,则改由[网关管理密钥](../guides/22-gateway-operations.md#gateway-management-key)把关:init 生成一个以 `ovgm_` 开头的密钥,打印出来并写入 `ov.conf` 的 `gateway.management_key`,只有带着这个密钥的请求才能修改上游和上下文配置。请保存好打印出的密钥,第 6 步要用。
+3. **重启服务。** 网关和 OpenViking 共用同一个端口,地址是 `https://ov.example.com/gateway`。
+4. **准备 OpenViking API 密钥。** 用你自己的用户 API 密钥,或者按[认证](../guides/04-authentication.md)用 root API 密钥创建账号和用户。
+5. **登录 Studio。** 打开 `https://ov.example.com/studio/`,在**连接设置**中填入 API 密钥,然后在侧边栏选择 **OpenViking 网关**,应该能看到“概览”标签页。
+6. **添加上游。** 在“上游”标签页点**添加上游**,选择服务商和客户端使用的协议(下面的测试请求用 Chat Completions),粘贴服务商的 API Key 后保存。然后在上游列表里点**测试**,看到**连接可用**或**模型可用**,就说明网关能连上服务商。如果标签页是只读的,说明设置了网关管理密钥:点**输入网关管理密钥**解锁编辑(见[解锁编辑](06-manage-in-studio.md#unlock-editing)),或者联系部署网关的人。
+7. **创建上下文配置。** 在“上下文配置”标签页点**使用推荐设置创建**,卡片列表里应该出现这份新的上下文配置。
+8. **签发网关密钥**,做法同本地路径第 4 步,签发给你自己。随后会弹出**复制网关密钥**对话框,密钥只显示这一次,请立即复制。要给其他用户签发,见[签发密钥](09-gateway-keys.md#issue-a-key)。
+
+网关地址是 `https://ov.example.com/gateway`,其中 `ov.example.com` 换成你的服务端地址。
+
+## 发送测试请求 {#send-a-test-request}
+
+> **提示**:[确认记忆生效](#confirm-that-memory-works)的第 3 步要等对话停顿 10 分钟才会提取记忆。想更快试用,可以先建一份上下文配置,把**最新回复等待时长**调短(例如 30 秒),用它签发一个密钥,下面的 `GATEWAY_KEY` 就用这个密钥。上下文配置的修改只对之后开始的对话生效(见[修改何时生效](06-manage-in-studio.md#when-changes-take-effect))。
+
+用 curl 发两个请求:第一个列出密钥可用的模型,第二个经网关向模型提一个问题。把 `GATEWAY_URL` 设为你的网关地址(本地服务是 `http://127.0.0.1:1933/gateway`),并把 `<model>` 换成上游提供的模型:
+
+```bash
+export GATEWAY_URL=https://ov.example.com/gateway
+export GATEWAY_KEY='ovgw_...'
+
+curl -s "$GATEWAY_URL/v1/models" -H "Authorization: Bearer $GATEWAY_KEY"
+
+curl -s "$GATEWAY_URL/v1/chat/completions" \
+ -H "Authorization: Bearer $GATEWAY_KEY" \
+ -H "Content-Type: application/json" \
+ -H "X-OpenViking-Session: quickstart-1" \
+ -d '{"model": "<model>", "messages": [{"role": "user", "content": "记住:我喜欢简短的回答。"}]}'
+```
+
+| 命令 | 预期结果 |
+| --- | --- |
+| `GET /v1/models` | 密钥绑定的已启用上游里配置的模型名和别名;密钥限定了可用模型时,只列出允许的那些 |
+| `POST /v1/chat/completions` | 服务商的一次正常回复 |
+
+模型列表不全甚至为空,请求也可能照样成功:模型列表留空的上游接受任意模型名,但不往这个列表里加任何名称。`X-OpenViking-Session` 请求头用来标识对话,带同一个值的下一个请求会接着这段对话往下走,详见[网关如何识别对话](03-connect-clients.md#how-conversations-are-recognized)。
+
+## 确认记忆生效 {#confirm-that-memory-works}
+
+依次确认三件事:请求经过了网关,对话已经保存,新对话里能召回记忆。
+
+1. **请求经过了网关。** 打开“请求日志”标签页,刚才的请求应该显示为**新消息**,状态 200。OpenViking 里有相关内容时,**记忆**列会显示补充的条数,例如 `+3`;全新账号下这一列为空。
+2. **对话已保存。** 用同一个 `X-OpenViking-Session` 值再发一个请求,它的 `messages` 要包含整段对话:你的第一条消息、收到的回复和一条新消息。聊天客户端会自动带上这些内容,用 curl 时要自己补上:
+
+ ```bash
+ curl -s "$GATEWAY_URL/v1/chat/completions" \
+ -H "Authorization: Bearer $GATEWAY_KEY" \
+ -H "Content-Type: application/json" \
+ -H "X-OpenViking-Session: quickstart-1" \
+ -d '{"model": "<model>", "messages": [
+ {"role": "user", "content": "记住:我喜欢简短的回答。"},
+ {"role": "assistant", "content": "<收到的回复>"},
+ {"role": "user", "content": "谢谢。"}]}'
+ ```
+
+ 这个请求一到,第一轮对话就会保存([为什么保存总是晚一轮](01-how-it-works.md#when-conversations-are-saved))。打开 Studio 的**会话**页面,应该能看到一个 `gateway-…` 会话。会话属于密钥所属的用户:如果密钥是为别人签发的,需要在**连接设置**中填入该用户的 OpenViking API 密钥登录后才能看到。
+3. **记忆已提取。** 对话停顿达到**最新回复等待时长**(默认 10 分钟)后,网关提交会话,OpenViking 在后台提取记忆,需要稍等片刻。然后换一个会话值开始新对话,问一个依赖这条记忆的问题,例如“你的回答应该多长?”。**记忆**列应显示召回的条数,回复也应该用上了这条记忆。
+
+如果**记忆**列一直为空,或者看不到会话,见[没有补充记忆](12-troubleshooting.md#no-memory-is-added)和[OpenViking 中看不到对话](12-troubleshooting.md#conversations-do-not-appear-in-openviking)。
+
+## 下一步 {#next-steps}
+
+- [接入客户端](03-connect-clients.md#connect-clients):把 Claude Code、Codex CLI 或聊天应用指向网关。
+- [签发密钥](09-gateway-keys.md#issue-a-key):给其他用户签发各自的网关密钥。
+- [部署与运维](../guides/22-gateway-operations.md):用 Docker Compose、Helm 或独立部署为团队运行网关。
diff --git a/docs/zh/gateway/03-connect-clients.md b/docs/zh/gateway/03-connect-clients.md
new file mode 100644
index 000000000..6424d284f
--- /dev/null
+++ b/docs/zh/gateway/03-connect-clients.md
@@ -0,0 +1,315 @@
+---
+description: 把 Claude Code、Codex、聊天应用、SDK 等客户端接入 OpenViking 网关,并检查接入是否生效。
+---
+
+# 把客户端接入 OpenViking 网关
+
+本页按客户端给出具体配置,以及验证配置是否生效的方法。每个客户端都需要三样东西:网关地址、网关密钥,以及这把密钥绑定的一个已启用上游——它要支持客户端使用的协议,并提供客户端请求的模型。还没有网关密钥?先看[快速上手](02-quickstart.md)。
+
+以下两条限制对所有客户端都适用:
+
+- 客户端不能用订阅账号登录网关。上游需要配置服务商的 API Key,或者接一个订阅反代:Codex 可以通过 CLIProxyAPI 上游使用 ChatGPT 订阅(见[使用 ChatGPT 订阅](#codex-chatgpt-subscription))。其他订阅服务请自行确认其使用条款(另见[使用须知](01-how-it-works.md#what-to-expect))。
+- 使用 Responses 的客户端,每个请求都必须带上完整的对话历史(见[客户端要求](04-openviking-tools.md#client-requirements))。
+
+## 客户端设置一览 {#connect-clients}
+
+网关地址是服务地址加上 `/gateway`。在 Studio 中,OpenViking 网关页面顶部和**接入**标签页都会显示它。下面的示例用 `https://ov.example.com/gateway`,请换成你自己的地址。Anthropic 客户端直接使用网关地址,OpenAI 兼容客户端在后面加 `/v1`,方舟 SDK 加 `/api/v3`。
+
+| 客户端 | 上游协议 | Base URL | 对话识别方式 |
+| --- | --- | --- | --- |
+| [Claude Code](#claude-code) | Anthropic Messages | `https://ov.example.com/gateway` | Claude Code 的会话请求头 |
+| [Codex CLI](#codex-cli) | Responses | `https://ov.example.com/gateway/v1` | Codex 的会话请求头 |
+| [聊天客户端和 SDK](#chat-clients-and-sdks) | Chat Completions(或 SDK 使用的 API) | `https://ov.example.com/gateway/v1` | `X-OpenViking-Session`,需要自己发送 |
+| [Open WebUI](#open-webui) | Chat Completions | `https://ov.example.com/gateway/v1` | 在连接上配置 `X-OpenViking-Session` 请求头 |
+| [OpenCode](#opencode) | Chat Completions、Anthropic Messages 或 Responses | `https://ov.example.com/gateway/v1` | OpenCode 的会话请求头 |
+| [pi](#pi) | Chat Completions、Anthropic Messages 或 Responses | `https://ov.example.com/gateway/v1`(Anthropic Messages 用 `https://ov.example.com/gateway`) | 通常根据对话历史匹配 |
+| [DSH](#dsh) | Chat Completions、Anthropic Messages 或 Responses | `https://ov.example.com/gateway/v1`(Anthropic Messages 用 `https://ov.example.com/gateway`) | 通常根据对话历史匹配 |
+| [火山方舟与 BytePlus 方舟 SDK](#volcano-engine-ark-and-byteplus-modelark-sdks) | 三种均可 | `https://ov.example.com/gateway/api/v3` 或 `https://ov.example.com/gateway/api/compatible` | 取决于客户端发送的请求头 |
+
+最后一列的含义见[网关如何识别对话](#how-conversations-are-recognized)。
+
+## 客户端自带服务商 API Key 时 {#bring-your-own-provider-key}
+
+默认情况下,服务商的 API Key 由网关保管,客户端只需发送网关密钥。[上游](07-upstreams.md#upstreams)也可以把 **API Key 由谁提供**设为**每个客户端自带 API Key**(见[凭证](07-upstreams.md#credentials))。这时客户端仍把网关密钥填在原来填 API Key 的地方,同时在每个请求里用 `X-OpenViking-Upstream-Key` 请求头带上自己的服务商 API Key。在 Studio 中,**接入**标签页的**客户端自带服务商 API Key**卡片会列出哪些上游需要它。
+
+缺了这个请求头,所有请求都会返回 401 `Upstream API key is missing`。各客户端的添加方式:
+
+| 客户端 | 如何发送 `X-OpenViking-Upstream-Key` |
+| --- | --- |
+| Claude Code | `export ANTHROPIC_CUSTOM_HEADERS='X-OpenViking-Upstream-Key: <provider-key>'` |
+| Codex CLI | 在服务商配置里使用 `env_http_headers`,例如 `env_http_headers = { "X-OpenViking-Upstream-Key" = "PROVIDER_API_KEY" }`,并把服务商 API Key 导出为 `PROVIDER_API_KEY` |
+| OpenAI 和 Anthropic SDK | 在客户端上设置 `default_headers`,或在每个请求里传 `extra_headers` |
+| Open WebUI | 加到连接的自定义请求头里,与会话请求头放在一起 |
+
+## Claude Code {#claude-code}
+
+Claude Code 使用 Anthropic Messages,Base URL 为 `https://ov.example.com/gateway`。启动前设置三个环境变量:
+
+```bash
+export ANTHROPIC_BASE_URL=https://ov.example.com/gateway
+export ANTHROPIC_AUTH_TOKEN='<gateway-key>'
+export CLAUDE_CODE_GATEWAY_HINT_HEADERS=1
+```
+
+- 地址不要带 `/v1`,Claude Code 会自己补全路径。
+- `CLAUDE_CODE_GATEWAY_HINT_HEADERS=1` 让 Claude Code 给子 Agent、上下文压缩和后台请求加上标记,网关就不会为它们召回记忆,也不会把它们当作对话轮次保存。
+- Claude Code 发送自己的会话 ID,网关据此识别对话,`--resume` 之后也一样。
+- 上游必须接受 Claude Code 请求的模型名:模型列表留空、列出这些名称,或者用模型别名映射到服务商的模型(见[模型](07-upstreams.md#models))。
+- Claude 订阅登录不能通过网关使用,带订阅令牌的请求会被拒绝。请为上游配置服务商的 API Key。
+- 同时装了 OpenViking 插件时,网关会让出这些对话(见[两者同时使用时](../guides/15-gateway.md#when-both-are-in-use))。只接了 OpenViking MCP 服务器时,网关照常补充记忆,OpenViking 工具交给 MCP 服务器。
+
+配好后,[检查接入是否生效](#check-the-connection)。
+
+## Codex CLI {#codex-cli}
+
+Codex 使用 Responses API,Base URL 为 `https://ov.example.com/gateway/v1`。它每个请求都带完整历史,正好满足网关的要求。在 `~/.codex/config.toml` 中添加一个服务商,两个顶层设置必须写在所有 `[section]` 之前:
+
+```toml
+model_provider = "openviking"
+model = "<model>"
+
+[model_providers.openviking]
+name = "OpenViking Gateway"
+base_url = "https://ov.example.com/gateway/v1"
+wire_api = "responses"
+env_key = "OPENVIKING_GATEWAY_KEY"
+```
+
+然后在运行 Codex 的环境里设置网关密钥:
+
+```bash
+export OPENVIKING_GATEWAY_KEY='<gateway-key>'
+```
+
+- 密钥绑定的上游必须使用 Responses,并提供 `<model>`。
+- Codex 会先尝试 WebSocket 连接,被网关拒绝后自动改用 HTTP。
+- Codex 发送自己的会话 ID,网关据此识别对话,`codex resume` 之后也一样。
+- 遇到不认识的模型名,Codex 可能提示缺少模型元数据,不影响请求。
+- 想用 ChatGPT 订阅代替 API Key,见下一节。
+
+### 使用 ChatGPT 订阅 {#codex-chatgpt-subscription}
+
+Codex 可以经网关使用你的 ChatGPT 订阅。Codex 不会把 ChatGPT 登录信息发给网关,而是由 [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI)(CPA)作为上游接在网关后面:CPA 用你的 ChatGPT 账号登录,再以 Responses API 的形式提供服务。这种用法得到了 OpenAI 的认可:OpenAI Codex 负责人 Tibo 曾[公开介绍](https://x.com/thsottiaux/status/2076119366647894371)过用 CLIProxyAPI 接入 Codex 订阅的做法。
+
+1. 按 CPA 的 README 运行 CPA,并用你的 ChatGPT 账号登录。
+2. 在 Studio 中把 CPA 添加为上游:服务商选*通用*,协议选 Responses,**Base URL** 填 CPA 的地址,API Key 填 CPA 的某个 API 密钥。见[自定义上游](07-upstreams.md#custom-upstreams)。
+3. 签发绑定该上游的网关密钥,再按上文配置 Codex。Codex 仍用网关密钥连接网关,订阅只保存在 CPA 里。
+
+配好后,[检查接入是否生效](#check-the-connection)。
+
+## 聊天客户端和 SDK {#chat-clients-and-sdks}
+
+支持 OpenAI Chat Completions API 的客户端和 SDK 都能接入,Base URL 为 `https://ov.example.com/gateway/v1`。在客户端填写 OpenAI 兼容服务商的地方填入:
+
+```text
+Base URL: https://ov.example.com/gateway/v1
+API key: <gateway-key>
+Model: <model>
+X-OpenViking-Session: <conversation-id>
+```
+
+`X-OpenViking-Session` 请求头可选,但建议发送,它告诉网关请求属于哪段对话。取值在同一段对话内保持不变、不同对话之间互不相同,例如应用里的聊天 ID。不发送时,网关根据历史匹配对话,见[网关如何识别对话](#how-conversations-are-recognized)。
+
+用 OpenAI Python SDK:
+
+```python
+from openai import OpenAI
+
+client = OpenAI(base_url="https://ov.example.com/gateway/v1", api_key="<gateway-key>")
+
+reply = client.chat.completions.create(
+ model="<model>",
+ messages=[{"role": "user", "content": "发布日期最后定在哪天?"}],
+ extra_headers={"X-OpenViking-Session": "chat-42"},
+)
+print(reply.choices[0].message.content)
+```
+
+流式调用 Chat Completions 时,请同时请求返回用量(`"stream_options": {"include_usage": true}`)。否则服务商不报告流式回复的 token 数,Studio 显示不了用量,网关也只能估算上下文窗口用了多少。
+
+另外两种 API 的 SDK 用法相同,前提是上游使用的 API 和 SDK 一致:
+
+- Anthropic SDK 指向 `https://ov.example.com/gateway`。
+- Responses API 使用 `https://ov.example.com/gateway/v1`,每个请求都要带完整历史并设置 `store: false`;其他 Responses 请求直接转发,不补充记忆。
+
+配好后,[检查接入是否生效](#check-the-connection)。
+
+## Open WebUI {#open-webui}
+
+Open WebUI 通过 Chat Completions 接入,Base URL 为 `https://ov.example.com/gateway/v1`。分三步配置:
+
+1. 在 Open WebUI 中打开 Admin Panel → Settings → Connections,添加一个 OpenAI 兼容连接,Base URL 填 `https://ov.example.com/gateway/v1`,密钥填网关密钥。
+2. 给这个连接加上下面的自定义请求头,让每个聊天成为一段独立的对话,并让网关认出 Open WebUI 的后台任务:
+
+ ```json
+ {
+ "X-OpenViking-Session": "{{CHAT_ID}}",
+ "X-OpenViking-Task": "{{TASK}}"
+ }
+ ```
+
+3. 在 Open WebUI 的环境变量中设置 `RAG_SYSTEM_CONTEXT=true`。这样 Open WebUI 会把附件检索结果放进 system 消息,而不是临时改写你这一轮的消息,请求之间的对话历史才能保持稳定。
+
+另外需要注意两点:
+
+- **一个连接密钥只对应一位记忆归属者。** 通过这个连接聊天的所有 Open WebUI 用户,读写的都是密钥背后那位 OpenViking 用户的记忆。要么只让一个人用这个连接,要么接受这些用户共享记忆(见[每人一把密钥](09-gateway-keys.md#one-key-per-person))。
+- Open WebUI 还会通过同一个连接发送后台请求(生成标题、标签和追问建议)。网关能识别标题和摘要请求;如果请求日志里有其他后台任务被标成**新消息**,就把 Open WebUI 的任务模型改成一个不经过网关的连接。
+
+配好后,[检查接入是否生效](#check-the-connection)。
+
+## OpenCode {#opencode}
+
+OpenCode 可以使用 Chat Completions、Anthropic Messages 或 Responses,Base URL 都是 `https://ov.example.com/gateway/v1`。在 `~/.config/opencode/opencode.json` 中添加一个服务商,与已有设置合并:
+
+```json
+{
+ "provider": {
+ "openviking": {
+ "npm": "@ai-sdk/openai-compatible",
+ "name": "OpenViking",
+ "options": {
+ "baseURL": "https://ov.example.com/gateway/v1",
+ "apiKey": "{env:OPENVIKING_GATEWAY_KEY}"
+ },
+ "models": {
+ "<model>": {}
+ }
+ }
+ }
+}
+```
+
+示例用的是 Chat Completions。换用其他协议时改 `npm`,`baseURL` 不变。密钥绑定的上游必须使用你选的协议;Studio 的**接入**标签页会自动填好对应的包:
+
+| 上游协议 | `npm` |
+| --- | --- |
+| Chat Completions | `@ai-sdk/openai-compatible` |
+| Responses | `@ai-sdk/openai` |
+| Anthropic Messages | `@ai-sdk/anthropic` |
+
+把网关密钥导出为 `OPENVIKING_GATEWAY_KEY`,然后在 OpenCode 中选择 `openviking/<model>`。同时装了 OpenViking 的 OpenCode 插件时,网关会让出这些对话。
+
+配好后,[检查接入是否生效](#check-the-connection)。
+
+## pi {#pi}
+
+pi 可以使用 Chat Completions、Anthropic Messages 或 Responses,Base URL 为 `https://ov.example.com/gateway/v1`(Anthropic Messages 用 `https://ov.example.com/gateway`)。在 pi 的模型配置 `~/.pi/agent/models.json` 中添加一个服务商:
+
+```json
+{
+ "providers": {
+ "openviking": {
+ "baseUrl": "https://ov.example.com/gateway/v1",
+ "apiKey": "$OPENVIKING_GATEWAY_KEY",
+ "api": "openai-completions",
+ "models": [
+ {
+ "id": "<model>"
+ }
+ ]
+ }
+ }
+}
+```
+
+示例用的是 Chat Completions。换用其他协议时,按下表设置 `api` 和 `baseUrl`,密钥绑定的上游也必须使用这种协议。Anthropic Messages 的地址不带 `/v1`,因为 Anthropic SDK 会自己补上:
+
+| 上游协议 | `api` | `baseUrl` |
+| --- | --- | --- |
+| Chat Completions | `openai-completions` | `https://ov.example.com/gateway/v1` |
+| Responses | `openai-responses` | `https://ov.example.com/gateway/v1` |
+| Anthropic Messages | `anthropic-messages` | `https://ov.example.com/gateway` |
+
+- `apiKey` 从环境变量 `OPENVIKING_GATEWAY_KEY` 读取网关密钥,启动 pi 前先导出它。开头的 `$` 不能省,否则 pi 会把这个字符串本身当作密钥发送。
+- pi 通常不发送会话请求头,网关根据历史匹配它的对话(见[网关如何识别对话](#how-conversations-are-recognized))。
+- pi 自己的 OpenViking 扩展启用时,网关会让出这些对话,两者选一个即可。
+
+配好后,[检查接入是否生效](#check-the-connection)。
+
+## DSH {#dsh}
+
+[DeepSeek Harness](https://www.npmjs.com/package/@deepseek-ai/dsh)(`dsh`)的模型层基于 pi,`api` 和 Base URL 的取值与 pi 相同:`https://ov.example.com/gateway/v1`,Anthropic Messages 用 `https://ov.example.com/gateway`。在 profile 配置中添加一个服务商;`dsh web` 使用的 profile 是 `web`,所以文件是 `~/.dsh/profiles/web/cordis.patch.yml`:
+
+```yaml
+- id: llm-pi-ai
+ config:
+ providers:
+ openviking:
+ api: openai-completions
+ baseURL: "https://ov.example.com/gateway/v1"
+ apiKeyEnv: OPENVIKING_GATEWAY_KEY
+ models:
+ - id: "<model>"
+```
+
+如果文件里已经有 `llm-pi-ai` 条目,就把 `openviking` 加到它的 `providers` 下,不要再写第二个条目。使用 Responses 或 Anthropic Messages 时,按 [pi 一节的表格](#pi)设置 `api` 和 `baseURL`。
+
+把网关密钥导出为 `OPENVIKING_GATEWAY_KEY`(也就是 `apiKeyEnv` 填的变量名),然后启动 `dsh web`,在模型选择器中选择 `openviking` 服务商下的 `<model>`。
+
+- 也可以在 Web UI 的 Settings → Models → Add model provider → Custom model API 中添加,写入的是同一个文件。
+- DSH 的一个服务商只使用一种协议。要通过多种协议使用网关,就为每种协议各声明一个服务商。
+- 除非 DSH 发送了某个会话请求头,否则网关根据历史匹配它的对话(见[网关如何识别对话](#how-conversations-are-recognized))。
+- 同一个 profile 里装了 [OpenViking 的 DSH 插件](../agent-integrations/17-dsh.md)时,网关会让出这些对话,两者选一个即可。
+
+配好后,[检查接入是否生效](#check-the-connection)。
+
+## 火山方舟与 BytePlus 方舟 SDK {#volcano-engine-ark-and-byteplus-modelark-sdks}
+
+已经接入火山方舟或其海外站 BytePlus 方舟的客户端和 SDK,三种 API 都可以用,只需替换地址,通常换成 `https://ov.example.com/gateway/api/v3`。在 `/gateway` 下,网关既接受方舟自己的路径(`/api/v3/chat/completions`、`/api/v3/responses`、`/api/v3/models` 和 `/api/compatible/v1/messages`),也接受标准的 `/v1` 路径:
+
+| 原地址 | 网关地址 |
+| --- | --- |
+| `https://ark.cn-beijing.volces.com/api/v3` | `https://ov.example.com/gateway/api/v3` |
+| `https://ark.ap-southeast.bytepluses.com/api/v3` | `https://ov.example.com/gateway/api/v3` |
+| `https://ark.cn-beijing.volces.com/api/compatible`(Anthropic 兼容) | `https://ov.example.com/gateway/api/compatible` |
+
+用网关密钥代替方舟的 API Key。以火山方舟 Python SDK 为例:
+
+```python
+from volcenginesdkarkruntime import Ark
+
+client = Ark(base_url="https://ov.example.com/gateway/api/v3", api_key="<gateway-key>")
+```
+
+客户端用哪个路径,只决定它使用哪种 API。请求仍然发往密钥绑定的、使用这种 API 并提供该模型的上游,通常是服务商选为“火山方舟”或“BytePlus 方舟(海外站)”的上游(见[上游](07-upstreams.md#upstreams))。和其他聊天客户端一样,请用 `X-OpenViking-Session` 为每段对话发送一个固定的值。
+
+配好后,[检查接入是否生效](#check-the-connection)。
+
+## 检查接入是否生效 {#check-the-connection}
+
+每配好一个新客户端,都用一段简短的对话验证一次。Open WebUI、OpenCode、pi 和 DSH 尤其需要:它们的配置是依据各自文档中的服务商设置编写的,请当作起点。
+
+1. 在客户端的同一段对话(同一个聊天或同一个 Agent 会话)里发两条消息。应该能正常收到回复。
+2. 在 Studio 中打开**请求日志**标签页。两个请求都应显示为**新消息**,状态码为 200。
+3. 展开这两个请求。它们的**对话**应该相同,**保存**一栏应显示**正常**,表示保存已开启且运行正常。第二条消息到达后第一轮就会保存;要看到它,请以密钥所属用户的身份登录 Studio,在**会话**页面找到 `gateway-…` 会话(见[确认记忆生效](02-quickstart.md#confirm-that-memory-works))。
+
+如果结果不对:
+
+- **看不到任何请求。** 只有到达模型服务商的请求才会记录,说明客户端直接收到了网关返回的错误,见[客户端收到网关返回的错误](12-troubleshooting.md#clients-get-an-error-from-the-gateway)。
+- **两个请求属于不同的对话。** 客户端没有发送会话请求头,且历史也没有匹配上,见[网关如何识别对话](#how-conversations-are-recognized)。
+- **记忆一栏一直是空的。** 全新账号本来就是这样。要完整验证记忆是否生效,按[确认记忆生效](02-quickstart.md#confirm-that-memory-works)操作。
+
+请求日志每一列和每个标签的含义见[请求日志](10-overview-and-requests.md#requests)。
+
+## 网关如何识别对话 {#how-conversations-are-recognized}
+
+对话是网关当作同一次聊天处理的一系列请求:一段对话固定使用同一份上下文配置和同一个上游,并保存到一个 OpenViking 会话,某些情况下改存到新会话,例如客户端改写历史时(见[保存状态](10-overview-and-requests.md#saving-status))。为了判断请求属于哪段对话,网关按以下顺序取第一个出现的请求头:
+
+1. `X-OpenViking-Session`
+2. `thread-id`
+3. `x-claude-code-session-id`(Claude Code)
+4. `x-opencode-session-id`(OpenCode)
+5. `x-session-id`
+6. `session-id`(Codex CLI)
+
+这些请求头都没有时,网关查看历史中最近一条助手回复:如果恰好有一段之前的对话产生过这条回复,请求就并入那段对话,否则开始一段新对话。开场消息相同的两段对话不会因此被合并。普通的一问一答这样就能识别,但重试、重新生成和内容完全相同的对话存在歧义,可能被当成新对话。所以只要客户端允许设置请求头,就发送 `X-OpenViking-Session`。
+
+对话归属于密钥背后的 OpenViking 用户,并按 API 区分。同一用户的两个网关密钥发送相同的会话值,会共享同一段对话;同一个会话值用在另一种 API 上,则是另一段对话。网关转发前会去掉所有 `X-OpenViking-*` 请求头,服务商看不到它们。
+
+请求没有归入已有对话时,记忆照样工作:新消息照常召回,之前补充的记忆也照常原样放回,因为网关是根据消息本身找到这些记忆的。区别在于这个请求会开始一段新对话:它的轮次保存到新的 OpenViking 会话,记忆预算从头计算,并使用密钥当前的上下文配置。
+
+## 下一步 {#next-steps}
+
+- [使用须知](01-how-it-works.md#what-to-expect):客户端改走网关后,哪些行为会变化。
+- [上下文配置](08-context-profiles.md):调整召回多少记忆、是否保存对话。
+- [OpenViking 网关排障](12-troubleshooting.md):处理报错、记忆缺失或对话没有保存等问题。
diff --git a/docs/zh/gateway/04-openviking-tools.md b/docs/zh/gateway/04-openviking-tools.md
new file mode 100644
index 000000000..f62ac5255
--- /dev/null
+++ b/docs/zh/gateway/04-openviking-tools.md
@@ -0,0 +1,215 @@
+---
+description: 让模型通过 OpenViking 网关代为执行的工具检索、读取和写入 OpenViking 记忆,适用于任意客户端。
+---
+
+# 网关中的 OpenViking 工具
+
+开启 OpenViking 工具后,模型在回答过程中自己检索、读取和写入 OpenViking 记忆,工具调用由网关替客户端执行。这项功能面向接不了 OpenViking MCP 服务器的聊天应用和 API 应用;Claude Code、Codex 这类支持 MCP 或有插件的客户端,用 MCP 或插件更合适,因为它们会显示每次工具调用和结果,并在调用前请求确认。在 Studio 中的位置:**上下文配置** → **OpenViking 工具**,以及每个上游的**允许 OpenViking 工具**。
+
+## 让任意客户端拥有 Agentic 记忆 {#agentic-memory-for-any-client}
+
+自动召回是网关替模型猜它需要什么;开启 OpenViking 工具后,由模型自己决定查什么、读什么、记什么。工具由网关执行,客户端的请求里一个工具都没有也能用。
+
+![开启 OpenViking 工具后的一条回复:网关在客户端的请求上附加召回的记忆和 OpenViking 工具定义,模型调用 OpenViking 工具时由网关用该用户的 OpenViking 密钥执行,再把结果接回请求继续询问模型,直到模型给出最终回答;客户端收到的是一条带提示行的连贯回复,工具往返在下一轮被原样放回](../../images/gateway/tool-loop.zh.svg)
+
+- **一条回复里完成多步操作**:网关拦下模型发出的 OpenViking 工具调用,用该用户的 OpenViking 密钥执行,把结果接回再问模型,直到模型不再调用。客户端只收到一条连贯的回复,流式和非流式都支持。
+- **客户端自己的工具照常可用**:同一条回复里,模型可以同时调用 OpenViking 工具和客户端工具(例如 Bash)。客户端工具的调用原样交给客户端执行,照常经过客户端的权限确认。
+- **下一轮还记得**:工具调用和结果不在客户端的历史里,网关把这些往返存下来,下一轮原样放回。模型记得自己查到过什么,[提示词缓存](01-how-it-works.md#replay)也不受影响。
+
+## 不同客户端得到什么 {#what-each-kind-of-client-gets}
+
+| 客户端 | 不经过网关时 | 经过网关并开启 OpenViking 工具后 |
+| --- | --- | --- |
+| 聊天应用,例如 Cherry Studio、Open WebUI | 要用记忆得自己配 MCP 或写工具,普通对话只收发文本。 | 模型自己检索记忆、按 URI 读取原文。勾选 `remember` 后,能记下用户要求记住的事;勾选 `add_resource` 后,能把用户附带的文件导入 OpenViking。不带任何工具的纯聊天模式也能用。 |
+| SDK 脚本、低代码平台 | 一问一答,多步操作要自己写循环。 | 一次请求里完成“检索 → 读取 → grep 精确匹配 → 作答”,代码不用改。 |
+| Claude Code、Codex 等编程 Agent(未装 OpenViking 插件或 MCP) | 有自己的工具,但没有 OpenViking。 | OpenViking 工具和 Bash 等客户端工具在同一条回复里混用。需要逐次确认工具调用时,仍建议用插件或 MCP。 |
+
+## 模型能用哪些工具 {#which-tools-the-model-can-use}
+
+工具清单直接来自你的 OpenViking 服务提供的 MCP 工具,名称加上 `openviking_` 前缀,所以 OpenViking 以后新增的工具也会自动可用。模型能做的事不超出该用户自己的 OpenViking 权限。常用的几类:
+
+| 用途 | 工具 | 模型拿来做什么 |
+| --- | --- | --- |
+| 检索 | `find`、`search`、`grep`、`glob` | 语义检索记忆和资料;按正则或文件名精确查找。 |
+| 浏览和读取 | `list`、`tree`、`read` | 按 URI 展开召回条目的原文,浏览记忆和技能目录。 |
+| 写入 | `remember`、`write`、`edit` | 存一条长期记忆,写入或局部修改记忆文件。 |
+| 导入 | `add_resource`、`add_skill` | 按 URL 导入网页或代码仓库,导入对话附件,用一段文本新建技能,都不需要客户端有 shell。 |
+| 删除和权限 | `forget`、`set_acl` 等 | 永久删除记忆,修改共享资源的访问权限。 |
+
+新建的上下文配置默认勾选哪些工具,见[选择工具](#choose-tools)。另有一项实验性设置 **Agent 自管上下文窗口**,会再给模型两个用于开启新上下文窗口的工具,见[实验性:Agent 自管上下文窗口](05-long-conversations.md#experimental-agent-managed-context-windows)。
+
+## 用户看到什么 {#what-users-see}
+
+模型的文字照常实时流出。开启**显示工具调用**时(默认开启,位于[上下文配置](08-context-profiles.md#context-profiles)的 **OpenViking 工具**部分),每次 OpenViking 工具调用都会在回复中调用发生的位置留下一行提示:
+
+```text
+> OpenViking find: "上次定的发布日期" — done
+> OpenViking read: viking://user/alice/memories/release.md — done
+```
+
+- **提示写什么**:工具名;网关能识别调用对象时,还显示检索的查询词,读取、列出或写入的 URI,或者正在导入的文件或技能。用户看不到完整参数和结果。
+- **何时出现**:流式回复中,调用一开始提示就出现,导入这类耗时的调用进行时,用户也能看到网关在工作;非流式回复在最终消息里带上同样的提示。
+- **放在哪里**:每条提示单独成段。在 Chat Completions 中,提示是回复文本的一部分;在 Anthropic Messages 中,同一轮调用的提示放在同一个文本块里;在 Responses 中,放在同一条助手消息里。
+- **只给用户看**:模型看不到这些提示,它收到的是真实的调用和结果;网关也不把提示保存到 OpenViking。
+- **Token 用量**:客户端收到的用量是这条回复中所有模型调用之和,包括模型使用工具期间额外发起的调用。
+
+### 工具调用提示 {#tool-call-notices}
+
+每次调用结束后,网关在提示末尾补上结果:
+
+| 结果 | 含义 |
+| --- | --- |
+| `done` | 调用完成。 |
+| `failed` | 调用返回了错误。 |
+| `skipped` | 网关拒绝了这次调用、没有执行,例如工具轮数或 token 预算已经用完。 |
+
+要隐藏提示,关闭**显示工具调用**即可。和上下文配置的其他改动一样,它只影响新对话(见[修改何时生效](06-manage-in-studio.md#when-changes-take-effect))。
+
+## 风险和控制点 {#risks-and-controls}
+
+> **警告**:勾选的工具直接执行,不经过客户端的权限确认,写入和删除数据的工具也一样;工具调用提示只在调用之后报告,不是确认步骤。如果用户需要逐次确认工具调用,请改用 OpenViking 插件或 MCP 服务器(见[网关还是插件](../guides/15-gateway.md#gateway-or-plugin))。模型能做的事以该用户自己的 OpenViking 权限为上限。
+
+勾选会修改数据的工具前,先确认能接受这一点。给聊天应用用的配置,建议至少不勾选 `forget` 和 `set_acl`。
+
+管理员能控制的地方:
+
+| 控制点 | Studio 中的位置 | 作用 |
+| --- | --- | --- |
+| **OpenViking 工具**总开关 | **上下文配置** → **OpenViking 工具** | 为使用该配置的对话开启或关闭网关工具。 |
+| **工具**勾选 | **上下文配置** → **OpenViking 工具** | 决定模型能拿到哪些工具,见[选择工具](#choose-tools)。 |
+| **允许 OpenViking 工具** | **上游** → **路由** | 允许上下文配置通过这个上游提供工具。关闭后,进行中的对话也随即停用。 |
+| 工具轮数、总时长和 Token 预算 | **上下文配置** → **OpenViking 工具** → **高级设置** | 限制模型能连续使用工具多久,见[上限](#limits)。 |
+
+## 选择工具 {#choose-tools}
+
+[上下文配置](08-context-profiles.md#context-profiles)中 **OpenViking 工具**部分的**工具**清单,决定模型能拿到哪些 OpenViking 工具。新建的上下文配置默认开启 **OpenViking 工具**,用**使用推荐设置创建**新建的也一样;除了网关已知会修改数据的工具,其余工具默认都勾选:
+
+| 默认状态 | 工具 |
+| --- | --- |
+| 勾选 | `find`、`search`、`grep`、`glob`、`list`、`tree`、`read`、`download`、`list_watches`、`get_acl`、`list_users`、`list_groups`、`health` |
+| 不勾选(会修改数据) | `remember`、`write`、`edit`、`add_resource`、`add_skill`、`forget`、`set_acl`、`cancel_watch` |
+
+想让模型保存记忆就勾选 `remember`,想让它导入网页或附件就勾选 `add_resource`。勾选任何会修改数据的工具之前,请先看[风险和控制点](#risks-and-controls)中的警告。
+
+每个[上游](07-upstreams.md#upstreams)的**允许 OpenViking 工具**默认开启。两个开关都开启时,新对话获得选中的工具,名称加上 `openviking_` 前缀,例如 `openviking_find`、`openviking_read`。工具定义随对话中的每个请求发送,全部工具约占 3,500 个输入 token,所以取消用不到的工具也能省 token。
+
+关于工具清单,还有几点需要知道:
+
+- **清单来源**:**工具**清单来自你的 OpenViking 服务,Studio 会说明每个工具的用途;OpenViking 为工具提供了标注时,还会在旁边显示**只读**或**会修改数据**。OpenViking 把 `search` 标为**会修改数据**,但网关仍默认勾选它。
+- **以后新增的工具**:OpenViking 以后新增的工具会默认可用,已有对话仍沿用开始时的工具清单。已有的上下文配置保留原来的勾选。
+- **root 看到的清单为空**:OpenViking 不允许 root API 密钥调用它的工具,所以 root 查看时,网关用当前账号中某把[网关密钥](09-gateway-keys.md#gateway-keys)背后的 OpenViking 密钥读取清单。账号里还没有网关密钥时,清单可能为空,Studio 显示提示“**签发网关密钥后即可加载工具清单。**”请先签发一把密钥,或者用用户、账号管理员的身份登录后再编辑配置。在此之前保存的配置沿用默认勾选。
+- **`download` 需要 shell**:`download` 返回一条一次性的 `curl` 命令,所以客户端需要有 shell 工具,而且客户端要能访问这条链接。哪些名称算 shell 工具、链接指向哪里,见[通过客户端的 shell 工具](#import-with-a-shell-tool)。
+
+## 客户端要求 {#client-requirements}
+
+三种模型 API 都支持 OpenViking 工具,流式和非流式请求都可以,前提是客户端每轮都回传完整对话:
+
+| 协议 | 客户端要求 |
+| --- | --- |
+| Chat Completions | 回传完整的 `messages` 历史。 |
+| Responses | 使用 `store: false` 和完整的 `input` 历史;下一轮回传本轮返回的全部 `output` 内容,包括 reasoning 和客户端工具调用。`item_reference` 无法还原完整历史。 |
+| Anthropic Messages | 回传完整的 `messages` 历史,保留 thinking 和 signature 块。token 计数请求带相同的工具定义,但不执行工具。 |
+
+模型在同一条回复中同时调用 OpenViking 工具和客户端工具时,网关处理 OpenViking 调用,客户端照常执行自己的工具并回传结果。Responses 支持客户端的 function 和 custom 工具,Anthropic Messages 支持客户端的 tool_use 调用。
+
+依赖服务商端已存状态的 Responses 请求(`previous_response_id`、`conversation`、`background`),以及没有设置 `store: false` 的 Responses 请求,原样转发:既不补充召回的记忆,也不提供 OpenViking 工具。之后查询这些响应时,请求仍然发往创建它们的上游。
+
+## 什么时候不提供工具 {#when-tools-are-not-offered}
+
+即使[上下文配置](08-context-profiles.md#context-profiles)开启了 OpenViking 工具,个别请求发给模型时也可能不带工具。这时在**请求日志**标签页中展开该请求,详情会显示“**未提供:**”加上原因。Studio 显示原因名称,括号里是管理 API 中对应的值(`tool_skip_reason`):
+
+| 原因 | 说明 |
+| --- | --- |
+| **Responses 请求需回传完整对话,并设置 store: false**(`tools_require_full_history`) | Responses 请求需要 `store: false` 和完整 input 历史,不能使用 `item_reference`。 |
+| **这个上游关闭了 OpenViking 工具**(`upstream_tools_disabled`) | 上游关闭了**允许 OpenViking 工具**。 |
+| **请求要求返回多个候选结果(n > 1)**(`tools_multiple_choices`) | 请求要求返回多个候选(`n` 大于 1)。 |
+| **请求要求结构化输出**(`tools_structured_output`) | 请求要求结构化输出(`response_format`、`text.format` 或 `output_config.format`)。 |
+| **客户端传入了非函数类型的工具**(`tools_non_function`) | Chat Completions 客户端传入了 function 以外类型的工具。 |
+| **客户端指定了必须调用的工具**(`tools_forced_choice`) | `tool_choice` 不是 `auto` 或 `none`:例如 `required`、Anthropic 的 `any` 或 `tool`、指定某个函数,或者 Responses 的 `allowed_tools` 这类对象形式。 |
+| **DeepSeek 开启了思考模式,但之前回复的推理内容补不回来**(`deepseek_reasoning_history_required`) | 上游是 DeepSeek,开启了思考模式(标准 Responses 请求没有 `thinking` 字段,按开启处理),而之前的回复发到 DeepSeek 时会缺推理内容。在上游的**路由**部分开启**补全推理内容回传**([说明及补不回的情况](07-upstreams.md#restore-reasoning)),或者发送 `"thinking": {"type": "disabled"}`。 |
+| **客户端已接入 OpenViking 工具**(`tool_name_collision`) | 网关在这段对话剩下的部分不再提供自己的工具(回传的历史里模型已经调用过网关工具的请求仍保留工具)。判断条件见[客户端自己接了 OpenViking 工具时](#client-has-openviking-tools)。 |
+| **这段对话首次需要工具时无法加载 OpenViking 工具清单**(`tools_unavailable`) | 无法从 OpenViking 加载工具清单,也没有之前加载成功的清单。连接恢复后开始新对话。 |
+| **这段对话没有 OpenViking 工具**(`tools_not_selected_at_session_start`) | 上下文配置开启了工具,但这段对话的工具列表为空:配置里一个工具都没选,或者对话在网关升级前就已开始。开始新对话即可。 |
+
+### 何时决定是否提供 {#when-the-decision-is-made}
+
+对话是否带工具,由它第一个能用工具的请求决定(生成标题这类辅助请求不算),之后保持不变,所以修改上下文配置只影响新对话。唯一的例外是关闭:模型还没调用过网关工具时,客户端出现了自己的 OpenViking 工具,例如 MCP 服务器在第一轮之后才连上。
+
+辅助请求、子 Agent 请求和检测到 OpenViking 插件的对话都不带 OpenViking 工具。这类请求如果回传了模型用过这些工具的历史,网关仍附上工具定义,让这段历史保持有效,但拒绝新的 OpenViking 调用。客户端自己的工具在每个请求里都照常可用。
+
+### 客户端自己接了 OpenViking 工具时 {#client-has-openviking-tools}
+
+满足以下任一条件,网关就认为客户端已经接了 OpenViking 工具(`tool_name_collision`):
+
+- MCP 服务名(`server_label`、`mcp_server_name`、`mcp_servers[].name`)含单词 `openviking`。
+- 以 OpenViking 工具名结尾的工具名中也含这个单词,例如 `mcp__claude_ai_OpenViking__search`;连接器的 `authenticate` 工具不算。独占一行列出的延迟加载工具名也算。
+- 带前缀、以 OpenViking 工具名结尾的工具(例如 `mcp__ov__read`),定义中出现 `viking://`。
+- 任一请求中,客户端工具和网关工具同名,因为上游会拒绝重名工具。
+
+误判同样会持续整段对话,开始新对话即可。
+
+## 导入文件和技能 {#import-files-and-skills}
+
+OpenViking 服务提供导入工具(`add_resource`、`add_skill`)、上下文配置也勾选了它们时,模型就能导入资料。按 URL 导入不需要额外条件;导入本地文件则需要客户端有 shell 工具,或者用户消息带附件。上传大小受网关的请求大小上限 `max_body_bytes` 限制(默认 32 MiB,见[副作用](05-long-conversations.md#side-effects))。
+
+### 通过客户端的 shell 工具 {#import-with-a-shell-tool}
+
+shell 工具指名称类似 bash、shell、exec_command、terminal 或 run_command 的客户端工具。导入工具返回一个一次性上传链接,模型再用客户端的 shell 工具上传文件,这一步经过客户端的权限确认。技能目录会先打包成 zip。
+
+上传链接,以及 `download` 返回的下载链接,指向 `public_url` 加 `/gateway/uploads` 或 `/gateway/downloads`。所以 `public_url` 必须是客户端能访问的地址(见[对外地址](../guides/22-gateway-operations.md#public-address)),前面的代理也要像其他路径一样转发这两个路径。没有设置 `public_url` 时,导入失败并提示 "Set gateway.public_url for client uploads and downloads"。把 `mcp_file_links` 设为 `direct` 后,网关原样透传 OpenViking 返回的链接,链接直接指向 OpenViking Server,此时 Server 的 `OPENVIKING_PUBLIC_BASE_URL`(或 `server.public_base_url`)必须是客户端能访问的地址。
+
+### 通过消息附件 {#import-from-an-attachment}
+
+没有 shell 工具时,模型可以导入用户消息里附带的文件,文件可以是 base64 数据,也可以是附件文本,支持 Chat Completions `file` 内容块(`file.file_data`,可以是 base64 或 `data:` URL)、Responses `input_file` 和 Anthropic `document.source` 中内嵌的 `base64`、`text` 数据。Open WebUI 通常只发送提取出的文本,这些文本作为文本文件导入。
+
+附件中的 URL 和服务商的文件 ID 不会被抓取;要导入远程资源,请用导入工具的 URL 参数。
+
+## 上限 {#limits}
+
+工具轮数、总时长和 Token 预算默认都不限:和 Agent 自己的工具循环一样,模型会一直使用 OpenViking 工具直到完成。在 Studio 中,这些上限位于**上下文配置** → **OpenViking 工具** → **高级设置**,字段留空表示不限:
+
+| 设置 | 默认值 | 达到上限时 |
+| --- | --- | --- |
+| **每次请求的工具轮数** | 不限 | 拒绝之后的 OpenViking 调用,模型用已有结果和客户端自己的工具继续。 |
+| **单次调用超时** | 30 秒 | 这次调用向模型返回错误。 |
+| **结果大小上限** | 65,536 字节 | 结果被截断。 |
+| **总时长** | 不限 | 请求失败,报错 "Hidden tool request timed out",见[失败处理](#failure-handling)。 |
+| **Token 预算** | 不限 | 拒绝之后的 OpenViking 调用,模型用已有结果和客户端自己的工具继续。这不是计费上限,最终回答可能超出它。 |
+
+API 名称和取值范围见[上下文配置的设置](13-configuration.md#context-profile-settings)。
+
+> **注意**:非流式请求在客户端断开后仍会继续执行,所以客户端发送非流式请求时,请设置**总时长**。流式请求中,用户可以随时中断回复,客户端断开后网关也会停止。
+
+Token 预算只计算模型使用 OpenViking 工具时新增的调用、结果和后续生成内容,客户端已有的对话、工具定义和图片不计入。网关保留客户端设置的回答长度上限(`max_tokens`、`max_completion_tokens` 或 `max_output_tokens`)。
+
+想知道某个请求用了多少,在**请求日志**标签页中展开它:**OpenViking 工具**一项会显示轮数、额外模型调用次数和增加的 Token 数;预算用完、后续调用被拒绝时,还会显示**工具 Token 预算已用完**。
+
+这几项默认值改为“不限”之前保存的上下文配置仍保留原来的值(5 轮、120 秒、100,000 token),清空字段即可取消限制。
+
+## 失败处理 {#failure-handling}
+
+单次 OpenViking 调用失败时,模型收到错误结果,可以据此继续回答。只有以下情况会让整个回答失败:
+
+- 服务商拒绝了后续的模型请求。
+- 模型调用了这段对话里没有提供的 OpenViking 工具,或者 OpenViking 调用被拒绝后仍坚持调用。
+- **Hidden tool request timed out**:OpenViking 工具的往返超过了上下文配置中工具的**总时长**;没有设置总时长时,是往返中某次模型请求超过了 `upstream_timeout_seconds`。
+
+这时客户端收到错误,请求日志显示 **OpenViking 工具调用失败**(`hidden_tool_loop_failed`)。错误的形式取决于请求类型:
+
+| 请求 | 客户端收到什么 |
+| --- | --- |
+| 流式 | 流以错误事件结束:Responses 是 `response.failed`,Chat Completions 和 Anthropic Messages 是类型为 `gateway_tool_error` 的 `error`。此时 HTTP 状态码已经是 200。 |
+| 非流式,服务商拒绝了后续请求 | 原样返回服务商的错误内容和状态码。 |
+| 非流式,超时 | 504(`gateway_http_504`)。 |
+| 非流式,其他失败 | 502,响应体为 `{"reason": "gateway_http_502", "detail": "..."}`。 |
+
+另外两种情况:
+
+- **某个上游反复失败**:关闭它的**允许 OpenViking 工具**。用过这些工具的 Claude 对话可能随之出现**工具历史无法继续使用**(`hidden_tool_history_unavailable`):之前的思考内容无法继续使用,网关已将其去掉。可以按请求详情中的停用原因恢复设置,或者开始新对话。
+- **重试**:重试的工具调用复用第一次调用的结果,中断的写入操作不会自动重做。
+
+## 下一步 {#next-steps}
+
+- [上下文配置](08-context-profiles.md#context-profiles):为每类客户端一起配置召回、保存和工具。
+- [文件导入或下载失败](12-troubleshooting.md#file-imports-or-downloads-fail):排查上传和下载链接的问题。
+- [上下文配置的设置](13-configuration.md#context-profile-settings):各项工具设置的 API 名称和取值范围。
diff --git a/docs/zh/gateway/05-long-conversations.md b/docs/zh/gateway/05-long-conversations.md
new file mode 100644
index 000000000..f5b13674e
--- /dev/null
+++ b/docs/zh/gateway/05-long-conversations.md
@@ -0,0 +1,166 @@
+---
+description: OpenViking 网关如何压缩长对话、要设置哪个上下文窗口,以及压缩的代价。
+---
+
+# 网关中的长对话
+
+本页写给配置上下文配置和上游的管理员,也写给长对话被截断或被服务商以过长为由拒绝的用户。读完后你会知道网关何时、如何为长对话生成摘要,压缩后模型收到什么,以及要付出什么代价。最先要检查的是模型的[上下文窗口](#context-window):没有设置时,网关按 1,000,000 token 计算。
+
+## 压缩做什么 {#long-conversations}
+
+[压缩](../guides/15-gateway.md#key-terms)让对话始终不超出模型的上下文窗口(单次请求最多能容纳的 token 数),默认开启。对话接近窗口上限时,由同一个模型为目前为止的对话写一份摘要,此后截断点之前的全部内容都由这份摘要替代。客户端里显示的历史不受影响。开启了保存对话、模型也能用 OpenViking 的 `grep` 和 `read` 工具时,摘要末尾会附上[查找被压缩内容](#finding-what-was-cut)的方法。
+
+在 Studio 中的位置:**上下文配置** → **长对话**。
+
+| 设置 | 默认值 | 作用 |
+| --- | --- | --- |
+| **压缩** | 开启 | 对话接近上下文窗口时,用摘要替换较早的部分。 |
+| **压缩时机** | 窗口的 0.9 | 窗口用到多大比例时开始压缩。 |
+| **摘要长度上限** | 8,000 token | 模型写一份摘要最多能用多少 token。 |
+| **默认上下文窗口** | 未设置(按 1,000,000 token 计算) | 上游没有列出的模型用这个窗口,见[设置模型的上下文窗口](#context-window)。 |
+| **Agent 自管上下文窗口** | 关闭 | 实验性功能,由模型自己开启新窗口,见[下文](#experimental-agent-managed-context-windows)。 |
+
+对话会一直沿用开始时的上下文配置,所以修改配置只影响新对话,见[修改何时生效](06-manage-in-studio.md#when-changes-take-effect)。取值范围和 API 字段名见[配置参考](13-configuration.md#context-profile-settings)。
+
+## 何时压缩 {#when-it-compacts}
+
+每收到一条新的用户消息或一个工具步骤(客户端回传自己工具执行结果的请求,即[请求类型](10-overview-and-requests.md#request-types)中的**工具步骤**),网关都估算一次窗口用量:取服务商为这段对话上一次回复报告的 token 用量,加上之后新增消息的估算值。估算值达到**压缩时机**(默认是窗口的 0.9)时,网关先压缩,再转发请求。
+
+例外情况:
+
+- **服务商没有报告用量。** 拿不到用量时(例如流式 Chat Completions 没有设置 `stream_options.include_usage`),网关估算整个请求。
+- **不触发压缩的请求。** 辅助请求、子 Agent 请求和 Token 计数请求不会触发压缩。
+- **OpenViking 工具往返不检查。** 网关只在请求到达时检查窗口用量,所以它在一次请求内部代为执行的 OpenViking 工具往返不会被压缩。工具轮数和 Token 预算默认都不限;要让单次请求不超出窗口,请设置**每次请求的工具轮数**或 **Token 预算**(见[上限](04-openviking-tools.md#limits))。
+
+## 设置模型的上下文窗口 {#context-window}
+
+网关要知道每个模型的上下文窗口有多大,才能及时压缩。它按以下顺序取第一个设置了的值:
+
+1. 上游**上下文窗口**中该模型的条目,按发给上游的模型名(别名换算之后)匹配。
+2. 上下文配置的**默认上下文窗口**。
+3. 都没有设置时,按 1,000,000 token 计算。
+
+模型的窗口小于 1,000,000 token 时,请设置前两项之一。否则网关压缩得太晚,还没等到压缩,服务商就会以对话过长为由拒绝请求。如果你没有权限修改上游或上下文配置,请联系负责管理网关的人,见[谁能修改什么](06-manage-in-studio.md#who-can-change-what)。
+
+设置并确认模型的窗口:
+
+1. 在 Studio 中打开**上游**,编辑对应上游,在**模型** → **上下文窗口**中添加模型名及其窗口大小(单位为 token,至少 1,024)。上游设置保存后立即生效。如果想让这个上游没列出的所有模型都用同一个窗口,改为在**上下文配置** → **长对话**中设置**默认上下文窗口**,这只对新对话生效。
+2. 发一条消息,然后在**请求日志**标签页展开这条请求。**上下文窗口**一行应显示“约 … / *N* Token”,*N* 就是你填的窗口大小。
+
+## 摘要怎么生成 {#how-the-summary-is-written}
+
+网关向同一个上游、同一个模型额外发一次非流式请求。客户端的系统提示词、工具和思考设置保持不变,所以大部分内容能命中服务商的[提示词缓存](01-how-it-works.md#replay)。纯文本摘要做不到的设置会被去掉:强制的工具选择改为不调用工具,结构化输出格式和停止序列也不保留。
+
+这次请求包含截断点之前的对话,以及一条让模型为自己写摘要的指令。之前的摘要会并入新摘要。摘要要覆盖:
+
+- 用户的目标和最新请求的原文;
+- 关键决定和当前进度;
+- 文件、路径和标识符;
+- 出过的错误和修正;
+- 未完成的事项;
+- 最近几次工具结果里的要点。
+
+摘要是纯文本,最长**摘要长度上限**(8,000)个 token。思考内容也计入输出上限,而有些模型(如 DeepSeek V4.1)即使请求里没有思考设置也会默认思考,所以网关总在摘要长度上限之外再留 16,000 token 的输出余量;客户端手动指定了思考预算时,改为加上这份预算。这次请求和其他请求一样由服务商计费。
+
+## 压缩之后模型收到什么 {#what-the-model-receives-afterwards}
+
+截断点的位置取决于请求类型:
+
+| 请求 | 截断点 | 模型收到的内容 |
+| --- | --- | --- |
+| 新的用户消息 | 紧挨在这条消息之前 | system 和 developer 消息、作为一条用户消息的摘要,以及这条新消息 |
+| 工具步骤 | 最近一次工具结果之后 | system 和 developer 消息,以及摘要;模型从摘要出发继续完成任务 |
+
+摘要消息开头说明网关替换了对话较早的部分、这段内容不是用户写的;结尾附上这段对话开头的网关说明和用户画像,所以压缩后它们仍然保留。
+
+之后凡是重发这段历史的请求,包括辅助请求和 Token 计数请求,都做同样的替换;子 Agent 通常发送自己单独的历史,不受影响。每次压缩让服务商缓存在截断点失效一次,之后照常命中。
+
+**截断点之前的原文一概不保留**,最近几轮也一样。模型之前的回复和其中的思考内容都依赖被替换掉的历史,只保留一部分会破坏 Claude 的思考签名。截断点之后生成的内容照常发送,包括思考内容。
+
+### 查找被压缩的内容 {#finding-what-was-cut}
+
+对话本身仍保存在 OpenViking 里。开启了**保存对话**、这段对话也提供了 `openviking_grep` 和 `openviking_read` 工具时,摘要末尾会附上查找方法:
+
+- 这段对话对应的 OpenViking 会话(`viking://user/<user_id>/sessions/<session_id>/`),以及会话中消息的存放位置;
+- 检索步骤:先用具体的关键词 grep 会话,拿到行号,再读取匹配位置前后的内容。
+
+截断点落在一轮中间时,截断点之前的部分会立即保存到 OpenViking,模型在这一轮里就能检索到。
+
+## 在请求日志中查看压缩 {#see-compaction-in-the-request-log}
+
+在**请求日志**标签页展开一条请求(见[请求日志](10-overview-and-requests.md#requests)),**上下文窗口**一行会显示:
+
+| 显示内容 | 含义 |
+| --- | --- |
+| 约 *X* / *Y* Token(*P*) | 估算的窗口用量,以及网关采用的窗口大小 *Y* |
+| 发送时较早的历史已被替换 | 这次请求用摘要替代了截断点之前的历史 |
+| 生成了约 *N* Token 的摘要,用时 *T* | 这次请求触发了压缩,写摘要用了 *T* |
+| 压缩失败(*原因*),已发送完整历史 | 见[压缩失败时](#when-compaction-fails) |
+| 摘要已保留,但用量仍达到压缩时机(`still_over_threshold`) | 摘要已写好并用上,但对话仍占满窗口,见[压缩失败时](#when-compaction-fails) |
+
+## 压缩失败时 {#when-compaction-fails}
+
+摘要请求失败,或者回复里调用了工具、内容为空、因长度上限被截断时,网关改为发送完整历史。请求详情会显示**压缩失败**及原因,并且 60 秒内不再为这段对话尝试压缩。
+
+只有一种情况会保留摘要:摘要写完后用量仍达到**压缩时机**(例如系统提示词和工具本身就占了窗口的大部分)。这时网关照常使用这份摘要,同时记一次失败,同样等 60 秒再尝试。
+
+各个原因的含义和处理方法见[长对话超出上下文长度](12-troubleshooting.md#long-conversations-hit-the-context-limit)。
+
+## 副作用 {#side-effects}
+
+**不再生成 Working Memory 摘要。** 摘要由对话所用的模型生成,不使用 OpenViking 的会话摘要。网关新建的 OpenViking 会话都关闭了 Working Memory:提交时照常归档消息、提取记忆,只是不生成会话摘要。
+
+**记忆预算重新计算。** 每压缩一次,**单个上下文窗口预算**(见[召回记忆](08-context-profiles.md#recall-memory))就重新计算,截断点之前补充过的记忆可能再次补充。
+
+**客户端仍发送完整历史。** 网关压缩后,客户端还是发送完整历史,网关在每个请求里替换截断点之前的部分。客户端看到的用量很小,所以按用量决定何时压缩的客户端很少再自己压缩。
+
+**特别长的会话可能超出请求大小上限。** 客户端的历史越来越长,特别长的会话最终可能超出请求大小上限:请求体超过 32 MiB 会被拒绝,返回 HTTP 413(见[客户端收到网关返回的错误](12-troubleshooting.md#clients-get-an-error-from-the-gateway))。运维人员可以用 `max_body_bytes` 调整这个上限(见[网关字段](13-configuration.md#gateway-fields));网关前面的反向代理允许的请求体也不能比它小(见[反向代理和 HTTPS](../guides/22-gateway-operations.md#reverse-proxy-and-https))。
+
+**客户端自己压缩会换到新会话。** 客户端压缩或编辑历史后,网关把新历史保存到新的 OpenViking 会话。检索工具可用时,新历史开头的网关说明会告诉模型之前的会话在哪里。
+
+## 实验性:Agent 自管上下文窗口 {#experimental-agent-managed-context-windows}
+
+开启 **Agent 自管上下文窗口**(默认关闭)后,由模型自己决定何时开启新的上下文窗口,并自己写交接笔记,不必等网关生成摘要。网关会给模型两个工具,并在窗口快满时提醒它。这项设置只对能使用 [OpenViking 工具](04-openviking-tools.md#agentic-memory-for-any-client)的对话生效,其他对话照常[压缩](#long-conversations);开启压缩时,如果模型一直不开新窗口,压缩仍会兜底。
+
+在 Studio 中的位置:**上下文配置** → **长对话** → **Agent 自管上下文窗口**(标有**实验性**),以及**软提醒时机**(0.7)和**硬提醒时机**(0.85)。效果取决于所用的模型,后续版本中的行为也可能调整。
+
+### 模型多了什么 {#what-the-model-gets}
+
+两个额外的工具。它们不在上下文配置的**工具**清单里,只由这项设置控制。
+
+| 工具 | 作用 |
+| --- | --- |
+| `openviking_new_context(reason, notes, next_steps)` | 开启新窗口,`next_steps` 可省略。 |
+| `openviking_context_remaining()` | 返回窗口序号、已用和剩余 token 的估算值、本窗口内的用户轮数、距用户上一条消息的时间,以及一句建议。 |
+
+`openviking_new_context` 必须在一轮里单独调用;和其他工具同一轮调用时,这一轮的每个调用都返回错误,窗口不重置。网关在本次请求里已经在同一位置替换过上下文(例如刚压缩过)时,它同样返回错误。
+
+模型还会看到:
+
+- **开头的网关说明里多一行**,告诉模型它用这两个工具自己管理上下文窗口。
+- **一行状态**:每条新的用户消息之后,记忆块末尾附上 `[context-status] window wN · ~X/Y tokens (P%) · T since your previous message`。
+- **软提醒**:窗口用到**软提醒时机**(0.7)时,网关提醒一次,要求模型做完当前这一步就开启新窗口,并在交接笔记里记下之后要用的确切路径、行号和取值。
+- **硬提醒**:用到**硬提醒时机**(0.85)时,要求模型立即开启新窗口,此后每一步都重复,直到模型开启新窗口或压缩接手。
+
+提醒附在新的用户消息上,工具步骤里则附在客户端回传的工具结果上;网关自己执行的 OpenViking 工具往返之间不加提醒。
+
+### 模型开启新窗口时 {#when-the-model-starts-a-new-window}
+
+模型调用 `openviking_new_context` 后,网关把目前为止的对话换成一个窗口头,模型在同一条回复里接着工作。窗口头依次包含:
+
+1. 这是模型开启的第 N 个窗口,内容不是用户写的;
+2. reason、notes 和 next_steps;
+3. 用户最新一条消息的原文;
+4. 检索之前窗口的方法(条件和[压缩](#finding-what-was-cut)时相同);
+5. 这段对话开头的网关说明。
+
+之后的请求会根据客户端的历史重建同一个窗口。重置之前的内容会立即保存到 OpenViking,之后仍可检索;reason 和 notes 只出现在窗口头里,不保存到 OpenViking。每次重置让服务商缓存失效一次,但不需要摘要请求。
+
+在请求日志中,每条请求的**上下文窗口**一行会显示窗口序号(“第 *N* 个窗口,由模型管理”),模型开启了新窗口时显示“模型开启了新窗口”,还会显示模型收到了哪种提醒(“已提醒模型尽快开启新窗口”或“已要求模型立即开启新窗口”)。
+
+## 下一步 {#next-steps}
+
+- [长对话超出上下文长度](12-troubleshooting.md#long-conversations-hit-the-context-limit):每种压缩失败原因的含义和处理方法。
+- [模型](07-upstreams.md#models):上游的**上下文窗口**和其他模型设置在哪里。
+- [什么是上下文配置](08-context-profiles.md#context-profiles):上下文配置的其他分区及默认值。
+- [上限](04-openviking-tools.md#limits):限制单次请求的工具轮数和 token。
diff --git a/docs/zh/gateway/06-manage-in-studio.md b/docs/zh/gateway/06-manage-in-studio.md
new file mode 100644
index 000000000..219fe4467
--- /dev/null
+++ b/docs/zh/gateway/06-manage-in-studio.md
@@ -0,0 +1,95 @@
+---
+description: Studio 中 OpenViking 网关页面的使用方法:各标签页、谁能修改什么、如何解锁,以及修改何时生效。
+---
+
+# 在 Studio 中管理 OpenViking 网关
+
+本页面向在 Studio 里使用网关页面的人,说明各标签页的用途、谁能修改什么,以及保存的修改何时生效。用你的 OpenViking API 密钥打开 Studio([本地 dev 模式](02-quickstart.md#local-server-no-api-key)的服务无需密钥),在侧边栏选择 **OpenViking 网关**;独立部署的网关在自己的 `/studio/` 下提供 Studio。上游和上下文配置由同一 OpenViking 账号下的所有用户共享,网关密钥和请求日志则属于各个用户。
+
+## Studio 标签页 {#studio-tabs}
+
+网关页面共有六个标签页,每行都链接到详细说明该标签页的文档。
+
+| 标签页 | 用途 | 数据归属 | 详见 |
+| --- | --- | --- | --- |
+| **概览** | 一眼看清运行状况:请求数、缓存命中率、召回的记忆、OpenViking 状态和降级请求。第一个请求到达之前,这里显示**快速开始**清单。 | 自己的请求;账号管理员和 root 看到整个账号的 | [概览](10-overview-and-requests.md#overview)、[快速开始清单](#get-started-checklist) |
+| **上游** | 添加、编辑、测试和导入网关转发请求的模型端点。 | 账号内共享 | [上游](07-upstreams.md#upstreams) |
+| **上下文配置** | 新建和编辑上下文配置:召回、保存、长对话和 OpenViking 工具。 | 账号内共享 | [上下文配置](08-context-profiles.md#context-profiles) |
+| **密钥** | 签发和吊销网关密钥;账号管理员和 root 还能删除某个用户的网关数据。 | 自己的密钥;账号管理员和 root 管理整个账号的 | [网关密钥](09-gateway-keys.md#gateway-keys) |
+| **请求日志** | 每个模型请求的记录,包括补充的记忆、Token 用量、问题和保存状态。 | 自己的请求;账号管理员和 root 看到整个账号的 | [请求日志](10-overview-and-requests.md#requests) |
+| **接入** | 网关地址,以及各客户端可直接复制的配置。 | 所有人相同 | [接入客户端](03-connect-clients.md#connect-clients) |
+
+## 谁能修改什么 {#who-can-change-what}
+
+能否修改[上游和上下文配置](../guides/15-gateway.md#key-terms),取决于一项部署设置:[网关管理密钥](../guides/22-gateway-operations.md#gateway-management-key)。默认不设置,是否设置由部署网关的人决定。
+
+| Studio 中的操作 | 没有设置管理密钥 | 设置了管理密钥 |
+| --- | --- | --- |
+| 查看上游和上下文配置,并在签发密钥时选用 | 本账号所有登录用户 | 所有登录用户;只读视图看不到上游的 API Key 和请求头 |
+| 添加、修改或删除上游和上下文配置 | 本账号所有登录用户 | 必须先[解锁编辑](#unlock-editing),账号管理员和 root 也不例外 |
+| 测试上游(连接测试或模型测试) | 本账号所有登录用户 | 必须先解锁;只读时不显示**测试**按钮 |
+| 导入 OpenViking 模型配置(仅限嵌入式部署) | 只有 root,包括本地 dev 模式 | 必须先解锁 |
+| 签发网关密钥 | 用户给自己签发;账号管理员可给本账号的用户签发;root 先在侧边栏切换账号 | 同左,管理密钥不额外授予任何权限 |
+
+测试之所以需要写权限,是因为测试会使用已存的凭证,模型测试还会被服务商计费。签发密钥的细节见[网关密钥](09-gateway-keys.md#gateway-keys);包括管理 API 在内的完整规则见[权限矩阵](../api/25-gateway.md#credentials-and-account-scope)。
+
+如果还没有可用的上游或上下文配置、自己又无权修改,**快速开始**清单会显示正在等待网关管理员添加。这时请联系部署网关的人。
+
+## 解锁编辑 {#unlock-editing}
+
+设置了[网关管理密钥](../guides/22-gateway-operations.md#gateway-management-key)后,“上游”和“上下文配置”标签页默认只读,需要在当前浏览器标签页里解锁。账号管理员或 root 的 API 密钥不能解锁,网关密钥(`ovgw_…`)也不行。
+
+1. 在“上游”或“上下文配置”标签页的只读提示中,点**输入网关管理密钥**。
+2. 粘贴管理密钥,点**解锁**。`openviking-server init`、`openviking-gateway init` 和 Studio 的**开启网关**生成的密钥都以 `ovgm_` 开头;对话框里的**在哪里找?**列出了它的存放位置。
+3. 页面提示“已解锁,现在可以修改上游和上下文配置”,页头显示“可修改上游和上下文配置”和**锁定**按钮。
+
+解锁只对当前浏览器标签页有效,直到你点**锁定**或关闭这个标签页。服务端更换管理密钥后,Studio 会自动锁定,并提示“网关管理密钥已失效,上游和上下文配置恢复为只读。”如果没人知道密钥,见[忘记网关管理密钥](../guides/22-gateway-operations.md#lost-the-management-key)。
+
+## 快速开始清单和快速模式 {#get-started-checklist}
+
+第一个请求到达之前,“概览”标签页上会显示**快速开始**清单,按顺序列出四步:**添加上游**、**创建上下文配置**、**签发网关密钥**、**接入客户端**。客户端发出第一个请求后,清单自动隐藏。
+
+还没有任何[网关密钥](../guides/15-gateway.md#key-terms)时,清单里还有一张**快速模式**卡片,点**一键生成密钥**即可完成前三步:
+
+| 步骤 | 快速模式做什么 |
+| --- | --- |
+| 上游 | 沿用已有的可用上游;一个都没有时,把 OpenViking 自身的模型配置(`ov.conf` 里的 VLM)[导入](07-upstreams.md#import-openviking-model-settings)为上游。 |
+| 上下文配置 | 沿用已有的上下文配置;一个都没有时,用推荐设置新建一份,名为“默认”。 |
+| 密钥 | 为当前用户签发一个名为“快速模式”的密钥,绑定所有可用上游。本地 dev 模式以外,root 改为在签发对话框里选择密钥归属的用户。 |
+
+同时满足以下条件的上游才算可用:
+
+- 已启用;
+- API Key 由网关保管(没有设为**每个客户端自带 API Key**),并且已经保存了密钥;
+- 至少列出一个模型或别名(**模型**列表为空的上游不算,所以即使已经有这样的上游,快速模式也会导入模型配置);
+- 不是仍被[拦截](07-upstreams.md#blocked-upstreams)的 [Coding Plan 上游](07-upstreams.md#coding-plan-keys)。
+
+例外情况:
+
+- 导入后仍没有网关能直接转发的模型时,卡片会说明原因,这时请在第 1 步(**添加上游**)手动添加上游。
+- 设置了管理密钥、而快速模式需要新建上下文配置或导入模型时,卡片会先要求你用管理密钥解锁。
+- 只有部分用户能导入模型配置:未设置管理密钥时是 root(本地 dev 模式下任何人都可以),设置了管理密钥时是用它解锁的人;独立部署的网关则完全无法导入。不能导入时,只有已经存在可用上游才会显示这张卡片。
+
+## 修改何时生效 {#when-changes-take-effect}
+
+上游或上下文配置保存后,会作用于所有使用它的网关密钥,不需要重新签发密钥。区别只在于已经开始的[对话](../guides/15-gateway.md#key-terms)能不能用上修改:
+
+| 修改内容 | 何时生效 |
+| --- | --- |
+| 除优先级外的任何上游设置,例如 API Key、模型、**启用** | 立即生效,进行中的对话也一样。停用上游会对它的对话产生什么影响,见[路由](07-upstreams.md#routing)。 |
+| 上游优先级 | 只对之后开始的对话生效。进行中的对话只要原来的上游还能服务,就一直留在那里。 |
+| 任何上下文配置 | 只对之后开始的对话生效。 |
+| 网关密钥 | 密钥不能编辑。要更换密钥的上下文配置、上游、允许的模型或归属用户,请签发新密钥并吊销旧密钥,见[签发之后](09-gateway-keys.md#after-issuing)。 |
+
+对话在第一个请求时记下当时的上下文配置并一直沿用,因为中途改变模型看到的内容会破坏服务商的[提示词缓存](01-how-it-works.md#replay)。所以客户端多快能用上新的上下文配置,取决于它多久开始一次新对话:
+
+- 每次聊天都新开对话的客户端,很快就能用上新设置。
+- Claude Code、Codex 以及发送固定会话请求头的客户端,会把一段对话延续很多天。它们一直沿用旧设置,直到开始新对话,或者这段对话闲置满 30 天(`session_ttl_days`),此时网关会删除这段对话的状态。
+
+网关如何区分不同的对话,见[网关如何识别对话](03-connect-clients.md#how-conversations-are-recognized)。
+
+## 下一步 {#next-steps}
+
+- [OpenViking 网关快速上手](02-quickstart.md):从空白的网关开始,拿到可用的密钥并发出测试请求。
+- [网关管理密钥](../guides/22-gateway-operations.md#gateway-management-key):设置、更换或重置保护上游和上下文配置的密钥。
+- [Studio 显示设置卡片](12-troubleshooting.md#studio-shows-a-setup-card):Studio 显示设置卡片、看不到网关标签页时怎么办。
diff --git a/docs/zh/gateway/07-upstreams.md b/docs/zh/gateway/07-upstreams.md
new file mode 100644
index 000000000..0521f95d6
--- /dev/null
+++ b/docs/zh/gateway/07-upstreams.md
@@ -0,0 +1,230 @@
+---
+description: 添加和配置 OpenViking 网关转发请求的模型服务地址。
+---
+
+# 管理网关上游
+
+本页面向负责添加和修复上游(OpenViking 网关转发请求的模型服务接口)的人:先照步骤添加一个一次就能用的上游,再按 Studio 编辑页的顺序查阅每个字段。在 Studio 中:**上游**标签页。添加、修改和测试上游需要写权限,见[谁能修改什么](06-manage-in-studio.md#who-can-change-what)。
+
+## 什么是上游 {#upstreams}
+
+上游是网关转发请求的一个模型服务接口,只使用一种 API。网关不在 API 之间转换,所以客户端用到几种 API,就要添加几个上游,即使它们来自同一家服务商:
+
+| 协议 | 使用者 |
+| --- | --- |
+| Anthropic Messages | Claude Code 和 Anthropic SDK |
+| Chat Completions | 大多数聊天应用和 SDK |
+| Responses | Codex CLI,前提是每个请求都携带完整历史(见[客户端要求](04-openviking-tools.md#client-requirements)) |
+
+上游由整个账号共享,但一个[网关密钥](09-gateway-keys.md#gateway-keys)只能访问签发时选中的上游。
+
+在编辑页选择服务商后,会自动填入它的默认 Base URL:
+
+| 服务商 | 协议 | 默认 Base URL |
+| --- | --- | --- |
+| 通用 | 三种都有 | 无,自己填写 |
+| Anthropic | Anthropic Messages | `https://api.anthropic.com` |
+| OpenAI | Chat Completions、Responses | `https://api.openai.com/v1` |
+| DeepSeek | 三种都有 | `https://api.deepseek.com`;Anthropic Messages 为 `https://api.deepseek.com/anthropic` |
+| 火山方舟 | 三种都有 | Chat Completions 和 Responses 为 `https://ark.cn-beijing.volces.com/api/v3`;Anthropic Messages 为 `https://ark.cn-beijing.volces.com/api/compatible` |
+| BytePlus 方舟(海外站) | 三种都有 | Chat Completions 和 Responses 为 `https://ark.ap-southeast.bytepluses.com/api/v3`;Anthropic Messages 为 `https://ark.ap-southeast.bytepluses.com/api/compatible` |
+
+## 添加上游 {#add-an-upstream}
+
+1. 在**上游**标签页点**添加上游**,打开**新建上游**编辑页。页面分为**接口**、**凭证**、**模型**和**路由**四部分。
+2. 在**接口**中填写**名称**,选择**服务商**和客户端所用的**协议**。**Base URL** 下方的**请求将发往**应显示服务商接口的完整地址,例如 `https://api.openai.com/v1/chat/completions`。
+3. 在**凭证**中保持**由网关保管 API Key**,粘贴服务商的 **API Key**。
+4. 在**模型**中列出客户端会请求的模型名,留空则接受任意模型名。窗口小于默认值的模型,要在**上下文窗口**里加一项,见[设置模型的上下文窗口](05-long-conversations.md#context-window)。
+5. 点**添加上游**。应看到提示**已添加“<名称>”**,列表里出现新上游。如果编辑页底部显示**还需填写或修正**,按提示修改对应字段。
+6. 在新上游这一行点**测试**,再选择模型并点**运行测试**。应先看到**连接可用**,再看到**模型可用**;否则见[测试和删除](#test-and-delete)。
+7. [签发一个网关密钥](09-gateway-keys.md#issue-a-key)并选中这个上游。已有的密钥只能访问签发时选中的上游。
+
+## 接口 {#endpoint}
+
+**接口**部分决定网关把请求发到哪里,以及[上游](#upstreams)使用哪种 API。新建的上游默认服务商为*通用*、协议为 *Chat Completions*。
+
+| 字段 | 作用 |
+| --- | --- |
+| **名称** | 在 Studio 中和签发网关密钥时显示。 |
+| **服务商** | 决定可选的协议,以及网关如何适配这家服务商的差异(见下文)。 |
+| **协议** | 上游接受哪种 API。Anthropic 上游同时发送 `x-api-key` 和 `Authorization: Bearer`,Chat Completions 和 Responses 上游只发送 Bearer。 |
+| **Base URL** | 服务商地址,网关在后面拼接接口路径(见[Base URL 的拼接规则](#base-url))。 |
+| **拼接协议接口路径** | 默认开启。只有 Base URL 已经是完整请求地址时才关闭(见[直接发往完整请求地址](#exact-endpoint))。 |
+
+### 各服务商的差异 {#provider-differences}
+
+列表里没有的服务商、LiteLLM 和 new-api 这类兼容代理,以及 [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) 这类把订阅账号包装成 API 的反向代理,都选*通用*,见[自定义上游](#custom-upstreams)。
+
+- *通用*、*Anthropic* 和 *OpenAI* 转发请求的方式相同。
+- *DeepSeek*:请求带工具时,DeepSeek 要求历史中之前每条回复都带推理内容,而很多聊天应用不回传它。DeepSeek 上游默认开启[**补全推理内容回传**](#restore-reasoning),所以请求保持思考模式也能用 OpenViking 工具。关闭这项后,只有请求关闭了思考模式(`"thinking": {"type": "disabled"}`)才提供 OpenViking 工具;标准 Responses 请求没有 `thinking` 字段,这时也得不到工具。记忆照常补充。
+- *火山方舟*和 *BytePlus 方舟*行为相同:Chat Completions 和 Responses 的每段对话使用一个固定的 `prompt_cache_key`,方舟的前缀缓存就能跟着对话走。请求的模型、思考模式、采样参数、系统提示词或工具和对话的第一个请求不同时,方舟会重建缓存,请求被标为**缓存参数有变化**(见[降级请求的异常](12-troubleshooting.md#issues-on-degraded-requests))。
+
+### Base URL 的拼接规则 {#base-url}
+
+Base URL 按服务商 SDK 文档填写,网关在后面拼接协议的接口路径:
+
+| 协议 | 拼接的路径 | 说明 |
+| --- | --- | --- |
+| Chat Completions | `/chat/completions` | 只填域名时不会自动补 `/v1`,OpenAI 要写 `https://api.openai.com/v1`。 |
+| Responses | `/responses` | 同 Chat Completions。 |
+| Anthropic Messages | `/v1/messages` | Base URL 不能以 `/v1` 结尾,否则保存时被拒绝。 |
+
+- 末尾的斜杠会被去掉。`/api/paas/v4` 这类带版本路径的地址可以直接使用。
+- Base URL 可以带查询参数,例如 `?api-version=…`。客户端的查询参数接在后面,同名参数以 Base URL 里的为准。
+- 客户端用方舟路径(`/gateway/api/v3/`、`/gateway/api/compatible/v1/`)发来的请求,按同样的规则拼接。
+- 一个上游只有一个 Base URL。同一服务商的不同协议地址不同时,要分别建上游。
+
+编辑页会实时预览最终的请求地址;OpenAI、方舟这类地址漏掉路径,或者 Anthropic 地址多了 `/v1` 时,会给出提示和一键修正。
+
+一些没有预设的服务商的 Base URL,同样按上面的规则拼接:
+
+| 服务 | 协议 | Base URL |
+| --- | --- | --- |
+| Azure OpenAI(v1 接口) | Chat Completions 或 Responses | `https://RES.openai.azure.com/openai/v1` |
+| Microsoft Foundry 上的 Claude | Anthropic Messages | `https://RES.services.ai.azure.com/anthropic` |
+| Gemini(OpenAI 兼容接口) | Chat Completions | `https://generativelanguage.googleapis.com/v1beta/openai` |
+| 智谱 | Chat Completions | `https://open.bigmodel.cn/api/paas/v4` |
+| 智谱 | Responses | `https://open.bigmodel.cn/api/v1` |
+| 方舟 Coding Plan | Chat Completions、Responses | `…/api/coding/v3` |
+| 方舟 Coding Plan | Anthropic Messages | `…/api/coding` |
+
+### 直接发往完整请求地址 {#exact-endpoint}
+
+如果 Base URL 已经是完整的请求地址,就关闭**拼接协议接口路径**。以 Azure OpenAI 部署为例:
+
+- **协议**选 *Chat Completions*,**服务商**选*通用*
+- **Base URL** 填 `https://RES.openai.azure.com/openai/deployments/DEPLOYMENT/chat/completions?api-version=2024-10-21`
+- 关闭**拼接协议接口路径**
+- **密钥发送方式**选 *api-key 请求头*
+
+关闭后,网关把该协议的请求直接发往这个 URL,不再拼接协议路径。子路径接在后面:Anthropic 的 Token 计数发往 `…/count_tokens`。Embeddings、模型列表等其他接口不会路由到这样的上游,连接测试也会跳过它。
+
+## 凭证 {#credentials}
+
+**凭证**部分决定网关用什么凭证访问服务商。默认由网关保管服务商的 API Key,客户端只需要[网关密钥](09-gateway-keys.md#gateway-keys)。
+
+- **API Key 由谁提供**:
+ - **由网关保管 API Key**(默认):网关发送上游的 API Key。
+ - **每个客户端自带 API Key**:每个请求除了网关密钥,还要在 `X-OpenViking-Upstream-Key` 请求头里带上客户端自己的服务商 API Key,缺少时返回 401 "Upstream API key is missing"。网关按**密钥发送方式**转发这个 API Key,Base URL 含 `{api_key}` 时则填进地址;`X-OpenViking-*` 请求头本身从不转发。各客户端怎么加这个请求头,见[客户端自带服务商 API Key 时](03-connect-clients.md#bring-your-own-provider-key)。
+- **密钥发送方式**(仅服务商为*通用*时):`Authorization: Bearer`(默认)、`api-key` 请求头(Azure OpenAI)或 `x-api-key` 请求头。
+- **密钥放在地址里**:服务商要求把密钥写在地址里时,在 Base URL 的路径或查询参数中写 `{api_key}`,例如 `?key={api_key}`。网关发送时填入 URL 编码后的密钥,并且不再发送鉴权请求头。不要把密钥本身写进地址:能查看上游的人都能看到 Base URL。
+- **API Key**:加密保存,之后不再显示。留空表示保留已存的密钥。
+- **额外请求头**加在发往这个上游的每个请求上,例如服务商的版本或组织请求头,并覆盖客户端发送的同名请求头。取值和 API Key 一样只写不读:留空表示保留已存的值,删除这一行就删除这个请求头。不能设置 `Host`、`Content-Length`、`Transfer-Encoding` 和 `Connection`。
+
+> **修改 Base URL 会清除已存的 API Key 和请求头取值。** 每次改地址都要重新填写,已存的密钥不会被发往新地址。
+
+### Coding Plan 和订阅密钥 {#coding-plan-keys}
+
+服务商通常只允许 Coding Plan 这类订阅密钥用在自家的编程工具里,通过共享网关使用可能导致订阅被封禁。网关无法从密钥本身分辨它是不是订阅密钥,需要你自己勾选**这是 Coding Plan 或订阅密钥**来标记。
+
+标记后,发往这个上游的请求一律被拒绝,返回 403 "Coding Plan upstreams are disabled; configure a model API key",除非同时勾选**允许通过网关使用这个套餐**。请先确认套餐条款允许在服务商自己的工具之外使用,再勾选这一项。
+
+Claude 订阅令牌(`sk-ant-oat…`)无论怎么勾选都会被拒绝,见[使用须知](01-how-it-works.md#what-to-expect)。
+
+## 模型 {#models}
+
+**模型**部分决定[上游](#upstreams)提供哪些模型名,以及它们在服务商那边叫什么。默认列表为空,表示接受任何模型名。
+
+| 字段 | 作用 |
+| --- | --- |
+| **模型** | 这个上游提供的模型名。只有列出的名称和别名会出现在模型列表(`/gateway/v1/models`)里。 |
+| **模型别名** | 把客户端使用的名称映射为发给上游的模型,例如把 Claude Code 请求的 Claude 模型名映射到服务商提供的模型。别名出现在模型列表中,请求日志显示客户端使用的名称。 |
+| **上下文窗口** | 按模型记录窗口大小(token,至少 1,024),键是别名转换之后、实际发给上游的模型名。 |
+
+长对话按上下文窗口的比例触发压缩,所以窗口小于默认值的模型都要列出来,见[设置模型的上下文窗口](05-long-conversations.md#context-window)。
+
+## 路由 {#routing}
+
+**路由**部分决定有多个上游可选时网关如何选择。对每个请求,网关在密钥绑定的已启用[上游](#upstreams)中,找出使用这种 API 并提供所请求模型的上游,选**优先级**最高的一个。对话一旦开始,只要原来的上游还能服务就一直用它。
+
+| 字段 | 默认值 | 作用 |
+| --- | --- | --- |
+| **优先级** | 0 | 数值大的优先。修改只影响新对话,见[修改何时生效](06-manage-in-studio.md#when-changes-take-effect)。 |
+| **启用** | 开启 | 停用的上游不接收请求,也不出现在模型列表里。 |
+| **允许 OpenViking 工具** | 开启 | 决定能否通过这个上游提供 [OpenViking 工具](04-openviking-tools.md#choose-tools)。关闭后立即生效,已经带工具的对话也受影响。 |
+| **补全推理内容回传** | 取决于服务商 | 把客户端丢掉的推理内容放回后续请求(见下文)。 |
+| **最小可缓存长度** | 1,024 token | 仅火山方舟和 BytePlus 方舟:模型能缓存的最短提示词长度,只影响请求日志如何报告缓存资格。 |
+
+停用一个上游后,原本使用它的对话会转到下一个候选上游,造成一次服务商缓存未命中,并丢掉之前的 Claude 思考块,这些请求被标为**上游已切换**(见[降级请求的异常](12-troubleshooting.md#issues-on-degraded-requests))。想保留恢复的余地,就停用而不是删除。
+
+网关不做故障转移:选中的上游出错时,客户端收到这个错误;服务商无法访问时返回 502 "Model upstream is unavailable"。
+
+### 补全推理内容回传 {#restore-reasoning}
+
+客户端回传历史时,常常丢掉模型之前回复里的推理内容。**补全推理内容回传**在 DeepSeek、火山方舟和 BytePlus 方舟上默认开启,其他服务商默认关闭。
+
+开启后,网关记下经它转发的每条回复的推理内容,在后续请求中放回原处:
+
+- Chat Completions:补回 `reasoning_content`。
+- Anthropic Messages:放回 thinking 块。
+- Responses:把带明文内容的 reasoning 项放回对应条目之前。
+
+补回的内容每次逐字节相同,服务商的提示词缓存照常命中,但计入输入 token。客户端自己回传了推理内容的回复保持不变。
+
+有些请求即使开启也补不回推理内容:对话换了上游(**上游已切换**)、Claude 对话丢了记忆记录(**记忆记录缺失**),或者客户端把思考内容当作正文发回。DeepSeek 上游的这类请求同样得不到 OpenViking 工具。
+
+### 所有请求都失败的上游 {#blocked-upstreams}
+
+上游列表会用两个标记提示发往该上游的请求都会失败:
+
+| 标记 | 原因 | 客户端收到 |
+| --- | --- | --- |
+| **缺少 API Key** | 由网关保管 API Key,却没有保存密钥,例如改过 Base URL 之后。 | 401 "Upstream API key is missing" |
+| **请求被拒绝** | [Coding Plan 上游](#coding-plan-keys)未获准通过网关使用。 | 403 |
+
+这样的上游照样参与路由:如果它在匹配的上游中优先级最高,请求会直接失败,不会转到优先级更低的上游。请修好它,或者停用它。
+
+## 测试和删除 {#test-and-delete}
+
+**测试**检查[上游](#upstreams)已保存的接口地址、密钥、模型和协议能否一起正常工作。测试的始终是已保存的设置,改动后要先保存。
+
+1. 在上游列表或上游编辑页的页头点**测试**。网关先检查已保存配置的连接,应看到**连接可用**。完整请求地址没有模型列表可查,会跳过这一步。
+2. 选择或输入模型名,点**运行测试**。网关使用已存的凭证发送一次很小的生成请求,应看到**模型可用**。服务商可能对这次请求计费。
+
+模型测试在上游允许 OpenViking 工具时会带上这些工具,reasoning effort 使用模型默认值。各种结果的含义见[上游测试](../api/25-gateway.md#upstream-tests)。
+
+以下情况不能测试:
+
+- 没有写权限,这时**测试**按钮不显示;
+- 上游设为**每个客户端自带 API Key**,网关没有可用于测试的密钥;
+- 上游还没保存 API Key。
+
+Coding Plan 上游在勾选**允许通过网关使用这个套餐**之前,仍会阻止模型测试。
+
+**删除**会连同保存的 API Key 和请求头一起删掉上游。有密钥在用的上游不能删除:删除对话框会改为提供**停用**,也可以先吊销这些密钥。
+
+## 导入 OpenViking 模型配置 {#import-openviking-model-settings}
+
+导入把 OpenViking 服务端的 VLM 凭证转成当前账号的上游,省去重新填写,只在嵌入部署中可用。在上游页头点**从 OpenViking 导入**;上游列表还是空的时候,这个按钮叫**使用 OpenViking 的模型配置**。没有设置管理密钥时只有 root(包括本地 dev)能导入;设置了管理密钥时需要先[解锁编辑](06-manage-in-studio.md#unlock-editing)。
+
+结果分三组显示:已导入、需要确认、未导入。
+
+- **需要确认**:Base URL 路径中有一段名为 `coding` 或 `plan`(例如 `/api/coding/v3`)的上游会被标为 [Coding Plan](#coding-plan-keys)。确认服务商条款允许后,勾选**允许通过网关使用这个套餐**才能使用。
+- **Azure OpenAI** 凭证(服务商 `azure`,或 LiteLLM 的 `azure/<deployment>`)会导入为完整请求地址的上游,带上配置的 `api_version`,密钥放在 `api-key` 请求头里发送。
+- **未导入**:Codex OAuth 凭证、缺少 `api_base` 的 LiteLLM 凭证,以及不使用 OpenAI Chat Completions API 的 LiteLLM 路由。原因见[导入 VLM 配置](../api/25-gateway.md#import-vlm-settings)。
+
+重复导入不会产生重复的上游:
+
+| 按服务端配置刷新 | 保留你在网关里的修改 |
+| --- | --- |
+| 地址、API Key、请求头、协议、服务商、Coding Plan 标记、**拼接协议接口路径**、**密钥发送方式** | 名称、启用状态、优先级、模型、别名、上下文窗口、**允许通过网关使用这个套餐** |
+
+如果你取消了某个导入上游的 Coding Plan 标记,下次导入时会重新标上,在你勾选**允许通过网关使用这个套餐**之前,这个上游的请求都会被拒绝。
+
+## 自定义上游:代理与订阅额度 {#custom-upstreams}
+
+任何兼容这三种 API 之一的服务都能添加为上游,不一定是模型服务商本身。两种常见用法:
+
+- **计费、配额和负载均衡。** 网关不做这些。需要时在网关后面接一层 LiteLLM、new-api 这类服务,把它添加为上游。
+- **使用订阅额度。** 客户端不能用订阅账号登录网关,但可以把 [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) 这类反向代理添加为上游。它把 ChatGPT(Codex)、Claude 等订阅账号包装成 API,例如 Codex 就能经网关使用 ChatGPT 订阅额度。Codex 的这种用法得到了 OpenAI 的认可:OpenAI Codex 负责人 Tibo 曾[公开介绍](https://x.com/thsottiaux/status/2076119366647894371)过用 CLIProxyAPI 接入 Codex 订阅的做法,具体步骤见[使用 ChatGPT 订阅](03-connect-clients.md#codex-chatgpt-subscription)。**其他订阅服务能否这样使用,请自行确认其使用条款。**
+
+添加时服务商选*通用*,然后按[添加上游](#add-an-upstream)操作。
+
+每个字段的 API 名称、默认值和取值范围见[上游设置](13-configuration.md#upstream-settings)。
+
+## 下一步 {#next-steps}
+
+- [签发网关密钥](09-gateway-keys.md#issue-a-key),选中你的上游。
+- [接入客户端](03-connect-clients.md#connect-clients)。
+- [创建上下文配置](08-context-profiles.md#context-profiles),设置召回和保存。
+- 请求失败时,见[上游返回错误](12-troubleshooting.md#the-upstream-returned-an-error)。
diff --git a/docs/zh/gateway/08-context-profiles.md b/docs/zh/gateway/08-context-profiles.md
new file mode 100644
index 000000000..3fa76fd2a
--- /dev/null
+++ b/docs/zh/gateway/08-context-profiles.md
@@ -0,0 +1,109 @@
+---
+description: 创建上下文配置,决定 OpenViking 网关为每个网关密钥如何召回和保存记忆。
+---
+
+# 管理网关上下文配置
+
+在 Studio 中:**上下文配置**标签页。上下文配置决定 OpenViking 网关如何为使用它的网关密钥召回记忆、保存对话、处理长对话和提供 OpenViking 工具。本页按配置编辑页的分组逐一说明各项设置及默认值;修改配置需要写权限,见[谁能修改什么](06-manage-in-studio.md#who-can-change-what)。
+
+## 什么是上下文配置 {#context-profiles}
+
+[上下文配置](../guides/15-gateway.md#key-terms)是一组有名字的记忆设置。每个[网关密钥](09-gateway-keys.md#gateway-keys)在签发时选定一份配置,一份配置可以供多个密钥使用。比如准备一份“Coding”配置,召回记忆、资源和技能;再准备一份“Chat”配置,只召回记忆,预算也小一些。
+
+一份配置分为四个部分,下表中的默认值也就是推荐设置:
+
+| 部分 | 作用 | 主要设置和默认值 |
+| --- | --- | --- |
+| 召回记忆 | 用每条新的用户消息检索 OpenViking,把相关内容附加到这条消息上。 | 检索范围:记忆、资源、技能 · 单条消息预算:1,600 token · 单个上下文窗口预算:30,000 token · 相关度阈值:0.35 · 超时时间:2 秒 |
+| 保存对话 | 把完成的轮次写入 OpenViking 会话并提交,供 OpenViking 提取记忆。 | 最新回复等待时长:600 秒 · 提交阈值:20,000 token · 保留最近消息:10 |
+| 长对话 | 对话接近上下文窗口时,让同一个模型写摘要,替换之前的消息。 | 压缩:开启 · 压缩时机:窗口的 0.9 · 摘要长度上限:8,000 token · Agent 自管上下文窗口:关闭 |
+| OpenViking 工具 | 让模型在回答时使用 OpenViking 的工具。 | 开启 · 只勾选只读工具,见 [OpenViking 工具](04-openviking-tools.md) |
+
+每个部分都有自己的开关,长对话部分的压缩和 Agent 自管上下文窗口各有一个。召回和保存相互独立,只召回不保存、只保存不召回都可以。
+
+保存后的修改只对之后开始的对话生效,见[修改何时生效](06-manage-in-studio.md#when-changes-take-effect)。
+
+### 创建、复制或删除配置 {#manage-profiles}
+
+1. 打开 **上下文配置** 标签页。标签页为空时,选择**使用推荐设置创建**可一键创建一份名为“默认”的配置,选择**自定义**则先打开编辑页。已有配置后,改用**新建配置**。
+2. 在编辑页填写**名称**,为网关密钥选择配置时会显示这个名称。再按本页的说明调整各部分。
+3. 选择**创建配置**;编辑已有配置时选择**保存**。之后能看到这份配置的卡片,上面概括了各部分的设置和使用它的密钥数(刚创建时显示**没有密钥在用**)。
+
+其他操作:
+
+- **复制一份**:在卡片上或编辑页的**更多操作**(⋯)菜单中,打开一份名为“… 副本”的拷贝。想做一份变体,这样最快。
+- **恢复推荐设置**:在同一个菜单中,把各项恢复为推荐设置,保存后生效。
+- 有密钥在用的配置不能删除。先吊销这些密钥;如果还需要它们,先签发使用其他配置的新密钥来替换。
+- Studio 处于只读状态时,卡片上显示**查看**而不是**编辑**,也不能创建、复制或删除配置,见[解锁编辑](06-manage-in-studio.md#unlock-editing)。
+
+## 召回记忆 {#recall-memory}
+
+**召回记忆**部分(默认开启)控制[召回](../guides/15-gateway.md#key-terms):每收到一条新的用户消息,网关就用它检索 OpenViking,把相关内容附加到这条消息上。模型最终收到什么,见[模型看到什么](01-how-it-works.md#what-the-model-sees)。各项设置按编辑页中的顺序排列:
+
+| 设置 | 默认值 | 控制什么 |
+| --- | --- | --- |
+| **会话开头提供用户画像** | 开启 | 新对话开始时,向模型提供你的 OpenViking 用户画像。 |
+| **开头内容预算** | 4,000 token | 开头的用户画像、记忆目录和技能目录最多占用多少。 |
+| **显示召回摘要** | 关闭 | 在回复开头加一行摘要,见[召回摘要](#recall-summary)。 |
+| **检索范围** | 记忆、资源、技能 | 召回时检索哪些内容。 |
+| **单条消息预算** | 1,600 token | 一条消息最多附加多少记忆。 |
+| **单个上下文窗口预算** | 30,000 token | 一个上下文窗口内累计最多附加多少记忆。 |
+| **相关度阈值** | 0.35 | 只附加相关度不低于该值的结果,取值 0 到 1。值越高,附加的内容越少、越贴切。 |
+| **超时时间** | 2 秒 | 一次检索最多等多久。 |
+| **检索文本长度**(在**高级设置**中) | 8,000 个字符 | 取消息的多少字符作为检索文本。 |
+| **按分类限量**(在**高级设置**中) | 关闭 | 每个分类最多附加多少条。 |
+
+这些设置如何配合:
+
+- **开头内容。** **会话开头提供用户画像**独立于召回。提供 OpenViking 的 `read` 工具(`openviking_read`)时,开头还会提供记忆目录和技能目录。技能最多占**开头内容预算**的四分之一,预算设为 0 时全部省略。这份预算不占召回预算,见[对话开头的内容](01-how-it-works.md#the-opening-context)。
+- **补充什么。** 召回内容由 OpenViking 在预算内选取和排版,也可能只给出 URI,供模型之后读取。
+- **检索文本。** 检索文本是去掉客户端噪声后的用户消息,最多取**检索文本长度**个字符。少于 3 个字符的消息不检索。
+- **预算。** 每条消息最多补充**单条消息预算**和**单个上下文窗口预算**剩余额度中较小的那个;剩余额度不足 64 token 时跳过检索。无论是网关还是客户端压缩了对话,单个上下文窗口预算都重新计算。这里的 token 数是偏保守的估算,不是服务商的计费数。
+- **关闭召回。** 把**单个上下文窗口预算**设为 0 就等于关闭召回;**单条消息预算**最小为 64。
+- **超时。** OpenViking 在**超时时间**内没有返回时,这条消息不带记忆发给模型,之后也不会补上,客户端重试也一样。
+- **按分类限量。** 可以给事件、实体、偏好、经验、资源和技能六类分别设条数上限,只检索上限大于 0 的类别。关闭时,所有来源放在一起排序。
+
+### 召回摘要 {#recall-summary}
+
+召回摘要是回复开头的一段简短说明,写明 OpenViking 为这条新用户消息补充了什么,或者召回为什么失败。它默认关闭,在[上下文配置](#context-profiles)的**召回记忆**部分开启**显示召回摘要**即可。模型看不到摘要。示例:
+
+```text
+> OpenViking context: user profile, memory index, skill list, earlier sessions
+> OpenViking recall: 4 items (3 memories, 1 resource) — booking_duplicate_handling, user_lang_pref, +2 more
+```
+
+- `context` 行只出现在对话的第一条回复里,列出开头实际提供的内容:用户画像、记忆目录、技能目录,以及这段对话较早部分在 OpenViking 中的位置。
+- `recall` 行按类别统计召回条数,最多列出三个条目名。检索失败时改为说明原因,例如 `> OpenViking recall failed: OpenViking unavailable`。没有找到内容、召回已关闭或预算用完时不显示这一行,所以第一条回复之后,这类消息没有摘要。
+- 工具步骤等后续请求不显示摘要;客户端重试同一条消息时,摘要和第一次相同。
+- 摘要在 Anthropic Messages 中单独占一个文本块,在 Responses 中单独占一条助手消息,在 Chat Completions 中位于回复文本开头。要求结构化输出的请求,以及 `n` 大于 1 的 Chat Completions 请求,不显示摘要。
+- 客户端随下一条消息把回复发回来时,网关先删掉摘要再转发,也不会把它保存到 OpenViking。
+
+## 保存对话 {#save-conversations}
+
+**保存对话**部分(默认开启)控制[保存](../guides/15-gateway.md#key-terms):网关把完成的轮次写入 OpenViking 会话并提交,供 OpenViking 提取记忆。网关怎样判断一轮已经完成,见[对话什么时候保存](01-how-it-works.md#when-conversations-are-saved)。
+
+| 设置 | 默认值 | 控制什么 |
+| --- | --- | --- |
+| **最新回复等待时长** | 600 秒 | 最新一轮等待后续消息多久,之后网关保存它并提交会话。 |
+| **提交阈值** | 20,000 token | 会话中待提交的内容达到多少 token 时提交。 |
+| **保留最近消息** | 10 | 提交后会话中保留多少条消息。 |
+
+- 下一条用户消息到达时,上一轮就会保存。**最新回复等待时长**针对的是最后一轮,这样短对话也能被提交。
+- 会话中待提交的内容达到**提交阈值**时提交一次。每次提交后,OpenViking 在后台提取记忆。
+- 提交后,会话中保留最新的若干完整轮次,至少包含**保留最近消息**条消息。
+
+## 长对话和 OpenViking 工具 {#long-conversations-and-tools}
+
+编辑页的最后两个部分各有专门的页面:
+
+- **长对话**部分包括**压缩**及其**压缩时机**和**摘要长度上限**、实验性的 **Agent 自管上下文窗口**及其**软提醒时机**和**硬提醒时机**,以及**高级设置**中的**默认上下文窗口**。详见[网关中的长对话](05-long-conversations.md#long-conversations);窗口较小的模型需要设置窗口大小,见[设置模型的上下文窗口](05-long-conversations.md#context-window)。
+- **OpenViking 工具**部分包括**工具**清单和**显示工具调用**,**高级设置**中还有**每次请求的工具轮数**、**单次调用超时**、**结果大小上限**、**总时长**和 **Token 预算**。详见[选择工具](04-openviking-tools.md#choose-tools)和[上限](04-openviking-tools.md#limits)。网关执行所选工具时不经过客户端的权限确认,勾选会修改数据的工具之前,请先阅读[风险和控制点](04-openviking-tools.md#risks-and-controls)。
+
+每项设置的 API 名称和取值范围见[配置参考](13-configuration.md#context-profile-settings)。
+
+## 下一步 {#next-steps}
+
+- [签发一个网关密钥](09-gateway-keys.md#issue-a-key),让它使用这份配置。
+- 在[请求日志](10-overview-and-requests.md#requests)中逐条查看召回和保存情况。
+- 始终没有补充记忆时,见[没有补充记忆](12-troubleshooting.md#no-memory-is-added)。
+- 在[OpenViking 网关的工作原理](01-how-it-works.md#what-happens-once-you-connect)中完整走一遍一轮对话。
diff --git a/docs/zh/gateway/09-gateway-keys.md b/docs/zh/gateway/09-gateway-keys.md
new file mode 100644
index 000000000..911dcdea4
--- /dev/null
+++ b/docs/zh/gateway/09-gateway-keys.md
@@ -0,0 +1,84 @@
+---
+description: 签发把客户端接入 OpenViking 网关的网关密钥,并在之后管理它们。
+---
+
+# 管理网关密钥
+
+本页面向需要签发网关密钥的人:给自己签发的普通用户,以及替他人签发密钥、或为某位用户做清理的账号管理员。读完后你能签发密钥并填进客户端,也清楚密钥被吊销、或其用户的 OpenViking API 密钥变化后会发生什么。开始前至少需要一个[上游](07-upstreams.md#upstreams)和一份[上下文配置](08-context-profiles.md#context-profiles)。
+
+## 什么是网关密钥 {#gateway-keys}
+
+在 Studio 中:**OpenViking 网关** → **密钥**。网关密钥(`ovgw_…`)是客户端用来代替服务商 API Key 的凭证。每把密钥绑定:
+
+- **一位 OpenViking 用户。** 网关以这位用户的身份、用其本人的 [OpenViking API 密钥](../guides/22-gateway-operations.md#keys-and-credentials)召回和保存记忆,所以密钥的权限永远不会超出用户本人,见[按用户隔离](11-security-and-data.md#isolation-by-user)。
+- **一份上下文配置**,决定用这把密钥的对话如何召回和保存记忆。
+- **一组上游**,还可以进一步限定允许使用的模型。
+
+**密钥**标签页列出你自己的密钥;账号管理员和 root 能看到本账号的全部密钥,并多出一列 **OpenViking 用户**。**密钥**列只显示每把密钥的开头几个字符。
+
+## 签发密钥 {#issue-a-key}
+
+如果**密钥**标签页提示先添加上游或创建上下文配置,请先完成;自己没有权限时,联系部署网关的人。在全新的网关上,概览页**快速模式**卡片里的**一键生成密钥**可以一步完成这些准备并签发密钥,见[快速开始清单和快速模式](06-manage-in-studio.md#get-started-checklist)。
+
+1. 在**密钥**标签页点**签发密钥**,弹出**签发网关密钥**对话框。
+2. 填写**名称**,用来区分不同的密钥,写上使用者和客户端最清楚,例如“Alice · Claude Code”。
+3. 在**给谁用**里选择这把密钥读写谁的记忆,见[密钥给谁用](#who-the-key-is-for)。
+4. 选择一份**上下文配置**,并至少勾选一个**上游**。密钥只能访问选中的上游;每个请求到达时,网关从中挑一个协议与客户端一致、并且提供所请求模型的上游(见[路由](07-upstreams.md#routing))。
+5. 按需填写**允许的模型**,见[限定密钥可用的模型](#allowed-models)。
+6. 点**签发密钥**。网关会先向 OpenViking 核实这位用户的 OpenViking API 密钥,成功后会弹出**复制网关密钥**对话框。如果看到的是**无法签发密钥**,见[签发密钥失败](12-troubleshooting.md#issuing-a-key-fails)。
+7. 点**复制网关密钥**,再复制 Claude Code、Codex CLI 或聊天客户端的配置,里面已经填好真实密钥和网关地址。某个客户端的配置页提示这把密钥没有已启用的对应协议上游时,该客户端用不了这把密钥。复制完点**我已复制**。
+
+密钥签发后立即可用。**复制网关密钥**对话框是唯一一次能看到完整密钥的机会:网关只保存它的哈希和开头几个字符。密钥丢了就重新签发。其他客户端的接入方式见[把客户端接入 OpenViking 网关](03-connect-clients.md#connect-clients)。
+
+### 密钥给谁用 {#who-the-key-is-for}
+
+网关会以**给谁用**中所选用户的身份召回和保存记忆。能选哪些用户取决于你的身份:
+
+| 你的身份 | 能给谁签发 |
+| --- | --- |
+| 普通用户 | 只能给自己。Studio 显示“以你的身份(<用户>)读写记忆。”,不需要粘贴任何密钥。 |
+| 账号管理员 | 本账号中的任意用户或管理员。 |
+| root | 先在侧边栏切换到目标账号,再选择该账号中的用户。root API 密钥不能绑定到网关密钥。 |
+| 本地 dev 模式下的任何人 | 密钥以 `default` 用户的身份读写记忆。 |
+
+除 root 外,给自己签发时都不需要粘贴密钥。给别人签发时,网关要从 OpenViking 读取那位用户的 API 密钥。OpenViking 只保存密钥哈希时读不出来:这位用户旁会标注“服务端读不到这个用户的用户 API 密钥,请改为粘贴”,并出现**粘贴 <用户> 的用户 API 密钥**输入框,填入该用户当前的密钥即可。也可以点**粘贴用户 API 密钥**直接填写。用户列表加载失败时,Studio 改为要求填写 **OpenViking API 密钥**。
+
+持有网关密钥就能使用对应用户的记忆,因此能替他人签发密钥,就等于能读取本账号所有用户的记忆,见[访问控制](11-security-and-data.md#access-control)。
+
+### 限定密钥可用的模型 {#allowed-models}
+
+**允许的模型**默认留空,表示允许这把密钥所绑[上游](07-upstreams.md#upstreams)提供的全部模型。要限制时,填入客户端发送的模型名称,包括别名。之后这把密钥的模型列表只显示这些名称,请求其他模型会在到达服务商之前被拒绝。设置了允许模型的密钥还要求每个请求都写明模型;具体报错见[客户端收到网关返回的错误](12-troubleshooting.md#clients-get-an-error-from-the-gateway)。
+
+## 签发之后 {#after-issuing}
+
+[网关密钥](#gateway-keys)一经签发就不能再改,但它发起的对话属于它的用户。
+
+- **密钥不能编辑。** 要更换上下文配置、上游、允许的模型或用户,就签发新密钥,再吊销旧的。
+- **对话属于用户,不属于密钥。** 客户端发送相同的会话 ID 时,同一用户的新密钥会接着原来的[对话](03-connect-clients.md#how-conversations-are-recognized),换密钥不会打断对话。
+- **吊销**(在**密钥**标签页点**吊销**,再点**吊销密钥**确认)后,这把密钥立即失效。用户的对话状态和日志保留,直到被显式删除或过期。尚未保存到 OpenViking 的内容(例如最新一条回复),只有在用新密钥继续这段对话时才会保存。
+
+### 每人一把密钥 {#one-key-per-person}
+
+记忆属于[网关密钥](#gateway-keys)背后的 OpenViking 用户,所以共用一把密钥的人也共用这位用户的记忆。请给每人签发一把密钥。想让不同客户端使用不同的上下文配置,或者想单独吊销某个客户端,再按客户端分开签发。
+
+### 用户的 OpenViking API 密钥变了 {#when-the-openviking-key-changes}
+
+每把网关密钥都依赖其用户当前的 [OpenViking API 密钥](../guides/22-gateway-operations.md#keys-and-credentials)。这个密钥重新生成或用户被删除后,OpenViking 会拒绝网关保存的旧密钥。网关在随后的请求中发现这一点(最多延迟约 30 秒),删除绑定它的网关密钥,对话状态和日志保留。请用当前的 OpenViking API 密钥重新签发。
+
+如果 OpenViking 只是暂时连不上或返回错误,网关不会删除密钥,请求照常发给模型,只是不带记忆。
+
+## 删除用户的网关数据 {#delete-a-users-gateway-data}
+
+吊销密钥不会删除网关为用户保存的数据。要删除,账号管理员或 root 在**密钥**标签页打开该用户任意一把密钥的 **…** 菜单,选择**删除该用户的网关数据…**,再点**删除网关数据**确认。这一操作会:
+
+- 吊销该用户的全部网关密钥,其客户端立即失去访问权限;
+- 删除网关为该用户保存的对话状态,包括尚未保存到 OpenViking 的内容;
+- 删除该用户的请求日志。
+
+已存入 OpenViking 的记忆不受影响。对应的 API、按账号整体删除以及适用场景,见[删除数据](11-security-and-data.md#deleting-data)。
+
+## 下一步 {#next-steps}
+
+- [把客户端接入 OpenViking 网关](03-connect-clients.md#connect-clients):把密钥填进 Claude Code、Codex 或其他客户端。
+- [检查接入是否生效](03-connect-clients.md#check-the-connection):确认请求和记忆都已到达。
+- [OpenViking 网关安全与数据](11-security-and-data.md):网关为每位用户保存什么、保存多久。
diff --git a/docs/zh/gateway/10-overview-and-requests.md b/docs/zh/gateway/10-overview-and-requests.md
new file mode 100644
index 000000000..6fef12afe
--- /dev/null
+++ b/docs/zh/gateway/10-overview-and-requests.md
@@ -0,0 +1,149 @@
+---
+description: 读懂 Studio 中 OpenViking 网关的“概览”和“请求日志”标签页:卡片、列、请求类型和保存状态。
+---
+
+# 网关概览与请求日志
+
+本页逐一说明网关**概览**和**请求日志**两个标签页里的卡片、列、标签和保存状态,以及哪些数值说明网关运行正常。在 Studio 中打开 **OpenViking 网关**,选择**概览**或**请求日志**标签页即可。客户端通过网关发出第一个请求之前,这两个标签页都没有数据,接入方法见[接入客户端](03-connect-clients.md#connect-clients)。
+
+## 谁能看到哪些请求 {#requests-and-overview}
+
+两个标签页读的都是网关的请求日志:每个经过网关的模型请求对应一条记录。普通用户只看到自己的请求,账号管理员和 root 看到整个账号的请求。概览里的数字也是从这些记录算出来的,所以统计范围和请求日志一致。
+
+日志只记元数据,从不保存提示词、回复或记忆内容,详见[请求日志记什么](11-security-and-data.md#what-request-logs-record)。记录默认保留 30 天,见[保留期限](11-security-and-data.md#retention)。
+
+## 概览 {#overview}
+
+**概览**标签页汇总请求日志中最新的 10,000 条请求。收到第一个请求之前,页面上还会显示**快速开始**清单,见[快速开始清单和快速模式](06-manage-in-studio.md#get-started-checklist)。
+
+| 卡片 | 显示什么 | 正常时 | 不正常时看 |
+| --- | --- | --- | --- |
+| **请求数** | 模型请求的数量(不含后台保存事件,即日志中的**记忆同步**)、最近一次请求的时间,以及这些请求的输出 token | 随客户端发请求而增长 | [检查接入是否生效](03-connect-clients.md#check-the-connection) |
+| **首次调用缓存命中率** | 每条新用户消息的第一次模型调用中,命中服务商[提示词缓存](01-how-it-works.md#replay)的输入 token 所占比例 | 接近不经过网关时服务商能达到的水平。这是判断网关是否健康最重要的指标。 | [首次调用缓存命中率下降](12-troubleshooting.md#the-first-call-cache-hit-rate-dropped) |
+| **轮内缓存命中率** | 同一轮里后续调用的同一比例,例如工具步骤和 OpenViking 工具的往返 | 通常很高 | — |
+| **召回的记忆条数** | 补充到新消息中的记忆条数,以及每次检索 OpenViking 的平均耗时(只统计实际检索了的消息) | 用户在 OpenViking 中有记忆后开始增长;全新账号为 0 属于正常 | [没有补充记忆](12-troubleshooting.md#no-memory-is-added) |
+| **OpenViking** | **已连接**、**异常**或**启动中**,OpenViking 的版本,以及异常时的原因。卡片中的**保存对话**一栏统计正在重试或已暂停保存的对话数。 | **已连接**,且最近的请求中没有保存失败的对话 | [OpenViking 异常](12-troubleshooting.md#openviking-is-degraded)、[OpenViking 中看不到对话](12-troubleshooting.md#conversations-do-not-appear-in-openviking) |
+| **降级请求** | 每种异常出现的次数,附说明和建议操作 | **没有降级请求** | [降级请求的异常](12-troubleshooting.md#issues-on-degraded-requests) |
+| **最近请求** | 最新的几条请求,以及前往**请求日志**标签页的链接 | — | [请求日志](#requests) |
+
+首次调用缓存命中率明显下降,通常说明网关发送的历史和上一次对不上了。OpenViking 连不上期间,请求照常发给模型,只是不带记忆;保存对话会一直重试,直到 OpenViking 恢复。**保存对话**一栏或**降级请求**卡片报告问题时,点**在请求日志中查看**会打开**请求日志**标签页,并筛选出**异常**。
+
+### 长对话没有命中缓存 {#long-conversations-missing-the-cache}
+
+某段对话最近连续 3 次模型调用的输入都不少于 32,000 token、相邻两次相隔不到 5 分钟,而服务商返回的缓存命中每次都是 0 时,顶部四张数字卡片(**请求数**、**首次调用缓存命中率**、**轮内缓存命中率**和**召回的记忆条数**)下方会出现“有 2 段长对话连续没有命中提示词缓存”这样的警告,并列出每段对话的模型、上游和连续未命中次数。如果这些都是 Anthropic 对话,而且上游也从没写入过缓存,警告会建议检查客户端是否设置了 `cache_control`。
+
+下面这些变化之后缓存本来就无法命中,所以连续次数会从头算起:
+
+- 一次[压缩](05-long-conversations.md#long-conversations),或者模型开启了新的上下文窗口
+- 切换到别的模型或上游
+- 网关工具在请求中时有时无
+
+某个上游最近从没返回过缓存命中时,显示的是一条提示:经过它的长对话缓存命中率一直是 0%。原因和处理方法见[首次调用缓存命中率下降](12-troubleshooting.md#the-first-call-cache-hit-rate-dropped)。
+
+## 请求日志 {#requests}
+
+**请求日志**标签页按时间倒序列出日志中最新的 1,000 条记录,停留在第一页时每 30 秒刷新一次。筛选和搜索也只覆盖这 1,000 条。
+
+只有到达模型服务商的请求才会记录。被网关先行拒绝的请求不记录,例如密钥无效、模型不在密钥允许的范围内、没有匹配的上游、请求体超限,这些情况下客户端直接收到错误,见[客户端收到网关返回的错误](12-troubleshooting.md#clients-get-an-error-from-the-gateway)。
+
+### 筛选和搜索 {#filter-and-search}
+
+| 筛选 | 显示 |
+| --- | --- |
+| **全部** | 所有记录 |
+| **新消息** | 以一条新用户消息开启一轮的请求 |
+| **工具步骤** | 延续同一轮的请求,例如带着工具结果继续 |
+| **异常** | 降级请求、对话保存处于**重试中**或**已暂停**的请求,以及服务商返回 HTTP 400 及以上状态码的请求(见[上游返回错误](12-troubleshooting.md#the-upstream-returned-an-error)) |
+| **请求类型** | 某一种[请求类型](#request-types) |
+
+搜索范围包括模型、对话 ID、请求 ID、密钥名称或前缀,以及上游名称。日志只保存对话 ID 的哈希,所以 Studio 会先在浏览器里对粘贴的对话 ID 求哈希再匹配。这要求 Studio 通过 HTTPS 或 localhost 打开;用普通 HTTP 打开时,按对话 ID 搜索什么也找不到。
+
+### 各列含义 {#columns}
+
+| 列 | 显示 |
+| --- | --- |
+| **时间** | 请求到达的时间 |
+| **类型** | [请求类型](#request-types) |
+| **模型** | 客户端发送的模型名称 |
+| **状态** | 服务商返回的 HTTP 状态码 |
+| **Token** | 输入 token、其中命中缓存的比例,以及输出 token |
+| **记忆** | 这次请求中[召回](../guides/15-gateway.md#key-terms)做了什么(见下表) |
+| **保存** | 所在对话的[保存状态](#saving-status);鼠标悬停可以看到原因 |
+| **异常** | 降级请求的异常 |
+
+**记忆**列的写法:
+
+| 显示 | 含义 |
+| --- | --- |
+| `+3` | 这次检索补充了 3 条记忆,旁边附检索耗时。 |
+| `↺ 4` | 之前 4 条消息补充的记忆被原样放回。 |
+| **召回失败** | 这次请求的记忆检索没有完成,例如 OpenViking 连不上、拒绝了密钥,或者没有在上下文配置的**超时时间**内返回。鼠标悬停可以看到原因,另见[没有补充记忆](12-troubleshooting.md#no-memory-is-added)。 |
+
+### 请求详情 {#request-details}
+
+展开一行可以看到:
+
+- 对话 ID、上游、网关密钥和耗时
+- token 明细
+- 记忆检索结果
+- 上下文窗口用量,以及历史是否经过压缩、模型是否开启了新窗口
+- 保存状态和下次重试时间
+- OpenViking 工具详情,包括没有提供工具的原因
+
+有异常的请求,展开后还会说明发生了什么、该怎么处理。
+
+### 请求类型 {#request-types}
+
+每条记录都属于一种类型。类型决定这次请求是否检索记忆、所在的轮次是否保存。
+
+| 类型 | 含义 | 记忆 |
+| --- | --- | --- |
+| 新消息 | 最后一条是新用户消息的请求 | 检索一次,并放回之前的记忆;这一轮会被保存 |
+| 工具步骤 | 同一轮的延续,例如带着工具结果继续 | 放回之前的记忆;随所在轮次一起保存 |
+| 辅助请求 | 生成标题、摘要、压缩、建议和权限检查的请求 | 放回之前的记忆;从不保存 |
+| 子 Agent | 客户端的子 Agent 发出的请求 | 放回之前的记忆;从不保存 |
+| Token 计数 | token 计数请求(`/gateway/v1/messages/count_tokens`) | 放回之前的记忆,计数才和实际发送的内容一致 |
+| 直接转发 | 原样转发、不带记忆的请求:其他接口、依赖服务商端状态的 Responses 请求、压缩过或无法解析的请求体 | 无 |
+| 记忆同步 | 后台保存事件,不是模型请求 | — |
+
+## 保存状态 {#saving-status}
+
+**保存**列显示网关是否在把一段对话中已完成的轮次[保存](../guides/15-gateway.md#key-terms)到 OpenViking。正常情况下显示**正常**。
+
+| 状态 | 含义 | 网关怎么做 |
+| --- | --- | --- |
+| **正常** | 保存正常进行。 | — |
+| **已关闭** | 这段对话的[上下文配置](08-context-profiles.md#save-conversations)不保存对话。 | 不保存任何内容。 |
+| **重试中** | OpenViking 拒绝了保存或无法访问。 | 在 10、20、40、80 秒后依次重试。 |
+| **已暂停** | 连续失败 5 次。 | 之后每 5 分钟重试一次,直到成功;未保存的轮次一直保留,直到保存成功或对话过期。 |
+| **已暂停**,原因为 `gateway_key_revoked` | 这段对话的网关密钥已被吊销或删除。 | 不再重试。用户之后用有效密钥在这段对话里发请求时,保存自动恢复。 |
+
+展开的行和**保存**标记的悬停提示会显示最近一次变化的原因:
+
+| 显示的原因 | 代码 | 含义 |
+| --- | --- | --- |
+| OpenViking 拒绝了这个密钥,它可能填错了或已被吊销。 | `openviking_http_401` | 用户的 OpenViking 密钥已失效。 |
+| OpenViking 无法访问或响应超时 | `openviking_unavailable` | OpenViking 没有运行、连不上或响应太慢。 |
+| 保存到 OpenViking 失败 | `delivery_failed` | 其他原因导致保存失败,网关按上表重试。 |
+| 保存已恢复正常 | `delivery_recovered` | 失败之后又保存成功了。 |
+| 对话历史有改动,后续内容改存到新的 OpenViking 会话 | `history_changed` | 正常现象:客户端编辑、重新生成或压缩了对话,网关用当前历史在新的 OpenViking 会话中继续保存。 |
+| 保存过程中对话历史有改动,后续内容改存到新的 OpenViking 会话 | `history_changed_during_delivery` | 正常现象:同上,只是发生在保存进行中。 |
+| 已保存的一轮对话在停顿后又继续了,后续内容改存到新的 OpenViking 会话 | `continued_after_idle` | 正常现象:已在**最新回复等待时长**之后保存的一轮又继续了。 |
+| 管理员已手动重新同步 | `manual_reset` | 有人用了**重新同步对话…**(见下文)。 |
+
+之前的轮次留在旧的 OpenViking 会话里。保存一直处于**重试中**或**已暂停**时,见[OpenViking 中看不到对话](12-troubleshooting.md#conversations-do-not-appear-in-openviking)。
+
+### 重新同步对话 {#resync-a-conversation}
+
+重新同步会为一段对话新建一个 OpenViking 会话,用户下次发消息时,网关把完整历史写进去。原因已经修复、对话却仍然暂停,或者想要一份干净的对话副本时,可以用它。已经保存的内容留在旧会话里,所以 OpenViking 可能会把部分记忆提取两次。
+
+1. 在**请求日志**标签页展开这段对话的一条记录。重新同步需要记录上显示的那把密钥;它已被吊销时,请选同一段对话里更新的一条记录。
+2. 点击**重新同步对话…**,再点**重新同步**。页面会提示“这段对话会在下一条消息时重新保存。”
+3. 等用户在这段对话里发下一条消息。消息到达之前什么都不会发生;到达后,网关把完整历史保存到新会话,这段对话的记录会显示原因“管理员已手动重新同步”。
+
+## 下一步 {#next-steps}
+
+- [OpenViking 网关排障](12-troubleshooting.md#common-symptoms):根据卡片、标签或状态找到原因和处理方法。
+- [记忆原样放回与提示词缓存](01-how-it-works.md#replay):为什么首次调用缓存命中率这么重要。
+- [观测](../guides/22-gateway-operations.md#monitoring):在 Studio 之外检查网关的运行状态。
+- [安全与数据](11-security-and-data.md#what-request-logs-record):日志记录什么、保留多久。
diff --git a/docs/zh/gateway/11-security-and-data.md b/docs/zh/gateway/11-security-and-data.md
new file mode 100644
index 000000000..f6819d9a1
--- /dev/null
+++ b/docs/zh/gateway/11-security-and-data.md
@@ -0,0 +1,120 @@
+---
+description: OpenViking 网关存储什么、谁能访问、服务商能看到什么,以及数据如何保留、删除和备份。
+---
+
+# OpenViking 网关安全与数据
+
+本页写给审批网关部署的运维和安全评审人员,也写给想知道网关保存了自己哪些数据的用户。会话和记忆始终保存在 OpenViking 中,按 OpenViking 自己的规则管理;网关只在 `storage_path` 下的两个 SQLite 文件里保存自身配置、让对话继续所需的状态,以及只含元数据的请求日志。下面每一节回答一个评审问题,都可以单独链接。
+
+## 按用户隔离 {#isolation-by-user}
+
+每把[网关密钥](../guides/15-gateway.md#key-terms)绑定一位 OpenViking 用户。网关用这位用户自己的 OpenViking 密钥检索记忆、保存对话和调用工具,所以能做的事不会超出用户本人的权限。各用户的对话状态互相隔离。
+
+## 网关存储什么 {#what-the-gateway-stores}
+
+网关保存的全部数据都在 `storage_path`(默认 `~/.openviking/gateway`)下的两个 SQLite 数据库里:
+
+| 文件 | 内容 |
+| --- | --- |
+| `management.sqlite3` | 上游、上下文配置、网关密钥、请求日志,以及每个 Responses 响应由哪个上游创建 |
+| `kernel.sqlite3` | 每段对话的状态:补充到消息中的记忆原文、OpenViking 工具的往返记录及其结果、摘要、等待保存的对话文本,以及开启**补全推理内容回传**时模型回复的推理内容 |
+
+其中有些属于敏感数据:
+
+- `management.sqlite3` 存有上游 API Key、请求头的值,以及网关密钥绑定的 OpenViking 密钥。网关密钥本身只存哈希和一段短前缀。
+- `kernel.sqlite3` 逐字保存记忆原文,因为网关要靠它把之前几轮补充的内容[原样放回](01-how-it-works.md#replay)。
+
+这两个文件只有运行网关的系统用户能读取。开启[加密](../guides/22-gateway-operations.md#encryption)后,存储的每个值也都会加密;加密关闭时,上面这些凭证以明文存储,只靠文件权限保护。
+
+## 请求日志记什么 {#what-request-logs-record}
+
+请求日志只记元数据,不记内容:
+
+| 会记录 | 不会记录 |
+| --- | --- |
+| 请求类型、模型、状态、上游 | 消息文本 |
+| 对话 ID 的哈希 | 召回的记忆 |
+| token 数、记忆条数和耗时 | 工具参数和结果 |
+| 保存状态和异常 | 任何密钥 |
+
+网关不写 HTTP 访问日志,错误信息也不回显提交的值。在 Studio 中查看日志,见[请求日志](10-overview-and-requests.md#requests)。
+
+## 服务商能看到什么 {#what-providers-see}
+
+每个[上游](../guides/15-gateway.md#key-terms)都收到完整的模型输入,包括网关补充的记忆和 OpenViking 工具的结果。只添加你放心交出这些数据的服务商。
+
+也有一些内容不会离开网关:`X-OpenViking-*` 请求头、客户端凭证和 Cookie 从不转发给上游。上游设为由每个客户端提供自己的服务商密钥时,这把密钥只作为该上游的凭证发给服务商。
+
+## 访问控制 {#access-control}
+
+通过网关获得访问权的途径有四种,每种都有需要了解的边界:
+
+| 凭证 | 允许做什么 | 注意 |
+| --- | --- | --- |
+| [网关密钥](09-gateway-keys.md#gateway-keys),放在 `Authorization: Bearer` 或 `x-api-key` 中 | 以绑定用户的身份发起模型请求:召回记忆、保存对话、调用 OpenViking 工具 | 随时可以在**密钥**页吊销 |
+| [网关管理密钥](../guides/22-gateway-operations.md#gateway-management-key) | 只能修改上游和上下文配置 | 不授予读取记忆、日志或签发密钥的权限 |
+| 账号管理员的签发权 | 给本账号的任何用户签发网关密钥 | 实际上等于能读取本账号所有用户的记忆 |
+| 上传、下载链接里的一次性令牌 | 调用 `/gateway/uploads` 和 `/gateway/downloads`,这两个接口不需要网关密钥 | 令牌放在查询字符串里 |
+
+其中两项需要特别留意:
+
+- **签发密钥。** 拿到网关密钥就能以该用户的身份召回记忆、调用工具,所以签发权只交给可信的管理员。OpenViking 只存密钥哈希时,需要用户本人提供自己的 OpenViking 密钥。
+- **上传和下载链接。** 每个链接由 OpenViking 签发的一次性令牌授权,网关只把它转发到 OpenViking 的上传或下载接口。不要让它们的查询字符串出现在代理日志里。
+
+包括管理 API 在内的完整规则见[权限矩阵](../api/25-gateway.md#credentials-and-account-scope);各角色在 Studio 中能做什么,见[谁能修改什么](06-manage-in-studio.md#who-can-change-what)。
+
+## 保留期限 {#retention}
+
+网关数据会自动过期,清理任务每小时运行一次:
+
+| 数据 | 保留时长 | 设置 |
+| --- | --- | --- |
+| 对话状态 | 最后一次使用后 30 天 | `session_ttl_days` |
+| 请求日志 | 30 天 | `log_retention_days` |
+| Responses 响应与上游的对应关系 | 30 天 | `response_ttl_seconds` |
+| OpenViking 中的会话和记忆 | 遵循 OpenViking 自己的规则 | — |
+
+这些设置的最小值和配置位置见[网关字段](13-configuration.md#gateway-fields)。
+
+## 删除数据 {#deleting-data}
+
+吊销网关密钥、或者它绑定的 OpenViking 密钥失效,都不会删除用户数据。要删除,有三种途径:
+
+| 谁 | 怎么做 | 删除什么 |
+| --- | --- | --- |
+| 账号管理员或 root | 在 Studio 中用**删除该用户的网关数据…**([操作步骤](09-gateway-keys.md#delete-a-users-gateway-data)),或者调用 `DELETE /gateway/admin/users/{user_id}/data` | 单个用户:吊销其网关密钥,删除其对话状态和日志,包括尚未保存的内容 |
+| root | 调用 `DELETE /gateway/admin/account/data?account_id=<account>` | 整个账号的网关数据 |
+| 嵌入部署,自动进行 | 在 OpenViking 中删除用户或账号 | 对应的网关数据 |
+
+独立部署没有自动删除这一步,数据会一直保留,直到被显式删除或[过期](#retention)。
+
+已存入 OpenViking 的记忆和会话不受这些操作影响。反过来,在 OpenViking 中删除一条记忆后,网关为进行中的对话保存的那份副本仍会被原样放回,直到对话过期;要立即清除,删除该用户的网关数据。
+
+## 备份与恢复 {#backups}
+
+以下内容要一起备份:
+
+- 整个 `storage_path` 目录:两个数据库及其 `-wal`、`-shm` 文件。
+- 开启加密时,还有 OpenViking 的加密根密钥(不是 root API 密钥),按[加密指南](../guides/08-encryption.md)的说明保管。
+
+要得到一致的副本,先停止网关,或者在运行中使用 SQLite 的在线备份:
+
+```bash
+sqlite3 kernel.sqlite3 ".backup kernel.backup.sqlite3"
+sqlite3 management.sqlite3 ".backup management.backup.sqlite3"
+```
+
+丢失不同内容的后果:
+
+| 丢失 | 后果 | 怎么办 |
+| --- | --- | --- |
+| `kernel.sqlite3` | 之前补充的记忆无法放回。每段进行中的对话会有一次服务商缓存未命中,Claude 对话会丢掉一次之前的思考内容([**记忆记录缺失**](12-troubleshooting.md#issues-on-degraded-requests)),尚未保存的轮次也会丢失。 | 无需处理,进行中的对话在一次未命中之后就会恢复 |
+| `management.sqlite3` | 上游、上下文配置、密钥和请求日志全部丢失。 | 重新配置,并签发新密钥 |
+| 加密根密钥(开启加密时) | 两个数据库中已加密的值都无法读取。 | 只能从空的 `storage_path` 重新开始 |
+
+## 下一步 {#next-steps}
+
+- [加密](../guides/22-gateway-operations.md#encryption):为已存的凭证和对话状态开启加密。
+- [删除用户的网关数据](09-gateway-keys.md#delete-a-users-gateway-data):在 Studio 中删除单个用户数据的步骤。
+- [例行检查](../guides/22-gateway-operations.md#day-to-day-operations):需要定期检查的事项,包括备份。
+- [权限矩阵](../api/25-gateway.md#credentials-and-account-scope):每项操作及其所需的凭证。
diff --git a/docs/zh/gateway/12-troubleshooting.md b/docs/zh/gateway/12-troubleshooting.md
new file mode 100644
index 000000000..5e6aff880
--- /dev/null
+++ b/docs/zh/gateway/12-troubleshooting.md
@@ -0,0 +1,218 @@
+---
+description: 根据现象、Studio 标签或错误码,找到 OpenViking 网关问题的原因和解决办法。
+---
+
+# OpenViking 网关排障
+
+客户端报错、记忆没有补充或对话没有保存、Studio 标出异常时,都可以从这一页查起。先看三个地方:**概览**标签页上的 **OpenViking** 卡片、筛选为**异常**的**请求日志**标签页,以及 Server 日志(Docker Compose 部署用 `docker compose logs openviking`,独立网关看它自己的输出)。然后在下面的表格里找到对应现象;每一节都能单独阅读,并链接到相关设置。
+
+## 常见现象 {#common-symptoms}
+
+| 现象 | 可能原因 | 处理 |
+| --- | --- | --- |
+| 开启网关后 Server 随即停止 | 嵌入网关没有通过启动检查。 | [网关无法启动](#the-gateway-does-not-start) |
+| Studio 显示一张卡片,看不到网关标签页 | 网关没有开启、OpenViking API 密钥缺失或无效,或者网关连不上 OpenViking。 | [Studio 显示设置卡片](#studio-shows-a-setup-card) |
+| “上游”和“上下文配置”标签页只读 | 部署者设置了网关管理密钥。 | [解锁编辑](06-manage-in-studio.md#unlock-editing);没人记得密钥时,见[忘记网关管理密钥](../guides/22-gateway-operations.md#lost-the-management-key) |
+| **无法签发密钥** | 新网关密钥要绑定的 OpenViking API 密钥没有通过校验。 | [签发密钥失败](#issuing-a-key-fails) |
+| 客户端报错,请求日志里却没有这条请求 | 请求在到达服务商之前就被网关拒绝了。 | [客户端收到网关返回的错误](#clients-get-an-error-from-the-gateway) |
+| 请求日志中某条请求的状态码为 400 及以上 | 服务商拒绝了请求或调用失败。 | [上游返回错误](#the-upstream-returned-an-error) |
+| 某段对话没有召回,也没有保存 | 检测到 OpenViking 插件,网关把召回、保存和工具都让给了插件。 | 正常行为,避免同一份内容被补充、保存两次,见[两者同时使用时](../guides/15-gateway.md#when-both-are-in-use)。 |
+| 请求不带记忆 | OpenViking 无法访问或超时、预算用完、没有相关内容等。 | [没有补充记忆](#no-memory-is-added) |
+| 保存显示**重试中**,之后变成**已暂停** | OpenViking 拒绝保存或无法访问;或者这段对话的网关密钥已被吊销(`gateway_key_revoked`),例如用户的 OpenViking 密钥被重新生成过。 | OpenViking 恢复后网关会自动恢复保存。密钥被吊销时,重新签发网关密钥,用户的下一个请求会恢复保存。见[OpenViking 中看不到对话](#conversations-do-not-appear-in-openviking)。 |
+| 上下文配置开启了工具,对话里却没有 | 还没有能用工具的请求,第一个能用的请求加载工具清单失败,客户端没有回传完整历史,或者客户端自己接了 OpenViking 工具。 | 在请求日志里查看原因,见[什么时候不提供工具](04-openviking-tools.md#when-tools-are-not-offered)。客户端接了 OpenViking MCP 服务器时出现**客户端已接入 OpenViking 工具**(`tool_name_collision`)是正常的;其他原因修正后开始新对话。 |
+| **首次调用缓存命中率**下降,或者概览提示缓存连续未命中 | 记忆无法原样放回、对话换了上游,或者客户端、中转服务改动了请求开头的内容。 | [首次调用缓存命中率下降](#the-first-call-cache-hit-rate-dropped) |
+| 长对话被服务商以过长为由拒绝 | 网关不知道模型的实际窗口,压缩得太晚。 | [长对话超出上下文长度](#long-conversations-hit-the-context-limit) |
+| 文件导入或下载链接失败 | 没有设置 `public_url` 或设置有误,或者代理没有转发文件相关路径。 | [文件导入或下载失败](#file-imports-or-downloads-fail) |
+| 请求被标上了异常名称 | 网关没能完整处理这条请求。 | [降级请求的异常](#issues-on-degraded-requests) |
+
+## 网关无法启动 {#the-gateway-does-not-start}
+
+嵌入网关无法启动时,整个 OpenViking Server 都会停止。请在 Server 日志中找到启动错误(Compose 中用 `docker compose logs openviking`),再对照下表处理。
+
+| 问题(日志原文) | 原因和处理 |
+| --- | --- |
+| v0.5 数据缺少旧密钥(`holds data encrypted by OpenViking Gateway 0.5`) | 存储目录里有 v0.5 网关加密的数据,但既没有 `OPENVIKING_GATEWAY_ENCRYPTION_KEY`,`storage_path` 下也没有 `encryption.key`。提供原来的密钥,见[迁移](../guides/22-gateway-operations.md#migration)第 5 步。 |
+| 已移除的参数或字段(`unrecognized argument --…`、`Extra inputs are not permitted`) | 独立网关启动时用了已移除的 `openviking-gateway` 参数,或者 `gateway.conf` 里还留着它不接受的字段,例如 `enabled`。把这些设置移到 `gateway.conf` 或环境变量中,见[迁移](../guides/22-gateway-operations.md#migration)第 2 步。`ov.conf` 的 `gateway` 段里残留的旧字段只会打印 `Ignoring removed gateway settings`,不会阻止启动。 |
+| 管理密钥太短(`management_key must resolve to at least 32 characters`) | [网关管理密钥](../guides/22-gateway-operations.md#gateway-management-key)至少要 32 个字符;用 `$VAR` 引用的环境变量没有设置时,也会报这个错。 |
+| 加密设置(`Gateway data is encrypted; configure the encryption settings it was written with`,或加密配置错误) | Server 的 `encryption` 段(嵌入)或 `gateway.conf` 的 `encryption` 块(独立)缺失、不合法,或者加载不了加密根密钥。见[加密指南](../guides/08-encryption.md)。 |
+| 存储格式不兼容(`Unsupported gateway schema`) | 存储目录由不兼容的网关版本写入(更旧的版本,或降级前更新的版本)。换一个空的 `storage_path`。 |
+| 独立运行缺少 OpenViking 地址(`OpenViking Gateway needs an OpenViking server URL`) | 运行 `openviking-gateway init`,或者设置 `OPENVIKING_GATEWAY_OPENVIKING_URL`。 |
+| 独立运行找不到配置文件(`Gateway config file not found`) | `--config` 或 `OPENVIKING_GATEWAY_CONFIG_FILE` 指定的文件不存在。改正路径,或者用 `openviking-gateway init --config <路径>` 生成它。 |
+| 独立运行绑定非回环地址(`A publicly bound OpenViking Gateway requires a successful synchronous probe`) | 启动检查必须连上 OpenViking 并确认它使用 `api_key` 认证,否则网关退出。先启动 OpenViking(在容器中要等它就绪),或者绑定 `127.0.0.1`。 |
+| OpenViking 处于 Trusted 模式(`OpenViking Gateway does not support trusted authentication`) | 仅独立运行:无论绑定什么地址,启动检查都拒绝 OpenViking 的 Trusted 模式。把 OpenViking Server 改为 `api_key` 认证(`server.auth_mode`),见[启动检查](../guides/22-gateway-operations.md#startup-checks)。 |
+
+## Studio 显示设置卡片 {#studio-shows-a-setup-card}
+
+Studio 无法为你加载网关时,会用一张设置卡片代替网关标签页。卡片标题说明了问题所在:
+
+| 卡片 | 处理 |
+| --- | --- |
+| **这台 OpenViking 没有开启网关**(404) | 运行 `openviking-server init` → **Update gateway**,或者在 `ov.conf` 中设置 `gateway.enabled: true` 后重启,见[在 Server 中启用](../guides/22-gateway-operations.md#enable-it-in-the-server)。使用 API 密钥的服务端上,root 也可以直接在卡片上点**开启网关**。账号管理员和普通用户看到的卡片只提示联系部署者开启网关。 |
+| **先连接 OpenViking**,或者 **OpenViking API 密钥无效**(401) | 点**打开连接设置**,填入当前的 OpenViking API 密钥。 |
+| **网关不支持 Trusted 模式**(`trusted_mode_unsupported`) | 把 Server 改为 `api_key` 认证。 |
+| **网关连不上 OpenViking**(`openviking_unreachable`) | 只出现在独立网关:检查 `openviking_url`(`gateway.conf` 或 `OPENVIKING_GATEWAY_OPENVIKING_URL`)和网络。 |
+| **无法加载 OpenViking 网关** | 其他各种失败。卡片会显示网关返回的提示;点**重试**,再根据提示到本页对应的小节排查。 |
+
+**上游**和**上下文配置**标签页只读不属于设置卡片:这是因为部署者设置了[网关管理密钥](../guides/22-gateway-operations.md#gateway-management-key)(`management_key_required`),而 账号管理员或 root 的 API 密钥并不能解锁编辑。点**输入网关管理密钥**,见[解锁编辑](06-manage-in-studio.md#unlock-editing)。服务端更换管理密钥后(`management_key_invalid`),Studio 会重新锁定;没人记得密钥时,见[忘记网关管理密钥](../guides/22-gateway-operations.md#lost-the-management-key)。
+
+## 签发密钥失败 {#issuing-a-key-fails}
+
+签发[网关密钥](09-gateway-keys.md#issue-a-key)之前,网关会先向 OpenViking 校验要绑定的 OpenViking API 密钥。校验不通过时,**签发网关密钥**对话框会显示原因,括号里是管理 API 返回的 `reason`。
+
+| Studio 中的提示 | 原因和处理 |
+| --- | --- |
+| 服务端只保存了这个用户 API 密钥的哈希,无法自动读取。请粘贴该用户的用户 API 密钥。(`user_key_unreadable`) | OpenViking Server 只保存了密钥哈希(`encryption.api_key_hashing.enabled`)。在**粘贴用户 API 密钥**中填入该用户自己的密钥。 |
+| 这是 Root API 密钥,请改用本账号中某个用户的用户 API 密钥。(`root_key_not_allowed`) | root API 密钥不能绑定到网关密钥,改用某个用户或账号管理员的 API 密钥。本地 dev 模式的 `default/default` 不受此限。 |
+| root API 密钥不属于任何用户,请选择这把密钥对应的用户。(`user_required`) | 你以 root 身份登录 Studio,既没有选择用户,也没有粘贴密钥。选择用户,或者粘贴该用户的密钥。 |
+| 这个 OpenViking API 密钥属于其他账号。(`other_account`) | 密钥所属的账号不是你在 Studio 中管理的账号。 |
+| OpenViking 拒绝了这个密钥。(`openviking_http_401`、`openviking_http_403`) | 密钥不完整、已被重新生成,或者用户已被删除。使用该用户当前的密钥。 |
+| OpenViking 无法识别这个密钥所属的用户(`openviking_identity_missing`) | OpenViking 没有返回这个密钥对应的用户。使用本账号中某个用户的密钥。 |
+| 网关连不上 OpenViking,无法校验这个密钥。(`openviking_unavailable`) | 网关访问不到 OpenViking;独立网关检查 `openviking_url`。 |
+| OpenViking 版本低于网关的要求。(`openviking_version_mismatch`) | 仅独立网关:OpenViking Server 低于 `min_server_version`(0.4.16),请升级。从源码安装、没有版本标签的服务可能报告 `0.1.dev123` 这样的开发版本号;请安装正式版本,或者把 `min_server_version` 改成与之匹配的值。 |
+| 没有执行此操作的权限。(`forbidden`) | 粘贴的 OpenViking API 密钥不属于对话框中选中的用户,例如管理员粘贴了自己的密钥,而不是所选用户的。请粘贴所选用户自己的密钥,或者改选密钥所属的用户。普通用户粘贴的密钥不是自己的,也会报这个错。 |
+| 这个用户已不在本账号中,请重新选择。(`unknown_user`) | 对话框打开期间,所选用户被移出了本账号。`unknown_policy` 和 `unknown_upstream` 同理,分别表示所选的上下文配置或上游已被删除。刷新后重新选择。 |
+
+## 客户端收到网关返回的错误 {#clients-get-an-error-from-the-gateway}
+
+网关在转发每个客户端请求之前,会先检查网关密钥、模型和是否有匹配的上游。下面这些拒绝都发生在请求到达服务商之前,所以不会出现在请求日志里。服务商自己返回的错误见[上游返回错误](#the-upstream-returned-an-error)。
+
+| 状态码和提示 | 原因和处理 |
+| --- | --- |
+| 401 "Invalid gateway key. It may have been revoked, or removed because its OpenViking API key was regenerated…" | 客户端没有发送网关密钥,发送了已吊销的密钥或服务商的 API Key,或者用户的 OpenViking API 密钥重新生成后,网关删除了这把密钥。检查客户端实际发送的密钥,必要时[重新签发](09-gateway-keys.md#issue-a-key)。 |
+| 403 "Claude subscription OAuth credentials are not supported" | 客户端发送了 Claude 订阅令牌,例如 Claude Code 用订阅账号登录且没有设置 `ANTHROPIC_AUTH_TOKEN`;或者上游保存的就是订阅令牌。请改用 API Key。 |
+| 403 "Model is not allowed by this key" | 模型不在密钥[允许的模型](09-gateway-keys.md#allowed-models)范围内。签发一把允许这个模型的密钥。 |
+| 400 "Request model is missing"、415 "Compressed request bodies are not supported" | 只出现在限定了模型的密钥上:请求体必须写明模型,且不能经过压缩编码。 |
+| 404 "This upstream is an exact endpoint for … only" | 密钥绑定的上游关闭了**拼接协议接口路径**(见[直接发往完整请求地址](07-upstreams.md#exact-endpoint)),只接受该协议的接口地址,而客户端调用了别的路径,例如 `/v1/models`。 |
+| 404 "No allowed upstream matches this protocol and model" | 密钥绑定的已启用上游中,没有一个使用客户端调用的 API 并提供所请求的模型。检查上游的协议、模型和别名、是否启用,以及密钥绑定了哪些上游。 |
+| 401 "Upstream API key is missing" | 上游要求每个客户端在 `X-OpenViking-Upstream-Key` 中自带 API Key,或者由网关保管 API Key 的上游没有填写。见[凭证](07-upstreams.md#credentials)。 |
+| 403 "Coding Plan upstreams are disabled; configure a model API key" | 上游被标记为 [Coding Plan 密钥](07-upstreams.md#coding-plan-keys)。改用模型 API Key,或者有意勾选**允许通过网关使用这个套餐**。 |
+| 403 "Context policy is unavailable" | 密钥绑定的上下文配置已不存在。用现有的上下文配置重新签发密钥。 |
+| 404 "Unknown response for this key"、403 "Response upstream is no longer allowed" | 查询的 Responses 响应不是这把密钥创建的,或者创建它的上游已停用、不再绑定到这把密钥。 |
+| 413 "Request exceeds configured body limit" | 请求体超过了 `max_body_bytes`(见[请求大小上限](05-long-conversations.md#side-effects)),或者超过了代理自己的上限。 |
+| 426 | 对 Responses API 发起了 WebSocket 连接。这是预期行为,Codex 会改用 HTTP。 |
+| 502 "Model upstream is unavailable" | 网关连不上服务商,或者调用超过了 `upstream_timeout_seconds`。在上游上点**测试**(见[测试和删除](07-upstreams.md#test-and-delete))。 |
+
+"Hidden tool request timed out"(504)发生在调用服务商之后,会记入请求日志,见[失败处理](04-openviking-tools.md#failure-handling)。
+
+## 上游返回错误 {#the-upstream-returned-an-error}
+
+上游错误是服务商自己返回的错误。它在**请求日志**标签页中的那一行,HTTP 状态码为 400 及以上,又没有网关异常,详情里写着**上游返回了 HTTP …,客户端收到了这个错误。**网关把服务商的错误原样交给了客户端。
+
+常见原因有 API Key 填错或过期、服务商不认识这个模型名、触发限流或额度用完、对话超出了模型的上下文窗口,或者服务商故障。在[上游](07-upstreams.md#test-and-delete)上点**测试**,再和客户端收到的错误对照。上下文长度相关的错误见[长对话超出上下文长度](#long-conversations-hit-the-context-limit)。
+
+## OpenViking 异常 {#openviking-is-degraded}
+
+“概览”标签页上的 **OpenViking** 卡片显示网关最近一次检查 OpenViking 的结果。**已连接**表示正常,其他状态如下:
+
+- **启动中**:网关还没完成第一次检查。嵌入网关每秒检查一次,直到 OpenViking 启动。稍后刷新即可。
+- **异常**:最近一次检查失败,卡片会写明原因:
+
+| 原因 | 处理 |
+| --- | --- |
+| OpenViking 无法访问或响应超时(`openviking_unavailable`) | OpenViking 没有运行或无法访问。独立网关检查 `openviking_url` 和网络。 |
+| OpenViking 返回了 HTTP …(`openviking_http_<status>`),或 OpenViking 报告了错误 …(`openviking_<CODE>`) | OpenViking 返回了错误。查看 OpenViking Server 的日志。 |
+| `trusted_mode_unsupported` | OpenViking 使用 Trusted 模式。把它改为 `api_key` 认证。 |
+
+OpenViking 异常期间,请求照常发给模型,只是不带记忆;保存对话会一直重试,直到 OpenViking 恢复。网关会以逐渐拉长的间隔重新检查,最长间隔为 `health_interval_seconds`(默认 60 秒)。
+
+## 没有补充记忆 {#no-memory-is-added}
+
+[召回](08-context-profiles.md#recall-memory)会在每条新的用户消息到达时检索 OpenViking,把找到的内容补充进去;没有补充时,请求日志会写明原因。先在**请求日志**标签页里找到这个请求。找不到,说明客户端没有经过网关,或者请求被网关拒绝了(见[客户端收到网关返回的错误](#clients-get-an-error-from-the-gateway))。找到后展开它,查看详情中的**召回**:
+
+| 召回结果 | 含义 | 处理 |
+| --- | --- | --- |
+| **没有找到相关内容**(`empty`) | 新用户通常如此。对话提交、OpenViking 提取之后才会有记忆。 | 继续使用即可;一直没有记忆时,见[OpenViking 中看不到对话](#conversations-do-not-appear-in-openviking)。 |
+| **召回已关闭或预算已用完**(`disabled`) | 上下文配置关闭了召回,当前上下文窗口剩下的召回预算不足 64 token,或者消息短于 3 个字符。 | 召回被关闭时,在上下文配置中打开。 |
+| **剩余预算不足,未补充记忆**(`budget`) | 这条消息的召回预算扣掉记忆块的包装后,留给检索结果的不足 64 token,所以没有检索。可能是这段对话快用完了**单个上下文窗口预算**(进入下一个上下文窗口后重新计算,例如压缩之后),也可能是**单条消息预算**设得太低,接近 64 token 的下限。 | **单条消息预算**接近下限时,调大它。 |
+| **OpenViking 无法访问或响应超时**(`openviking_unavailable`)、**召回超时**(`recall_timeout`) | 检索没有完成。 | 查看 OpenViking 卡片(见[OpenViking 异常](#openviking-is-degraded))。OpenViking 在运行但响应慢时,调长**超时时间**。 |
+| **OpenViking 拒绝了这个密钥**(`openviking_http_401`) | 用户的 OpenViking 密钥已失效。 | 用当前的密钥签发新的网关密钥,见[用户的 OpenViking API 密钥变了](09-gateway-keys.md#when-the-openviking-key-changes)。 |
+| **OpenViking 返回了 HTTP …**(`openviking_http_<status>`)或 **OpenViking 报告了错误 …**(`openviking_<CODE>`) | 检索在 OpenViking 内部失败。OpenViking Server 低于 `min_server_version` 时也可能这样失败。 | 查看 OpenViking Server 的日志。 |
+| **检测到 OpenViking 插件**(`plugin_present`) | 网关发现了 OpenViking 插件,让出了这段对话。 | 正常行为,见[两者同时使用时](../guides/15-gateway.md#when-both-are-in-use)。 |
+| **类型**不是**新消息** | 工具步骤、辅助请求和子 Agent 请求从不检索,它们放回之前的消息得到的记忆。 | 无需处理,见[请求类型](10-overview-and-requests.md#request-types)。 |
+
+检索失败的消息之后也不会补上记忆;下一条消息会重新检索。
+
+## OpenViking 中看不到对话 {#conversations-do-not-appear-in-openviking}
+
+[保存](08-context-profiles.md#save-conversations)会把每一轮完成的对话写进名为 `gateway-…` 的 OpenViking 会话,会话属于网关密钥背后的 OpenViking 用户。预期中的某一轮没有出现时,对照下表:
+
+| 看到的情况 | 原因 | 处理 |
+| --- | --- | --- |
+| 缺少最新的一轮 | 保存晚一轮:下一条消息到达时,上一轮才会出现;最后一轮要等**最新回复等待时长**(默认 10 分钟)。 | 稍等,或者发送下一条消息。 |
+| **保存**列显示**已关闭** | 上下文配置不保存对话。 | 在上下文配置中打开保存;修改只对新对话生效(见[修改何时生效](06-manage-in-studio.md#when-changes-take-effect))。 |
+| **重试中**或**已暂停** | 保存失败,展开的行会显示原因。 | 修复原因(例如让 OpenViking 恢复访问)后,网关会在 5 分钟内重试。原因为 `gateway_key_revoked` 时,重新签发网关密钥,下一个请求会恢复保存。对话一直暂停时,用**重新同步对话…**(见[重新同步对话](10-overview-and-requests.md#resync-a-conversation))。 |
+| **检测到 OpenViking 插件**(`plugin_present`) | 检测到 OpenViking 插件的对话,网关不保存任何内容。 | 正常行为;同一个客户端在插件和网关之间二选一。 |
+| 会话里只有部分对话 | 以下情况下,网关会把当前历史写进新的 `gateway-…` 会话:客户端编辑、重新生成或压缩了历史(`history_changed`、`history_changed_during_delivery`),已在**最新回复等待时长**之后保存的一轮又继续了(`continued_after_idle`),或者有人用了**重新同步对话…**(`manual_reset`)。之前的轮次留在旧会话里。 | 到旧会话里找,见[保存状态](10-overview-and-requests.md#saving-status)。 |
+| 完全看不到 `gateway-…` 会话 | 你查看时用的 OpenViking 用户,不是网关密钥背后的那个用户。 | 换成那个用户查看。 |
+| 会话出现了,记忆还没有 | OpenViking 在提交之后才在后台提取记忆。 | 等提取完成。 |
+
+## 首次调用缓存命中率下降 {#the-first-call-cache-hit-rate-dropped}
+
+“概览”标签页上的**首次调用缓存命中率**,是每条新用户消息的第一次模型调用中,命中服务商[提示词缓存](01-how-it-works.md#replay)的输入 token 所占的比例。正常情况下它接近不经过网关时服务商能达到的水平,所以先和这个水平比较,再看最近请求上标出的异常和概览上的提示:
+
+| 看到的情况 | 原因 | 处理 |
+| --- | --- | --- |
+| **记忆记录缺失**(`missing_injection_record`) | 网关存储丢失、从旧备份恢复,或者记录已过期,之前补充的记忆无法放回。 | 无需处理,进行中的对话在一次未命中之后就会恢复。 |
+| **上游已切换**(`upstream_changed`) | 对话原来的上游被停用、没有绑定到客户端当前用的密钥,或者不再提供这个模型,于是对话转到了另一个上游。 | 重新启用这个上游,或者让客户端改用包含它的密钥,见[路由](07-upstreams.md#routing)。 |
+| **缓存参数有变化**(`ark_cache_parameters_changed`) | 在火山方舟或 BytePlus 方舟上,客户端在同一段对话里改变了模型、思考模式、采样参数、系统提示词或工具。 | 在同一段对话里保持这些参数不变。 |
+| 没有标出异常 | 客户端本身可能每轮都在改动之前的消息或系统提示词,例如插入当前时间,网关无法修正。每次压缩、模型每次开启新的上下文窗口,也都会造成一次未命中,这是预期内的。 | 检查客户端的系统提示词里有没有每次都变的内容。 |
+| **有 … 段长对话连续没有命中提示词缓存**,或者命中率一直是 0%,而服务商或中转服务后台的缓存记录有命中 | 上游没有把缓存用量传回网关,例如中转服务转换协议时丢掉了缓存字段。网关读取 `cache_read_input_tokens`、`prompt_tokens_details.cached_tokens`、`input_tokens_details.cached_tokens`、`prompt_cache_hit_tokens` 等常见字段。 | 让中转服务把缓存用量原样传回。 |
+| 同上,或者提示**上游 … 最近没有返回过缓存命中**,而服务商后台也没有命中 | 根本没有用上缓存。 | 检查服务商是否支持提示词缓存、Anthropic 客户端是否设置了 `cache_control`,以及中转服务是否在多个账号或渠道之间轮换。 |
+
+## 长对话超出上下文长度 {#long-conversations-hit-the-context-limit}
+
+[压缩](05-long-conversations.md#long-conversations)会在长对话占满模型上下文窗口之前,用一份摘要替换较早的历史。服务商仍以对话过长为由拒绝请求时,通常是下面三种原因之一:
+
+| 原因 | 处理 |
+| --- | --- |
+| 网关不知道模型的窗口大小:上游的**上下文窗口**里没有这个模型,上下文配置也没有设置**默认上下文窗口**,网关就按默认的 1,000,000 token 计算,对窗口更小的模型压缩得太晚。 | 补上模型的窗口大小,见[设置模型的上下文窗口](05-long-conversations.md#context-window)。 |
+| 对话所用的上下文配置关闭了压缩。 | 打开压缩;修改上下文配置只对新对话生效(见[修改何时生效](06-manage-in-studio.md#when-changes-take-effect))。 |
+| 压缩失败。请求详情会显示**压缩失败**及下表中的某个原因。 | 见下表。 |
+
+| 原因 | 说明和处理 |
+| --- | --- |
+| `summary_incomplete` | 摘要回复没有正常结束,通常是碰到了长度上限。调大**摘要长度上限**。 |
+| `summary_http_<status>` | 摘要请求被拒绝,可能来自上游,也可能是网关在发送前就拦下了(没有上游 API Key,或 Coding Plan 检查不通过)。检查上游的 API Key、模型和 Coding Plan 设置。状态码为 400 时,网关已经去掉额外的输出余量重试过一次。 |
+| `summary_unavailable` | 上游无法访问、超时(`upstream_timeout_seconds`),或者返回的不是 JSON。 |
+| `summary_tool_call`、`summary_empty` | 模型调用了工具,或者没有返回文本,而不是写出摘要。 |
+| `cut_not_found` | 客户端最新的消息和网关存下的历史对不上,网关无法确定截断点。通常是暂时的。 |
+| `summary_failed` | 意外的内部错误。在网关日志里查找 "OpenViking Gateway summary failed"。 |
+| `still_over_threshold` | 摘要已经写好并保留,但用量仍达到**压缩时机**:系统提示词、工具和摘要本身就占满了大部分窗口。调小**摘要长度上限**,或者检查模型的上下文窗口设置。 |
+
+除 `still_over_threshold` 外,其他原因下这次请求都发送了完整历史。无论哪种原因,网关都会等 60 秒再尝试压缩这段对话。
+
+## 文件导入或下载失败 {#file-imports-or-downloads-fail}
+
+[导入文件](04-openviking-tools.md#import-files-and-skills)时,网关会在自己的[对外地址](../guides/22-gateway-operations.md#public-address)上给客户端生成上传和下载链接。对照看到的错误处理:
+
+| 错误 | 处理 |
+| --- | --- |
+| "Set gateway.public_url for client uploads and downloads" | 把 `public_url` 设为客户端能访问的地址,或者把 `mcp_file_links` 设为 `direct`。 |
+| 上传或下载链接无法访问或返回 404 | 确认 `public_url` 不是旧的 `:1935` 地址,也没有以 `/gateway` 结尾,并且代理像其他路径一样转发 `/gateway/uploads` 和 `/gateway/downloads`。`mcp_file_links` 设为 `direct` 时,改查 Server 的 `OPENVIKING_PUBLIC_BASE_URL`。 |
+| 413 "Upload exceeds configured body limit" | 文件超过了 `max_body_bytes` 或代理的上限。 |
+| 502 "OpenViking upload is unavailable" 或 "OpenViking download is unavailable" | 网关连不上 OpenViking Server。 |
+| 模型没有导入工具 | OpenViking 服务没有提供该工具,上下文配置没有勾选,或者当前请求不能使用网关工具。检查工具清单和请求详情。 |
+
+## 降级请求的异常 {#issues-on-degraded-requests}
+
+降级请求是网关没能完整处理的请求,“请求日志”和“概览”标签页会把它标出来。Studio 显示异常名称,括号里是管理 API 中对应的值:
+
+| 异常 | 发生了什么 | 怎么处理 |
+| --- | --- | --- |
+| 记忆不可用(`memory_store_failure`) | 网关无法读写自己的存储,或者该用户的网关数据刚被删除。请求不带记忆发给了模型;Claude 对话中之前的思考内容被去掉。 | 检查磁盘空间、权限和网关日志。刚[删除过该用户的网关数据](09-gateway-keys.md#delete-a-users-gateway-data)时出现属于正常。 |
+| 原样转发(`unsafe_json`) | 请求中有无法精确重新编码的数字或重复的键,网关逐字节原样转发,没有补充记忆。 | 通常只与某个客户端有关,网关这边无需调整。 |
+| 上游已切换(`upstream_changed`) | 对话原来的上游无法再服务,转到了另一个上游,造成一次缓存未命中,之前的 Claude 思考内容也被去掉。 | 重新启用这个上游,或者让客户端改用包含它的密钥;也可以接受这次切换。 |
+| 记忆记录缺失(`missing_injection_record`) | Claude 对话中,之前补充的记忆已经没有记录,之前的思考内容被去掉一次。 | 存储丢失后,或者在很久以前的对话里出现,都在预期之内。反复出现时,开始新对话。 |
+| 检测到 OpenViking 插件(`plugin_present`) | 检测到 OpenViking 插件,这段对话不再使用网关记忆。 | 使用插件时出现属于正常。同一个客户端在插件和网关之间二选一。 |
+| 缓存参数有变化(`ark_cache_parameters_changed`) | 在火山方舟或 BytePlus 方舟上,影响缓存的参数与对话的第一个请求不同,提示词缓存很可能没有命中。 | 在同一段对话里保持模型、思考模式、采样参数、系统提示词和工具不变。 |
+| 工具历史无法继续使用(`hidden_tool_history_unavailable`) | Claude 对话用过 OpenViking 工具,但当前请求不能使用这些工具,之前的思考内容已被去掉。 | 查看请求详情中的工具停用原因,恢复原设置,或者开始新对话。 |
+| OpenViking 工具调用失败(`hidden_tool_loop_failed`) | 模型使用 OpenViking 工具时未能完成回答,客户端收到错误。 | 见[失败处理](04-openviking-tools.md#failure-handling)。 |
+| 模型未返回回答(`hidden_reply_without_anchor`) | 模型在这次请求中使用了 OpenViking 工具,但没有返回可用于继续对话的内容。客户端仍收到了回复,但下一轮无法沿用这次工具调用的结果。 | 重试本次提问,或开始一段新对话。 |
+| 回复未保存(`capture_parse_failure`) | 流式回复无法解析,这条回复没有保存,客户端不受影响。 | 无需处理,仅供了解。 |
+| 密钥未校验(`revocation_check_unavailable`) | OpenViking 无法确认这把网关密钥,请求在没有检查是否已吊销的情况下照常处理。 | 检查 OpenViking 是否可达、运行是否正常。 |
+
+## 下一步 {#next-steps}
+
+- [网关概览与请求日志](10-overview-and-requests.md#requests):了解请求日志中每一列、每个标签和每种保存状态的含义。
+- [观测](../guides/22-gateway-operations.md#monitoring):用 `/health` 检查存活,通过管理 API 查看网关状态,在用户发现问题之前先察觉。
+- [配置参考](13-configuration.md#gateway-fields):查找本页提到的 `max_body_bytes`、`public_url`、`min_server_version` 等字段。
diff --git a/docs/zh/gateway/13-configuration.md b/docs/zh/gateway/13-configuration.md
new file mode 100644
index 000000000..c2516feaa
--- /dev/null
+++ b/docs/zh/gateway/13-configuration.md
@@ -0,0 +1,183 @@
+---
+description: 查询 OpenViking 网关的配置字段、环境变量、上下文配置设置和上游设置。
+---
+
+# OpenViking 网关配置参考
+
+本页供修改 `ov.conf`、`gateway.conf` 或环境变量的运维人员查阅,也方便把 Studio 中的名称对应到管理 API 的字段名。每张表都列出名称、默认值和可选值;设置的作用和什么时候需要改,见各节链接的功能页面。
+
+## 配置放在哪里 {#configuration-reference}
+
+嵌入网关和独立网关的字段大部分相同,区别在于写在哪个文件里、用什么命令生成。只有一种部署形态使用的字段,在[网关字段](#gateway-fields)的“适用于”一列中标出。
+
+| | 嵌入 | 独立 |
+| --- | --- | --- |
+| 文件 | `ov.conf` 的 `gateway` 段 | `gateway.conf` 的根层,没有 `gateway` 外层 |
+| 生成命令 | `openviking-server init` | `openviking-gateway init` |
+| 读取哪个文件 | Server 自己的 `ov.conf` | `--config` 或 `OPENVIKING_GATEWAY_CONFIG_FILE` 指定的文件,且文件必须存在;两者都没设置时,读取 `~/.openviking/gateway.conf` 和 `/etc/openviking/gateway.conf` 中第一个存在的文件 |
+| host、port 和 workers | 跟随 Server | 由 `host`、`port`、`workers` 字段设置 |
+
+`OPENVIKING_CONFIG_FILE` 只用来选择 Server 的配置,不会让独立网关读取它指向的文件。
+
+## 网关字段 {#gateway-fields}
+
+| 字段 | 适用于 | 默认值 | 可选值 | 含义 |
+| --- | --- | --- | --- | --- |
+| `enabled` | 嵌入 | `false` | | 在 Server 中开启网关 |
+| `openviking_url` | 独立 | —(必填) | HTTP(S) URL | OpenViking Server 的地址 |
+| `host` | 独立 | `127.0.0.1` | | 监听地址 |
+| `port` | 独立 | `1935` | 1–65,535 | 监听端口 |
+| `workers` | 独立 | `1` | 1–64 | worker 进程数 |
+| `public_url` | 两者 | 空 | HTTP(S) URL,不带 `/gateway` | 客户端访问的对外地址,`/gateway` 由网关自己加。为空时,嵌入网关沿用 Server 的对外地址;两者都没有时,接入指南使用请求来源地址,MCP 文件上传和下载也不可用(`mcp_file_links` 为 `direct` 时除外)。见[对外地址](../guides/22-gateway-operations.md#public-address) |
+| `mcp_file_links` | 两者 | `proxy` | `proxy`、`direct` | MCP 上传和下载工具返回的链接如何交给客户端。`proxy` 改写为 `public_url` 加 `/gateway/uploads` 或 `/gateway/downloads`,需要设置 `public_url`。`direct` 原样透传 OpenViking 的链接,需要 Server 的 `OPENVIKING_PUBLIC_BASE_URL`(或 `server.public_base_url`)是客户端能访问的地址 |
+| `storage_path` | 两者 | `~/.openviking/gateway` | | 本地存储目录 |
+| `encryption` | 独立 | 不设置(明文) | 字段同 `ov.conf` 的 `encryption` 段 | 加密本地保存的数据,见[加密](../guides/22-gateway-operations.md#encryption);嵌入网关沿用 Server 的设置 |
+| `management_key` | 两者 | 空 | 至少 32 个字符 | 可选的[网关管理密钥](../guides/22-gateway-operations.md#gateway-management-key) |
+| `min_server_version` | 两者 | `0.4.16` | 版本号 | 独立网关要求的 OpenViking Server 最低版本 |
+| `session_ttl_days` | 两者 | `30` | 1 及以上 | 对话闲置多少天后过期 |
+| `response_ttl_seconds` | 两者 | `2592000`(30 天) | 60 及以上 | Responses 响应与上游的对应关系保留多少秒 |
+| `log_retention_days` | 两者 | `30` | 1 及以上 | 请求日志保留天数 |
+| `max_body_bytes` | 两者 | `33554432`(32 MiB) | 1,024 及以上 | 请求和上传的大小上限,单位为字节 |
+| `upstream_timeout_seconds` | 两者 | `600` | 大于 0 | 服务商请求超时 |
+| `health_interval_seconds` | 两者 | `60` | 1 及以上 | 检查 OpenViking 状态的间隔秒数 |
+
+## 环境变量 {#environment-variables}
+
+每个网关字段都能用环境变量设置,变量名是 `OPENVIKING_GATEWAY_` 加上大写的字段名,两种部署形态都适用:
+
+```bash
+OPENVIKING_GATEWAY_PUBLIC_URL=https://ov.example.com
+OPENVIKING_GATEWAY_MANAGEMENT_KEY='<management-key>'
+```
+
+- **环境变量优先于配置文件。** 非空的环境变量覆盖文件中的值,值为空等于没有设置。
+- 以 `tcp://` 或 `udp://` 开头的值会被忽略。这样,Kubernetes 为名为 `openviking-gateway` 的 Service 自动注入的变量(例如 `OPENVIKING_GATEWAY_PORT=tcp://…`)不会覆盖文件。
+- 文件中的值也可以写成 `"$VAR"`,从环境变量中取值。
+- `encryption` 块只能写在文件里。
+- 容器通常不需要配置文件,用环境变量设置需要的字段即可。
+
+## 校验 {#validation}
+
+| 对象 | 规则 |
+| --- | --- |
+| `openviking_url` 和 `public_url` | 必须是 HTTP(S),不能含凭证、查询参数或 fragment |
+| 上游的 `base_url` | 规则不同,见[接口](07-upstreams.md#endpoint) |
+| `management_key` | 解析 `$VAR` 引用后至少 32 个字符;`$VAR` 没能解析时校验失败 |
+| 未知字段 | 校验失败 |
+| 已删除的字段 | 忽略,启动时打印警告:`encryption_key_env`,以及 `ov.conf` 中[迁移](../guides/22-gateway-operations.md#migration)列出的 v0.5 字段 |
+
+## 上下文配置的设置 {#context-profile-settings}
+
+在 Studio 中:**上下文配置** → 打开一份配置。下面几张表按编辑器的分区排列,先写 Studio 中的名称,再写管理 API 中的名称(管理 API 把上下文配置称为 `policies`)。**名称**(`name`,默认 `Default`)是配置的显示名称;各分区的作用见[上下文配置](08-context-profiles.md#context-profiles)。
+
+### 召回记忆 {#profile-recall}
+
+作用见[召回记忆](08-context-profiles.md#recall-memory)。
+
+| Studio 名称 | API 名称 | 默认值 | 取值范围 | 含义 |
+| --- | --- | --- | --- | --- |
+| 召回记忆 | `recall` | `true` | | 为每条新的用户消息检索记忆。 |
+| 会话开头提供用户画像 | `profile` | `true` | | 新对话开始时提供画像,独立于召回。 |
+| 开头内容预算 | `profile_max_tokens` | `4000` | 0–32,000 | 画像和目录的独立预算;0 表示省略。目录需要提供 OpenViking 的 `read` 工具(`openviking_read`)。 |
+| 显示召回摘要 | `show_recall` | `false` | | 在回复开头说明 OpenViking 补充了什么,或召回失败的原因。模型看不到。 |
+| 检索范围 | `context_types` | `memory`、`resource`、`skill` | 开启召回时至少一个(仅 Studio 校验) | 检索哪些内容:记忆、资源、技能。 |
+| 单条消息预算 | `max_tokens` | `1600` | 64–32,000 | 一条消息最多补充的 token 数。 |
+| 单个上下文窗口预算 | `session_max_tokens` | `30000` | 0 及以上 | 一个上下文窗口内最多补充的 token 数,每次压缩后重新计算;0 表示关闭召回。 |
+| 相关度阈值 | `score_threshold` | `0.35` | 0–1 | 接受的最低相关度分数。 |
+| 超时时间 | `recall_timeout` | `2`(秒) | 大于 0,最多 30 | 检索最多等多久,超时后消息不带记忆继续发送。 |
+| 检索文本长度 | `query_max_chars` | `8000` | 3–32,000 | 取消息的多少个字符作为检索文本。 |
+| 按分类限量 | `quotas` | `{}`(关闭) | 键:`events`、`entities`、`preferences`、`experiences`、`resources`、`skills`;设置时至少一项大于 0(仅 Studio 校验) | 每个分类最多取的条数;只检索大于 0 的分类。 |
+
+管理 API 保存 `context_types` 和 `quotas` 时不做校验。`quotas` 里出现未知的键时,OpenViking 会拒绝检索请求,导致每次召回都失败。
+
+### 保存对话 {#profile-saving}
+
+作用见[保存对话](08-context-profiles.md#save-conversations)。
+
+| Studio 名称 | API 名称 | 默认值 | 取值范围 | 含义 |
+| --- | --- | --- | --- | --- |
+| 保存对话 | `capture` | `true` | | 把完成的轮次保存到 OpenViking。 |
+| 最新回复等待时长 | `idle_seconds` | `600`(秒) | 1 及以上 | 停顿多久之后保存最后一轮并提交会话。 |
+| 提交阈值 | `commit_tokens` | `20000` | 1 及以上 | 会话中待提交的 token 数达到这个值时提交。 |
+| 保留最近消息 | `keep_recent_messages` | `10` | 0–1,000 | 提交后会话中保留的消息数。 |
+
+### 长对话 {#profile-long-conversations}
+
+作用见[网关中的长对话](05-long-conversations.md#long-conversations)。
+
+| Studio 名称 | API 名称 | 默认值 | 取值范围 | 含义 |
+| --- | --- | --- | --- | --- |
+| 压缩 | `compaction` | `true` | | 接近上下文窗口时,用摘要替换对话较早的部分。 |
+| 压缩时机 | `compaction_threshold` | `0.9` | 0.5–0.98 | 上下文窗口用到多大比例时压缩。 |
+| 摘要长度上限 | `summary_max_tokens` | `8000` | 1,000–32,000 | 一份摘要最多多少 token。 |
+| 默认上下文窗口 | `context_window` | 未设置(按 1,000,000 计算) | 1,024 及以上 | 上游没有列出该模型时使用的窗口,见[设置模型的上下文窗口](05-long-conversations.md#context-window)。 |
+| Agent 自管上下文窗口 | `agent_windows` | `false` | | 实验性。让模型自己开启新的上下文窗口;需要 OpenViking 工具。 |
+| 软提醒时机 | `window_soft_ratio` | `0.7` | 0.3–0.95,须低于 `window_hard_ratio` | 窗口用到这个比例时,提醒模型尽快开启新窗口。 |
+| 硬提醒时机 | `window_hard_ratio` | `0.85` | 0.4–0.97 | 窗口用到这个比例时,要求模型立即开启新窗口。 |
+
+### OpenViking 工具 {#profile-tools}
+
+作用见[选择工具](04-openviking-tools.md#choose-tools)和[上限](04-openviking-tools.md#limits)。
+
+| Studio 名称 | API 名称 | 默认值 | 取值范围 | 含义 |
+| --- | --- | --- | --- | --- |
+| OpenViking 工具 | `gateway_tools` | `true` | | 为 Chat Completions、完整历史的 Responses 和 Anthropic Messages 提供 OpenViking 工具。 |
+| 工具(未勾选的项) | `disabled_tools` | 会修改数据的 8 个工具 | OpenViking 工具原名,不带 `openviking_` | 新对话不提供这些工具,其余可用工具都提供,包括以后新增的。 |
+| 显示工具调用 | `show_tool_calls` | `true` | | 每次 OpenViking 工具调用都在回复里加一行提示。 |
+| 每次请求的工具轮数 | `tool_max_rounds` | `null`(不限) | 1 及以上 | 工具调用达到这个轮数后,拒绝继续调用 OpenViking 工具。 |
+| 单次调用超时 | `tool_timeout_seconds` | `30`(秒) | 大于 0,最多 120 | 超时的调用向模型返回错误。 |
+| 结果大小上限 | `tool_result_bytes` | `65536`(字节) | 1,024–1,048,576 | 超出部分在交给模型前截掉。 |
+| 总时长 | `tool_total_seconds` | `null`(不限) | 大于 0 | 超过这个秒数模型仍在调用工具时,请求失败。 |
+| Token 预算 | `tool_total_tokens` | `null`(不限) | 1,024 及以上 | 工具调用和结果在一次请求中最多增加的估算 token 数,用完后拒绝继续调用 OpenViking 工具。 |
+
+API 请求省略 `disabled_tools` 时使用默认列表;列表为空且 `gateway_tools` 开启时,提供全部可用工具。
+
+## 上游设置 {#upstream-settings}
+
+在 Studio 中:**上游** → 打开一个上游。下面几张表按编辑器的四个分区排列;各字段的作用见[上游](07-upstreams.md#upstreams)。
+
+### 接口 {#upstream-endpoint}
+
+| Studio 名称 | API 名称 | 默认值 | 可选值 | 含义 |
+| --- | --- | --- | --- | --- |
+| 名称 | `name` | —(必填) | | 显示名称。 |
+| 服务商 | `vendor` | `generic` | `generic`、`anthropic`、`openai`、`deepseek`、`ark`(火山方舟)、`byteplus`(BytePlus 方舟) | Studio 只提供服务商支持的协议,API 接受任意组合。 |
+| 协议 | `protocol` | —(必填) | `anthropic`(Anthropic Messages)、`chat`(Chat Completions)、`responses`(Responses) | 这个上游使用的 API。 |
+| Base URL | `base_url` | —(必填) | HTTP(S) URL | 服务商地址;默认地址见[什么是上游](07-upstreams.md#upstreams),拼接规则见[接口](07-upstreams.md#endpoint)。 |
+| 拼接协议接口路径 | `append_endpoint_path` | `true` | | 拼接所选协议的接口路径;关闭时把 `base_url` 直接作为完整请求地址。 |
+
+### 凭证 {#upstream-credentials}
+
+| Studio 名称 | API 名称 | 默认值 | 可选值 | 含义 |
+| --- | --- | --- | --- | --- |
+| API Key 由谁提供 | `auth_mode` | `managed` | `managed`(由网关保管 API Key)、`passthrough`(每个客户端自带 API Key) | 见[凭证](07-upstreams.md#credentials)。 |
+| 密钥发送方式 | `key_header` | `authorization` | `authorization`(Bearer)、`api-key`、`x-api-key` | `base_url` 含 `{api_key}` 时不生效。 |
+| API Key | `api_key` | 空 | | 只写,见[凭证](07-upstreams.md#credentials)。 |
+| 额外请求头 | `headers` | `{}` | 请求头名称 → 取值 | 只写,见[凭证](07-upstreams.md#credentials)。 |
+| 这是 Coding Plan 或订阅密钥 | `coding_plan` | `false` | | 除非另外允许,否则拒绝发往这个上游的请求。 |
+| 允许通过网关使用这个套餐 | `allow_coding_plan` | `false` | | 允许使用被标记为 Coding Plan 的密钥。 |
+
+### 模型 {#upstream-models}
+
+| Studio 名称 | API 名称 | 默认值 | 可选值 | 含义 |
+| --- | --- | --- | --- | --- |
+| 模型 | `models` | `[]` | 模型名 | 提供的模型名;留空表示接受任何名称。 |
+| 模型别名 | `aliases` | `{}` | 客户端使用的名称 → 发给上游的模型 | |
+| 上下文窗口 | `context_windows` | `{}` | 模型 → token 数,每项至少 1,024 | 各模型的上下文窗口,见[设置模型的上下文窗口](05-long-conversations.md#context-window)。 |
+
+### 路由 {#upstream-routing}
+
+| Studio 名称 | API 名称 | 默认值 | 可选值 | 含义 |
+| --- | --- | --- | --- | --- |
+| 优先级 | `priority` | `0` | 整数 | 数值越大,新对话越优先使用。 |
+| 启用 | `enabled` | `true` | | 停用的上游不接收请求。 |
+| 允许 OpenViking 工具 | `allow_gateway_tools` | `true` | | 能否通过这个上游提供 OpenViking 工具。 |
+| 补全推理内容回传 | `replay_reasoning` | `null`(跟随服务商) | `null`、`true`、`false` | 把客户端丢掉的推理内容补回之前的回复。`null` 时 `deepseek`、`ark` 和 `byteplus` 开启,其他服务商关闭;`true` 或 `false` 覆盖服务商默认值。Studio 中开关与服务商默认值一致时保存为 `null`。 |
+| 最小可缓存长度 | `cache_min_tokens` | `1024` | 0 及以上 | 仅火山方舟和 BytePlus 方舟;影响缓存资格的报告。 |
+
+## 下一步 {#next-steps}
+
+- [独立部署](../guides/22-gateway-operations.md#standalone-deployment):生成 `gateway.conf`,单独运行网关。
+- [在 Server 中启用](../guides/22-gateway-operations.md#enable-it-in-the-server):在 `ov.conf` 中开启嵌入网关。
+- [上下文配置](08-context-profiles.md)和[上游](07-upstreams.md):用 Studio 的说法解释上面这些设置的作用。
+- [管理 API](../api/25-gateway.md):网关密钥的字段、全部管理操作、权限规则和错误原因。
diff --git a/docs/zh/guides/15-gateway.md b/docs/zh/guides/15-gateway.md
index 08a3a4b30..397e87811 100644
--- a/docs/zh/guides/15-gateway.md
+++ b/docs/zh/guides/15-gateway.md
@@ -6,8 +6,6 @@ description: 把任何使用 API Key 的模型客户端指向 OpenViking 网关
OpenViking 网关是一个模型 API 代理:客户端只要能修改 Base URL,接上它就能用上 OpenViking 记忆。接入只改两处:Base URL 换成网关地址,模型服务商的 API Key 换成网关密钥。不用装插件,也不用改代码或提示词。
-想先直观了解网关的工作原理,可以看官网的动画演示:[openviking.ai/gateway](https://openviking.ai/gateway)。
-
网关在转发请求时完成三件事:
| 能力 | 网关做什么 |
@@ -16,461 +14,155 @@ OpenViking 网关是一个模型 API 代理:客户端只要能修改 Base URL
| 主动使用记忆 | 模型可以调用 OpenViking 工具检索、读取、写入和导入资料。工具由网关执行,客户端不用声明或实现任何工具。 |
| 沉淀与压缩 | 网关把对话保存回 OpenViking,由 OpenViking 从中提取新记忆。对话接近模型的上下文窗口时,网关让同一个模型写摘要,替换较早的内容。 |
-**适合谁**:装不了插件或 MCP 的客户端,例如聊天应用、SDK 脚本和低代码平台;以及想集中管理模型服务商、密钥和记忆设置的团队。**不适用**:直接用订阅账号登录的客户端(可以改用[订阅反代上游](#自定义上游)),以及 Cursor、Trae 这类从厂商服务器发起模型调用的客户端。
-
-网关支持三种模型 API:Anthropic Messages、OpenAI Chat Completions 和 OpenAI Responses(要求每个请求带完整历史)。请求转发到你配置的模型服务地址,本文称为**上游**。请求用哪种 API 发来,网关就用同一种 API 转发,不做协议转换。
+想先直观了解网关的工作原理,可以看官网的动画演示:[openviking.ai/gateway](https://openviking.ai/gateway)。想马上接入客户端,直接看[把客户端接入 OpenViking 网关](../gateway/03-connect-clients.md);其他任务或 Studio 标签页对应哪一页,见[下一步去哪](#next-steps)。
-网关目前处于 Beta 阶段。本页介绍它的工作方式和客户端接入;部署、Studio 中的管理和排障见[OpenViking 网关部署与运维](22-gateway-operations.md)。
+> **注意**:OpenViking 网关目前处于 Beta 阶段。它和 VikingBot Gateway(`vikingbot gateway`)是两个组件,后者负责远程访问和聊天平台接入。
-> **注意**:OpenViking 网关和 VikingBot Gateway(`vikingbot gateway`)是两个组件。后者负责远程访问和聊天平台接入。
+## 适合谁 {#who-it-is-for}
-## 自定义上游
+- **适合**:装不了插件或 MCP 的客户端,例如聊天应用、SDK 脚本和低代码平台;以及想集中管理模型服务商、密钥和记忆设置的团队。
+- **不适用**:直接用订阅账号登录的客户端(可以改用[订阅反代上游](../gateway/07-upstreams.md#custom-upstreams),Codex 就可以这样使用 ChatGPT 订阅,见[使用 ChatGPT 订阅](../gateway/03-connect-clients.md#codex-chatgpt-subscription)),以及 Cursor、Trae 这类从厂商服务器发起模型调用的客户端。
-任何兼容这三种 API 之一的服务都能添加为上游,不一定是模型服务商本身。两种常见用法:
+网关支持三种模型 API:Anthropic Messages、OpenAI Chat Completions 和 OpenAI Responses(要求每个请求带完整历史,见[客户端要求](../gateway/04-openviking-tools.md#client-requirements))。请求转发到你配置的模型服务地址,称为**上游**。请求用哪种 API 发来,网关就用同一种 API 转发,不做协议转换。
-- **计费、配额和负载均衡。** 网关不做这些。需要时在网关后面接一层 LiteLLM、new-api 这类服务,把它添加为上游。
-- **使用订阅额度。** 客户端不能用订阅账号登录网关,但可以把 [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) 这类反向代理添加为上游。它把 ChatGPT(Codex)、Claude 等订阅账号包装成 API,例如 Codex 就能经网关使用 ChatGPT 订阅额度。OpenAI Codex 负责人 Tibo 曾[公开介绍](https://x.com/thsottiaux/status/2076119366647894371)过用 CLIProxyAPI 接入 Codex 订阅的做法。**是否符合服务商的使用条款,请自行确认。**
+## 关键术语 {#key-terms}
-添加时服务商选*通用*,见[上游](22-gateway-operations.md#上游)。
+网关文档的各个页面都按下表的含义使用这些术语。同一 OpenViking 账号的用户共用上游和上下文配置;网关密钥和请求日志归各个用户自己。
-## 一张图看懂架构
+| 术语 | 含义 | 详见 |
+| --- | --- | --- |
+| 上游 | 网关把请求转发过去的模型服务地址,连同它的 API Key;每个上游只使用三种 API 中的一种。 | [上游](../gateway/07-upstreams.md#upstreams) |
+| 上下文配置 | 一组有名字的记忆设置,例如召回预算、是否保存对话、是否开放 OpenViking 工具;每个网关密钥使用一份。 | [上下文配置](../gateway/08-context-profiles.md#context-profiles) |
+| 网关密钥 | 客户端用来代替服务商 API Key 的密钥(`ovgw_…`),绑定一位 OpenViking 用户、一份上下文配置和一组上游。 | [网关密钥](../gateway/09-gateway-keys.md#gateway-keys) |
+| OpenViking API 密钥 | 你在 OpenViking 的用户密钥:用它登录 Studio,它也决定以哪个账号、哪个用户的身份读写记忆。 | [密钥和凭证](22-gateway-operations.md#keys-and-credentials) |
+| 网关管理密钥 | 可选的密钥(`ovgm_…`);设置后,只有带上它的请求才能修改上游和上下文配置。谁能修改什么,见[权限矩阵](../api/25-gateway.md#credentials-and-account-scope)。 | [网关管理密钥](22-gateway-operations.md#gateway-management-key) |
+| 对话 | 网关认定属于同一次聊天的一组请求;一段对话沿用开始时的上下文配置和上游。它的轮次保存到一个 OpenViking 会话,某些情况下改存到新会话,例如客户端改写历史时(见[保存状态](../gateway/10-overview-and-requests.md#saving-status))。 | [网关如何识别对话](../gateway/03-connect-clients.md#how-conversations-are-recognized) |
+| 召回 | 从 OpenViking 搜出和当前消息相关的记忆,附加到这条消息上。 | [模型看到什么](../gateway/01-how-it-works.md#what-the-model-sees) |
+| 保存 | 把已完成的轮次写入 OpenViking 会话(晚一轮进行),供之后的提交从中提取新记忆。 | [对话什么时候保存](../gateway/01-how-it-works.md#when-conversations-are-saved) |
+| 提交 | 告诉 OpenViking 会话里已保存的轮次可以处理了:OpenViking 归档较早的轮次(会话中只留最新的消息),并在后台从中提取记忆。已保存的轮次要等提交之后才会变成记忆。 | [对话什么时候保存](../gateway/01-how-it-works.md#when-conversations-are-saved) |
+| 压缩 | 对话接近模型的上下文窗口时,让同一个模型写一份摘要,替换截断点之前的全部内容。 | [网关中的长对话](../gateway/05-long-conversations.md#long-conversations) |
+| 提示词缓存 | 服务商的计费机制:请求开头和上一次请求相同的部分按缓存价计费(通常只有原价的一小部分),从第一个不同的字节起按原价计费。 | [记忆原样放回与提示词缓存](../gateway/01-how-it-works.md#replay) |
+| 本地 dev 模式 | 以 dev 模式运行的 OpenViking 服务:绑定 `127.0.0.1`、未配置 `root_api_key`,打开 Studio 不需要 API 密钥,所有操作都以 `default` 用户身份进行。 | [本地服务](../gateway/02-quickstart.md#local-server-no-api-key) |
+| OpenViking 工具 | 你的 OpenViking 服务提供的工具(名为 `openviking_…`),由网关提供给模型,并在模型回答时由网关自己执行。 | [OpenViking 工具](../gateway/04-openviking-tools.md#agentic-memory-for-any-client) |
+
+## 一张图看懂架构 {#architecture-at-a-glance}
![OpenViking 网关的两种运行形态。嵌入:客户端访问 OpenViking Server 的端口,Server 把 /gateway 下的所有路径(模型 API、上传和网关管理)交给同一进程里的网关,网关通过本机回环 HTTP、用用户本人的 OpenViking 密钥检索和保存记忆。独立:openviking-gateway 用自己的端口提供同样的 /gateway 路径和只含网关页面的 Studio,通过 HTTP(S) 调用已有的 OpenViking 服务。两种形态下,网关都用同一种 API 把请求转发给上游模型服务商;会话和记忆的正本在 OpenViking,网关本机只有两个 SQLite 文件(开启 OpenViking 加密时加密存储)](../../images/gateway/architecture.zh.svg)
-- **运行在哪**:开启后嵌入 OpenViking Server,和 Server 共用端口;也可以用 `openviking-gateway` 独立运行,连接已有的 OpenViking 服务(开源版或商业版)。两种方式下网关的所有 URL 都在 `/gateway` 下(例如 `/gateway/v1`),客户端路径相同,见[部署方式](22-gateway-operations.md#部署方式)。
+- **运行在哪**:开启后嵌入 OpenViking Server,和 Server 共用端口;也可以用 `openviking-gateway` 独立运行,连接已有的 OpenViking 服务(开源版或商业版)。两种方式下网关的所有 URL 都在 `/gateway` 下(例如 `/gateway/v1`),客户端路径相同,见[选择部署方式](22-gateway-operations.md#deployment-options)。
- **和 OpenViking 的关系**:网关只调用 OpenViking 的公开接口,向量化和记忆提取都在 OpenViking 中完成。
-- **数据在哪**:会话和记忆的正本在 OpenViking。网关本机只有两个 SQLite 文件(开启 OpenViking 加密时加密存储),一个存上游、密钥和配置,一个存对话状态,见[安全与数据](22-gateway-operations.md#安全与数据)。
+- **数据在哪**:会话和记忆的正本在 OpenViking。网关本机只有两个 SQLite 文件(开启 OpenViking 加密时加密存储),一个存上游、密钥和配置,一个存对话状态,见[安全与数据](../gateway/11-security-and-data.md)。
- **出故障时**:OpenViking 不可用时,对话照常进行,只是不带记忆,保存会自动重试。网关停止服务时,经过它的模型调用全部失败。
-- **管理哪些对象**:同一账号的用户共用**上游**(模型服务地址和 API Key)和**上下文配置**(召回预算、是否保存对话、是否开放 OpenViking 工具等记忆设置)。每个网关密钥绑定一位 OpenViking 用户、一份上下文配置和一组上游。谁能修改什么,见[权限矩阵](../api/25-gateway.md#凭证和账号范围)。
-
-## 接入后,对话会发生什么
-
-先解释两个词。**召回**指从 OpenViking 搜出和当前消息相关的记忆,附加到消息上。**提示缓存**是服务商的计费机制:请求开头和上一次相同的部分按缓存价计费,从第一个不同的字节起按原价计费。缓存价通常只有原价的一小部分,具体比例见各服务商的定价。
-
-接入后你会得到:每条新消息补上相关记忆,新对话开头带上用户画像;对话保存回 OpenViking 并提取成新记忆;长对话自动压缩;开启 OpenViking 工具后,模型还能主动检索、读取和写入记忆(见[下一节](#让任意客户端拥有-agentic-记忆))。
-
-代价有三项:每条新消息的第一次模型调用最多多等 2 秒;补充的记忆按输入 token 计费,后续请求里大部分按缓存价计费;触发压缩的那一轮多一次模型调用。
-
-![一轮对话里发生了什么:网关识别对话和请求类型,把之前补充的记忆原样放回,只为新消息召回,再用同一种 API 转发给上游,并把这一轮放进待保存队列;下方说明原样放回如何让提示缓存持续命中,以及跨轮的保存和长对话压缩](../../images/gateway/one-turn.zh.svg)
-
-网关自动认出同一段对话(方法见[网关如何识别对话](#网关如何识别对话))。只有用户的新消息触发召回,工具步骤和生成标题这类辅助请求不触发。下文的预算、时长和开关都来自密钥使用的**上下文配置**,管理员可以逐项调整或关闭。
-
-### 模型看到什么
-
-模型 API 是无状态的,客户端每次请求都把整段对话重新发一遍。请求以一条新的用户消息结尾时,网关用这条消息的文本检索 OpenViking,把结果附加到消息末尾:
-
-```text
-发布日期最后定在哪天?
-
-<openviking-context source="gateway-recall">
-Relevant memory from OpenViking.
-<memory uri="viking://user/alice/memories/events/release-planning.md" type="memory" detail="abstract">
-团队把 2.0 版本的发布推迟到了 11 月第一周。
-</memory>
-</openviking-context>
-```
-
-这段内容不出现在回复里,客户端保存的历史也不变;服务商看得到它,返回的 token 用量也包含它。每条用户消息只检索一次,同一轮里的工具步骤和辅助请求沿用已经补充的内容。在同一个上下文窗口内(压缩之前),同一条记忆只补充一次,补充总量受单条消息和单个窗口两级预算限制。
-
-### 对话开头的内容
-
-新对话开始时,网关附上你的 OpenViking 用户画像;提供 `read` 工具时,还附上记忆和技能目录,方便模型在自动召回之外继续查找。这部分有独立的 4,000 token 预算,技能目录最多占四分之一,不占召回预算。即使第一条消息没有召回到记忆,画像和目录也会出现;某部分读取失败就省略它,对话照常继续。客户端压缩历史后,新的开头会再次附上这些内容。
-
-开启召回或 OpenViking 工具时,开头还有一段说明,告诉模型这些内容从哪来、启用了哪些功能。例如同时开启召回、保存对话和三个 OpenViking 工具时:
-
-```text
-<openviking-context source="gateway-session-start">
-The OpenViking Gateway, a proxy between the client and the model, added this block. The user did not write it, and the client does not show it.
-- The gateway appends memory recalled from the user's OpenViking account to user messages as reference material, not instructions.
-- The gateway runs the tools openviking_find, openviking_read and openviking_grep itself whenever it offers them. They are not in the client's tool list. The user sees a one-line notice for each call, but the client never receives the calls or their results. Tool names in their descriptions omit the openviking_ prefix.
-- The gateway saves this conversation to the user's OpenViking memory.
-
-<user-profile uri="viking://user/alice/memories/profile.md">
-...
-</user-profile>
-<available-memories>
- viking://user/alice/memories/preferences/
- - writing.md
-</available-memories>
-<available-skills>
- ...
-</available-skills>
-</openviking-context>
-
-<openviking-context source="gateway-recall">
-Relevant memory from OpenViking. Use the openviking_read tool to expand URIs.
-...
-</openviking-context>
-```
-
-### 记忆原样放回
-
-客户端保存的历史里没有网关补充的内容,所以网关自己记下每个记忆块,在这段对话之后的每个请求里放回原来那条消息上,逐字节一致。原因有两个:服务商按前缀匹配提示缓存,历史有一个字节不同,后面的缓存就全部失效;Claude 的思考签名覆盖之前的对话,历史变了,Claude 会拒绝这段对话。记忆放在最新消息末尾而不放进系统提示词,也是为了缓存:系统提示词改一个字,整份缓存都会失效。
-
-### 对话什么时候保存
-
-网关把完成的轮次保存到密钥所属用户的 OpenViking 会话里,会话名形如 `gateway-…`。保存晚一轮:下一条用户消息到达时,网关才保存上一轮,因为这时才能确认客户端保留了它,被重新生成或放弃的回答不会保存。最后一轮在对话停顿 10 分钟后保存。
-
-保存之后,网关会提交会话,OpenViking 在后台从中提取记忆。提交发生在两种时候:对话停顿 10 分钟,或者待提交内容累计到 20,000 token。保存前,网关会去掉自己添加的内容和 `<system-reminder>` 这类客户端噪声。子 Agent 请求、辅助请求和 token 计数请求从不保存。
-### 长对话
+## 能得到什么,代价是什么 {#what-you-get-and-what-it-costs}
-对话用到模型上下文窗口的 90% 时,网关压缩它:让同一个模型为目前为止的对话写一份有长度上限的摘要,此后用摘要代替压缩位置之前的全部内容,客户端界面里的历史不变。开启了保存对话、模型也能用 OpenViking 的 grep 和 read 工具时,摘要后面会说明如何在已保存的对话里查找细节。每次压缩多一次模型请求,服务商缓存也失效一次。
+接入后你会得到:
-网关需要知道模型的上下文窗口有多大。上游和上下文配置都没有设置时,网关按 1,000,000 token 计算,所以使用窗口更小的模型时,要请管理员填上实际窗口,否则长对话会在压缩前被服务商以过长为由拒绝。压缩的细节见[长对话](22-gateway-operations.md#长对话)。
+- 每条新消息都补上相关记忆;
+- 新对话开头带上你的用户画像;
+- 对话保存回 OpenViking,并提取成新记忆;
+- 长对话自动压缩;
+- 开启 OpenViking 工具后,模型还能主动检索、读取和写入记忆(见[让任意客户端拥有 Agentic 记忆](../gateway/04-openviking-tools.md#agentic-memory-for-any-client))。
-## 让任意客户端拥有 Agentic 记忆
+代价有三项:
-自动召回是网关替模型猜它需要什么;开启 OpenViking 工具后,由模型自己决定查什么、读什么、记什么。工具由网关执行,客户端的请求里一个工具都没有也能用。
+- 每条新消息的第一次模型调用最多多等 2 秒;
+- 补充的记忆按输入 token 计费,后续请求里大部分按缓存价计费;
+- 触发压缩的那一轮多一次模型调用。
-![开启 OpenViking 工具后的一条回复:网关在客户端的请求上附加召回的记忆和 OpenViking 工具定义,模型调用 OpenViking 工具时由网关用该用户的 OpenViking 密钥执行,再把结果接回请求继续询问模型,直到模型给出最终回答;客户端收到的是一条带提示行的连贯回复,工具往返在下一轮被原样放回](../../images/gateway/tool-loop.zh.svg)
+每一项在一轮对话里具体怎么发生,见[OpenViking 网关的工作原理](../gateway/01-how-it-works.md)。
-- **一条回复里完成多步操作**:网关拦下模型发出的 OpenViking 工具调用,用该用户的 OpenViking 密钥执行,把结果接回再问模型,直到模型不再调用。客户端只收到一条连贯的回复,流式和非流式都支持。
-- **客户端自己的工具照常可用**:同一条回复里,模型可以同时调用 OpenViking 工具和客户端工具(例如 Bash)。客户端工具的调用原样交给客户端执行,照常经过客户端的权限确认。
-- **下一轮还记得**:工具调用和结果不在客户端的历史里,网关把这些往返存下来,下一轮原样放回。模型记得自己查到过什么,提示缓存也不受影响。
+## 网关还是插件 {#gateway-or-plugin}
-### 不同客户端得到什么
+OpenViking 也能以插件形式接入 Agent,例如 Claude Code、Codex、Cursor、TRAE、OpenCode、pi、DSH、OpenClaw 和 Hermes(见 [Agent 集成概览](../agent-integrations/01-overview.md))。两者读写的是同一份 OpenViking 记忆,区别在于运行位置:网关位于模型调用的链路上,改的是模型收到的请求;插件运行在某个 Agent 内部,靠这个 Agent 的事件工作。没有哪一种总是更好,下面的差别大多由这一点决定,有些还因插件而异。
-| 客户端 | 不经过网关时 | 经过网关并开启 OpenViking 工具后 |
-| --- | --- | --- |
-| 聊天应用,例如 Cherry Studio、Open WebUI | 要用记忆得自己配 MCP 或写工具,普通对话只收发文本。 | 模型自己检索记忆、按 URI 读取原文。勾选 `remember` 后,能记下用户要求记住的事;勾选 `add_resource` 后,能把用户附带的文件导入 OpenViking。不带任何工具的纯聊天模式也能用。 |
-| SDK 脚本、低代码平台 | 一问一答,多步操作要自己写循环。 | 一次请求里完成“检索 → 读取 → grep 精确匹配 → 作答”,代码不用改。 |
-| Claude Code、Codex 等编程 Agent(未装 OpenViking 插件或 MCP) | 有自己的工具,但没有 OpenViking。 | OpenViking 工具和 Bash 等客户端工具在同一条回复里混用。需要逐次确认工具调用时,仍建议用插件或 MCP。 |
-
-### 模型能用哪些工具
-
-工具清单直接来自你的 OpenViking 服务提供的 MCP 工具,名称加上 `openviking_` 前缀;OpenViking 新增的工具也会自动可用。常用的几类:
-
-| 用途 | 工具 | 模型拿来做什么 |
-| --- | --- | --- |
-| 检索 | `find`、`search`、`grep`、`glob` | 语义检索记忆和资料;按正则或文件名精确查找。 |
-| 浏览和读取 | `list`、`tree`、`read` | 按 URI 展开召回条目的原文,浏览记忆和技能目录。 |
-| 写入 | `remember`、`write`、`edit` | 存一条长期记忆,写入或局部修改记忆文件。 |
-| 导入 | `add_resource`、`add_skill` | 按 URL 导入网页或代码仓库,导入对话附件,用一段文本新建技能,都不需要客户端有 shell。 |
-| 删除和权限 | `forget`、`set_acl` 等 | 永久删除记忆,修改共享资源的访问权限。 |
-
-### 默认设置
-
-新建的上下文配置默认开启 OpenViking 工具,但只勾选检索、浏览和读取这类只读工具。会修改数据的工具(如 `remember`、`add_resource`、`forget`)要管理员主动勾选。轮数、总时长和 token 预算默认都不限,模型会一直使用工具直到完成。
-
-客户端必须每轮回传完整历史;使用 Responses 时还要设置 `store: false`。客户端强制指定工具、要求结构化输出,或者自己已经接了 OpenViking 工具时,网关不再提供自己的工具。完整的默认工具列表、上限、文件导入方式和不提供工具的原因,见[OpenViking 工具](22-gateway-operations.md#openviking-工具)。
-
-### 用户看到什么
-
-模型的文字实时流出。每次 OpenViking 工具调用在回复里留一行提示,调用开始时出现,结束后补上 `done`、`failed` 或 `skipped`:
-
-```text
-> OpenViking find: "上次定的发布日期" — done
-> OpenViking read: viking://user/alice/memories/release.md — done
-```
-
-提示行只显示工具名和调用对象(查询词、URI 等),用户看不到完整参数和结果。模型看不到提示行,网关也不把它保存到 OpenViking;管理员可以在上下文配置里关掉它。客户端收到的 token 用量是这条回复中所有模型调用之和。
-
-### 风险和控制点
-
-> **注意**:勾选的工具直接执行,不经过客户端的权限确认,写入和删除数据的工具也一样。提示行是事后告知,不是确认。模型能做的事以该用户自己的 OpenViking 权限为上限。
-
-- **管理员的控制点**:上下文配置里的总开关和逐个工具勾选、每个上游的**允许 OpenViking 工具**开关,以及工具轮数、总时长和 token 上限。给聊天应用用的配置,建议至少不勾选 `forget` 和 `set_acl`。
-- **和插件或 MCP 怎么选**:插件和 MCP 在客户端里显示每次调用和结果,调用前还会请求确认,所以 Claude Code、Codex 用它们更透明。网关工具主要服务接不了插件或 MCP 的客户端。
-
-**实验性功能**:上下文配置还可以让模型自己管理上下文窗口:模型多两个工具,一个查看窗口用了多少,一个写好交接笔记后开启新窗口;窗口快满时网关会提醒它。这项功能默认关闭,见[实验性:Agent 自管上下文窗口](22-gateway-operations.md#实验性-agent-自管上下文窗口)。
-
-## 网关还是插件
-
-OpenViking 也能以插件形式接入 Claude Code、Codex、OpenCode、pi、OpenClaw、Hermes 等 Agent(见 [Agent 集成概览](../agent-integrations/01-overview.md))。两种方式互相补充,差别都来自运行位置:
+### 逐项对比 {#gateway-and-plugin-compared}
| | OpenViking 网关 | Agent 插件 |
| --- | --- | --- |
-| 运行位置 | 在客户端和模型服务商之间,只看得到发给模型的请求。 | 在 Agent 内部,看得到 Agent 的会话、事件和本地工作区。 |
-| 适用的客户端 | 能设置 Base URL 和 API Key 的客户端:聊天应用、SDK 和 API 应用、低代码平台、编程 Agent。 | 有 OpenViking 插件的 Agent。 |
-| 覆盖不到的客户端 | 用订阅账号直接登录的客户端(Claude Code 的 Claude 登录、Codex 的 ChatGPT 登录;可以改用[订阅反代上游](#自定义上游)),以及从厂商服务器发起模型调用的客户端,例如 Cursor 和 Trae。 | 没有扩展接口的客户端。 |
-| 按项目区分记忆 | 看不到工作目录和代码仓库。记忆按 OpenViking 用户归属,要按项目隔离,就给每个项目一个绑定不同 OpenViking 用户的网关密钥。 | 自动识别工作区和代码仓库。 |
-| 可见性 | 补充的记忆在客户端里不可见。OpenViking 工具调用默认在回复里显示一行提示,不显示结果。Studio 的请求日志记录召回条数和工具轮数,不记录内容。工具调用不经过客户端的权限确认。 | 工具调用出现在对话记录里,经过 Agent 的权限确认。 |
-| 保存时机 | 晚一轮:下一条消息到达时保存上一轮,最后一轮在对话停顿后保存。 | 跟随 Agent 自己的事件,例如每轮结束时。 |
-| 安装与升级 | 所有人共用一个服务,不用在每台机器上安装;上游、密钥和记忆设置集中管理。 | 每台机器分别安装和升级。 |
-| 密钥、数据和故障 | 集中保管服务商的 API Key 和尚未保存的对话文本(开启 OpenViking 加密时加密存储),每次模型调用多一跳。网关停止服务时,经过它的模型调用全部失败。 | 服务商的 API Key 留在各自的 Agent 里,只有保存的对话进入 OpenViking,不需要额外维护服务。 |
-
-Claude Code、Codex 和 pi 需要按项目区分记忆,或者要求每次工具调用都能看到并确认时,继续用插件。没有插件的客户端,以及想集中管理服务商、密钥和记忆设置的场景,用网关。
-
-**两者同时使用时,网关让路。** 请求中出现 OpenViking 插件的迹象时,网关不再为这段对话补充记忆、保存对话或提供 OpenViking 工具,只做转发,避免同一份内容被补充两次、保存两次。判断依据有两类:
-
-- 插件插入的记忆块:`<openviking-context>`、`<relevant-memories>`、`<relevant-memory>` 或 `<memory-context>`;
-- `X-OpenViking-Plugin` 请求头。插件和应用的作者可以发送它,明确告诉网关不要补充记忆。
-
-这个判断对整段对话有效,其他对话不受影响;想重新用上网关记忆,需要不带插件开始新对话。Studio 的请求日志会把这些请求标为**检测到 OpenViking 插件**。
-
-只接了 OpenViking MCP 工具、没装插件的客户端不算:网关照常补充记忆和保存对话,只是不再提供自己的 OpenViking 工具,免得模型看到两套同名工具(请求日志中显示为 `tool_name_collision`)。
-
-## 快速开始
+| 运行位置 | 客户端和模型服务商之间的一个共享服务,只看得到模型请求。 | 通过 hook 或扩展接口运行在每个 Agent 内部,看得到 Agent 的会话、事件和工作区。 |
+| 适用客户端 | 能设置 Base URL 和 API Key、使用 Anthropic Messages、Chat Completions 或 Responses 的客户端:聊天应用、SDK 脚本、低代码平台和编程 Agent。Cursor 和 TRAE 不行,它们的模型调用从厂商服务器发出。 | 只有带 OpenViking 插件的 Agent。其他 MCP 客户端可以接入 OpenViking 工具,但没有自动召回和保存。 |
+| 模型登录方式 | 需要服务商的 API Key,由网关保管,或[由客户端各自发送](../gateway/03-connect-clients.md#bring-your-own-provider-key)。客户端不能用订阅账号登录,可以改用[订阅反代上游](../gateway/07-upstreams.md#custom-upstreams)。Codex 可以通过 [CLIProxyAPI](../gateway/03-connect-clients.md#codex-chatgpt-subscription) 使用 ChatGPT 订阅;其他订阅服务请自行确认其使用条款。 | 不经手模型调用,Agent 原来怎么登录就怎么登录,订阅也可以。 |
+| 召回 | 每条新的用户消息召回一次,结果附加在这条消息末尾;检索默认最多等 2 秒。默认检索记忆、资源和技能。 | 在 Agent 的提问事件里进行。多数插件会带上会话 ID,让服务端结合对话扩展查询;自动召回不含资源。 |
+| 保存 | 晚一轮保存已完成的轮次,连同客户端自己的工具调用和结果。子 Agent 请求和杂项请求不保存。 | 跟随 Agent 的事件,通常在每轮结束时。子 Agent 各不相同:Claude Code、OpenCode 和 DSH 存成单独的会话,Codex 并入主会话,Hermes 不保存。 |
+| OpenViking 工具 | 由网关在回复过程中执行,不支持工具或 MCP 的客户端也能用。默认只开放只读工具。调用[不经过客户端的权限确认](../gateway/04-openviking-tools.md#risks-and-controls),每次调用显示一行提示。 | 由 Agent 当作自己的工具执行,调用和结果出现在对话记录里,遵循 Agent 的工具权限设置。 |
+| 提示词缓存 | 在后续请求里把每个记忆块逐字节原样放回,缓存前缀保持不变。**概览**页显示缓存命中率。 | 因插件而异。基于 hook 的插件把记忆块交给 Agent,由 Agent 保存在自己的历史里;pi 和 OpenCode v2 也会让之前的召回保持不变;OpenClaw 每轮在系统提示词里重建召回内容。 |
+| 长对话 | 接近模型上下文窗口时由网关压缩,任何客户端都适用,包括从不压缩的应用。[实验性的 Agent 自管上下文窗口](../gateway/05-long-conversations.md#experimental-agent-managed-context-windows)让模型自己决定何时开启新窗口。 | 由 Agent 自己压缩,多数插件会先提交已捕获的内容。pi 和 OpenClaw 可以用 OpenViking 的摘要替换 Agent 的摘要。 |
+| 按项目区分记忆 | 看不到工作目录。要按项目隔离,就给每个项目一个绑定不同 OpenViking 用户的网关密钥。 | 基于共享插件代码的插件会自动给记忆标上当前代码仓库。 |
+| 可见性 | 补充的记忆在客户端里看不到,除非上下文配置开启了[召回摘要](../gateway/08-context-profiles.md#recall-summary)。Studio 的请求日志记录条数和保存状态,不记录内容。 | Claude Code 的状态栏和 `/openviking-memory:ov` 命令显示召回条数和补充内容的来源;pi 的状态栏显示连接状态。其他插件没有自己的状态显示。 |
+| 部署与运维 | 一个服务,嵌入 OpenViking Server 或独立运行。用户只改 Base URL 和密钥;上游、上下文配置和密钥都在 Studio 里管理。 | 每台机器分别安装和升级,各自配置 OpenViking 凭证。 |
+| 团队使用 | 管理员给每人签发一个网关密钥,可以单独吊销。网关保管服务商 API Key 时,用户看不到它。 | 每人用自己的 OpenViking API 密钥安装插件。行为设置可以写进代码仓库的 `.openviking/config.json`,按仓库共享。 |
+| 出故障时 | OpenViking 不可用时,请求照常发出,只是不带记忆,保存会自动重试。网关本身停止服务时(嵌入形态即 OpenViking Server 停止时),经过它的模型调用全部失败。服务商 API Key 和尚未保存的对话文本集中存放在网关,每次模型调用也多经过一跳。 | OpenViking 不可用时,Agent 等到插件的召回超时(多数为 15 秒,Hermes 为 4 秒)后不带记忆继续;多数插件会把写入失败的内容排队存到磁盘。模型调用从不依赖 OpenViking。 |
-先准备好一套能正常工作的 OpenViking,`ov.conf` 中已经配好 embedding 和 VLM 模型(见[快速开始](../getting-started/02-quickstart.md))。网关包含在核心包中,不需要另外安装。下面按服务端的情况选一条路径。已有 OpenViking 服务、不想改它的配置时,可以独立运行网关,见[独立部署](22-gateway-operations.md#独立部署)。
+各插件的细节见 [Agent 集成能力](../agent-integrations/16-capability-reference.md),网关的细节见 [OpenViking 网关的工作原理](../gateway/01-how-it-works.md)。
-### 本地服务(不需要 API 密钥)
+### 怎么选 {#which-to-choose}
-适用于绑定在 `127.0.0.1`、使用默认本地认证的服务。
+以下情况选网关:
-1. **开启网关。** 运行 `openviking-server init`,在 **Enable OpenViking Gateway on the same port?** 处回答 yes;已有配置时,在菜单中选择 **Update gateway**。也可以直接把 `{"gateway": {"enabled": true}}` 合并进 `ov.conf`。
-2. **启动或重启** `openviking-server`。
-3. **在 Studio 中打开网关。** 打开 <http://127.0.0.1:1933/studio/>,在侧边栏选择 **OpenViking 网关**,不用填写密钥。默认账号还没有上游时,网关启动时会把服务端的 VLM 配置导入为上游,并创建一份上下文配置,所以“概览”标签页的**快速开始**清单前两步已经完成。导入的 Coding Plan 上游需要你确认后才能使用,见[导入 OpenViking 模型配置](22-gateway-operations.md#导入-openviking-模型配置);没有可导入的配置时,按[上游](22-gateway-operations.md#上游)手动添加。
-4. **签发网关密钥。** 在“概览”标签页的**快速模式**卡片中点**一键生成密钥**;也可以手动签发:在“密钥”标签页点**签发密钥**,填写名称,选择上下文配置和上游,然后签发。这个密钥以本地 `default` 用户的身份读写记忆。**复制网关密钥**对话框只显示一次完整的 `ovgw_…` 密钥,关闭前先复制。
+- 客户端没有 OpenViking 插件:聊天应用、SDK 脚本、低代码平台,或者你自己写的、调用模型 API 的应用;
+- 多人或多个客户端要共用一套配置:服务商、记忆设置和每人的密钥都在 Studio 里管理,用户的机器上什么都不用装;
+- 客户端自己没有记忆工具或压缩功能,网关可以把两者都补上;
+- 你的客户端本来就用服务商 API Key,或者模型流量本来就经过一个集中代理。
-然后向 `http://127.0.0.1:1933/gateway` [发送测试请求](#发送测试请求)。
+以下情况选插件:
-### 远程服务(使用 API 密钥)
+- 你用 Claude 订阅账号登录 Claude Code;
+- 你用 Cursor 或 TRAE,只有插件能接入;
+- 你希望记忆不用配置就按代码仓库标记,或者希望每次 OpenViking 工具调用都在 Agent 里展示并经过确认;
+- 你希望保存跟随 Agent 的事件,例如子 Agent 的会话、Agent 压缩前的保存、退出时的提交;
+- 你不想在模型调用链路上多加一个服务。
-适用于通过网络访问、使用 `api_key` 认证的服务。
+用 ChatGPT 订阅的 Codex 两种方式都行:装它的插件,或者经网关接 [CLIProxyAPI 上游](../gateway/03-connect-clients.md#codex-chatgpt-subscription)。
-1. **开启网关。** 在服务端主机上运行 `openviking-server init`,绑定选择 **Remote (0.0.0.0)**,在 **Enable OpenViking Gateway on the same port?** 处回答 yes。接下来的 **Allow users to configure their own gateway upstreams?** 决定谁能修改上游和上下文配置:
- - 回答 yes:每个登录的用户都能配置本账号的上游和上下文配置。
- - 回答 no:init 生成一个以 `ovgm_` 开头的网关管理密钥,打印出来并写入 `ov.conf` 的 `gateway.management_key`。只有输入这个密钥才能修改上游和上下文配置,见[网关管理密钥](22-gateway-operations.md#网关管理密钥)。
+两者也可以混用:编程 Agent 用各自的插件,其他客户端都走网关。同一个客户端两者都装时,见下一节。
- 然后重启服务。也可以用 root 密钥登录 Studio,在 OpenViking 网关页面点**开启网关**:Studio 会写入 `ov.conf` 并重启服务(仅限只有一个 worker 的服务端)。
-2. **准备 OpenViking API 密钥。** 用你自己的用户 API 密钥,或者按[认证](04-authentication.md)用 root 密钥创建账号和用户。
-3. **登录 Studio。** 打开 `https://ov.example.com/studio/`,在**连接设置**中填入 API 密钥,然后在侧边栏选择 **OpenViking 网关**。
-4. **添加上游。** 在“上游”标签页点**添加上游**,选择服务商和客户端使用的协议(下面的测试请求用 Chat Completions),粘贴服务商的 API Key 后保存。在上游列表里点**测试**,确认网关能连上服务商。如果标签页是只读的,说明部署者设置了网关管理密钥,见[在 Studio 中管理网关](22-gateway-operations.md#在-studio-中管理网关)。
-5. **创建上下文配置。** 在“上下文配置”标签页点**使用推荐设置创建**。
-6. **签发网关密钥**,做法同本地路径第 4 步,签发给你自己。要给其他用户签发,见[网关密钥](22-gateway-operations.md#网关密钥)。
+> **抢先试用新功能**:网关掌控整个模型请求,因此能做到插件通过 Agent 扩展接口做不到的功能。[Agent 自管上下文窗口](../gateway/05-long-conversations.md#experimental-agent-managed-context-windows)是第一个,由模型自己决定何时开启新的上下文窗口;之后还会有更多这类功能加入网关。想抢先试用,就把客户端接入网关。
-### 发送测试请求
+### 两者同时使用时 {#when-both-are-in-use}
-本地服务把地址换成 `http://127.0.0.1:1933/gateway`,并把 `<model>` 换成上游提供的模型:
+请求中出现 OpenViking 插件的迹象时,网关会让路:不再为这段[对话](#key-terms)补充记忆、保存对话或提供 OpenViking 工具,只做转发,避免同一份内容被补充两次、保存两次。判断依据有两类:
-```bash
-export GATEWAY_URL=https://ov.example.com/gateway
-export GATEWAY_KEY='ovgw_...'
-
-curl -s "$GATEWAY_URL/v1/models" -H "Authorization: Bearer $GATEWAY_KEY"
-
-curl -s "$GATEWAY_URL/v1/chat/completions" \
- -H "Authorization: Bearer $GATEWAY_KEY" \
- -H "Content-Type: application/json" \
- -H "X-OpenViking-Session: quickstart-1" \
- -d '{"model": "<model>", "messages": [{"role": "user", "content": "记住:我喜欢简短的回答。"}]}'
-```
-
-第一条命令列出上游配置的模型和别名;上游接受任意模型名时,列表为空。第二条命令应该返回服务商的一次正常回复。
-
-### 确认记忆生效
-
-1. **请求经过了网关。** 打开“请求日志”标签页,刚才的请求显示为**新消息**,状态 200。OpenViking 里有相关内容时,**记忆**列显示补充的条数(例如 `+3`);全新账号下这一列为空。
-2. **对话已保存。** 用同一个 `X-OpenViking-Session` 值再发一条消息,第一轮随即保存。以密钥所属用户的身份连接 Studio,**会话**页面会出现一个 `gateway-…` 会话。
-3. **记忆已提取。** 对话停顿 10 分钟后,网关提交会话,OpenViking 在后台提取记忆,需要稍等片刻。然后换一个会话值开始新对话,问一个依赖这条记忆的问题,例如“你的回答应该多长?”。**记忆**列应显示召回的条数,回复也应该用上了这条记忆。
-
-试用时想更快看到效果,可以另建一份上下文配置,把**最新回复等待时长**调短,用它签发一个密钥,再用这个密钥开始新对话。上下文配置的修改只对之后开始的对话生效。
-
-## 接入客户端
-
-每个客户端需要两样东西:网关地址和网关密钥。网关地址是服务地址加上 `/gateway`。下面的示例用 `https://ov.example.com/gateway`,请换成你的网关地址;Studio 的 OpenViking 网关页面顶部和“接入”标签页都会显示它。Anthropic 客户端直接使用网关地址,OpenAI 兼容客户端在后面加 `/v1`,方舟 SDK 加 `/api/v3`。客户端用的密钥还必须绑定一个已启用的上游,这个上游要支持客户端的协议,并提供客户端请求的模型。
-
-| 客户端 | 上游协议 | Base URL | 对话识别方式 |
-| --- | --- | --- | --- |
-| [Claude Code](#claude-code) | Anthropic Messages | `https://ov.example.com/gateway` | Claude Code 的会话请求头 |
-| [Codex CLI](#codex-cli) | Responses | `https://ov.example.com/gateway/v1` | Codex 的会话请求头 |
-| [聊天客户端和 SDK](#聊天客户端和-sdk) | Chat Completions(或 SDK 使用的 API) | `https://ov.example.com/gateway/v1` | `X-OpenViking-Session`,需要自己发送 |
-| [Open WebUI](#open-webui) | Chat Completions | `https://ov.example.com/gateway/v1` | 在连接上配置 `X-OpenViking-Session` 请求头 |
-| [OpenCode](#opencode) | Chat Completions | `https://ov.example.com/gateway/v1` | OpenCode 的会话请求头 |
-| [pi](#pi) | Chat Completions | `https://ov.example.com/gateway/v1` | 通常根据对话历史匹配 |
-| [火山方舟与 BytePlus 方舟 SDK](#火山方舟与-byteplus-方舟-sdk) | 三种均可 | `https://ov.example.com/gateway/api/v3` 或 `https://ov.example.com/gateway/api/compatible` | 取决于客户端发送的请求头 |
-
-Open WebUI、OpenCode 和 pi 的配置依据它们各自文档中的服务商设置编写,请当作起点,配好后验证一下:在同一段对话里发两条消息,然后在“请求日志”中展开这两个请求,它们应该属于同一段对话,并且第二条消息到达后,第一轮已经保存。
-
-### Claude Code
-
-Claude Code 使用 Anthropic Messages。启动前设置三个环境变量:
-
-```bash
-export ANTHROPIC_BASE_URL=https://ov.example.com/gateway
-export ANTHROPIC_AUTH_TOKEN='<gateway-key>'
-export CLAUDE_CODE_GATEWAY_HINT_HEADERS=1
-```
-
-- 地址不要带 `/v1`,Claude Code 会自己补全路径。
-- `CLAUDE_CODE_GATEWAY_HINT_HEADERS=1` 让 Claude Code 给子 Agent、上下文压缩和后台请求加上标记,网关就不会为它们召回记忆,也不会把它们当作对话轮次保存。
-- Claude Code 发送自己的会话 ID,网关据此识别对话,`--resume` 之后也一样。
-- 上游必须接受 Claude Code 请求的模型名:模型列表留空、列出这些名称,或者用模型别名映射到服务商的模型。
-- Claude 订阅登录不能通过网关使用,带订阅令牌的请求会被拒绝。请为上游配置服务商的 API Key。
-- 同时装了 OpenViking 插件时,网关会让出这些对话(见[网关还是插件](#网关还是插件))。只接了 OpenViking MCP 服务器时,网关照常补充记忆,OpenViking 工具交给 MCP 服务器。
-
-### Codex CLI
-
-Codex 使用 Responses API,每个请求都带完整历史,正好满足网关的要求。在 `~/.codex/config.toml` 中添加一个服务商,两个顶层设置必须写在所有 `[section]` 之前:
-
-```toml
-model_provider = "openviking"
-model = "<model>"
-
-[model_providers.openviking]
-name = "OpenViking Gateway"
-base_url = "https://ov.example.com/gateway/v1"
-wire_api = "responses"
-env_key = "OPENVIKING_GATEWAY_KEY"
-```
-
-然后在运行 Codex 的环境里设置网关密钥:
-
-```bash
-export OPENVIKING_GATEWAY_KEY='<gateway-key>'
-```
-
-- 密钥绑定的上游必须使用 Responses,并提供 `<model>`。
-- Codex 会先尝试 WebSocket 连接,被网关拒绝后自动改用 HTTP。
-- Codex 发送自己的会话 ID,网关据此识别对话,`codex resume` 之后也一样。
-- 遇到不认识的模型名,Codex 可能提示缺少模型元数据,不影响请求。
-- ChatGPT 登录不能通过网关使用,请为上游配置服务商的 API Key。
-
-### 聊天客户端和 SDK
-
-支持 OpenAI Chat Completions API 的客户端和 SDK 都能接入。在客户端填写 OpenAI 兼容服务商的地方填入:
-
-```text
-Base URL: https://ov.example.com/gateway/v1
-API key: <gateway-key>
-Model: <model>
-X-OpenViking-Session: <conversation-id>
-```
-
-`X-OpenViking-Session` 请求头可选,但建议发送,它告诉网关请求属于哪段对话。取值在同一段对话内保持不变、不同对话之间互不相同,例如应用里的聊天 ID。不发送时,网关根据历史匹配对话,见[网关如何识别对话](#网关如何识别对话)。
-
-用 OpenAI Python SDK:
-
-```python
-from openai import OpenAI
-
-client = OpenAI(base_url="https://ov.example.com/gateway/v1", api_key="<gateway-key>")
-
-reply = client.chat.completions.create(
- model="<model>",
- messages=[{"role": "user", "content": "发布日期最后定在哪天?"}],
- extra_headers={"X-OpenViking-Session": "chat-42"},
-)
-print(reply.choices[0].message.content)
-```
-
-另外两种 API 的 SDK 用法相同,上游使用的 API 要和 SDK 一致:
-
-- Anthropic SDK 指向 `https://ov.example.com/gateway`。
-- Responses API 使用 `https://ov.example.com/gateway/v1`,每个请求都要带完整历史并设置 `store: false`;其他 Responses 请求直接转发,不补充记忆。
-
-流式调用 Chat Completions 时,请同时请求返回用量(`"stream_options": {"include_usage": true}`)。否则服务商不报告流式回复的 token 数,Studio 显示不了用量,网关也只能估算上下文窗口用了多少。
-
-### Open WebUI
-
-在 Open WebUI 中添加一个 OpenAI 兼容连接(Admin Panel → Settings → Connections),Base URL 填 `https://ov.example.com/gateway/v1`,密钥填网关密钥。再给这个连接加上下面的自定义请求头,让每个聊天成为一段独立的对话,并让网关认出 Open WebUI 的后台任务:
-
-```json
-{
- "X-OpenViking-Session": "{{CHAT_ID}}",
- "X-OpenViking-Task": "{{TASK}}"
-}
-```
-
-同时在 Open WebUI 的环境变量中设置 `RAG_SYSTEM_CONTEXT=true`。这样 Open WebUI 把附件检索结果放进 system 消息,而不是临时改写你这一轮的消息,请求之间的对话历史才能保持稳定。
-
-- **一个连接密钥只对应一位记忆归属者。** 通过这个连接聊天的所有 Open WebUI 用户,读写的都是密钥背后那位 OpenViking 用户的记忆。要么只让一个人用这个连接,要么接受这些用户共享记忆。
-- Open WebUI 还会通过同一个连接发送后台请求(生成标题、标签和追问建议)。网关能识别标题和摘要请求;如果请求日志里有其他后台任务被标成**新消息**,就把 Open WebUI 的任务模型改成一个不经过网关的连接。
-
-### OpenCode
-
-在 `~/.config/opencode/opencode.json` 中添加一个服务商,与已有设置合并:
-
-```json
-{
- "provider": {
- "openviking": {
- "npm": "@ai-sdk/openai-compatible",
- "name": "OpenViking",
- "options": {
- "baseURL": "https://ov.example.com/gateway/v1",
- "apiKey": "{env:OPENVIKING_GATEWAY_KEY}"
- },
- "models": {
- "<model>": {}
- }
- }
- }
-}
-```
+- 插件插入的记忆块:`<openviking-context>`(基于共享插件代码的插件,例如 Claude Code、Codex、OpenCode、pi 和 DSH)、`<relevant-memories>`(OpenClaw)、`<memory-context>`(Hermes)或 `<relevant-memory>`;
+- `X-OpenViking-Plugin` 请求头。插件和应用的作者可以发送它,明确告诉网关不要补充记忆。
-把网关密钥导出为 `OPENVIKING_GATEWAY_KEY`,然后在 OpenCode 中选择 `openviking/<model>`。上游必须使用 Chat Completions。同时装了 OpenViking 的 OpenCode 插件时,网关会让出这些对话。
+这个判断对整段对话有效,其他对话不受影响;想重新用上网关记忆,需要不带插件开始新对话。Studio 的请求日志会把这些请求标为**检测到 OpenViking 插件**。实际效果是记忆由插件负责,网关只做转发;客户端仍然需要网关密钥,以及配有服务商 API Key 的上游。
-### pi
+只接了 OpenViking MCP 工具、没装插件的客户端不算:网关照常补充记忆和保存对话,只是不再提供自己的 OpenViking 工具,免得模型看到两套同名工具。这时在**请求日志**标签页的请求详情里,**OpenViking 工具**一项显示**未提供:客户端已接入 OpenViking 工具**,见[什么时候不提供工具](../gateway/04-openviking-tools.md#when-tools-are-not-offered)。
-在 pi 的模型配置 `~/.pi/agent/models.json` 中添加一个服务商:
-
-```json
-{
- "providers": {
- "openviking": {
- "baseUrl": "https://ov.example.com/gateway/v1",
- "apiKey": "$OPENVIKING_GATEWAY_KEY",
- "api": "openai-completions",
- "models": [
- {
- "id": "<model>"
- }
- ]
- }
- }
-}
-```
+## 下一步去哪 {#next-steps}
-- `apiKey` 从环境变量 `OPENVIKING_GATEWAY_KEY` 读取网关密钥,启动 pi 前先导出它。开头的 `$` 不能省,否则 pi 会把这个字符串本身当作密钥发送。
-- 上游必须使用 Chat Completions。
-- pi 通常不发送会话请求头,网关根据历史匹配它的对话(见[网关如何识别对话](#网关如何识别对话))。
-- pi 自己的 OpenViking 扩展启用时,网关会让出这些对话,两者选一个即可。
+### 按任务查找 {#by-task}
-### 火山方舟与 BytePlus 方舟 SDK
-
-已经接入火山方舟或其海外站 BytePlus 方舟的客户端和 SDK,只需替换地址。在 `/gateway` 下,网关既接受方舟自己的路径(`/api/v3/chat/completions`、`/api/v3/responses`、`/api/v3/models` 和 `/api/compatible/v1/messages`),也接受标准的 `/v1` 路径:
-
-| 原地址 | 网关地址 |
+| 我想… | 去看 |
| --- | --- |
-| `https://ark.cn-beijing.volces.com/api/v3` | `https://ov.example.com/gateway/api/v3` |
-| `https://ark.ap-southeast.bytepluses.com/api/v3` | `https://ov.example.com/gateway/api/v3` |
-| `https://ark.cn-beijing.volces.com/api/compatible`(Anthropic 兼容) | `https://ov.example.com/gateway/api/compatible` |
-
-用网关密钥代替方舟的 API Key。以火山方舟 Python SDK 为例:
-
-```python
-from volcenginesdkarkruntime import Ark
-
-client = Ark(base_url="https://ov.example.com/gateway/api/v3", api_key="<gateway-key>")
-```
+| 弄清一轮对话里发生什么、模型看到什么、为什么这样设计 | [OpenViking 网关的工作原理](../gateway/01-how-it-works.md) |
+| 从拿到网关密钥到确认记忆生效,完整走一遍 | [快速上手](../gateway/02-quickstart.md) |
+| 接入 Claude Code、Codex、聊天应用或 SDK | [把客户端接入 OpenViking 网关](../gateway/03-connect-clients.md) |
+| 让模型使用记忆工具,或处理长对话 | [OpenViking 工具](../gateway/04-openviking-tools.md)和[网关中的长对话](../gateway/05-long-conversations.md) |
+| 部署、对外暴露、升级和监控网关 | [部署与运维](22-gateway-operations.md) |
+| 审查存了哪些数据、谁能看到、怎么删除 | [安全与数据](../gateway/11-security-and-data.md) |
+| 排查报错、警告或记忆没有生效 | [排障](../gateway/12-troubleshooting.md) |
+| 查某项设置的名称、默认值或取值范围 | [配置参考](../gateway/13-configuration.md) |
+| 通过 HTTP 管理网关 | [管理 API](../api/25-gateway.md) |
-客户端用哪个路径,只决定它使用哪种 API。请求仍然发往密钥绑定的、使用这种 API 并提供该模型的上游,通常是服务商选为“火山方舟”或“BytePlus 方舟(海外站)”的上游(见[上游](22-gateway-operations.md#上游))。
+### 按 Studio 标签页查找 {#by-studio-tab}
-## 网关如何识别对话
+在 Studio 侧边栏打开 **OpenViking 网关**,每个标签页都有对应的文档:
-网关需要知道请求属于哪段对话:一段对话固定使用同一份上下文配置和同一个上游,并保存到同一个 OpenViking 会话。网关按以下顺序取第一个出现的请求头:
-
-1. `X-OpenViking-Session`
-2. `thread-id`
-3. `x-claude-code-session-id`(Claude Code)
-4. `x-opencode-session-id`(OpenCode)
-5. `x-session-id`
-6. `session-id`(Codex CLI)
-
-这些请求头都没有时,网关查看历史中最近一条助手回复:如果之前某段对话产生过这条回复,请求就并入那段对话,否则开始一段新对话。开场消息相同的两段对话不会因此被合并。普通的一问一答这样就能识别,但重试、重新生成和内容完全相同的对话存在歧义,可能被当成新对话。所以只要客户端允许设置请求头,就发送 `X-OpenViking-Session`。
-
-对话归属于密钥背后的 OpenViking 用户,并按 API 区分。同一用户的两个网关密钥发送相同的会话值,会共享同一段对话;同一个会话值用在另一种 API 上,则是另一段对话。网关转发前会去掉所有 `X-OpenViking-*` 请求头,服务商看不到它们。
-
-请求没有归入已有对话时,记忆照样工作:新消息照常召回,之前补充的记忆也照常原样放回,因为网关是根据消息本身找到这些记忆的。区别在于这个请求会开始一段新对话:它的轮次保存到新的 OpenViking 会话,记忆预算从头计算,并使用密钥当前的上下文配置。
-
-## 使用须知
+| 标签页 | 用途 | 文档 |
+| --- | --- | --- |
+| **概览** | 一眼看清请求量、提示词缓存、记忆召回和 OpenViking 的运行状态 | [概览](../gateway/10-overview-and-requests.md#overview) |
+| **上游** | 网关转发请求的模型服务地址 | [上游](../gateway/07-upstreams.md) |
+| **上下文配置** | 对话如何使用记忆和工具 | [上下文配置](../gateway/08-context-profiles.md) |
+| **密钥** | 签发和吊销网关密钥 | [网关密钥](../gateway/09-gateway-keys.md) |
+| **请求日志** | 每次模型请求,以及其中记忆的处理情况 | [请求日志](../gateway/10-overview-and-requests.md#requests) |
+| **接入** | 网关地址和每种客户端的具体设置 | [把客户端接入 OpenViking 网关](../gateway/03-connect-clients.md) |
-- **召回最多等 2 秒。** 每条新消息的第一次模型调用要等 OpenViking 检索完成,最多等上下文配置里的**超时时间**(默认 2 秒)。OpenViking 超时或不可用时,这条消息不带记忆直接发给模型,之后也不会补上。
-- **设置只对新对话生效。** 一段对话始终使用它开始时的上下文配置和上游。Claude Code、Codex 这类长期运行的客户端会把一段对话延续很多天,修改上下文配置后要等它们开始新对话才生效。对话闲置 30 天后,网关删除它的状态。
-- **改动过的历史会重新保存。** 客户端编辑或删除了之前的消息、在回答保存后重新生成,或者自己压缩了对话时,网关把当前的完整历史保存到一个新的 OpenViking 会话,已经保存的轮次留在旧会话里。
-- **特别长的会话可能碰到请求大小上限。** 网关压缩对话后,客户端仍发送完整历史,但看到的用量很小,所以按用量决定何时压缩的客户端很少再自己压缩。请求体超过 32 MiB 会被拒绝,运维人员可以调整这个上限,见[长对话](22-gateway-operations.md#长对话)。
-- **一个密钥只对应一位记忆归属者。** 共用一个密钥的人共享其背后 OpenViking 用户的记忆。请给每人签发一个密钥;想让不同客户端使用不同的上下文配置,再按客户端分开签发。
-- **不支持订阅登录。** 带 Claude 订阅令牌的请求会被拒绝。请为上游配置服务商的 API Key。
-- **Responses 需要完整历史。** 依赖服务商端状态的 Responses 请求(`previous_response_id`、`conversation`、`background`),以及没有设置 `store: false` 的请求,直接转发,不补充记忆。之后查询这些响应时,请求仍然发往创建它们的上游。
-- **其他接口直接转发。** 三种模型 API 和模型列表之外的接口(例如 embeddings)不补充记忆,直接转发给密钥绑定的、提供所请求模型且优先级最高的上游。
+如果**上游**或**上下文配置**是只读的,或者 Studio 要求你**输入网关管理密钥**,见[谁能修改什么](../gateway/06-manage-in-studio.md#who-can-change-what)。
-## 下一步
+### 相关文档 {#related-docs}
-- [OpenViking 网关部署与运维](22-gateway-operations.md):用 Docker Compose、Helm 或独立进程部署,管理上游、上下文配置和密钥,排查问题。
-- [OpenViking 网关管理 API](../api/25-gateway.md):权限矩阵和管理接口。
- [认证](04-authentication.md):创建账号、用户和他们的密钥。
- [公网访问与反向代理](12-public-access.md):为 OpenViking 配置 HTTPS。
- [Agent 集成概览](../agent-integrations/01-overview.md):为支持插件的 Agent 安装插件。
diff --git a/docs/zh/guides/22-gateway-operations.md b/docs/zh/guides/22-gateway-operations.md
index c659af57f..13921b7c6 100644
--- a/docs/zh/guides/22-gateway-operations.md
+++ b/docs/zh/guides/22-gateway-operations.md
@@ -1,95 +1,50 @@
---
-description: 用 Docker Compose、Helm 或独立进程部署 OpenViking 网关,在 Studio 中管理网关并排查问题。
+description: 把 OpenViking 网关嵌入 Server、用 Docker Compose 或 Helm 部署,或者作为独立进程运行;再对外暴露、做好保护,并在升级中保持稳定运行。
---
# OpenViking 网关部署与运维
-本页写给运行 OpenViking 网关的人:怎么部署,怎么在 Studio 中管理上游、上下文配置和密钥,数据存在哪里、怎么备份,以及出了问题怎么查。网关能做什么、客户端怎么接入,见[OpenViking 网关](15-gateway.md);整体结构见[一张图看懂架构](15-gateway.md#一张图看懂架构)。
+本页写给把 OpenViking 网关作为服务来运行的人:按合适的方式部署、放到反向代理后面、控制谁能修改配置,以及在升级和迁移中保持服务正常。你需要一台使用 API 密钥认证或本地 dev 模式的 OpenViking Server,完整条件见[环境要求](#requirements)。第一次接触网关,请先读[OpenViking 网关](15-gateway.md)。
-网关目前处于 Beta 阶段,设置和接口可能随版本调整,升级前请先读发布说明。
+> **注意**:网关目前处于 Beta 阶段,设置和接口可能随版本调整,升级前请先读发布说明。
-## 环境要求
+**要找别的内容?** 本页只讲运行网关,其他内容见:
-- **OpenViking 的认证方式**:`api_key` 或本地 dev 模式。网关不支持 trusted 认证。
-- **OpenViking 版本**:嵌入运行时和 Server 同版本发布,无需额外检查;独立运行时要求 OpenViking Server 0.4.16 或更高版本。
-- **安装**:网关包含在 OpenViking 核心包中。可选的 `gateway-fast` extra(`pip install "openviking[gateway-fast]"`)装上更快的事件循环和 HTTP 解析器。
-- **登录身份**:远程部署需要 OpenViking API 密钥,普通用户、账号管理员和 root 都能登录 Studio 的网关页面。本地 dev 模式不需要密钥,固定使用 `default/default` 身份。
-- **存储**:本地磁盘。网关的 SQLite 数据库只供一台主机使用,不支持网络文件系统或跨主机共享存储。
+- Studio 标签页和各项设置:[在 Studio 中管理 OpenViking 网关](../gateway/06-manage-in-studio.md),以及[上游](../gateway/07-upstreams.md)、[上下文配置](../gateway/08-context-profiles.md)、[网关密钥](../gateway/09-gateway-keys.md)和[网关概览与请求日志](../gateway/10-overview-and-requests.md)。
+- 报错、告警或 Studio 设置卡片:[OpenViking 网关排障](../gateway/12-troubleshooting.md)。
+- 配置字段或环境变量:[配置参考](../gateway/13-configuration.md)。
+- 存了什么、谁能看到、保留多久、怎么备份:[安全与数据](../gateway/11-security-and-data.md)。
+- OpenViking 工具或长对话:[网关中的 OpenViking 工具](../gateway/04-openviking-tools.md)和[网关中的长对话](../gateway/05-long-conversations.md)。
+- 某个客户端怎么配置:[把客户端接入 OpenViking 网关](../gateway/03-connect-clients.md)。
-## 密钥和凭证
+## 环境要求 {#requirements}
-网关涉及四种密钥,各管一件事:
-
-| 密钥 | 用途 | 在哪里使用 |
-| --- | --- | --- |
-| OpenViking API 密钥 | 登录 Studio;决定以哪个账号、哪个用户的身份读写记忆 | 管理请求的 `X-API-Key` 或 `Authorization: Bearer` |
-| 网关密钥(`ovgw_…`) | 客户端接入;每把绑定一位用户、一份上下文配置和一组上游 | 客户端的 API Key 输入框 |
-| 网关管理密钥(可选) | 限制谁能修改上游和上下文配置 | `gateway.management_key`;请求头 `X-OpenViking-Gateway-Management-Key` |
-| 上游 API Key | 调用模型服务商 | 上游编辑页 |
-
-网关没有自己的加密密钥,本地存储按 OpenViking 的加密配置加密,见[加密](#加密)。
-
-### 网关管理密钥
-
-不设置管理密钥时,账号内每个登录的用户都能添加和修改本账号的上游和上下文配置。设置之后,只有带上这把密钥的请求能修改它们,OpenViking 的 admin 和 root 也不例外;其他人只能查看、测试,并在签发密钥时选用。管理密钥不限制谁能登录,也不限制用户给自己签发网关密钥。完整的权限规则见[权限矩阵](../api/25-gateway.md#凭证和账号范围)。
-
-设置方法:
-
-- **`openviking-server init`**(嵌入):远程部署回答 **Allow users to configure their own gateway upstreams?** 时选 no,init 会生成一个以 `ovgm_` 开头的值,打印出来并写入 `ov.conf` 的 `gateway.management_key`。
-- **`openviking-gateway init`**(独立):回答 **Require a management key to change upstreams and profiles?** 时选 yes,init 会生成一个 `ovgm_` 开头的值,只打印一次,并写入 `gateway.conf` 的 `management_key`。
-- **手动设置**:值至少 32 个字符,可以用 `openssl rand -base64 32` 生成。写进 `management_key`,或者设置环境变量 `OPENVIKING_GATEWAY_MANAGEMENT_KEY`;两种部署下环境变量都优先于配置文件,见[配置参考](#配置参考)。
-- **Compose 和 Helm**:Compose 会把 `OPENVIKING_GATEWAY_MANAGEMENT_KEY` 传进容器;Helm 从 `gateway.existingSecret` 指定的 Secret 中读取 `management-key` 字段。见 [Docker Compose](#docker-compose) 和 [Helm](#helm)。
-
-管理密钥不提供命令行参数,因为命令行参数会出现在进程列表和 shell 历史里。设置、更换或去掉管理密钥后需要重启,这不会吊销已签发的网关密钥,也不会改动已有的上游和上下文配置。
-
-#### 忘记网关管理密钥
-
-到网关读取它的位置查找:
-
-- 环境变量 `OPENVIKING_GATEWAY_MANAGEMENT_KEY` 优先于配置文件。Compose 部署一般写在 `docker-compose.yml` 旁边的 `.env` 里;Helm 从 `gateway.existingSecret` 指定的 Secret 中读取 `management-key` 字段。
-- 没有设置环境变量时,看 `ov.conf` 的 `gateway.management_key`(嵌入)或 `gateway.conf` 的 `management_key`(独立)。值写成 `$VAR` 时,密钥在对应的环境变量里。
-- 嵌入部署的 root 还可以在 Studio 的**设置** → **服务端配置** → **文件编辑**中查看 `ov.conf`。`openviking-server init` 和 Studio **开启网关**生成的密钥都以明文保存在这里。
-
-实在找不回来,就在原来的位置换一个至少 32 个字符的新值(可以用 `openssl rand -base64 32` 生成),然后重启。已签发的网关密钥、上游和上下文配置都不受影响。把环境变量设为空字符串不会清除文件里的值,需要删掉这个变量。
-
-### 加密
-
-网关用 OpenViking 自己的加密功能保护已存的凭证和对话状态(见[加密指南](08-encryption.md)):
-
-- **嵌入**:网关沿用 Server 在 `ov.conf` 中的 `encryption` 段,不需要为网关单独设置。
-- **独立**:在 `gateway.conf` 中加一个 `encryption` 块,字段和 `ov.conf` 的 `encryption` 段完全相同,例如:
-
- ```json
- {
- "openviking_url": "https://ov.example.com",
- "encryption": {
- "enabled": true,
- "provider": "local",
- "local": { "key_file": "~/.openviking/master.key" }
- }
- }
- ```
-
-加密关闭或没有这个块时,网关以明文存储,只靠文件权限保护。之后再开启加密不会出问题:已有的明文值照常可读,新写入的值会加密。反过来,关闭加密或换一把根密钥后,已加密的值就读不出来了,所以要保持写入时的加密设置。按加密指南备份根密钥,丢了它,网关的数据库就无法读取。
+| 条件 | 说明 |
+| --- | --- |
+| OpenViking 认证方式 | `api_key` 或本地 dev 模式。网关不支持 trusted 认证。 |
+| OpenViking 版本 | 嵌入运行时和 Server 同版本发布,无需额外检查;独立运行时要求 OpenViking Server 0.4.16 或更高版本。 |
+| 安装 | 网关包含在 OpenViking 核心包中。可选的 `gateway-fast` extra(`pip install "openviking[gateway-fast]"`)装上更快的事件循环和 HTTP 解析器。 |
+| 登录身份 | 远程部署需要 OpenViking API 密钥,普通用户、账号管理员和 root 都能登录 Studio 的网关页面。本地 dev 模式不需要密钥,固定使用 `default/default` 身份。 |
+| 存储 | 本地磁盘。网关的 SQLite 数据库只供一台主机使用,不支持网络文件系统或跨主机共享存储。 |
-v0.5 网关用自己的密钥加密数据,这些数据会在首次启动时转换,见[迁移](#迁移)。
+## 选择部署方式 {#deployment-options}
-## 部署
+网关可以运行在 OpenViking Server 内部(嵌入),也可以作为单独的进程运行(独立)。两种方式都在 `/gateway` 下提供相同的模型路径和管理路径。
-### 部署方式
+| 方式 | 适用场景 | 怎么开启 | 客户端地址 |
+| --- | --- | --- | --- |
+| 嵌入 Server(包括 Compose 和 Helm) | OpenViking Server 由你自己运行。不需要第二个进程,也不需要按路径分流的反向代理。 | 在 `ov.conf` 中开启 `gateway.enabled` | Server 地址加 `/gateway`,默认 `http://127.0.0.1:1933/gateway` |
+| 独立运行 | 不想改动 OpenViking 服务的配置,例如使用 OpenViking 商业版服务。 | 先 `openviking-gateway init`,再 `openviking-gateway` | 网关自己的地址加 `/gateway`,默认 `http://127.0.0.1:1935/gateway` |
-| 方式 | 怎么开启 | 客户端地址 |
-| --- | --- | --- |
-| 嵌入 Server(包括 Compose 和 Helm) | 在 `ov.conf` 中开启 `gateway.enabled` | Server 地址加 `/gateway`,默认 `http://127.0.0.1:1933/gateway` |
-| 独立运行 | 先 `openviking-gateway init`,再 `openviking-gateway` | 网关自己的地址加 `/gateway`,默认 `http://127.0.0.1:1935/gateway` |
+选好之后,按你的部署方式阅读对应小节:[在 Server 中启用](#enable-it-in-the-server)、[Docker Compose](#docker-compose)、[Helm](#helm)或[独立部署](#standalone-deployment)。
-两种方式都在 `/gateway` 下提供相同的模型路径和管理路径。嵌入部署不需要第二个进程,也不需要按路径分流的反向代理;独立部署不用改动已有 OpenViking 服务的配置。
+## 在 Server 中启用 {#enable-it-in-the-server}
-### 在 Server 中启用
+嵌入网关运行在 OpenViking Server 内部、和 Server 共用端口,默认关闭(`gateway.enabled` 为 `false`)。开启之前,Studio 的 **OpenViking 网关**页面会显示**这台 OpenViking 没有开启网关**。开启方式有三种。
-运行 `openviking-server init`,在 **Enable OpenViking Gateway on the same port?** 处回答 yes,然后启动或重启服务。已有配置时,在菜单中选择 **Update gateway**。远程部署还会询问是否允许用户自行配置上游,见[网关管理密钥](#网关管理密钥)。
+**用 `openviking-server init`。** 在 **Enable OpenViking Gateway on the same port?** 处回答 yes,然后启动或重启服务。已有配置时,在菜单中选择 **Update gateway**。远程部署还会询问是否允许用户自行配置上游,见[网关管理密钥](#gateway-management-key)。
-也可以手动把下面的内容合并进 `ov.conf`,再重启:
+**改 `ov.conf`。** 把下面的内容合并进 `ov.conf`,再重启服务:
```json
{
@@ -99,44 +54,25 @@ v0.5 网关用自己的密钥加密数据,这些数据会在首次启动时转
}
```
-使用 API 密钥的服务端上,root 也可以在 Studio 的 OpenViking 网关页面点**开启网关**:Studio 会把 `gateway.enabled: true` 写入 `ov.conf` 并重启服务(从 Studio 重启要求服务端只有一个 worker,否则 Studio 只保存文件,需要你自行重启)。
+**在 Studio 中开启。** 使用 API 密钥的服务端上,root 可以在 Studio 的 OpenViking 网关页面点**开启网关**,Studio 会把 `gateway.enabled: true` 写入 `ov.conf` 并重启服务。确认对话框还可以顺便生成网关管理密钥,见[网关管理密钥](#gateway-management-key)。几种例外情况:
-打开服务端的 `/studio/`,在侧边栏选择 **OpenViking 网关**。dev 模式下,如果默认账号还没有上游,网关启动时会导入服务端可用的 VLM 凭证作为上游,并创建 `default` 上下文配置。导入的 Coding Plan 上游需要确认后才能使用;没有可导入的凭证时,请手动添加上游。
+- 从 Studio 重启要求服务端只有一个 worker,否则 Studio 只保存文件,需要你自行重启。
+- 设置了 `OPENVIKING_GATEWAY_ENABLED` 时,它会覆盖 `ov.conf` 中的 `gateway.enabled`,值为 false 时重启后网关仍不开启。
+- `ov.conf` 只读时(例如由 Helm ConfigMap 挂载),Studio 改不了它。请在 Helm values 中设置 `gateway.enabled: true`,或者设置 `OPENVIKING_GATEWAY_ENABLED=true`,然后重启服务。
-**让 Agent 修改配置。** 持有 root API 密钥的 Agent 可以通过[运行时配置接口](../api/08-admin.md#runtime-configuration)修改 `ov.conf` 并重启服务。独立网关不提供这组接口。
+**确认已经开启。** 打开服务端的 `/studio/`,在侧边栏选择 **OpenViking 网关**,应看到网关的各个标签页,而不是未开启的提示卡片。本地 dev 模式下,如果默认账号还没有上游,网关启动时会导入服务端可用的 VLM 凭证作为上游,并创建 `default` 上下文配置。导入的 Coding Plan 上游需要确认后才能使用;没有可导入的凭证时,请手动添加上游(见[添加上游](../gateway/07-upstreams.md#add-an-upstream))。
-### 路由
-
-两种部署方式下,网关的所有 URL 都在 `/gateway` 下。嵌入部署中,Server 把整个 `/gateway` 前缀交给网关,其他路径仍由 Server 自己处理:
-
-| 路径前缀 | 用途 |
-| --- | --- |
-| `/gateway/v1/` | 模型 API 和模型列表 |
-| `/gateway/api/v3/` | 方舟兼容客户端 |
-| `/gateway/api/compatible/v1/` | 方舟 Anthropic 兼容客户端 |
-| `/gateway/uploads` | 工具上传 |
-| `/gateway/admin/` | 管理 API,需要认证 |
-
-因此客户端使用下面的 Base URL,把 `http://127.0.0.1:1933` 换成你的 Server 地址即可:
-
-| 客户端 | Base URL |
-| --- | --- |
-| Claude Code 和 Anthropic SDK | `http://127.0.0.1:1933/gateway` |
-| OpenAI 兼容的客户端和 SDK,包括 Codex、OpenCode、pi 和 Open WebUI | `http://127.0.0.1:1933/gateway/v1` |
-| 火山方舟和 BytePlus 方舟 SDK | `http://127.0.0.1:1933/gateway/api/v3` |
-
-`/health` 仍是 Server 自己的健康检查,嵌入网关不单独提供 `/health`。
-
-独立网关在自己的端口上提供同样的 `/gateway` 路径,另外在根路径提供:
+**让 Agent 修改配置。** 持有 root API 密钥的 Agent 可以通过[运行时配置接口](../api/08-admin.md#runtime-configuration)修改 `ov.conf` 并重启服务。独立网关不提供这组接口。
-- `/` 跳转到 `/studio/`,Studio 只包含网关和连接页面。
-- `/health` 返回 `service: "openviking-gateway"`、`auth_mode` 和 `openviking_url`;请求带有效的 OpenViking 凭证时,还返回调用方身份。
+## Docker Compose {#docker-compose}
-**对外地址。** 共享部署要把 `public_url` 设为客户端访问 Server(或独立网关)的地址,不带 `/gateway`,网关会自己加上。嵌入网关不设置时,沿用 Server 的对外地址(`OPENVIKING_PUBLIC_BASE_URL` 或 `server.public_base_url`)。Studio 的接入指南用它生成配置:Anthropic 客户端使用 `<public_url>/gateway`,OpenAI 风格的客户端使用 `<public_url>/gateway/v1`。不设置时,指南使用浏览器访问 Studio 的地址;但上传和下载链接必须依赖 `public_url`,见[导入文件和技能](#导入文件和技能)。
+用 Docker Compose 部署时,网关在 `openviking` 服务内运行,不需要单独的服务或 profile。
-### Docker Compose
+1. 在 `.env` 中设置 `OPENVIKING_GATEWAY_ENABLED=true`,或者在挂载的 `ov.conf` 里开启 `gateway.enabled`。设置了这个变量时,以变量为准。
+2. 确认挂载的 `ov.conf` 使用 API 密钥认证:容器内 Server 监听 `0.0.0.0`。
+3. 运行 `docker compose up -d`,打开 1933 端口上的 `/studio/`,选择 **OpenViking 网关**,应看到网关的各个标签页。服务没起来时,用 `docker compose logs openviking` 查看启动错误。
-在 `.env` 中设置 `OPENVIKING_GATEWAY_ENABLED=true`,然后运行 `docker compose up -d`;也可以在挂载的 `ov.conf` 里开启 `gateway.enabled`。网关在 `openviking` 服务内运行,不需要单独的服务或 profile。不用 Compose 时,`docker run` 加上 `-e OPENVIKING_GATEWAY_ENABLED=true` 即可:
+不用 Compose 时,`docker run` 加上 `-e OPENVIKING_GATEWAY_ENABLED=true` 即可:
```bash
docker run -d -p 1933:1933 -v ~/.openviking:/app/.openviking \
@@ -144,17 +80,15 @@ docker run -d -p 1933:1933 -v ~/.openviking:/app/.openviking \
ghcr.io/volcengine/openviking:latest
```
-容器内 Server 监听 `0.0.0.0`,所以 `ov.conf` 要使用 API 密钥认证。
-
-- **管理密钥**:在 `.env` 中设置 `OPENVIKING_GATEWAY_MANAGEMENT_KEY`,自带的 Compose 文件会把它传进容器;也可以写进挂载的 `ov.conf` 的 `gateway.management_key`。Compose 文件还会传入 `OPENVIKING_GATEWAY_ENCRYPTION_KEY`,它只在迁移 v0.5 数据时读取一次,见[迁移](#迁移)。
-- **对外地址**:设置 `OPENVIKING_PUBLIC_BASE_URL`(自带的 Compose 文件会传入)即可,网关没有单独配置 `public_url` 时沿用它。
-- **修改配置后**:执行 `docker compose restart openviking`;启动错误用 `docker compose logs openviking` 查看。
+- **管理密钥**:在 `.env` 中设置 `OPENVIKING_GATEWAY_MANAGEMENT_KEY`,自带的 Compose 文件会把它传进容器;也可以写进挂载的 `ov.conf` 的 `gateway.management_key`。Compose 文件还会传入 `OPENVIKING_GATEWAY_ENCRYPTION_KEY`,它只在迁移 v0.5 数据时读取一次,见[迁移](#migration)。
+- **对外地址**:设置 `OPENVIKING_PUBLIC_BASE_URL`(自带的 Compose 文件会传入)即可,网关没有单独配置 `public_url` 时沿用它。见[对外地址](#public-address)。
+- **修改配置后**:改了挂载的 `ov.conf`,执行 `docker compose restart openviking`;改了 `.env`,执行 `docker compose up -d`,因为 `restart` 沿用原来的容器,读不到 `.env` 的新值。
自带的 Caddy 把所有路径转发到 `openviking:1933`。可以继续用兼容端口 1934,也可以直接访问 Server 的 1933。配置 HTTPS 时,一条 `reverse_proxy openviking:1933` 就能承载 Studio、管理接口和模型流量,见[公网访问](12-public-access.md)。
-### Helm
+## Helm {#helm}
-在 chart values 中设置 `gateway.enabled: true`。网关嵌入 server 容器,数据保存在 `<persistence.mountPath>/gateway`,Service 和 Ingress 都使用 Server 端口。保持 `replicaCount: 1`。
+用 Helm chart 部署时,在 chart values 中设置 `gateway.enabled: true`。网关嵌入 server 容器,数据保存在 `<persistence.mountPath>/gateway`,Service 和 Ingress 都使用 Server 端口。保持 `replicaCount: 1`。
```yaml
gateway:
@@ -167,745 +101,252 @@ config:
- 网关和 Server 一样,按 chart 的 `config.encryption` 设置加密数据。
- `existingSecret` 指定的 Secret 中有 `management-key` 字段时,修改上游和上下文配置需要这把管理密钥。
-- 模型请求是流式的:Ingress 要关闭响应缓冲,允许至少 32 MiB 的请求体和 600 秒超时。
+- 模型请求是流式的:Ingress 要关闭响应缓冲,允许至少 32 MiB 的请求体和 600 秒超时(见[反向代理和 HTTPS](#reverse-proxy-and-https))。
NGINX annotations、创建 Secret 的命令和从 sidecar 版本升级的说明见 [chart README](https://github.com/volcengine/OpenViking/blob/main/deploy/helm/README.md#openviking-gateway)。
-### 独立部署
-
-独立网关不读取 `ov.conf`,只需要知道 OpenViking 的地址,已有的开源版或商业版服务不用改配置:
+## 独立部署 {#standalone-deployment}
-```bash
-openviking-gateway init # 写入 ~/.openviking/gateway.conf
-openviking-gateway
-```
-
-`openviking-gateway init` 依次询问 OpenViking 地址(会实际访问一次,并显示服务端的认证模式和版本)、监听地址(默认 `127.0.0.1:1935`),以及是否要求[管理密钥](#网关管理密钥)。结果写入 `~/.openviking/gateway.conf`,或者 `--config` 指定的文件,只有你自己能读。想修改设置就再运行一次:它把当前值作为默认值,已有的密钥不改就原样保留。生成的文件类似这样:
-
-```json
-{
- "openviking_url": "https://ov.example.com",
- "host": "127.0.0.1",
- "port": 1935
-}
-```
-
-打开网关的 `/studio/`,用 OpenViking 用户、账号管理员或 root 的 API 密钥登录。连接页会显示网关连接的 OpenViking 地址。独立网关读不到远端服务的 VLM 配置,所以不能导入模型配置,上游要手动添加。
-
-**设置从哪里来。** 命令行只有 `--config` 一个参数。设置了 `--config` 或 `OPENVIKING_GATEWAY_CONFIG_FILE` 时,它必须指向已存在的文件;两者都没设置时,网关读取 `~/.openviking/gateway.conf` 和 `/etc/openviking/gateway.conf` 中第一个存在的文件。环境变量可以覆盖其中任何字段。容器里可以完全不用文件:设置 `OPENVIKING_GATEWAY_OPENVIKING_URL`,再按需加上 `OPENVIKING_GATEWAY_HOST=0.0.0.0` 之类的变量。两处都没有 OpenViking 地址时,网关退出,并提示运行 `openviking-gateway init` 或设置 `OPENVIKING_GATEWAY_OPENVIKING_URL`。全部字段和覆盖规则见[配置参考](#配置参考)。
-
-**启动检查。** 独立网关启动前会先访问一次 OpenViking:
-
-- OpenViking 使用 trusted 认证时,网关拒绝启动。
-- 绑定非回环地址时,必须确认 OpenViking 使用 `api_key` 认证才会启动;OpenViking 连不上或处于 dev 模式时,网关直接退出。请先启动 OpenViking,或者只绑定 `127.0.0.1`。
-- 跨主机连接 OpenViking 时,请使用 TLS 或私有网络。
-
-**连接公共 OpenViking 服务。** 连接 `https://api.vikingdb.cn-beijing.volces.com/openviking` 且没有设置管理密钥时,启动日志和 Studio 都会显示 `public_openviking_without_management_key` 告警:任何持有该服务 API 密钥的人都能登录这台网关,并修改所在账号的上游。网关只给你自己或团队使用时,设置 `OPENVIKING_GATEWAY_MANAGEMENT_KEY` 后重启即可限制修改;这不限制谁能登录,也不限制他们给自己签发网关密钥。
-
-### 反向代理和 HTTPS
-
-把整个站点转发到 Server(嵌入)或网关(独立),不需要按路径分流。以 Caddy 为例:
-
-```caddyfile
-ov.example.com {
- reverse_proxy 127.0.0.1:1933 {
- flush_interval -1
- }
-}
-```
-
-无论用哪种代理,都要满足三点:关闭响应缓冲,流式输出才能实时到达;允许至少 32 MiB 的请求体;读取超时至少 600 秒。另外,不要在代理日志中记录 `/gateway/uploads` 的查询字符串,其中带有一次性上传令牌。对外发布前先配置好认证,见[公网访问](12-public-access.md)。
-
-### 扩展
-
-一个存储目录只供一台主机上的一套部署使用,嵌入网关和独立网关不能共用同一目录。嵌入网关跟随 Server 的 worker 设置;独立网关用 `workers` 设置,取值 1–64。需要在服务商之间负载均衡、故障转移或限流时,把 LiteLLM 这类服务添加为上游。
-
-## 在 Studio 中管理网关
-
-用 OpenViking API 密钥连接 Studio 后,在侧边栏打开 **OpenViking 网关**。上游和上下文配置由整个账号共享,网关密钥和请求日志属于各个用户:
-
-- **没有设置管理密钥**:每个登录的用户都能添加和修改本账号的上游和上下文配置。
-- **设置了管理密钥**:“上游”和“上下文配置”标签页变为只读,OpenViking 的 admin 和 root 也一样。只读时仍能查看上游(看不到 API Key 和请求头),并在给自己签发密钥时选用;模型测试会真实请求服务商并可能计费,因此需要写权限。点**输入网关管理密钥**解锁编辑和测试,页头会显示“可修改上游和上下文配置”;解锁状态保持到点击**锁定**或关闭浏览器标签页。管理密钥被更换后,Studio 会自动锁定。
-- **网关密钥**:每个人都能给自己签发;账号管理员可以给本账号的用户签发;root 先在侧边栏切换账号。见[网关密钥](#网关密钥)。
+独立网关不读取 `ov.conf`,只需要知道 OpenViking 的地址,已有的开源版或商业版服务不用改配置。
-上游和上下文配置保存后,立即对使用它们的密钥生效(上下文配置只影响之后开始的对话)。还没有可用的上游或上下文配置、自己又不能修改时,请联系部署网关的人。
-
-### 上游
-
-上游是模型服务的一个接口,只使用一种 API:Anthropic Messages、Chat Completions 或 Responses。网关不在 API 之间转换,所以客户端用到几种 API,就要添加几个上游,即使它们来自同一家服务商:Claude Code 用 Anthropic Messages,Codex CLI 用 Responses,大多数聊天应用和 SDK 用 Chat Completions。
-
-在编辑页选择服务商后,会自动填入它的默认 Base URL:
-
-| 服务商 | 协议 | 默认 Base URL |
-| --- | --- | --- |
-| 通用 | 三种都有 | 无,自己填写 |
-| Anthropic | Anthropic Messages | `https://api.anthropic.com` |
-| OpenAI | Chat Completions、Responses | `https://api.openai.com/v1` |
-| DeepSeek | 三种都有 | `https://api.deepseek.com`;Anthropic Messages 为 `https://api.deepseek.com/anthropic` |
-| 火山方舟 | 三种都有 | Chat Completions 和 Responses 为 `https://ark.cn-beijing.volces.com/api/v3`;Anthropic Messages 为 `https://ark.cn-beijing.volces.com/api/compatible` |
-| BytePlus 方舟(海外站) | 三种都有 | Chat Completions 和 Responses 为 `https://ark.ap-southeast.bytepluses.com/api/v3`;Anthropic Messages 为 `https://ark.ap-southeast.bytepluses.com/api/compatible` |
-
-#### 接口
-
-- **服务商**决定可选的协议,并让网关适配各家的差异。列表里没有的服务商、LiteLLM 和 new-api 这类兼容代理,以及 [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) 这类把订阅账号包装成 API 的反向代理,都选*通用*(见[自定义上游](15-gateway.md#自定义上游);用订阅额度是否合规请自行确认)。
- - *通用*、*Anthropic* 和 *OpenAI* 转发请求的方式相同。
- - *DeepSeek*:请求带工具时,DeepSeek 要求历史中之前每条回复都带推理内容,而很多聊天应用不回传它。DeepSeek 上游默认开启**补全推理内容回传**(见下文“路由和开关”),所以请求保持思考模式也能用 OpenViking 工具。关闭这项后,只有请求关闭了思考模式(`"thinking": {"type": "disabled"}`)才提供 OpenViking 工具;标准 Responses 请求没有 `thinking` 字段,这时也得不到工具。记忆照常补充。
- - *火山方舟*和 *BytePlus 方舟*行为相同:Chat Completions 和 Responses 的每段对话使用一个固定的 `prompt_cache_key`,方舟的前缀缓存就能跟着对话走。请求的模型、思考模式、采样参数、系统提示词或工具和对话的第一个请求不同时,方舟会重建缓存,请求被标为**缓存参数有变化**(`ark_cache_parameters_changed`)。
-- **协议**决定上游接受哪种 API。Anthropic 上游同时发送 `x-api-key` 和 `Authorization: Bearer`,Chat Completions 和 Responses 上游只发送 Bearer。
-- **Base URL** 按服务商 SDK 文档填写,网关在后面拼接端点:
- - Chat Completions 和 Responses 拼接 `/chat/completions` 或 `/responses`。只填域名时不会自动补 `/v1`,OpenAI 要写 `https://api.openai.com/v1`。
- - Anthropic Messages 拼接 `/v1/messages`,所以 Base URL 不能以 `/v1` 结尾,否则保存时被拒绝。
- - 末尾的斜杠会被去掉。`/api/paas/v4` 这类带版本路径的地址可以直接使用。
- - Base URL 可以带查询参数,例如 `?api-version=…`。客户端的查询参数接在后面,同名参数以 Base URL 里的为准。
- - 客户端用方舟路径(`/gateway/api/v3/`、`/gateway/api/compatible/v1/`)发来的请求,按同样的规则拼接。
- - Azure OpenAI v1 接口填 `https://RES.openai.azure.com/openai/v1`,Microsoft Foundry 上的 Claude 用 Anthropic Messages 协议、填 `https://RES.services.ai.azure.com/anthropic`,Gemini 的 OpenAI 兼容接口填 `https://generativelanguage.googleapis.com/v1beta/openai`,都按拼接规则使用。
- - 一个上游只有一个 Base URL。同一服务商的不同协议地址不同时,要分别建上游:例如智谱 Chat Completions 用 `https://open.bigmodel.cn/api/paas/v4`,Responses 用 `https://open.bigmodel.cn/api/v1`。方舟 Coding Plan 的 Chat Completions 和 Responses 用 `…/api/coding/v3`,Anthropic Messages 用 `…/api/coding`。
-- **拼接协议接口路径**默认开启。如果 Base URL 已经是完整的请求地址,可以关闭它;关闭后,网关把该协议的请求直接发往这个 URL,不再拼接协议路径。子路径接在后面:Anthropic 的 Token 计数发往 `…/count_tokens`。Embeddings、模型列表等其他接口不会路由到这样的上游,连接测试也会跳过它。例如 Azure OpenAI 部署:协议选 *Chat Completions*,服务商选*通用*,Base URL 填 `https://RES.openai.azure.com/openai/deployments/DEPLOYMENT/chat/completions?api-version=2024-10-21`,关闭这个开关,**密钥发送方式**选 *api-key 请求头*。
-
- 编辑页会实时预览最终的请求地址;OpenAI、方舟这类地址漏掉路径,或者 Anthropic 地址多了 `/v1` 时,会给出提示和一键修正。
-
-#### 凭证
-
-- **API Key 由谁提供**:
- - **由网关保管 API Key**(默认):网关发送上游的 API Key,客户端只需要网关密钥。
- - **每个客户端自带 API Key**:每个请求除了网关密钥,还要在 `X-OpenViking-Upstream-Key` 请求头里带上客户端自己的服务商 API Key,缺少时返回 401 "Upstream API key is missing"。网关按**密钥发送方式**转发这个 API Key(Base URL 含 `{api_key}` 时填进地址),`X-OpenViking-*` 请求头本身从不转发。
-- **密钥发送方式**(仅服务商为*通用*时):`Authorization: Bearer`(默认)、`api-key` 请求头(Azure OpenAI)或 `x-api-key` 请求头。
-- **密钥放在地址里**:服务商要求把密钥写在地址里时,在 Base URL 的路径或查询参数中写 `{api_key}`,例如 `?key={api_key}`。网关发送时填入 URL 编码后的密钥,并且不再发送鉴权请求头。不要把密钥本身写进地址:能查看上游的人都能看到 Base URL。
-- **API Key 和额外请求头只写不读**:留空表示保留已存的值,删除请求头行就删除这个请求头。**修改 Base URL 会清除已存的 API Key 和请求头值**,所以每次改地址都要重新填写,已存的密钥不会被发往新地址。
-- **额外请求头**加在发往这个上游的每个请求上,例如服务商的版本或组织请求头,并覆盖客户端发送的同名请求头。不能设置 `Host`、`Content-Length`、`Transfer-Encoding` 和 `Connection`。
-- **这是 Coding Plan 或订阅密钥**:服务商通常只允许 Coding Plan 这类订阅密钥用在自家的编程工具里,通过共享网关使用可能导致订阅被封禁。勾选后,发往这个上游的请求一律被拒绝,返回 403 "Coding Plan upstreams are disabled; configure a model API key",除非同时勾选**允许通过网关使用这个套餐**。网关无法从密钥本身分辨它是不是订阅密钥,需要你自己标记。Claude 订阅令牌(`sk-ant-oat…`)始终被拒绝。
-
-#### 模型
-
-- **模型**列出这个上游提供的模型名,留空表示接受任何名称。只有列出的名称和别名会出现在模型列表(`/gateway/v1/models`)里。
-- **模型别名**把客户端使用的名称映射为发给上游的模型,例如把 Claude Code 请求的 Claude 模型名映射到服务商提供的模型。别名出现在模型列表中,请求日志显示客户端使用的名称。
-- **上下文窗口**按模型记录窗口大小(token,至少 1,024),键是映射之后、实际发给上游的模型名。长对话按窗口的比例触发压缩,窗口小于 1,000,000 token 的模型都要列出来,见[长对话](#长对话)。
-
-#### 路由和开关
-
-- **优先级**:对每个请求,网关在密钥绑定的已启用上游中,找出使用这种 API 并提供所请求模型的上游,选优先级最高的一个。对话一旦开始,只要原来的上游还能服务就一直用它,所以修改优先级只影响新对话。
-- **启用**:停用的上游不接收请求,也不出现在模型列表里。原本使用它的对话会转到下一个候选上游,造成一次服务商缓存未命中,并丢掉之前的 Claude 思考块,这些请求被标为**上游已切换**(`upstream_changed`)。想保留恢复的余地,就停用而不是删除。
-- **允许 OpenViking 工具**:决定能否通过这个上游提供 OpenViking 工具。关闭后立即生效,已经带工具的对话也受影响。
-- **补全推理内容回传**:客户端回传历史时常常丢掉模型之前回复里的推理内容。开启后,网关记下经它转发的每条回复的推理内容,在后续请求中放回原处:Chat Completions 补回 `reasoning_content`,Anthropic Messages 放回 thinking 块,Responses 把带明文内容的 reasoning 项放回对应条目之前。补回的内容每次逐字节相同,服务商的提示缓存照常命中,但计入输入 token。客户端自己回传了推理内容的回复保持不变。DeepSeek、火山方舟和 BytePlus 方舟默认开启,其他服务商默认关闭。有些请求即使开启也补不回推理内容:对话换了上游(`upstream_changed`)、Claude 对话丢了记忆记录(`missing_injection_record`),或者客户端把思考内容当作正文发回;DeepSeek 上游的这类请求同样得不到 OpenViking 工具。
-- **最小可缓存长度**(仅火山方舟和 BytePlus 方舟):模型能缓存的最短提示词长度,只影响请求日志如何报告缓存资格。
-
-除了优先级,其他上游设置都立即生效,进行中的对话也一样。网关不做故障转移:选中的上游出错时,客户端收到这个错误;服务商无法访问时返回 502 "Model upstream is unavailable"。
-
-#### 测试和删除
-
-有写权限时,在上游列表里点**测试**,网关先检查已保存配置的连接。连接成功后,再选择或输入模型名运行模型测试。网关使用已存的凭证发送一次很小的生成请求,验证接口地址、密钥、模型名和协议能否一起正常工作。上游允许 Gateway 工具时会带上 OpenViking 工具,reasoning effort 使用模型默认值。服务商可能对模型请求计费。Coding Plan 上游在授权网关使用前仍会阻止模型测试。各种结果的含义见[上游测试](../api/25-gateway.md#上游测试)。
-
-有密钥在用的上游不能删除:先吊销这些密钥,或者改为停用这个上游。
-
-### 导入 OpenViking 模型配置
-
-嵌入部署中,**使用 OpenViking 的模型配置**(上游页头的**从 OpenViking 导入**)把服务端的 VLM 凭证导入为当前账号的上游。没有设置管理密钥时只有 root(包括本地 dev)能导入;设置了管理密钥时需要先解锁。
-
-- 结果分三组显示:已导入、需要确认、未导入。路径中带 `coding` 或 `plan` 的上游被标为 Coding Plan,确认服务商条款允许后,勾选**允许通过网关使用这个套餐**才能使用。
-- 重复导入不会产生重复的上游。再次导入时,地址、API Key、请求头、协议和服务商按服务端配置刷新;你在网关里改过的名称、启用状态、优先级、模型、别名、上下文窗口和 Coding Plan 确认都保留。
-- Azure OpenAI 凭证(服务商 `azure`,或 LiteLLM 的 `azure/<deployment>`)会导入为完整请求地址的上游,带上配置的 `api_version`,密钥放在 `api-key` 请求头里发送。
-- Codex OAuth 凭证、缺少 `api_base` 的 LiteLLM 凭证,以及不使用 OpenAI Chat Completions API 的 LiteLLM 路由会被跳过,原因见[导入 VLM 配置](../api/25-gateway.md#导入-vlm-配置)。
-
-### 上下文配置
-
-上下文配置是一组有名字的记忆设置。每个网关密钥使用一份,一份可以供多个密钥使用。比如准备一份“Coding”配置,召回记忆、资源和技能;再准备一份“Chat”配置,只召回记忆,预算也小一些。
-
-“上下文配置”标签页为每份配置显示一张卡片,概括各部分的设置和使用它的密钥数。标签页为空时,**使用推荐设置创建**一键创建一份名为“默认”的配置,**自定义**打开编辑页;之后用**新建配置**。有密钥在用的配置不能删除;想做一份变体,用**复制一份**最快。
-
-> **注意**:保存的修改只对之后开始的对话生效。对话在第一个请求时记下当时的上下文配置并一直沿用,因为中途改变模型看到的内容会破坏服务商缓存。每次聊天都新开对话的客户端很快就能用上新设置;Claude Code、Codex 以及发送固定会话请求头的客户端会一直沿用旧设置,直到开始新对话,或者这段对话闲置满 30 天(`session_ttl_days`)。
-
-| 部分 | 作用 | 主要设置和默认值 |
-| --- | --- | --- |
-| 召回记忆 | 用每条新的用户消息检索 OpenViking,把相关内容附加到这条消息上。 | 检索范围:记忆、资源、技能 · 单条消息预算:1,600 token · 单个上下文窗口预算:30,000 token · 相关度阈值:0.35 · 超时时间:2 秒 |
-| 保存对话 | 把完成的轮次写入 OpenViking 会话并提交,供 OpenViking 提取记忆。 | 最新回复等待时长:600 秒 · 提交阈值:20,000 token · 保留最近消息:10 |
-| 长对话 | 对话接近上下文窗口时,让同一个模型写摘要,替换之前的消息。 | 压缩:开启 · 压缩时机:窗口的 0.9 · 摘要长度上限:8,000 token · Agent 自管上下文窗口:关闭 |
-| OpenViking 工具 | 让模型在回答时使用 OpenViking 的工具。 | 开启 · 只勾选只读工具,见 [OpenViking 工具](#openviking-工具) |
-
-每个部分都有自己的开关,长对话部分的压缩和 Agent 自管上下文窗口各有一个。召回和保存相互独立,只召回不保存、只保存不召回都可以。
-
-**召回的细节:**
-
-- **会话开头提供用户画像**独立于召回。提供 `read` 工具时,开头还提供记忆和技能目录。**开头内容预算**默认 4,000 token,技能最多占四分之一,设为 0 时全部省略;这部分不占召回预算。
-- 召回内容由 OpenViking 在预算内选取和排版,也可能只给出 URI,供模型之后读取。
-- 检索文本是去掉客户端噪声后的用户消息,最多取**检索文本长度**(8,000)个字符。少于 3 个字符的消息不检索。
-- 每条消息最多补充**单条消息预算**和**单个上下文窗口预算**剩余额度中较小的那个;剩余额度不足 64 token 时跳过检索。无论网关还是客户端压缩了对话,单个上下文窗口预算都重新计算。预算设为 0 就等于关闭召回。这里的 token 数是偏保守的估算,不是服务商的计费数。
-- OpenViking 在**超时时间**内没有返回时,这条消息不带记忆发给模型,之后也不补,客户端重试也一样。
-- **按分类限量**(在“高级设置”中)可以给事件、实体、偏好、经验、资源和技能六类分别设条数上限,只检索上限大于 0 的类别。关闭时,所有来源放在一起排序。
-
-**召回摘要。** 开启**显示召回摘要**(默认关闭)后,每条新用户消息的回复以一段简短摘要开头,说明网关补充了什么:
-
-```text
-> OpenViking context: user profile, memory index, skill list, earlier sessions
-> OpenViking recall: 4 items (3 memories, 1 resource) — booking_duplicate_handling, user_lang_pref, +2 more
-```
+1. 运行 `openviking-gateway init`。它依次询问 OpenViking 地址(会实际访问一次,并显示服务端的认证模式和版本)、监听地址(默认 `127.0.0.1:1935`),以及是否要求[管理密钥](#gateway-management-key)。结果写入 `~/.openviking/gateway.conf`,或者 `--config` 指定的文件,只有你自己能读:
-- `context` 行只出现在对话的第一条回复里,列出开头实际提供的内容:用户画像、记忆目录、技能目录,以及这段对话较早部分在 OpenViking 中的位置。
-- `recall` 行按类别统计召回条数,最多列出三个条目名。检索失败时改为说明原因,例如 `> OpenViking recall failed: OpenViking unavailable`。没有找到内容、召回已关闭或预算用完时不显示,所以第一条回复之后,这类消息没有摘要。
-- 工具步骤等后续请求不显示摘要;客户端重试同一条消息时,摘要和第一次相同。
-- 摘要在 Anthropic Messages 中单独占一个文本块,在 Responses 中单独占一条助手消息,在 Chat Completions 中位于回复文本开头。要求结构化输出的请求,以及 `n` 大于 1 的 Chat Completions 请求,不显示摘要。
-- 模型看不到摘要:客户端随下一条消息把回复发回来时,网关先删掉摘要再转发,也不把它保存到 OpenViking。
+ ```json
+ {
+ "openviking_url": "https://ov.example.com",
+ "host": "127.0.0.1",
+ "port": 1935
+ }
+ ```
-**保存的细节:**
+2. 运行 `openviking-gateway`。它先完成[启动检查](#startup-checks),然后在你选的地址上监听。
+3. 打开网关的 `/studio/`,用 OpenViking 用户、账号管理员或 root 的 API 密钥登录。应看到网关页面,以及显示网关所连 OpenViking 地址的连接页。
+4. 手动添加上游。独立网关读不到远端服务的 VLM 配置,所以不能导入模型配置。
-- 下一条用户消息到达时,上一轮就会保存。**最新回复等待时长**决定网关等多久之后保存最后一轮并提交会话,这样短对话也能被提交。
-- **提交阈值**:会话中待提交的内容达到这么多 token 时提交一次。每次提交后,OpenViking 在后台提取记忆。
-- **保留最近消息**:提交后,会话中保留最新的若干完整轮次,至少包含这么多条消息。
+之后想修改设置,再运行一次 `openviking-gateway init` 即可:它把当前值作为默认值,已有的密钥不改就原样保留。
-每项设置的 API 名称和取值范围见[配置参考](#配置参考)。
+### 设置从哪里来 {#standalone-config-sources}
-### 网关密钥
+命令行只有 `--config` 一个参数。设置了 `--config` 或 `OPENVIKING_GATEWAY_CONFIG_FILE` 时,它必须指向已存在的文件;两者都没设置时,网关读取 `~/.openviking/gateway.conf` 和 `/etc/openviking/gateway.conf` 中第一个存在的文件。环境变量可以覆盖其中任何字段,所以容器里可以完全不用文件:设置 `OPENVIKING_GATEWAY_OPENVIKING_URL`,再按需加上 `OPENVIKING_GATEWAY_HOST=0.0.0.0` 之类的变量。
-网关密钥(`ovgw_…`)是客户端用来代替服务商 API Key 的凭证。每把密钥属于一位 OpenViking 用户,使用一份上下文配置和一组上游。
+两处都没有 OpenViking 地址时,网关退出,并提示运行 `openviking-gateway init` 或设置 `OPENVIKING_GATEWAY_OPENVIKING_URL`。全部字段和覆盖规则见[配置参考](../gateway/13-configuration.md#configuration-reference)。
-在“密钥”标签页点**签发密钥**,依次填写:
+### 启动检查 {#startup-checks}
-- **名称**:方便日后辨认,例如“alice · Claude Code”。
-- **给谁用**:普通用户只能给自己签发;账号管理员可以选本账号的用户;root 先在侧边栏切换账号。网关会从 OpenViking 读取所选用户的 API 密钥;OpenViking 只保存密钥哈希时读不出来,Studio 会显示**粘贴用户 API 密钥**输入框,填入该用户当前的密钥。root API 密钥不能绑定到网关密钥。本地 dev 模式下,密钥以 `default` 用户的身份读写记忆。
-- **上下文配置**。
-- **上游**:至少一个,密钥只能访问选中的上游。
-- **允许的模型**(可选):留空表示允许这些上游的全部模型。这里填客户端发送的名称,包括别名。请求其他模型返回 403 "Model is not allowed by this key",模型列表也只显示允许的名称。
+独立网关启动前会先访问一次 OpenViking:
-签发前,网关会向 OpenViking 核实这位用户的密钥。粘贴的是 root 密钥、其他账号的密钥或无效密钥,或者 OpenViking 连不上时,签发失败,见[签发密钥失败](#签发密钥失败)。
-
-签发成功后,**复制网关密钥**对话框显示完整密钥,这是唯一一次:网关只保存它的哈希和开头几个字符。对话框里还有 Claude Code、Codex CLI 和聊天客户端的配置,已填好真实密钥和网关地址,可以直接粘贴。密钥丢了就重新签发。
-
-- **密钥不能编辑。** 要更换上下文配置、上游、允许的模型或用户,就签发新密钥,再吊销旧的。
-- **对话属于用户,不属于密钥。** 客户端发送相同的会话 ID 时,同一用户的新密钥会接着原来的对话,换密钥不会打断对话。
-- **吊销**后,这把密钥立即不能再用;用户的对话状态和日志保留,直到被显式删除或过期。
-- **OpenViking 密钥变了。** 用户的 OpenViking API 密钥重新生成或用户被删除后,OpenViking 会拒绝网关保存的旧密钥。网关在随后的请求中发现这一点(最多延迟约 30 秒),删除绑定它的网关密钥,对话状态和日志保留。请用当前的 OpenViking 密钥重新签发。OpenViking 暂时连不上或出错时,网关不删除密钥,请求照常发给模型,只是不带记忆。
-- **每人一把密钥。** 共用一把密钥的人共享其 OpenViking 用户的记忆。请给每人签发一把;想让不同客户端使用不同的上下文配置,再按客户端分开签发。
-
-账号管理员和 root 可以在密钥页使用**删除该用户的网关数据…**:吊销该用户的全部网关密钥,删除网关为该用户保存的对话状态(包括尚未保存到 OpenViking 的内容)和请求日志。已存入 OpenViking 的记忆不受影响,见[安全与数据](#安全与数据)。
-
-### 请求日志和概览
-
-普通用户只看到自己的请求,账号管理员和 root 看到整个账号的请求。
-
-**概览**标签页汇总日志保留期(默认 30 天)内最新的 10,000 条请求:
-
-- 第一个请求到达之前,显示**快速开始**清单,顺序是“上游 → 上下文配置 → 签发密钥 → 接入”。还没有密钥时,清单里的**快速模式**卡片一键完成前三步:没有可用上游时导入 OpenViking 的 VLM 配置,没有上下文配置时用推荐设置新建一份,再为当前用户签发密钥。本地 dev 模式以外,root 改为在签发对话框里选择密钥归属的用户。
-- **请求数**:模型请求的数量、最近一次请求的时间,以及这些请求的输出 token。
-- **首次调用缓存命中率**:每条新用户消息的第一次模型调用中,命中服务商提示缓存的输入 token 所占比例。这是判断网关是否健康最重要的指标,应该接近不经过网关时服务商能达到的水平;明显下降通常说明网关发送的历史和上一次对不上了,见[首次调用缓存命中率下降](#首次调用缓存命中率下降)。
-- **轮内缓存命中率**:同一轮里后续调用的命中率,例如工具步骤和 OpenViking 工具的往返,通常很高。
-- **召回的记忆条数**:补充到新消息中的条数,以及每次检索 OpenViking 的平均耗时(只统计实际检索了的消息)。
-- **长对话没有命中缓存**:某段对话最近连续 3 次模型调用的输入都不少于 32,000 token、相邻两次相隔不到 5 分钟,服务商返回的缓存命中却都是 0 时出现警告,列出模型、上游和连续次数;如果都是 Anthropic 对话、上游也从没写入缓存,建议改为检查客户端是否设置了 `cache_control`。压缩、开启新窗口、切换模型或上游,以及网关工具时有时无的请求不计入。某个上游最近从没返回过缓存命中时,改为一条提示,说明经过它的长对话缓存命中率一直是 0%。见[首次调用缓存命中率下降](#首次调用缓存命中率下降)。
-- **OpenViking**:已连接、异常或启动中,附带版本;异常时给出原因。OpenViking 连不上期间,请求照常发给模型,只是不带记忆。卡片中的**保存对话**一栏统计正在重试或已暂停保存的对话数。
-- **降级请求**:每种异常出现的次数和说明,见[降级请求的异常](#降级请求的异常)。
-- **最近请求**,以及前往“请求日志”标签页的链接。
-
-**请求日志**标签页按时间倒序列出最新的 1,000 条记录,停留在第一页时每 30 秒刷新一次。可以按**全部**、**新消息**、**工具步骤**或**异常**筛选,也可以按请求类型筛选,或者按模型、对话或密钥搜索。
-
-各列依次是类型、模型(客户端发送的名称)、服务商返回的 HTTP 状态、token(输入、缓存占比、输出)、**记忆**、**保存**状态和**异常**。**记忆**列中,`+3` 表示这次检索补充了 3 条,并附检索耗时;`↺ 4` 表示之前 4 条消息补充的记忆被原样放回。展开一行可以看到对话 ID、上游、密钥、耗时、token 明细、记忆检索结果、上下文窗口用量(以及是否压缩或开启了新窗口)、保存状态和下次重试时间、OpenViking 工具详情;有异常的请求还会说明发生了什么、怎么处理。
-
-只有到达模型服务商的请求才会记录。被网关先行拒绝的请求不记录,例如密钥无效、模型不在允许范围内、没有匹配的上游、请求体超限,这些情况下客户端直接收到错误。
-
-| 类型 | 含义 | 记忆 |
-| --- | --- | --- |
-| 新消息 | 最后一条是新用户消息的请求 | 检索一次,并放回之前的记忆;这一轮会被保存 |
-| 工具步骤 | 同一轮的延续,例如带着工具结果继续 | 放回之前的记忆;随所在轮次一起保存 |
-| 辅助请求 | 生成标题、摘要、压缩、建议和权限检查的请求 | 放回之前的记忆;从不保存 |
-| 子 Agent | 客户端的子 Agent 发出的请求 | 放回之前的记忆;从不保存 |
-| Token 计数 | token 计数请求(`/gateway/v1/messages/count_tokens`) | 放回之前的记忆,计数才和实际发送的内容一致 |
-| 直接转发 | 原样转发、不带记忆的请求:其他接口、依赖服务商端状态的 Responses 请求、压缩过或无法解析的请求体 | 无 |
-| 记忆同步 | 后台保存事件,不是模型请求 | — |
-
-**保存**列显示每段对话的保存状态:
-
-- **正常**:保存正常进行。
-- **已关闭**:这段对话的上下文配置不保存对话。
-- **重试中**:OpenViking 拒绝了保存或无法访问。网关在 10、20、40、80 秒后依次重试。
-- **已暂停**:连续失败 5 次。网关之后每 5 分钟重试一次,直到成功;未保存的轮次一直保留,直到保存成功或对话过期。
-- **已暂停**,原因为 `gateway_key_revoked`:这段对话的网关密钥已被吊销或删除,网关不再重试。用户之后用有效密钥在这段对话里发请求时,保存自动恢复。
-
-展开的行会显示原因,例如 OpenViking 拒绝了密钥(`openviking_http_401`,即用户的 OpenViking 密钥已失效),或者 OpenViking 无法访问(`openviking_unavailable`)。对话历史有改动(`history_changed`)是正常的:客户端编辑、重新生成或压缩了对话,网关用当前历史在新的 OpenViking 会话中继续保存。
-
-展开行中的**重新同步对话…**为这段对话新建一个 OpenViking 会话,用户下次发消息时,网关把完整历史写进去。已经保存的内容留在旧会话里,所以部分记忆可能被提取两次。原因已经修复、对话却仍然暂停,或者想要一份干净的对话副本时,可以用它。下一条消息到达之前什么都不会发生。重新同步需要记录上显示的那把密钥;它已被吊销时,请选同一段对话里更新的一条记录。
+- OpenViking 使用 trusted 认证时,网关拒绝启动。
+- 绑定非回环地址时,必须确认 OpenViking 使用 `api_key` 认证才会启动;OpenViking 连不上或处于本地 dev 模式时,网关直接退出。请先启动 OpenViking,或者只绑定 `127.0.0.1`。
+- 跨主机连接 OpenViking 时,请使用 TLS 或私有网络。
-## OpenViking 工具
+### 连接公共 OpenViking 服务 {#public-openviking-service}
-开启 OpenViking 工具后,模型能在回答过程中使用 OpenViking 服务提供的工具,范围受该用户自己的 OpenViking 权限限制。调用由网关执行,客户端持续收到回答直到本次回复结束,显示的 token 用量包含期间所有模型调用。这项功能对各类客户端意味着什么、用户在回复里看到什么,见[让任意客户端拥有 Agentic 记忆](15-gateway.md#让任意客户端拥有-agentic-记忆);本节说明客户端要求、设置和上限。
+独立网关连接公共 OpenViking 服务 `https://api.vikingdb.cn-beijing.volces.com/openviking`、又没有设置管理密钥时,会对该服务的所有用户开放。启动日志会显示 `public_openviking_without_management_key` 告警,Studio 会显示**这台网关对所有 OpenViking 商业版用户开放**:任何持有该服务 API 密钥的人都能登录这台网关,并修改所在账号的上游。
-这项功能面向接不了 OpenViking MCP 服务器的聊天应用和 API 应用。Claude Code、Codex 这类支持 MCP 或有插件的客户端,用 MCP 或插件更合适,因为它们会显示每次工具调用和结果,并在调用前请求确认。
+网关只给你自己或团队使用时,设置 `OPENVIKING_GATEWAY_MANAGEMENT_KEY` 后重启即可限制修改。这不限制谁能登录,也不限制他们给自己签发网关密钥。
-### 客户端要求
+## 路由 {#routes}
-三种协议都支持流式和非流式请求:
+两种部署方式下,网关的所有 URL 都在 `/gateway` 下。嵌入部署中,Server 把整个 `/gateway` 前缀交给网关,其他路径仍由 Server 自己处理:
-| 协议 | 客户端要求 |
+| 路径前缀 | 用途 |
| --- | --- |
-| Chat Completions | 回传完整的 `messages` 历史。 |
-| Responses | 使用 `store: false` 和完整的 `input` 历史;下一轮回传本轮返回的全部 `output` 内容,包括 reasoning 和客户端工具调用。带 `previous_response_id`、`conversation` 或 `background` 的请求照常转发,不提供网关工具;`item_reference` 无法还原完整历史。 |
-| Anthropic Messages | 回传完整的 `messages` 历史,保留 thinking 和 signature 块。token 计数请求带相同的工具定义,但不执行工具。 |
-
-模型在同一条回复中同时调用 OpenViking 工具和客户端工具时,网关处理 OpenViking 调用,客户端照常执行自己的工具并回传结果。Responses 支持客户端的 function 和 custom 工具,Anthropic Messages 支持客户端的 tool_use 调用。
-
-### 选择工具
-
-新建的上下文配置默认开启 **OpenViking 工具**,“使用推荐设置创建”也一样。**工具**清单来自你的 OpenViking 服务,默认只勾选只读工具:
-
-- **默认勾选**:`find`、`search`、`grep`、`glob`、`list`、`tree`、`read`、`download`、`list_watches`、`get_acl`、`list_users`、`list_groups` 和 `health`。
-- **默认不勾选**(会修改数据):`remember`、`write`、`edit`、`add_resource`、`add_skill`、`forget`、`set_acl` 和 `cancel_watch`。想让模型保存记忆就勾选 `remember`,想让它导入网页或附件就勾选 `add_resource`。
-
-`download` 返回一条一次性的 `curl` 命令,所以客户端需要有 shell 工具(哪些名称算 shell 工具见[导入文件和技能](#导入文件和技能))。和上传链接一样,下载链接默认经过网关,指向 `public_url` 加 `/gateway/downloads`。把 `mcp_file_links` 设为 `direct` 后,网关原样透传 OpenViking 返回的上传和下载链接,链接直接指向 Server,此时 Server 的 `OPENVIKING_PUBLIC_BASE_URL`(或 `server.public_base_url`)必须是客户端能访问的地址。
-
-OpenViking 以后新增的工具会默认可用,已有对话仍沿用开始时的工具清单。已有的上下文配置保留原来的勾选。
-
-每个上游的**允许 OpenViking 工具**默认开启。两个开关都开启时,新对话获得选中的工具,名称加上 `openviking_` 前缀,例如 `openviking_find`、`openviking_read`。Studio 会说明每个工具的用途;只有 OpenViking 提供了相应信息时,才显示只读标记。工具定义随对话中的每个请求发送,全部工具约占 3,500 个输入 token,所以取消用不到的工具也能省 token。
-
-> **注意**:选中的工具直接执行,不经过客户端的权限确认,写入和删除数据的工具也一样。勾选会修改数据的工具前,先确认能接受这一点;给聊天应用用的配置,建议不勾选 `forget` 和 `set_acl`。调用提示只说明已经发生的操作,不是权限确认。
-
-### 工具调用提示
-
-开启**显示工具调用**(默认开启)时,网关每执行一次 OpenViking 工具调用,就在回复中调用发生的位置加一行提示:
-
-```text
-> OpenViking find: "release date" — done
-```
-
-- 提示写明工具名;能识别调用对象时,还显示检索的查询词,读取、列出或写入的 URI,或者正在导入的文件或技能。
-- 流式回复中,调用一开始提示就出现,导入这类耗时的调用进行时,用户也能看到网关在工作;非流式回复在最终消息里带上同样的提示。
-- 调用结束后补上结果:`done` 表示完成,`failed` 表示调用返回了错误,`skipped` 表示网关拒绝了这次调用、没有执行,例如工具轮数或 token 预算已经用完。
-- 每条提示单独成段。在 Chat Completions 中,提示是回复文本的一部分;在 Anthropic Messages 中,同一轮调用的提示放在同一个文本块里;在 Responses 中,放在同一条助手消息里。
-- 模型看不到这些提示,它收到的是真实的调用和结果;网关也不把提示保存到 OpenViking。
-
-要隐藏提示,在上下文配置的 **OpenViking 工具**部分关闭**显示工具调用**。和其他工具设置一样,改动只影响新对话。
-
-### 什么时候不提供工具
-
-对话是否带工具,由它第一个能用工具的请求决定(生成标题这类辅助请求不算),之后保持不变,所以修改上下文配置只影响新对话。唯一的例外是关闭:模型还没调用过网关工具时,客户端出现了自己的 OpenViking 工具,例如 MCP 服务器在第一轮之后才连上。
-
-辅助请求、子 Agent 请求和检测到 OpenViking 插件的对话都不带 OpenViking 工具。这类请求如果回传了模型用过这些工具的历史,网关仍附上工具定义,让这段历史保持有效,但拒绝新的 OpenViking 调用。客户端自己的工具在每个请求里都照常可用。
+| `/gateway/v1/` | 模型 API 和模型列表 |
+| `/gateway/api/v3/` | 方舟兼容客户端 |
+| `/gateway/api/compatible/v1/` | 方舟 Anthropic 兼容客户端 |
+| `/gateway/uploads` | 工具上传 |
+| `/gateway/downloads` | 工具下载 |
+| `/gateway/admin/` | 管理 API,需要认证 |
-请求没有带工具时,请求日志的详情会说明原因:
+因此客户端使用下面的 Base URL,把 `http://127.0.0.1:1933` 换成你的 Server 地址即可。各客户端的具体设置见[把客户端接入 OpenViking 网关](../gateway/03-connect-clients.md#connect-clients)。
-| 原因 | 说明 |
+| 客户端 | Base URL |
| --- | --- |
-| `tools_require_full_history` | Responses 请求需要 `store: false` 和完整 input 历史,不能使用 `item_reference`。 |
-| `upstream_tools_disabled` | 上游关闭了**允许 OpenViking 工具**。 |
-| `tools_multiple_choices` | 请求要求返回多个候选(`n` 大于 1)。 |
-| `tools_structured_output` | 请求要求结构化输出(`response_format`、`text.format` 或 `output_config.format`)。 |
-| `tools_non_function` | Chat Completions 客户端传入了 function 以外类型的工具。 |
-| `tools_forced_choice` | `tool_choice` 为 `required`,或者指定了某个工具。 |
-| `deepseek_reasoning_history_required` | 上游是 DeepSeek,请求没有关闭思考模式(`"thinking": {"type": "disabled"}`),而之前的回复发到上游时会缺推理内容:关闭了**补全推理内容回传**,或者这个请求补不回推理内容(对话换了上游、丢了记忆记录,或者思考内容被当作正文发回)。标准 Responses 请求没有 `thinking` 字段,按开启思考模式处理。 |
-| `tool_name_collision` | 客户端已经接了 OpenViking 工具,网关在这段对话剩下的部分不再提供自己的工具(模型已经调用过网关工具的分支除外)。判断条件见下文。 |
-| `tools_unavailable` | 无法从 OpenViking 加载工具清单,也没有之前加载成功的清单。连接恢复后开始新对话。 |
-| `tools_not_selected_at_session_start` | 上下文配置开启了工具,但这段对话的工具列表为空:配置里一个工具都没选,或者对话在网关升级前就已开始。开始新对话即可。 |
-
-满足以下任一条件,网关就认为客户端已经接了 OpenViking 工具(`tool_name_collision`):
-
-- MCP 服务名(`server_label`、`mcp_server_name`、`mcp_servers[].name`)含单词 `openviking`。
-- 以 OpenViking 工具名结尾的工具名中也含这个单词,例如 `mcp__claude_ai_OpenViking__search`;连接器的 `authenticate` 工具不算。独占一行列出的延迟加载工具名也算。
-- 带前缀、以 OpenViking 工具名结尾的工具(例如 `mcp__ov__read`),定义中出现 `viking://`。
-- 任一请求中,客户端工具和网关工具同名,因为上游会拒绝重名工具。
-
-误判同样会持续整段对话,开始新对话即可。
-
-### 导入文件和技能
-
-OpenViking 服务提供导入工具、上下文配置也勾选了它们时,模型就能导入资料。按 URL 导入不需要额外条件;导入本地文件需要以下两种方式之一:
-
-- **客户端有 shell 工具**(名称类似 bash、shell、exec_command、terminal 或 run_command):导入工具返回一个一次性上传链接,模型再用客户端的 shell 工具上传文件,这一步经过客户端的权限确认。技能目录会先打包成 zip。链接指向 `public_url` 加 `/gateway/uploads`,所以 `public_url` 必须是客户端能访问的地址,前面的代理也要像其他路径一样转发它。没有设置 `public_url` 时,导入失败并提示 "Set gateway.public_url for client uploads and downloads"。`mcp_file_links` 设为 `direct` 时,链接改为直接指向 OpenViking Server。
-- **用户消息带附件**:没有 shell 工具时,模型可以导入用户消息里附带的文件,文件可以是 base64 数据,也可以是附件文本,支持 Responses `input_file` 和 Anthropic `document.source` 中内嵌的 `base64`、`text` 数据。Open WebUI 通常只发送提取出的文本,这些文本作为文本文件导入。附件中的 URL 和服务商的文件 ID 不会被抓取;要导入远程资源,请用导入工具的 URL 参数。
-
-上传大小受 `max_body_bytes` 限制(默认 32 MiB)。
-
-### 上限
-
-上下文配置中 **OpenViking 工具**部分的**高级设置**里有以下上限:
-
-| 设置 | API 名称 | 默认值 | 范围 | 达到上限时 |
-| --- | --- | --- | --- | --- |
-| 每次请求的工具轮数 | `tool_max_rounds` | 不限 | 1 及以上 | 拒绝之后的 OpenViking 调用,模型用已有结果和客户端自己的工具继续。 |
-| 单次调用超时 | `tool_timeout_seconds` | 30 秒 | 最多 120 秒 | 这次调用向模型返回错误。 |
-| 结果大小上限 | `tool_result_bytes` | 65,536 字节 | 1,024–1,048,576 | 结果被截断。 |
-| 总时长 | `tool_total_seconds` | 不限 | 大于 0 秒 | 请求失败,返回 504 "Hidden tool request timed out"。 |
-| Token 预算 | `tool_total_tokens` | 不限 | 1,024 及以上 | 拒绝之后的 OpenViking 调用,模型用已有结果和客户端自己的工具继续。这不是计费上限,最终回答可能超出它。 |
-
-轮数、总时长和 Token 预算默认都不限,和 Agent 自己的工具循环一样,模型会一直使用 OpenViking 工具直到完成。流式请求中,用户可以随时中断回复,客户端断开后网关也会停止。**非流式请求在客户端断开后仍会继续执行,所以客户端发送非流式请求时,请设置总时长。**字段留空表示不限。这几项默认值改为“不限”之前保存的上下文配置仍保留原来的值(5 轮、120 秒、100,000 token),清空即可取消限制。
-
-Token 预算只计算模型使用 OpenViking 工具时新增的调用、结果和后续生成内容,客户端已有的对话、工具定义和图片不计入。网关保留客户端设置的回答长度上限(`max_tokens`、`max_completion_tokens` 或 `max_output_tokens`)。
-
-### 失败处理
-
-- **单次调用失败**:模型收到错误结果,可以据此继续回答。
-- **整个回答失败**:例如服务商拒绝了后续的模型请求,或者 OpenViking 调用被拒绝后模型仍坚持调用。客户端收到错误,请求日志显示 **OpenViking 工具调用失败**(`hidden_tool_loop_failed`)。流式 Responses 请求以 `response.failed` 事件结束;Chat Completions 和 Anthropic Messages 返回 `gateway_tool_error` 错误。
-- **某个上游反复失败**:关闭它的**允许 OpenViking 工具**。用过这些工具的 Claude 对话可能随之出现**工具历史无法继续使用**(`hidden_tool_history_unavailable`):之前的思考内容无法继续使用,网关已将其去掉。可以按请求详情中的停用原因恢复设置,或者开始新对话。
-- **重试**:重试的工具调用复用第一次调用的结果,中断的写入操作不会自动重做。
-
-## 长对话
-
-模型的上下文窗口限制了一段对话的长度。开启**压缩**(默认开启)后,网关会在对话撑满窗口之前,把较早的部分换成一份摘要。
-
-**何时压缩。** 每收到一条新的用户消息或一个工具步骤,网关都估算一次窗口用量:取服务商为这段对话上一次回复报告的 token 用量,加上之后新增消息的估算值。没有这份用量时(例如流式 Chat Completions 没有设置 `stream_options.include_usage`),就估算整个请求。估算值达到**压缩时机**(窗口的 0.9)时开始压缩。辅助请求、子 Agent 请求和 token 计数请求不触发压缩。
+| Claude Code 和 Anthropic SDK | `http://127.0.0.1:1933/gateway` |
+| OpenAI 兼容的客户端和 SDK,包括 Codex、OpenCode、pi 和 Open WebUI | `http://127.0.0.1:1933/gateway/v1` |
+| 火山方舟和 BytePlus 方舟 SDK | `http://127.0.0.1:1933/gateway/api/v3` |
-**窗口大小从哪来。** 网关先查上游**上下文窗口**中该模型的条目(按发给上游的模型名查找),没有时用上下文配置的**默认上下文窗口**,两者都没有时按 1,000,000 token 计算。使用窗口更小的模型时请设置其中一项,否则还没等到压缩,服务商就会以对话过长为由拒绝请求。
+`/health` 仍是 Server 自己的健康检查,嵌入网关不单独提供 `/health`。独立网关在自己的端口上提供同样的 `/gateway` 路径,另外在根路径提供两个地址:
-**摘要怎么生成。** 网关向同一个上游、同一个模型额外发一次非流式请求,客户端的系统提示词、工具和思考设置保持不变,所以大部分内容能命中服务商的提示缓存。纯文本摘要做不到的设置会被去掉:强制的工具选择改为不调用工具,结构化输出格式和停止序列也不保留。这次请求包含压缩位置之前的对话,以及一条让模型为自己写摘要的指令,摘要要覆盖:
+- `/` 跳转到 `/studio/`,Studio 只包含网关和连接页面。
+- `/health` 返回 `service: "openviking-gateway"`、`auth_mode` 和 `openviking_url`;请求带有效的 OpenViking 凭证时,还返回调用方身份。
-- 用户的目标和最新请求的原文;
-- 关键决定和当前进度;
-- 文件、路径和标识符;
-- 出过的错误和修正;
-- 未完成的事项;
-- 最近几次工具结果里的要点。
+### 对外地址 {#public-address}
-之前的摘要会并入新摘要。摘要是纯文本,最长**摘要长度上限**(8,000)个 token。思考内容也计入输出上限,而有些模型(如 DeepSeek V4.1)即使请求里没有思考设置也会默认思考,所以网关总在摘要长度上限之外再留 16,000 token 的输出余量;客户端手动指定了思考预算时,改为加上这份预算。这次请求和其他请求一样由服务商计费。
+对外地址 `public_url` 是客户端访问 Server(或独立网关)时使用的地址,不带 `/gateway`,网关会自己加上。它默认为空,此时嵌入网关沿用 Server 的对外地址(`OPENVIKING_PUBLIC_BASE_URL` 或 `server.public_base_url`)。共享部署都应设置它,前面有反向代理时更是必须设置:
-**压缩之后模型收到什么。** 压缩位置取决于请求类型:
+- **嵌入**:在 `ov.conf` 中设置 `gateway.public_url`,然后重启服务。
+- **独立**:设置 `gateway.conf` 中的 `public_url` 或环境变量 `OPENVIKING_GATEWAY_PUBLIC_URL`,然后重启网关。
-- 新的用户消息:压缩位置就在这条消息之前。模型收到 system 和 developer 消息、作为一条用户消息的摘要,以及这条新消息。
-- 工具步骤:压缩位置在最近一次工具结果之后,模型从摘要出发继续完成任务。
+有两样东西依赖它:
-摘要消息开头说明网关替换了对话较早的部分、这段内容不是用户写的;结尾附上这段对话开头的网关说明和用户画像,压缩后它们仍然保留。之后凡是重发这段历史的请求,包括辅助请求和 token 计数请求,都做同样的替换;子 Agent 通常发送自己单独的历史,不受影响。每次压缩让服务商缓存在压缩位置失效一次,之后照常命中。
+- **Studio 的接入指南**:Anthropic 客户端使用 `<public_url>/gateway`,OpenAI 风格的客户端使用 `<public_url>/gateway/v1`。
+- **OpenViking 工具的上传和下载链接**,除非 `mcp_file_links` 设为 `direct`,见[导入文件和技能](../gateway/04-openviking-tools.md#import-files-and-skills)。
-**压缩位置之前的原文一概不保留**,最近几轮也一样。模型之前的回复和其中的思考内容都依赖被替换掉的历史,只保留一部分会破坏 Claude 的思考签名。压缩位置之后生成的内容照常发送,包括思考内容。
+一个对外地址都没有设置时,指南用的是请求到达服务器时的协议和主机。经过反向代理时,这可能是内部地址或 `http://` 地址,**接入**标签页会提示**客户端可能连不上这个地址**;如果是 `127.0.0.1` 这类回环地址,则提示**只有网关所在的机器能使用这个地址**。
-**查找被压缩的内容。** 对话本身仍保存在 OpenViking 里。开启了**保存对话**、这段对话也提供了 `openviking_grep` 和 `openviking_read` 工具时,摘要后面会附上查找方法:这段对话对应的 OpenViking 会话(`viking://user/<user_id>/sessions/<session_id>/`)、会话中消息的存放位置,以及检索步骤:先用具体关键词 grep 会话拿到行号,再读取匹配位置前后的内容。压缩发生在一轮中间时,压缩位置之前的部分会立即保存到 OpenViking,模型在这一轮里就能检索到。
+## 反向代理和 HTTPS {#reverse-proxy-and-https}
-**压缩失败时。** 摘要请求失败,或者回复里调用了工具、内容为空、因长度上限被截断时,网关改为发送完整历史,并在 60 秒内不再为这段对话尝试压缩。请求详情会显示**压缩失败**及原因。如果摘要写完后用量仍达到**压缩时机**(例如系统提示词和工具本身就占了窗口的大部分),网关保留这份摘要,同样 60 秒后再尝试,原因显示为 `still_over_threshold`。
+把整个站点转发到 Server(嵌入)或网关(独立),不需要按路径分流。以 Caddy 为例:
-**不再生成 Working Memory 摘要。** 摘要由对话所用的模型生成,不使用 OpenViking 的会话摘要。网关新建的 OpenViking 会话都关闭了 Working Memory:提交时照常归档消息、提取记忆,只是不生成会话摘要。
+```caddyfile
+ov.example.com {
+ reverse_proxy 127.0.0.1:1933 {
+ flush_interval -1
+ }
+}
+```
-**记忆预算重新计算。** 每压缩一次,**单个上下文窗口预算**就重新计算,压缩位置之前补充过的记忆可能再次补充。
+无论用哪种代理,都要满足下面几项:
-**客户端仍发送完整历史。** 网关压缩后,客户端还是发送完整历史,网关在每个请求里替换压缩位置之前的部分。客户端看到的用量很小,按用量决定何时压缩的客户端很少再自己压缩,所以特别长的会话最终可能超过 `max_body_bytes`。客户端压缩或编辑历史后,网关把新历史保存到新的 OpenViking 会话;检索工具可用时,新历史开头的网关说明会告诉模型之前的会话在哪里。
+| 设置 | 取值 | 原因 |
+| --- | --- | --- |
+| 响应缓冲 | 关闭 | 流式输出才能实时到达 |
+| 请求体大小 | 至少 32 MiB | 这是网关自身对请求和上传的默认上限;长对话每次都发送完整历史(见[副作用](../gateway/05-long-conversations.md#side-effects)) |
+| 读取超时 | 至少 600 秒 | 网关默认最多等待服务商 600 秒 |
+| `/gateway/uploads` 和 `/gateway/downloads` 的日志 | 不记录查询字符串 | 其中带有一次性令牌 |
-请求日志中每条请求的详情会显示上下文窗口用量、较早的历史是否被替换,以及新摘要的大小和耗时。
+对外发布前,先配置好认证和[对外地址](#public-address),见[公网访问](12-public-access.md)。
-### 实验性:Agent 自管上下文窗口
+## 密钥和凭证 {#keys-and-credentials}
-开启 **Agent 自管上下文窗口**(默认关闭)后,由模型自己决定何时开启新的上下文窗口,并自己写交接笔记,不必等网关生成摘要。这项设置只对能使用 [OpenViking 工具](#openviking-工具)的对话生效,其他对话照常压缩。开启压缩时,如果模型一直不开新窗口,压缩仍会兜底。
+网关涉及四种密钥,各管一件事:
-模型会看到:
+| 密钥 | 用途 | 在哪里使用 |
+| --- | --- | --- |
+| OpenViking API 密钥 | 登录 Studio;决定以哪个账号、哪个用户的身份读写记忆 | 管理请求的 `X-API-Key` 或 `Authorization: Bearer` |
+| 网关密钥(`ovgw_…`) | 客户端接入;每把绑定一位用户、一份上下文配置和一组上游(见[网关密钥](../gateway/09-gateway-keys.md#gateway-keys)) | 客户端的 API Key 输入框 |
+| 网关管理密钥(可选) | 限制谁能修改上游和上下文配置 | `gateway.management_key`;请求头 `X-OpenViking-Gateway-Management-Key` |
+| 上游 API Key | 调用模型服务商(见[凭证](../gateway/07-upstreams.md#credentials)) | 上游编辑页 |
-- **两个额外的工具**。它们不在上下文配置的**工具**清单里,只由这项设置控制:
- - `openviking_new_context(reason, notes, next_steps)`:开启新窗口,`next_steps` 可省略。它必须在一轮里单独调用;和其他工具同一轮调用时,这一轮的每个调用都返回错误,窗口不重置。网关在本次请求里已经在同一位置替换过上下文(例如刚压缩过)时,它同样返回错误。
- - `openviking_context_remaining()`:返回窗口序号、已用和剩余 token 的估算值、本窗口内的用户轮数、距用户上一条消息的时间,以及一句建议。
-- **开头的网关说明里多一行**,告诉模型它用这两个工具自己管理上下文窗口。
-- **一行状态**:每条新的用户消息之后,记忆块末尾附上 `[context-status] window wN · ~X/Y tokens (P%) · T since your previous message`。
-- **两级提醒**:窗口用到**软提醒时机**(0.7)时,网关提醒一次,要求模型做完当前这一步就开启新窗口,并在交接笔记里记下之后要用的确切路径、行号和取值。用到**硬提醒时机**(0.85)时,要求模型立即开启新窗口,此后每一步都重复,直到模型开启新窗口或压缩接手。提醒附在新的用户消息上,工具步骤里则附在工具结果上。
+网关没有自己的加密密钥,本地存储按 OpenViking 的加密配置加密,见[加密](#encryption)。
-模型调用 `openviking_new_context` 后,网关把目前为止的对话换成一个窗口头,模型在同一条回复里接着工作。窗口头依次包含:这是模型开启的第 N 个窗口、内容不是用户写的;reason、notes 和 next_steps;用户最新一条消息的原文;检索之前窗口的方法(条件和压缩时相同);这段对话开头的网关说明。之后的请求会根据客户端的历史重建同一个窗口。重置之前的内容会立即保存到 OpenViking,之后仍可检索;reason 和 notes 只出现在窗口头里,不保存到 OpenViking。每次重置让服务商缓存失效一次,但不需要摘要请求。
+### 网关管理密钥 {#gateway-management-key}
-请求日志中每条请求的详情会显示窗口序号、模型是否开启了新窗口,以及收到了哪种提醒。效果取决于所用的模型,后续版本中的行为也可能调整。
+网关管理密钥是一项可选的部署密钥,用来限制谁能修改[上游和上下文配置](15-gateway.md#key-terms)。它默认不设置,此时账号内每个登录的用户都能添加和修改本账号的上游和上下文配置。设置之后,只有带上这把密钥的请求能修改它们,账号管理员和 root 也不例外。它不限制谁能登录,也不限制用户给自己签发网关密钥。
-## 安全与数据
+只读用户在 Studio 里还能看到什么、做什么,见[谁能修改什么](../gateway/06-manage-in-studio.md#who-can-change-what);包括管理 API 在内的完整规则见[权限矩阵](../api/25-gateway.md#credentials-and-account-scope)。
-**按用户隔离。** 每把网关密钥绑定一位 OpenViking 用户。网关用这位用户自己的 OpenViking 密钥检索记忆、保存对话和调用工具,所以能做的事不会超出用户本人的权限;各用户的对话状态互相隔离。会话和记忆的正本始终在 OpenViking,网关只保存让对话继续所需的状态。
+**像部署密钥一样保管它。** 管理密钥本身就能当凭证用,不需要 OpenViking API 密钥:带上 `account_id`,它可以查看、创建、修改和删除任意账号的上游和上下文配置,包括把上游指向另一个服务商地址。但它读不了记忆和日志,也不能签发网关密钥。只把它交给维护上游的人。
-**网关存储什么。** `storage_path` 下有两个 SQLite 数据库,文件只有运行网关的系统用户能读取;开启[加密](#加密)后,存储的每个值也都会加密:
+设置方法:
-- `management.sqlite3`:上游、上下文配置、网关密钥、请求日志,以及每个 Responses 响应由哪个上游创建。其中包括上游 API Key、请求头的值,以及网关密钥绑定的 OpenViking 密钥,加密关闭时它们以明文存储;网关密钥本身只存哈希和一段短前缀。
-- `kernel.sqlite3`:每段对话的状态,包括补充到消息中的记忆原文(原样放回需要它)、OpenViking 工具的往返记录、摘要,以及等待保存的对话文本。
+- **`openviking-server init`**(嵌入):远程部署回答 **Allow users to configure their own gateway upstreams?** 时选 no,init 会生成一个以 `ovgm_` 开头的值,打印出来并写入 `ov.conf` 的 `gateway.management_key`。
+- **`openviking-gateway init`**(独立):回答 **Require a management key to change upstreams and profiles?** 时选 yes,init 会生成一个 `ovgm_` 开头的值,只打印一次,并写入 `gateway.conf` 的 `management_key`。
+- **Studio**(嵌入,root):点**开启网关**后弹出的确认对话框里有一个复选框**只有持有网关管理密钥的人才能修改上游和上下文配置**,默认不勾选。勾选后,Studio 会生成一个 `ovgm_` 开头的值,写入 `ov.conf` 的 `gateway.management_key`(同时写入 `gateway.enabled: true`),并且只显示一次。
+- **手动设置**:值至少 32 个字符,可以用 `openssl rand -base64 32` 生成。写进 `management_key`,或者设置环境变量 `OPENVIKING_GATEWAY_MANAGEMENT_KEY`;两种部署下环境变量都优先于配置文件,见[配置参考](../gateway/13-configuration.md#configuration-reference)。
+- **Compose 和 Helm**:Compose 会把 `OPENVIKING_GATEWAY_MANAGEMENT_KEY` 传进容器;Helm 从 `gateway.existingSecret` 指定的 Secret 中读取 `management-key` 字段。见 [Docker Compose](#docker-compose) 和 [Helm](#helm)。
-**请求日志记什么。** 只有元数据:请求类型、模型、状态、上游、对话 ID 的哈希、token 数、记忆条数和耗时、保存状态和异常。不记录消息文本、召回的记忆、工具参数和结果,也不记录任何密钥。网关不写 HTTP 访问日志,错误信息也不回显提交的值。
+管理密钥不提供命令行参数,因为命令行参数会出现在进程列表和 shell 历史里。设置、更换或去掉管理密钥后需要重启,这不会吊销已签发的网关密钥,也不会改动已有的上游和上下文配置。
-**服务商能看到什么。** 每个上游都收到完整的模型输入,包括网关补充的记忆和 OpenViking 工具的结果。只添加你放心交出这些数据的服务商。
+#### 忘记网关管理密钥 {#lost-the-management-key}
-**保留期限。** 清理任务每小时运行一次:
+没人记得[网关管理密钥](#gateway-management-key)时,按网关读取它的顺序查找:
-| 数据 | 保留时长 | 设置 |
-| --- | --- | --- |
-| 对话状态 | 最后一次使用后 30 天 | `session_ttl_days` |
-| 请求日志 | 30 天 | `log_retention_days` |
-| Responses 响应与上游的对应关系 | 30 天 | `response_ttl_seconds` |
-| OpenViking 中的会话和记忆 | 遵循 OpenViking 自己的规则 | — |
+1. 环境变量 `OPENVIKING_GATEWAY_MANAGEMENT_KEY`,它优先于配置文件。Compose 部署一般写在 `docker-compose.yml` 旁边的 `.env` 里;Helm 从 `gateway.existingSecret` 指定的 Secret 中读取 `management-key` 字段。
+2. 没有设置环境变量时,看 `ov.conf` 的 `gateway.management_key`(嵌入)或 `gateway.conf` 的 `management_key`(独立)。值写成 `$VAR` 时,密钥在对应的环境变量里。
-**删除数据。** 吊销网关密钥、或者它绑定的 OpenViking 密钥失效,都不会删除用户数据。要删除,有三种途径:
+嵌入部署的 root 还可以在 Studio 的**设置** → **服务端配置** → **文件编辑**中查看 `ov.conf`。`openviking-server init` 和 Studio **开启网关**生成的密钥都以明文保存在这里。
-- 账号管理员或 root 在 Studio 中用**删除该用户的网关数据…**,或者调用 `DELETE /gateway/admin/users/{user_id}/data`:吊销该用户的网关密钥,删除对话状态和日志,包括尚未保存的内容。
-- root 调用 `DELETE /gateway/admin/account/data?account_id=<account>`,清除整个账号的网关数据。
-- 嵌入部署中,在 OpenViking 里删除用户或账号时,网关自动删除对应的网关数据。独立部署没有这一步,数据保留到显式删除或过期。
+实在找不回来,就换一把新的:
-已存入 OpenViking 的记忆和会话不受这些操作影响。反过来,在 OpenViking 中删除一条记忆后,网关为进行中的对话保存的那份记忆副本仍会被原样放回,直到对话过期;要立即清除,删除该用户的网关数据。
+1. 生成一个至少 32 个字符的新值,例如用 `openssl rand -base64 32`。
+2. 写到原来的位置。把环境变量设为空字符串不会清除文件里的值,需要删掉这个变量。
+3. 重启。Compose 部署改了 `.env` 之后,要运行 `docker compose up -d` 才会生效,`docker compose restart` 读不到新值。
+4. 在 Studio 中点**输入网关管理密钥**,粘贴新值。已签发的网关密钥、上游和上下文配置都不受影响。
-**访问控制。**
+## 加密 {#encryption}
-- 客户端用网关密钥认证,放在 `Authorization: Bearer` 或 `x-api-key` 中,密钥可以随时吊销。
-- 管理密钥只控制上游和上下文配置的修改,不授予读取记忆、日志或签发密钥的权限,见[权限矩阵](../api/25-gateway.md#凭证和账号范围)。
-- 账号管理员能给本账号的任何用户签发网关密钥(OpenViking 只存密钥哈希时,需要用户本人提供密钥)。拿到网关密钥就能以该用户的身份召回记忆、调用工具,所以签发权实际上等于读取本账号所有用户记忆的权限,只交给可信的管理员。
-- `/gateway/uploads` 不需要网关密钥。每次上传由 OpenViking 签发的一次性令牌授权,网关只把它转发到 OpenViking 的上传接口。不要让它的查询字符串出现在代理日志里。
-- `X-OpenViking-*` 请求头、客户端凭证和 Cookie 从不转发给上游。
+网关用 OpenViking 自己的加密功能保护已存的凭证和对话状态(见[加密指南](08-encryption.md))。加密关闭或没有配置时,网关以明文存储,只靠文件权限保护。
-**备份。** 备份 `storage_path`,包括两个数据库及其 `-wal`、`-shm` 文件;开启加密时,还要保管好 OpenViking 根密钥的备份。要得到一致的副本,先停止网关,或者用 SQLite 的在线备份(`sqlite3 kernel.sqlite3 ".backup kernel.backup.sqlite3"`,`management.sqlite3` 同理)。丢失不同文件的后果:
+- **嵌入**:网关沿用 Server 在 `ov.conf` 中的 `encryption` 段,不需要为网关单独设置。
+- **独立**:在 `gateway.conf` 中加一个 `encryption` 块,字段和 `ov.conf` 的 `encryption` 段完全相同,例如:
-- **丢失 `kernel.sqlite3`**:之前补充的记忆无法放回。每段进行中的对话会有一次服务商缓存未命中,Claude 对话会丢掉一次之前的思考内容(**记忆记录缺失**,`missing_injection_record`),尚未保存的轮次也会丢失。
-- **丢失 `management.sqlite3`**:上游、上下文配置、密钥和请求日志全部丢失,需要重新配置并签发新密钥。
-- **丢失根密钥**(开启加密时):两个数据库中已加密的值都无法读取,只能从空的 `storage_path` 重新开始。
+ ```json
+ {
+ "openviking_url": "https://ov.example.com",
+ "encryption": {
+ "enabled": true,
+ "provider": "local",
+ "local": { "key_file": "~/.openviking/master.key" }
+ }
+ }
+ ```
-## 日常运维
+之后修改加密设置时:
-- **盯住首次调用缓存命中率。** 它反映跨轮次的提示缓存,应该接近不经过网关时服务商能达到的水平;**轮内缓存命中率**覆盖工具步骤,正常时很高。明显下降时,见[首次调用缓存命中率下降](#首次调用缓存命中率下降)。
-- **用请求日志定位单个请求。** 按新消息、工具步骤或异常筛选,展开一行就能看到召回结果、保存状态和 OpenViking 工具的停用原因,见[请求日志和概览](#请求日志和概览)。
-- **设置对外地址。** 把 `public_url` 设为客户端访问的地址(不带 `/gateway`),反向代理后的客户端配置和上传链接才能保持一致。
-- **定期备份。** 备份网关存储目录;开启加密时还要备份 OpenViking 根密钥,见[安全与数据](#安全与数据)中的“备份”。
+- **开启加密**不会出问题:已有的明文值照常可读,新写入的值会加密。
+- **关闭加密或换一把加密根密钥**后,已加密的值就读不出来了,所以要保持写入时的加密设置。
+- **丢失加密根密钥**后,网关的数据库就无法读取。请按加密指南备份加密根密钥。
-### 升级
+v0.5 网关用自己的密钥加密数据,这些数据会在首次启动时转换,见[迁移](#migration)。
-- 升级前读发布说明。新版本的网关读不了旧的存储格式时,启动会报 `Unsupported gateway schema`,见[网关无法启动](#网关无法启动)。
-- 独立网关要求 OpenViking Server 不低于 `min_server_version`(0.4.16),否则记忆检索和保存都会停止,也无法签发密钥。两者分开升级时,先升级 OpenViking,再升级网关。嵌入网关和 Server 同版本发布,不做这项检查。
-- 从 sidecar 或旧版独立网关升级,见[迁移](#迁移)。
+## 扩展 {#scaling}
-### 观测
+一个存储目录只供一台主机上的一套部署使用,嵌入网关和独立网关不能共用同一目录。嵌入网关跟随 Server 的 worker 设置;独立网关用 `workers` 设置,取值 1–64。需要在服务商之间负载均衡、故障转移或限流时,把 LiteLLM 这类服务添加为上游。
-网关不导出 Prometheus 之类的监控指标,也不写 HTTP 访问日志。运行状态通过 Studio 的“概览”和“请求日志”标签页查看,或者调用管理 API 的 `/gateway/admin/overview` 和 `/gateway/admin/logs`。进程存活用 `/health` 检查:嵌入部署用 Server 的健康检查,独立部署用网关自己的。
+## 观测与例行检查 {#monitoring}
-## 设计取舍
+网关不导出 Prometheus 之类的监控指标,也不写 HTTP 访问日志。运行状态通过 Studio 的[概览和请求日志](../gateway/10-overview-and-requests.md#overview)标签页查看,或者调用管理 API 的 `/gateway/admin/overview` 和 `/gateway/admin/logs`。
-下表说明网关几项关键设计的原因和代价,帮你判断它是否适合自己的场景:
+### 例行检查 {#day-to-day-operations}
-| 设计 | 选择及原因 | 代价 |
-| --- | --- | --- |
-| 接入位置 | 接在模型调用路径上,而不是给每个 Agent 装插件:装不了插件的客户端也能用,服务商密钥集中管理。 | 看不到工作目录,按项目隔离记忆要给每个项目用不同的 OpenViking 用户。 |
-| 工具由谁执行 | 网关在回复过程中代为执行 OpenViking 工具,存下往返并在下一轮原样放回:没有工具、不支持 MCP 的客户端也能让模型主动使用记忆。 | 没有逐次确认;客户端必须每轮回传完整历史;需要管理员收紧工具清单和上限。 |
-| 记忆放在哪 | 附加在最新用户消息末尾,而不是系统提示词里:系统提示词改一个字整份缓存就失效;附加在末尾并在之后原样放回,前缀始终不变。 | 网关必须可靠地记下每处补充的原文,记录丢失时缓存失效一次。 |
-| 保存时机 | 晚一轮保存:下一条消息带回上一轮,才能确认用户保留了它。 | 最后一轮要等**最新回复等待时长**(默认 10 分钟)之后才保存。 |
-| 长对话 | 由网关让同一个模型写摘要:只有网关知道模型实际收到了什么,摘要请求也大部分命中缓存。 | 触发压缩的那一轮多一次模型调用和计费;压缩位置之前的原文不再发给模型。 |
-| 本地状态 | 单台主机上的 SQLite,不引入 Postgres、Redis 这类依赖,适合自部署。 | 网关不能多机互备,是模型调用路径上的单点。 |
-| 客户端身份 | 网关签发自己的密钥,而不是直接用 OpenViking 密钥:可以单独吊销,同一个人的不同客户端可以绑定不同的上下文配置。 | 网关要保存用户的 OpenViking 密钥,因此应开启加密;网关密钥泄露,等于该用户的记忆泄露。 |
+- **进程存活:** `/health`。嵌入部署用的是 Server 的健康检查,独立部署用的是网关自己的。
+- **网关健康:** **概览**标签页上的**首次调用缓存命中率**([含义](../gateway/10-overview-and-requests.md#overview))。明显下降时,见[首次调用缓存命中率下降](../gateway/12-troubleshooting.md#the-first-call-cache-hit-rate-dropped)。
+- **单个请求:** 在**请求日志**标签页展开对应的行,见[请求日志](../gateway/10-overview-and-requests.md#requests)。
+- **对外地址:** `public_url` 仍是客户端访问的地址,见[对外地址](#public-address)。
+- **备份:** 存储目录;开启加密时还有加密根密钥,见[备份与恢复](../gateway/11-security-and-data.md#backups)。
-## 配置参考
+## 升级 {#upgrades}
-两种部署用同一套字段,区别只在配置文件放在哪、用什么命令生成:
+- 升级前读发布说明。新版本的网关读不了旧的存储格式时,启动会报 `Unsupported gateway schema`,见[网关无法启动](../gateway/12-troubleshooting.md#the-gateway-does-not-start)。
+- 独立网关要求 OpenViking Server 不低于 `min_server_version`(0.4.16),否则无法签发密钥,保存重试也会以 `openviking_version_mismatch` 失败;记忆检索也可能失败,显示为 `openviking_http_<status>`。两者分开升级时,先升级 OpenViking,再升级网关。嵌入网关和 Server 同版本发布,不做这项检查。
+- 从 sidecar 或旧版独立网关升级,见[迁移](#migration)。
-- **嵌入**:写在 `ov.conf` 的 `gateway` 段,由 `openviking-server init` 生成。host、port 和 workers 跟随 Server。
-- **独立**:写在 `gateway.conf` 的根层,没有 `gateway` 外层,由 `openviking-gateway init` 生成。设置了 `--config` 或 `OPENVIKING_GATEWAY_CONFIG_FILE` 时,它必须指向已存在的文件;两者都没设置时,网关读取 `~/.openviking/gateway.conf` 和 `/etc/openviking/gateway.conf` 中第一个存在的文件。`OPENVIKING_CONFIG_FILE` 只用来选择 Server 的配置。
+## 从早期版本迁移 {#migration}
-| 字段 | 适用于 | 默认值 | 含义 |
-| --- | --- | --- | --- |
-| `enabled` | 嵌入 | `false` | 在 Server 中开启网关 |
-| `openviking_url` | 独立 | —(必填) | OpenViking Server 的地址 |
-| `host` | 独立 | `127.0.0.1` | 监听地址 |
-| `port` | 独立 | `1935` | 监听端口 |
-| `workers` | 独立 | `1` | worker 进程数,1–64 |
-| `encryption` | 独立 | 不设置(明文) | 字段同 `ov.conf` 的 `encryption` 段,见[加密](#加密);嵌入网关沿用 Server 的设置 |
-| `public_url` | 两者 | 空 | 客户端访问的对外地址,不带 `/gateway`(网关自己加);嵌入时为空则沿用 Server 的对外地址;都没有时接入指南用请求来源地址,MCP 文件上传和下载也不可用(`mcp_file_links` 为 `direct` 时除外) |
-| `mcp_file_links` | 两者 | `proxy` | MCP 上传和下载工具返回的链接如何交给客户端:`proxy` 改写为 `public_url` 加 `/gateway/uploads` 或 `/gateway/downloads`,需要设置 `public_url`;`direct` 原样透传 OpenViking 的链接,需要 Server 的 `OPENVIKING_PUBLIC_BASE_URL`(或 `server.public_base_url`)是客户端能访问的地址 |
-| `storage_path` | 两者 | `~/.openviking/gateway` | 本地存储目录 |
-| `management_key` | 两者 | 空 | 可选的网关管理密钥,至少 32 个字符 |
-| `min_server_version` | 两者 | `0.4.16` | 独立网关要求的 OpenViking Server 最低版本 |
-| `session_ttl_days` | 两者 | `30` | 对话闲置多少天后过期,最小 1 |
-| `response_ttl_seconds` | 两者 | `2592000` | Responses 响应与上游的对应关系保留多少秒,最小 60 |
-| `log_retention_days` | 两者 | `30` | 请求日志保留天数,最小 1 |
-| `max_body_bytes` | 两者 | `33554432` | 请求和上传的大小上限,至少 1,024 字节 |
-| `upstream_timeout_seconds` | 两者 | `600` | 服务商请求超时,必须大于 0 |
-| `health_interval_seconds` | 两者 | `60` | 检查 OpenViking 状态的间隔秒数,最小 1 |
-
-**环境变量优先于配置文件。** 两种部署规则相同:非空的 `OPENVIKING_GATEWAY_<字段名大写>` 环境变量(例如 `OPENVIKING_GATEWAY_PUBLIC_URL`、`OPENVIKING_GATEWAY_MANAGEMENT_KEY`)覆盖文件中的值,值为空等于没有设置。文件中的值也可以写成 `"$VAR"` 引用环境变量。`encryption` 块只能写在文件里。容器通常不需要配置文件,用环境变量设置需要的字段即可。
-
-URL 必须是 HTTP(S),不能含凭证、查询参数或 fragment。未知字段会导致校验失败;已删除的字段除外,它们会被忽略并在启动时打印警告,包括 `encryption_key_env`,以及 `ov.conf` 中[迁移](#迁移)列出的 v0.5 字段。
-
-**上下文配置的设置。** 先列 Studio 中的名称,再列管理 API 中的名称(管理 API 把上下文配置称为 `policies`):
-
-| Studio 名称 | API 名称 | 默认值 | 取值范围 | 含义 |
-| --- | --- | --- | --- | --- |
-| 名称 | `name` | `Default` | | 显示名称。 |
-| 召回记忆 | `recall` | `true` | | 为每条新的用户消息检索记忆。 |
-| 会话开头提供用户画像 | `profile` | `true` | | 新对话开始时提供画像,独立于召回。 |
-| 开头内容预算 | `profile_max_tokens` | `4000` | 0–32,000 | 画像和目录的独立预算;0 表示省略。目录需要提供 `read` 工具。 |
-| 显示召回摘要 | `show_recall` | `false` | | 在回复开头说明 OpenViking 补充了什么,或召回失败的原因。模型看不到。 |
-| 检索范围 | `context_types` | `memory`、`resource`、`skill` | 至少一个 | 检索哪些内容:记忆、资源、技能。 |
-| 单条消息预算 | `max_tokens` | `1600` | 64–32,000 | 一条消息最多补充的 token 数。 |
-| 单个上下文窗口预算 | `session_max_tokens` | `30000` | ≥ 0 | 一个上下文窗口内最多补充的 token 数,每次压缩后重新计算;0 表示关闭召回。 |
-| 相关度阈值 | `score_threshold` | `0.35` | 0–1 | 接受的最低相关度分数。 |
-| 超时时间 | `recall_timeout` | `2`(秒) | 最多 30 | 检索最多等多久,超时后消息不带记忆继续发送。 |
-| 检索文本长度 | `query_max_chars` | `8000` | 3–32,000 | 取消息的多少个字符作为检索文本。 |
-| 按分类限量 | `quotas` | `{}`(关闭) | 键:`events`、`entities`、`preferences`、`experiences`、`resources`、`skills` | 每个分类最多取的条数;只检索大于 0 的分类。 |
-| 保存对话 | `capture` | `true` | | 把完成的轮次保存到 OpenViking。 |
-| 最新回复等待时长 | `idle_seconds` | `600`(秒) | ≥ 1 | 停顿多久之后保存最后一轮并提交会话。 |
-| 提交阈值 | `commit_tokens` | `20000` | ≥ 1 | 会话中待提交的 token 数达到这个值时提交。 |
-| 保留最近消息 | `keep_recent_messages` | `10` | 0–1,000 | 提交后会话中保留的消息数。 |
-| 压缩 | `compaction` | `true` | | 接近上下文窗口时,用摘要替换对话较早的部分。 |
-| 压缩时机 | `compaction_threshold` | `0.9` | 0.5–0.98 | 上下文窗口用到多大比例时压缩。 |
-| 摘要长度上限 | `summary_max_tokens` | `8000` | 1,000–32,000 | 一份摘要最多多少 token。 |
-| 默认上下文窗口 | `context_window` | 未设置(按 1,000,000 计算) | ≥ 1,024 | 上游没有列出该模型时使用的窗口。 |
-| Agent 自管上下文窗口 | `agent_windows` | `false` | | 实验性。让模型自己开启新的上下文窗口;需要 OpenViking 工具。 |
-| 软提醒时机 | `window_soft_ratio` | `0.7` | 0.3–0.95,须低于 `window_hard_ratio` | 窗口用到这个比例时,提醒模型尽快开启新窗口。 |
-| 硬提醒时机 | `window_hard_ratio` | `0.85` | 0.4–0.97 | 窗口用到这个比例时,要求模型立即开启新窗口。 |
-| OpenViking 工具 | `gateway_tools` | `true` | | 为 Chat Completions、完整历史的 Responses 和 Anthropic Messages 提供 OpenViking 工具。 |
-| 取消勾选的工具 | `disabled_tools` | 会修改数据的 8 个工具,见[选择工具](#选择工具) | OpenViking 工具原名,不带 `openviking_` | 新对话不提供这些工具,其余可用工具都提供,包括以后新增的。API 请求省略这个字段时使用默认列表;列表为空且总开关开启时,提供全部可用工具。 |
-| 显示工具调用 | `show_tool_calls` | `true` | | 每次 OpenViking 工具调用都在回复里加一行提示。 |
-| 每次请求的工具轮数 | `tool_max_rounds` | `null`(不限) | 1 及以上 | 见[上限](#上限)。 |
-| 单次调用超时 | `tool_timeout_seconds` | `30` | 最多 120 | |
-| 结果大小上限 | `tool_result_bytes` | `65536` | 1,024–1,048,576 | |
-| 总时长 | `tool_total_seconds` | `null`(不限) | 大于 0 | |
-| Token 预算 | `tool_total_tokens` | `null`(不限) | 1,024 及以上 | |
-
-**上游设置:**
-
-| Studio 名称 | API 名称 | 默认值 | 含义 |
-| --- | --- | --- | --- |
-| 名称 | `name` | | 显示名称。 |
-| 协议 | `protocol` | | `anthropic`(Anthropic Messages)、`chat`(Chat Completions)或 `responses`(Responses)。 |
-| 服务商 | `vendor` | `generic` | `generic`、`anthropic`、`openai`、`deepseek`、`ark`(火山方舟)或 `byteplus`(BytePlus 方舟)。Studio 只提供服务商支持的协议,API 接受任意组合。 |
-| Base URL | `base_url` | | 服务商地址;默认地址和拼接规则见[上游](#上游)。 |
-| 拼接协议接口路径 | `append_endpoint_path` | `true` | 拼接所选协议的接口路径;关闭时把 `base_url` 直接作为完整请求地址。 |
-| 密钥发送方式 | `key_header` | `authorization` | `authorization`(Bearer)、`api-key` 或 `x-api-key`。`base_url` 含 `{api_key}` 时不生效。 |
-| API Key 由谁提供 | `auth_mode` | `managed` | `managed`(由网关保管 API Key)或 `passthrough`(每个客户端自带 API Key)。 |
-| API Key | `api_key` | | 只写,见[凭证](#凭证)。 |
-| 额外请求头 | `headers` | `{}` | 只写,见[凭证](#凭证)。 |
-| 模型 | `models` | `[]` | 提供的模型名;留空表示接受任何名称。 |
-| 模型别名 | `aliases` | `{}` | 客户端使用的名称 → 发给上游的模型。 |
-| 上下文窗口 | `context_windows` | `{}` | 模型 → token 数,每项至少 1,024。 |
-| 优先级 | `priority` | `0` | 数值越大,新对话越优先使用。 |
-| 启用 | `enabled` | `true` | 停用的上游不接收请求。 |
-| 允许 OpenViking 工具 | `allow_gateway_tools` | `true` | 能否通过这个上游提供 OpenViking 工具。 |
-| 补全推理内容回传 | `replay_reasoning` | `null`(跟随服务商) | 把客户端丢掉的推理内容补回之前的回复。`null` 时 `deepseek`、`ark` 和 `byteplus` 开启,其他服务商关闭;`true` 或 `false` 覆盖服务商默认值。Studio 中开关与服务商默认值一致时保存为 `null`。 |
-| 这是 Coding Plan 或订阅密钥 | `coding_plan` | `false` | 除非另外允许,否则拒绝发往这个上游的请求。 |
-| 允许通过网关使用这个套餐 | `allow_coding_plan` | `false` | 允许使用被标记为 Coding Plan 的密钥。 |
-| 最小可缓存长度 | `cache_min_tokens` | `1024` | 仅火山方舟和 BytePlus 方舟;影响缓存资格的报告。 |
-
-网关密钥的字段、全部管理操作、权限规则和错误原因见[管理 API](../api/25-gateway.md)。
-
-## 迁移
-
-以下步骤适用于从早期版本的 sidecar 或独立网关迁移到嵌入网关。
+以下步骤适用于从早期版本的 sidecar 或独立网关迁移到嵌入网关。第 4 步和第 7 步的细节见列表后面的两张表。
1. **先备份。** 备份 `storage_path`(两个数据库,以及存在的话 `encryption.key`)。停止旧的网关进程或 sidecar,再启用嵌入网关。
-2. **删掉旧字段。** 从 `ov.conf` 的 `gateway` 段删除 `host`、`port`、`workers`、`url`、`openviking_url`、`admin_token_env` 和 `encryption_key_env`。Server 会忽略这些字段并在启动时打印警告,旧的 `ov.conf` 仍能启动,但还是应该清理掉。`openviking-server init` → **Update gateway** 会自动删除它们。想继续独立运行网关,就运行 `openviking-gateway init`,或者把设置移到单独的 `gateway.conf`,去掉 `gateway` 外层和 `enabled`。独立网关的命令不再接受 `--openviking-url`、`--host`、`--port`、`--workers` 和 `--storage-path`,这些设置改写到 `gateway.conf` 或环境变量中。
+2. **删掉旧字段。** 从 `ov.conf` 的 `gateway` 段删除 `host`、`port`、`workers`、`url`、`openviking_url`、`admin_token_env` 和 `encryption_key_env`。Server 会忽略这些字段并在启动时打印警告,旧的 `ov.conf` 仍能启动,但还是应该清理掉;`openviking-server init` → **Update gateway** 会自动删除它们。
+
+ 想继续独立运行网关,就运行 `openviking-gateway init`,或者把设置移到单独的 `gateway.conf`,去掉 `gateway` 外层和 `enabled`。独立网关的命令不再接受 `--openviking-url`、`--host`、`--port`、`--workers` 和 `--storage-path`,这些设置改写到 `gateway.conf` 或环境变量中。
3. **改对外地址。** 把 `public_url` 改为 Server 的对外地址(不带 `/gateway`),或者删掉。旧版快速开始把它设成了 `http://127.0.0.1:1935`,嵌入网关不再监听这个端口,接入指南和上传链接都会指向一个不存在的地址。`openviking-server init` → **Update gateway** 发现 `public_url` 指向别的端口时,会询问是否清除。
-4. **改客户端地址和部署配置。** 网关的所有 URL 现在都在 `/gateway` 下,所以客户端要同时改端口和路径:`http://host:1935/v1` 改为 `http://host:1933/gateway/v1`,Claude Code 的 `ANTHROPIC_BASE_URL` 从 `http://host:1935` 改为 `http://host:1933/gateway`,方舟 SDK 改用 `http://host:1933/gateway/api/v3`。旧路径不再提供服务。调用管理 API 的脚本把 `/api/v1/admin/gateway/...` 改为 `/gateway/admin/...`。移除旧的 1935 Service 和 Ingress 路由、Compose 的 `gateway` 服务和 profile,以及 Helm 的 sidecar 配置 `gateway.workers`、`gateway.port`、`gateway.resources`。1935 仍是独立运行的默认端口,独立网关也使用同样的 `/gateway` 路径。
-5. **首次启动会转换已存数据。** v0.5 网关用自己的密钥加密数据。新版网关(嵌入或独立)首次启动时,用这把旧密钥解密,再按当前的[加密](#加密)设置重新写入;加密关闭时写成明文,所以想让数据继续加密,要在这次启动前开启 OpenViking 加密。旧密钥从环境变量 `OPENVIKING_GATEWAY_ENCRYPTION_KEY` 读取,或者从 `storage_path` 下的 `encryption.key` 读取。`encryption_key_env` 会被忽略:如果你曾用它指向别的环境变量,这次启动时把密钥导出为 `OPENVIKING_GATEWAY_ENCRYPTION_KEY`。存在旧的加密数据、两处却都没有密钥时,网关拒绝启动,错误信息会写明这两个位置。用 Helm 时,只在这次升级的版本中保留 `existingSecret` 里的 `encryption-key` 字段。启动成功后旧密钥不会再被读取,可以删掉这个环境变量、Secret 字段和 `encryption.key`。
-6. **移除共享 admin token。** `OPENVIKING_GATEWAY_ADMIN_TOKEN` **不会**被当作管理密钥。需要限制谁能修改上游和上下文配置时,显式设置 `management_key`。
-7. **核对上游地址。** 首次启动时,网关会改写一次已存上游的 Base URL,让每个上游继续请求升级前的同一个地址:
- - 火山方舟和 BytePlus 方舟的 Chat Completions、Responses 上游,只有域名的补上 `/api/v3`。
- - 其他 Chat Completions、Responses 上游,路径不以 `/v1`、`/v4` 这类版本段结尾的补上 `/v1`。这包括纯域名(`https://api.deepseek.com` → `https://api.deepseek.com/v1`),也包括带路径前缀的地址(`https://openrouter.ai/api` → `https://openrouter.ai/api/v1`,或者挂在 `/litellm` 下的自建代理)。
- - 方舟和 BytePlus 方舟的 Anthropic 上游,只有域名的补上 `/api/compatible`。
- - 以 `/v1` 结尾的 Anthropic Base URL 去掉 `/v1`。
-
- 已经以其他版本段结尾的地址保持不变,例如智谱的 `https://open.bigmodel.cn/api/paas/v4`:升级前它会被拼成 `…/v4/v1` 而请求失败,升级后按填写的地址直接可用。新建和修改的上游按[上游](#上游)中的规则拼接,以 `/v1` 结尾的 Anthropic Base URL 会被拒绝。
+4. **改客户端地址和部署配置。** 网关的所有 URL 现在都在 `/gateway` 下,所以客户端要同时改端口和路径,旧路径不再提供服务,见[新地址](#new-addresses)。移除旧的 1935 Service 和 Ingress 路由、Compose 的 `gateway` 服务和 profile,以及 Helm 的 sidecar 配置 `gateway.workers`、`gateway.port`、`gateway.resources`。
+5. **首次启动会转换已存数据。** v0.5 网关用自己的密钥加密数据。新版网关(嵌入或独立)首次启动时,用这把旧密钥解密,再按当前的[加密](#encryption)设置重新写入;加密关闭时写成明文,所以想让数据继续加密,要在这次启动前开启 OpenViking 加密。
+
+ 旧密钥从环境变量 `OPENVIKING_GATEWAY_ENCRYPTION_KEY` 读取,或者从 `storage_path` 下的 `encryption.key` 读取。`encryption_key_env` 会被忽略:如果你曾用它指向别的环境变量,这次启动时把密钥导出为 `OPENVIKING_GATEWAY_ENCRYPTION_KEY`。存在旧的加密数据、两处却都没有密钥时,网关拒绝启动,错误信息会写明这两个位置。用 Helm 时,只在这次升级的版本中保留 `existingSecret` 里的 `encryption-key` 字段。启动成功后旧密钥不会再被读取,可以删掉这个环境变量、Secret 字段和 `encryption.key`。
+6. **移除共享 admin token。** `OPENVIKING_GATEWAY_ADMIN_TOKEN` **不会**被当作管理密钥。需要限制谁能修改上游和上下文配置时,显式设置 `management_key`,见[网关管理密钥](#gateway-management-key)。
+7. **核对上游地址。** 首次启动时,网关会改写一次已存上游的 Base URL,让每个上游继续请求升级前的同一个地址,见[已存上游地址的变化](#upstream-address-rewrite)。在**上游**标签页对每个上游点**测试**,确认它仍然可用。
8. **了解日志和吊销的变化。** 请求日志新增用户列,没有用户的旧记录只出现在账号管理员和 root 的视图中。吊销密钥不再删除用户数据,显式删除和保留期照常生效。
-## 故障排查
+### 新地址 {#new-addresses}
-### 常见现象
+把 `host` 换成你的 Server 地址:
-| 现象 | 原因 | 处理 |
+| 对象 | 迁移前 | 迁移后 |
| --- | --- | --- |
-| 某段对话没有召回,也没有保存 | 检测到 OpenViking 插件,网关把召回、保存和工具都让给了插件。 | 正常行为,避免同一份内容被补充、保存两次,见[网关还是插件](15-gateway.md#网关还是插件)。 |
-| 保存显示“重试中”,之后变成“已暂停” | OpenViking 拒绝保存或无法访问;或者这段对话的网关密钥已被吊销(`gateway_key_revoked`),例如用户的 OpenViking 密钥被重新生成过。 | OpenViking 恢复后网关会自动恢复保存。密钥被吊销时,重新签发网关密钥,用户的下一个请求会恢复保存。见[OpenViking 中看不到对话](#openviking-中看不到对话)。 |
-| 上下文配置开启了工具,对话里却没有 | 还没有能用工具的请求,第一个能用的请求加载工具清单失败,客户端没有回传完整历史,或者客户端自己接了 OpenViking 工具。 | 在请求日志里查看原因(见[什么时候不提供工具](#什么时候不提供工具))。客户端接了 OpenViking MCP 服务器时出现 `tool_name_collision` 是正常的;其他原因修正后开始新对话。 |
-| 请求不带记忆 | OpenViking 无法访问或超时、预算用完、没有相关内容等。 | 见[没有补充记忆](#没有补充记忆)。 |
-| 长对话被服务商以过长为由拒绝 | 网关不知道模型的实际窗口,压缩得太晚。 | 见[长对话超出上下文长度](#长对话超出上下文长度)。 |
-
-### 网关无法启动
-
-嵌入网关无法启动时,整个 OpenViking Server 都会停止。请在 Server 日志中查看启动错误(Compose 中用 `docker compose logs openviking`)。
-
-- **v0.5 数据缺少旧密钥**:存储目录里有 v0.5 网关加密的数据,但既没有 `OPENVIKING_GATEWAY_ENCRYPTION_KEY`,`storage_path` 下也没有 `encryption.key`。提供原来的密钥,见[迁移](#迁移)第 5 步。
-- **旧字段**:删除[迁移](#迁移)第 2 步列出的字段。
-- **管理密钥太短**:至少 32 个字符;用 `$VAR` 引用的环境变量没有设置时,也会报这个错。
-- **加密设置**:Server 的 `encryption` 段(嵌入)或 `gateway.conf` 的 `encryption` 块(独立)不合法,或者加载不了根密钥。见[加密指南](08-encryption.md)。
-- **存储格式不支持**(`Unsupported gateway schema`):存储目录由不兼容的网关版本写入(更旧的版本,或降级前更新的版本)。换一个空的 `storage_path`。
-- **独立运行缺少 OpenViking 地址**:运行 `openviking-gateway init`,或者设置 `OPENVIKING_GATEWAY_OPENVIKING_URL`。
-- **独立运行找不到配置文件**:`--config` 或 `OPENVIKING_GATEWAY_CONFIG_FILE` 指定的文件不存在。改正路径,或者用 `openviking-gateway init --config <路径>` 生成它。
-- **独立运行绑定非回环地址**:启动检查必须连上 OpenViking 并确认它使用 `api_key` 认证,否则网关退出。先启动 OpenViking(在容器中要等它就绪),或者绑定 `127.0.0.1`。
-
-### Studio 显示设置卡片
-
-| 卡片 | 处理 |
-| --- | --- |
-| 这台 OpenViking 没有开启网关(404) | 运行 `openviking-server init` → **Update gateway**,或者在 `ov.conf` 中设置 `gateway.enabled: true` 后重启。使用 API 密钥的服务端上,root 也可以直接在这个页面点**开启网关**。账号管理员和普通用户看到的卡片只提示联系部署者开启网关。 |
-| 先连接 OpenViking,或者 OpenViking API 密钥无效(401) | 打开连接设置,填入当前的 OpenViking API 密钥。 |
-| 网关不支持 Trusted 模式(`trusted_mode_unsupported`) | 把 Server 改为 `api_key` 认证。 |
-| 网关连不上 OpenViking(`openviking_unreachable`) | 只出现在独立网关:检查 `openviking_url`(`gateway.conf` 或 `OPENVIKING_GATEWAY_OPENVIKING_URL`)和网络。 |
-
-“上游”和“上下文配置”标签页只读,是因为部署者设置了网关管理密钥:点**输入网关管理密钥**解锁。OpenViking 的 root 或 admin API 密钥不能解锁编辑;管理密钥被更换后(`management_key_invalid`),Studio 会重新锁定。没人记得密钥时,见[忘记网关管理密钥](#忘记网关管理密钥)。
-
-### 签发密钥失败
-
-**签发密钥**对话框会显示失败原因,括号里是管理 API 返回的 `reason`。
-
-| Studio 中的提示 | 原因和处理 |
-| --- | --- |
-| 服务端读不到这个用户的用户 API 密钥,请改为粘贴(`user_key_unreadable`) | OpenViking Server 只保存了密钥哈希(`encryption.api_key_hashing.enabled`)。在**粘贴用户 API 密钥**中填入该用户自己的密钥。 |
-| 不接受 Root API 密钥,请使用本账号下的用户 API 密钥(`root_key_not_allowed`) | root API 密钥不能绑定到网关密钥,改用某个用户或账号管理员的 API 密钥。本地 dev 模式的 `default/default` 不受此限。 |
-| 这个 OpenViking API 密钥属于其他账号(`other_account`) | 密钥所属的账号不是你在 Studio 中管理的账号。 |
-| OpenViking 拒绝了这个密钥(`openviking_http_401`) | 密钥不完整、已被重新生成,或者用户已被删除。使用该用户当前的密钥。 |
-| OpenViking 无法识别这个密钥所属的用户(`openviking_identity_missing`) | OpenViking 没有返回这个密钥对应的用户。使用本账号中某个用户的密钥。 |
-| 网关连不上 OpenViking,无法校验这个密钥(`openviking_unavailable`) | 网关访问不到 OpenViking;独立网关检查 `openviking_url`。 |
-| OpenViking 版本低于网关的要求(`openviking_version_mismatch`) | 仅独立网关:OpenViking Server 低于 `min_server_version`(0.4.16),请升级。从源码安装、没有版本标签的服务可能报告 `0.1.dev123` 这样的开发版本号;请安装正式版本,或者把 `min_server_version` 改成与之匹配的值。 |
-
-### 客户端收到网关返回的错误
+| OpenAI 兼容客户端 | `http://host:1935/v1` | `http://host:1933/gateway/v1` |
+| Claude Code 的 `ANTHROPIC_BASE_URL` | `http://host:1935` | `http://host:1933/gateway` |
+| 火山方舟和 BytePlus 方舟 SDK | 旧的网关地址 | `http://host:1933/gateway/api/v3` |
+| 调用管理 API 的脚本 | `/api/v1/admin/gateway/...` | `/gateway/admin/...` |
-这些拒绝都发生在请求到达服务商之前,所以不会出现在请求日志里。
+1935 仍是独立运行的默认端口,独立网关也使用同样的 `/gateway` 路径。
-| 状态码和提示 | 原因和处理 |
-| --- | --- |
-| 401 "Invalid gateway key. It may have been revoked, or removed because its OpenViking API key was regenerated…" | 客户端没有发送网关密钥,发送了已吊销的密钥或服务商的 API Key,或者用户的 OpenViking API 密钥重新生成后,网关删除了这把密钥。检查客户端实际发送的密钥,必要时重新签发。 |
-| 403 "Claude subscription OAuth credentials are not supported" | 客户端发送了 Claude 订阅令牌,例如 Claude Code 用订阅账号登录且没有设置 `ANTHROPIC_AUTH_TOKEN`;或者上游保存的就是订阅令牌。请改用 API Key。 |
-| 403 "Model is not allowed by this key" | 模型不在密钥允许的范围内。签发一把允许这个模型的密钥。 |
-| 404 "No allowed upstream matches this protocol and model" | 密钥绑定的已启用上游中,没有一个使用客户端调用的 API 并提供所请求的模型。检查上游的协议、模型和别名、是否启用,以及密钥绑定了哪些上游。 |
-| 401 "Upstream API key is missing" | 上游要求每个客户端在 `X-OpenViking-Upstream-Key` 中自带 API Key,或者由网关保管 API Key 的上游没有填写。 |
-| 403 "Coding Plan upstreams are disabled; configure a model API key" | 上游被标记为 Coding Plan 密钥。改用模型 API Key,或者有意勾选**允许通过网关使用这个套餐**。 |
-| 404 "Unknown response for this key"、403 "Response upstream is no longer allowed" | 查询的 Responses 响应不是这把密钥创建的,或者创建它的上游已停用、不再绑定到这把密钥。 |
-| 413 | 请求体超过了 `max_body_bytes`,或者超过了代理自己的上限。 |
-| 426 | 对 Responses API 发起了 WebSocket 连接。这是预期行为,Codex 会改用 HTTP。 |
-| 502 "Model upstream is unavailable" | 网关连不上服务商,或者调用超过了 `upstream_timeout_seconds`。在上游上点**测试**。 |
-| 504 "Hidden tool request timed out" | OpenViking 工具的往返超过了上下文配置中工具的**总时长**;没有设置总时长时,是往返中某次模型请求超过了 `upstream_timeout_seconds`。 |
-
-### 没有补充记忆
-
-先在请求日志里找到这个请求。找不到,说明客户端没有经过网关,或者请求被网关拒绝了(见上一节)。找到后展开它,查看记忆检索结果:
-
-- **没有找到相关内容**(`empty`):新用户通常如此。对话提交、OpenViking 提取之后才会有记忆。
-- **召回已关闭或预算已用完**(`disabled`):上下文配置关闭了召回,这段对话的预算已经用完,或者消息短于 3 个字符。
-- **OpenViking 无法访问或响应超时**(`openviking_unavailable`):查看“概览”标签页上的 OpenViking 卡片。OpenViking 在运行但响应慢时,可以调长**超时时间**。
-- **OpenViking 拒绝了这个密钥**(`openviking_http_401`):用户的 OpenViking 密钥已失效。用当前的密钥签发新的网关密钥。
-- **OpenViking 版本低于网关的要求**(`openviking_version_mismatch`):见[签发密钥失败](#签发密钥失败)。
-- **检测到 OpenViking 插件**(`plugin_present`):网关发现了 OpenViking 插件,让出了这段对话。
-- **类型不是新消息**:工具步骤、辅助请求和子 Agent 请求从不检索,它们放回之前的消息得到的记忆。
-
-检索失败的消息之后也不会补上记忆;下一条消息会重新检索。
-
-### OpenViking 中看不到对话
-
-- **保存晚一轮。** 下一条消息到达时,上一轮才会出现;最后一轮要等**最新回复等待时长**(默认 10 分钟)。
-- **上下文配置不保存对话。** 这时**保存**列显示“已关闭”。
-- **保存正在重试或已暂停。** 展开的行会显示原因。原因修复后(例如 OpenViking 恢复访问),网关会在 5 分钟内重试。原因为 `gateway_key_revoked` 时,重新签发网关密钥,下一个请求会恢复保存。对话一直暂停时,用**重新同步对话…**。
-- **检测到 OpenViking 插件**(`plugin_present`):网关不为这段对话保存任何内容。
-- **你用的是其他用户的身份。** 会话属于网关密钥背后的 OpenViking 用户,名称形如 `gateway-…`。
-- **记忆比会话出现得晚。** OpenViking 在提交之后才在后台提取记忆。
-
-### 首次调用缓存命中率下降
+### 已存上游地址的变化 {#upstream-address-rewrite}
-先和不经过网关时服务商能达到的命中率比较,再看最近请求上标出的异常:
-
-- **记忆记录缺失**(`missing_injection_record`):网关存储丢失、从旧备份恢复,或者记录已过期,之前补充的记忆无法放回。进行中的对话在一次未命中之后就会恢复。
-- **上游已切换**(`upstream_changed`):对话原来的上游被停用、没有绑定到客户端当前用的密钥,或者不再提供这个模型,于是对话转到了另一个上游。
-- **缓存参数有变化**(`ark_cache_parameters_changed`):在火山方舟或 BytePlus 方舟上,客户端在同一段对话里改变了模型、思考模式、采样参数、系统提示词或工具。
-- **没有标出异常**:客户端本身可能每轮都在改动之前的消息或系统提示词,例如插入当前时间,网关无法修正。每次压缩、模型每次开启新的上下文窗口,也都会造成一次未命中,这是预期内的。
-- **一直是 0%**:先对照服务商或中转服务后台的缓存记录。那边有命中,说明上游没有把缓存用量传回网关,例如中转服务转换协议时丢掉了缓存字段;网关读取 `cache_read_input_tokens`、`prompt_tokens_details.cached_tokens`、`input_tokens_details.cached_tokens`、`prompt_cache_hit_tokens` 等常见字段。那边也没有,检查服务商是否支持提示缓存、Anthropic 客户端是否设置了 `cache_control`,以及中转服务是否在多个账号或渠道之间轮换。
-
-### 长对话超出上下文长度
-
-服务商以对话过长为由拒绝长对话的请求时,通常是下面三种原因之一:
-
-- **网关不知道模型的窗口大小。** 上游的**上下文窗口**里没有这个模型,上下文配置也没有设置**默认上下文窗口**,网关就按 1,000,000 token 计算,对窗口更小的模型压缩得太晚。补上模型的窗口大小。
-- **对话所用的上下文配置关闭了压缩。** 修改配置只对新对话生效。
-- **压缩失败。** 请求详情会显示原因,网关 60 秒后再试。摘要总因长度上限被截断时,调大**摘要长度上限**。原因是 `still_over_threshold` 时,说明系统提示词、工具和摘要本身就占满了大部分窗口:调小**摘要长度上限**,或者检查模型的上下文窗口设置。
-
-### 文件导入或下载失败
-
-- "Set gateway.public_url for client uploads and downloads":把 `public_url` 设为客户端能访问的地址,或者把 `mcp_file_links` 设为 `direct`。
-- 上传或下载链接无法访问或返回 404:确认 `public_url` 不是旧的 `:1935` 地址,也没有以 `/gateway` 结尾,并且代理像其他路径一样转发 `/gateway/uploads` 和 `/gateway/downloads`。`mcp_file_links` 设为 `direct` 时,改查 Server 的 `OPENVIKING_PUBLIC_BASE_URL`。
-- 413:文件超过了 `max_body_bytes` 或代理的上限。
-- 502 "OpenViking upload is unavailable" 或 "OpenViking download is unavailable":网关连不上 OpenViking Server。
-- 模型没有导入工具:OpenViking 服务没有提供该工具,上下文配置没有勾选,或者当前请求不能使用网关工具。检查工具清单和请求详情。
+| 上游 | 已存的 Base URL | 首次启动后 |
+| --- | --- | --- |
+| 火山方舟和 BytePlus 方舟的 Chat Completions、Responses 上游 | 只有域名 | 补上 `/api/v3` |
+| 其他 Chat Completions、Responses 上游 | 路径不以 `/v1`、`/v4` 这类版本段结尾,包括纯域名和带路径前缀的地址 | 补上 `/v1`:`https://api.deepseek.com` → `https://api.deepseek.com/v1`,`https://openrouter.ai/api` → `https://openrouter.ai/api/v1`,或者挂在 `/litellm` 下的自建代理 |
+| 火山方舟和 BytePlus 方舟的 Anthropic 上游 | 只有域名 | 补上 `/api/compatible` |
+| Anthropic 上游 | 以 `/v1` 结尾 | 去掉 `/v1` |
+| 任意上游 | 已经以其他版本段结尾,例如智谱的 `https://open.bigmodel.cn/api/paas/v4` | 保持不变。升级前它会被拼成 `…/v4/v1` 而请求失败,升级后按填写的地址直接可用。 |
-### 降级请求的异常
+新建和修改的上游按 [Base URL 的拼接规则](../gateway/07-upstreams.md#base-url)拼接,以 `/v1` 结尾的 Anthropic Base URL 会被拒绝。
-“请求日志”和“概览”标签页会标出网关没能完整处理的请求。Studio 显示异常名称,括号里是管理 API 中对应的值:
+## 下一步 {#next-steps}
-| 异常 | 发生了什么 | 怎么处理 |
-| --- | --- | --- |
-| 记忆不可用(`memory_store_failure`) | 网关无法读写自己的存储,或者该用户的网关数据刚被删除。请求不带记忆发给了模型;Claude 对话中之前的思考内容被去掉。 | 检查磁盘空间、权限和网关日志。刚删除过该用户的网关数据时出现属于正常。 |
-| 原样转发(`unsafe_json`) | 请求中有无法精确重新编码的数字或重复的键,网关逐字节原样转发,没有补充记忆。 | 通常只与某个客户端有关,网关这边无需调整。 |
-| 上游已切换(`upstream_changed`) | 对话原来的上游无法再服务,转到了另一个上游,造成一次缓存未命中,之前的 Claude 思考内容也被去掉。 | 重新启用这个上游,或者让客户端改用包含它的密钥;也可以接受这次切换。 |
-| 记忆记录缺失(`missing_injection_record`) | Claude 对话中,之前补充的记忆已经没有记录,之前的思考内容被去掉一次。 | 存储丢失后,或者在很久以前的对话里出现,都在预期之内。反复出现时,开始新对话。 |
-| 检测到 OpenViking 插件(`plugin_present`) | 检测到 OpenViking 插件,这段对话不再使用网关记忆。 | 使用插件时出现属于正常。同一个客户端在插件和网关之间二选一。 |
-| 缓存参数有变化(`ark_cache_parameters_changed`) | 在火山方舟或 BytePlus 方舟上,影响缓存的参数与对话的第一个请求不同,提示缓存很可能没有命中。 | 在同一段对话里保持模型、思考模式、采样参数、系统提示词和工具不变。 |
-| 工具历史无法继续使用(`hidden_tool_history_unavailable`) | Claude 对话用过 OpenViking 工具,但当前请求不能使用这些工具,之前的思考内容已被去掉。 | 查看请求详情中的工具停用原因,恢复原设置,或者开始新对话。 |
-| OpenViking 工具调用失败(`hidden_tool_loop_failed`) | 模型使用 OpenViking 工具时未能完成回答,客户端收到错误。 | 见[失败处理](#失败处理)。 |
-| 回复未保存(`capture_parse_failure`) | 流式回复无法解析,这条回复没有保存,客户端不受影响。 | 无需处理,仅供了解。 |
-| 密钥未校验(`revocation_check_unavailable`) | OpenViking 无法确认这把网关密钥,请求在没有检查是否已吊销的情况下照常处理。 | 检查 OpenViking 是否可达、运行是否正常。 |
+- [在 Studio 中管理 OpenViking 网关](../gateway/06-manage-in-studio.md):添加上游、创建上下文配置,签发第一批网关密钥。
+- [安全与数据](../gateway/11-security-and-data.md):了解网关存了什么、谁能访问,以及怎么备份和删除数据。
+- [OpenViking 网关排障](../gateway/12-troubleshooting.md):根据启动错误、设置卡片或失败的请求找到解决办法。
diff --git a/web-studio/src/i18n/locales/en/gateway/common.ts b/web-studio/src/i18n/locales/en/gateway/common.ts
index cf2bbfde4..0022a9008 100644
--- a/web-studio/src/i18n/locales/en/gateway/common.ts
+++ b/web-studio/src/i18n/locales/en/gateway/common.ts
@@ -48,6 +48,11 @@ const common = {
done: 'Copied to clipboard',
failed: "Couldn't copy. Select the text and copy it manually.",
},
+ docs: {
+ link: 'Docs',
+ learnMore: 'Learn more',
+ troubleshoot: 'Troubleshooting',
+ },
access: {
title: 'Connect to OpenViking first',
invalid: 'Your OpenViking API key is invalid',
@@ -70,7 +75,7 @@ const common = {
'Root can view ov.conf in Settings → Server configuration → File editor.',
reset:
"Can't find it? Put a new key of at least 32 characters in the same place and restart.",
- resetDocs: 'See the operations guide',
+ resetDocs: 'How to reset it',
keyPlaceholder: '<at least 32 characters>',
session:
'Kept only in this browser tab. Closing the tab locks editing again.',
@@ -85,7 +90,7 @@ const common = {
expired:
'The gateway management key is no longer valid. Upstreams and profiles are read-only again.',
readOnly:
- 'Upstreams and profiles are provided by your gateway admin. You can view and test them, and pick them when issuing a key.',
+ 'Upstreams and profiles are provided by your gateway admin. You can view them and pick them when issuing a key.',
adminReadOnly:
'OpenViking admins and root also need the gateway management key to change them. If you deployed this server, the key is in ov.conf gateway.management_key.',
shared:
@@ -119,7 +124,6 @@ const common = {
fixLabel: 'What to change',
terminal: 'Terminal',
environment: 'Environment variable',
- docs: 'How to deploy',
enable: {
description:
'Studio can turn it on for you: it saves the setting to ov.conf and restarts the server.',
diff --git a/web-studio/src/i18n/locales/en/gateway/connect.ts b/web-studio/src/i18n/locales/en/gateway/connect.ts
index b8c66b5de..fa410378e 100644
--- a/web-studio/src/i18n/locales/en/gateway/connect.ts
+++ b/web-studio/src/i18n/locales/en/gateway/connect.ts
@@ -103,7 +103,7 @@ const connect = {
metadata:
"Codex may warn that it has no metadata for an unfamiliar model name. The warning doesn't affect requests.",
login:
- "A ChatGPT login doesn't work through the gateway. Give the upstream a provider API key.",
+ "Codex can't sign in to the gateway with a ChatGPT login. To use a ChatGPT subscription, add CLIProxyAPI as the upstream, a setup OpenAI's Codex team has endorsed; otherwise give the upstream a provider API key.",
},
},
chat: {
@@ -240,7 +240,8 @@ const connect = {
description:
"If a conversation already gets memory from an OpenViking plugin, the gateway steps aside for it: no recall, no saving and no OpenViking tools, so memory isn't added twice. Other conversations are unaffected.",
detection:
- 'The gateway recognizes a plugin by the memory blocks it adds or its OpenViking tools. Integrations can also announce themselves with this header.',
+ 'The gateway recognizes a plugin by the memory blocks it adds to messages. Integrations can also announce themselves with this header.',
+ mcp: "OpenViking MCP tools alone don't count: the gateway still recalls and saves memory, and only stops offering its own OpenViking tools.",
restart:
"This lasts for the rest of the conversation. To use the gateway's memory again, start a new conversation without the plugin.",
},
diff --git a/web-studio/src/i18n/locales/en/gateway/enums.ts b/web-studio/src/i18n/locales/en/gateway/enums.ts
index 66ebacead..d8b4d8468 100644
--- a/web-studio/src/i18n/locales/en/gateway/enums.ts
+++ b/web-studio/src/i18n/locales/en/gateway/enums.ts
@@ -52,6 +52,7 @@ const enums = {
recalled: 'Memory added',
empty: 'Nothing relevant found',
disabled: 'Recall is off or the budget is used up',
+ budget: 'Too little budget left to add memory',
recall_timeout: 'Recall timed out',
},
toolSkipReason: {
diff --git a/web-studio/src/i18n/locales/en/gateway/overview.ts b/web-studio/src/i18n/locales/en/gateway/overview.ts
index bf7fd8215..661364090 100644
--- a/web-studio/src/i18n/locales/en/gateway/overview.ts
+++ b/web-studio/src/i18n/locales/en/gateway/overview.ts
@@ -114,7 +114,6 @@ const overview = {
none: 'No recalls yet',
},
},
- cacheDocs: 'Troubleshooting',
cacheMiss: {
title_one: '{{count}} long conversation keeps missing the prompt cache',
title_other: '{{count}} long conversations keep missing the prompt cache',
diff --git a/web-studio/src/i18n/locales/en/gateway/requests.ts b/web-studio/src/i18n/locales/en/gateway/requests.ts
index dd81ffd7a..be122ea57 100644
--- a/web-studio/src/i18n/locales/en/gateway/requests.ts
+++ b/web-studio/src/i18n/locales/en/gateway/requests.ts
@@ -90,6 +90,8 @@ const requests = {
'Summary of about {{tokens}} tokens written in {{duration}}',
compactionFailed:
'Compaction failed ({{reason}}), so the full history was sent',
+ compactionStillOver:
+ 'Summary kept, but usage is still at or above Compact at ({{reason}})',
window: 'Window {{number}}, managed by the model',
windowReset: 'The model started a new window',
saving: 'Saving to OpenViking',
diff --git a/web-studio/src/i18n/locales/zh-CN/gateway/common.ts b/web-studio/src/i18n/locales/zh-CN/gateway/common.ts
index 43709c59c..92c87bf8f 100644
--- a/web-studio/src/i18n/locales/zh-CN/gateway/common.ts
+++ b/web-studio/src/i18n/locales/zh-CN/gateway/common.ts
@@ -48,6 +48,11 @@ const common = {
done: '已复制到剪贴板',
failed: '复制失败,请选中文本后手动复制。',
},
+ docs: {
+ link: '文档',
+ learnMore: '了解更多',
+ troubleshoot: '排查说明',
+ },
access: {
title: '先连接 OpenViking',
invalid: 'OpenViking API 密钥无效',
@@ -68,7 +73,7 @@ const common = {
environment: '也可能设在环境变量里,它优先于配置文件:',
studio: 'Root 可以在“设置 → 服务端配置 → 文件编辑”中查看 ov.conf。',
reset: '实在找不到,就在原来的位置换一个至少 32 个字符的新密钥,然后重启。',
- resetDocs: '查看运维文档',
+ resetDocs: '如何重置',
keyPlaceholder: '<至少 32 个字符>',
session: '只保存在当前浏览器标签页,关闭后自动锁定。',
wrongKey: '这是网关密钥(给客户端用的),请输入网关管理密钥。',
@@ -80,7 +85,7 @@ const common = {
editing: '可修改上游和上下文配置',
expired: '网关管理密钥已失效,上游和上下文配置恢复为只读。',
readOnly:
- '上游和上下文配置由网关管理员统一提供。你可以查看、测试连接,并在签发密钥时选用。',
+ '上游和上下文配置由网关管理员统一提供。你可以查看,并在签发密钥时选用。',
adminReadOnly:
'OpenViking 的管理员和 Root 也需要网关管理密钥才能修改。如果这台服务是你部署的,密钥在 ov.conf 的 gateway.management_key 里。',
shared:
@@ -114,7 +119,6 @@ const common = {
fixLabel: '需要修改的配置',
terminal: '终端',
environment: '环境变量',
- docs: '部署说明',
enable: {
description: 'Studio 可以直接开启:把设置写入 ov.conf,然后重启服务。',
descriptionManualRestart:
diff --git a/web-studio/src/i18n/locales/zh-CN/gateway/connect.ts b/web-studio/src/i18n/locales/zh-CN/gateway/connect.ts
index fe0cd13ae..e8371ef27 100644
--- a/web-studio/src/i18n/locales/zh-CN/gateway/connect.ts
+++ b/web-studio/src/i18n/locales/zh-CN/gateway/connect.ts
@@ -99,7 +99,8 @@ const connect = {
'Codex 会先尝试 WebSocket 连接,网关拒绝后它会自动改用 HTTP。',
metadata:
'遇到不认识的模型名,Codex 可能提示缺少模型元数据,这个提示不影响请求。',
- login: 'ChatGPT 登录无法通过网关使用,请为上游配置服务商的 API Key。',
+ login:
+ 'Codex 不能用 ChatGPT 账号登录网关。想用 ChatGPT 订阅,可以把 CLIProxyAPI 添加为上游(OpenAI Codex 团队认可这种用法);否则请为上游配置服务商的 API Key。',
},
},
chat: {
@@ -232,7 +233,8 @@ const connect = {
description:
'如果某段对话已经通过 OpenViking 插件获得记忆,网关会让出这段对话:不召回、不保存,也不提供 OpenViking 工具,避免重复补充记忆。其他对话不受影响。',
detection:
- '网关根据插件注入的记忆块或 OpenViking 工具识别插件。集成方也可以通过这个请求头主动声明。',
+ '网关根据插件注入消息的记忆块识别插件。集成方也可以通过这个请求头主动声明。',
+ mcp: '只接入 OpenViking MCP 工具不算插件:网关照常召回和保存记忆,只是不再提供自己的 OpenViking 工具。',
restart:
'这个状态会持续到对话结束。要重新使用网关的记忆,请在不启用插件的情况下开始一段新对话。',
},
diff --git a/web-studio/src/i18n/locales/zh-CN/gateway/enums.ts b/web-studio/src/i18n/locales/zh-CN/gateway/enums.ts
index b9874540a..821dd034e 100644
--- a/web-studio/src/i18n/locales/zh-CN/gateway/enums.ts
+++ b/web-studio/src/i18n/locales/zh-CN/gateway/enums.ts
@@ -51,6 +51,7 @@ const enums = {
recalled: '已补充记忆',
empty: '没有找到相关内容',
disabled: '召回已关闭或预算已用完',
+ budget: '剩余预算不足,未补充记忆',
recall_timeout: '召回超时',
},
toolSkipReason: {
diff --git a/web-studio/src/i18n/locales/zh-CN/gateway/overview.ts b/web-studio/src/i18n/locales/zh-CN/gateway/overview.ts
index 5ca8c7516..5d169a65c 100644
--- a/web-studio/src/i18n/locales/zh-CN/gateway/overview.ts
+++ b/web-studio/src/i18n/locales/zh-CN/gateway/overview.ts
@@ -108,7 +108,6 @@ const overview = {
none: '还没有召回',
},
},
- cacheDocs: '排查说明',
cacheMiss: {
title_one: '有 {{count}} 段长对话连续没有命中提示词缓存',
title_other: '有 {{count}} 段长对话连续没有命中提示词缓存',
diff --git a/web-studio/src/i18n/locales/zh-CN/gateway/requests.ts b/web-studio/src/i18n/locales/zh-CN/gateway/requests.ts
index 70ad84eb2..d5129e749 100644
--- a/web-studio/src/i18n/locales/zh-CN/gateway/requests.ts
+++ b/web-studio/src/i18n/locales/zh-CN/gateway/requests.ts
@@ -84,6 +84,7 @@ const requests = {
compactionApplied: '发送时较早的历史已被替换',
compactionWritten: '生成了约 {{tokens}} Token 的摘要,用时 {{duration}}',
compactionFailed: '压缩失败({{reason}}),已发送完整历史',
+ compactionStillOver: '摘要已保留,但用量仍达到压缩时机({{reason}})',
window: '第 {{number}} 个窗口,由模型管理',
windowReset: '模型开启了新窗口',
saving: '保存到 OpenViking',
diff --git a/web-studio/src/routes/gateway/-components/access-notices.tsx b/web-studio/src/routes/gateway/-components/access-notices.tsx
index 6e265aa1d..e1c49901f 100644
--- a/web-studio/src/routes/gateway/-components/access-notices.tsx
+++ b/web-studio/src/routes/gateway/-components/access-notices.tsx
@@ -1,10 +1,10 @@
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { Button } from '#/components/ui/button'
-import { gatewayDocsUrl } from '../-lib/client-guides'
import { requestManagementUnlock } from '../-lib/management-key'
import { useGateway } from '../-lib/use-gateway'
import { CodeBlock } from './code-block'
+import { DocsLink } from './docs-link'
import { Notice } from './notice'
const GENERATE_KEY_COMMAND = 'openssl rand -base64 32'
@@ -24,7 +24,7 @@ export function ManagementUnlockButton() {
}
export function AccessNotices({ objectsTab }: { objectsTab: boolean }) {
- const { t, i18n } = useTranslation('gateway')
+ const { t } = useTranslation('gateway')
const { access, connection, readOnly } = useGateway()
const dismissedKey = `gateway-public-warning:${connection.baseUrl}`
const [dismissed, setDismissed] = React.useState(() => {
@@ -51,20 +51,7 @@ export function AccessNotices({ objectsTab }: { objectsTab: boolean }) {
title={t('management.publicTitle')}
action={
<div className="flex gap-2">
- <Button
- size="sm"
- variant="outline"
- nativeButton={false}
- render={
- <a
- href={gatewayDocsUrl('operations', i18n.resolvedLanguage)}
- target="_blank"
- rel="noreferrer"
- />
- }
- >
- {t('unavailable.docs')}
- </Button>
+ <DocsLink section="publicService">{t('docs.learnMore')}</DocsLink>
<Button size="sm" variant="ghost" onClick={dismiss}>
{t('management.dismiss')}
</Button>
@@ -84,7 +71,10 @@ export function AccessNotices({ objectsTab }: { objectsTab: boolean }) {
{objectsTab && access?.managed ? (
readOnly ? (
<Notice tone="info" action={<ManagementUnlockButton />}>
- <p>{t('management.readOnly')}</p>
+ <p>
+ {t('management.readOnly')}{' '}
+ <DocsLink section="studioAccess" variant="text" />
+ </p>
{['admin', 'root'].includes(access.role) ? (
<p>{t('management.adminReadOnly')}</p>
) : null}
diff --git a/web-studio/src/routes/gateway/-components/connect-page.test.tsx b/web-studio/src/routes/gateway/-components/connect-page.test.tsx
index 79ac40ecd..27454347a 100644
--- a/web-studio/src/routes/gateway/-components/connect-page.test.tsx
+++ b/web-studio/src/routes/gateway/-components/connect-page.test.tsx
@@ -203,7 +203,29 @@ describe('ConnectPage', () => {
expect(screen.getByText('https://gw.example.com/gateway/v1')).toBeTruthy()
expect(screen.queryByText(/public_url/)).toBeNull()
expect(linkTo('Manage keys')).toBe('/gateway/keys')
- expect(linkTo('Full guide')).toBe(gatewayDocsUrl('guide', 'en'))
+ expect(linkTo('Full guide')).toBe(gatewayDocsUrl('claudeCode', 'en'))
+ // Each reference card links its docs section.
+ expect(
+ screen
+ .getAllByText('Learn more')
+ .map((node) => node.closest('a')?.getAttribute('href')),
+ ).toEqual([
+ gatewayDocsUrl('conversations', 'en'),
+ gatewayDocsUrl('providerKey', 'en'),
+ gatewayDocsUrl('pluginDetected', 'en'),
+ ])
+ })
+
+ it('tells plugins apart from OpenViking MCP tools', async () => {
+ renderPage()
+ expect(
+ await screen.findByText(
+ 'The gateway recognizes a plugin by the memory blocks it adds to messages. Integrations can also announce themselves with this header.',
+ ),
+ ).toBeTruthy()
+ expect(
+ screen.getByText(/^OpenViking MCP tools alone don't count/),
+ ).toBeTruthy()
})
it.each([
@@ -225,6 +247,10 @@ describe('ConnectPage', () => {
renderPage()
expect(await screen.findByText(title)).toBeTruthy()
expect(screen.getAllByText('gateway.public_url')).toHaveLength(1)
+ const docs = within(screen.getByText(title).parentElement as HTMLElement)
+ expect(
+ docs.getByText('Learn more').closest('a')?.getAttribute('href'),
+ ).toBe(gatewayDocsUrl('publicAddress', 'en'))
})
it('points a standalone gateway at gateway.conf instead of ov.conf', async () => {
@@ -289,6 +315,8 @@ describe('ConnectPage', () => {
).toBeTruthy()
expect(screen.queryByText(/^Add an upstream for/)).toBeNull()
expect(screen.getByText('<model>')).toBeTruthy()
+ // The full guide opens the picked client's section.
+ expect(linkTo('Full guide')).toBe(gatewayDocsUrl('codex', 'en'))
})
it('falls back to Claude Code for an unknown client', async () => {
diff --git a/web-studio/src/routes/gateway/-components/connect-page.tsx b/web-studio/src/routes/gateway/-components/connect-page.tsx
index c914f539e..802e13f9c 100644
--- a/web-studio/src/routes/gateway/-components/connect-page.tsx
+++ b/web-studio/src/routes/gateway/-components/connect-page.tsx
@@ -1,11 +1,6 @@
import type * as React from 'react'
import { Link, getRouteApi } from '@tanstack/react-router'
-import {
- ExternalLinkIcon,
- KeyRoundIcon,
- MessagesSquareIcon,
- PuzzleIcon,
-} from 'lucide-react'
+import { KeyRoundIcon, MessagesSquareIcon, PuzzleIcon } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Button } from '#/components/ui/button'
@@ -19,11 +14,8 @@ import {
import { useAppConnection } from '#/hooks/use-app-connection'
import type { ConnectionInfo, Upstream } from '../-lib/api'
-import {
- CLIENT_IDS,
- SESSION_HEADERS,
- gatewayDocsUrl,
-} from '../-lib/client-guides'
+import { CLIENT_DOCS, CLIENT_IDS, SESSION_HEADERS } from '../-lib/client-guides'
+import type { DocsSection } from '../-lib/client-guides'
import { isLoopbackUrl } from '../-lib/format'
import { authModeLabel } from '../-lib/localize'
import { UPSTREAM_KEY_HEADER } from '../-lib/upstream-schema'
@@ -32,6 +24,7 @@ import { CodeBlock } from './code-block'
import { ClientGuide } from './connect-client-guide'
import { CodeText } from './connect-text'
import { CopyButton } from './copy-button'
+import { DocsLink } from './docs-link'
import { LoadingState } from './empty-state'
import { Notice } from './notice'
import { SectionHeader } from './section-header'
@@ -53,7 +46,7 @@ const PLUGIN_HEADER_EXAMPLE = 'X-OpenViking-Plugin: <plugin-name>'
* `?protocol=` the protocol for clients set up per protocol).
*/
export function ConnectPage() {
- const { t, i18n } = useTranslation('gateway')
+ const { t } = useTranslation('gateway')
const { client = CLIENT_IDS[0], protocol } = route.useSearch()
const info = useConnectionInfo()
const upstreams = useUpstreams()
@@ -63,21 +56,9 @@ export function ConnectPage() {
<SectionHeader
description={t('connect.description')}
actions={
- <Button
- variant="outline"
- size="sm"
- nativeButton={false}
- render={
- <a
- href={gatewayDocsUrl('guide', i18n.resolvedLanguage)}
- target="_blank"
- rel="noreferrer"
- />
- }
- >
- <ExternalLinkIcon />
+ <DocsLink section={CLIENT_DOCS[client]}>
{t('connect.fullGuide')}
- </Button>
+ </DocsLink>
}
/>
{info.data ? (
@@ -131,7 +112,13 @@ function AddressCard({ info }: { info: ConnectionInfo }) {
/>
</dl>
{warning ? (
- <Notice tone="warning" title={t(`connect.address.${warning}.title`)}>
+ <Notice
+ tone="warning"
+ title={t(`connect.address.${warning}.title`)}
+ action={
+ <DocsLink section="publicAddress">{t('docs.learnMore')}</DocsLink>
+ }
+ >
<p>
<CodeText
text={t(
@@ -184,11 +171,14 @@ function ReferenceCard({
icon,
title,
description,
+ docs,
children,
}: {
icon: React.ReactNode
title: string
description: React.ReactNode
+ /** Docs section with the details, linked under the content. */
+ docs: DocsSection
children: React.ReactNode
}) {
return (
@@ -206,6 +196,9 @@ function ReferenceCard({
</CardHeader>
<CardContent className="grid content-start gap-3 text-sm leading-6 text-muted-foreground">
{children}
+ <p>
+ <DocsLink section={docs} variant="text" />
+ </p>
</CardContent>
</Card>
)
@@ -218,6 +211,7 @@ function IdentityCard() {
icon={<MessagesSquareIcon />}
title={t('connect.identity.title')}
description={t('connect.identity.description')}
+ docs="conversations"
>
<ol className="grid gap-1">
{SESSION_HEADERS.map((header, index) => (
@@ -250,6 +244,7 @@ function PassthroughCard({ upstreams }: { upstreams?: Upstream[] }) {
description={t('connect.passthrough.description', {
mode: authModeLabel(t, 'passthrough'),
})}
+ docs="providerKey"
>
<CodeBlock code={UPSTREAM_KEY_EXAMPLE} wrap />
<p>{t('connect.passthrough.note')}</p>
@@ -273,9 +268,11 @@ function PluginCard() {
icon={<PuzzleIcon />}
title={t('connect.plugin.title')}
description={t('connect.plugin.description')}
+ docs="pluginDetected"
>
<p>{t('connect.plugin.detection')}</p>
<CodeBlock code={PLUGIN_HEADER_EXAMPLE} wrap />
+ <p>{t('connect.plugin.mcp')}</p>
<p>{t('connect.plugin.restart')}</p>
</ReferenceCard>
)
diff --git a/web-studio/src/routes/gateway/-components/docs-link.tsx b/web-studio/src/routes/gateway/-components/docs-link.tsx
new file mode 100644
index 000000000..6168aeaad
--- /dev/null
+++ b/web-studio/src/routes/gateway/-components/docs-link.tsx
@@ -0,0 +1,56 @@
+import type * as React from 'react'
+import { ExternalLinkIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+
+import { Button } from '#/components/ui/button'
+import { cn } from '#/lib/utils'
+
+import { gatewayDocsUrl } from '../-lib/client-guides'
+import type { DocsSection } from '../-lib/client-guides'
+
+type DocsLinkProps = {
+ section: DocsSection
+ /** Defaults to "Docs" for a button and "Learn more" for text. */
+ children?: React.ReactNode
+ /** An outline button for actions, or a link inside running text. */
+ variant?: 'button' | 'text'
+ className?: string
+}
+
+/** Opens a section of the gateway docs, in the UI language, in a new tab. */
+export function DocsLink({
+ section,
+ children,
+ variant = 'button',
+ className,
+}: DocsLinkProps) {
+ const { t, i18n } = useTranslation('gateway')
+ const href = gatewayDocsUrl(section, i18n.resolvedLanguage)
+ if (variant === 'text')
+ return (
+ <a
+ href={href}
+ target="_blank"
+ rel="noreferrer"
+ className={cn(
+ 'inline-flex items-center gap-1 font-medium text-foreground underline underline-offset-4',
+ className,
+ )}
+ >
+ {children ?? t('docs.learnMore')}
+ <ExternalLinkIcon aria-hidden className="size-3" />
+ </a>
+ )
+ return (
+ <Button
+ size="sm"
+ variant="outline"
+ className={className}
+ nativeButton={false}
+ render={<a href={href} target="_blank" rel="noreferrer" />}
+ >
+ <ExternalLinkIcon />
+ {children ?? t('docs.link')}
+ </Button>
+ )
+}
diff --git a/web-studio/src/routes/gateway/-components/gateway-enable.test.tsx b/web-studio/src/routes/gateway/-components/gateway-enable.test.tsx
index eb0768197..2c739b3cd 100644
--- a/web-studio/src/routes/gateway/-components/gateway-enable.test.tsx
+++ b/web-studio/src/routes/gateway/-components/gateway-enable.test.tsx
@@ -22,6 +22,7 @@ import type * as ConfigFileApi from '#/routes/settings/-lib/config-file-api'
import { GatewayError } from '../-lib/api'
import type * as Api from '../-lib/api'
import type { GatewayConnection } from '../-lib/api'
+import { gatewayDocsUrl } from '../-lib/client-guides'
import { getManagementKey } from '../-lib/management-key'
import { GatewayLayout } from './gateway-layout'
@@ -333,6 +334,9 @@ describe('enabling the gateway from Studio', () => {
expect(
screen.queryByRole('button', { name: 'unavailable.enable.action' }),
).toBeNull()
+ expect(
+ screen.getByText('docs.link').closest('a')?.getAttribute('href'),
+ ).toBe(gatewayDocsUrl('enableGateway', 'en'))
})
it('reports a rejected configuration that the server rolled back', async () => {
@@ -382,5 +386,8 @@ describe('enabling the gateway from Studio', () => {
await screen.findByText('unavailable.notEnabled.description'),
).toBeTruthy()
expect(screen.getByText(/"enabled":true/)).toBeTruthy()
+ expect(
+ screen.getByText('docs.link').closest('a')?.getAttribute('href'),
+ ).toBe(gatewayDocsUrl('enableGateway', 'en'))
})
})
diff --git a/web-studio/src/routes/gateway/-components/gateway-enable.tsx b/web-studio/src/routes/gateway/-components/gateway-enable.tsx
index 778b8a212..ce2d4ace2 100644
--- a/web-studio/src/routes/gateway/-components/gateway-enable.tsx
+++ b/web-studio/src/routes/gateway/-components/gateway-enable.tsx
@@ -23,6 +23,7 @@ import {
import { setManagementKey } from '../-lib/management-key'
import { CodeBlock } from './code-block'
import { ConfirmDialog } from './confirm-dialog'
+import { DocsLink } from './docs-link'
import { Notice } from './notice'
import { SetupCard } from './setup-card'
@@ -227,7 +228,12 @@ export function EnableGatewayCard({
<SetupCard
title={t('unavailable.notEnabled.title')}
description={t('unavailable.enable.readOnly')}
- actions={retry}
+ actions={
+ <>
+ {retry}
+ <DocsLink section="enableGateway" />
+ </>
+ }
>
<CodeBlock
label={t('unavailable.environment')}
diff --git a/web-studio/src/routes/gateway/-components/gateway-unavailable.tsx b/web-studio/src/routes/gateway/-components/gateway-unavailable.tsx
index 748656851..76fde011d 100644
--- a/web-studio/src/routes/gateway/-components/gateway-unavailable.tsx
+++ b/web-studio/src/routes/gateway/-components/gateway-unavailable.tsx
@@ -6,6 +6,7 @@ import { useAppConnection } from '#/hooks/use-app-connection'
import type { GatewayError } from '../-lib/api'
import { gatewayErrorMessage } from '../-lib/localize'
import { CodeBlock } from './code-block'
+import { DocsLink } from './docs-link'
import { EnableGatewayCard } from './gateway-enable'
import { SetupCard } from './setup-card'
@@ -54,6 +55,13 @@ export function GatewayUnavailable({
{t('actions.retry')}
</Button>
)
+ // For the cards that ask whoever runs the server to change something.
+ const fix = (
+ <>
+ {retry}
+ <DocsLink section="setupCard">{t('docs.troubleshoot')}</DocsLink>
+ </>
+ )
if (error.status === 401 && error.reason !== 'management_key_invalid')
return <GatewayConnect invalid />
if (error.reason === 'not_enabled' || error.status === 404) {
@@ -69,7 +77,12 @@ export function GatewayUnavailable({
<SetupCard
title={t('unavailable.notEnabled.title')}
description={t('unavailable.notEnabled.description')}
- actions={retry}
+ actions={
+ <>
+ {retry}
+ <DocsLink section="enableGateway" />
+ </>
+ }
>
<CodeBlock
label={t('unavailable.terminal')}
@@ -94,7 +107,7 @@ export function GatewayUnavailable({
<SetupCard
title={t('unavailable.trusted.title')}
description={t('unavailable.trusted.description')}
- actions={retry}
+ actions={fix}
>
<CodeBlock
label={CONFIG_FILE}
@@ -110,14 +123,14 @@ export function GatewayUnavailable({
url: openvikingUrl,
})}
description={t('unavailable.openvikingUnreachable.description')}
- actions={retry}
+ actions={fix}
/>
)
return (
<SetupCard
title={t('unavailable.failed.title')}
description={gatewayErrorMessage(t, error)}
- actions={retry}
+ actions={fix}
/>
)
}
diff --git a/web-studio/src/routes/gateway/-components/keys-dialogs.test.tsx b/web-studio/src/routes/gateway/-components/keys-dialogs.test.tsx
index 687294149..1cf8c32d5 100644
--- a/web-studio/src/routes/gateway/-components/keys-dialogs.test.tsx
+++ b/web-studio/src/routes/gateway/-components/keys-dialogs.test.tsx
@@ -8,12 +8,14 @@ import {
render,
screen,
waitFor,
+ within,
} from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { GatewayError } from '../-lib/api'
import type * as Api from '../-lib/api'
import type { IssuedKey, KeyUser, Profile, Upstream } from '../-lib/api'
+import { gatewayDocsUrl } from '../-lib/client-guides'
import type { Translate } from '../-lib/localize'
import { PROFILE_DEFAULTS } from '../-lib/profile-schema'
import { UPSTREAM_DEFAULTS } from '../-lib/upstream-schema'
@@ -721,6 +723,11 @@ describe('KeysIssueDialog', () => {
const alert = await screen.findByRole('alert')
expect(alert.textContent).toContain('keys.errors.title')
expect(alert.textContent).toContain('keys.errors.unavailable')
+ expect(
+ within(alert)
+ .getByRole('link', { name: 'docs.troubleshoot' })
+ .getAttribute('href'),
+ ).toBe(gatewayDocsUrl('issueKeyFails', 'en'))
})
})
diff --git a/web-studio/src/routes/gateway/-components/keys-issue-dialog.tsx b/web-studio/src/routes/gateway/-components/keys-issue-dialog.tsx
index 67de8d4ce..8b63130ee 100644
--- a/web-studio/src/routes/gateway/-components/keys-issue-dialog.tsx
+++ b/web-studio/src/routes/gateway/-components/keys-issue-dialog.tsx
@@ -47,6 +47,7 @@ import { requestManagementUnlock } from '../-lib/management-key'
import { NEW_ID } from '../-lib/search'
import { servedModels } from '../-lib/upstream-schema'
import { useGateway, useKeyUsers } from '../-lib/use-gateway'
+import { DocsLink } from './docs-link'
import { SettingField } from './setting-field'
import { ProtocolBadge, ToneBadge } from './status-badges'
import { TagInput } from './tag-input'
@@ -616,7 +617,12 @@ export function KeysIssueDialog({
<Alert variant="destructive">
<CircleAlertIcon />
<AlertTitle>{t('keys.errors.title')}</AlertTitle>
- <AlertDescription>{problem.message}</AlertDescription>
+ <AlertDescription>
+ {problem.message}{' '}
+ <DocsLink section="issueKeyFails" variant="text">
+ {t('docs.troubleshoot')}
+ </DocsLink>
+ </AlertDescription>
</Alert>
) : null}
</form>
diff --git a/web-studio/src/routes/gateway/-components/keys-page.test.tsx b/web-studio/src/routes/gateway/-components/keys-page.test.tsx
index e1c46c605..7e40376ff 100644
--- a/web-studio/src/routes/gateway/-components/keys-page.test.tsx
+++ b/web-studio/src/routes/gateway/-components/keys-page.test.tsx
@@ -14,6 +14,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as Api from '../-lib/api'
import type { GatewayKey, IssuedKey, Profile, Upstream } from '../-lib/api'
+import { gatewayDocsUrl } from '../-lib/client-guides'
import { PROFILE_DEFAULTS } from '../-lib/profile-schema'
import { UPSTREAM_DEFAULTS } from '../-lib/upstream-schema'
import { KeysPage } from './keys-page'
@@ -194,6 +195,9 @@ describe('KeysPage', () => {
expect(within(rows[2]).getByText('CI bot')).toBeTruthy()
expect(within(rows[2]).getByText('keys.missing')).toBeTruthy()
expect(within(rows[2]).getByText('deepseek-chat')).toBeTruthy()
+ expect(
+ screen.getByText('docs.link').closest('a')?.getAttribute('href'),
+ ).toBe(gatewayDocsUrl('keys', 'en'))
})
it('revokes a key after confirmation', async () => {
diff --git a/web-studio/src/routes/gateway/-components/keys-page.tsx b/web-studio/src/routes/gateway/-components/keys-page.tsx
index d68f6273a..afbae8766 100644
--- a/web-studio/src/routes/gateway/-components/keys-page.tsx
+++ b/web-studio/src/routes/gateway/-components/keys-page.tsx
@@ -47,6 +47,7 @@ import {
useUpstreams,
} from '../-lib/use-gateway'
import { ConfirmDialog } from './confirm-dialog'
+import { DocsLink } from './docs-link'
import { EmptyState, ErrorState, LoadingState } from './empty-state'
import { ExplainedButton } from './explained-button'
import { KeysIssueDialog } from './keys-issue-dialog'
@@ -200,6 +201,7 @@ export function KeysPage() {
description={t('keys.description')}
actions={
<>
+ <DocsLink section="keys" />
<Button
type="button"
variant="outline"
diff --git a/web-studio/src/routes/gateway/-components/management-key-dialog.test.tsx b/web-studio/src/routes/gateway/-components/management-key-dialog.test.tsx
index c2a7c461d..fd34be6f5 100644
--- a/web-studio/src/routes/gateway/-components/management-key-dialog.test.tsx
+++ b/web-studio/src/routes/gateway/-components/management-key-dialog.test.tsx
@@ -64,7 +64,7 @@ function open() {
)
requestManagementUnlock()
}
-it('explains where to find a lost key and links to the operations guide', async () => {
+it('explains where to find a lost key and links to how to reset it', async () => {
open()
fireEvent.click(await screen.findByText('management.where'))
expect(screen.getByText('management.studio')).toBeTruthy()
@@ -73,7 +73,7 @@ it('explains where to find a lost key and links to the operations guide', async
screen
.getByRole('link', { name: 'management.resetDocs' })
.getAttribute('href'),
- ).toBe(gatewayDocsUrl('operations', 'en'))
+ ).toBe(gatewayDocsUrl('lostManagementKey', 'en'))
})
it('rejects client keys in the management field without sending them', async () => {
open()
diff --git a/web-studio/src/routes/gateway/-components/management-key-dialog.tsx b/web-studio/src/routes/gateway/-components/management-key-dialog.tsx
index 6ee80bab9..f58c029ad 100644
--- a/web-studio/src/routes/gateway/-components/management-key-dialog.tsx
+++ b/web-studio/src/routes/gateway/-components/management-key-dialog.tsx
@@ -13,13 +13,13 @@ import {
DialogFooter,
} from '#/components/ui/dialog'
import { getAccess, toGatewayError } from '../-lib/api'
-import { gatewayDocsUrl } from '../-lib/client-guides'
import {
MANAGEMENT_UNLOCK_EVENT,
setManagementKey,
} from '../-lib/management-key'
import { useGateway } from '../-lib/use-gateway'
import { gatewayErrorMessage } from '../-lib/localize'
+import { DocsLink } from './docs-link'
import { SettingField } from './setting-field'
const MANAGEMENT_CONFIGS = [
@@ -28,7 +28,7 @@ const MANAGEMENT_CONFIGS = [
]
export function ManagementKeyDialog() {
- const { t, i18n } = useTranslation('gateway')
+ const { t } = useTranslation('gateway')
const { connection } = useGateway()
const [open, setOpen] = React.useState(false)
const [key, setKey] = React.useState('')
@@ -96,14 +96,9 @@ export function ManagementKeyDialog() {
<li>{t('management.prefix')}</li>
<li>
{t('management.reset')}{' '}
- <a
- href={gatewayDocsUrl('operations', i18n.resolvedLanguage)}
- target="_blank"
- rel="noreferrer"
- className="font-medium text-foreground underline underline-offset-4"
- >
+ <DocsLink section="lostManagementKey" variant="text">
{t('management.resetDocs')}
- </a>
+ </DocsLink>
</li>
</ul>
</details>
diff --git a/web-studio/src/routes/gateway/-components/memory-cell.tsx b/web-studio/src/routes/gateway/-components/memory-cell.tsx
index 060c5eb67..449cadb98 100644
--- a/web-studio/src/routes/gateway/-components/memory-cell.tsx
+++ b/web-studio/src/routes/gateway/-components/memory-cell.tsx
@@ -8,7 +8,7 @@ import { recallReasonLabel } from '../-lib/localize'
import { EmptyValue } from './status-badges'
/** Recall outcomes that are not failures. */
-const RECALL_OUTCOMES = new Set(['recalled', 'empty', 'disabled'])
+const RECALL_OUTCOMES = new Set(['recalled', 'empty', 'disabled', 'budget'])
/** A recall that failed, as opposed to finding nothing or being off. */
export function recallFailed(record: LogRecord): boolean {
diff --git a/web-studio/src/routes/gateway/-components/overview-cache.tsx b/web-studio/src/routes/gateway/-components/overview-cache.tsx
index 52f100713..57615a023 100644
--- a/web-studio/src/routes/gateway/-components/overview-cache.tsx
+++ b/web-studio/src/routes/gateway/-components/overview-cache.tsx
@@ -1,8 +1,6 @@
-import { ExternalLinkIcon, LightbulbIcon } from 'lucide-react'
+import { LightbulbIcon } from 'lucide-react'
import { useTranslation } from 'react-i18next'
-import { Button } from '#/components/ui/button'
-
import type { CacheAlerts, CacheMiss, Upstream } from '../-lib/api'
import {
formatCompact,
@@ -10,8 +8,8 @@ import {
formatRelativeTime,
shortenId,
} from '../-lib/format'
-import { gatewayDocsUrl } from '../-lib/client-guides'
import { useUpstreams } from '../-lib/use-gateway'
+import { DocsLink } from './docs-link'
import { Notice } from './notice'
/** Upstream name, or its shortened id once deleted or not yet loaded. */
@@ -64,21 +62,7 @@ export function CacheNotices({ alerts }: { alerts: CacheAlerts }) {
const upstreams = useUpstreams().data
const { misses, unreported } = alerts
const docs = (
- <Button
- size="sm"
- variant="outline"
- nativeButton={false}
- render={
- <a
- href={gatewayDocsUrl('operations', locale, 'cacheHitRate')}
- target="_blank"
- rel="noreferrer"
- />
- }
- >
- <ExternalLinkIcon />
- {t('overview.cacheDocs')}
- </Button>
+ <DocsLink section="cacheHitRate">{t('docs.troubleshoot')}</DocsLink>
)
return (
<div className="grid gap-3">
diff --git a/web-studio/src/routes/gateway/-components/overview-page.test.tsx b/web-studio/src/routes/gateway/-components/overview-page.test.tsx
index fcb7cc14d..0a9651fce 100644
--- a/web-studio/src/routes/gateway/-components/overview-page.test.tsx
+++ b/web-studio/src/routes/gateway/-components/overview-page.test.tsx
@@ -220,6 +220,13 @@ function hrefOf(text: string) {
return screen.getByText(text).closest('a')?.getAttribute('href')
}
+/** Hrefs of every link with this text, in page order. */
+function hrefsOf(text: string) {
+ return screen
+ .getAllByText(text)
+ .map((node) => node.closest('a')?.getAttribute('href'))
+}
+
function renderOverview() {
const root = createRootRoute({ component: Outlet })
const router = createRouter({
@@ -384,6 +391,13 @@ describe('OverviewPage', () => {
'/gateway/requests?filter=issues',
'/gateway/requests?filter=issues',
])
+ // Each problem links the docs section that troubleshoots it.
+ expect(hrefsOf('Troubleshooting')).toEqual([
+ gatewayDocsUrl('openvikingDegraded', 'en'),
+ gatewayDocsUrl('notSaved', 'en'),
+ gatewayDocsUrl('degradedRequests', 'en'),
+ ])
+ expect(hrefOf('Docs')).toBe(gatewayDocsUrl('overview', 'en'))
const reasons = screen
.getAllByText(/^(Upstream switched|OpenViking plugin in use)$/, {
@@ -460,9 +474,9 @@ describe('OverviewPage', () => {
'deadbeefcafe0001',
)
expect(screen.queryByText(/cache hits lately/)).toBeNull()
- expect(
- screen.getByText('Troubleshooting').closest('a')?.getAttribute('href'),
- ).toBe(gatewayDocsUrl('operations', 'en', 'cacheHitRate'))
+ expect(hrefsOf('Troubleshooting')).toContain(
+ gatewayDocsUrl('cacheHitRate', 'en'),
+ )
})
it('points Anthropic conversations that never write the cache at cache_control', async () => {
@@ -643,6 +657,7 @@ describe('OverviewPage quick mode', () => {
).toBeTruthy()
expect(screen.getByText('Context profile: use “Default”')).toBeTruthy()
expect(screen.getByText('Or set up step by step')).toBeTruthy()
+ expect(hrefsOf('Learn more')).toContain(gatewayDocsUrl('quickMode', 'en'))
api.listKeys.mockResolvedValue([ISSUED])
fireEvent.click(await quickButton())
diff --git a/web-studio/src/routes/gateway/-components/overview-page.tsx b/web-studio/src/routes/gateway/-components/overview-page.tsx
index 0d2c5b685..e46b0be4f 100644
--- a/web-studio/src/routes/gateway/-components/overview-page.tsx
+++ b/web-studio/src/routes/gateway/-components/overview-page.tsx
@@ -28,6 +28,7 @@ import {
useLogs,
useOverview,
} from '../-lib/use-gateway'
+import { DocsLink } from './docs-link'
import { ErrorState, LoadingState } from './empty-state'
import { MetricCard } from './metric-card'
import { CacheNotices } from './overview-cache'
@@ -150,6 +151,7 @@ export function OverviewPage() {
description={t('overview.description')}
actions={
<>
+ <DocsLink section="overview" />
{overview.dataUpdatedAt ? (
<span className="text-xs text-muted-foreground tabular-nums">
{t('states.updatedAt', {
diff --git a/web-studio/src/routes/gateway/-components/overview-quick-start.tsx b/web-studio/src/routes/gateway/-components/overview-quick-start.tsx
index 2f09fdcb2..1cf21dcc9 100644
--- a/web-studio/src/routes/gateway/-components/overview-quick-start.tsx
+++ b/web-studio/src/routes/gateway/-components/overview-quick-start.tsx
@@ -30,6 +30,7 @@ import type { QuickPlan } from '../-lib/quick-start'
import { servedModels } from '../-lib/upstream-schema'
import { useGateway } from '../-lib/use-gateway'
import { ManagementUnlockButton } from './access-notices'
+import { DocsLink } from './docs-link'
import { issueProblem } from './keys-issue-dialog'
import { Notice } from './notice'
import { ImportResultNotice } from './upstreams-page'
@@ -158,7 +159,8 @@ export function OverviewQuickStart({
{t('overview.quick.title')}
</p>
<p className="text-sm text-muted-foreground">
- {t('overview.quick.description')}
+ {t('overview.quick.description')}{' '}
+ <DocsLink section="quickMode" variant="text" />
</p>
</div>
<ul className="grid list-inside list-disc gap-0.5 text-sm text-muted-foreground">
diff --git a/web-studio/src/routes/gateway/-components/overview-status.tsx b/web-studio/src/routes/gateway/-components/overview-status.tsx
index 1300f894e..20c04d98e 100644
--- a/web-studio/src/routes/gateway/-components/overview-status.tsx
+++ b/web-studio/src/routes/gateway/-components/overview-status.tsx
@@ -15,6 +15,7 @@ import {
import type { OpenVikingHealth, Overview } from '../-lib/api'
import { formatNumber } from '../-lib/format'
import { degradationInfo, healthReasonLabel } from '../-lib/localize'
+import { DocsLink } from './docs-link'
import { EmptyState } from './empty-state'
import { Notice } from './notice'
import { EmptyValue, HealthBadge, ToneBadge } from './status-badges'
@@ -45,7 +46,12 @@ function SavingStatus({ issues }: { issues: Overview['capture_issues'] }) {
<p className="text-sm font-medium">{t('overview.saving.title')}</p>
{retrying > 0 || paused > 0 ? (
<>
- <Notice tone="warning">
+ <Notice
+ tone="warning"
+ action={
+ <DocsLink section="notSaved">{t('docs.troubleshoot')}</DocsLink>
+ }
+ >
{retrying > 0 ? (
<p>{t('overview.saving.retrying', { count: retrying })}</p>
) : null}
@@ -104,6 +110,11 @@ export function OpenVikingCard({
<Notice
tone="danger"
title={reason ? healthReasonLabel(t, reason) : undefined}
+ action={
+ <DocsLink section="openvikingDegraded">
+ {t('docs.troubleshoot')}
+ </DocsLink>
+ }
>
<p className="text-foreground/80">
{t('overview.openviking.unreachable')}
@@ -112,7 +123,8 @@ export function OpenVikingCard({
) : null}
{status === 'starting' ? (
<p className="text-sm leading-6 text-muted-foreground">
- {t('overview.openviking.starting')}
+ {t('overview.openviking.starting')}{' '}
+ <DocsLink section="openvikingDegraded" variant="text" />
</p>
) : null}
<SavingStatus issues={captureIssues} />
@@ -137,7 +149,10 @@ export function DegradedRequestsCard({
<CardTitle>{t('overview.degraded.title')}</CardTitle>
<CardDescription>{t('overview.degraded.description')}</CardDescription>
{entries.length > 0 ? (
- <CardAction>
+ <CardAction className="flex flex-wrap justify-end gap-1">
+ <DocsLink section="degradedRequests">
+ {t('docs.troubleshoot')}
+ </DocsLink>
<IssuesLink />
</CardAction>
) : null}
diff --git a/web-studio/src/routes/gateway/-components/profiles-page.tsx b/web-studio/src/routes/gateway/-components/profiles-page.tsx
index 5113711a9..f83d153ea 100644
--- a/web-studio/src/routes/gateway/-components/profiles-page.tsx
+++ b/web-studio/src/routes/gateway/-components/profiles-page.tsx
@@ -34,6 +34,7 @@ import { offeredTools, toProfileSettings } from '../-lib/profile-schema'
import { NEW_ID } from '../-lib/search'
import { useGateway, useKeys, useProfiles, useTools } from '../-lib/use-gateway'
import { ConfirmDialog } from './confirm-dialog'
+import { DocsLink } from './docs-link'
import { EmptyState, ErrorState, LoadingState } from './empty-state'
import { ExplainedButton } from './explained-button'
import { PROFILE_SECTIONS, isSectionOn } from './profiles-settings'
@@ -313,6 +314,7 @@ export function ProfilesPage() {
description={t('profiles.description')}
actions={
<>
+ <DocsLink section="profiles" />
<Button
type="button"
variant="outline"
diff --git a/web-studio/src/routes/gateway/-components/profiles-pages.test.tsx b/web-studio/src/routes/gateway/-components/profiles-pages.test.tsx
index 6abbe96d8..96806b780 100644
--- a/web-studio/src/routes/gateway/-components/profiles-pages.test.tsx
+++ b/web-studio/src/routes/gateway/-components/profiles-pages.test.tsx
@@ -28,6 +28,7 @@ import type {
Profile,
ProfileSettings,
} from '../-lib/api'
+import { gatewayDocsUrl } from '../-lib/client-guides'
import { PROFILE_DEFAULTS, WRITE_TOOLS } from '../-lib/profile-schema'
import { parseProfileEditorSearch } from '../-lib/search'
import { ProfilesPage } from './profiles-page'
@@ -194,6 +195,12 @@ const saveButton = () =>
})
const nameInput = () =>
screen.getByLabelText<HTMLInputElement>('profiles.name.label')
+/** Hrefs of every link with this text (Base UI gives button links the button role). */
+const hrefsOf = (text: string) =>
+ screen
+ .getAllByText(text)
+ .map((node) => node.closest('a')?.getAttribute('href'))
+
const sectionSwitch = (section: string) =>
screen.getByRole('switch', { name: `profiles.${section}.title` })
/** A tool checkbox's accessible name starts with the tool name; its description follows. */
@@ -254,6 +261,7 @@ describe('profile list', () => {
chatCard.getByText('profiles.summary.compactionOn {"percent":"90%"}'),
).toBeTruthy()
expect(chatCard.getByText('profiles.unused')).toBeTruthy()
+ expect(hrefsOf('docs.link')).toEqual([gatewayDocsUrl('profiles', 'en')])
})
it('keeps tool counts unknown until the catalog loads', async () => {
@@ -377,6 +385,19 @@ describe('profile editor', () => {
it('hides settings of switched-off sections and switches long-conversation features on their own', async () => {
renderAt('/gateway/profiles/p2')
await screen.findByDisplayValue('Chat')
+ // Every section links its docs, switched on or not, and so does the
+ // experimental agent-managed windows setting.
+ expect(hrefsOf('docs.learnMore')).toEqual(
+ (
+ [
+ 'recall',
+ 'capture',
+ 'longConversations',
+ 'agentWindows',
+ 'tools',
+ ] as const
+ ).map((section) => gatewayDocsUrl(section, 'en')),
+ )
expect(
screen.queryByLabelText('profiles.recall.maxTokens.label'),
diff --git a/web-studio/src/routes/gateway/-components/profiles-settings.tsx b/web-studio/src/routes/gateway/-components/profiles-settings.tsx
index 08af2ec12..0962d52f4 100644
--- a/web-studio/src/routes/gateway/-components/profiles-settings.tsx
+++ b/web-studio/src/routes/gateway/-components/profiles-settings.tsx
@@ -457,6 +457,7 @@ export function ProfileSettingsForm({
icon={<BrainIcon />}
title={t('profiles.recall.title')}
description={t('profiles.recall.description')}
+ docs="recall"
checked={value.recall}
onCheckedChange={(recall) => onChange({ recall })}
note={
@@ -527,6 +528,7 @@ export function ProfileSettingsForm({
icon={<SaveIcon />}
title={t('profiles.capture.title')}
description={t('profiles.capture.description')}
+ docs="capture"
checked={value.capture}
onCheckedChange={(capture) => onChange({ capture })}
>
@@ -543,6 +545,7 @@ export function ProfileSettingsForm({
icon={<ScrollTextIcon />}
title={t('profiles.longConversations.title')}
description={t('profiles.longConversations.description')}
+ docs="longConversations"
advanced={
<div className="grid gap-5 md:grid-cols-2">
{numberField('context_window')}
@@ -572,6 +575,7 @@ export function ProfileSettingsForm({
{t('profiles.longConversations.agentWindows.experimental')}
</Badge>
}
+ docs="agentWindows"
description={t('profiles.longConversations.agentWindows.description')}
checked={value.agent_windows}
invalid={Boolean(
@@ -597,6 +601,7 @@ export function ProfileSettingsForm({
icon={<WrenchIcon />}
title={t('profiles.tools.title')}
description={t('profiles.tools.description')}
+ docs="tools"
checked={value.gateway_tools}
onCheckedChange={(gateway_tools) => onChange({ gateway_tools })}
advanced={
diff --git a/web-studio/src/routes/gateway/-components/request-details.tsx b/web-studio/src/routes/gateway/-components/request-details.tsx
index ebb0bdf66..df07e72ef 100644
--- a/web-studio/src/routes/gateway/-components/request-details.tsx
+++ b/web-studio/src/routes/gateway/-components/request-details.tsx
@@ -6,6 +6,7 @@ import { Button } from '#/components/ui/button'
import { cn } from '#/lib/utils'
import type { GatewayKey, LogRecord, ResyncTarget, Upstream } from '../-lib/api'
+import type { DocsSection } from '../-lib/client-guides'
import {
EMPTY_VALUE,
formatDateTime,
@@ -24,6 +25,7 @@ import {
} from '../-lib/localize'
import type { Translate } from '../-lib/localize'
import { CopyButton } from './copy-button'
+import { DocsLink } from './docs-link'
import { recallFailed } from './memory-cell'
import { Notice } from './notice'
import { CaptureStatusBadge, ProtocolBadge } from './status-badges'
@@ -81,21 +83,47 @@ function DetailItem({
)
}
+/** Docs link under a detail that may need explaining. */
+function DetailDocs({
+ section,
+ children,
+}: {
+ section: DocsSection
+ children?: React.ReactNode
+}) {
+ return (
+ <DocsLink section={section} variant="text" className="w-fit text-xs">
+ {children}
+ </DocsLink>
+ )
+}
+
/** What went wrong with a request and what to do about it. */
function Callout({
tone,
title,
happened,
action,
+ docs,
}: {
tone: 'warning' | 'danger'
title?: string
happened?: string
action?: string
+ /** Troubleshooting section for this problem. */
+ docs?: DocsSection
}) {
const { t } = useTranslation('gateway')
return (
- <Notice tone={tone} title={title}>
+ <Notice
+ tone={tone}
+ title={title}
+ action={
+ docs ? (
+ <DocsLink section={docs}>{t('docs.troubleshoot')}</DocsLink>
+ ) : undefined
+ }
+ >
<dl className="grid gap-x-4 gap-y-1.5 text-foreground sm:grid-cols-[8rem_minmax(0,1fr)]">
{happened ? (
<>
@@ -367,6 +395,11 @@ export function RequestDetails({
{t('requests.memory.replayed', { count: record.replay_hits })}
</span>
) : null}
+ {recallFailed(record) ? (
+ <DetailDocs section="noMemory">
+ {t('docs.troubleshoot')}
+ </DetailDocs>
+ ) : null}
</DetailItem>
) : null}
{hasContext ? (
@@ -395,11 +428,19 @@ export function RequestDetails({
</span>
) : null}
{record.compaction_failed ? (
- <span className="text-amber-700 dark:text-amber-300">
- {t('requests.details.compactionFailed', {
- reason: record.compaction_failed,
- })}
- </span>
+ <>
+ <span className="text-amber-700 dark:text-amber-300">
+ {t(
+ record.compaction_failed === 'still_over_threshold'
+ ? 'requests.details.compactionStillOver'
+ : 'requests.details.compactionFailed',
+ { reason: record.compaction_failed },
+ )}
+ </span>
+ <DetailDocs section="contextLimit">
+ {t('docs.troubleshoot')}
+ </DetailDocs>
+ </>
) : null}
{record.window ? (
<span>
@@ -431,16 +472,23 @@ export function RequestDetails({
})}
</span>
) : null}
+ {record.capture_status === 'retrying' ||
+ record.capture_status === 'paused' ? (
+ <DetailDocs section="savingStatus" />
+ ) : null}
</DetailItem>
) : null}
{hasTools ? (
<DetailItem label={t('requests.details.tools')}>
{record.tool_skip_reason ? (
- <span>
- {t('requests.details.toolsSkipped', {
- reason: toolSkipReasonLabel(t, record.tool_skip_reason),
- })}
- </span>
+ <>
+ <span>
+ {t('requests.details.toolsSkipped', {
+ reason: toolSkipReasonLabel(t, record.tool_skip_reason),
+ })}
+ </span>
+ <DetailDocs section="toolsNotOffered" />
+ </>
) : null}
{(record.hidden_rounds ?? 0) > 0 ? (
<span className="tabular-nums">
@@ -472,6 +520,7 @@ export function RequestDetails({
tone="danger"
happened={t('requests.details.httpError', { status: record.status })}
action={t('requests.details.httpErrorAction')}
+ docs="upstreamError"
/>
) : null}
{resync ? (
diff --git a/web-studio/src/routes/gateway/-components/requests-page.test.tsx b/web-studio/src/routes/gateway/-components/requests-page.test.tsx
index ef450d9ec..1be7a7e44 100644
--- a/web-studio/src/routes/gateway/-components/requests-page.test.tsx
+++ b/web-studio/src/routes/gateway/-components/requests-page.test.tsx
@@ -32,6 +32,7 @@ import i18n from '#/i18n'
import type * as Api from '../-lib/api'
import type { GatewayKey, LogRecord, Upstream } from '../-lib/api'
+import { gatewayDocsUrl } from '../-lib/client-guides'
import { parseRequestsSearch } from '../-lib/search'
import { RequestsPage } from './requests-page'
@@ -173,6 +174,13 @@ function rowOf(text: string) {
return row
}
+/** Hrefs of every link with this text, in page order. */
+function hrefsOf(text: string) {
+ return screen
+ .getAllByText(text)
+ .map((node) => node.closest('a')?.getAttribute('href'))
+}
+
function expand(text: string) {
fireEvent.click(
within(rowOf(text)).getByRole('button', { name: 'Show details' }),
@@ -225,6 +233,7 @@ describe('RequestsPage', () => {
expect(
screen.getByText('Filters and search cover the latest 1,000 records.'),
).toBeTruthy()
+ expect(hrefsOf('Docs')).toEqual([gatewayDocsUrl('requests', 'en')])
})
it('shows a dash for requests that report no token usage', async () => {
@@ -341,6 +350,58 @@ describe('RequestsPage', () => {
'The upstream answered with HTTP 502, and the client received this error.',
),
).toBeTruthy()
+ // Only the provider error links troubleshooting; the issue explains itself.
+ expect(hrefsOf('Troubleshooting')).toEqual([
+ gatewayDocsUrl('upstreamError', 'en'),
+ ])
+ })
+
+ it('links the docs for failed recalls and tools that were not offered', async () => {
+ api.listLogs.mockResolvedValue([
+ {
+ time: NOW - 30,
+ request_id: 'req-failed',
+ kind: 'user',
+ model: 'failed-model',
+ status: 200,
+ recall_reason: 'openviking_unavailable',
+ tool_skip_reason: 'tools_forced_choice',
+ },
+ {
+ time: NOW - 60,
+ request_id: 'req-budget',
+ kind: 'user',
+ model: 'budget-model',
+ status: 200,
+ recall_reason: 'budget',
+ },
+ ])
+ renderPage()
+ await screen.findByText('failed-model')
+ // Running out of budget is not a failure.
+ expect(
+ within(rowOf('failed-model')).getByText('Recall failed'),
+ ).toBeTruthy()
+ expect(
+ within(rowOf('budget-model')).queryByText('Recall failed'),
+ ).toBeNull()
+
+ expand('budget-model')
+ expect(
+ screen.getByText('Too little budget left to add memory'),
+ ).toBeTruthy()
+ expect(screen.queryByText('Troubleshooting')).toBeNull()
+
+ expand('failed-model')
+ expect(hrefsOf('Troubleshooting')).toEqual([
+ gatewayDocsUrl('noMemory', 'en'),
+ ])
+ expect(
+ screen.getByText('Not offered: The client required a specific tool'),
+ ).toBeTruthy()
+ expect(hrefsOf('Learn more')).toEqual([
+ gatewayDocsUrl('toolsNotOffered', 'en'),
+ ])
})
it('shows how full the context window was and what replaced earlier history', async () => {
@@ -395,6 +456,38 @@ describe('RequestsPage', () => {
expect(
screen.getByText('Told the model to start a new window now'),
).toBeTruthy()
+ expect(hrefsOf('Troubleshooting')).toEqual([
+ gatewayDocsUrl('contextLimit', 'en'),
+ ])
+ })
+
+ it('does not claim the full history was sent when the summary was kept', async () => {
+ api.listLogs.mockResolvedValue([
+ {
+ time: NOW - 30,
+ request_id: 'req-still-over',
+ kind: 'user',
+ model: 'still-over-model',
+ status: 200,
+ context_tokens: 190000,
+ context_window: 200000,
+ compaction_tokens: 2400,
+ compaction_ms: 8500,
+ compaction_failed: 'still_over_threshold',
+ },
+ ])
+ renderPage()
+ await screen.findByText('still-over-model')
+ expand('still-over-model')
+ expect(
+ screen.getByText(
+ 'Summary kept, but usage is still at or above Compact at (still_over_threshold)',
+ ),
+ ).toBeTruthy()
+ expect(screen.queryByText(/full history was sent/)).toBeNull()
+ expect(hrefsOf('Troubleshooting')).toEqual([
+ gatewayDocsUrl('contextLimit', 'en'),
+ ])
})
it('resyncs a conversation after confirmation', async () => {
@@ -437,6 +530,10 @@ describe('RequestsPage', () => {
"The gateway key this conversation used has been revoked, so it can't be resynced.",
),
).toBeTruthy()
+ // Paused saving links the docs on saving states and resyncing.
+ expect(hrefsOf('Learn more')).toEqual([
+ gatewayDocsUrl('savingStatus', 'en'),
+ ])
})
it('pages through 25 records at a time', async () => {
diff --git a/web-studio/src/routes/gateway/-components/requests-page.tsx b/web-studio/src/routes/gateway/-components/requests-page.tsx
index 622ed86be..4b0152375 100644
--- a/web-studio/src/routes/gateway/-components/requests-page.tsx
+++ b/web-studio/src/routes/gateway/-components/requests-page.tsx
@@ -43,6 +43,7 @@ import { gatewayErrorMessage, kindLabel } from '../-lib/localize'
import type { RequestsFilter } from '../-lib/search'
import { useGateway, useKeys, useLogs, useUpstreams } from '../-lib/use-gateway'
import { ConfirmDialog } from './confirm-dialog'
+import { DocsLink } from './docs-link'
import { EmptyState, ErrorState, LoadingState } from './empty-state'
import type { ResyncRequest } from './request-details'
import { RequestRow, RequestsTableHeader } from './requests-row'
@@ -342,7 +343,10 @@ export function RequestsPage() {
return (
<div className="flex w-full min-w-0 flex-col gap-5">
- <SectionHeader description={t('requests.description')} />
+ <SectionHeader
+ description={t('requests.description')}
+ actions={<DocsLink section="requests" />}
+ />
<Card className="gap-0 overflow-hidden py-0">
<CardHeader className="border-b bg-muted/20 px-4 py-3 [.border-b]:pb-3">
<div className="flex min-w-0 flex-wrap items-center gap-2">
diff --git a/web-studio/src/routes/gateway/-components/setting-section.tsx b/web-studio/src/routes/gateway/-components/setting-section.tsx
index 4b5988229..a07b10b22 100644
--- a/web-studio/src/routes/gateway/-components/setting-section.tsx
+++ b/web-studio/src/routes/gateway/-components/setting-section.tsx
@@ -18,12 +18,17 @@ import {
} from '#/components/ui/collapsible'
import { Switch } from '#/components/ui/switch'
+import type { DocsSection } from '../-lib/client-guides'
+import { DocsLink } from './docs-link'
+
type SettingSectionProps = {
/** Anchor id for in-page navigation. */
id?: string
icon?: React.ReactNode
title: string
description?: React.ReactNode
+ /** Docs section explaining these settings, linked after the description. */
+ docs?: DocsSection
/** State of the header switch; omit for a section without one. */
checked?: boolean
onCheckedChange?: (checked: boolean) => void
@@ -53,6 +58,7 @@ export function SettingSection({
icon,
title,
description,
+ docs,
checked,
onCheckedChange,
switchDisabled,
@@ -78,6 +84,12 @@ export function SettingSection({
{description ? (
<CardDescription className="max-w-2xl leading-6">
{description}
+ {docs ? (
+ <>
+ {' '}
+ <DocsLink section={docs} variant="text" />
+ </>
+ ) : null}
</CardDescription>
) : null}
{checked !== undefined ? (
diff --git a/web-studio/src/routes/gateway/-components/toggle-row.tsx b/web-studio/src/routes/gateway/-components/toggle-row.tsx
index f0a52c62a..43071daf4 100644
--- a/web-studio/src/routes/gateway/-components/toggle-row.tsx
+++ b/web-studio/src/routes/gateway/-components/toggle-row.tsx
@@ -1,4 +1,6 @@
+import { DocsLink } from './docs-link'
import { useReadOnly } from './read-only'
+import type { DocsSection } from '../-lib/client-guides'
import type * as React from 'react'
import { Label } from '#/components/ui/label'
@@ -12,6 +14,8 @@ type ToggleRowProps = {
onCheckedChange: (checked: boolean) => void
/** Shown after the label, such as an "Experimental" mark. */
badge?: React.ReactNode
+ /** Docs section linked after the description. */
+ docs?: DocsSection
/** A dependent setting is invalid, so they stay visible while the switch is off. */
invalid?: boolean
/** Dependent settings, shown below the row while it is on. */
@@ -26,6 +30,7 @@ export function ToggleRow({
checked,
onCheckedChange,
badge,
+ docs,
invalid = false,
children,
}: ToggleRowProps) {
@@ -40,6 +45,12 @@ export function ToggleRow({
</span>
<p className="text-xs leading-5 text-muted-foreground">
{description}
+ {docs ? (
+ <>
+ {' '}
+ <DocsLink section={docs} variant="text" />
+ </>
+ ) : null}
</p>
</div>
<Switch
diff --git a/web-studio/src/routes/gateway/-components/upstreams-actions.tsx b/web-studio/src/routes/gateway/-components/upstreams-actions.tsx
index b77cc6ca0..f9cd15ea4 100644
--- a/web-studio/src/routes/gateway/-components/upstreams-actions.tsx
+++ b/web-studio/src/routes/gateway/-components/upstreams-actions.tsx
@@ -30,6 +30,7 @@ import { gatewayErrorMessage } from '../-lib/localize'
import type { Translate } from '../-lib/localize'
import { useGateway } from '../-lib/use-gateway'
import { servedModels, toUpstreamInput } from '../-lib/upstream-schema'
+import { DocsLink } from './docs-link'
import { Notice } from './notice'
import { ExplainedButton } from './explained-button'
import { ToneBadge } from './status-badges'
@@ -311,7 +312,8 @@ export function UpstreamTest({
{t('upstreams.test.dialog.title', { name: upstream.name })}
</DialogTitle>
<DialogDescription>
- {t('upstreams.test.dialog.description')}
+ {t('upstreams.test.dialog.description')}{' '}
+ <DocsLink section="testUpstream" variant="text" />
</DialogDescription>
</DialogHeader>
<form className="grid min-w-0 gap-5" onSubmit={submit}>
diff --git a/web-studio/src/routes/gateway/-components/upstreams-form.tsx b/web-studio/src/routes/gateway/-components/upstreams-form.tsx
index c98abfd1e..7660a07e1 100644
--- a/web-studio/src/routes/gateway/-components/upstreams-form.tsx
+++ b/web-studio/src/routes/gateway/-components/upstreams-form.tsx
@@ -244,6 +244,7 @@ export function UpstreamForm({
icon={<GlobeIcon />}
title={t('upstreams.sections.endpoint.title')}
description={t('upstreams.sections.endpoint.description')}
+ docs="endpoint"
>
<SettingField
label={t('upstreams.form.name.label')}
@@ -411,6 +412,7 @@ export function UpstreamForm({
icon={<KeyRoundIcon />}
title={t('upstreams.sections.credentials.title')}
description={t('upstreams.sections.credentials.description')}
+ docs="credentials"
>
{readOnly ? (
<div className="flex flex-wrap items-center gap-2 text-sm">
@@ -589,6 +591,7 @@ export function UpstreamForm({
icon={<BoxesIcon />}
title={t('upstreams.sections.models.title')}
description={t('upstreams.sections.models.description')}
+ docs="models"
>
<SettingField
label={t('upstreams.form.models.label')}
@@ -638,6 +641,7 @@ export function UpstreamForm({
icon={<RouteIcon />}
title={t('upstreams.sections.routing.title')}
description={t('upstreams.sections.routing.description')}
+ docs="routing"
>
<SettingField
label={t('upstreams.form.priority.label')}
diff --git a/web-studio/src/routes/gateway/-components/upstreams-page.tsx b/web-studio/src/routes/gateway/-components/upstreams-page.tsx
index 6034f7416..d07f00c8f 100644
--- a/web-studio/src/routes/gateway/-components/upstreams-page.tsx
+++ b/web-studio/src/routes/gateway/-components/upstreams-page.tsx
@@ -53,6 +53,7 @@ import {
useKeys,
useUpstreams,
} from '../-lib/use-gateway'
+import { DocsLink } from './docs-link'
import { EmptyState, ErrorState, LoadingState } from './empty-state'
import { Notice } from './notice'
import { SectionHeader } from './section-header'
@@ -265,6 +266,7 @@ export function UpstreamsPage() {
description={t('upstreams.description')}
actions={
<>
+ <DocsLink section="upstreams" />
<Button
type="button"
variant="outline"
@@ -332,9 +334,14 @@ export function ImportResultNotice({
<Notice
tone={confirm.length || skipped.length ? 'warning' : 'info'}
action={
- <Button type="button" size="sm" variant="outline" onClick={onDismiss}>
- {t('upstreams.import.dismiss')}
- </Button>
+ <div className="flex flex-wrap gap-2">
+ {skipped.length ? (
+ <DocsLink section="importModels">{t('docs.learnMore')}</DocsLink>
+ ) : null}
+ <Button type="button" size="sm" variant="outline" onClick={onDismiss}>
+ {t('upstreams.import.dismiss')}
+ </Button>
+ </div>
}
>
{saved ? (
diff --git a/web-studio/src/routes/gateway/-components/upstreams-pages.test.tsx b/web-studio/src/routes/gateway/-components/upstreams-pages.test.tsx
index 8972623f8..1bfcbb827 100644
--- a/web-studio/src/routes/gateway/-components/upstreams-pages.test.tsx
+++ b/web-studio/src/routes/gateway/-components/upstreams-pages.test.tsx
@@ -22,6 +22,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { GatewayError } from '../-lib/api'
import type * as Api from '../-lib/api'
import type { GatewayKey, Upstream, UpstreamInput } from '../-lib/api'
+import { gatewayDocsUrl } from '../-lib/client-guides'
import type { Translate } from '../-lib/localize'
import { UPSTREAM_DEFAULTS } from '../-lib/upstream-schema'
import { UpstreamEditor } from './upstreams-editor'
@@ -204,6 +205,12 @@ const rowOf = (name: string) => {
return within(row)
}
+/** Hrefs of every link with this text (Base UI gives button links the button role). */
+const hrefsOf = (text: string) =>
+ screen
+ .getAllByText(text)
+ .map((node) => node.closest('a')?.getAttribute('href'))
+
beforeEach(() => {
vi.spyOn(window, 'scrollTo').mockImplementation(() => {})
for (const fn of [...Object.values(api), ...Object.values(toast)]) {
@@ -257,6 +264,7 @@ describe('UpstreamsPage', () => {
expect(blocked.getByText('upstreams.credentials.keyMissing')).toBeTruthy()
expect(blocked.getByText('upstreams.credentials.blocked')).toBeTruthy()
expect(blocked.getByText('upstreams.notUsed')).toBeTruthy()
+ expect(hrefsOf('docs.link')).toEqual([gatewayDocsUrl('upstreams', 'en')])
})
it('explains an empty account', async () => {
@@ -350,6 +358,9 @@ describe('UpstreamsPage', () => {
expect(api.testUpstream).toHaveBeenCalledWith(expect.anything(), 'u1'),
)
await screen.findByText('upstreams.test.result.connected')
+ expect(hrefsOf('docs.learnMore')).toEqual([
+ gatewayDocsUrl('testUpstream', 'en'),
+ ])
fireEvent.click(
screen.getByRole('button', {
name: 'upstreams.test.dialog.run',
@@ -533,6 +544,12 @@ describe('UpstreamEditor', () => {
expect(
screen.getByText('https://api.openai.com/v1/chat/completions'),
).toBeTruthy()
+ // One docs link per section, after its description.
+ expect(hrefsOf('docs.learnMore')).toEqual(
+ (['endpoint', 'credentials', 'models', 'routing'] as const).map(
+ (section) => gatewayDocsUrl(section, 'en'),
+ ),
+ )
const save = screen.getByRole('button', { name: 'actions.save' })
expect(save.hasAttribute('disabled')).toBe(true)
@@ -1157,6 +1174,10 @@ describe('upstream access and import', () => {
screen.getByText('lite: upstreams.import.reasons.litellm_no_api_base'),
).toBeTruthy()
expect(screen.getByText('upstreams.import.repeat')).toBeTruthy()
+ // Skipped credentials link the import docs.
+ expect(hrefsOf('docs.learnMore')).toEqual([
+ gatewayDocsUrl('importModels', 'en'),
+ ])
fireEvent.click(
screen.getByRole('button', { name: 'upstreams.import.dismiss' }),
)
diff --git a/web-studio/src/routes/gateway/-lib/api.ts b/web-studio/src/routes/gateway/-lib/api.ts
index 7852b479d..a5c2cb3e9 100644
--- a/web-studio/src/routes/gateway/-lib/api.ts
+++ b/web-studio/src/routes/gateway/-lib/api.ts
@@ -292,7 +292,10 @@ export type LogRecord = {
degradation?: string
/** Anchor of the cut whose replacement this request used. */
compaction_applied?: string
- /** Why generating a summary failed; the full history was sent. */
+ /**
+ * Why compaction failed. The full history was sent, except for
+ * `still_over_threshold`, where the summary was written and kept.
+ */
compaction_failed?: string
/** Estimated size of the summary written for this request. */
compaction_tokens?: number
diff --git a/web-studio/src/routes/gateway/-lib/client-guides.test.ts b/web-studio/src/routes/gateway/-lib/client-guides.test.ts
index 6c102d53d..75e25b709 100644
--- a/web-studio/src/routes/gateway/-lib/client-guides.test.ts
+++ b/web-studio/src/routes/gateway/-lib/client-guides.test.ts
@@ -176,14 +176,19 @@ it('quotes shell values only when needed', () => {
})
it('links the docs in the UI language', () => {
- expect(gatewayDocsUrl('guide', 'en')).toBe(
- 'https://docs.openviking.ai/en/guides/15-gateway',
+ expect(gatewayDocsUrl('claudeCode', 'en')).toBe(
+ 'https://docs.openviking.ai/en/gateway/03-connect-clients#claude-code',
)
- expect(gatewayDocsUrl('operations', 'zh-CN')).toBe(
- 'https://docs.openviking.ai/zh/guides/22-gateway-operations',
+ // Headings carry the same explicit id in every language.
+ expect(gatewayDocsUrl('cacheHitRate', 'zh-CN')).toBe(
+ 'https://docs.openviking.ai/zh/gateway/12-troubleshooting#the-first-call-cache-hit-rate-dropped',
)
- expect(gatewayDocsUrl('operations', 'zh-CN', 'cacheHitRate')).toBe(
- 'https://docs.openviking.ai/zh/guides/22-gateway-operations#首次调用缓存命中率下降',
+ expect(gatewayDocsUrl('cacheHitRate')).toBe(
+ 'https://docs.openviking.ai/en/gateway/12-troubleshooting#the-first-call-cache-hit-rate-dropped',
+ )
+ // The entry and deployment pages keep their guides/ paths.
+ expect(gatewayDocsUrl('enableGateway', 'zh')).toBe(
+ 'https://docs.openviking.ai/zh/guides/22-gateway-operations#enable-it-in-the-server',
)
})
diff --git a/web-studio/src/routes/gateway/-lib/client-guides.ts b/web-studio/src/routes/gateway/-lib/client-guides.ts
index 6edb04336..cd2d6dc91 100644
--- a/web-studio/src/routes/gateway/-lib/client-guides.ts
+++ b/web-studio/src/routes/gateway/-lib/client-guides.ts
@@ -357,22 +357,130 @@ export const SESSION_HEADERS = [
'session-id',
]
-/** Headings Studio links to, by each docs language's anchor. */
-const DOCS_SECTIONS = {
+/**
+ * Gateway docs pages, by their path under `docs/<language>`. The entry and
+ * deployment pages stay under `guides/` so links from released builds keep
+ * working; the rest live in the gateway section's own folder.
+ */
+export const DOCS_PAGES = {
+ guide: 'guides/15-gateway',
+ clients: 'gateway/03-connect-clients',
+ tools: 'gateway/04-openviking-tools',
+ longConversations: 'gateway/05-long-conversations',
+ studio: 'gateway/06-manage-in-studio',
+ upstreams: 'gateway/07-upstreams',
+ profiles: 'gateway/08-context-profiles',
+ keys: 'gateway/09-gateway-keys',
+ requests: 'gateway/10-overview-and-requests',
+ operations: 'guides/22-gateway-operations',
+ troubleshooting: 'gateway/12-troubleshooting',
+}
+
+type DocsPage = keyof typeof DOCS_PAGES
+
+/**
+ * Docs headings Studio links to. Each heading carries an explicit `{#id}`,
+ * the same in every docs language, so one id serves them all.
+ */
+export const DOCS_SECTIONS = {
+ // Overview
+ pluginDetected: { page: 'guide', id: 'when-both-are-in-use' },
+ // Connect clients
+ claudeCode: { page: 'clients', id: 'claude-code' },
+ codex: { page: 'clients', id: 'codex-cli' },
+ chat: { page: 'clients', id: 'chat-clients-and-sdks' },
+ openWebui: { page: 'clients', id: 'open-webui' },
+ opencode: { page: 'clients', id: 'opencode' },
+ pi: { page: 'clients', id: 'pi' },
+ dsh: { page: 'clients', id: 'dsh' },
+ ark: {
+ page: 'clients',
+ id: 'volcano-engine-ark-and-byteplus-modelark-sdks',
+ },
+ conversations: { page: 'clients', id: 'how-conversations-are-recognized' },
+ providerKey: { page: 'clients', id: 'bring-your-own-provider-key' },
+ // OpenViking tools
+ tools: { page: 'tools', id: 'choose-tools' },
+ toolsNotOffered: { page: 'tools', id: 'when-tools-are-not-offered' },
+ // Long conversations
+ longConversations: { page: 'longConversations', id: 'long-conversations' },
+ agentWindows: {
+ page: 'longConversations',
+ id: 'experimental-agent-managed-context-windows',
+ },
+ // Manage in Studio
+ studioAccess: { page: 'studio', id: 'who-can-change-what' },
+ quickMode: { page: 'studio', id: 'get-started-checklist' },
+ // Upstreams
+ upstreams: { page: 'upstreams', id: 'upstreams' },
+ endpoint: { page: 'upstreams', id: 'endpoint' },
+ credentials: { page: 'upstreams', id: 'credentials' },
+ models: { page: 'upstreams', id: 'models' },
+ routing: { page: 'upstreams', id: 'routing' },
+ testUpstream: { page: 'upstreams', id: 'test-and-delete' },
+ importModels: { page: 'upstreams', id: 'import-openviking-model-settings' },
+ // Context profiles
+ profiles: { page: 'profiles', id: 'context-profiles' },
+ recall: { page: 'profiles', id: 'recall-memory' },
+ capture: { page: 'profiles', id: 'save-conversations' },
+ // Gateway keys
+ keys: { page: 'keys', id: 'gateway-keys' },
+ // Overview and requests
+ overview: { page: 'requests', id: 'overview' },
+ requests: { page: 'requests', id: 'requests' },
+ savingStatus: { page: 'requests', id: 'saving-status' },
+ // Deployment and operations
+ enableGateway: { page: 'operations', id: 'enable-it-in-the-server' },
+ publicService: { page: 'operations', id: 'public-openviking-service' },
+ publicAddress: { page: 'operations', id: 'public-address' },
+ lostManagementKey: { page: 'operations', id: 'lost-the-management-key' },
+ // Troubleshooting
+ setupCard: { page: 'troubleshooting', id: 'studio-shows-a-setup-card' },
+ issueKeyFails: { page: 'troubleshooting', id: 'issuing-a-key-fails' },
+ upstreamError: {
+ page: 'troubleshooting',
+ id: 'the-upstream-returned-an-error',
+ },
+ openvikingDegraded: { page: 'troubleshooting', id: 'openviking-is-degraded' },
+ noMemory: { page: 'troubleshooting', id: 'no-memory-is-added' },
+ notSaved: {
+ page: 'troubleshooting',
+ id: 'conversations-do-not-appear-in-openviking',
+ },
cacheHitRate: {
- en: 'the-first-call-cache-hit-rate-dropped',
- zh: '首次调用缓存命中率下降',
+ page: 'troubleshooting',
+ id: 'the-first-call-cache-hit-rate-dropped',
+ },
+ contextLimit: {
+ page: 'troubleshooting',
+ id: 'long-conversations-hit-the-context-limit',
},
+ degradedRequests: {
+ page: 'troubleshooting',
+ id: 'issues-on-degraded-requests',
+ },
+} satisfies Record<string, { page: DocsPage; id: string }>
+
+export type DocsSection = keyof typeof DOCS_SECTIONS
+
+/** Each client's section on the connect-clients page. */
+export const CLIENT_DOCS: Record<ClientId, DocsSection> = {
+ 'claude-code': 'claudeCode',
+ codex: 'codex',
+ chat: 'chat',
+ 'open-webui': 'openWebui',
+ opencode: 'opencode',
+ pi: 'pi',
+ dsh: 'dsh',
+ ark: 'ark',
}
-/** OpenViking docs page for the gateway, in the UI language. */
+/** A gateway docs section, in the UI language. */
export function gatewayDocsUrl(
- page: 'guide' | 'operations',
+ section: DocsSection,
language?: string,
- section?: keyof typeof DOCS_SECTIONS,
): string {
const locale = language?.startsWith('zh') ? 'zh' : 'en'
- const slug = page === 'guide' ? '15-gateway' : '22-gateway-operations'
- const anchor = section ? `#${DOCS_SECTIONS[section][locale]}` : ''
- return `https://docs.openviking.ai/${locale}/guides/${slug}${anchor}`
+ const { page, id } = DOCS_SECTIONS[section]
+ return `https://docs.openviking.ai/${locale}/${DOCS_PAGES[page]}#${id}`
}
diff --git a/web-studio/src/routes/gateway/-lib/docs-anchors.test.ts b/web-studio/src/routes/gateway/-lib/docs-anchors.test.ts
new file mode 100644
index 000000000..1e62b23c1
--- /dev/null
+++ b/web-studio/src/routes/gateway/-lib/docs-anchors.test.ts
@@ -0,0 +1,82 @@
+/// <reference types="node" />
+import { existsSync, readFileSync, readdirSync } from 'node:fs'
+
+import { describe, expect, it } from 'vitest'
+
+import { DOCS_PAGES, DOCS_SECTIONS } from './client-guides'
+
+/** The repository's docs folder, five levels above this file. */
+const DOCS = new URL('../../../../../docs/', import.meta.url)
+
+const LANGUAGES = ['en', 'zh']
+
+/**
+ * Every page of the gateway docs section: the entry and deployment pages,
+ * which keep their `guides/` paths, and the gateway folder.
+ */
+const SECTION_PAGES = [
+ 'guides/15-gateway',
+ 'guides/22-gateway-operations',
+ ...readdirSync(new URL('en/gateway/', DOCS))
+ .filter((name) => name.endsWith('.md'))
+ .sort()
+ .map((name) => `gateway/${name.slice(0, -3)}`),
+]
+
+function pageUrl(language: string, page: string) {
+ return new URL(`${language}/${page}.md`, DOCS)
+}
+
+/** The page's headings, outside code blocks. */
+function headings(language: string, page: string) {
+ const text = readFileSync(pageUrl(language, page), 'utf8').replace(
+ /^(```|~~~)[^\n]*\n[\s\S]*?^\1[ \t]*$/gm,
+ '',
+ )
+ return [...text.matchAll(/^#{2,6} .*$/gm)].map((match) => match[0])
+}
+
+/** Explicit `{#id}`s on the page's headings. */
+function headingIds(language: string, page: string) {
+ return headings(language, page).flatMap((heading) => {
+ const id = /\{#([\w-]+)\}[ \t]*$/.exec(heading)?.[1]
+ return id ? [id] : []
+ })
+}
+
+// Studio links one id for every language, so each heading needs it pinned.
+describe.each(LANGUAGES)('%s gateway docs', (language) => {
+ it.each(Object.values(DOCS_PAGES))('have the page %s', (page) => {
+ expect(existsSync(pageUrl(language, page))).toBe(true)
+ })
+
+ it.each(Object.entries(DOCS_SECTIONS))(
+ 'pin the heading Studio links as %s',
+ (_, { page, id }) => {
+ expect(headingIds(language, DOCS_PAGES[page])).toContain(id)
+ },
+ )
+
+ it.each(SECTION_PAGES)('pin every H2 and H3 on %s', (page) => {
+ const unpinned = headings(language, page).filter(
+ (heading) =>
+ /^#{2,3} /.test(heading) && !/\{#[\w-]+\}[ \t]*$/.test(heading),
+ )
+ expect(unpinned).toEqual([])
+ })
+})
+
+// The same ids in every language, so a link works whichever one is open.
+describe('gateway docs languages', () => {
+ it('have the same gateway pages', () => {
+ const pages = (language: string) =>
+ readdirSync(new URL(`${language}/gateway/`, DOCS))
+ .filter((name) => name.endsWith('.md'))
+ .sort()
+ expect(pages('zh')).toEqual(pages('en'))
+ })
+
+ it.each(SECTION_PAGES)('pin the same heading ids on %s', (page) => {
+ expect(headingIds('zh', page)).toEqual(headingIds('en', page))
+ })
+})