Skip to content

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

fix(memory-plugins): report tool output verbatim, let the server externalize (#3933)

t0saki7e26fab61ca8
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index 89638ada9..69544052c 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -33,6 +33,7 @@ jobs:
node --test \
examples/codex-memory-plugin/servers/mcp-proxy.test.mjs \
examples/codex-memory-plugin/scripts/auto-capture.test.mjs \
+ examples/codex-memory-plugin/scripts/capture-utils.test.mjs \
examples/codex-memory-plugin/scripts/marketplace.test.mjs \
examples/codex-memory-plugin/scripts/ov-credentials.test.mjs \
examples/codex-memory-plugin/scripts/recall-compressor-profile.test.mjs \
diff --git a/docs/en/agent-integrations/02-claude-code.md b/docs/en/agent-integrations/02-claude-code.md
index 3e38ee78d..c45a4e429 100644
--- a/docs/en/agent-integrations/02-claude-code.md
+++ b/docs/en/agent-integrations/02-claude-code.md
@@ -72,6 +72,8 @@ The plugin hooks into the Claude Code lifecycle:
All write operations run asynchronously, ensuring they never block your conversation.
+Tool calls and results are captured as dedicated `tool` parts, and `tool_output` is reported verbatim. Truncation is the server's job: output larger than `tool_output_externalization.threshold_chars` (default `20000`) is written to the session's tool-result store, and the part keeps a synopsis stub plus `tool_output_ref`, so the original stays readable through [`/api/v1/sessions/{id}/tool-results`](../api/05-sessions.md#read_tool_result).
+
<details>
<summary><b>Configuration</b></summary>
diff --git a/docs/en/agent-integrations/04-codex.md b/docs/en/agent-integrations/04-codex.md
index 01382c95e..a8dff8134 100644
--- a/docs/en/agent-integrations/04-codex.md
+++ b/docs/en/agent-integrations/04-codex.md
@@ -52,6 +52,8 @@ The plugin integrates with Codex's lifecycle by hooking into key events. On `Ses
> **Known limitation**: Codex does not fire a hook upon `SIGTERM`, `Ctrl+C`, or `/exit`. Orphaned sessions are recovered during the next `SessionStart` via the idle-TTL sweep (30 minutes) or the active-window heuristic.
+Tool calls and results are captured as dedicated `tool` parts, and `tool_output` is reported verbatim. Truncation is the server's job: output larger than `tool_output_externalization.threshold_chars` (default `20000`) is written to the session's tool-result store, and the part keeps a synopsis stub plus `tool_output_ref`, so the original stays readable through [`/api/v1/sessions/{id}/tool-results`](../api/05-sessions.md#read_tool_result).
+
<details>
<summary><b>Configuration</b></summary>
diff --git a/docs/en/agent-integrations/10-opencode.md b/docs/en/agent-integrations/10-opencode.md
index 7a91a912c..fa08a65c6 100644
--- a/docs/en/agent-integrations/10-opencode.md
+++ b/docs/en/agent-integrations/10-opencode.md
@@ -4,6 +4,8 @@ Give [OpenCode](https://opencode.ai/) cross-project and cross-session long-term
Source: [examples/opencode-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin)
+Tool calls and results are captured as dedicated `tool` parts, and `tool_output` is reported verbatim. Truncation is the server's job: output larger than `tool_output_externalization.threshold_chars` (default `20000`) is written to the session's tool-result store, and the part keeps a synopsis stub plus `tool_output_ref`, so the original stays readable through [`/api/v1/sessions/{id}/tool-results`](../api/05-sessions.md#read_tool_result).
+
## Prerequisites
- [OpenCode](https://opencode.ai/)
diff --git a/docs/en/agent-integrations/11-pi.md b/docs/en/agent-integrations/11-pi.md
index 8fb090908..e65c40558 100644
--- a/docs/en/agent-integrations/11-pi.md
+++ b/docs/en/agent-integrations/11-pi.md
@@ -14,6 +14,8 @@ Source: [examples/pi-coding-agent-extension](https://github.com/volcengine/OpenV
- A footer status segment (`OV ✓ …`) shows connection and capture state; the `/viking` command prints status, and `/viking commit` forces a commit.
- Accidental `read`/`bash` calls on `viking://` URIs are blocked with a hint pointing back to `viking_read` / `viking_search`.
+Tool calls and results are captured as dedicated `tool` parts, and `tool_output` is reported verbatim. Truncation is the server's job: output larger than `tool_output_externalization.threshold_chars` (default `20000`) is written to the session's tool-result store, and the part keeps a synopsis stub plus `tool_output_ref`, so the original stays readable through [`/api/v1/sessions/{id}/tool-results`](../api/05-sessions.md#read_tool_result).
+
## Prerequisites
- pi coding agent (`npm i -g @earendil-works/pi-coding-agent`)
diff --git a/docs/zh/agent-integrations/02-claude-code.md b/docs/zh/agent-integrations/02-claude-code.md
index aa1dd02c3..eb1c90e3f 100644
--- a/docs/zh/agent-integrations/02-claude-code.md
+++ b/docs/zh/agent-integrations/02-claude-code.md
@@ -72,6 +72,8 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar
所有数据写入操作均为异步执行,不会阻塞当前的对话进程。
+工具调用和结果会作为独立的 `tool` part 捕获,`tool_output` 原样上报。截断由服务端负责:超过 `tool_output_externalization.threshold_chars`(默认 `20000`)的输出会写入 session 的 tool-result 存储,part 中只保留 synopsis stub 和 `tool_output_ref`,原文仍可通过 [`/api/v1/sessions/{id}/tool-results`](../api/05-sessions.md#read_tool_result) 读回。
+
<details>
<summary><b>配置</b></summary>
diff --git a/docs/zh/agent-integrations/04-codex.md b/docs/zh/agent-integrations/04-codex.md
index ac37894d3..e357522fe 100644
--- a/docs/zh/agent-integrations/04-codex.md
+++ b/docs/zh/agent-integrations/04-codex.md
@@ -52,6 +52,8 @@ codex # 首次启动需进入 /hooks 完成一次审批
> **已知局限**:当通过 `SIGTERM`、`Ctrl+C` 或输入 `/exit` 退出 Codex 时,不会触发任何 hook(钩子)。遗留的孤儿会话将在下一次触发 `SessionStart` 时,通过闲置 TTL(生存时间,默认为 30 分钟)机制或活动窗口启发式策略进行回收清理。
+工具调用和结果会作为独立的 `tool` part 捕获,`tool_output` 原样上报。截断由服务端负责:超过 `tool_output_externalization.threshold_chars`(默认 `20000`)的输出会写入 session 的 tool-result 存储,part 中只保留 synopsis stub 和 `tool_output_ref`,原文仍可通过 [`/api/v1/sessions/{id}/tool-results`](../api/05-sessions.md#read_tool_result) 读回。
+
<details>
<summary><b>配置</b></summary>
diff --git a/docs/zh/agent-integrations/10-opencode.md b/docs/zh/agent-integrations/10-opencode.md
index a56da1732..4449d5070 100644
--- a/docs/zh/agent-integrations/10-opencode.md
+++ b/docs/zh/agent-integrations/10-opencode.md
@@ -4,6 +4,8 @@
源码:[examples/opencode-plugin](https://github.com/volcengine/OpenViking/tree/main/examples/opencode-plugin)
+工具调用和结果会作为独立的 `tool` part 捕获,`tool_output` 原样上报。截断由服务端负责:超过 `tool_output_externalization.threshold_chars`(默认 `20000`)的输出会写入 session 的 tool-result 存储,part 中只保留 synopsis stub 和 `tool_output_ref`,原文仍可通过 [`/api/v1/sessions/{id}/tool-results`](../api/05-sessions.md#read_tool_result) 读回。
+
## 前置条件
- [OpenCode](https://opencode.ai/)
diff --git a/docs/zh/agent-integrations/11-pi.md b/docs/zh/agent-integrations/11-pi.md
index 16cda24d1..e569754d3 100644
--- a/docs/zh/agent-integrations/11-pi.md
+++ b/docs/zh/agent-integrations/11-pi.md
@@ -14,6 +14,8 @@
- 底部状态栏显示 `OV ✓ …` 连接与捕获状态;`/viking` 命令查看状态,`/viking commit` 强制 commit。
- 模型误用本地 `read`/`bash` 读取 `viking://` URI 时会被拦截,并提示改用 `viking_read` / `viking_search`。
+工具调用和结果会作为独立的 `tool` part 捕获,`tool_output` 原样上报。截断由服务端负责:超过 `tool_output_externalization.threshold_chars`(默认 `20000`)的输出会写入 session 的 tool-result 存储,part 中只保留 synopsis stub 和 `tool_output_ref`,原文仍可通过 [`/api/v1/sessions/{id}/tool-results`](../api/05-sessions.md#read_tool_result) 读回。
+
## 前置条件
- pi coding agent(`npm i -g @earendil-works/pi-coding-agent`)
diff --git a/examples/claude-code-memory-plugin/README.md b/examples/claude-code-memory-plugin/README.md
index 451cb4890..70d7a02f0 100644
--- a/examples/claude-code-memory-plugin/README.md
+++ b/examples/claude-code-memory-plugin/README.md
@@ -167,6 +167,7 @@ Recall defaults to the broad mode: global memory, the current workspace, and oth
| `OPENVIKING_CAPTURE_MODE` | `semantic` | `semantic` (always capture) or `keyword` (trigger-based) |
| `OPENVIKING_CAPTURE_MAX_LENGTH` | `24000` | Max sanitized text length for the capture decision |
| `OPENVIKING_CAPTURE_ASSISTANT_TURNS` | `true` | Include assistant turns (text + tool I/O). Set to `0` for user-only. |
+| `OPENVIKING_CAPTURE_TOOL_MAX_CHARS` | `1000000` | Guard cap on one tool part's `tool_output`; oversized output is externalized server-side |
| `OPENVIKING_COMMIT_TOKEN_THRESHOLD` | `20000` | Pending-token threshold for client-driven commit |
| `OPENVIKING_RESUME_CONTEXT_BUDGET` | `32000` | Token budget when fetching archive overview on session resume |
diff --git a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs b/examples/claude-code-memory-plugin/scripts/auto-capture.mjs
index 60d17ea23..dc098bcf5 100644
--- a/examples/claude-code-memory-plugin/scripts/auto-capture.mjs
+++ b/examples/claude-code-memory-plugin/scripts/auto-capture.mjs
@@ -276,17 +276,14 @@ function extractToolResultText(content) {
// Tool output retention for the part path. Unlike the legacy prose path
// (TOOL_RESULT_MAX_CHARS, which drops outputs to keep the extractor's text
-// clean), results here land in a separable tool_output field, so we keep them —
-// bounded so we don't store whole files / web pages / command stdout verbatim.
-const TOOL_OUTPUT_PART_MAX_CHARS = 2000;
-
+// clean), results here land in a separable tool_output field and are reported
+// verbatim — the server externalizes anything oversized and leaves a stub plus
+// tool_output_ref, so truncating here would only destroy what it stores.
function truncateToolOutput(s) {
if (typeof s !== "string") s = String(s ?? "");
- if (s.length <= TOOL_OUTPUT_PART_MAX_CHARS) return s;
- return (
- s.slice(0, TOOL_OUTPUT_PART_MAX_CHARS) +
- `\n... [truncated, ${s.length - TOOL_OUTPUT_PART_MAX_CHARS} more chars]`
- );
+ const max = cfg.captureToolMaxChars;
+ if (s.length <= max) return s;
+ return s.slice(0, max) + `\n... [truncated, ${s.length - max} more chars]`;
}
// tool_result blocks carry only tool_use_id, not the tool name. Pre-scan all
diff --git a/examples/claude-code-memory-plugin/scripts/auto-capture.test.mjs b/examples/claude-code-memory-plugin/scripts/auto-capture.test.mjs
index 6b5899b2d..5f9933e51 100644
--- a/examples/claude-code-memory-plugin/scripts/auto-capture.test.mjs
+++ b/examples/claude-code-memory-plugin/scripts/auto-capture.test.mjs
@@ -227,3 +227,92 @@ test("legacy advanced cursor rewinds when the server session is empty", async ()
await rm(root, { recursive: true, force: true });
}
});
+
+async function captureToolResult(root, transcriptPath, sessionId, extraEnv = {}) {
+ const batches = [];
+ await withMockOpenViking(async (req, res) => {
+ const url = new URL(req.url, "http://127.0.0.1");
+ if (req.method === "GET" && url.pathname === "/health") {
+ writeJson(res, 200, { status: "ok", result: { healthy: true } });
+ return;
+ }
+ if (req.method === "POST" && url.pathname.endsWith("/messages/batch")) {
+ const body = await readRequestBody(req);
+ batches.push(body);
+ writeJson(res, 200, { status: "ok", result: { added: body.messages.length } });
+ return;
+ }
+ if (req.method === "GET" && url.pathname === `/api/v1/sessions/cc-${sessionId}`) {
+ writeJson(res, 200, {
+ status: "ok",
+ result: { message_count: 2, pending_tokens: 10, commit_count: 0 },
+ });
+ return;
+ }
+ writeJson(res, 404, { status: "error", error: { code: "NOT_FOUND" } });
+ }, async (baseUrl) => {
+ await runAutoCapture(
+ { session_id: sessionId, transcript_path: transcriptPath, cwd: root },
+ { ...hookEnv(root, baseUrl), ...extraEnv },
+ );
+ });
+ return batches
+ .flatMap((batch) => batch.messages)
+ .flatMap((message) => message.parts || [])
+ .filter((part) => part.type === "tool");
+}
+
+async function writeToolTranscript(path, output) {
+ await writeFile(
+ path,
+ [
+ JSON.stringify({ role: "user", content: "read the large fixture please" }),
+ JSON.stringify({
+ role: "assistant",
+ content: [{ type: "tool_use", id: "toolu_1", name: "Read", input: { file_path: "/big.txt" } }],
+ }),
+ JSON.stringify({
+ role: "user",
+ content: [{
+ type: "tool_result",
+ tool_use_id: "toolu_1",
+ content: [{ type: "text", text: output }],
+ }],
+ }),
+ ].join("\n"),
+ );
+}
+
+test("tool output is reported verbatim so the server can externalize it", async () => {
+ const root = await mkdtemp(join(tmpdir(), "ov-cc-capture-toolout-"));
+ const transcriptPath = join(root, "transcript.jsonl");
+ const output = "x".repeat(50_000);
+
+ try {
+ await writeToolTranscript(transcriptPath, output);
+ const toolParts = await captureToolResult(root, transcriptPath, "capture-toolout");
+ const result = toolParts.find((part) => part.tool_status === "completed");
+ assert.equal(result.tool_name, "Read");
+ assert.equal(result.tool_output, output);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("captureToolMaxChars still caps tool output when an operator lowers it", async () => {
+ const root = await mkdtemp(join(tmpdir(), "ov-cc-capture-toolcap-"));
+ const transcriptPath = join(root, "transcript.jsonl");
+ const output = "y".repeat(5_000);
+
+ try {
+ await writeToolTranscript(transcriptPath, output);
+ const toolParts = await captureToolResult(root, transcriptPath, "capture-toolcap", {
+ OPENVIKING_CAPTURE_TOOL_MAX_CHARS: "1000",
+ });
+ const result = toolParts.find((part) => part.tool_status === "completed");
+ assert.ok(result.tool_output.startsWith("y".repeat(1000)));
+ assert.match(result.tool_output, /\[truncated, 4000 more chars\]$/);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/examples/claude-code-memory-plugin/scripts/config.mjs b/examples/claude-code-memory-plugin/scripts/config.mjs
index 29684965a..8dc37251a 100644
--- a/examples/claude-code-memory-plugin/scripts/config.mjs
+++ b/examples/claude-code-memory-plugin/scripts/config.mjs
@@ -322,6 +322,13 @@ export function loadConfig() {
process.env.OPENVIKING_CAPTURE_MAX_LENGTH,
num(cc.captureMaxLength, 24000),
))),
+ // Tool output is reported verbatim; the server owns truncation via
+ // tool_output_externalization (threshold_chars, default 20000). This cap only
+ // guards against pathological payloads.
+ captureToolMaxChars: Math.max(200, Math.floor(num(
+ process.env.OPENVIKING_CAPTURE_TOOL_MAX_CHARS,
+ num(cc.captureToolMaxChars, 1000000),
+ ))),
captureTimeoutMs,
// Default true: a "memory plugin" without assistant-side capture only sees half the
// conversation, which makes extraction noticeably worse. Subagent capture has always
diff --git a/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs b/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs
index c28d9ffd9..0cc76778f 100644
--- a/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs
+++ b/examples/claude-code-memory-plugin/scripts/shared/capture-utils.mjs
@@ -17,6 +17,11 @@ const TOOL_RESULT_TYPES = new Set([
"functioncalloutput",
]);
+// Tool output is reported verbatim; the server owns truncation via
+// tool_output_externalization (threshold_chars, default 20000). This cap only
+// guards against pathological payloads.
+const DEFAULT_TOOL_MAX_CHARS = 1000000;
+
const ACK_RE = /^(?:ok|okay|k|yes|yep|no|nope|thanks|thank you|thx|done|收到|好的|好|嗯|可以|继续|不用|不需要|没了|好了)[.!?。!?\s]*$/i;
const SLASH_COMMAND_RE = /^\/[a-z0-9_-]{1,64}\b/i;
const METADATA_KEYS = [
@@ -147,7 +152,7 @@ function toolStatus(block, kind) {
return status || "completed";
}
-function buildToolPart(block, kind, { toolMaxChars = 2000, toolNameById = {} } = {}) {
+function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, toolNameById = {} } = {}) {
const id = toolId(block);
const name = toolName(block) || (id ? toolNameById[id] : "");
const payload = toolPayload(block, kind);
@@ -201,7 +206,7 @@ function blockToText(block, options) {
}
export function extractTextFromContent(content, options = {}) {
- const opts = { toolMaxChars: 2000, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options };
if (!content) return "";
if (typeof content === "string") return content;
if (Array.isArray(content)) {
@@ -221,7 +226,7 @@ export function extractTextFromPayload(payload, options = {}) {
const chunks = [];
const directType = normalizeType(payload.type || payload.kind || payload.role);
if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || TOOL_CALL_TYPES.has(directType)) {
- const direct = blockToText(payload, { toolMaxChars: 2000, ...options });
+ const direct = blockToText(payload, { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options });
if (direct) return direct;
}
@@ -241,7 +246,7 @@ export function extractTextFromPayload(payload, options = {}) {
}
if (chunks.length === 0) {
- const direct = blockToText(payload, { toolMaxChars: 2000, ...options });
+ const direct = blockToText(payload, { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options });
if (direct) chunks.push(direct);
}
@@ -281,7 +286,7 @@ function collectToolNamesByIdFromPayload(payload, out) {
}
function extractPartsFromContent(content, options = {}) {
- const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, toolNameById: {}, ...options };
const parts = [];
if (!content) return parts;
if (typeof content === "string") {
@@ -309,7 +314,7 @@ function extractPartsFromContent(content, options = {}) {
export function extractPartsFromPayload(payload, options = {}) {
if (!payload || typeof payload !== "object") return [];
- const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, toolNameById: {}, ...options };
if (payload.message && typeof payload.message === "object") {
return extractPartsFromPayload(payload.message, opts);
}
diff --git a/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs b/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs
index 946aa4677..9574d177e 100644
--- a/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs
+++ b/examples/claude-code-memory-plugin/scripts/subagent-stop.mjs
@@ -112,16 +112,13 @@ function extractToolResultText(content) {
}
// Structured parts (parts-mode capture) — mirrors auto-capture.mjs. Tool calls /
-// results become dedicated `tool` parts instead of being inlined into content.
-const TOOL_OUTPUT_PART_MAX_CHARS = 2000;
-
+// results become dedicated `tool` parts instead of being inlined into content,
+// and tool_output is reported verbatim so the server can externalize it.
function truncateToolOutput(s) {
if (typeof s !== "string") s = String(s ?? "");
- if (s.length <= TOOL_OUTPUT_PART_MAX_CHARS) return s;
- return (
- s.slice(0, TOOL_OUTPUT_PART_MAX_CHARS) +
- `\n... [truncated, ${s.length - TOOL_OUTPUT_PART_MAX_CHARS} more chars]`
- );
+ const max = cfg.captureToolMaxChars;
+ if (s.length <= max) return s;
+ return s.slice(0, max) + `\n... [truncated, ${s.length - max} more chars]`;
}
function collectToolNamesById(messages) {
diff --git a/examples/codex-memory-plugin/DESIGN.md b/examples/codex-memory-plugin/DESIGN.md
index ee0e7827d..dccd9c128 100644
--- a/examples/codex-memory-plugin/DESIGN.md
+++ b/examples/codex-memory-plugin/DESIGN.md
@@ -259,7 +259,7 @@ Env var overrides for tuning without rebuilding:
| `OPENVIKING_RESUME_ARCHIVE_INJECT` | `1` | inject latest archive summary on `source=resume` when no live OV session is open |
| `OPENVIKING_RESUME_ARCHIVE_TOKEN_BUDGET` | `32000` | token budget for `/sessions/{id}/context` on resume |
| `OPENVIKING_RESUME_ARCHIVE_MAX_CHARS` | `6000` | max chars injected from latest archive overview |
-| `OPENVIKING_CAPTURE_TOOL_MAX_CHARS` | `2000` | max chars retained per compressed tool call/result |
+| `OPENVIKING_CAPTURE_TOOL_MAX_CHARS` | `1000000` | guard cap on one tool part's `tool_output`; the server externalizes anything over `tool_output_externalization.threshold_chars` (default 20000) |
| `OPENVIKING_DEBUG` | `0` | enable hook debug log |
## Resume context inject
diff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.md
index e3dd023ac..5b926a902 100644
--- a/examples/codex-memory-plugin/README.md
+++ b/examples/codex-memory-plugin/README.md
@@ -245,7 +245,7 @@ defaults.
### Stop (turn end → `add_message`, threshold commit)
-`auto-capture.mjs` derives one long-lived OpenViking session id per Codex `session_id` as `cx-<safe-session-id>` and incrementally appends every new user/assistant turn via `/api/v1/sessions/{id}/messages`. The `/messages` endpoint auto-creates the session on first append. Per-codex-session state lives at `~/.openviking/codex-plugin-state/<safe-session-id>.json`. Capture sanitizes obvious hook noise, metadata wrappers, and plugin-injected `<openviking-context ...>` blocks before append; tool calls/results are retained as compact `[tool-call ...]` / `[tool-result ...]` lines capped by `OPENVIKING_CAPTURE_TOOL_MAX_CHARS` (default 2000).
+`auto-capture.mjs` derives one long-lived OpenViking session id per Codex `session_id` as `cx-<safe-session-id>` and incrementally appends every new user/assistant turn via `/api/v1/sessions/{id}/messages`. The `/messages` endpoint auto-creates the session on first append. Per-codex-session state lives at `~/.openviking/codex-plugin-state/<safe-session-id>.json`. Capture sanitizes obvious hook noise, metadata wrappers, and plugin-injected `<openviking-context ...>` blocks before append. Tool calls and results become dedicated `tool` parts and `tool_output` is reported verbatim — the server externalizes anything larger than `tool_output_externalization.threshold_chars` (default `20000`) and leaves a synopsis stub plus `tool_output_ref`, so the original stays readable via `/api/v1/sessions/{id}/tool-results`. `OPENVIKING_CAPTURE_TOOL_MAX_CHARS` (default `1000000`) is only a guard against pathological payloads.
After a successful append, Stop reads the session meta and commits when `pending_tokens >= OPENVIKING_COMMIT_TOKEN_THRESHOLD` (default `20000`). Threshold commits pass `keep_recent_count=OPENVIKING_COMMIT_KEEP_RECENT_COUNT` (default `10`) so the newest turns remain live for continuity while older context is archived and extracted. `PreCompact` still commits everything before compaction.
diff --git a/examples/codex-memory-plugin/scripts/capture-utils.test.mjs b/examples/codex-memory-plugin/scripts/capture-utils.test.mjs
index 8412898f5..db4fa4ad4 100644
--- a/examples/codex-memory-plugin/scripts/capture-utils.test.mjs
+++ b/examples/codex-memory-plugin/scripts/capture-utils.test.mjs
@@ -5,7 +5,7 @@ import { extractCaptureTurns } from "./capture-utils.mjs";
const CAPTURE_CONFIG = {
captureAssistantTurns: true,
- captureToolMaxChars: 2000,
+ captureToolMaxChars: 1000000,
captureMaxLength: 24000,
};
@@ -391,7 +391,7 @@ test("preserves Experience usage metadata when Codex truncates a long MCP result
assert.deepEqual(completed.tool_input, { uri });
});
-test("keeps search Experience URIs parseable when snippets exceed the capture limit", () => {
+test("keeps search Experience results parseable when snippets are long", () => {
const uri = "viking://user/test/memories/experiences/long-search-result.md";
const turns = extractCaptureTurns(
[
@@ -426,5 +426,69 @@ test("keeps search Experience URIs parseable when snippets exceed the capture li
const completed = turns
.flatMap((turn) => turn.parts)
.find((part) => part.tool_status === "completed");
- assert.deepEqual(JSON.parse(completed.tool_output), { results: [{ uri }] });
+ assert.deepEqual(JSON.parse(completed.tool_output), {
+ results: [{ uri, title: "换货经验", snippet: "x".repeat(3000) }],
+ });
+});
+
+test("reports tool output verbatim so the server can externalize it", () => {
+ const output = "x".repeat(50_000);
+ const turns = extractCaptureTurns(
+ [
+ {
+ type: "response_item",
+ payload: {
+ type: "function_call",
+ call_id: "call-large-output",
+ name: "shell",
+ arguments: { command: "cat big.txt" },
+ },
+ },
+ {
+ type: "response_item",
+ payload: {
+ type: "function_call_output",
+ call_id: "call-large-output",
+ output,
+ },
+ },
+ ],
+ CAPTURE_CONFIG,
+ );
+
+ const completed = turns
+ .flatMap((turn) => turn.parts)
+ .find((part) => part.tool_status === "completed");
+ assert.equal(completed.tool_output, output);
+});
+
+test("captureToolMaxChars still caps tool output when an operator lowers it", () => {
+ const turns = extractCaptureTurns(
+ [
+ {
+ type: "response_item",
+ payload: {
+ type: "function_call",
+ call_id: "call-capped-output",
+ name: "shell",
+ arguments: { command: "cat big.txt" },
+ },
+ },
+ {
+ type: "response_item",
+ payload: {
+ type: "function_call_output",
+ call_id: "call-capped-output",
+ output: "y".repeat(5000),
+ },
+ },
+ ],
+ { ...CAPTURE_CONFIG, captureToolMaxChars: 1000 },
+ );
+
+ const completed = turns
+ .flatMap((turn) => turn.parts)
+ .find((part) => part.tool_status === "completed");
+ assert.ok(completed.tool_output.length <= 1000);
+ assert.match(completed.tool_output, /\[truncated\]$/);
});
diff --git a/examples/codex-memory-plugin/scripts/config.mjs b/examples/codex-memory-plugin/scripts/config.mjs
index 5a064a755..526144ffb 100644
--- a/examples/codex-memory-plugin/scripts/config.mjs
+++ b/examples/codex-memory-plugin/scripts/config.mjs
@@ -237,7 +237,7 @@ export function loadConfig() {
captureTimeoutMs,
captureToolMaxChars: Math.max(200, Math.floor(num(
process.env.OPENVIKING_CAPTURE_TOOL_MAX_CHARS,
- num(cx.captureToolMaxChars, 2000),
+ num(cx.captureToolMaxChars, 1000000),
))),
writePathAsync: envBool("OPENVIKING_WRITE_PATH_ASYNC") ?? (cx.writePathAsync !== false),
// Default true: a "memory plugin" without assistant-side capture only sees half the
diff --git a/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs b/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs
index c28d9ffd9..0cc76778f 100644
--- a/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs
+++ b/examples/codex-memory-plugin/scripts/shared/capture-utils.mjs
@@ -17,6 +17,11 @@ const TOOL_RESULT_TYPES = new Set([
"functioncalloutput",
]);
+// Tool output is reported verbatim; the server owns truncation via
+// tool_output_externalization (threshold_chars, default 20000). This cap only
+// guards against pathological payloads.
+const DEFAULT_TOOL_MAX_CHARS = 1000000;
+
const ACK_RE = /^(?:ok|okay|k|yes|yep|no|nope|thanks|thank you|thx|done|收到|好的|好|嗯|可以|继续|不用|不需要|没了|好了)[.!?。!?\s]*$/i;
const SLASH_COMMAND_RE = /^\/[a-z0-9_-]{1,64}\b/i;
const METADATA_KEYS = [
@@ -147,7 +152,7 @@ function toolStatus(block, kind) {
return status || "completed";
}
-function buildToolPart(block, kind, { toolMaxChars = 2000, toolNameById = {} } = {}) {
+function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, toolNameById = {} } = {}) {
const id = toolId(block);
const name = toolName(block) || (id ? toolNameById[id] : "");
const payload = toolPayload(block, kind);
@@ -201,7 +206,7 @@ function blockToText(block, options) {
}
export function extractTextFromContent(content, options = {}) {
- const opts = { toolMaxChars: 2000, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options };
if (!content) return "";
if (typeof content === "string") return content;
if (Array.isArray(content)) {
@@ -221,7 +226,7 @@ export function extractTextFromPayload(payload, options = {}) {
const chunks = [];
const directType = normalizeType(payload.type || payload.kind || payload.role);
if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || TOOL_CALL_TYPES.has(directType)) {
- const direct = blockToText(payload, { toolMaxChars: 2000, ...options });
+ const direct = blockToText(payload, { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options });
if (direct) return direct;
}
@@ -241,7 +246,7 @@ export function extractTextFromPayload(payload, options = {}) {
}
if (chunks.length === 0) {
- const direct = blockToText(payload, { toolMaxChars: 2000, ...options });
+ const direct = blockToText(payload, { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options });
if (direct) chunks.push(direct);
}
@@ -281,7 +286,7 @@ function collectToolNamesByIdFromPayload(payload, out) {
}
function extractPartsFromContent(content, options = {}) {
- const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, toolNameById: {}, ...options };
const parts = [];
if (!content) return parts;
if (typeof content === "string") {
@@ -309,7 +314,7 @@ function extractPartsFromContent(content, options = {}) {
export function extractPartsFromPayload(payload, options = {}) {
if (!payload || typeof payload !== "object") return [];
- const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, toolNameById: {}, ...options };
if (payload.message && typeof payload.message === "object") {
return extractPartsFromPayload(payload.message, opts);
}
diff --git a/examples/memory-plugin-shared/lib/capture-utils.mjs b/examples/memory-plugin-shared/lib/capture-utils.mjs
index 4c951bc5a..2bd98e326 100644
--- a/examples/memory-plugin-shared/lib/capture-utils.mjs
+++ b/examples/memory-plugin-shared/lib/capture-utils.mjs
@@ -16,6 +16,11 @@ const TOOL_RESULT_TYPES = new Set([
"functioncalloutput",
]);
+// Tool output is reported verbatim; the server owns truncation via
+// tool_output_externalization (threshold_chars, default 20000). This cap only
+// guards against pathological payloads.
+const DEFAULT_TOOL_MAX_CHARS = 1000000;
+
const ACK_RE = /^(?:ok|okay|k|yes|yep|no|nope|thanks|thank you|thx|done|收到|好的|好|嗯|可以|继续|不用|不需要|没了|好了)[.!?。!?\s]*$/i;
const SLASH_COMMAND_RE = /^\/[a-z0-9_-]{1,64}\b/i;
const METADATA_KEYS = [
@@ -146,7 +151,7 @@ function toolStatus(block, kind) {
return status || "completed";
}
-function buildToolPart(block, kind, { toolMaxChars = 2000, toolNameById = {} } = {}) {
+function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, toolNameById = {} } = {}) {
const id = toolId(block);
const name = toolName(block) || (id ? toolNameById[id] : "");
const payload = toolPayload(block, kind);
@@ -200,7 +205,7 @@ function blockToText(block, options) {
}
export function extractTextFromContent(content, options = {}) {
- const opts = { toolMaxChars: 2000, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options };
if (!content) return "";
if (typeof content === "string") return content;
if (Array.isArray(content)) {
@@ -220,7 +225,7 @@ export function extractTextFromPayload(payload, options = {}) {
const chunks = [];
const directType = normalizeType(payload.type || payload.kind || payload.role);
if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || TOOL_CALL_TYPES.has(directType)) {
- const direct = blockToText(payload, { toolMaxChars: 2000, ...options });
+ const direct = blockToText(payload, { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options });
if (direct) return direct;
}
@@ -240,7 +245,7 @@ export function extractTextFromPayload(payload, options = {}) {
}
if (chunks.length === 0) {
- const direct = blockToText(payload, { toolMaxChars: 2000, ...options });
+ const direct = blockToText(payload, { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options });
if (direct) chunks.push(direct);
}
@@ -280,7 +285,7 @@ function collectToolNamesByIdFromPayload(payload, out) {
}
function extractPartsFromContent(content, options = {}) {
- const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, toolNameById: {}, ...options };
const parts = [];
if (!content) return parts;
if (typeof content === "string") {
@@ -308,7 +313,7 @@ function extractPartsFromContent(content, options = {}) {
export function extractPartsFromPayload(payload, options = {}) {
if (!payload || typeof payload !== "object") return [];
- const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, toolNameById: {}, ...options };
if (payload.message && typeof payload.message === "object") {
return extractPartsFromPayload(payload.message, opts);
}
diff --git a/examples/opencode-plugin/lib/config.mjs b/examples/opencode-plugin/lib/config.mjs
index 20e4552b8..e32c7eb14 100644
--- a/examples/opencode-plugin/lib/config.mjs
+++ b/examples/opencode-plugin/lib/config.mjs
@@ -45,7 +45,7 @@ const DEFAULT_CONFIG = {
captureMode: "semantic",
captureMaxLength: 24000,
captureAssistantTurns: true,
- captureToolMaxChars: 2000,
+ captureToolMaxChars: 1000000,
commitTokenThreshold: 20000,
commitKeepRecentCount: 10,
profileTokenBudget: 10000,
@@ -261,7 +261,7 @@ function normalizeConfig(config) {
config.recallPeerScope = config.recallPeerScope === "actor" ? "actor" : "all"
config.recallQueryExpansion = config.recallQueryExpansion === "off" ? "off" : "auto"
config.captureMaxLength = Math.max(200, Math.min(100000, Math.round(Number(config.captureMaxLength) || 24000)))
- config.captureToolMaxChars = Math.max(200, Math.min(20000, Math.round(Number(config.captureToolMaxChars) || 2000)))
+ config.captureToolMaxChars = Math.max(200, Math.min(1000000, Math.round(Number(config.captureToolMaxChars) || 1000000)))
config.commitTokenThreshold = Math.max(1000, Math.round(Number(config.commitTokenThreshold) || 20000))
const rawCommitKeepRecentCount = config.commitKeepRecentCount
const commitKeepRecentCount = rawCommitKeepRecentCount == null ||
diff --git a/examples/opencode-plugin/lib/shared/capture-utils.mjs b/examples/opencode-plugin/lib/shared/capture-utils.mjs
index c28d9ffd9..0cc76778f 100644
--- a/examples/opencode-plugin/lib/shared/capture-utils.mjs
+++ b/examples/opencode-plugin/lib/shared/capture-utils.mjs
@@ -17,6 +17,11 @@ const TOOL_RESULT_TYPES = new Set([
"functioncalloutput",
]);
+// Tool output is reported verbatim; the server owns truncation via
+// tool_output_externalization (threshold_chars, default 20000). This cap only
+// guards against pathological payloads.
+const DEFAULT_TOOL_MAX_CHARS = 1000000;
+
const ACK_RE = /^(?:ok|okay|k|yes|yep|no|nope|thanks|thank you|thx|done|收到|好的|好|嗯|可以|继续|不用|不需要|没了|好了)[.!?。!?\s]*$/i;
const SLASH_COMMAND_RE = /^\/[a-z0-9_-]{1,64}\b/i;
const METADATA_KEYS = [
@@ -147,7 +152,7 @@ function toolStatus(block, kind) {
return status || "completed";
}
-function buildToolPart(block, kind, { toolMaxChars = 2000, toolNameById = {} } = {}) {
+function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, toolNameById = {} } = {}) {
const id = toolId(block);
const name = toolName(block) || (id ? toolNameById[id] : "");
const payload = toolPayload(block, kind);
@@ -201,7 +206,7 @@ function blockToText(block, options) {
}
export function extractTextFromContent(content, options = {}) {
- const opts = { toolMaxChars: 2000, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options };
if (!content) return "";
if (typeof content === "string") return content;
if (Array.isArray(content)) {
@@ -221,7 +226,7 @@ export function extractTextFromPayload(payload, options = {}) {
const chunks = [];
const directType = normalizeType(payload.type || payload.kind || payload.role);
if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || TOOL_CALL_TYPES.has(directType)) {
- const direct = blockToText(payload, { toolMaxChars: 2000, ...options });
+ const direct = blockToText(payload, { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options });
if (direct) return direct;
}
@@ -241,7 +246,7 @@ export function extractTextFromPayload(payload, options = {}) {
}
if (chunks.length === 0) {
- const direct = blockToText(payload, { toolMaxChars: 2000, ...options });
+ const direct = blockToText(payload, { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options });
if (direct) chunks.push(direct);
}
@@ -281,7 +286,7 @@ function collectToolNamesByIdFromPayload(payload, out) {
}
function extractPartsFromContent(content, options = {}) {
- const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, toolNameById: {}, ...options };
const parts = [];
if (!content) return parts;
if (typeof content === "string") {
@@ -309,7 +314,7 @@ function extractPartsFromContent(content, options = {}) {
export function extractPartsFromPayload(payload, options = {}) {
if (!payload || typeof payload !== "object") return [];
- const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, toolNameById: {}, ...options };
if (payload.message && typeof payload.message === "object") {
return extractPartsFromPayload(payload.message, opts);
}
diff --git a/examples/pi-coding-agent-extension/README.md b/examples/pi-coding-agent-extension/README.md
index 61c674955..67bf54c6a 100644
--- a/examples/pi-coding-agent-extension/README.md
+++ b/examples/pi-coding-agent-extension/README.md
@@ -127,7 +127,7 @@ integrations should configure category `quotas` when they need exact ceilings.
| `captureMaxLength` | `24000` | Max sanitized text length for the capture decision |
| `captureAssistantTurns` | `true` | Include assistant turns (text + tool USE inputs) |
| `captureToolResults` | `false` | Include tool result output (noisy — off by default) |
-| `captureToolMaxChars` | `2000` | Max captured output chars for one tool part |
+| `captureToolMaxChars` | `1000000` | Guard cap on one tool part's `tool_output`; the server externalizes oversized output |
| `commitTokenThreshold` | `20000` | Pending-token threshold for client-driven commit |
| `commitKeepRecentCount` | `10` | Live tail kept after commit |
diff --git a/examples/pi-coding-agent-extension/config.json b/examples/pi-coding-agent-extension/config.json
index 7d32a4c4e..b557602db 100644
--- a/examples/pi-coding-agent-extension/config.json
+++ b/examples/pi-coding-agent-extension/config.json
@@ -21,7 +21,7 @@
"captureToolResults": false,
"captureMode": "semantic",
"captureMaxLength": 24000,
- "captureToolMaxChars": 2000,
+ "captureToolMaxChars": 1000000,
"captureAssistantTurns": true,
"bypassPatterns": [],
"logLevel": "error"
diff --git a/examples/pi-coding-agent-extension/config.ts b/examples/pi-coding-agent-extension/config.ts
index 8d9c1dd22..e95ec05ea 100644
--- a/examples/pi-coding-agent-extension/config.ts
+++ b/examples/pi-coding-agent-extension/config.ts
@@ -81,7 +81,7 @@ const DEFAULT_CONFIG: OVConfig = {
captureToolResults: false,
captureMode: "semantic",
captureMaxLength: 24000,
- captureToolMaxChars: 2000,
+ captureToolMaxChars: 1000000,
captureAssistantTurns: true,
bypassPatterns: [],
logLevel: "error",
@@ -161,7 +161,7 @@ export function loadConfig(extensionDir: string): OVConfig {
config.takeoverOverviewPollMs = clampInt(config.takeoverOverviewPollMs, 0, 60000, DEFAULT_CONFIG.takeoverOverviewPollMs);
config.takeoverOverviewPollMax = clampInt(config.takeoverOverviewPollMax, 1, 120, DEFAULT_CONFIG.takeoverOverviewPollMax);
config.captureMaxLength = clampInt(config.captureMaxLength, 200, 100000, DEFAULT_CONFIG.captureMaxLength);
- config.captureToolMaxChars = clampInt(config.captureToolMaxChars, 200, 20000, DEFAULT_CONFIG.captureToolMaxChars);
+ config.captureToolMaxChars = clampInt(config.captureToolMaxChars, 200, 1000000, DEFAULT_CONFIG.captureToolMaxChars);
config.captureMode = config.captureMode === "keyword" ? "keyword" : "semantic";
config.recallPeerScope = config.recallPeerScope === "actor" ? "actor" : "all";
config.recallQueryExpansion = config.recallQueryExpansion === "off" ? "off" : "auto";
diff --git a/examples/pi-coding-agent-extension/lib/capture-adapter.mjs b/examples/pi-coding-agent-extension/lib/capture-adapter.mjs
index 498f1d5fa..f8da674b6 100644
--- a/examples/pi-coding-agent-extension/lib/capture-adapter.mjs
+++ b/examples/pi-coding-agent-extension/lib/capture-adapter.mjs
@@ -61,8 +61,15 @@ export function extractBranchCapturePayloads(branch, syncedEntryCount = 0, cfg =
const structuredParts = parts.filter((part) => part?.type !== "text");
if (!decision.shouldCapture && structuredParts.length === 0) continue;
+ // decision.text is derived from rawText, which renders tool I/O as
+ // "[tool-result ...]" lines. For a tool-only payload that would resend the
+ // same output the tool part already carries, so only keep it when the
+ // payload really had text of its own.
+ const hasTextPart = parts.some((part) => part?.type === "text");
const bodyParts = [
- ...(decision.shouldCapture && decision.text ? [{ type: "text", text: decision.text }] : []),
+ ...(hasTextPart && decision.shouldCapture && decision.text
+ ? [{ type: "text", text: decision.text }]
+ : []),
...structuredParts,
];
const body = bodyParts.length > 0
diff --git a/examples/pi-coding-agent-extension/shared/capture-utils.mjs b/examples/pi-coding-agent-extension/shared/capture-utils.mjs
index c28d9ffd9..0cc76778f 100644
--- a/examples/pi-coding-agent-extension/shared/capture-utils.mjs
+++ b/examples/pi-coding-agent-extension/shared/capture-utils.mjs
@@ -17,6 +17,11 @@ const TOOL_RESULT_TYPES = new Set([
"functioncalloutput",
]);
+// Tool output is reported verbatim; the server owns truncation via
+// tool_output_externalization (threshold_chars, default 20000). This cap only
+// guards against pathological payloads.
+const DEFAULT_TOOL_MAX_CHARS = 1000000;
+
const ACK_RE = /^(?:ok|okay|k|yes|yep|no|nope|thanks|thank you|thx|done|收到|好的|好|嗯|可以|继续|不用|不需要|没了|好了)[.!?。!?\s]*$/i;
const SLASH_COMMAND_RE = /^\/[a-z0-9_-]{1,64}\b/i;
const METADATA_KEYS = [
@@ -147,7 +152,7 @@ function toolStatus(block, kind) {
return status || "completed";
}
-function buildToolPart(block, kind, { toolMaxChars = 2000, toolNameById = {} } = {}) {
+function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, toolNameById = {} } = {}) {
const id = toolId(block);
const name = toolName(block) || (id ? toolNameById[id] : "");
const payload = toolPayload(block, kind);
@@ -201,7 +206,7 @@ function blockToText(block, options) {
}
export function extractTextFromContent(content, options = {}) {
- const opts = { toolMaxChars: 2000, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options };
if (!content) return "";
if (typeof content === "string") return content;
if (Array.isArray(content)) {
@@ -221,7 +226,7 @@ export function extractTextFromPayload(payload, options = {}) {
const chunks = [];
const directType = normalizeType(payload.type || payload.kind || payload.role);
if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || TOOL_CALL_TYPES.has(directType)) {
- const direct = blockToText(payload, { toolMaxChars: 2000, ...options });
+ const direct = blockToText(payload, { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options });
if (direct) return direct;
}
@@ -241,7 +246,7 @@ export function extractTextFromPayload(payload, options = {}) {
}
if (chunks.length === 0) {
- const direct = blockToText(payload, { toolMaxChars: 2000, ...options });
+ const direct = blockToText(payload, { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options });
if (direct) chunks.push(direct);
}
@@ -281,7 +286,7 @@ function collectToolNamesByIdFromPayload(payload, out) {
}
function extractPartsFromContent(content, options = {}) {
- const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, toolNameById: {}, ...options };
const parts = [];
if (!content) return parts;
if (typeof content === "string") {
@@ -309,7 +314,7 @@ function extractPartsFromContent(content, options = {}) {
export function extractPartsFromPayload(payload, options = {}) {
if (!payload || typeof payload !== "object") return [];
- const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, toolNameById: {}, ...options };
if (payload.message && typeof payload.message === "object") {
return extractPartsFromPayload(payload.message, opts);
}
diff --git a/examples/pi-coding-agent-extension/tests/capture-adapter.test.mjs b/examples/pi-coding-agent-extension/tests/capture-adapter.test.mjs
index aeb17d703..de6b45584 100644
--- a/examples/pi-coding-agent-extension/tests/capture-adapter.test.mjs
+++ b/examples/pi-coding-agent-extension/tests/capture-adapter.test.mjs
@@ -72,3 +72,28 @@ test("extractBranchCapturePayloads faithful mode still skips commands and plugin
assert.equal(result.payloads.length, 0);
});
+
+test("tool-only payloads carry tool output once, not duplicated as text", () => {
+ const output = "z".repeat(5000);
+ const { payloads } = extractBranchCapturePayloads(
+ [
+ {
+ type: "message",
+ message: {
+ role: "assistant",
+ content: [
+ { type: "tool_result", tool_use_id: "call-dup-check", output },
+ ],
+ },
+ },
+ ],
+ 0,
+ { captureAssistantTurns: true, captureToolMaxChars: 1000000 },
+ );
+
+ const parts = payloads.flatMap((payload) => payload.parts || []);
+ assert.equal(parts.filter((part) => part.type === "text").length, 0);
+ const toolParts = parts.filter((part) => part.type === "tool");
+ assert.equal(toolParts.length, 1);
+ assert.equal(toolParts[0].tool_output, output);
+});
diff --git a/examples/zcode-memory-plugin/scripts/shared/capture-utils.mjs b/examples/zcode-memory-plugin/scripts/shared/capture-utils.mjs
index c28d9ffd9..0cc76778f 100644
--- a/examples/zcode-memory-plugin/scripts/shared/capture-utils.mjs
+++ b/examples/zcode-memory-plugin/scripts/shared/capture-utils.mjs
@@ -17,6 +17,11 @@ const TOOL_RESULT_TYPES = new Set([
"functioncalloutput",
]);
+// Tool output is reported verbatim; the server owns truncation via
+// tool_output_externalization (threshold_chars, default 20000). This cap only
+// guards against pathological payloads.
+const DEFAULT_TOOL_MAX_CHARS = 1000000;
+
const ACK_RE = /^(?:ok|okay|k|yes|yep|no|nope|thanks|thank you|thx|done|收到|好的|好|嗯|可以|继续|不用|不需要|没了|好了)[.!?。!?\s]*$/i;
const SLASH_COMMAND_RE = /^\/[a-z0-9_-]{1,64}\b/i;
const METADATA_KEYS = [
@@ -147,7 +152,7 @@ function toolStatus(block, kind) {
return status || "completed";
}
-function buildToolPart(block, kind, { toolMaxChars = 2000, toolNameById = {} } = {}) {
+function buildToolPart(block, kind, { toolMaxChars = DEFAULT_TOOL_MAX_CHARS, toolNameById = {} } = {}) {
const id = toolId(block);
const name = toolName(block) || (id ? toolNameById[id] : "");
const payload = toolPayload(block, kind);
@@ -201,7 +206,7 @@ function blockToText(block, options) {
}
export function extractTextFromContent(content, options = {}) {
- const opts = { toolMaxChars: 2000, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options };
if (!content) return "";
if (typeof content === "string") return content;
if (Array.isArray(content)) {
@@ -221,7 +226,7 @@ export function extractTextFromPayload(payload, options = {}) {
const chunks = [];
const directType = normalizeType(payload.type || payload.kind || payload.role);
if (TOOL_RESULT_TYPES.has(directType) || directType === "tool" || TOOL_CALL_TYPES.has(directType)) {
- const direct = blockToText(payload, { toolMaxChars: 2000, ...options });
+ const direct = blockToText(payload, { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options });
if (direct) return direct;
}
@@ -241,7 +246,7 @@ export function extractTextFromPayload(payload, options = {}) {
}
if (chunks.length === 0) {
- const direct = blockToText(payload, { toolMaxChars: 2000, ...options });
+ const direct = blockToText(payload, { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, ...options });
if (direct) chunks.push(direct);
}
@@ -281,7 +286,7 @@ function collectToolNamesByIdFromPayload(payload, out) {
}
function extractPartsFromContent(content, options = {}) {
- const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, toolNameById: {}, ...options };
const parts = [];
if (!content) return parts;
if (typeof content === "string") {
@@ -309,7 +314,7 @@ function extractPartsFromContent(content, options = {}) {
export function extractPartsFromPayload(payload, options = {}) {
if (!payload || typeof payload !== "object") return [];
- const opts = { toolMaxChars: 2000, toolNameById: {}, ...options };
+ const opts = { toolMaxChars: DEFAULT_TOOL_MAX_CHARS, toolNameById: {}, ...options };
if (payload.message && typeof payload.message === "object") {
return extractPartsFromPayload(payload.message, opts);
}