dsh-snail-memory 0.0.0-stage → 0.1.6

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 (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +139 -2
  3. package/cordis.patch.yml +3 -0
  4. package/dist/api/command.d.ts +3 -0
  5. package/dist/api/command.js +73 -0
  6. package/dist/api/controller.d.ts +70 -0
  7. package/dist/api/controller.js +156 -0
  8. package/dist/api/errors.d.ts +6 -0
  9. package/dist/api/errors.js +29 -0
  10. package/dist/api/http.d.ts +17 -0
  11. package/dist/api/http.js +54 -0
  12. package/dist/api/index.d.ts +3 -0
  13. package/dist/api/index.js +29 -0
  14. package/dist/api/validate.d.ts +2 -0
  15. package/dist/api/validate.js +110 -0
  16. package/dist/client.js +2352 -0
  17. package/dist/context/message-source.d.ts +8 -0
  18. package/dist/context/message-source.js +1 -0
  19. package/dist/context/service.d.ts +62 -0
  20. package/dist/context/service.js +233 -0
  21. package/dist/context/snapshot.d.ts +22 -0
  22. package/dist/context/snapshot.js +62 -0
  23. package/dist/context/tool.d.ts +6 -0
  24. package/dist/context/tool.js +125 -0
  25. package/dist/contract.d.ts +115 -0
  26. package/dist/contract.js +5 -0
  27. package/dist/index.d.ts +17 -0
  28. package/dist/index.js +190 -0
  29. package/dist/lifecycle/activity.d.ts +70 -0
  30. package/dist/lifecycle/activity.js +104 -0
  31. package/dist/lifecycle/consolidate.d.ts +13 -0
  32. package/dist/lifecycle/consolidate.js +118 -0
  33. package/dist/lifecycle/counters.d.ts +17 -0
  34. package/dist/lifecycle/counters.js +67 -0
  35. package/dist/lifecycle/distill.d.ts +24 -0
  36. package/dist/lifecycle/distill.js +91 -0
  37. package/dist/lifecycle/index.d.ts +14 -0
  38. package/dist/lifecycle/index.js +7 -0
  39. package/dist/lifecycle/llm.d.ts +50 -0
  40. package/dist/lifecycle/llm.js +164 -0
  41. package/dist/lifecycle/retention.d.ts +12 -0
  42. package/dist/lifecycle/retention.js +45 -0
  43. package/dist/lifecycle/scheduler.d.ts +88 -0
  44. package/dist/lifecycle/scheduler.js +689 -0
  45. package/dist/lifecycle/service.d.ts +73 -0
  46. package/dist/lifecycle/service.js +299 -0
  47. package/dist/lifecycle/settings.d.ts +13 -0
  48. package/dist/lifecycle/settings.js +107 -0
  49. package/dist/lifecycle/writer-runtime.d.ts +25 -0
  50. package/dist/lifecycle/writer-runtime.js +70 -0
  51. package/dist/runtime.d.ts +52 -0
  52. package/dist/runtime.js +144 -0
  53. package/dist/safety/index.d.ts +5 -0
  54. package/dist/safety/index.js +4 -0
  55. package/dist/safety/policy.d.ts +5 -0
  56. package/dist/safety/policy.js +27 -0
  57. package/dist/safety/redact.d.ts +3 -0
  58. package/dist/safety/redact.js +21 -0
  59. package/dist/safety/scanner.d.ts +2 -0
  60. package/dist/safety/scanner.js +103 -0
  61. package/dist/safety/types.d.ts +39 -0
  62. package/dist/safety/types.js +14 -0
  63. package/dist/store/aggregate.d.ts +5 -0
  64. package/dist/store/aggregate.js +20 -0
  65. package/dist/store/chunks.d.ts +8 -0
  66. package/dist/store/chunks.js +35 -0
  67. package/dist/store/json.d.ts +10 -0
  68. package/dist/store/json.js +157 -0
  69. package/dist/store/lock.d.ts +42 -0
  70. package/dist/store/lock.js +263 -0
  71. package/dist/store/paths.d.ts +20 -0
  72. package/dist/store/paths.js +45 -0
  73. package/dist/store/projections.d.ts +5 -0
  74. package/dist/store/projections.js +140 -0
  75. package/dist/store/records.d.ts +5 -0
  76. package/dist/store/records.js +41 -0
  77. package/dist/store/store.d.ts +54 -0
  78. package/dist/store/store.js +576 -0
  79. package/dist/store/types.d.ts +178 -0
  80. package/dist/store/types.js +6 -0
  81. package/dist/time.d.ts +3 -0
  82. package/dist/time.js +15 -0
  83. package/dsh.plugin.json +31 -0
  84. package/package.json +127 -4
  85. package/plugin.json +31 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 snaiheihei
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,140 @@
1
- # Temporary Holding Version
1
+ # Snail Memory
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ DeepSeek Harness(dsh)插件:单用户、**全局 / workspace 分层**的记忆。在 Web 面板里查看、控制记忆条目,调整对话记忆的整理与整合;启用后索引常驻上下文、详情按需加载,每个对话手动选择要加载的记忆层。
4
+
5
+ > Layered single-user global and workspace memory for DeepSeek Harness, with a web panel to browse entries and tune distillation and consolidation, an index kept in context with records loaded on demand, and a per-session choice of layer.
6
+
7
+ - npm 包名:`dsh-snail-memory`
8
+ - 源码:<https://github.com/snaiheihei/dsh-snail-memory>
9
+ - 兼容:dsh `>=0.2.1-rc.3 <0.3.0-0`,Node `>=22.19.0`
10
+ - 协议:MIT
11
+
12
+ ## 功能
13
+
14
+ - **两级记忆**:`global`(跨工作区)与 `workspace`(绑定单个工作区)相互独立,各自有 revision。
15
+ - **显式开关**:记忆不会自动进入上下文。每个 Session 里手动启用某一层,用 `refresh` 生成新快照,`disable` 关闭。
16
+ - **只追加注入**:快照通过 `agent.inject()` 作为一条 `user` 消息追加(`source.kind = "snail-memory"`),插件从不改写、替换或删除既有会话消息。
17
+ - **可对账的注入**:每次注入带稳定 `injectionId`,区分 `desired → queued → committed`;只有观察到会话里真正落盘的 `user/message` 才算 committed,重启后按会话日志对账,不会重复注入。
18
+ - **生命周期维护**:统计完成的真实用户轮次,按空闲时间蒸馏记忆,分别调度 workspace 与 global 的 consolidation,并按分类执行 retention 清理。会话活动只推进内存中的空闲期限,最近一次 transcript 不可用的 Session 会退避重试并在有限次数后放弃。
19
+ - **模型工具**:`snail_memory_read`(按 id 读取,大对象先返回分片清单)、`snail_memory_feedback`(对已 committed 快照里的记忆打 helpful / unhelpful / incorrect)。
20
+ - **斜杠命令**:`/memory status`、`/memory remember workspace <text>`、`/memory correct workspace <id> <text>`、`/memory forget workspace <id>`。
21
+ - **Web UI**:输入框左侧记忆按钮,侧栏 `Memory` 面板(全局 / 工作区 / 设置三个标签),可查看条目、引用、最近一次已提交快照与 token 估算。
22
+ - **单写者**:同一数据根目录下允许多个 Host 启动,但只有一个持有写锁,其余自动只读;锁有心跳与 stale 回收,写操作带 fencing 校验。
23
+
24
+ ## 安装
25
+
26
+ 任选一种,然后重启 Host 并刷新页面。
27
+
28
+ ```powershell
29
+ # 1) 从 npm 安装
30
+ dsh plugin --profile web add dsh-snail-memory
31
+
32
+ # 2) 从 tarball 安装
33
+ dsh plugin --profile web add .\dsh-snail-memory-0.1.0.tgz
34
+
35
+ # 3) 从解压后的目录安装
36
+ dsh plugin --profile web add .\dsh-snail-memory
37
+
38
+ # 4) 从 Git 安装(需要该 tag/commit 带上构建产物)
39
+ dsh plugin --profile web add github:snaiheihei/dsh-snail-memory#v0.1.0
40
+ ```
41
+
42
+ 装完先确认组合层生效,再启动:
43
+
44
+ ```powershell
45
+ dsh --profile web --dump-config # 应出现 "# == dsh-snail-memory"
46
+ ```
47
+
48
+ 卸载:`dsh plugin --profile web remove dsh-snail-memory`。
49
+
50
+ ## 使用
51
+
52
+ 1. 打开一个 Session,点击输入框左侧的记忆按钮,选择 **global** 或 **workspace** 启用。
53
+ 2. 启用后当前记忆索引会作为一条快照注入;之后对话中可随时 `refresh` 生成新快照。
54
+ 3. 侧栏 `Memory` 面板可浏览条目、查看详情、删除、promote 到 global,以及调整全局设置。
55
+ 4. 需要沉淀新记忆时用 `/memory remember workspace <text>`,或让模型在对话中写入;读取与反馈由两个工具完成。
56
+
57
+ 快照里的 token 数字是**估算值**,用于控制上下文预算,不代表 provider 的精确 usage。
58
+
59
+ ## 配置
60
+
61
+ 配置写在 profile 的 `cordis.patch.yml` 中,按行 id `snail-memory` 覆盖。**patch 会整体替换该行的 `config`**,所以需要把想保留的键一起写全:
62
+
63
+ ```yaml
64
+ - id: snail-memory
65
+ config:
66
+ provider: deepseek
67
+ model: deepseek-chat
68
+ reviewEveryUserTurns: 15
69
+ idleDelayMinutes: 60
70
+ consolidationCooldownHours: 20
71
+ globalConsolidationCooldownDays: 7
72
+ retentionSweepHours: 24
73
+ ```
74
+
75
+ | 键 | 默认值 | 说明 |
76
+ | --- | --- | --- |
77
+ | `dshHome` | 宿主解析值 | 数据根目录;默认跟随 `DSH_HOME` |
78
+ | `provider` / `model` | 未设置 | 辅助模型路由。留空时从当前 agent 列表中选择可用模型 |
79
+ | `reviewEveryUserTurns` | `15` | 每累计多少个完成的用户轮次触发一次记忆蒸馏 |
80
+ | `idleDelayMinutes` | `60` | 会话空闲多久后触发蒸馏 |
81
+ | `consolidationCooldownHours` | `20` | workspace consolidation 冷却时间;一次 dirty 窗口只在首次需要排期时定时,后续写入不再推迟 |
82
+ | `globalConsolidationCooldownDays` | `7` | global consolidation 冷却时间,语义同上 |
83
+ | `retentionSweepHours` | `24` | retention 清理的间隔 |
84
+
85
+ ## 数据位置
86
+
87
+ 默认在 `$DSH_HOME/snail_memory/`(设置了 `config.dshHome` 时随之变化):
88
+
89
+ ```text
90
+ snail_memory/
91
+ ├── state.v2.json # 唯一权威状态(原子发布)
92
+ ├── details/ # 可重建的 Markdown 投影
93
+ ├── detail-data/ # 详情记录(按 revision)
94
+ ├── global/
95
+ ├── workspaces/
96
+ ├── settings.v1.json
97
+ ├── audit.v1.jsonl # 只记 operation / revision / 时间
98
+ ├── projection-pending.v1.json
99
+ └── lock.json # 单写者锁(心跳 + fencing)
100
+ ```
101
+
102
+ Markdown 投影可以从 `state.v2.json` 重建,两者不是双事实源。审计日志只记录操作元数据,不记录提示词、记忆正文或路径。
103
+
104
+ ## 隐私与安全
105
+
106
+ - 记忆数据只落在本地 `$DSH_HOME` 下,不采集遥测、不上传到第三方。
107
+ - 蒸馏/合并需要调用模型时,走宿主注入的 `ctx.llm`,即你自己配置的 provider 与凭据;插件不自行发起网络请求。
108
+ - 写入与蒸馏前会做秘密扫描与长度限制,模型输出一律按不可信数据处理。
109
+ - 插件的 RPC 挂在宿主 `webServer` 的同源路由上(`/snail-memory/rpc/*`)。**请勿把 dsh Web 服务绑定到不受信任的网络**(`--host` 默认只监听本机)。
110
+
111
+ ## 开发
112
+
113
+ ```powershell
114
+ npm install
115
+ npm run build # tsc + esbuild,产出 dist/ 与 dist/client.js
116
+ npm run typecheck
117
+ npm test # vitest
118
+ npm run lint
119
+ npm pack # prepack 会自动构建
120
+ ```
121
+
122
+ 目录:
123
+
124
+ ```text
125
+ src/index.ts # Cordis 入口:inject / Config / apply
126
+ src/contract.ts # Host ↔ Client RPC 类型
127
+ src/api/ # 同源路由、命令、校验
128
+ src/context/ # 快照生成、注入对账、工具
129
+ src/lifecycle/ # 轮次统计、蒸馏、consolidation、retention、调度
130
+ src/store/ # 权威状态、写队列、锁、投影
131
+ client/src/ # slots、面板、locale、RPC 客户端
132
+ scripts/ # 构建脚本(Client handoff)
133
+ tests/ # 单元 / 集成 / 客户端测试
134
+ ```
135
+
136
+ Client 侧通过 `window.__ModuleLoader__.load({ id, factory })` 的 CJS closure-factory 装载,`react` / `react/jsx-runtime` 由宿主平台表提供,不打第二份 React。
137
+
138
+ ## License
139
+
140
+ [MIT](LICENSE) © 2026 snaiheihei
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: snail-memory
3
+ name: dsh-snail-memory
@@ -0,0 +1,3 @@
1
+ import type { CommandResult } from '@deepseek-ai/dsh-commands';
2
+ import type { MemoryController } from './controller.js';
3
+ export declare function executeMemoryCommand(controller: MemoryController, rawInput: string, sessionId: string): Promise<CommandResult>;
@@ -0,0 +1,73 @@
1
+ import { memoryId, workspaceId } from '../store/types.js';
2
+ import { formatBeijingTime } from '../time.js';
3
+ import { safeError } from './errors.js';
4
+ const USAGE = 'Usage: /memory status | remember workspace <text> | correct workspace <id> <text> | forget workspace <id>';
5
+ function formatScheduleTime(value) {
6
+ if (value === null || value === undefined)
7
+ return 'not scheduled';
8
+ return formatBeijingTime(value);
9
+ }
10
+ function scope(value) {
11
+ if (value === 'global')
12
+ return { kind: 'global' };
13
+ if (value === 'workspace')
14
+ return { kind: 'workspace', workspaceId: workspaceId('pending') };
15
+ return undefined;
16
+ }
17
+ export async function executeMemoryCommand(controller, rawInput, sessionId) {
18
+ const match = /^\s*(\S+)(?:\s+(global|workspace))?(?:\s+([\s\S]*))?\s*$/u.exec(rawInput);
19
+ const action = match?.[1];
20
+ const layer = match?.[2];
21
+ const rest = match?.[3]?.trim();
22
+ if (!action || !['remember', 'correct', 'forget', 'status'].includes(action))
23
+ return { kind: 'error', text: USAGE };
24
+ try {
25
+ if (action === 'status') {
26
+ if (layer || rest)
27
+ return { kind: 'error', text: USAGE };
28
+ const status = await controller.call('status', {});
29
+ const workspaceSchedules = Object.values(status.workspaceConsolidation).filter(consolidation => consolidation.dirty);
30
+ const nextConsolidationAt = workspaceSchedules.map(consolidation => consolidation.nextConsolidationAt)
31
+ .filter((value) => value !== null).sort()[0];
32
+ return { kind: 'success', text: `Snail Memory: ${status.writable ? 'writable' : 'read-only'}; dirty workspaces=${workspaceSchedules.length}; next workspace consolidation=${formatScheduleTime(nextConsolidationAt)}; next cleanup=${formatScheduleTime(status.nextRetentionAt)}` };
33
+ }
34
+ let target = scope(layer);
35
+ if (!target || !rest)
36
+ return { kind: 'error', text: USAGE };
37
+ if (target.kind === 'global') {
38
+ return { kind: 'error', text: 'Direct global writes are unavailable; use Promote from a workspace memory.' };
39
+ }
40
+ const attachedWorkspaceId = controller.workspaceForSession(sessionId);
41
+ if (!attachedWorkspaceId)
42
+ return { kind: 'error', text: 'Workspace memory requires a session attached to a workspace.' };
43
+ target = { kind: 'workspace', workspaceId: attachedWorkspaceId };
44
+ if (action === 'forget') {
45
+ if (/\s/u.test(rest))
46
+ return { kind: 'error', text: USAGE };
47
+ const result = await controller.call('remove', { scope: target, id: memoryId(rest) });
48
+ return { kind: 'success', text: result.removed ? 'Memory forgotten. Conversation history was not changed.' : 'Memory was already absent.' };
49
+ }
50
+ if (action === 'remember') {
51
+ const request = {
52
+ scope: target, category: 'project-convention',
53
+ summary: rest, detail: rest, sessionId,
54
+ };
55
+ const entry = await controller.call('remember', request);
56
+ return { kind: 'success', text: `Remembered ${entry.id} in ${target.kind} memory.` };
57
+ }
58
+ const separator = rest.search(/\s/u);
59
+ if (separator <= 0)
60
+ return { kind: 'error', text: USAGE };
61
+ const id = rest.slice(0, separator);
62
+ const text = rest.slice(separator).trim();
63
+ const existing = await controller.call('read', { scope: target, id: memoryId(id) });
64
+ const request = {
65
+ id: memoryId(id), scope: target, category: existing.category, summary: text, detail: text, sessionId,
66
+ };
67
+ await controller.call('correct', request);
68
+ return { kind: 'success', text: `Corrected ${id}.` };
69
+ }
70
+ catch (error) {
71
+ return { kind: 'error', text: safeError(error).message };
72
+ }
73
+ }
@@ -0,0 +1,70 @@
1
+ import type { ConsolidateMemoryResult, CorrectRequest, EnableRequest, LayerRequest, MemorySettings, MemoryStatus, ReadRequest, ScopeRequest, SessionRequest, SessionStateView, WorkspaceView, WriteRequest, RpcPayload, RpcValue, RpcMethod, MemoryOperationResult } from '../contract.js';
2
+ import type { MemoryContextService, InjectionAgent } from '../context/service.js';
3
+ import type { LifecycleIntentRunResult } from '../lifecycle/activity.js';
4
+ import { type MemoryStore } from '../store/store.js';
5
+ import type { MemoryEntry, MemoryId, MemoryIndex, MemoryScope, PromoteMemoryResult, UpsertMemoryInput, WorkspaceId } from '../store/types.js';
6
+ export interface ResolvedSession {
7
+ readonly agent: InjectionAgent;
8
+ readonly workspaceId?: WorkspaceId;
9
+ }
10
+ export interface MemoryWriteLifecycle {
11
+ remember(input: UpsertMemoryInput): Promise<MemoryEntry>;
12
+ correct(input: UpsertMemoryInput & {
13
+ id: MemoryId;
14
+ }): Promise<MemoryEntry>;
15
+ promote(scope: MemoryScope, id: MemoryId): Promise<PromoteMemoryResult>;
16
+ forget(scope: MemoryScope, id: MemoryId): Promise<boolean>;
17
+ }
18
+ export interface MemorySettingsLifecycle {
19
+ getSettings(): MemorySettings;
20
+ updateSettings(settings: MemorySettings): Promise<MemorySettings>;
21
+ }
22
+ export interface MemoryConsolidationLifecycle {
23
+ consolidateNow(scope: MemoryScope): Promise<LifecycleIntentRunResult>;
24
+ }
25
+ export interface MemoryControllerOptions {
26
+ readonly resolveSession: (sessionId: string) => ResolvedSession | undefined;
27
+ readonly isWorkspace?: (workspaceId: string) => boolean;
28
+ readonly lifecycle?: MemoryWriteLifecycle;
29
+ readonly settings?: MemorySettingsLifecycle;
30
+ readonly consolidation?: MemoryConsolidationLifecycle;
31
+ readonly listWorkspaces?: () => readonly WorkspaceView[];
32
+ readonly now?: () => Date;
33
+ }
34
+ export declare class MemoryController {
35
+ private readonly store;
36
+ private readonly context;
37
+ private readonly options;
38
+ private readonly now;
39
+ constructor(store: MemoryStore, context: MemoryContextService, options: MemoryControllerOptions);
40
+ workspaceForSession(sessionId: string): WorkspaceId | undefined;
41
+ call(method: 'getSessionState', payload: SessionRequest): Promise<SessionStateView>;
42
+ call(method: 'disable', payload: SessionRequest): Promise<MemoryOperationResult>;
43
+ call(method: 'enable', payload: EnableRequest): Promise<MemoryOperationResult>;
44
+ call(method: 'refresh', payload: LayerRequest): Promise<MemoryOperationResult>;
45
+ call(method: 'list', payload: ScopeRequest): Promise<MemoryIndex>;
46
+ call(method: 'consolidate', payload: ScopeRequest): Promise<ConsolidateMemoryResult>;
47
+ call(method: 'read', payload: ReadRequest): Promise<MemoryEntry>;
48
+ call(method: 'remove', payload: ReadRequest): Promise<{
49
+ removed: boolean;
50
+ }>;
51
+ call(method: 'promote', payload: ReadRequest): Promise<PromoteMemoryResult>;
52
+ call(method: 'remember', payload: WriteRequest): Promise<MemoryEntry>;
53
+ call(method: 'correct', payload: CorrectRequest): Promise<MemoryEntry>;
54
+ call(method: 'status', payload: Record<string, never>): Promise<MemoryStatus>;
55
+ call(method: 'getSettings', payload: Record<string, never>): Promise<MemorySettings>;
56
+ call(method: 'updateSettings', payload: MemorySettings): Promise<MemorySettings>;
57
+ call(method: 'listWorkspaces', payload: Record<string, never>): Promise<WorkspaceView[]>;
58
+ call(method: RpcMethod, payload: RpcPayload): Promise<RpcValue>;
59
+ private sessionState;
60
+ private enable;
61
+ private disable;
62
+ private list;
63
+ private consolidate;
64
+ private readMemory;
65
+ private writeMemory;
66
+ private forget;
67
+ private promote;
68
+ private assertWorkspace;
69
+ private settings;
70
+ }
@@ -0,0 +1,156 @@
1
+ import { pendingInjection } from '../store/store.js';
2
+ import { prepareMemoryCandidate } from '../safety/index.js';
3
+ import { MemoryApiError, safeError } from './errors.js';
4
+ export class MemoryController {
5
+ store;
6
+ context;
7
+ options;
8
+ now;
9
+ constructor(store, context, options) {
10
+ this.store = store;
11
+ this.context = context;
12
+ this.options = options;
13
+ this.now = options.now ?? (() => new Date());
14
+ }
15
+ workspaceForSession(sessionId) {
16
+ return this.store.getSessionState(sessionId).workspaceId ?? this.options.resolveSession(sessionId)?.workspaceId;
17
+ }
18
+ async call(method, payload) {
19
+ try {
20
+ switch (method) {
21
+ case 'getSessionState': return this.sessionState(payload.sessionId);
22
+ case 'enable': return await this.enable(payload, false);
23
+ case 'disable': return await this.disable(payload.sessionId);
24
+ case 'refresh': return await this.enable(payload, true);
25
+ case 'list': return this.list(payload.scope);
26
+ case 'consolidate': return await this.consolidate(payload.scope);
27
+ case 'read': return await this.readMemory(payload);
28
+ case 'remove': return { removed: await this.forget(payload) };
29
+ case 'promote': return await this.promote(payload);
30
+ case 'remember': return await this.writeMemory(payload, false);
31
+ case 'correct': return await this.writeMemory(payload, true);
32
+ case 'status': return { writable: this.store.writable, ...this.store.getMeta() };
33
+ case 'getSettings': return this.settings().getSettings();
34
+ case 'updateSettings': return await this.settings().updateSettings(payload);
35
+ case 'listWorkspaces': return [...(this.options.listWorkspaces?.() ?? [])];
36
+ }
37
+ }
38
+ catch (error) {
39
+ throw safeError(error);
40
+ }
41
+ }
42
+ sessionState(sessionId) {
43
+ const state = this.store.getSessionState(sessionId);
44
+ const resolvedWorkspace = state.workspaceId ?? this.options.resolveSession(sessionId)?.workspaceId;
45
+ const layerView = (layer) => {
46
+ const value = state.layers[layer];
47
+ const selected = layer === 'workspace' ? state.selectedWorkspaceId : undefined;
48
+ const desired = selected === undefined ? value.desired : value.desired.filter(item => (item.workspaceId ?? state.workspaceId) === selected);
49
+ const committed = selected === undefined ? value.committed : value.committed.filter(item => (item.workspaceId ?? state.workspaceId) === selected);
50
+ return {
51
+ enabled: value.enabled,
52
+ desiredRevision: desired.at(-1)?.revision ?? null,
53
+ committedRevision: committed.at(-1)?.revision ?? null,
54
+ pending: pendingInjection(state, layer).length,
55
+ lastTokens: committed.at(-1)?.tokens ?? 0,
56
+ committedTokens: value.committed.reduce((total, item) => total + item.tokens, 0),
57
+ };
58
+ };
59
+ return {
60
+ sessionId,
61
+ ...(resolvedWorkspace ? { workspaceId: resolvedWorkspace } : {}),
62
+ ...(state.selectedWorkspaceId ? { selectedWorkspaceId: state.selectedWorkspaceId } : {}),
63
+ layers: { global: layerView('global'), workspace: layerView('workspace') },
64
+ };
65
+ }
66
+ async enable(payload, refresh) {
67
+ const resolved = this.options.resolveSession(payload.sessionId);
68
+ if (!resolved)
69
+ throw new MemoryApiError('session-not-found', 'The session is not live.', 404);
70
+ if (refresh)
71
+ return this.context.refresh(resolved.agent, payload.layer);
72
+ if (payload.layer === 'global')
73
+ return this.context.enable(resolved.agent, payload.layer);
74
+ const selectedWorkspaceId = payload.workspaceId ?? resolved.workspaceId;
75
+ if (!selectedWorkspaceId) {
76
+ throw new MemoryApiError('workspace-required', 'Select a registered workspace to enable workspace memory.', 400);
77
+ }
78
+ this.assertWorkspace({ kind: 'workspace', workspaceId: selectedWorkspaceId });
79
+ return this.context.enable(resolved.agent, payload.layer, selectedWorkspaceId);
80
+ }
81
+ async disable(sessionId) {
82
+ const resolved = this.options.resolveSession(sessionId);
83
+ if (!resolved)
84
+ throw new MemoryApiError('session-not-found', 'The session is not live.', 404);
85
+ return this.context.disable(resolved.agent);
86
+ }
87
+ list(scope) {
88
+ this.assertWorkspace(scope, true);
89
+ return this.store.list(scope);
90
+ }
91
+ async consolidate(scope) {
92
+ this.assertWorkspace(scope, true);
93
+ if (!this.options.consolidation) {
94
+ throw new MemoryApiError('invalid-operation', 'Manual memory consolidation is unavailable.', 409);
95
+ }
96
+ const result = await this.options.consolidation.consolidateNow(scope);
97
+ return { intentId: result.intentId, written: result.written };
98
+ }
99
+ async readMemory(request) {
100
+ this.assertWorkspace(request.scope, true);
101
+ const entry = await this.store.read(request.scope, request.id);
102
+ if (!entry)
103
+ throw new MemoryApiError('memory-not-found', 'The memory entry does not exist.', 404);
104
+ return entry;
105
+ }
106
+ async writeMemory(request, correction) {
107
+ this.assertWorkspace(request.scope);
108
+ const clean = (text) => prepareMemoryCandidate(text, { source: 'explicit', mode: 'explicit' }).text;
109
+ const input = {
110
+ scope: request.scope,
111
+ category: request.category,
112
+ summary: clean(request.summary),
113
+ detail: clean(request.detail),
114
+ sourceRefs: request.sessionId ? [{ sessionId: request.sessionId }] : [],
115
+ lastVerifiedAt: this.now().toISOString(),
116
+ };
117
+ if (correction) {
118
+ const id = request.id;
119
+ // A correction rewrites the record, so carry the provenance it already has instead of
120
+ // replacing it with the editor's session.
121
+ const existing = await this.store.read(request.scope, id);
122
+ const sourceRefs = [...(existing?.sourceRefs ?? [])];
123
+ if (request.sessionId !== undefined && !sourceRefs.some(ref => ref.sessionId === request.sessionId)) {
124
+ sourceRefs.push({ sessionId: request.sessionId });
125
+ }
126
+ const corrected = { ...input, sourceRefs, id };
127
+ return this.options.lifecycle ? this.options.lifecycle.correct(corrected) : this.store.upsert(corrected);
128
+ }
129
+ return this.options.lifecycle ? this.options.lifecycle.remember(input) : this.store.upsert(input);
130
+ }
131
+ async forget(request) {
132
+ this.assertWorkspace(request.scope, true);
133
+ return this.options.lifecycle
134
+ ? this.options.lifecycle.forget(request.scope, request.id)
135
+ : this.store.remove(request.scope, request.id);
136
+ }
137
+ async promote(request) {
138
+ this.assertWorkspace(request.scope);
139
+ return this.options.lifecycle
140
+ ? this.options.lifecycle.promote(request.scope, request.id)
141
+ : this.store.promote(request.scope, request.id);
142
+ }
143
+ assertWorkspace(scope, allowGlobal = false) {
144
+ if (scope.kind === 'global' && !allowGlobal) {
145
+ throw new MemoryApiError('invalid-operation', 'Direct global writes are unavailable; promote a workspace memory instead.', 409);
146
+ }
147
+ if (scope.kind === 'workspace' && this.options.isWorkspace && !this.options.isWorkspace(scope.workspaceId)) {
148
+ throw new MemoryApiError('workspace-not-found', 'The workspace does not exist.', 404);
149
+ }
150
+ }
151
+ settings() {
152
+ if (!this.options.settings)
153
+ throw new MemoryApiError('invalid-operation', 'Lifecycle settings are unavailable.', 409);
154
+ return this.options.settings;
155
+ }
156
+ }
@@ -0,0 +1,6 @@
1
+ export declare class MemoryApiError extends Error {
2
+ readonly code: string;
3
+ readonly status: number;
4
+ constructor(code: string, message: string, status?: number);
5
+ }
6
+ export declare function safeError(error: unknown): MemoryApiError;
@@ -0,0 +1,29 @@
1
+ import { MemoryStoreReadonlyError } from '../store/store.js';
2
+ import { SafetyError } from '../safety/index.js';
3
+ export class MemoryApiError extends Error {
4
+ code;
5
+ status;
6
+ constructor(code, message, status = 400) {
7
+ super(message);
8
+ this.code = code;
9
+ this.status = status;
10
+ this.name = 'MemoryApiError';
11
+ }
12
+ }
13
+ export function safeError(error) {
14
+ if (error instanceof MemoryApiError)
15
+ return error;
16
+ if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'read-only') {
17
+ return new MemoryApiError('read-only', 'Snail Memory is read-only on this host.', 409);
18
+ }
19
+ if (error instanceof MemoryStoreReadonlyError || (error instanceof Error && error.name === 'MemoryStoreReadonlyError')) {
20
+ return new MemoryApiError('read-only', 'Snail Memory is read-only on this host.', 409);
21
+ }
22
+ if (error instanceof SafetyError) {
23
+ return new MemoryApiError(error.code, 'The memory contains content that cannot be stored safely.', 422);
24
+ }
25
+ if (error instanceof Error && /disabled|ungrouped|cannot move/i.test(error.message)) {
26
+ return new MemoryApiError('invalid-operation', error.message, 409);
27
+ }
28
+ return new MemoryApiError('internal', 'Snail Memory could not complete the operation.', 500);
29
+ }
@@ -0,0 +1,17 @@
1
+ import { type RpcMethod, type RpcPayload, type RpcValue } from '../contract.js';
2
+ export interface RpcDispatcher {
3
+ call(method: RpcMethod, payload: RpcPayload): Promise<RpcValue>;
4
+ }
5
+ export interface RpcRequest extends AsyncIterable<Uint8Array | string> {
6
+ method?: string | undefined;
7
+ url?: string | undefined;
8
+ headers: Record<string, string | string[] | undefined>;
9
+ }
10
+ export interface RpcResponse {
11
+ statusCode: number;
12
+ setHeader(name: string, value: string): void;
13
+ end(chunk?: string): void;
14
+ }
15
+ export declare function createRpcHandler(dispatcher: RpcDispatcher, options?: {
16
+ maxBodyBytes?: number;
17
+ }): (req: RpcRequest, res: RpcResponse) => Promise<void>;
@@ -0,0 +1,54 @@
1
+ import { RPC_METHODS, RPC_ROUTE_PREFIX } from '../contract.js';
2
+ import { MemoryApiError, safeError } from './errors.js';
3
+ import { validatePayload } from './validate.js';
4
+ function write(res, status, result) {
5
+ res.statusCode = status;
6
+ res.setHeader('content-type', 'application/json; charset=utf-8');
7
+ res.setHeader('cache-control', 'no-store');
8
+ res.end(JSON.stringify(result));
9
+ }
10
+ async function body(req, max) {
11
+ const chunks = [];
12
+ let size = 0;
13
+ for await (const chunk of req) {
14
+ const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
15
+ size += value.length;
16
+ if (size > max)
17
+ throw new MemoryApiError('body-too-large', 'Request body is too large.', 413);
18
+ chunks.push(value);
19
+ }
20
+ return Buffer.concat(chunks).toString('utf8');
21
+ }
22
+ export function createRpcHandler(dispatcher, options = {}) {
23
+ const maxBodyBytes = options.maxBodyBytes ?? 65_536;
24
+ return async function handleRpc(req, res) {
25
+ try {
26
+ const pathname = new URL(req.url ?? '/', 'http://snail-memory.local').pathname;
27
+ const methodName = pathname.startsWith(`${RPC_ROUTE_PREFIX}/`) ? pathname.slice(RPC_ROUTE_PREFIX.length + 1) : '';
28
+ if (!RPC_METHODS.includes(methodName))
29
+ throw new MemoryApiError('not-found', 'Unknown Snail Memory RPC method.', 404);
30
+ if (req.method !== 'POST')
31
+ throw new MemoryApiError('method-not-allowed', 'Only POST is supported.', 405);
32
+ const contentType = Array.isArray(req.headers['content-type']) ? req.headers['content-type'][0] : req.headers['content-type'];
33
+ if (!contentType?.toLowerCase().startsWith('application/json'))
34
+ throw new MemoryApiError('unsupported-media-type', 'Expected application/json.', 415);
35
+ if (req.headers['x-snail-memory'] !== '1')
36
+ throw new MemoryApiError('forbidden', 'Missing Snail Memory request header.', 403);
37
+ const raw = await body(req, maxBodyBytes);
38
+ let payload;
39
+ try {
40
+ payload = JSON.parse(raw);
41
+ }
42
+ catch {
43
+ throw new MemoryApiError('invalid-request', 'Malformed JSON request.');
44
+ }
45
+ const method = methodName;
46
+ const value = await dispatcher.call(method, validatePayload(method, payload));
47
+ write(res, 200, { ok: true, value });
48
+ }
49
+ catch (error) {
50
+ const safe = safeError(error);
51
+ write(res, safe.status, { ok: false, error: { code: safe.code, message: safe.message } });
52
+ }
53
+ };
54
+ }
@@ -0,0 +1,3 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { MemoryController } from './controller.js';
3
+ export declare function registerMemoryApi(ctx: Context, controller: MemoryController): () => void;
@@ -0,0 +1,29 @@
1
+ import { RPC_ROUTE_PREFIX } from '../contract.js';
2
+ import { executeMemoryCommand } from './command.js';
3
+ import { createRpcHandler } from './http.js';
4
+ export function registerMemoryApi(ctx, controller) {
5
+ const handler = createRpcHandler(controller);
6
+ const disposeRoute = ctx.webServer.register({ kind: 'prefix', path: RPC_ROUTE_PREFIX, handler });
7
+ let disposeCommand;
8
+ try {
9
+ disposeCommand = ctx.commands.register({
10
+ name: 'memory',
11
+ description: 'Remember, correct, forget, or inspect Snail Memory',
12
+ input: { hint: 'status | remember workspace <text> | correct workspace <id> <text> | forget workspace <id>' },
13
+ recordInput: false,
14
+ handler: invocation => executeMemoryCommand(controller, invocation.rawInput, invocation.agent.session.id),
15
+ });
16
+ }
17
+ catch (error) {
18
+ disposeRoute();
19
+ throw error;
20
+ }
21
+ let disposed = false;
22
+ return () => {
23
+ if (disposed)
24
+ return;
25
+ disposed = true;
26
+ disposeCommand();
27
+ disposeRoute();
28
+ };
29
+ }
@@ -0,0 +1,2 @@
1
+ import type { RpcMethod, RpcPayload } from '../contract.js';
2
+ export declare function validatePayload(method: RpcMethod, payload: unknown): RpcPayload;