opencode-codex-memory 0.12.1 → 0.13.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.
@@ -25,8 +25,10 @@ export function watchMemoryStatus(read, subscribe) {
25
25
  const next = await read(AbortSignal.any([lifetime.signal, AbortSignal.timeout(5_000)]));
26
26
  if (lifetime.signal.aborted || request !== revision)
27
27
  return;
28
- if (!isMemoryStatus(next))
29
- throw new Error("invalid memory status payload");
28
+ if (!isMemoryStatus(next)) {
29
+ setUnavailable(true);
30
+ return;
31
+ }
30
32
  setStatus(next);
31
33
  setUpdatedAt(Date.now());
32
34
  setUnavailable(false);
@@ -54,12 +56,14 @@ export function hasConsolidationLease(pipeline, now) {
54
56
  return pipeline.phase2Status === "running" && (pipeline.phase2LeaseUntil == null || pipeline.phase2LeaseUntil > now);
55
57
  }
56
58
  export function activeMemoryWork(status, now) {
57
- if (status.manualRetry?.state === "running")
59
+ if (status.manualRetry?.state === "running" && status.manualRetry.action !== "update")
58
60
  return "retry";
59
61
  if (status.activity === "consolidating")
60
62
  return "consolidation";
61
63
  if (status.activity === "extracting")
62
64
  return "extraction";
65
+ if (status.manualRetry?.state === "running")
66
+ return "consolidation";
63
67
  if (status.pipelines.some((pipeline) => hasConsolidationLease(pipeline, now)))
64
68
  return "consolidation";
65
69
  if (status.pipelines.some((pipeline) => pipeline.extracting > 0))
@@ -36,7 +36,8 @@ import { performMemoryReset } from "../../tools/control.js";
36
36
  import { guardMemorySearchTools } from "./search-sandbox.js";
37
37
  import { isMemoryRetryPhase, MemoryStatusRpc } from "./status-rpc.js";
38
38
  import { readMemoryStatus } from "./status.js";
39
- import { clearMemoryRetryResult, memoryRetryStatus, onMemoryRetryChanged, requestMemoryRetry, waitForMemoryRetry, } from "../retry.js";
39
+ import { clearMemoryRetryResult, memoryRetryStatus, onMemoryRetryChanged, requestMemoryUpdate, waitForMemoryRetry, } from "../retry.js";
40
+ import { clearRetryQueue, extractionQueue, memoryLearningPermit, pauseMemoryLearning, requestV2MemoryRetry, } from "./memory-work.js";
40
41
  import { recordInjection, resetInjectionStats } from "./injection.js";
41
42
  import { overlayV2CitationInstructions } from "./citation-overlay.js";
42
43
  import { estimateTokens } from "../token.js";
@@ -101,6 +102,8 @@ export function resetV2ModuleStateForTest() {
101
102
  statusNotifyTimer = null;
102
103
  backgroundTasks.clear();
103
104
  clearMemoryRetryResult();
105
+ clearRetryQueue();
106
+ pauseMemoryLearning();
104
107
  seenTurnSessions.clear();
105
108
  liveInstances.length = 0;
106
109
  activeConfig = undefined;
@@ -191,27 +194,22 @@ function stampAndPump(sid, directory) {
191
194
  trackBackgroundTask(triggerPhase1(sid));
192
195
  }
193
196
  async function triggerPhase1(currentSessionId) {
197
+ if (memoryRetryStatus()?.state === "running")
198
+ return;
199
+ const canStart = memoryLearningPermit();
194
200
  notifyStatusChanged();
195
201
  try {
196
- await runMemoryPipeline(currentSessionId);
202
+ await runMemoryPipeline(currentSessionId, false, canStart);
197
203
  }
198
204
  finally {
199
205
  notifyStatusChanged();
200
206
  }
201
207
  }
202
208
  async function triggerPhase2() {
209
+ if (memoryRetryStatus()?.state === "running")
210
+ return "already_running";
203
211
  try {
204
- return (await runMemoryConsolidation()).join(", ");
205
- }
206
- finally {
207
- notifyStatusChanged();
208
- }
209
- }
210
- /** Panel "Consolidate now": one phase-1 pass over idle sessions, then phase 2 without cooldown. */
211
- async function consolidateNow() {
212
- notifyStatusChanged();
213
- try {
214
- return (await runMemoryPipeline(undefined, true)).join(", ");
212
+ return (await runMemoryConsolidation(false, memoryLearningPermit())).join(", ");
215
213
  }
216
214
  finally {
217
215
  notifyStatusChanged();
@@ -252,8 +250,11 @@ async function attach(ctx) {
252
250
  status: async (input) => {
253
251
  const sessionID = input?.sessionID;
254
252
  const minimum = input?.minConsolidatedThreads;
253
+ const status = readMemoryStatus(typeof sessionID === "string" ? sessionID : null, minimum);
254
+ const canRetryExtraction = status.notices?.some(({ retryPhase }) => retryPhase === "extraction");
255
255
  return {
256
- ...readMemoryStatus(typeof sessionID === "string" ? sessionID : null, minimum),
256
+ ...status,
257
+ ...(canRetryExtraction ? { extractionQueue: extractionQueue(notifyStatusChanged) } : {}),
257
258
  manualRetry: memoryRetryStatus(RETRY_RESULT_LIFETIME_MS),
258
259
  };
259
260
  },
@@ -276,6 +277,8 @@ async function attach(ctx) {
276
277
  }
277
278
  const previous = pluginOptions[key];
278
279
  pluginOptions[key] = value;
280
+ if (key === "generate_memories" && !value && previous)
281
+ pauseMemoryLearning();
279
282
  if (key === "use_memories" && value !== previous) {
280
283
  // Transforms capture options but the host only replays them after an
281
284
  // explicit registry invalidation. Affect future tool snapshots now,
@@ -308,24 +311,25 @@ async function attach(ctx) {
308
311
  return { ok: true };
309
312
  },
310
313
  consolidateNow: async () => {
311
- if (memoryRetryStatus()?.state === "running")
312
- return { status: "already_running", message: "A memory retry is in progress." };
313
- // Runs detached so the dialog does not block on a multi-minute turn.
314
- const run = consolidateNow();
315
- trackBackgroundTask(run.then(() => { }));
316
- return { status: "started" };
314
+ const canStart = memoryLearningPermit();
315
+ const request = requestMemoryUpdate(() => runMemoryPipeline(undefined, true, canStart));
316
+ return request.ok ? { status: "started" } : { status: "blocked", message: request.message };
317
317
  },
318
318
  retryFailed: async (input) => {
319
- const phase = input?.phase;
319
+ const { phase, all } = (input ?? {});
320
320
  if (!isMemoryRetryPhase(phase))
321
321
  return { ok: false, message: "Choose extraction or consolidation to retry." };
322
- const request = requestMemoryRetry(phase);
322
+ if (all && phase !== "extraction")
323
+ return { ok: false, message: "Retry all is only available for extraction." };
324
+ const request = requestV2MemoryRetry(phase, undefined, all);
323
325
  return request.ok ? { ok: true } : request;
324
326
  },
325
327
  resetMemory: async (input) => {
326
328
  if (input?.confirm !== true)
327
329
  return { ok: false, message: "Reset not confirmed." };
328
330
  const result = performMemoryReset();
331
+ if (result.ok)
332
+ clearRetryQueue();
329
333
  notifyStatusChanged();
330
334
  return result;
331
335
  },
@@ -435,7 +439,7 @@ async function attach(ctx) {
435
439
  try {
436
440
  if (!pluginOptions.disable_on_external_context || !ev?.sessionID)
437
441
  return;
438
- if ((await classifyExternalContextTool(ev.tool)) !== true)
442
+ if (!(await classifyExternalContextTool(ev.tool)))
439
443
  return;
440
444
  getStore().markPolluted(ev.sessionID);
441
445
  }
@@ -549,6 +553,7 @@ function releaseLocation(ctx) {
549
553
  setSubSessionDirectory();
550
554
  setV2Context(null);
551
555
  clearMemoryRetryResult();
556
+ clearRetryQueue();
552
557
  activeConfig = undefined;
553
558
  draining = undefined;
554
559
  invalidateCache();
@@ -6,7 +6,7 @@
6
6
  * `Rpc.define` is a runtime passthrough (validation only), so a plain object
7
7
  * with JSON Schema nodes is an equivalent portable definition.
8
8
  */
9
- import { type MemoryNotice, type MemoryRetry, type MemoryRetryPhase } from "../recovery-info.js";
9
+ import { type ExtractionQueue, type MemoryNotice, type MemoryRetry, type MemoryRetryPhase } from "../recovery-info.js";
10
10
  export { MEMORY_NOTICE_KINDS, type MemoryNotice, type MemoryRetry, type MemoryRetryPhase } from "../recovery-info.js";
11
11
  export declare const MEMORY_STATUS_ACTIVITIES: readonly ["idle", "extracting", "consolidating", "retrying", "error", "read_only", "disabled", "stopping"];
12
12
  export type MemoryStatusActivity = (typeof MEMORY_STATUS_ACTIVITIES)[number];
@@ -45,7 +45,13 @@ export interface MemoryStatus {
45
45
  warnings: string[];
46
46
  /** Typed guidance inputs. Older servers only send warning strings. */
47
47
  notices?: MemoryNotice[];
48
- /** Null when no recent request; absent on servers without manual retry support. */
48
+ /** Distinct conversations with exhausted attempts across active memory versions. */
49
+ extractionBacklog?: {
50
+ count: number;
51
+ historical: boolean;
52
+ };
53
+ extractionQueue?: ExtractionQueue;
54
+ /** Latest visible result; absent on servers without manual retry support. */
49
55
  manualRetry?: MemoryRetry | null;
50
56
  /** Per-session read/write mode when a sessionID was supplied. */
51
57
  sessionMode: "enabled" | "disabled" | "polluted" | null;
@@ -186,6 +192,45 @@ export declare const MemoryStatusRpc: {
186
192
  readonly type: "string";
187
193
  };
188
194
  };
195
+ readonly extractionBacklog: {
196
+ readonly type: "object";
197
+ readonly properties: {
198
+ readonly count: {
199
+ readonly type: "integer";
200
+ readonly minimum: 1;
201
+ };
202
+ readonly historical: {
203
+ readonly type: "boolean";
204
+ };
205
+ };
206
+ readonly required: readonly ["count", "historical"];
207
+ readonly additionalProperties: false;
208
+ };
209
+ readonly extractionQueue: {
210
+ readonly type: "object";
211
+ readonly properties: {
212
+ readonly ready: {
213
+ readonly type: readonly ["integer", "null"];
214
+ readonly minimum: 0;
215
+ };
216
+ readonly waitingForIdle: {
217
+ readonly type: "integer";
218
+ readonly minimum: 0;
219
+ };
220
+ readonly unavailable: {
221
+ readonly type: "integer";
222
+ readonly minimum: 0;
223
+ };
224
+ readonly checking: {
225
+ readonly type: "boolean";
226
+ };
227
+ readonly multipleBatches: {
228
+ readonly type: "boolean";
229
+ };
230
+ };
231
+ readonly required: readonly ["ready", "waitingForIdle", "unavailable"];
232
+ readonly additionalProperties: false;
233
+ };
189
234
  readonly notices: {
190
235
  readonly type: "array";
191
236
  readonly items: {
@@ -212,6 +257,9 @@ export declare const MemoryStatusRpc: {
212
257
  readonly retryAt: {
213
258
  readonly type: "number";
214
259
  };
260
+ readonly failedAt: {
261
+ readonly type: "number";
262
+ };
215
263
  readonly retryPhase: {
216
264
  readonly type: "string";
217
265
  readonly enum: readonly ["extraction", "consolidation"];
@@ -235,6 +283,22 @@ export declare const MemoryStatusRpc: {
235
283
  readonly message: {
236
284
  readonly type: "string";
237
285
  };
286
+ readonly conversationsProcessed: {
287
+ readonly type: "integer";
288
+ readonly minimum: 1;
289
+ };
290
+ readonly conversationsFailed: {
291
+ readonly type: "integer";
292
+ readonly minimum: 1;
293
+ };
294
+ readonly conversationsSkipped: {
295
+ readonly type: "integer";
296
+ readonly minimum: 1;
297
+ };
298
+ readonly action: {
299
+ readonly type: "string";
300
+ readonly enum: readonly ["update"];
301
+ };
238
302
  };
239
303
  readonly required: readonly ["phase", "state", "message"];
240
304
  readonly additionalProperties: false;
@@ -354,6 +418,9 @@ export declare const MemoryStatusRpc: {
354
418
  readonly type: "string";
355
419
  readonly enum: readonly ["extraction", "consolidation"];
356
420
  };
421
+ readonly all: {
422
+ readonly type: "boolean";
423
+ };
357
424
  };
358
425
  readonly required: readonly ["phase"];
359
426
  readonly additionalProperties: false;
@@ -82,6 +82,27 @@ export const MemoryStatusRpc = {
82
82
  lastSuccessAt: { type: ["number", "null"] },
83
83
  retryAt: { type: ["number", "null"] },
84
84
  warnings: { type: "array", items: { type: "string" } },
85
+ extractionBacklog: {
86
+ type: "object",
87
+ properties: {
88
+ count: { type: "integer", minimum: 1 },
89
+ historical: { type: "boolean" },
90
+ },
91
+ required: ["count", "historical"],
92
+ additionalProperties: false,
93
+ },
94
+ extractionQueue: {
95
+ type: "object",
96
+ properties: {
97
+ ready: { type: ["integer", "null"], minimum: 0 },
98
+ waitingForIdle: { type: "integer", minimum: 0 },
99
+ unavailable: { type: "integer", minimum: 0 },
100
+ checking: { type: "boolean" },
101
+ multipleBatches: { type: "boolean" },
102
+ },
103
+ required: ["ready", "waitingForIdle", "unavailable"],
104
+ additionalProperties: false,
105
+ },
85
106
  notices: {
86
107
  type: "array",
87
108
  items: {
@@ -93,6 +114,7 @@ export const MemoryStatusRpc = {
93
114
  phase: RETRY_PHASE_SCHEMA,
94
115
  sessionID: { type: "string" },
95
116
  retryAt: { type: "number" },
117
+ failedAt: { type: "number" },
96
118
  retryPhase: RETRY_PHASE_SCHEMA,
97
119
  },
98
120
  required: ["kind"],
@@ -105,6 +127,10 @@ export const MemoryStatusRpc = {
105
127
  phase: RETRY_PHASE_SCHEMA,
106
128
  state: { type: "string", enum: [...MEMORY_RETRY_STATES] },
107
129
  message: { type: "string" },
130
+ conversationsProcessed: { type: "integer", minimum: 1 },
131
+ conversationsFailed: { type: "integer", minimum: 1 },
132
+ conversationsSkipped: { type: "integer", minimum: 1 },
133
+ action: { type: "string", enum: ["update"] },
108
134
  },
109
135
  required: ["phase", "state", "message"],
110
136
  additionalProperties: false,
@@ -187,7 +213,7 @@ export const MemoryStatusRpc = {
187
213
  retryFailed: {
188
214
  input: {
189
215
  type: "object",
190
- properties: { phase: RETRY_PHASE_SCHEMA },
216
+ properties: { phase: RETRY_PHASE_SCHEMA, all: { type: "boolean" } },
191
217
  required: ["phase"],
192
218
  additionalProperties: false,
193
219
  },
@@ -289,14 +315,33 @@ export function isMemoryStatus(value) {
289
315
  (notice.detail === undefined || typeof notice.detail === "string") &&
290
316
  (notice.sessionID === undefined || typeof notice.sessionID === "string") &&
291
317
  (notice.retryPhase === undefined || isMemoryRetryPhase(notice.retryPhase)) &&
318
+ (notice.failedAt === undefined ||
319
+ (typeof notice.failedAt === "number" && Number.isFinite(notice.failedAt))) &&
292
320
  (notice.retryAt === undefined || (typeof notice.retryAt === "number" && Number.isFinite(notice.retryAt))))))
293
321
  return false;
322
+ const backlog = value.extractionBacklog;
323
+ if (backlog !== undefined &&
324
+ (!isRecord(backlog) ||
325
+ !Number.isInteger(backlog.count) ||
326
+ backlog.count < 1 ||
327
+ typeof backlog.historical !== "boolean"))
328
+ return false;
294
329
  const retry = value.manualRetry;
295
330
  if (retry != null &&
296
331
  (!isRecord(retry) ||
297
332
  !isMemoryRetryPhase(retry.phase) ||
298
333
  typeof retry.message !== "string" ||
299
- !MEMORY_RETRY_STATES.includes(retry.state)))
334
+ !MEMORY_RETRY_STATES.includes(retry.state) ||
335
+ (retry.action !== undefined && retry.action !== "update") ||
336
+ ![retry.conversationsProcessed, retry.conversationsFailed, retry.conversationsSkipped].every((count) => count === undefined || (Number.isInteger(count) && count >= 1))))
337
+ return false;
338
+ const queue = value.extractionQueue;
339
+ if (queue !== undefined &&
340
+ (!isRecord(queue) ||
341
+ ![queue.waitingForIdle, queue.unavailable].every((count) => Number.isInteger(count) && count >= 0) ||
342
+ (queue.ready !== null && (!Number.isInteger(queue.ready) || queue.ready < 0)) ||
343
+ (queue.checking !== undefined && typeof queue.checking !== "boolean") ||
344
+ (queue.multipleBatches !== undefined && typeof queue.multipleBatches !== "boolean")))
300
345
  return false;
301
346
  if (value.sessionMode !== null &&
302
347
  value.sessionMode !== "enabled" &&
@@ -25,10 +25,20 @@ export function readMemoryStatus(sessionID, minConsolidatedThreads) {
25
25
  const snapshots = existingMemoryStores().map((pipelineStore) => ({
26
26
  version: pipelineStore.version,
27
27
  stage1Count: pipelineStore.stage1OutputCount(),
28
- phase1: pipelineStore.stage1JobSnapshot(staleBeforeSec),
28
+ phase1: pipelineStore.stage1JobSnapshot(staleBeforeSec, (sessionID) => {
29
+ const mode = pipelineStore.getMemoryMode(sessionID);
30
+ return mode !== "disabled" && mode !== "polluted";
31
+ }),
29
32
  phase2: pipelineStore.phase2JobSnapshot(),
30
33
  }));
31
34
  const activeWriters = snapshots.filter((pipeline) => writeVersions.includes(pipeline.version));
35
+ const exhaustedWriters = activeWriters.filter(({ phase1 }) => phase1.latest_exhausted !== null);
36
+ const exhaustedCount = new Set(exhaustedWriters.flatMap(({ phase1 }) => phase1.exhausted_session_ids)).size;
37
+ const historicalBacklog = exhaustedWriters.every(({ phase1 }) => {
38
+ const failedAt = phase1.latest_exhausted?.finished_at;
39
+ // Job timestamps only have whole-second precision.
40
+ return failedAt != null && phase1.latest_success_at != null && phase1.latest_success_at > failedAt;
41
+ });
32
42
  const nextRetry = (times) => {
33
43
  const future = times.filter((time) => time != null && time * 1000 > now);
34
44
  return future.length ? Math.min(...future) * 1000 : null;
@@ -97,7 +107,7 @@ export function readMemoryStatus(sessionID, minConsolidatedThreads) {
97
107
  }
98
108
  if (due > 0)
99
109
  warnings.push(`${prefix}Some extraction jobs are due to retry.`);
100
- if (phase1.latest_exhausted)
110
+ if (phase1.latest_exhausted && !historicalBacklog)
101
111
  warnings.push(`${prefix}Some extraction jobs exhausted their retries.`);
102
112
  if (capacity > 0)
103
113
  warnings.push(`${prefix}Some extraction jobs hit provider capacity limits.`);
@@ -152,6 +162,9 @@ export function readMemoryStatus(sessionID, minConsolidatedThreads) {
152
162
  retryAt,
153
163
  warnings,
154
164
  notices,
165
+ ...(options.generate_memories && exhaustedCount > 0
166
+ ? { extractionBacklog: { count: exhaustedCount, historical: historicalBacklog } }
167
+ : {}),
155
168
  sessionMode: sessionID ? store.getMemoryMode(sessionID) : null,
156
169
  memoryRoot: memoryRoot(sessionVersion),
157
170
  injected: {
@@ -11,9 +11,13 @@
11
11
  */
12
12
  import { tool } from "@opencode-ai/plugin";
13
13
  import { memory_read, memory_search, memory_list, memory_add_note } from "../../tools/memory.js";
14
- import { memory_inspect, memory_mode, memory_retry } from "../../tools/control.js";
14
+ import { makeMemoryRetryTool, memory_inspect, memory_mode } from "../../tools/control.js";
15
15
  import { pluginOptions } from "../options.js";
16
16
  import { getV2DiscoveryStatus } from "./shim.js";
17
+ import { inspectExtractionQueue, requestV2MemoryRetry } from "./memory-work.js";
18
+ import { extractionQueueText } from "../recovery-info.js";
19
+ import { isMemoryWorkInFlight } from "../pipeline.js";
20
+ import { memoryRetryStatus } from "../retry.js";
17
21
  function adaptTool(name, v1, ask) {
18
22
  return {
19
23
  name,
@@ -41,14 +45,43 @@ function adaptTool(name, v1, ask) {
41
45
  let content = res.output ?? "";
42
46
  let metadata = res.metadata;
43
47
  if (name === "memory_inspect") {
48
+ const info = metadata;
49
+ const recovery = info?.recovery;
50
+ const queue = recovery?.notices.some((notice) => notice.phase === "extraction")
51
+ ? await inspectExtractionQueue(v1ctx.sessionID)
52
+ : undefined;
44
53
  const discovery = getV2DiscoveryStatus();
54
+ if (queue && recovery) {
55
+ const batchAdvice = ' After fixing the issue, call memory_retry({"phase":"extraction"}).';
56
+ const advice = queue.ready
57
+ ? `${batchAdvice}${queue.multipleBatches ? '\n To retry all eligible conversations on request, use memory_retry({"phase":"extraction","all":true}).' : ""}`
58
+ : " No extraction retries are ready.";
59
+ content = content.replace(batchAdvice, advice);
60
+ if (!queue.ready)
61
+ recovery.retryable_phases = recovery.retryable_phases.filter((phase) => phase !== "extraction");
62
+ }
63
+ const pausing = !pluginOptions.generate_memories && (isMemoryWorkInFlight() || memoryRetryStatus()?.state === "running");
45
64
  content = [
46
65
  `v2_discovery_source: ${discovery?.source ?? "not_checked"}`,
47
66
  ...(discovery?.warning ? [`v2_discovery_warning: ${discovery.warning}`] : []),
67
+ ...(pausing ? ["Learning is pausing. Current memory work is finishing; no new jobs will start."] : []),
68
+ ...(queue ? [`Extraction retries: ${extractionQueueText(queue)}`] : []),
48
69
  "",
49
70
  content,
50
71
  ].join("\n");
51
- metadata = { ...(metadata && typeof metadata === "object" ? metadata : {}), v2_discovery: discovery };
72
+ metadata = {
73
+ ...(metadata && typeof metadata === "object" ? metadata : {}),
74
+ v2_discovery: discovery,
75
+ ...(queue ? { extraction_queue: queue } : {}),
76
+ };
77
+ }
78
+ if (name === "memory_retry" && pluginOptions.generate_memories) {
79
+ const result = metadata?.retry;
80
+ if (result?.phase === "extraction") {
81
+ const queue = await inspectExtractionQueue(v1ctx.sessionID);
82
+ content += `\nRemaining extraction retries: ${extractionQueueText(queue)}`;
83
+ metadata = { retry: result, extraction_queue: queue };
84
+ }
52
85
  }
53
86
  // V2 validates metadata as JSON before persisting Tool.Success. V1 tool
54
87
  // metadata can contain undefined optional fields (search path/since/until).
@@ -67,7 +100,7 @@ const ALL_MEMORY_TOOLS = [
67
100
  ["memory_add_note", memory_add_note],
68
101
  ["memory_inspect", memory_inspect],
69
102
  ["memory_mode", memory_mode],
70
- ["memory_retry", memory_retry],
103
+ ["memory_retry", makeMemoryRetryTool(requestV2MemoryRetry)],
71
104
  ];
72
105
  const CONTROL_ONLY = new Set(["memory_inspect", "memory_mode", "memory_retry"]);
73
106
  /**