@lykling/pi-supermemory 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +84 -2
- package/package.json +50 -4
- package/src/api.ts +247 -0
- package/src/config.ts +179 -0
- package/src/context.ts +107 -0
- package/src/index.ts +385 -0
- package/src/privacy.ts +10 -0
- package/src/tags.ts +157 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Pride Leong (lykling)
|
|
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,85 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-supermemory
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Supermemory](https://supermemory.ai) persistent memory for the
|
|
4
|
+
[pi coding agent](https://github.com/earendil-works/pi-mono) — and it **shares
|
|
5
|
+
the same memory store as your opencode supermemory plugin**.
|
|
6
|
+
|
|
7
|
+
Both agents derive identical per-repo container tags (`repo_<name>__<hash>`),
|
|
8
|
+
so anything you told opencode to remember is recalled by pi in the same
|
|
9
|
+
repository, and vice versa.
|
|
10
|
+
|
|
11
|
+
## What it does
|
|
12
|
+
|
|
13
|
+
- Registers a `supermemory` tool with modes: `add`, `search`, `list`,
|
|
14
|
+
`forget`, `profile`, `help` — the same interface as the opencode plugin.
|
|
15
|
+
- **Hybrid recall** (v0.2.0, the default `autoRecall: "hybrid"`):
|
|
16
|
+
- At the first prompt of a session it injects a *small deterministic
|
|
17
|
+
preload*: user profile + a recent-project snapshot (latest 3, with age
|
|
18
|
+
labels) + semantic search hits for the opening prompt, within a hard
|
|
19
|
+
character budget.
|
|
20
|
+
- For the rest of the session, per-turn reasoned recall: the tool's prompt
|
|
21
|
+
guidelines tell the model when to `search` (topic shift, references to
|
|
22
|
+
past decisions) and when to skip (self-contained or trivial messages).
|
|
23
|
+
- After context compaction, profile + snapshot are re-injected, because
|
|
24
|
+
the session-start block does not survive summarization.
|
|
25
|
+
- `add` refuses once on near-duplicates (similarity ≥ 0.9) and suggests
|
|
26
|
+
`forget`-then-`add`, keeping the store from stacking stale copies.
|
|
27
|
+
- Redacts `<private>...</private>` blocks before sending anything to the cloud.
|
|
28
|
+
- Reuses your existing Supermemory credentials — zero extra setup if you
|
|
29
|
+
already use opencode-supermemory.
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pi install npm:@lykling/pi-supermemory
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Configuration
|
|
38
|
+
|
|
39
|
+
API key resolution order (first match wins):
|
|
40
|
+
|
|
41
|
+
1. `SUPERMEMORY_API_KEY` environment variable
|
|
42
|
+
2. `~/.pi/agent/supermemory.json` — pi-native config:
|
|
43
|
+
```json
|
|
44
|
+
{ "apiKey": "sm_...", "autoRecall": "full" }
|
|
45
|
+
```
|
|
46
|
+
3. `~/.config/opencode/supermemory.jsonc` — shared with opencode
|
|
47
|
+
4. `~/.supermemory-opencode/credentials.json` — opencode device-flow login
|
|
48
|
+
|
|
49
|
+
Other options:
|
|
50
|
+
|
|
51
|
+
- `SUPERMEMORY_API_BASE_URL` — override `https://api.supermemory.ai`
|
|
52
|
+
- `SUPERMEMORY_REPO_TAG` — force a fixed container tag
|
|
53
|
+
- `SUPERMEMORY_ISOLATE_WORKTREES=true` — give each git worktree its own tag
|
|
54
|
+
- `autoRecall` in `~/.pi/agent/supermemory.json`:
|
|
55
|
+
`"hybrid"` (default; profile + recent snapshot + prompt search on both
|
|
56
|
+
scopes), `"full"` (legacy eager dump), `"profile"` (profile only), or `"off"`
|
|
57
|
+
- Tunables in the same file: `snapshotCount` (3), `maxContextChars` (4000),
|
|
58
|
+
`compactReinject` (true), `dedupeOnAdd` (true), `dedupeThreshold` (0.9),
|
|
59
|
+
`similarityThreshold` (0.6), `maxMemories` (5), `maxProjectMemories` (10),
|
|
60
|
+
`maxProfileItems` (5)
|
|
61
|
+
|
|
62
|
+
## The tool
|
|
63
|
+
|
|
64
|
+
| mode | args | description |
|
|
65
|
+
|---|---|---|
|
|
66
|
+
| `add` | `content`, `type?`, `scope?`, `force?` | Store a memory (`scope`: `user`/`project`, default `project`; `force: true` skips the near-duplicate check) |
|
|
67
|
+
| `search` | `query`, `scope?`, `limit?` | Hybrid search over memories |
|
|
68
|
+
| `list` | `scope?`, `limit?` | List recent memories |
|
|
69
|
+
| `profile` | `query?` | User profile extracted by Supermemory |
|
|
70
|
+
| `forget` | `memoryId` | Delete a memory |
|
|
71
|
+
| `help` | — | Usage guide |
|
|
72
|
+
|
|
73
|
+
## Development
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
npm install
|
|
77
|
+
npm run typecheck
|
|
78
|
+
npm test
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
The extension is plain TypeScript loaded by pi via jiti — no build step.
|
|
82
|
+
|
|
83
|
+
## License
|
|
84
|
+
|
|
85
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lykling/pi-supermemory",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Persistent Supermemory cloud memory for the Pi coding agent. Shares the same memory store as your opencode supermemory plugin.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pi-package",
|
|
7
|
+
"pi",
|
|
8
|
+
"supermemory",
|
|
9
|
+
"memory",
|
|
10
|
+
"coding-agent"
|
|
11
|
+
],
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"author": "lykling <lykling.lyk@gmail.com>",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/lykling/pi-supermemory.git"
|
|
17
|
+
},
|
|
18
|
+
"type": "module",
|
|
19
|
+
"main": "src/index.ts",
|
|
20
|
+
"scripts": {
|
|
21
|
+
"typecheck": "tsc --noEmit",
|
|
22
|
+
"test": "node --test \"test/*.test.ts\""
|
|
23
|
+
},
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=20"
|
|
26
|
+
},
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"@earendil-works/pi-ai": "*",
|
|
29
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
30
|
+
"typebox": "*"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@earendil-works/pi-ai": "^1.5.2",
|
|
34
|
+
"@earendil-works/pi-coding-agent": "^1.5.2",
|
|
35
|
+
"typebox": "^1.4.7",
|
|
36
|
+
"typescript": "^5.9.3"
|
|
37
|
+
},
|
|
38
|
+
"pi": {
|
|
39
|
+
"extensions": [
|
|
40
|
+
"./src/index.ts"
|
|
41
|
+
]
|
|
42
|
+
},
|
|
43
|
+
"files": [
|
|
44
|
+
"src",
|
|
45
|
+
"README.md",
|
|
46
|
+
"LICENSE"
|
|
47
|
+
],
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public",
|
|
50
|
+
"provenance": true
|
|
51
|
+
}
|
|
52
|
+
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal REST client for the Supermemory cloud API.
|
|
3
|
+
*
|
|
4
|
+
* Endpoints match what opencode-supermemory uses:
|
|
5
|
+
* - POST /v3/documents add memory
|
|
6
|
+
* - POST /v3/documents/list list memories
|
|
7
|
+
* - DELETE /v3/documents/{id} delete memory
|
|
8
|
+
* - POST /v4/search search memories
|
|
9
|
+
* - POST /v4/profile user profile
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export interface MemoryResult {
|
|
13
|
+
id?: string;
|
|
14
|
+
memory?: string;
|
|
15
|
+
content?: string;
|
|
16
|
+
chunk?: string;
|
|
17
|
+
title?: string;
|
|
18
|
+
summary?: string;
|
|
19
|
+
similarity?: number;
|
|
20
|
+
metadata?: Record<string, unknown>;
|
|
21
|
+
createdAt?: string;
|
|
22
|
+
documents?: Array<{ id?: string; title?: string }>;
|
|
23
|
+
[key: string]: unknown;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface ProfileResult {
|
|
27
|
+
static: string[];
|
|
28
|
+
dynamic: string[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface SearchResponse {
|
|
32
|
+
success: boolean;
|
|
33
|
+
results: MemoryResult[];
|
|
34
|
+
total: number;
|
|
35
|
+
error?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface ListResponse {
|
|
39
|
+
success: boolean;
|
|
40
|
+
memories: MemoryResult[];
|
|
41
|
+
error?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface AddResponse {
|
|
45
|
+
success: boolean;
|
|
46
|
+
id?: string;
|
|
47
|
+
error?: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
|
|
51
|
+
let id: ReturnType<typeof setTimeout>;
|
|
52
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
53
|
+
id = setTimeout(() => reject(new Error(`Timeout after ${ms}ms`)), ms);
|
|
54
|
+
});
|
|
55
|
+
return Promise.race([promise, timeout]).finally(() => clearTimeout(id!)) as Promise<T>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export class SupermemoryClient {
|
|
59
|
+
private readonly apiKey: string;
|
|
60
|
+
private readonly baseUrl: string;
|
|
61
|
+
private readonly timeoutMs: number;
|
|
62
|
+
|
|
63
|
+
constructor(apiKey: string, baseUrl = "https://api.supermemory.ai", timeoutMs = 8000) {
|
|
64
|
+
this.apiKey = apiKey;
|
|
65
|
+
this.baseUrl = baseUrl;
|
|
66
|
+
this.timeoutMs = timeoutMs;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
private async request(path: string, init: RequestInit, signal?: AbortSignal): Promise<unknown> {
|
|
70
|
+
const controller = new AbortController();
|
|
71
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
72
|
+
const onAbort = () => controller.abort();
|
|
73
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
74
|
+
try {
|
|
75
|
+
const response = await fetch(`${this.baseUrl}${path}`, {
|
|
76
|
+
...init,
|
|
77
|
+
signal: controller.signal,
|
|
78
|
+
headers: {
|
|
79
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
80
|
+
"Content-Type": "application/json",
|
|
81
|
+
...(init.headers ?? {}),
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
if (!response.ok) {
|
|
85
|
+
const body = await response.text().catch(() => "");
|
|
86
|
+
throw new Error(`Supermemory API ${response.status}: ${body.slice(0, 300)}`);
|
|
87
|
+
}
|
|
88
|
+
const text = await response.text();
|
|
89
|
+
return text ? JSON.parse(text) : null;
|
|
90
|
+
} finally {
|
|
91
|
+
clearTimeout(timer);
|
|
92
|
+
signal?.removeEventListener("abort", onAbort);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async addMemory(
|
|
97
|
+
content: string,
|
|
98
|
+
containerTag: string,
|
|
99
|
+
metadata: Record<string, unknown>,
|
|
100
|
+
signal?: AbortSignal,
|
|
101
|
+
): Promise<AddResponse> {
|
|
102
|
+
try {
|
|
103
|
+
const result = (await withTimeout(
|
|
104
|
+
this.request(
|
|
105
|
+
"/v3/documents",
|
|
106
|
+
{
|
|
107
|
+
method: "POST",
|
|
108
|
+
body: JSON.stringify({ content, containerTag, metadata }),
|
|
109
|
+
},
|
|
110
|
+
signal,
|
|
111
|
+
),
|
|
112
|
+
this.timeoutMs,
|
|
113
|
+
)) as { id?: string };
|
|
114
|
+
return { success: true, id: result?.id };
|
|
115
|
+
} catch (error) {
|
|
116
|
+
return { success: false, error: error instanceof Error ? error.message : String(error) };
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async searchMemories(
|
|
121
|
+
query: string,
|
|
122
|
+
containerTag: string,
|
|
123
|
+
options?: {
|
|
124
|
+
threshold?: number;
|
|
125
|
+
limit?: number;
|
|
126
|
+
filters?: unknown;
|
|
127
|
+
signal?: AbortSignal;
|
|
128
|
+
},
|
|
129
|
+
): Promise<SearchResponse> {
|
|
130
|
+
try {
|
|
131
|
+
const body = {
|
|
132
|
+
q: query,
|
|
133
|
+
containerTag,
|
|
134
|
+
threshold: options?.threshold ?? 0.6,
|
|
135
|
+
limit: options?.limit ?? 5,
|
|
136
|
+
searchMode: "hybrid",
|
|
137
|
+
...(options?.filters ? { filters: options.filters } : {}),
|
|
138
|
+
};
|
|
139
|
+
const result = (await withTimeout(
|
|
140
|
+
this.request("/v4/search", { method: "POST", body: JSON.stringify(body) }, options?.signal),
|
|
141
|
+
this.timeoutMs,
|
|
142
|
+
)) as { results?: MemoryResult[]; total?: number };
|
|
143
|
+
return {
|
|
144
|
+
success: true,
|
|
145
|
+
results: Array.isArray(result?.results) ? result.results : [],
|
|
146
|
+
total: result?.total ?? 0,
|
|
147
|
+
};
|
|
148
|
+
} catch (error) {
|
|
149
|
+
return {
|
|
150
|
+
success: false,
|
|
151
|
+
results: [],
|
|
152
|
+
total: 0,
|
|
153
|
+
error: error instanceof Error ? error.message : String(error),
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async listMemories(
|
|
159
|
+
containerTag: string,
|
|
160
|
+
limit = 20,
|
|
161
|
+
filters?: unknown,
|
|
162
|
+
signal?: AbortSignal,
|
|
163
|
+
): Promise<ListResponse> {
|
|
164
|
+
try {
|
|
165
|
+
const body = {
|
|
166
|
+
containerTags: [containerTag],
|
|
167
|
+
limit,
|
|
168
|
+
order: "desc",
|
|
169
|
+
sort: "createdAt",
|
|
170
|
+
includeContent: true,
|
|
171
|
+
...(filters ? { filters } : {}),
|
|
172
|
+
};
|
|
173
|
+
const result = (await withTimeout(
|
|
174
|
+
this.request("/v3/documents/list", { method: "POST", body: JSON.stringify(body) }, signal),
|
|
175
|
+
this.timeoutMs,
|
|
176
|
+
)) as { memories?: MemoryResult[]; documents?: MemoryResult[] };
|
|
177
|
+
const memories = Array.isArray(result?.memories)
|
|
178
|
+
? result.memories
|
|
179
|
+
: Array.isArray(result?.documents)
|
|
180
|
+
? result.documents
|
|
181
|
+
: [];
|
|
182
|
+
return { success: true, memories };
|
|
183
|
+
} catch (error) {
|
|
184
|
+
return {
|
|
185
|
+
success: false,
|
|
186
|
+
memories: [],
|
|
187
|
+
error: error instanceof Error ? error.message : String(error),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async deleteMemory(memoryId: string, signal?: AbortSignal): Promise<{ success: boolean; error?: string }> {
|
|
193
|
+
try {
|
|
194
|
+
await withTimeout(
|
|
195
|
+
this.request(`/v3/documents/${encodeURIComponent(memoryId)}`, { method: "DELETE" }, signal),
|
|
196
|
+
this.timeoutMs,
|
|
197
|
+
);
|
|
198
|
+
return { success: true };
|
|
199
|
+
} catch (error) {
|
|
200
|
+
return { success: false, error: error instanceof Error ? error.message : String(error) };
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async getProfile(
|
|
205
|
+
containerTag: string,
|
|
206
|
+
query?: string,
|
|
207
|
+
filters?: unknown,
|
|
208
|
+
signal?: AbortSignal,
|
|
209
|
+
): Promise<{ success: boolean; profile: ProfileResult; error?: string }> {
|
|
210
|
+
try {
|
|
211
|
+
const body = {
|
|
212
|
+
containerTag,
|
|
213
|
+
...(query ? { q: query } : {}),
|
|
214
|
+
...(filters ? { filters } : {}),
|
|
215
|
+
};
|
|
216
|
+
const result = (await withTimeout(
|
|
217
|
+
this.request("/v4/profile", { method: "POST", body: JSON.stringify(body) }, signal),
|
|
218
|
+
this.timeoutMs,
|
|
219
|
+
)) as {
|
|
220
|
+
profile?: { static?: unknown[]; dynamic?: unknown[] };
|
|
221
|
+
};
|
|
222
|
+
const toLines = (items: unknown[] | undefined): string[] =>
|
|
223
|
+
(items ?? [])
|
|
224
|
+
.map((item) =>
|
|
225
|
+
typeof item === "string"
|
|
226
|
+
? item
|
|
227
|
+
: ((item as Record<string, unknown>)?.content as string | undefined) ??
|
|
228
|
+
((item as Record<string, unknown>)?.text as string | undefined) ??
|
|
229
|
+
JSON.stringify(item),
|
|
230
|
+
)
|
|
231
|
+
.filter((line): line is string => Boolean(line?.trim()));
|
|
232
|
+
return {
|
|
233
|
+
success: true,
|
|
234
|
+
profile: {
|
|
235
|
+
static: toLines(result?.profile?.static),
|
|
236
|
+
dynamic: toLines(result?.profile?.dynamic),
|
|
237
|
+
},
|
|
238
|
+
};
|
|
239
|
+
} catch (error) {
|
|
240
|
+
return {
|
|
241
|
+
success: false,
|
|
242
|
+
profile: { static: [], dynamic: [] },
|
|
243
|
+
error: error instanceof Error ? error.message : String(error),
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
/** Settings resolved from env vars and config files. */
|
|
6
|
+
export interface SupermemorySettings {
|
|
7
|
+
apiKey: string | undefined;
|
|
8
|
+
baseUrl: string;
|
|
9
|
+
/** Recall strategy for the first prompt of each session. */
|
|
10
|
+
autoRecall: "hybrid" | "full" | "profile" | "off";
|
|
11
|
+
similarityThreshold: number;
|
|
12
|
+
maxMemories: number;
|
|
13
|
+
maxProjectMemories: number;
|
|
14
|
+
maxProfileItems: number;
|
|
15
|
+
/** Size of the "recent work snapshot" injected at session start and after compaction. */
|
|
16
|
+
snapshotCount: number;
|
|
17
|
+
/** Hard budget for the injected memory context block, in characters. */
|
|
18
|
+
maxContextChars: number;
|
|
19
|
+
/** Re-inject profile + snapshot after context compaction. */
|
|
20
|
+
compactReinject: boolean;
|
|
21
|
+
/** Similarity above which add-mode refuses once and suggests replacing the old memory. */
|
|
22
|
+
dedupeThreshold: number;
|
|
23
|
+
/** Run the near-duplicate check in add mode. */
|
|
24
|
+
dedupeOnAdd: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const DEFAULT_BASE_URL = "https://api.supermemory.ai";
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Strip line and block comments plus trailing commas so JSONC files parse.
|
|
31
|
+
* Port of the jsonc parser used by opencode-supermemory.
|
|
32
|
+
*/
|
|
33
|
+
export function stripJsoncComments(content: string): string {
|
|
34
|
+
let result = "";
|
|
35
|
+
let i = 0;
|
|
36
|
+
let inString = false;
|
|
37
|
+
let inSingleLineComment = false;
|
|
38
|
+
let inMultiLineComment = false;
|
|
39
|
+
while (i < content.length) {
|
|
40
|
+
const char = content[i];
|
|
41
|
+
const nextChar = content[i + 1];
|
|
42
|
+
if (!inSingleLineComment && !inMultiLineComment) {
|
|
43
|
+
if (char === '"') {
|
|
44
|
+
let backslashCount = 0;
|
|
45
|
+
let j = i - 1;
|
|
46
|
+
while (j >= 0 && content[j] === "\\") {
|
|
47
|
+
backslashCount++;
|
|
48
|
+
j--;
|
|
49
|
+
}
|
|
50
|
+
if (backslashCount % 2 === 0) {
|
|
51
|
+
inString = !inString;
|
|
52
|
+
}
|
|
53
|
+
result += char;
|
|
54
|
+
i++;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (inString) {
|
|
59
|
+
result += char;
|
|
60
|
+
i++;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (!inSingleLineComment && !inMultiLineComment) {
|
|
64
|
+
if (char === "/" && nextChar === "/") {
|
|
65
|
+
inSingleLineComment = true;
|
|
66
|
+
i += 2;
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (char === "/" && nextChar === "*") {
|
|
70
|
+
inMultiLineComment = true;
|
|
71
|
+
i += 2;
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (inSingleLineComment) {
|
|
76
|
+
if (char === "\n") {
|
|
77
|
+
inSingleLineComment = false;
|
|
78
|
+
result += char;
|
|
79
|
+
}
|
|
80
|
+
i++;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (inMultiLineComment) {
|
|
84
|
+
if (char === "*" && nextChar === "/") {
|
|
85
|
+
inMultiLineComment = false;
|
|
86
|
+
i += 2;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (char === "\n") {
|
|
90
|
+
result += char;
|
|
91
|
+
}
|
|
92
|
+
i++;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
result += char;
|
|
96
|
+
i++;
|
|
97
|
+
}
|
|
98
|
+
return result.replace(/,\s*([}\]])/g, "$1");
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Read and parse a JSON or JSONC file, returning null on any failure. */
|
|
102
|
+
export function readJsonFile(path: string): Record<string, unknown> | null {
|
|
103
|
+
try {
|
|
104
|
+
if (!existsSync(path)) return null;
|
|
105
|
+
const raw = readFileSync(path, "utf-8");
|
|
106
|
+
return JSON.parse(stripJsoncComments(raw)) as Record<string, unknown>;
|
|
107
|
+
} catch {
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function firstString(...values: unknown[]): string | undefined {
|
|
113
|
+
for (const value of values) {
|
|
114
|
+
if (typeof value === "string" && value.trim()) return value.trim();
|
|
115
|
+
}
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Resolve credentials and settings.
|
|
121
|
+
*
|
|
122
|
+
* API key precedence (later sources reuse credentials you already have):
|
|
123
|
+
* 1. SUPERMEMORY_API_KEY env var
|
|
124
|
+
* 2. ~/.pi/agent/supermemory.json (pi-native config)
|
|
125
|
+
* 3. ~/.config/opencode/supermemory.jsonc (shared with opencode plugin)
|
|
126
|
+
* 4. ~/.supermemory-opencode/credentials.json (opencode device-flow login)
|
|
127
|
+
*/
|
|
128
|
+
export function resolveSettings(): SupermemorySettings {
|
|
129
|
+
const piConfig = readJsonFile(join(homedir(), ".pi", "agent", "supermemory.json"));
|
|
130
|
+
const opencodeConfig = readJsonFile(
|
|
131
|
+
join(homedir(), ".config", "opencode", "supermemory.jsonc"),
|
|
132
|
+
);
|
|
133
|
+
const opencodeCredentials = readJsonFile(
|
|
134
|
+
join(homedir(), ".supermemory-opencode", "credentials.json"),
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
const apiKey = firstString(
|
|
138
|
+
process.env.SUPERMEMORY_API_KEY,
|
|
139
|
+
piConfig?.apiKey,
|
|
140
|
+
opencodeConfig?.apiKey,
|
|
141
|
+
opencodeCredentials?.apiKey,
|
|
142
|
+
);
|
|
143
|
+
const baseUrl = firstString(
|
|
144
|
+
process.env.SUPERMEMORY_API_BASE_URL,
|
|
145
|
+
piConfig?.apiBaseUrl,
|
|
146
|
+
opencodeConfig?.apiBaseUrl,
|
|
147
|
+
opencodeCredentials?.apiBaseUrl,
|
|
148
|
+
DEFAULT_BASE_URL,
|
|
149
|
+
) as string;
|
|
150
|
+
|
|
151
|
+
const autoRecallRaw = firstString(piConfig?.autoRecall);
|
|
152
|
+
const autoRecall: SupermemorySettings["autoRecall"] =
|
|
153
|
+
autoRecallRaw === "hybrid" ||
|
|
154
|
+
autoRecallRaw === "full" ||
|
|
155
|
+
autoRecallRaw === "profile" ||
|
|
156
|
+
autoRecallRaw === "off"
|
|
157
|
+
? autoRecallRaw
|
|
158
|
+
: "hybrid";
|
|
159
|
+
|
|
160
|
+
const num = (value: unknown, fallback: number): number =>
|
|
161
|
+
typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
162
|
+
const bool = (value: unknown, fallback: boolean): boolean =>
|
|
163
|
+
typeof value === "boolean" ? value : fallback;
|
|
164
|
+
|
|
165
|
+
return {
|
|
166
|
+
apiKey,
|
|
167
|
+
baseUrl,
|
|
168
|
+
autoRecall,
|
|
169
|
+
similarityThreshold: num(piConfig?.similarityThreshold, 0.6),
|
|
170
|
+
maxMemories: num(piConfig?.maxMemories, 5),
|
|
171
|
+
maxProjectMemories: num(piConfig?.maxProjectMemories, 10),
|
|
172
|
+
maxProfileItems: num(piConfig?.maxProfileItems, 5),
|
|
173
|
+
snapshotCount: num(piConfig?.snapshotCount, 3),
|
|
174
|
+
maxContextChars: num(piConfig?.maxContextChars, 4000),
|
|
175
|
+
compactReinject: bool(piConfig?.compactReinject, true),
|
|
176
|
+
dedupeThreshold: num(piConfig?.dedupeThreshold, 0.9),
|
|
177
|
+
dedupeOnAdd: bool(piConfig?.dedupeOnAdd, true),
|
|
178
|
+
};
|
|
179
|
+
}
|
package/src/context.ts
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import type { MemoryResult, ProfileResult } from "./api.ts";
|
|
2
|
+
|
|
3
|
+
/** Extract the deletable memory id from a search/list result. */
|
|
4
|
+
export function memoryId(memory: MemoryResult): string {
|
|
5
|
+
return memory.documents?.[0]?.id ?? memory.id ?? "";
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** Extract the human-readable content from a search/list result. */
|
|
9
|
+
export function memoryContent(memory: MemoryResult): string {
|
|
10
|
+
return memory.memory || memory.chunk || memory.content || memory.summary || "";
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Short "how old" label from an ISO createdAt, for snapshot lines. */
|
|
14
|
+
export function relativeAge(createdAt?: string, now = Date.now()): string {
|
|
15
|
+
if (!createdAt) return "";
|
|
16
|
+
const then = Date.parse(createdAt);
|
|
17
|
+
if (!Number.isFinite(then) || then > now) return "";
|
|
18
|
+
const days = Math.floor((now - then) / 86_400_000);
|
|
19
|
+
if (days <= 0) return "today";
|
|
20
|
+
if (days === 1) return "yesterday";
|
|
21
|
+
if (days < 30) return `${days}d ago`;
|
|
22
|
+
if (days < 365) return `${Math.floor(days / 30)}mo ago`;
|
|
23
|
+
return `${Math.floor(days / 365)}y ago`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface MemoryContextOptions {
|
|
27
|
+
profile: ProfileResult | null;
|
|
28
|
+
/** Recent project memories (recency-based snapshot). */
|
|
29
|
+
snapshot: MemoryResult[];
|
|
30
|
+
/** Semantically matched memories, project and personal combined. */
|
|
31
|
+
relevant: Array<{ memory: MemoryResult; scope: "project" | "personal" }>;
|
|
32
|
+
maxProfileItems: number;
|
|
33
|
+
maxContextChars: number;
|
|
34
|
+
/** Clock override for deterministic age labels in tests. */
|
|
35
|
+
now?: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Format recalled memories into a compact context block for the LLM. */
|
|
39
|
+
export function formatMemoryContext(options: MemoryContextOptions): string {
|
|
40
|
+
const { profile, snapshot, relevant, maxProfileItems, maxContextChars, now } = options;
|
|
41
|
+
const header = "[Supermemory — persistent memory recalled for this project]";
|
|
42
|
+
const budget = Math.max(0, maxContextChars - header.length);
|
|
43
|
+
|
|
44
|
+
const lines: string[] = [];
|
|
45
|
+
let used = 0;
|
|
46
|
+
const push = (line: string): boolean => {
|
|
47
|
+
if (used + line.length + 1 > budget) return false;
|
|
48
|
+
lines.push(line);
|
|
49
|
+
used += line.length + 1;
|
|
50
|
+
return true;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
if (profile && (profile.static.length > 0 || profile.dynamic.length > 0)) {
|
|
54
|
+
const section = ["User Profile:"];
|
|
55
|
+
for (const line of profile.static.slice(0, maxProfileItems)) section.push(`- ${line}`);
|
|
56
|
+
for (const line of profile.dynamic.slice(0, maxProfileItems)) section.push(`- ${line}`);
|
|
57
|
+
if (!push(section.join("\n"))) return block(header, lines);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const snapshotIds = new Set<string>();
|
|
61
|
+
if (snapshot.length > 0) {
|
|
62
|
+
const sectionHeader = "Recent Project Snapshot (latest first):";
|
|
63
|
+
let opened = false;
|
|
64
|
+
for (const memory of snapshot) {
|
|
65
|
+
const age = relativeAge(memory.createdAt, now);
|
|
66
|
+
const content = memoryContent(memory);
|
|
67
|
+
if (!content) continue;
|
|
68
|
+
const id = memoryId(memory);
|
|
69
|
+
if (id) snapshotIds.add(id);
|
|
70
|
+
const line = `- ${age ? `[${age}] ` : ""}${content}`;
|
|
71
|
+
// First entry travels with its section header so we never emit an empty header.
|
|
72
|
+
if (!opened) {
|
|
73
|
+
if (!push(`${sectionHeader}\n${line}`)) return block(header, lines);
|
|
74
|
+
opened = true;
|
|
75
|
+
} else if (!push(line)) {
|
|
76
|
+
return block(header, lines);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (relevant.length > 0) {
|
|
82
|
+
// Highest similarity first; skip memories already shown in the snapshot.
|
|
83
|
+
const ordered = [...relevant].sort(
|
|
84
|
+
(a, b) => (b.memory.similarity ?? 0) - (a.memory.similarity ?? 0),
|
|
85
|
+
);
|
|
86
|
+
let opened = false;
|
|
87
|
+
for (const { memory, scope } of ordered) {
|
|
88
|
+
const content = memoryContent(memory);
|
|
89
|
+
if (!content) continue;
|
|
90
|
+
if (snapshotIds.has(memoryId(memory))) continue;
|
|
91
|
+
const similarity = Math.round((memory.similarity ?? 0) * 100);
|
|
92
|
+
const line = `- [${scope}, ${similarity}%] ${content}`;
|
|
93
|
+
if (!opened) {
|
|
94
|
+
if (push(`\nRelevant Memories:\n${line}`)) opened = true;
|
|
95
|
+
} else {
|
|
96
|
+
push(line);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return block(header, lines);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function block(header: string, lines: string[]): string {
|
|
105
|
+
if (lines.length === 0) return "";
|
|
106
|
+
return `${header}\n${lines.join("\n")}`;
|
|
107
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { StringEnum } from "@earendil-works/pi-ai";
|
|
4
|
+
import { SupermemoryClient } from "./api.ts";
|
|
5
|
+
import { resolveSettings } from "./config.ts";
|
|
6
|
+
import { formatMemoryContext, memoryId } from "./context.ts";
|
|
7
|
+
import { isFullyPrivate, stripPrivateContent } from "./privacy.ts";
|
|
8
|
+
import { getProjectName, getProjectIdentity, getProjectTag, getScopeFilters } from "./tags.ts";
|
|
9
|
+
|
|
10
|
+
const VERSION = "0.2.0";
|
|
11
|
+
const PLUGIN_NAME = "@lykling/pi-supermemory";
|
|
12
|
+
|
|
13
|
+
/** Prompts shorter than this make poor semantic search queries; snapshot covers them. */
|
|
14
|
+
const MIN_SEARCH_PROMPT_LENGTH = 16;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Persistent Supermemory memory for pi.
|
|
18
|
+
*
|
|
19
|
+
* Reuses the Supermemory cloud account already configured for opencode
|
|
20
|
+
* (same API key, same per-repo container tags), so memories are shared
|
|
21
|
+
* across both agents.
|
|
22
|
+
*
|
|
23
|
+
* Recall strategy (hybrid): small deterministic preload (profile + recent
|
|
24
|
+
* snapshot) at session start, per-turn reasoned recall via the tool
|
|
25
|
+
* thereafter, and re-injection after context compaction.
|
|
26
|
+
*/
|
|
27
|
+
export default function supermemoryExtension(pi: ExtensionAPI) {
|
|
28
|
+
const settings = resolveSettings();
|
|
29
|
+
if (!settings.apiKey) {
|
|
30
|
+
// Not configured: stay silent. Set SUPERMEMORY_API_KEY or create
|
|
31
|
+
// ~/.pi/agent/supermemory.json, then run /reload.
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const client = new SupermemoryClient(settings.apiKey, settings.baseUrl);
|
|
36
|
+
|
|
37
|
+
const tagsFor = (directory: string) => ({
|
|
38
|
+
containerTag: getProjectTag(directory),
|
|
39
|
+
projectId: getProjectIdentity(directory),
|
|
40
|
+
projectName: getProjectName(directory),
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
pi.registerTool({
|
|
44
|
+
name: "supermemory",
|
|
45
|
+
label: "Supermemory",
|
|
46
|
+
description:
|
|
47
|
+
"Manage and query the Supermemory persistent memory system shared across coding agents and sessions. " +
|
|
48
|
+
"Use 'search' to find relevant memories, 'add' to store new knowledge, 'list' to see recent memories, " +
|
|
49
|
+
"'profile' to view the user profile, 'forget' to remove a memory.",
|
|
50
|
+
promptSnippet: "Search, add, list, or forget persistent memories shared across sessions and agents",
|
|
51
|
+
promptGuidelines: [
|
|
52
|
+
"Recall discipline: before answering, silently decide whether saved memory would materially improve THIS reply. Use supermemory mode=search when starting a task that may build on earlier sessions, when the user references past decisions or preferences, or when the topic shifts to something previously discussed. Skip recall when the message is self-contained, trivial, or you already recalled this topic and it has not shifted. Fold results into your answer without narrating the search.",
|
|
53
|
+
"Before storing with mode=add, search first for near-duplicates: if the tool warns about similar existing memories, forget the outdated one (mode=forget with its memoryId) and then add, instead of stacking similar entries.",
|
|
54
|
+
],
|
|
55
|
+
parameters: Type.Object({
|
|
56
|
+
mode: StringEnum(["add", "search", "profile", "list", "forget", "help"], {
|
|
57
|
+
description: "Operation to perform (default: help)",
|
|
58
|
+
}),
|
|
59
|
+
content: Type.Optional(
|
|
60
|
+
Type.String({ description: "Memory content to store (mode=add)" }),
|
|
61
|
+
),
|
|
62
|
+
force: Type.Optional(
|
|
63
|
+
Type.Boolean({
|
|
64
|
+
description: "Skip the near-duplicate check (mode=add)",
|
|
65
|
+
}),
|
|
66
|
+
),
|
|
67
|
+
query: Type.Optional(Type.String({ description: "Search query (mode=search, mode=profile)" })),
|
|
68
|
+
type: Type.Optional(
|
|
69
|
+
StringEnum(
|
|
70
|
+
["project-config", "architecture", "error-solution", "preference", "learned-pattern", "conversation"],
|
|
71
|
+
{ description: "Memory type (mode=add)" },
|
|
72
|
+
),
|
|
73
|
+
),
|
|
74
|
+
scope: Type.Optional(
|
|
75
|
+
StringEnum(["user", "project"], {
|
|
76
|
+
description: "user = personal preferences for this project, project = project knowledge (default)",
|
|
77
|
+
}),
|
|
78
|
+
),
|
|
79
|
+
memoryId: Type.Optional(Type.String({ description: "Memory id to remove (mode=forget)" })),
|
|
80
|
+
limit: Type.Optional(Type.Number({ description: "Max results (mode=search, mode=list)" })),
|
|
81
|
+
}),
|
|
82
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
83
|
+
const mode = params.mode ?? "help";
|
|
84
|
+
const tags = tagsFor(ctx.cwd);
|
|
85
|
+
|
|
86
|
+
try {
|
|
87
|
+
switch (mode) {
|
|
88
|
+
case "add": {
|
|
89
|
+
if (!params.content) {
|
|
90
|
+
return text({ success: false, error: "content parameter is required for add mode" });
|
|
91
|
+
}
|
|
92
|
+
if (isFullyPrivate(params.content)) {
|
|
93
|
+
return text({ success: false, error: "Cannot store fully private content" });
|
|
94
|
+
}
|
|
95
|
+
if (settings.dedupeOnAdd && !params.force) {
|
|
96
|
+
const dup = await client.searchMemories(params.content, tags.containerTag, {
|
|
97
|
+
threshold: settings.dedupeThreshold,
|
|
98
|
+
limit: 3,
|
|
99
|
+
signal,
|
|
100
|
+
});
|
|
101
|
+
if (dup.success && dup.results.length > 0) {
|
|
102
|
+
return text({
|
|
103
|
+
success: false,
|
|
104
|
+
duplicate: true,
|
|
105
|
+
message:
|
|
106
|
+
"Highly similar memories already exist. If the new content supersedes them, " +
|
|
107
|
+
"call forget with each memoryId below and then add again; to store anyway, " +
|
|
108
|
+
"retry add with force=true.",
|
|
109
|
+
similar: dup.results.map((m) => ({
|
|
110
|
+
id: memoryId(m),
|
|
111
|
+
similarity: m.similarity,
|
|
112
|
+
content: (m.memory || m.chunk || m.content || m.summary || "").slice(0, 200),
|
|
113
|
+
})),
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const scope = params.scope ?? "project";
|
|
118
|
+
const internalScope = scope === "user" ? "personal" : "project";
|
|
119
|
+
const result = await client.addMemory(
|
|
120
|
+
stripPrivateContent(params.content),
|
|
121
|
+
tags.containerTag,
|
|
122
|
+
{
|
|
123
|
+
type: params.type,
|
|
124
|
+
project: tags.projectName,
|
|
125
|
+
sm_project_id: tags.projectId,
|
|
126
|
+
sm_scope: internalScope,
|
|
127
|
+
sm_capture_mode: "tool",
|
|
128
|
+
sm_source: "pi",
|
|
129
|
+
sm_client: PLUGIN_NAME,
|
|
130
|
+
sm_plugin_version: VERSION,
|
|
131
|
+
},
|
|
132
|
+
signal,
|
|
133
|
+
);
|
|
134
|
+
if (!result.success) {
|
|
135
|
+
return text({ success: false, error: result.error || "Failed to add memory" });
|
|
136
|
+
}
|
|
137
|
+
return text({
|
|
138
|
+
success: true,
|
|
139
|
+
message: `Memory added to ${scope} scope`,
|
|
140
|
+
id: result.id,
|
|
141
|
+
scope,
|
|
142
|
+
type: params.type,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
case "search": {
|
|
147
|
+
if (!params.query) {
|
|
148
|
+
return text({ success: false, error: "query parameter is required for search mode" });
|
|
149
|
+
}
|
|
150
|
+
const filters = params.scope
|
|
151
|
+
? getScopeFilters(params.scope === "user" ? "personal" : "project")
|
|
152
|
+
: undefined;
|
|
153
|
+
const result = await client.searchMemories(params.query, tags.containerTag, {
|
|
154
|
+
threshold: settings.similarityThreshold,
|
|
155
|
+
limit: params.limit ?? settings.maxMemories,
|
|
156
|
+
filters,
|
|
157
|
+
signal,
|
|
158
|
+
});
|
|
159
|
+
if (!result.success) {
|
|
160
|
+
return text({ success: false, error: result.error || "Search failed" });
|
|
161
|
+
}
|
|
162
|
+
return text({
|
|
163
|
+
success: true,
|
|
164
|
+
query: params.query,
|
|
165
|
+
scope: params.scope,
|
|
166
|
+
results: result.results.map((m) => ({
|
|
167
|
+
// Top-level id is a chunk id; the deletable memory id lives in documents[0].
|
|
168
|
+
id: m.documents?.[0]?.id ?? m.id,
|
|
169
|
+
content: m.memory || m.chunk || m.content || "",
|
|
170
|
+
title: m.title,
|
|
171
|
+
similarity: m.similarity,
|
|
172
|
+
metadata: m.metadata,
|
|
173
|
+
})),
|
|
174
|
+
total: result.total,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
case "list": {
|
|
179
|
+
const filters = params.scope
|
|
180
|
+
? getScopeFilters(params.scope === "user" ? "personal" : "project")
|
|
181
|
+
: undefined;
|
|
182
|
+
const result = await client.listMemories(
|
|
183
|
+
tags.containerTag,
|
|
184
|
+
params.limit ?? 20,
|
|
185
|
+
filters,
|
|
186
|
+
signal,
|
|
187
|
+
);
|
|
188
|
+
if (!result.success) {
|
|
189
|
+
return text({ success: false, error: result.error || "List failed" });
|
|
190
|
+
}
|
|
191
|
+
return text({
|
|
192
|
+
success: true,
|
|
193
|
+
memories: result.memories.map((m) => ({
|
|
194
|
+
id: m.id,
|
|
195
|
+
content: m.summary || m.content || m.title || "",
|
|
196
|
+
metadata: m.metadata,
|
|
197
|
+
createdAt: m.createdAt,
|
|
198
|
+
})),
|
|
199
|
+
containerTag: tags.containerTag,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
case "forget": {
|
|
204
|
+
if (!params.memoryId) {
|
|
205
|
+
return text({ success: false, error: "memoryId parameter is required for forget mode" });
|
|
206
|
+
}
|
|
207
|
+
const result = await client.deleteMemory(params.memoryId, signal);
|
|
208
|
+
if (!result.success) {
|
|
209
|
+
return text({ success: false, error: result.error || "Failed to delete memory" });
|
|
210
|
+
}
|
|
211
|
+
return text({ success: true, message: `Memory ${params.memoryId} deleted` });
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
case "profile": {
|
|
215
|
+
const filters = params.scope
|
|
216
|
+
? getScopeFilters(params.scope === "user" ? "personal" : "project")
|
|
217
|
+
: undefined;
|
|
218
|
+
const result = await client.getProfile(
|
|
219
|
+
tags.containerTag,
|
|
220
|
+
params.query,
|
|
221
|
+
filters,
|
|
222
|
+
signal,
|
|
223
|
+
);
|
|
224
|
+
if (!result.success) {
|
|
225
|
+
return text({ success: false, error: result.error || "Failed to load profile" });
|
|
226
|
+
}
|
|
227
|
+
return text({ success: true, profile: result.profile });
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
case "help":
|
|
231
|
+
default:
|
|
232
|
+
return text({
|
|
233
|
+
success: true,
|
|
234
|
+
message: "Supermemory Usage Guide (shared with opencode)",
|
|
235
|
+
commands: [
|
|
236
|
+
{ command: "add", description: "Store a new memory", args: ["content", "type?", "scope?", "force?"] },
|
|
237
|
+
{ command: "search", description: "Search memories", args: ["query", "scope?", "limit?"] },
|
|
238
|
+
{ command: "profile", description: "View user profile", args: ["query?"] },
|
|
239
|
+
{ command: "list", description: "List recent memories", args: ["scope?", "limit?"] },
|
|
240
|
+
{ command: "forget", description: "Remove a memory", args: ["memoryId"] },
|
|
241
|
+
],
|
|
242
|
+
scopes: {
|
|
243
|
+
user: "Personal preferences and knowledge for this project",
|
|
244
|
+
project: "Project-specific knowledge (default)",
|
|
245
|
+
},
|
|
246
|
+
containerTag: tags.containerTag,
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
} catch (error) {
|
|
250
|
+
return text({
|
|
251
|
+
success: false,
|
|
252
|
+
error: error instanceof Error ? error.message : String(error),
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
},
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
// Recall memories on the first prompt of each session.
|
|
259
|
+
const injectedSessions = new Set<string>();
|
|
260
|
+
|
|
261
|
+
pi.on("before_agent_start", async (event, ctx) => {
|
|
262
|
+
if (settings.autoRecall === "off") return;
|
|
263
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
264
|
+
if (!sessionId || injectedSessions.has(sessionId)) return;
|
|
265
|
+
injectedSessions.add(sessionId);
|
|
266
|
+
|
|
267
|
+
try {
|
|
268
|
+
const tag = getProjectTag(ctx.cwd);
|
|
269
|
+
const prompt =
|
|
270
|
+
event.messageType === "user" ? (event as { prompt: string }).prompt : "";
|
|
271
|
+
// Short openers ("continue") are poor queries; the snapshot covers them.
|
|
272
|
+
const searchable = prompt.trim().length >= MIN_SEARCH_PROMPT_LENGTH;
|
|
273
|
+
|
|
274
|
+
let profileResult: Awaited<ReturnType<typeof client.getProfile>>;
|
|
275
|
+
let snapshotResult: Awaited<ReturnType<typeof client.listMemories>> | null = null;
|
|
276
|
+
let projectSearchResult: Awaited<ReturnType<typeof client.searchMemories>> | null = null;
|
|
277
|
+
let personalSearchResult: Awaited<ReturnType<typeof client.searchMemories>> | null = null;
|
|
278
|
+
|
|
279
|
+
if (settings.autoRecall === "profile") {
|
|
280
|
+
profileResult = await client.getProfile(tag);
|
|
281
|
+
} else if (settings.autoRecall === "full") {
|
|
282
|
+
[profileResult, snapshotResult, personalSearchResult] = await Promise.all([
|
|
283
|
+
client.getProfile(tag),
|
|
284
|
+
client.listMemories(tag, settings.maxProjectMemories, getScopeFilters("project")),
|
|
285
|
+
searchable
|
|
286
|
+
? client.searchMemories(prompt, tag, {
|
|
287
|
+
threshold: settings.similarityThreshold,
|
|
288
|
+
limit: settings.maxMemories,
|
|
289
|
+
filters: getScopeFilters("personal"),
|
|
290
|
+
})
|
|
291
|
+
: Promise.resolve(null),
|
|
292
|
+
]);
|
|
293
|
+
} else {
|
|
294
|
+
// hybrid (default): profile + small recent snapshot + semantic search on both scopes.
|
|
295
|
+
[profileResult, snapshotResult, projectSearchResult, personalSearchResult] = await Promise.all([
|
|
296
|
+
client.getProfile(tag, undefined, getScopeFilters("personal")),
|
|
297
|
+
client.listMemories(tag, settings.snapshotCount, getScopeFilters("project")),
|
|
298
|
+
searchable
|
|
299
|
+
? client.searchMemories(prompt, tag, {
|
|
300
|
+
threshold: settings.similarityThreshold,
|
|
301
|
+
limit: settings.maxMemories,
|
|
302
|
+
filters: getScopeFilters("project"),
|
|
303
|
+
})
|
|
304
|
+
: Promise.resolve(null),
|
|
305
|
+
searchable
|
|
306
|
+
? client.searchMemories(prompt, tag, {
|
|
307
|
+
threshold: settings.similarityThreshold,
|
|
308
|
+
limit: 3,
|
|
309
|
+
filters: getScopeFilters("personal"),
|
|
310
|
+
})
|
|
311
|
+
: Promise.resolve(null),
|
|
312
|
+
]);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const relevant: Array<{ memory: NonNullable<typeof projectSearchResult>["results"][number]; scope: "project" | "personal" }> = [];
|
|
316
|
+
for (const memory of projectSearchResult?.results ?? []) {
|
|
317
|
+
relevant.push({ memory, scope: "project" });
|
|
318
|
+
}
|
|
319
|
+
for (const memory of personalSearchResult?.results ?? []) {
|
|
320
|
+
relevant.push({ memory, scope: "personal" });
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const content = formatMemoryContext({
|
|
324
|
+
profile: profileResult.success ? profileResult.profile : null,
|
|
325
|
+
snapshot: snapshotResult?.memories ?? [],
|
|
326
|
+
relevant,
|
|
327
|
+
maxProfileItems: settings.maxProfileItems,
|
|
328
|
+
maxContextChars: settings.maxContextChars,
|
|
329
|
+
});
|
|
330
|
+
if (!content) return;
|
|
331
|
+
|
|
332
|
+
const snapshotCount = snapshotResult?.memories.length ?? 0;
|
|
333
|
+
const relevantCount = relevant.length;
|
|
334
|
+
ctx.ui.notify(
|
|
335
|
+
`Supermemory: recalled ${snapshotCount} snapshot / ${relevantCount} relevant memories`,
|
|
336
|
+
"info",
|
|
337
|
+
);
|
|
338
|
+
return {
|
|
339
|
+
message: {
|
|
340
|
+
customType: "supermemory-recall",
|
|
341
|
+
content,
|
|
342
|
+
display: true,
|
|
343
|
+
},
|
|
344
|
+
};
|
|
345
|
+
} catch {
|
|
346
|
+
// Recall must never break the turn.
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
// Compaction washes out the session-start injection; re-inject the
|
|
351
|
+
// deterministic parts (profile + recent snapshot) so memory survives.
|
|
352
|
+
pi.on("session_compact", async (event, ctx) => {
|
|
353
|
+
if (!settings.compactReinject || settings.autoRecall === "off") return;
|
|
354
|
+
void event;
|
|
355
|
+
try {
|
|
356
|
+
const tag = getProjectTag(ctx.cwd);
|
|
357
|
+
const [profileResult, snapshotResult] = await Promise.all([
|
|
358
|
+
client.getProfile(tag, undefined, getScopeFilters("personal")),
|
|
359
|
+
client.listMemories(tag, settings.snapshotCount, getScopeFilters("project")),
|
|
360
|
+
]);
|
|
361
|
+
const content = formatMemoryContext({
|
|
362
|
+
profile: profileResult.success ? profileResult.profile : null,
|
|
363
|
+
snapshot: snapshotResult?.memories ?? [],
|
|
364
|
+
relevant: [],
|
|
365
|
+
maxProfileItems: settings.maxProfileItems,
|
|
366
|
+
maxContextChars: settings.maxContextChars,
|
|
367
|
+
});
|
|
368
|
+
if (!content) return;
|
|
369
|
+
pi.sendMessage({
|
|
370
|
+
customType: "supermemory-recall",
|
|
371
|
+
content,
|
|
372
|
+
display: true,
|
|
373
|
+
});
|
|
374
|
+
} catch {
|
|
375
|
+
// Re-injection must never break the session.
|
|
376
|
+
}
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function text(value: unknown) {
|
|
381
|
+
return {
|
|
382
|
+
content: [{ type: "text" as const, text: JSON.stringify(value, null, 2) }],
|
|
383
|
+
details: value as Record<string, unknown>,
|
|
384
|
+
};
|
|
385
|
+
}
|
package/src/privacy.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Redact <private>...</private> blocks before content is sent to Supermemory. */
|
|
2
|
+
export function stripPrivateContent(content: string): string {
|
|
3
|
+
return content.replace(/<private>[\s\S]*?<\/private>/gi, "[REDACTED]");
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
/** True when nothing except private markers remains. */
|
|
7
|
+
export function isFullyPrivate(content: string): boolean {
|
|
8
|
+
const stripped = stripPrivateContent(content).trim();
|
|
9
|
+
return stripped === "[REDACTED]" || stripped === "";
|
|
10
|
+
}
|
package/src/tags.ts
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { execSync } from "node:child_process";
|
|
3
|
+
import { realpathSync } from "node:fs";
|
|
4
|
+
import { basename, dirname, resolve, sep } from "node:path";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Container-tag derivation, ported 1:1 from opencode-supermemory so pi and
|
|
8
|
+
* opencode share the same Supermemory container for the same repository.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const repoInfoCache = new Map<string, { name: string | null; normalizedRemote: string | null }>();
|
|
12
|
+
|
|
13
|
+
function git(command: string, cwd: string): string | null {
|
|
14
|
+
try {
|
|
15
|
+
return execSync(command, {
|
|
16
|
+
cwd,
|
|
17
|
+
encoding: "utf-8",
|
|
18
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
19
|
+
}).trim();
|
|
20
|
+
} catch {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** First 16 hex chars of sha256 — matches supermemory's tag hashing. */
|
|
26
|
+
export function sha256Short(input: string): string {
|
|
27
|
+
return createHash("sha256").update(input).digest("hex").slice(0, 16);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Root of the git worktree/repo, accounting for worktrees sharing a common dir. */
|
|
31
|
+
export function getGitRoot(directory: string): string | null {
|
|
32
|
+
const isolateWorktrees = process.env.SUPERMEMORY_ISOLATE_WORKTREES === "true";
|
|
33
|
+
try {
|
|
34
|
+
if (isolateWorktrees) {
|
|
35
|
+
return git("git rev-parse --show-toplevel", directory) || null;
|
|
36
|
+
}
|
|
37
|
+
const gitCommonDir = git("git rev-parse --git-common-dir", directory);
|
|
38
|
+
if (!gitCommonDir) return null;
|
|
39
|
+
if (gitCommonDir === ".git") {
|
|
40
|
+
return git("git rev-parse --show-toplevel", directory) || null;
|
|
41
|
+
}
|
|
42
|
+
const resolved = resolve(directory, gitCommonDir);
|
|
43
|
+
if (basename(resolved) === ".git" && !resolved.includes(`${sep}.git${sep}`)) {
|
|
44
|
+
return dirname(resolved);
|
|
45
|
+
}
|
|
46
|
+
return git("git rev-parse --show-toplevel", directory) || null;
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function getProjectBasePath(directory: string): string {
|
|
53
|
+
return getGitRoot(directory) || resolve(directory);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Normalize a git remote URL to a stable lowercase identity string. */
|
|
57
|
+
export function normalizeGitRemote(remoteUrl: string): string | null {
|
|
58
|
+
const raw = remoteUrl.trim();
|
|
59
|
+
if (!raw) return null;
|
|
60
|
+
let normalized: string;
|
|
61
|
+
if (/^[a-z][a-z\d+.-]*:\/\//i.test(raw)) {
|
|
62
|
+
try {
|
|
63
|
+
const parsed = new URL(raw);
|
|
64
|
+
normalized =
|
|
65
|
+
parsed.protocol === "file:"
|
|
66
|
+
? `file:${decodeURIComponent(parsed.pathname)}`
|
|
67
|
+
: `${parsed.hostname.toLowerCase()}${parsed.port ? `:${parsed.port}` : ""}/${parsed.pathname.replace(/^\/+/, "")}`;
|
|
68
|
+
} catch {
|
|
69
|
+
normalized = raw;
|
|
70
|
+
}
|
|
71
|
+
} else {
|
|
72
|
+
const scpStyle = raw.match(/^(?:[^@/]+@)?([^:]+):(.+)$/);
|
|
73
|
+
normalized =
|
|
74
|
+
scpStyle?.[1] && scpStyle?.[2]
|
|
75
|
+
? `${scpStyle[1].toLowerCase()}/${scpStyle[2]}`
|
|
76
|
+
: `file:${resolve(raw)}`;
|
|
77
|
+
}
|
|
78
|
+
return normalized
|
|
79
|
+
.replace(/[?#].*$/, "")
|
|
80
|
+
.replace(/\/+$/, "")
|
|
81
|
+
.replace(/\.git$/i, "")
|
|
82
|
+
.replace(/\/{2,}/g, "/")
|
|
83
|
+
.toLowerCase();
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function getGitRepoInfo(directory: string): {
|
|
87
|
+
name: string | null;
|
|
88
|
+
normalizedRemote: string | null;
|
|
89
|
+
} {
|
|
90
|
+
const cached = repoInfoCache.get(directory);
|
|
91
|
+
if (cached) return cached;
|
|
92
|
+
const remoteUrl = git("git remote get-url origin", directory);
|
|
93
|
+
if (!remoteUrl) {
|
|
94
|
+
const result = { name: null, normalizedRemote: null };
|
|
95
|
+
repoInfoCache.set(directory, result);
|
|
96
|
+
return result;
|
|
97
|
+
}
|
|
98
|
+
const normalizedRemote = normalizeGitRemote(remoteUrl);
|
|
99
|
+
const displayRemote = remoteUrl.replace(/\/+$/, "").replace(/\.git$/i, "");
|
|
100
|
+
const separator = Math.max(displayRemote.lastIndexOf("/"), displayRemote.lastIndexOf(":"));
|
|
101
|
+
const result = {
|
|
102
|
+
name: displayRemote.slice(separator + 1) || null,
|
|
103
|
+
normalizedRemote,
|
|
104
|
+
};
|
|
105
|
+
repoInfoCache.set(directory, result);
|
|
106
|
+
return result;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function getGitRepoName(directory: string): string | null {
|
|
110
|
+
return getGitRepoInfo(directory).name;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function sanitizeRepoName(name: string): string {
|
|
114
|
+
const sanitized = name
|
|
115
|
+
.toLowerCase()
|
|
116
|
+
.replace(/[^a-z0-9]/g, "_")
|
|
117
|
+
.replace(/_+/g, "_")
|
|
118
|
+
.replace(/^_|_$/g, "");
|
|
119
|
+
return sanitized.slice(0, 95).replace(/_+$/g, "") || "unknown";
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Stable per-repo identity: remote URL when available, otherwise local path. */
|
|
123
|
+
export function getProjectIdentity(directory: string): string {
|
|
124
|
+
const basePath = getProjectBasePath(directory);
|
|
125
|
+
const { normalizedRemote } = getGitRepoInfo(basePath);
|
|
126
|
+
const isolateWorktrees = process.env.SUPERMEMORY_ISOLATE_WORKTREES === "true";
|
|
127
|
+
let localIdentity = basePath;
|
|
128
|
+
try {
|
|
129
|
+
localIdentity = realpathSync.native(basePath);
|
|
130
|
+
} catch {
|
|
131
|
+
// keep basePath
|
|
132
|
+
}
|
|
133
|
+
return sha256Short(!isolateWorktrees && normalizedRemote ? normalizedRemote : `path:${localIdentity}`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Generated tag: repo_<name>__<identity-hash>. */
|
|
137
|
+
export function getGeneratedProjectTag(directory: string): string {
|
|
138
|
+
const basePath = getProjectBasePath(directory);
|
|
139
|
+
const repoName = getGitRepoName(basePath) || basename(basePath) || "unknown";
|
|
140
|
+
const shortName = sanitizeRepoName(repoName).slice(0, 72).replace(/_+$/g, "");
|
|
141
|
+
return `repo_${shortName || "unknown"}__${getProjectIdentity(directory)}`;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Canonical container tag for a directory, with env override. */
|
|
145
|
+
export function getProjectTag(directory: string): string {
|
|
146
|
+
return process.env.SUPERMEMORY_REPO_TAG || getGeneratedProjectTag(directory);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function getProjectName(directory: string): string {
|
|
150
|
+
const basePath = getProjectBasePath(directory);
|
|
151
|
+
return getGitRepoName(basePath) || basename(basePath) || "unknown";
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Metadata filter for sm_scope, matching opencode-supermemory. */
|
|
155
|
+
export function getScopeFilters(scope: string): { AND: Array<{ key: string; value: string; filterType: string }> } {
|
|
156
|
+
return { AND: [{ key: "sm_scope", value: scope, filterType: "metadata" }] };
|
|
157
|
+
}
|