@chenhw7/dsh-memory 0.1.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.
Files changed (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +288 -0
  3. package/README.zh-CN.md +280 -0
  4. package/cordis.patch.yml +32 -0
  5. package/lib/brand.d.ts +10 -0
  6. package/lib/brand.d.ts.map +1 -0
  7. package/lib/brand.js +10 -0
  8. package/lib/brand.js.map +1 -0
  9. package/lib/context/index.d.ts +70 -0
  10. package/lib/context/index.d.ts.map +1 -0
  11. package/lib/context/index.js +123 -0
  12. package/lib/context/index.js.map +1 -0
  13. package/lib/context/policy.d.ts +28 -0
  14. package/lib/context/policy.d.ts.map +1 -0
  15. package/lib/context/policy.js +52 -0
  16. package/lib/context/policy.js.map +1 -0
  17. package/lib/index.d.ts +75 -0
  18. package/lib/index.d.ts.map +1 -0
  19. package/lib/index.js +33 -0
  20. package/lib/index.js.map +1 -0
  21. package/lib/invariant.d.ts +27 -0
  22. package/lib/invariant.d.ts.map +1 -0
  23. package/lib/invariant.js +42 -0
  24. package/lib/invariant.js.map +1 -0
  25. package/lib/review/accumulator.d.ts +64 -0
  26. package/lib/review/accumulator.d.ts.map +1 -0
  27. package/lib/review/accumulator.js +101 -0
  28. package/lib/review/accumulator.js.map +1 -0
  29. package/lib/review/extract.d.ts +112 -0
  30. package/lib/review/extract.d.ts.map +1 -0
  31. package/lib/review/extract.js +249 -0
  32. package/lib/review/extract.js.map +1 -0
  33. package/lib/review/index.d.ts +45 -0
  34. package/lib/review/index.d.ts.map +1 -0
  35. package/lib/review/index.js +173 -0
  36. package/lib/review/index.js.map +1 -0
  37. package/lib/scanner.d.ts +21 -0
  38. package/lib/scanner.d.ts.map +1 -0
  39. package/lib/scanner.js +75 -0
  40. package/lib/scanner.js.map +1 -0
  41. package/lib/store/index.d.ts +24 -0
  42. package/lib/store/index.d.ts.map +1 -0
  43. package/lib/store/index.js +137 -0
  44. package/lib/store/index.js.map +1 -0
  45. package/lib/tool/index.d.ts +33 -0
  46. package/lib/tool/index.d.ts.map +1 -0
  47. package/lib/tool/index.js +455 -0
  48. package/lib/tool/index.js.map +1 -0
  49. package/lib/types.d.ts +123 -0
  50. package/lib/types.d.ts.map +1 -0
  51. package/lib/types.js +10 -0
  52. package/lib/types.js.map +1 -0
  53. package/package.json +94 -0
@@ -0,0 +1,173 @@
1
+ /**
2
+ * `@chenhw7/dsh-memory/review`: the automatic memory sediment layer. A
3
+ * function plugin that registers a `session-projection` accumulator over
4
+ * `user/message` / `assistant/message` events and triggers one LLM extraction
5
+ * call when the accumulator crosses its threshold, plus a fire-and-forget
6
+ * flush on `compaction/end` and `session/disposed` (方案 C).
7
+ *
8
+ * Two mechanisms, one store:
9
+ * 1. **Periodic review** — a pure synchronous projection collects candidate
10
+ * fragments (keyword/correction signals); on `agent/pre-step`, when the
11
+ * unprocessed candidates reach the threshold, one `ctx.llm.stream`
12
+ * extraction runs and the high-water mark advances (the logical "clear").
13
+ * 2. **Flush** — on `compaction/end` the shadowed raw events are read from the
14
+ * matching `compaction/summary` and extracted; on `session/disposed` the
15
+ * recent derived messages are extracted. Both are fire-and-forget and never
16
+ * block their event.
17
+ *
18
+ * @module @chenhw7/dsh-memory/review
19
+ */
20
+ import z from '@deepseek-ai/schemastery';
21
+ import { MEMORY_REVIEW_PROJECTION_KEY, accumulatorSchema, applyAccumulator, emptyAccumulator, messageText, } from "./accumulator.js";
22
+ import { runFlushExtraction, runReviewExtraction } from "./extract.js";
23
+ /** Cordis function-plugin name. */
24
+ export const name = 'memory-review';
25
+ /** Services required before the plugin applies. The LLM seam is mandatory;
26
+ * `sessionProjections` and `memory` are optional (read via `ctx.get`). */
27
+ export const inject = ['llm'];
28
+ export const Config = z.object({
29
+ reviewEnabled: z.boolean().default(true),
30
+ reviewCandidateThreshold: z.number().step(1).min(1).default(10),
31
+ flushOnCompaction: z.boolean().default(true),
32
+ flushOnDispose: z.boolean().default(true),
33
+ });
34
+ /** Best-effort timeout for the dispose flush, in milliseconds. */
35
+ const DISPOSE_FLUSH_TIMEOUT_MS = 5_000;
36
+ /** Resolve and validate the raw config into the runtime form. */
37
+ function resolveConfig(config) {
38
+ return {
39
+ reviewEnabled: config.reviewEnabled ?? true,
40
+ reviewCandidateThreshold: config.reviewCandidateThreshold ?? 10,
41
+ flushOnCompaction: config.flushOnCompaction ?? true,
42
+ flushOnDispose: config.flushOnDispose ?? true,
43
+ };
44
+ }
45
+ /** Render one derived message as a flush fragment (role-prefixed text). */
46
+ function messageFragment(message) {
47
+ const parts = [];
48
+ for (const block of message.content) {
49
+ if (block.type === 'text' && typeof block.text === 'string')
50
+ parts.push(block.text);
51
+ }
52
+ if (parts.length === 0)
53
+ return undefined;
54
+ return `${message.role}: ${parts.join('\n')}`;
55
+ }
56
+ /** Collect text fragments for the shadowed seqs of a compaction summary. */
57
+ function collectShadowedFragments(session, seqs) {
58
+ const fragments = [];
59
+ const events = session.events;
60
+ for (const seq of seqs) {
61
+ const event = events[seq];
62
+ if (event === undefined)
63
+ continue;
64
+ const text = messageText(event);
65
+ if (text !== undefined)
66
+ fragments.push(text);
67
+ }
68
+ return fragments;
69
+ }
70
+ /** Locate the `compaction/summary` matching one `compaction/end` id. */
71
+ function findCompactionSummary(session, compactionId) {
72
+ for (const event of session.events) {
73
+ if (event.type === 'compaction/summary' && event.data.compactionId === compactionId) {
74
+ return event;
75
+ }
76
+ }
77
+ return undefined;
78
+ }
79
+ /** Fire-and-forget flush on `compaction/end`: extract the shadowed fragments. */
80
+ async function flushOnCompaction(ctx, session, compactionId) {
81
+ const summary = findCompactionSummary(session, compactionId);
82
+ if (summary === undefined)
83
+ return;
84
+ const fragments = collectShadowedFragments(session, summary.data.shadowedSeqs);
85
+ await runFlushExtraction(ctx, session, fragments);
86
+ }
87
+ /** Fire-and-forget flush on `session/disposed`: extract recent derived messages. */
88
+ async function flushOnDispose(ctx, session) {
89
+ const messages = session.deriveMessages();
90
+ const fragments = [];
91
+ for (const message of messages) {
92
+ const fragment = messageFragment(message);
93
+ if (fragment !== undefined)
94
+ fragments.push(fragment);
95
+ }
96
+ const signal = AbortSignal.timeout(DISPOSE_FLUSH_TIMEOUT_MS);
97
+ await runFlushExtraction(ctx, session, fragments, signal);
98
+ }
99
+ /**
100
+ * Install the memory-review function plugin.
101
+ * @param ctx - Cordis context carrying the LLM seam.
102
+ * @param config - plugin configuration (defaults applied by schemastery).
103
+ */
104
+ export function apply(ctx, config = {}) {
105
+ const resolved = resolveConfig(config);
106
+ /** Per-session high-water mark: the seq of the last candidate covered by an extraction. */
107
+ const highWaterMarks = new WeakMap();
108
+ // Register the projection accumulator (optional: only when sessionProjections
109
+ // is composed; headless assemblies stay unaffected).
110
+ ctx.inject(['sessionProjections'], (pctx) => {
111
+ pctx.sessionProjections.register({
112
+ key: MEMORY_REVIEW_PROJECTION_KEY,
113
+ schema: accumulatorSchema,
114
+ init: () => emptyAccumulator,
115
+ apply: applyAccumulator,
116
+ view: (state) => state,
117
+ stateVersion: 1,
118
+ });
119
+ });
120
+ // Periodic review: drain the accumulator on agent/pre-step.
121
+ if (resolved.reviewEnabled) {
122
+ ctx.on('agent/pre-step', async ({ agent, signal }, next) => {
123
+ if (!signal.aborted) {
124
+ try {
125
+ await maybeRunReview(ctx, agent, resolved.reviewCandidateThreshold, highWaterMarks);
126
+ }
127
+ catch (_reviewError) {
128
+ // Best-effort: a review failure must never block the step.
129
+ }
130
+ }
131
+ return next();
132
+ });
133
+ }
134
+ // Flush on compaction/end (fire-and-forget; never blocks compaction).
135
+ if (resolved.flushOnCompaction) {
136
+ ctx.on('session/event', (session, event) => {
137
+ if (event.type !== 'compaction/end')
138
+ return;
139
+ if (event.data.error !== undefined)
140
+ return;
141
+ void flushOnCompaction(ctx, session, event.data.compactionId).catch(() => {
142
+ // Best-effort: a flush failure is logged by the runtime, not thrown here.
143
+ });
144
+ });
145
+ }
146
+ // Flush on session/disposed (fire-and-forget; never blocks dispose).
147
+ if (resolved.flushOnDispose) {
148
+ ctx.on('session/disposed', (session) => {
149
+ void flushOnDispose(ctx, session).catch(() => {
150
+ // Best-effort: dispose must not block on memory extraction.
151
+ });
152
+ });
153
+ }
154
+ }
155
+ /** Read the projection snapshot and run one review extraction if the threshold is met. */
156
+ async function maybeRunReview(ctx, agent, threshold, highWaterMarks) {
157
+ const projections = ctx.get('sessionProjections');
158
+ if (projections === undefined)
159
+ return;
160
+ const session = agent.session;
161
+ const snapshot = projections.snapshot(session);
162
+ const state = snapshot.values[MEMORY_REVIEW_PROJECTION_KEY];
163
+ if (state === undefined)
164
+ return;
165
+ const mark = highWaterMarks.get(session) ?? -1;
166
+ const unprocessed = state.candidates.filter(candidate => candidate.seq > mark);
167
+ if (unprocessed.length < threshold)
168
+ return;
169
+ await runReviewExtraction(ctx, agent, unprocessed);
170
+ const nextMark = unprocessed.reduce((max, candidate) => Math.max(max, candidate.seq), mark);
171
+ highWaterMarks.set(session, nextMark);
172
+ }
173
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/review/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,CAAC,MAAM,0BAA0B,CAAA;AASxC,OAAO,EACL,4BAA4B,EAC5B,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EAChB,WAAW,GACZ,MAAM,kBAAkB,CAAA;AAEzB,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAA;AAEtE,mCAAmC;AACnC,MAAM,CAAC,MAAM,IAAI,GAAG,eAAe,CAAA;AAEnC;2EAC2E;AAC3E,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,KAAK,CAAC,CAAA;AAc7B,MAAM,CAAC,MAAM,MAAM,GAAc,CAAC,CAAC,MAAM,CAAC;IACxC,aAAa,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC;IACxC,w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AAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,4BAA4B,CAAiC,CAAA;IAC3F,IAAI,KAAK,KAAK,SAAS;QAAE,OAAM;IAC/B,MAAM,IAAI,GAAG,cAAc,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAA;IAC9C,MAAM,WAAW,GAAG,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC,SAAS,CAAC,GAAG,GAAG,IAAI,CAAC,CAAA;IAC9E,IAAI,WAAW,CAAC,MAAM,GAAG,SAAS;QAAE,OAAM;IAC1C,MAAM,mBAAmB,CAAC,GAAG,EAAE,KAAK,EAAE,WAAW,CAAC,CAAA;IAClD,MAAM,QAAQ,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,SAAS,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,SAAS,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,CAAA;IAC3F,cAAc,CAAC,GAAG,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAA;AACvC,CAAC"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Content scanner for the long-term memory domain: pure functions that detect
3
+ * secrets, prompt-injection patterns, and exfiltration attempts before content
4
+ * is persisted. Every memory write — whether from a model tool call or a
5
+ * background review/flush — passes through {@link scanContent} before the
6
+ * store accepts it.
7
+ *
8
+ * The scanner is deliberately a dependency-free pure module shared by the tool
9
+ * Consumer and the review function plugin without importing each other.
10
+ *
11
+ * @module @chenhw7/dsh-memory/scanner
12
+ */
13
+ import type { ScanResult } from './types.ts';
14
+ /**
15
+ * Scan content for secrets, prompt injection, and exfiltration patterns.
16
+ *
17
+ * @param content - The text to scan.
18
+ * @returns `allowed: true` when all checks pass; `allowed: false` with reasons when any pattern matches.
19
+ */
20
+ export declare function scanContent(content: string): ScanResult;
21
+ //# sourceMappingURL=scanner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scanner.d.ts","sourceRoot":"","sources":["../src/scanner.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AA8C5C;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,UAAU,CAuBvD"}
package/lib/scanner.js ADDED
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Content scanner for the long-term memory domain: pure functions that detect
3
+ * secrets, prompt-injection patterns, and exfiltration attempts before content
4
+ * is persisted. Every memory write — whether from a model tool call or a
5
+ * background review/flush — passes through {@link scanContent} before the
6
+ * store accepts it.
7
+ *
8
+ * The scanner is deliberately a dependency-free pure module shared by the tool
9
+ * Consumer and the review function plugin without importing each other.
10
+ *
11
+ * @module @chenhw7/dsh-memory/scanner
12
+ */
13
+ /** API key and token patterns (high-confidence secrets). */
14
+ const SECRET_PATTERNS = [
15
+ { name: 'DeepSeek API key', re: /sk-[a-f0-9]{32,}/i },
16
+ { name: 'OpenAI API key', re: /sk-[a-zA-Z0-9]{48,}/ },
17
+ { name: 'Anthropic API key', re: /sk-ant-[a-zA-Z0-9]{40,}/ },
18
+ { name: 'GitHub token', re: /gh[pousr]_[A-Za-z0-9]{36,}/ },
19
+ { name: 'AWS access key', re: /AKIA[0-9A-Z]{16}/ },
20
+ { name: 'AWS secret key', re: /(?<![A-Za-z0-9/+])[A-Za-z0-9/+]{40}(?![A-Za-z0-9/+])/ },
21
+ { name: 'Generic Bearer token', re: /Bearer\s+[a-z0-9._~+/=-]{20,}/i },
22
+ { name: 'JWT', re: /eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/ },
23
+ { name: 'SSH private key header', re: /-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----/ },
24
+ { name: 'Slack token', re: /xox[baprs]-[A-Za-z0-9-]{10,}/ },
25
+ { name: 'Google API key', re: /AIza[0-9A-Za-z_-]{35}/ },
26
+ ];
27
+ /** Prompt-injection patterns: instruction-like text that could hijack later reads. */
28
+ const INJECTION_PATTERNS = [
29
+ { name: 'ignore previous instructions', re: /ignore\s+(?:all\s+)?previous\s+instructions/i },
30
+ { name: 'disregard prior', re: /disregard\s+(?:all\s+)?(?:prior|previous|above)\s+(?:instructions|prompts|messages)/i },
31
+ { name: 'you are now', re: /you\s+are\s+now\s+(?:a|an)\s+/i },
32
+ { name: 'forget everything', re: /forget\s+(?:everything|all\s+(?:prior|previous)\s+(?:instructions|context))/i },
33
+ { name: 'new system prompt', re: /new\s+system\s+prompt/i },
34
+ { name: 'act as a different', re: /act\s+as\s+a\s+(?:different|new)\s+/i },
35
+ { name: 'do not follow', re: /do\s+not\s+follow\s+(?:any\s+)?(?:previous|prior|above)\s+(?:instructions|rules)/i },
36
+ { name: 'override instructions', re: /override\s+(?:all\s+)?(?:previous|prior|system)\s+\w*\s*instructions/i },
37
+ { name: 'system: ignore', re: /\[?system\]?\s*:\s*ignore/i },
38
+ ];
39
+ /** Exfiltration patterns: content that tries to induce tool calls or data egress on later reads. */
40
+ const EXFILTRATION_PATTERNS = [
41
+ { name: 'curl/wget exfil', re: /(?:curl|wget)\s+(?:https?:\/\/|ftp:\/\/)[^\s]+\s+\$?\{?(?:DSH_|DEEPSEEK_|API_|SECRET_|TOKEN_|KEY_)/i },
42
+ { name: 'env var leak', re: /(?:print|echo|cat|export)\s+\$?\{?(?:DSH_|DEEPSEEK_|API_|SECRET_|TOKEN_|KEY_)[A-Z_]+/i },
43
+ { name: 'base64 exfil', re: /(?:base64|eval)\s+--?decode\s+\$?\{?(?:DSH_|DEEPSEEK_|API_|SECRET_|TOKEN_|KEY_)/i },
44
+ { name: 'send credentials', re: /send\s+(?:the\s+)?(?:api\s+)?(?:key|token|secret|credential)s?\s+to\s+/i },
45
+ ];
46
+ /**
47
+ * Scan content for secrets, prompt injection, and exfiltration patterns.
48
+ *
49
+ * @param content - The text to scan.
50
+ * @returns `allowed: true` when all checks pass; `allowed: false` with reasons when any pattern matches.
51
+ */
52
+ export function scanContent(content) {
53
+ if (content.length === 0) {
54
+ return { allowed: true, reasons: [] };
55
+ }
56
+ const hits = [];
57
+ for (const { name, re } of SECRET_PATTERNS) {
58
+ if (re.test(content))
59
+ hits.push({ kind: 'secret', pattern: name });
60
+ }
61
+ for (const { name, re } of INJECTION_PATTERNS) {
62
+ if (re.test(content))
63
+ hits.push({ kind: 'injection', pattern: name });
64
+ }
65
+ for (const { name, re } of EXFILTRATION_PATTERNS) {
66
+ if (re.test(content))
67
+ hits.push({ kind: 'exfiltration', pattern: name });
68
+ }
69
+ if (hits.length === 0) {
70
+ return { allowed: true, reasons: [] };
71
+ }
72
+ const reasons = hits.map(hit => `${hit.kind}: ${hit.pattern}`);
73
+ return { allowed: false, reasons };
74
+ }
75
+ //# sourceMappingURL=scanner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scanner.js","sourceRoot":"","sources":["../src/scanner.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAYH,4DAA4D;AAC5D,MAAM,eAAe,GAA8D;IACjF,EAAE,IAAI,EAAE,kBAAkB,EAAE,EAAE,EAAE,mBAAmB,EAAE;IACrD,EAAE,IAAI,EAAE,gBAAgB,EAAE,EAAE,EAAE,qBAAqB,EAAE;IACrD,EAAE,IAAI,EAAE,mBAAmB,EAAE,EAAE,EAAE,yBAAyB,EAAE;IAC5D,EAAE,IAAI,EAAE,cAAc,EAAE,EAAE,EAAE,4BAA4B,EAAE;IAC1D,EAAE,IAAI,EAAE,gBAAgB,EAAE,EAAE,EAAE,kBAAkB,EAAE;IAClD,EAAE,IAAI,EAAE,gBAAgB,EAAE,EAAE,EAAE,sDAAsD,EAAE;IACtF,EAAE,IAAI,EAAE,sBAAsB,EAAE,EAAE,EAAE,gCAAgC,EAAE;IACtE,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE,kEAAkE,EAAE;IACvF,EAA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store. Opens a `memory`
3
+ * domain with one table (`entries`) keyed by `MemoryId` and implements the
4
+ * {@link MemoryStore} abstract service against it. Reads are synchronous from
5
+ * the domain's authoritative in-memory state; writes serialize on the domain's
6
+ * write chain and reach the backend before updating memory.
7
+ *
8
+ * The provider is a function plugin that mounts on `ctx.memory` after the
9
+ * `storage-domain` facility is available.
10
+ *
11
+ * @module @chenhw7/dsh-memory/store
12
+ */
13
+ import type { Context } from '@deepseek-ai/cordis';
14
+ /** Cordis plugin name. */
15
+ export declare const name = "memory-store-domain";
16
+ /** Services required before this provider can mount. */
17
+ export declare const inject: string[];
18
+ /**
19
+ * Mount the storage-domain memory store provider. Opens the `memory` domain
20
+ * and registers a {@link MemoryStore} subclass on `ctx.memory`.
21
+ * @param ctx - Cordis context with `storageDomain` injected.
22
+ */
23
+ export declare function apply(ctx: Context): Promise<void>;
24
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/store/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAwClD,0BAA0B;AAC1B,eAAO,MAAM,IAAI,wBAAwB,CAAA;AAEzC,wDAAwD;AACxD,eAAO,MAAM,MAAM,UAAoB,CAAA;AAEvC;;;;GAIG;AACH,wBAAsB,KAAK,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAOvD"}
@@ -0,0 +1,137 @@
1
+ /**
2
+ * storage-domain provider for the long-term memory store. Opens a `memory`
3
+ * domain with one table (`entries`) keyed by `MemoryId` and implements the
4
+ * {@link MemoryStore} abstract service against it. Reads are synchronous from
5
+ * the domain's authoritative in-memory state; writes serialize on the domain's
6
+ * write chain and reach the backend before updating memory.
7
+ *
8
+ * The provider is a function plugin that mounts on `ctx.memory` after the
9
+ * `storage-domain` facility is available.
10
+ *
11
+ * @module @chenhw7/dsh-memory/store
12
+ */
13
+ import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain';
14
+ import { z } from 'zod';
15
+ import { MemoryStore, MemoryId, scanContent, validateProjectScope } from "../index.js";
16
+ /** Zod schema for one memory entry record on the durable medium. */
17
+ const memoryEntrySchema = z.object({
18
+ id: z.string().min(1),
19
+ scope: z.enum(['global', 'project', 'user']),
20
+ category: z.enum(['failure', 'correction', 'insight', 'preference', 'convention', 'tool-quirk']).optional(),
21
+ content: z.string(),
22
+ projectName: z.string().optional(),
23
+ createdAt: z.number(),
24
+ updatedAt: z.number(),
25
+ });
26
+ /** The memory domain spec: one table of memory entries keyed by id. */
27
+ const memoryDomainSpec = defineDomain({
28
+ name: 'memory',
29
+ version: 0,
30
+ tables: {
31
+ entries: domainTable(memoryEntrySchema),
32
+ },
33
+ });
34
+ /** Cordis plugin name. */
35
+ export const name = 'memory-store-domain';
36
+ /** Services required before this provider can mount. */
37
+ export const inject = ['storageDomain'];
38
+ /**
39
+ * Mount the storage-domain memory store provider. Opens the `memory` domain
40
+ * and registers a {@link MemoryStore} subclass on `ctx.memory`.
41
+ * @param ctx - Cordis context with `storageDomain` injected.
42
+ */
43
+ export async function apply(ctx) {
44
+ const domain = await ctx.storageDomain.open(memoryDomainSpec);
45
+ const entries = domain.table('entries');
46
+ ctx.effect(() => async () => { await domain.close(); });
47
+ ctx.provide('memory', new DomainMemoryStore(entries));
48
+ }
49
+ /**
50
+ * MemoryStore implementation backed by a storage-domain KV table.
51
+ * Reads are synchronous from memory; writes serialize on the domain chain.
52
+ */
53
+ class DomainMemoryStore extends MemoryStore {
54
+ entries;
55
+ constructor(entries) {
56
+ super();
57
+ this.entries = entries;
58
+ }
59
+ async add(input) {
60
+ validateProjectScope(input);
61
+ const scan = scanContent(input.content);
62
+ if (!scan.allowed) {
63
+ throw new Error(`memory content rejected by scanner: ${scan.reasons.join('; ')}`);
64
+ }
65
+ const now = Date.now();
66
+ const id = MemoryId();
67
+ const entry = {
68
+ id,
69
+ scope: input.scope,
70
+ category: input.category,
71
+ content: input.content,
72
+ projectName: input.projectName,
73
+ createdAt: now,
74
+ updatedAt: now,
75
+ };
76
+ await this.entries.put(id, entry);
77
+ return { entry };
78
+ }
79
+ get(id) {
80
+ return this.entries.get(id);
81
+ }
82
+ list(scope, projectName) {
83
+ const results = [];
84
+ for (const [, entry] of this.entries.entries()) {
85
+ if (scope !== undefined && entry.scope !== scope)
86
+ continue;
87
+ if (projectName !== undefined && entry.projectName !== projectName)
88
+ continue;
89
+ results.push(entry);
90
+ }
91
+ return results.sort((a, b) => a.createdAt - b.createdAt);
92
+ }
93
+ async update(id, input) {
94
+ const existing = this.entries.get(id);
95
+ if (existing === undefined)
96
+ return undefined;
97
+ const newContent = input.content ?? existing.content;
98
+ const scan = scanContent(newContent);
99
+ if (!scan.allowed) {
100
+ throw new Error(`memory content rejected by scanner: ${scan.reasons.join('; ')}`);
101
+ }
102
+ const updated = {
103
+ ...existing,
104
+ content: newContent,
105
+ category: input.category ?? existing.category,
106
+ updatedAt: Date.now(),
107
+ };
108
+ await this.entries.put(id, updated);
109
+ return updated;
110
+ }
111
+ async remove(id) {
112
+ return this.entries.delete(id);
113
+ }
114
+ search(query) {
115
+ const limit = query.limit ?? 50;
116
+ let all = [];
117
+ for (const [, entry] of this.entries.entries()) {
118
+ if (query.scope !== undefined && entry.scope !== query.scope)
119
+ continue;
120
+ if (query.category !== undefined && entry.category !== query.category)
121
+ continue;
122
+ if (query.projectName !== undefined && entry.projectName !== query.projectName)
123
+ continue;
124
+ if (query.query !== undefined && query.query.length > 0) {
125
+ const needle = query.query.toLowerCase();
126
+ if (!entry.content.toLowerCase().includes(needle))
127
+ continue;
128
+ }
129
+ all.push(entry);
130
+ }
131
+ all.sort((a, b) => b.updatedAt - a.updatedAt);
132
+ const total = all.length;
133
+ all = limit > 0 ? all.slice(0, limit) : all;
134
+ return { entries: all, total };
135
+ }
136
+ }
137
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+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;oBAAE,SAAQ;YAC7D,CAAC;YACD,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;QACjB,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,CAAC,CAAA;QAC7C,MAAM,KAAK,GAAG,GAAG,CAAC,MAAM,CAAA;QACxB,GAAG,GAAG,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAA;QAC3C,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,CAAA;IAChC,CAAC;CACF"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Model-facing tools over the long-term memory service. Registers six tools on
3
+ * `ctx.tools`: `memory_search`, `memory_add`, `memory_replace`,
4
+ * `memory_remove`, `memory_list`, and `memory_get`. Each tool reads the
5
+ * optional `memory` service through `ctx.get('memory')` and fails loud when no
6
+ * provider is composed. Write paths run content through {@link scanContent} at
7
+ * the tool boundary so the model sees a clean rejection before the store is
8
+ * asked to persist.
9
+ *
10
+ * @module @chenhw7/dsh-memory/tool
11
+ */
12
+ import type { Context } from '@deepseek-ai/cordis';
13
+ import z from '@deepseek-ai/schemastery';
14
+ export declare const name = "tool-memory";
15
+ export declare const inject: string[];
16
+ /** Model-facing memory tool configuration. */
17
+ export interface Config {
18
+ /** Maximum entries a `memory_search` returns when the call omits `limit`. */
19
+ maxSearchResults: number;
20
+ }
21
+ /** Schemastery configuration for the memory tool consumer. */
22
+ export declare const Config: z<Schemastery.ObjectS<{
23
+ maxSearchResults: z<number, number>;
24
+ }>, Schemastery.ObjectT<{
25
+ maxSearchResults: z<number, number>;
26
+ }>>;
27
+ /**
28
+ * Register the six memory tools on `ctx.tools`.
29
+ * @param ctx - registrant context carrying the tool registry.
30
+ * @param config - deployment's search-result cap.
31
+ */
32
+ export declare function apply(ctx: Context, config: Config): void;
33
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/tool/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAWxC,eAAO,MAAM,IAAI,gBAAgB,CAAA;AACjC,eAAO,MAAM,MAAM,UAAY,CAAA;AAU/B,8CAA8C;AAC9C,MAAM,WAAW,MAAM;IACrB,6EAA6E;IAC7E,gBAAgB,EAAE,MAAM,CAAA;CACzB;AAED,8DAA8D;AAC9D,eAAO,MAAM,MAAM;;;;GAEjB,CAAA;AAiIF;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CA2VxD"}