@codemem/opencode-plugin 0.47.5 → 0.48.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/.opencode/lib/child-command.js +130 -0
- package/.opencode/lib/host-contract.js +2 -0
- package/.opencode/lib/memory-tool-contracts.json +1712 -0
- package/.opencode/lib/memory-tool-schema.js +105 -0
- package/.opencode/lib/memory-tools.js +404 -0
- package/.opencode/lib/opencode-v2-adapter.js +272 -113
- package/.opencode/lib/runtime.js +139 -144
- package/.opencode/package.json +1 -1
- package/.opencode/plugins/codemem.js +60 -3
- package/package.json +4 -3
package/.opencode/lib/runtime.js
CHANGED
|
@@ -5,6 +5,7 @@ import { appendFile, mkdir } from "node:fs/promises";
|
|
|
5
5
|
import { homedir } from "node:os";
|
|
6
6
|
import { basename, dirname, join, posix, resolve, win32 } from "node:path";
|
|
7
7
|
import { createCachedCliRunner } from "./cached-cli-runner.js";
|
|
8
|
+
import { runChildCommand } from "./child-command.js";
|
|
8
9
|
import {
|
|
9
10
|
isVersionAtLeast,
|
|
10
11
|
parseBackendUpdatePolicy,
|
|
@@ -13,6 +14,11 @@ import {
|
|
|
13
14
|
resolveUpgradeGuidance,
|
|
14
15
|
} from "./compat.js";
|
|
15
16
|
import { V2_ADAPTER_DIAGNOSTICS } from "./host-contract.js";
|
|
17
|
+
import {
|
|
18
|
+
createMemoryToolExecutor,
|
|
19
|
+
createNativeMemoryTools,
|
|
20
|
+
nativeMemoryToolsEnabled,
|
|
21
|
+
} from "./memory-tools.js";
|
|
16
22
|
import { createPromptTransportDiagnostics } from "./prompt-transport-diagnostics.js";
|
|
17
23
|
import {
|
|
18
24
|
classifyRawEventTransportCause,
|
|
@@ -32,7 +38,7 @@ import {
|
|
|
32
38
|
|
|
33
39
|
const TRUTHY_VALUES = ["1", "true", "yes"];
|
|
34
40
|
const DISABLED_VALUES = ["0", "false", "off"];
|
|
35
|
-
const PINNED_BACKEND_VERSION = "0.
|
|
41
|
+
const PINNED_BACKEND_VERSION = "0.48.0";
|
|
36
42
|
const COMPAT_CHECK_DELAY_MS = 1500;
|
|
37
43
|
const COMPAT_CHECK_CACHE_TTL_MS = 5 * 60 * 1000;
|
|
38
44
|
const MAX_UPDATE_STATUS_BYTES = 16 * 1024;
|
|
@@ -45,8 +51,10 @@ const COMPACTION_INJECTION_SKIP_TTL_MS = 30 * 1000;
|
|
|
45
51
|
const MAX_WORKING_SET_PATH_CHARS = 400;
|
|
46
52
|
const VIEWER_HEALTH_CHECK_INTERVAL_MS = 60_000;
|
|
47
53
|
const VIEWER_HEALTH_TIMEOUT_MS = 5_000;
|
|
48
|
-
const
|
|
49
|
-
|
|
54
|
+
const VIEWER_HEALTH_RECOVERY_THRESHOLD = 2;
|
|
55
|
+
// Every plugin instance probes the shared viewer, so the cooldown keeps one
|
|
56
|
+
// instance from retrying recovery on every interval while the viewer boots.
|
|
57
|
+
const VIEWER_HEALTH_RECOVERY_COOLDOWN_MS = 5 * 60_000;
|
|
50
58
|
const RAW_EVENTS_STATUS_TIMEOUT_MS = 5_000;
|
|
51
59
|
const DEFAULT_INJECT_TOKEN_BUDGET = 800;
|
|
52
60
|
const DEFAULT_RETAINED_TOKEN_BUDGET = Infinity;
|
|
@@ -102,11 +110,28 @@ const envHasValue = (value, truthyValues) =>
|
|
|
102
110
|
const envNotDisabled = (value) =>
|
|
103
111
|
!DISABLED_VALUES.includes(normalizeEnvValue(value));
|
|
104
112
|
|
|
113
|
+
/** `codemem serve start` prints this when a viewer already holds the port. */
|
|
114
|
+
const viewerAlreadyRunning = (result) =>
|
|
115
|
+
/viewer already running/i.test(`${result?.stdout ?? ""}\n${result?.stderr ?? ""}`);
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Health recovery runs `serve start`, which exits without touching a viewer that
|
|
119
|
+
* already holds the port, so concurrent recoveries from several instances cannot
|
|
120
|
+
* stop each other's freshly started process the way `serve restart` would. The
|
|
121
|
+
* instance owns the viewer only if its start launched one: when another
|
|
122
|
+
* instance's viewer holds the port, `serve start` exits 0 and says so.
|
|
123
|
+
*/
|
|
124
|
+
const recoverViewerStart = async (started, onLaunched) => {
|
|
125
|
+
const result = await started;
|
|
126
|
+
if (result?.exitCode === 0 && !viewerAlreadyRunning(result)) onLaunched();
|
|
127
|
+
return result;
|
|
128
|
+
};
|
|
129
|
+
|
|
105
130
|
const createViewerHealthMonitor = ({
|
|
106
131
|
viewerHealthUrl,
|
|
107
132
|
legacyStatusUrl,
|
|
108
133
|
isActive,
|
|
109
|
-
|
|
134
|
+
recoverViewer,
|
|
110
135
|
logLine,
|
|
111
136
|
fetchFn = fetch,
|
|
112
137
|
now = Date.now,
|
|
@@ -192,27 +217,27 @@ const createViewerHealthMonitor = ({
|
|
|
192
217
|
`viewer.health check failed (${result.detail}, consecutive=${consecutiveFailures})`
|
|
193
218
|
);
|
|
194
219
|
if (
|
|
195
|
-
consecutiveFailures <
|
|
196
|
-
now() - lastRestartAttempt <
|
|
220
|
+
consecutiveFailures < VIEWER_HEALTH_RECOVERY_THRESHOLD ||
|
|
221
|
+
now() - lastRestartAttempt < VIEWER_HEALTH_RECOVERY_COOLDOWN_MS
|
|
197
222
|
) {
|
|
198
223
|
return;
|
|
199
224
|
}
|
|
200
225
|
|
|
201
226
|
// Re-check after the awaited probe: a stop requested while the probe was
|
|
202
|
-
// in flight must not be undone by a
|
|
227
|
+
// in flight must not be undone by a recovery start.
|
|
203
228
|
if (!isActive()) return;
|
|
204
229
|
|
|
205
230
|
lastRestartAttempt = now();
|
|
206
|
-
await logLine(`viewer.health
|
|
231
|
+
await logLine(`viewer.health starting viewer after ${consecutiveFailures} consecutive failures`);
|
|
207
232
|
try {
|
|
208
|
-
const
|
|
209
|
-
const
|
|
233
|
+
const startResult = await recoverViewer();
|
|
234
|
+
const started = startResult?.exitCode === 0;
|
|
210
235
|
await logLine(
|
|
211
|
-
`viewer.health
|
|
236
|
+
`viewer.health start ${started ? "succeeded" : "failed"} (exit=${startResult?.exitCode ?? "unknown"})`
|
|
212
237
|
);
|
|
213
|
-
if (
|
|
238
|
+
if (started) consecutiveFailures = 0;
|
|
214
239
|
} catch (error) {
|
|
215
|
-
await logLine(`viewer.health
|
|
240
|
+
await logLine(`viewer.health start error: ${String(error).slice(0, 200)}`);
|
|
216
241
|
}
|
|
217
242
|
};
|
|
218
243
|
|
|
@@ -2272,6 +2297,79 @@ const createViewerCliArgs = ({ viewerHost, viewerPort, viewerDbPath, viewerConfi
|
|
|
2272
2297
|
return args;
|
|
2273
2298
|
};
|
|
2274
2299
|
|
|
2300
|
+
/** The CLI-backed `mem-*` status tools every plugin instance registers. */
|
|
2301
|
+
const createCliStatusTools = ({ runCli, viewerUrlHost, viewerPort, logPath }) => ({
|
|
2302
|
+
"mem-status": {
|
|
2303
|
+
description: "Show codemem stats and recent entries",
|
|
2304
|
+
args: {},
|
|
2305
|
+
async execute() {
|
|
2306
|
+
const stats = await runCli(["stats"]);
|
|
2307
|
+
const recent = await runCli(["recent", "--limit", "5"]);
|
|
2308
|
+
const lines = [
|
|
2309
|
+
`viewer: http://${viewerUrlHost}:${viewerPort}`,
|
|
2310
|
+
`log: ${logPath || "disabled"}`,
|
|
2311
|
+
];
|
|
2312
|
+
if (stats.exitCode === 0 && stats.stdout.trim()) {
|
|
2313
|
+
lines.push("", "stats:", stats.stdout.trim());
|
|
2314
|
+
}
|
|
2315
|
+
if (recent.exitCode === 0 && recent.stdout.trim()) {
|
|
2316
|
+
lines.push("", "recent:", recent.stdout.trim());
|
|
2317
|
+
}
|
|
2318
|
+
return lines.join("\n");
|
|
2319
|
+
},
|
|
2320
|
+
},
|
|
2321
|
+
|
|
2322
|
+
"mem-recent": {
|
|
2323
|
+
description: "Show recent codemem entries",
|
|
2324
|
+
args: {
|
|
2325
|
+
limit: { type: "number", optional: true },
|
|
2326
|
+
},
|
|
2327
|
+
async execute({ limit }) {
|
|
2328
|
+
// Number.isFinite accepts floats and negatives; coerce to a positive
|
|
2329
|
+
// integer (default 5) before forwarding to the CLI.
|
|
2330
|
+
const safeLimit = String(parsePositiveInt(limit, 5));
|
|
2331
|
+
const recent = await runCli(["recent", "--limit", safeLimit]);
|
|
2332
|
+
if (recent.exitCode === 0) {
|
|
2333
|
+
return recent.stdout.trim() || "No recent memories.";
|
|
2334
|
+
}
|
|
2335
|
+
return `Failed to fetch recent: ${recent.stderr || recent.exitCode}`;
|
|
2336
|
+
},
|
|
2337
|
+
},
|
|
2338
|
+
|
|
2339
|
+
"mem-stats": {
|
|
2340
|
+
description: "Show codemem stats",
|
|
2341
|
+
args: {},
|
|
2342
|
+
async execute() {
|
|
2343
|
+
const stats = await runCli(["stats"]);
|
|
2344
|
+
if (stats.exitCode === 0) {
|
|
2345
|
+
return stats.stdout.trim() || "No stats yet.";
|
|
2346
|
+
}
|
|
2347
|
+
return `Failed to fetch stats: ${stats.stderr || stats.exitCode}`;
|
|
2348
|
+
},
|
|
2349
|
+
},
|
|
2350
|
+
});
|
|
2351
|
+
|
|
2352
|
+
/** Native memory tools, or null unless CODEMEM_OPENCODE_NATIVE_TOOLS enables them. */
|
|
2353
|
+
const createRuntimeMemoryTools = ({
|
|
2354
|
+
viewerEnabled, viewerBaseUrl, dbPath, identityTarget, runCli, location, log, notify,
|
|
2355
|
+
}) => {
|
|
2356
|
+
if (!nativeMemoryToolsEnabled()) return null;
|
|
2357
|
+
return createNativeMemoryTools({
|
|
2358
|
+
executor: createMemoryToolExecutor({
|
|
2359
|
+
viewerEnabled,
|
|
2360
|
+
viewerBaseUrl,
|
|
2361
|
+
dbPath,
|
|
2362
|
+
identityTarget,
|
|
2363
|
+
// The same target proof prompt recall uses.
|
|
2364
|
+
isProfileMatch: (profile) => viewerProfileFailureKind(profile, dbPath, identityTarget) === null,
|
|
2365
|
+
runCli,
|
|
2366
|
+
defaultDirectory: resolve(location.directory || location.cwd),
|
|
2367
|
+
}),
|
|
2368
|
+
log,
|
|
2369
|
+
notify,
|
|
2370
|
+
});
|
|
2371
|
+
};
|
|
2372
|
+
|
|
2275
2373
|
export const createCodememRuntime = async ({ location, host, hostGeneration = null }) => {
|
|
2276
2374
|
const { project, directory, worktree } = location;
|
|
2277
2375
|
const hostLog = typeof host?.log === "function" ? host.log : async () => {};
|
|
@@ -2332,9 +2430,9 @@ export const createCodememRuntime = async ({ location, host, hostGeneration = nu
|
|
|
2332
2430
|
const viewerAutoStart = envNotDisabled(
|
|
2333
2431
|
process.env.CODEMEM_VIEWER_AUTO || "1"
|
|
2334
2432
|
);
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
);
|
|
2433
|
+
// Opt-in: the viewer is shared by every OpenCode project on this machine, so
|
|
2434
|
+
// one session ending must not stop it for the others.
|
|
2435
|
+
const viewerAutoStop = envHasValue(process.env.CODEMEM_VIEWER_AUTO_STOP, TRUTHY_VALUES);
|
|
2338
2436
|
const viewerHost = process.env.CODEMEM_VIEWER_HOST || "127.0.0.1";
|
|
2339
2437
|
const viewerPort = process.env.CODEMEM_VIEWER_PORT || "38888";
|
|
2340
2438
|
const viewerDbPath = process.env.CODEMEM_DB || "";
|
|
@@ -2771,6 +2869,8 @@ export const createCodememRuntime = async ({ location, host, hostGeneration = nu
|
|
|
2771
2869
|
if (viewerStarted) logLine("viewer already started, skipping auto-start").catch(() => {});
|
|
2772
2870
|
return;
|
|
2773
2871
|
}
|
|
2872
|
+
// Monitor the shared viewer whether or not this instance ends up spawning it.
|
|
2873
|
+
watchViewerHealth();
|
|
2774
2874
|
viewerStartInFlight = true;
|
|
2775
2875
|
let existingViewer = false;
|
|
2776
2876
|
try {
|
|
@@ -2802,7 +2902,6 @@ export const createCodememRuntime = async ({ location, host, hostGeneration = nu
|
|
|
2802
2902
|
child.once("spawn", () => {
|
|
2803
2903
|
viewerStarted = true;
|
|
2804
2904
|
viewerStartInFlight = false;
|
|
2805
|
-
startHealthCheck();
|
|
2806
2905
|
});
|
|
2807
2906
|
child.on("error", (err) => {
|
|
2808
2907
|
viewerStartInFlight = false;
|
|
@@ -2815,78 +2914,9 @@ export const createCodememRuntime = async ({ location, host, hostGeneration = nu
|
|
|
2815
2914
|
}
|
|
2816
2915
|
};
|
|
2817
2916
|
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
stdinText = null,
|
|
2822
|
-
timeoutMs = commandTimeout,
|
|
2823
|
-
} = options;
|
|
2824
|
-
const [command, ...args] = cmd;
|
|
2825
|
-
return new Promise((resolve) => {
|
|
2826
|
-
const proc = nodeSpawn(command, args, {
|
|
2827
|
-
cwd,
|
|
2828
|
-
env,
|
|
2829
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
2830
|
-
});
|
|
2831
|
-
let stdout = "";
|
|
2832
|
-
let stderr = "";
|
|
2833
|
-
// Guard stdio access: a hard spawn failure (ENOENT) can hand back null
|
|
2834
|
-
// streams, and a synchronous null-deref here would reject the promise
|
|
2835
|
-
// that callers await for a resolved { exitCode, stdout, stderr }.
|
|
2836
|
-
if (proc.stdout) proc.stdout.on("data", (chunk) => { stdout += chunk; });
|
|
2837
|
-
if (proc.stderr) proc.stderr.on("data", (chunk) => { stderr += chunk; });
|
|
2838
|
-
// Absorb async stream errors (e.g. EPIPE when the child exits mid-write,
|
|
2839
|
-
// or a spawn failure surfacing on a pipe). Without these handlers an
|
|
2840
|
-
// unhandled stream "error" event would crash the host process. The
|
|
2841
|
-
// child-level proc.once("error") below still resolves the promise.
|
|
2842
|
-
for (const stream of [proc.stdin, proc.stdout, proc.stderr]) {
|
|
2843
|
-
if (stream && typeof stream.on === "function") stream.on("error", () => {});
|
|
2844
|
-
}
|
|
2845
|
-
if (typeof stdinText === "string") {
|
|
2846
|
-
try {
|
|
2847
|
-
proc.stdin.write(stdinText);
|
|
2848
|
-
} catch (stdinErr) {
|
|
2849
|
-
try { proc.kill(); } catch { /* ignore */ }
|
|
2850
|
-
resolve({ exitCode: 1, stdout: "", stderr: `stdin write failed: ${String(stdinErr)}` });
|
|
2851
|
-
return;
|
|
2852
|
-
}
|
|
2853
|
-
}
|
|
2854
|
-
try {
|
|
2855
|
-
proc.stdin.end();
|
|
2856
|
-
} catch (stdinErr) {
|
|
2857
|
-
try { proc.kill(); } catch { /* ignore */ }
|
|
2858
|
-
resolve({ exitCode: 1, stdout: "", stderr: `stdin close failed: ${String(stdinErr)}` });
|
|
2859
|
-
return;
|
|
2860
|
-
}
|
|
2861
|
-
let timer = null;
|
|
2862
|
-
let killTimer = null;
|
|
2863
|
-
let timedOut = false;
|
|
2864
|
-
let settled = false;
|
|
2865
|
-
const finish = (result) => {
|
|
2866
|
-
if (settled) return;
|
|
2867
|
-
settled = true;
|
|
2868
|
-
if (timer) clearTimeout(timer);
|
|
2869
|
-
if (killTimer) clearTimeout(killTimer);
|
|
2870
|
-
resolve(result);
|
|
2871
|
-
};
|
|
2872
|
-
if (Number.isFinite(timeoutMs) && timeoutMs > 0) {
|
|
2873
|
-
timer = setTimeout(() => {
|
|
2874
|
-
timedOut = true;
|
|
2875
|
-
try { proc.kill("SIGTERM"); } catch { /* ignore */ }
|
|
2876
|
-
killTimer = setTimeout(() => {
|
|
2877
|
-
try { proc.kill("SIGKILL"); } catch { /* ignore */ }
|
|
2878
|
-
}, 5_000);
|
|
2879
|
-
if (killTimer.unref) killTimer.unref();
|
|
2880
|
-
}, timeoutMs);
|
|
2881
|
-
}
|
|
2882
|
-
proc.once("exit", (exitCode) => {
|
|
2883
|
-
finish({ exitCode: timedOut ? null : exitCode, stdout, stderr: timedOut ? "timeout" : stderr });
|
|
2884
|
-
});
|
|
2885
|
-
proc.once("error", (err) => {
|
|
2886
|
-
finish({ exitCode: 1, stdout: "", stderr: String(err) });
|
|
2887
|
-
});
|
|
2888
|
-
});
|
|
2889
|
-
};
|
|
2917
|
+
// Options may set cwd, env, signal, stdinText, and timeoutMs; see runChildCommand.
|
|
2918
|
+
const runCommand = async (cmd, options = {}) =>
|
|
2919
|
+
runChildCommand(cmd, options, { cwd, timeoutMs: commandTimeout });
|
|
2890
2920
|
|
|
2891
2921
|
const runCli = (args, options = {}) => {
|
|
2892
2922
|
const command = cliRunner.command(args);
|
|
@@ -2897,6 +2927,17 @@ export const createCodememRuntime = async ({ location, host, hostGeneration = nu
|
|
|
2897
2927
|
});
|
|
2898
2928
|
};
|
|
2899
2929
|
|
|
2930
|
+
const memoryTools = createRuntimeMemoryTools({
|
|
2931
|
+
viewerEnabled,
|
|
2932
|
+
viewerBaseUrl: `http://${viewerUrlHost}:${viewerPort}`,
|
|
2933
|
+
dbPath: promptPackDbPath,
|
|
2934
|
+
identityTarget: promptPackIdentityTarget,
|
|
2935
|
+
runCli,
|
|
2936
|
+
location: { directory, cwd },
|
|
2937
|
+
log,
|
|
2938
|
+
notify: hostNotify,
|
|
2939
|
+
});
|
|
2940
|
+
|
|
2900
2941
|
const installCliUpdate = async (command) => {
|
|
2901
2942
|
const result = await runCommand(command, { env: resolveAutoUpdateEnvironment(), timeoutMs: 480_000 });
|
|
2902
2943
|
if (result?.exitCode === 0) cliRunner.invalidate();
|
|
@@ -3807,9 +3848,7 @@ export const createCodememRuntime = async ({ location, host, hostGeneration = nu
|
|
|
3807
3848
|
};
|
|
3808
3849
|
|
|
3809
3850
|
const stopViewer = async () => {
|
|
3810
|
-
if (!viewerEnabled || !viewerAutoStop || !viewerStarted)
|
|
3811
|
-
return;
|
|
3812
|
-
}
|
|
3851
|
+
if (!viewerEnabled || !viewerAutoStop || !viewerStarted) return;
|
|
3813
3852
|
viewerStarted = false;
|
|
3814
3853
|
stopHealthCheck();
|
|
3815
3854
|
await logLine("viewer stop requested");
|
|
@@ -3819,12 +3858,16 @@ export const createCodememRuntime = async ({ location, host, hostGeneration = nu
|
|
|
3819
3858
|
const viewerHealthMonitor = createViewerHealthMonitor({
|
|
3820
3859
|
viewerHealthUrl,
|
|
3821
3860
|
legacyStatusUrl: rawEventsStatusUrl,
|
|
3822
|
-
isActive: () =>
|
|
3823
|
-
|
|
3861
|
+
isActive: () => viewerEnabled && viewerAutoStart && viewerHealthMonitor.state().running,
|
|
3862
|
+
recoverViewer: () =>
|
|
3863
|
+
recoverViewerStart(runCli(buildViewerCliArgs("start")), () => { viewerStarted = true; }),
|
|
3824
3864
|
logLine,
|
|
3825
3865
|
});
|
|
3826
3866
|
const startHealthCheck = viewerHealthMonitor.start;
|
|
3827
3867
|
const stopHealthCheck = viewerHealthMonitor.stop;
|
|
3868
|
+
const watchViewerHealth = () => {
|
|
3869
|
+
if (runtimeActive) startHealthCheck();
|
|
3870
|
+
};
|
|
3828
3871
|
|
|
3829
3872
|
// Get version info (commit hash) for debugging
|
|
3830
3873
|
let version = "unknown";
|
|
@@ -4752,56 +4795,8 @@ export const createCodememRuntime = async ({ location, host, hostGeneration = nu
|
|
|
4752
4795
|
await flushEvents();
|
|
4753
4796
|
}
|
|
4754
4797
|
},
|
|
4755
|
-
|
|
4756
|
-
|
|
4757
|
-
description: "Show codemem stats and recent entries",
|
|
4758
|
-
args: {},
|
|
4759
|
-
async execute() {
|
|
4760
|
-
const stats = await runCli(["stats"]);
|
|
4761
|
-
const recent = await runCli(["recent", "--limit", "5"]);
|
|
4762
|
-
const lines = [
|
|
4763
|
-
`viewer: http://${viewerUrlHost}:${viewerPort}`,
|
|
4764
|
-
`log: ${logPath || "disabled"}`,
|
|
4765
|
-
];
|
|
4766
|
-
if (stats.exitCode === 0 && stats.stdout.trim()) {
|
|
4767
|
-
lines.push("", "stats:", stats.stdout.trim());
|
|
4768
|
-
}
|
|
4769
|
-
if (recent.exitCode === 0 && recent.stdout.trim()) {
|
|
4770
|
-
lines.push("", "recent:", recent.stdout.trim());
|
|
4771
|
-
}
|
|
4772
|
-
return lines.join("\n");
|
|
4773
|
-
},
|
|
4774
|
-
},
|
|
4775
|
-
|
|
4776
|
-
"mem-recent": {
|
|
4777
|
-
description: "Show recent codemem entries",
|
|
4778
|
-
args: {
|
|
4779
|
-
limit: { type: "number", optional: true },
|
|
4780
|
-
},
|
|
4781
|
-
async execute({ limit }) {
|
|
4782
|
-
// Number.isFinite accepts floats and negatives; coerce to a positive
|
|
4783
|
-
// integer (default 5) before forwarding to the CLI.
|
|
4784
|
-
const safeLimit = String(parsePositiveInt(limit, 5));
|
|
4785
|
-
const recent = await runCli(["recent", "--limit", safeLimit]);
|
|
4786
|
-
if (recent.exitCode === 0) {
|
|
4787
|
-
return recent.stdout.trim() || "No recent memories.";
|
|
4788
|
-
}
|
|
4789
|
-
return `Failed to fetch recent: ${recent.stderr || recent.exitCode}`;
|
|
4790
|
-
},
|
|
4791
|
-
},
|
|
4792
|
-
|
|
4793
|
-
"mem-stats": {
|
|
4794
|
-
description: "Show codemem stats",
|
|
4795
|
-
args: {},
|
|
4796
|
-
async execute() {
|
|
4797
|
-
const stats = await runCli(["stats"]);
|
|
4798
|
-
if (stats.exitCode === 0) {
|
|
4799
|
-
return stats.stdout.trim() || "No stats yet.";
|
|
4800
|
-
}
|
|
4801
|
-
return `Failed to fetch stats: ${stats.stderr || stats.exitCode}`;
|
|
4802
|
-
},
|
|
4803
|
-
},
|
|
4804
|
-
},
|
|
4798
|
+
memoryTools,
|
|
4799
|
+
tools: createCliStatusTools({ runCli, viewerUrlHost, viewerPort, logPath }),
|
|
4805
4800
|
};
|
|
4806
4801
|
};
|
|
4807
4802
|
|
package/.opencode/package.json
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
1
2
|
import { tool } from "@opencode-ai/plugin";
|
|
2
3
|
import { createDelegationContext } from "../lib/delegation-context.js";
|
|
3
4
|
|
|
4
5
|
import { createRuntimeHost, createRuntimeLocation } from "../lib/host-contract.js";
|
|
6
|
+
import { convertObjectShape } from "../lib/memory-tool-schema.js";
|
|
7
|
+
import { formatMemoryToolOutcome, isMemoryToolId, memoryToolId } from "../lib/memory-tools.js";
|
|
5
8
|
import {
|
|
6
9
|
__testUtils,
|
|
7
10
|
buildInjectionToastMessage,
|
|
@@ -74,6 +77,53 @@ const createV1Tool = (definition) => {
|
|
|
74
77
|
});
|
|
75
78
|
};
|
|
76
79
|
|
|
80
|
+
// OpenCode 1 tools return plain text and have no error flag, so a failed call
|
|
81
|
+
// returns the same error payload text the MCP server would send.
|
|
82
|
+
const createV1MemoryTool = (contract, execute) => tool({
|
|
83
|
+
description: contract.description,
|
|
84
|
+
args: convertObjectShape(tool.schema, contract.input, contract.name),
|
|
85
|
+
execute: async (args, context) => {
|
|
86
|
+
const outcome = await execute(contract.name, args, {
|
|
87
|
+
directory: context?.directory,
|
|
88
|
+
sessionID: context?.sessionID,
|
|
89
|
+
// OpenCode 1 supplies no call ID. One per execution lets the viewer and a
|
|
90
|
+
// CLI retry of this same call share a retrieval-ledger identity.
|
|
91
|
+
callID: randomUUID(),
|
|
92
|
+
signal: context?.abort,
|
|
93
|
+
});
|
|
94
|
+
const { text, note } = formatMemoryToolOutcome(outcome);
|
|
95
|
+
return note ? `${text}\n${note}` : text;
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
const createV1MemoryTools = (memoryTools) => {
|
|
100
|
+
if (!memoryTools) return {};
|
|
101
|
+
return Object.fromEntries(
|
|
102
|
+
memoryTools.contracts.map((contract) => [
|
|
103
|
+
memoryToolId(contract.name),
|
|
104
|
+
createV1MemoryTool(contract, memoryTools.execute),
|
|
105
|
+
]),
|
|
106
|
+
);
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const isV1CodememMcpConfigured = async (client) => {
|
|
110
|
+
const response = await client.config.get();
|
|
111
|
+
if (!response?.data) throw new Error("OpenCode config unavailable");
|
|
112
|
+
const server = response.data.mcp?.codemem;
|
|
113
|
+
return Boolean(server) && server.enabled !== false;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/** Native memory tools to register, or null when off or a codemem MCP server already serves them. */
|
|
117
|
+
const resolveV1MemoryTools = async (client, memoryTools) => {
|
|
118
|
+
if (!memoryTools) return null;
|
|
119
|
+
const register = await memoryTools.shouldRegister({
|
|
120
|
+
isCodememMcpConfigured: typeof client.config?.get === "function"
|
|
121
|
+
? () => isV1CodememMcpConfigured(client)
|
|
122
|
+
: null,
|
|
123
|
+
});
|
|
124
|
+
return register ? memoryTools : null;
|
|
125
|
+
};
|
|
126
|
+
|
|
77
127
|
const dispatchV1Event = async (delegation, runtime, event) => {
|
|
78
128
|
const translated = translateV1Event(event);
|
|
79
129
|
if (event?.type === "session.deleted") {
|
|
@@ -128,9 +178,12 @@ const createOpenCodeV1Adapter = async ({ project, client, directory, worktree })
|
|
|
128
178
|
});
|
|
129
179
|
if (!runtime) return {};
|
|
130
180
|
|
|
131
|
-
const memoryTools =
|
|
132
|
-
Object.
|
|
133
|
-
|
|
181
|
+
const memoryTools = {
|
|
182
|
+
...Object.fromEntries(
|
|
183
|
+
Object.entries(runtime.tools).map(([name, definition]) => [name, createV1Tool(definition)]),
|
|
184
|
+
),
|
|
185
|
+
...createV1MemoryTools(await resolveV1MemoryTools(client, runtime.memoryTools)),
|
|
186
|
+
};
|
|
134
187
|
|
|
135
188
|
return {
|
|
136
189
|
dispose: async () => {
|
|
@@ -156,6 +209,9 @@ const createOpenCodeV1Adapter = async ({ project, client, directory, worktree })
|
|
|
156
209
|
),
|
|
157
210
|
event: ({ event }) => dispatchV1Event(delegation, runtime, event),
|
|
158
211
|
"tool.execute.after": (input, output) => {
|
|
212
|
+
// Native memory tool output is retrieved memory; capturing it would distill it into new
|
|
213
|
+
// memories. With the flag off, MCP-provided codemem tools keep their existing capture path.
|
|
214
|
+
if (runtime.memoryTools && isMemoryToolId(input?.tool)) return;
|
|
159
215
|
const translated = translateV1ToolResult(input, output);
|
|
160
216
|
return runtime.handleToolResult(translated.input, translated.output);
|
|
161
217
|
},
|
|
@@ -173,6 +229,7 @@ export default CodememPlugin;
|
|
|
173
229
|
export const OpencodeMemPlugin = CodememPlugin;
|
|
174
230
|
export { __testUtils, buildInjectionToastMessage };
|
|
175
231
|
export const __v1AdapterTestUtils = {
|
|
232
|
+
createV1MemoryTools,
|
|
176
233
|
createV1Tool,
|
|
177
234
|
dispatchV1Event,
|
|
178
235
|
extractV1HookSessionID,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codemem/opencode-plugin",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.48.0",
|
|
4
4
|
"description": "CodeMem plugin for OpenCode",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
@@ -35,11 +35,11 @@
|
|
|
35
35
|
".opencode/lib/"
|
|
36
36
|
],
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@opencode-ai/plugin": "1.19.
|
|
38
|
+
"@opencode-ai/plugin": "1.19.5",
|
|
39
39
|
"@opencode/plugin": "2.0.24"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
|
-
"codemem": "^0.
|
|
42
|
+
"codemem": "^0.48.0",
|
|
43
43
|
"@opencode/cli": "2.0.24",
|
|
44
44
|
"@types/node": "^24.12.4",
|
|
45
45
|
"vitest": "^4.1.11"
|
|
@@ -73,6 +73,7 @@
|
|
|
73
73
|
"scripts": {
|
|
74
74
|
"test": "pnpm exec vitest run",
|
|
75
75
|
"test:opencode-v2-contract": "node ./scripts/packed-v2-host-smoke.mjs",
|
|
76
|
+
"test:native-memory-tools-host": "node ./scripts/native-memory-tools-host-smoke.mjs",
|
|
76
77
|
"test:packed-artifact": "pnpm --filter codemem build && node ./scripts/packed-artifact-smoke.mjs",
|
|
77
78
|
"test:packed-artifact:prepared": "node ./scripts/packed-artifact-smoke.mjs"
|
|
78
79
|
}
|