@9to9/opencode-memos 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ama
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,368 @@
1
- # Temporary Holding Version
1
+ # @9to9/opencode-memos
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Persistent memory for [opencode](https://opencode.ai) — automatically **recalls** relevant memories before each prompt and **stores** new conversation turns after each run, backed by [MemOS Cloud](https://memos.memtensor.cn).
4
+
5
+ This is the **opencode** counterpart to the official MemOS Cloud lifecycle plugin (`@memtensor/memos-cloud-openclaw-plugin`, built for OpenClaw/Moltbot/ClawDBot). It ports the same lifecycle — **recall → answer → add** — to opencode's plugin hooks.
6
+
7
+ ---
8
+
9
+ ## Table of contents
10
+
11
+ - [Why](#why)
12
+ - [How it works](#how-it-works)
13
+ - [Lifecycle parity](#lifecycle-parity)
14
+ - [Requirements](#requirements)
15
+ - [Installation](#installation)
16
+ - [Configuration](#configuration)
17
+ - [Options](#options)
18
+ - [Credentials](#credentials)
19
+ - [MemOS API contract](#memos-api-contract)
20
+ - [Behavior details](#behavior-details)
21
+ - [Files and state](#files-and-state)
22
+ - [Security](#security)
23
+ - [Troubleshooting](#troubleshooting)
24
+ - [Development](#development)
25
+ - [FAQ](#faq)
26
+ - [License](#license)
27
+
28
+ ---
29
+
30
+ ## Why
31
+
32
+ LLM sessions are stateless. Without memory, every new opencode session starts from zero — it forgets decisions, IDs, deploy steps, and preferences from yesterday.
33
+
34
+ `@9to9/opencode-memos` fixes that:
35
+
36
+ - **Recall** — before the model answers, it searches your MemOS project for memories relevant to the current message and injects them into the system context.
37
+ - **Add** — when the session goes idle, it sends the new turns to MemOS, which extracts durable memories server-side.
38
+
39
+ No manual "remember this" prompts. No extra tools to call. It just happens.
40
+
41
+ ---
42
+
43
+ ## How it works
44
+
45
+ ```
46
+ ┌─────────────────────────────┐
47
+ user message ──▶│ experimental.chat.system. │
48
+ │ transform │
49
+ │ → find last user message │
50
+ │ → POST /search/memory │
51
+ │ → append "## MemOS recall" │
52
+ │ to system context │
53
+ └──────────────┬──────────────┘
54
+ │
55
+ LLM answers
56
+ │
57
+ ┌──────────────▼──────────────┐
58
+ │ event: session.idle │
59
+ │ → read new messages │
60
+ │ → POST /add/message │
61
+ └─────────────────────────────┘
62
+ ```
63
+
64
+ 1. **Recall** (`experimental.chat.system.transform`): reads the session messages, takes the latest user message as the query, calls `POST /search/memory`, and appends a formatted `## MemOS recall` block to `output.system`.
65
+ 2. **Add** (`session.idle`): reads the session messages, sends only the **new** messages since the last sync (per-session cursor), and updates the cursor on success.
66
+
67
+ Both steps are **fail-open**: network errors, timeouts, or bad responses are logged and never break the session.
68
+
69
+ ---
70
+
71
+ ## Lifecycle parity
72
+
73
+ | Capability | Official MemOS Cloud (OpenClaw) | This plugin (opencode) |
74
+ |---|---|---|
75
+ | Host | OpenClaw / Moltbot / ClawDBot | **opencode** |
76
+ | Recall / inject | `before_prompt_build` → `/search/memory` | `experimental.chat.system.transform` → `/search/memory` ✅ |
77
+ | Add | `agent_end` → `/add/message` | `session.idle` → `/add/message` ✅ |
78
+ | Auth | `Authorization: Token <key>` | same ✅ |
79
+ | Conversation id | `md5(user_id + "\n" + first message)` | same ✅ |
80
+ | Tags / KB ids | `tags`, `allow_knowledgebase_ids`, `knowledgebase_ids` | same ✅ |
81
+ | Dedup | snapshot-based | per-session cursor ✅ |
82
+ | Config UI | local web UI (`:38463`) | — (uses `opencode.json`) |
83
+ | Multi-agent / env-file resolution / update check | yes | — (not applicable / not implemented) |
84
+
85
+ The **core lifecycle is equivalent**. Host-specific extras (config UI, multi-agent isolation, env-file precedence, self-update) are intentionally out of scope because opencode resolves plugins and config differently.
86
+
87
+ ---
88
+
89
+ ## Requirements
90
+
91
+ - [opencode](https://opencode.ai) (plugin hooks `experimental.chat.system.transform` and `session.idle`)
92
+ - A MemOS Cloud API key (`mpg-…`) — https://memos-dashboard.openmem.net/cn/apikeys/
93
+ - A `MEMOS_USER_ID` (typically your email)
94
+ - Node/Bun runtime as used by opencode (the plugin only uses `node:` builtins and global `fetch`)
95
+
96
+ No npm dependencies.
97
+
98
+ ---
99
+
100
+ ## Installation
101
+
102
+ ### Option A — npm (recommended for everyone else)
103
+
104
+ Install from the npm registry (name on npm: `@9to9/opencode-memos`) and reference it by package name in `~/.config/opencode/opencode.json` (or a project `opencode.json`):
105
+
106
+ ```json
107
+ {
108
+ "$schema": "https://opencode.ai/config.json",
109
+ "plugin": [
110
+ [
111
+ "@9to9/opencode-memos",
112
+ {
113
+ "match": ["kirimwa"],
114
+ "knowledgebaseIds": ["base-xxxxxxxx"],
115
+ "tags": ["kirimwa", "opencode"]
116
+ }
117
+ ]
118
+ ]
119
+ }
120
+ ```
121
+
122
+ Pin a version with `"@9to9/opencode-memos@0.1.0"`.
123
+
124
+ ### Option B — local file (development / private)
125
+
126
+ ```json
127
+ {
128
+ "$schema": "https://opencode.ai/config.json",
129
+ "plugin": [
130
+ [
131
+ "file:///Users/ama/Repositories/opencode-memory-sync/index.ts",
132
+ {
133
+ "match": ["kirimwa"],
134
+ "knowledgebaseIds": ["base-xxxxxxxx"],
135
+ "tags": ["kirimwa", "opencode"]
136
+ }
137
+ ]
138
+ ]
139
+ }
140
+ ```
141
+
142
+ > Prefer a stable location (clone somewhere permanent) — the `file://` path must resolve after a restart.
143
+
144
+ Then **restart opencode** (plugins load at startup; config is not hot-reloaded).
145
+
146
+ The plugin also needs a `memos-mcp` entry so it can read credentials (see [Credentials](#credentials)), e.g.:
147
+
148
+ ```json
149
+ {
150
+ "mcp": {
151
+ "memos-mcp": {
152
+ "type": "local",
153
+ "command": ["npx", "-y", "@memtensor/memos-api-mcp@latest"],
154
+ "enabled": true,
155
+ "environment": {
156
+ "MEMOS_API_KEY": "mpg-…",
157
+ "MEMOS_USER_ID": "you@example.com"
158
+ }
159
+ }
160
+ }
161
+ }
162
+ ```
163
+
164
+ > Prefer a stable location for the file (e.g. clone the repo somewhere permanent) — the `file://` path must resolve after a restart.
165
+
166
+ ---
167
+
168
+ ## Configuration
169
+
170
+ Options are passed as the second element of the plugin tuple. All are optional.
171
+
172
+ ### Options
173
+
174
+ | Option | Type | Default | Description |
175
+ |---|---|---|---|
176
+ | `match` | `string[]` | `[]` | Only act on sessions whose `worktree`, `directory`, or message content contains one of these strings (case-insensitive). `[]` = every session. Use this to keep a project's memory isolated. |
177
+ | `knowledgebaseIds` | `string[]` | `[]` | Knowledge base ids sent to `/search/memory` (recall from curated docs). |
178
+ | `allowKnowledgebaseIds` | `string[]` | `[]` | KB ids sent to `/add/message` as `allow_knowledgebase_ids`. |
179
+ | `tags` | `string[]` | `[]` | Tags attached to `/add/message`. |
180
+ | `recallEnabled` | `boolean` | `true` | Enable recall injection. |
181
+ | `addEnabled` | `boolean` | `true` | Enable add-on-idle. |
182
+ | `memoryLimit` | `number` | `6` | Factual memories to recall (`memory_limit_number`). |
183
+ | `preferenceLimit` | `number` | `5` | Preference memories to recall (`preference_limit_number`). |
184
+ | `relativity` | `number` | — | Relevance threshold `0..1` for `/search/memory`. |
185
+ | `recallThrottleMs` | `number` | `3000` | Min gap between searches per session. |
186
+ | `recallCacheTtlMs` | `number` | `60000` | Reuse an identical-query result for this long. |
187
+ | `timeoutMs` | `number` | `6000` | HTTP timeout per request (both endpoints). |
188
+
189
+ ### Credentials
190
+
191
+ Resolution order:
192
+
193
+ 1. Environment variables `MEMOS_API_KEY`, `MEMOS_USER_ID`, `MEMOS_BASE_URL`, `MEMOS_SOURCE`
194
+ 2. `mcp.memos-mcp.environment` in `~/.config/opencode/opencode.json`
195
+
196
+ `MEMOS_BASE_URL` defaults to `https://memos.memtensor.cn/api/openmem/v1`.
197
+ `MEMOS_SOURCE` defaults to `MEMOS`.
198
+
199
+ ---
200
+
201
+ ## MemOS API contract
202
+
203
+ Auth header on every request:
204
+
205
+ ```
206
+ Authorization: Token <MEMOS_API_KEY>
207
+ Content-Type: application/json
208
+ ```
209
+
210
+ ### Recall — `POST {base}/search/memory`
211
+
212
+ ```json
213
+ {
214
+ "query": "<latest user message>",
215
+ "user_id": "you@example.com",
216
+ "memory_limit_number": 6,
217
+ "include_preference": true,
218
+ "preference_limit_number": 5,
219
+ "knowledgebase_ids": ["base-..."],
220
+ "relativity": 0.4,
221
+ "source": "MEMOS"
222
+ }
223
+ ```
224
+
225
+ The plugin reads `memory_detail_list[]` and `preference_detail_list[]` from the response and formats the top entries into a `## MemOS recall` block.
226
+
227
+ ### Add — `POST {base}/add/message`
228
+
229
+ ```json
230
+ {
231
+ "user_id": "you@example.com",
232
+ "conversation_id": "<md5(user_id + \"\\n\" + first user message)>",
233
+ "messages": [
234
+ { "role": "user", "content": "..." },
235
+ { "role": "assistant", "content": "..." }
236
+ ],
237
+ "tags": ["kirimwa", "opencode"],
238
+ "allow_knowledgebase_ids": ["base-..."],
239
+ "source": "MEMOS"
240
+ }
241
+ ```
242
+
243
+ `conversation_id` is derived exactly like the official plugin / MemOS MCP, so memories land in the same conversation thread.
244
+
245
+ ---
246
+
247
+ ## Behavior details
248
+
249
+ - **Scoping (`match`).** If provided, the plugin only acts when the session's worktree, directory, or any message text contains one of the keywords. This lets you keep one MemOS project clean while running other work in the same opencode install.
250
+ - **Incremental add.** A per-session cursor (`state.json`) tracks how many message entries were already sent; only new ones are posted. No duplicate memories.
251
+ - **Recall cache.** Identical query within `recallCacheTtlMs` reuses the previous result; `recallThrottleMs` limits request frequency across rapid prompt builds (tool loops).
252
+ - **Content caps.** Text parts only (tool output ignored); each message capped at 8,000 chars, recall block at 4,000 chars.
253
+ - **Fail-open.** Any error is written to the log and the session continues normally.
254
+
255
+ ---
256
+
257
+ ## Files and state
258
+
259
+ | Path | Purpose |
260
+ |---|---|
261
+ | `~/.local/share/opencode-memory-sync/state.json` | Per-session cursors (dedup) |
262
+ | `~/.local/share/opencode-memory-sync/plugin.log` | Runtime log (syncs, failures) |
263
+
264
+ Delete `state.json` to force a full re-sync of new sessions; delete `plugin.log` to reset logs.
265
+
266
+ ---
267
+
268
+ ## Security
269
+
270
+ - **No secrets in this repo.** Credentials are read at runtime from your opencode config or env.
271
+ - Only message **text parts** are sent to MemOS; tool calls/outputs are excluded.
272
+ - Requests are scoped to the MemOS project tied to your API key.
273
+ - Timeouts are enforced; failures never interrupt opencode.
274
+
275
+ ---
276
+
277
+ ## Troubleshooting
278
+
279
+ **Nothing happens / no log file**
280
+ - Did you restart opencode after editing `opencode.json`?
281
+ - Verify the `file://` path exists and is a `.ts` file.
282
+ - Check `~/.local/share/opencode-memory-sync/plugin.log`.
283
+
284
+ **`add/message failed (401)`**
285
+ - Wrong/expired `MEMOS_API_KEY`, or key not set in the `memos-mcp` env / `MEMOS_API_KEY`.
286
+
287
+ **Recall is empty**
288
+ - No memories yet for this user, or `knowledgebaseIds` points to an empty KB.
289
+ - Try lowering `relativity` or raising `memoryLimit`.
290
+
291
+ **Sessions aren't syncing**
292
+ - `match` may exclude them. Use `match: []` to sync everything, or include the right keyword.
293
+
294
+ **Duplicate memories**
295
+ - Delete `state.json` and restart to reset cursors (this will resend recent messages).
296
+
297
+ **Slow prompts**
298
+ - Increase `recallThrottleMs` / `recallCacheTtlMs`, lower `memoryLimit`, or disable recall with `recallEnabled: false`.
299
+
300
+ ---
301
+
302
+ ## Development
303
+
304
+ The plugin has no dependencies and uses only `node:` builtins + global `fetch`.
305
+
306
+ Quick load check (Node with TS type stripping, e.g. Node 22+):
307
+
308
+ ```bash
309
+ node --input-type=module -e "import('file://'"$PWD"'/index.ts').then(m=>console.log(typeof m.default))"
310
+ ```
311
+
312
+ It should print `function`.
313
+
314
+ Hooks rely on the `@opencode-ai/plugin` types but do **not** import them at runtime (type-only), so no install is needed inside this repo.
315
+
316
+ ---
317
+
318
+ ## Distribution / maintainers
319
+
320
+ **Build the publishable bundle** (plain ESM `dist/index.js`, so both opencode and normal Node consumers can import it):
321
+
322
+ ```bash
323
+ npm run build # npx esbuild ... -> dist/index.js
324
+ npm pack # produces 9to9-opencode-memos-X.Y.Z.tgz
325
+ ```
326
+
327
+ `package.json` points `main`/`exports` at `dist/index.js` and `prepublishOnly` builds automatically before publish.
328
+
329
+ **Publish to npm** (pick one):
330
+
331
+ ```bash
332
+ # manual
333
+ npm login
334
+ npm publish --access public
335
+
336
+ # or: bump version, tag, push — the Release workflow publishes
337
+ npm version patch # creates vX.Y.Z tag
338
+ git push --follow-tags
339
+ ```
340
+
341
+ **GitHub Actions** (in `.github/workflows/`):
342
+
343
+ - `ci.yml` — on push/PR: bundles with esbuild, verifies the default export, and runs `npm pack --dry-run`.
344
+ - `release.yml` — on `v*` tags (or manual dispatch): builds and runs `npm publish --access public` via **npm Trusted Publishing (OIDC)** — no token.
345
+
346
+ To enable automated publishing, register a **Trusted Publisher** on npm for `@9to9/opencode-memos`: package **Settings → Trusted publishing → GitHub Actions**, user `amajust`, repo `opencode-memos`, workflow `release.yml`. No `NPM_TOKEN` secret is needed. No Actions are required for installation — they only automate validation and publishing.
347
+
348
+ ---
349
+
350
+ ## FAQ
351
+
352
+ **Does it replace the `memos-mcp` MCP server?**
353
+ No. The MCP gives the model explicit `search_memory` / `add_message` tools. This plugin automates recall + add on lifecycle events. They can coexist (with a slight duplicate risk if the model also calls `add_message` manually — the accompanying instruction file disables that).
354
+
355
+ **Does it work per project?**
356
+ Yes — MemOS projects are keyed by API key. The plugin writes to whichever project the configured key belongs to; `match` keeps sessions scoped.
357
+
358
+ **Can I use it for a different MemOS project?**
359
+ Change `MEMOS_API_KEY` (and optionally `knowledgebaseIds`/`tags`) and restart.
360
+
361
+ **Is it the same as the official OpenClaw plugin?**
362
+ Same lifecycle and API; different host and a smaller feature set (no config UI/multi-agent/self-update).
363
+
364
+ ---
365
+
366
+ ## License
367
+
368
+ MIT © 2026 Ama
package/dist/index.js ADDED
@@ -0,0 +1,223 @@
1
+ // index.ts
2
+ import { createHash } from "node:crypto";
3
+ import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+ var CONFIG_PATH = join(homedir(), ".config", "opencode", "opencode.json");
7
+ var DATA_DIR = join(homedir(), ".local", "share", "opencode-memory-sync");
8
+ var STATE_PATH = join(DATA_DIR, "state.json");
9
+ var LOG_PATH = join(DATA_DIR, "plugin.log");
10
+ function ensureDir() {
11
+ try {
12
+ mkdirSync(DATA_DIR, { recursive: true });
13
+ } catch {
14
+ }
15
+ }
16
+ function log(msg) {
17
+ try {
18
+ ensureDir();
19
+ appendFileSync(LOG_PATH, `[${(/* @__PURE__ */ new Date()).toISOString()}] ${msg}
20
+ `);
21
+ } catch {
22
+ }
23
+ }
24
+ function listOf(v) {
25
+ return Array.isArray(v) ? v.map((s) => String(s)).filter(Boolean) : [];
26
+ }
27
+ function readCreds() {
28
+ let apiKey = process.env.MEMOS_API_KEY || "";
29
+ let userId = process.env.MEMOS_USER_ID || "";
30
+ let baseUrl = process.env.MEMOS_BASE_URL || "";
31
+ let source = process.env.MEMOS_SOURCE || "MEMOS";
32
+ try {
33
+ const cfg = JSON.parse(readFileSync(CONFIG_PATH, "utf8"));
34
+ const env = cfg && cfg.mcp && cfg.mcp["memos-mcp"] && cfg.mcp["memos-mcp"].environment || {};
35
+ apiKey = apiKey || env.MEMOS_API_KEY || "";
36
+ userId = userId || env.MEMOS_USER_ID || "";
37
+ baseUrl = baseUrl || env.MEMOS_BASE_URL || "";
38
+ source = process.env.MEMOS_SOURCE || env.MEMOS_SOURCE || source;
39
+ } catch (e) {
40
+ log("config read failed: " + (e instanceof Error ? e.message : String(e)));
41
+ }
42
+ return {
43
+ apiKey,
44
+ userId,
45
+ baseUrl: (baseUrl || "https://memos.memtensor.cn/api/openmem/v1").replace(/\/+$/, ""),
46
+ source
47
+ };
48
+ }
49
+ function loadState() {
50
+ try {
51
+ const j = JSON.parse(readFileSync(STATE_PATH, "utf8"));
52
+ return j && typeof j === "object" ? j : {};
53
+ } catch {
54
+ return {};
55
+ }
56
+ }
57
+ function saveState(s) {
58
+ try {
59
+ ensureDir();
60
+ writeFileSync(STATE_PATH, JSON.stringify(s));
61
+ } catch (e) {
62
+ log("state save failed: " + (e instanceof Error ? e.message : String(e)));
63
+ }
64
+ }
65
+ function textOf(parts) {
66
+ if (!Array.isArray(parts)) return "";
67
+ return parts.filter((p) => p && p.type === "text" && typeof p.text === "string").map((p) => p.text).join("\n").trim();
68
+ }
69
+ async function postJson(baseUrl, apiKey, path, body, timeoutMs) {
70
+ const ctrl = new AbortController();
71
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
72
+ try {
73
+ const res = await fetch(baseUrl + path, {
74
+ method: "POST",
75
+ headers: { "Content-Type": "application/json", Authorization: "Token " + apiKey },
76
+ body: JSON.stringify(body),
77
+ signal: ctrl.signal
78
+ });
79
+ if (!res.ok) {
80
+ const text = await res.text().catch(() => "");
81
+ return { ok: false, status: res.status, error: text.slice(0, 300) };
82
+ }
83
+ return { ok: true, data: await res.json().catch(() => null) };
84
+ } catch (e) {
85
+ return { ok: false, status: 0, error: e instanceof Error ? e.message : String(e) };
86
+ } finally {
87
+ clearTimeout(timer);
88
+ }
89
+ }
90
+ function formatRecall(data) {
91
+ const mem = Array.isArray(data && data.memory_detail_list) ? data.memory_detail_list.map((x) => x && x.memory_value) : [];
92
+ const pref = Array.isArray(data && data.preference_detail_list) ? data.preference_detail_list.map((x) => x && (x.memory_value || x.preference)) : [];
93
+ const items = [...mem, ...pref].map((s) => String(s || "").trim()).filter(Boolean);
94
+ if (items.length === 0) return "";
95
+ let out = "\n## MemOS recall\nRelevant memories from prior sessions. Use only if relevant to the current request; if they conflict with the user's latest message, prefer the user's message.\n";
96
+ let total = 0;
97
+ for (const it of items) {
98
+ const line = "- " + it.replace(/\s+/g, " ").slice(0, 600) + "\n";
99
+ if (total + line.length > 4e3) break;
100
+ out += line;
101
+ total += line.length;
102
+ }
103
+ return out;
104
+ }
105
+ async function plugin(input, options) {
106
+ const { client, directory, worktree } = input || {};
107
+ const opt = options || {};
108
+ const match = listOf(opt.match).map((s) => s.toLowerCase());
109
+ const knowledgebaseIds = listOf(opt.knowledgebaseIds);
110
+ const allowKnowledgebaseIds = listOf(opt.allowKnowledgebaseIds);
111
+ const tags = listOf(opt.tags);
112
+ const recallEnabled = opt.recallEnabled !== false;
113
+ const addEnabled = opt.addEnabled !== false;
114
+ const memoryLimit = Number(opt.memoryLimit) || 6;
115
+ const preferenceLimit = Number(opt.preferenceLimit) || 5;
116
+ const relativity = typeof opt.relativity === "number" ? opt.relativity : void 0;
117
+ const recallThrottleMs = Number.isFinite(opt.recallThrottleMs) ? Number(opt.recallThrottleMs) : 3e3;
118
+ const recallCacheTtlMs = Number.isFinite(opt.recallCacheTtlMs) ? Number(opt.recallCacheTtlMs) : 6e4;
119
+ const timeoutMs = Number(opt.timeoutMs) || 6e3;
120
+ const inflight = /* @__PURE__ */ new Set();
121
+ const recallCache = /* @__PURE__ */ new Map();
122
+ async function getSession(sessionID) {
123
+ const args = { path: { id: sessionID } };
124
+ if (directory) args.query = { directory };
125
+ const result = await client.session.messages(args);
126
+ const entries = Array.isArray(result) ? result : result && result.data ? result.data : [];
127
+ const mapped = (entries || []).map((e) => ({ role: String(e && e.info && e.info.role || ""), content: textOf(e && e.parts) })).filter((m) => m.content);
128
+ const hay = `${worktree || ""} ${directory || ""} ${mapped.map((m) => m.content).join(" ")}`.toLowerCase();
129
+ return { entries: entries || [], mapped, hay };
130
+ }
131
+ function inScope(hay) {
132
+ return match.length === 0 || match.some((k) => hay.includes(k));
133
+ }
134
+ async function recall(sessionID) {
135
+ try {
136
+ const { apiKey, userId, baseUrl, source } = readCreds();
137
+ if (!apiKey || !userId) return "";
138
+ const { mapped, hay } = await getSession(sessionID);
139
+ if (!inScope(hay)) return "";
140
+ const lastUser = [...mapped].reverse().find((m) => m.role === "user");
141
+ if (!lastUser || !lastUser.content) return "";
142
+ const query = lastUser.content.slice(0, 1e3);
143
+ const now = Date.now();
144
+ const cache = recallCache.get(sessionID);
145
+ if (cache && cache.query === query && now - cache.ts < recallCacheTtlMs) return cache.block;
146
+ if (cache && now - cache.ts < recallThrottleMs) return cache.block || "";
147
+ const body = {
148
+ query,
149
+ user_id: userId,
150
+ memory_limit_number: memoryLimit,
151
+ include_preference: true,
152
+ preference_limit_number: preferenceLimit,
153
+ source
154
+ };
155
+ if (knowledgebaseIds.length) body.knowledgebase_ids = knowledgebaseIds;
156
+ if (typeof relativity === "number") body.relativity = relativity;
157
+ const res = await postJson(baseUrl, apiKey, "/search/memory", body, timeoutMs);
158
+ const block = res.ok ? formatRecall(res.data) : "";
159
+ if (!res.ok) log(`search/memory failed (${res.status}): ${res.error}`);
160
+ recallCache.set(sessionID, { query, ts: now, block });
161
+ return block;
162
+ } catch (e) {
163
+ log("recall error: " + (e instanceof Error ? e.message : String(e)));
164
+ return "";
165
+ }
166
+ }
167
+ async function add(sessionID) {
168
+ if (!addEnabled || !sessionID || inflight.has(sessionID)) return;
169
+ inflight.add(sessionID);
170
+ try {
171
+ const { apiKey, userId, baseUrl, source } = readCreds();
172
+ if (!apiKey || !userId) return;
173
+ const { entries, mapped, hay } = await getSession(sessionID);
174
+ if (!entries.length || !inScope(hay)) return;
175
+ const state = loadState();
176
+ const cursor = Number.isInteger(state[sessionID]) ? state[sessionID] : 0;
177
+ if (entries.length <= cursor) return;
178
+ const firstUser = (mapped.find((m) => m.role === "user") || mapped[0]).content;
179
+ const conversationId = createHash("md5").update(userId + "\n" + firstUser).digest("hex");
180
+ const messages = entries.slice(cursor).map((e) => ({
181
+ role: String(e && e.info && e.info.role || "user") || "user",
182
+ content: textOf(e && e.parts).slice(0, 8e3)
183
+ })).filter((m) => m.content);
184
+ if (messages.length === 0) {
185
+ state[sessionID] = entries.length;
186
+ saveState(state);
187
+ return;
188
+ }
189
+ const body = { user_id: userId, conversation_id: conversationId, messages, source };
190
+ if (tags.length) body.tags = tags;
191
+ if (allowKnowledgebaseIds.length) body.allow_knowledgebase_ids = allowKnowledgebaseIds;
192
+ const res = await postJson(baseUrl, apiKey, "/add/message", body, timeoutMs);
193
+ if (!res.ok) {
194
+ log(`add/message failed (${res.status}): ${res.error}`);
195
+ return;
196
+ }
197
+ state[sessionID] = entries.length;
198
+ saveState(state);
199
+ log(`synced ${messages.length} message(s) session=${sessionID}`);
200
+ } catch (e) {
201
+ log("add error: " + (e instanceof Error ? e.message : String(e)));
202
+ } finally {
203
+ inflight.delete(sessionID);
204
+ }
205
+ }
206
+ return {
207
+ "experimental.chat.system.transform": async (hookInput, output) => {
208
+ if (!recallEnabled) return;
209
+ const sessionID = hookInput && hookInput.sessionID;
210
+ if (!sessionID || !output || !Array.isArray(output.system)) return;
211
+ const block = await recall(sessionID);
212
+ if (block) output.system.push(block);
213
+ },
214
+ event: async ({ event }) => {
215
+ if (!event || event.type !== "session.idle") return;
216
+ const sessionID = event.properties && event.properties.sessionID;
217
+ if (sessionID) await add(sessionID);
218
+ }
219
+ };
220
+ }
221
+ export {
222
+ plugin as default
223
+ };
package/index.ts ADDED
@@ -0,0 +1,299 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * @9to9/opencode-memos
4
+ *
5
+ * opencode equivalent of the official MemOS Cloud lifecycle plugin:
6
+ * - Recall: experimental.chat.system.transform -> POST /search/memory -> inject context
7
+ * - Add: session.idle -> POST /add/message
8
+ *
9
+ * Credentials are read from the `memos-mcp` server entry in
10
+ * ~/.config/opencode/opencode.json (or MEMOS_* env vars), so it writes to
11
+ * whichever MemOS project that API key belongs to.
12
+ *
13
+ * Install (opencode.json):
14
+ * "plugin": [
15
+ * ["file:///Users/ama/Repositories/opencode-memory-sync/index.ts", {
16
+ * "match": ["kirimwa"],
17
+ * "knowledgebaseIds": ["base-..."],
18
+ * "tags": ["kirimwa", "opencode"]
19
+ * }]
20
+ * ]
21
+ *
22
+ * Options:
23
+ * match[] only act on sessions whose worktree/dir/content contains one (ci). [] = all
24
+ * knowledgebaseIds[] KB ids passed to /search/memory
25
+ * allowKnowledgebaseIds[] KB ids passed to /add/message (allow_knowledgebase_ids)
26
+ * tags[] tags for /add/message
27
+ * recallEnabled default true
28
+ * addEnabled default true
29
+ * memoryLimit default 6
30
+ * preferenceLimit default 5
31
+ * relativity optional 0..1
32
+ * recallThrottleMs min gap between searches per session (default 3000)
33
+ * recallCacheTtlMs reuse identical query result (default 60000)
34
+ * timeoutMs HTTP timeout (default 6000)
35
+ */
36
+ import { createHash } from "node:crypto"
37
+ import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
38
+ import { homedir } from "node:os"
39
+ import { join } from "node:path"
40
+
41
+ const CONFIG_PATH = join(homedir(), ".config", "opencode", "opencode.json")
42
+ const DATA_DIR = join(homedir(), ".local", "share", "opencode-memory-sync")
43
+ const STATE_PATH = join(DATA_DIR, "state.json")
44
+ const LOG_PATH = join(DATA_DIR, "plugin.log")
45
+
46
+ function ensureDir() {
47
+ try {
48
+ mkdirSync(DATA_DIR, { recursive: true })
49
+ } catch {
50
+ /* ignore */
51
+ }
52
+ }
53
+
54
+ function log(msg) {
55
+ try {
56
+ ensureDir()
57
+ appendFileSync(LOG_PATH, `[${new Date().toISOString()}] ${msg}\n`)
58
+ } catch {
59
+ /* never break the session */
60
+ }
61
+ }
62
+
63
+ function listOf(v) {
64
+ return Array.isArray(v) ? v.map((s) => String(s)).filter(Boolean) : []
65
+ }
66
+
67
+ function readCreds() {
68
+ let apiKey = process.env.MEMOS_API_KEY || ""
69
+ let userId = process.env.MEMOS_USER_ID || ""
70
+ let baseUrl = process.env.MEMOS_BASE_URL || ""
71
+ let source = process.env.MEMOS_SOURCE || "MEMOS"
72
+ try {
73
+ const cfg = JSON.parse(readFileSync(CONFIG_PATH, "utf8"))
74
+ const env = (cfg && cfg.mcp && cfg.mcp["memos-mcp"] && cfg.mcp["memos-mcp"].environment) || {}
75
+ apiKey = apiKey || env.MEMOS_API_KEY || ""
76
+ userId = userId || env.MEMOS_USER_ID || ""
77
+ baseUrl = baseUrl || env.MEMOS_BASE_URL || ""
78
+ source = process.env.MEMOS_SOURCE || env.MEMOS_SOURCE || source
79
+ } catch (e) {
80
+ log("config read failed: " + (e instanceof Error ? e.message : String(e)))
81
+ }
82
+ return {
83
+ apiKey,
84
+ userId,
85
+ baseUrl: (baseUrl || "https://memos.memtensor.cn/api/openmem/v1").replace(/\/+$/, ""),
86
+ source,
87
+ }
88
+ }
89
+
90
+ function loadState() {
91
+ try {
92
+ const j = JSON.parse(readFileSync(STATE_PATH, "utf8"))
93
+ return j && typeof j === "object" ? j : {}
94
+ } catch {
95
+ return {}
96
+ }
97
+ }
98
+
99
+ function saveState(s) {
100
+ try {
101
+ ensureDir()
102
+ writeFileSync(STATE_PATH, JSON.stringify(s))
103
+ } catch (e) {
104
+ log("state save failed: " + (e instanceof Error ? e.message : String(e)))
105
+ }
106
+ }
107
+
108
+ function textOf(parts) {
109
+ if (!Array.isArray(parts)) return ""
110
+ return parts
111
+ .filter((p) => p && p.type === "text" && typeof p.text === "string")
112
+ .map((p) => p.text)
113
+ .join("\n")
114
+ .trim()
115
+ }
116
+
117
+ async function postJson(baseUrl, apiKey, path, body, timeoutMs) {
118
+ const ctrl = new AbortController()
119
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs)
120
+ try {
121
+ const res = await fetch(baseUrl + path, {
122
+ method: "POST",
123
+ headers: { "Content-Type": "application/json", Authorization: "Token " + apiKey },
124
+ body: JSON.stringify(body),
125
+ signal: ctrl.signal,
126
+ })
127
+ if (!res.ok) {
128
+ const text = await res.text().catch(() => "")
129
+ return { ok: false, status: res.status, error: text.slice(0, 300) }
130
+ }
131
+ return { ok: true, data: await res.json().catch(() => null) }
132
+ } catch (e) {
133
+ return { ok: false, status: 0, error: e instanceof Error ? e.message : String(e) }
134
+ } finally {
135
+ clearTimeout(timer)
136
+ }
137
+ }
138
+
139
+ function formatRecall(data) {
140
+ const mem = Array.isArray(data && data.memory_detail_list)
141
+ ? data.memory_detail_list.map((x) => x && x.memory_value)
142
+ : []
143
+ const pref = Array.isArray(data && data.preference_detail_list)
144
+ ? data.preference_detail_list.map((x) => x && (x.memory_value || x.preference))
145
+ : []
146
+ const items = [...mem, ...pref].map((s) => String(s || "").trim()).filter(Boolean)
147
+ if (items.length === 0) return ""
148
+
149
+ let out =
150
+ "\n## MemOS recall\nRelevant memories from prior sessions. Use only if relevant to the current request; if they conflict with the user's latest message, prefer the user's message.\n"
151
+ let total = 0
152
+ for (const it of items) {
153
+ const line = "- " + it.replace(/\s+/g, " ").slice(0, 600) + "\n"
154
+ if (total + line.length > 4000) break
155
+ out += line
156
+ total += line.length
157
+ }
158
+ return out
159
+ }
160
+
161
+ export default async function plugin(input, options) {
162
+ const { client, directory, worktree } = input || {}
163
+ const opt = options || {}
164
+ const match = listOf(opt.match).map((s) => s.toLowerCase())
165
+ const knowledgebaseIds = listOf(opt.knowledgebaseIds)
166
+ const allowKnowledgebaseIds = listOf(opt.allowKnowledgebaseIds)
167
+ const tags = listOf(opt.tags)
168
+ const recallEnabled = opt.recallEnabled !== false
169
+ const addEnabled = opt.addEnabled !== false
170
+ const memoryLimit = Number(opt.memoryLimit) || 6
171
+ const preferenceLimit = Number(opt.preferenceLimit) || 5
172
+ const relativity = typeof opt.relativity === "number" ? opt.relativity : undefined
173
+ const recallThrottleMs = Number.isFinite(opt.recallThrottleMs) ? Number(opt.recallThrottleMs) : 3000
174
+ const recallCacheTtlMs = Number.isFinite(opt.recallCacheTtlMs) ? Number(opt.recallCacheTtlMs) : 60000
175
+ const timeoutMs = Number(opt.timeoutMs) || 6000
176
+
177
+ const inflight = new Set()
178
+ const recallCache = new Map() // sessionID -> { query, ts, block }
179
+
180
+ async function getSession(sessionID) {
181
+ const args = { path: { id: sessionID } }
182
+ if (directory) args.query = { directory }
183
+ const result = await client.session.messages(args)
184
+ const entries = Array.isArray(result) ? result : result && result.data ? result.data : []
185
+ const mapped = (entries || [])
186
+ .map((e) => ({ role: String((e && e.info && e.info.role) || ""), content: textOf(e && e.parts) }))
187
+ .filter((m) => m.content)
188
+ const hay = `${worktree || ""} ${directory || ""} ${mapped.map((m) => m.content).join(" ")}`.toLowerCase()
189
+ return { entries: entries || [], mapped, hay }
190
+ }
191
+
192
+ function inScope(hay) {
193
+ return match.length === 0 || match.some((k) => hay.includes(k))
194
+ }
195
+
196
+ async function recall(sessionID) {
197
+ try {
198
+ const { apiKey, userId, baseUrl, source } = readCreds()
199
+ if (!apiKey || !userId) return ""
200
+
201
+ const { mapped, hay } = await getSession(sessionID)
202
+ if (!inScope(hay)) return ""
203
+ const lastUser = [...mapped].reverse().find((m) => m.role === "user")
204
+ if (!lastUser || !lastUser.content) return ""
205
+
206
+ const query = lastUser.content.slice(0, 1000)
207
+ const now = Date.now()
208
+ const cache = recallCache.get(sessionID)
209
+ if (cache && cache.query === query && now - cache.ts < recallCacheTtlMs) return cache.block
210
+ if (cache && now - cache.ts < recallThrottleMs) return cache.block || ""
211
+
212
+ const body = {
213
+ query,
214
+ user_id: userId,
215
+ memory_limit_number: memoryLimit,
216
+ include_preference: true,
217
+ preference_limit_number: preferenceLimit,
218
+ source,
219
+ }
220
+ if (knowledgebaseIds.length) body.knowledgebase_ids = knowledgebaseIds
221
+ if (typeof relativity === "number") body.relativity = relativity
222
+
223
+ const res = await postJson(baseUrl, apiKey, "/search/memory", body, timeoutMs)
224
+ const block = res.ok ? formatRecall(res.data) : ""
225
+ if (!res.ok) log(`search/memory failed (${res.status}): ${res.error}`)
226
+ recallCache.set(sessionID, { query, ts: now, block })
227
+ return block
228
+ } catch (e) {
229
+ log("recall error: " + (e instanceof Error ? e.message : String(e)))
230
+ return ""
231
+ }
232
+ }
233
+
234
+ async function add(sessionID) {
235
+ if (!addEnabled || !sessionID || inflight.has(sessionID)) return
236
+ inflight.add(sessionID)
237
+ try {
238
+ const { apiKey, userId, baseUrl, source } = readCreds()
239
+ if (!apiKey || !userId) return
240
+
241
+ const { entries, mapped, hay } = await getSession(sessionID)
242
+ if (!entries.length || !inScope(hay)) return
243
+
244
+ const state = loadState()
245
+ const cursor = Number.isInteger(state[sessionID]) ? state[sessionID] : 0
246
+ if (entries.length <= cursor) return
247
+
248
+ const firstUser = (mapped.find((m) => m.role === "user") || mapped[0]).content
249
+ const conversationId = createHash("md5").update(userId + "\n" + firstUser).digest("hex")
250
+
251
+ const messages = entries
252
+ .slice(cursor)
253
+ .map((e) => ({
254
+ role: String((e && e.info && e.info.role) || "user") || "user",
255
+ content: textOf(e && e.parts).slice(0, 8000),
256
+ }))
257
+ .filter((m) => m.content)
258
+
259
+ if (messages.length === 0) {
260
+ state[sessionID] = entries.length
261
+ saveState(state)
262
+ return
263
+ }
264
+
265
+ const body = { user_id: userId, conversation_id: conversationId, messages, source }
266
+ if (tags.length) body.tags = tags
267
+ if (allowKnowledgebaseIds.length) body.allow_knowledgebase_ids = allowKnowledgebaseIds
268
+
269
+ const res = await postJson(baseUrl, apiKey, "/add/message", body, timeoutMs)
270
+ if (!res.ok) {
271
+ log(`add/message failed (${res.status}): ${res.error}`)
272
+ return
273
+ }
274
+ state[sessionID] = entries.length
275
+ saveState(state)
276
+ log(`synced ${messages.length} message(s) session=${sessionID}`)
277
+ } catch (e) {
278
+ log("add error: " + (e instanceof Error ? e.message : String(e)))
279
+ } finally {
280
+ inflight.delete(sessionID)
281
+ }
282
+ }
283
+
284
+ return {
285
+ "experimental.chat.system.transform": async (hookInput, output) => {
286
+ if (!recallEnabled) return
287
+ const sessionID = hookInput && hookInput.sessionID
288
+ if (!sessionID || !output || !Array.isArray(output.system)) return
289
+ const block = await recall(sessionID)
290
+ if (block) output.system.push(block)
291
+ },
292
+
293
+ event: async ({ event }) => {
294
+ if (!event || event.type !== "session.idle") return
295
+ const sessionID = event.properties && event.properties.sessionID
296
+ if (sessionID) await add(sessionID)
297
+ },
298
+ }
299
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@9to9/opencode-memos",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Persistent memory for opencode: recalls from and adds to MemOS Cloud (lifecycle plugin).",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "exports": {
8
+ ".": "./dist/index.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "index.ts",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "scripts": {
17
+ "build": "npx -y esbuild index.ts --bundle --platform=node --format=esm --target=node20 --outfile=dist/index.js",
18
+ "prepublishOnly": "npm run build",
19
+ "check": "node --input-type=module -e \"import('./index.ts').then(m=>{if(typeof m.default!=='function'){console.error('missing default export');process.exit(1)};console.log('plugin ok')})\""
20
+ },
21
+ "keywords": [
22
+ "opencode",
23
+ "opencode-plugin",
24
+ "plugin",
25
+ "memos",
26
+ "memory",
27
+ "automation",
28
+ "ai"
29
+ ],
30
+ "license": "MIT",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/amajust/opencode-memos.git"
34
+ },
35
+ "homepage": "https://github.com/amajust/opencode-memos#readme",
36
+ "bugs": {
37
+ "url": "https://github.com/amajust/opencode-memos/issues"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "engines": {
43
+ "node": ">=20"
44
+ }
45
+ }