opencode-memstack 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +1 -1
  2. package/hook.mjs +1 -1
  3. package/index.js +110 -51
  4. package/package.json +1 -1
package/LICENSE CHANGED
@@ -14,7 +14,7 @@ is prohibited.
14
14
  Limited install license. MemStack grants you a non-exclusive, non-transferable, revocable license to
15
15
  download and install unmodified copies of (a) the MemStack plugins from the official public repository at
16
16
  https://github.com/MemStack-AI/Memstack-plugins and (b) the MemStack command-line tool and software development kit
17
- from the official npm packages @memstackai/cli and @memstackai/sdk, on your own devices and servers, and to
17
+ from the official npm packages @memstackai/memstack, @memstackai/cli and @memstackai/sdk, on your own devices and servers, and to
18
18
  run them solely to access the MemStack service at https://memstack.nidonic.online. This license does not
19
19
  permit you to modify, redistribute, sublicense, resell, or publish those copies, or to use them with any
20
20
  other service, and it grants no rights to any other part of the Software. It ends automatically if you
package/hook.mjs CHANGED
@@ -15,7 +15,7 @@ import { basename, dirname, join, resolve } from "node:path";
15
15
  import { fileURLToPath, pathToFileURL } from "node:url";
16
16
 
17
17
  export const DEFAULT_BASE = "https://memstack.nidonic.online";
18
- export const NOT_LOGGED_IN = "MemStack is off: you are not logged in. Run `npx @memstackai/cli login` in a terminal, then start a new session.";
18
+ export const NOT_LOGGED_IN = "MemStack is off: you are not logged in. Run `mem login` in a terminal (install it with `npm install -g @memstackai/memstack`), then start a new session.";
19
19
  const ABOUT_CHARS = 2_000; // fits the smallest host injection limit (Codex: 2,500 tokens) with the per-prompt notes
20
20
  const NOTE_CHARS = 300, NOTES_PER_PROMPT = 5, MIN_SCORE = 0.5; // below MIN_SCORE a note is mostly a shared keyword
21
21
  const FIND_TIMEOUT = 2_500; // per prompt; fails open with no context
package/index.js CHANGED
@@ -1,51 +1,110 @@
1
- // MemStack for OpenCode. Copyright © 2026 MemStack. All rights reserved.
2
- // Injects About and relevant notes into each message and saves the conversation as it goes, turn by turn.
3
- // Tools (mem_find / mem_save) come from MemStack's MCP server (`mem setup opencode`).
4
- // Needs `mem login` (or MEMSTACK_API_KEY); without it the plugin logs how to log in and does nothing.
5
- // The work is done by hook.mjs, the same core `mem hook` runs for every agent (copied from packages/cli/bin).
6
- import { capturing, login, NOT_LOGGED_IN, promptContext, realmFor, send, spool, startContext } from "./hook.mjs";
7
-
8
- /** A message's own text: no synthetic parts (our injections), no ignored parts, no tool output. */
9
- export const textOf = (parts) => parts.filter((p) => p.type === "text" && !p.synthetic && !p.ignored).map((p) => p.text).join("\n").trim();
10
-
11
- /** @type {import("@opencode-ai/plugin").Plugin} */
12
- export const MemStackPlugin = async ({ client, directory }) => {
13
- const auth = login();
14
- if (!auth) {
15
- await client?.app?.log?.({ body: { service: "mem", level: "warn", message: NOT_LOGGED_IN } }).catch(() => {});
16
- return {};
17
- }
18
- const where = realmFor(directory), { realm } = where;
19
- const started = new Set(); // sessions that already got About
20
-
21
- return {
22
- "chat.message": async (input, output) => {
23
- const prompt = textOf(output.parts);
24
- if (!prompt) return;
25
- const blocks = [];
26
- try {
27
- if (!started.has(input.sessionID)) {
28
- started.add(input.sessionID);
29
- blocks.push(await startContext(auth, realm));
30
- }
31
- const notes = await promptContext(auth, realm, "opencode", input.sessionID, prompt);
32
- if (notes) blocks.push(notes);
33
- } catch { /* memory is a bonus: never fail the user's message */ }
34
- if (blocks.length) {
35
- output.parts.push({ id: `prt_recall_${Date.now()}`, sessionID: input.sessionID, messageID: output.message.id, type: "text", text: blocks.join("\n\n"), synthetic: true });
36
- }
37
- },
38
-
39
- event: async ({ event }) => {
40
- const id = event.properties?.sessionID ?? event.properties?.info?.id;
41
- if (!id || !capturing(where) || !["session.idle", "session.compacted", "session.deleted"].includes(event.type)) return;
42
- try {
43
- if (event.type === "session.idle") {
44
- const { data } = await client.session.messages({ path: { id } });
45
- spool("opencode", id, (data ?? []).map(({ info, parts }) => ({ id: info.id, role: info.role === "user" ? "user" : "assistant", text: textOf(parts) })));
46
- }
47
- await send(auth, realm, "opencode", id, { force: event.type !== "session.idle", repoId: where.repoId }); // compaction or deletion: send the rest now
48
- } catch { /* kept in the spool; sent on the next idle */ }
49
- },
50
- };
51
- };
1
+ // MemStack for OpenCode. Copyright © 2026 MemStack. All rights reserved.
2
+ // Brings in About and the notes relevant to each message, and saves the conversation as it goes, turn by turn.
3
+ // Tools (mem_find / mem_save) come from MemStack's MCP server (`mem setup opencode`).
4
+ // Needs `mem login` (or MEMSTACK_API_KEY); without it the plugin says how to log in and does nothing.
5
+ // The work is done by hook.mjs, the same core `mem hook` runs for every agent (copied from packages/cli/bin).
6
+ // OpenCode 2 runs `setup` (its plugin format: a default export with an id); OpenCode 1 runs `server`.
7
+ import { capturing, login, NOT_LOGGED_IN, promptContext, realmFor, send, spool, startContext } from "./hook.mjs";
8
+
9
+ /** A message's own text: no synthetic parts (our injections), no ignored parts, no tool output. */
10
+ export const textOf = (parts) => parts.filter((p) => p.type === "text" && !p.synthetic && !p.ignored).map((p) => p.text).join("\n").trim();
11
+
12
+ /** An OpenCode 2 session message as a turn to save: a user's text, or an assistant's text parts (no reasoning, no tools). */
13
+ const turnOf = (m) => m.type === "user" ? { id: m.id, role: "user", text: (m.text ?? "").trim() }
14
+ : m.type === "assistant" ? { id: m.id, role: "assistant", text: (m.content ?? []).filter((c) => c.type === "text").map((c) => c.text).join("\n").trim() }
15
+ : null;
16
+
17
+ /** OpenCode 2. Every model request gets About (once fetched per session) in its system part, and each prompt's notes on
18
+ * that prompt's own user message, the same way in every request: the earlier part of a conversation stays identical, so
19
+ * provider prompt caching keeps working, and notes stay with the message they came for, as in OpenCode 1. Nothing is
20
+ * added to the stored conversation. Going idle saves the new turns; compaction and deletion send the rest. */
21
+ async function setup(ctx) {
22
+ const auth = login();
23
+ if (!auth) { console.warn(NOT_LOGGED_IN); return; }
24
+ const where = realmFor(ctx.location.directory), { realm } = where;
25
+ const about = new Map(), notes = new Map(); // sessionID → About text; sessionID → Map(messageID → notes)
26
+
27
+ await ctx.session.hook("prompt", async ({ sessionID, messageID, prompt }) => {
28
+ const text = prompt?.text?.trim();
29
+ if (!text) return;
30
+ try {
31
+ if (!about.has(sessionID)) about.set(sessionID, await startContext(auth, realm));
32
+ const found = await promptContext(auth, realm, "opencode", sessionID, text);
33
+ if (found) notes.set(sessionID, (notes.get(sessionID) ?? new Map()).set(messageID, found));
34
+ } catch { /* memory is a bonus: never fail the user's message */ }
35
+ });
36
+ await ctx.session.hook("context", (request) => {
37
+ const top = about.get(request.sessionID);
38
+ if (top) request.system.push({ type: "text", text: top });
39
+ const mine = notes.get(request.sessionID);
40
+ if (!mine?.size) return;
41
+ const users = request.messages.filter((m) => m.role === "user"), last = [...mine.keys()].at(-1);
42
+ for (const [messageID, text] of mine) {
43
+ const target = users.find((m) => m.id === messageID) ?? (messageID === last ? users.at(-1) : undefined); // no ids: the latest prompt's notes on the latest message
44
+ if (!target) continue;
45
+ try { target.content.push({ type: "text", text }); } catch { request.system.push({ type: "text", text }); }
46
+ }
47
+ });
48
+
49
+ const save = async (sessionID, force) => {
50
+ if (!capturing(where)) return;
51
+ try {
52
+ if (!force) spool("opencode", sessionID, (await ctx.session.context({ sessionID })).map(turnOf).filter(Boolean));
53
+ await send(auth, realm, "opencode", sessionID, { force, repoId: where.repoId });
54
+ } catch { /* kept in the spool; sent on the next idle */ }
55
+ };
56
+ // not awaited: the session goes idle (or compacts) at once, and the save runs beside it
57
+ await ctx.session.hook("experimental.idle", ({ sessionID }) => { void save(sessionID, false); });
58
+ await ctx.session.hook("compaction", ({ sessionID }) => { void save(sessionID, true); });
59
+ const stop = new AbortController();
60
+ void (async () => {
61
+ try { for await (const event of ctx.event.subscribe({ signal: stop.signal })) if (event.type === "session.deleted") void save(event.data.sessionID, true); }
62
+ catch { /* unsubscribed on unload */ }
63
+ })();
64
+ return () => stop.abort();
65
+ }
66
+
67
+ /** OpenCode 1: injects into each message as a synthetic part and saves on session events. */
68
+ async function server({ client, directory }) {
69
+ const auth = login();
70
+ if (!auth) {
71
+ await client?.app?.log?.({ body: { service: "mem", level: "warn", message: NOT_LOGGED_IN } }).catch(() => {});
72
+ return {};
73
+ }
74
+ const where = realmFor(directory), { realm } = where;
75
+ const started = new Set(); // sessions that already got About
76
+
77
+ return {
78
+ "chat.message": async (input, output) => {
79
+ const prompt = textOf(output.parts);
80
+ if (!prompt) return;
81
+ const blocks = [];
82
+ try {
83
+ if (!started.has(input.sessionID)) {
84
+ started.add(input.sessionID);
85
+ blocks.push(await startContext(auth, realm));
86
+ }
87
+ const notes = await promptContext(auth, realm, "opencode", input.sessionID, prompt);
88
+ if (notes) blocks.push(notes);
89
+ } catch { /* memory is a bonus: never fail the user's message */ }
90
+ if (blocks.length) {
91
+ output.parts.push({ id: `prt_recall_${Date.now()}`, sessionID: input.sessionID, messageID: output.message.id, type: "text", text: blocks.join("\n\n"), synthetic: true });
92
+ }
93
+ },
94
+
95
+ event: async ({ event }) => {
96
+ const id = event.properties?.sessionID ?? event.properties?.info?.id;
97
+ if (!id || !capturing(where) || !["session.idle", "session.compacted", "session.deleted"].includes(event.type)) return;
98
+ try {
99
+ if (event.type === "session.idle") {
100
+ const { data } = await client.session.messages({ path: { id } });
101
+ spool("opencode", id, (data ?? []).map(({ info, parts }) => ({ id: info.id, role: info.role === "user" ? "user" : "assistant", text: textOf(parts) })));
102
+ }
103
+ await send(auth, realm, "opencode", id, { force: event.type !== "session.idle", repoId: where.repoId }); // compaction or deletion: send the rest now
104
+ } catch { /* kept in the spool; sent on the next idle */ }
105
+ },
106
+ };
107
+ }
108
+
109
+ /** One default export for both: OpenCode 2 needs an id and setup, OpenCode 1 (1.18.29 and newer) runs server. */
110
+ export default { id: "memstack.mem", setup, server };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-memstack",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Long-term memory for OpenCode, backed by MemStack.",
5
5
  "type": "module",
6
6
  "main": "index.js",