From d2dcaa7939af87f5a10be72f1cea98d94f42f6bc Mon Sep 17 00:00:00 2001 From: ktz03 <2484593937@qq.com> Date: Thu, 8 Oct 2026 16:23:10 +0800 Subject: [PATCH] fix(plugins): keep SessionStart profiles within UTF-8 byte caps --- .../16-capability-reference.md | 2 +- .../16-capability-reference.md | 2 +- .../hosts/cursor/openviking.integration.json | 2 +- .../hosts/kimicode/kimi.plugin.json | 2 +- .../kimicode/openviking.integration.json | 2 +- .../hosts/trae/openviking.integration.json | 2 +- .../hosts/zcode/openviking.integration.json | 2 +- examples/agent-hook-plugin/plugin.json | 2 +- .../.claude-plugin/plugin.json | 2 +- .../claude-code-memory-plugin/package.json | 2 +- .../scripts/shared/profile-inject.mjs | 40 ++++++++++++---- .../.codex-plugin/plugin.json | 2 +- .../scripts/shared/profile-inject.mjs | 40 ++++++++++++---- examples/dsh-memory-plugin/config.mjs | 2 +- examples/dsh-memory-plugin/package-lock.json | 4 +- examples/dsh-memory-plugin/package.json | 2 +- .../lib/profile-inject.mjs | 40 ++++++++++++---- .../profile-inject.test.mjs | 46 ++++++++++++++++++- examples/opencode-plugin/package.json | 2 +- .../package-lock.json | 4 +- .../pi-coding-agent-extension/package.json | 2 +- 21 files changed, 157 insertions(+), 47 deletions(-) diff --git a/docs/en/agent-integrations/16-capability-reference.md b/docs/en/agent-integrations/16-capability-reference.md index ef950238330..ca44f1b05f2 100644 --- a/docs/en/agent-integrations/16-capability-reference.md +++ b/docs/en/agent-integrations/16-capability-reference.md @@ -228,7 +228,7 @@ Budgets and limits: - `profileTokenBudget` (default 10,000 tokens) covers the profile and the memory index. The profile gets half. An oversized profile keeps its first 8 lines and its end; an oversized listing ends with `... +N more`. Token estimates count CJK characters as 1.5 tokens and other text as four characters per token. - `skillCatalogTokenBudget` (default 1,200 tokens, `OPENVIKING_SKILL_CATALOG_TOKEN_BUDGET`) is a separate budget for the skill catalog. `skillCatalog` (`OPENVIKING_SKILL_CATALOG`) or a budget of 0 turns the catalog off. - The catalog comes from one `GET /api/v1/skills` request. The user's own skills come first, and an account skill with the same name as a user skill is left out. Each description is cut to about 40 tokens. If descriptions do not fit, the catalog lists names only; if names do not fit, it ends with `... +N more`, or shrinks to a one-line count. Servers without that endpoint get no catalog. -- `sessionStartMaxBytes` caps the whole block in UTF-8 bytes: 9,500 for Claude Code and Codex, whose hosts move hook output above about 10,000 characters into a file and show only a preview; 20,000 for ZCode, which drops output above 32 KB; no cap elsewhere. Above the cap, the memory index is dropped first, then the skill catalog. +- `sessionStartMaxBytes` caps the whole block in UTF-8 bytes: 9,500 for Claude Code and Codex, whose hosts move hook output above about 10,000 characters into a file and show only a preview; 20,000 for ZCode, which drops output above 32 KB; no cap elsewhere. Above the cap, the memory index is dropped first, then the skill catalog. If the profile alone is still too large, it is elided using its retained UTF-8 size while keeping its tags complete; a cap too small for a wrapped profile omits it. `0` removes the byte cap. On resume, some integrations also inject the previous archive summary, with a 32,000-token budget: Claude Code on resume and compact, Codex on resume after its local session was cleared, OpenCode at session start, and pi when takeover is off. Claude Code and Codex skip a profile block identical to the one the session already received. diff --git a/docs/zh/agent-integrations/16-capability-reference.md b/docs/zh/agent-integrations/16-capability-reference.md index ba949aad2d6..43cf14a6e16 100644 --- a/docs/zh/agent-integrations/16-capability-reference.md +++ b/docs/zh/agent-integrations/16-capability-reference.md @@ -228,7 +228,7 @@ skill 走单独的路径。创建、安装或替换 skill 用 MCP `add_skill` - `profileTokenBudget`(默认 10,000 token)覆盖 profile 和记忆索引,profile 占一半。profile 超长时保留前 8 行和结尾;清单超长时以 `... +N more` 结尾。token 估算中,CJK 字符按 1.5 token 计,其他文本按每 4 个字符 1 token 计。 - `skillCatalogTokenBudget`(默认 1,200 token,`OPENVIKING_SKILL_CATALOG_TOKEN_BUDGET`)是 skill 清单的独立预算。`skillCatalog`(`OPENVIKING_SKILL_CATALOG`)或把预算设为 0 都会关闭清单。 - 清单来自一次 `GET /api/v1/skills` 请求。用户自己的 skill 排在前面,与用户 skill 同名的账户 skill 不再列出。每条描述截到约 40 token。描述放不下时只列名称;名称也放不下时以 `... +N more` 结尾,或缩成一行数量。服务端没有该接口时不注入清单。 -- `sessionStartMaxBytes` 按 UTF-8 字节限制整个块:Claude Code 和 Codex 为 9,500,因为这两个宿主会把超过约 10,000 字符的 hook 输出存成文件,只显示预览;ZCode 为 20,000,因为它会丢弃超过 32 KB 的输出;其他集成不设上限。超出上限时,先去掉记忆索引,再去掉 skill 清单。 +- `sessionStartMaxBytes` 按 UTF-8 字节限制整个块:Claude Code 和 Codex 为 9,500,因为这两个宿主会把超过约 10,000 字符的 hook 输出存成文件,只显示预览;ZCode 为 20,000,因为它会丢弃超过 32 KB 的输出;其他集成不设上限。超出上限时,先去掉记忆索引,再去掉 skill 清单。如果仅 profile 仍然过大,再按实际保留内容的 UTF-8 大小裁剪,并保留完整标签;上限连带标签的 profile 都无法容纳时,省略该块。设为 `0` 取消字节上限。 恢复会话时,部分集成还会注入上一次归档的摘要,预算 32,000 token:Claude Code 在 resume 和 compact 时,Codex 在本地会话已清空后的 resume 时,OpenCode 在会话开始时,pi 在 takeover 关闭时。Claude Code 和 Codex 遇到与本会话已注入内容相同的 profile 块时会跳过。 diff --git a/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json b/examples/agent-hook-plugin/hosts/cursor/openviking.integration.json index 4e6778787a2..8dcbd7eb1aa 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.12", + "version": "0.5.13", "clients": [ "cursor" ], diff --git a/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json b/examples/agent-hook-plugin/hosts/kimicode/kimi.plugin.json index 01ba46a9e6c..8b39fc914b1 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.12", + "version": "0.5.13", "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 01b7e037719..138e6884a14 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.12", + "version": "0.5.13", "clients": [ "kimicode" ], diff --git a/examples/agent-hook-plugin/hosts/trae/openviking.integration.json b/examples/agent-hook-plugin/hosts/trae/openviking.integration.json index 546dcf0d715..64c50950d84 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.12", + "version": "0.5.13", "clients": [ "trae", "trae-cn" diff --git a/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json b/examples/agent-hook-plugin/hosts/zcode/openviking.integration.json index 06ed4632f74..e3d1ec57cba 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.12", + "version": "0.5.13", "clients": [ "zcode" ], diff --git a/examples/agent-hook-plugin/plugin.json b/examples/agent-hook-plugin/plugin.json index bf19512688e..46cea3e2b9c 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.12", + "version": "0.5.13", "description": "Long-term semantic memory for Cursor, TRAE, TRAE CN, ZCode and Kimi Code — 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 5d2077ca92f..ec2325ea58e 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.4", + "version": "0.7.5", "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/package.json b/examples/claude-code-memory-plugin/package.json index 68052abddcc..0dde69d87ee 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.4", + "version": "0.7.5", "description": "OpenViking memory plugin for Claude Code — semantic long-term memory", "type": "module", "scripts": { diff --git a/examples/claude-code-memory-plugin/scripts/shared/profile-inject.mjs b/examples/claude-code-memory-plugin/scripts/shared/profile-inject.mjs index 510f1feb4c8..4a59fb35886 100644 --- a/examples/claude-code-memory-plugin/scripts/shared/profile-inject.mjs +++ b/examples/claude-code-memory-plugin/scripts/shared/profile-inject.mjs @@ -157,32 +157,47 @@ async function lsDir(fetchJSON, dirUri, actorPeerId = "") { * meaningfully ( - content.slice(0, maxChars).trimEnd() + "\n... [profile truncated]"; + const fallbackHeadTruncate = () => { + const marker = "\n... [profile truncated]"; + if (maxBytes === Infinity) return content.slice(0, maxChars).trimEnd() + marker; + let used = utf8Bytes(marker); + let prefix = ""; + for (const character of content) { + const cost = utf8Bytes(character); + if (prefix.length + character.length > maxChars || used + cost > maxBytes) break; + prefix += character; + used += cost; + } + return prefix.trimEnd() ? prefix.trimEnd() + marker : null; + }; if (lines.length <= HEAD_LINES + 4) return fallbackHeadTruncate(); const head = lines.slice(0, HEAD_LINES).join("\n"); const reserveForTail = maxChars - head.length - ELLIPSIS.length; - if (reserveForTail < 200) return fallbackHeadTruncate(); + const reserveTailBytes = maxBytes - utf8Bytes(head + ELLIPSIS); + if (reserveForTail < 200 || reserveTailBytes <= 0) return fallbackHeadTruncate(); let tailChars = 0; + let tailBytes = 0; let tailStart = lines.length; for (let i = lines.length - 1; i > HEAD_LINES; i--) { const lineLen = lines[i].length + 1; - if (tailChars + lineLen > reserveForTail) break; + const lineBytes = utf8Bytes(lines[i]) + 1; + if (tailChars + lineLen > reserveForTail || tailBytes + lineBytes > reserveTailBytes) break; tailChars += lineLen; + tailBytes += lineBytes; tailStart = i; } if (tailStart >= lines.length - 1) return fallbackHeadTruncate(); @@ -371,8 +386,8 @@ function formatSkillCatalog(groups, budgetTokens) { export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerId = "", options = {}) { const { skillCatalog = false, skillCatalogTokenBudget = 0, sessionStartMaxBytes = 0 } = options; // Hosts that spill (Claude Code, Codex) or drop (ZCode) oversized hook output - // get a byte cap. An estimated token is about 4 UTF-8 bytes at most, so the - // token budgets shrink to fit under it. + // get a byte cap. Shrink the token budgets first, then check the actual + // retained UTF-8 bytes: elision can change the profile's character density. const capTokens = sessionStartMaxBytes > 0 ? Math.max(0, Math.floor(sessionStartMaxBytes / 4) - 50) : Infinity; @@ -409,7 +424,7 @@ export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerI const entBudget = Math.max(0, listingBudget - prefBlock.used); const entBlock = formatListing(entUri, ents, entBudget); - const profileLines = profileTrunc + let profileLines = profileTrunc ? [``, profileTrunc, ``] : []; let memoryLines = prefBlock.lines.length > 0 || entBlock.lines.length > 0 @@ -428,6 +443,13 @@ export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerI skillLines = []; block = render(); } + if (sessionStartMaxBytes > 0 && utf8Bytes(block) > sessionStartMaxBytes) { + const [open, , close] = profileLines; + const frameBytes = utf8Bytes(`${open}\n\n${close}`); + const boundedProfile = elideProfile(profile, profileBudget, sessionStartMaxBytes - frameBytes); + profileLines = boundedProfile ? [open, boundedProfile, close] : []; + block = render(); + } if (!block) return null; return { diff --git a/examples/codex-memory-plugin/.codex-plugin/plugin.json b/examples/codex-memory-plugin/.codex-plugin/plugin.json index 51862a5ba1c..425e21f6945 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.3", + "version": "0.11.4", "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/profile-inject.mjs b/examples/codex-memory-plugin/scripts/shared/profile-inject.mjs index 510f1feb4c8..4a59fb35886 100644 --- a/examples/codex-memory-plugin/scripts/shared/profile-inject.mjs +++ b/examples/codex-memory-plugin/scripts/shared/profile-inject.mjs @@ -157,32 +157,47 @@ async function lsDir(fetchJSON, dirUri, actorPeerId = "") { * meaningfully ( - content.slice(0, maxChars).trimEnd() + "\n... [profile truncated]"; + const fallbackHeadTruncate = () => { + const marker = "\n... [profile truncated]"; + if (maxBytes === Infinity) return content.slice(0, maxChars).trimEnd() + marker; + let used = utf8Bytes(marker); + let prefix = ""; + for (const character of content) { + const cost = utf8Bytes(character); + if (prefix.length + character.length > maxChars || used + cost > maxBytes) break; + prefix += character; + used += cost; + } + return prefix.trimEnd() ? prefix.trimEnd() + marker : null; + }; if (lines.length <= HEAD_LINES + 4) return fallbackHeadTruncate(); const head = lines.slice(0, HEAD_LINES).join("\n"); const reserveForTail = maxChars - head.length - ELLIPSIS.length; - if (reserveForTail < 200) return fallbackHeadTruncate(); + const reserveTailBytes = maxBytes - utf8Bytes(head + ELLIPSIS); + if (reserveForTail < 200 || reserveTailBytes <= 0) return fallbackHeadTruncate(); let tailChars = 0; + let tailBytes = 0; let tailStart = lines.length; for (let i = lines.length - 1; i > HEAD_LINES; i--) { const lineLen = lines[i].length + 1; - if (tailChars + lineLen > reserveForTail) break; + const lineBytes = utf8Bytes(lines[i]) + 1; + if (tailChars + lineLen > reserveForTail || tailBytes + lineBytes > reserveTailBytes) break; tailChars += lineLen; + tailBytes += lineBytes; tailStart = i; } if (tailStart >= lines.length - 1) return fallbackHeadTruncate(); @@ -371,8 +386,8 @@ function formatSkillCatalog(groups, budgetTokens) { export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerId = "", options = {}) { const { skillCatalog = false, skillCatalogTokenBudget = 0, sessionStartMaxBytes = 0 } = options; // Hosts that spill (Claude Code, Codex) or drop (ZCode) oversized hook output - // get a byte cap. An estimated token is about 4 UTF-8 bytes at most, so the - // token budgets shrink to fit under it. + // get a byte cap. Shrink the token budgets first, then check the actual + // retained UTF-8 bytes: elision can change the profile's character density. const capTokens = sessionStartMaxBytes > 0 ? Math.max(0, Math.floor(sessionStartMaxBytes / 4) - 50) : Infinity; @@ -409,7 +424,7 @@ export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerI const entBudget = Math.max(0, listingBudget - prefBlock.used); const entBlock = formatListing(entUri, ents, entBudget); - const profileLines = profileTrunc + let profileLines = profileTrunc ? [``, profileTrunc, ``] : []; let memoryLines = prefBlock.lines.length > 0 || entBlock.lines.length > 0 @@ -428,6 +443,13 @@ export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerI skillLines = []; block = render(); } + if (sessionStartMaxBytes > 0 && utf8Bytes(block) > sessionStartMaxBytes) { + const [open, , close] = profileLines; + const frameBytes = utf8Bytes(`${open}\n\n${close}`); + const boundedProfile = elideProfile(profile, profileBudget, sessionStartMaxBytes - frameBytes); + profileLines = boundedProfile ? [open, boundedProfile, close] : []; + block = render(); + } if (!block) return null; return { diff --git a/examples/dsh-memory-plugin/config.mjs b/examples/dsh-memory-plugin/config.mjs index ec7d584303b..23f99d1c960 100644 --- a/examples/dsh-memory-plugin/config.mjs +++ b/examples/dsh-memory-plugin/config.mjs @@ -1,7 +1,7 @@ import { buildPluginConfig } from "./shared/plugin-config.mjs"; import { loadCredentialFiles } from "./shared/credentials.mjs"; -export const PLUGIN_VERSION = "0.5.18"; +export const PLUGIN_VERSION = "0.5.19"; /** * Namespace for the bridged OpenViking MCP tools. DSH publishes every MCP tool diff --git a/examples/dsh-memory-plugin/package-lock.json b/examples/dsh-memory-plugin/package-lock.json index 42a7c9414f7..d5703006a8a 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.18", + "version": "0.5.19", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@openviking/dsh-memory-plugin", - "version": "0.5.18", + "version": "0.5.19", "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 7cf57cc0b3d..12cede1185c 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.18", + "version": "0.5.19", "description": "OpenViking memory and context bundle for DeepSeek Harness", "icon": "./icon.svg", "type": "module", diff --git a/examples/memory-plugin-shared/lib/profile-inject.mjs b/examples/memory-plugin-shared/lib/profile-inject.mjs index 1015a2c5301..8dfd8012a50 100644 --- a/examples/memory-plugin-shared/lib/profile-inject.mjs +++ b/examples/memory-plugin-shared/lib/profile-inject.mjs @@ -156,32 +156,47 @@ async function lsDir(fetchJSON, dirUri, actorPeerId = "") { * meaningfully ( - content.slice(0, maxChars).trimEnd() + "\n... [profile truncated]"; + const fallbackHeadTruncate = () => { + const marker = "\n... [profile truncated]"; + if (maxBytes === Infinity) return content.slice(0, maxChars).trimEnd() + marker; + let used = utf8Bytes(marker); + let prefix = ""; + for (const character of content) { + const cost = utf8Bytes(character); + if (prefix.length + character.length > maxChars || used + cost > maxBytes) break; + prefix += character; + used += cost; + } + return prefix.trimEnd() ? prefix.trimEnd() + marker : null; + }; if (lines.length <= HEAD_LINES + 4) return fallbackHeadTruncate(); const head = lines.slice(0, HEAD_LINES).join("\n"); const reserveForTail = maxChars - head.length - ELLIPSIS.length; - if (reserveForTail < 200) return fallbackHeadTruncate(); + const reserveTailBytes = maxBytes - utf8Bytes(head + ELLIPSIS); + if (reserveForTail < 200 || reserveTailBytes <= 0) return fallbackHeadTruncate(); let tailChars = 0; + let tailBytes = 0; let tailStart = lines.length; for (let i = lines.length - 1; i > HEAD_LINES; i--) { const lineLen = lines[i].length + 1; - if (tailChars + lineLen > reserveForTail) break; + const lineBytes = utf8Bytes(lines[i]) + 1; + if (tailChars + lineLen > reserveForTail || tailBytes + lineBytes > reserveTailBytes) break; tailChars += lineLen; + tailBytes += lineBytes; tailStart = i; } if (tailStart >= lines.length - 1) return fallbackHeadTruncate(); @@ -370,8 +385,8 @@ function formatSkillCatalog(groups, budgetTokens) { export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerId = "", options = {}) { const { skillCatalog = false, skillCatalogTokenBudget = 0, sessionStartMaxBytes = 0 } = options; // Hosts that spill (Claude Code, Codex) or drop (ZCode) oversized hook output - // get a byte cap. An estimated token is about 4 UTF-8 bytes at most, so the - // token budgets shrink to fit under it. + // get a byte cap. Shrink the token budgets first, then check the actual + // retained UTF-8 bytes: elision can change the profile's character density. const capTokens = sessionStartMaxBytes > 0 ? Math.max(0, Math.floor(sessionStartMaxBytes / 4) - 50) : Infinity; @@ -408,7 +423,7 @@ export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerI const entBudget = Math.max(0, listingBudget - prefBlock.used); const entBlock = formatListing(entUri, ents, entBudget); - const profileLines = profileTrunc + let profileLines = profileTrunc ? [``, profileTrunc, ``] : []; let memoryLines = prefBlock.lines.length > 0 || entBlock.lines.length > 0 @@ -427,6 +442,13 @@ export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerI skillLines = []; block = render(); } + if (sessionStartMaxBytes > 0 && utf8Bytes(block) > sessionStartMaxBytes) { + const [open, , close] = profileLines; + const frameBytes = utf8Bytes(`${open}\n\n${close}`); + const boundedProfile = elideProfile(profile, profileBudget, sessionStartMaxBytes - frameBytes); + profileLines = boundedProfile ? [open, boundedProfile, close] : []; + block = render(); + } if (!block) return null; return { diff --git a/examples/memory-plugin-shared/profile-inject.test.mjs b/examples/memory-plugin-shared/profile-inject.test.mjs index 9f053df34da..ebd487042b3 100644 --- a/examples/memory-plugin-shared/profile-inject.test.mjs +++ b/examples/memory-plugin-shared/profile-inject.test.mjs @@ -190,10 +190,54 @@ test("a byte cap keeps the whole block under it with profile, index and catalog" test("when the cap cannot hold everything, the memory index goes before the catalog", async () => { const { fetchJSON } = fakeServer({ profile: HEAVY_PROFILE, memories: HEAVY_MEMORIES, skills: HEAVY_SKILLS }); const result = await buildProfileBlock(fetchJSON, 10000, "", { ...CATALOG, sessionStartMaxBytes: 1000 }); - assert.ok(Buffer.byteLength(result.block) <= 1000 || !result.block.includes("/); }); +test("the byte cap uses the retained profile's density and keeps its envelope complete", async () => { + for (const [width, tailWidth, tailCount] of [[400, 1000, 100], [350, 100, 1000]]) { + const head = Array.from({ length: 8 }, () => "中".repeat(width)).join("\n"); + const profile = `${head}\n${Array.from({ length: tailCount }, () => "x".repeat(tailWidth)).join("\n")}`; + const { fetchJSON } = fakeServer({ profile, memories: HEAVY_MEMORIES }); + const result = await buildProfileBlock(fetchJSON, 10000, "", { sessionStartMaxBytes: 9500 }); + assert.ok(Buffer.byteLength(result.block) <= 9500, `${width}: ${Buffer.byteLength(result.block)} bytes`); + assert.match(result.block, /^\n/); + assert.match(result.block, /\n<\/user-profile>$/); + assert.doesNotMatch(result.block, /`)); + } + } +}); + +test("small byte caps retain whole Unicode characters or omit a profile that cannot fit", async () => { + for (const profile of ["x".repeat(3000), "中".repeat(3000), "😀".repeat(3000), HEAVY_PROFILE]) { + const { fetchJSON } = fakeServer({ profile }); + for (const cap of [1, 80, 100, 128, 500, 1000]) { + const result = await buildProfileBlock(fetchJSON, 10000, "", { sessionStartMaxBytes: cap }); + if (!result) continue; + assert.ok(Buffer.byteLength(result.block) <= cap, `${cap}: ${Buffer.byteLength(result.block)} bytes`); + assert.match(result.block, /^\n/); + assert.match(result.block, /\n<\/user-profile>$/); + assert.equal(Buffer.from(result.block).toString("utf8"), result.block); + } + assert.equal(await buildProfileBlock(fetchJSON, 10000, "", { sessionStartMaxBytes: 1 }), null); + } +}); + +test("uncapped and fitting profiles keep the same output", async () => { + for (const profile of ["# Alice\n- prefers small PRs", "中文".repeat(50), "x".repeat(100), "😀".repeat(20)]) { + const { fetchJSON } = fakeServer({ profile }); + const expected = `\n${profile}\n`; + for (const cap of [0, 9500]) { + const result = await buildProfileBlock(fetchJSON, 2000, "", { sessionStartMaxBytes: cap }); + assert.equal(result.block, expected); + } + } +}); + test("the two roots share no client-side cap, so shared skills survive a full private root", async () => { const skills = [ ...Array.from({ length: 200 }, (_, i) => skill(OWN, `own-${String(i).padStart(3, "0")}`)), diff --git a/examples/opencode-plugin/package.json b/examples/opencode-plugin/package.json index cb0bfae49be..3888ac0fca6 100644 --- a/examples/opencode-plugin/package.json +++ b/examples/opencode-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@openviking/opencode-plugin", - "version": "0.5.6", + "version": "0.5.7", "author": "@openviking", "description": "Unified OpenCode plugin for OpenViking repository retrieval and long-term memory", "type": "module", diff --git a/examples/pi-coding-agent-extension/package-lock.json b/examples/pi-coding-agent-extension/package-lock.json index cc275a72b65..544cda338d3 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.11", + "version": "0.4.12", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "openviking-pi-extension", - "version": "0.4.11", + "version": "0.4.12", "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 c20eeb9c1b1..727bfb23401 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.11", + "version": "0.4.12", "description": "OpenViking memory and context extension for the pi coding agent", "private": true, "type": "module",