opencode-codex-memory 0.8.4 → 0.9.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.
@@ -34,6 +34,7 @@ import { applyPluginOptions, handleSessionDeleted } from "../index.js";
34
34
  import { setV2Context, buildV1ClientShim, rememberV2Session, } from "./shim.js";
35
35
  import { ensureV2Agents } from "./agents.js";
36
36
  import { buildV2Tools } from "./tools.js";
37
+ import { performMemoryReset } from "../../tools/control.js";
37
38
  import { guardMemorySearchTools } from "./search-sandbox.js";
38
39
  import { MemoryStatusRpc } from "./status-rpc.js";
39
40
  import { readMemoryStatus } from "./status.js";
@@ -43,9 +44,41 @@ import { estimateTokens } from "../token.js";
43
44
  let shimClient = null;
44
45
  const backgroundTasks = new Set();
45
46
  const statusListeners = new Set();
47
+ /**
48
+ * The V2 host runs one plugin instance per location in the same process and
49
+ * evicts idle locations independently. Process-wide state (lifecycle, shim
50
+ * context, panel toggles) belongs to the set of live instances, not to
51
+ * whichever location booted or disposed last.
52
+ */
53
+ const liveInstances = [];
54
+ /** Panel toggles; survive later location setups until the last instance disposes. */
55
+ const runtimeOverrides = {};
56
+ const eventLoops = new Set();
57
+ function abortableSleep(ms, signal) {
58
+ return new Promise((resolve) => {
59
+ if (signal.aborted)
60
+ return resolve();
61
+ const timer = setTimeout(done, ms);
62
+ function done() {
63
+ clearTimeout(timer);
64
+ signal.removeEventListener("abort", done);
65
+ resolve();
66
+ }
67
+ signal.addEventListener("abort", done, { once: true });
68
+ });
69
+ }
70
+ // Context hooks fire on every LLM step; each emit makes every open panel
71
+ // re-read status. Coalesce bursts.
72
+ let statusNotifyTimer = null;
46
73
  function notifyStatusChanged() {
47
- for (const notify of statusListeners)
48
- notify();
74
+ if (statusNotifyTimer)
75
+ return;
76
+ statusNotifyTimer = setTimeout(() => {
77
+ statusNotifyTimer = null;
78
+ for (const notify of statusListeners)
79
+ notify();
80
+ }, 250);
81
+ statusNotifyTimer.unref?.();
49
82
  }
50
83
  function trackBackgroundTask(task) {
51
84
  const tracked = task.catch((err) => {
@@ -63,9 +96,18 @@ export async function waitForV2BackgroundTasks() {
63
96
  /** Test seam: reset module state between tests. */
64
97
  export function resetV2ModuleStateForTest() {
65
98
  statusListeners.clear();
99
+ if (statusNotifyTimer)
100
+ clearTimeout(statusNotifyTimer);
101
+ statusNotifyTimer = null;
66
102
  backgroundTasks.clear();
67
103
  seenTurnSessions.clear();
68
104
  mcpStatusInFlight = null;
105
+ liveInstances.length = 0;
106
+ for (const loop of eventLoops)
107
+ loop.abort();
108
+ eventLoops.clear();
109
+ for (const key of Object.keys(runtimeOverrides))
110
+ delete runtimeOverrides[key];
69
111
  }
70
112
  function getStore() {
71
113
  return new MemoryStore();
@@ -82,6 +124,7 @@ function stripAndReconcileCitations(sessionId, messages) {
82
124
  // Model-bound LLM.Message uses role; persisted/legacy rows use type.
83
125
  if ((msg?.role ?? msg?.type) !== "assistant" || !Array.isArray(msg.content))
84
126
  continue;
127
+ let emptied = false;
85
128
  for (const part of msg.content) {
86
129
  if (part?.type !== "text" || typeof part.text !== "string")
87
130
  continue;
@@ -97,6 +140,15 @@ function stripAndReconcileCitations(sessionId, messages) {
97
140
  console.error("[opencode-codex-memory] citation recording failed:", e);
98
141
  }
99
142
  part.text = stripCitations(part.text);
143
+ if (part.text === "")
144
+ emptied = true;
145
+ }
146
+ // The host drops empty text parts before this hook; some providers reject them.
147
+ if (emptied && msg.content.some((part) => part?.type !== "text" || part.text !== "")) {
148
+ for (let i = msg.content.length - 1; i >= 0; i--) {
149
+ if (msg.content[i]?.type === "text" && msg.content[i].text === "")
150
+ msg.content.splice(i, 1);
151
+ }
100
152
  }
101
153
  }
102
154
  }
@@ -221,13 +273,18 @@ async function consolidateNow() {
221
273
  }
222
274
  }
223
275
  export async function setup(ctx) {
224
- resetPluginLifecycle();
225
- resetInjectionStats();
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) {
280
+ resetPluginLifecycle();
281
+ resetInjectionStats();
282
+ resetAgentHealth();
283
+ }
226
284
  setV2Context(ctx);
227
285
  shimClient = buildV1ClientShim();
228
286
  setPluginInput({ client: shimClient });
229
287
  setSubSessionDirectory(ctx.location.directory);
230
- resetAgentHealth();
231
288
  mcpStatusInFlight = null;
232
289
  clearConfigWarnings();
233
290
  const rawOptions = ctx.options;
@@ -239,6 +296,7 @@ export async function setup(ctx) {
239
296
  if (dataRoot() !== previousDb)
240
297
  closeDb();
241
298
  }
299
+ Object.assign(pluginOptions, runtimeOverrides);
242
300
  await ensureV2Agents(ctx);
243
301
  const statusRegistration = await ctx.rpc.register(MemoryStatusRpc, {
244
302
  status: async (input) => {
@@ -250,10 +308,12 @@ export async function setup(ctx) {
250
308
  const { key, value } = (input ?? {});
251
309
  if ((key !== "use_memories" && key !== "generate_memories") || typeof value !== "boolean")
252
310
  return { ok: false };
311
+ const instances = liveInstances.includes(ctx) ? [...liveInstances] : [ctx];
253
312
  if (key === "generate_memories" && value && !pluginOptions.generate_memories) {
254
313
  pluginOptions.generate_memories = true;
255
314
  try {
256
- await ensureV2Agents(ctx);
315
+ for (const instance of instances)
316
+ await ensureV2Agents(instance);
257
317
  }
258
318
  catch (error) {
259
319
  pluginOptions.generate_memories = false;
@@ -264,17 +324,25 @@ export async function setup(ctx) {
264
324
  const previous = pluginOptions[key];
265
325
  pluginOptions[key] = value;
266
326
  if (key === "use_memories" && value !== previous) {
327
+ // Transforms capture options but the host only replays them after an
328
+ // explicit registry invalidation. Affect future tool snapshots now,
329
+ // in every location.
330
+ const reloaded = [];
267
331
  try {
268
- // Transforms capture options but the host only replays them after an
269
- // explicit registry invalidation. Affect future tool snapshots now.
270
- await ctx.tool.reload();
332
+ for (const instance of instances) {
333
+ await instance.tool.reload();
334
+ reloaded.push(instance);
335
+ }
271
336
  }
272
337
  catch (error) {
273
338
  pluginOptions[key] = previous;
339
+ for (const instance of reloaded)
340
+ await instance.tool.reload().catch(() => { });
274
341
  console.error("[opencode-codex-memory] failed to reload V2 memory tools:", error);
275
342
  return { ok: false };
276
343
  }
277
344
  }
345
+ runtimeOverrides[key] = value;
278
346
  invalidateCache();
279
347
  notifyStatusChanged();
280
348
  return { ok: true };
@@ -293,6 +361,13 @@ export async function setup(ctx) {
293
361
  trackBackgroundTask(run.then(() => { }));
294
362
  return { status: "started" };
295
363
  },
364
+ resetMemory: async (input) => {
365
+ if (input?.confirm !== true)
366
+ return { ok: false, message: "Reset not confirmed." };
367
+ const result = performMemoryReset();
368
+ notifyStatusChanged();
369
+ return result;
370
+ },
296
371
  });
297
372
  const publishStatus = () => {
298
373
  void statusRegistration.events.emit("changed", {}).catch((err) => {
@@ -366,6 +441,15 @@ export async function setup(ctx) {
366
441
  console.error("[opencode-codex-memory] v2 generate hook error:", err);
367
442
  }
368
443
  });
444
+ // Title requests replay history too; citation markup is noise there.
445
+ await ctx.session.hook("title", (ev) => {
446
+ try {
447
+ handleModelBoundSession(ev, false);
448
+ }
449
+ catch (err) {
450
+ console.error("[opencode-codex-memory] v2 title hook error:", err);
451
+ }
452
+ });
369
453
  await ctx.tool.hook("execute.before", async (ev) => {
370
454
  try {
371
455
  if (!pluginOptions.disable_on_external_context || !ev?.sessionID)
@@ -438,19 +522,39 @@ export async function setup(ctx) {
438
522
  console.error("[opencode-codex-memory] v2 event handling error:", err);
439
523
  }
440
524
  }
441
- break;
525
+ // A stream that ends without dispose (host restart of the bus) must
526
+ // not silently stop phase-1 pumps and citation accounting.
527
+ if (eventAbort.signal.aborted || isPluginShuttingDown())
528
+ break;
442
529
  }
443
530
  catch (err) {
444
531
  if (eventAbort.signal.aborted || isPluginShuttingDown())
445
532
  break;
446
533
  console.error("[opencode-codex-memory] v2 event subscription error:", err);
447
- await new Promise((r) => setTimeout(r, 5000));
448
534
  }
535
+ await abortableSleep(5000, eventAbort.signal);
449
536
  }
450
- })().catch((err) => console.error("[opencode-codex-memory] v2 event loop error:", err));
537
+ })().catch((err) => console.error("[opencode-codex-memory] v2 event loop error:", err))
538
+ .finally(() => eventLoops.delete(eventAbort));
539
+ eventLoops.add(eventAbort);
540
+ liveInstances.push(ctx);
451
541
  return () => {
452
542
  statusListeners.delete(publishStatus);
453
543
  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;
555
+ }
556
+ for (const key of Object.keys(runtimeOverrides))
557
+ delete runtimeOverrides[key];
454
558
  beginPluginShutdown();
455
559
  setSubSessionDirectory();
456
560
  setV2Context(null);
@@ -198,7 +198,8 @@ async function probeEndpoint(deps, endpoint, client, signal) {
198
198
  export function isLoopbackEndpointUrl(url) {
199
199
  try {
200
200
  const hostname = new URL(url).hostname;
201
- return hostname === "127.0.0.1" || hostname === "localhost" || hostname === "::1";
201
+ // WHATWG URL keeps IPv6 brackets in hostname.
202
+ return hostname === "127.0.0.1" || hostname === "localhost" || hostname === "[::1]" || hostname === "::1";
202
203
  }
203
204
  catch {
204
205
  return false;
@@ -295,11 +295,17 @@ async function loadV2Messages(sessionID, context, signal) {
295
295
  cursor = next;
296
296
  }
297
297
  }
298
+ // session.context is the model context from the latest completed compaction
299
+ // on, not the full transcript: the originals before it are gone here, so
300
+ // the compaction summary is the only record of them. (message.list above
301
+ // keeps the originals; there the summary would duplicate them.)
298
302
  const raw = await (context ?? ctx()).session.context({ sessionID });
299
303
  const rows = responseRows(raw);
300
304
  if (!rows)
301
305
  throw new Error("session context returned an invalid message list");
302
- return rows;
306
+ return rows.map((m) => m?.type === "compaction" && typeof m.summary === "string" && typeof m.text !== "string"
307
+ ? { ...m, text: `[Summary of earlier conversation]\n${m.summary}` }
308
+ : m);
303
309
  }
304
310
  function completedPromptResponse(rows, promptID) {
305
311
  const boundary = typeof promptID === "string" ? rows.findIndex((m) => m?.id === promptID && m.type === "user") : -1;
@@ -342,6 +348,21 @@ function adaptV2SessionRow(row) {
342
348
  // ---------------------------------------------------------------------------
343
349
  // The façade: V1-shaped client over the V2 context
344
350
  // ---------------------------------------------------------------------------
351
+ /** Race a promise against a (possibly long-lived) signal without leaking listeners. */
352
+ function raceAbort(promise, signal) {
353
+ let onAbort;
354
+ const aborted = new Promise((_, reject) => {
355
+ onAbort = () => reject(new Error("sub-agent prompt cancelled"));
356
+ if (signal.aborted)
357
+ onAbort();
358
+ else
359
+ signal.addEventListener("abort", onAbort, { once: true });
360
+ });
361
+ return Promise.race([promise, aborted]).finally(() => {
362
+ if (onAbort)
363
+ signal.removeEventListener("abort", onAbort);
364
+ });
365
+ }
345
366
  async function v2promptWithWait(sessionID, body, signal) {
346
367
  const c = ctx();
347
368
  const text = body.parts.map((p) => p.text ?? "").join("\n");
@@ -381,14 +402,7 @@ async function v2promptWithWait(sessionID, body, signal) {
381
402
  }
382
403
  // ctx.generate.text ignores request-option signals. Race AbortSignal.
383
404
  const genP = c.generate.text(payload);
384
- const gen = signal
385
- ? await Promise.race([
386
- genP,
387
- new Promise((_, reject) => {
388
- signal.addEventListener("abort", () => reject(new Error("sub-agent prompt cancelled")), { once: true });
389
- }),
390
- ])
391
- : await genP;
405
+ const gen = signal ? await raceAbort(genP, signal) : await genP;
392
406
  const outText = typeof gen?.text === "string" ? gen.text : JSON.stringify(gen);
393
407
  return { data: { parts: [{ type: "text", text: outText }] } };
394
408
  }
@@ -416,12 +430,7 @@ async function v2promptWithWait(sessionID, body, signal) {
416
430
  await waitP.catch(() => { });
417
431
  throw new Error("sub-agent prompt cancelled");
418
432
  }
419
- await Promise.race([
420
- waitP,
421
- new Promise((_, reject) => {
422
- signal.addEventListener("abort", () => reject(new Error("sub-agent prompt cancelled")), { once: true });
423
- }),
424
- ]).catch(async (e) => {
433
+ await raceAbort(waitP, signal).catch(async (e) => {
425
434
  await c.session.interrupt({ sessionID }).catch(() => { });
426
435
  await waitP.catch(() => { });
427
436
  throw e;
@@ -538,7 +547,13 @@ export function buildV1ClientShim() {
538
547
  return await v2promptWithWait(opts.path.id, opts.body, opts.signal);
539
548
  }
540
549
  catch (e) {
541
- return { error: e instanceof Error ? { message: e.message } : e };
550
+ // Keep the HTTP status: an undeclared 429 surfaces as ClientError
551
+ // "UnexpectedStatus" whose message alone misses the capacity breaker.
552
+ if (!(e instanceof Error))
553
+ return { error: e };
554
+ const status = e.status
555
+ ?? e.cause?.status;
556
+ return { error: { message: e.message, ...(typeof status === "number" ? { statusCode: status } : {}) } };
542
557
  }
543
558
  },
544
559
  messages: async (opts) => {
@@ -558,61 +573,52 @@ export function buildV1ClientShim() {
558
573
  markReleased(opts.path.id);
559
574
  return {};
560
575
  }
561
- let shutdownError;
562
- try {
563
- const client = await serviceOrThrow();
564
- if (typeof client.session.remove !== "function")
565
- throw new Error("registered service does not support session.remove");
566
- const result = await serviceRequest(client, () => client.session.remove({ sessionID: opts.path.id }, opts.signal ? { signal: opts.signal } : undefined));
567
- if (result?.error)
568
- throw result.error;
569
- if (await sessionGoneOnService(client, opts.path.id)) {
570
- markReleased(opts.path.id);
571
- return {};
572
- }
573
- throw new Error("session still exists after remove");
574
- }
575
- catch (error) {
576
- shutdownError = error;
577
- }
576
+ const id = opts.path.id;
577
+ // Interrupt where the helper runs first. With a loopback PID mismatch the
578
+ // service is another process: removing the row there alone would leave
579
+ // this process's consolidator editing after the lease is released.
580
+ let interruptError;
578
581
  try {
579
582
  const session = ctx().session;
580
- const interrupt = await session.interrupt({ sessionID: opts.path.id });
583
+ const interrupt = await session.interrupt({ sessionID: id });
581
584
  if (interrupt?.error)
582
585
  throw interrupt.error;
583
586
  if (typeof session.wait === "function")
584
- await session.wait({ sessionID: opts.path.id });
587
+ await session.wait({ sessionID: id });
585
588
  }
586
- catch (interruptError) {
587
- return { error: shutdownError ?? interruptError };
589
+ catch (error) {
590
+ interruptError = error ?? new Error("session interrupt failed");
588
591
  }
592
+ let client = null;
593
+ let removeError;
589
594
  try {
590
- const client = await ownServiceClient();
591
- if (client?.session?.get) {
592
- const info = await serviceRequest(client, () => client.session.get({ sessionID: opts.path.id }));
593
- if (info?.error && isNotFoundError(info.error)) {
594
- markReleased(opts.path.id);
595
- return {};
596
- }
597
- const data = und(info);
598
- if (data && typeof data === "object") {
599
- return { error: shutdownError ?? new Error("session still exists after interrupt") };
600
- }
601
- return { error: shutdownError ?? new Error("session still exists after interrupt") };
595
+ client = await ownServiceClient();
596
+ if (client) {
597
+ if (typeof client.session.remove !== "function")
598
+ throw new Error("registered service does not support session.remove");
599
+ const service = client;
600
+ const result = await serviceRequest(service, () => service.session.remove({ sessionID: id }, opts.signal ? { signal: opts.signal } : undefined));
601
+ if (result?.error)
602
+ throw result.error;
602
603
  }
603
- // Isolated serve: no session.remove on plugin ctx. interrupt+wait already
604
- // finished, so the helper is idle. Holding the phase-2 lease until it
605
- // expires would block consolidation for an hour.
606
- markReleased(opts.path.id);
607
- return {};
608
604
  }
609
- catch (e) {
610
- if (isNotFoundError(e)) {
611
- markReleased(opts.path.id);
605
+ catch (error) {
606
+ removeError = error;
607
+ }
608
+ if (client && typeof client.session.get === "function") {
609
+ if (await sessionGoneOnService(client, id)) {
610
+ markReleased(id);
612
611
  return {};
613
612
  }
614
- return { error: shutdownError ?? e };
613
+ return { error: removeError ?? interruptError ?? new Error("session still exists after remove") };
615
614
  }
615
+ if (interruptError !== undefined)
616
+ return { error: removeError ?? interruptError };
617
+ // Isolated serve: no session.remove on plugin ctx. interrupt+wait already
618
+ // finished, so the helper is idle. Holding the phase-2 lease until it
619
+ // expires would block consolidation for an hour.
620
+ markReleased(id);
621
+ return {};
616
622
  },
617
623
  get: async (opts) => {
618
624
  try {
@@ -643,19 +649,20 @@ export function buildV1ClientShim() {
643
649
  abort: async (opts) => {
644
650
  if (opts.path.id === EXTRACT_STUB_SESSION_ID)
645
651
  return {};
652
+ // Local first: the helper runs in this process (see delete above).
646
653
  try {
647
- const client = await serviceOrThrow();
648
- if (typeof client.session.interrupt !== "function")
649
- throw new Error("registered service does not support session.interrupt");
650
- const result = await serviceRequest(client, () => client.session.interrupt({ sessionID: opts.path.id }));
654
+ const result = await ctx().session.interrupt({ sessionID: opts.path.id });
651
655
  if (!result?.error)
652
656
  return {};
653
657
  }
654
658
  catch {
655
- // Fall through to the context-local interrupt below.
659
+ // Fall through to the registered service.
656
660
  }
657
661
  try {
658
- await ctx().session.interrupt({ sessionID: opts.path.id });
662
+ const client = await ownServiceClient();
663
+ if (client && typeof client.session.interrupt === "function") {
664
+ await serviceRequest(client, () => client.session.interrupt({ sessionID: opts.path.id }));
665
+ }
659
666
  }
660
667
  catch {
661
668
  // Best-effort, mirrors V1.
@@ -262,6 +262,32 @@ export declare const MemoryStatusRpc: {
262
262
  readonly additionalProperties: false;
263
263
  };
264
264
  };
265
+ /** Same wipe as the V1 memory_reset tool; the panel's confirm step is the approval. */
266
+ readonly resetMemory: {
267
+ readonly input: {
268
+ readonly type: "object";
269
+ readonly properties: {
270
+ readonly confirm: {
271
+ readonly type: "boolean";
272
+ };
273
+ };
274
+ readonly required: readonly ["confirm"];
275
+ readonly additionalProperties: false;
276
+ };
277
+ readonly output: {
278
+ readonly type: "object";
279
+ readonly properties: {
280
+ readonly ok: {
281
+ readonly type: "boolean";
282
+ };
283
+ readonly message: {
284
+ readonly type: "string";
285
+ };
286
+ };
287
+ readonly required: readonly ["ok", "message"];
288
+ readonly additionalProperties: false;
289
+ };
290
+ };
265
291
  };
266
292
  readonly events: {
267
293
  readonly changed: {
@@ -133,6 +133,21 @@ export const MemoryStatusRpc = {
133
133
  additionalProperties: false,
134
134
  },
135
135
  },
136
+ /** Same wipe as the V1 memory_reset tool; the panel's confirm step is the approval. */
137
+ resetMemory: {
138
+ input: {
139
+ type: "object",
140
+ properties: { confirm: { type: "boolean" } },
141
+ required: ["confirm"],
142
+ additionalProperties: false,
143
+ },
144
+ output: {
145
+ type: "object",
146
+ properties: { ok: { type: "boolean" }, message: { type: "string" } },
147
+ required: ["ok", "message"],
148
+ additionalProperties: false,
149
+ },
150
+ },
136
151
  },
137
152
  events: {
138
153
  changed: { schema: { type: "object", properties: {}, additionalProperties: false } },
@@ -27,7 +27,8 @@ interface V2ToolDefinition {
27
27
  /**
28
28
  * Same gating as the V1 entry: the read/search/list/add-note tools require
29
29
  * BOTH use_memories and dedicated_tools (codex MemoriesExtension); the
30
- * control tools are always available.
30
+ * control tools are always available. memory_reset needs user approval,
31
+ * which V2 plugin tools cannot request: reset lives in the memory panel.
31
32
  */
32
33
  export declare function buildV2Tools(): V2ToolDefinition[];
33
34
  export {};
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import { z } from "zod";
13
13
  import { memory_read, memory_search, memory_list, memory_add_note } from "../../tools/memory.js";
14
- import { memory_reset, memory_inspect, memory_mode } from "../../tools/control.js";
14
+ import { memory_inspect, memory_mode } from "../../tools/control.js";
15
15
  import { pluginOptions } from "../options.js";
16
16
  import { getV2DiscoveryStatus } from "./shim.js";
17
17
  function adaptTool(name, v1) {
@@ -28,7 +28,10 @@ function adaptTool(name, v1) {
28
28
  worktree: "",
29
29
  abort: tctx.abort instanceof AbortSignal ? tctx.abort : new AbortController().signal,
30
30
  metadata: () => { },
31
- ask: async () => { },
31
+ // OpenCode 2 gives plugin tools no approval request; fail closed.
32
+ ask: async () => {
33
+ throw new Error("User approval is unavailable to plugin tools on OpenCode 2. Use /memory-inspect → Controls instead.");
34
+ },
32
35
  };
33
36
  const res = await v1.execute(input, v1ctx);
34
37
  if (typeof res === "string")
@@ -54,15 +57,15 @@ const ALL_MEMORY_TOOLS = [
54
57
  ["memory_search", memory_search],
55
58
  ["memory_list", memory_list],
56
59
  ["memory_add_note", memory_add_note],
57
- ["memory_reset", memory_reset],
58
60
  ["memory_inspect", memory_inspect],
59
61
  ["memory_mode", memory_mode],
60
62
  ];
61
- const CONTROL_ONLY = new Set(["memory_reset", "memory_inspect", "memory_mode"]);
63
+ const CONTROL_ONLY = new Set(["memory_inspect", "memory_mode"]);
62
64
  /**
63
65
  * Same gating as the V1 entry: the read/search/list/add-note tools require
64
66
  * BOTH use_memories and dedicated_tools (codex MemoriesExtension); the
65
- * control tools are always available.
67
+ * control tools are always available. memory_reset needs user approval,
68
+ * which V2 plugin tools cannot request: reset lives in the memory panel.
66
69
  */
67
70
  export function buildV2Tools() {
68
71
  const full = pluginOptions.use_memories && pluginOptions.dedicated_tools;
@@ -143,6 +143,20 @@ var MemoryStatusRpc = {
143
143
  required: ["status"],
144
144
  additionalProperties: false
145
145
  }
146
+ },
147
+ resetMemory: {
148
+ input: {
149
+ type: "object",
150
+ properties: { confirm: { type: "boolean" } },
151
+ required: ["confirm"],
152
+ additionalProperties: false
153
+ },
154
+ output: {
155
+ type: "object",
156
+ properties: { ok: { type: "boolean" }, message: { type: "string" } },
157
+ required: ["ok", "message"],
158
+ additionalProperties: false
159
+ }
146
160
  }
147
161
  },
148
162
  events: {
@@ -449,6 +463,7 @@ function MemoryDialog(context, sessionID) {
449
463
  const [cursor, setCursor] = createSignal(0);
450
464
  const [notice, setNotice] = createSignal(null);
451
465
  const [busy, setBusy] = createSignal(null);
466
+ const [armed, setArmed] = createSignal(false);
452
467
  let scroll;
453
468
  const call = async (id, method, input, done) => {
454
469
  if (busy() || unavailable())
@@ -464,7 +479,7 @@ function MemoryDialog(context, sessionID) {
464
479
  return;
465
480
  const reply = result;
466
481
  if (method === "consolidateNow" ? reply?.status !== "started" : reply?.ok !== true) {
467
- throw new Error("The server did not apply the request. Refresh and try again.");
482
+ throw new Error(reply?.message ?? "The server did not apply the request. Refresh and try again.");
468
483
  }
469
484
  setNotice({
470
485
  message: done,
@@ -531,6 +546,26 @@ function MemoryDialog(context, sessionID) {
531
546
  enabled: s.generateMemories && !running && s.activity !== "stopping",
532
547
  run: () => void call("now", "consolidateNow", {}, "Background run requested. See Overview for progress.")
533
548
  });
549
+ list.push({
550
+ id: "reset",
551
+ title: armed() ? "Reset memory \u2014 press again to confirm" : "Reset memory",
552
+ hint: armed() ? "Erases all learned memories, notes, and history. This cannot be undone. Moving the selection cancels." : running ? "Wait for the running extraction or consolidation to finish." : "Erase all learned memories and notes for every project. Session preferences are kept.",
553
+ enabled: !running,
554
+ run: () => {
555
+ if (!armed()) {
556
+ setArmed(true);
557
+ setNotice({
558
+ message: "Press Enter again to erase all memory.",
559
+ tone: "warn"
560
+ });
561
+ return;
562
+ }
563
+ setArmed(false);
564
+ call("reset", "resetMemory", {
565
+ confirm: true
566
+ }, "Memory reset complete.");
567
+ }
568
+ });
534
569
  return list;
535
570
  };
536
571
  const activate = (i) => {
@@ -553,6 +588,8 @@ function MemoryDialog(context, sessionID) {
553
588
  });
554
589
  };
555
590
  const select = (i) => {
591
+ if (i !== cursor())
592
+ setArmed(false);
556
593
  setCursor(i);
557
594
  const control = controls()[i];
558
595
  if (!control || !scroll)
@@ -575,6 +612,7 @@ function MemoryDialog(context, sessionID) {
575
612
  select((cursor() + d + n) % n);
576
613
  };
577
614
  const switchTab = (next) => {
615
+ setArmed(false);
578
616
  setTab(next);
579
617
  setCursor(0);
580
618
  scroll?.scrollTo(0);
@@ -867,7 +905,7 @@ function MemoryDialog(context, sessionID) {
867
905
  const selected = () => cursor() === i();
868
906
  const disabled = () => !c.enabled || unavailable() || busy() !== null;
869
907
  const fg = () => selected() ? color.selectedText : disabled() ? color.muted : color.text;
870
- const state = () => busy() === c.id ? c.id === "now" ? "Starting\u2026" : "Saving\u2026" : c.on === undefined ? c.enabled ? "Run" : "Unavailable" : c.on ? "On" : "Off";
908
+ const state = () => busy() === c.id ? c.id === "now" ? "Starting\u2026" : c.id === "reset" ? "Resetting\u2026" : "Saving\u2026" : c.id === "reset" && armed() ? "Confirm" : c.on === undefined ? c.enabled ? "Run" : "Unavailable" : c.on ? "On" : "Off";
871
909
  return (() => {
872
910
  var _el$34 = _$createElement("box"), _el$35 = _$createElement("box"), _el$36 = _$createElement("text"), _el$37 = _$createElement("text"), _el$38 = _$createElement("text"), _el$39 = _$createElement("box"), _el$40 = _$createElement("text");
873
911
  _$insertNode(_el$34, _el$35);
@@ -960,7 +998,7 @@ function MemoryDialog(context, sessionID) {
960
998
  _$insert(_el$19, () => tab() === "Controls" ? "select" : "scroll", null);
961
999
  _$insert(_el$21, () => tab() === "Controls" ? "Enter/Space change" : "PgUp/PgDn page \xB7 Home/End ends");
962
1000
  _$effect((_p$) => {
963
- var _v$5 = Math.min(tab() === "Overview" ? 34 : sessionID ? 22 : 19, Math.max(8, dimensions().height - 2)), _v$6 = color.text, _v$7 = color.muted, _v$8 = click(() => {
1001
+ var _v$5 = Math.min(tab() === "Overview" ? 34 : sessionID ? 25 : 22, Math.max(8, dimensions().height - 2)), _v$6 = color.text, _v$7 = color.muted, _v$8 = click(() => {
964
1002
  refresh();
965
1003
  }), _v$9 = color.muted, _v$0 = click(() => context.ui.dialog.clear()), _v$1 = color.muted, _v$10 = color.muted;
966
1004
  _v$5 !== _p$.e && (_p$.e = _$setProp(_el$9, "height", _v$5, _p$.e));