dsh-context-graph 0.2.1 → 0.2.3
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 +7 -5
- package/cordis.patch.yml +1 -1
- package/graph.js +41 -11
- package/index.js +421 -384
- package/package.json +54 -53
- package/update.js +54 -0
package/README.md
CHANGED
|
@@ -53,10 +53,12 @@ Command line (use the profile your app runs; the desktop app uses `desktop`):
|
|
|
53
53
|
dsh plugin --profile desktop add dsh-context-graph
|
|
54
54
|
```
|
|
55
55
|
|
|
56
|
-
**Updates.**
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
56
|
+
**Updates.** dsh 0.2.1 desktop builds have no update check for third-party plugins, so the
|
|
57
|
+
plugin checks npm itself once per app start. When a newer version exists, your next chat reply
|
|
58
|
+
ends with one line saying so, and `/context-graph stats` shows it on its first line. To update:
|
|
59
|
+
Plugins, open dsh-context-graph, **Uninstall**, then **Add plugin** `dsh-context-graph@<new version>`
|
|
60
|
+
and restart the app. Name the exact version: dsh's pnpm holds back very new releases otherwise.
|
|
61
|
+
Turn the check off with the environment variable `DSH_CONTEXT_GRAPH_NO_UPDATE_CHECK=1`.
|
|
60
62
|
|
|
61
63
|
Remove with `dsh plugin --profile desktop remove dsh-context-graph`.
|
|
62
64
|
|
|
@@ -85,7 +87,7 @@ Defaults live in [cordis.patch.yml](cordis.patch.yml). A patch replaces the row'
|
|
|
85
87
|
| `maxHits` | `5` | Nodes shown per human turn |
|
|
86
88
|
| `inlineMaxChars` | `1200` | A single dominant hit this short is shown verbatim |
|
|
87
89
|
| `surfaceMaxNodes` | `40` | Nodes listed at the start of a session |
|
|
88
|
-
| `builderMaxTokens` | `
|
|
90
|
+
| `builderMaxTokens` | `8192` | Output cap for the indexing call; thinking models spend part of it reasoning |
|
|
89
91
|
| `provider`, `model` | `''` | Empty: reuse the conversation's routed provider and model |
|
|
90
92
|
| `fold` | `true` | Fold old turns of the current chat into a table of contents |
|
|
91
93
|
| `foldAtTokens` | `24000` | Fold once the foldable part costs this much per request |
|
package/cordis.patch.yml
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
maxHits: 5 # nodes shown per human turn
|
|
11
11
|
inlineMaxChars: 1200 # one dominant hit this short is shown verbatim, no recall needed
|
|
12
12
|
surfaceMaxNodes: 40 # god nodes listed at the start of a session
|
|
13
|
-
builderMaxTokens:
|
|
13
|
+
builderMaxTokens: 8192 # thinking models spend part of this on reasoning
|
|
14
14
|
provider: '' # empty: reuse the conversation's routed provider/model
|
|
15
15
|
model: ''
|
|
16
16
|
fold: true # replace old turns of the current chat with a table of contents
|
package/graph.js
CHANGED
|
@@ -187,18 +187,48 @@ export function builderInstruction(graph) {
|
|
|
187
187
|
].join('\n')
|
|
188
188
|
}
|
|
189
189
|
|
|
190
|
-
/**
|
|
190
|
+
/** Complete top-level `{...}` objects inside the array that opens at `open`; an unfinished last one is dropped. */
|
|
191
|
+
function objectsInArray(text, open) {
|
|
192
|
+
const out = []
|
|
193
|
+
let depth = 0
|
|
194
|
+
let start = -1
|
|
195
|
+
let inString = false
|
|
196
|
+
for (let i = open + 1; i < text.length; i++) {
|
|
197
|
+
const ch = text[i]
|
|
198
|
+
if (inString) {
|
|
199
|
+
if (ch === '\\') i++
|
|
200
|
+
else if (ch === '"') inString = false
|
|
201
|
+
continue
|
|
202
|
+
}
|
|
203
|
+
if (ch === '"') inString = true
|
|
204
|
+
else if (ch === '{' || ch === '[') { if (depth++ === 0 && ch === '{') start = i }
|
|
205
|
+
else if (ch === '}' || ch === ']') {
|
|
206
|
+
if (depth === 0) break
|
|
207
|
+
if (--depth === 0 && ch === '}' && start >= 0) { out.push(text.slice(start, i + 1)); start = -1 }
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return out
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Tolerant extraction of the builder's JSON. Handles code fences, prose around it, `<think>` blocks,
|
|
215
|
+
* trailing commas, and output cut off mid-way (every complete node object is kept).
|
|
216
|
+
* `undefined` when there is no `"nodes"` array at all.
|
|
217
|
+
*/
|
|
191
218
|
export function parseBuilderOutput(text) {
|
|
192
|
-
const
|
|
193
|
-
const
|
|
194
|
-
if (
|
|
195
|
-
const
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
const
|
|
200
|
-
const edges =
|
|
201
|
-
return {
|
|
219
|
+
const clean = String(text ?? '').replace(/<think>[\s\S]*?(?:<\/think>|$)/g, '')
|
|
220
|
+
const at = clean.search(/"nodes"\s*:\s*\[/)
|
|
221
|
+
if (at < 0) return undefined
|
|
222
|
+
const nodes = []
|
|
223
|
+
for (const raw of objectsInArray(clean, clean.indexOf('[', at))) {
|
|
224
|
+
try { nodes.push(JSON.parse(raw.replace(/,\s*([}\]])/g, '$1'))) } catch { /* skip a malformed node */ }
|
|
225
|
+
}
|
|
226
|
+
const edgesAt = clean.search(/"edges"\s*:/)
|
|
227
|
+
const edges = edgesAt < 0 ? [] : [...clean.slice(edgesAt).matchAll(/\[\s*"([^"]+)"\s*,\s*"([^"]+)"\s*,\s*"([^"]+)"\s*\]/g)].map((m) => [m[1], m[2], m[3]])
|
|
228
|
+
return {
|
|
229
|
+
nodes: nodes.filter((n) => n && typeof n.label === 'string' && n.label.trim() && Array.isArray(n.msgs) && n.msgs.length > 0),
|
|
230
|
+
edges
|
|
231
|
+
}
|
|
202
232
|
}
|
|
203
233
|
|
|
204
234
|
/**
|
package/index.js
CHANGED
|
@@ -1,384 +1,421 @@
|
|
|
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
|
-
const
|
|
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
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
} catch {
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
const
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
return { status: '
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
const
|
|
205
|
-
const
|
|
206
|
-
//
|
|
207
|
-
if (
|
|
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
|
-
|
|
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
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
}
|
|
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 turns t1-t${result.turns}: ~${result.before} tokens replaced by a ~${result.after}-token table of contents.` }
|
|
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: `Indexed ${result.nodes} nodes (${result.newNodes} new); graph now ${result.totalNodes} nodes, ${result.edges} edges at ${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
|
+
return { kind: 'success', text: hits.length ? renderHits(graph, hits) : 'No matching nodes.' }
|
|
396
|
+
}
|
|
397
|
+
if (sub !== 'stats') return { kind: 'error', text: 'Usage: /context-graph [stats|build|fold|find <words>]' }
|
|
398
|
+
const m = meter.main
|
|
399
|
+
const cached = m.cacheRead + m.cacheWrite
|
|
400
|
+
const hitRate = m.input + cached > 0 ? Math.round((m.cacheRead / (m.input + cached)) * 100) : 0
|
|
401
|
+
const session = agent.session
|
|
402
|
+
const pending = collectSpan(session.surface.nodes, (seq) => session.eventAt(seq), state(String(session.id)).lastBuiltSeq).userTurns
|
|
403
|
+
return {
|
|
404
|
+
kind: 'success',
|
|
405
|
+
text: [
|
|
406
|
+
`Version ${version}: ${updates.current() ?? 'no newer version found'}`,
|
|
407
|
+
`Graph: ${Object.keys(graph.nodes).length} nodes, ${graph.edges.length} edges (${dirFor(agent)})`,
|
|
408
|
+
`This chat: ${pending} human turns not indexed yet; auto-index at ${cfg.buildEveryTurns}, or run /context-graph build now.`,
|
|
409
|
+
'Counters below are since the app started:',
|
|
410
|
+
`Builds: ${meter.builds}; builder tokens in/out: ${meter.builder.input + meter.builder.cacheRead + meter.builder.cacheWrite}/${meter.builder.output}`,
|
|
411
|
+
`Folds: ${meter.folds}; ~${meter.foldSaved} input tokens removed from every later request`,
|
|
412
|
+
`Injected blocks: ${meter.injected} (~${meter.injectedTokens} tokens); recalls: ${meter.recalls}`,
|
|
413
|
+
`Main requests: ${m.requests}; input ${m.input} uncached + ${m.cacheRead} cache-read + ${m.cacheWrite} cache-write; cache-hit ${hitRate}%`
|
|
414
|
+
].join('\n')
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
})
|
|
418
|
+
}, 'context-graph command')
|
|
419
|
+
}
|
|
420
|
+
})
|
|
421
|
+
}
|
package/package.json
CHANGED
|
@@ -1,53 +1,54 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "dsh-context-graph",
|
|
3
|
-
"version": "0.2.
|
|
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
|
-
"type": "module",
|
|
6
|
-
"main": "index.js",
|
|
7
|
-
"exports": {
|
|
8
|
-
".": "./index.js",
|
|
9
|
-
"./graph": "./graph.js",
|
|
10
|
-
"./package.json": "./package.json"
|
|
11
|
-
},
|
|
12
|
-
"files": [
|
|
13
|
-
"index.js",
|
|
14
|
-
"graph.js",
|
|
15
|
-
"store.js",
|
|
16
|
-
"
|
|
17
|
-
"
|
|
18
|
-
"
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
"
|
|
26
|
-
"deepseek",
|
|
27
|
-
"
|
|
28
|
-
"
|
|
29
|
-
"
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
"
|
|
33
|
-
|
|
34
|
-
"
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
"
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
"
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
"@deepseek-ai/dsh-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "dsh-context-graph",
|
|
3
|
+
"version": "0.2.3",
|
|
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
|
+
"type": "module",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./index.js",
|
|
9
|
+
"./graph": "./graph.js",
|
|
10
|
+
"./package.json": "./package.json"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"index.js",
|
|
14
|
+
"graph.js",
|
|
15
|
+
"store.js",
|
|
16
|
+
"update.js",
|
|
17
|
+
"cordis.patch.yml",
|
|
18
|
+
"README.md",
|
|
19
|
+
"LICENSE"
|
|
20
|
+
],
|
|
21
|
+
"scripts": {
|
|
22
|
+
"test": "node --import ./test/resolve-dsh.mjs --test test/graph.test.js test/fold.test.js test/update.test.js test/plugin.test.js"
|
|
23
|
+
},
|
|
24
|
+
"keywords": [
|
|
25
|
+
"dsh-plugin",
|
|
26
|
+
"deepseek-harness",
|
|
27
|
+
"deepseek",
|
|
28
|
+
"memory",
|
|
29
|
+
"context",
|
|
30
|
+
"knowledge-graph"
|
|
31
|
+
],
|
|
32
|
+
"license": "MIT",
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/William20100221/dsh-context-graph.git"
|
|
36
|
+
},
|
|
37
|
+
"homepage": "https://github.com/William20100221/dsh-context-graph#readme",
|
|
38
|
+
"bugs": {
|
|
39
|
+
"url": "https://github.com/William20100221/dsh-context-graph/issues"
|
|
40
|
+
},
|
|
41
|
+
"engines": {
|
|
42
|
+
"dsh": ">=0.2.1-rc.5 <0.3.0",
|
|
43
|
+
"node": ">=20"
|
|
44
|
+
},
|
|
45
|
+
"peerDependencies": {
|
|
46
|
+
"@deepseek-ai/dsh-llm": ">=0.2.1-rc.5 <0.3.0",
|
|
47
|
+
"@deepseek-ai/dsh-tools": ">=0.2.1-rc.5 <0.3.0"
|
|
48
|
+
},
|
|
49
|
+
"dsh": {
|
|
50
|
+
"bundle": {
|
|
51
|
+
"patch": "./cordis.patch.yml"
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
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
|
+
}
|