@restregular/dsh-memory 0.3.1 → 0.4.1

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/index.js ADDED
@@ -0,0 +1,72 @@
1
+ /**
2
+ * @restregular/dsh-memory —— 单入口插件(一个包,一条 Loader entry)。
3
+ *
4
+ * 为什么必须是一条 entry:
5
+ * 宿主的 dsh-client-modules 只为「有活 Loader entry、且那条 entry 能解析到包名」
6
+ * 的包提供 client bundle(reconcilePackage 要求一个包名只能有一个解析源,见
7
+ * "resolves from multiple active Loader sources")。而声明了 dsh.client 的包一旦
8
+ * 被两个来源命中,整个客户端图组合就失败(fail-loud,桌面上表现为起不来)。
9
+ * 所以「一个包 + 一个面板」的唯一稳定形态就是:一个包名,一条 entry,两侧都在。
10
+ * 与 dshmarket 同形(1 包 / 1 行 / dsh.bundle + dsh.client)。
11
+ *
12
+ * 四个半边(provider / 模型工具 / 召回注入 / 面板服务端)都在这一行里组合,但各自
13
+ * 独立降级:任何一半抛错都只写一行日志,绝不让 DSH 启动失败 —— 这是本仓库从第一版
14
+ * 起就有的铁律,合并后由 part() 继续兜住。
15
+ *
16
+ * 每个半边的 apply 都是原样复用(不复制代码),它们的单元测试因此继续有效。
17
+ */
18
+
19
+ import { apply as providerApply } from './provider/apply.js'
20
+
21
+ import { apply as toolsApply, } from './tools/apply.js'
22
+ import { apply as injectApply, } from './inject/apply.js'
23
+ import { apply as panelApply } from './panel.js'
24
+
25
+ export const name = 'dsh-memory'
26
+
27
+ /**
28
+ * 合并后的配置形态:provider 的配置保持在顶层(与既有文档、既有 profile 配置兼容),
29
+ * 工具 / 注入 / 面板各自一个小节。原来靠「多条 entry 各自一个 config 块」实现的
30
+ * 独立开关,现在由小节里的 enabled / defaultScope 表达。
31
+ */
32
+
33
+            
34
+
35
+        
36
+
37
+         
38
+
39
+
40
+
41
+ /** 跑一个半边:失败只记日志,不影响其它半边,也不影响宿主启动。 */
42
+ function part(ctx , label , fn ) {
43
+ try {
44
+ fn()
45
+ } catch (error) {
46
+ const message = error instanceof Error ? error.message : String(error)
47
+ console.warn(`[dsh-memory] ${label} 未能加载(已忽略,其余部分照常): ${message}`)
48
+ }
49
+ }
50
+
51
+ export function apply(ctx , config = {}) {
52
+ // 1) provider:注册 ctx.memory(JSONL 存储 + 双通道检索 + 向量后端生命周期)。
53
+ // 它是其余半边的前置:注册不成本插件时,工具会拿到 undefined 并明确报错,
54
+ // 面板会显示「memory provider 未加载」,注入则静默跳过。
55
+ part(ctx, 'provider', () => providerApply(ctx, config))
56
+
57
+ // 2) 召回注入:自身惰性取 memory(ctx.get),所以不需要等待任何服务即可挂上。
58
+ part(ctx, 'inject', () => injectApply(ctx, config.inject ?? {}))
59
+
60
+ // 3) 面板服务端路由:内部 ctx.inject(['webServer']),没有 webServer 就只是没有 UI。
61
+ part(ctx, 'panel', () => panelApply(ctx, config.panel ?? {}))
62
+
63
+ // 4) 模型工具:同时需要工具注册表与本插件提供的 memory 服务。
64
+ // 用 ctx.inject 而不是模块级 inject —— 缺服务时只是这四个工具不出现,
65
+ // 而不是让整条 entry 挂在 PENDING 上(那会连 provider 一起拖住)。
66
+ ctx.inject(['tools', 'memory'], (c ) => {
67
+ part(c, 'tools', () => toolsApply(c, config.tools ?? {}))
68
+ })
69
+ }
70
+
71
+
72
+ //# sourceURL=source/memory-plugin/src/index.ts
@@ -1,82 +1,82 @@
1
- /**
2
- * Cordis wiring for dsh-memory-inject. Loaded only inside DSH: hooks the
3
- * documented agent/pre-step waterfall and appends a user-role recall message
4
- * carrying the retrieved memories.
5
- *
6
- * Message construction MUST go through createUserMessage: the loop reads
7
- * `decision.kind` and downstream consumers read `message.source.kind`, so a
8
- * hand-rolled `{ role, content }` object aborts the turn with
9
- * "Cannot read properties of undefined (reading 'kind')" (incident 2026-10-10).
10
- * The reference implementation is the official dsh-time-context plugin.
11
- *
12
- * Memory is an OPTIONAL dependency (ctx.get) by design — this plugin must not
13
- * sit PENDING when no provider is loaded; it just stays passive.
14
- */
15
-
16
- import { createUserMessage } from '@deepseek-ai/dsh-llm'
17
-
18
- import { MemoryInjector, defaultInjectConfig, } from './inject.js'
1
+ /**
2
+ * Cordis wiring for dsh-memory-inject. Loaded only inside DSH: hooks the
3
+ * documented agent/pre-step waterfall and appends a user-role recall message
4
+ * carrying the retrieved memories.
5
+ *
6
+ * Message construction MUST go through createUserMessage: the loop reads
7
+ * `decision.kind` and downstream consumers read `message.source.kind`, so a
8
+ * hand-rolled `{ role, content }` object aborts the turn with
9
+ * "Cannot read properties of undefined (reading 'kind')" (incident 2026-10-10).
10
+ * The reference implementation is the official dsh-time-context plugin.
11
+ *
12
+ * Memory is an OPTIONAL dependency (ctx.get) by design — this plugin must not
13
+ * sit PENDING when no provider is loaded; it just stays passive.
14
+ */
15
+
16
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
17
+
18
+ import { MemoryInjector, defaultInjectConfig, } from './inject.js'
19
+
20
+
21
+
22
+
23
+
24
+
25
+ export const name = 'dsh-memory-inject'
26
+
27
+ export function apply(ctx , config = {}) {
28
+ const cfg = {
29
+ enabled: config.enabled ?? defaultInjectConfig.enabled,
30
+ tokenBudget: config.tokenBudget ?? defaultInjectConfig.tokenBudget,
31
+ topK: config.topK ?? defaultInjectConfig.topK,
32
+ }
33
+
34
+ // One injector per activation: its repeat-suppression state must live across
35
+ // the steps of a turn (a per-step instance would re-inject every step).
36
+ const injector = new MemoryInjector(
37
+ async (query, signal) => {
38
+ const memory = ctx.get('memory')
39
+ if (!memory?.search) return []
40
+ return memory.search({ text: query, signal, topK: cfg.topK })
41
+ },
42
+ cfg,
43
+ )
44
+
45
+ ctx.on('agent/pre-step', async (input, next) => {
46
+ // Runs outermost (prepend), so `next()` yields the fully assembled decision.
47
+ const decision = await next()
48
+ // A rejected step must pass through untouched — never rebuild the decision.
49
+ if (!decision || decision.kind === 'reject' || input.signal?.aborted) return decision
50
+ // optional capability: absence (or partial load) → pass through untouched
51
+ if (!ctx.get('memory')) return decision
52
+
53
+ const text = await injector.maybeInject(
54
+ { messages: input.messages , signal: input.signal },
55
+ { messages: decision.messages },
56
+ )
57
+ if (!text) return decision
58
+ const message = createUserMessage({
59
+ content: [{ type: 'text', text }],
60
+ source: { kind: 'memory', form: 'recall' },
61
+ })
62
+ // Last-resort guard: a malformed message aborts the whole turn downstream
63
+ // (consumers read message.source.kind), so never publish one.
64
+ if (!isWellFormedMessage(message)) return decision
65
+ return { ...decision, messages: [...decision.messages, message] }
66
+ }, { prepend: true })
67
+ }
68
+
69
+ const VALID_BLOCK_TYPES = new Set(['text', 'reasoning', 'image', 'file', 'tool-call', 'tool-addition', 'tool-removal'])
70
+
71
+ /** Structural check against the host Message contract (id/role/content/source.kind). */
72
+ function isWellFormedMessage(message ) {
73
+ const m = message
74
+ if (!m || typeof m.id !== 'string' || typeof m.role !== 'string') return false
75
+ if (!Array.isArray(m.content) || m.content.length === 0) return false
76
+ if (!m.content.every((block) => typeof (block )?.type === 'string' && VALID_BLOCK_TYPES.has((block ).type))) return false
77
+ const source = m.source
78
+ return typeof source?.kind === 'string'
79
+ }
19
80
 
20
-
21
-
22
-
23
-
24
81
 
25
- export const name = 'dsh-memory-inject'
26
-
27
- export function apply(ctx , config = {}) {
28
- const cfg = {
29
- enabled: config.enabled ?? defaultInjectConfig.enabled,
30
- tokenBudget: config.tokenBudget ?? defaultInjectConfig.tokenBudget,
31
- topK: config.topK ?? defaultInjectConfig.topK,
32
- }
33
-
34
- // One injector per activation: its repeat-suppression state must live across
35
- // the steps of a turn (a per-step instance would re-inject every step).
36
- const injector = new MemoryInjector(
37
- async (query, signal) => {
38
- const memory = ctx.get('memory')
39
- if (!memory?.search) return []
40
- return memory.search({ text: query, signal, topK: cfg.topK })
41
- },
42
- cfg,
43
- )
44
-
45
- ctx.on('agent/pre-step', async (input, next) => {
46
- // Runs outermost (prepend), so `next()` yields the fully assembled decision.
47
- const decision = await next()
48
- // A rejected step must pass through untouched — never rebuild the decision.
49
- if (!decision || decision.kind === 'reject' || input.signal?.aborted) return decision
50
- // optional capability: absence (or partial load) → pass through untouched
51
- if (!ctx.get('memory')) return decision
52
-
53
- const text = await injector.maybeInject(
54
- { messages: input.messages , signal: input.signal },
55
- { messages: decision.messages },
56
- )
57
- if (!text) return decision
58
- const message = createUserMessage({
59
- content: [{ type: 'text', text }],
60
- source: { kind: 'memory', form: 'recall' },
61
- })
62
- // Last-resort guard: a malformed message aborts the whole turn downstream
63
- // (consumers read message.source.kind), so never publish one.
64
- if (!isWellFormedMessage(message)) return decision
65
- return { ...decision, messages: [...decision.messages, message] }
66
- }, { prepend: true })
67
- }
68
-
69
- const VALID_BLOCK_TYPES = new Set(['text', 'reasoning', 'image', 'file', 'tool-call', 'tool-addition', 'tool-removal'])
70
-
71
- /** Structural check against the host Message contract (id/role/content/source.kind). */
72
- function isWellFormedMessage(message ) {
73
- const m = message
74
- if (!m || typeof m.id !== 'string' || typeof m.role !== 'string') return false
75
- if (!Array.isArray(m.content) || m.content.length === 0) return false
76
- if (!m.content.every((block) => typeof (block )?.type === 'string' && VALID_BLOCK_TYPES.has((block ).type))) return false
77
- const source = m.source
78
- return typeof source?.kind === 'string'
79
- }
80
-
81
-
82
- //# sourceURL=D:\.deepseek\memory-plugin\packages\memory-inject\src\apply.ts
82
+ //# sourceURL=source/memory-inject/src/apply.ts
@@ -1,127 +1,127 @@
1
- /**
2
- * Memory injection logic (M3) — pure functions, no cordis imports.
3
- *
4
- * Injection shape follows the official docs: a user-role message whose content
5
- * is a single `context` block with `contextForm: 'recall'`, prepended to the
6
- * messages that enter the step via the agent/pre-step waterfall.
7
- */
8
-
9
- import { estimateTokens } from '../provider/rerank.js'
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
- export const defaultInjectConfig = {
20
- enabled: true,
21
- tokenBudget: 500,
22
- topK: 5,
23
- }
24
-
25
- /** Minimal structural view of the messages we inspect (role + text blocks). */
26
-
27
-
28
-
29
-
30
-
31
-
32
-
33
-
34
-
35
-
36
-
37
-
38
-
39
-
40
- /**
41
- * Extract the retrieval query: the text of the LAST user message. Synthetic
42
- * context injections (file notices etc.) are user-role too, so scanning from
43
- * the end finds the freshest human-visible input; empty text → no injection.
44
- */
45
- export function pickQueryText(messages ) {
46
- for (let i = messages.length - 1; i >= 0; i--) {
47
- const m = messages[i]
48
- if (m.role !== 'user') continue
49
- const text = (m.content ?? [])
50
- .filter((b) => b.type === 'text' && typeof b.text === 'string')
51
- .map((b) => b.text )
52
- .join(' ')
53
- .trim()
54
- if (text) return text
55
- }
56
- return ''
57
- }
58
-
59
- /** Render hits into a recall text block, greedily within the token budget. */
60
- export function renderRecallBlock(hits , cfg ) {
61
- if (hits.length === 0) return null
62
- const header = '以下是与此请求可能相关的长期记忆,供参考(可用 memory_search 核实,用 memory_forget 删除):'
63
- let tokens = estimateTokens(header) + 4
64
- const lines = []
65
- for (const h of hits.slice(0, cfg.topK)) {
66
- const line = `- ${h.record.content.replace(/\s+/g, ' ').slice(0, 300)}`
67
- const cost = estimateTokens(line) + 1
68
- if (tokens + cost > cfg.tokenBudget) break
69
- lines.push(line)
70
- tokens += cost
71
- }
72
- if (lines.length === 0) return null
73
- return { text: `${header}\n${lines.join('\n')}`, tokens }
74
- }
75
-
76
- /** The context block we prepend (matches the documented ContextForm 'recall'). */
77
- export function recallText(text ) {
78
- return text
79
- }
80
-
81
- /**
82
- * Turn-agnostic injector: searches memory for the step's query and returns the
83
- * recall text to append. The host middleware (apply.ts) wraps that text into a
84
- * real message via createUserMessage — a bare {role, content} object is NOT a
85
- * message and crashes the loop (see the 2026-10-10 incident below).
86
- *
87
- * Repeated identical injections are suppressed so a multi-step turn does not
88
- * repeat the same block before every model call.
89
- */
90
- export class MemoryInjector {
91
- lastText = ''
92
- search
93
- cfg
94
-
95
- constructor(
96
- search ,
97
- cfg ,
98
- ) {
99
- this.search = search
100
- this.cfg = cfg
101
- }
102
-
103
- async maybeInject(
104
- input ,
105
- _decision ,
106
- ) {
107
- if (!this.cfg.enabled) return undefined
108
- const query = pickQueryText(input.messages)
109
- if (!query) return undefined
110
-
111
- let hits
112
- try {
113
- hits = await this.search(query, input.signal)
114
- } catch {
115
- return undefined // retrieval failure never breaks the agent loop
116
- }
117
-
118
- const block = renderRecallBlock(hits, this.cfg)
119
- if (!block || block.text === this.lastText) return undefined
120
- this.lastText = block.text
121
-
122
- return block.text
123
- }
124
- }
125
-
126
-
127
- //# sourceURL=D:\.deepseek\memory-plugin\packages\memory-inject\src\inject.ts
1
+ /**
2
+ * Memory injection logic (M3) — pure functions, no cordis imports.
3
+ *
4
+ * Injection shape follows the official docs: a user-role message whose content
5
+ * is a single `context` block with `contextForm: 'recall'`, prepended to the
6
+ * messages that enter the step via the agent/pre-step waterfall.
7
+ */
8
+
9
+ import { estimateTokens } from '../provider/rerank.js'
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+ export const defaultInjectConfig = {
20
+ enabled: true,
21
+ tokenBudget: 500,
22
+ topK: 5,
23
+ }
24
+
25
+ /** Minimal structural view of the messages we inspect (role + text blocks). */
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+ /**
41
+ * Extract the retrieval query: the text of the LAST user message. Synthetic
42
+ * context injections (file notices etc.) are user-role too, so scanning from
43
+ * the end finds the freshest human-visible input; empty text → no injection.
44
+ */
45
+ export function pickQueryText(messages ) {
46
+ for (let i = messages.length - 1; i >= 0; i--) {
47
+ const m = messages[i]
48
+ if (m.role !== 'user') continue
49
+ const text = (m.content ?? [])
50
+ .filter((b) => b.type === 'text' && typeof b.text === 'string')
51
+ .map((b) => b.text )
52
+ .join(' ')
53
+ .trim()
54
+ if (text) return text
55
+ }
56
+ return ''
57
+ }
58
+
59
+ /** Render hits into a recall text block, greedily within the token budget. */
60
+ export function renderRecallBlock(hits , cfg ) {
61
+ if (hits.length === 0) return null
62
+ const header = '以下是与此请求可能相关的长期记忆,供参考(可用 memory_search 核实,用 memory_forget 删除):'
63
+ let tokens = estimateTokens(header) + 4
64
+ const lines = []
65
+ for (const h of hits.slice(0, cfg.topK)) {
66
+ const line = `- ${h.record.content.replace(/\s+/g, ' ').slice(0, 300)}`
67
+ const cost = estimateTokens(line) + 1
68
+ if (tokens + cost > cfg.tokenBudget) break
69
+ lines.push(line)
70
+ tokens += cost
71
+ }
72
+ if (lines.length === 0) return null
73
+ return { text: `${header}\n${lines.join('\n')}`, tokens }
74
+ }
75
+
76
+ /** The context block we prepend (matches the documented ContextForm 'recall'). */
77
+ export function recallText(text ) {
78
+ return text
79
+ }
80
+
81
+ /**
82
+ * Turn-agnostic injector: searches memory for the step's query and returns the
83
+ * recall text to append. The host middleware (apply.ts) wraps that text into a
84
+ * real message via createUserMessage — a bare {role, content} object is NOT a
85
+ * message and crashes the loop (see the 2026-10-10 incident below).
86
+ *
87
+ * Repeated identical injections are suppressed so a multi-step turn does not
88
+ * repeat the same block before every model call.
89
+ */
90
+ export class MemoryInjector {
91
+ lastText = ''
92
+ search
93
+ cfg
94
+
95
+ constructor(
96
+ search ,
97
+ cfg ,
98
+ ) {
99
+ this.search = search
100
+ this.cfg = cfg
101
+ }
102
+
103
+ async maybeInject(
104
+ input ,
105
+ _decision ,
106
+ ) {
107
+ if (!this.cfg.enabled) return undefined
108
+ const query = pickQueryText(input.messages)
109
+ if (!query) return undefined
110
+
111
+ let hits
112
+ try {
113
+ hits = await this.search(query, input.signal)
114
+ } catch {
115
+ return undefined // retrieval failure never breaks the agent loop
116
+ }
117
+
118
+ const block = renderRecallBlock(hits, this.cfg)
119
+ if (!block || block.text === this.lastText) return undefined
120
+ this.lastText = block.text
121
+
122
+ return block.text
123
+ }
124
+ }
125
+
126
+
127
+ //# sourceURL=source/memory-inject/src/inject.ts