@codemem/opencode-plugin 0.47.4 → 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
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Convert the memory tool JSON Schemas to Zod for OpenCode 1, whose plugin
|
|
3
|
+
* tools only accept Zod argument shapes. Only the subset the shared contracts
|
|
4
|
+
* use is supported; any other keyword throws at registration so a contract
|
|
5
|
+
* change cannot silently lose validation.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const ANNOTATIONS = ["description", "default"];
|
|
9
|
+
const ALLOWED_KEYWORDS = {
|
|
10
|
+
object: ["type", "properties", "required", ...ANNOTATIONS],
|
|
11
|
+
string: ["type", "enum", ...ANNOTATIONS],
|
|
12
|
+
number: ["type", "minimum", "maximum", ...ANNOTATIONS],
|
|
13
|
+
integer: ["type", "minimum", "maximum", ...ANNOTATIONS],
|
|
14
|
+
boolean: ["type", ...ANNOTATIONS],
|
|
15
|
+
array: ["type", "items", "maxItems", ...ANNOTATIONS],
|
|
16
|
+
anyOf: ["anyOf", ...ANNOTATIONS],
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const isRecord = (value) => value != null && typeof value === "object" && !Array.isArray(value);
|
|
20
|
+
|
|
21
|
+
const schemaKind = (schema) => (Array.isArray(schema.anyOf) ? "anyOf" : schema.type);
|
|
22
|
+
|
|
23
|
+
const assertKnownKeywords = (schema, path) => {
|
|
24
|
+
if (!isRecord(schema)) throw new TypeError(`Unsupported memory tool schema at ${path}: not an object`);
|
|
25
|
+
const kind = schemaKind(schema);
|
|
26
|
+
const allowed = ALLOWED_KEYWORDS[kind];
|
|
27
|
+
if (!allowed) throw new TypeError(`Unsupported memory tool schema type at ${path}: ${String(kind)}`);
|
|
28
|
+
const unknown = Object.keys(schema).filter((key) => !allowed.includes(key));
|
|
29
|
+
if (unknown.length > 0) {
|
|
30
|
+
throw new TypeError(`Unsupported memory tool schema keyword at ${path}: ${unknown.join(", ")}`);
|
|
31
|
+
}
|
|
32
|
+
return kind;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const withBounds = (base, schema) => {
|
|
36
|
+
let result = base;
|
|
37
|
+
if (schema.minimum !== undefined) result = result.min(schema.minimum);
|
|
38
|
+
if (schema.maximum !== undefined) result = result.max(schema.maximum);
|
|
39
|
+
return result;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const stringSchema = (z, schema, path) => {
|
|
43
|
+
if (schema.enum === undefined) return z.string();
|
|
44
|
+
if (!Array.isArray(schema.enum) || !schema.enum.every((value) => typeof value === "string")) {
|
|
45
|
+
throw new TypeError(`Unsupported memory tool enum at ${path}: only string enums are supported`);
|
|
46
|
+
}
|
|
47
|
+
return z.enum(schema.enum);
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const arraySchema = (z, schema, path) => {
|
|
51
|
+
const items = convertSchema(z, schema.items, `${path}[]`);
|
|
52
|
+
const array = z.array(items);
|
|
53
|
+
return schema.maxItems === undefined ? array : array.max(schema.maxItems);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const anyOfSchema = (z, schema, path) => {
|
|
57
|
+
const variants = schema.anyOf.map((variant, index) => convertSchema(z, variant, `${path}|${index}`));
|
|
58
|
+
if (variants.length < 2) throw new TypeError(`Unsupported memory tool anyOf at ${path}: needs two variants`);
|
|
59
|
+
return z.union(variants);
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const BASE_CONVERTERS = {
|
|
63
|
+
string: stringSchema,
|
|
64
|
+
number: (z, schema) => withBounds(z.number(), schema),
|
|
65
|
+
integer: (z, schema) => withBounds(z.number().int(), schema),
|
|
66
|
+
boolean: (z) => z.boolean(),
|
|
67
|
+
array: arraySchema,
|
|
68
|
+
anyOf: anyOfSchema,
|
|
69
|
+
object: (z, schema, path) => z.object(convertObjectShape(z, schema, path)),
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const convertSchema = (z, schema, path) => {
|
|
73
|
+
const kind = assertKnownKeywords(schema, path);
|
|
74
|
+
let result = BASE_CONVERTERS[kind](z, schema, path);
|
|
75
|
+
if (typeof schema.description === "string") result = result.describe(schema.description);
|
|
76
|
+
return result;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const convertProperty = (z, schema, { path, required }) => {
|
|
80
|
+
const base = convertSchema(z, schema, path);
|
|
81
|
+
// Defaults mirror the MCP server's Zod schemas, so a defaulted value reaches
|
|
82
|
+
// the handler exactly as it would through stdio MCP.
|
|
83
|
+
if (Object.hasOwn(schema, "default")) return base.default(schema.default);
|
|
84
|
+
return required ? base : base.optional();
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/** Convert an object schema to a Zod raw shape (OpenCode 1 `tool({ args })`). */
|
|
88
|
+
export const convertObjectShape = (z, schema, path = "input") => {
|
|
89
|
+
const kind = assertKnownKeywords(schema, path);
|
|
90
|
+
if (kind !== "object" || !isRecord(schema.properties)) {
|
|
91
|
+
throw new TypeError(`Unsupported memory tool schema at ${path}: expected an object with properties`);
|
|
92
|
+
}
|
|
93
|
+
const required = new Set(schema.required ?? []);
|
|
94
|
+
for (const name of required) {
|
|
95
|
+
if (!Object.hasOwn(schema.properties, name)) {
|
|
96
|
+
throw new TypeError(`Memory tool schema at ${path} requires unknown property ${name}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return Object.fromEntries(
|
|
100
|
+
Object.entries(schema.properties).map(([name, property]) => [
|
|
101
|
+
name,
|
|
102
|
+
convertProperty(z, property, { path: `${path}.${name}`, required: required.has(name) }),
|
|
103
|
+
]),
|
|
104
|
+
);
|
|
105
|
+
};
|
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Native codemem memory tools for OpenCode: the plugin registers the same
|
|
3
|
+
* fourteen tools the codemem MCP server exposes and runs each call through
|
|
4
|
+
* the shared viewer (`POST /api/memory-tools/:name`), falling back to
|
|
5
|
+
* `codemem memory-tool <name>` when the viewer cannot take the call.
|
|
6
|
+
*
|
|
7
|
+
* Arguments pass through unchanged. The viewer and the CLI run the real MCP
|
|
8
|
+
* handlers with this caller's directory and CODEMEM_PROJECT, so default
|
|
9
|
+
* project scoping matches stdio MCP without the plugin injecting anything.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { readFileSync } from "node:fs";
|
|
13
|
+
import { isAbsolute } from "node:path";
|
|
14
|
+
|
|
15
|
+
export const NATIVE_TOOLS_ENV = "CODEMEM_OPENCODE_NATIVE_TOOLS";
|
|
16
|
+
// Experimental for one release; the setup/docs rollout step flips this default.
|
|
17
|
+
const NATIVE_TOOLS_DEFAULT = false;
|
|
18
|
+
const TRUTHY_VALUES = new Set(["1", "true", "yes"]);
|
|
19
|
+
|
|
20
|
+
export const MEMORY_TOOL_NAMESPACE = "codemem";
|
|
21
|
+
export const MEMORY_TOOL_NAMESPACE_DESCRIPTION =
|
|
22
|
+
"codemem persistent memory: search, inspect, and record memories for this project";
|
|
23
|
+
// The ingest filter drops tool events with this prefix, so tool output never
|
|
24
|
+
// gets captured and re-distilled into new memories.
|
|
25
|
+
export const MEMORY_TOOL_ID_PREFIX = "codemem_memory_";
|
|
26
|
+
export const CLI_FALLBACK_NOTE = "(codemem viewer unavailable; ran via CLI)";
|
|
27
|
+
export const MEMORY_TOOL_CALL_CAPABILITY = "memory_tool_call";
|
|
28
|
+
|
|
29
|
+
const WRITE_TOOLS = new Set(["memory_remember", "memory_forget"]);
|
|
30
|
+
const TOOL_TIMEOUT_MS = Object.freeze({
|
|
31
|
+
memory_pack: 120_000,
|
|
32
|
+
memory_distill_candidates: 300_000,
|
|
33
|
+
});
|
|
34
|
+
const DEFAULT_TOOL_TIMEOUT_MS = 30_000;
|
|
35
|
+
const PROOF_TIMEOUT_MS = 2_000;
|
|
36
|
+
const PROOF_TTL_MS = 30_000;
|
|
37
|
+
// Failures where the request never reached the viewer, so a CLI retry cannot double-apply a write.
|
|
38
|
+
const SAFE_CONNECT_CODES = new Set([
|
|
39
|
+
"ECONNREFUSED",
|
|
40
|
+
"ENOTFOUND",
|
|
41
|
+
"EAI_AGAIN",
|
|
42
|
+
"ENETUNREACH",
|
|
43
|
+
"EHOSTUNREACH",
|
|
44
|
+
]);
|
|
45
|
+
const FALLBACK_STATUSES = new Set([404, 405, 409]);
|
|
46
|
+
|
|
47
|
+
const isRecord = (value) => value != null && typeof value === "object" && !Array.isArray(value);
|
|
48
|
+
|
|
49
|
+
export const nativeMemoryToolsEnabled = (env = process.env) => {
|
|
50
|
+
const raw = String(env[NATIVE_TOOLS_ENV] ?? "").trim().toLowerCase();
|
|
51
|
+
if (!raw) return NATIVE_TOOLS_DEFAULT;
|
|
52
|
+
return TRUTHY_VALUES.has(raw);
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export const memoryToolId = (name) => `${MEMORY_TOOL_NAMESPACE}_${name}`;
|
|
56
|
+
|
|
57
|
+
/** Host tool names may arrive namespaced with dots (`codemem.memory_search`); compare the effective form. */
|
|
58
|
+
export const isMemoryToolId = (toolName) =>
|
|
59
|
+
String(toolName || "").replace(/[^A-Za-z0-9_]/g, "_").startsWith(MEMORY_TOOL_ID_PREFIX);
|
|
60
|
+
|
|
61
|
+
let contractsCache = null;
|
|
62
|
+
export const loadMemoryToolContracts = () => {
|
|
63
|
+
contractsCache ??= Object.freeze(
|
|
64
|
+
JSON.parse(readFileSync(new URL("./memory-tool-contracts.json", import.meta.url), "utf8")),
|
|
65
|
+
);
|
|
66
|
+
return contractsCache;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
export const memoryToolTimeoutMs = (name) => TOOL_TIMEOUT_MS[name] ?? DEFAULT_TOOL_TIMEOUT_MS;
|
|
70
|
+
|
|
71
|
+
const abortError = (signal) => {
|
|
72
|
+
if (signal?.reason instanceof Error) return signal.reason;
|
|
73
|
+
const error = new Error("codemem memory tool call was cancelled");
|
|
74
|
+
error.name = "AbortError";
|
|
75
|
+
return error;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const throwIfAborted = (signal) => {
|
|
79
|
+
if (signal?.aborted) throw abortError(signal);
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const collectErrorCodes = (error) => {
|
|
83
|
+
const codes = [];
|
|
84
|
+
let current = error;
|
|
85
|
+
for (let depth = 0; depth < 6 && isRecord(current); depth += 1) {
|
|
86
|
+
if (typeof current.code === "string") codes.push(current.code);
|
|
87
|
+
current = current.cause;
|
|
88
|
+
}
|
|
89
|
+
return codes;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
export const isSafeConnectFailure = (error) =>
|
|
93
|
+
collectErrorCodes(error).some((code) => SAFE_CONNECT_CODES.has(code));
|
|
94
|
+
|
|
95
|
+
/** Abort on the caller's signal or after `timeoutMs`, and report which one fired. */
|
|
96
|
+
const linkSignal = (timeoutMs, signal) => {
|
|
97
|
+
const controller = new AbortController();
|
|
98
|
+
const state = { timedOut: false };
|
|
99
|
+
const onAbort = () => controller.abort();
|
|
100
|
+
if (signal?.aborted) controller.abort();
|
|
101
|
+
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
102
|
+
const timer = setTimeout(() => {
|
|
103
|
+
state.timedOut = true;
|
|
104
|
+
controller.abort();
|
|
105
|
+
}, timeoutMs);
|
|
106
|
+
return {
|
|
107
|
+
signal: controller.signal,
|
|
108
|
+
state,
|
|
109
|
+
release: () => {
|
|
110
|
+
clearTimeout(timer);
|
|
111
|
+
signal?.removeEventListener("abort", onAbort);
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const readJson = async (response) => {
|
|
117
|
+
try {
|
|
118
|
+
return await response.json();
|
|
119
|
+
} catch {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
export const buildMemoryToolCaller = ({ directory, sessionID, callID, envProject }) => {
|
|
125
|
+
const sessionId = typeof sessionID === "string" && sessionID.trim() ? sessionID.trim() : null;
|
|
126
|
+
const requestId = typeof callID === "string" && callID.trim() ? callID.trim() : null;
|
|
127
|
+
const project = typeof envProject === "string" ? envProject.trim() : "";
|
|
128
|
+
return {
|
|
129
|
+
directory,
|
|
130
|
+
env_project: project || null,
|
|
131
|
+
...(sessionId ? { session_id: sessionId } : {}),
|
|
132
|
+
// The viewer rejects a request ID without a session, and so would the ledger.
|
|
133
|
+
...(sessionId && requestId ? { request_id: requestId } : {}),
|
|
134
|
+
};
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* `--db-path` pins the database the viewer target proof uses. A relative
|
|
139
|
+
* CODEMEM_DB would otherwise resolve against the caller directory (the CLI's
|
|
140
|
+
* cwd) instead of the runtime cwd the viewer was started from.
|
|
141
|
+
*/
|
|
142
|
+
export const buildMemoryToolCliArgs = (name, caller, dbPath) => {
|
|
143
|
+
const args = ["memory-tool", name];
|
|
144
|
+
if (dbPath) args.push("--db-path", dbPath);
|
|
145
|
+
if (caller.session_id) args.push("--session-id", caller.session_id);
|
|
146
|
+
if (caller.request_id) args.push("--request-id", caller.request_id);
|
|
147
|
+
return args;
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
/** The last stdout line that parses as a JSON object; the CLI may log before it. */
|
|
151
|
+
const parseCliPayload = (stdout) => {
|
|
152
|
+
const lines = String(stdout || "").split("\n").map((line) => line.trim()).filter(Boolean);
|
|
153
|
+
for (const line of lines.reverse()) {
|
|
154
|
+
try {
|
|
155
|
+
const parsed = JSON.parse(line);
|
|
156
|
+
if (isRecord(parsed)) return parsed;
|
|
157
|
+
} catch {
|
|
158
|
+
// keep scanning earlier lines
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return null;
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const toolOutcome = (payload) => {
|
|
165
|
+
if (payload.ok === true) return { ok: true, result: payload.result };
|
|
166
|
+
return {
|
|
167
|
+
ok: false,
|
|
168
|
+
error: String(payload.error ?? "tool_error"),
|
|
169
|
+
...(payload.result !== undefined ? { result: payload.result } : {}),
|
|
170
|
+
};
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const unsettledWriteMessage = (name, reason) =>
|
|
174
|
+
`${name} ${reason}; the write may have completed, so it was not retried. Check with memory_recent before retrying.`;
|
|
175
|
+
|
|
176
|
+
/** Viewer failure where retrying the same call through the CLI is safe for reads but not writes. */
|
|
177
|
+
const uncertainFailure = (name, reason) => {
|
|
178
|
+
if (WRITE_TOOLS.has(name)) return { kind: "error", error: unsettledWriteMessage(name, reason) };
|
|
179
|
+
return { kind: "fallback", reason };
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
const classifyViewerResponse = async (name, response) => {
|
|
183
|
+
const body = await readJson(response);
|
|
184
|
+
if (response.ok && isRecord(body) && typeof body.ok === "boolean") {
|
|
185
|
+
return { kind: "outcome", outcome: toolOutcome(body) };
|
|
186
|
+
}
|
|
187
|
+
if (response.ok) return uncertainFailure(name, "returned a malformed viewer response");
|
|
188
|
+
if (FALLBACK_STATUSES.has(response.status)) {
|
|
189
|
+
return { kind: "fallback", reason: `viewer HTTP ${response.status}`, invalidate: true };
|
|
190
|
+
}
|
|
191
|
+
if (response.status >= 500) return uncertainFailure(name, `failed in the viewer (HTTP ${response.status})`);
|
|
192
|
+
const message = isRecord(body?.error) ? body.error.message : body?.error;
|
|
193
|
+
return { kind: "error", error: String(message || `viewer HTTP ${response.status}`) };
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const createViewerProof = ({ fetchImpl, profileUrl, isProfileMatch, now }) => {
|
|
197
|
+
let provenUntil = 0;
|
|
198
|
+
const prove = async (signal) => {
|
|
199
|
+
if (now() < provenUntil) return true;
|
|
200
|
+
const link = linkSignal(PROOF_TIMEOUT_MS, signal);
|
|
201
|
+
try {
|
|
202
|
+
const response = await fetchImpl(profileUrl, { method: "GET", redirect: "manual", signal: link.signal });
|
|
203
|
+
const profile = response.ok ? await readJson(response) : null;
|
|
204
|
+
const capable = Array.isArray(profile?.capabilities)
|
|
205
|
+
&& profile.capabilities.includes(MEMORY_TOOL_CALL_CAPABILITY);
|
|
206
|
+
if (!capable || !isProfileMatch(profile)) return false;
|
|
207
|
+
provenUntil = now() + PROOF_TTL_MS;
|
|
208
|
+
return true;
|
|
209
|
+
} catch {
|
|
210
|
+
throwIfAborted(signal);
|
|
211
|
+
return false;
|
|
212
|
+
} finally {
|
|
213
|
+
link.release();
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
return {
|
|
217
|
+
prove,
|
|
218
|
+
invalidate: () => {
|
|
219
|
+
provenUntil = 0;
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
const formatCliFailure = (name, result) => {
|
|
225
|
+
if (result.exitCode === null) {
|
|
226
|
+
if (WRITE_TOOLS.has(name)) return unsettledWriteMessage(name, "timed out in the codemem CLI");
|
|
227
|
+
return `${name} timed out in the codemem CLI`;
|
|
228
|
+
}
|
|
229
|
+
const payload = parseCliPayload(result.stdout);
|
|
230
|
+
const detail = payload?.message ?? payload?.error ?? String(result.stderr || "").trim();
|
|
231
|
+
return detail ? String(detail) : `codemem memory-tool exited with code ${result.exitCode}`;
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* @param {object} options
|
|
236
|
+
* @param {boolean} options.viewerEnabled
|
|
237
|
+
* @param {string} options.viewerBaseUrl `http://host:port`, no trailing slash
|
|
238
|
+
* @param {string} options.dbPath
|
|
239
|
+
* @param {object} options.identityTarget
|
|
240
|
+
* @param {(profile: unknown) => boolean} options.isProfileMatch Same target proof prompt recall uses.
|
|
241
|
+
* @param {(args: string[], options: object) => Promise<{exitCode: number | null, stdout: string, stderr: string}>} options.runCli
|
|
242
|
+
* @param {string} options.defaultDirectory Used only when the host context omits a directory.
|
|
243
|
+
*/
|
|
244
|
+
export const createMemoryToolExecutor = ({
|
|
245
|
+
viewerEnabled,
|
|
246
|
+
viewerBaseUrl,
|
|
247
|
+
dbPath,
|
|
248
|
+
identityTarget,
|
|
249
|
+
isProfileMatch,
|
|
250
|
+
runCli,
|
|
251
|
+
defaultDirectory,
|
|
252
|
+
readEnvProject = () => process.env.CODEMEM_PROJECT,
|
|
253
|
+
fetchImpl = (...args) => fetch(...args),
|
|
254
|
+
now = Date.now,
|
|
255
|
+
}) => {
|
|
256
|
+
const proof = createViewerProof({
|
|
257
|
+
fetchImpl,
|
|
258
|
+
profileUrl: `${viewerBaseUrl}/api/prompt-pack-profile`,
|
|
259
|
+
isProfileMatch,
|
|
260
|
+
now,
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
const callViewer = async (name, args, caller, signal) => {
|
|
264
|
+
if (!viewerEnabled) return { kind: "fallback", reason: "viewer disabled" };
|
|
265
|
+
if (!(await proof.prove(signal))) return { kind: "fallback", reason: "viewer unproven" };
|
|
266
|
+
const link = linkSignal(memoryToolTimeoutMs(name), signal);
|
|
267
|
+
try {
|
|
268
|
+
const response = await fetchImpl(`${viewerBaseUrl}/api/memory-tools/${encodeURIComponent(name)}`, {
|
|
269
|
+
method: "POST",
|
|
270
|
+
redirect: "manual",
|
|
271
|
+
headers: { "Content-Type": "application/json" },
|
|
272
|
+
body: JSON.stringify({ arguments: args, caller, db_path: dbPath, identity_target: identityTarget }),
|
|
273
|
+
signal: link.signal,
|
|
274
|
+
});
|
|
275
|
+
const classified = await classifyViewerResponse(name, response);
|
|
276
|
+
if (classified.invalidate) proof.invalidate();
|
|
277
|
+
return classified;
|
|
278
|
+
} catch (error) {
|
|
279
|
+
proof.invalidate();
|
|
280
|
+
throwIfAborted(signal);
|
|
281
|
+
if (link.state.timedOut) return uncertainFailure(name, "timed out in the viewer");
|
|
282
|
+
if (isSafeConnectFailure(error)) return { kind: "fallback", reason: "viewer unreachable" };
|
|
283
|
+
return uncertainFailure(name, "lost its viewer connection");
|
|
284
|
+
} finally {
|
|
285
|
+
link.release();
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
const callCli = async (name, args, caller, signal) => {
|
|
290
|
+
const result = await runCli(buildMemoryToolCliArgs(name, caller, dbPath), {
|
|
291
|
+
cwd: caller.directory,
|
|
292
|
+
stdinText: JSON.stringify(args),
|
|
293
|
+
signal,
|
|
294
|
+
timeoutMs: memoryToolTimeoutMs(name),
|
|
295
|
+
});
|
|
296
|
+
throwIfAborted(signal);
|
|
297
|
+
const payload = result.exitCode === 0 ? parseCliPayload(result.stdout) : null;
|
|
298
|
+
if (typeof payload?.ok === "boolean") return toolOutcome(payload);
|
|
299
|
+
return { ok: false, error: formatCliFailure(name, result) };
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Run one memory tool. Resolves `{ ok, result | error, transport }`; throws
|
|
304
|
+
* only when `signal` aborts.
|
|
305
|
+
*/
|
|
306
|
+
const execute = async (name, rawArgs, { directory, sessionID, callID, signal } = {}) => {
|
|
307
|
+
throwIfAborted(signal);
|
|
308
|
+
const args = isRecord(rawArgs) ? rawArgs : {};
|
|
309
|
+
const caller = buildMemoryToolCaller({
|
|
310
|
+
directory: typeof directory === "string" && isAbsolute(directory) ? directory : defaultDirectory,
|
|
311
|
+
sessionID,
|
|
312
|
+
callID,
|
|
313
|
+
envProject: readEnvProject(),
|
|
314
|
+
});
|
|
315
|
+
const viewer = await callViewer(name, args, caller, signal);
|
|
316
|
+
if (viewer.kind === "outcome") return { ...viewer.outcome, transport: "viewer" };
|
|
317
|
+
if (viewer.kind === "error") return { ok: false, error: viewer.error, transport: "viewer" };
|
|
318
|
+
return { ...(await callCli(name, args, caller, signal)), transport: "cli" };
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
return { execute, invalidateProof: proof.invalidate };
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
const resultText = (value) => (typeof value === "string" ? value : JSON.stringify(value ?? null));
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Text the model sees, matching the MCP tool content: the JSON result on
|
|
328
|
+
* success, the MCP error payload (or `{"error":...}`) on failure. The CLI note
|
|
329
|
+
* stays separate so the JSON remains parseable.
|
|
330
|
+
*/
|
|
331
|
+
export const formatMemoryToolOutcome = (outcome) => {
|
|
332
|
+
let text;
|
|
333
|
+
if (outcome.ok) text = resultText(outcome.result);
|
|
334
|
+
else if (outcome.result != null) text = resultText(outcome.result);
|
|
335
|
+
else text = JSON.stringify({ error: outcome.error });
|
|
336
|
+
return {
|
|
337
|
+
isError: !outcome.ok,
|
|
338
|
+
text,
|
|
339
|
+
note: outcome.transport === "cli" ? CLI_FALLBACK_NOTE : null,
|
|
340
|
+
};
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
export const MCP_PREFERRED_MESSAGE =
|
|
344
|
+
"codemem MCP server is configured, so codemem's built-in memory tools are off. "
|
|
345
|
+
+ "Remove the codemem MCP server from your OpenCode config to switch to them, or keep it.";
|
|
346
|
+
const MCP_DETECTION_TIMEOUT_MS = 2_000;
|
|
347
|
+
|
|
348
|
+
const withTimeout = (promise, timeoutMs) => {
|
|
349
|
+
let timer;
|
|
350
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
351
|
+
timer = setTimeout(() => reject(new Error(`timed out after ${timeoutMs} ms`)), timeoutMs);
|
|
352
|
+
});
|
|
353
|
+
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
|
354
|
+
};
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Runtime-facing bundle: contracts, the executor, and the registration
|
|
358
|
+
* decision. A configured "codemem" MCP server wins so the model never sees
|
|
359
|
+
* two sets of memory tools (users who chose `--opencode-mcp stdio`, or who
|
|
360
|
+
* upgraded without re-running setup). Detection failures register the
|
|
361
|
+
* native tools.
|
|
362
|
+
*/
|
|
363
|
+
export const createNativeMemoryTools = ({ executor, log, notify = null }) => {
|
|
364
|
+
const announceMcpPreferred = async () => {
|
|
365
|
+
await log("warn", MCP_PREFERRED_MESSAGE);
|
|
366
|
+
if (!notify) return;
|
|
367
|
+
try {
|
|
368
|
+
await notify({ message: MCP_PREFERRED_MESSAGE, variant: "warning" });
|
|
369
|
+
} catch {
|
|
370
|
+
// best-effort only
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
let announced = false;
|
|
374
|
+
const announceOnce = async () => {
|
|
375
|
+
if (announced) return;
|
|
376
|
+
announced = true;
|
|
377
|
+
await announceMcpPreferred();
|
|
378
|
+
};
|
|
379
|
+
return {
|
|
380
|
+
contracts: loadMemoryToolContracts(),
|
|
381
|
+
execute: executor.execute,
|
|
382
|
+
/** Log and toast once that a codemem MCP server took precedence. */
|
|
383
|
+
announceMcpPreferred: announceOnce,
|
|
384
|
+
/** @param {{ isCodememMcpConfigured: (() => Promise<boolean>) | null }} detection */
|
|
385
|
+
shouldRegister: async ({ isCodememMcpConfigured }) => {
|
|
386
|
+
if (typeof isCodememMcpConfigured !== "function") {
|
|
387
|
+
await log("warn", "codemem could not check for a codemem MCP server; registering built-in memory tools");
|
|
388
|
+
return true;
|
|
389
|
+
}
|
|
390
|
+
let configured;
|
|
391
|
+
try {
|
|
392
|
+
configured = await withTimeout(isCodememMcpConfigured(), MCP_DETECTION_TIMEOUT_MS);
|
|
393
|
+
} catch (error) {
|
|
394
|
+
await log("warn", "codemem MCP server check failed; registering built-in memory tools", {
|
|
395
|
+
error: error instanceof Error ? error.message : String(error),
|
|
396
|
+
});
|
|
397
|
+
return true;
|
|
398
|
+
}
|
|
399
|
+
if (!configured) return true;
|
|
400
|
+
await announceOnce();
|
|
401
|
+
return false;
|
|
402
|
+
},
|
|
403
|
+
};
|
|
404
|
+
};
|