@zephor/dsh-agent-context 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Zephor5
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,42 @@
1
- # Temporary Holding Version
1
+ # Agent Context · 个人知识库
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@zephor/dsh-agent-context` 让 DSH 会话通过本机 MCP 服务检索 wiki、追加记录和共享黑板。安装包随附预编译的 `agent-context`,覆盖 macOS(Apple Silicon、Intel)、Linux(x64、ARM64)和 Windows x64。用户无需安装 Rust 或手动启动 CLI。
4
+
5
+ ## 在 DSH 中使用
6
+
7
+ 在「插件」中安装并启用组合包。首发前可通过「添加插件」选择构建产出的本地 `.tgz`;发布后可直接按包名安装。按宿主提示重启或开新会话,然后试一句「列出本机黑板条目」。新知识库的列表可能为空。会话可通过 MCP 工具读写所选知识库。
8
+
9
+ 初次使用会自动初始化本人的知识库。macOS 和 Linux 默认路径是 `~/.local/share/agent-context/vault`,Windows 默认路径是 `%LOCALAPPDATA%/agent-context/vault`;设置了绝对路径 `XDG_DATA_HOME` 时使用其下的 `agent-context/vault`。重启、升级或从其他 DSH profile 启用时都会复用该目录。缺少 Git 时,内置 CLI 仍可初始化 wiki 和黑板;需要提交历史时再安装 Git 并初始化仓库。
10
+
11
+ ## 在 DSH 里打开工作台
12
+
13
+ 点击 DSH 左侧的 **Agent Context**,在主区域查看或编辑当前知识库。若这个 Host 启用了多个 agent-context 实例,可在页面上选择服务名。黑板、Wiki、原始记录、Markdown 预览和单页 Git 提交与独立 Web 使用同一套页面和接口。离开侧栏页面再回来时,当前 DSH 客户端会保留该库的编辑草稿;刷新整个 DSH 窗口会清除内存草稿。
14
+
15
+ 工作台在首次请求时通过包内 CLI 的 `web --stdio` 通道读取当前 vault,由 DSH Host 校验访问者。它不占用本机 Web 端口,也不改动独立 Web 的根目录配置。关掉插件会关闭该通道。已有 CLI 可以继续提供 MCP 服务。单页 Git 提交需要本机有 Git 且知识库已经初始化 Git 仓库。
16
+
17
+ ## 已有安装与配置
18
+
19
+ - **可执行文件**依次查找显式 `binaryPath`、PATH 中的绝对目录、Cargo bin 目录、包内当前平台的程序。自定义路径须可执行。
20
+ - **知识库**依次采用显式 `vaultRoot`、环境变量 `AGENT_CONTEXT_ROOT`、`agent-context web` 记住的目录、已有的 `~/agent-context` vault、上述默认目录。旧库会原地打开。其他位置的旧库可以用绝对路径指定。
21
+ - 显式配置或 Web 记录指向无效目录时,修正路径后重新启用。已有的非 vault 目录会受到保护。
22
+ - 旧本地包 `dsh-agent-context` 用户先记录自定义路径,再停用旧组合包、启用新版。保留已有条目 ID `mcp-agent-context` 和服务名 `agent-context`。若 profile 覆盖项指定了旧模块 `name`,把该字段改为 `"@zephor/dsh-agent-context"`。已有同名手工 MCP 注册时先移除重复注册,保留原 vault。
23
+ - 多个 vault 可以用不同条目 ID、`serverName` 和 `vaultRoot` 挂载。卸载插件会撤回其 MCP 注册,知识库保留在原处。
24
+
25
+ 需要自定义时,在当前 profile 的 `cordis.patch.yml` 覆盖已启用组合包的配置。例如:
26
+
27
+ ```yaml
28
+ - id: mcp-agent-context
29
+ config:
30
+ vaultRoot: /absolute/path/to/my-vault
31
+ binaryPath: /absolute/path/to/agent-context
32
+ ```
33
+
34
+ 两个路径都可留空。要查看工具,打开 DSH 的 MCP 设置检查 `agent-context` 的连接状态。接口和维护流程见[项目说明](https://github.com/Zephor5/agent-context#readme)。
35
+
36
+ ## 开发与打包
37
+
38
+ 运行 `npm test` 检查配置选择、注册和卸载。仓库中的 **Build DSH plugin** 工作流在各平台从同一份 `Cargo.lock` 编译 release 程序,验证首次启动和 MCP 握手,再将五个程序放进同一个 npm 安装包。下载 `dsh-agent-context-npm` artifact,解压即可获得 DSH 可安装的 `.tgz`。工作流仅构建测试包。正式打包要求五个平台的文件齐全。
39
+
40
+ 本平台开发时,在仓库根目录执行 `cargo build --locked --release`,将 `target/release/agent-context`(Windows 为 `agent-context.exe`)放到本插件的 `native/<platform>-<arch>/`。进入插件目录运行 `npm test`,运行 `npm run build:web` 后可用 `npm pack --ignore-scripts` 生成仅用于本机试装的单平台包。
41
+
42
+ [MIT 许可证](LICENSE)
@@ -0,0 +1,10 @@
1
+ # Existing profile overrides can keep id: mcp-agent-context.
2
+ - insert:
3
+ - id: mcp-agent-context
4
+ name: '@zephor/dsh-agent-context'
5
+ config:
6
+ serverName: agent-context
7
+ vaultRoot: ''
8
+ binaryPath: ''
9
+ - id: agent-context-web
10
+ name: '@zephor/dsh-agent-context/web-host'
package/icon.svg ADDED
@@ -0,0 +1 @@
1
+ <svg width="36" height="36" viewBox="0 0 36 36" fill="none" xmlns="http://www.w3.org/2000/svg"><title>agent-context</title><rect x="7" y="5" width="19" height="26" rx="3" fill="#1F9E8C" fill-opacity="0.92"/><path d="M9.5 5H12v26H9.5A2.5 2.5 0 0 1 7 28.5v-21A2.5 2.5 0 0 1 9.5 5Z" fill="#0E6B5F"/><path d="M16 12h6.5M16 17h6.5M16 22h4" stroke="#fff" stroke-width="1.6" stroke-linecap="round"/><circle cx="26.5" cy="26.5" r="5" fill="#F0A33A" stroke="#fff" stroke-width="1.5"/><path d="M26.5 24.2v4.6M24.2 26.5h4.6" stroke="#fff" stroke-width="1.5" stroke-linecap="round"/></svg>
package/lib/client.js ADDED
@@ -0,0 +1,165 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "@zephor/dsh-agent-context",
3
+ factory(require) {
4
+ const React = require('react');
5
+ const h = React.createElement;
6
+ const source = "<!doctype html>\n<html lang=\"zh-CN\">\n<head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><meta name=\"color-scheme\" content=\"light dark\"><title>Agent Context</title><meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; script-src 'sha256-RxB4p2LGupD/FmALT0O43jQTq+Sv1F0asUhyghzrX7U=' 'sha256-xTZN7n/N+XZZ3e+Gm7mjk12QlbkLPy2OWNmmP0kzvco='; style-src 'sha256-S0cO4d1yxl6qsqVqItApQ6TwrH2COtXsNxgEjM8h9RY='; img-src data:; form-action 'none'; base-uri 'none'\"><meta name=\"bridge\" content=\"__BRIDGE_TOKEN__\"><style>:root{color-scheme:light dark;--bg:light-dark(#fff,#202522);--side:light-dark(#f5f7f4,#191e1b);--ink:light-dark(#23302a,#e2e9e3);--dim:light-dark(#68776c,#a6b4aa);--line:light-dark(#dfe7df,#38453d);--accent:light-dark(#285d45,#a4d2b7);--on-accent:light-dark(#fff,#183c28);--selected:light-dark(#e7f0e9,#2c4032);--warn:light-dark(#fbf2dc,#493e25);font:14px/1.65 -apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;color:var(--ink);background:var(--bg)}\n*{box-sizing:border-box}\nbody{margin:0;height:100vh;height:100dvh;display:flex;flex-direction:column;overflow:hidden}\n[hidden]{display:none!important}\nbutton,input,textarea{font:inherit;color:inherit}\nbutton{cursor:pointer;border:1px solid var(--line);border-radius:7px;padding:6px 12px;background:var(--bg)}\nbutton:hover{background:var(--selected)}\nbutton:disabled{cursor:wait;opacity:.5}\nbutton.primary{background:var(--accent);color:var(--on-accent);border-color:transparent}\nbutton:focus-visible,a:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--accent);outline-offset:3px}\na{color:var(--accent)}\nh1,h2,h3,strong{font-weight:600}\nh1{font-size:23px;margin:0}\nh2{font-size:21px}\nh3{font-size:17px}\n.top{height:56px;flex-shrink:0;padding:12px 22px;display:flex;align-items:center;gap:20px;border-bottom:1px solid var(--line)}\n.brand{font-size:18px;text-decoration:none;color:var(--ink);white-space:nowrap}\n#vault-name{font-size:12px;color:var(--dim);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}\n#connection{margin-left:auto;font-size:12px;color:var(--dim);white-space:nowrap}\n#app{display:grid;grid-template-rows:minmax(0,1fr);grid-template-columns:144px 320px minmax(0,1fr);flex:1;min-height:0;overflow:hidden}\nnav{background:var(--side);border-right:1px solid var(--line);padding:20px 10px;overflow:auto}\nnav .eyebrow{font-size:12px;color:var(--dim);padding:0 10px;margin:0 0 12px}\nnav button{border:0;display:flex;align-items:center;width:100%;text-align:left;gap:8px;margin:4px 0;padding:10px;background:transparent}\nnav button span{margin-left:auto;color:var(--dim);font-size:12px}\nnav [aria-current=page]{background:var(--selected);color:var(--accent)}\n.nav-note{margin:64px 10px 0;color:var(--dim);font-size:12px}\n.nav-note span{font-size:11px}\n.index{padding:20px 16px 0;border-right:1px solid var(--line);min-width:0;min-height:0;display:flex;flex-direction:column}\n.list-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;margin-bottom:18px;flex-shrink:0}\n.list-head button{flex-shrink:0}\n.list-head p{font-size:12px;color:var(--dim);margin:4px 0 0}\n.search{display:flex;align-items:center;gap:8px;padding:6px 10px;border:1px solid var(--line);border-radius:7px;background:var(--bg);flex-shrink:0}\n.search input{border:0;background:transparent;width:100%;min-width:0}\n.search span{color:var(--dim);font-size:20px}\n.list-meta{display:flex;align-items:center;justify-content:space-between;color:var(--dim);font-size:12px;margin:12px 0 8px;flex-shrink:0}\n.list-meta button{font-size:12px;background:transparent;border:0;padding:3px 5px}\n.group{display:flex;align-items:center;gap:10px;color:var(--dim);font-size:11px;margin:12px 10px 6px;grid-column:1/-1}\n.group:after{content:\"\";height:1px;background:var(--line);flex:1}\n.item{display:block;text-align:left;width:100%;border:1px solid transparent;border-radius:7px;padding:12px;margin:2px 0;overflow:hidden;overflow-wrap:anywhere;background:transparent}\n.item.selected{background:var(--selected);border-color:var(--line);box-shadow:inset 3px 0 var(--accent)}\n.item-title{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden;font-weight:600;font-size:14px;line-height:1.5;margin-bottom:5px}\n.item-key{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:100%;font:11px/1.6 ui-monospace,monospace;color:var(--dim);margin-bottom:8px}\n.item-summary{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden;color:var(--dim);font-size:12px;line-height:1.65}\n.item-meta{display:flex;justify-content:space-between;gap:8px;margin-top:12px;color:var(--dim);font-size:12px}\n.item-tag{display:block;min-width:0;max-width:130px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10px;background:var(--side);border-radius:4px;padding:1px 6px}\n.board .index{background:var(--side);padding:20px 16px 0}\n.board #items{display:grid;grid-template-columns:minmax(0,1fr);grid-auto-rows:max-content;align-content:start;gap:12px}\n.board .item{display:flex;flex-direction:column;align-items:flex-start;margin:0;padding:18px;background:var(--bg);border:1px solid var(--line);border-radius:9px;transition:border-color .15s,box-shadow .15s}\n/* Cards must grow and scroll, never compress text below its line height. */\n.board .item>span{flex-shrink:0;max-width:100%}\n.board .item:hover{border-color:var(--accent);box-shadow:0 3px 14px #00000009}\n.board .item.selected{border-color:var(--accent);background:var(--selected)}\n.board .item-title{font-size:16px}\n.board .item-summary{color:var(--ink);margin-bottom:14px;-webkit-line-clamp:3}\n.board .item-meta{margin-top:auto;padding-top:12px;border-top:1px solid var(--line);width:100%}\n#app.board.overview{grid-template-columns:144px minmax(0,1fr)}\n.board.overview .index{border:0}\n.board.overview #items{grid-template-columns:repeat(auto-fill,minmax(min(100%,310px),1fr))}\n.board.overview #detail{display:none}\n#app.board:not(.overview){grid-template-columns:144px 320px minmax(0,1fr)}\n#detail{padding:20px clamp(24px,4vw,64px) 36px;min-width:0;min-height:0;overflow-y:auto;scrollbar-gutter:stable;display:flex;flex-direction:column}\n#back{align-self:flex-start;font-size:12px;margin-bottom:22px}\n.toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:32px;flex-shrink:0}\n#location{color:var(--dim);font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}\n.actions{display:flex;gap:8px;flex-shrink:0}\n.text-button{border:0;padding:0;color:var(--dim);background:transparent}\n#reader,#editor{flex:1;min-width:0;width:100%;max-width:880px;margin-inline:auto}\n.markdown{overflow-wrap:anywhere}\n.markdown>:first-child{margin-top:0}\n.markdown h1{font-size:25px;margin:16px 0}\n.markdown h2{margin:28px 0 12px}\n.markdown h3{margin:24px 0 8px}\n.markdown li{margin:6px 0}\n.markdown pre{overflow:auto;padding:16px;background:var(--side);border-radius:7px}\n.markdown code{font-family:ui-monospace,monospace;font-size:.9em;background:var(--side);padding:1px 4px;border-radius:3px}\n.markdown pre code{padding:0}\n.markdown blockquote{margin:16px 0;padding:4px 16px;border-left:3px solid var(--line);color:var(--dim)}\n.markdown img{max-width:100%;height:auto}\n.markdown table{border-collapse:collapse;display:block;overflow:auto}\n.markdown td,.markdown th{padding:7px 10px;border:1px solid var(--line)}\n.markdown hr{border:0;border-top:1px solid var(--line);margin:25px 0}\nfooter{border-top:1px solid var(--line);margin:30px auto 0;padding-top:16px;display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;font-size:12px;color:var(--dim);width:100%;max-width:880px}\nfooter button{font-size:12px}\n.empty{padding:42px 8px;color:var(--dim);grid-column:1/-1}\n#name-label{display:block;font-size:12px;color:var(--dim)}\n#name{display:block;margin:6px 0 16px;width:100%;border:1px solid var(--line);border-radius:6px;padding:9px 12px;background:var(--bg)}\n#name:read-only{background:var(--side)}\n.editor-head,.editor-foot{display:flex;align-items:center;justify-content:space-between;gap:12px;font-size:12px;color:var(--dim);margin:10px 0}\n.editor-head button{font-size:12px}\n#source{display:block;width:100%;min-height:480px;resize:vertical;padding:18px;border:1px solid var(--line);border-radius:7px;background:var(--bg);font:13px/1.9 ui-monospace,monospace}\n#preview-body{min-height:480px}\n.notice{background:var(--warn);border-radius:7px;padding:14px;margin-bottom:18px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;font-size:13px}\n.notice button{font-size:12px}\n#toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);max-width:calc(100% - 32px);z-index:4;background:var(--ink);color:var(--bg);border-radius:9px;padding:12px 20px;box-shadow:0 4px 24px #0002;overflow-wrap:anywhere}\ndialog{max-width:min(760px,calc(100% - 32px));width:680px;max-height:85vh;border:1px solid var(--line);border-radius:12px;padding:24px;color:var(--ink);background:var(--bg)}\ndialog::backdrop{background:#0005}\n.dialog-head{display:flex;align-items:center;justify-content:space-between;gap:12px}\n.dialog-head h2{margin:0}\n.dialog-head button{border:0;font-size:20px}\n.dialog-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:24px}\n#dialog-message{color:var(--dim)}\n#dialog-content pre{white-space:pre-wrap;word-break:break-word;padding:14px;background:var(--side);font:12px/1.7 ui-monospace,monospace;max-height:45vh;overflow:auto}\n#dialog-content input,#dialog-content textarea{display:block;width:100%;padding:10px;border:1px solid var(--line);border-radius:6px;background:var(--bg);margin:8px 0}\n#dialog-content textarea{min-height:240px;font:13px/1.8 ui-monospace,monospace}\n\n\n/* The list and document own their scroll positions; navigation stays in view. */\n#items{flex:1;min-height:0;overflow-y:auto;overscroll-behavior:contain;padding-bottom:20px;scrollbar-gutter:stable}\n.item-labels{display:flex;align-items:center;gap:5px;overflow:hidden;margin-top:8px}\n.tag-more,.item-status{font-size:10px;color:var(--dim);white-space:nowrap;flex-shrink:0}\n.item-status{padding-right:5px;border-right:1px solid var(--line)}\n.item-summary:empty{display:none}\n#app:not(.board) #back{display:none}\n.board.overview .index{padding:28px 32px 0}\n.board.overview .search{max-width:480px}\n.board.overview .item{min-height:190px}\n.board:not(.overview) .item{padding:14px}\n.board:not(.overview) .item-title{font-size:14px}\n.board:not(.overview) .item-summary{-webkit-line-clamp:2;font-size:12px}\n.board:not(.overview) .item-meta{font-size:11px}\n#external{width:100%;max-width:880px;margin-inline:auto;flex-shrink:0}\n#reader{font-size:15px;line-height:1.85}\n@media(min-width:1800px){\n #app,#app.board:not(.overview){grid-template-columns:160px 360px minmax(0,1fr)}\n #app.board.overview{grid-template-columns:160px minmax(0,1fr)}\n}\n@media(max-width:1100px) and (min-width:761px){\n #app,#app.board:not(.overview){grid-template-columns:120px 280px minmax(0,1fr)}\n #app.board.overview{grid-template-columns:120px minmax(0,1fr)}\n nav{padding-inline:6px}\n nav button{padding-inline:8px}\n #detail{padding:20px 24px 28px}\n .toolbar{flex-wrap:wrap;gap:8px}\n #location{width:100%}\n}\n@media(max-width:760px){\n .top{height:52px;padding:10px 16px;gap:10px}\n .brand{font-size:16px}\n #vault-name{display:none}\n #connection{font-size:11px}\n #app,#app.board.overview,#app.board:not(.overview){display:flex;flex-direction:column}\n nav{display:flex;flex-shrink:0;padding:6px 8px;border-right:0;border-bottom:1px solid var(--line);gap:4px}\n nav button{white-space:nowrap;justify-content:center;margin:0;padding:8px 6px}\n nav .eyebrow,.nav-note{display:none}\n nav button span{margin-left:3px}\n .index,.board .index,.board.overview .index{flex:1;padding:18px 16px 0;border-right:0;overflow:hidden}\n #app:not(.overview) .index{display:none}\n #app.overview #detail{display:none}\n #detail{flex:1;padding:18px 20px 24px}\n #app:not(.board) #back{display:block}\n #back{margin-bottom:16px}\n .toolbar{flex-wrap:wrap;margin-bottom:24px}\n #location{width:100%;font-size:11px}\n .actions button{padding:6px 10px}\n .editor-foot{flex-wrap:wrap}\n input,textarea{font-size:16px}\n #source{font-size:16px;min-height:360px}\n #reader{font-size:14px}\n .markdown h1{font-size:23px}\n}\n@media(prefers-reduced-motion:reduce){*{transition:none!important}}\n</style></head>\n<body>\n<header class=\"top\"><a class=\"brand\" href=\"/\">▤ <strong>agent-context</strong></a><span id=\"vault-name\"></span><span id=\"connection\" role=\"status\">正在连接…</span></header>\n<div id=\"app\" class=\"board overview\">\n<nav aria-label=\"工作空间\"><p class=\"eyebrow\">工作空间</p><button data-area=\"board\" aria-current=\"page\">▦ 黑板 <span id=\"count-board\">0</span></button><button data-area=\"wiki\">▤ Wiki <span id=\"count-wiki\">0</span></button><button data-area=\"raw\">▱ 原始记录 <span id=\"count-raw\">0</span></button><div class=\"nav-note\">本机工作空间<br><span>Markdown · 本地文件</span></div></nav>\n<section class=\"index\" aria-label=\"内容列表\"><div class=\"list-head\"><div><h1 id=\"area-title\">黑板</h1><p id=\"subtitle\">跨工具交接与本机工作状态</p></div><button id=\"new\" class=\"primary\">+ 新建</button></div><label class=\"search\"><span>⌕</span><input id=\"query\" type=\"search\" placeholder=\"搜索 key 或正文\" aria-label=\"搜索内容\"></label><div class=\"list-meta\"><span id=\"list-count\"></span><button id=\"refresh\">刷新</button></div><div id=\"items\"></div></section>\n<main id=\"detail\"><button id=\"back\" class=\"text-button\">← 返回总览</button><div class=\"toolbar\"><span id=\"location\"></span><div class=\"actions\"><button id=\"commit\" hidden>提交到 Git</button><button id=\"cancel\" hidden>取消</button><button id=\"edit\" class=\"primary\" hidden>编辑</button></div></div>\n<div id=\"external\" class=\"notice\" hidden><span id=\"external-message\">内容已有更新,当前草稿已保留。</span><button id=\"latest\">查看最新内容</button></div>\n<article id=\"reader\" class=\"markdown\"><div class=\"empty\">选择一条记录开始阅读</div></article>\n<section id=\"editor\" hidden><label id=\"name-label\"><span id=\"name-caption\">条目 key</span><input id=\"name\" autocomplete=\"off\"></label><div class=\"editor-head\"><span>Markdown</span><button id=\"preview\">预览</button></div><textarea id=\"source\" aria-label=\"Markdown 正文\" spellcheck=\"false\"></textarea><article id=\"preview-body\" class=\"markdown\" hidden></article><div class=\"editor-foot\"><span id=\"save-hint\"></span><span id=\"dirty\"></span></div></section>\n<footer><span id=\"meta\"></span><button id=\"delete\" class=\"text-button\" hidden>删除条目</button></footer></main>\n</div>\n<div id=\"toast\" role=\"status\" aria-live=\"polite\" hidden></div>\n<dialog id=\"dialog\"><form method=\"dialog\"><div class=\"dialog-head\"><h2 id=\"dialog-title\"></h2><button value=\"cancel\" aria-label=\"关闭\" formnovalidate>×</button></div><p id=\"dialog-message\"></p><div id=\"dialog-content\"></div><div class=\"dialog-actions\"><button value=\"cancel\" id=\"dialog-cancel\" formnovalidate>取消</button><button value=\"confirm\" id=\"dialog-confirm\" class=\"primary\">确认</button></div></form></dialog>\n<script>// Runs inside an opaque-origin sandbox. Only the transferred port can answer these calls.\nconst channel = new MessageChannel();\nconst requests = new Map();\nlet seq = 0;\nlet restore;\nwindow.agentContextSavedDraft = new Promise((resolve) => {\n restore = resolve;\n});\nwindow.agentContextSaveDraft = (draft) => channel.port1.postMessage({ type: 'draft', draft });\nchannel.port1.onmessage = ({ data }) => {\n if (data.type === 'restore') {\n restore(data.draft);\n return;\n }\n const request = requests.get(data.id);\n if (!request) return;\n requests.delete(data.id);\n if (data.status >= 400) {\n const error = new Error(data.body?.error || '请求失败');\n error.status = data.status;\n request.reject(error);\n } else request.resolve(data.body);\n};\nwindow.agentContextApi = (path, method, body) =>\n new Promise((resolve, reject) => {\n const id = ++seq;\n requests.set(id, { resolve, reject });\n channel.port1.postMessage({ id, path, method, body });\n });\nparent.postMessage({ agentContextFrame: document.querySelector('meta[name=bridge]').content }, '*', [\n channel.port2,\n]);\n</script><script>'use strict';\nconst $ = id => document.getElementById(id);\nconst state = { area: 'board', selected: null, data: {board: [], wiki: [], raw: []}, doc: null, editing: false, fresh: false, boardOpen: false, busy: false, external: false, generation: 0, refreshing: false };\nconst escapeHtml = value => String(value ?? '').replace(/[&<>\"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;',\"'\":'&#39;'}[c]));\nlet toastTimer;\nlet pointerDown = false, listHtml;\nfunction readingSelection() { const selection = window.getSelection(); return pointerDown || !!selection && !selection.isCollapsed; }\nfunction toast(message) { $('toast').textContent = message; $('toast').hidden = false; clearTimeout(toastTimer); toastTimer = setTimeout(() => $('toast').hidden = true, 6000); }\nasync function api(path, method = 'GET', body) {\n if (window.agentContextApi) return window.agentContextApi(path, method, body);\n const response = await fetch(path, {method, headers: {'Content-Type': 'application/json', 'X-Agent-Context': '1'}, ...(body === undefined ? {} : {body: JSON.stringify(body)})});\n const content = await response.text();\n let data; try { data = JSON.parse(content); } catch { data = {error: content}; }\n if (!response.ok) { const error = new Error(data.error || `请求失败 (${response.status})`); error.status = response.status; throw error; }\n return data;\n}\nfunction modal({title, message = '', content = '', confirm = '确认', cancel = '取消', onMount}) {\n if ($('dialog').open) return Promise.resolve(null);\n $('dialog-title').textContent = title; $('dialog-message').textContent = message;\n $('dialog-content').innerHTML = content; $('dialog-confirm').textContent = confirm; $('dialog-cancel').textContent = cancel;\n $('dialog').returnValue = ''; $('dialog').showModal(); onMount?.();\n return new Promise(resolve => $('dialog').addEventListener('close', () => {\n const values = Object.fromEntries([...$('dialog-content').querySelectorAll('[name]')].map(el => [el.name, el.value]));\n resolve($('dialog').returnValue === 'confirm' ? values : null);\n }, {once: true}));\n}\nfunction dirty() { return state.editing && (state.fresh || $('source').value !== (state.doc?.text || '')); }\nasync function leaveDraft() {\n if (!dirty()) return true;\n return !!await modal({title:'有尚未保存的修改', message:'离开会丢弃当前草稿。', confirm:'放弃修改', cancel:'继续编辑'});\n}\nlet trackEmbeddedDraft = false;\nfunction rememberDraft() {\n if (!trackEmbeddedDraft || !window.agentContextSaveDraft || !state.data.root) return;\n const draft = dirty() ? { root: state.data.root, area: state.area, selected: state.selected,\n fresh: state.fresh, doc: state.doc, key: $('name').value, text: $('source').value } : null;\n window.agentContextSaveDraft(draft);\n}\nfunction currentItem() { return state.data[state.area].find(row => (row.key || row.path) === state.selected); }\nfunction fingerprint(row) { return !row ? null : state.area === 'board' ? JSON.stringify([row.version,row.value,row.updated_at]) : row.revision; }\nfunction boardTitle(row) { return row.value.split('\\n').find(s => s.trim())?.replace(/^#+\\s*/, '').slice(0, 90) || row.key; }\nfunction boardSummary(row) { const lines = row.value.trim().split('\\n'); return lines.slice(1).filter(s => s.trim() && !s.startsWith('#')).join(' ').slice(0, 160); }\nfunction time(value) { const d = new Date(value); return Number.isNaN(d.valueOf()) ? value : new Intl.DateTimeFormat('zh-CN', {month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',hour12:false}).format(d); }\nfunction renderList() {\n const query = $('query').value.trim().toLowerCase();\n const rows = state.data[state.area].filter(row => `${row.key || row.path} ${row.value || row.search_text || ''} ${row.title || ''} ${(row.tags || []).join(' ')}`.toLowerCase().includes(query));\n $('list-count').textContent = `${rows.length} 条${query ? ' / 共 ' + state.data[state.area].length + ' 条' : ''}${state.area === 'board' ? ' · 最近更新' : ''}`;\n const grouped = new Map();\n for (const row of rows) { const group = state.area === 'board' ? row.key.split(':')[0] : state.area === 'raw' ? row.compiled ? '已整理' : '待整理' : '主题页面'; if (!grouped.has(group)) grouped.set(group, []); grouped.get(group).push(row); }\n const html = [...grouped].map(([group, list]) => `<div class=\"group\">${escapeHtml({repo:'仓库交接 · repo',worktree:'工作区 · worktree',port:'端口 · port',env:'环境 · env'}[group] || group)} · ${list.length}</div>` + list.map(row => {\n const key = row.key || row.path, board = state.area === 'board';\n const chosen = state.selected === key && (!board || state.boardOpen);\n const tags = row.tags || [];\n const status = state.area === 'raw' ? `<span class=\"item-status\">${row.compiled ? '已整理' : '待整理'}</span>` : '';\n const labels = !board && (tags.length || status) ? `<span class=\"item-labels\">${status}${tags.slice(0, 2).map(tag => `<span class=\"item-tag\">${escapeHtml(tag)}</span>`).join('')}${tags.length > 2 ? `<span class=\"tag-more\" title=\"${escapeHtml(tags.slice(2).join('、'))}\">+${tags.length - 2}</span>` : ''}</span>` : '';\n return `<button class=\"item${chosen ? ' selected' : ''}\" data-item=\"${escapeHtml(key)}\" aria-pressed=\"${chosen}\" title=\"${escapeHtml(key)}\"><span class=\"item-title\">${escapeHtml(board ? boardTitle(row) : row.title)}</span>${board ? `<span class=\"item-key\">${escapeHtml(key)}</span>` : ''}<span class=\"item-summary\">${escapeHtml(board ? boardSummary(row) : row.summary)}</span>${labels}${board ? `<span class=\"item-meta\"><span>${escapeHtml(time(row.updated_at))}</span><span>查看 →</span></span>` : ''}</button>`;\n }).join('')).join('') || `<div class=\"empty\">${query ? '没有匹配的内容' : state.area === 'board' ? '黑板还是空的。新建一条记录,或让 agent 写下交接。' : '这里还没有内容。'}</div>`;\n if (html !== listHtml) { $('items').innerHTML = html; listHtml = html; }\n}\nfunction chrome() {\n rememberDraft();\n $('app').className = `${state.area} ${!state.boardOpen ? 'overview' : ''}`;\n document.querySelectorAll('[data-area]').forEach(button => button.setAttribute('aria-current', button.dataset.area === state.area ? 'page' : 'false'));\n for (const area of ['board','wiki','raw']) $(`count-${area}`).textContent = state.data[area].length;\n $('area-title').textContent = {board:'黑板',wiki:'Wiki',raw:'原始记录'}[state.area];\n $('subtitle').textContent = {board:'跨工具交接与本机工作状态',wiki:'按主题积累的长期知识',raw:'写入现场的原始记录 · 只读'}[state.area];\n $('new').hidden = state.area === 'raw'; $('query').placeholder = state.area === 'board' ? '搜索 key 或正文' : '搜索标题、标签或正文';\n $('back').hidden = !state.boardOpen; $('back').textContent = state.area === 'board' ? '← 返回总览' : '← 返回列表'; $('reader').hidden = state.editing; $('editor').hidden = !state.editing;\n $('edit').hidden = state.area === 'raw' || (!state.doc && !state.editing); $('edit').textContent = state.editing ? '保存' : '编辑';\n $('cancel').hidden = !state.editing; $('delete').hidden = state.area !== 'board' || !state.doc || state.editing;\n $('commit').hidden = state.area !== 'wiki' || !state.doc || state.editing;\n $('external').hidden = !state.external;\n $('location').textContent = state.editing && state.fresh ? '新建记录' : state.selected || '';\n $('meta').textContent = state.area === 'board' ? `本机黑板 · 不进入 Git${state.doc ? ' · v' + state.doc.version + ' · ' + time(state.doc.updated_at) : ''}` : state.area === 'raw' ? '原始记录只追加,保留作为来源' : '保存到 Markdown · Git 提交单独操作';\n for (const id of ['edit','cancel','delete','commit','new']) $(id).disabled = state.busy;\n}\nfunction linkify(container) {\n const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);\n const nodes = []; while (walker.nextNode()) if (!walker.currentNode.parentElement.closest('a,code,pre')) nodes.push(walker.currentNode);\n for (const node of nodes) {\n const matches = [...node.textContent.matchAll(/\\[\\[([^\\]]+)\\]\\]/g)]; if (!matches.length) continue;\n const fragment = document.createDocumentFragment(); let at = 0;\n for (const match of matches) {\n fragment.append(node.textContent.slice(at, match.index)); const [target,label] = match[1].split('|'); const a = document.createElement('a');\n let path = target.split('#')[0]; if (!path.startsWith('wiki/') && !path.startsWith('raw/')) path = 'wiki/' + path;\n if (!path.endsWith('.md')) path += '.md'; a.href = '/?page=' + encodeURIComponent(path); a.dataset.page = path; a.textContent = label || target; fragment.append(a); at = match.index + match[0].length;\n }\n fragment.append(node.textContent.slice(at)); node.replaceWith(fragment);\n }\n container.querySelectorAll('a[href]').forEach(link => {\n if (link.dataset.page) return;\n const href = link.getAttribute('href');\n if (href.startsWith('#')) return;\n if (/^https?:\\/\\//i.test(href)) { link.target = '_blank'; link.rel = 'noopener noreferrer'; return; }\n if (!href || /^[a-z]+:/i.test(href)) return;\n try {\n const base = new URL(state.selected || 'wiki/index.md', (location.origin === 'null' ? 'https://agent-context.invalid' : location.origin) + '/');\n const url = new URL(href, base); const path = decodeURIComponent(url.pathname.slice(1));\n if (path.endsWith('.md') && /^(wiki|raw)\\//.test(path)) { link.dataset.page = path; link.href = '/?page=' + encodeURIComponent(path); }\n } catch { /* Keep malformed Markdown links inert. */ link.removeAttribute('href'); }\n });\n}\nasync function getDocument(area, id) {\n if (area === 'board') {\n const row = state.data.board.find(r => r.key === id); if (!row) return null;\n const rendered = await api('/api/preview','POST',{text:row.value});\n return {...row,text:row.value,html:rendered.html};\n }\n return api('/api/document?path=' + encodeURIComponent(id));\n}\nfunction showReader() {\n $('reader').innerHTML = state.doc?.html || '<div class=\"empty\">选择一条记录开始阅读</div>';\n if (state.area === 'raw' && state.doc) {\n const name = state.selected.replace(/\\.md$/, '');\n const sources = state.data.wiki.filter(page => page.search_text.includes(name));\n if (sources.length) $('reader').insertAdjacentHTML('beforeend', '<h2>引用此记录的页面</h2>' + sources.map(page => `<p><a href=\"/?page=${encodeURIComponent(page.path)}\" data-page=\"${escapeHtml(page.path)}\">${escapeHtml(page.title)}</a></p>`).join(''));\n }\n linkify($('reader')); chrome();\n}\nasync function select(id) {\n if (state.busy || !await leaveDraft()) return;\n state.editing = false; state.fresh = false; state.external = false; state.selected = id; state.boardOpen = true;\n const gen = ++state.generation, area = state.area; state.doc = null; chrome(); renderList(); $('detail').scrollTop = 0; $('reader').textContent = '正在读取…';\n try { const doc = await getDocument(area,id); if (gen !== state.generation) return; state.doc = doc; showReader(); }\n catch (e) { if (gen === state.generation) { $('reader').textContent = '无法读取内容:' + e.message; chrome(); } }\n}\nasync function switchArea(area) {\n if (state.busy || !await leaveDraft()) return;\n ++state.generation; state.area = area; state.selected = null; state.doc = null; state.editing = false; state.fresh = false; state.external = false; state.boardOpen = false;\n $('query').value = ''; chrome(); renderList(); $('items').scrollTop = 0; showReader();\n if (area !== 'board' && window.innerWidth > 760 && state.data[area].length) await select(state.data[area][0].path);\n}\nasync function refresh(manual = false) {\n const paused = () => !manual && readingSelection();\n if (state.refreshing || state.busy || paused()) return;\n state.refreshing = true;\n try {\n const data = await api('/api/catalog');\n if (state.busy || paused()) return;\n // Compare against the displayed document so a deferred update is retried.\n const before = fingerprint(state.doc); state.data = data;\n $('vault-name').textContent = data.root; $('connection').textContent = '● 本机已连接';\n const after = fingerprint(currentItem()); chrome(); renderList();\n if (state.selected && before !== after && !state.fresh) {\n if (state.editing) { state.external = true; $('external-message').textContent = after ? '内容已有更新,当前草稿已保留。' : '这条内容已被删除,当前草稿已保留。'; chrome(); }\n else if (after) {\n const gen = ++state.generation; const doc = await getDocument(state.area,state.selected);\n if (gen === state.generation && !state.editing && !paused()) { state.doc = doc; showReader(); }\n } else { state.doc = null; state.selected = null; showReader(); }\n }\n if (manual) toast('内容已刷新');\n } catch (e) { $('connection').textContent = '连接中断 · 自动重试'; if (manual) toast(e.message); }\n finally { state.refreshing = false; }\n}\nfunction edit(fresh = false) {\n if (!fresh && !state.doc) return;\n state.editing = true; state.fresh = fresh; state.external = false; state.boardOpen = true;\n $('name-caption').textContent = state.area === 'board' ? '条目 key(用 : 分段)' : '页面路径(wiki/ 下的 .md 文件)';\n $('name').value = fresh ? state.area === 'board' ? '' : 'wiki/' : state.selected;\n $('name').readOnly = !fresh; $('source').value = fresh ? '# 新记录\\n\\n' : state.doc.text;\n $('source').hidden = false; $('preview-body').hidden = true; $('preview').textContent = '预览';\n $('save-hint').textContent = state.area === 'board' ? '保存时检查版本,避免覆盖其他会话的修改' : '保留完整 Markdown(含元数据);保存后可单独提交 Git';\n $('dirty').textContent = fresh ? '未保存' : ''; chrome(); if (fresh) $('name').focus(); else $('source').focus();\n}\nasync function newItem() { if (state.busy || !await leaveDraft()) return; ++state.generation; state.selected = null; state.doc = null; edit(true); renderList(); }\nasync function save() {\n if (state.busy) return;\n const key = $('name').value.trim(), text = $('source').value;\n if (!key || !text.trim()) return toast('请填写名称和正文');\n const area = state.area; state.busy = true; chrome();\n try {\n if (area === 'board') await api('/api/board','POST',{key,value:text,expect_version:state.fresh ? 0 : state.doc.version});\n else await api('/api/document','PUT',{path:key,text,expected_revision:state.fresh ? null : state.doc.revision});\n state.editing = false; state.fresh = false; state.external = false; state.selected = key;\n // Read the canonical saved text/version (board writes trim whitespace).\n state.data = await api('/api/catalog'); state.doc = await getDocument(area,key); ++state.generation;\n showReader(); renderList(); toast('已保存到本机文件');\n } catch (e) { if (e.status === 409) { state.external = true; $('external-message').textContent = '保存冲突:其他会话已修改内容,当前草稿已保留。'; } toast(e.message); }\n finally { state.busy = false; chrome(); }\n}\nasync function showLatest() {\n try {\n const data = await api('/api/catalog'); state.data = data; renderList();\n const latest = await getDocument(state.area,state.selected || $('name').value.trim());\n if (!latest) return toast('内容已被删除,请复制草稿后新建记录');\n const result = await modal({title:'合并最新内容',message:'对照最新内容修改下方草稿。确认后更新编辑基准,仍需点击保存。',content:'<label>最新内容<textarea name=\"latest\" readonly></textarea></label><label>你的草稿(可在此合并)<textarea name=\"merged\"></textarea></label>',confirm:'使用合并草稿',cancel:'继续原草稿',onMount:()=>{document.querySelector('[name=latest]').value = latest.text; document.querySelector('[name=merged]').value = $('source').value;}});\n if (result) { state.doc = latest; state.fresh = false; state.external = false; state.selected = latest.key || latest.path; $('name').value = state.selected; $('name').readOnly = true; $('source').value = result.merged; $('source').hidden = false; $('preview-body').hidden = true; $('preview').textContent = '预览'; $('dirty').textContent = dirty() ? '未保存' : ''; chrome(); }\n } catch (e) { toast(e.message); }\n}\nasync function remove() {\n const doc = state.doc; if (!doc || state.busy) return;\n if (!await modal({title:'删除黑板记录',message:`将删除 ${doc.key}。黑板没有 Git 历史,删除后无法在页面中撤销。`,confirm:'删除记录'})) return;\n state.busy = true; chrome();\n try { await api('/api/board','DELETE',{key:doc.key,expect_version:doc.version}); state.doc = null; state.selected = null; state.boardOpen = false; state.data = await api('/api/catalog'); renderList(); showReader(); toast('记录已删除'); }\n catch (e) { toast(e.message); }\n finally { state.busy = false; chrome(); }\n}\nasync function commit() {\n if (state.busy) return;\n try {\n const info = await api('/api/git?path=' + encodeURIComponent(state.selected));\n if (!info.changed) return toast('当前页面没有待提交的修改');\n const result = await modal({title:'提交当前 Wiki 页面',message:`仅提交 ${state.selected},其他文件保持原样。${info.new_file ? '这是新页面,下方展示完整内容。' : ''}`,content:`<pre>${escapeHtml(info.diff)}</pre><label>提交说明<input name=\"message\" required placeholder=\"说明这次修改\"></label>`,confirm:'提交到 Git'});\n if (!result) return; if (!result.message.trim()) return toast('请输入提交说明');\n state.busy = true; chrome();\n const outcome = await api('/api/git','POST',{path:info.path,expected_revision:info.revision,message:result.message});\n toast(outcome.committed ? `已提交 ${outcome.commit}` : '没有待提交的修改');\n } catch (e) { toast(e.message); }\n finally { state.busy = false; chrome(); }\n}\n// All persisted changes are explicit actions; polling never replaces a draft.\n// Keep DOM nodes stable while dragging or copying, including requests already in flight.\nwindow.addEventListener('pointerdown', () => { pointerDown = true; }, true);\nwindow.addEventListener('pointerup', () => { pointerDown = false; }, true);\nwindow.addEventListener('pointercancel', () => { pointerDown = false; }, true);\nwindow.addEventListener('blur', () => { pointerDown = false; });\ndocument.querySelectorAll('[data-area]').forEach(button => button.addEventListener('click',()=>switchArea(button.dataset.area)));\n$('items').addEventListener('click',event => {const button=event.target.closest('[data-item]');if(button) select(button.dataset.item);});\n$('detail').addEventListener('click',async event => {const link=event.target.closest('[data-page]');if(!link)return;event.preventDefault();const path=link.dataset.page;if(state.busy||!await leaveDraft())return;state.editing=false;state.area=path.startsWith('raw/')?'raw':'wiki';$('query').value='';await select(path);});\n$('query').addEventListener('input',renderList); $('refresh').onclick=()=>refresh(true); $('new').onclick=newItem;\n$('edit').onclick=()=>state.editing?save():edit(); $('cancel').onclick=async()=>{if(await leaveDraft()){state.editing=false;state.fresh=false;state.external=false;if(state.selected)await select(state.selected);else {state.boardOpen=false;showReader();}}};\n$('back').onclick=async()=>{if(state.busy||!await leaveDraft())return;++state.generation;state.editing=false;state.fresh=false;state.external=false;state.boardOpen=false;chrome();renderList();};\n$('delete').onclick=remove; $('commit').onclick=commit; $('latest').onclick=showLatest;\n$('source').addEventListener('input',()=>{$('dirty').textContent=dirty()?'未保存':'';});\n$('preview').onclick=async()=>{if(!$('preview-body').hidden){$('preview-body').hidden=true;$('source').hidden=false;$('preview').textContent='预览';return;}try{const result=await api('/api/preview','POST',{text:$('source').value});$('preview-body').innerHTML=result.html;linkify($('preview-body'));$('preview-body').hidden=false;$('source').hidden=true;$('preview').textContent='返回编辑';}catch(e){toast(e.message);}};\nwindow.addEventListener('beforeunload',event=>{if(dirty()){event.preventDefault();event.returnValue='';}});\nwindow.addEventListener('keydown',event=>{if((event.metaKey||event.ctrlKey)&&event.key==='s'&&state.editing){event.preventDefault();save();}});\nif (window.agentContextApi) {\n document.addEventListener('input', rememberDraft);\n document.querySelector('.brand').onclick = async event => { event.preventDefault(); await switchArea('board'); };\n}\n\n(async () => {\n const draft = await window.agentContextSavedDraft;\n await refresh();\n if (draft && draft.root === state.data.root && ['board','wiki'].includes(draft.area)) {\n state.area = draft.area; state.selected = draft.selected; state.doc = draft.doc;\n edit(draft.fresh);\n $('name').value = draft.key; $('source').value = draft.text; $('dirty').textContent = '未保存';\n renderList(); await refresh(true);\n } else {\n const path = new URLSearchParams(location.search).get('page');\n if (path && /^(wiki|raw)\\//.test(path)) { state.area = path.startsWith('raw/') ? 'raw' : 'wiki'; await select(path); }\n else { chrome(); renderList(); }\n }\n trackEmbeddedDraft = true;\n setInterval(() => refresh(), 3000);\n})();\n</script></body></html>\n";
7
+ const drafts = new Map();
8
+ const base = new URL('api/agent-context/', document.baseURI);
9
+ function Frame({ vault, title }) {
10
+ const ref = React.useRef(null);
11
+ const [doc, setDoc] = React.useState('');
12
+ React.useEffect(() => {
13
+ const token = crypto.randomUUID();
14
+ let port;
15
+ const controller = new AbortController();
16
+ function connect(e) {
17
+ if (
18
+ port ||
19
+ e.source !== ref.current?.contentWindow ||
20
+ e.origin !== 'null' ||
21
+ e.data?.agentContextFrame !== token ||
22
+ !e.ports[0]
23
+ )
24
+ return;
25
+ port = e.ports[0];
26
+ port.onmessage = async ({ data }) => {
27
+ if (data.type === 'draft') {
28
+ if (data.draft) drafts.set(vault, data.draft);
29
+ else drafts.delete(vault);
30
+ return;
31
+ }
32
+ let status = 503,
33
+ body;
34
+ try {
35
+ const res = await fetch(new URL('request', base), {
36
+ method: 'POST',
37
+ credentials: 'same-origin',
38
+ signal: controller.signal,
39
+ headers: { 'Content-Type': 'application/json', 'X-Agent-Context': '1' },
40
+ body: JSON.stringify({ vault, path: data.path, method: data.method, body: data.body }),
41
+ });
42
+ status = res.status;
43
+ body = await res.json();
44
+ } catch (err) {
45
+ status = 503;
46
+ body = { error: err.message };
47
+ }
48
+ if (!controller.signal.aborted) port.postMessage({ id: data.id, status, body });
49
+ };
50
+ port.postMessage({ type: 'restore', draft: drafts.get(vault) ?? null });
51
+ }
52
+ window.addEventListener('message', connect);
53
+ setDoc(source.replace('__BRIDGE_TOKEN__', token));
54
+ return () => {
55
+ window.removeEventListener('message', connect);
56
+ controller.abort();
57
+ port?.close();
58
+ };
59
+ }, [vault]);
60
+ return (
61
+ doc &&
62
+ h('iframe', {
63
+ ref,
64
+ title,
65
+ srcDoc: doc,
66
+ sandbox: 'allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox',
67
+ style: { border: 0, flex: 1, width: '100%', minHeight: 0 },
68
+ })
69
+ );
70
+ }
71
+ function Page({ t }) {
72
+ const [vaults, setVaults] = React.useState(null),
73
+ [selected, setSelected] = React.useState('');
74
+ const [error, setError] = React.useState(''),
75
+ [attempt, setAttempt] = React.useState(0);
76
+ React.useEffect(() => {
77
+ const c = new AbortController();
78
+ fetch(new URL('vaults', base), { credentials: 'same-origin', cache: 'no-store', signal: c.signal })
79
+ .then(async (res) => {
80
+ if (!res.ok) throw Error(String(res.status));
81
+ return res.json();
82
+ })
83
+ .then((names) => {
84
+ if (!c.signal.aborted) {
85
+ setVaults(names);
86
+ setSelected(names[0] || '');
87
+ setError('');
88
+ }
89
+ })
90
+ .catch((err) => {
91
+ if (!c.signal.aborted) setError(err.message);
92
+ });
93
+ return () => c.abort();
94
+ }, [attempt]);
95
+ return h(
96
+ 'section',
97
+ { style: { display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0 } },
98
+ vaults?.length > 1 &&
99
+ h(
100
+ 'select',
101
+ { 'aria-label': t('vault'), value: selected, onChange: (e) => setSelected(e.target.value) },
102
+ vaults.map((n) => h('option', { key: n }, n)),
103
+ ),
104
+ selected
105
+ ? h(Frame, { key: selected, vault: selected, title: t('title') })
106
+ : h(
107
+ 'div',
108
+ { role: 'status' },
109
+ error || t(vaults ? 'empty' : 'waiting'),
110
+ ' ',
111
+ h('button', { onClick: () => setAttempt((i) => i + 1) }, t('refresh')),
112
+ ),
113
+ );
114
+ }
115
+ function Icon({ size }) {
116
+ return h(
117
+ 'svg',
118
+ {
119
+ viewBox: '0 0 24 24',
120
+ width: size,
121
+ height: size,
122
+ fill: 'none',
123
+ stroke: 'currentColor',
124
+ strokeWidth: 1.7,
125
+ 'aria-hidden': true,
126
+ },
127
+ h('path', { d: 'M12 6c-2-2-6-2-9-1v14c3-1 7-1 9 1 2-2 6-2 9-1V5c-3-1-7-1-9 1Zm0 0v14' }),
128
+ );
129
+ }
130
+ return {
131
+ inject: ['locale', 'slots'],
132
+ apply(ctx) {
133
+ ctx.effect(() => () => drafts.clear());
134
+ const ns = 'agentContextPage',
135
+ key = 'agent-context';
136
+ ctx.effect(() =>
137
+ ctx.locale.register(ns, {
138
+ zh: {
139
+ title: 'Agent Context',
140
+ vault: '知识库',
141
+ waiting: '正在读取知识库',
142
+ empty: '没有已启用的知识库',
143
+ refresh: '刷新',
144
+ },
145
+ en: {
146
+ title: 'Agent Context',
147
+ vault: 'Vault',
148
+ waiting: 'Loading vaults',
149
+ empty: 'No enabled vaults',
150
+ refresh: 'Refresh',
151
+ },
152
+ }),
153
+ );
154
+ const t = ctx.locale.bind(ns);
155
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key, locale: ns }, Page));
156
+ ctx.slots.inject('sidebar.panellist', () =>
157
+ ctx.slots.register(
158
+ { name: 'sidebar.panellist', id: key, order: 20, label: () => t('title'), locale: ns },
159
+ Icon,
160
+ ),
161
+ );
162
+ },
163
+ };
164
+ },
165
+ });
package/lib/index.js ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * agent-context for DeepSeek Harness.
3
+ *
4
+ * Registers the `agent-context` MCP server (stdio, `agent-context serve`) on
5
+ * the host's `mcpManager`, so a DSH session reads and writes the same personal
6
+ * wiki vault and blackboard as every other agent tool on the machine.
7
+ *
8
+ * Named exports only. A default export would hide the loader metadata (`name`,
9
+ * `inject`, `Config`) from the cordis loader, which is why the host's own
10
+ * plugins avoid one.
11
+ *
12
+ * `inject: ['mcpManager']` means `apply` runs while the MCP manager service is
13
+ * present and is torn down with it; the registration itself is held by
14
+ * `ctx.effect`, so disabling or reconfiguring the plugin unregisters the
15
+ * server.
16
+ *
17
+ * @module dsh-agent-context
18
+ */
19
+
20
+ import z from '@deepseek-ai/schemastery';
21
+
22
+ import { attachVault } from './web-host.js';
23
+ import { mountAgentContext } from './mount.js';
24
+
25
+ export const name = 'agent-context';
26
+
27
+ export const inject = ['mcpManager'];
28
+
29
+ export const Config = z.object({
30
+ serverName: z
31
+ .string()
32
+ .default('agent-context')
33
+ .description('Name the MCP server is registered under in the host.'),
34
+ vaultRoot: z
35
+ .string()
36
+ .default('')
37
+ .description(
38
+ 'Absolute path of the vault, passed to the server as AGENT_CONTEXT_ROOT. It must already exist and contain raw/ and wiki/ (create it with `agent-context init <dir>`). "~" is not expanded. Empty: reuse an existing vault or initialize the managed user vault.',
39
+ ),
40
+ binaryPath: z
41
+ .string()
42
+ .default('')
43
+ .description(
44
+ 'Absolute path of the agent-context executable. Empty: absolute PATH entries are searched, then Cargo’s bin directory and the bundled executable. When set, the path is used as given and must be an executable file — there is no fallback.',
45
+ ),
46
+ });
47
+
48
+ /**
49
+ * @param {import('@deepseek-ai/cordis').Context} ctx
50
+ * @param {{ serverName: string, vaultRoot: string, binaryPath: string }} config
51
+ */
52
+ export function apply(ctx, config) {
53
+ // schemastery has already applied every default, so `config` is complete.
54
+ const registration = mountAgentContext(ctx, config);
55
+ ctx.effect(() => attachVault(ctx, registration));
56
+ }
package/lib/mount.js ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Mounts one stdio MCP server — `agent-context serve` — on the host's
3
+ * `mcpManager`.
4
+ *
5
+ * Kept apart from `./index.js` so the wiring can be driven by `node --test`
6
+ * with a fake context: this module imports no DSH package, while `./index.js`
7
+ * owns the schemastery `Config` and the loader metadata.
8
+ *
9
+ * Lifecycle: `mcpManager.register()` returns a disposer, and it is handed
10
+ * straight to `ctx.effect()`. The server is therefore unregistered when the
11
+ * plugin is disabled, reloaded, or reconfigured — the same pattern the host's
12
+ * own plugins use for service registrations.
13
+ *
14
+ * @module dsh-agent-context/mount
15
+ */
16
+
17
+ import { ConfigError, resolveBinary } from './resolve.js';
18
+ import { selectVault } from './vault.js';
19
+
20
+ /**
21
+ * Accepted MCP server names. Conservative on purpose: the name becomes a tool
22
+ * namespace in the host, so punctuation and whitespace are kept out.
23
+ */
24
+ export const SERVER_NAME_PATTERN = /^[A-Za-z0-9_-]{1,32}$/;
25
+
26
+ /** Argument vector for the server. `serve` speaks MCP over stdio. */
27
+ export const SERVE_ARGS = ['serve'];
28
+
29
+ const NOOP_LOGGER = { info() {} };
30
+
31
+ /** Resolve the executable and vault before registering one server for this plugin's lifetime. */
32
+ export function mountAgentContext(ctx, config = {}, options = {}) {
33
+ const logger = ctx.logger ?? NOOP_LOGGER;
34
+
35
+ const serverName = typeof config.serverName === 'string' ? config.serverName.trim() : '';
36
+ if (!SERVER_NAME_PATTERN.test(serverName)) {
37
+ throw new ConfigError(
38
+ `serverName must match ${SERVER_NAME_PATTERN.source}, got ${JSON.stringify(config.serverName ?? '')}`,
39
+ );
40
+ }
41
+
42
+ const binary = resolveBinary(config.binaryPath, options);
43
+ if (!binary) {
44
+ throw new ConfigError(`no executable for ${process.platform}-${process.arch}; install the packaged plugin or set binaryPath to your agent-context executable`);
45
+ }
46
+ const vault = selectVault(config.vaultRoot, binary.path, options);
47
+
48
+ // Exactly the registration documented in docs/clients.md: stdio transport,
49
+ // `serve`, and the vault passed through AGENT_CONTEXT_ROOT. The env is this
50
+ // single variable; the host supplies the rest of the child environment, and
51
+ // nothing else from this plugin's own environment is forwarded.
52
+ ctx.effect(() =>
53
+ ctx.mcpManager.register(serverName, {
54
+ transport: 'stdio',
55
+ command: binary.path,
56
+ args: [...SERVE_ARGS],
57
+ env: { AGENT_CONTEXT_ROOT: vault.root },
58
+ }),
59
+ );
60
+
61
+ logger.info(
62
+ `agent-context: submitted MCP server "${serverName}" for connection (binary resolved from ${binary.source})`,
63
+ );
64
+
65
+ return {
66
+ registered: true,
67
+ serverName,
68
+ command: binary.path,
69
+ vaultRoot: vault.root,
70
+ source: binary.source,
71
+ };
72
+ }
73
+
74
+ export { ConfigError };
package/lib/resolve.js ADDED
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Configuration resolution for the agent-context DSH Host plugin.
3
+ *
4
+ * This module deliberately imports nothing from DSH or cordis, so the rules it
5
+ * encodes can be exercised with plain `node --test` in a checkout that has no
6
+ * dependencies installed.
7
+ *
8
+ * Two rules matter here, and both fail closed:
9
+ *
10
+ * - An explicitly configured `binaryPath` is validated and never falls back to
11
+ * a search. A user who names an executable gets that executable or an error,
12
+ * not a different binary found somewhere on PATH.
13
+ * - A vault root must be an absolute, existing directory that really is a
14
+ * vault (`raw/` and `wiki/`, the same two directories `Vault::open` requires
15
+ * in `src/vault.rs`). Explicit roots are validated without modification.
16
+ *
17
+ * Resolution never spawns a shell: `command -v` would pull in a login shell's
18
+ * PATH and arbitrary profile scripts. Candidates are probed with `fs` only.
19
+ *
20
+ * @module dsh-agent-context/resolve
21
+ */
22
+
23
+ import { accessSync, constants, statSync } from 'node:fs';
24
+ import { homedir as osHomedir } from 'node:os';
25
+ import { delimiter, isAbsolute, join } from 'node:path';
26
+ import { fileURLToPath } from 'node:url';
27
+
28
+ /** Executable installed by `cargo install --locked --path .`. */
29
+ export const BINARY_NAME = 'agent-context';
30
+
31
+ /** Directories that make a directory a vault, per `Vault::open` in `src/vault.rs`. */
32
+ export const VAULT_SUBDIRS = ['raw', 'wiki'];
33
+
34
+ /** Last-resort install location searched after PATH: `~/.cargo/bin`. */
35
+ export const CARGO_BIN_SEGMENTS = ['.cargo', 'bin'];
36
+
37
+ /**
38
+ * A configuration value the user has to fix. Thrown rather than logged: a
39
+ * misconfigured plugin should be visibly broken, not quietly inactive.
40
+ */
41
+ export class ConfigError extends Error {
42
+ constructor(message) {
43
+ super(message.startsWith('agent-context:') ? message : `agent-context: ${message}`);
44
+ this.name = 'ConfigError';
45
+ }
46
+ }
47
+
48
+ /** Trim a possibly absent string config field down to a plain string. */
49
+ function text(value) {
50
+ return typeof value === 'string' ? value.trim() : '';
51
+ }
52
+
53
+ /**
54
+ * File names to probe for one directory. Windows keeps the bare name as well,
55
+ * so a shim without an extension is still found.
56
+ *
57
+ * @param {NodeJS.Platform} platform
58
+ */
59
+ function executableNames(platform) {
60
+ return platform === 'win32' ? [`${BINARY_NAME}.exe`, BINARY_NAME] : [BINARY_NAME];
61
+ }
62
+
63
+ /**
64
+ * True when `candidate` is a regular file this process may execute.
65
+ *
66
+ * `access(X_OK)` is used instead of inspecting `mode` bits so the answer
67
+ * accounts for the effective user. (As root, X_OK is permissive: it reports
68
+ * success when any execute bit is set.) On Windows the execute bit carries no
69
+ * meaning, so being a regular file is all that is checked.
70
+ *
71
+ * @param {string} candidate absolute path
72
+ * @param {NodeJS.Platform} platform
73
+ */
74
+ export function isExecutableFile(candidate, platform = process.platform) {
75
+ let stats;
76
+ try {
77
+ stats = statSync(candidate);
78
+ } catch {
79
+ return false;
80
+ }
81
+ if (!stats.isFile()) return false;
82
+ if (platform === 'win32') return true;
83
+ try {
84
+ accessSync(candidate, constants.X_OK);
85
+ return true;
86
+ } catch {
87
+ return false;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Locate the `agent-context` executable.
93
+ *
94
+ * @param {string | undefined} binaryPath the configured path; empty means "search"
95
+ * @param {object} [options]
96
+ * @param {NodeJS.ProcessEnv} [options.env] environment to read PATH from
97
+ * @param {string} [options.homedir] home directory used for `~/.cargo/bin`
98
+ * @param {NodeJS.Platform} [options.platform]
99
+ * @returns {{ path: string, source: 'config' | 'path' | 'cargo' | 'bundled' } | null}
100
+ * `null` when nothing was configured and no candidate was found; the caller
101
+ * then stays inactive instead of guessing.
102
+ * @throws {ConfigError} when `binaryPath` is set but is not an absolute path to
103
+ * an executable file. No search is attempted in that case.
104
+ */
105
+ export function resolveBinary(binaryPath, options = {}) {
106
+ const env = options.env ?? process.env;
107
+ const platform = options.platform ?? process.platform;
108
+ const home = options.homedir ?? osHomedir();
109
+ const names = executableNames(platform);
110
+
111
+ const configured = text(binaryPath);
112
+ if (configured !== '') {
113
+ if (!isAbsolute(configured)) {
114
+ throw new ConfigError(
115
+ `binaryPath must be an absolute path to the agent-context executable, got ${JSON.stringify(configured)}`,
116
+ );
117
+ }
118
+ if (!isExecutableFile(configured, platform)) {
119
+ throw new ConfigError(
120
+ `binaryPath is not an executable file: ${configured} — fix the path or clear it to search PATH and ~/.cargo/bin`,
121
+ );
122
+ }
123
+ return { path: configured, source: 'config' };
124
+ }
125
+
126
+ // PATH, absolute entries only. A relative entry (including the empty string,
127
+ // which means "current directory") resolves against whatever working
128
+ // directory the host happens to have, so it is skipped rather than searched.
129
+ const rawPath = typeof env.PATH === 'string' ? env.PATH : (env.Path ?? '');
130
+ for (const entry of String(rawPath).split(delimiter)) {
131
+ const dir = entry.trim();
132
+ if (dir === '' || !isAbsolute(dir)) continue;
133
+ for (const name of names) {
134
+ const candidate = join(dir, name);
135
+ if (isExecutableFile(candidate, platform)) {
136
+ return { path: candidate, source: 'path' };
137
+ }
138
+ }
139
+ }
140
+
141
+ // The documented install location, for a GUI host that did not inherit a
142
+ // shell PATH (see docs/clients.md).
143
+ const cargoDirs = [];
144
+ if (env.CARGO_HOME && isAbsolute(env.CARGO_HOME)) cargoDirs.push(join(env.CARGO_HOME, 'bin'));
145
+ if (home && isAbsolute(home)) cargoDirs.push(join(home, ...CARGO_BIN_SEGMENTS));
146
+ for (const dir of new Set(cargoDirs)) {
147
+ for (const name of names) {
148
+ const candidate = join(dir, name);
149
+ if (isExecutableFile(candidate, platform)) return { path: candidate, source: 'cargo' };
150
+ }
151
+ }
152
+ const nativeRoot = options.nativeRoot ?? fileURLToPath(new URL('../native/', import.meta.url));
153
+ const bundled = join(nativeRoot, platform + '-' + (options.arch ?? process.arch), names[0]);
154
+ if (isExecutableFile(bundled, platform)) return { path: bundled, source: 'bundled' };
155
+ return null;
156
+ }
157
+
158
+ /**
159
+ * Validate the configured vault root.
160
+ *
161
+ * @param {string | undefined} vaultRoot
162
+ * @returns {{ root: string } | null} `null` when nothing is configured
163
+ * @throws {ConfigError} when the value is set but is not an absolute path to an
164
+ * existing vault directory
165
+ */
166
+ export function resolveVault(vaultRoot) {
167
+ const configured = text(vaultRoot);
168
+ if (configured === '') return null;
169
+
170
+ if (!isAbsolute(configured)) {
171
+ throw new ConfigError(
172
+ `vaultRoot must be an absolute path (agent-context does not expand "~"), got ${JSON.stringify(configured)}`,
173
+ );
174
+ }
175
+
176
+ let stats;
177
+ try {
178
+ stats = statSync(configured);
179
+ } catch {
180
+ throw new ConfigError(
181
+ `vaultRoot does not exist: ${configured} — create a vault with \`agent-context init <dir>\` first`,
182
+ );
183
+ }
184
+ if (!stats.isDirectory()) {
185
+ throw new ConfigError(`vaultRoot is not a directory: ${configured}`);
186
+ }
187
+
188
+ for (const sub of VAULT_SUBDIRS) {
189
+ const dir = join(configured, sub);
190
+ let subStats;
191
+ try {
192
+ subStats = statSync(dir);
193
+ } catch {
194
+ subStats = undefined;
195
+ }
196
+ if (subStats === undefined || !subStats.isDirectory()) {
197
+ throw new ConfigError(
198
+ `vaultRoot is not an agent-context vault (missing ${sub}/): ${configured} — create one with \`agent-context init\``,
199
+ );
200
+ }
201
+ }
202
+
203
+ return { root: configured };
204
+ }
package/lib/vault.js ADDED
@@ -0,0 +1,59 @@
1
+ import { lstatSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { isAbsolute, join } from 'node:path';
4
+ import { execFileSync } from 'node:child_process';
5
+ import { ConfigError, resolveVault } from './resolve.js';
6
+
7
+ function exists(path) {
8
+ return lstatSync(path, { throwIfNoEntry: false }) !== undefined;
9
+ }
10
+
11
+ export function selectVault(configured, command, options = {}) {
12
+ const env = options.env ?? process.env;
13
+ const home = options.homedir ?? homedir();
14
+ const explicit = resolveVault(configured) ?? resolveVault(env.AGENT_CONTEXT_ROOT);
15
+ if (explicit) return explicit;
16
+ if (!home || !isAbsolute(home)) throw new ConfigError('cannot determine home directory; set vaultRoot');
17
+
18
+ const settings = join(env.XDG_CONFIG_HOME || join(home, '.config'), 'agent-context', 'web.json');
19
+ if (isAbsolute(settings) && exists(settings)) {
20
+ let saved;
21
+ try {
22
+ saved = JSON.parse(readFileSync(settings, 'utf8'));
23
+ } catch (error) {
24
+ throw new ConfigError(`cannot read ${settings}: ${error.message}; set vaultRoot`);
25
+ }
26
+ const vault = resolveVault(saved?.root);
27
+ if (!vault) throw new ConfigError(`missing vault root in ${settings}; set vaultRoot`);
28
+ return vault;
29
+ }
30
+
31
+ // Only adopt a conventional location if it is already a vault. It may be a source checkout.
32
+ const conventional = join(home, 'agent-context');
33
+ if (exists(join(conventional, 'wiki')) && exists(join(conventional, 'raw'))) return resolveVault(conventional);
34
+
35
+ const data = env.XDG_DATA_HOME || (process.platform === 'win32' && env.LOCALAPPDATA) || join(home, '.local', 'share');
36
+ if (!isAbsolute(data)) throw new ConfigError('user data directory must be absolute; set vaultRoot');
37
+ const parent = join(data, 'agent-context');
38
+ const dest = join(parent, 'vault');
39
+ if (exists(dest)) return resolveVault(dest);
40
+
41
+ // Publish a complete vault in one rename. A failed init never leaves a half-built default.
42
+ mkdirSync(parent, { recursive: true, mode: 0o700 });
43
+ const staging = mkdtempSync(join(parent, '.init-'));
44
+ try {
45
+ const initEnv = { ...env, AGENT_CONTEXT_ROOT: staging };
46
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR']) delete initEnv[key];
47
+ execFileSync(command, ['init', staging], { env: initEnv, stdio: 'pipe', timeout: 15000, windowsHide: true });
48
+ resolveVault(staging);
49
+ try {
50
+ renameSync(staging, dest);
51
+ } catch (error) {
52
+ if (!exists(dest)) throw error;
53
+ // Another DSH profile can win the first-start race.
54
+ }
55
+ return resolveVault(dest);
56
+ } finally {
57
+ rmSync(staging, { force: true, recursive: true });
58
+ }
59
+ }
@@ -0,0 +1,117 @@
1
+ // One route owner per bundle, with one lazily started stdio worker per enabled vault.
2
+ import { spawn } from 'node:child_process';
3
+ import { createInterface } from 'node:readline';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const hosts = new WeakMap();
7
+ function vaults(ctx) {
8
+ const root = ctx.root ?? ctx;
9
+ if (!hosts.has(root)) hosts.set(root, new Map());
10
+ return hosts.get(root);
11
+ }
12
+
13
+ function backend(root) {
14
+ const executable = fileURLToPath(
15
+ new URL(
16
+ `../native/${process.platform}-${process.arch}/agent-context${process.platform === 'win32' ? '.exe' : ''}`,
17
+ import.meta.url,
18
+ ),
19
+ );
20
+ let active;
21
+ function stop(session, error) {
22
+ if (active === session) active = undefined;
23
+ session.child.kill();
24
+ for (const request of session.pending.splice(0)) request.reject(error);
25
+ }
26
+ function start() {
27
+ const child = spawn(executable, ['--root', root, 'web', '--stdio'], {
28
+ env: { ...process.env, AGENT_CONTEXT_ROOT: root },
29
+ stdio: ['pipe', 'pipe', 'ignore'],
30
+ windowsHide: true,
31
+ });
32
+ const session = { child, pending: [] };
33
+ active = session;
34
+ createInterface({ input: child.stdout }).on('line', (line) => {
35
+ const request = session.pending[0];
36
+ if (!request) return;
37
+ try {
38
+ const reply = JSON.parse(line);
39
+ session.pending.shift();
40
+ request.resolve(reply);
41
+ } catch (error) {
42
+ stop(session, error);
43
+ }
44
+ });
45
+ child.stdin.on('error', (error) => stop(session, error));
46
+ child.on('error', (error) => stop(session, error));
47
+ child.once('close', () => stop(session, new Error('Agent Context web backend closed')));
48
+ return session;
49
+ }
50
+ return {
51
+ request(input) {
52
+ const session = active ?? start();
53
+ return new Promise((resolve, reject) => {
54
+ session.pending.push({ resolve, reject });
55
+ session.child.stdin.write(JSON.stringify(input) + '\n');
56
+ });
57
+ },
58
+ close() {
59
+ if (active) stop(active, new Error('Vault disabled'));
60
+ },
61
+ };
62
+ }
63
+
64
+ export function attachVault(ctx, registration) {
65
+ const list = vaults(ctx);
66
+ const server = backend(registration.vaultRoot);
67
+ list.set(registration.serverName, server);
68
+ return () => {
69
+ if (list.get(registration.serverName) === server) list.delete(registration.serverName);
70
+ server.close();
71
+ };
72
+ }
73
+
74
+ export const inject = ['connection'];
75
+ export function apply(ctx) {
76
+ const list = vaults(ctx);
77
+ const headers = { 'cache-control': 'no-store' };
78
+ const json = (body, status = 200) => Response.json(body, { status, headers });
79
+ ctx.effect(() =>
80
+ ctx.connection.fetch.register({
81
+ path: '/api/agent-context/vaults',
82
+ methods: ['GET'],
83
+ requestBody: 'buffered',
84
+ fetch: async () => json([...list.keys()]),
85
+ }),
86
+ );
87
+ ctx.effect(() =>
88
+ ctx.connection.fetch.register({
89
+ path: '/api/agent-context/request',
90
+ methods: ['POST'],
91
+ requestBody: 'buffered',
92
+ async fetch(req) {
93
+ if (
94
+ req.headers.get('content-type')?.split(';')[0] !== 'application/json' ||
95
+ req.headers.get('x-agent-context') !== '1'
96
+ )
97
+ return json({ error: 'Expected an Agent Context request' }, 415);
98
+ const input = await req.json().catch(() => null);
99
+ if (
100
+ !input ||
101
+ typeof input.path !== 'string' ||
102
+ !/^\/api\/(catalog|document|board|preview|git)(\?|$)/.test(input.path) ||
103
+ !['GET', 'POST', 'PUT', 'DELETE'].includes(input.method)
104
+ )
105
+ return json({ error: 'Invalid Web API request' }, 400);
106
+ const server = list.get(input.vault);
107
+ if (!server) return json({ error: 'Knowledge base unavailable' }, 404);
108
+ try {
109
+ const reply = await server.request({ path: input.path, method: input.method, body: input.body });
110
+ return json(reply.body, reply.status);
111
+ } catch (error) {
112
+ return json({ error: error.message }, 503);
113
+ }
114
+ },
115
+ }),
116
+ );
117
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Agent Context · Personal wiki",
4
+ "description": "Search your knowledge, capture notes, and share a local blackboard in DSH. Existing settings take priority; first-time users get a new vault."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Agent Context · 个人知识库",
4
+ "description": "在 DSH 中检索知识、追加记录并共享本机黑板。首次使用会初始化知识库,已有配置会优先复用。"
5
+ }
6
+ }
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "@zephor/dsh-agent-context",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "license": "MIT",
5
+ "description": "agent-context for DeepSeek Harness: registers the agent-context MCP server (stdio) so a DSH session shares one personal wiki vault and blackboard with every other agent tool on the machine.",
6
+ "type": "module",
7
+ "main": "lib/index.js",
8
+ "exports": {
9
+ ".": "./lib/index.js",
10
+ "./cordis.patch.yml": "./cordis.patch.yml",
11
+ "./icon.svg": "./icon.svg",
12
+ "./locale/*.json": "./locale/*.json",
13
+ "./package.json": "./package.json",
14
+ "./web-host": "./lib/web-host.js",
15
+ "./client": "./lib/client.js"
16
+ },
17
+ "files": [
18
+ "cordis.patch.yml",
19
+ "icon.svg",
20
+ "locale/*.json",
21
+ "lib/*.js",
22
+ "README.md",
23
+ "native/",
24
+ "scripts/check-native.mjs"
25
+ ],
26
+ "icon": "./icon.svg",
27
+ "keywords": [
28
+ "dsh",
29
+ "deepseek-harness",
30
+ "mcp",
31
+ "agent-context",
32
+ "wiki",
33
+ "blackboard"
34
+ ],
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/Zephor5/agent-context.git",
38
+ "directory": "integrations/dsh"
39
+ },
40
+ "scripts": {
41
+ "test": "node --test",
42
+ "prepack": "npm run build:web && node scripts/check-native.mjs",
43
+ "build:web": "node scripts/build-web.mjs"
44
+ },
45
+ "dependencies": {
46
+ "@deepseek-ai/schemastery": "~3.18.5"
47
+ },
48
+ "peerDependencies": {
49
+ "@deepseek-ai/cordis": "~4.1.0"
50
+ },
51
+ "engines": {
52
+ "node": ">=24",
53
+ "dsh": ">=0.2.2-rc.3"
54
+ },
55
+ "dsh": {
56
+ "bundle": {
57
+ "patch": "./cordis.patch.yml"
58
+ },
59
+ "client": {
60
+ "platform": "web"
61
+ }
62
+ },
63
+ "publishConfig": {
64
+ "access": "public"
65
+ }
66
+ }
@@ -0,0 +1,11 @@
1
+ import { accessSync, constants, statSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ // npm pack for distribution must include the executables built by package-dsh.yml.
5
+ for (const platform of ['darwin-arm64', 'darwin-x64', 'linux-arm64', 'linux-x64', 'win32-x64']) {
6
+ const windows = platform.startsWith('win32');
7
+ const file = fileURLToPath(new URL('../native/' + platform + '/agent-context' + (windows ? '.exe' : ''), import.meta.url));
8
+ const stat = statSync(file, { throwIfNoEntry: false });
9
+ if (!stat?.isFile() || stat.size === 0) throw new Error('Missing native executable: ' + file);
10
+ accessSync(file, windows ? constants.R_OK : constants.X_OK);
11
+ }