dsh-weknora-panel 0.0.0-stage → 0.1.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 chenge
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,61 @@
1
- # Temporary Holding Version
1
+ # dsh-weknora-panel
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
+ 在 DSH 侧边栏加一个网页入口,点开就是一个内嵌页面(iframe)。
4
+
5
+ 它是一个**通用反代**,跟 WeKnora 没有绑定关系 —— 默认指向 WeKnora 前端(`127.0.0.1:80`),你把 `target` 指到任何本机网页都行。名字里带 `weknora` 只是因为最早为它写的。
6
+
7
+ > 从 0.1.x 起默认值是 `80`(WeKnora 前端)。更早的版本默认值是 `18801`(MemOS Viewer,那个服务已经不用了),如果你是从旧版升上来的,检查一下配置里有没有硬写 `18801`。
8
+
9
+ ## 它解决两个问题
10
+
11
+ ### 1. 跨源被拦
12
+
13
+ 被嵌的前端往往带 `X-Frame-Options: SAMEORIGIN` 或 CSP,跨源直接嵌不进来。插件在本机起一个反代(默认 `127.0.0.1:8099`),转发时摘掉三个头:
14
+
15
+ - `X-Frame-Options`
16
+ - `Content-Security-Policy`
17
+ - `Content-Security-Policy-Report-Only`
18
+
19
+ 前端资源通常是根绝对路径(`/assets/…`)、API 同源(`/api/v1`),所以只能换端口、保留根路径,不能挂到子路径下。
20
+
21
+ ### 2. 登录态进不了 iframe
22
+
23
+ `SameSite=Lax` 的 cookie 在跨站 iframe 里会被浏览器丢掉,表现是"外部浏览器能进,侧边栏一直停在解锁页"。
24
+
25
+ 解法是把登录搬到服务端:反代启动时用配置里的密码向目标要一个 cookie,之后每个转发请求自己带上。浏览器端完全不需要 cookie,iframe 里直接就是已登录态。
26
+
27
+ ## 安装
28
+
29
+ ```bash
30
+ pnpm add dsh-weknora-panel
31
+ ```
32
+
33
+ 加进 profile 的 `dsh.profile.bundles`,重启 DSH。侧边栏那排小图标里会多一个地球。
34
+
35
+ ## 配置
36
+
37
+ 在 `cordis.patch.yml` 里:
38
+
39
+ ```yaml
40
+ - id: weknora-panel
41
+ config:
42
+ weknoraProxy:
43
+ port: 8099
44
+ target: http://127.0.0.1:80
45
+ login:
46
+ path: /api/v1/auth/login
47
+ password: "改成你自己的"
48
+ ```
49
+
50
+ - `port`:反代监听端口,默认 8099
51
+ - `target`:要嵌的地址,默认 `http://127.0.0.1:80`(WeKnora 前端)
52
+ - `login`:可不填。填了才做服务端登录注入;不填就是纯透明反代
53
+ - `login.password`:目标站点的登录密码。**明文存在配置文件里**,本机用没问题,多机部署要考虑换成环境变量
54
+
55
+ ## 安全
56
+
57
+ 反代只绑 `127.0.0.1`,没有鉴权,也不该往外转发。它等价于本机的网页访问权限——谁能访问 8099,谁就能访问目标站点,**并且是已登录状态**。所以不要把 `port` 改成对外监听。
58
+
59
+ ## 许可
60
+
61
+ MIT
@@ -0,0 +1,12 @@
1
+ # Bundle layer for dsh-weknora-panel.
2
+ # Mounts one host-plane row: a tiny reverse proxy on 127.0.0.1:8099 that forwards to the
3
+ # WeKnora web UI and strips X-Frame-Options / CSP so the sidebar can iframe it.
4
+ # The visible entry is a client-plane slot (lib/client.js), no config file needed.
5
+ - insert:
6
+ - id: weknora-panel
7
+ name: "dsh-weknora-panel"
8
+ config:
9
+ weknoraProxy:
10
+ target: "http://127.0.0.1:80"
11
+ login:
12
+ password: "123456"
package/lib/client.js ADDED
@@ -0,0 +1,382 @@
1
+ /**
2
+ * Sidebar entries for the memory system.
3
+ *
4
+ * Three tabs share one panel list: the WeKnora web UI (embedded through the local proxy),
5
+ * the daily ledger (read and edit by hand), and the remaining memory items (edit or forget).
6
+ *
7
+ * Loaded by the DSH web GUI through its module loader, so this file is a plain factory:
8
+ * no bundler, no JSX. React arrives through require().
9
+ *
10
+ * No hooks in the slot components: the shell renders a slot contribution as a plain
11
+ * function call, where a hook answers "Invalid hook call" (React error #321). State lives
12
+ * in class component lifecycles instead.
13
+ *
14
+ * The frame URL is the local reverse proxy (lib/proxy.js), not WeKnora itself: its nginx
15
+ * sends `X-Frame-Options: SAMEORIGIN`, and the GUI is on another port, so the browser would
16
+ * refuse to render it. 127.0.0.1 is deliberate -- the proxy only listens on loopback.
17
+ */
18
+ window.__ModuleLoader__.load({
19
+ id: "dsh-weknora-panel",
20
+ factory: (require) => {
21
+ var module = { exports: {} };
22
+ var exports = module.exports;
23
+
24
+ const React = require("react");
25
+ const el = React.createElement;
26
+
27
+ const FRAME_URL = "http://127.0.0.1:8099/";
28
+ const JOURNAL_API = "/api/weknora-panel/journal";
29
+ const MEMORY_API = "/api/weknora-panel/memory";
30
+
31
+ const CSS =
32
+ "[data-wk-panel]{display:flex;flex-direction:column;width:100%;height:100%;min-width:0;min-height:0;box-sizing:border-box;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary)}" +
33
+ "[data-wk-panel] .wkp-bar{display:flex;align-items:center;gap:8px;padding:8px 12px;flex:none;border-bottom:1px solid var(--dsw-alias-border-l1);font-size:12px;line-height:18px}" +
34
+ "[data-wk-panel] .wkp-title{font-size:13px;font-weight:600}" +
35
+ "[data-wk-panel] .wkp-note{color:var(--dsw-alias-label-tertiary);font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}" +
36
+ "[data-wk-panel] .wkp-tools{display:flex;align-items:center;gap:6px;margin-left:auto;flex:none}" +
37
+ "[data-wk-panel] .wkp-btn{height:24px;padding:0 10px;border:1px solid var(--dsw-alias-border-l2);border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;cursor:pointer}" +
38
+ "[data-wk-panel] .wkp-btn:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}" +
39
+ "[data-wk-panel] .wkp-btn[data-danger]{border-color:var(--dsw-alias-border-danger,#c0392b);color:var(--dsw-alias-label-danger,#c0392b)}" +
40
+ "[data-wk-panel] .wkp-frame{flex:1 1 auto;display:block;width:100%;min-height:0;border:0;background:#fff}" +
41
+ "[data-wk-panel] .wkp-split{flex:1 1 auto;display:flex;min-height:0}" +
42
+ "[data-wk-panel] .wkp-list{width:236px;flex:none;overflow:auto;border-right:1px solid var(--dsw-alias-border-l1)}" +
43
+ "[data-wk-panel] .wkp-item{padding:8px 10px;border-bottom:1px solid var(--dsw-alias-border-l1);cursor:pointer;font-size:12px;line-height:17px}" +
44
+ "[data-wk-panel] .wkp-item:hover{background:var(--dsw-alias-interactive-bg-hover)}" +
45
+ "[data-wk-panel] .wkp-item[data-active]{background:var(--dsw-alias-interactive-bg-selected,rgba(64,132,255,.12))}" +
46
+ "[data-wk-panel] .wkp-itemName{font-weight:600}" +
47
+ "[data-wk-panel] .wkp-itemMeta{color:var(--dsw-alias-label-tertiary);font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}" +
48
+ "[data-wk-panel] .wkp-body{flex:1 1 auto;display:flex;flex-direction:column;min-width:0;min-height:0}" +
49
+ "[data-wk-panel] .wkp-editor{flex:1 1 auto;width:100%;min-height:0;box-sizing:border-box;border:0;padding:10px 12px;background:transparent;color:inherit;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;line-height:19px;resize:none;outline:none}" +
50
+ "[data-wk-panel] .wkp-hint{padding:6px 12px;color:var(--dsw-alias-label-tertiary);font-size:11px;border-top:1px solid var(--dsw-alias-border-l1)}" +
51
+ "[data-wk-panel] .wkp-card{padding:10px 12px;border-bottom:1px solid var(--dsw-alias-border-l1);font-size:12px;line-height:18px}" +
52
+ "[data-wk-panel] .wkp-cardHead{display:flex;align-items:center;gap:8px;margin-bottom:4px}" +
53
+ "[data-wk-panel] .wkp-tag{font-size:10px;padding:1px 6px;border-radius:999px;border:1px solid var(--dsw-alias-border-l2);color:var(--dsw-alias-label-tertiary)}" +
54
+ "[data-wk-panel] .wkp-empty{padding:24px 12px;color:var(--dsw-alias-label-tertiary);font-size:12px;text-align:center}";
55
+
56
+ function ensureStyles() {
57
+ const id = "dsh-weknora-panel-style";
58
+ if (typeof document === "undefined" || document.getElementById(id)) return;
59
+ const style = document.createElement("style");
60
+ style.id = id;
61
+ style.textContent = CSS;
62
+ document.head.appendChild(style);
63
+ }
64
+
65
+ async function postJson(url, body) {
66
+ const response = await fetch(url, {
67
+ method: "POST",
68
+ headers: { "Content-Type": "application/json" },
69
+ body: JSON.stringify(body),
70
+ });
71
+ return await response.json().catch(() => ({ ok: false, error: "bad_response" }));
72
+ }
73
+
74
+ // ---------------------------------------------------------------- WeKnora frame
75
+
76
+ class WeKnoraPage extends React.Component {
77
+ constructor(props) {
78
+ super(props);
79
+ this.state = { nonce: 0 };
80
+ this.reload = this.reload.bind(this);
81
+ this.openWindow = this.openWindow.bind(this);
82
+ }
83
+
84
+ reload() {
85
+ this.setState({ nonce: this.state.nonce + 1 });
86
+ }
87
+
88
+ openWindow() {
89
+ try {
90
+ window.open(FRAME_URL, "_blank", "noopener");
91
+ } catch {}
92
+ }
93
+
94
+ render() {
95
+ return el(
96
+ "div",
97
+ { "data-wk-panel": "" },
98
+ el(
99
+ "div",
100
+ { className: "wkp-bar" },
101
+ el("span", { className: "wkp-title" }, "记忆"),
102
+ el("span", { className: "wkp-note" }, "MemOS 本地 127.0.0.1:18801 · 世界模型 / 轨迹 / 策略都在这里"),
103
+ el(
104
+ "span",
105
+ { className: "wkp-tools" },
106
+ el("button", { className: "wkp-btn", onClick: this.reload }, "刷新"),
107
+ el("button", { className: "wkp-btn", onClick: this.openWindow }, "新窗口"),
108
+ ),
109
+ ),
110
+ el("iframe", { key: this.state.nonce, className: "wkp-frame", src: FRAME_URL, title: "WeKnora" }),
111
+ );
112
+ }
113
+ }
114
+
115
+ // ---------------------------------------------------------------- ledger
116
+
117
+ class JournalPage extends React.Component {
118
+ constructor(props) {
119
+ super(props);
120
+ this.state = { items: [], current: "", content: "", draft: "", busy: false, notice: "" };
121
+ this.load = this.load.bind(this);
122
+ this.open = this.open.bind(this);
123
+ this.save = this.save.bind(this);
124
+ this.remove = this.remove.bind(this);
125
+ this.onChange = this.onChange.bind(this);
126
+ }
127
+
128
+ componentDidMount() {
129
+ this.load();
130
+ }
131
+
132
+ async load() {
133
+ this.setState({ busy: true, notice: "" });
134
+ const data = await fetch(JOURNAL_API).then((r) => r.json()).catch(() => ({ items: [] }));
135
+ this.setState({ busy: false, items: Array.isArray(data.items) ? data.items : [] });
136
+ if (this.state.current === "" && Array.isArray(data.items) && data.items.length > 0) this.open(data.items[0].name);
137
+ }
138
+
139
+ async open(name) {
140
+ this.setState({ current: name, busy: true, notice: "" });
141
+ const data = await postJson(JOURNAL_API, { op: "read", name });
142
+ if (data.ok) this.setState({ busy: false, content: data.content, draft: data.content });
143
+ else this.setState({ busy: false, content: "", draft: "", notice: "读不到:" + String(data.error ?? "") });
144
+ }
145
+
146
+ onChange(event) {
147
+ this.setState({ draft: event.target.value });
148
+ }
149
+
150
+ async save() {
151
+ if (this.state.current === "") return;
152
+ this.setState({ busy: true });
153
+ const data = await postJson(JOURNAL_API, { op: "save", name: this.state.current, content: this.state.draft });
154
+ this.setState({ busy: false, content: data.ok ? this.state.draft : this.state.content, notice: data.ok ? "已保存" : "保存失败:" + String(data.error ?? "") });
155
+ this.load();
156
+ }
157
+
158
+ async remove() {
159
+ if (this.state.current === "") return;
160
+ this.setState({ busy: true });
161
+ const data = await postJson(JOURNAL_API, { op: "delete", name: this.state.current });
162
+ this.setState({
163
+ busy: false,
164
+ items: Array.isArray(data.items) ? data.items : this.state.items,
165
+ current: "",
166
+ content: "",
167
+ draft: "",
168
+ notice: data.ok ? "已删除这一本" : "删除失败:" + String(data.error ?? ""),
169
+ });
170
+ }
171
+
172
+ renderList() {
173
+ if (this.state.items.length === 0) return el("div", { className: "wkp-empty" }, "还没有账本。你说的话会在每轮结束时落到这里。");
174
+ return this.state.items.map((item) =>
175
+ el(
176
+ "div",
177
+ {
178
+ key: item.name,
179
+ className: "wkp-item",
180
+ "data-active": item.name === this.state.current ? "" : undefined,
181
+ onClick: () => this.open(item.name),
182
+ },
183
+ el("div", { className: "wkp-itemName" }, item.name.replace(/\.md$/u, "")),
184
+ el("div", { className: "wkp-itemMeta" }, Math.round(item.bytes / 1024) + " KB · " + item.lines + " 句"),
185
+ el("div", { className: "wkp-itemMeta" }, item.preview || "(空)"),
186
+ ),
187
+ );
188
+ }
189
+
190
+ render() {
191
+ const dirty = this.state.draft !== this.state.content;
192
+ return el(
193
+ "div",
194
+ { "data-wk-panel": "" },
195
+ el(
196
+ "div",
197
+ { className: "wkp-bar" },
198
+ el("span", { className: "wkp-title" }, "账本"),
199
+ el("span", { className: "wkp-note" }, "你说的话 + 我的回复,逐字记,没经过模型改"),
200
+ el(
201
+ "span",
202
+ { className: "wkp-tools" },
203
+ dirty ? el("button", { className: "wkp-btn", onClick: this.save }, "保存") : null,
204
+ el("button", { className: "wkp-btn", onClick: this.remove, "data-danger": "" }, "删这本"),
205
+ el("button", { className: "wkp-btn", onClick: this.load }, "刷新"),
206
+ ),
207
+ ),
208
+ el(
209
+ "div",
210
+ { className: "wkp-split" },
211
+ el("div", { className: "wkp-list" }, this.renderList()),
212
+ el(
213
+ "div",
214
+ { className: "wkp-body" },
215
+ this.state.current === ""
216
+ ? el("div", { className: "wkp-empty" }, "左边选一本看")
217
+ : el("textarea", { className: "wkp-editor", value: this.state.draft, onChange: this.onChange, spellCheck: false }),
218
+ el("div", { className: "wkp-hint" }, this.state.notice || (dirty ? "改过还没保存" : "改动会直接影响明天入库的原话")),
219
+ ),
220
+ ),
221
+ );
222
+ }
223
+ }
224
+
225
+ // ---------------------------------------------------------------- memory items
226
+
227
+ class MemoryPage extends React.Component {
228
+ constructor(props) {
229
+ super(props);
230
+ this.state = { items: [], error: "", editing: "", draft: "", busy: false, notice: "" };
231
+ this.load = this.load.bind(this);
232
+ this.startEdit = this.startEdit.bind(this);
233
+ this.save = this.save.bind(this);
234
+ this.forget = this.forget.bind(this);
235
+ this.onChange = this.onChange.bind(this);
236
+ }
237
+
238
+ componentDidMount() {
239
+ this.load();
240
+ }
241
+
242
+ async load() {
243
+ this.setState({ busy: true });
244
+ const data = await fetch(MEMORY_API).then((r) => r.json()).catch(() => ({ items: [], error: "fetch" }));
245
+ this.setState({
246
+ busy: false,
247
+ items: Array.isArray(data.items) ? data.items : [],
248
+ error: data.ok === false ? String(data.error ?? "") : "",
249
+ });
250
+ }
251
+
252
+ startEdit(id, content) {
253
+ this.setState({ editing: id, draft: content, notice: "" });
254
+ }
255
+
256
+ onChange(event) {
257
+ this.setState({ draft: event.target.value });
258
+ }
259
+
260
+ async save(id) {
261
+ this.setState({ busy: true });
262
+ const data = await postJson(MEMORY_API, { op: "update", id, content: this.state.draft });
263
+ this.setState({ busy: false, editing: data.ok ? "" : this.state.editing, notice: data.ok ? "已保存" : "失败:" + String(data.error ?? "") });
264
+ if (data.ok) this.load();
265
+ }
266
+
267
+ async forget(id) {
268
+ this.setState({ busy: true });
269
+ const data = await postJson(MEMORY_API, { op: "forget", id });
270
+ this.setState({ busy: false, notice: data.ok ? "已失效(保留历史,不删行)" : "失败:" + String(data.error ?? "") });
271
+ if (data.ok) this.load();
272
+ }
273
+
274
+ render() {
275
+ const { items, editing, draft, error, notice } = this.state;
276
+ return el(
277
+ "div",
278
+ { "data-wk-panel": "" },
279
+ el(
280
+ "div",
281
+ { className: "wkp-bar" },
282
+ el("span", { className: "wkp-title" }, "记忆条目"),
283
+ el("span", { className: "wkp-note" }, items.length + " 条在生效 · 剩下的结论都已经并进百科页"),
284
+ el(
285
+ "span",
286
+ { className: "wkp-tools" },
287
+ el("button", { className: "wkp-btn", onClick: this.load }, "刷新"),
288
+ ),
289
+ ),
290
+ el("div", { className: "wkp-hint" }, notice || error || "点正文可以直接改;删是标记失效,历史留着"),
291
+ el(
292
+ "div",
293
+ { className: "wkp-body", style: { overflow: "auto" } },
294
+ items.length === 0
295
+ ? el("div", { className: "wkp-empty" }, error ? "读不到记忆条目(" + error + ")" : "没有在生效的记忆条目")
296
+ : items.map((item) =>
297
+ el(
298
+ "div",
299
+ { key: item.id, className: "wkp-card" },
300
+ el(
301
+ "div",
302
+ { className: "wkp-cardHead" },
303
+ el("span", { className: "wkp-tag" }, item.kind || "fact"),
304
+ el("span", { className: "wkp-tag" }, "重要度 " + item.importance),
305
+ item.origin ? el("span", { className: "wkp-tag" }, item.origin) : null,
306
+ el(
307
+ "span",
308
+ { className: "wkp-tools" },
309
+ editing === item.id
310
+ ? el("button", { className: "wkp-btn", onClick: () => this.save(item.id) }, "保存")
311
+ : el("button", { className: "wkp-btn", onClick: () => this.startEdit(item.id, item.content) }, "改"),
312
+ editing === item.id
313
+ ? el("button", { className: "wkp-btn", onClick: () => this.setState({ editing: "" }) }, "取消")
314
+ : el("button", { className: "wkp-btn", onClick: () => this.forget(item.id), "data-danger": "" }, "失效"),
315
+ ),
316
+ ),
317
+ editing === item.id
318
+ ? el("textarea", { className: "wkp-editor", style: { minHeight: "120px" }, value: draft, onChange: this.onChange })
319
+ : el("div", null, item.content),
320
+ ),
321
+ ),
322
+ ),
323
+ );
324
+ }
325
+ }
326
+
327
+ // ---------------------------------------------------------------- slots
328
+
329
+ function withStyles(Component) {
330
+ return function Wrapped() {
331
+ ensureStyles();
332
+ return el(Component, null);
333
+ };
334
+ }
335
+
336
+ const WeKnoraTab = withStyles(WeKnoraPage);
337
+ const JournalTab = withStyles(JournalPage);
338
+ const MemoryTab = withStyles(MemoryPage);
339
+
340
+ function icon(paths) {
341
+ return function Row() {
342
+ return el(
343
+ "span",
344
+ { style: { display: "inline-flex", alignItems: "center", justifyContent: "center", width: 18, height: 18 } },
345
+ el(
346
+ "svg",
347
+ { width: 18, height: 18, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round" },
348
+ ...paths.map((d, index) => el("path", { key: index, d })),
349
+ ),
350
+ );
351
+ };
352
+ }
353
+
354
+ const GlobeRow = icon(["M4 12h16", "M12 4c2.6 2.5 2.6 13.5 0 16M12 4c-2.6 2.5-2.6 13.5 0 16", "M12 12m-8 0a8 8 0 1 0 16 0a8 8 0 1 0-16 0"]);
355
+ const BookRow = icon(["M6 3h9l4 4v14H6z", "M15 3v4h4", "M9 12h7", "M9 16h7"]);
356
+ const TagRow = icon(["M4 5h9l7 7-7 7H4z", "M8 12h.01"]);
357
+
358
+ const inject = ["slots"];
359
+
360
+ function apply(ctx) {
361
+ const mount = (id, label, order, row, page) => {
362
+ ctx.slots.inject("sidebar.panellist", () =>
363
+ ctx.slots.register({ name: "sidebar.panellist", id, order, label: () => label }, row),
364
+ );
365
+ ctx.slots.inject("main", () => ctx.slots.register({ name: "main", key: id, inject: () => ({}) }, page));
366
+ };
367
+ try {
368
+ // 只用 WeKnora 一个入口。「账本」「记忆条目」两个页面按用户要求从界面上撤掉
369
+ // (0.9.2):底层路由还在 /api/weknora-panel/*,想找回来把下面两行的 mounted 语义恢复即可。
370
+ mount("weknora-panel", "记忆", 70, GlobeRow, WeKnoraTab);
371
+ void JournalTab;
372
+ void MemoryTab;
373
+ } catch (error) {
374
+ // A shell that does not declare these seats simply has no panel here.
375
+ }
376
+ }
377
+
378
+ exports.apply = apply;
379
+ exports.inject = inject;
380
+ return module.exports;
381
+ },
382
+ });
package/lib/index.js ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * DSH host-plane plugin: the reverse proxy that makes the WeKnora web UI embeddable,
3
+ * plus two small JSON routes so the sidebar can show and edit the ledger and the memory items.
4
+ *
5
+ * Why this exists as its own package: the memory injector that used to own this proxy
6
+ * is being retired (m04555), but the sidebar entry that shows WeKnora is a keep. Splitting
7
+ * it out means the panel survives even after every line of the injector is gone.
8
+ *
9
+ * The proxy does exactly one thing: forward 127.0.0.1:8099 → WeKnora's web entry, minus the
10
+ * two headers that would make a browser refuse to render it in a frame. The routes live in
11
+ * lib/routes.js; the visible tabs live in lib/client.js on the client plane.
12
+ */
13
+ import { PROXY_DEFAULTS, startWeKnoraProxy } from "./proxy.js";
14
+ import { panelRoutes } from "./routes.js";
15
+
16
+ export const name = "dsh-weknora-panel";
17
+
18
+ export function apply(ctx, config = {}) {
19
+ const log =
20
+ typeof ctx?.logger === "function"
21
+ ? (line) => {
22
+ try {
23
+ ctx.logger("weknora-panel").info?.(line);
24
+ } catch {}
25
+ }
26
+ : null;
27
+
28
+ const settings = {
29
+ weknoraProxy: {
30
+ ...PROXY_DEFAULTS,
31
+ ...(config?.weknoraProxy ?? {}),
32
+ },
33
+ };
34
+
35
+ const proxy = startWeKnoraProxy(settings, log);
36
+ if (proxy?.error) log?.("weknora panel proxy failed: " + String(proxy.error?.message ?? proxy.error));
37
+ else if (proxy?.port) log?.(`weknora panel proxy listening on ${proxy.host ?? settings.weknoraProxy.host}:${proxy.port}`);
38
+
39
+ // The two edit endpoints mount on the GUI's own /api transport. A headless host (no GUI
40
+ // bundle) simply has no `connection.fetch`, and the tabs stay read-only-but-absent.
41
+ const disposers = [];
42
+ const mount = (scope) => {
43
+ try {
44
+ for (const route of panelRoutes({})) disposers.push(scope.connection.fetch.register(route));
45
+ log?.("panel routes mounted (" + disposers.length + ")");
46
+ } catch (error) {
47
+ log?.("panel routes failed: " + String(error?.message ?? error));
48
+ }
49
+ };
50
+ try {
51
+ if (typeof ctx.inject === "function") ctx.inject(["connection"], mount);
52
+ else if (ctx.connection?.fetch?.register) mount(ctx);
53
+ } catch (error) {
54
+ log?.("panel routes skipped: " + String(error?.message ?? error));
55
+ }
56
+
57
+ ctx.on?.("disposed", () => {
58
+ for (const dispose of disposers) {
59
+ try {
60
+ dispose?.();
61
+ } catch {}
62
+ }
63
+ try {
64
+ proxy?.close?.();
65
+ } catch {}
66
+ });
67
+ }
package/lib/proxy.js ADDED
@@ -0,0 +1,181 @@
1
+ /**
2
+ * WeKnora 前端页面的反代:让侧边栏能用 iframe 直接打开它。
3
+ *
4
+ * 为什么必须反代,而不是直接 iframe `http://localhost:80`:
5
+ * - WeKnora 的 Nginx 发 `X-Frame-Options: SAMEORIGIN`,而 GUI 在另一个端口(例如
6
+ * 127.0.0.1:62174),浏览器会直接拒绝渲染,页面一片空白且没有报错线索。
7
+ * - 它的前端资源全用根绝对路径(`/assets/…`)并同源调 `/api/v1`,所以不能在路径上
8
+ * 挂前缀,只能换端口、保住根路径。
9
+ *
10
+ * 于是:本机再起一个端口(默认 8099),把请求原样转给 WeKnora,只做两件事——删掉
11
+ * `x-frame-options`,并把 CSP 里的 `frame-ancestors` 去掉。除此之外一个字都不改,
12
+ * 免得哪天 WeKnora 换了接口,我们这边还要跟着改一遍。
13
+ *
14
+ * 只 listen 在 127.0.0.1:这是给本机 GUI 用的,不该被局域网看到。
15
+ *
16
+ * @module weknora-proxy
17
+ */
18
+ import http from "node:http";
19
+
20
+ export const PROXY_DEFAULTS = {
21
+ enabled: true,
22
+ port: 8099,
23
+ host: "127.0.0.1",
24
+ /** 目标:默认指向 MemOS 的 Memory Viewer(登录过的 WeKnora 前端也可以)。 */
25
+ target: "http://127.0.0.1:80",
26
+ /**
27
+ * 上游要登录时,由反代替浏览器持有会话。
28
+ *
29
+ * 为什么必须这样做:MemOS 的 Memory Viewer 登录后发的 cookie 是 `SameSite=Lax`,
30
+ * 而侧边栏是 iframe —— 顶层是 GUI 的端口、iframe 是 8099,浏览器把这次写 cookie
31
+ * 当成跨站请求直接丢掉,于是页面永远停在“解锁”按钮上转圈。把登录搬到服务端,
32
+ * iframe 里就不再需要任何 cookie。密码留空则退化成透明反代(不许密码的上游)。
33
+ */
34
+ login: { path: "/api/v1/auth/login", password: "123456" },
35
+ };
36
+
37
+ /** 这些响应头会让 iframe 被浏览器拒绝,转发时直接丢掉。 */
38
+ const STRIP_HEADERS = new Set(["x-frame-options", "content-security-policy", "content-security-policy-report-only"]);
39
+
40
+ function targetOf(config) {
41
+ const raw = config?.weknoraProxy ?? {};
42
+ const target = typeof raw.target === "string" && raw.target ? raw.target : PROXY_DEFAULTS.target;
43
+ try {
44
+ const url = new URL(target);
45
+ return { host: url.hostname, port: Number(url.port) || 80, protocol: url.protocol };
46
+ } catch {
47
+ const fallback = new URL(PROXY_DEFAULTS.target);
48
+ return { host: fallback.hostname, port: 80, protocol: fallback.protocol };
49
+ }
50
+ }
51
+
52
+ /** 拿一次上游的登录会话,只取 Cookie 头第一段(其余属性交给浏览器也没用)。 */
53
+ function loginUpstream(upstreamHost, upstreamPort, login) {
54
+ return new Promise((resolve) => {
55
+ const password = typeof login?.password === "string" ? login.password : "";
56
+ if (!password) return resolve("");
57
+ const path = typeof login?.path === "string" && login.path ? login.path : PROXY_DEFAULTS.login.path;
58
+ const body = JSON.stringify({ password });
59
+ const req = http.request(
60
+ {
61
+ host: upstreamHost,
62
+ port: upstreamPort,
63
+ method: "POST",
64
+ path,
65
+ headers: { "content-type": "application/json", "content-length": Buffer.byteLength(body) },
66
+ },
67
+ (res) => {
68
+ const raw = res.headers["set-cookie"] ?? [];
69
+ const cookie = raw
70
+ .map((line) => String(line).split(";")[0])
71
+ .filter(Boolean)
72
+ .join("; ");
73
+ res.resume();
74
+ resolve(res.statusCode && res.statusCode < 400 ? cookie : "");
75
+ },
76
+ );
77
+ req.on("error", () => resolve(""));
78
+ req.end(body);
79
+ });
80
+ }
81
+
82
+ /** 把上游响应头过一遍:去掉框架限制,其余原样。 */
83
+ export function filterHeaders(rawHeaders) {
84
+ const out = {};
85
+ for (const [key, value] of Object.entries(rawHeaders ?? {})) {
86
+ if (STRIP_HEADERS.has(String(key).toLowerCase())) continue;
87
+ out[key] = value;
88
+ }
89
+ return out;
90
+ }
91
+
92
+ /**
93
+ * 起一个反代。返回 `{ port, close }`;端口被占时返回 `{ port, close, error }`,
94
+ * 不抛错——侧边栏少一个 tab 可以接受,记忆注入不能因为反代起不来而挂掉。
95
+ */
96
+ export function startWeKnoraProxy(config, log) {
97
+ const raw = config?.weknoraProxy ?? {};
98
+ const enabled = raw.enabled === undefined ? PROXY_DEFAULTS.enabled : Boolean(raw.enabled);
99
+ if (!enabled) return { port: 0, close() {}, skipped: true };
100
+ const port = Number(raw.port) || PROXY_DEFAULTS.port;
101
+ const host = typeof raw.host === "string" && raw.host ? raw.host : PROXY_DEFAULTS.host;
102
+ const { host: upstreamHost, port: upstreamPort } = targetOf(config);
103
+
104
+ const login = raw.login ?? PROXY_DEFAULTS.login;
105
+ let cookie = "";
106
+ let pendingLogin = null;
107
+ /** 没有会话就去换一个;换不到就按未登录转发,让上游自己回 401。 */
108
+ const ensureCookie = () => {
109
+ if (cookie || !login?.password) return Promise.resolve(cookie);
110
+ if (!pendingLogin) {
111
+ pendingLogin = loginUpstream(upstreamHost, upstreamPort, login).then((value) => {
112
+ cookie = value;
113
+ pendingLogin = null;
114
+ if (!value) log?.("weknora proxy: 上游登录没换到 cookie,按未登录转发");
115
+ return value;
116
+ });
117
+ }
118
+ return pendingLogin;
119
+ };
120
+ void ensureCookie();
121
+
122
+ const server = http.createServer((req, res) => {
123
+ const forward = () => {
124
+ const headers = {
125
+ ...req.headers,
126
+ host: upstreamHost + (upstreamPort === 80 ? "" : ":" + upstreamPort),
127
+ };
128
+ if (cookie) headers.cookie = cookie;
129
+ const upstream = http.request(
130
+ {
131
+ host: upstreamHost,
132
+ port: upstreamPort,
133
+ method: req.method,
134
+ path: req.url,
135
+ headers,
136
+ },
137
+ (upRes) => {
138
+ // 会话过期:丢掉缓存的那份,下一个请求会重新登录。不重放请求——body 可能已被上游读过一半。
139
+ if (upRes.statusCode === 401 && login?.password) cookie = "";
140
+ res.writeHead(upRes.statusCode ?? 502, filterHeaders(upRes.headers));
141
+ upRes.pipe(res);
142
+ },
143
+ );
144
+ upstream.on("error", (error) => {
145
+ log?.("weknora proxy: " + String(error?.message ?? error));
146
+ if (!res.headersSent) {
147
+ res.writeHead(502, { "content-type": "text/plain; charset=utf-8" });
148
+ }
149
+ res.end("反代连不上上游(" + String(error?.message ?? error) + ")");
150
+ });
151
+ req.pipe(upstream);
152
+ };
153
+ if (cookie || !login?.password) return forward();
154
+ ensureCookie().then(forward);
155
+ });
156
+
157
+ let failure = null;
158
+ server.on("error", (error) => {
159
+ failure = error;
160
+ log?.("weknora proxy listen failed on " + host + ":" + port + " -- " + String(error?.message ?? error));
161
+ });
162
+ try {
163
+ server.listen(port, host);
164
+ // 别让一个 side-channel 的监听句柄拖住整个进程:DSH 退出、测试跑完,都该说走就走。
165
+ server.unref?.();
166
+ } catch (error) {
167
+ failure = error;
168
+ }
169
+ return {
170
+ port,
171
+ host,
172
+ get error() {
173
+ return failure;
174
+ },
175
+ close() {
176
+ try {
177
+ server.close();
178
+ } catch {}
179
+ },
180
+ };
181
+ }
package/lib/routes.js ADDED
@@ -0,0 +1,226 @@
1
+ /**
2
+ * Panel routes: two small JSON endpoints that let the sidebar show and edit the two things
3
+ * a person actually wants to fix by hand — today's transcript and the remaining memory
4
+ * items. Everything else in the panel is the WeKnora UI itself, embedded through the proxy.
5
+ *
6
+ * Why routes instead of a second listener: they mount on the GUI's own /api transport, so the
7
+ * browser talks to the page's own origin. No CORS, no extra port, no token to pass around.
8
+ *
9
+ * Safety rails, because these handlers can write files:
10
+ * · transcript names must match the ledger pattern and resolve inside the transcripts dir;
11
+ * · the memory endpoint is proxied to the endpoint already saved in memory-providers.json,
12
+ * never to a URL the browser sends.
13
+ */
14
+ import { existsSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
15
+ import { homedir } from "node:os";
16
+ import { join, resolve, sep } from "node:path";
17
+
18
+ export const PANEL_API_PREFIX = "/api/weknora-panel";
19
+ export const JOURNAL_ROUTE = PANEL_API_PREFIX + "/journal";
20
+ export const MEMORY_ROUTE = PANEL_API_PREFIX + "/memory";
21
+
22
+ const NAME_PATTERN = /^\d{4}-\d{2}-\d{2}(-[0-9a-zA-Z]{1,16})?\.md$/u;
23
+ const MAX_READ_BYTES = 400 * 1024;
24
+
25
+ function json(status, body) {
26
+ return new Response(JSON.stringify(body), {
27
+ status,
28
+ headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" },
29
+ });
30
+ }
31
+
32
+ export function transcriptDirOf() {
33
+ return join(homedir(), ".mnemon", "transcripts");
34
+ }
35
+
36
+ export function providersPathOf() {
37
+ return join(homedir(), ".mnemon", "state", "memory-providers.json");
38
+ }
39
+
40
+ /** 只认账本目录下的正规文件名,别的一律拒掉 */
41
+ function safePath(dir, name) {
42
+ if (typeof name !== "string" || NAME_PATTERN.test(name) === false) return undefined;
43
+ const full = resolve(dir, name);
44
+ if (full.startsWith(resolve(dir) + sep) === false) return undefined;
45
+ return full;
46
+ }
47
+
48
+ function firstLineOf(text) {
49
+ for (const raw of text.split("\n")) {
50
+ const line = raw.trim();
51
+ if (line === "" || line.startsWith("#")) continue;
52
+ return line.replace(/^\*\*(你|我)\*\*[::]?\s*/u, "").slice(0, 60);
53
+ }
54
+ return "";
55
+ }
56
+
57
+ function listTranscripts(dir) {
58
+ if (!existsSync(dir)) return [];
59
+ return readdirSync(dir)
60
+ .filter((name) => NAME_PATTERN.test(name))
61
+ .map((name) => {
62
+ const full = join(dir, name);
63
+ const stat = statSync(full);
64
+ const head = readFileSync(full, "utf8").slice(0, 4000);
65
+ return {
66
+ name,
67
+ bytes: stat.size,
68
+ modifiedAt: stat.mtime.toISOString(),
69
+ lines: head.split("\n").filter((line) => line.startsWith("**")).length,
70
+ preview: firstLineOf(head),
71
+ };
72
+ })
73
+ .sort((left, right) => right.name.localeCompare(left.name));
74
+ }
75
+
76
+ function memoryService() {
77
+ try {
78
+ const state = JSON.parse(readFileSync(providersPathOf(), "utf8"));
79
+ const service = state?.services?.weknora;
80
+ if (typeof service?.endpoint !== "string" || typeof service?.apiKey !== "string") return undefined;
81
+ if (service.endpoint === "" || service.apiKey === "") return undefined;
82
+ return { endpoint: service.endpoint.replace(/\/+$/u, ""), apiKey: service.apiKey };
83
+ } catch {
84
+ return undefined;
85
+ }
86
+ }
87
+
88
+ async function callWeKnora(service, method, path, body) {
89
+ const response = await fetch(service.endpoint + path, {
90
+ method,
91
+ headers: { "X-API-Key": service.apiKey, ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
92
+ body: body === undefined ? undefined : JSON.stringify(body),
93
+ signal: AbortSignal.timeout(15000),
94
+ }).catch(() => undefined);
95
+ if (response === undefined) return { ok: false, status: 0, error: "transport" };
96
+ const text = await response.text().catch(() => "");
97
+ let payload;
98
+ try {
99
+ payload = text === "" ? undefined : JSON.parse(text);
100
+ } catch {
101
+ payload = undefined;
102
+ }
103
+ if (!response.ok) {
104
+ const message = payload?.error?.message ?? payload?.error ?? payload?.message ?? ("HTTP " + response.status);
105
+ return { ok: false, status: response.status, error: String(message).slice(0, 160) };
106
+ }
107
+ return { ok: true, payload };
108
+ }
109
+
110
+ export function journalRoutes(options = {}) {
111
+ const dir = options.transcriptDir ?? transcriptDirOf();
112
+
113
+ return [
114
+ {
115
+ path: JOURNAL_ROUTE,
116
+ methods: ["GET"],
117
+ requestBody: "buffered",
118
+ fetch: () => Promise.resolve(json(200, { ok: true, dir, items: listTranscripts(dir) })),
119
+ },
120
+ {
121
+ path: JOURNAL_ROUTE,
122
+ methods: ["POST"],
123
+ requestBody: "buffered",
124
+ fetch: async (request) => {
125
+ let body;
126
+ try {
127
+ body = await request.json();
128
+ } catch {
129
+ return json(400, { ok: false, error: "bad_json" });
130
+ }
131
+ const op = String(body?.op ?? "");
132
+ const full = safePath(dir, body?.name);
133
+ if (full === undefined) return json(400, { ok: false, error: "bad_name" });
134
+
135
+ if (op === "read") {
136
+ if (!existsSync(full)) return json(404, { ok: false, error: "not_found" });
137
+ const stat = statSync(full);
138
+ if (stat.size > MAX_READ_BYTES) return json(413, { ok: false, error: "too_large" });
139
+ return json(200, { ok: true, name: body.name, content: readFileSync(full, "utf8") });
140
+ }
141
+
142
+ if (op === "save") {
143
+ const content = typeof body?.content === "string" ? body.content : undefined;
144
+ if (content === undefined) return json(400, { ok: false, error: "bad_content" });
145
+ if (Buffer.byteLength(content) > MAX_READ_BYTES) return json(413, { ok: false, error: "too_large" });
146
+ writeFileSync(full, content, "utf8");
147
+ return json(200, { ok: true, name: body.name, bytes: Buffer.byteLength(content) });
148
+ }
149
+
150
+ if (op === "delete") {
151
+ if (!existsSync(full)) return json(404, { ok: false, error: "not_found" });
152
+ unlinkSync(full);
153
+ return json(200, { ok: true, name: body.name, items: listTranscripts(dir) });
154
+ }
155
+
156
+ return json(400, { ok: false, error: "bad_op" });
157
+ },
158
+ },
159
+ ];
160
+ }
161
+
162
+ export function memoryRoutes() {
163
+ return [
164
+ {
165
+ path: MEMORY_ROUTE,
166
+ methods: ["GET"],
167
+ requestBody: "buffered",
168
+ fetch: async () => {
169
+ const service = memoryService();
170
+ if (service === undefined) return json(200, { ok: false, error: "no_provider", items: [] });
171
+ const list = await callWeKnora(service, "GET", "/api/v1/memory/items?limit=200");
172
+ if (list.ok === false) return json(200, { ok: false, error: list.error, items: [] });
173
+ const rows = Array.isArray(list.payload?.data) ? list.payload.data : [];
174
+ const items = rows
175
+ .filter((row) => row?.status === "active")
176
+ .map((row) => ({
177
+ id: String(row.id ?? ""),
178
+ kind: String(row.kind ?? ""),
179
+ content: String(row.content ?? ""),
180
+ importance: Number(row.importance) || 0,
181
+ origin: String(row.origin ?? ""),
182
+ updatedAt: String(row.updated_at ?? ""),
183
+ }));
184
+ return json(200, { ok: true, items, total: rows.length });
185
+ },
186
+ },
187
+ {
188
+ path: MEMORY_ROUTE,
189
+ methods: ["POST"],
190
+ requestBody: "buffered",
191
+ fetch: async (request) => {
192
+ let body;
193
+ try {
194
+ body = await request.json();
195
+ } catch {
196
+ return json(400, { ok: false, error: "bad_json" });
197
+ }
198
+ const service = memoryService();
199
+ if (service === undefined) return json(200, { ok: false, error: "no_provider" });
200
+ const op = String(body?.op ?? "");
201
+ const id = String(body?.id ?? "");
202
+ if (/^[0-9a-f-]{8,40}$/u.test(id) === false) return json(400, { ok: false, error: "bad_id" });
203
+
204
+ if (op === "update") {
205
+ const patch = {};
206
+ if (typeof body?.content === "string") patch.content = body.content;
207
+ if (body?.importance !== undefined) patch.importance = Math.min(Math.max(Number(body.importance) || 3, 1), 5);
208
+ if (Object.keys(patch).length === 0) return json(400, { ok: false, error: "nothing_to_update" });
209
+ const res = await callWeKnora(service, "PUT", "/api/v1/memory/items/" + encodeURIComponent(id), patch);
210
+ return json(200, res.ok ? { ok: true } : { ok: false, error: res.error });
211
+ }
212
+
213
+ if (op === "forget") {
214
+ const res = await callWeKnora(service, "DELETE", "/api/v1/memory/items/" + encodeURIComponent(id));
215
+ return json(200, res.ok ? { ok: true } : { ok: false, error: res.error });
216
+ }
217
+
218
+ return json(400, { ok: false, error: "bad_op" });
219
+ },
220
+ },
221
+ ];
222
+ }
223
+
224
+ export function panelRoutes(options = {}) {
225
+ return [...journalRoutes(options), ...memoryRoutes()];
226
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "dsh-weknora-panel",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Sidebar panel for browsing and editing WeKnora knowledge bases without leaving DSH.",
5
+ "type": "module",
6
+ "main": "./lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./client": "./lib/client.js",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "dsh": {
13
+ "bundle": {
14
+ "patch": "./cordis.patch.yml"
15
+ },
16
+ "client": {
17
+ "inject": [
18
+ "@deepseek-ai/dsh-client-ui-renderer",
19
+ "@deepseek-ai/dsh-client-ui-layout"
20
+ ],
21
+ "platform": "web"
22
+ }
23
+ },
24
+ "keywords": [
25
+ "dsh",
26
+ "dsh-plugin",
27
+ "weknora",
28
+ "panel",
29
+ "ui",
30
+ "knowledge-base"
31
+ ],
32
+ "license": "MIT",
33
+ "files": [
34
+ "lib",
35
+ "README.md",
36
+ "cordis.patch.yml",
37
+ "package.json"
38
+ ],
39
+ "author": "chenge",
40
+ "engines": {
41
+ "node": ">=20"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public",
45
+ "registry": "https://registry.npmjs.org"
46
+ }
47
+ }