dsh-context-graph 0.2.2 → 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.
Files changed (4) hide show
  1. package/README.md +6 -4
  2. package/index.js +421 -396
  3. package/package.json +3 -2
  4. 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.** Installed from npm, the plugin gets dsh's built-in updater: on the Plugins page
57
- press **Refresh**, and when a newer version is published an **Update** button appears on the
58
- plugin. Restart the app after updating. A `github:` install is not eligible for this; remove
59
- it and add `dsh-context-graph` from npm once.
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
 
package/index.js CHANGED
@@ -1,396 +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 { mkdir, stat, writeFile } from 'node:fs/promises'
17
-
18
- import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'
19
- import { defineTool } from '@deepseek-ai/dsh-tools'
20
-
21
- import {
22
- builderInstruction, collectSpan, emptyGraph, estimateTokens, foldKept, matchNodes, mergeDelta, neighbors, onlyFromSession,
23
- parseBuilderOutput, planFold, renderFoldIndex, renderHits, renderSurface, SOURCE_KIND, surfaceNodes, transcriptForBuilder,
24
- turnIndex, turnTranscript
25
- } from './graph.js'
26
- import { appendSource, loadGraph, readSource, saveGraph } from './store.js'
27
-
28
- export const name = 'context-graph'
29
- export const inject = ['tools']
30
-
31
- const PURPOSE = 'context-graph'
32
-
33
- const DEFAULTS = {
34
- dir: '.context-graph',
35
- buildEveryTurns: 4,
36
- buildMinChars: 400,
37
- maxHits: 5,
38
- inlineMaxChars: 1200,
39
- surfaceMaxNodes: 40,
40
- builderMaxTokens: 8192,
41
- provider: '',
42
- model: '',
43
- fold: true,
44
- foldAtTokens: 24000,
45
- keepTurns: 2
46
- }
47
-
48
- const textOf = (content) => (Array.isArray(content) ? content : []).filter((b) => b?.type === 'text').map((b) => b.text).join('\n').trim()
49
-
50
- export function apply(ctx, config = {}) {
51
- const cfg = { ...DEFAULTS, ...config }
52
- const sessions = new Map()
53
- const graphCache = new Map()
54
- const meter = {
55
- main: { requests: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
56
- builder: { requests: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
57
- builds: 0,
58
- folds: 0,
59
- foldSaved: 0,
60
- injected: 0,
61
- injectedTokens: 0,
62
- recalls: 0
63
- }
64
-
65
- const state = (sid) => {
66
- let st = sessions.get(sid)
67
- if (!st) { st = { lastBuiltSeq: -1, building: false, surfaceSent: false }; sessions.set(sid, st) }
68
- return st
69
- }
70
-
71
- function dirFor(agent) {
72
- const base = agent.options?.cwd ?? agent.session.header?.cwd ?? process.cwd()
73
- return isAbsolute(cfg.dir) ? cfg.dir : join(base, cfg.dir)
74
- }
75
-
76
- /** Graph read with an mtime check so other sessions' builds show up without a restart. */
77
- async function getGraph(dir) {
78
- let mtimeMs = 0
79
- try { mtimeMs = (await stat(join(dir, 'graph.json'))).mtimeMs } catch { return emptyGraph() }
80
- const cached = graphCache.get(dir)
81
- if (cached && cached.mtimeMs === mtimeMs) return cached.graph
82
- const graph = await loadGraph(dir)
83
- graphCache.set(dir, { mtimeMs, graph })
84
- return graph
85
- }
86
-
87
- function resolveTarget(agent) {
88
- if (cfg.provider && cfg.model) return { provider: cfg.provider, model: cfg.model }
89
- const routed = agent.session.requestHeader()?.config
90
- if (routed?.provider && routed?.model) return { provider: routed.provider, model: routed.model }
91
- const { provider, model } = agent.options ?? {}
92
- return provider && model ? { provider, model } : undefined
93
- }
94
-
95
- function surfaceAlreadyOnLog(session) {
96
- return session.surface.nodes.some((seq) => {
97
- const event = session.eventAt(seq)
98
- return event?.type === 'user/message' && event.data?.source?.kind === SOURCE_KIND && event.data.source.layer === 'surface'
99
- })
100
- }
101
-
102
- // ---------- builder ----------
103
- const isSubagent = (agent) => agent.options?.origin === 'subagent' || agent.session.header?.origin === 'subagent'
104
-
105
- async function build(agent, { force = false, turn = null } = {}) {
106
- const session = agent.session
107
- const sid = String(session.id)
108
- const st = state(sid)
109
- if (st.building) return { status: 'busy' }
110
- // ponytail: subagent chatter stays out of the project graph; revisit if delegated work holds decisions worth keeping.
111
- if (isSubagent(agent)) return { status: 'skipped', reason: 'subagent session' }
112
- st.building = true
113
- try {
114
- const span = collectSpan(session.surface.nodes, (seq) => session.eventAt(seq), st.lastBuiltSeq)
115
- const chars = span.messages.reduce((n, m) => n + m.text.length, 0)
116
- if (span.messages.length === 0) return { status: 'nothing', reason: 'no new messages since the last build' }
117
- if (!force && (span.userTurns < cfg.buildEveryTurns || chars < cfg.buildMinChars)) {
118
- return { status: 'skipped', reason: `${span.userTurns}/${cfg.buildEveryTurns} human turns, ${chars}/${cfg.buildMinChars} chars` }
119
- }
120
- const llm = ctx.get('llm')
121
- if (!llm) return { status: 'unavailable', reason: 'no llm service in this composition' }
122
- const target = resolveTarget(agent)
123
- if (!target) return { status: 'unavailable', reason: 'no provider/model routed yet' }
124
- const dir = dirFor(agent)
125
- const graph = await loadGraph(dir)
126
- const prompt = `${transcriptForBuilder(span.messages)}\n\n${builderInstruction(graph)}`
127
- const assembler = new BlockAssembler()
128
- for await (const chunk of llm.stream({
129
- provider: target.provider,
130
- model: target.model,
131
- messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
132
- maxTokens: cfg.builderMaxTokens,
133
- sessionId: session.id,
134
- purpose: PURPOSE
135
- })) assembler.push(chunk)
136
- const finish = assembler.finish
137
- if (finish?.kind === 'error' || finish?.kind === 'aborted') throw new Error(finish.failure?.message ?? finish.kind)
138
- const blocks = assembler.blocks()
139
- const answer = textOf(blocks)
140
- // Some thinking models put everything, JSON included, into reasoning blocks.
141
- const reasoning = blocks.filter((b) => b?.type === 'reasoning').map((b) => b.text).join('\n')
142
- const delta = parseBuilderOutput(answer) ?? parseBuilderOutput(reasoning)
143
- if (!delta || (delta.nodes.length === 0 && finish?.kind === 'max-tokens')) {
144
- const saved = join(dir, 'last-builder-output.txt')
145
- await mkdir(dir, { recursive: true })
146
- await writeFile(saved, `finish: ${finish?.kind}\n\n--- answer ---\n${answer}\n\n--- reasoning ---\n${reasoning}\n`, 'utf8')
147
- const why = finish?.kind === 'max-tokens'
148
- ? `the model ran out of output tokens (builderMaxTokens ${cfg.builderMaxTokens}) before finishing`
149
- : 'builder output was not the expected JSON'
150
- return { status: 'failed', reason: `${why}; raw output saved to ${saved}` }
151
- }
152
- // Reversibility rule: a node is written only when it cites text we can store verbatim.
153
- delta.nodes = delta.nodes.filter((n) => n.msgs.some((i) => span.messages[i]))
154
- const now = new Date().toISOString()
155
- const touched = mergeDelta(graph, delta, { session: sid, turn, now })
156
- for (const { id, msgs } of touched) {
157
- const cited = msgs.map((i) => span.messages[i]).filter(Boolean)
158
- if (cited.length > 0) await appendSource(dir, id, { session: sid, turn, at: now, messages: cited })
159
- }
160
- await saveGraph(dir, graph)
161
- st.lastBuiltSeq = span.lastSeq
162
- meter.builds++
163
- return { status: 'built', nodes: touched.length, newNodes: touched.filter((t) => t.isNew).length, totalNodes: Object.keys(graph.nodes).length, edges: graph.edges.length, dir }
164
- } catch (error) {
165
- console.error('context-graph: build failed (non-fatal)', error)
166
- return { status: 'failed', reason: String(error?.message ?? error) }
167
- } finally {
168
- st.building = false
169
- }
170
- }
171
-
172
- ctx.on('agent/turn-stopping', (payload) => {
173
- // Fire and forget: the build must never delay the turn's close.
174
- void build(payload.agent, { turn: payload.turn })
175
- })
176
-
177
- // ---------- fold: replace old turns of this chat with a table of contents ----------
178
- function rangeTokens(session, seqs) {
179
- const wanted = new Set(seqs)
180
- try {
181
- const nodes = ctx.get('tokenMeter')?.measure(session)?.nodes
182
- if (Array.isArray(nodes)) return nodes.filter((n) => wanted.has(n.seq)).reduce((sum, n) => sum + (n.tokens ?? n.heuristicTokens ?? 0), 0)
183
- } catch { /* fall back to the estimate */ }
184
- return seqs.reduce((sum, seq) => sum + estimateTokens(JSON.stringify(session.eventAt(seq)?.data ?? '')), 0)
185
- }
186
-
187
- async function fold(agent, { force = false } = {}) {
188
- const session = agent.session
189
- const sid = String(session.id)
190
- const eventAt = (seq) => session.eventAt(seq)
191
- const plan = planFold(session.surface.nodes, eventAt, { keepTurns: cfg.keepTurns, maxSeq: state(sid).lastBuiltSeq })
192
- if (!plan) return { status: 'skipped', reason: `nothing indexed outside the last ${cfg.keepTurns} turns yet` }
193
- const before = rangeTokens(session, plan.shadowedSeqs)
194
- if (!force && before < cfg.foldAtTokens) return { status: 'skipped', reason: `foldable part is ~${before} tokens, folds at ${cfg.foldAtTokens}` }
195
- const turns = turnIndex(eventAt, plan.endSeq)
196
- const index = renderFoldIndex(await getGraph(dirFor(agent)), sid, turns, { maxNodes: cfg.surfaceMaxNodes })
197
- const kept = foldKept(plan.shadowedSeqs, eventAt)
198
- const after = estimateTokens([index, ...kept.blocks.map((b) => b.text ?? '')].join('\n'))
199
- // Never-worse gate: a fold must at least halve what it replaces, or it is not worth breaking the cache.
200
- if (after * 2 > before) return { status: 'skipped', reason: `table of contents (~${after}) is not under half of the ~${before} tokens it would replace` }
201
- const message = createUserMessage({
202
- content: [{ type: 'text', text: index }, ...kept.blocks],
203
- source: { kind: SOURCE_KIND, fold: true, keptKinds: kept.kinds, foldedTurns: turns.length, foldedTokens: before }
204
- })
205
- session.append('user/message', message, {
206
- surfaceOp: { op: 'replace', startSeq: plan.startSeq, endSeq: plan.endSeq },
207
- sourceEventSeqs: [...plan.shadowedSeqs]
208
- })
209
- meter.folds++
210
- meter.foldSaved += before - after
211
- return { status: 'folded', turns: turns.length, before, after }
212
- }
213
-
214
- // ---------- matcher ----------
215
- ctx.on('agent/pre-step', async (payload, next) => {
216
- const agent = payload.agent
217
- const prompt = payload.messages.filter((m) => m.source?.kind === 'user').map((m) => textOf(m.content)).join('\n')
218
- // Fold only at the start of a human turn: the previous turn is closed, so no tool call is open.
219
- if (cfg.fold && prompt && !isSubagent(agent)) {
220
- try { await fold(agent) } catch (error) { console.error('context-graph: fold failed (non-fatal)', error) }
221
- }
222
- const decision = await next()
223
- if (decision.kind !== 'enter') return decision
224
- try {
225
- if (isSubagent(agent) || !prompt) return decision
226
- const dir = dirFor(agent)
227
- const graph = await getGraph(dir)
228
- if (Object.keys(graph.nodes).length === 0) return decision
229
- const sid = String(agent.session.id)
230
- const st = state(sid)
231
- const sessionCompacted = agent.session.surface.replaceGeneration > 0
232
- const parts = []
233
- let layer
234
- if (!st.surfaceSent) {
235
- st.surfaceSent = true
236
- // Nodes that only come from this very session are still in its context: no need to repeat them.
237
- const ids = surfaceNodes(graph, cfg.surfaceMaxNodes).filter((id) => sessionCompacted || !onlyFromSession(graph.nodes[id], sid))
238
- if (ids.length > 0 && !surfaceAlreadyOnLog(agent.session)) {
239
- parts.push(renderSurface(graph, ids))
240
- layer = 'surface'
241
- }
242
- }
243
- const hits = matchNodes(graph, prompt, { max: cfg.maxHits, session: sid, sessionCompacted })
244
- let inline
245
- if (hits.length === 1 || (hits.length > 1 && hits[0].score >= 2 * hits[1].score)) {
246
- const text = await readSource(dir, hits[0].id)
247
- if (text && text.length <= cfg.inlineMaxChars) inline = { id: hits[0].id, text }
248
- }
249
- const block = renderHits(graph, hits, { inline })
250
- if (block) parts.push(block)
251
- if (parts.length === 0) return decision
252
- const text = parts.join('\n\n')
253
- meter.injected++
254
- meter.injectedTokens += estimateTokens(text)
255
- const message = createUserMessage({ content: [{ type: 'text', text }], source: layer ? { kind: SOURCE_KIND, layer } : { kind: SOURCE_KIND } })
256
- return { ...decision, messages: [...decision.messages, message] }
257
- } catch (error) {
258
- console.error('context-graph: matcher failed (non-fatal)', error)
259
- return decision
260
- }
261
- })
262
-
263
- // ---------- meter ----------
264
- ctx.on('llm/stream', (options, next) => {
265
- const inner = next()
266
- const bucket = options.purpose === PURPOSE ? meter.builder : meter.main
267
- async function* tracked() {
268
- try {
269
- for await (const chunk of inner) {
270
- if (chunk?.type === 'usage' && chunk.usage) {
271
- bucket.input += chunk.usage.inputTokens ?? 0
272
- bucket.cacheRead += chunk.usage.cacheReadTokens ?? 0
273
- bucket.cacheWrite += chunk.usage.cacheWriteTokens ?? 0
274
- bucket.output += chunk.usage.outputTokens ?? 0
275
- }
276
- yield chunk
277
- }
278
- } finally {
279
- bucket.requests++
280
- }
281
- }
282
- return tracked()
283
- })
284
-
285
- // ---------- recall tool ----------
286
- ctx.tools.register(defineTool({
287
- name: 'recall',
288
- description: [
289
- '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.',
290
- 'Call it when a gist is relevant but not precise enough to answer. Never invent an id; only use ids you were shown.'
291
- ].join(' '),
292
- parameters: {
293
- id: { type: 'string', required: true, description: 'Topic id such as n17, or turn id such as t7.' },
294
- depth: { type: 'integer', description: '0 (default): this node only. 1: also include each neighbour\'s gist.' }
295
- },
296
- output: {
297
- schema: {
298
- type: 'object',
299
- additionalProperties: false,
300
- properties: {
301
- status: { type: 'string', enum: ['ok', 'unknown'], required: true },
302
- text: { type: 'string', required: true }
303
- }
304
- },
305
- render: (_args, value) => [{ type: 'text', text: value.text }]
306
- },
307
- async execute(args, exec) {
308
- const agent = exec.agent
309
- if (!agent?.session) return { status: 'unknown', text: 'recall is unavailable: no session attached to this call.' }
310
- const id = String(args.id ?? '').trim()
311
- const turn = /^t(\d+)$/.exec(id)
312
- if (turn) {
313
- const text = turnTranscript((seq) => agent.session.eventAt(seq), Number(turn[1]))
314
- if (text === undefined) return { status: 'unknown', text: `No turn ${id} in this conversation.` }
315
- meter.recalls++
316
- return { status: 'ok', text: `# ${id} (verbatim)\n\n${text}` }
317
- }
318
- const dir = dirFor(agent)
319
- const graph = await getGraph(dir)
320
- const node = graph.nodes[id]
321
- if (!node) return { status: 'unknown', text: `No node "${id}" in this project's context graph. Only use ids shown in a [context-graph] block.` }
322
- meter.recalls++
323
- node.hits = (node.hits ?? 0) + 1
324
- saveGraph(dir, graph).catch((error) => console.error('context-graph: hit count save failed', error))
325
- const lines = [`# ${id} ${node.label}`, `${node.kind}. ${node.gist}`, '']
326
- const source = await readSource(dir, id)
327
- lines.push(source ? source.trim() : '(no verbatim source stored for this node)')
328
- const links = neighbors(graph, id)
329
- if (links.length > 0) {
330
- lines.push('', 'Neighbours:')
331
- for (const link of links) {
332
- const other = graph.nodes[link.id]
333
- const arrow = link.direction === 'out' ? `${id} ${link.relation} ${link.id}` : `${link.id} ${link.relation} ${id}`
334
- lines.push(`- ${arrow}: ${other.label}${args.depth >= 1 ? ` — ${other.gist}` : ''}`)
335
- }
336
- }
337
- return { status: 'ok', text: lines.join('\n') }
338
- }
339
- }))
340
-
341
- // ---------- /context-graph command (nested: only where a human-command surface exists) ----------
342
- ctx.plugin({
343
- name: 'context-graph-command',
344
- inject: ['commands'],
345
- apply(cmdCtx) {
346
- cmdCtx.effect(function* () {
347
- yield cmdCtx.commands.register({
348
- name: 'context-graph',
349
- description: 'Project memory graph: /context-graph [stats|build|fold|find <words>]',
350
- // Without `input`, dsh clients run the bare name and send any typed arguments to the model as chat.
351
- input: { hint: '[stats|build|fold|find <words>]' },
352
- async handler(invocation) {
353
- const [sub = 'stats', ...rest] = invocation.rawInput.trim().split(/\s+/).filter(Boolean)
354
- const agent = invocation.agent
355
- if (sub === 'fold') {
356
- const result = await agent.runMaintenance(async () => {
357
- await build(agent, { force: true })
358
- return fold(agent, { force: true })
359
- })
360
- if (result.status !== 'folded') return { kind: 'error', text: `Not folded: ${result.reason}` }
361
- return { kind: 'success', text: `Folded turns t1-t${result.turns}: ~${result.before} tokens replaced by a ~${result.after}-token table of contents.` }
362
- }
363
- if (sub === 'build') {
364
- const result = await agent.runMaintenance(() => build(agent, { force: true }))
365
- if (result.status !== 'built') return { kind: 'error', text: `Build ${result.status}: ${result.reason ?? ''}`.trim() }
366
- return { kind: 'success', text: `Indexed ${result.nodes} nodes (${result.newNodes} new); graph now ${result.totalNodes} nodes, ${result.edges} edges at ${result.dir}` }
367
- }
368
- const graph = await getGraph(dirFor(agent))
369
- if (sub === 'find') {
370
- const hits = matchNodes(graph, rest.join(' '), { max: cfg.maxHits })
371
- return { kind: 'success', text: hits.length ? renderHits(graph, hits) : 'No matching nodes.' }
372
- }
373
- if (sub !== 'stats') return { kind: 'error', text: 'Usage: /context-graph [stats|build|fold|find <words>]' }
374
- const m = meter.main
375
- const cached = m.cacheRead + m.cacheWrite
376
- const hitRate = m.input + cached > 0 ? Math.round((m.cacheRead / (m.input + cached)) * 100) : 0
377
- const session = agent.session
378
- const pending = collectSpan(session.surface.nodes, (seq) => session.eventAt(seq), state(String(session.id)).lastBuiltSeq).userTurns
379
- return {
380
- kind: 'success',
381
- text: [
382
- `Graph: ${Object.keys(graph.nodes).length} nodes, ${graph.edges.length} edges (${dirFor(agent)})`,
383
- `This chat: ${pending} human turns not indexed yet; auto-index at ${cfg.buildEveryTurns}, or run /context-graph build now.`,
384
- 'Counters below are since the app started:',
385
- `Builds: ${meter.builds}; builder tokens in/out: ${meter.builder.input + meter.builder.cacheRead + meter.builder.cacheWrite}/${meter.builder.output}`,
386
- `Folds: ${meter.folds}; ~${meter.foldSaved} input tokens removed from every later request`,
387
- `Injected blocks: ${meter.injected} (~${meter.injectedTokens} tokens); recalls: ${meter.recalls}`,
388
- `Main requests: ${m.requests}; input ${m.input} uncached + ${m.cacheRead} cache-read + ${m.cacheWrite} cache-write; cache-hit ${hitRate}%`
389
- ].join('\n')
390
- }
391
- }
392
- })
393
- }, 'context-graph command')
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 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,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-context-graph",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
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
5
  "type": "module",
6
6
  "main": "index.js",
@@ -13,12 +13,13 @@
13
13
  "index.js",
14
14
  "graph.js",
15
15
  "store.js",
16
+ "update.js",
16
17
  "cordis.patch.yml",
17
18
  "README.md",
18
19
  "LICENSE"
19
20
  ],
20
21
  "scripts": {
21
- "test": "node --import ./test/resolve-dsh.mjs --test test/graph.test.js test/fold.test.js test/plugin.test.js"
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"
22
23
  },
23
24
  "keywords": [
24
25
  "dsh-plugin",
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
+ }