shmem-opencode 0.3.31 → 0.3.33

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 (2) hide show
  1. package/index.ts +344 -20
  2. package/package.json +2 -2
package/index.ts CHANGED
@@ -1,6 +1,9 @@
1
- import type { Plugin as V1Plugin } from "@opencode-ai/plugin"
1
+ import type { Hooks as V1Hooks, Plugin as V1Plugin } from "@opencode-ai/plugin"
2
2
  import type { Plugin as V2 } from "@opencode/plugin"
3
- import { execFileSync } from "child_process"
3
+ import { spawn, spawnSync } from "child_process"
4
+ import { appendFileSync, mkdirSync, renameSync, statSync } from "fs"
5
+ import { homedir } from "os"
6
+ import { join } from "path"
4
7
 
5
8
  // One module serves both plugin APIs. OpenCode 2.x loads `id` and `setup`;
6
9
  // OpenCode 1.x calls `server`. The plugin packages are imported for types
@@ -37,45 +40,295 @@ function rootArg(command: string[]): string | undefined {
37
40
  return undefined
38
41
  }
39
42
 
40
- function shmemHook(subcommand: string, payload: Record<string, string>): void {
43
+ // AGENT labels what this plugin captures. Claude Code and Codex hooks pass
44
+ // --caller-agent; it is set in the environment here instead, which every
45
+ // shmem binary reads, and which OpenCode's own environment would otherwise
46
+ // leave to detection: "cli" from a shell, "claude-code" inside Claude Code.
47
+ const AGENT = "opencode"
48
+
49
+ // SHMEM_HOOK_DEDUP=off: shmem hook's dedup matches its argv against Claude
50
+ // Code's settings files to skip a duplicate Claude registration. The plugin
51
+ // is not one, and a bare `shmem hook <event>` registered at an older Claude
52
+ // level would match it and skip the capture silently. OpenCode has one
53
+ // registration, the plugin, so there is nothing to dedup.
54
+ function hookEnv(): NodeJS.ProcessEnv {
55
+ const env: NodeJS.ProcessEnv = { ...process.env, SHMEM_CALLER_AGENT: AGENT, SHMEM_HOOK_DEDUP: "off" }
56
+ if (shmemRoot && !process.env.SHMEM_ROOT) env.SHMEM_ROOT = shmemRoot
57
+ return env
58
+ }
59
+
60
+ // recordFailure appends a capture failure to hook-errors.log in the shmem
61
+ // root, which `shmem admin status` reports. It is the one channel both
62
+ // plugin APIs have: OpenCode 2.x shows plugins' output nowhere and has no
63
+ // log call, and a hook that throws blocks the prompt. Written with fs, not
64
+ // shmem, so it works when the binary is what's missing.
65
+ const ERRORS_FILE = "hook-errors.log"
66
+ const ERRORS_MAX_BYTES = 256 * 1024
67
+
68
+ function recordFailure(message: string): void {
41
69
  try {
42
- execFileSync("shmem", ["hook", subcommand], {
70
+ // The same precedence as hookEnv, so the log lands in the root the
71
+ // hooks write to and status reads: the environment's, then install's.
72
+ const root = process.env.SHMEM_ROOT || shmemRoot || join(homedir(), ".shmem")
73
+ const path = join(root, ERRORS_FILE)
74
+ // Private, as SECURITY.md has shmem's data: directories 0700, files 0600.
75
+ mkdirSync(root, { recursive: true, mode: 0o700 })
76
+ try {
77
+ if (statSync(path).size > ERRORS_MAX_BYTES) renameSync(path, `${path}.1`)
78
+ } catch {
79
+ // no file yet
80
+ }
81
+ appendFileSync(path, `${new Date().toISOString()}\t${AGENT}\t${message.replace(/\s+/g, " ")}\n`, { mode: 0o600 })
82
+ } catch {
83
+ // nowhere left to report to
84
+ }
85
+ }
86
+
87
+ // report surfaces a capture failure. Failures never interrupt OpenCode, but
88
+ // they must not vanish either: a capture that stops working otherwise looks
89
+ // exactly like one that works. The 1.x server adds OpenCode's log and a toast.
90
+ let report = (message: string): void => {
91
+ recordFailure(message)
92
+ console.error(`${ID}: ${message}`)
93
+ }
94
+
95
+ // SKIPPED starts the line shmem hook prints when it drops a capture it was
96
+ // given (cli/hook.go).
97
+ const SKIPPED = "shmem: warning [hook]:"
98
+
99
+ const HOOK_TIMEOUT_MS = 10_000
100
+
101
+ // checkHook reports a hook run that failed: a spawn error, a non-zero
102
+ // exit, or shmem hook's own skip line. shmem hook exits 0 even when it
103
+ // skips a capture, and says why on stderr; other stderr on success is
104
+ // ordinary notices (a new release, a first-run message), not failures.
105
+ function checkHook(what: string, error: Error | undefined, status: number | null, signal: string | null, stderr: string) {
106
+ stderr = stderr.trim()
107
+ if (error) report(`${what} failed: ${error.message}`)
108
+ else if (status !== 0) report(`${what} exited ${status ?? signal}${stderr ? `: ${stderr}` : ""}`)
109
+ else {
110
+ for (const line of stderr.split("\n")) {
111
+ if (line.startsWith(SKIPPED)) report(`${what}: ${line}`)
112
+ }
113
+ }
114
+ }
115
+
116
+ // shmemHook runs `shmem hook <subcommand>`, waits for it, and returns what
117
+ // it printed. It blocks OpenCode's one JS thread, so it is kept for the
118
+ // prompt, whose hook must finish (and hand back its context) before the
119
+ // turn goes on.
120
+ function shmemHook(subcommand: string, payload: Record<string, unknown>): string {
121
+ const what = `shmem hook ${subcommand}`
122
+ try {
123
+ const run = spawnSync("shmem", ["hook", subcommand], {
43
124
  input: JSON.stringify(payload),
44
- timeout: 10_000,
45
- stdio: ["pipe", "ignore", "ignore"],
46
- env: shmemRoot && !process.env.SHMEM_ROOT ? { ...process.env, SHMEM_ROOT: shmemRoot } : undefined,
125
+ timeout: HOOK_TIMEOUT_MS,
126
+ stdio: ["pipe", "pipe", "pipe"],
127
+ encoding: "utf8",
128
+ env: hookEnv(),
47
129
  })
130
+ checkHook(what, run.error, run.status, run.signal, run.stderr ?? "")
131
+ // stdout even on failure: the hook hands out its context before it
132
+ // saves, so a failed save can still have printed context that shmem
133
+ // won't hand out again. hookContext ignores anything that isn't it.
134
+ return run.stdout ?? ""
135
+ } catch (err) {
136
+ report(`${what} failed: ${err instanceof Error ? err.message : String(err)}`)
137
+ return ""
138
+ }
139
+ }
140
+
141
+ // hookContext is the additionalContext in `shmem hook user-message`'s
142
+ // output: the signed-out reminder and share updates, which Claude Code adds
143
+ // to the turn. shmem hands each one out once, so whatever comes back here
144
+ // must reach the model or it is lost.
145
+ function hookContext(stdout: string): string {
146
+ if (!stdout.trim()) return ""
147
+ try {
148
+ const ctx = JSON.parse(stdout)?.hookSpecificOutput?.additionalContext
149
+ return typeof ctx === "string" ? ctx : ""
48
150
  } catch {
49
- // hook failures must not surface to the user
151
+ return ""
50
152
  }
51
153
  }
52
154
 
53
- function userMessage(text: string, cwd: string) {
54
- if (text.length >= 10) shmemHook("user-message", { prompt: text, cwd })
155
+ // turnContext holds each session's hook context for its current turn. Every
156
+ // model request of the turn gets it, not just the first, since a turn that
157
+ // starts with a tool call answers the user in a later request. The next
158
+ // prompt replaces it once a request has carried it; until then, as when
159
+ // prompts are queued behind a running turn, the next prompt's context is
160
+ // added to it.
161
+ const turnContext = new Map<string, { text: string; delivered: boolean }>()
162
+
163
+ function contextFor(sessionID: string | undefined): string {
164
+ const ctx = sessionID ? turnContext.get(sessionID) : undefined
165
+ if (!ctx) return ""
166
+ ctx.delivered = true
167
+ return ctx.text
168
+ }
169
+
170
+ function setTurnContext(sessionID: string, text: string) {
171
+ const prev = turnContext.get(sessionID)
172
+ const waiting = prev && !prev.delivered ? prev.text : ""
173
+ const joined = [waiting, text].filter(Boolean).join("\n\n")
174
+ if (joined) turnContext.set(sessionID, { text: joined, delivered: false })
175
+ else turnContext.delete(sessionID)
176
+ }
177
+
178
+ // shmemHookAsync runs `shmem hook <subcommand>` without waiting, for
179
+ // replies and tool calls: an agent turn can make dozens of tool calls, and
180
+ // waiting on each would stall OpenCode's streaming and UI every time.
181
+ function shmemHookAsync(subcommand: string, payload: Record<string, unknown>): void {
182
+ const what = `shmem hook ${subcommand}`
183
+ try {
184
+ // Detached, so the capture finishes when OpenCode exits right after the
185
+ // turn (as `opencode run` does): OpenCode 2.x kills its plugins'
186
+ // children on shutdown.
187
+ const child = spawn("shmem", ["hook", subcommand], {
188
+ stdio: ["pipe", "ignore", "pipe"],
189
+ env: hookEnv(),
190
+ detached: true,
191
+ })
192
+ child.unref()
193
+ let stderr = ""
194
+ let failed: Error | undefined
195
+ const timer = setTimeout(() => {
196
+ failed = new Error(`timed out after ${HOOK_TIMEOUT_MS / 1000}s`)
197
+ child.kill()
198
+ }, HOOK_TIMEOUT_MS)
199
+ child.stderr?.setEncoding("utf8").on("data", (chunk: string) => (stderr += chunk))
200
+ child.on("error", (err) => (failed = err))
201
+ child.on("close", (status, signal) => {
202
+ clearTimeout(timer)
203
+ checkHook(what, failed, failed ? null : status, signal, stderr)
204
+ })
205
+ child.stdin?.on("error", () => {})
206
+ child.stdin?.end(JSON.stringify(payload))
207
+ } catch (err) {
208
+ report(`${what} failed: ${err instanceof Error ? err.message : String(err)}`)
209
+ }
210
+ }
211
+
212
+ // What counts as too short to keep is `shmem hook`'s call, as it is for
213
+ // every other agent: the plugin passes everything through.
214
+ function userMessage(text: string, cwd: string, sessionID: string) {
215
+ setTurnContext(sessionID, text.trim() ? hookContext(shmemHook("user-message", { prompt: text, cwd })) : "")
55
216
  }
56
217
 
57
218
  function response(text: string, cwd: string) {
58
- if (text.length >= 20) shmemHook("response", { last_assistant_message: text, cwd })
219
+ if (text.trim()) shmemHookAsync("response", { last_assistant_message: text, cwd })
220
+ }
221
+
222
+ // TOOLS maps OpenCode's tool names (1.x and 2.x) onto the Claude Code names
223
+ // `shmem hook tool-use` formats, so a tool fact reads the same from any
224
+ // agent, and its input keys onto Claude Code's.
225
+ const TOOLS: Record<string, string> = {
226
+ read: "Read",
227
+ edit: "Edit",
228
+ write: "Write",
229
+ bash: "Bash",
230
+ shell: "Bash",
231
+ grep: "Grep",
232
+ glob: "Glob",
233
+ webfetch: "WebFetch",
234
+ websearch: "WebSearch",
235
+ task: "Agent",
236
+ subagent: "Agent",
237
+ }
238
+
239
+ function toolInput(args: Record<string, unknown>): Record<string, unknown> {
240
+ const out: Record<string, unknown> = { ...args }
241
+ const path = args.filePath ?? args.path
242
+ if (path !== undefined) out.file_path = path
243
+ return out
244
+ }
245
+
246
+ // toolResponse is what `shmem hook` renders as the fact's body. OpenCode's
247
+ // edit and write tools answer with a status line ("Edit applied
248
+ // successfully."); the change itself is in their input. They get the object
249
+ // shape Claude Code's Edit and Write results have, which the hook renders
250
+ // as the old and new text, or the content written.
251
+ function toolResponse(tool: string, args: Record<string, unknown>, output: string): unknown {
252
+ const filePath = args.filePath ?? args.path
253
+ if (tool === "edit" && typeof args.oldString === "string" && typeof args.newString === "string")
254
+ return { filePath, oldString: args.oldString, newString: args.newString }
255
+ if (tool === "write" && typeof args.content === "string") return { filePath, content: args.content }
256
+ return output
257
+ }
258
+
259
+ // toolUse captures one finished tool call. shmem's own MCP tools are left
260
+ // out, as `shmem hook` leaves out shmem's own CLI calls.
261
+ function toolUse(
262
+ tool: string,
263
+ args: Record<string, unknown> | undefined,
264
+ output: string,
265
+ callID: string,
266
+ sessionID: string,
267
+ cwd: string,
268
+ ) {
269
+ if (/shmem/i.test(tool)) return
270
+ shmemHookAsync("tool-use", {
271
+ tool_name: TOOLS[tool] ?? tool,
272
+ tool_input: toolInput(args ?? {}),
273
+ tool_response: toolResponse(tool, args ?? {}, output),
274
+ tool_use_id: callID,
275
+ session_id: sessionID,
276
+ cwd,
277
+ })
59
278
  }
60
279
 
61
280
  // OpenCode 2.x.
62
281
  async function setup(ctx: V2.Context): Promise<V2.Cleanup> {
63
282
  const cwd = ctx.location.directory
64
283
  await ctx.mcp.transform((mcp) => rootFrom(mcp.get("shmem")))
65
- await ctx.session.hook("prompt", (input) => userMessage(input.prompt.text, cwd))
284
+ await ctx.session.hook("prompt", (input) => userMessage(input.prompt.text, cwd, input.sessionID))
285
+ await ctx.session.hook("context", (input) => {
286
+ const extra = contextFor(input.sessionID)
287
+ if (extra) input.system.push({ type: "text", text: extra })
288
+ })
66
289
 
67
290
  // A reply's text arrives whole in session.text.ended, the 2.x counterpart
68
- // of 1.x's experimental.text.complete.
291
+ // of the finished text parts 1.x captures from its event stream. A tool call arrives in three
292
+ // events with one id: its name, then its input, then its result.
69
293
  // The stream can error or end while OpenCode keeps running; subscribe again
70
294
  // after a pause, so replies don't stop being captured until a restart.
71
295
  // Only cleanup (the abort) ends it. Errors never reach OpenCode.
72
296
  const controller = new AbortController()
73
297
  const { signal } = controller
298
+ const calls = new Map<string, { name?: string; input?: Record<string, unknown> }>()
299
+ const types = [
300
+ "session.text.ended",
301
+ "session.tool.input.started",
302
+ "session.tool.called",
303
+ "session.tool.success",
304
+ "session.tool.failed",
305
+ ] as const
74
306
  void (async () => {
75
307
  while (!signal.aborted) {
76
308
  try {
77
- for await (const event of ctx.event.subscribe({ types: ["session.text.ended"], signal })) {
78
- if (event.type === "session.text.ended") response(event.data.text, cwd)
309
+ for await (const event of ctx.event.subscribe({ types: [...types], signal })) {
310
+ switch (event.type) {
311
+ case "session.text.ended":
312
+ response(event.data.text, cwd)
313
+ break
314
+ case "session.tool.input.started":
315
+ calls.set(event.data.id, { name: event.data.name })
316
+ break
317
+ case "session.tool.called":
318
+ calls.set(event.data.id, { ...calls.get(event.data.id), input: { ...event.data.input } })
319
+ break
320
+ case "session.tool.success": {
321
+ const call = calls.get(event.data.id)
322
+ calls.delete(event.data.id)
323
+ if (!call?.name) break
324
+ toolUse(call.name, call.input, contentText(event.data.content), event.data.id, event.data.sessionID, cwd)
325
+ break
326
+ }
327
+ case "session.tool.failed":
328
+ // Claude Code's PostToolUse fires on success only.
329
+ calls.delete(event.data.id)
330
+ break
331
+ }
79
332
  }
80
333
  } catch {
81
334
  // fall through to resubscribe
@@ -86,20 +339,91 @@ async function setup(ctx: V2.Context): Promise<V2.Cleanup> {
86
339
  return () => controller.abort()
87
340
  }
88
341
 
342
+ // contentText renders MCP-style content blocks: text joined, anything else
343
+ // as a placeholder naming it.
344
+ function contentText(content: ReadonlyArray<{ type: string; text?: string; name?: string; uri?: string }>): string {
345
+ return content.map((c) => (c.type === "text" ? (c.text ?? "") : `[${c.type}: ${c.name ?? c.uri ?? ""}]`)).join("\n")
346
+ }
347
+
348
+ // toolOutputV1 is a 1.x tool's result. Built-in tools give a string
349
+ // `output`; an MCP tool can hand back its content blocks instead.
350
+ function toolOutputV1(output: unknown): string {
351
+ const o = output as { output?: unknown; content?: unknown }
352
+ if (typeof o?.output === "string") return o.output
353
+ if (Array.isArray(o?.content)) return contentText(o.content)
354
+ return output === undefined ? "" : JSON.stringify(output)
355
+ }
356
+
89
357
  // OpenCode 1.x.
90
- const server: V1Plugin = async ({ directory }) => ({
358
+ const server: V1Plugin = async ({ directory, client }) => {
359
+ let toasted = false
360
+ report = (message) => {
361
+ recordFailure(message)
362
+ console.error(`${ID}: ${message}`)
363
+ void client.app.log({ body: { service: ID, level: "warn", message } }).catch(() => {})
364
+ // One toast per OpenCode run: enough to be noticed, not one per turn.
365
+ if (!toasted) {
366
+ toasted = true
367
+ void client.tui
368
+ .showToast({ body: { title: "shmem", message: `Memory capture failed: ${message}`, variant: "warning" } })
369
+ .catch(() => {})
370
+ }
371
+ }
372
+ return hooksV1(directory)
373
+ }
374
+
375
+ // A 1.x reply is captured from the stable event stream: a text part whose
376
+ // time.end is set has finished, and message.updated says which messages
377
+ // are the assistant's. Parts are sent once each, since part.updated can
378
+ // repeat for a finished part.
379
+ type V1Event = Parameters<NonNullable<V1Hooks["event"]>>[0]["event"]
380
+
381
+ // replyEvents only counts replies being generated: a message first seen already
382
+ // completed is a copy (a forked session re-emits every earlier message under
383
+ // new ids), and was captured when it was written. A message's state is
384
+ // dropped when it completes, so a long-running OpenCode keeps none per reply.
385
+ function replyEvents(directory: string) {
386
+ const live = new Map<string, Set<string>>() // message id -> text parts sent
387
+ return async ({ event }: { event: V1Event }) => {
388
+ if (event.type === "message.updated") {
389
+ const info = event.properties.info
390
+ if (info.role !== "assistant") return
391
+ if (info.time.completed !== undefined) live.delete(info.id)
392
+ else if (!live.has(info.id)) live.set(info.id, new Set())
393
+ return
394
+ }
395
+ if (event.type !== "message.part.updated") return
396
+ const part = event.properties.part
397
+ if (part.type !== "text" || part.synthetic || part.time?.end === undefined) return
398
+ const sent = live.get(part.messageID)
399
+ if (!sent || sent.has(part.id)) return
400
+ sent.add(part.id)
401
+ response(part.text, directory)
402
+ }
403
+ }
404
+
405
+ const hooksV1 = (directory: string): Awaited<ReturnType<V1Plugin>> => ({
406
+ event: replyEvents(directory),
407
+
91
408
  config: async (config) => rootFrom(config.mcp?.shmem),
92
409
 
93
- "chat.message": async (_input, output) => {
410
+ "chat.message": async (input, output) => {
94
411
  const text = output.parts
95
412
  .filter((p): p is Extract<typeof p, { type: "text" }> => p.type === "text")
96
413
  .map((p) => p.text)
97
414
  .join("")
98
- userMessage(text, directory)
415
+ userMessage(text, directory, input.sessionID)
416
+ },
417
+
418
+ // The 1.x counterpart of 2.x's context hook: the only place a plugin can
419
+ // add to the model's instructions for a request.
420
+ "experimental.chat.system.transform": async (input, output) => {
421
+ const extra = contextFor(input.sessionID)
422
+ if (extra) output.system.push(extra)
99
423
  },
100
424
 
101
- "experimental.text.complete": async (_input, output) => {
102
- response(output.text, directory)
425
+ "tool.execute.after": async (input, output) => {
426
+ toolUse(input.tool, input.args, toolOutputV1(output), input.callID, input.sessionID, directory)
103
427
  },
104
428
  })
105
429
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shmem-opencode",
3
- "version": "0.3.31",
3
+ "version": "0.3.33",
4
4
  "description": "shmem memory hooks for OpenCode",
5
5
  "main": "index.ts",
6
6
  "scripts": {
@@ -13,7 +13,7 @@
13
13
  "@opencode-ai/plugin": "^1.17.13",
14
14
  "@opencode/plugin": "^2.2.7",
15
15
  "@types/node": "^26.1.0",
16
- "typescript": "^5.0.0"
16
+ "typescript": "^7.0.2"
17
17
  },
18
18
  "keywords": [
19
19
  "shmem",