opencode-codex-memory 0.10.1 → 0.10.3

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 (47) 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 +20 -5
  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 +4 -6
  10. package/dist/src/git-baseline.js +45 -68
  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 +4 -145
  14. package/dist/src/index.js +56 -99
  15. package/dist/src/llm.d.ts +4 -1
  16. package/dist/src/llm.js +41 -13
  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 +3 -3
  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 +9 -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 +20 -14
  40. package/dist/src/v2/tools.js +14 -14
  41. package/dist/src/v2/tui.js +14 -4
  42. package/dist/src/workspace.js +13 -4
  43. package/dist/tools/control.d.ts +4 -33
  44. package/dist/tools/control.js +29 -28
  45. package/dist/tools/memory.d.ts +5 -70
  46. package/dist/tools/memory.js +164 -89
  47. package/package.json +32 -20
@@ -24,14 +24,12 @@ import { MemoryStore, existingMemoryStores } from "../store.js";
24
24
  import { runMemoryPipeline, runMemoryConsolidation } from "../pipeline.js";
25
25
  import { sessionMemoryVersion, withSessionMemoryVersion } from "../session-version.js";
26
26
  import { setPluginInput, setSubSessionDirectory, cleanupOldSubSessions, isMemorySubSession, abortActiveSubSessions, } from "../llm.js";
27
- import { pluginOptions, clearConfigWarnings, resetPluginOptions } from "../options.js";
28
- import { dataRoot } from "../paths.js";
29
- import { closeDb } from "../db.js";
27
+ import { pluginOptions, reserveMemoryConfig } from "../options.js";
30
28
  import { beginPluginShutdown, isPluginShuttingDown, resetPluginLifecycle } from "../lifecycle.js";
31
- import { hostMcpStatus } from "../host-client.js";
29
+ import { externalContextClassifier } from "../host-client.js";
32
30
  import { resetAgentHealth } from "../agent-health.js";
33
31
  import { applyPluginOptions, handleSessionDeleted } from "../index.js";
34
- import { setV2Context, buildV1ClientShim, rememberV2Session, } from "./shim.js";
32
+ import { setV2Context, buildV1ClientShim, rememberV2Session, localMcpStatus } from "./shim.js";
35
33
  import { ensureV2Agents } from "./agents.js";
36
34
  import { buildV2Tools } from "./tools.js";
37
35
  import { performMemoryReset } from "../../tools/control.js";
@@ -41,7 +39,6 @@ import { readMemoryStatus } from "./status.js";
41
39
  import { recordInjection, resetInjectionStats } from "./injection.js";
42
40
  import { overlayV2CitationInstructions } from "./citation-overlay.js";
43
41
  import { estimateTokens } from "../token.js";
44
- let shimClient = null;
45
42
  const backgroundTasks = new Set();
46
43
  const statusListeners = new Set();
47
44
  /**
@@ -51,8 +48,8 @@ const statusListeners = new Set();
51
48
  * whichever location booted or disposed last.
52
49
  */
53
50
  const liveInstances = [];
54
- /** Panel toggles; survive later location setups until the last instance disposes. */
55
- const runtimeOverrides = {};
51
+ let activeConfig;
52
+ let draining;
56
53
  const eventLoops = new Set();
57
54
  function abortableSleep(ms, signal) {
58
55
  return new Promise((resolve) => {
@@ -101,13 +98,12 @@ export function resetV2ModuleStateForTest() {
101
98
  statusNotifyTimer = null;
102
99
  backgroundTasks.clear();
103
100
  seenTurnSessions.clear();
104
- mcpStatusInFlight = null;
105
101
  liveInstances.length = 0;
102
+ activeConfig = undefined;
103
+ draining = undefined;
106
104
  for (const loop of eventLoops)
107
105
  loop.abort();
108
106
  eventLoops.clear();
109
- for (const key of Object.keys(runtimeOverrides))
110
- delete runtimeOverrides[key];
111
107
  }
112
108
  function getStore() {
113
109
  return new MemoryStore();
@@ -179,61 +175,6 @@ export function markV2TurnSeen(sessionId) {
179
175
  lruSet(seenTurnSessions, sessionId, first ?? Date.now(), MAX_TRACKED_TURN_SESSIONS);
180
176
  return first === undefined;
181
177
  }
182
- let mcpStatusInFlight = null;
183
- const MCP_STATUS_TIMEOUT_MS = 1_000;
184
- async function mcpToolPrefixes() {
185
- if (!shimClient)
186
- return null;
187
- if (!mcpStatusInFlight) {
188
- mcpStatusInFlight = (async () => {
189
- const controller = new AbortController();
190
- let timer;
191
- try {
192
- const res = await Promise.race([
193
- hostMcpStatus(shimClient, controller.signal),
194
- new Promise((_, reject) => {
195
- timer = setTimeout(() => {
196
- controller.abort();
197
- reject(new Error(`mcp status timed out after ${MCP_STATUS_TIMEOUT_MS}ms`));
198
- }, MCP_STATUS_TIMEOUT_MS);
199
- }),
200
- ]);
201
- if (!res || res.error)
202
- return null;
203
- const servers = res.data;
204
- if (!servers || typeof servers !== "object" || Array.isArray(servers))
205
- return null;
206
- const prefixes = [];
207
- for (const [server, status] of Object.entries(servers)) {
208
- if (!status || typeof status !== "object" || typeof status.status !== "string")
209
- continue;
210
- prefixes.push(server.replace(/[^a-zA-Z0-9_-]/g, "_"));
211
- }
212
- return prefixes;
213
- }
214
- catch {
215
- return null;
216
- }
217
- finally {
218
- clearTimeout(timer);
219
- mcpStatusInFlight = null;
220
- }
221
- })();
222
- }
223
- return mcpStatusInFlight;
224
- }
225
- async function classifyExternalContextTool(toolName) {
226
- if (toolName === "websearch" || toolName === "webfetch")
227
- return true;
228
- const prefixes = await mcpToolPrefixes();
229
- if (prefixes === null)
230
- return null;
231
- for (const prefix of prefixes) {
232
- if (toolName.startsWith(`${prefix}_`) || toolName.startsWith(`mcp_${prefix}_`))
233
- return true;
234
- }
235
- return false;
236
- }
237
178
  function stampAndPump(sid, directory) {
238
179
  rememberV2Session(sid, directory ?? null);
239
180
  try {
@@ -273,30 +214,35 @@ async function consolidateNow() {
273
214
  }
274
215
  }
275
216
  export async function setup(ctx) {
276
- // Later locations join a running process: resetting the lifecycle would
277
- // abort the live consolidator, and resetting stats/health would erase state
278
- // the other locations still report.
279
- if (liveInstances.length === 0) {
217
+ if (draining)
218
+ await draining;
219
+ // Reserve synchronously: setups can overlap before either finishes registering.
220
+ const config = reserveMemoryConfig(activeConfig, ctx.options, ctx.location.directory);
221
+ if (!activeConfig) {
280
222
  resetPluginLifecycle();
281
223
  resetInjectionStats();
282
224
  resetAgentHealth();
225
+ applyPluginOptions(ctx.options ?? {}, { modelFallback: true });
226
+ activeConfig = config;
227
+ setV2Context(ctx);
228
+ setPluginInput({ client: buildV1ClientShim() });
229
+ setSubSessionDirectory(ctx.location.directory);
230
+ }
231
+ liveInstances.push(ctx);
232
+ try {
233
+ const detach = await attach(ctx);
234
+ return () => {
235
+ detach();
236
+ return releaseLocation(ctx);
237
+ };
283
238
  }
284
- setV2Context(ctx);
285
- shimClient = buildV1ClientShim();
286
- setPluginInput({ client: shimClient });
287
- setSubSessionDirectory(ctx.location.directory);
288
- mcpStatusInFlight = null;
289
- clearConfigWarnings();
290
- const rawOptions = ctx.options;
291
- if (rawOptions && Object.keys(rawOptions).length > 0)
292
- applyPluginOptions(rawOptions, { modelFallback: true });
293
- else {
294
- const previousDb = dataRoot();
295
- resetPluginOptions();
296
- if (dataRoot() !== previousDb)
297
- closeDb();
239
+ catch (error) {
240
+ await releaseLocation(ctx);
241
+ throw error;
298
242
  }
299
- Object.assign(pluginOptions, runtimeOverrides);
243
+ }
244
+ async function attach(ctx) {
245
+ const classifyExternalContextTool = externalContextClassifier((signal) => localMcpStatus(ctx, signal), true);
300
246
  await ensureV2Agents(ctx);
301
247
  const statusRegistration = await ctx.rpc.register(MemoryStatusRpc, {
302
248
  status: async (input) => {
@@ -342,7 +288,6 @@ export async function setup(ctx) {
342
288
  return { ok: false };
343
289
  }
344
290
  }
345
- runtimeOverrides[key] = value;
346
291
  invalidateCache();
347
292
  notifyStatusChanged();
348
293
  return { ok: true };
@@ -351,7 +296,7 @@ export async function setup(ctx) {
351
296
  const { sessionID, mode } = (input ?? {});
352
297
  if (typeof sessionID !== "string" || (mode !== "enabled" && mode !== "disabled"))
353
298
  return { ok: false };
354
- getStore().setMemoryMode(sessionID, mode);
299
+ getStore().setMemoryMode(sessionID, mode, mode === "enabled");
355
300
  notifyStatusChanged();
356
301
  return { ok: true };
357
302
  },
@@ -374,9 +319,29 @@ export async function setup(ctx) {
374
319
  console.warn("[opencode-codex-memory] status notification failed:", err);
375
320
  });
376
321
  };
322
+ // Only offer model-initiated restore when the host can require a one-time
323
+ // permission decision. A general tool allow rule isn't consent to restore.
324
+ const permission = ctx.permission;
325
+ const restoreAction = "memory_restore_learning";
326
+ const canAsk = !!permission?.assert && !!permission.hook;
327
+ if (canAsk)
328
+ await permission.hook("evaluate", (event) => {
329
+ if (event.action === restoreAction && event.effect === "allow")
330
+ event.effect = "ask";
331
+ });
377
332
  await ctx.tool.transform((editor) => {
378
333
  guardMemorySearchTools(editor, (sessionID) => ctx.session.get({ sessionID }));
379
- for (const t of buildV2Tools())
334
+ for (const t of buildV2Tools(canAsk
335
+ ? (call, req) => permission.assert({
336
+ sessionID: call.sessionID,
337
+ agent: call.agent,
338
+ action: restoreAction,
339
+ resources: req.patterns,
340
+ metadata: req.metadata,
341
+ save: [],
342
+ source: { type: "tool", messageID: call.messageID, id: call.id },
343
+ })
344
+ : undefined))
380
345
  editor.add(t);
381
346
  });
382
347
  await ctx.session.hook("prompt", (ev) => {
@@ -480,7 +445,12 @@ export async function setup(ctx) {
480
445
  void (async () => {
481
446
  while (!eventAbort.signal.aborted && !isPluginShuttingDown()) {
482
447
  try {
483
- for await (const raw of ctx.event.subscribe({ signal: eventAbort.signal })) {
448
+ // Older hosts ignore the type filter and deliver the full stream.
449
+ const subscription = {
450
+ signal: eventAbort.signal,
451
+ types: ["session.text.ended", "session.execution.succeeded", "session.deleted"],
452
+ };
453
+ for await (const raw of ctx.event.subscribe(subscription)) {
484
454
  const e = raw;
485
455
  try {
486
456
  const data = e.data ?? e;
@@ -534,33 +504,35 @@ export async function setup(ctx) {
534
504
  }
535
505
  await abortableSleep(5000, eventAbort.signal);
536
506
  }
537
- })().catch((err) => console.error("[opencode-codex-memory] v2 event loop error:", err))
507
+ })()
508
+ .catch((err) => console.error("[opencode-codex-memory] v2 event loop error:", err))
538
509
  .finally(() => eventLoops.delete(eventAbort));
539
510
  eventLoops.add(eventAbort);
540
- liveInstances.push(ctx);
541
511
  return () => {
542
512
  statusListeners.delete(publishStatus);
543
513
  eventAbort.abort();
544
- const index = liveInstances.indexOf(ctx);
545
- if (index >= 0)
546
- liveInstances.splice(index, 1);
547
- const survivor = liveInstances.at(-1);
548
- if (survivor) {
549
- // Only the newest location owns the shim; re-point when it leaves.
550
- if (index === liveInstances.length) {
551
- setV2Context(survivor);
552
- setSubSessionDirectory(survivor.location.directory);
553
- }
554
- return;
514
+ };
515
+ }
516
+ function releaseLocation(ctx) {
517
+ const index = liveInstances.indexOf(ctx);
518
+ if (index < 0)
519
+ return;
520
+ liveInstances.splice(index, 1);
521
+ const survivor = liveInstances[0];
522
+ if (survivor) {
523
+ if (index === 0) {
524
+ setV2Context(survivor);
525
+ setSubSessionDirectory(survivor.location.directory);
555
526
  }
556
- for (const key of Object.keys(runtimeOverrides))
557
- delete runtimeOverrides[key];
558
- beginPluginShutdown();
527
+ return;
528
+ }
529
+ beginPluginShutdown();
530
+ draining = Promise.allSettled([abortActiveSubSessions(), waitForV2BackgroundTasks()]).then(() => {
559
531
  setSubSessionDirectory();
560
532
  setV2Context(null);
561
- void abortActiveSubSessions().catch((err) => {
562
- console.warn("[opencode-codex-memory] v2 dispose abort of sub-sessions failed:", err);
563
- });
533
+ activeConfig = undefined;
534
+ draining = undefined;
564
535
  invalidateCache();
565
- };
536
+ });
537
+ return draining;
566
538
  }
@@ -11,7 +11,7 @@ export function guardMemorySearchTools(editor, getSession) {
11
11
  tool.execute = async (input, context) => {
12
12
  if (context.agent !== MEMORIZE_AGENT_ID)
13
13
  return execute(input, context);
14
- const response = await getSession(context.sessionID);
14
+ const response = (await getSession(context.sessionID));
15
15
  const session = response?.data ?? response;
16
16
  // Helper permissions persist across plugin reloads and select one writer
17
17
  // even during dual-write. Never fall back to the active project or version.
@@ -226,6 +226,11 @@ export async function discoverOwnService(dependencies, timeoutMs = SERVICE_REQUE
226
226
  }
227
227
  console.warn(`[opencode-codex-memory] registered OpenCode service PID ${String(health.pid)} is a different local process than plugin host PID ${process.pid}; using it for global session list`);
228
228
  }
229
+ // The bundled 2.0.5 client posts to /api/experimental/generate. 2.0.3
230
+ // serves /api/generate instead. Use that host's native context generator
231
+ // rather than trying a mismatched route or replaying a generation.
232
+ if (health.version === "2.0.3" && client.generate)
233
+ return { endpoint, client: { ...client, generate: undefined }, health };
229
234
  return { endpoint, client, health };
230
235
  }
231
236
  /** Resolve the registered client once per live service; never start a service. */
@@ -58,6 +58,9 @@ export declare function adaptV2Messages(msgs: unknown): Array<{
58
58
  export declare function adaptProviderCatalog(v2: unknown): unknown;
59
59
  /** V2 mcp.list → V1 mcp.status map shape. */
60
60
  export declare function adaptMcpStatus(v2: unknown): unknown;
61
+ export declare function localMcpStatus(owner: V2Context, signal?: AbortSignal): Promise<{
62
+ data: unknown;
63
+ }>;
61
64
  /** Build the V1-shaped client. Passed to setPluginInput() by V2 setup(). */
62
65
  export declare function buildV1ClientShim(): unknown;
63
66
  export {};