opencode-codex-memory 0.10.0 → 0.10.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 (45) hide show
  1. package/README.md +10 -12
  2. package/dist/src/agent-health.js +10 -7
  3. package/dist/src/capture.js +7 -7
  4. package/dist/src/citation.js +12 -3
  5. package/dist/src/claude-import.js +1 -3
  6. package/dist/src/codex-interop.js +51 -17
  7. package/dist/src/db.d.ts +0 -2
  8. package/dist/src/db.js +0 -4
  9. package/dist/src/git-baseline.d.ts +10 -11
  10. package/dist/src/git-baseline.js +167 -97
  11. package/dist/src/host-client.d.ts +5 -0
  12. package/dist/src/host-client.js +24 -0
  13. package/dist/src/index.d.ts +1 -1
  14. package/dist/src/index.js +56 -99
  15. package/dist/src/llm.d.ts +4 -1
  16. package/dist/src/llm.js +43 -15
  17. package/dist/src/options.d.ts +7 -0
  18. package/dist/src/options.js +20 -2
  19. package/dist/src/paths.d.ts +1 -0
  20. package/dist/src/paths.js +5 -2
  21. package/dist/src/phase1.js +12 -21
  22. package/dist/src/phase2.js +7 -6
  23. package/dist/src/reasoning-variant.d.ts +7 -0
  24. package/dist/src/reasoning-variant.js +11 -2
  25. package/dist/src/rollout-input.js +3 -5
  26. package/dist/src/session-version.js +4 -5
  27. package/dist/src/source.js +6 -2
  28. package/dist/src/store.d.ts +3 -2
  29. package/dist/src/store.js +72 -47
  30. package/dist/src/v2/agents.js +11 -14
  31. package/dist/src/v2/model-readiness.js +3 -1
  32. package/dist/src/v2/plugin.js +81 -109
  33. package/dist/src/v2/search-sandbox.js +1 -1
  34. package/dist/src/v2/service.js +5 -0
  35. package/dist/src/v2/shim.d.ts +3 -0
  36. package/dist/src/v2/shim.js +144 -90
  37. package/dist/src/v2/status-rpc.js +40 -14
  38. package/dist/src/v2/status.js +4 -7
  39. package/dist/src/v2/tools.d.ts +15 -9
  40. package/dist/src/v2/tools.js +9 -9
  41. package/dist/src/v2/tui.js +14 -4
  42. package/dist/src/workspace.js +13 -4
  43. package/dist/tools/control.js +29 -28
  44. package/dist/tools/memory.js +163 -89
  45. package/package.json +22 -9
@@ -1,4 +1,3 @@
1
- import { createHash } from "crypto";
2
1
  import fs from "fs";
3
2
  import path from "path";
4
3
  import { memoryRoot } from "./paths.js";
@@ -10,6 +9,11 @@ const AUTHOR = { name: "opencode-codex-memory", email: "memory@opencode.local" }
10
9
  // commits (mirrors codex's remove_workspace_diff) so it never enters the
11
10
  // baseline history or shows up as memory content.
12
11
  export const DIFF_ARTIFACT = "phase2_workspace_diff.md";
12
+ // codex baseline.rs: a baseline is derived data, so snapshots skip files above
13
+ // the automatic ghost-snapshot limit instead of reading unbounded content.
14
+ const MAX_BASELINE_FILE_BYTES = 10 * 1024 * 1024;
15
+ const BASELINE_VERSION_FILE = "codex-baseline-version";
16
+ const BASELINE_VERSION = "1\n";
13
17
  /**
14
18
  * Hidden path components are invisible to tools/path-guard (`not found`).
15
19
  * Codex's gix walker includes them and reads bytes directly; isomorphic-git
@@ -20,73 +24,50 @@ function isHiddenBaselinePath(filepath) {
20
24
  return filepath.split("/").some((part) => part.startsWith("."));
21
25
  }
22
26
  const EXTENSIONS_PREFIX = "extensions/";
23
- function workdirHash(dir, filepath) {
24
- try {
25
- const content = readRegularFileNoFollow(safeResolveUnderRoot(dir, filepath)).content;
26
- return createHash("sha1").update(content).digest("hex");
27
- }
28
- catch {
29
- return null;
30
- }
31
- }
32
27
  function removeDiffArtifact(dir) {
33
28
  try {
34
29
  fs.unlinkSync(path.join(dir, DIFF_ARTIFACT));
35
30
  }
36
- catch {
37
- }
31
+ catch { }
38
32
  }
39
- async function ensureInit(dir) {
40
- const gitDir = path.join(dir, ".git");
41
- let recreate = false;
42
- try {
43
- recreate = gitMetadataUnusable(gitDir);
44
- }
45
- catch (err) {
46
- if (err.code !== "ENOENT")
47
- throw err;
48
- }
49
- if (recreate)
50
- fs.rmSync(gitDir, { recursive: true, force: true });
51
- if (!fs.existsSync(gitDir)) {
52
- await isogit.init({ fs, dir });
53
- }
33
+ function baselineVersionPath(dir) {
34
+ return path.join(dir, ".git", BASELINE_VERSION_FILE);
54
35
  }
55
36
  /**
56
37
  * Only the `.git` entry itself. A recursive walk of git objects hangs on
57
38
  * Windows junctions / symlink cycles and is not needed: we only refuse a
58
- * `.git` that is a symlink or a non-directory.
39
+ * `.git` that is a symlink, a non-directory (gitfile), or a linked worktree.
59
40
  */
60
41
  function gitMetadataUnusable(gitDir) {
61
42
  const st = fs.lstatSync(gitDir);
62
- return st.isSymbolicLink() || !st.isDirectory();
63
- }
64
- // statusMatrix rows are [filepath, head, workdir, stage]; head !== workdir
65
- // means the working tree differs from HEAD (added, modified, or deleted).
66
- async function stageAll(dir, skip) {
67
- const matrix = await isogit.statusMatrix({ fs, dir });
68
- let changes = 0;
69
- for (const [filepath, head, workdir, stage] of matrix) {
70
- if (isHiddenBaselinePath(filepath))
71
- continue;
72
- if (head === 1 && workdir === 1 && stage === 1)
73
- continue;
74
- if (workdir !== 0 && skip?.(filepath))
75
- continue;
76
- if (workdir === 0) {
77
- // isogit.add throws on deleted files; they must be staged via remove
78
- await isogit.remove({ fs, dir, filepath });
79
- }
80
- else {
81
- await isogit.add({ fs, dir, filepath });
82
- }
83
- if (head !== workdir)
84
- changes++;
43
+ if (st.isSymbolicLink() || !st.isDirectory())
44
+ return true;
45
+ // codex requires common_dir == git_dir; a commondir file marks a linked worktree.
46
+ return fs.existsSync(path.join(gitDir, "commondir"));
47
+ }
48
+ function isOversizedFile(dir, filepath) {
49
+ try {
50
+ const st = fs.lstatSync(path.join(dir, filepath));
51
+ return st.isFile() && st.size > MAX_BASELINE_FILE_BYTES;
52
+ }
53
+ catch {
54
+ return false;
85
55
  }
86
- return changes;
87
56
  }
88
- async function hasHeadCommit(dir) {
57
+ function statusMatrix(dir, gitdir) {
58
+ return isogit.statusMatrix({
59
+ fs,
60
+ dir,
61
+ gitdir,
62
+ filter: (filepath) => !isHiddenBaselinePath(filepath) && !isOversizedFile(dir, filepath),
63
+ });
64
+ }
65
+ async function hasVersionedBaseline(dir) {
89
66
  try {
67
+ if (gitMetadataUnusable(path.join(dir, ".git")))
68
+ return false;
69
+ if (fs.readFileSync(baselineVersionPath(dir), "utf8") !== BASELINE_VERSION)
70
+ return false;
90
71
  await isogit.resolveRef({ fs, dir, ref: "HEAD" });
91
72
  return true;
92
73
  }
@@ -94,36 +75,45 @@ async function hasHeadCommit(dir) {
94
75
  return false;
95
76
  }
96
77
  }
97
- async function commitBaseline(dir, skip) {
98
- await stageAll(dir, skip);
99
- return isogit.commit({ fs, dir, message: "memory baseline", author: AUTHOR });
78
+ /**
79
+ * codex ensure_git_baseline_repository: missing, outdated, or unusable
80
+ * metadata is replaced with an EMPTY baseline, so every eligible working file
81
+ * stays visible to the next consolidation as an addition. The version marker
82
+ * is written last; an interrupted reset therefore never looks trusted.
83
+ */
84
+ async function initEmptyBaseline(dir) {
85
+ fs.rmSync(path.join(dir, ".git"), { recursive: true, force: true });
86
+ await isogit.init({ fs, dir });
87
+ const tree = await isogit.writeTree({ fs, dir, tree: [] });
88
+ await isogit.commit({ fs, dir, message: "memory baseline", author: AUTHOR, tree, parent: [] });
89
+ fs.writeFileSync(baselineVersionPath(dir), BASELINE_VERSION);
90
+ }
91
+ async function ensureVersionedBaseline(dir) {
92
+ if (!(await hasVersionedBaseline(dir)))
93
+ await initEmptyBaseline(dir);
100
94
  }
101
95
  /**
102
- * Mirrors codex prepare_memory_workspace: an existing baseline is preserved
103
- * untouched so the phase-2 diff spans last-successful-run -> now — including
104
- * manual user edits and newly added ad-hoc notes. Committing here would
105
- * swallow those changes and consolidation would never see them. Only a root
106
- * without any commit gets a fresh baseline.
96
+ * Mirrors codex prepare_memory_workspace: a current-version baseline is
97
+ * preserved untouched so the phase-2 diff spans last-successful-run -> now —
98
+ * including manual user edits and newly added ad-hoc notes. Committing here
99
+ * would swallow those changes and consolidation would never see them. Missing,
100
+ * outdated, or unusable metadata gets an empty baseline (codex keeps existing
101
+ * memory files visible as additions).
107
102
  */
108
103
  export async function ensureBaseline() {
109
104
  const dir = memoryRoot();
110
105
  try {
111
106
  removeDiffArtifact(dir);
112
- await ensureInit(dir);
113
- if (!(await hasHeadCommit(dir))) {
114
- await commitBaseline(dir);
115
- }
107
+ await ensureVersionedBaseline(dir);
116
108
  return true;
117
109
  }
118
110
  catch (err) {
119
111
  // codex ensure_git_baseline_repository: unusable/corrupt git metadata is
120
- // recovered by a destructive fresh re-init (reset_git_repository_sync)
121
- // instead of failing the job forever.
112
+ // recovered by a destructive fresh empty re-init instead of failing the
113
+ // job forever.
122
114
  console.error("[opencode-codex-memory] ensureBaseline error, re-initializing baseline:", err);
123
115
  try {
124
- fs.rmSync(path.join(dir, ".git"), { recursive: true, force: true });
125
- await isogit.init({ fs, dir });
126
- await commitBaseline(dir);
116
+ await initEmptyBaseline(dir);
127
117
  return true;
128
118
  }
129
119
  catch (err2) {
@@ -141,19 +131,79 @@ async function readBaselineText(dir, headOid, filepath) {
141
131
  return "";
142
132
  }
143
133
  }
144
- function readWorkdirText(dir, filepath) {
134
+ function readWorkingFile(dir, filepath) {
145
135
  const file = safeResolveUnderRoot(dir, filepath);
146
- return readRegularFileNoFollow(file).content.toString("utf8");
136
+ if (fs.lstatSync(file).size > MAX_BASELINE_FILE_BYTES) {
137
+ throw new Error(`file grew beyond the snapshot file limit during diff: ${filepath}`);
138
+ }
139
+ return readRegularFileNoFollow(file).content;
140
+ }
141
+ /**
142
+ * Every non-hidden regular file above the snapshot limit. Used to invalidate a
143
+ * baseline whose tracked inputs grew after preparation (codex
144
+ * diff_since_latest_init).
145
+ */
146
+ function collectOversizedPaths(dir) {
147
+ const out = [];
148
+ const walk = (current, prefix) => {
149
+ let entries;
150
+ try {
151
+ entries = fs.readdirSync(current, { withFileTypes: true });
152
+ }
153
+ catch {
154
+ return;
155
+ }
156
+ for (const entry of entries) {
157
+ if (entry.name === ".git")
158
+ continue;
159
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
160
+ if (isHiddenBaselinePath(rel))
161
+ continue;
162
+ const full = path.join(current, entry.name);
163
+ if (entry.isDirectory()) {
164
+ walk(full, rel);
165
+ }
166
+ else if (entry.isFile()) {
167
+ try {
168
+ if (fs.lstatSync(full).size > MAX_BASELINE_FILE_BYTES)
169
+ out.push(rel);
170
+ }
171
+ catch { }
172
+ }
173
+ }
174
+ };
175
+ walk(dir, "");
176
+ return out;
177
+ }
178
+ async function hasTrackedOversizedFile(dir) {
179
+ const oversized = collectOversizedPaths(dir);
180
+ if (oversized.length === 0)
181
+ return false;
182
+ let tracked;
183
+ try {
184
+ tracked = await isogit.listFiles({ fs, dir, ref: "HEAD" });
185
+ }
186
+ catch {
187
+ return false;
188
+ }
189
+ const trackedSet = new Set(tracked);
190
+ return oversized.some((filepath) => trackedSet.has(filepath));
147
191
  }
148
192
  // Throws on failure: codex fails the phase-2 job on workspace-status errors
149
193
  // (failed_workspace_status). Swallowing the error here would make an errored
150
194
  // diff indistinguishable from "no changes" and falsely mark the job succeeded.
151
195
  export async function captureWorkspaceDiff() {
152
196
  const dir = memoryRoot();
153
- await ensureInit(dir);
197
+ await ensureVersionedBaseline(dir);
154
198
  removeDiffArtifact(dir);
155
- const matrix = await isogit.statusMatrix({ fs, dir });
156
- const changedRows = matrix.filter(([filepath, head, workdir]) => head !== workdir && filepath !== DIFF_ARTIFACT && !isHiddenBaselinePath(filepath));
199
+ let matrix = await statusMatrix(dir);
200
+ // Inputs may grow during synchronization, after the initial baseline was
201
+ // prepared. Rebuild empty so the remaining files stay visible as additions.
202
+ if (await hasTrackedOversizedFile(dir)) {
203
+ await initEmptyBaseline(dir);
204
+ matrix = await statusMatrix(dir);
205
+ }
206
+ const changedRows = matrix.filter(([filepath, head, workdir]) => head !== workdir && filepath !== DIFF_ARTIFACT);
157
207
  const changes = changedRows.map(([filepath, head, workdir]) => {
158
208
  if (head === 0)
159
209
  return { status: "A", path: filepath };
@@ -169,20 +219,23 @@ export async function captureWorkspaceDiff() {
169
219
  // no commits yet — every file diffs against empty
170
220
  }
171
221
  const patches = [];
222
+ const extensionSnapshot = new Map();
172
223
  for (const [filepath, head, workdir] of changedRows) {
173
224
  const oldText = head === 1 && headOid ? await readBaselineText(dir, headOid, filepath) : "";
174
- const newText = workdir === 0 ? "" : readWorkdirText(dir, filepath);
175
- // No per-file cap: codex renders every file's patch in full and relies
176
- // on the global 4 MiB truncation in writeWorkspaceDiff.
225
+ const content = workdir === 0 ? null : readWorkingFile(dir, filepath);
226
+ const newText = content?.toString("utf8") ?? "";
227
+ if (content && filepath.startsWith(EXTENSIONS_PREFIX))
228
+ extensionSnapshot.set(filepath, await isogit.writeBlob({ fs, dir, blob: content }));
229
+ // Per-file patches render in full; only the global 4 MiB truncation in
230
+ // writeWorkspaceDiff caps the rendered diff. Files above the baseline
231
+ // snapshot limit never reach this loop.
177
232
  patches.push(createPatch(filepath, oldText, newText));
178
233
  }
179
- const extensionSnapshot = new Map();
180
234
  for (const [filepath, , workdir] of matrix) {
181
- if (workdir === 0 || !filepath.startsWith(EXTENSIONS_PREFIX) || isHiddenBaselinePath(filepath))
182
- continue;
183
- const hash = workdirHash(dir, filepath);
184
- if (hash)
185
- extensionSnapshot.set(filepath, hash);
235
+ if (workdir === 1 && filepath.startsWith(EXTENSIONS_PREFIX) && headOid) {
236
+ // Unchanged at status capture: use HEAD, not a second live read.
237
+ extensionSnapshot.set(filepath, (await isogit.readBlob({ fs, dir, oid: headOid, filepath })).oid);
238
+ }
186
239
  }
187
240
  return { changes, unifiedDiff: patches.join("\n"), extensionSnapshot };
188
241
  }
@@ -191,25 +244,42 @@ export async function captureWorkspaceDiff() {
191
244
  * single-commit baseline so deleted/redacted memory content is not retained
192
245
  * in unreachable git objects (history is intentionally dropped).
193
246
  *
194
- * Divergence: `extensions/` files added or edited after `captured` (e.g. a
195
- * memory_add_note during the consolidator turn) stay out of the baseline, so
196
- * they appear as added in the next diff instead of never being consolidated.
247
+ * Stage captured extension blobs alongside live consolidator outputs. This
248
+ * preserves concurrent additions, edits AND deletions for the next diff.
197
249
  */
198
250
  export async function resetBaseline(captured) {
199
251
  try {
200
252
  const dir = memoryRoot();
201
253
  removeDiffArtifact(dir);
202
- fs.rmSync(path.join(dir, ".git"), { recursive: true, force: true });
203
- await isogit.init({ fs, dir });
204
- const skip = captured
205
- ? (filepath) => {
206
- if (!filepath.startsWith(EXTENSIONS_PREFIX))
207
- return false;
208
- const hash = workdirHash(dir, filepath);
209
- return hash !== null && captured.get(filepath) !== hash;
254
+ await ensureVersionedBaseline(dir);
255
+ const old = path.join(dir, ".git");
256
+ // Inside plugin-owned metadata: a crash while building leaves the old
257
+ // baseline valid, and the next attempt discards the unfinished staging dir.
258
+ const gitdir = path.join(old, "codex-next");
259
+ fs.rmSync(gitdir, { recursive: true, force: true });
260
+ await isogit.init({ fs, dir, gitdir });
261
+ for (const [filepath, , workdir] of await statusMatrix(dir, gitdir)) {
262
+ if (workdir !== 0 && !(captured && filepath.startsWith(EXTENSIONS_PREFIX))) {
263
+ await isogit.add({ fs, dir, gitdir, filepath });
210
264
  }
211
- : undefined;
212
- await commitBaseline(dir, skip);
265
+ }
266
+ for (const [filepath, oid] of captured ?? []) {
267
+ const { blob } = await isogit.readBlob({ fs, dir, oid });
268
+ await isogit.writeBlob({ fs, dir, gitdir, blob });
269
+ await isogit.updateIndex({ fs, dir, gitdir, filepath, oid, mode: 0o100644, add: true });
270
+ }
271
+ await isogit.commit({ fs, dir, gitdir, message: "memory baseline", author: AUTHOR });
272
+ // The version marker brackets promotion: interrupted promotions recover
273
+ // as an empty baseline instead of trusting a partial repository.
274
+ fs.unlinkSync(baselineVersionPath(dir));
275
+ for (const name of fs.readdirSync(old)) {
276
+ if (name !== "codex-next")
277
+ fs.rmSync(path.join(old, name), { recursive: true, force: true });
278
+ }
279
+ for (const name of fs.readdirSync(gitdir))
280
+ fs.renameSync(path.join(gitdir, name), path.join(old, name));
281
+ fs.rmdirSync(gitdir);
282
+ fs.writeFileSync(baselineVersionPath(dir), BASELINE_VERSION);
213
283
  return true;
214
284
  }
215
285
  catch (err) {
@@ -98,6 +98,11 @@ export declare function hostMcpStatus(client: PluginInput["client"] | null, sign
98
98
  error?: unknown;
99
99
  data?: unknown;
100
100
  } | null>;
101
+ /** Coalesce concurrent reads within one location; never reuse a stale MCP catalog. */
102
+ export declare function externalContextClassifier(status: (signal: AbortSignal) => Promise<{
103
+ data?: unknown;
104
+ error?: unknown;
105
+ } | null>, legacyPrefix?: boolean): (tool: string) => Promise<boolean>;
101
106
  /** session.messages — weakly typed parts; centralize the cast. */
102
107
  export declare function hostSessionMessages(client: PluginInput["client"] | null | undefined, sessionId: string, signal?: AbortSignal): Promise<{
103
108
  error?: unknown;
@@ -115,6 +115,30 @@ export async function hostMcpStatus(client, signal) {
115
115
  return null;
116
116
  return (await mcp.status({ signal }));
117
117
  }
118
+ /** Coalesce concurrent reads within one location; never reuse a stale MCP catalog. */
119
+ export function externalContextClassifier(status, legacyPrefix = false) {
120
+ let inFlight;
121
+ return async (tool) => {
122
+ if (tool === "websearch" || tool === "webfetch")
123
+ return true;
124
+ if (!inFlight) {
125
+ const controller = new AbortController();
126
+ inFlight = withHostTimeout(status(controller.signal), 1000, "mcp.status", controller)
127
+ .then((result) => {
128
+ if (result?.error || !result?.data || typeof result.data !== "object" || Array.isArray(result.data))
129
+ return [];
130
+ return Object.entries(result.data)
131
+ .filter(([, server]) => typeof server?.status === "string")
132
+ .map(([name]) => name.replace(/[^a-zA-Z0-9_-]/g, "_"));
133
+ })
134
+ .catch(() => [])
135
+ .finally(() => {
136
+ inFlight = undefined;
137
+ });
138
+ }
139
+ return (await inFlight).some((name) => tool.startsWith(`${name}_`) || (legacyPrefix && tool.startsWith(`mcp_${name}_`)));
140
+ };
141
+ }
118
142
  /** session.messages — weakly typed parts; centralize the cast. */
119
143
  export async function hostSessionMessages(client, sessionId, signal) {
120
144
  if (!client || typeof client.session?.messages !== "function") {
@@ -19,6 +19,7 @@ declare const _default: {
19
19
  id: string;
20
20
  setup: typeof setupV2;
21
21
  server(input: PluginInput, opts?: PluginOptions): Promise<{
22
+ dispose(): Promise<void>;
22
23
  tool: {
23
24
  memory_read: {
24
25
  description: string;
@@ -238,7 +239,6 @@ declare const _default: {
238
239
  properties: unknown;
239
240
  };
240
241
  }): Promise<void>;
241
- dispose(): Promise<void>;
242
242
  }>;
243
243
  };
244
244
  export default _default;
package/dist/src/index.js CHANGED
@@ -10,12 +10,14 @@ import { writeMemoryVersions } from "./memory-version.js";
10
10
  import { sessionMemoryVersion, withSessionMemoryVersion } from "./session-version.js";
11
11
  import { existingMemoryStores } from "./store.js";
12
12
  import { setPluginInput, cleanupOldSubSessions, isMemorySubSession, abortActiveSubSessions } from "./llm.js";
13
- import { pluginOptions, recordConfigWarning, clearConfigWarnings, resetPluginOptions, modelList } from "./options.js";
13
+ import { pluginOptions, recordConfigWarning, clearConfigWarnings, resetPluginOptions, modelList, reserveMemoryConfig, } from "./options.js";
14
14
  import { beginPluginShutdown, resetPluginLifecycle } from "./lifecycle.js";
15
- import { hostMcpStatus } from "./host-client.js";
15
+ import { externalContextClassifier, hostMcpStatus } from "./host-client.js";
16
16
  import { loadBundledAgentDefinitions, recordAgentConfig, resetAgentHealth } from "./agent-health.js";
17
17
  import path from "path";
18
- let pluginClient = null;
18
+ const hosts = [];
19
+ let hostConfig;
20
+ let draining;
19
21
  const backgroundTasks = new Set();
20
22
  function trackBackgroundTask(task) {
21
23
  // Hooks must remain non-blocking, but test teardown needs a way to wait until
@@ -32,9 +34,6 @@ export async function waitForBackgroundTasks() {
32
34
  await Promise.all([...backgroundTasks]);
33
35
  }
34
36
  }
35
- // Single-flight guard for mcp.status(); see mcpToolPrefixes below.
36
- let mcpStatusInFlight = null;
37
- const MCP_STATUS_TIMEOUT_MS = 1_000;
38
37
  // Deliberately uncached: openDb() is already a singleton, and caching a store
39
38
  // here would hold a stale handle across closeDb() (e.g. after memory_reset).
40
39
  function getStore() {
@@ -115,8 +114,10 @@ export function handleSessionDeleted(sessionId, store,
115
114
  // attempt could only fail; the row deletion above still happens, and the
116
115
  // enqueued job runs when generation is re-enabled (codex: delete only
117
116
  // enqueues; the pipeline itself is gated elsewhere).
118
- schedulePhase2 = () => { if (pluginOptions.generate_memories)
119
- trackBackgroundTask(triggerPhase2()); }) {
117
+ schedulePhase2 = () => {
118
+ if (pluginOptions.generate_memories)
119
+ trackBackgroundTask(triggerPhase2());
120
+ }) {
120
121
  const stores = store ? [store] : existingMemoryStores();
121
122
  let changed = false;
122
123
  for (const target of stores)
@@ -130,24 +131,17 @@ export default {
130
131
  // Added additively: V1 hosts keep calling server() exactly as before.
131
132
  setup: setupV2,
132
133
  async server(input, opts) {
133
- // A reload after dispose must be able to run the pipeline again.
134
- resetPluginLifecycle();
135
- setPluginInput(input);
136
- pluginClient = input.client;
137
- resetAgentHealth();
138
- mcpStatusInFlight = null;
139
- // Unconditional, like the caches above: a boot WITHOUT options must not
140
- // inherit the previous boot's warnings (opencode can host several
141
- // instances in one process — see the ARCHITECTURE known-gaps table).
142
- clearConfigWarnings();
143
- if (opts)
144
- applyPluginOptions(opts);
145
- else {
146
- const previousDb = dataRoot();
147
- resetPluginOptions();
148
- if (dataRoot() !== previousDb)
149
- closeDb();
134
+ if (draining)
135
+ await draining;
136
+ const config = reserveMemoryConfig(hostConfig, opts, input.directory);
137
+ if (!hostConfig) {
138
+ resetPluginLifecycle();
139
+ setPluginInput(input);
140
+ resetAgentHealth();
141
+ applyPluginOptions(opts ?? {});
142
+ hostConfig = config;
150
143
  }
144
+ hosts.push(input);
151
145
  // Finish bounded reseeding before hooks can see a surviving memory
152
146
  // sub-session after a plugin reload.
153
147
  await cleanupOldSubSessions();
@@ -161,7 +155,32 @@ export default {
161
155
  catch (err) {
162
156
  console.warn("[opencode-codex-memory] orphaned phase2 sweep failed:", err);
163
157
  }
164
- return buildHooks();
158
+ const hooks = buildHooks(input.client);
159
+ let released = false;
160
+ return {
161
+ ...hooks,
162
+ async dispose() {
163
+ if (released)
164
+ return;
165
+ released = true;
166
+ const idx = hosts.indexOf(input);
167
+ hosts.splice(idx, 1);
168
+ if (hosts.length) {
169
+ if (idx === 0) {
170
+ setPluginInput(hosts[0]);
171
+ }
172
+ return;
173
+ }
174
+ draining = hooks
175
+ .dispose()
176
+ .then(waitForBackgroundTasks)
177
+ .finally(() => {
178
+ hostConfig = undefined;
179
+ draining = undefined;
180
+ });
181
+ await draining;
182
+ },
183
+ };
165
184
  },
166
185
  };
167
186
  const KNOWN_OPTION_KEYS = new Set([
@@ -223,7 +242,13 @@ export function applyPluginOptions(opts, { modelFallback = false } = {}) {
223
242
  recordConfigWarning(`unknown/unsupported option '${key}' ignored`);
224
243
  }
225
244
  }
226
- for (const key of ["generate_memories", "use_memories", "dedicated_tools", "disable_on_external_context", "dual_write"]) {
245
+ for (const key of [
246
+ "generate_memories",
247
+ "use_memories",
248
+ "dedicated_tools",
249
+ "disable_on_external_context",
250
+ "dual_write",
251
+ ]) {
227
252
  if (!(key in raw))
228
253
  continue;
229
254
  if (typeof raw[key] === "boolean")
@@ -363,76 +388,6 @@ export function applyPluginOptions(opts, { modelFallback = false } = {}) {
363
388
  if (dataRoot() !== previousDb)
364
389
  closeDb();
365
390
  }
366
- /**
367
- * codex marks every MCP server as memory-polluting unconditionally
368
- * (codex-mcp server.rs pollutes_memory: true). opencode registers MCP tools
369
- * as "<server>_<tool>", so match tool names against the configured server
370
- * list. Query live status so runtime MCP changes cannot escape pollution
371
- * marking. Falls back to the web-tools-only check when status is unavailable.
372
- *
373
- * Concurrent tool calls coalesce on one in-flight status fetch. Deliberately
374
- * NOT cached with a TTL: a stale list would miss servers connected
375
- * mid-session and silently stop marking their calls as polluting, which is
376
- * the failure this classification exists to prevent. The accepted cost is one
377
- * status round trip per tool call — bounded to sessions that opt in with
378
- * disable_on_external_context (off by default), and paid only in
379
- * tool.execute.before.
380
- */
381
- async function mcpToolPrefixes() {
382
- if (!pluginClient)
383
- return null;
384
- if (!mcpStatusInFlight) {
385
- mcpStatusInFlight = (async () => {
386
- const controller = new AbortController();
387
- let timer;
388
- try {
389
- const res = await Promise.race([
390
- hostMcpStatus(pluginClient, controller.signal),
391
- new Promise((_, reject) => {
392
- timer = setTimeout(() => {
393
- controller.abort();
394
- reject(new Error(`mcp.status timed out after ${MCP_STATUS_TIMEOUT_MS}ms`));
395
- }, MCP_STATUS_TIMEOUT_MS);
396
- }),
397
- ]);
398
- if (!res || res.error)
399
- return null;
400
- const servers = res.data;
401
- if (!servers || typeof servers !== "object" || Array.isArray(servers))
402
- return null;
403
- const prefixes = [];
404
- for (const [server, status] of Object.entries(servers)) {
405
- if (!status || typeof status !== "object" || typeof status.status !== "string")
406
- continue;
407
- // Mirrors OpenCode's McpCatalog.sanitize when constructing tool names.
408
- prefixes.push(server.replace(/[^a-zA-Z0-9_-]/g, "_"));
409
- }
410
- return prefixes;
411
- }
412
- catch {
413
- // MCP status unavailable (older OpenCode); keep web-tools-only checks.
414
- return null;
415
- }
416
- finally {
417
- clearTimeout(timer);
418
- mcpStatusInFlight = null;
419
- }
420
- })();
421
- }
422
- return mcpStatusInFlight;
423
- }
424
- async function classifyExternalContextTool(toolName) {
425
- if (toolName === "websearch" || toolName === "webfetch")
426
- return true;
427
- const prefixes = await mcpToolPrefixes();
428
- if (prefixes === null)
429
- return null;
430
- for (const prefix of prefixes) {
431
- if (toolName.startsWith(`${prefix}_`))
432
- return true;
433
- }
434
- return false;
435
- }
436
391
  const TITLE_GENERATOR_MARKER = "You are a title generator. You output ONLY a thread title.";
437
392
  function isTitleGenerationPrompt(system) {
438
393
  return system.some((block) => block.includes(TITLE_GENERATOR_MARKER));
@@ -468,7 +423,8 @@ export function injectAgentDefinitions(config) {
468
423
  }
469
424
  recordAgentConfig(config, true, defs);
470
425
  }
471
- function buildHooks() {
426
+ function buildHooks(client) {
427
+ const classifyExternalContextTool = externalContextClassifier((signal) => hostMcpStatus(client, signal));
472
428
  const base = {
473
429
  async config(input) {
474
430
  try {
@@ -632,7 +588,8 @@ function buildHooks() {
632
588
  try {
633
589
  const ev = input.event;
634
590
  if (ev.type === "message.part.updated") {
635
- const part = ev.properties.part;
591
+ const part = ev.properties
592
+ .part;
636
593
  if (!part || part.type !== "text" || typeof part.text !== "string")
637
594
  return;
638
595
  if (part.sessionID && isMemorySubSession(part.sessionID))
package/dist/src/llm.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { PluginInput } from "@opencode-ai/plugin";
2
2
  import { type MemoryVersion } from "./options.js";
3
+ export declare const MAX_TRANSCRIPT_BYTES = 600000;
4
+ type Transcript = string | ((byteLimit: number) => string);
3
5
  export interface ExtractionResult {
4
6
  raw_memory: string;
5
7
  rollout_summary: string;
@@ -64,7 +66,7 @@ export interface ExtractOptions {
64
66
  * session.aborts the sub-session for host-side cleanup; extractor has no FS
65
67
  * write tools (D2) so a lingering server turn cannot dual-write the memory root.
66
68
  */
67
- export declare function extractViaSubagent(sessionId: string, transcript: string, opts?: ExtractOptions): Promise<ExtractionResult | null>;
69
+ export declare function extractViaSubagent(sessionId: string, transcript: Transcript, opts?: ExtractOptions): Promise<ExtractionResult | null>;
68
70
  /** `model`: "provider/model", or a comma-separated fallback chain tried in order. */
69
71
  export declare function consolidateViaSubagent(memoryRoot: string, diffFileName: string, model?: string, signal?: AbortSignal): Promise<void>;
70
72
  export declare function cleanupOldSubSessions(maxAgeMinutes?: number, timeoutMs?: number): Promise<void>;
@@ -83,3 +85,4 @@ export declare function validateExtraction(obj: Partial<ExtractionResult>, versi
83
85
  * is unavailable; the primary path reads AssistantMessage.structured directly.
84
86
  */
85
87
  export declare function parseExtraction(raw: string, version?: MemoryVersion): ExtractionResult | null;
88
+ export {};