Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(plugins): add OpenViking memory integration for TRAE CLI (#4026)
bhnanb7aa01d227c2
diff --git a/.github/scripts/stage-memory-plugin-marketplace.sh b/.github/scripts/stage-memory-plugin-marketplace.shindex 34ec02b22..1a020b2c0 100644--- a/.github/scripts/stage-memory-plugin-marketplace.sh+++ b/.github/scripts/stage-memory-plugin-marketplace.sh@@ -14,6 +14,7 @@ cp -R \"${ROOT}/examples/codex-memory-plugin" \"${ROOT}/examples/cursor-memory-plugin" \"${ROOT}/examples/trae-memory-hooks" \+ "${ROOT}/examples/trae-cli-memory-hooks" \"${ROOT}/examples/zcode-memory-plugin" \"${ROOT}/examples/opencode-plugin" \"${ROOT}/examples/pi-coding-agent-extension" \@@ -48,6 +49,16 @@ for required in \trae-memory-hooks/scripts/trae-turns.mjs \trae-memory-hooks/scripts/uri-guard.mjs \trae-memory-hooks/servers/mcp-proxy.mjs \+ trae-cli-memory-hooks/hooks/hooks.json \+ trae-cli-memory-hooks/.mcp.json \+ trae-cli-memory-hooks/openviking.integration.json \+ trae-cli-memory-hooks/scripts/trae-cli-hook.mjs \+ trae-cli-memory-hooks/scripts/session-start.mjs \+ trae-cli-memory-hooks/scripts/auto-recall.mjs \+ trae-cli-memory-hooks/scripts/auto-capture.mjs \+ trae-cli-memory-hooks/scripts/trae-cli-turns.mjs \+ trae-cli-memory-hooks/scripts/uri-guard.mjs \+ trae-cli-memory-hooks/servers/mcp-proxy.mjs \zcode-memory-plugin/.zcode-plugin/plugin.json \zcode-memory-plugin/hooks/hooks.json \zcode-memory-plugin/.mcp.json \diff --git a/README.md b/README.mdindex befacb6bd..d9f46aaff 100644--- a/README.md+++ b/README.md@@ -143,7 +143,7 @@ Integrations inject OpenViking recall into your agent's context and auto-commit- [OpenClaw](https://docs.openviking.ai/en/agent-integrations/03-openclaw)- [Hermes](https://docs.openviking.ai/en/agent-integrations/05-hermes)- [Cursor](https://docs.openviking.ai/en/agent-integrations/12-cursor)-- [Trae](https://docs.openviking.ai/en/agent-integrations/13-trae)+- [TRAE / TRAE CN / TRAE CLI](https://docs.openviking.ai/en/agent-integrations/13-trae)- [OpenCode](https://docs.openviking.ai/en/agent-integrations/10-opencode)- [pi](https://docs.openviking.ai/en/agent-integrations/11-pi)- [Agent Plugins 1.0](https://docs.openviking.ai/en/agent-integrations/15-agent-plugins)diff --git a/docs/en/agent-integrations/01-overview.md b/docs/en/agent-integrations/01-overview.mdindex 9983c1101..2f9b286bc 100644--- a/docs/en/agent-integrations/01-overview.md+++ b/docs/en/agent-integrations/01-overview.md@@ -10,7 +10,7 @@ OpenViking can act as the long-term memory and context backend for many agent ru| **OpenClaw** | [OpenClaw Plugin](./03-openclaw.md) — context-engine with full lifecycle integration || **Codex** | [Codex Memory Plugin](./04-codex.md) — lifecycle hooks for auto-recall and incremental capture || **Cursor** | [Cursor Memory Integration](./12-cursor.md) — one command installs lifecycle hooks, MCP tools, rules, and skills |-| **TRAE / TRAE CN** | [TRAE Memory Integration](./13-trae.md) — one installer configures prompt-time recall, turn capture, and OpenViking tools |+| **TRAE / TRAE CN / TRAE CLI** | [TRAE Memory Integration](./13-trae.md) — one installer configures prompt-time recall, turn capture, and OpenViking tools || **Hermes Agent** | [Hermes Agent](./05-hermes.md) — built-in OpenViking memory provider, no plugin install needed || **OpenCode** | [OpenCode Plugin](./10-opencode.md) — MCP tools plus lifecycle hooks for repo context, auto-recall, and capture || **pi** | [pi Coding Agent Extension](./11-pi.md) — native extension with auto-recall, turn capture, and threshold commit |diff --git a/docs/en/agent-integrations/13-trae.md b/docs/en/agent-integrations/13-trae.mdindex eb6459c96..8b73915c9 100644--- a/docs/en/agent-integrations/13-trae.md+++ b/docs/en/agent-integrations/13-trae.md@@ -1,10 +1,10 @@-# TRAE and TRAE CN Memory Integration+# TRAE, TRAE CN, and TRAE CLI Memory Integration-Give TRAE and TRAE CN long-term memory across projects and sessions. OpenViking Hooks automatically load relevant context, capture each conversation turn, and commit it for memory extraction. MCP remains available for explicit memory search, reading, and management.+Give TRAE, TRAE CN, and TRAE CLI long-term memory across projects and sessions. OpenViking Hooks automatically load relevant context, capture each conversation turn, and commit it for memory extraction. MCP remains available for explicit memory search, reading, and management.## Install-Prerequisites: macOS or Linux, Node.js 18+, and a TRAE/TRAE CN release that supports the `SessionStart`, `UserPromptSubmit`, `PreToolUse`, and `Stop` Hooks. The installer guides you through the OpenViking connection settings.+Prerequisites: macOS or Linux, Node.js 18+, and a TRAE/TRAE CN release that supports the `SessionStart`, `UserPromptSubmit`, `PreToolUse`, and `Stop` Hooks. TRAE CLI additionally needs a version that exposes those lifecycle hooks and can show its effective Hook and MCP sources through `/hooks` and `/mcp` (or `traecli mcp list`). The installer guides you through the OpenViking connection settings.When prompted for the connection, Volcengine Cloud users should select **Volcengine OpenViking Cloud** and enter their API key. Select **Self-hosted / local** only when an OpenViking server is running locally.@@ -20,6 +20,10 @@ bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/e# Bothbash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) \--harness trae,trae-cn++# TRAE CLI+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) \+ --harness trae-cli```If GitHub is unavailable, use the TOS mirror:@@ -27,6 +31,10 @@ If GitHub is unavailable, use the TOS mirror:```bashbash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) \--harness trae,trae-cn --dist tos++# TRAE CLI+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) \+ --harness trae-cli --dist tos```Quit and restart the corresponding client after installation.@@ -41,15 +49,17 @@ Quit and restart the corresponding client after installation.## Verify-1. Restart TRAE or TRAE CN and create a new Agent session.+1. Restart TRAE, TRAE CN, or TRAE CLI and create a new Agent session.2. Confirm that `openviking` is connected in the client's MCP settings.3. Ask about an existing project or preference and confirm that the answer uses stored memory.4. Tell the Agent a temporary preference, wait for the response to finish, then create a new session and ask for it again to verify capture, commit, and cross-session recall.+5. For TRAE CLI, use `/hooks` and `/mcp` (or `traecli mcp list`) to confirm that the client is consuming the installed user-level configuration. Treat the client's displayed source as authoritative if it differs from the default path.For Hook diagnostics, start the client with `OPENVIKING_DEBUG=1` and inspect:- TRAE: `~/.openviking/logs/trae-hooks.log`- TRAE CN: `~/.openviking/logs/trae-cn-hooks.log`+- TRAE CLI: `~/.openviking/logs/trae-cli-hooks.log`## Upgrade and uninstall@@ -65,7 +75,7 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar--harness trae-cn --uninstall --yes```-Replace `trae-cn` with `trae` for TRAE. Uninstall removes only OpenViking-managed configuration and runtime files.+Replace `trae-cn` with `trae` or `trae-cli` for TRAE or TRAE CLI. Uninstall removes only OpenViking-managed configuration and runtime files.## Troubleshooting@@ -75,6 +85,7 @@ Replace `trae-cn` with `trae` for TRAE. Uninstall removes only OpenViking-manage| MCP does not connect | Check the URL/API key in `~/.openviking/ovcli.conf`, then restart the client. || A new session cannot recall the previous turn | Inspect the Hook log and confirm that `Stop` ran without `/commit` connection or authentication errors. || The same content is captured more than once | Check user and project Hooks for older `trae-auto-recall.mjs` or `trae-auto-capture.mjs` entries. Re-running the installer removes OpenViking-managed legacy entries. |+| TRAE CLI does not list the hook or MCP server | Use `/hooks` and `/mcp` (or `traecli mcp list`) to identify the effective source. The CLI's reported config source takes precedence over the installer's default path. |## See alsodiff --git a/docs/zh/agent-integrations/01-overview.md b/docs/zh/agent-integrations/01-overview.mdindex 81f203b3a..d57452115 100644--- a/docs/zh/agent-integrations/01-overview.md+++ b/docs/zh/agent-integrations/01-overview.md@@ -10,7 +10,7 @@ OpenViking 可以作为多种 Agent 运行时的长期记忆与上下文后端| **OpenClaw** | [OpenClaw 插件](./03-openclaw.md) — 全生命周期一体化集成 || **Codex** | [Codex 记忆插件](./04-codex.md) — 生命周期 hooks 自动召回与增量捕获 || **Cursor** | [Cursor 记忆集成](./12-cursor.md) — 一条命令安装生命周期 Hook、MCP 工具、Rules 与 Skills |-| **TRAE / TRAE CN** | [TRAE 记忆集成](./13-trae.md) — 一个安装器完成 prompt 召回、回合捕获与 OpenViking 工具接入 |+| **TRAE / TRAE CN / TRAE CLI** | [TRAE 记忆集成](./13-trae.md) — 一个安装器完成 prompt 召回、回合捕获与 OpenViking 工具接入 || **Hermes Agent** | [Hermes Agent](./05-hermes.md) — 内置 OpenViking 记忆提供方,无需安装插件 || **OpenCode** | [OpenCode 插件](./10-opencode.md) — MCP 工具 + 生命周期 hooks,覆盖仓库上下文、自动召回与捕获 || **pi** | [pi Coding Agent 扩展](./11-pi.md) — 原生扩展,自动召回、逐轮捕获与阈值 commit |diff --git a/docs/zh/agent-integrations/13-trae.md b/docs/zh/agent-integrations/13-trae.mdindex e03db1e64..ee4848a19 100644--- a/docs/zh/agent-integrations/13-trae.md+++ b/docs/zh/agent-integrations/13-trae.md@@ -1,10 +1,10 @@-# TRAE 与 TRAE CN 记忆集成+# TRAE、TRAE CN 与 TRAE CLI 记忆集成-为 TRAE 和 TRAE CN 添加跨项目、跨会话的长期记忆。安装后,OpenViking Hook 会自动加载相关上下文、捕获每轮对话并提交给记忆抽取器;MCP 用于主动搜索、读取和管理记忆。+为 TRAE、TRAE CN 和 TRAE CLI 添加跨项目、跨会话的长期记忆。安装后,OpenViking Hook 会自动加载相关上下文、捕获每轮对话并提交给记忆抽取器;MCP 用于主动搜索、读取和管理记忆。## 安装-前置条件:macOS 或 Linux、Node.js 18+,以及支持 `SessionStart`、`UserPromptSubmit`、`PreToolUse`、`Stop` Hook 的 TRAE/TRAE CN 版本。安装过程中会引导配置 OpenViking 连接信息。+前置条件:macOS 或 Linux、Node.js 18+,以及支持 `SessionStart`、`UserPromptSubmit`、`PreToolUse`、`Stop` Hook 的 TRAE/TRAE CN 版本。TRAE CLI 还需要能够通过 `/hooks` 和 `/mcp`(或 `traecli mcp list`)显示生效 Hook 与 MCP 来源的版本。安装过程中会引导配置 OpenViking 连接信息。安装器询问连接方式时,火山引擎云服务用户请选择 **火山引擎 OpenViking 云服务** 并填写 API Key。只有本机已运行 OpenViking 服务时才选择 **自建 / 本地**。@@ -20,6 +20,10 @@ bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/e# 同时安装bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) \--harness trae,trae-cn++# TRAE CLI+bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) \+ --harness trae-cli```GitHub 访问受限时使用 TOS 镜像:@@ -27,6 +31,10 @@ GitHub 访问受限时使用 TOS 镜像:```bashbash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) \--harness trae,trae-cn --dist tos++# TRAE CLI+bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) \+ --harness trae-cli --dist tos```安装后完全退出并重启对应客户端。@@ -41,15 +49,17 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar## 验证-1. 重启 TRAE 或 TRAE CN,并新建 Agent 会话。+1. 重启 TRAE、TRAE CN 或 TRAE CLI,并新建 Agent 会话。2. 在客户端的 MCP 设置中确认 `openviking` 已连接。3. 提问一个与已有项目或个人偏好相关的问题,确认回答使用了已有记忆。4. 告诉 Agent 一个临时偏好,等待回复完成;新建会话后再次询问,确认捕获、提交和跨会话召回均生效。+5. 对 TRAE CLI,使用 `/hooks` 和 `/mcp`(或 `traecli mcp list`)确认客户端确实读取了安装后的用户级配置;若与默认路径不同,以客户端显示的有效来源为准。需要排查 Hook 时,设置 `OPENVIKING_DEBUG=1` 后启动客户端,并查看:- TRAE:`~/.openviking/logs/trae-hooks.log`- TRAE CN:`~/.openviking/logs/trae-cn-hooks.log`+- TRAE CLI:`~/.openviking/logs/trae-cli-hooks.log`## 升级与卸载@@ -65,7 +75,7 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar--harness trae-cn --uninstall --yes```-将 `trae-cn` 替换为 `trae` 可管理 TRAE 集成。卸载只移除 OpenViking 管理的配置与运行文件。+将 `trae-cn` 替换为 `trae` 或 `trae-cli` 可管理 TRAE 或 TRAE CLI 集成。卸载只移除 OpenViking 管理的配置与运行文件。## 故障排查@@ -75,6 +85,7 @@ bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shar| MCP 未连接 | 检查 `~/.openviking/ovcli.conf` 中的 URL/API Key,然后重启客户端。 || 新会话无法回忆上一轮内容 | 查看 Hook 日志,确认 `Stop` 已执行且 `/commit` 没有连接或鉴权错误。 || 同一内容被捕获多次 | 检查用户级与项目级 Hook 中是否仍有旧版 `trae-auto-recall.mjs` 或 `trae-auto-capture.mjs`;重跑安装器会移除由 OpenViking 管理的旧条目。 |+| TRAE CLI 未列出 Hook 或 MCP Server | 用 `/hooks` 和 `/mcp`(或 `traecli mcp list`)查看有效配置来源;客户端显示的来源优先于安装器默认路径。 |## 参见diff --git a/examples/memory-plugin-shared/install-agent-hooks.test.mjs b/examples/memory-plugin-shared/install-agent-hooks.test.mjsindex 4795051dd..1c2ddf222 100644--- a/examples/memory-plugin-shared/install-agent-hooks.test.mjs+++ b/examples/memory-plugin-shared/install-agent-hooks.test.mjs@@ -43,6 +43,122 @@ function runUninstall(home) {assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);}+test("TRAE CLI install preserves unrelated config and is idempotent", () => {+ const home = mkdtempSync(join(tmpdir(), "openviking-trae-cli-hooks-"));+ try {+ const hooksPath = join(home, ".trae", "cli", "hooks.json");+ const configPath = join(home, ".trae", "traecli.toml");+ writeJson(hooksPath, {+ version: 1,+ hooks: {+ Stop: [+ { hooks: [{ type: "command", command: "third-party stop" }] },+ {+ hooks: [{+ type: "command",+ command: "node /tmp/OpenViking/examples/trae-memory-hooks/scripts/auto-capture.mjs trae",+ }],+ },+ ],+ },+ });+ mkdirSync(dirname(configPath), { recursive: true });+ writeFileSync(configPath, [+ 'model = "test-model"',+ "",+ "[mcp_servers.third_party]",+ 'url = "https://example.com/mcp"',+ "",+ "[mcp_servers.openviking]",+ 'command = "node"',+ 'args = ["/tmp/OpenViking/examples/trae-memory-hooks/servers/mcp-proxy.mjs"]',+ "",+ "[mcp_servers.openviking.tools.read]",+ 'approval_mode = "approve"',+ "",+ ].join("\n"));++ runInstall(home, "trae-cli");+ runInstall(home, "trae-cli");++ const hooks = JSON.parse(readFileSync(hooksPath, "utf8"));+ assert.ok(hooks.hooks.Stop.some((entry) => JSON.stringify(entry).includes("third-party stop")));+ assert.equal(+ hooks.hooks.Stop.filter((entry) => JSON.stringify(entry).includes("auto-capture.mjs")).length,+ 1,+ );+ assert.equal(+ hooks.hooks.SessionStart.filter((entry) => JSON.stringify(entry).includes("session-start.mjs")).length,+ 1,+ );+ assert.equal(+ hooks.hooks.UserPromptSubmit.filter((entry) => JSON.stringify(entry).includes("auto-recall.mjs")).length,+ 1,+ );+ assert.equal(+ hooks.hooks.PreToolUse.filter((entry) => JSON.stringify(entry).includes("uri-guard.mjs")).length,+ 1,+ );+ assert.ok(JSON.stringify(hooks).includes("OPENVIKING_HOOK_SOURCE='trae-cli'"));++ const config = readFileSync(configPath, "utf8");+ assert.match(config, /model = "test-model"/);+ assert.match(config, /\[mcp_servers\.third_party\]/);+ assert.equal((config.match(/^\[mcp_servers\."openviking-memory"\]$/gmu) || []).length, 1);+ assert.doesNotMatch(config, /^\[mcp_servers\.openviking\]$/mu);+ assert.doesNotMatch(config, /^\[mcp_servers\.openviking\.tools\.read\]$/mu);+ assert.match(config, /agent-integrations\/trae-cli\/servers\/mcp-proxy\.mjs/);++ const integrationRoot = join(home, ".openviking", "agent-integrations", "trae-cli");+ const manifest = JSON.parse(readFileSync(join(integrationRoot, "integration.json"), "utf8"));+ assert.equal(manifest.id, "openviking-memory");+ assert.equal(manifest.client, "trae-cli");+ assert.equal(manifest.hooksConfig, hooksPath);+ assert.equal(manifest.mcpConfig, configPath);++ const smoke = spawnSync(process.execPath, [join(integrationRoot, "scripts", "session-start.mjs")], {+ env: { ...process.env, HOME: home, OPENVIKING_MEMORY_ENABLED: "0" },+ input: "{}",+ encoding: "utf8",+ });+ assert.equal(smoke.status, 0, smoke.stderr);+ assert.equal(smoke.stdout.trim(), "{}");++ const guard = spawnSync(process.execPath, [join(integrationRoot, "scripts", "uri-guard.mjs")], {+ env: { ...process.env, HOME: home },+ input: JSON.stringify({+ tool_name: "Read",+ tool_input: { file_path: "viking://resources/project/file.md" },+ }),+ encoding: "utf8",+ });+ assert.equal(guard.status, 0, guard.stderr);+ assert.match(guard.stdout, /"permissionDecision":"deny"/);++ const uninstall = runInstaller(home, [+ "--harness", "trae-cli",+ "--uninstall",+ "--yes",+ ]);+ assert.equal(uninstall.status, 0, `${uninstall.stdout}\n${uninstall.stderr}`);++ const hooksAfter = JSON.parse(readFileSync(hooksPath, "utf8"));+ assert.ok(hooksAfter.hooks.Stop.some((entry) => JSON.stringify(entry).includes("third-party stop")));+ assert.equal(JSON.stringify(hooksAfter).includes("openviking-memory"), false);+ const configAfter = readFileSync(configPath, "utf8");+ assert.match(configAfter, /model = "test-model"/);+ assert.match(configAfter, /\[mcp_servers\.third_party\]/);+ assert.doesNotMatch(configAfter, /openviking-memory/);+ assert.equal(existsSync(integrationRoot), false);+ assert.equal(+ existsSync(join(home, ".openviking", "agent-integrations", "memory-plugin-shared")),+ false,+ );+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+});+test("combined Cursor and TRAE install preserves unrelated hooks and is idempotent", () => {const home = mkdtempSync(join(tmpdir(), "openviking-agent-hooks-"));try {diff --git a/examples/memory-plugin-shared/install-tui.test.mjs b/examples/memory-plugin-shared/install-tui.test.mjsindex 41f4fc214..05b379b09 100644--- a/examples/memory-plugin-shared/install-tui.test.mjs+++ b/examples/memory-plugin-shared/install-tui.test.mjs@@ -1,6 +1,8 @@import assert from "node:assert/strict";import { spawnSync } from "node:child_process";-import { readFileSync } from "node:fs";+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";import { fileURLToPath } from "node:url";import test from "node:test";@@ -18,6 +20,12 @@ function runInstallerPrelude(body) {});}+function makeTempHome(t) {+ const home = mkdtempSync(join(tmpdir(), "openviking-trae-"));+ t.after(() => rmSync(home, { recursive: true, force: true }));+ return home;+}+test("finishing TUI selection succeeds when the final harness is not selected", () => {const result = runInstallerPrelude(`SEL_CLAUDE_BINS=claude@@ -49,3 +57,70 @@ installer_test_failureassert.match(result.stderr, /Script line: [0-9]+/);assert.match(result.stderr, /Command: false/);});++test("a pre-existing TRAE home directory keeps TRAE Desktop as the default", (t) => {+ const home = makeTempHome(t);+ mkdirSync(join(home, ".trae"));++ const result = runInstallerPrelude(`+PATH=/usr/bin:/bin+HOME=${JSON.stringify(home)}+refresh_available_harnesses+INTERACTIVE=0+REQUESTED_HARNESSES=""+select_harnesses+printf '%s:%s\\n' "$HAVE_TRAE" "$SELECTED_HARNESSES"+`);++ assert.equal(result.status, 0, result.stderr);+ assert.equal(result.stdout.trim(), "1:trae");+});++test("TRAE CLI configuration does not auto-select the TRAE CLI harness", (t) => {+ const home = makeTempHome(t);+ const cliHome = join(home, ".trae", "cli");+ mkdirSync(cliHome, { recursive: true });+ writeFileSync(join(cliHome, "hooks.json"), "{}\n");++ const result = runInstallerPrelude(`+PATH=/usr/bin:/bin+HOME=${JSON.stringify(home)}+refresh_available_harnesses+INTERACTIVE=0+REQUESTED_HARNESSES=""+select_harnesses+printf '%s\\n' "$SELECTED_HARNESSES"+`);++ assert.equal(result.status, 0, result.stderr);+ assert.equal(result.stdout.trim(), "trae");+});++test("TRAE CLI command aliases are detected and auto-selected", (t) => {+ const home = makeTempHome(t);+ const cliHome = join(home, ".trae", "cli");+ mkdirSync(cliHome, { recursive: true });+ writeFileSync(join(cliHome, "hooks.json"), "{}\n");+ for (const command of ["traecli", "traex"]) {+ const bin = join(home, `bin-${command}`);+ mkdirSync(bin);+ writeFileSync(join(bin, command), "#!/bin/sh\nexit 0\n");+ chmodSync(join(bin, command), 0o755);++ const result = runInstallerPrelude(`+PATH=${JSON.stringify(`${bin}:/usr/bin:/bin`)}+HOME=${JSON.stringify(home)}+refresh_available_harnesses+tui_reset_bin_selection+selected_in_tui="$SEL_TRAE_CLI"+INTERACTIVE=0+REQUESTED_HARNESSES=""+select_harnesses+if tui_bin_detected trae-cli traecli; then detected=yes; else detected=no; fi+printf '%s:%s:%s\\n' "$selected_in_tui" "$SELECTED_HARNESSES" "$detected"+`);++ assert.equal(result.status, 0, result.stderr);+ assert.equal(result.stdout.trim(), "1:trae,trae-cli:yes", command);+ }+});diff --git a/examples/memory-plugin-shared/install.sh b/examples/memory-plugin-shared/install.shindex f3046eafd..d521e98bc 100644--- a/examples/memory-plugin-shared/install.sh+++ b/examples/memory-plugin-shared/install.sh@@ -1,14 +1,14 @@#!/usr/bin/env bash## OpenViking Memory Plugin shared installer for Claude Code, Codex, Cursor,-# TRAE / TRAE CN, ZCode, OpenCode, and pi.+# TRAE / TRAE CN, TRAE CLI, ZCode, OpenCode, and pi.## One-liner (GitHub):# bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh)# One-liner (TOS mirror, for regions where GitHub is unreachable):# bash <(curl -fsSL https://ovrelease.tos-cn-beijing.volces.com/memory-plugin-shared/install.sh) --dist tos# Non-interactive:-# bash install.sh --harness claude,codex,cursor,trae,trae-cn,zcode,opencode,pi --dist github --lang en --url http://127.0.0.1:1933 --api-key ''+# bash install.sh --harness claude,codex,cursor,trae,trae-cn,trae-cli,zcode,opencode,pi --dist github --lang en --url http://127.0.0.1:1933# Format-compatible CLI aliases:# bash install.sh --harness codex --codex-bin codex,traex# bash install.sh --harness claude --claude-bin claude,seed@@ -143,7 +143,7 @@ usage() {Usage: install.sh [options]Options:- --harness LIST Comma-separated harnesses: claude, codex, cursor, trae, trae-cn, zcode, opencode, pi.+ --harness LIST Comma-separated harnesses: claude, codex, cursor, trae, trae-cn, trae-cli, zcode, opencode, pi.--claude-bin LIST Comma-separated Claude-format CLI commands (default: claude).--codex-bin LIST Comma-separated Codex-format CLI commands (default: codex).--dist CHANNEL github (default) | tos (mirror for GitHub-blocked regions).@@ -369,12 +369,13 @@ EOF}refresh_available_harnesses() {- HAVE_CLAUDE=0; HAVE_CODEX=0; HAVE_CURSOR=0; HAVE_TRAE=0; HAVE_TRAE_CN=0; HAVE_OPENCODE=0; HAVE_PI=0; HAVE_ZCODE=0+ HAVE_CLAUDE=0; HAVE_CODEX=0; HAVE_CURSOR=0; HAVE_TRAE=0; HAVE_TRAE_CN=0; HAVE_TRAE_CLI=0; HAVE_OPENCODE=0; HAVE_PI=0; HAVE_ZCODE=0has_available_bin "$CLAUDE_BINS" && HAVE_CLAUDE=1has_available_bin "$CODEX_BINS" && HAVE_CODEX=1{ command -v cursor >/dev/null 2>&1 || command -v cursor-agent >/dev/null 2>&1 || [ -d "/Applications/Cursor.app" ] || [ -d "$HOME/.cursor" ]; } && HAVE_CURSOR=1{ [ -d "/Applications/Trae.app" ] || [ -d "/Applications/TRAE.app" ] || [ -d "$HOME/.trae" ]; } && HAVE_TRAE=1{ [ -d "/Applications/Trae CN.app" ] || [ -d "/Applications/TRAE SOLO CN.app" ] || [ -d "$HOME/.trae-cn" ]; } && HAVE_TRAE_CN=1+ { command -v traecli >/dev/null 2>&1 || command -v traex >/dev/null 2>&1; } && HAVE_TRAE_CLI=1command -v opencode >/dev/null 2>&1 && HAVE_OPENCODE=1command -v pi >/dev/null 2>&1 && HAVE_PI=1{ command -v zcode >/dev/null 2>&1 || [ -d "$HOME/.zcode" ]; } && HAVE_ZCODE=1@@ -444,7 +445,7 @@ NODECLAUDE_BINS="$(normalize_bin_list "$CLAUDE_BINS_ARG" claude)"CODEX_BINS="$(normalize_bin_list "$CODEX_BINS_ARG" codex)"-HAVE_CLAUDE=0; HAVE_CODEX=0; HAVE_CURSOR=0; HAVE_TRAE=0; HAVE_TRAE_CN=0; HAVE_OPENCODE=0; HAVE_PI=0; HAVE_ZCODE=0+HAVE_CLAUDE=0; HAVE_CODEX=0; HAVE_CURSOR=0; HAVE_TRAE=0; HAVE_TRAE_CN=0; HAVE_TRAE_CLI=0; HAVE_OPENCODE=0; HAVE_PI=0; HAVE_ZCODE=0refresh_available_harnessesTUI_CLAUDE_BINS="$CLAUDE_BINS"@@ -456,6 +457,7 @@ SEL_PI=0SEL_CURSOR_APP=0SEL_TRAE=0SEL_TRAE_CN=0+SEL_TRAE_CLI=0SEL_ZCODE=0TUI_CURSOR=0; TUI_LINES=0@@ -470,7 +472,7 @@ EOF}tui_selectable_count() {- printf '%s' $(( $(list_count "$TUI_CLAUDE_BINS") + $(list_count "$TUI_CODEX_BINS") + 6 ))+ printf '%s' $(( $(list_count "$TUI_CLAUDE_BINS") + $(list_count "$TUI_CODEX_BINS") + 7 ))}tui_total_count() {@@ -503,6 +505,8 @@ EOFi=$((i + 1))if [ "$i" -eq "$idx" ]; then printf 'trae-cn|trae-cn'; return 0; fii=$((i + 1))+ if [ "$i" -eq "$idx" ]; then printf 'trae-cli|trae-cli'; return 0; fi+ i=$((i + 1))if [ "$i" -eq "$idx" ]; then printf 'zcode|zcode'; return 0; fiprintf 'add|'}@@ -533,6 +537,7 @@ tui_bin_label() {cursor:*) printf 'Cursor' ;;trae:*) printf 'TRAE' ;;trae-cn:*) printf 'TRAE CN' ;;+ trae-cli:*) printf 'TRAE CLI' ;;zcode:*) printf 'ZCode' ;;claude:*) printf '%s %s' "$bin" "$(t '(Claude-format)' '(Claude 格式)')" ;;codex:*) printf '%s %s' "$bin" "$(t '(Codex-format)' '(Codex 格式)')" ;;@@ -553,10 +558,12 @@ tui_bin_selected() {[ "$SEL_CURSOR_APP" -eq 1 ]elif [ "$kind" = "trae" ]; then[ "$SEL_TRAE" -eq 1 ]- elif [ "$kind" = "zcode" ]; then- [ "$SEL_ZCODE" -eq 1 ]- else+ elif [ "$kind" = "trae-cn" ]; then[ "$SEL_TRAE_CN" -eq 1 ]+ elif [ "$kind" = "trae-cli" ]; then+ [ "$SEL_TRAE_CLI" -eq 1 ]+ else+ [ "$SEL_ZCODE" -eq 1 ]fi}@@ -565,6 +572,7 @@ tui_bin_detected() { # tui_bin_detected <kind> <bin>cursor) [ "$HAVE_CURSOR" -eq 1 ] ;;trae) [ "$HAVE_TRAE" -eq 1 ] ;;trae-cn) [ "$HAVE_TRAE_CN" -eq 1 ] ;;+ trae-cli) [ "$HAVE_TRAE_CLI" -eq 1 ] ;;zcode) [ "$HAVE_ZCODE" -eq 1 ] ;;*) command -v "$2" >/dev/null 2>&1 ;;esac@@ -578,6 +586,7 @@ tui_set_all_bins() {SEL_CURSOR_APP=1SEL_TRAE=1SEL_TRAE_CN=1+ SEL_TRAE_CLI=1SEL_ZCODE=1}@@ -597,10 +606,12 @@ tui_toggle_bin() {SEL_CURSOR_APP=$((1 - SEL_CURSOR_APP)); return 0elif [ "$kind" = "trae" ]; thenSEL_TRAE=$((1 - SEL_TRAE)); return 0- elif [ "$kind" = "zcode" ]; then- SEL_ZCODE=$((1 - SEL_ZCODE)); return 0- else+ elif [ "$kind" = "trae-cn" ]; thenSEL_TRAE_CN=$((1 - SEL_TRAE_CN)); return 0+ elif [ "$kind" = "trae-cli" ]; then+ SEL_TRAE_CLI=$((1 - SEL_TRAE_CLI)); return 0+ else+ SEL_ZCODE=$((1 - SEL_ZCODE)); return 0fiif list_contains_line "$selected" "$bin"; thenwhile IFS= read -r item; do@@ -669,6 +680,7 @@ tui_reset_bin_selection() {SEL_CURSOR_APP=0SEL_TRAE=0SEL_TRAE_CN=0+ SEL_TRAE_CLI=0SEL_ZCODE=0while IFS= read -r bin; do[ -n "$bin" ] || continue@@ -693,6 +705,7 @@ EOFif [ "$HAVE_CURSOR" -eq 1 ]; then SEL_CURSOR_APP=1; any=1; fiif [ "$HAVE_TRAE" -eq 1 ]; then SEL_TRAE=1; any=1; fiif [ "$HAVE_TRAE_CN" -eq 1 ]; then SEL_TRAE_CN=1; any=1; fi+ if [ "$HAVE_TRAE_CLI" -eq 1 ]; then SEL_TRAE_CLI=1; any=1; fiif [ "$HAVE_ZCODE" -eq 1 ]; then SEL_ZCODE=1; any=1; fiif [ "$any" -ne 1 ]; thenSEL_CLAUDE_BINS="$TUI_CLAUDE_BINS"@@ -781,7 +794,7 @@ tui_add_compatible_cli() {tui_has_selection() {[ -n "$(list_words "$SEL_CLAUDE_BINS")" ] || [ -n "$(list_words "$SEL_CODEX_BINS")" ] \|| [ "$SEL_OPENCODE" -eq 1 ] || [ "$SEL_PI" -eq 1 ] || [ "$SEL_CURSOR_APP" -eq 1 ] \- || [ "$SEL_TRAE" -eq 1 ] || [ "$SEL_TRAE_CN" -eq 1 ] || [ "$SEL_ZCODE" -eq 1 ]+ || [ "$SEL_TRAE" -eq 1 ] || [ "$SEL_TRAE_CN" -eq 1 ] || [ "$SEL_TRAE_CLI" -eq 1 ] || [ "$SEL_ZCODE" -eq 1 ]}tui_finish_selection() {@@ -795,6 +808,7 @@ tui_finish_selection() {[ "$SEL_CURSOR_APP" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}cursor"[ "$SEL_TRAE" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}trae"[ "$SEL_TRAE_CN" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}trae-cn"+ [ "$SEL_TRAE_CLI" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}trae-cli"[ "$SEL_ZCODE" -eq 1 ] && SELECTED_HARNESSES="${SELECTED_HARNESSES:+$SELECTED_HARNESSES,}zcode"return 0}@@ -864,6 +878,7 @@ select_harnesses() {[ "$HAVE_CURSOR" -eq 1 ] && detected="${detected:+$detected,}cursor"[ "$HAVE_TRAE" -eq 1 ] && detected="${detected:+$detected,}trae"[ "$HAVE_TRAE_CN" -eq 1 ] && detected="${detected:+$detected,}trae-cn"+ [ "$HAVE_TRAE_CLI" -eq 1 ] && detected="${detected:+$detected,}trae-cli"[ "$HAVE_OPENCODE" -eq 1 ] && detected="${detected:+$detected,}opencode"[ "$HAVE_PI" -eq 1 ] && detected="${detected:+$detected,}pi"[ "$HAVE_ZCODE" -eq 1 ] && detected="${detected:+$detected,}zcode"@@ -912,7 +927,7 @@ validate_selected_harnesses() {local h bad=0while IFS= read -r h; docase "$h" in- claude|codex|cursor|trae|trae-cn|opencode|pi|zcode) ;;+ claude|codex|cursor|trae|trae-cn|trae-cli|opencode|pi|zcode) ;;*) err "Unsupported harness: $h"; bad=1 ;;esacdone <<EOF@@ -951,7 +966,7 @@ EOFif contains_harness pi && command -v pi >/dev/null 2>&1; then ok=1; fi# Cursor and TRAE are config-driven integrations. They may be installed# before the desktop app itself, so a CLI in PATH is not required.- if contains_harness cursor || contains_harness trae || contains_harness trae-cn || contains_harness zcode; then ok=1; fi+ if contains_harness cursor || contains_harness trae || contains_harness trae-cn || contains_harness trae-cli || contains_harness zcode; then ok=1; fiif [ "$ok" -ne 1 ]; thenerr "$(t 'No selected compatible CLI command was found in PATH.' '未在 PATH 中找到任何已选择的兼容 CLI 命令。')"exit 2@@ -1950,6 +1965,208 @@ atomicWrite(installedManifestPath, {NODE}+agent_write_trae_cli_configs() { # agent_write_trae_cli_configs <hooks> <traecli.toml> <root> <node-bin>+ local hooks_path="$1" config_path="$2" root="$3" node_bin="$4"+ "$NODE_BIN" - "$hooks_path" "$config_path" "$root" "$node_bin" "$SOURCE_MODE" <<'NODE'+const fs = require("node:fs");+const path = require("node:path");+const [hooksPath, configPath, root, nodeBin, sourceMode] = process.argv.slice(2);+const clientId = "trae-cli";+const serverName = "openviking-memory";++function readJson(file) {+ if (!fs.existsSync(file)) return {};+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ throw new Error(`${file} top-level value must be an object`);+ }+ return parsed;+}++function atomicWrite(file, content) {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ let previous = "";+ try { previous = fs.readFileSync(file, "utf8"); } catch {}+ if (previous === content) return;+ if (previous) fs.writeFileSync(`${file}.bak`, previous, { mode: 0o600 });+ const tmp = `${file}.${process.pid}.tmp`;+ fs.writeFileSync(tmp, content, { mode: 0o600 });+ fs.renameSync(tmp, file);+}++function shellArg(value) {+ return `'${String(value).replace(/'/g, `'"'"'`)}'`;+}++function isOpenVikingHook(value) {+ const text = JSON.stringify(value || {}).toLowerCase();+ return text.includes("openviking_integration_id")+ || (text.includes("openviking") && [+ "trae-cli-hook.mjs",+ "session-start.mjs",+ "auto-recall.mjs",+ "auto-capture.mjs",+ "uri-guard.mjs",+ ].some((name) => text.includes(name)));+}++function stripTomlSections(content, prefix) {+ const lines = String(content || "").split(/\r?\n/u);+ const out = [];+ let skipping = false;+ for (const line of lines) {+ const match = /^\s*\[([^\]]+)\]\s*$/u.exec(line);+ if (match) skipping = match[1] === prefix || match[1].startsWith(`${prefix}.`);+ if (!skipping) out.push(line);+ }+ return out.join("\n").replace(/\n{3,}/gu, "\n\n").trimEnd();+}++function stripLegacyOpenVikingServer(content) {+ const lines = String(content || "").split(/\r?\n/u);+ for (let index = 0; index < lines.length; index += 1) {+ const match = /^\s*\[([^\]]+)\]\s*$/u.exec(lines[index]);+ if (!match || !["mcp_servers.openviking", 'mcp_servers."openviking"'].includes(match[1])) continue;+ let end = index + 1;+ while (end < lines.length && !/^\s*\[[^\]]+\]\s*$/u.test(lines[end])) end += 1;+ const block = lines.slice(index, end).join("\n").toLowerCase();+ if (block.includes("mcp-proxy.mjs") && block.includes("openviking")) {+ return stripTomlSections(content, match[1]);+ }+ }+ return content;+}++const manifest = readJson(path.join(root, "openviking.integration.json"));+if (manifest.id !== "openviking-memory" || !manifest.clients?.includes(clientId)) {+ throw new Error("Invalid OpenViking TRAE CLI integration manifest");+}+const integrationEnv = {+ OPENVIKING_INTEGRATION_ID: manifest.id,+ OPENVIKING_INTEGRATION_VERSION: manifest.version,+ OPENVIKING_HOOK_SOURCE: clientId,+};+const envPrefix = Object.entries(integrationEnv)+ .map(([key, value]) => `${key}=${shellArg(value)}`)+ .join(" ");++function renderHookValue(value) {+ if (Array.isArray(value)) return value.map(renderHookValue);+ if (!value || typeof value !== "object") return value;+ return Object.fromEntries(Object.entries(value).map(([key, child]) => {+ if (key !== "command" || typeof child !== "string") {+ return [key, renderHookValue(child)];+ }+ const match = /^node\s+__OPENVIKING_TRAE_CLI_ROOT__\/(\S+)$/u.exec(child);+ if (!match) throw new Error(`Unsupported TRAE CLI hook command template: ${child}`);+ const command = `${shellArg(nodeBin)} ${shellArg(path.join(root, match[1]))}`;+ return [key, `${envPrefix} ${command} # openviking-memory`];+ }));+}++const hookTemplate = readJson(path.join(root, "hooks", "hooks.json"));+const hooksConfig = readJson(hooksPath);+hooksConfig.version = Number.isFinite(Number(hooksConfig.version)) ? Number(hooksConfig.version) : 1;+hooksConfig.hooks = hooksConfig.hooks && typeof hooksConfig.hooks === "object"+ ? hooksConfig.hooks : {};+for (const [event, entries] of Object.entries(hookTemplate.hooks || {})) {+ const current = Array.isArray(hooksConfig.hooks[event]) ? hooksConfig.hooks[event] : [];+ hooksConfig.hooks[event] = [+ ...current.filter((item) => !isOpenVikingHook(item)),+ ...renderHookValue(entries),+ ];+}+atomicWrite(hooksPath, `${JSON.stringify(hooksConfig, null, 2)}\n`);++let toml = "";+try { toml = fs.readFileSync(configPath, "utf8"); } catch {}+toml = stripLegacyOpenVikingServer(toml);+toml = stripTomlSections(toml, `mcp_servers."${serverName}"`);+const envToml = Object.entries(integrationEnv)+ .map(([key, value]) => `${key} = ${JSON.stringify(value)}`)+ .join(", ");+const section = [+ `[mcp_servers."${serverName}"]`,+ `command = ${JSON.stringify(nodeBin)}`,+ `args = [${JSON.stringify(path.join(root, "servers", "mcp-proxy.mjs"))}]`,+ `env = { ${envToml} }`,+].join("\n");+atomicWrite(configPath, `${toml ? `${toml}\n\n` : ""}${section}\n`);++const manifestPath = path.join(root, "integration.json");+const previous = readJson(manifestPath);+const now = new Date().toISOString();+const unchanged = previous.version === manifest.version+ && previous.source === sourceMode+ && previous.hooksConfig === hooksPath+ && previous.mcpConfig === configPath;+atomicWrite(manifestPath, `${JSON.stringify({+ schemaVersion: 1,+ id: manifest.id,+ version: manifest.version,+ client: clientId,+ installMode: "managed-native",+ source: sourceMode,+ capabilities: manifest.capabilities,+ hooksConfig: hooksPath,+ mcpConfig: configPath,+ installedAt: previous.installedAt || now,+ updatedAt: unchanged ? previous.updatedAt || previous.installedAt || now : now,+}, null, 2)}\n`);+NODE+}++agent_remove_trae_cli_configs() { # agent_remove_trae_cli_configs <hooks> <traecli.toml>+ local hooks_path="$1" config_path="$2"+ "$NODE_BIN" - "$hooks_path" "$config_path" <<'NODE'+const fs = require("node:fs");+const path = require("node:path");+const [hooksPath, configPath] = process.argv.slice(2);++function atomicWrite(file, content) {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const tmp = `${file}.${process.pid}.tmp`;+ fs.writeFileSync(tmp, content, { mode: 0o600 });+ fs.renameSync(tmp, file);+}++function ownsHook(value) {+ const text = JSON.stringify(value || {}).toLowerCase();+ return text.includes("openviking_integration_id")+ || (text.includes("openviking") && [+ "trae-cli-hook.mjs",+ "session-start.mjs",+ "auto-recall.mjs",+ "auto-capture.mjs",+ "uri-guard.mjs",+ ].some((name) => text.includes(name)));+}++if (fs.existsSync(hooksPath)) {+ const hooks = JSON.parse(fs.readFileSync(hooksPath, "utf8"));+ for (const event of Object.keys(hooks.hooks || {})) {+ if (!Array.isArray(hooks.hooks[event])) continue;+ hooks.hooks[event] = hooks.hooks[event].filter((item) => !ownsHook(item));+ if (hooks.hooks[event].length === 0) delete hooks.hooks[event];+ }+ atomicWrite(hooksPath, `${JSON.stringify(hooks, null, 2)}\n`);+}++if (fs.existsSync(configPath)) {+ const lines = fs.readFileSync(configPath, "utf8").split(/\r?\n/u);+ const prefix = 'mcp_servers."openviking-memory"';+ const out = [];+ let skipping = false;+ for (const line of lines) {+ const match = /^\s*\[([^\]]+)\]\s*$/u.exec(line);+ if (match) skipping = match[1] === prefix || match[1].startsWith(`${prefix}.`);+ if (!skipping) out.push(line);+ }+ atomicWrite(configPath, `${out.join("\n").replace(/\n{3,}/gu, "\n\n").trimEnd()}\n`);+}+NODE+}+agent_remove_json_configs() { # agent_remove_json_configs <hooks> <mcp>local hooks_path="$1" mcp_path="$2""$NODE_BIN" - "$hooks_path" "$mcp_path" <<'NODE'@@ -2027,6 +2244,13 @@ uninstall_agent_integrations() {rm -rf "$OV_HOME/agent-integrations/trae-cn"info "$(t 'Removed TRAE CN OpenViking hooks and MCP config.' '已移除 TRAE CN OpenViking hooks 与 MCP 配置。')"fi+ if contains_harness trae-cli; then+ local trae_home="${TRAE_HOME:-$HOME/.trae}"+ local trae_cli_home="${TRAECLI_HOME:-$trae_home/cli}"+ agent_remove_trae_cli_configs "$trae_cli_home/hooks.json" "$trae_home/traecli.toml"+ rm -rf "$OV_HOME/agent-integrations/trae-cli"+ info "$(t 'Removed TRAE CLI OpenViking hooks and MCP config.' '已移除 TRAE CLI OpenViking hooks 与 MCP 配置。')"+ fiif contains_harness zcode; then# ZCode reads hooks/MCP from config.json, not standalone files.# Use a node script to strip openviking entries from config.json.@@ -2073,6 +2297,7 @@ CLEAN_NODEif [ ! -d "$OV_HOME/agent-integrations/cursor" ] \&& [ ! -d "$OV_HOME/agent-integrations/trae" ] \&& [ ! -d "$OV_HOME/agent-integrations/trae-cn" ] \+ && [ ! -d "$OV_HOME/agent-integrations/trae-cli" ] \&& [ ! -d "$OV_HOME/agent-integrations/zcode" ]; thenrm -rf "$OV_HOME/agent-integrations/memory-plugin-shared"fi@@ -2238,6 +2463,19 @@ install_trae_variant() { # install_trae_variant <trae|trae-cn>info "$client_id MCP: $mcp_path"}+install_trae_cli() {+ heading "$(t 'TRAE CLI integration' 'TRAE CLI 集成')"+ local root trae_home trae_cli_home hooks_path config_path+ root="$(assemble_agent_integration trae-cli-memory-hooks trae-cli)" || return 1+ trae_home="${TRAE_HOME:-$HOME/.trae}"+ trae_cli_home="${TRAECLI_HOME:-$trae_home/cli}"+ hooks_path="$trae_cli_home/hooks.json"+ config_path="$trae_home/traecli.toml"+ agent_write_trae_cli_configs "$hooks_path" "$config_path" "$root" "$NODE_BIN"+ info "$(t 'TRAE CLI hooks installed:' 'TRAE CLI hooks 已安装:') $hooks_path"+ info "$(t 'TRAE CLI MCP installed:' 'TRAE CLI MCP 已安装:') $config_path (mcp_servers.openviking-memory)"+}+# ---------------------------------------------------------------------------# OpenCode# ---------------------------------------------------------------------------@@ -2818,6 +3056,36 @@ EOFok=0; agent_fatal=1fifi+ if contains_harness trae-cli; then+ local trae_home="${TRAE_HOME:-$HOME/.trae}"+ local trae_cli_home="${TRAECLI_HOME:-$trae_home/cli}"+ local trae_cli_hooks="$trae_cli_home/hooks.json"+ local trae_cli_config="$trae_home/traecli.toml"+ if grep -q 'scripts/session-start.mjs' "$trae_cli_hooks" 2>/dev/null \+ && grep -q 'scripts/auto-recall.mjs' "$trae_cli_hooks" 2>/dev/null \+ && grep -q 'scripts/auto-capture.mjs' "$trae_cli_hooks" 2>/dev/null \+ && grep -q 'scripts/uri-guard.mjs' "$trae_cli_hooks" 2>/dev/null \+ && grep -q 'OPENVIKING_INTEGRATION_ID' "$trae_cli_hooks" 2>/dev/null \+ && grep -q '\[mcp_servers."openviking-memory"\]' "$trae_cli_config" 2>/dev/null \+ && grep -q 'mcp-proxy.mjs' "$trae_cli_config" 2>/dev/null \+ && [ -f "$OV_HOME/agent-integrations/trae-cli/scripts/trae-cli-hook.mjs" ] \+ && [ -f "$OV_HOME/agent-integrations/trae-cli/scripts/uri-guard.mjs" ] \+ && [ -f "$OV_HOME/agent-integrations/trae-cli/integration.json" ]; then+ "$NODE_BIN" --check "$OV_HOME/agent-integrations/trae-cli/scripts/trae-cli-hook.mjs" \+ || { ok=0; agent_fatal=1; }+ "$NODE_BIN" --check "$OV_HOME/agent-integrations/trae-cli/scripts/uri-guard.mjs" \+ || { ok=0; agent_fatal=1; }+ if ! printf '%s' '{}' | env HOME="$HOME" OPENVIKING_MEMORY_ENABLED=0 \+ "$NODE_BIN" "$OV_HOME/agent-integrations/trae-cli/scripts/session-start.mjs" >/dev/null; then+ warn "trae-cli: $(t 'installed Hook runtime failed its smoke test' '已安装的 Hook 运行时 smoke test 失败')"+ ok=0; agent_fatal=1+ fi+ info "trae-cli: $(t 'hooks and MCP are configured' 'hooks 与 MCP 已配置')"+ else+ warn "trae-cli: $(t 'OpenViking hook or MCP config is incomplete' 'OpenViking hook 或 MCP 配置不完整')"+ ok=0; agent_fatal=1+ fi+ fiif contains_harness zcode; thenlocal zcode_config="$HOME/.zcode/cli/config.json"if grep -q 'scripts/session-start.mjs' "$zcode_config" 2>/dev/null \@@ -2962,6 +3230,7 @@ fiif contains_harness cursor; then install_cursor; fiif contains_harness trae; then install_trae_variant trae; fiif contains_harness trae-cn; then install_trae_variant trae-cn; fi+if contains_harness trae-cli; then install_trae_cli; fiif contains_harness zcode; then install_zcode; fiif contains_harness opencode; then install_opencode; fiif contains_harness pi; then install_pi; fi@@ -2978,6 +3247,7 @@ if contains_harness codex; then info "Codex-format: $(list_words "$CODEX_BINS")if contains_harness cursor; then info "Cursor: Hooks + MCP + Rule + Skill"; fiif contains_harness trae; then info "TRAE: ~/.trae/hooks.json + MCP"; fiif contains_harness trae-cn; then info "TRAE CN: ~/.trae-cn/hooks.json + MCP"; fi+if contains_harness trae-cli; then info "TRAE CLI: ${TRAECLI_HOME:-${TRAE_HOME:-~/.trae}/cli}/hooks.json + ${TRAE_HOME:-~/.trae}/traecli.toml"; fiif contains_harness zcode; then info "ZCode: ~/.zcode/cli/config.json (hooks + MCP)"; fiif contains_harness opencode; then info "OpenCode: @openviking/opencode-plugin"; fiif contains_harness pi; then info "pi: ~/.pi/agent/extensions/openviking"; fidiff --git a/examples/memory-plugin-shared/release-marketplace.test.mjs b/examples/memory-plugin-shared/release-marketplace.test.mjsindex caa3e7e9d..dbe7ec644 100644--- a/examples/memory-plugin-shared/release-marketplace.test.mjs+++ b/examples/memory-plugin-shared/release-marketplace.test.mjs@@ -69,3 +69,45 @@ test("release marketplace archive supports a ZCode TOS install", () => {rmSync(tmp, { recursive: true, force: true });}});++test("release marketplace archive supports a TRAE CLI TOS install", () => {+ const tmp = mkdtempSync(join(tmpdir(), "openviking-trae-cli-release-"));+ try {+ const stage = join(tmp, "memory-plugin-marketplace");+ const staged = run("bash", [stageScript, stage]);+ assert.equal(staged.status, 0, `${staged.stdout}\n${staged.stderr}`);++ const zipped = run("zip", ["-rq", join(tmp, "memory-plugin-marketplace.zip"), "memory-plugin-marketplace"], {+ cwd: tmp,+ });+ assert.equal(zipped.status, 0, `${zipped.stdout}\n${zipped.stderr}`);++ const home = join(tmp, "home");+ mkdirSync(home, { recursive: true });+ const installed = run("bash", [+ installer,+ "--harness", "trae-cli",+ "--dist", "tos",+ "--source", "archive",+ "--lang", "en",+ "--url", "http://127.0.0.1:1933",+ "--api-key", "",+ "--yes",+ ], {+ env: {+ ...process.env,+ HOME: home,+ OPENVIKING_HOME: join(home, ".openviking"),+ OPENVIKING_MARKETPLACE_ARCHIVE_URL: `file://${join(tmp, "memory-plugin-marketplace.zip")}`,+ },+ });+ assert.equal(installed.status, 0, `${installed.stdout}\n${installed.stderr}`);++ const integrationRoot = join(home, ".openviking", "agent-integrations", "trae-cli");+ assert.ok(existsSync(join(integrationRoot, "scripts", "trae-cli-hook.mjs")));+ assert.ok(existsSync(join(integrationRoot, "scripts", "uri-guard.mjs")));+ assert.ok(existsSync(join(integrationRoot, "servers", "mcp-proxy.mjs")));+ } finally {+ rmSync(tmp, { recursive: true, force: true });+ }+});diff --git a/examples/trae-cli-memory-hooks/.mcp.json b/examples/trae-cli-memory-hooks/.mcp.jsonnew file mode 100644index 000000000..fd5668560--- /dev/null+++ b/examples/trae-cli-memory-hooks/.mcp.json@@ -0,0 +1,12 @@+{+ "mcpServers": {+ "openviking-memory": {+ "command": "node",+ "args": [+ "servers/mcp-proxy.mjs"+ ],+ "cwd": ".",+ "startup_timeout_sec": 30+ }+ }+}diff --git a/examples/trae-cli-memory-hooks/README.md b/examples/trae-cli-memory-hooks/README.mdnew file mode 100644index 000000000..fdc880d40--- /dev/null+++ b/examples/trae-cli-memory-hooks/README.md@@ -0,0 +1,146 @@+# OpenViking Memory Hooks for TRAE CLI++This directory provides the TRAE CLI lifecycle adapter for OpenViking memory:+three lifecycle hooks, a `PreToolUse` URI guard, and the `openviking-memory`+MCP server.++## Installation++Use the shared installer:++```bash+bash examples/memory-plugin-shared/install.sh --harness trae-cli+```++The installer:++- assembles the shared runtime under+ `$OPENVIKING_HOME/agent-integrations/memory-plugin-shared/lib`;+- installs this adapter under+ `$OPENVIKING_HOME/agent-integrations/trae-cli`;+- merges hooks into `${TRAECLI_HOME:-${TRAE_HOME:-~/.trae}/cli}/hooks.json`;+- registers `openviking-memory` in `${TRAE_HOME:-~/.trae}/traecli.toml`.++Uninstall with:++```bash+bash examples/memory-plugin-shared/install.sh --harness trae-cli --uninstall --yes+```++## Hook and MCP Surface++The draft registers four hook events:++| Event | Entry | Reuse assessment |+| --- | --- | --- |+| `SessionStart` | `scripts/session-start.mjs` | Reuses the shared thin-harness profile injection path. Requires TRAE CLI to provide a stable session id or equivalent cwd fallback. |+| `UserPromptSubmit` | `scripts/auto-recall.mjs` | Reuses the shared recall path. Requires TRAE CLI prompt input to be exposed as `prompt`, `user_prompt`, `message`, or `text`. |+| `Stop` | `scripts/auto-capture.mjs` | Reuses shared session append and commit helpers. Requires TRAE CLI stop input to expose the assistant response as `last_assistant_message`, `assistant_message`, `response`, `output`, or `text_content`. |+| `PreToolUse` | `scripts/uri-guard.mjs` | Follows the Codex hook output style for `permissionDecision: "deny"` and reuses the shared `agent-uri-guard` evaluator. |++TRAE CLI lifecycle hooks do not use TRAE / TRAE CN's `decision: "approve"`+output. No-op lifecycle hooks emit `{}`; context injection emits only+`hookSpecificOutput.hookEventName` plus `hookSpecificOutput.additionalContext`.+Tool-call allow/deny decisions belong to `PreToolUse` via+`hookSpecificOutput.permissionDecision`, and permission approval belongs to+`PermissionRequest` via `hookSpecificOutput.decision.behavior`.++The MCP server is named `openviking-memory`, matching the Codex memory plugin+name. The package keeps the same `.mcp.json` source shape as the other native+hook integrations; the shared installer writes the equivalent Node proxy entry+into TRAE CLI's configured `traecli.toml`:++```json+{+ "mcpServers": {+ "openviking-memory": {+ "command": "node",+ "args": ["servers/mcp-proxy.mjs"],+ "cwd": ".",+ "startup_timeout_sec": 30+ }+ }+}+```++## Runtime Boundary++This package follows the same source layout as `examples/trae-memory-hooks`:+the repository directory contains only TRAE CLI-specific adapters. The shared+runtime is assembled by the installer at install time.++- `examples/memory-plugin-shared/lib/agent-hook-runtime.mjs` handles profile+ injection, recall, capture, commit, session state, locking, credential+ loading, and pending retry replay.+- `examples/memory-plugin-shared/lib/mcp-proxy-core.mjs` handles the stdio to+ OpenViking `/mcp` proxy.+- `examples/memory-plugin-shared/lib/agent-uri-guard.mjs` handles `PreToolUse`+ blocking when local file or shell tools receive `viking://` virtual paths.++The source package intentionally does not carry a vendored `lib/` directory.+The installer should copy `examples/trae-cli-memory-hooks` into+`$OV_HOME/agent-integrations/trae-cli` and assemble the shared runtime into+`$OV_HOME/agent-integrations/memory-plugin-shared/lib`, matching the existing+TRAE installation model.++## What Is Not Reused From Codex++- Codex plugin marketplace metadata and install commands.+- Codex-specific `${PLUGIN_ROOT}` substitution.+- Codex-specific `PreCompact` commit flow.+- Codex transcript JSONL parsing and `cx-<session_id>` session prefix.+- Codex local compressor startup detection.++## Current Compatibility Notes++The three hook entries are intended to be reusable if TRAE CLI sends hook input+JSON close to the existing thin harness conventions:++- Session identity: `conversation_id`, `session_id`, `sessionId`, or+ `generation_id`.+- Workspace: `cwd`, `workspace_roots`, or `workspaceRoots`.+- User prompt: `prompt`, `user_prompt`, `userPrompt`, `message`, or `text`.+- Assistant response on stop: `last_assistant_message`,+ `lastAssistantMessage`, `assistant_message`, `assistantMessage`, `response`,+ `output`, or `text_content`.+- Tool call: `tool_name`, `toolName`, `name`, or `tool`; input under+ `tool_input`, `toolInput`, `input`, or `arguments`.++The three lifecycle wrappers enter `scripts/trae-cli-hook.mjs`, a CLI-only+adapter that uses the fixed `trae-cli` client id and `trcli-` OpenViking+session prefix. It intentionally does not carry the TRAE / TRAE CN `tr-` and+`trcn-` branches.++If TRAE CLI uses different field names, adapt `scripts/trae-cli-hook.mjs` or+the local text cleanup / turn parsing in `scripts/trae-cli-turns.mjs`. The+shared OpenViking runtime and MCP proxy can remain unchanged.++## User-Level Install Shape++An installer should render `hooks/hooks.json` by replacing+`__OPENVIKING_TRAE_CLI_ROOT__` with this directory's absolute path, then merge+the rendered hooks into the current `TRAECLI_HOME/hooks.json`. In the common+local setup this is:++```text+~/.trae/cli/hooks.json+```++TRAE CLI also supports hooks in the active `traecli.toml` under `[hooks]`, but+the source shown by the TUI `/hooks` command is the source of truth. Prefer the+user-level hooks file when installing this integration so the setup is not tied+to one workspace.++MCP should be added to the active `traecli.toml` under+`[mcp_servers."openviking-memory"]`. Project-level MCP files such as+`<workspace>/.trae/.mcp.json` or `<workspace>/.trae/mcp.json` are supported by+TRAE CLI, but they are not the recommended target for this integration. Confirm+the effective MCP source with `/mcp` or `traecli mcp list`.++If an existing OpenViking TRAE hook set is already installed, replace or disable+the old OpenViking entries rather than adding this draft beside them. Running+both will duplicate recall and capture.++The installer validates the installed hook entrypoints and MCP configuration.+Use `/hooks`, `/mcp`, or `traecli mcp list` to inspect the effective runtime+configuration.diff --git a/examples/trae-cli-memory-hooks/hooks/hooks.json b/examples/trae-cli-memory-hooks/hooks/hooks.jsonnew file mode 100644index 000000000..797e1c08c--- /dev/null+++ b/examples/trae-cli-memory-hooks/hooks/hooks.json@@ -0,0 +1,52 @@+{+ "hooks": {+ "SessionStart": [+ {+ "matcher": "clear|startup|resume",+ "hooks": [+ {+ "type": "command",+ "command": "node __OPENVIKING_TRAE_CLI_ROOT__/scripts/session-start.mjs",+ "timeout": 70+ }+ ]+ }+ ],+ "UserPromptSubmit": [+ {+ "matcher": "*",+ "hooks": [+ {+ "type": "command",+ "command": "node __OPENVIKING_TRAE_CLI_ROOT__/scripts/auto-recall.mjs",+ "timeout": 130+ }+ ]+ }+ ],+ "Stop": [+ {+ "matcher": "*",+ "hooks": [+ {+ "type": "command",+ "command": "node __OPENVIKING_TRAE_CLI_ROOT__/scripts/auto-capture.mjs",+ "timeout": 30+ }+ ]+ }+ ],+ "PreToolUse": [+ {+ "matcher": "Read|Glob|Grep|Bash|RunCommand|Shell",+ "hooks": [+ {+ "type": "command",+ "command": "node __OPENVIKING_TRAE_CLI_ROOT__/scripts/uri-guard.mjs",+ "timeout": 5+ }+ ]+ }+ ]+ }+}diff --git a/examples/trae-cli-memory-hooks/openviking.integration.json b/examples/trae-cli-memory-hooks/openviking.integration.jsonnew file mode 100644index 000000000..2055d7584--- /dev/null+++ b/examples/trae-cli-memory-hooks/openviking.integration.json@@ -0,0 +1,7 @@+{+ "schemaVersion": 1,+ "id": "openviking-memory",+ "version": "0.1.0",+ "clients": ["trae-cli"],+ "capabilities": ["hooks", "mcp"]+}diff --git a/examples/trae-cli-memory-hooks/scripts/auto-capture.mjs b/examples/trae-cli-memory-hooks/scripts/auto-capture.mjsnew file mode 100755index 000000000..3186f7e11--- /dev/null+++ b/examples/trae-cli-memory-hooks/scripts/auto-capture.mjs@@ -0,0 +1,4 @@+#!/usr/bin/env node++process.env.OPENVIKING_HOOK_EVENT = "stop";+await import("./trae-cli-hook.mjs");diff --git a/examples/trae-cli-memory-hooks/scripts/auto-recall.mjs b/examples/trae-cli-memory-hooks/scripts/auto-recall.mjsnew file mode 100755index 000000000..d39cdae78--- /dev/null+++ b/examples/trae-cli-memory-hooks/scripts/auto-recall.mjs@@ -0,0 +1,4 @@+#!/usr/bin/env node++process.env.OPENVIKING_HOOK_EVENT = "user-prompt-submit";+await import("./trae-cli-hook.mjs");diff --git a/examples/trae-cli-memory-hooks/scripts/session-start.mjs b/examples/trae-cli-memory-hooks/scripts/session-start.mjsnew file mode 100755index 000000000..cffb6b07b--- /dev/null+++ b/examples/trae-cli-memory-hooks/scripts/session-start.mjs@@ -0,0 +1,4 @@+#!/usr/bin/env node++process.env.OPENVIKING_HOOK_EVENT = "session-start";+await import("./trae-cli-hook.mjs");diff --git a/examples/trae-cli-memory-hooks/scripts/trae-cli-hook.mjs b/examples/trae-cli-memory-hooks/scripts/trae-cli-hook.mjsnew file mode 100644index 000000000..6e1a1997e--- /dev/null+++ b/examples/trae-cli-memory-hooks/scripts/trae-cli-hook.mjs@@ -0,0 +1,142 @@+#!/usr/bin/env node++import {+ addAgentMessages,+ buildAgentProfile,+ commitAgentSession,+ createAgentLogger,+ deriveAgentSessionId,+ loadAgentHookConfig,+ makeAgentFetchJSON,+ readHookInput,+ readHookState,+ recallForPrompt,+ replayAgentPending,+ resolveAgentCwd,+ resolveNativeSessionId,+ shouldBypassAgent,+ stableHash,+ withAgentHookLock,+ writeHookState,+} from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";+import { buildTraeCliTurns, resolveTraeCliPrompt } from "./trae-cli-turns.mjs";++const eventName = process.env.OPENVIKING_HOOK_EVENT || process.argv[2] || "";+const clientId = "trae-cli";+const prefix = "trcli-";+const cfg = loadAgentHookConfig(clientId);+const { log, logError } = createAgentLogger(clientId, eventName, cfg);++function output(value = {}) {+ process.stdout.write(`${JSON.stringify(value)}\n`);+}++function emitLifecycleOutput(additionalContext = "") {+ const value = {};+ if (additionalContext) {+ value.hookSpecificOutput = {+ hookEventName: eventName === "session-start" ? "SessionStart" : "UserPromptSubmit",+ additionalContext,+ };+ }+ output(value);+}++const input = await readHookInput();+const nativeSessionId = resolveNativeSessionId(input);+const sessionId = deriveAgentSessionId(prefix, input);+const cwd = resolveAgentCwd(input);+const { fetchJSON } = makeAgentFetchJSON(cfg, cwd);++async function main() {+ if (!cfg.enabled || shouldBypassAgent(cfg, input)) { emitLifecycleOutput(); return; }+ let state = await readHookState(clientId, nativeSessionId);++ if (eventName === "session-start") {+ const profile = await withAgentHookLock(clientId, nativeSessionId, async () => {+ state = await readHookState(clientId, nativeSessionId);+ const now = Date.now();+ if (now - Number(state.lastSessionStartAt || 0) < 2000) return null;+ state = { ...state, lastSessionStartAt: now };+ await writeHookState(clientId, nativeSessionId, state);+ await replayAgentPending(fetchJSON, log).catch((error) => logError("pending", error));+ return buildAgentProfile(fetchJSON, cfg, cwd).catch((error) => {+ logError("profile", error);+ return null;+ });+ });+ emitLifecycleOutput(profile ? `<openviking-context source="session-start">\n${profile}\n</openviking-context>` : "");+ return;+ }++ if (eventName === "user-prompt-submit") {+ const prompt = resolveTraeCliPrompt(input);+ if (!prompt) { emitLifecycleOutput(); return; }+ const recallBlock = await withAgentHookLock(clientId, nativeSessionId, async () => {+ state = await readHookState(clientId, nativeSessionId);+ const promptHash = stableHash(prompt);+ const now = Date.now();+ const promptEventId = input.generation_id || input.request_id || input.message_id || input.prompt_id || "";+ const duplicateEvent = promptEventId+ ? state.promptEventId === promptEventId+ : state.promptHash === promptHash && now - Number(state.promptAt || 0) < 500;+ if (duplicateEvent) return null;+ const block = state.promptHash === promptHash && state.recallBlock+ ? state.recallBlock+ : await recallForPrompt(fetchJSON, cfg, prompt, cwd, log, { sessionId }).catch((error) => {+ logError("recall", error);+ return null;+ });+ await writeHookState(clientId, nativeSessionId, {+ ...state,+ promptHash,+ promptEventId,+ promptAt: now,+ recallBlock: block,+ pendingPrompt: { prompt, hash: promptHash, at: now },+ });+ return block;+ });+ emitLifecycleOutput(recallBlock || "");+ return;+ }++ if (eventName === "stop") {+ if (!cfg.autoCapture) { emitLifecycleOutput(); return; }+ await withAgentHookLock(clientId, nativeSessionId, async () => {+ state = await readHookState(clientId, nativeSessionId);+ const hashes = new Set(Array.isArray(state.capturedHashes) ? state.capturedHashes : []);+ const turnKey = state.pendingPrompt?.at || state.lastTurnKey || state.promptHash || "unknown-turn";+ const toSend = [];+ for (const turn of buildTraeCliTurns(input, state)) {+ const hash = stableHash(turnKey, turn.role, turn.content);+ if (hashes.has(hash)) continue;+ toSend.push({ hash, turn });+ }+ const result = await addAgentMessages(fetchJSON, sessionId, toSend.map((item) => item.turn));+ const captured = result.sent + result.queued;+ for (const item of toSend.slice(0, captured)) hashes.add(item.hash);+ let nextCount = Number(state.capturedSinceCommit || 0) + captured;+ if (captured > 0) {+ const committed = await commitAgentSession(fetchJSON, sessionId, log);+ if (committed.ok) nextCount = 0;+ }+ await writeHookState(clientId, nativeSessionId, {+ ...state,+ capturedHashes: [...hashes].slice(-1000),+ capturedSinceCommit: nextCount,+ pendingPrompt: null,+ lastTurnKey: turnKey,+ });+ });+ emitLifecycleOutput();+ return;+ }++ emitLifecycleOutput();+}++main().catch((error) => {+ logError("uncaught", error);+ emitLifecycleOutput();+});diff --git a/examples/trae-cli-memory-hooks/scripts/trae-cli-hooks.test.mjs b/examples/trae-cli-memory-hooks/scripts/trae-cli-hooks.test.mjsnew file mode 100644index 000000000..4b3b0ba21--- /dev/null+++ b/examples/trae-cli-memory-hooks/scripts/trae-cli-hooks.test.mjs@@ -0,0 +1,102 @@+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createServer } from "node:http";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import test from "node:test";++import { buildTraeCliTurns } from "./trae-cli-turns.mjs";++const pluginRoot = join(dirname(fileURLToPath(import.meta.url)), "..");++function runHook(entrypoint, input, env) {+ return new Promise((resolveRun, reject) => {+ const child = spawn(process.execPath, [join(pluginRoot, "scripts", entrypoint)], {+ env: { ...process.env, ...env },+ stdio: ["pipe", "pipe", "pipe"],+ });+ let stdout = "";+ let stderr = "";+ child.stdout.on("data", (chunk) => { stdout += chunk; });+ child.stderr.on("data", (chunk) => { stderr += chunk; });+ child.on("error", reject);+ child.on("close", (code) => {+ if (code !== 0) reject(new Error(stderr || `hook exited ${code}`));+ else resolveRun(JSON.parse(stdout.trim() || "{}"));+ });+ child.stdin.end(JSON.stringify(input));+ });+}++test("TRAE CLI turn parsing supports every documented prompt and response alias", () => {+ const promptFields = ["prompt", "user_prompt", "userPrompt", "message", "text"];+ const responseFields = [+ "last_assistant_message",+ "lastAssistantMessage",+ "assistant_message",+ "assistantMessage",+ "response",+ "output",+ "text_content",+ ];++ for (const field of promptFields) {+ assert.deepEqual(buildTraeCliTurns({ [field]: "user question", last_assistant_message: "assistant answer" }), [+ { role: "user", content: "user question" },+ { role: "assistant", content: "assistant answer" },+ ], `prompt field ${field}`);+ }+ for (const field of responseFields) {+ assert.deepEqual(buildTraeCliTurns({ prompt: "user question", [field]: "assistant answer" }), [+ { role: "user", content: "user question" },+ { role: "assistant", content: "assistant answer" },+ ], `response field ${field}`);+ }+});++test("TRAE CLI lifecycle hooks recall and capture message/output payloads", async () => {+ const messages = [];+ const server = createServer((request, response) => {+ let body = "";+ request.on("data", (chunk) => { body += chunk; });+ request.on("end", () => {+ if (request.url === "/api/v1/search/search" || request.url === "/api/v1/search/recall") {+ response.end(JSON.stringify({ result: { rendered: "TRAE CLI memory", entries: [], stats: {} } }));+ } else if (request.url?.includes("/messages")) {+ const parsed = JSON.parse(body);+ messages.push(...(parsed.messages ?? [parsed]));+ response.end(JSON.stringify({ result: { ok: true } }));+ } else {+ response.end(JSON.stringify({ result: { ok: true } }));+ }+ });+ });+ await new Promise((resolveListen) => server.listen(0, "127.0.0.1", resolveListen));+ const home = mkdtempSync(join(tmpdir(), "openviking-trae-cli-hooks-"));+ const env = {+ HOME: home,+ OPENVIKING_URL: `http://127.0.0.1:${server.address().port}`,+ OPENVIKING_HOOK_STATE_DIR: join(home, "state"),+ OPENVIKING_MEMORY_ENABLED: "1",+ };+ try {+ const base = { session_id: "same-session", cwd: "/workspace" };+ const recalled = await runHook("auto-recall.mjs", {+ ...base,+ message: "remember this TRAE CLI question",+ generation_id: "prompt-1",+ }, env);+ assert.match(recalled.hookSpecificOutput?.additionalContext || "", /TRAE CLI memory/);++ await runHook("auto-capture.mjs", { ...base, output: "TRAE CLI answer" }, env);+ assert.deepEqual(messages.map((message) => message.content), [+ "remember this TRAE CLI question",+ "TRAE CLI answer",+ ]);+ } finally {+ await new Promise((resolveClose) => server.close(resolveClose));+ rmSync(home, { recursive: true, force: true });+ }+});diff --git a/examples/trae-cli-memory-hooks/scripts/trae-cli-turns.mjs b/examples/trae-cli-memory-hooks/scripts/trae-cli-turns.mjsnew file mode 100644index 000000000..b210b33b4--- /dev/null+++ b/examples/trae-cli-memory-hooks/scripts/trae-cli-turns.mjs@@ -0,0 +1,37 @@+export function cleanTraeCliText(value) {+ return String(value || "")+ .replace(/<openviking-context\b[^>]*>[\s\S]*?<\/openviking-context>/gi, "")+ .replace(/<relevant-memories>[\s\S]*?<\/relevant-memories>/gi, "")+ .trim();+}++function firstTraeCliText(input, fields) {+ for (const field of fields) {+ const text = cleanTraeCliText(input?.[field]);+ if (text) return text;+ }+ return "";+}++export function resolveTraeCliPrompt(input = {}) {+ return firstTraeCliText(input, ["prompt", "user_prompt", "userPrompt", "message", "text"]);+}++export function resolveTraeCliResponse(input = {}) {+ return firstTraeCliText(input, [+ "last_assistant_message",+ "lastAssistantMessage",+ "assistant_message",+ "assistantMessage",+ "response",+ "output",+ "text_content",+ ]);+}++export function buildTraeCliTurns(input = {}, state = {}) {+ return [+ { role: "user", content: resolveTraeCliPrompt(input) || cleanTraeCliText(state.pendingPrompt?.prompt) },+ { role: "assistant", content: resolveTraeCliResponse(input) },+ ].filter((turn) => turn.content);+}diff --git a/examples/trae-cli-memory-hooks/scripts/uri-guard.mjs b/examples/trae-cli-memory-hooks/scripts/uri-guard.mjsnew file mode 100755index 000000000..d30850b7a--- /dev/null+++ b/examples/trae-cli-memory-hooks/scripts/uri-guard.mjs@@ -0,0 +1,37 @@+#!/usr/bin/env node++import { readFileSync, realpathSync } from "node:fs";+import { fileURLToPath } from "node:url";+import {+ evaluateAgentUriGuard,+} from "../../memory-plugin-shared/lib/agent-uri-guard.mjs";++function readInput() {+ try {+ const raw = readFileSync(0, "utf8").trim();+ return raw ? JSON.parse(raw) : {};+ } catch {+ return {};+ }+}++export function evaluateTraeCliUriGuard(input = {}) {+ const toolName = input.tool_name ?? input.toolName ?? input.name ?? input.tool;+ const toolInput = input.tool_input ?? input.toolInput ?? input.input ?? input.arguments ?? {};+ const decision = evaluateAgentUriGuard(toolName, toolInput);+ if (!decision) return {};+ return {+ hookSpecificOutput: {+ hookEventName: "PreToolUse",+ permissionDecision: "deny",+ permissionDecisionReason: decision.reason,+ },+ };+}++const isEntrypoint = process.argv[1]+ && realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);+if (isEntrypoint) {+ const output = evaluateTraeCliUriGuard(readInput());+ if (Object.keys(output).length > 0) process.stdout.write(`${JSON.stringify(output)}\n`);+}diff --git a/examples/trae-cli-memory-hooks/servers/mcp-proxy.mjs b/examples/trae-cli-memory-hooks/servers/mcp-proxy.mjsnew file mode 100755index 000000000..ba1165404--- /dev/null+++ b/examples/trae-cli-memory-hooks/servers/mcp-proxy.mjs@@ -0,0 +1,30 @@+#!/usr/bin/env node++import { fileURLToPath } from "node:url";+import { resolve as resolvePath } from "node:path";++import { loadAgentHookConfig } from "../../memory-plugin-shared/lib/agent-hook-runtime.mjs";+import { createLogger } from "../../memory-plugin-shared/lib/debug-log.mjs";+import { createOpenVikingMcpProxy } from "../../memory-plugin-shared/lib/mcp-proxy-core.mjs";++function readConfig() {+ const cfg = loadAgentHookConfig("trae-cli");+ return {+ mcpUrl: cfg.mcpUrl,+ apiKey: cfg.apiKey,+ account: cfg.account,+ user: cfg.user,+ peerId: cfg.peerId,+ userAgent: cfg.userAgent,+ timeoutMs: cfg.timeoutMs,+ debug: cfg.debug,+ debugLogPath: cfg.debugLogPath,+ credentialSource: cfg.credentialSource,+ credentialPath: cfg.cliPath || cfg.ovPath || "",+ watchedPaths: [cfg.cliPath, cfg.ovPath].filter(Boolean),+ };+}++if (process.argv[1] && fileURLToPath(import.meta.url) === resolvePath(process.argv[1])) {+ createOpenVikingMcpProxy({ readConfig, loggerFactory: createLogger }).start();+}