opencode-codex-memory 0.10.1 → 0.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +10 -12
  2. package/dist/src/agent-health.js +10 -7
  3. package/dist/src/capture.js +7 -7
  4. package/dist/src/citation.js +12 -3
  5. package/dist/src/claude-import.js +1 -3
  6. package/dist/src/codex-interop.js +20 -5
  7. package/dist/src/db.d.ts +0 -2
  8. package/dist/src/db.js +0 -4
  9. package/dist/src/git-baseline.d.ts +4 -6
  10. package/dist/src/git-baseline.js +45 -68
  11. package/dist/src/host-client.d.ts +5 -0
  12. package/dist/src/host-client.js +24 -0
  13. package/dist/src/index.d.ts +4 -145
  14. package/dist/src/index.js +56 -99
  15. package/dist/src/llm.d.ts +4 -1
  16. package/dist/src/llm.js +41 -13
  17. package/dist/src/options.d.ts +7 -0
  18. package/dist/src/options.js +20 -2
  19. package/dist/src/paths.d.ts +1 -0
  20. package/dist/src/paths.js +5 -2
  21. package/dist/src/phase1.js +12 -21
  22. package/dist/src/phase2.js +3 -3
  23. package/dist/src/reasoning-variant.d.ts +7 -0
  24. package/dist/src/reasoning-variant.js +11 -2
  25. package/dist/src/rollout-input.js +3 -5
  26. package/dist/src/session-version.js +4 -5
  27. package/dist/src/source.js +6 -2
  28. package/dist/src/store.d.ts +3 -2
  29. package/dist/src/store.js +72 -47
  30. package/dist/src/v2/agents.js +11 -14
  31. package/dist/src/v2/model-readiness.js +9 -1
  32. package/dist/src/v2/plugin.js +81 -109
  33. package/dist/src/v2/search-sandbox.js +1 -1
  34. package/dist/src/v2/service.js +5 -0
  35. package/dist/src/v2/shim.d.ts +3 -0
  36. package/dist/src/v2/shim.js +144 -90
  37. package/dist/src/v2/status-rpc.js +40 -14
  38. package/dist/src/v2/status.js +4 -7
  39. package/dist/src/v2/tools.d.ts +20 -14
  40. package/dist/src/v2/tools.js +14 -14
  41. package/dist/src/v2/tui.js +14 -4
  42. package/dist/src/workspace.js +13 -4
  43. package/dist/tools/control.d.ts +4 -33
  44. package/dist/tools/control.js +29 -28
  45. package/dist/tools/memory.d.ts +5 -70
  46. package/dist/tools/memory.js +164 -89
  47. package/package.json +32 -20
@@ -1,4 +1,4 @@
1
- import type { PluginInput, PluginOptions } from "@opencode-ai/plugin";
1
+ import type { PluginInput, PluginOptions, ToolDefinition } from "@opencode-ai/plugin";
2
2
  /** Test seam: wait for all hook-launched work, including follow-up phase 2. */
3
3
  export declare function waitForBackgroundTasks(): Promise<void>;
4
4
  /**
@@ -19,149 +19,8 @@ declare const _default: {
19
19
  id: string;
20
20
  setup: typeof setupV2;
21
21
  server(input: PluginInput, opts?: PluginOptions): Promise<{
22
- tool: {
23
- memory_read: {
24
- description: string;
25
- args: {
26
- path: import("zod").ZodString;
27
- line_offset: import("zod").ZodOptional<import("zod").ZodNumber>;
28
- max_lines: import("zod").ZodOptional<import("zod").ZodNumber>;
29
- };
30
- execute(args: {
31
- path: string;
32
- line_offset?: number | undefined;
33
- max_lines?: number | undefined;
34
- }, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
35
- };
36
- memory_search: {
37
- description: string;
38
- args: {
39
- queries: import("zod").ZodOptional<import("zod").ZodArray<import("zod").ZodString>>;
40
- match_mode: import("zod").ZodDefault<import("zod").ZodEnum<{
41
- any: "any";
42
- all_on_same_line: "all_on_same_line";
43
- all_within_lines: "all_within_lines";
44
- }>>;
45
- line_count: import("zod").ZodOptional<import("zod").ZodNumber>;
46
- path: import("zod").ZodOptional<import("zod").ZodString>;
47
- cursor: import("zod").ZodOptional<import("zod").ZodString>;
48
- context_lines: import("zod").ZodDefault<import("zod").ZodNumber>;
49
- case_sensitive: import("zod").ZodDefault<import("zod").ZodBoolean>;
50
- normalized: import("zod").ZodDefault<import("zod").ZodBoolean>;
51
- since: import("zod").ZodOptional<import("zod").ZodString>;
52
- until: import("zod").ZodOptional<import("zod").ZodString>;
53
- max_results: import("zod").ZodDefault<import("zod").ZodNumber>;
54
- };
55
- execute(args: {
56
- match_mode: "any" | "all_on_same_line" | "all_within_lines";
57
- context_lines: number;
58
- case_sensitive: boolean;
59
- normalized: boolean;
60
- max_results: number;
61
- queries?: string[] | undefined;
62
- line_count?: number | undefined;
63
- path?: string | undefined;
64
- cursor?: string | undefined;
65
- since?: string | undefined;
66
- until?: string | undefined;
67
- }, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
68
- };
69
- memory_list: {
70
- description: string;
71
- args: {
72
- path: import("zod").ZodDefault<import("zod").ZodString>;
73
- cursor: import("zod").ZodOptional<import("zod").ZodString>;
74
- max_results: import("zod").ZodDefault<import("zod").ZodNumber>;
75
- };
76
- execute(args: {
77
- path: string;
78
- max_results: number;
79
- cursor?: string | undefined;
80
- }, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
81
- };
82
- memory_add_note: {
83
- description: string;
84
- args: {
85
- note: import("zod").ZodString;
86
- title: import("zod").ZodOptional<import("zod").ZodString>;
87
- };
88
- execute(args: {
89
- note: string;
90
- title?: string | undefined;
91
- }, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
92
- };
93
- memory_reset: {
94
- description: string;
95
- args: {
96
- confirm: import("zod").ZodBoolean;
97
- };
98
- execute(args: {
99
- confirm: boolean;
100
- }, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
101
- };
102
- memory_inspect: {
103
- description: string;
104
- args: {
105
- min_consolidated_threads: import("zod").ZodOptional<import("zod").ZodNumber>;
106
- };
107
- execute(args: {
108
- min_consolidated_threads?: number | undefined;
109
- }, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
110
- };
111
- memory_mode: {
112
- description: string;
113
- args: {
114
- mode: import("zod").ZodEnum<{
115
- enabled: "enabled";
116
- disabled: "disabled";
117
- polluted: "polluted";
118
- }>;
119
- sessionId: import("zod").ZodOptional<import("zod").ZodString>;
120
- };
121
- execute(args: {
122
- mode: "enabled" | "disabled" | "polluted";
123
- sessionId?: string | undefined;
124
- }, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
125
- };
126
- } | {
127
- memory_reset: {
128
- description: string;
129
- args: {
130
- confirm: import("zod").ZodBoolean;
131
- };
132
- execute(args: {
133
- confirm: boolean;
134
- }, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
135
- };
136
- memory_inspect: {
137
- description: string;
138
- args: {
139
- min_consolidated_threads: import("zod").ZodOptional<import("zod").ZodNumber>;
140
- };
141
- execute(args: {
142
- min_consolidated_threads?: number | undefined;
143
- }, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
144
- };
145
- memory_mode: {
146
- description: string;
147
- args: {
148
- mode: import("zod").ZodEnum<{
149
- enabled: "enabled";
150
- disabled: "disabled";
151
- polluted: "polluted";
152
- }>;
153
- sessionId: import("zod").ZodOptional<import("zod").ZodString>;
154
- };
155
- execute(args: {
156
- mode: "enabled" | "disabled" | "polluted";
157
- sessionId?: string | undefined;
158
- }, context: import("@opencode-ai/plugin").ToolContext): Promise<import("@opencode-ai/plugin").ToolResult>;
159
- };
160
- memory_read?: undefined;
161
- memory_search?: undefined;
162
- memory_list?: undefined;
163
- memory_add_note?: undefined;
164
- };
22
+ dispose(): Promise<void>;
23
+ tool: MemoryTools;
165
24
  config(input: {
166
25
  agent?: Record<string, unknown>;
167
26
  }): Promise<void>;
@@ -238,7 +97,6 @@ declare const _default: {
238
97
  properties: unknown;
239
98
  };
240
99
  }): Promise<void>;
241
- dispose(): Promise<void>;
242
100
  }>;
243
101
  };
244
102
  export default _default;
@@ -261,3 +119,4 @@ export declare function applyPluginOptions(opts: PluginOptions, { modelFallback
261
119
  export declare function injectAgentDefinitions(config: {
262
120
  agent?: Record<string, unknown>;
263
121
  }): void;
122
+ type MemoryTools = Record<"memory_reset" | "memory_inspect" | "memory_mode", ToolDefinition> & Partial<Record<"memory_read" | "memory_search" | "memory_list" | "memory_add_note", ToolDefinition>>;
package/dist/src/index.js CHANGED
@@ -10,12 +10,14 @@ import { writeMemoryVersions } from "./memory-version.js";
10
10
  import { sessionMemoryVersion, withSessionMemoryVersion } from "./session-version.js";
11
11
  import { existingMemoryStores } from "./store.js";
12
12
  import { setPluginInput, cleanupOldSubSessions, isMemorySubSession, abortActiveSubSessions } from "./llm.js";
13
- import { pluginOptions, recordConfigWarning, clearConfigWarnings, resetPluginOptions, modelList } from "./options.js";
13
+ import { pluginOptions, recordConfigWarning, clearConfigWarnings, resetPluginOptions, modelList, reserveMemoryConfig, } from "./options.js";
14
14
  import { beginPluginShutdown, resetPluginLifecycle } from "./lifecycle.js";
15
- import { hostMcpStatus } from "./host-client.js";
15
+ import { externalContextClassifier, hostMcpStatus } from "./host-client.js";
16
16
  import { loadBundledAgentDefinitions, recordAgentConfig, resetAgentHealth } from "./agent-health.js";
17
17
  import path from "path";
18
- let pluginClient = null;
18
+ const hosts = [];
19
+ let hostConfig;
20
+ let draining;
19
21
  const backgroundTasks = new Set();
20
22
  function trackBackgroundTask(task) {
21
23
  // Hooks must remain non-blocking, but test teardown needs a way to wait until
@@ -32,9 +34,6 @@ export async function waitForBackgroundTasks() {
32
34
  await Promise.all([...backgroundTasks]);
33
35
  }
34
36
  }
35
- // Single-flight guard for mcp.status(); see mcpToolPrefixes below.
36
- let mcpStatusInFlight = null;
37
- const MCP_STATUS_TIMEOUT_MS = 1_000;
38
37
  // Deliberately uncached: openDb() is already a singleton, and caching a store
39
38
  // here would hold a stale handle across closeDb() (e.g. after memory_reset).
40
39
  function getStore() {
@@ -115,8 +114,10 @@ export function handleSessionDeleted(sessionId, store,
115
114
  // attempt could only fail; the row deletion above still happens, and the
116
115
  // enqueued job runs when generation is re-enabled (codex: delete only
117
116
  // enqueues; the pipeline itself is gated elsewhere).
118
- schedulePhase2 = () => { if (pluginOptions.generate_memories)
119
- trackBackgroundTask(triggerPhase2()); }) {
117
+ schedulePhase2 = () => {
118
+ if (pluginOptions.generate_memories)
119
+ trackBackgroundTask(triggerPhase2());
120
+ }) {
120
121
  const stores = store ? [store] : existingMemoryStores();
121
122
  let changed = false;
122
123
  for (const target of stores)
@@ -130,24 +131,17 @@ export default {
130
131
  // Added additively: V1 hosts keep calling server() exactly as before.
131
132
  setup: setupV2,
132
133
  async server(input, opts) {
133
- // A reload after dispose must be able to run the pipeline again.
134
- resetPluginLifecycle();
135
- setPluginInput(input);
136
- pluginClient = input.client;
137
- resetAgentHealth();
138
- mcpStatusInFlight = null;
139
- // Unconditional, like the caches above: a boot WITHOUT options must not
140
- // inherit the previous boot's warnings (opencode can host several
141
- // instances in one process — see the ARCHITECTURE known-gaps table).
142
- clearConfigWarnings();
143
- if (opts)
144
- applyPluginOptions(opts);
145
- else {
146
- const previousDb = dataRoot();
147
- resetPluginOptions();
148
- if (dataRoot() !== previousDb)
149
- closeDb();
134
+ if (draining)
135
+ await draining;
136
+ const config = reserveMemoryConfig(hostConfig, opts, input.directory);
137
+ if (!hostConfig) {
138
+ resetPluginLifecycle();
139
+ setPluginInput(input);
140
+ resetAgentHealth();
141
+ applyPluginOptions(opts ?? {});
142
+ hostConfig = config;
150
143
  }
144
+ hosts.push(input);
151
145
  // Finish bounded reseeding before hooks can see a surviving memory
152
146
  // sub-session after a plugin reload.
153
147
  await cleanupOldSubSessions();
@@ -161,7 +155,32 @@ export default {
161
155
  catch (err) {
162
156
  console.warn("[opencode-codex-memory] orphaned phase2 sweep failed:", err);
163
157
  }
164
- return buildHooks();
158
+ const hooks = buildHooks(input.client);
159
+ let released = false;
160
+ return {
161
+ ...hooks,
162
+ async dispose() {
163
+ if (released)
164
+ return;
165
+ released = true;
166
+ const idx = hosts.indexOf(input);
167
+ hosts.splice(idx, 1);
168
+ if (hosts.length) {
169
+ if (idx === 0) {
170
+ setPluginInput(hosts[0]);
171
+ }
172
+ return;
173
+ }
174
+ draining = hooks
175
+ .dispose()
176
+ .then(waitForBackgroundTasks)
177
+ .finally(() => {
178
+ hostConfig = undefined;
179
+ draining = undefined;
180
+ });
181
+ await draining;
182
+ },
183
+ };
165
184
  },
166
185
  };
167
186
  const KNOWN_OPTION_KEYS = new Set([
@@ -223,7 +242,13 @@ export function applyPluginOptions(opts, { modelFallback = false } = {}) {
223
242
  recordConfigWarning(`unknown/unsupported option '${key}' ignored`);
224
243
  }
225
244
  }
226
- for (const key of ["generate_memories", "use_memories", "dedicated_tools", "disable_on_external_context", "dual_write"]) {
245
+ for (const key of [
246
+ "generate_memories",
247
+ "use_memories",
248
+ "dedicated_tools",
249
+ "disable_on_external_context",
250
+ "dual_write",
251
+ ]) {
227
252
  if (!(key in raw))
228
253
  continue;
229
254
  if (typeof raw[key] === "boolean")
@@ -363,76 +388,6 @@ export function applyPluginOptions(opts, { modelFallback = false } = {}) {
363
388
  if (dataRoot() !== previousDb)
364
389
  closeDb();
365
390
  }
366
- /**
367
- * codex marks every MCP server as memory-polluting unconditionally
368
- * (codex-mcp server.rs pollutes_memory: true). opencode registers MCP tools
369
- * as "<server>_<tool>", so match tool names against the configured server
370
- * list. Query live status so runtime MCP changes cannot escape pollution
371
- * marking. Falls back to the web-tools-only check when status is unavailable.
372
- *
373
- * Concurrent tool calls coalesce on one in-flight status fetch. Deliberately
374
- * NOT cached with a TTL: a stale list would miss servers connected
375
- * mid-session and silently stop marking their calls as polluting, which is
376
- * the failure this classification exists to prevent. The accepted cost is one
377
- * status round trip per tool call — bounded to sessions that opt in with
378
- * disable_on_external_context (off by default), and paid only in
379
- * tool.execute.before.
380
- */
381
- async function mcpToolPrefixes() {
382
- if (!pluginClient)
383
- return null;
384
- if (!mcpStatusInFlight) {
385
- mcpStatusInFlight = (async () => {
386
- const controller = new AbortController();
387
- let timer;
388
- try {
389
- const res = await Promise.race([
390
- hostMcpStatus(pluginClient, controller.signal),
391
- new Promise((_, reject) => {
392
- timer = setTimeout(() => {
393
- controller.abort();
394
- reject(new Error(`mcp.status timed out after ${MCP_STATUS_TIMEOUT_MS}ms`));
395
- }, MCP_STATUS_TIMEOUT_MS);
396
- }),
397
- ]);
398
- if (!res || res.error)
399
- return null;
400
- const servers = res.data;
401
- if (!servers || typeof servers !== "object" || Array.isArray(servers))
402
- return null;
403
- const prefixes = [];
404
- for (const [server, status] of Object.entries(servers)) {
405
- if (!status || typeof status !== "object" || typeof status.status !== "string")
406
- continue;
407
- // Mirrors OpenCode's McpCatalog.sanitize when constructing tool names.
408
- prefixes.push(server.replace(/[^a-zA-Z0-9_-]/g, "_"));
409
- }
410
- return prefixes;
411
- }
412
- catch {
413
- // MCP status unavailable (older OpenCode); keep web-tools-only checks.
414
- return null;
415
- }
416
- finally {
417
- clearTimeout(timer);
418
- mcpStatusInFlight = null;
419
- }
420
- })();
421
- }
422
- return mcpStatusInFlight;
423
- }
424
- async function classifyExternalContextTool(toolName) {
425
- if (toolName === "websearch" || toolName === "webfetch")
426
- return true;
427
- const prefixes = await mcpToolPrefixes();
428
- if (prefixes === null)
429
- return null;
430
- for (const prefix of prefixes) {
431
- if (toolName.startsWith(`${prefix}_`))
432
- return true;
433
- }
434
- return false;
435
- }
436
391
  const TITLE_GENERATOR_MARKER = "You are a title generator. You output ONLY a thread title.";
437
392
  function isTitleGenerationPrompt(system) {
438
393
  return system.some((block) => block.includes(TITLE_GENERATOR_MARKER));
@@ -468,7 +423,8 @@ export function injectAgentDefinitions(config) {
468
423
  }
469
424
  recordAgentConfig(config, true, defs);
470
425
  }
471
- function buildHooks() {
426
+ function buildHooks(client) {
427
+ const classifyExternalContextTool = externalContextClassifier((signal) => hostMcpStatus(client, signal));
472
428
  const base = {
473
429
  async config(input) {
474
430
  try {
@@ -632,7 +588,8 @@ function buildHooks() {
632
588
  try {
633
589
  const ev = input.event;
634
590
  if (ev.type === "message.part.updated") {
635
- const part = ev.properties.part;
591
+ const part = ev.properties
592
+ .part;
636
593
  if (!part || part.type !== "text" || typeof part.text !== "string")
637
594
  return;
638
595
  if (part.sessionID && isMemorySubSession(part.sessionID))
package/dist/src/llm.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { PluginInput } from "@opencode-ai/plugin";
2
2
  import { type MemoryVersion } from "./options.js";
3
+ export declare const MAX_TRANSCRIPT_BYTES = 600000;
4
+ type Transcript = string | ((byteLimit: number) => string);
3
5
  export interface ExtractionResult {
4
6
  raw_memory: string;
5
7
  rollout_summary: string;
@@ -64,7 +66,7 @@ export interface ExtractOptions {
64
66
  * session.aborts the sub-session for host-side cleanup; extractor has no FS
65
67
  * write tools (D2) so a lingering server turn cannot dual-write the memory root.
66
68
  */
67
- export declare function extractViaSubagent(sessionId: string, transcript: string, opts?: ExtractOptions): Promise<ExtractionResult | null>;
69
+ export declare function extractViaSubagent(sessionId: string, transcript: Transcript, opts?: ExtractOptions): Promise<ExtractionResult | null>;
68
70
  /** `model`: "provider/model", or a comma-separated fallback chain tried in order. */
69
71
  export declare function consolidateViaSubagent(memoryRoot: string, diffFileName: string, model?: string, signal?: AbortSignal): Promise<void>;
70
72
  export declare function cleanupOldSubSessions(maxAgeMinutes?: number, timeoutMs?: number): Promise<void>;
@@ -83,3 +85,4 @@ export declare function validateExtraction(obj: Partial<ExtractionResult>, versi
83
85
  * is unavailable; the primary path reads AssistantMessage.structured directly.
84
86
  */
85
87
  export declare function parseExtraction(raw: string, version?: MemoryVersion): ExtractionResult | null;
88
+ export {};
package/dist/src/llm.js CHANGED
@@ -2,7 +2,8 @@ import fs from "fs";
2
2
  import path from "path";
3
3
  import { memoryRoot } from "./paths.js";
4
4
  import { hostListSessionsGlobal, hostProviderList, hostSessionCreate, hostSessionDeletionConfirmed, hostSessionPrompt, hostStructuredOutput, ignoreLateRejection, pluginHttpGet, withHostTimeout, } from "./host-client.js";
5
- import { catalogVariantKeys, nearestReasoningVariant } from "./reasoning-variant.js";
5
+ import { catalogModel, catalogVariantKeys, nearestReasoningVariant } from "./reasoning-variant.js";
6
+ import { truncateToBytes } from "./token.js";
6
7
  import { isPluginShuttingDown, pluginShutdownSignal } from "./lifecycle.js";
7
8
  import { modelList } from "./options.js";
8
9
  import { currentMemoryVersion } from "./memory-version.js";
@@ -10,6 +11,7 @@ import { SCAN_LIMIT, STAGE1_LEASE_SECONDS } from "./store.js";
10
11
  import { isProviderCapacityBlocked, isProviderCapacityError, noteProviderCapacityExhausted, ProviderCapacityError, providerCapacityMessage, } from "./ratelimit.js";
11
12
  import { recordDiagnostic } from "./diagnostics.js";
12
13
  const EXTRACTION_TIMEOUT_MS = (STAGE1_LEASE_SECONDS - 600) * 1000;
14
+ export const MAX_TRANSCRIPT_BYTES = 600_000;
13
15
  let inputRef = null;
14
16
  let inputGeneration = 0;
15
17
  let subSessionDirectoryOverride = null;
@@ -97,10 +99,14 @@ async function createSession(title) {
97
99
  body: {
98
100
  title,
99
101
  metadata: { [SUBSESSION_METADATA_KEY]: true },
100
- ...(title === "codex-memory-consolidate" ? { permission: [
101
- { permission: "external_directory", pattern: "*", action: "deny" },
102
- { permission: "external_directory", pattern: path.join(memoryRoot(), "*"), action: "allow" },
103
- ] } : {}),
102
+ ...(title === "codex-memory-consolidate"
103
+ ? {
104
+ permission: [
105
+ { permission: "external_directory", pattern: "*", action: "deny" },
106
+ { permission: "external_directory", pattern: path.join(memoryRoot(), "*"), action: "allow" },
107
+ ],
108
+ }
109
+ : {}),
104
110
  },
105
111
  signal: controller.signal,
106
112
  }), createTimeoutMs, "session.create", controller);
@@ -134,7 +140,7 @@ async function getConfigModels() {
134
140
  const request = (async () => {
135
141
  const controller = new AbortController();
136
142
  try {
137
- const res = await withHostTimeout(input.client.config.get({ signal: controller.signal }), configGetTimeoutMs, "config.get", controller);
143
+ const res = (await withHostTimeout(input.client.config.get({ signal: controller.signal }), configGetTimeoutMs, "config.get", controller));
138
144
  if (res.error || !res.data || generation !== inputGeneration)
139
145
  return {};
140
146
  const resolved = { model: res.data.model, smallModel: res.data.small_model };
@@ -361,7 +367,10 @@ function extractAssistantText(body) {
361
367
  if (typeof body.text === "string")
362
368
  return body.text;
363
369
  if (body.parts && Array.isArray(body.parts))
364
- return body.parts.map((p) => p?.text ?? "").filter(Boolean).join("\n");
370
+ return body.parts
371
+ .map((p) => p?.text ?? "")
372
+ .filter(Boolean)
373
+ .join("\n");
365
374
  if (body.messages && Array.isArray(body.messages)) {
366
375
  return body.messages
367
376
  .filter((m) => m?.info?.role === "assistant")
@@ -471,18 +480,32 @@ async function extractOnce(sessionId, transcript, cwd, configuredModel, timeoutM
471
480
  const subId = await createSession(`codex-memory-extract-${sessionId}`);
472
481
  try {
473
482
  const version = currentMemoryVersion();
474
- const prompt = buildExtractionInput(sessionId, cwd ?? "unknown", transcript, version);
475
483
  // extract_model chain entry > opencode small_model > session default.
476
484
  const model = await resolveExtractionModel(configuredModel);
485
+ const system = readTemplate(version === "v2" ? "stage_one_system_v2.md" : "stage_one_system.md");
486
+ const schema = version === "v2" ? EXTRACTION_SCHEMA_V2 : EXTRACTION_SCHEMA;
487
+ const ref = model && parseModelRef(model);
488
+ const limit = ref ? catalogModel(await getProviderCatalog(), ref.providerID, ref.modelID)?.limit : undefined;
489
+ const windows = [limit?.context, limit?.input].filter((n) => typeof n === "number" && Number.isSafeInteger(n) && n > 0);
490
+ // 70% of the effective input window (Codex), reserving template/schema
491
+ // bytes plus host framing. Token counts are estimates, not provider billing.
492
+ const overhead = Buffer.byteLength(system + buildExtractionInput(sessionId, cwd ?? "unknown", "", version) + JSON.stringify(schema)) + 1024;
493
+ const budget = windows.length
494
+ ? Math.min(MAX_TRANSCRIPT_BYTES, Math.floor(Math.min(...windows) * 0.7) * 4 - overhead)
495
+ : MAX_TRANSCRIPT_BYTES;
496
+ if (budget < 256)
497
+ throw new Error(`Model ${model} has insufficient input space for the extraction instructions`);
498
+ const content = typeof transcript === "string" ? truncateToBytes(transcript, budget) : transcript(budget);
499
+ const prompt = buildExtractionInput(sessionId, cwd ?? "unknown", content, version);
477
500
  const data = await runPrompt(subId, prompt, agent, {
478
501
  timeoutMs,
479
- system: readTemplate(version === "v2" ? "stage_one_system_v2.md" : "stage_one_system.md"),
502
+ system,
480
503
  model,
481
504
  signal,
482
505
  // opencode enforces json_schema output via a forced StructuredOutput tool
483
506
  // call (toolChoice: required) — which is why memorize-extract must allow
484
507
  // that one otherwise-denied tool.
485
- format: { type: "json_schema", schema: version === "v2" ? EXTRACTION_SCHEMA_V2 : EXTRACTION_SCHEMA },
508
+ format: { type: "json_schema", schema },
486
509
  // Codex extraction ReasoningEffort::Low. Host maps variant → reasoningEffort.
487
510
  // If the model has no `low`, pick the nearest listed effort (host-only).
488
511
  variant: await resolveReasoningVariant(EXTRACT_VARIANT, model),
@@ -599,7 +622,9 @@ export async function cleanupOldSubSessions(maxAgeMinutes = 90, timeoutMs = SUBS
599
622
  }
600
623
  if (list.length < pageLimit)
601
624
  return;
602
- const updates = list.map((s) => s.time?.updated).filter((updated) => typeof updated === "number" && Number.isFinite(updated) && updated >= 0);
625
+ const updates = list
626
+ .map((s) => s.time?.updated)
627
+ .filter((updated) => typeof updated === "number" && Number.isFinite(updated) && updated >= 0);
603
628
  if (updates.length === 0)
604
629
  return;
605
630
  // listGlobal uses `updated < cursor`. Add one millisecond so sessions
@@ -680,7 +705,7 @@ async function deleteSession(id, input = getPluginInput(), timeoutMs = SUBSESSIO
680
705
  // after shutdown succeeded. Hosts without session.get cannot confirm;
681
706
  // the successful delete is all the evidence there is.
682
707
  const canConfirm = typeof input.client.session?.get === "function";
683
- if (!canConfirm || await hostSessionDeletionConfirmed(input.client, id, SUBSESSION_CONFIRM_TIMEOUT_MS)) {
708
+ if (!canConfirm || (await hostSessionDeletionConfirmed(input.client, id, SUBSESSION_CONFIRM_TIMEOUT_MS))) {
684
709
  activeSubSessions.delete(id);
685
710
  }
686
711
  return true;
@@ -813,7 +838,10 @@ export function validateExtraction(obj, version = currentMemoryVersion()) {
813
838
  * is unavailable; the primary path reads AssistantMessage.structured directly.
814
839
  */
815
840
  export function parseExtraction(raw, version = currentMemoryVersion()) {
816
- const cleaned = raw.replace(/^```(?:json)?/gim, "").replace(/```$/gim, "").trim();
841
+ const cleaned = raw
842
+ .replace(/^```(?:json)?/gim, "")
843
+ .replace(/```$/gim, "")
844
+ .trim();
817
845
  const start = cleaned.indexOf("{");
818
846
  const end = cleaned.lastIndexOf("}");
819
847
  if (start === -1 || end === -1 || end <= start) {
@@ -1,5 +1,11 @@
1
1
  import type { CodexInteropOptions } from "./codex-interop.js";
2
2
  import type { ClaudeImportOptions } from "./claude-import.js";
3
+ type SharedConfig = {
4
+ home: string;
5
+ options: Record<string, unknown>;
6
+ };
7
+ /** Check the effective home before applying options or touching DB handles. */
8
+ export declare function reserveMemoryConfig(active: SharedConfig | undefined, raw: Record<string, unknown> | undefined, directory: string): SharedConfig;
3
9
  /**
4
10
  * Effective plugin options + configuration diagnostics, owned by a leaf
5
11
  * module so both the plugin entry (writes) and the control tools (read for
@@ -50,3 +56,4 @@ export declare function getConfigWarnings(): readonly string[];
50
56
  export declare function clearConfigWarnings(): void;
51
57
  /** Test seam: options/warnings are module state, tests need a clean slate. */
52
58
  export declare function resetConfigWarningsForTest(): void;
59
+ export {};
@@ -1,4 +1,17 @@
1
- import { setConfiguredHome } from "./paths.js";
1
+ import { resolveDataRoot, resolveHomePath, setConfiguredHome } from "./paths.js";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ /** Check the effective home before applying options or touching DB handles. */
4
+ export function reserveMemoryConfig(active, raw, directory) {
5
+ const { home, ...options } = raw ?? {};
6
+ const config = {
7
+ home: resolveDataRoot(typeof home === "string" ? (resolveHomePath(home) ?? undefined) : undefined),
8
+ options,
9
+ };
10
+ if (active && !isDeepStrictEqual(active, config)) {
11
+ throw new Error(`Conflicting memory configuration for ${directory}. Configure one memory home and options for all locations in this OpenCode process.`);
12
+ }
13
+ return active ?? config;
14
+ }
2
15
  const DEFAULT_PLUGIN_OPTIONS = {
3
16
  generate_memories: true,
4
17
  use_memories: true,
@@ -22,7 +35,12 @@ export const pluginOptions = {
22
35
  };
23
36
  /** Splits an extract_model / consolidation_model value into its fallback chain. */
24
37
  export function modelList(value) {
25
- return [...new Set((value ?? "").split(",").map((model) => model.trim()).filter(Boolean))];
38
+ return [
39
+ ...new Set((value ?? "")
40
+ .split(",")
41
+ .map((model) => model.trim())
42
+ .filter(Boolean)),
43
+ ];
26
44
  }
27
45
  export function resetPluginOptions() {
28
46
  delete pluginOptions.extract_model;
@@ -25,6 +25,7 @@ export type MemoryHomeSource = "test" | "option" | "env" | "default";
25
25
  export declare function resolveHomePath(raw: string): string | null;
26
26
  export declare function setConfiguredHome(home: string | undefined): void;
27
27
  export declare function dataRoot(): string;
28
+ export declare function resolveDataRoot(home: string | undefined): string;
28
29
  export declare function memoryHomeSource(): MemoryHomeSource;
29
30
  export declare function memoryRoot(version?: MemoryVersion): string;
30
31
  /** Jobs/outputs DB for the selected version. Session mode/pollution lives in sessionMetaDbPath. */
package/dist/src/paths.js CHANGED
@@ -51,11 +51,14 @@ export function setConfiguredHome(home) {
51
51
  configuredHome = home;
52
52
  }
53
53
  export function dataRoot() {
54
+ return resolveDataRoot(configuredHome);
55
+ }
56
+ export function resolveDataRoot(home) {
54
57
  const testRoot = process.env[TEST_ROOT_ENV];
55
58
  if (testRoot)
56
59
  return testRoot;
57
- if (configuredHome)
58
- return configuredHome;
60
+ if (home)
61
+ return home;
59
62
  const envHome = process.env[HOME_ENV];
60
63
  if (envHome) {
61
64
  const resolved = resolveHomePath(envHome);