@codemem/opencode-plugin 0.49.0 → 0.50.0-beta.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.
@@ -117,7 +117,7 @@ export const probeCliCandidate = async ({ path, nodePath, expectedVersion, boots
117
117
  try {
118
118
  const candidate = readCandidate(location.manifestPath, { nodePath, expectedVersion, executable: location.executable });
119
119
  const result = await executeFile(candidate.command, [...candidate.args, "--version"], {
120
- timeout: remaining, maxBuffer: MAX_OUTPUT_BYTES, killSignal: "SIGKILL",
120
+ timeout: remaining, maxBuffer: MAX_OUTPUT_BYTES, killSignal: "SIGKILL", windowsHide: true,
121
121
  });
122
122
  if (result.stdout.trim() === candidate.version && isCachedCliCurrent(candidate)) return candidate;
123
123
  } catch { /* An unusable candidate must not select an unverified command. */ }
@@ -128,7 +128,7 @@ export const probeCliCandidate = async ({ path, nodePath, expectedVersion, boots
128
128
  const runProbe = async ({ command, args, cwd, env, timeout, execute, expectedVersion }) => {
129
129
  try {
130
130
  const result = await execute(command, args, {
131
- cwd, env, timeout, maxBuffer: MAX_OUTPUT_BYTES, killSignal: "SIGKILL",
131
+ cwd, env, timeout, maxBuffer: MAX_OUTPUT_BYTES, killSignal: "SIGKILL", windowsHide: true,
132
132
  });
133
133
  const candidate = JSON.parse(result.stdout);
134
134
  if (!candidate || !isAbsolute(candidate.command) || candidate.args?.length !== 1
@@ -118,7 +118,9 @@ export const runChildCommand = (cmd, options = {}, defaults = {}) => {
118
118
  resolve({ exitCode: null, stdout: "", stderr: "aborted", aborted: true });
119
119
  return;
120
120
  }
121
- const proc = nodeSpawn(command, args, { cwd, env, stdio: ["pipe", "pipe", "pipe"] });
121
+ const proc = nodeSpawn(command, args, {
122
+ cwd, env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true,
123
+ });
122
124
  const output = collectOutput(proc);
123
125
  const stdinFailure = writeStdin(proc, stdinText);
124
126
  if (stdinFailure) {
@@ -90,13 +90,22 @@ export const parseBackendUpdatePolicy = (value) => {
90
90
  return "notify";
91
91
  };
92
92
 
93
+ // Same result as /@[^/]+$/.test(value) without the regex, which backtracks
94
+ // quadratically on long "@" runs: some "@" in the last path segment must be
95
+ // followed by at least one character.
96
+ const endsWithRefSuffix = (value) => {
97
+ const refStart = value.indexOf("@", value.lastIndexOf("/") + 1);
98
+ return refStart !== -1 && refStart < value.length - 1;
99
+ };
100
+
93
101
  const isPinnedGitSource = (runnerFrom) => {
94
102
  const source = String(runnerFrom || "").trim();
95
103
  if (!source) return false;
96
104
  if (!(source.startsWith("git+") || source.includes(".git"))) {
97
105
  return false;
98
106
  }
99
- const withoutQuery = source.replace(/[?#].*$/, "");
107
+ const queryStart = source.search(/[?#]/);
108
+ const withoutQuery = queryStart === -1 ? source : source.slice(0, queryStart);
100
109
  if (withoutQuery.includes(".git@")) {
101
110
  return true;
102
111
  }
@@ -110,9 +119,9 @@ const isPinnedGitSource = (runnerFrom) => {
110
119
  if (path.includes(".git@")) {
111
120
  return true;
112
121
  }
113
- return /@[^/]+$/.test(path);
122
+ return endsWithRefSuffix(path);
114
123
  } catch {
115
- return /@[^/]+$/.test(withoutQuery);
124
+ return endsWithRefSuffix(withoutQuery);
116
125
  }
117
126
  };
118
127
 
@@ -9,6 +9,7 @@ import {
9
9
  MEMORY_TOOL_NAMESPACE,
10
10
  MEMORY_TOOL_NAMESPACE_DESCRIPTION,
11
11
  } from "./memory-tools.js";
12
+ import { addCallerToPooledMcpTools, createCallSequence } from "./pooled-mcp-caller.js";
12
13
  import { createCodememRuntime } from "./runtime.js";
13
14
  import { registerV2NotificationBridge } from "./v2-notification-bridge.js";
14
15
  import { readV2SessionOwnership } from "./v2-session-location.js";
@@ -478,8 +479,11 @@ const registerV2Tools = async (context, runtime, isActive) => {
478
479
  const mcpObserver = memoryTools
479
480
  ? await observeV2McpPrecedence(context, memoryTools, gate, isActive)
480
481
  : null;
482
+ const nextSequence = createCallSequence();
481
483
  const tools = await context.tool.transform((editor) => {
482
484
  if (!isActive()) return;
485
+ // A shared codemem MCP server needs this instance's directory on each call.
486
+ addCallerToPooledMcpTools(editor, { directory: context.location.directory, nextSequence });
483
487
  for (const [name, definition] of Object.entries(runtime.tools)) {
484
488
  editor.add(createV2Tool(name, definition, { isActive }));
485
489
  }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Caller context for a codemem MCP server that several project directories
3
+ * share (OpenCode `pool: true`). A shared server has one fixed working
4
+ * directory, so it started with `--caller-context required` and declares a
5
+ * `_codemem_caller` argument on every tool. This module fills that argument
6
+ * in from the plugin instance that runs the call and hides it from the model.
7
+ * Tools that do not declare the argument are left alone, so a private
8
+ * per-project server is unaffected. So are tools of any other MCP server: the
9
+ * argument carries the project path and session ID, which only the server
10
+ * configured under the name `codemem` should receive.
11
+ */
12
+
13
+ import { randomUUID } from "node:crypto";
14
+
15
+ export const CALLER_ARGUMENT = "_codemem_caller";
16
+ const CODEMEM_SERVER = "codemem";
17
+
18
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
19
+
20
+ // The host reports an MCP tool's server name as its namespace. Tool IDs are
21
+ // not enough: a server named `codemem_other` produces IDs with the same prefix.
22
+ const declaresCaller = (tool) =>
23
+ tool?.options?.namespace === CODEMEM_SERVER
24
+ && isObject(tool.input?.properties)
25
+ && CALLER_ARGUMENT in tool.input.properties;
26
+
27
+ const cleanProject = (value) => (typeof value === "string" && value.trim() ? value.trim() : null);
28
+
29
+ /**
30
+ * Inner calls of one Code Mode block share the block's call ID, so a sequence
31
+ * number keeps each call distinct. The per-instance nonce keeps a provider
32
+ * that reuses call IDs from repeating an identity after the plugin reloads.
33
+ * A redelivery of one dispatched call keeps the value it was dispatched with.
34
+ */
35
+ export const createCallSequence = (nonce = randomUUID().slice(0, 8)) => {
36
+ let next = 0;
37
+ return () => {
38
+ next += 1;
39
+ return `${nonce}:${next}`;
40
+ };
41
+ };
42
+
43
+ /**
44
+ * @param {{ list(): readonly object[], update(id: string, update: (tool: any) => void): void }} editor
45
+ * @param {{ directory: string, nextSequence: () => string, readEnvProject?: () => unknown }} options
46
+ * @returns {string[]} IDs of the tools that now receive the caller argument.
47
+ */
48
+ export const addCallerToPooledMcpTools = (editor, options) => {
49
+ const { directory, nextSequence, readEnvProject = () => process.env.CODEMEM_PROJECT } = options;
50
+ // Hosts whose tool editor cannot list or update tools have no pooling either.
51
+ if (typeof editor.list !== "function" || typeof editor.update !== "function") return [];
52
+ const pooled = editor.list().filter(declaresCaller);
53
+ for (const tool of pooled) {
54
+ editor.update(tool.id, (target) => {
55
+ const { [CALLER_ARGUMENT]: _hidden, ...properties } = target.input.properties;
56
+ target.input = { ...target.input, properties };
57
+ const execute = target.execute;
58
+ // The plugin's value always replaces one that arrived with the call.
59
+ target.execute = (input, context) => execute({
60
+ ...input,
61
+ [CALLER_ARGUMENT]: {
62
+ directory,
63
+ env_project: cleanProject(readEnvProject()),
64
+ session_id: context.sessionID,
65
+ request_id: `${context.id}:${nextSequence()}`,
66
+ },
67
+ }, context);
68
+ });
69
+ }
70
+ return pooled.map((tool) => tool.id);
71
+ };
@@ -92,6 +92,7 @@ const createDeliveryState = (options) => ({
92
92
  lastStatusCheckAt: 0,
93
93
  latestViewerFailure: null,
94
94
  lastToastAtBySession: new Map(),
95
+ identityMismatch: false,
95
96
  options,
96
97
  retainedPayloads: new WeakSet(),
97
98
  spoolDirectory: resolveSpoolDirectory(options.spoolHome),
@@ -344,6 +345,29 @@ const armViewerBackoff = (state, error, timing) => {
344
345
  return viewerFailure;
345
346
  };
346
347
 
348
+ const isIdentityMismatchFailure = (error) =>
349
+ error?.rawEventFailure?.cause === "viewer_identity_mismatch";
350
+
351
+ const pauseForIdentityMismatch = async (state) => {
352
+ if (state.identityMismatch) return;
353
+ state.identityMismatch = true;
354
+ if (!state.options.isActive()) return;
355
+ const message = "codemem capture delivery paused: viewer identity mismatch; align CODEMEM_* settings, then restart the viewer and OpenCode to resume saved events";
356
+ const diagnostic = `raw_events.delivery.paused code=viewer_identity_mismatch category=identity ${message}`;
357
+ try {
358
+ await persistSafeSpoolDiagnostic(state, diagnostic);
359
+ } catch {
360
+ // The host warning still explains recovery when the default log is unavailable.
361
+ }
362
+ await bestEffortHostLog(state, {
363
+ service: "codemem",
364
+ level: "error",
365
+ message,
366
+ extra: { category: "identity", code: "viewer_identity_mismatch" },
367
+ });
368
+ await bestEffortNotify(state, { message, variant: "error" });
369
+ };
370
+
347
371
  const warnRejectedEntry = async (state, { rejection, outcome, sessionID }) => {
348
372
  const messages = {
349
373
  retained: "codemem retained a rejected raw event; inspect it with codemem diagnostics capture list-rejected",
@@ -386,6 +410,24 @@ const retainRejectedEntry = async (state, { eventId, rejection, sessionID, paylo
386
410
  }
387
411
  };
388
412
 
413
+ const handleDrainFailure = async (state, entry, error, startedAt) => {
414
+ if (isIdentityMismatchFailure(error)) {
415
+ await pauseForIdentityMismatch(state);
416
+ return false;
417
+ }
418
+ if (error?.rawEventTerminalRejection) {
419
+ await retainRejectedEntry(state, { eventId: entry.eventId, rejection: error.rawEventTerminalRejection });
420
+ return true;
421
+ }
422
+ await state.options.logLine("raw_events.spool.drain_deferred category=fallback");
423
+ const status = error?.rawEventFailure?.status;
424
+ if (!Number.isInteger(status) || status >= 500 || status === 409) {
425
+ armViewerBackoff(state, error, { stage: "post", startedAt });
426
+ return false;
427
+ }
428
+ return true;
429
+ };
430
+
389
431
  const drainLoadedEntries = async (state, loaded) => {
390
432
  if (loaded.corruptCount > 0) {
391
433
  await state.options.logLine(`raw_events.spool.corrupt_retained count=${loaded.corruptCount}`);
@@ -394,21 +436,14 @@ const drainLoadedEntries = async (state, loaded) => {
394
436
  state.spoolCorruptionNoted = false;
395
437
  }
396
438
  for (const entry of loaded.entries) {
439
+ if (state.identityMismatch) break;
397
440
  const viewerStartedAt = Date.now();
398
441
  try {
399
442
  await postToViewer(state, entry.envelope);
400
443
  await removeFromSpool(state, { eventId: entry.eventId });
401
444
  } catch (error) {
402
- if (error?.rawEventTerminalRejection) {
403
- await retainRejectedEntry(state, { eventId: entry.eventId, rejection: error.rawEventTerminalRejection });
404
- continue;
405
- }
406
- await state.options.logLine("raw_events.spool.drain_deferred category=fallback");
407
- const status = error?.rawEventFailure?.status;
408
- if (!Number.isInteger(status) || status >= 500 || status === 409) {
409
- armViewerBackoff(state, error, { stage: "post", startedAt: viewerStartedAt });
410
- break;
411
- }
445
+ const canContinue = await handleDrainFailure(state, entry, error, viewerStartedAt);
446
+ if (!canContinue) break;
412
447
  }
413
448
  }
414
449
  };
@@ -420,6 +455,7 @@ const runSpoolDrain = async (state) => {
420
455
 
421
456
  const drainSpool = (state) => {
422
457
  if (!state.options.enabled) return Promise.resolve();
458
+ if (state.identityMismatch) return Promise.resolve();
423
459
  if (Date.now() < state.streamUnavailableUntil) return Promise.resolve();
424
460
  const existingDrain = rawEventSpoolDrainsInFlight.get(state.spoolDirectory);
425
461
  if (existingDrain) return existingDrain;
@@ -533,28 +569,40 @@ const postToViewer = async (state, body) => {
533
569
  cause: "http_status",
534
570
  status: response.status,
535
571
  };
572
+ if (response.status === 409 && responseBody?.error?.code === "viewer_identity_mismatch") {
573
+ error.rawEventFailure.cause = "viewer_identity_mismatch";
574
+ }
536
575
  throw error;
537
576
  };
538
577
 
578
+ const persistRejectedDelivery = async (state, input, rejection) => {
579
+ const durable = await persistForRetry(state, input);
580
+ if (durable) {
581
+ const canonical = input.payload && typeof input.payload === "object"
582
+ ? state.envelopes.get(input.payload) : null;
583
+ // A size rejection proves only the posted copy was too large. Retry changed saved bytes first.
584
+ if (rejection.status === 413
585
+ && canonical && canonical.serialized !== input.serialized) return durable;
586
+ await retainRejectedEntry(state, {
587
+ eventId: input.body.event_id,
588
+ rejection,
589
+ sessionID: input.sessionID,
590
+ payload: input.payload,
591
+ });
592
+ }
593
+ return durable;
594
+ };
595
+
539
596
  const handleViewerFailure = async (state, input, error, timing) => {
597
+ if (isIdentityMismatchFailure(error)) {
598
+ await pauseForIdentityMismatch(state);
599
+ return persistForRetry(state, input);
600
+ }
540
601
  if (error?.rawEventTerminalRejection) {
541
- const durable = await persistForRetry(state, input);
542
- if (durable) {
543
- const canonical = input.payload && typeof input.payload === "object"
544
- ? state.envelopes.get(input.payload) : null;
545
- // A size rejection proves only the posted copy was too large. Retry changed saved bytes first.
546
- if (error.rawEventTerminalRejection.status === 413
547
- && canonical && canonical.serialized !== input.serialized) return durable;
548
- await retainRejectedEntry(state, {
549
- eventId: input.body.event_id,
550
- rejection: error.rawEventTerminalRejection,
551
- sessionID: input.sessionID,
552
- payload: input.payload,
553
- });
554
- }
555
- return durable;
602
+ return persistRejectedDelivery(state, input, error.rawEventTerminalRejection);
556
603
  }
557
604
  if (!state.options.isActive()) return persistForRetry(state, input);
605
+ if (state.identityMismatch) return persistForRetry(state, input);
558
606
  const category = error?.rawEventFailureCategory || "connection";
559
607
  const viewerFailure = armViewerBackoff(state, error, timing);
560
608
  await state.options.logLine(
@@ -584,11 +632,13 @@ const deliver = async (state, { sessionID, type, payload }) => {
584
632
  const envelope = cachedEnvelope(state, sessionID, type, payload, now);
585
633
  const input = { ...envelope, payload, sessionID };
586
634
  if (!state.options.isActive()) return persistForRetry(state, input);
635
+ if (state.identityMismatch) return persistForRetry(state, input);
587
636
  if (now < state.streamUnavailableUntil) return deliverDuringBackoff(state, input);
588
637
  const viewerStartedAt = Date.now();
589
638
  let viewerStage = "status";
590
639
  try {
591
640
  await checkViewerAvailability(state, now);
641
+ if (state.identityMismatch) return persistForRetry(state, input);
592
642
  viewerStage = "post";
593
643
  await postToViewer(state, envelope.body);
594
644
  state.streamUnavailableUntil = 0;
@@ -1,5 +1,5 @@
1
1
  import { execSync, spawn as nodeSpawn } from "node:child_process";
2
- import { createHash } from "node:crypto";
2
+ import { createHash, randomUUID } from "node:crypto";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
4
  import { appendFile, mkdir } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
@@ -38,7 +38,7 @@ import {
38
38
 
39
39
  const TRUTHY_VALUES = ["1", "true", "yes"];
40
40
  const DISABLED_VALUES = ["0", "false", "off"];
41
- const PINNED_BACKEND_VERSION = "0.49.0";
41
+ const PINNED_BACKEND_VERSION = "0.50.0-beta.1";
42
42
  const COMPAT_CHECK_DELAY_MS = 1500;
43
43
  const COMPAT_CHECK_CACHE_TTL_MS = 5 * 60 * 1000;
44
44
  const MAX_UPDATE_STATUS_BYTES = 16 * 1024;
@@ -2218,6 +2218,7 @@ const detectRunner = ({ cwd, envRunner }) => {
2218
2218
  // catch below falls back to npx. Without this, stderr leaks to the
2219
2219
  // terminal on every OpenCode startup for npx-only installs.
2220
2220
  stdio: ["ignore", "pipe", "ignore"],
2221
+ windowsHide: true,
2221
2222
  }).trim();
2222
2223
  // Use a newer global CLI only when it remains on the plugin's release
2223
2224
  // channel. This prevents both channel crossing and fallback to an older pin
@@ -2555,12 +2556,7 @@ export const createCodememRuntime = async ({ location, host, hostGeneration = nu
2555
2556
  let rawEventDeliveryCount = 0;
2556
2557
  let flushDeliveryTail = Promise.resolve();
2557
2558
  let promptPackTransportUnavailableUntil = 0;
2558
- const nextEventId = () => {
2559
- if (typeof crypto !== "undefined" && crypto.randomUUID) {
2560
- return crypto.randomUUID();
2561
- }
2562
- return `${Date.now()}-${Math.random()}`;
2563
- };
2559
+ const nextEventId = () => randomUUID();
2564
2560
 
2565
2561
  const buildViewerCliArgs = createViewerCliArgs({ viewerHost, viewerPort, viewerDbPath, viewerConfigPath });
2566
2562
 
@@ -2904,7 +2900,7 @@ export const createCodememRuntime = async ({ location, host, hostGeneration = nu
2904
2900
  cwd,
2905
2901
  env: process.env,
2906
2902
  detached: true,
2907
- stdio: "ignore",
2903
+ stdio: "ignore", windowsHide: true,
2908
2904
  });
2909
2905
  child.once("spawn", () => {
2910
2906
  viewerStarted = true;
@@ -3885,7 +3881,7 @@ export const createCodememRuntime = async ({ location, host, hostGeneration = nu
3885
3881
  encoding: "utf-8",
3886
3882
  // Suppress "fatal: not a git repository" when the working directory is
3887
3883
  // not a git repo. The catch below leaves version as "unknown".
3888
- stdio: ["ignore", "pipe", "ignore"],
3884
+ stdio: ["ignore", "pipe", "ignore"], windowsHide: true,
3889
3885
  }).trim();
3890
3886
  } catch {
3891
3887
  // Ignore - version will remain 'unknown'
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@codemem/opencode-plugin",
3
- "version": "0.49.0",
4
- "description": "CodeMem plugin for OpenCode",
3
+ "version": "0.50.0-beta.1",
4
+ "description": "Codemem plugin for OpenCode",
5
5
  "type": "module",
6
6
  "main": "./index.js",
7
7
  "types": "./index.d.ts",
@@ -42,7 +42,7 @@
42
42
  "@babel/parser": "8.1.0",
43
43
  "@opencode/cli": "2.0.24",
44
44
  "@types/node": "^24.12.4",
45
- "codemem": "^0.49.0",
45
+ "codemem": "^0.50.0-beta.1",
46
46
  "vitest": "^4.1.11"
47
47
  },
48
48
  "repository": {