dsh-context-graph 0.2.2 → 0.3.0
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/README.md +20 -6
- package/README.zh.md +38 -0
- package/icon.svg +15 -0
- package/index.js +424 -396
- package/lib/client.js +118 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +7 -0
- package/package.json +17 -2
- package/update.js +54 -0
package/README.md
CHANGED
|
@@ -12,8 +12,16 @@ turn (t1, t2, ...). The model follows that table to the exact part it needs with
|
|
|
12
12
|
or `recall("n12")`. Your newest turns stay word for word. Nothing is deleted: the full turns stay
|
|
13
13
|
in the session log and in the chat window.
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
**Looks like dsh (v0.3.0).** The Plugins page shows the plugin's own icon in dsh's icon style, a
|
|
16
|
+
title and description in English or Chinese (上下文图谱), and a Chinese detail page. In chat,
|
|
17
|
+
`/context-graph` results appear in dsh's own command card: a titled row with a one-line summary
|
|
18
|
+
that expands to the details.
|
|
19
|
+
|
|
20
|
+
Status: v0.3.0. Installs and loads in the dsh desktop app (dsh 0.2.1-rc.5); folding and indexing
|
|
21
|
+
are not yet verified with a live model. 28 tests pass against the published dsh packages.
|
|
22
|
+
|
|
23
|
+
Using Claude Code instead? The Claude version is a separate plugin built for Claude's app:
|
|
24
|
+
[claude-context-graph](https://github.com/William20100221/claude-context-graph).
|
|
17
25
|
|
|
18
26
|
## What it does
|
|
19
27
|
|
|
@@ -53,10 +61,12 @@ Command line (use the profile your app runs; the desktop app uses `desktop`):
|
|
|
53
61
|
dsh plugin --profile desktop add dsh-context-graph
|
|
54
62
|
```
|
|
55
63
|
|
|
56
|
-
**Updates.**
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
64
|
+
**Updates.** dsh 0.2.1 desktop builds have no update check for third-party plugins, so the
|
|
65
|
+
plugin checks npm itself once per app start. When a newer version exists, your next chat reply
|
|
66
|
+
ends with one line saying so, and `/context-graph stats` shows it on its first line. To update:
|
|
67
|
+
Plugins, open dsh-context-graph, **Uninstall**, then **Add plugin** `dsh-context-graph@<new version>`
|
|
68
|
+
and restart the app. Name the exact version: dsh's pnpm holds back very new releases otherwise.
|
|
69
|
+
Turn the check off with the environment variable `DSH_CONTEXT_GRAPH_NO_UPDATE_CHECK=1`.
|
|
60
70
|
|
|
61
71
|
Remove with `dsh plugin --profile desktop remove dsh-context-graph`.
|
|
62
72
|
|
|
@@ -97,6 +107,10 @@ Defaults live in [cordis.patch.yml](cordis.patch.yml). A patch replaces the row'
|
|
|
97
107
|
index.js dsh plugin: builder, matcher, recall tool, meter, /context-graph command
|
|
98
108
|
graph.js pure core: tokenize, match, merge, render, builder prompt and parser
|
|
99
109
|
store.js graph.json and src/<id>.md read/write
|
|
110
|
+
update.js once-per-start check of npm for a newer version
|
|
111
|
+
lib/client.js dsh chat card for /context-graph (DisclosureRow, en/zh titles)
|
|
112
|
+
icon.svg Plugins page icon in dsh's built-in icon style
|
|
113
|
+
locale/ Plugins page title and description (en, zh); zh links README.zh.md
|
|
100
114
|
cordis.patch.yml mounts the plugin at the profile root with default config
|
|
101
115
|
test/ node --test; plugin.test.js needs DSH_NODE_MODULES (see below)
|
|
102
116
|
docs/ design
|
package/README.zh.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# 上下文图谱(dsh-context-graph)
|
|
2
|
+
|
|
3
|
+
DeepSeek Harness 插件:把过往对话记成一张小型主题图谱,并把长对话的旧轮次折叠成目录,让每次请求少发送输入 token。需要细节时,模型按目录找到原文。
|
|
4
|
+
|
|
5
|
+
## 它做什么
|
|
6
|
+
|
|
7
|
+
| 时机 | 发生了什么 |
|
|
8
|
+
|---|---|
|
|
9
|
+
| 每 4 轮人类发言 | 回合结束后,用一次小型模型调用把新内容整理进 `.context-graph/graph.json`,并原样保存被引用的消息。不会拖慢回复。 |
|
|
10
|
+
| 新对话的第一条消息 | 附上之前对话中最重要的主题(编号、名称、一句话要点),最多 40 条。 |
|
|
11
|
+
| 每条人类消息 | 按词语重合匹配图谱(不调用模型),把最多 5 个相关主题附在消息末尾。 |
|
|
12
|
+
| 对话旧内容每次请求超过约 24k token | 在下一轮开始时,把旧轮次替换为一份目录:主题列表加每轮一句话。最近 2 轮保持原样。原文不删除,聊天窗口照常显示。 |
|
|
13
|
+
| 模型调用 `recall` | `n12`:返回该主题的原文和相邻主题。`t7`:原样返回被折叠的第 7 轮,包括工具输出。 |
|
|
14
|
+
|
|
15
|
+
## 命令
|
|
16
|
+
|
|
17
|
+
在对话中输入(菜单弹出时先选 `context-graph`,再输入后面的词):
|
|
18
|
+
|
|
19
|
+
- `/context-graph`:状态,包括主题数、待索引轮数、是否有新版本。
|
|
20
|
+
- `/context-graph build`:立即索引当前对话。
|
|
21
|
+
- `/context-graph fold`:立即索引并折叠旧轮次。
|
|
22
|
+
- `/context-graph find 关键词`:查找相关主题。
|
|
23
|
+
|
|
24
|
+
## 安装与更新
|
|
25
|
+
|
|
26
|
+
插件 → 添加插件 → 官方 npm 源 → 输入 `dsh-context-graph`,安装后完全重启应用。
|
|
27
|
+
|
|
28
|
+
有新版本时,你的下一次回复末尾会提示一次,`/context-graph` 的第一行也会显示。更新方法:打开本插件 → 卸载 → 添加插件 `dsh-context-graph@新版本号` → 重启。务必写明版本号:dsh 的 pnpm 默认会暂缓刚发布的版本。
|
|
29
|
+
|
|
30
|
+
## 关于费用
|
|
31
|
+
|
|
32
|
+
DeepSeek 对重复发送的已缓存输入只收约 1/30 的价格,而每次折叠都会让缓存重新开始一次。所以折叠只在旧内容很大时、并且目录不到原内容一半时才发生。短对话里它什么都不做。最大的收益来自新对话:不用重复解释,图谱已经记得之前的决定。
|
|
33
|
+
|
|
34
|
+
## 设置
|
|
35
|
+
|
|
36
|
+
默认值见 [cordis.patch.yml](cordis.patch.yml)。如果你的对话模型是"思考型"模型(例如 Qwen3)而且较慢,可以用 `provider` 和 `model` 让索引改用更快的模型。
|
|
37
|
+
|
|
38
|
+
英文完整说明见 [README.md](README.md)。
|
package/icon.svg
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
<svg width="36" height="36" viewBox="0 0 36 36" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2
|
+
<g transform="translate(1.5 1.5) scale(0.9166666667)">
|
|
3
|
+
<rect x="6" y="6" width="24" height="24" rx="7" fill="url(#a)" fill-opacity="0.8" />
|
|
4
|
+
<path d="M13 13.5L23 15.5M13 13.5L16 23M23 15.5L16 23" stroke="#FFFFFF" stroke-width="1.6" stroke-linecap="round" />
|
|
5
|
+
<circle cx="13" cy="13.5" r="2.6" fill="#FFFFFF" />
|
|
6
|
+
<circle cx="23" cy="15.5" r="2.2" fill="#FFFFFF" />
|
|
7
|
+
<circle cx="16" cy="23" r="2.2" fill="#FFFFFF" />
|
|
8
|
+
</g>
|
|
9
|
+
<defs>
|
|
10
|
+
<linearGradient id="a" x1="18" y1="6" x2="18" y2="30" gradientUnits="userSpaceOnUse">
|
|
11
|
+
<stop stop-color="#7AC2FF" />
|
|
12
|
+
<stop offset="1" stop-color="#4A65E8" />
|
|
13
|
+
</linearGradient>
|
|
14
|
+
</defs>
|
|
15
|
+
</svg>
|
package/index.js
CHANGED
|
@@ -1,396 +1,424 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* dsh-context-graph: memory of past conversations as a small graph, so the model reads node
|
|
3
|
-
* gists instead of old messages and fetches verbatim text only when it needs it.
|
|
4
|
-
*
|
|
5
|
-
* - `agent/turn-stopping`: every few human turns, one cheap auxiliary model call indexes the new
|
|
6
|
-
* span into `<workspace>/.context-graph/graph.json` and stores the cited messages verbatim.
|
|
7
|
-
* - `agent/pre-step`: on a human turn, lexically match the prompt against the graph and append one
|
|
8
|
-
* short `[context-graph]` block to the admitted messages (end of the request, so the provider's
|
|
9
|
-
* prefix cache survives). The first human turn of a session also gets the cross-session surface layer.
|
|
10
|
-
* - Tool `recall`: verbatim source and neighbours of one node.
|
|
11
|
-
* - `llm/stream`: meters main vs builder tokens and cache reads for `/context-graph stats`.
|
|
12
|
-
* Stock compaction is untouched.
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
import { isAbsolute, join } from 'node:path'
|
|
16
|
-
import {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
import {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
if (
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
const
|
|
123
|
-
if (
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
st.
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
const
|
|
196
|
-
const
|
|
197
|
-
const
|
|
198
|
-
const
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
const
|
|
378
|
-
const
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* dsh-context-graph: memory of past conversations as a small graph, so the model reads node
|
|
3
|
+
* gists instead of old messages and fetches verbatim text only when it needs it.
|
|
4
|
+
*
|
|
5
|
+
* - `agent/turn-stopping`: every few human turns, one cheap auxiliary model call indexes the new
|
|
6
|
+
* span into `<workspace>/.context-graph/graph.json` and stores the cited messages verbatim.
|
|
7
|
+
* - `agent/pre-step`: on a human turn, lexically match the prompt against the graph and append one
|
|
8
|
+
* short `[context-graph]` block to the admitted messages (end of the request, so the provider's
|
|
9
|
+
* prefix cache survives). The first human turn of a session also gets the cross-session surface layer.
|
|
10
|
+
* - Tool `recall`: verbatim source and neighbours of one node.
|
|
11
|
+
* - `llm/stream`: meters main vs builder tokens and cache reads for `/context-graph stats`.
|
|
12
|
+
* Stock compaction is untouched.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { isAbsolute, join } from 'node:path'
|
|
16
|
+
import { readFileSync } from 'node:fs'
|
|
17
|
+
import { mkdir, stat, writeFile } from 'node:fs/promises'
|
|
18
|
+
|
|
19
|
+
import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
20
|
+
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
builderInstruction, collectSpan, emptyGraph, estimateTokens, foldKept, matchNodes, mergeDelta, neighbors, onlyFromSession,
|
|
24
|
+
parseBuilderOutput, planFold, renderFoldIndex, renderHits, renderSurface, SOURCE_KIND, surfaceNodes, transcriptForBuilder,
|
|
25
|
+
turnIndex, turnTranscript
|
|
26
|
+
} from './graph.js'
|
|
27
|
+
import { appendSource, loadGraph, readSource, saveGraph } from './store.js'
|
|
28
|
+
import { startUpdateCheck } from './update.js'
|
|
29
|
+
|
|
30
|
+
export const name = 'context-graph'
|
|
31
|
+
export const inject = ['tools']
|
|
32
|
+
|
|
33
|
+
const PURPOSE = 'context-graph'
|
|
34
|
+
const { version } = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
|
|
35
|
+
|
|
36
|
+
const DEFAULTS = {
|
|
37
|
+
dir: '.context-graph',
|
|
38
|
+
buildEveryTurns: 4,
|
|
39
|
+
buildMinChars: 400,
|
|
40
|
+
maxHits: 5,
|
|
41
|
+
inlineMaxChars: 1200,
|
|
42
|
+
surfaceMaxNodes: 40,
|
|
43
|
+
builderMaxTokens: 8192,
|
|
44
|
+
provider: '',
|
|
45
|
+
model: '',
|
|
46
|
+
fold: true,
|
|
47
|
+
foldAtTokens: 24000,
|
|
48
|
+
keepTurns: 2
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const textOf = (content) => (Array.isArray(content) ? content : []).filter((b) => b?.type === 'text').map((b) => b.text).join('\n').trim()
|
|
52
|
+
|
|
53
|
+
export function apply(ctx, config = {}) {
|
|
54
|
+
const { _updates, ...rest } = config
|
|
55
|
+
const cfg = { ...DEFAULTS, ...rest }
|
|
56
|
+
// `_updates` lets tests stand in for the network check.
|
|
57
|
+
const updates = _updates ?? startUpdateCheck(version)
|
|
58
|
+
let noticeShown = false
|
|
59
|
+
const sessions = new Map()
|
|
60
|
+
const graphCache = new Map()
|
|
61
|
+
const meter = {
|
|
62
|
+
main: { requests: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
|
|
63
|
+
builder: { requests: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
|
|
64
|
+
builds: 0,
|
|
65
|
+
folds: 0,
|
|
66
|
+
foldSaved: 0,
|
|
67
|
+
injected: 0,
|
|
68
|
+
injectedTokens: 0,
|
|
69
|
+
recalls: 0
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const state = (sid) => {
|
|
73
|
+
let st = sessions.get(sid)
|
|
74
|
+
if (!st) { st = { lastBuiltSeq: -1, building: false, surfaceSent: false }; sessions.set(sid, st) }
|
|
75
|
+
return st
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function dirFor(agent) {
|
|
79
|
+
const base = agent.options?.cwd ?? agent.session.header?.cwd ?? process.cwd()
|
|
80
|
+
return isAbsolute(cfg.dir) ? cfg.dir : join(base, cfg.dir)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Graph read with an mtime check so other sessions' builds show up without a restart. */
|
|
84
|
+
async function getGraph(dir) {
|
|
85
|
+
let mtimeMs = 0
|
|
86
|
+
try { mtimeMs = (await stat(join(dir, 'graph.json'))).mtimeMs } catch { return emptyGraph() }
|
|
87
|
+
const cached = graphCache.get(dir)
|
|
88
|
+
if (cached && cached.mtimeMs === mtimeMs) return cached.graph
|
|
89
|
+
const graph = await loadGraph(dir)
|
|
90
|
+
graphCache.set(dir, { mtimeMs, graph })
|
|
91
|
+
return graph
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function resolveTarget(agent) {
|
|
95
|
+
if (cfg.provider && cfg.model) return { provider: cfg.provider, model: cfg.model }
|
|
96
|
+
const routed = agent.session.requestHeader()?.config
|
|
97
|
+
if (routed?.provider && routed?.model) return { provider: routed.provider, model: routed.model }
|
|
98
|
+
const { provider, model } = agent.options ?? {}
|
|
99
|
+
return provider && model ? { provider, model } : undefined
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function surfaceAlreadyOnLog(session) {
|
|
103
|
+
return session.surface.nodes.some((seq) => {
|
|
104
|
+
const event = session.eventAt(seq)
|
|
105
|
+
return event?.type === 'user/message' && event.data?.source?.kind === SOURCE_KIND && event.data.source.layer === 'surface'
|
|
106
|
+
})
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ---------- builder ----------
|
|
110
|
+
const isSubagent = (agent) => agent.options?.origin === 'subagent' || agent.session.header?.origin === 'subagent'
|
|
111
|
+
|
|
112
|
+
async function build(agent, { force = false, turn = null } = {}) {
|
|
113
|
+
const session = agent.session
|
|
114
|
+
const sid = String(session.id)
|
|
115
|
+
const st = state(sid)
|
|
116
|
+
if (st.building) return { status: 'busy' }
|
|
117
|
+
// ponytail: subagent chatter stays out of the project graph; revisit if delegated work holds decisions worth keeping.
|
|
118
|
+
if (isSubagent(agent)) return { status: 'skipped', reason: 'subagent session' }
|
|
119
|
+
st.building = true
|
|
120
|
+
try {
|
|
121
|
+
const span = collectSpan(session.surface.nodes, (seq) => session.eventAt(seq), st.lastBuiltSeq)
|
|
122
|
+
const chars = span.messages.reduce((n, m) => n + m.text.length, 0)
|
|
123
|
+
if (span.messages.length === 0) return { status: 'nothing', reason: 'no new messages since the last build' }
|
|
124
|
+
if (!force && (span.userTurns < cfg.buildEveryTurns || chars < cfg.buildMinChars)) {
|
|
125
|
+
return { status: 'skipped', reason: `${span.userTurns}/${cfg.buildEveryTurns} human turns, ${chars}/${cfg.buildMinChars} chars` }
|
|
126
|
+
}
|
|
127
|
+
const llm = ctx.get('llm')
|
|
128
|
+
if (!llm) return { status: 'unavailable', reason: 'no llm service in this composition' }
|
|
129
|
+
const target = resolveTarget(agent)
|
|
130
|
+
if (!target) return { status: 'unavailable', reason: 'no provider/model routed yet' }
|
|
131
|
+
const dir = dirFor(agent)
|
|
132
|
+
const graph = await loadGraph(dir)
|
|
133
|
+
const prompt = `${transcriptForBuilder(span.messages)}\n\n${builderInstruction(graph)}`
|
|
134
|
+
const assembler = new BlockAssembler()
|
|
135
|
+
for await (const chunk of llm.stream({
|
|
136
|
+
provider: target.provider,
|
|
137
|
+
model: target.model,
|
|
138
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
|
|
139
|
+
maxTokens: cfg.builderMaxTokens,
|
|
140
|
+
sessionId: session.id,
|
|
141
|
+
purpose: PURPOSE
|
|
142
|
+
})) assembler.push(chunk)
|
|
143
|
+
const finish = assembler.finish
|
|
144
|
+
if (finish?.kind === 'error' || finish?.kind === 'aborted') throw new Error(finish.failure?.message ?? finish.kind)
|
|
145
|
+
const blocks = assembler.blocks()
|
|
146
|
+
const answer = textOf(blocks)
|
|
147
|
+
// Some thinking models put everything, JSON included, into reasoning blocks.
|
|
148
|
+
const reasoning = blocks.filter((b) => b?.type === 'reasoning').map((b) => b.text).join('\n')
|
|
149
|
+
const delta = parseBuilderOutput(answer) ?? parseBuilderOutput(reasoning)
|
|
150
|
+
if (!delta || (delta.nodes.length === 0 && finish?.kind === 'max-tokens')) {
|
|
151
|
+
const saved = join(dir, 'last-builder-output.txt')
|
|
152
|
+
await mkdir(dir, { recursive: true })
|
|
153
|
+
await writeFile(saved, `finish: ${finish?.kind}\n\n--- answer ---\n${answer}\n\n--- reasoning ---\n${reasoning}\n`, 'utf8')
|
|
154
|
+
const why = finish?.kind === 'max-tokens'
|
|
155
|
+
? `the model ran out of output tokens (builderMaxTokens ${cfg.builderMaxTokens}) before finishing`
|
|
156
|
+
: 'builder output was not the expected JSON'
|
|
157
|
+
return { status: 'failed', reason: `${why}; raw output saved to ${saved}` }
|
|
158
|
+
}
|
|
159
|
+
// Reversibility rule: a node is written only when it cites text we can store verbatim.
|
|
160
|
+
delta.nodes = delta.nodes.filter((n) => n.msgs.some((i) => span.messages[i]))
|
|
161
|
+
const now = new Date().toISOString()
|
|
162
|
+
const touched = mergeDelta(graph, delta, { session: sid, turn, now })
|
|
163
|
+
for (const { id, msgs } of touched) {
|
|
164
|
+
const cited = msgs.map((i) => span.messages[i]).filter(Boolean)
|
|
165
|
+
if (cited.length > 0) await appendSource(dir, id, { session: sid, turn, at: now, messages: cited })
|
|
166
|
+
}
|
|
167
|
+
await saveGraph(dir, graph)
|
|
168
|
+
st.lastBuiltSeq = span.lastSeq
|
|
169
|
+
meter.builds++
|
|
170
|
+
return { status: 'built', nodes: touched.length, newNodes: touched.filter((t) => t.isNew).length, totalNodes: Object.keys(graph.nodes).length, edges: graph.edges.length, dir }
|
|
171
|
+
} catch (error) {
|
|
172
|
+
console.error('context-graph: build failed (non-fatal)', error)
|
|
173
|
+
return { status: 'failed', reason: String(error?.message ?? error) }
|
|
174
|
+
} finally {
|
|
175
|
+
st.building = false
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
ctx.on('agent/turn-stopping', (payload) => {
|
|
180
|
+
// Fire and forget: the build must never delay the turn's close.
|
|
181
|
+
void build(payload.agent, { turn: payload.turn })
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
// ---------- fold: replace old turns of this chat with a table of contents ----------
|
|
185
|
+
function rangeTokens(session, seqs) {
|
|
186
|
+
const wanted = new Set(seqs)
|
|
187
|
+
try {
|
|
188
|
+
const nodes = ctx.get('tokenMeter')?.measure(session)?.nodes
|
|
189
|
+
if (Array.isArray(nodes)) return nodes.filter((n) => wanted.has(n.seq)).reduce((sum, n) => sum + (n.tokens ?? n.heuristicTokens ?? 0), 0)
|
|
190
|
+
} catch { /* fall back to the estimate */ }
|
|
191
|
+
return seqs.reduce((sum, seq) => sum + estimateTokens(JSON.stringify(session.eventAt(seq)?.data ?? '')), 0)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async function fold(agent, { force = false } = {}) {
|
|
195
|
+
const session = agent.session
|
|
196
|
+
const sid = String(session.id)
|
|
197
|
+
const eventAt = (seq) => session.eventAt(seq)
|
|
198
|
+
const plan = planFold(session.surface.nodes, eventAt, { keepTurns: cfg.keepTurns, maxSeq: state(sid).lastBuiltSeq })
|
|
199
|
+
if (!plan) return { status: 'skipped', reason: `nothing indexed outside the last ${cfg.keepTurns} turns yet` }
|
|
200
|
+
const before = rangeTokens(session, plan.shadowedSeqs)
|
|
201
|
+
if (!force && before < cfg.foldAtTokens) return { status: 'skipped', reason: `foldable part is ~${before} tokens, folds at ${cfg.foldAtTokens}` }
|
|
202
|
+
const turns = turnIndex(eventAt, plan.endSeq)
|
|
203
|
+
const index = renderFoldIndex(await getGraph(dirFor(agent)), sid, turns, { maxNodes: cfg.surfaceMaxNodes })
|
|
204
|
+
const kept = foldKept(plan.shadowedSeqs, eventAt)
|
|
205
|
+
const after = estimateTokens([index, ...kept.blocks.map((b) => b.text ?? '')].join('\n'))
|
|
206
|
+
// Never-worse gate: a fold must at least halve what it replaces, or it is not worth breaking the cache.
|
|
207
|
+
if (after * 2 > before) return { status: 'skipped', reason: `table of contents (~${after}) is not under half of the ~${before} tokens it would replace` }
|
|
208
|
+
const message = createUserMessage({
|
|
209
|
+
content: [{ type: 'text', text: index }, ...kept.blocks],
|
|
210
|
+
source: { kind: SOURCE_KIND, fold: true, keptKinds: kept.kinds, foldedTurns: turns.length, foldedTokens: before }
|
|
211
|
+
})
|
|
212
|
+
session.append('user/message', message, {
|
|
213
|
+
surfaceOp: { op: 'replace', startSeq: plan.startSeq, endSeq: plan.endSeq },
|
|
214
|
+
sourceEventSeqs: [...plan.shadowedSeqs]
|
|
215
|
+
})
|
|
216
|
+
meter.folds++
|
|
217
|
+
meter.foldSaved += before - after
|
|
218
|
+
return { status: 'folded', turns: turns.length, before, after }
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ---------- matcher ----------
|
|
222
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
223
|
+
const agent = payload.agent
|
|
224
|
+
const prompt = payload.messages.filter((m) => m.source?.kind === 'user').map((m) => textOf(m.content)).join('\n')
|
|
225
|
+
// Fold only at the start of a human turn: the previous turn is closed, so no tool call is open.
|
|
226
|
+
if (cfg.fold && prompt && !isSubagent(agent)) {
|
|
227
|
+
try { await fold(agent) } catch (error) { console.error('context-graph: fold failed (non-fatal)', error) }
|
|
228
|
+
}
|
|
229
|
+
const decision = await next()
|
|
230
|
+
if (decision.kind !== 'enter') return decision
|
|
231
|
+
const result = await addMemory(agent, prompt, decision)
|
|
232
|
+
return prompt && !isSubagent(agent) ? addUpdateNotice(result) : result
|
|
233
|
+
})
|
|
234
|
+
|
|
235
|
+
/** Once per app start, ask the model to pass an available update on to the user. */
|
|
236
|
+
function addUpdateNotice(decision) {
|
|
237
|
+
const notice = updates.current()
|
|
238
|
+
if (!notice || noticeShown) return decision
|
|
239
|
+
noticeShown = true
|
|
240
|
+
const message = createUserMessage({
|
|
241
|
+
content: [{ type: 'text', text: `[${SOURCE_KIND}] ${notice} At the end of your reply, tell the user this in one short line.` }],
|
|
242
|
+
source: { kind: SOURCE_KIND, notice: true }
|
|
243
|
+
})
|
|
244
|
+
return { ...decision, messages: [...decision.messages, message] }
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function addMemory(agent, prompt, decision) {
|
|
248
|
+
try {
|
|
249
|
+
if (isSubagent(agent) || !prompt) return decision
|
|
250
|
+
const dir = dirFor(agent)
|
|
251
|
+
const graph = await getGraph(dir)
|
|
252
|
+
if (Object.keys(graph.nodes).length === 0) return decision
|
|
253
|
+
const sid = String(agent.session.id)
|
|
254
|
+
const st = state(sid)
|
|
255
|
+
const sessionCompacted = agent.session.surface.replaceGeneration > 0
|
|
256
|
+
const parts = []
|
|
257
|
+
let layer
|
|
258
|
+
if (!st.surfaceSent) {
|
|
259
|
+
st.surfaceSent = true
|
|
260
|
+
// Nodes that only come from this very session are still in its context: no need to repeat them.
|
|
261
|
+
const ids = surfaceNodes(graph, cfg.surfaceMaxNodes).filter((id) => sessionCompacted || !onlyFromSession(graph.nodes[id], sid))
|
|
262
|
+
if (ids.length > 0 && !surfaceAlreadyOnLog(agent.session)) {
|
|
263
|
+
parts.push(renderSurface(graph, ids))
|
|
264
|
+
layer = 'surface'
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
const hits = matchNodes(graph, prompt, { max: cfg.maxHits, session: sid, sessionCompacted })
|
|
268
|
+
let inline
|
|
269
|
+
if (hits.length === 1 || (hits.length > 1 && hits[0].score >= 2 * hits[1].score)) {
|
|
270
|
+
const text = await readSource(dir, hits[0].id)
|
|
271
|
+
if (text && text.length <= cfg.inlineMaxChars) inline = { id: hits[0].id, text }
|
|
272
|
+
}
|
|
273
|
+
const block = renderHits(graph, hits, { inline })
|
|
274
|
+
if (block) parts.push(block)
|
|
275
|
+
if (parts.length === 0) return decision
|
|
276
|
+
const text = parts.join('\n\n')
|
|
277
|
+
meter.injected++
|
|
278
|
+
meter.injectedTokens += estimateTokens(text)
|
|
279
|
+
const message = createUserMessage({ content: [{ type: 'text', text }], source: layer ? { kind: SOURCE_KIND, layer } : { kind: SOURCE_KIND } })
|
|
280
|
+
return { ...decision, messages: [...decision.messages, message] }
|
|
281
|
+
} catch (error) {
|
|
282
|
+
console.error('context-graph: matcher failed (non-fatal)', error)
|
|
283
|
+
return decision
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// ---------- meter ----------
|
|
288
|
+
ctx.on('llm/stream', (options, next) => {
|
|
289
|
+
const inner = next()
|
|
290
|
+
const bucket = options.purpose === PURPOSE ? meter.builder : meter.main
|
|
291
|
+
async function* tracked() {
|
|
292
|
+
try {
|
|
293
|
+
for await (const chunk of inner) {
|
|
294
|
+
if (chunk?.type === 'usage' && chunk.usage) {
|
|
295
|
+
bucket.input += chunk.usage.inputTokens ?? 0
|
|
296
|
+
bucket.cacheRead += chunk.usage.cacheReadTokens ?? 0
|
|
297
|
+
bucket.cacheWrite += chunk.usage.cacheWriteTokens ?? 0
|
|
298
|
+
bucket.output += chunk.usage.outputTokens ?? 0
|
|
299
|
+
}
|
|
300
|
+
yield chunk
|
|
301
|
+
}
|
|
302
|
+
} finally {
|
|
303
|
+
bucket.requests++
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return tracked()
|
|
307
|
+
})
|
|
308
|
+
|
|
309
|
+
// ---------- recall tool ----------
|
|
310
|
+
ctx.tools.register(defineTool({
|
|
311
|
+
name: 'recall',
|
|
312
|
+
description: [
|
|
313
|
+
'Fetch verbatim text behind an id shown in a [context-graph] block: a topic id (n17) returns its source messages and neighbouring topics; a turn id (t7) returns that folded turn of this conversation exactly.',
|
|
314
|
+
'Call it when a gist is relevant but not precise enough to answer. Never invent an id; only use ids you were shown.'
|
|
315
|
+
].join(' '),
|
|
316
|
+
parameters: {
|
|
317
|
+
id: { type: 'string', required: true, description: 'Topic id such as n17, or turn id such as t7.' },
|
|
318
|
+
depth: { type: 'integer', description: '0 (default): this node only. 1: also include each neighbour\'s gist.' }
|
|
319
|
+
},
|
|
320
|
+
output: {
|
|
321
|
+
schema: {
|
|
322
|
+
type: 'object',
|
|
323
|
+
additionalProperties: false,
|
|
324
|
+
properties: {
|
|
325
|
+
status: { type: 'string', enum: ['ok', 'unknown'], required: true },
|
|
326
|
+
text: { type: 'string', required: true }
|
|
327
|
+
}
|
|
328
|
+
},
|
|
329
|
+
render: (_args, value) => [{ type: 'text', text: value.text }]
|
|
330
|
+
},
|
|
331
|
+
async execute(args, exec) {
|
|
332
|
+
const agent = exec.agent
|
|
333
|
+
if (!agent?.session) return { status: 'unknown', text: 'recall is unavailable: no session attached to this call.' }
|
|
334
|
+
const id = String(args.id ?? '').trim()
|
|
335
|
+
const turn = /^t(\d+)$/.exec(id)
|
|
336
|
+
if (turn) {
|
|
337
|
+
const text = turnTranscript((seq) => agent.session.eventAt(seq), Number(turn[1]))
|
|
338
|
+
if (text === undefined) return { status: 'unknown', text: `No turn ${id} in this conversation.` }
|
|
339
|
+
meter.recalls++
|
|
340
|
+
return { status: 'ok', text: `# ${id} (verbatim)\n\n${text}` }
|
|
341
|
+
}
|
|
342
|
+
const dir = dirFor(agent)
|
|
343
|
+
const graph = await getGraph(dir)
|
|
344
|
+
const node = graph.nodes[id]
|
|
345
|
+
if (!node) return { status: 'unknown', text: `No node "${id}" in this project's context graph. Only use ids shown in a [context-graph] block.` }
|
|
346
|
+
meter.recalls++
|
|
347
|
+
node.hits = (node.hits ?? 0) + 1
|
|
348
|
+
saveGraph(dir, graph).catch((error) => console.error('context-graph: hit count save failed', error))
|
|
349
|
+
const lines = [`# ${id} ${node.label}`, `${node.kind}. ${node.gist}`, '']
|
|
350
|
+
const source = await readSource(dir, id)
|
|
351
|
+
lines.push(source ? source.trim() : '(no verbatim source stored for this node)')
|
|
352
|
+
const links = neighbors(graph, id)
|
|
353
|
+
if (links.length > 0) {
|
|
354
|
+
lines.push('', 'Neighbours:')
|
|
355
|
+
for (const link of links) {
|
|
356
|
+
const other = graph.nodes[link.id]
|
|
357
|
+
const arrow = link.direction === 'out' ? `${id} ${link.relation} ${link.id}` : `${link.id} ${link.relation} ${id}`
|
|
358
|
+
lines.push(`- ${arrow}: ${other.label}${args.depth >= 1 ? ` — ${other.gist}` : ''}`)
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
return { status: 'ok', text: lines.join('\n') }
|
|
362
|
+
}
|
|
363
|
+
}))
|
|
364
|
+
|
|
365
|
+
// ---------- /context-graph command (nested: only where a human-command surface exists) ----------
|
|
366
|
+
ctx.plugin({
|
|
367
|
+
name: 'context-graph-command',
|
|
368
|
+
inject: ['commands'],
|
|
369
|
+
apply(cmdCtx) {
|
|
370
|
+
cmdCtx.effect(function* () {
|
|
371
|
+
yield cmdCtx.commands.register({
|
|
372
|
+
name: 'context-graph',
|
|
373
|
+
description: 'Project memory graph: /context-graph [stats|build|fold|find <words>]',
|
|
374
|
+
// Without `input`, dsh clients run the bare name and send any typed arguments to the model as chat.
|
|
375
|
+
input: { hint: '[stats|build|fold|find <words>]' },
|
|
376
|
+
async handler(invocation) {
|
|
377
|
+
const [sub = 'stats', ...rest] = invocation.rawInput.trim().split(/\s+/).filter(Boolean)
|
|
378
|
+
const agent = invocation.agent
|
|
379
|
+
if (sub === 'fold') {
|
|
380
|
+
const result = await agent.runMaintenance(async () => {
|
|
381
|
+
await build(agent, { force: true })
|
|
382
|
+
return fold(agent, { force: true })
|
|
383
|
+
})
|
|
384
|
+
if (result.status !== 'folded') return { kind: 'error', text: `Not folded: ${result.reason}` }
|
|
385
|
+
return { kind: 'success', text: `Folded t1-t${result.turns} · ~${result.before} → ~${result.after} tokens per request
|
|
386
|
+
}
|
|
387
|
+
if (sub === 'build') {
|
|
388
|
+
const result = await agent.runMaintenance(() => build(agent, { force: true }))
|
|
389
|
+
if (result.status !== 'built') return { kind: 'error', text: `Build ${result.status}: ${result.reason ?? ''}`.trim() }
|
|
390
|
+
return { kind: 'success', text: `${result.nodes} topics indexed (${result.newNodes} new) · graph has ${result.totalNodes} topics\nLinks: ${result.edges}\nFolder: ${result.dir}` }
|
|
391
|
+
}
|
|
392
|
+
const graph = await getGraph(dirFor(agent))
|
|
393
|
+
if (sub === 'find') {
|
|
394
|
+
const hits = matchNodes(graph, rest.join(' '), { max: cfg.maxHits })
|
|
395
|
+
if (hits.length === 0) return { kind: 'success', text: 'No matching topics' }
|
|
396
|
+
const lines = hits.map(({ id, node }) => `${id} ${node.label}: ${node.gist}`)
|
|
397
|
+
return { kind: 'success', text: [`${hits.length} matching ${hits.length === 1 ? 'topic' : 'topics'}`, ...lines].join('\n') }
|
|
398
|
+
}
|
|
399
|
+
if (sub !== 'stats') return { kind: 'error', text: 'Usage: /context-graph [stats|build|fold|find <words>]' }
|
|
400
|
+
const m = meter.main
|
|
401
|
+
const cached = m.cacheRead + m.cacheWrite
|
|
402
|
+
const hitRate = m.input + cached > 0 ? Math.round((m.cacheRead / (m.input + cached)) * 100) : 0
|
|
403
|
+
const session = agent.session
|
|
404
|
+
const pending = collectSpan(session.surface.nodes, (seq) => session.eventAt(seq), state(String(session.id)).lastBuiltSeq).userTurns
|
|
405
|
+
return {
|
|
406
|
+
kind: 'success',
|
|
407
|
+
text: [
|
|
408
|
+
`${Object.keys(graph.nodes).length} topics · ${graph.edges.length} links · ${pending} turns waiting to be indexed${updates.current() ? ' · update available' : ''}`,
|
|
409
|
+
`Version ${version}: ${updates.current() ?? 'no newer version found'}`,
|
|
410
|
+
`Graph folder: ${dirFor(agent)}`,
|
|
411
|
+
`This chat indexes itself every ${cfg.buildEveryTurns} turns; /context-graph build indexes it now.`,
|
|
412
|
+
'Counters below are since the app started:',
|
|
413
|
+
`Builds: ${meter.builds}; builder tokens in/out: ${meter.builder.input + meter.builder.cacheRead + meter.builder.cacheWrite}/${meter.builder.output}`,
|
|
414
|
+
`Folds: ${meter.folds}; ~${meter.foldSaved} input tokens removed from every later request`,
|
|
415
|
+
`Injected blocks: ${meter.injected} (~${meter.injectedTokens} tokens); recalls: ${meter.recalls}`,
|
|
416
|
+
`Main requests: ${m.requests}; input ${m.input} uncached + ${m.cacheRead} cache-read + ${m.cacheWrite} cache-write; cache-hit ${hitRate}%`
|
|
417
|
+
].join('\n')
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
})
|
|
421
|
+
}, 'context-graph command')
|
|
422
|
+
}
|
|
423
|
+
})
|
|
424
|
+
}
|
package/lib/client.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// Chat card for `/context-graph`, hand-written in dsh's client-bundle format (no build step).
|
|
2
|
+
// The shell loads this file as a plain script; `require` reaches only the shell's shared modules.
|
|
3
|
+
// Layout follows dsh's own command card: DisclosureRow with a 14px icon, a title, a one-line
|
|
4
|
+
// summary, and the remaining lines as an expandable body.
|
|
5
|
+
window.__ModuleLoader__.load({
|
|
6
|
+
id: 'dsh-context-graph',
|
|
7
|
+
factory: (require) => {
|
|
8
|
+
var module = { exports: {} }
|
|
9
|
+
var exports = module.exports
|
|
10
|
+
const { useState } = require('react')
|
|
11
|
+
const { jsx, jsxs } = require('react/jsx-runtime')
|
|
12
|
+
const { DisclosureRow } = require('@deepseek-ai/dsh-client-ui-primitives')
|
|
13
|
+
|
|
14
|
+
const NAMESPACE = 'dsh-context-graph'
|
|
15
|
+
const en = {
|
|
16
|
+
stats: 'Context graph',
|
|
17
|
+
build: 'Index this chat',
|
|
18
|
+
fold: 'Fold old turns',
|
|
19
|
+
find: 'Find topics',
|
|
20
|
+
running: 'Working…',
|
|
21
|
+
failed: 'Failed'
|
|
22
|
+
}
|
|
23
|
+
const zh = {
|
|
24
|
+
stats: '上下文图谱',
|
|
25
|
+
build: '索引当前对话',
|
|
26
|
+
fold: '折叠旧轮次',
|
|
27
|
+
find: '查找主题',
|
|
28
|
+
running: '处理中…',
|
|
29
|
+
failed: '失败'
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const CSS = [
|
|
33
|
+
'.dshcg-root{margin:2px 0}',
|
|
34
|
+
'.dshcg-summary{margin-left:8px;font-size:13px;opacity:.72}',
|
|
35
|
+
'.dshcg-summary[data-error]{color:var(--color-text-danger,#d64545);opacity:1}',
|
|
36
|
+
'.dshcg-body{padding:6px 0 6px 24px;font-size:13px;line-height:1.6;white-space:pre-wrap;word-break:break-word}'
|
|
37
|
+
].join('')
|
|
38
|
+
if (typeof document !== 'undefined' && document.querySelector('style[data-plugin-css="dsh-context-graph"]') === null) {
|
|
39
|
+
const tag = document.createElement('style')
|
|
40
|
+
tag.dataset.pluginCss = NAMESPACE
|
|
41
|
+
tag.textContent = CSS
|
|
42
|
+
document.head.appendChild(tag)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Three linked nodes: the same mark as the plugin icon, drawn in the current text colour.
|
|
46
|
+
const ICON = jsxs('svg', {
|
|
47
|
+
width: 14,
|
|
48
|
+
height: 14,
|
|
49
|
+
viewBox: '0 0 24 24',
|
|
50
|
+
fill: 'none',
|
|
51
|
+
stroke: 'currentColor',
|
|
52
|
+
strokeWidth: 2,
|
|
53
|
+
strokeLinecap: 'round',
|
|
54
|
+
'aria-hidden': true,
|
|
55
|
+
children: [
|
|
56
|
+
jsx('path', { d: 'M7 7l10 3M7 7l3 10M17 10l-7 7' }),
|
|
57
|
+
jsx('circle', { cx: 7, cy: 7, r: 2.5, fill: 'currentColor' }),
|
|
58
|
+
jsx('circle', { cx: 17, cy: 10, r: 2, fill: 'currentColor' }),
|
|
59
|
+
jsx('circle', { cx: 10, cy: 17, r: 2, fill: 'currentColor' })
|
|
60
|
+
]
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
const SUBCOMMANDS = ['stats', 'build', 'fold', 'find']
|
|
64
|
+
|
|
65
|
+
/** Title key from the typed arguments (`/context-graph fold` -> fold); no argument means stats. */
|
|
66
|
+
function subcommandOf(args) {
|
|
67
|
+
const first = String(args ?? '').trim().split(/\s+/)[0] || 'stats'
|
|
68
|
+
return SUBCOMMANDS.includes(first) ? first : 'stats'
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Host text: line 1 is the summary, later lines are the details shown when expanded. */
|
|
72
|
+
function splitText(text) {
|
|
73
|
+
const lines = String(text ?? '').split('\n')
|
|
74
|
+
return { summary: lines[0] ?? '', body: lines.slice(1).join('\n').trim() }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function ContextGraphCard({ node, t }) {
|
|
78
|
+
const [open, setOpen] = useState(false)
|
|
79
|
+
const outcome = node.outcome
|
|
80
|
+
const running = outcome === null
|
|
81
|
+
const failed = outcome?.kind === 'error'
|
|
82
|
+
const { summary, body } = splitText(outcome?.text)
|
|
83
|
+
const shown = running ? t('running') : summary || (failed ? t('failed') : '')
|
|
84
|
+
const hasBody = !running && body.length > 0
|
|
85
|
+
return jsx('div', {
|
|
86
|
+
className: 'dshcg-root',
|
|
87
|
+
'data-state': running ? 'running' : failed ? 'error' : 'ok',
|
|
88
|
+
children: jsx(DisclosureRow, {
|
|
89
|
+
icon: ICON,
|
|
90
|
+
title: t(subcommandOf(node.args)),
|
|
91
|
+
running,
|
|
92
|
+
open: open && hasBody,
|
|
93
|
+
expandable: hasBody,
|
|
94
|
+
expandOnRowClick: true,
|
|
95
|
+
keepContentWhenOpen: true,
|
|
96
|
+
onToggle: () => setOpen((value) => !value),
|
|
97
|
+
collapsedContent: shown ? jsx('span', { className: 'dshcg-summary', 'data-error': failed || undefined, children: shown }) : undefined,
|
|
98
|
+
children: open && hasBody ? jsx('div', { className: 'dshcg-body', children: body }) : undefined
|
|
99
|
+
})
|
|
100
|
+
})
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const inject = ['slots', 'locale']
|
|
104
|
+
function apply(ctx) {
|
|
105
|
+
ctx.effect(() => ctx.locale.register(NAMESPACE, { en, zh }), 'dsh-context-graph: dictionaries')
|
|
106
|
+
ctx.slots.inject('conversation.chat.commandview', () =>
|
|
107
|
+
ctx.slots.register({ name: 'conversation.chat.commandview', key: 'context-graph', locale: NAMESPACE }, ContextGraphCard)
|
|
108
|
+
)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
exports.inject = inject
|
|
112
|
+
exports.apply = apply
|
|
113
|
+
exports.ContextGraphCard = ContextGraphCard
|
|
114
|
+
exports.subcommandOf = subcommandOf
|
|
115
|
+
exports.splitText = splitText
|
|
116
|
+
return module.exports
|
|
117
|
+
}
|
|
118
|
+
})
|
package/locale/en.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,24 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-context-graph",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "DeepSeek Harness plugin: remembers past conversations as a small graph and folds old turns of a long chat into a table of contents, so fewer input tokens are sent; exact text is recalled on demand",
|
|
5
|
+
"icon": "./icon.svg",
|
|
5
6
|
"type": "module",
|
|
6
7
|
"main": "index.js",
|
|
7
8
|
"exports": {
|
|
8
9
|
".": "./index.js",
|
|
10
|
+
"./client": "./lib/client.js",
|
|
9
11
|
"./graph": "./graph.js",
|
|
12
|
+
"./locale/*.json": "./locale/*.json",
|
|
10
13
|
"./package.json": "./package.json"
|
|
11
14
|
},
|
|
12
15
|
"files": [
|
|
13
16
|
"index.js",
|
|
14
17
|
"graph.js",
|
|
15
18
|
"store.js",
|
|
19
|
+
"update.js",
|
|
20
|
+
"lib/client.js",
|
|
21
|
+
"locale",
|
|
22
|
+
"icon.svg",
|
|
16
23
|
"cordis.patch.yml",
|
|
17
24
|
"README.md",
|
|
25
|
+
"README.zh.md",
|
|
18
26
|
"LICENSE"
|
|
19
27
|
],
|
|
20
28
|
"scripts": {
|
|
21
|
-
"test": "node --import ./test/resolve-dsh.mjs --test test/graph.test.js test/fold.test.js test/plugin.test.js"
|
|
29
|
+
"test": "node --import ./test/resolve-dsh.mjs --test test/graph.test.js test/fold.test.js test/update.test.js test/client.test.js test/plugin.test.js"
|
|
22
30
|
},
|
|
23
31
|
"keywords": [
|
|
24
32
|
"dsh-plugin",
|
|
@@ -48,6 +56,13 @@
|
|
|
48
56
|
"dsh": {
|
|
49
57
|
"bundle": {
|
|
50
58
|
"patch": "./cordis.patch.yml"
|
|
59
|
+
},
|
|
60
|
+
"client": {
|
|
61
|
+
"platform": "web",
|
|
62
|
+
"inject": [
|
|
63
|
+
"@deepseek-ai/dsh-client-ui-renderer",
|
|
64
|
+
"@deepseek-ai/dsh-client-locale"
|
|
65
|
+
]
|
|
51
66
|
}
|
|
52
67
|
}
|
|
53
68
|
}
|
package/update.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Update check (same pattern as dsh-clear-conversation/update.js): asks the npm registry once per app
|
|
3
|
+
* start for the latest published version. Never throws and never delays a turn; offline means no notice.
|
|
4
|
+
* Needed because dsh 0.2.1 builds have no update check for third-party plugins on the Plugins page.
|
|
5
|
+
* Opt out with the environment variable DSH_CONTEXT_GRAPH_NO_UPDATE_CHECK=1.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export const PACKAGE = 'dsh-context-graph'
|
|
9
|
+
const LATEST_URL = `https://registry.npmjs.org/${PACKAGE}/latest`
|
|
10
|
+
|
|
11
|
+
const parts = (version) => String(version).replace(/^v/, '').split(/[-+]/)[0].split('.').map(Number)
|
|
12
|
+
|
|
13
|
+
/** True when `latest` has a higher major.minor.patch than `current`; prerelease tags are ignored. */
|
|
14
|
+
export function isNewer(latest, current) {
|
|
15
|
+
const a = parts(latest)
|
|
16
|
+
const b = parts(current)
|
|
17
|
+
if (a.some(Number.isNaN) || b.some(Number.isNaN)) return false
|
|
18
|
+
for (let i = 0; i < 3; i++) {
|
|
19
|
+
if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) > (b[i] ?? 0)
|
|
20
|
+
}
|
|
21
|
+
return false
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The latest published version, or undefined when it cannot be read in time. */
|
|
25
|
+
export async function fetchLatestVersion({ fetchImpl = globalThis.fetch, timeoutMs = 5000 } = {}) {
|
|
26
|
+
try {
|
|
27
|
+
const response = await fetchImpl(LATEST_URL, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeoutMs) })
|
|
28
|
+
if (!response.ok) return undefined
|
|
29
|
+
const version = (await response.json())?.version
|
|
30
|
+
return typeof version === 'string' ? version : undefined
|
|
31
|
+
} catch {
|
|
32
|
+
return undefined
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* One line telling the user how to update, or undefined when this copy is current. The exact
|
|
38
|
+
* `name@version` matters: dsh's pnpm holds back very new releases unless the version is named.
|
|
39
|
+
*/
|
|
40
|
+
export function updateNotice(latest, current) {
|
|
41
|
+
if (!latest || !isNewer(latest, current)) return undefined
|
|
42
|
+
return `${PACKAGE} ${latest} is available (you have ${current}). To update: Plugins, open ${PACKAGE}, Uninstall, then Add plugin ${PACKAGE}@${latest} and restart the app.`
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Start the check now; `current()` returns the notice once the answer has arrived. */
|
|
46
|
+
export function startUpdateCheck(version, { env = process.env, ...options } = {}) {
|
|
47
|
+
let notice
|
|
48
|
+
if (!env.DSH_CONTEXT_GRAPH_NO_UPDATE_CHECK) {
|
|
49
|
+
void fetchLatestVersion(options).then((latest) => {
|
|
50
|
+
notice = updateNotice(latest, version)
|
|
51
|
+
})
|
|
52
|
+
}
|
|
53
|
+
return { current: () => notice }
|
|
54
|
+
}
|