opencode-codex-memory 0.10.3 → 0.12.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.
@@ -0,0 +1,198 @@
1
+ import { hasConsolidationLease, remaining } from "./panel-status.js";
2
+ import { modelRecoveryGuidance } from "../recovery-info.js";
3
+ import { MEMORY_NOTICE_KINDS } from "./status-rpc.js";
4
+ export const memoryHelp = {
5
+ models: { label: "Background model setup", path: "configuration.md#choose-background-models" },
6
+ providers: { label: "Open provider settings", path: null },
7
+ backup: { label: "Set up backup models", path: "configuration.md#backup-models" },
8
+ configuration: { label: "Memory configuration", path: "configuration.md#where-to-put-options" },
9
+ service: { label: "Check the OpenCode service", path: "troubleshooting.md#check-opencodes-server" },
10
+ troubleshooting: { label: "Troubleshooting", path: "troubleshooting.md#common-symptoms" },
11
+ codex: { label: "Codex import setup", path: "integrations.md#sharing-memory-with-the-codex-cli" },
12
+ };
13
+ export function memoryHelpURL(help) {
14
+ const page = memoryHelp[help].path;
15
+ return page === null ? null : `https://github.com/moritzfl/opencode-codex-memory/blob/main/docs/${page}`;
16
+ }
17
+ export const retryLabels = {
18
+ extraction: { action: "Retry extraction", result: "Extraction retry" },
19
+ consolidation: { action: "Retry consolidation", result: "Consolidation retry" },
20
+ };
21
+ function retryDescription(times, now) {
22
+ return times.every((time) => time > now)
23
+ ? `Automatic retry can run ${remaining(Math.min(...times), now)}, when there’s OpenCode activity.`
24
+ : "Automatic retry can run on the next OpenCode activity.";
25
+ }
26
+ function noticeMessage(kind, details, now, retryPhases, supportsRetry, sessionID) {
27
+ switch (kind) {
28
+ case "extraction_exhausted": {
29
+ const current = sessionID ? details.find((notice) => notice.sessionID === sessionID) : undefined;
30
+ const affected = current ?? details[0];
31
+ const recovery = modelRecoveryGuidance(details.filter((notice) => notice.sessionID === affected?.sessionID).map((notice) => notice.detail ?? ""), "extraction");
32
+ const conversation = current ? "this conversation" : "an affected conversation";
33
+ const nextStep = retryPhases.length
34
+ ? "Retry a batch with the current background models. No new message is needed."
35
+ : supportsRetry
36
+ ? "Wait for the provider limit to clear before retrying."
37
+ : `After fixing the issue, send a new message in ${conversation} and let it go idle.`;
38
+ return {
39
+ title: "Learning stopped for some sessions",
40
+ description: `${recovery?.description ?? "Some conversations ran out of retries."} ${nextStep}`,
41
+ help: recovery?.help ?? "troubleshooting",
42
+ warning: true,
43
+ affectedSessionID: current ? undefined : affected?.sessionID,
44
+ details,
45
+ };
46
+ }
47
+ case "extraction_retry":
48
+ case "consolidation_failed": {
49
+ const extraction = kind === "extraction_retry";
50
+ const phase = extraction ? "Extraction" : "Consolidation";
51
+ const recovery = modelRecoveryGuidance(details.map((notice) => notice.detail ?? ""), extraction ? "extraction" : "consolidation");
52
+ const times = details.map((notice) => notice.retryAt ?? 0);
53
+ const waiting = times.every((time) => time > now);
54
+ const retry = retryDescription(times, now);
55
+ return {
56
+ title: recovery ? `${phase} failed` : waiting ? `${phase} waiting to retry` : `${phase} can retry`,
57
+ description: [
58
+ recovery?.description ??
59
+ (extraction ? "Learning from some sessions failed." : "The last memory update failed."),
60
+ retry,
61
+ retryPhases.length ? "You can retry now with the current models." : "",
62
+ ]
63
+ .filter(Boolean)
64
+ .join(" "),
65
+ help: recovery?.help ?? (extraction ? undefined : "troubleshooting"),
66
+ warning: !!recovery,
67
+ details,
68
+ };
69
+ }
70
+ case "provider_capacity":
71
+ return {
72
+ title: "Provider rate limit or quota",
73
+ description: details.every((notice) => (notice.retryAt ?? 0) > now)
74
+ ? retryDescription(details.map((notice) => notice.retryAt ?? 0), now)
75
+ : retryPhases.length
76
+ ? "If the provider allows requests again, retry with the current background models."
77
+ : "Learning can resume when the provider allows requests again.",
78
+ help: "backup",
79
+ details,
80
+ };
81
+ case "configuration":
82
+ return {
83
+ title: "Check memory configuration",
84
+ description: "OpenCode ignored or adjusted some memory options. Correct the options listed below.",
85
+ help: "configuration",
86
+ warning: true,
87
+ details,
88
+ };
89
+ case "consolidator_setup":
90
+ return {
91
+ title: "Memory agent needs attention",
92
+ description: "Check for overrides of the memorize agent. Restore the plugin's default agent permissions.",
93
+ help: "troubleshooting",
94
+ warning: true,
95
+ details,
96
+ };
97
+ case "discovery":
98
+ return {
99
+ title: "Learning is limited to recent activity",
100
+ description: "Memory can only see conversations this server has observed. Check the OpenCode service to restore access to past sessions.",
101
+ help: "service",
102
+ warning: true,
103
+ details,
104
+ };
105
+ case "codex_import":
106
+ return {
107
+ title: "Codex import is blocked",
108
+ description: "Check the Codex home and memory paths. OpenCode can still learn from its own conversations.",
109
+ help: "codex",
110
+ warning: true,
111
+ details,
112
+ };
113
+ }
114
+ }
115
+ export function memoryMessages(status, now, sessionID) {
116
+ if (status.activity === "stopping")
117
+ return [{ title: "Memory is stopping", description: "Wait for OpenCode to reconnect." }];
118
+ const shownRetries = new Set();
119
+ const messages = MEMORY_NOTICE_KINDS.flatMap((kind) => {
120
+ const notices = status.notices?.filter((notice) => notice.kind === kind) ?? [];
121
+ if (!notices.length)
122
+ return [];
123
+ const retryPhases = [];
124
+ if (status.manualRetry !== undefined) {
125
+ for (const { retryPhase } of notices) {
126
+ if (!retryPhase || shownRetries.has(retryPhase))
127
+ continue;
128
+ retryPhases.push(retryPhase);
129
+ shownRetries.add(retryPhase);
130
+ }
131
+ }
132
+ return [
133
+ { ...noticeMessage(kind, notices, now, retryPhases, status.manualRetry !== undefined, sessionID), retryPhases },
134
+ ];
135
+ });
136
+ if (status.manualRetry?.state === "running")
137
+ return [{ title: `Retrying ${status.manualRetry.phase}…`, description: status.manualRetry.message }, ...messages];
138
+ if (status.generateMemories) {
139
+ const active = status.pipelines.filter((pipeline) => status.dualWrite || pipeline.version === status.version);
140
+ if (status.activity === "consolidating") {
141
+ messages.unshift({ title: "Consolidating memories", description: "Updating the memory files used for recall." });
142
+ }
143
+ else if (status.activity === "extracting") {
144
+ messages.unshift({
145
+ title: "Learning from sessions",
146
+ description: "Saving useful context from eligible conversations.",
147
+ });
148
+ }
149
+ else if (active.some((pipeline) => hasConsolidationLease(pipeline, now))) {
150
+ messages.unshift({
151
+ title: "Waiting for consolidation",
152
+ description: "A consolidation lock is active. Wait for the run to finish or for the lock to expire.",
153
+ });
154
+ }
155
+ if (messages.length)
156
+ return messages.sort((a, b) => Number(!!b.warning) - Number(!!a.warning));
157
+ if (status.notices === undefined && status.activity === "error")
158
+ return [
159
+ {
160
+ title: "Check memory status",
161
+ description: "See the reported warnings, or ask the agent to run memory_inspect for recent errors.",
162
+ warning: true,
163
+ help: "troubleshooting",
164
+ },
165
+ ];
166
+ if (status.notices === undefined && status.activity === "retrying")
167
+ return [
168
+ {
169
+ title: "Waiting to retry",
170
+ description: retryDescription([status.retryAt ?? 0], now),
171
+ },
172
+ ];
173
+ const queued = active.filter((pipeline) => pipeline.phase2Status === "pending");
174
+ if (queued.length) {
175
+ const cooldowns = queued.map((pipeline) => pipeline.phase2CooldownUntil ?? 0);
176
+ return [
177
+ {
178
+ title: "Consolidation queued",
179
+ description: cooldowns.every((time) => time > now)
180
+ ? `Cooldown ends ${remaining(Math.min(...cooldowns), now)}. OpenCode can update memory on activity after that.`
181
+ : "OpenCode can update memory on the next conversation activity or when a session goes idle.",
182
+ },
183
+ ];
184
+ }
185
+ return [
186
+ {
187
+ title: "Idle",
188
+ description: "OpenCode checks for eligible idle conversations on new activity.",
189
+ },
190
+ ];
191
+ }
192
+ return [
193
+ status.useMemories
194
+ ? { title: "Learning paused", description: "OpenCode can still use existing memories in conversations." }
195
+ : { title: "Memory is off", description: "Turn on recall or learning below." },
196
+ ...messages,
197
+ ];
198
+ }
@@ -0,0 +1,24 @@
1
+ import { type MemoryStatus } from "./status-rpc.js";
2
+ export declare const activityLabels: Record<MemoryStatus["activity"], string>;
3
+ /** Keep the last good snapshot on disconnect; ignore late replies and abort on close. */
4
+ export declare function watchMemoryStatus(read: (signal: AbortSignal) => Promise<unknown>, subscribe: (listener: () => void) => () => void): {
5
+ status: import("solid-js").Accessor<MemoryStatus | null>;
6
+ unavailable: import("solid-js").Accessor<boolean>;
7
+ refreshing: import("solid-js").Accessor<boolean>;
8
+ updatedAt: import("solid-js").Accessor<number>;
9
+ refresh: () => Promise<void>;
10
+ signal: AbortSignal;
11
+ };
12
+ export declare function hasConsolidationLease(pipeline: MemoryStatus["pipelines"][number], now: number): boolean;
13
+ export declare function isMemoryRunning(status: MemoryStatus, now?: number): boolean;
14
+ export declare function elapsed(time: number, now: number): string;
15
+ export declare function remaining(time: number | null | undefined, now: number): string;
16
+ export type StatusRow = {
17
+ label: string;
18
+ value: string;
19
+ tone?: "ok" | "warn" | "muted";
20
+ };
21
+ export declare function diagnosticRows(s: MemoryStatus, now: number): StatusRow[];
22
+ export declare function statusRows(s: MemoryStatus, now: number): StatusRow[];
23
+ export declare function usageRows(s: MemoryStatus, sessionID?: string): StatusRow[];
24
+ export declare function configRows(s: MemoryStatus): StatusRow[];
@@ -0,0 +1,212 @@
1
+ import { createSignal, onCleanup } from "solid-js";
2
+ import { isMemoryStatus } from "./status-rpc.js";
3
+ export const activityLabels = {
4
+ idle: "Idle",
5
+ extracting: "Extracting",
6
+ consolidating: "Consolidating",
7
+ retrying: "Waiting to retry",
8
+ error: "Needs attention",
9
+ read_only: "Read only",
10
+ disabled: "Disabled",
11
+ stopping: "Stopping",
12
+ };
13
+ /** Keep the last good snapshot on disconnect; ignore late replies and abort on close. */
14
+ export function watchMemoryStatus(read, subscribe) {
15
+ const [status, setStatus] = createSignal(null);
16
+ const [unavailable, setUnavailable] = createSignal(false);
17
+ const [refreshing, setRefreshing] = createSignal(false);
18
+ const [updatedAt, setUpdatedAt] = createSignal(Date.now());
19
+ const lifetime = new AbortController();
20
+ let revision = 0;
21
+ const refresh = async () => {
22
+ const request = ++revision;
23
+ setRefreshing(true);
24
+ try {
25
+ const next = await read(AbortSignal.any([lifetime.signal, AbortSignal.timeout(5_000)]));
26
+ if (lifetime.signal.aborted || request !== revision)
27
+ return;
28
+ if (!isMemoryStatus(next))
29
+ throw new Error("invalid memory status payload");
30
+ setStatus(next);
31
+ setUpdatedAt(Date.now());
32
+ setUnavailable(false);
33
+ }
34
+ catch {
35
+ if (!lifetime.signal.aborted && request === revision)
36
+ setUnavailable(true);
37
+ }
38
+ finally {
39
+ if (!lifetime.signal.aborted && request === revision)
40
+ setRefreshing(false);
41
+ }
42
+ };
43
+ const unsubscribe = subscribe(() => void refresh());
44
+ const timer = setInterval(() => void refresh(), 30_000);
45
+ onCleanup(() => {
46
+ lifetime.abort();
47
+ clearInterval(timer);
48
+ unsubscribe();
49
+ });
50
+ void refresh();
51
+ return { status, unavailable, refreshing, updatedAt, refresh, signal: lifetime.signal };
52
+ }
53
+ export function hasConsolidationLease(pipeline, now) {
54
+ return pipeline.phase2Status === "running" && (pipeline.phase2LeaseUntil == null || pipeline.phase2LeaseUntil > now);
55
+ }
56
+ export function isMemoryRunning(status, now = Date.now()) {
57
+ return (status.manualRetry?.state === "running" ||
58
+ status.activity === "consolidating" ||
59
+ status.activity === "extracting" ||
60
+ status.pipelines.some((pipeline) => pipeline.extracting > 0 || hasConsolidationLease(pipeline, now)));
61
+ }
62
+ export function elapsed(time, now) {
63
+ const minutes = Math.max(0, Math.floor((now - time) / 60_000));
64
+ if (minutes === 0)
65
+ return "just now";
66
+ if (minutes < 60)
67
+ return `${minutes}m ago`;
68
+ if (minutes < 1440)
69
+ return `${Math.floor(minutes / 60)}h ago`;
70
+ return `${Math.floor(minutes / 1440)}d ago`;
71
+ }
72
+ export function remaining(time, now) {
73
+ if (time == null)
74
+ return "—";
75
+ const minutes = Math.max(0, Math.ceil((time - now) / 60_000));
76
+ if (minutes < 1)
77
+ return "in <1m";
78
+ if (minutes < 60)
79
+ return `in ${minutes}m`;
80
+ if (minutes < 1440)
81
+ return `in ${Math.floor(minutes / 60)}h ${minutes % 60}m`;
82
+ return `in ${Math.floor(minutes / 1440)}d`;
83
+ }
84
+ function formatTokens(n) {
85
+ if (n >= 1_000_000)
86
+ return `${(n / 1_000_000).toFixed(1)}M`;
87
+ if (n >= 1_000)
88
+ return `${(n / 1_000).toFixed(1)}K`;
89
+ return String(n);
90
+ }
91
+ function pipelineRows(s, now) {
92
+ return s.pipelines.flatMap((pipeline) => {
93
+ const version = pipeline.version.toUpperCase();
94
+ const paused = !s.generateMemories || (!s.dualWrite && pipeline.version !== s.version);
95
+ const extractionRetry = pipeline.phase1RetryAt != null && pipeline.phase1RetryAt > now;
96
+ const consolidationRetry = pipeline.phase2RetryAt != null && pipeline.phase2RetryAt > now;
97
+ const cooldown = pipeline.phase2CooldownUntil != null && pipeline.phase2CooldownUntil > now;
98
+ const consolidation = pipeline.phase2Status === "pending" ? "Queued" : pipeline.phase2Status === "failed" ? "Retry due" : "Idle";
99
+ return [
100
+ { label: `${version} recaps`, value: `${pipeline.stage1Count} stored`, tone: "muted" },
101
+ {
102
+ label: `${version} extraction`,
103
+ value: pipeline.extracting
104
+ ? `Running (${pipeline.extracting})`
105
+ : paused
106
+ ? "Paused"
107
+ : extractionRetry
108
+ ? `Retry ${remaining(pipeline.phase1RetryAt, now)}`
109
+ : "Idle",
110
+ tone: extractionRetry && !paused ? "warn" : "muted",
111
+ },
112
+ {
113
+ label: `${version} consolidation`,
114
+ value: hasConsolidationLease(pipeline, now)
115
+ ? "Running"
116
+ : paused
117
+ ? "Paused"
118
+ : consolidationRetry
119
+ ? `Retry ${remaining(pipeline.phase2RetryAt, now)}`
120
+ : cooldown
121
+ ? `${consolidation} · cooldown ends ${remaining(pipeline.phase2CooldownUntil, now)}`
122
+ : pipeline.phase2Status === "pending"
123
+ ? "Queued · next activity"
124
+ : pipeline.phase2Status === "running"
125
+ ? "Interrupted · next activity"
126
+ : consolidation,
127
+ tone: pipeline.lastError ? "warn" : "muted",
128
+ },
129
+ ...(pipeline.lastError
130
+ ? [{ label: `${version} last error`, value: pipeline.lastError, tone: "warn" }]
131
+ : []),
132
+ ];
133
+ });
134
+ }
135
+ export function diagnosticRows(s, now) {
136
+ return [
137
+ { label: "Memory version", value: `${s.sessionVersion} (default ${s.version})` },
138
+ { label: "Learning pipelines", value: s.dualWrite ? "v1 + v2" : s.version },
139
+ {
140
+ label: "V2 readiness",
141
+ value: `${s.v2Ready ? "Ready" : "Not ready"} · ${s.v2ConsolidatedThreads}/${s.minConsolidatedThreads} sessions`,
142
+ tone: s.v2Ready ? "ok" : "muted",
143
+ },
144
+ ...(s.v2NotReadyReason ? [{ label: "V2 not ready", value: s.v2NotReadyReason, tone: "muted" }] : []),
145
+ ...(s.v2SummaryBytes !== undefined
146
+ ? [
147
+ {
148
+ label: "V2 summary",
149
+ value: s.v2SummaryBytes === null
150
+ ? "Unreadable"
151
+ : s.v2InjectedSummaryBytes != null
152
+ ? `${s.v2SummaryBytes} bytes on disk · ${s.v2InjectedSummaryBytes} injected${s.v2SummaryBytes >= 10000 ? " (capped)" : ""}`
153
+ : `${s.v2SummaryBytes} UTF-8 bytes`,
154
+ tone: "muted",
155
+ },
156
+ ]
157
+ : []),
158
+ ...pipelineRows(s, now),
159
+ ];
160
+ }
161
+ export function statusRows(s, now) {
162
+ return [
163
+ { label: "Activity", value: activityLabels[s.activity] },
164
+ ...diagnosticRows(s, now),
165
+ { label: "Use memories", value: s.useMemories ? "On" : "Off", tone: s.useMemories ? "ok" : "muted" },
166
+ {
167
+ label: "Learn from sessions",
168
+ value: s.generateMemories ? "On" : "Off",
169
+ tone: s.generateMemories ? "ok" : "muted",
170
+ },
171
+ ...(s.sessionMode
172
+ ? [
173
+ {
174
+ label: "This session",
175
+ value: s.sessionMode === "enabled"
176
+ ? s.generateMemories
177
+ ? "Eligible for learning"
178
+ : "Eligible (learning paused)"
179
+ : s.sessionMode === "disabled"
180
+ ? "Not learning"
181
+ : "Excluded (external context)",
182
+ tone: (s.sessionMode === "enabled" && s.generateMemories ? "ok" : "muted"),
183
+ },
184
+ ]
185
+ : []),
186
+ { label: "Last consolidated", value: s.lastSuccessAt == null ? "Never" : elapsed(s.lastSuccessAt, now) },
187
+ ...(s.retryAt == null ? [] : [{ label: "Next retry", value: remaining(s.retryAt, now), tone: "warn" }]),
188
+ ];
189
+ }
190
+ export function usageRows(s, sessionID) {
191
+ const inj = s.injected;
192
+ const per = inj.sessionRequests > 0
193
+ ? Math.round(inj.sessionTokens / inj.sessionRequests)
194
+ : inj.totalRequests > 0
195
+ ? Math.round(inj.totalTokens / inj.totalRequests)
196
+ : 0;
197
+ return [
198
+ { label: "Block size", value: per ? `~${formatTokens(per)} tokens / request` : "—" },
199
+ ...(sessionID
200
+ ? [{ label: "This session", value: `~${formatTokens(inj.sessionTokens)} tokens · ${inj.sessionRequests} req` }]
201
+ : []),
202
+ { label: "Since start", value: `~${formatTokens(inj.totalTokens)} tokens · ${inj.totalRequests} req` },
203
+ ];
204
+ }
205
+ export function configRows(s) {
206
+ return [
207
+ { label: "Extraction", value: s.extractModel ?? "Host default" },
208
+ { label: "Consolidation", value: s.consolidationModel ?? "Host default" },
209
+ { label: "Codex import", value: s.codexImport ? "On" : "Off", tone: s.codexImport ? "ok" : "muted" },
210
+ { label: "Location", value: s.memoryRoot },
211
+ ];
212
+ }
@@ -34,13 +34,15 @@ import { ensureV2Agents } from "./agents.js";
34
34
  import { buildV2Tools } from "./tools.js";
35
35
  import { performMemoryReset } from "../../tools/control.js";
36
36
  import { guardMemorySearchTools } from "./search-sandbox.js";
37
- import { MemoryStatusRpc } from "./status-rpc.js";
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
40
  import { recordInjection, resetInjectionStats } from "./injection.js";
40
41
  import { overlayV2CitationInstructions } from "./citation-overlay.js";
41
42
  import { estimateTokens } from "../token.js";
42
43
  const backgroundTasks = new Set();
43
44
  const statusListeners = new Set();
45
+ const RETRY_RESULT_LIFETIME_MS = 2 * 60_000;
44
46
  /**
45
47
  * The V2 host runs one plugin instance per location in the same process and
46
48
  * evicts idle locations independently. Process-wide state (lifecycle, shim
@@ -86,6 +88,7 @@ function trackBackgroundTask(task) {
86
88
  }
87
89
  /** Test seam: wait for hook-launched work to settle. */
88
90
  export async function waitForV2BackgroundTasks() {
91
+ await waitForMemoryRetry();
89
92
  while (backgroundTasks.size > 0) {
90
93
  await Promise.all([...backgroundTasks]);
91
94
  }
@@ -97,6 +100,7 @@ export function resetV2ModuleStateForTest() {
97
100
  clearTimeout(statusNotifyTimer);
98
101
  statusNotifyTimer = null;
99
102
  backgroundTasks.clear();
103
+ clearMemoryRetryResult();
100
104
  seenTurnSessions.clear();
101
105
  liveInstances.length = 0;
102
106
  activeConfig = undefined;
@@ -248,7 +252,10 @@ async function attach(ctx) {
248
252
  status: async (input) => {
249
253
  const sessionID = input?.sessionID;
250
254
  const minimum = input?.minConsolidatedThreads;
251
- return readMemoryStatus(typeof sessionID === "string" ? sessionID : null, minimum);
255
+ return {
256
+ ...readMemoryStatus(typeof sessionID === "string" ? sessionID : null, minimum),
257
+ manualRetry: memoryRetryStatus(RETRY_RESULT_LIFETIME_MS),
258
+ };
252
259
  },
253
260
  setOption: async (input) => {
254
261
  const { key, value } = (input ?? {});
@@ -301,11 +308,20 @@ async function attach(ctx) {
301
308
  return { ok: true };
302
309
  },
303
310
  consolidateNow: async () => {
311
+ if (memoryRetryStatus()?.state === "running")
312
+ return { status: "already_running", message: "A memory retry is in progress." };
304
313
  // Runs detached so the dialog does not block on a multi-minute turn.
305
314
  const run = consolidateNow();
306
315
  trackBackgroundTask(run.then(() => { }));
307
316
  return { status: "started" };
308
317
  },
318
+ retryFailed: async (input) => {
319
+ const phase = input?.phase;
320
+ if (!isMemoryRetryPhase(phase))
321
+ return { ok: false, message: "Choose extraction or consolidation to retry." };
322
+ const request = requestMemoryRetry(phase);
323
+ return request.ok ? { ok: true } : request;
324
+ },
309
325
  resetMemory: async (input) => {
310
326
  if (input?.confirm !== true)
311
327
  return { ok: false, message: "Reset not confirmed." };
@@ -440,6 +456,7 @@ async function attach(ctx) {
440
456
  console.warn("[opencode-codex-memory] orphaned phase2 sweep failed:", err);
441
457
  }
442
458
  statusListeners.add(publishStatus);
459
+ const unsubscribeRetry = onMemoryRetryChanged(publishStatus);
443
460
  // Event loop: execution.succeeded pumps phase 1 the way V1's idle events did.
444
461
  const eventAbort = new AbortController();
445
462
  void (async () => {
@@ -509,6 +526,7 @@ async function attach(ctx) {
509
526
  .finally(() => eventLoops.delete(eventAbort));
510
527
  eventLoops.add(eventAbort);
511
528
  return () => {
529
+ unsubscribeRetry();
512
530
  statusListeners.delete(publishStatus);
513
531
  eventAbort.abort();
514
532
  };
@@ -530,6 +548,7 @@ function releaseLocation(ctx) {
530
548
  draining = Promise.allSettled([abortActiveSubSessions(), waitForV2BackgroundTasks()]).then(() => {
531
549
  setSubSessionDirectory();
532
550
  setV2Context(null);
551
+ clearMemoryRetryResult();
533
552
  activeConfig = undefined;
534
553
  draining = undefined;
535
554
  invalidateCache();
@@ -1,11 +1,13 @@
1
1
  /**
2
- * Shared server↔TUI wire contract for the memory sidebar status.
2
+ * Shared server↔UI wire contract for the memory panels.
3
3
  *
4
4
  * Dependency-free on purpose: the TUI bundle runs in the CLI sandbox, where
5
5
  * only `@opencode/plugin/tui` (+ rendering peers) is guaranteed to resolve.
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";
10
+ export { MEMORY_NOTICE_KINDS, type MemoryNotice, type MemoryRetry, type MemoryRetryPhase } from "../recovery-info.js";
9
11
  export declare const MEMORY_STATUS_ACTIVITIES: readonly ["idle", "extracting", "consolidating", "retrying", "error", "read_only", "disabled", "stopping"];
10
12
  export type MemoryStatusActivity = (typeof MEMORY_STATUS_ACTIVITIES)[number];
11
13
  export interface MemoryStatus {
@@ -31,6 +33,7 @@ export interface MemoryStatus {
31
33
  phase2CooldownUntil?: number | null;
32
34
  phase1RetryAt?: number | null;
33
35
  phase2RetryAt?: number | null;
36
+ phase2LeaseUntil?: number | null;
34
37
  }[];
35
38
  useMemories: boolean;
36
39
  generateMemories: boolean;
@@ -40,6 +43,10 @@ export interface MemoryStatus {
40
43
  lastSuccessAt: number | null;
41
44
  retryAt: number | null;
42
45
  warnings: string[];
46
+ /** Typed guidance inputs. Older servers only send warning strings. */
47
+ notices?: MemoryNotice[];
48
+ /** Null when no recent request; absent on servers without manual retry support. */
49
+ manualRetry?: MemoryRetry | null;
43
50
  /** Per-session read/write mode when a sessionID was supplied. */
44
51
  sessionMode: "enabled" | "disabled" | "polluted" | null;
45
52
  /** Root directory of the memory workspace. */
@@ -147,6 +154,9 @@ export declare const MemoryStatusRpc: {
147
154
  readonly phase2RetryAt: {
148
155
  readonly type: readonly ["number", "null"];
149
156
  };
157
+ readonly phase2LeaseUntil: {
158
+ readonly type: readonly ["number", "null"];
159
+ };
150
160
  };
151
161
  readonly required: readonly ["version", "stage1Count", "extracting", "phase2Status", "lastError"];
152
162
  readonly additionalProperties: false;
@@ -176,6 +186,59 @@ export declare const MemoryStatusRpc: {
176
186
  readonly type: "string";
177
187
  };
178
188
  };
189
+ readonly notices: {
190
+ readonly type: "array";
191
+ readonly items: {
192
+ readonly type: "object";
193
+ readonly properties: {
194
+ readonly kind: {
195
+ readonly type: "string";
196
+ readonly enum: readonly ["extraction_exhausted", "consolidator_setup", "configuration", "discovery", "codex_import", "consolidation_failed", "extraction_retry", "provider_capacity"];
197
+ };
198
+ readonly detail: {
199
+ readonly type: "string";
200
+ };
201
+ readonly version: {
202
+ readonly type: "string";
203
+ readonly enum: readonly ["v1", "v2"];
204
+ };
205
+ readonly phase: {
206
+ readonly type: "string";
207
+ readonly enum: readonly ["extraction", "consolidation"];
208
+ };
209
+ readonly sessionID: {
210
+ readonly type: "string";
211
+ };
212
+ readonly retryAt: {
213
+ readonly type: "number";
214
+ };
215
+ readonly retryPhase: {
216
+ readonly type: "string";
217
+ readonly enum: readonly ["extraction", "consolidation"];
218
+ };
219
+ };
220
+ readonly required: readonly ["kind"];
221
+ readonly additionalProperties: false;
222
+ };
223
+ };
224
+ readonly manualRetry: {
225
+ readonly type: readonly ["object", "null"];
226
+ readonly properties: {
227
+ readonly phase: {
228
+ readonly type: "string";
229
+ readonly enum: readonly ["extraction", "consolidation"];
230
+ };
231
+ readonly state: {
232
+ readonly type: "string";
233
+ readonly enum: readonly ["running", "completed", "blocked", "failed"];
234
+ };
235
+ readonly message: {
236
+ readonly type: "string";
237
+ };
238
+ };
239
+ readonly required: readonly ["phase", "state", "message"];
240
+ readonly additionalProperties: false;
241
+ };
179
242
  readonly sessionMode: {
180
243
  readonly type: readonly ["string", "null"];
181
244
  readonly enum: readonly ["enabled", "disabled", "polluted", null];
@@ -274,11 +337,41 @@ export declare const MemoryStatusRpc: {
274
337
  readonly status: {
275
338
  readonly type: "string";
276
339
  };
340
+ readonly message: {
341
+ readonly type: "string";
342
+ };
277
343
  };
278
344
  readonly required: readonly ["status"];
279
345
  readonly additionalProperties: false;
280
346
  };
281
347
  };
348
+ /** Try failed work with current options. Progress and outcome appear in status. */
349
+ readonly retryFailed: {
350
+ readonly input: {
351
+ readonly type: "object";
352
+ readonly properties: {
353
+ readonly phase: {
354
+ readonly type: "string";
355
+ readonly enum: readonly ["extraction", "consolidation"];
356
+ };
357
+ };
358
+ readonly required: readonly ["phase"];
359
+ readonly additionalProperties: false;
360
+ };
361
+ readonly output: {
362
+ readonly type: "object";
363
+ readonly properties: {
364
+ readonly ok: {
365
+ readonly type: "boolean";
366
+ };
367
+ readonly message: {
368
+ readonly type: "string";
369
+ };
370
+ };
371
+ readonly required: readonly ["ok"];
372
+ readonly additionalProperties: false;
373
+ };
374
+ };
282
375
  /** Same wipe as the V1 memory_reset tool; the panel's confirm step is the approval. */
283
376
  readonly resetMemory: {
284
377
  readonly input: {
@@ -316,6 +409,7 @@ export declare const MemoryStatusRpc: {
316
409
  };
317
410
  };
318
411
  };
412
+ export declare function isMemoryRetryPhase(value: unknown): value is MemoryRetryPhase;
319
413
  /** Runtime guard for the untyped RPC client result (no zod in the TUI bundle). */
320
414
  export declare function isMemoryStatus(value: unknown): value is MemoryStatus;
321
415
  /** Throwing parser for tests and call sites that want a typed value. */