diff --git a/docs/en/agent-integrations/02-claude-code.md b/docs/en/agent-integrations/02-claude-code.md index 5d43bdeea3e..f48a9430992 100644 --- a/docs/en/agent-integrations/02-claude-code.md +++ b/docs/en/agent-integrations/02-claude-code.md @@ -101,9 +101,13 @@ Configuration priority: Environment variables > `ovcli.conf` > `ov.conf` > Built | `OPENVIKING_CAPTURE_FILTERS` | `""` | CSV of sed-style regex rules applied to every captured turn (same grammar) | | `OPENVIKING_MEMORY_ENABLED` | (auto) | Force on/off | | `OPENVIKING_DEBUG` | `false` | Write logs to `~/.openviking/logs/cc-hooks.log` | +| `OPENVIKING_SEAL_SECRETS` | `false` | Seal secrets out of what the model sees (`sealSecrets`; needs OpenViking server 0.5.7 or newer) | +| `OPENVIKING_ENROLL_TOOL_SECRETS` | `false` | With `sealSecrets` on, also store new secrets found in tool output (`enrollToolSecrets`) | Most of these knobs can also live in `ovcli.conf` under `plugin` — see [Plugin Settings](../configuration/02-client.md#plugin-settings). The two filter knobs are better written there, as JSON arrays, because the environment form is split on commas. +Sealing secrets is described in [Seal secrets](#seal-secrets). + If recall latency matters most, see [Low-latency recall](./01-overview.md#low-latency-recall) for the environment-variable and `ovcli.conf` settings that disable query expansion and result compression. With a user/admin key, the server derives identity from the key. Set `OPENVIKING_ACCOUNT` and `OPENVIKING_USER` only for trusted mode, using values supplied by your administrator. The complete list of environment variables is available in the [plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#configuration). @@ -126,6 +130,23 @@ Under each answer, the plugin adds a one-line card listing the OpenViking source The cards need Claude Code 2.1.286 or newer with plugin hooks modules enabled. On older versions, or with modules off, no cards are shown, and recall, capture and the other hooks work as before. See [Source cards](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#source-cards) in the plugin README. +## Seal secrets {#seal-secrets} + +With `sealSecrets` on, the plugin replaces the secrets your OpenViking server knows with {{ov_privacy:…}} references in what Claude reads, and gives tools the real values back. It is off by default and needs OpenViking server 0.5.7 or newer. It runs on your machine. + +| Setting | Environment variable | Default | Effect | +|---------|----------------------|---------|--------| +| `sealSecrets` | `OPENVIKING_SEAL_SECRETS` | `false` | Turns sealing on | +| `enrollToolSecrets` | `OPENVIKING_ENROLL_TOOL_SECRETS` | `false` | Also stores new secrets found in tool output | + +Set them in `ovcli.conf` (see the plugin README) or in the environment; a changed setting takes effect in a new session. Sealing runs in the plugin's hooks module, so it needs what [Source cards](#source-cards) need; where the module is not loaded, nothing is sealed. + +- **Sealed:** your prompt, tool results, and the files, reminders and hook context Claude Code attaches. New secrets are stored from your prompt, and from tool results only with `enrollToolSecrets`. A reference Claude writes in a tool call becomes the real value before the tool runs. The local transcript stores prompts and tool results with references; for attached files and reminders it keeps Claude Code's own record, with the original text. +- **When sealing cannot be done** (a server older than 0.5.7, a failed `/health`, seal or resolve call), it stops: your prompt is not sent, a tool result is withheld, and a tool call whose references cannot be resolved does not run. The message says why. Upgrade the server or restore the connection, or turn `sealSecrets` off. +- **Not covered:** the system prompt, slash-command arguments, skill bodies, and history written before sealing was turned on. + +Details: [plugin README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#seal-secrets). + ## Troubleshooting | Issue | Cause | Solution | diff --git a/docs/en/agent-integrations/11-pi.md b/docs/en/agent-integrations/11-pi.md index e3f0732916d..212f8acb059 100644 --- a/docs/en/agent-integrations/11-pi.md +++ b/docs/en/agent-integrations/11-pi.md @@ -104,6 +104,23 @@ Settings resolve highest priority first: `OPENVIKING_*` environment variables, t Takeover is fail-open: if pending writes cannot flush, commit fails, the archive overview is not ready, or the branch fingerprint no longer matches, pi keeps full local history or falls back to its default compaction. Set `OPENVIKING_DEBUG_LOG=/tmp/ov-pi.log` when validating boundary advances; the log is JSON Lines, one record per event. `OV_DEBUG_LOG` is a deprecated alias that still works. +## Seal secrets {#seal-secrets} + +`sealSecrets` keeps the secrets your OpenViking server knows out of what the model sees; a reference the model writes in a tool call is turned back into the real value for the tool only. It is off by default and needs OpenViking server 0.5.7 or newer. + +| Setting | Environment variable | Default | Effect | +|---------|----------------------|---------|--------| +| `sealSecrets` | `OPENVIKING_SEAL_SECRETS` | `false` | Seals what you type and every tool result | +| `enrollToolSecrets` | `OPENVIKING_ENROLL_TOOL_SECRETS` | `false` | Also stores new secrets found in tool results | + +Neither can be set in a workspace file. + +- **Sealed:** what you type and every tool result, before pi stores or sends them, so the model and the session file see references ({{ov_privacy:…}}). New secrets in what you type are stored automatically; a reference the model writes in a tool call becomes the real value for the tool only. +- **When sealing cannot be done** (a server older than 0.5.7, a failed `/health`, seal or resolve call), it stops: what you typed is not sent, a tool result is withheld, and a tool call whose references cannot be resolved does not run. pi tells you why. Upgrade the server or restore the connection, or turn `sealSecrets` off. +- **Not covered:** the system prompt and context files, skill and prompt-template text, recall blocks, compaction summaries, and history from before sealing was turned on. + +Details: [extension README](https://github.com/volcengine/OpenViking/blob/main/examples/pi-coding-agent-extension/README.md#secret-sealing). + ## Verify Start `pi`. Once connected, the footer shows an `OV ✓` status segment, and `/viking` prints the current session mapping and how many `openviking_*` tools registered. Ask pi about something you mentioned in an earlier session to confirm recall. diff --git a/docs/zh/agent-integrations/02-claude-code.md b/docs/zh/agent-integrations/02-claude-code.md index d5c36a775a0..947c075aaf5 100644 --- a/docs/zh/agent-integrations/02-claude-code.md +++ b/docs/zh/agent-integrations/02-claude-code.md @@ -101,9 +101,13 @@ skill 清单就是 `` 块,列出存放在 OpenViking 中的 | `OPENVIKING_CAPTURE_FILTERS` | `""` | CSV 格式的 sed 风格正则规则,作用于每个被捕获的回合(同一套语法) | | `OPENVIKING_MEMORY_ENABLED` | (auto) | 强制开启或关闭插件 | | `OPENVIKING_DEBUG` | `false` | 将调试日志输出至 `~/.openviking/logs/cc-hooks.log` | +| `OPENVIKING_SEAL_SECRETS` | `false` | 把密钥从模型看到的内容中封存(`sealSecrets`;需要 OpenViking 服务端 0.5.7 或更新版本) | +| `OPENVIKING_ENROLL_TOOL_SECRETS` | `false` | 开启 `sealSecrets` 时,工具输出中的新密钥也登记(`enrollToolSecrets`) | 这些配置大多也可以写在 `ovcli.conf` 的 `plugin` 段下——见[插件配置](../configuration/02-client.md#插件配置)。两个过滤器建议使用 JSON 数组,避免环境变量中的逗号被当作分隔符。 +密钥封存见[封存密钥](#seal-secrets)。 + 如果更看重召回响应速度,请参阅[低延迟召回](./01-overview.md#低延迟召回),其中说明了如何通过环境变量或 `ovcli.conf` 关闭查询扩展与结果压缩。 使用 user/admin key 时,服务端从密钥解析身份;仅在 trusted 模式下按管理员提供的信息设置 `OPENVIKING_ACCOUNT` 和 `OPENVIKING_USER`。完整的环境变量列表请参阅 [插件 README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README.md#configuration)。 @@ -126,6 +130,23 @@ skill 清单就是 `` 块,列出存放在 OpenViking 中的 卡片需要 Claude Code 2.1.286 或更高版本,并启用插件 hooks 模块。版本更早或模块未启用时不显示卡片,召回、捕获等 hook 照常工作。详见插件 README 的[来源卡片](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README_CN.md#来源卡片)。 +## 封存密钥 {#seal-secrets} + +开启 `sealSecrets` 后,插件会把 OpenViking 服务端已知的密钥在 Claude 读到的内容里换成 {{ov_privacy:…}} 引用,交给工具时再换回真值。默认关闭,需要 OpenViking 服务端 0.5.7 或更新版本。它运行在你的机器上。 + +| 设置 | 环境变量 | 默认值 | 作用 | +|------|----------|--------|------| +| `sealSecrets` | `OPENVIKING_SEAL_SECRETS` | `false` | 开启封存 | +| `enrollToolSecrets` | `OPENVIKING_ENROLL_TOOL_SECRETS` | `false` | 工具输出中的新密钥也登记 | + +这几项写在 `ovcli.conf`(见插件 README)或环境变量里;改动在新 session 中生效。封存由插件的 hooks 模块执行,所以要求与[来源卡片](#来源卡片)相同;没有加载该模块时不会封存任何内容。 + +- **封存的内容**:你的提示词、工具结果,以及 Claude Code 附带的文件、提醒和 hook 上下文。新密钥从提示词中登记;工具结果中的新密钥只在开启 `enrollToolSecrets` 时登记。Claude 在工具调用里写下的引用,在工具运行前换成真值。本机对话记录里,提示词和工具结果存的是引用;附带的文件和提醒保留 Claude Code 自己的记录,即原文。 +- **无法封存时**(服务端低于 0.5.7,`/health`、封存或解析请求失败)会拦下:提示词不会发出,工具结果被扣下,引用解析不了的工具调用不会运行。提示里会说明原因。升级服务端或恢复连接,或者关闭 `sealSecrets`。 +- **覆盖不到的内容**:系统提示词、斜杠命令参数、skill 正文,以及开启封存之前写下的历史。 + +详见[插件 README](https://github.com/volcengine/OpenViking/blob/main/examples/claude-code-memory-plugin/README_CN.md#封存密钥)。 + ## 故障排查 | 现象 | 原因 | 修复 | diff --git a/docs/zh/agent-integrations/11-pi.md b/docs/zh/agent-integrations/11-pi.md index 7eec29ad105..ae67a984fb0 100644 --- a/docs/zh/agent-integrations/11-pi.md +++ b/docs/zh/agent-integrations/11-pi.md @@ -104,6 +104,23 @@ node ~/.pi/agent/extensions/openviking/scripts/setup.mjs Takeover 是 fail-open:如果 pending 写入无法 flush、commit 失败、archive overview 尚未生成,或 branch 指纹不匹配,pi 会继续保留完整本地历史,或回退到默认 compaction。验证边界推进时可设置 `OPENVIKING_DEBUG_LOG=/tmp/ov-pi.log`,日志按 JSON Lines 写入,每个事件一行。`OV_DEBUG_LOG` 是已弃用的别名,仍然可用。 +## 封存密钥 {#seal-secrets} + +`sealSecrets` 让 OpenViking 服务端已知的密钥不进入模型的视野;模型在工具调用里写下的引用,只在交给工具时换回真值。默认关闭,需要 OpenViking 服务端 0.5.7 或更新版本。 + +| 设置 | 环境变量 | 默认值 | 作用 | +|------|----------|--------|------| +| `sealSecrets` | `OPENVIKING_SEAL_SECRETS` | `false` | 封存你输入的内容和每个工具结果 | +| `enrollToolSecrets` | `OPENVIKING_ENROLL_TOOL_SECRETS` | `false` | 工具结果中的新密钥也登记 | + +这两项都不能在工作区配置文件里设置。 + +- **封存的内容**:你输入的内容和每个工具结果,在 pi 保存或发送之前先封存,模型和 session 文件看到的是引用({{ov_privacy:…}})。你输入中的新密钥会自动登记;模型在工具调用里写下的引用,只在交给工具时换回真值。 +- **无法封存时**(服务端低于 0.5.7,`/health`、封存或解析请求失败)会拦下:你输入的内容不会发出,工具结果被扣下,引用解析不了的工具调用不会运行。pi 会告诉你原因。升级服务端或恢复连接,或者关闭 `sealSecrets`。 +- **覆盖不到的内容**:系统提示词和上下文文件、skill 与 prompt 模板的正文、recall 注入块、compaction 摘要,以及开启封存之前已有的历史。 + +详见[扩展 README](https://github.com/volcengine/OpenViking/blob/main/examples/pi-coding-agent-extension/README.md#secret-sealing)。 + ## 验证 启动 `pi`。连接成功后底部状态栏出现 `OV ✓` 段,`/viking` 会打印当前 session 映射和已注册的 `openviking_*` 工具数量。问 pi 一个你在早前会话里提到过的事情,确认召回生效。 diff --git a/examples/agent-hook-plugin/hosts/antigravity/skills/openviking-memory/SKILL.md b/examples/agent-hook-plugin/hosts/antigravity/skills/openviking-memory/SKILL.md index 253a32e508c..2b9bb18320c 100644 --- a/examples/agent-hook-plugin/hosts/antigravity/skills/openviking-memory/SKILL.md +++ b/examples/agent-hook-plugin/hosts/antigravity/skills/openviking-memory/SKILL.md @@ -8,8 +8,11 @@ description: > context this session does not have — even if nobody says the word "memory". Also use it when the user asks where memories are stored: per project, per folder, or shared between repositories. Covers choosing between context search, find, list search, and grep, reading viking:// - URIs, and when (not) to write. -version: 2026.10.1 + URIs, and when (not) to write. Also use it when a message or file holds an + {{ov_privacy:…}} reference or says OpenViking replaced a secret with one: it + covers using saved credentials without reading them (`ov privacy run`), and + naming or rotating them. +version: 2026.11.1 --- # OpenViking Memory @@ -98,6 +101,56 @@ Do not invent other keys or commands for this: that file is the whole interface, - Skills stored in OpenViking (the `` list, `add_skill`, moving local skills in) are covered by the `openviking-skills` skill. +## Saved credentials + +OpenViking keeps the user's API keys and tokens in Privacy. A saved secret is +named by a reference such as +`{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}`: the +owner, then the field. It stands for a value you are not meant to read. + +- **Use it without reading it** — `ov privacy run` resolves references for one + local command and masks their values in its output. Pass a reference as an + environment variable with `--env NAME=REF` (repeatable), load `NAME=REF` + lines with `--env-file `, or put it inside an argument; the command + comes after `--`. Single-quote every reference in a shell command, because + `{{…}}` and `#` are otherwise open to shell interpretation: + + ```bash + ov privacy run --env GH_TOKEN='{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}' -- gh repo list + ``` + + To use the variable on the command line, wrap the command in `sh -c '…'`: + + ```bash + ov privacy run --env GH_TOKEN='' -- sh -c 'curl -H "Authorization: Bearer $GH_TOKEN" https://api.github.com/user' + ``` + + `$GH_TOKEN` written outside `sh -c '…'` is expanded by your own shell + before `ov` runs, and is empty. + + Prefer `--env`: with `OPENVIKING_PRIVACY_RUN_STRICT=1` references in arguments are refused. +- **Do not print values.** `privacy_resolve`, `ov privacy resolve`, + `ov privacy get` and `ov privacy version` print plain values; use them only + when the user asks to see a value. Do not print any part of a secret either + (a prefix, a suffix); to check a secret, print only its length. + `ov privacy run` masks only complete values in its output. +- **What exists** — `privacy_tree` lists targets, fields, their references and + descriptions, never values; on the CLI, `ov privacy tree --references` shows + the references and `ov privacy tree -o json` also the descriptions. The + description is how to tell similar credentials apart. `privacy_tree` leaves + the `auto` category out unless you ask for it with `category="auto"`; an + `auto/…` reference was created automatically and works like any other. +- **Naming and rotating** — only when the `privacy_upsert` tool's own + description says that a reference can be passed as the value: then a whole + reference as a value copies that field's current value, so the secret never + passes through you; prefer it. On the CLI, under the same condition: + `ov privacy upsert credential --field =''`. Use it + to save an automatic entry under a proper name in `credential`, or to + replace a value. The automatic entry is removed once saved, so use the + reference the upsert returns from then on. Give a short description of what + the credential is for: `description` on `privacy_upsert`, or `--labels-json + '{"description":"…"}'` on the CLI, which replaces all of the target's labels. + ## Beyond the MCP tools More advanced OpenViking operations are available through the `ov` CLI — diff --git a/examples/agent-hook-plugin/hosts/codebuddy/plugin.json b/examples/agent-hook-plugin/hosts/codebuddy/plugin.json index f9395b8b0a2..0e2477e1384 100644 --- a/examples/agent-hook-plugin/hosts/codebuddy/plugin.json +++ b/examples/agent-hook-plugin/hosts/codebuddy/plugin.json @@ -1,6 +1,6 @@ { "name": "openviking-memory", - "version": "0.5.39", + "version": "0.5.40", "description": "Long-term semantic memory for the CodeBuddy Code CLI, powered by OpenViking. Injects relevant context at session start and on each prompt, and captures the conversation back into OpenViking.", "author": { "name": "OpenViking", diff --git a/examples/agent-hook-plugin/hosts/codebuddy/skills/openviking-memory/SKILL.md b/examples/agent-hook-plugin/hosts/codebuddy/skills/openviking-memory/SKILL.md index 253a32e508c..2b9bb18320c 100644 --- a/examples/agent-hook-plugin/hosts/codebuddy/skills/openviking-memory/SKILL.md +++ b/examples/agent-hook-plugin/hosts/codebuddy/skills/openviking-memory/SKILL.md @@ -8,8 +8,11 @@ description: > context this session does not have — even if nobody says the word "memory". Also use it when the user asks where memories are stored: per project, per folder, or shared between repositories. Covers choosing between context search, find, list search, and grep, reading viking:// - URIs, and when (not) to write. -version: 2026.10.1 + URIs, and when (not) to write. Also use it when a message or file holds an + {{ov_privacy:…}} reference or says OpenViking replaced a secret with one: it + covers using saved credentials without reading them (`ov privacy run`), and + naming or rotating them. +version: 2026.11.1 --- # OpenViking Memory @@ -98,6 +101,56 @@ Do not invent other keys or commands for this: that file is the whole interface, - Skills stored in OpenViking (the `` list, `add_skill`, moving local skills in) are covered by the `openviking-skills` skill. +## Saved credentials + +OpenViking keeps the user's API keys and tokens in Privacy. A saved secret is +named by a reference such as +`{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}`: the +owner, then the field. It stands for a value you are not meant to read. + +- **Use it without reading it** — `ov privacy run` resolves references for one + local command and masks their values in its output. Pass a reference as an + environment variable with `--env NAME=REF` (repeatable), load `NAME=REF` + lines with `--env-file `, or put it inside an argument; the command + comes after `--`. Single-quote every reference in a shell command, because + `{{…}}` and `#` are otherwise open to shell interpretation: + + ```bash + ov privacy run --env GH_TOKEN='{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}' -- gh repo list + ``` + + To use the variable on the command line, wrap the command in `sh -c '…'`: + + ```bash + ov privacy run --env GH_TOKEN='' -- sh -c 'curl -H "Authorization: Bearer $GH_TOKEN" https://api.github.com/user' + ``` + + `$GH_TOKEN` written outside `sh -c '…'` is expanded by your own shell + before `ov` runs, and is empty. + + Prefer `--env`: with `OPENVIKING_PRIVACY_RUN_STRICT=1` references in arguments are refused. +- **Do not print values.** `privacy_resolve`, `ov privacy resolve`, + `ov privacy get` and `ov privacy version` print plain values; use them only + when the user asks to see a value. Do not print any part of a secret either + (a prefix, a suffix); to check a secret, print only its length. + `ov privacy run` masks only complete values in its output. +- **What exists** — `privacy_tree` lists targets, fields, their references and + descriptions, never values; on the CLI, `ov privacy tree --references` shows + the references and `ov privacy tree -o json` also the descriptions. The + description is how to tell similar credentials apart. `privacy_tree` leaves + the `auto` category out unless you ask for it with `category="auto"`; an + `auto/…` reference was created automatically and works like any other. +- **Naming and rotating** — only when the `privacy_upsert` tool's own + description says that a reference can be passed as the value: then a whole + reference as a value copies that field's current value, so the secret never + passes through you; prefer it. On the CLI, under the same condition: + `ov privacy upsert credential --field =''`. Use it + to save an automatic entry under a proper name in `credential`, or to + replace a value. The automatic entry is removed once saved, so use the + reference the upsert returns from then on. Give a short description of what + the credential is for: `description` on `privacy_upsert`, or `--labels-json + '{"description":"…"}'` on the CLI, which replaces all of the target's labels. + ## Beyond the MCP tools More advanced OpenViking operations are available through the `ov` CLI — diff --git a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json index 23b1f003d50..8c6baa1cae1 100644 --- a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json +++ b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "id": "openviking-memory", - "version": "0.5.39", + "version": "0.5.40", "clients": [ "cursor" ], diff --git a/examples/agent-hook-plugin/hosts/cursor/skills/openviking-memory/SKILL.md b/examples/agent-hook-plugin/hosts/cursor/skills/openviking-memory/SKILL.md index 253a32e508c..2b9bb18320c 100644 --- a/examples/agent-hook-plugin/hosts/cursor/skills/openviking-memory/SKILL.md +++ b/examples/agent-hook-plugin/hosts/cursor/skills/openviking-memory/SKILL.md @@ -8,8 +8,11 @@ description: > context this session does not have — even if nobody says the word "memory". Also use it when the user asks where memories are stored: per project, per folder, or shared between repositories. Covers choosing between context search, find, list search, and grep, reading viking:// - URIs, and when (not) to write. -version: 2026.10.1 + URIs, and when (not) to write. Also use it when a message or file holds an + {{ov_privacy:…}} reference or says OpenViking replaced a secret with one: it + covers using saved credentials without reading them (`ov privacy run`), and + naming or rotating them. +version: 2026.11.1 --- # OpenViking Memory @@ -98,6 +101,56 @@ Do not invent other keys or commands for this: that file is the whole interface, - Skills stored in OpenViking (the `` list, `add_skill`, moving local skills in) are covered by the `openviking-skills` skill. +## Saved credentials + +OpenViking keeps the user's API keys and tokens in Privacy. A saved secret is +named by a reference such as +`{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}`: the +owner, then the field. It stands for a value you are not meant to read. + +- **Use it without reading it** — `ov privacy run` resolves references for one + local command and masks their values in its output. Pass a reference as an + environment variable with `--env NAME=REF` (repeatable), load `NAME=REF` + lines with `--env-file `, or put it inside an argument; the command + comes after `--`. Single-quote every reference in a shell command, because + `{{…}}` and `#` are otherwise open to shell interpretation: + + ```bash + ov privacy run --env GH_TOKEN='{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}' -- gh repo list + ``` + + To use the variable on the command line, wrap the command in `sh -c '…'`: + + ```bash + ov privacy run --env GH_TOKEN='' -- sh -c 'curl -H "Authorization: Bearer $GH_TOKEN" https://api.github.com/user' + ``` + + `$GH_TOKEN` written outside `sh -c '…'` is expanded by your own shell + before `ov` runs, and is empty. + + Prefer `--env`: with `OPENVIKING_PRIVACY_RUN_STRICT=1` references in arguments are refused. +- **Do not print values.** `privacy_resolve`, `ov privacy resolve`, + `ov privacy get` and `ov privacy version` print plain values; use them only + when the user asks to see a value. Do not print any part of a secret either + (a prefix, a suffix); to check a secret, print only its length. + `ov privacy run` masks only complete values in its output. +- **What exists** — `privacy_tree` lists targets, fields, their references and + descriptions, never values; on the CLI, `ov privacy tree --references` shows + the references and `ov privacy tree -o json` also the descriptions. The + description is how to tell similar credentials apart. `privacy_tree` leaves + the `auto` category out unless you ask for it with `category="auto"`; an + `auto/…` reference was created automatically and works like any other. +- **Naming and rotating** — only when the `privacy_upsert` tool's own + description says that a reference can be passed as the value: then a whole + reference as a value copies that field's current value, so the secret never + passes through you; prefer it. On the CLI, under the same condition: + `ov privacy upsert credential --field =''`. Use it + to save an automatic entry under a proper name in `credential`, or to + replace a value. The automatic entry is removed once saved, so use the + reference the upsert returns from then on. Give a short description of what + the credential is for: `description` on `privacy_upsert`, or `--labels-json + '{"description":"…"}'` on the CLI, which replaces all of the target's labels. + ## Beyond the MCP tools More advanced OpenViking operations are available through the `ov` CLI — diff --git a/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json index b46e38109c3..3b5439665c5 100644 --- a/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json +++ b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json @@ -1,6 +1,6 @@ { "name": "openviking-memory", - "version": "0.5.39", + "version": "0.5.40", "description": "Long-term semantic memory for Kimi Code CLI, powered by OpenViking.", "author": { "name": "OpenViking", diff --git a/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json b/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json index dd49ae3c592..f7cc29ddbfe 100644 --- a/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json +++ b/examples/agent-hook-plugin/hosts/kimicode/openviking.integration.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "id": "openviking-memory", - "version": "0.5.39", + "version": "0.5.40", "clients": [ "kimicode" ], diff --git a/examples/agent-hook-plugin/hosts/kimicode/skills/openviking-memory/SKILL.md b/examples/agent-hook-plugin/hosts/kimicode/skills/openviking-memory/SKILL.md index 253a32e508c..2b9bb18320c 100644 --- a/examples/agent-hook-plugin/hosts/kimicode/skills/openviking-memory/SKILL.md +++ b/examples/agent-hook-plugin/hosts/kimicode/skills/openviking-memory/SKILL.md @@ -8,8 +8,11 @@ description: > context this session does not have — even if nobody says the word "memory". Also use it when the user asks where memories are stored: per project, per folder, or shared between repositories. Covers choosing between context search, find, list search, and grep, reading viking:// - URIs, and when (not) to write. -version: 2026.10.1 + URIs, and when (not) to write. Also use it when a message or file holds an + {{ov_privacy:…}} reference or says OpenViking replaced a secret with one: it + covers using saved credentials without reading them (`ov privacy run`), and + naming or rotating them. +version: 2026.11.1 --- # OpenViking Memory @@ -98,6 +101,56 @@ Do not invent other keys or commands for this: that file is the whole interface, - Skills stored in OpenViking (the `` list, `add_skill`, moving local skills in) are covered by the `openviking-skills` skill. +## Saved credentials + +OpenViking keeps the user's API keys and tokens in Privacy. A saved secret is +named by a reference such as +`{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}`: the +owner, then the field. It stands for a value you are not meant to read. + +- **Use it without reading it** — `ov privacy run` resolves references for one + local command and masks their values in its output. Pass a reference as an + environment variable with `--env NAME=REF` (repeatable), load `NAME=REF` + lines with `--env-file `, or put it inside an argument; the command + comes after `--`. Single-quote every reference in a shell command, because + `{{…}}` and `#` are otherwise open to shell interpretation: + + ```bash + ov privacy run --env GH_TOKEN='{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}' -- gh repo list + ``` + + To use the variable on the command line, wrap the command in `sh -c '…'`: + + ```bash + ov privacy run --env GH_TOKEN='' -- sh -c 'curl -H "Authorization: Bearer $GH_TOKEN" https://api.github.com/user' + ``` + + `$GH_TOKEN` written outside `sh -c '…'` is expanded by your own shell + before `ov` runs, and is empty. + + Prefer `--env`: with `OPENVIKING_PRIVACY_RUN_STRICT=1` references in arguments are refused. +- **Do not print values.** `privacy_resolve`, `ov privacy resolve`, + `ov privacy get` and `ov privacy version` print plain values; use them only + when the user asks to see a value. Do not print any part of a secret either + (a prefix, a suffix); to check a secret, print only its length. + `ov privacy run` masks only complete values in its output. +- **What exists** — `privacy_tree` lists targets, fields, their references and + descriptions, never values; on the CLI, `ov privacy tree --references` shows + the references and `ov privacy tree -o json` also the descriptions. The + description is how to tell similar credentials apart. `privacy_tree` leaves + the `auto` category out unless you ask for it with `category="auto"`; an + `auto/…` reference was created automatically and works like any other. +- **Naming and rotating** — only when the `privacy_upsert` tool's own + description says that a reference can be passed as the value: then a whole + reference as a value copies that field's current value, so the secret never + passes through you; prefer it. On the CLI, under the same condition: + `ov privacy upsert credential --field =''`. Use it + to save an automatic entry under a proper name in `credential`, or to + replace a value. The automatic entry is removed once saved, so use the + reference the upsert returns from then on. Give a short description of what + the credential is for: `description` on `privacy_upsert`, or `--labels-json + '{"description":"…"}'` on the CLI, which replaces all of the target's labels. + ## Beyond the MCP tools More advanced OpenViking operations are available through the `ov` CLI — diff --git a/examples/agent-hook-plugin/hosts/qoder/plugin.json b/examples/agent-hook-plugin/hosts/qoder/plugin.json index 60888ab5778..4275ac24023 100644 --- a/examples/agent-hook-plugin/hosts/qoder/plugin.json +++ b/examples/agent-hook-plugin/hosts/qoder/plugin.json @@ -1,6 +1,6 @@ { "name": "openviking-memory", - "version": "0.5.39", + "version": "0.5.40", "description": "Long-term semantic memory for the Qoder CLI, powered by OpenViking. Injects relevant context at session start and on each prompt, and captures the conversation back into OpenViking.", "author": { "name": "OpenViking", diff --git a/examples/agent-hook-plugin/hosts/qoder/skills/openviking-memory/SKILL.md b/examples/agent-hook-plugin/hosts/qoder/skills/openviking-memory/SKILL.md index 253a32e508c..2b9bb18320c 100644 --- a/examples/agent-hook-plugin/hosts/qoder/skills/openviking-memory/SKILL.md +++ b/examples/agent-hook-plugin/hosts/qoder/skills/openviking-memory/SKILL.md @@ -8,8 +8,11 @@ description: > context this session does not have — even if nobody says the word "memory". Also use it when the user asks where memories are stored: per project, per folder, or shared between repositories. Covers choosing between context search, find, list search, and grep, reading viking:// - URIs, and when (not) to write. -version: 2026.10.1 + URIs, and when (not) to write. Also use it when a message or file holds an + {{ov_privacy:…}} reference or says OpenViking replaced a secret with one: it + covers using saved credentials without reading them (`ov privacy run`), and + naming or rotating them. +version: 2026.11.1 --- # OpenViking Memory @@ -98,6 +101,56 @@ Do not invent other keys or commands for this: that file is the whole interface, - Skills stored in OpenViking (the `` list, `add_skill`, moving local skills in) are covered by the `openviking-skills` skill. +## Saved credentials + +OpenViking keeps the user's API keys and tokens in Privacy. A saved secret is +named by a reference such as +`{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}`: the +owner, then the field. It stands for a value you are not meant to read. + +- **Use it without reading it** — `ov privacy run` resolves references for one + local command and masks their values in its output. Pass a reference as an + environment variable with `--env NAME=REF` (repeatable), load `NAME=REF` + lines with `--env-file `, or put it inside an argument; the command + comes after `--`. Single-quote every reference in a shell command, because + `{{…}}` and `#` are otherwise open to shell interpretation: + + ```bash + ov privacy run --env GH_TOKEN='{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}' -- gh repo list + ``` + + To use the variable on the command line, wrap the command in `sh -c '…'`: + + ```bash + ov privacy run --env GH_TOKEN='' -- sh -c 'curl -H "Authorization: Bearer $GH_TOKEN" https://api.github.com/user' + ``` + + `$GH_TOKEN` written outside `sh -c '…'` is expanded by your own shell + before `ov` runs, and is empty. + + Prefer `--env`: with `OPENVIKING_PRIVACY_RUN_STRICT=1` references in arguments are refused. +- **Do not print values.** `privacy_resolve`, `ov privacy resolve`, + `ov privacy get` and `ov privacy version` print plain values; use them only + when the user asks to see a value. Do not print any part of a secret either + (a prefix, a suffix); to check a secret, print only its length. + `ov privacy run` masks only complete values in its output. +- **What exists** — `privacy_tree` lists targets, fields, their references and + descriptions, never values; on the CLI, `ov privacy tree --references` shows + the references and `ov privacy tree -o json` also the descriptions. The + description is how to tell similar credentials apart. `privacy_tree` leaves + the `auto` category out unless you ask for it with `category="auto"`; an + `auto/…` reference was created automatically and works like any other. +- **Naming and rotating** — only when the `privacy_upsert` tool's own + description says that a reference can be passed as the value: then a whole + reference as a value copies that field's current value, so the secret never + passes through you; prefer it. On the CLI, under the same condition: + `ov privacy upsert credential --field =''`. Use it + to save an automatic entry under a proper name in `credential`, or to + replace a value. The automatic entry is removed once saved, so use the + reference the upsert returns from then on. Give a short description of what + the credential is for: `description` on `privacy_upsert`, or `--labels-json + '{"description":"…"}'` on the CLI, which replaces all of the target's labels. + ## Beyond the MCP tools More advanced OpenViking operations are available through the `ov` CLI — diff --git a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json index 765dda9cf53..b7ee0bb0972 100644 --- a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json +++ b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "id": "openviking-memory", - "version": "0.5.39", + "version": "0.5.40", "clients": [ "trae", "trae-cn" diff --git a/examples/agent-hook-plugin/hosts/trae/skills/openviking-memory/SKILL.md b/examples/agent-hook-plugin/hosts/trae/skills/openviking-memory/SKILL.md index 253a32e508c..2b9bb18320c 100644 --- a/examples/agent-hook-plugin/hosts/trae/skills/openviking-memory/SKILL.md +++ b/examples/agent-hook-plugin/hosts/trae/skills/openviking-memory/SKILL.md @@ -8,8 +8,11 @@ description: > context this session does not have — even if nobody says the word "memory". Also use it when the user asks where memories are stored: per project, per folder, or shared between repositories. Covers choosing between context search, find, list search, and grep, reading viking:// - URIs, and when (not) to write. -version: 2026.10.1 + URIs, and when (not) to write. Also use it when a message or file holds an + {{ov_privacy:…}} reference or says OpenViking replaced a secret with one: it + covers using saved credentials without reading them (`ov privacy run`), and + naming or rotating them. +version: 2026.11.1 --- # OpenViking Memory @@ -98,6 +101,56 @@ Do not invent other keys or commands for this: that file is the whole interface, - Skills stored in OpenViking (the `` list, `add_skill`, moving local skills in) are covered by the `openviking-skills` skill. +## Saved credentials + +OpenViking keeps the user's API keys and tokens in Privacy. A saved secret is +named by a reference such as +`{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}`: the +owner, then the field. It stands for a value you are not meant to read. + +- **Use it without reading it** — `ov privacy run` resolves references for one + local command and masks their values in its output. Pass a reference as an + environment variable with `--env NAME=REF` (repeatable), load `NAME=REF` + lines with `--env-file `, or put it inside an argument; the command + comes after `--`. Single-quote every reference in a shell command, because + `{{…}}` and `#` are otherwise open to shell interpretation: + + ```bash + ov privacy run --env GH_TOKEN='{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}' -- gh repo list + ``` + + To use the variable on the command line, wrap the command in `sh -c '…'`: + + ```bash + ov privacy run --env GH_TOKEN='' -- sh -c 'curl -H "Authorization: Bearer $GH_TOKEN" https://api.github.com/user' + ``` + + `$GH_TOKEN` written outside `sh -c '…'` is expanded by your own shell + before `ov` runs, and is empty. + + Prefer `--env`: with `OPENVIKING_PRIVACY_RUN_STRICT=1` references in arguments are refused. +- **Do not print values.** `privacy_resolve`, `ov privacy resolve`, + `ov privacy get` and `ov privacy version` print plain values; use them only + when the user asks to see a value. Do not print any part of a secret either + (a prefix, a suffix); to check a secret, print only its length. + `ov privacy run` masks only complete values in its output. +- **What exists** — `privacy_tree` lists targets, fields, their references and + descriptions, never values; on the CLI, `ov privacy tree --references` shows + the references and `ov privacy tree -o json` also the descriptions. The + description is how to tell similar credentials apart. `privacy_tree` leaves + the `auto` category out unless you ask for it with `category="auto"`; an + `auto/…` reference was created automatically and works like any other. +- **Naming and rotating** — only when the `privacy_upsert` tool's own + description says that a reference can be passed as the value: then a whole + reference as a value copies that field's current value, so the secret never + passes through you; prefer it. On the CLI, under the same condition: + `ov privacy upsert credential --field =''`. Use it + to save an automatic entry under a proper name in `credential`, or to + replace a value. The automatic entry is removed once saved, so use the + reference the upsert returns from then on. Give a short description of what + the credential is for: `description` on `privacy_upsert`, or `--labels-json + '{"description":"…"}'` on the CLI, which replaces all of the target's labels. + ## Beyond the MCP tools More advanced OpenViking operations are available through the `ov` CLI — diff --git a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json index 736ef0f8062..8c3d973208f 100644 --- a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json +++ b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "id": "openviking-memory", - "version": "0.5.39", + "version": "0.5.40", "clients": [ "zcode" ], diff --git a/examples/agent-hook-plugin/hosts/zcode/skills/openviking-memory/SKILL.md b/examples/agent-hook-plugin/hosts/zcode/skills/openviking-memory/SKILL.md index 253a32e508c..2b9bb18320c 100644 --- a/examples/agent-hook-plugin/hosts/zcode/skills/openviking-memory/SKILL.md +++ b/examples/agent-hook-plugin/hosts/zcode/skills/openviking-memory/SKILL.md @@ -8,8 +8,11 @@ description: > context this session does not have — even if nobody says the word "memory". Also use it when the user asks where memories are stored: per project, per folder, or shared between repositories. Covers choosing between context search, find, list search, and grep, reading viking:// - URIs, and when (not) to write. -version: 2026.10.1 + URIs, and when (not) to write. Also use it when a message or file holds an + {{ov_privacy:…}} reference or says OpenViking replaced a secret with one: it + covers using saved credentials without reading them (`ov privacy run`), and + naming or rotating them. +version: 2026.11.1 --- # OpenViking Memory @@ -98,6 +101,56 @@ Do not invent other keys or commands for this: that file is the whole interface, - Skills stored in OpenViking (the `` list, `add_skill`, moving local skills in) are covered by the `openviking-skills` skill. +## Saved credentials + +OpenViking keeps the user's API keys and tokens in Privacy. A saved secret is +named by a reference such as +`{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}`: the +owner, then the field. It stands for a value you are not meant to read. + +- **Use it without reading it** — `ov privacy run` resolves references for one + local command and masks their values in its output. Pass a reference as an + environment variable with `--env NAME=REF` (repeatable), load `NAME=REF` + lines with `--env-file `, or put it inside an argument; the command + comes after `--`. Single-quote every reference in a shell command, because + `{{…}}` and `#` are otherwise open to shell interpretation: + + ```bash + ov privacy run --env GH_TOKEN='{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}' -- gh repo list + ``` + + To use the variable on the command line, wrap the command in `sh -c '…'`: + + ```bash + ov privacy run --env GH_TOKEN='' -- sh -c 'curl -H "Authorization: Bearer $GH_TOKEN" https://api.github.com/user' + ``` + + `$GH_TOKEN` written outside `sh -c '…'` is expanded by your own shell + before `ov` runs, and is empty. + + Prefer `--env`: with `OPENVIKING_PRIVACY_RUN_STRICT=1` references in arguments are refused. +- **Do not print values.** `privacy_resolve`, `ov privacy resolve`, + `ov privacy get` and `ov privacy version` print plain values; use them only + when the user asks to see a value. Do not print any part of a secret either + (a prefix, a suffix); to check a secret, print only its length. + `ov privacy run` masks only complete values in its output. +- **What exists** — `privacy_tree` lists targets, fields, their references and + descriptions, never values; on the CLI, `ov privacy tree --references` shows + the references and `ov privacy tree -o json` also the descriptions. The + description is how to tell similar credentials apart. `privacy_tree` leaves + the `auto` category out unless you ask for it with `category="auto"`; an + `auto/…` reference was created automatically and works like any other. +- **Naming and rotating** — only when the `privacy_upsert` tool's own + description says that a reference can be passed as the value: then a whole + reference as a value copies that field's current value, so the secret never + passes through you; prefer it. On the CLI, under the same condition: + `ov privacy upsert credential --field =''`. Use it + to save an automatic entry under a proper name in `credential`, or to + replace a value. The automatic entry is removed once saved, so use the + reference the upsert returns from then on. Give a short description of what + the credential is for: `description` on `privacy_upsert`, or `--labels-json + '{"description":"…"}'` on the CLI, which replaces all of the target's labels. + ## Beyond the MCP tools More advanced OpenViking operations are available through the `ov` CLI — diff --git a/examples/agent-hook-plugin/plugin.json b/examples/agent-hook-plugin/plugin.json index f9fb484fb19..9d8bfa99a9e 100644 --- a/examples/agent-hook-plugin/plugin.json +++ b/examples/agent-hook-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agent-hook-plugin", - "version": "0.5.39", + "version": "0.5.40", "description": "Long-term semantic memory for Cursor, TRAE, TRAE CN, ZCode, Kimi Code, CodeBuddy Code, Qoder CLI and Antigravity — powered by OpenViking. Auto-recall relevant memories and capture the conversation as it happens.", "author": { "name": "OpenViking", diff --git a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json index 50eae2d0bc6..1e675c220ed 100644 --- a/examples/claude-code-memory-plugin/.claude-plugin/plugin.json +++ b/examples/claude-code-memory-plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "openviking-memory", - "version": "0.7.31", + "version": "0.7.32", "description": "Long-term semantic memory for Claude Code, powered by OpenViking. Auto-recall relevant memories at session start and capture important information during conversations.", "author": { "name": "OpenViking", diff --git a/examples/claude-code-memory-plugin/README.md b/examples/claude-code-memory-plugin/README.md index 1f699664d5a..de9893b2337 100644 --- a/examples/claude-code-memory-plugin/README.md +++ b/examples/claude-code-memory-plugin/README.md @@ -250,6 +250,8 @@ The bundled `openviking-skills` skill tells Claude what to do with the catalog: | `OPENVIKING_DEBUG_LOG` | `~/.openviking/logs/cc-hooks.log` | Override log path | | `OPENVIKING_CONFIG_FILE` | `~/.openviking/ov.conf` | Override `ov.conf` path | | `OPENVIKING_CLI_CONFIG_FILE` | `~/.openviking/ovcli.conf` | Override `ovcli.conf` path | +| `OPENVIKING_SEAL_SECRETS` | `false` | Replace secrets with Privacy references in what Claude reads, and give tools the values back; see [Seal secrets](#seal-secrets) | +| `OPENVIKING_ENROLL_TOOL_SECRETS` | `false` | With sealing on, also enroll new secrets found in tool output; see [Seal secrets](#seal-secrets) | Pure-env example (no config file required): @@ -283,6 +285,37 @@ OPENVIKING_BYPASS_SESSION=1 claude When bypass is active, every hook approves immediately without contacting OpenViking. +### Seal secrets + +Off by default; it runs on your machine and needs OpenViking server 0.5.7 or newer. Two settings in `ovcli.conf`, each with an environment override: + +```json +{ "plugin": { "claude_code": { "sealSecrets": true, "enrollToolSecrets": false } } } +``` + +- `sealSecrets` (`OPENVIKING_SEAL_SECRETS`) turns sealing on. +- `enrollToolSecrets` (`OPENVIKING_ENROLL_TOOL_SECRETS`) also sends tool results with enrollment, so a secret first seen in a command's output or a file is saved too. It has no effect while `sealSecrets` is off. + +With `sealSecrets` on, Claude reads `{{ov_privacy:…}}` references in place of secrets, and tools get the real values: + +- **Your prompt.** Each prompt goes to OpenViking (`POST /api/v1/privacy-configs/seal`) before Claude Code sends it. Secrets already saved in Privacy are replaced with their references. Tokens the server's detector recognises (its built-in rules plus your `custom_rules`, minus `never_mask`) are saved as new entries in the `auto` category, such as `auto/github-k3j2m8`, and replaced too. While a prompt holds such a temporary entry, Claude gets a note telling it to save the entry under a proper name with a short description unless it is clearly for one-off use, use the reference that returns (for example with `ov privacy run`), and tell you what it stored. Slash commands and empty prompts are left alone. +- **Tool results.** Every string in a tool's result (Bash output, a file Read returns, an MCP tool's answer, a failed command's error) is sealed before Claude reads it. Saved secrets are replaced; new ones are enrolled only with `enrollToolSecrets`. The transcript stores the sealed result. +- **Tool arguments.** A reference Claude writes in a tool call is replaced by its value before the tool runs, so the command or the file gets the real secret, while the conversation keeps the reference Claude wrote. Only a whole reference to your own `credential` or `auto` entries is replaced, and only when the server resolves it and the value seals back to the same reference. A string with an `ov privacy` command, OpenViking's own tools, and tools that pass their arguments to a model (`Agent`, `Task`, `SendMessage`, `Workflow`, `Skill`) keep the references as written. +- **Attached and `@`-mentioned files, and reminders.** The text Claude Code injects for the model (a mentioned file's contents, `CLAUDE.md` files found while working, reminders, other hooks' context) is sealed without enrolling. The transcript keeps the engine's own record of these, with the original text. + +How it runs and fails: + +- **Read once per session.** The plugin runs `node scripts/seal-prompt.mjs` once per session to read the settings, how to reach the server (the URL and headers every other hook uses), and whether the server can seal: the helper reads the version from the server's `/health` and compares it with the feature table the plugin ships (`scripts/shared/server-features.json`), where sealing needs 0.5.7 (a development build such as `0.5.7.dev44` counts as 0.5.7). The hooks module then sends every seal and resolve call from the hooks module itself, through Claude Code's HTTP API. A changed setting takes effect in a new session (`/clear` counts as one). After a stopped prompt, the next prompt reads all of this again, so sealing resumes once the server can seal. While it is off, nothing is run after that first read. +- **When sealing cannot be done, it stops.** That is: the server is older than 0.5.7, its `/health` fails (the version is unknown), a seal or resolve call fails (the server cannot be reached, answers with an error or a malformed answer, or too slowly: 10 s per call), or `OPENVIKING_SEAL_SECRETS` turns sealing on but the setting helper gives no answer. The prompt is not sent and Claude Code shows why (for a version, the required and the actual one) and what to do: upgrade or reach the server, or turn `sealSecrets` off. A tool result is replaced by a short note saying it was withheld (the tool did run); a tool call whose reference cannot be resolved is blocked with the reason; an attachment is replaced by a short note. To a server that is too old or whose version is unknown, no seal call is made at all. `OPENVIKING_SEAL_SECRETS=0` turns sealing off without running anything, even when the plugin's own helper is broken. +- **The session text** (what Claude is told about references) comes with the first prompt the hooks module seals in a session, and again with the first one after a compaction or after the module reloads. +- **Cost.** One server call per prompt, per tool result and per injected attachment (Claude Code asks once per attachment and keeps the answer), plus a resolve call and a check per reference in a tool call. +- **Not covered.** The system prompt, slash-command arguments, skill bodies, and history written before sealing was turned on are not sealed. OpenViking's own tools are recognised by a name containing `openviking`: with the OpenViking MCP server registered under another name, references in the arguments of its `privacy_upsert`, `write` or `remember` are replaced by their values before the call. +- **Undoing a false positive.** Delete the entry (`ov privacy delete auto `), and add the value to `never_mask` so it is not enrolled again. +- **Requirements.** Sealing is part of the plugin's hooks module (`mods/seal/`), so it needs what [Source cards](#source-cards) need. On a Claude Code that does not load the module it does not run, and nothing is sealed. Reading the setting needs Claude Code's process API (the CLI has it). Where it is missing (or the helper gives no answer), sealing stays off without a message, whatever `ovcli.conf` says; set `OPENVIKING_SEAL_SECRETS=1` there and prompts are stopped with a message that the settings could not be read. +- No sealing setting is a workspace setting, so a repository's `.openviking/config.json` cannot switch them. + +To try it with a local server: save a value (`ov privacy upsert credential demo --values-json '{"token":""}'`), turn `sealSecrets` on, start `claude`, and ask it to `echo` the value: the answer it reads holds `{{ov_privacy:…}}`. Ask it to run `printf '%s' '{{ov_privacy:…}}' > /tmp/t` with that reference: `/tmp/t` holds the value. + ### Input filters Two knobs put an ordered list of regex rules in front of the text the plugin sends: @@ -450,7 +483,7 @@ Claude's own lookups - An answer that used nothing from OpenViking gets no card. - Expand or collapse one card with its button. Expand or collapse every card with `/openviking-usage expand` or `/openviking-usage collapse`. -**Requirements.** Cards are a Claude Code hooks module (`modules` in `hooks/hooks.json`, code in `mods/usage/`). They need Claude Code 2.1.286 or newer with hooks modules enabled. Claude Code ignores the module and runs the command hooks as before in these cases: +**Requirements.** Cards are a Claude Code hooks module (`modules` in `hooks/hooks.json`, entry `mods/register.ts`, code in `mods/usage/`). They need Claude Code 2.1.286 or newer with hooks modules enabled. Claude Code ignores the module and runs the command hooks as before in these cases: - On versions without modules. - When modules are switched off, for example with `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=0` or by the rollout flag. @@ -461,7 +494,7 @@ On builds between the first modules release and 2.1.286 with modules switched on It keeps each answer's source URIs, scores, redacted search queries, and the transcript row id and a hash of the reply text it sits under (the desktop finds a card's reply by that hash) in Claude Code's plugin store, for the last 20 sessions, so cards survive `claude --continue`. Shell commands and prompt text are not stored. The card isn't sent to Claude, so it costs no tokens. -**Development.** `claude plugin test examples/claude-code-memory-plugin` runs `mods/usage/sources.test.ts`. After `claude --plugin-dir examples/claude-code-memory-plugin` has generated `.claude-plugin/types/`, run `tsc -p examples/claude-code-memory-plugin/mods/usage` to type-check the module. +**Development.** `claude plugin test examples/claude-code-memory-plugin` runs `mods/usage/sources.test.ts` and `mods/seal/seal.test.ts`. Prompt sealing's decisions are also tested with `node --test` in `scripts/lib/prompt-seal.test.mjs` and `scripts/seal-prompt.test.mjs`. After `claude --plugin-dir examples/claude-code-memory-plugin` has generated `.claude-plugin/types/`, run `tsc -p examples/claude-code-memory-plugin/mods/usage` (or `mods/seal`) to type-check the module. ## Debug logging @@ -575,6 +608,10 @@ claude-code-memory-plugin/ │ └── hooks.json # 9 hook registrations ├── commands/ │ └── ov.md # /ov status command +├── mods/ +│ ├── register.ts # hooks module entry +│ ├── seal/ # seal secrets in prompts, tool calls/results and attachments +│ └── usage/ # source cards ├── skills/ │ ├── openviking-memory/ # how to use the memory tools │ ├── openviking-skills/ # find, add, share, and migrate OpenViking skills @@ -594,6 +631,7 @@ claude-code-memory-plugin/ │ ├── subagent-stop.mjs # SubagentStop │ ├── ov-status.mjs # /ov status report │ ├── ov-memory-doctor.mjs # diagnostics script (ov-memory-doctor skill) +│ ├── seal-prompt.mjs # setting helper for mods/seal │ └── lib/ │ ├── ov-session.mjs # OV HTTP client + session helpers + bypass check │ └── async-writer.mjs # detached-worker helper for write-path hooks diff --git a/examples/claude-code-memory-plugin/README_CN.md b/examples/claude-code-memory-plugin/README_CN.md index 09d236fae0e..d97aa54bed9 100644 --- a/examples/claude-code-memory-plugin/README_CN.md +++ b/examples/claude-code-memory-plugin/README_CN.md @@ -218,6 +218,8 @@ claude | `OPENVIKING_DEBUG_LOG` | `~/.openviking/logs/cc-hooks.log` | 覆盖日志路径 | | `OPENVIKING_CONFIG_FILE` | `~/.openviking/ov.conf` | 覆盖 `ov.conf` 路径 | | `OPENVIKING_CLI_CONFIG_FILE` | `~/.openviking/ovcli.conf` | 覆盖 `ovcli.conf` 路径 | +| `OPENVIKING_SEAL_SECRETS` | `false` | 把 Claude 读到的内容里的密钥换成 Privacy 引用,并把真实值交给工具;见[封存密钥](#封存密钥) | +| `OPENVIKING_ENROLL_TOOL_SECRETS` | `false` | 封存打开时,工具输出里的新密钥也登记;见[封存密钥](#封存密钥) | 纯环境变量启动(无需配置文件): @@ -251,6 +253,37 @@ OPENVIKING_BYPASS_SESSION=1 claude bypass 命中时所有 hook 直接放行,不联系 OpenViking。 +### 封存密钥 + +默认关闭,在你的机器上运行,需要 OpenViking 服务端 0.5.7 或更新版本。`ovcli.conf` 里有两个设置,各有一个环境变量覆盖: + +```json +{ "plugin": { "claude_code": { "sealSecrets": true, "enrollToolSecrets": false } } } +``` + +- `sealSecrets`(`OPENVIKING_SEAL_SECRETS`)打开封存。 +- `enrollToolSecrets`(`OPENVIKING_ENROLL_TOOL_SECRETS`)让工具结果也带登记发送,第一次出现在命令输出或文件里的密钥也会存下来。`sealSecrets` 关闭时不起作用。 + +打开 `sealSecrets` 后,Claude 读到的是 `{{ov_privacy:…}}` 引用而不是密钥,工具拿到的是真实值: + +- **你的提示。** 每条提示在 Claude Code 发出之前先发到 OpenViking(`POST /api/v1/privacy-configs/seal`)。已经存进 Privacy 的密钥会换成对应的引用。服务端探测器认得出的 token(内置规则加上你的 `custom_rules`,去掉 `never_mask`)会登记成 `auto` 类别下的新条目,比如 `auto/github-k3j2m8`,同样换成引用。提示里含有这类临时条目时,Claude 会收到一句提示:除非明显只用一次,先把条目存到正式名字下并写一句用途说明,之后使用保存时返回的引用(比如配合 `ov privacy run`),并告诉你存了什么。斜杠命令和空提示不处理。 +- **工具结果。** 工具结果里的每个字符串(Bash 输出、Read 读到的文件、MCP 工具的回答、失败命令的报错)在 Claude 读到之前都会封存。已保存的密钥会被替换;新密钥只在打开 `enrollToolSecrets` 时登记。会话记录里存的是封存后的结果。 +- **工具参数。** Claude 在工具调用里写的引用,会在工具运行前换成真实值,所以命令或文件拿到的是真正的密钥,对话里保留的仍是 Claude 写的引用。只替换指向你自己 `credential` 或 `auto` 条目的完整引用,并且要服务端能解析出值、这个值再封存回来是同一个引用。含有 `ov privacy` 命令的字符串、OpenViking 自己的工具,以及把参数交给模型的工具(`Agent`、`Task`、`SendMessage`、`Workflow`、`Skill`)保留原样的引用。 +- **附加和 `@` 提及的文件,以及提醒。** Claude Code 为模型注入的文本(提及文件的内容、工作中发现的 `CLAUDE.md`、各种提醒、其他 hook 的上下文)封存时不登记。会话记录里保存的是 Claude Code 自己的记录,仍是原文。 + +运行方式和出错时的行为: + +- **每个会话读一次。** 插件每个会话运行一次 `node scripts/seal-prompt.mjs`,读取设置、连接服务端的方式(和其他 hook 相同的 URL 和请求头),以及服务端能否封存:辅助脚本从服务端的 `/health` 读取版本,和插件自带的功能表(`scripts/shared/server-features.json`)比较,封存需要 0.5.7(`0.5.7.dev44` 这样的开发版算作 0.5.7)。之后所有封存和解析请求都由 hooks 模块通过 Claude Code 的 HTTP 接口直接发出。改了设置要到新会话才生效(`/clear` 也算新会话)。提示被拦下之后,下一条提示会重新读取这些内容,所以服务端能封存之后封存就恢复。关闭时,第一次读取之后不再运行任何东西。 +- **无法封存时会拦下。** 包括:服务端版本低于 0.5.7;`/health` 失败(版本未知);封存或解析请求失败(服务端连不上、返回错误或格式不对的回答、超时,每次请求 10 秒);`OPENVIKING_SEAL_SECRETS` 打开了封存,但读取设置的辅助脚本没有给出结果。提示不会发出,Claude Code 会显示原因(版本问题会写出要求的版本和实际版本)和怎么办:升级服务端或恢复连接,或者关闭 `sealSecrets`。工具结果换成一句说明,告诉 Claude 结果被扣下了(工具已经运行过);引用解析不了的工具调用会被拦下并给出原因;附件换成一句说明。对版本太旧或版本未知的服务端,根本不发封存请求。`OPENVIKING_SEAL_SECRETS=0` 不运行任何东西直接关闭封存,插件自己的辅助脚本坏了也能关掉。 +- **会话说明**(告诉 Claude 引用是怎么回事的那段文字)随 hooks 模块在一个会话里封存的第一条提示一起发出,压缩(compact)之后或模块重新加载之后的第一条提示再带一次。 +- **开销。** 每条提示、每个工具结果、每个注入的附件各一次服务端请求(Claude Code 对每个附件只问一次并记住结果),工具调用里的每个引用再加一次解析和一次校验。 +- **不覆盖的内容。** 系统提示、斜杠命令参数、skill 正文,以及打开封存之前写下的历史,会原样到达 Claude。OpenViking 自己的工具按名字里含 `openviking` 识别:把 OpenViking MCP 服务器注册成别的名字时,它的 `privacy_upsert`、`write` 或 `remember` 参数里的引用会在调用前换成真实值。 +- **误报的撤销。** 删除这个条目(`ov privacy delete auto `),再把这个值加进 `never_mask`,以后就不会再登记。 +- **前提。** 封存是插件 hooks 模块的一部分(`mods/seal/`),前提和[来源卡片](#来源卡片)相同。Claude Code 不加载这个模块时封存不会运行,所有内容原样发出。读取设置需要 Claude Code 的进程接口(CLI 有)。没有这个接口(或辅助脚本没有给出结果)时,不管 `ovcli.conf` 怎么写,封存都保持关闭,也不显示提示;在这类环境里设置 `OPENVIKING_SEAL_SECRETS=1`,提示会被拦下,并说明读不到设置。 +- 封存相关的设置都不是工作区设置,仓库里的 `.openviking/config.json` 改不了它们。 + +用本地服务端试一下:先存一个值(`ov privacy upsert credential demo --values-json '{"token":""}'`),打开 `sealSecrets`,启动 `claude`,让它 `echo` 这个值:它读到的回答里是 `{{ov_privacy:…}}`。再让它用这个引用运行 `printf '%s' '{{ov_privacy:…}}' > /tmp/t`:`/tmp/t` 里是真实值。 + ### 输入过滤器 两个配置项在插件送出文本之前加了一层有序的正则规则: @@ -398,7 +431,7 @@ Claude's own lookups - 没用到任何 OpenViking 内容的回答不显示卡片。 - 用卡片上的按钮展开或折叠单张卡片;用 `/openviking-usage expand` 或 `/openviking-usage collapse` 展开或折叠全部卡片。界面文字只有英文。 -**前提。** 卡片是一个 Claude Code hooks 模块(`hooks/hooks.json` 里的 `modules`,代码在 `mods/usage/`),需要 Claude Code 2.1.286 或更高版本,并启用 hooks 模块。下面这些情况下,Claude Code 会忽略这个模块,命令 hook 照常运行: +**前提。** 卡片是一个 Claude Code hooks 模块(`hooks/hooks.json` 里的 `modules`,入口 `mods/register.ts`,代码在 `mods/usage/`),需要 Claude Code 2.1.286 或更高版本,并启用 hooks 模块。下面这些情况下,Claude Code 会忽略这个模块,命令 hook 照常运行: - 版本不支持模块。 - 模块被关闭,例如设置了 `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=0`,或被灰度开关关闭。 @@ -409,7 +442,7 @@ Claude's own lookups 它在 Claude Code 的插件存储里保存每次回答的来源 URI、分数、脱敏后的搜索词,以及卡片所在对话行的 id 和该行回答文本的哈希(桌面端靠这个哈希找到卡片对应的回答),保留最近 20 个会话,所以 `claude --continue` 之后卡片还在。不保存 shell 命令和提示原文。卡片不会发给 Claude,不消耗 token。 -**开发。** `claude plugin test examples/claude-code-memory-plugin` 会运行 `mods/usage/sources.test.ts`。用 `claude --plugin-dir examples/claude-code-memory-plugin` 启动一次、生成 `.claude-plugin/types/` 后,可以用 `tsc -p examples/claude-code-memory-plugin/mods/usage` 做类型检查。 +**开发。** `claude plugin test examples/claude-code-memory-plugin` 会运行 `mods/usage/sources.test.ts` 和 `mods/seal/seal.test.ts`。提示封存的判断逻辑另用 `node --test` 测试,见 `scripts/lib/prompt-seal.test.mjs` 和 `scripts/seal-prompt.test.mjs`。用 `claude --plugin-dir examples/claude-code-memory-plugin` 启动一次、生成 `.claude-plugin/types/` 后,可以用 `tsc -p examples/claude-code-memory-plugin/mods/usage`(或 `mods/seal`)做类型检查。 ## 调试日志 @@ -520,7 +553,7 @@ claude-code-memory-plugin/ ├── .claude-plugin/ │ └── plugin.json # plugin manifest ├── hooks/ -│ └── hooks.json # 9 个 hook 注册 + 来源卡片模块 +│ └── hooks.json # 9 个 hook 注册 + hooks 模块 ├── commands/ │ └── ov.md # /ov 状态命令 ├── skills/ @@ -529,7 +562,9 @@ claude-code-memory-plugin/ │ ├── ov-experience-memory/ │ └── ov-memory-doctor/ # 安装 / 配置 / 连接 / 本机 server 排障 ├── mods/ -│ └── usage/ # 来源卡片(Claude Code hooks 模块) +│ ├── register.ts # hooks 模块入口 +│ ├── seal/ # 封存提示、工具调用和结果、附件里的密钥 +│ └── usage/ # 来源卡片 ├── servers/ │ └── mcp-proxy.mjs # stdio -> OpenViking /mcp 桥接 ├── scripts/ @@ -544,6 +579,7 @@ claude-code-memory-plugin/ │ ├── subagent-stop.mjs # SubagentStop │ ├── ov-status.mjs # /ov 状态报告 │ ├── ov-memory-doctor.mjs # 体检脚本(ov-memory-doctor skill) +│ ├── seal-prompt.mjs # mods/seal 的设置辅助脚本 │ └── lib/ │ ├── ov-session.mjs # OV HTTP 客户端 + session 帮助 + bypass 检查 │ └── async-writer.mjs # 写路径 detach-worker 帮助 diff --git a/examples/claude-code-memory-plugin/hooks/hooks.json b/examples/claude-code-memory-plugin/hooks/hooks.json index b3039999d31..d9f5e6af385 100644 --- a/examples/claude-code-memory-plugin/hooks/hooks.json +++ b/examples/claude-code-memory-plugin/hooks/hooks.json @@ -1,6 +1,6 @@ { "modules": [ - "../mods/usage/register.tsx" + "../mods/register.ts" ], "hooks": { "SessionStart": [ diff --git a/examples/claude-code-memory-plugin/mods/register.ts b/examples/claude-code-memory-plugin/mods/register.ts new file mode 100644 index 00000000000..ec349f903ae --- /dev/null +++ b/examples/claude-code-memory-plugin/mods/register.ts @@ -0,0 +1,9 @@ +import type { Register } from "claude-code"; +import { registerSeal } from "./seal/register"; +import { register as registerUsage } from "./usage/register"; + +// Claude Code loads one hooks module per plugin; this one gathers the mods. +export const register: Register = (on, options) => { + registerSeal(on); + registerUsage(on, options); +}; diff --git a/examples/claude-code-memory-plugin/mods/seal/register.ts b/examples/claude-code-memory-plugin/mods/seal/register.ts new file mode 100644 index 00000000000..165f2ad35f0 --- /dev/null +++ b/examples/claude-code-memory-plugin/mods/seal/register.ts @@ -0,0 +1,189 @@ +import type { EngineInterface, On } from "claude-code"; +import { + createSealPolicy, + envTurnsOff, + isSealable, + sealAttachment, + sealFailureMessage, + sealingMode, + sealPrompt, + sealToolResult, + serverPost, + SESSION_TEXT, + settingUnknown, + unsealCall, + unsealFailureMessage, + withheld, + withheldAttachment, + type SealingMode, + type SealPost, + type SealSetting, +} from "../../scripts/lib/prompt-seal.mjs"; + +// Reading the setting asks the server's /health once (3 s at most). +const SETTING_TIMEOUT_MS = 5_000; + +const HELPER = "scripts/seal-prompt.mjs"; + +async function envSetting($: EngineInterface): Promise { + return $.env.get("OPENVIKING_SEAL_SECRETS").catch(() => undefined); +} + +// The setting, the connection and the server's support as the helper reads +// them (the plugin's config chain and the feature table, which a hooks module +// cannot import); undefined when the helper gives no answer. +async function readSetting($: EngineInterface): Promise { + try { + const run = await $.process.run(["node", `${$.plugin.root}/${HELPER}`], { + env: await $.process.hookEnv(), + timeoutMs: SETTING_TIMEOUT_MS, + }); + return run.exitCode === 0 ? (JSON.parse(run.stdout) as SealSetting) : undefined; + } catch { + // No answer, e.g. a surface without $.process (the Desktop Code tab, VS Code). + return undefined; + } +} + +type Session = { mode: SealingMode; enrollTools: boolean; post: SealPost }; + +// Session id -> what the session seals with, so `/clear` (a new id, no +// session.start) reads it again. A promise, so hooks racing at the start of a +// session run the helper once. +const sessions = new Map>(); + +async function readSession($: EngineInterface): Promise { + const env = await envSetting($); + // An explicit OPENVIKING_SEAL_SECRETS=0 needs no helper at all. + const setting = envTurnsOff(env) ? undefined : await readSetting($); + const mode = sealingMode(setting, env); + const on = setting?.sealing === "on" ? setting : undefined; + // Unknown (the environment turns sealing on, the helper gave no answer) is + // one more reason sealing cannot be done, answered like a failed call. + const policy = createSealPolicy({ + check: () => (mode === "unknown" ? settingUnknown() : on?.support ?? { supported: false }), + }); + // Every seal and resolve call goes to the server directly from here, and + // none while the policy says the server cannot seal. + const post = policy.guard(serverPost((url, init) => $.http.fetch(url, init), on?.server)); + return { mode, enrollTools: Boolean(on?.enrollToolSecrets), post }; +} + +// Never throws: a helper that gives no answer is a setting of undefined. +async function session($: EngineInterface): Promise { + const id = await $.session.id().catch(() => ""); + let known = sessions.get(id); + if (!known) { + known = readSession($); + sessions.set(id, known); + } + return known; +} + +// Session ids whose conversation holds SESSION_TEXT. A compaction takes it +// out, and a reload of this module forgets them: the next sealed prompt adds +// it again. +const told = new Set(); + +// What a catch handler acts on: whether the hook's failure stops what it was +// about, which it does while sealing is on. +async function stopsOnFailure($: EngineInterface): Promise { + const known = sessions.get(await $.session.id().catch(() => "")); + const s = known ? await known : undefined; + return Boolean(s && s.mode !== "off"); +} + +function why(kind: string, what: string) { + return kind === "timeout" ? `the ${what} timed out` : `the ${what} failed`; +} + +// Replaces secrets with {{ov_privacy:…}} references in what the model reads, +// and gives tools the values back, when `sealSecrets` is on. +// The setting is read once per session (a changed setting takes effect in a +// new one), and again after a stopped prompt. Off: after the one setting read, everything passes untouched. A +// helper that gives no answer means off, unless OPENVIKING_SEAL_SECRETS turns +// sealing on. When sealing cannot be done (that case, the server too old or +// unreachable, a call failed), every such failure stops what it was about, +// since the runtime would otherwise let the original through. +export function registerSeal(on: On) { + // The prompt: sealed with enroll; the note rides along for temporary + // references, and the session text with the first sealed prompt. + on("prompt.submit", async ($, e, next) => { + if (!isSealable(e)) return next(e); + const s = await session($); + if (s.mode === "off") return next(e); + const decision = await sealPrompt(e, { post: s.post }); + const id = await $.session.id().catch(() => ""); + // A server that cannot seal drops the prompt here, so the session text + // below only reaches a session that seals. The next prompt reads the + // setting and the server's version again. + if (decision.kind === "drop") { + sessions.delete(id); + return { drop: decision.reason }; + } + const tell = !told.has(id); + if (tell) told.add(id); + if (decision.kind === "pass" && !tell) return next(e); + return next({ + ...e, + text: decision.kind === "rewrite" ? decision.text : e.text, + context: [ + ...(e.context ?? []), + ...(decision.kind === "rewrite" ? decision.context : []), + ...(tell ? [SESSION_TEXT] : []), + ], + }); + }).catch(async ($, e, next) => { + if (next.called) return undefined; + const reason = why(next.error.kind, "seal hook"); + if (!(await stopsOnFailure($))) return next(e); + return { drop: sealFailureMessage(reason) }; + }); + + // A tool call: the tool gets the values for the references the model wrote + // (the transcript keeps what it wrote), and the model gets the result sealed. + // The matcher takes every tool; it is there because the usage mod hooks + // tool.call without one, and a plugin may do that once. + on("tool.call", { tool: /./ }, async ($, e, next) => { + const s = await session($); + if (s.mode === "off") return next(e); + const unsealed = await unsealCall(s.post, e); + if (unsealed.deny !== undefined) return { deny: unsealed.deny }; + const outcome = await next(unsealed.call); + // A throw past this point would let the original result stand, so + // sealToolResult never throws. + return sealToolResult(s.post, outcome, { enroll: s.enrollTools }); + }).catch(async ($, e, next) => { + // Calling next again would run the tool a second time: after it ran, no + // answer but a deny changes its result. + const reason = why(next.error.kind, "seal hook"); + if (!(await stopsOnFailure($))) return next.called ? undefined : next(e); + if (next.called) return { deny: withheld(reason) }; + return { deny: unsealFailureMessage(reason) }; + }); + + // The main conversation's summary drops the session text (a precompute + // installs nothing). + on("session.compact", async ($, e, next) => { + const done = await next(e); + if (!e.agentId && e.trigger !== "precompute" && !done.skip) { + told.delete(await $.session.id().catch(() => "")); + } + return done; + }); + + // What the engine injects for the model: a mentioned file, a reminder, a + // hook's context. Sealed without enrolling; the transcript keeps the + // engine's record. + on("prompt.attachment", async ($, e, next) => { + const s = await session($); + if (s.mode === "off") return next(e); + const text = await sealAttachment(s.post, e.text); + return text === e.text ? next(e) : next({ ...e, text }); + }).catch(async ($, e, next) => { + if (next.called) return undefined; + const reason = why(next.error.kind, "seal hook"); + if (!(await stopsOnFailure($))) return next(e); + return { text: withheldAttachment(reason) }; + }); +} diff --git a/examples/claude-code-memory-plugin/mods/seal/seal.test.ts b/examples/claude-code-memory-plugin/mods/seal/seal.test.ts new file mode 100644 index 00000000000..7f81a0c34b1 --- /dev/null +++ b/examples/claude-code-memory-plugin/mods/seal/seal.test.ts @@ -0,0 +1,334 @@ +import type { On } from "claude-code"; +import { describe, expect, mock, test } from "claude-code/testing"; +import { SESSION_TEXT, sealNote } from "../../scripts/lib/prompt-seal.mjs"; + +// The wiring only: what reaches the session for each helper answer. The +// decisions themselves are tested with node --test in scripts/lib/prompt-seal.test.mjs. +const TOKEN = "ghp_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const REF = "{{ov_privacy:alice:viking://~/privacy/auto/github-k3j2m8#/values/token}}"; +const TEXT = `use ${TOKEN}`; +// Typed at the prompt, as the engine raises it. +const TYPED = { text: TEXT, wait: false, origin: { kind: "composer" } } as const; + +type Run = { exitCode: number; stdout: string } | Error; +type Answer = { status: number; json: unknown } | Error; + +const SERVER = { baseUrl: "http://ov.test:1933", headers: { Authorization: "Bearer sk-test" } }; + +// The setting helper (`setting` answers each run) and the server, reached +// through $.http.fetch (`seal` and `resolve` answer each call). +function helper( + on: On, + { setting: read, seal, resolve, env = {} }: { setting: Run | (() => Run); seal?: Answer | ((body: any) => Answer); resolve?: Answer; env?: Record }, +) { + mock.env(on, env); + on("process.hookEnv", () => ({ value: { CLAUDE_PLUGIN_ROOT: "/plugin" } })); + const runs: string[][] = []; + const calls: { url: string; body: any; auth?: string }[] = []; + on("process.run", (_$, e) => { + runs.push([...e.argv]); + if (!String(e.argv[1]).endsWith("/scripts/seal-prompt.mjs")) throw new Error("unexpected process run"); + const setting = typeof read === "function" ? read() : read; + if (setting instanceof Error) throw setting; + const stderr = setting.exitCode ? "boom" : ""; + return { value: { ...setting, stderr, isStdoutTruncated: false, isStderrTruncated: false } }; + }); + on("http.fetch", (_$, e) => { + const body = JSON.parse(String(e.init?.body ?? "{}")); + calls.push({ url: e.url, body, auth: e.init?.headers?.Authorization }); + const pick = e.url.endsWith("/resolve") ? resolve : seal; + const answer = typeof pick === "function" ? pick(body) : pick; + if (!answer) throw new Error("unexpected server call"); + if (answer instanceof Error) throw answer; + return { value: { status: answer.status, ok: answer.status < 300, headers: {}, text: JSON.stringify(answer.json) } }; + }); + return { runs, calls }; +} + +const answer = (value: unknown) => ({ exitCode: 0, stdout: JSON.stringify(value) }); +const support = (actual: string | null) => ({ + feature: "privacy_seal", + supported: actual !== null && actual >= "0.5.7", + required: "0.5.7", + actual, +}); +const ON = answer({ sealing: "on", enrollToolSecrets: false, server: SERVER, support: support("0.5.7") }); +const SETTING_RUN = ["node", expect.stringMatching(/\/scripts\/seal-prompt\.mjs$/)]; +const SEAL_URL = "http://ov.test:1933/api/v1/privacy-configs/seal"; + +function sessionSees(on: On) { + const seen: { text: string; context?: readonly string[] }[] = []; + on("prompt.submit", (_$, e) => { + seen.push({ text: e.text, context: e.context }); + return { text: e.text, context: e.context }; + }); + return seen; +} + +function logged(on: On) { + const lines: string[] = []; + on("ui.log", (_$, e) => { + lines.push(e.text); + return { value: undefined }; + }); + return lines; +} + +const sealedAnswer = (temporary: boolean): Answer => ({ + status: 200, + json: { + status: "ok", + result: { + revision: "r1", + texts: [{ text: `use ${REF}`, replaced: [{ start: 4, end: 4 + TOKEN.length, reference: REF, created: false, temporary }] }], + }, + }, +}); + +describe("prompt sealing", () => { + test("off: read once per session, then no process at all", async ($, on) => { + const { runs } = helper(on, { setting: answer({ sealing: "off" }) }); + const seen = sessionSees(on); + await $.prompt.submit(TYPED); + await $.prompt.submit(TYPED); + expect(runs).toEqual([SETTING_RUN]); + expect(seen).toEqual([{ text: TEXT, context: undefined }, { text: TEXT, context: undefined }]); + }); + + test("on: a temporary reference is replaced and the note rides along as context", async ($, on) => { + const { runs, calls } = helper(on, { setting: ON, seal: sealedAnswer(true) }); + const seen = sessionSees(on); + await $.prompt.submit(TYPED); + await $.prompt.submit(TYPED); + // One helper run for the session; every seal goes to the server directly. + expect(runs).toEqual([SETTING_RUN]); + expect(calls).toEqual([ + { url: SEAL_URL, body: { texts: [{ text: TEXT, enroll: true }] }, auth: "Bearer sk-test" }, + { url: SEAL_URL, body: { texts: [{ text: TEXT, enroll: true }] }, auth: "Bearer sk-test" }, + ]); + // The session text rides along with the first sealed prompt only. + expect(seen).toEqual([ + { text: `use ${REF}`, context: [sealNote([REF]), SESSION_TEXT] }, + { text: `use ${REF}`, context: [sealNote([REF])] }, + ]); + }); + + test("on: a saved reference is replaced without a note", async ($, on) => { + helper(on, { setting: ON, seal: sealedAnswer(false) }); + const seen = sessionSees(on); + await $.prompt.submit(TYPED); + await $.prompt.submit(TYPED); + expect(seen).toEqual([{ text: `use ${REF}`, context: [SESSION_TEXT] }, { text: `use ${REF}`, context: [] }]); + }); + + test("on: the session text comes again after a compaction", async ($, on) => { + helper(on, { setting: ON, seal: { status: 200, json: { status: "ok", result: { revision: "r1", texts: [null] } } } }); + const seen = sessionSees(on); + const summary = [{ role: "user" as const, text: "summary", toolUses: [] }]; + on("session.compact", () => ({ messages: summary })); + await $.prompt.submit(TYPED); + await $.prompt.submit(TYPED); + await $.session.compact({ trigger: "manual", messages: summary } as never); + await $.prompt.submit(TYPED); + expect(seen.map((p) => p.context)).toEqual([[SESSION_TEXT], undefined, [SESSION_TEXT]]); + }); + + test("a server too old to seal stops the prompt without a call, until it is upgraded", async ($, on) => { + let version = "0.5.6"; + const { calls } = helper(on, { + setting: () => answer({ sealing: "on", enrollToolSecrets: false, server: SERVER, support: support(version) }), + seal: sealedAnswer(false), + }); + const seen = sessionSees(on); + const res = await $.prompt.submit(TYPED); + expect(calls).toEqual([]); + expect(seen).toEqual([]); + expect(res.drop).toContain("version 0.5.6, and sealing secrets needs 0.5.7 or newer"); + expect(res.drop).toContain("Upgrade the OpenViking server, or turn sealing off with sealSecrets: false"); + version = "0.5.7"; + await $.prompt.submit(TYPED); + expect(calls.map((call) => call.url)).toEqual([SEAL_URL]); + expect(seen.length).toBe(1); + }); + + test("a failed seal stops the prompt", async ($, on) => { + helper(on, { setting: ON, seal: new Error("connection refused") }); + const seen = sessionSees(on); + const res = await $.prompt.submit(TYPED); + expect(seen).toEqual([]); + expect(res.drop).toContain("sealing secrets failed (cannot reach the OpenViking server: "); + expect(res.drop).toContain("OPENVIKING_SEAL_SECRETS=0"); + }); + + test("no answer: a failed setting helper means off, without a message", async ($, on) => { + const { runs, calls } = helper(on, { setting: { exitCode: 1, stdout: "" } }); + const seen = sessionSees(on); + const lines = logged(on); + await $.prompt.submit(TYPED); + await $.prompt.submit(TYPED); + expect(runs).toEqual([SETTING_RUN]); + expect(calls).toEqual([]); + expect(seen).toEqual([{ text: TEXT, context: undefined }, { text: TEXT, context: undefined }]); + expect(lines).toEqual([]); + }); + + test("no answer: a surface without $.process means off, without a message", async ($, on) => { + mock.env(on, {}); + const seen = sessionSees(on); + const lines = logged(on); + await $.prompt.submit(TYPED); + expect(seen).toEqual([{ text: TEXT, context: undefined }]); + expect(lines).toEqual([]); + }); + + test("unknown: OPENVIKING_SEAL_SECRETS=1 without an answer stops prompts", async ($, on) => { + const { runs, calls } = helper(on, { setting: { exitCode: 1, stdout: "" }, env: { OPENVIKING_SEAL_SECRETS: "1" } }); + const seen = sessionSees(on); + const first = await $.prompt.submit(TYPED); + await $.prompt.submit(TYPED); + // Each stopped prompt reads the setting again. + expect(runs).toEqual([SETTING_RUN, SETTING_RUN]); + expect(calls).toEqual([]); + expect(seen).toEqual([]); + expect(first.drop).toContain("the plugin's settings could not be read here"); + expect(first.drop).toContain("Use Claude Code where the plugin can run its setting helper"); + }); + + test("unknown: OPENVIKING_SEAL_SECRETS=1 on a surface without $.process stops the prompt", async ($, on) => { + mock.env(on, { OPENVIKING_SEAL_SECRETS: "1" }); + const seen = sessionSees(on); + const res = await $.prompt.submit(TYPED); + expect(seen).toEqual([]); + expect(res.drop).toContain("the plugin's settings could not be read here"); + }); + + test("OPENVIKING_SEAL_SECRETS=0 starts no process", async ($, on) => { + const { runs, calls } = helper(on, { setting: new Error("must not read"), env: { OPENVIKING_SEAL_SECRETS: "0" } }); + const seen = sessionSees(on); + await $.prompt.submit(TYPED); + expect(runs).toEqual([]); + expect(calls).toEqual([]); + expect(seen).toEqual([{ text: TEXT, context: undefined }]); + }); +}); + +// ── tool calls and attachments ────────────────────────────────────────── + +const VALUE = "ghp_REGISTEREDsecretVALUE1234567890abcd"; +const SAVED = "{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}"; + +// The server: VALUE is registered as SAVED. +function sealBody(body: { texts: { text: string; enroll?: boolean }[] }): Answer { + const texts = body.texts.map(({ text }) => { + const at = text.indexOf(VALUE); + if (at < 0) return null; + return { + text: text.replace(VALUE, SAVED), + replaced: [{ start: at, end: at + VALUE.length, reference: SAVED, created: false, temporary: false }], + }; + }); + return { status: 200, json: { status: "ok", result: { revision: "r1", texts } } }; +} +const RESOLVED: Answer = { status: 200, json: { status: "ok", result: { value: VALUE } } }; + +// The engine beneath the plugin: Bash records the command it ran and prints `out`. +function bash(on: On, out: (command: string) => string, isError = false) { + const ran: string[] = []; + on("tool.call", (_$, e) => { + if (e.tool !== "Bash") throw new Error("unexpected tool"); + ran.push(e.command); + const stdout = out(e.command); + if (isError) return { isError: true as const, result: stdout, text: stdout }; + return { result: { stdout, stderr: "", interrupted: false }, text: stdout }; + }); + return ran; +} + +describe("tool sealing", () => { + test("a reference in the arguments runs with the value, and the result is sealed", async ($, on) => { + const { calls } = helper(on, { setting: ON, seal: sealBody, resolve: RESOLVED }); + const ran = bash(on, (command) => `got ${command.slice(5)}`); + const res = await $.tool.call({ tool: "Bash", command: `echo ${SAVED}` }); + expect(ran).toEqual([`echo ${VALUE}`]); + expect(res.result).toEqual({ stdout: `got ${SAVED}`, stderr: "", interrupted: false }); + expect(calls.map((c) => c.url.split("/").at(-1))).toEqual(["resolve", "seal", "seal"]); + // Tool output is not enrolled unless enrollToolSecrets is on. + expect(calls[2]?.body).toEqual({ texts: [{ text: `got ${VALUE}`, enroll: false }] }); + }); + + test("enrollToolSecrets sends the result with enroll", async ($, on) => { + const { calls } = helper(on, { + setting: answer({ sealing: "on", enrollToolSecrets: true, server: SERVER, support: support("0.5.7") }), + seal: sealBody, + }); + bash(on, () => "a plain output line"); + await $.tool.call({ tool: "Bash", command: "ls" }); + expect(calls).toEqual([ + { url: SEAL_URL, body: { texts: [{ text: "a plain output line", enroll: true }] }, auth: "Bearer sk-test" }, + ]); + }); + + test("an errored call's text is sealed", async ($, on) => { + helper(on, { setting: ON, seal: sealBody }); + bash(on, () => `Exit code 1\nbad token ${VALUE}`, true); + const res = await $.tool.call({ tool: "Bash", command: "false" }); + expect(JSON.stringify(res)).not.toContain(VALUE); + expect(JSON.stringify(res)).toContain(SAVED); + }); + + test("a failed seal withholds the result", async ($, on) => { + helper(on, { setting: ON, seal: { status: 500, json: {} } }); + const ran = bash(on, () => `token ${VALUE}`); + const res = await $.tool.call({ tool: "Bash", command: "cat .env" }); + expect(ran).toEqual(["cat .env"]); + expect(JSON.stringify(res)).not.toContain(VALUE); + expect(JSON.stringify(res)).toContain("OpenViking withheld this tool result"); + }); + + test("a failed resolve blocks the call", async ($, on) => { + helper(on, { setting: ON, seal: sealBody, resolve: new Error("connection refused") }); + const ran = bash(on, () => "x"); + const res = await $.tool.call({ tool: "Bash", command: `echo ${SAVED}` }); + expect(ran).toEqual([]); + expect(JSON.stringify(res)).toContain("OpenViking blocked this tool call"); + }); + + test("off: tools run untouched with no server call", async ($, on) => { + const { calls } = helper(on, { setting: answer({ sealing: "off" }) }); + const ran = bash(on, () => `token ${VALUE}`); + const res = await $.tool.call({ tool: "Bash", command: `echo ${SAVED}` }); + expect(ran).toEqual([`echo ${SAVED}`]); + expect(res.result).toEqual({ stdout: `token ${VALUE}`, stderr: "", interrupted: false }); + expect(calls).toEqual([]); + }); +}); + +// The engine beneath the plugin: the attachment as the model would read it. +function attachments(on: On) { + const seen: string[] = []; + on("prompt.attachment", (_$, e) => { + seen.push(e.text); + return { text: e.text }; + }); + return seen; +} + +describe("attachment sealing", () => { + test("a mentioned file's text is sealed without enroll", async ($, on) => { + const { calls } = helper(on, { setting: ON, seal: sealBody }); + const seen = attachments(on); + const res = await $.prompt.attachment({ type: "file", text: `KEY=${VALUE}`, origin: { kind: "engine" } }); + expect(res.text).toBe(`KEY=${SAVED}`); + expect(seen).toEqual([`KEY=${SAVED}`]); + expect(calls[0]?.body).toEqual({ texts: [{ text: `KEY=${VALUE}`, enroll: false }] }); + }); + + test("a failed seal withholds the attachment", async ($, on) => { + helper(on, { setting: ON, seal: { status: 503, json: {} } }); + const seen = attachments(on); + const res = await $.prompt.attachment({ type: "file", text: `KEY=${VALUE}`, origin: { kind: "engine" } }); + expect(res.text).toContain("OpenViking withheld this attached content"); + expect(res.text).not.toContain(VALUE); + expect(seen).toEqual([res.text]); + }); +}); diff --git a/examples/claude-code-memory-plugin/mods/seal/tsconfig.json b/examples/claude-code-memory-plugin/mods/seal/tsconfig.json new file mode 100644 index 00000000000..f7c64afd7af --- /dev/null +++ b/examples/claude-code-memory-plugin/mods/seal/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../.claude-plugin/types/tsconfig.json", + "include": ["."] +} diff --git a/examples/claude-code-memory-plugin/package.json b/examples/claude-code-memory-plugin/package.json index f8ca3b45906..2be0ea653ef 100644 --- a/examples/claude-code-memory-plugin/package.json +++ b/examples/claude-code-memory-plugin/package.json @@ -1,6 +1,6 @@ { "name": "claude-code-openviking-memory", - "version": "0.7.31", + "version": "0.7.32", "description": "OpenViking memory plugin for Claude Code — semantic long-term memory", "type": "module", "scripts": { diff --git a/examples/claude-code-memory-plugin/scripts/lib/prompt-seal.d.mts b/examples/claude-code-memory-plugin/scripts/lib/prompt-seal.d.mts new file mode 100644 index 00000000000..c13dd5252fb --- /dev/null +++ b/examples/claude-code-memory-plugin/scripts/lib/prompt-seal.d.mts @@ -0,0 +1,63 @@ +export const SEAL_TIMEOUT_MS: number; +export const AGENT_TOOLS: ReadonlySet; +export const SESSION_TEXT: string; + +// The shared core's types, declared here: Claude Code's copies of the shared +// modules carry no declarations. +export type SealReason = "seal_failed" | "server_too_old" | "version_unknown"; +interface SealError extends Error { + status?: number; + reason: SealReason; +} +export type SealSupport = { supported: boolean; required?: string; actual?: string | null }; +export type SealPolicy = { + unavailable(): Promise; + guard(post: SealPost): SealPost; +}; +export function createSealPolicy(options?: { + check?: () => SealSupport | SealError | Promise; +}): SealPolicy; + +export type SealPost = (path: string, body: unknown) => Promise<{ status: number; json: unknown }>; + +export type SealServer = { baseUrl: string; headers: Record }; + +export type SealSetting = + | { sealing: "on"; enrollToolSecrets?: boolean; server?: SealServer; support?: SealSupport } + | { sealing: "off" }; + +export type SealingMode = "on" | "off" | "unknown"; + +export type SealDecision = + | { kind: "pass" } + | { kind: "rewrite"; text: string; context: string[] } + | { kind: "drop"; reason: string }; + +export function sealNote(references: readonly string[]): string; +export function withheld(reason?: string): string; +export function withheldAttachment(why: string): string; +export function sealFailureMessage(why: unknown): string; +export function unsealFailureMessage(why: unknown): string; +export function settingUnknown(): SealError; +export function envTurnsOff(envOverride: string | undefined): boolean; +export function sealingMode(setting: SealSetting | undefined, envOverride: string | undefined): SealingMode; +export function isSealable(prompt: { text: string; command?: unknown; isMeta?: unknown }): boolean; +export function serverPost( + fetch: (url: string, init: { method: string; headers: Record; body: string }) => Promise<{ status: number; text: string }>, + server: SealServer | undefined, + options?: { timeoutMs?: number }, +): SealPost; +export function sealPrompt( + prompt: { text: string; command?: unknown; isMeta?: unknown }, + options: { post: SealPost }, +): Promise; +export function unsealCall( + post: SealPost, + input: T, +): Promise<{ call: T; replaced: number; deny?: undefined } | { deny: string; call?: undefined; replaced?: undefined }>; +export function sealToolResult( + post: SealPost, + outcome: T, + options?: { enroll?: boolean }, +): Promise; +export function sealAttachment(post: SealPost, text: string): Promise; diff --git a/examples/claude-code-memory-plugin/scripts/lib/prompt-seal.mjs b/examples/claude-code-memory-plugin/scripts/lib/prompt-seal.mjs new file mode 100644 index 00000000000..b7970e5b847 --- /dev/null +++ b/examples/claude-code-memory-plugin/scripts/lib/prompt-seal.mjs @@ -0,0 +1,239 @@ +/** + * Seal secrets out of what Claude Code sends to the model, and give tools the + * real values back: the Claude Code side of plugin sealing (`sealSecrets`). + * The hooks module in `mods/seal/` calls it on prompt.submit (sealPrompt), + * tool.call (unsealCall, then sealToolResult) and prompt.attachment + * (sealAttachment). The requests, the response check, the deep walks and the + * note live in the shared core (`scripts/shared/seal-core.mjs`); this module + * adds what is Claude Code's own. + * + * When sealing cannot be done, what each function was about is stopped. The + * mods runtime lets the original through when a hook throws, so a failure is + * turned into an answer here (a drop, a deny, a withheld text). Pure: no Node + * or engine API. + */ + +import { + SESSION_TEXT, + SealError, + createSealPolicy, + isOpenVikingTool, + sealNote, + sealTexts, + sealValue, + stopHint, + unsealValue, + whyNotSealed, + withheld, +} from "../shared/seal-core.mjs"; + +export { SESSION_TEXT, createSealPolicy, sealNote, withheld }; + +// The person waits on each call (a prompt, a tool), so it gets less than the +// general request timeout. +export const SEAL_TIMEOUT_MS = 10000; + +/** + * Tools that hand their arguments to a model: a subagent's prompt, a message + * to another session, a workflow's agents, a skill's arguments. A value put + * there would reach a model, so their arguments keep the references. + */ +export const AGENT_TOOLS = new Set(["Agent", "Task", "SendMessage", "Workflow", "Skill"]); + +// What `tool.call`'s input carries beside the tool's own arguments. +const RESERVED_KEYS = new Set(["tool", "tool_use_id", "agentId", "requestMeta", "consent"]); + +const SETTINGS_PLACE = "The settings go in the claude_code section of ~/.openviking/ovcli.conf, or in the environment."; + +/** Why sealing cannot be done when OPENVIKING_SEAL_SECRETS is on but the setting helper gave no answer. */ +export function settingUnknown() { + return new SealError( + "OPENVIKING_SEAL_SECRETS is on, but the plugin's settings could not be read here (the setting helper gave no answer)", + { reason: "setting_unknown" }, + ); +} + +/** The message shown to the user when the prompt is stopped; `why` an error or a text. */ +export function sealFailureMessage(why) { + return `OpenViking did not send this prompt: ${whyNotSealed(why)}. ${stopHint(why)} ${SETTINGS_PLACE}`; +} + +/** The reason the model reads when a tool call is blocked. */ +export function unsealFailureMessage(why) { + return ( + `OpenViking blocked this tool call: the secret values could not be put back in place of the references, because ${whyNotSealed(why)}. ` + + "The tool did not run. Try again later, or ask the user to check the OpenViking server or the sealSecrets setting." + ); +} + +/** What the model reads in place of an attachment that could not be sealed. */ +export function withheldAttachment(why) { + return ( + `[OpenViking withheld this attached content: sealing secrets in it failed (${why}). ` + + "Its text is not shown so that no secret reaches the model.]" + ); +} + +function messageOf(error) { + return error instanceof Error ? error.message : String(error); +} + +/** + * The core's `post` over the runtime's `$.http.fetch`: `fetch(url, init)` + * resolving `{ status, text }`, and `server` the `{ baseUrl, headers }` the + * setting helper printed. A call that takes longer than `timeoutMs` is + * reported as a timeout. + */ +export function serverPost(fetch, server, { timeoutMs = SEAL_TIMEOUT_MS } = {}) { + return async (path, body) => { + if (!server?.baseUrl) throw new SealError("no OpenViking server URL is configured"); + let timer; + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => reject(Object.assign(new Error("timed out"), { name: "TimeoutError" })), timeoutMs); + }); + try { + const res = await Promise.race([ + fetch(`${server.baseUrl}${path}`, { + method: "POST", + headers: { ...server.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + }), + timeout, + ]); + let json = null; + try { + json = JSON.parse(res.text); + } catch { + // Not JSON: the core reports the answer as malformed. + } + return { status: res.status, json }; + } finally { + clearTimeout(timer); + } + }; +} + +function envFlag(value) { + if (typeof value !== "string") return undefined; + const v = value.trim().toLowerCase(); + if (["0", "false", "no", "off"].includes(v)) return false; + if (["1", "true", "yes", "on"].includes(v)) return true; + return undefined; +} + +/** Whether OPENVIKING_SEAL_SECRETS explicitly turns sealing off: then no helper runs. */ +export function envTurnsOff(envOverride) { + return envFlag(envOverride) === false; +} + +/** + * The session's sealing mode: "on", "off" or "unknown". + * + * `setting` is what `seal-prompt.mjs` printed (`{ sealing: "on" | "off" }`), + * or undefined when the helper could not answer. `envOverride` is + * OPENVIKING_SEAL_SECRETS as the mod reads it: an explicit off value wins, so + * a broken helper can always be switched off. Without an answer, sealing is + * off (its default) unless the environment turns it on; only then is the mode + * unknown, and the user told that it cannot run. + */ +export function sealingMode(setting, envOverride) { + const env = envFlag(envOverride); + if (env === false) return "off"; + const sealing = setting && typeof setting === "object" ? setting.sealing : undefined; + if (sealing === "on" || sealing === "off") return sealing; + return env === true ? "unknown" : "off"; +} + +/** Whether a prompt is one the seal looks at: not a slash command, meta or empty. */ +export function isSealable(prompt) { + const text = typeof prompt?.text === "string" ? prompt.text : ""; + return !prompt?.command && !prompt?.isMeta && Boolean(text.trim()); +} + +/** + * Decide what happens to one `prompt.submit` while sealing is on. + * + * `prompt` is the event's input (`text`, and `command` for a slash command). + */ +export async function sealPrompt(prompt, { post }) { + if (!isSealable(prompt)) return { kind: "pass" }; + try { + const { texts } = await sealTexts(post, [{ text: prompt.text, enroll: true }]); + const [item] = texts; + if (!item.changed) return { kind: "pass" }; + const context = item.temporary.length ? [sealNote(item.temporary)] : []; + return { kind: "rewrite", text: item.text, context }; + } catch (error) { + return { kind: "drop", reason: sealFailureMessage(error) }; + } +} + +/** + * The tool call to run for one `tool.call` input: references in the tool's + * arguments replaced by their values. OpenViking's own tools + * and the tools in AGENT_TOOLS keep what the model wrote. + * + * Resolves `{ call, replaced }` (`call` is the input itself when nothing was + * replaced) or `{ deny }` when a reference could not be resolved or checked. + */ +export async function unsealCall(post, input) { + const args = {}; + for (const [key, value] of Object.entries(input)) if (!RESERVED_KEYS.has(key)) args[key] = value; + const skip = isOpenVikingTool(input.tool) || AGENT_TOOLS.has(input.tool); + try { + const { value, replaced } = await unsealValue(post, args, { skip }); + return replaced ? { call: { ...input, ...value }, replaced } : { call: input, replaced: 0 }; + } catch (error) { + return { deny: unsealFailureMessage(error) }; + } +} + +/** + * What the model gets for one tool result (what `next` resolved to in a + * `tool.call` hook). Never throws. + * + * - A deny passes as it is. + * - An error result: its text and context sealed, given back as one deny (the + * model reads a deny of an errored call as the error). + * - A result: every string of the tool's record and of its context sealed, + * given back as the hook's own `{ result, context }`, which core maps for the + * model and records in the transcript. Unchanged, the original object + * (core then uses its own messages). + * - Sealing failed: a deny with the withheld text. + */ +export async function sealToolResult(post, outcome, { enroll = false } = {}) { + if (!outcome || typeof outcome !== "object" || outcome.deny !== undefined) return outcome; + try { + if (outcome.isError) { + const text = typeof outcome.text === "string" ? outcome.text : typeof outcome.result === "string" ? outcome.result : ""; + const { value: sealed } = await sealValue(post, { text, context: outcome.context }, { enroll }); + if (sealed.text === text && sealed.context === outcome.context) return outcome; + // A deny carries no context: what the model would read after the error follows it. + return { deny: [sealed.text || withheld("the tool failed"), ...(sealed.context ?? [])].join("\n\n") }; + } + const { value: sealed, sealed: count } = await sealValue( + post, + { result: outcome.result, context: outcome.context }, + { enroll }, + ); + if (!count) return outcome; + return sealed.context?.length ? { result: sealed.result, context: sealed.context } : { result: sealed.result }; + } catch (error) { + return { deny: withheld(messageOf(error)) }; + } +} + +/** + * The text the model reads for one `prompt.attachment` (a mentioned file, a + * reminder, a hook's context), sealed without enrolling. Never throws: on a + * failure it is the withheld text. + */ +export async function sealAttachment(post, text) { + if (typeof text !== "string") return text; + try { + const { value } = await sealValue(post, text, { enroll: false }); + return value; + } catch (error) { + return withheldAttachment(messageOf(error)); + } +} diff --git a/examples/claude-code-memory-plugin/scripts/lib/prompt-seal.test.mjs b/examples/claude-code-memory-plugin/scripts/lib/prompt-seal.test.mjs new file mode 100644 index 00000000000..509323ba44c --- /dev/null +++ b/examples/claude-code-memory-plugin/scripts/lib/prompt-seal.test.mjs @@ -0,0 +1,343 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + AGENT_TOOLS, + createSealPolicy, + envTurnsOff, + isSealable, + sealAttachment, + sealingMode, + sealNote, + sealPrompt, + sealToolResult, + serverPost, + settingUnknown, + unsealCall, + withheld, +} from "./prompt-seal.mjs"; + +const REF = "{{ov_privacy:alice:viking://~/privacy/auto/github-k3j2m8#/values/token}}"; +const OLD_REF = "{{ov_privacy:alice:viking://~/privacy/credential/openai#/values/token}}"; +const TOKEN = "ghp_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + +// A server answer for `text` with each [secret, reference, temporary] replaced. +function sealed(text, swaps) { + const replaced = []; + let out = text; + for (const [secret, reference, temporary] of swaps) { + const unit = text.indexOf(secret); + const start = Array.from(text.slice(0, unit)).length; + replaced.push({ start, end: start + Array.from(secret).length, reference, created: false, temporary }); + out = out.replace(secret, reference); + } + return { ok: true, status: 200, result: { revision: "r1", texts: [{ text: out, replaced }] } }; +} + +// The core's `post` for an answer written as `{ ok, status, result, error }`: +// status 0 is no answer at all (a network error, or a timeout when aborted). +function postOf(answer) { + return async () => { + if (!answer.ok && !answer.status) { + if (answer.error?.aborted) throw Object.assign(new Error("aborted"), { name: "AbortError" }); + throw new Error(answer.error?.message || ""); + } + const json = answer.ok ? { status: "ok", result: answer.result } : { status: "error", error: answer.error }; + return { status: answer.status, json }; + }; +} + +function recorder(answer) { + const calls = []; + const post = async (path, body) => { + calls.push({ path, body }); + return postOf(typeof answer === "function" ? answer(body) : answer)(path, body); + }; + return { calls, post }; +} + +test("the session's mode: the setting, an explicit off, and unknown", () => { + assert.equal(sealingMode({ sealing: "on" }, undefined), "on"); + assert.equal(sealingMode({ sealing: "off" }, undefined), "off"); + // Without an answer, sealing keeps its default: off. + assert.equal(sealingMode(undefined, undefined), "off"); + assert.equal(sealingMode("garbage", ""), "off"); + assert.equal(sealingMode(undefined, "maybe"), "off"); + // An explicit off always wins, so a broken helper can be switched off. + for (const env of [undefined, "", "1", "maybe"]) assert.equal(envTurnsOff(env), false); + for (const env of ["0", "false", "no", "OFF"]) { + assert.equal(envTurnsOff(env), true); + assert.equal(sealingMode({ sealing: "on" }, env), "off"); + assert.equal(sealingMode(undefined, env), "off"); + } + // Without an answer, an explicit on does not make it known: the user is told it cannot run. + for (const env of ["1", "true", "yes", " ON "]) { + assert.equal(sealingMode(undefined, env), "unknown"); + assert.equal(sealingMode({ sealing: "off" }, env), "off"); + } +}); + +test("no replacement: the prompt passes unchanged", async () => { + const { post } = recorder({ ok: true, status: 200, result: { revision: "r1", texts: [null] } }); + assert.deepEqual(await sealPrompt({ text: "fix the build" }, { post }), { kind: "pass" }); +}); + +test("a registered secret is replaced without a note", async () => { + const text = `use ${TOKEN} please`; + const { post } = recorder(sealed(text, [[TOKEN, OLD_REF, false]])); + assert.deepEqual(await sealPrompt({ text }, { post }), { + kind: "rewrite", + text: `use ${OLD_REF} please`, + context: [], + }); +}); + +test("a temporary reference is replaced and the note names it once", async () => { + // Offsets count code points: the emoji ahead of the secret is one, not two. + const text = `🔑 ${TOKEN} and ${TOKEN}, plus sk-old-secret-value`; + const n = TOKEN.length; + const answer = { + ok: true, + status: 200, + result: { + revision: "r2", + texts: [{ + text: `🔑 ${REF} and ${REF}, plus ${OLD_REF}`, + replaced: [ + { start: 2, end: 2 + n, reference: REF, created: true, temporary: true }, + { start: 7 + n, end: 7 + 2 * n, reference: REF, created: false, temporary: true }, + { start: 14 + 2 * n, end: 33 + 2 * n, reference: OLD_REF, created: false, temporary: false }, + ], + }], + }, + }; + + const decision = await sealPrompt({ text }, { post: recorder(answer).post }); + assert.deepEqual(decision, { + kind: "rewrite", + text: `🔑 ${REF} and ${REF}, plus ${OLD_REF}`, + context: [sealNote([REF])], + }); +}); + +// The note's wording, pinned word for word. +const NOTE_TEMPLATE = + "OpenViking stored a secret from the user's message and replaced it with a reference: [, …]. You will not see the value. Unless it is clearly for one-off use, save it under a proper name now with privacy_upsert (or `ov privacy upsert`), passing the reference as the value and a short description of what it is for, for example category=\"credential\", target_key=\"github\", values={\"token\": \"\"}, description=\"GitHub PAT for the acme org\". The temporary entry is removed once it is saved, so use the reference that privacy_upsert returns from then on. Write the reference as is wherever the secret is needed, for example `ov privacy run --env NAME='' -- sh -c ''`; do not resolve it to plain text or print any part of it. Tell the user what was stored and under which name."; + +test("the note is the pinned wording with the enrolled references filled in", () => { + const expected = NOTE_TEMPLATE + .replace("[, …]", `${REF}, ${OLD_REF}`) + .replace('"token": ""', `"token": "${REF}"`); + assert.equal(sealNote([REF, OLD_REF]), expected); +}); + +test("the note follows temporary, not created", async () => { + const text = `use ${TOKEN}`; + const make = (created, temporary) => { + const answer = sealed(text, [[TOKEN, REF, temporary]]); + answer.result.texts[0].replaced[0].created = created; + return answer; + }; + // Enrolled earlier (a count_tokens call, another replica): still owed. + let decision = await sealPrompt({ text }, { post: recorder(make(false, true)).post }); + assert.deepEqual(decision.context, [sealNote([REF])]); + // Enrolled by this call but already saved under a name: not owed. + decision = await sealPrompt({ text }, { post: recorder(make(true, false)).post }); + assert.deepEqual(decision.context, []); +}); + +test("slash commands, meta prompts and empty prompts never reach the server", async () => { + const post = async () => { + throw new Error("must not run"); + }; + for (const prompt of [ + { text: `/review ${TOKEN}`, command: { name: "review", args: TOKEN } }, + { text: TOKEN, isMeta: true }, + { text: "" }, + { text: " \n" }, + ]) { + assert.deepEqual(await sealPrompt(prompt, { post }), { kind: "pass" }); + assert.equal(isSealable(prompt), false); + } + assert.equal(isSealable({ text: "hi" }), true); +}); + +test("a failed seal call stops the prompt, naming why and what to do", async () => { + const decision = await sealPrompt({ text: `key ${TOKEN}` }, { post: postOf({ ok: false, status: 0, error: { message: "fetch failed" } }) }); + assert.equal(decision.kind, "drop"); + assert.match(decision.reason, /^OpenViking did not send this prompt: sealing secrets failed \(cannot reach the OpenViking server: fetch failed\)/); + assert.match(decision.reason, /Try again once the OpenViking server answers, or turn sealing off with sealSecrets: false \(OPENVIKING_SEAL_SECRETS=0\)/); +}); + +// ── tools and attachments ─────────────────────────────────────────────── + +const VALUE = "ghp_REGISTEREDsecretVALUE1234567890abcd"; +const SAVED = "{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}"; + +// A server that knows VALUE as SAVED: seal replaces it, resolve gives it back. +function vault({ resolve = (selector) => (selector === SAVED ? { status: 200, value: VALUE } : { status: 404 }), seal } = {}) { + const calls = []; + const post = async (path, body) => { + calls.push({ path, body }); + if (path.endsWith("/resolve")) { + const answer = resolve(body.selector); + if (answer instanceof Error) throw answer; + return answer.status === 200 + ? { status: 200, json: { status: "ok", result: { value: answer.value } } } + : { status: answer.status, json: { status: "error", error: { message: "no" } } }; + } + if (seal) return seal(body); + const texts = body.texts.map(({ text }) => { + if (!text.includes(VALUE)) return null; + const replaced = []; + let from = 0; + for (let at = text.indexOf(VALUE); at >= 0; at = text.indexOf(VALUE, from)) { + const start = Array.from(text.slice(0, at)).length; + replaced.push({ start, end: start + VALUE.length, reference: SAVED, created: false, temporary: false }); + from = at + VALUE.length; + } + return { text: text.split(VALUE).join(SAVED), replaced }; + }); + return { status: 200, json: { status: "ok", result: { revision: "r1", texts } } }; + }; + return { calls, post }; +} + +test("unsealCall: a reference in the arguments becomes the value, reserved keys stay", async () => { + const { post, calls } = vault(); + const input = { tool: "Bash", tool_use_id: "t1", command: `curl -H "Authorization: ${SAVED}" x`, description: "fetch" }; + const { call, replaced } = await unsealCall(post, input); + assert.equal(replaced, 1); + assert.deepEqual(call, { ...input, command: `curl -H "Authorization: ${VALUE}" x` }); + assert.deepEqual(calls.map((c) => c.path), ["/api/v1/privacy-configs/resolve", "/api/v1/privacy-configs/seal"]); + // The round-trip check never enrolls. + assert.deepEqual(calls[1].body, { texts: [{ text: VALUE, enroll: false }] }); +}); + +test("unsealCall: nothing to resolve makes no request and keeps the input", async () => { + const { post, calls } = vault(); + const input = { tool: "Read", tool_use_id: "t1", file_path: "/tmp/x" }; + const res = await unsealCall(post, input); + assert.equal(res.call, input); + assert.equal(calls.length, 0); +}); + +test("unsealCall: OpenViking's and agent-spawning tools keep the references", async () => { + const { post, calls } = vault(); + for (const tool of ["mcp__plugin_openviking-memory_openviking__privacy_upsert", ...AGENT_TOOLS]) { + const input = { tool, prompt: `use ${SAVED}` }; + assert.equal((await unsealCall(post, input)).call, input); + } + assert.equal(calls.length, 0); + assert.ok(AGENT_TOOLS.has("Agent")); +}); + +test("unsealCall: an `ov privacy` command and an unknown reference stay as written", async () => { + const { post } = vault(); + const ovRun = { tool: "Bash", command: `ov privacy run --env T='${SAVED}' -- sh -c 'x "$T"'` }; + assert.equal((await unsealCall(post, ovRun)).call, ovRun); + const missing = { tool: "Bash", command: `echo ${SAVED.replace("github", "gone")}` }; + assert.equal((await unsealCall(post, missing)).call, missing); +}); + +test("unsealCall: a failed resolve blocks the call", async () => { + const { post } = vault({ resolve: () => new Error("ECONNREFUSED") }); + const res = await unsealCall(post, { tool: "Bash", command: `echo ${SAVED}` }); + assert.match(res.deny, /^OpenViking blocked this tool call: .*could not resolve a secret reference: cannot reach the OpenViking server: ECONNREFUSED/); + assert.match(res.deny, /The tool did not run/); + const res500 = await unsealCall(vault({ resolve: () => ({ status: 500 }) }).post, { tool: "Bash", command: `echo ${SAVED}` }); + assert.match(res500.deny, /HTTP 500/); +}); + +test("sealToolResult: the record and its context are sealed, an unchanged result is kept", async () => { + const { post, calls } = vault(); + const outcome = { ref: 3, text: `out ${VALUE}`, result: { stdout: `token=${VALUE}\n`, stderr: "", interrupted: false } }; + assert.deepEqual(await sealToolResult(post, outcome), { + result: { stdout: `token=${SAVED}\n`, stderr: "", interrupted: false }, + }); + assert.deepEqual(calls.at(-1).body, { texts: [{ text: `token=${VALUE}\n`, enroll: false }] }); + const withContext = { ...outcome, context: [`ctx ${VALUE}`] }; + assert.deepEqual((await sealToolResult(post, withContext, { enroll: true })).context, [`ctx ${SAVED}`]); + assert.equal(calls.at(-1).body.texts.every((t) => t.enroll === true), true); + const clean = { ref: 4, text: "fine", result: { stdout: "all fine here", stderr: "" } }; + assert.equal(await sealToolResult(post, clean), clean); + const denied = { deny: "no" }; + assert.equal(await sealToolResult(post, denied), denied); +}); + +test("sealToolResult: an error's text is sealed and given back as a deny", async () => { + const { post } = vault(); + const failed = { isError: true, ref: 5, text: `Exit code 1\nbad token ${VALUE}`, result: "x" }; + assert.deepEqual(await sealToolResult(post, failed), { deny: `Exit code 1\nbad token ${SAVED}` }); + const plain = { isError: true, text: "Exit code 1\nnothing secret" }; + assert.equal(await sealToolResult(post, plain), plain); + // The context a hook attached stays, sealed, after the error's text. + const noted = { isError: true, text: "Exit code 1", context: [`hint: ${VALUE}`] }; + assert.deepEqual(await sealToolResult(post, noted), { deny: `Exit code 1\n\nhint: ${SAVED}` }); +}); + +test("sealToolResult: a failed seal withholds the result", async () => { + const { post } = vault({ seal: async () => ({ status: 503, json: {} }) }); + const res = await sealToolResult(post, { result: { stdout: `token=${VALUE}` } }); + assert.deepEqual(res, { deny: withheld("HTTP 503") }); + assert.doesNotMatch(res.deny, new RegExp(VALUE)); +}); + +test("sealAttachment: sealed without enroll, withheld on failure", async () => { + const { post, calls } = vault(); + assert.equal(await sealAttachment(post, `file: ${VALUE}`), `file: ${SAVED}`); + assert.deepEqual(calls[0].body, { texts: [{ text: `file: ${VALUE}`, enroll: false }] }); + assert.equal(await sealAttachment(post, "plain text"), "plain text"); + const broken = vault({ seal: async () => ({ status: 500, json: {} }) }); + const text = await sealAttachment(broken.post, `file: ${VALUE}`); + assert.match(text, /^\[OpenViking withheld this attached content: sealing secrets in it failed \(HTTP 500\)/); +}); + +test("serverPost: URL, headers and body, the parsed answer, and a timeout", async () => { + const seen = []; + const fetch = async (url, init) => { + seen.push({ url, init }); + return { status: 200, text: '{"status":"ok","result":{"value":"v"}}' }; + }; + const post = serverPost(fetch, { baseUrl: "http://ov:1933", headers: { Authorization: "Bearer k" } }); + assert.deepEqual(await post("/api/v1/privacy-configs/resolve", { selector: "s" }), { + status: 200, + json: { status: "ok", result: { value: "v" } }, + }); + assert.deepEqual(seen, [{ + url: "http://ov:1933/api/v1/privacy-configs/resolve", + init: { method: "POST", headers: { Authorization: "Bearer k", "Content-Type": "application/json" }, body: '{"selector":"s"}' }, + }]); + const html = serverPost(async () => ({ status: 200, text: "" }), { baseUrl: "http://ov" }); + assert.deepEqual(await html("/x", {}), { status: 200, json: null }); + const slow = serverPost(() => new Promise(() => {}), { baseUrl: "http://ov" }, { timeoutMs: 20 }); + await assert.rejects(slow("/x", {}), { name: "TimeoutError" }); + await assert.rejects(serverPost(fetch, undefined)("/x", {}), /no OpenViking server URL/); + // Through the core, a timeout reads as one. + const decision = await sealPrompt({ text: "hello there" }, { post: slow }); + assert.match(decision.reason, /did not answer in time/); +}); + +// ── a server that cannot seal ─────────────────────────────────────────── + +for (const [name, check, pattern, hint] of [ + ["a server too old by the table", () => ({ supported: false, required: "0.5.7", actual: "0.5.6" }), + /server is version 0\.5\.6, and sealing secrets needs 0\.5\.7 or newer/, /Upgrade the OpenViking server/], + ["a failing health check", () => ({ supported: false, required: "0.5.7", actual: null }), + /version could not be read/, /running and reachable/], + ["an unknown setting", () => settingUnknown(), + /OPENVIKING_SEAL_SECRETS is on, but the plugin's settings could not be read here/, /Use Claude Code where the plugin can run its setting helper/], +]) { + test(`${name} stops at each point with the reason named, without a call`, async () => { + const server = vault(); + const post = createSealPolicy({ check }).guard(server.post); + const drop = await sealPrompt({ text: `key ${VALUE}` }, { post }); + assert.equal(drop.kind, "drop"); + assert.match(drop.reason, pattern); + assert.match(drop.reason, hint); + assert.match((await unsealCall(post, { tool: "Bash", command: `echo ${SAVED}` })).deny, pattern); + assert.match((await sealToolResult(post, { result: { stdout: `token=${VALUE}` } })).deny, /withheld/); + assert.match(await sealAttachment(post, `file: ${VALUE}`), /withheld/); + assert.equal(server.calls.length, 0); + }); +} diff --git a/examples/claude-code-memory-plugin/scripts/seal-prompt.mjs b/examples/claude-code-memory-plugin/scripts/seal-prompt.mjs new file mode 100644 index 00000000000..b78c852acdd --- /dev/null +++ b/examples/claude-code-memory-plugin/scripts/seal-prompt.mjs @@ -0,0 +1,78 @@ +#!/usr/bin/env node + +/** + * The setting helper the hooks module in `mods/seal/` runs once per session. A + * hooks module has no Node, so the plugin's config chain is read through this + * one-shot process; every seal and resolve call then goes from the module to + * the server directly. It prints one SealSetting (scripts/lib/prompt-seal.d.mts): + * with sealing on, `server` carries the URL and headers every other hook sends + * (credential included) and `support` the server's support for sealing, from + * one `GET /health`. + * + * Any failure to answer exits non-zero. Nothing here logs a credential. + */ + +import { realpathSync } from "node:fs"; +import { pathToFileURL } from "node:url"; + +import { loadConfig } from "./config.mjs"; +import { parseExtraHeaders } from "./shared/mcp-proxy-config.mjs"; +import { buildOvHeaders } from "./shared/ov-http.mjs"; +import { featureStatus, healthVersion } from "./shared/server-features.mjs"; + +// The mod gives this whole process 5 s. +const HEALTH_TIMEOUT_MS = 3000; + +/** How the module reaches the server: the URL and headers of every other hook. */ +export function serverOf(cfg, env = process.env) { + const extraHeaders = parseExtraHeaders(env.OPENVIKING_EXTRA_HEADERS, { onWarn: () => {} }); + return { baseUrl: String(cfg.baseUrl || "").replace(/\/+$/, ""), headers: buildOvHeaders(cfg, { extraHeaders }) }; +} + +/** `fetchJSON` for `healthVersion`: one GET over Node's fetch, `{ ok, result }`, never throws. */ +function healthFetch(server) { + return async (path, _init, { timeoutMs = HEALTH_TIMEOUT_MS } = {}) => { + try { + const res = await fetch(`${server.baseUrl}${path}`, { + headers: server.headers, + signal: AbortSignal.timeout(timeoutMs), + }); + const body = await res.json().catch(() => null); + return { ok: res.ok, status: res.status, result: body?.result ?? body }; + } catch { + return { ok: false, status: 0, result: null }; + } + }; +} + +export async function readSetting({ env = process.env, load = loadConfig, fetchFor = healthFetch } = {}) { + const cfg = load(process.cwd(), { env }); + if (!cfg.sealSecrets) return { sealing: "off" }; + const server = serverOf(cfg, env); + const version = server.baseUrl ? await healthVersion(fetchFor(server), { timeoutMs: HEALTH_TIMEOUT_MS }) : null; + return { + sealing: "on", + enrollToolSecrets: Boolean(cfg.enrollToolSecrets), + server, + support: featureStatus("privacy_seal", version), + }; +} + +async function main() { + process.stdout.write(`${JSON.stringify(await readSetting())}\n`); +} + +function isDirectRun() { + try { + return Boolean(process.argv[1]) && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href; + } catch { + return false; + } +} + +if (isDirectRun()) { + main().catch((error) => { + process.stderr.write(`seal-prompt: ${error instanceof Error ? error.message : String(error)}\n`); + process.exit(1); + }); +} diff --git a/examples/claude-code-memory-plugin/scripts/seal-prompt.test.mjs b/examples/claude-code-memory-plugin/scripts/seal-prompt.test.mjs new file mode 100644 index 00000000000..7427b04805a --- /dev/null +++ b/examples/claude-code-memory-plugin/scripts/seal-prompt.test.mjs @@ -0,0 +1,108 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +import { serverOf } from "./seal-prompt.mjs"; + +const HELPER = join(dirname(fileURLToPath(import.meta.url)), "seal-prompt.mjs"); + +test("serverOf: the URL and the headers every other hook sends", () => { + assert.deepEqual(serverOf({ baseUrl: "http://ov:1933/", apiKey: "sk-test" }, {}), { + baseUrl: "http://ov:1933", + headers: { "Content-Type": "application/json", Authorization: "Bearer sk-test" }, + }); + const extra = serverOf({ baseUrl: "http://ov" }, { OPENVIKING_EXTRA_HEADERS: '{"CF-Access-Client-Id":"id"}' }); + assert.equal(extra.headers["CF-Access-Client-Id"], "id"); + assert.equal(extra.headers.Authorization, undefined); +}); + +// The helper as the mod runs it: a process reading the plugin's config chain. +function runHelper(env) { + return new Promise((resolve) => { + const child = spawn(process.execPath, [HELPER], { env, stdio: ["pipe", "pipe", "pipe"] }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (c) => (stdout += c)); + child.stderr.on("data", (c) => (stderr += c)); + child.on("close", (code) => resolve({ code, stdout, stderr })); + child.stdin.end(); + }); +} + +function isolatedEnv(dir, extra) { + const env = { PATH: process.env.PATH, HOME: dir, OPENVIKING_HOME: join(dir, "home") }; + env.OPENVIKING_CONFIG_FILE = join(dir, "ov.conf"); + env.OPENVIKING_CLI_CONFIG_FILE = join(dir, "ovcli.conf"); + return { ...env, ...extra }; +} + +const readSetting = async (env) => { + const res = await runHelper(env); + assert.equal(res.code, 0, res.stderr); + return JSON.parse(res.stdout); +}; + +test("the setting is off by default and follows ovcli.conf and the environment", async (t) => { + const dir = mkdtempSync(join(tmpdir(), "cc-seal-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + assert.deepEqual(await readSetting(isolatedEnv(dir, {})), { sealing: "off" }); + const forced = await readSetting(isolatedEnv(dir, { OPENVIKING_SEAL_SECRETS: "1", OPENVIKING_URL: "http://127.0.0.1:9" })); + assert.equal(forced.sealing, "on"); + assert.equal(forced.server.baseUrl, "http://127.0.0.1:9"); + + writeFileSync( + join(dir, "ovcli.conf"), + JSON.stringify({ url: "http://x:1933", api_key: "sk-test", plugin: { claude_code: { sealSecrets: true } } }), + ); + const on = await readSetting(isolatedEnv(dir, {})); + assert.equal(on.sealing, "on"); + assert.equal(on.enrollToolSecrets, false); + assert.equal(on.server.baseUrl, "http://x:1933"); + assert.equal(on.server.headers.Authorization, "Bearer sk-test"); + assert.equal((await readSetting(isolatedEnv(dir, { OPENVIKING_ENROLL_TOOL_SECRETS: "1" }))).enrollToolSecrets, true); + assert.deepEqual(await readSetting(isolatedEnv(dir, { OPENVIKING_SEAL_SECRETS: "0" })), { sealing: "off" }); + + writeFileSync( + join(dir, "ovcli.conf"), + JSON.stringify({ url: "http://x:1933", plugin: { claude_code: { sealSecrets: true, enrollToolSecrets: true } } }), + ); + assert.equal((await readSetting(isolatedEnv(dir, {}))).enrollToolSecrets, true); +}); + +// One stub /health, answering `version` (or failing with 503 when it is null). +async function healthServer(t, version) { + const seen = []; + const server = createServer((req, res) => { + seen.push({ url: req.url, auth: req.headers.authorization }); + const body = version === null ? { status: "error" } : { status: "ok", healthy: true, version }; + res.writeHead(version === null ? 503 : 200, { "content-type": "application/json" }); + res.end(JSON.stringify(body)); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + t.after(() => server.close()); + return { url: `http://127.0.0.1:${server.address().port}`, seen }; +} + +test("the setting reports whether the server supports sealing, from one /health", async (t) => { + const dir = mkdtempSync(join(tmpdir(), "cc-seal-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + for (const [version, supported] of [["0.5.7.dev44", true], ["0.6.1", true], ["0.5.6", false], [null, false]]) { + const health = await healthServer(t, version); + const env = isolatedEnv(dir, { OPENVIKING_SEAL_SECRETS: "1", OPENVIKING_URL: health.url, OPENVIKING_API_KEY: "sk-h" }); + const on = await readSetting(env); + assert.equal(on.sealing, "on"); + assert.deepEqual(on.support, { feature: "privacy_seal", supported, required: "0.5.7", actual: version }, String(version)); + assert.deepEqual(health.seen, [{ url: "/health", auth: "Bearer sk-h" }]); + } + const unreachable = await readSetting(isolatedEnv(dir, { + OPENVIKING_SEAL_SECRETS: "1", + OPENVIKING_URL: "http://127.0.0.1:9", + })); + assert.equal(unreachable.support.supported, false); + assert.equal(unreachable.support.actual, null); +}); diff --git a/examples/claude-code-memory-plugin/scripts/shared/config-schema.mjs b/examples/claude-code-memory-plugin/scripts/shared/config-schema.mjs index 0250d3eece5..f427d52229c 100644 --- a/examples/claude-code-memory-plugin/scripts/shared/config-schema.mjs +++ b/examples/claude-code-memory-plugin/scripts/shared/config-schema.mjs @@ -189,6 +189,10 @@ export const KNOBS = [ capability: "session", }, { name: "skipSubagentSessions", type: "bool", default: false, env: "OPENVIKING_SKIP_SUBAGENT_SESSIONS", capability: "session" }, + // Plugin sealing; no workspace key, so a committed file cannot switch it off. + { name: "sealSecrets", type: "bool", default: false, env: "OPENVIKING_SEAL_SECRETS", capability: "session" }, + // With sealSecrets on, tool results are enrolled too. + { name: "enrollToolSecrets", type: "bool", default: false, env: "OPENVIKING_ENROLL_TOOL_SECRETS", capability: "session" }, { name: "repoContext", type: "bool", default: true, capability: "session" }, { name: "repoContextCacheTtlMs", type: "int", default: 60000, min: 1000, max: 3600000, capability: "session" }, diff --git a/examples/claude-code-memory-plugin/scripts/shared/seal-core.mjs b/examples/claude-code-memory-plugin/scripts/shared/seal-core.mjs new file mode 100644 index 00000000000..e1ffeacd825 --- /dev/null +++ b/examples/claude-code-memory-plugin/scripts/shared/seal-core.mjs @@ -0,0 +1,522 @@ +// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT. +/** + * Plugin-side sealing: the part every harness adapter shares. + * + * A harness plugin keeps registered secrets out of what the model sees and + * gives tools the real values. The OpenViking server does the matching + * (SEAL_PATH; see "Seal Texts" in docs/en/api/10-privacy.md) and turns a + * reference back into its value (RESOLVE_PATH); this module builds the + * requests, checks the answers and walks JSON-like values. Each adapter + * decides where to call it and what a failure does there. The exported API + * is typed in seal-core.d.mts. + * + * Pure ES module: no Node built-ins, no DOM, no global `fetch`, so it loads in + * Node and in the Claude Code mods runtime alike. All network access goes + * through the caller's `post(path, body) -> Promise<{ status, json }>`, where + * `json` is the server's `{ status: "ok", result }` envelope; `post` rejects + * when no answer arrived (`name` AbortError or TimeoutError, or `aborted: + * true`, reads as a timeout). Every failure is a SealError. + * + * Nothing here logs a text, a value or a response. + */ + +export const SEAL_PATH = "/api/v1/privacy-configs/seal"; +export const RESOLVE_PATH = "/api/v1/privacy-configs/resolve"; + +// The seal endpoint takes at most this many texts per call. +export const MAX_TEXTS = 1024; +// The endpoint allows 16 MiB of text per call; a request body through the +// Claude Code mods runtime may be 4 MiB, so a call carries about 3 MiB. +export const BATCH_BYTES = 3 * 1024 * 1024; +export const MAX_TEXT_BYTES = 16 * 1024 * 1024; +// Registered values are at least this long, so shorter strings cannot hold one. +export const MIN_LENGTH = 6; + +// The full canonical reference, in `credential` or `auto`. +const REFERENCE_SOURCE = + "\\{\\{ov_privacy:([^\\s:{}]+):viking:\\/\\/~\\/privacy\\/(?:credential|auto)\\/[^#\\s/{}]+#\\/values\\/[^{}\\s]+\\}\\}"; +const CANONICAL_REFERENCE = new RegExp(`^${REFERENCE_SOURCE}$`); +// A tool argument holding this command hands references to the OpenViking CLI as they are. +const OV_PRIVACY = /(?` as written: by then the model holds the + * reference privacy_upsert returned, and the temporary one no longer resolves. + */ +export function sealNote(references) { + const list = references.join(", "); + const first = references[0]; + return ( + `OpenViking stored a secret from the user's message and replaced it with a reference: ${list}. ` + + "You will not see the value. Unless it is clearly for one-off use, save it under a proper name now with privacy_upsert (or `ov privacy upsert`), " + + "passing the reference as the value and a short description of what it is for, " + + `for example category="credential", target_key="github", values={"token": "${first}"}, description="GitHub PAT for the acme org". ` + + "The temporary entry is removed once it is saved, so use the reference that privacy_upsert returns from then on. " + + "Write the reference as is wherever the secret is needed, for example " + + "`ov privacy run --env NAME='' -- sh -c ''`; " + + "do not resolve it to plain text or print any part of it. " + + "Tell the user what was stored and under which name." + ); +} + +/** What the model sees in place of a tool result that could not be sealed. */ +export function withheld(reason) { + const why = reason ? ` (${reason})` : ""; + return ( + `[OpenViking withheld this tool result: sealing secrets in it failed${why}. ` + + "The tool did run, but its output is not shown so that no secret reaches the model.]" + ); +} + +// ── when sealing cannot be done ───────────────────────────────────────── + +/** The SealError of a server without the capability, or null. */ +function unsupported(status) { + if (!status || status.supported === true) return null; + const required = status.required || "a newer version"; + if (!status.actual) { + return new SealError( + `the OpenViking server's version could not be read (its health check failed), and sealing secrets needs ${required} or newer`, + { reason: "version_unknown" }, + ); + } + return new SealError( + `the OpenViking server is version ${status.actual}, and sealing secrets needs ${required} or newer`, + { reason: "server_too_old" }, + ); +} + +export function whyNotSealed(error) { + const reason = error?.reason ?? "seal_failed"; + const message = error instanceof Error ? error.message : String(error ?? "unknown error"); + return reason === "seal_failed" ? `sealing secrets failed (${message})` : message; +} + +/** What the user can do about `error`; the stop messages end with this. */ +export function stopHint(error) { + const fix = + { + server_too_old: "Upgrade the OpenViking server", + version_unknown: "Make sure the OpenViking server is running and reachable", + setting_unknown: "Use Claude Code where the plugin can run its setting helper (the CLI)", + }[error?.reason] ?? "Try again once the OpenViking server answers"; + return ( + "With sealSecrets on, OpenViking sends nothing unsealed. " + + `${fix}, or turn sealing off with sealSecrets: false (OPENVIKING_SEAL_SECRETS=0).` + ); +} + +/** + * Whether the server can seal. `check()` answers `{ supported, required, + * actual }` for the server (`featureStatus("privacy_seal", version)`), or a + * SealError of its own. `unavailable()` resolves the SealError of a server + * that cannot seal (`server_too_old`, or `version_unknown` when the version + * could not be read) or null. Only "can seal" is kept: a no is asked again the + * next time, so sealing resumes once the server can. `guard(post)` is a `post` + * that asks `unavailable()` first and makes no call while it says no, so a + * pass that sends nothing does not ask the server at all. + */ +export function createSealPolicy({ check = async () => ({ supported: true }) } = {}) { + let known = null; + const policy = { + unavailable() { + const asked = (known ??= Promise.resolve() + .then(check) + .then( + (status) => (status instanceof SealError ? status : unsupported(status)), + () => unsupported({ supported: false }), + )); + asked.then((problem) => { + if (problem && known === asked) known = null; + }); + return asked; + }, + guard(post) { + return async (path, body) => { + const problem = await policy.unavailable(); + if (problem) throw problem; + return post(path, body); + }; + }, + }; + return policy; +} + +// ── sizes and code points ─────────────────────────────────────────────── + +function codePointLength(text) { + let n = 0; + for (const _ of text) n += 1; + return n; +} + +function utf8Size(text) { + let n = 0; + for (const ch of text) { + const c = ch.codePointAt(0); + n += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + return n; +} + +// ── talking to the server ─────────────────────────────────────────────── + +async function call(post, path, body) { + try { + return await post(path, body); + } catch (error) { + if (error instanceof SealError) throw error; + if (error?.name === "AbortError" || error?.name === "TimeoutError" || error?.aborted) { + throw new SealError("the OpenViking server did not answer in time"); + } + const message = error instanceof Error ? error.message : String(error ?? ""); + throw new SealError(`cannot reach the OpenViking server${message ? `: ${message}` : ""}`); + } +} + +function httpFailure(status, json, missing) { + if (status === 404 && missing) return new SealError(`HTTP 404: ${missing}`, { status }); + const message = json && typeof json === "object" ? json.error?.message : undefined; + return new SealError(`HTTP ${status}${typeof message === "string" && message ? `: ${message}` : ""}`, { status }); +} + +/** The `result` of an ok answer; throws on anything else. */ +function okResult(answer, missing) { + if (!answer || typeof answer !== "object") throw malformed("no answer"); + const { status, json } = answer; + if (!Number.isInteger(status)) throw malformed("no HTTP status"); + if (status < 200 || status >= 300) throw httpFailure(status, json, missing); + if (!json || typeof json !== "object" || json.status !== "ok") throw malformed("the answer is not ok"); + return json.result; +} + +// ── sealing ───────────────────────────────────────────────────────────── + +/** + * Check one `result.texts` item against its original text: offsets in range + * and in order, and a canonical reference on every span. The sealed text is + * built from the spans; the item's `text` is not read. An item with no spans + * is no change. + */ +function checkItem(item, original, index) { + const where = `texts[${index}]`; + if (item === null) return null; + if (typeof item !== "object" || Array.isArray(item)) throw malformed(`${where} is not an object or null`); + if (!Array.isArray(item.replaced)) throw malformed(`${where}.replaced is not a list`); + if (!item.replaced.length) return null; + + const chars = Array.from(original); + const length = chars.length; + const spans = []; + const parts = []; + let cursor = 0; + for (const span of item.replaced) { + if (!span || typeof span !== "object") throw malformed("a replacement is not an object"); + const { start, end, reference } = span; + if (!Number.isInteger(start) || !Number.isInteger(end) || start < cursor || end <= start || end > length) { + throw malformed("replacement offsets are out of order or out of range"); + } + if (!isCanonicalReference(reference)) throw malformed("a replacement has no canonical reference"); + parts.push(chars.slice(cursor, start).join(""), reference); + cursor = end; + spans.push({ start, end, reference, temporary: span.temporary === true }); + } + parts.push(chars.slice(cursor).join("")); + return { text: parts.join(""), spans }; +} + +async function sealBatch(post, batch) { + const answer = await call(post, SEAL_PATH, { texts: batch.map(({ text, enroll }) => ({ text, enroll })) }); + const result = okResult(answer, "the OpenViking server has no seal endpoint; it may be too old"); + if (!result || typeof result !== "object") throw malformed("no result"); + const { texts } = result; + if (!Array.isArray(texts) || texts.length !== batch.length) throw malformed("result.texts does not match the request"); + return texts.map((item, i) => checkItem(item, batch[i].text, i)); +} + +function batches(units) { + const out = []; + let batch = []; + let size = 0; + for (const unit of units) { + // The JSON-encoded size, which is what the request body carries. + const length = utf8Size(JSON.stringify(unit.text)) + 32; + if (batch.length && (batch.length === MAX_TEXTS || size + length > BATCH_BYTES)) { + out.push(batch); + batch = []; + size = 0; + } + batch.push(unit); + size += length; + } + if (batch.length) out.push(batch); + return out; +} + +function distinctTemporary(spans, into = []) { + for (const span of spans) { + if (span.temporary && !into.includes(span.reference)) into.push(span.reference); + } + return into; +} + +/** + * Seal `items` (`[{ text, enroll? }]`) and resolve `{ texts, temporary }`: + * `texts[i]` is `{ text, changed, temporary, spans }` for `items[i]`, where + * `text` is the text to use (the original when nothing was replaced), + * `temporary` its distinct temporary references in order of first + * appearance, and `spans` the checked replacements `{ start, end, reference, + * temporary }` (code point offsets into the original). The top-level + * `temporary` is the same over all texts, in input order. A duplicate text is + * sent once; the request is split at MAX_TEXTS texts or about BATCH_BYTES per + * call. + */ +export async function sealTexts(post, items) { + if (!Array.isArray(items)) throw new SealError("sealTexts needs a list of texts"); + const units = []; + const unitOf = new Map(); + const order = items.map((item) => { + const text = item?.text; + if (typeof text !== "string") throw new SealError("sealTexts needs a string text in every item"); + const enroll = item.enroll === true; + if (utf8Size(text) > MAX_TEXT_BYTES) throw new SealError("a text is larger than the seal endpoint accepts"); + const key = `${enroll ? 1 : 0}\u0000${text}`; + if (!unitOf.has(key)) { + unitOf.set(key, units.length); + units.push({ text, enroll }); + } + return unitOf.get(key); + }); + if (!units.length) return { texts: [], temporary: [] }; + + const results = []; + for (const batch of batches(units)) results.push(...(await sealBatch(post, batch))); + + const temporary = []; + const texts = order.map((index) => { + const item = results[index]; + if (!item) return { text: units[index].text, changed: false, temporary: [], spans: [] }; + distinctTemporary(item.spans, temporary); + return { text: item.text, changed: true, temporary: distinctTemporary(item.spans), spans: item.spans }; + }); + return { texts, temporary }; +} + +// ── walking JSON-like values ──────────────────────────────────────────── + +function isPlainObject(node) { + if (!node || typeof node !== "object") return false; + const proto = Object.getPrototypeOf(node); + return proto === Object.prototype || proto === null; +} + +function eachString(node, visit, key) { + if (typeof node === "string") { + visit(node, key); + } else if (Array.isArray(node)) { + for (const item of node) eachString(item, visit); + } else if (isPlainObject(node)) { + for (const name of Object.keys(node)) eachString(node[name], visit, name); + } +} + +/** `node` with `edit(text, key)` applied to every string leaf; the same object where nothing changed. */ +function mapStrings(node, edit, key) { + if (typeof node === "string") return edit(node, key); + if (Array.isArray(node)) { + const items = node.map((item) => mapStrings(item, edit)); + return items.every((item, i) => item === node[i]) ? node : items; + } + if (isPlainObject(node)) { + let out = null; + for (const key of Object.keys(node)) { + const next = mapStrings(node[key], edit, key); + if (next !== node[key]) { + out ??= Object.assign(Object.getPrototypeOf(node) === null ? Object.create(null) : {}, node); + out[key] = next; + } + } + return out ?? node; + } + return node; +} + +// File content such as an image is not text a secret is typed into, and can +// be megabytes: a data: URI anywhere, and a long base64 run under the keys +// file content goes in (`data`, `file_data`), the gateway's rule. A long run +// under any other key may be a secret itself (a session token) and is sealed. +const BASE64 = /^[A-Za-z0-9+/=_-]{256,}$/; + +function isEncodedData(text, key) { + if (text.startsWith("data:") && text.slice(0, 256).includes(",")) return true; + return (key === "data" || key === "file_data") && BASE64.test(text); +} + +function isSealableLeaf(text, key) { + return codePointLength(text) >= MIN_LENGTH && !isEncodedData(text, key); +} + +/** + * Seal every string leaf of a JSON-like value (arrays and plain objects; + * object keys are never touched), all leaves in one sealTexts, and resolve + * `{ value, temporary, sealed }`. Strings of fewer than MIN_LENGTH code points + * are left as they are, and so is encoded file content (isEncodedData). Parts + * with nothing replaced keep their identity; nothing replaced at + * all returns the input itself. `sealed` counts the string leaves rewritten. + */ +export async function sealValue(post, value, { enroll = false } = {}) { + const leaves = []; + eachString(value, (text, key) => { + if (isSealableLeaf(text, key)) leaves.push(text); + }); + const unique = [...new Set(leaves)]; + if (!unique.length) return { value, temporary: [], sealed: 0 }; + + const { texts } = await sealTexts(post, unique.map((text) => ({ text, enroll: enroll === true }))); + const byText = new Map(unique.map((text, i) => [text, texts[i]])); + const temporary = []; + for (const text of leaves) distinctTemporary(byText.get(text).spans, temporary); + let sealed = 0; + const rewritten = mapStrings(value, (text, key) => { + const result = isSealableLeaf(text, key) && byText.get(text); + if (!result?.changed) return text; + sealed += 1; + return result.text; + }); + return { value: rewritten, temporary, sealed }; +} + +// ── unsealing ─────────────────────────────────────────────────────────── + +function referencesIn(text) { + if (containsOvPrivacy(text)) return []; + return [...text.matchAll(new RegExp(REFERENCE_SOURCE, "g"))]; +} + +// 404 (unknown) and 403 (another user's reference) leave the reference as it is. +async function resolveOne(post, reference) { + let result; + try { + const answer = await call(post, RESOLVE_PATH, { selector: reference }); + if (answer && typeof answer === "object" && (answer.status === 404 || answer.status === 403)) { + return null; + } + result = okResult(answer); + } catch (error) { + if (error instanceof SealError && error.reason !== "seal_failed") throw error; + throw new SealError(`could not resolve a secret reference: ${error.message}`, { status: error.status }); + } + const value = result && typeof result === "object" ? result.value : undefined; + return typeof value === "string" && value ? value : null; +} + +/** + * Every whole canonical reference in a string leaf is replaced + * by its value once the resolve endpoint returned one and sealing that value + * alone gives back exactly one span over all of it with the same reference; + * resolve `{ value, replaced }`. A string that contains an `ov privacy` + * invocation is left untouched as a whole. `skip: true` (the arguments of an + * OpenViking or agent-spawning tool) returns the value as it is without a + * request. Each reference is resolved at most once per call; `replaced` + * counts the occurrences rewritten. + */ +export async function unsealValue(post, value, { skip = false } = {}) { + if (skip) return { value, replaced: 0 }; + const found = new Set(); + eachString(value, (text) => { + for (const match of referencesIn(text)) found.add(match[0]); + }); + if (!found.size) return { value, replaced: 0 }; + + const references = [...found]; + const resolved = new Map(); + for (const reference of references) resolved.set(reference, await resolveOne(post, reference)); + + // Only a value that seals back to its own reference: the next turn must + // show the model the reference it wrote. + const candidates = [...new Set([...resolved.values()].filter(Boolean))]; + const values = new Map(); + if (candidates.length) { + let checked; + try { + ({ texts: checked } = await sealTexts(post, candidates.map((text) => ({ text, enroll: false })))); + } catch (error) { + if (error instanceof SealError && error.reason !== "seal_failed") throw error; + throw new SealError(`could not confirm a secret reference: ${error.message}`, { status: error.status }); + } + const byValue = new Map(candidates.map((text, i) => [text, checked[i]])); + for (const [reference, plain] of resolved) { + if (!plain) continue; + const { spans } = byValue.get(plain); + const exact = + spans.length === 1 && + spans[0].start === 0 && + spans[0].end === codePointLength(plain) && + spans[0].reference === reference; + if (exact) values.set(reference, plain); + } + } + if (!values.size) return { value, replaced: 0 }; + + let replaced = 0; + const rewritten = mapStrings(value, (text) => { + const matches = referencesIn(text).filter((match) => values.has(match[0])); + if (!matches.length) return text; + let out = ""; + let cursor = 0; + for (const match of matches) { + out += text.slice(cursor, match.index) + values.get(match[0]); + cursor = match.index + match[0].length; + } + replaced += matches.length; + return out + text.slice(cursor); + }); + return { value: rewritten, replaced }; +} diff --git a/examples/claude-code-memory-plugin/scripts/shared/server-features.json b/examples/claude-code-memory-plugin/scripts/shared/server-features.json new file mode 100644 index 00000000000..20d8f22f7bf --- /dev/null +++ b/examples/claude-code-memory-plugin/scripts/shared/server-features.json @@ -0,0 +1,4 @@ +{ + "working_memory_opt_in": "0.5.0", + "privacy_seal": "0.5.7" +} diff --git a/examples/claude-code-memory-plugin/scripts/shared/server-features.mjs b/examples/claude-code-memory-plugin/scripts/shared/server-features.mjs new file mode 100644 index 00000000000..f3f8b101c04 --- /dev/null +++ b/examples/claude-code-memory-plugin/scripts/shared/server-features.mjs @@ -0,0 +1,92 @@ +// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT. +/** + * Which OpenViking server capabilities a server has, by its version. + * + * `server-features.json` lists each capability a client depends on with the + * first server version that has it; the gateway ships the same file + * (`openviking_gateway/server-features.json`), and the sync keeps both copies + * byte-identical. Callers ask `supports` before using a capability; they do + * not infer support from a 404. + * + * Exports: + * + * SERVER_FEATURES the table, frozen + * requiredVersion(feature) -> string the first version with `feature` + * supports(feature, version) -> boolean + * Compares the release part of `version` (what `/health` reports, so + * `0.5.7.dev44` counts as 0.5.7) with the table. A version that cannot be + * read does not support anything; "readable" is PEP 440, the grammar the + * gateway's reader (Python `packaging`) accepts, so both answer the same + * for the same string. An unknown feature name throws: it is a programming + * error, not a property of the server. + * featureStatus(feature, version) -> { feature, supported, required, actual } + * The same answer with what a message to the user needs; `actual` is the + * version as given, or null. + * healthVersion(fetchJSON) -> Promise + * The version from `GET /health` through a plugin's `fetchJSON` + * (`ov-http.mjs`: resolves `{ ok, result }`, never throws); null when the + * health check fails or reports no version. + */ +import { readFileSync } from "node:fs"; + +const TABLE = JSON.parse(readFileSync(new URL("./server-features.json", import.meta.url), "utf-8")); + +export const SERVER_FEATURES = Object.freeze({ ...TABLE }); + +// packaging.version.VERSION_PATTERN, anchored and case-insensitive as +// `Version` uses it. Only the epoch and the release are read; the rest is +// matched so that a string Python rejects is rejected here too. +const PEP440 = new RegExp( + "^v?(?:(\\d+)!)?(\\d+(?:\\.\\d+)*)" + + "(?:[-_.]?(?:alpha|a|beta|b|preview|pre|c|rc)[-_.]?\\d*)?" + + "(?:-\\d+|[-_.]?(?:post|rev|r)[-_.]?\\d*)?" + + "(?:[-_.]?dev[-_.]?\\d*)?" + + "(?:\\+[a-z0-9]+(?:[-_.][a-z0-9]+)*)?$", + "i", +); + +/** `[epoch, ...release]` of a version string, or null when it is not one. */ +function release(version) { + if (typeof version !== "string") return null; + const match = PEP440.exec(version.trim()); + if (!match) return null; + return [Number(match[1] ?? 0), ...match[2].split(".").map(Number)]; +} + +export function requiredVersion(feature) { + if (!Object.prototype.hasOwnProperty.call(SERVER_FEATURES, feature)) { + throw new Error(`unknown server feature: ${String(feature)}`); + } + return SERVER_FEATURES[feature]; +} + +export function supports(feature, version) { + const need = release(requiredVersion(feature)); + const have = release(version); + if (!have) return false; + for (let i = 0; i < Math.max(have.length, need.length); i += 1) { + const a = have[i] ?? 0; + const b = need[i] ?? 0; + if (a !== b) return a > b; + } + return true; +} + +export function featureStatus(feature, version) { + return { + feature, + supported: supports(feature, version), + required: requiredVersion(feature), + actual: typeof version === "string" && version ? version : null, + }; +} + +export async function healthVersion(fetchJSON, { timeoutMs = 5000 } = {}) { + try { + const res = await fetchJSON("/health", undefined, { timeoutMs }); + const version = res?.ok ? res.result?.version : undefined; + return typeof version === "string" && version ? version : null; + } catch { + return null; + } +} diff --git a/examples/claude-code-memory-plugin/scripts/shared/uri-guard.mjs b/examples/claude-code-memory-plugin/scripts/shared/uri-guard.mjs index 213efcbb842..b80052f710f 100644 --- a/examples/claude-code-memory-plugin/scripts/shared/uri-guard.mjs +++ b/examples/claude-code-memory-plugin/scripts/shared/uri-guard.mjs @@ -47,9 +47,16 @@ export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS, contentKeys = return findVikingUriInValue(args, new Set(contentKeys)); } +// A privacy reference, {{ov_privacy::viking://~/privacy/...#/values/}}, +// names a sealed value and is meant to sit in a command line (`ov privacy run +// --env TOKEN='{{ov_privacy:...}}' -- ...`). Its viking:// URI is not a path, so +// the sweep blanks each reference out before it looks; a bare URI in the same +// string is still found. +const PRIVACY_REFERENCE_RE = /\{\{ov_privacy:[^\s{}]*\}\}/gi; + export function findVikingUriInValue(value, skipKeys) { if (typeof value === "string") { - const match = value.match(/\bviking:\/\/[^\s"'`<>)]*/i); + const match = value.replace(PRIVACY_REFERENCE_RE, " ").match(/\bviking:\/\/[^\s"'`<>)]*/i); return match?.[0] || null; } if (Array.isArray(value)) { diff --git a/examples/claude-code-memory-plugin/skills/openviking-memory/SKILL.md b/examples/claude-code-memory-plugin/skills/openviking-memory/SKILL.md index 253a32e508c..2b9bb18320c 100644 --- a/examples/claude-code-memory-plugin/skills/openviking-memory/SKILL.md +++ b/examples/claude-code-memory-plugin/skills/openviking-memory/SKILL.md @@ -8,8 +8,11 @@ description: > context this session does not have — even if nobody says the word "memory". Also use it when the user asks where memories are stored: per project, per folder, or shared between repositories. Covers choosing between context search, find, list search, and grep, reading viking:// - URIs, and when (not) to write. -version: 2026.10.1 + URIs, and when (not) to write. Also use it when a message or file holds an + {{ov_privacy:…}} reference or says OpenViking replaced a secret with one: it + covers using saved credentials without reading them (`ov privacy run`), and + naming or rotating them. +version: 2026.11.1 --- # OpenViking Memory @@ -98,6 +101,56 @@ Do not invent other keys or commands for this: that file is the whole interface, - Skills stored in OpenViking (the `` list, `add_skill`, moving local skills in) are covered by the `openviking-skills` skill. +## Saved credentials + +OpenViking keeps the user's API keys and tokens in Privacy. A saved secret is +named by a reference such as +`{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}`: the +owner, then the field. It stands for a value you are not meant to read. + +- **Use it without reading it** — `ov privacy run` resolves references for one + local command and masks their values in its output. Pass a reference as an + environment variable with `--env NAME=REF` (repeatable), load `NAME=REF` + lines with `--env-file `, or put it inside an argument; the command + comes after `--`. Single-quote every reference in a shell command, because + `{{…}}` and `#` are otherwise open to shell interpretation: + + ```bash + ov privacy run --env GH_TOKEN='{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}' -- gh repo list + ``` + + To use the variable on the command line, wrap the command in `sh -c '…'`: + + ```bash + ov privacy run --env GH_TOKEN='' -- sh -c 'curl -H "Authorization: Bearer $GH_TOKEN" https://api.github.com/user' + ``` + + `$GH_TOKEN` written outside `sh -c '…'` is expanded by your own shell + before `ov` runs, and is empty. + + Prefer `--env`: with `OPENVIKING_PRIVACY_RUN_STRICT=1` references in arguments are refused. +- **Do not print values.** `privacy_resolve`, `ov privacy resolve`, + `ov privacy get` and `ov privacy version` print plain values; use them only + when the user asks to see a value. Do not print any part of a secret either + (a prefix, a suffix); to check a secret, print only its length. + `ov privacy run` masks only complete values in its output. +- **What exists** — `privacy_tree` lists targets, fields, their references and + descriptions, never values; on the CLI, `ov privacy tree --references` shows + the references and `ov privacy tree -o json` also the descriptions. The + description is how to tell similar credentials apart. `privacy_tree` leaves + the `auto` category out unless you ask for it with `category="auto"`; an + `auto/…` reference was created automatically and works like any other. +- **Naming and rotating** — only when the `privacy_upsert` tool's own + description says that a reference can be passed as the value: then a whole + reference as a value copies that field's current value, so the secret never + passes through you; prefer it. On the CLI, under the same condition: + `ov privacy upsert credential --field =''`. Use it + to save an automatic entry under a proper name in `credential`, or to + replace a value. The automatic entry is removed once saved, so use the + reference the upsert returns from then on. Give a short description of what + the credential is for: `description` on `privacy_upsert`, or `--labels-json + '{"description":"…"}'` on the CLI, which replaces all of the target's labels. + ## Beyond the MCP tools More advanced OpenViking operations are available through the `ov` CLI — diff --git a/examples/codex-memory-plugin/.codex-plugin/plugin.json b/examples/codex-memory-plugin/.codex-plugin/plugin.json index 8392207c7ee..6eb088ce6c2 100644 --- a/examples/codex-memory-plugin/.codex-plugin/plugin.json +++ b/examples/codex-memory-plugin/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "openviking-memory", - "version": "0.11.28", + "version": "0.11.29", "description": "Long-term semantic memory for Codex, powered by OpenViking. Recall on UserPromptSubmit, incremental add_message on Stop (per turn), commit on SessionEnd (Codex >= 0.145) and on PreCompact, with an idle/ended sweep on SessionStart as the fallback for signals, crashes and older Codex builds. Includes a local stdio MCP proxy that reads OpenViking credentials from env/ovcli.conf.", "author": { "name": "OpenViking", diff --git a/examples/codex-memory-plugin/scripts/shared/config-schema.mjs b/examples/codex-memory-plugin/scripts/shared/config-schema.mjs index 0250d3eece5..f427d52229c 100644 --- a/examples/codex-memory-plugin/scripts/shared/config-schema.mjs +++ b/examples/codex-memory-plugin/scripts/shared/config-schema.mjs @@ -189,6 +189,10 @@ export const KNOBS = [ capability: "session", }, { name: "skipSubagentSessions", type: "bool", default: false, env: "OPENVIKING_SKIP_SUBAGENT_SESSIONS", capability: "session" }, + // Plugin sealing; no workspace key, so a committed file cannot switch it off. + { name: "sealSecrets", type: "bool", default: false, env: "OPENVIKING_SEAL_SECRETS", capability: "session" }, + // With sealSecrets on, tool results are enrolled too. + { name: "enrollToolSecrets", type: "bool", default: false, env: "OPENVIKING_ENROLL_TOOL_SECRETS", capability: "session" }, { name: "repoContext", type: "bool", default: true, capability: "session" }, { name: "repoContextCacheTtlMs", type: "int", default: 60000, min: 1000, max: 3600000, capability: "session" }, diff --git a/examples/codex-memory-plugin/skills/openviking-memory/SKILL.md b/examples/codex-memory-plugin/skills/openviking-memory/SKILL.md index 253a32e508c..2b9bb18320c 100644 --- a/examples/codex-memory-plugin/skills/openviking-memory/SKILL.md +++ b/examples/codex-memory-plugin/skills/openviking-memory/SKILL.md @@ -8,8 +8,11 @@ description: > context this session does not have — even if nobody says the word "memory". Also use it when the user asks where memories are stored: per project, per folder, or shared between repositories. Covers choosing between context search, find, list search, and grep, reading viking:// - URIs, and when (not) to write. -version: 2026.10.1 + URIs, and when (not) to write. Also use it when a message or file holds an + {{ov_privacy:…}} reference or says OpenViking replaced a secret with one: it + covers using saved credentials without reading them (`ov privacy run`), and + naming or rotating them. +version: 2026.11.1 --- # OpenViking Memory @@ -98,6 +101,56 @@ Do not invent other keys or commands for this: that file is the whole interface, - Skills stored in OpenViking (the `` list, `add_skill`, moving local skills in) are covered by the `openviking-skills` skill. +## Saved credentials + +OpenViking keeps the user's API keys and tokens in Privacy. A saved secret is +named by a reference such as +`{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}`: the +owner, then the field. It stands for a value you are not meant to read. + +- **Use it without reading it** — `ov privacy run` resolves references for one + local command and masks their values in its output. Pass a reference as an + environment variable with `--env NAME=REF` (repeatable), load `NAME=REF` + lines with `--env-file `, or put it inside an argument; the command + comes after `--`. Single-quote every reference in a shell command, because + `{{…}}` and `#` are otherwise open to shell interpretation: + + ```bash + ov privacy run --env GH_TOKEN='{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}' -- gh repo list + ``` + + To use the variable on the command line, wrap the command in `sh -c '…'`: + + ```bash + ov privacy run --env GH_TOKEN='' -- sh -c 'curl -H "Authorization: Bearer $GH_TOKEN" https://api.github.com/user' + ``` + + `$GH_TOKEN` written outside `sh -c '…'` is expanded by your own shell + before `ov` runs, and is empty. + + Prefer `--env`: with `OPENVIKING_PRIVACY_RUN_STRICT=1` references in arguments are refused. +- **Do not print values.** `privacy_resolve`, `ov privacy resolve`, + `ov privacy get` and `ov privacy version` print plain values; use them only + when the user asks to see a value. Do not print any part of a secret either + (a prefix, a suffix); to check a secret, print only its length. + `ov privacy run` masks only complete values in its output. +- **What exists** — `privacy_tree` lists targets, fields, their references and + descriptions, never values; on the CLI, `ov privacy tree --references` shows + the references and `ov privacy tree -o json` also the descriptions. The + description is how to tell similar credentials apart. `privacy_tree` leaves + the `auto` category out unless you ask for it with `category="auto"`; an + `auto/…` reference was created automatically and works like any other. +- **Naming and rotating** — only when the `privacy_upsert` tool's own + description says that a reference can be passed as the value: then a whole + reference as a value copies that field's current value, so the secret never + passes through you; prefer it. On the CLI, under the same condition: + `ov privacy upsert credential --field =''`. Use it + to save an automatic entry under a proper name in `credential`, or to + replace a value. The automatic entry is removed once saved, so use the + reference the upsert returns from then on. Give a short description of what + the credential is for: `description` on `privacy_upsert`, or `--labels-json + '{"description":"…"}'` on the CLI, which replaces all of the target's labels. + ## Beyond the MCP tools More advanced OpenViking operations are available through the `ov` CLI — diff --git a/examples/dsh-memory-plugin/package-lock.json b/examples/dsh-memory-plugin/package-lock.json index d8d4278aa4c..0ee03ab97a2 100644 --- a/examples/dsh-memory-plugin/package-lock.json +++ b/examples/dsh-memory-plugin/package-lock.json @@ -1,12 +1,12 @@ { "name": "@openviking/dsh-memory-plugin", - "version": "0.5.43", + "version": "0.5.44", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@openviking/dsh-memory-plugin", - "version": "0.5.43", + "version": "0.5.44", "license": "Apache-2.0", "devDependencies": { "@deepseek-ai/dsh-llm": "0.1.0-rc.6", diff --git a/examples/dsh-memory-plugin/package.json b/examples/dsh-memory-plugin/package.json index 0bbd908c2bd..9ddd3e75bec 100644 --- a/examples/dsh-memory-plugin/package.json +++ b/examples/dsh-memory-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@openviking/dsh-memory-plugin", - "version": "0.5.43", + "version": "0.5.44", "description": "OpenViking memory and context bundle for DeepSeek Harness", "icon": "./icon.svg", "type": "module", diff --git a/examples/dsh-memory-plugin/skills/openviking-memory/SKILL.md b/examples/dsh-memory-plugin/skills/openviking-memory/SKILL.md index 253a32e508c..2b9bb18320c 100644 --- a/examples/dsh-memory-plugin/skills/openviking-memory/SKILL.md +++ b/examples/dsh-memory-plugin/skills/openviking-memory/SKILL.md @@ -8,8 +8,11 @@ description: > context this session does not have — even if nobody says the word "memory". Also use it when the user asks where memories are stored: per project, per folder, or shared between repositories. Covers choosing between context search, find, list search, and grep, reading viking:// - URIs, and when (not) to write. -version: 2026.10.1 + URIs, and when (not) to write. Also use it when a message or file holds an + {{ov_privacy:…}} reference or says OpenViking replaced a secret with one: it + covers using saved credentials without reading them (`ov privacy run`), and + naming or rotating them. +version: 2026.11.1 --- # OpenViking Memory @@ -98,6 +101,56 @@ Do not invent other keys or commands for this: that file is the whole interface, - Skills stored in OpenViking (the `` list, `add_skill`, moving local skills in) are covered by the `openviking-skills` skill. +## Saved credentials + +OpenViking keeps the user's API keys and tokens in Privacy. A saved secret is +named by a reference such as +`{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}`: the +owner, then the field. It stands for a value you are not meant to read. + +- **Use it without reading it** — `ov privacy run` resolves references for one + local command and masks their values in its output. Pass a reference as an + environment variable with `--env NAME=REF` (repeatable), load `NAME=REF` + lines with `--env-file `, or put it inside an argument; the command + comes after `--`. Single-quote every reference in a shell command, because + `{{…}}` and `#` are otherwise open to shell interpretation: + + ```bash + ov privacy run --env GH_TOKEN='{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}' -- gh repo list + ``` + + To use the variable on the command line, wrap the command in `sh -c '…'`: + + ```bash + ov privacy run --env GH_TOKEN='' -- sh -c 'curl -H "Authorization: Bearer $GH_TOKEN" https://api.github.com/user' + ``` + + `$GH_TOKEN` written outside `sh -c '…'` is expanded by your own shell + before `ov` runs, and is empty. + + Prefer `--env`: with `OPENVIKING_PRIVACY_RUN_STRICT=1` references in arguments are refused. +- **Do not print values.** `privacy_resolve`, `ov privacy resolve`, + `ov privacy get` and `ov privacy version` print plain values; use them only + when the user asks to see a value. Do not print any part of a secret either + (a prefix, a suffix); to check a secret, print only its length. + `ov privacy run` masks only complete values in its output. +- **What exists** — `privacy_tree` lists targets, fields, their references and + descriptions, never values; on the CLI, `ov privacy tree --references` shows + the references and `ov privacy tree -o json` also the descriptions. The + description is how to tell similar credentials apart. `privacy_tree` leaves + the `auto` category out unless you ask for it with `category="auto"`; an + `auto/…` reference was created automatically and works like any other. +- **Naming and rotating** — only when the `privacy_upsert` tool's own + description says that a reference can be passed as the value: then a whole + reference as a value copies that field's current value, so the secret never + passes through you; prefer it. On the CLI, under the same condition: + `ov privacy upsert credential --field =''`. Use it + to save an automatic entry under a proper name in `credential`, or to + replace a value. The automatic entry is removed once saved, so use the + reference the upsert returns from then on. Give a short description of what + the credential is for: `description` on `privacy_upsert`, or `--labels-json + '{"description":"…"}'` on the CLI, which replaces all of the target's labels. + ## Beyond the MCP tools More advanced OpenViking operations are available through the `ov` CLI — diff --git a/examples/magpie-memory-plugin/README.md b/examples/magpie-memory-plugin/README.md index be8332dba35..312407feeac 100644 --- a/examples/magpie-memory-plugin/README.md +++ b/examples/magpie-memory-plugin/README.md @@ -25,7 +25,7 @@ The standalone `@openviking/magpie-models-plugin` is no longer packaged. For man See [Model management](models/README.md) for Root permissions, Bot detection, restart and recovery limits. Model management never enables Bot automatically. -Version 0.2.6 has not been published. Install from source below; after publication: +Version 0.2.7 has not been published. Install from source below; after publication: ```sh magpie plugin add @openviking/magpie-plugin diff --git a/examples/magpie-memory-plugin/README_CN.md b/examples/magpie-memory-plugin/README_CN.md index c0f0f881af0..f5590344be9 100644 --- a/examples/magpie-memory-plugin/README_CN.md +++ b/examples/magpie-memory-plugin/README_CN.md @@ -25,7 +25,7 @@ ## 安装 -统一版本 0.2.6 尚未发布;当前请按下文从源码安装。发布后可安装: +统一版本 0.2.7 尚未发布;当前请按下文从源码安装。发布后可安装: ```sh magpie plugin add @openviking/magpie-plugin diff --git a/examples/magpie-memory-plugin/package.json b/examples/magpie-memory-plugin/package.json index 11591ee19fd..0de97dad6c0 100644 --- a/examples/magpie-memory-plugin/package.json +++ b/examples/magpie-memory-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@openviking/magpie-plugin", - "version": "0.2.6", + "version": "0.2.7", "description": "OpenViking integration for Magpie: memory recall/capture and model switching with automatic restart.", "author": "OpenViking", "homepage": "https://github.com/volcengine/OpenViking/tree/main/examples/magpie-memory-plugin", diff --git a/examples/memory-plugin-shared/lib/config-schema.mjs b/examples/memory-plugin-shared/lib/config-schema.mjs index f55d0f70656..280d4bb22ea 100644 --- a/examples/memory-plugin-shared/lib/config-schema.mjs +++ b/examples/memory-plugin-shared/lib/config-schema.mjs @@ -188,6 +188,10 @@ export const KNOBS = [ capability: "session", }, { name: "skipSubagentSessions", type: "bool", default: false, env: "OPENVIKING_SKIP_SUBAGENT_SESSIONS", capability: "session" }, + // Plugin sealing; no workspace key, so a committed file cannot switch it off. + { name: "sealSecrets", type: "bool", default: false, env: "OPENVIKING_SEAL_SECRETS", capability: "session" }, + // With sealSecrets on, tool results are enrolled too. + { name: "enrollToolSecrets", type: "bool", default: false, env: "OPENVIKING_ENROLL_TOOL_SECRETS", capability: "session" }, { name: "repoContext", type: "bool", default: true, capability: "session" }, { name: "repoContextCacheTtlMs", type: "int", default: 60000, min: 1000, max: 3600000, capability: "session" }, diff --git a/examples/memory-plugin-shared/lib/seal-core.d.mts b/examples/memory-plugin-shared/lib/seal-core.d.mts new file mode 100644 index 00000000000..1b70d08650a --- /dev/null +++ b/examples/memory-plugin-shared/lib/seal-core.d.mts @@ -0,0 +1,71 @@ +export const SEAL_PATH: "/api/v1/privacy-configs/seal"; +export const RESOLVE_PATH: "/api/v1/privacy-configs/resolve"; +export const MAX_TEXTS: number; +export const BATCH_BYTES: number; +export const MAX_TEXT_BYTES: number; +export const MIN_LENGTH: number; +/** The session text, given to the model while sealing is on. */ +export const SESSION_TEXT: string; + +/** The one transport the core uses; rejects when no answer arrived. */ +export type SealPost = (path: string, body: unknown) => Promise<{ status: number; json: unknown }>; + +export type SealSpan = { start: number; end: number; reference: string; temporary: boolean }; + +export type SealedText = { + /** The text to use: the rewritten one, or the original when nothing was replaced. */ + text: string; + changed: boolean; + /** Distinct temporary references in this text, in order of first appearance. */ + temporary: string[]; + spans: SealSpan[]; +}; + +/** Why sealing cannot be done. */ +export type SealReason = "seal_failed" | "server_too_old" | "version_unknown"; + +export class SealError extends Error { + constructor(message: string, options?: { status?: number; reason?: SealReason }); + status?: number; + reason: SealReason; +} + +/** What the plugin knows of the server's support for sealing. */ +export type SealSupport = { supported: boolean; required?: string; actual?: string | null }; + +export type SealPolicy = { + /** The SealError of a server without the capability, or null; asked until it is null. */ + unavailable(): Promise; + /** `post` behind `unavailable()`: no call while the server cannot seal. */ + guard(post: SealPost): SealPost; +}; + +export function createSealPolicy(options?: { + check?: () => SealSupport | SealError | Promise; +}): SealPolicy; +export function whyNotSealed(error: unknown): string; +/** What the user can do about a SealError: upgrade or reach the server, or turn sealing off. */ +export function stopHint(error: unknown): string; + +export function sealTexts( + post: SealPost, + items: readonly { text: string; enroll?: boolean }[], +): Promise<{ texts: SealedText[]; temporary: string[] }>; + +export function sealValue( + post: SealPost, + value: T, + options?: { enroll?: boolean }, +): Promise<{ value: T; temporary: string[]; sealed: number }>; + +export function unsealValue( + post: SealPost, + value: T, + options?: { skip?: boolean }, +): Promise<{ value: T; replaced: number }>; + +export function sealNote(references: readonly string[]): string; +export function withheld(reason?: string): string; +export function isOpenVikingTool(name: unknown, ownNames?: readonly string[]): boolean; +export function containsOvPrivacy(text: unknown): boolean; +export function isCanonicalReference(text: unknown): boolean; diff --git a/examples/memory-plugin-shared/lib/seal-core.mjs b/examples/memory-plugin-shared/lib/seal-core.mjs new file mode 100644 index 00000000000..9bfdb07cca2 --- /dev/null +++ b/examples/memory-plugin-shared/lib/seal-core.mjs @@ -0,0 +1,521 @@ +/** + * Plugin-side sealing: the part every harness adapter shares. + * + * A harness plugin keeps registered secrets out of what the model sees and + * gives tools the real values. The OpenViking server does the matching + * (SEAL_PATH; see "Seal Texts" in docs/en/api/10-privacy.md) and turns a + * reference back into its value (RESOLVE_PATH); this module builds the + * requests, checks the answers and walks JSON-like values. Each adapter + * decides where to call it and what a failure does there. The exported API + * is typed in seal-core.d.mts. + * + * Pure ES module: no Node built-ins, no DOM, no global `fetch`, so it loads in + * Node and in the Claude Code mods runtime alike. All network access goes + * through the caller's `post(path, body) -> Promise<{ status, json }>`, where + * `json` is the server's `{ status: "ok", result }` envelope; `post` rejects + * when no answer arrived (`name` AbortError or TimeoutError, or `aborted: + * true`, reads as a timeout). Every failure is a SealError. + * + * Nothing here logs a text, a value or a response. + */ + +export const SEAL_PATH = "/api/v1/privacy-configs/seal"; +export const RESOLVE_PATH = "/api/v1/privacy-configs/resolve"; + +// The seal endpoint takes at most this many texts per call. +export const MAX_TEXTS = 1024; +// The endpoint allows 16 MiB of text per call; a request body through the +// Claude Code mods runtime may be 4 MiB, so a call carries about 3 MiB. +export const BATCH_BYTES = 3 * 1024 * 1024; +export const MAX_TEXT_BYTES = 16 * 1024 * 1024; +// Registered values are at least this long, so shorter strings cannot hold one. +export const MIN_LENGTH = 6; + +// The full canonical reference, in `credential` or `auto`. +const REFERENCE_SOURCE = + "\\{\\{ov_privacy:([^\\s:{}]+):viking:\\/\\/~\\/privacy\\/(?:credential|auto)\\/[^#\\s/{}]+#\\/values\\/[^{}\\s]+\\}\\}"; +const CANONICAL_REFERENCE = new RegExp(`^${REFERENCE_SOURCE}$`); +// A tool argument holding this command hands references to the OpenViking CLI as they are. +const OV_PRIVACY = /(?` as written: by then the model holds the + * reference privacy_upsert returned, and the temporary one no longer resolves. + */ +export function sealNote(references) { + const list = references.join(", "); + const first = references[0]; + return ( + `OpenViking stored a secret from the user's message and replaced it with a reference: ${list}. ` + + "You will not see the value. Unless it is clearly for one-off use, save it under a proper name now with privacy_upsert (or `ov privacy upsert`), " + + "passing the reference as the value and a short description of what it is for, " + + `for example category="credential", target_key="github", values={"token": "${first}"}, description="GitHub PAT for the acme org". ` + + "The temporary entry is removed once it is saved, so use the reference that privacy_upsert returns from then on. " + + "Write the reference as is wherever the secret is needed, for example " + + "`ov privacy run --env NAME='' -- sh -c ''`; " + + "do not resolve it to plain text or print any part of it. " + + "Tell the user what was stored and under which name." + ); +} + +/** What the model sees in place of a tool result that could not be sealed. */ +export function withheld(reason) { + const why = reason ? ` (${reason})` : ""; + return ( + `[OpenViking withheld this tool result: sealing secrets in it failed${why}. ` + + "The tool did run, but its output is not shown so that no secret reaches the model.]" + ); +} + +// ── when sealing cannot be done ───────────────────────────────────────── + +/** The SealError of a server without the capability, or null. */ +function unsupported(status) { + if (!status || status.supported === true) return null; + const required = status.required || "a newer version"; + if (!status.actual) { + return new SealError( + `the OpenViking server's version could not be read (its health check failed), and sealing secrets needs ${required} or newer`, + { reason: "version_unknown" }, + ); + } + return new SealError( + `the OpenViking server is version ${status.actual}, and sealing secrets needs ${required} or newer`, + { reason: "server_too_old" }, + ); +} + +export function whyNotSealed(error) { + const reason = error?.reason ?? "seal_failed"; + const message = error instanceof Error ? error.message : String(error ?? "unknown error"); + return reason === "seal_failed" ? `sealing secrets failed (${message})` : message; +} + +/** What the user can do about `error`; the stop messages end with this. */ +export function stopHint(error) { + const fix = + { + server_too_old: "Upgrade the OpenViking server", + version_unknown: "Make sure the OpenViking server is running and reachable", + setting_unknown: "Use Claude Code where the plugin can run its setting helper (the CLI)", + }[error?.reason] ?? "Try again once the OpenViking server answers"; + return ( + "With sealSecrets on, OpenViking sends nothing unsealed. " + + `${fix}, or turn sealing off with sealSecrets: false (OPENVIKING_SEAL_SECRETS=0).` + ); +} + +/** + * Whether the server can seal. `check()` answers `{ supported, required, + * actual }` for the server (`featureStatus("privacy_seal", version)`), or a + * SealError of its own. `unavailable()` resolves the SealError of a server + * that cannot seal (`server_too_old`, or `version_unknown` when the version + * could not be read) or null. Only "can seal" is kept: a no is asked again the + * next time, so sealing resumes once the server can. `guard(post)` is a `post` + * that asks `unavailable()` first and makes no call while it says no, so a + * pass that sends nothing does not ask the server at all. + */ +export function createSealPolicy({ check = async () => ({ supported: true }) } = {}) { + let known = null; + const policy = { + unavailable() { + const asked = (known ??= Promise.resolve() + .then(check) + .then( + (status) => (status instanceof SealError ? status : unsupported(status)), + () => unsupported({ supported: false }), + )); + asked.then((problem) => { + if (problem && known === asked) known = null; + }); + return asked; + }, + guard(post) { + return async (path, body) => { + const problem = await policy.unavailable(); + if (problem) throw problem; + return post(path, body); + }; + }, + }; + return policy; +} + +// ── sizes and code points ─────────────────────────────────────────────── + +function codePointLength(text) { + let n = 0; + for (const _ of text) n += 1; + return n; +} + +function utf8Size(text) { + let n = 0; + for (const ch of text) { + const c = ch.codePointAt(0); + n += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + return n; +} + +// ── talking to the server ─────────────────────────────────────────────── + +async function call(post, path, body) { + try { + return await post(path, body); + } catch (error) { + if (error instanceof SealError) throw error; + if (error?.name === "AbortError" || error?.name === "TimeoutError" || error?.aborted) { + throw new SealError("the OpenViking server did not answer in time"); + } + const message = error instanceof Error ? error.message : String(error ?? ""); + throw new SealError(`cannot reach the OpenViking server${message ? `: ${message}` : ""}`); + } +} + +function httpFailure(status, json, missing) { + if (status === 404 && missing) return new SealError(`HTTP 404: ${missing}`, { status }); + const message = json && typeof json === "object" ? json.error?.message : undefined; + return new SealError(`HTTP ${status}${typeof message === "string" && message ? `: ${message}` : ""}`, { status }); +} + +/** The `result` of an ok answer; throws on anything else. */ +function okResult(answer, missing) { + if (!answer || typeof answer !== "object") throw malformed("no answer"); + const { status, json } = answer; + if (!Number.isInteger(status)) throw malformed("no HTTP status"); + if (status < 200 || status >= 300) throw httpFailure(status, json, missing); + if (!json || typeof json !== "object" || json.status !== "ok") throw malformed("the answer is not ok"); + return json.result; +} + +// ── sealing ───────────────────────────────────────────────────────────── + +/** + * Check one `result.texts` item against its original text: offsets in range + * and in order, and a canonical reference on every span. The sealed text is + * built from the spans; the item's `text` is not read. An item with no spans + * is no change. + */ +function checkItem(item, original, index) { + const where = `texts[${index}]`; + if (item === null) return null; + if (typeof item !== "object" || Array.isArray(item)) throw malformed(`${where} is not an object or null`); + if (!Array.isArray(item.replaced)) throw malformed(`${where}.replaced is not a list`); + if (!item.replaced.length) return null; + + const chars = Array.from(original); + const length = chars.length; + const spans = []; + const parts = []; + let cursor = 0; + for (const span of item.replaced) { + if (!span || typeof span !== "object") throw malformed("a replacement is not an object"); + const { start, end, reference } = span; + if (!Number.isInteger(start) || !Number.isInteger(end) || start < cursor || end <= start || end > length) { + throw malformed("replacement offsets are out of order or out of range"); + } + if (!isCanonicalReference(reference)) throw malformed("a replacement has no canonical reference"); + parts.push(chars.slice(cursor, start).join(""), reference); + cursor = end; + spans.push({ start, end, reference, temporary: span.temporary === true }); + } + parts.push(chars.slice(cursor).join("")); + return { text: parts.join(""), spans }; +} + +async function sealBatch(post, batch) { + const answer = await call(post, SEAL_PATH, { texts: batch.map(({ text, enroll }) => ({ text, enroll })) }); + const result = okResult(answer, "the OpenViking server has no seal endpoint; it may be too old"); + if (!result || typeof result !== "object") throw malformed("no result"); + const { texts } = result; + if (!Array.isArray(texts) || texts.length !== batch.length) throw malformed("result.texts does not match the request"); + return texts.map((item, i) => checkItem(item, batch[i].text, i)); +} + +function batches(units) { + const out = []; + let batch = []; + let size = 0; + for (const unit of units) { + // The JSON-encoded size, which is what the request body carries. + const length = utf8Size(JSON.stringify(unit.text)) + 32; + if (batch.length && (batch.length === MAX_TEXTS || size + length > BATCH_BYTES)) { + out.push(batch); + batch = []; + size = 0; + } + batch.push(unit); + size += length; + } + if (batch.length) out.push(batch); + return out; +} + +function distinctTemporary(spans, into = []) { + for (const span of spans) { + if (span.temporary && !into.includes(span.reference)) into.push(span.reference); + } + return into; +} + +/** + * Seal `items` (`[{ text, enroll? }]`) and resolve `{ texts, temporary }`: + * `texts[i]` is `{ text, changed, temporary, spans }` for `items[i]`, where + * `text` is the text to use (the original when nothing was replaced), + * `temporary` its distinct temporary references in order of first + * appearance, and `spans` the checked replacements `{ start, end, reference, + * temporary }` (code point offsets into the original). The top-level + * `temporary` is the same over all texts, in input order. A duplicate text is + * sent once; the request is split at MAX_TEXTS texts or about BATCH_BYTES per + * call. + */ +export async function sealTexts(post, items) { + if (!Array.isArray(items)) throw new SealError("sealTexts needs a list of texts"); + const units = []; + const unitOf = new Map(); + const order = items.map((item) => { + const text = item?.text; + if (typeof text !== "string") throw new SealError("sealTexts needs a string text in every item"); + const enroll = item.enroll === true; + if (utf8Size(text) > MAX_TEXT_BYTES) throw new SealError("a text is larger than the seal endpoint accepts"); + const key = `${enroll ? 1 : 0}\u0000${text}`; + if (!unitOf.has(key)) { + unitOf.set(key, units.length); + units.push({ text, enroll }); + } + return unitOf.get(key); + }); + if (!units.length) return { texts: [], temporary: [] }; + + const results = []; + for (const batch of batches(units)) results.push(...(await sealBatch(post, batch))); + + const temporary = []; + const texts = order.map((index) => { + const item = results[index]; + if (!item) return { text: units[index].text, changed: false, temporary: [], spans: [] }; + distinctTemporary(item.spans, temporary); + return { text: item.text, changed: true, temporary: distinctTemporary(item.spans), spans: item.spans }; + }); + return { texts, temporary }; +} + +// ── walking JSON-like values ──────────────────────────────────────────── + +function isPlainObject(node) { + if (!node || typeof node !== "object") return false; + const proto = Object.getPrototypeOf(node); + return proto === Object.prototype || proto === null; +} + +function eachString(node, visit, key) { + if (typeof node === "string") { + visit(node, key); + } else if (Array.isArray(node)) { + for (const item of node) eachString(item, visit); + } else if (isPlainObject(node)) { + for (const name of Object.keys(node)) eachString(node[name], visit, name); + } +} + +/** `node` with `edit(text, key)` applied to every string leaf; the same object where nothing changed. */ +function mapStrings(node, edit, key) { + if (typeof node === "string") return edit(node, key); + if (Array.isArray(node)) { + const items = node.map((item) => mapStrings(item, edit)); + return items.every((item, i) => item === node[i]) ? node : items; + } + if (isPlainObject(node)) { + let out = null; + for (const key of Object.keys(node)) { + const next = mapStrings(node[key], edit, key); + if (next !== node[key]) { + out ??= Object.assign(Object.getPrototypeOf(node) === null ? Object.create(null) : {}, node); + out[key] = next; + } + } + return out ?? node; + } + return node; +} + +// File content such as an image is not text a secret is typed into, and can +// be megabytes: a data: URI anywhere, and a long base64 run under the keys +// file content goes in (`data`, `file_data`), the gateway's rule. A long run +// under any other key may be a secret itself (a session token) and is sealed. +const BASE64 = /^[A-Za-z0-9+/=_-]{256,}$/; + +function isEncodedData(text, key) { + if (text.startsWith("data:") && text.slice(0, 256).includes(",")) return true; + return (key === "data" || key === "file_data") && BASE64.test(text); +} + +function isSealableLeaf(text, key) { + return codePointLength(text) >= MIN_LENGTH && !isEncodedData(text, key); +} + +/** + * Seal every string leaf of a JSON-like value (arrays and plain objects; + * object keys are never touched), all leaves in one sealTexts, and resolve + * `{ value, temporary, sealed }`. Strings of fewer than MIN_LENGTH code points + * are left as they are, and so is encoded file content (isEncodedData). Parts + * with nothing replaced keep their identity; nothing replaced at + * all returns the input itself. `sealed` counts the string leaves rewritten. + */ +export async function sealValue(post, value, { enroll = false } = {}) { + const leaves = []; + eachString(value, (text, key) => { + if (isSealableLeaf(text, key)) leaves.push(text); + }); + const unique = [...new Set(leaves)]; + if (!unique.length) return { value, temporary: [], sealed: 0 }; + + const { texts } = await sealTexts(post, unique.map((text) => ({ text, enroll: enroll === true }))); + const byText = new Map(unique.map((text, i) => [text, texts[i]])); + const temporary = []; + for (const text of leaves) distinctTemporary(byText.get(text).spans, temporary); + let sealed = 0; + const rewritten = mapStrings(value, (text, key) => { + const result = isSealableLeaf(text, key) && byText.get(text); + if (!result?.changed) return text; + sealed += 1; + return result.text; + }); + return { value: rewritten, temporary, sealed }; +} + +// ── unsealing ─────────────────────────────────────────────────────────── + +function referencesIn(text) { + if (containsOvPrivacy(text)) return []; + return [...text.matchAll(new RegExp(REFERENCE_SOURCE, "g"))]; +} + +// 404 (unknown) and 403 (another user's reference) leave the reference as it is. +async function resolveOne(post, reference) { + let result; + try { + const answer = await call(post, RESOLVE_PATH, { selector: reference }); + if (answer && typeof answer === "object" && (answer.status === 404 || answer.status === 403)) { + return null; + } + result = okResult(answer); + } catch (error) { + if (error instanceof SealError && error.reason !== "seal_failed") throw error; + throw new SealError(`could not resolve a secret reference: ${error.message}`, { status: error.status }); + } + const value = result && typeof result === "object" ? result.value : undefined; + return typeof value === "string" && value ? value : null; +} + +/** + * Every whole canonical reference in a string leaf is replaced + * by its value once the resolve endpoint returned one and sealing that value + * alone gives back exactly one span over all of it with the same reference; + * resolve `{ value, replaced }`. A string that contains an `ov privacy` + * invocation is left untouched as a whole. `skip: true` (the arguments of an + * OpenViking or agent-spawning tool) returns the value as it is without a + * request. Each reference is resolved at most once per call; `replaced` + * counts the occurrences rewritten. + */ +export async function unsealValue(post, value, { skip = false } = {}) { + if (skip) return { value, replaced: 0 }; + const found = new Set(); + eachString(value, (text) => { + for (const match of referencesIn(text)) found.add(match[0]); + }); + if (!found.size) return { value, replaced: 0 }; + + const references = [...found]; + const resolved = new Map(); + for (const reference of references) resolved.set(reference, await resolveOne(post, reference)); + + // Only a value that seals back to its own reference: the next turn must + // show the model the reference it wrote. + const candidates = [...new Set([...resolved.values()].filter(Boolean))]; + const values = new Map(); + if (candidates.length) { + let checked; + try { + ({ texts: checked } = await sealTexts(post, candidates.map((text) => ({ text, enroll: false })))); + } catch (error) { + if (error instanceof SealError && error.reason !== "seal_failed") throw error; + throw new SealError(`could not confirm a secret reference: ${error.message}`, { status: error.status }); + } + const byValue = new Map(candidates.map((text, i) => [text, checked[i]])); + for (const [reference, plain] of resolved) { + if (!plain) continue; + const { spans } = byValue.get(plain); + const exact = + spans.length === 1 && + spans[0].start === 0 && + spans[0].end === codePointLength(plain) && + spans[0].reference === reference; + if (exact) values.set(reference, plain); + } + } + if (!values.size) return { value, replaced: 0 }; + + let replaced = 0; + const rewritten = mapStrings(value, (text) => { + const matches = referencesIn(text).filter((match) => values.has(match[0])); + if (!matches.length) return text; + let out = ""; + let cursor = 0; + for (const match of matches) { + out += text.slice(cursor, match.index) + values.get(match[0]); + cursor = match.index + match[0].length; + } + replaced += matches.length; + return out + text.slice(cursor); + }); + return { value: rewritten, replaced }; +} diff --git a/examples/memory-plugin-shared/lib/server-features.d.mts b/examples/memory-plugin-shared/lib/server-features.d.mts index 78ea90ee331..a161e1120c6 100644 --- a/examples/memory-plugin-shared/lib/server-features.d.mts +++ b/examples/memory-plugin-shared/lib/server-features.d.mts @@ -1,4 +1,4 @@ -export type ServerFeature = "working_memory_opt_in"; +export type ServerFeature = "working_memory_opt_in" | "privacy_seal"; export const SERVER_FEATURES: Readonly>; diff --git a/examples/memory-plugin-shared/lib/server-features.json b/examples/memory-plugin-shared/lib/server-features.json index e0e3ee0f192..20d8f22f7bf 100644 --- a/examples/memory-plugin-shared/lib/server-features.json +++ b/examples/memory-plugin-shared/lib/server-features.json @@ -1,3 +1,4 @@ { - "working_memory_opt_in": "0.5.0" + "working_memory_opt_in": "0.5.0", + "privacy_seal": "0.5.7" } diff --git a/examples/memory-plugin-shared/lib/uri-guard.mjs b/examples/memory-plugin-shared/lib/uri-guard.mjs index 31324dadd69..f6a4e05041e 100644 --- a/examples/memory-plugin-shared/lib/uri-guard.mjs +++ b/examples/memory-plugin-shared/lib/uri-guard.mjs @@ -46,9 +46,16 @@ export function findVikingUri(args = {}, keys = DEFAULT_URI_KEYS, contentKeys = return findVikingUriInValue(args, new Set(contentKeys)); } +// A privacy reference, {{ov_privacy::viking://~/privacy/...#/values/}}, +// names a sealed value and is meant to sit in a command line (`ov privacy run +// --env TOKEN='{{ov_privacy:...}}' -- ...`). Its viking:// URI is not a path, so +// the sweep blanks each reference out before it looks; a bare URI in the same +// string is still found. +const PRIVACY_REFERENCE_RE = /\{\{ov_privacy:[^\s{}]*\}\}/gi; + export function findVikingUriInValue(value, skipKeys) { if (typeof value === "string") { - const match = value.match(/\bviking:\/\/[^\s"'`<>)]*/i); + const match = value.replace(PRIVACY_REFERENCE_RE, " ").match(/\bviking:\/\/[^\s"'`<>)]*/i); return match?.[0] || null; } if (Array.isArray(value)) { diff --git a/examples/memory-plugin-shared/seal-core.test.mjs b/examples/memory-plugin-shared/seal-core.test.mjs new file mode 100644 index 00000000000..f9f4c691ddb --- /dev/null +++ b/examples/memory-plugin-shared/seal-core.test.mjs @@ -0,0 +1,572 @@ +import assert from "node:assert/strict"; +import { existsSync, readFileSync } from "node:fs"; +import test from "node:test"; + +import { + BATCH_BYTES, + MAX_TEXTS, + RESOLVE_PATH, + SEAL_PATH, + SESSION_TEXT, + SealError, + containsOvPrivacy, + createSealPolicy, + stopHint, + whyNotSealed, + isCanonicalReference, + isOpenVikingTool, + sealNote, + sealTexts, + sealValue, + unsealValue, + withheld, +} from "./lib/seal-core.mjs"; + +const ref = (target, category = "credential", owner = "alice") => + `{{ov_privacy:${owner}:viking://~/privacy/${category}/${target}#/values/token}}`; +const GH = "ghp_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const GH_REF = ref("github"); +const NEW = "sk-new-secret-1234567890"; +const NEW_REF = ref("openai-k3j2", "auto"); + +/** + * A fake server: `vault` maps value -> reference (auto references are + * temporary); `enrollable` values join the vault when sent with enroll. + * Records every call. `override(path, body, calls)` may return an answer. + */ +function fakeServer({ vault = {}, enrollable = {}, override } = {}) { + const calls = []; + const known = new Map(Object.entries(vault)); + const post = async (path, body) => { + calls.push({ path, body: structuredClone(body) }); + const forced = override?.(path, body, calls); + if (forced !== undefined) return typeof forced === "function" ? forced() : forced; + if (path === RESOLVE_PATH) { + for (const [value, reference] of known) { + if (reference === body.selector) return { status: 200, json: { status: "ok", result: { value } } }; + } + return { status: 404, json: { status: "error", error: { message: "not found" } } }; + } + assert.equal(path, SEAL_PATH); + const texts = body.texts.map(({ text, enroll }) => { + if (enroll) { + for (const [value, reference] of Object.entries(enrollable)) { + if (text.includes(value) && !known.has(value)) known.set(value, reference); + } + } + return sealOne(text, known); + }); + return { status: 200, json: { status: "ok", result: { revision: "r1", texts } } }; + }; + return { post, calls, known }; +} + +function sealOne(text, known) { + const hits = []; + for (const [value, reference] of known) { + let at = text.indexOf(value); + while (at >= 0) { + hits.push({ at, value, reference }); + at = text.indexOf(value, at + value.length); + } + } + if (!hits.length) return null; + hits.sort((a, b) => a.at - b.at); + let out = ""; + let cursor = 0; + const replaced = []; + for (const { at, value, reference } of hits) { + const start = Array.from(text.slice(0, at)).length; + replaced.push({ + start, + end: start + Array.from(value).length, + reference, + created: false, + temporary: reference.includes("/privacy/auto/"), + }); + out += text.slice(cursor, at) + reference; + cursor = at + value.length; + } + return { text: out + text.slice(cursor), replaced }; +} + +const answer = (texts) => ({ status: 200, json: { status: "ok", result: { revision: "r1", texts } } }); + +async function sealError(promise, pattern) { + await assert.rejects(promise, (error) => { + assert.ok(error instanceof SealError, `expected SealError, got ${error}`); + if (pattern) assert.match(error.message, pattern); + return true; + }); +} + +// ── sealTexts ─────────────────────────────────────────────────────────── + +test("sealTexts returns each text to use with its temporary references", async () => { + const { post, calls } = fakeServer({ vault: { [GH]: GH_REF }, enrollable: { [NEW]: NEW_REF } }); + const result = await sealTexts(post, [ + { text: `🔑 ${GH} and ${NEW} and ${NEW}`, enroll: true }, + { text: "nothing here" }, + { text: `again ${GH}` }, + ]); + assert.deepEqual(calls[0].body, { + texts: [ + { text: `🔑 ${GH} and ${NEW} and ${NEW}`, enroll: true }, + { text: "nothing here", enroll: false }, + { text: `again ${GH}`, enroll: false }, + ], + }); + assert.deepEqual(result.texts.map((t) => [t.text, t.changed, t.temporary]), [ + [`🔑 ${GH_REF} and ${NEW_REF} and ${NEW_REF}`, true, [NEW_REF]], + ["nothing here", false, []], + [`again ${GH_REF}`, true, []], + ]); + assert.deepEqual(result.temporary, [NEW_REF]); + // Code points: the emoji is one. + assert.deepEqual(result.texts[0].spans[0], { start: 2, end: 2 + GH.length, reference: GH_REF, temporary: false }); +}); + +test("sealTexts sends no request for no texts, and a duplicate once", async () => { + const { post, calls } = fakeServer(); + assert.deepEqual(await sealTexts(post, []), { texts: [], temporary: [] }); + assert.equal(calls.length, 0); + const result = await sealTexts(post, [{ text: "same text" }, { text: "same text" }, { text: "same text", enroll: true }]); + assert.equal(calls[0].body.texts.length, 2); + assert.equal(result.texts.length, 3); +}); + +test("sealTexts splits at 1024 texts and at the byte budget", async () => { + const { post, calls } = fakeServer({ vault: { [GH]: GH_REF } }); + const items = Array.from({ length: MAX_TEXTS * 2 + 5 }, (_, i) => ({ text: `text ${i} ${GH}` })); + const result = await sealTexts(post, items); + assert.deepEqual(calls.map((c) => c.body.texts.length), [MAX_TEXTS, MAX_TEXTS, 5]); + assert.equal(result.texts[2050].text, `text 2050 ${GH_REF}`); + + calls.length = 0; + const big = "x".repeat(Math.floor(BATCH_BYTES / 2.5)); + await sealTexts(post, [{ text: `a${big}` }, { text: `b${big}` }, { text: `c${big}` }, { text: "small one" }]); + assert.deepEqual(calls.map((c) => c.body.texts.length), [2, 2]); + // A text larger than the budget goes alone. + calls.length = 0; + const huge = "y".repeat(BATCH_BYTES + 10); + await sealTexts(post, [{ text: "before it" }, { text: huge }, { text: "after it" }]); + assert.deepEqual(calls.map((c) => c.body.texts.map((t) => t.text.length)), [[9], [huge.length], [8]]); + await sealError(sealTexts(post, [{ text: "z".repeat(16 * 1024 * 1024 + 1) }]), /larger than/); +}); + +test("transport failures, timeouts and non-ok answers are a SealError", async () => { + const cases = [ + [async () => { throw new Error("connect ECONNREFUSED"); }, /cannot reach the OpenViking server: connect ECONNREFUSED/], + [async () => { throw Object.assign(new Error("x"), { name: "AbortError" }); }, /did not answer in time/], + [async () => { throw Object.assign(new Error("x"), { name: "TimeoutError" }); }, /did not answer in time/], + [async () => { throw Object.assign(new Error("x"), { aborted: true }); }, /did not answer in time/], + [async () => ({ status: 404, json: { detail: "Not Found" } }), /HTTP 404: .*too old/], + [async () => ({ status: 413, json: { status: "error", error: { message: "too large" } } }), /HTTP 413: too large/], + [async () => ({ status: 500, json: null }), /^HTTP 500$/], + [async () => ({ status: 200, json: { status: "error", result: {} } }), /not ok/], + [async () => ({ status: 200, json: "nonsense" }), /not ok/], + [async () => null, /no answer/], + [async () => ({ json: {} }), /no HTTP status/], + ]; + for (const [post, pattern] of cases) await sealError(sealTexts(post, [{ text: `key ${GH}` }]), pattern); + await sealError(sealTexts(async () => answer([null]), [{ text: 7 }]), /string text/); + // A status on HTTP failures, for adapters that care. + await assert.rejects(sealTexts(async () => ({ status: 503, json: {} }), [{ text: "x" }]), { status: 503 }); +}); + +// One good answer for `key GH`, with its item or first span changed. +const TEXT = `key ${GH}`; +const GOOD_ITEM = sealOne(TEXT, new Map([[GH, GH_REF]])); +function withSpan(change) { + const span = { ...GOOD_ITEM.replaced[0], ...change }; + for (const [key, value] of Object.entries(change)) if (value === undefined) delete span[key]; + const text = typeof span.reference === "string" ? GOOD_ITEM.text.replace(GH_REF, span.reference) : GOOD_ITEM.text; + return answer([{ text, replaced: [span] }]); +} + +test("a span needs offsets in order and in range and a canonical reference", async () => { + assert.equal((await sealTexts(async () => answer([GOOD_ITEM]), [{ text: TEXT }])).texts[0].text, GOOD_ITEM.text); + const result = (texts) => ({ status: 200, json: { status: "ok", result: { revision: "r1", texts } } }); + const cases = [ + [{ status: 200, json: { status: "ok" } }, /no result/], + [result([]), /does not match the request/], + [result([null, null]), /does not match the request/], + [result("x"), /does not match the request/], + [answer(["x"]), /not an object or null/], + [answer([[]]), /not an object or null/], + [answer([{ ...GOOD_ITEM, replaced: "x" }]), /replaced is not a list/], + [answer([{ ...GOOD_ITEM, replaced: [null] }]), /not an object/], + [withSpan({ end: 999 }), /out of order or out of range/], + [withSpan({ start: 5, end: 5 }), /out of order or out of range/], + [withSpan({ start: 1.5 }), /out of order or out of range/], + [withSpan({ start: -1 }), /out of order or out of range/], + ]; + // Two spans out of order. + const twice = `${GH} ${GH}`; + const two = sealOne(twice, new Map([[GH, GH_REF]])); + cases.push([answer([{ ...two, replaced: [two.replaced[1], two.replaced[0]] }]), /out of order/]); + for (const reference of [ + "[redacted]", + "{{ov_privacy:x}}", + ref("github", "contact"), + ref("github", "credentials"), + ref("github", "autox"), + "{{ov_privacy:alice:viking://~/privacy/auto#/values/token}}", + "{{ov_privacy:alice:viking://user/alice/privacy/credential/github#/values/token}}", + "{{ov_privacy:alice:viking://~/privacy/credential/github}}", + "{{ov_privacy:alice:viking://~/privacy/credential/#/values/token}}", + "{{ov_privacy:alice:viking://~/privacy/credential/github#/values/}}", + "{{ov_privacy:al ice:viking://~/privacy/credential/github#/values/token}}", + "{{ov_privacy:alice:viking://~/privacy/credential/a/b#/values/token}}", + "{{ ov_privacy:alice:viking://~/privacy/credential/github#/values/token }}", + `${GH_REF}}}`, + ]) { + cases.push([withSpan({ reference }), /no canonical reference/]); + } + for (const [reply, pattern] of cases) { + await sealError(sealTexts(async () => reply, [{ text: TEXT }]), pattern); + } + // The text is built from the spans, and no spans is no change. + const built = await sealTexts(async () => answer([{ ...GOOD_ITEM, text: 7 }]), [{ text: TEXT }]); + assert.equal(built.texts[0].text, GOOD_ITEM.text); + const none = await sealTexts(async () => answer([{ ...GOOD_ITEM, replaced: [] }]), [{ text: TEXT }]); + assert.equal(none.texts[0].changed, false); +}); + +test("the canonical reference pattern takes credential and auto only", () => { + assert.equal(isCanonicalReference(GH_REF), true); + assert.equal(isCanonicalReference(NEW_REF), true); + assert.equal(isCanonicalReference(` ${GH_REF}`), false); + assert.equal(isCanonicalReference(ref("x", "contact")), false); + assert.equal(isCanonicalReference(null), false); +}); + +// ── sealValue ─────────────────────────────────────────────────────────── + +test("sealValue seals every string leaf in one call, not keys or short strings", async () => { + const { post, calls } = fakeServer({ vault: { [GH]: GH_REF }, enrollable: { [NEW]: NEW_REF } }); + const untouched = { deep: ["plain text", 42, null, true] }; + const value = { + [GH]: "key is a secret", + content: [{ type: "text", text: `out ${GH}` }, { type: "text", text: `new ${NEW}` }], + untouched, + short: "ghp_1", + again: `out ${GH}`, + nested: { list: [[`x ${NEW}`]] }, + }; + const before = structuredClone(value); + const result = await sealValue(post, value, { enroll: true }); + assert.equal(calls.length, 1); + // Distinct leaves of 6 code points or more, all enrollable. + assert.deepEqual( + calls[0].body.texts, + ["key is a secret", `out ${GH}`, `new ${NEW}`, "plain text", `x ${NEW}`].map((text) => ({ text, enroll: true })), + ); + assert.deepEqual(result.value, { + [GH]: "key is a secret", + content: [{ type: "text", text: `out ${GH_REF}` }, { type: "text", text: `new ${NEW_REF}` }], + untouched, + short: "ghp_1", + again: `out ${GH_REF}`, + nested: { list: [[`x ${NEW_REF}`]] }, + }); + assert.equal(result.sealed, 4); + assert.deepEqual(result.temporary, [NEW_REF]); + // The input is not modified; unchanged parts keep their identity. + assert.deepEqual(value, before); + assert.equal(result.value.untouched, untouched); +}); + +test("sealValue: nothing to seal returns the input itself; enroll defaults to false", async () => { + const { post, calls } = fakeServer({ enrollable: { [NEW]: NEW_REF } }); + const value = { a: ["short", 1], b: `text with ${NEW}` }; + const result = await sealValue(post, value); + assert.equal(result.value, value); + assert.deepEqual(result.temporary, []); + assert.equal(result.sealed, 0); + assert.equal(calls[0].body.texts[0].enroll, false); + + calls.length = 0; + const bare = await sealValue(post, "tiny"); + assert.equal(bare.value, "tiny"); + assert.equal(calls.length, 0); + assert.deepEqual((await sealValue(post, `${NEW}`, { enroll: true })).value, NEW_REF); +}); + +test("sealValue leaves data: URIs and long base64 runs out", async () => { + const { post, calls } = fakeServer({ vault: { [GH]: GH_REF } }); + const image = "iVBORw0KGgo" + "A".repeat(300) + "+/="; + const uri = `data:image/png;base64,${image}${GH}`; + const almost = "A".repeat(255); + const spaced = `${"A".repeat(300)} ${GH}`; + const value = { data: image, uri, almost, spaced, plain: `out ${GH}` }; + const result = await sealValue(post, value); + assert.deepEqual( + calls[0].body.texts.map(({ text }) => text), + [almost, spaced, `out ${GH}`], + ); + assert.equal(result.value.data, image); + assert.equal(result.value.uri, uri); + assert.equal(result.value.spaced, `${"A".repeat(300)} ${GH_REF}`); + + calls.length = 0; + assert.equal((await sealValue(post, { data: image, uri })).sealed, 0); + assert.equal(calls.length, 0); + + // Image blocks of both shapes keep their data; file_data too. + const blocks = [ + { type: "image", source: { type: "base64", media_type: "image/png", data: image } }, + { type: "image", data: image, mimeType: "image/png" }, + { type: "file", file: { file_data: image } }, + ]; + assert.equal((await sealValue(post, blocks)).value, blocks); + assert.ok(calls.every(({ body }) => body.texts.every(({ text }) => text !== image))); +}); + +test("sealValue seals a long base64 run that is not under data or file_data", async () => { + const token = "FwoGZXIvYXdzE" + "B".repeat(300); + const { post, calls } = fakeServer({ vault: { [token]: GH_REF } }); + const value = { content: [{ type: "text", text: token }], data: token, structured: { token } }; + const result = await sealValue(post, value); + assert.deepEqual(calls[0].body.texts, [{ text: token, enroll: false }]); + assert.deepEqual(result.value, { content: [{ type: "text", text: GH_REF }], data: token, structured: { token: GH_REF } }); + assert.equal(result.sealed, 2); + assert.equal((await sealValue(post, token)).value, GH_REF); +}); + +test("sealValue fails as a whole", async () => { + await sealError(sealValue(async () => ({ status: 500, json: {} }), { a: `x ${GH}` }), /HTTP 500/); +}); + +// ── unsealValue ───────────────────────────────────────────────────────── + +test("unsealValue puts values in place of whole references and reuses each resolution", async () => { + const { post, calls } = fakeServer({ vault: { [GH]: GH_REF, [NEW]: NEW_REF } }); + const keep = { list: ["no reference here"] }; + const value = { + command: `curl -H "Authorization: token ${GH_REF}" && echo ${GH_REF}`, + env: { KEY: NEW_REF }, + keep, + [GH_REF]: "keys are left alone", + }; + const result = await unsealValue(post, value); + assert.deepEqual(result.value, { + command: `curl -H "Authorization: token ${GH}" && echo ${GH}`, + env: { KEY: NEW }, + keep, + [GH_REF]: "keys are left alone", + }); + assert.equal(result.replaced, 3); + assert.equal(result.value.keep, keep); + // One resolve per reference, then one seal call for the round trip. + assert.deepEqual(calls.map((c) => c.path), [RESOLVE_PATH, RESOLVE_PATH, SEAL_PATH]); + assert.deepEqual(calls.slice(0, 2).map((c) => c.body), [{ selector: GH_REF }, { selector: NEW_REF }]); + assert.deepEqual(calls[2].body, { texts: [{ text: GH, enroll: false }, { text: NEW, enroll: false }] }); + assert.match(value.command, /ov_privacy/, "the input is not modified"); +}); + +test("unsealValue: no reference means no request", async () => { + const { post, calls } = fakeServer(); + const value = { a: "plain", b: ["{{ov_privacy:not-a-reference}}"] }; + assert.deepEqual(await unsealValue(post, value), { value, replaced: 0 }); + assert.equal(calls.length, 0); +}); + +test("unsealValue: a 404 leaves the reference as it is", async () => { + const { post } = fakeServer({ vault: { [GH]: GH_REF } }); + const missing = ref("gone"); + const result = await unsealValue(post, { a: `${missing} ${GH_REF}` }); + assert.deepEqual(result, { value: { a: `${missing} ${GH}` }, replaced: 1 }); +}); + +test("unsealValue: a value that does not seal back to exactly its reference is left", async () => { + const other = ref("other"); + const cases = [ + // Seals to another reference. + (text) => ({ text: other, replaced: [{ start: 0, end: Array.from(text).length, reference: other, created: false, temporary: false }] }), + // Not sealed at all (never_mask, too short). + () => null, + // One span, but not over the whole value. + (text) => ({ text: `${text.slice(0, 2)}${GH_REF}`, replaced: [{ start: 2, end: Array.from(text).length, reference: GH_REF, created: false, temporary: false }] }), + ]; + for (const item of cases) { + const { post } = fakeServer({ + vault: { [GH]: GH_REF }, + override: (path, body) => (path === SEAL_PATH ? answer(body.texts.map(({ text }) => item(text))) : undefined), + }); + const value = { a: `use ${GH_REF}` }; + assert.deepEqual(await unsealValue(post, value), { value, replaced: 0 }); + } +}); + +test("unsealValue: a string with an `ov privacy` command is left untouched as a whole", async () => { + const { post, calls } = fakeServer({ vault: { [GH]: GH_REF } }); + const value = { + command: `ov privacy run --env T='${GH_REF}' -- sh -c 'gh auth status'`, + other: `echo ${GH_REF}`, + }; + const result = await unsealValue(post, value); + assert.equal(result.value.command, value.command); + assert.equal(result.value.other, `echo ${GH}`); + assert.equal(result.replaced, 1); + assert.equal(calls.filter((c) => c.path === RESOLVE_PATH).length, 1); + // Only the command itself: not a word that merely ends in "ov". + for (const text of ["ov privacy upsert", "x; ov privacy tree", "/usr/bin/ov privacy run"]) { + assert.equal(containsOvPrivacy(text), true, text); + } + for (const text of ["gov privacy", "my-ov privacy", "ovprivacy", "ov privacyx", "ov private"]) { + assert.equal(containsOvPrivacy(text), false, text); + } +}); + +test("unsealValue: skip returns the arguments as written without a request", async () => { + const { post, calls } = fakeServer({ vault: { [GH]: GH_REF } }); + const value = { prompt: `use ${GH_REF}` }; + assert.deepEqual(await unsealValue(post, value, { skip: true }), { value, replaced: 0 }); + assert.equal(calls.length, 0); +}); + +test("unsealValue: a 403 (another user's reference) leaves it as it is", async () => { + const bob = ref("github", "credential", "bob"); + const { post } = fakeServer({ + vault: { [GH]: GH_REF }, + override: (path, body) => + path === RESOLVE_PATH && body.selector === bob + ? { status: 403, json: { status: "error", error: { message: "belongs to user bob" } } } + : undefined, + }); + assert.deepEqual(await unsealValue(post, { a: `${bob} ${GH_REF}` }), { value: { a: `${bob} ${GH}` }, replaced: 1 }); +}); + +test("unsealValue: transport and server errors are a failure", async () => { + const cases = [ + [() => { throw new Error("ECONNRESET"); }, RESOLVE_PATH, /could not resolve.*cannot reach the OpenViking server: ECONNRESET/], + [() => ({ status: 500, json: {} }), RESOLVE_PATH, /could not resolve a secret reference: HTTP 500/], + [() => ({ status: 200, json: { status: "error" } }), RESOLVE_PATH, /could not resolve/], + [() => ({ status: 500, json: {} }), SEAL_PATH, /could not confirm a secret reference: HTTP 500/], + [() => answer([]), SEAL_PATH, /could not confirm.*does not match the request/], + ]; + for (const [reply, at, pattern] of cases) { + const { post } = fakeServer({ vault: { [GH]: GH_REF }, override: (path) => (path === at ? reply : undefined) }); + await sealError(unsealValue(post, { a: GH_REF }), pattern); + } + // A resolved value that is empty or not a string leaves the reference. + for (const result of [{ value: "" }, { value: 7 }, {}]) { + const { post } = fakeServer({ override: (path) => (path === RESOLVE_PATH ? { status: 200, json: { status: "ok", result } } : undefined) }); + assert.deepEqual(await unsealValue(post, { a: GH_REF }), { value: { a: GH_REF }, replaced: 0 }); + } +}); + +test("seal and unseal round-trip", async () => { + const { post } = fakeServer({ vault: { [GH]: GH_REF } }); + const sealed = await sealValue(post, { output: `token=${GH}` }); + assert.deepEqual(sealed.value, { output: `token=${GH_REF}` }); + const unsealed = await unsealValue(post, sealed.value); + assert.deepEqual(unsealed.value, { output: `token=${GH}` }); +}); + +// ── texts and names ───────────────────────────────────────────────────── + +// The note's wording, pinned word for word. +const NOTE_TEMPLATE = + "OpenViking stored a secret from the user's message and replaced it with a reference: [, …]. You will not see the value. Unless it is clearly for one-off use, save it under a proper name now with privacy_upsert (or `ov privacy upsert`), passing the reference as the value and a short description of what it is for, for example category=\"credential\", target_key=\"github\", values={\"token\": \"\"}, description=\"GitHub PAT for the acme org\". The temporary entry is removed once it is saved, so use the reference that privacy_upsert returns from then on. Write the reference as is wherever the secret is needed, for example `ov privacy run --env NAME='' -- sh -c ''`; do not resolve it to plain text or print any part of it. Tell the user what was stored and under which name."; + +test("the note is the pinned wording with the references filled in", () => { + const second = ref("aws-x1", "auto"); + assert.equal( + sealNote([NEW_REF, second]), + NOTE_TEMPLATE + .replace("[, …]", `${NEW_REF}, ${second}`) + .replace('"token": ""', `"token": "${NEW_REF}"`), + ); + // The run example keeps the literal placeholders. + assert.match(sealNote([NEW_REF]), /--env NAME='' -- sh -c ''/); +}); + +test("the withheld text says why and shows nothing of the result", () => { + const text = withheld("HTTP 503"); + assert.match(text, /^\[OpenViking withheld this tool result: sealing secrets in it failed \(HTTP 503\)\./); + assert.match(text, /no secret reaches the model/); + assert.doesNotMatch(withheld(), /\(\)/); +}); + +test("OpenViking's own tools are recognised by name", () => { + for (const name of ["mcp__plugin_openviking-memory_openviking__read", "OpenViking_search", "openviking"]) { + assert.equal(isOpenVikingTool(name), true, name); + } + for (const name of ["Bash", "Agent", "mcp__github__get", undefined, null, 3]) { + assert.equal(isOpenVikingTool(name), false, String(name)); + } + assert.equal(isOpenVikingTool("memory_recall", ["memory_recall"]), true); + assert.equal(isOpenVikingTool("memory_recall"), false); +}); + +test("the session text is the gateway's SESSION_NOTE without its leading dash", (t) => { + const source = new URL("../../openviking_gateway/sealing.py", import.meta.url); + if (!existsSync(source)) return t.skip("the gateway source is not next to the examples"); + const block = readFileSync(source, "utf8").match(/^SESSION_NOTE = \(\n([\s\S]*?)\n\)/m); + assert.ok(block, "SESSION_NOTE not found"); + const note = [...block[1].matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => JSON.parse(`"${m[1]}"`)).join(""); + assert.ok(note.startsWith("- ")); + assert.equal(SESSION_TEXT, note.slice(2)); +}); + +// ── when sealing cannot be done ───────────────────────────────────────── + +test("the policy makes no call while the server cannot seal, and keeps only a yes", async () => { + let asked = 0; + let actual = "0.5.6"; + const server = fakeServer({ vault: { [GH]: GH_REF } }); + const policy = createSealPolicy({ + check: () => { + asked += 1; + return { supported: actual !== "0.5.6", required: "0.5.7", actual }; + }, + }); + const send = policy.guard(server.post); + await sealError(sealTexts(send, [{ text: `token ${GH}` }]), /version 0\.5\.6, and sealing secrets needs 0\.5\.7 or newer/); + await assert.rejects(unsealValue(send, { command: `echo ${GH_REF}` }), (error) => error.reason === "server_too_old"); + assert.equal(asked, 2); + assert.deepEqual(server.calls, []); + // The server was upgraded: asked once more, then not again. + actual = "0.5.7"; + assert.equal((await sealTexts(send, [{ text: `token ${GH}` }])).texts[0].text, `token ${GH_REF}`); + await sealTexts(send, [{ text: `again ${GH}` }]); + assert.equal(asked, 3); + // Nothing to send: not even the support is needed. + const fresh = createSealPolicy({ check: () => { throw new Error("must not be asked"); } }); + assert.deepEqual(await sealValue(fresh.guard(server.post), { n: 1, s: "abc" }), { value: { n: 1, s: "abc" }, temporary: [], sealed: 0 }); +}); + +test("the policy: an unreadable version, a check that throws, a supported server", async () => { + const unknown = await createSealPolicy({ check: () => ({ supported: false, required: "0.5.7", actual: null }) }).unavailable(); + assert.equal(unknown.reason, "version_unknown"); + assert.match(unknown.message, /version could not be read .* needs 0\.5\.7 or newer/); + assert.equal((await createSealPolicy({ check: () => { throw new Error("x"); } }).unavailable()).reason, "version_unknown"); + const own = new SealError("the setting could not be read"); + assert.equal(await createSealPolicy({ check: () => own }).unavailable(), own); + const server = fakeServer({ vault: { [GH]: GH_REF } }); + const ok = createSealPolicy({ check: async () => ({ supported: true, required: "0.5.7", actual: "0.5.7.dev44" }) }); + assert.equal(await ok.unavailable(), null); + const { texts } = await sealTexts(ok.guard(server.post), [{ text: `token ${GH}` }]); + assert.equal(texts[0].text, `token ${GH_REF}`); +}); + +test("the stop hint says what to do for each reason", () => { + assert.equal(whyNotSealed("the seal hook timed out"), "sealing secrets failed (the seal hook timed out)"); + assert.match(stopHint(new SealError("x", { reason: "server_too_old" })), /^With sealSecrets on, OpenViking sends nothing unsealed\. Upgrade the OpenViking server, or turn sealing off with sealSecrets: false \(OPENVIKING_SEAL_SECRETS=0\)\.$/); + assert.match(stopHint(new SealError("x", { reason: "version_unknown" })), /running and reachable/); + assert.match(stopHint(new SealError("x", { reason: "setting_unknown" })), /Use Claude Code where the plugin can run its setting helper/); + assert.match(stopHint(new SealError("HTTP 500: boom", { status: 500 })), /Try again once the OpenViking server answers/); +}); + +test("unsealValue keeps the reason of a server that cannot seal", async () => { + const server = fakeServer({ vault: { [GH]: GH_REF } }); + const policy = createSealPolicy({ check: () => ({ supported: false, required: "0.5.7", actual: null }) }); + await assert.rejects(unsealValue(policy.guard(server.post), { command: `echo ${GH_REF}` }), (error) => { + assert.equal(error.reason, "version_unknown"); + return true; + }); + const failing = fakeServer({ override: () => ({ status: 500, json: { status: "error", error: { message: "x" } } }) }); + await assert.rejects(unsealValue(failing.post, { command: `echo ${GH_REF}` }), (error) => error.reason === "seal_failed"); +}); diff --git a/examples/memory-plugin-shared/uri-guard.test.mjs b/examples/memory-plugin-shared/uri-guard.test.mjs index 51a0cb802b4..eb540930bd3 100644 --- a/examples/memory-plugin-shared/uri-guard.test.mjs +++ b/examples/memory-plugin-shared/uri-guard.test.mjs @@ -71,6 +71,23 @@ test("a shell command that carries a viking:// URI gets a notice, never a deny", assert.equal(evaluateUriNotice("Bash", { command: "cat /tmp/a.md" }), null) }) +test("a viking:// URI inside an {{ov_privacy:...}} reference is not a path", () => { + const ref = "{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}" + const command = `ov privacy run --env TOKEN='${ref}' -- sh -c 'gh api user'` + assert.equal(findVikingUri({ command }), null) + assert.equal(evaluateUriNotice("Bash", { command }), null) + assert.equal(evaluateUriNotice("shell", { command: ["ov", "privacy", "run", "--env", `TOKEN=${ref}`] }), null) + assert.deepEqual(preToolUseOutput({ tool_name: "Bash", tool_input: { command } }), {}) + // A file tool sees the same sweep. + assert.equal(evaluateUriGuard("Read", { file_path: "/tmp/a.md", note: ref }), null) + + // A bare URI next to a reference still gets the notice, for the bare one. + const mixed = `ov privacy run --env TOKEN='${ref}' -- sh -c 'cat viking://resources/a.md'` + assert.equal(evaluateUriNotice("Bash", { command: mixed })?.uri, "viking://resources/a.md") + assert.equal(evaluateUriNotice("Bash", { command: `cat viking://resources/a.md ${ref}` })?.uri, "viking://resources/a.md") + assert.equal(evaluateUriGuard("Write", { file_path: "viking://resources/a.md", note: ref })?.uri, "viking://resources/a.md") +}) + test("PowerShell tools are shell tools for a host that maps them, and unguarded otherwise", () => { const input = { command: "Get-Content viking://resources/a.md" } // The shape dsh passes for its Windows `pwsh` tool. diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.json index 1bbbbed603b..5c0f0737d6f 100644 --- a/examples/opencode-plugin/package.json +++ b/examples/opencode-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@openviking/opencode-plugin", - "version": "0.5.33", + "version": "0.5.34", "author": "@openviking", "description": "Unified OpenCode plugin for OpenViking repository retrieval and long-term memory", "type": "module", diff --git a/examples/opencode-plugin/skills/openviking-memory/SKILL.md b/examples/opencode-plugin/skills/openviking-memory/SKILL.md index 253a32e508c..2b9bb18320c 100644 --- a/examples/opencode-plugin/skills/openviking-memory/SKILL.md +++ b/examples/opencode-plugin/skills/openviking-memory/SKILL.md @@ -8,8 +8,11 @@ description: > context this session does not have — even if nobody says the word "memory". Also use it when the user asks where memories are stored: per project, per folder, or shared between repositories. Covers choosing between context search, find, list search, and grep, reading viking:// - URIs, and when (not) to write. -version: 2026.10.1 + URIs, and when (not) to write. Also use it when a message or file holds an + {{ov_privacy:…}} reference or says OpenViking replaced a secret with one: it + covers using saved credentials without reading them (`ov privacy run`), and + naming or rotating them. +version: 2026.11.1 --- # OpenViking Memory @@ -98,6 +101,56 @@ Do not invent other keys or commands for this: that file is the whole interface, - Skills stored in OpenViking (the `` list, `add_skill`, moving local skills in) are covered by the `openviking-skills` skill. +## Saved credentials + +OpenViking keeps the user's API keys and tokens in Privacy. A saved secret is +named by a reference such as +`{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}`: the +owner, then the field. It stands for a value you are not meant to read. + +- **Use it without reading it** — `ov privacy run` resolves references for one + local command and masks their values in its output. Pass a reference as an + environment variable with `--env NAME=REF` (repeatable), load `NAME=REF` + lines with `--env-file `, or put it inside an argument; the command + comes after `--`. Single-quote every reference in a shell command, because + `{{…}}` and `#` are otherwise open to shell interpretation: + + ```bash + ov privacy run --env GH_TOKEN='{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}' -- gh repo list + ``` + + To use the variable on the command line, wrap the command in `sh -c '…'`: + + ```bash + ov privacy run --env GH_TOKEN='' -- sh -c 'curl -H "Authorization: Bearer $GH_TOKEN" https://api.github.com/user' + ``` + + `$GH_TOKEN` written outside `sh -c '…'` is expanded by your own shell + before `ov` runs, and is empty. + + Prefer `--env`: with `OPENVIKING_PRIVACY_RUN_STRICT=1` references in arguments are refused. +- **Do not print values.** `privacy_resolve`, `ov privacy resolve`, + `ov privacy get` and `ov privacy version` print plain values; use them only + when the user asks to see a value. Do not print any part of a secret either + (a prefix, a suffix); to check a secret, print only its length. + `ov privacy run` masks only complete values in its output. +- **What exists** — `privacy_tree` lists targets, fields, their references and + descriptions, never values; on the CLI, `ov privacy tree --references` shows + the references and `ov privacy tree -o json` also the descriptions. The + description is how to tell similar credentials apart. `privacy_tree` leaves + the `auto` category out unless you ask for it with `category="auto"`; an + `auto/…` reference was created automatically and works like any other. +- **Naming and rotating** — only when the `privacy_upsert` tool's own + description says that a reference can be passed as the value: then a whole + reference as a value copies that field's current value, so the secret never + passes through you; prefer it. On the CLI, under the same condition: + `ov privacy upsert credential --field =''`. Use it + to save an automatic entry under a proper name in `credential`, or to + replace a value. The automatic entry is removed once saved, so use the + reference the upsert returns from then on. Give a short description of what + the credential is for: `description` on `privacy_upsert`, or `--labels-json + '{"description":"…"}'` on the CLI, which replaces all of the target's labels. + ## Beyond the MCP tools More advanced OpenViking operations are available through the `ov` CLI — diff --git a/examples/pi-coding-agent-extension/README.md b/examples/pi-coding-agent-extension/README.md index 6dfd2eaf124..372de43f517 100644 --- a/examples/pi-coding-agent-extension/README.md +++ b/examples/pi-coding-agent-extension/README.md @@ -242,6 +242,27 @@ The profile block is built at session start and added to pi's system prompt on e Bypass now runs through the same matcher every other OpenViking harness uses, so the patterns are real globs: `*` stops at a path separator and `**` crosses them. A bare path used to match its subdirectories as a prefix, and no longer does — write `"/tmp/scratch**"` where `"/tmp/scratch"` used to be enough. +### Secret sealing + +| Field | Default | Description | +|--------------------------|------------|--------------------------------------------------------------------------| +| `sealSecrets` | `false` | Keep secrets the OpenViking server knows out of what the model sees, and give tools the real values. Env: `OPENVIKING_SEAL_SECRETS` | +| `enrollToolSecrets` | `false` | With `sealSecrets` on, also store new secrets found in tool results (not only in what you type). Env: `OPENVIKING_ENROLL_TOOL_SECRETS` | + +None has a workspace key, so a repository's committed `.openviking/config.json` cannot turn them off; set them in `ovcli.conf`'s `plugin.pi` (or `plugin`) section or through the environment. Sealing needs OpenViking server 0.5.7 or newer (a development build such as `0.5.7.dev44` counts as 0.5.7): on the first hook that needs it, the extension reads the server's version from `/health` once for the session and compares it with the feature table it ships (`shared/server-features.json`). + +With `sealSecrets` on, the extension calls the server at three points: + +- **What you type** (`input`): registered secrets are replaced with their references (`{{ov_privacy:…}}`), and tokens the server's detector recognises are stored under `viking://~/privacy/auto/…` and replaced too. pi stores and sends the sealed text. When a new secret was stored this way, the model gets a note for that turn telling it to save the secret under a proper name. Empty input is left alone; text starting with `/` is sealed as well, because everything that reaches `input` (skill and template arguments included) goes to the model. When sealing cannot be done, the message is not sent and you are told why. +- **Tool results** (`tool_result`): every text block, the persisted `details` and `structuredContent` are sealed (with `enroll` only when `enrollToolSecrets` is on); images are left as they are. When sealing cannot be done, the result is replaced with a short "withheld" text and marked as an error, so the model never sees the original. +- **Tool arguments** (`tool_call`): a reference the model wrote is replaced with the real value for the tool that runs, after the server resolved it and a round trip through the seal endpoint gave the same reference back. pi keeps what the model wrote in the session. OpenViking's own tools (`openviking_*`), agent-spawning tools (`subagent`, `agent`) and any string containing an `ov privacy` command get the references as written. A reference the server does not know is left as it is; any other failure blocks the call with a reason. + +Sealing cannot be done when the server is older than 0.5.7, its `/health` fails (the version is unknown), or a seal or resolve call fails (unreachable, an error, a bad answer, a timeout). Each of these stops at the points above. The message pi shows names the reason (for a version, the required and the actual one) and what to do: upgrade or reach the server, or turn `sealSecrets` off. To a server that is too old or whose version is unknown, no seal or resolve call is made at all. The version is read again for the next message, so sealing resumes once the server can seal. + +The model is also told, in the system prompt of every turn, how references work. The session file holds references, not the values. + +Not covered, because it reaches the model without passing these events: the system prompt and context files (`AGENTS.md`), the text of skills and prompt templates (`/skill:…`, `/template` expand after `input`), recall blocks injected from OpenViking, compaction and branch summaries pi asks the model for, and history written before sealing was turned on. A bypassed directory does no sealing either. A tool this extension did not register counts as OpenViking's only when its name contains `openviking`, so an OpenViking MCP server bridged in under another name gets the values in place of the references in its arguments. + ## Architecture ``` @@ -276,8 +297,11 @@ When the model calls `openviking_session_history` without `session`, the extensi | Pi Event | Extension Action | |------------------------|----------------------------------------------------------------------------------| | `session_start` | Health check → derive OV session → build profile context → restore takeover state | -| `before_agent_start` | Idempotent startup for `pi -c` + queue the current prompt for recall | +| `input` | With `sealSecrets`: seal the typed text; stop it when sealing fails | +| `before_agent_start` | Idempotent startup for `pi -c` + queue the current prompt for recall; with `sealSecrets`, add the sealing paragraph and the turn's enrollment note | | `context` | Run current-prompt recall after UI rendering, then inject takeover and recall context | +| `tool_call` | URI guard, then with `sealSecrets`: put the real values in for references | +| `tool_result` | With `sealSecrets`: seal the result (or withhold it), then the viking:// notice | | `turn_end` | Extract branch entries → write or pending-queue OV messages → maybe advance boundary | | `session_before_compact`| Takeover mode returns OV overview as pi compaction summary; otherwise commits pending messages | | `session_shutdown` | Persist takeover state or final non-takeover commit | @@ -409,6 +433,7 @@ pi-coding-agent-extension/ ├── lib/mcp-result.mjs # pi content conversion and output limit ├── lib/takeover-core.mjs # Pure context-takeover state machine ├── lib/recall-ledger.mjs # Injected recall blocks, replayed to keep prompt caches warm +├── lib/seal-adapter.mjs # Secret sealing on input, tool_call and tool_result (shared/seal-core.mjs) ├── index.ts # Extension entry point (event handlers + /viking command) ├── scripts/ov-memory-doctor.mjs # Client-side doctor (install, config, connection) ├── skills/ # generated by memory-plugin-shared/sync.mjs diff --git a/examples/pi-coding-agent-extension/index.ts b/examples/pi-coding-agent-extension/index.ts index ef8ebc2b10e..a8d5c4f0d0a 100644 --- a/examples/pi-coding-agent-extension/index.ts +++ b/examples/pi-coding-agent-extension/index.ts @@ -27,6 +27,8 @@ import { createMcpBridge, DEFAULT_HANDSHAKE_BUDGET_MS } from "./lib/mcp-bridge.m import { registerMcpTools, TOOL_NAME_PREFIX } from "./tools.js"; import { createTakeoverManager } from "./takeover.js"; import { HANDLER_BUDGET_MS, describeSkip } from "./lib/takeover-core.mjs"; +import { createSealHandlers, createSealPost } from "./lib/seal-adapter.mjs"; +import { featureStatus, healthVersion } from "./shared/server-features.mjs"; /** This extension's directory, published for the experimental fork's probe. */ const EXTENSION_DIR = dirname(fileURLToPath(import.meta.url)); @@ -86,6 +88,24 @@ export default async function (pi: ExtensionAPI) { }) : null; + // Plugin-side sealing (`sealSecrets`). Whether the server supports it is read + // from its own /health on the first hook that needs it, and again while it + // cannot seal. When sealing + // cannot be done the traffic is stopped. A bypassed directory does not touch + // OpenViking at all, sealing included. + const seal = (config as any).sealSecrets === true && !isBypassed(config, { cwd }) + ? createSealHandlers({ + post: createSealPost((path, init, options) => client.fetchJSON(path, init, options)), + enrollToolSecrets: (config as any).enrollToolSecrets === true, + check: async () => featureStatus( + "privacy_seal", + await healthVersion((path, init, options) => client.fetchJSON(path, init, options)), + ), + ownToolNames: () => toolNames, + tell: tellUser, + }) + : null; + // Session state let connected = false; let bypassed = false; @@ -328,6 +348,13 @@ export default async function (pi: ExtensionAPI) { }; }); + // --- sealing: input, and the session text and note of each run --- + // After the handler above, so the session text follows the profile block. + if (seal) { + pi.on("input", async (event, ctx) => seal.onInput(event, ctx)); + pi.on("before_agent_start", async (event, _ctx) => seal.onBeforeAgentStart(event)); + } + // --- context --- pi.on("context", async (event, ctx) => { if (!connected || bypassed) return; @@ -391,13 +418,19 @@ export default async function (pi: ExtensionAPI) { }); // --- tool_call --- + // The URI guard first, so it judges what the model wrote; then sealing puts + // the real values in for the references, in place. pi.on("tool_call", async (event, _ctx) => { const decision = guardVikingUriToolCall(event); if (!decision) return; return decision; }); + if (seal) pi.on("tool_call", async (event, _ctx) => seal.onToolCall(event)); // --- tool_result --- + // Sealing first, so the notice below is added to the sealed result and is + // kept even when the result had to be withheld. + if (seal) pi.on("tool_result", async (event, _ctx) => seal.onToolResult(event)); pi.on("tool_result", async (event, _ctx) => { const notice = noticeVikingUriToolResult(event); if (!notice) return; @@ -599,6 +632,18 @@ async function fetchArchiveOverview( } } +/** + * Reach the user when sealing stops something. A notification in the TUI, + * stderr in print and JSON modes, where pi's notifications do nothing. + */ +function tellUser(ctx: any, message: string): void { + if (ctx?.hasUI) { + ctx.ui.notify(message, "error"); + return; + } + process.stderr.write(`${message}\n`); +} + /** * The extra line for a failed handshake that a root key explains. * diff --git a/examples/pi-coding-agent-extension/lib/seal-adapter.d.mts b/examples/pi-coding-agent-extension/lib/seal-adapter.d.mts new file mode 100644 index 00000000000..ba778ef05a7 --- /dev/null +++ b/examples/pi-coding-agent-extension/lib/seal-adapter.d.mts @@ -0,0 +1,24 @@ +import type { SealPost, SealSupport } from "../shared/seal-core.mjs"; + +export const SEAL_NOTE_TYPE: "openviking-seal-note"; +export const AGENT_TOOLS: Set; +export const SEAL_SESSION_TEXT: string; + +export function createSealPost( + fetchJSON: (path: string, init?: RequestInit, options?: { timeoutMs?: number }) => Promise, + options?: { timeoutMs?: number }, +): SealPost; + +export function createSealHandlers(options: { + post: SealPost; + enrollToolSecrets?: boolean; + /** Whether the server supports sealing; asked until it does. Unset: assumed supported. */ + check?: () => SealSupport | Promise; + ownToolNames?: () => readonly string[]; + tell?: (ctx: any, message: string) => void; +}): { + onInput(event: any, ctx: any): Promise<{ action: "continue" } | { action: "transform"; text: string; images?: any[] } | { action: "handled" }>; + onBeforeAgentStart(event: any): Promise<{ systemPrompt: string; message?: { customType: string; content: string; display: boolean } }>; + onToolCall(event: any): Promise<{ block: true; reason: string } | undefined>; + onToolResult(event: any): Promise<{ content?: any[]; details?: unknown; structuredContent?: unknown; isError?: boolean } | undefined>; +}; diff --git a/examples/pi-coding-agent-extension/lib/seal-adapter.mjs b/examples/pi-coding-agent-extension/lib/seal-adapter.mjs new file mode 100644 index 00000000000..dc500367903 --- /dev/null +++ b/examples/pi-coding-agent-extension/lib/seal-adapter.mjs @@ -0,0 +1,204 @@ +/** + * Plugin-side sealing for pi (`sealSecrets`, `enrollToolSecrets`). + * + * The shared core (`shared/seal-core.mjs`) talks to the server and checks its + * answers; this file decides where pi calls it and what happens there when + * sealing cannot be done: the server is too old for it or its + * version cannot be read (asked before any seal call), or a call failed. + * Then what it was about is stopped: + * + * - `input`: the user's text is sealed with `enroll: true` before pi stores it + * or sends it. A turn whose text got a temporary reference gets the note + * through `before_agent_start`. On failure the input is stopped and the user + * is told why; a throwing `input` handler would let the text through, so + * everything is caught here. + * - `tool_call`: references the model wrote are resolved in `event.input`, in + * place. pi hands extensions a copy of the arguments, so the transcript keeps + * what the model wrote. A failure blocks the call with a reason. + * - `tool_result`: the text content, `details` (persisted) and + * `structuredContent` are sealed. On failure they are replaced with the + * withheld text and the result is marked as an error; a throwing + * `tool_result` handler would let the original through, so this one does not + * throw. + * - `before_agent_start`: the session text. + * + * Nothing here logs a text, a value or a server answer. + */ +import { + createSealPolicy, + sealTexts, + sealValue, + sealNote, + unsealValue, + stopHint, + withheld, + whyNotSealed, + isOpenVikingTool, + SESSION_TEXT, +} from "../shared/seal-core.mjs"; + +/** The custom message type that carries the note of a turn. */ +export const SEAL_NOTE_TYPE = "openviking-seal-note"; + +/** + * Tools that hand their arguments to another model. Pi has none built in; its + * example subagent extension registers `subagent`. Unsealing there would send + * the plain value to a model, so their arguments keep the references. + */ +export const AGENT_TOOLS = new Set(["subagent", "agent"]); + +/** What the model is told for the whole session while sealing is on: the core's text. */ +export const SEAL_SESSION_TEXT = SESSION_TEXT; + +/** Seal and resolve calls can carry megabytes; give them more than a health check. */ +const SEAL_TIMEOUT_MS = 30000; + +/** + * The core's `post` over the extension's OpenViking client. + * + * `fetchJSON` (`shared/ov-http.mjs`) never throws: status 0 means no answer + * arrived, which the core needs as a rejection (a timeout marked as one). Any + * other answer is handed back as the server's envelope. + */ +export function createSealPost(fetchJSON, { timeoutMs = SEAL_TIMEOUT_MS } = {}) { + return async (path, body) => { + const res = await fetchJSON(path, { method: "POST", body: JSON.stringify(body) }, { timeoutMs }); + if (!res || !res.status) { + const error = new Error(res?.error?.message || "no answer"); + if (res?.error?.aborted || res?.error?.name === "AbortError") { + error.name = "AbortError"; + error.aborted = true; + } + throw error; + } + const json = res.ok ? { status: "ok", result: res.result } : { status: "error", error: res.error }; + return { status: res.status, json }; + }; +} + +function reasonOf(error) { + return error instanceof Error && error.message ? error.message : String(error || "unknown error"); +} + +function stoppedInput(error) { + return `OpenViking: your message was not sent, because ${whyNotSealed(error)}. ${stopHint(error)}`; +} + +/** + * The four handlers, for `index.ts` to register in the order the other + * handlers on the same events need. + * + * `ownToolNames()` lists the tools this extension registered (they count as + * OpenViking tools). `tell(ctx, message)` reaches the user: a notification in + * the TUI, stderr where pi has no UI. `check()` answers whether the server + * supports sealing (`featureStatus("privacy_seal", version)` of + * `shared/server-features.mjs`); a yes is kept for the pi session, a no is + * asked again. + */ +export function createSealHandlers({ + post, + enrollToolSecrets = false, + check, + ownToolNames = () => [], + tell = () => {}, +}) { + // The note owed to the run that the last sealed input starts. + let pending = null; + // Every seal and resolve call: none while the server cannot seal. + const send = createSealPolicy({ check }).guard(post); + + async function onInput(event, ctx) { + const text = typeof event?.text === "string" ? event.text : ""; + // Empty input passes untouched. Text starting with "/" is sealed too: pi + // runs extension commands before `input`, so whatever reaches it here + // (`/skill:…` and template arguments, or plain text) goes to the model. + if (!text.trim()) return { action: "continue" }; + try { + const { texts } = await sealTexts(send, [{ text, enroll: true }]); + const sealed = texts[0]; + pending = null; + if (!sealed.changed) return { action: "continue" }; + let out = sealed.text; + if (sealed.temporary.length) { + const note = sealNote(sealed.temporary); + // A message queued into a running turn never reaches + // before_agent_start, so its note travels with it. + if (event.streamingBehavior) out = `${out}\n\n${note}`; + else pending = { references: sealed.temporary, note }; + } + return { action: "transform", text: out, images: event.images }; + } catch (error) { + pending = null; + try { + tell(ctx, stoppedInput(error)); + } catch { + // A throw here would let the unsealed text through; the input stays stopped. + } + return { action: "handled" }; + } + } + + async function onBeforeAgentStart(event) { + const result = { systemPrompt: `${event.systemPrompt}\n\n${SEAL_SESSION_TEXT}` }; + const owed = pending; + pending = null; + // pi expands `/skill:…` and templates after `input`, so the prompt here may + // differ from the sealed text; it still holds the run's references. + const prompt = String(event.prompt ?? ""); + if (owed && event.messageType !== "custom" && owed.references.some((reference) => prompt.includes(reference))) { + result.message = { customType: SEAL_NOTE_TYPE, content: owed.note, display: false }; + } + return result; + } + + async function onToolCall(event) { + const name = event?.toolName; + const input = event?.input; + if (!input || typeof input !== "object") return; + const skip = isOpenVikingTool(name, ownToolNames()) || AGENT_TOOLS.has(name); + if (skip) return; + try { + const { value, replaced } = await unsealValue(send, input); + // pi runs the tool with this very object; the transcript holds its own copy. + if (replaced) Object.assign(input, value); + return; + } catch (error) { + return { + block: true, + reason: `OpenViking could not put the secret values in for the references in this call: ${reasonOf(error)}. ` + + `The tool did not run. ${stopHint(error)}`, + }; + } + } + + async function onToolResult(event) { + const content = Array.isArray(event?.content) ? event.content : []; + // Images are not text and stay as they are; only text blocks are sealed. + const texts = content.map((block) => (block?.type === "text" && typeof block.text === "string" ? block.text : null)); + const whole = { texts, details: event?.details ?? null, structured: event?.structuredContent ?? null }; + try { + const { value, sealed } = await sealValue(send, whole, { enroll: enrollToolSecrets === true }); + if (!sealed) return; + const patch = {}; + if (value.texts !== whole.texts) { + patch.content = content.map((block, i) => + value.texts[i] !== texts[i] ? { ...block, text: value.texts[i] } : block, + ); + // Replacing content drops structuredContent unless it comes back too. + if (event.structuredContent !== undefined) patch.structuredContent = value.structured; + } + if (value.details !== whole.details) patch.details = value.details; + if (value.structured !== whole.structured) patch.structuredContent = value.structured; + return patch; + } catch (error) { + return { + content: [{ type: "text", text: withheld(reasonOf(error)) }], + // pi ignores an undefined patch field, so an empty object clears them. + details: {}, + isError: true, + }; + } + } + + return { onInput, onBeforeAgentStart, onToolCall, onToolResult }; +} diff --git a/examples/pi-coding-agent-extension/package-lock.json b/examples/pi-coding-agent-extension/package-lock.json index 4969c0ab5eb..dcf78ef8668 100644 --- a/examples/pi-coding-agent-extension/package-lock.json +++ b/examples/pi-coding-agent-extension/package-lock.json @@ -1,12 +1,12 @@ { "name": "openviking-pi-extension", - "version": "0.4.35", + "version": "0.4.36", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "openviking-pi-extension", - "version": "0.4.35", + "version": "0.4.36", "dependencies": { "@modelcontextprotocol/client": "2.0.0" }, diff --git a/examples/pi-coding-agent-extension/package.json b/examples/pi-coding-agent-extension/package.json index 109501af175..67a7200e536 100644 --- a/examples/pi-coding-agent-extension/package.json +++ b/examples/pi-coding-agent-extension/package.json @@ -1,6 +1,6 @@ { "name": "openviking-pi-extension", - "version": "0.4.35", + "version": "0.4.36", "description": "OpenViking memory and context extension for the pi coding agent", "private": true, "type": "module", diff --git a/examples/pi-coding-agent-extension/skills/openviking-memory/SKILL.md b/examples/pi-coding-agent-extension/skills/openviking-memory/SKILL.md index 253a32e508c..2b9bb18320c 100644 --- a/examples/pi-coding-agent-extension/skills/openviking-memory/SKILL.md +++ b/examples/pi-coding-agent-extension/skills/openviking-memory/SKILL.md @@ -8,8 +8,11 @@ description: > context this session does not have — even if nobody says the word "memory". Also use it when the user asks where memories are stored: per project, per folder, or shared between repositories. Covers choosing between context search, find, list search, and grep, reading viking:// - URIs, and when (not) to write. -version: 2026.10.1 + URIs, and when (not) to write. Also use it when a message or file holds an + {{ov_privacy:…}} reference or says OpenViking replaced a secret with one: it + covers using saved credentials without reading them (`ov privacy run`), and + naming or rotating them. +version: 2026.11.1 --- # OpenViking Memory @@ -98,6 +101,56 @@ Do not invent other keys or commands for this: that file is the whole interface, - Skills stored in OpenViking (the `` list, `add_skill`, moving local skills in) are covered by the `openviking-skills` skill. +## Saved credentials + +OpenViking keeps the user's API keys and tokens in Privacy. A saved secret is +named by a reference such as +`{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}`: the +owner, then the field. It stands for a value you are not meant to read. + +- **Use it without reading it** — `ov privacy run` resolves references for one + local command and masks their values in its output. Pass a reference as an + environment variable with `--env NAME=REF` (repeatable), load `NAME=REF` + lines with `--env-file `, or put it inside an argument; the command + comes after `--`. Single-quote every reference in a shell command, because + `{{…}}` and `#` are otherwise open to shell interpretation: + + ```bash + ov privacy run --env GH_TOKEN='{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}' -- gh repo list + ``` + + To use the variable on the command line, wrap the command in `sh -c '…'`: + + ```bash + ov privacy run --env GH_TOKEN='' -- sh -c 'curl -H "Authorization: Bearer $GH_TOKEN" https://api.github.com/user' + ``` + + `$GH_TOKEN` written outside `sh -c '…'` is expanded by your own shell + before `ov` runs, and is empty. + + Prefer `--env`: with `OPENVIKING_PRIVACY_RUN_STRICT=1` references in arguments are refused. +- **Do not print values.** `privacy_resolve`, `ov privacy resolve`, + `ov privacy get` and `ov privacy version` print plain values; use them only + when the user asks to see a value. Do not print any part of a secret either + (a prefix, a suffix); to check a secret, print only its length. + `ov privacy run` masks only complete values in its output. +- **What exists** — `privacy_tree` lists targets, fields, their references and + descriptions, never values; on the CLI, `ov privacy tree --references` shows + the references and `ov privacy tree -o json` also the descriptions. The + description is how to tell similar credentials apart. `privacy_tree` leaves + the `auto` category out unless you ask for it with `category="auto"`; an + `auto/…` reference was created automatically and works like any other. +- **Naming and rotating** — only when the `privacy_upsert` tool's own + description says that a reference can be passed as the value: then a whole + reference as a value copies that field's current value, so the secret never + passes through you; prefer it. On the CLI, under the same condition: + `ov privacy upsert credential --field =''`. Use it + to save an automatic entry under a proper name in `credential`, or to + replace a value. The automatic entry is removed once saved, so use the + reference the upsert returns from then on. Give a short description of what + the credential is for: `description` on `privacy_upsert`, or `--labels-json + '{"description":"…"}'` on the CLI, which replaces all of the target's labels. + ## Beyond the MCP tools More advanced OpenViking operations are available through the `ov` CLI — diff --git a/examples/pi-coding-agent-extension/tests/seal-adapter.test.mjs b/examples/pi-coding-agent-extension/tests/seal-adapter.test.mjs new file mode 100644 index 00000000000..73d59ab1299 --- /dev/null +++ b/examples/pi-coding-agent-extension/tests/seal-adapter.test.mjs @@ -0,0 +1,280 @@ +import test from "node:test" +import assert from "node:assert/strict" +import { + AGENT_TOOLS, + SEAL_NOTE_TYPE, + SEAL_SESSION_TEXT, + createSealHandlers, + createSealPost, +} from "../lib/seal-adapter.mjs" +import { guardVikingUriToolCall, noticeVikingUriToolResult } from "../lib/uri-guard-adapter.mjs" + +const SAVED = "ghp_savedTokenValue0123456789" +const SAVED_REF = "{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}" +const TYPED = "sk-typedSecretValue987654" +const TYPED_REF = "{{ov_privacy:alice:viking://~/privacy/auto/openai-k3j2#/values/token}}" + +/** A seal and resolve endpoint over a two-entry vault, as the server answers. */ +function fakeServer({ fail = null } = {}) { + const calls = [] + const post = async (path, body) => { + calls.push({ path, body }) + if (fail) return fail(path, body) + if (path.endsWith("/seal")) { + const texts = body.texts.map(({ text, enroll }) => { + const vault = [[SAVED, SAVED_REF, false]] + if (enroll) vault.push([TYPED, TYPED_REF, true]) + const points = Array.from(text) + const replaced = [] + let out = "" + for (let i = 0; i < points.length;) { + const rest = points.slice(i).join("") + const hit = vault.find(([value]) => rest.startsWith(value)) + if (hit) { + const len = Array.from(hit[0]).length + replaced.push({ start: i, end: i + len, reference: hit[1], created: false, temporary: hit[2] }) + out += hit[1] + i += len + } else { + out += points[i] + i += 1 + } + } + return replaced.length ? { text: out, replaced } : null + }) + return { status: 200, json: { status: "ok", result: { revision: "r1", texts } } } + } + if (body.selector === SAVED_REF) return { status: 200, json: { status: "ok", result: { value: SAVED } } } + return { status: 404, json: { status: "error", error: { message: "not found" } } } + } + return { post, calls } +} + +function handlers(server, options = {}) { + const told = [] + const h = createSealHandlers({ + post: server.post, + ownToolNames: () => ["openviking_read"], + tell: (_ctx, message) => told.push({ message }), + ...options, + }) + return { ...h, told } +} + +test("input is sealed with enroll and the note comes with the run it starts", async () => { + const server = fakeServer() + const h = handlers(server) + const text = `use ${TYPED} and ${SAVED}` + const result = await h.onInput({ text, source: "interactive" }, {}) + assert.equal(result.action, "transform") + assert.equal(result.text, `use ${TYPED_REF} and ${SAVED_REF}`) + assert.equal(server.calls[0].body.texts[0].enroll, true) + + const start = await h.onBeforeAgentStart({ systemPrompt: "BASE", prompt: result.text, messageType: "user" }) + assert.equal(start.systemPrompt, `BASE\n\n${SEAL_SESSION_TEXT}`) + assert.equal(start.message.customType, SEAL_NOTE_TYPE) + assert.equal(start.message.display, false) + assert.match(start.message.content, /^OpenViking stored a secret from the user's message/) + assert.ok(start.message.content.includes(`values={"token": "${TYPED_REF}"}`)) + assert.ok(!start.message.content.includes(SAVED_REF), "only temporary references are listed") + + // The note belongs to that one run. + const next = await h.onBeforeAgentStart({ systemPrompt: "BASE", prompt: "next", messageType: "user" }) + assert.equal(next.message, undefined) + assert.equal(next.systemPrompt, `BASE\n\n${SEAL_SESSION_TEXT}`) +}) + +test("the note survives a /skill: expansion of the sealed input", async () => { + const h = handlers(fakeServer()) + const result = await h.onInput({ text: `/skill:deploy with ${TYPED}`, source: "interactive" }, {}) + const expanded = `Deploy the app.\n\nwith ${TYPED_REF}` + const start = await h.onBeforeAgentStart({ systemPrompt: "", prompt: expanded, messageType: "user" }) + assert.equal(result.text, `/skill:deploy with ${TYPED_REF}`) + assert.equal(start.message.customType, SEAL_NOTE_TYPE) +}) + +test("a saved secret is replaced without a note; nothing to replace continues", async () => { + const h = handlers(fakeServer()) + const sealed = await h.onInput({ text: `token ${SAVED}`, source: "interactive" }, {}) + assert.deepEqual(sealed, { action: "transform", text: `token ${SAVED_REF}`, images: undefined }) + assert.equal(await h.onBeforeAgentStart({ systemPrompt: "", prompt: sealed.text }).message, undefined) + assert.deepEqual(await h.onInput({ text: "hello there", source: "interactive" }, {}), { action: "continue" }) +}) + +test("a message queued into a running turn carries its note in the text", async () => { + const h = handlers(fakeServer()) + const result = await h.onInput({ text: `also ${TYPED}`, streamingBehavior: "steer" }, {}) + assert.ok(result.text.startsWith(`also ${TYPED_REF}\n\nOpenViking stored a secret`)) + assert.equal(await h.onBeforeAgentStart({ systemPrompt: "", prompt: "x" }).message, undefined) +}) + +test("empty input passes without a request", async () => { + const server = fakeServer() + const h = handlers(server) + assert.deepEqual(await h.onInput({ text: " " }, {}), { action: "continue" }) + assert.equal(server.calls.length, 0) +}) + +test("text starting with a slash is sealed: pi sends it to the model", async () => { + const h = handlers(fakeServer()) + const result = await h.onInput({ text: `/skill:deploy ${SAVED}` }, {}) + assert.equal(result.action, "transform") + assert.equal(result.text, `/skill:deploy ${SAVED_REF}`) +}) + +test("a failure to tell the user still stops the input", async () => { + const server = fakeServer({ fail: async () => { throw new Error("connect ECONNREFUSED") } }) + const h = createSealHandlers({ post: server.post, tell: () => { throw new Error("no ui") } }) + assert.deepEqual(await h.onInput({ text: `use ${SAVED}`, source: "interactive" }, {}), { action: "handled" }) +}) + +test("a sealing failure stops the input and tells the user why and what to do", async () => { + const server = fakeServer({ fail: async () => { throw new Error("connect ECONNREFUSED") } }) + const h = handlers(server) + const result = await h.onInput({ text: `use ${SAVED}`, source: "interactive" }, {}) + assert.deepEqual(result, { action: "handled" }) + assert.equal(h.told.length, 1) + assert.match(h.told[0].message, /not sent.*cannot reach the OpenViking server: connect ECONNREFUSED/) + assert.match(h.told[0].message, /Try again once the OpenViking server answers, or turn sealing off with sealSecrets: false \(OPENVIKING_SEAL_SECRETS=0\)/) + assert.ok(!h.told[0].message.includes(SAVED)) +}) + +test("tool_call puts real values in place, in the event's own input", async () => { + const h = handlers(fakeServer()) + const input = { command: `curl -H 'Authorization: ${SAVED_REF}' https://x`, timeout: 5 } + const event = { toolName: "bash", input } + assert.equal(await h.onToolCall(event), undefined) + assert.equal(event.input, input) + assert.equal(input.command, `curl -H 'Authorization: ${SAVED}' https://x`) + assert.equal(input.timeout, 5) +}) + +test("tool_call leaves OpenViking, own and agent tools alone", async () => { + const server = fakeServer() + const h = handlers(server) + for (const toolName of ["openviking_privacy_upsert", "openviking_read", ...AGENT_TOOLS]) { + const input = { values: { token: SAVED_REF } } + await h.onToolCall({ toolName, input }) + assert.equal(input.values.token, SAVED_REF, toolName) + } + assert.equal(server.calls.length, 0) +}) + +test("a resolve failure blocks the call", async () => { + const broken = handlers(fakeServer({ fail: async () => ({ status: 500, json: { status: "error", error: { message: "boom" } } }) })) + const decision = await broken.onToolCall({ toolName: "bash", input: { command: `echo ${SAVED_REF}` } }) + assert.equal(decision.block, true) + assert.match(decision.reason, /could not put the secret values in.*HTTP 500.*did not run.*OPENVIKING_SEAL_SECRETS=0/) +}) + +test("tool_result seals text, details and structuredContent; images and the rest stay", async () => { + const server = fakeServer() + const h = handlers(server) + const image = { type: "image", data: "aGVsbG8=", mimeType: "image/png" } + const event = { + toolName: "bash", + content: [{ type: "text", text: `out ${SAVED}` }, image], + details: { truncation: null, fullOutputPath: "/tmp/x", note: `saw ${SAVED}` }, + structuredContent: { token: SAVED }, + isError: false, + } + const patch = await h.onToolResult(event) + assert.deepEqual(patch.content, [{ type: "text", text: `out ${SAVED_REF}` }, image]) + assert.equal(patch.content[1], image) + assert.deepEqual(patch.details, { truncation: null, fullOutputPath: "/tmp/x", note: `saw ${SAVED_REF}` }) + assert.deepEqual(patch.structuredContent, { token: SAVED_REF }) + assert.equal(patch.isError, undefined) + // One request for the whole result, enroll off by default. + assert.equal(server.calls.length, 1) + assert.ok(server.calls[0].body.texts.every((t) => t.enroll === false)) +}) + +test("tool_result enrolls with enrollToolSecrets and returns nothing when nothing changed", async () => { + const server = fakeServer() + const h = handlers(server, { enrollToolSecrets: true }) + const patch = await h.onToolResult({ toolName: "read", content: [{ type: "text", text: `key=${TYPED}` }] }) + assert.deepEqual(patch, { content: [{ type: "text", text: `key=${TYPED_REF}` }] }) + assert.equal(server.calls[0].body.texts[0].enroll, true) + assert.equal(await h.onToolResult({ toolName: "read", content: [{ type: "text", text: "plain output" }] }), undefined) +}) + +test("a tool_result that cannot be sealed is withheld and marked as an error", async () => { + const h = handlers(fakeServer({ fail: async () => ({ status: 200, json: { status: "ok", result: { texts: [] } } }) })) + const patch = await h.onToolResult({ + toolName: "bash", + content: [{ type: "text", text: `out ${SAVED}` }], + details: { note: SAVED }, + }) + assert.equal(patch.isError, true) + assert.deepEqual(patch.details, {}) + assert.equal(patch.content.length, 1) + assert.match(patch.content[0].text, /^\[OpenViking withheld this tool result: sealing secrets in it failed \(malformed response/) + assert.ok(!JSON.stringify(patch).includes(SAVED)) +}) + +test("with the URI notice after it, the notice survives sealing and withholding", async () => { + // index.ts registers sealing before the notice, and pi hands each tool_result + // handler the result the previous one left. + const run = async (server) => { + const event = { toolName: "bash", input: { command: "cat viking://resources/a.md" }, content: [{ type: "text", text: SAVED }] } + const patch = await handlers(server).onToolResult(event) + if (patch?.content) event.content = patch.content + return noticeVikingUriToolResult(event).content + } + const sealed = await run(fakeServer()) + assert.equal(sealed[0].text, SAVED_REF) + assert.match(sealed[1].text, /viking:\/\//) + const withheldContent = await run(fakeServer({ fail: async () => { throw new Error("down") } })) + assert.match(withheldContent[0].text, /withheld/) + assert.match(withheldContent[1].text, /viking:\/\//) +}) + +test("the URI guard, run first, still sees the reference the model wrote", async () => { + const event = { toolName: "read", input: { path: `viking://resources/${SAVED_REF}` } } + assert.equal(guardVikingUriToolCall(event)?.block, true) +}) + +test("createSealPost hands the core the envelope and turns no answer into a rejection", async () => { + const seen = [] + const fetchJSON = async (path, init, options) => { + seen.push({ path, init, options }) + if (path === "/ok") return { ok: true, status: 200, result: { revision: "r" } } + if (path === "/err") return { ok: false, status: 403, result: null, error: { message: "denied" } } + if (path === "/slow") return { ok: false, status: 0, result: null, error: { name: "AbortError", aborted: true, message: "aborted" } } + return { ok: false, status: 0, result: null, error: { message: "ECONNREFUSED" } } + } + const post = createSealPost(fetchJSON) + assert.deepEqual(await post("/ok", { a: 1 }), { status: 200, json: { status: "ok", result: { revision: "r" } } }) + assert.equal(seen[0].init.method, "POST") + assert.equal(seen[0].init.body, '{"a":1}') + assert.equal(seen[0].options.timeoutMs, 30000) + assert.deepEqual(await post("/err", {}), { status: 403, json: { status: "error", error: { message: "denied" } } }) + await assert.rejects(post("/slow", {}), (error) => error.name === "AbortError" && error.aborted === true) + await assert.rejects(post("/down", {}), /ECONNREFUSED/) +}) + +// ── a server that cannot seal ─────────────────────────────────────────── + +const TOO_OLD = { check: () => ({ supported: false, required: "0.5.7", actual: "0.5.6" }) } +const NO_HEALTH = { check: async () => ({ supported: false, required: "0.5.7", actual: null }) } + +test("a server too old or without a readable version stops at each hook point without a call", async () => { + for (const [options, version, hint] of [ + [TOO_OLD, /is version 0\.5\.6, and sealing secrets needs 0\.5\.7 or newer/, /Upgrade the OpenViking server/], + [NO_HEALTH, /version could not be read .* needs 0\.5\.7 or newer/, /running and reachable/], + ]) { + const server = fakeServer() + const h = handlers(server, options) + assert.deepEqual(await h.onInput({ text: `use ${SAVED}`, source: "interactive" }, {}), { action: "handled" }) + assert.match(h.told[0].message, /not sent, because the OpenViking server/) + assert.match(h.told[0].message, version) + assert.match(h.told[0].message, hint) + const decision = await h.onToolCall({ toolName: "bash", input: { command: `echo ${SAVED_REF}` } }) + assert.equal(decision.block, true) + assert.match(decision.reason, hint) + const patch = await h.onToolResult({ toolName: "bash", content: [{ type: "text", text: `out ${SAVED}` }] }) + assert.equal(patch.isError, true) + assert.ok(!JSON.stringify(patch).includes(SAVED)) + assert.equal(server.calls.length, 0) + } +}) diff --git a/examples/pi-coding-agent-extension/tests/uri-guard.test.mjs b/examples/pi-coding-agent-extension/tests/uri-guard.test.mjs index 450a3371e24..70884c3d772 100644 --- a/examples/pi-coding-agent-extension/tests/uri-guard.test.mjs +++ b/examples/pi-coding-agent-extension/tests/uri-guard.test.mjs @@ -110,3 +110,13 @@ test("pi URI guard leaves other tool results alone", () => { assert.equal(noticeVikingUriToolResult({ toolName: "read", input: { path: "viking://resources/file.md" }, content }), null) assert.equal(noticeVikingUriToolResult({ toolName: "openviking_read", input: { uris: ["viking://resources/file.md"] }, content }), null) }) + +test("pi URI guard adds no notice for a privacy reference in a bash command", () => { + const content = [{ type: "text", text: "ok" }] + const ref = "{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}" + const command = `ov privacy run --env TOKEN='${ref}' -- sh -c 'gh api user'` + assert.equal(noticeVikingUriToolResult({ toolName: "bash", input: { command }, content }), null) + const mixed = noticeVikingUriToolResult({ toolName: "bash", input: { command: `${command}; cat viking://resources/a.md` }, content }) + assert.match(mixed?.content[1].text ?? "", /viking:\/\/resources\/a\.md/) + assert.doesNotMatch(mixed?.content[1].text ?? "", /privacy\/credential/) +}) diff --git a/examples/skills/openviking-memory/SKILL.md b/examples/skills/openviking-memory/SKILL.md index 253a32e508c..2b9bb18320c 100644 --- a/examples/skills/openviking-memory/SKILL.md +++ b/examples/skills/openviking-memory/SKILL.md @@ -8,8 +8,11 @@ description: > context this session does not have — even if nobody says the word "memory". Also use it when the user asks where memories are stored: per project, per folder, or shared between repositories. Covers choosing between context search, find, list search, and grep, reading viking:// - URIs, and when (not) to write. -version: 2026.10.1 + URIs, and when (not) to write. Also use it when a message or file holds an + {{ov_privacy:…}} reference or says OpenViking replaced a secret with one: it + covers using saved credentials without reading them (`ov privacy run`), and + naming or rotating them. +version: 2026.11.1 --- # OpenViking Memory @@ -98,6 +101,56 @@ Do not invent other keys or commands for this: that file is the whole interface, - Skills stored in OpenViking (the `` list, `add_skill`, moving local skills in) are covered by the `openviking-skills` skill. +## Saved credentials + +OpenViking keeps the user's API keys and tokens in Privacy. A saved secret is +named by a reference such as +`{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}`: the +owner, then the field. It stands for a value you are not meant to read. + +- **Use it without reading it** — `ov privacy run` resolves references for one + local command and masks their values in its output. Pass a reference as an + environment variable with `--env NAME=REF` (repeatable), load `NAME=REF` + lines with `--env-file `, or put it inside an argument; the command + comes after `--`. Single-quote every reference in a shell command, because + `{{…}}` and `#` are otherwise open to shell interpretation: + + ```bash + ov privacy run --env GH_TOKEN='{{ov_privacy:alice:viking://~/privacy/credential/github#/values/token}}' -- gh repo list + ``` + + To use the variable on the command line, wrap the command in `sh -c '…'`: + + ```bash + ov privacy run --env GH_TOKEN='' -- sh -c 'curl -H "Authorization: Bearer $GH_TOKEN" https://api.github.com/user' + ``` + + `$GH_TOKEN` written outside `sh -c '…'` is expanded by your own shell + before `ov` runs, and is empty. + + Prefer `--env`: with `OPENVIKING_PRIVACY_RUN_STRICT=1` references in arguments are refused. +- **Do not print values.** `privacy_resolve`, `ov privacy resolve`, + `ov privacy get` and `ov privacy version` print plain values; use them only + when the user asks to see a value. Do not print any part of a secret either + (a prefix, a suffix); to check a secret, print only its length. + `ov privacy run` masks only complete values in its output. +- **What exists** — `privacy_tree` lists targets, fields, their references and + descriptions, never values; on the CLI, `ov privacy tree --references` shows + the references and `ov privacy tree -o json` also the descriptions. The + description is how to tell similar credentials apart. `privacy_tree` leaves + the `auto` category out unless you ask for it with `category="auto"`; an + `auto/…` reference was created automatically and works like any other. +- **Naming and rotating** — only when the `privacy_upsert` tool's own + description says that a reference can be passed as the value: then a whole + reference as a value copies that field's current value, so the secret never + passes through you; prefer it. On the CLI, under the same condition: + `ov privacy upsert credential --field =''`. Use it + to save an automatic entry under a proper name in `credential`, or to + replace a value. The automatic entry is removed once saved, so use the + reference the upsert returns from then on. Give a short description of what + the credential is for: `description` on `privacy_upsert`, or `--labels-json + '{"description":"…"}'` on the CLI, which replaces all of the target's labels. + ## Beyond the MCP tools More advanced OpenViking operations are available through the `ov` CLI — diff --git a/openviking_gateway/server-features.json b/openviking_gateway/server-features.json index e0e3ee0f192..20d8f22f7bf 100644 --- a/openviking_gateway/server-features.json +++ b/openviking_gateway/server-features.json @@ -1,3 +1,4 @@ { - "working_memory_opt_in": "0.5.0" + "working_memory_opt_in": "0.5.0", + "privacy_seal": "0.5.7" } diff --git a/tests/fixtures/server_feature_versions.json b/tests/fixtures/server_feature_versions.json index 2ff5d21d961..a629ac44f6d 100644 --- a/tests/fixtures/server_feature_versions.json +++ b/tests/fixtures/server_feature_versions.json @@ -26,5 +26,15 @@ {"feature":"working_memory_opt_in","version":"unknown","supported":false}, {"feature":"working_memory_opt_in","version":"","supported":false}, {"feature":"working_memory_opt_in","version":null,"supported":false}, - {"feature":"working_memory_opt_in","version":57,"supported":false} + {"feature":"working_memory_opt_in","version":57,"supported":false}, + {"feature":"privacy_seal","version":"0.5.7","supported":true}, + {"feature":"privacy_seal","version":"0.5.7.dev44","supported":true}, + {"feature":"privacy_seal","version":"0.5.7rc1","supported":true}, + {"feature":"privacy_seal","version":"0.5.7.post2","supported":true}, + {"feature":"privacy_seal","version":"0.5.10","supported":true}, + {"feature":"privacy_seal","version":"1.0","supported":true}, + {"feature":"privacy_seal","version":"0.5.6","supported":false}, + {"feature":"privacy_seal","version":"0.5.6.post1","supported":false}, + {"feature":"privacy_seal","version":"0.5.6.dev99","supported":false}, + {"feature":"privacy_seal","version":"0.5","supported":false} ]