@lykling/pi-supermemory 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +71 -2
- package/package.json +46 -4
- package/src/api.ts +247 -0
- package/src/config.ts +156 -0
- package/src/context.ts +42 -0
- package/src/index.ts +287 -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,72 @@
|
|
|
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
|
+
- On the first prompt of each session, automatically recalls the user
|
|
16
|
+
profile, recent project memories, and user memories relevant to the prompt,
|
|
17
|
+
and injects them into context.
|
|
18
|
+
- Redacts `<private>...</private>` blocks before sending anything to the cloud.
|
|
19
|
+
- Reuses your existing Supermemory credentials — zero extra setup if you
|
|
20
|
+
already use opencode-supermemory.
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pi install npm:@lykling/pi-supermemory
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Configuration
|
|
29
|
+
|
|
30
|
+
API key resolution order (first match wins):
|
|
31
|
+
|
|
32
|
+
1. `SUPERMEMORY_API_KEY` environment variable
|
|
33
|
+
2. `~/.pi/agent/supermemory.json` — pi-native config:
|
|
34
|
+
```json
|
|
35
|
+
{ "apiKey": "sm_...", "autoRecall": "full" }
|
|
36
|
+
```
|
|
37
|
+
3. `~/.config/opencode/supermemory.jsonc` — shared with opencode
|
|
38
|
+
4. `~/.supermemory-opencode/credentials.json` — opencode device-flow login
|
|
39
|
+
|
|
40
|
+
Other options:
|
|
41
|
+
|
|
42
|
+
- `SUPERMEMORY_API_BASE_URL` — override `https://api.supermemory.ai`
|
|
43
|
+
- `SUPERMEMORY_REPO_TAG` — force a fixed container tag
|
|
44
|
+
- `SUPERMEMORY_ISOLATE_WORKTREES=true` — give each git worktree its own tag
|
|
45
|
+
- `autoRecall` in `~/.pi/agent/supermemory.json`:
|
|
46
|
+
`"full"` (default; profile + project list + prompt search),
|
|
47
|
+
`"profile"` (profile only), or `"off"`
|
|
48
|
+
|
|
49
|
+
## The tool
|
|
50
|
+
|
|
51
|
+
| mode | args | description |
|
|
52
|
+
|---|---|---|
|
|
53
|
+
| `add` | `content`, `type?`, `scope?` | Store a memory (`scope`: `user`/`project`, default `project`) |
|
|
54
|
+
| `search` | `query`, `scope?`, `limit?` | Hybrid search over memories |
|
|
55
|
+
| `list` | `scope?`, `limit?` | List recent memories |
|
|
56
|
+
| `profile` | `query?` | User profile extracted by Supermemory |
|
|
57
|
+
| `forget` | `memoryId` | Delete a memory |
|
|
58
|
+
| `help` | — | Usage guide |
|
|
59
|
+
|
|
60
|
+
## Development
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
npm install
|
|
64
|
+
npm run typecheck
|
|
65
|
+
npm test
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
The extension is plain TypeScript loaded by pi via jiti — no build step.
|
|
69
|
+
|
|
70
|
+
## License
|
|
71
|
+
|
|
72
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lykling/pi-supermemory",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.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+ssh://git@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
|
+
}
|
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,156 @@
|
|
|
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
|
+
/** Inject recalled memories into the first prompt of each session. */
|
|
10
|
+
autoRecall: "full" | "profile" | "off";
|
|
11
|
+
similarityThreshold: number;
|
|
12
|
+
maxMemories: number;
|
|
13
|
+
maxProjectMemories: number;
|
|
14
|
+
maxProfileItems: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const DEFAULT_BASE_URL = "https://api.supermemory.ai";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Strip line and block comments plus trailing commas so JSONC files parse.
|
|
21
|
+
* Port of the jsonc parser used by opencode-supermemory.
|
|
22
|
+
*/
|
|
23
|
+
export function stripJsoncComments(content: string): string {
|
|
24
|
+
let result = "";
|
|
25
|
+
let i = 0;
|
|
26
|
+
let inString = false;
|
|
27
|
+
let inSingleLineComment = false;
|
|
28
|
+
let inMultiLineComment = false;
|
|
29
|
+
while (i < content.length) {
|
|
30
|
+
const char = content[i];
|
|
31
|
+
const nextChar = content[i + 1];
|
|
32
|
+
if (!inSingleLineComment && !inMultiLineComment) {
|
|
33
|
+
if (char === '"') {
|
|
34
|
+
let backslashCount = 0;
|
|
35
|
+
let j = i - 1;
|
|
36
|
+
while (j >= 0 && content[j] === "\\") {
|
|
37
|
+
backslashCount++;
|
|
38
|
+
j--;
|
|
39
|
+
}
|
|
40
|
+
if (backslashCount % 2 === 0) {
|
|
41
|
+
inString = !inString;
|
|
42
|
+
}
|
|
43
|
+
result += char;
|
|
44
|
+
i++;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (inString) {
|
|
49
|
+
result += char;
|
|
50
|
+
i++;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (!inSingleLineComment && !inMultiLineComment) {
|
|
54
|
+
if (char === "/" && nextChar === "/") {
|
|
55
|
+
inSingleLineComment = true;
|
|
56
|
+
i += 2;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (char === "/" && nextChar === "*") {
|
|
60
|
+
inMultiLineComment = true;
|
|
61
|
+
i += 2;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (inSingleLineComment) {
|
|
66
|
+
if (char === "\n") {
|
|
67
|
+
inSingleLineComment = false;
|
|
68
|
+
result += char;
|
|
69
|
+
}
|
|
70
|
+
i++;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (inMultiLineComment) {
|
|
74
|
+
if (char === "*" && nextChar === "/") {
|
|
75
|
+
inMultiLineComment = false;
|
|
76
|
+
i += 2;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (char === "\n") {
|
|
80
|
+
result += char;
|
|
81
|
+
}
|
|
82
|
+
i++;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
result += char;
|
|
86
|
+
i++;
|
|
87
|
+
}
|
|
88
|
+
return result.replace(/,\s*([}\]])/g, "$1");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Read and parse a JSON or JSONC file, returning null on any failure. */
|
|
92
|
+
export function readJsonFile(path: string): Record<string, unknown> | null {
|
|
93
|
+
try {
|
|
94
|
+
if (!existsSync(path)) return null;
|
|
95
|
+
const raw = readFileSync(path, "utf-8");
|
|
96
|
+
return JSON.parse(stripJsoncComments(raw)) as Record<string, unknown>;
|
|
97
|
+
} catch {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function firstString(...values: unknown[]): string | undefined {
|
|
103
|
+
for (const value of values) {
|
|
104
|
+
if (typeof value === "string" && value.trim()) return value.trim();
|
|
105
|
+
}
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Resolve credentials and settings.
|
|
111
|
+
*
|
|
112
|
+
* API key precedence (later sources reuse credentials you already have):
|
|
113
|
+
* 1. SUPERMEMORY_API_KEY env var
|
|
114
|
+
* 2. ~/.pi/agent/supermemory.json (pi-native config)
|
|
115
|
+
* 3. ~/.config/opencode/supermemory.jsonc (shared with opencode plugin)
|
|
116
|
+
* 4. ~/.supermemory-opencode/credentials.json (opencode device-flow login)
|
|
117
|
+
*/
|
|
118
|
+
export function resolveSettings(): SupermemorySettings {
|
|
119
|
+
const piConfig = readJsonFile(join(homedir(), ".pi", "agent", "supermemory.json"));
|
|
120
|
+
const opencodeConfig = readJsonFile(
|
|
121
|
+
join(homedir(), ".config", "opencode", "supermemory.jsonc"),
|
|
122
|
+
);
|
|
123
|
+
const opencodeCredentials = readJsonFile(
|
|
124
|
+
join(homedir(), ".supermemory-opencode", "credentials.json"),
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
const apiKey = firstString(
|
|
128
|
+
process.env.SUPERMEMORY_API_KEY,
|
|
129
|
+
piConfig?.apiKey,
|
|
130
|
+
opencodeConfig?.apiKey,
|
|
131
|
+
opencodeCredentials?.apiKey,
|
|
132
|
+
);
|
|
133
|
+
const baseUrl = firstString(
|
|
134
|
+
process.env.SUPERMEMORY_API_BASE_URL,
|
|
135
|
+
piConfig?.apiBaseUrl,
|
|
136
|
+
opencodeConfig?.apiBaseUrl,
|
|
137
|
+
opencodeCredentials?.apiBaseUrl,
|
|
138
|
+
DEFAULT_BASE_URL,
|
|
139
|
+
) as string;
|
|
140
|
+
|
|
141
|
+
const autoRecallRaw = firstString(piConfig?.autoRecall);
|
|
142
|
+
const autoRecall: SupermemorySettings["autoRecall"] =
|
|
143
|
+
autoRecallRaw === "full" || autoRecallRaw === "profile" || autoRecallRaw === "off"
|
|
144
|
+
? autoRecallRaw
|
|
145
|
+
: "full";
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
apiKey,
|
|
149
|
+
baseUrl,
|
|
150
|
+
autoRecall,
|
|
151
|
+
similarityThreshold: 0.6,
|
|
152
|
+
maxMemories: 5,
|
|
153
|
+
maxProjectMemories: 10,
|
|
154
|
+
maxProfileItems: 5,
|
|
155
|
+
};
|
|
156
|
+
}
|
package/src/context.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { MemoryResult, ProfileResult } from "./api.ts";
|
|
2
|
+
|
|
3
|
+
/** Format recalled memories into a compact context block for the LLM. */
|
|
4
|
+
export function formatMemoryContext(options: {
|
|
5
|
+
profile: ProfileResult | null;
|
|
6
|
+
userResults: MemoryResult[];
|
|
7
|
+
projectResults: MemoryResult[];
|
|
8
|
+
maxProfileItems: number;
|
|
9
|
+
}): string {
|
|
10
|
+
const parts: string[] = [];
|
|
11
|
+
const { profile, userResults, projectResults, maxProfileItems } = options;
|
|
12
|
+
|
|
13
|
+
if (profile && (profile.static.length > 0 || profile.dynamic.length > 0)) {
|
|
14
|
+
parts.push("User Profile:");
|
|
15
|
+
for (const line of profile.static.slice(0, maxProfileItems)) {
|
|
16
|
+
parts.push(`- ${line}`);
|
|
17
|
+
}
|
|
18
|
+
for (const line of profile.dynamic.slice(0, maxProfileItems)) {
|
|
19
|
+
parts.push(`- ${line}`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
if (projectResults.length > 0) {
|
|
24
|
+
parts.push("\nProject Knowledge:");
|
|
25
|
+
for (const memory of projectResults) {
|
|
26
|
+
const content = memory.memory || memory.chunk || memory.content || memory.summary || "";
|
|
27
|
+
if (content) parts.push(`- ${content}`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (userResults.length > 0) {
|
|
32
|
+
parts.push("\nRelevant Memories:");
|
|
33
|
+
for (const memory of userResults) {
|
|
34
|
+
const similarity = Math.round((memory.similarity ?? 0) * 100);
|
|
35
|
+
const content = memory.memory || memory.chunk || memory.content || "";
|
|
36
|
+
if (content) parts.push(`- [${similarity}%] ${content}`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (parts.length === 0) return "";
|
|
41
|
+
return `[Supermemory — persistent memory recalled for this project]\n${parts.join("\n")}`;
|
|
42
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
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 } from "./context.ts";
|
|
7
|
+
import { isFullyPrivate, stripPrivateContent } from "./privacy.ts";
|
|
8
|
+
import { getProjectName, getProjectIdentity, getProjectTag, getScopeFilters } from "./tags.ts";
|
|
9
|
+
|
|
10
|
+
const VERSION = "0.1.0";
|
|
11
|
+
const PLUGIN_NAME = "@lykling/pi-supermemory";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Persistent Supermemory memory for pi.
|
|
15
|
+
*
|
|
16
|
+
* Reuses the Supermemory cloud account already configured for opencode
|
|
17
|
+
* (same API key, same per-repo container tags), so memories are shared
|
|
18
|
+
* across both agents.
|
|
19
|
+
*/
|
|
20
|
+
export default function supermemoryExtension(pi: ExtensionAPI) {
|
|
21
|
+
const settings = resolveSettings();
|
|
22
|
+
if (!settings.apiKey) {
|
|
23
|
+
// Not configured: stay silent. Set SUPERMEMORY_API_KEY or create
|
|
24
|
+
// ~/.pi/agent/supermemory.json, then run /reload.
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const client = new SupermemoryClient(settings.apiKey, settings.baseUrl);
|
|
29
|
+
|
|
30
|
+
const tagsFor = (directory: string) => ({
|
|
31
|
+
containerTag: getProjectTag(directory),
|
|
32
|
+
projectId: getProjectIdentity(directory),
|
|
33
|
+
projectName: getProjectName(directory),
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
pi.registerTool({
|
|
37
|
+
name: "supermemory",
|
|
38
|
+
label: "Supermemory",
|
|
39
|
+
description:
|
|
40
|
+
"Manage and query the Supermemory persistent memory system shared across coding agents and sessions. " +
|
|
41
|
+
"Use 'search' to find relevant memories, 'add' to store new knowledge, 'list' to see recent memories, " +
|
|
42
|
+
"'profile' to view the user profile, 'forget' to remove a memory.",
|
|
43
|
+
promptSnippet: "Search, add, list, or forget persistent memories shared across sessions and agents",
|
|
44
|
+
promptGuidelines: [
|
|
45
|
+
"Use supermemory with mode=search when starting a task that may build on earlier work in this project, or when the user references past decisions or preferences.",
|
|
46
|
+
"Use supermemory with mode=add when the user asks to remember something, or when a durable fact, preference, or error-solution worth keeping emerges.",
|
|
47
|
+
],
|
|
48
|
+
parameters: Type.Object({
|
|
49
|
+
mode: StringEnum(["add", "search", "profile", "list", "forget", "help"], {
|
|
50
|
+
description: "Operation to perform (default: help)",
|
|
51
|
+
}),
|
|
52
|
+
content: Type.Optional(
|
|
53
|
+
Type.String({ description: "Memory content to store (mode=add)" }),
|
|
54
|
+
),
|
|
55
|
+
query: Type.Optional(Type.String({ description: "Search query (mode=search, mode=profile)" })),
|
|
56
|
+
type: Type.Optional(
|
|
57
|
+
StringEnum(
|
|
58
|
+
["project-config", "architecture", "error-solution", "preference", "learned-pattern", "conversation"],
|
|
59
|
+
{ description: "Memory type (mode=add)" },
|
|
60
|
+
),
|
|
61
|
+
),
|
|
62
|
+
scope: Type.Optional(
|
|
63
|
+
StringEnum(["user", "project"], {
|
|
64
|
+
description: "user = personal preferences for this project, project = project knowledge (default)",
|
|
65
|
+
}),
|
|
66
|
+
),
|
|
67
|
+
memoryId: Type.Optional(Type.String({ description: "Memory id to remove (mode=forget)" })),
|
|
68
|
+
limit: Type.Optional(Type.Number({ description: "Max results (mode=search, mode=list)" })),
|
|
69
|
+
}),
|
|
70
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
71
|
+
const mode = params.mode ?? "help";
|
|
72
|
+
const tags = tagsFor(ctx.cwd);
|
|
73
|
+
|
|
74
|
+
try {
|
|
75
|
+
switch (mode) {
|
|
76
|
+
case "add": {
|
|
77
|
+
if (!params.content) {
|
|
78
|
+
return text({ success: false, error: "content parameter is required for add mode" });
|
|
79
|
+
}
|
|
80
|
+
if (isFullyPrivate(params.content)) {
|
|
81
|
+
return text({ success: false, error: "Cannot store fully private content" });
|
|
82
|
+
}
|
|
83
|
+
const scope = params.scope ?? "project";
|
|
84
|
+
const internalScope = scope === "user" ? "personal" : "project";
|
|
85
|
+
const result = await client.addMemory(
|
|
86
|
+
stripPrivateContent(params.content),
|
|
87
|
+
tags.containerTag,
|
|
88
|
+
{
|
|
89
|
+
type: params.type,
|
|
90
|
+
project: tags.projectName,
|
|
91
|
+
sm_project_id: tags.projectId,
|
|
92
|
+
sm_scope: internalScope,
|
|
93
|
+
sm_capture_mode: "tool",
|
|
94
|
+
sm_source: "pi",
|
|
95
|
+
sm_client: PLUGIN_NAME,
|
|
96
|
+
sm_plugin_version: VERSION,
|
|
97
|
+
},
|
|
98
|
+
signal,
|
|
99
|
+
);
|
|
100
|
+
if (!result.success) {
|
|
101
|
+
return text({ success: false, error: result.error || "Failed to add memory" });
|
|
102
|
+
}
|
|
103
|
+
return text({
|
|
104
|
+
success: true,
|
|
105
|
+
message: `Memory added to ${scope} scope`,
|
|
106
|
+
id: result.id,
|
|
107
|
+
scope,
|
|
108
|
+
type: params.type,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
case "search": {
|
|
113
|
+
if (!params.query) {
|
|
114
|
+
return text({ success: false, error: "query parameter is required for search mode" });
|
|
115
|
+
}
|
|
116
|
+
const filters = params.scope
|
|
117
|
+
? getScopeFilters(params.scope === "user" ? "personal" : "project")
|
|
118
|
+
: undefined;
|
|
119
|
+
const result = await client.searchMemories(params.query, tags.containerTag, {
|
|
120
|
+
threshold: settings.similarityThreshold,
|
|
121
|
+
limit: params.limit ?? settings.maxMemories,
|
|
122
|
+
filters,
|
|
123
|
+
signal,
|
|
124
|
+
});
|
|
125
|
+
if (!result.success) {
|
|
126
|
+
return text({ success: false, error: result.error || "Search failed" });
|
|
127
|
+
}
|
|
128
|
+
return text({
|
|
129
|
+
success: true,
|
|
130
|
+
query: params.query,
|
|
131
|
+
scope: params.scope,
|
|
132
|
+
results: result.results.map((m) => ({
|
|
133
|
+
// Top-level id is a chunk id; the deletable memory id lives in documents[0].
|
|
134
|
+
id: m.documents?.[0]?.id ?? m.id,
|
|
135
|
+
content: m.memory || m.chunk || m.content || "",
|
|
136
|
+
title: m.title,
|
|
137
|
+
similarity: m.similarity,
|
|
138
|
+
metadata: m.metadata,
|
|
139
|
+
})),
|
|
140
|
+
total: result.total,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
case "list": {
|
|
145
|
+
const filters = params.scope
|
|
146
|
+
? getScopeFilters(params.scope === "user" ? "personal" : "project")
|
|
147
|
+
: undefined;
|
|
148
|
+
const result = await client.listMemories(
|
|
149
|
+
tags.containerTag,
|
|
150
|
+
params.limit ?? 20,
|
|
151
|
+
filters,
|
|
152
|
+
signal,
|
|
153
|
+
);
|
|
154
|
+
if (!result.success) {
|
|
155
|
+
return text({ success: false, error: result.error || "List failed" });
|
|
156
|
+
}
|
|
157
|
+
return text({
|
|
158
|
+
success: true,
|
|
159
|
+
memories: result.memories.map((m) => ({
|
|
160
|
+
id: m.id,
|
|
161
|
+
content: m.summary || m.content || m.title || "",
|
|
162
|
+
metadata: m.metadata,
|
|
163
|
+
createdAt: m.createdAt,
|
|
164
|
+
})),
|
|
165
|
+
containerTag: tags.containerTag,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
case "forget": {
|
|
170
|
+
if (!params.memoryId) {
|
|
171
|
+
return text({ success: false, error: "memoryId parameter is required for forget mode" });
|
|
172
|
+
}
|
|
173
|
+
const result = await client.deleteMemory(params.memoryId, signal);
|
|
174
|
+
if (!result.success) {
|
|
175
|
+
return text({ success: false, error: result.error || "Failed to delete memory" });
|
|
176
|
+
}
|
|
177
|
+
return text({ success: true, message: `Memory ${params.memoryId} deleted` });
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
case "profile": {
|
|
181
|
+
const filters = params.scope
|
|
182
|
+
? getScopeFilters(params.scope === "user" ? "personal" : "project")
|
|
183
|
+
: undefined;
|
|
184
|
+
const result = await client.getProfile(
|
|
185
|
+
tags.containerTag,
|
|
186
|
+
params.query,
|
|
187
|
+
filters,
|
|
188
|
+
signal,
|
|
189
|
+
);
|
|
190
|
+
if (!result.success) {
|
|
191
|
+
return text({ success: false, error: result.error || "Failed to load profile" });
|
|
192
|
+
}
|
|
193
|
+
return text({ success: true, profile: result.profile });
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
case "help":
|
|
197
|
+
default:
|
|
198
|
+
return text({
|
|
199
|
+
success: true,
|
|
200
|
+
message: "Supermemory Usage Guide (shared with opencode)",
|
|
201
|
+
commands: [
|
|
202
|
+
{ command: "add", description: "Store a new memory", args: ["content", "type?", "scope?"] },
|
|
203
|
+
{ command: "search", description: "Search memories", args: ["query", "scope?", "limit?"] },
|
|
204
|
+
{ command: "profile", description: "View user profile", args: ["query?"] },
|
|
205
|
+
{ command: "list", description: "List recent memories", args: ["scope?", "limit?"] },
|
|
206
|
+
{ command: "forget", description: "Remove a memory", args: ["memoryId"] },
|
|
207
|
+
],
|
|
208
|
+
scopes: {
|
|
209
|
+
user: "Personal preferences and knowledge for this project",
|
|
210
|
+
project: "Project-specific knowledge (default)",
|
|
211
|
+
},
|
|
212
|
+
containerTag: tags.containerTag,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
} catch (error) {
|
|
216
|
+
return text({
|
|
217
|
+
success: false,
|
|
218
|
+
error: error instanceof Error ? error.message : String(error),
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
// Recall memories on the first prompt of each session.
|
|
225
|
+
const injectedSessions = new Set<string>();
|
|
226
|
+
|
|
227
|
+
pi.on("before_agent_start", async (event, ctx) => {
|
|
228
|
+
if (settings.autoRecall === "off") return;
|
|
229
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
230
|
+
if (!sessionId || injectedSessions.has(sessionId)) return;
|
|
231
|
+
injectedSessions.add(sessionId);
|
|
232
|
+
|
|
233
|
+
try {
|
|
234
|
+
const tag = getProjectTag(ctx.cwd);
|
|
235
|
+
const prompt =
|
|
236
|
+
event.messageType === "user" ? (event as { prompt: string }).prompt : "";
|
|
237
|
+
const [profileResult, projectListResult, userSearchResult] = await Promise.all([
|
|
238
|
+
settings.autoRecall === "full"
|
|
239
|
+
? client.getProfile(tag, undefined, getScopeFilters("personal"))
|
|
240
|
+
: client.getProfile(tag),
|
|
241
|
+
settings.autoRecall === "full"
|
|
242
|
+
? client.listMemories(tag, settings.maxProjectMemories, getScopeFilters("project"))
|
|
243
|
+
: Promise.resolve(null),
|
|
244
|
+
settings.autoRecall === "full"
|
|
245
|
+
? client.searchMemories(prompt, tag, {
|
|
246
|
+
threshold: settings.similarityThreshold,
|
|
247
|
+
limit: settings.maxMemories,
|
|
248
|
+
filters: getScopeFilters("personal"),
|
|
249
|
+
})
|
|
250
|
+
: Promise.resolve(null),
|
|
251
|
+
]);
|
|
252
|
+
|
|
253
|
+
const content = formatMemoryContext({
|
|
254
|
+
profile: profileResult.success ? profileResult.profile : null,
|
|
255
|
+
userResults: userSearchResult?.results ?? [],
|
|
256
|
+
projectResults:
|
|
257
|
+
projectListResult?.memories.map((m) => ({
|
|
258
|
+
...m,
|
|
259
|
+
similarity: 1,
|
|
260
|
+
})) ?? [],
|
|
261
|
+
maxProfileItems: settings.maxProfileItems,
|
|
262
|
+
});
|
|
263
|
+
if (!content) return;
|
|
264
|
+
|
|
265
|
+
ctx.ui.notify(
|
|
266
|
+
`Supermemory: recalled ${projectListResult?.memories.length ?? 0} project / ${userSearchResult?.results.length ?? 0} user memories`,
|
|
267
|
+
"info",
|
|
268
|
+
);
|
|
269
|
+
return {
|
|
270
|
+
message: {
|
|
271
|
+
customType: "supermemory-recall",
|
|
272
|
+
content,
|
|
273
|
+
display: true,
|
|
274
|
+
},
|
|
275
|
+
};
|
|
276
|
+
} catch {
|
|
277
|
+
// Recall must never break the turn.
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function text(value: unknown) {
|
|
283
|
+
return {
|
|
284
|
+
content: [{ type: "text" as const, text: JSON.stringify(value, null, 2) }],
|
|
285
|
+
details: value as Record<string, unknown>,
|
|
286
|
+
};
|
|
287
|
+
}
|
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
|
+
}
|