opencode-codex-memory 0.10.0 → 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 +51 -17
- package/dist/src/db.d.ts +0 -2
- package/dist/src/db.js +0 -4
- package/dist/src/git-baseline.d.ts +10 -11
- package/dist/src/git-baseline.js +167 -97
- 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 +43 -15
- 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 +7 -6
- 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/v2/tools.js
CHANGED
|
@@ -14,7 +14,7 @@ import { memory_read, memory_search, memory_list, memory_add_note } from "../../
|
|
|
14
14
|
import { memory_inspect, memory_mode } from "../../tools/control.js";
|
|
15
15
|
import { pluginOptions } from "../options.js";
|
|
16
16
|
import { getV2DiscoveryStatus } from "./shim.js";
|
|
17
|
-
function adaptTool(name, v1) {
|
|
17
|
+
function adaptTool(name, v1, ask) {
|
|
18
18
|
return {
|
|
19
19
|
name,
|
|
20
20
|
description: v1.description,
|
|
@@ -27,11 +27,12 @@ function adaptTool(name, v1) {
|
|
|
27
27
|
agent: tctx.agent,
|
|
28
28
|
directory: "",
|
|
29
29
|
worktree: "",
|
|
30
|
-
abort: tctx.
|
|
30
|
+
abort: tctx.signal ?? tctx.abort ?? new AbortController().signal,
|
|
31
31
|
metadata: () => { },
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
32
|
+
ask: async (request) => {
|
|
33
|
+
if (ask)
|
|
34
|
+
return ask(tctx, request);
|
|
35
|
+
throw new Error("User approval is unavailable to plugin tools on this host. Use /memory-inspect → Controls instead.");
|
|
35
36
|
},
|
|
36
37
|
};
|
|
37
38
|
const res = await v1.execute(input, v1ctx);
|
|
@@ -71,10 +72,9 @@ const CONTROL_ONLY = new Set(["memory_inspect", "memory_mode"]);
|
|
|
71
72
|
/**
|
|
72
73
|
* Same gating as the V1 entry: the read/search/list/add-note tools require
|
|
73
74
|
* BOTH use_memories and dedicated_tools (codex MemoriesExtension); the
|
|
74
|
-
* control tools are always available.
|
|
75
|
-
* which V2 plugin tools cannot request: reset lives in the memory panel.
|
|
75
|
+
* control tools are always available. Destructive reset lives in the panel.
|
|
76
76
|
*/
|
|
77
|
-
export function buildV2Tools() {
|
|
77
|
+
export function buildV2Tools(ask) {
|
|
78
78
|
const full = pluginOptions.use_memories && pluginOptions.dedicated_tools;
|
|
79
|
-
return ALL_MEMORY_TOOLS.filter(([name]) => full || CONTROL_ONLY.has(name)).map(([name, v1]) => adaptTool(name, v1));
|
|
79
|
+
return ALL_MEMORY_TOOLS.filter(([name]) => full || CONTROL_ONLY.has(name)).map(([name, v1]) => adaptTool(name, v1, ask));
|
|
80
80
|
}
|
package/dist/src/v2/tui.js
CHANGED
|
@@ -124,7 +124,12 @@ var MemoryStatusRpc = {
|
|
|
124
124
|
required: ["key", "value"],
|
|
125
125
|
additionalProperties: false
|
|
126
126
|
},
|
|
127
|
-
output: {
|
|
127
|
+
output: {
|
|
128
|
+
type: "object",
|
|
129
|
+
properties: { ok: { type: "boolean" } },
|
|
130
|
+
required: ["ok"],
|
|
131
|
+
additionalProperties: false
|
|
132
|
+
}
|
|
128
133
|
},
|
|
129
134
|
setSessionMode: {
|
|
130
135
|
input: {
|
|
@@ -136,7 +141,12 @@ var MemoryStatusRpc = {
|
|
|
136
141
|
required: ["sessionID", "mode"],
|
|
137
142
|
additionalProperties: false
|
|
138
143
|
},
|
|
139
|
-
output: {
|
|
144
|
+
output: {
|
|
145
|
+
type: "object",
|
|
146
|
+
properties: { ok: { type: "boolean" } },
|
|
147
|
+
required: ["ok"],
|
|
148
|
+
additionalProperties: false
|
|
149
|
+
}
|
|
140
150
|
},
|
|
141
151
|
consolidateNow: {
|
|
142
152
|
input: { type: "object", properties: {}, additionalProperties: false },
|
|
@@ -1021,9 +1031,9 @@ function MemoryDialog(context, sessionID) {
|
|
|
1021
1031
|
_$insert(_el$19, () => tab() === "Controls" ? "select" : "scroll", null);
|
|
1022
1032
|
_$insert(_el$21, () => tab() === "Controls" ? "Enter/Space change" : "PgUp/PgDn page \xB7 Home/End ends");
|
|
1023
1033
|
_$effect((_p$) => {
|
|
1024
|
-
var _v$5 = Math.min(tab() === "Overview" ? 34 : sessionID ? 25 : 22, Math.max(8, dimensions().height - 2)), _v$6
|
|
1034
|
+
var _v$5 = Math.min(tab() === "Overview" ? 34 : sessionID ? 25 : 22, Math.max(8, dimensions().height - 2)), { text: _v$6, muted: _v$7 } = color, _v$8 = click(() => {
|
|
1025
1035
|
refresh();
|
|
1026
|
-
}), _v$9 = color.muted, _v$0 = click(() => context.ui.dialog.clear()), _v$1
|
|
1036
|
+
}), _v$9 = color.muted, _v$0 = click(() => context.ui.dialog.clear()), { muted: _v$1, muted: _v$10 } = color;
|
|
1027
1037
|
_v$5 !== _p$.e && (_p$.e = _$setProp(_el$9, "height", _v$5, _p$.e));
|
|
1028
1038
|
_v$6 !== _p$.t && (_p$.t = _$setProp(_el$1, "fg", _v$6, _p$.t));
|
|
1029
1039
|
_v$7 !== _p$.a && (_p$.a = _$setProp(_el$13, "fg", _v$7, _p$.a));
|
package/dist/src/workspace.js
CHANGED
|
@@ -75,7 +75,9 @@ export function ensureLayout() {
|
|
|
75
75
|
removeMemorySymlinks(root);
|
|
76
76
|
const v1 = currentMemoryVersion() === "v1";
|
|
77
77
|
// Codex V2 consolidates into memory_summary.md only; it has no skills/.
|
|
78
|
-
for (const dir of v1
|
|
78
|
+
for (const dir of v1
|
|
79
|
+
? [ROLLOUT_DIR, SKILLS_DIR, EXTENSIONS_DIR, ADHOC_NOTES_DIR]
|
|
80
|
+
: [ROLLOUT_DIR, EXTENSIONS_DIR, ADHOC_NOTES_DIR]) {
|
|
79
81
|
fs.mkdirSync(safeResolveMemoryPath(dir), { recursive: true });
|
|
80
82
|
}
|
|
81
83
|
if (!v1) {
|
|
@@ -103,7 +105,12 @@ export function ensureLayout() {
|
|
|
103
105
|
* a regular file and memory_summary.md must start with the exact line `v1`.
|
|
104
106
|
* Invalid artifacts force a consolidator re-run and block baseline reset.
|
|
105
107
|
*/
|
|
106
|
-
const V2_SUMMARY_HEADINGS = [
|
|
108
|
+
const V2_SUMMARY_HEADINGS = [
|
|
109
|
+
"## User Profile",
|
|
110
|
+
"## User preferences",
|
|
111
|
+
"## General Tips",
|
|
112
|
+
"## What's in Memory",
|
|
113
|
+
];
|
|
107
114
|
/** Codex format checks with content-free diagnostics; V2 size is bounded at injection. */
|
|
108
115
|
export function validateV2Summary(summary) {
|
|
109
116
|
const bytes = Buffer.byteLength(summary, "utf8");
|
|
@@ -312,8 +319,10 @@ export function writeWorkspaceDiff(diff) {
|
|
|
312
319
|
// multibyte content. Cut on the byte buffer and drop a split trailing char.
|
|
313
320
|
if (Buffer.byteLength(body, "utf8") > WORKSPACE_DIFF_MAX_BYTES) {
|
|
314
321
|
body =
|
|
315
|
-
Buffer.from(body, "utf8")
|
|
316
|
-
|
|
322
|
+
Buffer.from(body, "utf8")
|
|
323
|
+
.subarray(0, WORKSPACE_DIFF_MAX_BYTES)
|
|
324
|
+
.toString("utf8")
|
|
325
|
+
.replace(/\uFFFD+$/, "") + `\n[workspace diff truncated at ${WORKSPACE_DIFF_MAX_BYTES} bytes]\n`;
|
|
317
326
|
}
|
|
318
327
|
rendered += "\n## Diff\n\n```diff\n" + body + (body.endsWith("\n") ? "" : "\n") + "```\n";
|
|
319
328
|
}
|
package/dist/tools/control.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import fs from "fs";
|
|
2
2
|
import path from "path";
|
|
3
3
|
import { tool } from "@opencode-ai/plugin";
|
|
4
|
-
import { allMemoryRoots, memoryDbPath, memoryRoot, memorySummaryPath, sessionMetaDbPath, dataRoot, memoryHomeSource } from "../src/paths.js";
|
|
4
|
+
import { allMemoryRoots, memoryDbPath, memoryRoot, memorySummaryPath, sessionMetaDbPath, dataRoot, memoryHomeSource, } from "../src/paths.js";
|
|
5
5
|
import { clearAllVersionMemoryData, MemoryStore, PHASE2_COOLDOWN_MS } from "../src/store.js";
|
|
6
6
|
import { invalidateCache } from "../src/source.js";
|
|
7
7
|
import { estimateTokens } from "../src/token.js";
|
|
@@ -10,7 +10,7 @@ import { isPhase2InFlight } from "../src/phase2.js";
|
|
|
10
10
|
import { pluginOptions, getConfigWarnings } from "../src/options.js";
|
|
11
11
|
import { codexInteropBlockReason, codexInteropMtimes, resolveCodexInterop } from "../src/codex-interop.js";
|
|
12
12
|
import { claudeImportStatus, resolveClaudeHome } from "../src/claude-import.js";
|
|
13
|
-
import { formatDiagnosticLine, getDiscoveryStatus, getRecentDiagnostics
|
|
13
|
+
import { formatDiagnosticLine, getDiscoveryStatus, getRecentDiagnostics } from "../src/diagnostics.js";
|
|
14
14
|
import { isPluginShuttingDown } from "../src/lifecycle.js";
|
|
15
15
|
import { getAgentHealth } from "../src/agent-health.js";
|
|
16
16
|
import { activeProviderCapacityBackoffs } from "../src/ratelimit.js";
|
|
@@ -185,14 +185,7 @@ function renderAgentHealth() {
|
|
|
185
185
|
function resetBlockedReason() {
|
|
186
186
|
if (isSymlinkedRoot())
|
|
187
187
|
return "Reset refused: memory root is a symlink. Remove it manually to be safe.";
|
|
188
|
-
//
|
|
189
|
-
// after the wipe (the sub-agent edits live artifacts and resets the git
|
|
190
|
-
// baseline). Refuse instead of racing it. clearMemoryData also leaves a
|
|
191
|
-
// phase-2 cooldown marker so the next idle/chat hook cannot first-run-claim
|
|
192
|
-
// phase 2 and re-seed the root via ensureLayout. Cross-process consolidators
|
|
193
|
-
// already in flight remain ownership-guarded (their final mark becomes a
|
|
194
|
-
// no-op once the row is replaced) but may leave stray files — same window
|
|
195
|
-
// codex has between CLI clear and a running daemon.
|
|
188
|
+
// Cheap preflight. The DB barrier checks both writers again after approval.
|
|
196
189
|
if (isPhase2InFlight())
|
|
197
190
|
return "Reset refused: memory consolidation is currently running. Try again in a few minutes.";
|
|
198
191
|
return null;
|
|
@@ -206,12 +199,14 @@ export function performMemoryReset() {
|
|
|
206
199
|
if (blocked)
|
|
207
200
|
return { ok: false, message: blocked };
|
|
208
201
|
try {
|
|
209
|
-
clearAllVersionMemoryData();
|
|
210
|
-
wipeMemoriesDir();
|
|
202
|
+
clearAllVersionMemoryData(wipeMemoriesDir);
|
|
211
203
|
// codex keeps its state DB pool open across resets (clear_memory_roots_contents
|
|
212
204
|
// only wipes directories); closing here would strand cached handles elsewhere.
|
|
213
205
|
invalidateCache();
|
|
214
|
-
return {
|
|
206
|
+
return {
|
|
207
|
+
ok: true,
|
|
208
|
+
message: "Memory reset complete. Extracted memories and jobs cleared, memories directory (incl. git history) wiped, cache invalidated. Per-session memory modes were preserved.",
|
|
209
|
+
};
|
|
215
210
|
}
|
|
216
211
|
catch (err) {
|
|
217
212
|
return { ok: false, message: `memory_reset error: ${err.message}` };
|
|
@@ -278,7 +273,12 @@ export const memory_inspect = tool({
|
|
|
278
273
|
"effective plugin options, and any configuration warnings. Use it to verify " +
|
|
279
274
|
"configuration and debug why memory is not building. Read-only.",
|
|
280
275
|
args: {
|
|
281
|
-
min_consolidated_threads: tool.schema
|
|
276
|
+
min_consolidated_threads: tool.schema
|
|
277
|
+
.number()
|
|
278
|
+
.int()
|
|
279
|
+
.min(1)
|
|
280
|
+
.max(4096)
|
|
281
|
+
.optional()
|
|
282
282
|
.describe("V2 readiness threshold: distinct sessions in a successful consolidation (default 20)."),
|
|
283
283
|
},
|
|
284
284
|
async execute(args, ctx) {
|
|
@@ -342,9 +342,7 @@ function inspect(args, ctx) {
|
|
|
342
342
|
`stage1_jobs: ${stage1StatusParts.length > 0 ? stage1StatusParts.join(" ") : "none"}`,
|
|
343
343
|
`stage1_failures: ${failureParts.length > 0 ? failureParts.join(" ") : "none"}`,
|
|
344
344
|
...(stage1Jobs.stale_exhausted > 0
|
|
345
|
-
? [
|
|
346
|
-
`stage1_stale_exhausted: ${stage1Jobs.stale_exhausted} (older than max_rollout_age_days, will not retry)`,
|
|
347
|
-
]
|
|
345
|
+
? [`stage1_stale_exhausted: ${stage1Jobs.stale_exhausted} (older than max_rollout_age_days, will not retry)`]
|
|
348
346
|
: []),
|
|
349
347
|
...stage1Jobs.recent_errors.map((e) => {
|
|
350
348
|
const klass = e.failure_class ? `, ${e.failure_class}` : "";
|
|
@@ -360,10 +358,7 @@ function inspect(args, ctx) {
|
|
|
360
358
|
const eligibilityHint = `eligibility: sessions must be idle ≥ ${idleHours}h and younger than ${pluginOptions.max_rollout_age_days}d ` +
|
|
361
359
|
`(generate_memories=${pluginOptions.generate_memories}). ` +
|
|
362
360
|
`For faster local testing, set min_rollout_idle_hours to 1 (clamp floor).`;
|
|
363
|
-
const processLines = [
|
|
364
|
-
`phase2_in_flight: ${isPhase2InFlight()}`,
|
|
365
|
-
`plugin_shutting_down: ${isPluginShuttingDown()}`,
|
|
366
|
-
];
|
|
361
|
+
const processLines = [`phase2_in_flight: ${isPhase2InFlight()}`, `plugin_shutting_down: ${isPluginShuttingDown()}`];
|
|
367
362
|
const capacityBackoffs = activeProviderCapacityBackoffs();
|
|
368
363
|
const capacityLines = capacityBackoffs.length > 0
|
|
369
364
|
? capacityBackoffs.map((b) => `provider_capacity_backoff ${b.scope}: retry_at=${fmtUnixSec(b.retry_at)}`)
|
|
@@ -436,9 +431,7 @@ function inspect(args, ctx) {
|
|
|
436
431
|
codex_interop: { ...pluginOptions.codex_interop },
|
|
437
432
|
claude_import: {
|
|
438
433
|
...pluginOptions.claude_import,
|
|
439
|
-
...(pluginOptions.claude_import.projects
|
|
440
|
-
? { projects: [...pluginOptions.claude_import.projects] }
|
|
441
|
-
: {}),
|
|
434
|
+
...(pluginOptions.claude_import.projects ? { projects: [...pluginOptions.claude_import.projects] } : {}),
|
|
442
435
|
},
|
|
443
436
|
},
|
|
444
437
|
config_warnings: [...getConfigWarnings()],
|
|
@@ -465,7 +458,7 @@ export const memory_mode = tool({
|
|
|
465
458
|
let polluted;
|
|
466
459
|
try {
|
|
467
460
|
store = new MemoryStore();
|
|
468
|
-
polluted = store.
|
|
461
|
+
polluted = store.isPolluted(sid);
|
|
469
462
|
}
|
|
470
463
|
catch (err) {
|
|
471
464
|
return { output: `memory_mode error: ${err.message}` };
|
|
@@ -474,11 +467,19 @@ export const memory_mode = tool({
|
|
|
474
467
|
// that read that content must not lift it on its own. A rejection
|
|
475
468
|
// propagates to the host as usual.
|
|
476
469
|
if (args.mode === "enabled" && polluted) {
|
|
477
|
-
await ctx.ask({
|
|
470
|
+
await ctx.ask({
|
|
471
|
+
permission: "memory_mode",
|
|
472
|
+
patterns: [sid],
|
|
473
|
+
always: [],
|
|
474
|
+
metadata: { sessionId: sid, from: "polluted", to: "enabled" },
|
|
475
|
+
});
|
|
478
476
|
}
|
|
479
477
|
try {
|
|
480
|
-
store.setMemoryMode(sid, args.mode);
|
|
481
|
-
return {
|
|
478
|
+
store.setMemoryMode(sid, args.mode, args.mode === "enabled" && polluted);
|
|
479
|
+
return {
|
|
480
|
+
output: `Memory mode for session ${sid} set to '${args.mode}'.`,
|
|
481
|
+
metadata: { sessionId: sid, mode: args.mode },
|
|
482
|
+
};
|
|
482
483
|
}
|
|
483
484
|
catch (err) {
|
|
484
485
|
return { output: `memory_mode error: ${err.message}` };
|
package/dist/tools/memory.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import fs from "fs";
|
|
2
2
|
import path from "path";
|
|
3
|
-
import {
|
|
3
|
+
import { setImmediate as yieldToHost } from "node:timers/promises";
|
|
4
|
+
import { safeResolveMemoryPath, safeResolveUnderRoot, assertMemoryRootSafe, readRegularFileNoFollow, writeRegularFileNoFollow, } from "../src/path-guard.js";
|
|
4
5
|
import { tool as defineTool } from "@opencode-ai/plugin";
|
|
5
6
|
import { withSessionMemoryVersion } from "../src/session-version.js";
|
|
6
7
|
// Both host adapters call these definitions. Resolve once for the whole tool
|
|
@@ -18,7 +19,9 @@ export const memory_read = tool({
|
|
|
18
19
|
"Paths are relative to the memory root and cannot escape it. Supports line_offset/max_lines for " +
|
|
19
20
|
"reading a window of a large file; line_offset is 1-indexed and the starting line is reported.",
|
|
20
21
|
args: {
|
|
21
|
-
path: tool.schema
|
|
22
|
+
path: tool.schema
|
|
23
|
+
.string()
|
|
24
|
+
.describe("Relative path inside the memory workspace (e.g. MEMORY.md, rollout_summaries/session-xyz.md)."),
|
|
22
25
|
line_offset: tool.schema.number().int().min(1).optional().describe("1-indexed line to start reading from."),
|
|
23
26
|
max_lines: tool.schema.number().int().min(1).optional().describe("Maximum number of lines to return."),
|
|
24
27
|
},
|
|
@@ -34,7 +37,9 @@ export const memory_read = tool({
|
|
|
34
37
|
.sort((a, b) => comparePathNames(a.name, b.name))
|
|
35
38
|
.map((e) => e.name);
|
|
36
39
|
return {
|
|
37
|
-
output: `Directory ${args.path}/\n` +
|
|
40
|
+
output: `Directory ${args.path}/\n` +
|
|
41
|
+
entries.map((e) => `- ${e}`).join("\n") +
|
|
42
|
+
"\n(use memory_list for sorted, typed listings)",
|
|
38
43
|
metadata: { kind: "directory", entries },
|
|
39
44
|
};
|
|
40
45
|
}
|
|
@@ -61,7 +66,10 @@ export const memory_read = tool({
|
|
|
61
66
|
if (Buffer.byteLength(body, "utf8") > MAX_READ_BYTES) {
|
|
62
67
|
byteTruncated = true;
|
|
63
68
|
// Byte-accurate cut; drop a possibly split trailing multibyte char.
|
|
64
|
-
body = Buffer.from(body, "utf8")
|
|
69
|
+
body = Buffer.from(body, "utf8")
|
|
70
|
+
.subarray(0, MAX_READ_BYTES)
|
|
71
|
+
.toString("utf8")
|
|
72
|
+
.replace(/\uFFFD+$/, "");
|
|
65
73
|
}
|
|
66
74
|
const notes = [];
|
|
67
75
|
if (lineTruncated)
|
|
@@ -71,7 +79,12 @@ export const memory_read = tool({
|
|
|
71
79
|
const header = startLine > 1 ? `[starting at line ${startLine}]\n` : "";
|
|
72
80
|
return {
|
|
73
81
|
output: header + body + (notes.length ? "\n\n" + notes.join("\n") : ""),
|
|
74
|
-
metadata: {
|
|
82
|
+
metadata: {
|
|
83
|
+
path: args.path,
|
|
84
|
+
bytes: stat.size,
|
|
85
|
+
start_line_number: startLine,
|
|
86
|
+
truncated: byteTruncated || lineTruncated,
|
|
87
|
+
},
|
|
75
88
|
};
|
|
76
89
|
}
|
|
77
90
|
catch (err) {
|
|
@@ -114,9 +127,18 @@ export const memory_list = tool({
|
|
|
114
127
|
"with entry types. Hidden files and symlinks are skipped. Supports cursor pagination and listing " +
|
|
115
128
|
"a single file. Use path '' (empty) for the memory root.",
|
|
116
129
|
args: {
|
|
117
|
-
path: tool.schema
|
|
130
|
+
path: tool.schema
|
|
131
|
+
.string()
|
|
132
|
+
.default("")
|
|
133
|
+
.describe("Relative directory path inside the memory workspace ('' for the root)."),
|
|
118
134
|
cursor: tool.schema.string().optional().describe("Pagination cursor from a previous response's next_cursor."),
|
|
119
|
-
max_results: tool.schema
|
|
135
|
+
max_results: tool.schema
|
|
136
|
+
.number()
|
|
137
|
+
.int()
|
|
138
|
+
.min(1)
|
|
139
|
+
.max(LIST_MAX_RESULTS)
|
|
140
|
+
.default(LIST_MAX_RESULTS)
|
|
141
|
+
.describe("Maximum entries to return."),
|
|
120
142
|
},
|
|
121
143
|
async execute(args) {
|
|
122
144
|
try {
|
|
@@ -235,6 +257,8 @@ function firstContentLine(content) {
|
|
|
235
257
|
}
|
|
236
258
|
// --- search engine, ported from codex ext/memories/src/local/search.rs ---
|
|
237
259
|
const SEARCH_MAX_RESULTS = 200; // codex MAX_SEARCH_RESULTS (= default)
|
|
260
|
+
const SEARCH_PAGE_BYTES = 128 * 1024;
|
|
261
|
+
const SNIPPET_BYTES = 16 * 1024;
|
|
238
262
|
// codex SearchComparison::prepare: lowercase when case-insensitive; when
|
|
239
263
|
// normalized, keep ONLY alphanumeric characters (Unicode) so "blue-green",
|
|
240
264
|
// "blue green" and "bluegreen" compare equal.
|
|
@@ -244,61 +268,57 @@ function prepareComparable(value, caseSensitive, normalized) {
|
|
|
244
268
|
v = v.replace(/[^\p{L}\p{N}]/gu, "");
|
|
245
269
|
return v;
|
|
246
270
|
}
|
|
247
|
-
/**
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
const prepared = prepareComparable(line, caseSensitive, normalized);
|
|
256
|
-
return preparedQueries.map((q) => prepared.includes(q));
|
|
257
|
-
});
|
|
258
|
-
const matchedQueries = (flags) => queries.filter((_, i) => flags[i]);
|
|
259
|
-
const push = (start, end, flags) => {
|
|
260
|
-
const contentStart = Math.max(0, start - contextLines);
|
|
261
|
-
const contentEnd = Math.min(lines.length, end + contextLines + 1);
|
|
262
|
-
out.push({
|
|
263
|
-
path: file.rel,
|
|
264
|
-
match_line_number: start + 1,
|
|
265
|
-
content_start_line_number: contentStart + 1,
|
|
266
|
-
content: lines.slice(contentStart, contentEnd).join("\n"),
|
|
267
|
-
matched_queries: matchedQueries(flags),
|
|
268
|
-
});
|
|
269
|
-
};
|
|
270
|
-
if (mode === "any" || mode === "all_on_same_line") {
|
|
271
|
-
for (let i = 0; i < lines.length; i++) {
|
|
272
|
-
const flags = lineFlags[i];
|
|
273
|
-
const hit = mode === "any" ? flags.some(Boolean) : flags.every(Boolean);
|
|
274
|
-
if (hit)
|
|
275
|
-
push(i, i, flags);
|
|
271
|
+
/** A minimal covering window ends exactly when the oldest last-seen query moves forward. */
|
|
272
|
+
async function searchFileContent(lines, preparedQueries, mode, lineCount, caseSensitive, normalized, signal, hit) {
|
|
273
|
+
const last = preparedQueries.map(() => -1);
|
|
274
|
+
let previous = -1;
|
|
275
|
+
for (let i = 0; i < lines.length; i++) {
|
|
276
|
+
if (i && i % 2048 === 0) {
|
|
277
|
+
await yieldToHost();
|
|
278
|
+
signal?.throwIfAborted();
|
|
276
279
|
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
if (!lineFlags[start].some(Boolean))
|
|
280
|
+
const line = prepareComparable(lines[i], caseSensitive, normalized);
|
|
281
|
+
const flags = preparedQueries.map((q) => line.includes(q));
|
|
282
|
+
if (mode !== "all_within_lines") {
|
|
283
|
+
if (mode === "any" ? flags.some(Boolean) : flags.every(Boolean))
|
|
284
|
+
hit(i, i, flags);
|
|
283
285
|
continue;
|
|
284
|
-
const lastAllowed = Math.min(start + lineCount - 1, lines.length - 1);
|
|
285
|
-
const flags = new Array(preparedQueries.length).fill(false);
|
|
286
|
-
for (let end = start; end <= lastAllowed; end++) {
|
|
287
|
-
for (let q = 0; q < flags.length; q++)
|
|
288
|
-
flags[q] = flags[q] || lineFlags[end][q];
|
|
289
|
-
if (flags.every(Boolean)) {
|
|
290
|
-
windows.push({ start, end, flags });
|
|
291
|
-
break;
|
|
292
|
-
}
|
|
293
286
|
}
|
|
287
|
+
for (let q = 0; q < flags.length; q++)
|
|
288
|
+
if (flags[q])
|
|
289
|
+
last[q] = i;
|
|
290
|
+
const start = Math.min(...last);
|
|
291
|
+
if (start > previous && i - start < lineCount)
|
|
292
|
+
hit(start, i);
|
|
293
|
+
previous = start;
|
|
294
294
|
}
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
295
|
+
}
|
|
296
|
+
/** Materialize only returned matches. Keep the hit visible even with huge leading context. */
|
|
297
|
+
function searchSnippet(lines, start, end, context) {
|
|
298
|
+
let first = start;
|
|
299
|
+
let bytes = 0;
|
|
300
|
+
while (first > Math.max(0, start - context)) {
|
|
301
|
+
const extra = Buffer.byteLength(lines[first - 1]) + 1;
|
|
302
|
+
if (bytes + extra > SNIPPET_BYTES / 4)
|
|
303
|
+
break;
|
|
304
|
+
bytes += extra;
|
|
305
|
+
first--;
|
|
306
|
+
}
|
|
307
|
+
const chunks = lines.slice(first, start);
|
|
308
|
+
for (let i = start; i <= Math.min(end + context, lines.length - 1); i++) {
|
|
309
|
+
const line = lines[i];
|
|
310
|
+
const room = SNIPPET_BYTES - bytes - 32;
|
|
311
|
+
if (line.length > room || Buffer.byteLength(line) > room) {
|
|
312
|
+
chunks.push(Buffer.from(line.slice(0, Math.max(0, room)))
|
|
313
|
+
.subarray(0, Math.max(0, room))
|
|
314
|
+
.toString("utf8")
|
|
315
|
+
.replace(/\uFFFD$/, "") + " […truncated]");
|
|
316
|
+
break;
|
|
317
|
+
}
|
|
318
|
+
chunks.push(line);
|
|
319
|
+
bytes += Buffer.byteLength(line) + 1;
|
|
301
320
|
}
|
|
321
|
+
return { content_start_line_number: first + 1, content: chunks.join("\n") };
|
|
302
322
|
}
|
|
303
323
|
function renderMatch(m) {
|
|
304
324
|
const header = `${m.path}:${m.match_line_number}`;
|
|
@@ -316,17 +336,49 @@ export const memory_search = tool({
|
|
|
316
336
|
"notes) from that period — useful to recall what the user was working on around a given time. " +
|
|
317
337
|
"With since/until and no queries, returns a chronological listing of that period's sessions/notes.",
|
|
318
338
|
args: {
|
|
319
|
-
queries: tool.schema
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
339
|
+
queries: tool.schema
|
|
340
|
+
.array(tool.schema.string())
|
|
341
|
+
.optional()
|
|
342
|
+
.describe("Search substrings (at least one, non-empty after trim). Optional only when since/until is set."),
|
|
343
|
+
match_mode: tool.schema
|
|
344
|
+
.enum(["any", "all_on_same_line", "all_within_lines"])
|
|
345
|
+
.default("any")
|
|
346
|
+
.describe("How multiple queries combine (default any)."),
|
|
347
|
+
line_count: tool.schema
|
|
348
|
+
.number()
|
|
349
|
+
.int()
|
|
350
|
+
.min(1)
|
|
351
|
+
.optional()
|
|
352
|
+
.describe("Window size in lines for all_within_lines (required for that mode)."),
|
|
353
|
+
path: tool.schema
|
|
354
|
+
.string()
|
|
355
|
+
.optional()
|
|
356
|
+
.describe("Restrict the search to a file or directory relative to the memory root."),
|
|
323
357
|
cursor: tool.schema.string().optional().describe("Pagination cursor from a previous response's next_cursor."),
|
|
324
358
|
context_lines: tool.schema.number().int().min(0).default(0).describe("Extra lines of context around each match."),
|
|
325
|
-
case_sensitive: tool.schema
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
359
|
+
case_sensitive: tool.schema
|
|
360
|
+
.boolean()
|
|
361
|
+
.default(true)
|
|
362
|
+
.describe("Case-sensitive matching (default true, like codex memories/search)."),
|
|
363
|
+
normalized: tool.schema
|
|
364
|
+
.boolean()
|
|
365
|
+
.default(false)
|
|
366
|
+
.describe("Compare only alphanumeric characters, ignoring separators (blue-green == bluegreen); combine with case_sensitive=false to also ignore case."),
|
|
367
|
+
since: tool.schema
|
|
368
|
+
.string()
|
|
369
|
+
.optional()
|
|
370
|
+
.describe("Only time-anchored files at/after this time (YYYY-MM-DD or ISO datetime)."),
|
|
371
|
+
until: tool.schema
|
|
372
|
+
.string()
|
|
373
|
+
.optional()
|
|
374
|
+
.describe("Only time-anchored files at/before this time (YYYY-MM-DD or ISO datetime; whole day for date-only)."),
|
|
375
|
+
max_results: tool.schema
|
|
376
|
+
.number()
|
|
377
|
+
.int()
|
|
378
|
+
.min(1)
|
|
379
|
+
.max(SEARCH_MAX_RESULTS)
|
|
380
|
+
.default(SEARCH_MAX_RESULTS)
|
|
381
|
+
.describe("Max matches per page (default/max 200, like codex)."),
|
|
330
382
|
},
|
|
331
383
|
async execute(args, ctx) {
|
|
332
384
|
try {
|
|
@@ -336,6 +388,8 @@ export const memory_search = tool({
|
|
|
336
388
|
if (!fs.existsSync(root))
|
|
337
389
|
return { output: "Memory workspace is empty." };
|
|
338
390
|
const queries = (args.queries ?? []).map((q) => q.trim());
|
|
391
|
+
if (queries.length > 64 || queries.reduce((sum, q) => sum + Buffer.byteLength(q), 0) > 8192)
|
|
392
|
+
return { output: "memory_search error: at most 64 queries and 8192 query bytes are supported." };
|
|
339
393
|
if (args.queries && (queries.length === 0 || queries.some((q) => q.length === 0))) {
|
|
340
394
|
return { output: "memory_search error: queries must be non-empty strings." };
|
|
341
395
|
}
|
|
@@ -364,7 +418,9 @@ export const memory_search = tool({
|
|
|
364
418
|
return { output: `Not found: ${args.path}` };
|
|
365
419
|
}
|
|
366
420
|
const rel = args.path.replace(/\/+$/, "");
|
|
367
|
-
files = st.isFile()
|
|
421
|
+
files = st.isFile()
|
|
422
|
+
? [{ rel, abs: start, ts: fileTimestamp(path.basename(start)) }]
|
|
423
|
+
: collectSearchFiles(start, rel);
|
|
368
424
|
}
|
|
369
425
|
else {
|
|
370
426
|
files = collectSearchFiles(root, "");
|
|
@@ -397,8 +453,7 @@ export const memory_search = tool({
|
|
|
397
453
|
try {
|
|
398
454
|
content = readRegularFileNoFollow(f.abs).content.toString("utf8");
|
|
399
455
|
}
|
|
400
|
-
catch {
|
|
401
|
-
}
|
|
456
|
+
catch { }
|
|
402
457
|
return `${new Date(f.ts).toISOString()} ${f.rel} — ${firstContentLine(content)}`;
|
|
403
458
|
});
|
|
404
459
|
if (files.length === 0)
|
|
@@ -428,40 +483,59 @@ export const memory_search = tool({
|
|
|
428
483
|
if (preparedQueries.some((q) => q.length === 0)) {
|
|
429
484
|
return { output: "memory_search error: a query is empty after normalization." };
|
|
430
485
|
}
|
|
431
|
-
|
|
432
|
-
|
|
486
|
+
const startIndex = args.cursor === undefined ? 0 : Number(args.cursor);
|
|
487
|
+
if (!Number.isSafeInteger(startIndex) ||
|
|
488
|
+
startIndex < 0 ||
|
|
489
|
+
(args.cursor !== undefined && String(startIndex) !== args.cursor.trim()))
|
|
490
|
+
return { output: `memory_search error: invalid cursor "${args.cursor}" (must be a non-negative integer).` };
|
|
491
|
+
const pageMatches = [];
|
|
492
|
+
const pageSize = args.max_results ?? SEARCH_MAX_RESULTS;
|
|
493
|
+
let count = 0;
|
|
494
|
+
let pageBytes = 0;
|
|
495
|
+
let pageFull = false;
|
|
496
|
+
files.sort((a, b) => comparePathNames(a.rel, b.rel));
|
|
433
497
|
for (const f of files) {
|
|
498
|
+
await yieldToHost();
|
|
499
|
+
ctx.abort?.throwIfAborted();
|
|
434
500
|
let content;
|
|
435
501
|
try {
|
|
436
|
-
content = readRegularFileNoFollow(f.
|
|
502
|
+
content = readRegularFileNoFollow(safeResolveUnderRoot(root, f.rel)).content.toString("utf8");
|
|
437
503
|
}
|
|
438
504
|
catch {
|
|
439
505
|
continue;
|
|
440
506
|
}
|
|
441
507
|
if (content.includes("\u0000"))
|
|
442
508
|
continue; // binary, like codex's InvalidData skip
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
509
|
+
const lines = content.split(/\r?\n/);
|
|
510
|
+
await searchFileContent(lines, preparedQueries, mode, args.line_count ?? 1, caseSensitive, normalized, ctx.abort, (start, end, flags) => {
|
|
511
|
+
if (count++ < startIndex || pageFull || pageMatches.length >= pageSize)
|
|
512
|
+
return;
|
|
513
|
+
const match = {
|
|
514
|
+
path: f.rel,
|
|
515
|
+
match_line_number: start + 1,
|
|
516
|
+
...searchSnippet(lines, start, end, args.context_lines ?? 0),
|
|
517
|
+
matched_queries: flags ? queries.filter((_, i) => flags[i]) : queries,
|
|
518
|
+
};
|
|
519
|
+
// Account for both the display text and persisted match metadata.
|
|
520
|
+
const size = Buffer.byteLength(JSON.stringify(match)) + Buffer.byteLength(renderMatch(match)) + 1;
|
|
521
|
+
if (pageMatches.length && pageBytes + size > SEARCH_PAGE_BYTES) {
|
|
522
|
+
pageFull = true;
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
pageBytes += size;
|
|
526
|
+
pageMatches.push(match);
|
|
527
|
+
});
|
|
455
528
|
}
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
const
|
|
529
|
+
if (startIndex > count)
|
|
530
|
+
return { output: `memory_search error: cursor ${startIndex} exceeds result count ${count}.` };
|
|
531
|
+
const endIndex = startIndex + pageMatches.length;
|
|
532
|
+
const nextCursor = endIndex < count ? String(endIndex) : null;
|
|
459
533
|
const truncated = nextCursor !== null;
|
|
460
534
|
const label = queries.map((q) => `"${q}"`).join(", ");
|
|
461
|
-
if (
|
|
535
|
+
if (count === 0)
|
|
462
536
|
return { output: `No matches for ${label}${rangeLabel}.` };
|
|
463
537
|
return {
|
|
464
|
-
output: `${pageMatches.length} of ${
|
|
538
|
+
output: `${pageMatches.length} of ${count} match(es) for ${label}${rangeLabel}` +
|
|
465
539
|
`${truncated ? ` (more available; pass cursor=${nextCursor})` : ""}:\n` +
|
|
466
540
|
pageMatches.map(renderMatch).join("\n"),
|
|
467
541
|
metadata: {
|