opencode-codex-memory 0.10.1 → 0.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -12
- package/dist/src/agent-health.js +10 -7
- package/dist/src/capture.js +7 -7
- package/dist/src/citation.js +12 -3
- package/dist/src/claude-import.js +1 -3
- package/dist/src/codex-interop.js +20 -5
- package/dist/src/db.d.ts +0 -2
- package/dist/src/db.js +0 -4
- package/dist/src/git-baseline.d.ts +4 -6
- package/dist/src/git-baseline.js +45 -68
- package/dist/src/host-client.d.ts +5 -0
- package/dist/src/host-client.js +24 -0
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.js +56 -99
- package/dist/src/llm.d.ts +4 -1
- package/dist/src/llm.js +41 -13
- package/dist/src/options.d.ts +7 -0
- package/dist/src/options.js +20 -2
- package/dist/src/paths.d.ts +1 -0
- package/dist/src/paths.js +5 -2
- package/dist/src/phase1.js +12 -21
- package/dist/src/phase2.js +3 -3
- package/dist/src/reasoning-variant.d.ts +7 -0
- package/dist/src/reasoning-variant.js +11 -2
- package/dist/src/rollout-input.js +3 -5
- package/dist/src/session-version.js +4 -5
- package/dist/src/source.js +6 -2
- package/dist/src/store.d.ts +3 -2
- package/dist/src/store.js +72 -47
- package/dist/src/v2/agents.js +11 -14
- package/dist/src/v2/model-readiness.js +3 -1
- package/dist/src/v2/plugin.js +81 -109
- package/dist/src/v2/search-sandbox.js +1 -1
- package/dist/src/v2/service.js +5 -0
- package/dist/src/v2/shim.d.ts +3 -0
- package/dist/src/v2/shim.js +144 -90
- package/dist/src/v2/status-rpc.js +40 -14
- package/dist/src/v2/status.js +4 -7
- package/dist/src/v2/tools.d.ts +15 -9
- package/dist/src/v2/tools.js +9 -9
- package/dist/src/v2/tui.js +14 -4
- package/dist/src/workspace.js +13 -4
- package/dist/tools/control.js +29 -28
- package/dist/tools/memory.js +163 -89
- package/package.json +22 -9
package/dist/src/store.d.ts
CHANGED
|
@@ -41,7 +41,7 @@ export type Phase2ClaimResult = {
|
|
|
41
41
|
type: "skipped_retry_unavailable";
|
|
42
42
|
};
|
|
43
43
|
/** Wipe jobs/outputs in every versioned DB. Leaves memory_session_meta on memory.db. */
|
|
44
|
-
export declare function clearAllVersionMemoryData(): void;
|
|
44
|
+
export declare function clearAllVersionMemoryData(wipeWorkspace: () => void): void;
|
|
45
45
|
/** Include inactive existing stores for deletion, reset guards and diagnostics. */
|
|
46
46
|
export declare function existingMemoryStores(): MemoryStore[];
|
|
47
47
|
export declare const PHASE2_HEARTBEAT_SECONDS = 90;
|
|
@@ -92,6 +92,7 @@ export declare class MemoryStore {
|
|
|
92
92
|
claimGlobalPhase2Job(opts?: {
|
|
93
93
|
bypassCooldown?: boolean;
|
|
94
94
|
}): Phase2ClaimResult;
|
|
95
|
+
private claimPhase2;
|
|
95
96
|
heartbeatPhase2Job(ownershipToken: string): boolean;
|
|
96
97
|
/**
|
|
97
98
|
* Marks the phase-2 job done and records exactly which stage-1 snapshots the
|
|
@@ -165,7 +166,7 @@ export declare class MemoryStore {
|
|
|
165
166
|
* surface is model-invoked mid-session, so hooks can race the wipe.
|
|
166
167
|
*/
|
|
167
168
|
clearMemoryData(): void;
|
|
168
|
-
setMemoryMode(sessionId: string, mode: "enabled" | "disabled" | "polluted"): void;
|
|
169
|
+
setMemoryMode(sessionId: string, mode: "enabled" | "disabled" | "polluted", approvedRestore?: boolean): void;
|
|
169
170
|
/**
|
|
170
171
|
* Stamp a mode only when the session has no meta row yet — used to mark
|
|
171
172
|
* sessions seen while generate_memories=false as permanently 'disabled'
|
package/dist/src/store.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import fs from "fs";
|
|
2
2
|
import os from "os";
|
|
3
|
-
import { openDb, openSessionMetaDb
|
|
4
|
-
import {
|
|
3
|
+
import { openDb, openSessionMetaDb } from "./db.js";
|
|
4
|
+
import { memoryDbPath } from "./paths.js";
|
|
5
5
|
import { currentMemoryVersion, MEMORY_VERSIONS, withMemoryVersion } from "./memory-version.js";
|
|
6
6
|
import { isProviderCapacityError } from "./ratelimit.js";
|
|
7
7
|
export const DEFAULT_RETRY_REMAINING = 3;
|
|
@@ -19,31 +19,33 @@ function clearJobTables(db) {
|
|
|
19
19
|
db.run("DELETE FROM memory_jobs");
|
|
20
20
|
db.run("DELETE FROM memory_citation_usage");
|
|
21
21
|
db.run("UPDATE consolidation_progress SET max_thread_count = 0");
|
|
22
|
-
db
|
|
23
|
-
.prepare(`INSERT INTO memory_jobs
|
|
22
|
+
db.prepare(`INSERT INTO memory_jobs
|
|
24
23
|
(kind, job_key, status, finished_at, last_error, retry_remaining, last_success_watermark)
|
|
25
|
-
VALUES ('memory_consolidate_global', 'global', 'done', ?, NULL, ?, 0)`)
|
|
26
|
-
.run(nowSec(), DEFAULT_RETRY_REMAINING);
|
|
24
|
+
VALUES ('memory_consolidate_global', 'global', 'done', ?, NULL, ?, 0)`).run(nowSec(), DEFAULT_RETRY_REMAINING);
|
|
27
25
|
}).immediate();
|
|
28
26
|
}
|
|
29
27
|
/** Wipe jobs/outputs in every versioned DB. Leaves memory_session_meta on memory.db. */
|
|
30
|
-
export function clearAllVersionMemoryData() {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
28
|
+
export function clearAllVersionMemoryData(wipeWorkspace) {
|
|
29
|
+
const catalog = openSessionMetaDb();
|
|
30
|
+
catalog
|
|
31
|
+
.transaction(() => {
|
|
32
|
+
const stores = existingMemoryStores();
|
|
33
|
+
for (const store of stores) {
|
|
34
|
+
const job = store.phase2JobSnapshot();
|
|
35
|
+
if (job?.status === "running" && (job.lease_until === null || job.lease_until > nowSec())) {
|
|
36
|
+
throw new Error(`Reset refused: ${store.version} memory consolidation has an active lease.`);
|
|
37
|
+
}
|
|
40
38
|
}
|
|
41
|
-
|
|
39
|
+
// No peer can claim either version until the filesystem wipe finishes.
|
|
40
|
+
wipeWorkspace();
|
|
41
|
+
for (const store of stores)
|
|
42
|
+
store.clearMemoryData();
|
|
43
|
+
})
|
|
44
|
+
.immediate();
|
|
42
45
|
}
|
|
43
46
|
/** Include inactive existing stores for deletion, reset guards and diagnostics. */
|
|
44
47
|
export function existingMemoryStores() {
|
|
45
|
-
return MEMORY_VERSIONS.filter((version) => version === "v1" || fs.existsSync(memoryDbPath(version)))
|
|
46
|
-
.map((version) => withMemoryVersion(version, () => new MemoryStore()));
|
|
48
|
+
return MEMORY_VERSIONS.filter((version) => version === "v1" || fs.existsSync(memoryDbPath(version))).map((version) => withMemoryVersion(version, () => new MemoryStore()));
|
|
47
49
|
}
|
|
48
50
|
function newId() {
|
|
49
51
|
return crypto.randomUUID();
|
|
@@ -103,9 +105,7 @@ export class MemoryStore {
|
|
|
103
105
|
return this.db.prepare("SELECT COUNT(*) AS count FROM memory_stage1_outputs").get().count;
|
|
104
106
|
}
|
|
105
107
|
hasStage1Output(sessionId) {
|
|
106
|
-
return this.db
|
|
107
|
-
.prepare("SELECT 1 FROM memory_stage1_outputs WHERE session_id = ?")
|
|
108
|
-
.get(sessionId) !== null;
|
|
108
|
+
return this.db.prepare("SELECT 1 FROM memory_stage1_outputs WHERE session_id = ?").get(sessionId) !== null;
|
|
109
109
|
}
|
|
110
110
|
/**
|
|
111
111
|
* Deletes stale rows; snapshots consumed by the last successful Phase 2 are
|
|
@@ -162,10 +162,12 @@ export class MemoryStore {
|
|
|
162
162
|
// upgrade failure under cross-process access.
|
|
163
163
|
const ts = now();
|
|
164
164
|
const stmt = this.db.prepare("UPDATE memory_stage1_outputs SET usage_count = usage_count + 1, last_usage = ? WHERE session_id = ?");
|
|
165
|
-
this.db
|
|
165
|
+
this.db
|
|
166
|
+
.transaction(() => {
|
|
166
167
|
for (const id of sessionIds)
|
|
167
168
|
stmt.run(ts, id);
|
|
168
|
-
})
|
|
169
|
+
})
|
|
170
|
+
.immediate();
|
|
169
171
|
}
|
|
170
172
|
/**
|
|
171
173
|
* Record citations from a durable assistant message exactly once. V2 can
|
|
@@ -182,7 +184,8 @@ export class MemoryStore {
|
|
|
182
184
|
VALUES (?, ?, ?, ?)`);
|
|
183
185
|
const update = this.db.prepare("UPDATE memory_stage1_outputs SET usage_count = usage_count + 1, last_usage = ? WHERE session_id = ?");
|
|
184
186
|
const ts = now();
|
|
185
|
-
this.db
|
|
187
|
+
this.db
|
|
188
|
+
.transaction(() => {
|
|
186
189
|
for (const citedSessionId of ids) {
|
|
187
190
|
const result = insert.run(sessionId, assistantMessageId, citedSessionId, ts);
|
|
188
191
|
if (result.changes === 0)
|
|
@@ -197,7 +200,8 @@ export class MemoryStore {
|
|
|
197
200
|
.run(sessionId, assistantMessageId, citedSessionId);
|
|
198
201
|
}
|
|
199
202
|
}
|
|
200
|
-
})
|
|
203
|
+
})
|
|
204
|
+
.immediate();
|
|
201
205
|
return fresh;
|
|
202
206
|
}
|
|
203
207
|
claimStage1Jobs(sessions, excludeSession, maxClaimed) {
|
|
@@ -263,7 +267,8 @@ export class MemoryStore {
|
|
|
263
267
|
return claimed;
|
|
264
268
|
}
|
|
265
269
|
markStage1Succeeded(sessionId, ownershipToken, out) {
|
|
266
|
-
this.db
|
|
270
|
+
this.db
|
|
271
|
+
.transaction(() => {
|
|
267
272
|
const res = this.db
|
|
268
273
|
.prepare(`UPDATE memory_jobs SET status='done', finished_at=?, lease_until=NULL, last_error=NULL,
|
|
269
274
|
last_success_watermark=?, retry_at=NULL
|
|
@@ -275,11 +280,13 @@ export class MemoryStore {
|
|
|
275
280
|
this.upsertStage1Output(out);
|
|
276
281
|
this.enqueueGlobalConsolidation(out.source_updated_at);
|
|
277
282
|
}
|
|
278
|
-
})
|
|
283
|
+
})
|
|
284
|
+
.immediate();
|
|
279
285
|
}
|
|
280
286
|
/** Extraction succeeded but produced nothing worth keeping: finish the job and drop any stale output. */
|
|
281
287
|
markStage1SucceededNoOutput(sessionId, ownershipToken, sourceUpdatedAt) {
|
|
282
|
-
this.db
|
|
288
|
+
this.db
|
|
289
|
+
.transaction(() => {
|
|
283
290
|
const res = this.db
|
|
284
291
|
.prepare(`UPDATE memory_jobs SET status='done', finished_at=?, lease_until=NULL, last_error=NULL,
|
|
285
292
|
last_success_watermark=?, retry_at=NULL
|
|
@@ -290,7 +297,8 @@ export class MemoryStore {
|
|
|
290
297
|
const deleted = this.db.prepare("DELETE FROM memory_stage1_outputs WHERE session_id = ?").run(sessionId);
|
|
291
298
|
if (deleted.changes > 0)
|
|
292
299
|
this.enqueueGlobalConsolidation(sourceUpdatedAt);
|
|
293
|
-
})
|
|
300
|
+
})
|
|
301
|
+
.immediate();
|
|
294
302
|
}
|
|
295
303
|
markStage1Failed(sessionId, ownershipToken, error) {
|
|
296
304
|
const message = failureMessage(error);
|
|
@@ -337,13 +345,15 @@ export class MemoryStore {
|
|
|
337
345
|
let n = 0;
|
|
338
346
|
const stmt = this.db.prepare(`UPDATE memory_jobs SET status='pending', retry_remaining=?
|
|
339
347
|
WHERE kind='memory_stage1' AND job_key=? AND status='failed'`);
|
|
340
|
-
this.db
|
|
348
|
+
this.db
|
|
349
|
+
.transaction(() => {
|
|
341
350
|
for (const row of rows) {
|
|
342
351
|
if (!isProviderCapacityError(row.last_error))
|
|
343
352
|
continue;
|
|
344
353
|
n += stmt.run(DEFAULT_RETRY_REMAINING, row.job_key).changes;
|
|
345
354
|
}
|
|
346
|
-
})
|
|
355
|
+
})
|
|
356
|
+
.immediate();
|
|
347
357
|
return n;
|
|
348
358
|
}
|
|
349
359
|
/**
|
|
@@ -389,6 +399,13 @@ export class MemoryStore {
|
|
|
389
399
|
.run(DEFAULT_RETRY_REMAINING, inputWatermark);
|
|
390
400
|
}
|
|
391
401
|
claimGlobalPhase2Job(opts = {}) {
|
|
402
|
+
// V1 already claims under the shared catalog write lock. Take that same
|
|
403
|
+
// lock first for V2, including its very first claim after a reset.
|
|
404
|
+
return this.meta === this.db
|
|
405
|
+
? this.claimPhase2(opts)
|
|
406
|
+
: this.meta.transaction(() => this.claimPhase2(opts)).immediate();
|
|
407
|
+
}
|
|
408
|
+
claimPhase2(opts) {
|
|
392
409
|
const workerId = phase2WorkerId();
|
|
393
410
|
const ownershipToken = newId();
|
|
394
411
|
const tNow = nowSec();
|
|
@@ -458,7 +475,8 @@ export class MemoryStore {
|
|
|
458
475
|
// mark_global_phase2_job_succeeded does the same): a crash between them
|
|
459
476
|
// must not leave a done job whose retention flags still describe the
|
|
460
477
|
// previous run — pruning could then delete inputs backing the artifacts.
|
|
461
|
-
this.db
|
|
478
|
+
this.db
|
|
479
|
+
.transaction(() => {
|
|
462
480
|
const res = this.db
|
|
463
481
|
.prepare(`UPDATE memory_jobs SET status='done', finished_at=?, lease_until=NULL, last_error=NULL, retry_remaining=?,
|
|
464
482
|
last_success_watermark=MAX(COALESCE(last_success_watermark, 0), ?), retry_at=NULL
|
|
@@ -466,7 +484,8 @@ export class MemoryStore {
|
|
|
466
484
|
.run(nowSec(), DEFAULT_RETRY_REMAINING, watermark, ownershipToken);
|
|
467
485
|
if (res.changes === 0)
|
|
468
486
|
return;
|
|
469
|
-
this.db
|
|
487
|
+
this.db
|
|
488
|
+
.prepare("UPDATE consolidation_progress SET max_thread_count = MAX(max_thread_count, ?)")
|
|
470
489
|
.run(new Set(selected.map((s) => s.session_id)).size);
|
|
471
490
|
this.db.run("UPDATE memory_stage1_outputs SET selected_for_phase2 = 0, selected_for_phase2_source_updated_at = NULL");
|
|
472
491
|
const mark = this.db.prepare(`UPDATE memory_stage1_outputs
|
|
@@ -474,12 +493,12 @@ export class MemoryStore {
|
|
|
474
493
|
WHERE session_id = ? AND source_updated_at = ?`);
|
|
475
494
|
for (const s of selected)
|
|
476
495
|
mark.run(s.source_updated_at, s.session_id, s.source_updated_at);
|
|
477
|
-
})
|
|
496
|
+
})
|
|
497
|
+
.immediate();
|
|
478
498
|
}
|
|
479
499
|
/** High-water mark of distinct sessions consumed by one successful run. */
|
|
480
500
|
maxConsolidatedThreadCount() {
|
|
481
|
-
return this.db.prepare("SELECT max_thread_count FROM consolidation_progress WHERE singleton = 1")
|
|
482
|
-
.get().max_thread_count;
|
|
501
|
+
return this.db.prepare("SELECT max_thread_count FROM consolidation_progress WHERE singleton = 1").get().max_thread_count;
|
|
483
502
|
}
|
|
484
503
|
/**
|
|
485
504
|
* Phase-2 job snapshot for memory_inspect. Always returns the global job row
|
|
@@ -495,9 +514,7 @@ export class MemoryStore {
|
|
|
495
514
|
.get();
|
|
496
515
|
if (!row)
|
|
497
516
|
return null;
|
|
498
|
-
const cleanSuccess = row.last_error === null &&
|
|
499
|
-
row.finished_at !== null &&
|
|
500
|
-
(row.status === "done" || row.status === "pending");
|
|
517
|
+
const cleanSuccess = row.last_error === null && row.finished_at !== null && (row.status === "done" || row.status === "pending");
|
|
501
518
|
// Codex initializes pending global jobs with watermark 0, so zero proves a
|
|
502
519
|
// success only while the row itself is a clean completed attempt.
|
|
503
520
|
const watermark = row.last_success_watermark === null
|
|
@@ -648,7 +665,8 @@ export class MemoryStore {
|
|
|
648
665
|
* job, then enqueue forgetting if phase 2 had consumed that output.
|
|
649
666
|
*/
|
|
650
667
|
deleteSessionMemory(sessionId) {
|
|
651
|
-
return this.db
|
|
668
|
+
return this.db
|
|
669
|
+
.transaction(() => {
|
|
652
670
|
const existing = this.db
|
|
653
671
|
.prepare("SELECT selected_for_phase2 FROM memory_stage1_outputs WHERE session_id = ?")
|
|
654
672
|
.get(sessionId);
|
|
@@ -658,7 +676,8 @@ export class MemoryStore {
|
|
|
658
676
|
if (shouldConsolidate)
|
|
659
677
|
this.enqueueGlobalConsolidation(now());
|
|
660
678
|
return shouldConsolidate;
|
|
661
|
-
})
|
|
679
|
+
})
|
|
680
|
+
.immediate();
|
|
662
681
|
}
|
|
663
682
|
/**
|
|
664
683
|
* codex clear_memory_data deletes extracted memories and jobs but explicitly
|
|
@@ -675,12 +694,18 @@ export class MemoryStore {
|
|
|
675
694
|
clearMemoryData() {
|
|
676
695
|
clearJobTables(this.db);
|
|
677
696
|
}
|
|
678
|
-
setMemoryMode(sessionId, mode) {
|
|
679
|
-
|
|
697
|
+
setMemoryMode(sessionId, mode, approvedRestore = false) {
|
|
698
|
+
if (mode === "polluted")
|
|
699
|
+
return this.markPolluted(sessionId);
|
|
700
|
+
const updated = this.meta
|
|
680
701
|
.prepare(`INSERT INTO memory_session_meta (session_id, memory_mode, polluted, updated_at)
|
|
681
|
-
VALUES (?, ?,
|
|
682
|
-
ON CONFLICT(session_id) DO UPDATE SET memory_mode=excluded.memory_mode,
|
|
683
|
-
|
|
702
|
+
VALUES (?, ?, 0, ?)
|
|
703
|
+
ON CONFLICT(session_id) DO UPDATE SET memory_mode=excluded.memory_mode,
|
|
704
|
+
polluted=CASE WHEN excluded.memory_mode='enabled' THEN 0 ELSE polluted END, updated_at=excluded.updated_at
|
|
705
|
+
WHERE excluded.memory_mode='disabled' OR polluted=0 OR ?`)
|
|
706
|
+
.run(sessionId, mode, now(), approvedRestore ? 1 : 0);
|
|
707
|
+
if (!updated.changes)
|
|
708
|
+
throw new Error("Restoring learning for this session requires approval.");
|
|
684
709
|
}
|
|
685
710
|
/**
|
|
686
711
|
* Stamp a mode only when the session has no meta row yet — used to mark
|
package/dist/src/v2/agents.js
CHANGED
|
@@ -47,17 +47,16 @@ export function buildMemorizeAgent() {
|
|
|
47
47
|
* store. Pass the same directory the session is created in.
|
|
48
48
|
*/
|
|
49
49
|
export function consolidationPermissions(root, sessionDir) {
|
|
50
|
-
return [
|
|
51
|
-
{ action: "*", resource: "*", effect: "deny" },
|
|
52
|
-
...workspacePermissions(root, sessionDir),
|
|
53
|
-
];
|
|
50
|
+
return [{ action: "*", resource: "*", effect: "deny" }, ...workspacePermissions(root, sessionDir)];
|
|
54
51
|
}
|
|
55
52
|
function workspacePermissions(root, sessionDir) {
|
|
56
53
|
const absolute = [root, path.join(root, "*")];
|
|
57
54
|
return [
|
|
58
55
|
...sessionRelativePermissions(root, sessionDir),
|
|
59
56
|
...["read", "edit", "external_directory"].flatMap((action) => absolute.map((resource) => ({
|
|
60
|
-
action,
|
|
57
|
+
action,
|
|
58
|
+
resource,
|
|
59
|
+
effect: "allow",
|
|
61
60
|
}))),
|
|
62
61
|
// These actions check the search pattern, not a path. search-sandbox.ts
|
|
63
62
|
// wraps the built-in executors to enforce this helper's single root.
|
|
@@ -79,10 +78,12 @@ function sessionRelativePermissions(root, sessionDir) {
|
|
|
79
78
|
const posix = rel.split(path.sep).join("/");
|
|
80
79
|
const inside = !posix || posix.split("/").every((seg) => seg === "..");
|
|
81
80
|
const escape = posix ? `${posix}/..` : "..";
|
|
82
|
-
return ["read", "edit"].flatMap((action) => inside
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
81
|
+
return ["read", "edit"].flatMap((action) => inside
|
|
82
|
+
? [
|
|
83
|
+
{ action, resource: "*", effect: "allow" },
|
|
84
|
+
...["/*", "?:/*", escape, `${escape}/*`].map((resource) => ({ action, resource, effect: "deny" })),
|
|
85
|
+
]
|
|
86
|
+
: [posix, `${posix}/*`].map((resource) => ({ action, resource, effect: "allow" })));
|
|
86
87
|
}
|
|
87
88
|
/**
|
|
88
89
|
* Hidden extraction definition. Unused at runtime (extraction goes through
|
|
@@ -204,11 +205,7 @@ export async function ensureV2Agents(ctx) {
|
|
|
204
205
|
recordAgentConfig({ agent: effective }, true, shippedV1AgentForHealth());
|
|
205
206
|
}
|
|
206
207
|
function isShippedIncomplete(id, existing, shipped) {
|
|
207
|
-
const system = typeof existing.system === "string"
|
|
208
|
-
? existing.system
|
|
209
|
-
: typeof existing.prompt === "string"
|
|
210
|
-
? existing.prompt
|
|
211
|
-
: "";
|
|
208
|
+
const system = typeof existing.system === "string" ? existing.system : typeof existing.prompt === "string" ? existing.prompt : "";
|
|
212
209
|
if (system !== shipped.system)
|
|
213
210
|
return false;
|
|
214
211
|
if (typeof existing.description === "string" && existing.description !== shipped.description)
|
|
@@ -17,7 +17,9 @@ export function isModelSelectionUnavailable(error, model) {
|
|
|
17
17
|
const tag = current._tag ?? current.name;
|
|
18
18
|
if (["InvalidRequestError", "Generate.ModelSelectionError"].includes(tag) && current.message === message)
|
|
19
19
|
return true;
|
|
20
|
-
if (tag === "ServiceUnavailableError" &&
|
|
20
|
+
if (tag === "ServiceUnavailableError" &&
|
|
21
|
+
current.service === "plugin" &&
|
|
22
|
+
current.message === PLUGIN_ACTIVATION_PENDING)
|
|
21
23
|
return true;
|
|
22
24
|
}
|
|
23
25
|
return false;
|
package/dist/src/v2/plugin.js
CHANGED
|
@@ -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,
|
|
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 {
|
|
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
|
-
|
|
55
|
-
|
|
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
|
-
|
|
277
|
-
|
|
278
|
-
//
|
|
279
|
-
|
|
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
|
-
|
|
285
|
-
|
|
286
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
})()
|
|
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
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
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
|
-
|
|
557
|
-
|
|
558
|
-
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
beginPluginShutdown();
|
|
530
|
+
draining = Promise.allSettled([abortActiveSubSessions(), waitForV2BackgroundTasks()]).then(() => {
|
|
559
531
|
setSubSessionDirectory();
|
|
560
532
|
setV2Context(null);
|
|
561
|
-
|
|
562
|
-
|
|
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.
|
package/dist/src/v2/service.js
CHANGED
|
@@ -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. */
|