dsh-context-graph 0.2.3 → 0.4.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/lib/client.js ADDED
@@ -0,0 +1,126 @@
1
+ // Chat card for `/context-graph`, hand-written in dsh's client-bundle format (no build step).
2
+ // The shell loads this file as a plain script; `require` reaches only the shell's shared modules.
3
+ // Layout follows dsh's own command card: DisclosureRow with a 14px icon, a title, a one-line
4
+ // summary, and the remaining lines as an expandable body.
5
+ window.__ModuleLoader__.load({
6
+ id: 'dsh-context-graph',
7
+ factory: (require) => {
8
+ var module = { exports: {} }
9
+ var exports = module.exports
10
+ const { useState } = require('react')
11
+ const { jsx, jsxs } = require('react/jsx-runtime')
12
+ const { DisclosureRow } = require('@deepseek-ai/dsh-client-ui-primitives')
13
+
14
+ const NAMESPACE = 'dsh-context-graph'
15
+ const en = {
16
+ stats: 'Context graph',
17
+ on: 'Memory on',
18
+ off: 'Memory off',
19
+ share: 'Share with workspace',
20
+ unshare: 'Stop sharing',
21
+ build: 'Index this chat',
22
+ map: 'Memory map',
23
+ find: 'Find topics',
24
+ running: 'Working…',
25
+ failed: 'Failed'
26
+ }
27
+ const zh = {
28
+ stats: '上下文图谱',
29
+ on: '开启记忆',
30
+ off: '关闭记忆',
31
+ share: '共享到工作区',
32
+ unshare: '取消共享',
33
+ build: '索引当前对话',
34
+ map: '记忆地图',
35
+ find: '查找主题',
36
+ running: '处理中…',
37
+ failed: '失败'
38
+ }
39
+
40
+ const CSS = [
41
+ '.dshcg-root{margin:2px 0}',
42
+ '.dshcg-summary{margin-left:8px;font-size:13px;opacity:.72}',
43
+ '.dshcg-summary[data-error]{color:var(--color-text-danger,#d64545);opacity:1}',
44
+ '.dshcg-body{padding:6px 0 6px 24px;font-size:13px;line-height:1.6;white-space:pre-wrap;word-break:break-word}'
45
+ ].join('')
46
+ if (typeof document !== 'undefined' && document.querySelector('style[data-plugin-css="dsh-context-graph"]') === null) {
47
+ const tag = document.createElement('style')
48
+ tag.dataset.pluginCss = NAMESPACE
49
+ tag.textContent = CSS
50
+ document.head.appendChild(tag)
51
+ }
52
+
53
+ // Three linked nodes: the same mark as the plugin icon, drawn in the current text colour.
54
+ const ICON = jsxs('svg', {
55
+ width: 14,
56
+ height: 14,
57
+ viewBox: '0 0 24 24',
58
+ fill: 'none',
59
+ stroke: 'currentColor',
60
+ strokeWidth: 2,
61
+ strokeLinecap: 'round',
62
+ 'aria-hidden': true,
63
+ children: [
64
+ jsx('path', { d: 'M7 7l10 3M7 7l3 10M17 10l-7 7' }),
65
+ jsx('circle', { cx: 7, cy: 7, r: 2.5, fill: 'currentColor' }),
66
+ jsx('circle', { cx: 17, cy: 10, r: 2, fill: 'currentColor' }),
67
+ jsx('circle', { cx: 10, cy: 17, r: 2, fill: 'currentColor' })
68
+ ]
69
+ })
70
+
71
+ const SUBCOMMANDS = ['stats', 'on', 'off', 'share', 'unshare', 'build', 'map', 'find']
72
+
73
+ /** Title key from the typed arguments (`/context-graph on` -> on); no argument means stats. */
74
+ function subcommandOf(args) {
75
+ const first = String(args ?? '').trim().split(/\s+/)[0] || 'stats'
76
+ return SUBCOMMANDS.includes(first) ? first : 'stats'
77
+ }
78
+
79
+ /** Host text: line 1 is the summary, later lines are the details shown when expanded. */
80
+ function splitText(text) {
81
+ const lines = String(text ?? '').split('\n')
82
+ return { summary: lines[0] ?? '', body: lines.slice(1).join('\n').trim() }
83
+ }
84
+
85
+ function ContextGraphCard({ node, t }) {
86
+ const [open, setOpen] = useState(false)
87
+ const outcome = node.outcome
88
+ const running = outcome === null
89
+ const failed = outcome?.kind === 'error'
90
+ const { summary, body } = splitText(outcome?.text)
91
+ const shown = running ? t('running') : summary || (failed ? t('failed') : '')
92
+ const hasBody = !running && body.length > 0
93
+ return jsx('div', {
94
+ className: 'dshcg-root',
95
+ 'data-state': running ? 'running' : failed ? 'error' : 'ok',
96
+ children: jsx(DisclosureRow, {
97
+ icon: ICON,
98
+ title: t(subcommandOf(node.args)),
99
+ running,
100
+ open: open && hasBody,
101
+ expandable: hasBody,
102
+ expandOnRowClick: true,
103
+ keepContentWhenOpen: true,
104
+ onToggle: () => setOpen((value) => !value),
105
+ collapsedContent: shown ? jsx('span', { className: 'dshcg-summary', 'data-error': failed || undefined, children: shown }) : undefined,
106
+ children: open && hasBody ? jsx('div', { className: 'dshcg-body', children: body }) : undefined
107
+ })
108
+ })
109
+ }
110
+
111
+ const inject = ['slots', 'locale']
112
+ function apply(ctx) {
113
+ ctx.effect(() => ctx.locale.register(NAMESPACE, { en, zh }), 'dsh-context-graph: dictionaries')
114
+ ctx.slots.inject('conversation.chat.commandview', () =>
115
+ ctx.slots.register({ name: 'conversation.chat.commandview', key: 'context-graph', locale: NAMESPACE }, ContextGraphCard)
116
+ )
117
+ }
118
+
119
+ exports.inject = inject
120
+ exports.apply = apply
121
+ exports.ContextGraphCard = ContextGraphCard
122
+ exports.subcommandOf = subcommandOf
123
+ exports.splitText = splitText
124
+ return module.exports
125
+ }
126
+ })
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Context Graph",
4
+ "description": "Per-chat memory you switch on with /context-graph on. Other chats in the workspace recall exact past text by topic, chat or day instead of re-sending it, so fewer input tokens go out."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "上下文图谱",
4
+ "description": "按对话开启的记忆:/context-graph on。工作区里的其他对话可按主题、对话或日期取回过往原文,而不是把旧消息重复发送,从而减少输入 token。",
5
+ "detail": "README.zh.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,12 +1,15 @@
1
1
  {
2
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",
3
+ "version": "0.4.0",
4
+ "description": "DeepSeek Harness plugin: per-chat memory graphs you switch on with /context-graph on; other chats in the workspace recall exact past text by topic, chat or day, so fewer input tokens are re-sent",
5
+ "icon": "./icon.svg",
5
6
  "type": "module",
6
7
  "main": "index.js",
7
8
  "exports": {
8
9
  ".": "./index.js",
10
+ "./client": "./lib/client.js",
9
11
  "./graph": "./graph.js",
12
+ "./locale/*.json": "./locale/*.json",
10
13
  "./package.json": "./package.json"
11
14
  },
12
15
  "files": [
@@ -14,12 +17,16 @@
14
17
  "graph.js",
15
18
  "store.js",
16
19
  "update.js",
20
+ "lib/client.js",
21
+ "locale",
22
+ "icon.svg",
17
23
  "cordis.patch.yml",
18
24
  "README.md",
25
+ "README.zh.md",
19
26
  "LICENSE"
20
27
  ],
21
28
  "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"
29
+ "test": "node --import ./test/resolve-dsh.mjs --test test/graph.test.js test/update.test.js test/client.test.js test/plugin.test.js"
23
30
  },
24
31
  "keywords": [
25
32
  "dsh-plugin",
@@ -49,6 +56,13 @@
49
56
  "dsh": {
50
57
  "bundle": {
51
58
  "patch": "./cordis.patch.yml"
59
+ },
60
+ "client": {
61
+ "platform": "web",
62
+ "inject": [
63
+ "@deepseek-ai/dsh-client-ui-renderer",
64
+ "@deepseek-ai/dsh-client-locale"
65
+ ]
52
66
  }
53
67
  }
54
68
  }
package/store.js CHANGED
@@ -1,44 +1,79 @@
1
1
  /**
2
- * On-disk layout under `<dir>` (default `<workspace>/.context-graph`):
3
- * graph.json the graph (see graph.js)
4
- * src/<id>.md verbatim source text of one node, one section appended per build
2
+ * On-disk layout under `<dir>` (default `<workspace>/.context-graph`), one folder per chat:
3
+ * chats/<sessionId>/meta.json { cid, title, workspace, startedAt, lastActiveAt, turns, memory, shared }
4
+ * chats/<sessionId>/graph.json the chat's graph (see graph.js)
5
+ * chats/<sessionId>/src/<id>.md verbatim source text of one node, one section appended per build
6
+ * Nothing is merged or copied between chats; the list of chats is the list of folders.
5
7
  * ponytail: last writer wins across concurrent sessions; add a lock file if two agents share a workspace.
6
8
  */
7
9
 
8
- import { mkdir, readFile, rename, writeFile, appendFile } from 'node:fs/promises'
10
+ import { mkdir, readdir, readFile, rename, writeFile, appendFile } from 'node:fs/promises'
9
11
  import { join } from 'node:path'
10
12
 
11
13
  import { emptyGraph, GRAPH_VERSION } from './graph.js'
12
14
 
13
- export async function loadGraph(dir) {
15
+ export const chatDir = (dir, sid) => join(dir, 'chats', String(sid))
16
+
17
+ async function readJson(path) {
14
18
  try {
15
- const graph = JSON.parse(await readFile(join(dir, 'graph.json'), 'utf8'))
16
- if (graph?.version !== GRAPH_VERSION || typeof graph.nodes !== 'object' || !Array.isArray(graph.edges)) return emptyGraph()
17
- return graph
19
+ return JSON.parse(await readFile(path, 'utf8'))
18
20
  } catch (error) {
19
- if (error?.code === 'ENOENT') return emptyGraph()
21
+ if (error?.code === 'ENOENT') return undefined
20
22
  throw error
21
23
  }
22
24
  }
23
25
 
24
- export async function saveGraph(dir, graph) {
25
- await mkdir(dir, { recursive: true })
26
- const target = join(dir, 'graph.json')
27
- const tmp = `${target}.${process.pid}.tmp`
28
- await writeFile(tmp, JSON.stringify(graph, null, 1), 'utf8')
29
- await rename(tmp, target)
26
+ async function writeJson(path, value) {
27
+ await mkdir(join(path, '..'), { recursive: true })
28
+ const tmp = `${path}.${process.pid}.tmp`
29
+ await writeFile(tmp, JSON.stringify(value, null, 1), 'utf8')
30
+ await rename(tmp, path)
31
+ }
32
+
33
+ export async function loadGraph(chat) {
34
+ const graph = await readJson(join(chat, 'graph.json'))
35
+ if (graph?.version !== GRAPH_VERSION || typeof graph.nodes !== 'object' || !Array.isArray(graph.edges)) return emptyGraph()
36
+ return graph
37
+ }
38
+
39
+ export const saveGraph = (chat, graph) => writeJson(join(chat, 'graph.json'), graph)
40
+
41
+ export const loadMeta = (dir, sid) => readJson(join(chatDir(dir, sid), 'meta.json'))
42
+
43
+ export const saveMeta = (dir, sid, meta) => writeJson(join(chatDir(dir, sid), 'meta.json'), meta)
44
+
45
+ /** Every chat folder with a readable meta.json, newest activity first. */
46
+ export async function listChats(dir) {
47
+ let names = []
48
+ try { names = await readdir(join(dir, 'chats')) } catch (error) { if (error?.code !== 'ENOENT') throw error }
49
+ const chats = []
50
+ for (const sid of names) {
51
+ const meta = await loadMeta(dir, sid)
52
+ if (meta) chats.push({ sid, meta })
53
+ }
54
+ return chats.sort((a, b) => String(b.meta.lastActiveAt ?? '').localeCompare(String(a.meta.lastActiveAt ?? '')))
55
+ }
56
+
57
+ /** The chat's meta, created on first sight with the next free chat number. */
58
+ export async function ensureMeta(dir, sid, { title, workspace, now }) {
59
+ const existing = await loadMeta(dir, sid)
60
+ if (existing) return existing
61
+ const cid = (await listChats(dir)).reduce((max, c) => Math.max(max, c.meta.cid ?? 0), 0) + 1
62
+ const meta = { cid, title, workspace, startedAt: now, lastActiveAt: now, turns: 0, memory: false, shared: false }
63
+ await saveMeta(dir, sid, meta)
64
+ return meta
30
65
  }
31
66
 
32
67
  /** Append one build's verbatim messages to the node's source file. */
33
- export async function appendSource(dir, id, { session, turn, at, messages }) {
34
- await mkdir(join(dir, 'src'), { recursive: true })
68
+ export async function appendSource(chat, id, { session, turn, at, messages }) {
69
+ await mkdir(join(chat, 'src'), { recursive: true })
35
70
  const body = messages.map((m) => `**${m.role}** (seq ${m.seq}):\n\n${m.text}`).join('\n\n')
36
- await appendFile(join(dir, 'src', `${id}.md`), `## ${at} session ${session} turn ${turn}\n\n${body}\n\n`, 'utf8')
71
+ await appendFile(join(chat, 'src', `${id}.md`), `## ${at} session ${session} turn ${turn}\n\n${body}\n\n`, 'utf8')
37
72
  }
38
73
 
39
- export async function readSource(dir, id) {
74
+ export async function readSource(chat, id) {
40
75
  try {
41
- return await readFile(join(dir, 'src', `${id}.md`), 'utf8')
76
+ return await readFile(join(chat, 'src', `${id}.md`), 'utf8')
42
77
  } catch (error) {
43
78
  if (error?.code === 'ENOENT') return undefined
44
79
  throw error