dsh-context-graph 0.6.2 → 0.11.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/CHANGELOG.md +563 -0
- package/README.md +252 -97
- package/README.zh.md +82 -32
- package/cordis.patch.yml +10 -6
- package/index.js +7 -432
- package/package.json +11 -12
- package/src/client/client.js +880 -0
- package/src/core/builder.js +210 -0
- package/src/core/chat.js +34 -0
- package/src/core/graph.js +134 -0
- package/src/core/index.js +14 -0
- package/src/core/ledger.js +108 -0
- package/src/core/match.js +377 -0
- package/src/core/render.js +195 -0
- package/src/core/session.js +446 -0
- package/src/core/text.js +220 -0
- package/src/core/time.js +147 -0
- package/src/core/tree.js +39 -0
- package/src/host/builder.js +416 -0
- package/src/host/command.js +155 -0
- package/src/host/config.js +50 -0
- package/src/host/memory.js +175 -0
- package/src/host/meter.js +75 -0
- package/src/host/page.js +186 -0
- package/src/host/plugin.js +46 -0
- package/src/host/recall.js +227 -0
- package/src/host/runtime.js +599 -0
- package/src/store/chats.js +236 -0
- package/src/store/files.js +181 -0
- package/src/store/ledger.js +65 -0
- package/src/store/messages.js +88 -0
- package/src/store/migrate.js +143 -0
- package/graph.js +0 -496
- package/lib/client.js +0 -126
- package/store.js +0 -81
- /package/{update.js → src/host/update.js} +0 -0
package/index.js
CHANGED
|
@@ -1,434 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* dsh
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* - `agent/pre-step`: on a human turn, match the prompt against the other shared chats (all chats unless unshared) of this
|
|
9
|
-
* workspace (a named day is searched first) and append one short `[context-graph]` block at the
|
|
10
|
-
* end of the request, so the provider's prefix cache survives. On a chat's first message, one block lists
|
|
11
|
-
* the shared chats, newest first.
|
|
12
|
-
* - Tool `recall`: a topic (c3n12), a chat (c3), a day (2026-11-01) or a turn of this chat (t7).
|
|
13
|
-
* - `llm/stream`: meters main vs builder tokens and cache reads for `/context-graph stats`.
|
|
14
|
-
* Nothing is merged between chats; sharing is a flag on the chat. Stock compaction is untouched.
|
|
2
|
+
* Package entry for dsh: the plugin's name, injections and apply(). The code lives in src/:
|
|
3
|
+
* src/core pure logic (text, graph, matching, time, rendering, builder prompt, session events)
|
|
4
|
+
* src/store files on disk under <workspace>/.context-graph
|
|
5
|
+
* src/host dsh wiring (builder, memory injection, recall tool, command, meter, update check)
|
|
6
|
+
* src/client the browser module (command card)
|
|
7
|
+
* See docs/architecture.md.
|
|
15
8
|
*/
|
|
16
|
-
|
|
17
|
-
import { isAbsolute, join } from 'node:path'
|
|
18
|
-
import { readFileSync } from 'node:fs'
|
|
19
|
-
import { mkdir, writeFile } from 'node:fs/promises'
|
|
20
|
-
|
|
21
|
-
import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
22
|
-
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
23
|
-
|
|
24
|
-
import {
|
|
25
|
-
builderInstruction, collectSpan, estimateTokens, matchAcross, memoryOn, mergeDelta, sharedOn, neighbors, parseBuilderOutput, parseTimeRange,
|
|
26
|
-
renderChatIndex, renderChats, renderHits, renderMap, renderRange, shownContext, SOURCE_KIND, tailWithin, titleOf, transcriptForBuilder, turnTranscript
|
|
27
|
-
} from './graph.js'
|
|
28
|
-
import { appendSource, chatDir, ensureMeta, listChats, loadGraph, loadMeta, readSource, saveGraph, saveMeta } from './store.js'
|
|
29
|
-
import { startUpdateCheck } from './update.js'
|
|
30
|
-
|
|
31
|
-
export const name = 'context-graph'
|
|
32
|
-
export const inject = ['tools']
|
|
33
|
-
|
|
34
|
-
const PURPOSE = 'context-graph'
|
|
35
|
-
const USAGE = '[on|off|share|unshare|stats|build|map|find <words>]'
|
|
36
|
-
const { version } = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
|
|
37
|
-
|
|
38
|
-
const DEFAULTS = {
|
|
39
|
-
dir: '.context-graph',
|
|
40
|
-
buildEveryTurns: 4,
|
|
41
|
-
buildMinChars: 400,
|
|
42
|
-
maxHits: 5,
|
|
43
|
-
inlineMaxChars: 1200,
|
|
44
|
-
surfaceMaxChats: 20,
|
|
45
|
-
builderMaxTokens: 8192,
|
|
46
|
-
builderMaxInputChars: 60000,
|
|
47
|
-
rangeMaxChats: 3,
|
|
48
|
-
rangeMaxTopics: 3,
|
|
49
|
-
provider: '',
|
|
50
|
-
model: ''
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
const textOf = (content) => (Array.isArray(content) ? content : []).filter((b) => b?.type === 'text').map((b) => b.text).join('\n').trim()
|
|
54
|
-
|
|
55
|
-
export function apply(ctx, config = {}) {
|
|
56
|
-
const { _updates, ...rest } = config
|
|
57
|
-
const cfg = { ...DEFAULTS, ...rest }
|
|
58
|
-
// `_updates` lets tests stand in for the network check.
|
|
59
|
-
const updates = _updates ?? startUpdateCheck(version)
|
|
60
|
-
let noticeShown = false
|
|
61
|
-
const sessions = new Map()
|
|
62
|
-
const meter = {
|
|
63
|
-
main: { requests: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
|
|
64
|
-
builder: { requests: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
|
|
65
|
-
builds: 0,
|
|
66
|
-
injected: 0,
|
|
67
|
-
injectedTokens: 0,
|
|
68
|
-
recalls: 0
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
const state = (sid) => {
|
|
72
|
-
let st = sessions.get(sid)
|
|
73
|
-
// retryAt: after a failed build, wait for this many new human turns before trying again (#3).
|
|
74
|
-
if (!st) { st = { building: false, announce: true, retryAt: 0 }; sessions.set(sid, st) }
|
|
75
|
-
return st
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
const sidOf = (agent) => String(agent.session.id)
|
|
79
|
-
const isSubagent = (agent) => agent.options?.origin === 'subagent' || agent.session.header?.origin === 'subagent'
|
|
80
|
-
|
|
81
|
-
function dirFor(agent) {
|
|
82
|
-
const base = agent.options?.cwd ?? agent.session.header?.cwd ?? process.cwd()
|
|
83
|
-
return isAbsolute(cfg.dir) ? cfg.dir : join(base, cfg.dir)
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
const metaFor = (agent) => loadMeta(dirFor(agent), sidOf(agent))
|
|
87
|
-
|
|
88
|
-
async function setFlags(agent, flags) {
|
|
89
|
-
const dir = dirFor(agent)
|
|
90
|
-
const session = agent.session
|
|
91
|
-
const now = new Date().toISOString()
|
|
92
|
-
const meta = await ensureMeta(dir, sidOf(agent), { title: titleOf((seq) => session.eventAt(seq)), workspace: dir, now })
|
|
93
|
-
Object.assign(meta, flags, { lastActiveAt: now })
|
|
94
|
-
await saveMeta(dir, sidOf(agent), meta)
|
|
95
|
-
return meta
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
/** Own chat plus every shared chat of the workspace, graphs loaded. ponytail: re-read per turn; cache by mtime if a workspace grows large. */
|
|
99
|
-
async function loadViews(agent) {
|
|
100
|
-
const dir = dirFor(agent)
|
|
101
|
-
const sid = sidOf(agent)
|
|
102
|
-
const views = []
|
|
103
|
-
for (const { sid: other, meta } of await listChats(dir)) {
|
|
104
|
-
const own = other === sid
|
|
105
|
-
if (!own && !sharedOn(meta)) continue
|
|
106
|
-
views.push({ sid: other, cid: meta.cid, meta, own, graph: await loadGraph(chatDir(dir, other)) })
|
|
107
|
-
}
|
|
108
|
-
return views
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
function resolveTarget(agent) {
|
|
112
|
-
if (cfg.provider && cfg.model) return { provider: cfg.provider, model: cfg.model }
|
|
113
|
-
const routed = agent.session.requestHeader()?.config
|
|
114
|
-
if (routed?.provider && routed?.model) return { provider: routed.provider, model: routed.model }
|
|
115
|
-
const { provider, model } = agent.options ?? {}
|
|
116
|
-
return provider && model ? { provider, model } : undefined
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// ---------- builder ----------
|
|
120
|
-
async function build(agent, { force = false, turn = null } = {}) {
|
|
121
|
-
const session = agent.session
|
|
122
|
-
const sid = sidOf(agent)
|
|
123
|
-
const st = state(sid)
|
|
124
|
-
if (st.building) return { status: 'busy' }
|
|
125
|
-
// ponytail: subagent chatter stays out of the graph; revisit if delegated work holds decisions worth keeping.
|
|
126
|
-
if (isSubagent(agent)) return { status: 'skipped', reason: 'subagent session' }
|
|
127
|
-
st.building = true
|
|
128
|
-
let span
|
|
129
|
-
const failed = (reason) => {
|
|
130
|
-
if (span) st.retryAt = span.userTurns + cfg.buildEveryTurns
|
|
131
|
-
return { status: 'failed', reason }
|
|
132
|
-
}
|
|
133
|
-
try {
|
|
134
|
-
let meta = await metaFor(agent)
|
|
135
|
-
if (!memoryOn(meta)) return { status: 'off', reason: 'memory is off for this chat; /context-graph on resumes it' }
|
|
136
|
-
// A chat that never ran a command has no folder yet; give it one so it gets a chat number (#1).
|
|
137
|
-
if (!meta) meta = await setFlags(agent, {})
|
|
138
|
-
// The index position is kept in meta.json so an app restart does not index the chat again (#2).
|
|
139
|
-
span = collectSpan(session.surface.nodes, (seq) => session.eventAt(seq), meta.builtSeq ?? -1)
|
|
140
|
-
const chars = span.messages.reduce((n, m) => n + m.text.length, 0)
|
|
141
|
-
if (span.messages.length === 0) return { status: 'nothing', reason: 'no new messages since the last build' }
|
|
142
|
-
const needTurns = Math.max(cfg.buildEveryTurns, st.retryAt)
|
|
143
|
-
if (!force && (span.userTurns < needTurns || chars < cfg.buildMinChars)) {
|
|
144
|
-
return { status: 'skipped', reason: `${span.userTurns}/${needTurns} human turns, ${chars}/${cfg.buildMinChars} chars` }
|
|
145
|
-
}
|
|
146
|
-
// A long chat indexed for the first time keeps the call small: only its newest messages are read (#4).
|
|
147
|
-
const messages = tailWithin(span.messages, cfg.builderMaxInputChars)
|
|
148
|
-
const llm = ctx.get('llm')
|
|
149
|
-
if (!llm) return { status: 'unavailable', reason: 'no llm service in this composition' }
|
|
150
|
-
const target = resolveTarget(agent)
|
|
151
|
-
if (!target) return { status: 'unavailable', reason: 'no provider/model routed yet' }
|
|
152
|
-
const chat = chatDir(dirFor(agent), sid)
|
|
153
|
-
const graph = await loadGraph(chat)
|
|
154
|
-
const prompt = `${transcriptForBuilder(messages)}\n\n${builderInstruction(graph)}`
|
|
155
|
-
const assembler = new BlockAssembler()
|
|
156
|
-
for await (const chunk of llm.stream({
|
|
157
|
-
provider: target.provider,
|
|
158
|
-
model: target.model,
|
|
159
|
-
messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
|
|
160
|
-
maxTokens: cfg.builderMaxTokens,
|
|
161
|
-
sessionId: session.id,
|
|
162
|
-
purpose: PURPOSE
|
|
163
|
-
})) assembler.push(chunk)
|
|
164
|
-
const finish = assembler.finish
|
|
165
|
-
if (finish?.kind === 'error' || finish?.kind === 'aborted') throw new Error(finish.failure?.message ?? finish.kind)
|
|
166
|
-
const blocks = assembler.blocks()
|
|
167
|
-
const answer = textOf(blocks)
|
|
168
|
-
// Some thinking models put everything, JSON included, into reasoning blocks.
|
|
169
|
-
const reasoning = blocks.filter((b) => b?.type === 'reasoning').map((b) => b.text).join('\n')
|
|
170
|
-
const delta = parseBuilderOutput(answer) ?? parseBuilderOutput(reasoning)
|
|
171
|
-
if (!delta || (delta.nodes.length === 0 && finish?.kind === 'max-tokens')) {
|
|
172
|
-
const saved = join(chat, 'last-builder-output.txt')
|
|
173
|
-
await mkdir(chat, { recursive: true })
|
|
174
|
-
await writeFile(saved, `finish: ${finish?.kind}\n\n--- answer ---\n${answer}\n\n--- reasoning ---\n${reasoning}\n`, 'utf8')
|
|
175
|
-
const why = finish?.kind === 'max-tokens'
|
|
176
|
-
? `the model ran out of output tokens (builderMaxTokens ${cfg.builderMaxTokens}) before finishing`
|
|
177
|
-
: 'builder output was not the expected JSON'
|
|
178
|
-
return failed(`${why}; raw output saved to ${saved}`)
|
|
179
|
-
}
|
|
180
|
-
// Reversibility rule: a node is written only when it cites text we can store verbatim.
|
|
181
|
-
delta.nodes = delta.nodes.filter((n) => n.msgs.some((i) => messages[i]))
|
|
182
|
-
const now = new Date().toISOString()
|
|
183
|
-
const touched = mergeDelta(graph, delta, { session: sid, turn, now })
|
|
184
|
-
for (const { id, msgs } of touched) {
|
|
185
|
-
const cited = msgs.map((i) => messages[i]).filter(Boolean)
|
|
186
|
-
if (cited.length > 0) await appendSource(chat, id, { session: sid, turn, at: now, messages: cited })
|
|
187
|
-
}
|
|
188
|
-
await saveGraph(chat, graph)
|
|
189
|
-
// Re-read: a share/off command may have changed the flags while the model was answering.
|
|
190
|
-
const latest = (await metaFor(agent)) ?? meta
|
|
191
|
-
await saveMeta(dirFor(agent), sid, { ...latest, title: latest.title ?? titleOf((seq) => session.eventAt(seq)), lastActiveAt: now, turns: (latest.turns ?? 0) + span.userTurns, builtSeq: span.lastSeq })
|
|
192
|
-
st.retryAt = 0
|
|
193
|
-
meter.builds++
|
|
194
|
-
return { status: 'built', nodes: touched.length, newNodes: touched.filter((t) => t.isNew).length, totalNodes: Object.keys(graph.nodes).length, edges: graph.edges.length, dir: chat }
|
|
195
|
-
} catch (error) {
|
|
196
|
-
console.error('context-graph: build failed (non-fatal)', error)
|
|
197
|
-
return failed(String(error?.message ?? error))
|
|
198
|
-
} finally {
|
|
199
|
-
st.building = false
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
ctx.on('agent/turn-stopping', (payload) => {
|
|
204
|
-
// Fire and forget: the build must never delay the turn's close.
|
|
205
|
-
void build(payload.agent, { turn: payload.turn })
|
|
206
|
-
})
|
|
207
|
-
|
|
208
|
-
// ---------- matcher ----------
|
|
209
|
-
ctx.on('agent/pre-step', async (payload, next) => {
|
|
210
|
-
const agent = payload.agent
|
|
211
|
-
const prompt = payload.messages.filter((m) => m.source?.kind === 'user').map((m) => textOf(m.content)).join('\n')
|
|
212
|
-
const decision = await next()
|
|
213
|
-
if (decision.kind !== 'enter') return decision
|
|
214
|
-
const result = await addMemory(agent, prompt, decision)
|
|
215
|
-
return prompt && !isSubagent(agent) ? addUpdateNotice(result) : result
|
|
216
|
-
})
|
|
217
|
-
|
|
218
|
-
/** Once per app start, ask the model to pass an available update on to the user. */
|
|
219
|
-
function addUpdateNotice(decision) {
|
|
220
|
-
const notice = updates.current()
|
|
221
|
-
if (!notice || noticeShown) return decision
|
|
222
|
-
noticeShown = true
|
|
223
|
-
const message = createUserMessage({
|
|
224
|
-
content: [{ type: 'text', text: `[${SOURCE_KIND}] ${notice} At the end of your reply, tell the user this in one short line.` }],
|
|
225
|
-
source: { kind: SOURCE_KIND, notice: true }
|
|
226
|
-
})
|
|
227
|
-
return { ...decision, messages: [...decision.messages, message] }
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
async function addMemory(agent, prompt, decision) {
|
|
231
|
-
try {
|
|
232
|
-
if (isSubagent(agent) || !prompt) return decision
|
|
233
|
-
if (!memoryOn(await metaFor(agent))) return decision
|
|
234
|
-
const st = state(sidOf(agent))
|
|
235
|
-
const views = await loadViews(agent)
|
|
236
|
-
const parts = []
|
|
237
|
-
let layer
|
|
238
|
-
if (st.announce) {
|
|
239
|
-
st.announce = false
|
|
240
|
-
const list = renderChats(views, { max: cfg.surfaceMaxChats })
|
|
241
|
-
if (list) { parts.push(list); layer = 'surface' }
|
|
242
|
-
}
|
|
243
|
-
const range = parseTimeRange(prompt)
|
|
244
|
-
// Topics already sent in this chat are still in its context; do not send them again (#5).
|
|
245
|
-
const shown = shownContext(agent.session.surface.nodes, (seq) => agent.session.eventAt(seq))
|
|
246
|
-
const { hits, slice } = matchAcross(views, prompt, { max: cfg.maxHits, range, skip: shown.ids })
|
|
247
|
-
if (hits.length === 0 && range) {
|
|
248
|
-
// Sent with every message that names a time, so kept small; recall("YYYY-MM-DD") gives the full day.
|
|
249
|
-
const block = renderRange(views.filter((v) => !v.own), range, { maxChats: cfg.rangeMaxChats, maxTopics: cfg.rangeMaxTopics })
|
|
250
|
-
const ids = block.match(/\bc\d+n\d+\b/g) ?? []
|
|
251
|
-
const seen = shown.texts.has(block) || (ids.length > 0 && ids.every((id) => shown.ids.has(id)))
|
|
252
|
-
if (!seen) parts.push(block)
|
|
253
|
-
} else {
|
|
254
|
-
let inline
|
|
255
|
-
if (hits.length === 1 || (hits.length > 1 && hits[0].score >= 2 * hits[1].score)) {
|
|
256
|
-
const top = hits[0]
|
|
257
|
-
const text = await readSource(chatDir(dirFor(agent), top.view.sid), top.id.slice(top.id.indexOf('n')))
|
|
258
|
-
if (text && text.length <= cfg.inlineMaxChars) inline = { id: top.id, text }
|
|
259
|
-
}
|
|
260
|
-
const block = renderHits(hits, { inline, slice })
|
|
261
|
-
if (block) parts.push(block)
|
|
262
|
-
}
|
|
263
|
-
if (parts.length === 0) return decision
|
|
264
|
-
const text = parts.join('\n\n')
|
|
265
|
-
meter.injected++
|
|
266
|
-
meter.injectedTokens += estimateTokens(text)
|
|
267
|
-
const message = createUserMessage({ content: [{ type: 'text', text }], source: layer ? { kind: SOURCE_KIND, layer } : { kind: SOURCE_KIND } })
|
|
268
|
-
return { ...decision, messages: [...decision.messages, message] }
|
|
269
|
-
} catch (error) {
|
|
270
|
-
console.error('context-graph: matcher failed (non-fatal)', error)
|
|
271
|
-
return decision
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
// ---------- meter ----------
|
|
276
|
-
ctx.on('llm/stream', (options, next) => {
|
|
277
|
-
const inner = next()
|
|
278
|
-
const bucket = options.purpose === PURPOSE ? meter.builder : meter.main
|
|
279
|
-
async function* tracked() {
|
|
280
|
-
try {
|
|
281
|
-
for await (const chunk of inner) {
|
|
282
|
-
if (chunk?.type === 'usage' && chunk.usage) {
|
|
283
|
-
bucket.input += chunk.usage.inputTokens ?? 0
|
|
284
|
-
bucket.cacheRead += chunk.usage.cacheReadTokens ?? 0
|
|
285
|
-
bucket.cacheWrite += chunk.usage.cacheWriteTokens ?? 0
|
|
286
|
-
bucket.output += chunk.usage.outputTokens ?? 0
|
|
287
|
-
}
|
|
288
|
-
yield chunk
|
|
289
|
-
}
|
|
290
|
-
} finally {
|
|
291
|
-
bucket.requests++
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
return tracked()
|
|
295
|
-
})
|
|
296
|
-
|
|
297
|
-
// ---------- recall tool ----------
|
|
298
|
-
ctx.tools.register(defineTool({
|
|
299
|
-
name: 'recall',
|
|
300
|
-
description: [
|
|
301
|
-
'Fetch the exact text behind an id shown in a [context-graph] block. A topic id (c3n12) returns its verbatim source and linked topics;',
|
|
302
|
-
'a chat id (c3) returns that chat\'s topics; a day (2026-11-01) returns every chat and topic from that day; a turn id (t7) returns turn 7 of this chat word for word.',
|
|
303
|
-
'Call it when a gist is relevant but not precise enough to answer. Never invent an id; only use ids you were shown.'
|
|
304
|
-
].join(' '),
|
|
305
|
-
parameters: {
|
|
306
|
-
id: { type: 'string', required: true, description: 'c3n12 (topic), c3 (chat), 2026-11-01 (day) or t7 (turn of this chat).' },
|
|
307
|
-
depth: { type: 'integer', description: '0 (default): this topic only. 1: also include each linked topic\'s gist.' }
|
|
308
|
-
},
|
|
309
|
-
output: {
|
|
310
|
-
schema: {
|
|
311
|
-
type: 'object',
|
|
312
|
-
additionalProperties: false,
|
|
313
|
-
properties: {
|
|
314
|
-
status: { type: 'string', enum: ['ok', 'unknown'], required: true },
|
|
315
|
-
text: { type: 'string', required: true }
|
|
316
|
-
}
|
|
317
|
-
},
|
|
318
|
-
render: (_args, value) => [{ type: 'text', text: value.text }]
|
|
319
|
-
},
|
|
320
|
-
async execute(args, exec) {
|
|
321
|
-
const agent = exec.agent
|
|
322
|
-
if (!agent?.session) return { status: 'unknown', text: 'recall is unavailable: no session attached to this call.' }
|
|
323
|
-
const id = String(args.id ?? '').trim()
|
|
324
|
-
const ok = (text) => { meter.recalls++; return { status: 'ok', text } }
|
|
325
|
-
const turn = /^t(\d+)$/.exec(id)
|
|
326
|
-
if (turn) {
|
|
327
|
-
const text = turnTranscript((seq) => agent.session.eventAt(seq), Number(turn[1]))
|
|
328
|
-
return text === undefined ? { status: 'unknown', text: `No turn ${id} in this chat.` } : ok(`# ${id} (verbatim)\n\n${text}`)
|
|
329
|
-
}
|
|
330
|
-
const views = await loadViews(agent)
|
|
331
|
-
if (/^\d{4}-\d{2}-\d{2}$/.test(id)) return ok(renderRange(views.filter((v) => !v.own), parseTimeRange(id)))
|
|
332
|
-
const m = /^(?:c(\d+))?(n\d+)?$/.exec(id)
|
|
333
|
-
if (!m || (!m[1] && !m[2])) return { status: 'unknown', text: `"${id}" is not an id. Use c3n12, c3, 2026-11-01 or t7, and only ids you were shown.` }
|
|
334
|
-
const view = m[1] ? views.find((v) => String(v.cid) === m[1]) : views.find((v) => v.own)
|
|
335
|
-
if (!view) return { status: 'unknown', text: m[1] ? `No chat c${m[1]} shared in this workspace.` : 'This chat has no indexed topics yet. Use a full id such as c3n12 from a [context-graph] block.' }
|
|
336
|
-
if (!m[2]) return ok(renderChatIndex(view))
|
|
337
|
-
const node = view.graph.nodes[m[2]]
|
|
338
|
-
if (!node) return { status: 'unknown', text: `No topic ${id}. Only use ids shown in a [context-graph] block.` }
|
|
339
|
-
node.hits = (node.hits ?? 0) + 1
|
|
340
|
-
const chat = chatDir(dirFor(agent), view.sid)
|
|
341
|
-
saveGraph(chat, view.graph).catch((error) => console.error('context-graph: hit count save failed', error))
|
|
342
|
-
const lines = [`# ${id} ${node.label}`, `${node.kind}. ${node.gist}`, '']
|
|
343
|
-
const source = await readSource(chat, m[2])
|
|
344
|
-
lines.push(source ? source.trim() : '(no verbatim source stored for this topic)')
|
|
345
|
-
const links = neighbors(view.graph, m[2])
|
|
346
|
-
if (links.length > 0) {
|
|
347
|
-
lines.push('', 'Linked topics:')
|
|
348
|
-
for (const link of links) {
|
|
349
|
-
const other = view.graph.nodes[link.id]
|
|
350
|
-
const otherId = `c${view.cid}${link.id}`
|
|
351
|
-
const arrow = link.direction === 'out' ? `${id} ${link.relation} ${otherId}` : `${otherId} ${link.relation} ${id}`
|
|
352
|
-
lines.push(`- ${arrow}: ${other.label}${args.depth >= 1 ? ` — ${other.gist}` : ''}`)
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
return ok(lines.join('\n'))
|
|
356
|
-
}
|
|
357
|
-
}))
|
|
358
|
-
|
|
359
|
-
// ---------- /context-graph command (nested: only where a human-command surface exists) ----------
|
|
360
|
-
ctx.plugin({
|
|
361
|
-
name: 'context-graph-command',
|
|
362
|
-
inject: ['commands'],
|
|
363
|
-
apply(cmdCtx) {
|
|
364
|
-
cmdCtx.effect(function* () {
|
|
365
|
-
yield cmdCtx.commands.register({
|
|
366
|
-
name: 'context-graph',
|
|
367
|
-
description: `Chat memory graph: /context-graph ${USAGE}`,
|
|
368
|
-
// Without `input`, dsh clients run the bare name and send any typed arguments to the model as chat.
|
|
369
|
-
input: { hint: USAGE },
|
|
370
|
-
async handler(invocation) {
|
|
371
|
-
const [sub = 'stats', ...rest] = invocation.rawInput.trim().split(/\s+/).filter(Boolean)
|
|
372
|
-
const agent = invocation.agent
|
|
373
|
-
const sid = sidOf(agent)
|
|
374
|
-
if (sub === 'on') {
|
|
375
|
-
await setFlags(agent, { memoryOff: false })
|
|
376
|
-
state(sid).announce = true
|
|
377
|
-
const result = await agent.runMaintenance(() => build(agent, { force: true }))
|
|
378
|
-
const shared = (await loadViews(agent)).filter((v) => !v.own).length
|
|
379
|
-
const indexed = result.status === 'built' ? `${result.totalNodes} topics in this chat` : `nothing indexed yet (${result.reason ?? result.status})`
|
|
380
|
-
return { kind: 'success', text: `Memory on · ${indexed} · ${shared} shared ${shared === 1 ? 'chat' : 'chats'} to draw on\nThis chat indexes itself every ${cfg.buildEveryTurns} turns and other chats in this workspace can use it. /context-graph unshare keeps it private; /context-graph off stops it.` }
|
|
381
|
-
}
|
|
382
|
-
if (sub === 'off') {
|
|
383
|
-
await setFlags(agent, { memoryOff: true })
|
|
384
|
-
return { kind: 'success', text: 'Memory off for this chat · nothing is added to its requests\nThe graph stays; /context-graph on resumes. To turn memory off in every chat, switch dsh-context-graph off on the Plugins page.' }
|
|
385
|
-
}
|
|
386
|
-
if (sub === 'share' || sub === 'unshare') {
|
|
387
|
-
const meta = await setFlags(agent, { private: sub === 'unshare' })
|
|
388
|
-
const topics = Object.keys((await loadGraph(chatDir(dirFor(agent), sid))).nodes).length
|
|
389
|
-
const hint = memoryOn(meta) ? '' : '\nMemory is off for this chat, so it has nothing new to share until /context-graph on.'
|
|
390
|
-
return { kind: 'success', text: sub === 'share' ? `Shared with the workspace · ${topics} topics\nOther chats with memory on can now match and recall this chat.${hint}` : `No longer shared · ${topics} topics stay private to this chat` }
|
|
391
|
-
}
|
|
392
|
-
if (sub === 'build') {
|
|
393
|
-
const result = await agent.runMaintenance(() => build(agent, { force: true }))
|
|
394
|
-
if (result.status !== 'built') return { kind: 'error', text: `Build ${result.status}: ${result.reason ?? ''}`.trim() }
|
|
395
|
-
return { kind: 'success', text: `${result.nodes} topics indexed (${result.newNodes} new) · this chat has ${result.totalNodes} topics\nLinks: ${result.edges}\nFolder: ${result.dir}` }
|
|
396
|
-
}
|
|
397
|
-
const views = await loadViews(agent)
|
|
398
|
-
if (sub === 'map') {
|
|
399
|
-
const all = []
|
|
400
|
-
for (const { sid: other, meta } of await listChats(dirFor(agent))) all.push({ sid: other, cid: meta.cid, meta, own: other === sid, graph: await loadGraph(chatDir(dirFor(agent), other)) })
|
|
401
|
-
return { kind: 'success', text: `${all.length} ${all.length === 1 ? 'chat' : 'chats'} in ${dirFor(agent)}\n${renderMap(all)}` }
|
|
402
|
-
}
|
|
403
|
-
if (sub === 'find') {
|
|
404
|
-
const query = rest.join(' ')
|
|
405
|
-
const { hits } = matchAcross(views, query, { max: cfg.maxHits, range: parseTimeRange(query) })
|
|
406
|
-
if (hits.length === 0) return { kind: 'success', text: 'No matching topics in shared chats' }
|
|
407
|
-
return { kind: 'success', text: [`${hits.length} matching ${hits.length === 1 ? 'topic' : 'topics'}`, ...hits.map(({ id, node }) => `${id} ${node.label}: ${node.gist}`)].join('\n') }
|
|
408
|
-
}
|
|
409
|
-
if (sub !== 'stats') return { kind: 'error', text: `Usage: /context-graph ${USAGE}` }
|
|
410
|
-
const own = views.find((v) => v.own)
|
|
411
|
-
const m = meter.main
|
|
412
|
-
const cached = m.cacheRead + m.cacheWrite
|
|
413
|
-
const hitRate = m.input + cached > 0 ? Math.round((m.cacheRead / (m.input + cached)) * 100) : 0
|
|
414
|
-
const session = agent.session
|
|
415
|
-
const pending = collectSpan(session.surface.nodes, (seq) => session.eventAt(seq), own?.meta.builtSeq ?? -1).userTurns
|
|
416
|
-
const shared = views.filter((v) => !v.own).length
|
|
417
|
-
return {
|
|
418
|
-
kind: 'success',
|
|
419
|
-
text: [
|
|
420
|
-
`Memory ${memoryOn(own?.meta) ? 'on' : 'off'} · ${Object.keys(own?.graph.nodes ?? {}).length} topics in this chat · ${sharedOn(own?.meta) ? 'shared' : 'private'} · ${shared} shared ${shared === 1 ? 'chat' : 'chats'} · ${pending} turns waiting to be indexed${updates.current() ? ' · update available' : ''}`,
|
|
421
|
-
`Version ${version}: ${updates.current() ?? 'no newer version found'}`,
|
|
422
|
-
`Graph folder: ${dirFor(agent)}`,
|
|
423
|
-
'Counters below are since the app started:',
|
|
424
|
-
`Builds: ${meter.builds}; builder tokens in/out: ${meter.builder.input + meter.builder.cacheRead + meter.builder.cacheWrite}/${meter.builder.output}`,
|
|
425
|
-
`Injected blocks: ${meter.injected} (~${meter.injectedTokens} tokens); recalls: ${meter.recalls}`,
|
|
426
|
-
`Main requests: ${m.requests}; input ${m.input} uncached + ${m.cacheRead} cache-read + ${m.cacheWrite} cache-write; cache-hit ${hitRate}%`
|
|
427
|
-
].join('\n')
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
})
|
|
431
|
-
}, 'context-graph command')
|
|
432
|
-
}
|
|
433
|
-
})
|
|
434
|
-
}
|
|
9
|
+
export { name, inject, apply } from './src/host/plugin.js'
|
package/package.json
CHANGED
|
@@ -1,32 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-context-graph",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "DeepSeek Harness plugin: memory graphs for every chat, on by default (switch the plugin off on the Plugins page to stop); other chats in the workspace recall exact past text by topic, chat or day, so fewer input tokens are re-sent",
|
|
5
5
|
"icon": "./icon.svg",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "index.js",
|
|
8
8
|
"exports": {
|
|
9
9
|
".": "./index.js",
|
|
10
|
-
"./client": "./
|
|
11
|
-
"./graph": "./
|
|
10
|
+
"./client": "./src/client/client.js",
|
|
11
|
+
"./graph": "./src/core/index.js",
|
|
12
12
|
"./locale/*.json": "./locale/*.json",
|
|
13
13
|
"./package.json": "./package.json"
|
|
14
14
|
},
|
|
15
15
|
"files": [
|
|
16
16
|
"index.js",
|
|
17
|
-
"
|
|
18
|
-
"store.js",
|
|
19
|
-
"update.js",
|
|
20
|
-
"lib/client.js",
|
|
17
|
+
"src",
|
|
21
18
|
"locale",
|
|
22
19
|
"icon.svg",
|
|
23
20
|
"cordis.patch.yml",
|
|
24
21
|
"README.md",
|
|
25
22
|
"README.zh.md",
|
|
26
|
-
"LICENSE"
|
|
23
|
+
"LICENSE",
|
|
24
|
+
"CHANGELOG.md"
|
|
27
25
|
],
|
|
28
26
|
"scripts": {
|
|
29
|
-
"test": "node --import ./test/resolve-dsh.mjs --test test
|
|
27
|
+
"test": "node --import ./test/helpers/resolve-dsh.mjs --test \"test/**/*.test.js\"",
|
|
28
|
+
"test:zones": "node scripts/test-zones.mjs"
|
|
30
29
|
},
|
|
31
30
|
"keywords": [
|
|
32
31
|
"dsh-plugin",
|
|
@@ -46,12 +45,12 @@
|
|
|
46
45
|
"url": "https://github.com/William20100221/dsh-context-graph/issues"
|
|
47
46
|
},
|
|
48
47
|
"engines": {
|
|
49
|
-
"dsh": ">=0.2.1-rc.
|
|
48
|
+
"dsh": ">=0.2.1-rc.1 <0.3.0-0",
|
|
50
49
|
"node": ">=20"
|
|
51
50
|
},
|
|
52
51
|
"peerDependencies": {
|
|
53
|
-
"@deepseek-ai/dsh-llm": ">=0.2.1-rc.
|
|
54
|
-
"@deepseek-ai/dsh-tools": ">=0.2.1-rc.
|
|
52
|
+
"@deepseek-ai/dsh-llm": ">=0.2.1-rc.1 <0.3.0-0",
|
|
53
|
+
"@deepseek-ai/dsh-tools": ">=0.2.1-rc.1 <0.3.0-0"
|
|
55
54
|
},
|
|
56
55
|
"dsh": {
|
|
57
56
|
"bundle": {
|